public ImageBlurApp() { _device = GraphicsDevice.Create(FeatureLevel.GraphicsLevel11_0, null); var rootParams = new RootParameter[] { RootParameter.CreateConstants <Settings>(0, 0), RootParameter.CreateDescriptorTable(DescriptorRangeType.ShaderResourceView, 0, 1, 0), RootParameter.CreateDescriptorTable(DescriptorRangeType.UnorderedAccessView, 0, 1, 1) }; var rootSig = _device.CreateRootSignature(rootParams); var psoDesc = new ComputePipelineDesc { RootSignature = rootSig, ComputeShader = ShaderManager.CompileShader("ImageBlur/ImageBlur.hlsl", ShaderType.Compute, entrypoint: "BlurHorizontal"), }; _horizontalBlurPso = _device.PipelineManager.CreatePipelineStateObject(psoDesc, "BlurHorizontal"); psoDesc = new ComputePipelineDesc { RootSignature = rootSig, ComputeShader = ShaderManager.CompileShader("ImageBlur/ImageBlur.hlsl", ShaderType.Compute, entrypoint: "BlurVertical"), }; _verticalBlurPso = _device.PipelineManager.CreatePipelineStateObject(psoDesc, "BlurVertical"); _settings = new Settings { BlurRadius = 8 }; GetWeights(); }
void GetPipelineState() { DescriptorRange[] ranges = new DescriptorRange[] { new DescriptorRange() { RangeType = DescriptorRangeType.ConstantBufferView, BaseShaderRegister = 0, DescriptorCount = 1 } }; RootParameter parameter = new RootParameter(ShaderVisibility.Vertex, ranges); // Create a root signature. RootSignatureDescription rootSignatureDesc = new RootSignatureDescription(RootSignatureFlags.AllowInputAssemblerInputLayout, new RootParameter[] { parameter }); var rootSignature = device.CreateRootSignature(rootSignatureDesc.Serialize()); // Create the pipeline state, which includes compiling and loading shaders. string filePath = @"E:\Code\ROE1\RoeHack-master\Forms\bin\Debug\DirectXHooker\shaders.hlsl"; #if DEBUG var vertexShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile(filePath, "VSMain", "vs_5_0", SharpDX.D3DCompiler.ShaderFlags.Debug)); #else var vertexShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("filePath, "VSMain", "vs_5_0")); #endif #if DEBUG var pixelShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile(filePath, "PSMain", "ps_5_0", SharpDX.D3DCompiler.ShaderFlags.Debug)); #else var pixelShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile(filePath, "PSMain", "ps_5_0")); #endif // Define the vertex input layout. InputElement[] inputElementDescs = new InputElement[] { new InputElement("POSITION",0,Format.R32G32B32_Float,0,0), new InputElement("COLOR",0,Format.R32G32B32A32_Float,12,0) }; // Describe and create the graphics pipeline state object (PSO). GraphicsPipelineStateDescription psoDesc = new GraphicsPipelineStateDescription() { InputLayout = new InputLayoutDescription(inputElementDescs), RootSignature = rootSignature, VertexShader = vertexShader, PixelShader = pixelShader, RasterizerState = RasterizerStateDescription.Default(), BlendState = BlendStateDescription.Default(), DepthStencilFormat = SharpDX.DXGI.Format.D32_Float, DepthStencilState = DepthStencilStateDescription.Default(), SampleMask = int.MaxValue, PrimitiveTopologyType = PrimitiveTopologyType.Triangle, RenderTargetCount = 1, Flags = PipelineStateFlags.None, SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0), StreamOutput = new StreamOutputDescription() }; psoDesc.DepthStencilState.IsDepthEnabled = false; psoDesc.RenderTargetFormats[0] = SharpDX.DXGI.Format.R8G8B8A8_UNorm; pipelineState = device.CreateGraphicsPipelineState(psoDesc); }
public override void Initialize(Size outputSize, IOutputOwner output) { #if DEBUG var debug = DebugLayerConfiguration.Debug.AddDebugFlags(DebugFlags.GpuBasedValidation); #else var debug = DebugLayerConfiguration.None; #endif _device = GraphicsDevice.Create(FeatureLevel.GraphicsLevel11_0, null, debug); _output = Output.Create(OutputConfiguration.Default, _device, output); using (var copy = _device.BeginUploadContext()) { _colors = copy.UploadBuffer(GetColors()); } var @params = new RootParameter[] { RootParameter.CreateDescriptor(RootParameterType.ShaderResourceView, 0, 0, ShaderVisibility.Pixel), RootParameter.CreateConstants <MandelbrotConstants>(0, 0, ShaderVisibility.Pixel), }; var rootSig = _device.CreateRootSignature(@params, null); var flags = new ShaderCompileFlag[] { ShaderCompileFlag.EnableDebugInformation, ShaderCompileFlag.WriteDebugInformationToFile(), ShaderCompileFlag.DefineMacro("ITER", IterCount.ToString()), #if DOUBLE ShaderCompileFlag.DefineMacro("DOUBLE") #endif }; var psoDesc = new GraphicsPipelineDesc { RootSignature = rootSig, Topology = TopologyClass.Triangle, DepthStencil = DepthStencilDesc.DisableDepthStencil, RenderTargetFormats = BackBufferFormat.R8G8B8A8UnsignedNormalized, VertexShader = ShaderManager.CompileShader("Shaders/Mandelbrot/EntireScreenCopyVS.hlsl", ShaderType.Vertex, flags), PixelShader = ShaderManager.CompileShader("Shaders/Mandelbrot/Mandelbrot.hlsl", ShaderType.Pixel, flags), Rasterizer = RasterizerDesc.Default.WithFrontFaceType(FaceType.Anticlockwise) }; _pso = _device.PipelineManager.CreatePipelineStateObject(psoDesc, "Mandelbrot"); _constants = new MandelbrotConstants { Scale = (FloatType)1, CenterX = (FloatType)(-1.789169018604823106674468341188838763), CenterY = (FloatType)(0.00000033936851576718256602823026614), ColorCount = _colors.LengthAs <Rgba128>() }; OnResize(outputSize); }
public void Initialize() { // Pipeline state. var testShaderPath = "../../../../../Resources/Engine/MipMap.hlsl"; ComputeShader = ShaderBytecode.CompileFromFile(testShaderPath, "GenerateMipMaps", "cs_5_0"); // Root parameters. var rootParameters = new RootParameter[] { new RootParameter(ShaderVisibility.All, new RootConstants(0, 0, 2)), new RootParameter(ShaderVisibility.Pixel, new DescriptorRange() { RangeType = DescriptorRangeType.ShaderResourceView, DescriptorCount = 1, OffsetInDescriptorsFromTableStart = int.MinValue, // D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND BaseShaderRegister = 0 }), new RootParameter(ShaderVisibility.Pixel, new DescriptorRange() { RangeType = DescriptorRangeType.UnorderedAccessView, BaseShaderRegister = 0, OffsetInDescriptorsFromTableStart = int.MinValue, // D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND DescriptorCount = 1 }), }; var staticSamplers = new StaticSamplerDescription[] { new StaticSamplerDescription() { Filter = Filter.MinMagLinearMipPoint, AddressUVW = TextureAddressMode.Clamp, MipLODBias = 0f, ComparisonFunc = Comparison.Never, MinLOD = 0f, MaxLOD = float.MaxValue, MaxAnisotropy = 0, BorderColor = StaticBorderColor.OpaqueBlack, ShaderRegister = 0, RegisterSpace = 0, ShaderVisibility = ShaderVisibility.All } }; var rootSignatureDescription = new RootSignatureDescription( RootSignatureFlags.AllowInputAssemblerInputLayout, rootParameters, staticSamplers); RootSignature = RootSignature.Create(Device, rootSignatureDescription); Layout = new DescriptorLayout( DescriptorLayout.EntryType.ConstantBufferShaderResourceOrUnorderedAccessView, DescriptorLayout.EntryType.ConstantBufferShaderResourceOrUnorderedAccessView); }
Boolean InitAsDescriptorRange(DescriptorRangeType type, Int32 register, Int32 counts, ShaderVisibility visibility = ShaderVisibility.All) { if (m_RootParameter != null) { return(false); } m_RootParameter = new RootParameter(visibility, new DescriptorRange(type, counts, register)); return(true); }
Boolean InitAsBufferUAV(Int32 register, ShaderVisibility visibility = ShaderVisibility.All) { if (m_RootParameter != null) { return(false); } m_RootParameter = new RootParameter(visibility, new DescriptorRange(DescriptorRangeType.UnorderedAccessView, 1, register)); return(true); }
Boolean InitAsConstants(Int32 register, Int32 numDWORDs, ShaderVisibility visibility = ShaderVisibility.All) { if (m_RootParameter != null) { return(false); } m_RootParameter = new RootParameter(visibility, new RootConstants(register, 0, numDWORDs)); return(true); }
//[MemberNotNull(nameof(_tex), nameof(_texMsaa8x))] public void CreatePipelines() { var rootParams = new[] { RootParameter.CreateDescriptor(RootParameterType.ConstantBufferView, 0, 0), RootParameter.CreateDescriptor(RootParameterType.ConstantBufferView, 1, 0), RootParameter.CreateDescriptor(RootParameterType.ConstantBufferView, 2, 0), RootParameter.CreateDescriptorTable(DescriptorRangeType.ShaderResourceView, 0, 1, 0) }; var samplers = new[] { new StaticSampler( TextureAddressMode.Clamp, SamplerFilterType.Anistropic, shaderRegister: 0, registerSpace: 0, ShaderVisibility.All, StaticSampler.OpaqueWhite ) }; _rootSig = _device.CreateRootSignature(rootParams, samplers); var compilationFlags = new[] { ShaderCompileFlag.PackMatricesInRowMajorOrder, ShaderCompileFlag.AllResourcesBound, ShaderCompileFlag.EnableDebugInformation, ShaderCompileFlag.WriteDebugInformationToFile() //ShaderCompileFlag.DefineMacro("NORMALS") }; var vertexShader = ShaderManager.CompileShader("Shaders/SimpleTexture/TextureVertexShader.hlsl", ShaderModel.Vs_6_0, compilationFlags); var pixelShader = ShaderManager.CompileShader("Shaders/SimpleTexture/TexturePixelShader.hlsl", ShaderModel.Ps_6_0, compilationFlags); var psoDesc = new GraphicsPipelineDesc { RootSignature = _rootSig, RenderTargetFormats = RenderTargetFormat, DepthStencilFormat = DepthStencilFormat, VertexShader = vertexShader, PixelShader = pixelShader, Topology = TopologyClass.Triangle, Inputs = InputLayout.FromType <TexturedVertex>() }; _tex = _device.PipelineManager.CreatePipelineStateObject(psoDesc, "Texture"); //psoDesc.Msaa = MultisamplingDesc.X8; _texMsaa8x = _device.PipelineManager.CreatePipelineStateObject(psoDesc, "Texture_MSAA8X"); }
internal unsafe void __MarshalFrom(ref __Native @ref) { Parameters = new RootParameter[@ref.NumParameters]; if (@ref.NumParameters > 0) { UnsafeUtilities.Read(@ref.PParameters, Parameters); } StaticSamplers = new StaticSamplerDescription[@ref.NumStaticSamplers]; if (@ref.NumStaticSamplers > 0) { UnsafeUtilities.Read(@ref.PStaticSamplers, StaticSamplers); } Flags = @ref.Flags; }
public void Initialize() { // Pipeline state. var testShaderPath = "../../../../../Resources/Engine/Forward/Standard.hlsl"; VertexShader = ShaderBytecode.CompileFromFile(testShaderPath, "VSMain", "vs_5_0"); PixelShader = ShaderBytecode.CompileFromFile(testShaderPath, "PSMain", "ps_5_0"); // Root parameters. var rootParameters = new RootParameter[] { new RootParameter(ShaderVisibility.All, new DescriptorRange() { RangeType = DescriptorRangeType.ConstantBufferView, BaseShaderRegister = 0, OffsetInDescriptorsFromTableStart = int.MinValue, DescriptorCount = 1, }), new RootParameter(ShaderVisibility.Pixel, new DescriptorRange() { RangeType = DescriptorRangeType.ShaderResourceView, DescriptorCount = 1, OffsetInDescriptorsFromTableStart = int.MinValue, BaseShaderRegister = 0 }), new RootParameter(ShaderVisibility.Pixel, new DescriptorRange() { RangeType = DescriptorRangeType.Sampler, BaseShaderRegister = 0, DescriptorCount = 1 }), }; var rootSignatureDescription = new RootSignatureDescription(RootSignatureFlags.AllowInputAssemblerInputLayout, rootParameters); RootSignature = RootSignature.Create(Device, rootSignatureDescription); Layout = new DescriptorLayout( DescriptorLayout.EntryType.ConstantBufferShaderResourceOrUnorderedAccessView, DescriptorLayout.EntryType.ConstantBufferShaderResourceOrUnorderedAccessView, DescriptorLayout.EntryType.SamplerState); }
private string RootParameterToString(RootParameter param) { switch (param.ParameterType) { case RootParameterType.Cbv: case RootParameterType.Srv: case RootParameterType.Uav: return(RootDescriptorToString(param as RootDescriptor)); case RootParameterType.DescriptorTable: return(DescriptorTableToString(param as RootDescriptorTable)); case RootParameterType._32BitConstants: return(RootConstantsToString(param as RootConstants)); default: throw new InvalidOperationException($"Unexpected type {param.ParameterType}"); } }
private static async Task ExecuteOnGpu(GraphicsDevice device, StructuredBuffer <float> sourceBufferView, WriteableStructuredBuffer <float> destinationBufferView) { bool generateWithDelegate = false; DescriptorSet descriptorSet = new DescriptorSet(device, 2); descriptorSet.AddResourceViews(destinationBufferView); descriptorSet.AddResourceViews(sourceBufferView); // Generate computer shader ShaderGenerator shaderGenerator = generateWithDelegate ? CreateShaderGeneratorWithDelegate(sourceBufferView, destinationBufferView) : CreateShaderGeneratorWithClass(); ShaderGeneratorResult result = shaderGenerator.GenerateShader(); // Compile shader byte[] shaderBytecode = ShaderCompiler.Compile(ShaderStage.ComputeShader, result.ShaderSource, result.EntryPoints["compute"]); DescriptorRange[] descriptorRanges = new DescriptorRange[] { new DescriptorRange(DescriptorRangeType.UnorderedAccessView, 1, 0), new DescriptorRange(DescriptorRangeType.ShaderResourceView, 1, 0) }; RootParameter rootParameter = new RootParameter(new RootDescriptorTable(descriptorRanges), ShaderVisibility.All); RootSignatureDescription rootSignatureDescription = new RootSignatureDescription(RootSignatureFlags.None, new[] { rootParameter }); RootSignature rootSignature = new RootSignature(device, rootSignatureDescription); PipelineState pipelineState = new PipelineState(device, rootSignature, shaderBytecode); // Execute computer shader using (CommandList commandList = new CommandList(device, CommandListType.Compute)) { commandList.SetPipelineState(pipelineState); commandList.SetComputeRootDescriptorTable(0, descriptorSet); commandList.Dispatch(1, 1, 1); await commandList.FlushAsync(); } }
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 } }; }
/// <summary> /// Setup resources for rendering /// </summary> void LoadAssets() { // Create the main command list commandList = Collect(device.CreateCommandList(CommandListType.Direct, commandListAllocator, pipelineState)); // Create the descriptor heap for the render target view descriptorHeapRT = Collect(device.CreateDescriptorHeap(new DescriptorHeapDescription() { Type = DescriptorHeapType.RenderTargetView, DescriptorCount = 1 })); #if USE_DEPTH descriptorHeapDS = Collect(device.CreateDescriptorHeap(new DescriptorHeapDescription() { Type = DescriptorHeapType.DepthStencilView, DescriptorCount = 1 })); #endif #if USE_TEXTURE descriptorHeapCB = Collect(device.CreateDescriptorHeap(new DescriptorHeapDescription() { Type = DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView, DescriptorCount = 2, Flags = DescriptorHeapFlags.ShaderVisible, })); descriptorHeapS = Collect(device.CreateDescriptorHeap(new DescriptorHeapDescription() { Type = DescriptorHeapType.Sampler, DescriptorCount = 1, Flags = DescriptorHeapFlags.ShaderVisible, })); descriptorsHeaps[0] = descriptorHeapCB; descriptorsHeaps[1] = descriptorHeapS; #else descriptorHeapCB = Collect(device.CreateDescriptorHeap(new DescriptorHeapDescription() { Type = DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView, DescriptorCount = 1, Flags = DescriptorHeapFlags.ShaderVisible, })); descriptorsHeaps[0] = descriptorHeapCB; #endif #if true // root signature in code var rsparams = new RootParameter[] { new RootParameter(ShaderVisibility.Vertex, new RootDescriptor(), RootParameterType.ConstantBufferView), new RootParameter(ShaderVisibility.Vertex, new DescriptorRange { RangeType = DescriptorRangeType.ConstantBufferView, BaseShaderRegister = 1, DescriptorCount = 1, }), #if USE_TEXTURE new RootParameter(ShaderVisibility.Pixel, new DescriptorRange { RangeType = DescriptorRangeType.ShaderResourceView, BaseShaderRegister = 0, DescriptorCount = 1, }), new RootParameter(ShaderVisibility.Pixel, new DescriptorRange { RangeType = DescriptorRangeType.Sampler, BaseShaderRegister = 0, DescriptorCount = 1, }), #endif }; var rs = new RootSignatureDescription(RootSignatureFlags.AllowInputAssemblerInputLayout, rsparams); rootSignature = Collect(device.CreateRootSignature(rs.Serialize())); #else var rootSignatureByteCode = Utilities.ReadStream(assembly.GetManifestResourceStream("Shaders.Cube" + shaderNameSuffix + ".rs")); using (var bufferRootSignature = DataBuffer.Create(rootSignatureByteCode)) rootSignature = Collect(device.CreateRootSignature(bufferRootSignature)); #endif byte[] vertexShaderByteCode = GetResourceBytes("Cube" + shaderNameSuffix + ".vso"); byte[] pixelShaderByteCode = GetResourceBytes("Cube" + shaderNameSuffix + ".pso"); var layout = new InputLayoutDescription(new InputElement[] { new InputElement("POSITION", 0, Format.R32G32B32_Float, 0), new InputElement("NORMAL", 0, Format.R32G32B32_Float, 0), new InputElement("TEXCOORD", 0, Format.R32G32_Float, 0), #if USE_INSTANCES new InputElement("OFFSET", 0, Format.R32G32B32_Float, 0, 1, InputClassification.PerInstanceData, 1), #endif }); #region pipeline state var psd = new GraphicsPipelineStateDescription { InputLayout = layout, VertexShader = vertexShaderByteCode, PixelShader = pixelShaderByteCode, RootSignature = rootSignature, DepthStencilState = DepthStencilStateDescription.Default(), DepthStencilFormat = Format.Unknown, BlendState = BlendStateDescription.Default(), RasterizerState = RasterizerStateDescription.Default(), SampleDescription = new SampleDescription(1, 0), RenderTargetCount = 1, PrimitiveTopologyType = PrimitiveTopologyType.Triangle, SampleMask = -1, StreamOutput = new StreamOutputDescription() }; psd.RenderTargetFormats[0] = Format.R8G8B8A8_UNorm; #if USE_DEPTH psd.DepthStencilFormat = Format.D32_Float; #else psd.DepthStencilState.IsDepthEnabled = false; #endif //psd.RasterizerState.CullMode = CullMode.None; pipelineState = Collect(device.CreateGraphicsPipelineState(psd)); #endregion pipeline state #region vertices var vertices = new[] { -1.0f, -1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, // Front -1.0f, 1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, -1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, -1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, // BACK -1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, // BACK 1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, -1.0f, 1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, // Top -1.0f, 1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, // Top -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, -1.0f, -1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, // Bottom -1.0f, -1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, // Bottom 1.0f, -1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, -1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, -1.0f, -1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, // Left -1.0f, -1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, // Left -1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, -1.0f, 1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, -1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, // Right 1.0f, -1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, // Right 1.0f, 1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, }; #endregion vertices #region vertex buffer // Instantiate Vertex buiffer from vertex data int sizeOfFloat = sizeof(float); int sizeInBytes = vertices.Length * sizeOfFloat; vertexBuffer = Collect(device.CreateCommittedResource( new HeapProperties(HeapType.Upload), HeapFlags.None, new ResourceDescription(ResourceDimension.Buffer, 0, sizeInBytes, 1, 1, 1, Format.Unknown, 1, 0, TextureLayout.RowMajor, ResourceFlags.None), ResourceStates.GenericRead)); vertexBufferView = new[] { new VertexBufferView { BufferLocation = vertexBuffer.GPUVirtualAddress, SizeInBytes = sizeInBytes, StrideInBytes = sizeOfFloat * 8, } }; var ptr = vertexBuffer.Map(0); Utilities.Write(ptr, vertices, 0, vertices.Length); vertexBuffer.Unmap(0); #endregion vertex buffer #region instances #if USE_INSTANCES int instanceSizeInBytes = sizeOfFloat * instances.Length; instancesBuffer = Collect(device.CreateCommittedResource( new HeapProperties(HeapType.Upload), HeapFlags.None, new ResourceDescription(ResourceDimension.Buffer, 0, instanceSizeInBytes, 1, 1, 1, Format.Unknown, 1, 0, TextureLayout.RowMajor, ResourceFlags.None), ResourceStates.GenericRead)); instancesBufferView = new[] { new VertexBufferView { BufferLocation = instancesBuffer.GPUVirtualAddress, SizeInBytes = instanceSizeInBytes, StrideInBytes = sizeOfFloat * 3, } }; ptr = instancesBuffer.Map(0); Utilities.Write(ptr, instances, 0, instances.Length); instancesBuffer.Unmap(0); #endif #endregion instances #region indices #if USE_INDICES var indexData = new[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33 }; sizeInBytes = indexData.Length * sizeof(int); indexBuffer = Collect(device.CreateCommittedResource( new HeapProperties(HeapType.Upload), HeapFlags.None, new ResourceDescription(ResourceDimension.Buffer, 0, sizeInBytes, 1, 1, 1, Format.Unknown, 1, 0, TextureLayout.RowMajor, ResourceFlags.None), ResourceStates.GenericRead)); ptr = indexBuffer.Map(0); Utilities.Write(ptr, indexData, 0, indexData.Length); indexBuffer.Unmap(0); indexBufferView = new IndexBufferView { BufferLocation = indexBuffer.GPUVirtualAddress, SizeInBytes = sizeInBytes, Format = Format.R32_UInt }; #endif #endregion indices #region transform transWorld = Collect(device.CreateCommittedResource( new HeapProperties(HeapType.Upload), HeapFlags.None, new ResourceDescription(ResourceDimension.Buffer, 0, 16 * sizeOfMatrix, 1, 1, 1, Format.Unknown, 1, 0, TextureLayout.RowMajor, ResourceFlags.None), ResourceStates.GenericRead)); transWorldPtr = transWorld.Map(0); transViewProj = Collect(device.CreateCommittedResource( new HeapProperties(HeapType.Upload), HeapFlags.None, new ResourceDescription(ResourceDimension.Buffer, 0, sizeOfMatrix, 1, 1, 1, Format.Unknown, 1, 0, TextureLayout.RowMajor, ResourceFlags.None), ResourceStates.GenericRead)); device.CreateConstantBufferView(new ConstantBufferViewDescription { BufferLocation = transViewProj.GPUVirtualAddress, SizeInBytes = sizeOfMatrix, }, descriptorHeapCB.CPUDescriptorHandleForHeapStart); var view = Matrix.LookAtLH(new Vector3(5, 5, -5), Vector3.Zero, Vector3.UnitY); var proj = Matrix.PerspectiveFovLH(MathUtil.Pi / 4, (float)width / height, 0.1f, 100); var vpT = view * proj; vpT.Transpose(); ptr = transViewProj.Map(0); Utilities.Write(ptr, ref vpT); transViewProj.Unmap(0); #endregion transform #if USE_TEXTURE #region texture Resource buf; using (var tl = new TextureLoader("GeneticaMortarlessBlocks.jpg")) { int w = tl.Width, h = tl.Height; var descrs = new[] { new ResourceDescription(ResourceDimension.Texture2D, 0, w, h, 1, 1, Format.B8G8R8A8_UNorm, 1, 0, TextureLayout.Unknown, ResourceFlags.None), }; texture = Collect(device.CreateCommittedResource( new HeapProperties(HeapType.Default), HeapFlags.None, descrs[0], ResourceStates.CopyDestination) ); var resAllocInfo = device.GetResourceAllocationInfo(1, 1, descrs); buf = device.CreateCommittedResource( new HeapProperties(HeapType.Upload), HeapFlags.None, new ResourceDescription( ResourceDimension.Buffer, 0, resAllocInfo.SizeInBytes, 1, 1, 1, Format.Unknown, 1, 0, TextureLayout.RowMajor, ResourceFlags.None), ResourceStates.GenericRead); var ptrBuf = buf.Map(0); int rowPitch = tl.CopyImageData(ptrBuf); buf.Unmap(0); var src = new TextureCopyLocation(buf, new PlacedSubResourceFootprint { Offset = 0, Footprint = new SubResourceFootprint { Format = Format.B8G8R8A8_UNorm_SRgb, Width = w, Height = h, Depth = 1, RowPitch = rowPitch } } ); var dst = new TextureCopyLocation(texture, 0); // record copy commandList.CopyTextureRegion(dst, 0, 0, 0, src, null); commandList.ResourceBarrierTransition(texture, ResourceStates.CopyDestination, ResourceStates.GenericRead); } descrOffsetCB = device.GetDescriptorHandleIncrementSize(DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView); device.CreateShaderResourceView(texture, null, descriptorHeapCB.CPUDescriptorHandleForHeapStart + descrOffsetCB); #endregion texture #region sampler device.CreateSampler(new SamplerStateDescription { AddressU = TextureAddressMode.Wrap, AddressV = TextureAddressMode.Wrap, AddressW = TextureAddressMode.Wrap, Filter = Filter.MaximumMinMagMipLinear, }, descriptorHeapS.CPUDescriptorHandleForHeapStart); #endregion sampler #endif // Get the backbuffer and creates the render target view renderTarget = Collect(swapChain.GetBackBuffer <Resource>(0)); device.CreateRenderTargetView(renderTarget, null, descriptorHeapRT.CPUDescriptorHandleForHeapStart); #if USE_DEPTH depthBuffer = Collect(device.CreateCommittedResource( new HeapProperties(HeapType.Default), HeapFlags.None, new ResourceDescription(ResourceDimension.Texture2D, 0, width, height, 1, 1, Format.D32_Float, 1, 0, TextureLayout.Unknown, ResourceFlags.AllowDepthStencil), ResourceStates.Present, new ClearValue { Format = Format.D32_Float, DepthStencil = new DepthStencilValue { Depth = 1, Stencil = 0, } })); device.CreateDepthStencilView(depthBuffer, null, descriptorHeapDS.CPUDescriptorHandleForHeapStart); #endif // Create the viewport viewPort = new ViewportF(0, 0, width, height); // Create the scissor scissorRectangle = new Rectangle(0, 0, width, height); // Create a fence to wait for next frame fence = Collect(device.CreateFence(0, FenceFlags.None)); currentFence = 1; // Close command list commandList.Close(); commandQueue.ExecuteCommandList(commandList); // Create an event handle use for VTBL CreateWaitEvent(); // Wait the command list to complete WaitForPrevFrame(); #if USE_TEXTURE buf.Dispose(); #endif }
private void LoadAssets() { DescriptorRange[] ranges = new DescriptorRange[] { new DescriptorRange() { RangeType = DescriptorRangeType.ShaderResourceView, DescriptorCount = 1, OffsetInDescriptorsFromTableStart = int.MinValue, BaseShaderRegister = 0 } }; StaticSamplerDescription sampler = new StaticSamplerDescription() { Filter = Filter.MinimumMinMagMipPoint, AddressU = TextureAddressMode.Border, AddressV = TextureAddressMode.Border, AddressW = TextureAddressMode.Border, MipLODBias = 0, MaxAnisotropy = 0, ComparisonFunc = Comparison.Never, BorderColor = StaticBorderColor.TransparentBlack, MinLOD = 0.0f, MaxLOD = float.MaxValue, ShaderRegister = 0, RegisterSpace = 0, ShaderVisibility = ShaderVisibility.Pixel, }; RootParameter[] rootParameters = new RootParameter[] { new RootParameter(ShaderVisibility.Pixel, ranges) }; RootSignatureDescription rootSignatureDesc = new RootSignatureDescription(RootSignatureFlags.AllowInputAssemblerInputLayout, rootParameters, new StaticSamplerDescription[] { sampler }); 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.CompileFromFile("shaders.hlsl", "VSMain", "vs_5_0", SharpDX.D3DCompiler.ShaderFlags.Debug)); #else var vertexShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("shaders.hlsl", "VSMain", "vs_5_0")); #endif #if DEBUG var pixelShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("shaders.hlsl", "PSMain", "ps_5_0", SharpDX.D3DCompiler.ShaderFlags.Debug)); #else var pixelShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("shaders.hlsl", "PSMain", "ps_5_0")); #endif // Define the vertex input layout. InputElement[] inputElementDescs = new InputElement[] { new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0), new InputElement("TEXCOORD", 0, Format.R32G32_Float, 12, 0) }; // Describe and create the graphics pipeline state object (PSO). GraphicsPipelineStateDescription psoDesc = new GraphicsPipelineStateDescription() { InputLayout = new InputLayoutDescription(inputElementDescs), RootSignature = rootSignature, VertexShader = vertexShader, PixelShader = pixelShader, RasterizerState = RasterizerStateDescription.Default(), BlendState = BlendStateDescription.Default(), DepthStencilFormat = SharpDX.DXGI.Format.D32_Float, DepthStencilState = new DepthStencilStateDescription() { IsDepthEnabled = false, IsStencilEnabled = false }, SampleMask = int.MaxValue, PrimitiveTopologyType = PrimitiveTopologyType.Triangle, RenderTargetCount = 1, Flags = PipelineStateFlags.None, SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0), StreamOutput = new StreamOutputDescription() }; psoDesc.RenderTargetFormats[0] = SharpDX.DXGI.Format.R8G8B8A8_UNorm; pipelineState = device.CreateGraphicsPipelineState(psoDesc); // Create the command list. commandList = device.CreateCommandList(CommandListType.Direct, commandAllocator, pipelineState); // Create the vertex buffer. float aspectRatio = viewport.Width / viewport.Height; // Define the geometry for a triangle. Vertex[] triangleVertices = new Vertex[] { new Vertex() { position = new Vector3(0.0f, 0.25f * aspectRatio, 0.0f), uv = new Vector2(0.5f, 0.0f) }, new Vertex() { position = new Vector3(0.25f, -0.25f * aspectRatio, 0.0f), uv = new Vector2(1.0f, 1.0f) }, new Vertex() { position = new Vector3(-0.25f, -0.25f * aspectRatio, 0.0f), uv = new Vector2(0.0f, 1.0f) }, }; int vertexBufferSize = Utilities.SizeOf(triangleVertices); // Note: using upload heaps to transfer static data like vert buffers is not // recommended. Every time the GPU needs it, the upload heap will be marshalled // over. Please read up on Default Heap usage. An upload heap is used here for // code simplicity and because there are very few verts to actually transfer. vertexBuffer = device.CreateCommittedResource(new HeapProperties(HeapType.Upload), HeapFlags.None, ResourceDescription.Buffer(vertexBufferSize), ResourceStates.GenericRead); // Copy the triangle data to the vertex buffer. IntPtr pVertexDataBegin = vertexBuffer.Map(0); Utilities.Write(pVertexDataBegin, triangleVertices, 0, triangleVertices.Length); vertexBuffer.Unmap(0); // Initialize the vertex buffer view. vertexBufferView = new VertexBufferView(); vertexBufferView.BufferLocation = vertexBuffer.GPUVirtualAddress; vertexBufferView.StrideInBytes = Utilities.SizeOf <Vertex>(); vertexBufferView.SizeInBytes = vertexBufferSize; Resource textureUploadHeap; // Create the texture. // Describe and create a Texture2D. ResourceDescription textureDesc = ResourceDescription.Texture2D(Format.R8G8B8A8_UNorm, TextureWidth, TextureHeight); texture = device.CreateCommittedResource(new HeapProperties(HeapType.Default), HeapFlags.None, textureDesc, ResourceStates.CopyDestination); long uploadBufferSize = GetRequiredIntermediateSize(this.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, TexturePixelSize * TextureWidth, textureData.Length); handle.Free(); commandList.CopyTextureRegion(new TextureCopyLocation(texture, 0), 0, 0, 0, new TextureCopyLocation(textureUploadHeap, 0), null); commandList.ResourceBarrierTransition(this.texture, ResourceStates.CopyDestination, ResourceStates.PixelShaderResource); // Describe and create a SRV for the texture. ShaderResourceViewDescription srvDesc = new ShaderResourceViewDescription() { Shader4ComponentMapping = D3DXUtilities.DefaultComponentMapping(), Format = textureDesc.Format, Dimension = ShaderResourceViewDimension.Texture2D, }; srvDesc.Texture2D.MipLevels = 1; device.CreateShaderResourceView(this.texture, srvDesc, shaderRenderViewHeap.CPUDescriptorHandleForHeapStart); // Command lists are created in the recording state, but there is nothing // to record yet. The main loop expects it to be closed, so close it now. commandList.Close(); commandQueue.ExecuteCommandList(commandList); // Create synchronization objects. fence = device.CreateFence(0, FenceFlags.None); fenceValue = 1; // Create an event handle to use for frame synchronization. fenceEvent = new AutoResetEvent(false); WaitForPreviousFrame(); //release temp texture textureUploadHeap.Dispose(); }
public static float[] AddGpu(float[] left, float[] right) { if (left.Length != right.Length) { throw new InvalidOperationException(); } long size = (sizeof(float) * left.Length); float[] output = new float[left.Length]; Resource leftInputBuffer = DirectXHelpers.CreateBuffer(device, size, HeapType.Upload, ResourceFlags.None, ResourceStates.GenericRead); Resource rightInputBuffer = DirectXHelpers.CreateBuffer(device, size, HeapType.Upload, ResourceFlags.None, ResourceStates.GenericRead); Resource outputBuffer = DirectXHelpers.CreateBuffer(device, size, HeapType.Readback, ResourceFlags.None, ResourceStates.CopyDestination); fixed(float *pLeft = &left[0]) { var mappedMemory = leftInputBuffer.Map(0); Buffer.MemoryCopy(pLeft, mappedMemory.ToPointer(), size, size); leftInputBuffer.Unmap(0); } fixed(float *pRight = &right[0]) { var mappedMemory = rightInputBuffer.Map(0); Buffer.MemoryCopy(pRight, mappedMemory.ToPointer(), size, size); rightInputBuffer.Unmap(0); } var rootParameters = new RootParameter[3] { new RootParameter(ShaderVisibility.All, new RootDescriptor(0, 0), RootParameterType.ShaderResourceView), new RootParameter(ShaderVisibility.All, new RootDescriptor(1, 0), RootParameterType.ShaderResourceView), new RootParameter(ShaderVisibility.All, new RootDescriptor(0, 0), RootParameterType.UnorderedAccessView) }; var rootSignatureDesc = new RootSignatureDescription(RootSignatureFlags.AllowInputAssemblerInputLayout, rootParameters); RootSignature computeRootSignature = DirectXHelpers.CreateRootSignature(device, rootParameters); PipelineState computePipelineState = DirectXHelpers.CreateComputePipelineState(device, computeRootSignature, AddArrayShaderCode); //sw.Restart(); commandList.Close(); commandAllocator.Reset(); { commandList.Reset(commandAllocator, computePipelineState); commandList.SetComputeRootSignature(computeRootSignature); commandList.SetComputeRootShaderResourceView(0, leftInputBuffer.GPUVirtualAddress); commandList.SetComputeRootShaderResourceView(1, rightInputBuffer.GPUVirtualAddress); commandList.SetComputeRootShaderResourceView(2, outputBuffer.GPUVirtualAddress); commandList.Dispatch(left.Length / ShaderThreadCount, 1, 1); commandList.Close(); } commandQueue.ExecuteCommandList(commandList); FlushCommandQueue(); commandList.Reset(commandAllocator, null); //sw.Stop(); fixed(float *pOutput = &output[0]) { var mappedMemory = outputBuffer.Map(0); Buffer.MemoryCopy(mappedMemory.ToPointer(), pOutput, size, size); outputBuffer.Unmap(0); } return(output); }
private void LoadAssets() { DescriptorRange[] ranges = new DescriptorRange[] { new DescriptorRange() { RangeType = DescriptorRangeType.ConstantBufferView, BaseShaderRegister = 0, DescriptorCount = 1 } }; RootParameter parameter = new RootParameter(ShaderVisibility.Vertex, ranges); // Create a root signature. RootSignatureDescription rootSignatureDesc = new RootSignatureDescription(RootSignatureFlags.AllowInputAssemblerInputLayout, new RootParameter[] { parameter }); rootSignature = device.CreateRootSignature(rootSignatureDesc.Serialize()); // Create the pipeline state, which includes compiling and loading shaders. #if DEBUG var vertexShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("shaders.hlsl", "VSMain", "vs_5_0", SharpDX.D3DCompiler.ShaderFlags.Debug)); #else var vertexShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("shaders.hlsl", "VSMain", "vs_5_0")); #endif #if DEBUG var pixelShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("shaders.hlsl", "PSMain", "ps_5_0", SharpDX.D3DCompiler.ShaderFlags.Debug)); #else var pixelShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("shaders.hlsl", "PSMain", "ps_5_0")); #endif // Define the vertex input layout. InputElement[] inputElementDescs = new InputElement[] { new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0), new InputElement("COLOR", 0, Format.R32G32B32A32_Float, 12, 0) }; // Describe and create the graphics pipeline state object (PSO). GraphicsPipelineStateDescription psoDesc = new GraphicsPipelineStateDescription() { InputLayout = new InputLayoutDescription(inputElementDescs), RootSignature = rootSignature, VertexShader = vertexShader, PixelShader = pixelShader, RasterizerState = RasterizerStateDescription.Default(), BlendState = BlendStateDescription.Default(), DepthStencilFormat = SharpDX.DXGI.Format.D32_Float, DepthStencilState = DepthStencilStateDescription.Default(), SampleMask = int.MaxValue, PrimitiveTopologyType = PrimitiveTopologyType.Triangle, RenderTargetCount = 1, Flags = PipelineStateFlags.None, SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0), StreamOutput = new StreamOutputDescription() }; psoDesc.RenderTargetFormats[0] = SharpDX.DXGI.Format.R8G8B8A8_UNorm; pipelineState = device.CreateGraphicsPipelineState(psoDesc); // Create the command list. commandList = device.CreateCommandList(CommandListType.Direct, commandAllocator, pipelineState); // Command lists are created in the recording state, but there is nothing // to record yet. The main loop expects it to be closed, so close it now. commandList.Close(); // Create the vertex buffer. float aspectRatio = viewport.Width / viewport.Height; // Define the geometry for a cube. Vertex[] vertices = new[] { ////TOP new Vertex(new Vector3(-5, 5, 5), new Vector4(0, 1, 0, 0)), new Vertex(new Vector3(5, 5, 5), new Vector4(0, 1, 0, 0)), new Vertex(new Vector3(5, 5, -5), new Vector4(0, 1, 0, 0)), new Vertex(new Vector3(-5, 5, -5), new Vector4(0, 1, 0, 0)), //BOTTOM new Vertex(new Vector3(-5, -5, 5), new Vector4(1, 0, 1, 1)), new Vertex(new Vector3(5, -5, 5), new Vector4(1, 0, 1, 1)), new Vertex(new Vector3(5, -5, -5), new Vector4(1, 0, 1, 1)), new Vertex(new Vector3(-5, -5, -5), new Vector4(1, 0, 1, 1)), //LEFT new Vertex(new Vector3(-5, -5, 5), new Vector4(1, 0, 0, 1)), new Vertex(new Vector3(-5, 5, 5), new Vector4(1, 0, 0, 1)), new Vertex(new Vector3(-5, 5, -5), new Vector4(1, 0, 0, 1)), new Vertex(new Vector3(-5, -5, -5), new Vector4(1, 0, 0, 1)), //RIGHT new Vertex(new Vector3(5, -5, 5), new Vector4(1, 1, 0, 1)), new Vertex(new Vector3(5, 5, 5), new Vector4(1, 1, 0, 1)), new Vertex(new Vector3(5, 5, -5), new Vector4(1, 1, 0, 1)), new Vertex(new Vector3(5, -5, -5), new Vector4(1, 1, 0, 1)), //FRONT new Vertex(new Vector3(-5, 5, 5), new Vector4(0, 1, 1, 1)), new Vertex(new Vector3(5, 5, 5), new Vector4(0, 1, 1, 1)), new Vertex(new Vector3(5, -5, 5), new Vector4(0, 1, 1, 1)), new Vertex(new Vector3(-5, -5, 5), new Vector4(0, 1, 1, 1)), //BACK new Vertex(new Vector3(-5, 5, -5), new Vector4(0, 0, 1, 1)), new Vertex(new Vector3(5, 5, -5), new Vector4(0, 0, 1, 1)), new Vertex(new Vector3(5, -5, -5), new Vector4(0, 0, 1, 1)), new Vertex(new Vector3(-5, -5, -5), new Vector4(0, 0, 1, 1)) }; int vertexBufferSize = Utilities.SizeOf(vertices); // Note: using upload heaps to transfer static data like vert buffers is not // recommended. Every time the GPU needs it, the upload heap will be marshalled // over. Please read up on Default Heap usage. An upload heap is used here for // code simplicity and because there are very few verts to actually transfer. vertexBuffer = device.CreateCommittedResource(new HeapProperties(HeapType.Upload), HeapFlags.None, ResourceDescription.Buffer(vertexBufferSize), ResourceStates.GenericRead); // Copy the triangle data to the vertex buffer. IntPtr pVertexDataBegin = vertexBuffer.Map(0); Utilities.Write(pVertexDataBegin, vertices, 0, vertices.Length); vertexBuffer.Unmap(0); // Initialize the vertex buffer view. vertexBufferView = new VertexBufferView(); vertexBufferView.BufferLocation = vertexBuffer.GPUVirtualAddress; vertexBufferView.StrideInBytes = Utilities.SizeOf <Vertex>(); vertexBufferView.SizeInBytes = vertexBufferSize; //Create Index Buffer //Indices int[] indices = new int[] { 0, 1, 2, 0, 2, 3, 4, 6, 5, 4, 7, 6, 8, 9, 10, 8, 10, 11, 12, 14, 13, 12, 15, 14, 16, 18, 17, 16, 19, 18, 20, 21, 22, 20, 22, 23 }; int indexBufferSize = Utilities.SizeOf(indices); indexBuffer = device.CreateCommittedResource(new HeapProperties(HeapType.Upload), HeapFlags.None, ResourceDescription.Buffer(indexBufferSize), ResourceStates.GenericRead); // Copy the triangle data to the vertex buffer. IntPtr pIndexDataBegin = indexBuffer.Map(0); Utilities.Write(pIndexDataBegin, indices, 0, indices.Length); indexBuffer.Unmap(0); // Initialize the index buffer view. indexBufferView = new IndexBufferView(); indexBufferView.BufferLocation = indexBuffer.GPUVirtualAddress; indexBufferView.Format = Format.R32_UInt; indexBufferView.SizeInBytes = indexBufferSize; //constant Buffer for each cubes constantBufferViewHeap = device.CreateDescriptorHeap(new DescriptorHeapDescription() { DescriptorCount = NumCubes, Type = DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView, Flags = DescriptorHeapFlags.ShaderVisible }); int constantBufferSize = (Utilities.SizeOf <Transform>() + 255) & ~255; constantBuffer = device.CreateCommittedResource(new HeapProperties(HeapType.Upload), HeapFlags.None, ResourceDescription.Buffer(constantBufferSize * NumCubes), ResourceStates.GenericRead); constantBufferDescriptorSize = device.GetDescriptorHandleIncrementSize(DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView); //First cube ConstantBufferViewDescription cbvDesc = new ConstantBufferViewDescription() { BufferLocation = constantBuffer.GPUVirtualAddress, SizeInBytes = constantBufferSize }; CpuDescriptorHandle cbHandleHeapStart = constantBufferViewHeap.CPUDescriptorHandleForHeapStart; for (int i = 0; i < NumCubes; i++) { device.CreateConstantBufferView(cbvDesc, cbHandleHeapStart); cbvDesc.BufferLocation += Utilities.SizeOf <Transform>(); cbHandleHeapStart += constantBufferDescriptorSize; } InitBundles(); }
private void LoadAssets() { DescriptorRange[] ranges = new DescriptorRange[] { new DescriptorRange() { RangeType = DescriptorRangeType.ConstantBufferView, BaseShaderRegister = 0, OffsetInDescriptorsFromTableStart = int.MinValue, DescriptorCount = 1 } }; RootParameter parameter = new RootParameter(ShaderVisibility.Vertex, ranges); // Create an empty root signature. RootSignatureDescription rootSignatureDesc = new RootSignatureDescription(RootSignatureFlags.AllowInputAssemblerInputLayout, new RootParameter[] { parameter }); rootSignature = device.CreateRootSignature(rootSignatureDesc.Serialize()); // Create the pipeline state, which includes compiling and loading shaders. #if DEBUG var vertexShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("shaders.hlsl", "VSMain", "vs_5_0", SharpDX.D3DCompiler.ShaderFlags.Debug)); #else var vertexShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("shaders.hlsl", "VSMain", "vs_5_0")); #endif #if DEBUG var pixelShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("shaders.hlsl", "PSMain", "ps_5_0", SharpDX.D3DCompiler.ShaderFlags.Debug)); #else var pixelShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("shaders.hlsl", "PSMain", "ps_5_0")); #endif // Define the vertex input layout. InputElement[] inputElementDescs = new InputElement[] { new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0), new InputElement("COLOR", 0, Format.R32G32B32A32_Float, 12, 0) }; // Describe and create the graphics pipeline state object (PSO). GraphicsPipelineStateDescription psoDesc = new GraphicsPipelineStateDescription() { InputLayout = new InputLayoutDescription(inputElementDescs), RootSignature = rootSignature, VertexShader = vertexShader, PixelShader = pixelShader, RasterizerState = RasterizerStateDescription.Default(), BlendState = BlendStateDescription.Default(), DepthStencilFormat = SharpDX.DXGI.Format.D32_Float, DepthStencilState = new DepthStencilStateDescription() { IsDepthEnabled = false, IsStencilEnabled = false }, SampleMask = int.MaxValue, PrimitiveTopologyType = PrimitiveTopologyType.Triangle, RenderTargetCount = 1, Flags = PipelineStateFlags.None, SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0), StreamOutput = new StreamOutputDescription() }; psoDesc.RenderTargetFormats[0] = SharpDX.DXGI.Format.R8G8B8A8_UNorm; pipelineState = device.CreateGraphicsPipelineState(psoDesc); // Create the command list. commandList = device.CreateCommandList(CommandListType.Direct, commandAllocator, pipelineState); // Create the vertex buffer. float aspectRatio = viewport.Width / viewport.Height; // Define the geometry for a triangle. Vertex[] triangleVertices = new Vertex[] { new Vertex() { position = new Vector3(0.0f, 0.25f * aspectRatio, 0.0f), color = new Vector4(1.0f, 0.0f, 0.0f, 1.0f) }, new Vertex() { position = new Vector3(0.25f, -0.25f * aspectRatio, 0.0f), color = new Vector4(0.0f, 1.0f, 0.0f, 1.0f) }, new Vertex() { position = new Vector3(-0.25f, -0.25f * aspectRatio, 0.0f), color = new Vector4(0.0f, 0.0f, 1.0f, 1.0f) }, }; int vertexBufferSize = Utilities.SizeOf(triangleVertices); // Note: using upload heaps to transfer static data like vert buffers is not // recommended. Every time the GPU needs it, the upload heap will be marshalled // over. Please read up on Default Heap usage. An upload heap is used here for // code simplicity and because there are very few verts to actually transfer. vertexBuffer = device.CreateCommittedResource(new HeapProperties(HeapType.Upload), HeapFlags.None, ResourceDescription.Buffer(vertexBufferSize), ResourceStates.GenericRead); // Copy the triangle data to the vertex buffer. IntPtr pVertexDataBegin = vertexBuffer.Map(0); Utilities.Write(pVertexDataBegin, triangleVertices, 0, triangleVertices.Length); vertexBuffer.Unmap(0); // Initialize the vertex buffer view. vertexBufferView = new VertexBufferView(); vertexBufferView.BufferLocation = vertexBuffer.GPUVirtualAddress; vertexBufferView.StrideInBytes = Utilities.SizeOf <Vertex>(); vertexBufferView.SizeInBytes = vertexBufferSize; // Command lists are created in the recording state, but there is nothing // to record yet. The main loop expects it to be closed, so close it now. commandList.Close(); constantBuffer = device.CreateCommittedResource(new HeapProperties(HeapType.Upload), HeapFlags.None, ResourceDescription.Buffer(1024 * 64), ResourceStates.GenericRead); //// Describe and create a constant buffer view. ConstantBufferViewDescription cbvDesc = new ConstantBufferViewDescription() { BufferLocation = constantBuffer.GPUVirtualAddress, SizeInBytes = (Utilities.SizeOf <ConstantBuffer>() + 255) & ~255 }; device.CreateConstantBufferView(cbvDesc, constantBufferViewHeap.CPUDescriptorHandleForHeapStart); // Initialize and map the constant buffers. We don't unmap this until the // app closes. Keeping things mapped for the lifetime of the resource is okay. constantBufferPointer = constantBuffer.Map(0); Utilities.Write(constantBufferPointer, ref constantBufferData); // Create synchronization objects. fence = device.CreateFence(0, FenceFlags.None); fenceValue = 1; // Create an event handle to use for frame synchronization. fenceEvent = new AutoResetEvent(false); }
public static async Task RunAsync(GraphicsDevice device) { bool generateWithDelegate = false; // Create graphics buffer int width = 10; int height = 10; float[] array = new float[width * height]; for (int i = 0; i < array.Length; i++) { array[i] = i; } float[] outputArray = new float[width * height]; using GraphicsBuffer <float> sourceBuffer = GraphicsBuffer.Create <float>(device, array, ResourceFlags.None); using GraphicsBuffer <float> destinationBuffer = GraphicsBuffer.Create <float>(device, array.Length * 2, ResourceFlags.AllowUnorderedAccess); GraphicsBuffer <float> slicedDestinationBuffer = destinationBuffer.Slice(20, 60); slicedDestinationBuffer = slicedDestinationBuffer.Slice(10, 50); DescriptorSet descriptorSet = new DescriptorSet(device, 2); descriptorSet.AddUnorderedAccessViews(slicedDestinationBuffer); descriptorSet.AddShaderResourceViews(sourceBuffer); // Generate computer shader ShaderGenerator shaderGenerator = generateWithDelegate ? CreateShaderGeneratorWithDelegate(sourceBuffer, destinationBuffer) : CreateShaderGeneratorWithClass(); ShaderGeneratorResult result = shaderGenerator.GenerateShader(); // Compile shader byte[] shaderBytecode = ShaderCompiler.Compile(ShaderStage.ComputeShader, result.ShaderSource, result.EntryPoints["compute"]); DescriptorRange[] descriptorRanges = new DescriptorRange[] { new DescriptorRange(DescriptorRangeType.UnorderedAccessView, 1, 0), new DescriptorRange(DescriptorRangeType.ShaderResourceView, 1, 0) }; RootParameter rootParameter = new RootParameter(new RootDescriptorTable(descriptorRanges), ShaderVisibility.All); RootSignatureDescription rootSignatureDescription = new RootSignatureDescription(RootSignatureFlags.None, new[] { rootParameter }); RootSignature rootSignature = new RootSignature(device, rootSignatureDescription); PipelineState pipelineState = new PipelineState(device, rootSignature, shaderBytecode); // Execute computer shader using (CommandList commandList = new CommandList(device, CommandListType.Compute)) { commandList.SetPipelineState(pipelineState); commandList.SetComputeRootDescriptorTable(0, descriptorSet); commandList.Dispatch(1, 1, 1); await commandList.FlushAsync(); } // Print matrix Console.WriteLine("Before:"); PrintMatrix(array, width, height); destinationBuffer.GetData(outputArray.AsSpan()); Console.WriteLine(); Console.WriteLine("After:"); PrintMatrix(outputArray, width, height); }
public Boolean Finalize(RootSignatureFlags flags) { if (m_Finalized) { return(false); } if (m_NumInitializedStaticSamplers != m_NumSamplers) { return(false); } // make root parameter array List <RootParameter> rootParams = new List <RootParameter>(); foreach (H1RootParameterDX12 param in m_ParamArray) { rootParams.Add(param.Parameter); } // create root signature description RootSignatureDescription rootSigDesc = new RootSignatureDescription(flags, rootParams.ToArray(), m_SamplerArray.ToArray()); // clear descriptor table bit map for (Int32 i = 0; i < m_DescriptorTableBitMap.Count; ++i) { m_DescriptorTableBitMap[i] = false; } m_MaxDescriptorCacheHandleCount = 0; for (Int32 param = 0; param < m_NumParameters; ++param) { RootParameter rootParam = rootSigDesc.Parameters[param]; m_DescriptorTableSize[param] = 0; if (rootParam.ParameterType == RootParameterType.DescriptorTable) { // if there is no descriptor range for descriptor table if (rootParam.DescriptorTable.Count() == 0) { return(false); } // we don't care about sampler descriptor tables // we don't manage them in descriptor cache if (rootParam.DescriptorTable[0].RangeType == DescriptorRangeType.Sampler) { continue; } // set the descriptor table bit map as true m_DescriptorTableBitMap[param] = true; // looping descriptor table and calculate descriptor table size for current root parameter for (Int32 tableRange = 0; tableRange < rootParam.DescriptorTable.Count(); ++tableRange) { m_DescriptorTableSize[param] += rootParam.DescriptorTable[tableRange].DescriptorCount; } m_MaxDescriptorCacheHandleCount += m_DescriptorTableSize[param]; } } // create root signature instance Device deviceRef = H1Global <H1ManagedRenderer> .Instance.Device; m_RootSignature = deviceRef.CreateRootSignature(rootSigDesc.Serialize()); // mark as finalized m_Finalized = true; return(true); }
private void PlatformConstruct(GraphicsDevice graphicsDevice, PipelineLayoutDescription description) { var rootParameters = new RootParameter[description.Entries.Length]; for (var i = 0; i < description.Entries.Length; i++) { var entry = description.Entries[i]; switch (entry.EntryType) { case PipelineLayoutEntryType.Resource: rootParameters[i] = new RootParameter( entry.Visibility.ToShaderVisibility(), new RootDescriptor(entry.Resource.ShaderRegister, 0), entry.ResourceType.ToRootParameterType()); break; case PipelineLayoutEntryType.ResourceView: rootParameters[i] = new RootParameter( entry.Visibility.ToShaderVisibility(), new DescriptorRange( entry.ResourceType.ToDescriptorRangeType(), entry.ResourceView.ResourceCount, entry.ResourceView.BaseShaderRegister)); break; default: throw new System.InvalidOperationException(); } } var staticSamplerStates = description.StaticSamplerStates ?? new StaticSamplerDescription[0]; var staticSamplerDescriptions = new D3D12.StaticSamplerDescription[staticSamplerStates.Length]; for (var i = 0; i < staticSamplerStates.Length; i++) { var staticSamplerState = staticSamplerStates[i]; var samplerStateDescription = new D3D12.SamplerStateDescription { Filter = staticSamplerState.SamplerStateDescription.Filter.ToFilter(), AddressU = TextureAddressMode.Wrap, AddressV = TextureAddressMode.Wrap, AddressW = TextureAddressMode.Clamp, ComparisonFunction = Comparison.Always, MinimumLod = 0, MaximumLod = float.MaxValue, MaximumAnisotropy = staticSamplerState.SamplerStateDescription.MaxAnisotropy }; staticSamplerDescriptions[i] = new D3D12.StaticSamplerDescription( samplerStateDescription, staticSamplerState.Visibility.ToShaderVisibility(), staticSamplerState.ShaderRegister, 0); } var rootSignatureDescription = new RootSignatureDescription( RootSignatureFlags.AllowInputAssemblerInputLayout, parameters: rootParameters, samplers: staticSamplerDescriptions); var serializedRootSignatureDescription = rootSignatureDescription.Serialize(); DeviceRootSignature = AddDisposable(graphicsDevice.Device.CreateRootSignature(serializedRootSignatureDescription)); }
public void BuildPSO(Device3 device, GraphicsCommandList commandList) { buffer = new CBuffer() { Rows = 3, Columns = 5 }; DescriptorHeapDescription cbvHeapDesc = new DescriptorHeapDescription() { DescriptorCount = 1, Flags = DescriptorHeapFlags.ShaderVisible, Type = DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView }; _constantBufferViewHeap = device.CreateDescriptorHeap(cbvHeapDesc); DescriptorHeapDescription srvHeapDesc = new DescriptorHeapDescription() { DescriptorCount = 1, Flags = DescriptorHeapFlags.ShaderVisible, Type = DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView }; _srvDescriptorHeap = device.CreateDescriptorHeap(srvHeapDesc); DescriptorRange[] ranges = new DescriptorRange[] { new DescriptorRange() { RangeType = DescriptorRangeType.ShaderResourceView, DescriptorCount = 1, OffsetInDescriptorsFromTableStart = int.MinValue, BaseShaderRegister = 0 } }; //Get sampler state setup StaticSamplerDescription sampler = new StaticSamplerDescription() { Filter = Filter.MinimumMinMagMipPoint, AddressU = TextureAddressMode.Border, AddressV = TextureAddressMode.Border, AddressW = TextureAddressMode.Border, MipLODBias = 0, MaxAnisotropy = 0, ComparisonFunc = Comparison.Never, BorderColor = StaticBorderColor.TransparentBlack, MinLOD = 0.0f, MaxLOD = float.MaxValue, ShaderRegister = 0, RegisterSpace = 0, ShaderVisibility = ShaderVisibility.Pixel, }; RootParameter[] rootParameters = new RootParameter[] { new RootParameter(ShaderVisibility.Pixel, ranges), new RootParameter(ShaderVisibility.Pixel, new RootDescriptor(1, 0), RootParameterType.ConstantBufferView) }; // Create an empty root signature. RootSignatureDescription rootSignatureDesc = new RootSignatureDescription(RootSignatureFlags.AllowInputAssemblerInputLayout, rootParameters, new StaticSamplerDescription[] { sampler }); _rootSignature = device.CreateRootSignature(rootSignatureDesc.Serialize()); // Create the pipeline state, which includes compiling and loading shaders. #if DEBUG var vertexShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("Shaders/AtlasWalk.hlsl", "VSMain", "vs_5_0", SharpDX.D3DCompiler.ShaderFlags.Debug)); #else var vertexShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("Shaders/AtlasWalk.hlsl", "VSMain", "vs_5_0")); #endif #if DEBUG var pixelShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("Shaders/AtlasWalk.hlsl", "PSMain", "ps_5_0", SharpDX.D3DCompiler.ShaderFlags.Debug)); #else var pixelShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("Shaders/AtlasWalk.hlsl", "PSMain", "ps_5_0")); #endif // Define the vertex input layout. InputElement[] inputElementDescs = new InputElement[] { new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0), new InputElement("TEXCOORD", 0, Format.R32G32_Float, 12, 0) }; // Describe and create the graphics pipeline state object (PSO). GraphicsPipelineStateDescription psoDesc = new GraphicsPipelineStateDescription() { InputLayout = new InputLayoutDescription(inputElementDescs), RootSignature = _rootSignature, VertexShader = vertexShader, PixelShader = pixelShader, RasterizerState = RasterizerStateDescription.Default(), BlendState = BlendStateDescription.Default(), DepthStencilFormat = SharpDX.DXGI.Format.D32_Float, DepthStencilState = new DepthStencilStateDescription() { IsDepthEnabled = false, IsStencilEnabled = false }, SampleMask = int.MaxValue, PrimitiveTopologyType = PrimitiveTopologyType.Triangle, RenderTargetCount = 1, Flags = PipelineStateFlags.None, SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0), StreamOutput = new StreamOutputDescription() }; psoDesc.RenderTargetFormats[0] = SharpDX.DXGI.Format.R8G8B8A8_UNorm; _pipelineState = device.CreateGraphicsPipelineState(psoDesc); // Define the geometry for a triangle. Vertex[] triangleVertices = new Vertex[] { new Vertex() { position = new Vector3(-0.5f, -0.5f, 0.5f), texCoord = new Vector2(1.0f, 1.0f) }, new Vertex() { position = new Vector3(-0.5f, 0.5f, 0.5f), texCoord = new Vector2(1.0f, 0.0f) }, new Vertex() { position = new Vector3(0.5f, -0.5f, 0.5f), texCoord = new Vector2(0.0f, 1.0f) }, new Vertex() { position = new Vector3(0.5f, 0.5f, 0.5f), texCoord = new Vector2(0.0f, 0.0f) } }; int vertexBufferSize = Utilities.SizeOf(triangleVertices); // Note: using upload heaps to transfer static data like vert buffers is not // recommended. Every time the GPU needs it, the upload heap will be marshalled // over. Please read up on Default Heap usage. An upload heap is used here for // code simplicity and because there are very few verts to actually transfer. _vertexBuffer = device.CreateCommittedResource(new HeapProperties(HeapType.Upload), HeapFlags.None, ResourceDescription.Buffer(vertexBufferSize), ResourceStates.GenericRead); // Copy the triangle data to the vertex buffer. IntPtr pVertexDataBegin = _vertexBuffer.Map(0); Utilities.Write(pVertexDataBegin, triangleVertices, 0, triangleVertices.Length); _vertexBuffer.Unmap(0); _indicies = new int[] { 0, 1, 2, 3, 2, 1 }; int indBufferSize = Utilities.SizeOf(_indicies); _indexBuffer = device.CreateCommittedResource(new HeapProperties(HeapType.Upload), HeapFlags.None, ResourceDescription.Buffer(indBufferSize), ResourceStates.GenericRead); IntPtr pIndBegin = _indexBuffer.Map(0); Utilities.Write(pIndBegin, _indicies, 0, _indicies.Length); _indexBuffer.Unmap(0); _indexBufferView = new IndexBufferView() { BufferLocation = _indexBuffer.GPUVirtualAddress, Format = Format.R32_UInt, SizeInBytes = indBufferSize }; // Initialize the vertex buffer view. _vertexBufferView = new VertexBufferView { BufferLocation = _vertexBuffer.GPUVirtualAddress, StrideInBytes = Utilities.SizeOf <Vertex>(), SizeInBytes = vertexBufferSize }; Resource textureUploadHeap; // Create the texture. // Describe and create a Texture2D. ResourceDescription textureDesc = ResourceDescription.Texture2D(Format.R8G8B8A8_UNorm, textureWidth, textureHeight); _texture = device.CreateCommittedResource(new HeapProperties(HeapType.Default), HeapFlags.None, textureDesc, ResourceStates.CopyDestination); long uploadBufferSize = GetRequiredIntermediateSize(device, _texture, 0, 1); // Create the GPU upload buffer. textureUploadHeap = device.CreateCommittedResource(new HeapProperties(CpuPageProperty.WriteBack, MemoryPool.L0), HeapFlags.None, ResourceDescription.Texture2D(Format.R8G8B8A8_UNorm, textureWidth, textureHeight), ResourceStates.GenericRead); // Copy data to the intermediate upload heap and then schedule a copy // from the upload heap to the Texture2D. byte[] textureData = GenerateTextureData(); GCHandle handle = GCHandle.Alloc(textureData, GCHandleType.Pinned); IntPtr ptr = Marshal.UnsafeAddrOfPinnedArrayElement(textureData, 0); textureUploadHeap.WriteToSubresource(0, null, ptr, 4 * textureWidth, textureData.Length); handle.Free(); commandList.CopyTextureRegion(new TextureCopyLocation(_texture, 0), 0, 0, 0, new TextureCopyLocation(textureUploadHeap, 0), null); commandList.ResourceBarrierTransition(_texture, ResourceStates.CopyDestination, ResourceStates.PixelShaderResource); // Describe and create a SRV for the texture. ShaderResourceViewDescription srvDesc = new ShaderResourceViewDescription() { Shader4ComponentMapping = ComponentMapping(0, 1, 2, 3), Format = textureDesc.Format, Dimension = ShaderResourceViewDimension.Texture2D, }; srvDesc.Texture2D.MipLevels = 1; device.CreateShaderResourceView(_texture, srvDesc, _srvDescriptorHeap.CPUDescriptorHandleForHeapStart); _constantBuffer = device.CreateCommittedResource(new HeapProperties(HeapType.Upload), HeapFlags.None, ResourceDescription.Buffer(1024 * 64), ResourceStates.GenericRead); //// Describe and create a constant buffer view. ConstantBufferViewDescription cbvDesc = new ConstantBufferViewDescription() { BufferLocation = _constantBuffer.GPUVirtualAddress, SizeInBytes = (Utilities.SizeOf <CBuffer>() + 255) & ~255 }; device.CreateConstantBufferView(cbvDesc, _constantBufferViewHeap.CPUDescriptorHandleForHeapStart); // Initialize and map the constant buffers. We don't unmap this until the // app closes. Keeping things mapped for the lifetime of the resource is okay. _constantBufferPointer = _constantBuffer.Map(0); Utilities.Write(_constantBufferPointer, ref buffer); _resources = new[] { new GraphicsResource() { Heap = _srvDescriptorHeap, Register = 0, type = ResourceType.DescriptorTable }, new GraphicsResource() { Resource = _constantBuffer, Register = 1, type = ResourceType.ConstantBufferView } }; }
private void LoadAssets() { RootParameter parameter1 = new RootParameter(ShaderVisibility.All, new DescriptorRange() { RangeType = DescriptorRangeType.ConstantBufferView, BaseShaderRegister = 0, DescriptorCount = 1 }); RootParameter parameter2 = new RootParameter(ShaderVisibility.Pixel, new DescriptorRange() { RangeType = DescriptorRangeType.ShaderResourceView, BaseShaderRegister = 0, DescriptorCount = 1 }); RootParameter parameter3 = new RootParameter(ShaderVisibility.Pixel, new DescriptorRange() { RangeType = DescriptorRangeType.Sampler, BaseShaderRegister = 0, DescriptorCount = 1 }); // Create a root signature. RootSignatureDescription rootSignatureDesc = new RootSignatureDescription(RootSignatureFlags.AllowInputAssemblerInputLayout, new RootParameter[] { parameter1, parameter2, parameter3 }); rootSignature = device.CreateRootSignature(rootSignatureDesc.Serialize()); // Create the pipeline state, which includes compiling and loading shaders. #if DEBUG var vertexShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("shaders.hlsl", "VSMain", "vs_5_0", SharpDX.D3DCompiler.ShaderFlags.Debug)); #else var vertexShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("shaders.hlsl", "VSMain", "vs_5_0")); #endif #if DEBUG var pixelShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("shaders.hlsl", "PSMain", "ps_5_0", SharpDX.D3DCompiler.ShaderFlags.Debug)); #else var pixelShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("shaders.hlsl", "PSMain", "ps_5_0")); #endif // Define the vertex input layout. InputElement[] inputElementDescs = new InputElement[] { new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0), new InputElement("NORMAL", 0, Format.R32G32B32_Float, 12, 0), new InputElement("TEXCOORD", 0, Format.R32G32B32_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.D32_Float, DepthStencilState = DepthStencilStateDescription.Default(), SampleMask = int.MaxValue, PrimitiveTopologyType = PrimitiveTopologyType.Triangle, RenderTargetCount = 1, Flags = PipelineStateFlags.None, SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0), StreamOutput = new StreamOutputDescription() }; psoDesc.RenderTargetFormats[0] = SharpDX.DXGI.Format.R8G8B8A8_UNorm; pipelineState = device.CreateGraphicsPipelineState(psoDesc); // Create the command list. commandList = device.CreateCommandList(CommandListType.Direct, commandAllocator, pipelineState); // Command lists are created in the recording state, but there is nothing // to record yet. The main loop expects it to be closed, so close it now. commandList.Close(); // Create the vertex buffer. float aspectRatio = viewport.Width / viewport.Height; //constant Buffer int constantBufferSize = (Utilities.SizeOf <Transform>() + 255) & ~255; constantBuffer = device.CreateCommittedResource(new HeapProperties(HeapType.Upload), HeapFlags.None, ResourceDescription.Buffer(constantBufferSize), ResourceStates.GenericRead); constantBufferDescriptorSize = device.GetDescriptorHandleIncrementSize(DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView); //constant buffer ConstantBufferViewDescription cbvDesc = new ConstantBufferViewDescription() { BufferLocation = constantBuffer.GPUVirtualAddress, SizeInBytes = constantBufferSize }; CpuDescriptorHandle cbHandleHeapStart = constantBufferViewHeap.CPUDescriptorHandleForHeapStart; device.CreateConstantBufferView(cbvDesc, cbHandleHeapStart); cbvDesc.BufferLocation += Utilities.SizeOf <Transform>(); cbHandleHeapStart += constantBufferDescriptorSize; LoadMesh(cbHandleHeapStart); // Create synchronization objects. { fence = device.CreateFence(0, FenceFlags.None); fenceValue = 1; // Create an event handle to use for frame synchronization. fenceEvent = new AutoResetEvent(false); } InitBundles(); }
public void BuildPSO(Device3 device, GraphicsCommandList commandList) { Projection = Matrix.PerspectiveFovLH((float)Math.PI / 3f, 4f / 3f, 1, 1000); View = Matrix.LookAtLH(new Vector3(10 * (float)Math.Sin(rotation), 5, 10 * (float)Math.Cos(rotation)), Vector3.Zero, Vector3.UnitY); World = Matrix.Translation(-2.5f, -2.5f, -2.5f); DescriptorHeapDescription cbvHeapDesc = new DescriptorHeapDescription() { DescriptorCount = 1, Flags = DescriptorHeapFlags.ShaderVisible, Type = DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView }; _perPassViewHeap = device.CreateDescriptorHeap(cbvHeapDesc); RootParameter[] rootParameters = new RootParameter[] { new RootParameter(ShaderVisibility.All, new RootDescriptor(0, 0), RootParameterType.ConstantBufferView) }; // Create an empty root signature. RootSignatureDescription rootSignatureDesc = new RootSignatureDescription(RootSignatureFlags.AllowInputAssemblerInputLayout, rootParameters); _rootSignature = device.CreateRootSignature(rootSignatureDesc.Serialize()); // Create the pipeline state, which includes compiling and loading shaders. #if DEBUG var vertexShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("Shaders/Untextured.hlsl", "VSMain", "vs_5_0", SharpDX.D3DCompiler.ShaderFlags.Debug)); #else var vertexShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("Shaders/Untextured.hlsl", "VSMain", "vs_5_0")); #endif #if DEBUG var pixelShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("Shaders/Untextured.hlsl", "PSMain", "ps_5_0", SharpDX.D3DCompiler.ShaderFlags.Debug)); #else var pixelShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("Shaders/Untextured.hlsl", "PSMain", "ps_5_0")); #endif // Define the vertex input layout. InputElement[] inputElementDescs = new InputElement[] { new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0), new InputElement("COLOR", 0, Format.R32G32B32A32_Float, 12, 0) }; // Describe and create the graphics pipeline state object (PSO). GraphicsPipelineStateDescription psoDesc = new GraphicsPipelineStateDescription() { InputLayout = new InputLayoutDescription(inputElementDescs), RootSignature = _rootSignature, VertexShader = vertexShader, PixelShader = pixelShader, RasterizerState = RasterizerStateDescription.Default(), BlendState = BlendStateDescription.Default(), DepthStencilFormat = SharpDX.DXGI.Format.D24_UNorm_S8_UInt, DepthStencilState = DepthStencilStateDescription.Default(), SampleMask = int.MaxValue, PrimitiveTopologyType = PrimitiveTopologyType.Triangle, RenderTargetCount = 1, Flags = PipelineStateFlags.None, SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0), StreamOutput = new StreamOutputDescription() }; psoDesc.RenderTargetFormats[0] = SharpDX.DXGI.Format.R8G8B8A8_UNorm; _pipelineState = device.CreateGraphicsPipelineState(psoDesc); // Define the geometry for a triangle. Vertex[] triangleVertices = new Vertex[] { //Front new Vertex() { Position = new Vector3(0, 0, 0), Color = new Vector4(0, 0, 1, 1) }, new Vertex() { Position = new Vector3(0, 5, 0), Color = new Vector4(0, 0, 1, 1) }, new Vertex() { Position = new Vector3(5, 0, 0), Color = new Vector4(0, 0, 1, 1) }, new Vertex() { Position = new Vector3(5, 5, 0), Color = new Vector4(0, 0, 1, 1) }, //Back new Vertex() { Position = new Vector3(0, 0, 5), Color = new Vector4(0, 0, 1, 1) }, new Vertex() { Position = new Vector3(0, 5, 5), Color = new Vector4(0, 0, 1, 1) }, new Vertex() { Position = new Vector3(5, 0, 5), Color = new Vector4(0, 0, 1, 1) }, new Vertex() { Position = new Vector3(5, 5, 5), Color = new Vector4(0, 0, 1, 1) }, //Left new Vertex() { Position = new Vector3(0, 0, 0), Color = new Vector4(0, 1, 0, 1) }, new Vertex() { Position = new Vector3(0, 5, 0), Color = new Vector4(0, 1, 0, 1) }, new Vertex() { Position = new Vector3(0, 0, 5), Color = new Vector4(0, 1, 0, 1) }, new Vertex() { Position = new Vector3(0, 5, 5), Color = new Vector4(0, 1, 0, 1) }, //Right new Vertex() { Position = new Vector3(5, 0, 0), Color = new Vector4(0, 1, 0, 1) }, new Vertex() { Position = new Vector3(5, 5, 0), Color = new Vector4(0, 1, 0, 1) }, new Vertex() { Position = new Vector3(5, 0, 5), Color = new Vector4(0, 1, 0, 1) }, new Vertex() { Position = new Vector3(5, 5, 5), Color = new Vector4(0, 1, 0, 1) }, //Top new Vertex() { Position = new Vector3(0, 0, 0), Color = new Vector4(1, 0, 0, 1) }, new Vertex() { Position = new Vector3(0, 0, 5), Color = new Vector4(1, 0, 0, 1) }, new Vertex() { Position = new Vector3(5, 0, 0), Color = new Vector4(1, 0, 0, 1) }, new Vertex() { Position = new Vector3(5, 0, 5), Color = new Vector4(1, 0, 0, 1) }, //Bottom new Vertex() { Position = new Vector3(0, 5, 0), Color = new Vector4(1, 0, 0, 1) }, new Vertex() { Position = new Vector3(0, 5, 5), Color = new Vector4(1, 0, 0, 1) }, new Vertex() { Position = new Vector3(5, 5, 0), Color = new Vector4(1, 0, 0, 1) }, new Vertex() { Position = new Vector3(5, 5, 5), Color = new Vector4(1, 0, 0, 1) } }; int vertexBufferSize = Utilities.SizeOf(triangleVertices); // Note: using upload heaps to transfer static data like vert buffers is not // recommended. Every time the GPU needs it, the upload heap will be marshalled // over. Please read up on Default Heap usage. An upload heap is used here for // code simplicity and because there are very few verts to actually transfer. _vertexBuffer = device.CreateCommittedResource(new HeapProperties(HeapType.Upload), HeapFlags.None, ResourceDescription.Buffer(vertexBufferSize), ResourceStates.GenericRead); // Copy the triangle data to the vertex buffer. IntPtr pVertexDataBegin = _vertexBuffer.Map(0); Utilities.Write(pVertexDataBegin, triangleVertices, 0, triangleVertices.Length); _vertexBuffer.Unmap(0); _indicies = new int[] { 0, 1, 2, 3, 2, 1, 6, 5, 4, 5, 6, 7, 10, 9, 8, 9, 10, 11, 12, 13, 14, 15, 14, 13, 18, 17, 16, 17, 18, 19, 20, 21, 22, 23, 22, 21 }; int indBufferSize = Utilities.SizeOf(_indicies); _indexBuffer = device.CreateCommittedResource(new HeapProperties(HeapType.Upload), HeapFlags.None, ResourceDescription.Buffer(indBufferSize), ResourceStates.GenericRead); IntPtr pIndBegin = _indexBuffer.Map(0); Utilities.Write(pIndBegin, _indicies, 0, _indicies.Length); _indexBuffer.Unmap(0); _indexBufferView = new IndexBufferView() { BufferLocation = _indexBuffer.GPUVirtualAddress, Format = Format.R32_UInt, SizeInBytes = indBufferSize }; // Initialize the vertex buffer view. _vertexBufferView = new VertexBufferView { BufferLocation = _vertexBuffer.GPUVirtualAddress, StrideInBytes = Utilities.SizeOf <Vertex>(), SizeInBytes = vertexBufferSize }; _perPassBuffer = device.CreateCommittedResource(new HeapProperties(HeapType.Upload), HeapFlags.None, ResourceDescription.Buffer(Utilities.SizeOf <PerPass>()), ResourceStates.GenericRead); //// Describe and create a constant buffer view. ConstantBufferViewDescription cbvDesc = new ConstantBufferViewDescription() { BufferLocation = _perPassBuffer.GPUVirtualAddress, SizeInBytes = (Utilities.SizeOf <PerPass>() + 255) & ~255 }; device.CreateConstantBufferView(cbvDesc, _perPassViewHeap.CPUDescriptorHandleForHeapStart); // Initialize and map the constant buffers. We don't unmap this until the // app closes. Keeping things mapped for the lifetime of the resource is okay. _perPassPointer = _perPassBuffer.Map(0); Utilities.Write(_perPassPointer, ref buffer); _resources = new[] { new GraphicsResource() { Resource = _perPassBuffer, Register = 0, type = ResourceType.ConstantBufferView } }; }
private void CreateRootSignature() { //RootDescriptorTable table = new RootDescriptorTable() //{ //Ranges = new DescriptorRange() // { // } //} //RootParameter rootParameter = new RootParameter(RootDescriptorTable) //{ // DescriptorTable = new RootDescriptorTable //} DescriptorRange Ranges = new DescriptorRange() { BaseShaderRegister = 0, NumDescriptors = 1, OffsetInDescriptorsFromTableStart = 0, RangeType = DescriptorRangeType.ShaderResourceView, RegisterSpace = 0, }; RootParameter[] slotRootParameters = new RootParameter[] { //new RootParameter(new roo //new RootParameter(RootParameterType.ConstantBufferView, new RootDescriptor(0, 0), ShaderVisibility.All), //new RootParameter(RootParameterType.ConstantBufferView, new RootDescriptor(1, 0), ShaderVisibility.All), //new RootParameter(RootParameterType.ShaderResourceView, new RootDescriptor(1, 0), ShaderVisibility.All), //new RootParameter(new RootDescriptorTable(new DescriptorRange[]{ Ranges }), ShaderVisibility.All) }; RootSignatureDescription SignatureDesc = new RootSignatureDescription() { Flags = RootSignatureFlags.AllowInputAssemblerInputLayout, //Parameters = slotRootParameters, //StaticSamplers = new StaticSamplerDescription[] //{ // new StaticSamplerDescription() // { // ShaderRegister = 0, // RegisterSpace = 0, // ShaderVisibility = ShaderVisibility.Pixel, // Filter = Filter.MinMagMipPoint, // AddressU = TextureAddressMode.Border, // AddressV = TextureAddressMode.Border, // AddressW = TextureAddressMode.Border, // MipLODBias = 0, // MaxAnisotropy = 0, // ComparisonFunction = ComparisonFunction.Never, // BorderColor = StaticBorderColor.TransparentBlack, // MinLOD = 0.0f, // MaxLOD = int.MaxValue, // } //}, }; RootSignature = GraphicsDevice.NativeDevice.CreateRootSignature <ID3D12RootSignature>(0, SignatureDesc, RootSignatureVersion.Version10); //RootSignature. }
public WorldPass(GraphicsDevice device, Camera camera) { _device = device; _camera = camera; _rtvs = _device.CreateDescriptorHeap(DescriptorHeapType.RenderTargetView, 1); _dsvs = _device.CreateDescriptorHeap(DescriptorHeapType.RenderTargetView, 1); var @params = new RootParameter[] { RootParameter.CreateDescriptor(RootParameterType.ConstantBufferView, 0, 0), RootParameter.CreateDescriptor(RootParameterType.ConstantBufferView, 1, 0), RootParameter.CreateDescriptor(RootParameterType.ShaderResourceView, 0, 0, ShaderVisibility.Pixel), RootParameter.CreateDescriptorTable(DescriptorRangeType.ShaderResourceView, 1, 2, 0, visibility: ShaderVisibility.Pixel) }; var samplers = new StaticSampler[] { new StaticSampler(TextureAddressMode.Clamp, SamplerFilterType.MagPoint | SamplerFilterType.MinPoint | SamplerFilterType.MipLinear, 0, 0, ShaderVisibility.Pixel) }; RootSignature = _device.CreateRootSignature(@params, samplers); var shaderFlags = new[] { ShaderCompileFlag.PackMatricesInRowMajorOrder, ShaderCompileFlag.DisableOptimizations, ShaderCompileFlag.EnableDebugInformation, ShaderCompileFlag.WriteDebugInformationToFile() }; var psoDesc = new GraphicsPipelineDesc { RootSignature = RootSignature, Topology = TopologyClass.Triangle, RenderTargetFormats = BackBufferFormat.R8G8B8A8UnsignedNormalized, DepthStencilFormat = DataFormat.Depth32Single, VertexShader = ShaderManager.CompileShader("Shaders/ChunkShader.hlsl", ShaderType.Vertex, shaderFlags, "VertexMain"), PixelShader = ShaderManager.CompileShader("Shaders/ChunkShader.hlsl", ShaderType.Pixel, shaderFlags, "PixelMain"), Inputs = InputLayout.FromType <BlockVertex>() }; Pso = _device.PipelineManager.CreatePipelineStateObject(psoDesc, "ChunkPso"); psoDesc.Msaa = MsaaDesc.X8; MsaaPso = _device.PipelineManager.CreatePipelineStateObject(psoDesc, "MsaaChunkPso"); UploadTextures(); Chunks = new[] { new RenderChunk() }; Chunks[0].Chunk.Blocks = new Block?[Width * Height * Depth]; Chunks[0].Chunk.NeedsRebuild = true; var rng = new Random(); foreach (ref readonly var block in Chunks[0].Chunk.Blocks.Span) { Unsafe.AsRef(in block) = new Block { TextureId = (uint)rng.Next(0, _textures.Length) }; } SetConstants(); }