diff --git a/src/ComputeSharp/Graphics/Commands/CommandList.cs b/src/ComputeSharp/Graphics/Commands/CommandList.cs
index 57c1ad23..706f8258 100644
--- a/src/ComputeSharp/Graphics/Commands/CommandList.cs
+++ b/src/ComputeSharp/Graphics/Commands/CommandList.cs
@@ -156,10 +156,17 @@ internal unsafe struct CommandList : IDisposable
return this.device.ExecuteCommandListAsync(ref this);
}
+ public void ExecuteWithoutWaiting()
+ {
+ this.d3D12GraphicsCommandList.Get()->Close().Assert();
+
+ this.device.ExecuteCommandListWithoutWaiting(ref this);
+ }
+
///
public void Dispose()
{
this.d3D12CommandAllocator.Dispose();
this.d3D12GraphicsCommandList.Dispose();
}
-}
\ No newline at end of file
+}
diff --git a/src/ComputeSharp/Graphics/Commands/Interop/ID3D12CommandListPool.cs b/src/ComputeSharp/Graphics/Commands/Interop/ID3D12CommandListPool.cs
index ed8e609b..3bccd574 100644
--- a/src/ComputeSharp/Graphics/Commands/Interop/ID3D12CommandListPool.cs
+++ b/src/ComputeSharp/Graphics/Commands/Interop/ID3D12CommandListPool.cs
@@ -11,12 +11,17 @@ namespace ComputeSharp.Graphics.Commands.Interop;
/// A type that acts as a pool to get new instances wheen needed.
///
/// The command list type to use.
-internal readonly unsafe struct ID3D12CommandListPool(D3D12_COMMAND_LIST_TYPE d3D12CommandListType) : IDisposable
+/// The fence used to track deferred command list completion.
+internal readonly unsafe struct ID3D12CommandListPool(D3D12_COMMAND_LIST_TYPE d3D12CommandListType, ID3D12Fence* d3D12Fence) : IDisposable
{
+ private const int MaximumPendingCommandListCount = 16;
+
///
/// The queue of items with the available command lists.
///
- private readonly Queue d3D12CommandListBundleQueue = [];
+ private readonly Queue d3D12CommandListBundleQueue = new(MaximumPendingCommandListCount * 2);
+
+ private readonly Queue pendingD3D12CommandListBundleQueue = new(MaximumPendingCommandListCount);
///
/// Rents a and pair.
@@ -29,6 +34,8 @@ internal readonly unsafe struct ID3D12CommandListPool(D3D12_COMMAND_LIST_TYPE d3
{
lock (this.d3D12CommandListBundleQueue)
{
+ ReclaimCompletedCommandLists();
+
if (this.d3D12CommandListBundleQueue.TryDequeue(out D3D12CommandListBundle d3D12CommandListBundle))
{
d3D12CommandList = d3D12CommandListBundle.D3D12CommandList;
@@ -68,18 +75,71 @@ internal readonly unsafe struct ID3D12CommandListPool(D3D12_COMMAND_LIST_TYPE d3
}
}
+ public void ReturnWhenCompleted(ID3D12GraphicsCommandList* d3D12CommandList, ID3D12CommandAllocator* d3D12CommandAllocator, ulong fenceValue)
+ {
+ lock (this.d3D12CommandListBundleQueue)
+ {
+ ReclaimCompletedCommandLists();
+
+ if (this.pendingD3D12CommandListBundleQueue.Count == MaximumPendingCommandListCount)
+ {
+ PendingD3D12CommandListBundle pendingD3D12CommandListBundle = this.pendingD3D12CommandListBundleQueue.Dequeue();
+
+ if (pendingD3D12CommandListBundle.FenceValue > d3D12Fence->GetCompletedValue())
+ {
+ d3D12Fence->SetEventOnCompletion(pendingD3D12CommandListBundle.FenceValue, default).Assert();
+ }
+
+ this.d3D12CommandListBundleQueue.Enqueue(pendingD3D12CommandListBundle.D3D12CommandListBundle);
+ }
+
+ this.pendingD3D12CommandListBundleQueue.Enqueue(new PendingD3D12CommandListBundle(d3D12CommandList, d3D12CommandAllocator, fenceValue));
+ }
+ }
+
///
public void Dispose()
{
lock (this.d3D12CommandListBundleQueue)
{
+ ulong pendingFenceValue = 0;
+
+ foreach (PendingD3D12CommandListBundle current in this.pendingD3D12CommandListBundleQueue)
+ {
+ pendingFenceValue = Math.Max(pendingFenceValue, current.FenceValue);
+ }
+
+ if (pendingFenceValue > d3D12Fence->GetCompletedValue())
+ {
+ d3D12Fence->SetEventOnCompletion(pendingFenceValue, default).Assert();
+ }
+
foreach (D3D12CommandListBundle d3D12CommandListBundle in this.d3D12CommandListBundleQueue)
{
_ = d3D12CommandListBundle.D3D12CommandList->Release();
_ = d3D12CommandListBundle.D3D12CommandAllocator->Release();
}
+ foreach (PendingD3D12CommandListBundle current in this.pendingD3D12CommandListBundleQueue)
+ {
+ _ = current.D3D12CommandListBundle.D3D12CommandList->Release();
+ _ = current.D3D12CommandListBundle.D3D12CommandAllocator->Release();
+ }
+
this.d3D12CommandListBundleQueue.Clear();
+ this.pendingD3D12CommandListBundleQueue.Clear();
+ }
+ }
+
+ private void ReclaimCompletedCommandLists()
+ {
+ ulong completedValue = d3D12Fence->GetCompletedValue();
+
+ while (this.pendingD3D12CommandListBundleQueue.TryPeek(out PendingD3D12CommandListBundle pendingD3D12CommandListBundle) &&
+ pendingD3D12CommandListBundle.FenceValue <= completedValue)
+ {
+ _ = this.pendingD3D12CommandListBundleQueue.Dequeue();
+ this.d3D12CommandListBundleQueue.Enqueue(pendingD3D12CommandListBundle.D3D12CommandListBundle);
}
}
@@ -121,4 +181,11 @@ internal readonly unsafe struct ID3D12CommandListPool(D3D12_COMMAND_LIST_TYPE d3
///
public readonly ID3D12CommandAllocator* D3D12CommandAllocator = d3D12CommandAllocator;
}
-}
\ No newline at end of file
+
+ private readonly struct PendingD3D12CommandListBundle(ID3D12GraphicsCommandList* d3D12CommandList, ID3D12CommandAllocator* d3D12CommandAllocator, ulong fenceValue)
+ {
+ public readonly D3D12CommandListBundle D3D12CommandListBundle = new(d3D12CommandList, d3D12CommandAllocator);
+
+ public readonly ulong FenceValue = fenceValue;
+ }
+}
diff --git a/src/ComputeSharp/Graphics/Extensions/Interop/ID3D12DeviceExtensions.cs b/src/ComputeSharp/Graphics/Extensions/Interop/ID3D12DeviceExtensions.cs
index 848cf1c3..294edc78 100644
--- a/src/ComputeSharp/Graphics/Extensions/Interop/ID3D12DeviceExtensions.cs
+++ b/src/ComputeSharp/Graphics/Extensions/Interop/ID3D12DeviceExtensions.cs
@@ -278,6 +278,7 @@ internal static unsafe class ID3D12DeviceExtensions
/// 使用する 値。
/// テクスチャの幅。
/// テクスチャの高さ。
+ /// レンダーターゲットとして使用可能にするかどうか。
/// 生成されたリソースの初期 値。
/// 共有可能な への参照。
public static ComPtr CreateSharedCommittedResource(
@@ -286,6 +287,7 @@ internal static unsafe class ID3D12DeviceExtensions
DXGI_FORMAT dxgiFormat,
uint width,
uint height,
+ bool isRenderTarget,
out D3D12_RESOURCE_STATES d3D12ResourceStates)
{
D3D12_RESOURCE_FLAGS d3D12ResourceFlags = resourceType switch
@@ -295,6 +297,11 @@ internal static unsafe class ID3D12DeviceExtensions
_ => default(ArgumentException).Throw(nameof(resourceType))
};
+ if (isRenderTarget)
+ {
+ d3D12ResourceFlags |= D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET;
+ }
+
d3D12ResourceStates = D3D12_RESOURCE_STATE_COMMON;
using ComPtr d3D12Resource = default;
@@ -828,4 +835,4 @@ internal static unsafe class ID3D12DeviceExtensions
return d3D12ShaderModel.HighestShaderModel == d3DShaderModel;
}
-}
\ No newline at end of file
+}
diff --git a/src/ComputeSharp/Graphics/GraphicsDevice.Execute.cs b/src/ComputeSharp/Graphics/GraphicsDevice.Execute.cs
index a5beec31..a81956ed 100644
--- a/src/ComputeSharp/Graphics/GraphicsDevice.Execute.cs
+++ b/src/ComputeSharp/Graphics/GraphicsDevice.Execute.cs
@@ -26,6 +26,7 @@ unsafe partial class GraphicsDevice
ref readonly ID3D12CommandListPool commandListPool = ref Unsafe.NullRef();
ID3D12CommandQueue* d3D12CommandQueue;
ID3D12Fence* d3D12Fence;
+ object d3D12CommandQueueLock;
ref ulong d3D12FenceValue = ref Unsafe.NullRef();
// Get the target command queue, fence and pool for the list type
@@ -35,28 +36,25 @@ unsafe partial class GraphicsDevice
commandListPool = ref this.computeCommandListPool;
d3D12CommandQueue = this.d3D12ComputeCommandQueue.Get();
d3D12Fence = this.d3D12ComputeFence.Get();
+ d3D12CommandQueueLock = this.d3D12ComputeCommandQueueLock;
d3D12FenceValue = ref this.nextD3D12ComputeFenceValue;
break;
case D3D12_COMMAND_LIST_TYPE_COPY:
commandListPool = ref this.copyCommandListPool;
d3D12CommandQueue = this.d3D12CopyCommandQueue.Get();
d3D12Fence = this.d3D12CopyFence.Get();
+ d3D12CommandQueueLock = this.d3D12CopyCommandQueueLock;
d3D12FenceValue = ref this.nextD3D12CopyFenceValue;
break;
default: default(ArgumentException).Throw(nameof(commandList)); return;
}
- // Execute the command list
- fixed (ID3D12CommandList** d3D12CommandList = &commandList.GetD3D12CommandListPinnableAddressOf())
- {
- d3D12CommandQueue->ExecuteCommandLists(1, d3D12CommandList);
- }
-
- ulong updatedFenceValue = Interlocked.Increment(ref d3D12FenceValue);
-
- // 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();
+ ulong updatedFenceValue = ExecuteCommandListCore(
+ ref commandList,
+ d3D12CommandQueue,
+ d3D12Fence,
+ ref d3D12FenceValue,
+ d3D12CommandQueueLock);
// If the fence value hasn't been reached, wait until the operation completes
if (updatedFenceValue > d3D12Fence->GetCompletedValue())
@@ -76,17 +74,12 @@ unsafe partial class GraphicsDevice
/// This method is only supported for compute operations.
internal ValueTask ExecuteCommandListAsync(ref CommandList commandList)
{
- // Execute the command list
- fixed (ID3D12CommandList** d3D12CommandList = &commandList.GetD3D12CommandListPinnableAddressOf())
- {
- this.d3D12ComputeCommandQueue.Get()->ExecuteCommandLists(1, d3D12CommandList);
- }
-
- ulong updatedFenceValue = Interlocked.Increment(ref this.nextD3D12ComputeFenceValue);
-
- // 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.
- this.d3D12ComputeCommandQueue.Get()->Signal(this.d3D12ComputeFence.Get(), updatedFenceValue).Assert();
+ ulong updatedFenceValue = ExecuteCommandListCore(
+ ref commandList,
+ this.d3D12ComputeCommandQueue.Get(),
+ this.d3D12ComputeFence.Get(),
+ ref this.nextD3D12ComputeFenceValue,
+ this.d3D12ComputeCommandQueueLock);
// If the fence value has been reached, complete synchronously
if (updatedFenceValue <= this.d3D12ComputeFence.Get()->GetCompletedValue())
@@ -105,6 +98,43 @@ unsafe partial class GraphicsDevice
commandList.DetachD3D12CommandAllocator()).AsValueTask();
}
+ internal void ExecuteCommandListWithoutWaiting(ref CommandList commandList)
+ {
+ ulong updatedFenceValue = ExecuteCommandListCore(
+ ref commandList,
+ this.d3D12ComputeCommandQueue.Get(),
+ this.d3D12ComputeFence.Get(),
+ ref this.nextD3D12ComputeFenceValue,
+ this.d3D12ComputeCommandQueueLock);
+
+ this.computeCommandListPool.ReturnWhenCompleted(
+ commandList.DetachD3D12CommandList(),
+ commandList.DetachD3D12CommandAllocator(),
+ updatedFenceValue);
+ }
+
+ private static ulong ExecuteCommandListCore(
+ ref CommandList commandList,
+ ID3D12CommandQueue* d3D12CommandQueue,
+ ID3D12Fence* d3D12Fence,
+ ref ulong d3D12FenceValue,
+ object d3D12CommandQueueLock)
+ {
+ lock (d3D12CommandQueueLock)
+ {
+ fixed (ID3D12CommandList** d3D12CommandList = &commandList.GetD3D12CommandListPinnableAddressOf())
+ {
+ d3D12CommandQueue->ExecuteCommandLists(1, d3D12CommandList);
+ }
+
+ ulong updatedFenceValue = ++d3D12FenceValue;
+
+ d3D12CommandQueue->Signal(d3D12Fence, updatedFenceValue).Assert();
+
+ return updatedFenceValue;
+ }
+ }
+
///
/// A context to support .
///
@@ -306,4 +336,4 @@ unsafe partial class GraphicsDevice
this.manualResetValueTaskSource.OnCompleted(continuation, state, token, flags);
}
}
-}
\ No newline at end of file
+}
diff --git a/src/ComputeSharp/Graphics/GraphicsDevice.Sharing.cs b/src/ComputeSharp/Graphics/GraphicsDevice.Sharing.cs
index a3e03194..feaa16fe 100644
--- a/src/ComputeSharp/Graphics/GraphicsDevice.Sharing.cs
+++ b/src/ComputeSharp/Graphics/GraphicsDevice.Sharing.cs
@@ -15,6 +15,7 @@ unsafe partial class GraphicsDevice
/// 使用する 値。
/// テクスチャの幅。
/// テクスチャの高さ。
+ /// レンダーターゲットとして使用可能にするかどうか。
/// 生成された オブジェクト。
/// 生成されたリソースの初期 値。
internal void CreateSharedResource(
@@ -22,10 +23,11 @@ unsafe partial class GraphicsDevice
DXGI_FORMAT dxgiFormat,
uint width,
uint height,
+ bool isRenderTarget,
out ComPtr d3D12Resource,
out D3D12_RESOURCE_STATES d3D12ResourceStates)
{
- d3D12Resource = this.d3D12Device.Get()->CreateSharedCommittedResource(resourceType, dxgiFormat, width, height, out d3D12ResourceStates);
+ d3D12Resource = this.d3D12Device.Get()->CreateSharedCommittedResource(resourceType, dxgiFormat, width, height, isRenderTarget, out d3D12ResourceStates);
}
///
@@ -74,7 +76,10 @@ unsafe partial class GraphicsDevice
/// シグナルする値。
internal void SignalSharedFence(ID3D12Fence* d3D12Fence, ulong value)
{
- this.d3D12ComputeCommandQueue.Get()->Signal(d3D12Fence, value).Assert();
+ lock (this.d3D12ComputeCommandQueueLock)
+ {
+ this.d3D12ComputeCommandQueue.Get()->Signal(d3D12Fence, value).Assert();
+ }
}
///
@@ -84,6 +89,9 @@ unsafe partial class GraphicsDevice
/// 待機する目標値。
internal void WaitForSharedFence(ID3D12Fence* d3D12Fence, ulong value)
{
- this.d3D12ComputeCommandQueue.Get()->Wait(d3D12Fence, value).Assert();
+ lock (this.d3D12ComputeCommandQueueLock)
+ {
+ this.d3D12ComputeCommandQueue.Get()->Wait(d3D12Fence, value).Assert();
+ }
}
}
diff --git a/src/ComputeSharp/Graphics/GraphicsDevice.cs b/src/ComputeSharp/Graphics/GraphicsDevice.cs
index aec8a836..da2b5605 100644
--- a/src/ComputeSharp/Graphics/GraphicsDevice.cs
+++ b/src/ComputeSharp/Graphics/GraphicsDevice.cs
@@ -43,6 +43,10 @@ public sealed unsafe partial class GraphicsDevice : IReferenceTrackedObject
///
private ComPtr d3D12CopyCommandQueue;
+ private readonly object d3D12ComputeCommandQueueLock = new();
+
+ private readonly object d3D12CopyCommandQueueLock = new();
+
///
/// The instance used for compute operations.
///
@@ -150,8 +154,8 @@ public sealed unsafe partial class GraphicsDevice : IReferenceTrackedObject
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);
+ this.computeCommandListPool = new ID3D12CommandListPool(D3D12_COMMAND_LIST_TYPE_COMPUTE, this.d3D12ComputeFence.Get());
+ this.copyCommandListPool = new ID3D12CommandListPool(D3D12_COMMAND_LIST_TYPE_COPY, this.d3D12CopyFence.Get());
this.allocator = new ComPtr(allocator);
Luid = Luid.FromLUID(dxgiDescription1->AdapterLuid);
@@ -423,13 +427,13 @@ public sealed unsafe partial class GraphicsDevice : IReferenceTrackedObject
{
DeviceHelper.NotifyDisposedDevice(this);
+ this.computeCommandListPool.Dispose();
+ this.copyCommandListPool.Dispose();
this.d3D12Device.Dispose();
this.d3D12ComputeCommandQueue.Dispose();
this.d3D12CopyCommandQueue.Dispose();
this.d3D12ComputeFence.Dispose();
this.d3D12CopyFence.Dispose();
- this.computeCommandListPool.Dispose();
- this.copyCommandListPool.Dispose();
this.shaderResourceViewDescriptorAllocator.Dispose();
this.allocator.Dispose();
@@ -451,4 +455,4 @@ public sealed unsafe partial class GraphicsDevice : IReferenceTrackedObject
{
return $"[{Luid}] {Name}";
}
-}
\ No newline at end of file
+}
diff --git a/src/ComputeSharp/Graphics/Interop/InteropServices.Sharing.cs b/src/ComputeSharp/Graphics/Interop/InteropServices.Sharing.cs
index ef64937a..2e73d22e 100644
--- a/src/ComputeSharp/Graphics/Interop/InteropServices.Sharing.cs
+++ b/src/ComputeSharp/Graphics/Interop/InteropServices.Sharing.cs
@@ -19,7 +19,8 @@ public static unsafe partial class InteropServices
/// が の場合にスローされます。
///
/// 返されるテクスチャは で共有 NT ハンドルをエクスポートでき、
- /// D3D11 など他 API から OpenSharedResource1 で開けます。クロス API の同期は共有フェンスで行ってください。
+ /// 対応する外部 API から開けます。D3D11およびDirect2Dの共有ターゲットには正規化オーバーロードを使用してください。
+ /// クロス API の同期は共有フェンスで行ってください。
///
public static ReadWriteTexture2D AllocateSharedReadWriteTexture2D(GraphicsDevice device, int width, int height)
where T : unmanaged
@@ -29,6 +30,30 @@ public static unsafe partial class InteropServices
return new ReadWriteTexture2D(device, width, height);
}
+ ///
+ /// クロス API 共有が可能な正規化 を確保します。
+ ///
+ /// CPU側で使用するピクセルの型。
+ /// GPU側で使用する正規化ピクセルの型。
+ /// テクスチャの確保に使用する 。
+ /// テクスチャの幅。
+ /// テクスチャの高さ。
+ /// 共有可能な正規化 インスタンス。
+ /// が の場合にスローされます。
+ ///
+ /// 返されるテクスチャはUAV、同時アクセス、レンダーターゲットに対応します。D3D11から共有リソースとして開け、
+ /// 互換性のある形式ではDirect2Dの共有ターゲットとして開けます。
+ /// クロス API の同期は共有フェンスで行ってください。
+ ///
+ public static ReadWriteTexture2D AllocateSharedReadWriteTexture2D(GraphicsDevice device, int width, int height)
+ where T : unmanaged, IPixel
+ where TPixel : unmanaged
+ {
+ default(ArgumentNullException).ThrowIfNull(device);
+
+ return new ReadWriteTexture2D(device, width, height);
+ }
+
///
/// クロス API 共有が可能な を確保します。
///
@@ -70,6 +95,32 @@ public static unsafe partial class InteropServices
return new ReadWriteTexture2D(device, d3D12Resource.Get());
}
+ ///
+ /// 外部 API が所有する共有 NT ハンドルを正規化 として開きます。
+ ///
+ /// CPU側で使用するピクセルの型。
+ /// GPU側で使用する正規化ピクセルの型。
+ /// リソースを開くために使用する 。
+ /// 開く対象の共有 NT ハンドル。
+ /// 共有リソースをラップする正規化 インスタンス。
+ /// が の場合にスローされます。
+ /// 共有リソースが2Dテクスチャでない、またはフォーマットが と一致しない場合にスローされます。
+ ///
+ /// 書き込み用に使用する場合、元のリソースはUAV対応かつ同時アクセス可能として作成されている必要があります。
+ /// クロス API の同期は共有フェンスで行ってください。
+ ///
+ public static ReadWriteTexture2D OpenSharedReadWriteTexture2D(GraphicsDevice device, nint handle)
+ where T : unmanaged, IPixel
+ where TPixel : 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 ハンドルを として開きます。
///
diff --git a/src/ComputeSharp/Graphics/Resources/Abstract/Texture2D{T}.cs b/src/ComputeSharp/Graphics/Resources/Abstract/Texture2D{T}.cs
index 15ca90c5..ee06b926 100644
--- a/src/ComputeSharp/Graphics/Resources/Abstract/Texture2D{T}.cs
+++ b/src/ComputeSharp/Graphics/Resources/Abstract/Texture2D{T}.cs
@@ -136,7 +136,8 @@ public abstract unsafe partial class Texture2D : IReferenceTrackedObject, IGr
/// テクスチャの高さ。
/// 現在のテクスチャのリソース種別。
/// 現在のテクスチャ型のフォーマット サポート。
- private protected Texture2D(GraphicsDevice device, int width, int height, ResourceType resourceType, D3D12_FORMAT_SUPPORT1 d3D12FormatSupport)
+ /// レンダーターゲットとして使用可能にするかどうか。
+ private protected Texture2D(GraphicsDevice device, int width, int height, ResourceType resourceType, D3D12_FORMAT_SUPPORT1 d3D12FormatSupport, bool isRenderTarget)
{
using ReferenceTracker.Lease _0 = ReferenceTracker.Create(this, out this.referenceTracker);
@@ -159,6 +160,7 @@ public abstract unsafe partial class Texture2D : IReferenceTrackedObject, IGr
DXGIFormatHelper.GetForType(),
(uint)width,
(uint)height,
+ isRenderTarget,
out this.d3D12Resource,
out this.d3D12ResourceState);
@@ -762,4 +764,4 @@ public abstract unsafe partial class Texture2D : IReferenceTrackedObject, IGr
{
return ValidateAndGetID3D12ResourceAndTransitionStates(device, resourceState, out d3D12Resource, out lease);
}
-}
\ No newline at end of file
+}
diff --git a/src/ComputeSharp/Graphics/Resources/ReadOnlyTexture2D{T}.cs b/src/ComputeSharp/Graphics/Resources/ReadOnlyTexture2D{T}.cs
index 2fc560a7..704ea8c4 100644
--- a/src/ComputeSharp/Graphics/Resources/ReadOnlyTexture2D{T}.cs
+++ b/src/ComputeSharp/Graphics/Resources/ReadOnlyTexture2D{T}.cs
@@ -35,7 +35,7 @@ public sealed class ReadOnlyTexture2D : Texture2D
/// テクスチャの幅。
/// テクスチャの高さ。
internal ReadOnlyTexture2D(GraphicsDevice device, int width, int height)
- : base(device, width, height, ResourceType.ReadOnly, D3D12_FORMAT_SUPPORT1_TEXTURE2D)
+ : base(device, width, height, ResourceType.ReadOnly, D3D12_FORMAT_SUPPORT1_TEXTURE2D, false)
{
}
@@ -69,4 +69,4 @@ public sealed class ReadOnlyTexture2D : Texture2D
{
return $"ComputeSharp.ReadOnlyTexture2D<{typeof(T)}>[{Width}, {Height}]";
}
-}
\ No newline at end of file
+}
diff --git a/src/ComputeSharp/Graphics/Resources/ReadWriteTexture2D{T,TPixel}.cs b/src/ComputeSharp/Graphics/Resources/ReadWriteTexture2D{T,TPixel}.cs
index d33f0da0..f862f993 100644
--- a/src/ComputeSharp/Graphics/Resources/ReadWriteTexture2D{T,TPixel}.cs
+++ b/src/ComputeSharp/Graphics/Resources/ReadWriteTexture2D{T,TPixel}.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;
@@ -29,6 +30,16 @@ public sealed partial class ReadWriteTexture2D : Texture2D, IReadW
{
}
+ 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 | D3D12_FORMAT_SUPPORT1_RENDER_TARGET, true)
+ {
+ }
+
+ internal unsafe ReadWriteTexture2D(GraphicsDevice device, ID3D12Resource* d3D12Resource)
+ : base(device, d3D12Resource, ResourceType.ReadWrite, D3D12_FORMAT_SUPPORT1_TEXTURE2D | D3D12_FORMAT_SUPPORT1_TYPED_UNORDERED_ACCESS_VIEW)
+ {
+ }
+
///
public ref TPixel this[int x, int y] => throw new InvalidExecutionContextException($"{typeof(ReadWriteTexture2D)}[{typeof(int)}, {typeof(int)}]");
@@ -40,4 +51,4 @@ public sealed partial class ReadWriteTexture2D : Texture2D, IReadW
{
return $"ComputeSharp.ReadWriteTexture2D<{typeof(T)}, {typeof(TPixel)}>[{Width}, {Height}]";
}
-}
\ No newline at end of file
+}
diff --git a/src/ComputeSharp/Graphics/Resources/ReadWriteTexture2D{T}.cs b/src/ComputeSharp/Graphics/Resources/ReadWriteTexture2D{T}.cs
index 14fccca7..89008580 100644
--- a/src/ComputeSharp/Graphics/Resources/ReadWriteTexture2D{T}.cs
+++ b/src/ComputeSharp/Graphics/Resources/ReadWriteTexture2D{T}.cs
@@ -35,7 +35,7 @@ public sealed partial class ReadWriteTexture2D : Texture2D
/// テクスチャの幅。
/// テクスチャの高さ。
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)
+ : base(device, width, height, ResourceType.ReadWrite, D3D12_FORMAT_SUPPORT1_TEXTURE2D | D3D12_FORMAT_SUPPORT1_TYPED_UNORDERED_ACCESS_VIEW, false)
{
}
@@ -69,4 +69,4 @@ public sealed partial class ReadWriteTexture2D : Texture2D
{
return $"ComputeSharp.ReadWriteTexture2D<{typeof(T)}>[{Width}, {Height}]";
}
-}
\ No newline at end of file
+}
diff --git a/src/ComputeSharp/Shaders/ComputeContext.cs b/src/ComputeSharp/Shaders/ComputeContext.cs
index bd978e18..b2f4284b 100644
--- a/src/ComputeSharp/Shaders/ComputeContext.cs
+++ b/src/ComputeSharp/Shaders/ComputeContext.cs
@@ -36,6 +36,8 @@ public struct ComputeContext : IDisposable, IAsyncDisposable
///
private CommandList commandList;
+ private bool isSubmitted;
+
///
/// Creates a new instance with the specified parameters.
///
@@ -44,6 +46,7 @@ public struct ComputeContext : IDisposable, IAsyncDisposable
{
this.device = device;
this.commandList = default;
+ this.isSubmitted = false;
// Increment the reference count for the device. This has to be released when disposing the context.
// Not disposing the context is undefined behavior, so we can rely on that to release the reference.
@@ -245,6 +248,11 @@ public struct ComputeContext : IDisposable, IAsyncDisposable
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Dispose()
{
+ if (this.isSubmitted)
+ {
+ return;
+ }
+
default(InvalidOperationException).ThrowIf(this.device is null);
GraphicsDevice device = this.device;
@@ -272,6 +280,11 @@ public struct ComputeContext : IDisposable, IAsyncDisposable
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ValueTask DisposeAsync()
{
+ if (this.isSubmitted)
+ {
+ return ValueTask.CompletedTask;
+ }
+
default(InvalidOperationException).ThrowIf(this.device is null);
GraphicsDevice device = this.device;
@@ -295,6 +308,42 @@ public struct ComputeContext : IDisposable, IAsyncDisposable
}
}
+ ///
+ /// 現在のコンテキストに記録されたコマンドをGPUへ送信します。
+ ///
+ ///
+ /// 通常はGPUでの完了を待たずに戻ります。内部の保留上限に達した場合は、最古の送信が完了するまで待機します。
+ /// コンテキストが参照するすべてのGPUリソースは、共有フェンスなどで送信した処理の完了を確認するまで保持する必要があります。
+ /// このメソッドを呼び出した後、スコープ終端のおよびは何も行いません。
+ ///
+ /// コンテキストが既に破棄または送信されている場合にスローされます。
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public void Submit()
+ {
+ default(InvalidOperationException).ThrowIf(this.device is null);
+
+ GraphicsDevice device = this.device;
+
+ this.device = null;
+ this.isSubmitted = true;
+
+ if (!this.commandList.IsAllocated)
+ {
+ device.GetReferenceTracker().DangerousRelease();
+
+ return;
+ }
+
+ try
+ {
+ this.commandList.ExecuteWithoutWaiting();
+ }
+ finally
+ {
+ device.GetReferenceTracker().DangerousRelease();
+ }
+ }
+
///
/// Gets the current instance.
///
@@ -341,4 +390,4 @@ public struct ComputeContext : IDisposable, IAsyncDisposable
return ref commandList;
}
-}
\ No newline at end of file
+}
diff --git a/src/ComputeSharp/Shaders/Loading/PipelineDataLoader{T}.cs b/src/ComputeSharp/Shaders/Loading/PipelineDataLoader{T}.cs
index ff559581..de794c30 100644
--- a/src/ComputeSharp/Shaders/Loading/PipelineDataLoader{T}.cs
+++ b/src/ComputeSharp/Shaders/Loading/PipelineDataLoader{T}.cs
@@ -21,6 +21,8 @@ internal static unsafe class PipelineDataLoader
///
private static readonly ConditionalWeakTable CachedPipelines = [];
+ private static readonly object PipelineCreationLock = new();
+
///
/// Gets the instance for a given shader.
///
@@ -28,11 +30,29 @@ internal static unsafe class PipelineDataLoader
/// The instance for a given shader.
public static PipelineData GetPipelineData(GraphicsDevice device)
{
- return CachedPipelines.GetValue(device, CreatePipelineData);
+ if (CachedPipelines.TryGetValue(device, out PipelineData? pipelineData))
+ {
+ return pipelineData;
+ }
+
+ lock (PipelineCreationLock)
+ {
+ if (CachedPipelines.TryGetValue(device, out pipelineData))
+ {
+ return pipelineData;
+ }
+
+ pipelineData = CreatePipelineData(device);
+
+ CachedPipelines.Add(device, pipelineData);
+ device.RegisterPipelineData(pipelineData);
+
+ return pipelineData;
+ }
}
///
- /// Creates and caches a instance for a given shader.
+ /// Creates a instance for a given shader.
///
/// The to use to run the shader.
/// The resulting instance to use to run the shader.
@@ -49,12 +69,6 @@ internal static unsafe class PipelineDataLoader
pipelineData = new PipelineData(d3D12RootSignature.Get(), d3D12PipelineState.Get());
}
- // Add the pipeline to the cache for this type
- CachedPipelines.Add(device, pipelineData);
-
- // Register the newly created pipeline data to enable early disposal
- device.RegisterPipelineData(pipelineData);
-
return pipelineData;
}
@@ -123,4 +137,4 @@ internal static unsafe class PipelineDataLoader
d3D12Device->CreateComputePipelineState(d3D12RootSignature, d3D12ShaderBytecode, d3D12PipelineState);
}
}
-}
\ No newline at end of file
+}
diff --git a/tests/ComputeSharp.Tests/InteropServicesTests.Sharing.cs b/tests/ComputeSharp.Tests/InteropServicesTests.Sharing.cs
index 0bac69e5..2e9c323e 100644
--- a/tests/ComputeSharp.Tests/InteropServicesTests.Sharing.cs
+++ b/tests/ComputeSharp.Tests/InteropServicesTests.Sharing.cs
@@ -1,5 +1,7 @@
+using System;
using System.Runtime.InteropServices;
using System.Threading;
+using System.Threading.Tasks;
using ComputeSharp.Interop;
using ComputeSharp.Tests.Attributes;
using ComputeSharp.Tests.Extensions;
@@ -72,6 +74,222 @@ public unsafe partial class InteropServicesTests
}
}
+ [CombinatorialTestMethod]
+ [AllDevices]
+ public void SharedNormalizedReadWriteTexture2D_RoundTripThroughSharedHandle(Device device)
+ {
+ using ReadWriteTexture2D source = InteropServices.AllocateSharedReadWriteTexture2D(device.Get(), 16, 16);
+ using ComPtr d3D12Resource = default;
+
+ InteropServices.GetID3D12Resource(source, Windows.__uuidof(), (void**)d3D12Resource.GetAddressOf());
+
+ D3D12_RESOURCE_FLAGS expectedFlags = D3D12_RESOURCE_FLAGS.D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET |
+ D3D12_RESOURCE_FLAGS.D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS |
+ D3D12_RESOURCE_FLAGS.D3D12_RESOURCE_FLAG_ALLOW_SIMULTANEOUS_ACCESS;
+
+ Assert.AreEqual(expectedFlags, d3D12Resource.Get()->GetDesc().Flags & expectedFlags);
+
+ device.Get().For(16, 16, new SharedNormalizedTextureFillShader(source));
+
+ nint handle = InteropServices.CreateSharedHandle(source);
+
+ Assert.AreNotEqual(0, handle);
+
+ try
+ {
+ using ReadWriteTexture2D opened = InteropServices.OpenSharedReadWriteTexture2D(device.Get(), handle);
+
+ Bgra32[] result = new Bgra32[16 * 16];
+
+ opened.CopyTo(result);
+
+ foreach (Bgra32 pixel in result)
+ {
+ Assert.AreEqual(0xFF808080u, pixel.PackedValue);
+ }
+ }
+ finally
+ {
+ _ = CloseHandle(handle);
+ }
+ }
+
+ [CombinatorialTestMethod]
+ [AllDevices]
+ public void SharedNormalizedReadWriteTexture2D_AllPixelFormats(Device device)
+ {
+ AssertSharedNormalizedTextureFlags(device.Get());
+ AssertSharedNormalizedTextureFlags(device.Get());
+ AssertSharedNormalizedTextureFlags(device.Get());
+ AssertSharedNormalizedTextureFlags(device.Get());
+ AssertSharedNormalizedTextureFlags(device.Get());
+ AssertSharedNormalizedTextureFlags(device.Get());
+ AssertSharedNormalizedTextureFlags(device.Get());
+ }
+
+ [CombinatorialTestMethod]
+ [AllDevices]
+ public void ComputeContext_SubmitDoesNotWaitForCompletion(Device device)
+ {
+ using ReadWriteTexture2D texture = InteropServices.AllocateSharedReadWriteTexture2D(device.Get(), 16, 16);
+ using ComPtr d3D12Fence = default;
+
+ nint handle = 0;
+
+ InteropServices.CreateSharedFence(device.Get(), Windows.__uuidof(), (void**)d3D12Fence.GetAddressOf(), &handle);
+
+ try
+ {
+ InteropServices.WaitForSharedFence(device.Get(), d3D12Fence.Get(), 1);
+
+ Task submitTask = Task.Run(() =>
+ {
+ using ComputeContext context = device.Get().CreateComputeContext();
+
+ context.For(16, 16, new SharedNormalizedTextureFillShader(texture));
+ context.Submit();
+ InteropServices.SignalSharedFence(device.Get(), d3D12Fence.Get(), 2);
+ });
+
+ bool completedWithoutFence;
+
+ try
+ {
+ completedWithoutFence = submitTask.Wait(TimeSpan.FromSeconds(5));
+ }
+ finally
+ {
+ Assert.IsTrue(d3D12Fence.Get()->Signal(1).SUCCEEDED);
+ submitTask.Wait();
+ }
+
+ Assert.IsTrue(completedWithoutFence);
+
+ while (d3D12Fence.Get()->GetCompletedValue() < 2)
+ {
+ _ = Thread.Yield();
+ }
+
+ Bgra32[] result = new Bgra32[16 * 16];
+
+ texture.CopyTo(result);
+
+ Assert.AreEqual(0xFF808080u, result[0].PackedValue);
+ }
+ finally
+ {
+ _ = CloseHandle(handle);
+ }
+ }
+
+ [CombinatorialTestMethod]
+ [AllDevices]
+ public void ComputeContext_SubmitDoesNotAllocateAfterWarmup(Device device)
+ {
+ using ReadWriteTexture2D texture = InteropServices.AllocateSharedReadWriteTexture2D(device.Get(), 16, 16);
+ using ComPtr d3D12Fence = default;
+
+ nint handle = 0;
+
+ InteropServices.CreateSharedFence(device.Get(), Windows.__uuidof(), (void**)d3D12Fence.GetAddressOf(), &handle);
+
+ try
+ {
+ ulong fenceValue = 0;
+
+ for (int i = 0; i < 4; i++)
+ {
+ SubmitAndWait(device.Get(), texture, d3D12Fence.Get(), ref fenceValue);
+ }
+
+ GC.Collect();
+ GC.WaitForPendingFinalizers();
+ GC.Collect();
+
+ long before = GC.GetAllocatedBytesForCurrentThread();
+
+ for (int i = 0; i < 32; i++)
+ {
+ SubmitAndWait(device.Get(), texture, d3D12Fence.Get(), ref fenceValue);
+ }
+
+ long allocated = GC.GetAllocatedBytesForCurrentThread() - before;
+
+ Assert.AreEqual(0, allocated);
+ }
+ finally
+ {
+ _ = CloseHandle(handle);
+ }
+ }
+
+ [CombinatorialTestMethod]
+ [AllDevices]
+ public void ComputeContext_SubmitAppliesBackpressureAtPendingLimit(Device device)
+ {
+ using ReadWriteTexture2D texture = InteropServices.AllocateSharedReadWriteTexture2D(device.Get(), 16, 16);
+ using ComPtr d3D12Fence = default;
+
+ nint handle = 0;
+
+ InteropServices.CreateSharedFence(device.Get(), Windows.__uuidof(), (void**)d3D12Fence.GetAddressOf(), &handle);
+
+ try
+ {
+ InteropServices.WaitForSharedFence(device.Get(), d3D12Fence.Get(), 1);
+
+ for (int i = 0; i < 16; i++)
+ {
+ using ComputeContext context = device.Get().CreateComputeContext();
+
+ context.For(16, 16, new SharedNormalizedTextureFillShader(texture));
+ context.Submit();
+ }
+
+ using ManualResetEventSlim started = new();
+ Task overflowTask = Task.Run(() =>
+ {
+ using ComputeContext context = device.Get().CreateComputeContext();
+
+ context.For(16, 16, new SharedNormalizedTextureFillShader(texture));
+ started.Set();
+ context.Submit();
+ InteropServices.SignalSharedFence(device.Get(), d3D12Fence.Get(), 2);
+ });
+
+ started.Wait();
+
+ bool completedBeforeRelease;
+
+ try
+ {
+ completedBeforeRelease = overflowTask.Wait(TimeSpan.FromMilliseconds(100));
+ }
+ finally
+ {
+ Assert.IsTrue(d3D12Fence.Get()->Signal(1).SUCCEEDED);
+ Assert.IsTrue(overflowTask.Wait(TimeSpan.FromSeconds(5)));
+ }
+
+ Assert.IsFalse(completedBeforeRelease);
+
+ while (d3D12Fence.Get()->GetCompletedValue() < 2)
+ {
+ _ = Thread.Yield();
+ }
+
+ Bgra32[] result = new Bgra32[16 * 16];
+
+ texture.CopyTo(result);
+
+ Assert.AreEqual(0xFF808080u, result[0].PackedValue);
+ }
+ finally
+ {
+ _ = CloseHandle(handle);
+ }
+ }
+
[CombinatorialTestMethod]
[AllDevices]
public void SharedReadOnlyTexture2D_AllocateAndExportHandle(Device device)
@@ -134,4 +352,48 @@ public unsafe partial class InteropServicesTests
this.texture[ThreadIds.XY] = ThreadIds.X + ThreadIds.Y;
}
}
+
+ [AutoConstructor]
+ [ThreadGroupSize(DefaultThreadGroupSizes.XY)]
+ [GeneratedComputeShaderDescriptor]
+ internal readonly partial struct SharedNormalizedTextureFillShader : IComputeShader
+ {
+ public readonly ReadWriteTexture2D texture;
+
+ public void Execute()
+ {
+ this.texture[ThreadIds.XY] = new Float4(0.5f, 0.5f, 0.5f, 1f);
+ }
+ }
+
+ private static void SubmitAndWait(GraphicsDevice device, ReadWriteTexture2D texture, ID3D12Fence* d3D12Fence, ref ulong fenceValue)
+ {
+ using ComputeContext context = device.CreateComputeContext();
+
+ context.For(16, 16, new SharedNormalizedTextureFillShader(texture));
+ context.Submit();
+
+ InteropServices.SignalSharedFence(device, d3D12Fence, ++fenceValue);
+
+ while (d3D12Fence->GetCompletedValue() < fenceValue)
+ {
+ _ = Thread.Yield();
+ }
+ }
+
+ private static void AssertSharedNormalizedTextureFlags(GraphicsDevice device)
+ where T : unmanaged, IPixel
+ where TPixel : unmanaged
+ {
+ using ReadWriteTexture2D texture = InteropServices.AllocateSharedReadWriteTexture2D(device, 1, 1);
+ using ComPtr d3D12Resource = default;
+
+ InteropServices.GetID3D12Resource(texture, Windows.__uuidof(), (void**)d3D12Resource.GetAddressOf());
+
+ D3D12_RESOURCE_FLAGS expectedFlags = D3D12_RESOURCE_FLAGS.D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET |
+ D3D12_RESOURCE_FLAGS.D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS |
+ D3D12_RESOURCE_FLAGS.D3D12_RESOURCE_FLAG_ALLOW_SIMULTANEOUS_ACCESS;
+
+ Assert.AreEqual(expectedFlags, d3D12Resource.Get()->GetDesc().Flags & expectedFlags);
+ }
}