From a4ded10a109d7ed5598701434524b7c5452c5a2f Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Wed, 3 Feb 2021 18:34:27 +0100 Subject: [PATCH] Added the TextureView2D type over Span2D --- .../ComputeSharp.Graphics.csproj | 1 - .../Abstract/TransferTexture2D{T}.cs | 17 +- .../Debug/TransferTexture2DDebugView{T}.cs | 2 +- .../Resources/Views/TextureView2D{T}.cs | 484 ++++++++++++++++++ .../Resources/Views/ThrowHelper.cs | 70 +++ 5 files changed, 556 insertions(+), 18 deletions(-) create mode 100644 src/ComputeSharp.Graphics/Resources/Views/TextureView2D{T}.cs create mode 100644 src/ComputeSharp.Graphics/Resources/Views/ThrowHelper.cs diff --git a/src/ComputeSharp.Graphics/ComputeSharp.Graphics.csproj b/src/ComputeSharp.Graphics/ComputeSharp.Graphics.csproj index 41957938..56784f00 100644 --- a/src/ComputeSharp.Graphics/ComputeSharp.Graphics.csproj +++ b/src/ComputeSharp.Graphics/ComputeSharp.Graphics.csproj @@ -9,7 +9,6 @@ - diff --git a/src/ComputeSharp.Graphics/Resources/Abstract/TransferTexture2D{T}.cs b/src/ComputeSharp.Graphics/Resources/Abstract/TransferTexture2D{T}.cs index 844d10c0..47e0c28f 100644 --- a/src/ComputeSharp.Graphics/Resources/Abstract/TransferTexture2D{T}.cs +++ b/src/ComputeSharp.Graphics/Resources/Abstract/TransferTexture2D{T}.cs @@ -7,7 +7,6 @@ using ComputeSharp.Graphics.Helpers; using ComputeSharp.Graphics.Resources.Enums; using ComputeSharp.Interop; using Microsoft.Toolkit.Diagnostics; -using Microsoft.Toolkit.HighPerformance.Memory; using TerraFX.Interop; using FX = TerraFX.Interop.Windows; using static TerraFX.Interop.D3D12_FORMAT_SUPPORT1; @@ -94,21 +93,7 @@ namespace ComputeSharp.Resources internal ID3D12Resource* D3D12Resource => this.d3D12Resource; /// - public Memory2D Memory - { - [MethodImpl(MethodImplOptions.AggressiveInlining)] - get - { - ThrowIfDisposed(); - - MemoryManager memoryManager = new(this); - - return new(memoryManager, 0, Height, Width, this.rowPitch); - } - } - - /// - public Span2D Span + public TextureView2D View { [MethodImpl(MethodImplOptions.AggressiveInlining)] get diff --git a/src/ComputeSharp.Graphics/Resources/Debug/TransferTexture2DDebugView{T}.cs b/src/ComputeSharp.Graphics/Resources/Debug/TransferTexture2DDebugView{T}.cs index 8ebde806..a98ed5d5 100644 --- a/src/ComputeSharp.Graphics/Resources/Debug/TransferTexture2DDebugView{T}.cs +++ b/src/ComputeSharp.Graphics/Resources/Debug/TransferTexture2DDebugView{T}.cs @@ -15,7 +15,7 @@ namespace ComputeSharp.Resources.Debug /// The input instance with the items to display. public TransferTexture2DDebugView(TransferTexture2D? texture) { - Items = texture?.Span.ToArray(); + Items = texture?.View.ToArray(); } /// diff --git a/src/ComputeSharp.Graphics/Resources/Views/TextureView2D{T}.cs b/src/ComputeSharp.Graphics/Resources/Views/TextureView2D{T}.cs new file mode 100644 index 00000000..78f3a5af --- /dev/null +++ b/src/ComputeSharp.Graphics/Resources/Views/TextureView2D{T}.cs @@ -0,0 +1,484 @@ +using System; +using System.ComponentModel; +using System.Diagnostics.Contracts; +using System.Runtime.CompilerServices; +using ComputeSharp.Resources.Views; + +#pragma warning disable CS0809 + +namespace ComputeSharp +{ + /// + /// The type represents a view over a 2D texture allocated on host memory, providing APIs to + /// easily manipulate its contents without having to manually deal with the internal alignment requirements of textures. + /// As such, one key difference with and arrays is that the underlying buffer for a + /// instance might not be contiguous in memory. All this logic is handled internally by the + /// type and it is transparent to the user, but note that working over discontiguous buffers has a performance impact. + /// It is recommended to execute as much computation on the GPU side as possible. + /// + /// The type of items in the current instance. + public readonly unsafe ref partial struct TextureView2D + where T : unmanaged + { + // Let's consider a representation of a 2D texture or a generic 2D memory region. + // The data is represented in row-major order as usual, and the 'XX' grid cells + // represent locations that are mapped by a given TextureView2D instance. + // An important aspec to note is that the pitch of each row is calculated in + // bytes, as the texture layout alignment is unrelated to the logical type in use. + // Assuming we a stride that's greater than the logical rows, we might have: + // + // _____________________stride_____... + // pointer__ /________width_________ + // \/ \ + // | -- | -- | |- | -- | -- | -- | -- | -- | -- | -- |_ + // | -- | -- | XX | XX | XX | XX | XX | XX | -- | -- | | + // | -- | -- | XX | XX | XX | XX | XX | XX | -- | -- | | + // | -- | -- | XX | XX | XX | XX | XX | XX | -- | -- | |_height + // | -- | -- | XX | XX | XX | XX | XX | XX | -- | -- |_| + // | -- | -- | -- | -- | -- | -- | -- | -- | -- | -- | + // | -- | -- | -- | -- | -- | -- | -- | -- | -- | -- | + // ..._stride__/ + // + // The stride is used to calculate the offset between each discontiguous row, so + // that any arbitrary memory locations can be used to internally represent a 2D view. + // This gives users much more flexibility when creating spans from data. + + /// + /// The pointer to the first element of the target 2D region. + /// + private readonly T* pointer; + + /// + /// The width of the specified 2D texture. + /// + private readonly int width; + + /// + /// The height of the specified 2D region. + /// + private readonly int height; + + /// + /// The stride of the specified 2D region. + /// + private readonly int strideInBytes; + + /// + /// Initializes a new instance of the struct with the specified parameters. + /// + /// The pointer to the start of the memory area to map. + /// The width of the 2D memory area to map. + /// The height of the 2D memory area to map. + /// The stride in bytes of the 2D memory area to map. + internal TextureView2D(T* pointer, int width, int height, int strideInBytes) + { + this.pointer = pointer; + this.height = height; + this.width = width; + this.strideInBytes = strideInBytes; + } + + /// + /// Gets an empty instance. + /// + public static TextureView2D Empty => default; + + /// + /// Gets a value indicating whether the current instance is empty. + /// + public bool IsEmpty + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => this.width == 0; + } + + /// + /// Gets the length of the current instance. + /// + public int Length + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => this.width * this.height; + } + + /// + /// Gets the width of the underlying 2D memory area. + /// + public int Width + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => this.width; + } + + /// + /// Gets the height of the underlying 2D memory area. + /// + public int Height + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => this.height; + } + + /// + /// Gets the element at the specified zero-based indices. + /// + /// The target row to get the element from. + /// The target column to get the element from. + /// A reference to the element at the specified indices. + /// + /// Thrown when either or are invalid. + /// + public ref T this[int row, int column] + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get + { + if ((uint)row >= (uint)Height || + (uint)column >= (uint)this.width) + { + ThrowHelper.ThrowIndexOutOfRangeException(); + } + + return ref *(((T*)((byte*)this.pointer + (row * this.strideInBytes))) + column); + } + } + + /// + /// Gets the element at the specified zero-based indices. + /// + /// The target row to get the element from. + /// The target column to get the element from. + /// A reference to the element at the specified indices. + /// + /// Thrown when either or are invalid. + /// + public ref T this[Index row, Index column] + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ref this[row.GetOffset(Height), column.GetOffset(this.width)]; + } + + /// + /// Slices the current instance with the specified parameters. + /// + /// The target range of rows to select. + /// The target range of columns to select. + /// + /// Thrown when either or are invalid. + /// + /// A new instance representing a slice of the current one. + public TextureView2D this[Range rows, Range columns] + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get + { + var (row, height) = rows.GetOffsetAndLength(Height); + var (column, width) = columns.GetOffsetAndLength(this.width); + + return Slice(row, column, height, width); + } + } + + /// + /// Clears the contents of the current instance. + /// + public void Clear() + { + if (IsEmpty) + { + return; + } + + if (TryGetSpan(out Span span)) + { + span.Clear(); + } + else + { + for (int i = 0; i < Height; i++) + { + GetRowSpan(i).Clear(); + } + } + } + + /// + /// Copies the contents of this into a destination instance. + /// + /// The destination instance. + /// + /// Thrown when is shorter than the source instance. + /// + public void CopyTo(Span destination) + { + if (IsEmpty) + { + return; + } + + if (TryGetSpan(out Span span)) + { + span.CopyTo(destination); + } + else + { + if (Length > destination.Length) + { + ThrowHelper.ThrowArgumentExceptionForDestinationTooShort(); + } + + for (int i = 0, j = 0; i < Height; i++, j += this.width) + { + GetRowSpan(i).CopyTo(destination.Slice(j)); + } + } + } + + /// + /// Copies the contents of this into a destination instance. + /// 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. + /// + public void CopyTo(TextureView2D destination) + { + if (destination.Height != Height || + destination.width != this.width) + { + ThrowHelper.ThrowArgumentException(); + } + + if (IsEmpty) + { + return; + } + + if (destination.TryGetSpan(out Span span)) + { + CopyTo(span); + } + else + { + for (int i = 0; i < Height; i++) + { + GetRowSpan(i).CopyTo(destination.GetRowSpan(i)); + } + } + } + + /// + /// Attempts to copy the current instance to a destination . + /// + /// The target of the copy operation. + /// Whether or not the operation was successful. + public bool TryCopyTo(Span destination) + { + if (destination.Length >= Length) + { + CopyTo(destination); + + return true; + } + + return false; + } + + /// + /// Attempts to copy the current instance to a destination . + /// + /// The target of the copy operation. + /// Whether or not the operation was successful. + public bool TryCopyTo(TextureView2D destination) + { + if (destination.Height == Height && + destination.Width == this.width) + { + CopyTo(destination); + + return true; + } + + return false; + } + + /// + /// Fills the elements of this span with a specified value. + /// + /// The value to assign to each element of the instance. + public void Fill(T value) + { + if (IsEmpty) + { + return; + } + + if (TryGetSpan(out Span span)) + { + span.Fill(value); + } + else + { + // Fill one row at a time + for (int i = 0; i < Height; i++) + { + GetRowSpan(i).Fill(value); + } + } + } + + /// + /// Returns a reference to the first element within the current instance, with no bounds check. + /// + /// A reference to the first element within the current instance. + [Pure] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public T* DangerousGetAddressAndByteStride(out int strideInBytes) + { + strideInBytes = this.strideInBytes; + + return this.pointer; + } + + /// + /// Slices the current instance with the specified parameters. + /// + /// The target row to map within the current instance. + /// The target column to map within the current instance. + /// The height to map within the current instance. + /// The width to map within the current instance. + /// + /// Thrown when either , or + /// are negative or not within the bounds that are valid for the current instance. + /// + /// A new instance representing a slice of the current one. + [Pure] + public TextureView2D Slice(int row, int column, int height, int width) + { + if ((uint)row >= Height) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForRow(); + } + + if ((uint)column >= this.width) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForColumn(); + } + + if ((uint)height > (Height - row)) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForHeight(); + } + + if ((uint)width > (this.width - column)) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForWidth(); + } + + T* pointer = (T*)((byte*)this.pointer + (row * this.strideInBytes)) + column; + + return new(pointer, width, height, this.strideInBytes); + } + + /// + /// Gets a for a specified row. + /// + /// The index of the target row to retrieve. + /// Throw when is out of range. + /// The resulting row . + [Pure] + public Span GetRowSpan(int row) + { + if ((uint)row >= (uint)Height) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForRow(); + } + + return new((byte*)this.pointer + (row * this.strideInBytes), this.width); + } + + /// + /// Tries to get a instance, if the underlying buffer is contiguous and small enough. + /// + /// The resulting , in case of success. + /// Whether or not was correctly assigned. + public bool TryGetSpan(out Span span) + { + if (this.strideInBytes == this.width) + { + span = new(this.pointer, Length); + + return true; + } + + span = default; + + return false; + } + + /// + /// Copies the contents of the current instance into a new 2D array. + /// + /// A 2D array containing the data in the current instance. + [Pure] + public T[,] ToArray() + { + T[,] array = new T[this.height, this.width]; + + fixed (T* pointer = array) + { + CopyTo(new Span(pointer, Length)); + } + + return array; + } + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + [Obsolete("Equals() on Span will always throw an exception. Use == instead.")] + public override bool Equals(object? obj) + { + throw new NotSupportedException("ComputeSharp.TextureView2D.Equals(object) is not supported"); + } + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + [Obsolete("GetHashCode() on Span will always throw an exception.")] + public override int GetHashCode() + { + throw new NotSupportedException("ComputeSharp.TextureView2D.GetHashCode() is not supported"); + } + + /// + public override string ToString() + { + return $"ComputeSharp.TextureView2D<{typeof(T)}>[{Width}, {Height}]"; + } + + /// + /// Checks whether two instances are equal. + /// + /// The first instance to compare. + /// The second instance to compare. + /// Whether or not and are equal. + public static bool operator ==(TextureView2D left, TextureView2D right) + { + return + left.pointer == right.pointer && + left.width == right.width && + left.height == right.height; + } + + /// + /// Checks whether two instances are not equal. + /// + /// The first instance to compare. + /// The second instance to compare. + /// Whether or not and are not equal. + public static bool operator !=(TextureView2D left, TextureView2D right) + { + return !(left == right); + } + } +} diff --git a/src/ComputeSharp.Graphics/Resources/Views/ThrowHelper.cs b/src/ComputeSharp.Graphics/Resources/Views/ThrowHelper.cs new file mode 100644 index 00000000..aa011264 --- /dev/null +++ b/src/ComputeSharp.Graphics/Resources/Views/ThrowHelper.cs @@ -0,0 +1,70 @@ +using System; + +namespace ComputeSharp.Resources.Views +{ + /// + /// A helper class to throw exceptions for view types. + /// + internal static class ThrowHelper + { + /// + /// Throws an when the target span is too short. + /// + public static void ThrowArgumentExceptionForDestinationTooShort() + { + throw new ArgumentException("The target span is too short to copy all the current items to"); + } + + /// + /// Throws an when the a given coordinate is invalid. + /// + /// + /// Throwing is technically discouraged in the docs, but + /// we're doing that here for consistency with the official type(s) from the BCL. + /// + public static void ThrowIndexOutOfRangeException() + { + throw new IndexOutOfRangeException(); + } + + /// + /// Throws an when more than one parameter are invalid. + /// + public static void ThrowArgumentException() + { + throw new ArgumentException("One or more input parameters were invalid"); + } + + /// + /// Throws an when the "row" parameter is invalid. + /// + public static void ThrowArgumentOutOfRangeExceptionForRow() + { + throw new ArgumentOutOfRangeException("row"); + } + + /// + /// Throws an when the "column" parameter is invalid. + /// + public static void ThrowArgumentOutOfRangeExceptionForColumn() + { + throw new ArgumentOutOfRangeException("column"); + } + + /// + /// Throws an when the "height" parameter is invalid. + /// + public static void ThrowArgumentOutOfRangeExceptionForHeight() + { + throw new ArgumentOutOfRangeException("height"); + } + + /// + /// Throws an when the "width" parameter is invalid. + /// + public static void ThrowArgumentOutOfRangeExceptionForWidth() + { + throw new ArgumentOutOfRangeException("width"); + } + } +}