private bool Add(string name, DescriptorHeapDescription description)
 {
     DescriptorHeap d = Engine.Instance.Core.Device.CreateDescriptorHeap(description);
     if (DescriptorHeaps.TryAdd(name, d))
         return true;
     d.Dispose();
     return false;
 }
        private void BuildDescriptorHeaps()
        {
            const int srvCount = 3;

            //
            // Create the SRV heap.
            //
            var srvHeapDesc = new DescriptorHeapDescription
            {
                DescriptorCount = srvCount + _waves.DescriptorCount,
                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;
            }

            _waves.BuildDescriptors(
                _srvDescriptorHeap.CPUDescriptorHandleForHeapStart + srvCount * CbvSrvUavDescriptorSize,
                _srvDescriptorHeap.GPUDescriptorHandleForHeapStart + srvCount * CbvSrvUavDescriptorSize,
                CbvSrvUavDescriptorSize);
        }
示例#3
0
        private bool Add(string name, DescriptorHeapDescription description)
        {
            DescriptorHeap d = Engine.Instance.Core.Device.CreateDescriptorHeap(description);

            if (DescriptorHeaps.TryAdd(name, d))
            {
                return(true);
            }
            d.Dispose();
            return(false);
        }
示例#4
0
            protected override DescriptorHeap Create()
            {
                var description = new DescriptorHeapDescription
                {
                    DescriptorCount = Size,
                    Flags           = DescriptorHeapFlags.ShaderVisible,
                    Type            = HeapType,
                };

                return(Device.NativeDevice.CreateDescriptorHeap(description));
            }
示例#5
0
        private void BuildDescriptorHeaps()
        {
            //
            // Create the SRV heap.
            //
            var srvHeapDesc = new DescriptorHeapDescription
            {
                DescriptorCount = 7,
                Type            = DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView,
                Flags           = DescriptorHeapFlags.ShaderVisible
            };

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

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

            var tex2DList = new List <Resource>
            {
                _textures["bricksTex"].Resource,
                _textures["stoneTex"].Resource,
                _textures["tileTex"].Resource,
                _textures["crateTex"].Resource,
                _textures["iceTex"].Resource,
                _textures["grassTex"].Resource,
                _textures["defaultTex"].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;
            }
        }
示例#6
0
 private void BuildDescriptorHeaps()
 {
     var cbvHeapDesc = new DescriptorHeapDescription
     {
         DescriptorCount = 1,
         Type            = DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView,
         Flags           = DescriptorHeapFlags.ShaderVisible,
         NodeMask        = 0
     };
     //_cbvHeap = Device.CreateDescriptorHeap(cbvHeapDesc);
     //_descriptorHeaps = new[] { _cbvHeap };
 }
        private void BuildDepthBuffer()
        {
            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;
        }
示例#8
0
        public ID3D12DescriptorHeap CreateDescriptorHeap(ID3D12Device5 pDevice, int count, DescriptorHeapType type, bool shaderVisible)
        {
            DescriptorHeapDescription desc = new DescriptorHeapDescription();

            desc.DescriptorCount = count;
            desc.Type            = type;
            desc.Flags           = shaderVisible ? DescriptorHeapFlags.ShaderVisible : DescriptorHeapFlags.None;

            ID3D12DescriptorHeap pHeap;

            pHeap = pDevice.CreateDescriptorHeap(desc);

            return(pHeap);
        }
        public DescriptorAllocator(GraphicsDevice device, DescriptorHeapType descriptorHeapType, int descriptorCount = DescriptorsPerHeap, DescriptorHeapFlags descriptorHeapFlags = DescriptorHeapFlags.None)
        {
            if (descriptorCount < 1 || descriptorCount > DescriptorsPerHeap)
            {
                throw new ArgumentOutOfRangeException(nameof(descriptorCount), $"Descriptor count must be between 1 and {DescriptorsPerHeap}.");
            }

            DescriptorHandleIncrementSize = device.NativeDevice.GetDescriptorHandleIncrementSize((Vortice.Direct3D12.DescriptorHeapType)descriptorHeapType);

            DescriptorHeapDescription descriptorHeapDescription = new DescriptorHeapDescription((Vortice.Direct3D12.DescriptorHeapType)descriptorHeapType, descriptorCount, descriptorHeapFlags);

            DescriptorHeap = device.NativeDevice.CreateDescriptorHeap(descriptorHeapDescription);

            TotalDescriptorCount = descriptorCount;
        }
示例#10
0
        /// <summary>
        /// Creates a new <see cref="DescriptorAllocator"/> instance with the specified parameters
        /// </summary>
        /// <param name="device">The <see cref="GraphicsDevice"/> instance to use</param>
        public DescriptorAllocator(GraphicsDevice device)
        {
            DescriptorSize = device.NativeDevice.GetDescriptorHandleIncrementSize(DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView);

            DescriptorHeapDescription descriptorHeapDescription = new DescriptorHeapDescription
            {
                DescriptorCount = DescriptorsPerHeap,
                Flags           = DescriptorHeapFlags.ShaderVisible,
                Type            = DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView
            };

            DescriptorHeap = device.NativeDevice.CreateDescriptorHeap(descriptorHeapDescription);

            _RemainingHandles = DescriptorsPerHeap;
            _CurrentCpuHandle = DescriptorHeap.GetCPUDescriptorHandleForHeapStart();
            _CurrentGpuHandle = DescriptorHeap.GetGPUDescriptorHandleForHeapStart();
        }
示例#11
0
        private void BuildDescriptorHeaps()
        {
            var cbvHeapDesc = new DescriptorHeapDescription
            {
                DescriptorCount = 2,
                Type            = DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView,
                Flags           = DescriptorHeapFlags.ShaderVisible
            };

            //_cbvHeap.
            //   DXGlobal.device.


            _cbvHeap         = DXGlobal.device.CreateDescriptorHeap(cbvHeapDesc);
            _descriptorHeaps = new[] { _cbvHeap };
            _cheap           = _cbvHeap;
        }
示例#12
0
        /// <summary>
        /// The RequestNewHeap
        /// </summary>
        /// <param name="type">The <see cref="DescriptorHeapType"/></param>
        /// <returns>The <see cref="DescriptorHeap"/></returns>
        protected static DescriptorHeap RequestNewHeap(DescriptorHeapType type)
        {
            lock (_AllocationMutex)
            {
                DescriptorHeapDescription desc = new DescriptorHeapDescription
                {
                    Type            = type,
                    DescriptorCount = _NumDescriptorsPerHeap,
                    Flags           = DescriptorHeapFlags.None,
                    NodeMask        = 1
                };

                var heap = Globals.Device.CreateDescriptorHeap(desc);
                Debug.Assert(heap != null);
                _DescriptorHeapPool.Add(heap);
                return(heap);
            }
        }
示例#13
0
        private void CreateRtvAndDsvDescriptorHeaps()
        {
            var rtvHeapDesc = new DescriptorHeapDescription
            {
                DescriptorCount = RtvDescriptorCount,
                Type            = DescriptorHeapType.RenderTargetView
            };

            RtvHeap = Device.CreateDescriptorHeap(rtvHeapDesc);

            var dsvHeapDesc = new DescriptorHeapDescription
            {
                DescriptorCount = DsvDescriptorCount,
                Type            = DescriptorHeapType.DepthStencilView
            };

            DsvHeap = Device.CreateDescriptorHeap(dsvHeapDesc);
        }
示例#14
0
        public void Initialize(Device device, Int32 descriptorCount, Boolean isShaderVisible, H1ViewType descriptorHeapType)
        {
            DescriptorHeapType?type = null;

            switch (descriptorHeapType)
            {
            case H1ViewType.DepthStencilView:
                type = DescriptorHeapType.DepthStencilView;
                break;

            case H1ViewType.RenderTargetView:
                type = DescriptorHeapType.RenderTargetView;
                break;

            case H1ViewType.ShaderResourceView:
            case H1ViewType.UnorderedAccessView:
            case H1ViewType.ConstantBufferView:
                type = DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView;
                break;
            }

            if (type == null)
            {
                return; // @TODO - excpetion handling
            }
            // create descriptorheap desc
            m_Desc = new DescriptorHeapDescription()
            {
                DescriptorCount = descriptorCount,
                Flags           = isShaderVisible ? DescriptorHeapFlags.ShaderVisible : DescriptorHeapFlags.None,
                Type            = type.Value
            };

            // create descriptor heap and set the descriptor incremental size
            m_DescriptorHeap = device.CreateDescriptorHeap(m_Desc);
            m_DescSize       = Convert.ToUInt32(device.GetDescriptorHandleIncrementSize(type.Value));

            // set the heap start CPU/GPU
            m_HeapStartCPU = m_DescriptorHeap.CPUDescriptorHandleForHeapStart;
            m_HeapStartGPU = m_DescriptorHeap.GPUDescriptorHandleForHeapStart;

            // set the cursor to 0
            m_Cursor = 0; // tracing next allocation flags
        }
        protected DescriptorHeap RequestNewHeap(H1DescriptorHeapType type)
        {
            DescriptorHeapType typeInDX12 = H1RHIDefinitionHelper.ConvertToDescriptorHeapType(type);

            // @TODO - need to be thread-safe
            DescriptorHeapDescription desc = new DescriptorHeapDescription();

            desc.Type            = typeInDX12;
            desc.DescriptorCount = NumDescriptorsPerHeap;

            // this part is none, but for usage in command context, you need to create new descriptor for shader-visible by UserDescriptorHeap or DynamicDescriptorHeap
            desc.Flags    = DescriptorHeapFlags.None;
            desc.NodeMask = 1;

            DescriptorHeap newHeap = m_Device.CreateDescriptorHeap(desc);

            m_DescriptorHeapPool.Add(newHeap);

            return(newHeap);
        }
示例#16
0
        public D3D12TextureView(DX12GraphicsDevice graphicsDevice,
                                int descriptorCount,
                                DescriptorHeapFlags descriptorHeapFlags,
                                DescriptorHeapType descriptorHeapType)
        {
            var descriptorHeapDescription = new DescriptorHeapDescription
            {
                DescriptorCount = descriptorCount,
                Flags           = descriptorHeapFlags,
                Type            = descriptorHeapType
            };

            if (descriptorHeapType == DescriptorHeapType.RenderTargetView)
            {
                _rtvDescriptorHeap = graphicsDevice.CreateDescriptorHeap(descriptorHeapDescription);
            }
            else if (descriptorHeapType == DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView)
            {
                _dsvDescriptorHeap = graphicsDevice.CreateDescriptorHeap(descriptorHeapDescription);
            }
        }
示例#17
0
        private void BuildDescriptorHeaps()
        {
            int objCount = _allRitems.Count;

            // Need a CBV descriptor for each object for each frame resource,
            // +1 for the perPass CBV for each frame resource.
            int numDescriptors = (objCount + 1) * NumFrameResources;

            // Save an offset to the start of the pass CBVs.  These are the last 3 descriptors.
            _passCbvOffset = objCount * NumFrameResources;

            var cbvHeapDesc = new DescriptorHeapDescription
            {
                DescriptorCount = numDescriptors,
                Type            = DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView,
                Flags           = DescriptorHeapFlags.ShaderVisible
            };

            _cbvHeap         = Device.CreateDescriptorHeap(cbvHeapDesc);
            _descriptorHeaps = new[] { _cbvHeap };
        }
示例#18
0
        private void BuildDescriptorHeaps()
        {
            //
            // Create the SRV heap.
            //
            var srvHeapDesc = new DescriptorHeapDescription
            {
                DescriptorCount = 1,
                Type            = DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView,
                Flags           = DescriptorHeapFlags.ShaderVisible
            };

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

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

            Resource woodCrateTexture = _textures["woodCrateTex"].Resource;

            var srvDesc = new ShaderResourceViewDescription
            {
                // TODO: API suggestion: Expose DefaultShader4ComponentMapping through ShaderComponentMapping enumeration.
                // TODO: Turn from int to ShaderComponentMapping enum.
                Shader4ComponentMapping = D3DUtil.DefaultShader4ComponentMapping,
                Format    = woodCrateTexture.Description.Format,
                Dimension = ShaderResourceViewDimension.Texture2D,
                Texture2D = new ShaderResourceViewDescription.Texture2DResource
                {
                    MostDetailedMip     = 0,
                    MipLevels           = woodCrateTexture.Description.MipLevels,
                    ResourceMinLODClamp = 0.0f
                }
            };

            Device.CreateShaderResourceView(woodCrateTexture, srvDesc, hDescriptor);
        }
        private void BuildDescriptorHeaps()
        {
            //
            // Create the SRV heap.
            //
            var srvHeapDesc = new DescriptorHeapDescription
            {
                DescriptorCount = 1,
                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 defaultDiffuseTex = _textures["defaultDiffuseTex"].Resource;

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

            Device.CreateShaderResourceView(defaultDiffuseTex, srvDesc, hDescriptor);
        }
示例#20
0
        internal CpuDescriptorHandle Allocate(int count)
        {
            if (currentHeap == null || remainingHandles < count)
            {
                DescriptorHeapDescription descriptorHeapDescription = new DescriptorHeapDescription()
                {
                    Flags           = DescriptorHeapFlags.None,
                    Type            = DescriptorHeapType,
                    DescriptorCount = DescriptorPerHeap,
                    NodeMask        = 1,
                };

                currentHeap      = GraphicsDevice.NativeDevice.CreateDescriptorHeap <ID3D12DescriptorHeap>(descriptorHeapDescription);
                remainingHandles = DescriptorPerHeap;
                currentHandle    = currentHeap.GetCPUDescriptorHandleForHeapStart();
            }

            CpuDescriptorHandle result = currentHandle;

            currentHandle.Ptr += DescriptorSize;
            remainingHandles  -= count;

            return(result);
        }
        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 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);
        }
示例#23
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
                                 } };
        }
示例#24
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();
        }
示例#25
0
 public DescriptorHeap CreateDescriptorHeap(DescriptorHeapDescription descriptorHeapDescription)
 {
     return(_nativeDevice.CreateDescriptorHeap(descriptorHeapDescription));
 }
        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;
        }
        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);
        }
        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);
        }
        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();
        }
示例#30
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_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);
        }
示例#31
0
        private void LoadPipeline()
        {
            viewport.Width    = this.width;
            viewport.Height   = this.height;
            viewport.MaxDepth = 1.0f;

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

#if DEBUG
            // Enable the D3D12 debug layer.
            {
                DebugInterface.Get().EnableDebugLayer();
            }
#endif
            var fact = new SharpDX.DXGI.Factory1();
            SharpDX.DXGI.Adapter adapter = fact.GetAdapter(1);

            // create device
            using (var defaultDevice = new Device(adapter, SharpDX.Direct3D.FeatureLevel.Level_12_1))
                device = defaultDevice.QueryInterface <SharpDX.Direct3D12.Device2>();

            using (var factory = new SharpDX.DXGI.Factory4())
            {
                // Describe and create the command queue.
                var queueDesc = new CommandQueueDescription(CommandListType.Direct);
                commandQueue = device.CreateCommandQueue(queueDesc);


                // Describe and create the swap chain.
                var swapChainDesc = new SharpDX.DXGI.SwapChainDescription1()
                {
                    BufferCount       = FrameCount,
                    Format            = SharpDX.DXGI.Format.R8G8B8A8_UNorm,
                    Height            = height,
                    Width             = width,
                    SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0),
                    Scaling           = SharpDX.DXGI.Scaling.Stretch,
                    Stereo            = false,
                    SwapEffect        = SharpDX.DXGI.SwapEffect.FlipDiscard,
                    Usage             = SharpDX.DXGI.Usage.RenderTargetOutput,
                };

                var tempSwapChain = new SharpDX.DXGI.SwapChain1(factory, commandQueue, ref swapChainDesc);
                swapChain = tempSwapChain.QueryInterface <SharpDX.DXGI.SwapChain3>();
                tempSwapChain.Dispose();
                frameIndex = swapChain.CurrentBackBufferIndex;

                using (SharpDX.DXGI.ISwapChainPanelNative nativeObject = ComObject.As <SharpDX.DXGI.ISwapChainPanelNative>(swapChainPanel))
                    nativeObject.SwapChain = swapChain;
            }

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

            renderTargetViewHeap = device.CreateDescriptorHeap(rtvHeapDesc);

            rtvDescriptorSize = device.GetDescriptorHandleIncrementSize(DescriptorHeapType.RenderTargetView);

            // Create frame resources.
            var 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);
        }
        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);
        }
        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);
        }
示例#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);
        }
示例#35
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_11_0);
            using (var factory = new Factory4())
            {
                // Describe and create the command queue.
                var queueDesc = new CommandQueueDescription(CommandListType.Direct);
                commandQueue = device.CreateCommandQueue(queueDesc);


                // Describe and create the swap chain.
                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,
                    //Flags = SwapChainFlags.None,
                    SampleDescription = new SampleDescription(1, 0),
                    IsWindowed        = true
                };

                var 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.
            var rtvHeapDesc = new DescriptorHeapDescription()
            {
                DescriptorCount = FrameCount,
                Flags           = DescriptorHeapFlags.None,
                Type            = DescriptorHeapType.RenderTargetView
            };

            renderTargetViewHeap = device.CreateDescriptorHeap(rtvHeapDesc);

            rtvDescriptorSize = device.GetDescriptorHandleIncrementSize(DescriptorHeapType.RenderTargetView);

            // Create frame resources.
            var 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);
        }
        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);
        }
        private void BuildDepthBuffer()
        {
            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;
        }