Ejemplo n.º 1
0
        public static SharpDX.Direct3D11.BlendState GetBlendState(Device d,params BlendStyle[] targets)
        {
            BlendStateDescription bsd = new BlendStateDescription();

            for (int i = 0; i < targets.Length; i++)
            {

                if (i < bsd.RenderTarget.Length)
                {
                    switch(targets[i])
                    {
                        case BlendStyle.AlphaBlend:
                            bsd.RenderTarget[i] = AlphaBlendDescription;
                            break;
                        case BlendStyle.Overwrite:
                            bsd.RenderTarget[i] = OverwriteBlendDescription;
                            break;
                        case BlendStyle.Disabled:
                            bsd.RenderTarget[i] = DisabledBlendDescription;
                            break;
                        default:
                            throw new ArgumentException("Unknown Blend Style " + targets[i].ToString());
                    }

                }
                else break;
            }

            return new BlendState(d, bsd);
        }
Ejemplo n.º 2
0
 /// <summary>
 /// Initializes a new instance of the <see cref="BlendState" /> class.
 /// </summary>
 /// <param name="device">The device local.</param>
 /// <param name="description">The description.</param>
 /// <param name="blendFactor">The blend factor.</param>
 /// <param name="mask">The mask.</param>
 private BlendState(GraphicsDevice device, BlendStateDescription description, Color4 blendFactor, int mask) : base(device)
 {
     Description = description;
     BlendFactor = blendFactor;
     MultiSampleMask = mask;
     Initialize(new Direct3D11.BlendState(GraphicsDevice, Description));
 }
Ejemplo n.º 3
0
        public BlendState(bool blendEnabled,
            BlendOperation blendOperation, BlendOperation alphaBlendOperation,
            BlendOption sourceBlend, BlendOption destinationBlend,
            BlendOption sourceAlphhaBlend, BlendOption destinationAlphaBlend)
        {
            RenderTargetBlendDescription targetDesc = new RenderTargetBlendDescription()
            {
                AlphaBlendOperation = alphaBlendOperation,
                BlendOperation = blendOperation,
                DestinationAlphaBlend = destinationAlphaBlend,
                SourceAlphaBlend = sourceAlphhaBlend,
                SourceBlend = sourceBlend,
                DestinationBlend = destinationBlend,
                IsBlendEnabled = blendEnabled,
                RenderTargetWriteMask = ColorWriteMaskFlags.All
            };

            BlendStateDescription desc = new BlendStateDescription()
            {
                IndependentBlendEnable = false,
            };

            desc.RenderTarget[0] = targetDesc;

            NativeBlendState = new SharpDX.Direct3D11.BlendState(GraphicManager.Device, desc);

        }
Ejemplo n.º 4
0
        /// <summary>
        /// Creates a new ApertureComposer instance.
        /// </summary>
        /// <param name="device">The graphics device.</param>
        public ApertureComposer(Device device)
        {
            BlendStateDescription description = new BlendStateDescription()
            {
                 AlphaToCoverageEnable = false,
                 IndependentBlendEnable = false,
            };

            description.RenderTarget[0] = new RenderTargetBlendDescription()
            {
                IsBlendEnabled = true,

                SourceBlend      = BlendOption.Zero,
                DestinationBlend = BlendOption.SourceColor,
                BlendOperation   = BlendOperation.Add,

                SourceAlphaBlend      = BlendOption.Zero,
                DestinationAlphaBlend = BlendOption.Zero,
                AlphaBlendOperation   = BlendOperation.Add,

                RenderTargetWriteMask = ColorWriteMaskFlags.Red,
            };

            blendState = new BlendState(device, description);

            // Instantiate all layers here

            layers.Add(new StructuralLayer());
        }
Ejemplo n.º 5
0
 /// <summary>
 /// Initializes a new instance of the <see cref="BlendState" /> class.
 /// </summary>
 /// <param name="device">The device local.</param>
 /// <param name="nativeState">State of the native.</param>
 /// <param name="blendFactor">The blend factor.</param>
 /// <param name="mask">The mask.</param>
 private BlendState(GraphicsDevice device, Direct3D11.BlendState nativeState, Color4 blendFactor, int mask) : base(device)
 {
     Description = nativeState.Description;
     BlendFactor = blendFactor;
     MultiSampleMask = mask;
     Initialize(nativeState);
 }
Ejemplo n.º 6
0
 /// <summary>
 /// Clones this instance.
 /// </summary>
 /// <returns>A copy of this instance.</returns>
 /// <remarks>
 /// Because this structure contains an array, it is not possible to modify it without making an explicit clone method.
 /// </remarks>
 public BlendStateDescription Clone()
 {
     var description = new BlendStateDescription {AlphaToCoverageEnable = AlphaToCoverageEnable, IndependentBlendEnable = IndependentBlendEnable};
     var sourceRenderTargets = RenderTarget;
     var destRenderTargets = description.RenderTarget;
     for (int i = 0; i < sourceRenderTargets.Length; i++)
         destRenderTargets[i] = sourceRenderTargets[i];
     return description;
 }
Ejemplo n.º 7
0
        public static D3D.BlendState CreateBlendState(this D3D.Device device)
        {
            var blendDesc = new D3D.BlendStateDescription();

            blendDesc.RenderTarget[0].IsBlendEnabled        = true;
            blendDesc.RenderTarget[0].SourceBlend           = D3D.BlendOption.SourceAlpha;
            blendDesc.RenderTarget[0].DestinationBlend      = D3D.BlendOption.InverseSourceAlpha;
            blendDesc.RenderTarget[0].BlendOperation        = D3D.BlendOperation.Add;
            blendDesc.RenderTarget[0].SourceAlphaBlend      = D3D.BlendOption.One;
            blendDesc.RenderTarget[0].DestinationAlphaBlend = D3D.BlendOption.Zero;
            blendDesc.RenderTarget[0].AlphaBlendOperation   = D3D.BlendOperation.Add;
            blendDesc.RenderTarget[0].RenderTargetWriteMask = D3D.ColorWriteMaskFlags.All;
            return(new D3D.BlendState(device, blendDesc));
        }
Ejemplo n.º 8
0
 protected static BlendStateDescription GetBlendStateDescription(
     BlendOption source = BlendOption.SourceAlpha,
     BlendOption destination = BlendOption.InverseSourceAlpha)
 {
     var description = new BlendStateDescription();
     description.RenderTarget[0].IsBlendEnabled = (source != BlendOption.One) ||
         (destination != BlendOption.Zero);
     description.RenderTarget[0].SourceBlend =
         description.RenderTarget[0].SourceAlphaBlend = source;
     description.RenderTarget[0].DestinationBlend =
         description.RenderTarget[0].DestinationAlphaBlend = destination;
     description.RenderTarget[0].BlendOperation =
         description.RenderTarget[0].AlphaBlendOperation = BlendOperation.Add;
     description.RenderTarget[0].RenderTargetWriteMask = ColorWriteMaskFlags.All;
     return description;
 }
        static void InitializeBlendStates()
        {
            BlendStateDescription desc = new BlendStateDescription();
            desc.RenderTarget[0].IsBlendEnabled = true;
            desc.RenderTarget[0].RenderTargetWriteMask = ColorWriteMaskFlags.All;
            desc.RenderTarget[0].BlendOperation = BlendOperation.Add;
            desc.RenderTarget[0].AlphaBlendOperation = BlendOperation.Add;
            desc.RenderTarget[0].DestinationBlend = BlendOption.InverseSourceAlpha;
            desc.RenderTarget[0].DestinationAlphaBlend = BlendOption.InverseSourceAlpha;
            desc.RenderTarget[0].SourceBlend = BlendOption.SourceAlpha;
            desc.RenderTarget[0].SourceAlphaBlend = BlendOption.SourceAlpha;
            BlendGui = MyPipelineStates.CreateBlendState(desc);

            desc.RenderTarget[0].IsBlendEnabled = true;
            desc.RenderTarget[0].RenderTargetWriteMask = ColorWriteMaskFlags.All;
            desc.RenderTarget[0].BlendOperation = BlendOperation.Add;
            desc.RenderTarget[0].AlphaBlendOperation = BlendOperation.Add;
            desc.RenderTarget[0].DestinationBlend = BlendOption.One;
            desc.RenderTarget[0].DestinationAlphaBlend = BlendOption.One;
            desc.RenderTarget[0].SourceBlend = BlendOption.One;
            desc.RenderTarget[0].SourceAlphaBlend = BlendOption.One;
            BlendAdditive = MyPipelineStates.CreateBlendState(desc);

            desc.RenderTarget[0].IsBlendEnabled = true;
            desc.RenderTarget[0].RenderTargetWriteMask = ColorWriteMaskFlags.All;
            desc.RenderTarget[0].BlendOperation = BlendOperation.Add;
            desc.RenderTarget[0].AlphaBlendOperation = BlendOperation.Add;
            desc.RenderTarget[0].DestinationBlend = BlendOption.InverseSourceAlpha;
            desc.RenderTarget[0].DestinationAlphaBlend = BlendOption.InverseSourceAlpha;
            desc.RenderTarget[0].SourceBlend = BlendOption.SourceAlpha;
            desc.RenderTarget[0].SourceAlphaBlend = BlendOption.One;
            BlendTransparent = MyPipelineStates.CreateBlendState(desc);

            desc.RenderTarget[0].IsBlendEnabled = true;
            desc.RenderTarget[0].RenderTargetWriteMask = ColorWriteMaskFlags.All;
            desc.RenderTarget[0].BlendOperation = BlendOperation.Add;
            desc.RenderTarget[0].AlphaBlendOperation = BlendOperation.Add;
            desc.RenderTarget[0].DestinationBlend = BlendOption.InverseSourceAlpha;
            desc.RenderTarget[0].DestinationAlphaBlend = BlendOption.InverseSourceAlpha;
            desc.RenderTarget[0].SourceBlend = BlendOption.One;
            desc.RenderTarget[0].SourceAlphaBlend = BlendOption.One;
            BlendAlphaPremult = MyPipelineStates.CreateBlendState(desc);
        }
Ejemplo n.º 10
0
        private BlendState CreateNewBlendState(ref BlendStateDescription description)
        {
            BlendAttachmentDescription[]             attachmentStates  = description.AttachmentStates;
            SharpDX.Direct3D11.BlendStateDescription d3dBlendStateDesc = new SharpDX.Direct3D11.BlendStateDescription();

            for (int i = 0; i < attachmentStates.Length; i++)
            {
                BlendAttachmentDescription state = attachmentStates[i];
                d3dBlendStateDesc.RenderTarget[i].IsBlendEnabled        = state.BlendEnabled;
                d3dBlendStateDesc.RenderTarget[i].RenderTargetWriteMask = ColorWriteMaskFlags.All;
                d3dBlendStateDesc.RenderTarget[i].SourceBlend           = D3D11Formats.VdToD3D11BlendOption(state.SourceColorFactor);
                d3dBlendStateDesc.RenderTarget[i].DestinationBlend      = D3D11Formats.VdToD3D11BlendOption(state.DestinationColorFactor);
                d3dBlendStateDesc.RenderTarget[i].BlendOperation        = D3D11Formats.VdToD3D11BlendOperation(state.ColorFunction);
                d3dBlendStateDesc.RenderTarget[i].SourceAlphaBlend      = D3D11Formats.VdToD3D11BlendOption(state.SourceAlphaFactor);
                d3dBlendStateDesc.RenderTarget[i].DestinationAlphaBlend = D3D11Formats.VdToD3D11BlendOption(state.DestinationAlphaFactor);
                d3dBlendStateDesc.RenderTarget[i].AlphaBlendOperation   = D3D11Formats.VdToD3D11BlendOperation(state.AlphaFunction);
            }

            return(new BlendState(_device, d3dBlendStateDesc));
        }
Ejemplo n.º 11
0
        private void EnableAlphaBlending()
        {
            if (blendState != null)
            {
                blendState.Dispose();
            }

            // Enable alpha blending
            // Based on: https://stackoverflow.com/questions/24899337/sharpdx-dx11-alpha-blend
            blendStateDesc = new D3D11.BlendStateDescription();
            blendStateDesc.RenderTarget[0].IsBlendEnabled        = true;
            blendStateDesc.RenderTarget[0].SourceBlend           = D3D11.BlendOption.SourceAlpha;
            blendStateDesc.RenderTarget[0].DestinationBlend      = D3D11.BlendOption.InverseSourceAlpha;
            blendStateDesc.RenderTarget[0].BlendOperation        = D3D11.BlendOperation.Add;
            blendStateDesc.RenderTarget[0].SourceAlphaBlend      = D3D11.BlendOption.One;
            blendStateDesc.RenderTarget[0].DestinationAlphaBlend = D3D11.BlendOption.Zero;
            blendStateDesc.RenderTarget[0].AlphaBlendOperation   = D3D11.BlendOperation.Add;
            blendStateDesc.RenderTarget[0].RenderTargetWriteMask = D3D11.ColorWriteMaskFlags.All;
            blendState = new D3D11.BlendState(d3dDevice, blendStateDesc);
            d3dDeviceContext.OutputMerger.SetBlendState(blendState);
        }
Ejemplo n.º 12
0
        public override bool Init()
        {
            if (!base.Init())
            {
                return(false);
            }


            //Initialize Wave Physics
            _awave = new AcceleratedWave(Device, ImmediateContext, "FX/compute.fx", "ProcessVertex");
            _awave.Init(200, 200, 0.8f, 0.03f, 6.25f, 0.1f);

            BuildLandGeometryBuffers();
            BuildWavesGeometryBuffers();
            BuildBallGeometryBuffers();
            BuildFX();
            BuildVertexLayout();
            FillWavesGeometryBuffer();


            //Initialize Alpha Blending
            D3D11.BlendStateDescription alphaDesc = new D3D11.BlendStateDescription();
            alphaDesc.RenderTarget[0].IsBlendEnabled        = true;
            alphaDesc.RenderTarget[0].SourceBlend           = D3D11.BlendOption.SourceAlpha;
            alphaDesc.RenderTarget[0].DestinationBlend      = D3D11.BlendOption.InverseSourceAlpha;
            alphaDesc.RenderTarget[0].BlendOperation        = D3D11.BlendOperation.Add;
            alphaDesc.RenderTarget[0].SourceAlphaBlend      = D3D11.BlendOption.One;
            alphaDesc.RenderTarget[0].DestinationAlphaBlend = D3D11.BlendOption.Zero;
            alphaDesc.RenderTarget[0].AlphaBlendOperation   = D3D11.BlendOperation.Add;
            alphaDesc.RenderTarget[0].RenderTargetWriteMask = D3D11.ColorWriteMaskFlags.All;

            _alphaBlend = new D3D11.BlendState(base.Device, alphaDesc);

            //Setup Ground Texture
            _groundMap    = TextureLoader.CreateTex2DFromFile(Device, "Textures\\grass.jpg");
            _groundMapSRV = new D3D11.ShaderResourceView(Device, _groundMap);

            return(true);
        }
Ejemplo n.º 13
0
        protected override void InitializeInternal()
        {
            var descr = new BlendStateDescription
            {
                AlphaToCoverageEnable = Settings.EnableAlphaToCoverage,
                IndependentBlendEnable = false,
            };

            descr.RenderTarget[0] = new RenderTargetBlendDescription
            {
                IsBlendEnabled = true,
                SourceBlend = GetBlendOption(Settings.FirstRGB),
                DestinationBlend = GetBlendOption(Settings.SecondRGB),
                BlendOperation = GetBlendOperation(Settings.OutputRGB),
                SourceAlphaBlend = GetBlendOption(Settings.FirstAlpha),
                DestinationAlphaBlend = GetBlendOption(Settings.SecondAlpha),
                AlphaBlendOperation = GetBlendOperation(Settings.OutputAlpha),
                RenderTargetWriteMask = (ColorWriteMaskFlags)Settings.OutputColorComponents
            };

            State = new global::SharpDX.Direct3D11.BlendState(DeviceManager.Device, descr);
        }
Ejemplo n.º 14
0
        public BlendState(GxContext context)
        {
            mContext = context;
            mDescription = new BlendStateDescription
            {
                AlphaToCoverageEnable = false,
                IndependentBlendEnable = false
            };

            mDescription.RenderTarget[0] = new RenderTargetBlendDescription
            {
                IsBlendEnabled = true,
                SourceBlend = BlendOption.SourceAlpha,
                DestinationBlend = BlendOption.InverseSourceAlpha,
                BlendOperation = BlendOperation.Add,
                SourceAlphaBlend = BlendOption.One,
                DestinationAlphaBlend = BlendOption.Zero,
                AlphaBlendOperation = BlendOperation.Add,
                RenderTargetWriteMask = ColorWriteMaskFlags.All
            };

            mChanged = true;
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Returns default values for <see cref="BlendStateDescription"/>. 
        /// </summary>
        /// <remarks>
        /// See MSDN documentation for default values.
        /// </remarks>
        public static BlendStateDescription Default()
        {
            var description = new BlendStateDescription()
            {
                AlphaToCoverageEnable = false,
                IndependentBlendEnable = false,
            };
            var renderTargets = description.RenderTarget;
            for (int i = 0; i < renderTargets.Length; i++)
            {
                renderTargets[i].IsBlendEnabled = false;
                renderTargets[i].SourceBlend = BlendOption.One;
                renderTargets[i].DestinationBlend = BlendOption.Zero;
                renderTargets[i].BlendOperation = BlendOperation.Add;

                renderTargets[i].SourceAlphaBlend = BlendOption.One;
                renderTargets[i].DestinationAlphaBlend = BlendOption.Zero;
                renderTargets[i].AlphaBlendOperation = BlendOperation.Add;

                renderTargets[i].RenderTargetWriteMask = ColorWriteMaskFlags.All;
            }

            return description;
        }
Ejemplo n.º 16
0
        public void Init(Form form)
        {
            ViewportSize  = new Size2F(form.Width, form.Height);
            hViewportSize = new Size2F(form.Width / 2f, form.Height / 2f);

            ModeDescription      backBufferDesc = new ModeDescription(form.Width, form.Height, new Rational(60, 1), Format.R8G8B8A8_UNorm);
            SwapChainDescription swapChainDesc  = new SwapChainDescription()
            {
                ModeDescription   = backBufferDesc,
                SampleDescription = new SampleDescription(1, 0),
                Usage             = Usage.RenderTargetOutput,
                BufferCount       = 1,
                OutputHandle      = form.Handle,
                IsWindowed        = true,
            };

            D3D11.Device.CreateWithSwapChain(DriverType.Hardware, D3D11.DeviceCreationFlags.None, swapChainDesc, out d3dDevice, out swapChain);
            d3dDeviceContext = d3dDevice.ImmediateContext;

            d3dDeviceContext.Rasterizer.SetViewport(0, 0, form.Width, form.Height);
            using (D3D11.Texture2D backBuffer = swapChain.GetBackBuffer <D3D11.Texture2D>(0))
            {
                renderTargetView = new D3D11.RenderTargetView(d3dDevice, backBuffer);
            }

            D3D11.BlendStateDescription blendStateDesc = D3D11.BlendStateDescription.Default();
            blendStateDesc.AlphaToCoverageEnable                 = false;
            blendStateDesc.RenderTarget[0].IsBlendEnabled        = true;
            blendStateDesc.RenderTarget[0].SourceBlend           = D3D11.BlendOption.SourceAlpha;
            blendStateDesc.RenderTarget[0].DestinationBlend      = D3D11.BlendOption.One;         //
            blendStateDesc.RenderTarget[0].BlendOperation        = D3D11.BlendOperation.Maximum;
            blendStateDesc.RenderTarget[0].SourceAlphaBlend      = D3D11.BlendOption.SourceAlpha; //Zero
            blendStateDesc.RenderTarget[0].DestinationAlphaBlend = D3D11.BlendOption.DestinationAlpha;
            blendStateDesc.RenderTarget[0].AlphaBlendOperation   = D3D11.BlendOperation.Maximum;
            blendStateDesc.RenderTarget[0].RenderTargetWriteMask = D3D11.ColorWriteMaskFlags.All;
            blendState = new D3D11.BlendState(d3dDevice, blendStateDesc);

            Fonts = new Detail.FontCache(this);

            var layout2d = new D3D11.InputElement[]
            {
                new D3D11.InputElement("POSITION", 0, Format.R32G32_Float, 0, 0),
                new D3D11.InputElement("COLOR", 0, Format.R32G32B32A32_Float, 8, 0),
                new D3D11.InputElement("TEXCOORDS", 0, Format.R32G32_Float, 24, 0),
            };

            var layout3d = new D3D11.InputElement[]
            {
                new D3D11.InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0),
                new D3D11.InputElement("COLOR", 0, Format.R32G32B32A32_Float, 12, 0),
            };

            var vertexShaderOutput2d = ShaderBytecode.Compile(Detail.Shaders.vertexShaderCode2d, "main", "vs_4_0", ShaderFlags.Debug);
            var vertexShaderOutput3d = ShaderBytecode.Compile(Detail.Shaders.vertexShaderCode3d, "main", "vs_4_0", ShaderFlags.Debug);
            var pixelShaderOutput    = ShaderBytecode.Compile(Detail.Shaders.pixelShaderCode, "main", "ps_4_0", ShaderFlags.Debug);

            Detail.Shaders.VertexShader2D = new D3D11.VertexShader(Device, vertexShaderOutput2d);
            Detail.Shaders.VertexShader3D = new D3D11.VertexShader(Device, vertexShaderOutput3d);
            Detail.Shaders.PixelShader    = new D3D11.PixelShader(Device, pixelShaderOutput);

            Detail.Shaders.InputLayout2D = new D3D11.InputLayout(Device, ShaderSignature.GetInputSignature(vertexShaderOutput2d), layout2d);
            Detail.Shaders.InputLayout3D = new D3D11.InputLayout(Device, ShaderSignature.GetInputSignature(vertexShaderOutput3d), layout3d);

            IntPtr data  = System.Runtime.InteropServices.Marshal.AllocHGlobal(4 * 4 * 4);
            var    white = BitConverter.GetBytes(1f);

            for (int i = 0; i < 4 * 4; i++)
            {
                for (int j = 0; j < white.Length; j++)
                {
                    System.Runtime.InteropServices.Marshal.WriteByte(data, i * sizeof(float) + j, white[j]);
                }
            }

            White = new D3D11.Texture2D(Device, new D3D11.Texture2DDescription
            {
                Width             = 4,
                Height            = 4,
                ArraySize         = 1,
                BindFlags         = D3D11.BindFlags.ShaderResource,
                Usage             = D3D11.ResourceUsage.Dynamic,
                CpuAccessFlags    = D3D11.CpuAccessFlags.Write,
                Format            = Format.R32G32B32A32_Float,
                MipLevels         = 1,
                OptionFlags       = D3D11.ResourceOptionFlags.None,
                SampleDescription = new DXGI.SampleDescription(1, 0),
            }, new DataBox[] { new DataBox(data, 4 * 2, 4) });

            System.Runtime.InteropServices.Marshal.FreeHGlobal(data);

            WhiteView = new D3D11.ShaderResourceView(Device, White);

            samplerState = new D3D11.SamplerState(Device, new D3D11.SamplerStateDescription()
            {
                Filter             = D3D11.Filter.MinMagMipLinear,
                AddressU           = D3D11.TextureAddressMode.Clamp,
                AddressV           = D3D11.TextureAddressMode.Clamp,
                AddressW           = D3D11.TextureAddressMode.Clamp,
                BorderColor        = new RawColor4(1f, 0f, 1f, 1f),
                ComparisonFunction = D3D11.Comparison.Never,
                MaximumAnisotropy  = 16,
                MipLodBias         = 0,
                MinimumLod         = 0,
                MaximumLod         = 16
            });

            transfBuffer = new SharpDX.Direct3D11.Buffer(Device,
                                                         new D3D11.BufferDescription(sizeof(float) * 4, D3D11.ResourceUsage.Dynamic, D3D11.BindFlags.ConstantBuffer,
                                                                                     D3D11.CpuAccessFlags.Write, D3D11.ResourceOptionFlags.None, sizeof(float)));

            DataStream stream;

            DeviceContext.MapSubresource(transfBuffer, D3D11.MapMode.WriteDiscard, D3D11.MapFlags.None, out stream);

            stream.Write(hViewportSize.Width);
            stream.Write(hViewportSize.Height);

            DeviceContext.UnmapSubresource(transfBuffer, 0);

            DeviceContext.VertexShader.SetShader(vertexShader, null, 0);
            DeviceContext.VertexShader.SetConstantBuffer(0, transfBuffer);
            DeviceContext.PixelShader.SetShader(pixelShader, null, 0);
            DeviceContext.PixelShader.SetSampler(0, samplerState);
            DeviceContext.InputAssembler.InputLayout = inputLayout;
            DeviceContext.OutputMerger.BlendState    = blendState;

            cam = new Camera(this);
        }
Ejemplo n.º 17
0
        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);
        }
Ejemplo n.º 18
0
        public void Initialize()
        {
            var direct2Dsettings = new RenderTarget.Configuration.CreationSettings(
                new Size(_settings.Width, _settings.Height),
                false,
                new SampleDescription(1, 0),
                RenderTarget.Configuration.RenderTargetClearSettings.Default,
                RenderTarget.Configuration.DepthStencilClearSettings.Default);

            RenderTargetDirect2D = _deviceManager.RenderTargetManager.CreateDirect2DRenderTarget(direct2Dsettings);

            _screenQuad = MeshFactory.CreateScreenQuad(_deviceManager.Device);
            //_screenQuadBinding = new VertexBufferBinding(_screenQuad, 20, 0);

            _effect = _deviceManager.ShaderCompiler.CreateEffectFromFile(@"..\..\Shaders\staging.fx");
            _pass = _effect.GetTechniqueByIndex(0).GetPassByIndex(0);

            //_elements = new[]
            //                {
            //                    new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0, InputClassification.PerVertexData, 0),
            //                    new InputElement("TEXCOORD", 0, Format.R32G32_Float, 12, 0, InputClassification.PerVertexData, 0),
            //                };

            _screenQuadBufferLayout = new InputLayout(_deviceManager.Device, _pass.Description.Signature, VertexPositionTexture.InputElements);
            //_screenQuadBufferLayout = new InputLayout(_deviceManager.Device, _pass.Description.Signature, _elements);

            _shaderResource = _effect.GetVariableByName("source").AsShaderResource();

            var bsd = new BlendStateDescription();
            bsd.RenderTarget[0].IsBlendEnabled = true;
            bsd.RenderTarget[0].SourceBlend = BlendOption.SourceColor;
            bsd.RenderTarget[0].DestinationBlend = BlendOption.BlendFactor;
            bsd.RenderTarget[0].BlendOperation = BlendOperation.Add;
            bsd.RenderTarget[0].SourceAlphaBlend = BlendOption.One;
            bsd.RenderTarget[0].DestinationAlphaBlend = BlendOption.Zero;
            bsd.RenderTarget[0].AlphaBlendOperation = BlendOperation.Add;
            bsd.RenderTarget[0].RenderTargetWriteMask = ColorWriteMaskFlags.All;

            _blendStateTransparent = new BlendState(_deviceManager.Device, bsd);
        }
        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));
            }
        }
Ejemplo n.º 20
0
 /// <summary>
 /// <p>Create a blend-state object that encapsulates blend state for the output-merger stage.</p>
 /// </summary>
 /// <param name="device">The  <see cref="GraphicsDevice"/>.</param>
 /// <param name="description"><dd>  <p>Pointer to a blend-state description (see <strong><see cref="SharpDX.Direct3D11.BlendStateDescription" /></strong>).</p> </dd></param>
 /// <param name="blendFactor">The blend factor.</param>
 /// <param name="mask">The mask.</param>
 /// <returns>A new <see cref="BlendState"/> instance.</returns>
 /// <msdn-id>ff476500</msdn-id>
 ///   <unmanaged>HRESULT ID3D11Device::CreateBlendState([In] const D3D11_BLEND_DESC* pBlendStateDesc,[Out, Fast] ID3D11BlendState** ppBlendState)</unmanaged>
 ///   <unmanaged-short>ID3D11Device::CreateBlendState</unmanaged-short>
 /// <remarks><p>An application can create up to 4096 unique blend-state objects. For each object created, the runtime checks to see if a previous object  has the same state. If such a previous object exists, the runtime will return a reference to previous instance instead of creating a duplicate object.</p></remarks>
 public static BlendState New(GraphicsDevice device, BlendStateDescription description, Color4 blendFactor, int mask = -1)
 {
     return new BlendState(device, description, blendFactor, mask);
 }
Ejemplo n.º 21
0
        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;
            }
        }
Ejemplo n.º 22
0
 /// <summary>
 ///   Constructs a new <see cref = "T:SharpDX.Direct3D11.BlendState" /> based on the specified description.
 /// </summary>
 /// <param name = "device">The device with which to associate the state object.</param>
 /// <param name = "description">The state description.</param>
 /// <returns>The newly created object.</returns>
 public BlendState(Device device, BlendStateDescription description)
     : base(IntPtr.Zero)
 {
     device.CreateBlendState(ref description, this);
 }
Ejemplo n.º 23
0
        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);
        }
Ejemplo n.º 24
0
        /// <summary>
        /// Creates a ConvolutionEngine instance.
        /// </summary>
        /// <param name="device">The graphics device to use.</param>
        /// <param name="context">The graphics context to use.</param>
        /// <param name="resolution">The convolution resolution.</param>
        public ConvolutionEngine(Device device, DeviceContext context, Size resolution)
        {
            fft = FastFourierTransform.Create2DComplex(context, resolution.Width, resolution.Height);
            fft.InverseScale = 1.0f / (float)(resolution.Width * resolution.Height);
            this.resolution = resolution;

            FastFourierTransformBufferRequirements bufferReqs = fft.BufferRequirements;
            precomputed = new FFTBuffer[bufferReqs.PrecomputeBufferCount];
            temporaries = new FFTBuffer[bufferReqs.TemporaryBufferCount];

            for (int t = 0; t < precomputed.Length; ++t)
                precomputed[t] = FFTUtils.AllocateBuffer(device, bufferReqs.PrecomputeBufferSizes[t]);

            for (int t = 0; t < temporaries.Length; ++t)
                temporaries[t] = FFTUtils.AllocateBuffer(device, bufferReqs.TemporaryBufferSizes[t]);

            UnorderedAccessView[] precomputedUAV = new UnorderedAccessView[bufferReqs.PrecomputeBufferCount];
            for (int t = 0; t < precomputed.Length; ++t) precomputedUAV[t] = precomputed[t].view;

            UnorderedAccessView[] temporariesUAV = new UnorderedAccessView[bufferReqs.TemporaryBufferCount];
            for (int t = 0; t < temporaries.Length; ++t) temporariesUAV[t] = temporaries[t].view;

            fft.AttachBuffersAndPrecompute(temporariesUAV, precomputedUAV);

            lBuf = FFTUtils.AllocateBuffer(device, 2 * resolution.Width * resolution.Height);
            rBuf = FFTUtils.AllocateBuffer(device, 2 * resolution.Width * resolution.Height);
            tBuf = FFTUtils.AllocateBuffer(device, 2 * resolution.Width * resolution.Height);

            rConvolved = new GraphicsResource(device, resolution, Format.R32_Float, true, true);
            gConvolved = new GraphicsResource(device, resolution, Format.R32_Float, true, true);
            bConvolved = new GraphicsResource(device, resolution, Format.R32_Float, true, true);
            staging    = new GraphicsResource(device, new Size(resolution.Width / 2, resolution.Height / 2), Format.R32G32B32A32_Float, true, true);

            BlendStateDescription description = new BlendStateDescription()
            {
                AlphaToCoverageEnable = false,
                IndependentBlendEnable = false,
            };

            description.RenderTarget[0] = new RenderTargetBlendDescription()
            {
                IsBlendEnabled = true,

                SourceBlend = BlendOption.One,
                DestinationBlend = BlendOption.One,
                BlendOperation = BlendOperation.Add,

                SourceAlphaBlend = BlendOption.Zero,
                DestinationAlphaBlend = BlendOption.Zero,
                AlphaBlendOperation = BlendOperation.Add,

                RenderTargetWriteMask = ColorWriteMaskFlags.Red
                                      | ColorWriteMaskFlags.Green
                                      | ColorWriteMaskFlags.Blue,
            };

            blendState = new BlendState(device, description);
        }
Ejemplo n.º 25
0
        public void Run()
        {
            var form = new RenderForm("2d and 3d combined...it's like magic");
            form.KeyDown += (sender, args) => { if (args.KeyCode == Keys.Escape) form.Close(); };

            // DirectX DXGI 1.1 factory
            var factory1 = new Factory1();

            // The 1st graphics adapter
            var adapter1 = factory1.GetAdapter1(0);

            // ---------------------------------------------------------------------------------------------
            // Setup direct 3d version 11. It's context will be used to combine the two elements
            // ---------------------------------------------------------------------------------------------

            var description = new SwapChainDescription
                {
                    BufferCount = 1,
                    ModeDescription = new ModeDescription(0, 0, new Rational(60, 1), Format.R8G8B8A8_UNorm),
                    IsWindowed = true,
                    OutputHandle = form.Handle,
                    SampleDescription = new SampleDescription(1, 0),
                    SwapEffect = SwapEffect.Discard,
                    Usage = Usage.RenderTargetOutput,
                    Flags = SwapChainFlags.AllowModeSwitch
                };

            Device11 device11;
            SwapChain swapChain;

            Device11.CreateWithSwapChain(adapter1, DeviceCreationFlags.None, description, out device11, out swapChain);

            // create a view of our render target, which is the backbuffer of the swap chain we just created
            RenderTargetView renderTargetView;
            using (var resource = Resource.FromSwapChain<Texture2D>(swapChain, 0))
                renderTargetView = new RenderTargetView(device11, resource);

            // setting a viewport is required if you want to actually see anything
            var context = device11.ImmediateContext;

            var viewport = new Viewport(0.0f, 0.0f, form.ClientSize.Width, form.ClientSize.Height);
            context.OutputMerger.SetTargets(renderTargetView);
            context.Rasterizer.SetViewports(viewport);

            //
            // Create the DirectX11 texture2D. This texture will be shared with the DirectX10 device.
            //
            // The DirectX10 device will be used to render text onto this texture.
            // DirectX11 will then draw this texture (blended) onto the screen.
            // The KeyedMutex flag is required in order to share this resource between the two devices.
            var textureD3D11 = new Texture2D(device11, new Texture2DDescription
            {
                Width = form.ClientSize.Width,
                Height = form.ClientSize.Height,
                MipLevels = 1,
                ArraySize = 1,
                Format = Format.B8G8R8A8_UNorm,
                SampleDescription = new SampleDescription(1, 0),
                Usage = ResourceUsage.Default,
                BindFlags = BindFlags.RenderTarget | BindFlags.ShaderResource,
                CpuAccessFlags = CpuAccessFlags.None,
                OptionFlags = ResourceOptionFlags.SharedKeyedmutex
            });

            // ---------------------------------------------------------------------------------------------
            // Setup a direct 3d version 10.1 adapter
            // ---------------------------------------------------------------------------------------------
            var device10 = new Device10(adapter1, SharpDX.Direct3D10.DeviceCreationFlags.BgraSupport, FeatureLevel.Level_10_0);

            // ---------------------------------------------------------------------------------------------
            // Setup Direct 2d
            // ---------------------------------------------------------------------------------------------

            // Direct2D Factory
            var factory2D = new SharpDX.Direct2D1.Factory(FactoryType.SingleThreaded, DebugLevel.Information);

            // Here we bind the texture we've created on our direct3d11 device through the direct3d10
            // to the direct 2d render target....
            var sharedResource = textureD3D11.QueryInterface<SharpDX.DXGI.Resource>();
            var textureD3D10 = device10.OpenSharedResource<SharpDX.Direct3D10.Texture2D>(sharedResource.SharedHandle);

            var surface = textureD3D10.AsSurface();
            var rtp = new RenderTargetProperties
                {
                    MinLevel = SharpDX.Direct2D1.FeatureLevel.Level_10,
                    Type = RenderTargetType.Hardware,
                    PixelFormat = new PixelFormat(Format.Unknown, AlphaMode.Premultiplied)
                };

            var renderTarget2D = new RenderTarget(factory2D, surface, rtp);
            var solidColorBrush = new SolidColorBrush(renderTarget2D, Colors.Red);

            // ---------------------------------------------------------------------------------------------------
            // Setup the rendering data
            // ---------------------------------------------------------------------------------------------------

            // Load Effect. This includes both the vertex and pixel shaders.
            // Also can include more than one technique.
            ShaderBytecode shaderByteCode = ShaderBytecode.CompileFromFile(
                "effectDx11.fx",
                "fx_5_0",
                ShaderFlags.EnableStrictness);

            var effect = new Effect(device11, shaderByteCode);

            // create triangle vertex data, making sure to rewind the stream afterward
            var verticesTriangle = new DataStream(VertexPositionColor.SizeInBytes * 3, true, true);
            verticesTriangle.Write(new VertexPositionColor(new Vector3(0.0f, 0.5f, 0.5f),new Color4(1.0f, 0.0f, 0.0f, 1.0f)));
            verticesTriangle.Write(new VertexPositionColor(new Vector3(0.5f, -0.5f, 0.5f),new Color4(0.0f, 1.0f, 0.0f, 1.0f)));
            verticesTriangle.Write(new VertexPositionColor(new Vector3(-0.5f, -0.5f, 0.5f),new Color4(0.0f, 0.0f, 1.0f, 1.0f)));

            verticesTriangle.Position = 0;

            // create the triangle vertex layout and buffer
            var layoutColor = new InputLayout(device11, effect.GetTechniqueByName("Color").GetPassByIndex(0).Description.Signature, VertexPositionColor.inputElements);
            var vertexBufferColor = new Buffer(device11, verticesTriangle, (int)verticesTriangle.Length, ResourceUsage.Default, BindFlags.VertexBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0);
            verticesTriangle.Close();

            // create overlay vertex data, making sure to rewind the stream afterward
            // Top Left of screen is -1, +1
            // Bottom Right of screen is +1, -1
            var verticesText = new DataStream(VertexPositionTexture.SizeInBytes * 4, true, true);
            verticesText.Write(new VertexPositionTexture(new Vector3(-1, 1, 0),new Vector2(0, 0f)));
            verticesText.Write(new VertexPositionTexture(new Vector3(1, 1, 0),new Vector2(1, 0)));
            verticesText.Write(new VertexPositionTexture(new Vector3(-1, -1, 0),new Vector2(0, 1)));
            verticesText.Write(new VertexPositionTexture(new Vector3(1, -1, 0),new Vector2(1, 1)));

            verticesText.Position = 0;

            // create the overlay vertex layout and buffer
            var layoutOverlay = new InputLayout(device11, effect.GetTechniqueByName("Overlay").GetPassByIndex(0).Description.Signature, VertexPositionTexture.inputElements);
            var vertexBufferOverlay = new Buffer(device11, verticesText, (int)verticesText.Length, ResourceUsage.Default, BindFlags.VertexBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0);
            verticesText.Close();

            // Think of the shared textureD3D10 as an overlay.
            // The overlay needs to show the 2d content but let the underlying triangle (or whatever)
            // show thru, which is accomplished by blending.
            var bsd = new BlendStateDescription();
            bsd.RenderTarget[0].IsBlendEnabled = true;
            bsd.RenderTarget[0].SourceBlend = BlendOption.SourceColor;
            bsd.RenderTarget[0].DestinationBlend = BlendOption.BlendFactor;
            bsd.RenderTarget[0].BlendOperation = BlendOperation.Add;
            bsd.RenderTarget[0].SourceAlphaBlend = BlendOption.One;
            bsd.RenderTarget[0].DestinationAlphaBlend = BlendOption.Zero;
            bsd.RenderTarget[0].AlphaBlendOperation = BlendOperation.Add;
            bsd.RenderTarget[0].RenderTargetWriteMask = ColorWriteMaskFlags.All;

            var blendStateTransparent = new BlendState(device11, bsd);

            // ---------------------------------------------------------------------------------------------------
            // Create and tesselate an ellipse
            // ---------------------------------------------------------------------------------------------------
            var center = new DrawingPointF(form.ClientSize.Width/2.0f, form.ClientSize.Height/2.0f);
            var ellipse = new EllipseGeometry(factory2D, new Ellipse(center, form.ClientSize.Width / 2.0f, form.ClientSize.Height / 2.0f));

            // Populate a PathGeometry from Ellipse tessellation
            var tesselatedGeometry = new PathGeometry(factory2D);
            _geometrySink = tesselatedGeometry.Open();

            // Force RoundLineJoin otherwise the tesselated looks buggy at line joins
            _geometrySink.SetSegmentFlags(PathSegment.ForceRoundLineJoin);

            // Tesselate the ellipse to our TessellationSink
            ellipse.Tessellate(1, this);

            _geometrySink.Close();

            // ---------------------------------------------------------------------------------------------------
            // Acquire the mutexes. These are needed to assure the device in use has exclusive access to the surface
            // ---------------------------------------------------------------------------------------------------

            var device10Mutex = textureD3D10.QueryInterface<KeyedMutex>();
            var device11Mutex = textureD3D11.QueryInterface<KeyedMutex>();

            // ---------------------------------------------------------------------------------------------------
            // Main rendering loop
            // ---------------------------------------------------------------------------------------------------

            bool first = true;

            RenderLoop
                .Run(form,
                     () =>
                         {
                             if(first)
                             {
                                 form.Activate();
                                 first = false;
                             }

                             // clear the render target to black
                             context.ClearRenderTargetView(renderTargetView, Colors.DarkSlateGray);

                             // Draw the triangle
                             context.InputAssembler.InputLayout = layoutColor;
                             context.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList;
                             context.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(vertexBufferColor, VertexPositionColor.SizeInBytes, 0));
                             context.OutputMerger.BlendState = null;
                             var currentTechnique = effect.GetTechniqueByName("Color");
                             for (var pass = 0; pass < currentTechnique.Description.PassCount; ++pass)
                             {
                                 using (var effectPass = currentTechnique.GetPassByIndex(pass))
                                 {
                                     System.Diagnostics.Debug.Assert(effectPass.IsValid, "Invalid EffectPass");
                                     effectPass.Apply(context);
                                 }
                                 context.Draw(3, 0);
                             };

                             // Draw Ellipse on the shared Texture2D
                             device10Mutex.Acquire(0, 100);
                             renderTarget2D.BeginDraw();
                             renderTarget2D.Clear(Colors.Black);
                             renderTarget2D.DrawGeometry(tesselatedGeometry, solidColorBrush);
                             renderTarget2D.DrawEllipse(new Ellipse(center, 200, 200), solidColorBrush, 20, null);
                             renderTarget2D.EndDraw();
                             device10Mutex.Release(0);

                             // Draw the shared texture2D onto the screen, blending the 2d content in
                             device11Mutex.Acquire(0, 100);
                             var srv = new ShaderResourceView(device11, textureD3D11);
                             effect.GetVariableByName("g_Overlay").AsShaderResource().SetResource(srv);
                             context.InputAssembler.InputLayout = layoutOverlay;
                             context.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleStrip;
                             context.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(vertexBufferOverlay, VertexPositionTexture.SizeInBytes, 0));
                             context.OutputMerger.BlendState = blendStateTransparent;
                             currentTechnique = effect.GetTechniqueByName("Overlay");

                             for (var pass = 0; pass < currentTechnique.Description.PassCount; ++pass)
                             {
                                 using (var effectPass = currentTechnique.GetPassByIndex(pass))
                                 {
                                     System.Diagnostics.Debug.Assert(effectPass.IsValid, "Invalid EffectPass");
                                     effectPass.Apply(context);
                                 }
                                 context.Draw(4, 0);
                             }
                             srv.Dispose();
                             device11Mutex.Release(0);

                             swapChain.Present(0, PresentFlags.None);
                         });

            // dispose everything
            vertexBufferColor.Dispose();
            vertexBufferOverlay.Dispose();
            layoutColor.Dispose();
            layoutOverlay.Dispose();
            effect.Dispose();
            shaderByteCode.Dispose();
            renderTarget2D.Dispose();
            swapChain.Dispose();
            device11.Dispose();
            device10.Dispose();
            textureD3D10.Dispose();
            textureD3D11.Dispose();
            factory1.Dispose();
            adapter1.Dispose();
            sharedResource.Dispose();
            factory2D.Dispose();
            surface.Dispose();
            solidColorBrush.Dispose();
            blendStateTransparent.Dispose();

            device10Mutex.Dispose();
            device11Mutex.Dispose();
        }
Ejemplo n.º 26
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 GorgonBlendStates stateType)
        {
#if DEBUG
            #region State Validation Code.
            if ((stateType.RenderTarget0.AlphaOperation == BlendOperation.Unknown) &&
                (stateType.RenderTarget1.AlphaOperation == BlendOperation.Unknown) &&
                (stateType.RenderTarget2.AlphaOperation == BlendOperation.Unknown) &&
                (stateType.RenderTarget3.AlphaOperation == BlendOperation.Unknown) &&
                (stateType.RenderTarget4.AlphaOperation == BlendOperation.Unknown) &&
                (stateType.RenderTarget5.AlphaOperation == BlendOperation.Unknown) &&
                (stateType.RenderTarget6.AlphaOperation == BlendOperation.Unknown) &&
                (stateType.RenderTarget7.AlphaOperation == BlendOperation.Unknown))
            {
                throw new GorgonException(GorgonResult.CannotBind,
                                          string.Format(Resources.GORGFX_INVALID_ENUM_VALUE, BlendOperation.Unknown,
                                                        "AlphaOperation"));
            }

            if ((stateType.RenderTarget0.BlendingOperation == BlendOperation.Unknown) &&
                (stateType.RenderTarget1.BlendingOperation == BlendOperation.Unknown) &&
                (stateType.RenderTarget2.BlendingOperation == BlendOperation.Unknown) &&
                (stateType.RenderTarget3.BlendingOperation == BlendOperation.Unknown) &&
                (stateType.RenderTarget4.BlendingOperation == BlendOperation.Unknown) &&
                (stateType.RenderTarget5.BlendingOperation == BlendOperation.Unknown) &&
                (stateType.RenderTarget6.BlendingOperation == BlendOperation.Unknown) &&
                (stateType.RenderTarget7.BlendingOperation == BlendOperation.Unknown))
            {
                throw new GorgonException(GorgonResult.CannotBind,
                                          string.Format(Resources.GORGFX_INVALID_ENUM_VALUE, BlendOperation.Unknown,
                                                        "BlendingOperation"));
            }

            if ((stateType.RenderTarget0.DestinationAlphaBlend == BlendType.Unknown) &&
                (stateType.RenderTarget1.DestinationAlphaBlend == BlendType.Unknown) &&
                (stateType.RenderTarget2.DestinationAlphaBlend == BlendType.Unknown) &&
                (stateType.RenderTarget3.DestinationAlphaBlend == BlendType.Unknown) &&
                (stateType.RenderTarget4.DestinationAlphaBlend == BlendType.Unknown) &&
                (stateType.RenderTarget5.DestinationAlphaBlend == BlendType.Unknown) &&
                (stateType.RenderTarget6.DestinationAlphaBlend == BlendType.Unknown) &&
                (stateType.RenderTarget7.DestinationAlphaBlend == BlendType.Unknown))
            {
                throw new GorgonException(GorgonResult.CannotBind,
                                          string.Format(Resources.GORGFX_INVALID_ENUM_VALUE, BlendType.Unknown,
                                                        "DestinationAlphaBlend"));
            }

            if ((stateType.RenderTarget0.DestinationBlend == BlendType.Unknown) &&
                (stateType.RenderTarget1.DestinationBlend == BlendType.Unknown) &&
                (stateType.RenderTarget2.DestinationBlend == BlendType.Unknown) &&
                (stateType.RenderTarget3.DestinationBlend == BlendType.Unknown) &&
                (stateType.RenderTarget4.DestinationBlend == BlendType.Unknown) &&
                (stateType.RenderTarget5.DestinationBlend == BlendType.Unknown) &&
                (stateType.RenderTarget6.DestinationBlend == BlendType.Unknown) &&
                (stateType.RenderTarget7.DestinationBlend == BlendType.Unknown))
            {
                throw new GorgonException(GorgonResult.CannotBind,
                                          string.Format(Resources.GORGFX_INVALID_ENUM_VALUE, BlendType.Unknown,
                                                        "DestinationBlend"));
            }

            if ((stateType.RenderTarget0.SourceAlphaBlend == BlendType.Unknown) &&
                (stateType.RenderTarget1.SourceAlphaBlend == BlendType.Unknown) &&
                (stateType.RenderTarget2.SourceAlphaBlend == BlendType.Unknown) &&
                (stateType.RenderTarget3.SourceAlphaBlend == BlendType.Unknown) &&
                (stateType.RenderTarget4.SourceAlphaBlend == BlendType.Unknown) &&
                (stateType.RenderTarget5.SourceAlphaBlend == BlendType.Unknown) &&
                (stateType.RenderTarget6.SourceAlphaBlend == BlendType.Unknown) &&
                (stateType.RenderTarget7.SourceAlphaBlend == BlendType.Unknown))
            {
                throw new GorgonException(GorgonResult.CannotBind,
                                          string.Format(Resources.GORGFX_INVALID_ENUM_VALUE, BlendType.Unknown,
                                                        "SourceAlphaBlend"));
            }

            if ((stateType.RenderTarget0.SourceBlend == BlendType.Unknown) &&
                (stateType.RenderTarget1.SourceBlend == BlendType.Unknown) &&
                (stateType.RenderTarget2.SourceBlend == BlendType.Unknown) &&
                (stateType.RenderTarget3.SourceBlend == BlendType.Unknown) &&
                (stateType.RenderTarget4.SourceBlend == BlendType.Unknown) &&
                (stateType.RenderTarget5.SourceBlend == BlendType.Unknown) &&
                (stateType.RenderTarget6.SourceBlend == BlendType.Unknown) &&
                (stateType.RenderTarget7.SourceBlend == BlendType.Unknown))
            {
                throw new GorgonException(GorgonResult.CannotBind,
                                          string.Format(Resources.GORGFX_INVALID_ENUM_VALUE, BlendType.Unknown,
                                                        "SourceBlend"));
            }

            if ((stateType.RenderTarget0.WriteMask == ColorWriteMaskFlags.None) &&
                (stateType.RenderTarget1.WriteMask == ColorWriteMaskFlags.None) &&
                (stateType.RenderTarget2.WriteMask == ColorWriteMaskFlags.None) &&
                (stateType.RenderTarget3.WriteMask == ColorWriteMaskFlags.None) &&
                (stateType.RenderTarget4.WriteMask == ColorWriteMaskFlags.None) &&
                (stateType.RenderTarget5.WriteMask == ColorWriteMaskFlags.None) &&
                (stateType.RenderTarget6.WriteMask == ColorWriteMaskFlags.None) &&
                (stateType.RenderTarget7.WriteMask == ColorWriteMaskFlags.None))
            {
                throw new GorgonException(GorgonResult.CannotBind,
                                          string.Format(Resources.GORGFX_INVALID_ENUM_VALUE, ColorWriteMaskFlags.None,
                                                        "WriteMask"));
            }
            #endregion
#endif

            var desc = new D3D.BlendStateDescription
            {
                AlphaToCoverageEnable  = stateType.IsAlphaCoverageEnabled,
                IndependentBlendEnable = stateType.IsIndependentBlendEnabled,
            };

            // Copy render targets.
            desc.RenderTarget[0] = stateType.RenderTarget0.Convert();
            desc.RenderTarget[1] = stateType.RenderTarget1.Convert();
            desc.RenderTarget[2] = stateType.RenderTarget2.Convert();
            desc.RenderTarget[3] = stateType.RenderTarget3.Convert();
            desc.RenderTarget[4] = stateType.RenderTarget4.Convert();
            desc.RenderTarget[5] = stateType.RenderTarget5.Convert();
            desc.RenderTarget[6] = stateType.RenderTarget6.Convert();
            desc.RenderTarget[7] = stateType.RenderTarget7.Convert();

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

            return(state);
        }
Ejemplo n.º 27
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));
            });
        }
Ejemplo n.º 28
0
        public Renderer(Game game, SharpDX.Windows.RenderForm renderForm)
        {
            this.game = game;
            int width = renderForm.ClientSize.Width, height = renderForm.ClientSize.Height;

            ResolutionX = width; ResolutionY = height;

            #region 3d device & context
            D3D11.DeviceCreationFlags creationFlags = D3D11.DeviceCreationFlags.BgraSupport;
            #if DEBUG
            creationFlags |= D3D11.DeviceCreationFlags.Debug;
            #endif
            DXGI.SwapChainDescription swapChainDesc = new DXGI.SwapChainDescription()
            {
                ModeDescription   = new DXGI.ModeDescription(width, height, new DXGI.Rational(60, 1), DXGI.Format.R8G8B8A8_UNorm),
                SampleDescription = new DXGI.SampleDescription(SampleCount, SampleQuality),
                Usage             = DXGI.Usage.RenderTargetOutput,
                BufferCount       = 1,
                OutputHandle      = renderForm.Handle,
                IsWindowed        = true,
                SwapEffect        = DXGI.SwapEffect.Discard
            };
            D3D11.Device device;
            D3D11.Device.CreateWithSwapChain(DriverType.Hardware, creationFlags, swapChainDesc, out device, out swapChain);
            Device  = device;
            Context = Device.ImmediateContext;
            #endregion
            #region 2d device & context
            DXGI.Device dxgiDevice = Device.QueryInterface <D3D11.Device1>().QueryInterface <DXGI.Device2>();
            D2DDevice  = new D2D1.Device(dxgiDevice);
            D2DContext = new D2D1.DeviceContext(D2DDevice, D2D1.DeviceContextOptions.None);
            D2DFactory = D2DDevice.Factory;
            #endregion
            #region 2d brushes/fonts
            Brushes = new Dictionary <string, D2D1.Brush>();
            Brushes.Add("Red", new D2D1.SolidColorBrush(D2DContext, Color.Red));
            Brushes.Add("Green", new D2D1.SolidColorBrush(D2DContext, Color.Green));
            Brushes.Add("Blue", new D2D1.SolidColorBrush(D2DContext, Color.Blue));
            Brushes.Add("White", new D2D1.SolidColorBrush(D2DContext, Color.White));
            Brushes.Add("Black", new D2D1.SolidColorBrush(D2DContext, Color.Black));
            Brushes.Add("TransparentWhite", new D2D1.SolidColorBrush(D2DContext, new Color(1, 1, 1, .5f)));
            Brushes.Add("TransparentBlack", new D2D1.SolidColorBrush(D2DContext, new Color(0, 0, 0, .5f)));
            Brushes.Add("LightGray", new D2D1.SolidColorBrush(D2DContext, Color.LightGray));
            Brushes.Add("OrangeRed", new D2D1.SolidColorBrush(D2DContext, Color.OrangeRed));
            Brushes.Add("CornflowerBlue", new D2D1.SolidColorBrush(D2DContext, Color.CornflowerBlue));
            Brushes.Add("Yellow", new D2D1.SolidColorBrush(D2DContext, Color.Yellow));
            Brushes.Add("Magenta", new D2D1.SolidColorBrush(D2DContext, Color.Magenta));
            Brushes.Add("RosyBrown", new D2D1.SolidColorBrush(D2DContext, Color.RosyBrown));

            DashStyle = new D2D1.StrokeStyle(D2DFactory, new D2D1.StrokeStyleProperties()
            {
                StartCap   = D2D1.CapStyle.Flat,
                DashCap    = D2D1.CapStyle.Round,
                EndCap     = D2D1.CapStyle.Flat,
                DashStyle  = D2D1.DashStyle.Custom,
                DashOffset = 0,
                LineJoin   = D2D1.LineJoin.Round,
                MiterLimit = 1
            }, new float[] { 4f, 4f });

            FontFactory = new DWrite.Factory();
            SegoeUI24   = new DWrite.TextFormat(FontFactory, "Segoe UI", 24f);
            SegoeUI14   = new DWrite.TextFormat(FontFactory, "Segoe UI", 14f);
            Consolas14  = new DWrite.TextFormat(FontFactory, "Consolas", 14f);
            #endregion

            #region blend states
            D3D11.BlendStateDescription opaqueDesc = new D3D11.BlendStateDescription();
            opaqueDesc.RenderTarget[0].IsBlendEnabled        = false;
            opaqueDesc.RenderTarget[0].RenderTargetWriteMask = D3D11.ColorWriteMaskFlags.All;
            blendStateOpaque = new D3D11.BlendState(Device, opaqueDesc);

            D3D11.BlendStateDescription alphaDesc = new D3D11.BlendStateDescription();
            alphaDesc.RenderTarget[0].IsBlendEnabled        = true;
            alphaDesc.RenderTarget[0].SourceBlend           = D3D11.BlendOption.SourceAlpha;
            alphaDesc.RenderTarget[0].DestinationBlend      = D3D11.BlendOption.InverseSourceAlpha;
            alphaDesc.RenderTarget[0].BlendOperation        = D3D11.BlendOperation.Add;
            alphaDesc.RenderTarget[0].SourceAlphaBlend      = D3D11.BlendOption.One;
            alphaDesc.RenderTarget[0].DestinationAlphaBlend = D3D11.BlendOption.Zero;
            alphaDesc.RenderTarget[0].AlphaBlendOperation   = D3D11.BlendOperation.Add;
            alphaDesc.RenderTarget[0].RenderTargetWriteMask = D3D11.ColorWriteMaskFlags.All;
            blendStateTransparent = new D3D11.BlendState(Device, alphaDesc);
            #endregion
            #region rasterizer states
            rasterizerStateSolidCullBack = new D3D11.RasterizerState(Device, new D3D11.RasterizerStateDescription()
            {
                FillMode = D3D11.FillMode.Solid,
                CullMode = D3D11.CullMode.Back,
                IsAntialiasedLineEnabled = true,
                IsDepthClipEnabled       = false,
                IsMultisampleEnabled     = true
            });
            rasterizerStateWireframeCullBack = new D3D11.RasterizerState(Device, new D3D11.RasterizerStateDescription()
            {
                FillMode = D3D11.FillMode.Wireframe,
                CullMode = D3D11.CullMode.Back,
                IsAntialiasedLineEnabled = true,
                IsDepthClipEnabled       = false,
                IsMultisampleEnabled     = true
            });
            rasterizerStateSolidNoCull = new D3D11.RasterizerState(Device, new D3D11.RasterizerStateDescription()
            {
                FillMode = D3D11.FillMode.Solid,
                CullMode = D3D11.CullMode.None,
                IsAntialiasedLineEnabled = true,
                IsDepthClipEnabled       = false,
                IsMultisampleEnabled     = true
            });
            rasterizerStateWireframeNoCull = new D3D11.RasterizerState(Device, new D3D11.RasterizerStateDescription()
            {
                FillMode = D3D11.FillMode.Wireframe,
                CullMode = D3D11.CullMode.None,
                IsAntialiasedLineEnabled = true,
                IsDepthClipEnabled       = false,
                IsMultisampleEnabled     = true
            });
            rasterizerStateSolidCullFront = new D3D11.RasterizerState(Device, new D3D11.RasterizerStateDescription()
            {
                FillMode = D3D11.FillMode.Solid,
                CullMode = D3D11.CullMode.Front,
                IsAntialiasedLineEnabled = true,
                IsDepthClipEnabled       = false,
                IsMultisampleEnabled     = true
            });
            rasterizerStateWireframeCullFront = new D3D11.RasterizerState(Device, new D3D11.RasterizerStateDescription()
            {
                FillMode = D3D11.FillMode.Wireframe,
                CullMode = D3D11.CullMode.Front,
                IsAntialiasedLineEnabled = true,
                IsDepthClipEnabled       = false,
                IsMultisampleEnabled     = true
            });
            #endregion

            #region depth stencil states
            depthStencilStateDefault = new D3D11.DepthStencilState(Device, new D3D11.DepthStencilStateDescription()
            {
                IsDepthEnabled   = true,
                IsStencilEnabled = false,
                DepthComparison  = D3D11.Comparison.Less,
                DepthWriteMask   = D3D11.DepthWriteMask.All
            });

            depthStencilStateNoDepth = new D3D11.DepthStencilState(Device, new D3D11.DepthStencilStateDescription()
            {
                IsDepthEnabled   = false,
                IsStencilEnabled = false,
                DepthComparison  = D3D11.Comparison.Less,
                DepthWriteMask   = D3D11.DepthWriteMask.All
            });

            Context.OutputMerger.SetDepthStencilState(depthStencilStateDefault);
            #endregion

            #region blank textures
            D3D11.Texture2D wtex   = new D3D11.Texture2D(Device, new D3D11.Texture2DDescription()
            {
                ArraySize         = 1,
                Width             = 1,
                Height            = 1,
                Format            = DXGI.Format.R32G32B32A32_Float,
                CpuAccessFlags    = D3D11.CpuAccessFlags.None,
                MipLevels         = 0,
                Usage             = D3D11.ResourceUsage.Default,
                SampleDescription = new DXGI.SampleDescription(1, 0),
                BindFlags         = D3D11.BindFlags.ShaderResource,
                OptionFlags       = D3D11.ResourceOptionFlags.None
            });
            Context.UpdateSubresource(new Vector4[] { Vector4.One }, wtex);
            WhiteTextureView = new D3D11.ShaderResourceView(Device, wtex);

            D3D11.Texture2D btex = new D3D11.Texture2D(Device, new D3D11.Texture2DDescription()
            {
                ArraySize         = 1,
                Width             = 1,
                Height            = 1,
                Format            = DXGI.Format.R32G32B32A32_Float,
                CpuAccessFlags    = D3D11.CpuAccessFlags.None,
                MipLevels         = 0,
                Usage             = D3D11.ResourceUsage.Default,
                SampleDescription = new DXGI.SampleDescription(1, 0),
                BindFlags         = D3D11.BindFlags.ShaderResource,
                OptionFlags       = D3D11.ResourceOptionFlags.None
            });
            Context.UpdateSubresource(new Vector4[] { new Vector4(0, 0, 0, 1) }, btex);
            BlackTextureView = new D3D11.ShaderResourceView(Device, btex);

            AnisotropicSampler = new D3D11.SamplerState(Device, new D3D11.SamplerStateDescription()
            {
                AddressU = D3D11.TextureAddressMode.Wrap,
                AddressV = D3D11.TextureAddressMode.Wrap,
                AddressW = D3D11.TextureAddressMode.Wrap,
                Filter   = D3D11.Filter.Anisotropic,
            });
            #endregion
            #region screen vertex & constants
            constants      = new CameraConstants();
            constantBuffer = D3D11.Buffer.Create(Device, D3D11.BindFlags.ConstantBuffer, ref constants);
            #endregion
            //swapChain.GetParent<DXGI.Factory>().MakeWindowAssociation(renderForm.Handle, DXGI.WindowAssociationFlags.);

            Cameras      = new List <Camera>();
            MainCamera   = Camera.CreatePerspective(MathUtil.DegreesToRadians(70), 16 / 9f);
            ActiveCamera = MainCamera;
            Cameras.Add(MainCamera);

            ShadowCamera       = Camera.CreateOrthographic(500, 1);
            ShadowCamera.zNear = 0;
            ShadowCamera.zFar  = 1000;
            ShadowCamera.CreateResources(Device, 1, 0, 1024, 1024);
            //Cameras.Add(ShadowCamera);
            // TODO: Shadow camera has no depth

            Resize(ResolutionX, ResolutionY);
        }
Ejemplo n.º 29
0
 /// <summary>
 /// <p>Create a blend-state object that encapsulates blend state for the output-merger stage.</p>
 /// </summary>
 /// <param name="device">The  <see cref="GraphicsDevice"/>.</param>
 /// <param name="name">Name of this blend state.</param>
 /// <param name="description"><dd>  <p>Pointer to a blend-state description (see <strong><see cref="SharpDX.Direct3D11.BlendStateDescription" /></strong>).</p> </dd></param>
 /// <param name="mask">The mask.</param>
 /// <returns>A new <see cref="BlendState"/> instance.</returns>
 /// <msdn-id>ff476500</msdn-id>
 ///   <unmanaged>HRESULT ID3D11Device::CreateBlendState([In] const D3D11_BLEND_DESC* pBlendStateDesc,[Out, Fast] ID3D11BlendState** ppBlendState)</unmanaged>
 ///   <unmanaged-short>ID3D11Device::CreateBlendState</unmanaged-short>
 /// <remarks><p>An application can create up to 4096 unique blend-state objects. For each object created, the runtime checks to see if a previous object  has the same state. If such a previous object exists, the runtime will return a reference to previous instance instead of creating a duplicate object.</p></remarks>
 public static BlendState New(GraphicsDevice device, string name, BlendStateDescription description, int mask = -1)
 {
     return new BlendState(device, description, Color.White, mask) {Name = name};
 }
        protected override void CreateDeviceDependentResources()
        {
            RemoveAndDispose(ref vertexShader);
            RemoveAndDispose(ref vertexShaderInstanced);
            RemoveAndDispose(ref geomShader);
            RemoveAndDispose(ref pixelShader);

            RemoveAndDispose(ref blendState);
            RemoveAndDispose(ref linearSampler);

            RemoveAndDispose(ref perComputeBuffer);
            RemoveAndDispose(ref perFrame);

            // Dispose of any loaded particle textures
            particleTextureSRVs.ForEach(srv => RemoveAndDispose(ref srv));
            particleTextureSRVs.Clear();

            // Dispose of any compute shaders
            computeShaders.Select(kv => kv.Value).ToList().ForEach(cs => RemoveAndDispose(ref cs));
            computeShaders.Clear();

            var device = this.DeviceManager.Direct3DDevice;

            #region Compile Vertex/Pixel/Geometry shaders

            // Compile and create the vertex shader
            using (var vsBytecode = HLSLCompiler.CompileFromFile(@"Shaders\ParticleVS.hlsl", "VSMain", "vs_5_0"))
            using (var vsInstance = HLSLCompiler.CompileFromFile(@"Shaders\ParticleVS.hlsl", "VSMainInstance", "vs_5_0"))
            // Compile and create the pixel shader
            using (var psBytecode = HLSLCompiler.CompileFromFile(@"Shaders\ParticlePS.hlsl", "PSMain", "ps_5_0"))
            // Compile and create the geometry shader
            using (var gsBytecode = HLSLCompiler.CompileFromFile(@"Shaders\ParticleGS.hlsl", "PointToQuadGS", "gs_5_0"))
            {
                vertexShader = ToDispose(new VertexShader(device, vsBytecode));
                vertexShaderInstanced = ToDispose(new VertexShader(device, vsInstance));
                pixelShader = ToDispose(new PixelShader(device, psBytecode));
                geomShader = ToDispose(new GeometryShader(device, gsBytecode));
            }
            #endregion

            #region Blend States
            var blendDesc = new BlendStateDescription() {
                IndependentBlendEnable = false,
                AlphaToCoverageEnable = false,
            };
            // Additive blend state that darkens
            blendDesc.RenderTarget[0] = new RenderTargetBlendDescription
            {
                IsBlendEnabled = true,
                BlendOperation = BlendOperation.Add,
                AlphaBlendOperation = BlendOperation.Add,
                SourceBlend = BlendOption.SourceAlpha,
                DestinationBlend = BlendOption.InverseSourceAlpha,
                SourceAlphaBlend = BlendOption.One,
                DestinationAlphaBlend = BlendOption.Zero,
                RenderTargetWriteMask = ColorWriteMaskFlags.All
            };
            blendState = ToDispose(new BlendState(device, blendDesc));

            // Additive blend state that lightens
            // (needs a dark background)
            blendDesc.RenderTarget[0].DestinationBlend = BlendOption.One;

            blendStateLight = ToDispose(new BlendState(device, blendDesc));
            #endregion

            // depth stencil state to disable Z-buffer
            disableDepthWrite = ToDispose(new DepthStencilState(device, new DepthStencilStateDescription {
                DepthComparison = Comparison.Less,
                DepthWriteMask = SharpDX.Direct3D11.DepthWriteMask.Zero,
                IsDepthEnabled = true,
                IsStencilEnabled = false
            }));

            // Create a linear sampler
            linearSampler = ToDispose(new SamplerState(device, new SamplerStateDescription
            {
                AddressU = TextureAddressMode.Wrap,
                AddressV = TextureAddressMode.Wrap,
                AddressW = TextureAddressMode.Wrap,
                Filter = Filter.MinMagMipLinear, // Bilinear
                MaximumLod = float.MaxValue,
                MinimumLod = 0,
            }));

            // Create the per compute shader constant buffer
            perComputeBuffer = ToDispose(new Buffer(device, Utilities.SizeOf<ParticleConstants>(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0));
            // Create the particle frame buffer
            perFrame = ToDispose(new Buffer(device, Utilities.SizeOf<ParticleFrame>(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0));

            particleTextureSRVs.Add(ToDispose(ShaderResourceView.FromFile(device, "Particle.png")));
            particleTextureSRVs.Add(ToDispose(ShaderResourceView.FromFile(device, "Snowflake.png")));
            particleTextureSRVs.Add(ToDispose(ShaderResourceView.FromFile(device, "Square.png")));
            activeParticleTextureIndex = 0;

            // Reinitialize particles if > 0
            if (this.Constants.MaxParticles > 0)
            {
                InitializeParticles(this.Constants.MaxParticles, this.Constants.MaxLifetime);
            }
        }
Ejemplo n.º 31
0
        public static void CreateBlendState(ref BlendId id, BlendStateDescription description)
        {
            if (id == BlendId.NULL)
            {
                id = new BlendId(BlendStates.Allocate());
                MyArrayHelpers.Reserve(ref BlendObjects, id.Index + 1);
                BlendIndices.Add(id);
            }
            else
            {
                BlendObjects[id.Index].Dispose();
            }

            BlendStates.Data[id.Index] = description.Clone();
            InitBlendState(id);
        }
Ejemplo n.º 32
0
 public static D3D.BlendState CreateBlendState(this D3D.Device device)
 {
     var blendDesc = new D3D.BlendStateDescription();
     blendDesc.RenderTarget[0].IsBlendEnabled = true;
     blendDesc.RenderTarget[0].SourceBlend = D3D.BlendOption.SourceAlpha;
     blendDesc.RenderTarget[0].DestinationBlend = D3D.BlendOption.InverseSourceAlpha;
     blendDesc.RenderTarget[0].BlendOperation = D3D.BlendOperation.Add;
     blendDesc.RenderTarget[0].SourceAlphaBlend = D3D.BlendOption.One;
     blendDesc.RenderTarget[0].DestinationAlphaBlend = D3D.BlendOption.Zero;
     blendDesc.RenderTarget[0].AlphaBlendOperation = D3D.BlendOperation.Add;
     blendDesc.RenderTarget[0].RenderTargetWriteMask = D3D.ColorWriteMaskFlags.All;
     return new D3D.BlendState(device, blendDesc);
 }
Ejemplo n.º 33
0
 public static BlendId CreateBlendState(BlendStateDescription description)
 {
     BlendId id = new BlendId();
     CreateBlendState(ref id, description);
     return id;
 }
Ejemplo n.º 34
0
 /// <summary>
 ///   Constructs a new <see cref = "T:SharpDX.Direct3D11.BlendState" /> based on the specified description.
 /// </summary>
 /// <param name = "device">The device with which to associate the state object.</param>
 /// <param name = "description">The state description.</param>
 /// <returns>The newly created object.</returns>
 public BlendState(Device device, BlendStateDescription description)
     : base(IntPtr.Zero)
 {
     device.CreateBlendState(ref description, this);
 }
Ejemplo n.º 35
0
		/// <summary>
		/// SetupBlendState
		/// </summary>
		void SetupBlendState ()
		{
			var	rtbd	=	new RenderTargetBlendDescription();

			bool enabled	=	true;

			if ( BlendState.DstAlpha==Blend.Zero && BlendState.SrcAlpha==Blend.One &&
				 BlendState.DstColor==Blend.Zero && BlendState.SrcColor==Blend.One ) {

				 enabled = false;
			}

			rtbd.IsBlendEnabled			=	enabled	;
			rtbd.BlendOperation			=	Converter.Convert( BlendState.ColorOp );
			rtbd.AlphaBlendOperation	=	Converter.Convert( BlendState.AlphaOp );
			rtbd.RenderTargetWriteMask	=	(ColorWriteMaskFlags)(int)BlendState.WriteMask;
			rtbd.DestinationBlend		=	Converter.Convert( BlendState.DstColor );
			rtbd.SourceBlend			=	Converter.Convert( BlendState.SrcColor );
			rtbd.DestinationAlphaBlend	=	Converter.Convert( BlendState.DstAlpha );
			rtbd.SourceAlphaBlend		=	Converter.Convert( BlendState.SrcAlpha );
				
			var	bsd		=	new BlendStateDescription();
			bsd.AlphaToCoverageEnable	=	false;
			bsd.IndependentBlendEnable	=	false;
			bsd.RenderTarget[0]			=	rtbd;

			blendFactor	=	SharpDXHelper.Convert( BlendState.BlendFactor );
			blendMsaaMask	=	BlendState.MultiSampleMask;

			blendState	=	new D3DBlendState( device.Device, bsd );
		}
Ejemplo n.º 36
0
        private void InitBlendState()
        {
            BlendStateDescription _BlendStateDescription = new BlendStateDescription {
                AlphaToCoverageEnable = false,
                IndependentBlendEnable = false
            };

            _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;

            _BlendState = new BlendState(GraphicsAdapter.GraphicsDevice, _BlendStateDescription);
        }
Ejemplo n.º 37
0
        internal static BlendId CreateBlendState(BlendStateDescription description)
        {
            var id = new BlendId { Index = BlendStates.Allocate() };
            MyArrayHelpers.Reserve(ref BlendObjects, id.Index + 1);

            BlendStates.Data[id.Index] = description.Clone();

            InitBlendState(id);
            BlendIndices.Add(id);

            return id;
        }
Ejemplo n.º 38
0
        protected void OnInitializeDevice()
        {
            Form.ClientSize = new Size(_width, _height);

            // SwapChain description
            var desc = new SwapChainDescription()
            {
                BufferCount = 1,
                ModeDescription = new ModeDescription(_width, _height, new Rational(60, 1), Format.R8G8B8A8_UNorm),
                IsWindowed = true,
                OutputHandle = Form.Handle,
                SampleDescription = new SampleDescription(1, 0),
                SwapEffect = SwapEffect.Discard,
                Usage = Usage.RenderTargetOutput,
            };

            // Create Device and SwapChain
            SharpDX.Direct3D11.Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.None, desc, out _device, out _swapChain);
            _immediateContext = _device.ImmediateContext;
            outputMerger = _immediateContext.OutputMerger;
            inputAssembler = _immediateContext.InputAssembler;

            Factory factory = _swapChain.GetParent<Factory>();
            factory.MakeWindowAssociation(Form.Handle, WindowAssociationFlags.None);

            var blendStateDesc = new BlendStateDescription();
            blendStateDesc.RenderTarget[0].IsBlendEnabled = true;
            blendStateDesc.RenderTarget[0].SourceBlend = BlendOption.SourceAlpha;
            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;
            alphaBlendState = new BlendState(_device, blendStateDesc);
        }
Ejemplo n.º 39
0
        public bool Initialize()
        {
            Debug.Assert(!_initialized);

            #region Shaders
            string SpriteFX = @"Texture2D SpriteTex;
SamplerState samLinear {
    Filter = MIN_MAG_MIP_LINEAR;
    AddressU = WRAP;
    AddressV = WRAP;
};
struct VertexIn {
    float3 PosNdc : POSITION;
    float2 Tex    : TEXCOORD;
    float4 Color  : COLOR;
};
struct VertexOut {
    float4 PosNdc : SV_POSITION;
    float2 Tex    : TEXCOORD;
    float4 Color  : COLOR;
};
VertexOut VS(VertexIn vin) {
    VertexOut vout;
    vout.PosNdc = float4(vin.PosNdc, 1.0f);
    vout.Tex    = vin.Tex;
    vout.Color  = vin.Color;
    return vout;
};
float4 PS(VertexOut pin) : SV_Target {
    return pin.Color*SpriteTex.Sample(samLinear, pin.Tex);
};
technique11 SpriteTech {
    pass P0 {
        SetVertexShader( CompileShader( vs_5_0, VS() ) );
        SetHullShader( NULL );
        SetDomainShader( NULL );
        SetGeometryShader( NULL );
        SetPixelShader( CompileShader( ps_5_0, PS() ) );
    }
};";
            #endregion

            _compiledFX = ShaderBytecode.Compile(SpriteFX, "SpriteTech", "fx_5_0");
            {
                
                if (_compiledFX.HasErrors)
                    return false;

                _effect = new Effect(_device, _compiledFX);
                {
                    _spriteTech = _effect.GetTechniqueByName("SpriteTech");
                    _spriteMap = _effect.GetVariableByName("SpriteTex").AsShaderResource();

                    var pass = _spriteTech.GetPassByIndex(0).Description.Signature;
                    InputElement[] layoutDesc = {
                                                    new InputElement("POSITION", 0, SharpDX.DXGI.Format.R32G32B32_Float, 0, 0, InputClassification.PerVertexData, 0),
                                                    new InputElement("TEXCOORD", 0, SharpDX.DXGI.Format.R32G32_Float, 12, 0, InputClassification.PerVertexData, 0),
                                                    new InputElement("COLOR", 0, SharpDX.DXGI.Format.R32G32B32A32_Float, 20, 0, InputClassification.PerVertexData, 0)
                                                };

                    _inputLayout = new InputLayout(_device, pass, layoutDesc);

                    // Create Vertex Buffer
                    BufferDescription vbd = new BufferDescription
                    {
                        SizeInBytes = 2048 * Marshal.SizeOf(typeof(SpriteVertex)),
                        Usage = ResourceUsage.Dynamic,
                        BindFlags = BindFlags.VertexBuffer,
                        CpuAccessFlags = CpuAccessFlags.Write,
                        OptionFlags = ResourceOptionFlags.None,
                        StructureByteStride = 0
                    };

                    _VB = new SharpDX.Direct3D11.Buffer(_device, vbd);

                    // Create and initialise Index Buffer

                    short[] indices = new short[3072];

                    for (ushort i = 0; i < 512; ++i)
                    {
                        indices[i * 6] = (short)(i * 4);
                        indices[i * 6 + 1] = (short)(i * 4 + 1);
                        indices[i * 6 + 2] = (short)(i * 4 + 2);
                        indices[i * 6 + 3] = (short)(i * 4);
                        indices[i * 6 + 4] = (short)(i * 4 + 2);
                        indices[i * 6 + 5] = (short)(i * 4 + 3);
                    }

                    _indexBuffer = Marshal.AllocHGlobal(indices.Length * Marshal.SizeOf(indices[0]));
                    Marshal.Copy(indices, 0, _indexBuffer, indices.Length);

                    BufferDescription ibd = new BufferDescription
                    {
                        SizeInBytes = 3072 * Marshal.SizeOf(typeof(short)),
                        Usage = ResourceUsage.Immutable,
                        BindFlags = BindFlags.IndexBuffer,
                        CpuAccessFlags = CpuAccessFlags.None,
                        OptionFlags = ResourceOptionFlags.None,
                        StructureByteStride = 0
                    };
                    
                    _IB = new SharpDX.Direct3D11.Buffer(_device, _indexBuffer, ibd);

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

                    _transparentBS = new BlendState(_device, transparentDesc);
                }
            }

            _initialized = true;

            return true;
        }
Ejemplo n.º 40
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);
        }