diff --git a/src/ComputeSharp.Win32.D3D12/DirectX/um/d3d12/ID3D12Device.cs b/src/ComputeSharp.Win32.D3D12/DirectX/um/d3d12/ID3D12Device.cs index 8956733c..f0e29ebc 100644 --- a/src/ComputeSharp.Win32.D3D12/DirectX/um/d3d12/ID3D12Device.cs +++ b/src/ComputeSharp.Win32.D3D12/DirectX/um/d3d12/ID3D12Device.cs @@ -217,6 +217,13 @@ internal unsafe partial struct ID3D12Device : IComObject return ((delegate* unmanaged[MemberFunction])(lpVtbl[30]))((ID3D12Device*)Unsafe.AsPointer(ref this), pDesc, InitialState, pOptimizedClearValue, riid, ppvResource); } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [VtblIndex(31)] + public HRESULT CreateSharedHandle(IUnknown* pObject, [NativeTypeName("const SECURITY_ATTRIBUTES *")] SECURITY_ATTRIBUTES* pAttributes, [NativeTypeName("DWORD")] uint Access, [NativeTypeName("LPCWSTR")] ushort* Name, HANDLE* pHandle) + { + return ((delegate* unmanaged[MemberFunction])(lpVtbl[31]))((ID3D12Device*)Unsafe.AsPointer(ref this), pObject, pAttributes, Access, Name, pHandle); + } + [MethodImpl(MethodImplOptions.AggressiveInlining)] [VtblIndex(32)] public HRESULT OpenSharedHandle(HANDLE NTHandle, [NativeTypeName("const IID &")] Guid* riid, void** ppvObj) diff --git a/src/ComputeSharp.Win32.D3D12/Windows/um/winnt/Windows.cs b/src/ComputeSharp.Win32.D3D12/Windows/um/winnt/Windows.cs index d2fb1c51..9f79b405 100644 --- a/src/ComputeSharp.Win32.D3D12/Windows/um/winnt/Windows.cs +++ b/src/ComputeSharp.Win32.D3D12/Windows/um/winnt/Windows.cs @@ -12,4 +12,7 @@ internal static partial class Windows [NativeTypeName("#define GENERIC_WRITE (0x40000000L)")] public const int GENERIC_WRITE = (0x40000000); + + [NativeTypeName("#define GENERIC_ALL (0x10000000L)")] + public const uint GENERIC_ALL = (0x10000000); } \ No newline at end of file diff --git a/src/ComputeSharp/Graphics/Extensions/Interop/ID3D12DeviceExtensions.cs b/src/ComputeSharp/Graphics/Extensions/Interop/ID3D12DeviceExtensions.cs index c9676d16..848cf1c3 100644 --- a/src/ComputeSharp/Graphics/Extensions/Interop/ID3D12DeviceExtensions.cs +++ b/src/ComputeSharp/Graphics/Extensions/Interop/ID3D12DeviceExtensions.cs @@ -270,6 +270,106 @@ internal static unsafe class ID3D12DeviceExtensions return d3D12Resource.Move(); } + /// + /// クロス API 共有が可能なコミット型の 2D テクスチャ リソースを生成します。 + /// + /// 使用する インスタンス。 + /// 生成するリソースの種別。 + /// 使用する 値。 + /// テクスチャの幅。 + /// テクスチャの高さ。 + /// 生成されたリソースの初期 値。 + /// 共有可能な への参照。 + public static ComPtr CreateSharedCommittedResource( + this ref ID3D12Device d3D12Device, + ResourceType resourceType, + DXGI_FORMAT dxgiFormat, + uint width, + uint height, + out D3D12_RESOURCE_STATES d3D12ResourceStates) + { + D3D12_RESOURCE_FLAGS d3D12ResourceFlags = resourceType switch + { + ResourceType.ReadOnly => D3D12_RESOURCE_FLAG_NONE, + ResourceType.ReadWrite => D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS | D3D12_RESOURCE_FLAG_ALLOW_SIMULTANEOUS_ACCESS, + _ => default(ArgumentException).Throw(nameof(resourceType)) + }; + + d3D12ResourceStates = D3D12_RESOURCE_STATE_COMMON; + + using ComPtr d3D12Resource = default; + + D3D12_HEAP_PROPERTIES d3D12HeapProperties; + d3D12HeapProperties.Type = D3D12_HEAP_TYPE_DEFAULT; + d3D12HeapProperties.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN; + d3D12HeapProperties.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN; + d3D12HeapProperties.CreationNodeMask = 1; + d3D12HeapProperties.VisibleNodeMask = 1; + + D3D12_RESOURCE_DESC d3D12ResourceDescription = D3D12_RESOURCE_DESC.Tex2D(dxgiFormat, width, height, mipLevels: 1, flags: d3D12ResourceFlags); + + d3D12Device.CreateCommittedResource( + &d3D12HeapProperties, + D3D12_HEAP_FLAG_SHARED, + &d3D12ResourceDescription, + d3D12ResourceStates, + null, + Windows.__uuidof(), + (void**)d3D12Resource.GetAddressOf()).Assert(); + + return d3D12Resource.Move(); + } + + /// + /// 他 API と共有可能な を生成します。 + /// + /// 使用する インスタンス。 + /// 共有可能な への参照。 + public static ComPtr CreateSharedFence(this ref ID3D12Device d3D12Device) + { + using ComPtr d3D12Fence = default; + + d3D12Device.CreateFence( + 0, + D3D12_FENCE_FLAG_SHARED, + Windows.__uuidof(), + (void**)d3D12Fence.GetAddressOf()).Assert(); + + return d3D12Fence.Move(); + } + + /// + /// 指定した COM オブジェクトに対する共有 NT ハンドルを生成します。 + /// + /// 使用する インスタンス。 + /// 共有ハンドルを生成する対象の COM オブジェクト。 + /// 生成された共有 NT ハンドル。呼び出し側が CloseHandle で解放する責任を持ちます。 + public static HANDLE CreateSharedHandle(this ref ID3D12Device d3D12Device, IUnknown* pObject) + { + HANDLE handle; + + d3D12Device.CreateSharedHandle(pObject, null, Windows.GENERIC_ALL, null, &handle).Assert(); + + return handle; + } + + /// + /// 指定した共有 NT ハンドルから 型の COM オブジェクトを開きます。 + /// + /// 開く COM オブジェクトの型。 + /// 使用する インスタンス。 + /// 開く対象の共有 NT ハンドル。 + /// 開かれた への参照。 + public static ComPtr OpenSharedHandle(this ref ID3D12Device d3D12Device, HANDLE handle) + where T : unmanaged, IComObject + { + using ComPtr obj = default; + + d3D12Device.OpenSharedHandle(handle, Windows.__uuidof(), (void**)obj.GetAddressOf()).Assert(); + + return obj.Move(); + } + /// /// Creates a new for a given device. /// diff --git a/src/ComputeSharp/Graphics/GraphicsDevice.Sharing.cs b/src/ComputeSharp/Graphics/GraphicsDevice.Sharing.cs new file mode 100644 index 00000000..a3e03194 --- /dev/null +++ b/src/ComputeSharp/Graphics/GraphicsDevice.Sharing.cs @@ -0,0 +1,89 @@ +using ComputeSharp.Core.Extensions; +using ComputeSharp.Graphics.Extensions; +using ComputeSharp.Win32; +using ResourceType = ComputeSharp.Graphics.Resources.Enums.ResourceType; + +namespace ComputeSharp; + +/// +unsafe partial class GraphicsDevice +{ + /// + /// クロス API 共有が可能な 2D テクスチャ リソースを生成します。 + /// + /// 生成するリソースの種別。 + /// 使用する 値。 + /// テクスチャの幅。 + /// テクスチャの高さ。 + /// 生成された オブジェクト。 + /// 生成されたリソースの初期 値。 + internal void CreateSharedResource( + ResourceType resourceType, + DXGI_FORMAT dxgiFormat, + uint width, + uint height, + out ComPtr d3D12Resource, + out D3D12_RESOURCE_STATES d3D12ResourceStates) + { + d3D12Resource = this.d3D12Device.Get()->CreateSharedCommittedResource(resourceType, dxgiFormat, width, height, out d3D12ResourceStates); + } + + /// + /// 指定した COM オブジェクトに対する共有 NT ハンドルを生成します。 + /// + /// 共有ハンドルを生成する対象の COM オブジェクト。 + /// 生成された共有 NT ハンドル。 + internal HANDLE CreateSharedHandle(IUnknown* pObject) + { + return this.d3D12Device.Get()->CreateSharedHandle(pObject); + } + + /// + /// 指定した共有 NT ハンドルから を開きます。 + /// + /// 開く対象の共有 NT ハンドル。 + /// 開かれた への参照。 + internal ComPtr OpenSharedResource(HANDLE handle) + { + return this.d3D12Device.Get()->OpenSharedHandle(handle); + } + + /// + /// 他 API と共有可能な を生成します。 + /// + /// 共有可能な への参照。 + internal ComPtr CreateSharedFence() + { + return this.d3D12Device.Get()->CreateSharedFence(); + } + + /// + /// 指定した共有 NT ハンドルから を開きます。 + /// + /// 開く対象の共有 NT ハンドル。 + /// 開かれた への参照。 + internal ComPtr OpenSharedFence(HANDLE handle) + { + return this.d3D12Device.Get()->OpenSharedHandle(handle); + } + + /// + /// コンピュート キュー上で指定した共有フェンスに値をシグナルします。 + /// + /// 対象の 。 + /// シグナルする値。 + internal void SignalSharedFence(ID3D12Fence* d3D12Fence, ulong value) + { + this.d3D12ComputeCommandQueue.Get()->Signal(d3D12Fence, value).Assert(); + } + + /// + /// コンピュート キュー上で指定した共有フェンスが目標値に達するまで待機するよう登録します。 + /// + /// 対象の 。 + /// 待機する目標値。 + internal void WaitForSharedFence(ID3D12Fence* d3D12Fence, ulong value) + { + this.d3D12ComputeCommandQueue.Get()->Wait(d3D12Fence, value).Assert(); + } +} diff --git a/src/ComputeSharp/Graphics/Interop/InteropServices.Sharing.cs b/src/ComputeSharp/Graphics/Interop/InteropServices.Sharing.cs new file mode 100644 index 00000000..ef64937a --- /dev/null +++ b/src/ComputeSharp/Graphics/Interop/InteropServices.Sharing.cs @@ -0,0 +1,196 @@ +using System; +using ComputeSharp.Core.Extensions; +using ComputeSharp.Resources; +using ComputeSharp.Win32; + +namespace ComputeSharp.Interop; + +/// +public static unsafe partial class InteropServices +{ + /// + /// クロス API 共有が可能な を確保します。 + /// + /// テクスチャに格納する要素の型。 + /// テクスチャの確保に使用する 。 + /// テクスチャの幅。 + /// テクスチャの高さ。 + /// 共有可能な インスタンス。 + /// が の場合にスローされます。 + /// + /// 返されるテクスチャは で共有 NT ハンドルをエクスポートでき、 + /// D3D11 など他 API から OpenSharedResource1 で開けます。クロス API の同期は共有フェンスで行ってください。 + /// + public static ReadWriteTexture2D AllocateSharedReadWriteTexture2D(GraphicsDevice device, int width, int height) + where T : unmanaged + { + default(ArgumentNullException).ThrowIfNull(device); + + return new ReadWriteTexture2D(device, width, height); + } + + /// + /// クロス API 共有が可能な を確保します。 + /// + /// テクスチャに格納する要素の型。 + /// テクスチャの確保に使用する 。 + /// テクスチャの幅。 + /// テクスチャの高さ。 + /// 共有可能な インスタンス。 + /// が の場合にスローされます。 + public static ReadOnlyTexture2D AllocateSharedReadOnlyTexture2D(GraphicsDevice device, int width, int height) + where T : unmanaged + { + default(ArgumentNullException).ThrowIfNull(device); + + return new ReadOnlyTexture2D(device, width, height); + } + + /// + /// 外部 API が所有する共有 NT ハンドルを として開きます。 + /// + /// テクスチャに格納する要素の型。 + /// リソースを開くために使用する 。 + /// 開く対象の共有 NT ハンドル。 + /// 共有リソースをラップする インスタンス。 + /// が の場合にスローされます。 + /// 共有リソースが 2D テクスチャでない、またはフォーマットが と一致しない場合にスローされます。 + /// + /// インポートしたリソースを として書き込み用に使用する場合、元のリソースは UAV 対応かつ + /// 同時アクセス可能 (simultaneous access) として作成されている必要があります。クロス API の同期は共有フェンスで行ってください。 + /// + public static ReadWriteTexture2D OpenSharedReadWriteTexture2D(GraphicsDevice device, nint handle) + where T : unmanaged + { + default(ArgumentNullException).ThrowIfNull(device); + + using ReferenceTracker.Lease _0 = device.GetReferenceTracker().GetLease(); + using ComPtr d3D12Resource = device.OpenSharedResource(new HANDLE((void*)handle)); + + return new ReadWriteTexture2D(device, d3D12Resource.Get()); + } + + /// + /// 外部 API が所有する共有 NT ハンドルを として開きます。 + /// + /// テクスチャに格納する要素の型。 + /// リソースを開くために使用する 。 + /// 開く対象の共有 NT ハンドル。 + /// 共有リソースをラップする インスタンス。 + /// が の場合にスローされます。 + /// 共有リソースが 2D テクスチャでない、またはフォーマットが と一致しない場合にスローされます。 + public static ReadOnlyTexture2D OpenSharedReadOnlyTexture2D(GraphicsDevice device, nint handle) + where T : unmanaged + { + default(ArgumentNullException).ThrowIfNull(device); + + using ReferenceTracker.Lease _0 = device.GetReferenceTracker().GetLease(); + using ComPtr d3D12Resource = device.OpenSharedResource(new HANDLE((void*)handle)); + + return new ReadOnlyTexture2D(device, d3D12Resource.Get()); + } + + /// + /// 共有可能なテクスチャの基になる に対する共有 NT ハンドルをエクスポートします。 + /// + /// テクスチャに格納する要素の型。 + /// 共有ハンドルをエクスポートする対象の 。 + /// エクスポートされた共有 NT ハンドル。呼び出し側が CloseHandle で解放する責任を持ちます。 + /// が の場合にスローされます。 + /// + /// このメソッドは、 など共有可能として + /// 作成されたテクスチャに対してのみ成功します。共有用に作成されていないテクスチャに対しては失敗します。 + /// + public static nint CreateSharedHandle(Texture2D texture) + where T : unmanaged + { + default(ArgumentNullException).ThrowIfNull(texture); + + using ReferenceTracker.Lease _0 = texture.GetReferenceTracker().GetLease(); + + HANDLE handle = texture.GraphicsDevice.CreateSharedHandle((IUnknown*)texture.D3D12Resource); + + return (nint)handle.Value; + } + + /// + /// クロス API 同期に使用する共有フェンスを生成し、要求されたインターフェイスとして取得します。 + /// + /// フェンスの生成に使用する 。 + /// 取得するフェンス インターフェイスの識別子 (IID) への参照。 + /// で指定したインターフェイスへのポインターのアドレス。 + /// 生成されたフェンスの共有 NT ハンドルを書き込む先のアドレス。呼び出し側が CloseHandle で解放する責任を持ちます。 + /// が の場合にスローされます。 + /// フェンスの生成、ハンドルのエクスポート、またはインターフェイスの取得に失敗した場合にスローされます。 + /// + /// エクスポートされた は、D3D11 側で ID3D11Device5::OpenSharedFence により開けます。 + /// 取得した は および + /// に渡して、コンピュート キュー上での同期に使用できます。 + /// + public static void CreateSharedFence(GraphicsDevice device, Guid* riid, void** ppvFence, nint* sharedHandle) + { + default(ArgumentNullException).ThrowIfNull(device); + + using ReferenceTracker.Lease _0 = device.GetReferenceTracker().GetLease(); + using ComPtr d3D12Fence = device.CreateSharedFence(); + + HANDLE handle = device.CreateSharedHandle((IUnknown*)d3D12Fence.Get()); + + *sharedHandle = (nint)handle.Value; + + d3D12Fence.Get()->QueryInterface(riid, ppvFence).Assert(); + } + + /// + /// 共有 NT ハンドルから他 API が生成した共有フェンスを開き、要求されたインターフェイスとして取得します。 + /// + /// フェンスを開くために使用する 。 + /// 開く対象の共有 NT ハンドル。 + /// 取得するフェンス インターフェイスの識別子 (IID) への参照。 + /// で指定したインターフェイスへのポインターのアドレス。 + /// が の場合にスローされます。 + /// フェンスを開く、またはインターフェイスの取得に失敗した場合にスローされます。 + public static void OpenSharedFence(GraphicsDevice device, nint handle, Guid* riid, void** ppvFence) + { + default(ArgumentNullException).ThrowIfNull(device); + + using ReferenceTracker.Lease _0 = device.GetReferenceTracker().GetLease(); + using ComPtr d3D12Fence = device.OpenSharedFence(new HANDLE((void*)handle)); + + d3D12Fence.Get()->QueryInterface(riid, ppvFence).Assert(); + } + + /// + /// コンピュート キュー上で指定した共有フェンスに値をシグナルします。 + /// + /// 操作を発行する 。 + /// 対象の ID3D12Fence COM オブジェクトへのポインター。 + /// シグナルする値。 + /// が の場合にスローされます。 + /// シグナルの発行に失敗した場合にスローされます。 + public static void SignalSharedFence(GraphicsDevice device, void* d3D12Fence, ulong value) + { + default(ArgumentNullException).ThrowIfNull(device); + + using ReferenceTracker.Lease _0 = device.GetReferenceTracker().GetLease(); + + device.SignalSharedFence((ID3D12Fence*)d3D12Fence, value); + } + + /// + /// コンピュート キュー上で指定した共有フェンスが目標値に達するまで待機するよう登録します。 + /// + /// 操作を発行する 。 + /// 対象の ID3D12Fence COM オブジェクトへのポインター。 + /// 待機する目標値。 + /// が の場合にスローされます。 + /// 待機の登録に失敗した場合にスローされます。 + public static void WaitForSharedFence(GraphicsDevice device, void* d3D12Fence, ulong value) + { + default(ArgumentNullException).ThrowIfNull(device); + + using ReferenceTracker.Lease _0 = device.GetReferenceTracker().GetLease(); + + device.WaitForSharedFence((ID3D12Fence*)d3D12Fence, value); + } +} diff --git a/src/ComputeSharp/Graphics/Interop/InteropServices.cs b/src/ComputeSharp/Graphics/Interop/InteropServices.cs index c91248b2..ec13d194 100644 --- a/src/ComputeSharp/Graphics/Interop/InteropServices.cs +++ b/src/ComputeSharp/Graphics/Interop/InteropServices.cs @@ -21,7 +21,7 @@ namespace ComputeSharp.Interop; /// that relies on resources being disposed as soon as the relative allocation object is disposed. /// /// -public static unsafe class InteropServices +public static unsafe partial class InteropServices { /// /// Gets the underlying COM object for a given device, as a specified interface. This method invokes diff --git a/src/ComputeSharp/Graphics/Resources/Abstract/Texture2D{T}.cs b/src/ComputeSharp/Graphics/Resources/Abstract/Texture2D{T}.cs index 6d969a48..15ca90c5 100644 --- a/src/ComputeSharp/Graphics/Resources/Abstract/Texture2D{T}.cs +++ b/src/ComputeSharp/Graphics/Resources/Abstract/Texture2D{T}.cs @@ -11,6 +11,7 @@ using ComputeSharp.Interop.Allocation; using ComputeSharp.Resources.Interop; using ComputeSharp.Win32; using static ComputeSharp.Win32.D3D12_COMMAND_LIST_TYPE; +using static ComputeSharp.Win32.D3D12_RESOURCE_DIMENSION; using static ComputeSharp.Win32.D3D12_RESOURCE_STATES; using static ComputeSharp.Win32.D3D12_SRV_DIMENSION; using static ComputeSharp.Win32.D3D12_UAV_DIMENSION; @@ -127,6 +128,141 @@ public abstract unsafe partial class Texture2D : IReferenceTrackedObject, IGr this.d3D12Resource.Get()->SetName(this); } + /// + /// クロス API 共有が可能な インスタンスを生成します。 + /// + /// 現在のインスタンスに関連付ける 。 + /// テクスチャの幅。 + /// テクスチャの高さ。 + /// 現在のテクスチャのリソース種別。 + /// 現在のテクスチャ型のフォーマット サポート。 + private protected Texture2D(GraphicsDevice device, int width, int height, ResourceType resourceType, D3D12_FORMAT_SUPPORT1 d3D12FormatSupport) + { + using ReferenceTracker.Lease _0 = ReferenceTracker.Create(this, out this.referenceTracker); + + default(ArgumentOutOfRangeException).ThrowIfNotBetweenOrEqual(width, 1, D3D12.D3D12_REQ_TEXTURE2D_U_OR_V_DIMENSION); + default(ArgumentOutOfRangeException).ThrowIfNotBetweenOrEqual(height, 1, D3D12.D3D12_REQ_TEXTURE2D_U_OR_V_DIMENSION); + + using ReferenceTracker.Lease _1 = device.GetReferenceTracker().GetLease(); + + device.ThrowIfDeviceLost(); + + if (!device.D3D12Device->IsDxgiFormatSupported(DXGIFormatHelper.GetForType(), d3D12FormatSupport)) + { + UnsupportedTextureTypeException.ThrowForTexture2D(); + } + + GraphicsDevice = device; + + device.CreateSharedResource( + resourceType, + DXGIFormatHelper.GetForType(), + (uint)width, + (uint)height, + out this.d3D12Resource, + out this.d3D12ResourceState); + + this.d3D12CommandListType = this.d3D12ResourceState == D3D12_RESOURCE_STATE_COMMON + ? D3D12_COMMAND_LIST_TYPE_COPY + : D3D12_COMMAND_LIST_TYPE_COMPUTE; + + device.D3D12Device->GetCopyableFootprint( + DXGIFormatHelper.GetForType(), + (uint)width, + (uint)height, + out this.d3D12PlacedSubresourceFootprint, + out _, + out _); + + device.RentShaderResourceViewDescriptorHandles(out this.d3D12ResourceDescriptorHandles); + + switch (resourceType) + { + case ResourceType.ReadOnly: + device.D3D12Device->CreateShaderResourceView(this.d3D12Resource.Get(), DXGIFormatHelper.GetForType(), D3D12_SRV_DIMENSION_TEXTURE2D, this.d3D12ResourceDescriptorHandles.D3D12CpuDescriptorHandle); + break; + case ResourceType.ReadWrite: + device.D3D12Device->CreateUnorderedAccessView(this.d3D12Resource.Get(), DXGIFormatHelper.GetForType(), D3D12_UAV_DIMENSION_TEXTURE2D, this.d3D12ResourceDescriptorHandles.D3D12CpuDescriptorHandle); + device.D3D12Device->CreateUnorderedAccessView(this.d3D12Resource.Get(), DXGIFormatHelper.GetForType(), D3D12_UAV_DIMENSION_TEXTURE2D, this.d3D12ResourceDescriptorHandles.D3D12CpuDescriptorHandleNonShaderVisible); + break; + } + + this.d3D12Resource.Get()->SetName(this); + } + + /// + /// 外部 API が所有する共有リソースをラップする インスタンスを生成します。 + /// + /// 現在のインスタンスに関連付ける 。 + /// ラップ対象の、共有ハンドルから開かれた 。 + /// 現在のテクスチャのリソース種別。 + /// 現在のテクスチャ型のフォーマット サポート。 + private protected Texture2D(GraphicsDevice device, ID3D12Resource* d3D12Resource, ResourceType resourceType, D3D12_FORMAT_SUPPORT1 d3D12FormatSupport) + { + using ReferenceTracker.Lease _0 = ReferenceTracker.Create(this, out this.referenceTracker); + + using ReferenceTracker.Lease _1 = device.GetReferenceTracker().GetLease(); + + device.ThrowIfDeviceLost(); + + if (!device.D3D12Device->IsDxgiFormatSupported(DXGIFormatHelper.GetForType(), d3D12FormatSupport)) + { + UnsupportedTextureTypeException.ThrowForTexture2D(); + } + + D3D12_RESOURCE_DESC d3D12ResourceDescription = d3D12Resource->GetDesc(); + + if (d3D12ResourceDescription.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D) + { + static void Throw() => throw new ArgumentException("The shared resource is not a 2D texture.", "handle"); + + Throw(); + } + + if (d3D12ResourceDescription.Format != DXGIFormatHelper.GetForType()) + { + static void Throw() => throw new ArgumentException($"The shared resource format does not match the texture element type '{typeof(T)}'.", "handle"); + + Throw(); + } + + int width = (int)d3D12ResourceDescription.Width; + int height = (int)d3D12ResourceDescription.Height; + + default(ArgumentOutOfRangeException).ThrowIfNotBetweenOrEqual(width, 1, D3D12.D3D12_REQ_TEXTURE2D_U_OR_V_DIMENSION); + default(ArgumentOutOfRangeException).ThrowIfNotBetweenOrEqual(height, 1, D3D12.D3D12_REQ_TEXTURE2D_U_OR_V_DIMENSION); + + GraphicsDevice = device; + + this.d3D12Resource = new ComPtr(d3D12Resource); + this.d3D12ResourceState = D3D12_RESOURCE_STATE_COMMON; + + this.d3D12CommandListType = D3D12_COMMAND_LIST_TYPE_COPY; + + device.D3D12Device->GetCopyableFootprint( + DXGIFormatHelper.GetForType(), + (uint)width, + (uint)height, + out this.d3D12PlacedSubresourceFootprint, + out _, + out _); + + device.RentShaderResourceViewDescriptorHandles(out this.d3D12ResourceDescriptorHandles); + + switch (resourceType) + { + case ResourceType.ReadOnly: + device.D3D12Device->CreateShaderResourceView(this.d3D12Resource.Get(), DXGIFormatHelper.GetForType(), D3D12_SRV_DIMENSION_TEXTURE2D, this.d3D12ResourceDescriptorHandles.D3D12CpuDescriptorHandle); + break; + case ResourceType.ReadWrite: + device.D3D12Device->CreateUnorderedAccessView(this.d3D12Resource.Get(), DXGIFormatHelper.GetForType(), D3D12_UAV_DIMENSION_TEXTURE2D, this.d3D12ResourceDescriptorHandles.D3D12CpuDescriptorHandle); + device.D3D12Device->CreateUnorderedAccessView(this.d3D12Resource.Get(), DXGIFormatHelper.GetForType(), D3D12_UAV_DIMENSION_TEXTURE2D, this.d3D12ResourceDescriptorHandles.D3D12CpuDescriptorHandleNonShaderVisible); + break; + } + + this.d3D12Resource.Get()->SetName(this); + } + /// public GraphicsDevice GraphicsDevice { get; } diff --git a/src/ComputeSharp/Graphics/Resources/ReadOnlyTexture2D{T}.cs b/src/ComputeSharp/Graphics/Resources/ReadOnlyTexture2D{T}.cs index de843f0b..2fc560a7 100644 --- a/src/ComputeSharp/Graphics/Resources/ReadOnlyTexture2D{T}.cs +++ b/src/ComputeSharp/Graphics/Resources/ReadOnlyTexture2D{T}.cs @@ -2,6 +2,7 @@ using System.Diagnostics; using ComputeSharp.Graphics.Resources.Enums; using ComputeSharp.Resources; using ComputeSharp.Resources.Debug; +using ComputeSharp.Win32; using static ComputeSharp.Win32.D3D12_FORMAT_SUPPORT1; namespace ComputeSharp; @@ -27,6 +28,27 @@ public sealed class ReadOnlyTexture2D : Texture2D { } + /// + /// クロス API 共有が可能な インスタンスを生成します。 + /// + /// 現在のインスタンスに関連付ける 。 + /// テクスチャの幅。 + /// テクスチャの高さ。 + internal ReadOnlyTexture2D(GraphicsDevice device, int width, int height) + : base(device, width, height, ResourceType.ReadOnly, D3D12_FORMAT_SUPPORT1_TEXTURE2D) + { + } + + /// + /// 外部 API が所有する共有リソースをラップする インスタンスを生成します。 + /// + /// 現在のインスタンスに関連付ける 。 + /// ラップ対象の、共有ハンドルから開かれた 。 + internal unsafe ReadOnlyTexture2D(GraphicsDevice device, ID3D12Resource* d3D12Resource) + : base(device, d3D12Resource, ResourceType.ReadOnly, D3D12_FORMAT_SUPPORT1_TEXTURE2D) + { + } + /// /// Gets a single value from the current readonly texture. /// diff --git a/src/ComputeSharp/Graphics/Resources/ReadWriteTexture2D{T}.cs b/src/ComputeSharp/Graphics/Resources/ReadWriteTexture2D{T}.cs index 75054776..14fccca7 100644 --- a/src/ComputeSharp/Graphics/Resources/ReadWriteTexture2D{T}.cs +++ b/src/ComputeSharp/Graphics/Resources/ReadWriteTexture2D{T}.cs @@ -2,6 +2,7 @@ using System.Diagnostics; using ComputeSharp.Graphics.Resources.Enums; using ComputeSharp.Resources; using ComputeSharp.Resources.Debug; +using ComputeSharp.Win32; using static ComputeSharp.Win32.D3D12_FORMAT_SUPPORT1; namespace ComputeSharp; @@ -27,6 +28,27 @@ public sealed partial class ReadWriteTexture2D : Texture2D { } + /// + /// クロス API 共有が可能な インスタンスを生成します。 + /// + /// 現在のインスタンスに関連付ける 。 + /// テクスチャの幅。 + /// テクスチャの高さ。 + internal ReadWriteTexture2D(GraphicsDevice device, int width, int height) + : base(device, width, height, ResourceType.ReadWrite, D3D12_FORMAT_SUPPORT1_TEXTURE2D | D3D12_FORMAT_SUPPORT1_TYPED_UNORDERED_ACCESS_VIEW) + { + } + + /// + /// 外部 API が所有する共有リソースをラップする インスタンスを生成します。 + /// + /// 現在のインスタンスに関連付ける 。 + /// ラップ対象の、共有ハンドルから開かれた 。 + internal unsafe ReadWriteTexture2D(GraphicsDevice device, ID3D12Resource* d3D12Resource) + : base(device, d3D12Resource, ResourceType.ReadWrite, D3D12_FORMAT_SUPPORT1_TEXTURE2D | D3D12_FORMAT_SUPPORT1_TYPED_UNORDERED_ACCESS_VIEW) + { + } + /// /// Gets a single value from the current writeable texture. /// diff --git a/tests/ComputeSharp.Tests/InteropServicesTests.Sharing.cs b/tests/ComputeSharp.Tests/InteropServicesTests.Sharing.cs new file mode 100644 index 00000000..0bac69e5 --- /dev/null +++ b/tests/ComputeSharp.Tests/InteropServicesTests.Sharing.cs @@ -0,0 +1,137 @@ +using System.Runtime.InteropServices; +using System.Threading; +using ComputeSharp.Interop; +using ComputeSharp.Tests.Attributes; +using ComputeSharp.Tests.Extensions; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using TerraFX.Interop.DirectX; +using TerraFX.Interop.Windows; + +namespace ComputeSharp.Tests; + +public unsafe partial class InteropServicesTests +{ + [DllImport("kernel32", ExactSpelling = true)] + private static extern int CloseHandle(nint hObject); + + [CombinatorialTestMethod] + [AllDevices] + public void SharedReadWriteTexture2D_ComputeShaderRoundTrip(Device device) + { + using ReadWriteTexture2D texture = InteropServices.AllocateSharedReadWriteTexture2D(device.Get(), 16, 16); + + device.Get().For(16, 16, new SharedTextureFillShader(texture)); + + float[] result = new float[16 * 16]; + + texture.CopyTo(result); + + for (int y = 0; y < 16; y++) + { + for (int x = 0; x < 16; x++) + { + Assert.AreEqual(x + y, result[(y * 16) + x]); + } + } + } + + [CombinatorialTestMethod] + [AllDevices] + public void SharedReadWriteTexture2D_RoundTripThroughSharedHandle(Device device) + { + using ReadWriteTexture2D source = InteropServices.AllocateSharedReadWriteTexture2D(device.Get(), 16, 16); + + device.Get().For(16, 16, new SharedTextureFillShader(source)); + + nint handle = InteropServices.CreateSharedHandle(source); + + Assert.AreNotEqual(0, handle); + + try + { + using ReadWriteTexture2D opened = InteropServices.OpenSharedReadWriteTexture2D(device.Get(), handle); + + Assert.AreEqual(16, opened.Width); + Assert.AreEqual(16, opened.Height); + + float[] result = new float[16 * 16]; + + opened.CopyTo(result); + + for (int y = 0; y < 16; y++) + { + for (int x = 0; x < 16; x++) + { + Assert.AreEqual(x + y, result[(y * 16) + x]); + } + } + } + finally + { + _ = CloseHandle(handle); + } + } + + [CombinatorialTestMethod] + [AllDevices] + public void SharedReadOnlyTexture2D_AllocateAndExportHandle(Device device) + { + using ReadOnlyTexture2D texture = InteropServices.AllocateSharedReadOnlyTexture2D(device.Get(), 16, 16); + + Assert.AreEqual(16, texture.Width); + Assert.AreEqual(16, texture.Height); + + nint handle = InteropServices.CreateSharedHandle(texture); + + Assert.AreNotEqual(0, handle); + + _ = CloseHandle(handle); + } + + [CombinatorialTestMethod] + [AllDevices] + public void SharedFence_SignalReachesValueOnComputeQueue(Device device) + { + using ComPtr d3D12Fence = default; + + nint handle = 0; + + InteropServices.CreateSharedFence(device.Get(), Windows.__uuidof(), (void**)d3D12Fence.GetAddressOf(), &handle); + + Assert.IsTrue(d3D12Fence.Get() != null); + Assert.AreNotEqual(0, handle); + + try + { + Assert.AreEqual(0u, d3D12Fence.Get()->GetCompletedValue()); + + InteropServices.SignalSharedFence(device.Get(), d3D12Fence.Get(), 7); + + int spin = 0; + + while (d3D12Fence.Get()->GetCompletedValue() < 7 && spin++ < 10000) + { + Thread.Sleep(1); + } + + Assert.AreEqual(7u, d3D12Fence.Get()->GetCompletedValue()); + } + finally + { + _ = CloseHandle(handle); + } + } + + [AutoConstructor] + [ThreadGroupSize(DefaultThreadGroupSizes.XY)] + [GeneratedComputeShaderDescriptor] + internal readonly partial struct SharedTextureFillShader : IComputeShader + { + public readonly ReadWriteTexture2D texture; + + public void Execute() + { + this.texture[ThreadIds.XY] = ThreadIds.X + ThreadIds.Y; + } + } +}