예제 #1
0
        public Fragment LoadFragment(string fileName, InputElement[] inputElements)
        {
            Fragment result = new Fragment();

            ShaderBytecode vertexShaderByteCode = null;
            ShaderBytecode pixelShaderByteCode  = null;

            Assembly assembly = Assembly.GetExecutingAssembly();

            using (Stream streamPS = assembly.GetManifestResourceStream("Profiler.DirectX.Shaders." + fileName + "_ps.fxo"))
            {
                pixelShaderByteCode = ShaderBytecode.FromStream(streamPS);
            }

            using (Stream streamVS = assembly.GetManifestResourceStream("Profiler.DirectX.Shaders." + fileName + "_vs.fxo"))
            {
                vertexShaderByteCode = ShaderBytecode.FromStream(streamVS);
            }

            result.VS = new VertexShader(RenderDevice, vertexShaderByteCode.Data);
            result.PS = new PixelShader(RenderDevice, pixelShaderByteCode.Data);

            result.Layout = new InputLayout(RenderDevice, vertexShaderByteCode, inputElements);

            vertexShaderByteCode.Dispose();
            pixelShaderByteCode.Dispose();

            return(result);
        }
예제 #2
0
        private bool InitializeShader(Device device, IntPtr hwnd, string vsFilename, string psFilename)
        {
            try
            {
                ShaderBytecode vertexShaderByteCode = ShaderBytecode.CompileFromFile(vsFilename, "PlotVertexShader", "vs_5_0", ShaderFlags.EnableStrictness, EffectFlags.None);
                ShaderBytecode pixelShaderByteCode  = ShaderBytecode.CompileFromFile(psFilename, "PlotPixelShader", "ps_5_0", ShaderFlags.EnableStrictness, EffectFlags.None);

                _vertexShader = new VertexShader(device, vertexShaderByteCode);
                _pixelShader  = new PixelShader(device, pixelShaderByteCode);

                InputElement[] inputElements = new InputElement[]
                {
                    new InputElement()
                    {
                        SemanticName         = "POSITION",
                        SemanticIndex        = 0,
                        Format               = SharpDX.DXGI.Format.R32G32B32_Float,
                        Slot                 = 0,
                        AlignedByteOffset    = 0,
                        Classification       = InputClassification.PerVertexData,
                        InstanceDataStepRate = 0
                    },
                    new InputElement()
                    {
                        SemanticName         = "COLOR",
                        SemanticIndex        = 0,
                        Format               = SharpDX.DXGI.Format.R32G32B32A32_Float,
                        Slot                 = 0,
                        AlignedByteOffset    = InputElement.AppendAligned,
                        Classification       = InputClassification.PerVertexData,
                        InstanceDataStepRate = 0
                    }
                };

                _layout = new InputLayout(device, ShaderSignature.GetInputSignature(vertexShaderByteCode), inputElements);

                vertexShaderByteCode.Dispose();
                pixelShaderByteCode.Dispose();

                BufferDescription constantBufferDesc = new BufferDescription()
                {
                    Usage               = ResourceUsage.Dynamic,
                    SizeInBytes         = Utilities.SizeOf <MatrixBufferType>(), // was Matrix
                    BindFlags           = BindFlags.ConstantBuffer,
                    CpuAccessFlags      = CpuAccessFlags.Write,
                    OptionFlags         = ResourceOptionFlags.None,
                    StructureByteStride = 0
                };

                _matrixBuffer = new SharpDX.Direct3D11.Buffer(device, constantBufferDesc);

                return(true);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error initializing shader. Error is " + ex.Message);
                return(false);
            }
        }
예제 #3
0
 public void Dispose()
 {
     inputLayout.Dispose();
     vertexShaderByteCode.Dispose();
     pixelShaderByteCode.Dispose();
     pixelShader.Dispose();
     vertexShader.Dispose();
 }
예제 #4
0
 protected virtual void Dispose(bool disposeManaged)
 {
     if (bytecode != null)
     {
         bytecode.Dispose();
         bytecode = null;
     }
 }
        private bool InitializeShader(Device device, IntPtr windowsHandle, string vsFileName, string psFileName)
        {
            try
            {
                vsFileName = DSystemConfiguration.ShaderFilePath + vsFileName;
                psFileName = DSystemConfiguration.ShaderFilePath + psFileName;
                ShaderBytecode vertexShaderByteCode = ShaderBytecode.CompileFromFile(vsFileName, "ColorVertexShader", "vs_4_0", ShaderFlags.None, EffectFlags.None);
                ShaderBytecode pixelShaderByteCode  = ShaderBytecode.CompileFromFile(psFileName, "ColorPixelShader", "ps_4_0", ShaderFlags.None, EffectFlags.None);
                VertexShader = new VertexShader(device, vertexShaderByteCode);
                PixelShader  = new PixelShader(device, pixelShaderByteCode);

                InputElement[] inputElements = new InputElement[]
                {
                    new InputElement()
                    {
                        SemanticName         = "POSITION",
                        SemanticIndex        = 0,
                        Format               = SharpDX.DXGI.Format.R32G32B32_Float,
                        Slot                 = 0,
                        AlignedByteOffset    = 0,
                        Classification       = InputClassification.PerVertexData,
                        InstanceDataStepRate = 0
                    },
                    new InputElement()
                    {
                        SemanticName         = "COLOR",
                        SemanticIndex        = 0,
                        Format               = SharpDX.DXGI.Format.R32G32B32A32_Float,
                        Slot                 = 0,
                        AlignedByteOffset    = InputElement.AppendAligned,
                        Classification       = InputClassification.PerVertexData,
                        InstanceDataStepRate = 0
                    }
                };

                Layout = new InputLayout(device, ShaderSignature.GetInputSignature(vertexShaderByteCode), inputElements);
                vertexShaderByteCode.Dispose();
                pixelShaderByteCode.Dispose();
                BufferDescription matrixBufDesc = new BufferDescription()
                {
                    Usage               = ResourceUsage.Dynamic,
                    SizeInBytes         = Utilities.SizeOf <DMatrixBuffer>(), // was Matrix
                    BindFlags           = BindFlags.ConstantBuffer,
                    CpuAccessFlags      = CpuAccessFlags.Write,
                    OptionFlags         = ResourceOptionFlags.None,
                    StructureByteStride = 0
                };
                ConstantMatrixBuffer = new SharpDX.Direct3D11.Buffer(device, matrixBufDesc);

                return(true);
            }
            catch
            {
                return(false);
            }
        }
예제 #6
0
        public void CleanUp()
        {
            vsByteCode.Dispose();
            vShader.Dispose();
            psByteCode.Dispose();
            pShader.Dispose();

            vertices.Dispose();
            layout.Dispose();
        }
 public Effect LoadEffect(string fileName)
 {
     if (!effects_.ContainsKey(fileName))
     {
         ShaderBytecode sb     = ShaderBytecode.CompileFromFile(fileName, "fx_5_0", ShaderFlags.None, EffectFlags.None);
         Effect         effect = new Effect(m_device, sb);
         effects_.Add(fileName, effect);
         sb.Dispose();
     }
     return(effects_[fileName]);
 }
예제 #8
0
 public void Dispose()
 {
     if (E == null)
     {
         return;
     }
     InputSignaturePT.Dispose();
     LayoutPT.Dispose();
     E.Dispose();
     _b.Dispose();
 }
예제 #9
0
 protected sealed override void DisposeResource()
 {
     try
     {
         Deallocate();
     }
     finally
     {
         mBytecode?.Dispose();
         mBytecode = null;
     }
 }
예제 #10
0
        private static void LoadShaders()
        {
            ShaderBytecode bytecode = null;

            bytecode = ShaderBytecode.CompileFromFile("Shaders.fx", null, "fx_5_0", ShaderFlags.None, EffectFlags.None, null, null);
            fx       = new Effect(device, bytecode);
            bytecode.Dispose();
            techniqueTextured = fx.GetTechniqueByName("Textured");
            techniqueSelected = fx.GetTechniqueByName("Selected");
            techniqueColor    = fx.GetTechniqueByName("Color");
            WVP   = fx.GetVariableByName("WVP").AsMatrix();
            fxTex = fx.GetVariableByName("tex").AsResource();
        }
예제 #11
0
        public virtual bool Init(Device device, ShaderInitParams InitParams)
        {
            // Attempt to construct pixel shader
            if (InitParams.PixelShaderFile.IsValid())
            {
                ShaderBytecode PixelBytecode = ConstructBytecode(InitParams.PixelShaderFile);
                OurPixelShader = new PixelShader(device, PixelBytecode);
                PixelBytecode.Dispose();
            }

            // Attempt to construct vertex shader
            if (InitParams.VertexShaderFile.IsValid())
            {
                ShaderBytecode VertexBytecode = ConstructBytecode(InitParams.VertexShaderFile);
                OurVertexShader = new VertexShader(device, VertexBytecode);
                Layout          = new InputLayout(device, ShaderSignature.GetInputSignature(VertexBytecode), InitParams.Elements);
                VertexBytecode.Dispose();
            }

            // Attempt to construct geometry shader
            if (InitParams.GeometryShaderFile.IsValid())
            {
                ShaderBytecode GeometryBytecode = ConstructBytecode(InitParams.GeometryShaderFile);
                OurGeometryShader = new GeometryShader(device, GeometryBytecode);
                GeometryBytecode.Dispose();
            }

            SamplerStateDescription samplerDesc = new SamplerStateDescription()
            {
                Filter             = Filter.Anisotropic,
                AddressU           = TextureAddressMode.Wrap,
                AddressV           = TextureAddressMode.Wrap,
                AddressW           = TextureAddressMode.Wrap,
                MipLodBias         = 0,
                MaximumAnisotropy  = 8,
                ComparisonFunction = Comparison.Always,
                BorderColor        = new Color4(0, 0, 0, 0),
                MinimumLod         = 0,
                MaximumLod         = 0
            };

            SamplerState = new SamplerState(device, samplerDesc);

            ConstantCameraBuffer       = ConstantBufferFactory.ConstructBuffer <DCameraBuffer>(device, "CameraBuffer");
            ConstantLightBuffer        = ConstantBufferFactory.ConstructBuffer <LightBuffer>(device, "LightBuffer");
            ConstantMatrixBuffer       = ConstantBufferFactory.ConstructBuffer <MatrixBuffer>(device, "MatrixBuffer");
            ConstantEditorParamsBuffer = ConstantBufferFactory.ConstructBuffer <EditorParameterBuffer>(device, "EditorBuffer");

            return(true);
        }
예제 #12
0
        /// <summary>
        /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
        /// </summary>
        public virtual void Dispose()
        {
            ShaderBytecode byteCode = Interlocked.Exchange(ref _byteCode, null);

            if (byteCode == null)
            {
                this.UnregisterDisposable(Graphics);
                GC.SuppressFinalize(this);
                return;
            }

            Graphics.Log.Print("Destroying shader byte code.", LoggingLevel.Verbose);
            byteCode.Dispose();

            this.UnregisterDisposable(Graphics);

            GC.SuppressFinalize(this);
        }
예제 #13
0
 public void Dispose()
 {
     _shaderSignature?.Dispose();
     _vertexShaderByteCode?.Dispose();
     _vertexShader?.Dispose();
     _pixelShaderByteCode?.Dispose();
     _pixelShader?.Dispose();
     _verticesBuffer?.Dispose();
     _inputLayout?.Dispose();
     _contantBuffer?.Dispose();
     _depthBuffer?.Dispose();
     _depthView?.Dispose();
     _context?.ClearState();
     _context?.Flush();
     _swapChain?.Dispose();
     _renderView?.Dispose();
     _backBuffer?.Dispose();
     _device?.Dispose();
     _context?.Dispose();
     _factory?.Dispose();
 }
예제 #14
0
        public int CompileSingleFile(string src_file_path, string des_file_path)
        {
            switch (this.CheckShaderType(src_file_path))
            {
            // invalid file type
            case ShaderType.Nope:
                break;

            // vertex shader
            case ShaderType.VertexShader:
            {
                ShaderBytecode vertexByteCode = ShaderBytecode.CompileFromFile(src_file_path, shaderEntryName,
                                                                               "vs_4_0", ShaderFlags.None, EffectFlags.None);
                string[] fileNameSpilt = src_file_path.Split('\\');
                this.WriteCsoFile(vertexByteCode.Data,
                                  String.Concat(des_file_path, "\\", fileNameSpilt[fileNameSpilt.Length - 1].Split('.')[0]));
                vertexByteCode.Dispose();
#if GENERATE_MSG
                Console.WriteLine("{0} compilation done.", src_file_path);
#endif
            }
            break;

            case ShaderType.PixelShader:
            {
                ShaderBytecode pixelByteCode = ShaderBytecode.CompileFromFile(src_file_path, shaderEntryName,
                                                                              "ps_4_0", ShaderFlags.None, EffectFlags.None);
                string[] fileNameSpilt = src_file_path.Split('\\');
                this.WriteCsoFile(pixelByteCode.Data,
                                  String.Concat(des_file_path, "\\", fileNameSpilt[fileNameSpilt.Length - 1].Split('.')[0]));
                pixelByteCode.Dispose();
#if GENERATE_MSG
                Console.WriteLine("{0} compilation done.", src_file_path);
#endif
            }
            break;
            }
            return(0);
        }
예제 #15
0
        internal Shader(Device device, string shaderFile, string[] includePaths)
        {
            var shaderContent = File.ReadAllText(shaderFile);
            var shaderData    = JsonConvert.DeserializeObject <ShaderData>(shaderContent);

            var shaderDir = Path.GetDirectoryName(shaderFile);

            var shaderInclude = new ShaderInclude(includePaths);

            var vertexMacros = new List <ShaderMacro> {
                new ShaderMacro("VERTEX_SHADER", 1)
            };
            var pixelMacros = new List <ShaderMacro> {
                new ShaderMacro("PIXEL_SHADER", 1)
            };

            ZWrite     = shaderData.ZWrite;
            WriteMask  = shaderData.WriteMask;
            Instancing = shaderData.Instancing;
            if (Instancing)
            {
                vertexMacros.Add(new ShaderMacro("INSTANCING", 1));
                pixelMacros.Add(new ShaderMacro("INSTANCING", 1));
            }

            ShaderBytecode vertexShaderByteCode = ShaderBytecode.CompileFromFile(shaderDir + "/" + shaderData.Vertex.Path, shaderData.Vertex.Entry, "vs_5_0", ShaderFlags.None, EffectFlags.None, vertexMacros.ToArray(), shaderInclude);
            ShaderBytecode pixelShaderByteCode  = ShaderBytecode.CompileFromFile(shaderDir + "/" + shaderData.Pixel.Path, shaderData.Pixel.Entry, "ps_5_0", ShaderFlags.None, EffectFlags.None, pixelMacros.ToArray(), shaderInclude);

            InputElement[] inputElements = LoadInputs(shaderData.Vertex.Input, shaderData.Instancing);
            ShaderInputLayout = new InputLayout(device, ShaderSignature.GetInputSignature(vertexShaderByteCode), inputElements);

            VertexShader = new VertexShader(device, vertexShaderByteCode);
            PixelShader  = new PixelShader(device, pixelShaderByteCode);


            vertexShaderByteCode.Dispose();
            pixelShaderByteCode.Dispose();
            this.device = device;
        }
예제 #16
0
        protected MyEffectBase(string asset)
        {
            string curdir        = System.IO.Directory.GetCurrentDirectory();
            bool   needRecompile = false;

            System.IO.Directory.SetCurrentDirectory(System.IO.Path.GetDirectoryName(MyMinerGame.Static.RootDirectoryEffects + "\\" + asset));

            SetEffectInDebug(asset);

            string sourceFX   = Path.GetFileName(asset + ".fx");
            string compiledFX = Path.GetFileName(asset + ".fxo");

            if (File.Exists(compiledFX))
            {
                if (File.Exists(sourceFX))
                {
                    DateTime compiledTime = File.GetLastWriteTime(compiledFX);
                    DateTime sourceTime   = File.GetLastWriteTime(sourceFX);
                    if (sourceTime > compiledTime)
                    {
                        needRecompile = true;
                    }
                }
            }
            else
            {
                if (File.Exists(sourceFX))
                {
                    needRecompile = true;
                }
                else
                {
                    throw new FileNotFoundException("Effect not found: " + asset);
                }
            }
            //Nepouzivat ShaderFlags.PartialPrecision, kurvi to na GeForce6600
            ShaderFlags flags = ShaderFlags.OptimizationLevel3 | ShaderFlags.SkipValidation;

            if (needRecompile)
            {
//#if DEBUG
//                flags |= ShaderFlags.Debug;
//#endif
                //m_D3DEffect = Effect.FromFile(MyMinerGameDX.Static.GraphicsDevice, sourceFX, flags);

                ShaderBytecode shaderByteCode = ShaderBytecode.CompileFromFile(sourceFX, "fx_2_0", flags);
                System.IO.Directory.SetCurrentDirectory(System.IO.Path.GetDirectoryName(MyMinerGame.Static.RootDirectoryEffects + "\\" + asset));
                shaderByteCode.Save(compiledFX);
                shaderByteCode.Dispose();
            }

            FileStream fs = File.Open(compiledFX, FileMode.Open, FileAccess.Read);

            byte[] m = new byte[fs.Length];
            fs.Read(m, 0, (int)fs.Length);
            fs.Close();
            fs.Dispose();

            m_D3DEffect = Effect.FromMemory(MyMinerGame.Static.GraphicsDevice, m, flags);

            System.IO.Directory.SetCurrentDirectory(curdir);

            Init();
        }
        private bool InitializeShader(Device device, IntPtr windowsHandler, string vsFileName, string psFileName)
        {
            try
            {
                /* vsFileName = "../../../sc_instance_shader/" + "texture.vs";
                 * psFileName = "../../../sc_instance_shader/" + "texture.ps";
                 *
                 * vertexShaderByteCode = ShaderBytecode.CompileFromFile(vsFileName, "TextureVertexShader", "vs_4_0", ShaderFlags.None, SharpDX.D3DCompiler.EffectFlags.None);
                 * pixelShaderByteCode = ShaderBytecode.CompileFromFile(psFileName, "TexturePixelShader", "ps_4_0", ShaderFlags.None, SharpDX.D3DCompiler.EffectFlags.None);
                 */


                /*
                 * if (MainWindow.is_wpf == 1)
                 * {
                 *  vsFileName = SCCoreSystems.Properties.Resources.texture1;// "../../../_sc_instance_shader/" + "texture.vs";
                 *  psFileName = SCCoreSystems.Properties.Resources.texture;// "../../../_sc_instance_shader/" + "texture.ps";
                 *
                 *   vertexShaderByteCode = ShaderBytecode.Compile(vsFileName, "TextureVertexShader", "vs_4_0", ShaderFlags.None, SharpDX.D3DCompiler.EffectFlags.None);
                 *   pixelShaderByteCode = ShaderBytecode.Compile(psFileName, "TexturePixelShader", "ps_4_0", ShaderFlags.None, SharpDX.D3DCompiler.EffectFlags.None);
                 *
                 * }
                 * else
                 * {
                 *
                 * }*/

                vsFileName = SCCoreSystems.Properties.Resources.texture1; // "../../../_sc_instance_shader/" + "texture.vs";
                psFileName = SCCoreSystems.Properties.Resources.texture;  // "../../../_sc_instance_shader/" + "texture.ps";

                vertexShaderByteCode = ShaderBytecode.Compile(vsFileName, "TextureVertexShader", "vs_4_0", ShaderFlags.None, SharpDX.D3DCompiler.EffectFlags.None);
                pixelShaderByteCode  = ShaderBytecode.Compile(psFileName, "TexturePixelShader", "ps_4_0", ShaderFlags.None, SharpDX.D3DCompiler.EffectFlags.None);



                VertexShader = new VertexShader(device, vertexShaderByteCode);
                PixelShader  = new PixelShader(device, pixelShaderByteCode);

                InputElement[] inputElements = new InputElement[]
                {
                    new InputElement()
                    {
                        SemanticName         = "POSITION",
                        SemanticIndex        = 0,
                        Format               = SharpDX.DXGI.Format.R32G32B32_Float,
                        Slot                 = 0,
                        AlignedByteOffset    = 0,
                        Classification       = InputClassification.PerVertexData,
                        InstanceDataStepRate = 0
                    },
                    new InputElement()
                    {
                        SemanticName         = "TEXCOORD",
                        SemanticIndex        = 0,
                        Format               = SharpDX.DXGI.Format.R32G32_Float,
                        Slot                 = 0,
                        AlignedByteOffset    = InputElement.AppendAligned,
                        Classification       = InputClassification.PerVertexData,
                        InstanceDataStepRate = 0
                    },
                    new InputElement()
                    {
                        SemanticName         = "COLOR",
                        SemanticIndex        = 0,
                        Format               = SharpDX.DXGI.Format.R32G32B32A32_Float,
                        Slot                 = 0,
                        AlignedByteOffset    = InputElement.AppendAligned,
                        Classification       = InputClassification.PerVertexData,
                        InstanceDataStepRate = 0
                    },
                    new InputElement()
                    {
                        SemanticName         = "NORMAL",
                        SemanticIndex        = 0,
                        Format               = SharpDX.DXGI.Format.R32G32B32_Float,
                        Slot                 = 0,
                        AlignedByteOffset    = InputElement.AppendAligned,
                        Classification       = InputClassification.PerVertexData,
                        InstanceDataStepRate = 0
                    },

                    new InputElement()
                    {
                        SemanticName         = "POSITION",
                        SemanticIndex        = 1,
                        Format               = SharpDX.DXGI.Format.R32G32B32_Float,
                        Slot                 = 1,
                        AlignedByteOffset    = 0,
                        Classification       = InputClassification.PerInstanceData,
                        InstanceDataStepRate = 1
                    },
                    new InputElement()
                    {
                        SemanticName         = "POSITION",
                        SemanticIndex        = 2,
                        Format               = SharpDX.DXGI.Format.R32G32B32_Float,
                        Slot                 = 2,
                        AlignedByteOffset    = 0,
                        Classification       = InputClassification.PerInstanceData,
                        InstanceDataStepRate = 1
                    },
                    new InputElement()
                    {
                        SemanticName         = "POSITION",
                        SemanticIndex        = 3,
                        Format               = SharpDX.DXGI.Format.R32G32B32_Float,
                        Slot                 = 3,
                        AlignedByteOffset    = 0,
                        Classification       = InputClassification.PerInstanceData,
                        InstanceDataStepRate = 1
                    },
                    new InputElement()
                    {
                        SemanticName         = "POSITION",
                        SemanticIndex        = 4,
                        Format               = SharpDX.DXGI.Format.R32G32B32_Float,
                        Slot                 = 4,
                        AlignedByteOffset    = 0,
                        Classification       = InputClassification.PerInstanceData,
                        InstanceDataStepRate = 1
                    },
                };

                Layout = new InputLayout(device, ShaderSignature.GetInputSignature(vertexShaderByteCode), inputElements);

                vertexShaderByteCode.Dispose();
                pixelShaderByteCode.Dispose();

                BufferDescription matrixBufferDescription = new BufferDescription()
                {
                    Usage               = ResourceUsage.Dynamic,
                    SizeInBytes         = Utilities.SizeOf <DMatrixBuffer>(),
                    BindFlags           = BindFlags.ConstantBuffer,
                    CpuAccessFlags      = CpuAccessFlags.Write,
                    OptionFlags         = ResourceOptionFlags.None,
                    StructureByteStride = 0
                };

                ConstantMatrixBuffer = new SharpDX.Direct3D11.Buffer(device, matrixBufferDescription);

                SamplerStateDescription samplerDesc = new SamplerStateDescription()
                {
                    Filter             = Filter.MinMagMipLinear,
                    AddressU           = TextureAddressMode.Wrap,
                    AddressV           = TextureAddressMode.Wrap,
                    AddressW           = TextureAddressMode.Wrap,
                    MipLodBias         = 0,
                    MaximumAnisotropy  = 1,
                    ComparisonFunction = Comparison.Always,
                    BorderColor        = new Color4(0, 0, 0, 0),
                    MinimumLod         = 0,
                    MaximumLod         = float.MaxValue
                };

                SamplerState = new SamplerState(device, samplerDesc);

                return(true);
            }
            catch (Exception ex)
            {
                return(false);
            }
        }
예제 #18
0
        private bool InitializeShader(Device device, IntPtr windowHandler, string vsFileName, string psFileName)
        {
            try
            {
                // Setup full pathes
                vsFileName = SystemConfiguration.ShaderFilePath + vsFileName;
                psFileName = SystemConfiguration.ShaderFilePath + psFileName;

                // Compile the Vertex & Pixel Shader code.
                ShaderBytecode vertexShaderByteCode = ShaderBytecode.CompileFromFile(vsFileName, "SkyPlaneVertexShader", SystemConfiguration.VertexShaderProfile, ShaderFlags.None, EffectFlags.None);
                ShaderBytecode pixelShaderByteCode  = ShaderBytecode.CompileFromFile(psFileName, "SkyPlanePixelShader", SystemConfiguration.PixelShaderProfile, ShaderFlags.None, EffectFlags.None);

                // Create the Vertex & Pixel Shader from the buffer.
                VertexShader = new VertexShader(device, vertexShaderByteCode);
                PixelShader  = new PixelShader(device, pixelShaderByteCode);

                // Create the vertex input layout description.
                InputElement[] inputElements = new InputElement[]
                {
                    new InputElement()
                    {
                        SemanticName         = "POSITION",
                        SemanticIndex        = 0,
                        Format               = SharpDX.DXGI.Format.R32G32B32_Float,
                        Slot                 = 0,
                        AlignedByteOffset    = 0,
                        Classification       = InputClassification.PerVertexData,
                        InstanceDataStepRate = 0
                    },
                    new InputElement()
                    {
                        SemanticName         = "TEXCOORD",
                        SemanticIndex        = 0,
                        Format               = SharpDX.DXGI.Format.R32G32_Float,
                        Slot                 = 0,
                        AlignedByteOffset    = InputElement.AppendAligned,
                        Classification       = InputClassification.PerVertexData,
                        InstanceDataStepRate = 0
                    },
                };

                // Create the vertex input the layout.
                Layout = new InputLayout(device, ShaderSignature.GetInputSignature(vertexShaderByteCode), inputElements);

                // Release the vertex and pixel shader buffers, since they are no longer needed.
                vertexShaderByteCode.Dispose();
                pixelShaderByteCode.Dispose();

                // Create a texture sampler state description.
                SamplerStateDescription samplerDesc = new SamplerStateDescription()
                {
                    Filter             = Filter.MinMagMipLinear,
                    AddressU           = TextureAddressMode.Wrap,
                    AddressV           = TextureAddressMode.Wrap,
                    AddressW           = TextureAddressMode.Wrap,
                    MipLodBias         = 0.0f,
                    MaximumAnisotropy  = 1,
                    ComparisonFunction = Comparison.Always,
                    BorderColor        = new Color4(0, 0, 0, 0),
                    MinimumLod         = 0,
                    MaximumLod         = float.MaxValue
                };

                // Create the texture sampler state.
                SampleState = new SamplerState(device, samplerDesc);

                // Setup the description of the dynamic matrix constant buffer that is in the vertex shader.
                BufferDescription matrixBufferDesc = new BufferDescription()
                {
                    Usage               = ResourceUsage.Dynamic,
                    SizeInBytes         = SharpDX.Utilities.SizeOf <DMatrixBuffer>(),
                    BindFlags           = BindFlags.ConstantBuffer,
                    CpuAccessFlags      = CpuAccessFlags.Write,
                    OptionFlags         = ResourceOptionFlags.None,
                    StructureByteStride = 0
                };

                // Create the constant buffer pointer so we can access the vertex shader constant buffer from within this class.
                ConstantMatrixBuffer = new SharpDX.Direct3D11.Buffer(device, matrixBufferDesc);

                // Setup the description of the light dynamic constant bufffer that is in the pixel shader.
                // Note that ByteWidth alwalys needs to be a multiple of the 16 if using D3D11_BIND_CONSTANT_BUFFER or CreateBuffer will fail.
                BufferDescription skyBufferDesc = new BufferDescription()
                {
                    Usage               = ResourceUsage.Dynamic,
                    SizeInBytes         = SharpDX.Utilities.SizeOf <DSkyBufferType>(),            // Must be divisable by 16 bytes, so this is equated to 32.
                    BindFlags           = BindFlags.ConstantBuffer,
                    CpuAccessFlags      = CpuAccessFlags.Write,
                    OptionFlags         = ResourceOptionFlags.None,
                    StructureByteStride = 0
                };

                // Create the constant buffer pointer so we can access the vertex shader constant buffer from within this class.
                ConstantSkyBuffer = new SharpDX.Direct3D11.Buffer(device, skyBufferDesc);

                return(true);
            }
            catch (Exception ex)
            {
                return(false);
            }
        }
예제 #19
0
        private System.Tuple <Shader, System.Exception> LoadShader(string shaderFile, params InputElement[] inputElements)
        {
            var result = new Shader()
            {
                vertexShader   = null,
                pixelShader    = null,
                geometryShader = null,
                layout         = null,
                validState     = false
            };

            ShaderBytecode  vertexShaderByteCode   = null;
            ShaderBytecode  pixelShaderByteCode    = null;
            ShaderBytecode  geometryShaderByteCode = null;
            ShaderSignature signature      = null;
            VertexShader    vertexShader   = null;
            PixelShader     pixelShader    = null;
            GeometryShader  geometryShader = null;
            InputLayout     layout         = null;

            System.Exception error = null;
            try
            {
                var shaderFileBytecode = File.ReadAllBytes(shaderFile);
                vertexShaderByteCode = ShaderBytecode.Compile(shaderFileBytecode, "VS", "vs_4_0", ShaderFlags.OptimizationLevel0);
                vertexShader         = new VertexShader(device, vertexShaderByteCode);
                var reflection = new ShaderReflection(vertexShaderByteCode);
                /* Iterate through constant buffers */
                for (int i = 0; i < reflection.Description.ConstantBuffers; ++i)
                {
                    var cb = reflection.GetConstantBuffer(i);
                    if (cb.Description.Name == "worldViewProj")
                    {
                        result.vertexShaderSlot.worldViewProj = i;
                    }
                }
                reflection.Dispose();

                pixelShaderByteCode = ShaderBytecode.Compile(shaderFileBytecode, "PS", "ps_4_0", ShaderFlags.OptimizationLevel0);
                pixelShader         = new PixelShader(device, pixelShaderByteCode);

                try
                {
                    geometryShaderByteCode = ShaderBytecode.Compile(shaderFileBytecode, "GS", "gs_4_0", ShaderFlags.OptimizationLevel0);
                    geometryShader         = new GeometryShader(device, geometryShaderByteCode);
                }
                catch (CompilationException e)
                {
                    if (!e.Message.Contains("'GS': entrypoint"))
                    {
                        throw e;
                    }
                }

                signature = ShaderSignature.GetInputSignature(vertexShaderByteCode);
                layout    = new InputLayout(device, signature, inputElements);
                signature.Dispose();

                result.vertexShader   = vertexShader;
                result.pixelShader    = pixelShader;
                result.geometryShader = geometryShader;
                result.layout         = layout;
            }
            catch (System.Exception e)
            {
                System.Console.WriteLine("Error while compiling shader {0}:\n{1}", shaderFile, e);
                error = e;
            }
            finally
            {
                if (geometryShaderByteCode != null)
                {
                    geometryShaderByteCode.Dispose();
                }
                if (vertexShaderByteCode != null)
                {
                    vertexShaderByteCode.Dispose();
                }
                if (pixelShaderByteCode != null)
                {
                    pixelShaderByteCode.Dispose();
                }
                if (geometryShaderByteCode != null)
                {
                    geometryShaderByteCode.Dispose();
                }
                if (signature != null)
                {
                    signature.Dispose();
                }

                if (error != null && vertexShader != null)
                {
                    vertexShader.Dispose();
                }
                if (error != null && pixelShader != null)
                {
                    pixelShader.Dispose();
                }
                if (error != null && geometryShader != null)
                {
                    geometryShader.Dispose();
                }
                if (error != null && layout != null)
                {
                    signature.Dispose();
                }
            }

            result.validState = error == null;

            return(System.Tuple.Create(result, error));
        }
예제 #20
0
        protected void Compile([NotNull] KernelSourceWriter source, [NotNull] CompilerContext context)
        {
            if (source == null)
            {
                throw new ArgumentNullException(nameof(source));
            }

            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            mBytecode = ShaderBytecode.Compile(
                source.SourceCode, KernelSourceWriter.EntryPointName, GetProfileName(),
                ShaderFlags.PackMatrixRowMajor | ShaderFlags.OptimizationLevel3,
                EffectFlags.None, null, null, out var output);

            var parseRegex = new Regex(
                @"^(?:(?:\b[a-z]:|\\\\[a-z0-9 %._-]+\\[a-z0-9 $%._-]+)\\|\\?[^\\/:*?""<>|\x00-\x1F]+\\?)(?:[^\\/:*?""<>"
                + @"|\x00-\x1F]+\\)*[^\\/:*?""<>|\x00-\x1F]*Shader@0x[a-f0-9]{8}\((\d+),(\d+)\):\s((?:warning)|(?:error))\"
                + @"sX(\d+):\s(.*?)$", RegexOptions.IgnoreCase | RegexOptions.Multiline);

            var matches  = parseRegex.Matches(output).OfType <Match>();
            var messages =
                from match in matches

                let lineNumber = match.Groups[1].Value.TryDeserialize <int>()
                                 let columnNumber                                                        = match.Groups[2].Value.TryDeserialize <int>()
                                                                          let type                       = match.Groups[3].Value.TryDeserialize <LogMessageClass>()
                                                                                                let code = match.Groups[4].Value.TryDeserialize <uint>()
                                                                                                           let message = match.Groups[5].Value

                                                                                                                         select new
            {
                Type = type,
                Text = message                         //match.Groups[0].Value
            };

            var hasError = false;
            var errors   = new List <string>();

            foreach (var message in messages)
            {
                context.Writer.Write(message.Text, message.Type);

                if (message.Type == LogMessageClass.Error)
                {
                    hasError = true;
                    errors.Add(message.Text);
                }
            }

            if (!hasError)
            {
                OnBytecodeLoaded();
                return;
            }

            mBytecode?.Dispose();
            mBytecode = null;

            throw new Exception($"The source code contains errors:\r\n{string.Join("\r\n", errors)}");
        }
예제 #21
0
        private bool InitializeShader(Device device, IntPtr windowsHandle, string vsFilePullPath, string psFilePullPath)
        {
            string vsFileName = vsFilePullPath;
            string psFileName = psFilePullPath;

            try
            {
                // Setup full pathes

                // Compile the vertex shader code.
                //ShaderBytecode vertexShaderByteCode = ShaderBytecode.CompileFromFile(vsFileName, "main", "vs_4_0", ShaderFlags.None, EffectFlags.None);
                //// Compile the pixel shader code.
                //ShaderBytecode pixelShaderByteCode = ShaderBytecode.CompileFromFile(psFileName, "main", "ps_4_0", ShaderFlags.None, EffectFlags.None);


                FileStream     fVS = new FileStream(@"C:\Users\qhrrk\Documents\visual studio 2017\Projects\WindowsFormsApp2\WindowsFormsApp2\bin\Debug\colorVS.cso", FileMode.Open);
                FileStream     fPS = new FileStream(@"C:\Users\qhrrk\Documents\visual studio 2017\Projects\WindowsFormsApp2\WindowsFormsApp2\bin\Debug\colorPS.cso", FileMode.Open);
                ShaderBytecode VS  = new ShaderBytecode(fVS);
                ShaderBytecode PS  = new ShaderBytecode(fPS);
                // Create the vertex shader from the buffer.
                VertexShader = new VertexShader(device, VS);
                // Create the pixel shader from the buffer.
                PixelShader = new PixelShader(device, PS);

                // Now setup the layout of the data that goes into the shader.
                // This setup needs to match the VertexType structure in the Model and in the shader.
                InputElement[] inputElements = new InputElement[]
                {
                    new InputElement()
                    {
                        SemanticName         = "POSITION",
                        SemanticIndex        = 0,
                        Format               = SharpDX.DXGI.Format.R32G32B32_Float,
                        Slot                 = 0,
                        AlignedByteOffset    = 0,
                        Classification       = InputClassification.PerVertexData,
                        InstanceDataStepRate = 0
                    },
                    new InputElement()
                    {
                        SemanticName         = "COLOR",
                        SemanticIndex        = 0,
                        Format               = SharpDX.DXGI.Format.R32G32B32A32_Float,
                        Slot                 = 0,
                        AlignedByteOffset    = InputElement.AppendAligned,
                        Classification       = InputClassification.PerVertexData,
                        InstanceDataStepRate = 0
                    }
                };

                // Create the vertex input the layout.
                Layout = new InputLayout(device, ShaderSignature.GetInputSignature(VS), inputElements);

                // Release the vertex and pixel shader buffers, since they are no longer needed.
                //vertexShaderByteCode.Dispose();
                //pixelShaderByteCode.Dispose();

                VS.Dispose();
                PS.Dispose();

                // Setup the description of the dynamic matrix constant buffer that is in the vertex shader.
                BufferDescription matrixBufDesc = new BufferDescription()
                {
                    Usage               = ResourceUsage.Dynamic,
                    SizeInBytes         = Utilities.SizeOf <DMatrixBuffer>(), // was Matrix
                    BindFlags           = BindFlags.ConstantBuffer,
                    CpuAccessFlags      = CpuAccessFlags.Write,
                    OptionFlags         = ResourceOptionFlags.None,
                    StructureByteStride = 0
                };

                // Create the constant buffer pointer so we can access the vertex shader constant buffer from within this class.
                ConstantMatrixBuffer = new SharpDX.Direct3D11.Buffer(device, matrixBufDesc);

                return(true);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error initializing shader. Error is " + ex.Message);
                return(false);
            }
        }
예제 #22
0
        public static BasicHlsl.VertexShaderOutput ExecuteVertexShader(string compiledShaderFile,
                                                                       BasicHlsl.ConstantBufferGlobals globals, VertexPositionNormalTexture vertex)
        {
            var device = new Device(DriverType.Warp);

            var vertexShaderBytes    = File.ReadAllBytes(compiledShaderFile);
            var vertexShaderBytecode = new ShaderBytecode(vertexShaderBytes);
            var vertexShader         = new VertexShader(device, vertexShaderBytecode);

            var layout = new InputLayout(device,
                                         ShaderSignature.GetInputSignature(vertexShaderBytecode),
                                         new[]
            {
                new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0),
                new InputElement("NORMAL", 0, Format.R32G32B32_Float, 16, 0),
                new InputElement("TEXCOORD", 0, Format.R32G32_Float, 28, 0)
            });

            var vertices = Buffer.Create(device, BindFlags.VertexBuffer, new[] { vertex });

            var constantBuffer = Buffer.Create(device, ref globals, new BufferDescription
            {
                BindFlags      = BindFlags.ConstantBuffer,
                CpuAccessFlags = CpuAccessFlags.None,
                Usage          = ResourceUsage.Default
            });

            var geometryShader = new GeometryShader(device, vertexShaderBytecode,
                                                    new[]
            {
                new StreamOutputElement {
                    SemanticName = "SV_POSITION", ComponentCount = 4
                },
                new StreamOutputElement {
                    SemanticName = "COLOR", ComponentCount = 4
                },
                new StreamOutputElement {
                    SemanticName = "TEXCOORD", ComponentCount = 2
                }
            },
                                                    BasicHlsl.VertexShaderOutput.SizeInBytes);

            var outputBuffer = Buffer.Create(device, new BasicHlsl.VertexShaderOutput[1],
                                             new BufferDescription
            {
                CpuAccessFlags = CpuAccessFlags.None,
                BindFlags      = BindFlags.StreamOutput,
                Usage          = ResourceUsage.Default
            });

            var stagingBuffer = Buffer.Create(device, new BasicHlsl.VertexShaderOutput[1],
                                              new BufferDescription
            {
                CpuAccessFlags = CpuAccessFlags.Read,
                BindFlags      = BindFlags.None,
                Usage          = ResourceUsage.Staging
            });

            device.InputAssembler.InputLayout       = layout;
            device.InputAssembler.PrimitiveTopology = PrimitiveTopology.PointList;
            device.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(vertices, VertexPositionNormalTexture.SizeInBytes, 0));
            device.VertexShader.SetConstantBuffer(0, constantBuffer);
            device.VertexShader.Set(vertexShader);
            device.GeometryShader.Set(geometryShader);
            device.StreamOutput.SetTargets(new StreamOutputBufferBinding(outputBuffer, 0));

            device.Draw(1, 0);

            device.CopyResource(outputBuffer, stagingBuffer);
            device.Flush();

            var stream = stagingBuffer.Map(MapMode.Read, SharpDX.Direct3D10.MapFlags.None);
            var bytes  = new byte[BasicHlsl.VertexShaderOutput.SizeInBytes];

            stream.Read(bytes, 0, bytes.Length);
            stream.Dispose();

            outputBuffer.Dispose();
            vertices.Dispose();
            layout.Dispose();
            geometryShader.Dispose();
            vertexShader.Dispose();
            vertexShaderBytecode.Dispose();
            device.Dispose();

            return(StructUtility.FromBytes <BasicHlsl.VertexShaderOutput>(bytes));
        }
예제 #23
0
        private void GenerateHeightMaps()
        {
            ShaderBytecode shaderByteCode = ShaderBytecode.CompileFromFile(@"Data/Shaders/TerrainCompute.hlsl", "initTerrain", "cs_5_0", Shader.ShaderFlags);
            ComputeShader  initTerrain    = new ComputeShader(_context.DirectX.Device, shaderByteCode);

            shaderByteCode.Dispose();
            shaderByteCode = ShaderBytecode.CompileFromFile(@"Data/Shaders/TerrainCompute.hlsl", "initWater", "cs_5_0", Shader.ShaderFlags);
            ComputeShader initWater = new ComputeShader(_context.DirectX.Device, shaderByteCode);

            shaderByteCode.Dispose();
            shaderByteCode         = ShaderBytecode.CompileFromFile(@"Data/Shaders/TerrainCompute.hlsl", "applyRandomDisplacement", "cs_5_0", Shader.ShaderFlags);
            _baseTerrainGeneration = new ComputeShader(_context.DirectX.Device, shaderByteCode);
            shaderByteCode.Dispose();
            shaderByteCode    = ShaderBytecode.CompileFromFile(@"Data/Shaders/TerrainCompute.hlsl", "flowsCalculation", "cs_5_0", Shader.ShaderFlags);
            _flowsCalculation = new ComputeShader(_context.DirectX.Device, shaderByteCode);
            shaderByteCode.Dispose();
            shaderByteCode    = ShaderBytecode.CompileFromFile(@"Data/Shaders/TerrainCompute.hlsl", "updateWaterLevel", "cs_5_0", Shader.ShaderFlags);
            _updateWaterLevel = new ComputeShader(_context.DirectX.Device, shaderByteCode);
            shaderByteCode.Dispose();

            Texture2DDescription textureDescription = new Texture2DDescription
            {
                ArraySize         = 1,
                BindFlags         = BindFlags.ShaderResource | BindFlags.UnorderedAccess,
                CpuAccessFlags    = CpuAccessFlags.None,
                Format            = Format.R32_Float,
                Height            = TextureSize,
                Width             = TextureSize,
                MipLevels         = 1,
                OptionFlags       = ResourceOptionFlags.None,
                SampleDescription = new SampleDescription(1, 0),
                Usage             = ResourceUsage.Default
            };

            ConstantBuffer <ComputeData> computeBuffer = new ConstantBuffer <ComputeData>(_context);

            _context.DirectX.DeviceContext.ComputeShader.SetConstantBuffer(1, computeBuffer.Buffer);

            foreach (Face face in _faces)
            {
                Texture2D terrainTexture = new Texture2D(_context.DirectX.Device, textureDescription);
                face.TerrainSrv = new ShaderResourceView(_context.DirectX.Device, terrainTexture);
                face.TerrainUav = new UnorderedAccessView(_context.DirectX.Device, terrainTexture);
                terrainTexture.Dispose();

                Texture2D waterTexture = new Texture2D(_context.DirectX.Device, textureDescription);
                face.WaterSrv = new ShaderResourceView(_context.DirectX.Device, waterTexture);
                face.WaterUav = new UnorderedAccessView(_context.DirectX.Device, waterTexture);
                waterTexture.Dispose();

                Texture2D flowsTexture = new Texture2D(_context.DirectX.Device, textureDescription);
                face.FlowsLeftUav = new UnorderedAccessView(_context.DirectX.Device, flowsTexture);
                flowsTexture.Dispose();

                flowsTexture     = new Texture2D(_context.DirectX.Device, textureDescription);
                face.FlowsTopUav = new UnorderedAccessView(_context.DirectX.Device, flowsTexture);
                flowsTexture.Dispose();

                flowsTexture       = new Texture2D(_context.DirectX.Device, textureDescription);
                face.FlowsRightUav = new UnorderedAccessView(_context.DirectX.Device, flowsTexture);
                flowsTexture.Dispose();

                flowsTexture        = new Texture2D(_context.DirectX.Device, textureDescription);
                face.FlowsBottomUav = new UnorderedAccessView(_context.DirectX.Device, flowsTexture);
                flowsTexture.Dispose();

                _context.DirectX.DeviceContext.ComputeShader.SetUnorderedAccessView(0, face.TerrainUav);
                _context.DirectX.DeviceContext.ComputeShader.SetUnorderedAccessView(1, face.WaterUav);

                _context.DirectX.DeviceContext.ComputeShader.Set(initTerrain);
                computeBuffer.Update(new ComputeData(TextureSize - 1 - BatchSize, 0, 0, 0.0f));
                _context.DirectX.DeviceContext.Dispatch(TextureSize / BatchSize, TextureSize / BatchSize, 1);

                _context.DirectX.DeviceContext.ComputeShader.Set(initWater);
                computeBuffer.Update(new ComputeData(TextureSize - 1 - BatchSize, 0, 0, 0.05f));
                _context.DirectX.DeviceContext.Dispatch(TextureSize / BatchSize, TextureSize / BatchSize, 1);

                _context.DirectX.DeviceContext.ComputeShader.Set(initTerrain);
                computeBuffer.Update(new ComputeData(TextureSize - 1 - BatchSize, BatchSize / 2, BatchSize / 2, 0.5f));
                _context.DirectX.DeviceContext.Dispatch(TextureSize / BatchSize - 1, TextureSize / BatchSize - 1, 1);
            }

            _planeBuffer = new ConstantBuffer <PlaneData>(_context);

            initTerrain.Dispose();
            computeBuffer.Dispose();
        }
예제 #24
0
        private bool InitializeShader(Device device, IntPtr windowsHandler, string vsFileName, string psFileName)
        {
            try
            {
                // Setup full pathes
                vsFileName = DSystemConfiguration.ShaderFilePath + vsFileName;
                psFileName = DSystemConfiguration.ShaderFilePath + psFileName;

                // Compile the Vertex Shader & Pixel Shader code.
                ShaderBytecode vertexShaderByteCode = ShaderBytecode.CompileFromFile(vsFileName, "TextureVertexShader", DSystemConfiguration.VertexShaderProfile, ShaderFlags.None, EffectFlags.None);
                ShaderBytecode pixelShaderByteCode  = ShaderBytecode.CompileFromFile(psFileName, "TexturePixelShader", DSystemConfiguration.PixelShaderProfile, ShaderFlags.None, EffectFlags.None);

                // Create the Vertex & Pixel Shaders from the buffer.
                VertexShader = new VertexShader(device, vertexShaderByteCode);
                PixelShader  = new PixelShader(device, pixelShaderByteCode);

                // Now setup the layout of the data that goes into the shader.
                // This setup needs to match the VertexType structure in the Model and in the shader.
                InputElement[] inputElements = new InputElement[]
                {
                    new InputElement()
                    {
                        SemanticName         = "POSITION",
                        SemanticIndex        = 0,
                        Format               = SharpDX.DXGI.Format.R32G32B32_Float,
                        Slot                 = 0,
                        AlignedByteOffset    = InputElement.AppendAligned,
                        Classification       = InputClassification.PerVertexData,
                        InstanceDataStepRate = 0
                    },
                    new InputElement()
                    {
                        SemanticName         = "TEXCOORD",
                        SemanticIndex        = 0,
                        Format               = SharpDX.DXGI.Format.R32G32_Float,
                        Slot                 = 0,
                        AlignedByteOffset    = InputElement.AppendAligned,
                        Classification       = InputClassification.PerVertexData,
                        InstanceDataStepRate = 0
                    }
                };

                // Create the vertex input the layout. Kin dof like a Vertex Declaration.
                Layout = new InputLayout(device, ShaderSignature.GetInputSignature(vertexShaderByteCode), inputElements);

                // Release the vertex and pixel shader buffers, since they are no longer needed.
                vertexShaderByteCode.Dispose();
                pixelShaderByteCode.Dispose();

                // Setup the description of the dynamic matrix constant Matrix buffer that is in the vertex shader.
                BufferDescription matrixBufferDescription = new BufferDescription()
                {
                    Usage               = ResourceUsage.Dynamic,
                    SizeInBytes         = Utilities.SizeOf <DMatrixBuffer>(),
                    BindFlags           = BindFlags.ConstantBuffer,
                    CpuAccessFlags      = CpuAccessFlags.Write,
                    OptionFlags         = ResourceOptionFlags.None,
                    StructureByteStride = 0
                };

                // Create the constant buffer pointer so we can access the vertex shader constant buffer from within this class.
                ConstantMatrixBuffer = new SharpDX.Direct3D11.Buffer(device, matrixBufferDescription);

                // Create a texture sampler state description.
                SamplerStateDescription samplerDesc = new SamplerStateDescription()
                {
                    Filter             = Filter.MinMagMipLinear,
                    AddressU           = TextureAddressMode.Wrap,
                    AddressV           = TextureAddressMode.Wrap,
                    AddressW           = TextureAddressMode.Wrap,
                    MipLodBias         = 0,
                    MaximumAnisotropy  = 1,
                    ComparisonFunction = Comparison.Always,
                    BorderColor        = new Color4(0, 0, 0, 0), // Black Border.
                    MinimumLod         = 0,
                    MaximumLod         = float.MaxValue
                };

                // Create the texture sampler state.
                SamplerState = new SamplerState(device, samplerDesc);

                return(true);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error initializing shader. Error is " + ex.Message);
                return(false);
            }
        }
예제 #25
0
        public bool init(Device D)
        {
            FileStream fvs = null;
            FileStream fps = null;
            FileStream fgs = null;

            try
            {
                fvs = new FileStream(@"C:\Users\qhrrk\Documents\visual studio 2017\Projects\WindowsFormsApp2\WindowsFormsApp2\GEOVSPASS.cso", FileMode.Open);
                fps = new FileStream(@"C:\Users\qhrrk\Documents\visual studio 2017\Projects\WindowsFormsApp2\WindowsFormsApp2\deffectPS.cso", FileMode.Open);
                fgs = new FileStream(@"C:\Users\qhrrk\Documents\visual studio 2017\Projects\WindowsFormsApp2\WindowsFormsApp2\defectMake.cso", FileMode.Open);
            }
            catch (Exception ex)
            {
            }

            ShaderBytecode vs = new ShaderBytecode(fvs);
            ShaderBytecode ps = new ShaderBytecode(fps);
            ShaderBytecode gs = new ShaderBytecode(fgs);


            VertexShader   = new VertexShader(D, vs);
            PixelShader    = new PixelShader(D, ps);
            GeometryShader = new GeometryShader(D, gs);


            InputElement[] inputElements = new InputElement[]
            {
                new InputElement()
                {
                    SemanticName         = "POSITION",
                    SemanticIndex        = 0,
                    Format               = SharpDX.DXGI.Format.R32G32B32_Float,
                    Slot                 = 0,
                    AlignedByteOffset    = 0,
                    Classification       = InputClassification.PerVertexData,
                    InstanceDataStepRate = 0
                }, //12
                new InputElement()
                {
                    SemanticName         = "COLOR",
                    SemanticIndex        = 0,
                    Format               = SharpDX.DXGI.Format.R32G32B32A32_Float,
                    Slot                 = 0,
                    AlignedByteOffset    = 12,
                    Classification       = InputClassification.PerVertexData,
                    InstanceDataStepRate = 0
                }, //12 + 16
                new InputElement()
                {
                    SemanticName         = "SIZE",
                    SemanticIndex        = 0,
                    Format               = SharpDX.DXGI.Format.R32G32_Float,
                    Slot                 = 0,
                    AlignedByteOffset    = 28,
                    Classification       = InputClassification.PerVertexData,
                    InstanceDataStepRate = 0
                }
            };

            Layout = new InputLayout(D, ShaderSignature.GetInputSignature(vs), inputElements);
            vs.Dispose();
            ps.Dispose();
            gs.Dispose();


            BufferDescription matrixBufDesc = new BufferDescription()
            {
                Usage               = ResourceUsage.Dynamic,
                SizeInBytes         = Utilities.SizeOf <DeffectMatrixBuffer>(), // was Matrix
                BindFlags           = BindFlags.ConstantBuffer,
                CpuAccessFlags      = CpuAccessFlags.Write,
                OptionFlags         = ResourceOptionFlags.None,
                StructureByteStride = 0
            };

            ConstantMatrixBuffer = new SharpDX.Direct3D11.Buffer(D, matrixBufDesc);
            return(true);
        }
예제 #26
0
        public SpritesRender(DX11 dx11, RenderForm form, CoreSettings setCoreSettings)
        {
            _form            = form;
            _dx11            = dx11;
            VertexBufferSize = MaxElements * Utilities.SizeOf <Vertex>() * 4;
            IndexBufferSize  = MaxElements * Utilities.SizeOf <uint>() * 6;

            // Compile the vertex shader code.
            ShaderBytecode vertexShaderByteCode =
                ShaderBytecode.CompileFromFile("Shaders\\VertexShader.hlsl", "VS", "vs_4_0");

            // Compile the pixel shader code.
            ShaderBytecode pixelShaderByteCode =
                ShaderBytecode.CompileFromFile("Shaders\\PixelShader.hlsl", "PS", "ps_4_0");

            VertexShader = new VertexShader(_dx11.D11Device, vertexShaderByteCode);
            PixelShader  = new PixelShader(_dx11.D11Device, pixelShaderByteCode);

            VertexBuffer = new Buffer(_dx11.D11Device,
                                      new BufferDescription
            {
                Usage          = ResourceUsage.Dynamic,
                BindFlags      = BindFlags.VertexBuffer,
                OptionFlags    = ResourceOptionFlags.None,
                CpuAccessFlags = CpuAccessFlags.Write,
                SizeInBytes    = VertexBufferSizeBytes
            });

            IndexBuffer = new Buffer(_dx11.D11Device,
                                     new BufferDescription
            {
                Usage          = ResourceUsage.Dynamic,
                BindFlags      = BindFlags.IndexBuffer,
                OptionFlags    = ResourceOptionFlags.None,
                CpuAccessFlags = CpuAccessFlags.Write,
                SizeInBytes    = IndexBufferSizeBytes
            });

            ConstantBuffer = new Buffer(_dx11.D11Device,
                                        new BufferDescription
            {
                BindFlags      = BindFlags.ConstantBuffer,
                Usage          = ResourceUsage.Dynamic,
                OptionFlags    = ResourceOptionFlags.None,
                CpuAccessFlags = CpuAccessFlags.Write,
                SizeInBytes    = Utilities.SizeOf <Vector2>() * 2
            });

            var inputElements = new[]
            {
                new InputElement
                {
                    SemanticName         = "POSITION",
                    SemanticIndex        = 0,
                    Format               = Format.R32G32_Float,
                    Slot                 = 0,
                    AlignedByteOffset    = 0,
                    Classification       = InputClassification.PerVertexData,
                    InstanceDataStepRate = 0
                },
                new InputElement
                {
                    SemanticName         = "TEXCOORD",
                    SemanticIndex        = 0,
                    Format               = Format.R32G32_Float,
                    Slot                 = 0,
                    AlignedByteOffset    = InputElement.AppendAligned,
                    Classification       = InputClassification.PerVertexData,
                    InstanceDataStepRate = 0
                },
                new InputElement
                {
                    SemanticName  = "COLOR",
                    SemanticIndex = 0,

                    // Format = Format.R32G32B32A32_Float,
                    Format               = Format.R8G8B8A8_UNorm,
                    Slot                 = 0,
                    AlignedByteOffset    = InputElement.AppendAligned,
                    Classification       = InputClassification.PerVertexData,
                    InstanceDataStepRate = 0
                }
            };

            Layout = new InputLayout(_dx11.D11Device, ShaderSignature.GetInputSignature(vertexShaderByteCode),
                                     inputElements);

            vertexShaderByteCode.Dispose();
            pixelShaderByteCode.Dispose();
            CreateStates();
            imagingFactory2 = new ImagingFactory2();
        }
        private bool InitializeShader(Device device, IntPtr hwnd, string vsFileName, string psFileName)
        {
            try
            {
                // Setup full pathes
                vsFileName = DSystemConfiguration.ShaderFilePath + vsFileName;
                psFileName = DSystemConfiguration.ShaderFilePath + psFileName;

                // Compile the Vertex & Pixel Shader code.
                ShaderBytecode vertexShaderByteCode = ShaderBytecode.CompileFromFile(vsFileName, "SkyDomeVertexShader", DSystemConfiguration.VertexShaderProfile, ShaderFlags.None, EffectFlags.None);
                ShaderBytecode pixelShaderByteCode  = ShaderBytecode.CompileFromFile(psFileName, "SkyDomePixelShader", DSystemConfiguration.PixelShaderProfile, ShaderFlags.None, EffectFlags.None);

                // Create the Vertex & Pixel Shader from the buffer.
                VertexShader = new VertexShader(device, vertexShaderByteCode);
                PixelShader  = new PixelShader(device, pixelShaderByteCode);

                // Create the vertex input layout description.
                InputElement[] inputElements = new InputElement[]
                {
                    new InputElement()
                    {
                        SemanticName         = "POSITION",
                        SemanticIndex        = 0,
                        Format               = SharpDX.DXGI.Format.R32G32B32_Float,
                        Slot                 = 0,
                        AlignedByteOffset    = 0,
                        Classification       = InputClassification.PerVertexData,
                        InstanceDataStepRate = 0
                    }
                };

                // Create the vertex input the layout.
                Layout = new InputLayout(device, ShaderSignature.GetInputSignature(vertexShaderByteCode), inputElements);

                // Release the vertex and pixel shader buffers, since they are no longer needed.
                vertexShaderByteCode.Dispose();
                pixelShaderByteCode.Dispose();

                // Setup the description of the dynamic matrix constant buffer that is in the vertex shader.
                BufferDescription matrixBufferDesc = new BufferDescription()
                {
                    Usage               = ResourceUsage.Dynamic,
                    SizeInBytes         = Utilities.SizeOf <DMatrixBuffer>(),
                    BindFlags           = BindFlags.ConstantBuffer,
                    CpuAccessFlags      = CpuAccessFlags.Write,
                    OptionFlags         = ResourceOptionFlags.None,
                    StructureByteStride = 0
                };

                // Create the constant buffer pointer so we can access the vertex shader constant buffer from within this class.
                ConstantMatrixBuffer = new SharpDX.Direct3D11.Buffer(device, matrixBufferDesc);

                // Setup the description of the gradient constant buffer that is in the pixel shader.
                BufferDescription gradientBufferDesc = new BufferDescription()
                {
                    Usage               = ResourceUsage.Dynamic,
                    SizeInBytes         = Utilities.SizeOf <DGradientBuffer>(),
                    BindFlags           = BindFlags.ConstantBuffer,
                    CpuAccessFlags      = CpuAccessFlags.Write,
                    OptionFlags         = ResourceOptionFlags.None,
                    StructureByteStride = 0
                };

                // Create the constant buffer pointer so we can access the pixel shader constant buffer from within this class.
                ConstantGradientBuffer = new SharpDX.Direct3D11.Buffer(device, gradientBufferDesc);

                return(true);
            }
            catch
            {
                return(false);
            }
        }
        private bool InitializeShader(SharpDX.Direct3D11.Device device, IntPtr windowsHandle) //, string vsFileName, string psFileName //, Matrix worldMatrix
        {
            try
            {
                /*var vsFileNameByteArray = "../../../sc_instance_shader/" + "red.vs";
                 * var psFileNameByteArray = "../../../sc_instance_shader/" + "red.ps";
                 * var gsFileNameByteArray = "../../../sc_instance_shader/" + "HLSL.gs";
                 *
                 * vertexShaderByteCode = ShaderBytecode.CompileFromFile(vsFileNameByteArray, "ColorVertexShader", "vs_4_0", ShaderFlags.None, SharpDX.D3DCompiler.EffectFlags.None);
                 * pixelShaderByteCode = ShaderBytecode.CompileFromFile(psFileNameByteArray, "ColorPixelShader", "ps_4_0", ShaderFlags.None, SharpDX.D3DCompiler.EffectFlags.None);
                 * geometryShaderByteCode = ShaderBytecode.CompileFromFile(gsFileNameByteArray, "GS", "gs_5_0", ShaderFlags.None, EffectFlags.None);
                 */
                /*
                 * if (Program.is_wpf == 1)
                 * {
                 *  var vsFileNameByteArray = SCCoreSystems.Properties.Resources.red1;
                 *  var psFileNameByteArray = SCCoreSystems.Properties.Resources.red;
                 *  var gsFileNameByteArray = SCCoreSystems.Properties.Resources.HLSL;
                 *  vertexShaderByteCode = ShaderBytecode.Compile(vsFileNameByteArray, "ColorVertexShader", "vs_5_0", ShaderFlags.None, EffectFlags.None);
                 *  pixelShaderByteCode = ShaderBytecode.Compile(psFileNameByteArray, "ColorPixelShader", "ps_5_0", ShaderFlags.None, EffectFlags.None);
                 *  geometryShaderByteCode = ShaderBytecode.Compile(gsFileNameByteArray, "GS", "gs_5_0", ShaderFlags.None, EffectFlags.None);
                 *
                 * }
                 * else
                 * {
                 *
                 * }*/

                //ShaderBytecode vertexShaderByteCode = ShaderBytecode.Compile(gsFileNameByteArray, "VS", "vs_5_0", ShaderFlags.None, EffectFlags.None);
                //ShaderBytecode pixelShaderByteCode = ShaderBytecode.Compile(gsFileNameByteArray, "PS", "ps_5_0", ShaderFlags.None, EffectFlags.None);

                var vsFileNameByteArray = SCCoreSystems.Properties.Resources.red1;
                var psFileNameByteArray = SCCoreSystems.Properties.Resources.red;
                var gsFileNameByteArray = SCCoreSystems.Properties.Resources.HLSL;
                vertexShaderByteCode   = ShaderBytecode.Compile(vsFileNameByteArray, "ColorVertexShader", "vs_5_0", ShaderFlags.None, EffectFlags.None);
                pixelShaderByteCode    = ShaderBytecode.Compile(psFileNameByteArray, "ColorPixelShader", "ps_5_0", ShaderFlags.None, EffectFlags.None);
                geometryShaderByteCode = ShaderBytecode.Compile(gsFileNameByteArray, "GS", "gs_5_0", ShaderFlags.None, EffectFlags.None);

                // Create the vertex shader from the buffer.
                VertexShader = new VertexShader(device, vertexShaderByteCode);
                // Create the pixel shader from the buffer.
                PixelShader = new PixelShader(device, pixelShaderByteCode);

                GeometryShader = new GeometryShader(device, geometryShaderByteCode);
                // Now setup the layout of the data that goes into the shader.
                // This setup needs to match the VertexType structure in the Model and in the shader.



                InputElement[] inputElements = new InputElement[]
                {
                    //new InputElement("POSITION", 0, SharpDX.DXGI.Format.R32G32B32_Float, 0, 0)

                    new InputElement()
                    {
                        SemanticName         = "POSITION",
                        SemanticIndex        = 0,
                        Format               = SharpDX.DXGI.Format.R32G32B32_Float,
                        Slot                 = 0,
                        AlignedByteOffset    = 0,
                        Classification       = InputClassification.PerVertexData,
                        InstanceDataStepRate = 0
                    },
                    new InputElement()
                    {
                        SemanticName         = "COLOR",
                        SemanticIndex        = 0,
                        Format               = SharpDX.DXGI.Format.R32G32B32A32_Float,
                        Slot                 = 0,
                        AlignedByteOffset    = InputElement.AppendAligned,
                        Classification       = InputClassification.PerVertexData,
                        InstanceDataStepRate = 0
                    },

                    new InputElement()
                    {
                        SemanticName         = "TEXCOORD",
                        SemanticIndex        = 1,
                        Format               = SharpDX.DXGI.Format.R32G32B32A32_Float,
                        Slot                 = 1,
                        AlignedByteOffset    = 0,
                        Classification       = InputClassification.PerInstanceData,
                        InstanceDataStepRate = 1
                    },
                };

                // Create the vertex input the layout. Kin dof like a Vertex Declaration.
                Layout = new InputLayout(device, ShaderSignature.GetInputSignature(vertexShaderByteCode), inputElements);

                // Release the vertex and pixel shader buffers, since they are no longer needed.
                vertexShaderByteCode.Dispose();
                pixelShaderByteCode.Dispose();

                // Setup the description of the dynamic matrix constant Matrix buffer that is in the vertex shader.
                BufferDescription matrixBufferDescription = new BufferDescription()
                {
                    Usage               = ResourceUsage.Dynamic,
                    SizeInBytes         = Utilities.SizeOf <DMatrixBuffer>(),// * Utilities.SizeOf<DInstanceType>() * instances.Length, //Utilities.SizeOf<DMatrixBuffer>() *
                    BindFlags           = BindFlags.ConstantBuffer,
                    CpuAccessFlags      = CpuAccessFlags.Write,
                    OptionFlags         = ResourceOptionFlags.None,
                    StructureByteStride = 0
                };


                /*BufferDescription matrixBufferDescription = new BufferDescription()
                 * {
                 *  Usage = ResourceUsage.Default,
                 *  SizeInBytes = Utilities.SizeOf<DMatrixBuffer>(),
                 *  BindFlags = BindFlags.ConstantBuffer,
                 *  CpuAccessFlags = CpuAccessFlags.None,
                 *  OptionFlags = ResourceOptionFlags.None,
                 *  StructureByteStride = 0
                 * };*/


                // Create the constant buffer pointer so we can access the vertex shader constant buffer from within this class.
                ConstantMatrixBuffer = new SharpDX.Direct3D11.Buffer(device, matrixBufferDescription);



                //ConstantMatrixBuffer = SharpDX.Direct3D11.Buffer.Create(device, BindFlags.VertexBuffer, instances);


                //int bufferSlotNumberer = 0;
                //device.ImmediateContext.VertexShader.SetConstantBuffer(bufferSlotNumberer, ConstantMatrixBuffer);


                //ConstantMatrixBuffer = SharpDX.Direct3D11.Buffer.Create(device, BindFlags.ConstantBuffer, instances, Utilities.SizeOf<DMatrixBuffer>()* Utilities.SizeOf<DInstanceType>() * instances.Length, ResourceUsage.Dynamic, CpuAccessFlags.Write, ResourceOptionFlags.None, 0);



                // Create a texture sampler state description.

                /*SamplerStateDescription samplerDesc = new SamplerStateDescription()
                 * {
                 *  Filter = Filter.MinMagMipLinear,
                 *  AddressU = TextureAddressMode.Wrap,
                 *  AddressV = TextureAddressMode.Wrap,
                 *  AddressW = TextureAddressMode.Wrap,
                 *  MipLodBias = 0,
                 *  MaximumAnisotropy = 1,
                 *  ComparisonFunction = Comparison.Always,
                 *  BorderColor = new Color4(0, 0, 0, 0),  // Black Border.
                 *  MinimumLod = 0,
                 *  MaximumLod = float.MaxValue
                 * };
                 *
                 * // Create the texture sampler state.
                 * SamplerState = new SamplerState(device, samplerDesc);
                 */

                //int bufferSlotNumber = 0;
                //device.ImmediateContext.VertexShader.SetConstantBuffer(bufferSlotNumber, ConstantMatrixBuffer);

                return(true);
            }
            catch (Exception ex)
            {
                Console.WriteLine(" SC_cloth_shader ERROR ### " + ex.ToString());
                return(false);
            }
        }
예제 #29
0
        private bool InitializeShader(Device device, IntPtr windowsHandle, string vsFileName, string psFileName)
        {
            try
            {
                //vsFileName = DSystemConfiguration.ShaderFilePath + vsFileName;
                //psFileName = DSystemConfiguration.ShaderFilePath + psFileName;
                vsFileName = SCCoreSystems.Properties.Resources.Color1; // "../../../_sc_instance_shader/" + "texture.vs";
                psFileName = SCCoreSystems.Properties.Resources.Color;  // "../../../_sc_instance_shader/" + "texture.ps";


                // Compile the vertex shader code.
                ShaderBytecode vertexShaderByteCode = ShaderBytecode.CompileFromFile(vsFileName, "ColorVertexShader", "vs_4_0", ShaderFlags.None, EffectFlags.None);
                // Compile the pixel shader code.
                ShaderBytecode pixelShaderByteCode = ShaderBytecode.CompileFromFile(psFileName, "ColorPixelShader", "ps_4_0", ShaderFlags.None, EffectFlags.None);

                // Create the vertex shader from the buffer.
                VertexShader = new VertexShader(device, vertexShaderByteCode);
                // Create the pixel shader from the buffer.
                PixelShader = new PixelShader(device, pixelShaderByteCode);

                // Now setup the layout of the data that goes into the shader.
                // This setup needs to match the VertexType structure in the Model and in the shader.
                InputElement[] inputElements = new InputElement[]
                {
                    new InputElement()
                    {
                        SemanticName         = "POSITION",
                        SemanticIndex        = 0,
                        Format               = SharpDX.DXGI.Format.R32G32B32_Float,
                        Slot                 = 0,
                        AlignedByteOffset    = 0,
                        Classification       = InputClassification.PerVertexData,
                        InstanceDataStepRate = 0
                    },
                    new InputElement()
                    {
                        SemanticName         = "COLOR",
                        SemanticIndex        = 0,
                        Format               = SharpDX.DXGI.Format.R32G32B32A32_Float,
                        Slot                 = 0,
                        AlignedByteOffset    = InputElement.AppendAligned,
                        Classification       = InputClassification.PerVertexData,
                        InstanceDataStepRate = 0
                    }
                };

                // Create the vertex input the layout.
                Layout = new InputLayout(device, ShaderSignature.GetInputSignature(vertexShaderByteCode), inputElements);

                // Release the vertex and pixel shader buffers, since they are no longer needed.
                vertexShaderByteCode.Dispose();
                pixelShaderByteCode.Dispose();

                // Setup the description of the dynamic matrix constant buffer that is in the vertex shader.
                BufferDescription matrixBufDesc = new BufferDescription()
                {
                    Usage               = ResourceUsage.Dynamic,
                    SizeInBytes         = Utilities.SizeOf <DMatrixBuffer>(), // was Matrix
                    BindFlags           = BindFlags.ConstantBuffer,
                    CpuAccessFlags      = CpuAccessFlags.Write,
                    OptionFlags         = ResourceOptionFlags.None,
                    StructureByteStride = 0
                };

                // Create the constant buffer pointer so we can access the vertex shader constant buffer from within this class.
                ConstantMatrixBuffer = new SharpDX.Direct3D11.Buffer(device, matrixBufDesc);

                return(true);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error initializing shader. Error is " + ex.Message);
                return(false);
            }
        }
예제 #30
0
        private bool InitializeShader(Device device, IntPtr windowsHandler, string vsFileName, string psFileName)
        {
            try
            {
                vsFileName = DSystemConfiguration.ShaderFilePath + vsFileName;
                psFileName = DSystemConfiguration.ShaderFilePath + psFileName;
                ShaderBytecode vertexShaderByteCode = ShaderBytecode.CompileFromFile(vsFileName, "TextureVertexShader", "vs_4_0", ShaderFlags.None, EffectFlags.None);
                ShaderBytecode pixelShaderByteCode  = ShaderBytecode.CompileFromFile(psFileName, "TexturePixelShader", "ps_4_0", ShaderFlags.None, EffectFlags.None);
                VertexShader = new VertexShader(device, vertexShaderByteCode);
                PixelShader  = new PixelShader(device, pixelShaderByteCode);
                InputElement[] inputElements = new InputElement[]
                {
                    new InputElement()
                    {
                        SemanticName         = "POSITION",
                        SemanticIndex        = 0,
                        Format               = SharpDX.DXGI.Format.R32G32B32_Float,
                        Slot                 = 0,
                        AlignedByteOffset    = 0,
                        Classification       = InputClassification.PerVertexData,
                        InstanceDataStepRate = 0
                    },
                    new InputElement()
                    {
                        SemanticName         = "TEXCOORD",
                        SemanticIndex        = 0,
                        Format               = SharpDX.DXGI.Format.R32G32_Float,
                        Slot                 = 0,
                        AlignedByteOffset    = InputElement.AppendAligned,
                        Classification       = InputClassification.PerVertexData,
                        InstanceDataStepRate = 0
                    }
                };
                Layout = new InputLayout(device, ShaderSignature.GetInputSignature(vertexShaderByteCode), inputElements);
                vertexShaderByteCode.Dispose();
                pixelShaderByteCode.Dispose();

                BufferDescription matrixBufferDescription = new BufferDescription()
                {
                    Usage               = ResourceUsage.Dynamic,
                    SizeInBytes         = Utilities.SizeOf <DMatrixBuffer>(),
                    BindFlags           = BindFlags.ConstantBuffer,
                    CpuAccessFlags      = CpuAccessFlags.Write,
                    OptionFlags         = ResourceOptionFlags.None,
                    StructureByteStride = 0
                };
                ConstantMatrixBuffer = new SharpDX.Direct3D11.Buffer(device, matrixBufferDescription);

                SamplerStateDescription samplerDesc = new SamplerStateDescription()
                {
                    Filter             = Filter.MinMagMipLinear,
                    AddressU           = TextureAddressMode.Wrap,
                    AddressV           = TextureAddressMode.Wrap,
                    AddressW           = TextureAddressMode.Wrap,
                    MipLodBias         = 0,
                    MaximumAnisotropy  = 1,
                    ComparisonFunction = Comparison.Always,
                    BorderColor        = new Color4(0, 0, 0, 0), // Black Border.
                    MinimumLod         = 0,
                    MaximumLod         = float.MaxValue
                };
                SamplerState = new SamplerState(device, samplerDesc);

                return(true);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error initializing shader. Error is " + ex.Message);
                return(false);
            }
        }