Merge pull request #196 from Sergio0694/feature/read-write-texture-sampling

Add ComputeContext.Transition APIs to sample writeable textures
このコミットが含まれているのは:
Sergio Pedri authored and GitHub committed 2022-01-17 22:38:52 +01:00
コミット e45aab0eed
23ファイル変更
+1044 -50

検索条件に一致するファイルはありません

+2 -2
ファイルの表示
@@ -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
};
/// <summary>
+56
ファイルの表示
@@ -1173,4 +1173,60 @@ public static partial class GraphicsDeviceExtensions
return texture;
}
/// <summary>
/// Loads a new upload 2D texture with the contents of the specified file.
/// </summary>
/// <typeparam name="T">The type of items to store in the texture.</typeparam>
/// <param name="device">The <see cref="GraphicsDevice"/> instance to use to allocate the texture.</param>
/// <param name="filename">The filename of the image file to load and decode into the texture.</param>
/// <returns>A <see cref="UploadTexture2D{T}"/> instance with the contents of the specified file.</returns>
public static UploadTexture2D<T> LoadUploadTexture2D<T>(this GraphicsDevice device, string filename)
where T : unmanaged
{
Guard.IsNotNull(filename, nameof(filename));
return device.LoadUploadTexture2D<T>(filename.AsSpan());
}
/// <summary>
/// Loads a new upload 2D texture with the contents of the specified file.
/// </summary>
/// <typeparam name="T">The type of items to store in the texture.</typeparam>
/// <param name="device">The <see cref="GraphicsDevice"/> instance to use to allocate the texture.</param>
/// <param name="filename">The filename of the image file to load and decode into the texture.</param>
/// <returns>A <see cref="UploadTexture2D{T}"/> instance with the contents of the specified file.</returns>
public static UploadTexture2D<T> LoadUploadTexture2D<T>(this GraphicsDevice device, ReadOnlySpan<char> filename)
where T : unmanaged
{
return WICHelper.Instance.LoadTexture<T>(device, filename);
}
/// <summary>
/// Loads a new upload 2D texture with the contents of the specified file.
/// </summary>
/// <typeparam name="T">The type of items to store in the texture.</typeparam>
/// <param name="device">The <see cref="GraphicsDevice"/> instance to use to allocate the texture.</param>
/// <param name="span">The buffer with the image data to load and decode into the texture.</param>
/// <returns>A <see cref="UploadTexture2D{T}"/> instance with the contents of the specified file.</returns>
public static UploadTexture2D<T> LoadUploadTexture2D<T>(this GraphicsDevice device, ReadOnlySpan<byte> span)
where T : unmanaged
{
return WICHelper.Instance.LoadTexture<T>(device, span);
}
/// <summary>
/// Loads a new upload 2D texture with the contents of the specified file.
/// </summary>
/// <typeparam name="T">The type of items to store in the texture.</typeparam>
/// <param name="device">The <see cref="GraphicsDevice"/> instance to use to allocate the texture.</param>
/// <param name="stream">The stream with the image data to load and decode into the texture.</param>
/// <returns>A <see cref="UploadTexture2D{T}"/> instance with the contents of the specified file.</returns>
public static UploadTexture2D<T> LoadUploadTexture2D<T>(this GraphicsDevice device, Stream stream)
where T : unmanaged
{
Guard.IsNotNull(stream, nameof(stream));
return WICHelper.Instance.LoadTexture<T>(device, stream);
}
}
+9
ファイルの表示
@@ -40,6 +40,15 @@ public static class GraphicsResourceHelper
/// <param name="device">The target <see cref="GraphicsDevice"/> instance in use.</param>
/// <returns>The the underlying <see cref="ID3D12Resource"/> object.</returns>
ID3D12Resource* ValidateAndGetID3D12Resource(GraphicsDevice device);
/// <summary>
/// Validates the given resource for usage with a specified device, and retrieves the underlying <see cref="ID3D12Resource"/> object, along with the transition states.
/// </summary>
/// <param name="device">The target <see cref="GraphicsDevice"/> instance in use.</param>
/// <param name="resourceState">The target state to transition the resource to.</param>
/// <param name="d3D12Resource">The the underlying <see cref="ID3D12Resource"/> object.</param>
/// <returns>The resource states for <paramref name="d3D12Resource"/>, before and after the transition.</returns>
(D3D12_RESOURCE_STATES Before, D3D12_RESOURCE_STATES After) ValidateAndGetID3D12ResourceAndTransitionStates(GraphicsDevice device, ResourceState resourceState, out ID3D12Resource* d3D12Resource);
}
/// <summary>
+49 -6
ファイルの表示
@@ -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<T> : NativeObject, IGraphicsResource, Gra
/// </summary>
private readonly ID3D12ResourceDescriptorHandles d3D12ResourceDescriptorHandles;
/// <summary>
/// The default <see cref="D3D12_RESOURCE_STATES"/> value for the current resource.
/// </summary>
private readonly D3D12_RESOURCE_STATES d3D12ResourceState;
/// <summary>
/// The <see cref="D3D12_COMMAND_LIST_TYPE"/> value to use for copy operations.
/// </summary>
@@ -59,6 +56,11 @@ public unsafe abstract class Texture2D<T> : NativeObject, IGraphicsResource, Gra
/// </summary>
private readonly D3D12_PLACED_SUBRESOURCE_FOOTPRINT d3D12PlacedSubresourceFootprint;
/// <summary>
/// The current <see cref="D3D12_RESOURCE_STATES"/> value for the current resource.
/// </summary>
private D3D12_RESOURCE_STATES d3D12ResourceState;
/// <summary>
/// Creates a new <see cref="Texture2D{T}"/> instance with the specified parameters.
/// </summary>
@@ -540,6 +542,25 @@ public unsafe abstract class Texture2D<T> : NativeObject, IGraphicsResource, Gra
}
}
/// <summary>
/// Throws an <see cref="InvalidOperationException"/> if the current resource is not in a readonly state.
/// </summary>
[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();
}
}
/// <summary>
/// Throws a <see cref="GraphicsDeviceMismatchException"/> if the target device doesn't match the current one.
/// </summary>
@@ -572,6 +593,22 @@ public unsafe abstract class Texture2D<T> : NativeObject, IGraphicsResource, Gra
return D3D12Resource;
}
/// <inheritdoc cref="GraphicsResourceHelper.IGraphicsResource.ValidateAndGetID3D12ResourceAndTransitionStates(GraphicsDevice, ResourceState, out ID3D12Resource*)"/>
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);
}
/// <inheritdoc/>
D3D12_GPU_DESCRIPTOR_HANDLE GraphicsResourceHelper.IGraphicsResource.ValidateAndGetGpuDescriptorHandle(GraphicsDevice device)
{
@@ -592,4 +629,10 @@ public unsafe abstract class Texture2D<T> : NativeObject, IGraphicsResource, Gra
{
return ValidateAndGetID3D12Resource(device);
}
/// <inheritdoc/>
(D3D12_RESOURCE_STATES, D3D12_RESOURCE_STATES) GraphicsResourceHelper.IGraphicsResource.ValidateAndGetID3D12ResourceAndTransitionStates(GraphicsDevice device, ResourceState resourceState, out ID3D12Resource* d3D12Resource)
{
return ValidateAndGetID3D12ResourceAndTransitionStates(device, resourceState, out d3D12Resource);
}
}
+49 -6
ファイルの表示
@@ -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<T> : NativeObject, IGraphicsResource, Gra
/// </summary>
private readonly ID3D12ResourceDescriptorHandles d3D12ResourceDescriptorHandles;
/// <summary>
/// The default <see cref="D3D12_RESOURCE_STATES"/> value for the current resource.
/// </summary>
private readonly D3D12_RESOURCE_STATES d3D12ResourceState;
/// <summary>
/// The <see cref="D3D12_COMMAND_LIST_TYPE"/> value to use for copy operations.
/// </summary>
@@ -59,6 +56,11 @@ public unsafe abstract class Texture3D<T> : NativeObject, IGraphicsResource, Gra
/// </summary>
private readonly D3D12_PLACED_SUBRESOURCE_FOOTPRINT d3D12PlacedSubresourceFootprint;
/// <summary>
/// The current <see cref="D3D12_RESOURCE_STATES"/> value for the current resource.
/// </summary>
private D3D12_RESOURCE_STATES d3D12ResourceState;
/// <summary>
/// Creates a new <see cref="Texture3D{T}"/> instance with the specified parameters.
/// </summary>
@@ -593,6 +595,25 @@ public unsafe abstract class Texture3D<T> : NativeObject, IGraphicsResource, Gra
}
}
/// <summary>
/// Throws an <see cref="InvalidOperationException"/> if the current resource is not in a readonly state.
/// </summary>
[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();
}
}
/// <summary>
/// Throws a <see cref="GraphicsDeviceMismatchException"/> if the target device doesn't match the current one.
/// </summary>
@@ -625,6 +646,22 @@ public unsafe abstract class Texture3D<T> : NativeObject, IGraphicsResource, Gra
return D3D12Resource;
}
/// <inheritdoc cref="GraphicsResourceHelper.IGraphicsResource.ValidateAndGetID3D12ResourceAndTransitionStates(GraphicsDevice, ResourceState, out ID3D12Resource*)"/>
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);
}
/// <inheritdoc/>
D3D12_GPU_DESCRIPTOR_HANDLE GraphicsResourceHelper.IGraphicsResource.ValidateAndGetGpuDescriptorHandle(GraphicsDevice device)
{
@@ -645,4 +682,10 @@ public unsafe abstract class Texture3D<T> : NativeObject, IGraphicsResource, Gra
{
return ValidateAndGetID3D12Resource(device);
}
/// <inheritdoc/>
(D3D12_RESOURCE_STATES, D3D12_RESOURCE_STATES) GraphicsResourceHelper.IGraphicsResource.ValidateAndGetID3D12ResourceAndTransitionStates(GraphicsDevice device, ResourceState resourceState, out ID3D12Resource* d3D12Resource)
{
return ValidateAndGetID3D12ResourceAndTransitionStates(device, resourceState, out d3D12Resource);
}
}
+17
ファイルの表示
@@ -0,0 +1,17 @@
namespace ComputeSharp;
/// <summary>
/// An <see langword="enum"/> that indicates the state of a resource after a given transition.
/// </summary>
public enum ResourceState
{
/// <summary>
/// A readonly resource, that can only be read from by the GPU and supports texture sampling.
/// </summary>
ReadOnly,
/// <summary>
/// A read write resource, with both read and write access for the GPU, but without support for texture sampling.
/// </summary>
ReadWrite
}
+33
ファイルの表示
@@ -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;
/// <summary>
/// A helper type with utility methods for <see cref="ResourceState"/>.
/// </summary>
internal static class ResourceStateHelper
{
/// <summary>
/// Gets the corresponding <see cref="D3D12_RESOURCE_STATES"/> value for the input resource state.
/// </summary>
/// <returns>The <see cref="D3D12_RESOURCE_STATES"/> value corresponding to the input resource state.</returns>
/// <exception cref="System.ArgumentException">Thrown when the input value is not valid.</exception>
[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<D3D12_RESOURCE_STATES>("The target resource state is not valid.");
}
}
+168
ファイルの表示
@@ -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;
/// <inheritdoc/>
partial class ReadWriteTexture2D<T, TPixel>
{
/// <summary>
/// The wrapping <see cref="ReadOnly"/> instance, if available.
/// </summary>
private ReadOnly? readOnlyWrapper;
/// <summary>
/// Retrieves a wrapping <see cref="IReadOnlyTexture2D{TPixel}"/> instance for the current resource.
/// </summary>
/// <returns>An <see cref="IReadOnlyTexture2D{TPixel}"/> instance wrapping the current resource.</returns>
/// <remarks>
/// <para>The returned instance can be used in a shader to enable texture sampling.</para>
/// <para>
/// 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 <see cref="ComputeContextExtensions.Transition{T, TPixel}(in ComputeContext, ReadWriteTexture2D{T, TPixel}, ResourceState)"/>,
/// and specify <see cref="ResourceState.ReadOnly"/>. After that, <see cref="AsReadOnly"/> 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 <see cref="ComputeContext"/>, 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 <see cref="ResourceState.ReadWrite"/>. Failing to do so results in undefined behavior.
/// </para>
/// </remarks>
/// <exception cref="ObjectDisposedException">Thrown if the current instance or its associated device are disposed.</exception>
/// <exception cref="InvalidOperationException">Thrown if the current instance is not in a readonly state.</exception>
public IReadOnlyTexture2D<TPixel> 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<T, TPixel> texture)
{
return texture.readOnlyWrapper = new(texture);
}
return InitializeWrapper(this);
}
/// <inheritdoc/>
protected override void OnDispose()
{
base.OnDispose();
this.readOnlyWrapper?.Dispose();
}
/// <summary>
/// A wrapper for a <see cref="ReadWriteTexture2D{T, TPixel}"/> resource that has been temporarily transitioned to readonly.
/// </summary>
private sealed unsafe class ReadOnly : NativeObject, IReadOnlyTexture2D<TPixel>, GraphicsResourceHelper.IGraphicsResource
{
/// <summary>
/// The owning <see cref="ReadWriteTexture2D{T, TPixel}"/> instance being wrapped.
/// </summary>
private readonly ReadWriteTexture2D<T, TPixel> owner;
/// <summary>
/// The <see cref="ID3D12ResourceDescriptorHandles"/> instance for the current resource.
/// </summary>
private readonly ID3D12ResourceDescriptorHandles d3D12ResourceDescriptorHandles;
/// <summary>
/// Creates a new <see cref="ReadOnly"/> instance with the specified parameters.
/// </summary>
/// <param name="owner">The owning <see cref="ReadWriteTexture2D{T, TPixel}"/> instance to wrap.</param>
public ReadOnly(ReadWriteTexture2D<T, TPixel> owner)
{
this.owner = owner;
owner.GraphicsDevice.RentShaderResourceViewDescriptorHandles(out this.d3D12ResourceDescriptorHandles);
owner.GraphicsDevice.D3D12Device->CreateShaderResourceView(owner.D3D12Resource, DXGIFormatHelper.GetForType<T>(), D3D12_SRV_DIMENSION_TEXTURE2D, this.d3D12ResourceDescriptorHandles.D3D12CpuDescriptorHandle);
}
/// <inheritdoc/>
public ref readonly TPixel this[int x, int y] => throw new InvalidExecutionContextException($"{typeof(ReadWriteTexture2D<T, TPixel>.ReadOnly)}[{typeof(int)}, {typeof(int)}]");
/// <inheritdoc/>
public ref readonly TPixel this[Int2 xy] => throw new InvalidExecutionContextException($"{typeof(ReadWriteTexture2D<T, TPixel>.ReadOnly)}[{typeof(Int2)}]");
/// <inheritdoc/>
public ref readonly TPixel this[float u, float v] => throw new InvalidExecutionContextException($"{typeof(ReadWriteTexture2D<T, TPixel>.ReadOnly)}[{typeof(float)}, {typeof(float)}]");
/// <inheritdoc/>
public ref readonly TPixel this[Float2 uv] => throw new InvalidExecutionContextException($"{typeof(ReadWriteTexture2D<T, TPixel>.ReadOnly)}[{typeof(Float2)}]");
/// <inheritdoc/>
public int Width => this.owner.Width;
/// <inheritdoc/>
public int Height => this.owner.Height;
/// <inheritdoc/>
public GraphicsDevice GraphicsDevice => this.owner.GraphicsDevice;
/// <inheritdoc/>
D3D12_GPU_DESCRIPTOR_HANDLE GraphicsResourceHelper.IGraphicsResource.ValidateAndGetGpuDescriptorHandle(GraphicsDevice device)
{
ThrowIfDisposed();
this.owner.ThrowIfDisposed();
this.owner.ThrowIfDeviceMismatch(device);
return this.d3D12ResourceDescriptorHandles.D3D12GpuDescriptorHandle;
}
/// <inheritdoc/>
(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.");
}
/// <inheritdoc/>
ID3D12Resource* GraphicsResourceHelper.IGraphicsResource.ValidateAndGetID3D12Resource(GraphicsDevice device)
{
ThrowIfDisposed();
this.owner.ThrowIfDisposed();
this.owner.ThrowIfDeviceMismatch(device);
return this.owner.D3D12Resource;
}
/// <inheritdoc/>
(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.");
}
/// <inheritdoc/>
protected override void OnDispose()
{
if (this.owner.GraphicsDevice is GraphicsDevice device)
{
device.ReturnShaderResourceViewDescriptorHandles(in this.d3D12ResourceDescriptorHandles);
}
}
}
}
+1 -1
ファイルの表示
@@ -14,7 +14,7 @@ namespace ComputeSharp;
/// <typeparam name="TPixel">The type of pixels used on the GPU side.</typeparam>
[DebuggerTypeProxy(typeof(Texture2DDebugView<>))]
[DebuggerDisplay("{ToString(),raw}")]
public sealed class ReadWriteTexture2D<T, TPixel> : Texture2D<T>, IReadWriteTexture2D<TPixel>
public sealed partial class ReadWriteTexture2D<T, TPixel> : Texture2D<T>, IReadWriteTexture2D<TPixel>
where T : unmanaged, IPixel<T, TPixel>
where TPixel : unmanaged
{
+168
ファイルの表示
@@ -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;
/// <inheritdoc/>
partial class ReadWriteTexture3D<T, TPixel>
{
/// <summary>
/// The wrapping <see cref="ReadOnly"/> instance, if available.
/// </summary>
private ReadOnly? readOnlyWrapper;
/// <summary>
/// Retrieves a wrapping <see cref="IReadOnlyTexture3D{TPixel}"/> instance for the current resource.
/// </summary>
/// <returns>An <see cref="IReadOnlyTexture3D{TPixel}"/> instance wrapping the current resource.</returns>
/// <remarks>
/// <para>The returned instance can be used in a shader to enable texture sampling.</para>
/// <para>
/// 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 <see cref="ComputeContextExtensions.Transition{T, TPixel}(in ComputeContext, ReadWriteTexture3D{T, TPixel}, ResourceState)"/>,
/// and specify <see cref="ResourceState.ReadOnly"/>. After that, <see cref="AsReadOnly"/> 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 <see cref="ComputeContext"/>, 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 <see cref="ResourceState.ReadWrite"/>. Failing to do so results in undefined behavior.
/// </para>
/// </remarks>
/// <exception cref="ObjectDisposedException">Thrown if the current instance or its associated device are disposed.</exception>
/// <exception cref="InvalidOperationException">Thrown if the current instance is not in a readonly state.</exception>
public IReadOnlyTexture3D<TPixel> AsReadOnly()
{
GraphicsDevice.ThrowIfDisposed();
ThrowIfDisposed();
ThrowIfIsNotInReadOnlyState();
ReadOnly? readOnlyWrapper = this.readOnlyWrapper;
if (readOnlyWrapper is not null)
{
return readOnlyWrapper;
}
[MethodImpl(MethodImplOptions.NoInlining)]
static ReadOnly InitializeWrapper(ReadWriteTexture3D<T, TPixel> texture)
{
return texture.readOnlyWrapper = new(texture);
}
return InitializeWrapper(this);
}
/// <inheritdoc/>
protected override void OnDispose()
{
base.OnDispose();
this.readOnlyWrapper?.Dispose();
}
/// <summary>
/// A wrapper for a <see cref="ReadWriteTexture3D{T, TPixel}"/> resource that has been temporarily transitioned to readonly.
/// </summary>
private sealed unsafe class ReadOnly : NativeObject, IReadOnlyTexture3D<TPixel>, GraphicsResourceHelper.IGraphicsResource
{
/// <summary>
/// The owning <see cref="ReadWriteTexture3D{T, TPixel}"/> instance being wrapped.
/// </summary>
private readonly ReadWriteTexture3D<T, TPixel> owner;
/// <summary>
/// The <see cref="ID3D12ResourceDescriptorHandles"/> instance for the current resource.
/// </summary>
private readonly ID3D12ResourceDescriptorHandles d3D12ResourceDescriptorHandles;
/// <summary>
/// Creates a new <see cref="ReadOnly"/> instance with the specified parameters.
/// </summary>
/// <param name="owner">The owning <see cref="ReadWriteTexture3D{T, TPixel}"/> instance to wrap.</param>
public ReadOnly(ReadWriteTexture3D<T, TPixel> owner)
{
this.owner = owner;
owner.GraphicsDevice.RentShaderResourceViewDescriptorHandles(out this.d3D12ResourceDescriptorHandles);
owner.GraphicsDevice.D3D12Device->CreateShaderResourceView(owner.D3D12Resource, DXGIFormatHelper.GetForType<T>(), D3D12_SRV_DIMENSION_TEXTURE3D, this.d3D12ResourceDescriptorHandles.D3D12CpuDescriptorHandle);
}
/// <inheritdoc/>
public ref readonly TPixel this[int x, int y, int z] => throw new InvalidExecutionContextException($"{typeof(ReadWriteTexture3D<T, TPixel>.ReadOnly)}[{typeof(int)}, {typeof(int)}, {typeof(int)}]");
/// <inheritdoc/>
public ref readonly TPixel this[Int3 xyz] => throw new InvalidExecutionContextException($"{typeof(ReadWriteTexture3D<T, TPixel>.ReadOnly)}[{typeof(Int3)}]");
/// <inheritdoc/>
public ref readonly TPixel this[float u, float v, float w] => throw new InvalidExecutionContextException($"{typeof(ReadWriteTexture3D<T, TPixel>.ReadOnly)}[{typeof(float)}, {typeof(float)}, {typeof(float)}]");
/// <inheritdoc/>
public ref readonly TPixel this[Float3 uvw] => throw new InvalidExecutionContextException($"{typeof(ReadWriteTexture3D<T, TPixel>.ReadOnly)}[{typeof(Float3)}]");
/// <inheritdoc/>
public int Width => this.owner.Width;
/// <inheritdoc/>
public int Height => this.owner.Height;
/// <inheritdoc/>
public int Depth => this.owner.Depth;
/// <inheritdoc/>
public GraphicsDevice GraphicsDevice => this.owner.GraphicsDevice;
/// <inheritdoc/>
D3D12_GPU_DESCRIPTOR_HANDLE GraphicsResourceHelper.IGraphicsResource.ValidateAndGetGpuDescriptorHandle(GraphicsDevice device)
{
ThrowIfDisposed();
this.owner.ThrowIfDisposed();
this.owner.ThrowIfDeviceMismatch(device);
return this.d3D12ResourceDescriptorHandles.D3D12GpuDescriptorHandle;
}
/// <inheritdoc/>
(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.");
}
/// <inheritdoc/>
ID3D12Resource* GraphicsResourceHelper.IGraphicsResource.ValidateAndGetID3D12Resource(GraphicsDevice device)
{
ThrowIfDisposed();
this.owner.ThrowIfDisposed();
this.owner.ThrowIfDeviceMismatch(device);
return this.owner.D3D12Resource;
}
/// <inheritdoc/>
(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.");
}
/// <inheritdoc/>
protected override void OnDispose()
{
if (this.owner.GraphicsDevice is GraphicsDevice device)
{
device.ReturnShaderResourceViewDescriptorHandles(in this.d3D12ResourceDescriptorHandles);
}
}
}
}
+1 -1
ファイルの表示
@@ -14,7 +14,7 @@ namespace ComputeSharp;
/// <typeparam name="TPixel">The type of pixels used on the GPU side.</typeparam>
[DebuggerTypeProxy(typeof(Texture3DDebugView<>))]
[DebuggerDisplay("{ToString(),raw}")]
public sealed class ReadWriteTexture3D<T, TPixel> : Texture3D<T>, IReadWriteTexture3D<TPixel>
public sealed partial class ReadWriteTexture3D<T, TPixel> : Texture3D<T>, IReadWriteTexture3D<TPixel>
where T : unmanaged, IPixel<T, TPixel>
where TPixel : unmanaged
{
+10 -12
ファイルの表示
@@ -55,7 +55,7 @@ public readonly unsafe ref partial struct TextureView2D<T>
/// <summary>
/// The row pitch of the specified 2D region.
/// </summary>
private readonly int pitchInBytes;
private readonly int strideInBytes;
/// <summary>
/// Initializes a new instance of the <see cref="TextureView2D{T}"/> struct with the specified parameters.
@@ -69,7 +69,7 @@ public readonly unsafe ref partial struct TextureView2D<T>
this.pointer = pointer;
this.width = width;
this.height = height;
this.pitchInBytes = pitchInBytes;
this.strideInBytes = pitchInBytes;
}
/// <summary>
@@ -130,7 +130,7 @@ public readonly unsafe ref partial struct TextureView2D<T>
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<T>
/// For this API to succeed, the target <see cref="TextureView2D{T}"/> has to have the same shape as the current one.
/// </summary>
/// <param name="destination">The destination <see cref="TextureView2D{T}"/> instance.</param>
/// <exception cref="ArgumentException">
/// Thrown when <paramref name="destination" /> is shorter than the source <see cref="TextureView2D{T}"/> instance.
/// </exception>
/// <exception cref="ArgumentException">Thrown when <paramref name="destination"/> doesn't match the size of the current <see cref="TextureView2D{T}"/> instance.</exception>
public void CopyTo(TextureView2D<T> 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<T>
/// <returns>Whether or not the operation was successful.</returns>
public bool TryCopyTo(TextureView2D<T> 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<T>
[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<T>
/// Gets a <see cref="Span{T}"/> for a specified row.
/// </summary>
/// <param name="y">The index of the target row to retrieve.</param>
/// <exception cref="ArgumentOutOfRangeException">Throw when <paramref name="y"/> is out of range.</exception>
/// <exception cref="ArgumentOutOfRangeException">Thrown when <paramref name="y"/> is out of range.</exception>
/// <returns>The resulting row <see cref="Span{T}"/>.</returns>
public Span<T> 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);
}
/// <summary>
@@ -311,7 +309,7 @@ public readonly unsafe ref partial struct TextureView2D<T>
/// <returns>Whether or not <paramref name="span"/> was correctly assigned.</returns>
public bool TryGetSpan(out Span<T> span)
{
if (this.pitchInBytes == this.width)
if (this.strideInBytes == this.width)
{
span = new(this.pointer, Length);
+24 -9
ファイルの表示
@@ -221,13 +221,12 @@ public readonly unsafe ref partial struct TextureView3D<T>
/// For this API to succeed, the target <see cref="TextureView3D{T}"/> has to have the same shape as the current one.
/// </summary>
/// <param name="destination">The destination <see cref="TextureView3D{T}"/> instance.</param>
/// <exception cref="ArgumentException">
/// Thrown when <paramref name="destination" /> is shorter than the source <see cref="TextureView3D{T}"/> instance.
/// </exception>
/// <exception cref="ArgumentException">Thrown when <paramref name="destination"/> doesn't match the size of the current <see cref="TextureView3D{T}"/> instance.</exception>
public void CopyTo(TextureView3D<T> 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<T>
/// <returns>Whether or not the operation was successful.</returns>
public bool TryCopyTo(TextureView3D<T> 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<T>
/// </summary>
/// <param name="y">The index of the target row to retrieve.</param>
/// <param name="z">The depth of the row to retrieve.</param>
/// <exception cref="ArgumentOutOfRangeException">
/// Throw when either <paramref name="y"/> or <paramref name="z"/> are out of range.
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">Thrown when either <paramref name="y"/> or <paramref name="z"/> are out of range.</exception>
/// <returns>The resulting row <see cref="Span{T}"/>.</returns>
public Span<T> GetRowSpan(int y, int z)
{
@@ -344,6 +342,23 @@ public readonly unsafe ref partial struct TextureView3D<T>
return new((byte*)this.pointer + (z * this.height * this.strideInBytes) + (y * this.strideInBytes), this.width);
}
/// <summary>
/// Gets a <see cref="TextureView2D{T}"/> for a depth layer.
/// </summary>
/// <param name="z">The depth of the layer to retrieve.</param>
/// <exception cref="ArgumentOutOfRangeException">Thrown when <paramref name="z"/> is out of range.</exception>
/// <returns>The resulting row <see cref="TextureView2D{T}"/>.</returns>
public TextureView2D<T> 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);
}
/// <summary>
/// Tries to get a <see cref="Span{T}"/> instance, if the underlying buffer is contiguous and small enough.
/// </summary>
+18
ファイルの表示
@@ -253,6 +253,24 @@ public struct ComputeContext : IDisposable, IAsyncDisposable
commandList.D3D12GraphicsCommandList->Dispatch((uint)groupsX, (uint)groupsY, 1);
}
/// <summary>
/// Inserts a transition for a specific resource.
/// </summary>
/// <param name="d3D12Resource">The <see cref="ID3D12Resource"/> to change state for.</param>
/// <param name="d3D12ResourceStatesBefore">The starting <see cref="D3D12_RESOURCE_STATES"/> value for the transition.</param>
/// <param name="d3D12ResourceStatesAfter">The destnation <see cref="D3D12_RESOURCE_STATES"/> value for the transition.</param>
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);
}
/// <inheritdoc/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Dispose()
+35
ファイルの表示
@@ -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));
}
/// <summary>
/// Transitions the state of a specific resource.
/// </summary>
/// <typeparam name="T">The type of items stored on the texture.</typeparam>
/// <typeparam name="TPixel">The type of pixels used on the GPU side.</typeparam>
/// <param name="context">The <see cref="ComputeContext"/> to use to transition the resource.</param>
/// <param name="texture">The input <see cref="ReadWriteTexture2D{T,TPixel}"/> instance to transition.</param>
/// <param name="resourceState">The state to transition the input resource to.</param>
public static unsafe void Transition<T, TPixel>(this in ComputeContext context, ReadWriteTexture2D<T, TPixel> texture, ResourceState resourceState)
where T : unmanaged, IPixel<T, TPixel>
where TPixel : unmanaged
{
var states = texture.ValidateAndGetID3D12ResourceAndTransitionStates(context.GraphicsDevice, resourceState, out ID3D12Resource* d3D12Resource);
context.Transition(d3D12Resource, states.Before, states.After);
}
/// <summary>
/// Transitions the state of a specific resource.
/// </summary>
/// <typeparam name="T">The type of items stored on the texture.</typeparam>
/// <typeparam name="TPixel">The type of pixels used on the GPU side.</typeparam>
/// <param name="context">The <see cref="ComputeContext"/> to use to transition the resource.</param>
/// <param name="texture">The input <see cref="ReadWriteTexture2D{T,TPixel}"/> instance to transition.</param>
/// <param name="resourceState">The state to transition the input resource to.</param>
public static unsafe void Transition<T, TPixel>(this in ComputeContext context, ReadWriteTexture3D<T, TPixel> texture, ResourceState resourceState)
where T : unmanaged, IPixel<T, TPixel>
where TPixel : unmanaged
{
var states = texture.ValidateAndGetID3D12ResourceAndTransitionStates(context.GraphicsDevice, resourceState, out ID3D12Resource* d3D12Resource);
context.Transition(d3D12Resource, states.Before, states.After);
}
}
バイナリファイルは表示されません。

変更後

幅:  |  高さ:  |  サイズ: 796 KiB

バイナリファイルは表示されません。

変更後

幅:  |  高さ:  |  サイズ: 645 KiB

バイナリファイルは表示されません。

変更後

幅:  |  高さ:  |  サイズ: 2.4 MiB

+243
ファイルの表示
@@ -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<ImageSharpRgba32>(Path.Combine(assetsPath, "CityAfter1024x1024Sampling.png"));
using ReadWriteTexture2D<Rgba32, float4> source = device.Get().LoadReadWriteTexture2D<Rgba32, float4>(Path.Combine(imagingPath, "city.jpg"));
using ReadWriteTexture2D<Rgba32, float4> destination = device.Get().AllocateReadWriteTexture2D<Rgba32, float4>(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<Rgba32, ImageSharpRgba32>();
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<ImageSharpRgba32>(Path.Combine(assetsPath, sampledPath));
using ReadWriteTexture3D<Rgba32, float4> source = device.Get().AllocateReadWriteTexture3D<Rgba32, float4>(imageInfo.Width, imageInfo.Height, 3);
using (UploadTexture2D<Rgba32> upload2D = device.Get().LoadUploadTexture2D<Rgba32>(originalPath))
using (UploadTexture3D<Rgba32> upload3D = device.Get().AllocateUploadTexture3D<Rgba32>(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<Rgba32, float4> destination = device.Get().AllocateReadWriteTexture3D<Rgba32, float4>(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<Rgba32, ImageSharpRgba32>(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<ImageSharpRgba32>(Path.Combine(assetsPath, "CityAfter1024x1024SamplingAndDashing.png"));
using ReadWriteTexture2D<Rgba32, float4> source = device.Get().LoadReadWriteTexture2D<Rgba32, float4>(Path.Combine(imagingPath, "city.jpg"));
using ReadWriteTexture2D<Rgba32, float4> destination = device.Get().AllocateReadWriteTexture2D<Rgba32, float4>(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<Rgba32, ImageSharpRgba32>();
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<ImageSharpRgba32>(Path.Combine(assetsPath, sampledPath));
using ReadWriteTexture3D<Rgba32, float4> source = device.Get().AllocateReadWriteTexture3D<Rgba32, float4>(imageInfo.Width, imageInfo.Height, 3);
using (UploadTexture2D<Rgba32> upload2D = device.Get().LoadUploadTexture2D<Rgba32>(originalPath))
using (UploadTexture3D<Rgba32> upload3D = device.Get().AllocateUploadTexture3D<Rgba32>(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<Rgba32, float4> destination = device.Get().AllocateReadWriteTexture3D<Rgba32, float4>(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<Rgba32, ImageSharpRgba32>(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<float4>
{
public readonly IReadOnlyTexture2D<float4> source;
/// <inheritdoc/>
public float4 Execute()
{
return source[ThreadIds.Normalized.XY];
}
}
[AutoConstructor]
internal readonly partial struct LinearSampling3DComputeShader : IComputeShader
{
public readonly IReadOnlyTexture3D<float4> source;
public readonly IReadWriteTexture3D<float4> destination;
/// <inheritdoc/>
public void Execute()
{
destination[ThreadIds.XYZ] = source[ThreadIds.Normalized.XYZ];
}
}
[AutoConstructor]
internal readonly partial struct Dotted2DPixelShader : IComputeShader
{
public readonly IReadWriteTexture2D<float4> source;
/// <inheritdoc/>
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<float4> source;
/// <inheritdoc/>
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;
}
}
}
}
}
+10 -1
ファイルの表示
@@ -48,7 +48,16 @@
<ItemGroup>
<None Include="..\..\samples\ComputeSharp.ImageProcessing\city.jpg" Link="Imaging\city.jpg" CopyToOutputDirectory="PreserveNewest" />
<None Include="..\..\samples\ComputeSharp.SwapChain\Textures\RustyMetal.png" Link="Shaders\Textures\RustyMetal.png" CopyToOutputDirectory="PreserveNewest" />
<None Update="Assets/CityAfter1024x1024Sampling.png">
<None Update="Assets\CityAfter1024x1024Sampling.png">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Update="Assets\CityAfter1024x1024SamplingAndDashing.png">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Update="Assets\CityAfter1024x1024SamplingFrom1920x1080AndDashing.png">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Update="Assets\CityWith1920x1280Resizing.png">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Update="Assets\HelloWorld.png">
+25
ファイルの表示
@@ -36,4 +36,29 @@ public static class ImagingExtensions
return image;
}
/// <summary>
/// Creates a new <see cref="Image{TPixel}"/> instance with the specified texture data.
/// </summary>
/// <typeparam name="TFrom">The input pixel format used in the texture.</typeparam>
/// <typeparam name="TTo">The target pixel format for the returned image.</typeparam>
/// <param name="texture">The source <see cref="Texture3D{T}"/> instance to read data from.</param>
/// <param name="depth">The depth layer to read the image from.</param>
/// <returns>An image with the data from the input texture at a specified depth layer.</returns>
public static unsafe Image<TTo> ToImage<TFrom, TTo>(this Texture3D<TFrom> texture, int depth)
where TFrom : unmanaged
where TTo : unmanaged, IPixel<TTo>
{
Guard.IsEqualTo(sizeof(TTo), sizeof(TFrom), nameof(TTo));
Image<TTo> image = new(texture.Width, texture.Height);
Assert.IsTrue(image.TryGetSinglePixelSpan(out Span<TTo> span));
Span<TFrom> pixels = MemoryMarshal.Cast<TTo, TFrom>(span);
texture.CopyTo(pixels, 0, 0, depth, texture.Width, texture.Height, 1);
return image;
}
}
+65 -8
ファイルの表示
@@ -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<Device, Type>(Test<Rgba32, float4>).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<Rgba32, float4>, 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<T, TPixel>(Device device)
where T : unmanaged, IPixel<T, TPixel>
where TPixel : unmanaged
{
using ReadWriteTexture2D<T, TPixel> texture = device.Get().AllocateReadWriteTexture2D<T, TPixel>(64, 64);
using (var context = device.Get().CreateComputeContext())
{
context.Transition(texture, ResourceState.ReadOnly);
IReadOnlyTexture2D<TPixel> wrapper1 = texture.AsReadOnly();
Assert.IsNotNull(wrapper1);
IReadOnlyTexture2D<TPixel> wrapper2 = texture.AsReadOnly();
Assert.IsNotNull(wrapper2);
Assert.AreSame(wrapper1, wrapper2);
context.Transition(texture, ResourceState.ReadWrite);
}
}
TestHelper.Run(Test<Rgba32, float4>, 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<T, TPixel>(Device device)
where T : unmanaged, IPixel<T, TPixel>
where TPixel : unmanaged
{
using ReadWriteTexture2D<T, TPixel> texture = device.Get().AllocateReadWriteTexture2D<T, TPixel>(64, 64);
_ = texture.AsReadOnly();
Assert.Fail();
}
TestHelper.Run(Test<Rgba32, float4>, t, tPixel, device);
}
}
+61 -4
ファイルの表示
@@ -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<Rgba32, float4>, 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<T, TPixel>(Device device)
where T : unmanaged, IPixel<T, TPixel>
where TPixel : unmanaged
{
new Action<Device, Type>(Test<Rgba32, float4>).Method.GetGenericMethodDefinition().MakeGenericMethod(t, tPixel).Invoke(null, new object[] { device, textureType });
using ReadWriteTexture3D<T, TPixel> texture = device.Get().AllocateReadWriteTexture3D<T, TPixel>(32, 32, 2);
using (var context = device.Get().CreateComputeContext())
{
context.Transition(texture, ResourceState.ReadOnly);
IReadOnlyTexture3D<TPixel> wrapper1 = texture.AsReadOnly();
Assert.IsNotNull(wrapper1);
IReadOnlyTexture3D<TPixel> 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<Rgba32, float4>, 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<T, TPixel>(Device device)
where T : unmanaged, IPixel<T, TPixel>
where TPixel : unmanaged
{
throw e.InnerException;
using ReadWriteTexture3D<T, TPixel> texture = device.Get().AllocateReadWriteTexture3D<T, TPixel>(32, 32, 2);
_ = texture.AsReadOnly();
Assert.Fail();
}
TestHelper.Run(Test<Rgba32, float4>, t, tPixel, device);
}
}