public DX11DynamicStructuredBuffer(Device dev, Buffer buffer, int cnt) //Dynamic default buffer
 {
     this.Size = cnt;
     this.Buffer = buffer;
     this.Stride = buffer.Description.StructureByteStride;
     this.SRV = new ShaderResourceView(dev, this.Buffer);
 }
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="context">Render context</param>
        /// <param name="vertexSize">Vertex size</param>
        /// <param name="vertexCount">Vertex Count</param>
        /// <param name="inputElements">Input elements</param>
        public StreamOutputBufferWithRawSupport(DX11RenderContext context, int vertexSize, int vertexCount, OutputDrawMode outputDrawMode, bool allowIndexBuffer, InputElement[] inputElements)
        {
            this.innerBuffer = BufferHelper.CreateStreamOutBuffer(context, vertexSize, vertexCount, true, allowIndexBuffer);

            //Copy a new Vertex buffer with stream out
            this.vertexGeometry           = new DX11VertexGeometry(context);
            vertexGeometry.HasBoundingBox = false;
            vertexGeometry.InputLayout    = inputElements;
            vertexGeometry.Topology       = PrimitiveTopology.TriangleList;
            vertexGeometry.VertexBuffer   = innerBuffer;
            vertexGeometry.VertexSize     = vertexSize;
            vertexGeometry.VerticesCount  = vertexCount;

            if (outputDrawMode == OutputDrawMode.Auto)
            {
                vertexGeometry.AssignDrawer(new DX11VertexAutoDrawer());
            }

            if (context.ComputeShaderSupport)
            {
                this.rawBuffer = new DX11RawBuffer(context, innerBuffer);
            }

            if (allowIndexBuffer)
            {
                this.indexBuffer = DX11IndexBuffer.FromReference(context, this.innerBuffer, vertexCount);
            }
        }
Example #3
0
        private void BuildQuadPatchIB(Device device)
        {
            var indices = new List <int>();

            for (var i = 0; i < NumPatchVertRows - 1; i++)
            {
                for (var j = 0; j < NumPatchVertCols - 1; j++)
                {
                    indices.Add(i * NumPatchVertCols + j);
                    indices.Add(i * NumPatchVertCols + j + 1);
                    indices.Add((i + 1) * NumPatchVertCols + j);
                    indices.Add((i + 1) * NumPatchVertCols + j + 1);
                }
            }
            var ibd = new BufferDescription(
                sizeof(short) * indices.Count,
                ResourceUsage.Immutable,
                BindFlags.IndexBuffer,
                CpuAccessFlags.None,
                ResourceOptionFlags.None, 0
                );

            _quadPatchIB = new Buffer(
                device,
                new DataStream(indices.Select(i => (short)i).ToArray(), false, false),
                ibd
                );
        }
Example #4
0
        //============================================================
        public void Upload(int vertexSize, byte[] data, int offset, int length)
        {
            int byteSize = sizeof(float) * vertexSize;

            var stream = new DataStream(length, true, true);

            stream.Write(data, offset, length);
            stream.Position = 0;

            _nativeDescription = new BufferDescription()
            {
                BindFlags      = BindFlags.VertexBuffer,
                CpuAccessFlags = CpuAccessFlags.None,
                OptionFlags    = ResourceOptionFlags.None,
                SizeInBytes    = length,
                Usage          = ResourceUsage.Default,
            };

            _nativeD3dBuffer = new DxBuffer(_device.NativeAdapter, stream, _nativeDescription);
            stream.Dispose();

            FVector <VertexBufferBinding> bindings = new FVector <VertexBufferBinding>();

            bindings.Push(new VertexBufferBinding(_nativeD3dBuffer, byteSize, 0));  // Position 4
            bindings.Push(new VertexBufferBinding(_nativeD3dBuffer, byteSize, 16)); // Color 4
            bindings.Push(new VertexBufferBinding(_nativeD3dBuffer, byteSize, 32)); // Coord 2
            bindings.Push(new VertexBufferBinding(_nativeD3dBuffer, byteSize, 40)); // Normal 4
            bindings.Push(new VertexBufferBinding(_nativeD3dBuffer, byteSize, 56)); // Binormal 3
            bindings.Push(new VertexBufferBinding(_nativeD3dBuffer, byteSize, 68)); // Tangent 3
            _nativeBuffers = bindings.ToArray();
        }
Example #5
0
        /// <summary>
        /// Creates the VertexBuffer for the quad
        /// </summary>
        private void createFullScreenQuad()
        {
            var vbData = new QuadVertex[4];

            // Upper right
            vbData[0].Position = new Vector3(1, 1, 1);
            vbData[0].TexCoordAndCornerIndex = new Vector3(1, 0, 1);

            // Lower right
            vbData[1].Position = new Vector3(1, -1, 1);
            vbData[1].TexCoordAndCornerIndex = new Vector3(1, 1, 2);

            // Upper left
            vbData[2].Position = new Vector3(-1, 1, 1);
            vbData[2].TexCoordAndCornerIndex = new Vector3(0, 0, 0);

            // Lower left
            vbData[3].Position = new Vector3(-1, -1, 1);
            vbData[3].TexCoordAndCornerIndex = new Vector3(0, 1, 3);


            using (var strm = new DataStream(vbData, true, false))
            {
                vertexBuffer = new Buffer(device, strm, 4 * QuadVertex.SizeInBytes, ResourceUsage.Immutable, BindFlags.VertexBuffer,
                                          CpuAccessFlags.None, ResourceOptionFlags.None, 0);
            }
        }
            public DX11SharedStructuredBuffer(DX11RenderContext context, IntPtr sharedHandle)
            {
                try
                {
                    Buffer            buffer = context.Device.OpenSharedResource <Buffer>(sharedHandle);
                    BufferDescription bdesc  = buffer.Description;

                    if (!bdesc.OptionFlags.HasFlag(ResourceOptionFlags.StructuredBuffer))
                    {
                        buffer.Dispose();
                        throw new InvalidOperationException("This buffer handle does not have structured buffer flag");
                    }

                    this.Buffer       = buffer;
                    this.Stride       = bdesc.StructureByteStride;
                    this.ElementCount = bdesc.SizeInBytes / this.Stride;
                    this.Size         = bdesc.SizeInBytes;

                    this.SRV = new ShaderResourceView(context.Device, this.Buffer);
                }
                catch
                {
                    throw new InvalidOperationException("Buffer handle is invalid");
                }
            }
Example #7
0
        public void Update(IPluginIO pin, DX11RenderContext context)
        {
            if (this.updateddevices.Contains(context))
            {
                return;
            }
            if (reset || !this.FOutGeom[0].Contains(context))
            {
                this.DisposeBuffers(context);

                // int vsize = customlayout ? size : ig.VertexSize;
                SlimDX.Direct3D11.Buffer vbo = BufferHelper.CreateStreamOutBuffer(context, vsize, this.cnt);

                //Copy a new Vertex buffer with stream out
                DX11VertexGeometry vg = new DX11VertexGeometry(context);
                vg.AssignDrawer(new DX11VertexAutoDrawer());
                vg.HasBoundingBox = false;
                vg.InputLayout    = this.FInLayout.ToArray();
                vg.Topology       = PrimitiveTopology.TriangleList;
                vg.VertexBuffer   = vbo;
                vg.VertexSize     = vsize;
                vg.VerticesCount  = this.cnt;

                this.buffer = vbo;

                this.FOutGeom[0][context] = vg;
            }

            this.updateddevices.Add(context);
        }
Example #8
0
        protected void TriangleContext(Pointdata a, Pointdata b, Pointdata c)
        {
            //clear history
            if (Vertices != null)
            {
                Vertices.Dispose();
                Layout.Dispose();
                Vertexbuffer.Dispose();
            }
            Vertices = new DataStream(12 * 3, true, true);
            Vertices.Write(new Vector3(a.x, a.y, a.z));
            Vertices.Write(new Vector3(b.x, b.y, b.z));
            Vertices.Write(new Vector3(c.x, c.y, c.z));
            Vertices.Position = 0;
            // create the vertex layout and buffer
            var elements = new[] { new InputElement("POSITION", 0, Format.R32G32B32_Float, 0) };

            Layout       = new InputLayout(_device, InputSignature, elements);
            Vertexbuffer = new Buffer(_device, Vertices, 12 * 3, ResourceUsage.Default, BindFlags.VertexBuffer,
                                      CpuAccessFlags.None, ResourceOptionFlags.None, 0);

            // configure the Input Assembler portion of the pipeline with the vertex data
            Devicecontext.InputAssembler.InputLayout       = Layout;
            Devicecontext.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList;
            Devicecontext.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(Vertexbuffer, 12, 0));

            // set the shaders
            Devicecontext.VertexShader.Set(Vertexshader);
            Devicecontext.PixelShader.Set(Pixelshader);
            // draw the triangle
            Devicecontext.Draw(3, 0);
        }
Example #9
0
        public void CreateBufferInstance(CustomConstantBufferDefinition baseDefinition, Device device, bool newInstance)
        {
            if (!newInstance)
            {
                m_Writer.Dispose();
                m_Writer = null;

                m_DataStream.Dispose();
                m_DataStream = null;

                m_ConstantBuffer.Dispose();
                m_ConstantBuffer = null;
            }
            else
            {
                m_Values = new Dictionary <String, object>();
            }

            m_Definition     = baseDefinition;
            m_DefinitionName = baseDefinition.m_Name;
            m_DataBuffer     = new byte[baseDefinition.m_Size];
            m_Size           = baseDefinition.m_Size;
            m_DataStream     = new MemoryStream(m_DataBuffer, 0, baseDefinition.m_Size, true);
            m_Writer         = new BinaryWriter(m_DataStream);
            m_ConstantBuffer = new SlimDX.Direct3D11.Buffer(
                device,
                baseDefinition.m_Size,
                ResourceUsage.Dynamic,
                BindFlags.ConstantBuffer,
                CpuAccessFlags.Write,
                ResourceOptionFlags.None,
                0);
        }
 public DX11DynamicStructuredBuffer(Device dev, Buffer buffer, int cnt) //Dynamic default buffer
 {
     this.Size   = cnt;
     this.Buffer = buffer;
     this.Stride = buffer.Description.StructureByteStride;
     this.SRV    = new ShaderResourceView(dev, this.Buffer);
 }
Example #11
0
        public bool OnInitialize(Device device, EffectPass pass)
        {
            DataStream stream;

            try
            {
                stream       = new DataStream(faces, true, true);
                vertexBuffer = new SlimDX.Direct3D11.Buffer(
                    device,
                    stream,
                    new BufferDescription
                {
                    SizeInBytes = (int)stream.Length,
                    BindFlags   = SlimDX.Direct3D11.BindFlags.VertexBuffer,
                    OptionFlags = ResourceOptionFlags.DrawIndirect,
                });
                stream.Dispose();
            }
            catch (Exception e)
            {
                return(false);
            }

            CreateInputBuffer(device, 0);

            vertexLayout = new InputLayout(
                device,
                pass.Description.Signature,
                VertexDefinition.VertexElements
                );

            return(true);
        }
Example #12
0
        public GameOfLifeCalculator()
        {
            var d = RenderFrame.Instance.device;

            var ShaderInputTexDescription = new Texture2DDescription
            {
                ArraySize         = 1,
                Width             = Config.Width,
                Height            = Config.Height,
                BindFlags         = BindFlags.ShaderResource,
                CpuAccessFlags    = CpuAccessFlags.None,
                Format            = Format.R8G8B8A8_UNorm,
                Usage             = ResourceUsage.Default,
                MipLevels         = 1,
                SampleDescription = new SampleDescription(1, 0)
            };

            ScreenBufferShaderResourceTexture = new Texture2D(d, ShaderInputTexDescription);
            ScreenBufferShaderResource        = new ShaderResourceView(d, ScreenBufferShaderResourceTexture);

            randomTex     = Texture2D.FromFile(d, @".\Content\Noise.png");
            randomTexView = new ShaderResourceView(d, randomTex);

            ShaderInputTexDescription.BindFlags = BindFlags.RenderTarget;
            OffscreenRenderTargetTexture        = new Texture2D(d, ShaderInputTexDescription);
            OffscreenRenderTarget = new RenderTargetView(d, OffscreenRenderTargetTexture);
            d.ImmediateContext.ClearRenderTargetView(OffscreenRenderTarget, Color.Black);

            GoLPS = ShaderProvider.CompilePS("./Shader/GoL.fx");
            GoLVS = ShaderProvider.CompileVS("./Shader/GoL.fx");

            CBuffer = new Buffer(d, Vector4.SizeInBytes * 2, ResourceUsage.Dynamic, BindFlags.ConstantBuffer, CpuAccessFlags.Write, ResourceOptionFlags.None, 0);

            quad = Mesh.ScreenQuad();
        }
Example #13
0
        public static T[] CopyBuffer <T>(Device graphicsDevice, Resource source, int offset, int count) where T : struct
        {
            Buffer destination = new Buffer(graphicsDevice, new BufferDescription()
            {
                BindFlags           = BindFlags.None,
                CpuAccessFlags      = CpuAccessFlags.Read,
                OptionFlags         = ResourceOptionFlags.None,
                Usage               = ResourceUsage.Staging,
                SizeInBytes         = (source as Buffer).Description.SizeInBytes,
                StructureByteStride = (source as Buffer).Description.StructureByteStride
            });

            graphicsDevice.ImmediateContext.CopyResource(source, destination);

            DataBox data = graphicsDevice.ImmediateContext.MapSubresource(destination, MapMode.Read, MapFlags.None);

            T[] result = new T[count];
            data.Data.Position = offset * Marshal.SizeOf(typeof(T));
            data.Data.ReadRange <T>(result, 0, count);
            graphicsDevice.ImmediateContext.UnmapSubresource(destination, 0);

            destination.Dispose();

            return(result);
        }
Example #14
0
        public override void BuildShapeBuffers(Device device)
        {
            var cylinder = CreateCylinder(bottomRadius, topRadius, height, sliceCount, stackCount);

            VertexCount = cylinder.Vertices.Count;
            IndexCount  = cylinder.Indices.Count;

            var vertices = cylinder.Vertices.Select(v => new Basic32(v.Position, v.Normal, v.TexC)).ToList();
            var indices  = cylinder.Indices;

            var vbd = new BufferDescription(
                Basic32.Stride * VertexCount,
                ResourceUsage.Default,
                BindFlags.VertexBuffer,
                CpuAccessFlags.None,
                ResourceOptionFlags.None,
                0);

            VertexBuffer = new Buffer(device, new DataStream(vertices.ToArray(), false, false), vbd);

            var ibd = new BufferDescription(
                sizeof(int) * IndexCount,
                ResourceUsage.Default,
                BindFlags.IndexBuffer,
                CpuAccessFlags.None,
                ResourceOptionFlags.None,
                0);

            IndexBuffer = new Buffer(device, new DataStream(indices.ToArray(), false, false), ibd);
        }
Example #15
0
        protected void SetIndexBuffer <I>(IIndexParser <I> indexParser) where I : struct
        {
            numIndices             = indexParser.IndexCount;
            indexStride            = Marshal.SizeOf(typeof(I));
            indexBufferSizeInBytes = numIndices * indexStride;

            indices = new DataStream(indexBufferSizeInBytes, true, true);
            for (int i = 0; i < numIndices; i++)
            {
                indexParser.FillIndex(i, out I index);
                indices.Write(index);
            }

            indices.Position = 0;

            indexBuffer = new Buffer(
                DeviceManager.Instance.device,
                indices,
                indexBufferSizeInBytes,
                ResourceUsage.Default,
                BindFlags.IndexBuffer,
                CpuAccessFlags.None,
                ResourceOptionFlags.None,
                0);
        }
        public void Render(SceneGraph SceneGraph, Camera Camera, Matrix ProjMatrix)
        {
            // Set input assembler information
            ImmediateContext.InputAssembler.InputLayout       = InputLayout;
            ImmediateContext.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList;

            // Build vertex and index buffer
            // TODO KAM: If nothing has changed, don't re-build the buffers maybe? But how to tell...
            var verts   = GetAllVertices(SceneGraph);
            var indices = GetAllIndices(SceneGraph);

            var vertBufferDesc = new BufferDescription(BasicEffectVertex.Stride * verts.Length,
                                                       ResourceUsage.Default, BindFlags.VertexBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0);

            Util.ReleaseCom(ref VertexBuffer);
            VertexBuffer = new SlimDX.Direct3D11.Buffer(Device, new DataStream(verts, false, false), vertBufferDesc);

            var indexBufferDesc = new BufferDescription(sizeof(uint) * indices.Length,
                                                        ResourceUsage.Default, BindFlags.IndexBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0);

            Util.ReleaseCom(ref IndexBuffer);
            IndexBuffer = new SlimDX.Direct3D11.Buffer(Device, new DataStream(indices, false, false), indexBufferDesc);

            // Set vertex and index buffers
            ImmediateContext.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(VertexBuffer, BasicEffectVertex.Stride, 0));
            ImmediateContext.InputAssembler.SetIndexBuffer(IndexBuffer, SlimDX.DXGI.Format.R32_UInt, 0);

            // Render all nodes!
            Pass = EffectTechnique.GetPassByIndex(0);
            int a, b;

            RenderNode(SceneGraph, Camera, ProjMatrix, 0, 0, out a, out b);
        }
Example #17
0
        private void BuildWaveGeometryBuffers()
        {
            var vbd = new BufferDescription(VertexPN.Stride * _waves.VertexCount, ResourceUsage.Dynamic, BindFlags.VertexBuffer, CpuAccessFlags.Write, ResourceOptionFlags.None, 0);

            _waveVB = new Buffer(Device, vbd);

            var indices = new List <int>();
            var m       = _waves.RowCount;
            var n       = _waves.ColumnCount;

            for (int i = 0; i < m - 1; i++)
            {
                for (int j = 0; j < n - 1; j++)
                {
                    indices.Add(i * n + j);
                    indices.Add(i * n + j + 1);
                    indices.Add((i + 1) * n + j);

                    indices.Add((i + 1) * n + j);
                    indices.Add(i * n + j + 1);
                    indices.Add((i + 1) * n + j + 1);
                }
            }
            var ibd = new BufferDescription(sizeof(int) * indices.Count, ResourceUsage.Immutable, BindFlags.IndexBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0);

            _waveIB = new Buffer(Device, new DataStream(indices.ToArray(), false, false), ibd);
        }
Example #18
0
		public void LoadResources()
		{
			if (m_Disposed == true)
			{
				if (m_Filename != null)
				{
					m_ImposterTexture = Texture2D.FromFile(GameEnvironment.Device, Helper.ResolvePath(m_Filename));
					TextureView = new ShaderResourceView(GameEnvironment.Device, m_ImposterTexture);
				}

				m_Vertices = new SlimDX.Direct3D11.Buffer(GameEnvironment.Device, new BufferDescription()
				{
					BindFlags = BindFlags.VertexBuffer,
					CpuAccessFlags = CpuAccessFlags.Write,
					OptionFlags = ResourceOptionFlags.None,
					SizeInBytes = 4 * Marshal.SizeOf(typeof(Vertex2D)),
					Usage = ResourceUsage.Dynamic
				});

				m_VerticesBindings = new VertexBufferBinding(m_Vertices, Marshal.SizeOf(typeof(Vertex2D)), 0);

				WriteRectangle(); 		

				m_Disposed = false;
			}
		}
Example #19
0
        /// <summary>
        /// Setting up the vertex buffer. Vertex size and number has to be known.
        /// </summary>
        /// <param name="origin"></param>
        /// <param name="xAxis"></param>
        /// <param name="yAxis"></param>
        /// <param name="scale"></param>
        protected void GenerateGeometry(Plane plane, PointSet <Point> points)
        {
            // Write poition and UV-map data.
            var     stream = new DataStream(_numVertices * _vertexSizeBytes, true, true);
            Vector3 zAxis  = plane.ZAxis;

            foreach (Point point in points.Points)
            {
                var test = new Vector4(plane.Origin + (plane.XAxis * point.Position[0] + plane.YAxis * point.Position[1] + zAxis * point.Position[2]), 1.0f);
                stream.Write(new Vector4(plane.Origin + (plane.XAxis * point.Position[0] + plane.YAxis * point.Position[1] + zAxis * point.Position[2]), 1.0f));
                stream.Write(point.Color);
                stream.Write(point.Radius * plane.PointSize);
            }
            stream.Position = 0;

            // Create and fill buffer.
            _vertices = new Buffer(Renderable._device, stream, new BufferDescription()
            {
                BindFlags      = BindFlags.VertexBuffer,
                CpuAccessFlags = CpuAccessFlags.None,
                OptionFlags    = ResourceOptionFlags.None,
                SizeInBytes    = _numVertices * _vertexSizeBytes,
                Usage          = ResourceUsage.Default
            });
            stream.Dispose();
        }
Example #20
0
        public ShaderResourceView GenerateNoiseTexture(Buffer constantBuffer, DirectComputeConstantBuffer container)
        {
            Texture3D noiseTexture = new Texture3D(graphicsDevice, new Texture3DDescription()
            {
                BindFlags      = BindFlags.ShaderResource | BindFlags.UnorderedAccess,
                CpuAccessFlags = CpuAccessFlags.None,
                Format         = Format.R32_Float,
                MipLevels      = 1,
                OptionFlags    = ResourceOptionFlags.None,
                Usage          = ResourceUsage.Default,
                Width          = container.Width,
                Height         = container.Height,
                Depth          = container.Depth
            });

            UnorderedAccessView noiseTextureUAV = new UnorderedAccessView(graphicsDevice, noiseTexture);

            DataBox data = graphicsDevice.ImmediateContext.MapSubresource(constantBuffer, MapMode.WriteDiscard, MapFlags.None);

            data.Data.Write <DirectComputeConstantBuffer>(container);
            graphicsDevice.ImmediateContext.UnmapSubresource(constantBuffer, 0);

            graphicsDevice.ImmediateContext.ComputeShader.Set(computeFillNoiseTexture);
            graphicsDevice.ImmediateContext.ComputeShader.SetConstantBuffer(constantBuffer, 0);
            graphicsDevice.ImmediateContext.ComputeShader.SetUnorderedAccessView(noiseTextureUAV, 0);

            Vector3 gridDim = new Vector3((float)Math.Ceiling(container.Width / 8.0f), (float)Math.Ceiling(container.Height / 8.0f), (float)Math.Ceiling(container.Depth / 8.0f));

            graphicsDevice.ImmediateContext.Dispatch((int)gridDim.X, (int)gridDim.Y, (int)gridDim.Z);

            noiseTextureUAV.Dispose();

            return(new ShaderResourceView(graphicsDevice, noiseTexture));
        }
Example #21
0
        public static SlimDX.Direct3D11.Buffer InitQuadIndices(Device device)
        {
            ushort[] indices = new ushort[6 * MaxQuads];
            for (int i = 0; i < MaxQuads; ++i)
            {
                int baseVal = i * 4;
                int idx     = i * 6;
                indices[idx + 0] = (ushort)(baseVal + 0);
                indices[idx + 1] = (ushort)(baseVal + 1);
                indices[idx + 2] = (ushort)(baseVal + 2);

                indices[idx + 3] = (ushort)(baseVal + 2);
                indices[idx + 4] = (ushort)(baseVal + 1);
                indices[idx + 5] = (ushort)(baseVal + 3);
            }

            using (var ds = new DataStream(indices, true, true))
            {
                ds.Position = 0;
                var buffer = new SlimDX.Direct3D11.Buffer(device, ds, new BufferDescription()
                {
                    BindFlags   = BindFlags.IndexBuffer,
                    SizeInBytes = 12 * MaxQuads,
                });
                return(buffer);
            }
        }
Example #22
0
        public SlimDXBuffer11 GetBuffer(string name)
        {
            SlimDXBuffer11 obj = null;

            m_BufferList.TryGetValue(name, out obj);
            return(obj);
        }
        public ShaderResourceView GenerateNoiseTexture(Buffer constantBuffer, DirectComputeConstantBuffer container)
        {
            Texture3D noiseTexture = new Texture3D(graphicsDevice, new Texture3DDescription()
            {
                BindFlags = BindFlags.ShaderResource | BindFlags.UnorderedAccess,
                CpuAccessFlags = CpuAccessFlags.None,
                Format = Format.R32_Float,
                MipLevels = 1,
                OptionFlags = ResourceOptionFlags.None,
                Usage = ResourceUsage.Default,
                Width = container.Width,
                Height = container.Height,
                Depth = container.Depth
            });

            UnorderedAccessView noiseTextureUAV = new UnorderedAccessView(graphicsDevice, noiseTexture);

            DataBox data = graphicsDevice.ImmediateContext.MapSubresource(constantBuffer, MapMode.WriteDiscard, MapFlags.None);
            data.Data.Write<DirectComputeConstantBuffer>(container);
            graphicsDevice.ImmediateContext.UnmapSubresource(constantBuffer, 0);

            graphicsDevice.ImmediateContext.ComputeShader.Set(computeFillNoiseTexture);
            graphicsDevice.ImmediateContext.ComputeShader.SetConstantBuffer(constantBuffer, 0);
            graphicsDevice.ImmediateContext.ComputeShader.SetUnorderedAccessView(noiseTextureUAV, 0);

            Vector3 gridDim = new Vector3((float)Math.Ceiling(container.Width / 8.0f), (float)Math.Ceiling(container.Height / 8.0f), (float)Math.Ceiling(container.Depth / 8.0f));

            graphicsDevice.ImmediateContext.Dispatch((int)gridDim.X, (int)gridDim.Y, (int)gridDim.Z);

            noiseTextureUAV.Dispose();

            return new ShaderResourceView(graphicsDevice, noiseTexture);
        }
Example #24
0
        public ConstantBuffer(SlimDX.Direct3D11.Device device)
        {
            _device     = device;
            sizeInBytes = 4 * 4 * sizeof(float) * 2 +
                          4 * sizeof(float) * 3 +
                          sizeof(float) * (4 + 4 + 4);
            BufferDescription constBufferDescription = new BufferDescription();

            constBufferDescription.Usage          = ResourceUsage.Default;
            constBufferDescription.SizeInBytes    = sizeInBytes;
            constBufferDescription.BindFlags      = BindFlags.ConstantBuffer;
            constBufferDescription.CpuAccessFlags = CpuAccessFlags.None;
            _constBuffer = new SlimDX.Direct3D11.Buffer(device, constBufferDescription);
            _wasChanged  = true;

            _world      = SlimDX.Matrix.Identity;
            _view       = SlimDX.Matrix.Identity;
            _projection = SlimDX.Matrix.Identity;
            _material   = new Material(new SlimDX.Vector4(0.6f, 0.6f, 0.6f, 1.0f),
                                       new SlimDX.Vector4(1.0f, 1.0f, 1.0f, 1.0f),
                                       new SlimDX.Vector4(0.0f, 0.0f, 0.0f, 1.0f));
            _lightDirection = new SlimDX.Vector4(0.0f, 0.0f, 1.0f, 1.0f);
            _ambientLight   = new SlimDX.Vector4(0.1f, 0.1f, 0.1f, 1.0f);
            _cameraPosition = new SlimDX.Vector4(0.0f, 0.0f, -1.0f, 1.0f);
        }
Example #25
0
            public Axes(Device device, InputLayout lineLayout, EffectTechnique _tech)
            {
                this.device     = device;
                this.lineLayout = lineLayout;
                this._pass      = _tech.GetPassByIndex(0);

                PositionColored[] axes = new PositionColored[]
                {
                    new PositionColored(new Vector3(0), Color.Red),
                    new PositionColored(new Vector3(10, 0, 0), Color.Red),

                    new PositionColored(new Vector3(0), Color.Green),
                    new PositionColored(new Vector3(0, 10, 0), Color.Green),

                    new PositionColored(new Vector3(0), Color.Blue),
                    new PositionColored(new Vector3(0, 0, 10), Color.Blue)
                };

                BufferDescription vbd = new BufferDescription(PositionColored.Stride * axes.Length, ResourceUsage.Immutable, BindFlags.VertexBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0);

                uint[]            indices      = new uint[] { 0, 1, 2, 3, 4, 5 };
                BufferDescription ibd          = new BufferDescription(sizeof(uint) * indices.Length, ResourceUsage.Immutable, BindFlags.IndexBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0);
                Buffer            vertexBuffer = new Buffer(device, new DataStream(axes, true, false), vbd);

                vertexBufferBinding = new VertexBufferBinding(vertexBuffer, PositionColored.Stride, 0);
                IndexBuffer         = new Buffer(device, new DataStream(indices, false, false), ibd);
            }
Example #26
0
        public Minimap(Device device, DeviceContext dc, int minimapWidth, int minimapHeight, Terrain terrain, CameraBase viewCam)
        {
            _dc = dc;

            _minimapViewport = new Viewport(0, 0, minimapWidth, minimapHeight);

            CreateMinimapTextureViews(device, minimapWidth, minimapHeight);

            _terrain = terrain;

            SetupOrthoCamera();
            _viewCam = viewCam;

            // frustum vb will contain four corners of view frustum, with first vertex repeated as the last
            var vbd = new BufferDescription(
                VertexPC.Stride * 5,
                ResourceUsage.Dynamic,
                BindFlags.VertexBuffer,
                CpuAccessFlags.Write,
                ResourceOptionFlags.None,
                0
            );
            _frustumVB = new Buffer(device, vbd);

            _edgePlanes = new[] {
            new Plane(1, 0, 0, -_terrain.Width / 2),
            new Plane(-1, 0, 0, _terrain.Width / 2),
            new Plane(0, 1, 0, -_terrain.Depth / 2),
            new Plane(0, -1, 0, _terrain.Depth / 2)
            };

            ScreenPosition = new Vector2(0.25f, 0.75f);
            Size = new Vector2(0.25f, 0.25f);
        }
 protected TransparencyShader(Device device, string vertexShaderPath, string pixelShaderPath, IInputLayoutProvider inputLayoutMaker)
     : base(device, vertexShaderPath, pixelShaderPath, inputLayoutMaker)
 {
     Contract.Ensures(transparencyConstantBuffer != null, "lightConstantBuffer must be instantiated by this function.");
     BufferDescription transparencyBufferDesc = new BufferDescription(System.Runtime.InteropServices.Marshal.SizeOf(typeof(TransparencyCBuffer)), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0);
     transparencyConstantBuffer = new SlimDX.Direct3D11.Buffer(device, transparencyBufferDesc);
 }
Example #28
0
        public void SetMesh(Mesh mesh)
        {
            Mesh = mesh;

            DataStream stream = new DataStream(12 * mesh.Vertices.Length, true, true);

            for (int i = 0; i < mesh.Vertices.Length; i++)
            {
                stream.Write(new Vector3(mesh.Vertices[i].X, mesh.Vertices[i].Y, mesh.Vertices[i].Z));
            }
            stream.Position = 0;

            // create the vertex layout and buffer
            var elements     = new[] { new InputElement("POSITION", 0, Format.R32G32B32_Float, 0) };
            var layout       = new InputLayout(device, inputSignature, elements);
            var vertexBuffer = new Buffer(device, stream, 12 * mesh.Vertices.Length, ResourceUsage.Default, BindFlags.VertexBuffer, CpuAccessFlags.None,
                                          ResourceOptionFlags.None, 0);

            // configure the Input Assembler portion of the pipeline with the vertex data
            context.InputAssembler.InputLayout       = layout;
            context.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList;
            context.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(vertexBuffer, 12, 0));

            context.VertexShader.Set(vertexShader);
            context.PixelShader.Set(pixelShader);
        }
Example #29
0
        public override void BuildShapeBuffers(Device device)
        {
            var grid = CreateGrid(width, depth, m, n);

            VertexCount = grid.Vertices.Count;
            IndexCount  = grid.Indices.Count;

            var vertices = grid.Vertices.Select(v => new Basic32(v.Position, v.Normal, v.TexC)).ToList();
            var indices  = grid.Indices;

            var vbd = new BufferDescription(
                Basic32.Stride * VertexCount,
                ResourceUsage.Default,
                BindFlags.VertexBuffer,
                CpuAccessFlags.None,
                ResourceOptionFlags.None,
                0);

            VertexBuffer = new Buffer(device, new DataStream(vertices.ToArray(), false, false), vbd);

            var ibd = new BufferDescription(
                sizeof(int) * IndexCount,
                ResourceUsage.Default,
                BindFlags.IndexBuffer,
                CpuAccessFlags.None,
                ResourceOptionFlags.None,
                0);

            IndexBuffer = new Buffer(device, new DataStream(indices.ToArray(), false, false), ibd);
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="WVPTransformShader" /> class.
 /// </summary>
 /// <param name="device">The device.</param>
 /// <param name="vertexShaderPath">The vertex shader path.</param>
 /// <param name="pixelShaderPath">The pixel shader path.</param>
 public WVPTransformShader(Device device, string vertexShaderPath, string pixelShaderPath, IInputLayoutProvider inputLayoutMaker)
     : base(device, vertexShaderPath, pixelShaderPath, inputLayoutMaker)
 {
     Contract.Ensures(matrixConstantBuffer != null, "matrixConstantBuffer must not be null after this method executes.");
     BufferDescription matrixBufferDesc = new BufferDescription(System.Runtime.InteropServices.Marshal.SizeOf(typeof(MatrixCBuffer)), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0);
     matrixConstantBuffer = new SlimDX.Direct3D11.Buffer(device, matrixBufferDesc);
 }
 // Functions
 public GPUBufferObject()
 {
     m_Size                = 1;
     m_BufferObject        = null;
     m_ShaderResourceView  = null;
     m_UnorderedAccessView = null;
 }
Example #32
0
        public ObjRenderer(Form1 F)
            : base(F.Device)
        {
            P = F;
            PortalRoomManager.Equals(null, null);
            S = new Sorter();
            string s0 = Environment.CurrentDirectory + "/resources/shaders/ambient_fast.fx";
            SB_V = ShaderBytecode.CompileFromFile(s0, "VS_STATIC", "vs_4_0", ManagedSettings.ShaderCompileFlags, EffectFlags.None);
            SB_P = ShaderBytecode.CompileFromFile(s0, "PS", "ps_4_0", ManagedSettings.ShaderCompileFlags, EffectFlags.None);
            VS = new VertexShader(F.Device.HadrwareDevice(), SB_V);
            PS = new PixelShader(F.Device.HadrwareDevice(), SB_P);
            IL = new InputLayout(Device.HadrwareDevice(), SB_V, StaticVertex.ies);
            BufferDescription desc = new BufferDescription
            {
                Usage = ResourceUsage.Default,
                SizeInBytes = 2 * 64,
                BindFlags = BindFlags.ConstantBuffer
            };
            cBuf = new SlimDX.Direct3D11.Buffer(Device.HadrwareDevice(), desc);
            dS = new DataStream(2 * 64, true, true);

            BufferDescription desc2 = new BufferDescription
            {
                Usage = ResourceUsage.Default,
                SizeInBytes = 64,
                BindFlags = BindFlags.ConstantBuffer
            };
            cBuf2 = new SlimDX.Direct3D11.Buffer(Device.HadrwareDevice(), desc2);
            dS2 = new DataStream(64, true, true);
        }
 public void Dispose()
 {
     VertexBuffer.Dispose();
     IndexBuffer.Dispose();
     VertexBuffer = null;
     IndexBuffer  = null;
 }
Example #34
0
        public T RetrieveArgs()
        {
            if (staging == null)
            {
                int size = Marshal.SizeOf(typeof(T));

                BufferDescription bd = new BufferDescription();
                bd.Usage = ResourceUsage.Staging;
                bd.StructureByteStride = 0;
                bd.SizeInBytes         = size;
                bd.CpuAccessFlags      = CpuAccessFlags.Read;
                bd.BindFlags           = BindFlags.None;
                bd.OptionFlags         = ResourceOptionFlags.None;

                staging = new SlimDX.Direct3D11.Buffer(context.Device, bd);
            }

            this.context.CurrentDeviceContext.CopyResource(this.Buffer, staging);

            DataBox db   = this.context.CurrentDeviceContext.MapSubresource(staging, MapMode.Read, MapFlags.None);
            T       data = db.Data.Read <T>();

            this.context.CurrentDeviceContext.UnmapSubresource(staging, 0);

            return(data);
        }
        public void Dispose()
        {
            Material       = null;
            DiffuseTexture = null;

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

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

            if (Parts != null)
            {
                foreach (var p in Parts)
                {
                    p.Dispose();
                }
            }
            Parts = null;
        }
Example #36
0
        /// <summary>
        /// インデックスバッファの格納
        /// </summary>
        /// <param name="device">GraphicsDevice</param>
        private void InitIndexBuffer(Dx11.Device device)
        {
            int counter = 0;

            foreach (int[] meshes in Cnv.meshSection.meshList.mesh)
            {
                Console.WriteLine("index:" + counter);
                if (meshes.Length == VTXNUM_SQUARE)
                {
                    Console.WriteLine("SQUARE:1 " + meshes[0] + ", " + meshes[1] + ", " + meshes[3]);
                    Console.WriteLine("SQUARE:2 " + meshes[1] + ", " + meshes[2] + ", " + meshes[3]);

                    //四角形を2つに分割してインデックスバッファに格納
                    indices.Add((uint)meshes[0]);
                    indices.Add((uint)meshes[1]);
                    indices.Add((uint)meshes[3]);

                    indices.Add((uint)meshes[1]);
                    indices.Add((uint)meshes[2]);
                    indices.Add((uint)meshes[3]);
                }
                else
                {
                    Console.WriteLine("TRIANGLE:1 " + meshes[0] + ", " + meshes[1] + ", " + meshes[2]);
                    //三角形なのでそのままインデックスバッファに格納
                    indices.Add((uint)meshes[0]);
                    indices.Add((uint)meshes[1]);
                    indices.Add((uint)meshes[2]);
                }
                counter++;
            }
            indexBuffer = MyDirectXHelper.CreateIndexBuffer(device, indices.ToArray());
        }
Example #37
0
        protected void SetVertexBuffer <V>(IVertexParser <V> vertexParser) where V : struct
        {
            numVertices  = vertexParser.VertexCount;
            vertexStride = Marshal.SizeOf(typeof(V));
            int SizeOfVertexBufferInBytes = numVertices * vertexStride;

            vertices = new DataStream(SizeOfVertexBufferInBytes, true, true);
            for (int i = 0; i < numVertices; i++)
            {
                vertexParser.FillVertex(i, out V vertex);
                vertices.Write(vertex);
            }

            vertices.Position = 0;

            boundingBox    = BoundingBox.FromPoints(vertices, numVertices, vertexStride);
            boundingSphere = BoundingSphere.FromBox(boundingBox);

            vertexBuffer = new Buffer(DeviceManager.Instance.device,
                                      vertices,
                                      SizeOfVertexBufferInBytes,
                                      ResourceUsage.Default,
                                      BindFlags.VertexBuffer,
                                      CpuAccessFlags.None,
                                      ResourceOptionFlags.None,
                                      0);
        }
Example #38
0
        public Quad(int startX,int endX, int startZ, int endZ, Base.Content.Terrain.Terrain terrain, RenderManager renderer)
        {
            _bounds = new QuadBounds
            {
                MinX = startX / terrain.PointsPerMeter,
                MaxX = endX / terrain.PointsPerMeter,
                MinZ = startZ / terrain.PointsPerMeter,
                MaxZ = endZ / terrain.PointsPerMeter,
                MinY = terrain.Height[0],
                MaxY = terrain.Height[0]
            };
            HorizontalCenter = new Vector2(Bounds.MinX + (Bounds.MaxX - Bounds.MinX) / 2, Bounds.MinZ + (Bounds.MaxZ - Bounds.MinZ) / 2);

            int verticesX = endX - startX + 1;
            int verticesZ = endZ - startZ + 1;

            var dataStream = new DataStream(32 * verticesX * verticesZ, true, true);

            for (int i = 0; i < verticesX; i++)
            {
                for (int j = 0; j < verticesZ; j++)
                {
                    //Position
                    int xindex = Math.Min(i + startX, terrain.PointsX - 1);//Clamp to arraybounds if neccessary
                    int zindex = Math.Min(j + startZ, terrain.PointsZ - 1);//(Quadsize needs to be consistent for sharing IndexBuffers)
                    float x = xindex / terrain.PointsPerMeter;
                    float z = zindex / terrain.PointsPerMeter;
                    float y = terrain.Height[xindex * terrain.PointsZ + zindex];
                    dataStream.Write(new Vector3(x, y, z));

                    //Normal
                    float deltax = (terrain.Height[(xindex < terrain.PointsX - 1 ? xindex + 1 : xindex) * terrain.PointsZ + zindex]
                        - terrain.Height[(xindex != 0 ? xindex - 1 : xindex) * terrain.PointsZ + zindex]);

                    float deltaz = (terrain.Height[xindex * terrain.PointsZ + (zindex < terrain.PointsZ - 1 ? zindex + 1 : zindex)]
                        - terrain.Height[xindex * terrain.PointsZ + (zindex != 0 ? zindex - 1 : zindex)]);
                    if (xindex == 0 || xindex == terrain.PointsX - 1)
                        deltax *= 2;
                    if (zindex == 0 || zindex == terrain.PointsZ - 1)
                        deltaz *= 2;
                    var normal = new Vector3(-deltax, 2 / terrain.PointsPerMeter, deltaz);
                    normal.Normalize();
                    dataStream.Write(normal);

                    //TextureCoordinates
                    dataStream.Write(new Vector2(x / terrain.PointsX, z / terrain.PointsZ));

                    //Boundingbox-Params
                    if (y < _bounds.MinY)
                        _bounds.MinY = y;
                    if (y > _bounds.MaxY)
                        _bounds.MaxY = y;
                }
            }

            dataStream.Position = 0;
            VBuffer = new Buffer(renderer.D3DDevice, dataStream, 32 * verticesX * verticesZ, ResourceUsage.Default, BindFlags.VertexBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0);
            VertexBuffer = new VertexBufferBinding(VBuffer, 32, 0);
            dataStream.Dispose();
        }
        public override RenderableLightPrimitive GetRenderablePrimitive()
        {
            LightShader shader = new LightShader(Renderer);

            using (ShaderBytecode bytecode = new ShaderBytecode(new DataStream(File.ReadAllBytes("Shaders\\DeferredPointLight.vs"), true, false)))
            {
                shader.VertexShader = new VertexShader(Renderer.Device, bytecode);
                shader.InputLayout = new InputLayout(Renderer.Device, bytecode, new[]
                {
                    new InputElement("Position", 0, Format.R32G32B32_Float, sizeof(float) * 0, 0),
                });
            }
            using (ShaderBytecode bytecode = new ShaderBytecode(new DataStream(File.ReadAllBytes("Shaders\\DeferredPointLightShadowless.ps"), true, false)))
            {
                shader.PixelShader = new PixelShader(Renderer.Device, bytecode);
            }
            using (ShaderBytecode bytecode = new ShaderBytecode(new DataStream(File.ReadAllBytes("Shaders\\DeferredPointLightShadowless.ps"), true, false)))
            {
                shader.PixelShaderShadowless = new PixelShader(Renderer.Device, bytecode);
            }
            shader.Topology = PrimitiveTopology.TriangleList;

            ConstantBufferWrapper MatricesCBuffer = new ConstantBufferWrapper(Renderer, sizeof(float) * 32, ShaderType.VertexShader, 0);
            ConstantBufferWrapper LightCBuffer = new ConstantBufferWrapper(Renderer, sizeof(float) * 64, ShaderType.PixelShader, 0);
            ConstantBufferWrapper ShadowCBuffer = new ConstantBufferWrapper(Renderer, sizeof(float) * 16 * 4, ShaderType.PixelShader, 1);
            MatricesCBuffer.Semantics.Add(Semantic.WorldViewProj);
            MatricesCBuffer.Semantics.Add(Semantic.World);
            LightCBuffer.Semantics.Add(Semantic.View);
            LightCBuffer.Semantics.Add(Semantic.ViewInverse);
            LightCBuffer.Semantics.Add(Semantic.ViewProjInverse);
            LightCBuffer.Semantics.Add(Semantic.CameraPosition);
            shader.ConstantBuffers.Add(MatricesCBuffer);
            shader.ConstantBuffers.Add(LightCBuffer);
            shader.ConstantBuffers.Add(ShadowCBuffer);

            GeometricPrimitive prim = new SpherePrimitive(Renderer, 1, 16);

            DataStream str = new DataStream(prim.GeometryData.Positions, true, false);
            Buffer vertexBuffer = new Buffer(Renderer.Device, str, new BufferDescription()
            {
                SizeInBytes = (int)str.Length,
                BindFlags = BindFlags.VertexBuffer,
                StructureByteStride = 3 * sizeof(float),
                CpuAccessFlags = CpuAccessFlags.None,
                OptionFlags = ResourceOptionFlags.None,
                Usage = ResourceUsage.Default,
            });
            int vertexCount = prim.GeometryData.VertexCount;

            DataStream IndicesStream = new DataStream(prim.GeometryData.Indices.ToArray(), true, true);

            int indexCount = prim.GeometryData.IndexCount;
            Buffer indexBuffer = new Buffer(Renderer.Device, IndicesStream, sizeof(ushort) * indexCount,
                ResourceUsage.Default, BindFlags.IndexBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, sizeof(ushort));

            prim.Dispose();

            return new RenderableLightPrimitive(shader, vertexBuffer, vertexCount, indexBuffer, indexCount);
        }
Example #40
0
 // Functions
 public GPUBufferObject()
 {
     m_Size = -1;
     m_BufferObject = null;
     m_ShaderResourceView = null;
     m_UnorderedAccessView = null;
     m_StagingBufferObject = null;
     m_StagingCountBufferObject = null;
 }
 protected override void Dispose(bool disposable)
 {
     Contract.Ensures(transparencyConstantBuffer == null, "This function must dispose of the lightConstantBuffer variable.");
     if (transparencyConstantBuffer != null)
     {
         transparencyConstantBuffer.Dispose();
         transparencyConstantBuffer = null;
     }
     base.Dispose(disposable);
 }
 public DXGraphicsRenderer(Game pmGame)
 {
     dxg=	new DirectXGraphics();
     settings=	new GraphicsSettings();
     game=	pmGame;
     clearColor=	new Color("royalblue");
     vbuffer=	null;
     ibuffer=	null;
     renderType=	RenderType.FILL;
     layout=	null;
 }
Example #43
0
        public DX11VertexGeometry LineStrip3d(List<Vector3> points, bool loop)
        {
            DX11VertexGeometry geom = new DX11VertexGeometry(context);

            int vcount = loop ? points.Count + 1 : points.Count;

            Pos3Tex2Vertex[] verts = new Pos3Tex2Vertex[vcount];

            float inc = loop ? 1.0f / (float)vcount : 1.0f / ((float)vcount + 1.0f);

            float curr = 0.0f;
            
                
            for (int i = 0; i < points.Count; i++)
            {
                verts[i].Position = points[i];
                verts[i].TexCoords.X = curr;
                curr += inc;
            }

            if (loop)
            {
                verts[points.Count].Position = points[0];
                verts[points.Count].TexCoords.X = 1.0f;
            }


            DataStream ds = new DataStream(vcount * Pos3Tex2Vertex.VertexSize, true, true);
            ds.Position = 0;
            ds.WriteRange(verts);
            ds.Position = 0;

            var vbuffer = new SlimDX.Direct3D11.Buffer(context.Device, ds, new BufferDescription()
            {
                BindFlags = BindFlags.VertexBuffer,
                CpuAccessFlags = CpuAccessFlags.None,
                OptionFlags = ResourceOptionFlags.None,
                SizeInBytes = (int)ds.Length,
                Usage = ResourceUsage.Default
            });

            ds.Dispose();

            geom.VertexBuffer = vbuffer;
            geom.InputLayout = Pos3Tex2Vertex.Layout;
            geom.Topology = PrimitiveTopology.LineStrip;
            geom.VerticesCount = vcount;
            geom.VertexSize = Pos3Tex2Vertex.VertexSize;

            geom.HasBoundingBox = false;

            return geom;
        }
 /// <summary>
 /// Releases unmanaged and - optionally - managed resources.
 /// </summary>
 /// <param name="disposable"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
 protected override void Dispose(bool disposable)
 {
     Contract.Ensures(matrixConstantBuffer == null, "matrixConstantBuffer must be null after this method executes.");
     if (disposable)
     {
         if (matrixConstantBuffer != null)
         {
             matrixConstantBuffer.Dispose();
             matrixConstantBuffer = null;
         }
     }
     base.Dispose(disposable);
 }
Example #45
0
        internal override void Draw(SlimDX.Direct3D11.DeviceContext context)
        {
            Effect effect;
            using (ShaderBytecode byteCode = ShaderBytecode.CompileFromFile("Graphics/Effects/default.fx", "bidon", "fx_5_0", ShaderFlags.OptimizationLevel3, EffectFlags.None))
            {
                effect = new Effect(context.Device, byteCode);
            }
            var technique = effect.GetTechniqueByIndex(1);
            var pass = technique.GetPassByIndex(0);
            InputLayout inputLayout = new InputLayout(context.Device, pass.Description.Signature, new[] {
                new InputElement("POSITION", 0, SlimDX.DXGI.Format.R32G32B32_Float, 0),
                new InputElement("COLOR", 0, SlimDX.DXGI.Format.R8G8B8A8_UNorm, InputElement.AppendAligned, 0)
            });

            DataStream vertices = new DataStream((Vector3.SizeInBytes + 4) * 6, true, true);
            vertices.Write(new ColoredVertex(new Vector3(1.0f, 1.0f, 0.0f), new Color4(1.0f, 0.0f, 0.0f, 0.0f).ToArgb()));
            vertices.Write(new ColoredVertex(new Vector3(-1.0f, 1.0f, 0.0f), new Color4(1.0f, 0.0f, 0.0f, 0.0f).ToArgb()));
            vertices.Write(new ColoredVertex(new Vector3(-1.0f, -1.0f, 0.0f), new Color4(1.0f, 0.0f, 0.0f, 0.0f).ToArgb()));
            vertices.Write(new ColoredVertex(new Vector3(-1.0f, -1.0f, 0.0f), new Color4(1.0f, 0.0f, 0.0f, 0.0f).ToArgb()));
            vertices.Write(new ColoredVertex(new Vector3(1.0f, 1.0f, 0.0f), new Color4(1.0f, 0.0f, 0.0f, 0.0f).ToArgb()));
            vertices.Write(new ColoredVertex(new Vector3(1.0f, -1.0f, 0.0f), new Color4(1.0f, 0.0f, 0.0f, 0.0f).ToArgb()));

            vertices.Position = 0;
            BufferDescription bd = new BufferDescription()
            {
                Usage = ResourceUsage.Default,
                SizeInBytes = 16 * 6,
                BindFlags = BindFlags.VertexBuffer,
                CpuAccessFlags = CpuAccessFlags.None
            };

            var vertexBuffer = new SlimDX.Direct3D11.Buffer(context.Device, vertices, bd);

            context.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(vertexBuffer, 16, 0));
            //context.InputAssembler.SetIndexBuffer(indices, Format.R16_UInt, 0);

            /* scale * rotation * translation */
            Matrix worldMatrix = Matrix.Scaling(Scale) * Matrix.RotationYawPitchRoll(Rotation.Y, Rotation.X, Rotation.Z) * Matrix.Translation(Position);

            Matrix viewMatrix = Camera.ViewMatrix;

            Matrix projectionMatrix = Camera.ProjectionMatrix;

            effect.GetVariableByName("finalMatrix").AsMatrix().SetMatrix(worldMatrix * viewMatrix * projectionMatrix);

            context.InputAssembler.InputLayout = inputLayout;
            context.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleStrip;

            pass.Apply(context);
            context.Draw(6, 0);
        }
Example #46
0
 protected override void Dispose(bool managed)
 {
     Contract.Ensures(fogConstantBuffer == null, "fogConstantBuffer must be null after this method executes.");
     if (managed)
     {
         //Check if fogConstantBuffer still exists and if so, dispose it and set it to null.
         if (fogConstantBuffer != null)
         {
             fogConstantBuffer.Dispose();
             fogConstantBuffer = null;
         }
     }
     base.Dispose(managed);
 }
Example #47
0
        public DX11RawBuffer(DX11RenderContext context, Buffer buffer)
        {
            this.Size = buffer.Description.SizeInBytes;
            this.Buffer = buffer;

            ShaderResourceViewDescription srvd = new ShaderResourceViewDescription()
            {
                Format = SlimDX.DXGI.Format.R32_Typeless,
                Dimension = ShaderResourceViewDimension.ExtendedBuffer,
                Flags = ShaderResourceViewExtendedBufferFlags.RawData,
                ElementCount = this.Size / 4
            };
            this.SRV = new ShaderResourceView(context.Device, this.Buffer, srvd);
        }
Example #48
0
        public SlimDXBuffer11 CreateBuffer(SCreateBufferCmd cmd)
        {
            var newBuffer = new SlimDX.Direct3D11.Buffer(Engine.Global.Device3d.GetDevice(), new BufferDescription()
            {
                BindFlags = cmd.BufferBindFlags,
                CpuAccessFlags = CpuAccessFlags.None,
                OptionFlags = ResourceOptionFlags.None,
                SizeInBytes = cmd.SizeInBytes,
                Usage = ResourceUsage.Default
            });

            m_BufferList.Add(cmd.Name, newBuffer);

            return newBuffer;
        }
Example #49
0
    public BoxApp(IntPtr hInstance) : base(hInstance) {
        _boxIB = null;
        _boxVB = null;
        _fx = null;
        _tech = null;
        _fxWVP = null;
        _inputLayout = null;
        _theta = 1.5f * MathF.PI;
        _phi = 0.25f * MathF.PI;
        _radius = 5.0f;

        MainWindowCaption = "Box Demo";
        _lastMousePos = new Point(0, 0);
        _world = Matrix.Identity;
        _view = Matrix.Identity;
        _proj = Matrix.Identity;
    }
 public ConstantBufferWrapper(Renderer Renderer, int SizeInBytes, ShaderType ShaderType, int slot)
 {
     this.Renderer = Renderer;
     this.SizeInBytes = SizeInBytes;
     this.ShaderType = ShaderType;
     this.ResourceSlot = slot;
     CBuffer = new Buffer(Renderer.Device, new BufferDescription()
     {
         Usage = ResourceUsage.Dynamic,
         BindFlags = BindFlags.ConstantBuffer,
         CpuAccessFlags = CpuAccessFlags.Write,
         OptionFlags = ResourceOptionFlags.None,
         SizeInBytes = SizeInBytes,
         StructureByteStride = 0,
     });
     this.Semantics = new List<Semantic>();
 }
        public TestTriangle(SlimDX.Direct3D11.Device Device)
        {
            using (ShaderBytecode bytecode = ShaderBytecode.CompileFromFile(@"R:\Users\Rox Cox\Documents\Visual Studio 2013\Projects\LightingEngine_v2\LightingEngine_v2\test.fx", "fx_5_0"))
            {
                try
                {
                    SampleEffect = new Effect(Device, bytecode);
                }
                catch (Exception e)
                {
                    throw e;
                }
            }
            using (ShaderBytecode bytecode = ShaderBytecode.CompileFromFile(@"R:\Users\Rox Cox\Documents\Visual Studio 2013\Projects\LightingEngine_v2\LightingEngine_v2\test.fx", "VSTri", "vs_5_0", ShaderFlags.None, EffectFlags.None))
            {
                VS = new VertexShader(Device, bytecode);
            }
            EffectTechnique technique = SampleEffect.GetTechniqueByIndex(0);
            EffectPass pass = technique.GetPassByIndex(0);
            SampleLayout = new InputLayout(Device, pass.Description.Signature, new[] {
                new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0),
                new InputElement("COLOR", 0, Format.R32G32B32A32_Float, 16, 0)
            });

            SampleStream = new DataStream(4 * 32, true, true);
            SampleStream.WriteRange(new[] {
                new Vector4(1.0f, 1.0f, 0.5f, 1.0f), new Vector4(0.0f, 0.8f, 1.0f, 1.0f),
                new Vector4(1.0f, -1.0f, 0.5f, 1.0f), new Vector4(0.3f, 1.0f, 0.3f, 1.0f),
                new Vector4(-1.0f, -1.0f, 0.5f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f),
                new Vector4(-1.0f, 1.0f, 0.5f, 1.0f), new Vector4(0.0f, 0.8f, 1.0f, 1.0f),
            });
            SampleStream.Position = 0;

            SampleVertices = new SlimDX.Direct3D11.Buffer(Device, SampleStream, new BufferDescription()
            {
                BindFlags = BindFlags.VertexBuffer,
                CpuAccessFlags = CpuAccessFlags.None,
                OptionFlags = ResourceOptionFlags.None,
                SizeInBytes = 3 * 32,
                Usage = ResourceUsage.Default
            });
        }
Example #52
0
        public BoxApp(IntPtr hInstance)
            : base(hInstance) {
            _ib = null;
            _vb = null;
            _fx = null;
            _tech = null;
            _fxWVP = null;
            _inputLayout = null;
            _theta = 1.5f * MathF.PI;
            _phi = 0.1f * MathF.PI;
            _radius = 200.0f;

            MainWindowCaption = "Hills Demo";
            _lastMousePos = new Point(0, 0);
            _world = Matrix.Identity;
            _view = Matrix.Identity;
            _proj = Matrix.Identity;

            _gridIndexCount = 0;
        }
Example #53
0
		public ThreadView(Connection conn, Scene scene)
		{
			m_connection = conn;
			m_device = scene.Device;
			m_context = m_device.ImmediateContext;

			var bytecode = ShaderBytecode.CompileFromFile(RenderSupport.ContentPath + "\\Universe.fx", "fx_5_0", ShaderFlags.None, EffectFlags.None);
			m_effect = new Effect(m_device, bytecode);
			var pass = m_effect.GetTechniqueByIndex(0).GetPassByIndex(0);
			m_layout = new InputLayout(m_device, pass.Description.Signature, QuadVertex.Elements);

			m_vertices = new SlimDX.Direct3D11.Buffer(m_device, new BufferDescription()
			{
				CpuAccessFlags = CpuAccessFlags.Write,
				BindFlags = BindFlags.VertexBuffer,
				SizeInBytes = 6 * MaxQuads * QuadVertex.SizeBytes,
				Usage = ResourceUsage.Dynamic
			});

			m_texture = Texture2D.FromFile(m_device, RenderSupport.ContentPath + "\\stars.png");
			m_textureView = new ShaderResourceView(m_device, m_texture);
		}
Example #54
0
        public SkullDemo(IntPtr hInstance) : base(hInstance) {
            _vb = null;
            _ib = null;
            _fx = null;
            _tech = null;
            _fxWVP = null;
            _inputLayout = null;
            _wireframeRS = null;
            _skullIndexCount = 0;
            _theta = 1.5f*MathF.PI;
            _phi = 0.1f*MathF.PI;
            _radius = 20.0f;

            MainWindowCaption = "Skull Demo";

            _lastMousePos = new Point(0,0);

            _view = Matrix.Identity;
            _proj = Matrix.Identity;
            _skullWorld = Matrix.Translation(0.0f, -2.0f, 0.0f);

        }
Example #55
0
        /// <summary>
        /// Default constructor.
        /// </summary>
        /// <param name="graphicsDevice">Virtual adapter used to perform rendering.</param>
        /// <param name="width">Screen space width.</param>
        /// <param name="height">Screen space height.</param>
        public PostProcess(Device graphicsDevice, int width, int height)
        {
            this.graphicsDevice = graphicsDevice;

            renderTargets = new List<RenderTarget>();
            effects = new Dictionary<string, ComputeShader>();

            AddEffect("DownSample4x");
            AddEffect("BlurV");
            AddEffect("BlurH");
            AddEffect("BrightPass");
            AddEffect("UpSample4x");
            AddEffect("UpSample4xCombine");
            AddEffect("AddFogTexture");

            AddRenderTarget(width / 4, height / 4, Format.R8G8B8A8_UNorm);
            AddRenderTarget(width / 16, height / 16, Format.R8G8B8A8_UNorm);
            AddRenderTarget(width / 16, height / 16, Format.R8G8B8A8_UNorm);
            AddRenderTarget(width, height, Format.R8G8B8A8_UNorm);
            AddRenderTarget(width, height, Format.R8G8B8A8_UNorm);
            AddRenderTarget(width, height, Format.R8G8B8A8_UNorm);
            AddRenderTarget(width, height, Format.R8G8B8A8_UNorm);

            BufferDescription description = new BufferDescription()
            {
                BindFlags = BindFlags.ConstantBuffer,
                CpuAccessFlags = CpuAccessFlags.Write,
                OptionFlags = ResourceOptionFlags.None,
                SizeInBytes = 2 * Marshal.SizeOf(typeof(Vector4)),
                StructureByteStride = 2 * Marshal.SizeOf(typeof(Vector4)),
                Usage = ResourceUsage.Dynamic
            };

            constantBuffer = new Buffer(graphicsDevice, description);

            Settings.BloomSettings = new Vector4(0.08f, 0.18f, 0.8f, 1);
        }
        public SlimDX.Direct3D11.Buffer GetVertexBuffer()
        {
            // dynamically create buffer
            if (m_DeviceBuffer == null)
            {
                ResourceUsage resourceUsage = ResourceUsage.Default;
                CpuAccessFlags cpuAccessFlags = CpuAccessFlags.None;

                if(m_Usage == Type.DYNAMIC )
                {
                    resourceUsage = ResourceUsage.Dynamic;
                    cpuAccessFlags = CpuAccessFlags.Write;
                }

                BufferDescription desc = new BufferDescription()
                {
                    BindFlags = BindFlags.VertexBuffer,
                    CpuAccessFlags = cpuAccessFlags,
                    OptionFlags = ResourceOptionFlags.None,
                    SizeInBytes = (int)m_RawData.Length,
                    Usage = resourceUsage
                };

                if (m_Usage == Type.DYNAMIC)
                {
                    m_DeviceBuffer = new SlimDX.Direct3D11.Buffer(m_D3dDevice, desc);
                }
                else
                {
                    DataStream dataStream = new DataStream(m_RawData.ToArray(), true, true);
                    m_DeviceBuffer = new SlimDX.Direct3D11.Buffer(m_D3dDevice, dataStream, desc);
                    dataStream.Dispose();
                }
            }

            return m_DeviceBuffer;
        }
Example #57
0
        public LightingDemo(IntPtr hInstance) : base(hInstance) {
            _landVB = null;
            _landIB = null;
            _waveVB = null;
            _waveIB = null;
            _fx = null;
            _tech = null;
            _fxWorld = null;
            _fxWIT = null;
            _fxEyePosW = null;
            _fxDirLight = null;
            _fxPointLight = null;
            _fxSpotLight = null;
            _fxMaterial = null;
            _fxWVP = null;
            _inputLayout = null;
            _eyePosW = new Vector3();
            _theta = 1.5f*MathF.PI;
            _phi = 0.1f*MathF.PI;
            _radius = 80.0f;

            MainWindowCaption = "Lighting Demo";

            _lastMousePos = new Point();

            _landWorld = Matrix.Identity;
            _wavesWorld = Matrix.Translation(0, -3.0f, 0);
            _view = Matrix.Identity;
            _proj = Matrix.Identity;

            _dirLight = new DirectionalLight {
                Ambient = new Color4(0.2f, 0.2f, 0.2f),
                Diffuse = new Color4(0.5f, 0.5f, 0.5f),
                Specular = new Color4(0.5f, 0.5f, 0.5f),
                Direction = new Vector3(0.57735f, -0.57735f, 0.57735f)
            };

            _pointLight = new PointLight {
                Ambient = new Color4(0.3f, 0.3f, 0.3f),
                Diffuse = new Color4(0.7f, 0.7f, 0.7f),
                Specular = new Color4(0.7f, 0.7f, 0.7f),
                Attenuation = new Vector3(0.0f, 0.1f, 0.0f),
                Range = 25.0f
            };
            _spotLight = new SpotLight {
                Ambient = new Color4(0,0,0),
                Diffuse = new Color4(1.0f, 1.0f, 0.0f),
                Specular = Color.White,
                Attenuation = new Vector3(1.0f, 0.0f, 0.0f),
                Spot = 96.0f,
                Range = 10000.0f
            };

            // NOTE: must put alpha (spec power) first, rather than last as in book code
            _landMaterial = new Material {
                Ambient = new Color4(1.0f, 0.48f, 0.77f, 0.46f),
                Diffuse = new Color4(1.0f, 0.48f, 0.77f, 0.46f),
                Specular = new Color4(16.0f, 0.2f, 0.2f, 0.2f)
            };
            _wavesMaterial = new Material {
                Ambient =  new Color4(0.137f, 0.42f, 0.556f),
                Diffuse = new Color4(0.137f, 0.42f, 0.556f),
                Specular = new Color4(96.0f, 0.8f, 0.8f, 0.8f)
            };

        }
Example #58
0
        private void BuildWaveGeometryBuffers() {
            var vbd = new BufferDescription(VertexPN.Stride * _waves.VertexCount, ResourceUsage.Dynamic, BindFlags.VertexBuffer, CpuAccessFlags.Write, ResourceOptionFlags.None, 0);
            _waveVB = new Buffer(Device, vbd);

            var indices = new List<int>();
            var m = _waves.RowCount;
            var n = _waves.ColumnCount;
            for (int i = 0; i < m - 1; i++) {
                for (int j = 0; j < n - 1; j++) {
                    indices.Add(i * n + j);
                    indices.Add(i * n + j + 1);
                    indices.Add((i + 1) * n + j);

                    indices.Add((i + 1) * n + j);
                    indices.Add(i * n + j + 1);
                    indices.Add((i + 1) * n + j + 1);
                }
            }
            var ibd = new BufferDescription(sizeof(int) * indices.Count, ResourceUsage.Immutable, BindFlags.IndexBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0);
            _waveIB = new Buffer(Device, new DataStream(indices.ToArray(), false, false), ibd);
        }
Example #59
0
        private void BuildLandGeometryBuffers() {
            var grid = GeometryGenerator.CreateGrid(160.0f, 160.0f, 50, 50);
            _landIndexCount = grid.Indices.Count;

            var vertices = new List<VertexPN>();
            foreach (var v in grid.Vertices) {
                var p = new Vector3(v.Position.X, GetHillHeight(v.Position.X, v.Position.Z), v.Position.Z);
                var n = GetHillNormal(p.X, p.Z);
                vertices.Add(new VertexPN(p,n));
            }
            var vbd = new BufferDescription(VertexPN.Stride * vertices.Count, ResourceUsage.Immutable, BindFlags.VertexBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0);
            _landVB = new Buffer(Device, new DataStream(vertices.ToArray(), false, false), vbd);

            var ibd = new BufferDescription(sizeof(int) * grid.Indices.Count, ResourceUsage.Immutable, BindFlags.IndexBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0);
            _landIB = new Buffer(Device, new DataStream(grid.Indices.ToArray(), false, false), ibd);
        }
Example #60
0
        public void Update(IPluginIO pin, DX11RenderContext context)
        {
            if (this.FInvalidate)
            {
                if (this.FOutput[0].Contains(context)) { this.FOutput[0].Dispose(context); }

                DX11VertexGeometry geom = new DX11VertexGeometry(context);
                geom.InputLayout = this.inputlayout;
                geom.VertexSize = this.vertexsize;

                try
                {
                    this.FStream.Position = 0;
                    var vertices = new SlimDX.Direct3D11.Buffer(context.Device, this.FStream, new BufferDescription()
                    {
                        BindFlags = BindFlags.VertexBuffer,
                        CpuAccessFlags = CpuAccessFlags.None,
                        OptionFlags = ResourceOptionFlags.None,
                        SizeInBytes = (int)this.FStream.Length,
                        Usage = ResourceUsage.Default
                    });

                    geom.VerticesCount = this.FInVerticesCount[0];
                    geom.VertexBuffer = vertices;
                    geom.Topology = this.FInTopology[0];
                    geom.HasBoundingBox = false;

                    /*if (geom.Topology == PrimitiveTopology.LineListWithAdjacency)
                    {
                        geom.VerticesCount /= 2;
                    }*/

                    this.FOutput[0][context] = geom;
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }
        }