diff --git a/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownMembers.cs b/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownMembers.cs
index 95114e39..05adcd0d 100644
--- a/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownMembers.cs
+++ b/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownMembers.cs
@@ -43,8 +43,8 @@ internal static class HlslKnownMembers
[$"ComputeSharp.IReadOnlyTexture2D`1.this[{typeof(Float2).FullName}]"] = null,
[$"ComputeSharp.ReadOnlyTexture3D`2.this[{typeof(float).FullName}, {typeof(float).FullName}, {typeof(float).FullName}]"] = "float3",
[$"ComputeSharp.ReadOnlyTexture3D`2.this[{typeof(Float3).FullName}]"] = null,
- [$"ComputeSharp.IReadOnlyTexture2D`1.this[{typeof(float).FullName}, {typeof(float).FullName}, {typeof(float).FullName}]"] = "float3",
- [$"ComputeSharp.IReadOnlyTexture2D`1.this[{typeof(Float3).FullName}]"] = null
+ [$"ComputeSharp.IReadOnlyTexture3D`1.this[{typeof(float).FullName}, {typeof(float).FullName}, {typeof(float).FullName}]"] = "float3",
+ [$"ComputeSharp.IReadOnlyTexture3D`1.this[{typeof(Float3).FullName}]"] = null
};
///
diff --git a/src/ComputeSharp/Graphics/Extensions/GraphicsDeviceExtensions.Resources.cs b/src/ComputeSharp/Graphics/Extensions/GraphicsDeviceExtensions.Resources.cs
index c235c555..09e50274 100644
--- a/src/ComputeSharp/Graphics/Extensions/GraphicsDeviceExtensions.Resources.cs
+++ b/src/ComputeSharp/Graphics/Extensions/GraphicsDeviceExtensions.Resources.cs
@@ -1173,4 +1173,60 @@ public static partial class GraphicsDeviceExtensions
return texture;
}
+
+ ///
+ /// Loads a new upload 2D texture with the contents of the specified file.
+ ///
+ /// The type of items to store in the texture.
+ /// The instance to use to allocate the texture.
+ /// The filename of the image file to load and decode into the texture.
+ /// A instance with the contents of the specified file.
+ public static UploadTexture2D LoadUploadTexture2D(this GraphicsDevice device, string filename)
+ where T : unmanaged
+ {
+ Guard.IsNotNull(filename, nameof(filename));
+
+ return device.LoadUploadTexture2D(filename.AsSpan());
+ }
+
+ ///
+ /// Loads a new upload 2D texture with the contents of the specified file.
+ ///
+ /// The type of items to store in the texture.
+ /// The instance to use to allocate the texture.
+ /// The filename of the image file to load and decode into the texture.
+ /// A instance with the contents of the specified file.
+ public static UploadTexture2D LoadUploadTexture2D(this GraphicsDevice device, ReadOnlySpan filename)
+ where T : unmanaged
+ {
+ return WICHelper.Instance.LoadTexture(device, filename);
+ }
+
+ ///
+ /// Loads a new upload 2D texture with the contents of the specified file.
+ ///
+ /// The type of items to store in the texture.
+ /// The instance to use to allocate the texture.
+ /// The buffer with the image data to load and decode into the texture.
+ /// A instance with the contents of the specified file.
+ public static UploadTexture2D LoadUploadTexture2D(this GraphicsDevice device, ReadOnlySpan span)
+ where T : unmanaged
+ {
+ return WICHelper.Instance.LoadTexture(device, span);
+ }
+
+ ///
+ /// Loads a new upload 2D texture with the contents of the specified file.
+ ///
+ /// The type of items to store in the texture.
+ /// The instance to use to allocate the texture.
+ /// The stream with the image data to load and decode into the texture.
+ /// A instance with the contents of the specified file.
+ public static UploadTexture2D LoadUploadTexture2D(this GraphicsDevice device, Stream stream)
+ where T : unmanaged
+ {
+ Guard.IsNotNull(stream, nameof(stream));
+
+ return WICHelper.Instance.LoadTexture(device, stream);
+ }
}
diff --git a/src/ComputeSharp/Graphics/Helpers/__Internals/GraphicsResourceHelper.cs b/src/ComputeSharp/Graphics/Helpers/__Internals/GraphicsResourceHelper.cs
index 195862ad..bc80a50a 100644
--- a/src/ComputeSharp/Graphics/Helpers/__Internals/GraphicsResourceHelper.cs
+++ b/src/ComputeSharp/Graphics/Helpers/__Internals/GraphicsResourceHelper.cs
@@ -40,6 +40,15 @@ public static class GraphicsResourceHelper
/// The target instance in use.
/// The the underlying object.
ID3D12Resource* ValidateAndGetID3D12Resource(GraphicsDevice device);
+
+ ///
+ /// Validates the given resource for usage with a specified device, and retrieves the underlying object, along with the transition states.
+ ///
+ /// The target instance in use.
+ /// The target state to transition the resource to.
+ /// The the underlying object.
+ /// The resource states for , before and after the transition.
+ (D3D12_RESOURCE_STATES Before, D3D12_RESOURCE_STATES After) ValidateAndGetID3D12ResourceAndTransitionStates(GraphicsDevice device, ResourceState resourceState, out ID3D12Resource* d3D12Resource);
}
///
diff --git a/src/ComputeSharp/Graphics/Resources/Abstract/Texture2D{T}.cs b/src/ComputeSharp/Graphics/Resources/Abstract/Texture2D{T}.cs
index 2e5f35b1..ef2de122 100644
--- a/src/ComputeSharp/Graphics/Resources/Abstract/Texture2D{T}.cs
+++ b/src/ComputeSharp/Graphics/Resources/Abstract/Texture2D{T}.cs
@@ -1,10 +1,12 @@
-using System.Runtime.CompilerServices;
+using System;
+using System.Runtime.CompilerServices;
using ComputeSharp.__Internals;
using ComputeSharp.Exceptions;
using ComputeSharp.Graphics.Commands;
using ComputeSharp.Graphics.Commands.Interop;
using ComputeSharp.Graphics.Extensions;
using ComputeSharp.Graphics.Helpers;
+using ComputeSharp.Graphics.Resources.Helpers;
using ComputeSharp.Graphics.Resources.Interop;
using ComputeSharp.Interop;
using Microsoft.Toolkit.Diagnostics;
@@ -44,11 +46,6 @@ public unsafe abstract class Texture2D : NativeObject, IGraphicsResource, Gra
///
private readonly ID3D12ResourceDescriptorHandles d3D12ResourceDescriptorHandles;
- ///
- /// The default value for the current resource.
- ///
- private readonly D3D12_RESOURCE_STATES d3D12ResourceState;
-
///
/// The value to use for copy operations.
///
@@ -59,6 +56,11 @@ public unsafe abstract class Texture2D : NativeObject, IGraphicsResource, Gra
///
private readonly D3D12_PLACED_SUBRESOURCE_FOOTPRINT d3D12PlacedSubresourceFootprint;
+ ///
+ /// The current value for the current resource.
+ ///
+ private D3D12_RESOURCE_STATES d3D12ResourceState;
+
///
/// Creates a new instance with the specified parameters.
///
@@ -540,6 +542,25 @@ public unsafe abstract class Texture2D : NativeObject, IGraphicsResource, Gra
}
}
+ ///
+ /// Throws an if the current resource is not in a readonly state.
+ ///
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ protected void ThrowIfIsNotInReadOnlyState()
+ {
+ if (this.d3D12ResourceState == D3D12_RESOURCE_STATE_UNORDERED_ACCESS)
+ {
+ static void Throw()
+ {
+ throw new InvalidOperationException(
+ "The texture is not currently in readonly mode. This API can only be used when creating a compute graph with " +
+ "the ComputeContext type, and after having used ComputeContext.Transition() to change the state of the texture.");
+ }
+
+ Throw();
+ }
+ }
+
///
/// Throws a if the target device doesn't match the current one.
///
@@ -572,6 +593,22 @@ public unsafe abstract class Texture2D : NativeObject, IGraphicsResource, Gra
return D3D12Resource;
}
+ ///
+ internal (D3D12_RESOURCE_STATES Before, D3D12_RESOURCE_STATES After) ValidateAndGetID3D12ResourceAndTransitionStates(GraphicsDevice device, ResourceState resourceState, out ID3D12Resource* d3D12Resource)
+ {
+ ThrowIfDisposed();
+ ThrowIfDeviceMismatch(device);
+
+ D3D12_RESOURCE_STATES d3D12ResourceStatesBefore = this.d3D12ResourceState;
+ D3D12_RESOURCE_STATES d3D12ResourceStatesAfter = ResourceStateHelper.GetD3D12ResourceStates(resourceState);
+
+ this.d3D12ResourceState = d3D12ResourceStatesAfter;
+
+ d3D12Resource = D3D12Resource;
+
+ return (d3D12ResourceStatesBefore, d3D12ResourceStatesAfter);
+ }
+
///
D3D12_GPU_DESCRIPTOR_HANDLE GraphicsResourceHelper.IGraphicsResource.ValidateAndGetGpuDescriptorHandle(GraphicsDevice device)
{
@@ -592,4 +629,10 @@ public unsafe abstract class Texture2D : NativeObject, IGraphicsResource, Gra
{
return ValidateAndGetID3D12Resource(device);
}
+
+ ///
+ (D3D12_RESOURCE_STATES, D3D12_RESOURCE_STATES) GraphicsResourceHelper.IGraphicsResource.ValidateAndGetID3D12ResourceAndTransitionStates(GraphicsDevice device, ResourceState resourceState, out ID3D12Resource* d3D12Resource)
+ {
+ return ValidateAndGetID3D12ResourceAndTransitionStates(device, resourceState, out d3D12Resource);
+ }
}
diff --git a/src/ComputeSharp/Graphics/Resources/Abstract/Texture3D{T}.cs b/src/ComputeSharp/Graphics/Resources/Abstract/Texture3D{T}.cs
index ddfda4af..ac0c4265 100644
--- a/src/ComputeSharp/Graphics/Resources/Abstract/Texture3D{T}.cs
+++ b/src/ComputeSharp/Graphics/Resources/Abstract/Texture3D{T}.cs
@@ -1,10 +1,12 @@
-using System.Runtime.CompilerServices;
+using System;
+using System.Runtime.CompilerServices;
using ComputeSharp.__Internals;
using ComputeSharp.Exceptions;
using ComputeSharp.Graphics.Commands;
using ComputeSharp.Graphics.Commands.Interop;
using ComputeSharp.Graphics.Extensions;
using ComputeSharp.Graphics.Helpers;
+using ComputeSharp.Graphics.Resources.Helpers;
using ComputeSharp.Graphics.Resources.Interop;
using ComputeSharp.Interop;
using Microsoft.Toolkit.Diagnostics;
@@ -44,11 +46,6 @@ public unsafe abstract class Texture3D : NativeObject, IGraphicsResource, Gra
///
private readonly ID3D12ResourceDescriptorHandles d3D12ResourceDescriptorHandles;
- ///
- /// The default value for the current resource.
- ///
- private readonly D3D12_RESOURCE_STATES d3D12ResourceState;
-
///
/// The value to use for copy operations.
///
@@ -59,6 +56,11 @@ public unsafe abstract class Texture3D : NativeObject, IGraphicsResource, Gra
///
private readonly D3D12_PLACED_SUBRESOURCE_FOOTPRINT d3D12PlacedSubresourceFootprint;
+ ///
+ /// The current value for the current resource.
+ ///
+ private D3D12_RESOURCE_STATES d3D12ResourceState;
+
///
/// Creates a new instance with the specified parameters.
///
@@ -593,6 +595,25 @@ public unsafe abstract class Texture3D : NativeObject, IGraphicsResource, Gra
}
}
+ ///
+ /// Throws an if the current resource is not in a readonly state.
+ ///
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ protected void ThrowIfIsNotInReadOnlyState()
+ {
+ if (this.d3D12ResourceState == D3D12_RESOURCE_STATE_UNORDERED_ACCESS)
+ {
+ static void Throw()
+ {
+ throw new InvalidOperationException(
+ "The texture is not currently in readonly mode. This API can only be used when creating a compute graph with " +
+ "the ComputeContext type, and after having used ComputeContext.Transition() to change the state of the texture.");
+ }
+
+ Throw();
+ }
+ }
+
///
/// Throws a if the target device doesn't match the current one.
///
@@ -625,6 +646,22 @@ public unsafe abstract class Texture3D : NativeObject, IGraphicsResource, Gra
return D3D12Resource;
}
+ ///
+ internal (D3D12_RESOURCE_STATES Before, D3D12_RESOURCE_STATES After) ValidateAndGetID3D12ResourceAndTransitionStates(GraphicsDevice device, ResourceState resourceState, out ID3D12Resource* d3D12Resource)
+ {
+ ThrowIfDisposed();
+ ThrowIfDeviceMismatch(device);
+
+ D3D12_RESOURCE_STATES d3D12ResourceStatesBefore = this.d3D12ResourceState;
+ D3D12_RESOURCE_STATES d3D12ResourceStatesAfter = ResourceStateHelper.GetD3D12ResourceStates(resourceState);
+
+ this.d3D12ResourceState = d3D12ResourceStatesAfter;
+
+ d3D12Resource = D3D12Resource;
+
+ return (d3D12ResourceStatesBefore, d3D12ResourceStatesAfter);
+ }
+
///
D3D12_GPU_DESCRIPTOR_HANDLE GraphicsResourceHelper.IGraphicsResource.ValidateAndGetGpuDescriptorHandle(GraphicsDevice device)
{
@@ -645,4 +682,10 @@ public unsafe abstract class Texture3D : NativeObject, IGraphicsResource, Gra
{
return ValidateAndGetID3D12Resource(device);
}
+
+ ///
+ (D3D12_RESOURCE_STATES, D3D12_RESOURCE_STATES) GraphicsResourceHelper.IGraphicsResource.ValidateAndGetID3D12ResourceAndTransitionStates(GraphicsDevice device, ResourceState resourceState, out ID3D12Resource* d3D12Resource)
+ {
+ return ValidateAndGetID3D12ResourceAndTransitionStates(device, resourceState, out d3D12Resource);
+ }
}
diff --git a/src/ComputeSharp/Graphics/Resources/Enums/ResourceState.cs b/src/ComputeSharp/Graphics/Resources/Enums/ResourceState.cs
new file mode 100644
index 00000000..684ed25b
--- /dev/null
+++ b/src/ComputeSharp/Graphics/Resources/Enums/ResourceState.cs
@@ -0,0 +1,17 @@
+namespace ComputeSharp;
+
+///
+/// An that indicates the state of a resource after a given transition.
+///
+public enum ResourceState
+{
+ ///
+ /// A readonly resource, that can only be read from by the GPU and supports texture sampling.
+ ///
+ ReadOnly,
+
+ ///
+ /// A read write resource, with both read and write access for the GPU, but without support for texture sampling.
+ ///
+ ReadWrite
+}
diff --git a/src/ComputeSharp/Graphics/Resources/Helpers/ResourceStateHelper.cs b/src/ComputeSharp/Graphics/Resources/Helpers/ResourceStateHelper.cs
new file mode 100644
index 00000000..38b95cca
--- /dev/null
+++ b/src/ComputeSharp/Graphics/Resources/Helpers/ResourceStateHelper.cs
@@ -0,0 +1,33 @@
+using System.Runtime.CompilerServices;
+using Microsoft.Toolkit.Diagnostics;
+using TerraFX.Interop.DirectX;
+using static TerraFX.Interop.DirectX.D3D12_RESOURCE_STATES;
+
+namespace ComputeSharp.Graphics.Resources.Helpers;
+
+///
+/// A helper type with utility methods for .
+///
+internal static class ResourceStateHelper
+{
+ ///
+ /// Gets the corresponding value for the input resource state.
+ ///
+ /// The value corresponding to the input resource state.
+ /// Thrown when the input value is not valid.
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static D3D12_RESOURCE_STATES GetD3D12ResourceStates(ResourceState resourceState)
+ {
+ if (resourceState == ResourceState.ReadOnly)
+ {
+ return D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE;
+ }
+
+ if (resourceState == ResourceState.ReadWrite)
+ {
+ return D3D12_RESOURCE_STATE_UNORDERED_ACCESS;
+ }
+
+ return ThrowHelper.ThrowArgumentException("The target resource state is not valid.");
+ }
+}
diff --git a/src/ComputeSharp/Graphics/Resources/ReadWriteTexture2D{T,TPixel}.ReadOnly.cs b/src/ComputeSharp/Graphics/Resources/ReadWriteTexture2D{T,TPixel}.ReadOnly.cs
new file mode 100644
index 00000000..33924345
--- /dev/null
+++ b/src/ComputeSharp/Graphics/Resources/ReadWriteTexture2D{T,TPixel}.ReadOnly.cs
@@ -0,0 +1,168 @@
+using System;
+using System.Runtime.CompilerServices;
+using ComputeSharp.__Internals;
+using ComputeSharp.Exceptions;
+using ComputeSharp.Graphics.Commands.Interop;
+using ComputeSharp.Graphics.Extensions;
+using ComputeSharp.Graphics.Helpers;
+using ComputeSharp.Interop;
+using TerraFX.Interop.DirectX;
+using static TerraFX.Interop.DirectX.D3D12_SRV_DIMENSION;
+
+#pragma warning disable CS0618
+
+namespace ComputeSharp;
+
+///
+partial class ReadWriteTexture2D
+{
+ ///
+ /// The wrapping instance, if available.
+ ///
+ private ReadOnly? readOnlyWrapper;
+
+ ///
+ /// Retrieves a wrapping instance for the current resource.
+ ///
+ /// An instance wrapping the current resource.
+ ///
+ /// The returned instance can be used in a shader to enable texture sampling.
+ ///
+ /// This is an advanced API that can only be used after the current instance has been transitioned to be in a readonly state. To do so,
+ /// use ,
+ /// and specify . After that, can be used to get a readonly wrapper for
+ /// the current texture to use in a shader. This instance should not be cached or reused, but just passed directly to a shader
+ /// being dispatched through that same , as it will not work if the texture changes state later on.
+ /// Before the end of that list of operations, the texture also needs to be transitioned back to writeable state, using the same
+ /// API as before but specifying . Failing to do so results in undefined behavior.
+ ///
+ ///
+ /// Thrown if the current instance or its associated device are disposed.
+ /// Thrown if the current instance is not in a readonly state.
+ public IReadOnlyTexture2D AsReadOnly()
+ {
+ GraphicsDevice.ThrowIfDisposed();
+
+ ThrowIfDisposed();
+ ThrowIfIsNotInReadOnlyState();
+
+ ReadOnly? readOnlyWrapper = this.readOnlyWrapper;
+
+ if (readOnlyWrapper is not null)
+ {
+ return readOnlyWrapper;
+ }
+
+ // The wrapper initialization is moved to a non inlined helper to keep the codegen of this method
+ // as compact as possible. If the current wrapper is not initialized, control goes directly to the
+ // helper that will initialize and return it, which translates to a single jump.
+ [MethodImpl(MethodImplOptions.NoInlining)]
+ static ReadOnly InitializeWrapper(ReadWriteTexture2D texture)
+ {
+ return texture.readOnlyWrapper = new(texture);
+ }
+
+ return InitializeWrapper(this);
+ }
+
+ ///
+ protected override void OnDispose()
+ {
+ base.OnDispose();
+
+ this.readOnlyWrapper?.Dispose();
+ }
+
+ ///
+ /// A wrapper for a resource that has been temporarily transitioned to readonly.
+ ///
+ private sealed unsafe class ReadOnly : NativeObject, IReadOnlyTexture2D, GraphicsResourceHelper.IGraphicsResource
+ {
+ ///
+ /// The owning instance being wrapped.
+ ///
+ private readonly ReadWriteTexture2D owner;
+
+ ///
+ /// The instance for the current resource.
+ ///
+ private readonly ID3D12ResourceDescriptorHandles d3D12ResourceDescriptorHandles;
+
+ ///
+ /// Creates a new instance with the specified parameters.
+ ///
+ /// The owning instance to wrap.
+ public ReadOnly(ReadWriteTexture2D owner)
+ {
+ this.owner = owner;
+
+ owner.GraphicsDevice.RentShaderResourceViewDescriptorHandles(out this.d3D12ResourceDescriptorHandles);
+
+ owner.GraphicsDevice.D3D12Device->CreateShaderResourceView(owner.D3D12Resource, DXGIFormatHelper.GetForType(), D3D12_SRV_DIMENSION_TEXTURE2D, this.d3D12ResourceDescriptorHandles.D3D12CpuDescriptorHandle);
+ }
+
+ ///
+ public ref readonly TPixel this[int x, int y] => throw new InvalidExecutionContextException($"{typeof(ReadWriteTexture2D.ReadOnly)}[{typeof(int)}, {typeof(int)}]");
+
+ ///
+ public ref readonly TPixel this[Int2 xy] => throw new InvalidExecutionContextException($"{typeof(ReadWriteTexture2D.ReadOnly)}[{typeof(Int2)}]");
+
+ ///
+ public ref readonly TPixel this[float u, float v] => throw new InvalidExecutionContextException($"{typeof(ReadWriteTexture2D.ReadOnly)}[{typeof(float)}, {typeof(float)}]");
+
+ ///
+ public ref readonly TPixel this[Float2 uv] => throw new InvalidExecutionContextException($"{typeof(ReadWriteTexture2D.ReadOnly)}[{typeof(Float2)}]");
+
+ ///
+ public int Width => this.owner.Width;
+
+ ///
+ public int Height => this.owner.Height;
+
+ ///
+ public GraphicsDevice GraphicsDevice => this.owner.GraphicsDevice;
+
+ ///
+ D3D12_GPU_DESCRIPTOR_HANDLE GraphicsResourceHelper.IGraphicsResource.ValidateAndGetGpuDescriptorHandle(GraphicsDevice device)
+ {
+ ThrowIfDisposed();
+
+ this.owner.ThrowIfDisposed();
+ this.owner.ThrowIfDeviceMismatch(device);
+
+ return this.d3D12ResourceDescriptorHandles.D3D12GpuDescriptorHandle;
+ }
+
+ ///
+ (D3D12_GPU_DESCRIPTOR_HANDLE, D3D12_CPU_DESCRIPTOR_HANDLE) GraphicsResourceHelper.IGraphicsResource.ValidateAndGetGpuAndCpuDescriptorHandlesForClear(GraphicsDevice device, out bool isNormalized)
+ {
+ throw new NotSupportedException("This operation cannot be performaned on a readonly wrapper.");
+ }
+
+ ///
+ ID3D12Resource* GraphicsResourceHelper.IGraphicsResource.ValidateAndGetID3D12Resource(GraphicsDevice device)
+ {
+ ThrowIfDisposed();
+
+ this.owner.ThrowIfDisposed();
+ this.owner.ThrowIfDeviceMismatch(device);
+
+ return this.owner.D3D12Resource;
+ }
+
+ ///
+ (D3D12_RESOURCE_STATES, D3D12_RESOURCE_STATES) GraphicsResourceHelper.IGraphicsResource.ValidateAndGetID3D12ResourceAndTransitionStates(GraphicsDevice device, ResourceState resourceState, out ID3D12Resource* d3D12Resource)
+ {
+ throw new NotSupportedException("This operation cannot be performaned on a readonly wrapper.");
+ }
+
+ ///
+ protected override void OnDispose()
+ {
+ if (this.owner.GraphicsDevice is GraphicsDevice device)
+ {
+ device.ReturnShaderResourceViewDescriptorHandles(in this.d3D12ResourceDescriptorHandles);
+ }
+ }
+ }
+}
diff --git a/src/ComputeSharp/Graphics/Resources/ReadWriteTexture2D{T,TPixel}.cs b/src/ComputeSharp/Graphics/Resources/ReadWriteTexture2D{T,TPixel}.cs
index ac9b2214..4647cace 100644
--- a/src/ComputeSharp/Graphics/Resources/ReadWriteTexture2D{T,TPixel}.cs
+++ b/src/ComputeSharp/Graphics/Resources/ReadWriteTexture2D{T,TPixel}.cs
@@ -14,7 +14,7 @@ namespace ComputeSharp;
/// The type of pixels used on the GPU side.
[DebuggerTypeProxy(typeof(Texture2DDebugView<>))]
[DebuggerDisplay("{ToString(),raw}")]
-public sealed class ReadWriteTexture2D : Texture2D, IReadWriteTexture2D
+public sealed partial class ReadWriteTexture2D : Texture2D, IReadWriteTexture2D
where T : unmanaged, IPixel
where TPixel : unmanaged
{
diff --git a/src/ComputeSharp/Graphics/Resources/ReadWriteTexture3D{T,TPixel}.ReadOnly.cs b/src/ComputeSharp/Graphics/Resources/ReadWriteTexture3D{T,TPixel}.ReadOnly.cs
new file mode 100644
index 00000000..8bc206b8
--- /dev/null
+++ b/src/ComputeSharp/Graphics/Resources/ReadWriteTexture3D{T,TPixel}.ReadOnly.cs
@@ -0,0 +1,168 @@
+using System;
+using System.Runtime.CompilerServices;
+using ComputeSharp.__Internals;
+using ComputeSharp.Exceptions;
+using ComputeSharp.Graphics.Commands.Interop;
+using ComputeSharp.Graphics.Extensions;
+using ComputeSharp.Graphics.Helpers;
+using ComputeSharp.Interop;
+using TerraFX.Interop.DirectX;
+using static TerraFX.Interop.DirectX.D3D12_SRV_DIMENSION;
+
+#pragma warning disable CS0618
+
+namespace ComputeSharp;
+
+///
+partial class ReadWriteTexture3D
+{
+ ///
+ /// The wrapping instance, if available.
+ ///
+ private ReadOnly? readOnlyWrapper;
+
+ ///
+ /// Retrieves a wrapping instance for the current resource.
+ ///
+ /// An instance wrapping the current resource.
+ ///
+ /// The returned instance can be used in a shader to enable texture sampling.
+ ///
+ /// This is an advanced API that can only be used after the current instance has been transitioned to be in a readonly state. To do so,
+ /// use ,
+ /// and specify . After that, can be used to get a readonly wrapper for
+ /// the current texture to use in a shader. This instance should not be cached or reused, but just passed directly to a shader
+ /// being dispatched through that same , as it will not work if the texture changes state later on.
+ /// Before the end of that list of operations, the texture also needs to be transitioned back to writeable state, using the same
+ /// API as before but specifying . Failing to do so results in undefined behavior.
+ ///
+ ///
+ /// Thrown if the current instance or its associated device are disposed.
+ /// Thrown if the current instance is not in a readonly state.
+ public IReadOnlyTexture3D AsReadOnly()
+ {
+ GraphicsDevice.ThrowIfDisposed();
+
+ ThrowIfDisposed();
+ ThrowIfIsNotInReadOnlyState();
+
+ ReadOnly? readOnlyWrapper = this.readOnlyWrapper;
+
+ if (readOnlyWrapper is not null)
+ {
+ return readOnlyWrapper;
+ }
+
+ [MethodImpl(MethodImplOptions.NoInlining)]
+ static ReadOnly InitializeWrapper(ReadWriteTexture3D texture)
+ {
+ return texture.readOnlyWrapper = new(texture);
+ }
+
+ return InitializeWrapper(this);
+ }
+
+ ///
+ protected override void OnDispose()
+ {
+ base.OnDispose();
+
+ this.readOnlyWrapper?.Dispose();
+ }
+
+ ///
+ /// A wrapper for a resource that has been temporarily transitioned to readonly.
+ ///
+ private sealed unsafe class ReadOnly : NativeObject, IReadOnlyTexture3D, GraphicsResourceHelper.IGraphicsResource
+ {
+ ///
+ /// The owning instance being wrapped.
+ ///
+ private readonly ReadWriteTexture3D owner;
+
+ ///
+ /// The instance for the current resource.
+ ///
+ private readonly ID3D12ResourceDescriptorHandles d3D12ResourceDescriptorHandles;
+
+ ///
+ /// Creates a new instance with the specified parameters.
+ ///
+ /// The owning instance to wrap.
+ public ReadOnly(ReadWriteTexture3D owner)
+ {
+ this.owner = owner;
+
+ owner.GraphicsDevice.RentShaderResourceViewDescriptorHandles(out this.d3D12ResourceDescriptorHandles);
+
+ owner.GraphicsDevice.D3D12Device->CreateShaderResourceView(owner.D3D12Resource, DXGIFormatHelper.GetForType(), D3D12_SRV_DIMENSION_TEXTURE3D, this.d3D12ResourceDescriptorHandles.D3D12CpuDescriptorHandle);
+ }
+
+ ///
+ public ref readonly TPixel this[int x, int y, int z] => throw new InvalidExecutionContextException($"{typeof(ReadWriteTexture3D.ReadOnly)}[{typeof(int)}, {typeof(int)}, {typeof(int)}]");
+
+ ///
+ public ref readonly TPixel this[Int3 xyz] => throw new InvalidExecutionContextException($"{typeof(ReadWriteTexture3D.ReadOnly)}[{typeof(Int3)}]");
+
+ ///
+ public ref readonly TPixel this[float u, float v, float w] => throw new InvalidExecutionContextException($"{typeof(ReadWriteTexture3D.ReadOnly)}[{typeof(float)}, {typeof(float)}, {typeof(float)}]");
+
+ ///
+ public ref readonly TPixel this[Float3 uvw] => throw new InvalidExecutionContextException($"{typeof(ReadWriteTexture3D.ReadOnly)}[{typeof(Float3)}]");
+
+ ///
+ public int Width => this.owner.Width;
+
+ ///
+ public int Height => this.owner.Height;
+
+ ///
+ public int Depth => this.owner.Depth;
+
+ ///
+ public GraphicsDevice GraphicsDevice => this.owner.GraphicsDevice;
+
+ ///
+ D3D12_GPU_DESCRIPTOR_HANDLE GraphicsResourceHelper.IGraphicsResource.ValidateAndGetGpuDescriptorHandle(GraphicsDevice device)
+ {
+ ThrowIfDisposed();
+
+ this.owner.ThrowIfDisposed();
+ this.owner.ThrowIfDeviceMismatch(device);
+
+ return this.d3D12ResourceDescriptorHandles.D3D12GpuDescriptorHandle;
+ }
+
+ ///
+ (D3D12_GPU_DESCRIPTOR_HANDLE, D3D12_CPU_DESCRIPTOR_HANDLE) GraphicsResourceHelper.IGraphicsResource.ValidateAndGetGpuAndCpuDescriptorHandlesForClear(GraphicsDevice device, out bool isNormalized)
+ {
+ throw new NotSupportedException("This operation cannot be performaned on a readonly wrapper.");
+ }
+
+ ///
+ ID3D12Resource* GraphicsResourceHelper.IGraphicsResource.ValidateAndGetID3D12Resource(GraphicsDevice device)
+ {
+ ThrowIfDisposed();
+
+ this.owner.ThrowIfDisposed();
+ this.owner.ThrowIfDeviceMismatch(device);
+
+ return this.owner.D3D12Resource;
+ }
+
+ ///
+ (D3D12_RESOURCE_STATES, D3D12_RESOURCE_STATES) GraphicsResourceHelper.IGraphicsResource.ValidateAndGetID3D12ResourceAndTransitionStates(GraphicsDevice device, ResourceState resourceState, out ID3D12Resource* d3D12Resource)
+ {
+ throw new NotSupportedException("This operation cannot be performaned on a readonly wrapper.");
+ }
+
+ ///
+ protected override void OnDispose()
+ {
+ if (this.owner.GraphicsDevice is GraphicsDevice device)
+ {
+ device.ReturnShaderResourceViewDescriptorHandles(in this.d3D12ResourceDescriptorHandles);
+ }
+ }
+ }
+}
diff --git a/src/ComputeSharp/Graphics/Resources/ReadWriteTexture3D{T,TPixel}.cs b/src/ComputeSharp/Graphics/Resources/ReadWriteTexture3D{T,TPixel}.cs
index 3007240b..492c6fd6 100644
--- a/src/ComputeSharp/Graphics/Resources/ReadWriteTexture3D{T,TPixel}.cs
+++ b/src/ComputeSharp/Graphics/Resources/ReadWriteTexture3D{T,TPixel}.cs
@@ -14,7 +14,7 @@ namespace ComputeSharp;
/// The type of pixels used on the GPU side.
[DebuggerTypeProxy(typeof(Texture3DDebugView<>))]
[DebuggerDisplay("{ToString(),raw}")]
-public sealed class ReadWriteTexture3D : Texture3D, IReadWriteTexture3D
+public sealed partial class ReadWriteTexture3D : Texture3D, IReadWriteTexture3D
where T : unmanaged, IPixel
where TPixel : unmanaged
{
diff --git a/src/ComputeSharp/Graphics/Resources/Views/TextureView2D{T}.cs b/src/ComputeSharp/Graphics/Resources/Views/TextureView2D{T}.cs
index 74393f90..abf0f066 100644
--- a/src/ComputeSharp/Graphics/Resources/Views/TextureView2D{T}.cs
+++ b/src/ComputeSharp/Graphics/Resources/Views/TextureView2D{T}.cs
@@ -55,7 +55,7 @@ public readonly unsafe ref partial struct TextureView2D
///
/// The row pitch of the specified 2D region.
///
- private readonly int pitchInBytes;
+ private readonly int strideInBytes;
///
/// Initializes a new instance of the struct with the specified parameters.
@@ -69,7 +69,7 @@ public readonly unsafe ref partial struct TextureView2D
this.pointer = pointer;
this.width = width;
this.height = height;
- this.pitchInBytes = pitchInBytes;
+ this.strideInBytes = pitchInBytes;
}
///
@@ -130,7 +130,7 @@ public readonly unsafe ref partial struct TextureView2D
Guard.IsInRange(x, 0, this.width, nameof(x));
Guard.IsInRange(y, 0, this.height, nameof(y));
- return ref *((T*)((byte*)this.pointer + (y * this.pitchInBytes)) + x);
+ return ref *((T*)((byte*)this.pointer + (y * this.strideInBytes)) + x);
}
}
@@ -191,13 +191,11 @@ public readonly unsafe ref partial struct TextureView2D
/// For this API to succeed, the target has to have the same shape as the current one.
///
/// The destination instance.
- ///
- /// Thrown when is shorter than the source instance.
- ///
+ /// Thrown when doesn't match the size of the current instance.
public void CopyTo(TextureView2D destination)
{
if (destination.width != this.width ||
- destination.width != this.height)
+ destination.height != this.height)
{
ThrowHelper.ThrowArgumentException();
}
@@ -244,7 +242,7 @@ public readonly unsafe ref partial struct TextureView2D
/// Whether or not the operation was successful.
public bool TryCopyTo(TextureView2D destination)
{
- if (destination.width == this.width ||
+ if (destination.width == this.width &&
destination.height == this.height)
{
CopyTo(destination);
@@ -286,7 +284,7 @@ public readonly unsafe ref partial struct TextureView2D
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public T* DangerousGetAddressAndByteStride(out int strideInBytes)
{
- strideInBytes = this.pitchInBytes;
+ strideInBytes = this.strideInBytes;
return this.pointer;
}
@@ -295,13 +293,13 @@ public readonly unsafe ref partial struct TextureView2D
/// Gets a for a specified row.
///
/// The index of the target row to retrieve.
- /// Throw when is out of range.
+ /// Thrown when is out of range.
/// The resulting row .
public Span GetRowSpan(int y)
{
Guard.IsInRange(y, 0, this.height, nameof(y));
- return new((byte*)this.pointer + (y * this.pitchInBytes), this.width);
+ return new((byte*)this.pointer + (y * this.strideInBytes), this.width);
}
///
@@ -311,7 +309,7 @@ public readonly unsafe ref partial struct TextureView2D
/// Whether or not was correctly assigned.
public bool TryGetSpan(out Span span)
{
- if (this.pitchInBytes == this.width)
+ if (this.strideInBytes == this.width)
{
span = new(this.pointer, Length);
diff --git a/src/ComputeSharp/Graphics/Resources/Views/TextureView3D{T}.cs b/src/ComputeSharp/Graphics/Resources/Views/TextureView3D{T}.cs
index 489b636d..9dfd0212 100644
--- a/src/ComputeSharp/Graphics/Resources/Views/TextureView3D{T}.cs
+++ b/src/ComputeSharp/Graphics/Resources/Views/TextureView3D{T}.cs
@@ -221,13 +221,12 @@ public readonly unsafe ref partial struct TextureView3D
/// For this API to succeed, the target has to have the same shape as the current one.
///
/// The destination instance.
- ///
- /// Thrown when is shorter than the source instance.
- ///
+ /// Thrown when doesn't match the size of the current instance.
public void CopyTo(TextureView3D destination)
{
if (destination.width != this.width ||
- destination.width != this.height)
+ destination.height != this.height ||
+ destination.depth != this.depth)
{
ThrowHelper.ThrowArgumentException();
}
@@ -277,8 +276,9 @@ public readonly unsafe ref partial struct TextureView3D
/// Whether or not the operation was successful.
public bool TryCopyTo(TextureView3D destination)
{
- if (destination.width == this.width ||
- destination.height == this.height)
+ if (destination.width == this.width &&
+ destination.height == this.height &&
+ destination.depth == this.depth)
{
CopyTo(destination);
@@ -332,9 +332,7 @@ public readonly unsafe ref partial struct TextureView3D
///
/// The index of the target row to retrieve.
/// The depth of the row to retrieve.
- ///
- /// Throw when either or are out of range.
- ///
+ /// Thrown when either or are out of range.
/// The resulting row .
public Span GetRowSpan(int y, int z)
{
@@ -344,6 +342,23 @@ public readonly unsafe ref partial struct TextureView3D
return new((byte*)this.pointer + (z * this.height * this.strideInBytes) + (y * this.strideInBytes), this.width);
}
+ ///
+ /// Gets a for a depth layer.
+ ///
+ /// The depth of the layer to retrieve.
+ /// Thrown when is out of range.
+ /// The resulting row .
+ public TextureView2D GetDepthView(int z)
+ {
+ Guard.IsInRange(z, 0, this.depth, nameof(z));
+
+ return new(
+ (T*)((byte*)this.pointer + (z * this.height * this.strideInBytes)),
+ this.width,
+ this.height,
+ this.strideInBytes);
+ }
+
///
/// Tries to get a instance, if the underlying buffer is contiguous and small enough.
///
diff --git a/src/ComputeSharp/Shaders/ComputeContext.cs b/src/ComputeSharp/Shaders/ComputeContext.cs
index aa28245a..304ca785 100644
--- a/src/ComputeSharp/Shaders/ComputeContext.cs
+++ b/src/ComputeSharp/Shaders/ComputeContext.cs
@@ -253,6 +253,24 @@ public struct ComputeContext : IDisposable, IAsyncDisposable
commandList.D3D12GraphicsCommandList->Dispatch((uint)groupsX, (uint)groupsY, 1);
}
+ ///
+ /// Inserts a transition for a specific resource.
+ ///
+ /// The to change state for.
+ /// The starting value for the transition.
+ /// The destnation value for the transition.
+ internal readonly unsafe void Transition(
+ ID3D12Resource* d3D12Resource,
+ D3D12_RESOURCE_STATES d3D12ResourceStatesBefore,
+ D3D12_RESOURCE_STATES d3D12ResourceStatesAfter)
+ {
+ ThrowInvalidOperationExceptionIfDeviceIsNull();
+
+ ref CommandList commandList = ref GetCommandList(in this, null);
+
+ commandList.D3D12GraphicsCommandList->TransitionBarrier(d3D12Resource, d3D12ResourceStatesBefore, d3D12ResourceStatesAfter);
+ }
+
///
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Dispose()
diff --git a/src/ComputeSharp/Shaders/Extensions/ComputeContextExtensions.cs b/src/ComputeSharp/Shaders/Extensions/ComputeContextExtensions.cs
index d288d243..0ef89976 100644
--- a/src/ComputeSharp/Shaders/Extensions/ComputeContextExtensions.cs
+++ b/src/ComputeSharp/Shaders/Extensions/ComputeContextExtensions.cs
@@ -1,6 +1,7 @@
using System.Runtime.CompilerServices;
using ComputeSharp.__Internals;
using ComputeSharp.Graphics.Helpers;
+using TerraFX.Interop.DirectX;
#pragma warning disable CS0618
@@ -361,4 +362,38 @@ public static class ComputeContextExtensions
{
context.Run(texture, ref Unsafe.AsRef(in shader));
}
+
+ ///
+ /// Transitions the state of a specific resource.
+ ///
+ /// The type of items stored on the texture.
+ /// The type of pixels used on the GPU side.
+ /// The to use to transition the resource.
+ /// The input instance to transition.
+ /// The state to transition the input resource to.
+ public static unsafe void Transition(this in ComputeContext context, ReadWriteTexture2D texture, ResourceState resourceState)
+ where T : unmanaged, IPixel
+ where TPixel : unmanaged
+ {
+ var states = texture.ValidateAndGetID3D12ResourceAndTransitionStates(context.GraphicsDevice, resourceState, out ID3D12Resource* d3D12Resource);
+
+ context.Transition(d3D12Resource, states.Before, states.After);
+ }
+
+ ///
+ /// Transitions the state of a specific resource.
+ ///
+ /// The type of items stored on the texture.
+ /// The type of pixels used on the GPU side.
+ /// The to use to transition the resource.
+ /// The input instance to transition.
+ /// The state to transition the input resource to.
+ public static unsafe void Transition(this in ComputeContext context, ReadWriteTexture3D texture, ResourceState resourceState)
+ where T : unmanaged, IPixel
+ where TPixel : unmanaged
+ {
+ var states = texture.ValidateAndGetID3D12ResourceAndTransitionStates(context.GraphicsDevice, resourceState, out ID3D12Resource* d3D12Resource);
+
+ context.Transition(d3D12Resource, states.Before, states.After);
+ }
}
diff --git a/tests/ComputeSharp.Tests/Assets/CityAfter1024x1024SamplingAndDashing.png b/tests/ComputeSharp.Tests/Assets/CityAfter1024x1024SamplingAndDashing.png
new file mode 100644
index 00000000..3ee0e09d
Binary files /dev/null and b/tests/ComputeSharp.Tests/Assets/CityAfter1024x1024SamplingAndDashing.png differ
diff --git a/tests/ComputeSharp.Tests/Assets/CityAfter1024x1024SamplingFrom1920x1080AndDashing.png b/tests/ComputeSharp.Tests/Assets/CityAfter1024x1024SamplingFrom1920x1080AndDashing.png
new file mode 100644
index 00000000..32c63715
Binary files /dev/null and b/tests/ComputeSharp.Tests/Assets/CityAfter1024x1024SamplingFrom1920x1080AndDashing.png differ
diff --git a/tests/ComputeSharp.Tests/Assets/CityWith1920x1280Resizing.png b/tests/ComputeSharp.Tests/Assets/CityWith1920x1280Resizing.png
new file mode 100644
index 00000000..aa317531
Binary files /dev/null and b/tests/ComputeSharp.Tests/Assets/CityWith1920x1280Resizing.png differ
diff --git a/tests/ComputeSharp.Tests/ComputeContextTests.cs b/tests/ComputeSharp.Tests/ComputeContextTests.cs
index 86b14b8c..9ba08e37 100644
--- a/tests/ComputeSharp.Tests/ComputeContextTests.cs
+++ b/tests/ComputeSharp.Tests/ComputeContextTests.cs
@@ -1,11 +1,15 @@
using System;
+using System.IO;
using System.Linq;
+using System.Reflection;
using System.Threading.Tasks;
using ComputeSharp.Tests.Attributes;
using ComputeSharp.Tests.Extensions;
using ComputeSharp.Tests.Helpers;
using Microsoft.Toolkit.HighPerformance;
using Microsoft.VisualStudio.TestTools.UnitTesting;
+using SixLabors.ImageSharp;
+using ImageSharpRgba32 = SixLabors.ImageSharp.PixelFormats.Rgba32;
namespace ComputeSharp.Tests;
@@ -883,6 +887,164 @@ public partial class ComputeContextTests
await Task.WhenAll(Enumerable.Range(0, 64).Select(_ => Task.Run(() => TestAsync(device))));
}
+ [CombinatorialTestMethod]
+ [AllDevices]
+ public void Transition_ReadWriteTexture2D(Device device)
+ {
+ _ = device.Get();
+
+ string imagingPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "Imaging");
+ string assetsPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "Assets");
+
+ using var sampled = Image.Load(Path.Combine(assetsPath, "CityAfter1024x1024Sampling.png"));
+
+ using ReadWriteTexture2D source = device.Get().LoadReadWriteTexture2D(Path.Combine(imagingPath, "city.jpg"));
+ using ReadWriteTexture2D destination = device.Get().AllocateReadWriteTexture2D(sampled.Width, sampled.Height);
+
+ using (var context = device.Get().CreateComputeContext())
+ {
+ context.Transition(source, ResourceState.ReadOnly);
+ context.ForEach(destination, new LinearSampling2DPixelShader(source.AsReadOnly()));
+ context.Transition(source, ResourceState.ReadWrite);
+ }
+
+ using var processed = destination.ToImage();
+
+ ImagingTests.TolerantImageComparer.AssertEqual(sampled, processed, 0.0000017f);
+ }
+
+ [CombinatorialTestMethod]
+ [AllDevices]
+ public void Transition_ReadWriteTexture3D(Device device)
+ {
+ _ = device.Get();
+
+ string assetsPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "Assets");
+ string originalPath = Path.Combine(assetsPath, "CityWith1920x1280Resizing.png");
+ string sampledPath = Path.Combine(assetsPath, "CityAfter1024x1024Sampling.png");
+
+ var imageInfo = Image.Identify(originalPath);
+
+ using var sampled = Image.Load(Path.Combine(assetsPath, sampledPath));
+
+ using ReadWriteTexture3D source = device.Get().AllocateReadWriteTexture3D(imageInfo.Width, imageInfo.Height, 3);
+
+ using (UploadTexture2D upload2D = device.Get().LoadUploadTexture2D(originalPath))
+ using (UploadTexture3D upload3D = device.Get().AllocateUploadTexture3D(upload2D.Width, upload2D.Height, 2))
+ {
+ for (int z = 0; z < upload3D.Depth; z++)
+ {
+ upload2D.View.CopyTo(upload3D.View.GetDepthView(z));
+ }
+
+ upload3D.CopyTo(source);
+ }
+
+ using ReadWriteTexture3D destination = device.Get().AllocateReadWriteTexture3D(sampled.Width, sampled.Height, 2);
+
+ using (var context = device.Get().CreateComputeContext())
+ {
+ context.Transition(source, ResourceState.ReadOnly);
+ context.For(destination.Width, destination.Height, destination.Depth, new LinearSampling3DComputeShader(source.AsReadOnly(), destination));
+ context.Transition(source, ResourceState.ReadWrite);
+ }
+
+ for (int z = 0; z < destination.Depth; z++)
+ {
+ using var processed = destination.ToImage(depth: z);
+
+ ImagingTests.TolerantImageComparer.AssertEqual(sampled, processed, 0.000012f);
+ }
+ }
+
+ [CombinatorialTestMethod]
+ [AllDevices]
+ public void TransitionAndWrites_ReadWriteTexture2D(Device device)
+ {
+ _ = device.Get();
+
+ string imagingPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "Imaging");
+ string assetsPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "Assets");
+
+ using var sampled = Image.Load(Path.Combine(assetsPath, "CityAfter1024x1024SamplingAndDashing.png"));
+
+ using ReadWriteTexture2D source = device.Get().LoadReadWriteTexture2D(Path.Combine(imagingPath, "city.jpg"));
+ using ReadWriteTexture2D destination = device.Get().AllocateReadWriteTexture2D(sampled.Width, sampled.Height);
+
+ using (var context = device.Get().CreateComputeContext())
+ {
+ context.For(source.Width, source.Height, new Dotted2DPixelShader(source));
+ context.Transition(source, ResourceState.ReadOnly);
+ context.ForEach(destination, new LinearSampling2DPixelShader(source.AsReadOnly()));
+ context.Transition(source, ResourceState.ReadWrite);
+ context.Fill(source, new Rgba32(0xFF, 0x6A, 0x00, 0x00));
+ }
+
+ using var processed = destination.ToImage();
+
+ ImagingTests.TolerantImageComparer.AssertEqual(sampled, processed, 0.0000017f);
+
+ Rgba32[,] clear = source.ToArray();
+
+ foreach (Rgba32 value in clear)
+ {
+ Assert.AreEqual(value, new Rgba32(0xFF, 0x6A, 0x00, 0x00));
+ }
+ }
+
+ [CombinatorialTestMethod]
+ [AllDevices]
+ public void TransitionAndWrites_ReadWriteTexture3D(Device device)
+ {
+ _ = device.Get();
+
+ string assetsPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "Assets");
+ string originalPath = Path.Combine(assetsPath, "CityWith1920x1280Resizing.png");
+ string sampledPath = Path.Combine(assetsPath, "CityAfter1024x1024SamplingFrom1920x1080AndDashing.png");
+
+ var imageInfo = Image.Identify(originalPath);
+
+ using var sampled = Image.Load(Path.Combine(assetsPath, sampledPath));
+
+ using ReadWriteTexture3D source = device.Get().AllocateReadWriteTexture3D(imageInfo.Width, imageInfo.Height, 3);
+
+ using (UploadTexture2D upload2D = device.Get().LoadUploadTexture2D(originalPath))
+ using (UploadTexture3D upload3D = device.Get().AllocateUploadTexture3D(upload2D.Width, upload2D.Height, 2))
+ {
+ for (int z = 0; z < upload3D.Depth; z++)
+ {
+ upload2D.View.CopyTo(upload3D.View.GetDepthView(z));
+ }
+
+ upload3D.CopyTo(source);
+ }
+
+ using ReadWriteTexture3D destination = device.Get().AllocateReadWriteTexture3D(sampled.Width, sampled.Height, 2);
+
+ using (var context = device.Get().CreateComputeContext())
+ {
+ context.For(source.Width, source.Height, source.Depth, new Dotted3DPixelShader(source));
+ context.Transition(source, ResourceState.ReadOnly);
+ context.For(destination.Width, destination.Height, destination.Depth, new LinearSampling3DComputeShader(source.AsReadOnly(), destination));
+ context.Transition(source, ResourceState.ReadWrite);
+ context.Fill(source, new Rgba32(0xFF, 0x6A, 0x00, 0x00));
+ }
+
+ for (int z = 0; z < destination.Depth; z++)
+ {
+ using var processed = destination.ToImage(depth: z);
+
+ ImagingTests.TolerantImageComparer.AssertEqual(sampled, processed, 0.000012f);
+ }
+
+ Rgba32[,,] clear = source.ToArray();
+
+ foreach (Rgba32 value in clear)
+ {
+ Assert.AreEqual(value, new Rgba32(0xFF, 0x6A, 0x00, 0x00));
+ }
+ }
+
[CombinatorialTestMethod]
[AllDevices]
[ExpectedException(typeof(InvalidOperationException), AllowDerivedTypes = false)]
@@ -1037,4 +1199,85 @@ public partial class ComputeContextTests
return color;
}
}
+
+ [AutoConstructor]
+ internal readonly partial struct LinearSampling2DPixelShader : IPixelShader
+ {
+ public readonly IReadOnlyTexture2D source;
+
+ ///
+ public float4 Execute()
+ {
+ return source[ThreadIds.Normalized.XY];
+ }
+ }
+
+ [AutoConstructor]
+ internal readonly partial struct LinearSampling3DComputeShader : IComputeShader
+ {
+ public readonly IReadOnlyTexture3D source;
+ public readonly IReadWriteTexture3D destination;
+
+ ///
+ public void Execute()
+ {
+ destination[ThreadIds.XYZ] = source[ThreadIds.Normalized.XYZ];
+ }
+ }
+
+ [AutoConstructor]
+ internal readonly partial struct Dotted2DPixelShader : IComputeShader
+ {
+ public readonly IReadWriteTexture2D source;
+
+ ///
+ public void Execute()
+ {
+ bool isHorizontal192CellEven = (ThreadIds.X / 192) % 2 == 0;
+ bool isVertical128CellEven = (ThreadIds.Y / 128) % 2 == 0;
+
+ if (isHorizontal192CellEven != isVertical128CellEven)
+ {
+ if ((ThreadIds.Normalized.X <= 0.5f &&
+ ThreadIds.Normalized.Y <= 0.5) ||
+ (ThreadIds.Normalized.X > 0.5f &&
+ ThreadIds.Normalized.Y > 0.5))
+ {
+ source[ThreadIds.XY] = float4.UnitW;
+ }
+ else
+ {
+ source[ThreadIds.XY] = float4.Zero;
+ }
+ }
+ }
+ }
+
+ [AutoConstructor]
+ internal readonly partial struct Dotted3DPixelShader : IComputeShader
+ {
+ public readonly IReadWriteTexture3D source;
+
+ ///
+ public void Execute()
+ {
+ bool isHorizontal192CellEven = (ThreadIds.X / 192) % 2 == 0;
+ bool isVertical128CellEven = (ThreadIds.Y / 128) % 2 == 0;
+
+ if (isHorizontal192CellEven != isVertical128CellEven)
+ {
+ if ((ThreadIds.Normalized.X <= 0.5f &&
+ ThreadIds.Normalized.Y <= 0.5) ||
+ (ThreadIds.Normalized.X > 0.5f &&
+ ThreadIds.Normalized.Y > 0.5))
+ {
+ source[ThreadIds.XYZ] = float4.UnitW;
+ }
+ else
+ {
+ source[ThreadIds.XYZ] = float4.Zero;
+ }
+ }
+ }
+ }
}
diff --git a/tests/ComputeSharp.Tests/ComputeSharp.Tests.csproj b/tests/ComputeSharp.Tests/ComputeSharp.Tests.csproj
index e8d85f91..ec714ef8 100644
--- a/tests/ComputeSharp.Tests/ComputeSharp.Tests.csproj
+++ b/tests/ComputeSharp.Tests/ComputeSharp.Tests.csproj
@@ -48,7 +48,16 @@
-
+
+ PreserveNewest
+
+
+ PreserveNewest
+
+
+ PreserveNewest
+
+
PreserveNewest
diff --git a/tests/ComputeSharp.Tests/Extensions/ImagingExtensions.cs b/tests/ComputeSharp.Tests/Extensions/ImagingExtensions.cs
index f05cc40f..785bc763 100644
--- a/tests/ComputeSharp.Tests/Extensions/ImagingExtensions.cs
+++ b/tests/ComputeSharp.Tests/Extensions/ImagingExtensions.cs
@@ -36,4 +36,29 @@ public static class ImagingExtensions
return image;
}
+
+ ///
+ /// Creates a new instance with the specified texture data.
+ ///
+ /// The input pixel format used in the texture.
+ /// The target pixel format for the returned image.
+ /// The source instance to read data from.
+ /// The depth layer to read the image from.
+ /// An image with the data from the input texture at a specified depth layer.
+ public static unsafe Image ToImage(this Texture3D texture, int depth)
+ where TFrom : unmanaged
+ where TTo : unmanaged, IPixel
+ {
+ Guard.IsEqualTo(sizeof(TTo), sizeof(TFrom), nameof(TTo));
+
+ Image image = new(texture.Width, texture.Height);
+
+ Assert.IsTrue(image.TryGetSinglePixelSpan(out Span span));
+
+ Span pixels = MemoryMarshal.Cast(span);
+
+ texture.CopyTo(pixels, 0, 0, depth, texture.Width, texture.Height, 1);
+
+ return image;
+ }
}
diff --git a/tests/ComputeSharp.Tests/Texture2DTests.Pixels.cs b/tests/ComputeSharp.Tests/Texture2DTests.Pixels.cs
index e7c7624c..b779e9db 100644
--- a/tests/ComputeSharp.Tests/Texture2DTests.Pixels.cs
+++ b/tests/ComputeSharp.Tests/Texture2DTests.Pixels.cs
@@ -4,6 +4,7 @@ using System.Reflection;
using ComputeSharp.Resources;
using ComputeSharp.Tests.Attributes;
using ComputeSharp.Tests.Extensions;
+using ComputeSharp.Tests.Helpers;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using SixLabors.ImageSharp;
using ImageSharpRgba32 = SixLabors.ImageSharp.PixelFormats.Rgba32;
@@ -46,14 +47,7 @@ public partial class Texture2DTests
}
}
- try
- {
- new Action(Test).Method.GetGenericMethodDefinition().MakeGenericMethod(t, tPixel).Invoke(null, new object[] { device, textureType });
- }
- catch (TargetInvocationException e) when (e.InnerException is not null)
- {
- throw e.InnerException;
- }
+ TestHelper.Run(Test, t, tPixel, device, textureType);
}
[CombinatorialTestMethod]
@@ -120,4 +114,67 @@ public partial class Texture2DTests
return texture[ThreadIds.Normalized.XY];
}
}
+
+ [CombinatorialTestMethod]
+ [AllDevices]
+ [Data(typeof(Bgra32), typeof(float4))]
+ [Data(typeof(R16), typeof(float))]
+ [Data(typeof(R8), typeof(float))]
+ [Data(typeof(Rg16), typeof(float2))]
+ [Data(typeof(Rg32), typeof(float2))]
+ [Data(typeof(Rgba32), typeof(float4))]
+ [Data(typeof(Rgba64), typeof(float4))]
+ public void AsReadOnly_MultipleCalls_SameInstance(Device device, Type t, Type tPixel)
+ {
+ static void Test(Device device)
+ where T : unmanaged, IPixel
+ where TPixel : unmanaged
+ {
+ using ReadWriteTexture2D texture = device.Get().AllocateReadWriteTexture2D(64, 64);
+
+ using (var context = device.Get().CreateComputeContext())
+ {
+ context.Transition(texture, ResourceState.ReadOnly);
+
+ IReadOnlyTexture2D wrapper1 = texture.AsReadOnly();
+
+ Assert.IsNotNull(wrapper1);
+
+ IReadOnlyTexture2D wrapper2 = texture.AsReadOnly();
+
+ Assert.IsNotNull(wrapper2);
+ Assert.AreSame(wrapper1, wrapper2);
+
+ context.Transition(texture, ResourceState.ReadWrite);
+ }
+ }
+
+ TestHelper.Run(Test, t, tPixel, device);
+ }
+
+ [CombinatorialTestMethod]
+ [AllDevices]
+ [Data(typeof(Bgra32), typeof(float4))]
+ [Data(typeof(R16), typeof(float))]
+ [Data(typeof(R8), typeof(float))]
+ [Data(typeof(Rg16), typeof(float2))]
+ [Data(typeof(Rg32), typeof(float2))]
+ [Data(typeof(Rgba32), typeof(float4))]
+ [Data(typeof(Rgba64), typeof(float4))]
+ [ExpectedException(typeof(InvalidOperationException))]
+ public void AsReadOnly_InvalidState_ThrowInvalidOperationException(Device device, Type t, Type tPixel)
+ {
+ static void Test(Device device)
+ where T : unmanaged, IPixel
+ where TPixel : unmanaged
+ {
+ using ReadWriteTexture2D texture = device.Get().AllocateReadWriteTexture2D(64, 64);
+
+ _ = texture.AsReadOnly();
+
+ Assert.Fail();
+ }
+
+ TestHelper.Run(Test, t, tPixel, device);
+ }
}
diff --git a/tests/ComputeSharp.Tests/Texture3DTests.Pixels.cs b/tests/ComputeSharp.Tests/Texture3DTests.Pixels.cs
index ec8f9a64..7a75234b 100644
--- a/tests/ComputeSharp.Tests/Texture3DTests.Pixels.cs
+++ b/tests/ComputeSharp.Tests/Texture3DTests.Pixels.cs
@@ -3,6 +3,7 @@ using System.Reflection;
using ComputeSharp.Resources;
using ComputeSharp.Tests.Attributes;
using ComputeSharp.Tests.Extensions;
+using ComputeSharp.Tests.Helpers;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace ComputeSharp.Tests;
@@ -44,13 +45,69 @@ public partial class Texture3DTests
}
}
- try
+ TestHelper.Run(Test, t, tPixel, device, textureType);
+ }
+
+ [CombinatorialTestMethod]
+ [AllDevices]
+ [Data(typeof(Bgra32), typeof(float4))]
+ [Data(typeof(R16), typeof(float))]
+ [Data(typeof(R8), typeof(float))]
+ [Data(typeof(Rg16), typeof(float2))]
+ [Data(typeof(Rg32), typeof(float2))]
+ [Data(typeof(Rgba32), typeof(float4))]
+ [Data(typeof(Rgba64), typeof(float4))]
+ public void AsReadOnly_MultipleCalls_SameInstance(Device device, Type t, Type tPixel)
+ {
+ static void Test(Device device)
+ where T : unmanaged, IPixel
+ where TPixel : unmanaged
{
- new Action(Test).Method.GetGenericMethodDefinition().MakeGenericMethod(t, tPixel).Invoke(null, new object[] { device, textureType });
+ using ReadWriteTexture3D texture = device.Get().AllocateReadWriteTexture3D(32, 32, 2);
+
+ using (var context = device.Get().CreateComputeContext())
+ {
+ context.Transition(texture, ResourceState.ReadOnly);
+
+ IReadOnlyTexture3D wrapper1 = texture.AsReadOnly();
+
+ Assert.IsNotNull(wrapper1);
+
+ IReadOnlyTexture3D wrapper2 = texture.AsReadOnly();
+
+ Assert.IsNotNull(wrapper2);
+ Assert.AreSame(wrapper1, wrapper2);
+
+ context.Transition(texture, ResourceState.ReadWrite);
+ }
}
- catch (TargetInvocationException e) when (e.InnerException is not null)
+
+ TestHelper.Run(Test, t, tPixel, device);
+ }
+
+ [CombinatorialTestMethod]
+ [AllDevices]
+ [Data(typeof(Bgra32), typeof(float4))]
+ [Data(typeof(R16), typeof(float))]
+ [Data(typeof(R8), typeof(float))]
+ [Data(typeof(Rg16), typeof(float2))]
+ [Data(typeof(Rg32), typeof(float2))]
+ [Data(typeof(Rgba32), typeof(float4))]
+ [Data(typeof(Rgba64), typeof(float4))]
+ [ExpectedException(typeof(InvalidOperationException))]
+ public void AsReadOnly_InvalidState_ThrowInvalidOperationException(Device device, Type t, Type tPixel)
+ {
+ static void Test(Device device)
+ where T : unmanaged, IPixel
+ where TPixel : unmanaged
{
- throw e.InnerException;
+ using ReadWriteTexture3D texture = device.Get().AllocateReadWriteTexture3D(32, 32, 2);
+
+ _ = texture.AsReadOnly();
+
+ Assert.Fail();
}
+
+ TestHelper.Run(Test, t, tPixel, device);
}
}