From 2070246f909b2ea552ccce07240d7df4d4da466a Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sat, 1 Jul 2023 14:27:21 +0200 Subject: [PATCH] Implement wrapping types for D3D12MA --- .../AllocatorExtensions.cs | 249 ------------------ .../Extensions/AllocatorExtensions.cs | 35 +++ .../Extensions/ID3D12DeviceExtensions.cs | 31 +++ .../Interop/ID3D12AllocationImpl.cs | 174 ++++++++++++ .../ID3D12MemoryAllocatorFactoryImpl.cs | 157 +++++++++++ .../Interop/ID3D12MemoryAllocatorImpl.cs | 216 +++++++++++++++ 6 files changed, 613 insertions(+), 249 deletions(-) delete mode 100644 src/ComputeSharp.D3D12MemoryAllocator/AllocatorExtensions.cs create mode 100644 src/ComputeSharp.D3D12MemoryAllocator/Extensions/AllocatorExtensions.cs create mode 100644 src/ComputeSharp.D3D12MemoryAllocator/Extensions/ID3D12DeviceExtensions.cs create mode 100644 src/ComputeSharp.D3D12MemoryAllocator/Interop/ID3D12AllocationImpl.cs create mode 100644 src/ComputeSharp.D3D12MemoryAllocator/Interop/ID3D12MemoryAllocatorFactoryImpl.cs create mode 100644 src/ComputeSharp.D3D12MemoryAllocator/Interop/ID3D12MemoryAllocatorImpl.cs diff --git a/src/ComputeSharp.D3D12MemoryAllocator/AllocatorExtensions.cs b/src/ComputeSharp.D3D12MemoryAllocator/AllocatorExtensions.cs deleted file mode 100644 index f45084df..00000000 --- a/src/ComputeSharp.D3D12MemoryAllocator/AllocatorExtensions.cs +++ /dev/null @@ -1,249 +0,0 @@ -using System; -using ComputeSharp.Core.Extensions; -using TerraFX.Interop.DirectX; -using TerraFX.Interop.Windows; -using static TerraFX.Interop.DirectX.D3D12_CPU_PAGE_PROPERTY; -using static TerraFX.Interop.DirectX.D3D12_HEAP_TYPE; -using static TerraFX.Interop.DirectX.D3D12_MEMORY_POOL; -using static TerraFX.Interop.DirectX.D3D12_RESOURCE_FLAGS; -using static TerraFX.Interop.DirectX.D3D12_RESOURCE_STATES; -using static TerraFX.Interop.DirectX.D3D12MA_ALLOCATION_FLAGS; -using ResourceType = ComputeSharp.Graphics.Resources.Enums.ResourceType; - -namespace ComputeSharp.Graphics.Extensions; - -/// -/// A with extensions for the type. -/// -internal static unsafe class AllocatorExtensions -{ - /// - /// Creates a instance suited to be used for cache coherent UMA devices. - /// - /// The instance in use. - /// A instance suited to be used for cache coherent UMA devices. - public static ComPtr CreatePoolForCacheCoherentUMA(this ref D3D12MA_Allocator allocator) - { - using ComPtr pool = default; - - D3D12MA_POOL_DESC poolDesc = default; - poolDesc.HeapProperties.CreationNodeMask = 1; - poolDesc.HeapProperties.VisibleNodeMask = 1; - poolDesc.HeapProperties.Type = D3D12_HEAP_TYPE_CUSTOM; - poolDesc.HeapProperties.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_WRITE_BACK; - poolDesc.HeapProperties.MemoryPoolPreference = D3D12_MEMORY_POOL_L0; - - allocator.CreatePool(&poolDesc, pool.GetAddressOf()).Assert(); - - return pool.Move(); - } - - /// - /// Creates a resource for a given buffer type. - /// - /// The instance in use. - /// The instance to use, if any. - /// The resource type currently in use. - /// The allocation mode to use for the new resource. - /// The size in bytes of the current buffer. - /// An reference for the current object. - public static ComPtr CreateResource( - this ref D3D12MA_Allocator allocator, - D3D12MA_Pool* pool, - ResourceType resourceType, - AllocationMode allocationMode, - ulong sizeInBytes) - { - D3D12MA_ALLOCATION_FLAGS allocationFlags = allocationMode == AllocationMode.Default ? D3D12MA_ALLOCATION_FLAG_NONE : D3D12MA_ALLOCATION_FLAG_COMMITTED; - (D3D12_HEAP_TYPE d3D12HeapType, - D3D12_RESOURCE_FLAGS d3D12ResourceFlags, - D3D12_RESOURCE_STATES d3D12ResourceStates) = resourceType switch - { - ResourceType.Constant => (D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_STATE_GENERIC_READ), - ResourceType.ReadOnly => (D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_STATE_COMMON), - ResourceType.ReadWrite => (D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COMMON), - ResourceType.ReadBack => (D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_STATE_COPY_DEST), - ResourceType.Upload => (D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_STATE_GENERIC_READ), - _ => default(ArgumentException).Throw<(D3D12_HEAP_TYPE, D3D12_RESOURCE_FLAGS, D3D12_RESOURCE_STATES)>(nameof(resourceType)) - }; - - using ComPtr allocation = default; - - D3D12_RESOURCE_DESC d3D12ResourceDescription = D3D12_RESOURCE_DESC.Buffer(sizeInBytes, d3D12ResourceFlags); - - D3D12MA_ALLOCATION_DESC allocationDesc = default; - allocationDesc.HeapType = d3D12HeapType; - allocationDesc.Flags = allocationFlags; - allocationDesc.CustomPool = pool; - - allocator.CreateResource( - &allocationDesc, - &d3D12ResourceDescription, - d3D12ResourceStates, - null, - allocation.GetAddressOf(), - null, - null).Assert(); - - return allocation.Move(); - } - - /// - /// Creates a resource for a given 1D texture type. - /// - /// The instance in use. - /// The instance to use, if any. - /// The resource type currently in use. - /// The allocation mode to use for the new resource. - /// The value to use. - /// The width of the texture resource. - /// The default value for the resource. - /// An reference for the current object. - public static ComPtr CreateResource( - this ref D3D12MA_Allocator allocator, - D3D12MA_Pool* pool, - ResourceType resourceType, - AllocationMode allocationMode, - DXGI_FORMAT dxgiFormat, - uint width, - out D3D12_RESOURCE_STATES d3D12ResourceStates) - { - D3D12MA_ALLOCATION_FLAGS allocationFlags = allocationMode == AllocationMode.Default ? D3D12MA_ALLOCATION_FLAG_NONE : D3D12MA_ALLOCATION_FLAG_COMMITTED; - D3D12_RESOURCE_FLAGS d3D12ResourceFlags; - - (d3D12ResourceFlags, d3D12ResourceStates) = resourceType switch - { - ResourceType.ReadOnly => (D3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_STATE_COMMON), - ResourceType.ReadWrite => (D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_UNORDERED_ACCESS), - _ => default(ArgumentException).Throw<(D3D12_RESOURCE_FLAGS, D3D12_RESOURCE_STATES)>(nameof(resourceType)) - }; - - using ComPtr allocation = default; - - D3D12_RESOURCE_DESC d3D12ResourceDescription = D3D12_RESOURCE_DESC.Tex1D(dxgiFormat, width, mipLevels: 1, flags: d3D12ResourceFlags); - - D3D12MA_ALLOCATION_DESC allocationDesc = default; - allocationDesc.HeapType = D3D12_HEAP_TYPE_DEFAULT; - allocationDesc.Flags = allocationFlags; - allocationDesc.CustomPool = pool; - - allocator.CreateResource( - &allocationDesc, - &d3D12ResourceDescription, - d3D12ResourceStates, - null, - allocation.GetAddressOf(), - null, - null).Assert(); - - return allocation.Move(); - } - - /// - /// Creates a resource for a given 2D texture type. - /// - /// The instance in use. - /// The instance to use, if any. - /// The resource type currently in use. - /// The allocation mode to use for the new resource. - /// The value to use. - /// The width of the texture resource. - /// The height of the texture resource. - /// The default value for the resource. - /// An reference for the current object. - public static ComPtr CreateResource( - this ref D3D12MA_Allocator allocator, - D3D12MA_Pool* pool, - ResourceType resourceType, - AllocationMode allocationMode, - DXGI_FORMAT dxgiFormat, - uint width, - uint height, - out D3D12_RESOURCE_STATES d3D12ResourceStates) - { - D3D12MA_ALLOCATION_FLAGS allocationFlags = allocationMode == AllocationMode.Default ? D3D12MA_ALLOCATION_FLAG_NONE : D3D12MA_ALLOCATION_FLAG_COMMITTED; - D3D12_RESOURCE_FLAGS d3D12ResourceFlags; - - (d3D12ResourceFlags, d3D12ResourceStates) = resourceType switch - { - ResourceType.ReadOnly => (D3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_STATE_COMMON), - ResourceType.ReadWrite => (D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_UNORDERED_ACCESS), - _ => default(ArgumentException).Throw<(D3D12_RESOURCE_FLAGS, D3D12_RESOURCE_STATES)>(nameof(resourceType)) - }; - - using ComPtr allocation = default; - - D3D12_RESOURCE_DESC d3D12ResourceDescription = D3D12_RESOURCE_DESC.Tex2D(dxgiFormat, width, height, mipLevels: 1, flags: d3D12ResourceFlags); - - D3D12MA_ALLOCATION_DESC allocationDesc = default; - allocationDesc.HeapType = D3D12_HEAP_TYPE_DEFAULT; - allocationDesc.Flags = allocationFlags; - allocationDesc.CustomPool = pool; - - allocator.CreateResource( - &allocationDesc, - &d3D12ResourceDescription, - d3D12ResourceStates, - null, - allocation.GetAddressOf(), - null, - null).Assert(); - - return allocation.Move(); - } - - /// - /// Creates a resource for a given 3D texture type. - /// - /// The instance in use. - /// The instance to use, if any. - /// The resource type currently in use. - /// The allocation mode to use for the new resource. - /// The value to use. - /// The width of the texture resource. - /// The height of the texture resource. - /// The depth of the texture resource. - /// The default value for the resource. - /// An reference for the current object. - public static ComPtr CreateResource( - this ref D3D12MA_Allocator allocator, - D3D12MA_Pool* pool, - ResourceType resourceType, - AllocationMode allocationMode, - DXGI_FORMAT dxgiFormat, - uint width, - uint height, - ushort depth, - out D3D12_RESOURCE_STATES d3D12ResourceStates) - { - D3D12MA_ALLOCATION_FLAGS allocationFlags = allocationMode == AllocationMode.Default ? D3D12MA_ALLOCATION_FLAG_NONE : D3D12MA_ALLOCATION_FLAG_COMMITTED; - D3D12_RESOURCE_FLAGS d3D12ResourceFlags; - - (d3D12ResourceFlags, d3D12ResourceStates) = resourceType switch - { - ResourceType.ReadOnly => (D3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_STATE_COMMON), - ResourceType.ReadWrite => (D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_UNORDERED_ACCESS), - _ => default(ArgumentException).Throw<(D3D12_RESOURCE_FLAGS, D3D12_RESOURCE_STATES)>(nameof(resourceType)) - }; - - using ComPtr allocation = default; - - D3D12_RESOURCE_DESC d3D12ResourceDescription = D3D12_RESOURCE_DESC.Tex3D(dxgiFormat, width, height, depth, mipLevels: 1, flags: d3D12ResourceFlags); - - D3D12MA_ALLOCATION_DESC allocationDesc = default; - allocationDesc.HeapType = D3D12_HEAP_TYPE_DEFAULT; - allocationDesc.Flags = allocationFlags; - allocationDesc.CustomPool = pool; - - allocator.CreateResource( - &allocationDesc, - &d3D12ResourceDescription, - d3D12ResourceStates, - null, - allocation.GetAddressOf(), - null, - null).Assert(); - - return allocation.Move(); - } -} \ No newline at end of file diff --git a/src/ComputeSharp.D3D12MemoryAllocator/Extensions/AllocatorExtensions.cs b/src/ComputeSharp.D3D12MemoryAllocator/Extensions/AllocatorExtensions.cs new file mode 100644 index 00000000..7d5156f3 --- /dev/null +++ b/src/ComputeSharp.D3D12MemoryAllocator/Extensions/AllocatorExtensions.cs @@ -0,0 +1,35 @@ +using ComputeSharp.Core.Extensions; +using TerraFX.Interop.DirectX; +using TerraFX.Interop.Windows; +using static TerraFX.Interop.DirectX.D3D12_CPU_PAGE_PROPERTY; +using static TerraFX.Interop.DirectX.D3D12_HEAP_TYPE; +using static TerraFX.Interop.DirectX.D3D12_MEMORY_POOL; + +namespace ComputeSharp.D3D12MemoryAllocator.Extensions; + +/// +/// A with extensions for the type. +/// +internal static unsafe class AllocatorExtensions +{ + /// + /// Creates a instance suited to be used for cache coherent UMA devices. + /// + /// The instance in use. + /// A instance suited to be used for cache coherent UMA devices. + public static ComPtr CreatePoolForCacheCoherentUMA(this ref D3D12MA_Allocator allocator) + { + using ComPtr pool = default; + + D3D12MA_POOL_DESC poolDesc = default; + poolDesc.HeapProperties.CreationNodeMask = 1; + poolDesc.HeapProperties.VisibleNodeMask = 1; + poolDesc.HeapProperties.Type = D3D12_HEAP_TYPE_CUSTOM; + poolDesc.HeapProperties.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_WRITE_BACK; + poolDesc.HeapProperties.MemoryPoolPreference = D3D12_MEMORY_POOL_L0; + + allocator.CreatePool(&poolDesc, pool.GetAddressOf()).Assert(); + + return pool.Move(); + } +} \ No newline at end of file diff --git a/src/ComputeSharp.D3D12MemoryAllocator/Extensions/ID3D12DeviceExtensions.cs b/src/ComputeSharp.D3D12MemoryAllocator/Extensions/ID3D12DeviceExtensions.cs new file mode 100644 index 00000000..d6e79ace --- /dev/null +++ b/src/ComputeSharp.D3D12MemoryAllocator/Extensions/ID3D12DeviceExtensions.cs @@ -0,0 +1,31 @@ +using ComputeSharp.Core.Extensions; +using TerraFX.Interop.DirectX; +using TerraFX.Interop.Windows; +using System.Runtime.CompilerServices; + +namespace ComputeSharp.Graphics.Extensions; + +/// +/// A with extensions for the type. +/// +internal static unsafe class ID3D12DeviceExtensions +{ + /// + /// Creates a instance for a given device. + /// + /// The target to use to create the allocator. + /// The that was created from. + /// A instance to create resources on the device in use. + public static ComPtr CreateAllocator(this ref ID3D12Device d3D12Device, IDXGIAdapter* dxgiAdapter) + { + using ComPtr allocator = default; + + D3D12MA_ALLOCATOR_DESC allocatorDesc = default; + allocatorDesc.pDevice = (ID3D12Device*)Unsafe.AsPointer(ref d3D12Device); + allocatorDesc.pAdapter = dxgiAdapter; + + D3D12MemAlloc.D3D12MA_CreateAllocator(&allocatorDesc, allocator.GetAddressOf()).Assert(); + + return allocator.Move(); + } +} \ No newline at end of file diff --git a/src/ComputeSharp.D3D12MemoryAllocator/Interop/ID3D12AllocationImpl.cs b/src/ComputeSharp.D3D12MemoryAllocator/Interop/ID3D12AllocationImpl.cs new file mode 100644 index 00000000..f8d20d4b --- /dev/null +++ b/src/ComputeSharp.D3D12MemoryAllocator/Interop/ID3D12AllocationImpl.cs @@ -0,0 +1,174 @@ +using System; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Threading; +using ComputeSharp.Interop.Allocation; +using TerraFX.Interop.DirectX; +using TerraFX.Interop.Windows; + +namespace ComputeSharp.D3D12MemoryAllocator.Interop; + +/// +/// An implementation of the interface. +/// +internal unsafe struct ID3D12AllocationImpl +{ + /// + /// The shared method table pointer for all instances. + /// + private static readonly void** Vtbl = InitVtbl(); + + /// + /// Builds the custom method table pointer for . + /// + /// The method table pointer for . + private static void** InitVtbl() + { + void** lpVtbl = (void**)RuntimeHelpers.AllocateTypeAssociatedMemory(typeof(ID3D12AllocationImpl), sizeof(void*) * 4); + + lpVtbl[0] = (delegate* unmanaged)&QueryInterface; + lpVtbl[1] = (delegate* unmanaged)&AddRef; + lpVtbl[2] = (delegate* unmanaged)&Release; + lpVtbl[3] = (delegate* unmanaged)&GetD3D12Resource; + + return lpVtbl; + } + + /// + /// The vtable pointer for the current instance. + /// + private void** lpVtbl; + + /// + /// The current reference count for the object (from ). + /// + private volatile int referenceCount; + + /// + /// The parent instance. + /// + private ID3D12MemoryAllocatorImpl* allocatorImpl; + + /// + /// The wrapped instance. + /// + private D3D12MA_Allocation* allocation; + + /// + /// The underlying instance. + /// + private ID3D12Resource* d3D12Resource; + + /// + /// The factory method for instances. + /// + /// The resulting instance. + /// The parent instance. + /// The wrapped instance. + /// The underlying instance. + /// An for the operation. + public static HRESULT Factory( + ID3D12AllocationImpl** allocationImpl, + ID3D12MemoryAllocatorImpl* allocatorImpl, + D3D12MA_Allocation* allocation, + ID3D12Resource* d3D12Resource) + { + ID3D12AllocationImpl* @this; + + try + { + @this = (ID3D12AllocationImpl*)NativeMemory.Alloc((nuint)sizeof(ID3D12AllocationImpl)); + } + catch (OutOfMemoryException) + { + *allocationImpl = null; + + return E.E_OUTOFMEMORY; + } + + _ = allocatorImpl->AddRef(); + _ = allocation->AddRef(); + _ = d3D12Resource->AddRef(); + + @this->lpVtbl = Vtbl; + @this->referenceCount = 1; + @this->allocatorImpl = allocatorImpl; + @this->allocation = allocation; + @this->d3D12Resource = d3D12Resource; + + *allocationImpl = @this; + + return S.S_OK; + } + + /// + [UnmanagedCallersOnly] + private static int QueryInterface(ID3D12AllocationImpl* @this, Guid* riid, void** ppvObject) + { + if (ppvObject is null) + { + return E.E_POINTER; + } + + if (riid->Equals(Windows.__uuidof()) || + riid->Equals(ID3D12Allocation.Guid)) + { + _ = Interlocked.Increment(ref @this->referenceCount); + + *ppvObject = @this; + + return S.S_OK; + } + + *ppvObject = null; + + return E.E_NOINTERFACE; + } + + /// + [UnmanagedCallersOnly] + private static uint AddRef(ID3D12AllocationImpl* @this) + { + return (uint)Interlocked.Increment(ref @this->referenceCount); + } + + /// + [UnmanagedCallersOnly] + private static uint Release(ID3D12AllocationImpl* @this) + { + uint referenceCount = (uint)Interlocked.Decrement(ref @this->referenceCount); + + if (referenceCount == 0) + { + _ = @this->allocation->Release(); + _ = @this->d3D12Resource->Release(); + + // Release the parent allocator as well as last thing. This is needed because the D3D12MA allocator + // will fail if an allocator is released while there are still outstanding allocations. So here we + // increment the reference count of the allocator when creating a new allocation object, and then we + // decrement it after the underlying allocation has been released. This means that if this allocation + // is the last thing keeping the allocator alive, it'll be disposed correctly after this last object. + _ = @this->allocatorImpl->Release(); + + NativeMemory.Free(@this); + } + + return referenceCount; + } + + /// + [UnmanagedCallersOnly] + private static int GetD3D12Resource(ID3D12AllocationImpl* @this, ID3D12Resource** resource) + { + if (resource is null) + { + return E.E_POINTER; + } + + _ = @this->d3D12Resource->AddRef(); + + *resource = @this->d3D12Resource; + + return S.S_OK; + } +} \ No newline at end of file diff --git a/src/ComputeSharp.D3D12MemoryAllocator/Interop/ID3D12MemoryAllocatorFactoryImpl.cs b/src/ComputeSharp.D3D12MemoryAllocator/Interop/ID3D12MemoryAllocatorFactoryImpl.cs new file mode 100644 index 00000000..4c37a045 --- /dev/null +++ b/src/ComputeSharp.D3D12MemoryAllocator/Interop/ID3D12MemoryAllocatorFactoryImpl.cs @@ -0,0 +1,157 @@ +using System; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Threading; +using ComputeSharp.D3D12MemoryAllocator.Extensions; +using ComputeSharp.Graphics.Extensions; +using ComputeSharp.Interop.Allocation; +using TerraFX.Interop.DirectX; +using TerraFX.Interop.Windows; +using static TerraFX.Interop.DirectX.D3D12_FEATURE; + +namespace ComputeSharp.D3D12MemoryAllocator.Interop; + +/// +/// An implementation of the interface. +/// +internal unsafe struct ID3D12MemoryAllocatorFactoryImpl +{ + /// + /// The shared method table pointer for all instances. + /// + private static readonly void** Vtbl = InitVtbl(); + + /// + /// Builds the custom method table pointer for . + /// + /// The method table pointer for . + private static void** InitVtbl() + { + void** lpVtbl = (void**)RuntimeHelpers.AllocateTypeAssociatedMemory(typeof(ID3D12MemoryAllocatorFactoryImpl), sizeof(void*) * 4); + + lpVtbl[0] = (delegate* unmanaged)&QueryInterface; + lpVtbl[1] = (delegate* unmanaged)&AddRef; + lpVtbl[2] = (delegate* unmanaged)&Release; + lpVtbl[3] = (delegate* unmanaged)&CreateAllocator; + + return lpVtbl; + } + + /// + /// The vtable pointer for the current instance. + /// + private void** lpVtbl; + + /// + /// The current reference count for the object (from ). + /// + private volatile int referenceCount; + + /// + /// The factory method for instances. + /// + /// The resulting instance. + /// An for the operation. + public static HRESULT Factory(ID3D12MemoryAllocatorFactoryImpl** allocatorFactoryImpl) + { + ID3D12MemoryAllocatorFactoryImpl* @this; + + try + { + @this = (ID3D12MemoryAllocatorFactoryImpl*)NativeMemory.Alloc((nuint)sizeof(ID3D12MemoryAllocatorFactoryImpl)); + } + catch (OutOfMemoryException) + { + *allocatorFactoryImpl = null; + + return E.E_OUTOFMEMORY; + } + + @this->lpVtbl = Vtbl; + @this->referenceCount = 1; + + *allocatorFactoryImpl = @this; + + return S.S_OK; + } + + /// + [UnmanagedCallersOnly] + private static int QueryInterface(ID3D12MemoryAllocatorFactoryImpl* @this, Guid* riid, void** ppvObject) + { + if (ppvObject is null) + { + return E.E_POINTER; + } + + if (riid->Equals(Windows.__uuidof()) || + riid->Equals(ID3D12MemoryAllocatorFactory.Guid)) + { + _ = Interlocked.Increment(ref @this->referenceCount); + + *ppvObject = @this; + + return S.S_OK; + } + + *ppvObject = null; + + return E.E_NOINTERFACE; + } + + /// + [UnmanagedCallersOnly] + private static uint AddRef(ID3D12MemoryAllocatorFactoryImpl* @this) + { + return (uint)Interlocked.Increment(ref @this->referenceCount); + } + + /// + [UnmanagedCallersOnly] + private static uint Release(ID3D12MemoryAllocatorFactoryImpl* @this) + { + uint referenceCount = (uint)Interlocked.Decrement(ref @this->referenceCount); + + if (referenceCount == 0) + { + NativeMemory.Free(@this); + } + + return referenceCount; + } + + /// + [UnmanagedCallersOnly] + private static int CreateAllocator( + ID3D12MemoryAllocatorFactoryImpl* @this, + ID3D12Device* device, + IDXGIAdapter* adapter, + ID3D12MemoryAllocator** allocator) + { + try + { + using ComPtr d3D12MA_allocator = device->CreateAllocator(adapter); + + // If the target device is a UMA device, also create a pool and use that in the allocator + if (device->CheckFeatureSupport(D3D12_FEATURE_ARCHITECTURE1).CacheCoherentUMA) + { + using ComPtr pool = d3D12MA_allocator.Get()->CreatePoolForCacheCoherentUMA(); + + return ID3D12MemoryAllocatorImpl.Factory( + allocatorImpl: (ID3D12MemoryAllocatorImpl**)allocator, + allocator: d3D12MA_allocator.Get(), + pool: pool.Get()); + } + + // Otherwise create a standard allocator with no explicit pool + return ID3D12MemoryAllocatorImpl.Factory( + allocatorImpl: (ID3D12MemoryAllocatorImpl**)allocator, + allocator: d3D12MA_allocator.Get(), + pool: null); + } + catch (Exception e) + { + return e.HResult; + } + } +} \ No newline at end of file diff --git a/src/ComputeSharp.D3D12MemoryAllocator/Interop/ID3D12MemoryAllocatorImpl.cs b/src/ComputeSharp.D3D12MemoryAllocator/Interop/ID3D12MemoryAllocatorImpl.cs new file mode 100644 index 00000000..eb601f4e --- /dev/null +++ b/src/ComputeSharp.D3D12MemoryAllocator/Interop/ID3D12MemoryAllocatorImpl.cs @@ -0,0 +1,216 @@ +using System; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Threading; +using ComputeSharp.Core.Extensions; +using ComputeSharp.Interop.Allocation; +using TerraFX.Interop.DirectX; +using TerraFX.Interop.Windows; +using static TerraFX.Interop.DirectX.D3D12MA_ALLOCATION_FLAGS; + +namespace ComputeSharp.D3D12MemoryAllocator.Interop; + +/// +/// An implementation of the interface. +/// +internal unsafe struct ID3D12MemoryAllocatorImpl +{ + /// + /// The shared method table pointer for all instances. + /// + private static readonly void** Vtbl = InitVtbl(); + + /// + /// Builds the custom method table pointer for . + /// + /// The method table pointer for . + private static void** InitVtbl() + { + void** lpVtbl = (void**)RuntimeHelpers.AllocateTypeAssociatedMemory(typeof(ID3D12MemoryAllocator), sizeof(void*) * 4); + + lpVtbl[0] = (delegate* unmanaged)&QueryInterface; + lpVtbl[1] = (delegate* unmanaged)&AddRef; + lpVtbl[2] = (delegate* unmanaged)&Release; + lpVtbl[3] = (delegate* unmanaged)&AllocateResource; + + return lpVtbl; + } + + /// + /// The vtable pointer for the current instance. + /// + private void** lpVtbl; + + /// + /// The current reference count for the object (from ). + /// + private volatile int referenceCount; + + /// + /// The in use associated to the current device. + /// + private D3D12MA_Allocator* allocator; + + /// + /// The instance in use, if the device is using cache coherent UMA. + /// + private D3D12MA_Pool* pool; + + /// + /// The factory method for instances. + /// + /// The resulting instance. + /// The input instance. + /// The input instance, if available. + /// An for the operation. + public static HRESULT Factory( + ID3D12MemoryAllocatorImpl** allocatorImpl, + D3D12MA_Allocator* allocator, + D3D12MA_Pool* pool) + { + ID3D12MemoryAllocatorImpl* @this; + + try + { + @this = (ID3D12MemoryAllocatorImpl*)NativeMemory.Alloc((nuint)sizeof(ID3D12MemoryAllocatorImpl)); + } + catch (OutOfMemoryException) + { + *allocatorImpl = null; + + return E.E_OUTOFMEMORY; + } + + _ = allocator->AddRef(); + + // The pool is not necessarily available (it's only used for UMA devices), as it allows creating + // resources in a CPU readable memory region. With non UMA devices, we use the default behavior. + if (pool is not null) + { + _ = pool->AddRef(); + } + + @this->lpVtbl = Vtbl; + @this->referenceCount = 1; + @this->allocator = allocator; + @this->pool = pool; + + *allocatorImpl = @this; + + return S.S_OK; + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public uint AddRef() + { + return (uint)Interlocked.Increment(ref this.referenceCount); + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public uint Release() + { + uint referenceCount = (uint)Interlocked.Decrement(ref this.referenceCount); + + if (referenceCount == 0) + { + // The pool must be released before its associated allocator is disposed. Note that in + // order for the disposal to work correctly, all resources created from the allocator + // must have been disposed already before the allocator is released. This is done by + // having the allocator also increment the reference count of their associated allocator. + // So here we just have to release first the pool, if present, and then the allocator. + if (this.pool is not null) + { + _ = this.pool->Release(); + } + + _ = this.allocator->Release(); + + NativeMemory.Free(Unsafe.AsPointer(ref this)); + } + + return referenceCount; + } + + /// + [UnmanagedCallersOnly] + private static int QueryInterface(ID3D12MemoryAllocatorImpl* @this, Guid* riid, void** ppvObject) + { + if (ppvObject is null) + { + return E.E_POINTER; + } + + if (riid->Equals(Windows.__uuidof()) || + riid->Equals(ID3D12MemoryAllocator.Guid)) + { + _ = Interlocked.Increment(ref @this->referenceCount); + + *ppvObject = @this; + + return S.S_OK; + } + + *ppvObject = null; + + return E.E_NOINTERFACE; + } + + /// + [UnmanagedCallersOnly] + private static uint AddRef(ID3D12MemoryAllocatorImpl* @this) + { + return @this->AddRef(); + } + + /// + [UnmanagedCallersOnly] + private static uint Release(ID3D12MemoryAllocatorImpl* @this) + { + return @this->Release(); + } + + /// + [UnmanagedCallersOnly] + private static int AllocateResource( + ID3D12MemoryAllocatorImpl* @this, + D3D12_RESOURCE_DESC* resourceDescription, + D3D12_HEAP_TYPE heapType, + D3D12_RESOURCE_STATES resourceStates, + BOOL clearAllocation, + ID3D12Allocation** allocation) + { + D3D12MA_ALLOCATION_FLAGS allocationFlags = clearAllocation ? D3D12MA_ALLOCATION_FLAG_COMMITTED : D3D12MA_ALLOCATION_FLAG_NONE; + + D3D12MA_ALLOCATION_DESC allocationDesc = default; + allocationDesc.HeapType = heapType; + allocationDesc.Flags = allocationFlags; + allocationDesc.CustomPool = @this->pool; + + using ComPtr d3D12MA_allocation = default; + using ComPtr d3D12Resource = default; + + // Invoke D3D12MA and create an allocation and resource + HRESULT hresult = @this->allocator->CreateResource( + pAllocDesc: &allocationDesc, + pResourceDesc: resourceDescription, + InitialResourceState: resourceStates, + pOptimizedClearValue: null, + ppAllocation: d3D12MA_allocation.GetAddressOf(), + riidResource: Windows.__uuidof(), + ppvResource: d3D12Resource.GetVoidAddressOf()); + + if (!Windows.SUCCEEDED(hresult)) + { + return hresult; + } + + // Create the allocation wrapper + return ID3D12AllocationImpl.Factory( + allocationImpl: (ID3D12AllocationImpl**)allocation, + allocatorImpl: @this, + allocation: d3D12MA_allocation.Get(), + d3D12Resource: d3D12Resource.Get()); + } +} \ No newline at end of file