diff --git a/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor{TPixel}.cs b/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor{TPixel}.cs index 71144b44..f22b9abd 100644 --- a/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor{TPixel}.cs +++ b/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor{TPixel}.cs @@ -261,7 +261,7 @@ namespace ComputeSharp.BokehBlur.Processors // Preliminary gamma highlight pass using IMemoryOwner source4 = GetExposedVector4Buffer(memory); - using ReadOnlyBuffer sourceBuffer = Gpu.Default.AllocateReadOnlyBuffer(source4.Memory.Span); + using ReadOnlyBuffer sourceBuffer = Gpu.Default.AllocateReadOnlyBuffer(source4.Memory.Span); using ReadWriteBuffer processingBuffer = Gpu.Default.AllocateReadWriteBuffer(sourceBuffer.Length); using ReadWriteBuffer firstPassBuffer = Gpu.Default.AllocateReadWriteBuffer(sourceBuffer.Length); using ReadOnlyBuffer kernelBuffer = Gpu.Default.AllocateReadOnlyBuffer(KernelSize); diff --git a/samples/ComputeSharp.ImageProcessing/Processors/HlslGaussianBlurProcessor{TPixel}.cs b/samples/ComputeSharp.ImageProcessing/Processors/HlslGaussianBlurProcessor{TPixel}.cs index d80307a0..31ca80cc 100644 --- a/samples/ComputeSharp.ImageProcessing/Processors/HlslGaussianBlurProcessor{TPixel}.cs +++ b/samples/ComputeSharp.ImageProcessing/Processors/HlslGaussianBlurProcessor{TPixel}.cs @@ -96,7 +96,7 @@ namespace ComputeSharp.BokehBlur.Processors PixelOperations.Instance.ToVector4(Configuration, spanTPixel, spanVector4); - using ReadWriteBuffer sourceBuffer = Gpu.Default.AllocateReadWriteBuffer(spanVector4); + using ReadWriteBuffer sourceBuffer = Gpu.Default.AllocateReadWriteBuffer(spanVector4); using ReadWriteBuffer firstPassBuffer = Gpu.Default.AllocateReadWriteBuffer(sourceBuffer.Length); using ReadOnlyBuffer kernelBuffer = Gpu.Default.AllocateReadOnlyBuffer(Kernel); diff --git a/src/ComputeSharp.Graphics/Buffers/Abstract/Buffer{T}.cs b/src/ComputeSharp.Graphics/Buffers/Abstract/Buffer{T}.cs index e4880443..b04c95b4 100644 --- a/src/ComputeSharp.Graphics/Buffers/Abstract/Buffer{T}.cs +++ b/src/ComputeSharp.Graphics/Buffers/Abstract/Buffer{T}.cs @@ -8,9 +8,6 @@ using ComputeSharp.Graphics.Buffers.Enums; using ComputeSharp.Graphics.Extensions; using Microsoft.Toolkit.Diagnostics; using TerraFX.Interop; -using static TerraFX.Interop.D3D12_SRV_DIMENSION; -using static TerraFX.Interop.D3D12_UAV_DIMENSION; -using FX = TerraFX.Interop.Windows; namespace ComputeSharp.Graphics.Buffers.Abstract { @@ -29,6 +26,7 @@ namespace ComputeSharp.Graphics.Buffers.Abstract /// /// The instance for the current resource. /// + /// This field is dynamically accessed when loading shader dispatch data. internal readonly D3D12_GPU_DESCRIPTOR_HANDLE D3D12GpuDescriptorHandle; /// @@ -42,8 +40,8 @@ namespace ComputeSharp.Graphics.Buffers.Abstract /// The associated with the current instance. /// The number of items to store in the current buffer. /// The size in bytes of each buffer item (including padding, if any). - /// The buffer type for the current buffer. - internal Buffer(GraphicsDevice device, int length, uint elementSizeInBytes, BufferType bufferType) + /// The resource type for the current buffer. + private protected Buffer(GraphicsDevice device, int length, uint elementSizeInBytes, ResourceType resourceType) { device.ThrowIfDisposed(); @@ -53,20 +51,26 @@ namespace ComputeSharp.Graphics.Buffers.Abstract GraphicsDevice = device; Length = length; - this.d3D12Resource = device.D3D12Device->CreateCommittedResource(bufferType, (ulong)SizeInBytes); + this.d3D12Resource = device.D3D12Device->CreateCommittedResource(resourceType, (ulong)SizeInBytes); - GraphicsDevice.AllocateShaderResourceViewDescriptorHandles(out D3D12_CPU_DESCRIPTOR_HANDLE d3D12CpuDescriptorHandle, out D3D12GpuDescriptorHandle); + device.AllocateShaderResourceViewDescriptorHandles(out D3D12_CPU_DESCRIPTOR_HANDLE d3D12CpuDescriptorHandle, out D3D12GpuDescriptorHandle); - switch (bufferType) + switch (resourceType) { - case BufferType.Constant: CreateConstantBufferView(d3D12CpuDescriptorHandle); break; - case BufferType.ReadOnly: CreateShaderResourceView(d3D12CpuDescriptorHandle); break; - case BufferType.ReadWrite: CreateUnorderedAccessView(d3D12CpuDescriptorHandle); break; + case ResourceType.Constant: + device.D3D12Device->CreateConstantBufferView(this.d3D12Resource, SizeInBytes, d3D12CpuDescriptorHandle); + break; + case ResourceType.ReadOnly: + device.D3D12Device->CreateShaderResourceView(this.d3D12Resource, (uint)length, elementSizeInBytes, d3D12CpuDescriptorHandle); + break; + case ResourceType.ReadWrite: + device.D3D12Device->CreateUnorderedAccessView(this.d3D12Resource, (uint)length, elementSizeInBytes, d3D12CpuDescriptorHandle); + break; } } /// - /// Gets the associated with the current instance. + /// Gets the associated with the current instance. /// public GraphicsDevice GraphicsDevice { get; } @@ -103,7 +107,10 @@ namespace ComputeSharp.Graphics.Buffers.Abstract /// /// A array with the contents of the current buffer. [Pure] - public T[] GetData() => GetData(0, Length); + public T[] GetData() + { + return GetData(0, Length); + } /// /// Reads the contents of the current instance in a given range and returns an array. @@ -127,7 +134,10 @@ namespace ComputeSharp.Graphics.Buffers.Abstract /// Reads the contents of the current instance and writes them into a target array. /// /// The input array to write data to. - public void GetData(T[] destination) => GetData(destination.AsSpan(), 0); + public void GetData(T[] destination) + { + GetData(destination.AsSpan(), 0); + } /// /// Reads the contents of the specified range from the current instance and writes them into a target array. @@ -148,7 +158,10 @@ namespace ComputeSharp.Graphics.Buffers.Abstract /// The input data will be read from the start of the buffer. /// /// The input to write data to. - public void GetData(Span destination) => GetData(destination, 0); + public void GetData(Span destination) + { + GetData(destination, 0); + } /// /// Reads the contents of the specified range from the current instance and writes them into a target . @@ -161,7 +174,10 @@ namespace ComputeSharp.Graphics.Buffers.Abstract /// Writes the contents of a given array to the current instance. /// /// The input array to read data from. - public void SetData(T[] source) => SetData(source.AsSpan()); + public void SetData(T[] source) + { + SetData(source.AsSpan()); + } /// /// Writes the contents of a given array to a specified area of the current instance. @@ -182,7 +198,10 @@ namespace ComputeSharp.Graphics.Buffers.Abstract /// The input data will be written to the start of the buffer, and all input items will be copied. /// /// The input to read data from. - public void SetData(ReadOnlySpan source) => SetData(source, 0); + public void SetData(ReadOnlySpan source) + { + SetData(source, 0); + } /// /// Writes the contents of a given to a specified area of the current instance. @@ -221,50 +240,6 @@ namespace ComputeSharp.Graphics.Buffers.Abstract } } - /// - /// Creates a view for a constant buffer. - /// - /// The instance for the current resource. - private void CreateConstantBufferView(D3D12_CPU_DESCRIPTOR_HANDLE d3D12CpuDescriptorHandle) - { - uint constantBufferSize = checked((uint)((SizeInBytes + 255) & ~255)); - - D3D12_CONSTANT_BUFFER_VIEW_DESC d3D12ConstantBufferViewDescription; - d3D12ConstantBufferViewDescription.BufferLocation = D3D12Resource->GetGPUVirtualAddress(); - d3D12ConstantBufferViewDescription.SizeInBytes = constantBufferSize; - - GraphicsDevice.D3D12Device->CreateConstantBufferView(&d3D12ConstantBufferViewDescription, d3D12CpuDescriptorHandle); - } - - /// - /// Creates a view for a readonly buffer. - /// - /// The instance for the current resource. - private void CreateShaderResourceView(D3D12_CPU_DESCRIPTOR_HANDLE d3D12CpuDescriptorHandle) - { - D3D12_SHADER_RESOURCE_VIEW_DESC d3D12ShaderResourceViewDescription = default; - d3D12ShaderResourceViewDescription.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; - d3D12ShaderResourceViewDescription.Shader4ComponentMapping = FX.D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; - d3D12ShaderResourceViewDescription.Buffer.NumElements = (uint)Length; - d3D12ShaderResourceViewDescription.Buffer.StructureByteStride = (uint)ElementSizeInBytes; - - GraphicsDevice.D3D12Device->CreateShaderResourceView(D3D12Resource, &d3D12ShaderResourceViewDescription, d3D12CpuDescriptorHandle); - } - - /// - /// Creates a view for a buffer than be both read and written to. - /// - /// The instance for the current resource. - private void CreateUnorderedAccessView(D3D12_CPU_DESCRIPTOR_HANDLE d3D12CpuDescriptorHandle) - { - D3D12_UNORDERED_ACCESS_VIEW_DESC d3D12UnorderedAccessViewDescription = default; - d3D12UnorderedAccessViewDescription.ViewDimension = D3D12_UAV_DIMENSION_BUFFER; - d3D12UnorderedAccessViewDescription.Buffer.NumElements = (uint)Length; - d3D12UnorderedAccessViewDescription.Buffer.StructureByteStride = (uint)ElementSizeInBytes; - - GraphicsDevice.D3D12Device->CreateUnorderedAccessView(D3D12Resource, null, &d3D12UnorderedAccessViewDescription, d3D12CpuDescriptorHandle); - } - /// protected override void OnDispose() { diff --git a/src/ComputeSharp.Graphics/Buffers/Abstract/StructuredBuffer{T}.cs b/src/ComputeSharp.Graphics/Buffers/Abstract/StructuredBuffer{T}.cs index d03c019c..2d448ca2 100644 --- a/src/ComputeSharp.Graphics/Buffers/Abstract/StructuredBuffer{T}.cs +++ b/src/ComputeSharp.Graphics/Buffers/Abstract/StructuredBuffer{T}.cs @@ -23,9 +23,9 @@ namespace ComputeSharp.Graphics.Buffers.Abstract /// /// The associated with the current instance. /// The number of items to store in the current buffer. - /// The buffer type for the current buffer. - internal StructuredBuffer(GraphicsDevice device, int length, BufferType bufferType) - : base(device, length, (uint)Unsafe.SizeOf(), bufferType) + /// The buffer type for the current buffer. + private protected StructuredBuffer(GraphicsDevice device, int length, ResourceType resourceType) + : base(device, length, (uint)Unsafe.SizeOf(), resourceType) { } @@ -43,11 +43,11 @@ namespace ComputeSharp.Graphics.Buffers.Abstract byteOffset = (nint)offset * ElementSizeInBytes, byteSize = (nint)destination.Length * ElementSizeInBytes; - using ComPtr d3D12Resource = GraphicsDevice.D3D12Device->CreateCommittedResource(BufferType.ReadBack, (ulong)byteSize); + using ComPtr d3D12Resource = GraphicsDevice.D3D12Device->CreateCommittedResource(ResourceType.ReadBack, (ulong)byteSize); using (CommandList copyCommandList = new(GraphicsDevice, D3D12_COMMAND_LIST_TYPE_COPY)) { - copyCommandList.CopyBufferRegion(D3D12Resource, (ulong)byteOffset, d3D12Resource.Get(), 0, (ulong)byteSize); + copyCommandList.CopyBufferRegion(d3D12Resource.Get(), 0, D3D12Resource, (ulong)byteOffset,(ulong)byteSize); copyCommandList.ExecuteAndWaitForCompletion(); } @@ -70,7 +70,7 @@ namespace ComputeSharp.Graphics.Buffers.Abstract byteOffset = (nint)offset * ElementSizeInBytes, byteSize = (nint)source.Length * ElementSizeInBytes; - using ComPtr d3D12Resource = GraphicsDevice.D3D12Device->CreateCommittedResource(BufferType.Upload, (ulong)byteSize); + using ComPtr d3D12Resource = GraphicsDevice.D3D12Device->CreateCommittedResource(ResourceType.Upload, (ulong)byteSize); using (ID3D12ResourceMap resource = d3D12Resource.Get()->Map()) { @@ -79,7 +79,7 @@ namespace ComputeSharp.Graphics.Buffers.Abstract using CommandList copyCommandList = new(GraphicsDevice, D3D12_COMMAND_LIST_TYPE_COPY); - copyCommandList.CopyBufferRegion(d3D12Resource.Get(), 0, D3D12Resource, (ulong)byteOffset, (ulong)byteSize); + copyCommandList.CopyBufferRegion(D3D12Resource, (ulong)byteOffset, d3D12Resource.Get(), 0,(ulong)byteSize); copyCommandList.ExecuteAndWaitForCompletion(); } @@ -98,7 +98,7 @@ namespace ComputeSharp.Graphics.Buffers.Abstract // Directly copy the input buffer using CommandList copyCommandList = new(GraphicsDevice, D3D12_COMMAND_LIST_TYPE_COPY); - copyCommandList.CopyBufferRegion(source.D3D12Resource, 0, D3D12Resource, 0, (ulong)SizeInBytes); + copyCommandList.CopyBufferRegion(D3D12Resource, 0, source.D3D12Resource, 0,(ulong)SizeInBytes); copyCommandList.ExecuteAndWaitForCompletion(); } else SetDataWithCpuBuffer(source); diff --git a/src/ComputeSharp.Graphics/Buffers/Abstract/Texture2D{T}.cs b/src/ComputeSharp.Graphics/Buffers/Abstract/Texture2D{T}.cs new file mode 100644 index 00000000..06e2c7af --- /dev/null +++ b/src/ComputeSharp.Graphics/Buffers/Abstract/Texture2D{T}.cs @@ -0,0 +1,409 @@ +using System; +using System.Diagnostics.Contracts; +using System.Runtime.CompilerServices; +using ComputeSharp.Core.Interop; +using ComputeSharp.Exceptions; +using ComputeSharp.Graphics.Buffers.Enums; +using ComputeSharp.Graphics.Buffers.Interop; +using ComputeSharp.Graphics.Commands; +using ComputeSharp.Graphics.Extensions; +using ComputeSharp.Graphics.Helpers; +using Microsoft.Toolkit.Diagnostics; +using TerraFX.Interop; +using static TerraFX.Interop.D3D12_COMMAND_LIST_TYPE; +using static TerraFX.Interop.D3D12_RESOURCE_STATES; + +namespace ComputeSharp.Graphics.Buffers.Abstract +{ + /// + /// A representing a typed 2D texture stored on GPU memory. + /// + /// The type of items stored on the texture. + public unsafe abstract class Texture2D : NativeObject + where T : unmanaged + { + /// + /// The instance currently mapped. + /// + private ComPtr d3D12Resource; + + /// + /// The instance for the current resource. + /// + /// This field is dynamically accessed when loading shader dispatch data. + internal readonly D3D12_GPU_DESCRIPTOR_HANDLE D3D12GpuDescriptorHandle; + + /// + /// The default value for the current resource. + /// + private readonly D3D12_RESOURCE_STATES D3D12ResourceStates; + + /// + /// Creates a new instance with the specified parameters. + /// + /// The associated with the current instance. + /// The height of the texture. + /// The width of the texture. + /// The resource type for the current texture. + private protected Texture2D(GraphicsDevice device, int width, int height, ResourceType resourceType) + { + device.ThrowIfDisposed(); + + Guard.IsGreaterThanOrEqualTo(width, 0, nameof(width)); + Guard.IsGreaterThanOrEqualTo(height, 0, nameof(height)); + + GraphicsDevice = device; + Width = width; + Height = height; + + this.d3D12Resource = device.D3D12Device->CreateCommittedResource( + resourceType, + DXGIFormatHelper.GetForType(), + (uint)width, + (uint)height, + out D3D12ResourceStates); + + device.AllocateShaderResourceViewDescriptorHandles(out D3D12_CPU_DESCRIPTOR_HANDLE d3D12CpuDescriptorHandle, out D3D12GpuDescriptorHandle); + + switch (resourceType) + { + case ResourceType.ReadOnly: + device.D3D12Device->CreateShaderResourceView(this.d3D12Resource, DXGIFormatHelper.GetForType(), d3D12CpuDescriptorHandle); + break; + case ResourceType.ReadWrite: + device.D3D12Device->CreateUnorderedAccessView(this.d3D12Resource, DXGIFormatHelper.GetForType(), d3D12CpuDescriptorHandle); + break; + } + } + + /// + /// Gets the associated with the current instance. + /// + public GraphicsDevice GraphicsDevice { get; } + + /// + /// Gets the width of the current texture. + /// + public int Width { get; } + + /// + /// Gets the height of the current texture. + /// + public int Height { get; } + + /// + /// Gets the instance currently mapped. + /// + internal ID3D12Resource* D3D12Resource => this.d3D12Resource; + + /// + /// Reads the contents of the current instance and returns an array. + /// + /// A array with the contents of the current buffer. + [Pure] + public T[,] GetData() + { + T[,] data = new T[Height, Width]; + + GetData(data); + + return data; + } + + /// + /// Reads the contents of the current instance and writes them into a target array. + /// + /// The input array to write data to. + public void GetData(T[,] destination) + { + fixed (T* p = destination) + { + GetData(new Span(p, destination.Length)); + } + } + + /// + /// Reads the contents of the specified range from the current instance and writes them into a target array. + /// + /// The input array to write data to. + public void GetData(T[] destination) + { + GetData(destination.AsSpan(), 0, 0, Width, Height); + } + + /// + /// Reads the contents of the specified range from the current instance and writes them into a target array. + /// + /// The input array to write data to. + /// The horizontal range of items to copy. + /// The vertical range of items to copy. + public void GetData(T[] destination, Range x, Range y) + { + GetData(destination.AsSpan(), x, y); + } + + /// + /// Reads the contents of the specified range from the current instance and writes them into a target array. + /// + /// The input array to write data to. + /// The horizontal offset in the source texture. + /// The vertical offset in the source texture. + /// The width of the memory area to copy. + /// The height of the memory area to copy. + public void GetData(T[] destination, int x, int y, int width, int height) + { + GetData(destination.AsSpan(), x, y, width, height); + } + + /// + /// Reads the contents of the specified range from the current instance and writes them into a target array. + /// + /// The input array to write data to. + /// The starting offset within to write data to. + public void GetData(T[] destination, int offset) + { + GetData(destination.AsSpan(offset), 0, 0, Width, Height); + } + + /// + /// Reads the contents of the specified range from the current instance and writes them into a target array. + /// + /// The input array to write data to. + /// The starting offset within to write data to. + /// The horizontal range of items to copy. + /// The vertical range of items to copy. + public void GetData(T[] destination, int offset, Range x, Range y) + { + GetData(destination.AsSpan(offset), x, y); + } + + /// + /// Reads the contents of the specified range from the current instance and writes them into a target array. + /// + /// The input array to write data to. + /// The starting offset within to write data to. + /// The horizontal offset in the source texture. + /// The vertical offset in the source texture. + /// The width of the memory area to copy. + /// The height of the memory area to copy. + public void GetData(T[] destination, int offset, int x, int y, int width, int height) + { + GetData(destination.AsSpan(offset), x, y, width, height); + } + + /// + /// Reads the contents of the current instance and writes them into a target . + /// The input data will be read from the start of the texture. + /// + /// The input to write data to. + public void GetData(Span destination) + { + GetData(destination, 0, 0, Width, Height); + } + + /// + /// Reads the contents of the specified range from the current instance and writes them into a target . + /// + /// The input to write data to. + /// The horizontal range of items to copy. + /// The vertical range of items to copy. + public void GetData(Span destination, Range x, Range y) + { + var (offsetX, width) = x.GetOffsetAndLength(Width); + var (offsetY, height) = y.GetOffsetAndLength(Height); + + GetData(destination, offsetX, offsetY, width, height); + } + + /// + /// Reads the contents of the specified range from the current instance and writes them into a target . + /// + /// The input to write data to. + /// The horizontal offset in the source texture. + /// The vertical offset in the source texture. + /// The width of the memory area to copy. + /// The height of the memory area to copy. + public void GetData(Span destination, int x, int y, int width, int height) + { + GraphicsDevice.ThrowIfDisposed(); + + ThrowIfDisposed(); + + Guard.IsInRange(x, 0, Width, nameof(x)); + Guard.IsInRange(y, 0, Height, nameof(y)); + Guard.IsBetweenOrEqualTo(width, 0, Width, nameof(width)); + Guard.IsBetweenOrEqualTo(height, 0, Height, nameof(height)); + Guard.IsLessThanOrEqualTo(x + width, Width, nameof(x)); + Guard.IsLessThanOrEqualTo(y + height, Height, nameof(y)); + Guard.HasSizeGreaterThanOrEqualTo(destination, width * height, nameof(destination)); + + nint byteSize = (nint)width * height * Unsafe.SizeOf(); + + using ComPtr d3D12Resource = GraphicsDevice.D3D12Device->CreateCommittedResource(ResourceType.ReadBack, (ulong)byteSize); + + using (CommandList copyCommandList = new(GraphicsDevice, D3D12_COMMAND_LIST_TYPE_COMPUTE)) + { + copyCommandList.ResourceBarrier(D3D12Resource, D3D12ResourceStates, D3D12_RESOURCE_STATE_COPY_SOURCE); + copyCommandList.CopyTextureRegion(d3D12Resource.Get(), (uint)Unsafe.SizeOf(), D3D12Resource, DXGIFormatHelper.GetForType(), (uint)x, (uint)y, (uint)width, (uint)height); + copyCommandList.ResourceBarrier(D3D12Resource, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12ResourceStates); + copyCommandList.ExecuteAndWaitForCompletion(); + } + + using ID3D12ResourceMap resource = d3D12Resource.Get()->Map(); + + MemoryHelper.Copy(resource.Pointer, 0, destination); + } + + /// + /// Writes the contents of a given array to the current instance. + /// + /// The input array to read data from. + public void SetData(T[,] source) + { + fixed (T* p = source) + { + SetData(new Span(p, source.Length)); + } + } + + /// + /// Writes the contents of a given array to the current instance. + /// + /// The input array to read data from. + public void SetData(T[] source) + { + SetData(source.AsSpan(), 0, 0, Width, Height); + } + + /// + /// Writes the contents of a given array to a specified area of the current instance. + /// + /// The input array to read data from. + /// The horizontal range of items to write. + /// The vertical range of items to write. + public void SetData(T[] source, Range x, Range y) + { + SetData(source.AsSpan(), x, y); + } + + /// + /// Writes the contents of a given array to a specified area of the current instance. + /// + /// The input array to read data from. + /// The horizontal offset in the destination texture. + /// The vertical offset in the destination texture. + /// The width of the memory area to write to. + /// The height of the memory area to write to. + public void SetData(T[] source, int x, int y, int width, int height) + { + SetData(source.AsSpan(), x, y, width, height); + } + + /// + /// Writes the contents of a given array to a specified area of the current instance. + /// + /// The input array to read data from. + /// The starting offset within to read data from. + /// The horizontal range of items to write. + /// The vertical range of items to write. + public void SetData(T[] source, int offset, Range x, Range y) + { + SetData(source.AsSpan(offset), x, y); + } + + /// + /// Writes the contents of a given array to a specified area of the current instance. + /// + /// The input array to read data from. + /// The starting offset within to read data from. + /// The horizontal offset in the destination texture. + /// The vertical offset in the destination texture. + /// The width of the memory area to write to. + /// The height of the memory area to write to. + public void SetData(T[] source, int offset, int x, int y, int width, int height) + { + SetData(source.AsSpan(offset), x, y, width, height); + } + + /// + /// Writes the contents of a given to the current instance. + /// The input data will be written to the start of the texture, and all input items will be copied. + /// + /// The input to read data from. + public void SetData(ReadOnlySpan source) + { + SetData(source, 0, 0, Width, Height); + } + + /// + /// Writes the contents of a given to a specified area of the current instance. + /// + /// The input to read data from. + /// The horizontal range of items to write. + /// The vertical range of items to write. + public void SetData(ReadOnlySpan source, Range x, Range y) + { + var (offsetX, width) = x.GetOffsetAndLength(Width); + var (offsetY, height) = y.GetOffsetAndLength(Height); + + SetData(source, offsetX, offsetY, width, height); + } + + /// + /// Writes the contents of a given to a specified area of the current instance. + /// + /// The input to read data from. + /// The horizontal offset in the destination texture. + /// The vertical offset in the destination texture. + /// The width of the memory area to write to. + /// The height of the memory area to write to. + public void SetData(ReadOnlySpan source, int x, int y, int width, int height) + { + GraphicsDevice.ThrowIfDisposed(); + + ThrowIfDisposed(); + + Guard.IsInRange(x, 0, Width, nameof(x)); + Guard.IsInRange(y, 0, Height, nameof(y)); + Guard.IsBetweenOrEqualTo(width, 0, Width, nameof(width)); + Guard.IsBetweenOrEqualTo(height, 0, Height, nameof(height)); + Guard.IsLessThanOrEqualTo(x + width, Width, nameof(x)); + Guard.IsLessThanOrEqualTo(y + height, Height, nameof(y)); + Guard.HasSizeGreaterThanOrEqualTo(source, width * height, nameof(source)); + + nint byteSize = (nint)width * height * Unsafe.SizeOf(); + + using ComPtr d3D12Resource = GraphicsDevice.D3D12Device->CreateCommittedResource(ResourceType.Upload, (ulong)byteSize); + + using (ID3D12ResourceMap resource = d3D12Resource.Get()->Map()) + { + MemoryHelper.Copy(source, resource.Pointer, 0); + } + + using CommandList copyCommandList = new(GraphicsDevice, D3D12_COMMAND_LIST_TYPE_COMPUTE); + + copyCommandList.ResourceBarrier(D3D12Resource, D3D12ResourceStates, D3D12_RESOURCE_STATE_COPY_DEST); + copyCommandList.CopyTextureRegion(D3D12Resource, DXGIFormatHelper.GetForType(), (uint)x, (uint)y, d3D12Resource.Get(), (uint)width, (uint)height, (uint)Unsafe.SizeOf()); + copyCommandList.ResourceBarrier(D3D12Resource, D3D12_RESOURCE_STATE_COPY_DEST, D3D12ResourceStates); + copyCommandList.ExecuteAndWaitForCompletion(); + } + + /// + protected override void OnDispose() + { + this.d3D12Resource.Dispose(); + } + + /// + /// Throws a if the target device doesn't match the current one. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal void ThrowIfDeviceMismatch(GraphicsDevice device) + { + if (GraphicsDevice != device) + { + GraphicsDeviceMismatchException.Throw(this, device); + } + } + } +} diff --git a/src/ComputeSharp.Graphics/Buffers/ConstantBuffer{T}.cs b/src/ComputeSharp.Graphics/Buffers/ConstantBuffer{T}.cs index 0fc6a98c..6a525432 100644 --- a/src/ComputeSharp.Graphics/Buffers/ConstantBuffer{T}.cs +++ b/src/ComputeSharp.Graphics/Buffers/ConstantBuffer{T}.cs @@ -32,7 +32,7 @@ namespace ComputeSharp /// The associated with the current instance. /// The number of items to store in the current buffer. internal ConstantBuffer(GraphicsDevice device, int length) - : base(device, length, (uint)GetPaddedSize(), BufferType.Constant) + : base(device, length, (uint)GetPaddedSize(), ResourceType.Constant) { } @@ -130,7 +130,7 @@ namespace ComputeSharp // Directly copy the input buffer, if possible using CommandList copyCommandList = new CommandList(GraphicsDevice, D3D12_COMMAND_LIST_TYPE_COPY); - copyCommandList.CopyBufferRegion(source.D3D12Resource, 0, D3D12Resource, 0, (ulong)SizeInBytes); + copyCommandList.CopyBufferRegion(D3D12Resource, 0, source.D3D12Resource, 0,(ulong)SizeInBytes); copyCommandList.ExecuteAndWaitForCompletion(); } else SetDataWithCpuBuffer(source); diff --git a/src/ComputeSharp.Graphics/Buffers/Enums/BufferType.cs b/src/ComputeSharp.Graphics/Buffers/Enums/BufferType.cs deleted file mode 100644 index e2df47aa..00000000 --- a/src/ComputeSharp.Graphics/Buffers/Enums/BufferType.cs +++ /dev/null @@ -1,38 +0,0 @@ -namespace ComputeSharp.Graphics.Buffers.Enums -{ - /// - /// An that indicates the type of a given HLSL buffer. - /// - internal enum BufferType - { - /// - /// A constant buffer, with items aligned to 16 bytes, used for individual values or very small arrays. - /// This is mapped to a in . - /// - Constant, - - /// - /// A readonly buffer, that can store arbitrary arrays of values and can only be read from by the GPU. - /// This is mapped to a in . - /// - ReadOnly, - - /// - /// A read write buffer, that can store arbitrary arrays with both read and write access for the GPU. - /// This is mapped to a in . - /// - ReadWrite, - - /// - /// A readback buffer, used as temporary buffer to read data back from and buffers. - /// This has no mapping in HLSL, and is allocated in . - /// - ReadBack, - - /// - /// A transfer buffer, used as a temporary buffer to set data to and buffers. - /// This has no mapping in HLSL, and is allocated in . - /// - Upload - } -} diff --git a/src/ComputeSharp.Graphics/Buffers/Enums/ResourceType.cs b/src/ComputeSharp.Graphics/Buffers/Enums/ResourceType.cs new file mode 100644 index 00000000..8ddddb8d --- /dev/null +++ b/src/ComputeSharp.Graphics/Buffers/Enums/ResourceType.cs @@ -0,0 +1,43 @@ +namespace ComputeSharp.Graphics.Buffers.Enums +{ + /// + /// An that indicates the type of a given HLSL resource. + /// + internal enum ResourceType + { + /// + /// A constant resource, with items aligned to 16 bytes, used for individual values or very small arrays. + /// This is only supported for buffers and is mapped to a . + /// Resources of this type are located in . + /// + Constant, + + /// + /// A readonly resource, that can store arbitrary arrays of values and can only be read from by the GPU. + /// This is mapped to either or . + /// Resources of this type are located in . + /// + ReadOnly, + + /// + /// A read write resource, that can store arbitrary arrays with both read and write access for the GPU. + /// This is mapped to either or . + /// Resources of this type are located in . + /// + ReadWrite, + + /// + /// A readback resource, used temporarily to read data back from and resources. + /// This has no direct mapping to a type in HLSL, as it's only used for copy operations. + /// Resources of this type are located in . + /// + ReadBack, + + /// + /// A transfer resource, used temporarily to set data to and resources. + /// This has no direct mapping to a type in HLSL, as it's only used for copy operations (like ). + /// Resources of this type are located in . + /// + Upload + } +} diff --git a/src/ComputeSharp.Graphics/Buffers/ReadOnlyBuffer{T}.cs b/src/ComputeSharp.Graphics/Buffers/ReadOnlyBuffer{T}.cs index 92789c87..296df86e 100644 --- a/src/ComputeSharp.Graphics/Buffers/ReadOnlyBuffer{T}.cs +++ b/src/ComputeSharp.Graphics/Buffers/ReadOnlyBuffer{T}.cs @@ -22,12 +22,12 @@ namespace ComputeSharp /// The associated with the current instance. /// The number of items to store in the current buffer. internal ReadOnlyBuffer(GraphicsDevice device, int length) - : base(device, length, BufferType.ReadOnly) + : base(device, length, ResourceType.ReadOnly) { } /// - /// Gets a single value from the current read write buffer. + /// Gets a single value from the current readonly buffer. /// /// The index of the value to get. /// This API can only be used from a compute shader, and will always throw if used anywhere else. diff --git a/src/ComputeSharp.Graphics/Buffers/ReadOnlyTexture2D{T}.cs b/src/ComputeSharp.Graphics/Buffers/ReadOnlyTexture2D{T}.cs new file mode 100644 index 00000000..2c7c9130 --- /dev/null +++ b/src/ComputeSharp.Graphics/Buffers/ReadOnlyTexture2D{T}.cs @@ -0,0 +1,43 @@ +using System.Diagnostics; +using ComputeSharp.Exceptions; +using ComputeSharp.Graphics; +using ComputeSharp.Graphics.Buffers.Abstract; +using ComputeSharp.Graphics.Buffers.Enums; +using ComputeSharp.Graphics.Buffers.Views; + +namespace ComputeSharp +{ + /// + /// A representing a typed readonly 2D texture stored on GPU memory. + /// + /// The type of items stored on the texture. + [DebuggerTypeProxy(typeof(BufferDebugView2D<>))] + [DebuggerDisplay("{ToString(),raw}")] + public sealed class ReadOnlyTexture2D : Texture2D + where T : unmanaged + { + /// + /// Creates a new instance with the specified parameters. + /// + /// The associated with the current instance. + /// The width of the texture. + /// The height of the texture. + internal ReadOnlyTexture2D(GraphicsDevice device, int width, int height) + : base(device, width, height, ResourceType.ReadOnly) + { + } + + /// + /// Gets a single value from the current readonly texture. + /// + /// The coordinates of the value to get. + /// This API can only be used from a compute shader, and will always throw if used anywhere else. + public T this[UInt2 xy] => throw new InvalidExecutionContextException($"{nameof(ReadOnlyTexture2D)}[UInt2]"); + + /// + public override string ToString() + { + return $"ComputeSharp.ReadOnlyTexture2D<{typeof(T)}>[{Width}, {Height}]"; + } + } +} diff --git a/src/ComputeSharp.Graphics/Buffers/ReadWriteBuffer{T}.cs b/src/ComputeSharp.Graphics/Buffers/ReadWriteBuffer{T}.cs index 7761da25..a2f2c0c2 100644 --- a/src/ComputeSharp.Graphics/Buffers/ReadWriteBuffer{T}.cs +++ b/src/ComputeSharp.Graphics/Buffers/ReadWriteBuffer{T}.cs @@ -22,7 +22,7 @@ namespace ComputeSharp /// The associated with the current instance. /// The number of items to store in the current buffer. internal ReadWriteBuffer(GraphicsDevice device, int length) - : base(device, length, BufferType.ReadWrite) + : base(device, length, ResourceType.ReadWrite) { } diff --git a/src/ComputeSharp.Graphics/Buffers/ReadWriteTexture2D{T}.cs b/src/ComputeSharp.Graphics/Buffers/ReadWriteTexture2D{T}.cs new file mode 100644 index 00000000..779bba67 --- /dev/null +++ b/src/ComputeSharp.Graphics/Buffers/ReadWriteTexture2D{T}.cs @@ -0,0 +1,43 @@ +using System.Diagnostics; +using ComputeSharp.Exceptions; +using ComputeSharp.Graphics; +using ComputeSharp.Graphics.Buffers.Abstract; +using ComputeSharp.Graphics.Buffers.Enums; +using ComputeSharp.Graphics.Buffers.Views; + +namespace ComputeSharp +{ + /// + /// A representing a typed read write 2D texture stored on GPU memory. + /// + /// The type of items stored on the texture. + [DebuggerTypeProxy(typeof(BufferDebugView2D<>))] + [DebuggerDisplay("{ToString(),raw}")] + public sealed class ReadWriteTexture2D : Texture2D + where T : unmanaged + { + /// + /// Creates a new instance with the specified parameters. + /// + /// The associated with the current instance. + /// The width of the texture. + /// The height of the texture. + internal ReadWriteTexture2D(GraphicsDevice device, int width, int height) + : base(device, width, height, ResourceType.ReadWrite) + { + } + + /// + /// Gets or sets a single value from the current readonly texture. + /// + /// The coordinates of the value to get. + /// This API can only be used from a compute shader, and will always throw if used anywhere else. + public ref T this[UInt2 xy] => throw new InvalidExecutionContextException($"{nameof(ReadOnlyTexture2D)}[UInt2]"); + + /// + public override string ToString() + { + return $"ComputeSharp.ReadWriteTexture2D<{typeof(T)}>[{Width}, {Height}]"; + } + } +} diff --git a/src/ComputeSharp.Graphics/Buffers/Views/BufferDebugView2D{T}.cs b/src/ComputeSharp.Graphics/Buffers/Views/BufferDebugView2D{T}.cs new file mode 100644 index 00000000..c3061ea1 --- /dev/null +++ b/src/ComputeSharp.Graphics/Buffers/Views/BufferDebugView2D{T}.cs @@ -0,0 +1,28 @@ +using System.Diagnostics; +using ComputeSharp.Graphics.Buffers.Abstract; + +namespace ComputeSharp.Graphics.Buffers.Views +{ + /// + /// A debug proxy used to display items in a instance. + /// + /// The type of items to display. + internal sealed class BufferDebugView2D + where T : unmanaged + { + /// + /// Initializes a new instance of the class with the specified parameters. + /// + /// The input instance with the items to display. + public BufferDebugView2D(Texture2D? texture) + { + Items = texture?.GetData(); + } + + /// + /// Gets the items to display for the current instance. + /// + [DebuggerBrowsable(DebuggerBrowsableState.Collapsed)] + public T[,]? Items { get; } + } +} diff --git a/src/ComputeSharp.Graphics/Commands/CommandList.cs b/src/ComputeSharp.Graphics/Commands/CommandList.cs index cebe74c8..18cecdf0 100644 --- a/src/ComputeSharp.Graphics/Commands/CommandList.cs +++ b/src/ComputeSharp.Graphics/Commands/CommandList.cs @@ -81,16 +81,81 @@ namespace ComputeSharp.Graphics.Commands /// /// Copies a memory region from one resource to another. /// - /// The source to read from. - /// The starting offset to read the source resource from. /// The destination to write to. /// The starting offset to write the destination resource from. + /// The source to read from. + /// The starting offset to read the source resource from. /// The total number of bytes to copy from one resource to another. - public readonly void CopyBufferRegion(ID3D12Resource* d3D12ResourceSource, ulong sourceOffset, ID3D12Resource* d3d12ResourceDestination, ulong destinationOffset, ulong numBytes) + public readonly void CopyBufferRegion(ID3D12Resource* d3d12ResourceDestination, ulong destinationOffset, ID3D12Resource* d3D12ResourceSource, ulong sourceOffset, ulong numBytes) { this.d3D12GraphicsCommandList.Get()->CopyBufferRegion(d3d12ResourceDestination, destinationOffset, d3D12ResourceSource, sourceOffset, numBytes); } + /// + /// Copies a texture memory region from one resource (a buffer) to another (a texture). + /// + /// The destination (a texture) to write to. + /// The parameter curreently in use by the texture. + /// The horizontal offset in the destination texture. + /// The vertical offset in the destination texture. + /// The source (a buffer) to read from. + /// The width of the memory area to write to. + /// The height of the memory area to write to. + /// The size of each element to copy. + + public readonly void CopyTextureRegion( + ID3D12Resource* d3d12ResourceDestination, + DXGI_FORMAT dxgiFormat, + uint x, + uint y, + ID3D12Resource* d3D12ResourceSource, + uint width, + uint height, + uint elementSizeInBytes) + { + this.d3D12GraphicsCommandList.Get()->CopyTextureRegion(d3d12ResourceDestination, dxgiFormat, x, y, d3D12ResourceSource, width, height, elementSizeInBytes); + } + + /// + /// Copies a texture memory region from one resource (a texture) to another (a buffer). + /// + /// The destination (a buffer) to write to. + /// The size of each element to copy. + /// The source (a texture) to read from. + /// The parameter curreently in use by the texture. + /// The horizontal offset in the destination texture. + /// The vertical offset in the destination texture. + /// The width of the memory area to write to. + /// The height of the memory area to write to. + public readonly void CopyTextureRegion( + ID3D12Resource* d3d12ResourceDestination, + uint elementSizeInBytes, + ID3D12Resource* d3D12ResourceSource, + DXGI_FORMAT dxgiFormat, + uint x, + uint y, + uint width, + uint height) + { + this.d3D12GraphicsCommandList.Get()->CopyTextureRegion(d3d12ResourceDestination, elementSizeInBytes, d3D12ResourceSource, dxgiFormat, x, y, width, height); + } + + /// + /// Creates a resource barrier to transition a resource to a specific state. + /// + /// The to change state for. + /// The starting value for the transition. + /// The destnation value for the transition. + public readonly void ResourceBarrier( + ID3D12Resource* d3D12Resource, + D3D12_RESOURCE_STATES d3D12ResourceStatesBefore, + D3D12_RESOURCE_STATES d3D12ResourceStatesAfter) + { + D3D12_RESOURCE_BARRIER d3D12ResourceBarrier = D3D12_RESOURCE_BARRIER.InitTransition(d3D12Resource, d3D12ResourceStatesBefore, d3D12ResourceStatesAfter); + + this.d3D12GraphicsCommandList.Get()->ResourceBarrier(1, &d3D12ResourceBarrier); + } + /// /// Binds an input value to a specified root parameter. /// diff --git a/src/ComputeSharp.Graphics/Exceptions/GraphicsDeviceMismatchException.cs b/src/ComputeSharp.Graphics/Exceptions/GraphicsDeviceMismatchException.cs index fe2c4490..8197b10f 100644 --- a/src/ComputeSharp.Graphics/Exceptions/GraphicsDeviceMismatchException.cs +++ b/src/ComputeSharp.Graphics/Exceptions/GraphicsDeviceMismatchException.cs @@ -1,6 +1,7 @@ using System; using System.Diagnostics.Contracts; using System.Text; +using ComputeSharp.Core.Interop; using ComputeSharp.Graphics; using ComputeSharp.Graphics.Buffers.Abstract; @@ -23,19 +24,22 @@ namespace ComputeSharp.Exceptions /// /// Creates a new instance from the specified parameters. /// - /// The type of values in the input buffer. - /// The input that was used. - /// The target instance that was used. + /// The input that was used. + /// The source instance tied to . + /// The target instance that was used. /// A new instance with a formatted error message. + /// + /// This method only takes a instance and the associated instance as + /// will still be available, but without the unnecessary generic type specializations for the method. + /// [Pure] - private static GraphicsDeviceMismatchException Create(Buffer buffer, GraphicsDevice device) - where T : unmanaged + private static GraphicsDeviceMismatchException Create(NativeObject resource, GraphicsDevice sourceDevice, GraphicsDevice destinationDevice) { StringBuilder builder = new(512); builder.AppendLine("Invalid pairing of graphics devices used to run a compute shader and allocate memory buffers."); - builder.AppendLine($"The target device to run the compute shader is \"{device}\"."); - builder.AppendLine($"The buffer of type {buffer.GetType()} was allocated on device \"{buffer.GraphicsDevice}\"."); + builder.AppendLine($"The target device to run the compute shader is \"{destinationDevice}\"."); + builder.AppendLine($"The buffer of type {resource.GetType()} was allocated on device \"{sourceDevice}\"."); builder.Append("Make sure to always allocate buffers on the same device used to actually run the code that accesses them."); builder.ToString(); @@ -52,7 +56,20 @@ namespace ComputeSharp.Exceptions internal static void Throw(Buffer buffer, GraphicsDevice device) where T : unmanaged { - throw Create(buffer, device); + throw Create(buffer, buffer.GraphicsDevice, device); + } + + /// + /// Throws a new instance from the specified parameters. + /// + /// The type of values in the input buffer. + /// The input that was used. + /// The target instance that was used. + [Pure] + internal static void Throw(Texture2D texture, GraphicsDevice device) + where T : unmanaged + { + throw Create(texture, texture.GraphicsDevice, device); } } } \ No newline at end of file diff --git a/src/ComputeSharp.Graphics/Extensions/ID3D12DeviceExtensions.cs b/src/ComputeSharp.Graphics/Extensions/ID3D12DeviceExtensions.cs index 910f86b2..3c95e4fc 100644 --- a/src/ComputeSharp.Graphics/Extensions/ID3D12DeviceExtensions.cs +++ b/src/ComputeSharp.Graphics/Extensions/ID3D12DeviceExtensions.cs @@ -11,9 +11,12 @@ using static TerraFX.Interop.D3D12_DESCRIPTOR_HEAP_FLAGS; using static TerraFX.Interop.D3D12_DESCRIPTOR_HEAP_TYPE; using static TerraFX.Interop.D3D12_FENCE_FLAGS; using static TerraFX.Interop.D3D12_MEMORY_POOL; +using static TerraFX.Interop.D3D12_HEAP_FLAGS; using static TerraFX.Interop.D3D12_HEAP_TYPE; using static TerraFX.Interop.D3D12_RESOURCE_FLAGS; using static TerraFX.Interop.D3D12_RESOURCE_STATES; +using static TerraFX.Interop.D3D12_SRV_DIMENSION; +using static TerraFX.Interop.D3D12_UAV_DIMENSION; using FX = TerraFX.Interop.Windows; namespace ComputeSharp.Graphics.Extensions @@ -86,7 +89,7 @@ namespace ComputeSharp.Graphics.Extensions d3d12device.CreateDescriptorHeap( &d3d12DescriptorHeapDesc, - FX.__uuidof< ID3D12DescriptorHeap>(), + FX.__uuidof(), d3d12DescriptorHeap.GetVoidAddressOf()).Assert(); return d3d12DescriptorHeap.Move(); @@ -96,25 +99,25 @@ namespace ComputeSharp.Graphics.Extensions /// Creates a committed resource for a given buffer type. /// /// The instance in use. - /// The buffer type currently in use. + /// The resource type currently in use. /// The size in bytes of the current buffer. /// An reference for the current buffer. public static ComPtr CreateCommittedResource( this ref ID3D12Device d3D12Device, - BufferType bufferType, + ResourceType resourceType, ulong sizeInBytes) { (D3D12_HEAP_TYPE d3D12HeapType, D3D12_RESOURCE_FLAGS d3D12ResourceFlags, - D3D12_RESOURCE_STATES d3D12ResourceStates) = bufferType switch - { - BufferType.Constant => (D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_STATE_GENERIC_READ), - BufferType.ReadOnly => (D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_STATE_COMMON), - BufferType.ReadWrite => (D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COMMON), - BufferType.ReadBack => (D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_STATE_COPY_DEST), - BufferType.Upload => (D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_STATE_GENERIC_READ), + D3D12_RESOURCE_STATES d3D12ResourceStates) = resourceType switch + { + ResourceType.Constant => (D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_STATE_GENERIC_READ), + ResourceType.ReadOnly => (D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_STATE_COMMON), + ResourceType.ReadWrite => (D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COMMON), + ResourceType.ReadBack => (D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_STATE_COPY_DEST), + ResourceType.Upload => (D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_STATE_GENERIC_READ), _ => ThrowHelper.ThrowArgumentException<(D3D12_HEAP_TYPE, D3D12_RESOURCE_FLAGS, D3D12_RESOURCE_STATES)>() - }; + }; using ComPtr d3D12Resource = default; @@ -128,7 +131,7 @@ namespace ComputeSharp.Graphics.Extensions d3D12Device.CreateCommittedResource( &d3D12HeapProperties, - D3D12_HEAP_FLAGS.D3D12_HEAP_FLAG_NONE, + D3D12_HEAP_FLAG_NONE, &d3D12ResourceDescription, d3D12ResourceStates, null, @@ -138,6 +141,165 @@ namespace ComputeSharp.Graphics.Extensions return d3D12Resource.Move(); } + /// + /// Creates a committed resource for a given 2D texture type. + /// + /// The instance in use. + /// The resource type currently in use. + /// The value to use. + /// The width of the texture resource. + /// The height of the texture resource. + /// The default value for the resource. + /// An reference for the current texture. + public static ComPtr CreateCommittedResource( + this ref ID3D12Device d3D12Device, + ResourceType resourceType, + DXGI_FORMAT dxgiFormat, + uint width, + uint height, + out D3D12_RESOURCE_STATES d3D12ResourceStates) + { + D3D12_RESOURCE_FLAGS d3D12ResourceFlags; + + (d3D12ResourceFlags, d3D12ResourceStates) = resourceType switch + { + ResourceType.ReadOnly => (D3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE), + ResourceType.ReadWrite => (D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_UNORDERED_ACCESS), + _ => ThrowHelper.ThrowArgumentException<(D3D12_RESOURCE_FLAGS, D3D12_RESOURCE_STATES)>() + }; + + using ComPtr d3D12Resource = default; + + D3D12_HEAP_PROPERTIES d3D12HeapProperties; + d3D12HeapProperties.Type = D3D12_HEAP_TYPE_DEFAULT; + d3D12HeapProperties.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN; + d3D12HeapProperties.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN; + d3D12HeapProperties.CreationNodeMask = 1; + d3D12HeapProperties.VisibleNodeMask = 1; + D3D12_RESOURCE_DESC d3D12ResourceDescription = D3D12_RESOURCE_DESC.Tex2D(dxgiFormat, width, height, flags: d3D12ResourceFlags); + + d3D12Device.CreateCommittedResource( + &d3D12HeapProperties, + D3D12_HEAP_FLAG_NONE, + &d3D12ResourceDescription, + d3D12ResourceStates, + null, + FX.__uuidof(), + d3D12Resource.GetVoidAddressOf()).Assert(); + + return d3D12Resource.Move(); + } + + /// + /// Creates a view for a constant buffer. + /// + /// The target instance in use. + /// The to create a view for. + /// The size of the target resource. + /// The instance for the current resource. + public static void CreateConstantBufferView( + this ref ID3D12Device d3d12Device, + ID3D12Resource* d3d12resource, + nint bufferSize, + D3D12_CPU_DESCRIPTOR_HANDLE d3D12CpuDescriptorHandle) + { + uint constantBufferSize = checked((uint)((bufferSize + 255) & ~255)); + + D3D12_CONSTANT_BUFFER_VIEW_DESC d3D12ConstantBufferViewDescription; + d3D12ConstantBufferViewDescription.BufferLocation = d3d12resource->GetGPUVirtualAddress(); + d3D12ConstantBufferViewDescription.SizeInBytes = constantBufferSize; + + d3d12Device.CreateConstantBufferView(&d3D12ConstantBufferViewDescription, d3D12CpuDescriptorHandle); + } + + /// + /// Creates a view for a readonly buffer. + /// + /// The target instance in use. + /// The to create a view for. + /// The size of the target resource. + /// The size in byte of each item in the resource. + /// The instance for the current resource. + public static void CreateShaderResourceView( + this ref ID3D12Device d3d12Device, + ID3D12Resource* d3d12resource, + uint bufferSize, + uint elementSize, + D3D12_CPU_DESCRIPTOR_HANDLE d3D12CpuDescriptorHandle) + { + D3D12_SHADER_RESOURCE_VIEW_DESC d3D12ShaderResourceViewDescription = default; + d3D12ShaderResourceViewDescription.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; + d3D12ShaderResourceViewDescription.Shader4ComponentMapping = FX.D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + d3D12ShaderResourceViewDescription.Buffer.NumElements = bufferSize; + d3D12ShaderResourceViewDescription.Buffer.StructureByteStride = elementSize; + + d3d12Device.CreateShaderResourceView(d3d12resource, &d3D12ShaderResourceViewDescription, d3D12CpuDescriptorHandle); + } + + /// + /// Creates a view for a readonly texture. + /// + /// The target instance in use. + /// The to create a view for. + /// The value to use. + /// The instance for the current resource. + public static void CreateShaderResourceView( + this ref ID3D12Device d3d12Device, + ID3D12Resource* d3d12resource, + DXGI_FORMAT dxgiFormat, + D3D12_CPU_DESCRIPTOR_HANDLE d3D12CpuDescriptorHandle) + { + D3D12_SHADER_RESOURCE_VIEW_DESC d3D12ShaderResourceViewDescription = default; + d3D12ShaderResourceViewDescription.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; + d3D12ShaderResourceViewDescription.Format = dxgiFormat; + d3D12ShaderResourceViewDescription.Shader4ComponentMapping = FX.D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + + d3d12Device.CreateShaderResourceView(d3d12resource, &d3D12ShaderResourceViewDescription, d3D12CpuDescriptorHandle); + } + + /// + /// Creates a view for a buffer that can be both read and written to. + /// + /// The target instance in use. + /// The to create a view for. + /// The size of the target resource. + /// The size in byte of each item in the resource. + /// The instance for the current resource. + public static void CreateUnorderedAccessView( + this ref ID3D12Device d3d12Device, + ID3D12Resource* d3d12resource, + uint bufferSize, + uint elementSize, + D3D12_CPU_DESCRIPTOR_HANDLE d3D12CpuDescriptorHandle) + { + D3D12_UNORDERED_ACCESS_VIEW_DESC d3D12UnorderedAccessViewDescription = default; + d3D12UnorderedAccessViewDescription.ViewDimension = D3D12_UAV_DIMENSION_BUFFER; + d3D12UnorderedAccessViewDescription.Buffer.NumElements = bufferSize; + d3D12UnorderedAccessViewDescription.Buffer.StructureByteStride = elementSize; + + d3d12Device.CreateUnorderedAccessView(d3d12resource, null, &d3D12UnorderedAccessViewDescription, d3D12CpuDescriptorHandle); + } + + /// + /// Creates a view for a texture that can be both read and written to. + /// + /// The target instance in use. + /// The to create a view for. + /// The value to use. + /// The instance for the current resource. + public static void CreateUnorderedAccessView( + this ref ID3D12Device d3d12Device, + ID3D12Resource* d3d12resource, + DXGI_FORMAT dxgiFormat, + D3D12_CPU_DESCRIPTOR_HANDLE d3D12CpuDescriptorHandle) + { + D3D12_UNORDERED_ACCESS_VIEW_DESC d3D12UnorderedAccessViewDescription = default; + d3D12UnorderedAccessViewDescription.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2D; + d3D12UnorderedAccessViewDescription.Format = dxgiFormat; + + d3d12Device.CreateUnorderedAccessView(d3d12resource, null, &d3D12UnorderedAccessViewDescription, d3D12CpuDescriptorHandle); + } + /// /// Creates a new for a given device. /// diff --git a/src/ComputeSharp.Graphics/Extensions/ID3D12GraphicsCommandListExtensions.cs b/src/ComputeSharp.Graphics/Extensions/ID3D12GraphicsCommandListExtensions.cs new file mode 100644 index 00000000..84e71da4 --- /dev/null +++ b/src/ComputeSharp.Graphics/Extensions/ID3D12GraphicsCommandListExtensions.cs @@ -0,0 +1,91 @@ +using TerraFX.Interop; +using FX = TerraFX.Interop.Windows; + +namespace ComputeSharp.Graphics.Extensions +{ + /// + /// A with extensions for the type. + /// + internal static unsafe class ID3D12GraphicsCommandListExtensions + { + /// + /// Copies a texture memory region from one resource (a buffer) to another (a texture). + /// + /// The instance in use. + /// The destination (a texture) to write to. + /// The parameter curreently in use by the texture. + /// The horizontal offset in the destination texture. + /// The vertical offset in the destination texture. + /// The source (a buffer) to read from. + /// The width of the memory area to write to. + /// The height of the memory area to write to. + /// The size of each element to copy. + + public static void CopyTextureRegion( + this ref ID3D12GraphicsCommandList d3D12GraphicsCommandList, + ID3D12Resource* d3d12ResourceDestination, + DXGI_FORMAT dxgiFormat, + uint x, + uint y, + ID3D12Resource* d3D12ResourceSource, + uint width, + uint height, + uint elementSizeInBytes) + { + D3D12_SUBRESOURCE_FOOTPRINT d3D12SubresourceFootprint = new( + dxgiFormat, + width, + height, + 1, + (elementSizeInBytes * width + FX.D3D12_TEXTURE_DATA_PITCH_ALIGNMENT - 1) & ~((uint)FX.D3D12_TEXTURE_DATA_PITCH_ALIGNMENT - 1)); + D3D12_PLACED_SUBRESOURCE_FOOTPRINT d3D12PlacedSubresourceFootprint; + d3D12PlacedSubresourceFootprint.Offset = 0; + d3D12PlacedSubresourceFootprint.Footprint = d3D12SubresourceFootprint; + D3D12_TEXTURE_COPY_LOCATION + d3D12TextureCopyLocationDestination = new(d3d12ResourceDestination, 0), + d3D12TextureCopyLocationSource = new(d3D12ResourceSource, d3D12PlacedSubresourceFootprint); + + d3D12GraphicsCommandList.CopyTextureRegion(&d3D12TextureCopyLocationDestination, x, y, 0, &d3D12TextureCopyLocationSource, null); + } + + /// + /// Copies a texture memory region from one resource (a texture) to another (a buffer). + /// + /// The instance in use. + /// The destination (a buffer) to write to. + /// The size of each element to copy. + /// The source (a texture) to read from. + /// The parameter curreently in use by the texture. + /// The horizontal offset in the destination texture. + /// The vertical offset in the destination texture. + /// The width of the memory area to write to. + /// The height of the memory area to write to. + public static void CopyTextureRegion( + this ref ID3D12GraphicsCommandList d3D12GraphicsCommandList, + ID3D12Resource* d3d12ResourceDestination, + uint elementSizeInBytes, + ID3D12Resource* d3D12ResourceSource, + DXGI_FORMAT dxgiFormat, + uint x, + uint y, + uint width, + uint height) + { + D3D12_SUBRESOURCE_FOOTPRINT d3D12SubresourceFootprint = new( + dxgiFormat, + width, + height, + 1, + (elementSizeInBytes * width + FX.D3D12_TEXTURE_DATA_PITCH_ALIGNMENT - 1) & ~((uint)FX.D3D12_TEXTURE_DATA_PITCH_ALIGNMENT - 1)); + D3D12_PLACED_SUBRESOURCE_FOOTPRINT d3D12PlacedSubresourceFootprint; + d3D12PlacedSubresourceFootprint.Offset = 0; + d3D12PlacedSubresourceFootprint.Footprint = d3D12SubresourceFootprint; + D3D12_TEXTURE_COPY_LOCATION + d3D12TextureCopyLocationDestination = new(d3d12ResourceDestination, d3D12PlacedSubresourceFootprint), + d3D12TextureCopyLocationSource = new(d3D12ResourceSource, 0); + D3D12_BOX d3D12Box = new((int)x, (int)y, (int)(x + width), (int)(y + height)); + + d3D12GraphicsCommandList.CopyTextureRegion(&d3D12TextureCopyLocationDestination, 0, 0, 0, &d3D12TextureCopyLocationSource, &d3D12Box); + } + } +} diff --git a/src/ComputeSharp.Graphics/Helpers/DXGIFormatHelper.cs b/src/ComputeSharp.Graphics/Helpers/DXGIFormatHelper.cs new file mode 100644 index 00000000..be8d5d21 --- /dev/null +++ b/src/ComputeSharp.Graphics/Helpers/DXGIFormatHelper.cs @@ -0,0 +1,44 @@ +using System.Diagnostics.Contracts; +using System.Numerics; +using System.Runtime.CompilerServices; +using Microsoft.Toolkit.Diagnostics; +using static TerraFX.Interop.DXGI_FORMAT; +using TerraFX.Interop; + +namespace ComputeSharp.Graphics.Helpers +{ + /// + /// A helper type with utility methods for . + /// + internal static class DXGIFormatHelper + { + /// + /// Gets the appropriate value for the input type argument. + /// + /// The input type argument to get the corresponding for. + /// The value corresponding to . + /// Thrown when the input type is not supported. + [Pure] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static DXGI_FORMAT GetForType() + where T : unmanaged + { + if (typeof(T) == typeof(int)) return DXGI_FORMAT_R32_SINT; + else if (typeof(T) == typeof(Int2)) return DXGI_FORMAT_R32G32_SINT; + else if (typeof(T) == typeof(Int3)) return DXGI_FORMAT_R32G32B32_SINT; + else if (typeof(T) == typeof(Int4)) return DXGI_FORMAT_R32G32B32A32_SINT; + else if (typeof(T) == typeof(uint)) return DXGI_FORMAT_R32_UINT; + else if (typeof(T) == typeof(UInt2)) return DXGI_FORMAT_R32G32_UINT; + else if (typeof(T) == typeof(UInt3)) return DXGI_FORMAT_R32G32B32_UINT; + else if (typeof(T) == typeof(UInt4)) return DXGI_FORMAT_R32G32B32A32_UINT; + else if (typeof(T) == typeof(float)) return DXGI_FORMAT_R32_FLOAT; + else if (typeof(T) == typeof(Float2)) return DXGI_FORMAT_R32G32_FLOAT; + else if (typeof(T) == typeof(Float3)) return DXGI_FORMAT_R32G32B32_FLOAT; + else if (typeof(T) == typeof(Float4)) return DXGI_FORMAT_R32G32B32A32_FLOAT; + else if (typeof(T) == typeof(Vector2)) return DXGI_FORMAT_R32G32_FLOAT; + else if (typeof(T) == typeof(Vector3)) return DXGI_FORMAT_R32G32B32_FLOAT; + else if (typeof(T) == typeof(Vector4)) return DXGI_FORMAT_R32G32B32A32_FLOAT; + else return ThrowHelper.ThrowArgumentException("Invalid texture type"); + } + } +} diff --git a/src/ComputeSharp.Shaders/Mappings/HlslKnownTypes.cs b/src/ComputeSharp.Shaders/Mappings/HlslKnownTypes.cs index 1396b16c..7ade5bc9 100644 --- a/src/ComputeSharp.Shaders/Mappings/HlslKnownTypes.cs +++ b/src/ComputeSharp.Shaders/Mappings/HlslKnownTypes.cs @@ -50,8 +50,8 @@ namespace ComputeSharp.Shaders.Mappings /// A indicating whether the input is in fact a known buffer type. [Pure] public static bool IsKnownBufferType(Type type) => IsConstantBufferType(type) || - IsReadOnlyBufferType(type) || - IsReadWriteBufferType(type); + IsReadOnlyResourceType(type) || + IsReadWriteResourceType(type); /// /// Checks whether or not the input type is a value. @@ -63,21 +63,37 @@ namespace ComputeSharp.Shaders.Mappings type.GetGenericTypeDefinition() == typeof(ConstantBuffer<>); /// - /// Checks whether or not the input type is a value. + /// Checks whether or not the input type is a or value. /// /// The input instance to check. - /// A indicating whether the input is in fact a instance. + /// A indicating whether the input is a readonly resource type. [Pure] - public static bool IsReadOnlyBufferType(Type type) => type.IsGenericType && - type.GetGenericTypeDefinition() == typeof(ReadOnlyBuffer<>); + public static bool IsReadOnlyResourceType(Type type) + { + if (!type.IsGenericType) return false; + + Type genericType = type.GetGenericTypeDefinition(); + + return + genericType == typeof(ReadOnlyBuffer<>) || + genericType == typeof(ReadOnlyTexture2D<>); + } /// - /// Checks whether or not the input type is a value. + /// Checks whether or not the input type is a or value. /// /// The input instance to check. - /// A indicating whether the input is in fact a instance. + /// A indicating whether the input is a writeable resource type. [Pure] - public static bool IsReadWriteBufferType(Type type) => type.IsGenericType && - type.GetGenericTypeDefinition() == typeof(ReadWriteBuffer<>); + public static bool IsReadWriteResourceType(Type type) + { + if (!type.IsGenericType) return false; + + Type genericType = type.GetGenericTypeDefinition(); + + return + genericType == typeof(ReadWriteBuffer<>) || + genericType == typeof(ReadWriteTexture2D<>); + } } } diff --git a/src/ComputeSharp.Shaders/Renderer/HlslShaderRenderer.cs b/src/ComputeSharp.Shaders/Renderer/HlslShaderRenderer.cs index 1db89f72..72ee091e 100644 --- a/src/ComputeSharp.Shaders/Renderer/HlslShaderRenderer.cs +++ b/src/ComputeSharp.Shaders/Renderer/HlslShaderRenderer.cs @@ -60,14 +60,14 @@ namespace ComputeSharp.Shaders.Renderer builder.AppendLine('}'); // Buffers - foreach (var buffer in info.HslsBuffersInfo) + foreach (var buffer in info.HlslResourceInfo) { builder.AppendLine(); switch (buffer) { // Constant buffer go to cbuffer fields with a dummy local - case HlslBufferInfo.Constant _: + case HlslResourceInfo.Constant _: builder.Append("cbuffer _"); builder.Append(buffer.FieldName); builder.Append(" : register(b"); @@ -83,10 +83,10 @@ namespace ComputeSharp.Shaders.Renderer break; // Structured buffer have the same syntax but different id - case HlslBufferInfo.ReadOnly _: + case HlslResourceInfo.ReadOnly _: char registerId = 't'; goto StructuredBuffer; - case HlslBufferInfo.ReadWrite _: + case HlslResourceInfo.ReadWrite _: registerId = 'u'; StructuredBuffer: builder.Append(buffer.FieldType); diff --git a/src/ComputeSharp.Shaders/Renderer/Models/HlslBufferInfo.cs b/src/ComputeSharp.Shaders/Renderer/Models/HlslResourceInfo.cs similarity index 57% rename from src/ComputeSharp.Shaders/Renderer/Models/HlslBufferInfo.cs rename to src/ComputeSharp.Shaders/Renderer/Models/HlslResourceInfo.cs index 5b9b90bb..f89cb615 100644 --- a/src/ComputeSharp.Shaders/Renderer/Models/HlslBufferInfo.cs +++ b/src/ComputeSharp.Shaders/Renderer/Models/HlslResourceInfo.cs @@ -1,32 +1,34 @@ namespace ComputeSharp.Shaders.Renderer.Models { /// - /// A model that contains info on a shader buffer field. + /// A model that contains info on a shader typed resource field. /// /// The type of the current field in the HLSL shader. /// The name to use for the current field. - internal abstract record HlslBufferInfo(string FieldType, string FieldName, int BufferIndex) + internal abstract record HlslResourceInfo(string FieldType, string FieldName, int BufferIndex) : CapturedFieldInfo(FieldType, FieldName) { - /// /// /// A model that represents a captured constant buffer in a shader. /// + /// public sealed record Constant(string FieldType, string FieldName, int BufferIndex) - : HlslBufferInfo(FieldType, FieldName, BufferIndex); + : HlslResourceInfo(FieldType, FieldName, BufferIndex); - /// /// - /// A model that represents a captured readonly buffer in a shader. + /// A model that represents a captured readonly typed resource in a shader. + /// Maps to either or . /// - public sealed record ReadOnly(string FieldType, string FieldName, int BufferIndex) - : HlslBufferInfo(FieldType, FieldName, BufferIndex); - /// + public sealed record ReadOnly(string FieldType, string FieldName, int BufferIndex) + : HlslResourceInfo(FieldType, FieldName, BufferIndex); + /// /// A model that represents a captured writeable buffer in a shader. + /// Maps to either or . /// + /// public sealed record ReadWrite(string FieldType, string FieldName, int BufferIndex) - : HlslBufferInfo(FieldType, FieldName, BufferIndex); + : HlslResourceInfo(FieldType, FieldName, BufferIndex); } } diff --git a/src/ComputeSharp.Shaders/Renderer/Models/ShaderInfo.cs b/src/ComputeSharp.Shaders/Renderer/Models/ShaderInfo.cs deleted file mode 100644 index 3ae877df..00000000 --- a/src/ComputeSharp.Shaders/Renderer/Models/ShaderInfo.cs +++ /dev/null @@ -1,62 +0,0 @@ -using System.Collections.Generic; - -#pragma warning disable CS8618 - -namespace ComputeSharp.Shaders.Renderer.Models -{ - /// - /// A that contains info to render a shader source to compile. - /// - internal sealed class ShaderInfo - { - /// - /// Gets or sets the list of captured buffers being present in the current shader. - /// - public IReadOnlyList BuffersList { get; init; } - - /// - /// Gets or sets the list of captured variables being present in the current shader. - /// - public IReadOnlyList FieldsList { get; init; } - - /// - /// Gets or sets the number of threads in the X group. - /// - public int NumThreadsX { get; init; } - - /// - /// Gets or sets the number of threads in the Y group. - /// - public int NumThreadsY { get; init; } - - /// - /// Gets or sets the number of threads in the Z group. - /// - public int NumThreadsZ { get; init; } - - /// - /// Gets or sets the name for the threads id variable used in the shader. - /// - public string ThreadsIdsVariableName { get; init; } - - /// - /// Gets or sets the entry point of the shader. - /// - public string EntryPoint { get; init; } - - /// - /// Gets or sets the list of static functions used by the shader. - /// - public IReadOnlyCollection FunctionsList { get; init; } // TODO - - /// - /// Gets or sets the list of local functions used by the shader. - /// - public IReadOnlyCollection LocalFunctionsList { get; init; } - - /// - /// Gets or sets the list of dependent types for the shader. - /// - public IReadOnlyCollection DeclaredTypes { get; init; } - } -} diff --git a/src/ComputeSharp.Shaders/Translation/IShaderLoader.cs b/src/ComputeSharp.Shaders/Translation/IShaderLoader.cs index 9a4724a7..1a8b5be0 100644 --- a/src/ComputeSharp.Shaders/Translation/IShaderLoader.cs +++ b/src/ComputeSharp.Shaders/Translation/IShaderLoader.cs @@ -14,9 +14,9 @@ namespace ComputeSharp.Shaders.Translation public string EntryPoint { get; } /// - /// Gets the collection of items for the shader fields. + /// Gets the collection of items for the shader fields. /// - public IReadOnlyList HslsBuffersInfo { get; } + public IReadOnlyList HlslResourceInfo { get; } /// /// Gets the collection of items for the shader fields. diff --git a/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.IL.cs b/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.IL.cs index 7da9b114..33fa3804 100644 --- a/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.IL.cs +++ b/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.IL.cs @@ -114,14 +114,14 @@ namespace ComputeSharp.Shaders.Translation nameof(NativeObject.ThrowIfDisposed), BindingFlags.Instance | BindingFlags.NonPublic)!, null); - // Call Buffer.ThrowIfDeviceMismatch(GraphicsDevice) + // Call ThrowIfDeviceMismatch(GraphicsDevice) il.Emit(OpCodes.Dup); il.Emit(OpCodes.Ldarg_1); il.EmitCall(OpCodes.Callvirt, fieldInfo.FieldType.GetMethod( nameof(Buffer.ThrowIfDeviceMismatch), BindingFlags.Instance | BindingFlags.NonPublic)!, null); - // Access Buffer.D3D12GpuDescriptorHandle + // Access D3D12GpuDescriptorHandle il.EmitReadMember(fieldInfo.FieldType.GetField( nameof(Buffer.D3D12GpuDescriptorHandle), BindingFlags.Instance | BindingFlags.NonPublic)!); diff --git a/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs b/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs index 5411b172..989207a2 100644 --- a/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs +++ b/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs @@ -47,9 +47,9 @@ namespace ComputeSharp.Shaders.Translation private readonly List d3D12DescriptorRanges1 = new(); /// - /// The with the items for the shader fields. + /// The with the items for the shader fields. /// - private readonly List hlslBuffersInfo = new(); + private readonly List hlslResourceInfo = new(); /// /// The with the items for the shader fields. @@ -85,7 +85,7 @@ namespace ComputeSharp.Shaders.Translation public string EntryPoint { get; private set; } /// - public IReadOnlyList HslsBuffersInfo => this.hlslBuffersInfo; + public IReadOnlyList HlslResourceInfo => this.hlslResourceInfo; /// public IReadOnlyList FieldsInfo => this.fieldsInfo; @@ -156,32 +156,29 @@ namespace ComputeSharp.Shaders.Translation Type fieldType = fieldInfo.FieldType; (string hlslName, string hlslType) = Attribute.Fields[fieldInfo.Name]; - // Constant buffer if (HlslKnownTypes.IsConstantBufferType(fieldType)) { D3D12_DESCRIPTOR_RANGE1 d3D12DescriptorRange1 = new(D3D12_DESCRIPTOR_RANGE_TYPE_CBV, 1, this.constantBuffersCount); this.d3D12DescriptorRanges1.Add(d3D12DescriptorRange1); this.capturedFields.Add(fieldInfo); - this.hlslBuffersInfo.Add(new HlslBufferInfo.Constant(hlslType, hlslName, (int)this.constantBuffersCount++)); + this.hlslResourceInfo.Add(new HlslResourceInfo.Constant(hlslType, hlslName, (int)this.constantBuffersCount++)); } - else if (HlslKnownTypes.IsReadOnlyBufferType(fieldType)) + else if (HlslKnownTypes.IsReadOnlyResourceType(fieldType)) { - // Root parameter for a readonly buffer D3D12_DESCRIPTOR_RANGE1 d3D12DescriptorRange1 = new(D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 1, this.readOnlyBuffersCount); this.d3D12DescriptorRanges1.Add(d3D12DescriptorRange1); this.capturedFields.Add(fieldInfo); - this.hlslBuffersInfo.Add(new HlslBufferInfo.ReadOnly(hlslType, hlslName, (int)this.readOnlyBuffersCount++)); + this.hlslResourceInfo.Add(new HlslResourceInfo.ReadOnly(hlslType, hlslName, (int)this.readOnlyBuffersCount++)); } - else if (HlslKnownTypes.IsReadWriteBufferType(fieldType)) + else if (HlslKnownTypes.IsReadWriteResourceType(fieldType)) { - // Root parameter for a read write buffer D3D12_DESCRIPTOR_RANGE1 d3D12DescriptorRange1 = new(D3D12_DESCRIPTOR_RANGE_TYPE_UAV, 1, this.readWriteBuffersCount); this.d3D12DescriptorRanges1.Add(d3D12DescriptorRange1); this.capturedFields.Add(fieldInfo); - this.hlslBuffersInfo.Add(new HlslBufferInfo.ReadWrite(hlslType, hlslName, (int)this.readWriteBuffersCount++)); + this.hlslResourceInfo.Add(new HlslResourceInfo.ReadWrite(hlslType, hlslName, (int)this.readWriteBuffersCount++)); } else if (HlslKnownTypes.IsKnownScalarType(fieldType) || HlslKnownTypes.IsKnownVectorType(fieldType)) { diff --git a/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs b/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs index b5cb0deb..f80986f1 100644 --- a/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs @@ -120,7 +120,7 @@ namespace ComputeSharp.SourceGenerators yield return new[] { fieldSymbol.Name, mapping ?? fieldSymbol.Name, typeName }; // Track the type of items in the current buffer - if (HlslKnownTypes.IsStructuredBufferType(typeSymbol.GetFullMetadataName())) + if (HlslKnownTypes.IsTypedResourceType(typeSymbol.GetFullMetadataName())) { types.Add((INamedTypeSymbol)typeSymbol.TypeArguments[0]); } diff --git a/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownTypes.cs b/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownTypes.cs index 39cfc05a..5b3b9299 100644 --- a/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownTypes.cs +++ b/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownTypes.cs @@ -57,15 +57,17 @@ namespace ComputeSharp.SourceGenerators.Mappings }); /// - /// Checks whether or not a given type name matches a structured buffer type. + /// Checks whether or not a given type name matches a typed resource type. /// /// The input type name to check. - /// Whether or not represents a structured buffer type. - public static bool IsStructuredBufferType(string typeName) + /// Whether or not represents a typed resource type. + public static bool IsTypedResourceType(string typeName) { return typeName == "ComputeSharp.ReadOnlyBuffer`1" || - typeName == "ComputeSharp.ReadWriteBuffer`1"; + typeName == "ComputeSharp.ReadWriteBuffer`1" || + typeName == "ComputeSharp.ReadOnlyTexture2D`1" || + typeName == "ComputeSharp.ReadWriteTexture2D`1"; } /// @@ -83,7 +85,7 @@ namespace ComputeSharp.SourceGenerators.Mappings string typeName = typeSymbol.GetFullMetadataName(); // Special case for the structured buffer types - if (IsStructuredBufferType(typeName)) + if (IsTypedResourceType(typeName)) { string genericArgumentName = ((INamedTypeSymbol)typeSymbol.TypeArguments[0]).GetFullMetadataName(); @@ -98,6 +100,8 @@ namespace ComputeSharp.SourceGenerators.Mappings { "ComputeSharp.ReadOnlyBuffer`1" => $"StructuredBuffer<{mapped}>", "ComputeSharp.ReadWriteBuffer`1" => $"RWStructuredBuffer<{mapped}>", + "ComputeSharp.ReadOnlyTexture2D`1" => $"Texture2D<{mapped}>", + "ComputeSharp.ReadWriteTexture2D`1" => $"RWTexture2D<{mapped}>", _ => throw new ArgumentException() }; } diff --git a/src/ComputeSharp/Extensions/GraphicsDeviceExtensions.cs b/src/ComputeSharp/Extensions/GraphicsDeviceExtensions.cs index 9b675154..303397c2 100644 --- a/src/ComputeSharp/Extensions/GraphicsDeviceExtensions.cs +++ b/src/ComputeSharp/Extensions/GraphicsDeviceExtensions.cs @@ -36,7 +36,7 @@ namespace ComputeSharp public static ConstantBuffer AllocateConstantBuffer(this GraphicsDevice device, T[] array) where T : unmanaged { - return device.AllocateConstantBuffer(array.AsSpan()); + return device.AllocateConstantBuffer(array.AsSpan()); } /// @@ -44,10 +44,10 @@ namespace ComputeSharp /// /// The type of items to store in the buffer. /// The instance to use to allocate the buffer. - /// The input with the data to copy on the allocated buffer. - /// A constant instance with the contents of the input . + /// The input with the data to copy on the allocated buffer. + /// A constant instance with the contents of the input . [Pure] - public static ConstantBuffer AllocateConstantBuffer(this GraphicsDevice device, Span span) + public static ConstantBuffer AllocateConstantBuffer(this GraphicsDevice device, ReadOnlySpan span) where T : unmanaged { ConstantBuffer buffer = new(device, span.Length); @@ -100,7 +100,7 @@ namespace ComputeSharp public static ReadOnlyBuffer AllocateReadOnlyBuffer(this GraphicsDevice device, T[] array) where T : unmanaged { - return device.AllocateReadOnlyBuffer(array.AsSpan()); + return device.AllocateReadOnlyBuffer(array.AsSpan()); } /// @@ -108,10 +108,10 @@ namespace ComputeSharp /// /// The type of items to store in the buffer. /// The instance to use to allocate the buffer. - /// The input with the data to copy on the allocated buffer. - /// A read write instance with the contents of the input . + /// The input with the data to copy on the allocated buffer. + /// A read write instance with the contents of the input . [Pure] - public static ReadOnlyBuffer AllocateReadOnlyBuffer(this GraphicsDevice device, Span span) + public static ReadOnlyBuffer AllocateReadOnlyBuffer(this GraphicsDevice device, ReadOnlySpan span) where T : unmanaged { ReadOnlyBuffer buffer = new(device, span.Length); @@ -164,7 +164,7 @@ namespace ComputeSharp public static ReadWriteBuffer AllocateReadWriteBuffer(this GraphicsDevice device, T[] array) where T : unmanaged { - return device.AllocateReadWriteBuffer(array.AsSpan()); + return device.AllocateReadWriteBuffer(array.AsSpan()); } /// @@ -172,10 +172,10 @@ namespace ComputeSharp /// /// The type of items to store in the buffer. /// The instance to use to allocate the buffer. - /// The input with the data to copy on the allocated buffer. - /// A read write instance with the contents of the input . + /// The input with the data to copy on the allocated buffer. + /// A read write instance with the contents of the input . [Pure] - public static ReadWriteBuffer AllocateReadWriteBuffer(this GraphicsDevice device, Span span) + public static ReadWriteBuffer AllocateReadWriteBuffer(this GraphicsDevice device, ReadOnlySpan span) where T : unmanaged { ReadWriteBuffer buffer = new(device, span.Length); @@ -203,6 +203,178 @@ namespace ComputeSharp return readWriteBuffer; } + /// + /// Allocates a new readonly 2D texture with the specified parameters. + /// + /// The type of items to store in the texture. + /// The instance to use to allocate the texture. + /// The width of the texture. + /// The height of the texture. + /// A zeroed instance of size [, ]. + [Pure] + public static ReadOnlyTexture2D AllocateReadOnlyTexture2D(this GraphicsDevice device, int width, int height) + where T : unmanaged + { + return new(device, width, height); + } + + /// + /// Allocates a new readonly 2D texture with the specified parameters. + /// + /// The type of items to store in the texture. + /// The instance to use to allocate the texture. + /// The input array with the data to copy on the allocated texture. + /// The width of the texture. + /// The height of the texture. + /// A instance with the contents of the input array. + [Pure] + public static ReadOnlyTexture2D AllocateReadOnlyTexture2D(this GraphicsDevice device, T[] array, int width, int height) + where T : unmanaged + { + return device.AllocateReadOnlyTexture2D(array.AsSpan(), width, height); + } + + /// + /// Allocates a new readonly 2D texture with the specified parameters. + /// + /// The type of items to store in the texture. + /// The instance to use to allocate the texture. + /// The input array with the data to copy on the allocated texture. + /// The starting offset within to read data from. + /// The width of the texture. + /// The height of the texture. + /// A instance with the contents of the input array. + [Pure] + public static ReadOnlyTexture2D AllocateReadOnlyTexture2D(this GraphicsDevice device, T[] array, int offset, int width, int height) + where T : unmanaged + { + return device.AllocateReadOnlyTexture2D(array.AsSpan(offset), width, height); + } + + /// + /// Allocates a new readonly 2D texture with the specified parameters. + /// + /// The type of items to store in the texture. + /// The instance to use to allocate the texture. + /// The input array with the data to copy on the allocated texture. + /// A read write instance with the contents of the input array. + [Pure] + public static ReadOnlyTexture2D AllocateReadOnlyTexture2D(this GraphicsDevice device, T[,] array) + where T : unmanaged + { + ReadOnlyTexture2D texture = new(device, array.GetLength(1), array.GetLength(0)); + + texture.SetData(array); + + return texture; + } + + /// + /// Allocates a new readonly 2D texture with the specified parameters. + /// + /// The type of items to store in the texture. + /// The instance to use to allocate the texture. + /// The input with the data to copy on the allocated texture. + /// The width of the texture. + /// The height of the texture. + /// A instance with the contents of the input . + [Pure] + public static ReadOnlyTexture2D AllocateReadOnlyTexture2D(this GraphicsDevice device, ReadOnlySpan span, int width, int height) + where T : unmanaged + { + ReadOnlyTexture2D texture = new(device, width, height); + + texture.SetData(span); + + return texture; + } + + /// + /// Allocates a new writeable 2D texture with the specified parameters. + /// + /// The type of items to store in the texture. + /// The instance to use to allocate the texture. + /// The width of the texture. + /// The height of the texture. + /// A zeroed instance of size [, ]. + [Pure] + public static ReadWriteTexture2D AllocateReadWriteTexture2D(this GraphicsDevice device, int width, int height) + where T : unmanaged + { + return new(device, width, height); + } + + /// + /// Allocates a new writeable 2D texture with the specified parameters. + /// + /// The type of items to store in the texture. + /// The instance to use to allocate the texture. + /// The input array with the data to copy on the allocated texture. + /// The width of the texture. + /// The height of the texture. + /// A instance with the contents of the input array. + [Pure] + public static ReadWriteTexture2D AllocateReadWriteTexture2D(this GraphicsDevice device, T[] array, int width, int height) + where T : unmanaged + { + return device.AllocateReadWriteTexture2D(array.AsSpan(), width, height); + } + + /// + /// Allocates a new writeable 2D texture with the specified parameters. + /// + /// The type of items to store in the texture. + /// The instance to use to allocate the texture. + /// The input array with the data to copy on the allocated texture. + /// The starting offset within to read data from. + /// The width of the texture. + /// The height of the texture. + /// A instance with the contents of the input array. + [Pure] + public static ReadWriteTexture2D AllocateReadWriteTexture2D(this GraphicsDevice device, T[] array, int offset, int width, int height) + where T : unmanaged + { + return device.AllocateReadWriteTexture2D(array.AsSpan(offset), width, height); + } + + /// + /// Allocates a new writeable 2D texture with the specified parameters. + /// + /// The type of items to store in the texture. + /// The instance to use to allocate the texture. + /// The input array with the data to copy on the allocated texture. + /// A read write instance with the contents of the input array. + [Pure] + public static ReadWriteTexture2D AllocateReadWriteTexture2D(this GraphicsDevice device, T[,] array) + where T : unmanaged + { + ReadWriteTexture2D texture = new(device, array.GetLength(1), array.GetLength(0)); + + texture.SetData(array); + + return texture; + } + + /// + /// Allocates a new writeable 2D texture with the specified parameters. + /// + /// The type of items to store in the texture. + /// The instance to use to allocate the texture. + /// The input with the data to copy on the allocated texture. + /// The width of the texture. + /// The height of the texture. + /// A instance with the contents of the input . + [Pure] + public static ReadWriteTexture2D AllocateReadWriteTexture2D(this GraphicsDevice device, ReadOnlySpan span, int width, int height) + where T : unmanaged + { + ReadWriteTexture2D texture = new(device, width, height); + + texture.SetData(span); + + return texture; + } + /// /// Compiles and runs the input shader on a target instance, with the specified parameters. ///