コード例 #1
0
        public FilterPixelShader(Device device, int imageWidth, int imageHeight, int constantBufferSize, string pixelShaderBytecodeFilename)
        {
            vertexShader = new VertexShader(device, new ShaderBytecode(File.ReadAllBytes("Content/FullScreenQuadVS.cso")));
            pixelShader = new PixelShader(device, new ShaderBytecode(File.ReadAllBytes(pixelShaderBytecodeFilename)));

            var rasterizerStateDesc = new RasterizerStateDescription()
            {
                CullMode = CullMode.None, 
                FillMode = FillMode.Solid,
                IsDepthClipEnabled = false,
                IsFrontCounterClockwise = true,
                IsMultisampleEnabled = false,
            };
            rasterizerState = new RasterizerState(device, rasterizerStateDesc);

            if (constantBufferSize > 0)
            {
                var constantBufferDesc = new BufferDescription()
                {
                    Usage = ResourceUsage.Dynamic,
                    BindFlags = BindFlags.ConstantBuffer,
                    SizeInBytes = constantBufferSize,
                    CpuAccessFlags = CpuAccessFlags.Write,
                    StructureByteStride = 0,
                    OptionFlags = 0,
                };
                constantBuffer = new Buffer(device, constantBufferDesc);
            }

            viewport = new Viewport(0, 0, imageWidth, imageHeight); // TODO: get these dimensions
            vertexBufferBinding = new VertexBufferBinding(null, 0, 0);
        }
コード例 #2
0
        protected override void OnRasterStateChanged()
        {
            if (IsAttached)
            {
                Disposer.RemoveAndDispose(ref rasterState);
                /// --- set up rasterizer states
                var rasterStateDesc = new RasterizerStateDescription()
                {
                    FillMode = FillMode.Solid,
                    CullMode = CullMode.Back,
                    DepthBias = DepthBias,
                    DepthBiasClamp = -1000,
                    SlopeScaledDepthBias = +0,
                    IsDepthClipEnabled = true,
                    IsFrontCounterClockwise = true,

                    //IsMultisampleEnabled = true,
                    //IsAntialiasedLineEnabled = true,                    
                    //IsScissorEnabled = true,
                };
                try
                {
                    rasterState = new RasterizerState(Device, rasterStateDesc);
                }
                catch (Exception)
                {
                }
            }
        }
コード例 #3
0
        public ProjectiveTexturingShader(Device device)
        {
            var shaderByteCode = new ShaderBytecode(File.ReadAllBytes("Content/DepthAndProjectiveTextureVS.cso"));
            vertexShader = new VertexShader(device, shaderByteCode);
            geometryShader = new GeometryShader(device, new ShaderBytecode(File.ReadAllBytes("Content/DepthAndColorGS.cso")));
            pixelShader = new PixelShader(device, new ShaderBytecode(File.ReadAllBytes("Content/DepthAndColorPS.cso")));

            // depth stencil state
            var depthStencilStateDesc = new DepthStencilStateDescription()
            {
                IsDepthEnabled = true,
                DepthWriteMask = DepthWriteMask.All,
                DepthComparison = Comparison.LessEqual,
                IsStencilEnabled = false,
            };
            depthStencilState = new DepthStencilState(device, depthStencilStateDesc);

            // rasterizer states
            var rasterizerStateDesc = new RasterizerStateDescription()
            {
                CullMode = CullMode.None,
                FillMode = FillMode.Solid,
                IsDepthClipEnabled = true,
                IsFrontCounterClockwise = true,
                IsMultisampleEnabled = true,
            };
            rasterizerState = new RasterizerState(device, rasterizerStateDesc);

            // constant buffer
            var constantBufferDesc = new BufferDescription()
            {
                Usage = ResourceUsage.Dynamic,
                BindFlags = BindFlags.ConstantBuffer,
                SizeInBytes = Constants.size,
                CpuAccessFlags = CpuAccessFlags.Write,
                StructureByteStride = 0,
                OptionFlags = 0,
            };
            constantBuffer = new SharpDX.Direct3D11.Buffer(device, constantBufferDesc);

            // user view sampler state
            var colorSamplerStateDesc = new SamplerStateDescription()
            {
                Filter = Filter.MinMagMipLinear,
                AddressU = TextureAddressMode.Border,
                AddressV = TextureAddressMode.Border,
                AddressW = TextureAddressMode.Border,
                //BorderColor = new SharpDX.Color4(0.5f, 0.5f, 0.5f, 1.0f),
                BorderColor = new SharpDX.Color4(0, 0, 0, 1.0f),
            };
            colorSamplerState = new SamplerState(device, colorSamplerStateDesc);

            vertexInputLayout = new InputLayout(device, shaderByteCode.Data, new[]
            {
                new InputElement("SV_POSITION", 0, Format.R32G32B32A32_Float, 0, 0),
            });

        }
コード例 #4
0
        static void InitializeRasterizerStates()
        {
            m_wireframeRasterizerState = MyPipelineStates.CreateRasterizerState(new RasterizerStateDescription
                {
                    FillMode = FillMode.Wireframe,
                    CullMode = CullMode.Back
                });

            RasterizerStateDescription desc = new RasterizerStateDescription();
            desc.FillMode = FillMode.Wireframe;
            desc.CullMode = CullMode.Back;
            m_wireframeRasterizerState = MyPipelineStates.CreateRasterizerState(desc);

            desc.FillMode = FillMode.Solid;
            desc.CullMode = CullMode.Front;
            m_invTriRasterizerState = MyPipelineStates.CreateRasterizerState(desc);

            desc.FillMode = FillMode.Solid;
            desc.CullMode = CullMode.None;
            m_nocullRasterizerState = MyPipelineStates.CreateRasterizerState(desc);

            desc.FillMode = FillMode.Wireframe;
            desc.CullMode = CullMode.None;
            m_nocullWireframeRasterizerState = MyPipelineStates.CreateRasterizerState(desc);

            desc = new RasterizerStateDescription();
            desc.FillMode = FillMode.Solid;
            desc.CullMode = CullMode.Back;
            m_linesRasterizerState = MyPipelineStates.CreateRasterizerState(desc);

            desc = new RasterizerStateDescription();
            desc.FillMode = FillMode.Solid;
            desc.CullMode = CullMode.None;
            desc.IsFrontCounterClockwise = true;
            desc.DepthBias = 20;
            desc.DepthBiasClamp = 2;
            desc.SlopeScaledDepthBias = 4;
            m_cascadesRasterizerState = MyPipelineStates.CreateRasterizerState(desc);

            desc = new RasterizerStateDescription();
            desc.FillMode = FillMode.Solid;
            desc.CullMode = CullMode.None;
            desc.IsFrontCounterClockwise = true;
            desc.DepthBias = 2500;
            desc.DepthBiasClamp = 10000;
            desc.SlopeScaledDepthBias = 4;
            m_shadowRasterizerState = MyPipelineStates.CreateRasterizerState(desc);

            desc.FillMode = FillMode.Solid;
            desc.CullMode = CullMode.Back;
            desc.IsFrontCounterClockwise = false;
            desc.IsScissorEnabled = true;
            m_scissorTestRasterizerState = MyPipelineStates.CreateRasterizerState(desc);
        }
コード例 #5
0
        /// <summary>
        /// Sets the cull mode.
        /// </summary>
        /// <param name="cullMode">The cull mode.</param>
        /// <exception cref="System.Exception"></exception>
        public void SetCullMode(D3D11.CullMode cullMode)
        {
            if (d3dContext == null)
            {
                throw new Exception(MethodBase.GetCurrentMethod().Name + "DeviceContext is null");
            }

            D3D11.RasterizerStateDescription rasterDesc = d3dContext.Rasterizer.State.Description;
            rasterDesc.CullMode = cullMode;

            SetRasterizerState(rasterDesc);
        }
コード例 #6
0
 public static D3D.RasterizerState CreateRasterizerState(this D3D.Device device)
 {
     var rasterizerDesc = new D3D.RasterizerStateDescription()
     {
         CullMode = D3D.CullMode.None,
         IsAntialiasedLineEnabled = true,
         IsMultisampleEnabled = true,
         FillMode = D3D.FillMode.Solid,
         IsDepthClipEnabled = true,
     };
     return new D3D.RasterizerState(device, rasterizerDesc);
 }
コード例 #7
0
        public RasterizerState(SharpDX.Direct3D11.FillMode fillMode, SharpDX.Direct3D11.CullMode cullMode, bool frontCounterClockwise)
        {
            
            RasterizerStateDescription desc = new RasterizerStateDescription(){
                FillMode = fillMode,
                CullMode = cullMode,
                IsFrontCounterClockwise = frontCounterClockwise
            };

            NativeRasterizerState = new SharpDX.Direct3D11.RasterizerState(GraphicManager.Device, desc);
            
        }
コード例 #8
0
        private RasterizerState CreateNewRasterizerState(ref RasterizerStateDescription description)
        {
            SharpDX.Direct3D11.RasterizerStateDescription rssDesc = new SharpDX.Direct3D11.RasterizerStateDescription
            {
                CullMode                = D3D11Formats.VdToD3D11CullMode(description.CullMode),
                FillMode                = D3D11Formats.VdToD3D11FillMode(description.FillMode),
                IsDepthClipEnabled      = description.DepthClipEnabled,
                IsScissorEnabled        = description.ScissorTestEnabled,
                IsFrontCounterClockwise = description.FrontFace == FrontFace.CounterClockwise
            };

            return(new RasterizerState(_device, rssDesc));
        }
コード例 #9
0
        public static D3D.RasterizerState CreateRasterizerState(this D3D.Device device)
        {
            var rasterizerDesc = new D3D.RasterizerStateDescription()
            {
                CullMode = D3D.CullMode.None,
                IsAntialiasedLineEnabled = true,
                IsMultisampleEnabled     = true,
                FillMode           = D3D.FillMode.Solid,
                IsDepthClipEnabled = true,
            };

            return(new D3D.RasterizerState(device, rasterizerDesc));
        }
コード例 #10
0
        private RasterizerState CreateNewRasterizerState(ref D3D11RasterizerStateCacheKey key)
        {
            SharpDX.Direct3D11.RasterizerStateDescription rssDesc = new SharpDX.Direct3D11.RasterizerStateDescription
            {
                CullMode                = D3D11Formats.VdToD3D11CullMode(key.VeldridDescription.CullMode),
                FillMode                = D3D11Formats.VdToD3D11FillMode(key.VeldridDescription.FillMode),
                IsDepthClipEnabled      = key.VeldridDescription.DepthClipEnabled,
                IsScissorEnabled        = key.VeldridDescription.ScissorTestEnabled,
                IsFrontCounterClockwise = key.VeldridDescription.FrontFace == FrontFace.CounterClockwise,
                IsMultisampleEnabled    = key.Multisampled
            };

            return(new RasterizerState(_device, rssDesc));
        }
コード例 #11
0
        /// <summary>
        /// Sets the state of the rasterizer.
        /// </summary>
        /// <param name="desc">The desc.</param>
        /// <exception cref="System.Exception"></exception>
        public void SetRasterizerState(D3D11.RasterizerStateDescription desc)
        {
            if (d3dDevice == null || d3dContext == null)
            {
                throw new Exception(MethodBase.GetCurrentMethod().Name + "Device or DeviceContext is null");
            }

            D3D11.RasterizerState rasterState = new D3D11.RasterizerState(d3dDevice, desc);

            if (d3dContext.Rasterizer.State != null)
            {
                d3dContext.Rasterizer.State.Dispose();
            }
            d3dContext.Rasterizer.State = rasterState;
        }
コード例 #12
0
        private void InitDevice(int numSamples)
        {
            var width  = m_Window.ClientRectangle.Width;
            var height = m_Window.ClientRectangle.Height;

            var refreshRate = new Rational(60, 1);
            var modeDesc    = new ModeDescription(width, height, refreshRate, Format.R8G8B8A8_UNorm);

            var quality = GetBestQuality(numSamples);

            var swapChainDesc = new SwapChainDescription()
            {
                BufferCount       = 1,
                IsWindowed        = true,
                ModeDescription   = modeDesc,
                SampleDescription = new SampleDescription(numSamples, quality),
                OutputHandle      = Game.Inst.Window.Handle,
                Usage             = Usage.RenderTargetOutput
            };

#if DEBUG
            const D3D11.DeviceCreationFlags DEBUG_FLAG = D3D11.DeviceCreationFlags.Debug;
#else
            const D3D11.DeviceCreationFlags DEBUG_FLAG = D3D11.DeviceCreationFlags.None;
#endif

            D3D11.Device.CreateWithSwapChain(DriverType.Hardware, D3D11.DeviceCreationFlags.SingleThreaded | DEBUG_FLAG, swapChainDesc, out Device, out m_SwapChain);
            m_DeviceContext = Device.ImmediateContext;

            var rsd = new D3D11.RasterizerStateDescription {
                CullMode             = D3D11.CullMode.Back,
                FillMode             = D3D11.FillMode.Solid,
                IsMultisampleEnabled = true,
            };
            var rs = new D3D11.RasterizerState(Device, rsd);
            Device.ImmediateContext.Rasterizer.State = rs;

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

            m_DefaultRenderTarget = new SharpDXRenderTarget(this, backBuffer, width, height, new D3D11.RenderTargetView(Device, backBuffer));
            RenderTarget          = m_DefaultRenderTarget;

            m_DeviceContext.Rasterizer.SetViewport(0.0f, 0.0f, width, height);
        }
コード例 #13
0
ファイル: RasterState.cs プロジェクト: Linrasis/WoWEditor
        public RasterState(GxContext context)
        {
            mContext = context;
            mDescription = new RasterizerStateDescription
            {
                CullMode = CullMode.None,
                DepthBias = 0,
                DepthBiasClamp = 0.0f,
                FillMode = FillMode.Solid,
                IsAntialiasedLineEnabled = false,
                IsDepthClipEnabled = true,
                IsFrontCounterClockwise = true,
                IsMultisampleEnabled = false,
                IsScissorEnabled = false,
                SlopeScaledDepthBias = 0.0f
            };

            mChanged = true;
        }
コード例 #14
0
        /// <summary>
        /// Function to retrieve the D3D state object.
        /// </summary>
        /// <param name="stateType">The state type information.</param>
        /// <returns>The D3D state object.</returns>
        internal override D3D.DeviceChild GetStateObject(ref GorgonRasterizerStates stateType)
        {
            var desc = new D3D.RasterizerStateDescription
            {
                CullMode                 = (D3D.CullMode)States.CullingMode,
                DepthBias                = States.DepthBias,
                DepthBiasClamp           = States.DepthBiasClamp,
                FillMode                 = (D3D.FillMode)States.FillMode,
                IsAntialiasedLineEnabled = States.IsAntialiasedLinesEnabled,
                IsDepthClipEnabled       = States.IsDepthClippingEnabled,
                IsFrontCounterClockwise  = States.IsFrontFacingTriangleCounterClockwise,
                IsMultisampleEnabled     = States.IsMultisamplingEnabled,
                IsScissorEnabled         = States.IsScissorTestingEnabled
            };

            var state = new D3D.RasterizerState(Graphics.D3DDevice, desc)
            {
                DebugName = "Gorgon Rasterizer State #" + StateCacheCount
            };

            return(state);
        }
コード例 #15
0
        /// <inheritdoc />
        protected override Task <bool> InternalInitialize(string licenseKey)
        {
            var rasterizeDescription = new SharpDX.Direct3D11.RasterizerStateDescription()
            {
                CullMode = SharpDX.Direct3D11.CullMode.None,
                FillMode = SharpDX.Direct3D11.FillMode.Solid,
                IsFrontCounterClockwise = false,
                DepthBias                = 0,
                SlopeScaledDepthBias     = 0,
                DepthBiasClamp           = 0.0f,
                IsDepthClipEnabled       = true,
                IsScissorEnabled         = false,
                IsMultisampleEnabled     = false,
                IsAntialiasedLineEnabled = false,
            };

            var adapter = Game.Current.Application.Adapter as Adapter.Adapter;

            this.rasterizerState = new SharpDX.Direct3D11.RasterizerState(adapter.GraphicsDevice.DeviceDirect3D, rasterizeDescription);

            return(base.InternalInitialize(licenseKey));
        }
コード例 #16
0
            public RasterizerStatesStruct(D3D.Device device)
            {
                var desc = new D3D.RasterizerStateDescription()
                {
                    CullMode                 = D3D.CullMode.Back,
                    DepthBias                = 0,
                    DepthBiasClamp           = 0,
                    FillMode                 = D3D.FillMode.Solid,
                    IsAntialiasedLineEnabled = false,
                    IsDepthClipEnabled       = true,
                    IsFrontCounterClockwise  = false,
                    IsMultisampleEnabled     = true,
                    IsScissorEnabled         = false,
                    SlopeScaledDepthBias     = 0
                };

                Back = new D3D.RasterizerState(device, desc);

                desc.CullMode = D3D.CullMode.None;
                None          = new D3D.RasterizerState(device, desc);

                desc.FillMode = D3D.FillMode.Wireframe;
                Wire          = new D3D.RasterizerState(device, desc);
            }
コード例 #17
0
ファイル: RasterizerState.cs プロジェクト: numo16/SharpDX
 /// <summary>	
 /// <p>Create a rasterizer state object that tells the rasterizer stage how to behave.</p>	
 /// </summary>	
 /// <param name="device">The <see cref="GraphicsDevice"/>.</param>
 /// <param name="name">Name of this depth stencil state.</param>
 /// <param name="description">A rasterizer state description</param>	
 /// <remarks>	
 /// <p>4096 unique rasterizer state objects can be created on a device at a time.</p><p>If an application attempts to create a rasterizer-state interface with the same state as an existing interface, the same interface will be returned and the total number of unique rasterizer state objects will stay the same.</p>	
 /// </remarks>	
 /// <msdn-id>ff476516</msdn-id>	
 /// <unmanaged>HRESULT ID3D11Device::CreateRasterizerState([In] const D3D11_RASTERIZER_DESC* pRasterizerDesc,[Out, Fast] ID3D11RasterizerState** ppRasterizerState)</unmanaged>	
 /// <unmanaged-short>ID3D11Device::CreateRasterizerState</unmanaged-short>	
 public static RasterizerState New(GraphicsDevice device, string name, RasterizerStateDescription description)
 {
     return new RasterizerState(device, description) {Name = name};
 }
コード例 #18
0
        /// <summary>
        /// Loads the resource.
        /// </summary>
        /// <param name="device">The device.</param>
        /// <param name="resources">Parent ResourceDictionary.</param>
        protected override void LoadResourceInternal(EngineDevice device, ResourceDictionary resources)
        {
            // Create default blend state
            m_defaultBlendState = new Lazy <D3D11.BlendState>(() =>
            {
                D3D11.BlendStateDescription blendDesc = D3D11.BlendStateDescription.Default();
                return(new D3D11.BlendState(device.DeviceD3D11_1, blendDesc));
            });

            // Create alpha blending blend state
            m_alphaBlendingBlendState = new Lazy <D3D11.BlendState>(() =>
            {
                //Define the blend state (based on http://www.rastertek.com/dx11tut26.html)
                D3D11.BlendStateDescription blendDesc           = D3D11.BlendStateDescription.Default();
                blendDesc.RenderTarget[0].IsBlendEnabled        = true;
                blendDesc.RenderTarget[0].SourceBlend           = D3D11.BlendOption.SourceAlpha;
                blendDesc.RenderTarget[0].DestinationBlend      = D3D11.BlendOption.InverseSourceAlpha;
                blendDesc.RenderTarget[0].BlendOperation        = D3D11.BlendOperation.Add;
                blendDesc.RenderTarget[0].DestinationAlphaBlend = D3D11.BlendOption.One;
                blendDesc.RenderTarget[0].SourceAlphaBlend      = D3D11.BlendOption.One;
                blendDesc.RenderTarget[0].AlphaBlendOperation   = D3D11.BlendOperation.Maximum;
                blendDesc.RenderTarget[0].RenderTargetWriteMask = D3D11.ColorWriteMaskFlags.All;

                //Create the blendstate object
                return(new D3D11.BlendState(device.DeviceD3D11_1, blendDesc));
            });

            // Create default depth stencil state
            m_depthStencilStateDefault = new Lazy <D3D11.DepthStencilState>(() =>
            {
                D3D11.DepthStencilStateDescription stateDesc = D3D11.DepthStencilStateDescription.Default();
                stateDesc.DepthComparison = D3D11.Comparison.LessEqual;
                return(new D3D11.DepthStencilState(device.DeviceD3D11_1, stateDesc));
            });

            // Create the depth stencil state for diabling z writes
            m_depthStencilStateDisableZWrites = new Lazy <D3D11.DepthStencilState>(() =>
            {
                D3D11.DepthStencilStateDescription stateDesc = D3D11.DepthStencilStateDescription.Default();
                stateDesc.DepthWriteMask  = D3D11.DepthWriteMask.Zero;
                stateDesc.DepthComparison = D3D11.Comparison.LessEqual;
                return(new D3D11.DepthStencilState(device.DeviceD3D11_1, stateDesc));
            });

            m_depthStencilStateAllwaysPass = new Lazy <D3D11.DepthStencilState>(() =>
            {
                D3D11.DepthStencilStateDescription stateDesc = D3D11.DepthStencilStateDescription.Default();
                stateDesc.DepthWriteMask  = D3D11.DepthWriteMask.Zero;
                stateDesc.DepthComparison = D3D11.Comparison.Always;
                stateDesc.IsDepthEnabled  = false;
                return(new D3D11.DepthStencilState(device.DeviceD3D11_1, stateDesc));
            });

            // Create the depth stencil state for inverting z logic
            m_depthStencilStateInvertedZTest = new Lazy <D3D11.DepthStencilState>(() =>
            {
                D3D11.DepthStencilStateDescription stateDesc = D3D11.DepthStencilStateDescription.Default();
                stateDesc.DepthComparison = D3D11.Comparison.Greater;
                stateDesc.DepthWriteMask  = D3D11.DepthWriteMask.Zero;
                return(new D3D11.DepthStencilState(device.DeviceD3D11_1, stateDesc));
            });

            // Create default rasterizer state
            m_rasterStateDefault = new Lazy <D3D11.RasterizerState>(() =>
            {
                return(new D3D11.RasterizerState(device.DeviceD3D11_1, D3D11.RasterizerStateDescription.Default()));
            });

            // Create a raster state with depth bias
            m_rasterStateBiased = new Lazy <D3D11.RasterizerState>(() =>
            {
                D3D11.RasterizerStateDescription rasterDesc = D3D11.RasterizerStateDescription.Default();
                rasterDesc.DepthBias = GraphicsHelper.GetDepthBiasValue(device, -0.00003f);
                return(new D3D11.RasterizerState(device.DeviceD3D11_1, rasterDesc));
            });

            // Create a raster state for wireframe rendering
            m_rasterStateWireframe = new Lazy <SharpDX.Direct3D11.RasterizerState>(() =>
            {
                D3D11.RasterizerStateDescription rasterDesc = D3D11.RasterizerStateDescription.Default();
                rasterDesc.FillMode = D3D11.FillMode.Wireframe;
                return(new D3D11.RasterizerState(device.DeviceD3D11_1, rasterDesc));
            });

            // Create the rasterizer state for line rendering
            m_rasterStateLines = new Lazy <D3D11.RasterizerState>(() =>
            {
                D3D11.RasterizerStateDescription stateDesc = D3D11.RasterizerStateDescription.Default();
                stateDesc.CullMode = D3D11.CullMode.None;
                stateDesc.IsAntialiasedLineEnabled = true;
                stateDesc.FillMode = D3D11.FillMode.Solid;
                return(new D3D11.RasterizerState(device.DeviceD3D11_1, stateDesc));
            });

            // Create sampler states
            m_samplerStateLow = new Lazy <D3D11.SamplerState>(() =>
            {
                return(GraphicsHelper.CreateDefaultTextureSampler(device, TextureSamplerQualityLevel.Low));
            });
            m_samplerStateMedium = new Lazy <D3D11.SamplerState>(() =>
            {
                return(GraphicsHelper.CreateDefaultTextureSampler(device, TextureSamplerQualityLevel.Medium));
            });
            m_samplerStateHigh = new Lazy <D3D11.SamplerState>(() =>
            {
                return(GraphicsHelper.CreateDefaultTextureSampler(device, TextureSamplerQualityLevel.High));
            });
        }
コード例 #19
0
ファイル: DX11.cs プロジェクト: ndech/PlaneSimulator
        public void InitializeBuffers()
        {
            //Create back buffer
            Texture2D backBuffer = Resource.FromSwapChain<Texture2D>(SwapChain, 0);
            _renderTargetView = new RenderTargetView(Device, backBuffer);
            backBuffer.Dispose();

            //Create the depth/stencil buffer
            var depthBufferDesc = new Texture2DDescription
            {
                Width = ConfigurationManager.Config.Width,
                Height = ConfigurationManager.Config.Height,
                MipLevels = 1,
                ArraySize = 1,
                Format = Format.D24_UNorm_S8_UInt,
                SampleDescription = ConfigurationManager.Config.AntiAliasing ? new SampleDescription(4, _maxQualityLevel-1) : new SampleDescription(1, 0),
                Usage = ResourceUsage.Default,
                BindFlags = BindFlags.DepthStencil,
                CpuAccessFlags = CpuAccessFlags.None,
                OptionFlags = ResourceOptionFlags.None
            };
            _depthStencilBuffer = new Texture2D(Device, depthBufferDesc);

            DepthStencilStateDescription 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);

            DepthStencilStateDescription 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
                }
            };

            _depthDisabledStencilState = new DepthStencilState(Device, depthDisabledStencilDesc);

            // Set the depth stencil state.
            _isZBufferEnabled = true;
            DeviceContext.OutputMerger.SetDepthStencilState(_depthStencilState, 1);

            // Initialize and set up the depth stencil view.
            DepthStencilViewDescription depthStencilViewDesc;
            if(ConfigurationManager.Config.AntiAliasing)
                depthStencilViewDesc = new DepthStencilViewDescription
                {
                    Format = Format.D24_UNorm_S8_UInt,
                    Dimension = DepthStencilViewDimension.Texture2DMultisampled,
                    Texture2DMS = new DepthStencilViewDescription.Texture2DMultisampledResource()
                };
            else
                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);

            RenderToTextureDepthStencilView = new DepthStencilView(Device, new Texture2D(Device, new Texture2DDescription
            {
                Width = ConfigurationManager.Config.Width,
                Height = ConfigurationManager.Config.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
            }), new DepthStencilViewDescription
            {
                Format = Format.D24_UNorm_S8_UInt,
                Dimension = DepthStencilViewDimension.Texture2D,
                Texture2D = new DepthStencilViewDescription.Texture2DResource() { MipSlice = 0 }
            });

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

            // 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.
            _rasterStateSolid = new RasterizerState(Device, rasterDesc);

            rasterDesc.FillMode = FillMode.Wireframe;

            _rasterStateWireFrame = new RasterizerState(Device, rasterDesc);

            // Now set the rasterizer state.
            DeviceContext.Rasterizer.State = _rasterStateSolid;

            // Setup and create the viewport for rendering.
            DeviceContext.Rasterizer.SetViewport(0, 0, ConfigurationManager.Config.Width, ConfigurationManager.Config.Height, 0, 1);

            var blendStateDescription = new BlendStateDescription();
            blendStateDescription.RenderTarget[0].IsBlendEnabled = true;
            blendStateDescription.RenderTarget[0].SourceBlend = BlendOption.SourceAlpha;
            blendStateDescription.RenderTarget[0].DestinationBlend = BlendOption.InverseSourceAlpha;
            blendStateDescription.RenderTarget[0].BlendOperation = BlendOperation.Add;
            blendStateDescription.RenderTarget[0].SourceAlphaBlend = BlendOption.One;
            blendStateDescription.RenderTarget[0].DestinationAlphaBlend = BlendOption.Zero;
            blendStateDescription.RenderTarget[0].AlphaBlendOperation = BlendOperation.Add;
            blendStateDescription.RenderTarget[0].RenderTargetWriteMask = ColorWriteMaskFlags.All;
            // Create the blend state using the description.
            _alphaEnabledBlendState = new BlendState(Device, blendStateDescription);

            blendStateDescription.RenderTarget[0].IsBlendEnabled = false;
            // Create the blend state using the description.
            _alphaDisabledBlendState = new BlendState(Device, blendStateDescription);
        }
コード例 #20
0
ファイル: Demo.cs プロジェクト: rhynodegreat/BulletSharp
        public void Initialize()
        {
            Form.SizeChanged += (o, args) =>
            {
                if (_swapChain == null)
                    return;

                renderView.Dispose();
                depthView.Dispose();
                DisposeBuffers();

                if (Form.WindowState == FormWindowState.Minimized)
                    return;

                Width = Form.ClientSize.Width;
                Height = Form.ClientSize.Height;
                _swapChain.ResizeBuffers(_swapChain.Description.BufferCount, 0, 0, Format.Unknown, 0);

                CreateBuffers();
                SetSceneConstants();
            };

            Width = 1024;
            Height = 768;
            NearPlane = 1.0f;
            FarPlane = 200.0f;
            FieldOfView = (float)Math.PI / 4;

            try
            {
                OnInitializeDevice();
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString(), "Could not create DirectX 11 device.");
                return;
            }


            // shader.fx

            const ShaderFlags shaderFlags = ShaderFlags.None;
            //const ShaderFlags shaderFlags = ShaderFlags.Debug | ShaderFlags.SkipOptimization;

            string[] sources = new[] { "shader.fx", "grender.fx" };
            using (var shaderByteCode = ShaderLoader.FromResource(Assembly.GetExecutingAssembly(), sources, shaderFlags))
            {
                effect = new Effect(_device, shaderByteCode);
            }
            EffectTechnique technique = effect.GetTechniqueByName("GBufferCreate");
            shadowGenPass = technique.GetPassByName("ShadowMap");
            gBufferGenPass = technique.GetPassByName("GBufferGen");
            debugDrawPass = technique.GetPassByName("DebugDraw");

            BufferDescription sceneConstantsDesc = new BufferDescription()
            {
                SizeInBytes = Marshal.SizeOf(typeof(ShaderSceneConstants)),
                Usage = ResourceUsage.Dynamic,
                BindFlags = BindFlags.ConstantBuffer,
                CpuAccessFlags = CpuAccessFlags.Write,
                OptionFlags = ResourceOptionFlags.None
            };
            sceneConstantsBuffer = new Buffer(_device, sceneConstantsDesc);
            EffectConstantBuffer effectConstantBuffer = effect.GetConstantBufferByName("scene");
            effectConstantBuffer.SetConstantBuffer(sceneConstantsBuffer);

            RasterizerStateDescription _rasterizerStateDesc = new RasterizerStateDescription()
            {
                CullMode = CullMode.None,
                FillMode = FillMode.Solid,
                DepthBias = 0,
                DepthBiasClamp = 0,
                SlopeScaledDepthBias = 0,
                IsDepthClipEnabled = true,
            };
            noCullState = new RasterizerState(_device, _rasterizerStateDesc);
            _rasterizerStateDesc.CullMode = CullMode.Back;
            backCullState = new RasterizerState(_device, _rasterizerStateDesc);
            _rasterizerStateDesc.CullMode = CullMode.Front;
            frontCullState = new RasterizerState(_device, _rasterizerStateDesc);
            _immediateContext.Rasterizer.State = CullingEnabled ? backCullState : noCullState;

            DepthStencilStateDescription depthDesc = new DepthStencilStateDescription()
            {
                IsDepthEnabled = true,
                IsStencilEnabled = false,
                DepthWriteMask = DepthWriteMask.All,
                DepthComparison = Comparison.Less
            };
            depthState = new DepthStencilState(_device, depthDesc);
            depthDesc.DepthWriteMask = DepthWriteMask.Zero;
            outsideLightVolumeDepthState = new DepthStencilState(_device, depthDesc);
            depthDesc.DepthComparison = Comparison.Greater;
            insideLightVolumeDepthState = new DepthStencilState(_device, depthDesc);

            DepthStencilStateDescription lightDepthStateDesc = new DepthStencilStateDescription()
            {
                IsDepthEnabled = true,
                IsStencilEnabled = false,
                DepthWriteMask = DepthWriteMask.All,
                DepthComparison = Comparison.Less
            };
            lightDepthStencilState = new DepthStencilState(_device, lightDepthStateDesc);


            // grender.fx
            technique = effect.GetTechniqueByName("DeferredShader");
            gBufferRenderPass = technique.GetPassByName("DeferredShader");
            gBufferPostProcessPass = technique.GetPassByName("Blur");
            gBufferPostProcessPass2 = technique.GetPassByName("PostProcess");
            gBufferOverlayPass = technique.GetPassByName("Overlay");

            lightBufferVar = effect.GetVariableByName("lightBuffer").AsShaderResource();
            normalBufferVar = effect.GetVariableByName("normalBuffer").AsShaderResource();
            diffuseBufferVar = effect.GetVariableByName("diffuseBuffer").AsShaderResource();
            depthMapVar = effect.GetVariableByName("depthMap").AsShaderResource();
            shadowLightDepthBufferVar = effect.GetVariableByName("lightDepthMap").AsShaderResource();

            sunLightDirectionVar = effect.GetVariableByName("SunLightDirection").AsVector();
            viewportWidthVar = effect.GetVariableByName("ViewportWidth").AsScalar();
            viewportHeightVar = effect.GetVariableByName("ViewportHeight").AsScalar();
            viewParametersVar = effect.GetVariableByName("ViewParameters").AsVector();

            overlayViewProjectionVar = effect.GetVariableByName("OverlayViewProjection").AsMatrix();


            // light.fx
            using (var shaderByteCode = ShaderLoader.FromResource(Assembly.GetExecutingAssembly(), "light.fx", shaderFlags))
            {
                lightShader = new Effect(_device, shaderByteCode);
            }

            technique = lightShader.GetTechniqueByIndex(0);
            lightAccumulationPass = technique.GetPassByName("Light");

            lightWorldVar = lightShader.GetVariableByName("World").AsMatrix();
            lightPositionRadiusVar = lightShader.GetVariableByName("PositionRadius").AsVector();
            lightColorVar = lightShader.GetVariableByName("Color").AsVector();

            lightProjectionVar = lightShader.GetVariableByName("Projection").AsMatrix();
            lightViewVar = lightShader.GetVariableByName("View").AsMatrix();
            lightViewInverseVar = lightShader.GetVariableByName("ViewInverse").AsMatrix();
            lightViewportWidthVar = lightShader.GetVariableByName("ViewportWidth").AsScalar();
            lightViewportHeightVar = lightShader.GetVariableByName("ViewportHeight").AsScalar();
            lightEyePositionVar = lightShader.GetVariableByName("EyePosition").AsVector();
            lightViewParametersVar = lightShader.GetVariableByName("ViewParameters").AsVector();

            InputElement[] elements = new InputElement[]
            {
                new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0, InputClassification.PerVertexData, 0),
            };
            lightVolumeInputLayout = new InputLayout(Device, lightShader.GetTechniqueByIndex(0).GetPassByName("Light").Description.Signature, elements);

            pointLightVolumeVertices = Light.CreatePointLightVolume(out pointLightVolumeIndices);
            BufferDescription vertexBufferDesc = new BufferDescription()
            {
                SizeInBytes = Vector3.SizeInBytes * pointLightVolumeVertices.Length,
                Usage = ResourceUsage.Default,
                BindFlags = BindFlags.VertexBuffer,
            };

            using (var data = new SharpDX.DataStream(vertexBufferDesc.SizeInBytes, false, true))
            {
                data.WriteRange(pointLightVolumeVertices);
                data.Position = 0;
                pointLightVolumeVertexBuffer = new Buffer(Device, data, vertexBufferDesc);
            }
            pointLightVolumeVertexBufferBinding = new VertexBufferBinding(pointLightVolumeVertexBuffer, 12, 0);

            BufferDescription indexBufferDesc = new BufferDescription()
            {
                SizeInBytes = sizeof(uint) * pointLightVolumeIndices.Length,
                Usage = ResourceUsage.Default,
                BindFlags = BindFlags.IndexBuffer
            };
            using (var data = new SharpDX.DataStream(indexBufferDesc.SizeInBytes, false, true))
            {
                data.WriteRange(pointLightVolumeIndices);
                data.Position = 0;
                pointLightVolumeIndexBuffer = new Buffer(Device, data, indexBufferDesc);
            }

            lightDepthBufferVar = lightShader.GetVariableByName("depthBuffer").AsShaderResource();
            lightNormalBufferVar = lightShader.GetVariableByName("normalBuffer").AsShaderResource();

            lights.Add(new Light(pointLightPosition, 60, new Vector4(1, 0.95f, 0.9f, 1)));
            //lights.Add(new Light(pointLightPosition, 60, new Vector4(0, 0, 1, 1)));
            //lights.Add(new Light(new Vector3(-10, 10, 10), 30, new Vector4(1, 0, 0, 1)));
            //lights.Add(new Light(new Vector3(10, 5, -10), 20, new Vector4(0, 1, 0, 1)));
            //lights.Add(new Light(new Vector3(-10, 5, -10), 20, new Vector4(1, 0, 1, 1)));


            Info = new InfoText(_device, 256, 256);
            _meshFactory = new MeshFactory(this);

            CreateBuffers();
        }
コード例 #21
0
        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));
            }
        }
コード例 #22
0
ファイル: RasterizerState.cs プロジェクト: numo16/SharpDX
 /// <summary>	
 /// <p>Create a rasterizer state object that tells the rasterizer stage how to behave.</p>	
 /// </summary>	
 /// <param name="device">The <see cref="GraphicsDevice"/>.</param>
 /// <param name="description">A rasterizer state description</param>	
 /// <remarks>	
 /// <p>4096 unique rasterizer state objects can be created on a device at a time.</p><p>If an application attempts to create a rasterizer-state interface with the same state as an existing interface, the same interface will be returned and the total number of unique rasterizer state objects will stay the same.</p>	
 /// </remarks>	
 /// <msdn-id>ff476516</msdn-id>	
 /// <unmanaged>HRESULT ID3D11Device::CreateRasterizerState([In] const D3D11_RASTERIZER_DESC* pRasterizerDesc,[Out, Fast] ID3D11RasterizerState** ppRasterizerState)</unmanaged>	
 /// <unmanaged-short>ID3D11Device::CreateRasterizerState</unmanaged-short>	
 public static RasterizerState New(GraphicsDevice device, RasterizerStateDescription description)
 {
     return new RasterizerState(device, description);
 }
コード例 #23
0
ファイル: MyResource.cs プロジェクト: Krulac/SpaceEngineers
        internal static void Modify(RasterizerId id, RasterizerStateDescription desc)
        {
            RasterizerStates.Data[id.Index] = desc;

            InitRasterizerState(id);
        }
コード例 #24
0
ファイル: RenderStates11.cs プロジェクト: Hozuki/Noire
        private void InitializeInternal(Device device) {
            Debug.Assert(device != null);

            var wfDesc = new RasterizerStateDescription {
                FillMode = FillMode.Wireframe,
                CullMode = CullMode.Back,
                IsFrontCounterClockwise = false,
                IsDepthClipEnabled = true
            };
            _wireframeRs = new RasterizerState(device, wfDesc);

            var noCullDesc = new RasterizerStateDescription {
                FillMode = FillMode.Solid,
                CullMode = CullMode.None,
                IsFrontCounterClockwise = false,
                IsDepthClipEnabled = true
            };
            _noCullRs = new RasterizerState(device, noCullDesc);

            var cullClockwiseDesc = new RasterizerStateDescription {
                FillMode = FillMode.Solid,
                CullMode = CullMode.Back,
                IsFrontCounterClockwise = true,
                IsDepthClipEnabled = true
            };
            _cullClockwiseRs = new RasterizerState(device, cullClockwiseDesc);

            var atcDesc = new BlendStateDescription {
                AlphaToCoverageEnable = true,
                IndependentBlendEnable = false,
            };
            atcDesc.RenderTarget[0].IsBlendEnabled = false;
            atcDesc.RenderTarget[0].RenderTargetWriteMask = ColorWriteMaskFlags.All;
            _alphaToCoverageBs = new BlendState(device, atcDesc);

            var transDesc = new BlendStateDescription {
                AlphaToCoverageEnable = false,
                IndependentBlendEnable = false
            };
            transDesc.RenderTarget[0].IsBlendEnabled = true;
            transDesc.RenderTarget[0].SourceBlend = BlendOption.SourceAlpha;
            transDesc.RenderTarget[0].DestinationBlend = BlendOption.InverseSourceAlpha;
            transDesc.RenderTarget[0].BlendOperation = BlendOperation.Add;
            transDesc.RenderTarget[0].SourceAlphaBlend = BlendOption.One;
            transDesc.RenderTarget[0].DestinationAlphaBlend = BlendOption.Zero;
            transDesc.RenderTarget[0].AlphaBlendOperation = BlendOperation.Add;
            transDesc.RenderTarget[0].RenderTargetWriteMask = ColorWriteMaskFlags.All;

            _transparentBs = new BlendState(device, transDesc);

            var noRenderTargetWritesDesc = new BlendStateDescription {
                AlphaToCoverageEnable = false,
                IndependentBlendEnable = false
            };
            noRenderTargetWritesDesc.RenderTarget[0].IsBlendEnabled = false;
            noRenderTargetWritesDesc.RenderTarget[0].SourceBlend = BlendOption.One;
            noRenderTargetWritesDesc.RenderTarget[0].DestinationBlend = BlendOption.Zero;
            noRenderTargetWritesDesc.RenderTarget[0].BlendOperation = BlendOperation.Add;
            noRenderTargetWritesDesc.RenderTarget[0].SourceAlphaBlend = BlendOption.One;
            noRenderTargetWritesDesc.RenderTarget[0].DestinationAlphaBlend = BlendOption.Zero;
            noRenderTargetWritesDesc.RenderTarget[0].AlphaBlendOperation = BlendOperation.Add;
            noRenderTargetWritesDesc.RenderTarget[0].RenderTargetWriteMask = 0;

            _noRenderTargetWritesBs = new BlendState(device, noRenderTargetWritesDesc);

            var mirrorDesc = new DepthStencilStateDescription {
                IsDepthEnabled = true,
                DepthWriteMask = DepthWriteMask.Zero,
                DepthComparison = Comparison.Less,
                IsStencilEnabled = true,
                StencilReadMask = 0xff,
                StencilWriteMask = 0xff,
                FrontFace = new DepthStencilOperationDescription {
                    FailOperation = StencilOperation.Keep,
                    DepthFailOperation = StencilOperation.Keep,
                    PassOperation = StencilOperation.Replace,
                    Comparison = Comparison.Always
                },
                BackFace = new DepthStencilOperationDescription {
                    FailOperation = StencilOperation.Keep,
                    DepthFailOperation = StencilOperation.Keep,
                    PassOperation = StencilOperation.Replace,
                    Comparison = Comparison.Always
                }
            };

            _markMirrorDss = new DepthStencilState(device, mirrorDesc);

            var drawReflectionDesc = new DepthStencilStateDescription {
                IsDepthEnabled = true,
                DepthWriteMask = DepthWriteMask.All,
                DepthComparison = Comparison.Less,
                IsStencilEnabled = true,
                StencilReadMask = 0xff,
                StencilWriteMask = 0xff,
                FrontFace = new DepthStencilOperationDescription {
                    FailOperation = StencilOperation.Keep,
                    DepthFailOperation = StencilOperation.Keep,
                    PassOperation = StencilOperation.Keep,
                    Comparison = Comparison.Equal
                },
                BackFace = new DepthStencilOperationDescription {
                    FailOperation = StencilOperation.Keep,
                    DepthFailOperation = StencilOperation.Keep,
                    PassOperation = StencilOperation.Keep,
                    Comparison = Comparison.Equal
                }
            };
            _drawReflectionDss = new DepthStencilState(device, drawReflectionDesc);

            var noDoubleBlendDesc = new DepthStencilStateDescription {
                IsDepthEnabled = true,
                DepthWriteMask = DepthWriteMask.All,
                DepthComparison = Comparison.Less,
                IsStencilEnabled = true,
                StencilReadMask = 0xff,
                StencilWriteMask = 0xff,
                FrontFace = new DepthStencilOperationDescription {
                    FailOperation = StencilOperation.Keep,
                    DepthFailOperation = StencilOperation.Keep,
                    PassOperation = StencilOperation.Increment,
                    Comparison = Comparison.Equal
                },
                BackFace = new DepthStencilOperationDescription {
                    FailOperation = StencilOperation.Keep,
                    DepthFailOperation = StencilOperation.Keep,
                    PassOperation = StencilOperation.Increment,
                    Comparison = Comparison.Equal
                }
            };
            _noDoubleBlendDss = new DepthStencilState(device, noDoubleBlendDesc);

            var lessEqualDesc = new DepthStencilStateDescription {
                IsDepthEnabled = true,
                DepthWriteMask = DepthWriteMask.All,
                DepthComparison = Comparison.LessEqual,
                IsStencilEnabled = false
            };
            _lessEqualDss = new DepthStencilState(device, lessEqualDesc);

            var equalsDesc = new DepthStencilStateDescription() {
                IsDepthEnabled = true,
                DepthWriteMask = DepthWriteMask.Zero,
                DepthComparison = Comparison.LessEqual,

            };
            _equalsDss = new DepthStencilState(device, equalsDesc);

            var noDepthDesc = new DepthStencilStateDescription() {
                IsDepthEnabled = false,
                DepthComparison = Comparison.Always,
                DepthWriteMask = DepthWriteMask.Zero
            };
            _noDepthDss = new DepthStencilState(device, noDepthDesc);
        }
コード例 #25
0
        public Window(SwapChainPanel panel, Aiv.Fast2D.UWP.IGame game)
        {
            this.context = panel;
            this.game    = game;

            using (D3D11.Device defaultDevice = new D3D11.Device(D3D.DriverType.Hardware, D3D11.DeviceCreationFlags.Debug))
            {
                this.device = defaultDevice.QueryInterface <D3D11.Device2>();
            }

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

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

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

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

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



            FinalizeSetup();

            width  = (int)this.context.RenderSize.Width;
            height = (int)this.context.RenderSize.Height;

            scaleX = 1;
            scaleY = 1;



            this.SetViewport(0, 0, width, height);

            // for now disable only backface culling
            D3D11.RasterizerStateDescription rasterizerDescription = D3D11.RasterizerStateDescription.Default();
            rasterizerDescription.CullMode      = D3D11.CullMode.None;
            this.deviceContext.Rasterizer.State = new SharpDX.Direct3D11.RasterizerState(this.device, rasterizerDescription);

            vsync = 1;

            CompositionTarget.Rendering += this.Update;
            this.game.GameSetup(this);

            watch = new Stopwatch();
        }
コード例 #26
0
ファイル: MyResource.cs プロジェクト: Chrus/SpaceEngineers
        internal static void Modify(RasterizerId id, RasterizerStateDescription desc)
        {
            RasterizerStates.Data[id.Index] = desc;
            RasterizerObjects[id.Index].Dispose();
            RasterizerObjects[id.Index] = null;

            InitRasterizerState(id);
        }
コード例 #27
0
		/// <summary>
		/// SetupRasterizerState
		/// </summary>
		void SetupRasterizerState ()
		{
			var rsd = new RasterizerStateDescription();

			if ( RasterizerState.CullMode == CullMode.CullNone ) {

				rsd.CullMode				=	D3DCullMode.None;
				rsd.IsFrontCounterClockwise	=	false;

			} else if ( RasterizerState.CullMode == CullMode.CullCW ) {

				rsd.CullMode				=	D3DCullMode.Front;
				rsd.IsFrontCounterClockwise	=	false;

			} else if ( RasterizerState.CullMode == CullMode.CullCCW ) {

				rsd.CullMode				=	D3DCullMode.Front;
				rsd.IsFrontCounterClockwise	=	true;
			}


			rsd.FillMode				=	Converter.Convert( RasterizerState.FillMode );
			rsd.DepthBias				=	RasterizerState.DepthBias;
			rsd.DepthBiasClamp			=	0;
			rsd.IsMultisampleEnabled	=	RasterizerState.MsaaEnabled;
			rsd.IsScissorEnabled		=	RasterizerState.ScissorEnabled;
			rsd.SlopeScaledDepthBias	=	RasterizerState.SlopeDepthBias;
			rsd.IsDepthClipEnabled		=	RasterizerState.DepthClipEnabled;

			rasterState	=	new D3DRasterizerState( device.Device, rsd );
		}
コード例 #28
0
 private static RasterizerStateDescription GetRasterizer(CullMode cullMode)
 {
     var rasterizerDescription = new RasterizerStateDescription
     {
         CullMode = cullMode,
         FillMode = FillMode.Solid,
         IsFrontCounterClockwise = false,
         DepthBias = 0,
         DepthBiasClamp = 0.0f,
         SlopeScaledDepthBias = 0.0f,
         IsDepthClipEnabled = true,
         IsScissorEnabled = false,
         IsMultisampleEnabled = true,
         IsAntialiasedLineEnabled = false
     };
     return rasterizerDescription;
 }
コード例 #29
0
ファイル: RasterizerState.cs プロジェクト: numo16/SharpDX
 /// <summary>
 /// Initializes a new instance of the <see cref="RasterizerState" /> class.
 /// </summary>
 /// <param name="device">The <see cref="GraphicsDevice"/>.</param>
 /// <param name="description">The description.</param>
 private RasterizerState(GraphicsDevice device, RasterizerStateDescription description) : base(device.MainDevice)
 {
     Description = description;
     Initialize(new Direct3D11.RasterizerState(GraphicsDevice, Description));
 }
コード例 #30
0
        public override void Run()
        {
            #region Create renderers

            // Note: the renderers take care of creating their own
            // device resources and listen for DeviceManager.OnInitialize

            // Create a axis-grid renderer
            var axisGrid = ToDispose(new AxisGridRenderer());
            axisGrid.Initialize(this);

            // Create and initialize the mesh renderer
            var loadedMesh = Common.Mesh.LoadFromFile("Character.cmo");
            List<MeshRenderer> meshes = new List<MeshRenderer>();
            meshes.AddRange((from mesh in loadedMesh
                             select ToDispose(new MeshRenderer(mesh))));
            foreach (var m in meshes) {
                m.Initialize(this);
                m.World = Matrix.Identity;
            }

            // Create and initialize a Direct2D FPS text renderer
            var fps = ToDispose(new Common.FpsRenderer("Calibri", Color.CornflowerBlue, new Point(8, 8), 16));
            fps.Initialize(this);

            // Create and initialize a general purpose Direct2D text renderer
            // This will display some instructions and the current view and rotation offsets
            var textRenderer = ToDispose(new Common.TextRenderer("Calibri", Color.CornflowerBlue, new Point(8, 40), 12));
            textRenderer.Initialize(this);

            #endregion

            // Initialize the world matrix
            var worldMatrix = Matrix.Identity;

            // Set the camera position
            var cameraPosition = new Vector3(1, 1, 2);
            var cameraTarget = Vector3.Zero; // Looking at the origin 0,0,0
            var cameraUp = Vector3.UnitY; // Y+ is Up

            // Prepare matrices
            // Create the view matrix from our camera position, look target and up direction
            var viewMatrix = Matrix.LookAtRH(cameraPosition, cameraTarget, cameraUp);
            viewMatrix.TranslationVector += new Vector3(0, -0.98f, 0);

            // Create the projection matrix
            /* FoV 60degrees = Pi/3 radians */
            // Aspect ratio (based on window size), Near clip, Far clip
            var projectionMatrix = Matrix.PerspectiveFovRH((float)Math.PI / 3f, Width / (float)Height, 0.5f, 100f);

            // Maintain the correct aspect ratio on resize
            Window.Resize += (s, e) =>
            {
                projectionMatrix = Matrix.PerspectiveFovRH((float)Math.PI / 3f, Width / (float)Height, 0.5f, 100f);
            };

            #region Rotation and window event handlers

            // Create a rotation vector to keep track of the rotation
            // around each of the axes
            var rotation = new Vector3(0.0f, 0.0f, 0.0f);

            // We will call this action to update text
            // for the text renderer
            Action updateText = () =>
            {
                textRenderer.Text =
                    String.Format("Rotation ({0}) (Up/Down Left/Right Wheel+-)\nView ({1}) (A/D, W/S, Shift+Wheel+-)"
                    + "\nPress X to reinitialize the device and resources (device ptr: {2})"
                    + "\nPress Z to show/hide depth buffer - Press F to toggle wireframe"
                    + "\nPress 1,2,3,4 to switch shaders",
                        rotation,
                        viewMatrix.TranslationVector,
                        DeviceManager.Direct3DDevice.NativePointer);
            };

            Dictionary<Keys, bool> keyToggles = new Dictionary<Keys, bool>();
            keyToggles[Keys.Z] = false;
            keyToggles[Keys.F] = false;

            // Support keyboard/mouse input to rotate or move camera view
            var moveFactor = 0.02f; // how much to change on each keypress
            var shiftKey = false;
            var ctrlKey = false;
            var background = Color.White;
            Window.KeyDown += (s, e) =>
            {
                var context = DeviceManager.Direct3DContext;

                shiftKey = e.Shift;
                ctrlKey = e.Control;

                switch (e.KeyCode)
                {
                    // WASD -> pans view
                    case Keys.A:
                        viewMatrix.TranslationVector += new Vector3(moveFactor * 2, 0f, 0f);
                        break;
                    case Keys.D:
                        viewMatrix.TranslationVector -= new Vector3(moveFactor * 2, 0f, 0f);
                        break;
                    case Keys.S:
                        if (shiftKey)
                            viewMatrix.TranslationVector += new Vector3(0f, moveFactor * 2, 0f);
                        else
                            viewMatrix.TranslationVector -= new Vector3(0f, 0f, 1) * moveFactor * 2;
                        break;
                    case Keys.W:
                        if (shiftKey)
                            viewMatrix.TranslationVector -= new Vector3(0f, moveFactor * 2, 0f);
                        else
                            viewMatrix.TranslationVector += new Vector3(0f, 0f, 1) * moveFactor * 2;
                        break;
                    // Up/Down and Left/Right - rotates around X / Y respectively
                    // (Mouse wheel rotates around Z)
                    case Keys.Down:
                        worldMatrix *= Matrix.RotationX(moveFactor);
                        rotation += new Vector3(moveFactor, 0f, 0f);
                        break;
                    case Keys.Up:
                        worldMatrix *= Matrix.RotationX(-moveFactor);
                        rotation -= new Vector3(moveFactor, 0f, 0f);
                        break;
                    case Keys.Left:
                        worldMatrix *= Matrix.RotationY(moveFactor);
                        rotation += new Vector3(0f, moveFactor, 0f);
                        break;
                    case Keys.Right:
                        worldMatrix *= Matrix.RotationY(-moveFactor);
                        rotation -= new Vector3(0f, moveFactor, 0f);
                        break;
                    case Keys.T:
                        fps.Show = !fps.Show;
                        textRenderer.Show = !textRenderer.Show;
                        break;
                    case Keys.B:
                        if (background == Color.White)
                        {
                            background = new Color(30, 30, 34);
                        }
                        else
                        {
                            background = Color.White;
                        }
                        break;
                    case Keys.G:
                        axisGrid.Show = !axisGrid.Show;
                        break;
                    case Keys.X:
                        // To test for correct resource recreation
                        // Simulate device reset or lost.
                        System.Diagnostics.Debug.WriteLine(SharpDX.Diagnostics.ObjectTracker.ReportActiveObjects());
                        DeviceManager.Initialize(DeviceManager.Dpi);
                        System.Diagnostics.Debug.WriteLine(SharpDX.Diagnostics.ObjectTracker.ReportActiveObjects());
                        break;
                    case Keys.Z:
                        keyToggles[Keys.Z] = !keyToggles[Keys.Z];
                        if (keyToggles[Keys.Z])
                        {
                            context.PixelShader.Set(depthPixelShader);
                        }
                        else
                        {
                            context.PixelShader.Set(pixelShader);
                        }
                        break;
                    case Keys.F:
                        keyToggles[Keys.F] = !keyToggles[Keys.F];
                        RasterizerStateDescription rasterDesc;
                        if (context.Rasterizer.State != null)
                            rasterDesc = context.Rasterizer.State.Description;
                        else
                            rasterDesc = new RasterizerStateDescription()
                            {
                                CullMode = CullMode.Back,
                                FillMode = FillMode.Solid
                            };
                        if (keyToggles[Keys.F])
                        {
                            rasterDesc.FillMode = FillMode.Wireframe;
                            context.Rasterizer.State = ToDispose(new RasterizerState(context.Device, rasterDesc));
                        }
                        else
                        {
                            rasterDesc.FillMode = FillMode.Solid;
                            context.Rasterizer.State = ToDispose(new RasterizerState(context.Device, rasterDesc));
                        }
                        break;
                    case Keys.D1:
                        context.PixelShader.Set(pixelShader);
                        break;
                    case Keys.D2:
                        context.PixelShader.Set(lambertShader);
                        break;
                    case Keys.D3:
                        context.PixelShader.Set(phongShader);
                        break;
                    case Keys.D4:
                        context.PixelShader.Set(blinnPhongShader);
                        break;
                }

                updateText();
            };
            Window.KeyUp += (s, e) =>
            {
                // Clear the shift/ctrl keys so they aren't sticky
                if (e.KeyCode == Keys.ShiftKey)
                    shiftKey = false;
                if (e.KeyCode == Keys.ControlKey)
                    ctrlKey = false;
            };
            Window.MouseWheel += (s, e) =>
            {
                if (shiftKey)
                {
                    // Zoom in/out
                    viewMatrix.TranslationVector += new Vector3(0f, 0f, (e.Delta / 120f) * moveFactor * 2);
                }
                else
                {
                    // rotate around Z-axis
                    viewMatrix *= Matrix.RotationZ((e.Delta / 120f) * moveFactor);
                    rotation += new Vector3(0f, 0f, (e.Delta / 120f) * moveFactor);
                }
                updateText();
            };

            var lastX = 0;
            var lastY = 0;

            Window.MouseDown += (s, e) =>
            {
                if (e.Button == MouseButtons.Left)
                {
                    lastX = e.X;
                    lastY = e.Y;
                }
            };

            Window.MouseMove += (s, e) =>
            {
                if (e.Button == MouseButtons.Left)
                {
                    var yRotate = lastX - e.X;
                    var xRotate = lastY - e.Y;
                    lastY = e.Y;
                    lastX = e.X;

                    // Mouse move changes
                    viewMatrix *= Matrix.RotationX(-xRotate * moveFactor);
                    viewMatrix *= Matrix.RotationY(-yRotate * moveFactor);

                    updateText();
                }
            };

            // Display instructions with initial values
            updateText();

            #endregion

            var clock = new System.Diagnostics.Stopwatch();
            clock.Start();

            #region Render loop

            // Create and run the render loop
            RenderLoop.Run(Window, () =>
            {
                // Start of frame:

                // Retrieve immediate context
                var context = DeviceManager.Direct3DContext;

                // Clear depth stencil view
                context.ClearDepthStencilView(DepthStencilView, DepthStencilClearFlags.Depth | DepthStencilClearFlags.Stencil, 1.0f, 0);
                // Clear render target view
                context.ClearRenderTargetView(RenderTargetView, background);

                // Create viewProjection matrix
                var viewProjection = Matrix.Multiply(viewMatrix, projectionMatrix);

                // Extract camera position from view
                var camPosition = Matrix.Transpose(Matrix.Invert(viewMatrix)).Column4;
                cameraPosition = new Vector3(camPosition.X, camPosition.Y, camPosition.Z);

                // If Keys.CtrlKey is down, auto rotate viewProjection based on time
                var time = clock.ElapsedMilliseconds / 1000.0f;
                if (ctrlKey)
                {
                    viewProjection = Matrix.RotationY(time * 1.8f) * Matrix.RotationX(time * 1f) * Matrix.RotationZ(time * 0.6f) * viewProjection;
                }
                var worldRotation = Matrix.RotationAxis(Vector3.UnitY, time);

                var perFrame = new ConstantBuffers.PerFrame();
                perFrame.Light.Color = new Color(0.8f, 0.8f, 0.8f, 1.0f);
                var lightDir = Vector3.Transform(new Vector3(1f, -1f, -1f), worldMatrix);
                perFrame.Light.Direction = new Vector3(lightDir.X, lightDir.Y, lightDir.Z);// new Vector3(Vector3.Transform(new Vector3(1f, -1f, 1f), worldMatrix * worldRotation).ToArray().Take(3).ToArray());
                perFrame.CameraPosition = cameraPosition;
                context.UpdateSubresource(ref perFrame, perFrameBuffer);

                // Render each object

                var perMaterial = new ConstantBuffers.PerMaterial();
                perMaterial.Ambient = new Color4(0.2f);
                perMaterial.Diffuse = Color.White;
                perMaterial.Emissive = new Color4(0);
                perMaterial.Specular = Color.White;
                perMaterial.SpecularPower = 20f;
                perMaterial.HasTexture = 0;
                perMaterial.UVTransform = Matrix.Identity;
                context.UpdateSubresource(ref perMaterial, perMaterialBuffer);

                var perObject = new ConstantBuffers.PerObject();

                foreach (var m in meshes)
                {
                    // MESH
                    perObject.World = m.World * worldMatrix;
                    perObject.WorldInverseTranspose = Matrix.Transpose(Matrix.Invert(perObject.World));
                    perObject.WorldViewProjection = perObject.World * viewProjection;
                    perObject.Transpose();
                    context.UpdateSubresource(ref perObject, perObjectBuffer);

                    // Provide the material constant buffer to the mesh renderer
                    m.PerMaterialBuffer = perMaterialBuffer;
                    m.PerArmatureBuffer = perArmatureBuffer;
                    m.Render();
                }

                // AXIS GRID
                using (var prevPixelShader = context.PixelShader.Get())
                {
                    perMaterial.HasTexture = 0;
                    perMaterial.UVTransform = Matrix.Identity;
                    context.UpdateSubresource(ref perMaterial, perMaterialBuffer);
                    context.PixelShader.Set(pixelShader);
                    perObject.World = worldMatrix;
                    perObject.WorldInverseTranspose = Matrix.Transpose(Matrix.Invert(perObject.World));
                    perObject.WorldViewProjection = perObject.World * viewProjection;
                    perObject.Transpose();
                    context.UpdateSubresource(ref perObject, perObjectBuffer);
                    axisGrid.Render();
                    context.PixelShader.Set(prevPixelShader);
                }

                // Render FPS
                fps.Render();

                // Render instructions + position changes
                textRenderer.Render();

                // Present the frame
                Present();
            });
            #endregion
        }
コード例 #31
0
ファイル: RasterizerState.cs プロジェクト: numo16/SharpDX
 /// <summary>
 /// Initializes a new instance of the <see cref="RasterizerState" /> class.
 /// </summary>
 /// <param name="device">The <see cref="GraphicsDevice"/>.</param>
 /// <param name="nativeState">State of the native.</param>
 private RasterizerState(GraphicsDevice device, Direct3D11.RasterizerState nativeState) : base(device.MainDevice)
 {
     Description = nativeState.Description;
     Initialize(nativeState);
 }
コード例 #32
0
        private void InitializeDeviceResources(DXGI.SwapChain swapChain)
        {
            backbufferTexture = swapChain.GetBackBuffer <D3D11.Texture2D>(0);
            backbufferRTV     = new D3D11.RenderTargetView(device, backbufferTexture);

            width  = backbufferTexture.Description.Width;
            height = backbufferTexture.Description.Height;

            D3D11.Texture2DDescription sceneTextureDesc = new D3D11.Texture2DDescription
            {
                CpuAccessFlags    = D3D11.CpuAccessFlags.None,
                BindFlags         = D3D11.BindFlags.RenderTarget | D3D11.BindFlags.ShaderResource,
                Format            = DXGI.Format.R8G8B8A8_UNorm,
                Width             = width,
                Height            = height,
                OptionFlags       = D3D11.ResourceOptionFlags.None,
                MipLevels         = 1,
                ArraySize         = 1,
                SampleDescription = { Count = 1, Quality = 0 },
                Usage             = D3D11.ResourceUsage.Default
            };

            sceneTexture = new D3D11.Texture2D(device, sceneTextureDesc);
            sceneRTV     = new D3D11.RenderTargetView(device, sceneTexture);
            sceneSRV     = new D3D11.ShaderResourceView(device, sceneTexture);

            var depthBufferDesc = new D3D11.Texture2DDescription()
            {
                Width             = width,
                Height            = height,
                MipLevels         = 1,
                ArraySize         = 1,
                Format            = DXGI.Format.R32_Typeless,
                SampleDescription = { Count = 1, Quality = 0 },
                Usage             = D3D11.ResourceUsage.Default,
                BindFlags         = D3D11.BindFlags.DepthStencil | D3D11.BindFlags.ShaderResource,
                CpuAccessFlags    = D3D11.CpuAccessFlags.None,
                OptionFlags       = D3D11.ResourceOptionFlags.None
            };

            using (var depthStencilBufferTexture = new D3D11.Texture2D(device, depthBufferDesc))
            {
                var depthStencilViewDesc = new D3D11.DepthStencilViewDescription()
                {
                    Format    = DXGI.Format.D32_Float,
                    Dimension = D3D11.DepthStencilViewDimension.Texture2D,
                    Texture2D = { MipSlice = 0 }
                };

                depthDSV = new D3D11.DepthStencilView(device, depthStencilBufferTexture, depthStencilViewDesc);

                var shaderResourceViewDesc = new D3D11.ShaderResourceViewDescription()
                {
                    Format    = DXGI.Format.R32_Float,
                    Dimension = SharpDX.Direct3D.ShaderResourceViewDimension.Texture2D,
                    Texture2D = { MipLevels = 1, MostDetailedMip = 0 }
                };

                depthSRV = new D3D11.ShaderResourceView(device, depthStencilBufferTexture, shaderResourceViewDesc);
            }

            var depthStencilDesc = new D3D11.DepthStencilStateDescription()
            {
                IsDepthEnabled   = true,
                DepthWriteMask   = D3D11.DepthWriteMask.All,
                DepthComparison  = D3D11.Comparison.Less,
                IsStencilEnabled = false,
                StencilReadMask  = 0xFF,
                StencilWriteMask = 0xFF,

                FrontFace = new D3D11.DepthStencilOperationDescription()
                {
                    FailOperation      = D3D11.StencilOperation.Keep,
                    DepthFailOperation = D3D11.StencilOperation.Keep,
                    PassOperation      = D3D11.StencilOperation.Keep,
                    Comparison         = D3D11.Comparison.Always
                },

                BackFace = new D3D11.DepthStencilOperationDescription()
                {
                    FailOperation      = D3D11.StencilOperation.Keep,
                    DepthFailOperation = D3D11.StencilOperation.Keep,
                    PassOperation      = D3D11.StencilOperation.Keep,
                    Comparison         = D3D11.Comparison.Always
                }
            };

            depthStencilState = new D3D11.DepthStencilState(device, depthStencilDesc);

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

            rasterizerState = new D3D11.RasterizerState(device, rasterDesc);
        }
コード例 #33
0
        /// <summary>
        /// Creates Direct3D11 Device, RenderTargetView, DepthStencilView, Viewport
        /// </summary>
        /// <param name="deviceDescription">The device description.</param>
        /// <exception cref="System.Exception"></exception>
        /// <exception cref="System.ComponentModel.InvalidEnumArgumentException">deviceDescription.MultiSampleCount</exception>
        private void Initialize(DeviceDescription deviceDescription)
        {
            FeatureLevel[] levels = new FeatureLevel[] {
                FeatureLevel.Level_10_0,
                FeatureLevel.Level_10_1,
                FeatureLevel.Level_11_0,
                FeatureLevel.Level_11_1,
            };

            d3dDevice = new D3D11.Device(DriverType.Hardware, D3D11.DeviceCreationFlags.Debug, levels);

            DXGI.ModeDescription backBufferDesc = new DXGI.ModeDescription()
            {
                Width            = width,
                Height           = height,
                Format           = BackBufferFormat,
                RefreshRate      = new DXGI.Rational(60, 1),
                Scaling          = DXGI.DisplayModeScaling.Unspecified,
                ScanlineOrdering = DXGI.DisplayModeScanlineOrder.Progressive,
            };

            DXGI.SwapChainDescription swapChainDesc = new DXGI.SwapChainDescription()
            {
                BufferCount     = 1,
                Flags           = DXGI.SwapChainFlags.None,
                IsWindowed      = !deviceDescription.Fullcreen,
                ModeDescription = backBufferDesc,
                OutputHandle    = renderControl.Handle,
                SwapEffect      = deviceDescription.SwapEffect,
                Usage           = DXGI.Usage.RenderTargetOutput,
            };

            switch (deviceDescription.MultiSampleCount)
            {
            case MultiSampleType.MSAA1:
                swapChainDesc.SampleDescription = new DXGI.SampleDescription(1, deviceDescription.MultiSampleQuality);
                break;

            case MultiSampleType.MSAA2:
                swapChainDesc.SampleDescription = new DXGI.SampleDescription(2, deviceDescription.MultiSampleQuality);
                break;

            case MultiSampleType.MSAA4:
                swapChainDesc.SampleDescription = new DXGI.SampleDescription(4, deviceDescription.MultiSampleQuality);
                break;

            case MultiSampleType.MSAA8:
                swapChainDesc.SampleDescription = new DXGI.SampleDescription(8, deviceDescription.MultiSampleQuality);
                break;

            case MultiSampleType.MSAA16:
                swapChainDesc.SampleDescription = new DXGI.SampleDescription(16, deviceDescription.MultiSampleQuality);
                break;

            case MultiSampleType.Unknown:
                var samples = SharpDXDevice.CheckMultiSample();
                if (samples == null)
                {
                    throw new Exception(MethodBase.GetCurrentMethod().Name +
                                        " Because the MultiSampleCount parameter is [Unknown], the device could not determine the parameter automatically");
                }
                swapChainDesc.SampleDescription = samples.Last();
                break;

            default:
                throw new System.ComponentModel.InvalidEnumArgumentException("deviceDescription.MultiSampleCount",
                                                                             (int)deviceDescription.MultiSampleCount, typeof(MultiSampleType));
            }

            DXGI.Device  device  = d3dDevice.QueryInterface <DXGI.Device>();
            DXGI.Adapter adapter = device.GetParent <DXGI.Adapter>();
            DXGI.Factory factory = adapter.GetParent <DXGI.Factory>();

            swapChain = new DXGI.SwapChain(factory, d3dDevice, swapChainDesc);

            d3dContext = d3dDevice.ImmediateContext;

            D3D11.RasterizerStateDescription rasterDesc = new D3D11.RasterizerStateDescription()
            {
                CullMode = D3D11.CullMode.Back,
                FillMode = D3D11.FillMode.Solid,
                IsAntialiasedLineEnabled = true,
                IsMultisampleEnabled     = true,
                IsDepthClipEnabled       = true,
            };

            viewport = new Viewport(0, 0, width, height);

            this.SetRasterizerState(rasterDesc);
            d3dRenderTarget = CreateRenderTarget();
            d3dDepthStencil = CreateDepthStencil();
        }
コード例 #34
0
ファイル: Framework.cs プロジェクト: sinushawa/ROD
        public Framework(string title, int width, int height, bool depth, bool stencil, bool _VSync)
        {
            // Create the display to display on
            Window = new Form()
            {
                StartPosition = FormStartPosition.CenterScreen,
                ClientSize = new Size(width, height),
                Text = title,
                TopMost = true,
            };
            Window.StartPosition = FormStartPosition.Manual;
            Window.Location = new Point(1100, 80);
            Window.FormBorderStyle = FormBorderStyle.Fixed3D;
            Window.WindowState =FormWindowState.Normal;
            Window.CreateControl();
            VerticalSyncEnabled = _VSync;
            CreateDevice();

            // Create a description of the display mode
            var modeDescription = new ModeDescription()
            {
                Format = Format.R8G8B8A8_UNorm,
                RefreshRate = new Rational(60, 1),
                Scaling = DisplayModeScaling.Unspecified,
                ScanlineOrdering = DisplayModeScanlineOrder.Unspecified,
                Width = width,
                Height = height,
            };

            // Create a description of the sampling for multisampling or antialiasing
            var sampleDescription = new SampleDescription()
            {
                Count = 1,
                Quality = 0,
            };

            // Create a description of the swap chain or front and back buffers
            var swapDescription = new SwapChainDescription()
            {
                ModeDescription = modeDescription,
                SampleDescription = sampleDescription,
                BufferCount = 1,
                Flags = SwapChainFlags.None,
                IsWindowed = true,
                OutputHandle = Window.Handle,
                SwapEffect = SwapEffect.Discard,
                Usage = Usage.RenderTargetOutput,
            };

            // Create the DirectX 11 Device
            SharpDX.Direct3D11.Device.CreateWithSwapChain(SharpDX.Direct3D.DriverType.Hardware, DeviceCreationFlags.BgraSupport|DeviceCreationFlags.Debug, swapDescription, out Device, out swapChain);

            DContext = Device.ImmediateContext;
            // Create the factory which manages general graphics resources
            // Ignore all windows events
            Factory = swapChain.GetParent<Factory>();
            Factory.MakeWindowAssociation(Window.Handle, WindowAssociationFlags.IgnoreAll);
            Factory.Dispose();
            // New RenderTargetView from the backbuffer
            var backBuffer = Texture2D.FromSwapChain<Texture2D>(swapChain, 0);
            RenderTargetView = new RenderTargetView(Device, backBuffer);
            RenderTargetView.DebugName = "std";
            // Release pointer to the back buffer as we no longer need it.
            backBuffer.Dispose();

            frame_width=Window.ClientSize.Width;
            frame_height=Window.ClientSize.Height;

            #region Zdepth
            if (depth || stencil)
            {
                _depth=true;
                var textureDescription = new Texture2DDescription()
                {
                    Width = frame_width,
                    Height = frame_height,
                    MipLevels = 1,
                    ArraySize = 1,
                    Format = (stencil) ? Format.D32_Float : Format.D24_UNorm_S8_UInt,
                    SampleDescription = sampleDescription,
                    Usage = ResourceUsage.Default,
                    BindFlags = BindFlags.DepthStencil,
                    CpuAccessFlags = CpuAccessFlags.None,
                    OptionFlags = ResourceOptionFlags.None,
                };

                var texture = new Texture2D(Device, textureDescription);

                var depthStencilViewDescription = new DepthStencilViewDescription()
                {
                    Format = textureDescription.Format,
                    Dimension = DepthStencilViewDimension.Texture2DMultisampled
                };

                DepthStencilView = new DepthStencilView(Device, texture, depthStencilViewDescription);
                DContext.OutputMerger.SetTargets(DepthStencilView, RenderTargetView);
            }
            else
            {
                DContext.OutputMerger.SetTargets(RenderTargetView);
            }

            if (depth && !stencil)
                depthStencilClear = DepthStencilClearFlags.Depth;
            else if (stencil && !depth)
                depthStencilClear = DepthStencilClearFlags.Stencil;
            else if (stencil && depth)
                depthStencilClear = DepthStencilClearFlags.Stencil | DepthStencilClearFlags.Depth;
            #endregion

            #region Rasterizer
            RasterizerStateDescription RAS = new RasterizerStateDescription();
            RAS.IsMultisampleEnabled = true; //important for AA
            RAS.CullMode = CullMode.Back;
            RAS.DepthBias = 0;
            RAS.DepthBiasClamp = 0.0f;
            RAS.FillMode = FillMode.Solid;
            RAS.IsDepthClipEnabled = false;
            RAS.IsFrontCounterClockwise = true;
            DContext.Rasterizer.State = new RasterizerState(Device, RAS);
            #endregion

            // Setup the camera viewport
            var viewport = new Viewport()
            {
                TopLeftX = 0,
                TopLeftY = 0,
                Width = width,
                Height = height,
                MinDepth = 0.0f,
                MaxDepth = 1.0f,
            };
            DContext.Rasterizer.SetViewports(viewport);

            Stopwatch = new Stopwatch();
        }
コード例 #35
0
        public override void Initialize()
        {
            Form.SizeChanged += (o, args) =>
            {
                if (_swapChain == null)
                    return;

                renderView.Dispose();
                depthView.Dispose();
                DisposeBuffers();

                if (Form.WindowState == FormWindowState.Minimized)
                    return;

                _width = Form.ClientSize.Width;
                _height = Form.ClientSize.Height;
                _swapChain.ResizeBuffers(_swapChain.Description.BufferCount, 0, 0, Format.Unknown, 0);

                CreateBuffers();
                SetSceneConstants();
            };

            _width = 1024;
            _height = 768;
            _nearPlane = 1.0f;

            ambient = new Color4(Color.Gray.ToArgb());

            try
            {
                OnInitializeDevice();
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString(), "Could not create DirectX 11 device.");
                return;
            }

            // shader.fx

            const ShaderFlags shaderFlags = ShaderFlags.None;
            //const ShaderFlags shaderFlags = ShaderFlags.Debug | ShaderFlags.SkipOptimization;
            ShaderBytecode shaderByteCode = LoadShader("shader.fx", shaderFlags);

            effect = new Effect(_device, shaderByteCode);
            EffectTechnique technique = effect.GetTechniqueByIndex(0);
            shadowGenPass = technique.GetPassByIndex(0);
            gBufferGenPass = technique.GetPassByIndex(1);
            debugDrawPass = technique.GetPassByName("debug");

            BufferDescription sceneConstantsDesc = new BufferDescription()
            {
                SizeInBytes = Marshal.SizeOf(typeof(ShaderSceneConstants)),
                Usage = ResourceUsage.Dynamic,
                BindFlags = BindFlags.ConstantBuffer,
                CpuAccessFlags = CpuAccessFlags.Write,
                OptionFlags = ResourceOptionFlags.None
            };

            sceneConstantsBuffer = new Buffer(_device, sceneConstantsDesc);
            EffectConstantBuffer effectConstantBuffer = effect.GetConstantBufferByName("scene");
            effectConstantBuffer.SetConstantBuffer(sceneConstantsBuffer);

            RasterizerStateDescription desc = new RasterizerStateDescription()
            {
                CullMode = CullMode.None,
                FillMode = FillMode.Solid,
                IsFrontCounterClockwise = true,
                DepthBias = 0,
                DepthBiasClamp = 0,
                SlopeScaledDepthBias = 0,
                IsDepthClipEnabled = true,
            };
            _immediateContext.Rasterizer.State = new RasterizerState(_device, desc);

            DepthStencilStateDescription depthDesc = new DepthStencilStateDescription()
            {
                IsDepthEnabled = true,
                IsStencilEnabled = false,
                DepthWriteMask = DepthWriteMask.All,
                DepthComparison = Comparison.Less
            };
            depthStencilState = new DepthStencilState(_device, depthDesc);

            DepthStencilStateDescription lightDepthStateDesc = new DepthStencilStateDescription()
            {
                IsDepthEnabled = true,
                IsStencilEnabled = false,
                DepthWriteMask = DepthWriteMask.All,
                DepthComparison = Comparison.Less
            };
            lightDepthStencilState = new DepthStencilState(_device, lightDepthStateDesc);

            // grender.fx

            shaderByteCode = LoadShader("grender.fx", shaderFlags);

            effect2 = new Effect(_device, shaderByteCode);
            technique = effect2.GetTechniqueByIndex(0);
            gBufferRenderPass = technique.GetPassByIndex(0);
            gBufferOverlayPass = technique.GetPassByIndex(1);

            info = new InfoText(_device);
            _meshFactory = new MeshFactory(this);
            MeshFactory = _meshFactory;

            CreateBuffers();
            LibraryManager.LibraryStarted();
        }
コード例 #36
0
ファイル: RaterizerState.cs プロジェクト: alexey-bez/SharpDX
 /// <summary>	
 /// <p>Create a rasterizer state object that tells the rasterizer stage how to behave.</p>	
 /// </summary>	
 /// <param name = "device">The device with which to associate the state object.</param>
 /// <param name="description">A rasterizer state description</param>	
 /// <remarks>	
 /// <p>4096 unique rasterizer state objects can be created on a device at a time.</p><p>If an application attempts to create a rasterizer-state interface with the same state as an existing interface, the same interface will be returned and the total number of unique rasterizer state objects will stay the same.</p>	
 /// </remarks>	
 /// <msdn-id>ff476516</msdn-id>	
 /// <unmanaged>HRESULT ID3D11Device::CreateRasterizerState([In] const D3D11_RASTERIZER_DESC* pRasterizerDesc,[Out, Fast] ID3D11RasterizerState** ppRasterizerState)</unmanaged>	
 /// <unmanaged-short>ID3D11Device::CreateRasterizerState</unmanaged-short>	
 public RasterizerState(Device device, RasterizerStateDescription description)
     : base(IntPtr.Zero)
 {
     device.CreateRasterizerState(ref description, this);
 }
コード例 #37
0
        public DepthAndColorShader(Device device)
        {
            shaderByteCode = new ShaderBytecode(File.ReadAllBytes("Content/DepthAndColorFloatVS.cso"));
            depthAndColorVS = new VertexShader(device, shaderByteCode);
            depthAndColorGS = new GeometryShader(device, new ShaderBytecode(File.ReadAllBytes("Content/DepthAndColorGS.cso")));
            depthAndColorPS = new PixelShader(device, new ShaderBytecode(File.ReadAllBytes("Content/DepthAndColorPS.cso")));

            // depth stencil state
            var depthStencilStateDesc = new DepthStencilStateDescription()
            {
                IsDepthEnabled = true,
                DepthWriteMask = DepthWriteMask.All,
                DepthComparison = Comparison.LessEqual,
                IsStencilEnabled = false,
            };
            depthStencilState = new DepthStencilState(device, depthStencilStateDesc);

            // rasterizer state
            var rasterizerStateDesc = new RasterizerStateDescription()
            {
                CullMode = CullMode.None,
                FillMode = FillMode.Solid,
                IsDepthClipEnabled = true,
                IsFrontCounterClockwise = true,
                IsMultisampleEnabled = true,
            };
            rasterizerState = new RasterizerState(device, rasterizerStateDesc);

            // color sampler state
            var colorSamplerStateDesc = new SamplerStateDescription()
            {
                Filter = Filter.MinMagMipLinear,
                AddressU = TextureAddressMode.Border,
                AddressV = TextureAddressMode.Border,
                AddressW = TextureAddressMode.Border,
                //BorderColor = new SharpDX.Color4(0.5f, 0.5f, 0.5f, 1.0f),
                BorderColor = new SharpDX.Color4(0, 0, 0, 1.0f),
            };
            colorSamplerState = new SamplerState(device, colorSamplerStateDesc);

            //// Kinect depth image
            //var depthImageTextureDesc = new Texture2DDescription()
            //{
            //    Width = depthImageWidth,
            //    Height = depthImageHeight,
            //    MipLevels = 1,
            //    ArraySize = 1,
            //    Format = SharpDX.DXGI.Format.R16_UInt, // R32_Float
            //    SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0),
            //    Usage = ResourceUsage.Dynamic,
            //    BindFlags = BindFlags.ShaderResource,
            //    CpuAccessFlags = CpuAccessFlags.Write,
            //};
            //depthImageTexture = new Texture2D(device, depthImageTextureDesc);
            //depthImageTextureRV = new ShaderResourceView(device, depthImageTexture);

            // filtered depth image
            var filteredDepthImageTextureDesc = new Texture2DDescription()
            {
                Width = Kinect2Calibration.depthImageWidth * 3,
                Height = Kinect2Calibration.depthImageHeight * 3,
                MipLevels = 1,
                ArraySize = 1,
                Format = SharpDX.DXGI.Format.R32G32_Float,
                SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0),
                Usage = ResourceUsage.Default,
                BindFlags = BindFlags.RenderTarget | BindFlags.ShaderResource,
                CpuAccessFlags = CpuAccessFlags.None,
            };
            filteredDepthImageTexture = new Texture2D(device, filteredDepthImageTextureDesc);
            filteredRenderTargetView = new RenderTargetView(device, filteredDepthImageTexture);
            filteredDepthImageSRV = new ShaderResourceView(device, filteredDepthImageTexture);

            filteredDepthImageTexture2 = new Texture2D(device, filteredDepthImageTextureDesc);
            filteredRenderTargetView2 = new RenderTargetView(device, filteredDepthImageTexture2);
            filteredDepthImageSRV2 = new ShaderResourceView(device, filteredDepthImageTexture2);

            //// Kinect color image
            //var colorImageStagingTextureDesc = new Texture2DDescription()
            //{
            //    Width = colorImageWidth,
            //    Height = colorImageHeight,
            //    MipLevels = 1,
            //    ArraySize = 1,
            //    Format = SharpDX.DXGI.Format.B8G8R8A8_UNorm,
            //    //Format = SharpDX.DXGI.Format.YUY2
            //    SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0),
            //    Usage = ResourceUsage.Dynamic,
            //    BindFlags = BindFlags.ShaderResource,
            //    CpuAccessFlags = CpuAccessFlags.Write
            //};
            //colorImageStagingTexture = new Texture2D(device, colorImageStagingTextureDesc);

            //var colorImageTextureDesc = new Texture2DDescription()
            //{
            //    Width = colorImageWidth,
            //    Height = colorImageHeight,
            //    MipLevels = 0,
            //    ArraySize = 1,
            //    Format = SharpDX.DXGI.Format.B8G8R8A8_UNorm,
            //    SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0),
            //    Usage = ResourceUsage.Default,
            //    BindFlags = BindFlags.ShaderResource | BindFlags.RenderTarget,
            //    CpuAccessFlags = CpuAccessFlags.None,
            //    OptionFlags = ResourceOptionFlags.GenerateMipMaps
            //};
            //colorImageTexture = new Texture2D(device, colorImageTextureDesc);
            //colorImageTextureRV = new ShaderResourceView(device, colorImageTexture);

            // constant buffer
            var constantBufferDesc = new BufferDescription()
            {
                Usage = ResourceUsage.Dynamic,
                BindFlags = BindFlags.ConstantBuffer,
                SizeInBytes = ConstantBuffer.size,
                CpuAccessFlags = CpuAccessFlags.Write,
                StructureByteStride = 0,
                OptionFlags = 0,
            };
            constantBuffer = new SharpDX.Direct3D11.Buffer(device, constantBufferDesc);

            bilateralFilter = new BilateralFilter(device, Kinect2Calibration.depthImageWidth, Kinect2Calibration.depthImageHeight);

            vertexInputLayout = new InputLayout(device, shaderByteCode.Data, new[]
            {
                new InputElement("SV_POSITION", 0, Format.R32G32B32A32_Float, 0, 0),
            });
        }
コード例 #38
0
        public override void Run()
        {
            #region Create renderers

            // Note: the renderers take care of creating their own
            // device resources and listen for DeviceManager.OnInitialize

            // Create a axis-grid renderer
            var axisGrid = ToDispose(new AxisGridRenderer());
            axisGrid.Initialize(this);

            //// Create and initialize the mesh renderer
            //var loadedMesh = Common.Mesh.LoadFromFile("frog.cmo");
            var loadedMesh = Common.Mesh.LoadFromFile("Character.cmo");
            loadedMesh.AddRange(Common.Mesh.LoadFromFile("frog.cmo"));
            List<TessellatedMeshRenderer> meshes = new List<TessellatedMeshRenderer>();
            meshes.AddRange((from mesh in loadedMesh
                             select ToDispose(new TessellatedMeshRenderer(mesh))));
            foreach (var m in meshes) {
                m.Initialize(this);
                m.World = Matrix.Identity;
            }

            // Set the first animation as the current animation and start clock
            foreach (var m in meshes)
            {
                if (m.Mesh.Animations != null && m.Mesh.Animations.Any())
                    m.CurrentAnimation = m.Mesh.Animations.First().Value;
                m.Clock.Start();
            }

            var triangle = new TriangleRenderer();
            triangle.Initialize(this);

            // Create and initialize a Direct2D FPS text renderer
            var fps = ToDispose(new Common.FpsRenderer("Calibri", Color.CornflowerBlue, new Point(8, 8), 16));
            fps.Initialize(this);

            // Create and initialize a general purpose Direct2D text renderer
            // This will display some instructions and the current view and rotation offsets
            var textRenderer = ToDispose(new Common.TextRenderer("Calibri", Color.CornflowerBlue, new Point(8, 40), 12));
            textRenderer.Initialize(this);

            #endregion

            // Initialize the world matrix
            var worldMatrix = Matrix.Identity;

            // Set the camera position
            var cameraPosition = new Vector3(0, 0, 2);
            var cameraTarget = Vector3.Zero; // Looking at the origin 0,0,0
            var cameraUp = Vector3.UnitY; // Y+ is Up

            // Prepare matrices
            // Create the view matrix from our camera position, look target and up direction
            var viewMatrix = Matrix.LookAtRH(cameraPosition, cameraTarget, cameraUp);
            viewMatrix.TranslationVector += new Vector3(0, -0.98f, 0);

            // Create the projection matrix
            /* FoV 60degrees = Pi/3 radians */
            // Aspect ratio (based on window size), Near clip, Far clip
            var projectionMatrix = Matrix.PerspectiveFovRH((float)Math.PI / 3f, Width / (float)Height, 0.1f, 100f);

            // Maintain the correct aspect ratio on resize
            Window.Resize += (s, e) =>
            {
                projectionMatrix = Matrix.PerspectiveFovRH((float)Math.PI / 3f, Width / (float)Height, 0.1f, 100f);
            };

            #region Rotation and window event handlers

            // Create a rotation vector to keep track of the rotation
            // around each of the axes
            var rotation = new Vector3(0.0f, 0.0f, 0.0f);
            var tessellationFactor = 1f;
            var tessellationPartition = "Integer";
            var tessellationMethod = "Phong";
            // We will call this action to update text
            // for the text renderer
            Action updateText = () =>
            {
                textRenderer.Text =
                    String.Format("Tessellation Factor: {0:#0.0} (+/- to change)"
                    + "\nPartitioning: {1} (F1,F2,F3,F4 to change)"
                    + "\nTessellation: {2} (F5,F6,F7)"
                    + "\nPress F to toggle wireframe | N show normals"
                    + "\nPress 1,2,3,4,5,6,7,8 to switch shaders",
                        tessellationFactor,
                        tessellationPartition,
                        tessellationMethod,
                        DeviceManager.Direct3DDevice.NativePointer);
            };

            Dictionary<Keys, bool> keyToggles = new Dictionary<Keys, bool>();
            keyToggles[Keys.Z] = false;
            keyToggles[Keys.F] = false;

            // Support keyboard/mouse input to rotate or move camera view
            var moveFactor = 0.02f; // how much to change on each keypress
            var shiftKey = false;
            var ctrlKey = false;
            var background = Color.White;
            var activeTriTessellator = tessellateTriIntegerShader;
            var activePnTriTessellator = pnTriIntegerShader;
            var usePhongTessellation = true;
            var usePNTessellation = false;
            var showNormals = false;
            var meshIndex = 0;
            Window.KeyDown += (s, e) =>
            {
                var context = DeviceManager.Direct3DContext;

                shiftKey = e.Shift;
                ctrlKey = e.Control;

                switch (e.KeyCode)
                {
                    // WASD -> pans view
                    case Keys.A:
                        viewMatrix.TranslationVector += new Vector3(moveFactor * 2, 0f, 0f);
                        break;
                    case Keys.D:
                        viewMatrix.TranslationVector -= new Vector3(moveFactor * 2, 0f, 0f);
                        break;
                    case Keys.S:
                        if (shiftKey)
                            viewMatrix.TranslationVector += new Vector3(0f, moveFactor * 2, 0f);
                        else
                            viewMatrix.TranslationVector -= new Vector3(0f, 0f, 1) * moveFactor * 2;
                        break;
                    case Keys.W:
                        if (shiftKey)
                            viewMatrix.TranslationVector -= new Vector3(0f, moveFactor * 2, 0f);
                        else
                            viewMatrix.TranslationVector += new Vector3(0f, 0f, 1) * moveFactor * 2;
                        break;
                    // Up/Down and Left/Right - rotates around X / Y respectively
                    // (Mouse wheel rotates around Z)
                    case Keys.Down:
                        worldMatrix *= Matrix.RotationX(moveFactor);
                        rotation += new Vector3(moveFactor, 0f, 0f);
                        break;
                    case Keys.Up:
                        worldMatrix *= Matrix.RotationX(-moveFactor);
                        rotation -= new Vector3(moveFactor, 0f, 0f);
                        break;
                    case Keys.Left:
                        worldMatrix *= Matrix.RotationY(moveFactor);
                        rotation += new Vector3(0f, moveFactor, 0f);
                        break;
                    case Keys.Right:
                        worldMatrix *= Matrix.RotationY(-moveFactor);
                        rotation -= new Vector3(0f, moveFactor, 0f);
                        break;
                    case Keys.T:
                        fps.Show = !fps.Show;
                        textRenderer.Show = !textRenderer.Show;
                        break;
                    case Keys.B:
                        if (background == Color.White)
                        {
                            background = new Color(30, 30, 34);
                        }
                        else
                        {
                            background = Color.White;
                        }
                        break;
                    case Keys.G:
                        axisGrid.Show = !axisGrid.Show;
                        break;
                    case Keys.P:
                        // Pause or resume mesh animation
                        meshes.ForEach(m => {
                            if (m.Clock.IsRunning)
                                m.Clock.Stop();
                            else
                                m.Clock.Start();
                        });
                        break;
                    case Keys.X:
                        // To test for correct resource recreation
                        // Simulate device reset or lost.
                        System.Diagnostics.Debug.WriteLine(SharpDX.Diagnostics.ObjectTracker.ReportActiveObjects());
                        DeviceManager.Initialize(DeviceManager.Dpi);
                        System.Diagnostics.Debug.WriteLine(SharpDX.Diagnostics.ObjectTracker.ReportActiveObjects());
                        break;
                    case Keys.Z:
                        keyToggles[Keys.Z] = !keyToggles[Keys.Z];
                        if (keyToggles[Keys.Z])
                        {
                            context.PixelShader.Set(depthPixelShader);
                        }
                        else
                        {
                            context.PixelShader.Set(pixelShader);
                        }
                        break;
                    case Keys.F:
                        keyToggles[Keys.F] = !keyToggles[Keys.F];
                        RasterizerStateDescription rasterDesc;
                        if (context.Rasterizer.State != null)
                            rasterDesc = context.Rasterizer.State.Description;
                        else
                            rasterDesc = new RasterizerStateDescription()
                            {
                                CullMode = CullMode.None,
                                FillMode = FillMode.Solid
                            };
                        if (keyToggles[Keys.F])
                        {
                            rasterDesc.FillMode = FillMode.Wireframe;
                            context.Rasterizer.State = ToDispose(new RasterizerState(context.Device, rasterDesc));
                        }
                        else
                        {
                            rasterDesc.FillMode = FillMode.Solid;
                            context.Rasterizer.State = ToDispose(new RasterizerState(context.Device, rasterDesc));
                        }
                        break;
                    case Keys.N:
                        showNormals = !showNormals;
                        break;
                    case Keys.D1:
                        context.PixelShader.Set(pixelShader);
                        break;
                    case Keys.D2:
                        context.PixelShader.Set(lambertShader);
                        break;
                    case Keys.D3:
                        context.PixelShader.Set(phongShader);
                        break;
                    case Keys.D4:
                        context.PixelShader.Set(blinnPhongShader);
                        break;
                    case Keys.Add:
                        var multiple = 1.0f;
                        if (ctrlKey)
                            multiple = 3.0f;
                        tessellationFactor += 0.2f * multiple;
                        tessellationFactor = Math.Min(tessellationFactor, 64);
                        break;
                    case Keys.Subtract:
                        multiple = 1.0f;
                        if (ctrlKey)
                            multiple = 3.0f;
                        tessellationFactor -= 0.2f * multiple;
                        tessellationFactor = Math.Max(tessellationFactor, 0);
                        break;
                    case Keys.F1:
                        tessellationPartition = "Integer";
                        activeTriTessellator = tessellateTriIntegerShader;
                        activePnTriTessellator = pnTriIntegerShader;
                        break;
                    case Keys.F2:
                        tessellationPartition = "Pow2";
                        activeTriTessellator = tessellateTriPow2Shader;
                        activePnTriTessellator = pnTriPow2Shader;
                        break;
                    case Keys.F3:
                        tessellationPartition = "Fractional Even";
                        activeTriTessellator = tessellateTriFractionalEvenShader;
                        activePnTriTessellator = pnTriFractionalEvenShader;
                        break;
                    case Keys.F4:
                        tessellationPartition = "Fractional Odd";
                        activeTriTessellator = tessellateTriFractionalOddShader;
                        activePnTriTessellator = pnTriFractionalOddShader;
                        break;
                    case Keys.F5:
                        usePhongTessellation = false;
                        usePNTessellation = false;
                        tessellationMethod = "Tri";
                        break;
                    case Keys.F6:
                        usePhongTessellation = true;
                        usePNTessellation = false;
                        tessellationMethod = "Phong";
                        break;
                    case Keys.F7:
                        usePhongTessellation = false;
                        usePNTessellation = true;
                        tessellationMethod = "PN-Triangle";
                        break;
                    case Keys.Back:
                        meshIndex = (meshIndex + 1) % meshes.Count;
                        break;
                }

                updateText();
            };
            Window.KeyUp += (s, e) =>
            {
                // Clear the shift/ctrl keys so they aren't sticky
                if (e.KeyCode == Keys.ShiftKey)
                    shiftKey = false;
                if (e.KeyCode == Keys.ControlKey)
                    ctrlKey = false;
            };
            Window.MouseWheel += (s, e) =>
            {
                if (shiftKey)
                {
                    // Zoom in/out
                    viewMatrix.TranslationVector += new Vector3(0f, 0f, (e.Delta / 120f) * moveFactor * 2);
                }
                else
                {
                    // rotate around Z-axis
                    viewMatrix *= Matrix.RotationZ((e.Delta / 120f) * moveFactor);
                    rotation += new Vector3(0f, 0f, (e.Delta / 120f) * moveFactor);
                }
                updateText();
            };

            var lastX = 0;
            var lastY = 0;

            Window.MouseDown += (s, e) =>
            {
                if (e.Button == MouseButtons.Left)
                {
                    lastX = e.X;
                    lastY = e.Y;
                }
            };

            Window.MouseMove += (s, e) =>
            {
                if (e.Button == MouseButtons.Left)
                {
                    var yRotate = lastX - e.X;
                    var xRotate = lastY - e.Y;
                    lastY = e.Y;
                    lastX = e.X;

                    // Mouse move changes
                    viewMatrix *= Matrix.RotationX(-xRotate * moveFactor);
                    viewMatrix *= Matrix.RotationY(-yRotate * moveFactor);

                    updateText();
                }
            };

            // Display instructions with initial values
            updateText();

            #endregion

            var clock = new System.Diagnostics.Stopwatch();
            clock.Start();

            #region Render loop

            // Create and run the render loop
            RenderLoop.Run(Window, () =>
            {
                // Start of frame:

                // Retrieve immediate context
                var context = DeviceManager.Direct3DContext;

                // Clear depth stencil view
                context.ClearDepthStencilView(DepthStencilView, DepthStencilClearFlags.Depth | DepthStencilClearFlags.Stencil, 1.0f, 0);
                // Clear render target view
                context.ClearRenderTargetView(RenderTargetView, background);

                // Create viewProjection matrix
                var viewProjection = Matrix.Multiply(viewMatrix, projectionMatrix);

                // Extract camera position from view
                var camPosition = Matrix.Transpose(Matrix.Invert(viewMatrix)).Column4;
                cameraPosition = new Vector3(camPosition.X, camPosition.Y, camPosition.Z);

                // If Keys.CtrlKey is down, auto rotate viewProjection based on time
                var time = clock.ElapsedMilliseconds / 1000.0f;

                var perFrame = new ConstantBuffers.PerFrame();
                perFrame.Light.Color = new Color(0.8f, 0.8f, 0.8f, 1.0f);
                var lightDir = Vector3.Transform(new Vector3(1f, -1f, -1f), worldMatrix);
                perFrame.Light.Direction = new Vector3(lightDir.X, lightDir.Y, lightDir.Z);// new Vector3(Vector3.Transform(new Vector3(1f, -1f, 1f), worldMatrix * worldRotation).ToArray().Take(3).ToArray());
                perFrame.CameraPosition = cameraPosition;
                perFrame.TessellationFactor = tessellationFactor;
                context.UpdateSubresource(ref perFrame, perFrameBuffer);

                // Render each object

                var perMaterial = new ConstantBuffers.PerMaterial();
                perMaterial.Ambient = new Color4(0.2f);
                perMaterial.Diffuse = Color.White;
                perMaterial.Emissive = new Color4(0);
                perMaterial.Specular = Color.White;
                perMaterial.SpecularPower = 20f;
                perMaterial.HasTexture = 0;
                perMaterial.UVTransform = Matrix.Identity;
                context.UpdateSubresource(ref perMaterial, perMaterialBuffer);

                var perObject = new ConstantBuffers.PerObject();

                // MESH
                context.VertexShader.Set(tessellateVertexShader);
                context.HullShader.Set(activeTriTessellator);
                if (usePhongTessellation)
                {
                    context.DomainShader.Set(tessellatePhongDomainShader);
                }
                else if (usePNTessellation)
                {
                    context.HullShader.Set(activePnTriTessellator);
                    context.DomainShader.Set(pnTriDomainShader);
                }
                else
                    context.DomainShader.Set(tessellateTriDomainShader);

                var m = meshes[meshIndex];
                //meshes.ForEach((m) =>
                //{
                // Provide the material constant buffer to the mesh renderer
                perObject.World = m.World * worldMatrix;
                perObject.WorldInverseTranspose = Matrix.Transpose(Matrix.Invert(perObject.World));
                perObject.WorldViewProjection = perObject.World * viewProjection;
                perObject.ViewProjection = viewProjection;
                perObject.Transpose();
                context.UpdateSubresource(ref perObject, perObjectBuffer);
                m.PerMaterialBuffer = perMaterialBuffer;
                m.PerArmatureBuffer = perArmatureBuffer;
                m.Render();

                if (showNormals)
                {
                    using (var prevPixelShader = context.PixelShader.Get())
                    {
                        perMaterial.HasTexture = 0;
                        perMaterial.UVTransform = Matrix.Identity;
                        context.UpdateSubresource(ref perMaterial, perMaterialBuffer);
                        context.PixelShader.Set(pixelShader);

                        context.GeometryShader.Set(debugNormals);

                        m.Render();

                        context.PixelShader.Set(prevPixelShader);
                        context.GeometryShader.Set(null);
                    }
                }

                //});

                // TRIANGLE
                //triangle.Render();

                //// QUAD
                //context.VertexShader.Set(tessellateVertexShader);
                //context.HullShader.Set(activeQuadTessellator);
                //context.DomainShader.Set(tessellateQuadDomainShader);

                //quad.Render();

                // BEZIER
                //context.VertexShader.Set(tessellateVertexShader);
                //context.HullShader.Set(activeBezierTessellator);
                //context.DomainShader.Set(tessellateBezierDomainShader);

                //bezier.Render();

                // AXIS GRID
                context.VertexShader.Set(vertexShader);
                context.HullShader.Set(null);
                context.DomainShader.Set(null);
                context.GeometryShader.Set(null);

                using (var prevPixelShader = context.PixelShader.Get())
                {
                    perMaterial.HasTexture = 0;
                    perMaterial.UVTransform = Matrix.Identity;
                    context.UpdateSubresource(ref perMaterial, perMaterialBuffer);
                    context.PixelShader.Set(pixelShader);
                    perObject = new ConstantBuffers.PerObject();
                    perObject.World = worldMatrix;
                    perObject.WorldInverseTranspose = Matrix.Transpose(Matrix.Invert(perObject.World));
                    perObject.WorldViewProjection = perObject.World * viewProjection;
                    perObject.ViewProjection = viewProjection;
                    perObject.Transpose();
                    context.UpdateSubresource(ref perObject, perObjectBuffer);
                    axisGrid.Render();
                    context.PixelShader.Set(prevPixelShader);
                }

                // Render FPS
                fps.Render();

                // Render instructions + position changes
                textRenderer.Render();

                // Present the frame
                Present();
            });
            #endregion
        }
コード例 #39
0
        private static void UpdateSceneFrame()
        {
            var desc = new RasterizerStateDescription();
            desc.FillMode = FillMode.Solid;
            desc.CullMode = CullMode.None;
            desc.IsFrontCounterClockwise = true;

            desc.DepthBias = 25000;
            desc.DepthBiasClamp = 2;
            desc.SlopeScaledDepthBias = 1;

            MyPipelineStates.Modify(m_shadowRasterizerState, desc);


            MyMeshes.Load();
            QueryTexturesFromEntities();
            MyTextures.Load();
            GatherTextures();
            MyComponents.UpdateCullProxies();
            MyComponents.ProcessEntities();
            MyComponents.SendVisible();

            MyBillboardRenderer.OnFrameStart();

            MyRender11.GetRenderProfiler().StartProfilingBlock("RebuildProxies");
            foreach (var renderable in MyComponentFactory<MyRenderableComponent>.GetAll())
            {
                renderable.RebuildRenderProxies();
            }
            MyRender11.GetRenderProfiler().EndProfilingBlock();

            MyRender11.GetRenderProfiler().StartProfilingBlock("UpdateProxies");
            UpdateActors();
            MyRender11.GetRenderProfiler().EndProfilingBlock();

            MyBigMeshTable.Table.MoveToGPU();

            MyRender11.GetRenderProfiler().StartProfilingBlock("Update merged groups");
            MyRender11.GetRenderProfiler().StartProfilingBlock("UpdateBeforeDraw");
            foreach (var r in MyComponentFactory<MyGroupRootComponent>.GetAll())
            {
                r.UpdateBeforeDraw();
            }
            MyRender11.GetRenderProfiler().EndProfilingBlock();

            MyRender11.GetRenderProfiler().StartProfilingBlock("MoveToGPU");
            foreach (var r in MyComponentFactory<MyGroupRootComponent>.GetAll())
            {
                foreach (var val in r.m_materialGroups.Values)
                {
                    // optimize: keep list+set for updating
                    val.MoveToGPU();
                }
            }
            MyRender11.GetRenderProfiler().EndProfilingBlock();
            MyRender11.GetRenderProfiler().EndProfilingBlock();

            MyRender11.GetRenderProfiler().StartProfilingBlock("Fill foliage streams");
            MyGpuProfiler.IC_BeginBlock("Fill foliage streams");
            MyGPUFoliageGenerating.GetInstance().PerFrame();
            MyGPUFoliageGenerating.GetInstance().Begin();
            foreach (var foliage in MyComponentFactory<MyFoliageComponent>.GetAll())
            {
                if (foliage.m_owner.CalculateCameraDistance() < MyRender11.RenderSettings.FoliageDetails.GrassDrawDistance())
                {
                    foliage.FillStreams();
                }
                else
                {
                    foliage.InvalidateStreams();
                }
            }
            MyGPUFoliageGenerating.GetInstance().End();
            MyGpuProfiler.IC_EndBlock();
            MyRender11.GetRenderProfiler().EndProfilingBlock();

            MyCommon.MoveToNextFrame();
        }
コード例 #40
0
ファイル: Program.cs プロジェクト: nyx1220/sharpdx-examples
        private static void Main()
        {
            var form = new RenderForm("SharpDX - MiniTri Direct3D 11 Sample");

            // SwapChain description
            var desc = new SwapChainDescription()
                           {
                               BufferCount = 3,
                               ModeDescription=
                                   new ModeDescription(form.ClientSize.Width, form.ClientSize.Height,
                                                       new Rational(60, 1), Format.R8G8B8A8_UNorm),
                               IsWindowed = true,
                               OutputHandle = form.Handle,
                               SampleDescription = new SampleDescription(1,0),
                               SwapEffect = SwapEffect.Sequential,
                               Usage = Usage.RenderTargetOutput

                           };

            // Create Device and SwapChain
            Device device;
            SwapChain swapChain;
            Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.None, desc, out device, out swapChain);
            var context = device.ImmediateContext;

            // Ignore all windows events
            var factory = swapChain.GetParent<Factory>();
            factory.MakeWindowAssociation(form.Handle, WindowAssociationFlags.IgnoreAll);

            // New RenderTargetView from the backbuffer
            var backBuffer = Texture2D.FromSwapChain<Texture2D>(swapChain, 0);
            var renderView = new RenderTargetView(device, backBuffer);

            Texture2DDescription depthBufferDesc;
            depthBufferDesc.Width = form.Width;
            depthBufferDesc.Height = form.Height;
            depthBufferDesc.MipLevels = 1;
            depthBufferDesc.ArraySize = 1;
            depthBufferDesc.Format = Format.D24_UNorm_S8_UInt;
            depthBufferDesc.SampleDescription.Count = 1;
            depthBufferDesc.SampleDescription.Quality = 0;
            depthBufferDesc.Usage = ResourceUsage.Default;
            depthBufferDesc.BindFlags = BindFlags.DepthStencil;
            depthBufferDesc.CpuAccessFlags = CpuAccessFlags.None ;
            depthBufferDesc.OptionFlags = ResourceOptionFlags.None;

            Texture2D DepthStencilTexture = new Texture2D(device, depthBufferDesc);

            DepthStencilViewDescription depthStencilViewDesc = new DepthStencilViewDescription();
            depthStencilViewDesc.Format = Format.D24_UNorm_S8_UInt;
            depthStencilViewDesc.Dimension =  DepthStencilViewDimension.Texture2D;
            depthStencilViewDesc.Texture2D.MipSlice = 0;
            DepthStencilView depthStencilView = new DepthStencilView(device, DepthStencilTexture, depthStencilViewDesc);
            context.OutputMerger.SetTargets(depthStencilView,renderView);

            DepthStencilStateDescription depthDesc = new DepthStencilStateDescription()
            {
                IsDepthEnabled = true,
                IsStencilEnabled = false,
                DepthWriteMask = DepthWriteMask.All,
                DepthComparison = Comparison.Less
            };
            DepthStencilState depthStencilState = new DepthStencilState(device, depthDesc);

            RasterizerStateDescription rasdesc = new RasterizerStateDescription()
            {
                CullMode = CullMode.None,
                FillMode = FillMode.Solid,
                IsFrontCounterClockwise = true,
                DepthBias = 0,
                DepthBiasClamp = 0,
                SlopeScaledDepthBias = 0,
                IsDepthClipEnabled = true,
                IsMultisampleEnabled =true,
            };
            context.Rasterizer.State = new RasterizerState(device, rasdesc);

            //////////////////////////////

            var flags = (ppsteps |
                aiPostProcessSteps.aiProcess_GenSmoothNormals | // generate smooth normal vectors if not existing
                aiPostProcessSteps.aiProcess_SplitLargeMeshes | // split large, unrenderable meshes into submeshes
                aiPostProcessSteps.aiProcess_Triangulate | // triangulate polygons with more than 3 edges
                aiPostProcessSteps.aiProcess_ConvertToLeftHanded | // convert everything to D3D left handed space
                aiPostProcessSteps.aiProcess_SortByPType | // make 'clean' meshes which consist of a single typ of primitives
                (aiPostProcessSteps)0);

            // default model
            var path = @"jeep1.ms3d";

            Importer importer = new Importer();

            //var path = "man.3ds";
            aiScene scene = importer.ReadFile(path, flags);
            String directory = null;
            if (scene != null)
            {
                directory = Path.GetDirectoryName(path);
            }
            else
            {
                MessageBox.Show("Failed to open file: " + path + ". Either Assimp screwed up or the path is not valid.");
                Application.Exit();
            }

            SceneLoader SceneLoader = new SceneLoader();
            List<model> models = new List<model>();
            for (int i = 0; i < scene.mNumMeshes; i++)
            {
                models.Add(SceneLoader.CreateMesh(device, scene.mMeshes[i], scene.mMaterials,directory));
            }

            //////////////////////////////

            // Compile Vertex and Pixel shaders
            var effectByteCode = ShaderBytecode.CompileFromFile("MiniTri.fx", "fx_5_0", ShaderFlags.None, EffectFlags.None);
            var effect = new Effect(device, effectByteCode);
            var technique = effect.GetTechniqueByIndex(0);
            var pass = technique.GetPassByIndex(0);

            // Layout from VertexShader input signature
            var passSignature = pass.Description.Signature;

            // Layout from VertexShader input signature
            var layout = new InputLayout(
                device,
                passSignature,
                new[]
                    {
                        new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0),
                        new InputElement("TEXCOORD", 0, Format.R32G32_Float, 12, 0)
                    });

            // Prepare All the stages
            context.Rasterizer.SetViewports(new Viewport(0, 0, form.ClientSize.Width, form.ClientSize.Height, 0.0f, 1.0f));
            context.OutputMerger.DepthStencilState = depthStencilState;

            Input input = new Input(form);
            //FreeLook FreeLook = new SharpExamples.FreeLook(input, (float)form.Width / (float)form.Height);
            CameraFirstPerson FreeLook = new CameraFirstPerson(input, 0, 0, Vector3.Zero, form.Width, form.Height);
            //FreeLook.SetEyeTarget(new Vector3(300), Vector3.Zero);
            Clock Clock = new SharpExamples.Clock();
            Clock.Start();

            effect.GetVariableByName("projection").AsMatrix().SetMatrix(FreeLook.Projection);

            // Main loop
            RenderLoop.Run(form, () =>
                                      {
                                          foreach (var item in models)
                                          {
                                                context.InputAssembler.InputLayout = layout;
                                                context.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList;
                                                int SizeInBytes = Marshal.SizeOf(typeof(VertexPostitionTexture));
                                                context.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(item.vertex, SizeInBytes, 0));
                                                context.InputAssembler.SetIndexBuffer(item.indices, Format.R32_UInt, 0);

                                                float elapsed = Clock.Update();
                                                FreeLook.Update(elapsed);

                                                effect.GetVariableByName("view").AsMatrix().SetMatrix(FreeLook.View);
                                                effect.GetVariableByName("World").AsMatrix().SetMatrix(Matrix.Scaling(5));
                                                effect.GetVariableByName("tex0").AsShaderResource().SetResource(item.ShaderResourceView);
                                                context.ClearRenderTargetView(renderView, Colors.Black);
                                                context.ClearDepthStencilView(depthStencilView, DepthStencilClearFlags.Depth | DepthStencilClearFlags.Stencil, 1, 0);

                                                for (int i = 0; i < technique.Description.PassCount; ++i)
                                                {
                                                    pass.Apply(context);
                                                    context.DrawIndexed(item.numberIndices, 0, 0);
                                                }
                                                swapChain.Present(0, PresentFlags.None);
                                          }

                                      });

            // Release all resources
            foreach (var item in models)
            {
                item.vertex.Dispose();
                item.indices.Dispose();
                item.ShaderResourceView.Dispose();
            }

            layout.Dispose();
            renderView.Dispose();
            backBuffer.Dispose();
            context.ClearState();
            context.Flush();
            device.Dispose();
            context.Dispose();
            swapChain.Dispose();
            factory.Dispose();
        }
コード例 #41
0
ファイル: MyResource.cs プロジェクト: Krulac/SpaceEngineers
        internal static RasterizerId CreateRasterizerState(RasterizerStateDescription description)
        {
            var id = new RasterizerId { Index = RasterizerStates.Allocate() };
            MyArrayHelpers.Reserve(ref RasterizerObjects, id.Index + 1);

            RasterizerStates.Data[id.Index] = description;

            InitRasterizerState(id);
            RasterizerIndices.Add(id);

            return id;
        }
コード例 #42
0
        public FrustumShader(Device device)
        {
            // create single vertex buffer
            var stream = new DataStream(24 * VertexPosition.SizeInBytes, true, true);
            stream.Write(new Vector4(-1, -1, 0, 1));
            stream.Write(new Vector4( 1, -1, 0, 1));
            stream.Write(new Vector4( 1, -1, 0, 1));
            stream.Write(new Vector4( 1,  1, 0, 1));
            stream.Write(new Vector4( 1,  1, 0, 1));
            stream.Write(new Vector4(-1,  1, 0, 1));
            stream.Write(new Vector4(-1,  1, 0, 1));
            stream.Write(new Vector4(-1, -1, 0, 1));

            stream.Write(new Vector4(-1, -1, maxZ, 1));
            stream.Write(new Vector4( 1, -1, maxZ, 1));
            stream.Write(new Vector4( 1, -1, maxZ, 1));
            stream.Write(new Vector4( 1,  1, maxZ, 1));
            stream.Write(new Vector4( 1,  1, maxZ, 1));
            stream.Write(new Vector4(-1,  1, maxZ, 1));
            stream.Write(new Vector4(-1,  1, maxZ, 1));
            stream.Write(new Vector4(-1, -1, maxZ, 1));

            stream.Write(new Vector4(-1, -1, 0, 1));
            stream.Write(new Vector4(-1, -1, maxZ, 1));
            stream.Write(new Vector4( 1, -1, 0, 1));
            stream.Write(new Vector4( 1, -1, maxZ, 1));
            stream.Write(new Vector4( 1,  1, 0, 1));
            stream.Write(new Vector4( 1,  1, maxZ, 1));
            stream.Write(new Vector4(-1,  1, 0, 1));
            stream.Write(new Vector4(-1,  1, maxZ, 1));
            stream.Position = 0;

            var vertexBufferDesc = new BufferDescription()
            {
                BindFlags = BindFlags.VertexBuffer,
                CpuAccessFlags = CpuAccessFlags.None,
                Usage = ResourceUsage.Default,
                SizeInBytes = 24 * VertexPosition.SizeInBytes,
            };
            vertexBuffer = new SharpDX.Direct3D11.Buffer(device, stream, vertexBufferDesc);

            stream.Dispose();

            vertexBufferBinding = new VertexBufferBinding(vertexBuffer, VertexPosition.SizeInBytes, 0);

            shaderByteCode = new ShaderBytecode(File.ReadAllBytes("Content/frustumVS.cso"));
            frustumVS = new VertexShader(device, shaderByteCode);
            frustumPS = new PixelShader(device, new ShaderBytecode(File.ReadAllBytes("Content/frustumPS.cso")));

            // depth stencil state
            var depthStencilStateDesc = new DepthStencilStateDescription()
            {
                IsDepthEnabled = true,
                DepthWriteMask = DepthWriteMask.All,
                DepthComparison = Comparison.LessEqual,
                IsStencilEnabled = false,
            };
            depthStencilState = new DepthStencilState(device, depthStencilStateDesc);

            // rasterizer state
            var rasterizerStateDesc = new RasterizerStateDescription()
            {
                CullMode = CullMode.None,
                FillMode = FillMode.Wireframe,
                IsDepthClipEnabled = true,
                IsFrontCounterClockwise = true,
                IsMultisampleEnabled = true,
            };
            rasterizerState = new RasterizerState(device, rasterizerStateDesc);

            // constant buffer
            var VSConstantBufferDesc = new BufferDescription()
            {
                Usage = ResourceUsage.Dynamic,
                BindFlags = BindFlags.ConstantBuffer,
                SizeInBytes = VSConstantBuffer.size,
                CpuAccessFlags = CpuAccessFlags.Write,
                StructureByteStride = 0,
                OptionFlags = 0,
            };
            vertexShaderConstantBuffer = new SharpDX.Direct3D11.Buffer(device, VSConstantBufferDesc);

            // Pixel shader constant buffer
            var PSConstantBufferDesc = new BufferDescription()
            {
                Usage = ResourceUsage.Dynamic,
                BindFlags = BindFlags.ConstantBuffer,
                SizeInBytes = PSConstantBuffer.size,
                CpuAccessFlags = CpuAccessFlags.Write,
                StructureByteStride = 0,
                OptionFlags = 0,
            };
            pixelShaderConstantBuffer = new SharpDX.Direct3D11.Buffer(device, PSConstantBufferDesc);

            vertexInputLayout = new InputLayout(device, shaderByteCode.Data, new[]
            {
                new InputElement("SV_POSITION", 0, Format.R32G32B32A32_Float, 0, 0),
            });
        }
コード例 #43
0
ファイル: DX11.cs プロジェクト: nyx1220/sharpdx-examples
        public bool Initialize(SystemConfiguration configuration, IntPtr windowHandle)
        {
            try
            {
                #region Environment Configuration
                // Store the vsync setting.
                VerticalSyncEnabled = SystemConfiguration.VerticalSyncEnabled;

                // Create a DirectX graphics interface factory.
                var factory = new Factory();
                // Use the factory to create an adapter for the primary graphics interface (video card).
                var adapter = factory.GetAdapter(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;

                // 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),
                    // 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 = !SystemConfiguration.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.
                Device device;
                SwapChain swapChain;
                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);
                #endregion

                #region Initialize Output Merger
                // Set the depth stencil state.
                DeviceContext.OutputMerger.SetDepthStencilState(DepthStencilState, 1);

                // 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);
                #endregion

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

                // Setup and create the viewport for rendering.
                DeviceContext.Rasterizer.SetViewport(0, 0, configuration.Width, configuration.Height, 0, 1);
                #endregion

                #region Initialize matrices
                // Setup and create the projection matrix.
                ProjectionMatrix = Matrix.PerspectiveFovLH((float)(Math.PI / 4f), ((float)configuration.Width / configuration.Height), SystemConfiguration.ScreenNear, SystemConfiguration.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, SystemConfiguration.ScreenNear, SystemConfiguration.ScreenDepth);
                #endregion

                #region Initialize Depth Disabled Stencil
                // Now create a second depth stencil state which turns off the Z buffer for 2D rendering.
                // 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 blend state using the description.
                AlphaDisableBlendingState = new BlendState(device, blendStateDesc);
                #endregion

                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }
コード例 #44
0
        private void InitializeDeviceResources(DXGI.SwapChain swapChain)
        {
            backbufferTexture = swapChain.GetBackBuffer <D3D11.Texture2D>(0);
            backbufferRTV     = new D3D11.RenderTargetView(device, backbufferTexture);

            width  = backbufferTexture.Description.Width;
            height = backbufferTexture.Description.Height;

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

            using (var depthStencilBufferTexture = new D3D11.Texture2D(device, depthBufferDesc))
            {
                var depthStencilViewDesc = new D3D11.DepthStencilViewDescription()
                {
                    Format    = DXGI.Format.D24_UNorm_S8_UInt,
                    Dimension = D3D11.DepthStencilViewDimension.Texture2D,
                    Texture2D = new D3D11.DepthStencilViewDescription.Texture2DResource()
                    {
                        MipSlice = 0
                    }
                };

                depthDSV = new D3D11.DepthStencilView(device, depthStencilBufferTexture, depthStencilViewDesc);
            }



            var depthStencilDesc = new D3D11.DepthStencilStateDescription()
            {
                IsDepthEnabled   = true,
                DepthWriteMask   = D3D11.DepthWriteMask.All,
                DepthComparison  = D3D11.Comparison.Less,
                IsStencilEnabled = false,
                StencilReadMask  = 0xFF,
                StencilWriteMask = 0xFF,

                FrontFace = new D3D11.DepthStencilOperationDescription()
                {
                    FailOperation      = D3D11.StencilOperation.Keep,
                    DepthFailOperation = D3D11.StencilOperation.Keep,
                    PassOperation      = D3D11.StencilOperation.Keep,
                    Comparison         = D3D11.Comparison.Always
                },

                BackFace = new D3D11.DepthStencilOperationDescription()
                {
                    FailOperation      = D3D11.StencilOperation.Keep,
                    DepthFailOperation = D3D11.StencilOperation.Keep,
                    PassOperation      = D3D11.StencilOperation.Keep,
                    Comparison         = D3D11.Comparison.Always
                }
            };

            depthStencilState = new D3D11.DepthStencilState(device, depthStencilDesc);

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

            /*var blendDesc = new D3D11.BlendStateDescription();
             * blendDesc.RenderTarget[0].IsBlendEnabled = true;
             * blendDesc.RenderTarget[0].SourceBlend = D3D11.BlendOption.SourceAlpha;
             * blendDesc.RenderTarget[0].DestinationBlend = D3D11.BlendOption.InverseSourceAlpha;
             * blendDesc.RenderTarget[0].BlendOperation = D3D11.BlendOperation.Add;
             * blendDesc.RenderTarget[0].SourceAlphaBlend = D3D11.BlendOption.Zero;
             * blendDesc.RenderTarget[0].DestinationAlphaBlend = D3D11.BlendOption.Zero;
             * blendDesc.RenderTarget[0].AlphaBlendOperation = D3D11.BlendOperation.Add;
             * blendDesc.RenderTarget[0].RenderTargetWriteMask = D3D11.ColorWriteMaskFlags.All;*/

#if ALPHABLENDING
            var blendDesc = new D3D11.BlendStateDescription();
            blendDesc.RenderTarget[0].IsBlendEnabled        = true;
            blendDesc.RenderTarget[0].SourceBlend           = D3D11.BlendOption.SourceAlpha;
            blendDesc.RenderTarget[0].DestinationBlend      = D3D11.BlendOption.InverseSourceAlpha;
            blendDesc.RenderTarget[0].BlendOperation        = D3D11.BlendOperation.Add;
            blendDesc.RenderTarget[0].SourceAlphaBlend      = D3D11.BlendOption.Zero;
            blendDesc.RenderTarget[0].DestinationAlphaBlend = D3D11.BlendOption.One;
            blendDesc.RenderTarget[0].AlphaBlendOperation   = D3D11.BlendOperation.Add;
            blendDesc.RenderTarget[0].RenderTargetWriteMask = D3D11.ColorWriteMaskFlags.All;
#endif

#if ADDITIVEBLENDING
            var blendDesc = new D3D11.BlendStateDescription();
            blendDesc.RenderTarget[0].IsBlendEnabled        = true;
            blendDesc.RenderTarget[0].SourceBlend           = D3D11.BlendOption.SourceAlpha;
            blendDesc.RenderTarget[0].DestinationBlend      = D3D11.BlendOption.DestinationAlpha;
            blendDesc.RenderTarget[0].BlendOperation        = D3D11.BlendOperation.Add;
            blendDesc.RenderTarget[0].SourceAlphaBlend      = D3D11.BlendOption.One;
            blendDesc.RenderTarget[0].DestinationAlphaBlend = D3D11.BlendOption.One;
            blendDesc.RenderTarget[0].AlphaBlendOperation   = D3D11.BlendOperation.Add;
            blendDesc.RenderTarget[0].RenderTargetWriteMask = D3D11.ColorWriteMaskFlags.All;
#endif



            //     RenderTarget[0].BlendOpSharpDX.Direct3D11.BlendOperation.Add RenderTarget[0].SrcBlendAlphaSharpDX.Direct3D11.BlendOption.One
            //     RenderTarget[0].DestBlendAlphaSharpDX.Direct3D11.BlendOption.Zero RenderTarget[0].BlendOpAlphaSharpDX.Direct3D11.BlendOperation.Add
            //     RenderTarget[0].RenderTargetWriteMaskSharpDX.Direct3D11.ColorWriteMaskFlags.All


            blendState      = new D3D11.BlendState(device, blendDesc);
            rasterizerState = new D3D11.RasterizerState(device, rasterDesc);
        }