Example #1
0
        public void Setup(ID3D11Device device, ID3D11DeviceContext context)
        {
            if (!m_vertexAttributes.Any())
            {
                return;
            }

            if (!m_inputLayout)
            {
                var hr = device.CreateVertexShader(m_vs_blob.GetBufferPointer(), m_vs_blob.GetBufferSize(), null, out m_vs);
                hr.ThrowIfFailed();
                hr = device.CreatePixelShader(m_ps_blob.GetBufferPointer(), m_ps_blob.GetBufferSize(), null, out m_ps);
                hr.ThrowIfFailed();

                hr = device.CreateInputLayout(ref m_layout[0], (uint)m_layout.Length,
                                              m_vs_blob.GetBufferPointer(), m_vs_blob.GetBufferSize(), out m_inputLayout);
                hr.ThrowIfFailed();
            }

            // setup shader pipeline
            Span <IntPtr> classes = stackalloc IntPtr[] { };

            context.VSSetShader(m_vs, ref MemoryMarshal.GetReference(classes), (uint)classes.Length);
            context.PSSetShader(m_ps, ref MemoryMarshal.GetReference(classes), (uint)classes.Length);
            context.IASetInputLayout(m_inputLayout);
        }
Example #2
0
        public static IComObject <ID3D11InputLayout> CreateInputLayout(this ID3D11Device device, D3D11_INPUT_ELEMENT_DESC[] inputElements, ID3D10Blob blob)
        {
            if (device == null)
            {
                throw new ArgumentNullException(nameof(device));
            }

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

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

            if (inputElements.Length == 0)
            {
                throw new ArgumentException(null, nameof(inputElements));
            }

            device.CreateInputLayout(inputElements, inputElements.Length, blob.GetBufferPointer(), blob.GetBufferSize(), out var layout).ThrowOnError();
            return(new ComObject <ID3D11InputLayout>(layout));
        }
        public static IComObject <ID3D11InputLayout> CreateInputLayout(this ID3D11Device device, D3D11_INPUT_ELEMENT_DESC[] inputElements, IntPtr shaderBytecodeWithInputSignature, IntPtr bytecodeLength)
        {
            if (device == null)
            {
                throw new ArgumentNullException(nameof(device));
            }

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

            if (inputElements.Length == 0)
            {
                throw new ArgumentException(null, nameof(inputElements));
            }

            foreach (var element in inputElements)
            {
                if (element.SemanticName == null)
                {
                    throw new ArgumentException(null, nameof(inputElements));
                }
            }

            device.CreateInputLayout(inputElements, inputElements.Length, shaderBytecodeWithInputSignature, bytecodeLength, out var layout).ThrowOnError();
            return(new ComObject <ID3D11InputLayout>(layout));
        }
Example #4
0
        public virtual bool Init(ID3D11Device device, ShaderInitParams InitParams)
        {
            // Attempt to construct pixel shader
            if (InitParams.PixelShaderFile.IsValid())
            {
                Blob PixelBytecode = ConstructBytecode(InitParams.PixelShaderFile);
                OurPixelShader = device.CreatePixelShader(PixelBytecode);
                PixelBytecode.Dispose();
            }

            // Attempt to construct vertex shader
            if (InitParams.VertexShaderFile.IsValid())
            {
                Blob VertexBytecode = ConstructBytecode(InitParams.VertexShaderFile);
                OurVertexShader = device.CreateVertexShader(VertexBytecode);
                Layout          = device.CreateInputLayout(InitParams.Elements, VertexBytecode);
                VertexBytecode.Dispose();
            }

            // Attempt to construct geometry shader
            if (InitParams.GeometryShaderFile.IsValid())
            {
                Blob GeometryBytecode = ConstructBytecode(InitParams.GeometryShaderFile);
                OurGeometryShader = device.CreateGeometryShader(GeometryBytecode);
                GeometryBytecode.Dispose();
            }

            SamplerDescription samplerDesc = new SamplerDescription()
            {
                Filter             = Filter.Anisotropic,
                AddressU           = TextureAddressMode.Wrap,
                AddressV           = TextureAddressMode.Wrap,
                AddressW           = TextureAddressMode.Wrap,
                MipLODBias         = 0,
                MaxAnisotropy      = 8,
                ComparisonFunction = ComparisonFunction.Always,
                BorderColor        = new Color4(0, 0, 0, 0),
                MinLOD             = 0,
                MaxLOD             = 0
            };

            SamplerState = device.CreateSamplerState(samplerDesc);

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

            return(true);
        }
Example #5
0
        static void Main()
        {
            ReferenceTracker.TrackReferences = true;
            Form form = new Form();

            IDXGIFactory factory = DXGI.CreateFactory();
            IDXGIAdapter adapter = null;

            factory.EnumAdapters(0, out adapter);

            DXGI_SWAP_CHAIN_DESC swapChainDescription = new DXGI_SWAP_CHAIN_DESC
            {
                BufferCount = 1,
                BufferDesc  = new DXGI_MODE_DESC
                {
                    Format      = DXGI_FORMAT.DXGI_FORMAT_R8G8B8A8_UNORM,
                    Height      = form.ClientSize.Height,
                    RefreshRate = new DXGI_RATIONAL
                    {
                        Denominator = 1,
                        Numerator   = 60
                    },

                    Scaling          = DXGI_MODE_SCALING.DXGI_MODE_SCALING_UNSPECIFIED,
                    ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER.DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED,
                    Width            = form.ClientSize.Width
                },
                BufferUsage  = (int)DXGI_USAGE.DXGI_USAGE_RENDER_TARGET_OUTPUT,
                Flags        = 0,
                OutputWindow = form.Handle,
                SampleDesc   = new DXGI_SAMPLE_DESC
                {
                    Count   = 1,
                    Quality = 0
                },
                SwapEffect = DXGI_SWAP_EFFECT.DXGI_SWAP_EFFECT_DISCARD,
                Windowed   = true
            };

            ID3D11Device   device    = SlimDX.Direct3D11.Direct3D11.CreateDevice(adapter);
            IDXGISwapChain swapChain = null;

            factory.CreateSwapChain(device, swapChainDescription, out swapChain);

            ID3D11Texture2D        backbuffer = swapChain.GetBuffer <ID3D11Texture2D>(0);
            ID3D11RenderTargetView view       = null;

            device.CreateRenderTargetView(backbuffer, null, out view);

            ID3DBlob vertexShaderBytecode = ShaderCompiler.CompileFromString(File.ReadAllText("MiniTri11.fx"), "MiniTri11.fx", "VS", "vs_4_0");
            ID3DBlob pixelShaderBytecode  = ShaderCompiler.CompileFromString(File.ReadAllText("MiniTri11.fx"), "MiniTri11.fx", "PS", "ps_4_0");

            D3D11_INPUT_ELEMENT_DESC[] inputElements = new[] {
                new D3D11_INPUT_ELEMENT_DESC {
                    SemanticName = "POSITION", AlignedByteOffset = 0, SemanticIndex = 0, Format = DXGI_FORMAT.DXGI_FORMAT_R32G32B32A32_FLOAT, InstanceDataStepRate = 0, InputSlot = 0, InputSlotClass = D3D11_INPUT_CLASSIFICATION.D3D11_INPUT_PER_VERTEX_DATA
                },
                new D3D11_INPUT_ELEMENT_DESC {
                    SemanticName = "COLOR", AlignedByteOffset = 16, SemanticIndex = 0, Format = DXGI_FORMAT.DXGI_FORMAT_R32G32B32A32_FLOAT, InstanceDataStepRate = 0, InputSlot = 0, InputSlotClass = D3D11_INPUT_CLASSIFICATION.D3D11_INPUT_PER_VERTEX_DATA
                }
            };

            ID3DBlob inputSignature;

            ShaderCompiler.D3DGetInputSignatureBlob(vertexShaderBytecode.GetBufferPointer(), vertexShaderBytecode.GetBufferSize(), out inputSignature);
            ID3D11InputLayout inputLayout;

            device.CreateInputLayout(inputElements, inputElements.Length, inputSignature.GetBufferPointer(), inputSignature.GetBufferSize(), out inputLayout);

            ByteBuffer vertexData = new ByteBuffer(3 * 32);

            vertexData.Write(0 * Vector4.SizeInBytes, new Vector4(0.0f, 0.5f, 0.5f, 1.0f));
            vertexData.Write(1 * Vector4.SizeInBytes, new Vector4(1.0f, 0.0f, 0.0f, 1.0f));
            vertexData.Write(2 * Vector4.SizeInBytes, new Vector4(0.5f, -0.5f, 0.5f, 1.0f));
            vertexData.Write(3 * Vector4.SizeInBytes, new Vector4(0.0f, 1.0f, 0.0f, 1.0f));
            vertexData.Write(4 * Vector4.SizeInBytes, new Vector4(-0.5f, -0.5f, 0.5f, 1.0f));
            vertexData.Write(5 * Vector4.SizeInBytes, new Vector4(0.0f, 0.0f, 1.0f, 1.0f));

            D3D11_BUFFER_DESC vertexBufferDescription = new D3D11_BUFFER_DESC
            {
                BindFlags           = 1,      //vertex buffer
                ByteWidth           = 3 * 32,
                CPUAccessFlags      = 0,
                MiscFlags           = 0,
                Usage               = D3D11_USAGE.D3D11_USAGE_DEFAULT,
                StructureByteStride = 0
            };
            ID3D11Buffer           vertexBuffer;
            D3D11_SUBRESOURCE_DATA srd = new D3D11_SUBRESOURCE_DATA
            {
                pSysMem          = vertexData.Pin(),
                SysMemPitch      = 0,
                SysMemSlicePitch = 0
            };

            device.CreateBuffer(vertexBufferDescription, srd, out vertexBuffer);
            vertexData.Unpin();

            RenderLoop          loop    = new RenderLoop();
            ID3D11DeviceContext context = null;

            device.GetImmediateContext(out context);

            ID3D11VertexShader vertexShader;
            ID3D11PixelShader  pixelShader;

            device.CreateVertexShader(vertexShaderBytecode.GetBufferPointer(), vertexShaderBytecode.GetBufferSize(), null, out vertexShader);
            device.CreatePixelShader(pixelShaderBytecode.GetBufferPointer(), pixelShaderBytecode.GetBufferSize(), null, out pixelShader);
            context.IASetInputLayout(inputLayout);
            context.VSSetShader(vertexShader, null, 0);
            context.PSSetShader(pixelShader, null, 0);
            context.IASetPrimitiveTopology(4);            //triangle list
            context.IASetVertexBuffers(0, 1, new ID3D11Buffer[] { vertexBuffer }, new int[] { 32 }, new int[] { 0 });
            context.OMSetRenderTargets(1, new ID3D11RenderTargetView[] { view }, IntPtr.Zero);

            D3D11_VIEWPORT vp = new D3D11_VIEWPORT {
                Height   = form.ClientSize.Height,
                Width    = form.ClientSize.Width,
                TopLeftX = 0,
                TopLeftY = 0,
                MinDepth = 0.0f,
                MaxDepth = 1.0f
            };

            context.RSSetViewports(1, new D3D11_VIEWPORT [] { vp });

            loop.Run(form, () =>
            {
                var clearColor = new SlimDX.Color4 {
                    R = 0.0f, G = 0.0f, B = 0.0f, A = 1.0f
                };
                context.ClearRenderTargetView(view, clearColor);
                context.Draw(3, 0);
                swapChain.Present(0, 0);
            });

            view.ReleaseReference();
            backbuffer.ReleaseReference();
            swapChain.ReleaseReference();
            device.ReleaseReference();
            adapter.ReleaseReference();
            factory.ReleaseReference();
        }
Example #6
0
        void CreateDeviceObjects()
        {
            var vertexShaderCode =
                @"
                    cbuffer vertexBuffer : register(b0) 
                    {
                        float4x4 ProjectionMatrix; 
                    };

                    struct VS_INPUT
                    {
                        float2 pos : POSITION;
                        float4 col : COLOR0;
                        float2 uv  : TEXCOORD0;
                    };
            
                    struct PS_INPUT
                    {
                        float4 pos : SV_POSITION;
                        float4 col : COLOR0;
                        float2 uv  : TEXCOORD0;
                    };
            
                    PS_INPUT main(VS_INPUT input)
                    {
                        PS_INPUT output;
                        output.pos = mul(ProjectionMatrix, float4(input.pos.xy, 0.f, 1.f));
                        output.col = input.col;
                        output.uv  = input.uv;
                        return output;
                    }";

            Compiler.Compile(vertexShaderCode, "main", "vs", "vs_4_0", out vertexShaderBlob, out var errorBlob);
            if (vertexShaderBlob == null)
            {
                throw new Exception("error compiling vertex shader");
            }

            vertexShader = device.CreateVertexShader(vertexShaderBlob.GetBytes());

            var inputElements = new[]
            {
                new InputElementDescription("POSITION", 0, Format.R32G32_Float, 0, 0, InputClassification.PerVertexData, 0),
                new InputElementDescription("TEXCOORD", 0, Format.R32G32_Float, 8, 0, InputClassification.PerVertexData, 0),
                new InputElementDescription("COLOR", 0, Format.R8G8B8A8_UNorm, 16, 0, InputClassification.PerVertexData, 0),
            };

            inputLayout = device.CreateInputLayout(inputElements, vertexShaderBlob);

            var constBufferDesc = new BufferDescription
            {
                SizeInBytes    = VertexConstantBufferSize,
                Usage          = Vortice.Direct3D11.Usage.Dynamic,
                BindFlags      = BindFlags.ConstantBuffer,
                CpuAccessFlags = CpuAccessFlags.Write
            };

            constantBuffer = device.CreateBuffer(constBufferDesc);

            var pixelShaderCode =
                @"struct PS_INPUT
                    {
                        float4 pos : SV_POSITION;
                        float4 col : COLOR0;
                        float2 uv  : TEXCOORD0;
                    };

                    sampler sampler0;
                    Texture2D texture0;
            
                    float4 main(PS_INPUT input) : SV_Target
                    {
                        float4 out_col = input.col * texture0.Sample(sampler0, input.uv); 
                        return out_col; 
                    }";

            Compiler.Compile(pixelShaderCode, "main", "ps", "ps_4_0", out pixelShaderBlob, out errorBlob);
            if (pixelShaderBlob == null)
            {
                throw new Exception("error compiling pixel shader");
            }

            pixelShader = device.CreatePixelShader(pixelShaderBlob.GetBytes());

            var blendDesc = new BlendDescription
            {
                AlphaToCoverageEnable = false
            };

            blendDesc.RenderTarget[0] = new RenderTargetBlendDescription
            {
                IsBlendEnabled        = true,
                SourceBlend           = Blend.SourceAlpha,
                DestinationBlend      = Blend.InverseSourceAlpha,
                BlendOperation        = BlendOperation.Add,
                SourceBlendAlpha      = Blend.InverseSourceAlpha,
                DestinationBlendAlpha = Blend.Zero,
                BlendOperationAlpha   = BlendOperation.Add,
                RenderTargetWriteMask = ColorWriteEnable.All
            };

            blendState = device.CreateBlendState(blendDesc);

            var rasterDesc = new RasterizerDescription
            {
                FillMode        = FillMode.Solid,
                CullMode        = CullMode.None,
                ScissorEnable   = true,
                DepthClipEnable = true
            };

            rasterizerState = device.CreateRasterizerState(rasterDesc);

            var stencilOpDesc = new DepthStencilOperationDescription(StencilOperation.Keep, StencilOperation.Keep, StencilOperation.Keep, ComparisonFunction.Always);
            var depthDesc     = new DepthStencilDescription
            {
                DepthEnable    = false,
                DepthWriteMask = DepthWriteMask.All,
                DepthFunc      = ComparisonFunction.Always,
                StencilEnable  = false,
                FrontFace      = stencilOpDesc,
                BackFace       = stencilOpDesc
            };

            depthStencilState = device.CreateDepthStencilState(depthDesc);

            CreateFontsTexture();
        }