Exemplo n.º 1
0
        private Shader(GraphicsDevice device, ShaderStage shaderStage, byte[] shaderBytecode)
            : base(device)
        {
            this.stage = shaderStage;

            switch (shaderStage)
            {
                case ShaderStage.Vertex:
                    NativeDeviceChild = new VertexShader(device.NativeDevice, shaderBytecode);
                    NativeInputSignature = shaderBytecode;
                    break;
                case ShaderStage.Hull:
                    NativeDeviceChild = new HullShader(device.NativeDevice, shaderBytecode);
                    break;
                case ShaderStage.Domain:
                    NativeDeviceChild = new DomainShader(device.NativeDevice, shaderBytecode);
                    break;
                case ShaderStage.Geometry:
                    NativeDeviceChild = new GeometryShader(device.NativeDevice, shaderBytecode);
                    break;
                case ShaderStage.Pixel:
                    NativeDeviceChild = new PixelShader(device.NativeDevice, shaderBytecode);
                    break;
                case ShaderStage.Compute:
                    NativeDeviceChild = new ComputeShader(device.NativeDevice, shaderBytecode);
                    break;
                default:
                    throw new ArgumentOutOfRangeException("shaderStage");
            }
        }
Exemplo n.º 2
0
        /// <summary>
        /// Releases unmanaged and - optionally - managed resources
        /// </summary>
        /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
        protected override void Dispose(bool disposing)
        {
            if (!_disposed)
            {
                if (disposing)
                {
                    // Disassociate any shaders after we've destroyed them.
                    if (Graphics.Shaders.HullShader.Current == this)
                    {
                        Graphics.Shaders.HullShader.Current = null;
                    }

                    if (D3DShader != null)
                    {
                        D3DShader.Dispose();
                    }

                    D3DShader = null;
                }

                _disposed = true;
            }

            base.Dispose(disposing);
        }
Exemplo n.º 3
0
        /// <summary>
        ///
        /// </summary>
        void SetupShadersAndLayouts()
        {
            ps = PixelShader == null ? null : new D3DPixelShader(device.Device, PixelShader.Bytecode);
            vs = VertexShader == null ? null : new D3DVertexShader(device.Device, VertexShader.Bytecode);
            gs = GeometryShader == null ? null : new D3DGeometryShader(device.Device, GeometryShader.Bytecode);
            hs = HullShader == null ? null : new D3DHullShader(device.Device, HullShader.Bytecode);
            ds = DomainShader == null ? null : new D3DDomainShader(device.Device, DomainShader.Bytecode);
            cs = ComputeShader == null ? null : new D3DComputeShader(device.Device, ComputeShader.Bytecode);

            if (cs != null)
            {
                if (ps != null || vs != null || gs != null || hs != null || ds != null)
                {
                    throw new InvalidOperationException("If ComputeShader is set, other shader must be set null.");
                }
            }
            else
            {
                if (vs == null)
                {
                    throw new InvalidOperationException("Vertex shader must be set.");
                }
            }



            if (VertexInputElements == null)
            {
                inputLayout = null;
            }
            else
            {
                inputLayout = new InputLayout(device.Device, VertexShader.Bytecode, VertexInputElement.Convert(VertexInputElements));
            }



            if (VertexOutputElements != null)
            {
                if (GeometryShader == null)
                {
                    throw new InvalidOperationException("Geometry shader is required for vertex output.");
                }

                var outputElements  = VertexOutputElement.Convert(VertexOutputElements);
                int maxBuffers      = outputElements.Max(oe => oe.OutputSlot) + 1;
                var bufferedStrides = new int[maxBuffers];

                for (int i = 0; i < maxBuffers; i++)
                {
                    bufferedStrides[i] = outputElements
                                         .Where(oe1 => oe1.OutputSlot == i)
                                         .Sum(oe2 => oe2.ComponentCount) * 4;
                }

                gs = new D3DGeometryShader(device.Device, GeometryShader.Bytecode, outputElements, bufferedStrides, RasterizedStream);
            }
        }
Exemplo n.º 4
0
 /// <summary>
 /// Initializes a new instance of the <see cref="GorgonHullShader" /> class.
 /// </summary>
 /// <param name="graphics">The graphics interface that owns this object.</param>
 /// <param name="name">The name for this shader.</param>
 /// <param name="isDebug"><b>true</b> if debug information is included in the byte code, <b>false</b> if not.</param>
 /// <param name="byteCode">The byte code for the shader.</param>
 internal GorgonHullShader(GorgonGraphics graphics, string name, bool isDebug, ShaderBytecode byteCode)
     : base(graphics, name, isDebug, byteCode)
 {
     graphics.Log.Print($"Creating {ShaderType} '{name}' ({ID})", LoggingLevel.Verbose);
     _shader = new D3D11.HullShader(graphics.D3DDevice, byteCode)
     {
         DebugName = name + "_ID3D11HullShader"
     };
 }
Exemplo n.º 5
0
        private void CreateShaders()
        {
            foreach (var shaderBytecode in effectBytecode.Stages)
            {
                var bytecodeRaw = shaderBytecode.Data;
                var reflection = effectBytecode.Reflection;

                // TODO CACHE Shaders with a bytecode hash
                switch (shaderBytecode.Stage)
                {
                    case ShaderStage.Vertex:
                        vertexShader = new VertexShader(GraphicsDevice.NativeDevice, bytecodeRaw);
                        // Note: input signature can be reused when reseting device since it only stores non-GPU data,
                        // so just keep it if it has already been created before.
                        if (inputSignature == null)
                            inputSignature = EffectInputSignature.GetOrCreateLayout(new EffectInputSignature(shaderBytecode.Id, bytecodeRaw));
                        break;
                    case ShaderStage.Domain:
                        domainShader = new DomainShader(GraphicsDevice.NativeDevice, bytecodeRaw);
                        break;
                    case ShaderStage.Hull:
                        hullShader = new HullShader(GraphicsDevice.NativeDevice, bytecodeRaw);
                        break;
                    case ShaderStage.Geometry:
                        if (reflection.ShaderStreamOutputDeclarations != null && reflection.ShaderStreamOutputDeclarations.Count > 0)
                        {
                            // Calculate the strides
                            var soStrides = new List<int>();
                            foreach (var streamOutputElement in reflection.ShaderStreamOutputDeclarations)
                            {
                                for (int i = soStrides.Count; i < (streamOutputElement.Stream + 1); i++)
                                {
                                    soStrides.Add(0);
                                }

                                soStrides[streamOutputElement.Stream] += streamOutputElement.ComponentCount * sizeof(float);
                            }
                            var soElements = new StreamOutputElement[0]; // TODO CREATE StreamOutputElement from bytecode.Reflection.ShaderStreamOutputDeclarations
                            geometryShader = new GeometryShader(GraphicsDevice.NativeDevice, bytecodeRaw, soElements, soStrides.ToArray(), reflection.StreamOutputRasterizedStream);
                        }
                        else
                        {
                            geometryShader = new GeometryShader(GraphicsDevice.NativeDevice, bytecodeRaw);
                        }
                        break;
                    case ShaderStage.Pixel:
                        pixelShader = new PixelShader(GraphicsDevice.NativeDevice, bytecodeRaw);
                        break;
                    case ShaderStage.Compute:
                        computeShader = new ComputeShader(GraphicsDevice.NativeDevice, bytecodeRaw);
                        break;
                }
            }
        }
Exemplo n.º 6
0
        /// <summary>
        /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
        /// </summary>
        public override void Dispose()
        {
            D3D11.HullShader shader = Interlocked.Exchange(ref _shader, null);

            if (shader != null)
            {
                Graphics.Log.Print($"Destroying {ShaderType} '{Name}' ({ID})", LoggingLevel.Verbose);
                shader.Dispose();
            }

            base.Dispose();
        }
Exemplo n.º 7
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.HullShader(Graphics.D3DDevice, byteCode)
            {
#if DEBUG
                DebugName = string.Format("Gorgon Hull Shader '{0}'", Name)
#endif
            };
        }
Exemplo n.º 8
0
        public CHullShader(ICDevice device, CShaderReflection reflection)
            : base(device, reflection)
        {
            Profile = ParseProfile(reflection.Profile);
            Domain = reflection.GetTesselationDomain();
            Partitioning = reflection.GetTesselationPartitioning();
            OutputTopology = reflection.GetTesselationOutputTopology();
            InputControlPoints = reflection.GetInputControlPoints();
            OutputControlPoints = reflection.GetOutputControlPoints();
            MaxTesselationFactor = reflection.GetMaxTesselationFactor();

            var text = GenerateText<CHullShader>(WriteIOAndCode);
            CompilationResult bytecode;
            try
            {
                bytecode = ShaderBytecode.Compile(text, "main", ProfileToString(Profile),
                    ShaderFlags.PackMatrixColumnMajor | ShaderFlags.OptimizationLevel3, EffectFlags.None, Name);
            }
            catch (Exception e)
            {
                throw new ArgumentException(string.Format("Failed to compile a hull shader '{0}'\r\n--- Code ---\r\n{1}\r\n--- Errors ---\r\n{2}", Name, text, e.Message), e);
            }
            D3DHullShader = new HullShader(device.D3DDevice, bytecode);
        }
Exemplo n.º 9
0
        private void Run()
        {
            var window = new TesselationParameterForm();
            window.Show();

            var deviceManager = new DeviceManager();
            deviceManager.Initialize(deviceCreationFlags: DeviceCreationFlags.Debug);

            var settings = new RenderFormSettings(800, 600, false, false, "hello!", WindowAssociationFlags.IgnoreAll);

            var renderWindow = new PresentationWindow(settings);
            renderWindow.SwapChain = deviceManager.CreateSwapChainForWindow(renderWindow.Handle, settings);

            var rtCreationSettings = new RenderTarget.Configuration.CreationSettings(
                new Size(settings.Width, settings.Height),
                true,
                new SampleDescription(1, 0),
                RenderTarget.Configuration.RenderTargetClearSettings.Default,
                RenderTarget.Configuration.DepthStencilClearSettings.Default);

            var renderTarget = deviceManager.RenderTargetManager.CreateRenderTargetFromSwapChain(renderWindow.SwapChain, rtCreationSettings);

            var context = deviceManager.Context;

            context.Rasterizer.SetViewports(new Viewport(0, 0, settings.Width, settings.Height, 0.0f, 1.0f));

            var vertexData = new[]
                                 {
                                     new VertexPosition {Position = new Vector3(0.0f, 0.5f, 0.5f)},
                                     new VertexPosition {Position = new Vector3(0.5f, -0.5f, 0.5f)},
                                     new VertexPosition {Position = new Vector3(-0.5f, -0.5f, 0.5f)},
                                 };

            var stride = Marshal.SizeOf(typeof (VertexPosition));

            var vertexBufferDesc = new BufferDescription(
                stride*vertexData.Length,
                ResourceUsage.Immutable,
                BindFlags.VertexBuffer,
                CpuAccessFlags.None,
                ResourceOptionFlags.None,
                stride);

            var vertexBuffer = Buffer.Create(deviceManager.Device, vertexData, vertexBufferDesc);

            var binding = new VertexBufferBinding(vertexBuffer, stride, 0);
            var inputLayout = new InputLayoutCache(deviceManager.Device).GetLayout<VertexPosition>();

            var fileName = "../../Shaders/triangle.fx";
            var hullShader = new HullShader(deviceManager.Device, deviceManager.ShaderCompiler.LoadByteCodeFromFile(ShaderCompiler.ShaderType.HullShader, fileName, "HS"));
            var domainerShader = new DomainShader(deviceManager.Device, deviceManager.ShaderCompiler.LoadByteCodeFromFile(ShaderCompiler.ShaderType.DomainShader, fileName, "DS"));
            var vertexShader = new VertexShader(deviceManager.Device, deviceManager.ShaderCompiler.LoadByteCodeFromFile(ShaderCompiler.ShaderType.VertexShader, fileName, "VS"));
            var pixelShader = new PixelShader(deviceManager.Device, deviceManager.ShaderCompiler.LoadByteCodeFromFile(ShaderCompiler.ShaderType.PixelShader, fileName, "PS"));

            Console.Out.WriteLine("");

            var rasterizerState = new RasterizerState(deviceManager.Device, new RasterizerStateDescription
                                                                                {
                                                                                    CullMode = CullMode.None,
                                                                                    FillMode = FillMode.Wireframe,
                                                                                    IsDepthClipEnabled = false,
                                                                                    IsFrontCounterClockwise = false,
                                                                                    IsScissorEnabled = false
                                                                                });

            var constantBuffer = new ConstantBuffer<TessellationParameters>(deviceManager.Device);
            var parameters = new TessellationParameters
                                 {
                                     TessellationFactor = 5
                                 };

            RenderLoop.Run(renderWindow, () =>
                                             {
                                                 renderTarget.SetActive(context);
                                                 renderTarget.Clear(context);

                                                 context.InputAssembler.SetVertexBuffers(0, binding);
                                                 context.InputAssembler.PrimitiveTopology = PrimitiveTopology.PatchListWith3ControlPoints;
                                                 context.InputAssembler.InputLayout = inputLayout;

                                                 context.VertexShader.Set(vertexShader);
                                                 context.PixelShader.Set(pixelShader);
                                                 context.HullShader.Set(hullShader);
                                                 context.DomainShader.Set(domainerShader);

                                                 parameters.TessellationFactor = window.TesselationFactor;

                                                 constantBuffer.UpdateValue(parameters);
                                                 context.HullShader.SetConstantBuffer(0, constantBuffer.Buffer);

                                                 //context.OutputMerger.DepthStencilState = null;

                                                 context.Rasterizer.State = rasterizerState;

                                                 context.Draw(3, 0);

                                                 renderWindow.Present();
                                             });

            deviceManager.Dispose();
        }
Exemplo n.º 10
0
 internal HullShader( GraphicsDevice device, string bytecode )
     : base(bytecode)
 {
     Shader = new D3D11.HullShader( device.Device, Misc.HexStringToByte(bytecode) );
 }
Exemplo n.º 11
0
        internal DeviceChild GetOrCompileShader(EffectShaderType shaderType, int index, int soRasterizedStream, StreamOutputElement[] soElements, out string profileError)
        {
            DeviceChild shader = null;
            profileError = null;
            lock (sync)
            {
                shader = compiledShadersGroup[(int)shaderType][index];
                if (shader == null)
                {
                    if (RegisteredShaders[index].Level > graphicsDevice.Features.Level)
                    {
                        profileError = string.Format("{0}", RegisteredShaders[index].Level);
                        return null;
                    }

                    var bytecodeRaw = RegisteredShaders[index].Bytecode;
                    switch (shaderType)
                    {
                        case EffectShaderType.Vertex:
                            shader = new VertexShader(graphicsDevice, bytecodeRaw);
                            break;
                        case EffectShaderType.Domain:
                            shader = new DomainShader(graphicsDevice, bytecodeRaw);
                            break;
                        case EffectShaderType.Hull:
                            shader = new HullShader(graphicsDevice, bytecodeRaw);
                            break;
                        case EffectShaderType.Geometry:
                            if (soElements != null)
                            {
                                // Calculate the strides
                                var soStrides = new List<int>();
                                foreach (var streamOutputElement in soElements)
                                {
                                    for (int i = soStrides.Count; i < (streamOutputElement.Stream+1); i++)
                                    {
                                        soStrides.Add(0);
                                    }

                                    soStrides[streamOutputElement.Stream] += streamOutputElement.ComponentCount * sizeof(float);
                                }
                                shader = new GeometryShader(graphicsDevice, bytecodeRaw, soElements, soStrides.ToArray(), soRasterizedStream);
                            }
                            else
                            {
                                shader = new GeometryShader(graphicsDevice, bytecodeRaw);
                            }
                            break;
                        case EffectShaderType.Pixel:
                            shader = new PixelShader(graphicsDevice, bytecodeRaw);
                            break;
                        case EffectShaderType.Compute:
                            shader = new ComputeShader(graphicsDevice, bytecodeRaw);
                            break;
                    }
                    compiledShadersGroup[(int)shaderType][index] = ToDispose(shader);
                }
            }
            return shader;
        }
Exemplo n.º 12
0
        public ShaderSolution(string _name, Device Device, ByteCodeBind[] _shaders_bytecode)
        {
            shaders_bytecode = new Dictionary<Shaders, ShaderBytecode>();
            shaders_buffers = new Dictionary<Shaders, SharpDX.Direct3D11.Buffer[]>();
            //shaders_bound_values = new Dictionary<Shaders, NonNullable<SharpDX.DataStream>[]>();
            name = _name;
            for (int i = 0; i < _shaders_bytecode.Length; i++)
            {
                shaders_bytecode.Add(_shaders_bytecode[i].shaderType, _shaders_bytecode[i].byteCode);

                switch (_shaders_bytecode[i].shaderType)
                {
                    case Shaders.VertexShader:
                        vs = new VertexShader(Device, _shaders_bytecode[i].byteCode);
                        break;
                    case Shaders.HullShader:
                        hs = new HullShader(Device, _shaders_bytecode[i].byteCode);
                        break;
                    case Shaders.DomainShader:
                        ds = new DomainShader(Device, _shaders_bytecode[i].byteCode);
                        break;
                    case Shaders.GeometryShader:
                        gs = new GeometryShader(Device, _shaders_bytecode[i].byteCode);
                        break;
                    case Shaders.PixelShader:
                        ps = new PixelShader(Device, _shaders_bytecode[i].byteCode);
                        break;
                    default:
                        break;
                }
            }
        }
Exemplo n.º 13
0
 internal DeviceChild GetOrCompileShader(EffectShaderType shaderType, int index)
 {
     DeviceChild shader = null;
     lock (sync)
     {
         shader = compiledShaders[index];
         if (shader == null)
         {
             var bytecodeRaw = dataGroup.Shaders[index].Bytecode;
             switch (shaderType)
             {
                 case EffectShaderType.Vertex:
                     shader = new VertexShader(graphicsDevice, bytecodeRaw);
                     break;
                 case EffectShaderType.Domain:
                     shader = new DomainShader(graphicsDevice, bytecodeRaw);
                     break;
                 case EffectShaderType.Hull:
                     shader = new HullShader(graphicsDevice, bytecodeRaw);
                     break;
                 case EffectShaderType.Geometry:
                     shader = new GeometryShader(graphicsDevice, bytecodeRaw);
                     break;
                 case EffectShaderType.Pixel:
                     shader = new PixelShader(graphicsDevice, bytecodeRaw);
                     break;
                 case EffectShaderType.Compute:
                     shader = new ComputeShader(graphicsDevice, bytecodeRaw);
                     break;
             }
             compiledShaders[index] = shader;
         }
     }
     return shader;
 }
        protected override void CreateDeviceDependentResources(DeviceManager deviceManager)
        {
            base.CreateDeviceDependentResources(deviceManager);

            // Release all resources
            RemoveAndDispose(ref vertexShader);

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

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

            RemoveAndDispose(ref tessellatePhongDomainShader);

            RemoveAndDispose(ref debugNormals);

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

            RemoveAndDispose(ref depthStencilState);

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

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

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

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

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

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

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

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

            #region Tessellation Shaders

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

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

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

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

            #endregion

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            // No culling
            context.Rasterizer.State = ToDispose(new RasterizerState(device, new RasterizerStateDescription()
            {
                FillMode = FillMode.Solid,
                CullMode = CullMode.None
            }));
        }
Exemplo n.º 15
0
		/// <summary>
		/// 
		/// </summary>
		void SetupShadersAndLayouts ()
		{
			ps	=	PixelShader		== null ? null : new D3DPixelShader		( device.Device, PixelShader	.Bytecode );
			vs	=	VertexShader	== null ? null : new D3DVertexShader	( device.Device, VertexShader	.Bytecode );
			gs	=	GeometryShader	== null ? null : new D3DGeometryShader	( device.Device, GeometryShader	.Bytecode );
			hs	=	HullShader		== null ? null : new D3DHullShader		( device.Device, HullShader		.Bytecode );
			ds	=	DomainShader	== null ? null : new D3DDomainShader	( device.Device, DomainShader	.Bytecode );
			cs	=	ComputeShader	== null ? null : new D3DComputeShader	( device.Device, ComputeShader	.Bytecode );

			if (cs!=null) {
				if ( ps!=null || vs!=null || gs!=null || hs!=null || ds!=null ) {
					throw new InvalidOperationException("If ComputeShader is set, other shader must be set null.");
				}
			} else {
				if ( vs==null ) {
					throw new InvalidOperationException("Vertex shader must be set.");
				}
			}


			
			if (VertexInputElements==null) {
				inputLayout =	null ;
			} else {
				inputLayout	=	new InputLayout( device.Device, VertexShader.Bytecode, VertexInputElement.Convert( VertexInputElements ) );
			}



			if (VertexOutputElements!=null) {

				if (GeometryShader==null) {
					throw new InvalidOperationException("Geometry shader is required for vertex output.");
				}

				var outputElements	=	VertexOutputElement.Convert( VertexOutputElements );
				int maxBuffers		=	outputElements.Max( oe => oe.OutputSlot ) + 1;
				var bufferedStrides	=	new int[ maxBuffers ];

				for (int i=0; i<maxBuffers; i++) {
					bufferedStrides[i] = outputElements	
										.Where( oe1 => oe1.OutputSlot==i )
										.Sum( oe2 => oe2.ComponentCount	) * 4;
				}

				gs	=	new D3DGeometryShader( device.Device, GeometryShader.Bytecode, outputElements, bufferedStrides, RasterizedStream ); 
			}
		}
Exemplo n.º 16
0
 internal HullShader(GraphicsDevice device, string bytecode) : base(bytecode)
 {
     Shader = new D3D11.HullShader(device.Device, Misc.HexStringToByte(bytecode));
 }