/// <summary>
        /// Create any device dependent resources here.
        /// This method will be called when the device is first
        /// initialized or recreated after being removed or reset.
        /// </summary>
        protected override void CreateDeviceDependentResources()
        {
            // Ensure that if already set the device resources
            // are correctly disposed of before recreating
            RemoveAndDispose(ref quadVertices);
            RemoveAndDispose(ref quadIndices);

            // Retrieve our SharpDX.Direct3D11.Device1 instance
            var device = this.DeviceManager.Direct3DDevice;

            // Create a quad (two triangles)
            quadVertices = ToDispose(Buffer.Create(device, BindFlags.VertexBuffer, new[] {
            /*  Vertex Position                       Vertex Color */
                new Vector4(0.25f, 0.5f, -0.5f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f), // Top-left
                new Vector4(0.75f, 0.5f, -0.5f, 1.0f), new Vector4(1.0f, 1.0f, 0.0f, 1.0f), // Top-right
                new Vector4(0.75f, 0.0f, -0.5f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f), // Base-right
                new Vector4(0.25f, 0.0f, -0.5f, 1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f), // Base-left
            }));
            quadBinding = new VertexBufferBinding(quadVertices, Utilities.SizeOf<Vector4>() * 2, 0);

            // v0    v1
            // |-----|
            // | \ A |
            // | B \ |
            // |-----|
            // v3    v2
            quadIndices = ToDispose(Buffer.Create(device, BindFlags.IndexBuffer, new ushort[] {
                0, 1, 2, // A
                2, 3, 0  // B
            }));
        }
        protected override void CreateDeviceDependentResources()
        {
            RemoveAndDispose(ref vertexBuffer);
            RemoveAndDispose(ref indexBuffer);

            // Retrieve our SharpDX.Direct3D11.Device1 instance
            var device = this.DeviceManager.Direct3DDevice;

            // Load texture (a DDS cube map)
            textureView = ShaderResourceView.FromFile(device, "CubeMap.dds");

            // Create our sampler state
            samplerState = new SamplerState(device, new SamplerStateDescription()
            {
                AddressU = TextureAddressMode.Clamp,
                AddressV = TextureAddressMode.Clamp,
                AddressW = TextureAddressMode.Clamp,
                BorderColor = new Color4(0, 0, 0, 0),
                ComparisonFunction = Comparison.Never,
                Filter = Filter.MinMagMipLinear,
                MaximumLod = 9, // Our cube map has 10 mip map levels (0-9)
                MinimumLod = 0,
                MipLodBias = 0.0f
            });

            Vertex[] vertices;
            int[] indices;
            GeometricPrimitives.GenerateSphere(out vertices, out indices, Color.Gray);

            vertexBuffer = ToDispose(Buffer.Create(device, BindFlags.VertexBuffer, vertices));
            vertexBinding = new VertexBufferBinding(vertexBuffer, Utilities.SizeOf<Vertex>(), 0);

            indexBuffer = ToDispose(Buffer.Create(device, BindFlags.IndexBuffer, indices));
            totalVertexCount = indices.Length;
        }
        public FilterPixelShader(Device device, int imageWidth, int imageHeight, int constantBufferSize, string pixelShaderBytecodeFilename)
        {
            vertexShader = new VertexShader(device, new ShaderBytecode(File.ReadAllBytes("Content/FullScreenQuadVS.cso")));
            pixelShader = new PixelShader(device, new ShaderBytecode(File.ReadAllBytes(pixelShaderBytecodeFilename)));

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

            if (constantBufferSize > 0)
            {
                var constantBufferDesc = new BufferDescription()
                {
                    Usage = ResourceUsage.Dynamic,
                    BindFlags = BindFlags.ConstantBuffer,
                    SizeInBytes = constantBufferSize,
                    CpuAccessFlags = CpuAccessFlags.Write,
                    StructureByteStride = 0,
                    OptionFlags = 0,
                };
                constantBuffer = new Buffer(device, constantBufferDesc);
            }

            viewport = new Viewport(0, 0, imageWidth, imageHeight); // TODO: get these dimensions
            vertexBufferBinding = new VertexBufferBinding(null, 0, 0);
        }
        public static void Draw(RenderContext11 renderContext, PositionColoredTextured[] points, int count, Matrix mat, bool triangleStrip)
        {
            if (VertexBuffer == null)
            {
                VertexBuffer = new Buffer(renderContext.Device, System.Runtime.InteropServices.Marshal.SizeOf(points[0]) * 2500, ResourceUsage.Dynamic, BindFlags.VertexBuffer, CpuAccessFlags.Write, ResourceOptionFlags.None, System.Runtime.InteropServices.Marshal.SizeOf(points[0]));
                VertexBufferBinding = new VertexBufferBinding(VertexBuffer, System.Runtime.InteropServices.Marshal.SizeOf((points[0])), 0);

            }

            renderContext.devContext.InputAssembler.PrimitiveTopology = triangleStrip ? SharpDX.Direct3D.PrimitiveTopology.TriangleStrip : SharpDX.Direct3D.PrimitiveTopology.TriangleList;
            renderContext.BlendMode = BlendMode.Alpha;
            renderContext.setRasterizerState(TriangleCullMode.Off);

            mat.Transpose();

            WarpOutputShader.MatWVP = mat;
            WarpOutputShader.Use(renderContext.devContext, false);

            renderContext.SetVertexBuffer(VertexBufferBinding);

            DataBox box = renderContext.devContext.MapSubresource(VertexBuffer, 0, MapMode.WriteDiscard, MapFlags.None);
            Utilities.Write(box.DataPointer, points, 0, count);

            renderContext.devContext.UnmapSubresource(VertexBuffer, 0);

            renderContext.devContext.PixelShader.SetShaderResource(0, null);

            renderContext.devContext.Draw(count, 0);
        }
        public static void Draw(RenderContext11 renderContext, PositionColoredTextured[] points, int count, Texture11 texture, SharpDX.Direct3D.PrimitiveTopology primitiveType, float opacity = 1.0f)
        {
            if (VertexBuffer == null)
            {
                VertexBuffer = new Buffer(renderContext.Device, System.Runtime.InteropServices.Marshal.SizeOf(points[0]) * 2500, ResourceUsage.Dynamic, BindFlags.VertexBuffer, CpuAccessFlags.Write, ResourceOptionFlags.None, System.Runtime.InteropServices.Marshal.SizeOf(points[0]));
                VertexBufferBinding = new VertexBufferBinding(VertexBuffer, System.Runtime.InteropServices.Marshal.SizeOf((points[0])), 0);

            }
            renderContext.devContext.InputAssembler.PrimitiveTopology = primitiveType;
            renderContext.BlendMode = BlendMode.Alpha;
            renderContext.setRasterizerState(TriangleCullMode.Off);
            SharpDX.Matrix mat = (renderContext.World * renderContext.View * renderContext.Projection).Matrix11;
            mat.Transpose();

            WarpOutputShader.MatWVP = mat;
            WarpOutputShader.Use(renderContext.devContext, texture != null, opacity);

            renderContext.SetVertexBuffer(VertexBufferBinding);

            DataBox box = renderContext.devContext.MapSubresource(VertexBuffer, 0, MapMode.WriteDiscard, MapFlags.None);
            Utilities.Write(box.DataPointer, points, 0, count);

            renderContext.devContext.UnmapSubresource(VertexBuffer, 0);
            if (texture != null)
            {
                renderContext.devContext.PixelShader.SetShaderResource(0, texture.ResourceView);
            }
            else
            {
                renderContext.devContext.PixelShader.SetShaderResource(0, null);
            }
            renderContext.devContext.Draw(count, 0);
        }
        public MeshContainer(Engine.Serialize.Mesh M)
        {
            if (M != null)
            {
                LocalAABBMax = M.AABBMax;
                LocalAABBMin = M.AABBMin;

                VertexsCount = M.VertexCount;
                FaceCount = M.FaceCount;
                BytesPerVertex = M.VertexData.Length / VertexsCount;

                using (var vertices = new DataStream(BytesPerVertex * VertexsCount, true, true))
                {
                    vertices.WriteRange<byte>(M.VertexData, 0, M.VertexData.Length);
                    vertices.Position = 0;
                    Vertexs = new Buffer(ModelViewer.Program.device, vertices, BytesPerVertex * VertexsCount, ResourceUsage.Default, BindFlags.VertexBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0);
                    binding = new VertexBufferBinding(Vertexs, BytesPerVertex, 0);
                }

                using (var indices = new DataStream(4 * FaceCount * 3, true, true))
                {
                    indices.WriteRange<byte>(M.IndexData, 0, M.IndexData.Length);
                    indices.Position = 0;
                    Indices = new Buffer(ModelViewer.Program.device, indices, 4 * FaceCount * 3, ResourceUsage.Default, BindFlags.IndexBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0);
                }
            }
        }
        public PhysicsDebugDraw(DeviceManager manager)
        {
            device = manager.Direct3DDevice;
            inputAssembler = device.ImmediateContext.InputAssembler;
            lineArray = new PositionColored[0];

            using (var bc = HLSLCompiler.CompileFromFile(@"Shaders\PhysicsDebug.hlsl", "VSMain", "vs_5_0"))
            {
                vertexShader = new VertexShader(device, bc);

                InputElement[] elements = new InputElement[]
                {
                    new InputElement("SV_POSITION", 0, Format.R32G32B32_Float, 0, 0, InputClassification.PerVertexData, 0),
                    new InputElement("COLOR", 0, Format.R8G8B8A8_UNorm, 12, 0, InputClassification.PerVertexData, 0)
                };
                inputLayout = new InputLayout(device, bc, elements);
            }

            vertexBufferDesc = new BufferDescription()
            {
                Usage = ResourceUsage.Dynamic,
                BindFlags = BindFlags.VertexBuffer,
                CpuAccessFlags = CpuAccessFlags.Write
            };

            vertexBufferBinding = new VertexBufferBinding(null, PositionColored.Stride, 0);

            using (var bc = HLSLCompiler.CompileFromFile(@"Shaders\PhysicsDebug.hlsl", "PSMain", "ps_5_0"))
                pixelShader = new PixelShader(device, bc);
        }
Beispiel #8
0
 public Shape(VertexBufferBinding vertexBinding, PrimitiveTopology topology, ShaderResourceView textureView, Style style, int vertexCount)
 {
     this.vertexBinding = vertexBinding;
     this.topology = topology;
     this.textureView = textureView;
     this.style = style;
     this.vertexCount = vertexCount;
 }
 /// <summary>
 /// <p>Bind a single vertex buffer to the input-assembler stage.</p>	
 /// </summary>	
 /// <param name="slot"><dd>  <p>The first input slot for binding. The first vertex buffer is explicitly bound to the start slot; this causes each additional vertex buffer in the array to be implicitly bound to each subsequent input slot. The maximum of 16 or 32 input slots (ranges from 0 to <see cref="SharpDX.Direct3D11.InputAssemblerStage.VertexInputResourceSlotCount"/> - 1) are available; the maximum number of input slots depends on the feature level.</p> </dd></param>	
 /// <param name="vertexBufferBinding"><dd>  <p>A <see cref="SharpDX.Direct3D11.VertexBufferBinding"/>. The vertex buffer must have been created with the <strong><see cref="SharpDX.Direct3D11.BindFlags.VertexBuffer"/></strong> flag.</p> </dd></param>        /// <remarks>	
 /// <p>For information about creating vertex buffers, see Create a Vertex Buffer.</p><p>Calling this method using a buffer that is currently bound for writing (i.e. bound to the stream output pipeline stage) will effectively bind <strong><c>null</c></strong> instead because a buffer cannot be bound as both an input and an output at the same time.</p><p>The debug layer will generate a warning whenever a resource is prevented from being bound simultaneously as an input and an output, but this will not prevent invalid data from being used by the runtime.</p><p> The method will hold a reference to the interfaces passed in. This differs from the device state behavior in Direct3D 10. </p>	
 /// </remarks>	
 /// <msdn-id>ff476456</msdn-id>	
 /// <unmanaged>void ID3D11DeviceContext::IASetVertexBuffers([In] unsigned int StartSlot,[In] unsigned int NumBuffers,[In, Buffer] const void* ppVertexBuffers,[In, Buffer] const void* pStrides,[In, Buffer] const void* pOffsets)</unmanaged>	
 /// <unmanaged-short>ID3D11DeviceContext::IASetVertexBuffers</unmanaged-short>	
 public void SetVertexBuffers(int slot, VertexBufferBinding vertexBufferBinding)
 {
     unsafe
     {
         int stride = vertexBufferBinding.Stride;
         int offset = vertexBufferBinding.Offset;
         IntPtr pVertexBuffers = vertexBufferBinding.Buffer == null ? IntPtr.Zero : vertexBufferBinding.Buffer.NativePointer;
         SetVertexBuffers(slot, 1, new IntPtr(&pVertexBuffers), new IntPtr(&stride), new IntPtr(&offset));
     }
 }
        public MultiMeshContainer(Engine.Serialize.MeshesContainer MC)
        {
            if (MC != null)
            {
                //Transform = Matrix.Scaling(1);

                Hardpoints = MC.HardPoints;
                if (MC.Materials != null && MC.Geometry != null && MC.Geometry.Meshes != null)
                {
                    BSP = MC.Geometry.BSP;
                    LocalAABBMax = MC.Geometry.AABBMax;
                    LocalAABBMin = MC.Geometry.AABBMin;

                    Meshes = new Serialize.MeshLink[MC.Materials.Length];
                    Materials = new MaterialContainer[MC.Materials.Length];
                    for (int i = 0; i < MC.Materials.Length; i++)
                    {
                        Meshes[i] = MC.Geometry.Meshes[i];
                        Materials[i] = new MaterialContainer(MC.Materials[i]);
                    }

                    VertexsCount = MC.Geometry.VertexCount;
                    BytesPerVertex = MC.Geometry.VertexData.Length / VertexsCount;
                    FaceCount = MC.Geometry.IndexData.Length / 12;

                    using (var vertices = new DataStream(BytesPerVertex * VertexsCount, true, true))
                    {
                        vertices.WriteRange<byte>(MC.Geometry.VertexData, 0, MC.Geometry.VertexData.Length);
                        vertices.Position = 0;
                        Vertexs = new Buffer(ModelViewer.Program.device, vertices, BytesPerVertex * VertexsCount, ResourceUsage.Default, BindFlags.VertexBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0);
                        binding = new VertexBufferBinding(Vertexs, BytesPerVertex, 0);
                    }

                    using (var indices = new DataStream(4 * FaceCount * 3, true, true))
                    {
                        indices.WriteRange<byte>(MC.Geometry.IndexData, 0, MC.Geometry.IndexData.Length);
                        indices.Position = 0;
                        Indices = new Buffer(ModelViewer.Program.device, indices, 4 * FaceCount * 3, ResourceUsage.Default, BindFlags.IndexBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0);
                    }

                    BufferDescription bd = new BufferDescription();
                    bd.SizeInBytes = Marshal.SizeOf(typeof(ShaderConstants));
                    bd.Usage = ResourceUsage.Dynamic;
                    bd.BindFlags = BindFlags.ConstantBuffer;
                    bd.CpuAccessFlags = CpuAccessFlags.Write;
                    bd.OptionFlags = ResourceOptionFlags.None;
                    bd.StructureByteStride = 0;

                    constantsBuffer = new Buffer(ModelViewer.Program.device, bd);
                    constants = new ShaderConstants();
                }
            }
        }
        public PrimitiveMesh(Device device, Mesh baseMesh)
        {
            BaseMesh = baseMesh;

            var vert3d = new Vertex3D[baseMesh.Vertices.Length];
            for (var i = 0; i < vert3d.Length; ++i)
                vert3d[i] = new Vertex3D(baseMesh.Vertices[i]);

            IndexBuffer = Buffer.Create<ushort>(device, BindFlags.IndexBuffer, baseMesh.Indices);
            VertexBuffer = Buffer.Create<Vertex3D>(device, BindFlags.VertexBuffer, vert3d);
            VertexBufferBinding = new VertexBufferBinding(VertexBuffer, VertexBuffer.Description.SizeInBytes / baseMesh.Vertices.Length, 0);
        }
 public Shape CreateShape(float[] floatArray, PrimitiveTopology topology, String textureName, Style style)
 {
     var vertices = program.ToDispose(Buffer.Create(program.pipeline.device, BindFlags.VertexBuffer, floatArray));
     var vertexBufferBinding = new VertexBufferBinding(vertices, Utilities.SizeOf<float>() * style.floatsPerVertex, 0);
     return new Shape
     {
         vertexBinding = vertexBufferBinding,
         topology = topology,
         textureView = GetTexture(textureName),
         style = style,
         vertexCount = floatArray.Length / style.floatsPerVertex,
     };
 }
        /// <summary>
        /// Renders one frame using the vertex and pixel shaders.
        /// On devices that do not support the D3D11_FEATURE_D3D11_OPTIONS3::
        /// VPAndRTArrayIndexFromAnyShaderFeedingRasterizer optional feature,
        /// a pass-through geometry shader is also used to set the render
        /// target array index.
        /// </summary>
        public void Render()
        {
            // Loading is asynchronous. Resources must be created before drawing can occur.
            if (!this.loadingComplete)
            {
                return;
            }

            var context = this.deviceResources.D3DDeviceContext;

            // Each vertex is one instance of the VertexPositionColor struct.
            int stride        = SharpDX.Utilities.SizeOf <TexturedVertex>();
            int offset        = 0;
            var bufferBinding = new SharpDX.Direct3D11.VertexBufferBinding(this.vertexBuffer, stride, offset);

            context.InputAssembler.SetVertexBuffers(0, bufferBinding);
            context.InputAssembler.SetIndexBuffer(
                this.indexBuffer,
                SharpDX.DXGI.Format.R16_UInt, // Each index is one 16-bit unsigned integer (short).
                0);
            context.InputAssembler.PrimitiveTopology = SharpDX.Direct3D.PrimitiveTopology.TriangleList;
            context.InputAssembler.InputLayout       = this.inputLayout;

            // Attach the vertex shader.
            context.VertexShader.SetShader(this.vertexShader, null, 0);
            // Apply the model constant buffer to the vertex shader.
            context.VertexShader.SetConstantBuffers(0, this.modelConstantBuffer);

            if (!this.usingVprtShaders)
            {
                // On devices that do not support the D3D11_FEATURE_D3D11_OPTIONS3::
                // VPAndRTArrayIndexFromAnyShaderFeedingRasterizer optional feature,
                // a pass-through geometry shader is used to set the render target
                // array index.
                context.GeometryShader.SetShader(this.geometryShader, null, 0);
            }

            // Attach the pixel shader.
            context.PixelShader.SetShader(this.pixelShader, null, 0);
            context.PixelShader.SetShaderResource(0, _textureView);

            // Draw the objects.
            context.DrawIndexedInstanced(
                indexCount,     // Index count per instance.
                2,              // Instance count.
                0,              // Start index location.
                0,              // Base vertex location.
                0               // Start instance location.
                );
        }
        protected override void CreateDeviceDependentResources()
        {
            base.CreateDeviceDependentResources();

            RemoveAndDispose(ref vertexBuffer);

            // Retrieve our SharpDX.Direct3D11.Device1 instance
            var device = this.DeviceManager.Direct3DDevice;

            // Patch layout
            // * U ------------>
            // V cp0--cp1--cp2--cp3
            //    |    |    |    |
            // | cp4--cp5--cp6--cp7
            // |  |    |    |    |
            // | cp8--cp9--cp10-cp11
            // V  |    |    |    |
            //   cp12-cp13-cp14-cp15
            //
            // (cp = control point)

            // Create the bezier surface
            // Note: the normals are discarded and instead calculated from the bezier surface during tessellation
            vertexBuffer = ToDispose(Buffer.Create(device, BindFlags.VertexBuffer, new[] {
                //          x, y, z        u, v texture coord
                new Vertex(-1, 0, 1,       0, 0),
                new Vertex(-0.34f, 0, 1,   1, 0),
                new Vertex(0.34f, 0.5f, 1, 2, 0),
                new Vertex(1, 2, 1,        3, 0),

                new Vertex(-1, 0, 0.34f,       0, 1),
                new Vertex(-0.34f, 0, 0.34f,   1, 1),
                new Vertex(0.34f, 0.1f, 0.34f, 2, 1),
                new Vertex(1, 0.5f, 0.34f,     3, 1),

                new Vertex(-1, 0, -0.34f,     0, 2),
                new Vertex(-0.34f, 0, -0.34f, 1, 2),
                new Vertex(0.34f, 0, -0.34f,  2, 2),
                new Vertex(1, 0, -0.34f,      3, 2),

                new Vertex(-1, 0, -1,     0, 3),
                new Vertex(-0.34f, 0, -1, 1, 3),
                new Vertex(0.34f, 0, -1,  2, 3),
                new Vertex(1, 0, -1,      3, 3),
            }));
            vertexBinding = new VertexBufferBinding(vertexBuffer, Utilities.SizeOf<Vertex>(), 0);
        }
        protected override void CreateDeviceDependentResources()
        {
            RemoveAndDispose(ref vertexBuffer);
            RemoveAndDispose(ref indexBuffer);

            // Retrieve our SharpDX.Direct3D11.Device1 instance
            var device = this.DeviceManager.Direct3DDevice;

            // Create vertex buffer for cube
            vertexBuffer = ToDispose(Buffer.Create(device, BindFlags.VertexBuffer, new Vertex[] {
                    /*  Vertex Position    Color */
            new Vertex(-0.5f, 0.5f, -0.5f, Color.Red),  // 0-Top-left
            new Vertex(0.5f, 0.5f, -0.5f,  Color.Green),  // 1-Top-right
            new Vertex(0.5f, -0.5f, -0.5f,  Color.Blue), // 2-Base-right
            new Vertex(-0.5f, -0.5f, -0.5f, Color.Cyan), // 3-Base-left

            new Vertex(-0.5f, 0.5f, 0.5f,  Color.Yellow),  // 4-Top-left
            new Vertex(0.5f, 0.5f, 0.5f,   Color.Red),  // 5-Top-right
            new Vertex(0.5f, -0.5f, 0.5f,  Color.Green),  // 6-Base-right
            new Vertex(-0.5f, -0.5f, 0.5f, Color.Blue),  // 7-Base-left
            }));
            vertexBinding = new VertexBufferBinding(vertexBuffer, Utilities.SizeOf<Vertex>(), 0);

            // Front    Right    Top      Back     Left     Bottom
            // v0    v1 v1    v5 v1    v0 v5    v4 v4    v0 v3    v2
            // |-----|  |-----|  |-----|  |-----|  |-----|  |-----|
            // | \ A |  | \ A |  | \ A |  | \ A |  | \ A |  | \ A |
            // | B \ |  | B \ |  | B \ |  | B \ |  | B \ |  | B \ |
            // |-----|  |-----|  |-----|  |-----|  |-----|  |-----|
            // v3    v2 v2    v6 v5    v4 v6    v7 v7    v3 v7    v6
            indexBuffer = ToDispose(Buffer.Create(device, BindFlags.IndexBuffer, new ushort[] {
                // using Right-handed coordinates, therefore counter-clockwise
                0, 2, 1, // Front A
                0, 3, 2, // Front B
                1, 6, 5, // Right A
                1, 2, 6, // Right B
                1, 4, 0, // Top A
                1, 5, 4, // Top B
                5, 7, 4, // Back A
                5, 6, 7, // Back B
                4, 3, 0, // Left A
                4, 7, 3, // Left B
                3, 6, 2, // Bottom A
                3, 7, 6, // Bottom B
            }));
        }
Beispiel #16
0
        public void Draw()
        {
            var dc = Device.ImmediateContext;

            pass.Apply();

            var matViewProj = Camera.ActiveCamera.ViewMatrix * Camera.ActiveCamera.ProjectionMatrix;
            dc.UpdateSubresource(ref matViewProj, matrixBuffer);
            dc.VertexShader.SetConstantBuffer(0, matrixBuffer);

            dc.InputAssembler.PrimitiveTopology = SharpDX.Direct3D.PrimitiveTopology.LineList;
            var bd = new VertexBufferBinding(vertexBuffer, Utilities.SizeOf<LineVertex>(), 0);
            dc.InputAssembler.SetVertexBuffers(0, bd);

            dc.Draw(vertexCount, 0);

            pass.Clear();
        }
        protected override void CreateDeviceDependentResources()
        {
            RemoveAndDispose(ref vertexBuffer);
            RemoveAndDispose(ref indexBuffer);

            // Retrieve our SharpDX.Direct3D11.Device1 instance
            var device = this.DeviceManager.Direct3DDevice;

            Vertex[] vertices;
            int[] indices;
            GeometricPrimitives.GenerateSphere(out vertices, out indices, Color.Gray);

            vertexBuffer = ToDispose(Buffer.Create(device, BindFlags.VertexBuffer, vertices));
            vertexBinding = new VertexBufferBinding(vertexBuffer, Utilities.SizeOf<Vertex>(), 0);

            indexBuffer = ToDispose(Buffer.Create(device, BindFlags.IndexBuffer, indices));
            totalVertexCount = indices.Length;
        }
        public void SetVertexBuffer(Device device, Vector3[] vectors)
        {
            BufferDescription vertexBufferDesc = new BufferDescription()
            {
                SizeInBytes = Vector3.SizeInBytes * vectors.Length,
                Usage = ResourceUsage.Default,
                BindFlags = BindFlags.VertexBuffer
            };

            using (var data = new DataStream(vertexBufferDesc.SizeInBytes, false, true))
            {
                data.WriteRange(vectors);
                data.Position = 0;
                VertexBuffer = new Buffer(device, data, vertexBufferDesc);
            }

            BufferBindings[0] = new VertexBufferBinding(VertexBuffer, 24, 0);
        }
Beispiel #19
0
        internal void Render(DeviceContext3 context, InputLayout inputLayout, VertexShader vertexShader, bool usingVprtShaders, GeometryShader geometryShader, PixelShader pixelShader)
        {
            //Update the texture
            context.PixelShader.SetShaderResource(0, textureView);
            // Each vertex is one instance of the VertexPositionColor struct.
            int stride        = SharpDX.Utilities.SizeOf <VertexPositionTexture>();
            int offset        = 0;
            var bufferBinding = new SharpDX.Direct3D11.VertexBufferBinding(this.vertexBuffer, stride, offset);

            context.InputAssembler.SetVertexBuffers(0, bufferBinding);
            context.InputAssembler.SetIndexBuffer(
                this.indexBuffer,
                SharpDX.DXGI.Format.R16_UInt, // Each index is one 16-bit unsigned integer (short).
                0);
            context.InputAssembler.PrimitiveTopology = SharpDX.Direct3D.PrimitiveTopology.TriangleList;
            context.InputAssembler.InputLayout       = inputLayout;

            // Attach the vertex shader.
            context.VertexShader.SetShader(vertexShader, null, 0);
            // Apply the model constant buffer to the vertex shader.
            context.VertexShader.SetConstantBuffers(0, this.modelConstantBuffer);

            if (!usingVprtShaders)
            {
                // On devices that do not support the D3D11_FEATURE_D3D11_OPTIONS3::
                // VPAndRTArrayIndexFromAnyShaderFeedingRasterizer optional feature,
                // a pass-through geometry shader is used to set the render target
                // array index.
                context.GeometryShader.SetShader(geometryShader, null, 0);
            }

            // Attach the pixel shader.
            context.PixelShader.SetShader(pixelShader, null, 0);

            // Draw the objects.
            context.DrawIndexedInstanced(
                indexCount,     // Index count per instance.
                2,              // Instance count.
                0,              // Start index location.
                0,              // Base vertex location.
                0               // Start instance location.
                );
        }
        public GSSprite(Device device, DVector3 Position)
        {
            //float3 Position //12
            //half2 Size //16
            //half4 AABBTexCoord //24
            //half4 AditiveColor //32
            InputElement[] elements = new[] {
                new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0),
                new InputElement("TEXCOORD", 0, Format.R16G16_Float, 12, 0),
                new InputElement("TEXCOORD", 1, Format.R16G16B16A16_Float, 16, 0),
                new InputElement("TEXCOORD", 2, Format.R16G16B16A16_Float, 24, 0),
            };

            BytesPerVertex = 32;
            VertexsCount = 1;

            var vertices = new DataStream(BytesPerVertex * VertexsCount, true, true);

            vertices.Write(Conversion.ToVector3(Position));
            vertices.Write(new Half2(10, 10));
            vertices.Write(new Half4(0, 0, 1, 1));
            vertices.Write(new Half4(1, 0, 0, 1));
            vertices.Position = 0;

            Vertexs = new Buffer(device, vertices, BytesPerVertex * VertexsCount, ResourceUsage.Dynamic, BindFlags.VertexBuffer, CpuAccessFlags.Write, ResourceOptionFlags.None, 0);
            binding = new VertexBufferBinding(Vertexs, BytesPerVertex, 0);
            vertices.Dispose();

            this.Position = Position;
            EEEM = ContentManager.LoadEffect("Content/Shaders/GSSprite", elements);
            TexCont = ContentManager.LoadTexture2D("Content/Textures/Particl");
            // Подготовка константного буффера
            BufferDescription bd = new BufferDescription();
            bd.SizeInBytes = Marshal.SizeOf(typeof(ShaderConstants));
            bd.Usage = ResourceUsage.Dynamic;
            bd.BindFlags = BindFlags.ConstantBuffer;
            bd.CpuAccessFlags = CpuAccessFlags.Write;
            bd.OptionFlags = ResourceOptionFlags.None;
            bd.StructureByteStride = 0;

            constantsBuffer = new Buffer(device, bd);
            constants = new ShaderConstants();
        }
Beispiel #21
0
 public static void Init(SharpDX.Direct3D11.Device device)
 {
     vertexShaderByteCode = ShaderBytecode.CompileFromFile("Graphics/VertexShader.hlsl", "vertex", "vs_4_0", ShaderFlags.OptimizationLevel1, EffectFlags.None, null, null);
     vertexShader = new VertexShader(device, vertexShaderByteCode, null);
     vertices = SharpDX.Direct3D11.Buffer.Create<Vertex>(device, BindFlags.VertexBuffer, new Vertex[]
     {
         new Vertex(new Vector4(-1f, -1f, 0.5f, 1f), new Vector2(0f, 1f)),
         new Vertex(new Vector4(-1f, 1f, 0.5f, 1f), new Vector2(0f, 0f)),
         new Vertex(new Vector4(1f, -1f, 0.5f, 1f), new Vector2(1f, 1f)),
         new Vertex(new Vector4(-1f, 1f, 0.5f, 1f), new Vector2(0f, 0f)),
         new Vertex(new Vector4(1f, 1f, 0.5f, 1f), new Vector2(1f, 0f)),
         new Vertex(new Vector4(1f, -1f, 0.5f, 1f), new Vector2(1f, 1f))
     }, 144, ResourceUsage.Default, CpuAccessFlags.None, ResourceOptionFlags.None, 0);
     layout = new InputLayout(device, ShaderSignature.GetInputSignature(vertexShaderByteCode), Vertex.elements);
     binding = new VertexBufferBinding(vertices, 24, 0);
     buffer = new SharpDX.Direct3D11.Buffer(device, 64, ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0);
     data.offset = 0f;
     data.scale = 1f;
 }
        public PhysicsDebugDraw(SharpDX11Graphics graphics)
        {
            _device = graphics.Device;
            _inputAssembler = _device.ImmediateContext.InputAssembler;

            InputElement[] elements = {
                new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0, InputClassification.PerVertexData, 0),
                new InputElement("COLOR", 0, Format.R8G8B8A8_UNorm, 12, 0, InputClassification.PerVertexData, 0)
            };
            _inputLayout = new InputLayout(_device, graphics.GetDebugDrawPass().Description.Signature, elements);

            _vertexBufferDesc = new BufferDescription
            {
                Usage = ResourceUsage.Dynamic,
                BindFlags = BindFlags.VertexBuffer,
                CpuAccessFlags = CpuAccessFlags.Write
            };

            _vertexBufferBinding = new VertexBufferBinding(null, PositionColored.Stride, 0);
        }
        /// <summary>
        /// Create any device dependent resources here.
        /// This method will be called when the device is first
        /// initialized or recreated after being removed or reset.
        /// </summary>
        protected override void CreateDeviceDependentResources()
        {
            base.CreateDeviceDependentResources();

            // Ensure that if already set the device resources
            // are correctly disposed of before recreating
            RemoveAndDispose(ref triangleVertices);

            // Retrieve our SharpDX.Direct3D11.Device1 instance
            var device = this.DeviceManager.Direct3DDevice;

            // Create a triangle
            triangleVertices = ToDispose(Buffer.Create(device, BindFlags.VertexBuffer, new[] {
            /*  Vertex Position                       Vertex Color */
                new Vector4(0.0f, 0.0f, 0.5f, 1.0f),  new Vector4(0.0f, 0.0f, 1.0f, 1.0f), // Base-right
                new Vector4(-0.5f, 0.0f, 0.0f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f), // Base-left
                new Vector4(-0.25f, 1f, 0.25f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f), // Apex
            }));
            triangleBinding = new VertexBufferBinding(triangleVertices, Utilities.SizeOf<Vector4>() * 2, 0);
        }
        /// <summary>
        /// Create any device dependent resources here.
        /// This method will be called when the device is first
        /// initialized or recreated after being removed or reset.
        /// </summary>
        protected override void CreateDeviceDependentResources()
        {
            base.CreateDeviceDependentResources();

            // Ensure that if already set the device resources
            // are correctly disposed of before recreating
            RemoveAndDispose(ref triangleVertices);
            RemoveAndDispose(ref textureView);
            RemoveAndDispose(ref samplerState);

            // Retrieve our SharpDX.Direct3D11.Device1 instance
            var device = this.DeviceManager.Direct3DDevice;

            // Create a triangle
            triangleVertices = ToDispose(Buffer.Create(device, BindFlags.VertexBuffer, new[] {
            /*  Vertex Position, normal, Color, UV */
            // Modified normals to work with Curved PN-Triangles
                new Vertex(new Vector3(0.75f, 0f, -0.001f), Vector3.Normalize(Vector3.UnitZ + Vector3.UnitX - Vector3.UnitY), Color.Black, new Vector2(1.0f, 1.0f)), // Base-right
                new Vertex(new Vector3(-0.75f, 0f, -0.001f),Vector3.Normalize(Vector3.UnitZ - Vector3.UnitX - Vector3.UnitY), Color.Black, new Vector2(0.0f, 1.0f)), // Base-left
                new Vertex(new Vector3(0f, 1.5f, -0.001f), Vector3.Normalize(Vector3.UnitZ + Vector3.UnitY), Color.Black, new Vector2(0.5f, 0.0f)), // Apex
            }));
            triangleBinding = new VertexBufferBinding(triangleVertices, Utilities.SizeOf<Vertex>(), 0);

            // Load texture
            textureView = ToDispose(ShaderResourceView.FromFile(device, "Texture2.png"));

            // Create our sampler state
            samplerState = ToDispose(new SamplerState(device, new SamplerStateDescription()
            {
                AddressU = TextureAddressMode.Wrap,
                AddressV = TextureAddressMode.Wrap,
                AddressW = TextureAddressMode.Wrap,
                BorderColor = new Color4(0, 0, 0, 0),
                ComparisonFunction = Comparison.Never,
                Filter = Filter.MinMagMipLinear,
                MaximumAnisotropy = 16,
                MaximumLod = float.MaxValue,
                MinimumLod = 0,
                MipLodBias = 0.0f
            }));
        }
        private VertexArrayObject(GraphicsDevice graphicsDevice, EffectInputSignature shaderSignature, IndexBufferBinding indexBufferBinding, VertexBufferBinding[] vertexBufferBindings)
            : base(graphicsDevice)
        {
            this.vertexBufferBindings = vertexBufferBindings;
            this.indexBufferBinding = indexBufferBinding;
            this.EffectInputSignature = shaderSignature;

            // Calculate Direct3D11 InputElement
            int inputElementCount = vertexBufferBindings.Sum(t => t.Declaration.VertexElements.Length);
            var inputElements = new InputElement[inputElementCount];

            int j = 0;
            for (int i = 0; i < vertexBufferBindings.Length; i++)
            {
                var declaration = vertexBufferBindings[i].Declaration;
                vertexBufferBindings[i].Buffer.AddReferenceInternal();
                foreach (var vertexElementWithOffset in declaration.EnumerateWithOffsets())
                {
                    var vertexElement = vertexElementWithOffset.VertexElement;
                    inputElements[j++] = new InputElement
                        {
                            Slot = i,
                            SemanticName = vertexElement.SemanticName,
                            SemanticIndex = vertexElement.SemanticIndex,
                            AlignedByteOffset = vertexElementWithOffset.Offset,
                            Format = (SharpDX.DXGI.Format)vertexElement.Format,
                        };
                }
            }

            Layout = VertexArrayLayout.GetOrCreateLayout(new VertexArrayLayout(inputElements));

            if (indexBufferBinding != null)
            {
                indexBufferBinding.Buffer.AddReferenceInternal();
                indexBufferOffset = indexBufferBinding.Offset;
                indexFormat = (indexBufferBinding.Is32Bit ? SharpDX.DXGI.Format.R32_UInt : SharpDX.DXGI.Format.R16_UInt);
            }

            CreateResources();
        }
Beispiel #26
0
        /// <summary>
        /// Creates a new mesh.
        /// </summary>
        /// <param name="device">The device to use.</param>
        /// <param name="name">The name of the mesh.</param>
        /// <param name="geometry">The list of vertices in the mesh.</param>
        public Mesh(Device device, String name, List<Vertex> geometry)
        {
            using (DataStream vertexStream = new DataStream(Vertex.Size * geometry.Count, false, true))
            {
                foreach (Vertex vertex in geometry) vertex.WriteTo(vertexStream);
                vertexStream.Position = 0;

                BufferDescription description = new BufferDescription()
                {
                    Usage = ResourceUsage.Immutable,
                    BindFlags = BindFlags.VertexBuffer,
                    CpuAccessFlags = CpuAccessFlags.None,
                    SizeInBytes = Vertex.Size * geometry.Count,
                };

                vertices = new Buffer(device, vertexStream, description);
                vertexBuffer = new VertexBufferBinding(vertices, Vertex.Size, 0);
            }

            MeshName = name;
        }
        /// <summary>
        /// Create any device dependent resources here.
        /// This method will be called when the device is first
        /// initialized or recreated after being removed or reset.
        /// </summary>
        protected override void CreateDeviceDependentResources()
        {
            // Ensure that if already set the device resources
            // are correctly disposed of before recreating
            RemoveAndDispose(ref axisLinesVertices);

            // Retrieve our SharpDX.Direct3D11.Device1 instance
            var device = this.DeviceManager.Direct3DDevice;

            // Create xyz-axis arrows
            // X is Red, Y is Green, Z is Blue
            // The arrows point along the + for each axis
            axisLinesVertices = ToDispose(Buffer.Create(device, BindFlags.VertexBuffer, new[]
            {
            /*  Vertex Position                       Vertex Color */
                new Vector4(-1f, 0f, 0f, 1f), (Vector4)Color.Red, // - x-axis
                new Vector4(1f, 0f, 0f, 1f), (Vector4)Color.Red,  // + x-axis
                new Vector4(0.9f, -0.05f, 0f, 1f), (Vector4)Color.Red,// arrow head start
                new Vector4(1f, 0f, 0f, 1f), (Vector4)Color.Red,
                new Vector4(0.9f, 0.05f, 0f, 1f), (Vector4)Color.Red,
                new Vector4(1f, 0f, 0f, 1f), (Vector4)Color.Red,  // arrow head end

                new Vector4(0f, -1f, 0f, 1f), (Vector4)Color.Lime, // - y-axis
                new Vector4(0f, 1f, 0f, 1f), (Vector4)Color.Lime,  // + y-axis
                new Vector4(-0.05f, 0.9f, 0f, 1f), (Vector4)Color.Lime,// arrow head start
                new Vector4(0f, 1f, 0f, 1f), (Vector4)Color.Lime,
                new Vector4(0.05f, 0.9f, 0f, 1f), (Vector4)Color.Lime,
                new Vector4(0f, 1f, 0f, 1f), (Vector4)Color.Lime,  // arrow head end

                new Vector4(0f, 0f, -1f, 1f), (Vector4)Color.Blue, // - z-axis
                new Vector4(0f, 0f, 1f, 1f), (Vector4)Color.Blue,  // + z-axis
                new Vector4(0f, -0.05f, 0.9f, 1f), (Vector4)Color.Blue,// arrow head start
                new Vector4(0f, 0f, 1f, 1f), (Vector4)Color.Blue,
                new Vector4(0f, 0.05f, 0.9f, 1f), (Vector4)Color.Blue,
                new Vector4(0f, 0f, 1f, 1f), (Vector4)Color.Blue,  // arrow head end
            }));
            axisLinesBinding = new VertexBufferBinding(axisLinesVertices, Utilities.SizeOf<Vector4>() * 2, 0);
        }
        /// <summary>
        /// Create any device dependent resources here.
        /// This method will be called when the device is first
        /// initialized or recreated after being removed or reset.
        /// </summary>
        protected override void CreateDeviceDependentResources()
        {
            base.CreateDeviceDependentResources();

            // Ensure that if already set the device resources
            // are correctly disposed of before recreating
            RemoveAndDispose(ref vertices);
            RemoveAndDispose(ref textureView);
            RemoveAndDispose(ref samplerState);

            // Retrieve our SharpDX.Direct3D11.Device1 instance
            var device = this.DeviceManager.Direct3DDevice;

            // Create a vertex to begin the parametric surface
            vertices = ToDispose(Buffer.Create(device, BindFlags.VertexBuffer, new[] {
            /*  Vertex Position */
                new Vertex(new Vector3(0f, 0f, 0f)), // Base-right
            }));
            vertexBinding = new VertexBufferBinding(vertices, Utilities.SizeOf<Vertex>(), 0);

            // Load texture
            textureView = ToDispose(ShaderResourceView.FromFile(device, "Texture2.png"));

            // Create our sampler state
            samplerState = ToDispose(new SamplerState(device, new SamplerStateDescription()
            {
                AddressU = TextureAddressMode.Wrap,
                AddressV = TextureAddressMode.Wrap,
                AddressW = TextureAddressMode.Wrap,
                BorderColor = new Color4(0, 0, 0, 0),
                ComparisonFunction = Comparison.Never,
                Filter = Filter.MinMagMipLinear,
                MaximumAnisotropy = 16,
                MaximumLod = float.MaxValue,
                MinimumLod = 0,
                MipLodBias = 0.0f
            }));
        }
        /// <summary>
        /// Create any device dependent resources here.
        /// This method will be called when the device is first
        /// initialized or recreated after being removed or reset.
        /// </summary>
        protected override void CreateDeviceDependentResources()
        {
            // Ensure that if already set the device resources
            // are correctly disposed of before recreating
            RemoveAndDispose(ref quadVertices);
            RemoveAndDispose(ref quadIndices);

            // Retrieve our SharpDX.Direct3D11.Device1 instance
            var device = this.DeviceManager.Direct3DDevice;

            // Create vertex buffer for quad
            quadVertices = ToDispose(Buffer.Create(device, BindFlags.VertexBuffer, new Vertex[] {
                /*  Position: float x 3, Normal: Vector3, Color */
                new Vertex(-0.5f, 0f, -0.5f, Vector3.UnitY, color),
                new Vertex(-0.5f, 0f, 0.5f, Vector3.UnitY, color),
                new Vertex(0.5f, 0f, 0.5f, Vector3.UnitY, color),
                new Vertex(0.5f, 0f, -0.5f, Vector3.UnitY, color),
            }));
            quadBinding = new VertexBufferBinding(quadVertices, Utilities.SizeOf<Vertex>(), 0);

            // v0    v1
            // |-----|
            // | \ A |
            // | B \ |
            // |-----|
            // v3    v2
            quadIndices = ToDispose(Buffer.Create(device, BindFlags.IndexBuffer, new ushort[] {
                0, 1, 2, // A
                2, 3, 0  // B
            }));
        }
        // Set up the pipeline for drawing a shape then draw it.
        public void Draw(Shape shape)
        {
            // Set pipeline components to suit the shape if necessary.
            if (currVertexBinding.Buffer != shape.vertexBinding.Buffer) { context.InputAssembler.SetVertexBuffers(0, shape.vertexBinding); currVertexBinding = shape.vertexBinding; }
            if (currLayout != shape.style.layout) { context.InputAssembler.InputLayout = shape.style.layout; currLayout = shape.style.layout; }
            if (currTopology != shape.topology) { context.InputAssembler.PrimitiveTopology = shape.topology; currTopology = shape.topology; }
            if (currVertexShader != shape.style.vertexShader) { context.VertexShader.Set(shape.style.vertexShader); currVertexShader = shape.style.vertexShader; }
            if (currPixelShader != shape.style.pixelShader) { context.PixelShader.Set(shape.style.pixelShader); currPixelShader = shape.style.pixelShader; }
            if (currTextureView != shape.textureView) { context.PixelShader.SetShaderResource(0, shape.textureView); currTextureView = shape.textureView; }

            // Calculate the vertex transformation and update the constant buffer.
            worldViewProj = world * view * proj;
            worldViewProj.Transpose();
            context.UpdateSubresource(ref worldViewProj, constantBuffer);

            // Draw the shape.
            context.Draw(shape.vertexCount, 0);
        }
Beispiel #31
0
        private void SwapChainPanel_OnLoaded(object sender, RoutedEventArgs e)
        {
            using (var defDevice = new D3D.Device(DriverType.Hardware, D3D.DeviceCreationFlags.Debug))
            {
                _device = defDevice.QueryInterface <D3D.Device3>();
            }
            _context = _device.ImmediateContext3;

            var pixelScale    = DisplayInformation.GetForCurrentView().LogicalDpi / 96.0f;
            var swapChainDesc = new DXGI.SwapChainDescription1()
            {
                AlphaMode         = DXGI.AlphaMode.Premultiplied,
                BufferCount       = 2,
                Flags             = DXGI.SwapChainFlags.None,
                Format            = DXGI.Format.B8G8R8A8_UNorm,
                Width             = (int)(panel.RenderSize.Width * pixelScale),
                Height            = (int)(panel.RenderSize.Height * pixelScale),
                SampleDescription = new DXGI.SampleDescription(1, 0),
                Scaling           = DXGI.Scaling.Stretch,
                Stereo            = false,
                SwapEffect        = DXGI.SwapEffect.FlipSequential,
                Usage             = DXGI.Usage.BackBuffer | DXGI.Usage.RenderTargetOutput
            };

            using (var dxgiDevice = _device.QueryInterface <DXGI.Device3>())
            {
                var factory = dxgiDevice.Adapter.GetParent <DXGI.Factory4>();
                using (var tmpSwapChain = new DXGI.SwapChain1(factory, _device, ref swapChainDesc))
                {
                    _swapChain = tmpSwapChain.QueryInterface <DXGI.SwapChain3>();
                }
            }

            using (var nativeObject = ComObject.As <DXGI.ISwapChainPanelNative>(panel))
            {
                nativeObject.SwapChain = _swapChain;
            }

            using (var depthBuffer = new D3D.Texture2D(_device, new D3D.Texture2DDescription()
            {
                Format = DXGI.Format.D24_UNorm_S8_UInt,
                ArraySize = 1,
                MipLevels = 1,
                Width = swapChainDesc.Width,
                Height = swapChainDesc.Height,
                SampleDescription = new DXGI.SampleDescription(1, 0),
                BindFlags = D3D.BindFlags.DepthStencil,
            }))
            {
                _depthStencilView = new D3D.DepthStencilView(_device, depthBuffer, new D3D.DepthStencilViewDescription()
                {
                    Dimension = D3D.DepthStencilViewDimension.Texture2D
                });
            }

            _backBuffer = D3D.Resource.FromSwapChain <D3D.Texture2D>(_swapChain, 0);
            _renderView = new D3D.RenderTargetView1(_device, _backBuffer);

            var viewport = new ViewportF(0, 0, (float)panel.RenderSize.Width, (float)panel.RenderSize.Height, 0.0f, 1.0f);

            _context.Rasterizer.SetViewport(viewport);

            ShaderBytecode shaderBytecode;

            using (shaderBytecode = ShaderBytecode.CompileFromFile("shaders.hlsl", "vs", "vs_5_0", ShaderFlags.Debug))
            {
                _vertexShader = new D3D.VertexShader(_device, shaderBytecode);
            }

            using (var byteCode = ShaderBytecode.CompileFromFile(@"shaders.hlsl", "ps", "ps_5_0", ShaderFlags.Debug))
            {
                _pixelShader = new D3D.PixelShader(_device, byteCode);
            }

            D3D.InputElement[] inputElements =
            {
                new D3D.InputElement("POSITION", 0, DXGI.Format.R32G32B32A32_Float, 0, 0),
            };
            _inputLayout = new D3D.InputLayout(_device, shaderBytecode, inputElements);

            _vertices = new[]
            {
                new Vector4(-0.5f, 0.0f, 0.5f, 1.0f),
                new Vector4(0.0f, 0.5f, 0.5f, 1.0f),
                new Vector4(0.5f, 0.0f, 0.5f, 1.0f),
            };
            _vertexBuffer  = D3D.Buffer.Create(_device, D3D.BindFlags.VertexBuffer, _vertices);
            _vertexBinding = new D3D.VertexBufferBinding(_vertexBuffer, Utilities.SizeOf <Vector4>(), 0);

            _constantBuffer = new SharpDX.Direct3D11.Buffer(
                _device,
                Utilities.SizeOf <SharpDX.Matrix>(),
                D3D.ResourceUsage.Default,
                D3D.BindFlags.ConstantBuffer,
                D3D.CpuAccessFlags.None,
                D3D.ResourceOptionFlags.None,
                0);

            _timer = new Stopwatch();
            _timer.Start();

            CompositionTarget.Rendering += CompositionTarget_Rendering;
        }
        // Used with soft bodies
        public void SetDynamicVertexBuffer(Device device, Vector3[] vectors)
        {
            if (VertexBuffer != null && VertexCount * 2 == vectors.Length)
            {
                DataBox db = device.ImmediateContext.MapSubresource(VertexBuffer, 0, MapMode.WriteDiscard, SharpDX.Direct3D11.MapFlags.None);
                SharpDX.Utilities.Write(db.DataPointer, vectors, 0, vectors.Length);
                device.ImmediateContext.UnmapSubresource(VertexBuffer, 0);
            }
            else
            {
                // Create new buffer
                if (VertexBuffer != null)
                    VertexBuffer.Dispose();

                BufferDescription vertexBufferDesc = new BufferDescription()
                {
                    SizeInBytes = Vector3.SizeInBytes * vectors.Length,
                    Usage = ResourceUsage.Dynamic,
                    BindFlags = BindFlags.VertexBuffer,
                    CpuAccessFlags = CpuAccessFlags.Write
                };

                using (var data = new DataStream(vertexBufferDesc.SizeInBytes, false, true))
                {
                    data.WriteRange(vectors);
                    data.Position = 0;
                    VertexBuffer = new Buffer(device, data, vertexBufferDesc);
                }

                VertexCount = vectors.Length / 2;
                BufferBindings[0] = new VertexBufferBinding(VertexBuffer, 24, 0);
            }
        }
Beispiel #33
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();
        }
Beispiel #34
0
        public override void LoadContent()
        {
            VertexBuffer = Buffer.Create(Engine.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),
            });
            VertexBufferBinding = new SharpDX.Direct3D11.VertexBufferBinding(VertexBuffer, Utilities.SizeOf <Vector4>() * 2, 0);
            ConstantBuffer      = new Buffer(Engine.Device, Utilities.SizeOf <Matrix>(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0);

            // Compile Vertex and Pixel shaders
            var vertexShaderByteCode = ShaderBytecode.CompileFromFile("./Effects/HLSL/BasicEffect.fx", "VS", "vs_4_0");

            VertexShader = new VertexShader(Engine.Device, vertexShaderByteCode);

            var pixelShaderByteCode = ShaderBytecode.CompileFromFile("./Effects/HLSL/BasicEffect.fx", "PS", "ps_4_0");

            PixelShader = new PixelShader(Engine.Device, pixelShaderByteCode);

            var signature = ShaderSignature.GetInputSignature(vertexShaderByteCode);

            // Layout from VertexShader input signature
            InputLayout = new InputLayout(Engine.Device, signature, new[]
            {
                new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0),
                new InputElement("COLOR", 0, Format.R32G32B32A32_Float, 16, 0)
            });

            base.LoadContent();
        }