/// <summary>
        /// Конструктор
        /// </summary>
        /// <param name="shadersFile">Путь к файлу с шейдерами PS и VS</param>
        /// <param name="inputElements">Какие входные данные ожидает шейдер</param>
        /// <param name="dvContext">Контекст видеокарты</param>
        /// <param name="texture">Путь к текстуре</param>
        public Drawer(string shadersFile,
                      InputElement[] inputElements,
                      DeviceContext dvContext,
                      bool isTesselation = false,
                      bool isGeometri    = false)
        {
            _dx11DeviceContext = dvContext;

            ShaderFlags shaderFlags = ShaderFlags.None;

#if DEBUG
            shaderFlags = ShaderFlags.Debug;
#endif

            using (var vertexShaderByteCode = ShaderBytecode.CompileFromFile(shadersFile, "VS", "vs_5_0", shaderFlags))
            {
                //Синатура храянящая сведения о том какие входные переменные есть у шейдера
                _inputSignature = ShaderSignature.GetInputSignature(vertexShaderByteCode);
                _vertexShader   = new VertexShader(_dx11DeviceContext.Device, vertexShaderByteCode);
            }
            using (var pixelShaderByteCode = ShaderBytecode.CompileFromFile(shadersFile, "PS", "ps_5_0", shaderFlags))
            {
                _pixelShader = new PixelShader(_dx11DeviceContext.Device, pixelShaderByteCode);
            }

            if (isTesselation)
            {
                using (var pixelShaderByteCode = ShaderBytecode.CompileFromFile(shadersFile, "HS", "hs_5_0", shaderFlags))
                {
                    _HShader = new HullShader(_dx11DeviceContext.Device, pixelShaderByteCode);
                }
                using (var pixelShaderByteCode = ShaderBytecode.CompileFromFile(shadersFile, "DS", "ds_5_0", shaderFlags))
                {
                    _DShader = new DomainShader(_dx11DeviceContext.Device, pixelShaderByteCode);
                }
            }

            if (isGeometri)
            {
                using (var pixelShaderByteCode = ShaderBytecode.CompileFromFile(shadersFile, "GS", "gs_5_0", shaderFlags))
                {
                    _GShader = new GeometryShader(_dx11DeviceContext.Device, pixelShaderByteCode);
                }
            }

            //Создаем шаблон ввода данных для шейдера
            _inputLayout = new InputLayout(_dx11DeviceContext.Device, _inputSignature, inputElements);
            var s = SamplerStateDescription.Default();
            s.AddressU          = TextureAddressMode.Wrap;
            s.AddressV          = TextureAddressMode.Wrap;
            s.AddressW          = TextureAddressMode.Wrap;
            s.MaximumAnisotropy = 16;
            s.MaximumLod        = float.MaxValue;
            s.MinimumLod        = 0;
            s.Filter            = Filter.MinMagMipLinear;
            Samplerdescription  = s;
            var d = DepthStencilStateDescription.Default();
            d.IsDepthEnabled         = true;
            d.IsStencilEnabled       = false;
            DepthStencilDescripshion = d;
            var r = RasterizerStateDescription.Default();
            r.CullMode            = CullMode.None;
            r.FillMode            = FillMode.Solid;
            RasterizerDescription = r;
            var b = BlendStateDescription.Default();
            b.AlphaToCoverageEnable = new RawBool(true);
            BlendDescription        = b;
        }
Esempio n. 2
0
        public WorldWaterShader(Device device)
        {
            var vertexShaderByteCode = ShaderBytecode.CompileFromFile(ShaderFileName, "WaterVertexShader", "vs_4_0", ShaderFlags);
            var pixelShaderByteCode  = ShaderBytecode.CompileFromFile(ShaderFileName, "WaterPixelShader", "ps_4_0", ShaderFlags);

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

            Layout = VertexDefinition.WaterVertex.GetInputLayout(device, vertexShaderByteCode);

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

            ConstantMatrixBuffer = new Buffer(device, MatrixBufferDesription);

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

            ConstantTranslationBuffer = new Buffer(device, translateBufferDesc);


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

            ConstantLightBuffer = new Buffer(device, lightBufferDesc);

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

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

            var samplerDescBorder = new SamplerStateDescription
            {
                Filter             = Filter.Anisotropic,
                AddressU           = TextureAddressMode.MirrorOnce,
                AddressV           = TextureAddressMode.Border,
                AddressW           = TextureAddressMode.Border,
                MipLodBias         = 0,
                MaximumAnisotropy  = 16,
                ComparisonFunction = Comparison.Always,
                BorderColor        = Color.Transparent,
                MinimumLod         = 0,
                MaximumLod         = float.MaxValue
            };

            // Create the texture sampler state.
            SamplerStateBorder = new SamplerState(device, samplerDescBorder);
        }
Esempio n. 3
0
        public ImGuiRender(DX11 dx11, RenderForm form, CoreSettings coreSettings)
        {
            _form        = form;
            Dx11         = dx11;
            CoreSettings = coreSettings;
            FormBounds   = form.Bounds;

            using (new PerformanceTimer("Init ImGui"))
            {
                Initialize();
            }

            sizeOfImDrawVert = Utilities.SizeOf <ImDrawVert>();
            sizeOfImDrawIdx  = Utilities.SizeOf <ushort>();
            VertexBufferSize = 10000;
            IndexBufferSize  = 30000;

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

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

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

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

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

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

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

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

            CreateStates();
            UpdateConstantBuffer();
            vertexShaderByteCode.Dispose();
            pixelShaderByteCode.Dispose();
        }
Esempio n. 4
0
        private static void Main()
        {
            var form = new RenderForm("SharpDX - MiniTri Direct3D 11 Sample");

            // SwapChain description
            var desc = new SwapChainDescription()
            {
                BufferCount     = 1,
                ModeDescription =
                    new ModeDescription(form.ClientSize.Width, form.ClientSize.Height,
                                        new Rational(60, 1), Format.R8G8B8A8_UNorm),
                IsWindowed        = true,
                OutputHandle      = form.Handle,
                SampleDescription = new SampleDescription(1, 0),
                SwapEffect        = SwapEffect.Discard,
                Usage             = Usage.RenderTargetOutput
            };

            // Create Device and SwapChain
            Device    device;
            SwapChain swapChain;

            Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.Debug, desc, out device, out swapChain);
            var context = device.ImmediateContext;

            // Ignore all windows events
            Factory factory = swapChain.GetParent <Factory>();

            factory.MakeWindowAssociation(form.Handle, WindowAssociationFlags.None);

            // New RenderTargetView from the backbuffer
            Texture2D backBuffer = Texture2D.FromSwapChain <Texture2D>(swapChain, 0);
            var       renderView = new RenderTargetView(device, backBuffer);

            // Compile Vertex and Pixel shaders
            var vertexShaderByteCode = ShaderBytecode.CompileFromFile("MiniTri.fx", "VS", "vs_4_0", ShaderFlags.None,
                                                                      EffectFlags.None);
            var vertexShader = new VertexShader(device, vertexShaderByteCode);

            var pixelShaderByteCode = ShaderBytecode.CompileFromFile("MiniTri.fx", "PS", "ps_4_0", ShaderFlags.None,
                                                                     EffectFlags.None);
            var pixelShader = new PixelShader(device, pixelShaderByteCode);

            // Layout from VertexShader input signature
            var layout = new InputLayout(device, ShaderSignature.GetInputSignature(vertexShaderByteCode), new[] {
                new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0),
                new InputElement("COLOR", 0, Format.R32G32B32A32_Float, 16, 0)
            });

            // Write vertex data to a datastream
            var stream = new DataStream(32 * 3, true, true);

            stream.WriteRange(new[]
            {
                new Vector4(0.0f, 0.5f, 0.5f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f),
                new Vector4(0.5f, -0.5f, 0.5f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f),
                new Vector4(-0.5f, -0.5f, 0.5f, 1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f)
            });
            stream.Position = 0;

            // Instantiate Vertex buiffer from vertex data
            var vertices = new Buffer(device, stream, new BufferDescription()
            {
                BindFlags           = BindFlags.VertexBuffer,
                CpuAccessFlags      = CpuAccessFlags.None,
                OptionFlags         = ResourceOptionFlags.None,
                SizeInBytes         = 32 * 3,
                Usage               = ResourceUsage.Default,
                StructureByteStride = 0
            });

            stream.Release();

            // Prepare All the stages
            context.InputAssembler.SetInputLayout(layout);
            context.InputAssembler.SetPrimitiveTopology(PrimitiveTopology.TriangleList);
            context.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(vertices, 32, 0));
            context.VertexShader.Set(vertexShader);
            context.Rasterizer.SetViewports(new Viewport(0, 0, form.ClientSize.Width, form.ClientSize.Height, 0.0f, 1.0f));
            context.PixelShader.Set(pixelShader);
            context.OutputMerger.SetTargets(renderView);

            // Main loop
            RenderLoop.Run(form, () =>
            {
                context.ClearRenderTargetView(renderView, new Color4(1.0f, 0.0f, 0.0f, 0.0f));
                context.Draw(3, 0);
                swapChain.Present(0, PresentFlags.None);
            });

            // Release all resources
            vertexShaderByteCode.Release();
            vertexShader.Release();
            pixelShaderByteCode.Release();
            pixelShader.Release();
            vertices.Release();
            layout.Release();
            renderView.Release();
            backBuffer.Release();
            context.ClearState();
            context.Flush();
            device.Release();
            context.Release();
            swapChain.Release();
            factory.Release();
        }
Esempio n. 5
0
        static void Main(string[] args)
        {
            const int elementCount      = 16;
            const int bufferSizeInBytes = elementCount * sizeof(float);

            D3D.Device device = new D3D.Device(D3D.DriverType.Hardware, D3D.DeviceCreationFlags.Debug);

            // The input to the computation will be a constant buffer containing
            // integers (in floating point representation) from 1 to numberOfElements,
            // inclusive. The compute shader itself will double these values and write
            // them to the output buffer.
            D3D.BufferDescription inputBufferDescription = new D3D.BufferDescription
            {
                BindFlags           = D3D.BindFlags.ConstantBuffer,
                CpuAccessFlags      = D3D.CpuAccessFlags.Write,
                OptionFlags         = D3D.ResourceOptionFlags.None,
                SizeInBytes         = bufferSizeInBytes,
                StructureByteStride = sizeof(float),
                Usage = D3D.ResourceUsage.Dynamic,
            };
            D3D.Buffer inputBuffer = new D3D.Buffer(device, inputBufferDescription);
            DataBox    input       = device.ImmediateContext.MapSubresource(inputBuffer, 0, bufferSizeInBytes, D3D.MapMode.WriteDiscard, D3D.MapFlags.None);

            for (int value = 1; value <= elementCount; ++value)
            {
                input.Data.Write((float)value);
            }
            device.ImmediateContext.UnmapSubresource(inputBuffer, 0);

            // A staging buffer is used to copy data between the CPU and GPU; the output
            // buffer (which gets the computation results) cannot be mapped directly.
            D3D.BufferDescription stagingBufferDescription = new D3D.BufferDescription
            {
                BindFlags           = D3D.BindFlags.None,
                CpuAccessFlags      = D3D.CpuAccessFlags.Read,
                OptionFlags         = D3D.ResourceOptionFlags.StructuredBuffer,
                SizeInBytes         = bufferSizeInBytes,
                StructureByteStride = sizeof(float),
                Usage = D3D.ResourceUsage.Staging,
            };
            D3D.Buffer stagingBuffer = new D3D.Buffer(device, stagingBufferDescription);

            // The output buffer itself, and the view required to bind it to the pipeline.
            D3D.BufferDescription outputBufferDescription = new D3D.BufferDescription
            {
                BindFlags           = D3D.BindFlags.UnorderedAccess | D3D.BindFlags.ShaderResource,
                OptionFlags         = D3D.ResourceOptionFlags.StructuredBuffer,
                SizeInBytes         = bufferSizeInBytes,
                StructureByteStride = sizeof(float),
                Usage = D3D.ResourceUsage.Default,
            };
            D3D.Buffer outputBuffer = new D3D.Buffer(device, outputBufferDescription);
            D3D.UnorderedAccessViewDescription outputViewDescription = new D3D.UnorderedAccessViewDescription
            {
                ElementCount = elementCount,
                Format       = DXGI.Format.Unknown,
                Dimension    = D3D.UnorderedAccessViewDimension.Buffer
            };
            D3D.UnorderedAccessView outputView = new D3D.UnorderedAccessView(device, outputBuffer, outputViewDescription);

            // Compile the shader.
            ShaderBytecode computeShaderCode = ShaderBytecode.CompileFromFile("BasicComputeShader.hlsl", "main", "cs_4_0", ShaderFlags.None, EffectFlags.None);

            D3D.ComputeShader computeShader = new D3D.ComputeShader(device, computeShaderCode);

            device.ImmediateContext.ComputeShader.Set(computeShader);
            device.ImmediateContext.ComputeShader.SetUnorderedAccessView(outputView, 0);
            device.ImmediateContext.ComputeShader.SetConstantBuffer(inputBuffer, 0);

            // Compute shaders execute on multiple threads at the same time. Those execution
            // threads are grouped; Dispatch() indicates how many groups in the X, Y and Z
            // dimension will be utilized. The shader itself specified how many threads per
            // group (also in X, Y and Z dimensions) to use via the [numthreads] attribute.
            // In this sample, one thread group will be used with 16 threads, each thread
            // will process one element of the input data.
            device.ImmediateContext.Dispatch(1, 1, 1);

            device.ImmediateContext.CopyResource(outputBuffer, stagingBuffer);
            DataBox output = device.ImmediateContext.MapSubresource(stagingBuffer, 0, sizeof(float) * elementCount, D3D.MapMode.Read, D3D.MapFlags.None);

            Console.Write("Results:");
            for (int index = 0; index < elementCount; ++index)
            {
                Console.Write(" {0}", output.Data.Read <float>());
            }
            device.ImmediateContext.UnmapSubresource(outputBuffer, 0);
            Console.WriteLine();

            computeShader.Dispose();
            outputView.Dispose();
            outputBuffer.Dispose();
            stagingBuffer.Dispose();
            inputBuffer.Dispose();
            device.Dispose();
        }
Esempio n. 6
0
        public void OnInitialize(System.Windows.Forms.Form form)
        {
            this.form  = form;
            clientSize = new Size(form.Width, form.Height);

            Device.CreateWithSwapChain(
                DriverType.Hardware,
                DeviceCreationFlags.Debug,
                new SlimDX.DXGI.SwapChainDescription
            {
                BufferCount       = 1,
                OutputHandle      = form.Handle,
                IsWindowed        = true,
                SampleDescription = new SlimDX.DXGI.SampleDescription
                {
                    Count   = 1,
                    Quality = 0
                },
                ModeDescription = new SlimDX.DXGI.ModeDescription
                {
                    Width       = form.Width,
                    Height      = form.Height,
                    RefreshRate = new SlimDX.Rational(60, 1),
                    Format      = SlimDX.DXGI.Format.R8G8B8A8_UNorm
                },
                Usage = SlimDX.DXGI.Usage.RenderTargetOutput
            },
                out device,
                out swapChain
                );

            using (Texture2D backBuffer =
                       SlimDX.Direct3D11.Resource.FromSwapChain <Texture2D>(swapChain, 0))
            {
                renderTarget = new RenderTargetView(device, backBuffer);
                device.ImmediateContext.OutputMerger.SetTargets(renderTarget);
            }

            device.ImmediateContext.Rasterizer.SetViewports(
                new Viewport
            {
                Width  = form.Width,
                Height = form.Height,
                MaxZ   = 1
            }
                );

            using (ShaderBytecode shaderBytecode = ShaderBytecode.CompileFromFile(
                       "simple.fx", "fx_5_0",
                       ShaderFlags.None,
                       EffectFlags.None))
            {
                effect = new Effect(device, shaderBytecode);
            }

            vertexLayout = new InputLayout(
                device,
                effect.GetTechniqueByIndex(0).GetPassByIndex(0).Description.Signature,
                VertexPointColor.VertexElements
                );

            // VertexBufer
            VertexPointColor[] vertices =
            {
                new VertexPointColor
                {
                    Position = new Vector3(0, 0.5f, 0),
                    Color    = new Vector3(0, 0, 1)
                },
                new VertexPointColor
                {
                    Position = new Vector3(0.5f, 0, 0),
                    Color    = new Vector3(0, 0, 1)
                },
                new VertexPointColor
                {
                    Position = new Vector3(-0.5f, 0, 0),
                    Color    = new Vector3(1, 0, 0)
                },
            };
            DataStream stream = new DataStream(vertices, true, true);

            vertexBuffer = new SlimDX.Direct3D11.Buffer(
                device,
                stream,
                new BufferDescription
            {
                SizeInBytes = (int)stream.Length,
                BindFlags   = BindFlags.VertexBuffer,
                OptionFlags = ResourceOptionFlags.DrawIndirect,
            }
                );
            stream.Dispose();

            // 定数バッファ
            Matrix[] mat = new Matrix[100];
            for (int i = 0; i < 100; i++)
            {
                mat[i] = Matrix.Translation(new Vector3((float)(0.2 * i), 0, (float)(0.2 * i)));
            }
            stream      = new DataStream(mat, true, true);
            inputBuffer = new SlimDX.Direct3D11.Buffer(
                device,
                stream,
                new BufferDescription
            {
                SizeInBytes = (int)stream.Length,
                BindFlags   = BindFlags.ShaderResource,
                OptionFlags = ResourceOptionFlags.DrawIndirect,
                //StructureByteStride = Marshal.SizeOf(typeof(Matrix)),
            }
                );

            // 深度バッファの設定
            Texture2DDescription depthBufferDesc = new Texture2DDescription
            {
                ArraySize         = 1,
                BindFlags         = BindFlags.DepthStencil,
                Format            = SlimDX.DXGI.Format.D32_Float,
                Width             = clientSize.Width,
                Height            = clientSize.Height,
                MipLevels         = 1,
                SampleDescription = new SlimDX.DXGI.SampleDescription(1, 0)
            };

            using (Texture2D depthBuffer = new Texture2D(device, depthBufferDesc))
            {
                depthStencil = new DepthStencilView(device, depthBuffer);
            }
            device.ImmediateContext.OutputMerger.SetTargets(depthStencil, renderTarget);

            EffectPass pass = effect.GetTechniqueByIndex(2).GetPassByIndex(0);

            foreach (IRenderObject itr in renderObjectArray)
            {
                itr.OnInitialize(device, pass);
            }

            // Textureの読み込み
            try
            {
                int testMode = 2;
                switch (testMode)
                {
                case 1:

                    Texture2D[] textureArray = new Texture2D[]
                    {
                        Texture2D.FromFile(device, "cobblestone_mossy.png"),
                        Texture2D.FromFile(device, "brick.png"),
                    };
                    stream = new DataStream(textureArray, true, true);

                    srv = new ShaderResourceView(device, textureArray[0]);

                    effect.GetVariableByName("g_DecalMap").AsResource().SetResource(srv);
                    break;

                case 2:

                    srv
                        = ShaderResourceView.FromFile(device, "cobblestone_mossy.png");
                    effect.GetVariableByName("g_DecalMap").AsResource().SetResource(srv);
                    //device.ImmediateContext.PixelShader.SetShaderResource(shaderResourceView, 19);

                    break;
                }

                SamplerDescription description = new SamplerDescription
                {
                    Filter   = SlimDX.Direct3D11.Filter.Anisotropic,
                    AddressU = SlimDX.Direct3D11.TextureAddressMode.Wrap,
                    AddressV = SlimDX.Direct3D11.TextureAddressMode.Wrap,
                    AddressW = TextureAddressMode.Wrap,
                };
                samplerState = SamplerState.FromDescription(device, description);
            }
            catch (Exception e)
            {
                return;
            }
            return;
        }
Esempio n. 7
0
        private bool InitializeShader(Device device, IntPtr windowsHandle, string vsFileName, string psFileName)
        {
            try
            {
                vsFileName = DSystemConfiguration.ShaderFilePath + vsFileName;
                psFileName = DSystemConfiguration.ShaderFilePath + psFileName;

                ShaderBytecode vertexShaderByteCode = ShaderBytecode.CompileFromFile(vsFileName, "ColorVertexShader", "vs_4_0", ShaderFlags.None, EffectFlags.None);
                ShaderBytecode pixelShaderByteCode  = ShaderBytecode.CompileFromFile(psFileName, "ColorPixelShader", "ps_4_0", ShaderFlags.None, EffectFlags.None);

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

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

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

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

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

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

                return(true);
            }
            catch (Exception)
            {
                throw new ShaderNotInitializedException();
            }
        }
Esempio n. 8
0
        public void Initialise()
        {
            sw = new Stopwatch();
            sw.Start();

            // Set the minimum and maximum values for the bounding box.
            minV = new Vector3(1000.0f, 1000.0f, 1000.0f);
            maxV = new Vector3(-1000.0f, -1000.0f, -1000.0f);

            // Get the terrain size.
            int te_width  = te.getTerrainSize();
            int te_length = te.getTerrainSize();

            // Initialise the vertex array.
            vl = new List <Vertex>();
            vt = new Vertex[te_width * te_length];

            for (int i = 0; i < te_width; i++)
            {
                for (int j = 0; j < te_length; j++)
                {
                    vt[te_width * i + j] = new Vertex()
                    {
                        Position = new Vector4(te.heightmap[i, j].position.X,
                                               te.heightmap[i, j].position.Y,
                                               te.heightmap[i, j].position.Z,
                                               1.0f),
                        Normal = new Vector4(te.heightmap[i, j].normal.X,
                                             te.heightmap[i, j].normal.Y,
                                             te.heightmap[i, j].normal.Z,
                                             1.0f),
                        TexUV = new Vector2(0.5f, 0.5f),
                        Color = new Vector4(0.13f, 0.5f, 0.2f, 1.0f)
                    };

                    // Perform a check for the min and max values.
                    // Update the bounds accordingly.
                    minV.X = getMin(vt[te_width * i + j].Position.X, minV.X);
                    minV.Y = getMin(vt[te_width * i + j].Position.Y, minV.Y);
                    minV.Z = getMin(vt[te_width * i + j].Position.Z, minV.Z);

                    maxV.X = getMax(vt[te_width * i + j].Position.X, maxV.X);
                    maxV.Y = getMax(vt[te_width * i + j].Position.Y, maxV.Y);
                    maxV.Z = getMax(vt[te_width * i + j].Position.Z, maxV.Z);
                }
            }

            for (int i = 0; i < te_width - 1; i++)
            {
                for (int j = 0; j < te_length - 1; j++)
                {
                    // Triangle 1
                    int index = i * te_width + j;
                    vl.Add(new Vertex()
                    {
                        Position = new Vector4(vt[index].Position.X,
                                               vt[index].Position.Y,
                                               vt[index].Position.Z,
                                               vt[index].Position.W),
                        Normal = new Vector4(vt[index].Normal.X,
                                             vt[index].Normal.Y,
                                             vt[index].Normal.Z,
                                             vt[index].Normal.W),
                        TexUV = new Vector2(0.0f, 0.0f),
                        Color = new Vector4(0.3f, 0.7f, 0.5f, 1.0f)
                    });

                    index = (i) * te_width + (j + 1);
                    vl.Add(new Vertex()
                    {
                        Position = new Vector4(vt[index].Position.X,
                                               vt[index].Position.Y,
                                               vt[index].Position.Z,
                                               vt[index].Position.W),
                        Normal = new Vector4(vt[index].Normal.X,
                                             vt[index].Normal.Y,
                                             vt[index].Normal.Z,
                                             vt[index].Normal.W),
                        TexUV = new Vector2(0.0f, 1.0f),
                        Color = new Vector4(0.3f, 0.7f, 0.5f, 1.0f)
                    });

                    index = (i + 1) * te_width + (j + 1);
                    vl.Add(new Vertex()
                    {
                        Position = new Vector4(vt[index].Position.X,
                                               vt[index].Position.Y,
                                               vt[index].Position.Z,
                                               vt[index].Position.W),
                        Normal = new Vector4(vt[index].Normal.X,
                                             vt[index].Normal.Y,
                                             vt[index].Normal.Z,
                                             vt[index].Normal.W),
                        TexUV = new Vector2(1.0f, 1.0f),
                        Color = new Vector4(0.3f, 0.7f, 0.5f, 1.0f)
                    });

                    // Triangle 2
                    index = (i + 1) * te_width + (j + 1);
                    vl.Add(new Vertex()
                    {
                        Position = new Vector4(vt[index].Position.X,
                                               vt[index].Position.Y,
                                               vt[index].Position.Z,
                                               vt[index].Position.W),
                        Normal = new Vector4(vt[index].Normal.X,
                                             vt[index].Normal.Y,
                                             vt[index].Normal.Z,
                                             vt[index].Normal.W),
                        TexUV = new Vector2(1.0f, 1.0f),
                        Color = new Vector4(0.3f, 0.7f, 0.5f, 1.0f)
                    });

                    index = (i + 1) * te_width + (j);
                    vl.Add(new Vertex()
                    {
                        Position = new Vector4(vt[index].Position.X,
                                               vt[index].Position.Y,
                                               vt[index].Position.Z,
                                               vt[index].Position.W),
                        Normal = new Vector4(vt[index].Normal.X,
                                             vt[index].Normal.Y,
                                             vt[index].Normal.Z,
                                             vt[index].Normal.W),
                        TexUV = new Vector2(1.0f, 0.0f),
                        Color = new Vector4(0.3f, 0.7f, 0.5f, 1.0f)
                    });

                    index = i * te_width + (j);
                    vl.Add(new Vertex()
                    {
                        Position = new Vector4(vt[index].Position.X,
                                               vt[index].Position.Y,
                                               vt[index].Position.Z,
                                               vt[index].Position.W),
                        Normal = new Vector4(vt[index].Normal.X,
                                             vt[index].Normal.Y,
                                             vt[index].Normal.Z,
                                             vt[index].Normal.W),
                        TexUV = new Vector2(0.0f, 0.0f),
                        Color = new Vector4(0.3f, 0.7f, 0.5f, 1.0f)
                    });
                }
            }

            var vt2 = vl.ToArray();

            vertices = Buffer.Create(dev, BindFlags.VertexBuffer, vt2);
            //vertices = new Buffer(dev, Utilities.SizeOf<Vertex>() * vl.Count,
            //    ResourceUsage.Dynamic, BindFlags.VertexBuffer,
            //    CpuAccessFlags.Write, ResourceOptionFlags.None, 0);
            //dev.ImmediateContext.UpdateSubresource(vt2, vertices);


            bbc = new BBCorners(minV, maxV);
            var bb8corners = bbc.getBB8Corners();

            bb   = bbc.getBoundingBox();
            bBox = Buffer.Create(dev, BindFlags.VertexBuffer, bb8corners);

            // Vertex and Pixel shaders.
            vsByteCode = ShaderBytecode.CompileFromFile("TerrainShader.hlsl", "VSMain", "vs_5_0", ShaderFlags.None, EffectFlags.None);
            vShader    = new VertexShader(dev, vsByteCode);

            psByteCode = ShaderBytecode.CompileFromFile("TerrainShader.hlsl", "PSMain", "ps_5_0", ShaderFlags.None, EffectFlags.None);
            pShader    = new PixelShader(dev, psByteCode);

            vsByteCode2 = ShaderBytecode.CompileFromFile("BBoxShader.hlsl", "VSMain", "vs_5_0", ShaderFlags.None, EffectFlags.None);
            vShader2    = new VertexShader(dev, vsByteCode2);

            psByteCode2 = ShaderBytecode.CompileFromFile("BBoxShader.hlsl", "PSMain", "ps_5_0", ShaderFlags.None, EffectFlags.None);
            pShader2    = new PixelShader(dev, psByteCode2);

            signature  = ShaderSignature.GetInputSignature(vsByteCode);
            signature2 = ShaderSignature.GetInputSignature(vsByteCode2);

            // Input layout.
            layout = new InputLayout(dev, signature, new[]
            {
                new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0),
                new InputElement("NORMAL", 0, Format.R32G32B32A32_Float, InputElement.AppendAligned, 0),
                new InputElement("TEXCOORD", 0, Format.R32G32_Float, InputElement.AppendAligned, 0),
                new InputElement("COLOR", 0, Format.R32G32B32A32_Float, InputElement.AppendAligned, 0)
            });

            layout2 = new InputLayout(dev, signature2, new[]
            {
                new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0)
            });

            // Constant buffer
            cBuffer = new Buffer(dev, Utilities.SizeOf <cBufferStruct>(), ResourceUsage.Default, BindFlags.ConstantBuffer,
                                 CpuAccessFlags.None, ResourceOptionFlags.None, 0);

            // Texture
            ImageLoader imgLoader = new ImageLoader();
            var         texture   = imgLoader.loadImage("grasstex.png", ref dev);

            textureView = new ShaderResourceView(dev, texture);

            colorSampler = new SamplerState(dev, new SamplerStateDescription()
            {
                Filter             = Filter.MinMagMipLinear,
                AddressU           = TextureAddressMode.Clamp,
                AddressV           = TextureAddressMode.Clamp,
                AddressW           = TextureAddressMode.Clamp,
                BorderColor        = Color.Black,
                ComparisonFunction = Comparison.Never,
                MaximumAnisotropy  = 16,
                MipLodBias         = 0,
                MinimumLod         = -float.MaxValue,
                MaximumLod         = float.MaxValue
            });


            // Set up matrices
            Vector3 eye = new Vector3(-20, 5, -20);
            Vector3 at  = new Vector3(0, 0, 0);
            Vector3 up  = Vector3.UnitY;

            view = Matrix.LookAtLH(eye, at, up);

            proj = Matrix.Identity;

            // Set up projection matrix with correct aspect ratio.
            proj = Matrix.PerspectiveFovLH((float)MathUtil.Pi / 4.0f,
                                           ((float)formWidth / (float)formHeight),
                                           0.1f, 1000.0f);
        }
Esempio n. 9
0
        public static void DrawMesh(Direct3DControl control)
        {
            var desc = new SwapChainDescription()
            {
                BufferCount     = 1,
                ModeDescription =
                    new ModeDescription(control.ClientSize.Width, control.ClientSize.Height,
                                        new Rational(60, 1), Format.R8G8B8A8_UNorm),
                IsWindowed        = true,
                OutputHandle      = control.Handle,
                SampleDescription = new SampleDescription(1, 0),
                SwapEffect        = SwapEffect.Discard,
                Usage             = Usage.RenderTargetOutput
            };
            Device    device;
            SwapChain swapChain;

            Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.None, desc, out device, out swapChain);
            var context = device.ImmediateContext;

            var vertices = Buffer.Create(device, BindFlags.VertexBuffer, new[]
            {
                new Vector4(-1.0f, -1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f),                       // Front
                new Vector4(-1.0f, 1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f),
                new Vector4(1.0f, 1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f),
                new Vector4(-1.0f, -1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f),
                new Vector4(1.0f, 1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f),
                new Vector4(1.0f, -1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f),

                new Vector4(-1.0f, -1.0f, 1.0f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f),                        // BACK
                new Vector4(1.0f, 1.0f, 1.0f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f),
                new Vector4(-1.0f, 1.0f, 1.0f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f),
                new Vector4(-1.0f, -1.0f, 1.0f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f),
                new Vector4(1.0f, -1.0f, 1.0f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f),
                new Vector4(1.0f, 1.0f, 1.0f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f),

                new Vector4(-1.0f, 1.0f, -1.0f, 1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f),                        // Top
                new Vector4(-1.0f, 1.0f, 1.0f, 1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f),
                new Vector4(1.0f, 1.0f, 1.0f, 1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f),
                new Vector4(-1.0f, 1.0f, -1.0f, 1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f),
                new Vector4(1.0f, 1.0f, 1.0f, 1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f),
                new Vector4(1.0f, 1.0f, -1.0f, 1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f),

                new Vector4(-1.0f, -1.0f, -1.0f, 1.0f), new Vector4(1.0f, 1.0f, 0.0f, 1.0f),                       // Bottom
                new Vector4(1.0f, -1.0f, 1.0f, 1.0f), new Vector4(1.0f, 1.0f, 0.0f, 1.0f),
                new Vector4(-1.0f, -1.0f, 1.0f, 1.0f), new Vector4(1.0f, 1.0f, 0.0f, 1.0f),
                new Vector4(-1.0f, -1.0f, -1.0f, 1.0f), new Vector4(1.0f, 1.0f, 0.0f, 1.0f),
                new Vector4(1.0f, -1.0f, -1.0f, 1.0f), new Vector4(1.0f, 1.0f, 0.0f, 1.0f),
                new Vector4(1.0f, -1.0f, 1.0f, 1.0f), new Vector4(1.0f, 1.0f, 0.0f, 1.0f),

                new Vector4(-1.0f, -1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 1.0f, 1.0f),                       // Left
                new Vector4(-1.0f, -1.0f, 1.0f, 1.0f), new Vector4(1.0f, 0.0f, 1.0f, 1.0f),
                new Vector4(-1.0f, 1.0f, 1.0f, 1.0f), new Vector4(1.0f, 0.0f, 1.0f, 1.0f),
                new Vector4(-1.0f, -1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 1.0f, 1.0f),
                new Vector4(-1.0f, 1.0f, 1.0f, 1.0f), new Vector4(1.0f, 0.0f, 1.0f, 1.0f),
                new Vector4(-1.0f, 1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 1.0f, 1.0f),

                new Vector4(1.0f, -1.0f, -1.0f, 1.0f), new Vector4(0.0f, 1.0f, 1.0f, 1.0f),                        // Right
                new Vector4(1.0f, 1.0f, 1.0f, 1.0f), new Vector4(0.0f, 1.0f, 1.0f, 1.0f),
                new Vector4(1.0f, -1.0f, 1.0f, 1.0f), new Vector4(0.0f, 1.0f, 1.0f, 1.0f),
                new Vector4(1.0f, -1.0f, -1.0f, 1.0f), new Vector4(0.0f, 1.0f, 1.0f, 1.0f),
                new Vector4(1.0f, 1.0f, -1.0f, 1.0f), new Vector4(0.0f, 1.0f, 1.0f, 1.0f),
                new Vector4(1.0f, 1.0f, 1.0f, 1.0f), new Vector4(0.0f, 1.0f, 1.0f, 1.0f),
            });

            var vertexShaderByteCode = ShaderBytecode.CompileFromFile("MiniCube.fx", "VS", "vs_4_0");
            var vertexShader         = new VertexShader(device, vertexShaderByteCode);

            var pixelShaderByteCode = ShaderBytecode.CompileFromFile("MiniCube.fx", "PS", "ps_4_0");
            var pixelShader         = new PixelShader(device, pixelShaderByteCode);

            var signature = ShaderSignature.GetInputSignature(vertexShaderByteCode);
            // Layout from VertexShader input signature
            var layout = new InputLayout(device, signature, new[]
            {
                new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0),
                new InputElement("COLOR", 0, Format.R32G32B32A32_Float, 16, 0)
            });

            var contantBuffer = new Buffer(device, Utilities.SizeOf <Matrix>(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0);

            context.InputAssembler.InputLayout       = layout;
            context.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleStrip;
            context.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(vertices, Utilities.SizeOf <Vector4>() * 2, 0));
            context.VertexShader.SetConstantBuffer(0, contantBuffer);
            context.VertexShader.Set(vertexShader);
            context.PixelShader.Set(pixelShader);

            //var view = Matrix.LookAtLH(new Vector3(0, 0, -5), new Vector3(0, 0, 0), Vector3.UnitY);
            //Matrix proj = Matrix.Identity;
            swapChain.ResizeBuffers(1, control.ClientSize.Width, control.ClientSize.Height, Format.Unknown, SwapChainFlags.None);

            // Get the backbuffer from the swapchain
            var backBuffer = Texture2D.FromSwapChain <Texture2D>(swapChain, 0);

            // Renderview on the backbuffer
            var renderView = new RenderTargetView(device, backBuffer);

            // Create the depth buffer
            var depthBuffer = new Texture2D(device, new Texture2DDescription()
            {
                Format            = Format.D32_Float_S8X24_UInt,
                ArraySize         = 1,
                MipLevels         = 1,
                Width             = control.ClientSize.Width,
                Height            = control.ClientSize.Height,
                SampleDescription = new SampleDescription(1, 0),
                Usage             = ResourceUsage.Default,
                BindFlags         = BindFlags.DepthStencil,
                CpuAccessFlags    = CpuAccessFlags.None,
                OptionFlags       = ResourceOptionFlags.None
            });

            // Create the depth buffer view
            var depthView = new DepthStencilView(device, depthBuffer);

            context.Rasterizer.SetViewport(new Viewport(0, 0, control.ClientSize.Width, control.ClientSize.Height, 0.0f, 1.0f));
            context.OutputMerger.SetTargets(depthView, renderView);
            //proj = Matrix.PerspectiveFovLH((float)Math.PI / 4.0f, 1, 0.1f, 100.0f);
            context.OutputMerger.SetTargets(depthView, renderView);
            //var viewProj = Matrix.Multiply(view, proj);
            context.ClearDepthStencilView(depthView, DepthStencilClearFlags.Depth, 1.0f, 0);
            context.ClearRenderTargetView(renderView, Color.White);
            //var worldViewProj = Matrix.RotationX(10) * Matrix.RotationY(10 * 2) * Matrix.RotationZ(10 * .7f) * viewProj;
            //worldViewProj.Transpose();
            //context.UpdateSubresource(ref worldViewProj, contantBuffer);
            context.Draw(36, 0);

            // Present!
            swapChain.Present(0, PresentFlags.None);
        }
Esempio n. 10
0
        public override void Initialize()
        {
            try
            {
                using (ShaderBytecode geometryShaderByteCode = ShaderBytecode.CompileFromFile(
                           "Shaders/Sprite.fx",
                           "mainGS",
                           "gs_4_0",
                           ShaderFlags.None,
                           EffectFlags.None,
                           null,
                           new IncludeFX("Shaders")))
                {
                    geometryShader = new GeometryShader(DeviceManager.Instance.device, geometryShaderByteCode);
                }

                using (ShaderBytecode vertexShaderByteCode = ShaderBytecode.CompileFromFile(
                           "Shaders/Sprite.fx",
                           "mainVS",
                           "vs_4_0",
                           ShaderFlags.None,
                           EffectFlags.None,
                           null,
                           new IncludeFX("Shaders")))
                {
                    vertexShader   = new VertexShader(DeviceManager.Instance.device, vertexShaderByteCode);
                    inputSignature = ShaderSignature.GetInputSignature(vertexShaderByteCode);
                }

                using (ShaderBytecode pixelShaderByteCode = ShaderBytecode.CompileFromFile(
                           "Shaders/Sprite.fx",
                           "mainPS",
                           "ps_4_0",
                           ShaderFlags.None,
                           EffectFlags.None,
                           null,
                           new IncludeFX("Shaders")))
                {
                    pixelShader = new PixelShader(DeviceManager.Instance.device, pixelShaderByteCode);
                }

                layout = new InputLayout(DeviceManager.Instance.device, inputSignature, elements);

                #region Blend States

                RenderTargetBlendDescription rtBlendDefault = new RenderTargetBlendDescription()
                {
                    BlendEnable           = true,
                    BlendOperation        = BlendOperation.Add,
                    RenderTargetWriteMask = ColorWriteMaskFlags.All,
                    SourceBlend           = BlendOption.SourceAlpha,
                    DestinationBlend      = BlendOption.InverseSourceAlpha,
                    BlendOperationAlpha   = BlendOperation.Add,
                    SourceBlendAlpha      = BlendOption.SourceAlpha,
                    DestinationBlendAlpha = BlendOption.InverseSourceAlpha,
                };

                BlendStateDescription bBlendStateDefault = new BlendStateDescription();
                bBlendStateDefault.AlphaToCoverageEnable  = false;
                bBlendStateDefault.IndependentBlendEnable = false;
                bBlendStateDefault.RenderTargets[0]       = rtBlendDefault;

                blendStateDepth = BlendState.FromDescription(DeviceManager.Instance.device, bBlendStateDefault);

                #endregion

                #region Depth Stencils

                DepthStencilStateDescription dsStateNoDepth = new DepthStencilStateDescription()
                {
                    IsDepthEnabled = false,
                    DepthWriteMask = DepthWriteMask.Zero
                };

                depthStencilStateNoDepth = DepthStencilState.FromDescription(DeviceManager.Instance.device, dsStateNoDepth);

                #endregion
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }
Esempio n. 11
0
        public static SharpDXInfo Initialize(IntPtr handle, System.Drawing.Size size, IEnumerable <VertexPositionColorTexture> rawVertices, IEnumerable <int> rawIndices, Matrix viewWorldProj, string texturePath)
        {
            var desc = new SwapChainDescription()
            {
                BufferCount       = 1,
                ModeDescription   = new ModeDescription(size.Width, size.Height, new Rational(60, 1), Format.R8G8B8A8_UNorm),
                IsWindowed        = true,
                OutputHandle      = handle,
                SampleDescription = new SampleDescription(1, 0),
                SwapEffect        = SwapEffect.Discard,
                Usage             = Usage.RenderTargetOutput
            };

            // Create Device and SwapChain
            Device    device;
            SwapChain swapChain;

            Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.Debug, desc, out device, out swapChain);
            var context = device.ImmediateContext;

            // Ignore all windows events
            var factory = swapChain.GetParent <Factory>();

            factory.MakeWindowAssociation(handle, WindowAssociationFlags.IgnoreAll);

            // New RenderTargetView from the backbuffer
            var backBuffer = Texture2D.FromSwapChain <Texture2D>(swapChain, 0);
            var renderView = new RenderTargetView(device, backBuffer);

            // Compile Vertex and Pixel shaders
            using (var vertexShaderByteCode = ShaderBytecode.CompileFromFile(DefaultShaderPath, "VS", "vs_4_0"))
                using (var pixelShaderByteCode = ShaderBytecode.CompileFromFile(DefaultShaderPath, "PS", "ps_4_0"))
                {
                    var vertexShader = new VertexShader(device, vertexShaderByteCode);
                    var pixelShader  = new PixelShader(device, pixelShaderByteCode);

                    // Layout from VertexShader input signature
                    var layout = new InputLayout(device, ShaderSignature.GetInputSignature(vertexShaderByteCode), new[]
                    {
                        new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0),
                        new InputElement("COLOR", 0, Format.R32G32B32A32_Float, 16, 0),
                        new InputElement("TEXCOORD", 0, Format.R32G32_Float, 32, 0),
                    });

                    // Instantiate buffers
                    var vertexBuffer = CreateBuffer <VertexPositionColorTexture>(device, BindFlags.VertexBuffer, rawVertices.Count());
                    var indexBuffer  = CreateBuffer <int>(device, BindFlags.IndexBuffer, rawIndices.Count());
                    var cameraBuffer = CreateConstantBuffer <Matrix>(device);

                    var depthBuffer = new Texture2D(device, new Texture2DDescription()
                    {
                        Format            = Format.D32_Float_S8X24_UInt,
                        ArraySize         = 1,
                        MipLevels         = 1,
                        Width             = size.Width,
                        Height            = size.Height,
                        SampleDescription = new SampleDescription(1, 0),
                        Usage             = ResourceUsage.Default,
                        BindFlags         = BindFlags.DepthStencil,
                        CpuAccessFlags    = CpuAccessFlags.None,
                        OptionFlags       = ResourceOptionFlags.None
                    });

                    var depthView = new DepthStencilView(device, depthBuffer);

                    // Load texture and create sampler
                    var texture     = Texture2D.FromFile <Texture2D>(device, texturePath);
                    var textureView = new ShaderResourceView(device, texture);

                    var sampler = new SamplerState(device, new SamplerStateDescription()
                    {
                        Filter             = Filter.MinMagMipLinear,
                        AddressU           = TextureAddressMode.Wrap,
                        AddressV           = TextureAddressMode.Wrap,
                        AddressW           = TextureAddressMode.Wrap,
                        BorderColor        = Color.Black,
                        ComparisonFunction = Comparison.Never,
                        MaximumAnisotropy  = 16,
                        MipLodBias         = 0,
                        MinimumLod         = 0,
                        MaximumLod         = 16,
                    });

                    // initialize sharpdxlib context
                    var info = new SharpDXInfo(
                        device, swapChain, handle, size,
                        depthView, renderView,
                        vertexBuffer, indexBuffer, cameraBuffer, depthBuffer,
                        rawVertices, rawIndices,
                        texture, textureView,
                        vertexShader, pixelShader, layout,
                        backBuffer, factory);

                    // Prepare All the stages
                    context.InputAssembler.InputLayout       = layout;
                    context.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList;
                    context.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(vertexBuffer, Utilities.SizeOf <VertexPositionColorTexture>(), 0));
                    context.InputAssembler.SetIndexBuffer(indexBuffer, Format.R32_UInt, 0);
                    context.VertexShader.SetConstantBuffer(0, cameraBuffer);
                    context.VertexShader.Set(vertexShader); RasterizerStateDescription rasdesc = new RasterizerStateDescription()
                    {
                        CullMode = CullMode.None,
                        FillMode = FillMode.Solid,
                        IsFrontCounterClockwise = true,
                        DepthBias            = 0,
                        DepthBiasClamp       = 0,
                        SlopeScaledDepthBias = 0,
                        IsDepthClipEnabled   = true,
                        IsMultisampleEnabled = true,
                    };
                    context.Rasterizer.State = new RasterizerState(device, rasdesc);
                    context.Rasterizer.SetViewport(new Viewport(0, 0, size.Width, size.Height, 0.0f, 1));
                    context.PixelShader.Set(pixelShader);
                    context.PixelShader.SetSampler(0, sampler);
                    context.PixelShader.SetShaderResource(0, textureView);
                    context.OutputMerger.SetTargets(depthView, renderView);

                    UpdateVertexBuffer(info, rawVertices);
                    UpdateIndexBuffer(info, rawIndices);
                    UpdateCameraBuffer(info, viewWorldProj);

                    return(info);
                }
        }