Esempio n. 1
0
        private DescriptorPool(GraphicsDevice graphicsDevice, DescriptorTypeCount[] counts) : base(graphicsDevice)
        {
            // For now, we put everything together so let's compute total count
            foreach (var count in counts)
            {
                if (count.Type == EffectParameterClass.Sampler)
                    SamplerCount += count.Count;
                else
                    SrvCount += count.Count;
            }

            if (SrvCount > 0)
            {
                SrvHeap = graphicsDevice.NativeDevice.CreateDescriptorHeap(new DescriptorHeapDescription
                {
                    DescriptorCount = SrvCount,
                    Flags = DescriptorHeapFlags.None,
                    Type = DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView,
                });
            }

            if (SamplerCount > 0)
            {
                SamplerHeap = graphicsDevice.NativeDevice.CreateDescriptorHeap(new DescriptorHeapDescription
                {
                    DescriptorCount = SamplerCount,
                    Flags = DescriptorHeapFlags.None,
                    Type = DescriptorHeapType.Sampler,
                });
            }
        }
Esempio n. 2
0
        public void CreateRenderTargetView(DescriptorHeap target, uint descriptorHeapSlot, Resource resource, ref RenderTargetViewDescription description)
        {
            Assert.Debug(target.Desc.Type == DescriptorHeap.Descriptor.ResourceDescriptorType.RenderTarget, "Can create render target views only on render target descriptor heaps.");
            Assert.Debug(target.Desc.NumResourceDescriptors >= descriptorHeapSlot, "Descriptor heap does not have enought slots.");

            target.SetAssociatedResource(descriptorHeapSlot, resource);
            CreateRenderTargetViewImpl(target, descriptorHeapSlot, resource, ref description);
        }
Esempio n. 3
0
        private DescriptorPool(GraphicsDevice graphicsDevice, DescriptorTypeCount[] counts) : base(graphicsDevice)
        {
            // For now, we put everything together so let's compute total count
            foreach (var count in counts)
            {
                if (count.Type == EffectParameterClass.Sampler)
                {
                    SamplerCount += count.Count;
                }
                else
                {
                    SrvCount += count.Count;
                }
            }

            if (SrvCount > 0)
            {
                SrvHeap = graphicsDevice.NativeDevice.CreateDescriptorHeap(new DescriptorHeapDescription
                {
                    DescriptorCount = SrvCount,
                    Flags           = DescriptorHeapFlags.None,
                    Type            = DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView,
                });
                SrvStart = SrvHeap.CPUDescriptorHandleForHeapStart;
            }

            if (SamplerCount > 0)
            {
                SamplerHeap = graphicsDevice.NativeDevice.CreateDescriptorHeap(new DescriptorHeapDescription
                {
                    DescriptorCount = SamplerCount,
                    Flags           = DescriptorHeapFlags.None,
                    Type            = DescriptorHeapType.Sampler,
                });
                SamplerStart = SamplerHeap.CPUDescriptorHandleForHeapStart;
            }
        }
        public DescriptorHeap RequestDescriptorHeap()
        {
            // @TODO - need to be thread-safe

            if (m_AvailableDescriptorHeaps.Count > 0)
            {
                DescriptorHeap heap = m_AvailableDescriptorHeaps.Dequeue();
                return(heap);
            }
            else
            {
                DescriptorHeapDescription descriptorHeapDesc = new DescriptorHeapDescription();
                descriptorHeapDesc.Type            = DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView;
                descriptorHeapDesc.DescriptorCount = NumDescriptorsPerHeap;
                descriptorHeapDesc.Flags           = DescriptorHeapFlags.ShaderVisible;
                descriptorHeapDesc.NodeMask        = 1;

                // create descriptor heap and add heap to the pool
                DescriptorHeap heap = H1Global <H1ManagedRenderer> .Instance.Device.CreateDescriptorHeap(descriptorHeapDesc);

                m_DescriptorHeapPool.Add(heap);
                return(heap);
            }
        }
        private void BuildDescriptorHeaps()
        {
            //
            // Create the SRV heap.
            //
            var srvHeapDesc = new DescriptorHeapDescription
            {
                DescriptorCount = 6,
                Type            = DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView,
                Flags           = DescriptorHeapFlags.ShaderVisible
            };

            _srvDescriptorHeap = Device.CreateDescriptorHeap(srvHeapDesc);
            _descriptorHeaps   = new[] { _srvDescriptorHeap };

            //
            // Fill out the heap with actual descriptors.
            //
            CpuDescriptorHandle hDescriptor = _srvDescriptorHeap.CPUDescriptorHandleForHeapStart;

            Resource[] tex2DList =
            {
                _textures["bricksDiffuseMap"].Resource,
                _textures["tileDiffuseMap"].Resource,
                _textures["defaultDiffuseMap"].Resource
            };
            Resource skyTex = _textures["skyCubeMap"].Resource;

            var srvDesc = new ShaderResourceViewDescription
            {
                Shader4ComponentMapping = D3DUtil.DefaultShader4ComponentMapping,
                Dimension = ShaderResourceViewDimension.Texture2D,
                Texture2D = new ShaderResourceViewDescription.Texture2DResource
                {
                    MostDetailedMip     = 0,
                    ResourceMinLODClamp = 0.0f
                }
            };

            foreach (Resource tex2D in tex2DList)
            {
                srvDesc.Format = tex2D.Description.Format;
                srvDesc.Texture2D.MipLevels = tex2D.Description.MipLevels;
                Device.CreateShaderResourceView(tex2D, srvDesc, hDescriptor);

                // Next descriptor.
                hDescriptor += CbvSrvUavDescriptorSize;
            }

            srvDesc.Dimension   = ShaderResourceViewDimension.TextureCube;
            srvDesc.TextureCube = new ShaderResourceViewDescription.TextureCubeResource
            {
                MostDetailedMip     = 0,
                MipLevels           = skyTex.Description.MipLevels,
                ResourceMinLODClamp = 0.0f
            };
            srvDesc.Format = skyTex.Description.Format;
            Device.CreateShaderResourceView(skyTex, srvDesc, hDescriptor);

            _skyTexHeapIndex     = 3;
            _dynamicTexHeapIndex = _skyTexHeapIndex + 1;

            CpuDescriptorHandle srvCpuStart = _srvDescriptorHeap.CPUDescriptorHandleForHeapStart;
            GpuDescriptorHandle srvGpuStart = _srvDescriptorHeap.GPUDescriptorHandleForHeapStart;
            CpuDescriptorHandle rtvCpuStart = RtvHeap.CPUDescriptorHandleForHeapStart;

            // Cubemap RTV goes after the swap chain descriptors.
            const int rtvOffset = SwapChainBufferCount;

            var cubeRtvHandles = new CpuDescriptorHandle[6];

            for (int i = 0; i < 6; i++)
            {
                cubeRtvHandles[i] = rtvCpuStart + (rtvOffset + i) * RtvDescriptorSize;
            }

            // Dynamic cubemap SRV is after the sky SRV.
            _dynamicCubeMap.BuildDescriptors(
                srvCpuStart + _dynamicTexHeapIndex * CbvSrvUavDescriptorSize,
                srvGpuStart + _dynamicTexHeapIndex * CbvSrvUavDescriptorSize,
                cubeRtvHandles);
        }
        public override void Load(string path2)
        {
            if (done)
            {
                return;
            }
            done = true;

            Bitmap bm = new Bitmap(path);

            Width  = bm.Width;
            Height = bm.Height;
            Depth  = 4;

            var textureDesc = ResourceDescription.Texture2D(Format.R8G8B8A8_UNorm, Width, Height);

            texture = DXGlobal.device.CreateCommittedResource(new HeapProperties(HeapType.Default), HeapFlags.None, textureDesc, ResourceStates.CopyDestination);

            long uploadBufferSize = GetRequiredIntermediateSize(this.texture, 0, 1);

            // Create the GPU upload buffer.
            var textureUploadHeap = DXGlobal.device.CreateCommittedResource(new HeapProperties(CpuPageProperty.WriteBack, MemoryPool.L0), HeapFlags.None, ResourceDescription.Texture2D(Format.R8G8B8A8_UNorm, Width, Height), ResourceStates.GenericRead);

            // Copy data to the intermediate upload heap and then schedule a copy
            // from the upload heap to the Texture2D.
            byte[] textureData = new byte[Width * Height * 4];

            int loc = 0;

            for (int y = 0; y < Height; y++)
            {
                for (int x = 0; x < Width; x++)
                {
                    var pix = bm.GetPixel(x, y);
                    textureData[loc++] = 0xff; //pix.R;
                    textureData[loc++] = 0xff; //pix.G;
                    textureData[loc++] = 0xff; // pix.B;
                    textureData[loc++] = 0xff;
                }
            }

            var handle = GCHandle.Alloc(textureData, GCHandleType.Pinned);
            var ptr    = Marshal.UnsafeAddrOfPinnedArrayElement(textureData, 0);

            textureUploadHeap.WriteToSubresource(0, null, ptr, Depth * Width, textureData.Length);
            handle.Free();
            //   DXGlobal.Display.CommandList.Close();
            DXGlobal.Display.CommandList.Reset(DXGlobal.Display.DirectCmdListAlloc, Effect.Effect._pip);

            DXGlobal.Display.CommandList.CopyTextureRegion(new TextureCopyLocation(texture, 0), 0, 0, 0, new TextureCopyLocation(textureUploadHeap, 0), null);

            DXGlobal.Display.CommandList.ResourceBarrierTransition(this.texture, ResourceStates.CopyDestination, ResourceStates.PixelShaderResource);

            // Describe and create a SRV for the texture.
            srvDesc = new ShaderResourceViewDescription
            {
                Shader4ComponentMapping = D3DXUtilities.DefaultComponentMapping(),
                Format    = textureDesc.Format,
                Dimension = ShaderResourceViewDimension.Texture2D,
                Texture2D = { MipLevels = 1 },
            };
            var srvHeapDesc = new DescriptorHeapDescription()
            {
                DescriptorCount = 1,
                Flags           = DescriptorHeapFlags.ShaderVisible,
                Type            = DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView
            };

            DescriptorHeap srvH = DXGlobal.device.CreateDescriptorHeap(srvHeapDesc);


            DXGlobal.device.CreateShaderResourceView(texture, srvDesc, srvH.CPUDescriptorHandleForHeapStart);



            DXGlobal.Display.CommandList.Close();
            DXGlobal.Display.CommandQueue.ExecuteCommandList(DXGlobal.Display.CommandList);
            DXGlobal.Display.FlushCommandQueue();
        }
        private void LoadAssets()
        {
            // Create the root signature description.
            var rootSignatureDesc = new RootSignatureDescription(

                RootSignatureFlags.AllowInputAssemblerInputLayout,
                // Root Parameters
                new[]
            {
                new RootParameter(ShaderVisibility.All,
                                  new []
                {
                    new DescriptorRange()
                    {
                        RangeType       = DescriptorRangeType.ShaderResourceView,
                        DescriptorCount = 1,
                        OffsetInDescriptorsFromTableStart = int.MinValue,
                        BaseShaderRegister = 0
                    },
                    new DescriptorRange()
                    {
                        RangeType       = DescriptorRangeType.ConstantBufferView,
                        DescriptorCount = 1,
                        OffsetInDescriptorsFromTableStart = int.MinValue + 1,
                        BaseShaderRegister = 0
                    }
                }),
                new RootParameter(ShaderVisibility.Pixel,
                                  new DescriptorRange()
                {
                    RangeType       = DescriptorRangeType.Sampler,
                    DescriptorCount = 1,
                    OffsetInDescriptorsFromTableStart = int.MinValue,
                    BaseShaderRegister = 0
                }),
            });

            //// Samplers
            //new[]
            //{
            //    new StaticSamplerDescription(ShaderVisibility.Pixel, 0, 0)
            //    {
            //        Filter = Filter.MinimumMinMagMipPoint,
            //        AddressUVW = TextureAddressMode.Border,
            //    }
            //});

            rootSignature = device.CreateRootSignature(0, rootSignatureDesc.Serialize());

            // Create the pipeline state, which includes compiling and loading shaders.
#if DEBUG
            var vertexShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.Compile(SharpDX.IO.NativeFile.ReadAllText("../../shaders.hlsl"), "VSMain", "vs_5_0", SharpDX.D3DCompiler.ShaderFlags.Debug));
#else
            var vertexShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("shaders.hlsl", "VSMain", "vs_5_0"));
#endif

#if DEBUG
            var pixelShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.Compile(SharpDX.IO.NativeFile.ReadAllText("../../shaders.hlsl"), "PSMain", "ps_5_0", SharpDX.D3DCompiler.ShaderFlags.Debug));
#else
            var pixelShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("shaders.hlsl", "PSMain", "ps_5_0"));
#endif

#if DEBUG
            //var result = SharpDX.D3DCompiler.ShaderBytecode.Compile(SharpDX.IO.NativeFile.ReadAllText("../../shaders.hlsl"), "GSMain", "gs_5_0", SharpDX.D3DCompiler.ShaderFlags.Debug);
            var geometryShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.Compile(SharpDX.IO.NativeFile.ReadAllText("../../shaders.hlsl"), "GSMain", "gs_5_0", SharpDX.D3DCompiler.ShaderFlags.Debug));
#else
            var pixelShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("shaders.hlsl", "PSMain", "ps_5_0"));
#endif

            // Define the vertex input layout.
            var inputElementDescs = new[]
            {
                new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0),
                new InputElement("TEXCOORD", 0, Format.R32G32_Float, 12, 0)
            };

            // Describe and create the graphics pipeline state object (PSO).
            var psoDesc = new GraphicsPipelineStateDescription()
            {
                InputLayout        = new InputLayoutDescription(inputElementDescs),
                RootSignature      = rootSignature,
                VertexShader       = vertexShader,
                GeometryShader     = geometryShader,
                PixelShader        = pixelShader,
                RasterizerState    = RasterizerStateDescription.Default(),
                BlendState         = BlendStateDescription.Default(),
                DepthStencilFormat = SharpDX.DXGI.Format.D32_Float,
                DepthStencilState  = new DepthStencilStateDescription()
                {
                    IsDepthEnabled   = true,
                    DepthComparison  = Comparison.LessEqual,
                    DepthWriteMask   = DepthWriteMask.All,
                    IsStencilEnabled = false
                },
                SampleMask            = int.MaxValue,
                PrimitiveTopologyType = PrimitiveTopologyType.Triangle,
                RenderTargetCount     = 1,
                Flags             = PipelineStateFlags.None,
                SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0),
                StreamOutput      = new StreamOutputDescription()
            };
            psoDesc.RenderTargetFormats[0] = SharpDX.DXGI.Format.R8G8B8A8_UNorm;

            pipelineState = device.CreateGraphicsPipelineState(psoDesc);

            commandList = device.CreateCommandList(CommandListType.Direct, commandAllocator, pipelineState);
            commandList.Close();

            // build vertex buffer

            var triangleVertices = new[]
            {
                //TOP
                new Vertex()
                {
                    Position = new Vector3(-1f, 1f, 1f), TexCoord = new Vector2(1f, 1f)
                },
                new Vertex()
                {
                    Position = new Vector3(1f, 1f, 1f), TexCoord = new Vector2(0f, 1f)
                },
                new Vertex()
                {
                    Position = new Vector3(1f, 1f, -1f), TexCoord = new Vector2(0f, 0f)
                },
                new Vertex()
                {
                    Position = new Vector3(-1f, 1f, -1f), TexCoord = new Vector2(1f, 0f)
                },
                //BOTTOM
                new Vertex()
                {
                    Position = new Vector3(-1f, -1f, 1f), TexCoord = new Vector2(1f, 1f)
                },
                new Vertex()
                {
                    Position = new Vector3(1f, -1f, 1f), TexCoord = new Vector2(0f, 1f)
                },
                new Vertex()
                {
                    Position = new Vector3(1f, -1f, -1f), TexCoord = new Vector2(0f, 0f)
                },
                new Vertex()
                {
                    Position = new Vector3(-1f, -1f, -1f), TexCoord = new Vector2(1f, 0f)
                },
                //LEFT
                new Vertex()
                {
                    Position = new Vector3(-1f, -1f, 1f), TexCoord = new Vector2(0f, 1f)
                },
                new Vertex()
                {
                    Position = new Vector3(-1f, 1f, 1f), TexCoord = new Vector2(0f, 0f)
                },
                new Vertex()
                {
                    Position = new Vector3(-1f, 1f, -1f), TexCoord = new Vector2(1f, 0f)
                },
                new Vertex()
                {
                    Position = new Vector3(-1f, -1f, -1f), TexCoord = new Vector2(1f, 1f)
                },
                //RIGHT
                new Vertex()
                {
                    Position = new Vector3(1f, -1f, 1f), TexCoord = new Vector2(1f, 1f)
                },
                new Vertex()
                {
                    Position = new Vector3(1f, 1f, 1f), TexCoord = new Vector2(1f, 0f)
                },
                new Vertex()
                {
                    Position = new Vector3(1f, 1f, -1f), TexCoord = new Vector2(0f, 0f)
                },
                new Vertex()
                {
                    Position = new Vector3(1f, -1f, -1f), TexCoord = new Vector2(0f, 1f)
                },
                //FRONT
                new Vertex()
                {
                    Position = new Vector3(-1f, 1f, 1f), TexCoord = new Vector2(1f, 0f)
                },
                new Vertex()
                {
                    Position = new Vector3(1f, 1f, 1f), TexCoord = new Vector2(0f, 0f)
                },
                new Vertex()
                {
                    Position = new Vector3(1f, -1f, 1f), TexCoord = new Vector2(0f, 1f)
                },
                new Vertex()
                {
                    Position = new Vector3(-1f, -1f, 1f), TexCoord = new Vector2(1f, 1f)
                },
                //BACK
                new Vertex()
                {
                    Position = new Vector3(-1f, 1f, -1f), TexCoord = new Vector2(0f, 0f)
                },
                new Vertex()
                {
                    Position = new Vector3(1f, 1f, -1f), TexCoord = new Vector2(1f, 0f)
                },
                new Vertex()
                {
                    Position = new Vector3(1f, -1f, -1f), TexCoord = new Vector2(1f, 1f)
                },
                new Vertex()
                {
                    Position = new Vector3(-1f, -1f, -1f), TexCoord = new Vector2(0f, 1f)
                }
            };

            int vertexBufferSize = Utilities.SizeOf(triangleVertices);

            vertexBuffer = device.CreateCommittedResource(new HeapProperties(HeapType.Upload), HeapFlags.None, ResourceDescription.Buffer(vertexBufferSize), ResourceStates.GenericRead);
            IntPtr pVertexDataBegin = vertexBuffer.Map(0);
            Utilities.Write(pVertexDataBegin, triangleVertices, 0, triangleVertices.Length);
            vertexBuffer.Unmap(0);

            vertexBufferView = new VertexBufferView();
            vertexBufferView.BufferLocation = vertexBuffer.GPUVirtualAddress;
            vertexBufferView.StrideInBytes  = Utilities.SizeOf <Vertex>();
            vertexBufferView.SizeInBytes    = vertexBufferSize;

            // build index buffer

            var triangleIndexes = new uint[]
            {
                0, 1, 2,
                0, 2, 3,

                4, 6, 5,
                4, 7, 6,

                8, 9, 10,
                8, 10, 11,

                12, 14, 13,
                12, 15, 14,

                16, 18, 17,
                16, 19, 18,

                20, 21, 22,
                20, 22, 23
            };

            int indexBufferSize = Utilities.SizeOf(triangleIndexes);

            indexBuffer = device.CreateCommittedResource(new HeapProperties(HeapType.Upload), HeapFlags.None, ResourceDescription.Buffer(indexBufferSize), ResourceStates.GenericRead);
            IntPtr pIndexDataBegin = indexBuffer.Map(0);
            Utilities.Write(pIndexDataBegin, triangleIndexes, 0, triangleIndexes.Length);
            indexBuffer.Unmap(0);

            indexBufferView = new IndexBufferView();
            indexBufferView.BufferLocation = indexBuffer.GPUVirtualAddress;
            indexBufferView.SizeInBytes    = indexBufferSize;
            indexBufferView.Format         = Format.R32_UInt;

            // Create the texture.
            // Describe and create a Texture2D.
            var textureDesc = ResourceDescription.Texture2D(Format.R8G8B8A8_UNorm, TextureWidth, TextureHeight, 1, 1, 1, 0, ResourceFlags.None, TextureLayout.Unknown, 0);
            texture = device.CreateCommittedResource(new HeapProperties(HeapType.Upload), HeapFlags.None, textureDesc, ResourceStates.GenericRead, null);

            // Copy data to the intermediate upload heap and then schedule a copy
            // from the upload heap to the Texture2D.
            byte[] textureData = Utilities.ReadStream(new FileStream("../../texture1.dds", FileMode.Open));

            texture.Name = "Texture";

            var handle = GCHandle.Alloc(textureData, GCHandleType.Pinned);
            var ptr    = Marshal.UnsafeAddrOfPinnedArrayElement(textureData, 0);
            texture.WriteToSubresource(0, null, ptr, TextureWidth * 4, textureData.Length);
            handle.Free();

            // Describe and create a SRV for the texture.
            var srvDesc = new ShaderResourceViewDescription
            {
                Shader4ComponentMapping = ((((0) & 0x7) | (((1) & 0x7) << 3) | (((2) & 0x7) << (3 * 2)) | (((3) & 0x7) << (3 * 3)) | (1 << (3 * 4)))),

                Format    = textureDesc.Format,
                Dimension = ShaderResourceViewDimension.Texture2D,
                Texture2D =
                {
                    MipLevels           = 1,
                    MostDetailedMip     = 0,
                    PlaneSlice          = 0,
                    ResourceMinLODClamp = 0.0f
                },
            };

            device.CreateShaderResourceView(texture, srvDesc, srvCbvHeap.CPUDescriptorHandleForHeapStart);

            SamplerStateDescription samplerDesc = new SamplerStateDescription
            {
                Filter             = Filter.MinMagMipLinear,
                AddressU           = TextureAddressMode.Clamp,
                AddressV           = TextureAddressMode.Clamp,
                AddressW           = TextureAddressMode.Clamp,
                MaximumAnisotropy  = 0,
                MaximumLod         = float.MaxValue,
                MinimumLod         = -float.MaxValue,
                MipLodBias         = 0,
                ComparisonFunction = Comparison.Never
            };

            device.CreateSampler(samplerDesc, samplerViewHeap.CPUDescriptorHandleForHeapStart);

            // build constant buffer

            constantBuffer = device.CreateCommittedResource(new HeapProperties(HeapType.Upload), HeapFlags.None, ResourceDescription.Buffer(1024 * 64), ResourceStates.GenericRead);

            var cbDesc = new ConstantBufferViewDescription()
            {
                BufferLocation = constantBuffer.GPUVirtualAddress,
                SizeInBytes    = (Utilities.SizeOf <ConstantBufferData>() + 255) & ~255
            };
            var srvCbvStep = device.GetDescriptorHandleIncrementSize(DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView);
            device.CreateConstantBufferView(cbDesc, srvCbvHeap.CPUDescriptorHandleForHeapStart + srvCbvStep);

            constantBufferData = new ConstantBufferData
            {
                Project = Matrix.Identity
            };

            constantBufferPointer = constantBuffer.Map(0);
            Utilities.Write(constantBufferPointer, ref constantBufferData);

            // build depth buffer

            DescriptorHeapDescription descDescriptorHeapDSB = new DescriptorHeapDescription()
            {
                DescriptorCount = 1,
                Type            = DescriptorHeapType.DepthStencilView,
                Flags           = DescriptorHeapFlags.None
            };

            DescriptorHeap      descriptorHeapDSB = device.CreateDescriptorHeap(descDescriptorHeapDSB);
            ResourceDescription descDepth         = new ResourceDescription()
            {
                Dimension         = ResourceDimension.Texture2D,
                DepthOrArraySize  = 1,
                MipLevels         = 0,
                Flags             = ResourceFlags.AllowDepthStencil,
                Width             = (int)viewport.Width,
                Height            = (int)viewport.Height,
                Format            = Format.R32_Typeless,
                Layout            = TextureLayout.Unknown,
                SampleDescription = new SampleDescription()
                {
                    Count = 1
                }
            };

            ClearValue dsvClearValue = new ClearValue()
            {
                Format       = Format.D32_Float,
                DepthStencil = new DepthStencilValue()
                {
                    Depth   = 1.0f,
                    Stencil = 0
                }
            };

            Resource renderTargetDepth = device.CreateCommittedResource(new HeapProperties(HeapType.Default), HeapFlags.None, descDepth, ResourceStates.GenericRead, dsvClearValue);

            DepthStencilViewDescription depthDSV = new DepthStencilViewDescription()
            {
                Dimension = DepthStencilViewDimension.Texture2D,
                Format    = Format.D32_Float,
                Texture2D = new DepthStencilViewDescription.Texture2DResource()
                {
                    MipSlice = 0
                }
            };

            device.CreateDepthStencilView(renderTargetDepth, depthDSV, descriptorHeapDSB.CPUDescriptorHandleForHeapStart);
            handleDSV = descriptorHeapDSB.CPUDescriptorHandleForHeapStart;

            fence      = device.CreateFence(0, FenceFlags.None);
            fenceValue = 1;
            fenceEvent = new AutoResetEvent(false);
        }
        private void BuildDescriptorHeaps()
        {
            //
            // Create the SRV heap.
            //
            var srvHeapDesc = new DescriptorHeapDescription
            {
                DescriptorCount = 14,
                Type            = DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView,
                Flags           = DescriptorHeapFlags.ShaderVisible
            };

            _srvDescriptorHeap = Device.CreateDescriptorHeap(srvHeapDesc);
            _descriptorHeaps   = new[] { _srvDescriptorHeap };

            //
            // Fill out the heap with actual descriptors.
            //
            CpuDescriptorHandle hDescriptor = _srvDescriptorHeap.CPUDescriptorHandleForHeapStart;

            Resource[] tex2DList =
            {
                _textures["bricksDiffuseMap"].Resource,
                _textures["bricksNormalMap"].Resource,
                _textures["tileDiffuseMap"].Resource,
                _textures["tileNormalMap"].Resource,
                _textures["defaultDiffuseMap"].Resource,
                _textures["defaultNormalMap"].Resource,
            };
            Resource skyCubeMap = _textures["skyCubeMap"].Resource;

            var srvDesc = new ShaderResourceViewDescription
            {
                Shader4ComponentMapping = D3DUtil.DefaultShader4ComponentMapping,
                Dimension = ShaderResourceViewDimension.Texture2D,
                Texture2D = new ShaderResourceViewDescription.Texture2DResource
                {
                    MostDetailedMip     = 0,
                    ResourceMinLODClamp = 0.0f
                }
            };

            foreach (Resource tex2D in tex2DList)
            {
                srvDesc.Format = tex2D.Description.Format;
                srvDesc.Texture2D.MipLevels = tex2D.Description.MipLevels;

                Device.CreateShaderResourceView(tex2D, srvDesc, hDescriptor);

                // Next descriptor.
                hDescriptor += CbvSrvUavDescriptorSize;
            }

            srvDesc.Dimension   = ShaderResourceViewDimension.TextureCube;
            srvDesc.TextureCube = new ShaderResourceViewDescription.TextureCubeResource
            {
                MostDetailedMip     = 0,
                MipLevels           = skyCubeMap.Description.MipLevels,
                ResourceMinLODClamp = 0.0f
            };
            srvDesc.Format = skyCubeMap.Description.Format;
            Device.CreateShaderResourceView(skyCubeMap, srvDesc, hDescriptor);

            _skyTexHeapIndex    = tex2DList.Length;
            _shadowMapHeapIndex = _skyTexHeapIndex + 1;

            _nullCubeSrvIndex = _shadowMapHeapIndex + 1;

            CpuDescriptorHandle srvCpuStart = _srvDescriptorHeap.CPUDescriptorHandleForHeapStart;
            GpuDescriptorHandle srvGpuStart = _srvDescriptorHeap.GPUDescriptorHandleForHeapStart;
            CpuDescriptorHandle dsvCpuStart = DsvHeap.CPUDescriptorHandleForHeapStart;

            CpuDescriptorHandle nullSrv = srvCpuStart + _nullCubeSrvIndex * CbvSrvUavDescriptorSize;

            _nullSrv = srvGpuStart + _nullCubeSrvIndex * CbvSrvUavDescriptorSize;

            Device.CreateShaderResourceView(null, srvDesc, nullSrv);
            nullSrv += CbvSrvUavDescriptorSize;

            srvDesc.Dimension = ShaderResourceViewDimension.Texture2D;
            srvDesc.Format    = Format.R8G8B8A8_UNorm;
            srvDesc.Texture2D = new ShaderResourceViewDescription.Texture2DResource
            {
                MostDetailedMip     = 0,
                MipLevels           = 1,
                ResourceMinLODClamp = 0.0f
            };
            Device.CreateShaderResourceView(null, srvDesc, nullSrv);

            _shadowMap.BuildDescriptors(
                srvCpuStart + _shadowMapHeapIndex * CbvSrvUavDescriptorSize,
                srvGpuStart + _shadowMapHeapIndex * CbvSrvUavDescriptorSize,
                dsvCpuStart + DsvDescriptorSize);
        }
Esempio n. 9
0
 /// <summary>
 /// Copies descriptors from a source to a destination.
 /// </summary>
 public void CopyDescriptors(DescriptorHeap source, DescriptorHeap destination, Tuple<uint>[] rangeStarts, uint numDescriptors)
 {
     throw new NotImplementedException();
     CopyDescriptorsImpl(source, destination, rangeStarts, numDescriptors);
 }
Esempio n. 10
0
        private void ResetSamplerHeap(bool createNewHeap)
        {
            if (samplerHeap != null)
            {
                GraphicsDevice.SamplerHeaps.RecycleObject(GraphicsDevice.NextFenceValue, samplerHeap);
                samplerHeap = null;
            }

            if (createNewHeap)
            {
                samplerHeap = GraphicsDevice.SamplerHeaps.GetObject();
                samplerHeapOffset = 0;
                samplerMapping.Clear();
            }

            descriptorHeaps[1] = samplerHeap;
        }
Esempio n. 11
0
        public void AfterEngineInit()
        {
            // Basics.
            {
                var deviceDesc = new Device.Descriptor {DebugDevice = true};
                renderDevice = new ClearSight.RendererDX12.Device(ref deviceDesc,
                    ClearSight.RendererDX12.Device.FeatureLevel.Level_11_0);

                var descCQ = new CommandQueue.Descriptor() {Type = CommandListType.Graphics};
                commandQueue = renderDevice.Create(ref descCQ);

                var wih = new WindowInteropHelper(window);
                var swapChainDesc = new SwapChain.Descriptor()
                {
                    AssociatedGraphicsQueue = commandQueue,

                    MaxFramesInFlight = 3,
                    BufferCount = 3,

                    Width = (uint) window.Width,
                    Height = (uint) window.Height,
                    Format = Format.R8G8B8A8_UNorm,

                    SampleCount = 1,
                    SampleQuality = 0,

                    WindowHandle = wih.Handle,
                    Fullscreen = false
                };
                swapChain = renderDevice.Create(ref swapChainDesc);

                var commandListDesc = new CommandList.Descriptor()
                {
                    Type = CommandListType.Graphics,
                    AllocationPolicy = new CommandListInFlightFrameAllocationPolicy(CommandListType.Graphics, swapChain)
                };
                commandList = renderDevice.Create(ref commandListDesc);
            }

            // Render targets.
            {
                var descHeapDesc = new DescriptorHeap.Descriptor()
                {
                    Type = DescriptorHeap.Descriptor.ResourceDescriptorType.RenderTarget,
                    NumResourceDescriptors = swapChain.Desc.BufferCount
                };
                descHeapRenderTargets = renderDevice.Create(ref descHeapDesc);

                var rtvViewDesc = new RenderTargetViewDescription()
                {
                    Format = swapChain.Desc.Format,
                    Dimension = Dimension.Texture2D,
                    Texture = new TextureSubresourceDesc(mipSlice: 0)
                };
                for (uint i = 0; i < swapChain.Desc.BufferCount; ++i)
                {
                    renderDevice.CreateRenderTargetView(descHeapRenderTargets, i, swapChain.BackbufferResources[i], ref rtvViewDesc);
                }
            }
        }
Esempio n. 12
0
 public void Dispose()
 {
     currentHeap?.Dispose();
     currentHeap = null;
 }
Esempio n. 13
0
        private void CreateDeviceResources()
        {
#if DEBUG
            Configuration.EnableObjectTracking      = true;
            Configuration.ThrowOnShaderCompileError = false;

            // Enable the D3D12 debug layer.
            DebugInterface.Get().EnableDebugLayer();
#endif

            using (var factory = new Factory4())
            {
                // Create the Direct3D 12 API device object
                device = new Device(null, SharpDX.Direct3D.FeatureLevel.Level_11_0);
                if (device == null)
                {
                    // TODO: We want to be able to specify adaptor
                    var adapter = factory.Adapters[0];
                    device = new Device(adapter, SharpDX.Direct3D.FeatureLevel.Level_11_0);
                }

                // Create the command queue.
                var queueDesc = new CommandQueueDescription(CommandListType.Direct);
                commandQueue      = device.CreateCommandQueue(queueDesc);
                commandQueue.Name = $"CommandQueue";

                // Create Command Allocator buffers.
                for (int i = 0; i < FrameCount; i++)
                {
                    commandAllocators[i]      = device.CreateCommandAllocator(CommandListType.Direct);
                    commandAllocators[i].Name = $"CommandAllocator F{i}";
                }
            }

            // Create RootSignature.
            var rootSignatureDesc = new RootSignatureDescription(RootSignatureFlags.AllowInputAssemblerInputLayout,
                                                                 new[]
            {
                new RootParameter(ShaderVisibility.Vertex,
                                  new DescriptorRange()
                {
                    RangeType       = DescriptorRangeType.ConstantBufferView,
                    DescriptorCount = 1,
                    OffsetInDescriptorsFromTableStart = int.MinValue,
                    BaseShaderRegister = 0,
                }),
                new RootParameter(ShaderVisibility.Pixel,
                                  new DescriptorRange()
                {
                    RangeType       = DescriptorRangeType.ShaderResourceView,
                    DescriptorCount = 1,
                    OffsetInDescriptorsFromTableStart = int.MinValue,
                    BaseShaderRegister = 0
                })
            },
                                                                 new[]
            {
                new StaticSamplerDescription(ShaderVisibility.Pixel, 0, 0)
                {
                    Filter     = Filter.MinimumMinMagMipPoint,
                    AddressUVW = TextureAddressMode.Border,
                }
            });

            rootSignature = device.CreateRootSignature(rootSignatureDesc.Serialize());

            // Create Constant Buffer View Heap.
            var cbvHeapDesc = new DescriptorHeapDescription()
            {
                DescriptorCount = 1,
                Flags           = DescriptorHeapFlags.ShaderVisible,
                Type            = DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView,
            };
            cbvHeap      = device.CreateDescriptorHeap(cbvHeapDesc);
            cbvHeap.Name = "CBV Heap";

            // Create Shader Render View Heap.
            var srvHeapDesc = new DescriptorHeapDescription()
            {
                DescriptorCount = 1,
                Flags           = DescriptorHeapFlags.ShaderVisible,
                Type            = DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView,
            };
            srvHeap      = device.CreateDescriptorHeap(srvHeapDesc);
            srvHeap.Name = "SRV Heap";

            // Create synchronization objects.
            fence      = device.CreateFence(fenceValues[currentFrame], FenceFlags.None);
            fence.Name = $"Fence";
            fenceValues[currentFrame]++;

            // Create an event handle to use for frame synchronization.
            fenceEvent = new AutoResetEvent(false);
        }
Esempio n. 14
0
 public abstract DescriptorHeap Create(ref DescriptorHeap.Descriptor desc, string label = "<unnamed descriptorHeap>");
        public GraphicsHost(RenderForm window, bool hidden = false)
        {
            if (window == null)
            {
                throw new ArgumentNullException(nameof(window));
            }

            this.window = window;
            if (!hidden)
            {
                this.window.Visible = true;
            }

#if DEBUG
            Configuration.EnableObjectTracking      = true;
            Configuration.ThrowOnShaderCompileError = false;
#endif

            var swapChainDescription = new SwapChainDescription()
            {
                BufferCount       = SwapBufferCount,
                ModeDescription   = new ModeDescription(Format.R8G8B8A8_UNorm),
                Usage             = Usage.RenderTargetOutput,
                OutputHandle      = window.Handle,
                SwapEffect        = SwapEffect.FlipDiscard,
                SampleDescription = new SampleDescription(1, 0),
                IsWindowed        = true
            };

#if DEBUG
            // Enable the D3D12 debug layer.
            // DebugInterface.Get().EnableDebugLayer();
#endif

            try
            {
                // null == DriverType.Hardware
                device       = new Device(null, FeatureLevel.Level_11_0);
                commandQueue = device.CreateCommandQueue(new CommandQueueDescription(CommandListType.Direct));
            }
            catch (SharpDXException)
            {
                using (var factory = new Factory4())
                {
                    device       = new Device(factory.GetWarpAdapter(), FeatureLevel.Level_11_0);
                    commandQueue = device.CreateCommandQueue(new CommandQueueDescription(CommandListType.Direct));
                }
            }

            using (var factory = new Factory1())
                swapChain = new SwapChain(factory, commandQueue, swapChainDescription);

            commandListAllocator = device.CreateCommandAllocator(CommandListType.Direct);

            descriptorHeap = device.CreateDescriptorHeap(new DescriptorHeapDescription()
            {
                Type            = DescriptorHeapType.RenderTargetView,
                DescriptorCount = 1
            });

            commandList = device.CreateCommandList(CommandListType.Direct, commandListAllocator, null);

            renderTarget = swapChain.GetBackBuffer <Resource>(0);
            device.CreateRenderTargetView(renderTarget, null, descriptorHeap.CPUDescriptorHandleForHeapStart);

            viewport         = new ViewportF(0, 0, this.Width, this.Height);
            scissorRectangle = new Rectangle(0, 0, this.Width, this.Height);

            fence        = device.CreateFence(0, FenceFlags.None);
            currentFence = 1;

            commandList.Close();

            eventHandle = new AutoResetEvent(false);

            WaitForPrevFrame();
        }
Esempio n. 16
0
 protected abstract void CreateRenderTargetViewImpl(DescriptorHeap target, uint descriptorHeapSlot, Resource resource, ref RenderTargetViewDescription description);
Esempio n. 17
0
 protected abstract void CopyDescriptorsImpl(DescriptorHeap source, DescriptorHeap destination, Tuple<uint>[] rangeStarts, uint numDescriptors);
Esempio n. 18
0
        /// <summary>
        /// Setup resources for rendering
        /// </summary>
        void LoadAssets()
        {
            // Create the main command list
            commandList = Collect(device.CreateCommandList(CommandListType.Direct, commandListAllocator, pipelineState));

            // Create the descriptor heap for the render target view
            descriptorHeapRT = Collect(device.CreateDescriptorHeap(new DescriptorHeapDescription()
            {
                Type            = DescriptorHeapType.RenderTargetView,
                DescriptorCount = 1
            }));
#if USE_DEPTH
            descriptorHeapDS = Collect(device.CreateDescriptorHeap(new DescriptorHeapDescription()
            {
                Type            = DescriptorHeapType.DepthStencilView,
                DescriptorCount = 1
            }));
#endif
#if USE_TEXTURE
            descriptorHeapCB = Collect(device.CreateDescriptorHeap(new DescriptorHeapDescription()
            {
                Type            = DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView,
                DescriptorCount = 2,
                Flags           = DescriptorHeapFlags.ShaderVisible,
            }));
            descriptorHeapS = Collect(device.CreateDescriptorHeap(new DescriptorHeapDescription()
            {
                Type            = DescriptorHeapType.Sampler,
                DescriptorCount = 1,
                Flags           = DescriptorHeapFlags.ShaderVisible,
            }));
            descriptorsHeaps[0] = descriptorHeapCB;
            descriptorsHeaps[1] = descriptorHeapS;
#else
            descriptorHeapCB = Collect(device.CreateDescriptorHeap(new DescriptorHeapDescription()
            {
                Type            = DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView,
                DescriptorCount = 1,
                Flags           = DescriptorHeapFlags.ShaderVisible,
            }));
            descriptorsHeaps[0] = descriptorHeapCB;
#endif
#if true // root signature in code
            var rsparams = new RootParameter[]
            {
                new RootParameter(ShaderVisibility.Vertex, new RootDescriptor(), RootParameterType.ConstantBufferView),
                new RootParameter(ShaderVisibility.Vertex,
                                  new DescriptorRange
                {
                    RangeType          = DescriptorRangeType.ConstantBufferView,
                    BaseShaderRegister = 1,
                    DescriptorCount    = 1,
                }),
#if USE_TEXTURE
                new RootParameter(ShaderVisibility.Pixel,
                                  new DescriptorRange
                {
                    RangeType          = DescriptorRangeType.ShaderResourceView,
                    BaseShaderRegister = 0,
                    DescriptorCount    = 1,
                }),
                new RootParameter(ShaderVisibility.Pixel,
                                  new DescriptorRange
                {
                    RangeType          = DescriptorRangeType.Sampler,
                    BaseShaderRegister = 0,
                    DescriptorCount    = 1,
                }),
#endif
            };
            var rs = new RootSignatureDescription(RootSignatureFlags.AllowInputAssemblerInputLayout, rsparams);
            rootSignature = Collect(device.CreateRootSignature(rs.Serialize()));
#else
            var rootSignatureByteCode = Utilities.ReadStream(assembly.GetManifestResourceStream("Shaders.Cube" + shaderNameSuffix + ".rs"));
            using (var bufferRootSignature = DataBuffer.Create(rootSignatureByteCode))
                rootSignature = Collect(device.CreateRootSignature(bufferRootSignature));
#endif
            byte[] vertexShaderByteCode = GetResourceBytes("Cube" + shaderNameSuffix + ".vso");
            byte[] pixelShaderByteCode  = GetResourceBytes("Cube" + shaderNameSuffix + ".pso");

            var layout = new InputLayoutDescription(new InputElement[]
            {
                new InputElement("POSITION", 0, Format.R32G32B32_Float, 0),
                new InputElement("NORMAL", 0, Format.R32G32B32_Float, 0),
                new InputElement("TEXCOORD", 0, Format.R32G32_Float, 0),
#if USE_INSTANCES
                new InputElement("OFFSET", 0, Format.R32G32B32_Float, 0, 1, InputClassification.PerInstanceData, 1),
#endif
            });

            #region pipeline state
            var psd = new GraphicsPipelineStateDescription
            {
                InputLayout           = layout,
                VertexShader          = vertexShaderByteCode,
                PixelShader           = pixelShaderByteCode,
                RootSignature         = rootSignature,
                DepthStencilState     = DepthStencilStateDescription.Default(),
                DepthStencilFormat    = Format.Unknown,
                BlendState            = BlendStateDescription.Default(),
                RasterizerState       = RasterizerStateDescription.Default(),
                SampleDescription     = new SampleDescription(1, 0),
                RenderTargetCount     = 1,
                PrimitiveTopologyType = PrimitiveTopologyType.Triangle,
                SampleMask            = -1,
                StreamOutput          = new StreamOutputDescription()
            };
            psd.RenderTargetFormats[0] = Format.R8G8B8A8_UNorm;
#if USE_DEPTH
            psd.DepthStencilFormat = Format.D32_Float;
#else
            psd.DepthStencilState.IsDepthEnabled = false;
#endif
            //psd.RasterizerState.CullMode = CullMode.None;
            pipelineState = Collect(device.CreateGraphicsPipelineState(psd));
            #endregion pipeline state

            #region vertices
            var vertices = new[]
            {
                -1.0f, -1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f,                       // Front
                -1.0f, 1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f,
                1.0f, -1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f,
                1.0f, 1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f,
                1.0f, 1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f,

                -1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f,                        // BACK
                -1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f,                        // BACK
                1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f,
                -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f,
                1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f,
                1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f,

                -1.0f, 1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f,                        // Top
                -1.0f, 1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f,                        // Top
                -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f,
                1.0f, 1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f,
                1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f,
                1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f,

                -1.0f, -1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f,                       // Bottom
                -1.0f, -1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f,                       // Bottom
                1.0f, -1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f,
                -1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f,
                1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f,
                1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f,

                -1.0f, -1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f,                       // Left
                -1.0f, -1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f,                       // Left
                -1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f,
                -1.0f, 1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f,
                -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f,
                -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f,

                1.0f, -1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f,                        // Right
                1.0f, -1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f,                        // Right
                1.0f, 1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f,
                1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f,
                1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f,
            };
            #endregion vertices
            #region vertex buffer
            // Instantiate Vertex buiffer from vertex data
            int sizeOfFloat = sizeof(float);
            int sizeInBytes = vertices.Length * sizeOfFloat;
            vertexBuffer = Collect(device.CreateCommittedResource(
                                       new HeapProperties(HeapType.Upload),
                                       HeapFlags.None,
                                       new ResourceDescription(ResourceDimension.Buffer, 0, sizeInBytes, 1, 1, 1, Format.Unknown, 1, 0, TextureLayout.RowMajor, ResourceFlags.None),
                                       ResourceStates.GenericRead));
            vertexBufferView = new[]
            {
                new VertexBufferView
                {
                    BufferLocation = vertexBuffer.GPUVirtualAddress,
                    SizeInBytes    = sizeInBytes,
                    StrideInBytes  = sizeOfFloat * 8,
                }
            };
            var ptr = vertexBuffer.Map(0);
            Utilities.Write(ptr, vertices, 0, vertices.Length);
            vertexBuffer.Unmap(0);
            #endregion vertex buffer
            #region instances
#if USE_INSTANCES
            int instanceSizeInBytes = sizeOfFloat * instances.Length;
            instancesBuffer = Collect(device.CreateCommittedResource(
                                          new HeapProperties(HeapType.Upload),
                                          HeapFlags.None,
                                          new ResourceDescription(ResourceDimension.Buffer, 0, instanceSizeInBytes, 1, 1, 1, Format.Unknown, 1, 0, TextureLayout.RowMajor, ResourceFlags.None),
                                          ResourceStates.GenericRead));
            instancesBufferView = new[]
            {
                new VertexBufferView
                {
                    BufferLocation = instancesBuffer.GPUVirtualAddress,
                    SizeInBytes    = instanceSizeInBytes,
                    StrideInBytes  = sizeOfFloat * 3,
                }
            };
            ptr = instancesBuffer.Map(0);
            Utilities.Write(ptr, instances, 0, instances.Length);
            instancesBuffer.Unmap(0);
#endif
            #endregion instances

            #region indices
#if USE_INDICES
            var indexData = new[]
            {
                0, 1, 2, 3, 4,
                5, 6, 7, 8, 9, 10,
                11, 12, 13, 14, 15, 16,
                17, 18, 19, 20, 21, 22,
                23, 24, 25, 26, 27, 28,
                29, 30, 31, 32, 33
            };
            sizeInBytes = indexData.Length * sizeof(int);
            indexBuffer = Collect(device.CreateCommittedResource(
                                      new HeapProperties(HeapType.Upload),
                                      HeapFlags.None,
                                      new ResourceDescription(ResourceDimension.Buffer, 0, sizeInBytes, 1, 1, 1, Format.Unknown, 1, 0, TextureLayout.RowMajor, ResourceFlags.None),
                                      ResourceStates.GenericRead));
            ptr = indexBuffer.Map(0);
            Utilities.Write(ptr, indexData, 0, indexData.Length);
            indexBuffer.Unmap(0);
            indexBufferView = new IndexBufferView
            {
                BufferLocation = indexBuffer.GPUVirtualAddress,
                SizeInBytes    = sizeInBytes,
                Format         = Format.R32_UInt
            };
#endif
            #endregion indices

            #region transform
            transWorld = Collect(device.CreateCommittedResource(
                                     new HeapProperties(HeapType.Upload),
                                     HeapFlags.None,
                                     new ResourceDescription(ResourceDimension.Buffer, 0, 16 * sizeOfMatrix, 1, 1, 1, Format.Unknown, 1, 0, TextureLayout.RowMajor, ResourceFlags.None),
                                     ResourceStates.GenericRead));
            transWorldPtr = transWorld.Map(0);
            transViewProj = Collect(device.CreateCommittedResource(
                                        new HeapProperties(HeapType.Upload),
                                        HeapFlags.None,
                                        new ResourceDescription(ResourceDimension.Buffer, 0, sizeOfMatrix, 1, 1, 1, Format.Unknown, 1, 0, TextureLayout.RowMajor, ResourceFlags.None),
                                        ResourceStates.GenericRead));
            device.CreateConstantBufferView(new ConstantBufferViewDescription
            {
                BufferLocation = transViewProj.GPUVirtualAddress,
                SizeInBytes    = sizeOfMatrix,
            }, descriptorHeapCB.CPUDescriptorHandleForHeapStart);

            var view = Matrix.LookAtLH(new Vector3(5, 5, -5), Vector3.Zero, Vector3.UnitY);
            var proj = Matrix.PerspectiveFovLH(MathUtil.Pi / 4, (float)width / height, 0.1f, 100);
            var vpT  = view * proj;
            vpT.Transpose();
            ptr = transViewProj.Map(0);
            Utilities.Write(ptr, ref vpT);
            transViewProj.Unmap(0);
            #endregion transform

#if USE_TEXTURE
            #region texture
            Resource buf;
            using (var tl = new TextureLoader("GeneticaMortarlessBlocks.jpg"))
            {
                int w = tl.Width, h = tl.Height;
                var descrs = new[]
                {
                    new ResourceDescription(ResourceDimension.Texture2D,
                                            0, w, h, 1, 1,
                                            Format.B8G8R8A8_UNorm, 1, 0,
                                            TextureLayout.Unknown,
                                            ResourceFlags.None),
                };
                texture = Collect(device.CreateCommittedResource(
                                      new HeapProperties(HeapType.Default),
                                      HeapFlags.None,
                                      descrs[0],
                                      ResourceStates.CopyDestination)
                                  );
                var resAllocInfo = device.GetResourceAllocationInfo(1, 1, descrs);
                buf = device.CreateCommittedResource(
                    new HeapProperties(HeapType.Upload),
                    HeapFlags.None,
                    new ResourceDescription(
                        ResourceDimension.Buffer,
                        0,
                        resAllocInfo.SizeInBytes,
                        1, 1, 1,
                        Format.Unknown,
                        1, 0,
                        TextureLayout.RowMajor,
                        ResourceFlags.None),
                    ResourceStates.GenericRead);

                var ptrBuf   = buf.Map(0);
                int rowPitch = tl.CopyImageData(ptrBuf);
                buf.Unmap(0);

                var src = new TextureCopyLocation(buf,
                                                  new PlacedSubResourceFootprint
                {
                    Offset    = 0,
                    Footprint = new SubResourceFootprint
                    {
                        Format   = Format.B8G8R8A8_UNorm_SRgb,
                        Width    = w,
                        Height   = h,
                        Depth    = 1,
                        RowPitch = rowPitch
                    }
                }
                                                  );
                var dst = new TextureCopyLocation(texture, 0);
                // record copy
                commandList.CopyTextureRegion(dst, 0, 0, 0, src, null);

                commandList.ResourceBarrierTransition(texture, ResourceStates.CopyDestination, ResourceStates.GenericRead);
            }
            descrOffsetCB = device.GetDescriptorHandleIncrementSize(DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView);
            device.CreateShaderResourceView(texture, null, descriptorHeapCB.CPUDescriptorHandleForHeapStart + descrOffsetCB);
            #endregion texture

            #region sampler
            device.CreateSampler(new SamplerStateDescription
            {
                AddressU = TextureAddressMode.Wrap,
                AddressV = TextureAddressMode.Wrap,
                AddressW = TextureAddressMode.Wrap,
                Filter   = Filter.MaximumMinMagMipLinear,
            }, descriptorHeapS.CPUDescriptorHandleForHeapStart);
            #endregion sampler
#endif
            // Get the backbuffer and creates the render target view
            renderTarget = Collect(swapChain.GetBackBuffer <Resource>(0));
            device.CreateRenderTargetView(renderTarget, null, descriptorHeapRT.CPUDescriptorHandleForHeapStart);

#if USE_DEPTH
            depthBuffer = Collect(device.CreateCommittedResource(
                                      new HeapProperties(HeapType.Default),
                                      HeapFlags.None,
                                      new ResourceDescription(ResourceDimension.Texture2D, 0, width, height, 1, 1, Format.D32_Float, 1, 0, TextureLayout.Unknown, ResourceFlags.AllowDepthStencil),
                                      ResourceStates.Present,
                                      new ClearValue
            {
                Format       = Format.D32_Float,
                DepthStencil = new DepthStencilValue
                {
                    Depth   = 1,
                    Stencil = 0,
                }
            }));
            device.CreateDepthStencilView(depthBuffer, null, descriptorHeapDS.CPUDescriptorHandleForHeapStart);
#endif

            // Create the viewport
            viewPort = new ViewportF(0, 0, width, height);

            // Create the scissor
            scissorRectangle = new Rectangle(0, 0, width, height);

            // Create a fence to wait for next frame
            fence        = Collect(device.CreateFence(0, FenceFlags.None));
            currentFence = 1;

            // Close command list
            commandList.Close();
            commandQueue.ExecuteCommandList(commandList);

            // Create an event handle use for VTBL
            CreateWaitEvent();

            // Wait the command list to complete
            WaitForPrevFrame();
#if USE_TEXTURE
            buf.Dispose();
#endif
        }
Esempio n. 19
0
        public void BuildPSO(Device3 device, GraphicsCommandList commandList)
        {
            Projection = Matrix.PerspectiveFovLH((float)Math.PI / 3f, 4f / 3f, 1, 1000);
            View       = Matrix.LookAtLH(new Vector3(10 * (float)Math.Sin(rotation), 5, 10 * (float)Math.Cos(rotation)), Vector3.Zero, Vector3.UnitY);
            World      = Matrix.Translation(-2.5f, -2.5f, -2.5f);

            DescriptorHeapDescription cbvHeapDesc = new DescriptorHeapDescription()
            {
                DescriptorCount = 1,
                Flags           = DescriptorHeapFlags.ShaderVisible,
                Type            = DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView
            };

            _perPassViewHeap = device.CreateDescriptorHeap(cbvHeapDesc);

            RootParameter[] rootParameters = new RootParameter[] { new RootParameter(ShaderVisibility.All, new RootDescriptor(0, 0), RootParameterType.ConstantBufferView) };


            // Create an empty root signature.
            RootSignatureDescription rootSignatureDesc = new RootSignatureDescription(RootSignatureFlags.AllowInputAssemblerInputLayout, rootParameters);

            _rootSignature = device.CreateRootSignature(rootSignatureDesc.Serialize());

            // Create the pipeline state, which includes compiling and loading shaders.

#if DEBUG
            var vertexShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("Shaders/Untextured.hlsl", "VSMain", "vs_5_0", SharpDX.D3DCompiler.ShaderFlags.Debug));
#else
            var vertexShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("Shaders/Untextured.hlsl", "VSMain", "vs_5_0"));
#endif

#if DEBUG
            var pixelShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("Shaders/Untextured.hlsl", "PSMain", "ps_5_0", SharpDX.D3DCompiler.ShaderFlags.Debug));
#else
            var pixelShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("Shaders/Untextured.hlsl", "PSMain", "ps_5_0"));
#endif

            // Define the vertex input layout.
            InputElement[] inputElementDescs = new InputElement[]
            {
                new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0),
                new InputElement("COLOR", 0, Format.R32G32B32A32_Float, 12, 0)
            };

            // Describe and create the graphics pipeline state object (PSO).
            GraphicsPipelineStateDescription psoDesc = new GraphicsPipelineStateDescription()
            {
                InputLayout           = new InputLayoutDescription(inputElementDescs),
                RootSignature         = _rootSignature,
                VertexShader          = vertexShader,
                PixelShader           = pixelShader,
                RasterizerState       = RasterizerStateDescription.Default(),
                BlendState            = BlendStateDescription.Default(),
                DepthStencilFormat    = SharpDX.DXGI.Format.D24_UNorm_S8_UInt,
                DepthStencilState     = DepthStencilStateDescription.Default(),
                SampleMask            = int.MaxValue,
                PrimitiveTopologyType = PrimitiveTopologyType.Triangle,
                RenderTargetCount     = 1,
                Flags             = PipelineStateFlags.None,
                SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0),
                StreamOutput      = new StreamOutputDescription()
            };
            psoDesc.RenderTargetFormats[0] = SharpDX.DXGI.Format.R8G8B8A8_UNorm;

            _pipelineState = device.CreateGraphicsPipelineState(psoDesc);

            // Define the geometry for a triangle.
            Vertex[] triangleVertices = new Vertex[]
            {
                //Front
                new Vertex()
                {
                    Position = new Vector3(0, 0, 0), Color = new Vector4(0, 0, 1, 1)
                },
                new Vertex()
                {
                    Position = new Vector3(0, 5, 0), Color = new Vector4(0, 0, 1, 1)
                },
                new Vertex()
                {
                    Position = new Vector3(5, 0, 0), Color = new Vector4(0, 0, 1, 1)
                },
                new Vertex()
                {
                    Position = new Vector3(5, 5, 0), Color = new Vector4(0, 0, 1, 1)
                },

                //Back
                new Vertex()
                {
                    Position = new Vector3(0, 0, 5), Color = new Vector4(0, 0, 1, 1)
                },
                new Vertex()
                {
                    Position = new Vector3(0, 5, 5), Color = new Vector4(0, 0, 1, 1)
                },
                new Vertex()
                {
                    Position = new Vector3(5, 0, 5), Color = new Vector4(0, 0, 1, 1)
                },
                new Vertex()
                {
                    Position = new Vector3(5, 5, 5), Color = new Vector4(0, 0, 1, 1)
                },

                //Left
                new Vertex()
                {
                    Position = new Vector3(0, 0, 0), Color = new Vector4(0, 1, 0, 1)
                },
                new Vertex()
                {
                    Position = new Vector3(0, 5, 0), Color = new Vector4(0, 1, 0, 1)
                },
                new Vertex()
                {
                    Position = new Vector3(0, 0, 5), Color = new Vector4(0, 1, 0, 1)
                },
                new Vertex()
                {
                    Position = new Vector3(0, 5, 5), Color = new Vector4(0, 1, 0, 1)
                },

                //Right
                new Vertex()
                {
                    Position = new Vector3(5, 0, 0), Color = new Vector4(0, 1, 0, 1)
                },
                new Vertex()
                {
                    Position = new Vector3(5, 5, 0), Color = new Vector4(0, 1, 0, 1)
                },
                new Vertex()
                {
                    Position = new Vector3(5, 0, 5), Color = new Vector4(0, 1, 0, 1)
                },
                new Vertex()
                {
                    Position = new Vector3(5, 5, 5), Color = new Vector4(0, 1, 0, 1)
                },

                //Top
                new Vertex()
                {
                    Position = new Vector3(0, 0, 0), Color = new Vector4(1, 0, 0, 1)
                },
                new Vertex()
                {
                    Position = new Vector3(0, 0, 5), Color = new Vector4(1, 0, 0, 1)
                },
                new Vertex()
                {
                    Position = new Vector3(5, 0, 0), Color = new Vector4(1, 0, 0, 1)
                },
                new Vertex()
                {
                    Position = new Vector3(5, 0, 5), Color = new Vector4(1, 0, 0, 1)
                },

                //Bottom
                new Vertex()
                {
                    Position = new Vector3(0, 5, 0), Color = new Vector4(1, 0, 0, 1)
                },
                new Vertex()
                {
                    Position = new Vector3(0, 5, 5), Color = new Vector4(1, 0, 0, 1)
                },
                new Vertex()
                {
                    Position = new Vector3(5, 5, 0), Color = new Vector4(1, 0, 0, 1)
                },
                new Vertex()
                {
                    Position = new Vector3(5, 5, 5), Color = new Vector4(1, 0, 0, 1)
                }
            };

            int vertexBufferSize = Utilities.SizeOf(triangleVertices);

            // Note: using upload heaps to transfer static data like vert buffers is not
            // recommended. Every time the GPU needs it, the upload heap will be marshalled
            // over. Please read up on Default Heap usage. An upload heap is used here for
            // code simplicity and because there are very few verts to actually transfer.
            _vertexBuffer = device.CreateCommittedResource(new HeapProperties(HeapType.Upload), HeapFlags.None, ResourceDescription.Buffer(vertexBufferSize), ResourceStates.GenericRead);

            // Copy the triangle data to the vertex buffer.
            IntPtr pVertexDataBegin = _vertexBuffer.Map(0);
            Utilities.Write(pVertexDataBegin, triangleVertices, 0, triangleVertices.Length);
            _vertexBuffer.Unmap(0);

            _indicies = new int[] { 0, 1, 2,
                                    3, 2, 1,
                                    6, 5, 4,
                                    5, 6, 7,

                                    10, 9, 8,
                                    9, 10, 11,
                                    12, 13, 14,
                                    15, 14, 13,

                                    18, 17, 16,
                                    17, 18, 19,
                                    20, 21, 22,
                                    23, 22, 21 };

            int indBufferSize = Utilities.SizeOf(_indicies);

            _indexBuffer = device.CreateCommittedResource(new HeapProperties(HeapType.Upload), HeapFlags.None, ResourceDescription.Buffer(indBufferSize), ResourceStates.GenericRead);

            IntPtr pIndBegin = _indexBuffer.Map(0);
            Utilities.Write(pIndBegin, _indicies, 0, _indicies.Length);
            _indexBuffer.Unmap(0);

            _indexBufferView = new IndexBufferView()
            {
                BufferLocation = _indexBuffer.GPUVirtualAddress,
                Format         = Format.R32_UInt,
                SizeInBytes    = indBufferSize
            };

            // Initialize the vertex buffer view.
            _vertexBufferView = new VertexBufferView
            {
                BufferLocation = _vertexBuffer.GPUVirtualAddress,
                StrideInBytes  = Utilities.SizeOf <Vertex>(),
                SizeInBytes    = vertexBufferSize
            };

            _perPassBuffer = device.CreateCommittedResource(new HeapProperties(HeapType.Upload), HeapFlags.None, ResourceDescription.Buffer(Utilities.SizeOf <PerPass>()), ResourceStates.GenericRead);

            //// Describe and create a constant buffer view.
            ConstantBufferViewDescription cbvDesc = new ConstantBufferViewDescription()
            {
                BufferLocation = _perPassBuffer.GPUVirtualAddress,
                SizeInBytes    = (Utilities.SizeOf <PerPass>() + 255) & ~255
            };
            device.CreateConstantBufferView(cbvDesc, _perPassViewHeap.CPUDescriptorHandleForHeapStart);

            // Initialize and map the constant buffers. We don't unmap this until the
            // app closes. Keeping things mapped for the lifetime of the resource is okay.
            _perPassPointer = _perPassBuffer.Map(0);
            Utilities.Write(_perPassPointer, ref buffer);

            _resources = new[] { new GraphicsResource()
                                 {
                                     Resource = _perPassBuffer, Register = 0, type = ResourceType.ConstantBufferView
                                 } };
        }
 public void Dispose()
 {
     DescriptorHeap.Dispose();
 }
Esempio n. 21
0
        private void LoadPipeline(RenderForm form)
        {
            int width = form.ClientSize.Width;
            int height = form.ClientSize.Height;

            viewport.Width = width;
            viewport.Height = height;
            viewport.MaxDepth = 1.0f;

            scissorRect.Right = width;
            scissorRect.Bottom = height;

            #if DEBUG
            // Enable the D3D12 debug layer.
            {
                DebugInterface.Get().EnableDebugLayer();
            }
            #endif
            device = new Device(null, SharpDX.Direct3D.FeatureLevel.Level_12_0);
            using (var factory = new Factory4())
            {

                // Describe and create the command queue.
                CommandQueueDescription queueDesc = new CommandQueueDescription(CommandListType.Direct);
                commandQueue = device.CreateCommandQueue(queueDesc);

                // Describe and create the swap chain.
                SwapChainDescription swapChainDesc = new SwapChainDescription()
                {
                    BufferCount = FrameCount,
                    ModeDescription = new ModeDescription(width, height, new Rational(60, 1), Format.R8G8B8A8_UNorm),
                    Usage = Usage.RenderTargetOutput,
                    SwapEffect = SwapEffect.FlipDiscard,
                    OutputHandle = form.Handle,
                    //Flags = SwapChainFlags.None,
                    SampleDescription = new SampleDescription(1, 0),
                    IsWindowed = true
                };

                SwapChain tempSwapChain = new SwapChain(factory, commandQueue, swapChainDesc);
                swapChain = tempSwapChain.QueryInterface<SwapChain3>();
                tempSwapChain.Dispose();
                frameIndex = swapChain.CurrentBackBufferIndex;
            }

            // Create descriptor heaps.
            // Describe and create a render target view (RTV) descriptor heap.
            DescriptorHeapDescription rtvHeapDesc = new DescriptorHeapDescription()
            {
                DescriptorCount = FrameCount,
                Flags = DescriptorHeapFlags.None,
                Type = DescriptorHeapType.RenderTargetView
            };

            renderTargetViewHeap = device.CreateDescriptorHeap(rtvHeapDesc);

            rtvDescriptorSize = device.GetDescriptorHandleIncrementSize(DescriptorHeapType.RenderTargetView);

            //Init Direct3D11 device from Direct3D12 device
            device11 = SharpDX.Direct3D11.Device.CreateFromDirect3D12(device, SharpDX.Direct3D11.DeviceCreationFlags.BgraSupport, null, null, commandQueue);
            deviceContext11 = device11.ImmediateContext;
            device11on12 = device11.QueryInterface<SharpDX.Direct3D11.ID3D11On12Device>();
            var d2dFactory = new SharpDX.Direct2D1.Factory(SharpDX.Direct2D1.FactoryType.MultiThreaded);

            // Create frame resources.
            CpuDescriptorHandle rtvHandle = renderTargetViewHeap.CPUDescriptorHandleForHeapStart;
            for (int n = 0; n < FrameCount; n++)
            {
                renderTargets[n] = swapChain.GetBackBuffer<Resource>(n);
                device.CreateRenderTargetView(renderTargets[n], null, rtvHandle);
                rtvHandle += rtvDescriptorSize;

                //init Direct2D surfaces
                SharpDX.Direct3D11.D3D11ResourceFlags format = new SharpDX.Direct3D11.D3D11ResourceFlags()
                {
                    BindFlags = (int)SharpDX.Direct3D11.BindFlags.RenderTarget,
                    CPUAccessFlags = (int)SharpDX.Direct3D11.CpuAccessFlags.None
                };

                device11on12.CreateWrappedResource(
                    renderTargets[n], format,
                    (int)ResourceStates.Present,
                    (int)ResourceStates.RenderTarget,
                    typeof(SharpDX.Direct3D11.Resource).GUID,
                    out wrappedBackBuffers[n]);

                //Init direct2D surface
                var d2dSurface = wrappedBackBuffers[n].QueryInterface<Surface>();
                direct2DRenderTarget[n] = new SharpDX.Direct2D1.RenderTarget(d2dFactory, d2dSurface, new SharpDX.Direct2D1.RenderTargetProperties(new SharpDX.Direct2D1.PixelFormat(Format.Unknown, SharpDX.Direct2D1.AlphaMode.Premultiplied)));
                d2dSurface.Dispose();
            }

            commandAllocator = device.CreateCommandAllocator(CommandListType.Direct);

            d2dFactory.Dispose();

            //Init font
            var directWriteFactory = new SharpDX.DirectWrite.Factory();
            textFormat = new SharpDX.DirectWrite.TextFormat(directWriteFactory, "Arial", SharpDX.DirectWrite.FontWeight.Bold, SharpDX.DirectWrite.FontStyle.Normal, 48) { TextAlignment = SharpDX.DirectWrite.TextAlignment.Leading, ParagraphAlignment = SharpDX.DirectWrite.ParagraphAlignment.Near };
            textBrush = new SharpDX.Direct2D1.SolidColorBrush(direct2DRenderTarget[0], Color.White);
            directWriteFactory.Dispose();
        }
        private void LoadPipeline(RenderForm form)
        {
            int width = form.ClientSize.Width;
            int height = form.ClientSize.Height;

            viewport.Width = width;
            viewport.Height = height;
            viewport.MaxDepth = 1.0f;

            scissorRect.Right = width;
            scissorRect.Bottom = height;

            #if DEBUG
            // Enable the D3D12 debug layer.
            {
                DebugInterface.Get().EnableDebugLayer();
            }
            #endif
            device = new Device(null, SharpDX.Direct3D.FeatureLevel.Level_11_0);
            using (var factory = new Factory4())
            {
                // Describe and create the command queue.
                CommandQueueDescription queueDesc = new CommandQueueDescription(CommandListType.Direct);
                commandQueue = device.CreateCommandQueue(queueDesc);

                // Describe and create the swap chain.
                SwapChainDescription swapChainDesc = new SwapChainDescription()
                {
                    BufferCount = FrameCount,
                    ModeDescription = new ModeDescription(width, height, new Rational(60, 1), Format.R8G8B8A8_UNorm),
                    Usage = Usage.RenderTargetOutput,
                    SwapEffect = SwapEffect.FlipDiscard,
                    OutputHandle = form.Handle,
                    //Flags = SwapChainFlags.None,
                    SampleDescription = new SampleDescription(1, 0),
                    IsWindowed = true
                };

                SwapChain tempSwapChain = new SwapChain(factory, commandQueue, swapChainDesc);
                swapChain = tempSwapChain.QueryInterface<SwapChain3>();
                tempSwapChain.Dispose();
                frameIndex = swapChain.CurrentBackBufferIndex;
            }

            // Create descriptor heaps.
            // Describe and create a render target view (RTV) descriptor heap.
            DescriptorHeapDescription rtvHeapDesc = new DescriptorHeapDescription()
            {
                DescriptorCount = FrameCount,
                Flags = DescriptorHeapFlags.None,
                Type = DescriptorHeapType.RenderTargetView
            };

            renderTargetViewHeap = device.CreateDescriptorHeap(rtvHeapDesc);

            DescriptorHeapDescription srvHeapDesc = new DescriptorHeapDescription()
            {
                DescriptorCount = 1,
                Flags = DescriptorHeapFlags.ShaderVisible,
                Type = DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView
            };

            shaderRenderViewHeap = device.CreateDescriptorHeap(srvHeapDesc);

            rtvDescriptorSize = device.GetDescriptorHandleIncrementSize(DescriptorHeapType.RenderTargetView);

            // Create frame resources.
            CpuDescriptorHandle rtvHandle = renderTargetViewHeap.CPUDescriptorHandleForHeapStart;
            for (int n = 0; n < FrameCount; n++)
            {
                renderTargets[n] = swapChain.GetBackBuffer<Resource>(n);
                device.CreateRenderTargetView(renderTargets[n], null, rtvHandle);
                rtvHandle += rtvDescriptorSize;
            }

            commandAllocator = device.CreateCommandAllocator(CommandListType.Direct);
        }
Esempio n. 23
0
        private void LoadPipeline(RenderForm form)
        {
            int width = form.ClientSize.Width;
            int height = form.ClientSize.Height;

            #if DEBUG
            // Enable the D3D12 debug layer.
            {
                DebugInterface.Get().EnableDebugLayer();
            }
            #endif
            device = new Device(null, SharpDX.Direct3D.FeatureLevel.Level_11_0);
            using (var factory = new Factory4())
            {
                // Describe and create the command queue.
                CommandQueueDescription queueDesc = new CommandQueueDescription(CommandListType.Direct);
                commandQueue = device.CreateCommandQueue(queueDesc);

                // Describe and create the swap chain.
                SwapChainDescription swapChainDesc = new SwapChainDescription()
                {
                    BufferCount = FrameCount,
                    ModeDescription = new ModeDescription(width, height, new Rational(60, 1), Format.R8G8B8A8_UNorm),
                    Usage = Usage.RenderTargetOutput,
                    SwapEffect = SwapEffect.FlipDiscard,
                    OutputHandle = form.Handle,
                    //Flags = SwapChainFlags.None,
                    SampleDescription = new SampleDescription(1, 0),
                    IsWindowed = true
                };

                SwapChain tempSwapChain = new SwapChain(factory, commandQueue, swapChainDesc);
                swapChain = tempSwapChain.QueryInterface<SwapChain3>();
                tempSwapChain.Dispose();
                frameIndex = swapChain.CurrentBackBufferIndex;
            }

            // Create descriptor heaps.
            // Describe and create a render target view (RTV) descriptor heap.
            renderTargetViewHeap = device.CreateDescriptorHeap(new DescriptorHeapDescription()
            {
                DescriptorCount = FrameCount,
                Flags = DescriptorHeapFlags.None,
                Type = DescriptorHeapType.RenderTargetView
            });
            rtvDescriptorSize = device.GetDescriptorHandleIncrementSize(DescriptorHeapType.RenderTargetView);

            //create depth buffer;
            depthStencilViewHeap = device.CreateDescriptorHeap(new DescriptorHeapDescription()
            {
                DescriptorCount = FrameCount,
                Flags = DescriptorHeapFlags.None,
                Type = DescriptorHeapType.DepthStencilView
            });

            //constant buffer view heap
            constantBufferViewHeap = device.CreateDescriptorHeap(new DescriptorHeapDescription()
            {
                DescriptorCount = 100,
                Type = DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView,
                Flags = DescriptorHeapFlags.ShaderVisible
            });

            //Create targets
            CreateTargets(width, height);

            //sampler buffer view heap
            samplerViewHeap = device.CreateDescriptorHeap(new DescriptorHeapDescription()
            {
                DescriptorCount = 10,
                Type = DescriptorHeapType.Sampler,
                Flags = DescriptorHeapFlags.ShaderVisible
            });

            //bind sampler
            device.CreateSampler(new SamplerStateDescription()
            {
                Filter = Filter.ComparisonMinMagMipLinear,
                AddressU = TextureAddressMode.Wrap,
                AddressV = TextureAddressMode.Wrap,
                AddressW = TextureAddressMode.Wrap,
                MinimumLod = float.MinValue,
                MaximumLod = float.MaxValue,
                MipLodBias = 0,
                MaximumAnisotropy = 0,
                ComparisonFunction = Comparison.Never
            }, samplerViewHeap.CPUDescriptorHandleForHeapStart);

            commandAllocator = device.CreateCommandAllocator(CommandListType.Direct);
            bundleAllocator = device.CreateCommandAllocator(CommandListType.Bundle);

            form.UserResized += (sender, e) =>
             {
                 isResizing = true;
             };
        }
Esempio n. 24
0
        void loadDevice()
        {
            _resources = new GraphicsResource[0];

            _viewport.Width    = WIDTH;
            _viewport.Height   = HEIGHT;
            _viewport.MaxDepth = 1.0f;

            _scissorRect.Right  = WIDTH;
            _scissorRect.Bottom = HEIGHT;

#if DEBUG
            // Enable the D3D12 debug layer.
            {
                DebugInterface.Get().EnableDebugLayer();
            }
#endif

            using (var factory = new Factory4())
            {
                _device = new Device(factory.GetAdapter(_adapterIndex), SharpDX.Direct3D.FeatureLevel.Level_12_1).QueryInterface <Device3>();
                // Describe and create the command queue.
                CommandQueueDescription queueDesc = new CommandQueueDescription(CommandListType.Direct);
                _graphicsQueue = _device.CreateCommandQueue(queueDesc);


                // Describe and create the swap chain.
                SwapChainDescription swapChainDesc = new SwapChainDescription()
                {
                    BufferCount       = FRAME_COUNT,
                    ModeDescription   = new ModeDescription(WIDTH, HEIGHT, new Rational(60, 1), Format.R8G8B8A8_UNorm),
                    Usage             = Usage.RenderTargetOutput,
                    SwapEffect        = SwapEffect.FlipDiscard,
                    OutputHandle      = _window.Handle,
                    Flags             = SwapChainFlags.AllowModeSwitch,
                    SampleDescription = new SampleDescription(1, 0),
                    IsWindowed        = true
                };

                SwapChain tempSwapChain = new SwapChain(factory, _graphicsQueue, swapChainDesc);
                _swapChain = tempSwapChain.QueryInterface <SwapChain3>();
                tempSwapChain.Dispose();
                _frameIndex = _swapChain.CurrentBackBufferIndex;
            }

            // Create descriptor heaps.
            // Describe and create a render target view (RTV) descriptor heap.
            DescriptorHeapDescription rtvHeapDesc = new DescriptorHeapDescription()
            {
                DescriptorCount = FRAME_COUNT,
                Flags           = DescriptorHeapFlags.None,
                Type            = DescriptorHeapType.RenderTargetView
            };

            _renderTargetViewHeap = _device.CreateDescriptorHeap(rtvHeapDesc);

            DescriptorHeapDescription _dsvHeapDescription = new DescriptorHeapDescription()
            {
                DescriptorCount = 1,
                Flags           = DescriptorHeapFlags.None,
                NodeMask        = 0,
                Type            = DescriptorHeapType.DepthStencilView
            };
            _depthStencilView = _device.CreateDescriptorHeap(_dsvHeapDescription);

            _rtvDescriptorSize = _device.GetDescriptorHandleIncrementSize(DescriptorHeapType.RenderTargetView);

            // Create frame resources.
            CpuDescriptorHandle rtvHandle = _renderTargetViewHeap.CPUDescriptorHandleForHeapStart;
            for (int n = 0; n < FRAME_COUNT; n++)
            {
                _renderTargets[n] = _swapChain.GetBackBuffer <Resource>(n);
                _device.CreateRenderTargetView(_renderTargets[n], null, rtvHandle);
                rtvHandle += _rtvDescriptorSize;
            }

            //Initialize Depth/Stencil Buffer
            _depthStencilDesc = new ResourceDescription(ResourceDimension.Texture2D, 0,
                                                        _window.Width, _window.Height, 1, 1, Format.D24_UNorm_S8_UInt, 1, 0,
                                                        TextureLayout.Unknown, ResourceFlags.AllowDepthStencil);
            _depthStencilClear = new ClearValue()
            {
                DepthStencil = new DepthStencilValue()
                {
                    Depth   = 1.0f,
                    Stencil = 0
                },
                Format = Format.D24_UNorm_S8_UInt
            };
            _depthStencilBuffer = _device.CreateCommittedResource(new HeapProperties(HeapType.Default),
                                                                  HeapFlags.None, _depthStencilDesc, ResourceStates.Common, _depthStencilClear);

            //Create Descriptor to mip level 0 of the entire resource using format of the resouce
            _device.CreateDepthStencilView(_depthStencilBuffer, null, DepthStencilHandle);

            _commandAllocator       = _device.CreateCommandAllocator(CommandListType.Direct);
            _bundleCommandAllocator = _device.CreateCommandAllocator(CommandListType.Bundle);

            // Create the command list.
            _commandList       = _device.CreateCommandList(CommandListType.Direct, _commandAllocator, null);
            _bundleCommandList = _device.CreateCommandList(CommandListType.Bundle, _bundleCommandAllocator, null);

            _commandList.ResourceBarrier(new ResourceBarrier(new ResourceTransitionBarrier(_depthStencilBuffer,
                                                                                           ResourceStates.Common, ResourceStates.DepthWrite)));

            // Command lists are created in the recording state, but there is nothing
            // to record yet. The main loop expects it to be closed, so close it now.
            _bundleCommandList.Close();
        }
Esempio n. 25
0
 public void SetRenderTargets(DescriptorHeap descriptorHeapColor, uint slotColor, DescriptorHeap descriptorHeapDepthStencil, uint slotDepthStencil)
 {
     SetRenderTargets(descriptorHeapColor, new uint[] { slotColor }, descriptorHeapDepthStencil, slotDepthStencil);
 }
Esempio n. 26
0
        public void BuildPSO(Device3 device, GraphicsCommandList commandList)
        {
            buffer = new CBuffer()
            {
                Rows    = 3,
                Columns = 5
            };

            DescriptorHeapDescription cbvHeapDesc = new DescriptorHeapDescription()
            {
                DescriptorCount = 1,
                Flags           = DescriptorHeapFlags.ShaderVisible,
                Type            = DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView
            };

            _constantBufferViewHeap = device.CreateDescriptorHeap(cbvHeapDesc);


            DescriptorHeapDescription srvHeapDesc = new DescriptorHeapDescription()
            {
                DescriptorCount = 1,
                Flags           = DescriptorHeapFlags.ShaderVisible,
                Type            = DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView
            };

            _srvDescriptorHeap = device.CreateDescriptorHeap(srvHeapDesc);

            DescriptorRange[] ranges = new DescriptorRange[] { new DescriptorRange()
                                                               {
                                                                   RangeType = DescriptorRangeType.ShaderResourceView, DescriptorCount = 1, OffsetInDescriptorsFromTableStart = int.MinValue, BaseShaderRegister = 0
                                                               } };

            //Get sampler state setup
            StaticSamplerDescription sampler = new StaticSamplerDescription()
            {
                Filter           = Filter.MinimumMinMagMipPoint,
                AddressU         = TextureAddressMode.Border,
                AddressV         = TextureAddressMode.Border,
                AddressW         = TextureAddressMode.Border,
                MipLODBias       = 0,
                MaxAnisotropy    = 0,
                ComparisonFunc   = Comparison.Never,
                BorderColor      = StaticBorderColor.TransparentBlack,
                MinLOD           = 0.0f,
                MaxLOD           = float.MaxValue,
                ShaderRegister   = 0,
                RegisterSpace    = 0,
                ShaderVisibility = ShaderVisibility.Pixel,
            };

            RootParameter[] rootParameters = new RootParameter[] { new RootParameter(ShaderVisibility.Pixel, ranges),
                                                                   new RootParameter(ShaderVisibility.Pixel, new RootDescriptor(1, 0), RootParameterType.ConstantBufferView) };


            // Create an empty root signature.
            RootSignatureDescription rootSignatureDesc = new RootSignatureDescription(RootSignatureFlags.AllowInputAssemblerInputLayout, rootParameters, new StaticSamplerDescription[] { sampler });

            _rootSignature = device.CreateRootSignature(rootSignatureDesc.Serialize());

            // Create the pipeline state, which includes compiling and loading shaders.

#if DEBUG
            var vertexShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("Shaders/AtlasWalk.hlsl", "VSMain", "vs_5_0", SharpDX.D3DCompiler.ShaderFlags.Debug));
#else
            var vertexShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("Shaders/AtlasWalk.hlsl", "VSMain", "vs_5_0"));
#endif

#if DEBUG
            var pixelShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("Shaders/AtlasWalk.hlsl", "PSMain", "ps_5_0", SharpDX.D3DCompiler.ShaderFlags.Debug));
#else
            var pixelShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("Shaders/AtlasWalk.hlsl", "PSMain", "ps_5_0"));
#endif

            // Define the vertex input layout.
            InputElement[] inputElementDescs = new InputElement[]
            {
                new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0),
                new InputElement("TEXCOORD", 0, Format.R32G32_Float, 12, 0)
            };

            // Describe and create the graphics pipeline state object (PSO).
            GraphicsPipelineStateDescription psoDesc = new GraphicsPipelineStateDescription()
            {
                InputLayout        = new InputLayoutDescription(inputElementDescs),
                RootSignature      = _rootSignature,
                VertexShader       = vertexShader,
                PixelShader        = pixelShader,
                RasterizerState    = RasterizerStateDescription.Default(),
                BlendState         = BlendStateDescription.Default(),
                DepthStencilFormat = SharpDX.DXGI.Format.D32_Float,
                DepthStencilState  = new DepthStencilStateDescription()
                {
                    IsDepthEnabled = false, IsStencilEnabled = false
                },
                SampleMask            = int.MaxValue,
                PrimitiveTopologyType = PrimitiveTopologyType.Triangle,
                RenderTargetCount     = 1,
                Flags             = PipelineStateFlags.None,
                SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0),
                StreamOutput      = new StreamOutputDescription()
            };
            psoDesc.RenderTargetFormats[0] = SharpDX.DXGI.Format.R8G8B8A8_UNorm;

            _pipelineState = device.CreateGraphicsPipelineState(psoDesc);

            // Define the geometry for a triangle.
            Vertex[] triangleVertices = new Vertex[]
            {
                new Vertex()
                {
                    position = new Vector3(-0.5f, -0.5f, 0.5f), texCoord = new Vector2(1.0f, 1.0f)
                },
                new Vertex()
                {
                    position = new Vector3(-0.5f, 0.5f, 0.5f), texCoord = new Vector2(1.0f, 0.0f)
                },
                new Vertex()
                {
                    position = new Vector3(0.5f, -0.5f, 0.5f), texCoord = new Vector2(0.0f, 1.0f)
                },
                new Vertex()
                {
                    position = new Vector3(0.5f, 0.5f, 0.5f), texCoord = new Vector2(0.0f, 0.0f)
                }
            };

            int vertexBufferSize = Utilities.SizeOf(triangleVertices);

            // Note: using upload heaps to transfer static data like vert buffers is not
            // recommended. Every time the GPU needs it, the upload heap will be marshalled
            // over. Please read up on Default Heap usage. An upload heap is used here for
            // code simplicity and because there are very few verts to actually transfer.
            _vertexBuffer = device.CreateCommittedResource(new HeapProperties(HeapType.Upload), HeapFlags.None, ResourceDescription.Buffer(vertexBufferSize), ResourceStates.GenericRead);

            // Copy the triangle data to the vertex buffer.
            IntPtr pVertexDataBegin = _vertexBuffer.Map(0);
            Utilities.Write(pVertexDataBegin, triangleVertices, 0, triangleVertices.Length);
            _vertexBuffer.Unmap(0);

            _indicies = new int[] { 0, 1, 2,
                                    3, 2, 1 };

            int indBufferSize = Utilities.SizeOf(_indicies);

            _indexBuffer = device.CreateCommittedResource(new HeapProperties(HeapType.Upload), HeapFlags.None, ResourceDescription.Buffer(indBufferSize), ResourceStates.GenericRead);

            IntPtr pIndBegin = _indexBuffer.Map(0);
            Utilities.Write(pIndBegin, _indicies, 0, _indicies.Length);
            _indexBuffer.Unmap(0);

            _indexBufferView = new IndexBufferView()
            {
                BufferLocation = _indexBuffer.GPUVirtualAddress,
                Format         = Format.R32_UInt,
                SizeInBytes    = indBufferSize
            };

            // Initialize the vertex buffer view.
            _vertexBufferView = new VertexBufferView
            {
                BufferLocation = _vertexBuffer.GPUVirtualAddress,
                StrideInBytes  = Utilities.SizeOf <Vertex>(),
                SizeInBytes    = vertexBufferSize
            };

            Resource textureUploadHeap;

            // Create the texture.
            // Describe and create a Texture2D.
            ResourceDescription textureDesc = ResourceDescription.Texture2D(Format.R8G8B8A8_UNorm, textureWidth, textureHeight);
            _texture = device.CreateCommittedResource(new HeapProperties(HeapType.Default), HeapFlags.None, textureDesc, ResourceStates.CopyDestination);

            long uploadBufferSize = GetRequiredIntermediateSize(device, _texture, 0, 1);

            // Create the GPU upload buffer.
            textureUploadHeap = device.CreateCommittedResource(new HeapProperties(CpuPageProperty.WriteBack, MemoryPool.L0), HeapFlags.None, ResourceDescription.Texture2D(Format.R8G8B8A8_UNorm, textureWidth, textureHeight), ResourceStates.GenericRead);

            // Copy data to the intermediate upload heap and then schedule a copy
            // from the upload heap to the Texture2D.
            byte[] textureData = GenerateTextureData();

            GCHandle handle = GCHandle.Alloc(textureData, GCHandleType.Pinned);
            IntPtr   ptr    = Marshal.UnsafeAddrOfPinnedArrayElement(textureData, 0);
            textureUploadHeap.WriteToSubresource(0, null, ptr, 4 * textureWidth, textureData.Length);
            handle.Free();

            commandList.CopyTextureRegion(new TextureCopyLocation(_texture, 0), 0, 0, 0, new TextureCopyLocation(textureUploadHeap, 0), null);

            commandList.ResourceBarrierTransition(_texture, ResourceStates.CopyDestination, ResourceStates.PixelShaderResource);

            // Describe and create a SRV for the texture.
            ShaderResourceViewDescription srvDesc = new ShaderResourceViewDescription()
            {
                Shader4ComponentMapping = ComponentMapping(0, 1, 2, 3),
                Format    = textureDesc.Format,
                Dimension = ShaderResourceViewDimension.Texture2D,
            };
            srvDesc.Texture2D.MipLevels = 1;

            device.CreateShaderResourceView(_texture, srvDesc, _srvDescriptorHeap.CPUDescriptorHandleForHeapStart);

            _constantBuffer = device.CreateCommittedResource(new HeapProperties(HeapType.Upload), HeapFlags.None, ResourceDescription.Buffer(1024 * 64), ResourceStates.GenericRead);

            //// Describe and create a constant buffer view.
            ConstantBufferViewDescription cbvDesc = new ConstantBufferViewDescription()
            {
                BufferLocation = _constantBuffer.GPUVirtualAddress,
                SizeInBytes    = (Utilities.SizeOf <CBuffer>() + 255) & ~255
            };
            device.CreateConstantBufferView(cbvDesc, _constantBufferViewHeap.CPUDescriptorHandleForHeapStart);

            // Initialize and map the constant buffers. We don't unmap this until the
            // app closes. Keeping things mapped for the lifetime of the resource is okay.
            _constantBufferPointer = _constantBuffer.Map(0);
            Utilities.Write(_constantBufferPointer, ref buffer);

            _resources = new[] { new GraphicsResource()
                                 {
                                     Heap = _srvDescriptorHeap, Register = 0, type = ResourceType.DescriptorTable
                                 },
                                 new GraphicsResource()
                                 {
                                     Resource = _constantBuffer, Register = 1, type = ResourceType.ConstantBufferView
                                 } };
        }
Esempio n. 27
0
        /// <summary>
        /// You need to make sure manually that all associated resources are in the RenderTargetColor / DepthWrite state.
        /// </summary>
        /// <param name="descriptorHeapColor">Can be null if no color target should be bound</param>
        /// <param name="slotsColor"></param>
        /// <param name="descriptorHeapDepthStencil">Can be null if no depth target should be bound.</param>
        /// <param name="slotDepthStencil"></param>
        public void SetRenderTargets(DescriptorHeap descriptorHeapColor, uint[] slotsColor, DescriptorHeap descriptorHeapDepthStencil, uint slotDepthStencil)
        {
            // Validitiy checks.
            Debug.Assert(descriptorHeapColor == null || descriptorHeapColor.Desc.Type == DescriptorHeap.Descriptor.ResourceDescriptorType.RenderTarget, "Descriptor heap for render target needs to be a rendertarget descriptor heap.");
#if DEBUG
            if (descriptorHeapColor != null)
            {
                Debug.Assert(slotsColor != null, "No descriptor slots given for render target color.");
                foreach (uint slot in slotsColor)
                {
                    Debug.Assert(descriptorHeapColor.Desc.NumResourceDescriptors >= slot, "Invalid descriptor heap slot.");
                }
            }
#endif
            Debug.Assert(descriptorHeapDepthStencil == null || descriptorHeapDepthStencil.Desc.Type == DescriptorHeap.Descriptor.ResourceDescriptorType.RenderTarget,
                         "Descriptor heap for depth needs to be a rendertarget descriptor heap.");
            Debug.Assert(descriptorHeapDepthStencil == null || descriptorHeapDepthStencil.Desc.NumResourceDescriptors < slotDepthStencil, "Invalid descriptor heap slot.");


            // Redundancy check.
            bool sameColor = descriptorHeapColor == this.descriptorHeapColor &&
                             slotsColor.SequenceEqual(this.slotsColor);
            bool sameDs = descriptorHeapDepthStencil == this.descriptorHeapDepthStencil &&
                          slotDepthStencil == this.slotDepthStencil;

            if (sameColor && sameDs)
            {
                return;
            }
            if (sameDs)
            {
                descriptorHeapDepthStencil = null;
            }
            else if (sameColor)
            {
                descriptorHeapColor = null;
                slotsColor          = null;
            }

            // State change.
            this.descriptorHeapColor        = descriptorHeapColor;
            this.slotsColor                 = slotsColor;
            this.descriptorHeapDepthStencil = descriptorHeapDepthStencil;
            this.slotDepthStencil           = slotDepthStencil;
            ActiveAllocator.RegisterResourceUse(descriptorHeapColor);
            ActiveAllocator.RegisterResourceUse(descriptorHeapDepthStencil);

            // Specific impl.
            SetRenderTargetsImpl(descriptorHeapColor, slotsColor, descriptorHeapDepthStencil, slotDepthStencil);
        }
        private void LoadPipeline(RenderForm form)
        {
            int width  = form.ClientSize.Width;
            int height = form.ClientSize.Height;

            viewport.Width    = width;
            viewport.Height   = height;
            viewport.MaxDepth = 1.0f;

            scissorRect.Right  = width;
            scissorRect.Bottom = height;

            device = new Device(null, SharpDX.Direct3D.FeatureLevel.Level_11_0);

            using (var factory = new Factory4())
            {
                var queueDesc = new CommandQueueDescription(CommandListType.Direct);
                commandQueue = device.CreateCommandQueue(queueDesc);

                var swapChainDesc = new SwapChainDescription()
                {
                    BufferCount       = FrameCount,
                    ModeDescription   = new ModeDescription(width, height, new Rational(60, 1), Format.R8G8B8A8_UNorm),
                    Usage             = Usage.RenderTargetOutput,
                    SwapEffect        = SwapEffect.FlipDiscard,
                    OutputHandle      = form.Handle,
                    SampleDescription = new SampleDescription(1, 0),
                    IsWindowed        = true
                };

                var tempSwapChain = new SwapChain(factory, commandQueue, swapChainDesc);
                swapChain  = tempSwapChain.QueryInterface <SwapChain3>();
                frameIndex = swapChain.CurrentBackBufferIndex;
            }

            var rtvHeapDesc = new DescriptorHeapDescription()
            {
                DescriptorCount = FrameCount,
                Flags           = DescriptorHeapFlags.None,
                Type            = DescriptorHeapType.RenderTargetView
            };

            renderTargetViewHeap = device.CreateDescriptorHeap(rtvHeapDesc);
            rtvDescriptorSize    = device.GetDescriptorHandleIncrementSize(DescriptorHeapType.RenderTargetView);

            var srvCbvHeapDesc = new DescriptorHeapDescription()
            {
                DescriptorCount = 1,
                Flags           = DescriptorHeapFlags.ShaderVisible,
                Type            = DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView
            };

            srvCbvHeap = device.CreateDescriptorHeap(srvCbvHeapDesc);

            var rtcHandle = renderTargetViewHeap.CPUDescriptorHandleForHeapStart;

            for (int n = 0; n < FrameCount; n++)
            {
                renderTargets[n] = swapChain.GetBackBuffer <Resource>(n);
                device.CreateRenderTargetView(renderTargets[n], null, rtcHandle);
                rtcHandle += rtvDescriptorSize;
            }

            var svHeapDesc = new DescriptorHeapDescription()
            {
                Type            = DescriptorHeapType.Sampler,
                DescriptorCount = 10,
                Flags           = DescriptorHeapFlags.ShaderVisible,
                NodeMask        = 0
            };

            samplerViewHeap = device.CreateDescriptorHeap(svHeapDesc);

            commandAllocator = device.CreateCommandAllocator(CommandListType.Direct);
        }
Esempio n. 29
0
 protected abstract void SetRenderTargetsImpl(DescriptorHeap descriptorHeapColor, uint[] slotsColor, DescriptorHeap descriptorHeapDepthStencil, uint slotDepthStencil);
        private void LoadPipeline(RenderForm form)
        {
            int width = form.ClientSize.Width;
            int height = form.ClientSize.Height;

            viewport.Width = width;
            viewport.Height = height;
            viewport.MaxDepth = 1.0f;

            scissorRect.Right = width;
            scissorRect.Bottom = height;

            device = new Device(null, SharpDX.Direct3D.FeatureLevel.Level_11_0);

            using (var factory = new Factory4())
            {
                var queueDesc = new CommandQueueDescription(CommandListType.Direct);
                commandQueue = device.CreateCommandQueue(queueDesc);

                var swapChainDesc = new SwapChainDescription()
                {
                    BufferCount = FrameCount,
                    ModeDescription = new ModeDescription(width, height, new Rational(60, 1), Format.R8G8B8A8_UNorm),
                    Usage = Usage.RenderTargetOutput,
                    SwapEffect = SwapEffect.FlipDiscard,
                    OutputHandle = form.Handle,
                    SampleDescription = new SampleDescription(1, 0),
                    IsWindowed = true
                };

                var tempSwapChain = new SwapChain(factory, commandQueue, swapChainDesc);
                swapChain = tempSwapChain.QueryInterface<SwapChain3>();
                frameIndex = swapChain.CurrentBackBufferIndex;

            }

            var rtvHeapDesc = new DescriptorHeapDescription()
            {
                DescriptorCount = FrameCount,
                Flags = DescriptorHeapFlags.None,
                Type = DescriptorHeapType.RenderTargetView
            };

            renderTargetViewHeap = device.CreateDescriptorHeap(rtvHeapDesc);
            rtvDescriptorSize = device.GetDescriptorHandleIncrementSize(DescriptorHeapType.RenderTargetView);

            var srvHeapDesc = new DescriptorHeapDescription()
            {
                DescriptorCount = 200,
                Flags = DescriptorHeapFlags.ShaderVisible,
                Type = DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView
            };

            shaderRenderViewHeap = device.CreateDescriptorHeap(srvHeapDesc);

            var terrainHeapDesc = new DescriptorHeapDescription()
            {
                DescriptorCount = 2,
                Flags = DescriptorHeapFlags.ShaderVisible,
                Type = DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView
            };

            terrainHeap = device.CreateDescriptorHeap(terrainHeapDesc);

            var meshCtrCbvDesc = new DescriptorHeapDescription()
            {
                DescriptorCount = 1,
                Flags = DescriptorHeapFlags.ShaderVisible,
                Type = DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView
            };

            meshCtrBufferViewHeap = device.CreateDescriptorHeap(meshCtrCbvDesc);

            var rtcHandle = renderTargetViewHeap.CPUDescriptorHandleForHeapStart;
            for (int n = 0; n < FrameCount; n++)
            {
                renderTargets[n] = swapChain.GetBackBuffer<Resource>(n);
                device.CreateRenderTargetView(renderTargets[n], null, rtcHandle);
                rtcHandle += rtvDescriptorSize;
            }

            var svHeapDesc = new DescriptorHeapDescription()
            {
                Type = DescriptorHeapType.Sampler,
                DescriptorCount = 1,
                Flags = DescriptorHeapFlags.ShaderVisible,
                NodeMask = 0
            };
            samplerViewHeap = device.CreateDescriptorHeap(svHeapDesc);

            commandAllocator = device.CreateCommandAllocator(CommandListType.Direct);
        }
Esempio n. 31
0
        public WorldPass(GraphicsDevice device, Camera camera)
        {
            _device = device;
            _camera = camera;

            _rtvs = _device.CreateDescriptorHeap(DescriptorHeapType.RenderTargetView, 1);
            _dsvs = _device.CreateDescriptorHeap(DescriptorHeapType.RenderTargetView, 1);

            var @params = new RootParameter[]
            {
                RootParameter.CreateDescriptor(RootParameterType.ConstantBufferView, 0, 0),
                RootParameter.CreateDescriptor(RootParameterType.ConstantBufferView, 1, 0),
                RootParameter.CreateDescriptor(RootParameterType.ShaderResourceView, 0, 0, ShaderVisibility.Pixel),
                RootParameter.CreateDescriptorTable(DescriptorRangeType.ShaderResourceView, 1, 2, 0, visibility: ShaderVisibility.Pixel)
            };

            var samplers = new StaticSampler[]
            {
                new StaticSampler(TextureAddressMode.Clamp, SamplerFilterType.MagPoint | SamplerFilterType.MinPoint | SamplerFilterType.MipLinear, 0, 0, ShaderVisibility.Pixel)
            };

            RootSignature = _device.CreateRootSignature(@params, samplers);

            var shaderFlags = new[]
            {
                ShaderCompileFlag.PackMatricesInRowMajorOrder,
                ShaderCompileFlag.DisableOptimizations,
                ShaderCompileFlag.EnableDebugInformation,
                ShaderCompileFlag.WriteDebugInformationToFile()
            };

            var psoDesc = new GraphicsPipelineDesc
            {
                RootSignature       = RootSignature,
                Topology            = TopologyClass.Triangle,
                RenderTargetFormats = BackBufferFormat.R8G8B8A8UnsignedNormalized,

                DepthStencilFormat = DataFormat.Depth32Single,

                VertexShader = ShaderManager.CompileShader("Shaders/ChunkShader.hlsl", ShaderType.Vertex, shaderFlags, "VertexMain"),
                PixelShader  = ShaderManager.CompileShader("Shaders/ChunkShader.hlsl", ShaderType.Pixel, shaderFlags, "PixelMain"),
                Inputs       = InputLayout.FromType <BlockVertex>()
            };

            Pso = _device.PipelineManager.CreatePipelineStateObject(psoDesc, "ChunkPso");

            psoDesc.Msaa = MsaaDesc.X8;

            MsaaPso = _device.PipelineManager.CreatePipelineStateObject(psoDesc, "MsaaChunkPso");

            UploadTextures();

            Chunks = new[] { new RenderChunk() };
            Chunks[0].Chunk.Blocks       = new Block?[Width * Height * Depth];
            Chunks[0].Chunk.NeedsRebuild = true;

            var rng = new Random();

            foreach (ref readonly var block in Chunks[0].Chunk.Blocks.Span)
            {
                Unsafe.AsRef(in block) = new Block {
                    TextureId = (uint)rng.Next(0, _textures.Length)
                };
            }

            SetConstants();
        }
Esempio n. 32
0
        private void BuildDescriptorHeaps()
        {
            //
            // Create the SRV heap.
            //
            var srvHeapDesc = new DescriptorHeapDescription
            {
                DescriptorCount = 5,
                Type            = DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView,
                Flags           = DescriptorHeapFlags.ShaderVisible
            };

            _srvDescriptorHeap = Device.CreateDescriptorHeap(srvHeapDesc);
            _descriptorHeaps   = new[] { _srvDescriptorHeap };

            //
            // Fill out the heap with actual descriptors.
            //
            CpuDescriptorHandle hDescriptor = _srvDescriptorHeap.CPUDescriptorHandleForHeapStart;

            Resource[] tex2DList =
            {
                _textures["bricksDiffuseMap"].Resource,
                _textures["tileDiffuseMap"].Resource,
                _textures["defaultDiffuseMap"].Resource
            };
            Resource skyTex = _textures["skyCubeMap"].Resource;

            var srvDesc = new ShaderResourceViewDescription
            {
                Shader4ComponentMapping = D3DUtil.DefaultShader4ComponentMapping,
                Dimension = ShaderResourceViewDimension.Texture2D,
                Texture2D = new ShaderResourceViewDescription.Texture2DResource
                {
                    MostDetailedMip     = 0,
                    ResourceMinLODClamp = 0.0f
                }
            };

            foreach (Resource tex2D in tex2DList)
            {
                srvDesc.Format = tex2D.Description.Format;
                srvDesc.Texture2D.MipLevels = tex2D.Description.MipLevels;
                Device.CreateShaderResourceView(tex2D, srvDesc, hDescriptor);

                // Next descriptor.
                hDescriptor += CbvSrvUavDescriptorSize;
            }

            srvDesc.Dimension   = ShaderResourceViewDimension.TextureCube;
            srvDesc.TextureCube = new ShaderResourceViewDescription.TextureCubeResource
            {
                MostDetailedMip     = 0,
                MipLevels           = skyTex.Description.MipLevels,
                ResourceMinLODClamp = 0.0f
            };
            srvDesc.Format = skyTex.Description.Format;
            Device.CreateShaderResourceView(skyTex, srvDesc, hDescriptor);

            _skyTexHeapIndex = 3;
        }
Esempio n. 33
0
        // Todo: functions similar to https://msdn.microsoft.com/en-us/library/windows/desktop/dn770363%28v=vs.85%29.aspx
        // Should be checked in various functions.

        #endregion

        #region Descriptor functions

        /// <summary>
        /// Copies descriptors from a source to a destination.
        /// </summary>
        public void CopyDescriptors(DescriptorHeap source, DescriptorHeap destination, Tuple <uint>[] rangeStarts, uint numDescriptors)
        {
            throw new NotImplementedException();
            CopyDescriptorsImpl(source, destination, rangeStarts, numDescriptors);
        }
Esempio n. 34
0
        //创建设备
        private void LoadPipeline(SharpDX.Windows.RenderForm form)
        {
            width  = form.ClientSize.Width;
            height = form.ClientSize.Height;

            //创建视口
            viewPort = new ViewportF(0, 0, width, height);

            //创建裁剪矩形
            scissorRectangle = new Rectangle(0, 0, width, height);

#if DEBUG
            //启用调试层
            {
                DebugInterface.Get().EnableDebugLayer();
            }
#endif
            device = new Device(null, SharpDX.Direct3D.FeatureLevel.Level_11_0);
            //工厂化
            using (var factory = new Factory4())
            {
                //创建命令队列
                CommandQueueDescription queueDesc = new CommandQueueDescription(CommandListType.Direct);
                commandQueue = device.CreateCommandQueue(queueDesc);

                //创建交换链
                SwapChainDescription swapChainDesc = new SwapChainDescription()
                {
                    BufferCount     = FrameCount,
                    ModeDescription = new ModeDescription(
                        width, height,                               //缓存大小,一般与窗口大小相同
                        new Rational(60, 1),                         //刷新率,60hz
                        Format.R8G8B8A8_UNorm),                      //像素格式,8位RGBA格式
                    Usage             = Usage.RenderTargetOutput,    //CPU访问缓冲权限
                    SwapEffect        = SwapEffect.FlipDiscard,      //描述处理曲面后的缓冲区内容
                    OutputHandle      = form.Handle,                 //获取渲染窗口句柄
                    Flags             = SwapChainFlags.None,         //描述交换链的行为
                    SampleDescription = new SampleDescription(1, 0), //一重采样
                    IsWindowed        = true                         //true为窗口显示,false为全屏显示
                };

                //创建交换链
                SwapChain tempSwapChain = new SwapChain(factory, commandQueue, swapChainDesc);
                swapChain = tempSwapChain.QueryInterface <SwapChain3>();
                tempSwapChain.Dispose();
                frameIndex = swapChain.CurrentBackBufferIndex;//获取交换链的当前缓冲区的索引
            }

            //创建描述符堆
            //创建一个渲染目标视图(RTV)的描述符堆
            DescriptorHeapDescription rtvHeapDesc = new DescriptorHeapDescription()
            {
                DescriptorCount = FrameCount,                         //堆中的描述符数
                Flags           = DescriptorHeapFlags.None,           //结果值指定符堆,None表示堆的默认用法
                Type            = DescriptorHeapType.RenderTargetView //堆中的描述符类型
            };
            renderTargetViewHeap = device.CreateDescriptorHeap(rtvHeapDesc);

            //获取给定类型的描述符堆的句柄增量的大小,将句柄按正确的数量递增到描述符数组中
            rtvDescriptorSize = device.GetDescriptorHandleIncrementSize(DescriptorHeapType.RenderTargetView);

            //创建一个CBV的描述符堆
            var cbvHeapDesc = new DescriptorHeapDescription()
            {
                DescriptorCount = 1,
                Flags           = DescriptorHeapFlags.ShaderVisible,
                Type            = DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView
            };
            constantBufferViewHeap = device.CreateDescriptorHeap(cbvHeapDesc);
            //创建一个SRV的描述符堆
            var srvHeapDesc = new DescriptorHeapDescription()
            {
                DescriptorCount = 1,
                Flags           = DescriptorHeapFlags.ShaderVisible,
                Type            = DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView
            };
            shaderRenderViewHeap = device.CreateDescriptorHeap(srvHeapDesc);
            srvDescriptorSize    = device.GetDescriptorHandleIncrementSize(DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView);
            //构建资源描述符来填充描述符堆
            //获取指向描述符堆起始处的指针
            CpuDescriptorHandle srvHandle = shaderRenderViewHeap.CPUDescriptorHandleForHeapStart;

            //创建渲染目标视图
            //获取堆中起始的CPU描述符句柄,for循环为交换链中的每一个缓冲区都创建了一个RTV(渲染目标视图)
            CpuDescriptorHandle rtvHandle = renderTargetViewHeap.CPUDescriptorHandleForHeapStart;
            for (int n = 0; n < FrameCount; n++)
            {
                //获得交换链的第n个缓冲区
                renderTargets[n] = swapChain.GetBackBuffer <Resource>(n);
                device.CreateRenderTargetView(
                    renderTargets[n], //指向渲染目标对象的指针
                    null,             //指向描述渲染目标视图结构的指针
                    rtvHandle);       //CPU描述符句柄,表示渲染目标视图的堆的开始
                rtvHandle += rtvDescriptorSize;
            }

            //创建命令分配器对象
            commandAllocator = device.CreateCommandAllocator(CommandListType.Direct);
            bundleAllocator  = device.CreateCommandAllocator(CommandListType.Bundle);
        }
Esempio n. 35
0
 protected abstract void CopyDescriptorsImpl(DescriptorHeap source, DescriptorHeap destination, Tuple <uint>[] rangeStarts, uint numDescriptors);
Esempio n. 36
0
        private void CreateWindowResources()
        {
            // Wait until all previous GPU work is complete.
            WaitForGPU();

            // Clear the previous window size specific content.
            for (int i = 0; i < FrameCount; i++)
            {
                renderTargets[i] = null;
            }

            // Calculate the necessary render target size in pixels.
            var outputSize = new Size2();

            outputSize.Width  = window.ClientSize.Width;
            outputSize.Height = window.ClientSize.Height;

            // Prevent zero size DirectX content from being created.
            outputSize.Width  = Math.Max(outputSize.Width, 640);
            outputSize.Height = Math.Max(outputSize.Width, 480);

            if (swapChain != null)
            {
                // If the swap chain already exists, resize it.
                swapChain.ResizeBuffers(FrameCount, outputSize.Width, outputSize.Height, Format.B8G8R8A8_UNorm, SwapChainFlags.None);

                if (!DXDebug.ValidateDevice(device))
                {
                    throw new ArgumentNullException(nameof(device));
                }
            }
            else
            {
                using (var factory = new Factory4())
                {
                    // Otherwise, create a new one using the same adapter as the existing Direct3D device.
                    SwapChainDescription swapChainDesc = new SwapChainDescription()
                    {
                        BufferCount       = FrameCount,
                        ModeDescription   = new ModeDescription(outputSize.Width, outputSize.Height, new Rational(60, 1), Format.R8G8B8A8_UNorm),
                        Usage             = Usage.RenderTargetOutput,
                        SwapEffect        = SwapEffect.FlipDiscard,
                        OutputHandle      = window.Handle,
                        SampleDescription = new SampleDescription(1, 0),
                        IsWindowed        = true,
                    };

                    var tempSwapChain = new SwapChain(factory, commandQueue, swapChainDesc);
                    swapChain           = tempSwapChain.QueryInterface <SwapChain3>();
                    swapChain.DebugName = "SwapChain";
                    tempSwapChain.Dispose();
                }
            }

            // Create a render target view of the swap chain back buffer.
            var descriptorHeapDesc = new DescriptorHeapDescription()
            {
                DescriptorCount = FrameCount,
                Type            = DescriptorHeapType.RenderTargetView,
                Flags           = DescriptorHeapFlags.None
            };

            rtvHeap      = device.CreateDescriptorHeap(descriptorHeapDesc);
            rtvHeap.Name = "Render Target View Descriptor Heap";

            // All pending GPU work was already finished. Update the tracked fence values
            // to the last value signaled.
            for (int i = 0; i < FrameCount; i++)
            {
                fenceValues[i] = fenceValues[currentFrame];
            }

            currentFrame = 0;
            var rtvDescriptor = rtvHeap.CPUDescriptorHandleForHeapStart;

            rtvDescriptorSize = device.GetDescriptorHandleIncrementSize(DescriptorHeapType.RenderTargetView);
            for (int i = 0; i < FrameCount; i++)
            {
                renderTargets[i] = swapChain.GetBackBuffer <Resource>(i);
                device.CreateRenderTargetView(renderTargets[i], null, rtvDescriptor + (rtvDescriptorSize * i));

                renderTargets[i].Name = $"Render Target {i}";
            }

            viewport          = new ViewportF();
            viewport.Width    = outputSize.Width;
            viewport.Height   = outputSize.Height;
            viewport.MaxDepth = 1.0f;

            scissorRect        = new Rectangle();
            scissorRect.Right  = outputSize.Width;
            scissorRect.Bottom = outputSize.Height;
        }
Esempio n. 37
0
 protected abstract void CreateRenderTargetViewImpl(DescriptorHeap target, uint descriptorHeapSlot, Resource resource, ref RenderTargetViewDescription description);
Esempio n. 38
0
        public void BuildPSO(Device3 device, GraphicsCommandList commandList)
        {
            World        = Matrix.Translation(-2.5f, -2.5f, -2.5f);
            buffer.World = World;
            light        = new Lighting
            {
                GlobalAmbientX = 1,
                GlobalAmbientY = 1,
                GlobalAmbientZ = 1,
                KaX            = .1f,
                KaY            = .1f,
                KaZ            = .1f,
                KdX            = .5f,
                KdY            = .5f,
                KdZ            = .5f,
                KeX            = .25f,
                KeY            = .25f,
                KeZ            = .25f,
                KsX            = .1f,
                KsY            = .1f,
                KsZ            = .1f,
                LightColorX    = 1,
                LightColorY    = 1,
                LightColorZ    = 1,
                LightPositionX = 10,
                LightPositionY = 10,
                LightPositionZ = 10,
                shininess      = 5
            };

            DescriptorHeapDescription srvHeapDesc = new DescriptorHeapDescription()
            {
                DescriptorCount = 1,
                Flags           = DescriptorHeapFlags.ShaderVisible,
                Type            = DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView
            };

            _srvDescriptorHeap = device.CreateDescriptorHeap(srvHeapDesc);

            //setup descriptor ranges
            DescriptorRange[] ranges = new DescriptorRange[] { new DescriptorRange()
                                                               {
                                                                   RangeType = DescriptorRangeType.ShaderResourceView, DescriptorCount = 1, OffsetInDescriptorsFromTableStart = int.MinValue, BaseShaderRegister = 0
                                                               } };

            //Get sampler state setup
            StaticSamplerDescription sampler = new StaticSamplerDescription()
            {
                Filter           = Filter.MinimumMinMagMipPoint,
                AddressU         = TextureAddressMode.Border,
                AddressV         = TextureAddressMode.Border,
                AddressW         = TextureAddressMode.Border,
                MipLODBias       = 0,
                MaxAnisotropy    = 0,
                ComparisonFunc   = Comparison.Never,
                BorderColor      = StaticBorderColor.TransparentBlack,
                MinLOD           = 0.0f,
                MaxLOD           = float.MaxValue,
                ShaderRegister   = 0,
                RegisterSpace    = 0,
                ShaderVisibility = ShaderVisibility.Pixel,
            };

            Projection = Matrix.PerspectiveFovLH((float)Math.PI / 3f, 4f / 3f, 1, 1000);
            View       = Matrix.LookAtLH(new Vector3(10 * (float)Math.Sin(rotation), 5, 10 * (float)Math.Cos(rotation)), Vector3.Zero, Vector3.UnitY);
            World      = Matrix.Translation(-2.5f, -2.5f, -2.5f);

            DescriptorHeapDescription cbvHeapDesc = new DescriptorHeapDescription()
            {
                DescriptorCount = 1,
                Flags           = DescriptorHeapFlags.ShaderVisible,
                Type            = DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView
            };

            _objectViewHeap   = device.CreateDescriptorHeap(cbvHeapDesc);
            _lightingViewHeap = device.CreateDescriptorHeap(cbvHeapDesc);

            RootParameter[] rootParameters = new RootParameter[] { new RootParameter(ShaderVisibility.Pixel, ranges),
                                                                   new RootParameter(ShaderVisibility.All, new RootDescriptor(1, 0), RootParameterType.ConstantBufferView),
                                                                   new RootParameter(ShaderVisibility.All, new RootDescriptor(2, 0), RootParameterType.ConstantBufferView) };


            // Create an empty root signature.
            RootSignatureDescription rootSignatureDesc = new RootSignatureDescription(RootSignatureFlags.AllowInputAssemblerInputLayout, rootParameters, new StaticSamplerDescription[] { sampler });

            _rootSignature = device.CreateRootSignature(rootSignatureDesc.Serialize());

            // Create the pipeline state, which includes compiling and loading shaders.

#if DEBUG
            var vertexShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("Shaders/LitVertex.hlsl", "VSMain", "vs_5_0", SharpDX.D3DCompiler.ShaderFlags.Debug));
#else
            var vertexShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("Shaders/LitVertex.hlsl", "VSMain", "vs_5_0"));
#endif

#if DEBUG
            var pixelShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("Shaders/LitVertex.hlsl", "PSMain", "ps_5_0", SharpDX.D3DCompiler.ShaderFlags.Debug));
#else
            var pixelShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("Shaders/LitVertex.hlsl", "PSMain", "ps_5_0"));
#endif

            // Define the vertex input layout.
            InputElement[] inputElementDescs = new InputElement[]
            {
                new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0),
                new InputElement("NORMAL", 0, Format.R32G32B32_Float, 12, 0),
                new InputElement("TEXCOORD", 0, Format.R32G32_Float, 24, 0)
            };

            // Describe and create the graphics pipeline state object (PSO).
            GraphicsPipelineStateDescription psoDesc = new GraphicsPipelineStateDescription()
            {
                InputLayout           = new InputLayoutDescription(inputElementDescs),
                RootSignature         = _rootSignature,
                VertexShader          = vertexShader,
                PixelShader           = pixelShader,
                RasterizerState       = RasterizerStateDescription.Default(),
                BlendState            = BlendStateDescription.Default(),
                DepthStencilFormat    = SharpDX.DXGI.Format.D24_UNorm_S8_UInt,
                DepthStencilState     = DepthStencilStateDescription.Default(),
                SampleMask            = int.MaxValue,
                PrimitiveTopologyType = PrimitiveTopologyType.Triangle,
                RenderTargetCount     = 1,
                Flags             = PipelineStateFlags.None,
                SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0),
                StreamOutput      = new StreamOutputDescription()
            };
            psoDesc.RenderTargetFormats[0] = SharpDX.DXGI.Format.R8G8B8A8_UNorm;

            _pipelineState = device.CreateGraphicsPipelineState(psoDesc);

            // Define the geometry for a triangle.
            Vertex[] triangleVertices = new Vertex[]
            {
                //Front
                new Vertex()
                {
                    Position = new Vector3(0, 0, 0), TexCoord = new Vector2(1, 1), Normal = -Vector3.UnitZ
                },
                new Vertex()
                {
                    Position = new Vector3(0, 5, 0), TexCoord = new Vector2(1, 0), Normal = -Vector3.UnitZ
                },
                new Vertex()
                {
                    Position = new Vector3(5, 0, 0), TexCoord = new Vector2(0, 1), Normal = -Vector3.UnitZ
                },
                new Vertex()
                {
                    Position = new Vector3(5, 5, 0), TexCoord = new Vector2(0, 0), Normal = -Vector3.UnitZ
                },

                //Back
                new Vertex()
                {
                    Position = new Vector3(0, 0, 5), TexCoord = new Vector2(1, 1), Normal = Vector3.UnitZ
                },
                new Vertex()
                {
                    Position = new Vector3(0, 5, 5), TexCoord = new Vector2(1, 0), Normal = Vector3.UnitZ
                },
                new Vertex()
                {
                    Position = new Vector3(5, 0, 5), TexCoord = new Vector2(0, 1), Normal = Vector3.UnitZ
                },
                new Vertex()
                {
                    Position = new Vector3(5, 5, 5), TexCoord = new Vector2(0, 0), Normal = Vector3.UnitZ
                },

                //Left
                new Vertex()
                {
                    Position = new Vector3(0, 0, 0), TexCoord = new Vector2(1, 1), Normal = -Vector3.UnitX
                },
                new Vertex()
                {
                    Position = new Vector3(0, 5, 0), TexCoord = new Vector2(1, 0), Normal = -Vector3.UnitX
                },
                new Vertex()
                {
                    Position = new Vector3(0, 0, 5), TexCoord = new Vector2(0, 1), Normal = -Vector3.UnitX
                },
                new Vertex()
                {
                    Position = new Vector3(0, 5, 5), TexCoord = new Vector2(0, 0), Normal = -Vector3.UnitX
                },

                //Right
                new Vertex()
                {
                    Position = new Vector3(5, 0, 0), TexCoord = new Vector2(1, 1), Normal = Vector3.UnitX
                },
                new Vertex()
                {
                    Position = new Vector3(5, 5, 0), TexCoord = new Vector2(1, 0), Normal = Vector3.UnitX
                },
                new Vertex()
                {
                    Position = new Vector3(5, 0, 5), TexCoord = new Vector2(0, 1), Normal = Vector3.UnitX
                },
                new Vertex()
                {
                    Position = new Vector3(5, 5, 5), TexCoord = new Vector2(0, 0), Normal = Vector3.UnitX
                },

                //Top
                new Vertex()
                {
                    Position = new Vector3(0, 0, 0), TexCoord = new Vector2(1, 1), Normal = -Vector3.UnitY
                },
                new Vertex()
                {
                    Position = new Vector3(0, 0, 5), TexCoord = new Vector2(1, 0), Normal = -Vector3.UnitY
                },
                new Vertex()
                {
                    Position = new Vector3(5, 0, 0), TexCoord = new Vector2(0, 1), Normal = -Vector3.UnitY
                },
                new Vertex()
                {
                    Position = new Vector3(5, 0, 5), TexCoord = new Vector2(0, 0), Normal = -Vector3.UnitY
                },

                //Bottom
                new Vertex()
                {
                    Position = new Vector3(0, 5, 0), TexCoord = new Vector2(1, 1), Normal = Vector3.UnitY
                },
                new Vertex()
                {
                    Position = new Vector3(0, 5, 5), TexCoord = new Vector2(1, 0), Normal = Vector3.UnitY
                },
                new Vertex()
                {
                    Position = new Vector3(5, 5, 0), TexCoord = new Vector2(0, 1), Normal = Vector3.UnitY
                },
                new Vertex()
                {
                    Position = new Vector3(5, 5, 5), TexCoord = new Vector2(0, 0), Normal = Vector3.UnitY
                }
            };

            int vertexBufferSize = Utilities.SizeOf(triangleVertices);

            // Note: using upload heaps to transfer static data like vert buffers is not
            // recommended. Every time the GPU needs it, the upload heap will be marshalled
            // over. Please read up on Default Heap usage. An upload heap is used here for
            // code simplicity and because there are very few verts to actually transfer.
            _vertexBuffer = device.CreateCommittedResource(new HeapProperties(HeapType.Upload), HeapFlags.None, ResourceDescription.Buffer(vertexBufferSize), ResourceStates.GenericRead);

            // Copy the triangle data to the vertex buffer.
            IntPtr pVertexDataBegin = _vertexBuffer.Map(0);
            Utilities.Write(pVertexDataBegin, triangleVertices, 0, triangleVertices.Length);
            _vertexBuffer.Unmap(0);

            _indicies = new int[] { 0, 1, 2,
                                    3, 2, 1,
                                    6, 5, 4,
                                    5, 6, 7,

                                    10, 9, 8,
                                    9, 10, 11,
                                    12, 13, 14,
                                    15, 14, 13,

                                    18, 17, 16,
                                    17, 18, 19,
                                    20, 21, 22,
                                    23, 22, 21 };

            int indBufferSize = Utilities.SizeOf(_indicies);

            _indexBuffer = device.CreateCommittedResource(new HeapProperties(HeapType.Upload), HeapFlags.None, ResourceDescription.Buffer(indBufferSize), ResourceStates.GenericRead);

            IntPtr pIndBegin = _indexBuffer.Map(0);
            Utilities.Write(pIndBegin, _indicies, 0, _indicies.Length);
            _indexBuffer.Unmap(0);

            _indexBufferView = new IndexBufferView()
            {
                BufferLocation = _indexBuffer.GPUVirtualAddress,
                Format         = Format.R32_UInt,
                SizeInBytes    = indBufferSize
            };

            // Initialize the vertex buffer view.
            _vertexBufferView = new VertexBufferView
            {
                BufferLocation = _vertexBuffer.GPUVirtualAddress,
                StrideInBytes  = Utilities.SizeOf <Vertex>(),
                SizeInBytes    = vertexBufferSize
            };

            _objectBuffer = device.CreateCommittedResource(new HeapProperties(HeapType.Upload), HeapFlags.None, ResourceDescription.Buffer(Utilities.SizeOf <ObjectData>()), ResourceStates.GenericRead);

            //// Describe and create a constant buffer view.
            ConstantBufferViewDescription cbvDesc = new ConstantBufferViewDescription()
            {
                BufferLocation = _objectBuffer.GPUVirtualAddress,
                SizeInBytes    = (Utilities.SizeOf <ObjectData>() + 255) & ~255
            };
            device.CreateConstantBufferView(cbvDesc, _objectViewHeap.CPUDescriptorHandleForHeapStart);

            // Initialize and map the constant buffers. We don't unmap this until the
            // app closes. Keeping things mapped for the lifetime of the resource is okay.
            _objectPointer = _objectBuffer.Map(0);
            Utilities.Write(_objectPointer, ref buffer);

            _lightingBuffer = device.CreateCommittedResource(new HeapProperties(HeapType.Upload), HeapFlags.None, ResourceDescription.Buffer(Utilities.SizeOf <Lighting>()), ResourceStates.GenericRead);

            //// Describe and create a constant buffer view.
            ConstantBufferViewDescription cbvDesc2 = new ConstantBufferViewDescription()
            {
                BufferLocation = _objectBuffer.GPUVirtualAddress,
                SizeInBytes    = (Utilities.SizeOf <Lighting>() + 255) & ~255
            };
            device.CreateConstantBufferView(cbvDesc2, _lightingViewHeap.CPUDescriptorHandleForHeapStart);

            // Initialize and map the constant buffers. We don't unmap this until the
            // app closes. Keeping things mapped for the lifetime of the resource is okay.
            _lightingPointer = _lightingBuffer.Map(0);
            Utilities.Write(_lightingPointer, ref light);

            Resource textureUploadHeap;

            // Create the texture.
            // Describe and create a Texture2D.
            ResourceDescription textureDesc = ResourceDescription.Texture2D(Format.R8G8B8A8_UNorm, textureWidth, textureHeight);
            _texture = device.CreateCommittedResource(new HeapProperties(HeapType.Default), HeapFlags.None, textureDesc, ResourceStates.CopyDestination);

            long uploadBufferSize = GetRequiredIntermediateSize(device, _texture, 0, 1);

            // Create the GPU upload buffer.
            textureUploadHeap = device.CreateCommittedResource(new HeapProperties(CpuPageProperty.WriteBack, MemoryPool.L0), HeapFlags.None, ResourceDescription.Texture2D(Format.R8G8B8A8_UNorm, textureWidth, textureHeight), ResourceStates.GenericRead);

            // Copy data to the intermediate upload heap and then schedule a copy
            // from the upload heap to the Texture2D.
            byte[] textureData = GenerateTextureData();

            GCHandle handle = GCHandle.Alloc(textureData, GCHandleType.Pinned);
            IntPtr   ptr    = Marshal.UnsafeAddrOfPinnedArrayElement(textureData, 0);
            textureUploadHeap.WriteToSubresource(0, null, ptr, 4 * textureWidth, textureData.Length);
            handle.Free();

            commandList.CopyTextureRegion(new TextureCopyLocation(_texture, 0), 0, 0, 0, new TextureCopyLocation(textureUploadHeap, 0), null);

            commandList.ResourceBarrierTransition(_texture, ResourceStates.CopyDestination, ResourceStates.PixelShaderResource);

            // Describe and create a SRV for the texture.
            ShaderResourceViewDescription srvDesc = new ShaderResourceViewDescription()
            {
                Shader4ComponentMapping = ComponentMapping(0, 1, 2, 3),
                Format    = textureDesc.Format,
                Dimension = ShaderResourceViewDimension.Texture2D,
            };
            srvDesc.Texture2D.MipLevels = 1;

            device.CreateShaderResourceView(_texture, srvDesc, _srvDescriptorHeap.CPUDescriptorHandleForHeapStart);

            _resources = new[] { new GraphicsResource()
                                 {
                                     Heap = _srvDescriptorHeap, Register = 0, type = ResourceType.DescriptorTable
                                 },
                                 new GraphicsResource()
                                 {
                                     Resource = _objectBuffer, Register = 2, type = ResourceType.ConstantBufferView
                                 },
                                 new GraphicsResource()
                                 {
                                     Resource = _lightingBuffer, Register = 1, type = ResourceType.ConstantBufferView
                                 } };
        }
        private void LoadAssets()
        {
            DescriptorRange[] ranges = new DescriptorRange[] { new DescriptorRange() { RangeType = DescriptorRangeType.ConstantBufferView, BaseShaderRegister = 0, DescriptorCount = 1 } };
            RootParameter parameter = new RootParameter(ShaderVisibility.Vertex, ranges);

            // Create a root signature.
            RootSignatureDescription rootSignatureDesc = new RootSignatureDescription(RootSignatureFlags.AllowInputAssemblerInputLayout, new RootParameter[] { parameter });
            rootSignature = device.CreateRootSignature(rootSignatureDesc.Serialize());

            // Create the pipeline state, which includes compiling and loading shaders.

            #if DEBUG
            var vertexShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("shaders.hlsl", "VSMain", "vs_5_0", SharpDX.D3DCompiler.ShaderFlags.Debug));
            #else
            var vertexShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("shaders.hlsl", "VSMain", "vs_5_0"));
            #endif

            #if DEBUG
            var pixelShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("shaders.hlsl", "PSMain", "ps_5_0", SharpDX.D3DCompiler.ShaderFlags.Debug));
            #else
            var pixelShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("shaders.hlsl", "PSMain", "ps_5_0"));
            #endif

            // Define the vertex input layout.
            InputElement[] inputElementDescs = new InputElement[]
            {
                    new InputElement("POSITION",0,Format.R32G32B32_Float,0,0),
                    new InputElement("COLOR",0,Format.R32G32B32A32_Float,12,0)
            };

            // Describe and create the graphics pipeline state object (PSO).
            GraphicsPipelineStateDescription psoDesc = new GraphicsPipelineStateDescription()
            {
                InputLayout = new InputLayoutDescription(inputElementDescs),
                RootSignature = rootSignature,
                VertexShader = vertexShader,
                PixelShader = pixelShader,
                RasterizerState = RasterizerStateDescription.Default(),
                BlendState = BlendStateDescription.Default(),
                DepthStencilFormat = SharpDX.DXGI.Format.D32_Float,
                DepthStencilState = DepthStencilStateDescription.Default(),
                SampleMask = int.MaxValue,
                PrimitiveTopologyType = PrimitiveTopologyType.Triangle,
                RenderTargetCount = 1,
                Flags = PipelineStateFlags.None,
                SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0),
                StreamOutput = new StreamOutputDescription()
            };
            psoDesc.RenderTargetFormats[0] = SharpDX.DXGI.Format.R8G8B8A8_UNorm;

            pipelineState = device.CreateGraphicsPipelineState(psoDesc);

            // Create the command list.
            commandList = device.CreateCommandList(CommandListType.Direct, commandAllocator, pipelineState);

            // Command lists are created in the recording state, but there is nothing
            // to record yet. The main loop expects it to be closed, so close it now.
            commandList.Close();

            // Create the vertex buffer.
            float aspectRatio = viewport.Width / viewport.Height;

            // Define the geometry for a cube.

            Vertex[] vertices = new[]
            {
                ////TOP
                new Vertex(new Vector3(-5,5,5),new Vector4(0,1,0,0)),
                new Vertex(new Vector3(5,5,5),new Vector4(0,1,0,0)),
                new Vertex(new Vector3(5,5,-5),new Vector4(0,1,0,0)),
                new Vertex(new Vector3(-5,5,-5),new Vector4(0,1,0,0)),
                //BOTTOM
                new Vertex(new Vector3(-5,-5,5),new Vector4(1,0,1,1)),
                new Vertex(new Vector3(5,-5,5),new Vector4(1,0,1,1)),
                new Vertex(new Vector3(5,-5,-5),new Vector4(1,0,1,1)),
                new Vertex(new Vector3(-5,-5,-5),new Vector4(1,0,1,1)),
                //LEFT
                new Vertex(new Vector3(-5,-5,5),new Vector4(1,0,0,1)),
                new Vertex(new Vector3(-5,5,5),new Vector4(1,0,0,1)),
                new Vertex(new Vector3(-5,5,-5),new Vector4(1,0,0,1)),
                new Vertex(new Vector3(-5,-5,-5),new Vector4(1,0,0,1)),
                //RIGHT
                new Vertex(new Vector3(5,-5,5),new Vector4(1,1,0,1)),
                new Vertex(new Vector3(5,5,5),new Vector4(1,1,0,1)),
                new Vertex(new Vector3(5,5,-5),new Vector4(1,1,0,1)),
                new Vertex(new Vector3(5,-5,-5),new Vector4(1,1,0,1)),
                //FRONT
                new Vertex(new Vector3(-5,5,5),new Vector4(0,1,1,1)),
                new Vertex(new Vector3(5,5,5),new Vector4(0,1,1,1)),
                new Vertex(new Vector3(5,-5,5),new Vector4(0,1,1,1)),
                new Vertex(new Vector3(-5,-5,5),new Vector4(0,1,1,1)),
                //BACK
                new Vertex(new Vector3(-5,5,-5),new Vector4(0,0,1,1)),
                new Vertex(new Vector3(5,5,-5),new Vector4(0,0,1,1)),
                new Vertex(new Vector3(5,-5,-5),new Vector4(0,0,1,1)),
                new Vertex(new Vector3(-5,-5,-5),new Vector4(0,0,1,1))
            };

            int vertexBufferSize = Utilities.SizeOf(vertices);

            // Note: using upload heaps to transfer static data like vert buffers is not
            // recommended. Every time the GPU needs it, the upload heap will be marshalled
            // over. Please read up on Default Heap usage. An upload heap is used here for
            // code simplicity and because there are very few verts to actually transfer.
            vertexBuffer = device.CreateCommittedResource(new HeapProperties(HeapType.Upload), HeapFlags.None, ResourceDescription.Buffer(vertexBufferSize), ResourceStates.GenericRead);

            // Copy the triangle data to the vertex buffer.
            IntPtr pVertexDataBegin = vertexBuffer.Map(0);
            Utilities.Write(pVertexDataBegin, vertices, 0, vertices.Length);
            vertexBuffer.Unmap(0);

            // Initialize the vertex buffer view.
            vertexBufferView = new VertexBufferView();
            vertexBufferView.BufferLocation = vertexBuffer.GPUVirtualAddress;
            vertexBufferView.StrideInBytes = Utilities.SizeOf<Vertex>();
            vertexBufferView.SizeInBytes = vertexBufferSize;

            //Create Index Buffer
            //Indices
            int[] indices = new int[]
            {
                0,1,2,0,2,3,
                4,6,5,4,7,6,
                8,9,10,8,10,11,
                12,14,13,12,15,14,
                16,18,17,16,19,18,
                20,21,22,20,22,23
            };
            int indexBufferSize = Utilities.SizeOf(indices);

            indexBuffer = device.CreateCommittedResource(new HeapProperties(HeapType.Upload), HeapFlags.None, ResourceDescription.Buffer(indexBufferSize), ResourceStates.GenericRead);

            // Copy the triangle data to the vertex buffer.
            IntPtr pIndexDataBegin = indexBuffer.Map(0);
            Utilities.Write(pIndexDataBegin, indices, 0, indices.Length);
            indexBuffer.Unmap(0);

            // Initialize the index buffer view.
            indexBufferView = new IndexBufferView();
            indexBufferView.BufferLocation = indexBuffer.GPUVirtualAddress;
            indexBufferView.Format = Format.R32_UInt;
            indexBufferView.SizeInBytes = indexBufferSize;

            //constant Buffer for each cubes
            constantBufferViewHeap = device.CreateDescriptorHeap(new DescriptorHeapDescription()
            {
                DescriptorCount = NumCubes,
                Type = DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView,
                Flags = DescriptorHeapFlags.ShaderVisible
            });

            int constantBufferSize = (Utilities.SizeOf<Transform>() + 255) & ~255;
            constantBuffer = device.CreateCommittedResource(new HeapProperties(HeapType.Upload), HeapFlags.None, ResourceDescription.Buffer(constantBufferSize * NumCubes), ResourceStates.GenericRead);
            constantBufferDescriptorSize = device.GetDescriptorHandleIncrementSize(DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView);

            //First cube
            ConstantBufferViewDescription cbvDesc = new ConstantBufferViewDescription()
            {
                BufferLocation = constantBuffer.GPUVirtualAddress,
                SizeInBytes = constantBufferSize
            };

            CpuDescriptorHandle cbHandleHeapStart = constantBufferViewHeap.CPUDescriptorHandleForHeapStart;

            for (int i = 0; i < NumCubes; i++)
            {
                device.CreateConstantBufferView(cbvDesc, cbHandleHeapStart);
                cbvDesc.BufferLocation += Utilities.SizeOf<Transform>();
                cbHandleHeapStart += constantBufferDescriptorSize;
            }

            InitBundles();
        }
Esempio n. 40
0
        public GpuDescriptorHandle GetGpuDescriptorHandle(CpuDescriptorHandle descriptor)
        {
            if (!DescriptorHeap.Description.Flags.HasFlag(DescriptorHeapFlags.ShaderVisible))
            {
                throw new InvalidOperationException();
            }

            return(DescriptorHeap.GetGPUDescriptorHandleForHeapStart() + (descriptor.Ptr - DescriptorHeap.GetCPUDescriptorHandleForHeapStart().Ptr));
        }
        private void LoadPipeline(RenderForm form)
        {
            int width = form.ClientSize.Width;
            int height = form.ClientSize.Height;

            viewport.Width = width;
            viewport.Height = height;
            viewport.MaxDepth = 1.0f;

            scissorRect.Right = width;
            scissorRect.Bottom = height;

            #if DEBUG
            // Enable the D3D12 debug layer.
            {
                DebugInterface.Get().EnableDebugLayer();
            }
            #endif
            device = new Device(null, SharpDX.Direct3D.FeatureLevel.Level_11_0);
            using (var factory = new Factory4())
            {
                // Describe and create the command queue.
                CommandQueueDescription queueDesc = new CommandQueueDescription(CommandListType.Direct);
                commandQueue = device.CreateCommandQueue(queueDesc);

                // Describe and create the swap chain.
                SwapChainDescription swapChainDesc = new SwapChainDescription()
                {
                    BufferCount = FrameCount,
                    ModeDescription = new ModeDescription(width, height, new Rational(60, 1), Format.R8G8B8A8_UNorm),
                    Usage = Usage.RenderTargetOutput,
                    SwapEffect = SwapEffect.FlipDiscard,
                    OutputHandle = form.Handle,
                    //Flags = SwapChainFlags.None,
                    SampleDescription = new SampleDescription(1, 0),
                    IsWindowed = true
                };

                SwapChain tempSwapChain = new SwapChain(factory, commandQueue, swapChainDesc);
                swapChain = tempSwapChain.QueryInterface<SwapChain3>();
                tempSwapChain.Dispose();
                frameIndex = swapChain.CurrentBackBufferIndex;
            }

            // Create descriptor heaps.
            // Describe and create a render target view (RTV) descriptor heap.
            DescriptorHeapDescription rtvHeapDesc = new DescriptorHeapDescription()
            {
                DescriptorCount = FrameCount,
                Flags = DescriptorHeapFlags.None,
                Type = DescriptorHeapType.RenderTargetView
            };

            renderTargetViewHeap = device.CreateDescriptorHeap(rtvHeapDesc);

            rtvDescriptorSize = device.GetDescriptorHandleIncrementSize(DescriptorHeapType.RenderTargetView);

            // Create frame resources.
            CpuDescriptorHandle rtvHandle = renderTargetViewHeap.CPUDescriptorHandleForHeapStart;
            for (int n = 0; n < FrameCount; n++)
            {
                renderTargets[n] = swapChain.GetBackBuffer<Resource>(n);
                device.CreateRenderTargetView(renderTargets[n], null, rtvHandle);
                rtvHandle += rtvDescriptorSize;
            }

            //create depth buffer;
            DescriptorHeapDescription dsvHeapDesc = new DescriptorHeapDescription()
            {
                DescriptorCount = FrameCount,
                Flags = DescriptorHeapFlags.None,
                Type = DescriptorHeapType.DepthStencilView
            };
            depthStencilViewHeap = device.CreateDescriptorHeap(dsvHeapDesc);
            CpuDescriptorHandle dsvHandle = depthStencilViewHeap.CPUDescriptorHandleForHeapStart;

            ClearValue depthOptimizedClearValue = new ClearValue()
            {
                Format = Format.D32_Float,
                DepthStencil = new DepthStencilValue() { Depth = 1.0F, Stencil = 0 },
            };

            depthTarget = device.CreateCommittedResource(
                new HeapProperties(HeapType.Default),
                HeapFlags.None,
                new ResourceDescription(ResourceDimension.Texture2D, 0, width, height, 1, 0, Format.D32_Float, 1, 0, TextureLayout.Unknown, ResourceFlags.AllowDepthStencil),
                ResourceStates.DepthWrite, depthOptimizedClearValue);

            var depthView = new DepthStencilViewDescription()
            {
                Format = Format.D32_Float,
                Dimension = DepthStencilViewDimension.Texture2D,
                Flags = DepthStencilViewFlags.None,
            };

            //bind depth buffer
            device.CreateDepthStencilView(depthTarget, null, dsvHandle);

            commandAllocator = device.CreateCommandAllocator(CommandListType.Direct);
            bundleAllocator = device.CreateCommandAllocator(CommandListType.Bundle);
        }
        private void BuildDescriptorHeaps()
        {
            // Offscreen RTV goes after the swap chain descriptors.
            const int rtvOffset = SwapChainBufferCount;

            const int srvCount = 3;

            int waveSrvOffset      = srvCount;
            int sobelSrvOffset     = waveSrvOffset + _waves.DescriptorCount;
            int offscreenSrvOffset = sobelSrvOffset + _sobelFilter.DescriptorCount;

            //
            // Create the SRV heap.
            //
            var srvHeapDesc = new DescriptorHeapDescription
            {
                DescriptorCount = srvCount + _waves.DescriptorCount + _sobelFilter.DescriptorCount + 1, // Extra offscreen render target.
                Type            = DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView,
                Flags           = DescriptorHeapFlags.ShaderVisible
            };

            _srvDescriptorHeap = Device.CreateDescriptorHeap(srvHeapDesc);
            _descriptorHeaps   = new[] { _srvDescriptorHeap };

            //
            // Fill out the heap with actual descriptors.
            //
            CpuDescriptorHandle hDescriptor = _srvDescriptorHeap.CPUDescriptorHandleForHeapStart;

            Resource[] tex2DList =
            {
                _textures["grassTex"].Resource,
                _textures["waterTex"].Resource,
                _textures["fenceTex"].Resource
            };

            var srvDesc = new ShaderResourceViewDescription
            {
                Shader4ComponentMapping = D3DUtil.DefaultShader4ComponentMapping,
                Dimension = ShaderResourceViewDimension.Texture2D,
                Texture2D = new ShaderResourceViewDescription.Texture2DResource
                {
                    MostDetailedMip = 0,
                    MipLevels       = -1,
                }
            };

            foreach (Resource tex2D in tex2DList)
            {
                srvDesc.Format = tex2D.Description.Format;
                Device.CreateShaderResourceView(tex2D, srvDesc, hDescriptor);

                // Next descriptor.
                hDescriptor += CbvSrvUavDescriptorSize;
            }

            CpuDescriptorHandle srvCpuStart = _srvDescriptorHeap.CPUDescriptorHandleForHeapStart;
            GpuDescriptorHandle srvGpuStart = _srvDescriptorHeap.GPUDescriptorHandleForHeapStart;

            CpuDescriptorHandle rtvCpuStart = RtvHeap.CPUDescriptorHandleForHeapStart;

            _waves.BuildDescriptors(
                _srvDescriptorHeap.CPUDescriptorHandleForHeapStart + waveSrvOffset * CbvSrvUavDescriptorSize,
                _srvDescriptorHeap.GPUDescriptorHandleForHeapStart + waveSrvOffset * CbvSrvUavDescriptorSize,
                CbvSrvUavDescriptorSize);

            _sobelFilter.BuildDescriptors(
                srvCpuStart + sobelSrvOffset * CbvSrvUavDescriptorSize,
                srvGpuStart + sobelSrvOffset * CbvSrvUavDescriptorSize,
                CbvSrvUavDescriptorSize);

            _offscreenRT.BuildDescriptors(
                srvCpuStart + offscreenSrvOffset * CbvSrvUavDescriptorSize,
                srvGpuStart + offscreenSrvOffset * CbvSrvUavDescriptorSize,
                rtvCpuStart + rtvOffset * RtvDescriptorSize);
        }
Esempio n. 43
0
        public void AfterEngineInit()
        {
            // Basics.
            {
                var deviceDesc = new Device.Descriptor {
                    DebugDevice = true
                };
                renderDevice = new ClearSight.RendererDX12.Device(ref deviceDesc,
                                                                  ClearSight.RendererDX12.Device.FeatureLevel.Level_11_0);

                var descCQ = new CommandQueue.Descriptor()
                {
                    Type = CommandListType.Graphics
                };
                commandQueue = renderDevice.Create(ref descCQ);

                var wih           = new WindowInteropHelper(window);
                var swapChainDesc = new SwapChain.Descriptor()
                {
                    AssociatedGraphicsQueue = commandQueue,

                    MaxFramesInFlight = 3,
                    BufferCount       = 3,

                    Width  = (uint)window.Width,
                    Height = (uint)window.Height,
                    Format = Format.R8G8B8A8_UNorm,

                    SampleCount   = 1,
                    SampleQuality = 0,

                    WindowHandle = wih.Handle,
                    Fullscreen   = false
                };
                swapChain = renderDevice.Create(ref swapChainDesc);

                var commandListDesc = new CommandList.Descriptor()
                {
                    Type             = CommandListType.Graphics,
                    AllocationPolicy = new CommandListInFlightFrameAllocationPolicy(CommandListType.Graphics, swapChain)
                };
                commandList = renderDevice.Create(ref commandListDesc);
            }

            // Render targets.
            {
                var descHeapDesc = new DescriptorHeap.Descriptor()
                {
                    Type = DescriptorHeap.Descriptor.ResourceDescriptorType.RenderTarget,
                    NumResourceDescriptors = swapChain.Desc.BufferCount
                };
                descHeapRenderTargets = renderDevice.Create(ref descHeapDesc);

                var rtvViewDesc = new RenderTargetViewDescription()
                {
                    Format    = swapChain.Desc.Format,
                    Dimension = Dimension.Texture2D,
                    Texture   = new TextureSubresourceDesc(mipSlice: 0)
                };
                for (uint i = 0; i < swapChain.Desc.BufferCount; ++i)
                {
                    renderDevice.CreateRenderTargetView(descHeapRenderTargets, i, swapChain.BackbufferResources[i], ref rtvViewDesc);
                }
            }
        }
Esempio n. 44
0
        private void LoadAssets()
        {
            // Create the descriptor heap for the render target view
            descriptorHeap = device.CreateDescriptorHeap(new DescriptorHeapDescription()
            {
                Type = DescriptorHeapType.RenderTargetView,
                DescriptorCount = 1
            });

            // Create the main command list
            commandList = device.CreateCommandList(CommandListType.Direct, commandListAllocator, null);

            // Get the backbuffer and creates the render target view
            renderTarget = swapChain.GetBackBuffer<Resource>(0);
            device.CreateRenderTargetView(renderTarget, null, descriptorHeap.CPUDescriptorHandleForHeapStart);

            // Create the viewport
            viewPort = new ViewportF(0, 0, width, height);

            // Create the scissor
            scissorRectangle = new Rectangle(0, 0, width, height);

            // Create a fence to wait for next frame
            fence = device.CreateFence(0, FenceFlags.None);
            currentFence = 1;

            // Close command list
            commandList.Close();

            // Create an event handle use for VTBL
            eventHandle = new AutoResetEvent(false);

            // Wait the command list to complete
            WaitForPrevFrame();
        }
 public void WriteTextureToRAM(DescriptorHeap shaderRenderViewHeap)
 {
     for (TextureType type = TextureType.Diffuse; type < TextureType.Bump; type++)
     {
         if (!HasTexture[type])
         {
             continue;
         }
         WriteTextureToRAM(shaderRenderViewHeap, type);
     }
 }
Esempio n. 46
0
 private protected override void CreateDescriptorHeaps()
 {
     base.CreateDescriptorHeaps();
     _samplers = CreateDescriptorHeap(DescriptorHeapType.Sampler, SamplerCount, true);
 }
 public void WriteTextureToRAM(DescriptorHeap shaderRenderViewHeap, TextureType type)
 {
     var tex = Texture.LoadFromFile(TexturePath[type]);
     var textureData = tex.Data;
     var textureDesc = ResourceDescription.Texture2D(tex.ColorFormat, tex.Width, tex.Height, 1, 1, 1, 0, ResourceFlags.None, TextureLayout.Unknown, 0);
     var texture = Engine.Instance.Core.Device.CreateCommittedResource(
         new HeapProperties(HeapType.Upload),
         HeapFlags.None,
         textureDesc,
         ResourceStates.GenericRead, null);
     var handle = GCHandle.Alloc(textureData, GCHandleType.Pinned);
     var ptr = Marshal.UnsafeAddrOfPinnedArrayElement(textureData, 0);
     texture.WriteToSubresource(0, null, ptr, tex.Width * tex.PixelWdith, textureData.Length);
     Marshal.FreeHGlobal(ptr);
     handle.Free();
     Engine.Instance.Core.Device.CreateShaderResourceView(
         texture,
         new ShaderResourceViewDescription
         {
             Shader4ComponentMapping = ((((0) & 0x7) | (((1) & 0x7) << 3) | (((2) & 0x7) << (3 * 2)) | (((3) & 0x7) << (3 * 3)) | (1 << (3 * 4)))),
             Format = textureDesc.Format,
             Dimension = ShaderResourceViewDimension.Texture2D,
             Texture2D =
             {
                     MipLevels = 1,
                     MostDetailedMip = 0,
                     PlaneSlice = 0,
                     ResourceMinLODClamp = 0.0f
             }
         },
         shaderRenderViewHeap.CPUDescriptorHandleForHeapStart + ViewStep + (int)type * Engine.Instance.Core.Device.GetDescriptorHandleIncrementSize(DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView));
 }