Beispiel #1
0
 private void OnClosing(object sender, CancelEventArgs e)
 {
     this.Dispose();
     _renderForm.Dispose();
     _d2DRenderTarget.Dispose();
     _d2DFactory.Dispose();
     _textFormat.Dispose();
     _swapChain.Dispose();
     _target.Dispose();
     _targetView.Dispose();
     _device.Dispose();
 }
Beispiel #2
0
        private void ReleaseResources()
        {
            ReleaseD2DObjects();
            ReleaseRenderingObjects();

            void ReleaseD2DObjects()
            {
                renderTarget2d?.Dispose();
                surface?.Dispose();
                renderView?.Dispose();
                backBuffer?.Dispose();
                swapChain?.Dispose();
                device?.Dispose();
                factoryWrite?.Dispose();
                factory2d?.Dispose();
                factory?.Dispose();
            }

            void ReleaseRenderingObjects()
            {
                foreach (var cell in cells)
                {
                    cell.Dispose();
                }
                textFormat?.Dispose();
                sColorBrush?.Dispose();
            }
        }
Beispiel #3
0
 //清除内存
 public void Dispose()
 {
     target.Dispose();
     factory.Dispose();
     rBrush.Dispose();
     pBrush.Dispose();
 }
Beispiel #4
0
        public void Dispose()
        {
            foreach (var grad in verticalGradientCache.Values)
            {
                grad.Dispose();
            }
            verticalGradientCache.Clear();

            if (renderTarget != null)
            {
                renderTarget.Dispose();
                renderTarget = null;
            }

            if (directWriteFactory != null)
            {
                directWriteFactory.Dispose();
                directWriteFactory = null;
            }

            if (factory != null)
            {
                factory.Dispose();
                factory = null;
            }
        }
Beispiel #5
0
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            target.Dispose();
            factory.Dispose();

            game.Closing();
        }
Beispiel #6
0
        public wnd_overlay()
        {
            this.Paint += Wnd_overlay_Paint;

            int initialStyle = WinAPI.GetWindowLong(this.Handle, -20);

            WinAPI.SetWindowLong(this.Handle, -20, initialStyle | 0x80000 | 0x20 | 0x80);

            InitializeComponent();

            var factory    = new Factory();
            var renderProp = new HwndRenderTargetProperties()
            {
                Hwnd           = this.Handle,
                PixelSize      = new Size2(this.Width, this.Height),
                PresentOptions = PresentOptions.Immediately,
            };

            Device = new WindowRenderTarget(factory,
                                            new RenderTargetProperties(new PixelFormat(Format.B8G8R8A8_UNorm, AlphaMode.Premultiplied)),
                                            renderProp);

            this.Visible = false;
            factory.Dispose();

            updateWnd.RunWorkerAsync();
            SharpDXThread.Start();
        }
Beispiel #7
0
        static void Main()
        {
            var form = new RenderForm("KinectLight");
            form.Size = new System.Drawing.Size(1920,1200);

            var desc = new SwapChainDescription()
            {
                BufferCount = 1,
                ModeDescription = new ModeDescription(form.ClientSize.Width, form.ClientSize.Height, new Rational(60, 1), Format.R8G8B8A8_UNorm),
                IsWindowed = true,
                OutputHandle = form.Handle,
                SampleDescription = new SampleDescription(1, 0),
                SwapEffect = SwapEffect.Discard,
                Usage = Usage.RenderTargetOutput
            };

            SharpDX.Direct3D10.Device1 device;
            SwapChain swapChain;
            SharpDX.Direct3D10.Device1.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.BgraSupport, desc, SharpDX.Direct3D10.FeatureLevel.Level_10_1, out device, out swapChain);

            var d2dFactory = new SharpDX.Direct2D1.Factory();
            var surface = Surface.FromSwapChain(swapChain, 0);

            RenderTarget dc = new RenderTarget(d2dFactory, surface, new RenderTargetProperties(new PixelFormat(Format.Unknown, AlphaMode.Premultiplied)));

            MainGame.Instance.Height = form.ClientSize.Height;
            MainGame.Instance.Width = form.ClientSize.Width;
            GameTime gameTime = new GameTime();

            var config = new HttpSelfHostConfiguration("http://localhost:8080");

            config.Routes.MapHttpRoute(
                "API Default", "api/{controller}/{action}/{name}",
                new { id = RouteParameter.Optional });

            HttpSelfHostServer server = new HttpSelfHostServer(config);
            server.OpenAsync().Wait();

            RenderLoop.Run(form, () =>
            {
                gameTime.StartFrame();
                MainGame.Instance.Update(gameTime);
                dc.BeginDraw();
                dc.Clear(Colors.White);
                MainGame.Instance.Render(dc);
                var res = dc.EndDraw();
                swapChain.Present(1, PresentFlags.None);
                //Thread.Sleep(1);
            });

            server.Dispose();
            MainGame.Instance.Dispose();
            dc.Dispose();
            surface.Dispose();
            d2dFactory.Dispose();
            device.Dispose();
            swapChain.Dispose();
        }
Beispiel #8
0
 public void Dispose()
 {
     backBuffer.Dispose();
     swapChain.Dispose();
     surface.Dispose();
     RenderTarget.Dispose();
     direct2DFactory.Dispose();
     device.Dispose();
 }
Beispiel #9
0
 public void Dispose()
 {
     _renderTarget2D?.Dispose();
     _surface?.Dispose();
     _factory2D?.Dispose();
     _textureD3D11.Dispose();
     _renderView?.Dispose();
     _backBuffer?.Dispose();
 }
Beispiel #10
0
        public D2DFont(Texture2D backBuffer)
        {
            var d2dFactory = new SharpDX.Direct2D1.Factory();
            var d2dSurface = backBuffer.QueryInterface <Surface>();

            renderTarget = new RenderTarget(d2dFactory, d2dSurface, new RenderTargetProperties(new PixelFormat(Format.Unknown, SharpDX.Direct2D1.AlphaMode.Premultiplied)));

            d2dSurface.Dispose();
            d2dFactory.Dispose();
        }
Beispiel #11
0
 static void Dispose()
 {
     target.Dispose();
     d2dFactory.Dispose();
     writeFactory.Dispose();
     foreach (var pair in brushes)
     {
         pair.Value.Dispose();
     }
 }
Beispiel #12
0
 private void Dispose()
 {
     RoundStroke?.Dispose();
     HardStroke?.Dispose();
     DefaultText?.Dispose();
     WriteFactory?.Dispose();
     Context?.Dispose();
     Handle?.Dispose();
     Factory?.Dispose();
 }
Beispiel #13
0
        public InfoText(SharpDX.Direct3D11.Device device)
        {
            _immediateContext = device.ImmediateContext;
            rect.Size         = new Size2F(Width, Height);

            var factoryWic = new SharpDX.WIC.ImagingFactory();

            _wicBitmap = new SharpDX.WIC.Bitmap(factoryWic, _width, _height, pixelFormat, SharpDX.WIC.BitmapCreateCacheOption.CacheOnLoad);
            var renderTargetProperties = new RenderTargetProperties(RenderTargetType.Default,
                                                                    new SharpDX.Direct2D1.PixelFormat(SharpDX.DXGI.Format.R8G8B8A8_UNorm,
                                                                                                      SharpDX.Direct2D1.AlphaMode.Premultiplied), 0, 0, RenderTargetUsage.None,
                                                                    SharpDX.Direct2D1.FeatureLevel.Level_DEFAULT);

            factoryWic.Dispose();

            var factory2D = new SharpDX.Direct2D1.Factory();

            _wicRenderTarget = new WicRenderTarget(factory2D, _wicBitmap, renderTargetProperties);
            _wicRenderTarget.TextAntialiasMode = TextAntialiasMode.Default;
            factory2D.Dispose();

            var factoryDWrite = new SharpDX.DirectWrite.Factory(SharpDX.DirectWrite.FactoryType.Shared);

            _textFormat = new TextFormat(factoryDWrite, "Tahoma", 20);
            factoryDWrite.Dispose();

            _sceneColorBrush = new SolidColorBrush(_wicRenderTarget, color);
            clearColor       = color;
            clearColor.Alpha = 0;

            _renderTexture = new Texture2D(device, new Texture2DDescription()
            {
                ArraySize         = 1,
                BindFlags         = BindFlags.ShaderResource,
                CpuAccessFlags    = CpuAccessFlags.Write,
                Format            = Format.R8G8B8A8_UNorm,
                Height            = _height,
                Width             = _width,
                MipLevels         = 1,
                OptionFlags       = ResourceOptionFlags.None,
                SampleDescription = new SampleDescription(1, 0),
                Usage             = ResourceUsage.Dynamic
            });

            OverlayBufferRes = new ShaderResourceView(device, _renderTexture, new ShaderResourceViewDescription()
            {
                Format    = _renderTexture.Description.Format,
                Dimension = ShaderResourceViewDimension.Texture2D,
                Texture2D = new ShaderResourceViewDescription.Texture2DResource()
                {
                    MipLevels       = 1,
                    MostDetailedMip = 0
                }
            });
        }
Beispiel #14
0
 private void Form1_FormClosing(object sender, FormClosingEventArgs e)
 {
     redBrush.Dispose();
     //release resource
     redBrush.Dispose();
     whiteBrush.Dispose();
     gradient.Dispose();
     target.Dispose();
     factory.Dispose();
     factoryWrite.Dispose();
 }
Beispiel #15
0
 public void Dispose()
 {
     _isRunning = false;
     render2d.Dispose();
     device.Dispose();
     swapChain.Dispose();
     factory2d.Dispose();
     factoryText.Dispose();
     factoryDX.Dispose();
     brush.Dispose();
 }
Beispiel #16
0
        /// <summary>
        /// Update all resources
        /// </summary>
        /// <param name="backBuffer">BackBuffer</param>
        internal void UpdateResources(SharpDX.Direct3D11.Texture2D backBuffer)
        {
            var d2dFactory = new SharpDX.Direct2D1.Factory();
            var d2dSurface = backBuffer.QueryInterface <Surface>();

            _direct2DRenderTarget = new SharpDX.Direct2D1.RenderTarget(d2dFactory, d2dSurface, new SharpDX.Direct2D1.RenderTargetProperties(new SharpDX.Direct2D1.PixelFormat(Format.Unknown, SharpDX.Direct2D1.AlphaMode.Premultiplied)));
            d2dSurface.Dispose();
            d2dFactory.Dispose();

            InitFont();
        }
Beispiel #17
0
        protected override void ReleaseManagedResources()
        {
            _d2d1Factory.Dispose();
            if (_renderTargetFactory is IDisposable)
            {
                ((IDisposable)_renderTargetFactory).Dispose();
            }
            _renderTargetFactory = null;

            base.ReleaseManagedResources();
        }
Beispiel #18
0
 private void DisposeDirectXResources()
 {
     _textFormat.Dispose();
     _dwFactory.Dispose();
     _renderTarget.Dispose();
     _renderTargetView.Dispose();
     _d2DFactory.Dispose();
     _swapChain.Dispose();
     _d3DDeviceContext.Dispose();
     _d3DDevice.Dispose();
 }
Beispiel #19
0
 public void Dispose()
 {
     TextRect.Dispose();
     LayoutRect.Dispose();
     FontFactory.Dispose();
     TextRectangleBrush.Dispose();
     consoleTextFormat.Dispose();
     historyTextFormat.Dispose();
     LayoutBrush.Dispose();
     TextBrush.Dispose();
     d2dRenderTarget.Dispose();
     d2dFactory.Dispose();
 }
Beispiel #20
0
        public override void DestroyDevice()
        {
            foreach (string key in fonts.Keys)
            {
                GetFont(key).Dispose();
            }
            fonts.Clear();

            factory.Dispose();
            fontFactory.Dispose();
            device.Dispose();
            this.device = null;
        }
Beispiel #21
0
 private void DestroyInstance()
 {
     try
     {
         _sharedBrush.Dispose();
         _fontFactory.Dispose();
         _factory.Dispose();
         _device.Dispose();
     }
     catch
     {
     }
 }
Beispiel #22
0
        public InfoText(SharpDX.Direct3D11.Device device)
        {
            _immediateContext = device.ImmediateContext;
            rect.Size = new Size2F(Width, Height);

            var factoryWic = new SharpDX.WIC.ImagingFactory();
            _wicBitmap = new SharpDX.WIC.Bitmap(factoryWic, _width, _height, pixelFormat, SharpDX.WIC.BitmapCreateCacheOption.CacheOnLoad);
            var renderTargetProperties = new RenderTargetProperties(RenderTargetType.Default,
                new SharpDX.Direct2D1.PixelFormat(SharpDX.DXGI.Format.R8G8B8A8_UNorm,
                    SharpDX.Direct2D1.AlphaMode.Premultiplied), 0, 0, RenderTargetUsage.None,
                    SharpDX.Direct2D1.FeatureLevel.Level_DEFAULT);
            factoryWic.Dispose();

            var factory2D = new SharpDX.Direct2D1.Factory();
            _wicRenderTarget = new WicRenderTarget(factory2D, _wicBitmap, renderTargetProperties);
            _wicRenderTarget.TextAntialiasMode = TextAntialiasMode.Default;
            factory2D.Dispose();

            var factoryDWrite = new SharpDX.DirectWrite.Factory(SharpDX.DirectWrite.FactoryType.Shared);
            _textFormat = new TextFormat(factoryDWrite, "Tahoma", 20);
            factoryDWrite.Dispose();

            _sceneColorBrush = new SolidColorBrush(_wicRenderTarget, color);
            clearColor = color;
            clearColor.Alpha = 0;

            _renderTexture = new Texture2D(device, new Texture2DDescription()
            {
                ArraySize = 1,
                BindFlags = BindFlags.ShaderResource,
                CpuAccessFlags = CpuAccessFlags.Write,
                Format = Format.R8G8B8A8_UNorm,
                Height = _height,
                Width = _width,
                MipLevels = 1,
                OptionFlags = ResourceOptionFlags.None,
                SampleDescription = new SampleDescription(1, 0),
                Usage = ResourceUsage.Dynamic
            });

            OverlayBufferRes = new ShaderResourceView(device, _renderTexture, new ShaderResourceViewDescription()
            {
                Format = _renderTexture.Description.Format,
                Dimension = ShaderResourceViewDimension.Texture2D,
                Texture2D = new ShaderResourceViewDescription.Texture2DResource()
                {
                    MipLevels = 1,
                    MostDetailedMip = 0
                }
            });
        }
        /// <summary>
        /// Do not call if you use OverlayWindow class
        /// </summary>
        public void Dispose()
        {
            this.DeleteBrushContainer();
            this.DeleteFontContainer();
            this.DeleteLayoutContainer();

            this.BrushContainer  = null;
            this.FontContainer   = null;
            this.LayoutContainer = null;

            fontFactory.Dispose();
            factory.Dispose();
            device.Dispose();
        }
        /// <summary>
        /// Do not call if you use OverlayWindow class
        /// </summary>
        public void Dispose()
        {
            DeleteBrushContainer();
            DeleteFontContainer();
            DeleteLayoutContainer();

            _brushContainer  = null;
            _fontContainer   = null;
            _layoutContainer = null;

            _fontFactory.Dispose();
            _factory.Dispose();
            _device.Dispose();
        }
Beispiel #25
0
        private void wnd_overlay_Resize(object sender, EventArgs e)
        {
            var factory    = new Factory();
            var renderProp = new HwndRenderTargetProperties()
            {
                Hwnd           = this.Handle,
                PixelSize      = new Size2(this.Width, this.Height),
                PresentOptions = PresentOptions.Immediately,
            };

            Device = new WindowRenderTarget(factory,
                                            new RenderTargetProperties(new PixelFormat(Format.B8G8R8A8_UNorm, AlphaMode.Premultiplied)),
                                            renderProp);
            factory.Dispose();
        }
Beispiel #26
0
        public D2DSprite(Texture2D backBuffer)
        {
            _LBackgroundSprite = new ConcurrentDictionary <string, SpriteData>();
            _LSprite           = new Dictionary <string, SpriteData>();
            _LClickableSprite  = new ConcurrentDictionary <string, ClickableSprite>();


            SharpDX.Direct2D1.Factory d2dFactory = new SharpDX.Direct2D1.Factory();
            Surface d2dSurface = backBuffer.QueryInterface <Surface>();

            renderTarget = new RenderTarget(d2dFactory, d2dSurface, new RenderTargetProperties(new SharpDX.Direct2D1.PixelFormat(D3DHandler.RENDER_FORMAT, D3DHandler.ALPHA_MODE)));

            d2dSurface.Dispose();
            d2dFactory.Dispose();
        }
Beispiel #27
0
        public D2DFont(Texture2D backBuffer)
        {
            SharpDX.Direct2D1.Factory d2dFactory = new SharpDX.Direct2D1.Factory();
            Surface d2dSurface = backBuffer.QueryInterface <Surface>();


            PixelFormat pixelFormat = new PixelFormat(D3DHandler.RENDER_FORMAT, D3DHandler.ALPHA_MODE);

            var renderTargetProp = new RenderTargetProperties(pixelFormat);

            renderTarget = new RenderTarget(d2dFactory, d2dSurface, renderTargetProp);

            d2dSurface.Dispose();
            d2dFactory.Dispose();
        }
Beispiel #28
0
        public D2DSprite(Texture2D backBuffer)
        {
            _LBackgroundSprite = new ConcurrentDictionary <string, SpriteData>();
            _LSprite           = new Dictionary <string, SpriteData>();
            _LClickableSprite  = new ConcurrentDictionary <string, ClickableSprite>();


            var d2dFactory = new SharpDX.Direct2D1.Factory();
            var d2dSurface = backBuffer.QueryInterface <Surface>();

            renderTarget = new RenderTarget(d2dFactory, d2dSurface, new RenderTargetProperties(new SharpDX.Direct2D1.PixelFormat(Format.Unknown, SharpDX.Direct2D1.AlphaMode.Premultiplied)));

            d2dSurface.Dispose();
            d2dFactory.Dispose();
        }
Beispiel #29
0
        private void setupInstance(bool deleteOld = false)
        {
            if (deleteOld)
            {
                try
                {
                    _brush.Dispose();
                    _font.Dispose();

                    _fontFactory.Dispose();
                    _factory.Dispose();
                    _device.Dispose();
                }
                catch
                {
                }
            }

            _factory     = new Factory(SharpDX.Direct2D1.FactoryType.MultiThreaded, DebugLevel.None);
            _fontFactory = new FontFactory();

            RECT bounds = default(RECT);

            User32.GetWindowRect(TargetHandle, out bounds);

            _targetProperties = new HwndRenderTargetProperties()
            {
                Hwnd           = TargetHandle,
                PixelSize      = new Size2(Math.Abs(bounds.Right - bounds.Left), Math.Abs(bounds.Bottom - bounds.Top)),
                PresentOptions = VSync ? PresentOptions.None : PresentOptions.Immediately
            };

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

            _device = new WindowRenderTarget(_factory, renderTargetProperties, _targetProperties);

            _device.TextAntialiasMode = SharpDX.Direct2D1.TextAntialiasMode.Aliased;
            _device.AntialiasMode     = AntialiasMode.Aliased;

            _brush = new SolidColorBrush(_device, new RawColor4(0, 0, 0, 0));
        }
Beispiel #30
0
        public void Dispose()
        {
            brush.Dispose();

            wrFactory.Dispose();
            target.Dispose();
            bb.Dispose();
            fac.Dispose();
            d2dDevice.Dispose();
            dxgiFactory2.Dispose();
            dxgiAdapter.Dispose();
            dxgiDevice2.Dispose();
            defDevice.Dispose();
            d3device.Dispose();
            swapChain.Dispose();
            d2dContext.Dispose();
        }
Beispiel #31
0
        public wnd_overlay()
        {
            if (!Sig.Init())
            {
                MessageBox.Show("Failed to Load!\nMake Sure You Have CS:GO Started Before Launching.");
                Environment.Exit(Environment.ExitCode);
            }

            Paint += Wnd_overlay_Paint;

            var initialStyle = WinAPI.GetWindowLong(Handle, -20);

            WinAPI.SetWindowLong(Handle, -20, initialStyle | 0x80000 | 0x20 | 0x80);

            SetStyle(ControlStyles.OptimizedDoubleBuffer |
                     ControlStyles.AllPaintingInWmPaint |
                     ControlStyles.DoubleBuffer |
                     ControlStyles.UserPaint |
                     ControlStyles.Opaque |
                     ControlStyles.ResizeRedraw |
                     ControlStyles.SupportsTransparentBackColor, true);

            InitializeComponent();

            var factory    = new Factory();
            var renderProp = new HwndRenderTargetProperties
            {
                Hwnd           = Handle,
                PixelSize      = new Size2(Width, Height),
                PresentOptions = PresentOptions.Immediately
            };

            Device = new WindowRenderTarget(factory,
                                            new RenderTargetProperties(new PixelFormat(Format.B8G8R8A8_UNorm, AlphaMode.Premultiplied)),
                                            renderProp);


            factory.Dispose();

            updateWnd.RunWorkerAsync();
            OnResize(null);
            SharpDXThread.Start();
        }
Beispiel #32
0
        private void wnd_overlay_Resize(object sender, EventArgs e)
        {
            var factory    = new Factory();
            var renderProp = new HwndRenderTargetProperties
            {
                Hwnd           = Handle,
                PixelSize      = new Size2(Width, Height),
                PresentOptions = PresentOptions.Immediately
            };

            var initialStyle = WinAPI.GetWindowLong(Handle, -20);

            WinAPI.SetWindowLong(Handle, -20, initialStyle | 0x80000 | 0x20 | 0x80);

            Device = new WindowRenderTarget(factory,
                                            new RenderTargetProperties(new PixelFormat(Format.B8G8R8A8_UNorm, AlphaMode.Premultiplied)),
                                            renderProp);
            factory.Dispose();
        }
Beispiel #33
0
        /// <summary>
        /// Update all resources
        /// </summary>
        /// <param name="backBuffer">BackBuffer</param>
        internal void UpdateResources(SharpDX.Direct3D11.Texture2D backBuffer)
        {
            var d2dFactory = new SharpDX.Direct2D1.Factory();
            var d2dSurface = backBuffer.QueryInterface<Surface>();
            _direct2DRenderTarget = new SharpDX.Direct2D1.RenderTarget(d2dFactory, d2dSurface, new SharpDX.Direct2D1.RenderTargetProperties(new SharpDX.Direct2D1.PixelFormat(Format.Unknown, SharpDX.Direct2D1.AlphaMode.Premultiplied)));
            d2dSurface.Dispose();
            d2dFactory.Dispose();

            InitFont();
        }
        public void Run()
        {
            var form = new RenderForm("2d and 3d combined...it's like magic");
            form.KeyDown += (sender, args) => { if (args.KeyCode == Keys.Escape) form.Close(); };

            // DirectX DXGI 1.1 factory
            var factory1 = new Factory1();

            // The 1st graphics adapter
            var adapter1 = factory1.GetAdapter1(0);

            // ---------------------------------------------------------------------------------------------
            // Setup direct 3d version 11. It's context will be used to combine the two elements
            // ---------------------------------------------------------------------------------------------

            var description = new SwapChainDescription
                {
                    BufferCount = 1,
                    ModeDescription = new ModeDescription(0, 0, new Rational(60, 1), Format.R8G8B8A8_UNorm),
                    IsWindowed = true,
                    OutputHandle = form.Handle,
                    SampleDescription = new SampleDescription(1, 0),
                    SwapEffect = SwapEffect.Discard,
                    Usage = Usage.RenderTargetOutput,
                    Flags = SwapChainFlags.AllowModeSwitch
                };

            Device11 device11;
            SwapChain swapChain;

            Device11.CreateWithSwapChain(adapter1, DeviceCreationFlags.None, description, out device11, out swapChain);

            // create a view of our render target, which is the backbuffer of the swap chain we just created
            RenderTargetView renderTargetView;
            using (var resource = Resource.FromSwapChain<Texture2D>(swapChain, 0))
                renderTargetView = new RenderTargetView(device11, resource);

            // setting a viewport is required if you want to actually see anything
            var context = device11.ImmediateContext;

            var viewport = new Viewport(0.0f, 0.0f, form.ClientSize.Width, form.ClientSize.Height);
            context.OutputMerger.SetTargets(renderTargetView);
            context.Rasterizer.SetViewports(viewport);

            //
            // Create the DirectX11 texture2D. This texture will be shared with the DirectX10 device.
            //
            // The DirectX10 device will be used to render text onto this texture.
            // DirectX11 will then draw this texture (blended) onto the screen.
            // The KeyedMutex flag is required in order to share this resource between the two devices.
            var textureD3D11 = new Texture2D(device11, new Texture2DDescription
            {
                Width = form.ClientSize.Width,
                Height = form.ClientSize.Height,
                MipLevels = 1,
                ArraySize = 1,
                Format = Format.B8G8R8A8_UNorm,
                SampleDescription = new SampleDescription(1, 0),
                Usage = ResourceUsage.Default,
                BindFlags = BindFlags.RenderTarget | BindFlags.ShaderResource,
                CpuAccessFlags = CpuAccessFlags.None,
                OptionFlags = ResourceOptionFlags.SharedKeyedmutex
            });

            // ---------------------------------------------------------------------------------------------
            // Setup a direct 3d version 10.1 adapter
            // ---------------------------------------------------------------------------------------------
            var device10 = new Device10(adapter1, SharpDX.Direct3D10.DeviceCreationFlags.BgraSupport, FeatureLevel.Level_10_0);

            // ---------------------------------------------------------------------------------------------
            // Setup Direct 2d
            // ---------------------------------------------------------------------------------------------

            // Direct2D Factory
            var factory2D = new SharpDX.Direct2D1.Factory(FactoryType.SingleThreaded, DebugLevel.Information);

            // Here we bind the texture we've created on our direct3d11 device through the direct3d10
            // to the direct 2d render target....
            var sharedResource = textureD3D11.QueryInterface<SharpDX.DXGI.Resource>();
            var textureD3D10 = device10.OpenSharedResource<SharpDX.Direct3D10.Texture2D>(sharedResource.SharedHandle);

            var surface = textureD3D10.AsSurface();
            var rtp = new RenderTargetProperties
                {
                    MinLevel = SharpDX.Direct2D1.FeatureLevel.Level_10,
                    Type = RenderTargetType.Hardware,
                    PixelFormat = new PixelFormat(Format.Unknown, AlphaMode.Premultiplied)
                };

            var renderTarget2D = new RenderTarget(factory2D, surface, rtp);
            var solidColorBrush = new SolidColorBrush(renderTarget2D, Colors.Red);

            // ---------------------------------------------------------------------------------------------------
            // Setup the rendering data
            // ---------------------------------------------------------------------------------------------------

            // Load Effect. This includes both the vertex and pixel shaders.
            // Also can include more than one technique.
            ShaderBytecode shaderByteCode = ShaderBytecode.CompileFromFile(
                "effectDx11.fx",
                "fx_5_0",
                ShaderFlags.EnableStrictness);

            var effect = new Effect(device11, shaderByteCode);

            // create triangle vertex data, making sure to rewind the stream afterward
            var verticesTriangle = new DataStream(VertexPositionColor.SizeInBytes * 3, true, true);
            verticesTriangle.Write(new VertexPositionColor(new Vector3(0.0f, 0.5f, 0.5f),new Color4(1.0f, 0.0f, 0.0f, 1.0f)));
            verticesTriangle.Write(new VertexPositionColor(new Vector3(0.5f, -0.5f, 0.5f),new Color4(0.0f, 1.0f, 0.0f, 1.0f)));
            verticesTriangle.Write(new VertexPositionColor(new Vector3(-0.5f, -0.5f, 0.5f),new Color4(0.0f, 0.0f, 1.0f, 1.0f)));

            verticesTriangle.Position = 0;

            // create the triangle vertex layout and buffer
            var layoutColor = new InputLayout(device11, effect.GetTechniqueByName("Color").GetPassByIndex(0).Description.Signature, VertexPositionColor.inputElements);
            var vertexBufferColor = new Buffer(device11, verticesTriangle, (int)verticesTriangle.Length, ResourceUsage.Default, BindFlags.VertexBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0);
            verticesTriangle.Close();

            // create overlay vertex data, making sure to rewind the stream afterward
            // Top Left of screen is -1, +1
            // Bottom Right of screen is +1, -1
            var verticesText = new DataStream(VertexPositionTexture.SizeInBytes * 4, true, true);
            verticesText.Write(new VertexPositionTexture(new Vector3(-1, 1, 0),new Vector2(0, 0f)));
            verticesText.Write(new VertexPositionTexture(new Vector3(1, 1, 0),new Vector2(1, 0)));
            verticesText.Write(new VertexPositionTexture(new Vector3(-1, -1, 0),new Vector2(0, 1)));
            verticesText.Write(new VertexPositionTexture(new Vector3(1, -1, 0),new Vector2(1, 1)));

            verticesText.Position = 0;

            // create the overlay vertex layout and buffer
            var layoutOverlay = new InputLayout(device11, effect.GetTechniqueByName("Overlay").GetPassByIndex(0).Description.Signature, VertexPositionTexture.inputElements);
            var vertexBufferOverlay = new Buffer(device11, verticesText, (int)verticesText.Length, ResourceUsage.Default, BindFlags.VertexBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0);
            verticesText.Close();

            // Think of the shared textureD3D10 as an overlay.
            // The overlay needs to show the 2d content but let the underlying triangle (or whatever)
            // show thru, which is accomplished by blending.
            var bsd = new BlendStateDescription();
            bsd.RenderTarget[0].IsBlendEnabled = true;
            bsd.RenderTarget[0].SourceBlend = BlendOption.SourceColor;
            bsd.RenderTarget[0].DestinationBlend = BlendOption.BlendFactor;
            bsd.RenderTarget[0].BlendOperation = BlendOperation.Add;
            bsd.RenderTarget[0].SourceAlphaBlend = BlendOption.One;
            bsd.RenderTarget[0].DestinationAlphaBlend = BlendOption.Zero;
            bsd.RenderTarget[0].AlphaBlendOperation = BlendOperation.Add;
            bsd.RenderTarget[0].RenderTargetWriteMask = ColorWriteMaskFlags.All;

            var blendStateTransparent = new BlendState(device11, bsd);

            // ---------------------------------------------------------------------------------------------------
            // Create and tesselate an ellipse
            // ---------------------------------------------------------------------------------------------------
            var center = new DrawingPointF(form.ClientSize.Width/2.0f, form.ClientSize.Height/2.0f);
            var ellipse = new EllipseGeometry(factory2D, new Ellipse(center, form.ClientSize.Width / 2.0f, form.ClientSize.Height / 2.0f));

            // Populate a PathGeometry from Ellipse tessellation
            var tesselatedGeometry = new PathGeometry(factory2D);
            _geometrySink = tesselatedGeometry.Open();

            // Force RoundLineJoin otherwise the tesselated looks buggy at line joins
            _geometrySink.SetSegmentFlags(PathSegment.ForceRoundLineJoin);

            // Tesselate the ellipse to our TessellationSink
            ellipse.Tessellate(1, this);

            _geometrySink.Close();

            // ---------------------------------------------------------------------------------------------------
            // Acquire the mutexes. These are needed to assure the device in use has exclusive access to the surface
            // ---------------------------------------------------------------------------------------------------

            var device10Mutex = textureD3D10.QueryInterface<KeyedMutex>();
            var device11Mutex = textureD3D11.QueryInterface<KeyedMutex>();

            // ---------------------------------------------------------------------------------------------------
            // Main rendering loop
            // ---------------------------------------------------------------------------------------------------

            bool first = true;

            RenderLoop
                .Run(form,
                     () =>
                         {
                             if(first)
                             {
                                 form.Activate();
                                 first = false;
                             }

                             // clear the render target to black
                             context.ClearRenderTargetView(renderTargetView, Colors.DarkSlateGray);

                             // Draw the triangle
                             context.InputAssembler.InputLayout = layoutColor;
                             context.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList;
                             context.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(vertexBufferColor, VertexPositionColor.SizeInBytes, 0));
                             context.OutputMerger.BlendState = null;
                             var currentTechnique = effect.GetTechniqueByName("Color");
                             for (var pass = 0; pass < currentTechnique.Description.PassCount; ++pass)
                             {
                                 using (var effectPass = currentTechnique.GetPassByIndex(pass))
                                 {
                                     System.Diagnostics.Debug.Assert(effectPass.IsValid, "Invalid EffectPass");
                                     effectPass.Apply(context);
                                 }
                                 context.Draw(3, 0);
                             };

                             // Draw Ellipse on the shared Texture2D
                             device10Mutex.Acquire(0, 100);
                             renderTarget2D.BeginDraw();
                             renderTarget2D.Clear(Colors.Black);
                             renderTarget2D.DrawGeometry(tesselatedGeometry, solidColorBrush);
                             renderTarget2D.DrawEllipse(new Ellipse(center, 200, 200), solidColorBrush, 20, null);
                             renderTarget2D.EndDraw();
                             device10Mutex.Release(0);

                             // Draw the shared texture2D onto the screen, blending the 2d content in
                             device11Mutex.Acquire(0, 100);
                             var srv = new ShaderResourceView(device11, textureD3D11);
                             effect.GetVariableByName("g_Overlay").AsShaderResource().SetResource(srv);
                             context.InputAssembler.InputLayout = layoutOverlay;
                             context.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleStrip;
                             context.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(vertexBufferOverlay, VertexPositionTexture.SizeInBytes, 0));
                             context.OutputMerger.BlendState = blendStateTransparent;
                             currentTechnique = effect.GetTechniqueByName("Overlay");

                             for (var pass = 0; pass < currentTechnique.Description.PassCount; ++pass)
                             {
                                 using (var effectPass = currentTechnique.GetPassByIndex(pass))
                                 {
                                     System.Diagnostics.Debug.Assert(effectPass.IsValid, "Invalid EffectPass");
                                     effectPass.Apply(context);
                                 }
                                 context.Draw(4, 0);
                             }
                             srv.Dispose();
                             device11Mutex.Release(0);

                             swapChain.Present(0, PresentFlags.None);
                         });

            // dispose everything
            vertexBufferColor.Dispose();
            vertexBufferOverlay.Dispose();
            layoutColor.Dispose();
            layoutOverlay.Dispose();
            effect.Dispose();
            shaderByteCode.Dispose();
            renderTarget2D.Dispose();
            swapChain.Dispose();
            device11.Dispose();
            device10.Dispose();
            textureD3D10.Dispose();
            textureD3D11.Dispose();
            factory1.Dispose();
            adapter1.Dispose();
            sharedResource.Dispose();
            factory2D.Dispose();
            surface.Dispose();
            solidColorBrush.Dispose();
            blendStateTransparent.Dispose();

            device10Mutex.Dispose();
            device11Mutex.Dispose();
        }
Beispiel #35
0
        static void Main(string[] args)
        {
            mainForm = new RenderForm("Advanced Text rendering demo");

            d2dFactory = new D2DFactory();
            dwFactory = new DWriteFactory(SharpDX.DirectWrite.FactoryType.Shared);
            
            textRenderer = new CustomColorRenderer();

            CreateResources();

            var bgcolor = new Color4(0.1f,0.1f,0.1f,1.0f);

            //This is the offset where we start our text layout
            Vector2 offset = new Vector2(202.0f,250.0f);

            textFormat = new TextFormat(dwFactory, "Arial", FontWeight.Regular, FontStyle.Normal, 16.0f);
            textLayout = new TextLayout(dwFactory, introText, textFormat, 300.0f, 200.0f);

            //Apply various modifications to text
            textLayout.SetUnderline(true, new TextRange(0, 5));
            textLayout.SetDrawingEffect(greenBrush, new TextRange(10, 20));
            textLayout.SetFontSize(24.0f, new TextRange(6, 4));
            textLayout.SetFontFamilyName("Comic Sans MS", new TextRange(11,7));

            //Measure full layout
            var textSize = textLayout.Metrics;
            fullTextBackground = new RectangleF(textSize.Left + offset.X, textSize.Top + offset.Y, textSize.Width, textSize.Height);

            //Measure text to apply background to
            var metrics = textLayout.HitTestTextRange(53, 4, 0.0f, 0.0f)[0];
            textRegionRect = new RectangleF(metrics.Left + offset.X, metrics.Top + offset.Y, metrics.Width, metrics.Height);

            //Assign render target and brush to our custom renderer
            textRenderer.AssignResources(renderTarget, defaultBrush);

            RenderLoop.Run(mainForm, () =>
            {
                renderTarget.BeginDraw();
                renderTarget.Clear(bgcolor);

                renderTarget.FillRectangle(fullTextBackground, backgroundBrush);

                renderTarget.FillRectangle(textRegionRect, redBrush);

                textLayout.Draw(textRenderer, offset.X, offset.Y);

                try
                {
                    renderTarget.EndDraw();
                }
                catch
                {
                    CreateResources();
                }
            });

            d2dFactory.Dispose();
            dwFactory.Dispose();
            renderTarget.Dispose();
        }