public PhysicsDebugDraw(DeviceManager manager)
        {
            device = manager.Direct3DDevice;
            inputAssembler = device.ImmediateContext.InputAssembler;
            lineArray = new PositionColored[0];

            using (var bc = HLSLCompiler.CompileFromFile(@"Shaders\PhysicsDebug.hlsl", "VSMain", "vs_5_0"))
            {
                vertexShader = new VertexShader(device, bc);

                InputElement[] elements = new InputElement[]
                {
                    new InputElement("SV_POSITION", 0, Format.R32G32B32_Float, 0, 0, InputClassification.PerVertexData, 0),
                    new InputElement("COLOR", 0, Format.R8G8B8A8_UNorm, 12, 0, InputClassification.PerVertexData, 0)
                };
                inputLayout = new InputLayout(device, bc, elements);
            }

            vertexBufferDesc = new BufferDescription()
            {
                Usage = ResourceUsage.Dynamic,
                BindFlags = BindFlags.VertexBuffer,
                CpuAccessFlags = CpuAccessFlags.Write
            };

            vertexBufferBinding = new VertexBufferBinding(null, PositionColored.Stride, 0);

            using (var bc = HLSLCompiler.CompileFromFile(@"Shaders\PhysicsDebug.hlsl", "PSMain", "ps_5_0"))
                pixelShader = new PixelShader(device, bc);
        }
        public static Resource LoadFromFile(DeviceManager manager, string fileName)
        {
            ShaderResourceView srv;
            var texture = LoadFromFile(manager, fileName, out srv);

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

            return texture;
        }
        /// <summary>
        /// Default constructor
        /// </summary>
        public D3DApplicationBase()
        {
            // Create our device manager instance.
            // This encapsulates the creation of Direct3D and Direct2D devices
            _deviceManager = ToDispose(new DeviceManager());

            // If the device needs to be reinitialized, make sure we
            // are able to recreate our device dependent resources.
            DeviceManager.OnInitialize += CreateDeviceDependentResources;

            // If the size changes, make sure we reinitialize
            // any size dependent resources.
            this.OnSizeChanged += CreateSizeDependentResources;
        }
 public static Resource LoadFromFile(DeviceManager manager, string fileName, out ShaderResourceView srv)
 {
     if (Path.GetExtension(fileName).ToLower() == ".dds")
     {
         var result = LoadDDSFromBuffer(manager.Direct3DDevice, SharpDX.IO.NativeFile.ReadAllBytes(fileName), out srv);
         return result;
     }
     else
     {
         var bs = LoadBitmap(manager.WICFactory, fileName);
         var texture = CreateTexture2DFromBitmap(manager.Direct3DDevice, bs);
         srv = new ShaderResourceView(manager.Direct3DDevice, texture);
         return texture;
     }
 }
        protected override void CreateDeviceDependentResources(DeviceManager deviceManager)
        {
            base.CreateDeviceDependentResources(deviceManager);

            // Release all resources
            RemoveAndDispose(ref vertexShader);

            RemoveAndDispose(ref pixelShader);
            RemoveAndDispose(ref depthPixelShader);
            RemoveAndDispose(ref lambertShader);
            RemoveAndDispose(ref blinnPhongShader);
            RemoveAndDispose(ref phongShader);

            RemoveAndDispose(ref vertexLayout);
            RemoveAndDispose(ref perObjectBuffer);
            RemoveAndDispose(ref perFrameBuffer);
            RemoveAndDispose(ref perMaterialBuffer);
            RemoveAndDispose(ref perArmatureBuffer);

            RemoveAndDispose(ref depthStencilState);

            // Get a reference to the Device1 instance and immediate context
            var device = deviceManager.Direct3DDevice;
            var context = deviceManager.Direct3DContext;

            // Compile and create the vertex shader and input layout
            using (var vertexShaderBytecode = HLSLCompiler.CompileFromFile(@"Shaders\VS.hlsl", "VSMain", "vs_5_0"))
            {
                vertexShader = ToDispose(new VertexShader(device, vertexShaderBytecode));
                // Layout from VertexShader input signature
                vertexLayout = ToDispose(new InputLayout(device,
                    vertexShaderBytecode.GetPart(ShaderBytecodePart.InputSignatureBlob),
                new[]
                {
                    // "SV_Position" = vertex coordinate in object space
                    new InputElement("SV_Position", 0, Format.R32G32B32_Float, 0, 0),
                    // "NORMAL" = the vertex normal
                    new InputElement("NORMAL", 0, Format.R32G32B32_Float, 12, 0),
                    // "COLOR"
                    new InputElement("COLOR", 0, Format.R8G8B8A8_UNorm, 24, 0),
                    // "UV"
                    new InputElement("TEXCOORD", 0, Format.R32G32_Float, 28, 0),
                    // "SkinIndices"
                    new InputElement("BLENDINDICES", 0, Format.R32G32B32A32_UInt, 36, 0),
                    // "SkinWeights"
                    new InputElement("BLENDWEIGHT", 0, Format.R32G32B32A32_Float, 52, 0),
                }));
            }

            // Compile and create the pixel shader
            using (var bytecode = HLSLCompiler.CompileFromFile(@"Shaders\SimplePS.hlsl", "PSMain", "ps_5_0"))
                pixelShader = ToDispose(new PixelShader(device, bytecode));

            // Compile and create the depth vertex and pixel shaders
            // This shader is for checking what the depth buffer would look like
            using (var bytecode = HLSLCompiler.CompileFromFile(@"Shaders\DepthPS.hlsl", "PSMain", "ps_5_0"))
                depthPixelShader = ToDispose(new PixelShader(device, bytecode));

            // Compile and create the Lambert pixel shader
            using (var bytecode = HLSLCompiler.CompileFromFile(@"Shaders\DiffusePS.hlsl", "PSMain", "ps_5_0"))
                lambertShader = ToDispose(new PixelShader(device, bytecode));

            // Compile and create the Lambert pixel shader
            using (var bytecode = HLSLCompiler.CompileFromFile(@"Shaders\BlinnPhongPS.hlsl", "PSMain", "ps_5_0"))
                blinnPhongShader = ToDispose(new PixelShader(device, bytecode));

            // Compile and create the Lambert pixel shader
            using (var bytecode = HLSLCompiler.CompileFromFile(@"Shaders\PhongPS.hlsl", "PSMain", "ps_5_0"))
                phongShader = ToDispose(new PixelShader(device, bytecode));

            // IMPORTANT: A constant buffer's size must be a multiple of 16-bytes
            // use LayoutKind.Explicit and an explicit Size= to force this for structures
            // or alternatively add padding fields and use a LayoutKind.Sequential and Pack=1

            // Create the constant buffer that will
            // store our worldViewProjection matrix
            perObjectBuffer = ToDispose(new SharpDX.Direct3D11.Buffer(device, Utilities.SizeOf<ConstantBuffers.PerObject>(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0));

            // Create the per frame constant buffer
            // lighting / camera position
            perFrameBuffer = ToDispose(new Buffer(device, Utilities.SizeOf<ConstantBuffers.PerFrame>(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0));

            // Create the per material constant buffer
            perMaterialBuffer = ToDispose(new Buffer(device, Utilities.SizeOf<ConstantBuffers.PerMaterial>(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0));

            // Create the per armature/skeletong constant buffer
            perArmatureBuffer = ToDispose(new Buffer(device, ConstantBuffers.PerArmature.Size(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0));

            // Configure the depth buffer to discard pixels that are
            // further than the current pixel.
            depthStencilState = ToDispose(new DepthStencilState(device,
                new DepthStencilStateDescription()
                {
                    IsDepthEnabled = true, // enable depth?
                    DepthComparison = Comparison.Less,
                    DepthWriteMask = SharpDX.Direct3D11.DepthWriteMask.All,
                    IsStencilEnabled = false,// enable stencil?
                    StencilReadMask = 0xff, // 0xff (no mask)
                    StencilWriteMask = 0xff,// 0xff (no mask)
                    // Configure FrontFace depth/stencil operations
                    FrontFace = new DepthStencilOperationDescription()
                    {
                        Comparison = Comparison.Always,
                        PassOperation = StencilOperation.Keep,
                        FailOperation = StencilOperation.Keep,
                        DepthFailOperation = StencilOperation.Increment
                    },
                    // Configure BackFace depth/stencil operations
                    BackFace = new DepthStencilOperationDescription()
                    {
                        Comparison = Comparison.Always,
                        PassOperation = StencilOperation.Keep,
                        FailOperation = StencilOperation.Keep,
                        DepthFailOperation = StencilOperation.Decrement
                    },
                }));

            // Tell the IA what the vertices will look like
            // in this case two 4-component 32bit floats
            // (32 bytes in total)
            context.InputAssembler.InputLayout = vertexLayout;

            // Set our constant buffer (to store worldViewProjection)
            context.VertexShader.SetConstantBuffer(0, perObjectBuffer);
            context.VertexShader.SetConstantBuffer(1, perFrameBuffer);
            context.VertexShader.SetConstantBuffer(2, perMaterialBuffer);
            context.VertexShader.SetConstantBuffer(3, perArmatureBuffer);

            // Set the vertex shader to run
            context.VertexShader.Set(vertexShader);

            // Set our pixel constant buffers
            context.PixelShader.SetConstantBuffer(1, perFrameBuffer);
            context.PixelShader.SetConstantBuffer(2, perMaterialBuffer);

            // Set the pixel shader to run
            context.PixelShader.Set(blinnPhongShader);

            // Set our depth stencil state
            context.OutputMerger.DepthStencilState = depthStencilState;

            // Back-face culling
            context.Rasterizer.State = ToDispose(new RasterizerState(device, new RasterizerStateDescription()
            {
                FillMode = FillMode.Solid,
                CullMode = CullMode.Back,
            }));
        }
 void DeviceManager_OnInitialize(DeviceManager deviceManager)
 {
     CreateDeviceDependentResources();
 }
        protected override void CreateDeviceDependentResources(DeviceManager deviceManager)
        {
            base.CreateDeviceDependentResources(deviceManager);

            // Release all resources
            RemoveAndDispose(ref vertexShader);

            RemoveAndDispose(ref pixelShader);
            RemoveAndDispose(ref depthPixelShader);
            RemoveAndDispose(ref lambertShader);
            RemoveAndDispose(ref blinnPhongShader);
            RemoveAndDispose(ref phongShader);

            RemoveAndDispose(ref tessellateVertexShader);
            RemoveAndDispose(ref tessellateTriIntegerShader);
            RemoveAndDispose(ref tessellateTriPow2Shader);
            RemoveAndDispose(ref tessellateTriFractionalEvenShader);
            RemoveAndDispose(ref tessellateTriFractionalOddShader);
            RemoveAndDispose(ref tessellateTriDomainShader);

            RemoveAndDispose(ref tessellatePhongDomainShader);

            RemoveAndDispose(ref debugNormals);

            RemoveAndDispose(ref vertexLayout);
            RemoveAndDispose(ref perObjectBuffer);
            RemoveAndDispose(ref perFrameBuffer);
            RemoveAndDispose(ref perMaterialBuffer);
            RemoveAndDispose(ref perArmatureBuffer);

            RemoveAndDispose(ref decalBuffer);
            RemoveAndDispose(ref decalDiffuse);
            RemoveAndDispose(ref decalDisplacement);
            RemoveAndDispose(ref decalNormal);

            RemoveAndDispose(ref depthStencilState);

            // Get a reference to the Device1 instance and immediate context
            var device = deviceManager.Direct3DDevice;
            var context = deviceManager.Direct3DContext;

            // Compile and create the vertex shader and input layout
            using (var vertexShaderBytecode = HLSLCompiler.CompileFromFile(@"Shaders\VS.hlsl", "VSMain", "vs_5_0"))
            using (var vertexTessBytecode = HLSLCompiler.CompileFromFile(@"Shaders\VS.hlsl", "VSPassThruTessellate", "vs_5_0"))
            {
                vertexShader = ToDispose(new VertexShader(device, vertexShaderBytecode));
                tessellateVertexShader = ToDispose(new VertexShader(device, vertexTessBytecode));

                // Layout from VertexShader input signature
                vertexLayout = ToDispose(new InputLayout(device,
                    vertexShaderBytecode.GetPart(ShaderBytecodePart.InputSignatureBlob),
                    new[]
                {
                    // "SV_Position" = vertex coordinate in object space
                    new InputElement("SV_Position", 0, Format.R32G32B32_Float, 0, 0),
                    // "NORMAL" = the vertex normal
                    new InputElement("NORMAL", 0, Format.R32G32B32_Float, 12, 0),
                    // "COLOR"
                    new InputElement("COLOR", 0, Format.R8G8B8A8_UNorm, 24, 0),
                    // "UV"
                    new InputElement("TEXCOORD", 0, Format.R32G32_Float, 28, 0),
                    // "BLENDINDICES"
                    new InputElement("BLENDINDICES", 0, Format.R32G32B32A32_UInt, 36, 0),
                    // "BLENDWEIGHT"
                    new InputElement("BLENDWEIGHT", 0, Format.R32G32B32A32_Float, 52, 0),
                    // "TANGENT"
                    new InputElement("TANGENT", 0, Format.R32G32B32A32_Float, 68, 0),
                }));
            }

            // Compile and create the pixel shader
            using (var bytecode = HLSLCompiler.CompileFromFile(@"Shaders\SimplePS.hlsl", "PSMain", "ps_5_0"))
                pixelShader = ToDispose(new PixelShader(device, bytecode));

            // Compile and create the depth vertex and pixel shaders
            // This shader is for checking what the depth buffer would look like
            using (var bytecode = HLSLCompiler.CompileFromFile(@"Shaders\DepthPS.hlsl", "PSMain", "ps_5_0"))
                depthPixelShader = ToDispose(new PixelShader(device, bytecode));

            // Compile and create the Lambert pixel shader
            using (var bytecode = HLSLCompiler.CompileFromFile(@"Shaders\DiffusePS.hlsl", "PSMain", "ps_5_0"))
                lambertShader = ToDispose(new PixelShader(device, bytecode));

            // Compile and create the Lambert pixel shader
            using (var bytecode = HLSLCompiler.CompileFromFile(@"Shaders\BlinnPhongPS.hlsl", "PSMain", "ps_5_0"))
                blinnPhongShader = ToDispose(new PixelShader(device, bytecode));

            // Compile and create the Lambert pixel shader
            using (var bytecode = HLSLCompiler.CompileFromFile(@"Shaders\PhongPS.hlsl", "PSMain", "ps_5_0"))
                phongShader = ToDispose(new PixelShader(device, bytecode));

            #region Tessellation Shaders

            using (var triIntegerBytecode = HLSLCompiler.CompileFromFile(@"Shaders\TessellateTri.hlsl", "HS_TrianglesInteger", "hs_5_0", null))
            using (var triPow2Bytecode = HLSLCompiler.CompileFromFile(@"Shaders\TessellateTri.hlsl", "HS_TrianglesPow2", "hs_5_0", null))
            using (var triFractionalEvenBytecode = HLSLCompiler.CompileFromFile(@"Shaders\TessellateTri.hlsl", "HS_TrianglesFractionalEven", "hs_5_0", null))
            using (var triFractionalOddBytecode = HLSLCompiler.CompileFromFile(@"Shaders\TessellateTri.hlsl", "HS_TrianglesFractionalOdd", "hs_5_0", null))
            using (var triDomainShaderBytecode = HLSLCompiler.CompileFromFile(@"Shaders\TessellateTri.hlsl", "DS_Triangles", "ds_5_0", null))
            {
                tessellateTriIntegerShader = ToDispose(new HullShader(device, triIntegerBytecode));
                tessellateTriPow2Shader = ToDispose(new HullShader(device, triPow2Bytecode));
                tessellateTriFractionalEvenShader = ToDispose(new HullShader(device, triFractionalEvenBytecode));
                tessellateTriFractionalOddShader = ToDispose(new HullShader(device, triFractionalOddBytecode));
                tessellateTriDomainShader = ToDispose(new DomainShader(device, triDomainShaderBytecode));
            }

            using (var phongDomainShaderBytecode = HLSLCompiler.CompileFromFile(@"Shaders\TessellatePhong.hlsl", "DS_PhongTessellation", "ds_5_0", null))
            {
                tessellatePhongDomainShader = ToDispose(new DomainShader(device, phongDomainShaderBytecode));
            }

            using (var pnTriIntegerBytecode = HLSLCompiler.CompileFromFile(@"Shaders\TessellatePNTri.hlsl", "HS_PNTrianglesInteger", "hs_5_0", null))
            using (var pnTriPow2Bytecode = HLSLCompiler.CompileFromFile(@"Shaders\TessellatePNTri.hlsl", "HS_PNTrianglesPow2", "hs_5_0", null))
            using (var pnTriFractionalEvenBytecode = HLSLCompiler.CompileFromFile(@"Shaders\TessellatePNTri.hlsl", "HS_PNTrianglesFractionalEven", "hs_5_0", null))
            using (var pnTriFractionalOddBytecode = HLSLCompiler.CompileFromFile(@"Shaders\TessellatePNTri.hlsl", "HS_PNTrianglesFractionalOdd", "hs_5_0", null))
            using (var pnTriDomainShaderBytecode = HLSLCompiler.CompileFromFile(@"Shaders\TessellatePNTri.hlsl", "DS_PNTriangles", "ds_5_0", null))
            {
                pnTriIntegerShader = ToDispose(new HullShader(device, pnTriIntegerBytecode));
                pnTriPow2Shader = ToDispose(new HullShader(device, pnTriPow2Bytecode));
                pnTriFractionalEvenShader = ToDispose(new HullShader(device, pnTriFractionalEvenBytecode));
                pnTriFractionalOddShader = ToDispose(new HullShader(device, pnTriFractionalOddBytecode));
                pnTriDomainShader = ToDispose(new DomainShader(device, pnTriDomainShaderBytecode));
            }

            using (var geomShaderByteCode = HLSLCompiler.CompileFromFile(@"Shaders\GS_DebugNormals.hlsl", "GSMain", "gs_5_0", null))
            {
                debugNormals = ToDispose(new GeometryShader(device, geomShaderByteCode));
            }

            #endregion

            // IMPORTANT: A constant buffer's size must be a multiple of 16-bytes
            // use LayoutKind.Explicit and an explicit Size= to force this for structures
            // or alternatively add padding fields and use a LayoutKind.Sequential and Pack=1

            // Create the constant buffer that will
            // store our worldViewProjection matrix
            perObjectBuffer = ToDispose(new SharpDX.Direct3D11.Buffer(device, Utilities.SizeOf<ConstantBuffers.PerObject>(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0));

            // Create the per frame constant buffer
            // lighting / camera position
            perFrameBuffer = ToDispose(new Buffer(device, Utilities.SizeOf<ConstantBuffers.PerFrame>(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0));

            // Create the per material constant buffer
            perMaterialBuffer = ToDispose(new Buffer(device, Utilities.SizeOf<ConstantBuffers.PerMaterial>(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0));

            // Create the per armature/skeletong constant buffer
            perArmatureBuffer = ToDispose(new Buffer(device, ConstantBuffers.PerArmature.Size(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0));

            // Create the decal buffer
            decalBuffer = ToDispose(new Buffer(device, Utilities.SizeOf<ConstantBuffers.DecalBuffer>(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0));

            // Load the decal textures
            decalDiffuse = ToDispose(ShaderResourceView.FromFile(device, "Crater_Diffuse.png"));
            decalDisplacement = ToDispose(ShaderResourceView.FromFile(device, "Crater_Displacement.png"));
            decalNormal = ToDispose(ShaderResourceView.FromFile(device, "Crater_Normal.png"));

            // Configure the depth buffer to discard pixels that are
            // further than the current pixel.
            depthStencilState = ToDispose(new DepthStencilState(device,
                new DepthStencilStateDescription()
                {
                    IsDepthEnabled = true, // enable depth?
                    DepthComparison = Comparison.Less,
                    DepthWriteMask = SharpDX.Direct3D11.DepthWriteMask.All,
                    IsStencilEnabled = false,// enable stencil?
                    StencilReadMask = 0xff, // 0xff (no mask)
                    StencilWriteMask = 0xff,// 0xff (no mask)
                    // Configure FrontFace depth/stencil operations
                    FrontFace = new DepthStencilOperationDescription()
                    {
                        Comparison = Comparison.Always,
                        PassOperation = StencilOperation.Keep,
                        FailOperation = StencilOperation.Keep,
                        DepthFailOperation = StencilOperation.Increment
                    },
                    // Configure BackFace depth/stencil operations
                    BackFace = new DepthStencilOperationDescription()
                    {
                        Comparison = Comparison.Always,
                        PassOperation = StencilOperation.Keep,
                        FailOperation = StencilOperation.Keep,
                        DepthFailOperation = StencilOperation.Decrement
                    },
                }));

            // Tell the IA what the vertices will look like
            // in this case two 4-component 32bit floats
            // (32 bytes in total)
            context.InputAssembler.InputLayout = vertexLayout;

            // Set our constant buffer (to store worldViewProjection)
            context.VertexShader.SetConstantBuffer(0, perObjectBuffer);
            context.VertexShader.SetConstantBuffer(1, perFrameBuffer);
            context.VertexShader.SetConstantBuffer(2, perMaterialBuffer);
            context.VertexShader.SetConstantBuffer(3, perArmatureBuffer);

            // Set the vertex shader to run
            context.VertexShader.Set(vertexShader);

            // Set our hull shader constant buffers
            context.HullShader.SetConstantBuffer(0, perObjectBuffer);
            context.HullShader.SetConstantBuffer(1, perFrameBuffer);

            // Set default Hull Shader
            context.HullShader.Set(tessellateTriIntegerShader);

            context.DomainShader.SetConstantBuffer(0, perObjectBuffer);
            context.DomainShader.SetConstantBuffer(1, perFrameBuffer);
            context.DomainShader.SetConstantBuffer(2, perMaterialBuffer);
            context.DomainShader.Set(tessellateTriDomainShader);

            // Set gemoetry shader buffers
            context.GeometryShader.SetConstantBuffer(0, perObjectBuffer);
            context.GeometryShader.SetConstantBuffer(1, perFrameBuffer);

            // Set our pixel constant buffers
            context.PixelShader.SetConstantBuffer(1, perFrameBuffer);
            context.PixelShader.SetConstantBuffer(2, perMaterialBuffer);

            // Set the pixel shader to run
            context.PixelShader.Set(blinnPhongShader);

            // Set our depth stencil state
            context.OutputMerger.DepthStencilState = depthStencilState;

            // Add the decal buffer to the pixel, hull and domain shaders (it uses the 5th slot 0-indexed)
            context.HullShader.SetConstantBuffer(4, decalBuffer);
            context.DomainShader.SetConstantBuffer(4, decalBuffer);
            context.PixelShader.SetConstantBuffer(4, decalBuffer);

            // No culling
            context.Rasterizer.State = ToDispose(new RasterizerState(device, new RasterizerStateDescription()
            {
                FillMode = FillMode.Solid,
                CullMode = CullMode.None
            }));
        }
        protected override void CreateDeviceDependentResources(DeviceManager deviceManager)
        {
            base.CreateDeviceDependentResources(deviceManager);

            // Release all resources
            RemoveAndDispose(ref vertexShader);
            RemoveAndDispose(ref vertexShaderBytecode);
            RemoveAndDispose(ref pixelShader);
            RemoveAndDispose(ref pixelShaderBytecode);

            RemoveAndDispose(ref vertexLayout);
            RemoveAndDispose(ref worldViewProjectionBuffer);
            RemoveAndDispose(ref depthStencilState);

            // Get a reference to the Device1 instance and immediate context
            var device = deviceManager.Direct3DDevice;
            var context = deviceManager.Direct3DContext;

            ShaderFlags shaderFlags = ShaderFlags.None;
            #if DEBUG
            shaderFlags = ShaderFlags.Debug;
            #endif

            // Compile and create the vertex shader
            vertexShaderBytecode = ToDispose(ShaderBytecode.CompileFromFile("Simple.hlsl", "VSMain", "vs_5_0", shaderFlags));
            vertexShader = ToDispose(new VertexShader(device, vertexShaderBytecode));

            // Compile and create the pixel shader
            pixelShaderBytecode = ToDispose(ShaderBytecode.CompileFromFile("Simple.hlsl", "PSMain", "ps_5_0", shaderFlags));
            pixelShader = ToDispose(new PixelShader(device, pixelShaderBytecode));

            // Layout from VertexShader input signature
            vertexLayout = ToDispose(new InputLayout(device,
                vertexShaderBytecode.GetPart(ShaderBytecodePart.InputSignatureBlob),
                //ShaderSignature.GetInputSignature(vertexShaderBytecode),
                new[]
                {
                    // input semantic SV_Position = vertex coordinate in object space
                    new InputElement("SV_Position", 0, Format.R32G32B32A32_Float, 0, 0),
                    // input semantic TEXTCOORD = vertex texture coordinate
                    new InputElement("TEXCOORD", 0, Format.R32G32_Float, 16, 0)
                }));

            // Create the constant buffer that will
            // store our worldViewProjection matrix
            worldViewProjectionBuffer = ToDispose(new SharpDX.Direct3D11.Buffer(device, Utilities.SizeOf<Matrix>(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0));

            // Configure the depth buffer to discard pixels that are
            // further than the current pixel.
            depthStencilState = ToDispose(new DepthStencilState(device,
                new DepthStencilStateDescription()
                {
                    IsDepthEnabled = true, // enable depth?
                    DepthComparison = Comparison.Less,
                    DepthWriteMask = SharpDX.Direct3D11.DepthWriteMask.All,
                    IsStencilEnabled = false,// enable stencil?
                    StencilReadMask = 0xff, // 0xff (no mask)
                    StencilWriteMask = 0xff,// 0xff (no mask)
                    // Configure FrontFace depth/stencil operations
                    FrontFace = new DepthStencilOperationDescription()
                    {
                        Comparison = Comparison.Always,
                        PassOperation = StencilOperation.Keep,
                        FailOperation = StencilOperation.Keep,
                        DepthFailOperation = StencilOperation.Increment
                    },
                    // Configure BackFace depth/stencil operations
                    BackFace = new DepthStencilOperationDescription()
                    {
                        Comparison = Comparison.Always,
                        PassOperation = StencilOperation.Keep,
                        FailOperation = StencilOperation.Keep,
                        DepthFailOperation = StencilOperation.Decrement
                    },
                }));

            // Tell the IA what the vertices will look like
            // in this case two 4-component 32bit floats
            // (32 bytes in total)
            context.InputAssembler.InputLayout = vertexLayout;

            // Set our constant buffer (to store worldViewProjection)
            context.VertexShader.SetConstantBuffer(0, worldViewProjectionBuffer);

            // Set the vertex shader to run
            context.VertexShader.Set(vertexShader);

            // Set the pixel shader to run
            context.PixelShader.Set(pixelShader);

            // Set our depth stencil state
            context.OutputMerger.DepthStencilState = depthStencilState;
        }
Exemple #9
0
        public static void SaveToFile(DeviceManager deviceManager, Texture2D source, string filename, SharpDX.DXGI.Format?format = null, int subResource = 0)
        {
            var device  = deviceManager.Direct3DDevice;
            var context = deviceManager.Direct3DContext;

            var txDesc = source.Description;

            txDesc.ArraySize         = 1;
            txDesc.Usage             = ResourceUsage.Staging;
            txDesc.CpuAccessFlags    = CpuAccessFlags.Read;
            txDesc.BindFlags         = BindFlags.None;
            txDesc.OptionFlags       = ResourceOptionFlags.None;
            txDesc.SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0);

            //Guid pixelFormat = PixelFormatFromFormat(txDesc.Format);
            //if (pixelFormat == Guid.Empty)
            //{
            //    return;
            //}

            //System.Diagnostics.Debug.Assert(BitsPerPixel(txDesc.Format) == SharpDX.WIC.PixelFormat.GetBitsPerPixel(pixelFormat), "Error with DXGI.Format -> PixelFormat");

            using (var dest = new Texture2D(device, txDesc))
            {
                if (source.Description.SampleDescription.Count > 1 || source.Description.SampleDescription.Quality > 0)
                {
                    // In order to copy a multisampled texture to a CPU readable texture, it must first be resolved into a GPU only Texture
                    // Initialize a target to resolve multi-sampled render target
                    var resolvedDesc = source.Description;
                    resolvedDesc.BindFlags         = BindFlags.ShaderResource;
                    resolvedDesc.OptionFlags       = ResourceOptionFlags.None;
                    resolvedDesc.SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0);

                    // if depth stencil needs to be typeless
                    if (resolvedDesc.Format == SharpDX.DXGI.Format.D24_UNorm_S8_UInt)
                    {
                        resolvedDesc.Format = SharpDX.DXGI.Format.R24G8_Typeless;
                    }

                    using (var resolvedTarget = new Texture2D(device, resolvedDesc))
                    {
                        CopyToTexture(context, source, resolvedTarget, subResource);
                        // Now we can copy to the destination
                        CopyToTexture(context, source, dest, subResource);
                    }
                }
                else
                {
                    CopyToTexture(context, source, dest, subResource);
                }

                var sourceData = context.MapSubresource(dest, 0, MapMode.Read, MapFlags.None);

                using (SharpDX.Toolkit.Graphics.Image image = SharpDX.Toolkit.Graphics.Image.New(new SharpDX.Toolkit.Graphics.ImageDescription()
                {
                    ArraySize = 1,
                    Depth = 1,
                    Dimension = SharpDX.Toolkit.Graphics.TextureDimension.Texture2D,
                    Format = format ?? dest.Description.Format,
                    Width = source.Description.Width,
                    MipLevels = 1,
                    Height = source.Description.Height
                }, sourceData.DataPointer))
                {
                    image.Save(filename);
                }
            }
        }
Exemple #10
0
        public static System.Drawing.Bitmap SaveToBitmap(DeviceManager deviceManager, Texture2D source)
        {
            var device  = deviceManager.Direct3DDevice;
            var context = deviceManager.Direct3DContext;

            var txDesc = source.Description;

            txDesc.Usage             = ResourceUsage.Staging;
            txDesc.CpuAccessFlags    = CpuAccessFlags.Read;
            txDesc.BindFlags         = BindFlags.None;
            txDesc.OptionFlags       = ResourceOptionFlags.None;
            txDesc.SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0);

            Guid pixelFormat = PixelFormatFromFormat(txDesc.Format);

            if (pixelFormat == Guid.Empty)
            {
                return(null);
            }

            System.Diagnostics.Debug.Assert(BitsPerPixel(txDesc.Format) == SharpDX.WIC.PixelFormat.GetBitsPerPixel(pixelFormat), "Error with DXGI.Format -> PixelFormat");

            using (var dest = new Texture2D(device, txDesc))
            {
                if (source.Description.SampleDescription.Count > 1 || source.Description.SampleDescription.Quality > 0)
                {
                    // In order to copy a multisampled texture to a CPU readable texture, it must first be resolved into a GPU only Texture
                    // Initialize a target to resolve multi-sampled render target
                    var resolvedDesc = source.Description;
                    resolvedDesc.BindFlags         = BindFlags.ShaderResource;
                    resolvedDesc.SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0);

                    // if depth stencil needs to be typeless
                    if (resolvedDesc.Format == SharpDX.DXGI.Format.D24_UNorm_S8_UInt)
                    {
                        resolvedDesc.Format = SharpDX.DXGI.Format.R24G8_Typeless;
                    }

                    using (var resolvedTarget = new Texture2D(device, resolvedDesc))
                    {
                        CopyToTexture(context, source, resolvedTarget);
                        // Now we can copy to the destination
                        CopyToTexture(context, source, dest);
                    }
                }
                else
                {
                    CopyToTexture(context, source, dest);
                }

                int width  = txDesc.Width;
                int height = txDesc.Height;
                // Get the desktop capture texture
                var mapSource = device.ImmediateContext.MapSubresource(dest, 0, MapMode.Read, MapFlags.None);

                // Create Drawing.Bitmap
                var bitmap     = new System.Drawing.Bitmap(width, height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
                var boundsRect = new System.Drawing.Rectangle(0, 0, width, height);

                // Copy pixels from screen capture Texture to GDI bitmap
                var mapDest   = bitmap.LockBits(boundsRect, System.Drawing.Imaging.ImageLockMode.WriteOnly, bitmap.PixelFormat);
                var sourcePtr = mapSource.DataPointer;
                var destPtr   = mapDest.Scan0;
                for (int y = 0; y < height; y++)
                {
                    // Copy a single line
                    SharpDX.Utilities.CopyMemory(destPtr, sourcePtr, width * 4);

                    // Advance pointers
                    sourcePtr = IntPtr.Add(sourcePtr, mapSource.RowPitch);
                    destPtr   = IntPtr.Add(destPtr, mapDest.Stride);
                }

                // Release source and dest locks
                bitmap.UnlockBits(mapDest);
                device.ImmediateContext.UnmapSubresource(dest, 0);

                return(bitmap);
            }
        }
        public static SharpDX.WIC.Bitmap SaveToWICBitmap(DeviceManager deviceManager, Texture2D source)
        {
            var device = deviceManager.Direct3DDevice;
            var context = deviceManager.Direct3DContext;

            var txDesc = source.Description;

            txDesc.Usage = ResourceUsage.Staging;
            txDesc.CpuAccessFlags = CpuAccessFlags.Read;
            txDesc.BindFlags = BindFlags.None;
            txDesc.OptionFlags = ResourceOptionFlags.None;
            txDesc.SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0);

            Guid pixelFormat = PixelFormatFromFormat(txDesc.Format);
            if (pixelFormat == Guid.Empty)
            {
                return null;
            }

            System.Diagnostics.Debug.Assert(BitsPerPixel(txDesc.Format) == SharpDX.WIC.PixelFormat.GetBitsPerPixel(pixelFormat), "Error with DXGI.Format -> PixelFormat");

            using (var dest = new Texture2D(device, txDesc))
            {
                if (source.Description.SampleDescription.Count > 1 || source.Description.SampleDescription.Quality > 0)
                {
                    // In order to copy a multisampled texture to a CPU readable texture, it must first be resolved into a GPU only Texture
                    // Initialize a target to resolve multi-sampled render target
                    var resolvedDesc = source.Description;
                    resolvedDesc.BindFlags = BindFlags.ShaderResource;
                    resolvedDesc.SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0);

                    // if depth stencil needs to be typeless
                    if (resolvedDesc.Format == SharpDX.DXGI.Format.D24_UNorm_S8_UInt)
                        resolvedDesc.Format = SharpDX.DXGI.Format.R24G8_Typeless;

                    using (var resolvedTarget = new Texture2D(device, resolvedDesc))
                    {
                        CopyToTexture(context, source, resolvedTarget);
                        // Now we can copy to the destination
                        CopyToTexture(context, source, dest);
                    }
                }
                else
                    CopyToTexture(context, source, dest);
                var sourceData = context.MapSubresource(dest, 0, MapMode.Read, MapFlags.None);

                var encoder = new SharpDX.WIC.PngBitmapEncoder(deviceManager.WICFactory);

                var formatConverter = new SharpDX.WIC.FormatConverter(deviceManager.WICFactory);

                SharpDX.WIC.Bitmap bm = new SharpDX.WIC.Bitmap(deviceManager.WICFactory, txDesc.Width, txDesc.Height, pixelFormat, SharpDX.WIC.BitmapCreateCacheOption.CacheOnLoad);

                var bytesPerPixel = BitsPerPixel(txDesc.Format) / 8;
                using (var l = bm.Lock(SharpDX.WIC.BitmapLockFlags.Write))
                {
                    var destPtr = l.Data.DataPointer;
                    var sourcePtr = sourceData.DataPointer;
                    for (int y = 0; y < bm.Size.Height; y++)
                    {
                        SharpDX.Utilities.CopyMemory(destPtr, sourcePtr, bm.Size.Width * bytesPerPixel);

                        sourcePtr = IntPtr.Add(sourcePtr, sourceData.RowPitch);
                        destPtr = IntPtr.Add(destPtr, l.Data.Pitch);
                    }
                }
                context.UnmapSubresource(dest, 0);

                return bm;
            }
        }
        public static void SaveToFile(DeviceManager deviceManager, Texture2D source, string filename, SharpDX.DXGI.Format? format = null, int subResource = 0)
        {
            var device = deviceManager.Direct3DDevice;
            var context = deviceManager.Direct3DContext;

            var txDesc = source.Description;
            txDesc.ArraySize = 1;
            txDesc.Usage = ResourceUsage.Staging;
            txDesc.CpuAccessFlags = CpuAccessFlags.Read;
            txDesc.BindFlags = BindFlags.None;
            txDesc.OptionFlags = ResourceOptionFlags.None;
            txDesc.SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0);

            //Guid pixelFormat = PixelFormatFromFormat(txDesc.Format);
            //if (pixelFormat == Guid.Empty)
            //{
            //    return;
            //}

            //System.Diagnostics.Debug.Assert(BitsPerPixel(txDesc.Format) == SharpDX.WIC.PixelFormat.GetBitsPerPixel(pixelFormat), "Error with DXGI.Format -> PixelFormat");

            using (var dest = new Texture2D(device, txDesc))
            {
                if (source.Description.SampleDescription.Count > 1 || source.Description.SampleDescription.Quality > 0)
                {
                    // In order to copy a multisampled texture to a CPU readable texture, it must first be resolved into a GPU only Texture
                    // Initialize a target to resolve multi-sampled render target
                    var resolvedDesc = source.Description;
                    resolvedDesc.BindFlags = BindFlags.ShaderResource;
                    resolvedDesc.OptionFlags = ResourceOptionFlags.None;
                    resolvedDesc.SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0);

                    // if depth stencil needs to be typeless
                    if (resolvedDesc.Format == SharpDX.DXGI.Format.D24_UNorm_S8_UInt)
                        resolvedDesc.Format = SharpDX.DXGI.Format.R24G8_Typeless;

                    using (var resolvedTarget = new Texture2D(device, resolvedDesc))
                    {
                        CopyToTexture(context, source, resolvedTarget, subResource);
                        // Now we can copy to the destination
                        CopyToTexture(context, source, dest, subResource);
                    }
                }
                else
                    CopyToTexture(context, source, dest, subResource);

                var sourceData = context.MapSubresource(dest, 0, MapMode.Read, MapFlags.None);

                using (SharpDX.Toolkit.Graphics.Image image = SharpDX.Toolkit.Graphics.Image.New(new SharpDX.Toolkit.Graphics.ImageDescription()
                {
                    ArraySize = 1,
                    Depth = 1,
                    Dimension = SharpDX.Toolkit.Graphics.TextureDimension.Texture2D,
                    Format = format ?? dest.Description.Format,
                    Width = source.Description.Width,
                    MipLevels = 1,
                    Height = source.Description.Height
                }, sourceData.DataPointer))
                {
                    image.Save(filename);
                }
            }
        }
        public static System.Drawing.Bitmap SaveToBitmap(DeviceManager deviceManager, Texture2D source)
        {
            var device = deviceManager.Direct3DDevice;
            var context = deviceManager.Direct3DContext;

            var txDesc = source.Description;
            txDesc.Usage = ResourceUsage.Staging;
            txDesc.CpuAccessFlags = CpuAccessFlags.Read;
            txDesc.BindFlags = BindFlags.None;
            txDesc.OptionFlags = ResourceOptionFlags.None;
            txDesc.SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0);

            Guid pixelFormat = PixelFormatFromFormat(txDesc.Format);
            if (pixelFormat == Guid.Empty)
            {
                return null;
            }

            System.Diagnostics.Debug.Assert(BitsPerPixel(txDesc.Format) == SharpDX.WIC.PixelFormat.GetBitsPerPixel(pixelFormat), "Error with DXGI.Format -> PixelFormat");

            using (var dest = new Texture2D(device, txDesc))
            {
                if (source.Description.SampleDescription.Count > 1 || source.Description.SampleDescription.Quality > 0)
                {
                    // In order to copy a multisampled texture to a CPU readable texture, it must first be resolved into a GPU only Texture
                    // Initialize a target to resolve multi-sampled render target
                    var resolvedDesc = source.Description;
                    resolvedDesc.BindFlags = BindFlags.ShaderResource;
                    resolvedDesc.SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0);

                    // if depth stencil needs to be typeless
                    if (resolvedDesc.Format == SharpDX.DXGI.Format.D24_UNorm_S8_UInt)
                        resolvedDesc.Format = SharpDX.DXGI.Format.R24G8_Typeless;

                    using (var resolvedTarget = new Texture2D(device, resolvedDesc))
                    {
                        CopyToTexture(context, source, resolvedTarget);
                        // Now we can copy to the destination
                        CopyToTexture(context, source, dest);
                    }
                }
                else
                    CopyToTexture(context, source, dest);

                int width = txDesc.Width;
                int height = txDesc.Height;
                // Get the desktop capture texture
                var mapSource = device.ImmediateContext.MapSubresource(dest, 0, MapMode.Read, MapFlags.None);

                // Create Drawing.Bitmap
                var bitmap = new System.Drawing.Bitmap(width, height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
                var boundsRect = new System.Drawing.Rectangle(0, 0, width, height);

                // Copy pixels from screen capture Texture to GDI bitmap
                var mapDest = bitmap.LockBits(boundsRect, System.Drawing.Imaging.ImageLockMode.WriteOnly, bitmap.PixelFormat);
                var sourcePtr = mapSource.DataPointer;
                var destPtr = mapDest.Scan0;
                for (int y = 0; y < height; y++)
                {
                    // Copy a single line
                    SharpDX.Utilities.CopyMemory(destPtr, sourcePtr, width * 4);

                    // Advance pointers
                    sourcePtr = IntPtr.Add(sourcePtr, mapSource.RowPitch);
                    destPtr = IntPtr.Add(destPtr, mapDest.Stride);
                }

                // Release source and dest locks
                bitmap.UnlockBits(mapDest);
                device.ImmediateContext.UnmapSubresource(dest, 0);

                return bitmap;
            }
        }
        public static void SaveBitmap(DeviceManager dev, SharpDX.WIC.Bitmap bm, string filename)
        {
            System.Diagnostics.Debug.Assert(bm != null);
            Guid containerFormat = Guid.Empty;
            string lowerName = filename.ToLower();
            if (lowerName.Contains(".png"))
                containerFormat = SharpDX.WIC.ContainerFormatGuids.Png;
            else if (lowerName.Contains(".bmp"))
                containerFormat = SharpDX.WIC.ContainerFormatGuids.Bmp;
            else if (lowerName.Contains(".jpg"))
                containerFormat = SharpDX.WIC.ContainerFormatGuids.Jpeg;
            else if (lowerName.Contains(".jpeg"))
                containerFormat = SharpDX.WIC.ContainerFormatGuids.Jpeg;
            else if (lowerName.Contains(".tif"))
                containerFormat = SharpDX.WIC.ContainerFormatGuids.Tiff;
            else if (lowerName.Contains(".gif"))
                containerFormat = SharpDX.WIC.ContainerFormatGuids.Gif;

            Guid format = bm.PixelFormat;
            using (var stream = System.IO.File.OpenWrite(filename))
            {
                stream.Position = 0;
                using (SharpDX.WIC.BitmapEncoder enc = new SharpDX.WIC.BitmapEncoder(dev.WICFactory, containerFormat, stream))
                using (SharpDX.WIC.BitmapFrameEncode bfe = new SharpDX.WIC.BitmapFrameEncode(enc))
                {
                    bfe.Initialize();
                    bfe.SetPixelFormat(ref format);
                    bfe.SetSize(bm.Size.Width, bm.Size.Height);
                    bfe.WriteSource(bm);
                    bfe.Commit();
                    enc.Commit();
                }
            }
        }
 public static ShaderResourceView SRVFromFile(DeviceManager manager, string fileName)
 {
     ShaderResourceView srv = null;
     using (var texture = LoadFromFile(manager, fileName, out srv))
     { }
     return srv;
 }
Exemple #16
0
        public static SharpDX.WIC.Bitmap SaveToWICBitmap(DeviceManager deviceManager, Texture2D source)
        {
            var device  = deviceManager.Direct3DDevice;
            var context = deviceManager.Direct3DContext;

            var txDesc = source.Description;

            txDesc.Usage             = ResourceUsage.Staging;
            txDesc.CpuAccessFlags    = CpuAccessFlags.Read;
            txDesc.BindFlags         = BindFlags.None;
            txDesc.OptionFlags       = ResourceOptionFlags.None;
            txDesc.SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0);

            Guid pixelFormat = PixelFormatFromFormat(txDesc.Format);

            if (pixelFormat == Guid.Empty)
            {
                return(null);
            }

            System.Diagnostics.Debug.Assert(BitsPerPixel(txDesc.Format) == SharpDX.WIC.PixelFormat.GetBitsPerPixel(pixelFormat), "Error with DXGI.Format -> PixelFormat");

            using (var dest = new Texture2D(device, txDesc))
            {
                if (source.Description.SampleDescription.Count > 1 || source.Description.SampleDescription.Quality > 0)
                {
                    // In order to copy a multisampled texture to a CPU readable texture, it must first be resolved into a GPU only Texture
                    // Initialize a target to resolve multi-sampled render target
                    var resolvedDesc = source.Description;
                    resolvedDesc.BindFlags         = BindFlags.ShaderResource;
                    resolvedDesc.SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0);

                    // if depth stencil needs to be typeless
                    if (resolvedDesc.Format == SharpDX.DXGI.Format.D24_UNorm_S8_UInt)
                    {
                        resolvedDesc.Format = SharpDX.DXGI.Format.R24G8_Typeless;
                    }

                    using (var resolvedTarget = new Texture2D(device, resolvedDesc))
                    {
                        CopyToTexture(context, source, resolvedTarget);
                        // Now we can copy to the destination
                        CopyToTexture(context, source, dest);
                    }
                }
                else
                {
                    CopyToTexture(context, source, dest);
                }
                var sourceData = context.MapSubresource(dest, 0, MapMode.Read, MapFlags.None);

                var encoder = new SharpDX.WIC.PngBitmapEncoder(deviceManager.WICFactory);

                var formatConverter = new SharpDX.WIC.FormatConverter(deviceManager.WICFactory);


                SharpDX.WIC.Bitmap bm = new SharpDX.WIC.Bitmap(deviceManager.WICFactory, txDesc.Width, txDesc.Height, pixelFormat, SharpDX.WIC.BitmapCreateCacheOption.CacheOnLoad);

                var bytesPerPixel = BitsPerPixel(txDesc.Format) / 8;
                using (var l = bm.Lock(SharpDX.WIC.BitmapLockFlags.Write))
                {
                    var destPtr   = l.Data.DataPointer;
                    var sourcePtr = sourceData.DataPointer;
                    for (int y = 0; y < bm.Size.Height; y++)
                    {
                        SharpDX.Utilities.CopyMemory(destPtr, sourcePtr, bm.Size.Width * bytesPerPixel);

                        sourcePtr = IntPtr.Add(sourcePtr, sourceData.RowPitch);
                        destPtr   = IntPtr.Add(destPtr, l.Data.Pitch);
                    }
                }
                context.UnmapSubresource(dest, 0);

                return(bm);
            }
        }
Exemple #17
0
        // Example using async
        protected async override void CreateDeviceDependentResources(Common.DeviceManager deviceManager)
        {
            ResourcesLoaded = false;
            base.CreateDeviceDependentResources(deviceManager);

            RemoveAndDispose(ref fpsRenderer);
            RemoveAndDispose(ref textRenderer);

            RemoveAndDispose(ref vertexShader);
            RemoveAndDispose(ref vertexLayout);
            RemoveAndDispose(ref pixelShader);

            foreach (var m in meshRenderers)
            {
                var m2 = m;
                RemoveAndDispose(ref m2);
            }
            meshRenderers.Clear();

            var device = deviceManager.Direct3DDevice;

            #region Compile shaders
            // Compile Vertex Shader and create vertex InputLayout
            using (var bytecode = await HLSLCompiler.CompileFromFileAsync(@"Shaders\VS.hlsl", "VSMain", "vs_5_0"))
            {
                vertexShader = new VertexShader(device, bytecode);
                vertexLayout = ToDispose(new InputLayout(device,
                                                         bytecode.GetPart(ShaderBytecodePart.InputSignatureBlob).Data,
                                                         new[]
                {
                    // "SV_Position" = vertex coordinate in object space
                    new InputElement("SV_Position", 0, Format.R32G32B32_Float, 0, 0),
                    // "NORMAL" = the vertex normal
                    new InputElement("NORMAL", 0, Format.R32G32B32_Float, 12, 0),
                    // "COLOR"
                    new InputElement("COLOR", 0, Format.R8G8B8A8_UNorm, 24, 0),
                    // "UV"
                    new InputElement("TEXCOORD", 0, Format.R32G32_Float, 28, 0),
                    // "BLENDINDICES"
                    new InputElement("BLENDINDICES", 0, Format.R32G32B32A32_UInt, 36, 0),
                    // "BLENDWEIGHT"
                    new InputElement("BLENDWEIGHT", 0, Format.R32G32B32A32_Float, 52, 0),
                }));
            }

            // Compile pixel shader
            using (var bytecode = await HLSLCompiler.CompileFromFileAsync(@"Shaders\BlinnPhongPS.hlsl", "PSMain", "ps_5_0"))
                pixelShader = ToDispose(new PixelShader(device, bytecode));
            #endregion

            #region Create constant buffers
            // Create constant buffers

            // Create the constant buffer that will
            // store our worldViewProjection matrix
            perObjectBuffer = ToDispose(new SharpDX.Direct3D11.Buffer(device, Utilities.SizeOf <ConstantBuffers.PerObject>(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0));

            // Create the per frame constant buffer
            // lighting / camera position
            perFrameBuffer = ToDispose(new Buffer(device, Utilities.SizeOf <ConstantBuffers.PerFrame>(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0));

            // Create the per material constant buffer
            perMaterialBuffer = ToDispose(new Buffer(device, Utilities.SizeOf <ConstantBuffers.PerMaterial>(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0));

            // Create the per armature/skeletong constant buffer
            perArmatureBuffer = ToDispose(new Buffer(device, ConstantBuffers.PerArmature.Size(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0));

            #endregion

            #region Create pipeline state variables
            // Configure the depth buffer to discard pixels that are
            // further than the current pixel.
            depthStencilState = ToDispose(new DepthStencilState(device,
                                                                new DepthStencilStateDescription()
            {
                IsDepthEnabled   = true,   // enable depth?
                DepthComparison  = Comparison.Less,
                DepthWriteMask   = SharpDX.Direct3D11.DepthWriteMask.All,
                IsStencilEnabled = false,   // enable stencil?
                StencilReadMask  = 0xff,    // 0xff (no mask)
                StencilWriteMask = 0xff,    // 0xff (no mask)
            }));

            rsCullBack = ToDispose(new RasterizerState(device, new RasterizerStateDescription
            {
                CullMode = CullMode.Back,
                IsFrontCounterClockwise = false,
                FillMode = FillMode.Solid,
            }));
            #endregion


            #region Create Renderers
            var meshes = await Mesh.LoadFromFileAsync("Character.cmo");

            meshRenderers.AddRange((from mesh in meshes
                                    select ToDispose(new MeshRenderer(mesh))));
            await Task.Run(() =>
            {
                foreach (var m in meshRenderers)
                {
                    m.Initialize(this);
                    m.PerArmatureBuffer = perArmatureBuffer;
                    m.PerMaterialBuffer = perMaterialBuffer;

                    if (m.Mesh.Animations != null && m.Mesh.Animations.Any())
                    {
                        m.CurrentAnimation = m.Mesh.Animations.First().Value;
                    }
                    m.Clock.Start();
                }
            });

            textRenderer = ToDispose(new TextRenderer("Calibri", SharpDX.Color.Black, new Point(20, 100), 48, 800));
            textRenderer.Initialize(this);

            fpsRenderer = ToDispose(new FpsRenderer("Calibri", SharpDX.Color.CornflowerBlue, new Point(20, 20), 16));
            fpsRenderer.Initialize(this);
            #endregion

            clock.Start();
            ResourcesLoaded = true;
        }
        /// <summary>
        /// Create device dependent resources
        /// </summary>
        /// <param name="deviceManager"></param>
        protected virtual void CreateDeviceDependentResources(DeviceManager deviceManager)
        {
            if (_swapChain != null)
            {
                // Release the swap chain
                RemoveAndDispose(ref _swapChain);

                // Force reinitialize size dependent resources
                SizeChanged(true);
            }
        }