private void PlatformEnd() { _commandList.Close(); var d3d12CommandQueue = _graphicsDevice.CommandQueue.DeviceCommandQueue; d3d12CommandQueue.ExecuteCommandList(_commandList); using (var fence = _device.CreateFence(0, FenceFlags.None)) using (var gpuCompletedEvent = new ManualResetEvent(false)) { d3d12CommandQueue.Signal(fence, 1); fence.SetEventOnCompletion(1, gpuCompletedEvent.GetSafeWaitHandle().DangerousGetHandle()); gpuCompletedEvent.WaitOne(); } foreach (var resource in _trackedResources) { resource.Dispose(); } _trackedResources.Clear(); _commandList.Dispose(); _commandList = null; _commandAllocator.Dispose(); _commandAllocator = null; }
private void DrawRenderItems(GraphicsCommandList cmdList, List <RenderItem> ritems) { int objCBByteSize = D3DUtil.CalcConstantBufferByteSize <ObjectConstants>(); int matCBByteSize = D3DUtil.CalcConstantBufferByteSize <MaterialConstants>(); Resource objectCB = CurrFrameResource.ObjectCB.Resource; Resource matCB = CurrFrameResource.MaterialCB.Resource; foreach (RenderItem ri in ritems) { cmdList.SetVertexBuffer(0, ri.Geo.VertexBufferView); cmdList.SetIndexBuffer(ri.Geo.IndexBufferView); cmdList.PrimitiveTopology = ri.PrimitiveType; GpuDescriptorHandle tex = _srvDescriptorHeap.GPUDescriptorHandleForHeapStart + ri.Mat.DiffuseSrvHeapIndex * CbvSrvUavDescriptorSize; long objCBAddress = objectCB.GPUVirtualAddress + ri.ObjCBIndex * objCBByteSize; long matCBAddress = matCB.GPUVirtualAddress + ri.Mat.MatCBIndex * matCBByteSize; cmdList.SetGraphicsRootDescriptorTable(0, tex); cmdList.SetGraphicsRootConstantBufferView(1, objCBAddress); cmdList.SetGraphicsRootConstantBufferView(3, matCBAddress); cmdList.DrawIndexedInstanced(ri.IndexCount, 1, ri.StartIndexLocation, ri.BaseVertexLocation, 0); } }
private void CreatePSO(InputElement[] inputElementDescs, ShaderBytecode vertexShader, ShaderBytecode pixelShader) { // 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 = 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(); }
public static List <Mesh> New(Device device, GraphicsCommandList commandList, PrimitiveTopology primitiveTopology, ref int index) { var meshes = new List <Mesh>(); var x = new Cylinder(device, commandList, primitiveTopology, new Vector3(0, 0, 0), new Vector3(1, 0, 0), 0.01f, 0.01f, 10, 10, Color.Red, ref index); meshes.Add(x); x = new Cylinder(device, commandList, primitiveTopology, new Vector3(1, 0, 0), new Vector3(1.1f, 0, 0), 0.00f, 0.05f, 10, 10, Color.Red, ref index); meshes.Add(x); var y = new Cylinder(device, commandList, primitiveTopology, new Vector3(0, 0, 0), new Vector3(0, 1, 0), 0.01f, 0.01f, 10, 10, Color.Green, ref index); meshes.Add(y); y = new Cylinder(device, commandList, primitiveTopology, new Vector3(0, 1, 0), new Vector3(0, 1.1f, 0), 0.00f, 0.05f, 10, 10, Color.Green, ref index); meshes.Add(y); var z = new Cylinder(device, commandList, primitiveTopology, new Vector3(0, 0, 0), new Vector3(0, 0, 1), 0.01f, 0.01f, 10, 10, Color.Blue, ref index); meshes.Add(z); z = new Cylinder(device, commandList, primitiveTopology, new Vector3(0, 0, 1), new Vector3(0, 0, 1.1f), 0.00f, 0.05f, 10, 10, Color.Blue, ref index); meshes.Add(z); return(meshes); }
public Sphere(Device device, GraphicsCommandList commandList, PrimitiveTopology primitiveTopology, Vector3 position, float radius, int slices, int stacks, Color color, ref int index, string name = "Default") { base.CommandList = commandList; base.PrimitiveTopology = primitiveTopology; base.Name = name; var vertices = new List <Vertex>(); var indices = new List <short>(); var numVerticesPerRow = slices + 1; var numVerticesPerColumn = stacks + 1; var verticalAngularStride = (float)Math.PI / stacks; var horizontalAngularStride = ((float)Math.PI * 2) / slices; for (var verticalIt = 0; verticalIt < numVerticesPerColumn; verticalIt++) { // beginning on top of the sphere: var theta = ((float)Math.PI / 2.0f) - verticalAngularStride * verticalIt; for (var horizontalIt = 0; horizontalIt < numVerticesPerRow; horizontalIt++) { var phi = horizontalAngularStride * horizontalIt; // position var x = radius * (float)Math.Cos(theta) * (float)Math.Cos(phi); var y = radius * (float)Math.Cos(theta) * (float)Math.Sin(phi); var z = radius * (float)Math.Sin(theta); vertices.Add(new Vertex { Position = new Vector3(position.X + x, position.Y + y, position.Z + z), Color = color.ToVector4() }); } } for (var verticalIt = 0; verticalIt < stacks; verticalIt++) { for (var horizontalIt = 0; horizontalIt < slices; horizontalIt++) { var lt = (short)(horizontalIt + verticalIt * (numVerticesPerRow)); var rt = (short)((horizontalIt + 1) + verticalIt * (numVerticesPerRow)); var lb = (short)(horizontalIt + (verticalIt + 1) * (numVerticesPerRow)); var rb = (short)((horizontalIt + 1) + (verticalIt + 1) * (numVerticesPerRow)); indices.Add(lt); indices.Add(rt); indices.Add(lb); indices.Add(rt); indices.Add(rb); indices.Add(lb); } } this.Initialize(device, ref index, vertices, indices); }
public GpuWaves(Device device, GraphicsCommandList cmdList, int m, int n, float dx, float dt, float speed, float damping) { _device = device; RowCount = m; ColumnCount = n; Debug.Assert((m * n) % 256 == 0); VertexCount = m * n; TriangleCount = (m - 1) * (n - 1) * 2; _timeStep = dt; SpatialStep = dx; float d = damping * dt + 2.0f; float e = (speed * speed) * (dt * dt) / (dx * dx); _k = new[] { (damping * dt - 2.0f) / d, (4.0f - 8.0f * e) / d, (2.0f * e) / d }; BuildResources(cmdList); }
public static double[] Add(string objPath, double[] left, double[] right) { using (var fileStream = File.Create("AddArray.dxil")) { ShaderCompilation.CompileFromFile("AddArray.hlsl", "CSMain", "cs_5_0").Bytecode.Save(fileStream); } objPath = "AddArray.dxil"; using (var fileStream = File.OpenRead(objPath)) { AddArrayShaderCode = new byte[fileStream.Length]; fileStream.Read(AddArrayShaderCode, 0, AddArrayShaderCode.Length); } device = new Device(null, FeatureLevel.Level_11_0); fence = device.CreateFence(0, FenceFlags.None); commandQueue = device.CreateCommandQueue(CommandListType.Compute); commandAllocator = device.CreateCommandAllocator(CommandListType.Compute); commandList = device.CreateCommandList(0, CommandListType.Compute, commandAllocator, null); currentFence = 0; fenceEvent = new AutoResetEvent(false); var gpuResult = AddGpu(left, right); return(gpuResult); }
public DXGraphicsHost(RenderForm window, bool hidden = false) { if (window == null) { throw new ArgumentNullException(nameof(window)); } this.window = window; this.window.Visible = !hidden; // Buffering this.FrameCount = 3; // Triple Buffering this.renderTargets = new Resource[FrameCount]; this.commandAllocators = new CommandAllocator[FrameCount]; this.fenceValues = new int[FrameCount]; this.renderLoop = new RenderLoop(this.window); this.CreateDeviceResources(); this.CreateWindowResources(); commandList = Device.CreateCommandList(CommandListType.Direct, CommandAllocator, null); commandList.Name = $"Main CommandList"; commandList.Close(); bundleAllocator = device.CreateCommandAllocator(CommandListType.Bundle); bundlePool = new DXGraphicsCommandListPool(this, bundleAllocator, CommandListType.Bundle, "Bundle"); commandListPool = new DXGraphicsCommandListPool(this, CommandAllocator, CommandListType.Direct); }
public Triangle(Device device, GraphicsCommandList commandList, PrimitiveTopology primitiveTopology, Vector3 a, Vector3 b, Vector3 c, Color color, ref int index, string name = "Default") { base.CommandList = commandList; base.PrimitiveTopology = primitiveTopology; base.Name = name; Vertex[] vertices = { new Vertex { Position = a, Color = color.ToVector4() }, new Vertex { Position = b, Color = color.ToVector4() }, new Vertex { Position = c, Color = color.ToVector4() } }; short[] indices = { 0, 1, 2 }; this.Initialize(device, ref index, vertices, indices); }
/// <summary> /// Setup resources for rendering /// </summary> private void LoadAssets() { // Create the descriptor heap for the render target view descriptorHeap = device.CreateDescriptorHeap(new DescriptorHeapDescription() { Type = DescriptorHeapType.RenderTargetView, DescriptorCount = 1 }); // Create the main command list commandList = device.CreateCommandList(CommandListType.Direct, commandListAllocator, null); // Get the backbuffer and creates the render target view renderTarget = swapChain.GetBackBuffer <Resource>(0); device.CreateRenderTargetView(renderTarget, null, descriptorHeap.CPUDescriptorHandleForHeapStart); // Create the viewport viewPort = new ViewportF(0, 0, width, height); // Create the scissor scissorRectangle = new Rectangle(0, 0, width, height); // Create a fence to wait for next frame fence = device.CreateFence(0, FenceFlags.None); currentFence = 1; // Close command list commandList.Close(); // Create an event handle use for VTBL eventHandle = new AutoResetEvent(false); // Wait the command list to complete WaitForPrevFrame(); }
internal long ExecuteCommandListInternal(GraphicsCommandList nativeCommandList) { NativeCommandQueue.ExecuteCommandList(nativeCommandList); NativeCommandQueue.Signal(nativeFence, NextFenceValue); return(NextFenceValue++); }
internal void BeginFrame(GraphicsCommandList commandList) { var heaps = new DescriptorHeap[] { cbvHeap }; commandList.SetGraphicsRootSignature(rootSignature); commandList.SetDescriptorHeaps(heaps.Length, heaps); }
public static MeshGeometry New <TIndex>( Device device, GraphicsCommandList commandList, IEnumerable <TIndex> indices, string name = "Default") where TIndex : struct { TIndex[] indexArray = indices.ToArray(); int indexBufferByteSize = Utilities.SizeOf(indexArray); Resource indexBuffer = D3DUtil.CreateDefaultBuffer( device, commandList, indexArray, indexBufferByteSize, out Resource indexBufferUploader); return(new MeshGeometry { Name = name, IndexCount = indexArray.Length, IndexFormat = GetIndexFormat <TIndex>(), IndexBufferByteSize = indexBufferByteSize, IndexBufferGPU = indexBuffer, IndexBufferCPU = indexArray, _toDispose = { indexBuffer, indexBufferUploader } }); }
/// <summary> /// The CreateCommandList /// </summary> /// <param name="type">The <see cref="CommandListType"/></param> /// <param name="list">The <see cref="GraphicsCommandList"/></param> /// <param name="allocator">The <see cref="CommandAllocator"/></param> public void CreateNewCommandList(CommandListType type, out GraphicsCommandList list, out CommandAllocator allocator) { Debug.Assert(type != CommandListType.Bundle, "Bundles are not yet supported"); CommandAllocator tempAllocatorRef = null; switch (type) { case CommandListType.Direct: tempAllocatorRef = _GraphicsQueue.RequestAllocator(); break; case CommandListType.Bundle: break; case CommandListType.Compute: tempAllocatorRef = _ComputeQueue.RequestAllocator(); break; case CommandListType.Copy: tempAllocatorRef = _CopyQueue.RequestAllocator(); break; } list = _Device.CreateCommandList(type, tempAllocatorRef, null); list.Name = "CommandList"; allocator = tempAllocatorRef; Debug.Assert(list != null); }
public static Resource CreateDefaultBuffer <T>( Device device, GraphicsCommandList cmdList, T[] initData, long byteSize, out Resource uploadBuffer) where T : struct { var defaultBuffer = device.CreateCommittedResource( new HeapProperties(HeapType.Default), HeapFlags.None, ResourceDescription.Buffer(byteSize), ResourceStates.Common); uploadBuffer = device.CreateCommittedResource( new HeapProperties(HeapType.Upload), HeapFlags.None, ResourceDescription.Buffer(byteSize), ResourceStates.GenericRead); var ptr = uploadBuffer.Map(0); Utilities.Write(ptr, initData, 0, initData.Length); uploadBuffer.Unmap(0); cmdList.ResourceBarrierTransition(defaultBuffer, ResourceStates.Common, ResourceStates.CopyDestination); cmdList.CopyResource(defaultBuffer, uploadBuffer); cmdList.ResourceBarrierTransition(defaultBuffer, ResourceStates.CopyDestination, ResourceStates.GenericRead); return(defaultBuffer); }
public void DrawIndexedInstancedHook(IntPtr commandListPtr, int indexCountPerInstance, int instanceCount, int startIndexLocation, int baseVertexLocation, int startInstanceLocation) { try { GraphicsCommandList commandList = (GraphicsCommandList)commandListPtr; if (!init) { commandList.GetDevice(SharpDX.Utilities.GetGuidFromType(typeof(D3D12.Device)), out IntPtr devicePtr); device = (D3D12.Device)devicePtr; GetPipelineState(); init = true; } if (device != null) { commandList.PipelineState = pipelineState; } } catch (Exception ex) { logger.Error("ce", ex); } hookDrawIndexedInstanced.Target(commandListPtr, indexCountPerInstance, instanceCount, startIndexLocation, baseVertexLocation, startInstanceLocation); }
internal GraphicsCommandList GetOrCreateCommandList() { // For now, just create a single command list. We can expand // this in the future. _currentAllocator = _allocatorPool.AcquireResource(_fence.CompletedValue); if (_commandList != null) { _commandList.Reset( _currentAllocator, null); } else { _commandList = GraphicsDevice.Device.CreateCommandList( DeviceCommandQueue.Description.Type, _currentAllocator, null); } _commandList.SetDescriptorHeaps(GraphicsDevice.DescriptorHeapCbvUavSrv.DeviceDescriptorHeap); return(_commandList); }
public void BundleDraw(GraphicsCommandList bundleList) { bundleList.SetVertexBuffer(0, _vertexBufferView); bundleList.SetIndexBuffer(_indexBufferView); bundleList.DrawIndexedInstanced(36, 1, 0, 0, 0); bundleList.SetGraphicsRootConstantBufferView(2, _objectBuffer.GPUVirtualAddress + (Utilities.SizeOf <ObjectData>() + 255) & ~255); bundleList.DrawIndexedInstanced(36, 1, 0, 0, 0); }
public static void SetMarker(this GraphicsCommandList commandList, string message) { // TODO: message.Length IntPtr hMessage = Marshal.StringToHGlobalUni(message); commandList.SetMarker(1, hMessage, message.Length); Marshal.FreeHGlobal(hMessage); }
internal CommandEncoder(GraphicsDevice graphicsDevice, GraphicsCommandList commandList, RenderPassDescriptor renderPassDescriptor) : base(graphicsDevice) { _commandList = commandList; _renderPassDescriptor = renderPassDescriptor; _renderPassDescriptor.OnOpenedCommandList(_commandList); }
public void BundleDraw(GraphicsCommandList bundleList) { bundleList.SetGraphicsRootConstantBufferView(0, _perPassBuffer.GPUVirtualAddress); bundleList.SetVertexBuffer(0, _vertexBufferView); bundleList.SetIndexBuffer(_indexBufferView); bundleList.DrawIndexedInstanced(36, 1, 0, 0, 0); }
public CommandList(GraphicsDevice device) : base(device) { nativeCommandAllocator = device.CommandAllocators.GetObject(); NativeCommandList = device.NativeDevice.CreateCommandList(CommandListType.Direct, nativeCommandAllocator, null); ResetSrvHeap(true); ResetSamplerHeap(true); }
public Ssao(Device device, GraphicsCommandList cmdList, int width, int height) { _device = device; OnResize(width, height); BuildOffsetVectors(); BuildRandomVectorTexture(cmdList); }
internal void OnClosingCommandList(GraphicsCommandList commandList) { _depthStencilBuffer?.Release(); commandList.ResourceBarrierTransition( _renderTargetDescriptor.RenderTarget.Texture, ResourceStates.RenderTarget, ResourceStates.Present); }
public void BundleDraw(GraphicsCommandList bundleList) { bundleList.SetDescriptorHeaps(_srvDescriptorHeap); bundleList.SetGraphicsRootDescriptorTable(0, _srvDescriptorHeap.GPUDescriptorHandleForHeapStart); bundleList.SetVertexBuffer(0, _vertexBufferView); bundleList.SetIndexBuffer(_indexBufferView); bundleList.DrawIndexedInstanced(6, 1, 0, 0, 0); }
private void DrawFullscreenQuad(GraphicsCommandList cmdList) { // Null-out IA stage since we build the vertex off the SV_VertexID in the shader. cmdList.SetVertexBuffers(0, null, 1); cmdList.SetIndexBuffer(null); cmdList.PrimitiveTopology = PrimitiveTopology.TriangleList; cmdList.DrawInstanced(6, 1, 0, 0); }
public void BundleDraw(GraphicsCommandList bundleList) { bundleList.SetDescriptorHeaps(_srvDescriptorHeap); bundleList.SetGraphicsRootDescriptorTable(0, _srvDescriptorHeap.GPUDescriptorHandleForHeapStart); bundleList.SetGraphicsRootConstantBufferView(1, _perPassBuffer.GPUVirtualAddress); bundleList.SetVertexBuffer(0, _vertexBufferView); bundleList.SetIndexBuffer(_indexBufferView); bundleList.DrawIndexedInstanced(36, 1, 0, 0, 0); }
public Mesh(Device device, GraphicsCommandList commandList, PrimitiveTopology primitiveTopology, ref int index, IEnumerable <TVertex> vertices = null, IEnumerable <TIndex> indices = null, string name = "Default") { this.CommandList = commandList; this.PrimitiveTopology = primitiveTopology; this.Name = name; this.World = Matrix.Identity; this.Initialize(device, ref index, vertices, indices); }
public void Update(GameTimer gt, GraphicsCommandList cmdList, RootSignature rootSig, PipelineState pso) { // Accumulate time. _t += gt.DeltaTime; cmdList.PipelineState = pso; cmdList.SetComputeRootSignature(rootSig); // Only update the simulation at the specified time step. if (_t >= _timeStep) { // Set the update constants. Utilities.Pin(_k, ptr => cmdList.SetComputeRoot32BitConstants(0, 3, ptr, 0)); cmdList.SetComputeRootDescriptorTable(1, _prevSolUav); cmdList.SetComputeRootDescriptorTable(2, _currSolUav); cmdList.SetComputeRootDescriptorTable(3, _nextSolUav); // How many groups do we need to dispatch to cover the wave grid. // Note that RowCount and ColumnCount should be divisible by 16 // so there is no remainder. int numGroupsX = ColumnCount / 16; int numGroupsY = RowCount / 16; cmdList.Dispatch(numGroupsX, numGroupsY, 1); // // Ping-pong buffers in preparation for the next update. // The previous solution is no longer needed and becomes the target of the next solution in the next update. // The current solution becomes the previous solution. // The next solution becomes the current solution. // Resource resTemp = _prevSol; _prevSol = _currSol; _currSol = _nextSol; _nextSol = resTemp; GpuDescriptorHandle srvTemp = _prevSolSrv; _prevSolSrv = _currSolSrv; _currSolSrv = _nextSolSrv; _nextSolSrv = srvTemp; GpuDescriptorHandle uavTemp = _prevSolUav; _prevSolUav = _currSolUav; _currSolUav = _nextSolUav; _nextSolUav = uavTemp; // Reset time. _t = 0.0f; // The current solution needs to be able to be read by the vertex shader, so change its state to GENERIC_READ. cmdList.ResourceBarrierTransition(_currSol, ResourceStates.UnorderedAccess, ResourceStates.GenericRead); } }
public Grid(Device device, GraphicsCommandList commandList, PrimitiveTopology primitiveTopology, int cellsPerSideH, int cellsPerSideV, float cellSize, Color color, ref int index, string name = "Default") { base.CommandList = commandList; base.PrimitiveTopology = primitiveTopology; base.Name = name; var lineLengthH = cellsPerSideH * cellSize; var lineLengthV = cellsPerSideV * cellSize; var xStart = 0.0f; var yStart = -lineLengthH; var xCurrent = xStart; var yCurrent = yStart; var vertices = new List <Vertex>(); var indices = new List <short>(); short gridIndex = 0; for (var y = 0; y <= cellsPerSideV; y++) { vertices.Add(new Vertex { Position = new Vector3(xCurrent, yStart, 0), Color = color.ToVector4() }); indices.Add(gridIndex++); vertices.Add(new Vertex { Position = new Vector3(xCurrent, yStart + lineLengthH, 0), Color = color.ToVector4() }); indices.Add(gridIndex++); xCurrent += cellSize; } for (var x = 0; x <= cellsPerSideH; x++) { vertices.Add(new Vertex { Position = new Vector3(xStart, yCurrent, 0), Color = color.ToVector4() }); indices.Add(gridIndex++); vertices.Add(new Vertex { Position = new Vector3(xStart + lineLengthV, yCurrent, 0), Color = color.ToVector4() }); indices.Add(gridIndex++); yCurrent += cellSize; } this.Initialize(device, ref index, vertices, indices); }