static void Main()
        {
            #region Direct3D Initialization
            // Create the window to render to
            Form1 form = new Form1();
            form.Text = "D3DRendering - Initialize D3D 11.1";
            form.Width = 640;
            form.Height = 480;

            // Create the device and swapchain
            Device1 device;
            SwapChain1 swapChain;

            // First create a regular D3D11 device
            using (
                var device11 = new Device(
                    SharpDX.Direct3D.DriverType.Hardware,
                    DeviceCreationFlags.None,
                    new [] {
                        SharpDX.Direct3D.FeatureLevel.Level_11_1,
                        SharpDX.Direct3D.FeatureLevel.Level_11_0,
                    }))
            {
                // Query device for the Device1 interface (ID3D11Device1)
                device = device11.QueryInterfaceOrNull<Device1>();

                if (device == null)
                    throw new NotSupportedException("SharpDX.Direct3D11.Device1 is not supported");
            }

            // Rather than create a new DXGI Factory we should reuse
            // the one that has been used internally to create the device
            using (var dxgi = device.QueryInterface<SharpDX.DXGI.Device2>())
            using (var adapter = dxgi.Adapter)
            using (var factory = adapter.GetParent<Factory2>())
            {
                var desc1 = new SwapChainDescription1()
                {
                    Width = form.ClientSize.Width,
                    Height = form.ClientSize.Height,
                    Format = Format.R8G8B8A8_UNorm,
                    Stereo = false,
                    SampleDescription = new SampleDescription(1, 0),
                    Usage = Usage.BackBuffer | Usage.RenderTargetOutput,
                    BufferCount = 1,
                    Scaling = Scaling.Stretch,
                    SwapEffect = SwapEffect.Discard,
                };

                swapChain = new SwapChain1(factory,
                    device,
                    form.Handle,
                    ref desc1,
                    new SwapChainFullScreenDescription()
                    {
                        RefreshRate = new Rational(60, 1),
                        Scaling = DisplayModeScaling.Centered,
                        Windowed = true
                    },
                    // Restrict output to specific Output (monitor)
                    null);
            }

            // Create references to backBuffer and renderTargetView
            var backBuffer = Texture2D.FromSwapChain<Texture2D>(swapChain, 0);
            var renderTargetView = new RenderTargetView(device, backBuffer);

            #endregion

            #region Render loop

            // Create Clock and FPS counters
            var clock = new System.Diagnostics.Stopwatch();
            var clockFrequency = (double)System.Diagnostics.Stopwatch.Frequency;
            clock.Start();
            var deltaTime = 0.0;
            var fpsTimer = new System.Diagnostics.Stopwatch();
            fpsTimer.Start();
            var fps = 0.0;
            int fpsFrames = 0;

            // Create and run the render loop
            RenderLoop.Run(form, () =>
            {
                // Time in seconds
                var totalSeconds = clock.ElapsedTicks / clockFrequency;

                #region FPS and title update
                fpsFrames++;
                if (fpsTimer.ElapsedMilliseconds > 1000)
                {
                    fps = 1000.0 * fpsFrames / fpsTimer.ElapsedMilliseconds;

                    // Update window title with FPS once every second
                    form.Text = string.Format("D3DRendering D3D11.1 - FPS: {0:F2} ({1:F2}ms/frame)", fps, (float)fpsTimer.ElapsedMilliseconds / fpsFrames);

                    // Restart the FPS counter
                    fpsTimer.Reset();
                    fpsTimer.Start();
                    fpsFrames = 0;
                }
                #endregion

                // Execute rendering commands here...
                device.ImmediateContext.ClearRenderTargetView(
                    renderTargetView,
                    Color.LightBlue);

                // Present the frame
                swapChain.Present(0, PresentFlags.None, new PresentParameters());

                // Determine the time it took to render the frame
                deltaTime = (clock.ElapsedTicks / clockFrequency) - totalSeconds;
            });
            #endregion

            #region Direct3D Cleanup

            // Release the device and any other resources created
            renderTargetView.Dispose();
            backBuffer.Dispose();
            device.Dispose();
            swapChain.Dispose();

            #endregion
        }
 protected override SharpDX.DXGI.SwapChain2 CreateSwapChain(SharpDX.DXGI.Factory2 factory, SharpDX.Direct3D11.Device1 device, SharpDX.DXGI.SwapChainDescription1 desc)
 {
     // Creates a SwapChain from a CoreWindow pointer
     using (var comWindow = new ComObject(window))
     using (var swapChain1 = new SwapChain1(factory, device, comWindow, ref desc))
         return swapChain1.QueryInterface<SwapChain2>();
 }
Example #3
0
        /// <summary>
        /// Create all view resources.
        /// </summary>
        Tuple <D3D11.Texture2D, D3D11.RenderTargetView, D3D11.Texture2D, D3D11.DepthStencilView, SharpDX.Mathematics.Interop.RawViewportF, Size2, DpiScaling> IRenderLoopHost.OnRenderLoop_CreateViewResources(EngineDevice device)
        {
            //Get references to current render device
            m_device        = device.DeviceD3D11_1;
            m_deviceContext = m_device.ImmediateContext;

            // Create swapchain and dummy form
            m_swapChain = GraphicsHelper.CreateSwapChainForFullScreen(
                m_dummyForm,
                m_targetOutput, m_targetOutputMode,
                device, m_renderLoop.ViewConfiguration);

            // Take width and height out of the render target
            m_renderTarget     = D3D11.Texture2D.FromSwapChain <D3D11.Texture2D>(m_swapChain, 0);
            m_renderTargetView = new D3D11.RenderTargetView(m_device, m_renderTarget);

            //Create the depth buffer
            m_renderTargetDepth     = GraphicsHelper.CreateDepthBufferTexture(device, m_targetOutputMode.PixelWidth, m_targetOutputMode.PixelHeight, m_renderLoop.ViewConfiguration);
            m_renderTargetDepthView = new D3D11.DepthStencilView(m_device, m_renderTargetDepth);

            //Define the viewport for rendering
            SharpDX.Mathematics.Interop.RawViewportF viewPort = GraphicsHelper.CreateDefaultViewport(m_targetOutputMode.PixelWidth, m_targetOutputMode.PixelHeight);

            //Return all generated objects
            return(Tuple.Create(m_renderTarget, m_renderTargetView, m_renderTargetDepth, m_renderTargetDepthView, viewPort, new Size2(m_targetOutputMode.PixelWidth, m_targetOutputMode.PixelHeight), DpiScaling.Default));
        }
Example #4
0
        private void CreateSwapChain(IntPtr window, bool vsync)
        {
            using (SharpDX.DXGI.Factory4 factory = new Factory4())
            {
                //SharpDX.DXGI.Adapter adapter = factory.GetAdapterByLuid(_dev.AdapterLuid);
                //System.Console.WriteLine($"  Adapter: {adapter.Description.Description}");
                System.Console.WriteLine($"  Adapter: {factory.Adapters[0].Description.Description}");

                if (!vsync)
                {
                    using (SharpDX.DXGI.Factory5 factory5 = factory.QueryInterface <Factory5>())
                    {
                        if (factory5 != null)
                        {
                            SharpDX.Mathematics.Interop.RawBool tearing = false;
                            GCHandle pinnedInt = GCHandle.Alloc(tearing, GCHandleType.Pinned);
                            IntPtr   pointer   = pinnedInt.AddrOfPinnedObject();

                            factory5.CheckFeatureSupport(SharpDX.DXGI.Feature.PresentAllowTearing, pointer, System.Runtime.InteropServices.Marshal.SizeOf(tearing));
                            if (tearing != false)
                            {
                                _swapChainFlags = SharpDX.DXGI.SwapChainFlags.AllowTearing;
                                _presentFlags   = SharpDX.DXGI.PresentFlags.AllowTearing;
                            }

                            pinnedInt.Free();
                        }
                    }

                    _syncInterval = 0;
                }
                else
                {
                    _syncInterval = 1;
                }

                SharpDX.DXGI.SwapChainDescription1 desc = new SharpDX.DXGI.SwapChainDescription1();
                desc.Width             = 0;
                desc.Height            = 0;
                desc.Format            = SharpDX.DXGI.Format.R8G8B8A8_UNorm;
                desc.Stereo            = false;
                desc.SampleDescription = new SampleDescription {
                    Count = 1, Quality = 0
                };
                desc.Usage       = SharpDX.DXGI.Usage.RenderTargetOutput;
                desc.BufferCount = FrameCount;
                desc.Scaling     = SharpDX.DXGI.Scaling.Stretch;
                desc.SwapEffect  = SharpDX.DXGI.SwapEffect.FlipDiscard;
                desc.AlphaMode   = SharpDX.DXGI.AlphaMode.Unspecified;
                desc.Flags       = _swapChainFlags;

                using (SharpDX.DXGI.SwapChain1 swapChain = new SharpDX.DXGI.SwapChain1(factory, _queue, window, ref desc))
                {
                    factory.MakeWindowAssociation(window, WindowAssociationFlags.IgnoreAltEnter);
                    _swapChain = swapChain.QueryInterface <SharpDX.DXGI.SwapChain3>();
                }
            }
        }
 /// <summary>
 /// Disposes all loaded view resources.
 /// </summary>
 void IRenderLoopHost.OnRenderLoop_DisposeViewResources(EngineDevice engineDevice)
 {
     m_renderTargetDepth      = GraphicsHelper.DisposeObject(m_renderTargetDepth);
     m_depthBuffer            = GraphicsHelper.DisposeObject(m_depthBuffer);
     m_renderTargetView       = GraphicsHelper.DisposeObject(m_renderTargetView);
     m_backBuffer             = GraphicsHelper.DisposeObject(m_backBuffer);
     m_backBufferMultisampled = GraphicsHelper.DisposeObject(m_backBufferMultisampled);
     m_swapChain = GraphicsHelper.DisposeObject(m_swapChain);
 }
Example #6
0
        void Initialize(ComObject coreWindow, AntiAliasingMode antiAliasingMode)
        {
            InitializeInner(antiAliasingMode);

            var swapChainDesc = device.CreateSwapChainDescription();

            DXGI.Factory2 factory = device.QueryInterface <DXGI.Device1>().Adapter.GetParent <DXGI.Factory2>();
            swapChain = new DXGI.SwapChain1(factory, device, coreWindow, ref swapChainDesc);
        }
        protected override SharpDX.DXGI.SwapChain1 CreateSwapChain(SharpDX.DXGI.Factory2 factory, SharpDX.Direct3D11.Device1 device, SharpDX.DXGI.SwapChainDescription1 desc)
        {
            // Creates the swap chain for XAML composition
            var swapChain = new SwapChain1(factory, device, ref desc);

            // Associate the SwapChainBackgroundPanel with the swap chain
            nativeBackgrounPanel.SwapChain = swapChain;

            return swapChain;
        }
Example #8
0
 public void InitializeDevice(ComObject coreWindow)
 {
     D3Device = DirectXTools.CreateD3Device();
     {
         RenderTarget = DirectXTools.CreateRenderTarget(Direct2DFactory, D3Device);
         _solidBrush  = new Direct2D1.SolidColorBrush(RenderTarget, Color.Black);
         SwapChain    = DirectXTools.CreateSwapChainForCoreWindow(D3Device, coreWindow);
         DirectXTools.CreateDeviceSwapChainBitmap(SwapChain, RenderTarget);
         Bitmaps.SetRenderTarget(RenderTarget);
         TextLayouts.SetRenderTarget(RenderTarget);
     }
 }
Example #9
0
 public void InitializeDevice(IntPtr windowHandle)
 {
     D3Device = DirectXTools.CreateD3Device();
     {
         RenderTarget = DirectXTools.CreateRenderTarget(Direct2DFactory, D3Device);
         _solidBrush  = new Direct2D1.SolidColorBrush(RenderTarget, Color.Black);
         SwapChain    = DirectXTools.CreateSwapChainForHwnd(D3Device, windowHandle);
         DirectXTools.CreateDeviceSwapChainBitmap(SwapChain, RenderTarget);
         Bitmaps.SetRenderTarget(RenderTarget);
         TextLayouts.SetRenderTarget(RenderTarget);
     }
 }
Example #10
0
        /// <summary>
        /// Disposes all loaded view resources.
        /// </summary>
        void IRenderLoopHost.OnRenderLoop_DisposeViewResources(EngineDevice device)
        {
            m_factory             = null;
            m_renderDevice        = null;
            m_renderDeviceContext = null;

            m_renderTargetDepth = GraphicsHelper.DisposeObject(m_renderTargetDepth);
            m_depthBuffer       = GraphicsHelper.DisposeObject(m_depthBuffer);
            m_renderTarget      = GraphicsHelper.DisposeObject(m_renderTarget);
            m_backBuffer        = GraphicsHelper.DisposeObject(m_backBuffer);
            m_swapChain         = GraphicsHelper.DisposeObject(m_swapChain);
        }
Example #11
0
 public void InitializeDeviceGdiCompatible(IntPtr windowHandle, int width, int height)
 {
     using (var d3device = DirectXTools.CreateD3Device())
     {
         RenderTarget = DirectXTools.CreateRenderTarget(Direct2DFactory, d3device);
         _solidBrush  = new Direct2D1.SolidColorBrush(RenderTarget, Color.Black);
         SwapChain    = DirectXTools.CreateSwapChainForHwnd(d3device, windowHandle);
         //DirectXTools.CreateDeviceSwapChainBitmap(SwapChain, RenderTarget);
         DirectXTools.CreateDeviceContextCPUBitmap(RenderTarget, width, height);
         Bitmaps.SetRenderTarget(RenderTarget);
         TextLayouts.SetRenderTarget(RenderTarget);
     }
 }
Example #12
0
        public BasicCapture(IDirect3DDevice d, GraphicsCaptureItem i)
        {
            item      = i;
            device    = d;
            d3dDevice = Direct3D11Helper.CreateSharpDXDevice(device);

            var size = item.Size;

            if (size.Height == 0 || size.Width == 0)
            {
                size = new SizeInt32()
                {
                    Height = 1, Width = 1
                }
            }
            ;

            var dxgiFactory = new SharpDX.DXGI.Factory2();
            var description = new SharpDX.DXGI.SwapChainDescription1()
            {
                Width             = size.Width,
                Height            = size.Height,
                Format            = SharpDX.DXGI.Format.B8G8R8A8_UNorm,
                Stereo            = false,
                SampleDescription = new SharpDX.DXGI.SampleDescription()
                {
                    Count   = 1,
                    Quality = 0
                },
                Usage       = SharpDX.DXGI.Usage.RenderTargetOutput,
                BufferCount = 2,
                Scaling     = SharpDX.DXGI.Scaling.Stretch,
                SwapEffect  = SharpDX.DXGI.SwapEffect.FlipSequential,
                AlphaMode   = SharpDX.DXGI.AlphaMode.Premultiplied,
                Flags       = SharpDX.DXGI.SwapChainFlags.None
            };

            swapChain = new SharpDX.DXGI.SwapChain1(dxgiFactory, d3dDevice, ref description);

            framePool = Direct3D11CaptureFramePool.Create(
                device,
                DirectXPixelFormat.B8G8R8A8UIntNormalized,
                2,
                size);
            session  = framePool.CreateCaptureSession(i);
            lastSize = size;

            framePool.FrameArrived += OnFrameArrived;
        }
Example #13
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;
        }
        public RenderController(IntPtr windowHandle)
        {
            writeFactory = new SharpDX.DirectWrite.Factory();

            SharpDX.Direct3D11.Device defaultDevice = new SharpDX.Direct3D11.Device
                                                      (
                DriverType.Hardware,
                DeviceCreationFlags.Debug | DeviceCreationFlags.BgraSupport
                                                      );

            device = defaultDevice.QueryInterface <SharpDX.Direct3D11.Device1>();
            SharpDX.DXGI.Device2  dxgiDevice2  = device.QueryInterface <SharpDX.DXGI.Device2>();
            SharpDX.DXGI.Adapter  dxgiAdapter  = dxgiDevice2.Adapter;
            SharpDX.DXGI.Factory2 dxgiFactory2 = dxgiAdapter.GetParent <SharpDX.DXGI.Factory2>();

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

            swapChain  = new SwapChain1(dxgiFactory2, device, windowHandle, ref description);
            backBuffer = Surface.FromSwapChain(swapChain, 0);

            d2dDevice  = new SharpDX.Direct2D1.Device(dxgiDevice2);
            d2dContext = new SharpDX.Direct2D1.DeviceContext(d2dDevice, SharpDX.Direct2D1.DeviceContextOptions.None);
            properties = new BitmapProperties1
                         (
                new SharpDX.Direct2D1.PixelFormat
                (
                    SharpDX.DXGI.Format.B8G8R8A8_UNorm,
                    SharpDX.Direct2D1.AlphaMode.Premultiplied
                ),
                0, 0, BitmapOptions.Target | BitmapOptions.CannotDraw
                         );
            d2dTarget         = new Bitmap1(d2dContext, backBuffer, properties);
            d2dContext.Target = d2dTarget;

            canDraw = true;
        }
Example #15
0
        public void InitializeDevice(int width, int height, object swapChainPanel)
        {
            var nativePanel = ComObject.As <DXGI.ISwapChainPanelNative>(swapChainPanel);

            Debug.Assert(nativePanel != null, $"{nameof(swapChainPanel)} should not be null.");

            D3Device = DirectXTools.CreateD3Device();
            {
                RenderTarget          = DirectXTools.CreateRenderTarget(Direct2DFactory, D3Device);
                _solidBrush           = new Direct2D1.SolidColorBrush(RenderTarget, Color.Black);
                SwapChain             = DirectXTools.CreateSwapChain(width, height, D3Device);
                nativePanel.SwapChain = SwapChain;
                DirectXTools.CreateDeviceSwapChainBitmap(SwapChain, RenderTarget);
                Bitmaps.SetRenderTarget(RenderTarget);
                TextLayouts.SetRenderTarget(RenderTarget);
            }
        }
Example #16
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;
         }
     }
 }
Example #17
0
        /// <summary>
        /// Create all view resources.
        /// </summary>
        Tuple <D3D11.Texture2D, D3D11.RenderTargetView, D3D11.Texture2D, D3D11.DepthStencilView, SharpDX.Mathematics.Interop.RawViewportF, Size2, DpiScaling> IRenderLoopHost.OnRenderLoop_CreateViewResources(EngineDevice device)
        {
            int width  = this.Width;
            int height = this.Height;

            if (width <= Constants.MIN_VIEW_WIDTH)
            {
                width = Constants.MIN_VIEW_WIDTH;
            }
            if (height <= Constants.MIN_VIEW_HEIGHT)
            {
                height = Constants.MIN_VIEW_HEIGHT;
            }

            //Get all factories
            m_factory = device.FactoryDxgi;

            //Get all devices
            m_renderDevice        = device.DeviceD3D11_1;
            m_renderDeviceContext = m_renderDevice.ImmediateContext;

            //Create the swap chain and the render target
            m_swapChain    = GraphicsHelper.CreateSwapChainForWinForms(this, device, m_renderLoop.ViewConfiguration);
            m_backBuffer   = D3D11.Texture2D.FromSwapChain <D3D11.Texture2D>(m_swapChain, 0);
            m_renderTarget = new D3D11.RenderTargetView(m_renderDevice, m_backBuffer);

            //Create the depth buffer
            m_depthBuffer       = GraphicsHelper.CreateDepthBufferTexture(device, width, height, m_renderLoop.ViewConfiguration);
            m_renderTargetDepth = new D3D11.DepthStencilView(m_renderDevice, m_depthBuffer);

            //Define the viewport for rendering
            SharpDX.Mathematics.Interop.RawViewportF viewPort = GraphicsHelper.CreateDefaultViewport(width, height);

            // Query for current dpi value
            DpiScaling dpiScaling = DpiScaling.Default;

            using (Graphics graphics = this.CreateGraphics())
            {
                dpiScaling.DpiX = graphics.DpiX;
                dpiScaling.DpiY = graphics.DpiY;
            }

            //Return all generated objects
            return(Tuple.Create(m_backBuffer, m_renderTarget, m_depthBuffer, m_renderTargetDepth, viewPort, new Size2(width, height), dpiScaling));
        }
Example #18
0
        /// <summary>
        /// Disposes all loaded view resources.
        /// </summary>
        void IRenderLoopHost.OnRenderLoop_DisposeViewResources(EngineDevice device)
        {
            // Switch to fullscreen
            if (m_isInFullscreen)
            {
                m_isInFullscreen = false;
                m_swapChain.SetFullscreenState(false, null);
            }

            m_renderTargetDepthView = GraphicsHelper.DisposeObject(m_renderTargetDepthView);
            m_renderTargetDepth     = GraphicsHelper.DisposeObject(m_renderTargetDepth);
            m_renderTargetView      = GraphicsHelper.DisposeObject(m_renderTargetView);
            m_renderTarget          = GraphicsHelper.DisposeObject(m_renderTarget);
            m_swapChain             = GraphicsHelper.DisposeObject(m_swapChain);

            m_device        = null;
            m_deviceContext = null;
        }
        /// <summary>
        /// Create all view resources.
        /// </summary>
        Tuple <D3D11.Texture2D, D3D11.RenderTargetView, D3D11.Texture2D, D3D11.DepthStencilView, SharpDX.ViewportF, Size2, DpiScaling> IRenderLoopHost.OnRenderLoop_CreateViewResources(EngineDevice engineDevice)
        {
            m_backBufferMultisampled = null;

            Size2 viewSize = GetTargetRenderPixelSize();

            // Create the SwapChain and associate it with the SwapChainBackgroundPanel
            m_swapChain               = GraphicsHelper.CreateSwapChainForComposition(engineDevice, viewSize.Width, viewSize.Height, m_renderLoop.ViewConfiguration);
            m_targetPanel.SwapChain   = m_swapChain;
            m_compositionScaleChanged = true;

            // Get the backbuffer from the SwapChain
            m_backBuffer = D3D11.Texture2D.FromSwapChain <D3D11.Texture2D>(m_swapChain, 0);

            // Define the render target (in case of multisample an own render target)
            D3D11.Texture2D backBufferForRenderloop = null;
            if (m_renderLoop.ViewConfiguration.AntialiasingEnabled)
            {
                m_backBufferMultisampled = GraphicsHelper.CreateRenderTargetTexture(engineDevice, viewSize.Width, viewSize.Height, m_renderLoop.ViewConfiguration);
                m_renderTargetView       = new D3D11.RenderTargetView(engineDevice.DeviceD3D11, m_backBufferMultisampled);
                backBufferForRenderloop  = m_backBufferMultisampled;
            }
            else
            {
                m_renderTargetView      = new D3D11.RenderTargetView(engineDevice.DeviceD3D11, m_backBuffer);
                backBufferForRenderloop = m_backBuffer;
            }

            //Create the depth buffer
            m_depthBuffer       = GraphicsHelper.CreateDepthBufferTexture(engineDevice, viewSize.Width, viewSize.Height, m_renderLoop.ViewConfiguration);
            m_renderTargetDepth = new D3D11.DepthStencilView(engineDevice.DeviceD3D11, m_depthBuffer);

            //Define the viewport for rendering
            SharpDX.ViewportF viewPort = GraphicsHelper.CreateDefaultViewport(viewSize.Width, viewSize.Height);
            m_lastRefreshTargetSize = new Size(viewSize.Width, viewSize.Height);

            DpiScaling dpiScaling = new DpiScaling();

            dpiScaling.DpiX = (float)(96.0 * m_targetPanel.CompositionScaleX);
            dpiScaling.DpiY = (float)(96.0 * m_targetPanel.CompositionScaleY);

            return(Tuple.Create(backBufferForRenderloop, m_renderTargetView, m_depthBuffer, m_renderTargetDepth, viewPort, viewSize, dpiScaling));
        }
Example #20
0
        private void InitializeDirectX(GameWindow gameWindow)
        {
            using (var defaultDevice = new SharpDX.Direct3D11.Device(DriverType.Hardware, DeviceCreationFlags.BgraSupport))
            {
                _d3dDevice = defaultDevice.QueryInterface <SharpDX.Direct3D11.Device1>();
            }

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

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

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

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

            _dwriteFactory   = new SharpDX.DirectWrite.Factory1();
            _wicFactory      = new ImagingFactory();
            _formatConverter = new FormatConverter(_wicFactory);
            _deviceContext.TextAntialiasMode = SharpDX.Direct2D1.TextAntialiasMode.Cleartype;
        }
Example #21
0
        private void InitializeD3D()
        {
            using (D3D11.Device defaultDevice = new D3D11.Device(D3D.DriverType.Hardware, D3D11.DeviceCreationFlags.Debug))
                this.device = defaultDevice.QueryInterface <D3D11.Device2>();
            this.deviceContext = this.device.ImmediateContext2;

            DXGI.SwapChainDescription1 swapChainDescription = new DXGI.SwapChainDescription1()
            {
                AlphaMode         = DXGI.AlphaMode.Ignore,
                BufferCount       = 2,
                Format            = DXGI.Format.R8G8B8A8_UNorm,
                Height            = (int)(this.swapChainPanel.RenderSize.Height),
                Width             = (int)(this.swapChainPanel.RenderSize.Width),
                SampleDescription = new DXGI.SampleDescription(1, 0),
                Scaling           = SharpDX.DXGI.Scaling.Stretch,
                Stereo            = false,
                SwapEffect        = DXGI.SwapEffect.FlipSequential,
                Usage             = DXGI.Usage.RenderTargetOutput
            };

            using (DXGI.Device3 dxgiDevice3 = this.device.QueryInterface <DXGI.Device3>())
                using (DXGI.Factory3 dxgiFactory3 = dxgiDevice3.Adapter.GetParent <DXGI.Factory3>())
                {
                    DXGI.SwapChain1 swapChain1 = new DXGI.SwapChain1(dxgiFactory3, this.device, ref swapChainDescription);
                    this.swapChain = swapChain1.QueryInterface <DXGI.SwapChain2>();
                }

            using (DXGI.ISwapChainPanelNative nativeObject = ComObject.As <DXGI.ISwapChainPanelNative>(this.swapChainPanel))
                nativeObject.SwapChain = this.swapChain;

            this.backBufferTexture = this.swapChain.GetBackBuffer <D3D11.Texture2D>(0);
            this.backBufferView    = new D3D11.RenderTargetView(this.device, this.backBufferTexture);

            deviceContext.Rasterizer.SetViewport(0, 0, (int)swapChainPanel.ActualWidth, (int)swapChainPanel.ActualHeight);

            CompositionTarget.Rendering    += CompositionTarget_Rendering;
            Application.Current.Suspending += Current_Suspending;

            isDXInitialized = true;
        }
        public Tuple <D3D11.Texture2D, D3D11.RenderTargetView, D3D11.Texture2D, D3D11.DepthStencilView, SDM.RawViewportF, Size2, DpiScaling> OnRenderLoop_CreateViewResources(EngineDevice device)
        {
            // Get the pixel size of the screen
            Size2 viewSize = GetTargetRenderPixelSize();

            // Create the SwapChain and associate it with the SwapChainBackgroundPanel
            using (SharpDX.ComObject targetWindowCom = new SharpDX.ComObject(m_targetWindow))
            {
                m_swapChain = GraphicsHelper.CreateSwapChainForCoreWindow(device, targetWindowCom, viewSize.Width, viewSize.Height, m_renderLoop.ViewConfiguration);
            }

            // Get the backbuffer from the SwapChain
            m_backBuffer = D3D11.Texture2D.FromSwapChain <D3D11.Texture2D>(m_swapChain, 0);

            // Define the render target (in case of multisample an own render target)
            D3D11.Texture2D backBufferForRenderloop = null;
            if (m_renderLoop.ViewConfiguration.AntialiasingEnabled)
            {
                m_backBufferMultisampled = GraphicsHelper.CreateRenderTargetTexture(device, viewSize.Width, viewSize.Height, m_renderLoop.ViewConfiguration);
                m_renderTargetView       = new D3D11.RenderTargetView(device.DeviceD3D11_1, m_backBufferMultisampled);
                backBufferForRenderloop  = m_backBufferMultisampled;
            }
            else
            {
                m_renderTargetView      = new D3D11.RenderTargetView(device.DeviceD3D11_1, m_backBuffer);
                backBufferForRenderloop = m_backBuffer;
            }

            //Create the depth buffer
            m_depthBuffer       = GraphicsHelper.CreateDepthBufferTexture(device, viewSize.Width, viewSize.Height, m_renderLoop.ViewConfiguration);
            m_renderTargetDepth = new D3D11.DepthStencilView(device.DeviceD3D11_1, m_depthBuffer);

            //Define the viewport for rendering
            SharpDX.Mathematics.Interop.RawViewportF viewPort = GraphicsHelper.CreateDefaultViewport(viewSize.Width, viewSize.Height);
            m_lastRefreshTargetSize = new Size(viewSize.Width, viewSize.Height);

            return(Tuple.Create(backBufferForRenderloop, m_renderTargetView, m_depthBuffer, m_renderTargetDepth, viewPort, viewSize, m_dpiScaling));
        }
Example #23
0
        /// <summary>
        /// Initializes a new instance of the <see cref="FormRenderer"/> class.
        /// </summary>
        /// <param name="form">The form.</param>
        public FormRenderer(Form1 form)
        {
            this.form = form;
#if DEBUG
            var creationFlags = D3D11.DeviceCreationFlags.BgraSupport | D3D11.DeviceCreationFlags.Debug;
            var debugFactory  = true;
#else
            var creationFlags = D3D11.DeviceCreationFlags.BgraSupport;
            var debugFactory  = false;
#endif

            this.device = new D3D11.Device(D3D.DriverType.Hardware, creationFlags);

#if DEBUG
            this.deviceDebug = new D3D11.DeviceDebug(this.device);
#endif

            using (var dxgiDevice = this.device.QueryInterface <DXGI.Device>())
            {
                using (var dxgiFactory = new DXGI.Factory2(debugFactory))
                {
                    var desc = new DXGI.SwapChainDescription1()
                    {
                        BufferCount       = 2,
                        AlphaMode         = DXGI.AlphaMode.Premultiplied,
                        SampleDescription = new DXGI.SampleDescription(1, 0),
                        Usage             = DXGI.Usage.RenderTargetOutput,
                        SwapEffect        = DXGI.SwapEffect.FlipDiscard,
                        Format            = DXGI.Format.B8G8R8A8_UNorm,
                        Width             = form.Width,
                        Height            = form.Height,
                    };

                    this.swapChain = new DXGI.SwapChain1(dxgiFactory, dxgiDevice, ref desc, null);

                    this.deviceComp        = new DComp.Device(dxgiDevice);
                    this.compositionTarget = DComp.Target.FromHwnd(this.deviceComp, form.Handle, true);

                    using (var visual = new DComp.Visual(this.deviceComp))
                    {
                        visual.Content = this.swapChain;
                        this.compositionTarget.Root = visual;
                    }

                    this.deviceComp.Commit();
                }
            }

            using (var device = this.device.QueryInterface <DXGI.Device>())
            {
                this.device2d = new D2D.Device(this.factory2d, device);
            }

            this.deviceContext2D = new D2D.DeviceContext(this.device2d, D2D.DeviceContextOptions.None)
            {
                DotsPerInch   = this.factory2d.DesktopDpi,
                AntialiasMode = D2D.AntialiasMode.PerPrimitive,
            };

            this.CreateResources();
        }
        /// <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
        }
Example #25
0
        private void SwapChainPanel_OnLoaded(object sender, RoutedEventArgs e)
        {
            using (var defDevice = new D3D.Device(DriverType.Hardware, D3D.DeviceCreationFlags.Debug))
            {
                _device = defDevice.QueryInterface <D3D.Device3>();
            }
            _context = _device.ImmediateContext3;

            var pixelScale    = DisplayInformation.GetForCurrentView().LogicalDpi / 96.0f;
            var swapChainDesc = new DXGI.SwapChainDescription1()
            {
                AlphaMode         = DXGI.AlphaMode.Premultiplied,
                BufferCount       = 2,
                Flags             = DXGI.SwapChainFlags.None,
                Format            = DXGI.Format.B8G8R8A8_UNorm,
                Width             = (int)(panel.RenderSize.Width * pixelScale),
                Height            = (int)(panel.RenderSize.Height * pixelScale),
                SampleDescription = new DXGI.SampleDescription(1, 0),
                Scaling           = DXGI.Scaling.Stretch,
                Stereo            = false,
                SwapEffect        = DXGI.SwapEffect.FlipSequential,
                Usage             = DXGI.Usage.BackBuffer | DXGI.Usage.RenderTargetOutput
            };

            using (var dxgiDevice = _device.QueryInterface <DXGI.Device3>())
            {
                var factory = dxgiDevice.Adapter.GetParent <DXGI.Factory4>();
                using (var tmpSwapChain = new DXGI.SwapChain1(factory, _device, ref swapChainDesc))
                {
                    _swapChain = tmpSwapChain.QueryInterface <DXGI.SwapChain3>();
                }
            }

            using (var nativeObject = ComObject.As <DXGI.ISwapChainPanelNative>(panel))
            {
                nativeObject.SwapChain = _swapChain;
            }

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

            _backBuffer = D3D.Resource.FromSwapChain <D3D.Texture2D>(_swapChain, 0);
            _renderView = new D3D.RenderTargetView1(_device, _backBuffer);

            var viewport = new ViewportF(0, 0, (float)panel.RenderSize.Width, (float)panel.RenderSize.Height, 0.0f, 1.0f);

            _context.Rasterizer.SetViewport(viewport);

            ShaderBytecode shaderBytecode;

            using (shaderBytecode = ShaderBytecode.CompileFromFile("shaders.hlsl", "vs", "vs_5_0", ShaderFlags.Debug))
            {
                _vertexShader = new D3D.VertexShader(_device, shaderBytecode);
            }

            using (var byteCode = ShaderBytecode.CompileFromFile(@"shaders.hlsl", "ps", "ps_5_0", ShaderFlags.Debug))
            {
                _pixelShader = new D3D.PixelShader(_device, byteCode);
            }

            D3D.InputElement[] inputElements =
            {
                new D3D.InputElement("POSITION", 0, DXGI.Format.R32G32B32A32_Float, 0, 0),
            };
            _inputLayout = new D3D.InputLayout(_device, shaderBytecode, inputElements);

            _vertices = new[]
            {
                new Vector4(-0.5f, 0.0f, 0.5f, 1.0f),
                new Vector4(0.0f, 0.5f, 0.5f, 1.0f),
                new Vector4(0.5f, 0.0f, 0.5f, 1.0f),
            };
            _vertexBuffer  = D3D.Buffer.Create(_device, D3D.BindFlags.VertexBuffer, _vertices);
            _vertexBinding = new D3D.VertexBufferBinding(_vertexBuffer, Utilities.SizeOf <Vector4>(), 0);

            _constantBuffer = new SharpDX.Direct3D11.Buffer(
                _device,
                Utilities.SizeOf <SharpDX.Matrix>(),
                D3D.ResourceUsage.Default,
                D3D.BindFlags.ConstantBuffer,
                D3D.CpuAccessFlags.None,
                D3D.ResourceOptionFlags.None,
                0);

            _timer = new Stopwatch();
            _timer.Start();

            CompositionTarget.Rendering += CompositionTarget_Rendering;
        }
Example #26
0
        private void InitSwapChain(int width, int height)
        {
            if (width <= 0 || height <= 0)
                throw new ArgumentException("panel must have a valid width or height");

            // Create swap chain for composition and bind to panel
            var desc = new SwapChainDescription1
                {
                    Width = width,
                    Height = height,
                    Format = Format.B8G8R8A8_UNorm,
                    Flags = SwapChainFlags.None,
                    BufferCount = 2,
                    AlphaMode = AlphaMode.Unspecified,
                    Stereo = false,
                    Scaling = Scaling.Stretch,
                    SampleDescription = { Count = 1, Quality = 0 },
                    SwapEffect = SwapEffect.FlipSequential,
                    Usage = Usage.RenderTargetOutput
                };

            _width = width;
            _height = height;

            var dxgiDev = ComObject.As<SharpDX.DXGI.Device1>(_device.NativePointer);
            var adapter = dxgiDev.Adapter;
            var fact = adapter.GetParent<SharpDX.DXGI.Factory2>();
            _swap = fact.CreateSwapChainForComposition(_device, ref desc, null);

            dxgiDev.MaximumFrameLatency = 1;
        }
        protected override SharpDX.DXGI.SwapChain2 CreateSwapChain(SharpDX.DXGI.Factory2 factory, SharpDX.Direct3D11.Device1 device, SharpDX.DXGI.SwapChainDescription1 desc)
        {
            // Creates the swap chain for XAML composition
            using (var swapChain1 = new SwapChain1(factory, device, ref desc))
            {
                var swapChain2 = swapChain1.QueryInterface<SwapChain2>();

                // Associate the SwapChainPanel with the swap chain
                nativePanel.SwapChain = swapChain2;

                // Returns the new swap chain
                return swapChain2;
            }
        }
Example #28
0
        public VideoRenderer(VideoTrack videoTrack, RendererOptions options)
        {
            VideoTrack = videoTrack;

            VideoFrameWidth     = options.VideoFrameWidth;
            VideoFrameHeight    = options.VideoFrameHeight;
            VideoFrameQueueSize = options.VideoFrameQueueSize;

            videoTrack.LocalVideoFrameProcessed += OnLocalVideoFrameProcessed;

            // _onMissedFrame = options.OnMissedFrame ?? OnMissedFrame;

            bool debug = options.CreationFlags.HasFlag(D3D11.DeviceCreationFlags.Debug);

            FactoryDXGI = new DXGI.Factory2(debug);

            // Find the requested adapter.
            using (var adapters = FactoryDXGI.Adapters.ToDisposableList())
            {
                var adapter = adapters.First(a => a.Description.VendorId == options.AdapterVendorId);

                Device3D = new D3D11.Device(adapter, options.CreationFlags, options.FeatureLevels);

                DeviceDXGI = Device3D.QueryInterface <DXGI.Device>();

                // We need to access D3D11 on multiple threads, so enable multi-threading
                ThreadLock3D = Device3D.ImmediateContext.QueryInterface <D3D11.Multithread>();
                ThreadLock3D.SetMultithreadProtected(true);

                if (options.PreviewWindowOptions != null)
                {
                    var width  = options.PreviewWindowOptions.Width ?? VideoFrameWidth;
                    var height = options.PreviewWindowOptions.Height ?? width * VideoFrameHeight / VideoFrameWidth;

                    _sdlWindow = new SdlWindow("WebRTC server preview", width, height);


                    // SwapChain description
                    var desc = new DXGI.SwapChainDescription1()
                    {
                        BufferCount       = 2,
                        AlphaMode         = DXGI.AlphaMode.Unspecified,
                        Format            = DXGI.Format.B8G8R8A8_UNorm,
                        Width             = VideoFrameWidth,
                        Height            = VideoFrameHeight,
                        Scaling           = DXGI.Scaling.Stretch,
                        Stereo            = false,
                        Flags             = DXGI.SwapChainFlags.AllowTearing | DXGI.SwapChainFlags.FrameLatencyWaitAbleObject,
                        Usage             = DXGI.Usage.RenderTargetOutput,
                        SampleDescription = new DXGI.SampleDescription(1, 0),
                        SwapEffect        = DXGI.SwapEffect.FlipDiscard,
                    };

                    SwapChain = new DXGI.SwapChain1(FactoryDXGI, Device3D, _sdlWindow.NativeHandle, ref desc);

                    using (var swapChain2 = SwapChain.QueryInterface <DXGI.SwapChain2>())
                    {
                        var value = swapChain2.MaximumFrameLatency;
                        swapChain2.MaximumFrameLatency = 1;
                    }
                }
            }
        }
        /// <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.
            SharpDX.Direct3D11.Device defaultDevice = new SharpDX.Direct3D11.Device(DriverType.Hardware, DeviceCreationFlags.Debug);

            // Query the default device for the supported device and context interfaces.
            device = defaultDevice.QueryInterface<SharpDX.Direct3D11.Device1>();
            context = device.ImmediateContext.QueryInterface<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);

            // Create the texture and render target that will hold our backbuffer.
            Texture2D backBufferTexture = Texture2D.FromSwapChain<Texture2D>(swapChain, 0);
            backBuffer = new RenderTargetView(device, backBufferTexture);

            backBufferTexture.Dispose();
        }
        /// <summary>
        /// Creates resources that depend on the current back buffer size.
        /// </summary>
        private void CreateSizeDependentResources()
        {
            this.ReleaseSizeDependentResources();

            if (swapChain != null)
            {
                swapChain.ResizeBuffers(2, (int)this.BackBufferSize.Width, (int)this.BackBufferSize.Height, Format.B8G8R8A8_UNorm, SwapChainFlags.None);
            }
            else
            {
                SwapChainDescription1 swapChainDescription = new SwapChainDescription1()
                {
                    Width = (int)this.BackBufferSize.Width,
                    Height = (int)this.BackBufferSize.Height,
                    Format = Format.B8G8R8A8_UNorm,
                    Stereo = false,
                    SampleDescription = new SampleDescription(1, 0),
                    Usage = Usage.BackBuffer | Usage.RenderTargetOutput,
                    BufferCount = 2,
                    Scaling = Scaling.Stretch,
                    SwapEffect = SwapEffect.FlipSequential,
                };

                using (SharpDX.DXGI.Device2 dxgiDevice2 = this.D3DDevice.QueryInterface<SharpDX.DXGI.Device2>())
                {
                    using (SharpDX.DXGI.Adapter dxgiAdapter = dxgiDevice2.Adapter)
                    {
                        using (SharpDX.DXGI.Factory2 dxgiFactory2 = dxgiAdapter.GetParent<SharpDX.DXGI.Factory2>())
                        {
                            swapChain = new SwapChain1(dxgiFactory2, this.D3DDevice, ref swapChainDescription);

                            if (this.backgroundPanel != null)
                            {
                                nativeBackgroundPanel.SwapChain = swapChain;
                            }
                            else if (this.panel != null)
                            {
                                nativePanel.SwapChain = swapChain;
                            }

                            dxgiDevice2.MaximumFrameLatency = 1;
                        }
                    }
                }
            }

            this.BackBuffer = Texture2D.FromSwapChain<Texture2D>(swapChain, 0);
            this.BackBufferView = new RenderTargetView(this.D3DDevice, this.BackBuffer);
            this.UpdateBackBufferSize();

            using (Texture2D depthBuffer = new Texture2D(this.D3DDevice, new Texture2DDescription()
            {
                Format = SharpDX.DXGI.Format.D24_UNorm_S8_UInt,
                ArraySize = 1,
                MipLevels = 1,
                Width = (int)this.BackBufferSize.Width,
                Height = (int)this.BackBufferSize.Height,
                SampleDescription = new SampleDescription(1, 0),
                BindFlags = BindFlags.DepthStencil,
            }))
            {
                this.DepthStencilView = new DepthStencilView(this.D3DDevice, depthBuffer, new DepthStencilViewDescription()
                {
                    Dimension = DepthStencilViewDimension.Texture2D
                });
            }

            ViewportF viewport = new ViewportF(0, 0, (float)this.BackBufferSize.Width, (float)this.BackBufferSize.Height, 0.0f, 1.0f);
            this.D3DContext.Rasterizer.SetViewport(viewport);
        }
Example #31
0
        private void SwapChainPanel_Loaded(object sender, RoutedEventArgs e)
        {
            // Create a new Direct3D hardware device and ask for Direct3D 11.2 support
            using (D3D11.Device defaultDevice = new D3D11.Device(D3D.DriverType.Hardware, D3D11.DeviceCreationFlags.Debug))
            {
                this.device = defaultDevice.QueryInterface <D3D11.Device2>();
            }

            // Save the context instance
            this.deviceContext = this.device.ImmediateContext2;

            Size2 sizeInPixels = RenderSizeToPixelSize(this.SwapChainPanel.RenderSize);

            // Properties of the swap chain
            DXGI.SwapChainDescription1 swapChainDescription = new DXGI.SwapChainDescription1()
            {
                // No transparency.
                AlphaMode = DXGI.AlphaMode.Ignore,
                // Double buffer.
                BufferCount = 2,
                // BGRA 32bit pixel format.
                Format = DXGI.Format.B8G8R8A8_UNorm,
                // Unlike in CoreWindow swap chains, the dimensions must be set.
                Height = sizeInPixels.Height,
                Width  = sizeInPixels.Width,
                // Default multisampling.
                SampleDescription = new DXGI.SampleDescription(1, 0),
                // In case the control is resized, stretch the swap chain accordingly.
                Scaling = DXGI.Scaling.Stretch,
                // No support for stereo display.
                Stereo = false,
                // Sequential displaying for double buffering.
                SwapEffect = DXGI.SwapEffect.FlipSequential,
                // This swapchain is going to be used as the back buffer.
                Usage = DXGI.Usage.BackBuffer | DXGI.Usage.RenderTargetOutput,
            };

            // Retrive the DXGI device associated to the Direct3D device.
            using (DXGI.Device3 dxgiDevice3 = this.device.QueryInterface <DXGI.Device3>())
            {
                // Get the DXGI factory automatically created when initializing the Direct3D device.
                using (DXGI.Factory3 dxgiFactory3 = dxgiDevice3.Adapter.GetParent <DXGI.Factory3>())
                {
                    // Create the swap chain and get the highest version available.
                    using (DXGI.SwapChain1 swapChain1 = new DXGI.SwapChain1(dxgiFactory3, this.device, ref swapChainDescription))
                    {
                        this.swapChain = swapChain1.QueryInterface <DXGI.SwapChain2>();
                    }
                }
            }

            // Obtain a reference to the native COM object of the SwapChainPanel.
            using (DXGI.ISwapChainPanelNative nativeObject = ComObject.As <DXGI.ISwapChainPanelNative>(this.SwapChainPanel))
            {
                // Set its swap chain.
                nativeObject.SwapChain = this.swapChain;
            }

            // Create a Texture2D from the existing swap chain to use as
            this.backBufferTexture = D3D11.Texture2D.FromSwapChain <D3D11.Texture2D>(this.swapChain, 0);
            this.backBufferView    = new D3D11.RenderTargetView(this.device, this.backBufferTexture);

            // This event is fired when the application requests a new frame from the DirectX interop controls.
            CompositionTarget.Rendering += CompositionTarget_Rendering;

            // Subscribe to the suspending event
            Application.Current.Suspending += Application_Suspending;

            // Mark our resources as initialized
            isDXInitialized = true;
        }
Example #32
0
            private void SetupScreenBuffers()
            {
                width = (int) window.Bounds.Width;
                height = (int) window.Bounds.Height;

                // If the swap chain already exists, resize it.
                if (swapChain != null)
                {
                    swapChain.ResizeBuffers(2, width, height, Format.B8G8R8A8_UNorm, SwapChainFlags.None);
                }
                    // Otherwise, create a new one.
                else
                {
                    // SwapChain description
                    var desc = new SwapChainDescription1
                                   {
                                       // Automatic sizing
                                       Width = width,
                                       Height = height,
                                       Format = Format.B8G8R8A8_UNorm,
                                       Stereo = false,
                                       SampleDescription = new SampleDescription(1, 0),
                                       Usage = Usage.BackBuffer | Usage.RenderTargetOutput,
                                       // Use two buffers to enable flip effect.
                                       BufferCount = 2,
                                       Scaling = Scaling.None,
                                       SwapEffect = SwapEffect.FlipSequential,
                                   };

                    // 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 = graphicsDevice.QueryInterface<Device2>())
                    using (Adapter dxgiAdapter = dxgiDevice2.Adapter)
                    using (var dxgiFactory2 = dxgiAdapter.GetParent<Factory2>())
                    {
                        // Creates a SwapChain from a CoreWindow pointer
                        using (var comWindow = new ComObject(window))
                            swapChain = dxgiFactory2.CreateSwapChainForCoreWindow(graphicsDevice, comWindow, ref desc, null);

                        // 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(Resource.FromSwapChain<Texture2D>(swapChain, 0));
                {
                    // Create a view interface on the rendertarget to use on bind.
                    renderTargetView = ToDispose(new RenderTargetView(graphicsDevice, backBuffer));
                }

                // Create a viewport descriptor of the full window size.
                var viewport = new Viewport(0, 0, width, height, 0.0f, 1.0f);

                // Set the current viewport using the descriptor.
                graphicsDevice.ImmediateContext.Rasterizer.SetViewports(viewport);
            }
Example #33
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();
        }
Example #34
0
 private void CreateSwapChain(ref SwapChainDescription1 swapChainDescription1, Factory4 factory)
 {
     using (var sc1 = new SwapChain1(factory, commandQueue, ref swapChainDescription1))
     {
         swapChain = Collect(sc1.QueryInterface<SwapChain3>());
         using (var comPtr = new ComObject(panel))
         {
             using (var native = comPtr.QueryInterface<ISwapChainPanelNative>())
             {
                 native.SwapChain = swapChain;
             }
         }
     }
 }
Example #35
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
        }
Example #36
0
        /// <summary>
        /// Create the swap chain used to store rendered scenes.
        /// </summary>
        /// <param name="windowHandle">The handle of the window that displays the game.</param>
        /// <param name="scWidth">The desired width of the swap chain.</param>
        /// <param name="scHeight">The desired height of the swap chain.</param>
        private void CreateSwapChain(IntPtr windowHandle, int scWidth, int scHeight)
        {
            SwapChainDescription1 scDescription = new SwapChainDescription1()
            {
                BufferCount = 1,
                Flags = SwapChainFlags.AllowModeSwitch,
                Format = Format.B8G8R8A8_UNorm,
                Height = scHeight,
                SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0),
                Scaling = Scaling.Stretch,
                Stereo = false,
                SwapEffect = SwapEffect.Discard,
                Usage = SharpDX.DXGI.Usage.BackBuffer | SharpDX.DXGI.Usage.RenderTargetOutput,
                Width = scWidth,
            };
            using (var dxgiDevice = Device3D.QueryInterface<SharpDX.DXGI.Device2>())
            using (var dxgiAdapter = dxgiDevice.Adapter)
            using (var dxgiFactory = dxgiAdapter.GetParent<SharpDX.DXGI.Factory2>())
            using (var output = dxgiAdapter.Outputs.First())
            {
                // Create a swap chain for a desktop application
                SwapChain = ToDispose(new SwapChain1(
                    dxgiFactory,
                    Device3D,
                    windowHandle,
                    ref scDescription,
                    CreateFullScreenDescription(),
                    null));

                // Retrieve the list of supported display modes
                DisplayModeList = output.GetDisplayModeList(scDescription.Format, DisplayModeEnumerationFlags.Scaling);
            }
        }
Example #37
0
        void Initialize(ComObject coreWindow, AntiAliasingMode antiAliasingMode)
        {
            InitializeInner(antiAliasingMode);

            var swapChainDesc = device.CreateSwapChainDescription();
            DXGI.Factory2 factory = device.QueryInterface<DXGI.Device1>().Adapter.GetParent<DXGI.Factory2>();
            swapChain = new DXGI.SwapChain1(factory, device, coreWindow, ref swapChainDesc);
        }
Example #38
0
        // 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);
            }
        }
Example #39
0
        private void SwapChainPanel_Loaded(object sender, RoutedEventArgs e)
        {
            var v = ApplicationView.GetForCurrentView();

            v.FullScreenSystemOverlayMode = FullScreenSystemOverlayMode.Minimal;
            v.TryEnterFullScreenMode();
#if DEBUG
            var debugLevel = D3D11.DeviceCreationFlags.Debug | D3D11.DeviceCreationFlags.BgraSupport;
#else
            var debugLevel = D3D11.DeviceCreationFlags.None | D3D11.DeviceCreationFlags.BgraSupport;
#endif
            using (D3D11.Device defaultDevice = new D3D11.Device(D3D.DriverType.Hardware, debugLevel))
            {
                this.device = defaultDevice.QueryInterface <D3D11.Device2>();
            }
            this.deviceContext = this.device.ImmediateContext2;
            float pixelScale = Windows.Graphics.Display.DisplayInformation.GetForCurrentView().LogicalDpi / 96.0f;

            DXGI.SwapChainDescription1 swapChainDescription = new DXGI.SwapChainDescription1()
            {
                AlphaMode         = DXGI.AlphaMode.Premultiplied,
                BufferCount       = 2,
                Format            = DXGI.Format.B8G8R8A8_UNorm,
                Height            = (int)(this.SwapChainPanel.RenderSize.Height * pixelScale),
                Width             = (int)(this.SwapChainPanel.RenderSize.Width * pixelScale),
                SampleDescription = new DXGI.SampleDescription(1, 0),
                Scaling           = DXGI.Scaling.Stretch,
                Stereo            = false,
                SwapEffect        = DXGI.SwapEffect.FlipSequential,
                Usage             = DXGI.Usage.BackBuffer | DXGI.Usage.RenderTargetOutput,
            };
            using (DXGI.Device3 dxgiDevice3 = this.device.QueryInterface <DXGI.Device3>())
            {
                using (DXGI.Factory3 dxgiFactory3 = dxgiDevice3.Adapter.GetParent <DXGI.Factory3>())
                {
                    using (DXGI.SwapChain1 swapChain1 = new DXGI.SwapChain1(dxgiFactory3, this.device, ref swapChainDescription))
                    {
                        this.swapChain = swapChain1.QueryInterface <DXGI.SwapChain2>();
                    }
                }
            }
            using (DXGI.ISwapChainPanelNative nativeObject = ComObject.As <DXGI.ISwapChainPanelNative>(this.SwapChainPanel))
            {
                nativeObject.SwapChain = this.swapChain;
            }
            this.backBufferTexture = D3D11.Texture2D.FromSwapChain <D3D11.Texture2D>(this.swapChain, 0);
            this.backBufferView    = new D3D11.RenderTargetView(this.device, this.backBufferTexture);
            isDXInitialized        = true;
            tw = new TextWirter(device, swapChain, Color.Black, DisplayInformation.GetForCurrentView().LogicalDpi);
//            #region D2D

//#if DEBUG
//            var debug = SharpDX.Direct2D1.DebugLevel.Error;
//#else
//            var debug = SharpDX.Direct2D1.DebugLevel.None;
//#endif

//            d2dFactory = new SharpDX.Direct2D1.Factory1(SharpDX.Direct2D1.FactoryType.SingleThreaded, debug);
//            using (var dxgiDevice = device.QueryInterface<SharpDX.DXGI.Device>())
//            {
//                d2dDevice = new SharpDX.Direct2D1.Device(d2dFactory, dxgiDevice);
//            }
//            d2dContext = new SharpDX.Direct2D1.DeviceContext(d2dDevice, SharpDX.Direct2D1.DeviceContextOptions.None);

//            BitmapProperties1 properties = new BitmapProperties1(
//                new PixelFormat(
//                    SharpDX.DXGI.Format.B8G8R8A8_UNorm,
//                    SharpDX.Direct2D1.AlphaMode.Premultiplied),
//                DisplayInformation.GetForCurrentView().LogicalDpi,
//                DisplayInformation.GetForCurrentView().LogicalDpi,
//                BitmapOptions.Target | BitmapOptions.CannotDraw);
//            DXGI.Surface backBuffer = swapChain.GetBackBuffer<DXGI.Surface>(0);
//            d2dTarget = new Bitmap1(d2dContext, backBuffer, properties);
//            SharpDX.DirectWrite.Factory fontFactory = new SharpDX.DirectWrite.Factory();
//            textFormat = new TextFormat(fontFactory, "Segoe UI", 24.0f);
//            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);
//            layoutY = 0.0f;
//            backgroundBrush = new SharpDX.Direct2D1.SolidColorBrush(d2dContext, Color.White);
//            textBrush = new SharpDX.Direct2D1.SolidColorBrush(d2dContext, Color.Black);
//            #endregion

            CompositionTarget.Rendering    += CompositionTarget_Rendering;
            Application.Current.Suspending += Application_Suspending;
        }
        /// <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);
        }
        /// <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,
                        }
                }));
        }
        public void Initialize()
        {
            if(!_deviceManager.IsInitialized)
                throw new InvalidOperationException("Device manager is not initialized");

            if(Initialized)
                Uninitialize();

            var swapChainDescription = new SwapChainDescription1
            {
                Width = Width,
                Height = Height,
                Format = Format.B8G8R8A8_UNorm,
                Stereo = false,
                SampleDescription = new SampleDescription(SampleCount, SampleQuality),
                Usage = Usage.BackBuffer | Usage.RenderTargetOutput,
                BufferCount = 1,
                Scaling = Scaling.Stretch,
                SwapEffect = SwapEffect.Discard,
                Flags = SwapChainFlags.AllowModeSwitch
            };
            var fullScreenDescription = new SwapChainFullScreenDescription
            {
                RefreshRate = new Rational(60, 1),
                Scaling = DisplayModeScaling.Centered,
                Windowed = true
            };

            using(var dxgiDevice2 = _deviceManager.Device.QueryInterface<Device2>())
            using(var dxgiFactory2 = dxgiDevice2.Adapter.GetParent<Factory2>())
            {
                SwapChain = new SwapChain1(dxgiFactory2, _deviceManager.Device, _windowHandle, ref swapChainDescription, fullScreenDescription);
                dxgiFactory2.MakeWindowAssociation(_windowHandle, WindowAssociationFlags.IgnoreAll);
            }

            Texture = Resource.FromSwapChain<Texture2D>(SwapChain, 0);
            RenderTargetView = new RenderTargetView(_deviceManager.Device, Texture);

            Initialized = true;
        }
Example #43
0
        public void Dispose()
        {
            if (_rtv != null)
                _rtv.Dispose();
            _rtv = null;

            if (_swap != null)
                _swap.Dispose();
            _swap = null;

            if (ToolkitDevice != null)
                ToolkitDevice.Dispose();
            ToolkitDevice = null;

            if (_context != null)
                _context.Dispose();
            _context = null;

            if (_device != null)
                _device.Dispose();
            _device = null;

            _width = 0;
            _height = 0;
        }
        private void SwapChainPanel_Loaded(object sender, RoutedEventArgs e)
        {
            // Create a new Direct3D hardware device and ask for Direct3D 11.2 support
            using (D3D11.Device defaultDevice = new D3D11.Device(D3D.DriverType.Hardware, D3D11.DeviceCreationFlags.Debug))
            {
                this.device = defaultDevice.QueryInterface<D3D11.Device2>();
            }

            // Save the context instance
            this.deviceContext = this.device.ImmediateContext2;

            // We have to take into account pixel scaling; Windows Phone 8.1 uses virtual resolutions smaller than the physical screen size.
            float pixelScale = Windows.Graphics.Display.DisplayInformation.GetForCurrentView().LogicalDpi / 96.0f;

            // Properties of the swap chain
            DXGI.SwapChainDescription1 swapChainDescription = new DXGI.SwapChainDescription1()
            {
                // No transparency.
                AlphaMode = DXGI.AlphaMode.Ignore,
                // Double buffer.
                BufferCount = 2,
                // BGRA 32bit pixel format.
                Format = DXGI.Format.B8G8R8A8_UNorm,
                // Unlike in CoreWindow swap chains, the dimensions must be set.
                Height = (int)(this.SwapChainPanel.RenderSize.Height * pixelScale),
                Width = (int)(this.SwapChainPanel.RenderSize.Width * pixelScale),
                // Default multisampling.
                SampleDescription = new DXGI.SampleDescription(1, 0),
                // In case the control is resized, stretch the swap chain accordingly.
                Scaling = DXGI.Scaling.Stretch,
                // No support for stereo display.
                Stereo = false,
                // Sequential displaying for double buffering.
                SwapEffect = DXGI.SwapEffect.FlipSequential,
                // This swapchain is going to be used as the back buffer.
                Usage = DXGI.Usage.BackBuffer | DXGI.Usage.RenderTargetOutput,
            };

            // Retrive the DXGI device associated to the Direct3D device.
            using (DXGI.Device3 dxgiDevice3 = this.device.QueryInterface<DXGI.Device3>())
            {
                // Get the DXGI factory automatically created when initializing the Direct3D device.
                using (DXGI.Factory3 dxgiFactory3 = dxgiDevice3.Adapter.GetParent<DXGI.Factory3>())
                {
                    // Create the swap chain and get the highest version available.
                    using (DXGI.SwapChain1 swapChain1 = new DXGI.SwapChain1(dxgiFactory3, this.device, ref swapChainDescription))
                    {
                        this.swapChain = swapChain1.QueryInterface<DXGI.SwapChain2>();
                    }
                }
            }

            // Obtain a reference to the native COM object of the SwapChainPanel.
            using (DXGI.ISwapChainPanelNative nativeObject = ComObject.As<DXGI.ISwapChainPanelNative>(this.SwapChainPanel))
            {
                // Set its swap chain.
                nativeObject.SwapChain = this.swapChain;
            }

            // Create a Texture2D from the existing swap chain to use as 
            this.backBufferTexture = D3D11.Texture2D.FromSwapChain<D3D11.Texture2D>(this.swapChain, 0);
            this.backBufferView = new D3D11.RenderTargetView(this.device, this.backBufferTexture);

            // This event is fired when the application requests a new frame from the DirectX interop controls.
            CompositionTarget.Rendering += CompositionTarget_Rendering;
        }
Example #45
0
        protected virtual void CreateSizeDependentResources(TargetBase renderBase)
        {
            var d3dDevice = DeviceManager.DeviceDirect3D;
            var d3dContext = DeviceManager.ContextDirect3D;
            var d2dContext = DeviceManager.ContextDirect2D;

            d2dContext.Target = null;
            RemoveAndDispose(ref renderTargetView);
            RemoveAndDispose(ref depthStencilView);
            RemoveAndDispose(ref bitmapTarget);
            RemoveAndDispose(ref backBuffer);

            // 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));
            {
                // Create a view interface on the rendertarget to use on bind.
                renderTargetView = ToDispose(new SharpDX.Direct3D11.RenderTargetView(d3dDevice, BackBuffer));

                // 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.SetViewports(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.
            using (var dxgiBackBuffer = swapChain.GetBackBuffer<SharpDX.DXGI.Surface>(0))
                bitmapTarget = 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;            
        }
        protected override SharpDX.DXGI.SwapChain1 CreateSwapChain(SharpDX.DXGI.Factory2 factory, SharpDX.Direct3D11.Device1 device, SharpDX.DXGI.SwapChainDescription1 desc)
        {
            // Creates the swap chain for XAML composition
            var swapChain = new SwapChain1(factory, device, ref  desc); //factory.CreateSwapChainForComposition(device, ref desc, null);

            // Associate the SwapChainPanel with the swap chain
            nativePanel.SwapChain = swapChain;

            // Returns the new swap chain
            return swapChain;
        }
 protected override SharpDX.DXGI.SwapChain1 CreateSwapChain(SharpDX.DXGI.Factory2 factory, SharpDX.Direct3D11.Device1 device, SharpDX.DXGI.SwapChainDescription1 desc)
 {
     // Create the swap chain for XAML composition
     var swapChain = new SwapChain1(factory, device, ref desc);
     // Attach swap chain to SwapChainPanel
     nativePanel.SwapChain = swapChain;
     return swapChain;
 }
        private SwapChain CreateSwapChainForWinRT()
        {
            var coreWindow = Description.DeviceWindowHandle as CoreWindow;
            var swapChainBackgroundPanel = Description.DeviceWindowHandle as SwapChainBackgroundPanel;

            bufferCount = 2;
            var description = new SwapChainDescription1
            {
                // Automatic sizing
                Width = Description.BackBufferWidth,
                Height = Description.BackBufferHeight,
                Format = SharpDX.DXGI.Format.B8G8R8A8_UNorm, // TODO: Check if we can use the Description.BackBufferFormat
                Stereo = false,
                SampleDescription = new SharpDX.DXGI.SampleDescription((int)Description.MultiSampleCount, 0),
                Usage = Description.RenderTargetUsage,
                // Use two buffers to enable flip effect.
                BufferCount = bufferCount,
                Scaling = SharpDX.DXGI.Scaling.Stretch,
                SwapEffect = SharpDX.DXGI.SwapEffect.FlipSequential,
            };

            if (coreWindow != null)
            {
                // Creates a SwapChain from a CoreWindow pointer
                using (var comWindow = new ComObject(coreWindow))
                    return new SwapChain1((DXGI.Factory2)GraphicsAdapter.Factory, (Direct3D11.Device)GraphicsDevice, comWindow, ref description);
            }
            else if (swapChainBackgroundPanel != null)
            {
                var nativePanel = ComObject.As<ISwapChainBackgroundPanelNative>(swapChainBackgroundPanel);
                // Creates the swap chain for XAML composition
                var swapChain = new SwapChain1((DXGI.Factory2)GraphicsAdapter.Factory, (Direct3D11.Device)GraphicsDevice, ref description);

                // Associate the SwapChainBackgroundPanel with the swap chain
                nativePanel.SwapChain = swapChain;
                return swapChain;
            }
            else
            {
#if DIRECTX11_2
                using (var comObject = new ComObject(Description.DeviceWindowHandle))
                {
                    var swapChainPanel = comObject.QueryInterfaceOrNull<ISwapChainPanelNative>();
                    if (swapChainPanel != null)
                    {
                        var swapChain = new SwapChain1((DXGI.Factory2)GraphicsAdapter.Factory, (Direct3D11.Device)GraphicsDevice, ref description);
                        swapChainPanel.SwapChain = swapChain;
                        return swapChain;
                    }
                }
#endif
                throw new NotSupportedException();
            }
        }
Example #49
0
        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 = 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
            });
        }
Example #51
0
 private void CreateSwapChain(ref SwapChainDescription1 swapChainDescription1, Factory4 factory)
 {
     using (var sc1 = new SwapChain1(factory, commandQueue, form.Handle, ref swapChainDescription1))
         swapChain = Collect(sc1.QueryInterface<SwapChain3>());
 }
Example #52
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));
        }