private void PlatformCreateBuffers() { // Create a upload resource, we are going to update the resource every // frame so we just upload it every time, instead of doing extra copies. vertexBuffer = graphicsHost.Device.CreateCommittedResource(new HeapProperties(HeapType.Upload), HeapFlags.None, ResourceDescription.Buffer(initialVertexCapacity * Vertex2D.SizeInBytes), ResourceStates.GenericRead); vertexBuffer.Name = "[SpriteRenderer] Vertex Buffer"; // Create the view. vertexBufferView = new VertexBufferView(); vertexBufferView.BufferLocation = vertexBuffer.GPUVirtualAddress; vertexBufferView.StrideInBytes = Vertex2D.SizeInBytes; vertexBufferView.SizeInBytes = initialVertexCapacity * Vertex2D.SizeInBytes; // Describe and create a SRV for the texture. //var srvDesc = new ShaderResourceViewDescription //{ // Shader4ComponentMapping = DXHelper.DefaultComponentMapping(), // Format = textureDesc.Format, // Dimension = ShaderResourceViewDimension.Texture2D, // Texture2D = { MipLevels = 1 }, //}; //graphicsHost.Device.CreateShaderResourceView(this.texture, srvDesc, graphicsHost.SRVHeap.CPUDescriptorHandleForHeapStart); }
public override void InitBuffer(MpGe.Data.Vertex[] verts, short[] indices, int size, int stride) { int vertexBufferSize = Utilities.SizeOf(verts); vertexBuffer = DXGlobal.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, verts, 0, verts.Length); vertexBuffer.Unmap(0); // Initialize the vertex buffer view. vertexBufferView = new VertexBufferView(); vertexBufferView.BufferLocation = vertexBuffer.GPUVirtualAddress; vertexBufferView.StrideInBytes = Utilities.SizeOf <MpGe.Data.Vertex>(); vertexBufferView.SizeInBytes = vertexBufferSize; int indexBufferSize = Utilities.SizeOf(indices); indexBuffer = DXGlobal.device.CreateCommittedResource(new HeapProperties(HeapType.Upload), HeapFlags.None, ResourceDescription.Buffer(indexBufferSize), ResourceStates.GenericRead); IntPtr pIndexDataBegin = indexBuffer.Map(0); Utilities.Write(pIndexDataBegin, indices, 0, indices.Length); indexBuffer.Unmap(0); indexBufferView = new IndexBufferView(); indexBufferView.BufferLocation = indexBuffer.GPUVirtualAddress; indexBufferView.Format = Format.R16_Typeless; indexBufferView.SizeInBytes = indexBufferSize; IndexCount = indices.Length; }
private bool Add(string name, VertexBufferView vertex, Resource data) { bool result = Resources.TryAdd(name, data); result = (result == true) ? Vertices.TryAdd(name, vertex) : false; return(result); }
public override void Render(ID3D11Device device, ID3D11DeviceContext deviceContext, Camera camera) { if (!DoRender) { return; } //if (!camera.CheckBBoxFrustum(Transform.TranslationVector, BoundingBox)) // return; VertexBufferView VertexBufferView = new VertexBufferView(vertexBuffer, Unsafe.SizeOf <VertexLayouts.NormalLayout.Vertex>(), 0); deviceContext.IASetVertexBuffers(0, VertexBufferView); deviceContext.IASetIndexBuffer(indexBuffer, Vortice.DXGI.Format.R32_UInt, 0); deviceContext.IASetPrimitiveTopology(PrimitiveTopology.TriangleList); deviceContext.PSSetShaderResource(2, AOTexture); for (int i = 0; i != LODs[0].ModelParts.Length; i++) { ModelPart Segment = LODs[0].ModelParts[i]; Segment.Shader.SetShaderParameters(device, deviceContext, new MaterialParameters(Segment.Material, SelectionColour.Normalize())); Segment.Shader.SetSceneVariables(deviceContext, Transform, camera); Segment.Shader.Render(deviceContext, PrimitiveTopology.TriangleList, (int)(Segment.NumFaces * 3), Segment.StartIndex); } }
void ConstructPlatformDependentMembers(Int64 bufferLocation, Int32 sizeInBytes, Int32 strideInBytes) { m_VBVDesc = new VertexBufferView() { BufferLocation = bufferLocation, SizeInBytes = sizeInBytes, StrideInBytes = strideInBytes, }; }
public void SetVertexBuffer(Buffer buffer) { VertexBufferView vertexBufferView = new VertexBufferView() { BufferLocation = (ulong)buffer.GPUVirtualAddress, SizeInBytes = buffer.SizeInBytes, StrideInBytes = buffer.StructureByteStride }; nativeCommandList.IASetVertexBuffers(0, vertexBufferView); }
private void RenderLines(ID3D11DeviceContext InDeviceContext, Camera InCamera) { VertexBufferView BufferView = new VertexBufferView(VertexBuffer, Unsafe.SizeOf <VertexLayouts.BasicLayout.Vertex>(), 0); InDeviceContext.IASetVertexBuffers(0, BufferView); InDeviceContext.IASetIndexBuffer(IndexBuffer, Vortice.DXGI.Format.R16_UInt, 0); InDeviceContext.IASetPrimitiveTopology(PrimitiveTopology.LineStrip); BaseShader Shader = RenderStorageSingleton.Instance.ShaderManager.shaders[1]; Shader.SetSceneVariables(InDeviceContext, Matrix4x4.Identity, InCamera); Shader.Render(InDeviceContext, PrimitiveTopology.LineList, SizeToRender, 0); }
public override void Render(ID3D11Device device, ID3D11DeviceContext deviceContext, Camera camera) { if (!DoRender) { return; } VertexBufferView VertexBufferView = new VertexBufferView(vertexBuffer, Unsafe.SizeOf <VertexLayouts.BasicLayout.Vertex>(), 0); deviceContext.IASetVertexBuffers(0, VertexBufferView); deviceContext.IASetPrimitiveTopology(PrimitiveTopology.LineStrip); shader.SetSceneVariables(deviceContext, Transform, camera); shader.Render(deviceContext, PrimitiveTopology.LineStrip, vertices.Length, 0); }
public override void Render(ID3D11Device device, ID3D11DeviceContext deviceContext, Camera camera) { if (!DoRender) { return; } VertexBufferView VertexBufferView = new VertexBufferView(vertexBuffer, Unsafe.SizeOf <VertexLayouts.BasicLayout.Vertex>(), 0); deviceContext.IASetVertexBuffers(0, VertexBufferView); deviceContext.IASetIndexBuffer(indexBuffer, Vortice.DXGI.Format.R32_UInt, 0); deviceContext.IASetPrimitiveTopology(PrimitiveTopology.LineList); shader.SetSceneVariables(deviceContext, Transform, camera); shader.Render(deviceContext, PrimitiveTopology.LineList, ReadOnlyIndices.Length, 0); }
public override void Render(ID3D11Device device, ID3D11DeviceContext deviceContext, Camera camera) { if (!DoRender) { return; } VertexBufferView VertexBufferView = new VertexBufferView(vertexBuffer, Unsafe.SizeOf <VertexLayouts.CollisionLayout.Vertex>(), 0); deviceContext.IASetVertexBuffers(0, VertexBufferView); deviceContext.IASetIndexBuffer(indexBuffer, Vortice.DXGI.Format.R32_UInt, 0); deviceContext.IASetPrimitiveTopology(PrimitiveTopology.TriangleList); Shader.SetSceneVariables(deviceContext, Transform, camera); Shader.SetShaderParameters(device, deviceContext, new BaseShader.MaterialParameters(null, SelectionColour.Normalize())); Shader.Render(deviceContext, PrimitiveTopology.TriangleList, Indices.Length, 0); }
private VertexBufferView[] GetVertexBufferViews(GltfLoader.Schema.Mesh mesh, Span <byte> indexBuffer = default, bool is32BitIndex = false) { VertexBufferView[] vertexBufferViews = new VertexBufferView[4]; Dictionary <string, int> attributes = mesh.Primitives[0].Attributes; bool hasPosition = attributes.TryGetValue("POSITION", out int positionIndex); bool hasNormal = attributes.TryGetValue("NORMAL", out int normalIndex); bool hasTangent = attributes.TryGetValue("TANGENT", out int tangentIndex); bool hasTexCoord0 = attributes.TryGetValue("TEXCOORD_0", out int texCoord0Index); if (hasPosition) { Span <byte> positionBuffer = GetVertexBuffer(positionIndex, out int positionStride); vertexBufferViews[0] = new VertexBufferView(GraphicsResource.CreateBuffer(GraphicsDevice, positionBuffer, ResourceFlags.None), positionStride); if (hasNormal) { Span <byte> normalBuffer = GetVertexBuffer(normalIndex, out int normalStride); vertexBufferViews[1] = new VertexBufferView(GraphicsResource.CreateBuffer(GraphicsDevice, normalBuffer, ResourceFlags.None), normalStride); } if (hasTangent) { Span <byte> tangentBuffer = GetVertexBuffer(tangentIndex, out int tangentStride); vertexBufferViews[2] = new VertexBufferView(GraphicsResource.CreateBuffer(GraphicsDevice, tangentBuffer, ResourceFlags.None), tangentStride); } if (hasTexCoord0) { Span <byte> texCoord0Buffer = GetVertexBuffer(texCoord0Index, out int texCoord0Stride); vertexBufferViews[3] = new VertexBufferView(GraphicsResource.CreateBuffer(GraphicsDevice, texCoord0Buffer, ResourceFlags.None), texCoord0Stride); if (!hasTangent) { Span <Vector4> tangentBuffer = VertexHelper.GenerateTangents(positionBuffer, texCoord0Buffer, indexBuffer, is32BitIndex); vertexBufferViews[2] = new VertexBufferView(GraphicsResource.CreateBuffer(GraphicsDevice, tangentBuffer, ResourceFlags.None), Unsafe.SizeOf <Vector4>()); } } } return(vertexBufferViews); }
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 BuildTerrainResouces() { float[] HeightMapData = new float[100 * 100]; for (int i = 0; i < 100; i++) for (int j = 0; j < 100; j++) HeightMapData[i * 100 + j] = Convert.ToSingle(Math.Cos(Math.PI * 2 * i) * Math.Sin(Math.PI * 2 * j)); var Tex = Texture.LoadFromFile("../../", "Terrain.jpg"); ResourceDescription HeighMapDesc = ResourceDescription.Texture2D(Format.R32_Float, 100, 100, 1); ResourceDescription TerrainTextureDesc = ResourceDescription.Texture2D(Tex[0].ColorFormat, Tex[0].Width, Tex[0].Height, 1); HeightMap = device.CreateCommittedResource( new HeapProperties(HeapType.Upload), HeapFlags.None, HeighMapDesc, ResourceStates.GenericRead, null); TerrainTexture = device.CreateCommittedResource( new HeapProperties(HeapType.Upload), HeapFlags.None, HeighMapDesc, ResourceStates.GenericRead, null); TerrainCBF = device.CreateCommittedResource( new HeapProperties(HeapType.Upload), HeapFlags.None, ResourceDescription.Buffer(1024 * 64), ResourceStates.GenericRead); GCHandle handle = GCHandle.Alloc(HeightMapData, GCHandleType.Pinned); IntPtr ptr = Marshal.UnsafeAddrOfPinnedArrayElement(HeightMapData, 0); HeightMap.WriteToSubresource(0, null, ptr, 100 * 4, HeightMapData.Length); handle.Free(); handle = GCHandle.Alloc(Tex[0].Data, GCHandleType.Pinned); ptr = Marshal.UnsafeAddrOfPinnedArrayElement(Tex[0].Data, 0); TerrainTexture.WriteToSubresource(0, null, ptr, Tex[0].Width * Tex[0].PixelWdith, Tex[0].Data.Length); handle.Free(); device.CreateShaderResourceView( HeightMap, new ShaderResourceViewDescription { Shader4ComponentMapping = ((((0) & 0x7) | (((1) & 0x7) << 3) | (((2) & 0x7) << (3 * 2)) | (((3) & 0x7) << (3 * 3)) | (1 << (3 * 4)))), Format = HeighMapDesc.Format, Dimension = ShaderResourceViewDimension.Texture2D, Texture2D = { MipLevels = 1, MostDetailedMip = 0, PlaneSlice = 0, ResourceMinLODClamp = 0.0f } }, terrainHeap.CPUDescriptorHandleForHeapStart); device.CreateShaderResourceView( TerrainTexture, new ShaderResourceViewDescription { Shader4ComponentMapping = ((((0) & 0x7) | (((1) & 0x7) << 3) | (((2) & 0x7) << (3 * 2)) | (((3) & 0x7) << (3 * 3)) | (1 << (3 * 4)))), Format = HeighMapDesc.Format, Dimension = ShaderResourceViewDimension.Texture2D, Texture2D = { MipLevels = 1, MostDetailedMip = 0, PlaneSlice = 0, ResourceMinLODClamp = 0.0f } }, terrainHeap.CPUDescriptorHandleForHeapStart + device.GetDescriptorHandleIncrementSize(DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView)); //========== TerrainCBF = device.CreateCommittedResource(new HeapProperties(HeapType.Upload), HeapFlags.None, ResourceDescription.Buffer(1024 * 64), ResourceStates.GenericRead); device.CreateConstantBufferView( new ConstantBufferViewDescription() { BufferLocation = TerrainCBF.GPUVirtualAddress, SizeInBytes = (Utilities.SizeOf<ConstantBufferData>() + 255) & ~255 }, terrainHeap.CPUDescriptorHandleForHeapStart + device.GetDescriptorHandleIncrementSize(DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView) * 2); TerrainCBFData = new ConstantBufferData { World = Matrix.Identity, View = Matrix.Identity, Project = Matrix.Identity, TexsCount = 1 }; TerrainCBFPointer = TerrainCBF.Map(0); Vertex[] TerrainVertex = new Vertex[100 * 100]; for (int i = 0; i < 100; i++) for (int j = 0; j < 100; j++) { TerrainVertex[i * 100 + j].Position = new Vector3(i, 0, j); TerrainVertex[i * 100 + j].TexCoord = new Vector2(i/2 == 0? 0 : 1, j/2==0? 0 : 1); } TerrainVertexBuffer = device.CreateCommittedResource( new HeapProperties(HeapType.Upload), HeapFlags.None, ResourceDescription.Buffer(Utilities.SizeOf(TerrainVertex)), ResourceStates.GenericRead); Utilities.Write(TerrainVertexBuffer.Map(0), TerrainVertex, 0, TerrainVertex.Length); vertexBuffer.Unmap(0); TerrainVertexBufferView = new VertexBufferView() { BufferLocation = TerrainVertexBuffer.GPUVirtualAddress, StrideInBytes = Utilities.SizeOf<Vertex>(), SizeInBytes = Utilities.SizeOf(TerrainVertex) }; }
public void SetVertexBuffer(int index, Buffer buffer, int offset, int stride) { var newVertexBuffer = new VertexBufferView(buffer, offset, stride); if (vertexBuffers[index] != newVertexBuffer) { vboDirty = true; vertexBuffers[index] = newVertexBuffer; } }
private void LoadMesh(CpuDescriptorHandle heapStart) { SamplerStateDescription samplerDesc = new SamplerStateDescription() { Filter = Filter.ComparisonMinMagMipLinear, AddressU = TextureAddressMode.Wrap, AddressV = TextureAddressMode.Wrap, AddressW = TextureAddressMode.Wrap, MinimumLod = float.MinValue, MaximumLod = float.MaxValue, MipLodBias = 0, MaximumAnisotropy = 0, ComparisonFunction = Comparison.Never }; var heapPosition = heapStart; // Load model from obj. var importer = new Assimp.AssimpContext(); var scene = importer.ImportFile(@"../../../Models/lara/lara.obj", PostProcessSteps.GenerateSmoothNormals | PostProcessSteps.FlipUVs | PostProcessSteps.PreTransformVertices); Vertex[] vertices = new Vertex[scene.Meshes.Sum(m => m.VertexCount)]; int[] indices = new int[scene.Meshes.Sum(m => m.FaceCount * 3)]; faceCounts = new List<int>(); int vertexOffSet = 0; int indexOffSet = 0; foreach (var mesh in scene.Meshes) { var positions = mesh.Vertices; var normals = mesh.Normals; var texs = mesh.TextureCoordinateChannels[0]; for (int i = 0; i < mesh.VertexCount; i++) { vertices[vertexOffSet + i] = new Vertex() { position = new Vector3(positions[i].X, positions[i].Y, positions[i].Z), normal = new Vector3(normals[i].X, normals[i].Y, normals[i].Z), textureCoordinate = new Vector3(texs[i].X, texs[i].Y, texs[i].Z) }; } var faces = mesh.Faces; for (int i = 0; i < mesh.FaceCount; i++) { indices[i * 3 + indexOffSet] = (int)faces[i].Indices[0] + vertexOffSet; indices[i * 3 + 1 + indexOffSet] = (int)faces[i].Indices[1] + vertexOffSet; indices[i * 3 + 2 + indexOffSet] = (int)faces[i].Indices[2] + vertexOffSet; } faceCounts.Add(mesh.FaceCount * 3); vertexOffSet += mesh.VertexCount; indexOffSet += mesh.FaceCount * 3; string textureName = System.IO.Path.GetFileName(scene.Materials[mesh.MaterialIndex].TextureDiffuse.FilePath); var texResource = TextureUtilities.CreateTextureFromDDS(device, @"../../../Models/lara/" + textureName); textures.Add(texResource); int D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING = 5768; ShaderResourceViewDescription desc = new ShaderResourceViewDescription { Dimension = ShaderResourceViewDimension.Texture2D, Format = texResource.Description.Format, Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, }; desc.Texture2D.MipLevels = 1; desc.Texture2D.MostDetailedMip = 0; desc.Texture2D.ResourceMinLODClamp = 0; device.CreateShaderResourceView(texResource, desc, heapStart); heapStart += constantBufferDescriptorSize; } 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 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; }
void Initialize() { // 1) We create vertex shader first. { vertexShader = new ShaderCode(BindingStage.VertexShader); vertexShader.InputOperation.AddInput(PinComponent.Position, PinFormat.Floatx2); // We now extend position ExpandOperation expandPositionOp = new ExpandOperation(PinFormat.Floatx4, ExpandType.AddOnesAtW); expandPositionOp.BindInputs(vertexShader.InputOperation.PinAsOutput(PinComponent.Position)); Pin position = expandPositionOp.Outputs[0]; // We now output position. vertexShader.OutputOperation.AddComponentAndLink(PinComponent.Position, position); } vertexShader.Immutable = true; // 2) We create pixel shader. { pixelShader = new ShaderCode(BindingStage.PixelShader); pixelShader.InputOperation.AddInput(PinComponent.Position, PinFormat.Floatx4); // We first use only XY. SwizzleOperation swizzleOp = new SwizzleOperation(SwizzleMask.XY); swizzleOp.BindInputs(pixelShader.InputOperation.PinAsOutput(PinComponent.Position)); ConstantOperation constant = vertexShader.CreateConstant("Offset", PinFormat.Floatx2); // We first offset. SubstractOperation subOp = new SubstractOperation(); subOp.BindInputs(swizzleOp.Outputs[0], constant.Outputs[0]); ConstantOperation interfaceOp = pixelShader.CreateConstant("Composite", PinFormat.Interface, Pin.DynamicArray); // We use the compositing operation. CompositingOperation op = new CompositingOperation(); op.BindInputs(subOp.Outputs[0], interfaceOp.Outputs[0]); // Compositing is bound to output. pixelShader.OutputOperation.AddComponentAndLink(PinComponent.RenderTarget0, op.Outputs[0]); } pixelShader.Immutable = true; // 3) Initialize states. // Depth-stencil state. depthStencilState = new DepthStencilState(); depthStencilState.DepthTestEnabled = false; depthStencilState.DepthWriteEnabled = false; // Blend state (no blending default). blendState = new BlendState(); // Rasterization state. rasterizationState = new RasterizationState(); rasterizationState.FrontFacing = Facing.CCW; rasterizationState.CullMode = CullMode.None; rasterizationState.FillMode = FillMode.Solid; rasterizationState.MultiSamplingEnabled = true; // We intern all states. depthStencilState = StateManager.Intern(depthStencilState); blendState = StateManager.Intern(blendState); rasterizationState = StateManager.Intern(rasterizationState); // 4) We create geometry. alignedQuad = new Geometry(device); alignedQuad.AssociateBuffers = true; { // We create vertex buffer VertexBufferView vertexBuffer = VertexBufferView.Create(device, vertexFormat, Usage.Default, CPUAccess.None, GraphicsLocality.DeviceOrSystemMemory, new Vector2f(-1.0f, -1.0f), new Vector2f(1.0f, -1.0f), new Vector2f(1.0f, 1.0f), new Vector2f(-1.0f, -1.0f), new Vector2f(1.0f, 1.0f), new Vector2f(-1.0f, 1.0f)); alignedQuad[0] = vertexBuffer; } // 5) We create pixel typeless buffer for constant buffer. pixelTypelessConstantBuffer = new TypelessBuffer(Usage.Dynamic, BufferUsage.ConstantBuffer, CPUAccess.Write, GraphicsLocality.DeviceOrSystemMemory, ConstantBufferView.MaxSize); }
private bool Add(string name, VertexBufferView vertex, Resource data) { bool result = Resources.TryAdd(name, data); result = (result == true) ? Vertices.TryAdd(name, vertex) : false; return result; }
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 void BuildPSO(Device3 device, GraphicsCommandList commandList) { World = Matrix.Translation(-2.5f, -2.5f, -2.5f); buffer.World = World; light = new Lighting { GlobalAmbientX = 1, GlobalAmbientY = 1, GlobalAmbientZ = 1, KaX = .1f, KaY = .1f, KaZ = .1f, KdX = .5f, KdY = .5f, KdZ = .5f, KeX = .25f, KeY = .25f, KeZ = .25f, KsX = .1f, KsY = .1f, KsZ = .1f, LightColorX = 1, LightColorY = 1, LightColorZ = 1, LightPositionX = 10, LightPositionY = 10, LightPositionZ = 10, shininess = 5 }; DescriptorHeapDescription srvHeapDesc = new DescriptorHeapDescription() { DescriptorCount = 1, Flags = DescriptorHeapFlags.ShaderVisible, Type = DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView }; _srvDescriptorHeap = device.CreateDescriptorHeap(srvHeapDesc); //setup descriptor ranges DescriptorRange[] ranges = new DescriptorRange[] { new DescriptorRange() { RangeType = DescriptorRangeType.ShaderResourceView, DescriptorCount = 1, OffsetInDescriptorsFromTableStart = int.MinValue, BaseShaderRegister = 0 } }; //Get sampler state setup StaticSamplerDescription sampler = new StaticSamplerDescription() { Filter = Filter.MinimumMinMagMipPoint, AddressU = TextureAddressMode.Border, AddressV = TextureAddressMode.Border, AddressW = TextureAddressMode.Border, MipLODBias = 0, MaxAnisotropy = 0, ComparisonFunc = Comparison.Never, BorderColor = StaticBorderColor.TransparentBlack, MinLOD = 0.0f, MaxLOD = float.MaxValue, ShaderRegister = 0, RegisterSpace = 0, ShaderVisibility = ShaderVisibility.Pixel, }; Projection = Matrix.PerspectiveFovLH((float)Math.PI / 3f, 4f / 3f, 1, 1000); View = Matrix.LookAtLH(new Vector3(10 * (float)Math.Sin(rotation), 5, 10 * (float)Math.Cos(rotation)), Vector3.Zero, Vector3.UnitY); World = Matrix.Translation(-2.5f, -2.5f, -2.5f); DescriptorHeapDescription cbvHeapDesc = new DescriptorHeapDescription() { DescriptorCount = 1, Flags = DescriptorHeapFlags.ShaderVisible, Type = DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView }; _objectViewHeap = device.CreateDescriptorHeap(cbvHeapDesc); _lightingViewHeap = device.CreateDescriptorHeap(cbvHeapDesc); RootParameter[] rootParameters = new RootParameter[] { new RootParameter(ShaderVisibility.Pixel, ranges), new RootParameter(ShaderVisibility.All, new RootDescriptor(1, 0), RootParameterType.ConstantBufferView), new RootParameter(ShaderVisibility.All, new RootDescriptor(2, 0), RootParameterType.ConstantBufferView) }; // Create an empty root signature. RootSignatureDescription rootSignatureDesc = new RootSignatureDescription(RootSignatureFlags.AllowInputAssemblerInputLayout, rootParameters, new StaticSamplerDescription[] { sampler }); _rootSignature = device.CreateRootSignature(rootSignatureDesc.Serialize()); // Create the pipeline state, which includes compiling and loading shaders. #if DEBUG var vertexShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("Shaders/LitVertex.hlsl", "VSMain", "vs_5_0", SharpDX.D3DCompiler.ShaderFlags.Debug)); #else var vertexShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("Shaders/LitVertex.hlsl", "VSMain", "vs_5_0")); #endif #if DEBUG var pixelShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("Shaders/LitVertex.hlsl", "PSMain", "ps_5_0", SharpDX.D3DCompiler.ShaderFlags.Debug)); #else var pixelShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("Shaders/LitVertex.hlsl", "PSMain", "ps_5_0")); #endif // Define the vertex input layout. InputElement[] inputElementDescs = new InputElement[] { new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0), new InputElement("NORMAL", 0, Format.R32G32B32_Float, 12, 0), new InputElement("TEXCOORD", 0, Format.R32G32_Float, 24, 0) }; // Describe and create the graphics pipeline state object (PSO). GraphicsPipelineStateDescription psoDesc = new GraphicsPipelineStateDescription() { InputLayout = new InputLayoutDescription(inputElementDescs), RootSignature = _rootSignature, VertexShader = vertexShader, PixelShader = pixelShader, RasterizerState = RasterizerStateDescription.Default(), BlendState = BlendStateDescription.Default(), DepthStencilFormat = SharpDX.DXGI.Format.D24_UNorm_S8_UInt, DepthStencilState = DepthStencilStateDescription.Default(), SampleMask = int.MaxValue, PrimitiveTopologyType = PrimitiveTopologyType.Triangle, RenderTargetCount = 1, Flags = PipelineStateFlags.None, SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0), StreamOutput = new StreamOutputDescription() }; psoDesc.RenderTargetFormats[0] = SharpDX.DXGI.Format.R8G8B8A8_UNorm; _pipelineState = device.CreateGraphicsPipelineState(psoDesc); // Define the geometry for a triangle. Vertex[] triangleVertices = new Vertex[] { //Front new Vertex() { Position = new Vector3(0, 0, 0), TexCoord = new Vector2(1, 1), Normal = -Vector3.UnitZ }, new Vertex() { Position = new Vector3(0, 5, 0), TexCoord = new Vector2(1, 0), Normal = -Vector3.UnitZ }, new Vertex() { Position = new Vector3(5, 0, 0), TexCoord = new Vector2(0, 1), Normal = -Vector3.UnitZ }, new Vertex() { Position = new Vector3(5, 5, 0), TexCoord = new Vector2(0, 0), Normal = -Vector3.UnitZ }, //Back new Vertex() { Position = new Vector3(0, 0, 5), TexCoord = new Vector2(1, 1), Normal = Vector3.UnitZ }, new Vertex() { Position = new Vector3(0, 5, 5), TexCoord = new Vector2(1, 0), Normal = Vector3.UnitZ }, new Vertex() { Position = new Vector3(5, 0, 5), TexCoord = new Vector2(0, 1), Normal = Vector3.UnitZ }, new Vertex() { Position = new Vector3(5, 5, 5), TexCoord = new Vector2(0, 0), Normal = Vector3.UnitZ }, //Left new Vertex() { Position = new Vector3(0, 0, 0), TexCoord = new Vector2(1, 1), Normal = -Vector3.UnitX }, new Vertex() { Position = new Vector3(0, 5, 0), TexCoord = new Vector2(1, 0), Normal = -Vector3.UnitX }, new Vertex() { Position = new Vector3(0, 0, 5), TexCoord = new Vector2(0, 1), Normal = -Vector3.UnitX }, new Vertex() { Position = new Vector3(0, 5, 5), TexCoord = new Vector2(0, 0), Normal = -Vector3.UnitX }, //Right new Vertex() { Position = new Vector3(5, 0, 0), TexCoord = new Vector2(1, 1), Normal = Vector3.UnitX }, new Vertex() { Position = new Vector3(5, 5, 0), TexCoord = new Vector2(1, 0), Normal = Vector3.UnitX }, new Vertex() { Position = new Vector3(5, 0, 5), TexCoord = new Vector2(0, 1), Normal = Vector3.UnitX }, new Vertex() { Position = new Vector3(5, 5, 5), TexCoord = new Vector2(0, 0), Normal = Vector3.UnitX }, //Top new Vertex() { Position = new Vector3(0, 0, 0), TexCoord = new Vector2(1, 1), Normal = -Vector3.UnitY }, new Vertex() { Position = new Vector3(0, 0, 5), TexCoord = new Vector2(1, 0), Normal = -Vector3.UnitY }, new Vertex() { Position = new Vector3(5, 0, 0), TexCoord = new Vector2(0, 1), Normal = -Vector3.UnitY }, new Vertex() { Position = new Vector3(5, 0, 5), TexCoord = new Vector2(0, 0), Normal = -Vector3.UnitY }, //Bottom new Vertex() { Position = new Vector3(0, 5, 0), TexCoord = new Vector2(1, 1), Normal = Vector3.UnitY }, new Vertex() { Position = new Vector3(0, 5, 5), TexCoord = new Vector2(1, 0), Normal = Vector3.UnitY }, new Vertex() { Position = new Vector3(5, 5, 0), TexCoord = new Vector2(0, 1), Normal = Vector3.UnitY }, new Vertex() { Position = new Vector3(5, 5, 5), TexCoord = new Vector2(0, 0), Normal = Vector3.UnitY } }; int vertexBufferSize = Utilities.SizeOf(triangleVertices); // Note: using upload heaps to transfer static data like vert buffers is not // recommended. Every time the GPU needs it, the upload heap will be marshalled // over. Please read up on Default Heap usage. An upload heap is used here for // code simplicity and because there are very few verts to actually transfer. _vertexBuffer = device.CreateCommittedResource(new HeapProperties(HeapType.Upload), HeapFlags.None, ResourceDescription.Buffer(vertexBufferSize), ResourceStates.GenericRead); // Copy the triangle data to the vertex buffer. IntPtr pVertexDataBegin = _vertexBuffer.Map(0); Utilities.Write(pVertexDataBegin, triangleVertices, 0, triangleVertices.Length); _vertexBuffer.Unmap(0); _indicies = new int[] { 0, 1, 2, 3, 2, 1, 6, 5, 4, 5, 6, 7, 10, 9, 8, 9, 10, 11, 12, 13, 14, 15, 14, 13, 18, 17, 16, 17, 18, 19, 20, 21, 22, 23, 22, 21 }; int indBufferSize = Utilities.SizeOf(_indicies); _indexBuffer = device.CreateCommittedResource(new HeapProperties(HeapType.Upload), HeapFlags.None, ResourceDescription.Buffer(indBufferSize), ResourceStates.GenericRead); IntPtr pIndBegin = _indexBuffer.Map(0); Utilities.Write(pIndBegin, _indicies, 0, _indicies.Length); _indexBuffer.Unmap(0); _indexBufferView = new IndexBufferView() { BufferLocation = _indexBuffer.GPUVirtualAddress, Format = Format.R32_UInt, SizeInBytes = indBufferSize }; // Initialize the vertex buffer view. _vertexBufferView = new VertexBufferView { BufferLocation = _vertexBuffer.GPUVirtualAddress, StrideInBytes = Utilities.SizeOf <Vertex>(), SizeInBytes = vertexBufferSize }; _objectBuffer = device.CreateCommittedResource(new HeapProperties(HeapType.Upload), HeapFlags.None, ResourceDescription.Buffer(Utilities.SizeOf <ObjectData>()), ResourceStates.GenericRead); //// Describe and create a constant buffer view. ConstantBufferViewDescription cbvDesc = new ConstantBufferViewDescription() { BufferLocation = _objectBuffer.GPUVirtualAddress, SizeInBytes = (Utilities.SizeOf <ObjectData>() + 255) & ~255 }; device.CreateConstantBufferView(cbvDesc, _objectViewHeap.CPUDescriptorHandleForHeapStart); // Initialize and map the constant buffers. We don't unmap this until the // app closes. Keeping things mapped for the lifetime of the resource is okay. _objectPointer = _objectBuffer.Map(0); Utilities.Write(_objectPointer, ref buffer); _lightingBuffer = device.CreateCommittedResource(new HeapProperties(HeapType.Upload), HeapFlags.None, ResourceDescription.Buffer(Utilities.SizeOf <Lighting>()), ResourceStates.GenericRead); //// Describe and create a constant buffer view. ConstantBufferViewDescription cbvDesc2 = new ConstantBufferViewDescription() { BufferLocation = _objectBuffer.GPUVirtualAddress, SizeInBytes = (Utilities.SizeOf <Lighting>() + 255) & ~255 }; device.CreateConstantBufferView(cbvDesc2, _lightingViewHeap.CPUDescriptorHandleForHeapStart); // Initialize and map the constant buffers. We don't unmap this until the // app closes. Keeping things mapped for the lifetime of the resource is okay. _lightingPointer = _lightingBuffer.Map(0); Utilities.Write(_lightingPointer, ref light); Resource textureUploadHeap; // Create the texture. // Describe and create a Texture2D. ResourceDescription textureDesc = ResourceDescription.Texture2D(Format.R8G8B8A8_UNorm, textureWidth, textureHeight); _texture = device.CreateCommittedResource(new HeapProperties(HeapType.Default), HeapFlags.None, textureDesc, ResourceStates.CopyDestination); long uploadBufferSize = GetRequiredIntermediateSize(device, _texture, 0, 1); // Create the GPU upload buffer. textureUploadHeap = device.CreateCommittedResource(new HeapProperties(CpuPageProperty.WriteBack, MemoryPool.L0), HeapFlags.None, ResourceDescription.Texture2D(Format.R8G8B8A8_UNorm, textureWidth, textureHeight), ResourceStates.GenericRead); // Copy data to the intermediate upload heap and then schedule a copy // from the upload heap to the Texture2D. byte[] textureData = GenerateTextureData(); GCHandle handle = GCHandle.Alloc(textureData, GCHandleType.Pinned); IntPtr ptr = Marshal.UnsafeAddrOfPinnedArrayElement(textureData, 0); textureUploadHeap.WriteToSubresource(0, null, ptr, 4 * textureWidth, textureData.Length); handle.Free(); commandList.CopyTextureRegion(new TextureCopyLocation(_texture, 0), 0, 0, 0, new TextureCopyLocation(textureUploadHeap, 0), null); commandList.ResourceBarrierTransition(_texture, ResourceStates.CopyDestination, ResourceStates.PixelShaderResource); // Describe and create a SRV for the texture. ShaderResourceViewDescription srvDesc = new ShaderResourceViewDescription() { Shader4ComponentMapping = ComponentMapping(0, 1, 2, 3), Format = textureDesc.Format, Dimension = ShaderResourceViewDimension.Texture2D, }; srvDesc.Texture2D.MipLevels = 1; device.CreateShaderResourceView(_texture, srvDesc, _srvDescriptorHeap.CPUDescriptorHandleForHeapStart); _resources = new[] { new GraphicsResource() { Heap = _srvDescriptorHeap, Register = 0, type = ResourceType.DescriptorTable }, new GraphicsResource() { Resource = _objectBuffer, Register = 2, type = ResourceType.ConstantBufferView }, new GraphicsResource() { Resource = _lightingBuffer, Register = 1, type = ResourceType.ConstantBufferView } }; }
private void LoadAssets() { // Create an empty root signature. var rootSignatureDesc = new RootSignatureDescription(RootSignatureFlags.AllowInputAssemblerInputLayout); 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. var inputElementDescs = new [] { 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). var 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. var triangleVertices = new [] { 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(); // Create synchronization objects. fence = device.CreateFence(0, FenceFlags.None); fenceValue = 1; // Create an event handle to use for frame synchronization. fenceEvent = new AutoResetEvent(false); }
private void BuildTerrainResouces() { float[] HeightMapData = new float[100 * 100]; for (int i = 0; i < 100; i++) { for (int j = 0; j < 100; j++) { HeightMapData[i * 100 + j] = Convert.ToSingle(Math.Cos(Math.PI * 2 * i) * Math.Sin(Math.PI * 2 * j)); } } var Tex = Texture.LoadFromFile("../../", "Terrain.jpg"); ResourceDescription HeighMapDesc = ResourceDescription.Texture2D(Format.R32_Float, 100, 100, 1); ResourceDescription TerrainTextureDesc = ResourceDescription.Texture2D(Tex[0].ColorFormat, Tex[0].Width, Tex[0].Height, 1); HeightMap = device.CreateCommittedResource( new HeapProperties(HeapType.Upload), HeapFlags.None, HeighMapDesc, ResourceStates.GenericRead, null); TerrainTexture = device.CreateCommittedResource( new HeapProperties(HeapType.Upload), HeapFlags.None, HeighMapDesc, ResourceStates.GenericRead, null); TerrainCBF = device.CreateCommittedResource( new HeapProperties(HeapType.Upload), HeapFlags.None, ResourceDescription.Buffer(1024 * 64), ResourceStates.GenericRead); GCHandle handle = GCHandle.Alloc(HeightMapData, GCHandleType.Pinned); IntPtr ptr = Marshal.UnsafeAddrOfPinnedArrayElement(HeightMapData, 0); HeightMap.WriteToSubresource(0, null, ptr, 100 * 4, HeightMapData.Length); handle.Free(); handle = GCHandle.Alloc(Tex[0].Data, GCHandleType.Pinned); ptr = Marshal.UnsafeAddrOfPinnedArrayElement(Tex[0].Data, 0); TerrainTexture.WriteToSubresource(0, null, ptr, Tex[0].Width * Tex[0].PixelWdith, Tex[0].Data.Length); handle.Free(); device.CreateShaderResourceView( HeightMap, new ShaderResourceViewDescription { Shader4ComponentMapping = ((((0) & 0x7) | (((1) & 0x7) << 3) | (((2) & 0x7) << (3 * 2)) | (((3) & 0x7) << (3 * 3)) | (1 << (3 * 4)))), Format = HeighMapDesc.Format, Dimension = ShaderResourceViewDimension.Texture2D, Texture2D = { MipLevels = 1, MostDetailedMip = 0, PlaneSlice = 0, ResourceMinLODClamp = 0.0f } }, terrainHeap.CPUDescriptorHandleForHeapStart); device.CreateShaderResourceView( TerrainTexture, new ShaderResourceViewDescription { Shader4ComponentMapping = ((((0) & 0x7) | (((1) & 0x7) << 3) | (((2) & 0x7) << (3 * 2)) | (((3) & 0x7) << (3 * 3)) | (1 << (3 * 4)))), Format = HeighMapDesc.Format, Dimension = ShaderResourceViewDimension.Texture2D, Texture2D = { MipLevels = 1, MostDetailedMip = 0, PlaneSlice = 0, ResourceMinLODClamp = 0.0f } }, terrainHeap.CPUDescriptorHandleForHeapStart + device.GetDescriptorHandleIncrementSize(DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView)); //========== TerrainCBF = device.CreateCommittedResource(new HeapProperties(HeapType.Upload), HeapFlags.None, ResourceDescription.Buffer(1024 * 64), ResourceStates.GenericRead); device.CreateConstantBufferView( new ConstantBufferViewDescription() { BufferLocation = TerrainCBF.GPUVirtualAddress, SizeInBytes = (Utilities.SizeOf <ConstantBufferData>() + 255) & ~255 }, terrainHeap.CPUDescriptorHandleForHeapStart + device.GetDescriptorHandleIncrementSize(DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView) * 2); TerrainCBFData = new ConstantBufferData { World = Matrix.Identity, View = Matrix.Identity, Project = Matrix.Identity, TexsCount = 1 }; TerrainCBFPointer = TerrainCBF.Map(0); Vertex[] TerrainVertex = new Vertex[100 * 100]; for (int i = 0; i < 100; i++) { for (int j = 0; j < 100; j++) { TerrainVertex[i * 100 + j].Position = new Vector3(i, 0, j); TerrainVertex[i * 100 + j].TexCoord = new Vector2(i / 2 == 0? 0 : 1, j / 2 == 0? 0 : 1); } } TerrainVertexBuffer = device.CreateCommittedResource( new HeapProperties(HeapType.Upload), HeapFlags.None, ResourceDescription.Buffer(Utilities.SizeOf(TerrainVertex)), ResourceStates.GenericRead); Utilities.Write(TerrainVertexBuffer.Map(0), TerrainVertex, 0, TerrainVertex.Length); vertexBuffer.Unmap(0); TerrainVertexBufferView = new VertexBufferView() { BufferLocation = TerrainVertexBuffer.GPUVirtualAddress, StrideInBytes = Utilities.SizeOf <Vertex>(), SizeInBytes = Utilities.SizeOf(TerrainVertex) }; }
private void LoadRenderTargetData() { // Define the geometry for a quad. Vertex[] quadBuffer = new Vertex[] { new Vertex() { position = new Vector3(-1, -1, 0), textureCoordinate = new Vector3(0, 1, 0) }, new Vertex() { position = new Vector3(-1, 1, 0), textureCoordinate = new Vector3(0, 0, 0) }, new Vertex() { position = new Vector3(1, -1, 0), textureCoordinate = new Vector3(1, 1, 0) }, new Vertex() { position = new Vector3(-1, 1, 0), textureCoordinate = new Vector3(0, 0, 0) }, new Vertex() { position = new Vector3(1, 1, 0), textureCoordinate = new Vector3(1, 0, 0) }, new Vertex() { position = new Vector3(1, -1, 0), textureCoordinate = new Vector3(1, 1, 0) }, }; int vertexBufferSize = Utilities.SizeOf(quadBuffer); quadVertexBuffer = device.CreateCommittedResource(new HeapProperties(HeapType.Upload), HeapFlags.None, ResourceDescription.Buffer(vertexBufferSize), ResourceStates.GenericRead); IntPtr pointer = quadVertexBuffer.Map(0); Utilities.Write(pointer, quadBuffer, 0, 6); quadVertexBuffer.Unmap(0); quadVertexBufferView = new VertexBufferView(); quadVertexBufferView.BufferLocation = quadVertexBuffer.GPUVirtualAddress; quadVertexBufferView.StrideInBytes = Utilities.SizeOf <Vertex>(); quadVertexBufferView.SizeInBytes = vertexBufferSize; //Render Target ClearValue renderTargetOptimizedClearValue = new ClearValue() { Format = Format.R8G8B8A8_UNorm, Color = new Vector4(0, 0.2F, 0.4f, 1) }; postProcessingRenderTarget = device.CreateCommittedResource(new HeapProperties(HeapType.Default), HeapFlags.None, new ResourceDescription(ResourceDimension.Texture2D, 0, TargetSize, TargetSize, 1, 0, Format.R8G8B8A8_UNorm, 1, 0, TextureLayout.Unknown, ResourceFlags.AllowRenderTarget), ResourceStates.RenderTarget, renderTargetOptimizedClearValue); CpuDescriptorHandle rtvHandle = renderTargetViewHeap.CPUDescriptorHandleForHeapStart + device.GetDescriptorHandleIncrementSize(DescriptorHeapType.RenderTargetView) * 2; device.CreateRenderTargetView(postProcessingRenderTarget, null, rtvHandle); //Shader Resource View int D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING = 5768; ShaderResourceViewDescription desc = new ShaderResourceViewDescription { Dimension = ShaderResourceViewDimension.Texture2D, Format = postProcessingRenderTarget.Description.Format, Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, }; desc.Texture2D.MipLevels = 1; desc.Texture2D.MostDetailedMip = 0; desc.Texture2D.ResourceMinLODClamp = 0; //Create Render Target View //position start after first constant buffer and textures device.CreateShaderResourceView(postProcessingRenderTarget, desc, resourceViewHeap.CPUDescriptorHandleForHeapStart + device.GetDescriptorHandleIncrementSize(DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView) * renderTargetViewPosition); //Depth Target ClearValue depthOptimizedClearValue = new ClearValue() { Format = Format.D32_Float, DepthStencil = new DepthStencilValue() { Depth = 1.0F, Stencil = 0 }, }; postProcessingDepthTarget = device.CreateCommittedResource(new HeapProperties(HeapType.Default), HeapFlags.None, new ResourceDescription(ResourceDimension.Texture2D, 0, TargetSize, TargetSize, 1, 0, Format.D32_Float, 1, 0, TextureLayout.Unknown, ResourceFlags.AllowDepthStencil), ResourceStates.DepthWrite, depthOptimizedClearValue); CpuDescriptorHandle dpsHandle = depthStencilViewHeap.CPUDescriptorHandleForHeapStart + device.GetDescriptorHandleIncrementSize(DescriptorHeapType.DepthStencilView); device.CreateDepthStencilView(postProcessingDepthTarget, null, dpsHandle); //Shader #if DEBUG var vertexShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("postProcessing.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("postProcessing.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; postProcessingPipelineState = device.CreateGraphicsPipelineState(psoDesc); //constant Buffer int constantBufferSize = (Utilities.SizeOf <PostProcessingData>() + 255) & ~255; postProcessingConstantBuffer = device.CreateCommittedResource(new HeapProperties(HeapType.Upload), HeapFlags.None, ResourceDescription.Buffer(constantBufferSize), ResourceStates.GenericRead); //constant buffer ConstantBufferViewDescription cbvDesc = new ConstantBufferViewDescription() { BufferLocation = postProcessingConstantBuffer.GPUVirtualAddress, SizeInBytes = constantBufferSize }; var heapPosition = resourceViewHeap.CPUDescriptorHandleForHeapStart + device.GetDescriptorHandleIncrementSize(DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView) * renderTargetConstantBufferPosition; device.CreateConstantBufferView(cbvDesc, heapPosition); }
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, 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); }
//创建资源 private void LoadAssets() { //创建一个空的根签名 var rootSignatureDesc = new RootSignatureDescription( RootSignatureFlags.AllowInputAssemblerInputLayout, //根常量 new[] { new RootParameter(ShaderVisibility.All, //指定可以访问根签名绑定的内容的着色器,这里设置为顶点着色器 new DescriptorRange() { RangeType = DescriptorRangeType.ConstantBufferView, //指定描述符范围,这里的参数是CBV BaseShaderRegister = 0, //指定描述符范围内的基本着色器 OffsetInDescriptorsFromTableStart = int.MinValue, //描述符从根签名开始的偏移量 DescriptorCount = 1 //描述符范围内的描述符数 }) }); //表示该根签名需要一组顶点缓冲区来绑定 rootSignature = device.CreateRootSignature(rootSignatureDesc.Serialize()); //创建流水线状态,负责编译和加载着色器 #if DEBUG var vertexShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("shaders.hlsl", "VS", "vs_5_0", SharpDX.D3DCompiler.ShaderFlags.Debug)); #else var vertexShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("shaders.hlsl", "VS", "vs_5_0")); #endif //#if DEBUG // var pixelShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("shaders.hlsl", "PS", "ps_5_0", SharpDX.D3DCompiler.ShaderFlags.Debug)); //#else // var pixelShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("shaders.hlsl", "PS", "ps_5_0")); //#endif //描述输入装配器阶段的输入元素,这里定义顶点输入布局 var inputElementDescs = new[] { new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0), new InputElement("TEXCOORD", 0, Format.R32G32_Float, 12, 0) }; //创建流水线状态对象(PSO) var 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, //RTVFormat成员中的渲染目标格式数 Flags = PipelineStateFlags.None, //用于控制管道状态的标志,这里表示没有标志 SampleDescription = new SampleDescription(1, 0), //描述资源的多采样参数 StreamOutput = new StreamOutputDescription() //描述输出缓冲器 }; psoDesc.RenderTargetFormats[0] = Format.R8G8B8A8_UNorm; //描述渲染目标格式的数组 //设置管道 pipelineState = device.CreateGraphicsPipelineState(psoDesc); //创建命令列表 commandList = device.CreateCommandList( CommandListType.Direct, //指定命令列表的创建类型,Direct命令列表不会继承任何GPU状态 commandAllocator, //指向设备创建的命令列表对象的指针 pipelineState); //指向(管道)内存块的指针 commandList.Close(); float aspectRatio = viewPort.Width / viewPort.Height; //定义待绘制图形的几何形状 string bitmapPath = @"C:\Users\yulanli\Desktop\TerrainForm\heightMap.BMP"; Bitmap bitmap = new Bitmap(bitmapPath); xCount = (bitmap.Width - 1) / 2; yCount = (bitmap.Height - 1) / 2; cellWidth = bitmap.Width / xCount; cellHeight = bitmap.Height / yCount; var vertices = new PositionTextured[(xCount + 1) * (yCount + 1)];//定义顶点 for (int i = 0; i < yCount + 1; i++) { for (int j = 0; j < xCount + 1; j++) { System.Drawing.Color color = bitmap.GetPixel((int)(j * cellWidth), (int)(i * cellHeight)); float height = float.Parse(color.R.ToString()) + float.Parse(color.G.ToString()) + float.Parse(color.B.ToString()); height /= 10; vertices[j + i * (xCount + 1)].Position = new Vector3(j * cellWidth, height, i * cellHeight); vertices[j + i * (xCount + 1)].Texcoord = new Vector2((float)j / (xCount + 1), (float)i / (yCount + 1)); } } texture = TextureLoader.TextureLoader.CreateTextureFromDDS(device, @"C:\Users\yulanli\Desktop\TerrainForm\colorMapDDS.DDS"); //创建待绘制图形的顶点索引 indices = new int[6 * xCount * yCount]; for (int i = 0; i < yCount; i++) { for (int j = 0; j < xCount; j++) { indices[6 * (j + i * xCount)] = j + i * (xCount + 1); indices[6 * (j + i * xCount) + 1] = j + (i + 1) * (xCount + 1); indices[6 * (j + i * xCount) + 2] = j + i * (xCount + 1) + 1; indices[6 * (j + i * xCount) + 3] = j + i * (xCount + 1) + 1; indices[6 * (j + i * xCount) + 4] = j + (i + 1) * (xCount + 1); indices[6 * (j + i * xCount) + 5] = j + (i + 1) * (xCount + 1) + 1; } } //创建视锥体 //创建摄像机 CamTarget = new Vector3(bitmap.Width / 2, 0f, bitmap.Height / 2); view = Matrix.LookAtLH( CamPostion, //摄像机原点 CamTarget, //摄像机观察目标点 Vector3.UnitY); //当前世界的向上方向的向量,通常为(0,1,0),即这里的UnitY参数 proj = Matrix.Identity; proj = Matrix.PerspectiveFovLH( (float)Math.PI / 4.0f, //用弧度制表示垂直视场角,这里是45°角 aspectRatio, //纵横比 0.3f, //到近平面的距离 500.0f //到远平面的距离 ); var worldViewProj = Matrix.Multiply(proj, view); //使用上传堆来传递顶点缓冲区的数据 /*--------------------------------------------------* * 不推荐使用上传堆来传递像顶点缓冲区这样的静态数据 * * 这里使用上载堆是为了代码的简洁性,并且还因为需要 * * 传递的资源很少 * *--------------------------------------------------*/ var vertexBufferSize = Utilities.SizeOf(vertices); vertexBuffer = device.CreateCommittedResource( new HeapProperties(HeapType.Upload), HeapFlags.None, ResourceDescription.Buffer(vertexBufferSize), ResourceStates.GenericRead); //将顶点的数据复制到顶点缓冲区 IntPtr pVertexDataBegin = vertexBuffer.Map(0); Utilities.Write( pVertexDataBegin, vertices, 0, vertices.Length); vertexBuffer.Unmap(0); //初始化顶点缓冲区视图 vertexBufferView = new VertexBufferView(); vertexBufferView.BufferLocation = vertexBuffer.GPUVirtualAddress; vertexBufferView.StrideInBytes = Utilities.SizeOf <PositionTextured>(); vertexBufferView.SizeInBytes = vertexBufferSize; //使用上传堆来传递索引缓冲区的数据 int indexBufferSize = Utilities.SizeOf(indices); indexBuffer = device.CreateCommittedResource( new HeapProperties(HeapType.Upload), HeapFlags.None, ResourceDescription.Buffer(indexBufferSize), ResourceStates.GenericRead); //将索引的数据复制到索引缓冲区 IntPtr pIndexDataBegin = indexBuffer.Map(0); Utilities.Write( pIndexDataBegin, indices, 0, indices.Length); indexBuffer.Unmap(0); //初始化索引缓冲区视图 indexBufferView = new IndexBufferView(); indexBufferView.BufferLocation = indexBuffer.GPUVirtualAddress; indexBufferView.SizeInBytes = indexBufferSize; indexBufferView.Format = Format.R32_UInt; //创建bundle bundle = device.CreateCommandList( 0, CommandListType.Bundle, bundleAllocator, pipelineState); bundle.SetGraphicsRootSignature(rootSignature); bundle.PrimitiveTopology = SharpDX.Direct3D.PrimitiveTopology.TriangleList; bundle.SetVertexBuffer(0, vertexBufferView); bundle.SetIndexBuffer(indexBufferView); //bundle.DrawInstanced( // vertices.Length,//VertexCountPerInstance,要绘制的顶点数 // 1,//InstanceCount,要绘制的实例数,这里是1个 // 0,//StartVertexLocation,第一个顶点的索引,这里是0 // 0);//StartInstanceLocation,在从顶点缓冲区读取每个实例数据之前添加到每个索引的值 bundle.DrawIndexedInstanced( indices.Length, //IndexCountPerInstance,要绘制的索引数 1, //InstanceCount,要绘制的实例数,这里是1个 0, //StartIndexLocation,第一个顶点的索引,这里是0 0, //BaseVertexLocation,,从顶点缓冲区读取顶点之前添加到每个索引的值 0); //StartInstanceLocation,在从顶点缓冲区读取每个实例数据之前添加到每个索引的值 bundle.Close(); //使用上传堆来传递常量缓冲区的数据 /*--------------------------------------------------* * 不推荐使用上传堆来传递像垂直缓冲区这样的静态数据 * * 这里使用上载堆是为了代码的简洁性,并且还因为需要 * * 传递的资源很少 * *--------------------------------------------------*/ constantBuffer = device.CreateCommittedResource( new HeapProperties(HeapType.Upload), HeapFlags.None, ResourceDescription.Buffer(1024 * 64), ResourceStates.GenericRead); //创建SRV视图 var srvDesc = new ShaderResourceViewDescription(); srvDesc.Texture2D.MostDetailedMip = 0; srvDesc.Texture2D.ResourceMinLODClamp = 0.0f; device.CreateShaderResourceView(texture, srvDesc, shaderRenderViewHeap.CPUDescriptorHandleForHeapStart); //创建常量缓冲区视图(CBV) var cbvDesc = new ConstantBufferViewDescription() { BufferLocation = constantBuffer.GPUVirtualAddress, SizeInBytes = (Utilities.SizeOf <ConstantBuffer>() + 255) & ~255 }; device.CreateConstantBufferView( cbvDesc, constantBufferViewHeap.CPUDescriptorHandleForHeapStart); //初始化并映射常量缓冲区 /*--------------------------------------------------* * 直到应用程序关闭,我们才会取消映射,因此在资源的 * * 生命周期中保持映射是可以的 * *------------------------------------------------- */ constantBufferPointer = constantBuffer.Map(0); Utilities.Write(constantBufferPointer, ref worldViewProj); //创建同步对象 //创建围栏 fence = device.CreateFence( 0, //围栏的初始值 FenceFlags.None); //指定围栏的类型,None表示没有指定的类型 fenceValue = 1; //创建用于帧同步的事件句柄 fenceEvent = new AutoResetEvent(false); }
private void LoadAssets() { // Create the root signature description. var rootSignatureDesc = new RootSignatureDescription( RootSignatureFlags.AllowInputAssemblerInputLayout, // Root Parameters new[] { new RootParameter(ShaderVisibility.All, new [] { new DescriptorRange() { RangeType = DescriptorRangeType.ShaderResourceView, DescriptorCount = 1, OffsetInDescriptorsFromTableStart = int.MinValue, BaseShaderRegister = 0 }, new DescriptorRange() { RangeType = DescriptorRangeType.ConstantBufferView, DescriptorCount = 1, OffsetInDescriptorsFromTableStart = int.MinValue + 1, BaseShaderRegister = 0 } }), new RootParameter(ShaderVisibility.Pixel, new DescriptorRange() { RangeType = DescriptorRangeType.Sampler, DescriptorCount = 1, OffsetInDescriptorsFromTableStart = int.MinValue, BaseShaderRegister = 0 }), }); //// Samplers //new[] //{ // new StaticSamplerDescription(ShaderVisibility.Pixel, 0, 0) // { // Filter = Filter.MinimumMinMagMipPoint, // AddressUVW = TextureAddressMode.Border, // } //}); rootSignature = device.CreateRootSignature(0, rootSignatureDesc.Serialize()); // Create the pipeline state, which includes compiling and loading shaders. #if DEBUG var vertexShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.Compile(SharpDX.IO.NativeFile.ReadAllText("../../shaders.hlsl"), "VSMain", "vs_5_0", SharpDX.D3DCompiler.ShaderFlags.Debug)); #else var vertexShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("shaders.hlsl", "VSMain", "vs_5_0")); #endif #if DEBUG var pixelShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.Compile(SharpDX.IO.NativeFile.ReadAllText("../../shaders.hlsl"), "PSMain", "ps_5_0", SharpDX.D3DCompiler.ShaderFlags.Debug)); #else var pixelShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("shaders.hlsl", "PSMain", "ps_5_0")); #endif #if DEBUG //var result = SharpDX.D3DCompiler.ShaderBytecode.Compile(SharpDX.IO.NativeFile.ReadAllText("../../shaders.hlsl"), "GSMain", "gs_5_0", SharpDX.D3DCompiler.ShaderFlags.Debug); var geometryShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.Compile(SharpDX.IO.NativeFile.ReadAllText("../../shaders.hlsl"), "GSMain", "gs_5_0", SharpDX.D3DCompiler.ShaderFlags.Debug)); #else var pixelShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("shaders.hlsl", "PSMain", "ps_5_0")); #endif // Define the vertex input layout. var inputElementDescs = new[] { new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0), new InputElement("TEXCOORD", 0, Format.R32G32_Float, 12, 0) }; // Describe and create the graphics pipeline state object (PSO). var psoDesc = new GraphicsPipelineStateDescription() { InputLayout = new InputLayoutDescription(inputElementDescs), RootSignature = rootSignature, VertexShader = vertexShader, GeometryShader = geometryShader, PixelShader = pixelShader, RasterizerState = RasterizerStateDescription.Default(), BlendState = BlendStateDescription.Default(), DepthStencilFormat = SharpDX.DXGI.Format.D32_Float, DepthStencilState = new DepthStencilStateDescription() { IsDepthEnabled = true, DepthComparison = Comparison.LessEqual, DepthWriteMask = DepthWriteMask.All, IsStencilEnabled = false }, SampleMask = int.MaxValue, PrimitiveTopologyType = PrimitiveTopologyType.Triangle, RenderTargetCount = 1, Flags = PipelineStateFlags.None, SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0), StreamOutput = new StreamOutputDescription() }; psoDesc.RenderTargetFormats[0] = SharpDX.DXGI.Format.R8G8B8A8_UNorm; pipelineState = device.CreateGraphicsPipelineState(psoDesc); commandList = device.CreateCommandList(CommandListType.Direct, commandAllocator, pipelineState); commandList.Close(); // build vertex buffer var triangleVertices = new[] { //TOP new Vertex() { Position = new Vector3(-1f, 1f, 1f), TexCoord = new Vector2(1f, 1f) }, new Vertex() { Position = new Vector3(1f, 1f, 1f), TexCoord = new Vector2(0f, 1f) }, new Vertex() { Position = new Vector3(1f, 1f, -1f), TexCoord = new Vector2(0f, 0f) }, new Vertex() { Position = new Vector3(-1f, 1f, -1f), TexCoord = new Vector2(1f, 0f) }, //BOTTOM new Vertex() { Position = new Vector3(-1f, -1f, 1f), TexCoord = new Vector2(1f, 1f) }, new Vertex() { Position = new Vector3(1f, -1f, 1f), TexCoord = new Vector2(0f, 1f) }, new Vertex() { Position = new Vector3(1f, -1f, -1f), TexCoord = new Vector2(0f, 0f) }, new Vertex() { Position = new Vector3(-1f, -1f, -1f), TexCoord = new Vector2(1f, 0f) }, //LEFT new Vertex() { Position = new Vector3(-1f, -1f, 1f), TexCoord = new Vector2(0f, 1f) }, new Vertex() { Position = new Vector3(-1f, 1f, 1f), TexCoord = new Vector2(0f, 0f) }, new Vertex() { Position = new Vector3(-1f, 1f, -1f), TexCoord = new Vector2(1f, 0f) }, new Vertex() { Position = new Vector3(-1f, -1f, -1f), TexCoord = new Vector2(1f, 1f) }, //RIGHT new Vertex() { Position = new Vector3(1f, -1f, 1f), TexCoord = new Vector2(1f, 1f) }, new Vertex() { Position = new Vector3(1f, 1f, 1f), TexCoord = new Vector2(1f, 0f) }, new Vertex() { Position = new Vector3(1f, 1f, -1f), TexCoord = new Vector2(0f, 0f) }, new Vertex() { Position = new Vector3(1f, -1f, -1f), TexCoord = new Vector2(0f, 1f) }, //FRONT new Vertex() { Position = new Vector3(-1f, 1f, 1f), TexCoord = new Vector2(1f, 0f) }, new Vertex() { Position = new Vector3(1f, 1f, 1f), TexCoord = new Vector2(0f, 0f) }, new Vertex() { Position = new Vector3(1f, -1f, 1f), TexCoord = new Vector2(0f, 1f) }, new Vertex() { Position = new Vector3(-1f, -1f, 1f), TexCoord = new Vector2(1f, 1f) }, //BACK new Vertex() { Position = new Vector3(-1f, 1f, -1f), TexCoord = new Vector2(0f, 0f) }, new Vertex() { Position = new Vector3(1f, 1f, -1f), TexCoord = new Vector2(1f, 0f) }, new Vertex() { Position = new Vector3(1f, -1f, -1f), TexCoord = new Vector2(1f, 1f) }, new Vertex() { Position = new Vector3(-1f, -1f, -1f), TexCoord = new Vector2(0f, 1f) } }; int vertexBufferSize = Utilities.SizeOf(triangleVertices); vertexBuffer = device.CreateCommittedResource(new HeapProperties(HeapType.Upload), HeapFlags.None, ResourceDescription.Buffer(vertexBufferSize), ResourceStates.GenericRead); IntPtr pVertexDataBegin = vertexBuffer.Map(0); Utilities.Write(pVertexDataBegin, triangleVertices, 0, triangleVertices.Length); vertexBuffer.Unmap(0); vertexBufferView = new VertexBufferView(); vertexBufferView.BufferLocation = vertexBuffer.GPUVirtualAddress; vertexBufferView.StrideInBytes = Utilities.SizeOf <Vertex>(); vertexBufferView.SizeInBytes = vertexBufferSize; // build index buffer var triangleIndexes = new uint[] { 0, 1, 2, 0, 2, 3, 4, 6, 5, 4, 7, 6, 8, 9, 10, 8, 10, 11, 12, 14, 13, 12, 15, 14, 16, 18, 17, 16, 19, 18, 20, 21, 22, 20, 22, 23 }; int indexBufferSize = Utilities.SizeOf(triangleIndexes); indexBuffer = device.CreateCommittedResource(new HeapProperties(HeapType.Upload), HeapFlags.None, ResourceDescription.Buffer(indexBufferSize), ResourceStates.GenericRead); IntPtr pIndexDataBegin = indexBuffer.Map(0); Utilities.Write(pIndexDataBegin, triangleIndexes, 0, triangleIndexes.Length); indexBuffer.Unmap(0); indexBufferView = new IndexBufferView(); indexBufferView.BufferLocation = indexBuffer.GPUVirtualAddress; indexBufferView.SizeInBytes = indexBufferSize; indexBufferView.Format = Format.R32_UInt; // Create the texture. // Describe and create a Texture2D. var textureDesc = ResourceDescription.Texture2D(Format.R8G8B8A8_UNorm, TextureWidth, TextureHeight, 1, 1, 1, 0, ResourceFlags.None, TextureLayout.Unknown, 0); texture = device.CreateCommittedResource(new HeapProperties(HeapType.Upload), HeapFlags.None, textureDesc, ResourceStates.GenericRead, null); // Copy data to the intermediate upload heap and then schedule a copy // from the upload heap to the Texture2D. byte[] textureData = Utilities.ReadStream(new FileStream("../../texture1.dds", FileMode.Open)); texture.Name = "Texture"; var handle = GCHandle.Alloc(textureData, GCHandleType.Pinned); var ptr = Marshal.UnsafeAddrOfPinnedArrayElement(textureData, 0); texture.WriteToSubresource(0, null, ptr, TextureWidth * 4, textureData.Length); handle.Free(); // Describe and create a SRV for the texture. var srvDesc = new ShaderResourceViewDescription { Shader4ComponentMapping = ((((0) & 0x7) | (((1) & 0x7) << 3) | (((2) & 0x7) << (3 * 2)) | (((3) & 0x7) << (3 * 3)) | (1 << (3 * 4)))), Format = textureDesc.Format, Dimension = ShaderResourceViewDimension.Texture2D, Texture2D = { MipLevels = 1, MostDetailedMip = 0, PlaneSlice = 0, ResourceMinLODClamp = 0.0f }, }; device.CreateShaderResourceView(texture, srvDesc, srvCbvHeap.CPUDescriptorHandleForHeapStart); SamplerStateDescription samplerDesc = new SamplerStateDescription { Filter = Filter.MinMagMipLinear, AddressU = TextureAddressMode.Clamp, AddressV = TextureAddressMode.Clamp, AddressW = TextureAddressMode.Clamp, MaximumAnisotropy = 0, MaximumLod = float.MaxValue, MinimumLod = -float.MaxValue, MipLodBias = 0, ComparisonFunction = Comparison.Never }; device.CreateSampler(samplerDesc, samplerViewHeap.CPUDescriptorHandleForHeapStart); // build constant buffer constantBuffer = device.CreateCommittedResource(new HeapProperties(HeapType.Upload), HeapFlags.None, ResourceDescription.Buffer(1024 * 64), ResourceStates.GenericRead); var cbDesc = new ConstantBufferViewDescription() { BufferLocation = constantBuffer.GPUVirtualAddress, SizeInBytes = (Utilities.SizeOf <ConstantBufferData>() + 255) & ~255 }; var srvCbvStep = device.GetDescriptorHandleIncrementSize(DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView); device.CreateConstantBufferView(cbDesc, srvCbvHeap.CPUDescriptorHandleForHeapStart + srvCbvStep); constantBufferData = new ConstantBufferData { Project = Matrix.Identity }; constantBufferPointer = constantBuffer.Map(0); Utilities.Write(constantBufferPointer, ref constantBufferData); // build depth buffer DescriptorHeapDescription descDescriptorHeapDSB = new DescriptorHeapDescription() { DescriptorCount = 1, Type = DescriptorHeapType.DepthStencilView, Flags = DescriptorHeapFlags.None }; DescriptorHeap descriptorHeapDSB = device.CreateDescriptorHeap(descDescriptorHeapDSB); ResourceDescription descDepth = new ResourceDescription() { Dimension = ResourceDimension.Texture2D, DepthOrArraySize = 1, MipLevels = 0, Flags = ResourceFlags.AllowDepthStencil, Width = (int)viewport.Width, Height = (int)viewport.Height, Format = Format.R32_Typeless, Layout = TextureLayout.Unknown, SampleDescription = new SampleDescription() { Count = 1 } }; ClearValue dsvClearValue = new ClearValue() { Format = Format.D32_Float, DepthStencil = new DepthStencilValue() { Depth = 1.0f, Stencil = 0 } }; Resource renderTargetDepth = device.CreateCommittedResource(new HeapProperties(HeapType.Default), HeapFlags.None, descDepth, ResourceStates.GenericRead, dsvClearValue); DepthStencilViewDescription depthDSV = new DepthStencilViewDescription() { Dimension = DepthStencilViewDimension.Texture2D, Format = Format.D32_Float, Texture2D = new DepthStencilViewDescription.Texture2DResource() { MipSlice = 0 } }; device.CreateDepthStencilView(renderTargetDepth, depthDSV, descriptorHeapDSB.CPUDescriptorHandleForHeapStart); handleDSV = descriptorHeapDSB.CPUDescriptorHandleForHeapStart; fence = device.CreateFence(0, FenceFlags.None); fenceValue = 1; fenceEvent = new AutoResetEvent(false); }
private void 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); }
protected virtual ID3D12Resource *CreateVertexBuffer(out VertexBufferView vertexBufferView) { // Define the geometry for a triangle. const int TriangleVerticesCount = 3; var triangleVertices = stackalloc Vertex[TriangleVerticesCount] { new Vertex { Position = new Vector3(0.0f, 0.5f, 0.0f), Color = new Vector4(1.0f, 0.0f, 0.0f, 1.0f) }, new Vertex { Position = new Vector3(0.5f, -0.5f, 0.0f), Color = new Vector4(0.0f, 1.0f, 0.0f, 1.0f) }, new Vertex { Position = new Vector3(-0.5f, -0.5f, 0.0f), Color = new Vector4(0.0f, 0.0f, 1.0f, 1.0f) }, }; var vertexBufferSize = (uint)sizeof(Vertex) * TriangleVerticesCount; // 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. ID3D12Resource *vertexBuffer; var heapProperties = new HeapProperties(HeapType.HeapTypeUpload); var bufferDesc = new ResourceDesc ( ResourceDimension.ResourceDimensionBuffer, 0, vertexBufferSize, 1, 1, 1, Format.FormatUnknown, new SampleDesc(1, 0), TextureLayout.TextureLayoutRowMajor, ResourceFlags.ResourceFlagNone ); var iid = ID3D12Resource.Guid; SilkMarshal.ThrowHResult ( D3DDevice->CreateCommittedResource ( &heapProperties, HeapFlags.HeapFlagNone, &bufferDesc, ResourceStates.ResourceStateGenericRead, pOptimizedClearValue: null, &iid, (void **)&vertexBuffer ) ); // Copy the triangle data to the vertex buffer. var readRange = new Range(); byte *pVertexDataBegin; SilkMarshal.ThrowHResult(vertexBuffer->Map(Subresource: 0, &readRange, (void **)&pVertexDataBegin)); Unsafe.CopyBlock(pVertexDataBegin, triangleVertices, vertexBufferSize); vertexBuffer->Unmap(0, null); // Initialize the vertex buffer view. vertexBufferView.BufferLocation = vertexBuffer->GetGPUVirtualAddress(); vertexBufferView.StrideInBytes = (uint)sizeof(Vertex); vertexBufferView.SizeInBytes = vertexBufferSize; return(vertexBuffer); }
private void LoadMesh(CpuDescriptorHandle heapStart) { SamplerStateDescription samplerDesc = new SamplerStateDescription() { Filter = Filter.ComparisonMinMagMipLinear, AddressU = TextureAddressMode.Wrap, AddressV = TextureAddressMode.Wrap, AddressW = TextureAddressMode.Wrap, MinimumLod = float.MinValue, MaximumLod = float.MaxValue, MipLodBias = 0, MaximumAnisotropy = 0, ComparisonFunction = Comparison.Never }; var heapPosition = heapStart; // Load model from obj. var importer = new Assimp.AssimpContext(); var scene = importer.ImportFile(@"../../../Models/lara/lara.obj", PostProcessSteps.GenerateSmoothNormals | PostProcessSteps.FlipUVs | PostProcessSteps.PreTransformVertices); Vertex[] vertices = new Vertex[scene.Meshes.Sum(m => m.VertexCount)]; int[] indices = new int[scene.Meshes.Sum(m => m.FaceCount * 3)]; faceCounts = new List <int>(); int vertexOffSet = 0; int indexOffSet = 0; foreach (var mesh in scene.Meshes) { var positions = mesh.Vertices; var normals = mesh.Normals; var texs = mesh.TextureCoordinateChannels[0]; for (int i = 0; i < mesh.VertexCount; i++) { vertices[vertexOffSet + i] = new Vertex() { position = new Vector3(positions[i].X, positions[i].Y, positions[i].Z), normal = new Vector3(normals[i].X, normals[i].Y, normals[i].Z), textureCoordinate = new Vector3(texs[i].X, texs[i].Y, texs[i].Z) }; } var faces = mesh.Faces; for (int i = 0; i < mesh.FaceCount; i++) { indices[i * 3 + indexOffSet] = (int)faces[i].Indices[0] + vertexOffSet; indices[i * 3 + 1 + indexOffSet] = (int)faces[i].Indices[1] + vertexOffSet; indices[i * 3 + 2 + indexOffSet] = (int)faces[i].Indices[2] + vertexOffSet; } faceCounts.Add(mesh.FaceCount * 3); vertexOffSet += mesh.VertexCount; indexOffSet += mesh.FaceCount * 3; string textureName = System.IO.Path.GetFileName(scene.Materials[mesh.MaterialIndex].TextureDiffuse.FilePath); var texResource = TextureUtilities.CreateTextureFromDDS(device, @"../../../Models/lara/" + textureName); textures.Add(texResource); int D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING = 5768; ShaderResourceViewDescription desc = new ShaderResourceViewDescription { Dimension = ShaderResourceViewDimension.Texture2D, Format = texResource.Description.Format, Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, }; desc.Texture2D.MipLevels = 1; desc.Texture2D.MostDetailedMip = 0; desc.Texture2D.ResourceMinLODClamp = 0; device.CreateShaderResourceView(texResource, desc, heapStart); heapStart += constantBufferDescriptorSize; } 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 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; }
public void BuildPSO(Device3 device, GraphicsCommandList commandList) { _resources = new GraphicsResource[0]; // Create an empty root signature. RootSignatureDescription rootSignatureDesc = new RootSignatureDescription(RootSignatureFlags.AllowInputAssemblerInputLayout); _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/SimpleShader.hlsl", "VSMain", "vs_5_0", SharpDX.D3DCompiler.ShaderFlags.Debug)); #else var vertexShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("Shaders/SimpleShader.hlsl", "VSMain", "vs_5_0")); #endif #if DEBUG var pixelShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("Shaders/SimpleShader.hlsl", "PSMain", "ps_5_0", SharpDX.D3DCompiler.ShaderFlags.Debug)); #else var pixelShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("Shaders/SimpleShader.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); // Define the geometry for a triangle. Vertex[] triangleVertices = new Vertex[] { new Vertex() { position = new Vector3(-0.5f, -0.5f, 0.5f), color = new Vector4(1.0f, 0.0f, 0.0f, 1.0f) }, new Vertex() { position = new Vector3(-0.5f, 0.5f, 0.5f), color = new Vector4(1.0f, 0.0f, 0.0f, 1.0f) }, new Vertex() { position = new Vector3(0.5f, -0.5f, 0.5f), color = new Vector4(1.0f, 0.0f, 0.0f, 1.0f) }, new Vertex() { position = new Vector3(0.5f, 0.5f, 0.5f), color = new Vector4(1.0f, 0.0f, 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); _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 }; }
private void LoadAssets() { // Create an empty root signature. var rootSignatureDesc = new RootSignatureDescription(RootSignatureFlags.AllowInputAssemblerInputLayout); rootSignature = device.CreateRootSignature(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 // Define the vertex input layout. var inputElementDescs = new [] { 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). var 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); // 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 triangle. var triangleVertices = new [] { 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; // Create and record the bundle. bundle = device.CreateCommandList(0, CommandListType.Bundle, bundleAllocator, pipelineState); bundle.SetGraphicsRootSignature(rootSignature); bundle.PrimitiveTopology = SharpDX.Direct3D.PrimitiveTopology.TriangleList; bundle.SetVertexBuffer(0, vertexBufferView); bundle.DrawInstanced(3, 1, 0, 0); bundle.Close(); // 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 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() { 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(); }
private void LoadAssets() { // Create the root signature description. var rootSignatureDesc = new RootSignatureDescription(RootSignatureFlags.AllowInputAssemblerInputLayout, // Root Parameters new[] { new RootParameter(ShaderVisibility.Pixel, new DescriptorRange() { RangeType = DescriptorRangeType.ShaderResourceView, DescriptorCount = 3, OffsetInDescriptorsFromTableStart = int.MinValue, BaseShaderRegister = 0 }), new RootParameter(ShaderVisibility.Pixel, new DescriptorRange() { RangeType = DescriptorRangeType.ConstantBufferView, DescriptorCount = 1, BaseShaderRegister = 0, OffsetInDescriptorsFromTableStart = int.MinValue, }) }, // Samplers new[] { new StaticSamplerDescription(ShaderVisibility.Pixel, 0, 0) { //Filter = Filter.MinimumMinMagMipPoint, Filter = Filter.ComparisonMinLinearMagPointMipLinear, AddressUVW = TextureAddressMode.Border, } }); rootSignature = device.CreateRootSignature(0, rootSignatureDesc.Serialize()); // Create the pipeline state, which includes compiling and loading shaders. var vertexShaderPath = Utils.GetVertexShaderPath(); var pixelShaderPath = Utils.GetPixelShaderForRenderingMode(VolViz.Configuration.RenderingMode.Dvr); #if DEBUG var vertexShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile(vertexShaderPath, "VSMain", "vs_5_0", SharpDX.D3DCompiler.ShaderFlags.Debug)); #else var vertexShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile(vertexShaderPath, "VSMain", "vs_5_0")); #endif #if DEBUG var pixelShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile(pixelShaderPath, "PSMain", "ps_5_0", SharpDX.D3DCompiler.ShaderFlags.Debug)); #else var pixelShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile(pixelShaderPath, "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, 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); // Define the geometry for a square consisting of two triangles. var squareVertexes = new[] { new Vertex() { Position = new Vector3(-1.0f, 1.0f, 0.0f), TexCoord = new Vector2(0.0f, 0.0f) }, new Vertex() { Position = new Vector3(1.0f, 1.0f, 0.0f), TexCoord = new Vector2(1.0f, 0.0f) }, new Vertex() { Position = new Vector3(-1.0f, -1.0f, 0.0f), TexCoord = new Vector2(0.0f, 1.0f) }, new Vertex() { Position = new Vector3(1.0f, 1.0f, 0.0f), TexCoord = new Vector2(1.0f, 0.0f) }, new Vertex() { Position = new Vector3(1.0f, -1.0f, 0.0f), TexCoord = new Vector2(1.0f, 1.0f) }, new Vertex() { Position = new Vector3(-1.0f, -1.0f, 0.0f), TexCoord = new Vector2(0.0f, 1.0f) }, }; // Create the vertex buffer. int vertexBufferSize = Utilities.SizeOf(squareVertexes); // 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. var pVertexDataBegin = vertexBuffer.Map(0); Utilities.Write(pVertexDataBegin, squareVertexes, 0, squareVertexes.Length); vertexBuffer.Unmap(0); // Initialize the vertex buffer view. vertexBufferView = new VertexBufferView(); vertexBufferView.BufferLocation = vertexBuffer.GPUVirtualAddress; vertexBufferView.StrideInBytes = Utilities.SizeOf <Vertex>(); vertexBufferView.SizeInBytes = vertexBufferSize; // Load volume data var volumeTextureDesc = ResourceDescription.Texture3D(Format.R8G8B8A8_UNorm, VolumeTextureWidth, VolumeTextureHeight, VolumeTextureDepth, 1); volumeTexture = device.CreateCommittedResource(new HeapProperties( HeapType.Default), HeapFlags.None, volumeTextureDesc, ResourceStates.CopyDestination); long volumeUploadBufferSize = GetRequiredIntermediateSize(this.volumeTexture, 0, 1); // Create the GPU upload buffer. var volumeTextureUploadHeap = device.CreateCommittedResource(new HeapProperties( CpuPageProperty.WriteBack, MemoryPool.L0), HeapFlags.None, ResourceDescription.Texture3D(Format.R8G8B8A8_UNorm, VolumeTextureWidth, VolumeTextureHeight, VolumeTextureDepth, 1), ResourceStates.GenericRead); // Copy data to the intermediate upload heap and then schedule a copy // from the upload heap to the Texture3D. byte[] volumeTextureData = GenerateVolumeTextureData(); var volumeHandle = GCHandle.Alloc(volumeTextureData, GCHandleType.Pinned); var volumePtr = Marshal.UnsafeAddrOfPinnedArrayElement(volumeTextureData, 0); volumeTextureUploadHeap.WriteToSubresource(0, null, volumePtr, TexturePixelSize * VolumeTextureWidth, TexturePixelSize * VolumeTextureWidth * VolumeTextureHeight); volumeHandle.Free(); commandList.CopyTextureRegion(new TextureCopyLocation(volumeTexture, 0), 0, 0, 0, new TextureCopyLocation(volumeTextureUploadHeap, 0), null); commandList.ResourceBarrierTransition(this.volumeTexture, ResourceStates.CopyDestination, ResourceStates.PixelShaderResource); // Describe and create a SRV for the volume texture. var volumeSrvDesc = new ShaderResourceViewDescription { Shader4ComponentMapping = D3DXUtilities.DefaultComponentMapping(), Format = volumeTextureDesc.Format, Dimension = ShaderResourceViewDimension.Texture3D, Texture3D = { MipLevels = 1 }, }; device.CreateShaderResourceView(this.volumeTexture, volumeSrvDesc, shaderRenderViewHeap.CPUDescriptorHandleForHeapStart); // End load volume data // Load transfer function var transferFunctionTextureDesc = ResourceDescription.Texture1D(Format.R8G8B8A8_UNorm, TransferFunctionWidth, 1); transferFunctionTexture = device.CreateCommittedResource(new HeapProperties( HeapType.Default), HeapFlags.None, transferFunctionTextureDesc, ResourceStates.CopyDestination); long transferFunctionUploadBufferSize = GetRequiredIntermediateSize(this.transferFunctionTexture, 0, 1); // Create the GPU upload buffer. var transferFunctionTextureUploadHeap = device.CreateCommittedResource(new HeapProperties( CpuPageProperty.WriteBack, MemoryPool.L0), HeapFlags.None, ResourceDescription.Texture1D(Format.R8G8B8A8_UNorm, TransferFunctionWidth, 1), ResourceStates.GenericRead); // Copy data to the intermediate upload heap and then schedule a copy // from the upload heap to the Texture1D. byte[] transferFunctionTextureData = GenerateTransferFunctionTextureData(); var transferFunctionHandle = GCHandle.Alloc(transferFunctionTextureData, GCHandleType.Pinned); var transferFunctionPtr = Marshal.UnsafeAddrOfPinnedArrayElement(transferFunctionTextureData, 0); transferFunctionTextureUploadHeap.WriteToSubresource(0, null, transferFunctionPtr, TransferFunctionWidth, TransferFunctionWidth); transferFunctionHandle.Free(); commandList.CopyTextureRegion(new TextureCopyLocation(transferFunctionTexture, 0), 0, 0, 0, new TextureCopyLocation(transferFunctionTextureUploadHeap, 0), null); commandList.ResourceBarrierTransition(this.transferFunctionTexture, ResourceStates.CopyDestination, ResourceStates.PixelShaderResource); // Describe and create a SRV for the transfer function texture. var transferFunctionSrvDesc = new ShaderResourceViewDescription { Shader4ComponentMapping = D3DXUtilities.DefaultComponentMapping(), Format = transferFunctionTextureDesc.Format, Dimension = ShaderResourceViewDimension.Texture1D, Texture1D = { MipLevels = 1 }, }; var transferFunctionHandleIncrement = device.GetDescriptorHandleIncrementSize(DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView); CpuDescriptorHandle transferFunctionLocationDesctiptor = shaderRenderViewHeap.CPUDescriptorHandleForHeapStart + transferFunctionHandleIncrement; device.CreateShaderResourceView(this.transferFunctionTexture, transferFunctionSrvDesc, transferFunctionLocationDesctiptor); // End load transfer function data // Load gradients data var gradientsTextureDesc = ResourceDescription.Texture3D(Format.R8G8B8A8_UNorm, VolumeTextureWidth, VolumeTextureHeight, VolumeTextureDepth, 1); gradientsTexture = device.CreateCommittedResource(new HeapProperties( HeapType.Default), HeapFlags.None, gradientsTextureDesc, ResourceStates.CopyDestination); long gradientsUploadBufferSize = GetRequiredIntermediateSize(this.gradientsTexture, 0, 1); // Create the GPU upload buffer. var gradientsTextureUploadHeap = device.CreateCommittedResource(new HeapProperties( CpuPageProperty.WriteBack, MemoryPool.L0), HeapFlags.None, ResourceDescription.Texture3D(Format.R8G8B8A8_UNorm, VolumeTextureWidth, VolumeTextureHeight, VolumeTextureDepth, 1), ResourceStates.GenericRead); // Copy data to the intermediate upload heap and then schedule a copy // from the upload heap to the Texture3D. byte[] gradientsTextureData = GenerateGradientsTextureData(); var gradientsHandle = GCHandle.Alloc(gradientsTextureData, GCHandleType.Pinned); var gradientsPtr = Marshal.UnsafeAddrOfPinnedArrayElement(gradientsTextureData, 0); gradientsTextureUploadHeap.WriteToSubresource(0, null, gradientsPtr, TexturePixelSize * VolumeTextureWidth, TexturePixelSize * VolumeTextureWidth * VolumeTextureHeight); gradientsHandle.Free(); commandList.CopyTextureRegion(new TextureCopyLocation(gradientsTexture, 0), 0, 0, 0, new TextureCopyLocation(gradientsTextureUploadHeap, 0), null); commandList.ResourceBarrierTransition(this.gradientsTexture, ResourceStates.CopyDestination, ResourceStates.PixelShaderResource); // Describe and create a SRV for the gradients texture. var gradientsSrvDesc = new ShaderResourceViewDescription { Shader4ComponentMapping = D3DXUtilities.DefaultComponentMapping(), Format = gradientsTextureDesc.Format, Dimension = ShaderResourceViewDimension.Texture3D, Texture3D = { MipLevels = 1 }, }; var gradientsHandleIncrement = device.GetDescriptorHandleIncrementSize(DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView); CpuDescriptorHandle gradientsLocationDesctiptor = shaderRenderViewHeap.CPUDescriptorHandleForHeapStart + gradientsHandleIncrement * 2; device.CreateShaderResourceView(this.gradientsTexture, gradientsSrvDesc, gradientsLocationDesctiptor); // End load gradients data // 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. var 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); 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 volumeTextureUploadHeap.Dispose(); transferFunctionTextureUploadHeap.Dispose(); gradientsTextureUploadHeap.Dispose(); }