Example #1
0
        public DX11CubeDepthStencil(DX11RenderContext context, int size, SampleDescription sd, Format format)
        {
            this.context = context;

            var texBufferDesc = new Texture2DDescription
            {
                ArraySize = 6,
                BindFlags = BindFlags.DepthStencil | BindFlags.ShaderResource,
                CpuAccessFlags = CpuAccessFlags.None,
                Format = DepthFormatsHelper.GetGenericTextureFormat(format),
                Height = size,
                Width = size,
                OptionFlags = ResourceOptionFlags.TextureCube,
                SampleDescription = sd,
                Usage = ResourceUsage.Default,
                MipLevels = 1
            };

            this.Resource = new Texture2D(context.Device, texBufferDesc);

            this.desc = texBufferDesc;

            //Create faces SRV/RTV
            this.SliceDSV = new DX11SliceDepthStencil[6];

            ShaderResourceViewDescription svd = new ShaderResourceViewDescription()
            {
                Dimension = ShaderResourceViewDimension.TextureCube,
                Format = DepthFormatsHelper.GetSRVFormat(format),
                MipLevels = 1,
                MostDetailedMip = 0,
                First2DArrayFace = 0
            };

            DepthStencilViewDescription dsvd = new DepthStencilViewDescription()
            {
                ArraySize= 6,
                Dimension = DepthStencilViewDimension.Texture2DArray,
                FirstArraySlice = 0,
                Format = DepthFormatsHelper.GetDepthFormat(format),
                MipSlice = 0
            };

            this.DSV = new DepthStencilView(context.Device, this.Resource, dsvd);

            if (context.IsFeatureLevel11)
            {
                dsvd.Flags = DepthStencilViewFlags.ReadOnlyDepth;
                if (format == Format.D24_UNorm_S8_UInt) { dsvd.Flags |= DepthStencilViewFlags.ReadOnlyStencil; }

                this.ReadOnlyDSV = new DepthStencilView(context.Device, this.Resource, dsvd);
            }

            this.SRV = new ShaderResourceView(context.Device, this.Resource, svd);

            for (int i = 0; i < 6; i++)
            {
                this.SliceDSV[i] = new DX11SliceDepthStencil(context, this, i, DepthFormatsHelper.GetDepthFormat(format));
            }
        }
Example #2
0
        protected D3DApp(IntPtr hInstance)
        {
            AppInst = hInstance;
            MainWindowCaption = "D3D11 Application";
            DriverType = DriverType.Hardware;
            ClientWidth = 800;
            ClientHeight = 600;
            Enable4XMsaa = false;
            Window = null;
            AppPaused = false;
            Minimized = false;
            Maximized = false;
            Resizing = false;
            Msaa4XQuality = 0;
            Device = null;
            ImmediateContext = null;
            SwapChain = null;
            DepthStencilBuffer = null;
            RenderTargetView = null;
            DepthStencilView = null;
            Viewport = new Viewport();
            Timer = new GameTimer();

            GD3DApp = this;
        }
        public override void Dispose() {
            base.Dispose();

            if (DepthView != null) {
                DepthView.Dispose();
                DepthView = null;
            }
        }
Example #4
0
        private DepthStencilTarget( int width, int height, Texture2D texture )
        {
            Width = width;
            Height = height;

            Texture = texture;

            var wrapper = D3D10Wrapper.Instance;
            DepthStencilView = new DepthStencilView( wrapper.Device, texture );
        }
Example #5
0
        public void Initialize(DeviceContextHolder holder) {
            const Format format = Format.R16G16B16A16_Float;

            using (var cubeTex = new Texture2D(holder.Device, new Texture2DDescription {
                Width = _cubeMapSize,
                Height = _cubeMapSize,
                MipLevels = 2,
                ArraySize = 6,
                SampleDescription = new SampleDescription(1, 0),
                Format = format,
                Usage = ResourceUsage.Default,
                BindFlags = BindFlags.ShaderResource | BindFlags.RenderTarget,
                CpuAccessFlags = CpuAccessFlags.None,
                OptionFlags = ResourceOptionFlags.GenerateMipMaps | ResourceOptionFlags.TextureCube
            })) {
                _targetView = Enumerable.Range(0, 6).Select(x => new RenderTargetView(holder.Device, cubeTex,
                    new RenderTargetViewDescription {
                        Format = format,
                        Dimension =
                            RenderTargetViewDimension
                        .Texture2DArray,
                        ArraySize = 1,
                        FirstArraySlice = x,
                        MipSlice = 0
                    })).ToArray();

                _view = new ShaderResourceView(holder.Device, cubeTex, new ShaderResourceViewDescription {
                    Format = format,
                    Dimension = ShaderResourceViewDimension.TextureCube,
                    MostDetailedMip = 0,
                    MipLevels = -1
                });
            }

            const Format depthFormat = Format.D32_Float;
            using (var depthTex = new Texture2D(holder.Device, new Texture2DDescription {
                Width = _cubeMapSize,
                Height = _cubeMapSize,
                MipLevels = 1,
                ArraySize = 1,
                SampleDescription = new SampleDescription(1, 0),
                Format = depthFormat,
                Usage = ResourceUsage.Default,
                BindFlags = BindFlags.DepthStencil,
                CpuAccessFlags = CpuAccessFlags.None,
                OptionFlags = ResourceOptionFlags.None
            })) {
                _depthTargetView = new DepthStencilView(holder.Device, depthTex, new DepthStencilViewDescription {
                    Format = depthFormat,
                    Flags = DepthStencilViewFlags.None,
                    Dimension = DepthStencilViewDimension.Texture2D,
                    MipSlice = 0,
                });
            }
        }
Example #6
0
        public void Render( DeviceContext deviceContext, Viewport viewport, RenderTargetView renderTargetView, DepthStencilView depthStencilView )
        {
            deviceContext.ClearRenderTargetView( renderTargetView, Constants.CLEAR_COLOR );
            deviceContext.ClearDepthStencilView( depthStencilView, DepthStencilClearFlags.Depth | DepthStencilClearFlags.Stencil, 1.0f, 0x00 );

            //mTinyTextContext.Print( viewport, "Frame Time: " + FrameTimeString, 10, 10 );
            //mTinyTextContext.Render();

            mStopwatch.Reset();
            mStopwatch.Start();
        }
 private void CreateDepthStencilViews()
 {
     var depthStencilViewDesc = new DepthStencilViewDescription();
     depthStencilViewDesc.Format = Format.D32_Float;
     depthStencilViewDesc.Dimension = DepthStencilViewDimension.Texture2DArray;
     depthStencilViewDesc.ArraySize = 1;
     depthStencilViewDesc.MipSlice = 0;
     for (int i = 0; i < deferredShadingConfiguration.LayerCount; ++i)
     {
         depthStencilViewDesc.FirstArraySlice = i;
         var depthStencilView = new DepthStencilView(device, texture, depthStencilViewDesc);
         depthStencilViews.Add(depthStencilView);
     }
 }
        public override void Resize(DeviceContextHolder holder, int width, int height) {
            base.Resize(holder, width, height);

            DepthView = new DepthStencilView(holder.Device, Texture, new DepthStencilViewDescription {
                Flags = DepthStencilViewFlags.None,
                Format = Format.D24_UNorm_S8_UInt,
                Dimension = DepthStencilViewDimension.Texture2D,
                MipSlice = 0
            });

            View = new ShaderResourceView(holder.Device, Texture, new ShaderResourceViewDescription {
                Format = Format.R24_UNorm_X8_Typeless,
                Dimension = ShaderResourceViewDimension.Texture2D,
                MipLevels = 1,
                MostDetailedMip = 0
            });
        }
Example #9
0
        public ShadowMap(Device device, int width, int height) {
            _width = width;
            _height = height;

            _viewport = new Viewport(0, 0, _width, _height, 0, 1.0f);

            var texDesc = new Texture2DDescription {
                Width = _width,
                Height = _height,
                MipLevels = 1,
                ArraySize = 1,
                Format = Format.R24G8_Typeless,
                SampleDescription = new SampleDescription(1, 0),
                Usage = ResourceUsage.Default,
                BindFlags = BindFlags.DepthStencil | BindFlags.ShaderResource ,
                CpuAccessFlags = CpuAccessFlags.None,
                OptionFlags = ResourceOptionFlags.None
            };

            var depthMap = new Texture2D(device, texDesc);
            depthMap.DebugName = "shadowmap depthmap";
            var dsvDesc = new DepthStencilViewDescription {
                Flags = DepthStencilViewFlags.None,
                Format = Format.D24_UNorm_S8_UInt,
                Dimension = DepthStencilViewDimension.Texture2D,
                MipSlice = 0
            };
            _depthMapDSV = new DepthStencilView(device, depthMap, dsvDesc);

            var srvDesc = new ShaderResourceViewDescription {
                Format = Format.R24_UNorm_X8_Typeless,
                Dimension = ShaderResourceViewDimension.Texture2D,
                MipLevels = texDesc.MipLevels,
                MostDetailedMip = 0

            };

            DepthMapSRV = new ShaderResourceView(device, depthMap, srvDesc);

            Util.ReleaseCom(ref depthMap);

        }
Example #10
0
        // Functions
        public TextureObject()
        {
            m_Width = m_Height = 1;
            m_Mips = 1;
            m_Depth = 1;
            m_ArraySize = 1;
            m_IsCube = false;
            m_TexFormat = Format.Unknown;
            m_TextureObject2D = null;
            m_TextureObject3D = null;
            m_RenderTargetView = null;
            m_ShaderResourceView = null;
            m_DepthStencilView = null;
            m_UnorderedAccessView = null;

            m_ArrayRenderTargetViews = null;
            m_ArrayShaderResourceViews = null;
            m_ArrayDepthStencilViews = null;
            m_ArrayUnorderedAccessViews = null;
        }
        public RenderToTextureCommand(int width, int height, SceneManager sceneTree)
            : base(CommandType.Action)
        {
            SceneTree = sceneTree;
            RenderTextureDesc = new Texture2DDescription
            {
                ArraySize = 1,
                BindFlags = BindFlags.RenderTarget | BindFlags.ShaderResource,
                CpuAccessFlags = CpuAccessFlags.None,
                Format = Format.R8G8B8A8_UNorm,
                Width = width,
                Height = height,
                MipLevels = 1,
                OptionFlags = ResourceOptionFlags.None,
                SampleDescription = new SampleDescription(1, 0),
                Usage = ResourceUsage.Default
            };

            texture = new Texture2D(Game.Context.Device, RenderTextureDesc);

            Texture2DDescription depthBufferDesc = new Texture2DDescription
            {
                ArraySize = 1,
                BindFlags = BindFlags.DepthStencil,
                CpuAccessFlags = CpuAccessFlags.None,
                Format = Format.D32_Float,
                Width = width,
                Height = height,
                MipLevels = 1,
                OptionFlags = ResourceOptionFlags.None,
                SampleDescription = new SampleDescription(1, 0),
                Usage = ResourceUsage.Default
            };

            using (Texture2D depthBuffer = new Texture2D(Game.Context.Device, depthBufferDesc))
            {
                DepthStencilView = new DepthStencilView(Game.Context.Device, depthBuffer);
            }

            RenderTargetView = new RenderTargetView(Game.Context.Device, texture);
        }
Example #12
0
 public void SetDepthStencilTarget(string name)
 {
     DepthStencilView target = null;
     m_DSVList.TryGetValue(name, out target);
     m_CurrDepthStencil = target;
 }
Example #13
0
        private void CreateRenderTargets()
        {
            Texture2D backBuffer = Texture2D.FromSwapChain<Texture2D>(SwapChain, 0);
            sceneView = new RenderTargetView(Device, backBuffer);

            Texture2DDescription depthBufferDesc = new Texture2DDescription
            {
                ArraySize = 1,
                BindFlags = BindFlags.DepthStencil | BindFlags.ShaderResource,
                CpuAccessFlags = CpuAccessFlags.None,
                Format = Format.R32_Typeless,
                Width = WindowWidth,
                Height = WindowHeight,
                MipLevels = 1,
                OptionFlags = ResourceOptionFlags.None,
                SampleDescription = new SampleDescription(1, 0),
                Usage = ResourceUsage.Default
            };
            Texture2D depthBuffer = new Texture2D(Device, depthBufferDesc);

            DepthStencilViewDescription depthStencilDesc = new DepthStencilViewDescription
            {
                ArraySize = 0,
                Format = Format.D32_Float,
                Dimension = DepthStencilViewDimension.Texture2D,
                MipSlice = 0,
                Flags = 0,
                FirstArraySlice = 0
            };
            depthView = new DepthStencilView(Device, depthBuffer, depthStencilDesc);
            ShaderResourceViewDescription depthResViewDesc = new ShaderResourceViewDescription
            {
                ArraySize = 0,
                Format = Format.R32_Float,
                Dimension = ShaderResourceViewDimension.Texture2D,
                MipLevels = 1,
                Flags = 0,
                FirstArraySlice = 0
            };
            depthResView = new ShaderResourceView(Device, depthBuffer, depthResViewDesc);

            Texture2DDescription densityBufferDesc = new Texture2DDescription
            {
                ArraySize = 1,
                BindFlags = BindFlags.RenderTarget | BindFlags.ShaderResource,
                CpuAccessFlags = CpuAccessFlags.None,
                Format = Format.R8G8B8A8_UNorm,
                Width = WindowWidth,
                Height = WindowHeight,
                MipLevels = 1,
                OptionFlags = ResourceOptionFlags.None,
                SampleDescription = new SampleDescription(1, 0),
                Usage = ResourceUsage.Default
            };
            Texture2D densityBuffer = new Texture2D(Device, densityBufferDesc);

            RenderTargetViewDescription densityViewDesc = new RenderTargetViewDescription
            {
                ArraySize = 0,
                Format = Format.R8G8B8A8_UNorm,
                Dimension = RenderTargetViewDimension.Texture2D,
                MipSlice = 0,
                FirstArraySlice = 0
            };
            densityView = new RenderTargetView(Device, densityBuffer, densityViewDesc);
            ShaderResourceViewDescription densityResViewDesc = new ShaderResourceViewDescription
            {
                ArraySize = 0,
                Format = Format.R8G8B8A8_UNorm,
                Dimension = ShaderResourceViewDimension.Texture2D,
                MipLevels = 1,
                Flags = 0,
                FirstArraySlice = 0
            };
            densityResView = new ShaderResourceView(Device, densityBuffer, densityResViewDesc);
        }
Example #14
0
 public void ClearRenderTarget(DeviceContext deviceContext, DepthStencilView depthStencilView, Color4 color)
 {
     deviceContext.ClearRenderTargetView(renderTargetView, color);
     deviceContext.ClearDepthStencilView(depthStencilView, DepthStencilClearFlags.Depth, 1.0f, 0);
 }
Example #15
0
        internal static void AddShadowCaster(BoundingFrustum frustum, Matrix viewProjectionLocal, MyViewport viewport, DepthStencilView depthTarget, bool isCascade, string debugName)
        {
            var frustumMask = m_cullQuery.AddFrustum(frustum);

            MyDepthPass pass = new MyDepthPass();

            pass.DebugName = debugName;
            pass.Cleanup();
            pass.ProcessingMask = frustumMask;
            pass.ViewProjection = viewProjectionLocal;
            pass.Viewport       = viewport;

            pass.DSV = depthTarget;
            pass.DefaultRasterizer = isCascade ? MyRender11.m_cascadesRasterizerState : MyRender11.m_shadowRasterizerState;

            pass.PerFrame();

            m_wavefront.Add(pass);
        }
Example #16
0
        private void InitializeDepthStencil(uint nWidth, uint nHeight)
        {
            // Create depth stencil texture
            Texture2DDescription descDepth = new Texture2DDescription()
                                                 {
                                                     Width = nWidth,
                                                     Height = nHeight,
                                                     MipLevels = 1,
                                                     ArraySize = 1,
                                                     Format = Format.D16_UNORM,
                                                     SampleDescription = new SampleDescription()
                                                                             {
                                                                                 Count = 1,
                                                                                 Quality = 0
                                                                             },
                                                     BindFlags = BindFlag.DepthStencil,
                                                 };
            depthStencil = device.CreateTexture2D(descDepth);

            // Create the depth stencil view
            DepthStencilViewDescription depthStencilViewDesc = new DepthStencilViewDescription()
                                                                   {
                                                                       Format = descDepth.Format,
                                                                       ViewDimension =
                                                                           DepthStencilViewDimension.
                                                                           Texture2D
                                                                   };
            depthStencilView = device.CreateDepthStencilView(depthStencil, depthStencilViewDesc);
        }
Example #17
0
        /// <summary>
        /// Sets the default render-targets
        /// </summary>
        public void SetDefaultColorTargets(DepthStencilView dsv)
        {
            this.targetWidth = this.colorBuffer.Description.Width;
            this.targetHeight = this.colorBuffer.Description.Height;

            this.device.ImmediateContext.OutputMerger.SetTargets(dsv, this.colorBufferView);
            this.device.ImmediateContext.Rasterizer.SetViewport(0, 0, this.colorBuffer.Description.Width, this.colorBuffer.Description.Height, 0.0f, 1.0f);

            this.device.ImmediateContext.ClearRenderTargetView(this.colorBufferView, this.ClearColor);
            this.device.ImmediateContext.ClearDepthStencilView(this.depthStencilBufferView, DepthStencilClearFlags.Depth | DepthStencilClearFlags.Stencil, 1.0f, 0);
        }
Example #18
0
        public SpotLightRenderer(DX11Game game, GBuffer gBuffer)
        {
            this.game    = game;
            this.gBuffer = gBuffer;
            var device = game.Device;

            context = device.ImmediateContext;

            reloadShader(game);

            quad = new FullScreenQuad(device);

            layout = FullScreenQuad.CreateInputLayout(device, noShadowsShader.GetCurrentPass(0));

            LightPosition     = new Vector3(0, 6, 0);
            LightRadius       = 6;
            LightIntensity    = 1;
            SpotDirection     = MathHelper.Down;
            SpotLightAngle    = MathHelper.ToRadians(30);
            SpotDecayExponent = 1;


            Color = new Vector3(1, 1, 0.9f);



            shadowMap = new Texture2D(device, new Texture2DDescription
            {
                ArraySize         = 1,
                BindFlags         = BindFlags.DepthStencil | BindFlags.ShaderResource,
                CpuAccessFlags    = CpuAccessFlags.None,
                Format            = global::SlimDX.DXGI.Format.R32_Typeless,
                Width             = shadowMapSize,
                Height            = shadowMapSize,
                MipLevels         = 1,
                Usage             = ResourceUsage.Default,
                SampleDescription = new global::SlimDX.DXGI.SampleDescription(1, 0)
            });
            shadowMapRV = new ShaderResourceView(device, shadowMap, new ShaderResourceViewDescription
            {
                Dimension       = ShaderResourceViewDimension.Texture2D,
                Format          = global::SlimDX.DXGI.Format.R32_Float,
                MipLevels       = 1,
                MostDetailedMip = 0
            });
            shadowMapDSV = new DepthStencilView(device, shadowMap, new DepthStencilViewDescription
            {
                Dimension = DepthStencilViewDimension.Texture2D,
                Format    = global::SlimDX.DXGI.Format.D32_Float
            });

            LightCamera = new CustomCamera();


            //var rasterizerInside = RasterizerState.FromDescription(device, new RasterizerStateDescription
            //                                                                   {
            //                                                                       CullMode = CullMode.Front
            //                                                                   });

            //var rasterizerOutside = RasterizerState.FromDescription(device, new RasterizerStateDescription
            //{
            //    CullMode = CullMode.Back
            //});
        }
Example #19
0
 private static void BindTarget(DepthStencilView dsv, RenderTargetView targetView, DeviceContextProxy context, int width, int height)
 {
     context.SetRenderTargets(dsv, targetView == null ? null : new RenderTargetView[] { targetView });
 }
Example #20
0
        public void Draw(DeviceContext deviceContext, RenderTargetView[] renderTargetViews, DepthStencilView depthStencilView,
                         Matrix proj, Matrix view,
                         Vector4 lightPos, Vector4 lightColor, Vector4 eyePos, float lightIntens,
                         PrimitiveTopology topology, bool withShadowMap = true)
        {
            var quat = Quaternion.RotationMatrix(Rotation);

            Matrix.AffineTransformation(Scaling.X, ref RotationCenter, ref quat, ref Translation, out Transform);

            if (withShadowMap)
            {
                MainShaderManager.ShadowTransform = ShadowTransform;
            }

            MainShaderManager.Render(deviceContext, renderTargetViews, depthStencilView,
                                     view, proj, Transform,
                                     lightPos, lightColor, eyePos, lightIntens,
                                     Material, TextureView, isTextureCube, isLighten,
                                     topology, VerticesCount,
                                     withShadowMap);
        }
Example #21
0
        public void DrawShadowMap(DeviceContext deviceContext, RenderTargetView[] renderTargetViews, DepthStencilView depthStencilView,
                                  Matrix lightProj, Matrix lightView, Matrix lightShadowTransform,
                                  PrimitiveTopology topology)
        {
            var quat = Quaternion.RotationMatrix(Rotation);

            Matrix.AffineTransformation(Scaling.X, ref RotationCenter, ref quat, ref Translation, out Transform);

            ShadowTransform = lightShadowTransform;

            ShadowShaderManager.RenderShadow(deviceContext, renderTargetViews, depthStencilView, lightView, lightProj, lightShadowTransform, Transform, topology, VerticesCount);
        }
        // Puvlix Methods
        public bool Initialize(SharpDX.Direct3D11.Device device, DSystemConfiguration configuration)
        {
            TextureWidth  = configuration.Width;
            TextureHeight = configuration.Height;

            try
            {
                // Initialize and set up the render target description.
                Texture2DDescription textureDesc = new Texture2DDescription()
                {
                    Width             = configuration.Width,
                    Height            = configuration.Height,
                    MipLevels         = 1,
                    ArraySize         = 1,
                    Format            = Format.R32G32B32A32_Float,
                    SampleDescription = new SampleDescription(1, 0),
                    Usage             = ResourceUsage.Default,
                    BindFlags         = BindFlags.RenderTarget | BindFlags.ShaderResource,
                    CpuAccessFlags    = CpuAccessFlags.None,
                    OptionFlags       = ResourceOptionFlags.None
                };

                // Create the render target texture.
                RenderTargetTexture = new Texture2D(device, textureDesc);

                // Initialize and setup the render target view
                RenderTargetViewDescription renderTargetViewDesc = new RenderTargetViewDescription()
                {
                    Format    = textureDesc.Format,
                    Dimension = RenderTargetViewDimension.Texture2D
                };
                renderTargetViewDesc.Texture2D.MipSlice = 0;

                // Create the render target view.
                RenderTargetView = new RenderTargetView(device, RenderTargetTexture, renderTargetViewDesc);

                // Initialize and setup the shader resource view
                ShaderResourceViewDescription shaderResourceViewDesc = new ShaderResourceViewDescription()
                {
                    Format    = textureDesc.Format,
                    Dimension = ShaderResourceViewDimension.Texture2D,
                };
                shaderResourceViewDesc.Texture2D.MipLevels       = 1;
                shaderResourceViewDesc.Texture2D.MostDetailedMip = 0;

                // Create the render target view.
                ShaderResourceView = new ShaderResourceView(device, RenderTargetTexture, shaderResourceViewDesc);

                // Initialize the description of the depth buffer.
                Texture2DDescription depthBufferDesc = new Texture2DDescription()
                {
                    Width             = configuration.Width,
                    Height            = configuration.Height,
                    MipLevels         = 1,
                    ArraySize         = 1,
                    Format            = Format.D24_UNorm_S8_UInt,
                    SampleDescription = new SampleDescription(1, 0),
                    Usage             = ResourceUsage.Default,
                    BindFlags         = BindFlags.DepthStencil,
                    CpuAccessFlags    = CpuAccessFlags.None,
                    OptionFlags       = ResourceOptionFlags.None
                };

                // Create the texture for the depth buffer using the filled out description.
                DepthStencilBuffer = new Texture2D(device, depthBufferDesc);

                // Initialize the depth stencil view.
                // Set up the depth stencil view description.
                DepthStencilViewDescription depthStencilViewBufferDesc = new DepthStencilViewDescription()
                {
                    Format    = SharpDX.DXGI.Format.D24_UNorm_S8_UInt,
                    Dimension = DepthStencilViewDimension.Texture2D
                };

                depthStencilViewBufferDesc.Texture2D.MipSlice = 0;

                // Create the depth stencil view.
                DepthStencilView = new DepthStencilView(device, DepthStencilBuffer, depthStencilViewBufferDesc);

                // Setup the viewport for rendering.
                ViewPort = new ViewportF(0.0f, 0.0f, (float)configuration.Width, (float)configuration.Height, 0.0f, 1.0f);

                // Create an orthographic projection matrix for 2D rendering.
                OrthoMatrix = Matrix.OrthoLH(configuration.Width, configuration.Height, DSystemConfiguration.ScreenNear, DSystemConfiguration.ScreenDepth);

                return(true);
            }
            catch
            {
                return(false);
            }
        }
Example #23
0
        private void Initialize()
        {
            //ViewPort Initialization
            Viewport.Height   = _textureHeight;
            Viewport.Width    = _textureWidth;
            Viewport.X        = 0;
            Viewport.Y        = 0;
            Viewport.MinDepth = 0.0f;
            Viewport.MaxDepth = 1.0f;

            //Create the TExture viewport 2D Projection Matrix
            Matrix.OrthoOffCenterLH(0, Viewport.Width, Viewport.Height, 0, 0, 1, out Projection2D); // Make the 0,0 bottom/left, 1,1 Up/right

            // Setup the render target texture description.
            _textureDesc = new Texture2DDescription()
            {
                Width             = _textureWidth,
                Height            = _textureHeight,
                MipLevels         = 1,
                ArraySize         = 1,
                Format            = _textureFormat,
                Usage             = ResourceUsage.Default,
                BindFlags         = BindFlags.RenderTarget | BindFlags.ShaderResource,
                CpuAccessFlags    = CpuAccessFlags.None,
                OptionFlags       = ResourceOptionFlags.None,
                SampleDescription = new SharpDX.DXGI.SampleDescription()
                {
                    Count = 1, Quality = 0
                }
            };

            // Create the render target texture.
            RenderTargetTexture = ToDispose(new Texture2D(_d3dEngine.Device, _textureDesc));

            Texture2DDescription depthMapDesc = new Texture2DDescription()
            {
                Width             = _textureWidth,
                Height            = _textureHeight,
                MipLevels         = 1,
                ArraySize         = 1,
                Format            = Format.R32_Typeless,
                SampleDescription = new SampleDescription()
                {
                    Count = 1, Quality = 0
                },
                Usage          = ResourceUsage.Default,
                BindFlags      = BindFlags.DepthStencil | BindFlags.ShaderResource,
                CpuAccessFlags = CpuAccessFlags.None,
                OptionFlags    = ResourceOptionFlags.None
            };
            Texture2D depthMap = new Texture2D(_d3dEngine.Device, depthMapDesc);

            DepthStencilViewDescription depthStencilViewDesc = new DepthStencilViewDescription()
            {
                Format    = Format.D32_Float,
                Dimension = DepthStencilViewDimension.Texture2D,
                Texture2D = new DepthStencilViewDescription.Texture2DResource()
                {
                    MipSlice = 0
                }
            };

            _depthStencilView = ToDispose(new DepthStencilView(_d3dEngine.Device, depthMap, depthStencilViewDesc));
            depthMap.Dispose();

            // Setup the description of the render target view.
            RenderTargetViewDescription renderTargetViewDesc = new RenderTargetViewDescription()
            {
                Format    = _textureFormat,
                Dimension = RenderTargetViewDimension.Texture2D,
                Texture2D = new RenderTargetViewDescription.Texture2DResource()
                {
                    MipSlice = 0
                }
            };

            // Create the render target view for using the Texture define.
            _renderTargetView = ToDispose(new RenderTargetView(_d3dEngine.Device, RenderTargetTexture, renderTargetViewDesc));

            // Setup the description of the shader resource view.
            ShaderResourceViewDescription shaderResourceViewDesc = new ShaderResourceViewDescription()
            {
                Format    = _textureFormat,
                Dimension = SharpDX.Direct3D.ShaderResourceViewDimension.Texture2D,
                Texture2D = new ShaderResourceViewDescription.Texture2DResource()
                {
                    MipLevels = 1, MostDetailedMip = 0
                }
            };

            ShaderResourceView = ToDispose(new ShaderResourceView(_d3dEngine.Device, RenderTargetTexture, shaderResourceViewDesc));
        }
        public SwapChainRenderTarget(GraphicsDevice graphicsDevice,
                                     IntPtr windowHandle,
                                     int width,
                                     int height,
                                     bool mipMap,
                                     SurfaceFormat surfaceFormat,
                                     DepthFormat depthFormat,
                                     int preferredMultiSampleCount,
                                     RenderTargetUsage usage,
                                     PresentInterval presentInterval)
            : base(
                graphicsDevice,
                width,
                height,
                mipMap,
                surfaceFormat,
                depthFormat,
                preferredMultiSampleCount,
                usage,
                SurfaceType.SwapChainRenderTarget)
        {
            var dxgiFormat = surfaceFormat == SurfaceFormat.Color
                             ? SharpDX.DXGI.Format.B8G8R8A8_UNorm
                             : SharpDXHelper.ToFormat(surfaceFormat);

            var multisampleDesc = new SampleDescription(1, 0);

            if (preferredMultiSampleCount > 1)
            {
                multisampleDesc.Count   = preferredMultiSampleCount;
                multisampleDesc.Quality = (int)StandardMultisampleQualityLevels.StandardMultisamplePattern;
            }

            var desc = new SwapChainDescription()
            {
                ModeDescription =
                {
                    Format  = dxgiFormat,
                    Scaling = DisplayModeScaling.Stretched,
                    Width   = width,
                    Height  = height,
                },

                OutputHandle      = windowHandle,
                SampleDescription = multisampleDesc,
                Usage             = Usage.RenderTargetOutput,
                BufferCount       = 2,
                SwapEffect        = SharpDXHelper.ToSwapEffect(presentInterval),
                IsWindowed        = true,
            };

            PresentInterval = presentInterval;

            // Once the desired swap chain description is configured, it must
            // be created on the same adapter as our D3D Device
            var d3dDevice = graphicsDevice._d3dDevice;

            // First, retrieve the underlying DXGI Device from the D3D Device.
            // Creates the swap chain
            using (var dxgiDevice = d3dDevice.QueryInterface <Device1>())
                using (var dxgiAdapter = dxgiDevice.Adapter)
                    using (var dxgiFactory = dxgiAdapter.GetParent <Factory1>())
                    {
                        _swapChain = new SwapChain(dxgiFactory, dxgiDevice, desc);
                    }

            // Obtain the backbuffer for this window which will be the final 3D rendertarget.
            var backBuffer = SharpDX.Direct3D11.Resource.FromSwapChain <SharpDX.Direct3D11.Texture2D>(_swapChain, 0);

            // Create a view interface on the rendertarget to use on bind.
            _renderTargetViews = new[] { new RenderTargetView(d3dDevice, backBuffer) };

            // Get the rendertarget dimensions for later.
            var backBufferDesc = backBuffer.Description;
            var targetSize     = new Point(backBufferDesc.Width, backBufferDesc.Height);

            _texture = backBuffer;

            // Create the depth buffer if we need it.
            if (depthFormat != DepthFormat.None)
            {
                dxgiFormat = SharpDXHelper.ToFormat(depthFormat);

                // Allocate a 2-D surface as the depth/stencil buffer.
                using (
                    var depthBuffer = new SharpDX.Direct3D11.Texture2D(d3dDevice,
                                                                       new Texture2DDescription()
                {
                    Format = dxgiFormat,
                    ArraySize = 1,
                    MipLevels = 1,
                    Width = targetSize.X,
                    Height = targetSize.Y,
                    SampleDescription = multisampleDesc,
                    Usage = ResourceUsage.Default,
                    BindFlags = BindFlags.DepthStencil,
                }))

                    // Create a DepthStencil view on this surface to use on bind.
                    _depthStencilView = new DepthStencilView(d3dDevice, depthBuffer);
            }
        }
        public void OnShutdown(ShutdownMessage msg)
        {
            // Debug
            Console.WriteLine("Shutting down renderer...");

            // Clean up all shader resource views
            /*foreach (var pair in shaderresourcemap)
                pair.Value.Dispose();
            shaderresourcemap.Clear();
            shaderresourcemap = null;

            // Clean up the sampler states
            smpClamp.Dispose();
            smpClamp = null;

            // Clean up the meshes
            mshrQuad.Dispose();
            mshrQuad = null;
            mshQuad = null;

            // Clean up the shaders
            shdBasic.Dispose();
            shdBasic = null;*/

            // Clean up the RT and depth buffer
            vwDepthBuffer.Dispose();
            vwDepthBuffer = null;
            texDepthBuffer.Dispose();
            texDepthBuffer = null;
            rtBackbuffer.Dispose();
            rtBackbuffer = null;

            // Clean up the depth states
            Depth_Disabled.Dispose();
            Depth_Disabled = null;
            Depth_Enabled.Dispose();
            Depth_Enabled = null;

            // Shutdown the swapchain and device
            swapchain.Dispose();
            swapchain = null;
            Device.Dispose();
            Device = null;

            // Cleanup other stuff
            context = null;

            // Cleanup the window
            window.Dispose();
            window = null;
        }
Example #26
0
        public bool Initialize(int screenWidth, int screenHeight, bool vSync, IntPtr hwnd, bool fullScreen, float screenDepth, float screenNear)
        {
            try {
                vSyncEnabled = vSync;

                Rational refreshRate = new Rational(0, 0);

                var factory       = new Factory1();
                var adapter       = factory.Adapters[0];
                var adapterOutput = adapter.Outputs[0];

                var modes = adapterOutput.GetDisplayModeList(Format.R8G8B8A8_UNorm, DisplayModeEnumerationFlags.Interlaced);
                for (int i = 0; i < modes.Length; i++)
                {
                    if (modes[i].Width == screenWidth)
                    {
                        if (modes[i].Height == screenHeight)
                        {
                            refreshRate = modes[i].RefreshRate;
                        }
                    }
                }

                VideoCardMemory      = adapter.Description.DedicatedVideoMemory / 1024 / 1024;
                VideoCardDescription = adapter.Description.Description;

                adapterOutput.Dispose();
                adapter.Dispose();
                factory.Dispose();

                var swapChainDescription = new SwapChainDescription {
                    BufferCount     = 1,
                    ModeDescription =
                    {
                        Width            = screenWidth,
                        Height           = screenHeight,
                        Format           = Format.R8G8B8A8_UNorm,
                        RefreshRate      = vSyncEnabled ? refreshRate : new Rational(0, 0),
                        ScanlineOrdering = DisplayModeScanlineOrder.Unspecified,
                        Scaling          = DisplayModeScaling.Unspecified
                    },
                    Usage             = Usage.RenderTargetOutput,
                    OutputHandle      = hwnd,
                    SampleDescription = { Count = 1, Quality = 0 },
                    IsWindowed        = !fullScreen,
                    SwapEffect        = SwapEffect.Discard,
                    Flags             = SwapChainFlags.None
                };

                var featureLevel = FeatureLevel.Level_11_0;

                Device device;
                Device.CreateWithSwapChain(
                    DriverType.Hardware,
                    DeviceCreationFlags.Debug,
                    new[] { featureLevel },
                    swapChainDescription,
                    out device,
                    out swapChain
                    );
                Device        = device;
                DeviceContext = device.ImmediateContext;

                using (var backBuffer = swapChain.GetBackBuffer <Texture2D>(0)) {
                    renderTargetView = new RenderTargetView(device, backBuffer);
                }

                var depthBufferDescription = new Texture2DDescription {
                    Width             = screenWidth,
                    Height            = screenHeight,
                    MipLevels         = 1,
                    ArraySize         = 1,
                    Format            = Format.D24_UNorm_S8_UInt,
                    SampleDescription = new SampleDescription(1, 0),
                    Usage             = ResourceUsage.Default,
                    BindFlags         = BindFlags.DepthStencil,
                    CpuAccessFlags    = CpuAccessFlags.None,
                    OptionFlags       = ResourceOptionFlags.None
                };

                depthStencilBuffer = new Texture2D(device, depthBufferDescription);

                var depthStencilStateDescription = new DepthStencilStateDescription {
                    IsDepthEnabled   = true,
                    DepthWriteMask   = DepthWriteMask.All,
                    DepthComparison  = Comparison.Less,
                    IsStencilEnabled = true,
                    StencilReadMask  = 0xFF,
                    StencilWriteMask = 0xFF,
                    FrontFace        =
                    {
                        FailOperation      = StencilOperation.Keep,
                        DepthFailOperation = StencilOperation.Increment,
                        PassOperation      = StencilOperation.Keep,
                        Comparison         = Comparison.Always
                    },
                    BackFace =
                    {
                        FailOperation      = StencilOperation.Keep,
                        DepthFailOperation = StencilOperation.Decrement,
                        PassOperation      = StencilOperation.Keep,
                        Comparison         = Comparison.Always
                    }
                };

                depthStencilState = new DepthStencilState(device, depthStencilStateDescription);

                var depthStencilViewDescription = new DepthStencilViewDescription {
                    Format    = Format.D24_UNorm_S8_UInt,
                    Dimension = DepthStencilViewDimension.Texture2D,
                    Texture2D =
                    {
                        MipSlice = 0
                    }
                };

                depthStencilView = new DepthStencilView(device, depthStencilBuffer, depthStencilViewDescription);

                DeviceContext.OutputMerger.SetRenderTargets(depthStencilView, renderTargetView);

                var rasterizerStateDescription = new RasterizerStateDescription {
                    IsAntialiasedLineEnabled = false,
                    CullMode                = CullMode.Back,
                    DepthBias               = 0,
                    DepthBiasClamp          = 0.0f,
                    IsDepthClipEnabled      = true,
                    FillMode                = FillMode.Solid,
                    IsFrontCounterClockwise = false,
                    IsMultisampleEnabled    = false,
                    IsScissorEnabled        = false,
                    SlopeScaledDepthBias    = 0.0f
                };

                rasterizerState = new RasterizerState(device, rasterizerStateDescription);

                DeviceContext.Rasterizer.State = rasterizerState;

                var viewport = new Viewport {
                    Width    = screenWidth,
                    Height   = screenHeight,
                    MinDepth = 0.0f,
                    MaxDepth = 1.0f,
                    X        = 0,
                    Y        = 0
                };

                DeviceContext.Rasterizer.SetViewport(viewport);

                var fieldOfView  = MathUtil.Pi / 4.0f;
                var screenAspect = (float)screenWidth / screenHeight;
                Projection = Matrix.PerspectiveFovLH(fieldOfView, screenAspect, screenNear, screenDepth);
                World      = Matrix.Identity;
                Orthogonal = Matrix.OrthoLH(screenWidth, screenHeight, screenNear, screenDepth);
            } catch { return(false); }
            return(true);
        }
Example #27
0
        void InitD3D()
        {
            D3DDevice = new Device(DriverType.Hardware, DeviceCreationFlags.Debug | DeviceCreationFlags.BgraSupport, FeatureLevel.Level_10_0);

            Texture2DDescription colordesc = new Texture2DDescription();
            colordesc.BindFlags = BindFlags.RenderTarget | BindFlags.ShaderResource;
            colordesc.Format = Format.B8G8R8A8_UNorm;
            colordesc.Width = WindowWidth;
            colordesc.Height = WindowHeight;
            colordesc.MipLevels = 1;
            colordesc.SampleDescription = new SampleDescription(1, 0);
            colordesc.Usage = ResourceUsage.Default;
            colordesc.OptionFlags = ResourceOptionFlags.Shared;
            colordesc.CpuAccessFlags = CpuAccessFlags.None;
            colordesc.ArraySize = 1;

            Texture2DDescription depthdesc = new Texture2DDescription();
            depthdesc.BindFlags = BindFlags.DepthStencil;
            depthdesc.Format = Format.D32_Float_S8X24_UInt;
            depthdesc.Width = WindowWidth;
            depthdesc.Height = WindowHeight;
            depthdesc.MipLevels = 1;
            depthdesc.SampleDescription = new SampleDescription(1, 0);
            depthdesc.Usage = ResourceUsage.Default;
            depthdesc.OptionFlags = ResourceOptionFlags.None;
            depthdesc.CpuAccessFlags = CpuAccessFlags.None;
            depthdesc.ArraySize = 1;

            SharedTexture = new Texture2D(D3DDevice, colordesc);
            DepthTexture = new Texture2D(D3DDevice, depthdesc);
            SampleRenderView = new RenderTargetView(D3DDevice, SharedTexture);
            SampleDepthView = new DepthStencilView(D3DDevice, DepthTexture);
            SampleEffect = Effect.FromFile(D3DDevice, "MiniTri.fx", "fx_4_0");
            EffectTechnique technique = SampleEffect.GetTechniqueByIndex(0); ;
            EffectPass pass = technique.GetPassByIndex(0);
            SampleLayout = new InputLayout(D3DDevice, pass.Description.Signature, new[] {
                new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0),
                new InputElement("COLOR", 0, Format.R32G32B32A32_Float, 16, 0) 
            });

            SampleStream = new DataStream(3 * 32, true, true);
            SampleStream.WriteRange(new[] {
                new Vector4(0.0f, 0.5f, 0.5f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f),
                new Vector4(0.5f, -0.5f, 0.5f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f),
                new Vector4(-0.5f, -0.5f, 0.5f, 1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f)
            });
            SampleStream.Position = 0;

            SampleVertices = new Buffer(D3DDevice, SampleStream, new BufferDescription()
            {
                BindFlags = BindFlags.VertexBuffer,
                CpuAccessFlags = CpuAccessFlags.None,
                OptionFlags = ResourceOptionFlags.None,
                SizeInBytes = 3 * 32,
                Usage = ResourceUsage.Default
            });

            D3DDevice.Flush();
        }
Example #28
0
        private void Resize(Size size)
        {
            Utilities.Dispose(ref _deviceContext);
            Utilities.Dispose(ref _backBuffer);
            Utilities.Dispose(ref _renderView);
            Utilities.Dispose(ref _depthBuffer);
            Utilities.Dispose(ref _depthView);
            var context = Direct2D1Platform.Direct3D11Device.ImmediateContext;

            // Resize the backbuffer
            _swapChain.ResizeBuffers(0, 0, 0, Format.Unknown, SwapChainFlags.None);

            // Get the backbuffer from the swapchain
            _backBuffer = Resource.FromSwapChain <Texture2D>(_swapChain, 0);

            // Renderview on the backbuffer
            _renderView = new RenderTargetView(Direct2D1Platform.Direct3D11Device, _backBuffer);

            // Create the depth buffer
            _depthBuffer = new Texture2D(
                Direct2D1Platform.Direct3D11Device,
                new Texture2DDescription()
            {
                Format            = Format.D32_Float_S8X24_UInt,
                ArraySize         = 1,
                MipLevels         = 1,
                Width             = (int)size.Width,
                Height            = (int)size.Height,
                SampleDescription = new SampleDescription(1, 0),
                Usage             = ResourceUsage.Default,
                BindFlags         = BindFlags.DepthStencil,
                CpuAccessFlags    = CpuAccessFlags.None,
                OptionFlags       = ResourceOptionFlags.None
            });

            // Create the depth buffer view
            _depthView = new DepthStencilView(Direct2D1Platform.Direct3D11Device, _depthBuffer);

            // Setup targets and viewport for rendering
            context.Rasterizer.SetViewport(new Viewport(0, 0, (int)size.Width, (int)size.Height, 0.0f, 1.0f));
            context.OutputMerger.SetTargets(_depthView, _renderView);

            // Setup new projection matrix with correct aspect ratio
            _proj = Matrix.PerspectiveFovLH((float)Math.PI / 4.0f, (float)(size.Width / size.Height), 0.1f, 100.0f);

            using (var dxgiBackBuffer = _swapChain.GetBackBuffer <Surface>(0))
            {
                var renderTarget = new SharpDX.Direct2D1.RenderTarget(
                    Direct2D1Platform.Direct2D1Factory,
                    dxgiBackBuffer,
                    new RenderTargetProperties
                {
                    DpiX        = 96,
                    DpiY        = 96,
                    Type        = RenderTargetType.Default,
                    PixelFormat = new PixelFormat(
                        Format.Unknown,
                        AlphaMode.Premultiplied)
                });

                _deviceContext = renderTarget.QueryInterface <DeviceContext>();

                renderTarget.Dispose();
            }
        }
Example #29
0
        public virtual void OnResize()
        {
            Debug.Assert(ImmediateContext != null);
            Debug.Assert(Device != null);
            Debug.Assert(SwapChain != null);

            Util.ReleaseCom(ref RenderTargetView);
            Util.ReleaseCom(ref DepthStencilView);
            Util.ReleaseCom(ref DepthStencilBuffer);

            SwapChain.ResizeBuffers(1, ClientWidth, ClientHeight, Format.R8G8B8A8_UNorm, SwapChainFlags.None);
            using (var resource = SlimDX.Direct3D11.Resource.FromSwapChain<Texture2D>(SwapChain, 0)) {
                RenderTargetView = new RenderTargetView(Device, resource);
                RenderTargetView.Resource.DebugName = "main render target";
            }

            var depthStencilDesc = new Texture2DDescription {
                Width = ClientWidth,
                Height = ClientHeight,
                MipLevels = 1,
                ArraySize = 1,
                Format = Format.D24_UNorm_S8_UInt,
                SampleDescription = (Enable4XMsaa && Device.FeatureLevel >= FeatureLevel.Level_10_1) ? new SampleDescription(4, Msaa4XQuality - 1) : new SampleDescription(1, 0),
                Usage = ResourceUsage.Default,
                BindFlags = BindFlags.DepthStencil,
                CpuAccessFlags = CpuAccessFlags.None,
                OptionFlags = ResourceOptionFlags.None
            };
            DepthStencilBuffer = new Texture2D(Device, depthStencilDesc) { DebugName = "DepthStencilBuffer" };
            DepthStencilView = new DepthStencilView(Device, DepthStencilBuffer);

            ImmediateContext.OutputMerger.SetTargets(DepthStencilView, RenderTargetView);

            Viewport = new Viewport(0, 0, ClientWidth, ClientHeight, 0.0f, 1.0f);

            ImmediateContext.Rasterizer.SetViewports(Viewport);
        }
        private void BindDepthRTInternal(MyBindableResource depthStencil, DepthStencilAccess dsAccess, params MyBindableResource[] RTs)
        {
            DepthStencilView dsv = null;

            if (depthStencil != null)
            {
                var ds = depthStencil as MyDepthStencil;
                Debug.Assert(ds != null);

                // check conflicts
                if (dsAccess == DepthStencilAccess.ReadWrite)
                {
                    // for both
                    // check reads
                    UnbindSRVRead(ds.Depth.GetID());
                    UnbindSRVRead(ds.Stencil.GetID());
                    dsv = ds.m_DSV;
                }
                else if (dsAccess == DepthStencilAccess.DepthReadOnly)
                {
                    // check reads
                    UnbindSRVRead(ds.Depth.GetID());
                    dsv = (ds.Depth as IDepthStencilBindable).DSV;
                }
                else if (dsAccess == DepthStencilAccess.StencilReadOnly)
                {
                    // check reads
                    UnbindSRVRead(ds.Stencil.GetID());
                    dsv = (ds.Stencil as IDepthStencilBindable).DSV;
                }
                else if (dsAccess == DepthStencilAccess.ReadOnly)
                {
                    dsv = ds.m_DSV_ro;
                }
            }
            Array.Clear(State.m_RTVs, 0, State.m_RTVs.Length);
            if (RTs != null)
            {
                for (int i = 0; i < RTs.Length; i++)
                {
                    if (RTs[i] != null)
                    {
                        Debug.Assert(RTs[i] as IRenderTargetBindable != null);
                        UnbindSRVRead(RTs[i].GetID());
                        State.m_RTVs[i] = (RTs[i] as IRenderTargetBindable).RTV;
                    }
                    else
                    {
                        State.m_RTVs[i] = null;
                    }
                }
            }
            DeviceContext.OutputMerger.SetTargets(
                dsv,
                State.m_RTVs);

            ClearDsvRtvWriteBindings();

            if (depthStencil != null)
            {
                var ds = depthStencil as MyDepthStencil;
                if (dsAccess == DepthStencilAccess.ReadWrite)
                {
                    var binding = new MyBinding(MyWriteBindingEnum.DSV);
                    State.m_bindings[ds.Depth.GetID()] = binding;
                    State.m_slotToBindingKeys.Add(binding.UavSlot, ds.Depth.GetID());
                    State.m_bindings[ds.Stencil.GetID()] = binding;
                    State.m_slotToBindingKeys.Add(binding.UavSlot, ds.Stencil.GetID());
                }
                else if (dsAccess == DepthStencilAccess.DepthReadOnly)
                {
                    var depthBinding = new MyBinding(true);
                    State.m_bindings[ds.Depth.GetID()] = depthBinding;
                    State.m_slotToBindingKeys.Add(depthBinding.UavSlot, ds.Depth.GetID());

                    var stencilBinding = new MyBinding(MyWriteBindingEnum.DSV);
                    State.m_bindings[ds.Stencil.GetID()] = stencilBinding;
                    State.m_slotToBindingKeys.Add(stencilBinding.UavSlot, ds.Stencil.GetID());
                }
                else if (dsAccess == DepthStencilAccess.StencilReadOnly)
                {
                    var depthBinding = new MyBinding(MyWriteBindingEnum.DSV);
                    State.m_bindings[ds.Depth.GetID()] = depthBinding;
                    State.m_slotToBindingKeys.Add(depthBinding.UavSlot, ds.Depth.GetID());

                    var stencilBinding = new MyBinding(true);
                    State.m_bindings[ds.Stencil.GetID()] = stencilBinding;
                    State.m_slotToBindingKeys.Add(stencilBinding.UavSlot, ds.Stencil.GetID());
                }
                else if (dsAccess == DepthStencilAccess.ReadOnly)
                {
                    var binding = new MyBinding(true);
                    State.m_bindings[ds.Depth.GetID()]   = binding;
                    State.m_bindings[ds.Stencil.GetID()] = binding;

                    State.m_slotToBindingKeys.Add(binding.UavSlot, ds.Depth.GetID());
                    State.m_slotToBindingKeys.Add(binding.UavSlot, ds.Stencil.GetID());
                }
            }
            if (RTs != null)
            {
                for (int i = 0; i < RTs.Length; i++)
                {
                    if (RTs[i] != null)
                    {
                        var binding = new MyBinding(MyWriteBindingEnum.RTV);
                        State.m_bindings[RTs[i].GetID()] = binding;
                        State.m_slotToBindingKeys.Add(binding.UavSlot, RTs[i].GetID());
                    }
                }
            }
        }
Example #31
0
        public void Render(DeviceContext deviceContext, Viewport viewport, RenderTargetView renderTargetView, DepthStencilView depthStencilView)
        {
            deviceContext.ClearRenderTargetView(renderTargetView, CLEAR_COLOR);
            deviceContext.ClearDepthStencilView(depthStencilView, DepthStencilClearFlags.Depth | DepthStencilClearFlags.Stencil, 1.0f, 0x00);

            // axes
            mDebugRenderer.RenderLine(deviceContext, new Vector3(0f, 0f, 0f), new Vector3(2f, 0f, 0f), new Vector3(1f, 0f, 0f), mBreadcrumber.Camera);
            mDebugRenderer.RenderLine(deviceContext, new Vector3(0f, 0f, 0f), new Vector3(0f, 2f, 0f), new Vector3(0f, 1f, 0f), mBreadcrumber.Camera);
            mDebugRenderer.RenderLine(deviceContext, new Vector3(0f, 0f, 0f), new Vector3(0f, 0f, 2f), new Vector3(0f, 0f, 1f), mBreadcrumber.Camera);

            //// volume
            //mDebugRenderer.RenderBoxGreyScaleTexture3DWireframe(
            //    deviceContext,
            //    new Vector3( 0f, 0f, mBreadcrumber.NormalizedVolumeExtent.Z * mBreadcrumber.CurrentSlice / ( mBreadcrumber.VolumeDescription.NumVoxelsZ - 1f ) ),
            //    mBreadcrumber.NormalizedVolumeExtent,
            //    new Vector3( 0f, 1f, mBreadcrumber.CurrentSlice / ( mBreadcrumber.VolumeDescription.NumVoxelsZ - 1f ) ),
            //    new Vector3( 1f, 0f, 1f ),
            //    mBreadcrumber.SourceTexture,
            //    new Vector3( 1f, 1f, 1f ),
            //    mBreadcrumber.Camera );

            //// breadcrumbs
            //foreach ( var neuralProcessDescription in mBreadcrumber.NeuralProcessDescriptions.Internal.Values )
            //{
            //    foreach ( var breadcrumbDescription in neuralProcessDescription.BreadcrumbDescriptions )
            //    {
            //        mDebugRenderer.RenderSphereSolidWireframe( deviceContext,
            //                                                   MathUtil.TransformAndHomogeneousDivide(
            //                                                       breadcrumbDescription.Position,
            //                                                       mBreadcrumber.VolumeIndexToNormalizedVolumeCoordinates *
            //                                                       mBreadcrumber.NormalizedVolumeCoordinatesToWorldCoordinates ),
            //                                                   0.001f,
            //                                                   MathUtil.ConvertToFloatColor( neuralProcessDescription.Color ),
            //                                                   new Vector3( 1f, 1f, 1f ),
            //                                                   mBreadcrumber.Camera );
            //    }
            //}

            // branch start and end points
            foreach (var neuralProcessDescription in mBreadcrumber.NeuralProcessDescriptions.Internal.Values)
            {
                foreach (var branch in neuralProcessDescription.Branches)
                {
                    mDebugRenderer.RenderSphereSolidWireframe(deviceContext,
                                                              MathUtil.TransformAndHomogeneousDivide(
                                                                  branch.P1,
                                                                  mBreadcrumber.VolumeIndexToNormalizedVolumeCoordinates *
                                                                  mBreadcrumber.NormalizedVolumeCoordinatesToWorldCoordinates),
                                                              0.01f,
                                                              MathUtil.ConvertToFloatColor(neuralProcessDescription.Color),
                                                              new Vector3(1f, 1f, 1f),
                                                              mBreadcrumber.Camera);

                    mDebugRenderer.RenderSphereSolidWireframe(deviceContext,
                                                              MathUtil.TransformAndHomogeneousDivide(
                                                                  branch.P2,
                                                                  mBreadcrumber.VolumeIndexToNormalizedVolumeCoordinates *
                                                                  mBreadcrumber.NormalizedVolumeCoordinatesToWorldCoordinates),
                                                              0.01f,
                                                              MathUtil.ConvertToFloatColor(neuralProcessDescription.Color),
                                                              new Vector3(1f, 1f, 1f),
                                                              mBreadcrumber.Camera);
                }
            }

            // shortest paths
            foreach (var shortestPathDescriptions in mBreadcrumber.ShortestPathDescriptions.Internal.Values)
            {
                var shortestPathDescription = shortestPathDescriptions[0];

                foreach (var shortestPathEdge in shortestPathDescription.SmoothPath)
                {
                    var p1 = MathUtil.TransformAndHomogeneousDivide(
                        shortestPathEdge.P1,
                        mBreadcrumber.VolumeIndexToNormalizedVolumeCoordinates *
                        mBreadcrumber.NormalizedVolumeCoordinatesToWorldCoordinates);

                    var p2 = MathUtil.TransformAndHomogeneousDivide(
                        shortestPathEdge.P2,
                        mBreadcrumber.VolumeIndexToNormalizedVolumeCoordinates *
                        mBreadcrumber.NormalizedVolumeCoordinatesToWorldCoordinates);

                    mDebugRenderer.RenderLine(deviceContext, p1, p2, new Vector3(1f, 1f, 0f), mBreadcrumber.Camera);
                }

                shortestPathDescription = shortestPathDescriptions[1];

                foreach (var shortestPathEdge in shortestPathDescription.SmoothPath)
                {
                    var p1 = MathUtil.TransformAndHomogeneousDivide(
                        shortestPathEdge.P1,
                        mBreadcrumber.VolumeIndexToNormalizedVolumeCoordinates *
                        mBreadcrumber.NormalizedVolumeCoordinatesToWorldCoordinates);

                    var p2 = MathUtil.TransformAndHomogeneousDivide(
                        shortestPathEdge.P2,
                        mBreadcrumber.VolumeIndexToNormalizedVolumeCoordinates *
                        mBreadcrumber.NormalizedVolumeCoordinatesToWorldCoordinates);

                    mDebugRenderer.RenderLine(deviceContext, p1, p2, new Vector3(1f, 0f, 1f), mBreadcrumber.Camera);
                }

                shortestPathDescription = shortestPathDescriptions[2];

                foreach (var shortestPathEdge in shortestPathDescription.SmoothPath)
                {
                    var p1 = MathUtil.TransformAndHomogeneousDivide(
                        shortestPathEdge.P1,
                        mBreadcrumber.VolumeIndexToNormalizedVolumeCoordinates *
                        mBreadcrumber.NormalizedVolumeCoordinatesToWorldCoordinates);

                    var p2 = MathUtil.TransformAndHomogeneousDivide(
                        shortestPathEdge.P2,
                        mBreadcrumber.VolumeIndexToNormalizedVolumeCoordinates *
                        mBreadcrumber.NormalizedVolumeCoordinatesToWorldCoordinates);

                    mDebugRenderer.RenderLine(deviceContext, p1, p2, new Vector3(0f, 1f, 1f), mBreadcrumber.Camera);
                }
            }

            var currentEdgeUnnormalized = mBreadcrumber.ShortestPathDescriptions.Get("Trail 1")[0].SmoothPath[mBreadcrumber.CurrentEdge];

            var currentEdgeP1 = MathUtil.TransformAndHomogeneousDivide(
                currentEdgeUnnormalized.P1,
                mBreadcrumber.VolumeIndexToNormalizedVolumeCoordinates);

            var currentEdgeP2 = MathUtil.TransformAndHomogeneousDivide(
                currentEdgeUnnormalized.P2,
                mBreadcrumber.VolumeIndexToNormalizedVolumeCoordinates);

            var forward = currentEdgeP2 - currentEdgeP1;
            var upHint  = new Vector3(0f, 1f, 0f);
            var right   = Vector3.Cross(upHint, forward);
            var up      = Vector3.Cross(forward, right);

            forward.Normalize();
            right.Normalize();
            up.Normalize();

            var q1 = currentEdgeP1 - right - up;
            var q2 = currentEdgeP1 - right + up;
            var q3 = currentEdgeP1 + right + up;
            var q4 = currentEdgeP1 + right - up;

            mDebugRenderer.RenderQuadGreyScaleTexture3DWireframe(
                deviceContext,
                MathUtil.TransformAndHomogeneousDivide(q1, mBreadcrumber.NormalizedVolumeCoordinatesToWorldCoordinates),
                MathUtil.TransformAndHomogeneousDivide(q2, mBreadcrumber.NormalizedVolumeCoordinatesToWorldCoordinates),
                MathUtil.TransformAndHomogeneousDivide(q3, mBreadcrumber.NormalizedVolumeCoordinatesToWorldCoordinates),
                MathUtil.TransformAndHomogeneousDivide(q4, mBreadcrumber.NormalizedVolumeCoordinatesToWorldCoordinates),
                MathUtil.TransformAndHomogeneousDivide(q1, mBreadcrumber.NormalizedVolumeCoordinatesToTextureCoordinates),
                MathUtil.TransformAndHomogeneousDivide(q2, mBreadcrumber.NormalizedVolumeCoordinatesToTextureCoordinates),
                MathUtil.TransformAndHomogeneousDivide(q3, mBreadcrumber.NormalizedVolumeCoordinatesToTextureCoordinates),
                MathUtil.TransformAndHomogeneousDivide(q4, mBreadcrumber.NormalizedVolumeCoordinatesToTextureCoordinates),
                mBreadcrumber.SourceTexture,
                new Vector3(1f, 1f, 1f),
                mBreadcrumber.Camera);

            if (Constants.RECORDING_MODE == RecordingMode.NotRecording)
            {
                mTinyTextContext.Print(viewport, "Frame Time: " + FrameTimeString, 10, 10);
                mTinyTextContext.Render();
            }

            mStopwatch.Reset();
        }
Example #32
0
        /// <summary>
        /// Updates resources associated with a holographic camera's swap chain.
        /// The app does not access the swap chain directly, but it does create
        /// resource views for the back buffer.
        /// </summary>
        public void CreateResourcesForBackBuffer(
            DeviceResources deviceResources,
            ref HolographicCameraRenderingParameters cameraParameters
            )
        {
            var device = deviceResources.D3DDevice;

            // Get the WinRT object representing the holographic camera's back buffer.
            IDirect3DSurface surface = cameraParameters.Direct3D11BackBuffer;

            // Get a DXGI interface for the holographic camera's back buffer.
            // Holographic cameras do not provide the DXGI swap chain, which is owned
            // by the system. The Direct3D back buffer resource is provided using WinRT
            // interop APIs.
            InteropStatics.IDirect3DDxgiInterfaceAccess surfaceDxgiInterfaceAccess = surface as InteropStatics.IDirect3DDxgiInterfaceAccess;
            IntPtr pResource = surfaceDxgiInterfaceAccess.GetInterface(InteropStatics.ID3D11Resource);

            // Determine if the back buffer has changed. If so, ensure that the render target view
            // is for the current back buffer.
            if ((null == d3dBackBuffer) || (d3dBackBuffer.NativePointer != pResource))
            {
                // Clean up references to previous resources.
                this.RemoveAndDispose(ref d3dBackBuffer);
                this.RemoveAndDispose(ref d3dRenderTargetView);

                // This can change every frame as the system moves to the next buffer in the
                // swap chain. This mode of operation will occur when certain rendering modes
                // are activated.
                d3dBackBuffer = this.ToDispose(new SharpDX.Direct3D11.Texture2D(pResource));

                // Create a render target view of the back buffer.
                // Creating this resource is inexpensive, and is better than keeping track of
                // the back buffers in order to pre-allocate render target views for each one.
                d3dRenderTargetView = this.ToDispose(new RenderTargetView(device, d3dBackBuffer));

                // Get the DXGI format for the back buffer.
                // This information can be accessed by the app using CameraResources::GetBackBufferDXGIFormat().
                Texture2DDescription backBufferDesc = BackBufferTexture2D.Description;
                dxgiFormat = backBufferDesc.Format;

                // Check for render target size changes.
                Size currentSize = holographicCamera.RenderTargetSize;
                if (d3dRenderTargetSize != currentSize)
                {
                    // Set render target size.
                    d3dRenderTargetSize = HolographicCamera.RenderTargetSize;

                    // A new depth stencil view is also needed.
                    this.RemoveAndDispose(ref d3dDepthStencilView);
                }
            }

            // We took a reference to a COM interface when we got the native pointer; here, we
            // release that reference.
            Marshal.Release(pResource);

            // Refresh depth stencil resources, if needed.
            if (null == DepthStencilView)
            {
                // Create a depth stencil view for use with 3D rendering if needed.
                var depthStencilDesc = new Texture2DDescription
                {
                    Format            = SharpDX.DXGI.Format.D16_UNorm,
                    Width             = (int)RenderTargetSize.Width,
                    Height            = (int)RenderTargetSize.Height,
                    ArraySize         = IsRenderingStereoscopic ? 2 : 1, // Create two textures when rendering in stereo.
                    MipLevels         = 1,                               // Use a single mipmap level.
                    BindFlags         = BindFlags.DepthStencil,
                    SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0)
                };

                using (var depthStencil = new Texture2D(device, depthStencilDesc))
                {
                    var depthStencilViewDesc = new DepthStencilViewDescription();
                    depthStencilViewDesc.Dimension = IsRenderingStereoscopic ? DepthStencilViewDimension.Texture2DArray : DepthStencilViewDimension.Texture2D;
                    depthStencilViewDesc.Texture2DArray.ArraySize = IsRenderingStereoscopic ? 2 : 0;
                    d3dDepthStencilView = this.ToDispose(new DepthStencilView(device, depthStencil, depthStencilViewDesc));
                }
            }

            // Create the constant buffer, if needed.
            if (null == viewProjectionConstantBuffer)
            {
                // Create a constant buffer to store view and projection matrices for the camera.
                ViewProjectionConstantBuffer viewProjectionConstantBufferData = new ViewProjectionConstantBuffer();
                viewProjectionConstantBuffer = this.ToDispose(SharpDX.Direct3D11.Buffer.Create(
                                                                  device,
                                                                  BindFlags.ConstantBuffer,
                                                                  ref viewProjectionConstantBufferData));
            }
        }
Example #33
0
        public void Setup(OperatorPart outputOpPart, double startTime = 0, double endTime = 184, double frameRate   = 30, double width                = 1920, double height = 1080,
                          string fileExtension = "png", bool skipExistingFiles            = false, string directory = "output", string filenameFormat = "[T]", SharpDX.DXGI.Format imageFormat = Format.R8G8B8A8_UNorm)
        {
            try
            {
                Dispose();

                _outputOpPart      = outputOpPart;
                _directory         = directory;
                _fileNameFormat    = filenameFormat;
                _startTime         = startTime;
                _endTime           = endTime;
                _frameRate         = frameRate;
                _width             = (int)width;
                _height            = (int)height;
                _samples           = 2;
                _fileExtension     = fileExtension.ToLower();
                _skipExistingFiles = skipExistingFiles;

                _defaultContext = new OperatorPartContext(0.0f);
                _defaultContext.Variables.Add("Screensize.Width", _width);
                _defaultContext.Variables.Add("Screensize.Height", _height);
                _defaultContext.Variables.Add("AspectRatio", (float)_width / _height);
                _defaultContext.Variables.Add("Samples", _samples);
                _defaultContext.Variables.Add("FullScreen", 0.0f);
                _defaultContext.Variables.Add("LoopMode", 0.0f);
                _defaultContext.ImageBufferFormat = imageFormat;

                _frameTime = 1.0 / _frameRate;

                Directory.CreateDirectory(_directory);

                _renderer = new DefaultRenderer();

                _texture = ShaderResourceView.FromFile(D3DDevice.Device, "./assets-common/image/white.png");


                _renderTargetResource = null;
                ResourceManager.ValidateRenderTargetResource(ref _renderTargetResource, _outputOpPart, D3DDevice.Device, _width, _height, imageFormat);
                _renderTargetView = new RenderTargetView(D3DDevice.Device, _renderTargetResource.Texture);

                _renderDepthResource = null;
                ResourceManager.ValidateDepthStencilResource(ref _renderDepthResource, _outputOpPart, D3DDevice.Device, _width, _height);
                var depthViewDesc = new DepthStencilViewDescription();
                depthViewDesc.Format    = Format.D32_Float;
                depthViewDesc.Dimension = DepthStencilViewDimension.Texture2D;

                _renderTargetDepthView = new DepthStencilView(D3DDevice.Device, _renderDepthResource.Texture, depthViewDesc);

                _gpuSyncer = new BlockingGpuSyncer(D3DDevice.Device);

                D3DDevice.Device.ImmediateContext.OutputMerger.SetTargets(_renderTargetDepthView, _renderTargetView);
                _viewport = new ViewportF(0, 0, _width, _height, 0.0f, 1.0f);
                D3DDevice.Device.ImmediateContext.Rasterizer.SetViewport(_viewport);


                var timeAccessorCollector = new OperatorPart.CollectOpPartFunctionsOfType <OperatorPartTraits.ITimeAccessor>();
                _outputOpPart.TraverseWithFunction(timeAccessorCollector, null);
                _timeAccessorOpPartFunctions = new List <OperatorPart.Function>();
                foreach (var opPartFunction in timeAccessorCollector.CollectedOpPartFunctions)
                {
                    _timeAccessorOpPartFunctions.Add(opPartFunction as OperatorPart.Function);
                }
                _currentTime  = _startTime;
                _currentFrame = 0;
            }
            catch (Exception e)
            {
                Logger.Error("Failed to setup image-sequence {0}", e.Message);
            }
        }
Example #34
0
 public void SetRenderTarget(DeviceContext context, DepthStencilView depthStencilView)
 {
     // Bind the render target view and depth stencil buffer to the output pipeline.
     context.OutputMerger.SetTargets(depthStencilView, RenderTargetView);
 }
 public void InitializeBuffers()
 {
     Helper.Dispose(ReadOnlyDepth, litBuffer, litTarget);
     DepthStencilViewDescription dsvDesc = Renderer.BackBufferDepth.Description;
     dsvDesc.Flags = DepthStencilViewFlags.ReadOnlyDepth;
     ReadOnlyDepth = new DepthStencilView(Renderer.Device, Renderer.OutputDepth, dsvDesc);
     Texture2DDescription litBufferDesc = Renderer.OutputTexture.Description;
     //TODO: This format
     litBufferDesc.Format = SlimDX.DXGI.Format.R11G11B10_Float;
     using (Texture2D tex = new Texture2D(Renderer.Device, litBufferDesc))
     {
         litTarget = new RenderTargetView(Renderer.Device, tex);
         litBuffer = new ShaderResourceView(Renderer.Device, tex, new ShaderResourceViewDescription()
         {
             Dimension = tex.Description.SampleDescription.Count > 1 ? ShaderResourceViewDimension.Texture2DMultisampled : ShaderResourceViewDimension.Texture2D,
             Format = tex.Description.Format,
             ArraySize = 1,
             MipLevels = 1,
             FirstArraySlice = 0,
             MostDetailedMip = 0
         });
     }
     GBuffer.Initialize();
 }
Example #36
0
        /// <summary>
        /// Creates render target
        /// </summary>
        /// <param name="rs"></param>
        /// <param name="width"></param>
        /// <param name="height"></param>
        /// <param name="format"></param>
        public DepthStencilCube(GraphicsDevice device, DepthFormat format, int size, int samples, string debugName = "") : base(device)
        {
            bool msaa = samples > 1;

            CheckSamplesCount(samples);

            SampleCount = samples;

            Format      = format;
            SampleCount = samples;
            Width       = size;
            Height      = size;
            Depth       = 1;

            var texDesc = new Texture2DDescription();

            texDesc.Width             = Width;
            texDesc.Height            = Height;
            texDesc.ArraySize         = 6;
            texDesc.BindFlags         = BindFlags.RenderTarget | BindFlags.ShaderResource;
            texDesc.CpuAccessFlags    = CpuAccessFlags.None;
            texDesc.Format            = Converter.ConvertToTex(format);
            texDesc.MipLevels         = 1;
            texDesc.OptionFlags       = ResourceOptionFlags.TextureCube;
            texDesc.SampleDescription = new DXGI.SampleDescription(samples, 0);
            texDesc.Usage             = ResourceUsage.Default;


            texCube = new D3D.Texture2D(device.Device, texDesc);


            var srvDesc = new ShaderResourceViewDescription();

            srvDesc.Dimension = samples > 1 ? ShaderResourceViewDimension.Texture2DMultisampled : ShaderResourceViewDimension.Texture2D;
            srvDesc.Format    = Converter.ConvertToSRV(format);
            srvDesc.Texture2D.MostDetailedMip = 0;
            srvDesc.Texture2D.MipLevels       = 1;

            SRV = new ShaderResourceView(device.Device, texCube);



            //
            //	Create surfaces :
            //
            surfaces = new DepthStencilSurface[6];

            for (int face = 0; face < 6; face++)
            {
                var rtvDesc = new DepthStencilViewDescription();
                rtvDesc.Texture2DArray.MipSlice        = 0;
                rtvDesc.Texture2DArray.FirstArraySlice = face;
                rtvDesc.Texture2DArray.ArraySize       = 1;
                rtvDesc.Dimension = msaa ? DepthStencilViewDimension.Texture2DMultisampledArray : DepthStencilViewDimension.Texture2DArray;
                rtvDesc.Format    = Converter.ConvertToDSV(format);

                var dsv = new DepthStencilView(device.Device, texCube, rtvDesc);

                int subResId = Resource.CalculateSubResourceIndex(0, face, 1);

                surfaces[face] = new DepthStencilSurface(dsv, format, Width, Height, SampleCount);
            }
        }
Example #37
0
        void CreateViews(string name, BindFlags flags, SlimDX.Direct3D11.Resource resource)
        {
            if (flags.HasFlag(BindFlags.RenderTarget))
            {
                var view = new RenderTargetView(m_D3dDevice, resource);
                m_RTVList.Add(name, view);
            }

            if (flags.HasFlag(BindFlags.DepthStencil))
            {
                var view = new DepthStencilView(m_D3dDevice, resource);
                m_DSVList.Add(name, view);
            }

            if (flags.HasFlag(BindFlags.ShaderResource))
            {
                var view = new ShaderResourceView(m_D3dDevice, resource);
                m_SRVList.Add(name, view);
            }

            if (flags.HasFlag(BindFlags.UnorderedAccess))
            {
                var view = new UnorderedAccessView(m_D3dDevice, resource);
                m_UAVList.Add(name, view);
            }
        }
Example #38
0
        /// <summary>
        /// Инициализирует объекты связанные с графическим устройство - Девайс его контекст и Свапчейн
        /// </summary>
        private void InitializeDeviceResources()
        {
            var creationFlags = DeviceCreationFlags.None;

#if DEBUG
            creationFlags = DeviceCreationFlags.Debug;
#endif

            //Создаем объектное преставление нашего GPU, его контекст и класс который будет менят местами буфферы в которые рисует наша GPU
            SharpDX.Direct3D11.Device.CreateWithSwapChain(
                SharpDX.Direct3D.DriverType.Hardware,
                creationFlags | DeviceCreationFlags.BgraSupport,
                new[] { SharpDX.Direct3D.FeatureLevel.Level_11_0 },
                new SwapChainDescription()
            {
                ModeDescription = new ModeDescription(
                    _renderForm.Width,
                    _renderForm.Height,
                    new Rational(60, 1),
                    Format.R8G8B8A8_UNorm),
                SampleDescription = new SampleDescription(4, 0),
                Usage             = Usage.BackBuffer | Usage.RenderTargetOutput,
                BufferCount       = 2,
                OutputHandle      = _renderForm.Handle,
                IsWindowed        = true,
                SwapEffect        = SwapEffect.Discard,
                Flags             = SwapChainFlags.None
            },
                out _dx11Device,
                out _swapChain);
            //Игноровать все события видновс
            _factory = _swapChain.GetParent <SharpDX.DXGI.Factory>();
            _factory.MakeWindowAssociation(_renderForm.Handle, WindowAssociationFlags.IgnoreAll);
            // Создаем буффер и вьюшку глубины
            using (var _depthBuffer = new Texture2D(
                       _dx11Device,
                       new Texture2DDescription()
            {
                Format = Format.D32_Float_S8X24_UInt,
                ArraySize = 1,
                MipLevels = 1,
                Width = _renderForm.Width,
                Height = _renderForm.Height,
                SampleDescription = _swapChain.Description.SampleDescription,
                Usage = ResourceUsage.Default,
                BindFlags = BindFlags.DepthStencil,
                CpuAccessFlags = CpuAccessFlags.None,
                OptionFlags = ResourceOptionFlags.None
            }))
                _depthView = new DepthStencilView(_dx11Device, _depthBuffer, new SharpDX.Direct3D11.DepthStencilViewDescription()
                {
                    Dimension = (SwapChain.Description.SampleDescription.Count > 1 ||
                                 SwapChain.Description.SampleDescription.Quality > 0) ?
                                DepthStencilViewDimension.Texture2DMultisampled :
                                DepthStencilViewDimension.Texture2D,
                    Flags = DepthStencilViewFlags.None
                });
            //Создаем буффер и вьюшку для рисования
            using (Texture2D backBuffer = _swapChain.GetBackBuffer <Texture2D>(0))
                _renderView = new RenderTargetView(_dx11Device, backBuffer);
            //Создаем контекст нашего GPU
            _dx11DeviceContext = _dx11Device.ImmediateContext;
            //Устанавливаем размер конечной картинки
            _dx11DeviceContext.Rasterizer.SetViewport(0, 0, _renderForm.Width, _renderForm.Height);
            _dx11DeviceContext.OutputMerger.SetTargets(_depthView, _renderView);
        }
Example #39
0
		void InitD3D()
		{
			var swapDesc = new Dxgi.SwapChainDescription
			{
				BufferCount = 1,
				ModeDescription = new Dxgi.ModeDescription
					{
						Width = Container.ClientSize.Width,
						Height = Container.ClientSize.Height,
						RefreshRate = new Rational(60, 1),
						Format = Dxgi.Format.R8G8B8A8_UNorm
					},
				IsWindowed = true,
				OutputHandle = Container.Handle,
				SampleDescription = new Dxgi.SampleDescription(1, 0),
				SwapEffect = Dxgi.SwapEffect.Discard,
				Usage = Dxgi.Usage.RenderTargetOutput
			};

			Device device;
			Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.Debug | DeviceCreationFlags.BgraSupport,
				swapDesc, out device, out SwapChain);
			Device = device;
			m_context = Device.ImmediateContext;

			Texture2DDescription colordesc = new Texture2DDescription
			{
				BindFlags = BindFlags.RenderTarget | BindFlags.ShaderResource,
				Format = Dxgi.Format.B8G8R8A8_UNorm,
				Width = Width,
				Height = Height,
				MipLevels = 1,
				SampleDescription = new Dxgi.SampleDescription(1, 0),
				Usage = ResourceUsage.Default,
				OptionFlags = ResourceOptionFlags.Shared,
				CpuAccessFlags = CpuAccessFlags.None,
				ArraySize = 1
			};

			Texture2DDescription depthdesc = new Texture2DDescription
			{
				BindFlags = BindFlags.DepthStencil,
				Format = Dxgi.Format.D24_UNorm_S8_UInt,
				Width = Width,
				Height = Height,
				MipLevels = 1,
				SampleDescription = new Dxgi.SampleDescription(1, 0),
				Usage = ResourceUsage.Default,
				OptionFlags = ResourceOptionFlags.None,
				CpuAccessFlags = CpuAccessFlags.None,
				ArraySize = 1
			};

			SharedTexture = new Texture2D(Device, colordesc);
			DepthTexture = new Texture2D(Device, depthdesc);
			RenderView = new RenderTargetView(Device, SharedTexture);
			DepthView = new DepthStencilView(Device, DepthTexture);

			var rastDesc = new RasterizerStateDescription()
			{
				CullMode = CullMode.None,
				FillMode = FillMode.Solid,
			};
			m_context.Rasterizer.State = RasterizerState.FromDescription(Device, rastDesc);

			QuadIndices = RenderSupport.InitQuadIndices(Device);

			m_context.Flush();
		}
Example #40
0
        public bool Initialize(DSystemConfiguration configuration, IntPtr windowHandle)
        {
            try
            {
                #region Environment Configuration
                // Store the vsync setting.
                VerticalSyncEnabled = DSystemConfiguration.VerticalSyncEnabled;

                // Create a DirectX graphics interface factory.
                var factory = new Factory1();

                // Use the factory to create an adapter for the primary graphics interface (video card).
                var adapter = factory.GetAdapter1(0);

                // Get the primary adapter output (monitor).
                var monitor = adapter.GetOutput(0);

                // Get modes that fit the DXGI_FORMAT_R8G8B8A8_UNORM display format for the adapter output (monitor).
                var modes = monitor.GetDisplayModeList(Format.R8G8B8A8_UNorm, DisplayModeEnumerationFlags.Interlaced);

                // Now go through all the display modes and find the one that matches the screen width and height.
                // When a match is found store the the refresh rate for that monitor, if vertical sync is enabled.
                // Otherwise we use maximum refresh rate.
                var rational = new Rational(0, 1);
                if (VerticalSyncEnabled)
                {
                    foreach (var mode in modes)
                    {
                        if (mode.Width == configuration.Width && mode.Height == configuration.Height)
                        {
                            rational = new Rational(mode.RefreshRate.Numerator, mode.RefreshRate.Denominator);
                            break;
                        }
                    }
                }

                // Get the adapter (video card) description.
                var adapterDescription = adapter.Description;

                // Store the dedicated video card memory in megabytes.
                VideoCardMemory = adapterDescription.DedicatedVideoMemory >> 10 >> 10;

                // Convert the name of the video card to a character array and store it.
                VideoCardDescription = adapterDescription.Description.Trim('\0');

                // Release the adapter output.
                monitor.Dispose();
                // Release the adapter.
                adapter.Dispose();
                // Release the factory.
                factory.Dispose();
                #endregion

                #region Initialize swap chain and d3d device
                // Initialize the swap chain description.
                var swapChainDesc = new SwapChainDescription()
                {
                    // Set to a single back buffer.
                    BufferCount = 1,
                    // Set the width and height of the back buffer.
                    ModeDescription = new ModeDescription(configuration.Width, configuration.Height, rational, Format.R8G8B8A8_UNorm)
                    {
                        Scaling = DisplayModeScaling.Unspecified, ScanlineOrdering = DisplayModeScanlineOrder.Unspecified
                    },
                    // Set the usage of the back buffer.
                    Usage = Usage.RenderTargetOutput,
                    // Set the handle for the window to render to.
                    OutputHandle = windowHandle,
                    // Turn multisampling off.
                    SampleDescription = new SampleDescription(1, 0),
                    // Set to full screen or windowed mode.
                    IsWindowed = !DSystemConfiguration.FullScreen,
                    // Don't set the advanced flags.
                    Flags = SwapChainFlags.None,
                    // Discard the back buffer content after presenting.
                    SwapEffect = SwapEffect.Discard
                };

                // Create the swap chain, Direct3D device, and Direct3D device context.
                SharpDX.Direct3D11.Device device;
                SwapChain swapChain;
                SharpDX.Direct3D11.Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.None, swapChainDesc, out device, out swapChain);

                Device        = device;
                SwapChain     = swapChain;
                DeviceContext = device.ImmediateContext;
                #endregion

                #region Initialize buffers
                // Get the pointer to the back buffer.
                var backBuffer = Texture2D.FromSwapChain <Texture2D>(SwapChain, 0);

                // Create the render target view with the back buffer pointer.
                RenderTargetView = new RenderTargetView(device, backBuffer);

                // Release pointer to the back buffer as we no longer need it.
                backBuffer.Dispose();

                // Initialize and set up the description of the depth buffer.
                var depthBufferDesc = new Texture2DDescription()
                {
                    Width             = configuration.Width,
                    Height            = configuration.Height,
                    MipLevels         = 1,
                    ArraySize         = 1,
                    Format            = Format.D24_UNorm_S8_UInt,
                    SampleDescription = new SampleDescription(1, 0),
                    Usage             = ResourceUsage.Default,
                    BindFlags         = BindFlags.DepthStencil,
                    CpuAccessFlags    = CpuAccessFlags.None,
                    OptionFlags       = ResourceOptionFlags.None
                };

                // Create the texture for the depth buffer using the filled out description.
                DepthStencilBuffer = new Texture2D(device, depthBufferDesc);
                #endregion

                #region Initialize Depth Enabled Stencil
                // Initialize and set up the description of the stencil state.
                var depthStencilDesc = new DepthStencilStateDescription()
                {
                    IsDepthEnabled   = true,
                    DepthWriteMask   = DepthWriteMask.All,
                    DepthComparison  = Comparison.Less,
                    IsStencilEnabled = true,
                    StencilReadMask  = 0xFF,
                    StencilWriteMask = 0xFF,
                    // Stencil operation if pixel front-facing.
                    FrontFace = new DepthStencilOperationDescription()
                    {
                        FailOperation      = StencilOperation.Keep,
                        DepthFailOperation = StencilOperation.Increment,
                        PassOperation      = StencilOperation.Keep,
                        Comparison         = Comparison.Always
                    },
                    // Stencil operation if pixel is back-facing.
                    BackFace = new DepthStencilOperationDescription()
                    {
                        FailOperation      = StencilOperation.Keep,
                        DepthFailOperation = StencilOperation.Decrement,
                        PassOperation      = StencilOperation.Keep,
                        Comparison         = Comparison.Always
                    }
                };

                // Create the depth stencil state.
                DepthStencilState = new DepthStencilState(Device, depthStencilDesc);

                // Set the depth stencil state.
                DeviceContext.OutputMerger.SetDepthStencilState(DepthStencilState, 1);
                #endregion

                #region Initialize Output Merger
                // Initialize and set up the depth stencil view.
                var depthStencilViewDesc = new DepthStencilViewDescription()
                {
                    Format    = Format.D24_UNorm_S8_UInt,
                    Dimension = DepthStencilViewDimension.Texture2D,
                    Texture2D = new DepthStencilViewDescription.Texture2DResource()
                    {
                        MipSlice = 0
                    }
                };

                // Create the depth stencil view.
                DepthStencilView = new DepthStencilView(Device, DepthStencilBuffer, depthStencilViewDesc);

                // Bind the render target view and depth stencil buffer to the output render pipeline.
                DeviceContext.OutputMerger.SetTargets(DepthStencilView, RenderTargetView);
                #endregion

                #region Initialize Raster State
                // Setup the raster description which will determine how and what polygon will be drawn.
                var rasterDesc = new RasterizerStateDescription()
                {
                    IsAntialiasedLineEnabled = false,
                    CullMode                = CullMode.Back,
                    DepthBias               = 0,
                    DepthBiasClamp          = .0f,
                    IsDepthClipEnabled      = true,
                    FillMode                = FillMode.Solid,
                    IsFrontCounterClockwise = false,
                    IsMultisampleEnabled    = false,
                    IsScissorEnabled        = false,
                    SlopeScaledDepthBias    = .0f
                };

                // Create the rasterizer state from the description we just filled out.
                RasterState = new RasterizerState(Device, rasterDesc);

                // Now set the rasterizer state.
                DeviceContext.Rasterizer.State = RasterState;
                #endregion

                #region Initialize Rasterizer
                ViewPort = new ViewportF(0.0f, 0.0f, (float)configuration.Width, (float)configuration.Height, 0.0f, 1.0f);

                // Setup and create the viewport for rendering.
                DeviceContext.Rasterizer.SetViewport(ViewPort);
                #endregion

                #region Initialize matrices
                // Setup and create the projection matrix.
                ProjectionMatrix = Matrix.PerspectiveFovLH((float)(Math.PI / 4), ((float)configuration.Width / (float)configuration.Height), DSystemConfiguration.ScreenNear, DSystemConfiguration.ScreenDepth);

                // Initialize the world matrix to the identity matrix.
                WorldMatrix = Matrix.Identity;

                // Create an orthographic projection matrix for 2D rendering.
                OrthoMatrix = Matrix.OrthoLH(configuration.Width, configuration.Height, DSystemConfiguration.ScreenNear, DSystemConfiguration.ScreenDepth);
                #endregion

                #region Initialize Depth Disabled Stencil
                // Now create a second depth stencil state which turns off the Z buffer for 2D rendering. Added in Tutorial 11
                // The difference is that DepthEnable is set to false.
                // All other parameters are the same as the other depth stencil state.
                var depthDisabledStencilDesc = new DepthStencilStateDescription()
                {
                    IsDepthEnabled   = false,
                    DepthWriteMask   = DepthWriteMask.All,
                    DepthComparison  = Comparison.Less,
                    IsStencilEnabled = true,
                    StencilReadMask  = 0xFF,
                    StencilWriteMask = 0xFF,
                    // Stencil operation if pixel front-facing.
                    FrontFace = new DepthStencilOperationDescription()
                    {
                        FailOperation      = StencilOperation.Keep,
                        DepthFailOperation = StencilOperation.Increment,
                        PassOperation      = StencilOperation.Keep,
                        Comparison         = Comparison.Always
                    },
                    // Stencil operation if pixel is back-facing.
                    BackFace = new DepthStencilOperationDescription()
                    {
                        FailOperation      = StencilOperation.Keep,
                        DepthFailOperation = StencilOperation.Decrement,
                        PassOperation      = StencilOperation.Keep,
                        Comparison         = Comparison.Always
                    }
                };

                // Create the depth stencil state.
                DepthDisabledStencilState = new DepthStencilState(Device, depthDisabledStencilDesc);
                #endregion

                #region Initialize Blend States
                // Create an alpha enabled blend state description.
                var blendStateDesc = new BlendStateDescription();
                blendStateDesc.RenderTarget[0].IsBlendEnabled        = true;
                blendStateDesc.RenderTarget[0].SourceBlend           = BlendOption.One;
                blendStateDesc.RenderTarget[0].DestinationBlend      = BlendOption.InverseSourceAlpha;
                blendStateDesc.RenderTarget[0].BlendOperation        = BlendOperation.Add;
                blendStateDesc.RenderTarget[0].SourceAlphaBlend      = BlendOption.One;
                blendStateDesc.RenderTarget[0].DestinationAlphaBlend = BlendOption.Zero;
                blendStateDesc.RenderTarget[0].AlphaBlendOperation   = BlendOperation.Add;
                blendStateDesc.RenderTarget[0].RenderTargetWriteMask = ColorWriteMaskFlags.All;

                // Create the blend state using the description.
                AlphaEnableBlendingState = new BlendState(device, blendStateDesc);

                // Modify the description to create an disabled blend state description.
                blendStateDesc.RenderTarget[0].IsBlendEnabled = false;

                // Create the Disabled blend state using the description.
                AlphaDisableBlendingState = new BlendState(device, blendStateDesc);
                #endregion

                return(true);
            }
            catch (Exception)
            {
                return(false);
            }
        }
        public void OnInitialise(InitialiseMessage msg)
        {
            // Initialise renderer
            Console.WriteLine("Initialising renderer...");
            rendermsg = new RenderMessage();
            updatemsg = new UpdateMessage();

            // Create the window
            window = new RenderForm("Castle Renderer - 11030062");
            window.Width = 1280;
            window.Height = 720;

            // Add form events
            window.FormClosed += window_FormClosed;

            // Defaults
            ClearColour = new Color4(1.0f, 0.0f, 0.0f, 1.0f);

            // Setup the device
            var description = new SwapChainDescription()
            {
                BufferCount = 1,
                Usage = Usage.RenderTargetOutput,
                OutputHandle = window.Handle,
                IsWindowed = true,
                ModeDescription = new ModeDescription(0, 0, new Rational(60, 1), Format.R8G8B8A8_UNorm),
                SampleDescription = new SampleDescription(1, 0),
                Flags = SwapChainFlags.AllowModeSwitch,
                SwapEffect = SwapEffect.Discard
            };
            Device tmp;
            var result = Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.None, description, out tmp, out swapchain);
            if (result.IsFailure)
            {
                Console.WriteLine("Failed to create Direct3D11 device (" + result.Code.ToString() + ":" + result.Description + ")");
                return;
            }
            Device = tmp;
            context = Device.ImmediateContext;
            using (var factory = swapchain.GetParent<Factory>())
                factory.SetWindowAssociation(window.Handle, WindowAssociationFlags.IgnoreAltEnter);

            // Check AA stuff
            int q = Device.CheckMultisampleQualityLevels(Format.R8G8B8A8_UNorm, 8);

            // Setup the viewport
            viewport = new Viewport(0.0f, 0.0f, window.ClientSize.Width, window.ClientSize.Height);
            viewport.MinZ = 0.0f;
            viewport.MaxZ = 1.0f;
            context.Rasterizer.SetViewports(viewport);

            // Setup the backbuffer
            using (var resource = Resource.FromSwapChain<Texture2D>(swapchain, 0))
                rtBackbuffer = new RenderTargetView(Device, resource);

            // Setup depth for backbuffer
            {
                Texture2DDescription texdesc = new Texture2DDescription()
                {
                    ArraySize = 1,
                    BindFlags = BindFlags.DepthStencil,
                    CpuAccessFlags = CpuAccessFlags.None,
                    Format = Format.D32_Float,
                    Width = (int)viewport.Width,
                    Height = (int)viewport.Height,
                    MipLevels = 1,
                    OptionFlags = ResourceOptionFlags.None,
                    SampleDescription = new SampleDescription(1, 0),
                    Usage = ResourceUsage.Default
                };
                texDepthBuffer = new Texture2D(Device, texdesc);
                DepthStencilViewDescription viewdesc = new DepthStencilViewDescription()
                {
                    ArraySize = 0,
                    Format = Format.D32_Float,
                    Dimension = DepthStencilViewDimension.Texture2D,
                    MipSlice = 0,
                    Flags = 0,
                    FirstArraySlice = 0
                };
                vwDepthBuffer = new DepthStencilView(Device, texDepthBuffer, viewdesc);
            }

            // Setup states
            #region Depth States
            // Setup depth states
            {
                DepthStencilStateDescription desc = new DepthStencilStateDescription()
                {
                    IsDepthEnabled = true,
                    IsStencilEnabled = false,
                    DepthWriteMask = DepthWriteMask.All,
                    DepthComparison = Comparison.Less
                };
                Depth_Enabled = DepthStencilState.FromDescription(Device, desc);
            }
            {
                DepthStencilStateDescription desc = new DepthStencilStateDescription()
                {
                    IsDepthEnabled = false,
                    IsStencilEnabled = false,
                    DepthWriteMask = DepthWriteMask.Zero,
                    DepthComparison = Comparison.Less
                };
                Depth_Disabled = DepthStencilState.FromDescription(Device, desc);
            }
            {
                DepthStencilStateDescription desc = new DepthStencilStateDescription()
                {
                    IsDepthEnabled = true,
                    IsStencilEnabled = false,
                    DepthWriteMask = DepthWriteMask.Zero,
                    DepthComparison = Comparison.Less
                };
                Depth_ReadOnly = DepthStencilState.FromDescription(Device, desc);
            }
            #endregion
            #region Sampler States
            Sampler_Clamp = SamplerState.FromDescription(Device, new SamplerDescription()
            {
                AddressU = TextureAddressMode.Clamp,
                AddressV = TextureAddressMode.Clamp,
                AddressW = TextureAddressMode.Clamp,
                Filter = Filter.Anisotropic,
                MinimumLod = 0.0f,
                MaximumLod = float.MaxValue,
                MaximumAnisotropy = 16
            });
            Sampler_Clamp_Point = SamplerState.FromDescription(Device, new SamplerDescription()
            {
                AddressU = TextureAddressMode.Clamp,
                AddressV = TextureAddressMode.Clamp,
                AddressW = TextureAddressMode.Clamp,
                Filter = Filter.MinMagMipPoint
            });
            Sampler_Clamp_Linear = SamplerState.FromDescription(Device, new SamplerDescription()
            {
                AddressU = TextureAddressMode.Clamp,
                AddressV = TextureAddressMode.Clamp,
                AddressW = TextureAddressMode.Clamp,
                Filter = Filter.MinMagMipLinear
            });
            Sampler_Wrap = SamplerState.FromDescription(Device, new SamplerDescription()
            {
                AddressU = TextureAddressMode.Wrap,
                AddressV = TextureAddressMode.Wrap,
                AddressW = TextureAddressMode.Wrap,
                Filter = Filter.Anisotropic,
                MinimumLod = 0.0f,
                MaximumLod = float.MaxValue,
                MaximumAnisotropy = 16
            });
            #endregion
            #region Rasterizer States
            Culling_Backface = RasterizerState.FromDescription(Device, new RasterizerStateDescription()
            {
                CullMode = CullMode.Back,
                DepthBias = 0,
                DepthBiasClamp = 0.0f,
                IsDepthClipEnabled = true,
                FillMode = FillMode.Solid,
                IsAntialiasedLineEnabled = false,
                IsFrontCounterclockwise = false,
                IsMultisampleEnabled = true,
                IsScissorEnabled = false,
                SlopeScaledDepthBias = 0.0f
            });
            Culling_Frontface = RasterizerState.FromDescription(Device, new RasterizerStateDescription()
            {
                CullMode = CullMode.Front,
                DepthBias = 0,
                DepthBiasClamp = 0.0f,
                IsDepthClipEnabled = true,
                FillMode = FillMode.Solid,
                IsAntialiasedLineEnabled = false,
                IsFrontCounterclockwise = false,
                IsMultisampleEnabled = true,
                IsScissorEnabled = false,
                SlopeScaledDepthBias = 0.0f
            });
            Culling_None = RasterizerState.FromDescription(Device, new RasterizerStateDescription()
            {
                CullMode = CullMode.None,
                DepthBias = 0,
                DepthBiasClamp = 0.0f,
                IsDepthClipEnabled = true,
                FillMode = FillMode.Solid,
                IsAntialiasedLineEnabled = false,
                IsFrontCounterclockwise = false,
                IsMultisampleEnabled = true,
                IsScissorEnabled = false,
                SlopeScaledDepthBias = 0.0f
            });
            #endregion
            #region Blend States
            {
                BlendStateDescription desc = new BlendStateDescription();
                desc.RenderTargets[0].BlendEnable = true;
                desc.RenderTargets[0].BlendOperation = BlendOperation.Add;
                desc.RenderTargets[0].SourceBlend = BlendOption.One;
                desc.RenderTargets[0].DestinationBlend = BlendOption.Zero;
                desc.RenderTargets[0].BlendOperationAlpha = BlendOperation.Add;
                desc.RenderTargets[0].SourceBlendAlpha = BlendOption.One;
                desc.RenderTargets[0].DestinationBlendAlpha = BlendOption.Zero;
                desc.RenderTargets[0].RenderTargetWriteMask = ColorWriteMaskFlags.All;
                Blend_Opaque = BlendState.FromDescription(Device, desc);
            }
            {
                BlendStateDescription desc = new BlendStateDescription();
                desc.RenderTargets[0].BlendEnable = true;
                desc.RenderTargets[0].BlendOperation = BlendOperation.Add;
                desc.RenderTargets[0].SourceBlend = BlendOption.SourceAlpha;
                desc.RenderTargets[0].DestinationBlend = BlendOption.InverseSourceAlpha;
                desc.RenderTargets[0].BlendOperationAlpha = BlendOperation.Add;
                desc.RenderTargets[0].SourceBlendAlpha = BlendOption.One;
                desc.RenderTargets[0].DestinationBlendAlpha = BlendOption.Zero;
                desc.RenderTargets[0].RenderTargetWriteMask = ColorWriteMaskFlags.All;
                Blend_Alpha = BlendState.FromDescription(Device, desc);
            }
            {
                BlendStateDescription desc = new BlendStateDescription();
                desc.RenderTargets[0].BlendEnable = true;
                desc.RenderTargets[0].BlendOperation = BlendOperation.Add;
                desc.RenderTargets[0].SourceBlend = BlendOption.One;
                desc.RenderTargets[0].DestinationBlend = BlendOption.One;
                desc.RenderTargets[0].BlendOperationAlpha = BlendOperation.Add;
                desc.RenderTargets[0].SourceBlendAlpha = BlendOption.One;
                desc.RenderTargets[0].DestinationBlendAlpha = BlendOption.Zero;
                desc.RenderTargets[0].RenderTargetWriteMask = ColorWriteMaskFlags.All;
                Blend_Add = BlendState.FromDescription(Device, desc);
            }
            {
                BlendStateDescription desc = new BlendStateDescription();
                desc.RenderTargets[0].BlendEnable = true;
                desc.RenderTargets[0].BlendOperation = BlendOperation.Add;
                desc.RenderTargets[0].SourceBlend = BlendOption.DestinationColor;
                desc.RenderTargets[0].DestinationBlend = BlendOption.Zero;
                desc.RenderTargets[0].BlendOperationAlpha = BlendOperation.Add;
                desc.RenderTargets[0].SourceBlendAlpha = BlendOption.One;
                desc.RenderTargets[0].DestinationBlendAlpha = BlendOption.Zero;
                desc.RenderTargets[0].RenderTargetWriteMask = ColorWriteMaskFlags.All;
                Blend_Multiply = BlendState.FromDescription(Device, desc);
            }
            #endregion

            // Setup default states
            Depth = Depth_Enabled;
            Culling = Culling_Backface;
            Blend = Blend_Opaque;

            // Setup other objects
            shaderresourcemap = new Dictionary<Resource, ShaderResourceView>();
            resourceviewslots = new ShaderResourceViewData[MaxPixelShaderResourceViewSlots];

            // Send the window created message
            WindowCreatedMessage windowcreatedmsg = new WindowCreatedMessage();
            windowcreatedmsg.Form = window;
            Owner.MessagePool.SendMessage(windowcreatedmsg);

            // Show the form
            window.Show();
        }
 public void InitializeBuffers()
 {
     Helper.Dispose(ReadOnlyDepth);
     DepthStencilViewDescription dsvDesc = Renderer.BackBufferDepth.Description;
     dsvDesc.Flags = DepthStencilViewFlags.ReadOnlyDepth;
     ReadOnlyDepth = new DepthStencilView(Renderer.Device, Renderer.OutputDepth, dsvDesc);
     GBuffer.Initialize();
 }
Example #43
0
        void DestroyD3D()
        {
            if (SampleVertices != null)
            {
                SampleVertices.Dispose();
                SampleVertices = null;
            }

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

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

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

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

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

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

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

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

            if (D3DDevice != null)
            {
                D3DDevice.Dispose();
                D3DDevice = null;
            }
        }
Example #44
0
            public ImageGenerator(IResourceManager resourceLoader)
            {
                const int width  = 400;
                const int height = 400;

                // Create device and swap chain.
                _device = new Device();
                var swapChainPresenter = new WpfSwapChainPresenter();

                _swapChain     = _device.CreateSwapChain(width, height, swapChainPresenter);
                _outputBitmap  = swapChainPresenter.Bitmap;
                _deviceContext = _device.ImmediateContext;

                // Create RenderTargetView from the backbuffer.
                var backBuffer = Texture2D.FromSwapChain(_swapChain, 0);

                _renderTargetView = _device.CreateRenderTargetView(backBuffer);

                // Create the depth buffer
                var depthBuffer = _device.CreateTexture2D(new Texture2DDescription
                {
                    ArraySize = 1,
                    MipLevels = 1,
                    Width     = width,
                    Height    = height,
                    BindFlags = BindFlags.DepthStencil
                });

                // Create the depth buffer view
                _depthView = _device.CreateDepthStencilView(depthBuffer);

                // Compile Vertex and Pixel shaders
                var vertexShaderByteCode = ShaderCompiler.CompileFromFile("Modules/SampleBrowser/TechDemos/Resources/TextureSampling/Texture.fx", "VS", "vs_4_0");
                var vertexShader         = _device.CreateVertexShader(vertexShaderByteCode);

                var pixelShaderByteCode = ShaderCompiler.CompileFromFile("Modules/SampleBrowser/TechDemos/Resources/TextureSampling/Texture.fx", "PS", "ps_4_1");
                var pixelShader         = _device.CreatePixelShader(pixelShaderByteCode);

                // Layout from VertexShader input signature
                var layout = _device.CreateInputLayout(
                    new[]
                {
                    new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0),
                    new InputElement("TEXCOORD", 0, Format.R32G32_Float, 0, 16)
                }, vertexShaderByteCode);

                // Instantiate Vertex buiffer from vertex data
                var vertices = _device.CreateBuffer(new BufferDescription(BindFlags.VertexBuffer), new[]
                {
                    // 3D coordinates              UV Texture coordinates
                    -1.0f, -1.0f, -1.0f, 1.0f, 0.0f, 1.0f,     // Front
                    -1.0f, 1.0f, -1.0f, 1.0f, 0.0f, 0.0f,
                    1.0f, 1.0f, -1.0f, 1.0f, 1.0f, 0.0f,
                    -1.0f, -1.0f, -1.0f, 1.0f, 0.0f, 1.0f,
                    1.0f, 1.0f, -1.0f, 1.0f, 1.0f, 0.0f,
                    1.0f, -1.0f, -1.0f, 1.0f, 1.0f, 1.0f,

                    -1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 0.0f,     // BACK
                    1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f,
                    -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f,
                    -1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 0.0f,
                    1.0f, -1.0f, 1.0f, 1.0f, 0.0f, 0.0f,
                    1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f,

                    -1.0f, 1.0f, -1.0f, 1.0f, 0.0f, 1.0f,     // Top
                    -1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f,
                    1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f,
                    -1.0f, 1.0f, -1.0f, 1.0f, 0.0f, 1.0f,
                    1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f,
                    1.0f, 1.0f, -1.0f, 1.0f, 1.0f, 1.0f,

                    -1.0f, -1.0f, -1.0f, 1.0f, 1.0f, 0.0f,     // Bottom
                    1.0f, -1.0f, 1.0f, 1.0f, 0.0f, 1.0f,
                    -1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f,
                    -1.0f, -1.0f, -1.0f, 1.0f, 1.0f, 0.0f,
                    1.0f, -1.0f, -1.0f, 1.0f, 0.0f, 0.0f,
                    1.0f, -1.0f, 1.0f, 1.0f, 0.0f, 1.0f,

                    -1.0f, -1.0f, -1.0f, 1.0f, 0.0f, 1.0f,     // Left
                    -1.0f, -1.0f, 1.0f, 1.0f, 0.0f, 0.0f,
                    -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f,
                    -1.0f, -1.0f, -1.0f, 1.0f, 0.0f, 1.0f,
                    -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f,
                    -1.0f, 1.0f, -1.0f, 1.0f, 1.0f, 1.0f,

                    1.0f, -1.0f, -1.0f, 1.0f, 1.0f, 0.0f,     // Right
                    1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f,
                    1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f,
                    1.0f, -1.0f, -1.0f, 1.0f, 1.0f, 0.0f,
                    1.0f, 1.0f, -1.0f, 1.0f, 0.0f, 0.0f,
                    1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f
                });

                // Create Constant Buffer
                _constantBuffer = _device.CreateBuffer(new BufferDescription
                {
                    SizeInBytes = Utilities.SizeOf <Matrix>(),
                    BindFlags   = BindFlags.ConstantBuffer
                });

                // Load texture and create sampler
                var textureStream = resourceLoader.GetStream(
                    "Modules/SampleBrowser/TechDemos/Resources/TextureSampling/CorrodedTiles.png",
                    GetType().Assembly.FullName);
                var texture     = TextureLoader.CreateTextureFromStream(_device, textureStream);
                var textureView = _device.CreateShaderResourceView(texture);

                // Prepare all the stages
                _deviceContext.InputAssembler.InputLayout       = layout;
                _deviceContext.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList;
                _deviceContext.InputAssembler.SetVertexBuffers(0,
                                                               new VertexBufferBinding(vertices, 0, Utilities.SizeOf <Vector4>() + Utilities.SizeOf <Vector2>()));
                _deviceContext.VertexShader.SetConstantBuffers(0, _constantBuffer);
                _deviceContext.VertexShader.Shader = vertexShader;
                _deviceContext.PixelShader.Shader  = pixelShader;
                _deviceContext.PixelShader.SetShaderResources(0, textureView);

                // Setup targets and viewport for rendering
                _deviceContext.Rasterizer.SetViewports(new Viewport(0, 0, _outputBitmap.PixelWidth, _outputBitmap.PixelHeight, 0.0f, 1.0f));
                _deviceContext.OutputMerger.SetTargets(_depthView, _renderTargetView);

                // Prepare matrices
                _view       = Matrix.LookAtRH(new Vector3(0.7f, 0, -1.7f), Vector3.BackwardRH, Vector3.UnitY);
                _projection = Matrix.PerspectiveFovRH(MathUtil.PiOverFour,
                                                      _outputBitmap.PixelWidth / (float)_outputBitmap.PixelHeight, 0.1f, 100.0f);
            }
Example #45
0
        public void ComputeSsao(DeviceContext dc, CameraBase cam, Ssao ssao, DepthStencilView depthStencilView)
        {
            ssao.SetNormalDepthRenderTarget(depthStencilView);

            dc.InputAssembler.PrimitiveTopology = PrimitiveTopology.PatchListWith4ControlPoints;
            dc.InputAssembler.InputLayout = InputLayouts.TerrainCP;

            var stride = TerrainCP.Stride;
            const int offset = 0;

            dc.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(_quadPatchVB, stride, offset));
            dc.InputAssembler.SetIndexBuffer(_quadPatchIB, Format.R16_UInt, 0);

            var viewProj = cam.ViewProj;
            var planes = cam.FrustumPlanes;

            Effects.TerrainFX.SetViewProj(viewProj);
            Effects.TerrainFX.SetEyePosW(cam.Position);
            Effects.TerrainFX.SetMinDist(MinDist);
            Effects.TerrainFX.SetMaxDist(MaxDist);
            Effects.TerrainFX.SetMinTess(MinTess);
            Effects.TerrainFX.SetMaxTess(MaxTess);
            Effects.TerrainFX.SetTexelCellSpaceU(1.0f / Info.HeightMapWidth);
            Effects.TerrainFX.SetTexelCellSpaceV(1.0f / Info.HeightMapHeight);
            Effects.TerrainFX.SetWorldCellSpace(Info.CellSpacing);
            Effects.TerrainFX.SetWorldFrustumPlanes(planes);
            Effects.TerrainFX.SetHeightMap(_heightMapSRV);
            Effects.TerrainFX.SetView(cam.View);

            var tech = Effects.TerrainFX.NormalDepthTech;
            for (int p = 0; p < tech.Description.PassCount; p++) {
                var pass = tech.GetPassByIndex(p);
                pass.Apply(dc);
                dc.DrawIndexed(_numPatchQuadFaces * 4, 0, 0);
            }
            dc.HullShader.Set(null);
            dc.DomainShader.Set(null);

            ssao.ComputeSsao(cam);
            ssao.BlurAmbientMap(4);
        }
        void Window1_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            if(device != null)
            {
                //need to remove the reference to the swapchain's backbuffer to enable ResizeBuffers() call
                renderTargetView.Dispose();
                SwapChainDescription sd = swapChain.Description;
                swapChain.ResizeBuffers(
                    sd.BufferCount,
                    (uint)renderHost.ActualWidth,
                    (uint)renderHost.ActualHeight,
                    sd.BufferDescription.Format,
                    sd.Options);

                using(Texture2D pBuffer = swapChain.GetBuffer<Texture2D>(0))
                {
                    renderTargetView = device.CreateRenderTargetView(pBuffer);
                }

                // Create depth stencil texture
                Texture2DDescription descDepth = new Texture2DDescription()
                {
                    Width = (uint)renderHost.ActualWidth,
                    Height = (uint)renderHost.ActualHeight,
                    MipLevels = 1,
                    ArraySize = 1,
                    Format = Format.D32Float,
                    SampleDescription = new SampleDescription()
                    {
                        Count = 1,
                        Quality = 0
                    },
                    BindingOptions = BindingOptions.DepthStencil,
                };

                depthStencil = device.CreateTexture2D(descDepth);

                // Create the depth stencil view
                DepthStencilViewDescription depthStencilViewDesc = new DepthStencilViewDescription()
                {
                    Format = descDepth.Format,
                    ViewDimension = DepthStencilViewDimension.Texture2D
                };
                depthStencilView = device.CreateDepthStencilView(depthStencil, depthStencilViewDesc);

                // bind the views to the device
                device.OM.RenderTargets = new OutputMergerRenderTargets(new RenderTargetView[ ] { renderTargetView }, depthStencilView);

                // Setup the viewport
                Viewport vp = new Viewport()
                {
                    Width = (uint)renderHost.ActualWidth,
                    Height = (uint)renderHost.ActualHeight,
                    MinDepth = 0.0f,
                    MaxDepth = 1.0f,
                    TopLeftX = 0,
                    TopLeftY = 0
                };

                device.RS.Viewports = new Viewport[ ] { vp };
            }
        }
Example #47
0
        private void CreateTargets()
        {
            using (Texture2D backBuffer = GetBackBuffer())
            {
                RenderTargetView = new RenderTargetView(device, backBuffer);
            }

            Texture2DDescription depthBufferDesc = new Texture2DDescription
                                                       {
                                                           ArraySize = 1,
                                                           BindFlags = BindFlags.DepthStencil,
                                                           CpuAccessFlags = CpuAccessFlags.None,
                                                           Format = Format.D32_Float,
                                                           Width = Settings.ScreenWidth,
                                                           Height = Settings.ScreenHeight,
                                                           MipLevels = 1,
                                                           OptionFlags = ResourceOptionFlags.None,
                                                           SampleDescription = Settings.SampleDescription,
                                                           Usage = ResourceUsage.Default
                                                       };

            using (Texture2D depthBuffer = new Texture2D(device, depthBufferDesc))
            {
                DepthStencilView = new DepthStencilView(device, depthBuffer);
            }
        }
Example #48
0
 public void SetRenderTarget(DeviceContext deviceContext, DepthStencilView depthStencilView)
 {
     deviceContext.OutputMerger.SetRenderTargets(depthStencilView, renderTargetView);
 }
Example #49
0
        internal static void AddForwardCamera(ref Matrix offsetedViewProjection, ref Matrix viewProjection, MyViewport viewport, DepthStencilView dsv, RenderTargetView rtv)
        {
            var frustumMask = m_cullQuery.AddFrustum(new BoundingFrustum(viewProjection));

            MyForwardPass pass = new MyForwardPass();

            pass.Cleanup();
            pass.ProcessingMask = frustumMask;
            pass.ViewProjection = offsetedViewProjection;
            pass.Viewport       = viewport;
            pass.DSV            = dsv;
            pass.RTV            = rtv;

            pass.PerFrame();

            m_wavefront.Add(pass);
        }
        internal MyDepthStencil(int width, int height,
                                int sampleCount, int sampleQuality)
        {
            m_resolution = new Vector2I(width, height);
            m_samples    = new Vector2I(sampleCount, sampleQuality);

            m_depthSubresource   = new MyDepthView(this);
            m_stencilSubresource = new MyStencilView(this);

            Texture2DDescription desc = new Texture2DDescription();

            desc.Width                     = width;
            desc.Height                    = height;
            desc.Format                    = Depth32F ? Format.R32G8X24_Typeless : Format.R24G8_Typeless;
            desc.ArraySize                 = 1;
            desc.MipLevels                 = 1;
            desc.BindFlags                 = BindFlags.DepthStencil | BindFlags.ShaderResource;
            desc.Usage                     = ResourceUsage.Default;
            desc.CpuAccessFlags            = 0;
            desc.SampleDescription.Count   = sampleCount;
            desc.SampleDescription.Quality = sampleQuality;
            desc.OptionFlags               = 0;
            m_resource                     = new Texture2D(MyRender11.Device, desc);

            DepthStencilViewDescription dsvDesc = new DepthStencilViewDescription();

            dsvDesc.Format = Depth32F ? Format.D32_Float_S8X24_UInt : Format.D24_UNorm_S8_UInt;
            if (sampleCount == 1)
            {
                dsvDesc.Dimension          = DepthStencilViewDimension.Texture2D;
                dsvDesc.Flags              = DepthStencilViewFlags.None;
                dsvDesc.Texture2D.MipSlice = 0;
            }
            else
            {
                dsvDesc.Dimension = DepthStencilViewDimension.Texture2DMultisampled;
                dsvDesc.Flags     = DepthStencilViewFlags.None;
            }
            m_DSV = new DepthStencilView(MyRender11.Device, m_resource, dsvDesc);
            if (sampleCount == 1)
            {
                dsvDesc.Dimension          = DepthStencilViewDimension.Texture2D;
                dsvDesc.Flags              = DepthStencilViewFlags.ReadOnlyDepth;
                dsvDesc.Texture2D.MipSlice = 0;
            }
            else
            {
                dsvDesc.Dimension = DepthStencilViewDimension.Texture2DMultisampled;
                dsvDesc.Flags     = DepthStencilViewFlags.ReadOnlyDepth;
            }
            m_DSV_roDepth = new DepthStencilView(MyRender11.Device, m_resource, dsvDesc);
            if (sampleCount == 1)
            {
                dsvDesc.Dimension          = DepthStencilViewDimension.Texture2D;
                dsvDesc.Flags              = DepthStencilViewFlags.ReadOnlyStencil;
                dsvDesc.Texture2D.MipSlice = 0;
            }
            else
            {
                dsvDesc.Dimension = DepthStencilViewDimension.Texture2DMultisampled;
                dsvDesc.Flags     = DepthStencilViewFlags.ReadOnlyStencil;
            }
            m_DSV_roStencil = new DepthStencilView(MyRender11.Device, m_resource, dsvDesc);
            dsvDesc.Flags   = DepthStencilViewFlags.ReadOnlyStencil | DepthStencilViewFlags.ReadOnlyDepth;
            if (sampleCount == 1)
            {
                dsvDesc.Dimension          = DepthStencilViewDimension.Texture2D;
                dsvDesc.Texture2D.MipSlice = 0;
            }
            else
            {
                dsvDesc.Dimension = DepthStencilViewDimension.Texture2DMultisampled;
            }
            m_DSV_ro = new DepthStencilView(MyRender11.Device, m_resource, dsvDesc);

            ShaderResourceViewDescription srvDesc = new ShaderResourceViewDescription();

            srvDesc.Format = Depth32F ? Format.R32_Float_X8X24_Typeless : Format.R24_UNorm_X8_Typeless;
            if (sampleCount == 1)
            {
                srvDesc.Dimension                 = ShaderResourceViewDimension.Texture2D;
                srvDesc.Texture2D.MipLevels       = -1;
                srvDesc.Texture2D.MostDetailedMip = 0;
            }
            else
            {
                srvDesc.Dimension = ShaderResourceViewDimension.Texture2DMultisampled;
            }
            m_SRV_depth = new ShaderResourceView(MyRender11.Device, m_resource, srvDesc);

            srvDesc.Format = Depth32F ? Format.X32_Typeless_G8X24_UInt : Format.X24_Typeless_G8_UInt;
            if (sampleCount == 1)
            {
                srvDesc.Dimension                 = ShaderResourceViewDimension.Texture2D;
                srvDesc.Texture2D.MipLevels       = -1;
                srvDesc.Texture2D.MostDetailedMip = 0;
            }
            else
            {
                srvDesc.Dimension = ShaderResourceViewDimension.Texture2DMultisampled;
            }
            m_SRV_stencil = new ShaderResourceView(MyRender11.Device, m_resource, srvDesc);
        }
Example #51
0
        /// <summary>
        /// 
        /// </summary>
        private void CreateAndBindTargets()
        {
            this.surfaceD3D.SetRenderTargetDX11(null);

            int width = System.Math.Max((int)this.ActualWidth, 100);
            int height = System.Math.Max((int)this.ActualHeight, 100);

            Disposer.RemoveAndDispose(ref this.colorBufferView);
            Disposer.RemoveAndDispose(ref this.depthStencilBufferView);
            Disposer.RemoveAndDispose(ref this.colorBuffer);
            Disposer.RemoveAndDispose(ref this.depthStencilBuffer);
            #if MSAA
            Disposer.RemoveAndDispose(ref this.renderTargetNMS);

            // check 8,4,2,1
            int sampleCount = 8;
            int sampleQuality = 0;

            if (this.IsMSAAEnabled)
            {
                do
                {
                    sampleQuality = this.device.CheckMultisampleQualityLevels(Format.B8G8R8A8_UNorm, sampleCount) - 1;
                    if (sampleQuality > 0)
                    {
                        break;
                    }
                    else
                    {
                        sampleCount /= 2;
                    }

                    if (sampleCount == 1)
                    {
                        sampleQuality = 0;
                        break;
                    }
                }
                while (true);
            }
            else
            {
                sampleCount = 1;
                sampleQuality = 0;
            }

            var sampleDesc = new SampleDescription(sampleCount, sampleQuality);
            var optionFlags = ResourceOptionFlags.None;
            #else
            var sampleDesc = new SampleDescription(1, 0);
            var optionFlags = ResourceOptionFlags.Shared;
            #endif

            var colordesc = new Texture2DDescription
            {
                BindFlags = BindFlags.RenderTarget | BindFlags.ShaderResource,
                Format = Format.B8G8R8A8_UNorm,
                Width = width,
                Height = height,
                MipLevels = 1,
                SampleDescription = sampleDesc,
                Usage = ResourceUsage.Default,
                OptionFlags = optionFlags,
                CpuAccessFlags = CpuAccessFlags.None,
                ArraySize = 1
            };

            var depthdesc = new Texture2DDescription
            {
                BindFlags = BindFlags.DepthStencil,
                //Format = Format.D24_UNorm_S8_UInt,
                Format = Format.D32_Float_S8X24_UInt,
                Width = width,
                Height = height,
                MipLevels = 1,
                SampleDescription = sampleDesc,
                Usage = ResourceUsage.Default,
                OptionFlags = ResourceOptionFlags.None,
                CpuAccessFlags = CpuAccessFlags.None,
                ArraySize = 1,
            };

            this.colorBuffer = new Texture2D(this.device, colordesc);
            this.depthStencilBuffer = new Texture2D(this.device, depthdesc);

            this.colorBufferView = new RenderTargetView(this.device, this.colorBuffer);
            this.depthStencilBufferView = new DepthStencilView(this.device, this.depthStencilBuffer);

            #if MSAA
            var colordescNMS = new Texture2DDescription
            {
                BindFlags = BindFlags.RenderTarget | BindFlags.ShaderResource,
                Format = Format.B8G8R8A8_UNorm,
                Width = width,
                Height = height,
                MipLevels = 1,
                SampleDescription = new SampleDescription(1, 0),
                Usage = ResourceUsage.Default,
                OptionFlags = ResourceOptionFlags.Shared,
                CpuAccessFlags = CpuAccessFlags.None,
                ArraySize = 1
            };

            this.renderTargetNMS = new Texture2D(this.device, colordescNMS);
            this.device.ImmediateContext.ResolveSubresource(this.colorBuffer, 0, this.renderTargetNMS, 0, Format.B8G8R8A8_UNorm);
            this.surfaceD3D.SetRenderTargetDX11(this.renderTargetNMS);
            #else
            this.surfaceD3D.SetRenderTargetDX11(this.colorBuffer);
            #endif
        }
Example #52
0
        void InitD3D()
        {
            var swapDesc = new Dxgi.SwapChainDescription
            {
                BufferCount     = 1,
                ModeDescription = new Dxgi.ModeDescription
                {
                    Width       = Container.ClientSize.Width,
                    Height      = Container.ClientSize.Height,
                    RefreshRate = new Rational(60, 1),
                    Format      = Dxgi.Format.R8G8B8A8_UNorm
                },
                IsWindowed        = true,
                OutputHandle      = Container.Handle,
                SampleDescription = new Dxgi.SampleDescription(1, 0),
                SwapEffect        = Dxgi.SwapEffect.Discard,
                Usage             = Dxgi.Usage.RenderTargetOutput
            };

            Device device;

            Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.Debug | DeviceCreationFlags.BgraSupport,
                                       swapDesc, out device, out SwapChain);
            Device    = device;
            m_context = Device.ImmediateContext;

            Texture2DDescription colordesc = new Texture2DDescription
            {
                BindFlags         = BindFlags.RenderTarget | BindFlags.ShaderResource,
                Format            = Dxgi.Format.B8G8R8A8_UNorm,
                Width             = Width,
                Height            = Height,
                MipLevels         = 1,
                SampleDescription = new Dxgi.SampleDescription(1, 0),
                Usage             = ResourceUsage.Default,
                OptionFlags       = ResourceOptionFlags.Shared,
                CpuAccessFlags    = CpuAccessFlags.None,
                ArraySize         = 1
            };

            Texture2DDescription depthdesc = new Texture2DDescription
            {
                BindFlags         = BindFlags.DepthStencil,
                Format            = Dxgi.Format.D24_UNorm_S8_UInt,
                Width             = Width,
                Height            = Height,
                MipLevels         = 1,
                SampleDescription = new Dxgi.SampleDescription(1, 0),
                Usage             = ResourceUsage.Default,
                OptionFlags       = ResourceOptionFlags.None,
                CpuAccessFlags    = CpuAccessFlags.None,
                ArraySize         = 1
            };

            SharedTexture = new Texture2D(Device, colordesc);
            DepthTexture  = new Texture2D(Device, depthdesc);
            RenderView    = new RenderTargetView(Device, SharedTexture);
            DepthView     = new DepthStencilView(Device, DepthTexture);

            var rastDesc = new RasterizerStateDescription()
            {
                CullMode = CullMode.None,
                FillMode = FillMode.Solid,
            };

            m_context.Rasterizer.State = RasterizerState.FromDescription(Device, rastDesc);

            QuadIndices = RenderSupport.InitQuadIndices(Device);

            m_context.Flush();
        }
        void InitDevice()
        {
            // create Direct 3D device
            device = D3DDevice.CreateDeviceAndSwapChain(renderHost.Handle);
            swapChain = device.SwapChain;

            // Create a render target view
            using (Texture2D pBuffer = swapChain.GetBuffer<Texture2D>(0))
            {
                renderTargetView = device.CreateRenderTargetView(pBuffer);
            }

            // Create depth stencil texture
            Texture2DDescription descDepth = new Texture2DDescription()
            {
                Width = (uint)renderHost.ActualWidth,
                Height = (uint)renderHost.ActualHeight,
                MipLevels = 1,
                ArraySize = 1,
                Format = Format.D32Float,
                SampleDescription = new SampleDescription()
                {
                    Count = 1,
                    Quality = 0
                },
                BindingOptions = BindingOptions.DepthStencil,
            };

            depthStencil = device.CreateTexture2D(descDepth);

            // Create the depth stencil view
            DepthStencilViewDescription depthStencilViewDesc = new DepthStencilViewDescription()
            {
                Format = descDepth.Format,
                ViewDimension = DepthStencilViewDimension.Texture2D
            };
            depthStencilView = device.CreateDepthStencilView(depthStencil, depthStencilViewDesc);

            // bind the views to the device
            device.OM.RenderTargets = new OutputMergerRenderTargets(new RenderTargetView[] { renderTargetView }, depthStencilView);

            // Setup the viewport
            Viewport vp = new Viewport()
            {
                Width = (uint)renderHost.ActualWidth,
                Height = (uint)renderHost.ActualHeight,
                MinDepth = 0.0f,
                MaxDepth = 1.0f,
                TopLeftX = 0,
                TopLeftY = 0
            };
            
            device.RS.Viewports = new Viewport[] { vp };
        }
        protected override void CreateDeviceDependentResources()
        {
            RemoveAndDispose(ref vertexShader);
            RemoveAndDispose(ref lightBuffer);
            RemoveAndDispose(ref RTV);
            RemoveAndDispose(ref SRV);
            RemoveAndDispose(ref rsCullBack);
            RemoveAndDispose(ref rsCullFront);
            RemoveAndDispose(ref rsWireframe);
            RemoveAndDispose(ref blendStateAdd);
            RemoveAndDispose(ref depthLessThan);
            RemoveAndDispose(ref depthGreaterThan);
            RemoveAndDispose(ref depthDisabled);
            RemoveAndDispose(ref perLightBuffer);

            RemoveAndDispose(ref psAmbientLight);
            RemoveAndDispose(ref psDirectionalLight);
            RemoveAndDispose(ref psPointLight);
            RemoveAndDispose(ref psSpotLight);
            RemoveAndDispose(ref psDebugLight);
            RemoveAndDispose(ref perLightBuffer);

            // Retrieve our SharpDX.Direct3D11.Device1 instance
            var device = this.DeviceManager.Direct3DDevice;

            int width, height;
            SampleDescription sampleDesc;

            // Retrieve DSV from GBuffer and extract width/height
            // then create a new read-only DSV
            using (var depthTexture = gbuffer.DSV.ResourceAs <Texture2D>())
            {
                width      = depthTexture.Description.Width;
                height     = depthTexture.Description.Height;
                sampleDesc = depthTexture.Description.SampleDescription;

                // Initialize read-only DSV
                var dsvDesc = gbuffer.DSV.Description;
                dsvDesc.Flags = DepthStencilViewFlags.ReadOnlyDepth | DepthStencilViewFlags.ReadOnlyStencil;
                DSVReadonly   = ToDispose(new DepthStencilView(device, depthTexture, dsvDesc));
            }
            // Check if GBuffer is multi-sampled
            bool isMSAA = sampleDesc.Count > 1;

            // Initialize the light render target
            var texDesc = new Texture2DDescription();

            texDesc.BindFlags         = BindFlags.ShaderResource | BindFlags.RenderTarget;
            texDesc.ArraySize         = 1;
            texDesc.CpuAccessFlags    = CpuAccessFlags.None;
            texDesc.Usage             = ResourceUsage.Default;
            texDesc.Width             = width;
            texDesc.Height            = height;
            texDesc.MipLevels         = 1; // No mip levels
            texDesc.SampleDescription = sampleDesc;
            texDesc.Format            = Format.R8G8B8A8_UNorm;

            lightBuffer = ToDispose(new Texture2D(device, texDesc));

            // Render Target View description
            var rtvDesc = new RenderTargetViewDescription();

            rtvDesc.Format             = Format.R8G8B8A8_UNorm;
            rtvDesc.Dimension          = isMSAA ? RenderTargetViewDimension.Texture2DMultisampled : RenderTargetViewDimension.Texture2D;
            rtvDesc.Texture2D.MipSlice = 0;
            RTV = ToDispose(new RenderTargetView(device, lightBuffer, rtvDesc));

            // SRV description for render targets
            var srvDesc = new ShaderResourceViewDescription();

            srvDesc.Format                    = Format.R8G8B8A8_UNorm;
            srvDesc.Dimension                 = isMSAA ? SharpDX.Direct3D.ShaderResourceViewDimension.Texture2DMultisampled : SharpDX.Direct3D.ShaderResourceViewDimension.Texture2D;
            srvDesc.Texture2D.MipLevels       = -1;
            srvDesc.Texture2D.MostDetailedMip = 0;
            SRV = ToDispose(new ShaderResourceView(device, lightBuffer, srvDesc));

            // Initialize additive blend state (assuming single render target)
            BlendStateDescription bsDesc = new BlendStateDescription();

            bsDesc.RenderTarget[0].IsBlendEnabled        = true;
            bsDesc.RenderTarget[0].AlphaBlendOperation   = BlendOperation.Add;
            bsDesc.RenderTarget[0].SourceAlphaBlend      = BlendOption.One;
            bsDesc.RenderTarget[0].DestinationAlphaBlend = BlendOption.One;
            bsDesc.RenderTarget[0].BlendOperation        = BlendOperation.Add;
            bsDesc.RenderTarget[0].SourceBlend           = BlendOption.One;
            bsDesc.RenderTarget[0].DestinationBlend      = BlendOption.One;
            bsDesc.RenderTarget[0].RenderTargetWriteMask = ColorWriteMaskFlags.All;
            blendStateAdd = ToDispose(new BlendState(device, bsDesc));

            // Initialize rasterizer states
            RasterizerStateDescription rsDesc = new RasterizerStateDescription();

            rsDesc.FillMode = FillMode.Solid;
            rsDesc.CullMode = CullMode.Back;
            rsCullBack      = ToDispose(new RasterizerState(device, rsDesc));
            rsDesc.CullMode = CullMode.Front;
            rsCullFront     = ToDispose(new RasterizerState(device, rsDesc));
            rsDesc.CullMode = CullMode.Front;
            rsDesc.FillMode = FillMode.Wireframe;
            rsWireframe     = ToDispose(new RasterizerState(device, rsDesc));

            // Initialize depth state
            var dsDesc = new DepthStencilStateDescription();

            dsDesc.IsStencilEnabled = false;
            dsDesc.IsDepthEnabled   = true;

            // Less-than depth comparison
            dsDesc.DepthComparison = Comparison.Less;
            depthLessThan          = ToDispose(new DepthStencilState(device, dsDesc));
            // Greater-than depth comparison
            dsDesc.DepthComparison = Comparison.Greater;
            depthGreaterThan       = ToDispose(new DepthStencilState(device, dsDesc));
            // Depth/stencil testing disabled
            dsDesc.IsDepthEnabled = false;
            depthDisabled         = ToDispose(new DepthStencilState(device, dsDesc));

            // Buffer to light parameters
            perLightBuffer = ToDispose(new Buffer(device, Utilities.SizeOf <PerLight>(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0));

            if (isMSAA)
            {
                // Compile and create the vertex shader
                using (var bytecode = HLSLCompiler.CompileFromFile(@"Shaders\LightsMS.hlsl", "VSLight", "vs_5_0"))
                    vertexShader = ToDispose(new VertexShader(device, bytecode));
                // Compile pixel shaders
                using (var bytecode = HLSLCompiler.CompileFromFile(@"Shaders\LightsMS.hlsl", "PSAmbientLight", "ps_5_0"))
                    psAmbientLight = ToDispose(new PixelShader(device, bytecode));
                using (var bytecode = HLSLCompiler.CompileFromFile(@"Shaders\LightsMS.hlsl", "PSDirectionalLight", "ps_5_0"))
                    psDirectionalLight = ToDispose(new PixelShader(device, bytecode));
                using (var bytecode = HLSLCompiler.CompileFromFile(@"Shaders\LightsMS.hlsl", "PSPointLight", "ps_5_0"))
                    psPointLight = ToDispose(new PixelShader(device, bytecode));
                using (var bytecode = HLSLCompiler.CompileFromFile(@"Shaders\LightsMS.hlsl", "PSSpotLight", "ps_5_0"))
                    psSpotLight = ToDispose(new PixelShader(device, bytecode));
                using (var bytecode = HLSLCompiler.CompileFromFile(@"Shaders\LightsMS.hlsl", "PSDebugLight", "ps_5_0"))
                    psDebugLight = ToDispose(new PixelShader(device, bytecode));
            }
            else
            {
                // Compile and create the vertex shader
                using (var bytecode = HLSLCompiler.CompileFromFile(@"Shaders\Lights.hlsl", "VSLight", "vs_5_0"))
                    vertexShader = ToDispose(new VertexShader(device, bytecode));
                // Compile pixel shaders
                using (var bytecode = HLSLCompiler.CompileFromFile(@"Shaders\Lights.hlsl", "PSAmbientLight", "ps_5_0"))
                    psAmbientLight = ToDispose(new PixelShader(device, bytecode));
                using (var bytecode = HLSLCompiler.CompileFromFile(@"Shaders\Lights.hlsl", "PSDirectionalLight", "ps_5_0"))
                    psDirectionalLight = ToDispose(new PixelShader(device, bytecode));
                using (var bytecode = HLSLCompiler.CompileFromFile(@"Shaders\Lights.hlsl", "PSPointLight", "ps_5_0"))
                    psPointLight = ToDispose(new PixelShader(device, bytecode));
                using (var bytecode = HLSLCompiler.CompileFromFile(@"Shaders\Lights.hlsl", "PSSpotLight", "ps_5_0"))
                    psSpotLight = ToDispose(new PixelShader(device, bytecode));
                using (var bytecode = HLSLCompiler.CompileFromFile(@"Shaders\Lights.hlsl", "PSDebugLight", "ps_5_0"))
                    psDebugLight = ToDispose(new PixelShader(device, bytecode));
            }
        }
Example #55
0
        private void SetViews()
        {
            // Create a render target view
            using (Texture2D pBuffer = swapChain.GetBuffer<Texture2D>(0))
            {
                renderTargetView = device.CreateRenderTargetView(pBuffer);
            }

            // Create depth stencil texture
            Texture2DDescription descDepth = new Texture2DDescription()
            {
                Width = (uint)directControl.ClientSize.Width,
                Height = (uint)directControl.ClientSize.Height,
                MipLevels = 1,
                ArraySize = 1,
                Format = Format.D32_FLOAT,
                SampleDescription = new SampleDescription()
                {
                    Count = 1,
                    Quality = 0
                },
                BindFlags = BindFlag.DepthStencil,
            };

            depthStencil = device.CreateTexture2D(descDepth);

            // Create the depth stencil view
            DepthStencilViewDescription depthStencilViewDesc = new DepthStencilViewDescription()
            {
                Format = descDepth.Format,
                ViewDimension = DepthStencilViewDimension.Texture2D
            };
            depthStencilView = device.CreateDepthStencilView(depthStencil, depthStencilViewDesc);

            //bind the views to the device
            device.OM.SetRenderTargets(new RenderTargetView[] { renderTargetView }, depthStencilView);

            // Setup the viewport
            Viewport vp = new Viewport()
            {
                Width = (uint)directControl.ClientSize.Width,
                Height = (uint)directControl.ClientSize.Height,
                MinDepth = 0.0f,
                MaxDepth = 1.0f,
                TopLeftX = 0,
                TopLeftY = 0
            };

            device.RS.SetViewports(new Viewport[] { vp });
        }
Example #56
0
        public override WriteableBitmap Initialize(Device device)
        {
            const int width  = 400;
            const int height = 300;

            // Create device and swap chain.
            var swapChainPresenter = new WpfSwapChainPresenter();

            _swapChain     = device.CreateSwapChain(width, height, swapChainPresenter);
            _deviceContext = device.ImmediateContext;

            // Create RenderTargetView from the backbuffer.
            var backBuffer = Texture2D.FromSwapChain(_swapChain, 0);

            _renderTargetView = device.CreateRenderTargetView(backBuffer);

            // Create the depth buffer
            var depthBuffer = device.CreateTexture2D(new Texture2DDescription
            {
                ArraySize = 1,
                MipLevels = 1,
                Width     = width,
                Height    = height,
                BindFlags = BindFlags.DepthStencil
            });

            // Create the depth buffer view
            _depthView = device.CreateDepthStencilView(depthBuffer);

            // Compile Vertex and Pixel shaders
            var vertexShaderByteCode = ShaderCompiler.CompileFromFile("Modules/SampleBrowser/Samples/MiniCube/MiniCube.fx", "VS", "vs_4_0");
            var vertexShader         = device.CreateVertexShader(vertexShaderByteCode);

            var pixelShaderByteCode = ShaderCompiler.CompileFromFile("Modules/SampleBrowser/Samples/MiniCube/MiniCube.fx", "PS", "ps_4_0");
            var pixelShader         = device.CreatePixelShader(pixelShaderByteCode);

            // Layout from VertexShader input signature
            var layout = device.CreateInputLayout(
                new[]
            {
                new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0),
                new InputElement("COLOR", 0, Format.R32G32B32A32_Float, 0)
            }, vertexShaderByteCode);

            // Instantiate Vertex buffer from vertex data
            var vertices = device.CreateBuffer(new BufferDescription(BindFlags.VertexBuffer), new[]
            {
                new Vector4(-1.0f, -1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f),                 // Front
                new Vector4(-1.0f, 1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f),
                new Vector4(1.0f, 1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f),
                new Vector4(-1.0f, -1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f),
                new Vector4(1.0f, 1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f),
                new Vector4(1.0f, -1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f),

                new Vector4(-1.0f, -1.0f, 1.0f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f),                 // BACK
                new Vector4(1.0f, 1.0f, 1.0f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f),
                new Vector4(-1.0f, 1.0f, 1.0f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f),
                new Vector4(-1.0f, -1.0f, 1.0f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f),
                new Vector4(1.0f, -1.0f, 1.0f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f),
                new Vector4(1.0f, 1.0f, 1.0f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f),

                new Vector4(-1.0f, 1.0f, -1.0f, 1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f),                 // Top
                new Vector4(-1.0f, 1.0f, 1.0f, 1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f),
                new Vector4(1.0f, 1.0f, 1.0f, 1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f),
                new Vector4(-1.0f, 1.0f, -1.0f, 1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f),
                new Vector4(1.0f, 1.0f, 1.0f, 1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f),
                new Vector4(1.0f, 1.0f, -1.0f, 1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f),

                new Vector4(-1.0f, -1.0f, -1.0f, 1.0f), new Vector4(1.0f, 1.0f, 0.0f, 1.0f),                 // Bottom
                new Vector4(1.0f, -1.0f, 1.0f, 1.0f), new Vector4(1.0f, 1.0f, 0.0f, 1.0f),
                new Vector4(-1.0f, -1.0f, 1.0f, 1.0f), new Vector4(1.0f, 1.0f, 0.0f, 1.0f),
                new Vector4(-1.0f, -1.0f, -1.0f, 1.0f), new Vector4(1.0f, 1.0f, 0.0f, 1.0f),
                new Vector4(1.0f, -1.0f, -1.0f, 1.0f), new Vector4(1.0f, 1.0f, 0.0f, 1.0f),
                new Vector4(1.0f, -1.0f, 1.0f, 1.0f), new Vector4(1.0f, 1.0f, 0.0f, 1.0f),

                new Vector4(-1.0f, -1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 1.0f, 1.0f),                 // Left
                new Vector4(-1.0f, -1.0f, 1.0f, 1.0f), new Vector4(1.0f, 0.0f, 1.0f, 1.0f),
                new Vector4(-1.0f, 1.0f, 1.0f, 1.0f), new Vector4(1.0f, 0.0f, 1.0f, 1.0f),
                new Vector4(-1.0f, -1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 1.0f, 1.0f),
                new Vector4(-1.0f, 1.0f, 1.0f, 1.0f), new Vector4(1.0f, 0.0f, 1.0f, 1.0f),
                new Vector4(-1.0f, 1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 1.0f, 1.0f),

                new Vector4(1.0f, -1.0f, -1.0f, 1.0f), new Vector4(0.0f, 1.0f, 1.0f, 1.0f),                 // Right
                new Vector4(1.0f, 1.0f, 1.0f, 1.0f), new Vector4(0.0f, 1.0f, 1.0f, 1.0f),
                new Vector4(1.0f, -1.0f, 1.0f, 1.0f), new Vector4(0.0f, 1.0f, 1.0f, 1.0f),
                new Vector4(1.0f, -1.0f, -1.0f, 1.0f), new Vector4(0.0f, 1.0f, 1.0f, 1.0f),
                new Vector4(1.0f, 1.0f, -1.0f, 1.0f), new Vector4(0.0f, 1.0f, 1.0f, 1.0f),
                new Vector4(1.0f, 1.0f, 1.0f, 1.0f), new Vector4(0.0f, 1.0f, 1.0f, 1.0f)
            });

            // Create Constant Buffer
            _constantBuffer = device.CreateBuffer(new BufferDescription
            {
                SizeInBytes = Utilities.SizeOf <Matrix>(),
                BindFlags   = BindFlags.ConstantBuffer
            });

            // Prepare all the stages
            _deviceContext.InputAssembler.InputLayout       = layout;
            _deviceContext.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList;
            _deviceContext.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(vertices, 0, Utilities.SizeOf <Vector4>() * 2));
            _deviceContext.VertexShader.SetConstantBuffers(0, _constantBuffer);
            _deviceContext.VertexShader.Shader = vertexShader;
            _deviceContext.PixelShader.Shader  = pixelShader;

            // Setup targets and viewport for rendering
            _deviceContext.Rasterizer.SetViewports(new Viewport(0, 0, width, height, 0.0f, 1.0f));
            _deviceContext.OutputMerger.SetTargets(_depthView, _renderTargetView);

            // Prepare matrices
            _view       = Matrix.LookAtLH(new Vector3(0, 0, -5), Vector3.Zero, Vector3.UnitY);
            _projection = Matrix.PerspectiveFovLH(MathUtil.PiOverFour,
                                                  width / (float)height, 0.1f, 100.0f);

            return(swapChainPresenter.Bitmap);
        }