Пример #1
0
        private void CreateDeviceContext()
        {
            _deviceContext = new DeviceContext(Direct2D1Platform.Direct2D1Device, DeviceContextOptions.None)
            {
                DotsPerInch = _savedDpi
            };

            if (_swapChain == null)
            {
                CreateSwapChain();
            }

            using (var dxgiBackBuffer = _swapChain.GetBackBuffer <Surface>(0))
                using (var d2dBackBuffer = new Bitmap1(
                           _deviceContext,
                           dxgiBackBuffer,
                           new BitmapProperties1(
                               new SharpDX.Direct2D1.PixelFormat
                {
                    AlphaMode = SharpDX.Direct2D1.AlphaMode.Premultiplied,
                    Format = Format.B8G8R8A8_UNorm
                },
                               _savedSize.Width,
                               _savedSize.Height,
                               BitmapOptions.Target | BitmapOptions.CannotDraw)))
                {
                    _deviceContext.Target = d2dBackBuffer;
                }
        }
Пример #2
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="swapChain"></param>
 /// <param name="deviceContext"></param>
 public void Initialize(SwapChain1 swapChain, DeviceContext2D deviceContext)
 {
     RemoveAndDispose(ref d2DTarget);
     using (var surf = swapChain.GetBackBuffer <Surface>(0))
     {
         d2DTarget = Collect(BitmapProxy.Create("SwapChainTarget", deviceContext, surf));
     }
 }
Пример #3
0
        private bool CheckRender(IntPtr hwnd)
        {
            //window did not change
            if (hwnd == window)
            {
                return(window != IntPtr.Zero); //is not no window
            }
            //window changed do some cleanup of resource attached to old window
            fpsColor?.Dispose();
            fpsFont?.Dispose();
            renderOverlay?.Dispose();
            renderTarget?.Dispose();
            renderTexture?.Dispose();
            renderWindow?.Dispose();
            fpsCounter?.Dispose();
            window = hwnd;

            //window changed to no window
            if (window == IntPtr.Zero)
            {
                return(false);
            }

            //window render init
            using (var factory = adapter.GetParent <Factory2>()) {
                renderWindow = new SwapChain1(factory, device, window, ref renderDescription,
                                              new SwapChainFullScreenDescription()
                {
                    RefreshRate = new Rational(15, 1),
                    Scaling     = DisplayModeScaling.Stretched,
                    Windowed    = true
                }, null);

                factory.MakeWindowAssociation(window, WindowAssociationFlags.IgnoreAll);
            }

            renderTexture = Texture2D.FromSwapChain <Texture2D>(renderWindow, 0);
            renderTarget  = new RenderTargetView(device, renderTexture);

            //overlay init
            using (var surface = renderWindow.GetBackBuffer <Surface>(0))
                using (var factory = new SharpDX.Direct2D1.Factory(SharpDX.Direct2D1.FactoryType.SingleThreaded))
                    renderOverlay = new RenderTarget(factory, surface, new RenderTargetProperties()
                    {
                        Type        = RenderTargetType.Default,
                        PixelFormat = new D2DPixelFormat(Format.B8G8R8A8_UNorm, D2DAlphaMode.Premultiplied)
                    })
                    {
                        TextAntialiasMode = TextAntialiasMode.Cleartype
                    };

            using (var factory = new SharpDX.DirectWrite.Factory(SharpDX.DirectWrite.FactoryType.Shared))
                fpsFont = new TextFormat(factory, "Calibri", FontWeight.Bold, FontStyle.Normal, 18);

            fpsColor   = new SolidColorBrush(renderOverlay, new Color4(1f, 0f, 1f, 0.7f));
            fpsCounter = new AvgFPSCounter();
            return(true);
        }
Пример #4
0
        private void OnFrameArrived(Direct3D11CaptureFramePool sender, object args)
        {
            using (var frame = sender.TryGetNextFrame())
            {
                var needsReset     = false;
                var recreateDevice = false;

                if ((frame.ContentSize.Width != _lastSize.Width) || (frame.ContentSize.Height != _lastSize.Height))
                {
                    needsReset = true;
                    _lastSize  = frame.ContentSize;
                }

                try
                {
                    using (var backBuffer = _swapChain.GetBackBuffer <Texture2D>(0))
                    {
                        using (var bitmap = Direct3D11Helper.CreateSharpDXTexture2D(frame.Surface))
                        {
                            // copy current surface to backbuffer
                            _d3dDevice.ImmediateContext.CopyResource(bitmap, backBuffer);

                            // Create buffer for the resized copy
                            var width  = StreamWidth;
                            var height = StreamHeight;

                            using (var copy = new Texture2D(_d3dDevice, new Texture2DDescription {
                                Width = width, Height = height, MipLevels = 1, ArraySize = 1, Format = bitmap.Description.Format,
                                Usage = ResourceUsage.Staging, SampleDescription = new SampleDescription(1, 0), BindFlags = BindFlags.None, CpuAccessFlags = CpuAccessFlags.Read, OptionFlags = ResourceOptionFlags.None
                            }))
                            {
                                // Copy region from captured bitmap to stream bitmap
                                _d3dDevice.ImmediateContext.CopySubresourceRegion(backBuffer, 0, ROI, copy, 0);

                                // access the copied data in a stream
                                _d3dDevice.ImmediateContext.MapSubresource(copy, 0, 0, MapMode.Read, SharpDX.Direct3D11.MapFlags.None, out DataStream stream);
                                _buf.Add(new BufferedFrame(stream, new SizeInt32 {
                                    Width = width, Height = height
                                }, bitmap.Description.Format));
                                _d3dDevice.ImmediateContext.UnmapSubresource(copy, 0);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    needsReset     = true;
                    recreateDevice = true;
                }

                if (needsReset)
                {
                    _swapChain.ResizeBuffers(_swapChain.Description1.BufferCount, _lastSize.Width, _lastSize.Height, _swapChain.Description1.Format, _swapChain.Description1.Flags);
                    ResetFramePool(_lastSize, recreateDevice);
                }
            }
        }
Пример #5
0
        /// <summary>
        ///		現在のバックバッファの内容を Bitmap に複写して返す。
        ///		すべての描画が終わったあと、Present() する前に呼び出すこと。
        /// </summary>
        /// <returns>Bitmap。使用後は解放すること。</returns>
        public static Bitmap 取得する(
            SharpDX.Direct3D11.Device1 d3dDevice1,
            SwapChain1 swapchain1,
            RenderTargetView renderTargetView,
            SharpDX.Direct2D1.DeviceContext d2dDeviceContext)
        {
            // バックバッファの情報を取得する。
            Texture2DDescription backBufferDesc;

            using (var backBuffer = swapchain1.GetBackBuffer <Texture2D>(0))
                backBufferDesc = backBuffer.Description;

            // CPUがアクセス可能な Texture2D バッファをGPU上に作成する。
            using var captureTexture = new Texture2D(
                      d3dDevice1,
                      new Texture2DDescription()
            {
                ArraySize         = 1,
                BindFlags         = BindFlags.None,
                CpuAccessFlags    = CpuAccessFlags.Read,    // CPUからアクセスできる。
                Format            = backBufferDesc.Format,
                Height            = backBufferDesc.Height,
                Width             = backBufferDesc.Width,
                MipLevels         = 1,
                OptionFlags       = ResourceOptionFlags.None,
                SampleDescription = new SampleDescription(1, 0),
                Usage             = ResourceUsage.Staging, // GPU から CPU への copy ができる。
            });

            // RenderTarget から Texture2D バッファに、GPU上で画像データをコピーする。
            using (var resource = renderTargetView.Resource)
                d3dDevice1.ImmediateContext.CopyResource(resource, captureTexture);

            // Texture2D の本体(DXGIサーフェス)から Bitmap を生成する。
            using var dxgiSurface = captureTexture.QueryInterface <Surface>();
            var dataRect = dxgiSurface.Map(SharpDX.DXGI.MapFlags.Read, out DataStream dataStream);

            try
            {
                return(new Bitmap(
                           d2dDeviceContext,
                           new Size2(captureTexture.Description.Width, captureTexture.Description.Height),
                           new DataPointer(dataStream.DataPointer, (int)dataStream.Length),
                           dataRect.Pitch,
                           new BitmapProperties(
                               new PixelFormat(Format.B8G8R8A8_UNorm, SharpDX.Direct2D1.AlphaMode.Ignore),
                               d2dDeviceContext.DotsPerInch.Width,
                               d2dDeviceContext.DotsPerInch.Width)));
            }
            finally
            {
                dxgiSurface.Unmap();
            }
        }
Пример #6
0
        private void CreateSwapChain()
        {
            using (var dxgiAdaptor = DxgiDevice.Adapter)
                using (var dxgiFactory = dxgiAdaptor.GetParent <Factory2>())
                {
                    _deviceContext?.Dispose();
                    _deviceContext = new DeviceContext(D2DDevice, DeviceContextOptions.None)
                    {
                        DotsPerInch = _savedDpi
                    };


                    var swapChainDesc = new SwapChainDescription1
                    {
                        Width             = _savedSize.Width,
                        Height            = _savedSize.Height,
                        Format            = Format.B8G8R8A8_UNorm,
                        Stereo            = false,
                        SampleDescription = new SampleDescription
                        {
                            Count   = 1,
                            Quality = 0,
                        },
                        Usage       = Usage.RenderTargetOutput,
                        BufferCount = 2,
                        Scaling     = Scaling.None,
                        SwapEffect  = SwapEffect.FlipSequential,
                        Flags       = 0,
                    };

                    _swapChain?.Dispose();
                    _swapChain = CreateSwapChain(dxgiFactory, swapChainDesc);

                    using (var dxgiBackBuffer = _swapChain.GetBackBuffer <Surface>(0))
                        using (var d2dBackBuffer = new Bitmap1(
                                   _deviceContext,
                                   dxgiBackBuffer,
                                   new BitmapProperties1(
                                       new PixelFormat
                        {
                            AlphaMode = AlphaMode.Ignore,
                            Format = Format.B8G8R8A8_UNorm
                        },
                                       _savedDpi.Width,
                                       _savedDpi.Height,
                                       BitmapOptions.Target | BitmapOptions.CannotDraw)))
                        {
                            _deviceContext.Target = d2dBackBuffer;
                        }
                }
        }
Пример #7
0
        void Resize()
        {
            d2dDeviceContext.Target = null;
            d2dSurface.Dispose();
            swapChain.ResizeBuffers(0, 0, 0, Format.Unknown, SwapChainFlags.None);
            Surface1 dxgiSurface = swapChain.GetBackBuffer <Surface1>(0);
            var      props       = new BitmapProperties1(new PixelFormat(Format.B8G8R8A8_UNorm, D2D.AlphaMode.Ignore),
                                                         d2dDeviceContext.DotsPerInch.Width,
                                                         d2dDeviceContext.DotsPerInch.Height,
                                                         BitmapOptions.Target | BitmapOptions.CannotDraw);

            d2dSurface = new Bitmap1(d2dDeviceContext, dxgiSurface, props);
            dxgiSurface.Dispose();
            d2dDeviceContext.Target = d2dSurface;
        }
Пример #8
0
        private void RetrieveSetBuffers()
        {
            if (_swap == null)
            {
                throw new NullReferenceException("SwapChain is null");
            }

            var bb = _swap.GetBackBuffer <D3D11.Texture2D>(0);

            _rtv = new D3D11.RenderTargetView(_device, bb);
            bb.Dispose();

            _context.OutputMerger.SetRenderTargets(_rtv);
            _context.Rasterizer.SetViewport(0, 0, _width, _height);
        }
Пример #9
0
        void InitializeDirect2D()
        {
            d3dDevice  = new D3D.Device(DriverType.Hardware, DeviceCreationFlags.BgraSupport);
            dxgiDevice = d3dDevice.QueryInterface <DXGI.Device1>();
            var desc = new SwapChainDescription1()
            {
                Width             = 0,
                Height            = 0,
                Format            = Format.B8G8R8A8_UNorm,
                Stereo            = false,
                SampleDescription = new SampleDescription(1, 0),
                Usage             = Usage.RenderTargetOutput,
                BufferCount       = 3,
                Scaling           = Scaling.None,
                SwapEffect        = SwapEffect.FlipSequential,
                Flags             = SwapChainFlags.None
            };

            DXGI.Factory2 dxgiFactory = dxgiDevice.Adapter.GetParent <DXGI.Factory2>();
            swapChain = new SwapChain1(dxgiFactory, d3dDevice, Child.Handle, ref desc);
            swapChain.BackgroundColor = Color4.White;
            dxgiFactory.Dispose();

            d2dFactory       = new D2D.Factory1(FactoryType.SingleThreaded);
            d2dDevice        = new D2D.Device(d2dFactory, dxgiDevice);
            d2dDeviceContext = new D2D.DeviceContext(d2dDevice, DeviceContextOptions.None);
            d2dDeviceContext.TextAntialiasMode = TextAntialiasMode.Cleartype;
            //d2dDeviceContext.DotsPerInch = new Size2F(96, 96);
            var props = new BitmapProperties1(new PixelFormat(Format.B8G8R8A8_UNorm, D2D.AlphaMode.Ignore),
                                              d2dDeviceContext.DotsPerInch.Width,
                                              d2dDeviceContext.DotsPerInch.Height,
                                              BitmapOptions.Target | BitmapOptions.CannotDraw);
            Surface1 dxgiSurface = swapChain.GetBackBuffer <Surface1>(0);

            d2dSurface = new Bitmap1(d2dDeviceContext, dxgiSurface, props);
            dxgiSurface.Dispose();
            d2dDeviceContext.Target = d2dSurface;

            VertexFillBrush = new SolidColorBrush(d2dDeviceContext, new Color4(1, 0.5f, 0, 1));
            VertexDrawBrush = new SolidColorBrush(d2dDeviceContext, new Color4(0.2f, 0.2f, 0.2f, 1));
            EdgeDrawBrush   = new SolidColorBrush(d2dDeviceContext, Color4.Black);
            RasterDrawBrush = new SolidColorBrush(d2dDeviceContext, new Color4(0.5f, 0.5f, 0.5f, 1));
        }
Пример #10
0
        private void CreateOrResizeSwapChainDependentResources()
        {
            if (m_swapChain == null)
            {
                var desc = new SwapChainDescription1
                {
                    BufferCount       = 2,
                    Flags             = SwapChainFlags.AllowModeSwitch,
                    Format            = Format.B8G8R8A8_UNorm,
                    SampleDescription = new SampleDescription(1, 0),
                    Stereo            = false,
                    SwapEffect        = SwapEffect.FlipSequential,
                    Usage             = Usage.BackBuffer | Usage.RenderTargetOutput
                };

                var dxgiDevice = Device.QueryInterface <SharpDX.DXGI.Device2>();
                m_swapChain = m_swapChainFactory.CreateSwapChain(dxgiDevice, desc);
            }

            var swapChainDescription = m_swapChain.Description1;

            using (var backbuffer = m_swapChain.GetBackBuffer <Texture2D>(0))
            {
                m_renderTargetView = new RenderTargetView(Device, backbuffer);
            }

            var depthStencilDesc = new Texture2DDescription
            {
                Format            = Format.D24_UNorm_S8_UInt,
                ArraySize         = 1,
                Width             = swapChainDescription.Width,
                Height            = swapChainDescription.Height,
                MipLevels         = 1,
                SampleDescription = new SampleDescription(1, 0),
                BindFlags         = BindFlags.DepthStencil
            };

            m_depthStencilBuffer = new Texture2D(Device, depthStencilDesc);
            m_depthStencilView   = new DepthStencilView(Device, m_depthStencilBuffer);

            ImmediateContext.OutputMerger.SetRenderTargets(m_renderTargetView);
        }
Пример #11
0
        protected virtual void InitializeDirectXResources()
        {
            var clientSize     = ClientSize;
            var backBufferDesc = new ModeDescription(clientSize.Width, clientSize.Height,
                                                     new Rational(60, 1), Format.R8G8B8A8_UNorm);

            var swapChainDesc = new SwapChainDescription
            {
                ModeDescription   = backBufferDesc,
                SampleDescription = new SampleDescription(1, 0),
                Usage             = Usage.RenderTargetOutput,
                BufferCount       = 1,
                OutputHandle      = Handle,
                SwapEffect        = SwapEffect.Discard,
                IsWindowed        = !IsFullscreen
            };

            D3D11.Device.CreateWithSwapChain(D3D.DriverType.Hardware, D3D11.DeviceCreationFlags.BgraSupport,
                                             new[] { D3D.FeatureLevel.Level_10_0 }, swapChainDesc,
                                             out var device, out var swapChain);
            D3DDevice        = device;
            D3DDeviceContext = D3DDevice.ImmediateContext;

            SwapChain = new SwapChain1(swapChain.NativePointer);

            D2DFactory = new D2D1.Factory();
            using (var backBuffer = SwapChain.GetBackBuffer <D3D11.Texture2D>(0))
            {
                RenderTargetView = new D3D11.RenderTargetView(D3DDevice, backBuffer);
                RenderTarget     = new D2D1.RenderTarget(D2DFactory, backBuffer.QueryInterface <Surface>(),
                                                         new D2D1.RenderTargetProperties(new D2D1.PixelFormat(Format.Unknown, D2D1.AlphaMode.Premultiplied)))
                {
                    TextAntialiasMode = D2D1.TextAntialiasMode.Cleartype
                };
            }
            DwFactory = new DW.Factory(DW.FactoryType.Shared);

            SolidColorBrush = new D2D1.SolidColorBrush(RenderTarget, Color.White);
        }
Пример #12
0
        public override void Resize()
        {
            _dev.ImmediateContext.OutputMerger.SetRenderTargets(null, (RenderTargetView)null);
            _renderTarget?.Dispose();
            _depthStencil?.Dispose();
            _swapChain.ResizeBuffers(0, 0, 0, Format.Unknown, SwapChainFlags.None);

            SwapChainDescription1 desc  = _swapChain.Description1;
            Texture2D             color = _swapChain.GetBackBuffer <Texture2D>(0);

            _renderTarget = new RenderTargetView(_dev, color);
            color.Dispose();

            Texture2DDescription textureDesc = new Texture2DDescription();

            textureDesc.Width             = desc.Width;
            textureDesc.Height            = desc.Height;
            textureDesc.MipLevels         = 1;
            textureDesc.ArraySize         = 1;
            textureDesc.SampleDescription = desc.SampleDescription;
            textureDesc.Usage             = ResourceUsage.Default;
            textureDesc.BindFlags         = BindFlags.DepthStencil;
            textureDesc.CpuAccessFlags    = CpuAccessFlags.None;
            textureDesc.OptionFlags       = ResourceOptionFlags.None;
            textureDesc.Format            = Format.D24_UNorm_S8_UInt;

            Texture2D depthStencil = new Texture2D(_dev, textureDesc);

            _depthStencil = new DepthStencilView(_dev, depthStencil);
            depthStencil.Dispose();

            _viewport.X        = 0.0f;
            _viewport.Y        = 0.0f;
            _viewport.Width    = (float)desc.Width;
            _viewport.Height   = (float)desc.Height;
            _viewport.MinDepth = 0.0f;
            _viewport.MaxDepth = 1.0f;
        }
Пример #13
0
        public void Resize(object sender, WindowEventArgs pE)
        {
            try
            {
                Device.ImmediateContext.ClearState();

                _backBuffer.Dispose();
                _renderTarget.Dispose();
                Context.Dispose();

                _swapChain.ResizeBuffers(BUFFER_COUNT, (int)pE.Size.Width, (int)pE.Size.Height, Format.Unknown, SwapChainFlags.AllowModeSwitch);

                Context = new SharpDX.Direct2D1.DeviceContext(_2dDevice, DeviceContextOptions.None);
                var dpi  = Factory2D.DesktopDpi;
                var prop = new BitmapProperties1(new PixelFormat(Format.B8G8R8A8_UNorm, SharpDX.Direct2D1.AlphaMode.Premultiplied), dpi.Height, dpi.Width, BitmapOptions.CannotDraw | BitmapOptions.Target);
                _backBuffer    = _swapChain.GetBackBuffer <Surface>(0);
                _renderTarget  = new Bitmap1(Context, _backBuffer, prop);
                Context.Target = _renderTarget;
            }
            catch (System.Exception e)
            {
                System.Diagnostics.Debug.WriteLine("Error creating render target: " + e.Message);
            }
        }
Пример #14
0
        /// <summary>
        /// Now that we have a CoreWindow object, the DirectX device/context can be created.
        /// </summary>
        /// <param name="entryPoint"></param>
        public void Load(string entryPoint)
        {
            // Get the default hardware device and enable debugging. Don't care about the available feature level.
            // DeviceCreationFlags.BgraSupport must be enabled to allow Direct2D interop.
            SharpDX.Direct3D11.Device defaultDevice = new SharpDX.Direct3D11.Device(DriverType.Hardware, DeviceCreationFlags.Debug | DeviceCreationFlags.BgraSupport);

            // Query the default device for the supported device and context interfaces.
            device     = defaultDevice.QueryInterface <SharpDX.Direct3D11.Device1>();
            d3dContext = device.ImmediateContext.QueryInterface <SharpDX.Direct3D11.DeviceContext1>();

            // Query for the adapter and more advanced DXGI objects.
            SharpDX.DXGI.Device2  dxgiDevice2  = device.QueryInterface <SharpDX.DXGI.Device2>();
            SharpDX.DXGI.Adapter  dxgiAdapter  = dxgiDevice2.Adapter;
            SharpDX.DXGI.Factory2 dxgiFactory2 = dxgiAdapter.GetParent <SharpDX.DXGI.Factory2>();

            // Description for our swap chain settings.
            SwapChainDescription1 description = new SwapChainDescription1()
            {
                // 0 means to use automatic buffer sizing.
                Width  = 0,
                Height = 0,
                // 32 bit RGBA color.
                Format = Format.B8G8R8A8_UNorm,
                // No stereo (3D) display.
                Stereo = false,
                // No multisampling.
                SampleDescription = new SampleDescription(1, 0),
                // Use the swap chain as a render target.
                Usage = Usage.RenderTargetOutput,
                // Enable double buffering to prevent flickering.
                BufferCount = 2,
                // No scaling.
                Scaling = Scaling.None,
                // Flip between both buffers.
                SwapEffect = SwapEffect.FlipSequential,
            };

            // Generate a swap chain for our window based on the specified description.
            swapChain = new SwapChain1(dxgiFactory2, device, new ComObject(window), ref description);

            // Get the default Direct2D device and create a context.
            SharpDX.Direct2D1.Device d2dDevice = new SharpDX.Direct2D1.Device(dxgiDevice2);
            d2dContext = new SharpDX.Direct2D1.DeviceContext(d2dDevice, SharpDX.Direct2D1.DeviceContextOptions.None);

            // Specify the properties for the bitmap that we will use as the target of our Direct2D operations.
            // We want a 32-bit BGRA surface with premultiplied alpha.
            BitmapProperties1 properties = new BitmapProperties1(new SharpDX.Direct2D1.PixelFormat(SharpDX.DXGI.Format.B8G8R8A8_UNorm, SharpDX.Direct2D1.AlphaMode.Premultiplied),
                                                                 DisplayProperties.LogicalDpi, DisplayProperties.LogicalDpi, BitmapOptions.Target | BitmapOptions.CannotDraw);

            // Get the default surface as a backbuffer and create the Bitmap1 that will hold the Direct2D drawing target.
            Surface backBuffer = swapChain.GetBackBuffer <Surface>(0);

            d2dTarget = new Bitmap1(d2dContext, backBuffer, properties);

            playerBitmap  = this.LoadBitmapFromContentFile("/Assets/Bitmaps/player.png");
            terrainBitmap = this.LoadBitmapFromContentFile("/Assets/Bitmaps/terrain.png");
            terrainBrush  = new BitmapBrush1(d2dContext, terrainBitmap, new BitmapBrushProperties1()
            {
                ExtendModeX = ExtendMode.Wrap,
                ExtendModeY = ExtendMode.Wrap,
            });
        }
Пример #15
0
        /// <summary>
        /// Now that we have a CoreWindow object, the DirectX device/context can be created.
        /// </summary>
        /// <param name="entryPoint"></param>
        public async void Load(string entryPoint)
        {
            // Get the default hardware device and enable debugging. Don't care about the available feature level.
            // DeviceCreationFlags.BgraSupport must be enabled to allow Direct2D interop.
            SharpDX.Direct3D11.Device defaultDevice = new SharpDX.Direct3D11.Device(DriverType.Hardware, DeviceCreationFlags.Debug | DeviceCreationFlags.BgraSupport);

            // Query the default device for the supported device and context interfaces.
            device     = defaultDevice.QueryInterface <SharpDX.Direct3D11.Device1>();
            d3dContext = device.ImmediateContext.QueryInterface <SharpDX.Direct3D11.DeviceContext1>();

            // Query for the adapter and more advanced DXGI objects.
            SharpDX.DXGI.Device2  dxgiDevice2  = device.QueryInterface <SharpDX.DXGI.Device2>();
            SharpDX.DXGI.Adapter  dxgiAdapter  = dxgiDevice2.Adapter;
            SharpDX.DXGI.Factory2 dxgiFactory2 = dxgiAdapter.GetParent <SharpDX.DXGI.Factory2>();

            // Description for our swap chain settings.
            SwapChainDescription1 description = new SwapChainDescription1()
            {
                // 0 means to use automatic buffer sizing.
                Width  = 0,
                Height = 0,
                // 32 bit RGBA color.
                Format = Format.B8G8R8A8_UNorm,
                // No stereo (3D) display.
                Stereo = false,
                // No multisampling.
                SampleDescription = new SampleDescription(1, 0),
                // Use the swap chain as a render target.
                Usage = Usage.RenderTargetOutput,
                // Enable double buffering to prevent flickering.
                BufferCount = 2,
                // No scaling.
                Scaling = Scaling.None,
                // Flip between both buffers.
                SwapEffect = SwapEffect.FlipSequential,
            };

            // Generate a swap chain for our window based on the specified description.
            swapChain = dxgiFactory2.CreateSwapChainForCoreWindow(device, new ComObject(window), ref description, null);

            // Get the default Direct2D device and create a context.
            SharpDX.Direct2D1.Device d2dDevice = new SharpDX.Direct2D1.Device(dxgiDevice2);
            d2dContext = new SharpDX.Direct2D1.DeviceContext(d2dDevice, SharpDX.Direct2D1.DeviceContextOptions.None);

            // Specify the properties for the bitmap that we will use as the target of our Direct2D operations.
            // We want a 32-bit BGRA surface with premultiplied alpha.
            BitmapProperties1 properties = new BitmapProperties1(new PixelFormat(SharpDX.DXGI.Format.B8G8R8A8_UNorm, SharpDX.Direct2D1.AlphaMode.Premultiplied),
                                                                 DisplayProperties.LogicalDpi, DisplayProperties.LogicalDpi, BitmapOptions.Target | BitmapOptions.CannotDraw);

            // Get the default surface as a backbuffer and create the Bitmap1 that will hold the Direct2D drawing target.
            Surface backBuffer = swapChain.GetBackBuffer <Surface>(0);

            d2dTarget = new Bitmap1(d2dContext, backBuffer, properties);

            // Create the DirectWrite factory objet.
            SharpDX.DirectWrite.Factory fontFactory = new SharpDX.DirectWrite.Factory();

            // Create a TextFormat object that will use the Segoe UI font with a size of 24 DIPs.
            textFormat = new TextFormat(fontFactory, "Segoe UI", 24.0f);

            // Create two TextLayout objects for rendering the moving text.
            textLayout1 = new TextLayout(fontFactory, "This is an example of a moving TextLayout object with snapped pixel boundaries.", textFormat, 400.0f, 200.0f);
            textLayout2 = new TextLayout(fontFactory, "This is an example of a moving TextLayout object with no snapped pixel boundaries.", textFormat, 400.0f, 200.0f);

            // Vertical offset for the moving text.
            layoutY = 0.0f;

            // Create the brushes for the text background and text color.
            backgroundBrush = new SolidColorBrush(d2dContext, Color.White);
            textBrush       = new SolidColorBrush(d2dContext, Color.Black);
        }
Пример #16
0
        private void OnFrameArrived(Direct3D11CaptureFramePool sender, object args)
        {
            var newSize = false;

            using (var frame = sender.TryGetNextFrame())
            {
                if (frame.ContentSize.Width != lastSize.Width ||
                    frame.ContentSize.Height != lastSize.Height)
                {
                    // The thing we have been capturing has changed size.
                    // We need to resize the swap chain first, then blit the pixels.
                    // After we do that, retire the frame and then recreate the frame pool.
                    newSize         = true;
                    lastSize        = frame.ContentSize;
                    lastSize.Width  = lastSize.Width / 8 * 8;
                    lastSize.Height = lastSize.Height / 8 * 8;
                    swapChain.ResizeBuffers(
                        2,
                        lastSize.Width,
                        lastSize.Height,
                        Format.B8G8R8A8_UNorm,
                        SwapChainFlags.None);
                }

                using (var backBuffer = swapChain.GetBackBuffer <SharpDX.Direct3D11.Texture2D>(0))
                    using (var bitmap = Direct3D11Helper.CreateSharpDXTexture2D(frame.Surface))
                    {
                        d3dDevice.ImmediateContext.CopyResource(bitmap, backBuffer);

                        if (lastFrame != null)
                        {
                            d3dDevice.ImmediateContext.UnmapSubresource(lastFrame, 0);
                            lastFrame.Dispose();
                        }

                        // Create texture copy
                        lastFrame = new SharpDX.Direct3D11.Texture2D(d3dDevice, new SharpDX.Direct3D11.Texture2DDescription
                        {
                            Width             = bitmap.Description.Width,
                            Height            = bitmap.Description.Height,
                            MipLevels         = 1,
                            ArraySize         = 1,
                            Format            = Format.B8G8R8A8_UNorm,
                            Usage             = ResourceUsage.Staging,
                            SampleDescription = new SampleDescription(1, 0),
                            BindFlags         = BindFlags.None,
                            CpuAccessFlags    = CpuAccessFlags.Read,
                            OptionFlags       = ResourceOptionFlags.None
                        });
                        d3dDevice.ImmediateContext.CopyResource(bitmap, lastFrame);

                        var dataBox = d3dDevice.ImmediateContext.MapSubresource(lastFrame, 0, 0, MapMode.Read, SharpDX.Direct3D11.MapFlags.None, out DataStream stream);
                        var rect    = new DataRectangle
                        {
                            DataPointer = stream.DataPointer,
                            Pitch       = dataBox.RowPitch
                        };
                        lastMat = new Mat(lastFrame.Description.Height, lastFrame.Description.Width, MatType.CV_8UC4, stream.DataPointer); // width % 4 != 0

                        OnFrameReady(EventArgs.Empty);
                    }
            } // Retire the frame.

            // swapChain.Present(0, SharpDX.DXGI.PresentFlags.None);
            if (newSize)
            {
                framePool.Recreate(
                    device,
                    DirectXPixelFormat.B8G8R8A8UIntNormalized,
                    2,
                    lastSize);
            }
        }
Пример #17
0
        /// <summary>
        /// Now that we have a CoreWindow object, the DirectX device/context can be created.
        /// </summary>
        /// <param name="entryPoint"></param>
        public void Load(string entryPoint)
        {
            // Get the default hardware device and enable debugging. Don't care about the available feature level.
            // DeviceCreationFlags.BgraSupport must be enabled to allow Direct2D interop.
            SharpDX.Direct3D11.Device defaultDevice = new SharpDX.Direct3D11.Device(DriverType.Hardware, DeviceCreationFlags.Debug | DeviceCreationFlags.BgraSupport);

            // Query the default device for the supported device and context interfaces.
            device     = defaultDevice.QueryInterface <SharpDX.Direct3D11.Device1>();
            d3dContext = device.ImmediateContext.QueryInterface <SharpDX.Direct3D11.DeviceContext1>();

            // Query for the adapter and more advanced DXGI objects.
            SharpDX.DXGI.Device2  dxgiDevice2  = device.QueryInterface <SharpDX.DXGI.Device2>();
            SharpDX.DXGI.Adapter  dxgiAdapter  = dxgiDevice2.Adapter;
            SharpDX.DXGI.Factory2 dxgiFactory2 = dxgiAdapter.GetParent <SharpDX.DXGI.Factory2>();

            // Description for our swap chain settings.
            SwapChainDescription1 description = new SwapChainDescription1()
            {
                // 0 means to use automatic buffer sizing.
                Width  = 0,
                Height = 0,
                // 32 bit RGBA color.
                Format = Format.B8G8R8A8_UNorm,
                // No stereo (3D) display.
                Stereo = false,
                // No multisampling.
                SampleDescription = new SampleDescription(1, 0),
                // Use the swap chain as a render target.
                Usage = Usage.RenderTargetOutput,
                // Enable double buffering to prevent flickering.
                BufferCount = 2,
                // No scaling.
                Scaling = Scaling.None,
                // Flip between both buffers.
                SwapEffect = SwapEffect.FlipSequential,
            };

            // Generate a swap chain for our window based on the specified description.
            swapChain = dxgiFactory2.CreateSwapChainForCoreWindow(device, new ComObject(window), ref description, null);

            // Get the default Direct2D device and create a context.
            SharpDX.Direct2D1.Device d2dDevice = new SharpDX.Direct2D1.Device(dxgiDevice2);
            d2dContext = new SharpDX.Direct2D1.DeviceContext(d2dDevice, SharpDX.Direct2D1.DeviceContextOptions.None);

            // Specify the properties for the bitmap that we will use as the target of our Direct2D operations.
            // We want a 32-bit BGRA surface with premultiplied alpha.
            BitmapProperties1 properties = new BitmapProperties1(new PixelFormat(SharpDX.DXGI.Format.B8G8R8A8_UNorm, SharpDX.Direct2D1.AlphaMode.Premultiplied),
                                                                 DisplayProperties.LogicalDpi, DisplayProperties.LogicalDpi, BitmapOptions.Target | BitmapOptions.CannotDraw);

            // Get the default surface as a backbuffer and create the Bitmap1 that will hold the Direct2D drawing target.
            Surface backBuffer = swapChain.GetBackBuffer <Surface>(0);

            d2dTarget = new Bitmap1(d2dContext, backBuffer, properties);

            // Create a solid color brush.
            solidBrush = new SolidColorBrush(d2dContext, Color.Coral);

            // Create a linear gradient brush.
            // Note that the StartPoint and EndPoint values are set as absolute coordinates of the surface you are drawing to,
            // NOT the geometry we will apply the brush.
            linearGradientBrush = new LinearGradientBrush(d2dContext, new LinearGradientBrushProperties()
            {
                StartPoint = new Vector2(50, 0),
                EndPoint   = new Vector2(450, 0),
            },
                                                          new GradientStopCollection(d2dContext, new GradientStop[]
            {
                new GradientStop()
                {
                    Color    = Color.Blue,
                    Position = 0,
                },
                new GradientStop()
                {
                    Color    = Color.Green,
                    Position = 1,
                }
            }));

            // Create a radial gradient brush.
            // The center is specified in absolute coordinates, too.
            radialGradientBrush = new RadialGradientBrush(d2dContext, new RadialGradientBrushProperties()
            {
                Center  = new Vector2(250, 525),
                RadiusX = 100,
                RadiusY = 100,
            },
                                                          new GradientStopCollection(d2dContext, new GradientStop[]
            {
                new GradientStop()
                {
                    Color    = Color.Yellow,
                    Position = 0,
                },
                new GradientStop()
                {
                    Color    = Color.Red,
                    Position = 1,
                }
            }));
        }
Пример #18
0
        public bool Initialize(GameForm pForm, bool pFullScreen)
        {
            _form = pForm;
            try
            {
#if DEBUG
                Device defaultDevice = new Device(DriverType.Hardware, DeviceCreationFlags.Debug | DeviceCreationFlags.BgraSupport);
                _debug = defaultDevice.QueryInterface <DeviceDebug>();
#else
                Device defaultDevice = new Device(DriverType.Hardware, DeviceCreationFlags.BgraSupport);
#endif
                Device = defaultDevice.QueryInterface <SharpDX.Direct3D11.Device1>();

                var dxgiDevice2  = Device.QueryInterface <SharpDX.DXGI.Device2>();
                var dxgiFactory2 = dxgiDevice2.Adapter.GetParent <SharpDX.DXGI.Factory2>();

                // SwapChain description
                var desc = new SwapChainDescription1()
                {
                    Width             = 0,
                    Height            = 0,
                    Format            = Format.B8G8R8A8_UNorm,
                    Stereo            = false,
                    SampleDescription = new SampleDescription(1, 0),
                    BufferCount       = BUFFER_COUNT,
                    Scaling           = Scaling.None,
                    SwapEffect        = SwapEffect.FlipSequential,
                    Usage             = Usage.RenderTargetOutput
                };

                _swapChain       = new SwapChain1(dxgiFactory2, Device, pForm.Handle, ref desc, null);
                _2dDevice        = new SharpDX.Direct2D1.Device(dxgiDevice2);
                Context          = new SharpDX.Direct2D1.DeviceContext(_2dDevice, DeviceContextOptions.EnableMultithreadedOptimizations);
                SecondaryContext = new SharpDX.Direct2D1.DeviceContext(_2dDevice, DeviceContextOptions.None);
#if DEBUG
                Factory2D = new SharpDX.Direct2D1.Factory(FactoryType.SingleThreaded, DebugLevel.Information);
#else
                Factory2D = new SharpDX.Direct2D1.Factory(FactoryType.SingleThreaded);
#endif
                var dpi  = Factory2D.DesktopDpi;
                var prop = new BitmapProperties1(new PixelFormat(Format.B8G8R8A8_UNorm, SharpDX.Direct2D1.AlphaMode.Premultiplied), dpi.Height, dpi.Width, BitmapOptions.CannotDraw | BitmapOptions.Target);
                _backBuffer    = _swapChain.GetBackBuffer <Surface>(0);
                _renderTarget  = new Bitmap1(Context, _backBuffer, prop);
                Context.Target = _renderTarget;

                // Ignore all windows events
                using (Factory factory = _swapChain.GetParent <Factory>())
                {
                    factory.MakeWindowAssociation(pForm.Handle, WindowAssociationFlags.IgnoreAll);
                }

                FactoryDWrite = new SharpDX.DirectWrite.Factory();

                return(true);
            }
            catch (System.Exception e)
            {
                System.Diagnostics.Debug.WriteLine("Error creating render target: " + e.Message);
                return(false);
            }
        }
        protected virtual void CreateSizeDependentResources()
        {
            // Ensure dependent objects have been released.
            d2dContext.Target = null;
            if (d2dTargetBitmap != null)
            {
                RemoveAndDispose(ref d2dTargetBitmap);
            }
            d3dContext.OutputMerger.SetRenderTargets((RenderTargetView)null);
            d3dContext.Flush();

            /*d3dContext.FinishCommandList(false);
             * d3dContext.li*/

            // Set render target size to the rendered size of the panel including the composition scale,
            // defaulting to the minimum of 1px if no size was specified.
            var scale              = Dpi / 96;
            var renderTargetWidth  = (int)(panel.ActualWidth * scale);
            var renderTargetHeight = (int)(panel.ActualHeight * scale);

            if (renderTargetWidth == 0 || renderTargetHeight == 0)
            {
                return;
            }

            if (swapChain != null)
            {
                swapChain.ResizeBuffers(2, renderTargetWidth, renderTargetHeight, Format.B8G8R8A8_UNorm, SwapChainFlags.None);
            }
            else
            {
                var swapChainDesc = new SwapChainDescription1();
                swapChainDesc.Width  = renderTargetWidth;
                swapChainDesc.Height = renderTargetHeight;
                swapChainDesc.Format = Format.B8G8R8A8_UNorm;
                swapChainDesc.Stereo = new RawBool(false);
                swapChainDesc.SampleDescription.Count   = 1;
                swapChainDesc.SampleDescription.Quality = 0;
                swapChainDesc.Usage       = Usage.RenderTargetOutput;
                swapChainDesc.BufferCount = 2;
                swapChainDesc.SwapEffect  = SwapEffect.FlipSequential;
                swapChainDesc.Flags       = SwapChainFlags.None;
                swapChainDesc.AlphaMode   = AlphaMode.Unspecified; // Todo... May need to change
                //swapChainDesc.Scaling = Scaling.None;

                using (var dxgiDevice = d3dDevice.QueryInterface <global::SharpDX.DXGI.Device1>())
                {
                    var dxgiAdapter = dxgiDevice.Adapter;
                    var dxgiFactory = dxgiAdapter.GetParent <global::SharpDX.DXGI.Factory2>();

                    swapChain = Collect(new SwapChain1(dxgiFactory, d3dDevice, ref swapChainDesc, null));

                    // Counter act the composition scale of the render target as
                    // we already handle this in the platform window code.
                    using (var swapChain2 = swapChain.QueryInterface <SwapChain2>())
                    {
                        var inverseScale = new RawMatrix3x2();
                        inverseScale.M11           = 1.0f / scale;
                        inverseScale.M22           = 1.0f / scale;
                        swapChain2.MatrixTransform = inverseScale;
                    }

                    dxgiDevice.MaximumFrameLatency = 1;
                }

                // Associate the SwapChainBackgroundPanel with the swap chain
                using (var panelNative = ComObject.As <ISwapChainPanelNative>(panel))
                {
                    panelNative.SwapChain = swapChain;
                }
            }

            var bitmapProperties = new BitmapProperties1(
                new PixelFormat(Format.B8G8R8A8_UNorm, global::SharpDX.Direct2D1.AlphaMode.Premultiplied),
                Dpi,
                Dpi,
                BitmapOptions.Target | BitmapOptions.CannotDraw);

            using (var dxgiBackBuffer = swapChain.GetBackBuffer <Surface>(0))
            {
                d2dTargetBitmap   = Collect(new Bitmap1(d2dContext, dxgiBackBuffer, bitmapProperties));
                d2dContext.Target = d2dTargetBitmap;
            }
        }
Пример #20
0
        protected void InitialiseResources()
        {
            RemoveAndDispose(ref _backBuffer);
            RemoveAndDispose(ref _renderTargetView);
            RemoveAndDispose(ref _surface);
            RemoveAndDispose(ref _target);
            _d2dContext.Target = null;

            var desc = CreateSwapChainDescription();

            if (_swapChain != null)
            {
                _swapChain.ResizeBuffers(
                    _swapChain.Description.BufferCount,
                    WindowSize.Width,
                    WindowSize.Height,
                    _swapChain.Description.ModeDescription.Format,
                    _swapChain.Description.Flags);
            }
            else
            {
                using (var dxgiDevice2 = _d3dDevice.QueryInterface <SharpDX.DXGI.Device2>())
                    using (var dxgiAdapter = dxgiDevice2.Adapter)
                        using (var dxgiFactory2 = dxgiAdapter.GetParent <SharpDX.DXGI.Factory2>())
                        {
                            _swapChain = ToDispose(new SwapChain1(dxgiFactory2, _d3dDevice, _outputHandle, ref desc));
                            //_swapChain = ToDispose(new SwapChain1(dxgiFactory2, _d3dDevice, _outputHandle, ref desc));
                        }
            }

            _backBuffer = ToDispose(Resource.FromSwapChain <Texture2D>(_swapChain, 0));
            {
                // Create a view interface on the rendertarget to use on bind.
                _renderTargetView = new RenderTargetView(_d3dDevice, _backBuffer);

                // Cache the rendertarget dimensions in our helper class for convenient use.
                var backBufferDesc = _backBuffer.Description;
                RenderTargetBounds = new Rectangle(0, 0, backBufferDesc.Width, backBufferDesc.Height);
            }

            using (var depthBuffer = new Texture2D(_d3dDevice,
                                                   new Texture2DDescription()
            {
                Format = Format.D24_UNorm_S8_UInt,
                ArraySize = 1,
                MipLevels = 1,
                Width = (int)WindowSize.Width,
                Height = (int)WindowSize.Height,
                SampleDescription = new SampleDescription(1, 0),
                BindFlags = BindFlags.DepthStencil,
            }))
                _depthStencilView = new DepthStencilView(_d3dDevice, depthBuffer, new DepthStencilViewDescription()
                {
                    Dimension = DepthStencilViewDimension.Texture2D
                });

            var viewport = new ViewportF((float)RenderTargetBounds.X, (float)RenderTargetBounds.Y, (float)RenderTargetBounds.Width, (float)RenderTargetBounds.Height, 0.0f, 1.0f);

            _d3dContext.Rasterizer.SetViewport(viewport);

            var bitmapProperties = new BitmapProperties1(
                new PixelFormat(Format.B8G8R8A8_UNorm, AlphaMode.Premultiplied),
                _d2dFactory.DesktopDpi.Width,
                _d2dFactory.DesktopDpi.Height,
                BitmapOptions.Target | BitmapOptions.CannotDraw);


            using (var dxgiBackBuffer = _swapChain.GetBackBuffer <Surface>(0))
                _target = new Bitmap1(_d2dContext, dxgiBackBuffer, bitmapProperties);

            _d2dContext.Target            = _target;
            _d2dContext.TextAntialiasMode = TextAntialiasMode.Grayscale;

            /*_backBuffer = ToDispose(Resource.FromSwapChain<Texture2D>(_swapChain, 0));
             * _renderTargetView = ToDispose(new RenderTargetView(_d3dDevice, _backBuffer));
             * _surface = ToDispose(_backBuffer.QueryInterface<Surface>());
             *
             * using (var dxgiBackBuffer = _swapChain.GetBackBuffer<Surface>(0))
             *  _target = ToDispose(new RenderTarget(_d2dFactory, dxgiBackBuffer, new RenderTargetProperties(new PixelFormat(Format.Unknown, AlphaMode.Premultiplied))));
             */
            OnInitialize?.Invoke(this);
        }