示例#1
2
		public static void GetHistogramEXT(HistogramTargetEXT target, bool reset, PixelFormat format, PixelType type, IntPtr values)
		{
			Debug.Assert(Delegates.pglGetHistogramEXT != null, "pglGetHistogramEXT not implemented");
			Delegates.pglGetHistogramEXT((Int32)target, reset, (Int32)format, (Int32)type, values);
			CallLog("glGetHistogramEXT({0}, {1}, {2}, {3}, 0x{4})", target, reset, format, type, values.ToString("X8"));
			DebugCheckErrors();
		}
        /// <summary>The quantize.</summary>
        /// <param name="image">The image.</param>
        /// <param name="pixelFormat">The pixel format.</param>
        /// <param name="useDither">The use dither.</param>
        /// <returns>The quantized image with the recalculated color palette.</returns>
        public static Bitmap Quantize(Image image, PixelFormat pixelFormat, bool useDither)
        {
            Bitmap tryBitmap = image as Bitmap;

            if (tryBitmap != null && tryBitmap.PixelFormat == PixelFormat.Format32bppArgb)
            {
                // The image passed to us is ALREADY a bitmap in the right format. No need to create
                // a copy and work from there.
                return DoQuantize(tryBitmap, pixelFormat, useDither);
            }

            // We use these values a lot
            int width = image.Width;
            int height = image.Height;
            Rectangle sourceRect = Rectangle.FromLTRB(0, 0, width, height);

            // Create a 24-bit rgb version of the source image
            using (Bitmap bitmapSource = new Bitmap(width, height, PixelFormat.Format32bppArgb))
            {
                using (Graphics grfx = Graphics.FromImage(bitmapSource))
                {
                    grfx.DrawImage(image, sourceRect, 0, 0, width, height, GraphicsUnit.Pixel);
                }

                return DoQuantize(bitmapSource, pixelFormat, useDither);
            }
        }
示例#3
0
 public static void WriteImageToStream(Image source, Stream fs, PixelFormat pixelFormat)
 {
     var bmp = new Bitmap(source);
     for (var y = 0; y < bmp.Height; y += 8)
         for (var x = 0; x < bmp.Width; x += 8)
             EncodeTile(8, 8, 0, 0, bmp, fs, pixelFormat);
 }
 //internal FeaturesPerFormat(PixelFormat format, MSAALevel maximumMSAALevel, ComputeShaderFormatSupport computeShaderFormatSupport, FormatSupport formatSupport)
 internal FeaturesPerFormat(PixelFormat format, MSAALevel maximumMSAALevel, FormatSupport formatSupport)
 {
     Format = format;
     this.MSAALevelMax = maximumMSAALevel;
     //ComputeShaderFormatSupport = computeShaderFormatSupport;
     FormatSupport = formatSupport;
 }
示例#5
0
        /// <summary>
        /// Converts a depth frame to the corresponding System.Drawing.Bitmap.
        /// </summary>
        /// <param name="frame">The specified depth frame.</param>
        /// <param name="format">Pixel format of the depth frame.</param>
        /// <param name="mode">Depth frame mode.</param>
        /// <returns>The corresponding System.Drawing.Bitmap representation of the depth frame.</returns>
        public static Bitmap ToBitmap(this DepthImageFrame frame, PixelFormat format, DepthImageMode mode)
        {
            short[] pixelData = new short[frame.PixelDataLength];
            frame.CopyPixelDataTo(pixelData);

            byte[] pixels;

            switch (mode)
            {
                case DepthImageMode.Raw:
                    pixels = GenerateRawFrame(frame, pixelData);
                    break;
                case DepthImageMode.Dark:
                    pixels = GenerateDarkFrame(frame, pixelData);
                    break;
                case DepthImageMode.Colors:
                    pixels = GenerateColoredFrame(frame, pixelData);
                    break;
                default:
                    pixels = GenerateRawFrame(frame, pixelData);
                    break;
            }

            return pixels.ToBitmap(frame.Width, frame.Height, format);
        }
示例#6
0
 /// <summary>
 /// Initializes a new instance of the <see cref="DecompressingRequest" /> class.
 /// </summary>
 /// <param name="isSRgb">Indicate if the input image is an sRGB image</param>
 /// <param name="pixelFormat">Input pixel format.</param>
 public DecompressingRequest(bool isSRgb, PixelFormat pixelFormat = PixelFormat.None)
 {
     if (pixelFormat.IsHDR())
         DecompressedFormat = PixelFormat.R16G16B16A16_Float;
     else
         DecompressedFormat = isSRgb ? PixelFormat.R8G8B8A8_UNorm_SRgb : PixelFormat.R8G8B8A8_UNorm;
 }
示例#7
0
文件: Tools.cs 项目: Jamedjo/IconLib
 public static int BitsFromPixelFormat(PixelFormat pixelFormat)
 {
     switch (pixelFormat)
     {
         case PixelFormat.Format1bppIndexed:
             return 1;
         case PixelFormat.Format4bppIndexed:
             return 4;
         case PixelFormat.Format8bppIndexed:
             return 8;
         case PixelFormat.Format16bppArgb1555:
         case PixelFormat.Format16bppGrayScale:
         case PixelFormat.Format16bppRgb555:
         case PixelFormat.Format16bppRgb565:
             return 16;
         case PixelFormat.Format24bppRgb:
             return 24;
         case PixelFormat.Format32bppArgb:
         case PixelFormat.Format32bppPArgb:
         case PixelFormat.Format32bppRgb:
             return 32;
         case PixelFormat.Format64bppArgb:
         case PixelFormat.Format64bppPArgb:
             return 64;
         default:
             return 0;
     }
 }
示例#8
0
 public static Bitmap ConvertToFormat(System.Drawing.Image image, PixelFormat format)
 {
     Bitmap bitmap = new Bitmap(image.Width, image.Height, format);
     using (Graphics graphics = Graphics.FromImage(bitmap))
         graphics.DrawImage(image, new Rectangle(0, 0, bitmap.Width, bitmap.Height));
     return bitmap;
 }
示例#9
0
 public Image(int width, int height, PixelFormat pixelFormat, byte[] pixels)
 {
     this.Width = width;
     this.Height = height;
     this.Format = pixelFormat;
     this.pixels = pixels;
 }
示例#10
0
        public Texture2D( TextureNativeSectionData tex )
            : base(TextureTarget.Texture2D)
        {
            Width = tex.Width;
            Height = tex.Height;

            WrapModeU = FindWrapMode( tex.WrapU );
            WrapModeV = FindWrapMode( tex.WrapV );

            InternalFormat = FindInternalFormat( tex.Compression, tex.Format );
            ExternalFormat = FindExternalFormat( tex.Compression, tex.Format );

            Compressed = tex.Compression != TextureNativeSectionData.CompressionMode.None;
            Alpha = tex.Alpha;

            MinFilter = FindMinFilter( tex.FilterFlags );

            MipMapCount = 1; // tex.MipMapCount;
            ContainsMipMaps = ( tex.Format & TextureNativeSectionData.RasterFormat.ExtMipMap ) != 0;
            GenerateMipMaps = true; // ( tex.Format & TextureNativeSectionData.RasterFormat.ExtAutoMipMap ) != 0;

            ImageLevelSizes = new int[ MipMapCount ];
            for ( int i = 0; i < MipMapCount; ++i )
                ImageLevelSizes[ i ] = FindImageDataSize( Width >> i, Height >> i, tex.Compression, tex.Format );

            ImageLevelData = new byte[ MipMapCount ][];
            for ( int i = 0; i < MipMapCount; ++i )
                ImageLevelData[ i ] = tex.ImageLevelData[ i ];
        }
示例#11
0
        public static FastDirectImage Create(int width, int height, PixelFormat pixelFormat)
        {
            var newImg = new FastDirectImage();
            newImg.PixelFormat = pixelFormat;
            newImg.BitPerPixel = Image.GetPixelFormatSize(pixelFormat);
            newImg.PixelFormatSize = newImg.BitPerPixel / 8;

            // Gör inte såhär för att räkna ut Stride: newImg.Stride = width * newImg.PixelFormatSize;
            // Detta då stride för bitmappar måste alignbara med 32 bitar (4 byte). (Antagligen för att förenkla kopiering av rader)
            // http://www.tech-archive.net/Archive/DotNet/microsoft.public.dotnet.framework.drawing/2006-09/msg00057.html

            //In your loop, you copy the pixels one scanline at a time and take into
            //consideration the amount of padding that occurs due to memory alignment.
            newImg.Stride = ((width * newImg.BitPerPixel + 31) & ~31) >> 3;
            newImg.Padding = newImg.Stride - (((width * newImg.BitPerPixel) + 7) / 8);

            newImg.bits = new byte[newImg.Stride * height];
            newImg.handle = GCHandle.Alloc(newImg.bits, GCHandleType.Pinned);
            IntPtr pointer = Marshal.UnsafeAddrOfPinnedArrayElement(newImg.bits, 0);
            newImg.NativeBitmap = new Bitmap(width, height, newImg.Stride, pixelFormat, pointer);

            // Kan kanske vara något för
            //var b = newImg.NativeBitmap.LockBits(new Rectangle(0, 0, newImg.NativeBitmap.Width, newImg.NativeBitmap.Height), ImageLockMode.ReadWrite, pixelFormat);

            return newImg;
        }
 public InvalidPixelFormatException(PixelFormat invalid, PixelFormat expected) : base (invalid != PixelFormat.Undefined ?
                                                                                     "PixelFormat " + invalid.ToString() + " is invalid" :
                                                                                     expected != PixelFormat.Undefined ?
                                                                                     "PixelFormat " + expected.ToString() + " expected" :
                                                                                     "Invalid PixelFormat")
 {
 }
示例#13
0
 static PixelFormats()
 {
     Bgr101010 = new PixelFormat("Bgr101010", 32);
     Bgr24 = new PixelFormat("Bgr24", 24);
     Bgr32 = new PixelFormat("Bgr32", 32);
     Bgr555 = new PixelFormat("Bgr555", 16);
     Bgr565 = new PixelFormat("Bgr565", 16);
     Bgra32 = new PixelFormat("Bgra32", 32);
     BlackWhite = new PixelFormat("BlackWhite", 1);
     Cmyk32 = new PixelFormat("Cmyk32", 32);
     Default = new PixelFormat("Default", 0);
     Gray16 = new PixelFormat("Gray16", 16);
     Gray2 = new PixelFormat("Gray2", 2);
     Gray32Float = new PixelFormat("Gray32Float", 32);
     Gray4 = new PixelFormat("Gray4", 4);
     Gray8 = new PixelFormat("Gray8", 8);
     Indexed1 = new PixelFormat("Indexed1", 1);
     Indexed2 = new PixelFormat("Indexed2", 2);
     Indexed4 = new PixelFormat("Indexed4", 4);
     Indexed8 = new PixelFormat("Indexed8", 8);
     Pbgra32 = new PixelFormat("Pbgra32", 32);
     Prgba128Float = new PixelFormat("Prgba128Float", 128);
     Prgba64 = new PixelFormat("Prgba64", 64);
     Rgb128Float = new PixelFormat("Rgb128Float", 128);
     Rgb24 = new PixelFormat("Rgb24", 24);
     Rgb48 = new PixelFormat("Rgb48", 48);
     Rgba128Float = new PixelFormat("Rgba128Float", 128);
     Rgba64 = new PixelFormat("Rgba64", 64);
 }
示例#14
0
        private static byte[] ConvertFrom24BppTo32Bpp(byte[] sourcePixels, PixelFormat destinationPixelFormat, PixelFormat sourcePixelFormat)
        {
            var newLength = (sourcePixels.Length / 3) << 2;
            var destinationPixels = new byte[newLength];
            var destinationPixelIndex = 0;

            var sourceColorSpace = ColorSpaces.RGB24BPP;
            var destinationColorSpace = ColorSpaces.RGBAlpha32BPP;

            for (var pixelIndex = 0; pixelIndex < sourcePixels.Length; pixelIndex += 3)
            {
                destinationPixels[destinationPixelIndex + destinationColorSpace.RedPosition] =
                    sourcePixels[pixelIndex + sourceColorSpace.RedPosition];

                destinationPixels[destinationPixelIndex + destinationColorSpace.GreenPosition] =
                    sourcePixels[pixelIndex + sourceColorSpace.GreenPosition];

                destinationPixels[destinationPixelIndex + destinationColorSpace.BluePosition] =
                    sourcePixels[pixelIndex + sourceColorSpace.BluePosition];

                destinationPixels[destinationPixelIndex + destinationColorSpace.AlphaPosition] = 0xff;

                destinationPixelIndex += 4;
            }

            return destinationPixels;
        }
 public VideoPacketDecoderWorker(PixelFormat pixelFormat, bool skipFrames, Action<VideoFrame> onFrameDecoded)
 {
   _pixelFormat = pixelFormat;
   _skipFrames = skipFrames;
   _onFrameDecoded = onFrameDecoded;
   _packetQueue = new ConcurrentQueue<VideoPacket>();
 }
示例#16
0
文件: Tools.cs 项目: tdhieu/iSpy
        public static int BytesPerPixel(PixelFormat pixelFormat)
        {
            int bytesPerPixel;

            // calculate bytes per pixel
            switch ( pixelFormat )
            {
                case PixelFormat.Format8bppIndexed:
                    bytesPerPixel = 1;
                    break;
                case PixelFormat.Format16bppGrayScale:
                    bytesPerPixel = 2;
                    break;
                case PixelFormat.Format24bppRgb:
                    bytesPerPixel = 3;
                    break;
                case PixelFormat.Format32bppRgb:
                case PixelFormat.Format32bppArgb:
                case PixelFormat.Format32bppPArgb:
                    bytesPerPixel = 4;
                    break;
                case PixelFormat.Format48bppRgb:
                    bytesPerPixel = 6;
                    break;
                case PixelFormat.Format64bppArgb:
                case PixelFormat.Format64bppPArgb:
                    bytesPerPixel = 8;
                    break;
                default:
                    throw new UnsupportedImageFormatException( "Can not create image with specified pixel format." );
            }
            return bytesPerPixel;
        }
示例#17
0
文件: SnippingTool.cs 项目: Nucs/nlib
 /// <summary>
 /// Takes screenshot of the window (supports multiple monitors) and then lets user to select the wanted area and returns that area.
 /// Also returns the rectangle of the selected part inside of the window.
 /// </summary>
 public static Image Snip(IntPtr hWnd, out Rectangle rect, PixelFormat format = PixelFormat.Format24bppRgb) {
     NativeWin32.SetForegroundWindow(hWnd);
     
     Rect r;
     if (!NativeWin32.GetWindowRect(hWnd, out r)) {
         rect = Rectangle.Empty;
         return null;
     } 
     rect = new Rectangle(Convert.ToInt32(r.X), Convert.ToInt32(r.Y), Convert.ToInt32(r.Width), Convert.ToInt32(r.Height));
     
     var bmp = ScreenShot.Create(hWnd);
     Graph = Graphics.FromImage(bmp);
     Graph.SmoothingMode = SmoothingMode.None;
     
     using (var snipper = new SnippingTool(bmp) {SpecificWindowMode = true}) {
         snipper.Location = new Point(rect.Left, rect.Top);
         NativeWin32.SetForegroundWindow(snipper.Handle);
          
         if (snipper.ShowDialog() == DialogResult.OK) {
             rect = snipper.rcSelect;
             return snipper.Image;
         }
     }
     rect = Rectangle.Empty;
     return null;
 }
示例#18
0
        //
        protected override void OnCreateTexture( string definitionName, ref Vec2I size, ref PixelFormat format )
        {
            base.OnCreateTexture( definitionName, ref size, ref format );

            if( definitionName == "scene" || definitionName == "temp" )
                size = Owner.DimensionsInPixels.Size / 2;
        }
示例#19
0
文件: Glu.cs 项目: dakahler/alloclave
 Int32 Build1DMipmapLevel(TextureTarget target, Int32 internalFormat, Int32 width, PixelFormat format, PixelType type, Int32 level, Int32 @base, Int32 max, IntPtr data)
 {
     unsafe
     {
         return Delegates.gluBuild1DMipmapLevels((TextureTarget)target, (Int32)internalFormat, (Int32)width, (PixelFormat)format, (PixelType)type, (Int32)level, (Int32)@base, (Int32)max, (IntPtr)data);
     }
 }
示例#20
0
文件: Glu.cs 项目: dakahler/alloclave
 Int32 Build1DMipmap(TextureTarget target, Int32 internalFormat, Int32 width, PixelFormat format, PixelType type, IntPtr data)
 {
     unsafe
     {
         return Delegates.gluBuild1DMipmaps((TextureTarget)target, (Int32)internalFormat, (Int32)width, (PixelFormat)format, (PixelType)type, (IntPtr)data);
     }
 }
示例#21
0
		public static void GetConvolutionFilterEXT(ConvolutionTargetEXT target, PixelFormat format, PixelType type, IntPtr image)
		{
			Debug.Assert(Delegates.pglGetConvolutionFilterEXT != null, "pglGetConvolutionFilterEXT not implemented");
			Delegates.pglGetConvolutionFilterEXT((Int32)target, (Int32)format, (Int32)type, image);
			CallLog("glGetConvolutionFilterEXT({0}, {1}, {2}, 0x{3})", target, format, type, image.ToString("X8"));
			DebugCheckErrors();
		}
示例#22
0
        /// <summary>
        /// Determines whether [is pixel format supported by graphics object] [the specified format].
        /// </summary>
        /// <param name="format">The format.</param>
        /// <returns><c>true</c> if [is pixel format supported by graphics object] [the specified format]; otherwise, <c>false</c>.</returns>
        public static bool IsPixelFormatSupportedByGraphicsObject(PixelFormat format)
        {
            // http://msdn.microsoft.com/en-us/library/system.drawing.graphics.fromimage.aspx

            if ((format & PixelFormat.Indexed) == PixelFormat.Indexed)
            {
                return false;
            }
            if ((format & PixelFormat.Undefined) == PixelFormat.Undefined)
            {
                return false;
            }
            if ((format & PixelFormat.DontCare) == PixelFormat.DontCare)
            {
                return false;
            }
            if ((format & PixelFormat.Format16bppArgb1555) == PixelFormat.Format16bppArgb1555)
            {
                return false;
            }
            if ((format & PixelFormat.Format16bppGrayScale) == PixelFormat.Format16bppGrayScale)
            {
                return false;
            }

            return true;
        }
示例#23
0
		public static Bitmap region(Rectangle area, bool cursor = true, PixelFormat pixel_format = PixelFormat.Format32bppRgb) {
			var bmp = new Bitmap(area.Width - 2, area.Height - 2, pixel_format);
			Graphics g = Graphics.FromImage(bmp);
			g.CopyFromScreen(area.X, area.Y, 0, 0, bmp.Size, CopyPixelOperation.SourceCopy);
			
			if (cursor)
			{
				CURSORINFO cursor_info;
				cursor_info.cbSize = Marshal.SizeOf(typeof (CURSORINFO));

				if (GetCursorInfo(out cursor_info))
					if (cursor_info.flags == (int)0x0001)
					{
						var hdc = g.GetHdc();
						DrawIconEx(
                            hdc, cursor_info.ptScreenPos.x - area.X, cursor_info.ptScreenPos.y - area.Y, cursor_info.hCursor,
                            0, 0, 0, IntPtr.Zero, (int)0x0003
                        );
						g.ReleaseHdc();
					}
			}
			
			g.Dispose();
			return bmp;
		}
示例#24
0
 /// <summary>
 /// Initializes a new instance of the <see cref="DisplayMode"/> class.
 /// </summary>
 /// <param name="format">The format.</param>
 /// <param name="width">The width.</param>
 /// <param name="height">The height.</param>
 /// <param name="refreshRate">The refresh rate.</param>
 public DisplayMode(PixelFormat format, int width, int height, Rational refreshRate)
 {
     Format = format;
     Width = width;
     Height = height;
     RefreshRate = refreshRate;
 }
示例#25
0
 public EmptyTexture2D( int width, int height, int channels, PixelFormat format )
 {
     this.Width = width;
     this.Height = height;
     this.Channels = channels;
     this.Format = format;
 }
示例#26
0
        internal ComBitmap(IntPtr bitmapData, int width, int height, int stride, PixelFormat format)
        {
            _bitmapData = bitmapData;

            _myBitmap = new Bitmap(width, height, stride, format, bitmapData);
            _myBitmap.RotateFlip(RotateFlipType.RotateNoneFlipY);
        }
示例#27
0
        /// <summary>
        /// Converts a color frame to a System.Drawing.Bitmap.
        /// </summary>
        /// <param name="frame">A ColorImageFrame generated from a Kinect sensor.</param>
        /// <param name="format">Image format.</param>
        /// <returns>The specified frame in a System.Drawing.Bitmap format.</returns>
        public static Bitmap ToBitmap(this ColorImageFrame frame, PixelFormat format)
        {
            byte[] pixels = new byte[frame.PixelDataLength];
            frame.CopyPixelDataTo(pixels);

            return pixels.ToBitmap(frame.Width, frame.Height, format);
        }
示例#28
0
文件: BlpLib.cs 项目: sonygod/dotahit
        public static Bitmap BlpToBitmap(MemoryStream ms, PixelFormat pf)
        {
            if (ms.Length == 0) return null;

            int width, height;
            uint type, subtype;

            byte[] srcBlp = ms.GetBuffer();

            //////////////////////////////
            // get required texture size
            //////////////////////////////

            uint textureSize = LoadBLP(IntPtr.Zero, srcBlp, out width, out height, out type, out subtype, false);

            IntPtr scan0 = Marshal.AllocHGlobal((int)textureSize);

            LoadBLP(scan0, srcBlp, out width, out height, out type, out subtype, false);

            Bitmap bmp = new Bitmap(width, height,
                (int)(textureSize / height),
                pf == PixelFormat.DontCare ? PixelFormat.Format32bppRgb : pf,
                scan0);

            return bmp;
        }
 public IPixelFormat CreatePixelFormat(PixelFormat format, uint pixelWidth, uint pixelHeight, out byte[] buffer)
 {
     switch (format)
     {
         case PixelFormat.Gray:
             {
                 return new FormatGray(
                     RasterBufferFactory.CreateBuffer(pixelWidth, pixelHeight, 3, 3, out buffer),
                     IoC.Instance.Resolve<IBlenderGray>(), 3, 2);
             }
         case PixelFormat.RGB:
             {
                 return new FormatRGB(
                    RasterBufferFactory.CreateBuffer(pixelWidth, pixelHeight, 3, 3, out buffer),
                     IoC.Instance.Resolve<IBlender>("rgb"));
             }
         case PixelFormat.RGBA:
             {
                 return new FormatRGBA(
                     RasterBufferFactory.CreateBuffer(pixelWidth, pixelHeight, 4, 4, out buffer),
                     IoC.Instance.Resolve<IBlender>("bgra"));
             }
         default:
             throw new InvalidOperationException();
     }
 }
示例#30
0
 /// <summary>
 /// Converts a shared image to a different pixel format using the specified transformer.
 /// </summary>
 /// <param name="source">Source image to compress.</param>
 /// <param name="transformer">Method for converting an image sample.</param>
 /// <param name="pixelFormat">Pixel format to use for converted image.</param>
 /// <param name="deliveryPolicy">An optional delivery policy.</param>
 /// <param name="sharedImageAllocator">Optional image allocator for creating new shared image.</param>
 /// <returns>Returns a producer that generates the transformed images.</returns>
 public static IProducer <Shared <Image> > Transform(this IProducer <Shared <Image> > source, TransformDelegate transformer, PixelFormat pixelFormat, DeliveryPolicy <Shared <Image> > deliveryPolicy = null, Func <int, int, PixelFormat, Shared <Image> > sharedImageAllocator = null)
 {
     return(source.PipeTo(new ImageTransformer(source.Out.Pipeline, transformer, pixelFormat, sharedImageAllocator), deliveryPolicy));
 }
示例#31
0
        public void ResolveMultisample(RenderTarget sourceMultisampleTexture, RenderTarget destTexture, int sourceSubResource = 0, int destSubResource = 0, PixelFormat format = PixelFormat.Unknown)
        {
#if UNIT_TEST_COMPILANT
            throw new NotImplementedException("Unit tests, don't support methods calls. Only properties can be get or set.");
#else
            Internal_ResolveMultisample(unmanagedPtr, Object.GetUnmanagedPtr(sourceMultisampleTexture), Object.GetUnmanagedPtr(destTexture), sourceSubResource, destSubResource, format);
#endif
        }
示例#32
0
 private static extern void Internal_create(Texture managedInstance, PixelFormat format, uint width, uint height, uint depth, TextureType texType, TextureUsage usage, uint numSamples, bool hasMipmaps, bool gammaCorrection);
示例#33
0
 /// <summary>
 /// Creates a new 3D <see cref="Texture"/> with a single mipmap.
 /// </summary>
 /// <param name="device">The <see cref="GraphicsDevice"/>.</param>
 /// <param name="width">The width.</param>
 /// <param name="height">The height.</param>
 /// <param name="depth">The depth.</param>
 /// <param name="format">Describes the format to use.</param>
 /// <param name="usage">The usage.</param>
 /// <param name="textureFlags">true if the texture needs to support unordered read write.</param>
 /// <returns>
 /// A new instance of 3D <see cref="Texture"/> class.
 /// </returns>
 public static Texture New3D(GraphicsDevice device, int width, int height, int depth, PixelFormat format, TextureFlags textureFlags = TextureFlags.ShaderResource, GraphicsResourceUsage usage = GraphicsResourceUsage.Default)
 {
     return New3D(device, width, height, depth, false, format, textureFlags, usage);
 }
示例#34
0
 /// <summary>
 /// Creates a new 3D <see cref="Texture"/>.
 /// </summary>
 /// <param name="device">The <see cref="GraphicsDevice"/>.</param>
 /// <param name="width">The width.</param>
 /// <param name="height">The height.</param>
 /// <param name="depth">The depth.</param>
 /// <param name="mipCount">Number of mipmaps, set to true to have all mipmaps, set to an int >=1 for a particular mipmap count.</param>
 /// <param name="format">Describes the format to use.</param>
 /// <param name="usage">The usage.</param>
 /// <param name="textureFlags">true if the texture needs to support unordered read write.</param>
 /// <returns>
 /// A new instance of 3D <see cref="Texture"/> class.
 /// </returns>
 public static Texture New3D(GraphicsDevice device, int width, int height, int depth, MipMapCount mipCount, PixelFormat format, TextureFlags textureFlags = TextureFlags.ShaderResource, GraphicsResourceUsage usage = GraphicsResourceUsage.Default)
 {
     return new Texture(device).InitializeFrom(TextureDescription.New3D(width, height, depth, mipCount, format, textureFlags, usage));
 }
示例#35
0
 public TexFormat(PixelInternalFormat _pif, PixelFormat _pf, PixelType _pt)
 {
     pif = _pif;
     pf  = _pf;
     pt  = _pt;
 }
示例#36
0
        /// <summary>
        /// BitmapEx object into system memory.
        /// </summary>
        /// <param name="rect">A System.Drawing.Rectangle structure specifying the portion of the BitmapEx to lock.  </param>
        /// <param name="flags">Access level (read and write) for the BitmapEx object. ></param>
        /// <param name="format">PixelFormat enumeration specifying the data format of this BitmapEx object.</param>
        /// <returns>BitmapData object containing information about this lock operation.  </returns>
        public OpenNETCF.Drawing.Imaging.BitmapData LockBits(Rectangle rect, int flags, PixelFormat format)
        {
            //TODO: Don't care about PixelFormat. For now they are all converted to 24 bits
            OpenNETCF.Drawing.Imaging.BitmapData data;

            data        = new OpenNETCF.Drawing.Imaging.BitmapData();
            saveHBitmap = hBitmap;
            hBitmap     = GDIPlus.BitmapLockBits(this, 0, 0, data);

            GC.KeepAlive(this);

            return(data);
        }
示例#37
0
        private unsafe Bitmap DecompressV2Texture(BinaryReader bReader, int imageLength, short outputWidth, short outputHeight, byte textureType)
        {
            var buffer = bReader.ReadBytes(imageLength);

            int w = Width + (4 - Width % 4) % 4;
            int a = 1;

            while (true)
            {
                a *= 2;
                if (a >= w)
                {
                    w = a;
                    break;
                }
            }
            int h = Height + (4 - Height % 4) % 4;
            int e = w * h / 2;

            SquishFlags type;

            switch (textureType)
            {
            case 0:
            case 1:
                type = SquishFlags.Dxt1;
                break;

            case 3:
                type = SquishFlags.Dxt3;
                break;

            case 5:
                type = SquishFlags.Dxt5;
                break;

            default:
                throw new NotImplementedException();
            }


            var decompressedBuffer = Ionic.Zlib.DeflateStream.UncompressBuffer(buffer);

            var bitmap = new Bitmap(w, h);

            BitmapData data = bitmap.LockBits(
                new Rectangle(0, 0, w, h),
                ImageLockMode.WriteOnly,
                PixelFormat.Format32bppRgb
                );

            fixed(byte *source = decompressedBuffer)
            Squish.DecompressImage(data.Scan0, w, h, (IntPtr)source, type);

            byte *dest = (byte *)data.Scan0;

            for (int i = 0; i < w * h * 4; i += 4)
            {
                //Reverse Red/Blue
                byte b = dest[i];
                dest[i]     = dest[i + 2];
                dest[i + 2] = b;
            }

            bitmap.UnlockBits(data);

            Rectangle   cloneRect   = new Rectangle(0, 0, outputWidth, outputHeight);
            PixelFormat format      = bitmap.PixelFormat;
            Bitmap      cloneBitmap = bitmap.Clone(cloneRect, format);

            return(cloneBitmap);
        }
        public LinearAccessByteImage(byte[] imageDataA, int strideA, int widthA, int heightA, PixelFormat pixelFormatA)
        {
            originalStride      = strideA;
            width               = widthA;
            height              = heightA;
            pixelFormat         = PixelFormat.Format24bppRgb;
            originalPixelFormat = pixelFormatA;

            // bc thats what were gonna be using for the calculations. 2 bc we need to use widen to go from byte to short and that creates 2 vectors.
            // we can ignore the bit of empty bytes being compared because they will just be zeros being compared to zeros and adding extra ifs to check they're not being compared would likely just slow down things more.
            int vectorCountForMultiplication = Vector <short> .Count * 2;

            int pixelCount = width * height * 3;
            int pixelCountDivisibleByVectorSize = (int)(vectorCountForMultiplication * Math.Ceiling((double)pixelCount / (double)vectorCountForMultiplication));

            imageData = new sbyte[pixelCountDivisibleByVectorSize]; // We're not actually going to be using the extra pixels for anything useful, it's just to avoid memory overflow when reading from the array

            int channelMultiplier = 3;

            if (pixelFormatA == PixelFormat.Format32bppArgb)
            {
                channelMultiplier = 4;
            }

            int strideHere, linearHere;

            for (int y = 0; y < height; y++)
            {
                strideHere = y * strideA;
                linearHere = y * width * 3;
                for (int x = 0; x < width; x++)
                {
                    imageData[linearHere + x * 3]     = (sbyte)(imageDataA[strideHere + x * channelMultiplier] - 128);
                    imageData[linearHere + x * 3 + 1] = (sbyte)(imageDataA[strideHere + x * channelMultiplier + 1] - 128);
                    imageData[linearHere + x * 3 + 2] = (sbyte)(imageDataA[strideHere + x * channelMultiplier + 2] - 128);
                }
            }

            stride = width;

            //imageData = imageDataA;
        }
示例#39
0
 private Texture(PixelFormat format, uint width, uint height, uint depth, TextureType texType, TextureUsage usage, uint numSamples, bool hasMipmaps, bool gammaCorrection)
 {
     Internal_create(this, format, width, height, depth, texType, usage, numSamples, hasMipmaps, gammaCorrection);
 }
示例#40
0
        private static Point FindPointImpl(Bitmap bitmap, out Point comboPoint)
        {
            var standPColor = Color.FromArgb(54, 60, 102);
            var comboPColor = Color.FromArgb(245, 245, 245);

            Point standPoint = Point.Empty;

            comboPoint = Point.Empty;

            int y1 = (int)(bitmap.Height * 0.2);
            int y2 = (int)(bitmap.Height * 0.63);

            PixelFormat pf = PixelFormat.Format24bppRgb;

            BitmapData bitmapData = bitmap.LockBits(new Rectangle(0, y1, bitmap.Width, y2), ImageLockMode.ReadOnly, pf);

            try
            {
                unsafe
                {
                    int w = 0;
                    while (y2 > y1)
                    {
                        byte *p = (byte *)bitmapData.Scan0 + (y2 - y1 - 1) * bitmapData.Stride;
                        w = bitmap.Width;
                        int endColorCount = 0;
                        while (w > 40)
                        {
                            ICColor *pc = (ICColor *)(p + w * 3);
                            if (standPoint == Point.Empty &&
                                pc->R == standPColor.R && pc->G == standPColor.G && pc->B == standPColor.B)
                            {
                                standPoint = new Point(w - 3, y2);
                                if (comboPoint != Point.Empty)
                                {
                                    break;
                                }
                            }
                            else if (comboPoint == Point.Empty)
                            {
                                if (pc->R == comboPColor.R && pc->G == comboPColor.G && pc->B == comboPColor.B)
                                {
                                    endColorCount++;
                                }
                                else
                                {
                                    if (endColorCount > 0)
                                    {
                                        comboPoint = new Point(w + 5, y2 - 1);
                                        if (standPoint != Point.Empty)
                                        {
                                            break;
                                        }
                                    }
                                    endColorCount = 0;
                                }
                            }
                            w--;
                        }
                        if (comboPoint == Point.Empty)
                        {
                            if (endColorCount > 10)
                            {
                                comboPoint = new Point(w + 5, y2 - 1);
                            }
                        }
                        if (standPoint != Point.Empty && comboPoint != Point.Empty)
                        {
                            break;
                        }
                        y2--;
                    }
                }
                return(standPoint);
            }
            finally
            {
                bitmap.UnlockBits(bitmapData);
            }
        }
示例#41
0
        public static void ConvertPixelFormat(GraphicsDevice graphicsDevice, PixelFormat inputFormat, out PixelInternalFormat internalFormat, out PixelFormatGl format, out PixelType type, out int pixelSize, out bool compressed)
        {
            compressed = false;

#if SILICONSTUDIO_PARADOX_GRAPHICS_API_OPENGLES
            // check formats is the device is initialized with OpenGL ES 2
            if (graphicsDevice.IsOpenGLES2)
            {
                switch (inputFormat)
                {
                case PixelFormat.R32_UInt:
                case PixelFormat.R32_Float:
                case PixelFormat.R32G32_Float:
                case PixelFormat.R32G32B32_Float:
                case PixelFormat.R16G16B16A16_Float:
                case PixelFormat.R32G32B32A32_Float:
                case PixelFormat.D32_Float:
                    throw new NotSupportedException(String.Format("Texture format {0} not supported", inputFormat));

                case PixelFormat.D24_UNorm_S8_UInt:
                    if (!(graphicsDevice.HasDepth24 && graphicsDevice.HasPackedDepthStencilExtension))
                    {
                        throw new NotSupportedException(String.Format("Texture format {0} not supported", inputFormat));
                    }
                    break;
                }
            }
#endif

            switch (inputFormat)
            {
            case PixelFormat.A8_UNorm:
                internalFormat = PixelInternalFormat.Alpha;
                format         = PixelFormatGl.Alpha;
                type           = PixelType.UnsignedByte;
                pixelSize      = 1;
                break;

            case PixelFormat.R8_UNorm:
#if SILICONSTUDIO_PARADOX_GRAPHICS_API_OPENGLES
                if (graphicsDevice.IsOpenGLES2)
                {
                    internalFormat = PixelInternalFormat.Luminance;
                    format         = PixelFormatGl.Luminance;
                }
                else
#endif
                {
                    internalFormat = R8;
                    format         = PixelFormatGl.Red;
                }
                type      = PixelType.UnsignedByte;
                pixelSize = 1;
                break;

            case PixelFormat.R8G8B8A8_UNorm:
                internalFormat = PixelInternalFormat.Rgba;
                format         = PixelFormatGl.Rgba;
                type           = PixelType.UnsignedByte;
                pixelSize      = 4;
                break;

            case PixelFormat.B8G8R8A8_UNorm:
#if SILICONSTUDIO_PARADOX_GRAPHICS_API_OPENGLES
                if (!graphicsDevice.HasExtTextureFormatBGRA8888)
                {
                    throw new NotSupportedException();
                }

                // It seems iOS and Android expects different things
#if SILICONSTUDIO_PLATFORM_IOS
                internalFormat = PixelInternalFormat.Rgba;
#else
                internalFormat = (PixelInternalFormat)ExtTextureFormatBgra8888.BgraExt;
#endif
                format = (PixelFormatGl)ExtTextureFormatBgra8888.BgraExt;
#else
                internalFormat = PixelInternalFormat.Rgba;
                format         = PixelFormatGl.Bgra;
#endif
                type      = PixelType.UnsignedByte;
                pixelSize = 4;
                break;

            case PixelFormat.R8G8B8A8_UNorm_SRgb:
                internalFormat = Srgb8Alpha8;
                format         = PixelFormatGl.Rgba;
                type           = PixelType.UnsignedByte;
                pixelSize      = 4;
                break;

            case PixelFormat.B8G8R8A8_UNorm_SRgb:
                internalFormat = Srgb8Alpha8;
#if SILICONSTUDIO_PARADOX_GRAPHICS_API_OPENGLES
                format = (PixelFormatGl)ExtTextureFormatBgra8888.BgraExt;
#else
                format = PixelFormatGl.Bgra;
#endif
                type      = PixelType.UnsignedByte;
                pixelSize = 4;
                break;

            case PixelFormat.R16_Float:
                internalFormat = R16f;
                format         = PixelFormatGl.Red;
                type           = PixelType.HalfFloat;
                pixelSize      = 2;
                break;

            case PixelFormat.R16G16_Float:
                internalFormat = Rg16f;
                format         = PixelFormatGl.Rg;
                type           = PixelType.HalfFloat;
                pixelSize      = 4;
                break;

            case PixelFormat.R16G16B16A16_Float:
                internalFormat = Rgba16f;
                format         = PixelFormatGl.Rgba;
                type           = PixelType.HalfFloat;
                pixelSize      = 8;
                break;

            case PixelFormat.R32_UInt:
                internalFormat = R32ui;
                format         = PixelFormatGl.RedInteger;
                type           = PixelType.UnsignedInt;
                pixelSize      = 4;
                break;

            case PixelFormat.R32_Float:
                internalFormat = R32f;
                format         = PixelFormatGl.Red;
                type           = PixelType.Float;
                pixelSize      = 4;
                break;

            case PixelFormat.R32G32_Float:
                internalFormat = Rg32f;
                format         = PixelFormatGl.Rg;
                type           = PixelType.Float;
                pixelSize      = 8;
                break;

            case PixelFormat.R32G32B32_Float:
                internalFormat = Rgb32f;
                format         = PixelFormatGl.Rgb;
                type           = PixelType.Float;
                pixelSize      = 12;
                break;

            case PixelFormat.R32G32B32A32_Float:
                internalFormat = Rgba32f;
                format         = PixelFormatGl.Rgba;
                type           = PixelType.Float;
                pixelSize      = 16;
                break;

            case PixelFormat.D16_UNorm:
                internalFormat = DepthComponent16;
                format         = PixelFormatGl.DepthComponent;
                type           = PixelType.UnsignedShort;
                pixelSize      = 2;
                break;

            case PixelFormat.D24_UNorm_S8_UInt:
                internalFormat = Depth24Stencil8;
                format         = PixelFormatGl.DepthStencil;
                type           = PixelType.UnsignedInt248;
                pixelSize      = 4;
                break;

            // TODO: Temporary depth format (need to decide relation between RenderTarget1D and Texture)
            case PixelFormat.D32_Float:
                internalFormat = DepthComponent32f;
                format         = PixelFormatGl.DepthComponent;
                type           = PixelType.Float;
                pixelSize      = 4;
                break;

#if SILICONSTUDIO_PLATFORM_IOS
            case PixelFormat.PVRTC_4bpp_RGB:
                internalFormat = (PixelInternalFormat)ImgTextureCompressionPvrtc.CompressedRgbPvrtc4Bppv1Img;
                format         = (PixelFormatGl)ImgTextureCompressionPvrtc.CompressedRgbPvrtc4Bppv1Img;
                compressed     = true;
                pixelSize      = 4;
                type           = PixelType.UnsignedByte;
                break;

            case PixelFormat.PVRTC_2bpp_RGB:
                internalFormat = (PixelInternalFormat)ImgTextureCompressionPvrtc.CompressedRgbPvrtc2Bppv1Img;
                format         = (PixelFormatGl)ImgTextureCompressionPvrtc.CompressedRgbPvrtc2Bppv1Img;
                compressed     = true;
                pixelSize      = 2;
                type           = PixelType.UnsignedByte;
                break;

            case PixelFormat.PVRTC_4bpp_RGBA:
                internalFormat = (PixelInternalFormat)ImgTextureCompressionPvrtc.CompressedRgbaPvrtc4Bppv1Img;
                format         = (PixelFormatGl)ImgTextureCompressionPvrtc.CompressedRgbaPvrtc4Bppv1Img;
                compressed     = true;
                pixelSize      = 4;
                type           = PixelType.UnsignedByte;
                break;

            case PixelFormat.PVRTC_2bpp_RGBA:
                internalFormat = (PixelInternalFormat)ImgTextureCompressionPvrtc.CompressedRgbaPvrtc2Bppv1Img;
                format         = (PixelFormatGl)ImgTextureCompressionPvrtc.CompressedRgbaPvrtc2Bppv1Img;
                compressed     = true;
                pixelSize      = 2;
                type           = PixelType.UnsignedByte;
                break;
#elif SILICONSTUDIO_PLATFORM_ANDROID || !SILICONSTUDIO_PLATFORM_MONO_MOBILE && SILICONSTUDIO_PARADOX_GRAPHICS_API_OPENGLES
// Desktop OpenGLES
            case PixelFormat.ETC1:
                // TODO: Runtime check for extension?
                internalFormat = (PixelInternalFormat)OesCompressedEtc1Rgb8Texture.Etc1Rgb8Oes;
                format         = (PixelFormatGl)OesCompressedEtc1Rgb8Texture.Etc1Rgb8Oes;
                compressed     = true;
                pixelSize      = 2;
                type           = PixelType.UnsignedByte;
                break;

            case PixelFormat.ETC2_RGBA:
                internalFormat = (PixelInternalFormat)CompressedInternalFormat.CompressedRgba8Etc2Eac;
                format         = (PixelFormatGl)CompressedInternalFormat.CompressedRgba8Etc2Eac;
                compressed     = true;
                pixelSize      = 2;
                type           = PixelType.UnsignedByte;
                break;
#endif
            case PixelFormat.None:     // TODO: remove this - this is only for buffers used in compute shaders
                internalFormat = PixelInternalFormat.Rgba;
                format         = PixelFormatGl.Red;
                type           = PixelType.UnsignedByte;
                pixelSize      = 1;
                break;

            default:
                throw new InvalidOperationException("Unsupported texture format");
            }
        }
示例#42
0
 /// <summary>
 /// Converts the source image to a different pixel format
 /// </summary>
 /// <param name="source">The source stream.</param>
 /// <param name="pixelFormat">The pixel format to convert to</param>
 /// <returns>The resulting stream.</returns>
 public static IProducer <Shared <Image> > Convert(this IProducer <Shared <Image> > source, PixelFormat pixelFormat)
 {
     return(source.PipeTo(new ToPixelFormat(source.Out.Pipeline, pixelFormat)));
 }
示例#43
0
 /// <summary>
 /// Converts the source image to a different pixel format.
 /// </summary>
 /// <param name="source">The source stream.</param>
 /// <param name="pixelFormat">The pixel format to convert to.</param>
 /// <param name="deliveryPolicy">An optional delivery policy.</param>
 /// <param name="sharedImageAllocator">Optional image allocator for creating new shared image.</param>
 /// <returns>The resulting stream.</returns>
 public static IProducer <Shared <Image> > ToPixelFormat(this IProducer <Shared <Image> > source, PixelFormat pixelFormat, DeliveryPolicy <Shared <Image> > deliveryPolicy = null, Func <int, int, PixelFormat, Shared <Image> > sharedImageAllocator = null)
 {
     return(source.PipeTo(new ToPixelFormat(source.Out.Pipeline, pixelFormat, sharedImageAllocator), deliveryPolicy));
 }
示例#44
0
        /// <summary>
        ///     Determines whether the specified <see cref="Image"/> size is within the
        ///     allowed range, depending on the specified pixel format.
        /// </summary>
        /// <param name="size">
        ///     The image size to check.
        /// </param>
        /// <param name="pixelFormat">
        ///     The pixel format.
        /// </param>
        public static bool SizeIsValid(Size size, PixelFormat pixelFormat)
        {
            var indicator = Math.Max(size.Width, size.Height);

            return(SizeIsValid(indicator, pixelFormat));
        }
示例#45
0
 /// <summary>
 /// Converts an image to a different pixel format using the specified transformer
 /// </summary>
 /// <param name="source">Source image to compress</param>
 /// <param name="transformer">Method for converting an image sample</param>
 /// <param name="pixelFormat">Pixel format to use for converted image</param>
 /// <param name="deliveryPolicy">Delivery policy</param>
 /// <returns>Returns a producer that generates the transformed images</returns>
 public static IProducer <Shared <Image> > Transform(this IProducer <Shared <Image> > source, TransformDelegate transformer, PixelFormat pixelFormat, DeliveryPolicy deliveryPolicy = null)
 {
     return(source.PipeTo(new ImageTransformer(source.Out.Pipeline, transformer, pixelFormat), deliveryPolicy));
 }
        private void Socket_StartDataRecievedCallback(MetaData metaData)
        {
            lock (this)
            {
                if (isDisposed)
                {
                    return;
                }

                void CreateTimer(bool recreate)
                {
                    if (recreate && timer != null)
                    {
                        timer.Tick -= Timer_Tick;
                        timer.Dispose();
                        timer = null;
                    }

                    if (timer == null)
                    {
                        timer          = new Timer();
                        timer.Interval = 1000 / targetFPS;
                        timer.Tick    += Timer_Tick;
                    }

                    timer.Start();
                }

                // update settings
                if (metaData.type == MetaDataTypes.UpdateSettings || metaData.type == MetaDataTypes.StartCapture)
                {
                    DebugLog.Log("Updating settings");
                    format          = metaData.format;
                    screenIndex     = metaData.screenIndex;
                    compress        = metaData.compressed;
                    resolutionScale = metaData.resolutionScale;
                    targetFPS       = metaData.targetFPS;
                    if (metaData.type == MetaDataTypes.UpdateSettings)
                    {
                        dispatcher.InvokeAsync(delegate()
                        {
                            CreateTimer(true);
                        });
                    }
                }

                // start / stop
                if (metaData.type == MetaDataTypes.StartCapture)
                {
                    dispatcher.InvokeAsync(delegate()
                    {
                        CreateTimer(false);
                    });
                }
                else if (metaData.type == MetaDataTypes.PauseCapture)
                {
                    dispatcher.InvokeAsync(delegate()
                    {
                        timer.Stop();
                    });
                }
                else if (metaData.type == MetaDataTypes.ResumeCapture)
                {
                    dispatcher.InvokeAsync(delegate()
                    {
                        timer.Start();
                    });
                }
                else if (metaData.type == MetaDataTypes.UpdateMouse)
                {
                    // mouse pos
                    Cursor.Position = new Point(metaData.mouseX, metaData.mouseY);

                    // mouse clicks
                    if (inputLastMouseState != metaData.mouseButtonPressed)
                    {
                        // handle state changes
                        if (inputLastMouseState == 1)
                        {
                            input.Mouse.LeftButtonUp();
                        }
                        else if (inputLastMouseState == 2)
                        {
                            input.Mouse.RightButtonUp();
                        }
                        else if (inputLastMouseState == 3)
                        {
                            input.Mouse.XButtonUp(2);
                        }

                        // handle new state
                        if (metaData.mouseButtonPressed == 1)
                        {
                            input.Mouse.LeftButtonDown();
                        }
                        else if (metaData.mouseButtonPressed == 2)
                        {
                            input.Mouse.RightButtonDown();
                        }
                        else if (metaData.mouseButtonPressed == 3)
                        {
                            input.Mouse.XButtonDown(2);
                        }
                    }

                    // mouse scroll wheel
                    if (metaData.mouseScroll != 0)
                    {
                        input.Mouse.VerticalScroll(metaData.mouseScroll);
                    }

                    // finish
                    inputLastMouseState = metaData.mouseButtonPressed;
                }
                else if (metaData.type == MetaDataTypes.UpdateKeyboard)
                {
                    VirtualKeyCode specialKey = 0;
                    if (metaData.specialKeyCode != 0)
                    {
                        specialKey = ConvertKeyCode((Key)metaData.specialKeyCode);
                        if (specialKey != 0)
                        {
                            input.Keyboard.KeyDown(specialKey);
                        }
                    }

                    if (metaData.keyCode != 0)
                    {
                        var key = ConvertKeyCode((Key)metaData.keyCode);
                        if (key != 0)
                        {
                            input.Keyboard.KeyPress(key);
                        }
                        if (specialKey != 0)
                        {
                            input.Keyboard.KeyUp(specialKey);
                        }
                    }
                }
            }
        }
        /// <summary>
        /// Gather vertical intensity statistics for specified image.
        /// </summary>
        ///
        /// <param name="image">Source image.</param>
        ///
        private void ProcessImage(UnmanagedImage image)
        {
            PixelFormat pixelFormat = image.PixelFormat;
            // get image dimension
            int width  = image.Width;
            int height = image.Height;

            red = green = blue = gray = null;

            // do the job
            unsafe
            {
                // check pixel format
                if (pixelFormat == PixelFormat.Format8bppIndexed)
                {
                    // 8 bpp grayscale image
                    byte *p      = (byte *)image.ImageData.ToPointer( );
                    int   offset = image.Stride - width;

                    // histogram array
                    int[] g = new int[height];

                    // for each pixel
                    for (int y = 0; y < height; y++)
                    {
                        int lineSum = 0;

                        // for each pixel
                        for (int x = 0; x < width; x++, p++)
                        {
                            lineSum += *p;
                        }
                        g[y] = lineSum;

                        p += offset;
                    }

                    // create historgram for gray level
                    gray = new Histogram(g);
                }
                else if (pixelFormat == PixelFormat.Format16bppGrayScale)
                {
                    // 16 bpp grayscale image
                    byte *basePtr = (byte *)image.ImageData.ToPointer( );
                    int   stride  = image.Stride;

                    // histogram array
                    int[] g = new int[height];

                    // for each pixel
                    for (int y = 0; y < height; y++)
                    {
                        ushort *p       = (ushort *)(basePtr + stride * y);
                        int     lineSum = 0;

                        // for each pixel
                        for (int x = 0; x < width; x++, p++)
                        {
                            lineSum += *p;
                        }
                        g[y] = lineSum;
                    }

                    // create historgram for gray level
                    gray = new Histogram(g);
                }
                else if (
                    (pixelFormat == PixelFormat.Format24bppRgb) ||
                    (pixelFormat == PixelFormat.Format32bppRgb) ||
                    (pixelFormat == PixelFormat.Format32bppArgb))
                {
                    // 24/32 bpp color image
                    byte *p         = (byte *)image.ImageData.ToPointer( );
                    int   pixelSize = (pixelFormat == PixelFormat.Format24bppRgb) ? 3 : 4;
                    int   offset    = image.Stride - width * pixelSize;

                    // histogram arrays
                    int[] r = new int[height];
                    int[] g = new int[height];
                    int[] b = new int[height];

                    // for each line
                    for (int y = 0; y < height; y++)
                    {
                        int lineRSum = 0;
                        int lineGSum = 0;
                        int lineBSum = 0;

                        // for each pixel
                        for (int x = 0; x < width; x++, p += pixelSize)
                        {
                            lineRSum += p[RGB.R];
                            lineGSum += p[RGB.G];
                            lineBSum += p[RGB.B];
                        }
                        r[y] = lineRSum;
                        g[y] = lineGSum;
                        b[y] = lineBSum;

                        p += offset;
                    }

                    // create histograms
                    red   = new Histogram(r);
                    green = new Histogram(g);
                    blue  = new Histogram(b);
                }
                else if (
                    (pixelFormat == PixelFormat.Format48bppRgb) ||
                    (pixelFormat == PixelFormat.Format64bppArgb))
                {
                    // 48/64 bpp color image
                    byte *basePtr   = (byte *)image.ImageData.ToPointer( );
                    int   stride    = image.Stride;
                    int   pixelSize = (pixelFormat == PixelFormat.Format48bppRgb) ? 3 : 4;

                    // histogram arrays
                    int[] r = new int[height];
                    int[] g = new int[height];
                    int[] b = new int[height];

                    // for each line
                    for (int y = 0; y < height; y++)
                    {
                        ushort *p = (ushort *)(basePtr + stride * y);

                        int lineRSum = 0;
                        int lineGSum = 0;
                        int lineBSum = 0;

                        // for each pixel
                        for (int x = 0; x < width; x++, p += pixelSize)
                        {
                            lineRSum += p[RGB.R];
                            lineGSum += p[RGB.G];
                            lineBSum += p[RGB.B];
                        }
                        r[y] = lineRSum;
                        g[y] = lineGSum;
                        b[y] = lineBSum;
                    }

                    // create histograms
                    red   = new Histogram(r);
                    green = new Histogram(g);
                    blue  = new Histogram(b);
                }
            }
        }
示例#48
0
 public static Bitmap CaptureRegion(int x, int y, int width, int height, PixelFormat format = PixelFormat.Format24bppRgb)
 {
     return(CaptureRegion(new Rectangle(x, y, width, height), format));
 }
示例#49
0
        /// <summary>
        ///     Determines whether the specified <see cref="Image"/> size is within the
        ///     allowed range, depending on the specified pixel format.
        /// </summary>
        /// <param name="width">
        ///     The image width to check.
        /// </param>
        /// <param name="height">
        ///     The image height to check.
        /// </param>
        /// <param name="pixelFormat">
        ///     The pixel format.
        /// </param>
        public static bool SizeIsValid(int width, int height, PixelFormat pixelFormat)
        {
            var indicator = Math.Max(width, height);

            return(SizeIsValid(indicator, pixelFormat));
        }
示例#50
0
        void CreateDeviceResources()
        {
            uint width  = (uint)host.ActualWidth;
            uint height = (uint)host.ActualHeight;

            // If we don't have a device, need to create one now and all
            // accompanying D3D resources.
            CreateDevice();

            Factory dxgiFactory = Factory.Create();

            SwapChainDescription swapDesc = new SwapChainDescription
            {
                BufferDescription = new ModeDescription
                {
                    Width       = width, Height = height,
                    Format      = Format.R8G8B8A8UNorm,
                    RefreshRate = new Rational {
                        Numerator = 60, Denominator = 1
                    }
                },
                SampleDescription = new SampleDescription {
                    Count = 1, Quality = 0
                },
                BufferUsage        = UsageOptions.RenderTargetOutput,
                BufferCount        = 1,
                OutputWindowHandle = host.Handle,
                Windowed           = true
            };

            swapChain = dxgiFactory.CreateSwapChain(
                device, swapDesc);

            // Create rasterizer state object
            RasterizerDescription rsDesc = new RasterizerDescription();

            rsDesc.AntiAliasedLineEnable = false;
            rsDesc.CullMode              = CullMode.None;
            rsDesc.DepthBias             = 0;
            rsDesc.DepthBiasClamp        = 0;
            rsDesc.DepthClipEnable       = true;
            rsDesc.FillMode              = D3D10.FillMode.Solid;
            rsDesc.FrontCounterclockwise = false; // Must be FALSE for 10on9
            rsDesc.MultisampleEnable     = false;
            rsDesc.ScissorEnable         = false;
            rsDesc.SlopeScaledDepthBias  = 0;

            rasterizerState = device.CreateRasterizerState(
                rsDesc);

            device.RS.State = rasterizerState;

            // If we don't have a D2D render target, need to create all of the resources
            // required to render to one here.
            // Ensure that nobody is holding onto one of the old resources
            device.OM.RenderTargets = new OutputMergerRenderTargets(new RenderTargetView[] { null });

            InitializeDepthStencil(width, height);

            // Create views on the RT buffers and set them on the device
            RenderTargetViewDescription renderDesc = new RenderTargetViewDescription();

            renderDesc.Format        = Format.R8G8B8A8UNorm;
            renderDesc.ViewDimension = RenderTargetViewDimension.Texture2D;

            Texture2DRenderTargetView renderView = renderDesc.Texture2D;

            renderView.MipSlice  = 0;
            renderDesc.Texture2D = renderView;

            using (D3DResource spBackBufferResource = swapChain.GetBuffer <D3DResource>(0))
            {
                renderTargetView = device.CreateRenderTargetView(
                    spBackBufferResource,
                    renderDesc);
            }

            device.OM.RenderTargets = new OutputMergerRenderTargets(new RenderTargetView[] { renderTargetView }, depthStencilView);

            SetViewport(width, height);


            // Create a D2D render target which can draw into the surface in the swap chain
            RenderTargetProperties props =
                new RenderTargetProperties(
                    RenderTargetType.Default, new PixelFormat(Format.Unknown, AlphaMode.Premultiplied),
                    96, 96, RenderTargetUsages.None, FeatureLevel.Default);

            // Allocate a offscreen D3D surface for D2D to render our 2D content into
            Texture2DDescription tex2DDescription = new Texture2DDescription
            {
                ArraySize                    = 1,
                BindingOptions               = BindingOptions.RenderTarget | BindingOptions.ShaderResource,
                CpuAccessOptions             = CpuAccessOptions.None,
                Format                       = Format.R8G8B8A8UNorm,
                Height                       = 4096,
                Width                        = 512,
                MipLevels                    = 1,
                MiscellaneousResourceOptions = MiscellaneousResourceOptions.None,
                SampleDescription            = new SampleDescription {
                    Count = 1, Quality = 0
                },
                Usage = Usage.Default
            };

            offscreenTexture = device.CreateTexture2D(tex2DDescription);

            using (Surface dxgiSurface = offscreenTexture.GraphicsSurface)
            {
                // Create a D2D render target which can draw into our offscreen D3D surface
                renderTarget = d2DFactory.CreateGraphicsSurfaceRenderTarget(
                    dxgiSurface,
                    props);
            }

            PixelFormat alphaOnlyFormat = new PixelFormat(Format.A8UNorm, AlphaMode.Premultiplied);

            opacityRenderTarget = renderTarget.CreateCompatibleRenderTarget(CompatibleRenderTargetOptions.None,
                                                                            alphaOnlyFormat);

            // Load pixel shader
            // Open precompiled vertex shader
            // This file was compiled using DirectX's SDK Shader compilation tool:
            // fxc.exe /T fx_4_0 /Fo SciFiText.fxo SciFiText.fx
            shader = LoadResourceShader(device, "SciFiTextDemo.SciFiText.fxo");

            // Obtain the technique
            technique = shader.GetTechniqueByName("Render");

            // Obtain the variables
            worldMatrixVariable     = shader.GetVariableByName("World").AsMatrix;
            viewMatrixVariable      = shader.GetVariableByName("View").AsMatrix;
            projectionMarixVariable = shader.GetVariableByName("Projection").AsMatrix;
            diffuseVariable         = shader.GetVariableByName("txDiffuse").AsShaderResource;

            // Create the input layout
            PassDescription passDesc = new PassDescription();

            passDesc = technique.GetPassByIndex(0).Description;

            vertexLayout = device.CreateInputLayout(
                inputLayoutDescriptions,
                passDesc.InputAssemblerInputSignature,
                passDesc.InputAssemblerInputSignatureSize
                );

            // Set the input layout
            device.IA.InputLayout = vertexLayout;

            IntPtr verticesDataPtr = Marshal.AllocHGlobal(Marshal.SizeOf(VertexArray.VerticesInstance));

            Marshal.StructureToPtr(VertexArray.VerticesInstance, verticesDataPtr, true);

            BufferDescription bd = new BufferDescription();

            bd.Usage                        = Usage.Default;
            bd.ByteWidth                    = (uint)Marshal.SizeOf(VertexArray.VerticesInstance);
            bd.BindingOptions               = BindingOptions.VertexBuffer;
            bd.CpuAccessOptions             = CpuAccessOptions.None;
            bd.MiscellaneousResourceOptions = MiscellaneousResourceOptions.None;

            SubresourceData InitData = new SubresourceData {
                SystemMemory = verticesDataPtr
            };

            vertexBuffer = device.CreateBuffer(bd, InitData);

            Marshal.FreeHGlobal(verticesDataPtr);

            // Set vertex buffer
            uint stride = (uint)Marshal.SizeOf(typeof(SimpleVertex));
            uint offset = 0;

            device.IA.SetVertexBuffers(
                0,
                new D3DBuffer[] { vertexBuffer },
                new uint[] { stride },
                new uint[] { offset }
                );

            IntPtr indicesDataPtr = Marshal.AllocHGlobal(Marshal.SizeOf(VertexArray.IndicesInstance));

            Marshal.StructureToPtr(VertexArray.IndicesInstance, indicesDataPtr, true);

            bd.Usage                        = Usage.Default;
            bd.ByteWidth                    = (uint)Marshal.SizeOf(VertexArray.IndicesInstance);
            bd.BindingOptions               = BindingOptions.IndexBuffer;
            bd.CpuAccessOptions             = CpuAccessOptions.None;
            bd.MiscellaneousResourceOptions = MiscellaneousResourceOptions.None;

            InitData.SystemMemory = indicesDataPtr;

            facesIndexBuffer = device.CreateBuffer(
                bd,
                InitData
                );

            Marshal.FreeHGlobal(indicesDataPtr);

            // Set primitive topology
            device.IA.PrimitiveTopology = PrimitiveTopology.TriangleList;

            // Convert the D2D texture into a Shader Resource View
            textureResourceView = device.CreateShaderResourceView(
                offscreenTexture);

            // Initialize the world matrices
            worldMatrix = Matrix4x4F.Identity;

            // Initialize the view matrix
            Vector3F Eye = new Vector3F(0.0f, 0.0f, 13.0f);
            Vector3F At  = new Vector3F(0.0f, -3.5f, 45.0f);
            Vector3F Up  = new Vector3F(0.0f, 1.0f, 0.0f);

            viewMatrix = Camera.MatrixLookAtLH(Eye, At, Up);

            // Initialize the projection matrix
            projectionMatrix = Camera.MatrixPerspectiveFovLH(
                (float)Math.PI * 0.1f,
                width / (float)height,
                0.1f,
                100.0f);

            // Update Variables that never change
            viewMatrixVariable.Matrix = viewMatrix;

            projectionMarixVariable.Matrix = projectionMatrix;

            GradientStop[] gradientStops =
            {
                new GradientStop(0.0f, new ColorF(GetColorValues(System.Windows.Media.Colors.Yellow))),
                new GradientStop(1.0f, new ColorF(GetColorValues(System.Windows.Media.Colors.Black)))
            };

            GradientStopCollection spGradientStopCollection = renderTarget.CreateGradientStopCollection(
                gradientStops, Gamma.StandardRgb, ExtendMode.Clamp);

            // Create a linear gradient brush for text
            textBrush = renderTarget.CreateLinearGradientBrush(
                new LinearGradientBrushProperties(new Point2F(0, 0), new Point2F(0, -2048)),
                spGradientStopCollection
                );
        }
示例#51
0
        public VkPipeline(VkGraphicsDevice gd, ref GraphicsPipelineDescription description)
            : base(ref description)
        {
            _gd = gd;
            IsComputePipeline = false;

            VkGraphicsPipelineCreateInfo pipelineCI = VkGraphicsPipelineCreateInfo.New();

            // Blend State
            VkPipelineColorBlendStateCreateInfo blendStateCI = VkPipelineColorBlendStateCreateInfo.New();
            int attachmentsCount = description.BlendState.AttachmentStates.Length;
            VkPipelineColorBlendAttachmentState *attachmentsPtr
                = stackalloc VkPipelineColorBlendAttachmentState[attachmentsCount];

            for (int i = 0; i < attachmentsCount; i++)
            {
                BlendAttachmentDescription          vdDesc          = description.BlendState.AttachmentStates[i];
                VkPipelineColorBlendAttachmentState attachmentState = new VkPipelineColorBlendAttachmentState();
                attachmentState.srcColorBlendFactor = VkFormats.VdToVkBlendFactor(vdDesc.SourceColorFactor);
                attachmentState.dstColorBlendFactor = VkFormats.VdToVkBlendFactor(vdDesc.DestinationColorFactor);
                attachmentState.colorBlendOp        = VkFormats.VdToVkBlendOp(vdDesc.ColorFunction);
                attachmentState.srcAlphaBlendFactor = VkFormats.VdToVkBlendFactor(vdDesc.SourceAlphaFactor);
                attachmentState.dstAlphaBlendFactor = VkFormats.VdToVkBlendFactor(vdDesc.DestinationAlphaFactor);
                attachmentState.alphaBlendOp        = VkFormats.VdToVkBlendOp(vdDesc.AlphaFunction);
                attachmentState.blendEnable         = vdDesc.BlendEnabled;
                attachmentState.colorWriteMask      = VkColorComponentFlags.R | VkColorComponentFlags.G | VkColorComponentFlags.B | VkColorComponentFlags.A;
                attachmentsPtr[i] = attachmentState;
            }

            blendStateCI.attachmentCount = (uint)attachmentsCount;
            blendStateCI.pAttachments    = attachmentsPtr;
            RgbaFloat blendFactor = description.BlendState.BlendFactor;

            blendStateCI.blendConstants_0 = blendFactor.R;
            blendStateCI.blendConstants_1 = blendFactor.G;
            blendStateCI.blendConstants_2 = blendFactor.B;
            blendStateCI.blendConstants_3 = blendFactor.A;

            pipelineCI.pColorBlendState = &blendStateCI;

            // Rasterizer State
            RasterizerStateDescription             rsDesc = description.RasterizerState;
            VkPipelineRasterizationStateCreateInfo rsCI   = VkPipelineRasterizationStateCreateInfo.New();

            rsCI.cullMode         = VkFormats.VdToVkCullMode(rsDesc.CullMode);
            rsCI.polygonMode      = VkFormats.VdToVkPolygonMode(rsDesc.FillMode);
            rsCI.depthClampEnable = !rsDesc.DepthClipEnabled;
            rsCI.frontFace        = rsDesc.FrontFace == FrontFace.Clockwise ? VkFrontFace.Clockwise : VkFrontFace.CounterClockwise;
            rsCI.lineWidth        = 1f;

            pipelineCI.pRasterizationState = &rsCI;

            ScissorTestEnabled = rsDesc.ScissorTestEnabled;

            // Dynamic State
            VkPipelineDynamicStateCreateInfo dynamicStateCI = VkPipelineDynamicStateCreateInfo.New();
            VkDynamicState *dynamicStates = stackalloc VkDynamicState[2];

            dynamicStates[0] = VkDynamicState.Viewport;
            dynamicStates[1] = VkDynamicState.Scissor;
            dynamicStateCI.dynamicStateCount = 2;
            dynamicStateCI.pDynamicStates    = dynamicStates;

            pipelineCI.pDynamicState = &dynamicStateCI;

            // Depth Stencil State
            DepthStencilStateDescription          vdDssDesc = description.DepthStencilState;
            VkPipelineDepthStencilStateCreateInfo dssCI     = VkPipelineDepthStencilStateCreateInfo.New();

            dssCI.depthWriteEnable  = vdDssDesc.DepthWriteEnabled;
            dssCI.depthTestEnable   = vdDssDesc.DepthTestEnabled;
            dssCI.depthCompareOp    = VkFormats.VdToVkCompareOp(vdDssDesc.DepthComparison);
            dssCI.stencilTestEnable = vdDssDesc.StencilTestEnabled;

            dssCI.front.failOp      = VkFormats.VdToVkStencilOp(vdDssDesc.StencilFront.Fail);
            dssCI.front.passOp      = VkFormats.VdToVkStencilOp(vdDssDesc.StencilFront.Pass);
            dssCI.front.depthFailOp = VkFormats.VdToVkStencilOp(vdDssDesc.StencilFront.DepthFail);
            dssCI.front.compareMask = vdDssDesc.StencilReadMask;
            dssCI.front.writeMask   = vdDssDesc.StencilWriteMask;
            dssCI.front.reference   = vdDssDesc.StencilReference;

            dssCI.back.failOp      = VkFormats.VdToVkStencilOp(vdDssDesc.StencilBack.Fail);
            dssCI.back.passOp      = VkFormats.VdToVkStencilOp(vdDssDesc.StencilBack.Pass);
            dssCI.back.depthFailOp = VkFormats.VdToVkStencilOp(vdDssDesc.StencilBack.DepthFail);
            dssCI.back.compareMask = vdDssDesc.StencilReadMask;
            dssCI.back.writeMask   = vdDssDesc.StencilWriteMask;
            dssCI.back.reference   = vdDssDesc.StencilReference;

            pipelineCI.pDepthStencilState = &dssCI;

            // Multisample
            VkPipelineMultisampleStateCreateInfo multisampleCI = VkPipelineMultisampleStateCreateInfo.New();
            VkSampleCountFlags vkSampleCount = VkFormats.VdToVkSampleCount(description.Outputs.SampleCount);

            multisampleCI.rasterizationSamples = vkSampleCount;

            pipelineCI.pMultisampleState = &multisampleCI;

            // Input Assembly
            VkPipelineInputAssemblyStateCreateInfo inputAssemblyCI = VkPipelineInputAssemblyStateCreateInfo.New();

            inputAssemblyCI.topology = VkFormats.VdToVkPrimitiveTopology(description.PrimitiveTopology);

            pipelineCI.pInputAssemblyState = &inputAssemblyCI;

            // Vertex Input State
            VkPipelineVertexInputStateCreateInfo vertexInputCI = VkPipelineVertexInputStateCreateInfo.New();

            VertexLayoutDescription[] inputDescriptions = description.ShaderSet.VertexLayouts;
            uint bindingCount   = (uint)inputDescriptions.Length;
            uint attributeCount = 0;

            for (int i = 0; i < inputDescriptions.Length; i++)
            {
                attributeCount += (uint)inputDescriptions[i].Elements.Length;
            }
            VkVertexInputBindingDescription *  bindingDescs   = stackalloc VkVertexInputBindingDescription[(int)bindingCount];
            VkVertexInputAttributeDescription *attributeDescs = stackalloc VkVertexInputAttributeDescription[(int)attributeCount];

            int targetIndex    = 0;
            int targetLocation = 0;

            for (int binding = 0; binding < inputDescriptions.Length; binding++)
            {
                VertexLayoutDescription inputDesc = inputDescriptions[binding];
                bindingDescs[binding] = new VkVertexInputBindingDescription()
                {
                    binding   = (uint)binding,
                    inputRate = (inputDesc.InstanceStepRate != 0) ? VkVertexInputRate.Instance : VkVertexInputRate.Vertex,
                    stride    = inputDesc.Stride
                };

                uint currentOffset = 0;
                for (int location = 0; location < inputDesc.Elements.Length; location++)
                {
                    VertexElementDescription inputElement = inputDesc.Elements[location];

                    attributeDescs[targetIndex] = new VkVertexInputAttributeDescription()
                    {
                        format   = VkFormats.VdToVkVertexElementFormat(inputElement.Format),
                        binding  = (uint)binding,
                        location = (uint)(targetLocation + location),
                        offset   = inputElement.Offset != 0 ? inputElement.Offset : currentOffset
                    };

                    targetIndex   += 1;
                    currentOffset += FormatHelpers.GetSizeInBytes(inputElement.Format);
                }

                targetLocation += inputDesc.Elements.Length;
            }

            vertexInputCI.vertexBindingDescriptionCount   = bindingCount;
            vertexInputCI.pVertexBindingDescriptions      = bindingDescs;
            vertexInputCI.vertexAttributeDescriptionCount = attributeCount;
            vertexInputCI.pVertexAttributeDescriptions    = attributeDescs;

            pipelineCI.pVertexInputState = &vertexInputCI;

            // Shader Stage

            VkSpecializationInfo specializationInfo;

            SpecializationConstant[] specDescs = description.ShaderSet.Specializations;
            if (specDescs != null)
            {
                uint specDataSize = 0;
                foreach (SpecializationConstant spec in specDescs)
                {
                    specDataSize += VkFormats.GetSpecializationConstantSize(spec.Type);
                }
                byte *fullSpecData                   = stackalloc byte[(int)specDataSize];
                int   specializationCount            = specDescs.Length;
                VkSpecializationMapEntry *mapEntries = stackalloc VkSpecializationMapEntry[specializationCount];
                uint specOffset = 0;
                for (int i = 0; i < specializationCount; i++)
                {
                    ulong data     = specDescs[i].Data;
                    byte *srcData  = (byte *)&data;
                    uint  dataSize = VkFormats.GetSpecializationConstantSize(specDescs[i].Type);
                    Unsafe.CopyBlock(fullSpecData + specOffset, srcData, dataSize);
                    mapEntries[i].constantID = specDescs[i].ID;
                    mapEntries[i].offset     = specOffset;
                    mapEntries[i].size       = (UIntPtr)dataSize;
                    specOffset += dataSize;
                }
                specializationInfo.dataSize      = (UIntPtr)specDataSize;
                specializationInfo.pData         = fullSpecData;
                specializationInfo.mapEntryCount = (uint)specializationCount;
                specializationInfo.pMapEntries   = mapEntries;
            }

            Shader[] shaders = description.ShaderSet.Shaders;
            StackList <VkPipelineShaderStageCreateInfo> stages = new StackList <VkPipelineShaderStageCreateInfo>();

            foreach (Shader shader in shaders)
            {
                VkShader vkShader = Util.AssertSubtype <Shader, VkShader>(shader);
                VkPipelineShaderStageCreateInfo stageCI = VkPipelineShaderStageCreateInfo.New();
                stageCI.module = vkShader.ShaderModule;
                stageCI.stage  = VkFormats.VdToVkShaderStages(shader.Stage);
                // stageCI.pName = CommonStrings.main; // Meh
                stageCI.pName = new FixedUtf8String(shader.EntryPoint); // TODO: DONT ALLOCATE HERE
                stageCI.pSpecializationInfo = &specializationInfo;
                stages.Add(stageCI);
            }

            pipelineCI.stageCount = stages.Count;
            pipelineCI.pStages    = (VkPipelineShaderStageCreateInfo *)stages.Data;

            // ViewportState
            VkPipelineViewportStateCreateInfo viewportStateCI = VkPipelineViewportStateCreateInfo.New();

            viewportStateCI.viewportCount = 1;
            viewportStateCI.scissorCount  = 1;

            pipelineCI.pViewportState = &viewportStateCI;

            // Pipeline Layout
            ResourceLayout[]           resourceLayouts  = description.ResourceLayouts;
            VkPipelineLayoutCreateInfo pipelineLayoutCI = VkPipelineLayoutCreateInfo.New();

            pipelineLayoutCI.setLayoutCount = (uint)resourceLayouts.Length;
            VkDescriptorSetLayout *dsls = stackalloc VkDescriptorSetLayout[resourceLayouts.Length];

            for (int i = 0; i < resourceLayouts.Length; i++)
            {
                dsls[i] = Util.AssertSubtype <ResourceLayout, VkResourceLayout>(resourceLayouts[i]).DescriptorSetLayout;
            }
            pipelineLayoutCI.pSetLayouts = dsls;

            vkCreatePipelineLayout(_gd.Device, ref pipelineLayoutCI, null, out _pipelineLayout);
            pipelineCI.layout = _pipelineLayout;

            // Create fake RenderPass for compatibility.

            VkRenderPassCreateInfo renderPassCI = VkRenderPassCreateInfo.New();
            OutputDescription      outputDesc   = description.Outputs;
            StackList <VkAttachmentDescription, Size512Bytes> attachments = new StackList <VkAttachmentDescription, Size512Bytes>();

            // TODO: A huge portion of this next part is duplicated in VkFramebuffer.cs.

            StackList <VkAttachmentDescription> colorAttachmentDescs = new StackList <VkAttachmentDescription>();
            StackList <VkAttachmentReference>   colorAttachmentRefs  = new StackList <VkAttachmentReference>();

            for (uint i = 0; i < outputDesc.ColorAttachments.Length; i++)
            {
                colorAttachmentDescs[i].format         = VkFormats.VdToVkPixelFormat(outputDesc.ColorAttachments[i].Format);
                colorAttachmentDescs[i].samples        = vkSampleCount;
                colorAttachmentDescs[i].loadOp         = VkAttachmentLoadOp.DontCare;
                colorAttachmentDescs[i].storeOp        = VkAttachmentStoreOp.Store;
                colorAttachmentDescs[i].stencilLoadOp  = VkAttachmentLoadOp.DontCare;
                colorAttachmentDescs[i].stencilStoreOp = VkAttachmentStoreOp.DontCare;
                colorAttachmentDescs[i].initialLayout  = VkImageLayout.Undefined;
                colorAttachmentDescs[i].finalLayout    = VkImageLayout.ShaderReadOnlyOptimal;
                attachments.Add(colorAttachmentDescs[i]);

                colorAttachmentRefs[i].attachment = i;
                colorAttachmentRefs[i].layout     = VkImageLayout.ColorAttachmentOptimal;
            }

            VkAttachmentDescription depthAttachmentDesc = new VkAttachmentDescription();
            VkAttachmentReference   depthAttachmentRef  = new VkAttachmentReference();

            if (outputDesc.DepthAttachment != null)
            {
                PixelFormat depthFormat = outputDesc.DepthAttachment.Value.Format;
                bool        hasStencil  = FormatHelpers.IsStencilFormat(depthFormat);
                depthAttachmentDesc.format         = VkFormats.VdToVkPixelFormat(outputDesc.DepthAttachment.Value.Format, toDepthFormat: true);
                depthAttachmentDesc.samples        = vkSampleCount;
                depthAttachmentDesc.loadOp         = VkAttachmentLoadOp.DontCare;
                depthAttachmentDesc.storeOp        = VkAttachmentStoreOp.Store;
                depthAttachmentDesc.stencilLoadOp  = VkAttachmentLoadOp.DontCare;
                depthAttachmentDesc.stencilStoreOp = hasStencil ? VkAttachmentStoreOp.Store : VkAttachmentStoreOp.DontCare;
                depthAttachmentDesc.initialLayout  = VkImageLayout.Undefined;
                depthAttachmentDesc.finalLayout    = VkImageLayout.DepthStencilAttachmentOptimal;

                depthAttachmentRef.attachment = (uint)outputDesc.ColorAttachments.Length;
                depthAttachmentRef.layout     = VkImageLayout.DepthStencilAttachmentOptimal;
            }

            VkSubpassDescription subpass = new VkSubpassDescription();

            subpass.pipelineBindPoint    = VkPipelineBindPoint.Graphics;
            subpass.colorAttachmentCount = (uint)outputDesc.ColorAttachments.Length;
            subpass.pColorAttachments    = (VkAttachmentReference *)colorAttachmentRefs.Data;
            for (int i = 0; i < colorAttachmentDescs.Count; i++)
            {
                attachments.Add(colorAttachmentDescs[i]);
            }

            if (outputDesc.DepthAttachment != null)
            {
                subpass.pDepthStencilAttachment = &depthAttachmentRef;
                attachments.Add(depthAttachmentDesc);
            }

            VkSubpassDependency subpassDependency = new VkSubpassDependency();

            subpassDependency.srcSubpass    = SubpassExternal;
            subpassDependency.srcStageMask  = VkPipelineStageFlags.ColorAttachmentOutput;
            subpassDependency.dstStageMask  = VkPipelineStageFlags.ColorAttachmentOutput;
            subpassDependency.dstAccessMask = VkAccessFlags.ColorAttachmentRead | VkAccessFlags.ColorAttachmentWrite;

            renderPassCI.attachmentCount = attachments.Count;
            renderPassCI.pAttachments    = (VkAttachmentDescription *)attachments.Data;
            renderPassCI.subpassCount    = 1;
            renderPassCI.pSubpasses      = &subpass;
            renderPassCI.dependencyCount = 1;
            renderPassCI.pDependencies   = &subpassDependency;

            VkResult creationResult = vkCreateRenderPass(_gd.Device, ref renderPassCI, null, out _renderPass);

            CheckResult(creationResult);

            pipelineCI.renderPass = _renderPass;

            VkResult result = vkCreateGraphicsPipelines(_gd.Device, VkPipelineCache.Null, 1, ref pipelineCI, null, out _devicePipeline);

            CheckResult(result);

            ResourceSetCount    = (uint)description.ResourceLayouts.Length;
            DynamicOffsetsCount = 0;
            foreach (VkResourceLayout layout in ResourceLayouts)
            {
                DynamicOffsetsCount += layout.DynamicBufferCount;
            }
        }
示例#52
0
        public Bitmap Convert(PixelFormat format, bool discardAlpha = false)
        {
            BitmapInstance instance = Instance.Convert(format, discardAlpha);

            return(new Bitmap(instance));
        }
        public bool GetThumbnail(Stream stream, int width, int height, bool cachedOnly, out byte[] imageData, out ImageType imageType)
        {
            imageData = null;
            imageType = ImageType.Unknown;
            // No support for cache
            if (cachedOnly)
            {
                return(false);
            }

            Bitmap cachedBitmap = null; // used only for rotation

            try
            {
                if (stream.CanSeek)
                {
                    stream.Seek(0, SeekOrigin.Begin);
                }

                // open the image file for reading
                using (var factory = new ImagingFactory2())
                    using (var inputStream = new WICStream(factory, stream))
                        using (var decoder = new BitmapDecoder(factory, inputStream, DecodeOptions.CacheOnLoad))
                            using (var rotator = new BitmapFlipRotator(factory))
                                using (var scaler = new BitmapScaler(factory))
                                    using (var output = new MemoryStream())
                                    {
                                        // decode the loaded image to a format that can be consumed by D2D
                                        BitmapSource source = decoder.GetFrame(0);

                                        // Prefer PNG output for source PNG and for source formats with Alpha channel
                                        var usePngOutput = decoder.DecoderInfo.FriendlyName.StartsWith("PNG") || PixelFormat.GetBitsPerPixel(source.PixelFormat) == 32;

                                        BitmapTransformOptions bitmapTransformationOptions = BitmapTransformOptions.Rotate0;
                                        BitmapFrameDecode      frame = source as BitmapFrameDecode;
                                        if (frame != null)
                                        {
                                            const string EXIF_ORIENTATION_TAG = "/app1/{ushort=0}/{ushort=274}";
                                            ushort?      orientation          = null;
                                            try
                                            {
                                                // Not supported on all input types, i.e. BMP will fail here
                                                orientation = (ushort?)frame.MetadataQueryReader.TryGetMetadataByName(EXIF_ORIENTATION_TAG); //0x0112
                                            }
                                            catch { }

                                            // If the EXIF orientation specifies that the image needs to be flipped or rotated before display, set that up to happen
                                            if (orientation.HasValue)
                                            {
                                                switch (orientation.Value)
                                                {
                                                case 1: break; // No rotation required.

                                                case 2: bitmapTransformationOptions = BitmapTransformOptions.Rotate0 | BitmapTransformOptions.FlipHorizontal; break;

                                                case 3: bitmapTransformationOptions = BitmapTransformOptions.Rotate180; break;

                                                case 4: bitmapTransformationOptions = BitmapTransformOptions.Rotate180 | BitmapTransformOptions.FlipHorizontal; break;

                                                case 5: bitmapTransformationOptions = BitmapTransformOptions.Rotate270 | BitmapTransformOptions.FlipHorizontal; break;

                                                case 6: bitmapTransformationOptions = BitmapTransformOptions.Rotate90; break;

                                                case 7: bitmapTransformationOptions = BitmapTransformOptions.Rotate90 | BitmapTransformOptions.FlipHorizontal; break;

                                                case 8: bitmapTransformationOptions = BitmapTransformOptions.Rotate270; break;
                                                }
                                            }
                                        }

                                        // Scale down larger images
                                        int sourceWidth  = source.Size.Width;
                                        int sourceHeight = source.Size.Height;
                                        if (width > 0 && height > 0 && (sourceWidth > width || sourceHeight > height))
                                        {
                                            if (sourceWidth <= height)
                                            {
                                                width = sourceWidth;
                                            }

                                            int newHeight = sourceHeight * height / sourceWidth;
                                            if (newHeight > height)
                                            {
                                                // Resize with height instead
                                                width     = sourceWidth * height / sourceHeight;
                                                newHeight = height;
                                            }

                                            scaler.Initialize(source, width, newHeight, BitmapInterpolationMode.Fant);
                                            source = scaler;
                                        }

                                        // Rotate
                                        if (bitmapTransformationOptions != BitmapTransformOptions.Rotate0)
                                        {
                                            // For fast rotation a cached bitmap is needed, otherwise only per-pixel-decoding happens which makes the process extremly slow.
                                            // See https://social.msdn.microsoft.com/Forums/windowsdesktop/en-US/5ff2b52b-602f-4b22-9fb2-371539ff5ebb/hang-in-createbitmapfromwicbitmap-when-using-iwicbitmapfliprotator?forum=windowswic
                                            cachedBitmap = new Bitmap(factory, source, BitmapCreateCacheOption.CacheOnLoad);
                                            rotator.Initialize(cachedBitmap, bitmapTransformationOptions);
                                            source = rotator;
                                        }

                                        Guid formatGuid = ContainerFormatGuids.Jpeg;
                                        imageType = ImageType.Jpeg;

                                        if (usePngOutput)
                                        {
                                            formatGuid = ContainerFormatGuids.Png;
                                            imageType  = ImageType.Png;
                                        }

                                        using (var encoder = new BitmapEncoder(factory, formatGuid))
                                        {
                                            encoder.Initialize(output);
                                            using (var bitmapFrameEncode = new BitmapFrameEncode(encoder))
                                            {
                                                // Create image encoder
                                                var wicPixelFormat = PixelFormat.FormatDontCare;
                                                bitmapFrameEncode.Initialize();
                                                bitmapFrameEncode.SetSize(source.Size.Width, source.Size.Height);
                                                bitmapFrameEncode.SetPixelFormat(ref wicPixelFormat);
                                                bitmapFrameEncode.WriteSource(source);
                                                bitmapFrameEncode.Commit();
                                                encoder.Commit();
                                            }
                                        }
                                        imageData = output.ToArray();
                                        return(true);
                                    }
            }
            catch (Exception)
            {
                //ServiceRegistration.Get<ILogger>().Warn("WICThumbnailProvider: Error loading bitmapSource from file data stream", ex);
                return(false);
            }
            finally
            {
                cachedBitmap?.Dispose();
            }
        }
示例#54
0
        public static Texture New2D <T>(GraphicsDevice device, Span <T> data, int width, int height, PixelFormat format, ResourceFlags textureFlags = ResourceFlags.ShaderResource, short mipLevels = 1, short arraySize = 1, int sampleCount = 1, int sampleQuality = 0, GraphicsHeapType heapType = GraphicsHeapType.Default) where T : unmanaged
        {
            Texture texture = New2D(device, width, height, format, textureFlags, mipLevels, arraySize, sampleCount, sampleQuality, heapType);

            texture.SetData(data);

            return(texture);
        }
 public ImageExportSettings(string path, string name, string extension, bool floor, bool fullbright, bool brightmap, bool tiles, float scale, PixelFormat pformat, ImageFormat iformat)
 {
     Path        = path;
     Name        = name;
     Extension   = extension;
     Floor       = floor;
     Brightmap   = brightmap;
     Tiles       = tiles;
     Fullbright  = fullbright;
     PixelFormat = pformat;
     ImageFormat = iformat;
     Scale       = scale;
 }
示例#56
0
 internal static extern void Internal_ResolveMultisample(IntPtr obj, IntPtr sourceMultisampleTexture, IntPtr destTexture, int sourceSubResource, int destSubResource, PixelFormat format);
示例#57
0
 public Bitmap(int width, int height, byte[] buffer, PixelFormat format, Palette?palette = null)
 {
     Instance = BitmapInstance.Create(width, height, buffer, format, palette);
 }
示例#58
0
 /// <summary>
 /// Factory for creating a FastBitmap as a destination for the source
 /// </summary>
 /// <param name="source">Bitmap to clone</param>
 /// <param name="pixelFormat">new Pixelformat</param>
 /// <returns>IFastBitmap</returns>
 public static IFastBitmap CreateCloneOf(Image source, PixelFormat pixelFormat)
 {
     return(CreateCloneOf(source, pixelFormat, Rectangle.Empty));
 }
示例#59
0
 public static Texture New2D(GraphicsDevice device, int width, int height, PixelFormat format, ResourceFlags textureFlags = ResourceFlags.ShaderResource, short mipLevels = 1, short arraySize = 1, int sampleCount = 1, int sampleQuality = 0, GraphicsHeapType heapType = GraphicsHeapType.Default)
 {
     return(New(device, TextureDescription.New2D(width, height, format, textureFlags, mipLevels, arraySize, sampleCount, sampleQuality, heapType)));
 }
 protected AbstractSampleGrabbingParticipant(short bitCount, int width, int height, bool flipImages)
 {
     _format = MediaTypeTools.GetPixelFormatForBitCount(bitCount);
     _width = width;
     _height = height;
     _flipImages = flipImages;
 }