Exemplo n.º 1
0
        /// <summary>
        /// Function to save the shader to a stream.
        /// </summary>
        /// <param name="stream">Stream to write into.</param>
        /// <param name="binary">[Optional] TRUE to save the binary version of the shader, FALSE to save the source.</param>
        /// <param name="saveDebug">[Optional] TRUE to save the debug information, FALSE to exclude it.</param>
        /// <remarks>The <paramref name="saveDebug"/> parameter is only applicable when the <paramref name="binary"/> parameter is set to TRUE.</remarks>
        /// <exception cref="System.ArgumentNullException">Thrown when the <paramref name="stream"/> parameter is NULL (Nothing in VB.Net).</exception>
        /// <exception cref="System.ArgumentException">Thrown when the shader is being saved as source code and the <see cref="GorgonLibrary.Graphics.GorgonShader.SourceCode">SourceCode</see> parameter is NULL (Nothing in VB.Net) or empty.</exception>
        /// <exception cref="GorgonLibrary.GorgonException">Thrown when the shader fails to compile.</exception>
        public void Save(Stream stream, bool binary = false, bool saveDebug = false)
        {
            Shaders.ShaderBytecode compiledShader = null;
            GorgonDebug.AssertNull(stream, "stream");

            if ((!binary) && (string.IsNullOrEmpty(SourceCode)))
            {
                throw new ArgumentException(Resources.GORGFX_SHADER_NO_CODE, "binary");
            }

            if (!binary)
            {
                byte[] shaderSource = Encoding.UTF8.GetBytes(SourceCode);
                stream.Write(shaderSource, 0, shaderSource.Length);

                return;
            }

            try
            {
                compiledShader = CompileFromSource(saveDebug);
                byte[] header = Encoding.UTF8.GetBytes(GorgonShaderBinding.BinaryShaderHeader);
                stream.Write(header, 0, header.Length);
                compiledShader.Save(stream);
            }
            finally
            {
                if (compiledShader != null)
                {
                    compiledShader.Dispose();
                }
            }
        }
        public ProjectiveTexturingShader(Device device)
        {
            var shaderByteCode = new ShaderBytecode(File.ReadAllBytes("Content/DepthAndProjectiveTextureVS.cso"));
            vertexShader = new VertexShader(device, shaderByteCode);
            geometryShader = new GeometryShader(device, new ShaderBytecode(File.ReadAllBytes("Content/DepthAndColorGS.cso")));
            pixelShader = new PixelShader(device, new ShaderBytecode(File.ReadAllBytes("Content/DepthAndColorPS.cso")));

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

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

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

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

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

        }
Exemplo n.º 3
0
        //================================================================================================================//

        public static bool CompileShader(string baseSourceDirectory, string outputDirectory, string includeDirectory, HlslConfiguration global_, HlslFileConfiguration file)
        {
            try
            {
                string _path = Path.GetDirectoryName(file.FileNameRelative);

                IncludeFX include_ = new IncludeFX(baseSourceDirectory + _path + "\\");

                Console.WriteLine("Compiler Flags used: " + global_.GetShaderFlagsAsString().ToString());

                if (File.Exists(baseSourceDirectory + file.FileNameRelative))
                {
                    D3DCompiler.CompilationResult errors_ = D3DCompiler.ShaderBytecode.CompileFromFile(baseSourceDirectory + file.FileNameRelative,
                                                                                                       file.EntryPoint,
                                                                                                       file.PixelShaderVersion,
                                                                                                       global_.GetShaderFlags(),
                                                                                                       D3DCompiler.EffectFlags.None,
                                                                                                       null,
                                                                                                       include_);

                    D3DCompiler.ShaderBytecode shaderByteCode = errors_.Bytecode;

                    if (shaderByteCode != null)
                    {
                        string fileName_ = Path.GetFileNameWithoutExtension(Path.GetFileName(file.FileNameRelative));

                        string path_ = Path.GetFullPath(outputDirectory);

                        file.OutputName = path_ + fileName_ + ".cso";

                        System.IO.Directory.CreateDirectory(path_ + "\\");

                        FileStream write_ = new FileStream(file.OutputName, FileMode.Create, FileAccess.Write);

                        shaderByteCode.Save(write_);
                    }
                    else
                    {
                        throw new Exception(errors_.Message);
                    }

                    return(true);
                }
                else
                {
                    Console.WriteLine("File not found: " + baseSourceDirectory + file.FileNameRelative);
                }
            }
            catch (Exception ex_)
            {
                Console.WriteLine("Failed to compile file: " + ex_.Message);

                return(false);
            }

            return(false);
        }
Exemplo n.º 4
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Module"/> class.
        /// </summary>
        /// <param name="bytecode">The source data of the module.</param>
        public Module(ShaderBytecode bytecode)
        {
            if (bytecode == null) throw new ArgumentNullException("bytecode");

            var data = bytecode.Data;
            unsafe
            {
                fixed (void* dataPtr = &data[0])
                    D3D.LoadModule(new IntPtr(dataPtr), new PointerSize(data.Length), this);
            }
        }
Exemplo n.º 5
0
        CompiledShaderReader(string fn,string shaderType,ConstantBuffer[] cbs , ShaderParameterDescription[] pds,InputBindingDescription[] rbs,ShaderReflection reflec,ShaderBytecode bytec)
        {
            cBuffers = cbs;
            parameterDescriptions = pds;
            resourceBindings = rbs;
            filename = fn;
            typePrefix = shaderType;

            reflector = reflec;
            bytecode = bytec;
        }
Exemplo n.º 6
0
        /// <summary>
        /// Function to create the shader.
        /// </summary>
        /// <param name="byteCode">Byte code for the shader.</param>
        protected override void CreateShader(Compiler.ShaderBytecode byteCode)
        {
            if (D3DShader != null)
            {
                D3DShader.Dispose();
            }

            D3DShader = new D3D.GeometryShader(Graphics.D3DDevice, byteCode)
            {
#if DEBUG
                DebugName = string.Format("Gorgon Geometry Shader '{0}'", Name)
#endif
            };
        }
Exemplo n.º 7
0
        void InitializeShaders(ShaderBytecode vertexShaderBytecode, ShaderBytecode pixelShaderBytecode)
        {
            vertexShader = new D3D11.VertexShader(device, vertexShaderBytecode);
            deviceContext.VertexShader.Set(vertexShader);
            pixelShader = new D3D11.PixelShader(device, pixelShaderBytecode);
            deviceContext.PixelShader.Set(pixelShader);

            D3D11.InputElement[] inputElements = new[]
            {
                new D3D11.InputElement("POSITION", 0, DXGI.Format.R32G32B32A32_Float, 0),
                new D3D11.InputElement("TEXTCOORD", 0, DXGI.Format.R32G32_Float, 0),
                new D3D11.InputElement("TEXTCOORD", 1, DXGI.Format.R32G32_Float, 0),
                new D3D11.InputElement("MODE", 0, DXGI.Format.R32_UInt, 0), 
            };
            deviceContext.InputAssembler.InputLayout = new D3D11.InputLayout(device, ShaderSignature.GetInputSignature(vertexShaderBytecode), inputElements);
        }
Exemplo n.º 8
0
        void Create(ShaderBytecode bytecode)
        {
            var context = m_device.ImmediateContext;

            m_vertexShader = ToDispose(new VertexShader(m_device, bytecode));
            context.VertexShader.Set(m_vertexShader);

            m_shaderDataBuffer = ToDispose(new Buffer(m_device, Utilities.SizeOf<ShaderData>(),
                ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0));

            //create world matrix
            Matrix w = Matrix.Identity;
            w *= Matrix.Scaling(2.0f, 2.0f, 0);
            w *= Matrix.Translation(-1.0f, -1.0f, 0);
            w.Transpose();
            m_shaderData.WorldMatrix = w;

            context.UpdateSubresource(ref m_shaderData, m_shaderDataBuffer);
            context.VertexShader.SetConstantBuffer(0, m_shaderDataBuffer);
        }
Exemplo n.º 9
0
        public static CompiledShaderReader ReadCompiledShader(string path)
        {
            if (File.Exists(path) && (Path.GetExtension(path) == ".cso"))
            {

                byte[] bytes = File.ReadAllBytes(path);
                ShaderReflection reflecter = new ShaderReflection(bytes);

                ShaderBytecode bytecode = new ShaderBytecode(bytes);
                ShaderProfile profile = bytecode.GetVersion();

                ConstantBuffer[] cbuffers = new ConstantBuffer[reflecter.Description.ConstantBuffers];
                for (int i = 0; i < reflecter.Description.ConstantBuffers; i++)
                {
                    cbuffers[i] = reflecter.GetConstantBuffer(i);//this might not work
                }

                ShaderParameterDescription[] paramdescriptions = new ShaderParameterDescription[reflecter.Description.InputParameters];
                for (int i = 0; i < reflecter.Description.InputParameters; i++)
                {
                    paramdescriptions[i] = reflecter.GetInputParameterDescription(i);
                }

                InputBindingDescription[] bindings = new InputBindingDescription[reflecter.Description.BoundResources];
                for (int i = 0; i < reflecter.Description.BoundResources; i++)
                {
                    bindings[i] = reflecter.GetResourceBindingDescription(i);
                }

                ConstantBuffer[] cbuffersCOPY = cbuffers.ToArray();

                return new CompiledShaderReader(path, profile.GetTypePrefix(), cbuffersCOPY, paramdescriptions.ToArray(), bindings.ToArray(), reflecter, bytecode);

            }
            else throw new Exception("Bad path " + path);
        }
Exemplo n.º 10
0
        private static void MakePixelShader()
        {
            string shaderText =
                ConstantDeclarations +

                "Texture2D spriteTexture;                      \n" +
                "SamplerState spriteSampler;                   \n" +
                " struct VS_OUT                                \n" +
                " {                                            \n" +
                "	    float4 pos : SV_POSITION;               \n" +
                "	    float2 tex : TEXCOORD;                  \n" +
                "	    float4 color : COLOR;                   \n" +
                " };                                           \n" +
                "                                              \n" +
                " float4 PS(VS_OUT In) : SV_Target               \n" +
                " {                                            \n" +
                "   float4 col = spriteTexture.Sample(spriteSampler, In.tex); \n " +
                "   float4 color;                              \n" +
                "   float1 diff = max(2*b, 0.01); //      put a floor on this \n" +
                "   float1 slope = 1/diff;                                    \n" +

                "   color.r =  max( min( (col.r-(a-b))*slope, 1), 0);                  \n" +
                "   color.g =  max( min( (col.g-(a-b))*slope, 1), 0);                  \n" +
                "   color.b = max( min( (col.b-(a-b))*slope, 1), 0);                   \n" +
                "   color.a = col.a * opacity;                                         \n" +
                "   return color * tint;                                                      \n" +
                " }                                            ";

            pixelShaderByteCode = ShaderBytecode.Compile(shaderText, "PS", RenderContext11.PixelProfile);
            pixelShader = new PixelShader(RenderContext11.PrepDevice, pixelShaderByteCode);
        }
Exemplo n.º 11
0
 public ByteCodeBind(Shaders _shaderType, ShaderBytecode _byteCode)
 {
     shaderType = _shaderType;
     byteCode = _byteCode;
 }
Exemplo n.º 12
0
        public FrustumShader(Device device)
        {
            // create single vertex buffer
            var stream = new DataStream(24 * VertexPosition.SizeInBytes, true, true);
            stream.Write(new Vector4(-1, -1, 0, 1));
            stream.Write(new Vector4( 1, -1, 0, 1));
            stream.Write(new Vector4( 1, -1, 0, 1));
            stream.Write(new Vector4( 1,  1, 0, 1));
            stream.Write(new Vector4( 1,  1, 0, 1));
            stream.Write(new Vector4(-1,  1, 0, 1));
            stream.Write(new Vector4(-1,  1, 0, 1));
            stream.Write(new Vector4(-1, -1, 0, 1));

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

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

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

            stream.Dispose();

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

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

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

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

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

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

            vertexInputLayout = new InputLayout(device, shaderByteCode.Data, new[]
            {
                new InputElement("SV_POSITION", 0, Format.R32G32B32A32_Float, 0, 0),
            });
        }
Exemplo n.º 13
0
        void Create(ShaderBytecode bytecode)
        {
            var context = m_device.ImmediateContext;

            m_pixelShader = ToDispose(new PixelShader(m_device, bytecode));
            context.PixelShader.Set(m_pixelShader);

            /* Constant buffer */
            var shaderDataBuffer = ToDispose(new Buffer(m_device, Utilities.SizeOf<ShaderData>(),
                ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0));

            context.PixelShader.SetConstantBuffer(0, shaderDataBuffer);

            ShaderData shaderData = new ShaderData()
            {
                SimpleTint = 1,
            };

            context.UpdateSubresource(ref shaderData, shaderDataBuffer);

            /* Constant buffer per frame */
            m_shaderDataBufferPerFrame = ToDispose(new Buffer(m_device, Utilities.SizeOf<ShaderDataPerFrame>(),
                ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0));

            context.PixelShader.SetConstantBuffer(1, m_shaderDataBufferPerFrame);

            /* color buffer */
            var colorBuffer = ToDispose(Helpers11.CreateGameColorBuffer(m_device));

            var colorBufferView = ToDispose(new ShaderResourceView(m_device, colorBuffer, new ShaderResourceViewDescription()
            {
                Format = SharpDX.DXGI.Format.R32_UInt,
                Dimension = ShaderResourceViewDimension.Buffer,
                Buffer = new ShaderResourceViewDescription.BufferResource()
                {
                    ElementWidth = colorBuffer.Description.SizeInBytes / sizeof(uint),
                    ElementOffset = 0,
                },
            }));

            context.PixelShader.SetShaderResource(1, colorBufferView);

            /* Texture sampler */
            var sampler = ToDispose(new SamplerState(m_device, new SamplerStateDescription()
            {
                Filter = Filter.MinMagMipLinear,
                AddressU = TextureAddressMode.Wrap,
                AddressV = TextureAddressMode.Wrap,
                AddressW = TextureAddressMode.Wrap,
                BorderColor = new Color4(0),
                ComparisonFunction = Comparison.Never,
                MaximumAnisotropy = 16,
                MipLodBias = 0,
                MinimumLod = 0,
                MaximumLod = 16,
            }));

            context.PixelShader.SetSampler(0, sampler);
        }
Exemplo n.º 14
0
        public void SetVertexShader(byte[] code)
        {
            var result = ShaderBytecode.FromStream(new MemoryStream(code));

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

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

            VertexShaderCode = result;
            mVertexShader = new VertexShader(mContext.Device, VertexShaderCode.Data);
        }
 public static SharpDX.Direct3D11.VertexShader VertexShader(SharpDX.Direct3D11.Device device, string hlslFile, string entryPoint, out ShaderBytecode bytecode, ShaderMacro[] defines = null, string profile = "vs_5_0")
 {
     bytecode = CompileFromFile(hlslFile, entryPoint, profile, defines);
     return new SharpDX.Direct3D11.VertexShader(device, bytecode);
 }
Exemplo n.º 16
0
        public Shader(String Name, String VS_EntryPoint = "VS_Main", String PS_EntryPoint = "PS_Main", String GS_EntryPoint = "GS_Main", Boolean PreCompiled = false)
        {
            Device dev = Engine.g_device;

            IncludeFX includeFX = new IncludeFX();

            if ( PreCompiled ) {
                // check that the shader is exist
                if ( File.Exists( ShaderRootPath + Name + "o" ) ) {
                    // open the file to read it
                    FileStream fileStream = new FileStream( ShaderRootPath + Name + "o", FileMode.Open );

                    // allocate the byte stream
                    byte[] fileByte = new byte[fileStream.Length];

                    // read the file stream
                    fileStream.Read( fileByte, 0, (int)fileStream.Length );

                    // close the file stream
                    fileStream.Close();

                    DataStream preBuildShaderStream = new DataStream( fileByte.Length, true, true );
                    preBuildShaderStream.Write(fileByte, 0, fileByte.Length);

                    m_PixelShaderByteCode = new ShaderBytecode( preBuildShaderStream );
                    m_VertexShaderByteCode = new ShaderBytecode( preBuildShaderStream );
                } else {
                    System.Windows.Forms.MessageBox.Show( "Shader:" + ShaderRootPath + Name + "o" + "   is not exist " );

                    return;
                }

            } else {
                // set the shader flags base on the debugging
                ShaderFlags sf;
                if ( Settings.Debug ) {
                    sf = ShaderFlags.SkipOptimization | ShaderFlags.Debug | ShaderFlags.PreferFlowControl;
                } else {
                    sf = ShaderFlags.OptimizationLevel3;
                }

                // set the compile feature
                String CompileLevelPS;
                String CompileLevelVS;
                String CompileLevelGS;

                if (Settings.FeatureLevel == FeatureLevel.Level_11_0)
                {
                    CompileLevelPS = "ps_5_0";
                    CompileLevelVS = "vs_5_0";
                    CompileLevelGS = "gs_5_0";
                }
                else
                {
                    CompileLevelPS = "ps_4_0";
                    CompileLevelVS = "vs_4_0";
                    CompileLevelGS = "gs_4_0";
                }

                try
                {
                    /// compile the shader to byte code
                    m_PixelShaderByteCode = ShaderBytecode.CompileFromFile(
                                                ShaderRootPath + Name,       /// File Path of the file containing the code
                                                PS_EntryPoint,               /// The entry point for the shader
                                                CompileLevelPS,              /// What specifications (shader version) to compile with
                                                sf, EffectFlags.None, null, includeFX);

                    /// compile the shader to byte code
                    m_VertexShaderByteCode = ShaderBytecode.CompileFromFile(
                                                ShaderRootPath + Name,       /// File Path of the file containing the code
                                                VS_EntryPoint,               /// The entry point for the shader
                                                CompileLevelVS,              /// What specifications (shader version) to compile with
                                                sf, EffectFlags.None, null, includeFX);

                    try
                    {
                        /// compile the shader to byte code
                        m_GeometryShaderByteCode = ShaderBytecode.CompileFromFile(
                                                    ShaderRootPath + Name,       /// File Path of the file containing the code
                                                    GS_EntryPoint,               /// The entry point for the shader
                                                    CompileLevelGS,              /// What specifications (shader version) to compile with
                                                    sf, EffectFlags.None, null, includeFX);
                    }catch(Exception ex)
                    {
                        // the geometry shader is not mandatory
                    }
                }
                catch (Exception ex)
                {
                    System.Windows.Forms.MessageBox.Show(ex.Message);

                }
            }

            /// init effect
            m_effect = new FXEffect( dev, m_PixelShaderByteCode, m_VertexShaderByteCode, null, m_GeometryShaderByteCode );

            /// init all the variables
            InitVariables();
        }
Exemplo n.º 17
0
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            RenderForm form = new RenderForm("Kinect Camera Joint sample");

            RenderDevice device = new RenderDevice(SharpDX.Direct3D11.DeviceCreationFlags.BgraSupport | DeviceCreationFlags.Debug);
            RenderContext context = new RenderContext(device);
            DX11SwapChain swapChain = DX11SwapChain.FromHandle(device, form.Handle);

            DX11DepthStencil depthStencil = new DX11DepthStencil(device, swapChain.Width, swapChain.Height, eDepthFormat.d24s8);

            //VertexShader vertexShader = ShaderCompiler.CompileFromFile<VertexShader>(device, "ColorJointView.fx", "VS");
            SharpDX.D3DCompiler.ShaderSignature signature;
            VertexShader vertexShader = ShaderCompiler.CompileFromFile(device, "CameraJointView.fx", "VS_Color", out signature);
            PixelShader pixelShader = ShaderCompiler.CompileFromFile<PixelShader>(device, "CameraJointView.fx", "PS_Color");

            VertexShader vertexShaderLine = ShaderCompiler.CompileFromFile<VertexShader>(device, "CameraJointView.fx", "VS");
            PixelShader pixelShaderLine = ShaderCompiler.CompileFromFile<PixelShader>(device, "CameraJointView.fx", "PS_White");

            JointTableIndexBuffer indexBuffer = new JointTableIndexBuffer(device, 6);

            DX11IndexedGeometry cube = device.Primitives.Box(new Box()
            {
                Size = new Vector3(0.05f)
            });
            DX11InstancedIndexedDrawer drawer = new DX11InstancedIndexedDrawer();
            cube.AssignDrawer(drawer);

            InputLayout layout;
            var bc = new ShaderBytecode(signature);
            cube.ValidateLayout(bc, out layout);

            KinectSensor sensor = KinectSensor.GetDefault();
            sensor.Open();

            Color4[] statusColor = new Color4[]
            {
                Color.Red,
                Color.Yellow,
                Color.Green
            };

            cbCamera camera = new cbCamera();
            camera.Projection = Matrix.PerspectiveFovLH(1.57f, 1.3f, 0.1f, 100.0f);
            camera.View = Matrix.Translation(0.0f, 0.0f, 2.0f);

            camera.Projection.Transpose();
            camera.View.Transpose();

            ConstantBuffer<cbCamera> cameraBuffer = new ConstantBuffer<cbCamera>(device);
            cameraBuffer.Update(context, ref camera);

            DX11StructuredBuffer colorTableBuffer = DX11StructuredBuffer.CreateImmutable<Color4>(device, statusColor);

            bool doQuit = false;
            bool doUpload = false;

            int bodyCount = 0;
            KinectBody[] bodyFrame = null;
            BodyCameraPositionBuffer positionBuffer = new BodyCameraPositionBuffer(device);
            BodyJointStatusBuffer statusBuffer = new BodyJointStatusBuffer(device);

            KinectSensorBodyFrameProvider provider = new KinectSensorBodyFrameProvider(sensor);
            provider.FrameReceived += (sender, args) => { bodyFrame = args.FrameData; doUpload = true; };

            form.KeyDown += (sender, args) => { if (args.KeyCode == Keys.Escape) { doQuit = true; } };

            context.Context.OutputMerger.DepthStencilState = device.DepthStencilStates.LessReadWrite;
            context.Context.Rasterizer.State = device.RasterizerStates.BackCullSolid;

            RenderLoop.Run(form, () =>
            {
                if (doQuit)
                {
                    form.Dispose();
                    return;
                }

                if (doUpload)
                {
                    var tracked = bodyFrame.TrackedOnly();
                    bodyCount = tracked.Count();

                    positionBuffer.Copy(context, tracked);
                    statusBuffer.Copy(context, tracked);
                    drawer.InstanceCount = tracked.Count() * Microsoft.Kinect.Body.JointCount;
                }

                context.RenderTargetStack.Push(depthStencil, false,swapChain);
                context.Context.ClearRenderTargetView(swapChain.RenderView, SharpDX.Color.Black);
                depthStencil.Clear(context);

                /*Position buffer and cbuffers are the same data and in same slot,
                 * so we bind them only once*/
                context.Context.VertexShader.SetShaderResource(0, positionBuffer.ShaderView);
                context.Context.VertexShader.SetConstantBuffer(0, cameraBuffer.Buffer);

                //Draw lines
                context.Context.PixelShader.Set(pixelShaderLine);
                context.Context.VertexShader.Set(vertexShaderLine);

                //Attach index buffer, null topology since we fetch
                indexBuffer.AttachWithLayout(context);
                indexBuffer.Draw(context,bodyCount);

                //Draw cubes
                cube.Bind(context, layout);
                context.Context.VertexShader.Set(vertexShader);
                context.Context.PixelShader.Set(pixelShader);

                context.Context.VertexShader.SetShaderResource(1, statusBuffer.ShaderView);
                context.Context.VertexShader.SetShaderResource(2, colorTableBuffer.ShaderView);

                cube.Draw(context);

                context.RenderTargetStack.Pop();
                swapChain.Present(0, SharpDX.DXGI.PresentFlags.None);
            });

            swapChain.Dispose();
            depthStencil.Dispose();
            context.Dispose();
            device.Dispose();

            positionBuffer.Dispose();
            statusBuffer.Dispose();
            colorTableBuffer.Dispose();

            cameraBuffer.Dispose();

            provider.Dispose();
            cube.Dispose();
            layout.Dispose();

            pixelShader.Dispose();
            vertexShader.Dispose();

            pixelShaderLine.Dispose();
            vertexShaderLine.Dispose();
            indexBuffer.Dispose();

            sensor.Close();
        }
 internal static void CreateShader(Device device, out ShaderBytecode shaderCode, out ComputeShader shader, string shaderPath)
 {
     MemoryStream mem = new MemoryStream(GetEmbeddedContent(shaderPath));
     shaderCode = new ShaderBytecode(mem);
     shader = new ComputeShader(device, shaderCode);
 }
Exemplo n.º 19
0
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            RenderForm form = new RenderForm("Kinect RGB Joint sample");

            RenderDevice device = new RenderDevice(SharpDX.Direct3D11.DeviceCreationFlags.BgraSupport | DeviceCreationFlags.Debug);
            RenderContext context = new RenderContext(device);
            DX11SwapChain swapChain = DX11SwapChain.FromHandle(device, form.Handle);

            //VertexShader vertexShader = ShaderCompiler.CompileFromFile<VertexShader>(device, "ColorJointView.fx", "VS");
            SharpDX.D3DCompiler.ShaderSignature signature;
            VertexShader vertexShader = ShaderCompiler.CompileFromFile(device, "ColorJointView.fx", "VS_Color", out signature);
            PixelShader pixelShader = ShaderCompiler.CompileFromFile<PixelShader>(device, "ColorJointView.fx", "PS_Color");

            DX11IndexedGeometry circle = device.Primitives.Segment(new Segment()
            {
                Resolution = 32
            });
            DX11InstancedIndexedDrawer drawer = new DX11InstancedIndexedDrawer();
            circle.AssignDrawer(drawer);

            InputLayout layout;
            var bc = new ShaderBytecode(signature);
            circle.ValidateLayout(bc, out layout);

            KinectSensor sensor = KinectSensor.GetDefault();
            sensor.Open();

            Color4[] statusColor = new Color4[]
            {
                Color.Red,
                Color.Yellow,
                Color.Green
            };

            //Note cbuffer should have a minimum size of 16 bytes, so we create verctor4 instead of vector2
            SharpDX.Vector4 jointSize = new SharpDX.Vector4(0.04f,0.07f,0.0f,1.0f);
            ConstantBuffer<SharpDX.Vector4> cbSize = new ConstantBuffer<SharpDX.Vector4>(device);
            cbSize.Update(context, ref jointSize);

            DX11StructuredBuffer colorTableBuffer = DX11StructuredBuffer.CreateImmutable<Color4>(device, statusColor);

            bool doQuit = false;
            bool doUpload = false;
            bool uploadImage = false;

            KinectBody[] bodyFrame = null;
            BodyColorPositionBuffer positionBuffer = new BodyColorPositionBuffer(device);
            BodyJointStatusBuffer statusBuffer = new BodyJointStatusBuffer(device);

            KinectSensorBodyFrameProvider provider = new KinectSensorBodyFrameProvider(sensor);
            provider.FrameReceived += (sender, args) => { bodyFrame = args.FrameData; doUpload = true; };

            ColorRGBAFrameData rgbFrame = null;
            DynamicColorRGBATexture colorTexture = new DynamicColorRGBATexture(device);
            KinectSensorColorRGBAFrameProvider colorProvider = new KinectSensorColorRGBAFrameProvider(sensor);
            colorProvider.FrameReceived += (sender, args) => { rgbFrame = args.FrameData; uploadImage = true; };

            form.KeyDown += (sender, args) => { if (args.KeyCode == Keys.Escape) { doQuit = true; } };

            RenderLoop.Run(form, () =>
            {
                if (doQuit)
                {
                    form.Dispose();
                    return;
                }

                if (doUpload)
                {
                    var tracked = bodyFrame.TrackedOnly();
                    var colorSpace = tracked.Select(kb => new ColorSpaceKinectJoints(kb, sensor.CoordinateMapper));

                    positionBuffer.Copy(context, colorSpace);
                    statusBuffer.Copy(context, tracked);
                    drawer.InstanceCount = colorSpace.Count() * Microsoft.Kinect.Body.JointCount;
                }

                if (uploadImage)
                {
                    colorTexture.Copy(context, rgbFrame);
                }

                context.RenderTargetStack.Push(swapChain);
                context.Context.ClearRenderTargetView(swapChain.RenderView, SharpDX.Color.Black);

                device.Primitives.ApplyFullTri(context, colorTexture.ShaderView);
                device.Primitives.FullScreenTriangle.Draw(context);

                circle.Bind(context, layout);

                context.Context.PixelShader.Set(pixelShader);
                context.Context.VertexShader.Set(vertexShader);
                context.Context.VertexShader.SetShaderResource(0, positionBuffer.ShaderView);
                context.Context.VertexShader.SetShaderResource(1, statusBuffer.ShaderView);
                context.Context.VertexShader.SetShaderResource(2, colorTableBuffer.ShaderView);
                context.Context.VertexShader.SetConstantBuffer(0, cbSize.Buffer);

                circle.Draw(context);

                context.RenderTargetStack.Pop();
                swapChain.Present(0, SharpDX.DXGI.PresentFlags.None);
            });

            swapChain.Dispose();
            context.Dispose();
            device.Dispose();

            colorProvider.Dispose();
            colorTexture.Dispose();

            positionBuffer.Dispose();
            statusBuffer.Dispose();
            colorTableBuffer.Dispose();

            cbSize.Dispose();

            provider.Dispose();
            circle.Dispose();
            layout.Dispose();

            pixelShader.Dispose();
            vertexShader.Dispose();

            sensor.Close();
        }
Exemplo n.º 20
0
        private static void MakePixelShaderNoTexture()
        {
            string shaderText =
                "struct PS_IN                                \n" +
                    "{                                          \n" +
                    "	float4 pos : SV_POSITION;               \n" +
                    "	float2 tex : TEXCOORD;                  \n" +
                    "	float4 color : COLOR;               \n" +
                    "};                                             \n" +
                "    \n" +
                " Texture2D picture;     \n" +
                " SamplerState pictureSampler;   \n" +
                "    \n" +
                "    \n" +
                "    \n" +
                " float4 PS( PS_IN input ) : SV_Target   \n" +
                " {     \n" +
                " 	return input.color;   \n" +
                " }   \n" +
                "    ";

            pixelShaderByteCodeNoTexture = ShaderBytecode.Compile(shaderText, "PS", RenderContext11.PixelProfile);
            pixelShaderNoTexture = new PixelShader(RenderContext11.PrepDevice, pixelShaderByteCodeNoTexture);
        }
        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;
        }
Exemplo n.º 22
0
        /// <summary>	
        /// Decompresses one or more shaders from a compressed set.	
        /// </summary>	
        /// <param name="indices"><para>An array of indexes that represent the shaders to decompress.</para></param>	
        /// <returns>Returns an array of decompress shader bytecode.</returns>	
        /// <unmanaged>HRESULT D3DDecompressShaders([In, Buffer] const void* pSrcData,[In] SIZE_T SrcDataSize,[In] unsigned int uNumShaders,[In] unsigned int uStartIndex,[In, Buffer, Optional] unsigned int* pIndices,[In] unsigned int uFlags,[Out, Buffer] ID3D10Blob** ppShaders,[Out, Optional] unsigned int* pTotalShaders)</unmanaged>	
        public unsafe ShaderBytecode[] Decompress(int[] indices)
        {
            if (indices.Length == 0)
                return null;
            var shadersBlobs = new Blob[indices.Length];
            int totalShadersRef;
            fixed (void* bufferPtr = Data)
                D3D.DecompressShaders((IntPtr)bufferPtr, Data.Length, indices.Length, 0, indices, 0, shadersBlobs, out totalShadersRef);

            //The size of shadersBlobs will not change
            //if the compressed shader contains less than requested in numShaders, null entries will appear in the result array
            var shadersByteArr = new ShaderBytecode[shadersBlobs.Length];
            for (int i = 0; i < shadersBlobs.Length; i++)
                if (shadersBlobs[i] != null)
                    shadersByteArr[i] = new ShaderBytecode(shadersBlobs[i]);

            return shadersByteArr;
        }
Exemplo n.º 23
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);
        }
        public DepthAndColorShader(Device device)
        {
            shaderByteCode = new ShaderBytecode(File.ReadAllBytes("Content/DepthAndColorFloatVS.cso"));
            depthAndColorVS = new VertexShader(device, shaderByteCode);
            depthAndColorGS = new GeometryShader(device, new ShaderBytecode(File.ReadAllBytes("Content/DepthAndColorGS.cso")));
            depthAndColorPS = new PixelShader(device, new ShaderBytecode(File.ReadAllBytes("Content/DepthAndColorPS.cso")));

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

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

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

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

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

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

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

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

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

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

            vertexInputLayout = new InputLayout(device, shaderByteCode.Data, new[]
            {
                new InputElement("SV_POSITION", 0, Format.R32G32B32A32_Float, 0, 0),
            });
        }
Exemplo n.º 25
0
        private static Effect GetEffect(Device device, byte[] effectBytes)
        {
            Effect effect;

            using (var dataStream = new DataStream(effectBytes.Length, true, true))
            {
                dataStream.WriteRange(effectBytes);
                dataStream.Position = 0;

                using (var bytecode = new ShaderBytecode(dataStream))
                {
                    effect = new Effect(device, bytecode);
                }
            }

            return effect;
        }
Exemplo n.º 26
0
        public void SetVertexShader(string code, string entry)
        {
            var result = ShaderBytecode.Compile(Encoding.UTF8.GetBytes(code), entry, "vs_5_0", ShaderFlags.OptimizationLevel3);
            if (result.HasErrors)
                throw new ArgumentException(result.Message, "code");

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

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

            VertexShaderCode = result.Bytecode;
            mVertexShader = new VertexShader(mContext.Device, VertexShaderCode.Data);
        }
        public EffectContainer(Device device, string EffectFile, InputElement[] _InputElement)
        {
            //Name = EffectFile;
            string extension = System.IO.Path.GetExtension(EffectFile);
            if (extension.ToLower() == ".fx")
            {
                IncludeFX includeFX = new IncludeFX();
                //Компилируем шейдер в байткод
            #if !DEBUG
                //на время отладки шейдеров
                try
            #endif
                {
                    SharpDX.Direct3D.ShaderMacro[] Macross = new SharpDX.Direct3D.ShaderMacro[6];
                    Macross[0] = new SharpDX.Direct3D.ShaderMacro("DX10_1", (Program.featureLevel > FeatureLevel.Level_10_0)? 1:0 );
                    Macross[1] = new SharpDX.Direct3D.ShaderMacro("SPLITCOUNT", PSSMsHelper.SplitsNumber);
                    Macross[2] = new SharpDX.Direct3D.ShaderMacro("OCCLPPIXELINTEX", DrawHelper.OcclPixelInTex);
                    Macross[3] = new SharpDX.Direct3D.ShaderMacro("SCREENX", Global.Settings.Width);
                    Macross[4] = new SharpDX.Direct3D.ShaderMacro("SCREENY", Global.Settings.Height);

                    using (ShaderBytecode bytecode = ShaderBytecode.CompileFromFile(EffectFile, "fx_5_0",
            #if DEBUG
                        ShaderFlags.Debug | ShaderFlags.SkipOptimization | ShaderFlags.PreferFlowControl,
            #else
                        ShaderFlags.OptimizationLevel3,
            #endif
                        EffectFlags.None, Macross, includeFX))
                    {
                        // Загрузим скомпилированный эффект в видеокарту
                        renderEffect = new Effect(device, bytecode);
                    }
                }
            #if !DEBUG
                catch (System.Exception ex)
                {
                    System.Windows.Forms.MessageBox.Show("Error! Ошибкак чтения эффекта: " + EffectFile);
                    new CompilationException(EffectFile);
                }
            #endif
            }
            else if (extension.ToLower() == ".ees")
            {
                try
                {
                    System.IO.FileStream fs = new System.IO.FileStream(EffectFile, System.IO.FileMode.Open, System.IO.FileAccess.Read);
                    byte[] bytes = new byte[(int)fs.Length];
                    fs.Read(bytes, 0, (int)fs.Length);
                    fs.Close();

                    using (DataStream DS = new DataStream(bytes.Length, true, true))
                    {
                        DS.Write(bytes, 0, bytes.Length);
                        using (ShaderBytecode bytecode = new ShaderBytecode(DS))
                        {
                            renderEffect = new Effect(device, bytecode);
                        }
                    }
                }
                catch (System.Exception ex)
                {
                    System.Windows.Forms.MessageBox.Show("Error! Ошибкак чтения эффекта: " + EffectFile);
                    new CompilationException(EffectFile);
                }
            }
            else
            {
                System.Windows.Forms.MessageBox.Show("Error! Не найден файл эффекта: " + EffectFile);
                new FileNotFoundException("Не найден файл", EffectFile);
            }

            //TODO изучить влияние
            renderEffect.Optimize();
            TechniqueCount = renderEffect.Description.TechniqueCount;
            renderTechniques = new EffectTechnique[TechniqueCount];
            // Загружаем техники из шейдера
            for (int i = 0; i < TechniqueCount; i++)
            {
                renderTechniques[i] = renderEffect.GetTechniqueByIndex(i);
            }
            // Выберем входную сигнатуру данных первого прохода
            var renderPassSignature = renderTechniques[0].GetPassByIndex(0).Description.Signature;

            if (_InputElement == null)
            {
                _InputElement= new InputElement[]{
                new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0),
                new InputElement("NORMAL", 0, Format.R32G32B32_Float, 12, 0),
                new InputElement("TEXCOORD", 0, Format.R32G32_Float, 24, 0),
                new InputElement("TEXCOORD", 1, Format.R32G32_Float, 32, 0),
                new InputElement("TANGENT", 0, Format.R32G32B32_Float, 40, 0),
                new InputElement("BINORMAL", 0, Format.R32G32B32_Float, 52, 0)};

            }

            //создаем входную конфигурвцию для стандартного меша
            layout = new InputLayout(device, renderPassSignature, _InputElement);
        }
Exemplo n.º 28
0
        /// <summary>
        /// Precompile the shader
        /// </summary>
        /// <param name="Name"></param>
        public ComputeShader( String Name )
        {
            Device dev = Engine.g_device;

            IncludeFX includeFX = new IncludeFX();
            ShaderBytecode bytecode= null;

            // check that the shader is exist
            if ( File.Exists( ShaderRootPath + Name ) ) {
                // open the file to read it
                FileStream fileStream = new FileStream( ShaderRootPath + Name, FileMode.Open );

                // allocate the byte stream
                byte []fileByte = new byte[fileStream.Length];

                // read the file stream
                fileStream.Read( fileByte, 0, (int)fileStream.Length );

                // close the file stream
                fileStream.Close();

                bytecode = new ShaderBytecode(fileByte);

            } else {
                System.Windows.Forms.MessageBox.Show( "Shader:" + ShaderRootPath + Name + "   is not exist " );

                return;
            }

            // init effect
            m_effect = new FXEffect( dev, csByteCode: bytecode );
        }
Exemplo n.º 29
0
 /// <summary>
 /// Function to create the shader.
 /// </summary>
 /// <param name="byteCode">Byte code for the shader.</param>
 protected abstract void CreateShader(Shaders.ShaderBytecode byteCode);