using System.Diagnostics; using System.Runtime.CompilerServices; using System.Threading; using ComputeSharp.Core.Extensions; using ComputeSharp.Graphics.Commands; using ComputeSharp.Graphics.Commands.Interop; using ComputeSharp.Graphics.Extensions; using ComputeSharp.Graphics.Helpers; using ComputeSharp.Interop; using Microsoft.Toolkit.Diagnostics; using TerraFX.Interop.DirectX; using TerraFX.Interop.Windows; using static TerraFX.Interop.DirectX.D3D12_COMMAND_LIST_TYPE; using static TerraFX.Interop.DirectX.D3D12_FEATURE; using static TerraFX.Interop.DirectX.D3D12_FORMAT_SUPPORT1; using static TerraFX.Interop.DirectX.DXGI_ADAPTER_FLAG; namespace ComputeSharp; /// /// A that represents an instance that can be used to run compute shaders. /// [DebuggerDisplay("{ToString(),raw}")] public sealed unsafe partial class GraphicsDevice : NativeObject { /// /// The underlying wrapped by the current instance. /// private ComPtr d3D12Device; /// /// The instance to use for compute operations. /// private ComPtr d3D12ComputeCommandQueue; /// /// The instance to use for copy operations. /// private ComPtr d3D12CopyCommandQueue; /// /// The instance used for compute operations. /// private ComPtr d3D12ComputeFence; /// /// The instance used for copy operations. /// private ComPtr d3D12CopyFence; /// /// The instance to use when allocating new buffers. /// private ID3D12DescriptorHandleAllocator shaderResourceViewDescriptorAllocator; /// /// The instance for compute operations. /// private readonly ID3D12CommandListPool computeCommandListPool; /// /// Gets the instance for copy operations. /// private readonly ID3D12CommandListPool copyCommandListPool; /// /// The next fence value for compute operations using . /// private ulong nextD3D12ComputeFenceValue; /// /// The next fence value for copy operations using . /// private ulong nextD3D12CopyFenceValue; #if NET6_0_OR_GREATER /// /// The in use associated to the current device. /// private ComPtr allocator; /// /// The instance in use, if is . /// private ComPtr pool; #endif /// /// Creates a new instance for the input . /// /// The to use for the new instance. /// The that was created from. /// The available info for the new instance. internal GraphicsDevice(ID3D12Device* d3D12Device, IDXGIAdapter* dxgiAdapter, DXGI_ADAPTER_DESC1* dxgiDescription1) { this.d3D12Device = new ComPtr(d3D12Device); this.d3D12ComputeCommandQueue = d3D12Device->CreateCommandQueue(D3D12_COMMAND_LIST_TYPE_COMPUTE); this.d3D12CopyCommandQueue = d3D12Device->CreateCommandQueue(D3D12_COMMAND_LIST_TYPE_COPY); this.d3D12ComputeFence = d3D12Device->CreateFence(); this.d3D12CopyFence = d3D12Device->CreateFence(); this.shaderResourceViewDescriptorAllocator = new ID3D12DescriptorHandleAllocator(d3D12Device); this.computeCommandListPool = new ID3D12CommandListPool(D3D12_COMMAND_LIST_TYPE_COMPUTE); this.copyCommandListPool = new ID3D12CommandListPool(D3D12_COMMAND_LIST_TYPE_COPY); Luid = Luid.FromLUID(dxgiDescription1->AdapterLuid); Name = new string((char*)dxgiDescription1->Description); DedicatedMemorySize = dxgiDescription1->DedicatedVideoMemory; SharedMemorySize = dxgiDescription1->SharedSystemMemory; IsHardwareAccelerated = (dxgiDescription1->Flags & (uint)DXGI_ADAPTER_FLAG_SOFTWARE) == 0; var d3D12Options1Data = d3D12Device->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS1); ComputeUnits = d3D12Options1Data.TotalLaneCount; WavefrontSize = d3D12Options1Data.WaveLaneCountMin; var d3D12Architecture1Data = d3D12Device->CheckFeatureSupport(D3D12_FEATURE_ARCHITECTURE1); IsCacheCoherentUMA = d3D12Architecture1Data.CacheCoherentUMA != 0; #if NET6_0_OR_GREATER this.allocator = d3D12Device->CreateAllocator(dxgiAdapter); if (IsCacheCoherentUMA) { this.pool = this.allocator.Get()->CreatePoolForCacheCoherentUMA(); } #endif } /// /// Gets the locally unique identifier for the current device. /// public Luid Luid { get; } /// /// Gets the name of the current instance. /// public string Name { get; } /// /// Gets the size of the dedicated memory for the current device. /// public nuint DedicatedMemorySize { get; } /// /// Gets the size of the shared system memory for the current device. /// public nuint SharedMemorySize { get; } /// /// Gets whether or not the current device is hardware accelerated. /// This value is for software fallback devices. /// public bool IsHardwareAccelerated { get; } /// /// Gets the number of total lanes on the current device (eg. CUDA cores on an nVidia GPU). /// public uint ComputeUnits { get; } /// /// Gets the number of lanes in a SIMD wave on the current device (also known as "wavefront size" or "warp width"). /// public uint WavefrontSize { get; } /// /// Gets the underlying wrapped by the current instance. /// internal ID3D12Device* D3D12Device => this.d3D12Device; #if NET6_0_OR_GREATER /// /// Gets the underlying wrapped by the current instance. /// internal D3D12MA_Allocator* Allocator => this.allocator; /// /// Gets the underlying wrapped by the current instance, if any. /// internal D3D12MA_Pool* Pool => this.pool; #endif /// /// Gets whether or not the current device has a cache coherent UMA architecture. /// internal bool IsCacheCoherentUMA { get; } /// /// Checks whether the current device supports double precision floating point operations in shaders. /// /// Whether the current device supports double precision floating point operations in shaders. public bool IsDoublePrecisionSupportAvailable() { ThrowIfDisposed(); var d3D12OptionsData = this.d3D12Device.Get()->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS); return d3D12OptionsData.DoublePrecisionFloatShaderOps; } /// /// Checks whether the current device supports the creation of /// resources for a specified type . /// /// The type of values to check support for. /// Whether instances can be created by the current device. public bool IsReadOnlyTexture2DSupportedForType() where T : unmanaged { ThrowIfDisposed(); return this.d3D12Device.Get()->IsDxgiFormatSupported(DXGIFormatHelper.GetForType(), D3D12_FORMAT_SUPPORT1_TEXTURE2D); } /// /// Checks whether the current device supports the creation of /// resources for a specified type . /// /// The type of values to check support for. /// Whether instances can be created by the current device. public bool IsReadWriteTexture2DSupportedForType() where T : unmanaged { ThrowIfDisposed(); return this.d3D12Device.Get()->IsDxgiFormatSupported( DXGIFormatHelper.GetForType(), D3D12_FORMAT_SUPPORT1_TEXTURE2D | D3D12_FORMAT_SUPPORT1_TYPED_UNORDERED_ACCESS_VIEW); } /// /// Checks whether the current device supports the creation of /// resources for a specified type . /// /// The type of values to check support for. /// Whether instances can be created by the current device. public bool IsReadOnlyTexture3DSupportedForType() where T : unmanaged { ThrowIfDisposed(); return this.d3D12Device.Get()->IsDxgiFormatSupported(DXGIFormatHelper.GetForType(), D3D12_FORMAT_SUPPORT1_TEXTURE3D); } /// /// Checks whether the current device supports the creation of /// resources for a specified type . /// /// The type of values to check support for. /// Whether instances can be created by the current device. public bool IsReadWriteTexture3DSupportedForType() where T : unmanaged { ThrowIfDisposed(); return this.d3D12Device.Get()->IsDxgiFormatSupported( DXGIFormatHelper.GetForType(), D3D12_FORMAT_SUPPORT1_TEXTURE3D | D3D12_FORMAT_SUPPORT1_TYPED_UNORDERED_ACCESS_VIEW); } /// /// Registers that a new resource has been allocated on the current device. /// internal void RegisterAllocatedResource() { #if NET6_0_OR_GREATER this.pool.AddRef(); this.allocator.AddRef(); #endif } /// /// Unregisters a generic resource that was allocated on the current device. /// internal void UnregisterAllocatedResource() { #if NET6_0_OR_GREATER this.pool.Release(); this.allocator.Release(); #endif } /// [MethodImpl(MethodImplOptions.AggressiveInlining)] internal void RentShaderResourceViewDescriptorHandles( out D3D12_CPU_DESCRIPTOR_HANDLE d3D12CpuDescriptorHandle, out D3D12_GPU_DESCRIPTOR_HANDLE d3D12GpuDescriptorHandle) { this.shaderResourceViewDescriptorAllocator.Rent(out d3D12CpuDescriptorHandle, out d3D12GpuDescriptorHandle); } /// [MethodImpl(MethodImplOptions.AggressiveInlining)] internal void ReturnShaderResourceViewDescriptorHandles( D3D12_CPU_DESCRIPTOR_HANDLE d3D12CpuDescriptorHandle, D3D12_GPU_DESCRIPTOR_HANDLE d3D12GpuDescriptorHandle) { this.shaderResourceViewDescriptorAllocator.Return(d3D12CpuDescriptorHandle, d3D12GpuDescriptorHandle); } /// /// The type of command allocator to rent. /// The resulting value. /// The resulting value. [MethodImpl(MethodImplOptions.AggressiveInlining)] internal void GetCommandListAndAllocator( D3D12_COMMAND_LIST_TYPE d3D12CommandListType, out ID3D12GraphicsCommandList* d3D12CommandList, out ID3D12CommandAllocator* d3D12CommandAllocator) { switch (d3D12CommandListType) { case D3D12_COMMAND_LIST_TYPE_COMPUTE: this.computeCommandListPool.Rent(this.d3D12Device.Get(), null, out d3D12CommandList, out d3D12CommandAllocator); break; case D3D12_COMMAND_LIST_TYPE_COPY: this.copyCommandListPool.Rent(this.d3D12Device.Get(), null, out d3D12CommandList, out d3D12CommandAllocator); break; default: ThrowHelper.ThrowArgumentException>(); d3D12CommandList = null; d3D12CommandAllocator = null; break; } } /// /// The instance to use for the new command list. /// The resulting value. /// The resulting value. [MethodImpl(MethodImplOptions.AggressiveInlining)] internal void GetCommandListAndAllocator( ID3D12PipelineState* d3D12PipelineState, out ID3D12GraphicsCommandList* d3D12CommandList, out ID3D12CommandAllocator* d3D12CommandAllocator) { this.computeCommandListPool.Rent(this.d3D12Device.Get(), d3D12PipelineState, out d3D12CommandList, out d3D12CommandAllocator); } /// /// Sets the descriptor heap for a given instance. /// /// The input instance to use. [MethodImpl(MethodImplOptions.AggressiveInlining)] internal void SetDescriptorHeapForCommandList(ID3D12GraphicsCommandList* d3D12GraphicsCommandList) { ID3D12DescriptorHeap* d3D12DescriptorHeap = this.shaderResourceViewDescriptorAllocator.D3D12DescriptorHeap; d3D12GraphicsCommandList->SetDescriptorHeaps(1, &d3D12DescriptorHeap); } /// /// Executes a given command list and waits for the operation to be completed. /// /// The input to execute. internal void ExecuteCommandList(ref CommandList commandList) { ref readonly ID3D12CommandListPool commandListPool = ref Unsafe.NullRef(); ID3D12CommandQueue* d3D12CommandQueue; ID3D12Fence* d3D12Fence; ref ulong d3D12FenceValue = ref Unsafe.NullRef(); // Get the target command queue, fence and pool for the list type switch (commandList.D3D12CommandListType) { case D3D12_COMMAND_LIST_TYPE_COMPUTE: commandListPool = ref this.computeCommandListPool; d3D12CommandQueue = this.d3D12ComputeCommandQueue; d3D12Fence = this.d3D12ComputeFence; d3D12FenceValue = ref this.nextD3D12ComputeFenceValue; break; case D3D12_COMMAND_LIST_TYPE_COPY: commandListPool = ref this.copyCommandListPool; d3D12CommandQueue = this.d3D12CopyCommandQueue; d3D12Fence = this.d3D12CopyFence; d3D12FenceValue = ref this.nextD3D12CopyFenceValue; break; default: ThrowHelper.ThrowArgumentException(); return; } // Execute the command list d3D12CommandQueue->ExecuteCommandLists(1, commandList.GetD3D12CommandListAddressOf()); #if NET6_0_OR_GREATER ulong updatedFenceValue = Interlocked.Increment(ref d3D12FenceValue); #else ulong updatedFenceValue = (ulong)Interlocked.Increment(ref Unsafe.As(ref d3D12FenceValue)); #endif // Signal to the target fence with the updated value. Note that incrementing the // target fence value to signal must be done after executing the command list. d3D12CommandQueue->Signal(d3D12Fence, updatedFenceValue).Assert(); // If the fence value hasn't been reached, wait until the operation completes if (updatedFenceValue > d3D12Fence->GetCompletedValue()) { d3D12Fence->SetEventOnCompletion(updatedFenceValue, default).Assert(); } // Return the rented command list and command allocator so that they can be reused commandListPool.Return(commandList.DetachD3D12CommandList(), commandList.DetachD3D12CommandAllocator()); } /// protected override void OnDispose() { DeviceHelper.NotifyDisposedDevice(this); this.d3D12Device.Dispose(); this.d3D12ComputeCommandQueue.Dispose(); this.d3D12CopyCommandQueue.Dispose(); this.d3D12ComputeFence.Dispose(); this.d3D12CopyFence.Dispose(); this.computeCommandListPool.Dispose(); this.copyCommandListPool.Dispose(); this.shaderResourceViewDescriptorAllocator.Dispose(); #if NET6_0_OR_GREATER this.pool.Dispose(); this.allocator.Dispose(); #endif } /// public override string ToString() { return $"[{Luid}] {Name}"; } }