Example #1
0
 private void UpdateUv()
 {
     for (int i = 0; i < _vertices.Length; i++)
     {
         _vertices[i].UV = GetTexCoord(_uV, i, _rotation);
     }
     _vertexBuffer.Dispose();
     SetVertexBuffer(_vertices);
 }
        } // AddLine(startPoint, endPoint, color)

        private void initialize(Device device)
        {
            if (vertexBuffer != null)
            {
                vertexBuffer.Dispose();
            }

            var bufferDesc = new BufferDescription(VertexPositionColor.SizeInBytes * lineVertices.Length,
                                                   ResourceUsage.Dynamic, BindFlags.VertexBuffer, CpuAccessFlags.Write,
                                                   ResourceOptionFlags.None, VertexPositionColor.SizeInBytes);

            vertexBuffer = new Buffer(device, bufferDesc);
        }
Example #3
0
        public void Dispose()
        {
            if (_shaderEffect != null)
            {
                _shaderEffect.Dispose();
            }
            if (_textureView != null)
            {
                _textureView.Dispose();
            }

            if (_indexBuffer != null)
            {
                _indexBuffer.Dispose();
            }
            if (_vertexBuffer != null)
            {
                _vertexBuffer.Dispose();
            }
            if (_accIndexBuffer != null)
            {
                _accIndexBuffer.Dispose();
            }
            if (_valencePrefixBuffer != null)
            {
                _valencePrefixBuffer.Dispose();
            }

            if (_valencePrefixView != null)
            {
                _valencePrefixView.Dispose();
            }
        }
            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 #5
0
 public void Unload()
 {
     vertexLayout.Dispose();
     vertexBuffer.Dispose();
     indexBuffer.Dispose();
     textureManager.Dispose();
 }
        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;
        }
 public void Dispose()
 {
     VertexBuffer.Dispose();
     IndexBuffer.Dispose();
     VertexBuffer = null;
     IndexBuffer  = null;
 }
Example #8
0
 private void ReleaseResources()
 {
     layout.Dispose();
     effect.Dispose();
     indicesb1.Dispose();
     indicesb2.Dispose();
 }
Example #9
0
 /// <summary>
 /// Gibt die Resourcen der Instanz frei.
 /// </summary>
 /// <param name="disposing">
 /// true, um managed Resourcen freizugeben; andernfalls false.
 /// </param>
 protected virtual void Dispose(bool disposing)
 {
     if (!disposed)
     {
         // Merken, daß die Instanz freigegeben wurde.
         disposed = true;
         // Managed Resourcen freigeben.
         if (disposing)
         {
             if (vertexBuffer != null)
             {
                 vertexBuffer.Dispose();
             }
             if (indexBuffer != null)
             {
                 indexBuffer.Dispose();
             }
             if (inputLayout != null)
             {
                 inputLayout.Dispose();
             }
         }
         // Hier Unmanaged Resourcen freigeben.
     }
 }
Example #10
0
 protected override void DisposeResource()
 {
     mUnorderedAccessView?.Dispose();
     mResourceView?.Dispose();
     mHardwareBuffer?.Dispose();
     mSwapBuffer?.Dispose();
 }
Example #11
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 #12
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);
        }
Example #13
0
 /// <summary>
 /// 廃棄
 /// </summary>
 public void Dispose()
 {
     shader_.Dispose();
     if (constantBuffer_ != null)
     {
         constantBuffer_.Dispose();
     }
 }
Example #14
0
 public void Dispose()
 {
     _quadVertices.Dispose();
     _layout.Dispose();
     _renderTexture.Dispose();
     _srv.Dispose();
     UAV.Dispose();
     _effect.Dispose();
 }
Example #15
0
 public void Dispose()
 {
     inputPS.Dispose();
     inputVS.Dispose();
     miscInfoBuffer.Dispose();
     strokeInfoBuffer.Dispose();
     quad.Dispose();
     bitmap.Dispose();
 }
Example #16
0
 public void Draw()
 {
     if (VertexCount > 0)
     {
         SlimDX.Direct3D11.Buffer vertices = GetDrawBuffer();
         DrawBuffer(vertices);
         vertices.Dispose();
     }
     Reset();
 }
Example #17
0
        public void Dispose()
        {
            if (_constBuffer != null)
            {
                _constBuffer.Dispose();
                _constBuffer = null;
            }

            _device = null;
        }
Example #18
0
        /// <summary>
        /// Converts mesh to DX-buffers.
        /// </summary>
        private static void MeshToBuffers(Device device,
                                          Mesh mesh,
                                          out SlimDX.Direct3D11.Buffer vertices,
                                          out SlimDX.Direct3D11.Buffer indices)
        {
            SlimDX.DataStream dsVertices = new SlimDX.DataStream(mesh.Vertices.Length * 6 * sizeof(float), true, true);
            SlimDX.DataStream dsIndices  = new SlimDX.DataStream(mesh.Indices.Length * 3 * sizeof(int), true, true);
            vertices = null;
            indices  = null;

            try
            {
                foreach (Vertex v in mesh.Vertices)
                {
                    v.WriteTo(dsVertices);
                }
                dsVertices.Position = 0;
                BufferDescription bdVertices = new BufferDescription();
                bdVertices.BindFlags      = BindFlags.VertexBuffer;
                bdVertices.CpuAccessFlags = CpuAccessFlags.None;
                bdVertices.OptionFlags    = ResourceOptionFlags.None;
                bdVertices.SizeInBytes    = mesh.Vertices.Length * 6 * sizeof(float);
                bdVertices.Usage          = ResourceUsage.Default;
                vertices = new SlimDX.Direct3D11.Buffer(device, dsVertices, bdVertices);

                dsIndices.WriteRange(mesh.Indices);
                dsIndices.Position = 0;
                BufferDescription bdIndices = new BufferDescription();
                bdIndices.BindFlags      = BindFlags.IndexBuffer;
                bdIndices.CpuAccessFlags = CpuAccessFlags.None;
                bdIndices.OptionFlags    = ResourceOptionFlags.None;
                bdIndices.SizeInBytes    = mesh.Indices.Length * 3 * sizeof(int);
                bdIndices.Usage          = ResourceUsage.Default;
                indices = new SlimDX.Direct3D11.Buffer(device, dsIndices, bdIndices);
            }
            catch (Exception)
            {
                if (vertices != null)
                {
                    vertices.Dispose();
                    vertices = null;
                }
                if (indices != null)
                {
                    indices.Dispose();
                    indices = null;
                }
                throw;
            }
            finally
            {
                dsVertices.Dispose();
                dsIndices.Dispose();
            }
        }
Example #19
0
 public void Dispose()
 {
     ScreenBufferShaderResource.Dispose();
     ScreenBufferShaderResourceTexture.Dispose();
     OffscreenRenderTargetTexture.Dispose();
     OffscreenRenderTarget.Dispose();
     CBuffer.Dispose();
     GoLVS.Dispose();
     GoLPS.Dispose();
     quad.Dispose();
 }
Example #20
0
 public void Dispose()
 {
     SetCull(true);
     device.ImmediateContext.Rasterizer.State?.Dispose();
     SetCull(false);
     device.ImmediateContext.Rasterizer.State?.Dispose();
     texture?.Dispose();
     index?.Dispose();
     Vertex?.Dispose();
     layout?.Dispose();
     effect?.Dispose();
 }
Example #21
0
        public override void Dispose()
        {
            vertexShader?.Dispose();
            pixelShader?.Dispose();
            inputSignature?.Dispose();
            layout?.Dispose();
            ConstantsBuffer?.Dispose();
            Texture?.Dispose();
            Sampler?.Dispose();

            base.Dispose();
        }
// ReSharper restore InconsistentNaming

        public void Dispose()
        {
            mTexCoordVertexBuffer.Dispose();
            mPositionVertexBuffer.Dispose();

            mRenderGreyScaleTexture3DInputLayout.Dispose();
            mRenderTexture3DInputLayout.Dispose();
            mRenderSolidInputLayout.Dispose();
            mRenderWireframeInputLayout.Dispose();

            mEffect.Dispose();
        }
Example #23
0
File: Mesh.cs Project: allvie/IS16
 internal void Dispose()
 {
     Disposed = true;
     if (!indexBuffer.Disposed)
     {
         indexBuffer.Dispose();
     }
     if (!vertexBuffer.Disposed)
     {
         vertexBuffer.Dispose();
     }
 }
 public void Destroy()
 {
     vertices.Close();
     vertexBuffer.Dispose();
     layout.Dispose();
     inputSignature.Dispose();
     vertexShader.Dispose();
     pixelShader.Dispose();
     renderTarget.Dispose();
     swapChain.Dispose();
     device.Dispose();
 }
Example #25
0
 public void Dispose()
 {
     Vb.Dispose();
     Ib.Dispose();
     if (Tex != null)
     {
         Tex.Dispose();
     }
     if (Blen != null)
     {
         Blen.Dispose();
     }
     //if (Rast != null) Rast.Dispose();
 }
Example #26
0
        /// <summary>
        /// Copies a range of data to an array
        /// </summary>
        /// <param name="index">Index from which to start copying</param>
        /// <param name="count">Number of elements to copy</param>
        /// <param name="array">Destination array to copy to</param>
        /// <param name="arrayIndex">Destination array index to copy to</param>
        public void CopyRangeTo(int index, int count, T[] array, int arrayIndex)
        {
            if (count == 0)
            {
                return;
            }

            if (count < 0)
            {
                throw new IndexOutOfRangeException();
            }
            if (index < 0 || index >= Count)
            {
                throw new IndexOutOfRangeException();
            }
            if (index + count < 0 || index + count > Count)
            {
                throw new IndexOutOfRangeException();
            }

            if (array == null)
            {
                throw new ArgumentNullException();
            }
            if (arrayIndex < 0 || arrayIndex >= array.Length)
            {
                throw new IndexOutOfRangeException();
            }
            if (arrayIndex + array.Length < 0 || arrayIndex + count > array.Length)
            {
                throw new IndexOutOfRangeException();
            }

            int    dataSize      = Marshal.SizeOf(typeof(T));
            Buffer stagingBuffer = new Buffer(context.Device, dataSize * count, ResourceUsage.Staging,
                                              BindFlags.None, CpuAccessFlags.Read, ResourceOptionFlags.None, 0);

            context.CopySubresourceRegion(buffer, 0,
                                          new ResourceRegion(dataSize * index, 0, 0, dataSize * (index + count), 1, 1),
                                          stagingBuffer, 0, 0, 0, 0);

            DataBox box = context.MapSubresource(stagingBuffer, MapMode.Read, MapFlags.None);

            box.Data.ReadRange <T>(array, arrayIndex, count);
            context.UnmapSubresource(stagingBuffer, 0);

            stagingBuffer.Dispose();
        }
Example #27
0
        private void Dispose(bool disposing)
        {
            if (!this.disposed)
            {
                if (disposing)
                {
                    //There are no managed resources to dispose
                }

                Fx.Dispose();
                InputLayout.Dispose();
                DSState.Dispose();

                VB.Dispose();
            }
            this.disposed = true;
        }
Example #28
0
        protected virtual void Dispose(bool disposing)
        {
            if (!isDisposed)
            {
                if (disposing)
                {
                }

                prefixScan.Dispose();
                computePositionWeightNoiseCube.Dispose();
                computeNormalAmbient.Dispose();
                computeMarchingCubesCases.Dispose();
                computeMarchingCubesVertices.Dispose();
                computePositionWeightNoiseCubeWarp.Dispose();
                computePositionWeightFormula.Dispose();
                constantBuffer.Dispose();
            }

            isDisposed = true;
        }
Example #29
0
        bool CreateInputBuffer(Device device, float diffTime)
        {
            List <Matrix> matrixArray = new List <Matrix>();

            for (int i = 0; i < statusArray.Count; i++)
            {
                float  speed = diffTime / (float)Math.Sqrt(statusArray[i].Length);
                Matrix lot   = Matrix.RotationAxis(statusArray[i].axis, speed);
                lot = Matrix.Multiply(statusArray[i].matrix, lot);

                statusArray[i].matrix = lot;
                matrixArray.Add(statusArray[i].matrix);
            }

            DataStream stream;

            try
            {
                if (inputBuffer != null)
                {
                    inputBuffer.Dispose();
                }
                stream      = new DataStream(matrixArray.ToArray(), true, true);
                inputBuffer = new SlimDX.Direct3D11.Buffer(
                    device,
                    stream,
                    new BufferDescription
                {
                    SizeInBytes = (int)stream.Length,
                    BindFlags   = BindFlags.ShaderResource,
                    OptionFlags = ResourceOptionFlags.DrawIndirect,
                }
                    );
                stream.Dispose();
            }
            catch (Exception e)
            {
                return(false);
            }
            return(true);
        }
Example #30
0
        public void Dispose()
        {
            if (mTexCoordVertexBuffer != null)
            {
                mTexCoordVertexBuffer.Dispose();
                mTexCoordVertexBuffer = null;
            }

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

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

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

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

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

            mEffect.Dispose();
        }
        public UnorderedAccessView PrefixSumArray(Buffer constantBuffer, UnorderedAccessView trisCountUAV)
        {
            int arrayLength = trisCountUAV.Description.ElementCount;
            int batchSize = trisCountUAV.Description.ElementCount / arrayLength;

            if (!IsPowerOfTwo(trisCountUAV.Description.ElementCount))
                throw new Exception("Input array length is not power of two.");

            Buffer buffer = new Buffer(graphicsDevice, new BufferDescription()
            {
                BindFlags = BindFlags.UnorderedAccess,
                CpuAccessFlags = CpuAccessFlags.None,
                OptionFlags = ResourceOptionFlags.StructuredBuffer,
                Usage = ResourceUsage.Default,
                SizeInBytes = Marshal.SizeOf(typeof(int)) * trisCountUAV.Description.ElementCount,
                StructureByteStride = Marshal.SizeOf(typeof(int))
            });

            UnorderedAccessView bufferUAV = new UnorderedAccessView(graphicsDevice, buffer);

            Buffer output = new Buffer(graphicsDevice, new BufferDescription()
            {
                BindFlags = BindFlags.UnorderedAccess,
                CpuAccessFlags = CpuAccessFlags.None,
                OptionFlags = ResourceOptionFlags.StructuredBuffer,
                Usage = ResourceUsage.Default,
                SizeInBytes = Marshal.SizeOf(typeof(int)) * trisCountUAV.Description.ElementCount,
                StructureByteStride = Marshal.SizeOf(typeof(int))
            });

            UnorderedAccessView outputUAV = new UnorderedAccessView(graphicsDevice, output);

            DirectComputeConstantBuffer constantBufferContainer = new DirectComputeConstantBuffer()
            {
                PrefixSize = 4 * threadBlockSize,
                PrefixN = (batchSize * arrayLength) / (4 * threadBlockSize),
                PrefixArrayLength = arrayLength / (4 * threadBlockSize)
            };

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

            Vector3 gridDim = new Vector3((batchSize * arrayLength) / (4 * threadBlockSize), 1, 1);
            Vector3 gridDimShared2 = new Vector3((int)Math.Ceiling(((batchSize * arrayLength) / (4 * threadBlockSize)) / (double)threadBlockSize), 1, 1);

            graphicsDevice.ImmediateContext.ComputeShader.Set(computeScanExclusiveShared);
            graphicsDevice.ImmediateContext.ComputeShader.SetConstantBuffer(constantBuffer, 0);
            graphicsDevice.ImmediateContext.ComputeShader.SetUnorderedAccessView(trisCountUAV, 2);
            graphicsDevice.ImmediateContext.ComputeShader.SetUnorderedAccessView(outputUAV, 3);
            graphicsDevice.ImmediateContext.ComputeShader.SetUnorderedAccessView(bufferUAV, 4);

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

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

            graphicsDevice.ImmediateContext.ComputeShader.Set(computeUniformUpdate);

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

            buffer.Dispose();
            bufferUAV.Dispose();

            return outputUAV;
        }
Example #32
0
        static void Main()
        {
            var form = new RenderForm("SlimDX - MiniTri Direct3D 11 Sample");
            var desc = new SwapChainDescription()
            {
                BufferCount = 1,
                ModeDescription = new ModeDescription(form.ClientSize.Width, form.ClientSize.Height, new Rational(60, 1), Format.R8G8B8A8_UNorm),
                IsWindowed = true,
                OutputHandle = form.Handle,
                SampleDescription = new SampleDescription(1, 0),
                SwapEffect = SwapEffect.Discard,
                Usage = Usage.RenderTargetOutput
            };

            Device device;
            SwapChain swapChain;
            Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.Debug, desc, out device, out swapChain);

            device.Factory.SetWindowAssociation(form.Handle, WindowAssociationFlags.IgnoreAll);

            Texture2D backBuffer = Texture2D.FromSwapChain<Texture2D>(swapChain, 0);
            var renderView = new RenderTargetView(device, backBuffer);
            var bytecode = ShaderBytecode.CompileFromFile("MiniTri.fx", "fx_5_0", ShaderFlags.None, EffectFlags.None);
            var effect = new Effect(device, bytecode);
            var technique = effect.GetTechniqueByIndex(0);
            var pass = technique.GetPassByIndex(0);
            var layout = 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) 
            });

            var stream = new DataStream(3 * 32, true, true);
            stream.WriteRange(new[] {
                new Vector4(0.0f, 0.5f, 0.5f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f),
                new Vector4(0.5f, -0.5f, 0.5f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f),
                new Vector4(-0.5f, -0.5f, 0.5f, 1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f)
            });
            stream.Position = 0;

            var vertices = new SlimDX.Direct3D11.Buffer(device, stream, new BufferDescription()
            {
                BindFlags = BindFlags.VertexBuffer,
                CpuAccessFlags = CpuAccessFlags.None,
                OptionFlags = ResourceOptionFlags.None,
                SizeInBytes = 3 * 32,
                Usage = ResourceUsage.Default
            });
            stream.Dispose();

            device.ImmediateContext.OutputMerger.SetTargets(renderView);
            device.ImmediateContext.Rasterizer.SetViewports(new Viewport(0, 0, form.ClientSize.Width, form.ClientSize.Height, 0.0f, 1.0f));

            MessagePump.Run(form, () =>
            {
                device.ImmediateContext.ClearRenderTargetView(renderView, Color.Black);

                device.ImmediateContext.InputAssembler.InputLayout = layout;
                device.ImmediateContext.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList;
                device.ImmediateContext.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(vertices, 32, 0));

                for (int i = 0; i < technique.Description.PassCount; ++i)
                {
                    pass.Apply(device.ImmediateContext);
                    device.ImmediateContext.Draw(3, 0);
                }

                swapChain.Present(0, PresentFlags.None);
            });

            bytecode.Dispose();
            vertices.Dispose();
            layout.Dispose();
            effect.Dispose();
            renderView.Dispose();
            backBuffer.Dispose();
            device.Dispose();
            swapChain.Dispose();
        }
        private static void TestManagedDXDevice()
        {
            Device device;
            SwapChain swapChain;
            ShaderSignature inputSignature;
            VertexShader vertexShader;
            PixelShader pixelShader;

            var form = new RenderForm("Tutorial 3: Simple Triangle");
            var description = new SwapChainDescription()
            {
                BufferCount = 2,
                Usage = Usage.RenderTargetOutput,
                OutputHandle = form.Handle,
                IsWindowed = true,
                ModeDescription = new ModeDescription(0, 0, new Rational(60, 1), Format.R8G8B8A8_UNorm),
                SampleDescription = new SampleDescription(1, 0),
                Flags = SwapChainFlags.AllowModeSwitch,
                SwapEffect = SwapEffect.Discard
            };

            Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.Debug, description, out device, out swapChain);

            // create a view of our render target, which is the backbuffer of the swap chain we just created
            RenderTargetView renderTarget;
            using (var resource = Resource.FromSwapChain<Texture2D>(swapChain, 0))
                renderTarget = new RenderTargetView(device, resource);

            // setting a viewport is required if you want to actually see anything
            var context = device.ImmediateContext;
            var viewport = new Viewport(0.0f, 0.0f, form.ClientSize.Width, form.ClientSize.Height);
            context.OutputMerger.SetTargets(renderTarget);
            context.Rasterizer.SetViewports(viewport);

            // load and compile the vertex shader
            using (var bytecode = ShaderBytecode.CompileFromFile("triangle.fx", "VShader", "vs_4_0", ShaderFlags.None, EffectFlags.None))
            {
                inputSignature = ShaderSignature.GetInputSignature(bytecode);
                vertexShader = new VertexShader(device, bytecode);
            }

            // load and compile the pixel shader
            using (var bytecode = ShaderBytecode.CompileFromFile("triangle.fx", "PShader", "ps_4_0", ShaderFlags.None, EffectFlags.None))
                pixelShader = new PixelShader(device, bytecode);

            // create test vertex data, making sure to rewind the stream afterward
            var vertices = new DataStream(12 * 3, true, true);
            vertices.Write(new Vector3(0.0f, 0.5f, 0.5f));
            vertices.Write(new Vector3(0.5f, -0.5f, 0.5f));
            vertices.Write(new Vector3(-0.5f, -0.5f, 0.5f));
            vertices.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 SlimDX.Direct3D11.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
            context.InputAssembler.InputLayout = layout;
            context.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList;
            context.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(vertexBuffer, 12, 0));

            // set the shaders
            context.VertexShader.Set(vertexShader);
            context.PixelShader.Set(pixelShader);

            // prevent DXGI handling of alt+enter, which doesn't work properly with Winforms
            using (var factory = swapChain.GetParent<Factory>())
                factory.SetWindowAssociation(form.Handle, WindowAssociationFlags.IgnoreAltEnter);

            // handle alt+enter ourselves
            form.KeyDown += (o, e) =>
            {
                if (e.Alt && e.KeyCode == Keys.Enter)
                    swapChain.IsFullScreen = !swapChain.IsFullScreen;
            };

            // handle form size changes
            form.UserResized += (o, e) =>
            {
                renderTarget.Dispose();

                swapChain.ResizeBuffers(2, 0, 0, Format.R8G8B8A8_UNorm, SwapChainFlags.AllowModeSwitch);
                using (var resource = Resource.FromSwapChain<Texture2D>(swapChain, 0))
                    renderTarget = new RenderTargetView(device, resource);

                context.OutputMerger.SetTargets(renderTarget);
            };

            MessagePump.Run(form, () =>
            {
                // clear the render target to a soothing blue
                context.ClearRenderTargetView(renderTarget, new Color4(0.5f, 0.5f, 1.0f));

                // draw the triangle
                context.Draw(3, 0);
                swapChain.Present(0, PresentFlags.None);
            });

            // clean up all resources
            // anything we missed will show up in the debug output
            vertices.Close();
            vertexBuffer.Dispose();
            layout.Dispose();
            inputSignature.Dispose();
            vertexShader.Dispose();
            pixelShader.Dispose();
            renderTarget.Dispose();
            swapChain.Dispose();
            device.Dispose();
        }
        private void Generate(ComputeShader computePositionWeight, int width, int height, int depth)
        {
            int count = width * height * depth;
            int widthD = width - 1;
            int heightD = height - 1;
            int depthD = depth - 1;
            int countD = widthD * heightD * depthD;

            int nearestW = NearestPowerOfTwo(widthD);
            int nearestH = NearestPowerOfTwo(heightD);
            int nearestD = NearestPowerOfTwo(depthD);
            int nearestCount = nearestW * nearestH * nearestD;

            Vector3 gridDim = new Vector3((float)Math.Ceiling(width / 8.0f), (float)Math.Ceiling(height / 8.0f), (float)Math.Ceiling(depth / 8.0f));
            Vector3 gridDimD = new Vector3((float)Math.Ceiling(widthD / 8.0f), (float)Math.Ceiling(heightD / 8.0f), (float)Math.Ceiling(depthD / 8.0f));

            constantBufferContainer = new DirectComputeConstantBuffer()
            {
                Width = 16,
                Height = 16,
                Depth = 16,
                Seed = (int)DateTime.Now.Ticks
            };

            DirectComputeNoiseCube noiseCube = new DirectComputeNoiseCube(graphicsDevice);

            ShaderResourceView noiseSRV = noiseCube.GenerateNoiseTexture(constantBuffer, constantBufferContainer);

            Buffer voxelsBuffer = new Buffer(graphicsDevice, new BufferDescription()
            {
                BindFlags = BindFlags.UnorderedAccess,
                CpuAccessFlags = CpuAccessFlags.None,
                OptionFlags = ResourceOptionFlags.StructuredBuffer,
                Usage = ResourceUsage.Default,
                SizeInBytes = Marshal.SizeOf(typeof(Voxel)) * count,
                StructureByteStride = Marshal.SizeOf(typeof(Voxel))
            });

            UnorderedAccessView voxelsUAV = new UnorderedAccessView(graphicsDevice, voxelsBuffer);

            constantBufferContainer = new DirectComputeConstantBuffer()
            {
                Width = width,
                Height = height,
                Depth = depth,
                AmbientRayWidth = container.Settings.AmbientRayWidth,
                AmbientSamplesCount = container.Settings.AmbientSamplesCount,
                NearestWidth = nearestW,
                NearestHeight = nearestH,
                NearestDepth = nearestD
            };

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

            graphicsDevice.ImmediateContext.ComputeShader.Set(computePositionWeight);
            graphicsDevice.ImmediateContext.ComputeShader.SetConstantBuffer(constantBuffer, 0);
            graphicsDevice.ImmediateContext.ComputeShader.SetUnorderedAccessView(voxelsUAV, 0);
            graphicsDevice.ImmediateContext.ComputeShader.SetShaderResource(noiseSRV, 0);

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

            graphicsDevice.ImmediateContext.ComputeShader.Set(computeNormalAmbient);

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

            Buffer offsetsBuffer = new Buffer(graphicsDevice, new BufferDescription()
            {
                BindFlags = BindFlags.UnorderedAccess,
                CpuAccessFlags = CpuAccessFlags.None,
                OptionFlags = ResourceOptionFlags.StructuredBuffer,
                Usage = ResourceUsage.Default,
                SizeInBytes = Marshal.SizeOf(typeof(int)) * countD,
                StructureByteStride = Marshal.SizeOf(typeof(int))
            });

            UnorderedAccessView offsetsUAV = new UnorderedAccessView(graphicsDevice, offsetsBuffer);

            Buffer trisCountBuffer = new Buffer(graphicsDevice, new BufferDescription()
            {
                BindFlags = BindFlags.UnorderedAccess,
                CpuAccessFlags = CpuAccessFlags.None,
                OptionFlags = ResourceOptionFlags.StructuredBuffer,
                Usage = ResourceUsage.Default,
                SizeInBytes = Marshal.SizeOf(typeof(int)) * nearestCount,
                StructureByteStride = Marshal.SizeOf(typeof(int))
            });

            UnorderedAccessView trisCountUAV = new UnorderedAccessView(graphicsDevice, trisCountBuffer);

            graphicsDevice.ImmediateContext.ClearUnorderedAccessView(trisCountUAV, new int[] { 0, 0, 0, 0 });

            graphicsDevice.ImmediateContext.ComputeShader.Set(computeMarchingCubesCases);
            graphicsDevice.ImmediateContext.ComputeShader.SetUnorderedAccessView(offsetsUAV, 1);
            graphicsDevice.ImmediateContext.ComputeShader.SetUnorderedAccessView(trisCountUAV, 2);

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

            UnorderedAccessView prefixSumsUAV = prefixScan.PrefixSumArray(constantBuffer, trisCountUAV);

            int lastTrisCount = DirectComputeBufferHelper.CopyBuffer<int>(graphicsDevice, trisCountBuffer, nearestCount - 1, 1)[0];

            int lastPrefixSum = DirectComputeBufferHelper.CopyBuffer<int>(graphicsDevice, prefixSumsUAV.Resource, nearestCount - 1, 1)[0];

            int totalVerticesCount = (lastTrisCount + lastPrefixSum) * 3;

            if (totalVerticesCount > 0)
            {
                if (container.Geometry != null)
                    container.Geometry.Dispose();

                container.VertexCount = totalVerticesCount;

                container.Geometry = new Buffer(graphicsDevice, new BufferDescription()
                {
                    BindFlags = BindFlags.VertexBuffer,
                    CpuAccessFlags = CpuAccessFlags.None,
                    OptionFlags = ResourceOptionFlags.None,
                    SizeInBytes = Marshal.SizeOf(typeof(VoxelMeshVertex)) * totalVerticesCount,
                    Usage = ResourceUsage.Default
                });

                Buffer verticesBuffer = new Buffer(graphicsDevice, new BufferDescription()
                {
                    BindFlags = BindFlags.UnorderedAccess,
                    CpuAccessFlags = CpuAccessFlags.None,
                    OptionFlags = ResourceOptionFlags.StructuredBuffer,
                    Usage = ResourceUsage.Default,
                    SizeInBytes = Marshal.SizeOf(typeof(VoxelMeshVertex)) * totalVerticesCount,
                    StructureByteStride = Marshal.SizeOf(typeof(VoxelMeshVertex))
                });

                UnorderedAccessView verticesUAV = new UnorderedAccessView(graphicsDevice, verticesBuffer);

                constantBufferContainer = new DirectComputeConstantBuffer()
                {
                    Width = width,
                    Height = height,
                    Depth = depth,
                    NearestWidth = nearestW,
                    NearestHeight = nearestH,
                    NearestDepth = nearestD
                };

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

                graphicsDevice.ImmediateContext.ComputeShader.Set(computeMarchingCubesVertices);
                graphicsDevice.ImmediateContext.ComputeShader.SetUnorderedAccessView(trisCountUAV, 2);
                graphicsDevice.ImmediateContext.ComputeShader.SetUnorderedAccessView(prefixSumsUAV, 3);
                graphicsDevice.ImmediateContext.ComputeShader.SetUnorderedAccessView(verticesUAV, 5);

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

                graphicsDevice.ImmediateContext.CopyResource(verticesBuffer, container.Geometry);

                verticesUAV.Dispose();
                verticesBuffer.Dispose();
            }
            else
            {
                container.VertexCount = 0;

                if (container.Geometry != null)
                    container.Geometry.Dispose();
            }

            for (int i = 0; i <= 5; i++)
            {
                graphicsDevice.ImmediateContext.ComputeShader.SetUnorderedAccessView(null, i);
            }

            prefixSumsUAV.Resource.Dispose();
            prefixSumsUAV.Dispose();
            noiseCube.Dispose();
            noiseSRV.Resource.Dispose();
            noiseSRV.Dispose();
            voxelsBuffer.Dispose();
            voxelsUAV.Dispose();
            offsetsBuffer.Dispose();
            offsetsUAV.Dispose();
            trisCountBuffer.Dispose();
            trisCountUAV.Dispose();
        }
Example #35
0
        static void Main(string[] args)
        {
            const int elementCount = 16;
            const int bufferSizeInBytes = elementCount * sizeof(float);

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

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

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

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

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

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

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

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

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

            computeShader.Dispose();
            outputView.Dispose();
            outputBuffer.Dispose();
            stagingBuffer.Dispose();
            inputBuffer.Dispose();
            device.Dispose();
        }