public static SharpDX.Direct2D1.Bitmap LoadBitmapFromResourceName(this RenderTarget renderTarget, string resourceName)
        {
            System.Drawing.Bitmap bitmap2;
            System.Drawing.Bitmap image = new System.Drawing.Bitmap(typeof(MusicCanvasControl), resourceName);
            if (image.PixelFormat != System.Drawing.Imaging.PixelFormat.Format32bppPArgb)
            {
                bitmap2 = new System.Drawing.Bitmap(image.Width, image.Height, System.Drawing.Imaging.PixelFormat.Format32bppPArgb);
                using (Graphics graphics = Graphics.FromImage(bitmap2))
                {
                    graphics.DrawImage(image, 0, 0, image.Width, image.Height);
                }
            }
            else
            {
                bitmap2 = image;
            }
            BitmapData bitmapdata = bitmap2.LockBits(new Rectangle(0, 0, bitmap2.Width, bitmap2.Height), ImageLockMode.ReadOnly, bitmap2.PixelFormat);
            int        length     = bitmapdata.Stride * bitmap2.Height;

            byte[] destination = new byte[length];
            Marshal.Copy(bitmapdata.Scan0, destination, 0, length);
            bitmap2.UnlockBits(bitmapdata);
            SharpDX.Direct2D1.PixelFormat pixelFormat = new SharpDX.Direct2D1.PixelFormat(Format.B8G8R8A8_UNorm, SharpDX.Direct2D1.AlphaMode.Premultiplied);
            BitmapProperties bitmapProperties         = new BitmapProperties(pixelFormat, bitmap2.HorizontalResolution, bitmap2.VerticalResolution);

            SharpDX.Direct2D1.Bitmap bitmap3 = new SharpDX.Direct2D1.Bitmap(renderTarget, new Size2(bitmap2.Width, bitmap2.Height), bitmapProperties);
            bitmap3.CopyFromMemory(destination, bitmapdata.Stride);
            bitmap2.Dispose();
            image.Dispose();
            return(bitmap3);
        }
Example #2
0
        public Bitmap ConvertBitmap(System.Drawing.Bitmap bmp)
        {
            System.Drawing.Imaging.BitmapData bmpData =
                bmp.LockBits(
                    new System.Drawing.Rectangle(0, 0, bmp.Width, bmp.Height),
                    System.Drawing.Imaging.ImageLockMode.ReadOnly,
                    System.Drawing.Imaging.PixelFormat.Format32bppPArgb);

            DataStream       stream   = new DataStream(bmpData.Scan0, bmpData.Stride * bmpData.Height, true, false);
            PixelFormat      pFormat  = new PixelFormat(Format.B8G8R8A8_UNorm, AlphaMode.Premultiplied);
            BitmapProperties bmpProps = new BitmapProperties(pFormat);

            Bitmap result =
                new Bitmap(
                    renderTarget,
                    new Size2(bmp.Width, bmp.Height),
                    stream,
                    bmpData.Stride,
                    bmpProps);

            bmp.UnlockBits(bmpData);

            stream.Dispose();
            bmp.Dispose();

            return(result);
        }
Example #3
0
    public void Init(Window window)
    {
        var factory = new D2D.Factory();

        var pixelFormat = new D2D.PixelFormat(DXGI.Format.B8G8R8A8_UNorm, D2D.AlphaMode.Ignore);

        var renderTargetProperties = new D2D.RenderTargetProperties
                                     (
            // 默认的行为就是尝试使用硬件优先,否则再使用软件
            D2D.RenderTargetType.Default,
            // 像素格式,对于当前大多数显卡来说,选择 B8G8R8A8 是完全能支持的
            // 而且也方便和其他框架,如 WPF 交互
            pixelFormat,
            dpiX: 96,
            dpiY: 96,
            D2D.RenderTargetUsage.None,
            D2D.FeatureLevel.Level_DEFAULT
                                     );
        var hwndRenderTargetProperties = new D2D.HwndRenderTargetProperties();

        hwndRenderTargetProperties.Hwnd      = new WindowInteropHelper(window).Handle;
        hwndRenderTargetProperties.PixelSize = new Size2((int)window.ActualWidth, (int)window.ActualHeight);

        var renderTarget = new D2D.WindowRenderTarget(factory, renderTargetProperties, hwndRenderTargetProperties);
    }
        public Direct2DEditorSession(int Width, int Height, IPreviewWindow PreviewWindow)
        {
            _previewWindow = PreviewWindow;

            try
            {
                Device = new Device(DriverType.Hardware,
                                    DeviceCreationFlags.BgraSupport);
            }
            catch (SharpDXException)
            {
                Device = new Device(DriverType.Warp,
                                    DeviceCreationFlags.BgraSupport);
            }

            StagingTexture = new Texture2D(Device, new Texture2DDescription
            {
                CpuAccessFlags    = CpuAccessFlags.Read,
                BindFlags         = BindFlags.None,
                Format            = Format.B8G8R8A8_UNorm,
                Width             = Width,
                Height            = Height,
                OptionFlags       = ResourceOptionFlags.None,
                MipLevels         = 1,
                ArraySize         = 1,
                SampleDescription = { Count = 1, Quality = 0 },
                Usage             = ResourceUsage.Staging
            });

            DesktopTexture = new Texture2D(Device, new Texture2DDescription
            {
                CpuAccessFlags    = CpuAccessFlags.None,
                BindFlags         = BindFlags.RenderTarget | BindFlags.ShaderResource,
                Format            = Format.B8G8R8A8_UNorm,
                Width             = Width,
                Height            = Height,
                OptionFlags       = ResourceOptionFlags.None,
                MipLevels         = 1,
                ArraySize         = 1,
                SampleDescription = { Count = 1, Quality = 0 },
                Usage             = ResourceUsage.Default
            });

            var desc = DesktopTexture.Description;

            desc.OptionFlags = ResourceOptionFlags.Shared;

            PreviewTexture = new Texture2D(Device, desc);

            _factory = new Factory1(FactoryType.MultiThreaded);

            var pixelFormat = new PixelFormat(Format.Unknown, AlphaMode.Ignore);

            var renderTargetProps = new RenderTargetProperties(pixelFormat);

            using (var surface = DesktopTexture.QueryInterface <Surface>())
            {
                RenderTarget = new RenderTarget(_factory, surface, renderTargetProps);
            }
        }
Example #5
0
        public Direct2DEditorSession(Texture2D Texture, Device Device, Texture2D StagingTexture)
        {
            _texture            = Texture;
            this.Device         = Device;
            this.StagingTexture = StagingTexture;

            var desc = Texture.Description;

            desc.OptionFlags = ResourceOptionFlags.Shared;

            PreviewTexture = new Texture2D(Device, desc);

            _factory = new Factory1(FactoryType.MultiThreaded);

            var pixelFormat = new PixelFormat(Format.Unknown, AlphaMode.Ignore);

            var renderTargetProps = new RenderTargetProperties(pixelFormat)
            {
                Type = RenderTargetType.Hardware
            };

            using (var surface = Texture.QueryInterface <Surface>())
            {
                RenderTarget = new RenderTarget(_factory, surface, renderTargetProps);
            }
        }
Example #6
0
 /// <summary>
 /// Initializes a new instance of the <see cref="BitmapProperties1"/> class.
 /// </summary>
 /// <param name="pixelFormat">The pixel format.</param>
 /// <param name="dpiX">The dpi X.</param>
 /// <param name="dpiY">The dpi Y.</param>
 /// <param name="bitmapOptions">The bitmap options.</param>
 /// <param name="colorContext">The color context.</param>
 public BitmapProperties1(PixelFormat pixelFormat, float dpiX, float dpiY, BitmapOptions bitmapOptions, ColorContext colorContext)
 {
     PixelFormat = pixelFormat;
     DpiX = dpiX;
     DpiY = dpiY;
     BitmapOptions = bitmapOptions;
     ColorContext = colorContext;
 }
Example #7
0
        private static RenderTargetProperties GetRenderTargetProperties()
        {
            PixelFormat format = new PixelFormat(Format.Unknown, AlphaMode.Premultiplied);

            return(new RenderTargetProperties(format)
            {
                MinLevel = SharpDX.Direct2D1.FeatureLevel.Level_10,
            });
        }
Example #8
0
        public Bitmap CreateBitmapFromResource(string name)
        {
            var assembly = Assembly.GetExecutingAssembly();

            bool needsScaling = false;

            System.Drawing.Bitmap bmp;

            if (Direct2DTheme.MainWindowScaling == 1.5f && assembly.GetManifestResourceInfo($"FamiStudio.Resources.{name}@15x.png") != null)
            {
                bmp = System.Drawing.Image.FromStream(assembly.GetManifestResourceStream($"FamiStudio.Resources.{name}@15x.png")) as System.Drawing.Bitmap;
            }
            else if (Direct2DTheme.MainWindowScaling > 1.0f && assembly.GetManifestResourceInfo($"FamiStudio.Resources.{name}@2x.png") != null)
            {
                bmp          = System.Drawing.Image.FromStream(assembly.GetManifestResourceStream($"FamiStudio.Resources.{name}@2x.png")) as System.Drawing.Bitmap;
                needsScaling = Direct2DTheme.MainWindowScaling != 2.0f;
            }
            else
            {
                bmp = System.Drawing.Image.FromStream(assembly.GetManifestResourceStream($"FamiStudio.Resources.{name}.png")) as System.Drawing.Bitmap;
            }

            // Pre-resize all images so we dont have to deal with scaling later.
            if (needsScaling)
            {
                var newWidth  = (int)(bmp.Width * (Direct2DTheme.MainWindowScaling / 2.0f));
                var newHeight = (int)(bmp.Height * (Direct2DTheme.MainWindowScaling / 2.0f));

                bmp = new System.Drawing.Bitmap(bmp, newWidth, newHeight);
            }

            var bmpData =
                bmp.LockBits(
                    new System.Drawing.Rectangle(0, 0, bmp.Width, bmp.Height),
                    System.Drawing.Imaging.ImageLockMode.ReadOnly,
                    System.Drawing.Imaging.PixelFormat.Format32bppPArgb);

            var stream   = new DataStream(bmpData.Scan0, bmpData.Stride * bmpData.Height, true, false);
            var pFormat  = new PixelFormat(Format.B8G8R8A8_UNorm, AlphaMode.Premultiplied);
            var bmpProps = new BitmapProperties(pFormat);

            var result =
                new Bitmap(
                    renderTarget,
                    new Size2(bmp.Width, bmp.Height),
                    stream,
                    bmpData.Stride,
                    bmpProps);

            bmp.UnlockBits(bmpData);

            stream.Dispose();
            bmp.Dispose();

            return(result);
        }
        private static Bitmap LoadBitmap(SharpDX.Direct2D1.RenderTarget target, System.Drawing.Bitmap bitmap)
        {
            var format   = new PixelFormat(Format.B8G8R8A8_UNorm, AlphaMode.Premultiplied);
            var bmpProps = new BitmapProperties(format);
            var bmp      = new Bitmap(target, new Size2(bitmap.Width, bitmap.Height), bmpProps);

            var bitmapData = bitmap.LockBits(new System.Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppPArgb);

            bmp.CopyFromMemory(bitmapData.Scan0, bitmapData.Stride);
            bitmap.UnlockBits(bitmapData);

            return(bmp);
        }
Example #10
0
        static public Dot9BitmapD2D CreateDot9BoxShadowBitmap(D2DGraphics g, float cornersRadius, float shadowRadius, System.Drawing.Color shadowColor)
        {
            int width  = (int)(cornersRadius * 2 + shadowRadius * 4 + 2);
            int height = (int)(cornersRadius * 2 + shadowRadius * 4 + 2);

            SharpDX.Direct2D1.PixelFormat format = new SharpDX.Direct2D1.PixelFormat(SharpDX.DXGI.Format.B8G8R8A8_UNorm, AlphaMode.Premultiplied);
            BitmapProperties prop = new BitmapProperties(format);

            SharpDX.Direct2D1.Bitmap bitmap = new SharpDX.Direct2D1.Bitmap(g.RenderTarget, new Size2(width, height), prop);

            unsafe
            {
                System.Drawing.Bitmap     gdibmp = new System.Drawing.Bitmap(width, height);
                System.Drawing.RectangleF rect   = new System.Drawing.RectangleF(shadowRadius, shadowRadius, width - shadowRadius * 2, height - shadowRadius * 2);
                Graphics             gdiGraph    = Graphics.FromImage(gdibmp);
                GraphicsPath         myPath      = DrawUtils.CreateRoundedRectanglePath(rect, cornersRadius);
                System.Drawing.Brush brush       = new SolidBrush(shadowColor);
                gdiGraph.FillPath(brush, myPath);
                brush.Dispose();

                GaussianBlur gs = new GaussianBlur((int)shadowRadius);
                gdibmp = gs.ProcessImage(gdibmp);

                System.Drawing.Rectangle bitmapRect = new System.Drawing.Rectangle(0, 0, gdibmp.Width, gdibmp.Height);
                BitmapData srcBmData = gdibmp.LockBits(bitmapRect, ImageLockMode.ReadWrite, System.Drawing.Imaging.PixelFormat.Format32bppPArgb);
                byte *     ptr       = (byte *)srcBmData.Scan0;
                bitmap.CopyFromMemory((IntPtr)ptr, srcBmData.Stride);
                gdibmp.UnlockBits(srcBmData);

                //  gdibmp.Save("f:\\shadow.png");
                gdibmp.Dispose();
            }



            int[] widthPts = new int[]
            {
                (int)(cornersRadius + shadowRadius * 2 + 1), (int)(width - cornersRadius - shadowRadius * 2 - 1)
            };

            int[] heightPts = new int[]
            {
                (int)(cornersRadius + shadowRadius * 2 + 1), (int)(width - cornersRadius - shadowRadius * 2 - 1)
            };


            Dot9BitmapD2D dot9Bitmap = new Dot9BitmapD2D(bitmap, widthPts, heightPts);

            return(dot9Bitmap);
        }
Example #11
0
 /// <summary>
 /// Initializes a new instance of the <see cref="WriteableBitmapResource"/> class.
 /// </summary>
 public WriteableBitmapResource(
     Size2 bitmapSize,
     BitmapFormat format = BitmapFormat.Bgra,
     AlphaMode alphaMode = AlphaMode.Straight,
     double dpiX         = 96.0, double dpiY = 96.0)
 {
     m_loadedBitmaps = new D2D.Bitmap[GraphicsCore.Current.DeviceCount];
     m_bitmapSize    = bitmapSize;
     m_pixelFormat   = new D2D.PixelFormat(
         (DXGI.Format)format,
         (D2D.AlphaMode)alphaMode);
     m_dpiX = dpiX;
     m_dpiY = dpiY;
 }
Example #12
0
        private void InitDX()
        {
            _d2dFactory = new SharpDX.Direct2D1.Factory(FactoryType.MultiThreaded);
            SharpDX.Direct2D1.PixelFormat p = new SharpDX.Direct2D1.PixelFormat(SharpDX.DXGI.Format.Unknown, SharpDX.Direct2D1.AlphaMode.Premultiplied);

            HwndRenderTargetProperties h = new HwndRenderTargetProperties();

            h.Hwnd           = _picContainer.Handle;
            h.PixelSize      = new Size2(_picContainer.Width, _picContainer.Height);
            h.PresentOptions = SharpDX.Direct2D1.PresentOptions.None;

            RenderTargetProperties r = new RenderTargetProperties(RenderTargetType.Hardware, p, 0, 0, RenderTargetUsage.None, FeatureLevel.Level_DEFAULT);

            _renderTarget = new WindowRenderTarget(_d2dFactory, r, h);
            _imgFactory   = new ImagingFactory();
        }
Example #13
0
        private void OnFormLoad(object sender, EventArgs e)
        {
            if (_osuModel != null)
            {
                LogUtil.LogInfo("Form loads normally.");
            }
            else
            {
                LogUtil.LogError("Form loads without real-time instance.");
                return;
            }

            Paint += OnPaint;
            // Initial settings
            var pixelFormat = new D2D.PixelFormat(DXGI.Format.B8G8R8A8_UNorm, D2D.AlphaMode.Premultiplied);
            var winProp     = new D2D.HwndRenderTargetProperties
            {
                Hwnd           = Handle,
                PixelSize      = new DX.Size2(ClientSize.Width, ClientSize.Height),
                PresentOptions = _useVsync ? D2D.PresentOptions.None : D2D.PresentOptions.Immediately
            };
            var renderProp = new D2D.RenderTargetProperties(D2D.RenderTargetType.Hardware, pixelFormat, 96, 96,
                                                            D2D.RenderTargetUsage.ForceBitmapRemoting, D2D.FeatureLevel.Level_DEFAULT);

            RenderTarget = new D2D.WindowRenderTarget(Factory, renderProp, winProp)
            {
                AntialiasMode     = D2D.AntialiasMode.PerPrimitive,
                TextAntialiasMode = D2D.TextAntialiasMode.Grayscale,
                Transform         = new Mathe.RawMatrix3x2(1, 0, 0, 1, 0, 0)
            };

            LayerList = new List <DxLayer>
            {
                new BgDxLayer(RenderTarget, _obj, _osuModel),
                new SongInfoDxLayer(RenderTarget, _obj, _osuModel),
                new FpsDxLayer(RenderTarget, _obj, _osuModel),
                //new TestLayer(RenderTarget, _obj, _osuModel),
            };

            _renderTask = new Task[LayerList.Count];

            // Avoid artifacts
            SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.Opaque, true);

            Text = "Osu!Live Player (DX)";
            LogUtil.LogInfo("Form loaded.");
        }
Example #14
0
        private void InitializeDirectX(GameWindow gameWindow)
        {
            using (var defaultDevice = new SharpDX.Direct3D11.Device(DriverType.Hardware, DeviceCreationFlags.BgraSupport))
            {
                _d3dDevice = defaultDevice.QueryInterface <SharpDX.Direct3D11.Device1>();
            }

            var swapChainDesc = new SwapChainDescription1()
            {
                Width             = 0,
                Height            = 0,
                Format            = Format.B8G8R8A8_UNorm,
                BufferCount       = 2,
                Usage             = Usage.BackBuffer | Usage.RenderTargetOutput,
                SwapEffect        = SwapEffect.FlipSequential,
                SampleDescription = new SampleDescription(1, 0),
                Scaling           = Scaling.AspectRatioStretch
            };

            using (var dxgiDevice = _d3dDevice.QueryInterface <SharpDX.DXGI.Device2>())
                using (var dxgiFactory = dxgiDevice.Adapter.GetParent <SharpDX.DXGI.Factory2>())
                {
                    var window = new ComObject(gameWindow.WindowObject);
                    _swapChain  = new SwapChain1(dxgiFactory, _d3dDevice, window, ref swapChainDesc);
                    _d2dFactory = new SharpDX.Direct2D1.Factory1();
                    _d2dDevice  = new SharpDX.Direct2D1.Device(_d2dFactory, dxgiDevice);
                }

            _deviceContext = new SharpDX.Direct2D1.DeviceContext(_d2dDevice, new DeviceContextOptions());
            using (var surface = Surface.FromSwapChain(_swapChain, 0))
            {
                var pixelFormat      = new SharpDX.Direct2D1.PixelFormat(Format.Unknown, SharpDX.Direct2D1.AlphaMode.Premultiplied);
                var bitmapProperties = new BitmapProperties1(pixelFormat, 0, 0, BitmapOptions.Target | BitmapOptions.CannotDraw);

                _d2dTargetBitmap      = new SharpDX.Direct2D1.Bitmap1(_deviceContext, surface, bitmapProperties);
                _deviceContext.Target = _d2dTargetBitmap;
            }

            _dwriteFactory   = new SharpDX.DirectWrite.Factory1();
            _wicFactory      = new ImagingFactory();
            _formatConverter = new FormatConverter(_wicFactory);
            _deviceContext.TextAntialiasMode = SharpDX.Direct2D1.TextAntialiasMode.Cleartype;
        }
Example #15
0
        private void Initialize()
        {
            _d2dFactory   = new SharpDX.Direct2D1.Factory1();
            DWriteFactory = new SharpDX.DirectWrite.Factory1();
            WicFactory    = new ImagingFactory2();

            DevicePixelFormat = new SharpDX.Direct2D1.PixelFormat(SharpDX.DXGI.Format.R8G8B8A8_UNorm, AlphaMode.Premultiplied);
            ImagePixelFormat  = SharpDX.WIC.PixelFormat.Format32bppPRGBA;
            using (var defaultDevice = new SharpDX.Direct3D11.Device(DriverType.Hardware, DeviceCreationFlags.BgraSupport))
                using (var d3dDevice = defaultDevice.QueryInterface <SharpDX.Direct3D11.Device1>())
                    using (var dxgiDevice = d3dDevice.QueryInterface <SharpDX.DXGI.Device2>())
                    {
                        _d2dDevice    = new SharpDX.Direct2D1.Device(_d2dFactory, dxgiDevice);
                        DeviceContext = new SharpDX.Direct2D1.DeviceContext(_d2dDevice, new DeviceContextOptions());
                    }

            WicImageEncoder = new ImageEncoder(WicFactory, _d2dDevice);
            DeviceContext.TextAntialiasMode = SharpDX.Direct2D1.TextAntialiasMode.Grayscale;
        }
Example #16
0
        private void LoadTarget(object sender, EventArgs e)
        {
            // Initial settings
            var pixelFormat = new D2D.PixelFormat(DXGI.Format.B8G8R8A8_UNorm, D2D.AlphaMode.Premultiplied);
            var winProp     = new D2D.HwndRenderTargetProperties
            {
                Hwnd           = Handle,
                PixelSize      = new DX.Size2(ClientSize.Width, ClientSize.Height),
                PresentOptions = Program.MainSettings.LimitFps ? D2D.PresentOptions.None : D2D.PresentOptions.Immediately
            };
            var renderProp = new D2D.RenderTargetProperties(D2D.RenderTargetType.Default, pixelFormat, 96, 96,
                                                            D2D.RenderTargetUsage.None, D2D.FeatureLevel.Level_DEFAULT);

            RenderTarget = new D2D.WindowRenderTarget(Factory, renderProp, winProp)
            {
                AntialiasMode     = D2D.AntialiasMode.PerPrimitive,
                TextAntialiasMode = D2D.TextAntialiasMode.Grayscale,
                Transform         = new Mathe.RawMatrix3x2 {
                    M11 = 1f, M12 = 0f, M21 = 0f, M22 = 1f, M31 = 0, M32 = 0
                }
            };

            // Create colors
            _colorBack = new Mathe.RawColor4(0, 0, 0, 1);

            LayerList = new Dictionary <string, ILayer>();
            LayerList.Add("back", new Background());
            if (Program.MainSettings.UseParticle)
            {
                LayerList.Add("particle", new Particle(500));
            }
            LayerList.Add("chess", new Chessboard());

            // Create brushes
            _whiteBrush = new D2D.SolidColorBrush(RenderTarget, new Mathe.RawColor4(1, 1, 1, 1));

            // Create text formats
            _textFormat = new DW.TextFormat(FactoryWrite, "Microsoft YaHei", 12);

            // Avoid artifacts
            SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.Opaque, true);
        }
Example #17
0
        public HwndRenderBase(Control control)
        {
            var hwndProp = new D2D.HwndRenderTargetProperties
            {
                Hwnd           = control.Handle,
                PixelSize      = new DX.Size2(control.ClientSize.Width, control.ClientSize.Height),
                PresentOptions = Vsync ? D2D.PresentOptions.None : D2D.PresentOptions.Immediately
            };

            var pixelFormat = new D2D.PixelFormat(DXGI.Format.B8G8R8A8_UNorm, D2D.AlphaMode.Premultiplied);
            var renderProp  = new D2D.RenderTargetProperties(D2D.RenderTargetType.Hardware, pixelFormat, 96, 96,
                                                             D2D.RenderTargetUsage.ForceBitmapRemoting, D2D.FeatureLevel.Level_DEFAULT);

            RenderTarget = new D2D.WindowRenderTarget(Factory, renderProp, hwndProp)
            {
                AntialiasMode     = D2D.AntialiasMode.Aliased,
                TextAntialiasMode = D2D.TextAntialiasMode.Default,
                Transform         = new Mathe.RawMatrix3x2(1, 0, 0, 1, 0, 0)
            };
        }
Example #18
0
        public DXBitmapExportContext(int width, int height, float displayScale = 1, int dpi = 72, bool disposeBitmap = true)
            : base(width, height, dpi)
        {
            _disposeBitmap = disposeBitmap;

            if (_default3DDevice == null)
            {
                _default3DDevice = new d3d.Device(DriverType.Hardware, d3d.DeviceCreationFlags.VideoSupport | d3d.DeviceCreationFlags.BgraSupport);
                // default3DDevice = new d3d.Device(DriverType.Warp,  d3d.DeviceCreationFlags.BgraSupport);

                _default3DDevice1 = _default3DDevice.QueryInterface <d3d.Device1>();
                _dxgiDevice       = _default3DDevice1.QueryInterface <dxgi.Device>(); // get a reference to DXGI device

                _device2D = new d2.Device(_dxgiDevice);

                // initialize the DeviceContext - it will be the D2D render target
                _deviceContext = new d2.DeviceContext(_device2D, d2.DeviceContextOptions.None);
            }

            // specify a pixel format that is supported by both and WIC
            _pixelFormat = new d2.PixelFormat(dxgi.Format.B8G8R8A8_UNorm, d2.AlphaMode.Premultiplied);

            // create the d2d bitmap description using default flags
            var bitmapProps = new d2.BitmapProperties1(_pixelFormat, Dpi, Dpi,
                                                       d2.BitmapOptions.Target | d2.BitmapOptions.CannotDraw);

            // create our d2d bitmap where all drawing will happen
            _bitmap = new d2.Bitmap1(_deviceContext, new Size2(width, height), bitmapProps);

            // associate bitmap with the d2d context
            _deviceContext.Target = _bitmap;
            _deviceContext.BeginDraw();
            _deviceContext.Clear(new Color4 {
                Alpha = 0, Blue = 0, Green = 0, Red = 0
            });

            _canvas = new DXCanvas(_deviceContext)
            {
                DisplayScale = displayScale
            };
        }
Example #19
0
        public Bitmap CreateBitmapFromResource(string name)
        {
            string suffix   = Direct2DTheme.MainWindowScaling > 1 ? "@2x" : "";
            var    assembly = Assembly.GetExecutingAssembly();

            System.Drawing.Bitmap bmp;

            if (assembly.GetManifestResourceInfo($"FamiStudio.Resources.{name}{suffix}.png") != null)
            {
                bmp = System.Drawing.Image.FromStream(assembly.GetManifestResourceStream($"FamiStudio.Resources.{name}{suffix}.png")) as System.Drawing.Bitmap;
            }
            else
            {
                bmp = System.Drawing.Image.FromStream(assembly.GetManifestResourceStream($"FamiStudio.Resources.{name}.png")) as System.Drawing.Bitmap;
            }

            var bmpData =
                bmp.LockBits(
                    new System.Drawing.Rectangle(0, 0, bmp.Width, bmp.Height),
                    System.Drawing.Imaging.ImageLockMode.ReadOnly,
                    System.Drawing.Imaging.PixelFormat.Format32bppPArgb);

            var stream   = new DataStream(bmpData.Scan0, bmpData.Stride * bmpData.Height, true, false);
            var pFormat  = new PixelFormat(Format.B8G8R8A8_UNorm, AlphaMode.Premultiplied);
            var bmpProps = new BitmapProperties(pFormat);

            var result =
                new Bitmap(
                    renderTarget,
                    new Size2(bmp.Width, bmp.Height),
                    stream,
                    bmpData.Stride,
                    bmpProps);

            bmp.UnlockBits(bmpData);

            stream.Dispose();
            bmp.Dispose();

            return(result);
        }
        public RenderTarget CreateRenderTarget(SharpDX.Direct2D1.FeatureLevel PFeatureLevel, PixelFormat PPixelFormat, RenderTargetType PRenderTargetType, RenderTargetUsage PRenderTargetUsage, Surface PBackBuffer, FactoryD2D PFactory)
        {
            this._FeatureLevel = PFeatureLevel;
            this._PixelFormat = PPixelFormat;
            this._RenderType = PRenderTargetType;
            this._RenderUsage = PRenderTargetUsage;
            _DPI = PFactory.DesktopDpi;

            _RenderTarget = new RenderTarget(PFactory, PBackBuffer, new RenderTargetProperties()
            {
                DpiX = _DPI.Width,
                DpiY = _DPI.Height,
                MinLevel = _FeatureLevel,
                PixelFormat = _PixelFormat,
                Type = _RenderType,
                Usage= _RenderUsage

            });

            return _RenderTarget;
        }
Example #21
0
        private void CreateTarget(int width, int height, System.IntPtr hwnd)
        {
            RenderTarget?.Dispose();
            var hwndProp = new D2D.HwndRenderTargetProperties
            {
                Hwnd           = hwnd,
                PixelSize      = new DX.Size2(width, height),
                PresentOptions = Vsync ? D2D.PresentOptions.None : D2D.PresentOptions.Immediately
            };

            var pixelFormat = new D2D.PixelFormat(DXGI.Format.B8G8R8A8_UNorm, D2D.AlphaMode.Premultiplied);
            var renderProp  = new D2D.RenderTargetProperties(D2D.RenderTargetType.Hardware, pixelFormat, 96, 96,
                                                             D2D.RenderTargetUsage.ForceBitmapRemoting, D2D.FeatureLevel.Level_DEFAULT);

            RenderTarget = new D2D.WindowRenderTarget(Factory, renderProp, hwndProp)
            {
                AntialiasMode     = D2D.AntialiasMode.Aliased,
                TextAntialiasMode = D2D.TextAntialiasMode.Default,
                Transform         = new Mathe.RawMatrix3x2(1, 0, 0, 1, 0, 0)
            };
        }
Example #22
0
        private void LoadTarget(object sender, EventArgs e)
        {
            var pixelFormat = new D2D.PixelFormat(DXGI.Format.B8G8R8A8_UNorm, D2D.AlphaMode.Premultiplied);

            var winProp = new D2D.HwndRenderTargetProperties
            {
                Hwnd           = this.Handle,
                PixelSize      = new DX.Size2(this.ClientSize.Width, this.ClientSize.Height),
                PresentOptions = D2D.PresentOptions.Immediately
            };

            var renderProp = new D2D.RenderTargetProperties(D2D.RenderTargetType.Default, pixelFormat,
                                                            96, 96, D2D.RenderTargetUsage.None, D2D.FeatureLevel.Level_DEFAULT);

            RenderTarget = new D2D.WindowRenderTarget(Factory, renderProp, winProp)
            {
                AntialiasMode     = D2D.AntialiasMode.PerPrimitive,
                TextAntialiasMode = D2D.TextAntialiasMode.Grayscale,
                Transform         = new Mathe.RawMatrix3x2
                {
                    M11 = 1,
                    M12 = 0,
                    M21 = 0,
                    M22 = 1,
                    M31 = 0,
                    M32 = 0
                }
            };

            // Create colors
            colorBack = new Mathe.RawColor4(0, 0, 0, 1);

            // Initialize layers
            layerClock    = new Layer.Clock(this.ClientSize);
            layerParticle = new Layer.Particles(500, 200);
            layerBack     = new Layer.Background();

            // Avoid artifacts
            this.SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.Opaque, true);
        }
Example #23
0
        public DeviceResources(IntPtr handle)
        {
            Factory2D      = new Factory1_2D1();
            ImagingFactory = new ImagingFactory();
            FontFactory    = new FactoryDW();
            PixelFormat    = new PixelFormat(Format.B8G8R8A8_UNorm, AlphaMode.Premultiplied);

            var modeDescription = new ModeDescription(PixelFormat.Format);

            var swapChainDescription = new SwapChainDescription
            {
                BufferCount       = 1,
                Flags             = SwapChainFlags.AllowModeSwitch,
                IsWindowed        = false,
                ModeDescription   = modeDescription,
                OutputHandle      = handle,
                SampleDescription = new SampleDescription(1, 0),
                SwapEffect        = SwapEffect.Discard,
                Usage             = Usage.RenderTargetOutput
            };

            Device.CreateWithSwapChain(
                DriverType.Hardware,
                DeviceCreationFlags.BgraSupport,
                swapChainDescription,
                out Device device3D,
                out SwapChain swapChain
                );
            SwapChain = swapChain;

            using (var dxgiDevice = device3D.QueryInterface <SharpDX.DXGI.Device>())
            {
                Device2D = new Device2D1(Factory2D, dxgiDevice);
            }

            device3D.Dispose();

            CreateDeviceContext();
        }
Example #24
0
        private void CreateDeviceIndependentResources()
        {
            _dxgiDevice = _d3dDevice.QueryInterface <SharpDX.DXGI.Device>();
            _d2dDevice  = new SharpDX.Direct2D1.Device(_dxgiDevice);
            _d2dFactory = _d2dDevice.Factory;
            var dpiX = _d2dFactory.DesktopDpi.Width;
            var dpiY = _d2dFactory.DesktopDpi.Height;

            _dc = new SharpDX.Direct2D1.DeviceContext(_d2dDevice, DeviceContextOptions.None);
            _dc.PrimitiveBlend = PrimitiveBlend.SourceOver;

            var format     = new SharpDX.Direct2D1.PixelFormat(Format.B8G8R8A8_UNorm, SharpDX.Direct2D1.AlphaMode.Premultiplied);
            var properties = new BitmapProperties1(format, dpiX, dpiY, BitmapOptions.Target | BitmapOptions.CannotDraw);

            _surface      = _swapChain.GetBackBuffer <Surface>(0);
            _renderTarget = new Bitmap1(_dc, _surface, properties);

            _dc.Target        = _renderTarget;
            _dc.AntialiasMode = AntialiasMode.PerPrimitive;

            OnCreateDeviceIndependentResources();
            this._deviceIndependedResourcesCreated = true;
        }
Example #25
0
        public static Bitmap ToD2D1Bitmap(this SdBitmap bitmap, RenderTarget renderTarget, PixelFormat pixelFormat)
        {
            var sourceArea       = new SdRect(0, 0, bitmap.Width, bitmap.Height);
            var bitmapProperties = new BitmapProperties(pixelFormat);
            var size             = new SharpDX.Size2(bitmap.Width, bitmap.Height);

            // Transform pixels from BGRA to RGBA.
            var stride = bitmap.Width * sizeof(int);

            using (var tempStream = new SharpDX.DataStream(bitmap.Height * stride, true, true))
            {
                // Lock System.Drawing.Bitmap
                var bitmapData = bitmap.LockBits(sourceArea, ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppPArgb);

                // Convert all pixels.
                for (var y = 0; y < bitmap.Height; y++)
                {
                    var offset = bitmapData.Stride * y;
                    for (var x = 0; x < bitmap.Width; x++)
                    {
                        // Not optimized.
                        var B = Marshal.ReadByte(bitmapData.Scan0, offset++);
                        var G = Marshal.ReadByte(bitmapData.Scan0, offset++);
                        var R = Marshal.ReadByte(bitmapData.Scan0, offset++);
                        var A = Marshal.ReadByte(bitmapData.Scan0, offset++);
                        tempStream.Write(R | (G << 8) | (B << 16) | (A << 24));
                    }
                }
                bitmap.UnlockBits(bitmapData);
                tempStream.Position = 0;
                return(new Bitmap(renderTarget, size, tempStream, stride, bitmapProperties));
            }
        }
Example #26
0
 private static void ConfigurePixelFormat(out PixelFormat description)
 {
     description.Format = Format.R8G8B8A8_UNorm;
     description.AlphaMode = AlphaMode.Premultiplied;
 }
Example #27
0
 /// <summary>
 /// Initializes a new instance of the <see cref="BitmapProperties1"/> class.
 /// </summary>
 /// <param name="pixelFormat">The pixel format.</param>
 /// <param name="dpiX">The dpi X.</param>
 /// <param name="dpiY">The dpi Y.</param>
 /// <param name="bitmapOptions">The bitmap options.</param>
 public BitmapProperties1(PixelFormat pixelFormat, float dpiX, float dpiY, BitmapOptions bitmapOptions) : this(pixelFormat, dpiX, dpiY, bitmapOptions, null)
 {
 }
Example #28
0
 /// <summary>
 /// Initializes a new instance of the <see cref="BitmapProperties"/> struct.
 /// </summary>
 /// <param name="pixelFormat">The pixel format.</param>
 /// <param name="dpiX">The dpi X.</param>
 /// <param name="dpiY">The dpi Y.</param>
 public BitmapProperties1(PixelFormat pixelFormat, float dpiX, float dpiY) : this(pixelFormat, dpiX, dpiY, BitmapOptions.None)
 {
 }
Example #29
0
 /// <summary>
 /// Initializes a new instance of the <see cref="BitmapProperties"/> struct.
 /// </summary>
 /// <param name="pixelFormat">The pixel format.</param>
 public BitmapProperties1(PixelFormat pixelFormat) : this(pixelFormat, 96, 96)
 {
 }
Example #30
0
        public static MemoryStream Resize(System.IO.Stream source, int maxwidth, int maxheight, Action beforeDrawImage, Action afterDrawImage)
        {
            // initialize the D3D device which will allow to render to image any graphics - 3D or 2D
            var defaultDevice = new SharpDX.Direct3D11.Device(SharpDX.Direct3D.DriverType.Warp,
                                                              d3d.DeviceCreationFlags.BgraSupport | d3d.DeviceCreationFlags.SingleThreaded | d3d.DeviceCreationFlags.PreventThreadingOptimizations);

            var d3dDevice = defaultDevice.QueryInterface<d3d.Device1>(); // get a reference to the Direct3D 11.1 device
            var dxgiDevice = d3dDevice.QueryInterface<dxgi.Device>(); // get a reference to DXGI device

            var d2dDevice = new d2.Device(dxgiDevice); // initialize the D2D device

            var imagingFactory = new wic.ImagingFactory2(); // initialize the WIC factory

            // initialize the DeviceContext - it will be the D2D render target and will allow all rendering operations
            var d2dContext = new d2.DeviceContext(d2dDevice, d2.DeviceContextOptions.None);

            var dwFactory = new dw.Factory();

            // specify a pixel format that is supported by both D2D and WIC
            var d2PixelFormat = new d2.PixelFormat(dxgi.Format.R8G8B8A8_UNorm, d2.AlphaMode.Premultiplied);
            // if in D2D was specified an R-G-B-A format - use the same for wic
            var wicPixelFormat = wic.PixelFormat.Format32bppPRGBA;

            // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
            // IMAGE LOADING ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
            var decoder = new wic.BitmapDecoder(imagingFactory,source, wic.DecodeOptions.CacheOnLoad);

            // decode the loaded image to a format that can be consumed by D2D
            var formatConverter = new wic.FormatConverter(imagingFactory);
            formatConverter.Initialize(decoder.GetFrame(0), wicPixelFormat);

            // store the image size - output will be of the same size
            var inputImageSize = formatConverter.Size;

            // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
            // RENDER TARGET SETUP ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

            // create the d2d bitmap description using default flags (from SharpDX samples) and 96 DPI
            var d2dBitmapProps = new d2.BitmapProperties1(d2PixelFormat, 96, 96, d2.BitmapOptions.Target | d2.BitmapOptions.CannotDraw);

            //Calculate size
            var resultSize = MathUtil.ScaleWithin(inputImageSize.Width,inputImageSize.Height,maxwidth,maxheight);
            var newWidth = resultSize.Item1;
            var newHeight = resultSize.Item2;

            // the render target
            var d2dRenderTarget = new d2.Bitmap1(d2dContext, new Size2(newWidth, newHeight), d2dBitmapProps);
            d2dContext.Target = d2dRenderTarget; // associate bitmap with the d2d context

            var bitmapSourceEffect = new d2.Effects.BitmapSourceEffect(d2dContext);
            bitmapSourceEffect.WicBitmapSource = formatConverter;

            // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
            // DRAWING ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
            beforeDrawImage();
            // slow preparations - fast drawing:
            d2dContext.BeginDraw();
            d2dContext.Transform = Matrix3x2.Scaling(new Vector2((float)(newWidth / (float)inputImageSize.Width), (float)(newHeight / (float)inputImageSize.Height)));
            d2dContext.DrawImage(bitmapSourceEffect, d2.InterpolationMode.HighQualityCubic);
            d2dContext.EndDraw();
            afterDrawImage();

            // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
            // IMAGE SAVING ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

            var ms = new MemoryStream();

            // use the appropiate overload to write either to stream or to a file
            var stream = new wic.WICStream(imagingFactory,ms);

            // select the image encoding format HERE
            var encoder = new wic.JpegBitmapEncoder(imagingFactory);
            encoder.Initialize(stream);

            var bitmapFrameEncode = new wic.BitmapFrameEncode(encoder);
            bitmapFrameEncode.Initialize();
            bitmapFrameEncode.SetSize(newWidth, newHeight);
            bitmapFrameEncode.SetPixelFormat(ref wicPixelFormat);

            // this is the trick to write D2D1 bitmap to WIC
            var imageEncoder = new wic.ImageEncoder(imagingFactory, d2dDevice);
            imageEncoder.WriteFrame(d2dRenderTarget, bitmapFrameEncode, new wic.ImageParameters(d2PixelFormat, 96, 96,  0, 0, newWidth, newHeight));

            bitmapFrameEncode.Commit();
            encoder.Commit();

            // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
            // CLEANUP ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

            // dispose everything and free used resources

            bitmapFrameEncode.Dispose();
            encoder.Dispose();
            stream.Dispose();
            formatConverter.Dispose();
            bitmapSourceEffect.Dispose();
            d2dRenderTarget.Dispose();
            decoder.Dispose();
            d2dContext.Dispose();
            dwFactory.Dispose();
            imagingFactory.Dispose();
            d2dDevice.Dispose();
            dxgiDevice.Dispose();
            d3dDevice.Dispose();
            defaultDevice.Dispose();
            return ms;
        }
            public void Init(Output output, GDI.Rectangle srcRect)
            {
                logger.Debug("DesktopDuplicator::Init(...) " + srcRect.ToString());

                try
                {
                    var          descr      = output.Description;
                    RawRectangle screenRect = descr.DesktopBounds;
                    int          width      = screenRect.Right - screenRect.Left;
                    int          height     = screenRect.Bottom - screenRect.Top;

                    SetupRegions(screenRect, srcRect);


                    if (descr.DeviceName == "\\\\.\\DISPLAY1")
                    {
                        drawRect = new Rectangle
                        {
                            X      = 1920,
                            Y      = 0,
                            Width  = width,
                            Height = height,
                        };
                    }
                    else if (descr.DeviceName == "\\\\.\\DISPLAY2")
                    {
                        drawRect = new Rectangle
                        {
                            X      = 0,
                            Y      = 0,
                            Width  = width,
                            Height = height,
                        };
                    }

                    screenTexture = new Texture2D(device,
                                                  new Texture2DDescription
                    {
                        CpuAccessFlags    = CpuAccessFlags.None,
                        BindFlags         = BindFlags.RenderTarget | BindFlags.ShaderResource,
                        Format            = Format.B8G8R8A8_UNorm,
                        Width             = width,
                        Height            = height,
                        MipLevels         = 1,
                        ArraySize         = 1,
                        SampleDescription = { Count = 1, Quality = 0 },
                        Usage             = ResourceUsage.Default,

                        OptionFlags = ResourceOptionFlags.Shared,
                    });

                    using (SharpDX.Direct2D1.Factory1 factory2D1 = new SharpDX.Direct2D1.Factory1(SharpDX.Direct2D1.FactoryType.MultiThreaded))
                    {
                        using (var surf = screenTexture.QueryInterface <Surface>())
                        {
                            var pixelFormat       = new Direct2D.PixelFormat(Format.B8G8R8A8_UNorm, Direct2D.AlphaMode.Premultiplied);
                            var renderTargetProps = new Direct2D.RenderTargetProperties(pixelFormat);
                            screenTarget = new Direct2D.RenderTarget(factory2D1, surf, renderTargetProps);
                        }
                    }

                    using (var output1 = output.QueryInterface <Output1>())
                    {
                        // Duplicate the output
                        deskDupl = output1.DuplicateOutput(device);
                    }
                }
                catch (Exception ex)
                {
                    logger.Error(ex);
                    Close();

                    throw;
                }

                deviceReady = true;
            }
Example #32
0
        static void Main()
        {
            // input and output files are supposed to be in the program folder
            var inputPath = "Input.png";
            var outputPath = "Output.png";

            // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
            // INITIALIZATION ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

            // initialize the D3D device which will allow to render to image any graphics - 3D or 2D
            var defaultDevice = new SharpDX.Direct3D11.Device(SharpDX.Direct3D.DriverType.Hardware,
                                                              d3d.DeviceCreationFlags.VideoSupport
                                                              | d3d.DeviceCreationFlags.BgraSupport
                                                              | d3d.DeviceCreationFlags.Debug); // take out the Debug flag for better performance

            var d3dDevice = defaultDevice.QueryInterface<d3d.Device1>(); // get a reference to the Direct3D 11.1 device
            var dxgiDevice = d3dDevice.QueryInterface<dxgi.Device>(); // get a reference to DXGI device

            var d2dDevice = new d2.Device(dxgiDevice); // initialize the D2D device

            var imagingFactory = new wic.ImagingFactory2(); // initialize the WIC factory

            // initialize the DeviceContext - it will be the D2D render target and will allow all rendering operations
            var d2dContext = new d2.DeviceContext(d2dDevice, d2.DeviceContextOptions.None);

            var dwFactory = new dw.Factory();

            // specify a pixel format that is supported by both D2D and WIC
            var d2PixelFormat = new d2.PixelFormat(dxgi.Format.R8G8B8A8_UNorm, d2.AlphaMode.Premultiplied);
            // if in D2D was specified an R-G-B-A format - use the same for wic
            var wicPixelFormat = wic.PixelFormat.Format32bppPRGBA;

            // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
            // IMAGE LOADING ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

            var decoder = new wic.PngBitmapDecoder(imagingFactory); // we will load a PNG image
            var inputStream = new wic.WICStream(imagingFactory, inputPath, NativeFileAccess.Read); // open the image file for reading
            decoder.Initialize(inputStream, wic.DecodeOptions.CacheOnLoad);

            // decode the loaded image to a format that can be consumed by D2D
            var formatConverter = new wic.FormatConverter(imagingFactory);
            formatConverter.Initialize(decoder.GetFrame(0), wicPixelFormat);

            // load the base image into a D2D Bitmap
            //var inputBitmap = d2.Bitmap1.FromWicBitmap(d2dContext, formatConverter, new d2.BitmapProperties1(d2PixelFormat));

            // store the image size - output will be of the same size
            var inputImageSize = formatConverter.Size;
            var pixelWidth = inputImageSize.Width;
            var pixelHeight = inputImageSize.Height;

            // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
            // EFFECT SETUP ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

            // Effect 1 : BitmapSource - take decoded image data and get a BitmapSource from it
            var bitmapSourceEffect = new d2.Effects.BitmapSource(d2dContext);
            bitmapSourceEffect.WicBitmapSource = formatConverter;

            // Effect 2 : GaussianBlur - give the bitmapsource a gaussian blurred effect
            var gaussianBlurEffect = new d2.Effects.GaussianBlur(d2dContext);
            gaussianBlurEffect.SetInput(0, bitmapSourceEffect.Output, true);
            gaussianBlurEffect.StandardDeviation = 5f;

            // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
            // OVERLAY TEXT SETUP ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

            var textFormat = new dw.TextFormat(dwFactory, "Arial", 15f); // create the text format of specified font configuration

            // draw a long text to show the automatic line wrapping
            var textToDraw = "Some long text to show the drawing of preformatted "
                             + "glyphs using DirectWrite on the Direct2D surface."
                             + " Notice the automatic wrapping of line if it exceeds desired width.";

            // create the text layout - this improves the drawing performance for static text
            // as the glyph positions are precalculated
            var textLayout = new dw.TextLayout(dwFactory, textToDraw, textFormat, 300f, 1000f);

            var textBrush = new d2.SolidColorBrush(d2dContext, Color.LightGreen);

            // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
            // RENDER TARGET SETUP ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

            // create the d2d bitmap description using default flags (from SharpDX samples) and 96 DPI
            var d2dBitmapProps = new d2.BitmapProperties1(d2PixelFormat, 96, 96, d2.BitmapOptions.Target | d2.BitmapOptions.CannotDraw);

            // the render target
            var d2dRenderTarget = new d2.Bitmap1(d2dContext, new Size2(pixelWidth, pixelHeight), d2dBitmapProps);
            d2dContext.Target = d2dRenderTarget; // associate bitmap with the d2d context

            // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
            // DRAWING ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

            // slow preparations - fast drawing:
            d2dContext.BeginDraw();
            d2dContext.DrawImage(gaussianBlurEffect);
            d2dContext.DrawTextLayout(new Vector2(5f, 5f), textLayout, textBrush);
            d2dContext.EndDraw();

            // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
            // IMAGE SAVING ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

            // delete the output file if it already exists
            if (System.IO.File.Exists(outputPath)) System.IO.File.Delete(outputPath);

            // use the appropiate overload to write either to stream or to a file
            var stream = new wic.WICStream(imagingFactory, outputPath, NativeFileAccess.Write);

            // select the image encoding format HERE
            var encoder = new wic.PngBitmapEncoder(imagingFactory);
            encoder.Initialize(stream);

            var bitmapFrameEncode = new wic.BitmapFrameEncode(encoder);
            bitmapFrameEncode.Initialize();
            bitmapFrameEncode.SetSize(pixelWidth, pixelHeight);
            bitmapFrameEncode.SetPixelFormat(ref wicPixelFormat);

            // this is the trick to write D2D1 bitmap to WIC
            var imageEncoder = new wic.ImageEncoder(imagingFactory, d2dDevice);
            imageEncoder.WriteFrame(d2dRenderTarget, bitmapFrameEncode, new wic.ImageParameters(d2PixelFormat, 96, 96, 0, 0, pixelWidth, pixelHeight));

            bitmapFrameEncode.Commit();
            encoder.Commit();

            // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
            // CLEANUP ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

            // dispose everything and free used resources

            bitmapFrameEncode.Dispose();
            encoder.Dispose();
            stream.Dispose();
            textBrush.Dispose();
            textLayout.Dispose();
            textFormat.Dispose();
            formatConverter.Dispose();
            gaussianBlurEffect.Dispose();
            bitmapSourceEffect.Dispose();
            d2dRenderTarget.Dispose();
            inputStream.Dispose();
            decoder.Dispose();
            d2dContext.Dispose();
            dwFactory.Dispose();
            imagingFactory.Dispose();
            d2dDevice.Dispose();
            dxgiDevice.Dispose();
            d3dDevice.Dispose();
            defaultDevice.Dispose();

            // show the result
            System.Diagnostics.Process.Start(outputPath);
        }
Example #33
0
        public static BitmapBrush makeBitmapBrush(RenderTarget renderTarget, string imgName, bool blankImage = false)
        {
            string imageSrc = Program.spriteFileDir + imgName;

            if (blankImage)
            {
                var pf = new SharpDX.Direct2D1.PixelFormat()
                {
                    AlphaMode = SharpDX.Direct2D1.AlphaMode.Premultiplied,
                    Format    = Format.B8G8R8A8_UNorm
                };

                BitmapRenderTarget pallete = new BitmapRenderTarget(renderTarget, CompatibleRenderTargetOptions.GdiCompatible, pf);
                return(new BitmapBrush(renderTarget, pallete.Bitmap, new BitmapBrushProperties()
                {
                    ExtendModeX = ExtendMode.Wrap, ExtendModeY = ExtendMode.Wrap
                }));
            }
            if (File.Exists(imageSrc))
            {
                ImagingFactory   imagingFactory = new ImagingFactory();
                NativeFileStream fileStream     = new NativeFileStream(imageSrc,
                                                                       NativeFileMode.Open, NativeFileAccess.Read);
                BitmapDecoder bitmapDecoder = new BitmapDecoder(imagingFactory, fileStream, DecodeOptions.CacheOnDemand);

                BitmapFrameDecode frame = bitmapDecoder.GetFrame(0);

                FormatConverter converter = new FormatConverter(imagingFactory);
                converter.Initialize(frame, SharpDX.WIC.PixelFormat.Format32bppPRGBA);

                Bitmap bitmap = Bitmap.FromWicBitmap(renderTarget, converter);

                Utilities.Dispose(ref bitmapDecoder);
                Utilities.Dispose(ref fileStream);
                Utilities.Dispose(ref imagingFactory);
                Utilities.Dispose(ref converter);

                return(new BitmapBrush(renderTarget, bitmap, new BitmapBrushProperties()
                {
                    ExtendModeX = ExtendMode.Wrap, ExtendModeY = ExtendMode.Wrap
                }));
            }
            else
            {
                Console.WriteLine("{0} missing", imageSrc);

                var pf = new SharpDX.Direct2D1.PixelFormat()
                {
                    AlphaMode = SharpDX.Direct2D1.AlphaMode.Premultiplied,
                    Format    = Format.B8G8R8A8_UNorm
                };
                BitmapRenderTarget pallete = new BitmapRenderTarget(renderTarget, CompatibleRenderTargetOptions.GdiCompatible, new Size2F(30f, 30f), new Size2(1, 1), pf);

                pallete.BeginDraw();
                pallete.Clear(Color.Purple);
                pallete.EndDraw();

                return(new BitmapBrush(renderTarget, pallete.Bitmap, new BitmapBrushProperties()
                {
                    ExtendModeX = ExtendMode.Wrap, ExtendModeY = ExtendMode.Wrap
                }));
            }
        }
        public override void initContent(SurfaceImageSourceTarget target, DrawingSize pixelSize)
        {
            this.drawingSize = pixelSize;
            this.size = new DrawingSize((int) (pixelSize.Width/scaling), (int) (pixelSize.Height/scaling));
            context = target.DeviceManager.ContextDirect2D;

            Mandelbrot engine = new BasicMandelbrot(iters);
            view = new TrajectoryMandelbrotView(engine, trajectory, size.Width, size.Height);

            data = new int[size.Width * size.Height];

            PixelFormat format = new PixelFormat(Format.B8G8R8A8_UNorm, SharpDX.Direct2D1.AlphaMode.Ignore);
            BitmapProperties props = new BitmapProperties(format);

            buf = Bitmap.New<int>(context, size, data, props);
        }
Example #35
0
        public BitmapBrush makeBitmapBrush(string imgName, RenderTarget renderTarget, bool blankImage = false)
        {
            //TODO : 여기 바꿔라!
            string imageSrc = "";

            if (blankImage)
            {
                SharpDX.Direct2D1.PixelFormat pf = new SharpDX.Direct2D1.PixelFormat()
                {
                    AlphaMode = D3DHandler.ALPHA_MODE,
                    Format    = D3DHandler.RENDER_FORMAT
                };

                BitmapRenderTarget pallete = new BitmapRenderTarget(renderTarget, CompatibleRenderTargetOptions.GdiCompatible, pf);
                return(new BitmapBrush(renderTarget, pallete.Bitmap, new BitmapBrushProperties()
                {
                    ExtendModeX = ExtendMode.Wrap, ExtendModeY = ExtendMode.Wrap
                }));
            }
            if (resourceCore.getFile(imgName, out ResFile resFile))
            {
                ImagingFactory imagingFactory = new ImagingFactory();

                /*NativeFileStream fileStream = new NativeFileStream(imageSrc,
                 *  NativeFileMode.Open, NativeFileAccess.Read);*/
                MemoryStream  ms            = new MemoryStream(resFile.rawData);
                BitmapDecoder bitmapDecoder = new BitmapDecoder(imagingFactory, ms, DecodeOptions.CacheOnDemand);

                BitmapFrameDecode frame = bitmapDecoder.GetFrame(0);

                FormatConverter converter = new FormatConverter(imagingFactory);
                converter.Initialize(frame, SharpDX.WIC.PixelFormat.Format32bppPRGBA);

                Bitmap bitmap = Bitmap.FromWicBitmap(renderTarget, converter);

                Utilities.Dispose(ref bitmapDecoder);
                Utilities.Dispose(ref imagingFactory);
                Utilities.Dispose(ref converter);

                return(new BitmapBrush(renderTarget, bitmap, new BitmapBrushProperties()
                {
                    ExtendModeX = ExtendMode.Wrap, ExtendModeY = ExtendMode.Wrap
                }));
            }
            else
            {
                Console.WriteLine("{0} missing", imageSrc);

                SharpDX.Direct2D1.PixelFormat pf = new SharpDX.Direct2D1.PixelFormat()
                {
                    AlphaMode = D3DHandler.ALPHA_MODE,
                    Format    = D3DHandler.RENDER_FORMAT
                };
                BitmapRenderTarget pallete = new BitmapRenderTarget(renderTarget, CompatibleRenderTargetOptions.GdiCompatible, new Size2F(30f, 30f), new Size2(1, 1), pf);

                pallete.BeginDraw();
                pallete.Clear(Color.Purple);
                pallete.EndDraw();

                return(new BitmapBrush(renderTarget, pallete.Bitmap, new BitmapBrushProperties()
                {
                    ExtendModeX = ExtendMode.Wrap, ExtendModeY = ExtendMode.Wrap
                }));
            }
        }
Example #36
0
        static void Main()
        {
            // input and output files are supposed to be in the program folder
            var inputPath  = "Input.png";
            var outputPath = "Output.png";

            // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
            // INITIALIZATION ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

            // initialize the D3D device which will allow to render to image any graphics - 3D or 2D
            var defaultDevice = new SharpDX.Direct3D11.Device(SharpDX.Direct3D.DriverType.Hardware,
                                                              d3d.DeviceCreationFlags.VideoSupport
                                                              | d3d.DeviceCreationFlags.BgraSupport
                                                              | d3d.DeviceCreationFlags.Debug); // take out the Debug flag for better performance

            var d3dDevice  = defaultDevice.QueryInterface <d3d.Device1>();                      // get a reference to the Direct3D 11.1 device
            var dxgiDevice = d3dDevice.QueryInterface <dxgi.Device>();                          // get a reference to DXGI device

            var d2dDevice = new d2.Device(dxgiDevice);                                          // initialize the D2D device

            var imagingFactory = new wic.ImagingFactory2();                                     // initialize the WIC factory

            // initialize the DeviceContext - it will be the D2D render target and will allow all rendering operations
            var d2dContext = new d2.DeviceContext(d2dDevice, d2.DeviceContextOptions.None);

            var dwFactory = new dw.Factory();

            // specify a pixel format that is supported by both D2D and WIC
            var d2PixelFormat = new d2.PixelFormat(dxgi.Format.R8G8B8A8_UNorm, d2.AlphaMode.Premultiplied);
            // if in D2D was specified an R-G-B-A format - use the same for wic
            var wicPixelFormat = wic.PixelFormat.Format32bppPRGBA;

            // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
            // IMAGE LOADING ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

            var decoder     = new wic.PngBitmapDecoder(imagingFactory);                            // we will load a PNG image
            var inputStream = new wic.WICStream(imagingFactory, inputPath, NativeFileAccess.Read); // open the image file for reading

            decoder.Initialize(inputStream, wic.DecodeOptions.CacheOnLoad);

            // decode the loaded image to a format that can be consumed by D2D
            var formatConverter = new wic.FormatConverter(imagingFactory);

            formatConverter.Initialize(decoder.GetFrame(0), wicPixelFormat);

            // load the base image into a D2D Bitmap
            //var inputBitmap = d2.Bitmap1.FromWicBitmap(d2dContext, formatConverter, new d2.BitmapProperties1(d2PixelFormat));

            // store the image size - output will be of the same size
            var inputImageSize = formatConverter.Size;
            var pixelWidth     = inputImageSize.Width;
            var pixelHeight    = inputImageSize.Height;

            // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
            // EFFECT SETUP ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

            // Effect 1 : BitmapSource - take decoded image data and get a BitmapSource from it
            var bitmapSourceEffect = new d2.Effects.BitmapSource(d2dContext);

            bitmapSourceEffect.WicBitmapSource = formatConverter;

            // Effect 2 : GaussianBlur - give the bitmapsource a gaussian blurred effect
            var gaussianBlurEffect = new d2.Effects.GaussianBlur(d2dContext);

            gaussianBlurEffect.SetInput(0, bitmapSourceEffect.Output, true);
            gaussianBlurEffect.StandardDeviation = 5f;

            // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
            // OVERLAY TEXT SETUP ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

            var textFormat = new dw.TextFormat(dwFactory, "Arial", 15f); // create the text format of specified font configuration

            // draw a long text to show the automatic line wrapping
            var textToDraw = "Some long text to show the drawing of preformatted "
                             + "glyphs using DirectWrite on the Direct2D surface."
                             + " Notice the automatic wrapping of line if it exceeds desired width.";

            // create the text layout - this improves the drawing performance for static text
            // as the glyph positions are precalculated
            var textLayout = new dw.TextLayout(dwFactory, textToDraw, textFormat, 300f, 1000f);

            var textBrush = new d2.SolidColorBrush(d2dContext, Color.LightGreen);

            // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
            // RENDER TARGET SETUP ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

            // create the d2d bitmap description using default flags (from SharpDX samples) and 96 DPI
            var d2dBitmapProps = new d2.BitmapProperties1(d2PixelFormat, 96, 96, d2.BitmapOptions.Target | d2.BitmapOptions.CannotDraw);

            // the render target
            var d2dRenderTarget = new d2.Bitmap1(d2dContext, new Size2(pixelWidth, pixelHeight), d2dBitmapProps);

            d2dContext.Target = d2dRenderTarget; // associate bitmap with the d2d context

            // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
            // DRAWING ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

            // slow preparations - fast drawing:
            d2dContext.BeginDraw();
            d2dContext.DrawImage(gaussianBlurEffect);
            d2dContext.DrawTextLayout(new Vector2(5f, 5f), textLayout, textBrush);
            d2dContext.EndDraw();

            // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
            // IMAGE SAVING ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

            // delete the output file if it already exists
            if (System.IO.File.Exists(outputPath))
            {
                System.IO.File.Delete(outputPath);
            }

            // use the appropiate overload to write either to stream or to a file
            var stream = new wic.WICStream(imagingFactory, outputPath, NativeFileAccess.Write);

            // select the image encoding format HERE
            var encoder = new wic.PngBitmapEncoder(imagingFactory);

            encoder.Initialize(stream);

            var bitmapFrameEncode = new wic.BitmapFrameEncode(encoder);

            bitmapFrameEncode.Initialize();
            bitmapFrameEncode.SetSize(pixelWidth, pixelHeight);
            bitmapFrameEncode.SetPixelFormat(ref wicPixelFormat);

            // this is the trick to write D2D1 bitmap to WIC
            var imageEncoder = new wic.ImageEncoder(imagingFactory, d2dDevice);

            imageEncoder.WriteFrame(d2dRenderTarget, bitmapFrameEncode, new wic.ImageParameters(d2PixelFormat, 96, 96, 0, 0, pixelWidth, pixelHeight));

            bitmapFrameEncode.Commit();
            encoder.Commit();

            // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
            // CLEANUP ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

            // dispose everything and free used resources

            bitmapFrameEncode.Dispose();
            encoder.Dispose();
            stream.Dispose();
            textBrush.Dispose();
            textLayout.Dispose();
            textFormat.Dispose();
            formatConverter.Dispose();
            gaussianBlurEffect.Dispose();
            bitmapSourceEffect.Dispose();
            d2dRenderTarget.Dispose();
            inputStream.Dispose();
            decoder.Dispose();
            d2dContext.Dispose();
            dwFactory.Dispose();
            imagingFactory.Dispose();
            d2dDevice.Dispose();
            dxgiDevice.Dispose();
            d3dDevice.Dispose();
            defaultDevice.Dispose();

            // show the result
            System.Diagnostics.Process.Start(outputPath);
        }
Example #37
0
        /// <summary>
        /// 初始化绘图有关组件
        /// </summary>
        /// <param name="width">游戏窗口宽度</param>
        /// <param name="height">游戏窗口高度</param>
        /// <param name="title">游戏窗口标题</param>
        private void InitRenderComponent(int width, int height, string title)
        {
            WindowSize = new Size2(width, height);

            var factory = new Factory(FactoryType.SingleThreaded);

            var hwndRenderTargetProperties = new HwndRenderTargetProperties {
                Hwnd = Form.Handle,
                PixelSize = new Size2(Form.Width, Form.Height),
                PresentOptions = PresentOptions.RetainContents
            };

            var pixelFormat = new PixelFormat(Format.B8G8R8A8_UNorm, AlphaMode.Ignore);
            var renderTargetProperties = new RenderTargetProperties(
                RenderTargetType.Hardware, pixelFormat, 0, 0, RenderTargetUsage.None, FeatureLevel.Level_DEFAULT);

            renderTarget = new WindowRenderTarget(factory, renderTargetProperties, hwndRenderTargetProperties);
        }
Example #38
0
        static void over()
        {
            var inputPath  = "Input.png";
            var outputPath = "output.png";

            // 그래픽을 랜더링할 장비를 추가 - 3D or 2D
            var defaultDevice = new SharpDX.Direct3D11.Device(SharpDX.Direct3D.DriverType.Hardware,
                                                              d3d.DeviceCreationFlags.VideoSupport
                                                              | d3d.DeviceCreationFlags.BgraSupport
                                                              | d3d.DeviceCreationFlags.None);
            var d3dDevice  = defaultDevice.QueryInterface <d3d.Device1>(); //get a refer to the D3D 11.1 device
            var dxgiDevice = d3dDevice.QueryInterface <dxgi.Device1>();    //get a refer to the DXGI device
            var d2dDevice  = new d2.Device(dxgiDevice);

            // DeviceContext를 초기화. D2D 렌더링 타겟이 될 것이고 모든 렌더링 작업을 허용
            var d2dContext = new d2.DeviceContext(d2dDevice, d2.DeviceContextOptions.None);
            var dwFactory  = new dw.Factory();


            //D2D, WIC 둘 다 지원되는 픽셀 형식 지정
            var d2PixelFormat = new d2.PixelFormat(dxgi.Format.R8G8B8A8_UNorm, d2.AlphaMode.Premultiplied);
            //RGBA형식 사용
            var wicPixelFormat = wic.PixelFormat.Format32bppPRGBA;



            //이미지 로딩
            var imagingFactory = new wic.ImagingFactory2();
            var decoder        = new wic.PngBitmapDecoder(imagingFactory);
            var inputStream    = new wic.WICStream(imagingFactory, inputPath, NativeFileAccess.Read);

            decoder.Initialize(inputStream, wic.DecodeOptions.CacheOnLoad);



            //다이렉트2D가 사용할수 있도록 디코딩
            var formatConverter = new wic.FormatConverter(imagingFactory);

            formatConverter.Initialize(decoder.GetFrame(0), wicPixelFormat);


            //기본 이미지를 D2D이미지로 로드
            //var inputBitmap = d2.Bitmap1.FromWicBitmap(d2dContext, formatConverter, new d2.BitmapProperties1(d2PixelFormat));

            //이미지 크기 저장
            var inputImageSize = formatConverter.Size;
            var pixelWidth     = inputImageSize.Width;
            var pixelHeight    = inputImageSize.Height;


            //Effect1 : BitpmapSource - 디코딩된 이미지 데이터를 가져오고 BitmapSource 가져오기
            var bitmapSourceEffect = new d2.Effects.BitmapSource(d2dContext);

            bitmapSourceEffect.WicBitmapSource = formatConverter;



            // Effect 2 : GaussianBlur - bitmapsource에 가우시안블러 효과 적용
            var gaussianBlurEffect = new d2.Effects.GaussianBlur(d2dContext);

            gaussianBlurEffect.SetInput(0, bitmapSourceEffect.Output, true);
            gaussianBlurEffect.StandardDeviation = 5f;



            //overlay text setup
            var textFormat = new dw.TextFormat(dwFactory, "Arial", 15f);

            //draw a long text to show the automatic line wrapping
            var textToDraw = "sime ling text..." + "text" + "dddd";

            //create the text layout - this imroves the drawing performance for static text
            // as the glyph positions are precalculated
            //윤곽선 글꼴 데이터에서 글자 하나의 모양에 대한 기본 단위를 글리프(glyph)라고 한다
            var textLayout = new dw.TextLayout(dwFactory, textToDraw, textFormat, 300f, 1000f);

            SharpDX.Mathematics.Interop.RawColor4 color = new SharpDX.Mathematics.Interop.RawColor4(255, 255, 255, 1);
            var textBrush = new d2.SolidColorBrush(d2dContext, color);



            //여기서부터 다시

            //render target setup

            //create the d2d bitmap description using default flags and 96 DPI
            var d2dBitmapProps = new d2.BitmapProperties1(d2PixelFormat, 96, 96, d2.BitmapOptions.Target | d2.BitmapOptions.CannotDraw);

            //the render target
            var d2dRenderTarget = new d2.Bitmap1(d2dContext, new Size2(pixelWidth, pixelHeight), d2dBitmapProps);

            d2dContext.Target = d2dRenderTarget; //associate bitmap with the d2d context



            //Drawing

            //slow preparations - fast drawing
            d2dContext.BeginDraw();
            d2dContext.DrawImage(gaussianBlurEffect, new SharpDX.Mathematics.Interop.RawVector2(100f, 100f));
            d2dContext.DrawTextLayout(new SharpDX.Mathematics.Interop.RawVector2(50f, 50f), textLayout, textBrush);
            d2dContext.EndDraw();

            //Image save

            //delete the output file if it already exists
            if (System.IO.File.Exists(outputPath))
            {
                System.IO.File.Delete(outputPath);
            }

            //use the appropiate overload to write either to tream or to a file
            var stream = new wic.WICStream(imagingFactory, outputPath, NativeFileAccess.Write);

            //select the image encoding format HERE
            var encoder = new wic.PngBitmapEncoder(imagingFactory);

            encoder.Initialize(stream);

            var bitmapFrameEncode = new wic.BitmapFrameEncode(encoder);

            bitmapFrameEncode.Initialize();
            bitmapFrameEncode.SetSize(pixelWidth, pixelHeight);
            bitmapFrameEncode.SetPixelFormat(ref wicPixelFormat);

            //this is the trick to write d2d1 bitmap to WIC
            var imageEncoder = new wic.ImageEncoder(imagingFactory, d2dDevice);

            imageEncoder.WriteFrame(d2dRenderTarget, bitmapFrameEncode, new wic.ImageParameters(d2PixelFormat, 96, 96, 0, 0, pixelWidth, pixelHeight));

            bitmapFrameEncode.Commit();
            encoder.Commit();

            //cleanup

            //dispose everything and free used resources
            bitmapFrameEncode.Dispose();
            encoder.Dispose();
            stream.Dispose();
            textBrush.Dispose();
            textLayout.Dispose();
            textFormat.Dispose();
            formatConverter.Dispose();
            //gaussianBlurEffect.Dispose();
            bitmapSourceEffect.Dispose();
            d2dRenderTarget.Dispose();
            inputStream.Dispose();
            decoder.Dispose();
            d2dContext.Dispose();
            dwFactory.Dispose();
            imagingFactory.Dispose();
            d2dDevice.Dispose();
            dxgiDevice.Dispose();
            d3dDevice.Dispose();
            defaultDevice.Dispose();

            //save
            System.Diagnostics.Process.Start(outputPath);
        }
        /// <summary>
        /// Run our application until the user quits.
        /// </summary>
        public void Run()
        {
            // Make window active and hide mouse cursor.
            window.PointerCursor = null;
            window.Activate();

            // Infinite loop to prevent the application from exiting.
            while (true)
            {
                // Dispatch all pending events in the queue.
                window.Dispatcher.ProcessEvents(CoreProcessEventsOption.ProcessAllIfPresent);

                // Quit if the users presses Escape key.
                if (window.GetAsyncKeyState(VirtualKey.Escape) == CoreVirtualKeyStates.Down)
                {
                    return;
                }

                int WIDTH = 1280;
                int HEIGHT = 800;
                Mandelbrot engine = new BasicMandelbrot(64);
                MandelbrotView view = new StaticMandelbrotView(engine, -.875f, 0f, 3f, WIDTH, HEIGHT);

                // Set the Direct2D drawing target.
                d2dContext.Target = d2dTarget;

                int[] data = new int[WIDTH * HEIGHT];
                for (int y = 0; y < HEIGHT; y++)
                {
                    for (int x = 0; x < WIDTH; x++)
                    {
                        float val = view.pixelAt(x, y);
                        int intVal = (int)(255 * val);
                        data[y * WIDTH + x] = 0 | intVal << 16 | intVal << 8 | intVal;
                    }
                }

                DrawingSize size = new DrawingSize(WIDTH, HEIGHT);
                PixelFormat format = new PixelFormat(Format.B8G8R8A8_UNorm, SharpDX.Direct2D1.AlphaMode.Ignore);
                BitmapProperties props = new BitmapProperties(format);
                RenderTarget target = d2dContext;
                Bitmap buf = Bitmap.New<int>(target, size, data, props);

                // Clear the target and draw some geometry with the brushes we created. Note that rectangles are
                // created specifying (start-x, start-y, end-x, end-y) coordinates; in XNA we used
                // (start-x, start-y, width, height).
                d2dContext.BeginDraw();
                d2dContext.DrawBitmap(buf, 1, BitmapInterpolationMode.Linear);
                d2dContext.EndDraw();

                // Present the current buffer to the screen.
                swapChain.Present(1, PresentFlags.None);
            }
        }