Beispiel #1
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;

                    swapChain.ResizeBuffers(
                        2,
                        lastSize.Width,
                        lastSize.Height,
                        SharpDX.DXGI.Format.B8G8R8A8_UNorm,
                        SharpDX.DXGI.SwapChainFlags.None);
                }

                if (!isWait)
                {
                    if (isStartCapture)
                    {
                        using (var backBuffer = swapChain.GetBackBuffer <SharpDX.Direct3D11.Texture2D>(0))
                            using (var bitmap = Direct3D11Helper.CreateSharpDXTexture2D(frame.Surface))
                            {
                                //d3dDevice.ImmediateContext.CopyResource(bitmap, backBuffer);
                                CopyBitmap(frame.Surface, bitmap, frame.ContentSize.Width, frame.ContentSize.Height);

                                Console.WriteLine("Capture");

                                bitmap.Dispose();
                            };

                        isStartCapture = false;
                    }
                }

                //using (var backBuffer = swapChain.GetBackBuffer<SharpDX.Direct3D11.Texture2D>(0))
            } // Retire the frame.

            swapChain.Present(0, SharpDX.DXGI.PresentFlags.None);

            if (newSize)
            {
                framePool.Recreate(
                    device,
                    DirectXPixelFormat.B8G8R8A8UIntNormalized,
                    2,
                    lastSize);
            }
        }
        internal void EndRender()
        {
            if (SyncInterval > 0 || sw.Elapsed.TotalMilliseconds >= 1000.0 / refreshRate)
            {
                D3D11.Texture2D backBuffer = swapChain.GetBackBuffer <D3D11.Texture2D>(0);
                deviceContext.ResolveSubresource(surfaceTexture, 0, backBuffer, 0, DXGI.Format.R8G8B8A8_UNorm);
                backBuffer.Dispose();

                swapChain.Present(SyncInterval, DXGI.PresentFlags.None);
                sw.Restart();
            }
        }
Beispiel #3
0
        private void InitializeDirectXResources()
        {
            var clientSize     = ClientSize;
            var backBufferDesc = new DXGI.ModeDescription(clientSize.Width, clientSize.Height,
                                                          new DXGI.Rational(60, 1), DXGI.Format.R8G8B8A8_UNorm);

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

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

            _swapChain = new DXGI.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 <DXGI.Surface>(),
                                                          new D2D1.RenderTargetProperties(new D2D1.PixelFormat(DXGI.Format.Unknown, D2D1.AlphaMode.Premultiplied)))
                {
                    TextAntialiasMode = D2D1.TextAntialiasMode.Cleartype
                };
            }

            _solidColorBrush = new D2D1.SolidColorBrush(_renderTarget, Color.White);

            _dwFactory  = new DW.Factory(DW.FactoryType.Shared);
            _textFormat = new DW.TextFormat(_dwFactory, "Arial", DW.FontWeight.Bold,
                                            DW.FontStyle.Normal, DW.FontStretch.Normal, 84 * (float)GraphicsUtils.Scale)
            {
                TextAlignment      = DW.TextAlignment.Center,
                ParagraphAlignment = DW.ParagraphAlignment.Center
            };

            _bitmap = _paradigm.Config.Gui.UseBitmap ? Properties.Resources.Einstein.ToD2D1Bitmap(_renderTarget) : null;
        }
Beispiel #4
0
 public static void CreateDeviceSwapChainBitmap(
     DXGI.SwapChain1 swapChain,
     Direct2D1.DeviceContext target)
 {
     using (var surface = swapChain.GetBackBuffer <DXGI.Surface>(0))
     {
         var props = new Direct2D1.BitmapProperties1
         {
             BitmapOptions = Direct2D1.BitmapOptions.Target | Direct2D1.BitmapOptions.CannotDraw,
             PixelFormat   = new Direct2D1.PixelFormat(DXGI.Format.B8G8R8A8_UNorm, Direct2D1.AlphaMode.Ignore)
         };
         using (var bitmap = new Direct2D1.Bitmap1(target, surface, props))
         {
             target.Target = bitmap;
         }
     }
 }
Beispiel #5
0
        protected void InitializeDirectXResources()
        {
            ScaleFactor = (float)GraphicsUtils.Scale;

            var clientSize     = ClientSize;
            var backBufferDesc = new DXGI.ModeDescription(clientSize.Width, clientSize.Height,
                                                          new DXGI.Rational(60, 1), DXGI.Format.R8G8B8A8_UNorm);

            var swapChainDesc = new DXGI.SwapChainDescription()
            {
                ModeDescription   = backBufferDesc,
                SampleDescription = new DXGI.SampleDescription(1, 0),
                Usage             = DXGI.Usage.RenderTargetOutput,
                BufferCount       = 1,
                OutputHandle      = Handle,
                SwapEffect        = DXGI.SwapEffect.Discard,
                IsWindowed        = Paradigm.Config.Test.Debug
            };

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

            SwapChain = new DXGI.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 <DXGI.Surface>(),
                                                         new D2D1.RenderTargetProperties(new D2D1.PixelFormat(DXGI.Format.Unknown, D2D1.AlphaMode.Premultiplied)))
                {
                    TextAntialiasMode = D2D1.TextAntialiasMode.Cleartype
                };
            }

            DwFactory = new DW.Factory(DW.FactoryType.Shared);

            _customColorRenderer.AssignResources(RenderTarget, ForegroundBrush);

            CueTextFormat = new DW.TextFormat(DwFactory, "Arial", DW.FontWeight.Bold,
                                              DW.FontStyle.Normal, DW.FontStretch.Normal, 120 * ScaleFactor)
            {
                TextAlignment      = DW.TextAlignment.Center,
                ParagraphAlignment = DW.ParagraphAlignment.Center
            };
            SubtitleTextFormat = new DW.TextFormat(DwFactory, "Consolas", DW.FontWeight.Light,
                                                   DW.FontStyle.Normal, DW.FontStretch.Normal, Paradigm.Config.Gui.InputTextFontSize * ScaleFactor / 2)
            {
                TextAlignment      = DW.TextAlignment.Center,
                ParagraphAlignment = DW.ParagraphAlignment.Center
            };
            ButtonLabelTextFormat = new DW.TextFormat(DwFactory, "Consolas", DW.FontWeight.Bold,
                                                      DW.FontStyle.Normal, DW.FontStretch.Normal, Paradigm.Config.Gui.ButtonFontSize * ScaleFactor)
            {
                TextAlignment      = DW.TextAlignment.Center,
                ParagraphAlignment = DW.ParagraphAlignment.Center
            };
            InputTextFormat = new DW.TextFormat(DwFactory, "Consolas", DW.FontWeight.Bold,
                                                DW.FontStyle.Normal, DW.FontStretch.Normal, Paradigm.Config.Gui.InputTextFontSize * ScaleFactor)
            {
                TextAlignment      = DW.TextAlignment.Leading,
                ParagraphAlignment = DW.ParagraphAlignment.Center
            };

            SharedBrush       = new D2D1.SolidColorBrush(RenderTarget, Color.White);
            BackgroundBrush   = new D2D1.SolidColorBrush(RenderTarget, BackgroundColor);
            ForegroundBrush   = new D2D1.SolidColorBrush(RenderTarget, ForegroundColor);
            CorrectColorBrush = new D2D1.SolidColorBrush(RenderTarget, CorrectTextColor);
            WrongColorBrush   = new D2D1.SolidColorBrush(RenderTarget, WrongTextColor);

            PostInitDirectXResources();
        }
        protected virtual void CreateSizeDependentResources(object sender, RenderEventArgs e)
        {
            var  d3dDevice       = DirectX.Direct3D.Device;
            var  d3dContext      = DirectX.Direct3D.Context;
            var  d2dContext      = DirectX.Direct2D.Context;
            bool isStereoEnabled = deviceManager.Settings.IsStereo;

            Cleanup();

            // If the swap chain already exists, resize it.
            if (swapChain != null)
            {
                swapChain.ResizeBuffers(2, Width, Height, SharpDX.DXGI.Format.B8G8R8A8_UNorm, SharpDX.DXGI.SwapChainFlags.None);
            }

            // Otherwise, create a new one.
            else
            {
                // SwapChain description
                var desc = CreateSwapChainDescription();

                // Once the desired swap chain description is configured, it must be created on the same adapter as our D3D Device

                // First, retrieve the underlying DXGI Device from the D3D Device.
                // Creates the swap chain
                using (var dxgiDevice2 = d3dDevice.QueryInterface <SharpDX.DXGI.Device2>())
                    using (var dxgiAdapter = dxgiDevice2.Adapter)
                        using (var dxgiFactory2 = dxgiAdapter.GetParent <SharpDX.DXGI.Factory2>())
                        {
                            swapChain = ToDispose(CreateSwapChain(dxgiFactory2, d3dDevice, desc));

                            // Ensure that DXGI does not queue more than one frame at a time. This both reduces
                            // latency and ensures that the application will only render after each VSync, minimizing
                            // power consumption.
                            dxgiDevice2.MaximumFrameLatency = 1;
                        }
            }

            // Obtain the backbuffer for this window which will be the final 3D rendertarget.
            backBuffer = ToDispose(SharpDX.Direct3D11.Texture2D.FromSwapChain <SharpDX.Direct3D11.Texture2D>(swapChain, 0));
            {
                RenderTargetViewDescription rtvDescription = new RenderTargetViewDescription()
                {
                    Dimension      = RenderTargetViewDimension.Texture2DArray,
                    Format         = SharpDX.DXGI.Format.B8G8R8A8_UNorm,
                    Texture2DArray = new RenderTargetViewDescription.Texture2DArrayResource()
                    {
                        MipSlice = 0, FirstArraySlice = 0, ArraySize = 1
                    }
                };

                // Create a view interface on the rendertarget to use on bind.
                renderTargetView = ToDispose(new SharpDX.Direct3D11.RenderTargetView(d3dDevice, BackBuffer, rtvDescription));

                if (IsStereoEnabled)
                {
                    RenderTargetViewDescription rtvDescriptionRight = new RenderTargetViewDescription()
                    {
                        Dimension      = RenderTargetViewDimension.Texture2DArray,
                        Format         = SharpDX.DXGI.Format.B8G8R8A8_UNorm,
                        Texture2DArray = new RenderTargetViewDescription.Texture2DArrayResource()
                        {
                            MipSlice = 0, FirstArraySlice = 1, ArraySize = 1
                        }
                    };

                    renderTargetViewRight = ToDispose(new SharpDX.Direct3D11.RenderTargetView(d3dDevice, BackBuffer, rtvDescriptionRight));
                }

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

            // Create a descriptor for the depth/stencil buffer.
            // Allocate a 2-D surface as the depth/stencil buffer.
            // Create a DepthStencil view on this surface to use on bind.
            using (var depthBuffer = new SharpDX.Direct3D11.Texture2D(d3dDevice, new SharpDX.Direct3D11.Texture2DDescription()
            {
                Format = SharpDX.DXGI.Format.D24_UNorm_S8_UInt,
                ArraySize = 1,
                MipLevels = 1,
                Width = (int)RenderTargetSize.Width,
                Height = (int)RenderTargetSize.Height,
                SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0),
                BindFlags = SharpDX.Direct3D11.BindFlags.DepthStencil,
            }))
                depthStencilView = ToDispose(new SharpDX.Direct3D11.DepthStencilView(d3dDevice, depthBuffer,
                                                                                     new SharpDX.Direct3D11.DepthStencilViewDescription()
                {
                    Dimension = SharpDX.Direct3D11.DepthStencilViewDimension.Texture2D
                }));

            // Create a viewport descriptor of the full window size.
            var viewport = new SharpDX.ViewportF((float)RenderTargetBounds.X, (float)RenderTargetBounds.Y, (float)RenderTargetBounds.Width, (float)RenderTargetBounds.Height, 0.0f, 1.0f);

            // Set the current viewport using the descriptor.
            d3dContext.Rasterizer.SetViewport(viewport);

            // Now we set up the Direct2D render target bitmap linked to the swapchain.
            // Whenever we render to this bitmap, it will be directly rendered to the
            // swapchain associated with the window.
            var bitmapProperties = new SharpDX.Direct2D1.BitmapProperties1(
                new SharpDX.Direct2D1.PixelFormat(SharpDX.DXGI.Format.B8G8R8A8_UNorm, SharpDX.Direct2D1.AlphaMode.Premultiplied),
                deviceManager.Dpi,
                deviceManager.Dpi,
                SharpDX.Direct2D1.BitmapOptions.Target | SharpDX.Direct2D1.BitmapOptions.CannotDraw);

            // Direct2D needs the dxgi version of the backbuffer surface pointer.
            // Get a D2D surface from the DXGI back buffer to use as the D2D render target.
            if (IsStereoEnabled)
            {
                using (var dxgiBackBuffer = swapChain.GetBackBuffer <SharpDX.DXGI.Resource1>(0))
                {
                    using (var dxgiSurface = new Surface2(dxgiBackBuffer, 0))
                        bitmapTarget = ToDispose(new SharpDX.Direct2D1.Bitmap1(d2dContext, dxgiSurface, bitmapProperties));
                    using (var dxgiSurface = new Surface2(dxgiBackBuffer, 1))
                        bitmapTargetRight = ToDispose(new SharpDX.Direct2D1.Bitmap1(d2dContext, dxgiSurface, bitmapProperties));
                }
            }
            else
            {
                using (var dxgiBackBuffer = swapChain.GetBackBuffer <SharpDX.DXGI.Surface2>(0))
                    bitmapTarget = ToDispose(new SharpDX.Direct2D1.Bitmap1(d2dContext, dxgiBackBuffer, bitmapProperties));
            }
            // So now we can set the Direct2D render target.
            d2dContext.Target = BitmapTarget;

            // Set D2D text anti-alias mode to Grayscale to ensure proper rendering of text on intermediate surfaces.
            d2dContext.TextAntialiasMode = SharpDX.Direct2D1.TextAntialiasMode.Grayscale;
        }
        /// <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,
                        }
                }));
        }
        /// <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);
        }
        // Allocate all memory resources that change on a window SizeChanged event.
        protected virtual void CreateWindowSizeDependentResources()
        {
            _windowBounds = _window.Bounds;

            if (_swapChain != null)
            {
                _swapChain.ResizeBuffers(2, 0, 0, DXGI.Format.B8G8R8A8_UNorm, 0);
            }
            else
            {
                var swapChainDesc = new DXGI.SwapChainDescription1()
                {
                    Width = 0,
                    Height = 0,
                    Format = DXGI.Format.B8G8R8A8_UNorm,
                    Stereo = false,
                    Usage = DXGI.Usage.RenderTargetOutput,
                    BufferCount = 2,
                    Scaling = DXGI.Scaling.None,
                    SwapEffect = DXGI.SwapEffect.FlipSequential,
                    SampleDescription = new DXGI.SampleDescription { Count = 1, Quality = 0 },
                    Flags = 0
                };

                _swapChain = _window.CreateSwapChain(_device, ref swapChainDesc);

                // gotta figure out some reasonable way of doing this
                // dxgiDevice.MaximumFrameLatency = 1;

                D3D11.Texture2D backBuffer = _swapChain.GetBackBuffer<D3D11.Texture2D>(0);

                _renderTargetView = new D3D11.RenderTargetView(_device, backBuffer);

                // Cache the rendertarget dimensions in our helper class for convenient use.
                _renderTargetSize.Width = backBuffer.Description.Width;
                _renderTargetSize.Height = backBuffer.Description.Height;

                // Create a descriptor for the depth/stencil buffer.
                var depthStencilDesc = new D3D11.Texture2DDescription
                {
                    Format = DXGI.Format.D24_UNorm_S8_UInt,
                    Width = backBuffer.Description.Width,
                    Height = backBuffer.Description.Height,
                    ArraySize = 1,
                    MipLevels = 1,
                    BindFlags = D3D11.BindFlags.DepthStencil,
                    SampleDescription = new DXGI.SampleDescription { Count = 1 }
                };

                // Allocate a 2-D surface as the depth/stencil buffer.
                var depthStencil = new D3D11.Texture2D(_device, depthStencilDesc);

                // Create a DepthStencil view on this surface to use on bind.
                _depthStencilView = new D3D11.DepthStencilView(_device, depthStencil,
                    new D3D11.DepthStencilViewDescription { Dimension = D3D11.DepthStencilViewDimension.Texture2D });

                // Create a viewport descriptor of the full window size.
                var viewPort = new D3D11.Viewport
                {
                    TopLeftX = 0.0f,
                    TopLeftY = 0.0f,
                    Width = backBuffer.Description.Width,
                    Height = backBuffer.Description.Height
                };

                // Set the current viewport using the descriptor.
                _deviceContext.Rasterizer.SetViewports(viewPort);
            }
        }
        /// <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);

            // Load bitmap images
            playerBitmap = this.LoadBitmapFromContentFile("/Assets/Bitmaps/player.png");
            terrainBitmap = this.LoadBitmapFromContentFile("/Assets/Bitmaps/terrain.png");

            // Create hue rotation effect
            hueRotationEffect = new SharpDX.Direct2D1.Effects.HueRotation(d2dContext);

            // Create image shadow effect
            shadowEffect = new SharpDX.Direct2D1.Effects.Shadow(d2dContext);

            // Create image transform effect
            affineTransformEffect = new SharpDX.Direct2D1.Effects.AffineTransform2D(d2dContext);
            affineTransformEffect.SetInputEffect(0, shadowEffect);
            affineTransformEffect.TransformMatrix = Matrix3x2.Translation(terrainBitmap.PixelSize.Width * 0.25f, terrainBitmap.PixelSize.Height * 0.25f);

            // Create composite effect
            compositeEffect = new SharpDX.Direct2D1.Effects.Composite(d2dContext);
            compositeEffect.InputCount = 2;
            compositeEffect.SetInputEffect(0, affineTransformEffect);

            // Create tiling brush for terrain bitmap
            terrainBrush = new ImageBrush(d2dContext, terrainBitmap, new ImageBrushProperties()
            {
                ExtendModeX = ExtendMode.Wrap,
                ExtendModeY = ExtendMode.Wrap,
                SourceRectangle = new RectangleF(0, 0, terrainBitmap.Size.Width, terrainBitmap.Size.Height),
            });

            // Create rendertarget for drawing the tiling brush
            brushTarget = new Bitmap1(d2dContext, new Size2((int)(terrainBitmap.Size.Width * 10), (int)terrainBitmap.Size.Height), new BitmapProperties1()
            {
                PixelFormat = new SharpDX.Direct2D1.PixelFormat(SharpDX.DXGI.Format.B8G8R8A8_UNorm, SharpDX.Direct2D1.AlphaMode.Premultiplied),
                BitmapOptions = BitmapOptions.Target
            });
        }
Beispiel #11
0
        /// <summary>
        /// Create size dependent resources, in this case the swap chain and render targets
        /// </summary>
        /// <param name="app"></param>
        protected virtual void CreateSizeDependentResources(D3DApplicationBase app)
        {
            // Retrieve references to device and context
            var device  = DeviceManager.Direct3DDevice;
            var context = DeviceManager.Direct3DContext;
            // Retrieve Direct2D context (for use with text rendering etc)
            var d2dContext = DeviceManager.Direct2DContext;

            // Before the swapchain can resize all the buffers must be released
            RemoveAndDispose(ref _backBuffer);
            RemoveAndDispose(ref _renderTargetView);
            RemoveAndDispose(ref _depthStencilView);
            RemoveAndDispose(ref _depthBuffer);
            RemoveAndDispose(ref _bitmapTarget);
            d2dContext.Target = null;

            #region Initialize Direct3D swap chain and render target

            // If the swap chain already exists, resize it.
            if (_swapChain != null)
            {
                _swapChain.ResizeBuffers(
                    _swapChain.Description1.BufferCount,
                    Width,
                    Height,
                    _swapChain.Description.ModeDescription.Format,
                    _swapChain.Description.Flags);
            }
            // Otherwise, create a new one.
            else
            {
                // SwapChain description
                var desc = CreateSwapChainDescription();

                // Rather than create a new DXGI Factory we should reuse
                // the one that has been used internally to create the device

                // First, retrieve the underlying DXGI Device from the D3D Device.
                // access the adapter used for that device and then create the swap chain
                using (var dxgiDevice2 = device.QueryInterface <SharpDX.DXGI.Device2>())
                    using (var dxgiAdapter = dxgiDevice2.Adapter)
                        using (var dxgiFactory2 = dxgiAdapter.GetParent <SharpDX.DXGI.Factory2>())
                            using (var output = dxgiAdapter.Outputs.First())
                            {
                                // The CreateSwapChain method is used so we can descend
                                // from this class and implement a swapchain for a desktop
                                // or a Windows 8 AppStore app
                                _swapChain = ToDispose(CreateSwapChain(dxgiFactory2, device, desc));

#if !NETFX_CORE
                                // Retrieve the list of supported display modes
                                DisplayModeList = output.GetDisplayModeList(desc.Format, DisplayModeEnumerationFlags.Scaling);
#endif
                            }
            }

            // Obtain the backbuffer for this window which will be the final 3D rendertarget.
            BackBuffer = ToDispose(Texture2D.FromSwapChain <Texture2D>(_swapChain, 0));
            // Create a view interface on the rendertarget to use on bind.
            RenderTargetView = ToDispose(new RenderTargetView(device, BackBuffer));

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

            // Create a viewport descriptor of the render size.
            this.Viewport = new SharpDX.ViewportF(
                (float)RenderTargetBounds.X,
                (float)RenderTargetBounds.Y,
                (float)RenderTargetBounds.Width,
                (float)RenderTargetBounds.Height,
                0.0f,   // min depth
                1.0f);  // max depth

            // Set the current viewport for the rasterizer.
            context.Rasterizer.SetViewport(Viewport);

            // Create a descriptor for the depth/stencil buffer.
            // Allocate a 2-D texture as the depth/stencil buffer.
            // Create a DSV to use on bind.
            this.DepthBuffer = ToDispose(new Texture2D(device, new Texture2DDescription()
            {
                Format            = SharpDX.DXGI.Format.D32_Float_S8X24_UInt,
                ArraySize         = 1,
                MipLevels         = 1,
                Width             = RenderTargetSize.Width,
                Height            = RenderTargetSize.Height,
                SampleDescription = SwapChain.Description.SampleDescription,
                BindFlags         = BindFlags.DepthStencil,
            }));
            this.DepthStencilView = ToDispose(
                new DepthStencilView(
                    device,
                    DepthBuffer,
                    new DepthStencilViewDescription()
            {
                Dimension = (SwapChain.Description.SampleDescription.Count > 1 || SwapChain.Description.SampleDescription.Quality > 0) ? DepthStencilViewDimension.Texture2DMultisampled : DepthStencilViewDimension.Texture2D
            }));

            // Set the OutputMerger targets
            context.OutputMerger.SetTargets(DepthStencilView, RenderTargetView);

            #endregion

            #region Initialize Direct2D render target

            // Now we set up the Direct2D render target bitmap linked to the swapchain.
            // Whenever we render to this bitmap, it will be directly rendered to the
            // swapchain associated with the window.
            var bitmapProperties = new SharpDX.Direct2D1.BitmapProperties1(
                new SharpDX.Direct2D1.PixelFormat(_swapChain.Description.ModeDescription.Format, SharpDX.Direct2D1.AlphaMode.Premultiplied),
                DeviceManager.Dpi,
                DeviceManager.Dpi,
                SharpDX.Direct2D1.BitmapOptions.Target | SharpDX.Direct2D1.BitmapOptions.CannotDraw);

            // Direct2D needs the dxgi version of the backbuffer surface pointer.
            // Get a D2D surface from the DXGI back buffer to use as the D2D render target.
            using (var dxgiBackBuffer = _swapChain.GetBackBuffer <SharpDX.DXGI.Surface>(0))
                BitmapTarget2D = ToDispose(new SharpDX.Direct2D1.Bitmap1(d2dContext, dxgiBackBuffer, bitmapProperties));

            // So now we can set the Direct2D render target.
            d2dContext.Target = BitmapTarget2D;

            // Set D2D text anti-alias mode to Grayscale to ensure proper rendering of text on intermediate surfaces.
            d2dContext.TextAntialiasMode = SharpDX.Direct2D1.TextAntialiasMode.Grayscale;

            #endregion
        }
Beispiel #12
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));
        }