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); }
/// <summary> /// Creates the rendering pipeline. /// </summary> /// <param name="form">The form.</param> private void LoadPipeline(Form form) { // create swap chain descriptor var swapChainDescription = new SwapChainDescription() { BufferCount = SwapBufferCount, ModeDescription = new ModeDescription(Format.R8G8B8A8_UNorm), Usage = Usage.RenderTargetOutput, OutputHandle = form.Handle, SwapEffect = SwapEffect.FlipDiscard, SampleDescription = new SampleDescription(1, 0), IsWindowed = true }; // create the device try { device = CreateDeviceWithSwapChain(DriverType.Hardware, FeatureLevel.Level_11_0, swapChainDescription, out swapChain, out commandQueue); } catch (SharpDXException) { device = CreateDeviceWithSwapChain(DriverType.Warp, FeatureLevel.Level_11_0, swapChainDescription, out swapChain, out commandQueue); } // create command queue and allocator objects commandListAllocator = device.CreateCommandAllocator(CommandListType.Direct); }
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; }
/// <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 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 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); }
/// <summary> /// The DiscardAllocator /// </summary> /// <param name="fenceValue">The <see cref="long"/></param> /// <param name="allocator">The <see cref="CommandAllocator"/></param> public void DiscardAllocator(long fenceValue, CommandAllocator allocator) { lock (_Mutex) { _ReadyAllocator.Enqueue(new Tuple <long, CommandAllocator>(fenceValue, allocator)); } }
/// <summary> /// The RequestAllocator /// </summary> /// <param name="completedFenceValue">The <see cref="long"/></param> /// <returns>The <see cref="CommandAllocator"/></returns> public CommandAllocator RequestAllocator(long completedFenceValue) { lock (_Mutex) { CommandAllocator result = null; if (_ReadyAllocator.Count != 0) { (var fenceValue, var allocator) = _ReadyAllocator.Peek(); if (fenceValue <= completedFenceValue) { result = allocator; result.Reset(); _ReadyAllocator.Dequeue(); } } if (result == null) { result = _Device.CreateCommandAllocator(_Type); result.Name = $"CommandAllocator {_AllocatorPool.Count}"; _AllocatorPool.Add(result); } return(result); } }
public CommandList(GraphicsDevice device) : base(device) { nativeCommandAllocator = device.CommandAllocators.GetObject(); NativeCommandList = device.NativeDevice.CreateCommandList(CommandListType.Direct, nativeCommandAllocator, null); ResetSrvHeap(true); ResetSamplerHeap(true); }
protected override void Draw(GameTimer gt) { CommandAllocator cmdListAlloc = CurrFrameResource.CmdListAlloc; // Reuse the memory associated with command recording. // We can only reset when the associated command lists have finished execution on the GPU. cmdListAlloc.Reset(); // A command list can be reset after it has been added to the command queue via ExecuteCommandList. // Reusing the command list reuses memory. CommandList.Reset(cmdListAlloc, _psos["opaque"]); CommandList.SetViewport(Viewport); CommandList.SetScissorRectangles(ScissorRectangle); // Indicate a state transition on the resource usage. CommandList.ResourceBarrierTransition(CurrentBackBuffer, ResourceStates.Present, ResourceStates.RenderTarget); // Clear the back buffer and depth buffer. CommandList.ClearRenderTargetView(CurrentBackBufferView, new Color(_mainPassCB.FogColor)); CommandList.ClearDepthStencilView(DepthStencilView, ClearFlags.FlagsDepth | ClearFlags.FlagsStencil, 1.0f, 0); // Specify the buffers we are going to render to. CommandList.SetRenderTargets(CurrentBackBufferView, DepthStencilView); CommandList.SetDescriptorHeaps(_descriptorHeaps.Length, _descriptorHeaps); CommandList.SetGraphicsRootSignature(_rootSignature); var passCBByteSize = D3DUtil.CalcConstantBufferByteSize <PassConstants>(); // Draw opaque items--floors, walls, skull. Resource passCB = CurrFrameResource.PassCB.Resource; CommandList.SetGraphicsRootConstantBufferView(2, passCB.GPUVirtualAddress); DrawRenderItems(CommandList, _ritemLayers[RenderLayer.Opaque]); // Indicate a state transition on the resource usage. CommandList.ResourceBarrierTransition(CurrentBackBuffer, ResourceStates.RenderTarget, ResourceStates.Present); // Done recording commands. CommandList.Close(); // Add the command list to the queue for execution. CommandQueue.ExecuteCommandList(CommandList); // Present the buffer to the screen. Presenting will automatically swap the back and front buffers. SwapChain.Present(0, PresentFlags.None); // Advance the fence value to mark commands up to this fence point. CurrFrameResource.Fence = ++CurrentFence; // Add an instruction to the command queue to set a new fence point. // Because we are on the GPU timeline, the new fence point won't be // set until the GPU finishes processing all the commands prior to this Signal(). CommandQueue.Signal(Fence, CurrentFence); }
private void ExecuteFailureCommand() { currentAllocator = failureAllocator; failureAllocator = null; while (enumerator.MoveNext()) { } StartCommandFromCurrentAllocator(); }
protected override void Draw(GameTimer gt) { CommandAllocator cmdListAlloc = CurrFrameResource.CmdListAlloc; // Reuse the memory associated with command recording. // We can only reset when the associated command lists have finished execution on the GPU. cmdListAlloc.Reset(); // A command list can be reset after it has been added to the command queue via ExecuteCommandList. // Reusing the command list reuses memory. CommandList.Reset(cmdListAlloc, _isWireframe ? _psos["opaque_wireframe"] : _psos["opaque"]); CommandList.SetViewport(Viewport); CommandList.SetScissorRectangles(ScissorRectangle); // Indicate a state transition on the resource usage. CommandList.ResourceBarrierTransition(CurrentBackBuffer, ResourceStates.Present, ResourceStates.RenderTarget); // Clear the back buffer and depth buffer. CommandList.ClearRenderTargetView(CurrentBackBufferView, Color.LightSteelBlue); CommandList.ClearDepthStencilView(DepthStencilView, ClearFlags.FlagsDepth | ClearFlags.FlagsStencil, 1.0f, 0); // Specify the buffers we are going to render to. CommandList.SetRenderTargets(CurrentBackBufferView, DepthStencilView); CommandList.SetDescriptorHeaps(_descriptorHeaps.Length, _descriptorHeaps); CommandList.SetGraphicsRootSignature(_rootSignature); int passCbvIndex = _passCbvOffset + _currFrameResourceIndex; GpuDescriptorHandle passCbvHandle = _cbvHeap.GPUDescriptorHandleForHeapStart; passCbvHandle += passCbvIndex * CbvSrvUavDescriptorSize; CommandList.SetGraphicsRootDescriptorTable(1, passCbvHandle); DrawRenderItems(CommandList, _ritemLayers[RenderLayer.Opaque]); // Indicate a state transition on the resource usage. CommandList.ResourceBarrierTransition(CurrentBackBuffer, ResourceStates.RenderTarget, ResourceStates.Present); // Done recording commands. CommandList.Close(); // Add the command list to the queue for execution. CommandQueue.ExecuteCommandList(CommandList); // Present the buffer to the screen. Presenting will automatically swap the back and front buffers. SwapChain.Present(0, PresentFlags.None); // Advance the fence value to mark commands up to this fence point. CurrFrameResource.Fence = ++CurrentFence; // Add an instruction to the command queue to set a new fence point. // Because we are on the GPU timeline, the new fence point won't be // set until the GPU finishes processing all the commands prior to this Signal(). CommandQueue.Signal(Fence, CurrentFence); }
public void Reset() { manager = null; triggeringEvent = null; currentCommand = null; pool = null; enumerator.Dispose(); failureAllocator = null; currentAllocator = null; }
internal void Start(Event triggeringEvent, CommandChain chain, CommandRelay manager, ObjectPool pool) { this.triggeringEvent = triggeringEvent; this.manager = manager; this.pool = pool; failureAllocator = chain.FailureCommand; enumerator = chain.Commands.GetEnumerator(); pool.Lock(triggeringEvent, this); enumerator.MoveNext(); Next(); }
public void Close() { NativeCommandList.Close(); // Recycle heaps ResetSrvHeap(false); ResetSamplerHeap(false); var fenceValue = GraphicsDevice.ExecuteCommandListInternal(NativeCommandList); GraphicsDevice.CommandAllocators.RecycleObject(fenceValue, nativeCommandAllocator); nativeCommandAllocator = null; }
public void Reset() { GraphicsDevice.ReleaseTemporaryResources(); ResetSrvHeap(true); ResetSamplerHeap(true); // Clear descriptor mappings srvMapping.Clear(); samplerMapping.Clear(); // Get a new allocator nativeCommandAllocator = GraphicsDevice.CommandAllocators.GetObject(); NativeCommandList.Reset(nativeCommandAllocator, null); }
/// <inheritdoc/> protected internal override void OnDestroyed() { // Recycle heaps ResetSrvHeap(false); ResetSamplerHeap(false); // Available right now (NextFenceValue - 1) // TODO: Note that it won't be available right away because CommandAllocators is currently not using a PriorityQueue but a simple Queue if (nativeCommandAllocator != null) { GraphicsDevice.CommandAllocators.RecycleObject(GraphicsDevice.NextFenceValue - 1, nativeCommandAllocator); nativeCommandAllocator = null; } Utilities.Dispose(ref NativeCommandList); base.OnDestroyed(); }
public DXGraphicsCommandListPool(DXGraphicsHost graphicsHost, CommandAllocator allocator, CommandListType type, string debugName = "CMDLIST") : base() { if (graphicsHost == null) { throw new ArgumentNullException(nameof(graphicsHost)); } if (allocator == null) { throw new ArgumentNullException(nameof(allocator)); } this.graphicsHost = graphicsHost; this.allocator = allocator; this.type = type; this.debugName = debugName; this.spareObjects = new ConcurrentBag <GraphicsCommandList>(); }
/// <summary> /// Creates the rendering pipeline. /// </summary> void LoadPipeline() { // create swap chain descriptor var swapChainDescription1 = new SwapChainDescription1() { AlphaMode = AlphaMode.Unspecified, BufferCount = SwapBufferCount, Usage = Usage.RenderTargetOutput, SwapEffect = SwapEffect.FlipSequential, SampleDescription = new SampleDescription(1, 0), Format = Format.R8G8B8A8_UNorm, Width = width, Height = height }; // enable debug layer using (var debugInterface = DebugInterface.Get()) debugInterface.EnableDebugLayer(); // create device using (var factory = new Factory4()) { #if USE_WARP using (var warpAdapter = factory.GetWarpAdapter()) { device = Collect(new Device(warpAdapter, FeatureLevel.Level_12_0)); } #else using (var adapter = factory.Adapters[1]) { device = Collect(new Device(adapter, FeatureLevel.Level_11_0)); } #endif commandQueue = Collect(device.CreateCommandQueue(new CommandQueueDescription(CommandListType.Direct))); CreateSwapChain(ref swapChainDescription1, factory); } // create command queue and allocator objects commandListAllocator = Collect(device.CreateCommandAllocator(CommandListType.Direct)); }
public CommandAllocator RequestCommandAllocator() { CommandAllocator newCommandAllocator = null; if (m_AvailableAllocators.Count > 0) { // when there are available allocators newCommandAllocator = m_AvailableAllocators.Dequeue(); } // if there is no available allocator, create new allocator if (newCommandAllocator == null) { switch (m_Type) { case H1CommandListType.Direct: newCommandAllocator = m_DeviceRef.CreateCommandAllocator(CommandListType.Direct); break; case H1CommandListType.Compute: newCommandAllocator = m_DeviceRef.CreateCommandAllocator(CommandListType.Compute); break; case H1CommandListType.Copy: newCommandAllocator = m_DeviceRef.CreateCommandAllocator(CommandListType.Copy); break; case H1CommandListType.Bundle: newCommandAllocator = m_DeviceRef.CreateCommandAllocator(CommandListType.Bundle); break; } // add new allocator to the pool m_AllocatorPool.Add(newCommandAllocator); } return(newCommandAllocator); }
public Boolean ReleaseCommandAllocator(CommandAllocator commandAllocator) { // check if the current command allocator is exists in the pool Boolean bExist = false; foreach (CommandAllocator allocator in m_AllocatorPool) { if (allocator == commandAllocator) { bExist = true; break; } } if (bExist == false) // if the allocator doesn't exists in the pool, return false { return(false); } // the current command allocator push to the available queue m_AvailableAllocators.Enqueue(commandAllocator); return(true); }
//创建设备 private void LoadPipeline(SharpDX.Windows.RenderForm form) { width = form.ClientSize.Width; height = form.ClientSize.Height; //创建视口 viewPort = new ViewportF(0, 0, width, height); //创建裁剪矩形 scissorRectangle = new Rectangle(0, 0, width, height); #if DEBUG //启用调试层 { DebugInterface.Get().EnableDebugLayer(); } #endif device = new Device(null, SharpDX.Direct3D.FeatureLevel.Level_11_0); //工厂化 using (var factory = new Factory4()) { //创建命令队列 CommandQueueDescription queueDesc = new CommandQueueDescription(CommandListType.Direct); commandQueue = device.CreateCommandQueue(queueDesc); //创建交换链 SwapChainDescription swapChainDesc = new SwapChainDescription() { BufferCount = FrameCount, ModeDescription = new ModeDescription( width, height, //缓存大小,一般与窗口大小相同 new Rational(60, 1), //刷新率,60hz Format.R8G8B8A8_UNorm), //像素格式,8位RGBA格式 Usage = Usage.RenderTargetOutput, //CPU访问缓冲权限 SwapEffect = SwapEffect.FlipDiscard, //描述处理曲面后的缓冲区内容 OutputHandle = form.Handle, //获取渲染窗口句柄 Flags = SwapChainFlags.None, //描述交换链的行为 SampleDescription = new SampleDescription(1, 0), //一重采样 IsWindowed = true //true为窗口显示,false为全屏显示 }; //创建交换链 SwapChain tempSwapChain = new SwapChain(factory, commandQueue, swapChainDesc); swapChain = tempSwapChain.QueryInterface <SwapChain3>(); tempSwapChain.Dispose(); frameIndex = swapChain.CurrentBackBufferIndex;//获取交换链的当前缓冲区的索引 } //创建描述符堆 //创建一个渲染目标视图(RTV)的描述符堆 DescriptorHeapDescription rtvHeapDesc = new DescriptorHeapDescription() { DescriptorCount = FrameCount, //堆中的描述符数 Flags = DescriptorHeapFlags.None, //结果值指定符堆,None表示堆的默认用法 Type = DescriptorHeapType.RenderTargetView //堆中的描述符类型 }; renderTargetViewHeap = device.CreateDescriptorHeap(rtvHeapDesc); //获取给定类型的描述符堆的句柄增量的大小,将句柄按正确的数量递增到描述符数组中 rtvDescriptorSize = device.GetDescriptorHandleIncrementSize(DescriptorHeapType.RenderTargetView); //创建一个CBV的描述符堆 var cbvHeapDesc = new DescriptorHeapDescription() { DescriptorCount = 1, Flags = DescriptorHeapFlags.ShaderVisible, Type = DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView }; constantBufferViewHeap = device.CreateDescriptorHeap(cbvHeapDesc); //创建一个SRV的描述符堆 var srvHeapDesc = new DescriptorHeapDescription() { DescriptorCount = 1, Flags = DescriptorHeapFlags.ShaderVisible, Type = DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView }; shaderRenderViewHeap = device.CreateDescriptorHeap(srvHeapDesc); srvDescriptorSize = device.GetDescriptorHandleIncrementSize(DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView); //构建资源描述符来填充描述符堆 //获取指向描述符堆起始处的指针 CpuDescriptorHandle srvHandle = shaderRenderViewHeap.CPUDescriptorHandleForHeapStart; //创建渲染目标视图 //获取堆中起始的CPU描述符句柄,for循环为交换链中的每一个缓冲区都创建了一个RTV(渲染目标视图) CpuDescriptorHandle rtvHandle = renderTargetViewHeap.CPUDescriptorHandleForHeapStart; for (int n = 0; n < FrameCount; n++) { //获得交换链的第n个缓冲区 renderTargets[n] = swapChain.GetBackBuffer <Resource>(n); device.CreateRenderTargetView( renderTargets[n], //指向渲染目标对象的指针 null, //指向描述渲染目标视图结构的指针 rtvHandle); //CPU描述符句柄,表示渲染目标视图的堆的开始 rtvHandle += rtvDescriptorSize; } //创建命令分配器对象 commandAllocator = device.CreateCommandAllocator(CommandListType.Direct); bundleAllocator = device.CreateCommandAllocator(CommandListType.Bundle); }
protected override void Draw(GameTimer gt) { CommandAllocator cmdListAlloc = CurrFrameResource.CmdListAlloc; // Reuse the memory associated with command recording. // We can only reset when the associated command lists have finished execution on the GPU. cmdListAlloc.Reset(); // A command list can be reset after it has been added to the command queue via ExecuteCommandList. // Reusing the command list reuses memory. CommandList.Reset(cmdListAlloc, _psos["opaque"]); CommandList.SetViewport(Viewport); CommandList.SetScissorRectangles(ScissorRectangle); // Indicate a state transition on the resource usage. CommandList.ResourceBarrierTransition(CurrentBackBuffer, ResourceStates.Present, ResourceStates.RenderTarget); // Clear the back buffer and depth buffer. CommandList.ClearRenderTargetView(CurrentBackBufferView, Color.LightSteelBlue); CommandList.ClearDepthStencilView(DepthStencilView, ClearFlags.FlagsDepth | ClearFlags.FlagsStencil, 1.0f, 0); // Specify the buffers we are going to render to. CommandList.SetRenderTargets(CurrentBackBufferView, DepthStencilView); CommandList.SetDescriptorHeaps(_descriptorHeaps.Length, _descriptorHeaps); CommandList.SetGraphicsRootSignature(_rootSignature); Resource passCB = CurrFrameResource.PassCB.Resource; CommandList.SetGraphicsRootConstantBufferView(1, passCB.GPUVirtualAddress); // Bind all the materials used in this scene. For structured buffers, we can bypass the heap and // set as a root descriptor. Resource matBuffer = CurrFrameResource.MaterialBuffer.Resource; CommandList.SetGraphicsRootShaderResourceView(2, matBuffer.GPUVirtualAddress); // Bind the sky cube map. For our demos, we just use one "world" cube map representing the environment // from far away, so all objects will use the same cube map and we only need to set it once per-frame. // If we wanted to use "local" cube maps, we would have to change them per-object, or dynamically // index into an array of cube maps. GpuDescriptorHandle skyTexDescriptor = _srvDescriptorHeap.GPUDescriptorHandleForHeapStart; skyTexDescriptor += _skyTexHeapIndex * CbvSrvUavDescriptorSize; CommandList.SetGraphicsRootDescriptorTable(3, skyTexDescriptor); // Bind all the textures used in this scene. Observe // that we only have to specify the first descriptor in the table. // The root signature knows how many descriptors are expected in the table. CommandList.SetGraphicsRootDescriptorTable(4, _srvDescriptorHeap.GPUDescriptorHandleForHeapStart); DrawRenderItems(CommandList, _ritemLayers[RenderLayer.Opaque]); CommandList.PipelineState = _psos["sky"]; DrawRenderItems(CommandList, _ritemLayers[RenderLayer.Sky]); // Indicate a state transition on the resource usage. CommandList.ResourceBarrierTransition(CurrentBackBuffer, ResourceStates.RenderTarget, ResourceStates.Present); // Done recording commands. CommandList.Close(); // Add the command list to the queue for execution. CommandQueue.ExecuteCommandList(CommandList); // Present the buffer to the screen. Presenting will automatically swap the back and front buffers. SwapChain.Present(0, PresentFlags.None); // Advance the fence value to mark commands up to this fence point. CurrFrameResource.Fence = ++CurrentFence; // Add an instruction to the command queue to set a new fence point. // Because we are on the GPU timeline, the new fence point won't be // set until the GPU finishes processing all the commands prior to this Signal(). CommandQueue.Signal(Fence, CurrentFence); }
private void LoadPipeline(RenderForm form) { int width = form.ClientSize.Width; int height = form.ClientSize.Height; #if DEBUG // Enable the D3D12 debug layer. { DebugInterface.Get().EnableDebugLayer(); } #endif device = new Device(null, SharpDX.Direct3D.FeatureLevel.Level_11_0); using (var factory = new Factory4()) { // Describe and create the command queue. CommandQueueDescription queueDesc = new CommandQueueDescription(CommandListType.Direct); commandQueue = device.CreateCommandQueue(queueDesc); // Describe and create the swap chain. SwapChainDescription swapChainDesc = new SwapChainDescription() { BufferCount = FrameCount, ModeDescription = new ModeDescription(width, height, new Rational(60, 1), Format.R8G8B8A8_UNorm), Usage = Usage.RenderTargetOutput, SwapEffect = SwapEffect.FlipDiscard, OutputHandle = form.Handle, //Flags = SwapChainFlags.None, SampleDescription = new SampleDescription(1, 0), IsWindowed = true }; SwapChain tempSwapChain = new SwapChain(factory, commandQueue, swapChainDesc); swapChain = tempSwapChain.QueryInterface<SwapChain3>(); tempSwapChain.Dispose(); frameIndex = swapChain.CurrentBackBufferIndex; } // Create descriptor heaps. // Describe and create a render target view (RTV) descriptor heap. renderTargetViewHeap = device.CreateDescriptorHeap(new DescriptorHeapDescription() { DescriptorCount = FrameCount, Flags = DescriptorHeapFlags.None, Type = DescriptorHeapType.RenderTargetView }); rtvDescriptorSize = device.GetDescriptorHandleIncrementSize(DescriptorHeapType.RenderTargetView); //create depth buffer; depthStencilViewHeap = device.CreateDescriptorHeap(new DescriptorHeapDescription() { DescriptorCount = FrameCount, Flags = DescriptorHeapFlags.None, Type = DescriptorHeapType.DepthStencilView }); //constant buffer view heap constantBufferViewHeap = device.CreateDescriptorHeap(new DescriptorHeapDescription() { DescriptorCount = 100, Type = DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView, Flags = DescriptorHeapFlags.ShaderVisible }); //Create targets CreateTargets(width, height); //sampler buffer view heap samplerViewHeap = device.CreateDescriptorHeap(new DescriptorHeapDescription() { DescriptorCount = 10, Type = DescriptorHeapType.Sampler, Flags = DescriptorHeapFlags.ShaderVisible }); //bind sampler device.CreateSampler(new SamplerStateDescription() { Filter = Filter.ComparisonMinMagMipLinear, AddressU = TextureAddressMode.Wrap, AddressV = TextureAddressMode.Wrap, AddressW = TextureAddressMode.Wrap, MinimumLod = float.MinValue, MaximumLod = float.MaxValue, MipLodBias = 0, MaximumAnisotropy = 0, ComparisonFunction = Comparison.Never }, samplerViewHeap.CPUDescriptorHandleForHeapStart); commandAllocator = device.CreateCommandAllocator(CommandListType.Direct); bundleAllocator = device.CreateCommandAllocator(CommandListType.Bundle); form.UserResized += (sender, e) => { isResizing = true; }; }
private void LoadPipeline(RenderForm form) { int width = form.ClientSize.Width; int height = form.ClientSize.Height; viewport.Width = width; viewport.Height = height; viewport.MaxDepth = 1.0f; scissorRect.Right = width; scissorRect.Bottom = height; #if DEBUG // Enable the D3D12 debug layer. { DebugInterface.Get().EnableDebugLayer(); } #endif device = new Device(null, SharpDX.Direct3D.FeatureLevel.Level_11_0); using (var factory = new Factory4()) { // Describe and create the command queue. CommandQueueDescription queueDesc = new CommandQueueDescription(CommandListType.Direct); commandQueue = device.CreateCommandQueue(queueDesc); // Describe and create the swap chain. SwapChainDescription swapChainDesc = new SwapChainDescription() { BufferCount = FrameCount, ModeDescription = new ModeDescription(width, height, new Rational(60, 1), Format.R8G8B8A8_UNorm), Usage = Usage.RenderTargetOutput, SwapEffect = SwapEffect.FlipDiscard, OutputHandle = form.Handle, //Flags = SwapChainFlags.None, SampleDescription = new SampleDescription(1, 0), IsWindowed = true }; SwapChain tempSwapChain = new SwapChain(factory, commandQueue, swapChainDesc); swapChain = tempSwapChain.QueryInterface<SwapChain3>(); tempSwapChain.Dispose(); frameIndex = swapChain.CurrentBackBufferIndex; } // Create descriptor heaps. // Describe and create a render target view (RTV) descriptor heap. DescriptorHeapDescription rtvHeapDesc = new DescriptorHeapDescription() { DescriptorCount = FrameCount, Flags = DescriptorHeapFlags.None, Type = DescriptorHeapType.RenderTargetView }; renderTargetViewHeap = device.CreateDescriptorHeap(rtvHeapDesc); rtvDescriptorSize = device.GetDescriptorHandleIncrementSize(DescriptorHeapType.RenderTargetView); // Create frame resources. CpuDescriptorHandle rtvHandle = renderTargetViewHeap.CPUDescriptorHandleForHeapStart; for (int n = 0; n < FrameCount; n++) { renderTargets[n] = swapChain.GetBackBuffer<Resource>(n); device.CreateRenderTargetView(renderTargets[n], null, rtvHandle); rtvHandle += rtvDescriptorSize; } //create depth buffer; DescriptorHeapDescription dsvHeapDesc = new DescriptorHeapDescription() { DescriptorCount = FrameCount, Flags = DescriptorHeapFlags.None, Type = DescriptorHeapType.DepthStencilView }; depthStencilViewHeap = device.CreateDescriptorHeap(dsvHeapDesc); CpuDescriptorHandle dsvHandle = depthStencilViewHeap.CPUDescriptorHandleForHeapStart; ClearValue depthOptimizedClearValue = new ClearValue() { Format = Format.D32_Float, DepthStencil = new DepthStencilValue() { Depth = 1.0F, Stencil = 0 }, }; depthTarget = device.CreateCommittedResource( new HeapProperties(HeapType.Default), HeapFlags.None, new ResourceDescription(ResourceDimension.Texture2D, 0, width, height, 1, 0, Format.D32_Float, 1, 0, TextureLayout.Unknown, ResourceFlags.AllowDepthStencil), ResourceStates.DepthWrite, depthOptimizedClearValue); var depthView = new DepthStencilViewDescription() { Format = Format.D32_Float, Dimension = DepthStencilViewDimension.Texture2D, Flags = DepthStencilViewFlags.None, }; //bind depth buffer device.CreateDepthStencilView(depthTarget, null, dsvHandle); commandAllocator = device.CreateCommandAllocator(CommandListType.Direct); bundleAllocator = device.CreateCommandAllocator(CommandListType.Bundle); }
protected override void Draw(GameTimer gt) { CommandAllocator cmdListAlloc = CurrFrameResource.CmdListAlloc; // Reuse the memory associated with command recording. // We can only reset when the associated command lists have finished execution on the GPU. cmdListAlloc.Reset(); // A command list can be reset after it has been added to the command queue via ExecuteCommandList. // Reusing the command list reuses memory. CommandList.Reset(cmdListAlloc, _psos["opaque"]); CommandList.SetViewport(Viewport); CommandList.SetScissorRectangles(ScissorRectangle); // Indicate a state transition on the resource usage. CommandList.ResourceBarrierTransition(CurrentBackBuffer, ResourceStates.Present, ResourceStates.RenderTarget); // Clear the back buffer and depth buffer. CommandList.ClearRenderTargetView(CurrentBackBufferView, new Color(_mainPassCB.FogColor)); CommandList.ClearDepthStencilView(DepthStencilView, ClearFlags.FlagsDepth | ClearFlags.FlagsStencil, 1.0f, 0); // Specify the buffers we are going to render to. CommandList.SetRenderTargets(CurrentBackBufferView, DepthStencilView); CommandList.SetDescriptorHeaps(_descriptorHeaps.Length, _descriptorHeaps); CommandList.SetGraphicsRootSignature(_rootSignature); // Bind per-pass constant buffer. We only need to do this once per-pass. Resource passCB = CurrFrameResource.PassCB.Resource; CommandList.SetGraphicsRootConstantBufferView(2, passCB.GPUVirtualAddress); DrawRenderItems(CommandList, _ritemLayers[RenderLayer.Opaque]); CommandList.PipelineState = _psos["alphaTested"]; DrawRenderItems(CommandList, _ritemLayers[RenderLayer.AlphaTested]); CommandList.PipelineState = _psos["transparent"]; DrawRenderItems(CommandList, _ritemLayers[RenderLayer.Transparent]); _blurFilter.Execute(CommandList, _postProcessRootSignature, _psos["horzBlur"], _psos["vertBlur"], CurrentBackBuffer, 4); // Prepare to copy blurred output to the back buffer. CommandList.ResourceBarrierTransition(CurrentBackBuffer, ResourceStates.CopySource, ResourceStates.CopyDestination); CommandList.CopyResource(CurrentBackBuffer, _blurFilter.Output); // Transition to PRESENT state. CommandList.ResourceBarrierTransition(CurrentBackBuffer, ResourceStates.CopyDestination, ResourceStates.Present); // Done recording commands. CommandList.Close(); // Add the command list to the queue for execution. CommandQueue.ExecuteCommandList(CommandList); // Present the buffer to the screen. Presenting will automatically swap the back and front buffers. SwapChain.Present(0, PresentFlags.None); // Advance the fence value to mark commands up to this fence point. CurrFrameResource.Fence = ++CurrentFence; // Add an instruction to the command queue to set a new fence point. // Because we are on the GPU timeline, the new fence point won't be // set until the GPU finishes processing all the commands prior to this Signal(). CommandQueue.Signal(Fence, CurrentFence); }
private void LoadPipeline(RenderForm form) { int width = form.ClientSize.Width; int height = form.ClientSize.Height; viewport.Width = width; viewport.Height = height; viewport.MaxDepth = 1.0f; scissorRect.Right = width; scissorRect.Bottom = height; device = new Device(null, SharpDX.Direct3D.FeatureLevel.Level_11_0); using (var factory = new Factory4()) { var queueDesc = new CommandQueueDescription(CommandListType.Direct); commandQueue = device.CreateCommandQueue(queueDesc); var swapChainDesc = new SwapChainDescription() { BufferCount = FrameCount, ModeDescription = new ModeDescription(width, height, new Rational(60, 1), Format.R8G8B8A8_UNorm), Usage = Usage.RenderTargetOutput, SwapEffect = SwapEffect.FlipDiscard, OutputHandle = form.Handle, SampleDescription = new SampleDescription(1, 0), IsWindowed = true }; var tempSwapChain = new SwapChain(factory, commandQueue, swapChainDesc); swapChain = tempSwapChain.QueryInterface<SwapChain3>(); frameIndex = swapChain.CurrentBackBufferIndex; } var rtvHeapDesc = new DescriptorHeapDescription() { DescriptorCount = FrameCount, Flags = DescriptorHeapFlags.None, Type = DescriptorHeapType.RenderTargetView }; renderTargetViewHeap = device.CreateDescriptorHeap(rtvHeapDesc); rtvDescriptorSize = device.GetDescriptorHandleIncrementSize(DescriptorHeapType.RenderTargetView); var srvHeapDesc = new DescriptorHeapDescription() { DescriptorCount = 200, Flags = DescriptorHeapFlags.ShaderVisible, Type = DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView }; shaderRenderViewHeap = device.CreateDescriptorHeap(srvHeapDesc); var terrainHeapDesc = new DescriptorHeapDescription() { DescriptorCount = 2, Flags = DescriptorHeapFlags.ShaderVisible, Type = DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView }; terrainHeap = device.CreateDescriptorHeap(terrainHeapDesc); var meshCtrCbvDesc = new DescriptorHeapDescription() { DescriptorCount = 1, Flags = DescriptorHeapFlags.ShaderVisible, Type = DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView }; meshCtrBufferViewHeap = device.CreateDescriptorHeap(meshCtrCbvDesc); var rtcHandle = renderTargetViewHeap.CPUDescriptorHandleForHeapStart; for (int n = 0; n < FrameCount; n++) { renderTargets[n] = swapChain.GetBackBuffer<Resource>(n); device.CreateRenderTargetView(renderTargets[n], null, rtcHandle); rtcHandle += rtvDescriptorSize; } var svHeapDesc = new DescriptorHeapDescription() { Type = DescriptorHeapType.Sampler, DescriptorCount = 1, Flags = DescriptorHeapFlags.ShaderVisible, NodeMask = 0 }; samplerViewHeap = device.CreateDescriptorHeap(svHeapDesc); commandAllocator = device.CreateCommandAllocator(CommandListType.Direct); }
void loadDevice() { _resources = new GraphicsResource[0]; _viewport.Width = WIDTH; _viewport.Height = HEIGHT; _viewport.MaxDepth = 1.0f; _scissorRect.Right = WIDTH; _scissorRect.Bottom = HEIGHT; #if DEBUG // Enable the D3D12 debug layer. { DebugInterface.Get().EnableDebugLayer(); } #endif using (var factory = new Factory4()) { _device = new Device(factory.GetAdapter(_adapterIndex), SharpDX.Direct3D.FeatureLevel.Level_12_1).QueryInterface <Device3>(); // Describe and create the command queue. CommandQueueDescription queueDesc = new CommandQueueDescription(CommandListType.Direct); _graphicsQueue = _device.CreateCommandQueue(queueDesc); // Describe and create the swap chain. SwapChainDescription swapChainDesc = new SwapChainDescription() { BufferCount = FRAME_COUNT, ModeDescription = new ModeDescription(WIDTH, HEIGHT, new Rational(60, 1), Format.R8G8B8A8_UNorm), Usage = Usage.RenderTargetOutput, SwapEffect = SwapEffect.FlipDiscard, OutputHandle = _window.Handle, Flags = SwapChainFlags.AllowModeSwitch, SampleDescription = new SampleDescription(1, 0), IsWindowed = true }; SwapChain tempSwapChain = new SwapChain(factory, _graphicsQueue, swapChainDesc); _swapChain = tempSwapChain.QueryInterface <SwapChain3>(); tempSwapChain.Dispose(); _frameIndex = _swapChain.CurrentBackBufferIndex; } // Create descriptor heaps. // Describe and create a render target view (RTV) descriptor heap. DescriptorHeapDescription rtvHeapDesc = new DescriptorHeapDescription() { DescriptorCount = FRAME_COUNT, Flags = DescriptorHeapFlags.None, Type = DescriptorHeapType.RenderTargetView }; _renderTargetViewHeap = _device.CreateDescriptorHeap(rtvHeapDesc); DescriptorHeapDescription _dsvHeapDescription = new DescriptorHeapDescription() { DescriptorCount = 1, Flags = DescriptorHeapFlags.None, NodeMask = 0, Type = DescriptorHeapType.DepthStencilView }; _depthStencilView = _device.CreateDescriptorHeap(_dsvHeapDescription); _rtvDescriptorSize = _device.GetDescriptorHandleIncrementSize(DescriptorHeapType.RenderTargetView); // Create frame resources. CpuDescriptorHandle rtvHandle = _renderTargetViewHeap.CPUDescriptorHandleForHeapStart; for (int n = 0; n < FRAME_COUNT; n++) { _renderTargets[n] = _swapChain.GetBackBuffer <Resource>(n); _device.CreateRenderTargetView(_renderTargets[n], null, rtvHandle); rtvHandle += _rtvDescriptorSize; } //Initialize Depth/Stencil Buffer _depthStencilDesc = new ResourceDescription(ResourceDimension.Texture2D, 0, _window.Width, _window.Height, 1, 1, Format.D24_UNorm_S8_UInt, 1, 0, TextureLayout.Unknown, ResourceFlags.AllowDepthStencil); _depthStencilClear = new ClearValue() { DepthStencil = new DepthStencilValue() { Depth = 1.0f, Stencil = 0 }, Format = Format.D24_UNorm_S8_UInt }; _depthStencilBuffer = _device.CreateCommittedResource(new HeapProperties(HeapType.Default), HeapFlags.None, _depthStencilDesc, ResourceStates.Common, _depthStencilClear); //Create Descriptor to mip level 0 of the entire resource using format of the resouce _device.CreateDepthStencilView(_depthStencilBuffer, null, DepthStencilHandle); _commandAllocator = _device.CreateCommandAllocator(CommandListType.Direct); _bundleCommandAllocator = _device.CreateCommandAllocator(CommandListType.Bundle); // Create the command list. _commandList = _device.CreateCommandList(CommandListType.Direct, _commandAllocator, null); _bundleCommandList = _device.CreateCommandList(CommandListType.Bundle, _bundleCommandAllocator, null); _commandList.ResourceBarrier(new ResourceBarrier(new ResourceTransitionBarrier(_depthStencilBuffer, ResourceStates.Common, ResourceStates.DepthWrite))); // Command lists are created in the recording state, but there is nothing // to record yet. The main loop expects it to be closed, so close it now. _bundleCommandList.Close(); }
/// <summary> /// Initializes the specified device. /// </summary> /// <param name="graphicsProfiles">The graphics profiles.</param> /// <param name="deviceCreationFlags">The device creation flags.</param> /// <param name="windowHandle">The window handle.</param> private void InitializePlatformDevice(GraphicsProfile[] graphicsProfiles, DeviceCreationFlags deviceCreationFlags, object windowHandle) { if (nativeDevice != null) { // Destroy previous device ReleaseDevice(); } rendererName = Adapter.NativeAdapter.Description.Description; // Profiling is supported through pix markers IsProfilingSupported = true; if ((deviceCreationFlags & DeviceCreationFlags.Debug) != 0) { SharpDX.Direct3D12.DebugInterface.Get().EnableDebugLayer(); } // Default fallback if (graphicsProfiles.Length == 0) { graphicsProfiles = new[] { GraphicsProfile.Level_11_0 } } ; // Create Device D3D12 with feature Level based on profile for (int index = 0; index < graphicsProfiles.Length; index++) { var graphicsProfile = graphicsProfiles[index]; try { // D3D12 supports only feature level 11+ var level = graphicsProfile.ToFeatureLevel(); if (level < SharpDX.Direct3D.FeatureLevel.Level_11_0) { level = SharpDX.Direct3D.FeatureLevel.Level_11_0; } nativeDevice = new SharpDX.Direct3D12.Device(Adapter.NativeAdapter, level); RequestedProfile = graphicsProfile; CurrentFeatureLevel = level; break; } catch (Exception) { if (index == graphicsProfiles.Length - 1) { throw; } } } // Describe and create the command queue. var queueDesc = new SharpDX.Direct3D12.CommandQueueDescription(SharpDX.Direct3D12.CommandListType.Direct); NativeCommandQueue = nativeDevice.CreateCommandQueue(queueDesc); //queueDesc.Type = CommandListType.Copy; NativeCopyCommandQueue = nativeDevice.CreateCommandQueue(queueDesc); SrvHandleIncrementSize = NativeDevice.GetDescriptorHandleIncrementSize(DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView); SamplerHandleIncrementSize = NativeDevice.GetDescriptorHandleIncrementSize(DescriptorHeapType.Sampler); // Prepare pools CommandAllocators = new CommandAllocatorPool(this); SrvHeaps = new HeapPool(this, SrvHeapSize, DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView); SamplerHeaps = new HeapPool(this, SamplerHeapSize, DescriptorHeapType.Sampler); // Prepare descriptor allocators SamplerAllocator = new DescriptorAllocator(this, DescriptorHeapType.Sampler); ShaderResourceViewAllocator = new DescriptorAllocator(this, DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView); DepthStencilViewAllocator = new DescriptorAllocator(this, DescriptorHeapType.DepthStencilView); RenderTargetViewAllocator = new DescriptorAllocator(this, DescriptorHeapType.RenderTargetView); // Prepare copy command list (start it closed, so that every new use start with a Reset) NativeCopyCommandAllocator = NativeDevice.CreateCommandAllocator(CommandListType.Direct); NativeCopyCommandList = NativeDevice.CreateCommandList(CommandListType.Direct, NativeCopyCommandAllocator, null); NativeCopyCommandList.Close(); // Fence for next frame and resource cleaning nativeFence = NativeDevice.CreateFence(0, FenceFlags.None); nativeCopyFence = NativeDevice.CreateFence(0, FenceFlags.None); }
protected override void Draw(GameTimer gt) { CommandAllocator cmdListAlloc = CurrFrameResource.CmdListAlloc; // Reuse the memory associated with command recording. // We can only reset when the associated command lists have finished execution on the GPU. cmdListAlloc.Reset(); // A command list can be reset after it has been added to the command queue via ExecuteCommandList. // Reusing the command list reuses memory. CommandList.Reset(cmdListAlloc, _psos["opaque"]); CommandList.SetDescriptorHeaps(_descriptorHeaps.Length, _descriptorHeaps); UpdateWavesGPU(gt); CommandList.PipelineState = _psos["opaque"]; CommandList.SetViewport(Viewport); CommandList.SetScissorRectangles(ScissorRectangle); // Change offscreen texture to be used as a a render target output. CommandList.ResourceBarrierTransition(_offscreenRT.Resource, ResourceStates.GenericRead, ResourceStates.RenderTarget); // Clear the back buffer and depth buffer. CommandList.ClearRenderTargetView(_offscreenRT.Rtv, new Color(_mainPassCB.FogColor)); CommandList.ClearDepthStencilView(DepthStencilView, ClearFlags.FlagsDepth | ClearFlags.FlagsStencil, 1.0f, 0); // Specify the buffers we are going to render to. CommandList.SetRenderTargets(_offscreenRT.Rtv, DepthStencilView); CommandList.SetGraphicsRootSignature(_rootSignature); Resource passCB = CurrFrameResource.PassCB.Resource; CommandList.SetGraphicsRootConstantBufferView(2, passCB.GPUVirtualAddress); CommandList.SetGraphicsRootDescriptorTable(4, _waves.DisplacementMap); DrawRenderItems(CommandList, _ritemLayers[RenderLayer.Opaque]); CommandList.PipelineState = _psos["alphaTested"]; DrawRenderItems(CommandList, _ritemLayers[RenderLayer.AlphaTested]); CommandList.PipelineState = _psos["transparent"]; DrawRenderItems(CommandList, _ritemLayers[RenderLayer.Transparent]); CommandList.PipelineState = _psos["wavesRender"]; DrawRenderItems(CommandList, _ritemLayers[RenderLayer.GpuWaves]); // Change offscreen texture to be used as an input. CommandList.ResourceBarrierTransition(_offscreenRT.Resource, ResourceStates.RenderTarget, ResourceStates.GenericRead); _sobelFilter.Execute(CommandList, _postProcessRootSignature, _psos["sobel"], _offscreenRT.Srv); // // Switching back to back buffer rendering. // // Indicate a state transition on the resource usage. CommandList.ResourceBarrierTransition(CurrentBackBuffer, ResourceStates.Present, ResourceStates.RenderTarget); // Specify the buffers we are going to render to. CommandList.SetRenderTargets(CurrentBackBufferView, DepthStencilView); CommandList.SetGraphicsRootSignature(_postProcessRootSignature); CommandList.PipelineState = _psos["composite"]; CommandList.SetGraphicsRootDescriptorTable(0, _offscreenRT.Srv); CommandList.SetGraphicsRootDescriptorTable(1, _sobelFilter.OutputSrv); DrawFullscreenQuad(CommandList); // Indicate a state transition on the resource usage. CommandList.ResourceBarrierTransition(CurrentBackBuffer, ResourceStates.RenderTarget, ResourceStates.Present); // Done recording commands. CommandList.Close(); // Add the command list to the queue for execution. CommandQueue.ExecuteCommandList(CommandList); // Present the buffer to the screen. Presenting will automatically swap the back and front buffers. SwapChain.Present(0, PresentFlags.None); // Advance the fence value to mark commands up to this fence point. CurrFrameResource.Fence = ++CurrentFence; // Add an instruction to the command queue to set a new fence point. // Because we are on the GPU timeline, the new fence point won't be // set until the GPU finishes processing all the commands prior to this Signal(). CommandQueue.Signal(Fence, CurrentFence); }
private void LoadPipeline(IntPtr handleToWindow) { // create swap chain descriptor var swapChainDescription = new SwapChainDescription() { BufferCount = SwapBufferCount, ModeDescription = new ModeDescription(Format.R8G8B8A8_UNorm), Usage = Usage.RenderTargetOutput, OutputHandle = handleToWindow, SwapEffect = SwapEffect.FlipDiscard, SampleDescription = new SampleDescription(1, 0), IsWindowed = true }; // create the device try { device = CreateDeviceWithSwapChain(DriverType.Hardware, FeatureLevel.Level_11_0, swapChainDescription, out swapChain, out commandQueue); } catch (SharpDXException) { device = CreateDeviceWithSwapChain(DriverType.Warp, FeatureLevel.Level_11_0, swapChainDescription, out swapChain, out commandQueue); } // create command queue and allocator objects commandListAllocator = device.CreateCommandAllocator(CommandListType.Direct); }
private void PlatformBegin() { _commandAllocator = _device.CreateCommandAllocator(CommandListType.Direct); _commandList = _device.CreateCommandList(CommandListType.Direct, _commandAllocator, null); }
public void Dispose() { if (Allocator != null) { Allocator.RemoveRef(); Allocator.Dispose(); Allocator = null; } }
private void LoadPipeline(RenderForm form) { int width = form.ClientSize.Width; int height = form.ClientSize.Height; viewport.Width = width; viewport.Height = height; viewport.MaxDepth = 1.0f; scissorRect.Right = width; scissorRect.Bottom = height; #if DEBUG // Enable the D3D12 debug layer. { DebugInterface.Get().EnableDebugLayer(); } #endif device = new Device(null, SharpDX.Direct3D.FeatureLevel.Level_12_0); using (var factory = new Factory4()) { // Describe and create the command queue. CommandQueueDescription queueDesc = new CommandQueueDescription(CommandListType.Direct); commandQueue = device.CreateCommandQueue(queueDesc); // Describe and create the swap chain. SwapChainDescription swapChainDesc = new SwapChainDescription() { BufferCount = FrameCount, ModeDescription = new ModeDescription(width, height, new Rational(60, 1), Format.R8G8B8A8_UNorm), Usage = Usage.RenderTargetOutput, SwapEffect = SwapEffect.FlipDiscard, OutputHandle = form.Handle, //Flags = SwapChainFlags.None, SampleDescription = new SampleDescription(1, 0), IsWindowed = true }; SwapChain tempSwapChain = new SwapChain(factory, commandQueue, swapChainDesc); swapChain = tempSwapChain.QueryInterface<SwapChain3>(); tempSwapChain.Dispose(); frameIndex = swapChain.CurrentBackBufferIndex; } // Create descriptor heaps. // Describe and create a render target view (RTV) descriptor heap. DescriptorHeapDescription rtvHeapDesc = new DescriptorHeapDescription() { DescriptorCount = FrameCount, Flags = DescriptorHeapFlags.None, Type = DescriptorHeapType.RenderTargetView }; renderTargetViewHeap = device.CreateDescriptorHeap(rtvHeapDesc); rtvDescriptorSize = device.GetDescriptorHandleIncrementSize(DescriptorHeapType.RenderTargetView); //Init Direct3D11 device from Direct3D12 device device11 = SharpDX.Direct3D11.Device.CreateFromDirect3D12(device, SharpDX.Direct3D11.DeviceCreationFlags.BgraSupport, null, null, commandQueue); deviceContext11 = device11.ImmediateContext; device11on12 = device11.QueryInterface<SharpDX.Direct3D11.ID3D11On12Device>(); var d2dFactory = new SharpDX.Direct2D1.Factory(SharpDX.Direct2D1.FactoryType.MultiThreaded); // Create frame resources. CpuDescriptorHandle rtvHandle = renderTargetViewHeap.CPUDescriptorHandleForHeapStart; for (int n = 0; n < FrameCount; n++) { renderTargets[n] = swapChain.GetBackBuffer<Resource>(n); device.CreateRenderTargetView(renderTargets[n], null, rtvHandle); rtvHandle += rtvDescriptorSize; //init Direct2D surfaces SharpDX.Direct3D11.D3D11ResourceFlags format = new SharpDX.Direct3D11.D3D11ResourceFlags() { BindFlags = (int)SharpDX.Direct3D11.BindFlags.RenderTarget, CPUAccessFlags = (int)SharpDX.Direct3D11.CpuAccessFlags.None }; device11on12.CreateWrappedResource( renderTargets[n], format, (int)ResourceStates.Present, (int)ResourceStates.RenderTarget, typeof(SharpDX.Direct3D11.Resource).GUID, out wrappedBackBuffers[n]); //Init direct2D surface var d2dSurface = wrappedBackBuffers[n].QueryInterface<Surface>(); direct2DRenderTarget[n] = new SharpDX.Direct2D1.RenderTarget(d2dFactory, d2dSurface, new SharpDX.Direct2D1.RenderTargetProperties(new SharpDX.Direct2D1.PixelFormat(Format.Unknown, SharpDX.Direct2D1.AlphaMode.Premultiplied))); d2dSurface.Dispose(); } commandAllocator = device.CreateCommandAllocator(CommandListType.Direct); d2dFactory.Dispose(); //Init font var directWriteFactory = new SharpDX.DirectWrite.Factory(); textFormat = new SharpDX.DirectWrite.TextFormat(directWriteFactory, "Arial", SharpDX.DirectWrite.FontWeight.Bold, SharpDX.DirectWrite.FontStyle.Normal, 48) { TextAlignment = SharpDX.DirectWrite.TextAlignment.Leading, ParagraphAlignment = SharpDX.DirectWrite.ParagraphAlignment.Near }; textBrush = new SharpDX.Direct2D1.SolidColorBrush(direct2DRenderTarget[0], Color.White); directWriteFactory.Dispose(); }
/// <summary> /// Initializes the specified device. /// </summary> /// <param name="graphicsProfiles">The graphics profiles.</param> /// <param name="deviceCreationFlags">The device creation flags.</param> /// <param name="windowHandle">The window handle.</param> private void InitializePlatformDevice(GraphicsProfile[] graphicsProfiles, DeviceCreationFlags deviceCreationFlags, object windowHandle) { if (nativeDevice != null) { // Destroy previous device ReleaseDevice(); } rendererName = Adapter.NativeAdapter.Description.Description; // Profiling is supported through pix markers IsProfilingSupported = true; // Command lists are thread-safe and execute deferred IsDeferred = true; bool isDebug = (deviceCreationFlags & DeviceCreationFlags.Debug) != 0; if (isDebug) { SharpDX.Direct3D12.DebugInterface.Get().EnableDebugLayer(); } // Create Device D3D12 with feature Level based on profile for (int index = 0; index < graphicsProfiles.Length; index++) { var graphicsProfile = graphicsProfiles[index]; try { // D3D12 supports only feature level 11+ var level = graphicsProfile.ToFeatureLevel(); if (level < SharpDX.Direct3D.FeatureLevel.Level_11_0) { level = SharpDX.Direct3D.FeatureLevel.Level_11_0; } nativeDevice = new SharpDX.Direct3D12.Device(Adapter.NativeAdapter, level); RequestedProfile = graphicsProfile; CurrentFeatureLevel = level; break; } catch (Exception) { if (index == graphicsProfiles.Length - 1) { throw; } } } // Describe and create the command queue. var queueDesc = new SharpDX.Direct3D12.CommandQueueDescription(SharpDX.Direct3D12.CommandListType.Direct); NativeCommandQueue = nativeDevice.CreateCommandQueue(queueDesc); //queueDesc.Type = CommandListType.Copy; NativeCopyCommandQueue = nativeDevice.CreateCommandQueue(queueDesc); TimestampFrequency = NativeCommandQueue.TimestampFrequency; SrvHandleIncrementSize = NativeDevice.GetDescriptorHandleIncrementSize(DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView); SamplerHandleIncrementSize = NativeDevice.GetDescriptorHandleIncrementSize(DescriptorHeapType.Sampler); if (isDebug) { var debugDevice = nativeDevice.QueryInterfaceOrNull <DebugDevice>(); if (debugDevice != null) { var infoQueue = debugDevice.QueryInterfaceOrNull <InfoQueue>(); if (infoQueue != null) { MessageId[] disabledMessages = { // This happens when render target or depth stencil clear value is diffrent // than provided during resource allocation. MessageId.CleardepthstencilviewMismatchingclearvalue, MessageId.ClearrendertargetviewMismatchingclearvalue, // This occurs when there are uninitialized descriptors in a descriptor table, // even when a shader does not access the missing descriptors. MessageId.InvalidDescriptorHandle, // These happen when capturing with VS diagnostics MessageId.MapInvalidNullRange, MessageId.UnmapInvalidNullRange, }; // Disable irrelevant debug layer warnings InfoQueueFilter filter = new InfoQueueFilter { DenyList = new InfoQueueFilterDescription { Ids = disabledMessages } }; infoQueue.AddStorageFilterEntries(filter); //infoQueue.SetBreakOnSeverity(MessageSeverity.Error, true); //infoQueue.SetBreakOnSeverity(MessageSeverity.Warning, true); infoQueue.Dispose(); } debugDevice.Dispose(); } } // Prepare pools CommandAllocators = new CommandAllocatorPool(this); SrvHeaps = new HeapPool(this, SrvHeapSize, DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView); SamplerHeaps = new HeapPool(this, SamplerHeapSize, DescriptorHeapType.Sampler); // Prepare descriptor allocators SamplerAllocator = new DescriptorAllocator(this, DescriptorHeapType.Sampler); ShaderResourceViewAllocator = new DescriptorAllocator(this, DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView); DepthStencilViewAllocator = new DescriptorAllocator(this, DescriptorHeapType.DepthStencilView); RenderTargetViewAllocator = new DescriptorAllocator(this, DescriptorHeapType.RenderTargetView); // Prepare copy command list (start it closed, so that every new use start with a Reset) NativeCopyCommandAllocator = NativeDevice.CreateCommandAllocator(CommandListType.Direct); NativeCopyCommandList = NativeDevice.CreateCommandList(CommandListType.Direct, NativeCopyCommandAllocator, null); NativeCopyCommandList.Close(); // Fence for next frame and resource cleaning nativeFence = NativeDevice.CreateFence(0, FenceFlags.None); nativeCopyFence = NativeDevice.CreateFence(0, FenceFlags.None); }
private void LoadPipeline(RenderForm form) { int width = form.ClientSize.Width; int height = form.ClientSize.Height; viewport.Width = width; viewport.Height = height; viewport.MaxDepth = 1.0f; scissorRect.Right = width; scissorRect.Bottom = height; device = new Device(null, SharpDX.Direct3D.FeatureLevel.Level_11_0); using (var factory = new Factory4()) { var queueDesc = new CommandQueueDescription(CommandListType.Direct); commandQueue = device.CreateCommandQueue(queueDesc); var swapChainDesc = new SwapChainDescription() { BufferCount = FrameCount, ModeDescription = new ModeDescription(width, height, new Rational(60, 1), Format.R8G8B8A8_UNorm), Usage = Usage.RenderTargetOutput, SwapEffect = SwapEffect.FlipDiscard, OutputHandle = form.Handle, SampleDescription = new SampleDescription(1, 0), IsWindowed = true }; var tempSwapChain = new SwapChain(factory, commandQueue, swapChainDesc); swapChain = tempSwapChain.QueryInterface <SwapChain3>(); frameIndex = swapChain.CurrentBackBufferIndex; } var rtvHeapDesc = new DescriptorHeapDescription() { DescriptorCount = FrameCount, Flags = DescriptorHeapFlags.None, Type = DescriptorHeapType.RenderTargetView }; renderTargetViewHeap = device.CreateDescriptorHeap(rtvHeapDesc); rtvDescriptorSize = device.GetDescriptorHandleIncrementSize(DescriptorHeapType.RenderTargetView); var srvCbvHeapDesc = new DescriptorHeapDescription() { DescriptorCount = 1, Flags = DescriptorHeapFlags.ShaderVisible, Type = DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView }; srvCbvHeap = device.CreateDescriptorHeap(srvCbvHeapDesc); var rtcHandle = renderTargetViewHeap.CPUDescriptorHandleForHeapStart; for (int n = 0; n < FrameCount; n++) { renderTargets[n] = swapChain.GetBackBuffer <Resource>(n); device.CreateRenderTargetView(renderTargets[n], null, rtcHandle); rtcHandle += rtvDescriptorSize; } var svHeapDesc = new DescriptorHeapDescription() { Type = DescriptorHeapType.Sampler, DescriptorCount = 10, Flags = DescriptorHeapFlags.ShaderVisible, NodeMask = 0 }; samplerViewHeap = device.CreateDescriptorHeap(svHeapDesc); commandAllocator = device.CreateCommandAllocator(CommandListType.Direct); }
private void LoadPipeline(RenderForm form) { int width = form.ClientSize.Width; int height = form.ClientSize.Height; viewport.Width = width; viewport.Height = height; viewport.MaxDepth = 1.0f; scissorRect.Right = width; scissorRect.Bottom = height; #if DEBUG // Enable the D3D12 debug layer. { DebugInterface.Get().EnableDebugLayer(); } #endif device = new Device(null, SharpDX.Direct3D.FeatureLevel.Level_11_0); using (var factory = new Factory4()) { // Describe and create the command queue. CommandQueueDescription queueDesc = new CommandQueueDescription(CommandListType.Direct); commandQueue = device.CreateCommandQueue(queueDesc); // Describe and create the swap chain. SwapChainDescription swapChainDesc = new SwapChainDescription() { BufferCount = FrameCount, ModeDescription = new ModeDescription(width, height, new Rational(60, 1), Format.R8G8B8A8_UNorm), Usage = Usage.RenderTargetOutput, SwapEffect = SwapEffect.FlipDiscard, OutputHandle = form.Handle, //Flags = SwapChainFlags.None, SampleDescription = new SampleDescription(1, 0), IsWindowed = true }; SwapChain tempSwapChain = new SwapChain(factory, commandQueue, swapChainDesc); swapChain = tempSwapChain.QueryInterface<SwapChain3>(); tempSwapChain.Dispose(); frameIndex = swapChain.CurrentBackBufferIndex; } // Create descriptor heaps. // Describe and create a render target view (RTV) descriptor heap. DescriptorHeapDescription rtvHeapDesc = new DescriptorHeapDescription() { DescriptorCount = FrameCount, Flags = DescriptorHeapFlags.None, Type = DescriptorHeapType.RenderTargetView }; renderTargetViewHeap = device.CreateDescriptorHeap(rtvHeapDesc); DescriptorHeapDescription srvHeapDesc = new DescriptorHeapDescription() { DescriptorCount = 1, Flags = DescriptorHeapFlags.ShaderVisible, Type = DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView }; shaderRenderViewHeap = device.CreateDescriptorHeap(srvHeapDesc); rtvDescriptorSize = device.GetDescriptorHandleIncrementSize(DescriptorHeapType.RenderTargetView); // Create frame resources. CpuDescriptorHandle rtvHandle = renderTargetViewHeap.CPUDescriptorHandleForHeapStart; for (int n = 0; n < FrameCount; n++) { renderTargets[n] = swapChain.GetBackBuffer<Resource>(n); device.CreateRenderTargetView(renderTargets[n], null, rtvHandle); rtvHandle += rtvDescriptorSize; } commandAllocator = device.CreateCommandAllocator(CommandListType.Direct); }
/// <summary> /// Creates a CommandAllocator. Usually not needed, since this is done by the CommandListAllocaionPolicy. /// </summary> public abstract CommandAllocator Create(ref CommandAllocator.Descriptor desc, string label = "<unnamed commandAllocator>");