Removed Vortice.Windows references and files

このコミットが含まれているのは:
Sergio Pedri committed 2020-11-17 19:40:24 +01:00
1 親 b67af4aaa1
コミット 4811769ebc
46ファイル変更
+1124 -3358

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

+35 -39
ファイルの表示
@@ -1,89 +1,85 @@
using System;
using ComputeSharp.Core.Interop;
using ComputeSharp.Graphics.Extensions;
using System;
using System.Runtime.CompilerServices;
using Vortice.Direct3D12;
using TerraFX.Interop;
namespace ComputeSharp.Graphics.Buffers.Abstract
{
/// <summary>
/// An abstract <see langword="class"/> that represents a graphics resource object
/// An abstract <see langword="class"/> that represents a graphics resource object.
/// </summary>
public abstract class GraphicsResource : IDisposable
public abstract unsafe class GraphicsResource : NativeObject
{
/// <summary>
/// Creates a new <see cref="GraphicsResource"/> instance with the specified parameters
/// The <see cref="ID3D12Resource"/> instance currently mapped.
/// </summary>
/// <param name="device">The <see cref="GraphicsDevice"/> associated with the current instance</param>
protected GraphicsResource(GraphicsDevice device)
protected internal readonly ID3D12Resource* D3D12Resource;
/// <summary>
/// Creates a new <see cref="GraphicsResource"/> instance with the specified parameters.
/// </summary>
/// <param name="device">The <see cref="GraphicsDevice"/> associated with the current instance.</param>
protected GraphicsResource(GraphicsDevice device, ID3D12Resource* d3d12resource)
{
D3D12Resource = d3d12resource;
GraphicsDevice = device;
}
/// <summary>
/// Gets the <see cref="GraphicsDevice"/> associated with the current instance
/// Gets the <see cref="GraphicsDevice"/> associated with the current instance.
/// </summary>
public GraphicsDevice GraphicsDevice { get; }
/// <summary>
/// Gets the <see cref="ID3D12Resource"/> object currently mapped
/// Maps the current resource to a specified subresource.
/// </summary>
protected internal ID3D12Resource? NativeResource { get; set; }
/// <summary>
/// Gets the <see cref="CpuDescriptorHandle"/> instance for the current resource
/// </summary>
protected internal CpuDescriptorHandle? NativeCpuDescriptorHandle { get; protected set; }
/// <summary>
/// Gets the <see cref="GpuDescriptorHandle"/> instance for the current resource
/// </summary>
protected internal GpuDescriptorHandle? NativeGpuDescriptorHandle { get; protected set; }
/// <summary>
/// Maps the current resource to a specified subresource
/// </summary>
/// <returns>A <see cref="MappedResource"/> instance representing the mapped resource</returns>
/// <returns>A <see cref="MappedResource"/> instance representing the mapped resource.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal MappedResource MapResource()
{
var resource = NativeResource ?? throw new InvalidOperationException("Missing resource");
return new MappedResource(resource);
return new MappedResource(D3D12Resource);
}
/// <inheritdoc/>
public virtual void Dispose() => NativeResource?.Dispose();
protected override void OnDispose()
{
D3D12Resource->Release();
}
/// <summary>
/// A type representing a mapped memory resource
/// A type representing a mapped memory resource.
/// </summary>
internal readonly ref struct MappedResource
{
/// <summary>
/// The target <see cref="ID3D12Resource"/> to map
/// The target <see cref="ID3D12Resource"/> to map.
/// </summary>
private readonly ID3D12Resource Resource;
private readonly ID3D12Resource* d3D12Resource;
/// <summary>
/// The pointer to the mapped resource
/// The pointer to the mapped resource.
/// </summary>
public readonly IntPtr Pointer;
/// <summary>
/// Creates a new <see cref="MappedResource"/> instance for a given <see cref="ID3D12Resource"/> value
/// Creates a new <see cref="MappedResource"/> instance for a given <see cref="ID3D12Resource"/> value.
/// </summary>
/// <param name="resource">The input <see cref="ID3D12Resource"/> instance to map</param>
/// <param name="resource">The input <see cref="ID3D12Resource"/> instance to map.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public MappedResource(ID3D12Resource resource)
public MappedResource(ID3D12Resource* d3d12resource)
{
Resource = resource;
Pointer = resource.Map(0);
d3D12Resource = d3d12resource;
Pointer = d3d12resource->Map();
}
/// <inheritdoc cref="IDisposable.Dispose"/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Dispose()
{
Resource.Unmap(0);
d3D12Resource->Unmap();
}
}
}
-86
ファイルの表示
@@ -1,86 +0,0 @@
using ComputeSharp.Core.Interop;
using ComputeSharp.Graphics.Extensions;
using System;
using System.Runtime.CompilerServices;
using TerraFX.Interop;
namespace ComputeSharp.Graphics.Buffers.Abstract
{
/// <summary>
/// An abstract <see langword="class"/> that represents a graphics resource object.
/// </summary>
public abstract unsafe class GraphicsResource2 : NativeObject
{
/// <summary>
/// The <see cref="ID3D12Resource"/> instance currently mapped.
/// </summary>
protected internal readonly ID3D12Resource* D3D12Resource;
/// <summary>
/// Creates a new <see cref="GraphicsResource"/> instance with the specified parameters.
/// </summary>
/// <param name="device">The <see cref="GraphicsDevice"/> associated with the current instance.</param>
protected GraphicsResource2(GraphicsDevice2 device, ID3D12Resource* d3d12resource)
{
D3D12Resource = d3d12resource;
GraphicsDevice = device;
}
/// <summary>
/// Gets the <see cref="GraphicsDevice"/> associated with the current instance.
/// </summary>
public GraphicsDevice2 GraphicsDevice { get; }
/// <summary>
/// Maps the current resource to a specified subresource.
/// </summary>
/// <returns>A <see cref="MappedResource"/> instance representing the mapped resource.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal MappedResource MapResource()
{
return new MappedResource(D3D12Resource);
}
/// <inheritdoc/>
protected override void OnDispose()
{
D3D12Resource->Release();
}
/// <summary>
/// A type representing a mapped memory resource.
/// </summary>
internal readonly ref struct MappedResource
{
/// <summary>
/// The target <see cref="ID3D12Resource"/> to map.
/// </summary>
private readonly ID3D12Resource* d3D12Resource;
/// <summary>
/// The pointer to the mapped resource.
/// </summary>
public readonly IntPtr Pointer;
/// <summary>
/// Creates a new <see cref="MappedResource"/> instance for a given <see cref="ID3D12Resource"/> value.
/// </summary>
/// <param name="resource">The input <see cref="ID3D12Resource"/> instance to map.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public MappedResource(ID3D12Resource* d3d12resource)
{
d3D12Resource = d3d12resource;
Pointer = d3d12resource->Map();
}
/// <inheritdoc cref="IDisposable.Dispose"/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Dispose()
{
d3D12Resource->Unmap();
}
}
}
}
-115
ファイルの表示
@@ -1,115 +0,0 @@
using System;
using System.Buffers;
using System.Diagnostics.Contracts;
using ComputeSharp.Graphics.Buffers.Enums;
namespace ComputeSharp.Graphics.Buffers.Abstract
{
/// <summary>
/// A <see langword="class"/> representing a typed buffer stored on GPU memory, that can be used from an HLSL shader
/// </summary>
/// <typeparam name="T">The type of items stored on the buffer</typeparam>
public abstract class HlslBuffer2<T> : Buffer2<T> where T : unmanaged
{
/// <summary>
/// Creates a new <see cref="HlslBuffer2{T}"/> instance with the specified parameters
/// </summary>
/// <param name="device">The <see cref="GraphicsDevice2"/> associated with the current instance</param>
/// <param name="size">The number of items to store in the current buffer</param>
/// <param name="sizeInBytes">The size in bytes for the current buffer</param>
/// <param name="bufferType">The buffer type for the current buffer</param>
private protected HlslBuffer2(GraphicsDevice2 device, int size, int sizeInBytes, BufferType bufferType)
: base(device, size, sizeInBytes, bufferType)
{
}
/// <summary>
/// Reads the contents of the current <see cref="HlslBuffer2{T}"/> instance and returns an array
/// </summary>
/// <returns>A <typeparamref name="T"/> array with the contents of the current buffer</returns>
[Pure]
public T[] GetData() => GetData(0, Size);
/// <summary>
/// Reads the contents of the current <see cref="HlslBuffer2{T}"/> instance in a given range and returns an array
/// </summary>
/// <param name="offset">The offset to start reading data from</param>
/// <param name="count">The number of items to read</param>
/// <returns>A <typeparamref name="T"/> array with the contents of the specified range from the current buffer</returns>
[Pure]
public T[] GetData(int offset, int count)
{
T[] data = new T[count];
GetData(data, offset, count);
return data;
}
/// <summary>
/// Reads the contents of the current <see cref="HlslBuffer2{T}"/> instance and writes them into a target <see cref="Span{T}"/>
/// </summary>
/// <param name="span">The input <see cref="Span{T}"/> to write data to</param>
public void GetData(Span<T> span) => GetData(span, 0, Size);
/// <summary>
/// Reads the contents of the specified range from the current <see cref="HlslBuffer2{T}"/> instance and writes them into a target <see cref="Span{T}"/>
/// </summary>
/// <param name="span">The input <see cref="Span{T}"/> to write data to</param>
/// <param name="offset">The offset to start reading data from</param>
/// <param name="count">The number of items to read</param>
public abstract void GetData(Span<T> span, int offset, int count);
/// <summary>
/// Writes the contents of a given <typeparamref name="T"/> array to the current <see cref="HlslBuffer2{T}"/> instance
/// </summary>
/// <param name="array">The input <typeparamref name="T"/> array to read data from</param>
public void SetData(T[] array) => SetData(array.AsSpan());
/// <summary>
/// Writes the contents of a given <typeparamref name="T"/> array to a specified area of the current <see cref="HlslBuffer2{T}"/> instance
/// </summary>
/// <param name="array">The input <typeparamref name="T"/> array to read data from</param>
/// <param name="offset">The offset to start writing data to</param>
/// <param name="count">The number of items to write</param>
public void SetData(T[] array, int offset, int count) => SetData(array.AsSpan(), offset, count);
/// <summary>
/// Writes the contents of a given <see cref="ReadOnlySpan{T}"/> to the current <see cref="HlslBuffer2{T}"/> instance
/// </summary>
/// <param name="span">The input <see cref="ReadOnlySpan{T}"/> to read data from</param>
public void SetData(ReadOnlySpan<T> span) => SetData(span, 0, Size);
/// <summary>
/// Writes the contents of a given <see cref="ReadOnlySpan{T}"/> to a specified area of the current <see cref="HlslBuffer2{T}"/> instance
/// </summary>
/// <param name="span">The input <see cref="ReadOnlySpan{T}"/> to read data from</param>
/// <param name="offset">The offset to start writing data to</param>
/// <param name="count">The number of items to write</param>
public abstract void SetData(ReadOnlySpan<T> span, int offset, int count);
/// <summary>
/// Writes the contents of a given <see cref="HlslBuffer2{T}"/> to the current <see cref="HlslBuffer2{T}"/> instance
/// </summary>
/// <param name="buffer">The input <see cref="HlslBuffer2{T}"/> to read data from</param>
public abstract void SetData(HlslBuffer2<T> buffer);
/// <summary>
/// Writes the contents of a given <see cref="HlslBuffer2{T}"/> to the current <see cref="HlslBuffer2{T}"/> instance, using a temporary CPU buffer
/// </summary>
/// <param name="buffer">The input <see cref="HlslBuffer2{T}"/> to read data from</param>
protected void SetDataWithCpuBuffer(HlslBuffer2<T> buffer)
{
// Create a temporary array
T[] array = ArrayPool<T>.Shared.Rent(buffer.Size);
Span<T> span = array.AsSpan(0, buffer.Size);
// Get the unpadded data from the read write buffer
buffer.GetData(span);
// Set the data, adding the padding if needed
SetData(span);
ArrayPool<T>.Shared.Return(array);
}
}
}
+4 -1
ファイルの表示
@@ -18,7 +18,10 @@ namespace ComputeSharp.Graphics.Buffers.Abstract
/// <param name="size">The number of items to store in the current buffer</param>
/// <param name="sizeInBytes">The size in bytes for the current buffer</param>
/// <param name="bufferType">The buffer type for the current buffer</param>
private protected HlslBuffer(GraphicsDevice device, int size, int sizeInBytes, BufferType bufferType) : base(device, size, sizeInBytes, bufferType) { }
private protected HlslBuffer(GraphicsDevice device, int size, int sizeInBytes, BufferType bufferType)
: base(device, size, sizeInBytes, bufferType)
{
}
/// <summary>
/// Reads the contents of the current <see cref="HlslBuffer{T}"/> instance and returns an array
-74
ファイルの表示
@@ -1,74 +0,0 @@
using System;
using System.Runtime.CompilerServices;
using ComputeSharp.Graphics.Buffers.Enums;
using ComputeSharp.Graphics.Commands;
using ComputeSharp.Graphics.Helpers;
using static TerraFX.Interop.D3D12_COMMAND_LIST_TYPE;
namespace ComputeSharp.Graphics.Buffers.Abstract
{
/// <summary>
/// A <see langword="class"/> representing a typed structured buffer stored on GPU memory
/// </summary>
/// <typeparam name="T">The type of items stored on the buffer</typeparam>
public abstract class HlslStructuredBuffer2<T> : HlslBuffer2<T>
where T : unmanaged
{
/// <summary>
/// Creates a new <see cref="HlslStructuredBuffer2{T}"/> instance with the specified parameters
/// </summary>
/// <param name="device">The <see cref="GraphicsDevice2"/> associated with the current instance</param>
/// <param name="size">The number of items to store in the current buffer</param>
/// <param name="bufferType">The buffer type for the current buffer</param>
internal HlslStructuredBuffer2(GraphicsDevice2 device, int size, BufferType bufferType)
: base(device, size, size * Unsafe.SizeOf<T>(), bufferType)
{
}
/// <inheritdoc/>
public override unsafe void GetData(Span<T> span, int offset, int count)
{
using Buffer2<T> transferBuffer = new Buffer2<T>(GraphicsDevice, count, count * ElementSizeInBytes, BufferType.ReadBack);
using (CommandList2 copyCommandList = new CommandList2(GraphicsDevice, D3D12_COMMAND_LIST_TYPE_COPY))
{
copyCommandList.CopyBufferRegion(D3D12Resource, offset * ElementSizeInBytes, transferBuffer.D3D12Resource, 0, count * ElementSizeInBytes);
copyCommandList.ExecuteAndWaitForCompletion();
}
using MappedResource resource = transferBuffer.MapResource();
MemoryHelper.Copy(resource.Pointer, 0, span, 0, count);
}
/// <inheritdoc/>
public override unsafe void SetData(ReadOnlySpan<T> span, int offset, int count)
{
using Buffer2<T> transferBuffer = new Buffer2<T>(GraphicsDevice, count, count * ElementSizeInBytes, BufferType.Transfer);
using (MappedResource resource = transferBuffer.MapResource())
{
MemoryHelper.Copy(span, resource.Pointer, 0, count);
}
using CommandList2 copyCommandList = new CommandList2(GraphicsDevice, D3D12_COMMAND_LIST_TYPE_COPY);
copyCommandList.CopyBufferRegion(transferBuffer.D3D12Resource, 0, D3D12Resource, offset * ElementSizeInBytes, count * ElementSizeInBytes);
copyCommandList.ExecuteAndWaitForCompletion();
}
/// <inheritdoc/>
public override unsafe void SetData(HlslBuffer2<T> buffer)
{
if (!buffer.IsPaddingPresent)
{
// Directly copy the input buffer
using CommandList2 copyCommandList = new CommandList2(GraphicsDevice, D3D12_COMMAND_LIST_TYPE_COPY);
copyCommandList.CopyBufferRegion(buffer.D3D12Resource, 0, D3D12Resource, 0, SizeInBytes);
copyCommandList.ExecuteAndWaitForCompletion();
}
else SetDataWithCpuBuffer(buffer);
}
}
}
+15 -12
ファイルの表示
@@ -1,9 +1,9 @@
using System;
using System.Runtime.CompilerServices;
using ComputeSharp.Graphics.Buffers.Enums;
using ComputeSharp.Graphics.Commands;
using ComputeSharp.Graphics.Helpers;
using Vortice.Direct3D12;
using CommandList = ComputeSharp.Graphics.Commands.CommandList;
using static TerraFX.Interop.D3D12_COMMAND_LIST_TYPE;
namespace ComputeSharp.Graphics.Buffers.Abstract
{
@@ -20,16 +20,19 @@ namespace ComputeSharp.Graphics.Buffers.Abstract
/// <param name="device">The <see cref="GraphicsDevice"/> associated with the current instance</param>
/// <param name="size">The number of items to store in the current buffer</param>
/// <param name="bufferType">The buffer type for the current buffer</param>
internal HlslStructuredBuffer(GraphicsDevice device, int size, BufferType bufferType) : base(device, size, size * Unsafe.SizeOf<T>(), bufferType) { }
internal HlslStructuredBuffer(GraphicsDevice device, int size, BufferType bufferType)
: base(device, size, size * Unsafe.SizeOf<T>(), bufferType)
{
}
/// <inheritdoc/>
public override void GetData(Span<T> span, int offset, int count)
public override unsafe void GetData(Span<T> span, int offset, int count)
{
using Buffer<T> transferBuffer = new Buffer<T>(GraphicsDevice, count, count * ElementSizeInBytes, BufferType.ReadBack);
using (CommandList copyCommandList = new CommandList(GraphicsDevice, CommandListType.Copy))
using (CommandList copyCommandList = new CommandList(GraphicsDevice, D3D12_COMMAND_LIST_TYPE_COPY))
{
copyCommandList.CopyBufferRegion(this, offset * ElementSizeInBytes, transferBuffer, 0, count * ElementSizeInBytes);
copyCommandList.CopyBufferRegion(D3D12Resource, offset * ElementSizeInBytes, transferBuffer.D3D12Resource, 0, count * ElementSizeInBytes);
copyCommandList.ExecuteAndWaitForCompletion();
}
@@ -39,7 +42,7 @@ namespace ComputeSharp.Graphics.Buffers.Abstract
}
/// <inheritdoc/>
public override void SetData(ReadOnlySpan<T> span, int offset, int count)
public override unsafe void SetData(ReadOnlySpan<T> span, int offset, int count)
{
using Buffer<T> transferBuffer = new Buffer<T>(GraphicsDevice, count, count * ElementSizeInBytes, BufferType.Transfer);
@@ -48,21 +51,21 @@ namespace ComputeSharp.Graphics.Buffers.Abstract
MemoryHelper.Copy(span, resource.Pointer, 0, count);
}
using CommandList copyCommandList = new CommandList(GraphicsDevice, CommandListType.Copy);
using CommandList copyCommandList = new CommandList(GraphicsDevice, D3D12_COMMAND_LIST_TYPE_COPY);
copyCommandList.CopyBufferRegion(transferBuffer, 0, this, offset * ElementSizeInBytes, count * ElementSizeInBytes);
copyCommandList.CopyBufferRegion(transferBuffer.D3D12Resource, 0, D3D12Resource, offset * ElementSizeInBytes, count * ElementSizeInBytes);
copyCommandList.ExecuteAndWaitForCompletion();
}
/// <inheritdoc/>
public override void SetData(HlslBuffer<T> buffer)
public override unsafe void SetData(HlslBuffer<T> buffer)
{
if (!buffer.IsPaddingPresent)
{
// Directly copy the input buffer
using CommandList copyCommandList = new CommandList(GraphicsDevice, CommandListType.Copy);
using CommandList copyCommandList = new CommandList(GraphicsDevice, D3D12_COMMAND_LIST_TYPE_COPY);
copyCommandList.CopyBufferRegion(buffer, 0, this, 0, SizeInBytes);
copyCommandList.CopyBufferRegion(buffer.D3D12Resource, 0, D3D12Resource, 0, SizeInBytes);
copyCommandList.ExecuteAndWaitForCompletion();
}
else SetDataWithCpuBuffer(buffer);
-156
ファイルの表示
@@ -1,156 +0,0 @@
using System.Runtime.CompilerServices;
using ComputeSharp.Graphics.Buffers.Abstract;
using ComputeSharp.Graphics.Buffers.Enums;
using ComputeSharp.Graphics.Extensions;
using TerraFX.Interop;
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.Buffers
{
/// <summary>
/// A <see langword="class"/> representing a typed buffer stored on GPU memory.
/// </summary>
/// <typeparam name="T">The type of items stored on the buffer.</typeparam>
public unsafe class Buffer2<T> : GraphicsResource2
where T : unmanaged
{
/// <summary>
/// The <see cref="D3D12_CPU_DESCRIPTOR_HANDLE"/> instance for the current resource.
/// </summary>
protected internal readonly D3D12_CPU_DESCRIPTOR_HANDLE D3D12CpuDescriptorHandle;
/// <summary>
/// The <see cref="D3D12_GPU_DESCRIPTOR_HANDLE"/> instance for the current resource.
/// </summary>
protected internal readonly D3D12_GPU_DESCRIPTOR_HANDLE D3D12GpuDescriptorHandle;
/// <summary>
/// The size in bytes of the current buffer.
/// </summary>
protected readonly int SizeInBytes;
/// <summary>
/// The size in bytes of each <typeparamref name="T"/> value contained in the buffer.
/// </summary>
protected readonly int ElementSizeInBytes;
/// <summary>
/// The size in bytes of the current buffer.
/// </summary>
internal readonly int PaddedElementSizeInBytes;
/// <summary>
/// The buffer type for the current <see cref="Buffer{T}"/> instance.
/// </summary>
internal readonly BufferType BufferType;
/// <summary>
/// Creates a new <see cref="Buffer{T}"/> instance with the specified parameters
/// </summary>
/// <param name="device">The <see cref="GraphicsDevice"/> associated with the current instance</param>
/// <param name="size">The number of items to store in the current buffer</param>
/// <param name="sizeInBytes">The size in bytes for the current buffer</param>
/// <param name="bufferType">The buffer type for the current buffer</param>
internal Buffer2(GraphicsDevice2 device, int size, int sizeInBytes, BufferType bufferType)
: base(device, CreateCommittedResource(device.D3D12Device, bufferType, sizeInBytes))
{
Size = size;
SizeInBytes = sizeInBytes;
ElementSizeInBytes = Unsafe.SizeOf<T>();
BufferType = bufferType;
PaddedElementSizeInBytes = sizeInBytes / size;
if (bufferType is BufferType.Constant or BufferType.ReadOnly or BufferType.ReadWrite)
{
GraphicsDevice.AllocateShaderResourceViewDescriptorHandles(out D3D12CpuDescriptorHandle, out D3D12GpuDescriptorHandle);
switch (bufferType)
{
case BufferType.Constant: CreateConstantBufferView(); break;
case BufferType.ReadOnly: CreateShaderResourceView(); break;
case BufferType.ReadWrite: CreateUnorderedAccessView(); break;
}
}
}
/// <summary>
/// Gets the size of the current buffer, as in the number of <typeparamref name="T"/> values it contains
/// </summary>
public int Size { get; }
/// <summary>
/// Gets whether or not there is some padding between elements in the current buffer
/// </summary>
internal bool IsPaddingPresent => PaddedElementSizeInBytes > ElementSizeInBytes;
/// <summary>
/// Creates a committed resource for a given buffer type.
/// </summary>
/// <param name="d3D12Device">The <see cref="ID3D12Device"/> instance in use.</param>
/// <param name="bufferType">The buffer type currently in use.</param>
/// <param name="sizeInBytes">The size in bytes of the current buffer.</param>
/// <returns>An <see cref="ID3D12Resource"/> reference for the current buffer.</returns>
private static ID3D12Resource* CreateCommittedResource(ID3D12Device* d3D12Device, BufferType bufferType, int 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.Transfer => (D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_STATE_GENERIC_READ),
_ => throw null!
};
return d3D12Device->CreateCommittedResource(d3D12HeapType, (uint)sizeInBytes, d3D12ResourceFlags, d3D12ResourceStates);
}
/// <summary>
/// Creates a view for a constant buffer.
/// </summary>
private void CreateConstantBufferView()
{
uint constantBufferSize = (uint)((SizeInBytes + 255) & ~255);
D3D12_CONSTANT_BUFFER_VIEW_DESC d3D12ConstantBufferViewDescription;
d3D12ConstantBufferViewDescription.BufferLocation = D3D12Resource->GetGPUVirtualAddress();
d3D12ConstantBufferViewDescription.SizeInBytes = constantBufferSize;
GraphicsDevice.D3D12Device->CreateConstantBufferView(&d3D12ConstantBufferViewDescription, D3D12CpuDescriptorHandle);
}
/// <summary>
/// Creates a view for a readonly buffer.
/// </summary>
private void CreateShaderResourceView()
{
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)Size;
d3D12ShaderResourceViewDescription.Buffer.StructureByteStride = (uint)ElementSizeInBytes;
GraphicsDevice.D3D12Device->CreateShaderResourceView(D3D12Resource, &d3D12ShaderResourceViewDescription, D3D12CpuDescriptorHandle);
}
/// <summary>
/// Creates a view for a buffer than be both read and written to.
/// </summary>
private void CreateUnorderedAccessView()
{
D3D12_UNORDERED_ACCESS_VIEW_DESC d3D12UnorderedAccessViewDescription = default;
d3D12UnorderedAccessViewDescription.ViewDimension = D3D12_UAV_DIMENSION_BUFFER;
d3D12UnorderedAccessViewDescription.Buffer.NumElements = (uint)Size;
d3D12UnorderedAccessViewDescription.Buffer.StructureByteStride = (uint)ElementSizeInBytes;
GraphicsDevice.D3D12Device->CreateUnorderedAccessView(D3D12Resource, null, &d3D12UnorderedAccessViewDescription, D3D12CpuDescriptorHandle);
}
}
}
+103 -100
ファイルの表示
@@ -1,20 +1,54 @@
using System;
using System.Diagnostics.Contracts;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using ComputeSharp.Graphics.Buffers.Abstract;
using ComputeSharp.Graphics.Buffers.Enums;
using SharpGen.Runtime;
using Vortice.Direct3D12;
using ComputeSharp.Graphics.Extensions;
using TerraFX.Interop;
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.Buffers
{
/// <summary>
/// A <see langword="class"/> representing a typed buffer stored on GPU memory
/// A <see langword="class"/> representing a typed buffer stored on GPU memory.
/// </summary>
/// <typeparam name="T">The type of items stored on the buffer</typeparam>
public class Buffer<T> : GraphicsResource where T : unmanaged
/// <typeparam name="T">The type of items stored on the buffer.</typeparam>
public unsafe class Buffer<T> : GraphicsResource
where T : unmanaged
{
/// <summary>
/// The <see cref="D3D12_CPU_DESCRIPTOR_HANDLE"/> instance for the current resource.
/// </summary>
protected internal readonly D3D12_CPU_DESCRIPTOR_HANDLE D3D12CpuDescriptorHandle;
/// <summary>
/// The <see cref="D3D12_GPU_DESCRIPTOR_HANDLE"/> instance for the current resource.
/// </summary>
protected internal readonly D3D12_GPU_DESCRIPTOR_HANDLE D3D12GpuDescriptorHandle;
/// <summary>
/// The size in bytes of the current buffer.
/// </summary>
protected readonly int SizeInBytes;
/// <summary>
/// The size in bytes of each <typeparamref name="T"/> value contained in the buffer.
/// </summary>
protected readonly int ElementSizeInBytes;
/// <summary>
/// The size in bytes of the current buffer.
/// </summary>
internal readonly int PaddedElementSizeInBytes;
/// <summary>
/// The buffer type for the current <see cref="Buffer{T}"/> instance.
/// </summary>
internal readonly BufferType BufferType;
/// <summary>
/// Creates a new <see cref="Buffer{T}"/> instance with the specified parameters
/// </summary>
@@ -22,44 +56,26 @@ namespace ComputeSharp.Graphics.Buffers
/// <param name="size">The number of items to store in the current buffer</param>
/// <param name="sizeInBytes">The size in bytes for the current buffer</param>
/// <param name="bufferType">The buffer type for the current buffer</param>
internal Buffer(GraphicsDevice device, int size, int sizeInBytes, BufferType bufferType) : base(device)
internal Buffer(GraphicsDevice device, int size, int sizeInBytes, BufferType bufferType)
: base(device, CreateCommittedResource(device.D3D12Device, bufferType, sizeInBytes))
{
Size = size;
SizeInBytes = sizeInBytes; // Not necessarily a multiple of the element size, as there could be padding
SizeInBytes = sizeInBytes;
ElementSizeInBytes = Unsafe.SizeOf<T>();
BufferType = bufferType;
PaddedElementSizeInBytes = sizeInBytes / size;
// Determine the right heap type and flags
(HeapType heapType, ResourceFlags flags, ResourceStates states) = bufferType switch
if (bufferType is BufferType.Constant or BufferType.ReadOnly or BufferType.ReadWrite)
{
BufferType.Constant => (HeapType.Upload, ResourceFlags.None, ResourceStates.GenericRead),
BufferType.ReadOnly => (HeapType.Default, ResourceFlags.None, ResourceStates.Common),
BufferType.ReadWrite => (HeapType.Default, ResourceFlags.AllowUnorderedAccess, ResourceStates.Common),
BufferType.ReadBack => (HeapType.Readback, ResourceFlags.None, ResourceStates.CopyDestination),
BufferType.Transfer => (HeapType.Upload, ResourceFlags.None, ResourceStates.GenericRead),
_ => throw new ArgumentException($"Invalid buffer type {bufferType}", nameof(bufferType))
};
GraphicsDevice.AllocateShaderResourceViewDescriptorHandles(out D3D12CpuDescriptorHandle, out D3D12GpuDescriptorHandle);
// Create the native resource
ResourceDescription description = ResourceDescription.Buffer(sizeInBytes, flags);
Result result = GraphicsDevice.NativeDevice.CreateCommittedResource(new HeapProperties(heapType), HeapFlags.None, description, states, out ID3D12Resource? resource);
if (result.Failure)
{
throw new COMException("Failed to create the committed resource", result.Code);
switch (bufferType)
{
case BufferType.Constant: CreateConstantBufferView(); break;
case BufferType.ReadOnly: CreateShaderResourceView(); break;
case BufferType.ReadWrite: CreateUnorderedAccessView(); break;
}
}
NativeResource = resource!;
// Create the resource handles, if needed
(NativeCpuDescriptorHandle, NativeGpuDescriptorHandle) = bufferType switch
{
BufferType.Constant => CreateConstantBufferView(),
BufferType.ReadOnly => CreateShaderResourceView(),
BufferType.ReadWrite => CreateUnorderedAccessView(),
_ => default
};
}
/// <summary>
@@ -67,87 +83,74 @@ namespace ComputeSharp.Graphics.Buffers
/// </summary>
public int Size { get; }
/// <summary>
/// Gets the size in bytes of the current buffer
/// </summary>
protected int SizeInBytes { get; }
/// <summary>
/// Gets the size in bytes of each <typeparamref name="T"/> value contained in the buffer
/// </summary>
protected int ElementSizeInBytes { get; }
/// <summary>
/// Gets the size in bytes of the current buffer
/// </summary>
internal int PaddedElementSizeInBytes { get; }
/// <summary>
/// Gets whether or not there is some padding between elements in the current buffer
/// </summary>
internal bool IsPaddingPresent => PaddedElementSizeInBytes > ElementSizeInBytes;
/// <summary>
/// Gets the buffer type for the current <see cref="Buffer{T}"/> instance
/// Creates a committed resource for a given buffer type.
/// </summary>
internal BufferType BufferType { get; }
/// <summary>
/// Creates the descriptors for a constant buffer
/// </summary>
/// <returns>The CPU and GPU handles for a constant buffer</returns>
[Pure]
private (CpuDescriptorHandle, GpuDescriptorHandle) CreateConstantBufferView()
/// <param name="d3D12Device">The <see cref="ID3D12Device"/> instance in use.</param>
/// <param name="bufferType">The buffer type currently in use.</param>
/// <param name="sizeInBytes">The size in bytes of the current buffer.</param>
/// <returns>An <see cref="ID3D12Resource"/> reference for the current buffer.</returns>
private static ID3D12Resource* CreateCommittedResource(ID3D12Device* d3D12Device, BufferType bufferType, int sizeInBytes)
{
(CpuDescriptorHandle cpuHandle, GpuDescriptorHandle gpuHandle) = GraphicsDevice.ShaderResourceViewAllocator.Allocate();
int constantBufferSize = (SizeInBytes + 255) & ~255;
ConstantBufferViewDescription description = new ConstantBufferViewDescription
(D3D12_HEAP_TYPE d3D12HeapType,
D3D12_RESOURCE_FLAGS d3D12ResourceFlags,
D3D12_RESOURCE_STATES d3D12ResourceStates) = bufferType switch
{
BufferLocation = NativeResource!.GPUVirtualAddress,
SizeInBytes = constantBufferSize
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.Transfer => (D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_STATE_GENERIC_READ),
_ => throw null!
};
GraphicsDevice.NativeDevice.CreateConstantBufferView(description, cpuHandle);
return (cpuHandle, gpuHandle);
}
private (CpuDescriptorHandle, GpuDescriptorHandle) CreateShaderResourceView()
{
(CpuDescriptorHandle cpuHandle, GpuDescriptorHandle gpuHandle) = GraphicsDevice.ShaderResourceViewAllocator.Allocate();
ShaderResourceViewDescription description = new ShaderResourceViewDescription
{
Shader4ComponentMapping = 5768,
ViewDimension = ShaderResourceViewDimension.Buffer,
Buffer = { NumElements = Size, StructureByteStride = ElementSizeInBytes }
};
GraphicsDevice.NativeDevice.CreateShaderResourceView(NativeResource, description, cpuHandle);
return (cpuHandle, gpuHandle);
return d3D12Device->CreateCommittedResource(d3D12HeapType, (uint)sizeInBytes, d3D12ResourceFlags, d3D12ResourceStates);
}
/// <summary>
/// Creates the descriptors for a read write buffer
/// Creates a view for a constant buffer.
/// </summary>
/// <returns>The CPU and GPU handles for a read write buffer</returns>
[Pure]
private (CpuDescriptorHandle, GpuDescriptorHandle) CreateUnorderedAccessView()
private void CreateConstantBufferView()
{
(CpuDescriptorHandle cpuHandle, GpuDescriptorHandle gpuHandle) = GraphicsDevice.ShaderResourceViewAllocator.Allocate();
uint constantBufferSize = (uint)((SizeInBytes + 255) & ~255);
UnorderedAccessViewDescription description = new UnorderedAccessViewDescription
{
ViewDimension = UnorderedAccessViewDimension.Buffer,
Buffer = { NumElements = Size, StructureByteStride = ElementSizeInBytes }
};
D3D12_CONSTANT_BUFFER_VIEW_DESC d3D12ConstantBufferViewDescription;
d3D12ConstantBufferViewDescription.BufferLocation = D3D12Resource->GetGPUVirtualAddress();
d3D12ConstantBufferViewDescription.SizeInBytes = constantBufferSize;
GraphicsDevice.NativeDevice.CreateUnorderedAccessView(NativeResource, null, description, cpuHandle);
GraphicsDevice.D3D12Device->CreateConstantBufferView(&d3D12ConstantBufferViewDescription, D3D12CpuDescriptorHandle);
}
/// <summary>
/// Creates a view for a readonly buffer.
/// </summary>
private void CreateShaderResourceView()
{
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)Size;
d3D12ShaderResourceViewDescription.Buffer.StructureByteStride = (uint)ElementSizeInBytes;
return (cpuHandle, gpuHandle);
GraphicsDevice.D3D12Device->CreateShaderResourceView(D3D12Resource, &d3D12ShaderResourceViewDescription, D3D12CpuDescriptorHandle);
}
/// <summary>
/// Creates a view for a buffer than be both read and written to.
/// </summary>
private void CreateUnorderedAccessView()
{
D3D12_UNORDERED_ACCESS_VIEW_DESC d3D12UnorderedAccessViewDescription = default;
d3D12UnorderedAccessViewDescription.ViewDimension = D3D12_UAV_DIMENSION_BUFFER;
d3D12UnorderedAccessViewDescription.Buffer.NumElements = (uint)Size;
d3D12UnorderedAccessViewDescription.Buffer.StructureByteStride = (uint)ElementSizeInBytes;
GraphicsDevice.D3D12Device->CreateUnorderedAccessView(D3D12Resource, null, &d3D12UnorderedAccessViewDescription, D3D12CpuDescriptorHandle);
}
}
}
-111
ファイルの表示
@@ -1,111 +0,0 @@
using System;
using System.Diagnostics.Contracts;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using ComputeSharp.Exceptions;
using ComputeSharp.Graphics;
using ComputeSharp.Graphics.Buffers.Abstract;
using ComputeSharp.Graphics.Buffers.Enums;
using ComputeSharp.Graphics.Commands;
using ComputeSharp.Graphics.Helpers;
using static TerraFX.Interop.D3D12_COMMAND_LIST_TYPE;
namespace ComputeSharp
{
/// <summary>
/// A <see langword="class"/> representing a typed read write buffer stored on GPU memory
/// </summary>
/// <typeparam name="T">The type of items stored on the buffer</typeparam>
public sealed class ConstantBuffer2<T> : HlslBuffer2<T>
where T : unmanaged
{
/// <summary>
/// Creates a new <see cref="ConstantBuffer2{T}"/> instance with the specified parameters
/// </summary>
/// <param name="device">The <see cref="GraphicsDevice2"/> associated with the current instance</param>
/// <param name="size">The number of items to store in the current buffer</param>
internal ConstantBuffer2(GraphicsDevice2 device, int size)
: base(device, size, size * GetPaddedSize(), BufferType.Constant)
{
}
/// <summary>
/// Gets the right padded size for <typeparamref name="T"/> elements to store in the current instance
/// </summary>
[Pure]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static int GetPaddedSize()
{
int size = Unsafe.SizeOf<T>();
return (size + 15) & ~15;
}
/// <summary>
/// Gets a single <typeparamref name="T"/> value from the current constant buffer
/// </summary>
/// <param name="i">The index of the value to get</param>
/// <remarks>This API can only be used from a compute shader, and will always throw if used anywhere else</remarks>
public T this[int i] => throw new InvalidExecutionContextException($"{nameof(ConstantBuffer<T>)}<T>[int]");
/// <inheritdoc/>
public override unsafe void GetData(Span<T> span, int offset, int count)
{
using MappedResource resource = MapResource();
if (IsPaddingPresent)
{
ref T spanRef = ref MemoryMarshal.GetReference(span);
ref byte resourceRef = ref Unsafe.AsRef<byte>((void*)resource.Pointer);
// Move to the initial ref
resourceRef = ref Unsafe.Add(ref resourceRef, offset * GetPaddedSize());
for (var i = 0; i < count; i++)
{
ref byte targetRef = ref Unsafe.Add(ref resourceRef, i * GetPaddedSize());
Unsafe.Add(ref spanRef, i) = Unsafe.As<byte, T>(ref targetRef);
}
}
else MemoryHelper.Copy(resource.Pointer, offset, span, 0, count);
}
/// <inheritdoc/>
public override unsafe void SetData(ReadOnlySpan<T> span, int offset, int count)
{
using MappedResource resource = MapResource();
if (IsPaddingPresent)
{
ref T spanRef = ref MemoryMarshal.GetReference(span);
ref byte resourceRef = ref Unsafe.AsRef<byte>((void*)resource.Pointer);
// Move to the initial offset
resourceRef = ref Unsafe.Add(ref resourceRef, offset * GetPaddedSize());
for (var i = 0; i < count; i++)
{
ref byte targetRef = ref Unsafe.Add(ref resourceRef, i * GetPaddedSize());
Unsafe.As<byte, T>(ref targetRef) = Unsafe.Add(ref spanRef, i);
}
}
else MemoryHelper.Copy(span, resource.Pointer, offset, count);
}
/// <inheritdoc/>
public override unsafe void SetData(HlslBuffer2<T> buffer)
{
if (buffer is ConstantBuffer2<T>)
{
// Directly copy the input buffer, if possible
using CommandList2 copyCommandList = new CommandList2(GraphicsDevice, D3D12_COMMAND_LIST_TYPE_COPY);
copyCommandList.CopyBufferRegion(buffer.D3D12Resource, 0, D3D12Resource, 0, SizeInBytes);
copyCommandList.ExecuteAndWaitForCompletion();
}
else SetDataWithCpuBuffer(buffer);
}
}
}
+11 -7
ファイルの表示
@@ -6,9 +6,9 @@ using ComputeSharp.Exceptions;
using ComputeSharp.Graphics;
using ComputeSharp.Graphics.Buffers.Abstract;
using ComputeSharp.Graphics.Buffers.Enums;
using ComputeSharp.Graphics.Commands;
using ComputeSharp.Graphics.Helpers;
using Vortice.Direct3D12;
using CommandList = ComputeSharp.Graphics.Commands.CommandList;
using static TerraFX.Interop.D3D12_COMMAND_LIST_TYPE;
namespace ComputeSharp
{
@@ -16,14 +16,18 @@ namespace ComputeSharp
/// A <see langword="class"/> representing a typed read write buffer stored on GPU memory
/// </summary>
/// <typeparam name="T">The type of items stored on the buffer</typeparam>
public sealed class ConstantBuffer<T> : HlslBuffer<T> where T : unmanaged
public sealed class ConstantBuffer<T> : HlslBuffer<T>
where T : unmanaged
{
/// <summary>
/// Creates a new <see cref="ConstantBuffer{T}"/> instance with the specified parameters
/// </summary>
/// <param name="device">The <see cref="GraphicsDevice"/> associated with the current instance</param>
/// <param name="size">The number of items to store in the current buffer</param>
internal ConstantBuffer(GraphicsDevice device, int size) : base(device, size, size * GetPaddedSize(), BufferType.Constant) { }
internal ConstantBuffer(GraphicsDevice device, int size)
: base(device, size, size * GetPaddedSize(), BufferType.Constant)
{
}
/// <summary>
/// Gets the right padded size for <typeparamref name="T"/> elements to store in the current instance
@@ -91,14 +95,14 @@ namespace ComputeSharp
}
/// <inheritdoc/>
public override void SetData(HlslBuffer<T> buffer)
public override unsafe void SetData(HlslBuffer<T> buffer)
{
if (buffer is ConstantBuffer<T>)
{
// Directly copy the input buffer, if possible
using CommandList copyCommandList = new CommandList(GraphicsDevice, CommandListType.Copy);
using CommandList copyCommandList = new CommandList(GraphicsDevice, D3D12_COMMAND_LIST_TYPE_COPY);
copyCommandList.CopyBufferRegion(buffer, 0, this, 0, SizeInBytes);
copyCommandList.CopyBufferRegion(buffer.D3D12Resource, 0, D3D12Resource, 0, SizeInBytes);
copyCommandList.ExecuteAndWaitForCompletion();
}
else SetDataWithCpuBuffer(buffer);
+92 -75
ファイルの表示
@@ -7,177 +7,194 @@ using ComputeSharp.Graphics.Buffers.Abstract;
namespace ComputeSharp
{
/// <summary>
/// A <see langword="class"/> with extension methods for the <see cref="GraphicsDevice"/> type to allocate buffers
/// A <see langword="class"/> with extension methods for the <see cref="GraphicsDevice"/> type to allocate buffers.
/// </summary>
public static class BufferExtensions
{
/// <summary>
/// Allocates a new constant buffer with the specified parameters
/// Allocates a new constant buffer with the specified parameters.
/// </summary>
/// <typeparam name="T">The type of items to store in the buffer</typeparam>
/// <param name="device">The <see cref="GraphicsDevice"/> instance to use to allocate the buffer</param>
/// <param name="array">The input <typeparamref name="T"/> array with the data to copy on the allocated buffer</param>
/// <returns>A constant <see cref="ConstantBuffer{T}"/> instance with the contents of the input array</returns>
/// <typeparam name="T">The type of items to store in the buffer.</typeparam>
/// <param name="device">The <see cref="GraphicsDevice"/> instance to use to allocate the buffer.</param>
/// <param name="array">The input <typeparamref name="T"/> array with the data to copy on the allocated buffer.</param>
/// <returns>A constant <see cref="ConstantBuffer{T}"/> instance with the contents of the input array.</returns>
[Pure]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ConstantBuffer<T> AllocateConstantBuffer<T>(this GraphicsDevice device, T[] array) where T : unmanaged
public static ConstantBuffer<T> AllocateConstantBuffer<T>(this GraphicsDevice device, T[] array)
where T : unmanaged
{
return device.AllocateConstantBuffer(array.AsSpan());
}
/// <summary>
/// Allocates a new constant buffer with the specified parameters
/// Allocates a new constant buffer with the specified parameters.
/// </summary>
/// <typeparam name="T">The type of items to store in the buffer</typeparam>
/// <param name="device">The <see cref="GraphicsDevice"/> instance to use to allocate the buffer</param>
/// <param name="span">The input <see cref="Span{T}"/> with the data to copy on the allocated buffer</param>
/// <returns>A constant <see cref="ConstantBuffer{T}"/> instance with the contents of the input <see cref="Span{T}"/></returns>
/// <typeparam name="T">The type of items to store in the buffer.</typeparam>
/// <param name="device">The <see cref="GraphicsDevice"/> instance to use to allocate the buffer.</param>
/// <param name="span">The input <see cref="Span{T}"/> with the data to copy on the allocated buffer.</param>
/// <returns>A constant <see cref="ConstantBuffer{T}"/> instance with the contents of the input <see cref="Span{T}"/>.</returns>
[Pure]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ConstantBuffer<T> AllocateConstantBuffer<T>(this GraphicsDevice device, Span<T> span) where T : unmanaged
public static ConstantBuffer<T> AllocateConstantBuffer<T>(this GraphicsDevice device, Span<T> span)
where T : unmanaged
{
ConstantBuffer<T> buffer = new ConstantBuffer<T>(device, span.Length);
ConstantBuffer<T> buffer = new(device, span.Length);
buffer.SetData(span);
return buffer;
}
/// <summary>
/// Allocates a new constant buffer with the specified parameters
/// Allocates a new constant buffer with the specified parameters.
/// </summary>
/// <typeparam name="T">The type of items to store in the buffer</typeparam>
/// <param name="device">The <see cref="GraphicsDevice"/> instance to use to allocate the buffer</param>
/// <param name="buffer">The input <see cref="HlslBuffer{T}"/> with the data to copy on the allocated buffer</param>
/// <returns>A constant <see cref="ConstantBuffer{T}"/> instance with the contents of the input <see cref="HlslBuffer{T}"/></returns>
/// <typeparam name="T">The type of items to store in the buffer.</typeparam>
/// <param name="device">The <see cref="GraphicsDevice"/> instance to use to allocate the buffer.</param>
/// <param name="buffer">The input <see cref="HlslBuffer{T}"/> with the data to copy on the allocated buffer.</param>
/// <returns>A constant <see cref="ConstantBuffer{T}"/> instance with the contents of the input <see cref="HlslBuffer{T}"/>.</returns>
[Pure]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ConstantBuffer<T> AllocateConstantBuffer<T>(this GraphicsDevice device, HlslBuffer<T> buffer) where T : unmanaged
public static ConstantBuffer<T> AllocateConstantBuffer<T>(this GraphicsDevice device, HlslBuffer<T> buffer)
where T : unmanaged
{
ConstantBuffer<T> constantBuffer = new ConstantBuffer<T>(device, buffer.Size);
ConstantBuffer<T> constantBuffer = new(device, buffer.Size);
constantBuffer.SetData(buffer);
return constantBuffer;
}
/// <summary>
/// Allocates a new readonly buffer with the specified parameters
/// Allocates a new readonly buffer with the specified parameters.
/// </summary>
/// <typeparam name="T">The type of items to store in the buffer</typeparam>
/// <param name="device">The <see cref="GraphicsDevice"/> instance to use to allocate the buffer</param>
/// <param name="size">The size of the buffer to allocate</param>
/// <returns>A zeroed <see cref="ReadOnlyBuffer{T}"/> instance of size <paramref name="size"/></returns>
/// <typeparam name="T">The type of items to store in the buffer.</typeparam>
/// <param name="device">The <see cref="GraphicsDevice"/> instance to use to allocate the buffer.</param>
/// <param name="size">The size of the buffer to allocate.</param>
/// <returns>A zeroed <see cref="ReadOnlyBuffer{T}"/> instance of size <paramref name="size"/>.</returns>
[Pure]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ReadOnlyBuffer<T> AllocateReadOnlyBuffer<T>(this GraphicsDevice device, int size) where T : unmanaged
public static ReadOnlyBuffer<T> AllocateReadOnlyBuffer<T>(this GraphicsDevice device, int size)
where T : unmanaged
{
return new ReadOnlyBuffer<T>(device, size);
return new(device, size);
}
/// <summary>
/// Allocates a new readonly buffer with the specified parameters
/// Allocates a new readonly buffer with the specified parameters.
/// </summary>
/// <typeparam name="T">The type of items to store in the buffer</typeparam>
/// <param name="device">The <see cref="GraphicsDevice"/> instance to use to allocate the buffer</param>
/// <param name="array">The input <typeparamref name="T"/> array with the data to copy on the allocated buffer</param>
/// <returns>A read write <see cref="ReadOnlyBuffer{T}"/> instance with the contents of the input array</returns>
/// <typeparam name="T">The type of items to store in the buffer.</typeparam>
/// <param name="device">The <see cref="GraphicsDevice"/> instance to use to allocate the buffer.</param>
/// <param name="array">The input <typeparamref name="T"/> array with the data to copy on the allocated buffer.</param>
/// <returns>A read write <see cref="ReadOnlyBuffer{T}"/> instance with the contents of the input array.</returns>
[Pure]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ReadOnlyBuffer<T> AllocateReadOnlyBuffer<T>(this GraphicsDevice device, T[] array) where T : unmanaged
public static ReadOnlyBuffer<T> AllocateReadOnlyBuffer<T>(this GraphicsDevice device, T[] array)
where T : unmanaged
{
return device.AllocateReadOnlyBuffer(array.AsSpan());
}
/// <summary>
/// Allocates a new readonly buffer with the specified parameters
/// Allocates a new readonly buffer with the specified parameters.
/// </summary>
/// <typeparam name="T">The type of items to store in the buffer</typeparam>
/// <param name="device">The <see cref="GraphicsDevice"/> instance to use to allocate the buffer</param>
/// <param name="span">The input <see cref="Span{T}"/> with the data to copy on the allocated buffer</param>
/// <returns>A read write <see cref="ReadOnlyBuffer{T}"/> instance with the contents of the input <see cref="Span{T}"/></returns>
/// <typeparam name="T">The type of items to store in the buffer.</typeparam>
/// <param name="device">The <see cref="GraphicsDevice"/> instance to use to allocate the buffer.</param>
/// <param name="span">The input <see cref="Span{T}"/> with the data to copy on the allocated buffer.</param>
/// <returns>A read write <see cref="ReadOnlyBuffer{T}"/> instance with the contents of the input <see cref="Span{T}"/>.</returns>
[Pure]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ReadOnlyBuffer<T> AllocateReadOnlyBuffer<T>(this GraphicsDevice device, Span<T> span) where T : unmanaged
public static ReadOnlyBuffer<T> AllocateReadOnlyBuffer<T>(this GraphicsDevice device, Span<T> span)
where T : unmanaged
{
ReadOnlyBuffer<T> buffer = new ReadOnlyBuffer<T>(device, span.Length);
ReadOnlyBuffer<T> buffer = new(device, span.Length);
buffer.SetData(span);
return buffer;
}
/// <summary>
/// Allocates a new readonly buffer with the specified parameters
/// Allocates a new readonly buffer with the specified parameters.
/// </summary>
/// <typeparam name="T">The type of items to store in the buffer</typeparam>
/// <param name="device">The <see cref="GraphicsDevice"/> instance to use to allocate the buffer</param>
/// <param name="buffer">The input <see cref="HlslBuffer{T}"/> with the data to copy on the allocated buffer</param>
/// <returns>A read write <see cref="ReadOnlyBuffer{T}"/> instance with the contents of the input <see cref="HlslBuffer{T}"/></returns>
/// <typeparam name="T">The type of items to store in the buffer.</typeparam>
/// <param name="device">The <see cref="GraphicsDevice"/> instance to use to allocate the buffer.</param>
/// <param name="buffer">The input <see cref="HlslBuffer{T}"/> with the data to copy on the allocated buffer.</param>
/// <returns>A read write <see cref="ReadOnlyBuffer{T}"/> instance with the contents of the input <see cref="HlslBuffer{T}"/>.</returns>
[Pure]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ReadOnlyBuffer<T> AllocateReadOnlyBuffer<T>(this GraphicsDevice device, HlslBuffer<T> buffer) where T : unmanaged
public static ReadOnlyBuffer<T> AllocateReadOnlyBuffer<T>(this GraphicsDevice device, HlslBuffer<T> buffer)
where T : unmanaged
{
ReadOnlyBuffer<T> readWriteBuffer = new ReadOnlyBuffer<T>(device, buffer.Size);
ReadOnlyBuffer<T> readWriteBuffer = new(device, buffer.Size);
readWriteBuffer.SetData(buffer);
return readWriteBuffer;
}
/// <summary>
/// Allocates a new read write buffer with the specified parameters
/// Allocates a new read write buffer with the specified parameters.
/// </summary>
/// <typeparam name="T">The type of items to store in the buffer</typeparam>
/// <param name="device">The <see cref="GraphicsDevice"/> instance to use to allocate the buffer</param>
/// <param name="size">The size of the buffer to allocate</param>
/// <returns>A zeroed <see cref="ReadWriteBuffer{T}"/> instance of size <paramref name="size"/></returns>
/// <typeparam name="T">The type of items to store in the buffer.</typeparam>
/// <param name="device">The <see cref="GraphicsDevice"/> instance to use to allocate the buffer.</param>
/// <param name="size">The size of the buffer to allocate.</param>
/// <returns>A zeroed <see cref="ReadWriteBuffer{T}"/> instance of size <paramref name="size"/>.</returns>
[Pure]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ReadWriteBuffer<T> AllocateReadWriteBuffer<T>(this GraphicsDevice device, int size) where T : unmanaged
public static ReadWriteBuffer<T> AllocateReadWriteBuffer<T>(this GraphicsDevice device, int size)
where T : unmanaged
{
return new ReadWriteBuffer<T>(device, size);
return new(device, size);
}
/// <summary>
/// Allocates a new read write buffer with the specified parameters
/// Allocates a new read write buffer with the specified parameters.
/// </summary>
/// <typeparam name="T">The type of items to store in the buffer</typeparam>
/// <param name="device">The <see cref="GraphicsDevice"/> instance to use to allocate the buffer</param>
/// <param name="array">The input <typeparamref name="T"/> array with the data to copy on the allocated buffer</param>
/// <returns>A read write <see cref="ReadWriteBuffer{T}"/> instance with the contents of the input array</returns>
/// <typeparam name="T">The type of items to store in the buffer.</typeparam>
/// <param name="device">The <see cref="GraphicsDevice"/> instance to use to allocate the buffer.</param>
/// <param name="array">The input <typeparamref name="T"/> array with the data to copy on the allocated buffer.</param>
/// <returns>A read write <see cref="ReadWriteBuffer{T}"/> instance with the contents of the input array.</returns>
[Pure]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ReadWriteBuffer<T> AllocateReadWriteBuffer<T>(this GraphicsDevice device, T[] array) where T : unmanaged
public static ReadWriteBuffer<T> AllocateReadWriteBuffer<T>(this GraphicsDevice device, T[] array)
where T : unmanaged
{
return device.AllocateReadWriteBuffer(array.AsSpan());
}
/// <summary>
/// Allocates a new read write buffer with the specified parameters
/// Allocates a new read write buffer with the specified parameters.
/// </summary>
/// <typeparam name="T">The type of items to store in the buffer</typeparam>
/// <param name="device">The <see cref="GraphicsDevice"/> instance to use to allocate the buffer</param>
/// <param name="span">The input <see cref="Span{T}"/> with the data to copy on the allocated buffer</param>
/// <returns>A read write <see cref="ReadWriteBuffer{T}"/> instance with the contents of the input <see cref="Span{T}"/></returns>
/// <typeparam name="T">The type of items to store in the buffer.</typeparam>
/// <param name="device">The <see cref="GraphicsDevice"/> instance to use to allocate the buffer.</param>
/// <param name="span">The input <see cref="Span{T}"/> with the data to copy on the allocated buffer.</param>
/// <returns>A read write <see cref="ReadWriteBuffer{T}"/> instance with the contents of the input <see cref="Span{T}"/>.</returns>
[Pure]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ReadWriteBuffer<T> AllocateReadWriteBuffer<T>(this GraphicsDevice device, Span<T> span) where T : unmanaged
public static ReadWriteBuffer<T> AllocateReadWriteBuffer<T>(this GraphicsDevice device, Span<T> span)
where T : unmanaged
{
ReadWriteBuffer<T> buffer = new ReadWriteBuffer<T>(device, span.Length);
ReadWriteBuffer<T> buffer = new(device, span.Length);
buffer.SetData(span);
return buffer;
}
/// <summary>
/// Allocates a new read write buffer with the specified parameters
/// Allocates a new read write buffer with the specified parameters.
/// </summary>
/// <typeparam name="T">The type of items to store in the buffer</typeparam>
/// <param name="device">The <see cref="GraphicsDevice"/> instance to use to allocate the buffer</param>
/// <param name="buffer">The input <see cref="HlslBuffer{T}"/> with the data to copy on the allocated buffer</param>
/// <returns>A read write <see cref="ReadWriteBuffer{T}"/> instance with the contents of the input <see cref="HlslBuffer{T}"/></returns>
/// <typeparam name="T">The type of items to store in the buffer.</typeparam>
/// <param name="device">The <see cref="GraphicsDevice"/> instance to use to allocate the buffer.</param>
/// <param name="buffer">The input <see cref="HlslBuffer{T}"/> with the data to copy on the allocated buffer.</param>
/// <returns>A read write <see cref="ReadWriteBuffer{T}"/> instance with the contents of the input <see cref="HlslBuffer{T}"/>.</returns>
[Pure]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ReadWriteBuffer<T> AllocateReadWriteBuffer<T>(this GraphicsDevice device, HlslBuffer<T> buffer) where T : unmanaged
public static ReadWriteBuffer<T> AllocateReadWriteBuffer<T>(this GraphicsDevice device, HlslBuffer<T> buffer)
where T : unmanaged
{
ReadWriteBuffer<T> readWriteBuffer = new ReadWriteBuffer<T>(device, buffer.Size);
ReadWriteBuffer<T> readWriteBuffer = new (device, buffer.Size);
readWriteBuffer.SetData(buffer);
return readWriteBuffer;
-203
ファイルの表示
@@ -1,203 +0,0 @@
using System;
using System.Diagnostics.Contracts;
using System.Runtime.CompilerServices;
using ComputeSharp.Graphics;
using ComputeSharp.Graphics.Buffers.Abstract;
namespace ComputeSharp
{
/// <summary>
/// A <see langword="class"/> with extension methods for the <see cref="GraphicsDevice2"/> type to allocate buffers.
/// </summary>
public static class BufferExtensions2
{
/// <summary>
/// Allocates a new constant buffer with the specified parameters.
/// </summary>
/// <typeparam name="T">The type of items to store in the buffer.</typeparam>
/// <param name="device">The <see cref="GraphicsDevice2"/> instance to use to allocate the buffer.</param>
/// <param name="array">The input <typeparamref name="T"/> array with the data to copy on the allocated buffer.</param>
/// <returns>A constant <see cref="ConstantBuffer2{T}"/> instance with the contents of the input array.</returns>
[Pure]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ConstantBuffer2<T> AllocateConstantBuffer<T>(this GraphicsDevice2 device, T[] array)
where T : unmanaged
{
return device.AllocateConstantBuffer(array.AsSpan());
}
/// <summary>
/// Allocates a new constant buffer with the specified parameters.
/// </summary>
/// <typeparam name="T">The type of items to store in the buffer.</typeparam>
/// <param name="device">The <see cref="GraphicsDevice2"/> instance to use to allocate the buffer.</param>
/// <param name="span">The input <see cref="Span{T}"/> with the data to copy on the allocated buffer.</param>
/// <returns>A constant <see cref="ConstantBuffer2{T}"/> instance with the contents of the input <see cref="Span{T}"/>.</returns>
[Pure]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ConstantBuffer2<T> AllocateConstantBuffer<T>(this GraphicsDevice2 device, Span<T> span)
where T : unmanaged
{
ConstantBuffer2<T> buffer = new(device, span.Length);
buffer.SetData(span);
return buffer;
}
/// <summary>
/// Allocates a new constant buffer with the specified parameters.
/// </summary>
/// <typeparam name="T">The type of items to store in the buffer.</typeparam>
/// <param name="device">The <see cref="GraphicsDevice2"/> instance to use to allocate the buffer.</param>
/// <param name="buffer">The input <see cref="HlslBuffer2{T}"/> with the data to copy on the allocated buffer.</param>
/// <returns>A constant <see cref="ConstantBuffer2{T}"/> instance with the contents of the input <see cref="HlslBuffer2{T}"/>.</returns>
[Pure]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ConstantBuffer2<T> AllocateConstantBuffer<T>(this GraphicsDevice2 device, HlslBuffer2<T> buffer)
where T : unmanaged
{
ConstantBuffer2<T> constantBuffer = new(device, buffer.Size);
constantBuffer.SetData(buffer);
return constantBuffer;
}
/// <summary>
/// Allocates a new readonly buffer with the specified parameters.
/// </summary>
/// <typeparam name="T">The type of items to store in the buffer.</typeparam>
/// <param name="device">The <see cref="GraphicsDevice2"/> instance to use to allocate the buffer.</param>
/// <param name="size">The size of the buffer to allocate.</param>
/// <returns>A zeroed <see cref="ReadOnlyBuffer2{T}"/> instance of size <paramref name="size"/>.</returns>
[Pure]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ReadOnlyBuffer2<T> AllocateReadOnlyBuffer<T>(this GraphicsDevice2 device, int size)
where T : unmanaged
{
return new(device, size);
}
/// <summary>
/// Allocates a new readonly buffer with the specified parameters.
/// </summary>
/// <typeparam name="T">The type of items to store in the buffer.</typeparam>
/// <param name="device">The <see cref="GraphicsDevice2"/> instance to use to allocate the buffer.</param>
/// <param name="array">The input <typeparamref name="T"/> array with the data to copy on the allocated buffer.</param>
/// <returns>A read write <see cref="ReadOnlyBuffer2{T}"/> instance with the contents of the input array.</returns>
[Pure]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ReadOnlyBuffer2<T> AllocateReadOnlyBuffer<T>(this GraphicsDevice2 device, T[] array)
where T : unmanaged
{
return device.AllocateReadOnlyBuffer(array.AsSpan());
}
/// <summary>
/// Allocates a new readonly buffer with the specified parameters.
/// </summary>
/// <typeparam name="T">The type of items to store in the buffer.</typeparam>
/// <param name="device">The <see cref="GraphicsDevice2"/> instance to use to allocate the buffer.</param>
/// <param name="span">The input <see cref="Span{T}"/> with the data to copy on the allocated buffer.</param>
/// <returns>A read write <see cref="ReadOnlyBuffer2{T}"/> instance with the contents of the input <see cref="Span{T}"/>.</returns>
[Pure]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ReadOnlyBuffer2<T> AllocateReadOnlyBuffer<T>(this GraphicsDevice2 device, Span<T> span)
where T : unmanaged
{
ReadOnlyBuffer2<T> buffer = new(device, span.Length);
buffer.SetData(span);
return buffer;
}
/// <summary>
/// Allocates a new readonly buffer with the specified parameters.
/// </summary>
/// <typeparam name="T">The type of items to store in the buffer.</typeparam>
/// <param name="device">The <see cref="GraphicsDevice2"/> instance to use to allocate the buffer.</param>
/// <param name="buffer">The input <see cref="HlslBuffer2{T}"/> with the data to copy on the allocated buffer.</param>
/// <returns>A read write <see cref="ReadOnlyBuffer2{T}"/> instance with the contents of the input <see cref="HlslBuffer2{T}"/>.</returns>
[Pure]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ReadOnlyBuffer2<T> AllocateReadOnlyBuffer<T>(this GraphicsDevice2 device, HlslBuffer2<T> buffer)
where T : unmanaged
{
ReadOnlyBuffer2<T> readWriteBuffer = new(device, buffer.Size);
readWriteBuffer.SetData(buffer);
return readWriteBuffer;
}
/// <summary>
/// Allocates a new read write buffer with the specified parameters.
/// </summary>
/// <typeparam name="T">The type of items to store in the buffer.</typeparam>
/// <param name="device">The <see cref="GraphicsDevice2"/> instance to use to allocate the buffer.</param>
/// <param name="size">The size of the buffer to allocate.</param>
/// <returns>A zeroed <see cref="ReadWriteBuffer2{T}"/> instance of size <paramref name="size"/>.</returns>
[Pure]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ReadWriteBuffer2<T> AllocateReadWriteBuffer<T>(this GraphicsDevice2 device, int size)
where T : unmanaged
{
return new(device, size);
}
/// <summary>
/// Allocates a new read write buffer with the specified parameters.
/// </summary>
/// <typeparam name="T">The type of items to store in the buffer.</typeparam>
/// <param name="device">The <see cref="GraphicsDevice2"/> instance to use to allocate the buffer.</param>
/// <param name="array">The input <typeparamref name="T"/> array with the data to copy on the allocated buffer.</param>
/// <returns>A read write <see cref="ReadWriteBuffer2{T}"/> instance with the contents of the input array.</returns>
[Pure]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ReadWriteBuffer2<T> AllocateReadWriteBuffer<T>(this GraphicsDevice2 device, T[] array)
where T : unmanaged
{
return device.AllocateReadWriteBuffer(array.AsSpan());
}
/// <summary>
/// Allocates a new read write buffer with the specified parameters.
/// </summary>
/// <typeparam name="T">The type of items to store in the buffer.</typeparam>
/// <param name="device">The <see cref="GraphicsDevice2"/> instance to use to allocate the buffer.</param>
/// <param name="span">The input <see cref="Span{T}"/> with the data to copy on the allocated buffer.</param>
/// <returns>A read write <see cref="ReadWriteBuffer2{T}"/> instance with the contents of the input <see cref="Span{T}"/>.</returns>
[Pure]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ReadWriteBuffer2<T> AllocateReadWriteBuffer<T>(this GraphicsDevice2 device, Span<T> span)
where T : unmanaged
{
ReadWriteBuffer2<T> buffer = new(device, span.Length);
buffer.SetData(span);
return buffer;
}
/// <summary>
/// Allocates a new read write buffer with the specified parameters.
/// </summary>
/// <typeparam name="T">The type of items to store in the buffer.</typeparam>
/// <param name="device">The <see cref="GraphicsDevice2"/> instance to use to allocate the buffer.</param>
/// <param name="buffer">The input <see cref="HlslBuffer{T}"/> with the data to copy on the allocated buffer.</param>
/// <returns>A read write <see cref="ReadWriteBuffer2{T}"/> instance with the contents of the input <see cref="HlslBuffer2{T}"/>.</returns>
[Pure]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ReadWriteBuffer2<T> AllocateReadWriteBuffer<T>(this GraphicsDevice2 device, HlslBuffer2<T> buffer)
where T : unmanaged
{
ReadWriteBuffer2<T> readWriteBuffer = new (device, buffer.Size);
readWriteBuffer.SetData(buffer);
return readWriteBuffer;
}
}
}
-32
ファイルの表示
@@ -1,32 +0,0 @@
using ComputeSharp.Exceptions;
using ComputeSharp.Graphics;
using ComputeSharp.Graphics.Buffers.Abstract;
using ComputeSharp.Graphics.Buffers.Enums;
namespace ComputeSharp
{
/// <summary>
/// A <see langword="class"/> representing a typed readonly buffer stored on GPU memory
/// </summary>
/// <typeparam name="T">The type of items stored on the buffer</typeparam>
public sealed class ReadOnlyBuffer2<T> : HlslStructuredBuffer2<T>
where T : unmanaged
{
/// <summary>
/// Creates a new <see cref="ReadOnlyBuffer2{T}"/> instance with the specified parameters
/// </summary>
/// <param name="device">The <see cref="GraphicsDevice"/> associated with the current instance</param>
/// <param name="size">The number of items to store in the current buffer</param>
internal ReadOnlyBuffer2(GraphicsDevice2 device, int size)
: base(device, size, BufferType.ReadOnly)
{
}
/// <summary>
/// Gets a single <typeparamref name="T"/> value from the current read write buffer
/// </summary>
/// <param name="i">The index of the value to get</param>
/// <remarks>This API can only be used from a compute shader, and will always throw if used anywhere else</remarks>
public T this[int i] => throw new InvalidExecutionContextException($"{nameof(ReadOnlyBuffer<T>)}<T>[int]");
}
}
+6 -2
ファイルの表示
@@ -9,14 +9,18 @@ namespace ComputeSharp
/// A <see langword="class"/> representing a typed readonly buffer stored on GPU memory
/// </summary>
/// <typeparam name="T">The type of items stored on the buffer</typeparam>
public sealed class ReadOnlyBuffer<T> : HlslStructuredBuffer<T> where T : unmanaged
public sealed class ReadOnlyBuffer<T> : HlslStructuredBuffer<T>
where T : unmanaged
{
/// <summary>
/// Creates a new <see cref="ReadOnlyBuffer{T}"/> instance with the specified parameters
/// </summary>
/// <param name="device">The <see cref="GraphicsDevice"/> associated with the current instance</param>
/// <param name="size">The number of items to store in the current buffer</param>
internal ReadOnlyBuffer(GraphicsDevice device, int size) : base(device, size, BufferType.ReadOnly) { }
internal ReadOnlyBuffer(GraphicsDevice device, int size)
: base(device, size, BufferType.ReadOnly)
{
}
/// <summary>
/// Gets a single <typeparamref name="T"/> value from the current read write buffer
-32
ファイルの表示
@@ -1,32 +0,0 @@
using ComputeSharp.Exceptions;
using ComputeSharp.Graphics;
using ComputeSharp.Graphics.Buffers.Abstract;
using ComputeSharp.Graphics.Buffers.Enums;
namespace ComputeSharp
{
/// <summary>
/// A <see langword="class"/> representing a typed read write buffer stored on GPU memory
/// </summary>
/// <typeparam name="T">The type of items stored on the buffer</typeparam>
public sealed class ReadWriteBuffer2<T> : HlslStructuredBuffer2<T>
where T : unmanaged
{
/// <summary>
/// Creates a new <see cref="ReadWriteBuffer2{T}"/> instance with the specified parameters
/// </summary>
/// <param name="device">The <see cref="GraphicsDevice2"/> associated with the current instance</param>
/// <param name="size">The number of items to store in the current buffer</param>
internal ReadWriteBuffer2(GraphicsDevice2 device, int size)
: base(device, size, BufferType.ReadWrite)
{
}
/// <summary>
/// Gets or sets a single <typeparamref name="T"/> value from the current read write buffer
/// </summary>
/// <param name="i">The index of the value to get or set</param>
/// <remarks>This API can only be used from a compute shader, and will always throw if used anywhere else</remarks>
public ref T this[int i] => throw new InvalidExecutionContextException($"{nameof(ReadWriteBuffer<T>)}<T>[int]");
}
}
+6 -2
ファイルの表示
@@ -9,14 +9,18 @@ namespace ComputeSharp
/// A <see langword="class"/> representing a typed read write buffer stored on GPU memory
/// </summary>
/// <typeparam name="T">The type of items stored on the buffer</typeparam>
public sealed class ReadWriteBuffer<T> : HlslStructuredBuffer<T> where T : unmanaged
public sealed class ReadWriteBuffer<T> : HlslStructuredBuffer<T>
where T : unmanaged
{
/// <summary>
/// Creates a new <see cref="ReadWriteBuffer{T}"/> instance with the specified parameters
/// </summary>
/// <param name="device">The <see cref="GraphicsDevice"/> associated with the current instance</param>
/// <param name="size">The number of items to store in the current buffer</param>
internal ReadWriteBuffer(GraphicsDevice device, int size) : base(device, size, BufferType.ReadWrite) { }
internal ReadWriteBuffer(GraphicsDevice device, int size)
: base(device, size, BufferType.ReadWrite)
{
}
/// <summary>
/// Gets or sets a single <typeparamref name="T"/> value from the current read write buffer
-35
ファイルの表示
@@ -1,35 +0,0 @@
using System;
using Vortice.Direct3D12;
namespace ComputeSharp.Graphics.Commands.Abstract
{
/// <summary>
/// A base <see langword="class"/> for an instance that deals with GPU commands in some way
/// </summary>
internal abstract class CommandController : IDisposable
{
/// <summary>
/// Creates a new <see cref="CommandAllocatorPool"/> instance with the specified parameters
/// </summary>
/// <param name="device">The input <see cref="Graphics.GraphicsDevice"/> to use to perform requested operations</param>
/// <param name="commandListType">The type of command list to use for the current instance</param>
protected CommandController(GraphicsDevice device, CommandListType commandListType)
{
GraphicsDevice = device;
CommandListType = commandListType;
}
/// <summary>
/// Gets the <see cref="Graphics.GraphicsDevice"/> object targeted by the current instance
/// </summary>
public GraphicsDevice GraphicsDevice { get; }
/// <summary>
/// Gets the command list type being used by the current instance
/// </summary>
public CommandListType CommandListType { get; }
/// <inheritdoc/>
public abstract void Dispose();
}
}
-92
ファイルの表示
@@ -1,92 +0,0 @@
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;
using ComputeSharp.Graphics.Commands.Abstract;
using SharpGen.Runtime;
using Vortice.Direct3D12;
namespace ComputeSharp.Graphics.Commands
{
/// <summary>
/// A <see langword="class"/> that acts as a pool to get new <see cref="ID3D12CommandAllocator"/> instances wheen needed
/// </summary>
internal sealed class CommandAllocatorPool : CommandController
{
/// <summary>
/// The queue of currently pooled <see cref="ID3D12CommandAllocator"/> instances
/// </summary>
private readonly Queue<(ID3D12CommandAllocator CommandAllocator, long FenceValue)> CommandAllocatorQueue = new Queue<(ID3D12CommandAllocator, long)>();
/// <inheritdoc/>
public CommandAllocatorPool(GraphicsDevice device, CommandListType commandListType) : base(device, commandListType) { }
/// <summary>
/// Adds a new <see cref="ID3D12CommandAllocator"/> item to the internal pool queue
/// </summary>
/// <param name="commandAllocator">The input <see cref="ID3D12CommandAllocator"/> to enqueue</param>
/// <param name="fenceValue">The fence value for the input <see cref="ID3D12CommandAllocator"/></param>
public void Enqueue(ID3D12CommandAllocator commandAllocator, long fenceValue)
{
lock (CommandAllocatorQueue)
{
CommandAllocatorQueue.Enqueue((commandAllocator, fenceValue));
}
}
/// <summary>
/// Gets a new or reused <see cref="ID3D12CommandAllocator"/> item to use to issue GPU commands
/// </summary>
[Pure]
public ID3D12CommandAllocator GetCommandAllocator()
{
lock (CommandAllocatorQueue)
{
// Reuse an existing command allocator, if one is present in the queue
if (CommandAllocatorQueue.Count > 0)
{
(ID3D12CommandAllocator commandAllocator, long fenceValue) = CommandAllocatorQueue.Peek();
long completedValue = CommandListType switch
{
CommandListType.Compute => GraphicsDevice.NativeComputeFence.CompletedValue,
CommandListType.Copy => GraphicsDevice.NativeCopyFence.CompletedValue,
_ => throw new NotSupportedException($"Unsupported command list type with value {CommandListType}")
};
if (fenceValue <= completedValue)
{
CommandAllocatorQueue.Dequeue();
commandAllocator.Reset();
return commandAllocator;
}
}
// Create a new command allocator
Result result = GraphicsDevice.NativeDevice.CreateCommandAllocator(CommandListType, out ID3D12CommandAllocator? nativeCommandAllocator);
if (result.Failure)
{
throw new COMException("Failed to create the command allocator", result.Code);
}
return nativeCommandAllocator!;
}
}
/// <inheritdoc/>
public override void Dispose()
{
lock (CommandAllocatorQueue)
{
foreach ((ID3D12CommandAllocator commandAllocator, long _) in CommandAllocatorQueue)
{
commandAllocator.Dispose();
}
CommandAllocatorQueue.Clear();
}
}
}
}
+95 -69
ファイルの表示
@@ -1,116 +1,142 @@
using System;
using System.Runtime.InteropServices;
using ComputeSharp.Exceptions;
using System.Diagnostics.Contracts;
using System.Runtime.CompilerServices;
using ComputeSharp.Graphics.Buffers.Abstract;
using ComputeSharp.Graphics.Commands.Abstract;
using SharpGen.Runtime;
using Vortice.Direct3D12;
using ComputeSharp.Graphics.Extensions;
using TerraFX.Interop;
using static TerraFX.Interop.D3D12_COMMAND_LIST_TYPE;
namespace ComputeSharp.Graphics.Commands
{
/// <summary>
/// A <see langword="class"/> that represents a list of commands to issue to a GPU
/// A command list to set and execute operaations on the GPU.
/// </summary>
internal sealed class CommandList : CommandController
internal unsafe ref struct CommandList
{
/// <inheritdoc/>
public CommandList(GraphicsDevice device, CommandListType commandListType) : base(device, commandListType)
/// <summary>
/// The <see cref="GraphicsDevice"/> instance associated with the current command list.
/// </summary>
private readonly GraphicsDevice device;
/// <summary>
/// The command list type being used by the current instance.
/// </summary>
private readonly D3D12_COMMAND_LIST_TYPE d3d12CommandListType;
/// <summary>
/// The <see cref="ID3D12CommandAllocator"/> object in use by the current instance.
/// </summary>
private ComPtr<ID3D12CommandAllocator> d3D12CommandAllocator;
/// <summary>
/// The <see cref="ID3D12GraphicsCommandList"/> object in use by the current instance.
/// </summary>
private ComPtr<ID3D12GraphicsCommandList> d3D12GraphicsCommandList;
/// <summary>
/// Creates a new <see cref="CommandList"/> instance with the specified parameters.
/// </summary>
/// <param name="device">The target <see cref="GraphicsDevice"/> instance to use.</param>
/// <param name="d3d12CommandListType">The type of command list to create.</param>
public CommandList(GraphicsDevice device, D3D12_COMMAND_LIST_TYPE d3d12CommandListType)
{
CommandAllocator = CommandListType switch
{
CommandListType.Compute => GraphicsDevice.ComputeAllocatorPool.GetCommandAllocator(),
CommandListType.Copy => GraphicsDevice.CopyAllocatorPool.GetCommandAllocator(),
_ => throw new NotSupportedException($"Unsupported command list type with value {CommandListType}")
};
Result result = GraphicsDevice.NativeDevice.CreateCommandList(0, commandListType, CommandAllocator, null, out ID3D12GraphicsCommandList? nativeCommandList);
if (result.Failure)
{
throw new COMException("Failed to create the commands list", result.Code);
}
NativeCommandList = nativeCommandList!;
this.device = device;
this.d3d12CommandListType = d3d12CommandListType;
this.d3D12CommandAllocator = device.GetCommandAllocator(d3d12CommandListType);
this.d3D12GraphicsCommandList = device.D3D12Device->CreateCommandList(d3d12CommandListType, this.d3D12CommandAllocator);
// Set the heap descriptor if the command list is not for copy operations
if (CommandListType != CommandListType.Copy)
if (d3d12CommandListType is not D3D12_COMMAND_LIST_TYPE_COPY)
{
NativeCommandList.SetDescriptorHeaps(1, new[] { GraphicsDevice.ShaderResourceViewAllocator.DescriptorHeap });
device.SetDescriptorHeapForCommandList(this.d3D12GraphicsCommandList);
}
}
/// <summary>
/// Gets the command list type being used by the current instance.
/// </summary>
public readonly D3D12_COMMAND_LIST_TYPE D3d12CommandListType => this.d3d12CommandListType;
/// <summary>
/// Gets the <see cref="ID3D12CommandAllocator"/> object in use by the current instance
/// Detaches the <see cref="ID3D12CommandAllocator"/> object in use by the current instance.
/// </summary>
public ID3D12CommandAllocator CommandAllocator { get; }
/// <summary>
/// Gets the <see cref="ID3D12GraphicsCommandList"/> object in use by the current instance
/// </summary>
public ID3D12GraphicsCommandList NativeCommandList { get; }
/// <summary>
/// Copies a memory region from one resource to another
/// </summary>
/// <param name="source">The source <see cref="GraphicsResource"/> to read from</param>
/// <param name="sourceOffset">The starting offset to read the source resource from</param>
/// <param name="destination">The destination <see cref="GraphicsResource"/> to write to</param>
/// <param name="destinationOffset">The starting offset to write the destination resource from</param>
/// <param name="numBytes">The total number of bytes to copy from one resource to another</param>
public void CopyBufferRegion(GraphicsResource source, long sourceOffset, GraphicsResource destination, long destinationOffset, long numBytes)
/// <returns>The <see cref="ID3D12CommandAllocator"/> object in use, with ownership.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ComPtr<ID3D12CommandAllocator> DetachD3D12CommandAllocator()
{
NativeCommandList.CopyBufferRegion(destination.NativeResource, destinationOffset, source.NativeResource, sourceOffset, numBytes);
return this.d3D12CommandAllocator.Move();
}
/// <summary>
/// Binds an input <see cref="GraphicsResource"/> object to a specified root parameter
/// Gets a pointer to the <see cref="ID3D12CommandList"/> object in use by the current instance.
/// </summary>
/// <param name="rootParameterIndex">The root parameter index to bind to the input resource</param>
/// <param name="resource">The input <see cref="GraphicsResource"/> instance to bind</param>
public void SetComputeRootDescriptorTable(int rootParameterIndex, GraphicsResource resource)
/// <returns>A double pointer to the current <see cref="ID3D12CommandList"/> object to execute.</returns>
[Pure]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly ID3D12CommandList** GetD3D12CommandListAddressOf()
{
if (resource.NativeGpuDescriptorHandle == null) throw new InvalidOperationException("Invalid graphics resource GPU descriptor");
if (resource.GraphicsDevice != GraphicsDevice) throw new GraphicsDeviceMismatchException(GraphicsDevice, resource);
NativeCommandList.SetComputeRootDescriptorTable(rootParameterIndex, resource.NativeGpuDescriptorHandle.Value);
return this.d3D12GraphicsCommandList.Upcast<ID3D12GraphicsCommandList, ID3D12CommandList>().GetAddressOf();
}
/// <summary>
/// Sets a given <see cref="PipelineState"/> object ready to be executed
/// Copies a memory region from one resource to another.
/// </summary>
/// <param name="pipelineState">The input <see cref="PipelineState"/> to setup</param>
public void SetPipelineState(PipelineState pipelineState)
/// <param name="d3D12ResourceSource">The source <see cref="ID3D12Resource"/> to read from.</param>
/// <param name="sourceOffset">The starting offset to read the source resource from.</param>
/// <param name="d3d12ResourceDestination">The destination <see cref="ID3D12Resource"/> to write to.</param>
/// <param name="destinationOffset">The starting offset to write the destination resource from.</param>
/// <param name="numBytes">The total number of bytes to copy from one resource to another.</param>
public readonly void CopyBufferRegion(ID3D12Resource* d3D12ResourceSource, int sourceOffset, ID3D12Resource* d3d12ResourceDestination, int destinationOffset, int numBytes)
{
NativeCommandList.SetComputeRootSignature(pipelineState.RootSignature);
NativeCommandList.SetPipelineState(pipelineState.NativePipelineState);
this.d3D12GraphicsCommandList.Get()->CopyBufferRegion(d3d12ResourceDestination, (uint)destinationOffset, d3D12ResourceSource, (uint)sourceOffset, (uint)numBytes);
}
/// <summary>
/// Dispatches the pending shader using the specified thread group values
/// Binds an input <see cref="GraphicsResource"/> object to a specified root parameter.
/// </summary>
/// <param name="threadGroupCountX">The number of thread groups to schedule for the X axis</param>
/// <param name="threadGroupCountY">The number of thread groups to schedule for the Y axis</param>
/// <param name="threadGroupCountZ">The number of thread groups to schedule for the Z axis</param>
public void Dispatch(int threadGroupCountX, int threadGroupCountY, int threadGroupCountZ)
/// <param name="rootParameterIndex">The root parameter index to bind to the input resource.</param>
/// <param name="resource">The input <see cref="GraphicsResource"/> instance to bind.</param>
public readonly void SetComputeRootDescriptorTable(int rootParameterIndex, D3D12_GPU_DESCRIPTOR_HANDLE d3D12GpuDescriptorHandle)
{
NativeCommandList.Dispatch(threadGroupCountX, threadGroupCountY, threadGroupCountZ);
this.d3D12GraphicsCommandList.Get()->SetComputeRootDescriptorTable((uint)rootParameterIndex, d3D12GpuDescriptorHandle);
}
/// <summary>
/// Executes the commands in the current commands list, and waits for completion
/// Sets a given <see cref="PipelineData"/> object ready to be executed.
/// </summary>
/// <param name="pipelineState">The input <see cref="PipelineData"/> to setup.</param>
public readonly void SetPipelineData(PipelineData pipelineData)
{
this.d3D12GraphicsCommandList.Get()->SetComputeRootSignature(pipelineData.D3D12RootSignature);
this.d3D12GraphicsCommandList.Get()->SetPipelineState(pipelineData.D3D12PipelineState);
}
/// <summary>
/// Dispatches the pending shader using the specified thread group values.
/// </summary>
/// <param name="threadGroupCountX">The number of thread groups to schedule for the X axis.</param>
/// <param name="threadGroupCountY">The number of thread groups to schedule for the Y axis.</param>
/// <param name="threadGroupCountZ">The number of thread groups to schedule for the Z axis.</param>
public readonly void Dispatch(int threadGroupCountX, int threadGroupCountY, int threadGroupCountZ)
{
this.d3D12GraphicsCommandList.Get()->Dispatch((uint)threadGroupCountX, (uint)threadGroupCountY, (uint)threadGroupCountZ);
}
/// <summary>
/// Executes the commands in the current commands list, and waits for completion.
/// </summary>
public void ExecuteAndWaitForCompletion()
{
NativeCommandList.Close();
this.d3D12GraphicsCommandList.Get()->Close();
GraphicsDevice.ExecuteCommandList(this);
this.device.ExecuteCommandList(ref this);
}
/// <inheritdoc/>
public override void Dispose()
/// <inheritdoc cref="IDisposable.Dispose"/>
public void Dispose()
{
NativeCommandList.Dispose();
this.d3D12CommandAllocator.Dispose();
this.d3D12GraphicsCommandList.Dispose();
}
}
}
-142
ファイルの表示
@@ -1,142 +0,0 @@
using System;
using System.Diagnostics.Contracts;
using System.Runtime.CompilerServices;
using ComputeSharp.Graphics.Buffers.Abstract;
using ComputeSharp.Graphics.Extensions;
using TerraFX.Interop;
using static TerraFX.Interop.D3D12_COMMAND_LIST_TYPE;
namespace ComputeSharp.Graphics.Commands
{
/// <summary>
/// A command list to set and execute operaations on the GPU.
/// </summary>
internal unsafe ref struct CommandList2
{
/// <summary>
/// The <see cref="GraphicsDevice2"/> instance associated with the current command list.
/// </summary>
private readonly GraphicsDevice2 device;
/// <summary>
/// The command list type being used by the current instance.
/// </summary>
private readonly D3D12_COMMAND_LIST_TYPE d3d12CommandListType;
/// <summary>
/// The <see cref="ID3D12CommandAllocator"/> object in use by the current instance.
/// </summary>
private ComPtr<ID3D12CommandAllocator> d3D12CommandAllocator;
/// <summary>
/// The <see cref="ID3D12GraphicsCommandList"/> object in use by the current instance.
/// </summary>
private ComPtr<ID3D12GraphicsCommandList> d3D12GraphicsCommandList;
/// <summary>
/// Creates a new <see cref="CommandList2"/> instance with the specified parameters.
/// </summary>
/// <param name="device">The target <see cref="GraphicsDevice2"/> instance to use.</param>
/// <param name="d3d12CommandListType">The type of command list to create.</param>
public CommandList2(GraphicsDevice2 device, D3D12_COMMAND_LIST_TYPE d3d12CommandListType)
{
this.device = device;
this.d3d12CommandListType = d3d12CommandListType;
this.d3D12CommandAllocator = device.GetCommandAllocator(d3d12CommandListType);
this.d3D12GraphicsCommandList = device.D3D12Device->CreateCommandList(d3d12CommandListType, this.d3D12CommandAllocator);
// Set the heap descriptor if the command list is not for copy operations
if (d3d12CommandListType is not D3D12_COMMAND_LIST_TYPE_COPY)
{
device.SetDescriptorHeapForCommandList(this.d3D12GraphicsCommandList);
}
}
/// <summary>
/// Gets the command list type being used by the current instance.
/// </summary>
public readonly D3D12_COMMAND_LIST_TYPE D3d12CommandListType => this.d3d12CommandListType;
/// <summary>
/// Detaches the <see cref="ID3D12CommandAllocator"/> object in use by the current instance.
/// </summary>
/// <returns>The <see cref="ID3D12CommandAllocator"/> object in use, with ownership.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ComPtr<ID3D12CommandAllocator> DetachD3D12CommandAllocator()
{
return this.d3D12CommandAllocator.Move();
}
/// <summary>
/// Gets a pointer to the <see cref="ID3D12CommandList"/> object in use by the current instance.
/// </summary>
/// <returns>A double pointer to the current <see cref="ID3D12CommandList"/> object to execute.</returns>
[Pure]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly ID3D12CommandList** GetD3D12CommandListAddressOf()
{
return this.d3D12GraphicsCommandList.Upcast<ID3D12GraphicsCommandList, ID3D12CommandList>().GetAddressOf();
}
/// <summary>
/// Copies a memory region from one resource to another.
/// </summary>
/// <param name="d3D12ResourceSource">The source <see cref="ID3D12Resource"/> to read from.</param>
/// <param name="sourceOffset">The starting offset to read the source resource from.</param>
/// <param name="d3d12ResourceDestination">The destination <see cref="ID3D12Resource"/> to write to.</param>
/// <param name="destinationOffset">The starting offset to write the destination resource from.</param>
/// <param name="numBytes">The total number of bytes to copy from one resource to another.</param>
public readonly void CopyBufferRegion(ID3D12Resource* d3D12ResourceSource, int sourceOffset, ID3D12Resource* d3d12ResourceDestination, int destinationOffset, int numBytes)
{
this.d3D12GraphicsCommandList.Get()->CopyBufferRegion(d3d12ResourceDestination, (uint)destinationOffset, d3D12ResourceSource, (uint)sourceOffset, (uint)numBytes);
}
/// <summary>
/// Binds an input <see cref="GraphicsResource"/> object to a specified root parameter.
/// </summary>
/// <param name="rootParameterIndex">The root parameter index to bind to the input resource.</param>
/// <param name="resource">The input <see cref="GraphicsResource"/> instance to bind.</param>
public readonly void SetComputeRootDescriptorTable(int rootParameterIndex, D3D12_GPU_DESCRIPTOR_HANDLE d3D12GpuDescriptorHandle)
{
this.d3D12GraphicsCommandList.Get()->SetComputeRootDescriptorTable((uint)rootParameterIndex, d3D12GpuDescriptorHandle);
}
/// <summary>
/// Sets a given <see cref="PipelineData"/> object ready to be executed.
/// </summary>
/// <param name="pipelineState">The input <see cref="PipelineData"/> to setup.</param>
public readonly void SetPipelineData(PipelineData pipelineData)
{
this.d3D12GraphicsCommandList.Get()->SetComputeRootSignature(pipelineData.D3D12RootSignature);
this.d3D12GraphicsCommandList.Get()->SetPipelineState(pipelineData.D3D12PipelineState);
}
/// <summary>
/// Dispatches the pending shader using the specified thread group values.
/// </summary>
/// <param name="threadGroupCountX">The number of thread groups to schedule for the X axis.</param>
/// <param name="threadGroupCountY">The number of thread groups to schedule for the Y axis.</param>
/// <param name="threadGroupCountZ">The number of thread groups to schedule for the Z axis.</param>
public readonly void Dispatch(int threadGroupCountX, int threadGroupCountY, int threadGroupCountZ)
{
this.d3D12GraphicsCommandList.Get()->Dispatch((uint)threadGroupCountX, (uint)threadGroupCountY, (uint)threadGroupCountZ);
}
/// <summary>
/// Executes the commands in the current commands list, and waits for completion.
/// </summary>
public void ExecuteAndWaitForCompletion()
{
this.d3D12GraphicsCommandList.Get()->Close();
this.device.ExecuteCommandList(ref this);
}
/// <inheritdoc cref="IDisposable.Dispose"/>
public void Dispose()
{
this.d3D12CommandAllocator.Dispose();
this.d3D12GraphicsCommandList.Dispose();
}
}
}
-29
ファイルの表示
@@ -1,29 +0,0 @@
using Vortice.Direct3D12;
namespace ComputeSharp.Graphics.Commands
{
/// <summary>
/// A <see langword="class"/> representing a custom pipeline state for a compute operation
/// </summary>
internal sealed class PipelineState : ComputePipelineStateDescription
{
/// <summary>
/// Creates a new <see cref="PipelineState"/> instance with the specified parameters
/// </summary>
/// <param name="device">The <see cref="GraphicsDevice"/> to use</param>
/// <param name="rootSignature">The <see cref="ID3D12RootSignature"/> value for the current shader</param>
/// <param name="computeShader">The bytecode for the compute shader to run</param>
public PipelineState(GraphicsDevice device, ID3D12RootSignature rootSignature, ShaderBytecode computeShader)
{
RootSignature = rootSignature;
ComputeShader = computeShader;
NativePipelineState = device.NativeDevice.CreateComputePipelineState<ID3D12PipelineState>(this);
}
/// <summary>
/// Gets the <see cref="ID3D12PipelineState"/> instance for the current <see cref="PipelineState"/> object
/// </summary>
public ID3D12PipelineState NativePipelineState { get; }
}
}
-4
ファイルの表示
@@ -6,10 +6,6 @@
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Vortice.Direct3D12" Version="1.8.6" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\ComputeSharp.Core\ComputeSharp.Core.csproj" />
</ItemGroup>
+52 -49
ファイルの表示
@@ -1,97 +1,100 @@
using System;
using Vortice.Direct3D12;
using ComputeSharp.Graphics.Extensions;
using System;
using TerraFX.Interop;
using static TerraFX.Interop.D3D12_DESCRIPTOR_HEAP_TYPE;
namespace ComputeSharp.Graphics
{
/// <summary>
/// A <see langword="class"/> that provides logic to create resource descriptors for a <see cref="GraphicsDevice"/> instance
/// A type that provides logic to create resource descriptors for a <see cref="GraphicsDevice"/> instance.
/// </summary>
internal sealed class DescriptorAllocator : IDisposable
internal unsafe struct DescriptorAllocator : IDisposable
{
/// <summary>
/// The default number of available descriptors per heap
/// The default number of available descriptors per heap.
/// </summary>
private const int DescriptorsPerHeap = 4096;
private const uint DescriptorsPerHeap = 4096;
/// <summary>
/// The dummy object used to handle concurrent allocation requests
/// The <see cref="ID3D12DescriptorHeap"/> in use for the current <see cref="DescriptorAllocator"/> instance.
/// </summary>
private readonly object Lock = new object();
private ComPtr<ID3D12DescriptorHeap> d3D12DescriptorHeap;
/// <summary>
/// The size of each new descriptor being allocated
/// The dummy object used to handle concurrent allocation requests.
/// </summary>
private readonly int DescriptorSize;
private readonly object allocationLock;
/// <summary>
/// The current <see cref="CpuDescriptorHandle"/> for the <see cref="DescriptorAllocator"/> instance in use
/// The size of each new descriptor being allocated.
/// </summary>
private CpuDescriptorHandle _CurrentCpuHandle;
private readonly uint descriptorSize;
/// <summary>
/// The current <see cref="GpuDescriptorHandle"/> for the <see cref="DescriptorAllocator"/> instance in use
/// The current <see cref="D3D12_CPU_DESCRIPTOR_HANDLE"/> for the <see cref="DescriptorAllocator"/> instance in use.
/// </summary>
private GpuDescriptorHandle _CurrentGpuHandle;
private D3D12_CPU_DESCRIPTOR_HANDLE d3d12CpuDescriptorHandle;
/// <summary>
/// The number of remaining handles to allocate on the current heap
/// The current <see cref="D3D12_GPU_DESCRIPTOR_HANDLE"/> for the <see cref="DescriptorAllocator"/> instance in use.
/// </summary>
private int _RemainingHandles;
private D3D12_GPU_DESCRIPTOR_HANDLE d3d12GpuDescriptorHandle;
/// <summary>
/// Creates a new <see cref="DescriptorAllocator"/> instance with the specified parameters
/// The number of remaining handles to allocate on the current heap.
/// </summary>
private uint remainingHandles;
/// <summary>
/// Creates a new <see cref="DescriptorAllocator"/> instance with the specified parameters.
/// </summary>
/// <param name="device">The <see cref="ID3D12Device"/> instance to use</param>
public DescriptorAllocator(ID3D12Device device)
public DescriptorAllocator(ID3D12Device* device)
{
DescriptorSize = device.GetDescriptorHandleIncrementSize(DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView);
DescriptorHeapDescription descriptorHeapDescription = new DescriptorHeapDescription
{
DescriptorCount = DescriptorsPerHeap,
Flags = DescriptorHeapFlags.ShaderVisible,
Type = DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView
};
DescriptorHeap = device.CreateDescriptorHeap(descriptorHeapDescription);
_RemainingHandles = DescriptorsPerHeap;
_CurrentCpuHandle = DescriptorHeap.GetCPUDescriptorHandleForHeapStart();
_CurrentGpuHandle = DescriptorHeap.GetGPUDescriptorHandleForHeapStart();
this.d3D12DescriptorHeap = device->CreateDescriptorHeap(DescriptorsPerHeap);
this.allocationLock = new object();
this.descriptorSize = device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV);
this.d3d12CpuDescriptorHandle = this.d3D12DescriptorHeap.Get()->GetCPUDescriptorHandleForHeapStart();
this.d3d12GpuDescriptorHandle = this.d3D12DescriptorHeap.Get()->GetGPUDescriptorHandleForHeapStart();
this.remainingHandles = this.d3D12DescriptorHeap.Get()->GetDesc().NumDescriptors;
}
/// <summary>
/// Gets the <see cref="ID3D12DescriptorHeap"/> object in use for the current <see cref="DescriptorAllocator"/> instance
/// Gets the <see cref="ID3D12DescriptorHeap"/> in use for the current <see cref="DescriptorAllocator"/> instance.
/// </summary>
public ID3D12DescriptorHeap DescriptorHeap { get; }
public ID3D12DescriptorHeap* D3D12DescriptorHeap => this.d3D12DescriptorHeap;
/// <summary>
/// Allocates a new CPU and GPU handle pair to use in a memory buffer
/// </summary>
/// <returns>A pair of <see cref="CpuDescriptorHandle"/> and <see cref="GpuDescriptorHandle"/> to use</returns>
public (CpuDescriptorHandle, GpuDescriptorHandle) Allocate()
/// <param name="d3d12CpuDescriptorHandle">The resulting <see cref="D3D12_CPU_DESCRIPTOR_HANDLE"/> value.</param>
/// <param name="d3d12CpuDescriptorHandle">The resulting <see cref="D3D12_GPU_DESCRIPTOR_HANDLE"/> value.</param>
public void Allocate(
out D3D12_CPU_DESCRIPTOR_HANDLE d3d12CpuDescriptorHandle,
out D3D12_GPU_DESCRIPTOR_HANDLE d3d12GpuDescriptorHandle)
{
lock (Lock)
lock (this.allocationLock)
{
if (_RemainingHandles == 0)
if (this.remainingHandles == 0)
{
_RemainingHandles = DescriptorHeap.Description.DescriptorCount;
_CurrentCpuHandle = DescriptorHeap.GetCPUDescriptorHandleForHeapStart();
_CurrentGpuHandle = DescriptorHeap.GetGPUDescriptorHandleForHeapStart();
this.d3d12CpuDescriptorHandle = this.d3D12DescriptorHeap.Get()->GetCPUDescriptorHandleForHeapStart();
this.d3d12GpuDescriptorHandle = this.d3D12DescriptorHeap.Get()->GetGPUDescriptorHandleForHeapStart();
this.remainingHandles = this.d3D12DescriptorHeap.Get()->GetDesc().NumDescriptors;
}
CpuDescriptorHandle cpuDescriptorHandle = _CurrentCpuHandle;
GpuDescriptorHandle gpuDescriptorHandle = _CurrentGpuHandle;
d3d12CpuDescriptorHandle = this.d3d12CpuDescriptorHandle;
d3d12GpuDescriptorHandle = this.d3d12GpuDescriptorHandle;
_CurrentCpuHandle += DescriptorSize;
_CurrentGpuHandle += DescriptorSize;
_RemainingHandles -= 1;
return (cpuDescriptorHandle, gpuDescriptorHandle);
this.d3d12CpuDescriptorHandle.ptr += this.descriptorSize;
this.d3d12GpuDescriptorHandle.ptr += this.descriptorSize;
this.remainingHandles--;
}
}
/// <inheritdoc/>
public void Dispose() => DescriptorHeap.Dispose();
public void Dispose()
{
this.d3D12DescriptorHeap.Dispose();
}
}
}
-100
ファイルの表示
@@ -1,100 +0,0 @@
using ComputeSharp.Graphics.Extensions;
using System;
using TerraFX.Interop;
using static TerraFX.Interop.D3D12_DESCRIPTOR_HEAP_TYPE;
namespace ComputeSharp.Graphics
{
/// <summary>
/// A type that provides logic to create resource descriptors for a <see cref="GraphicsDevice"/> instance.
/// </summary>
internal unsafe struct DescriptorAllocator2 : IDisposable
{
/// <summary>
/// The default number of available descriptors per heap.
/// </summary>
private const uint DescriptorsPerHeap = 4096;
/// <summary>
/// The <see cref="ID3D12DescriptorHeap"/> in use for the current <see cref="DescriptorAllocator2"/> instance.
/// </summary>
private ComPtr<ID3D12DescriptorHeap> d3D12DescriptorHeap;
/// <summary>
/// The dummy object used to handle concurrent allocation requests.
/// </summary>
private readonly object allocationLock;
/// <summary>
/// The size of each new descriptor being allocated.
/// </summary>
private readonly uint descriptorSize;
/// <summary>
/// The current <see cref="D3D12_CPU_DESCRIPTOR_HANDLE"/> for the <see cref="DescriptorAllocator2"/> instance in use.
/// </summary>
private D3D12_CPU_DESCRIPTOR_HANDLE d3d12CpuDescriptorHandle;
/// <summary>
/// The current <see cref="D3D12_GPU_DESCRIPTOR_HANDLE"/> for the <see cref="DescriptorAllocator2"/> instance in use.
/// </summary>
private D3D12_GPU_DESCRIPTOR_HANDLE d3d12GpuDescriptorHandle;
/// <summary>
/// The number of remaining handles to allocate on the current heap.
/// </summary>
private uint remainingHandles;
/// <summary>
/// Creates a new <see cref="DescriptorAllocator2"/> instance with the specified parameters.
/// </summary>
/// <param name="device">The <see cref="ID3D12Device"/> instance to use</param>
public DescriptorAllocator2(ID3D12Device* device)
{
this.d3D12DescriptorHeap = device->CreateDescriptorHeap(DescriptorsPerHeap);
this.allocationLock = new object();
this.descriptorSize = device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV);
this.d3d12CpuDescriptorHandle = this.d3D12DescriptorHeap.Get()->GetCPUDescriptorHandleForHeapStart();
this.d3d12GpuDescriptorHandle = this.d3D12DescriptorHeap.Get()->GetGPUDescriptorHandleForHeapStart();
this.remainingHandles = this.d3D12DescriptorHeap.Get()->GetDesc().NumDescriptors;
}
/// <summary>
/// Gets the <see cref="ID3D12DescriptorHeap"/> in use for the current <see cref="DescriptorAllocator2"/> instance.
/// </summary>
public ID3D12DescriptorHeap* D3D12DescriptorHeap => this.d3D12DescriptorHeap;
/// <summary>
/// Allocates a new CPU and GPU handle pair to use in a memory buffer
/// </summary>
/// <param name="d3d12CpuDescriptorHandle">The resulting <see cref="D3D12_CPU_DESCRIPTOR_HANDLE"/> value.</param>
/// <param name="d3d12CpuDescriptorHandle">The resulting <see cref="D3D12_GPU_DESCRIPTOR_HANDLE"/> value.</param>
public void Allocate(
out D3D12_CPU_DESCRIPTOR_HANDLE d3d12CpuDescriptorHandle,
out D3D12_GPU_DESCRIPTOR_HANDLE d3d12GpuDescriptorHandle)
{
lock (this.allocationLock)
{
if (this.remainingHandles == 0)
{
this.d3d12CpuDescriptorHandle = this.d3D12DescriptorHeap.Get()->GetCPUDescriptorHandleForHeapStart();
this.d3d12GpuDescriptorHandle = this.d3D12DescriptorHeap.Get()->GetGPUDescriptorHandleForHeapStart();
this.remainingHandles = this.d3D12DescriptorHeap.Get()->GetDesc().NumDescriptors;
}
d3d12CpuDescriptorHandle = this.d3d12CpuDescriptorHandle;
d3d12GpuDescriptorHandle = this.d3d12GpuDescriptorHandle;
this.d3d12CpuDescriptorHandle.ptr += this.descriptorSize;
this.d3d12GpuDescriptorHandle.ptr += this.descriptorSize;
this.remainingHandles--;
}
}
/// <inheritdoc/>
public void Dispose()
{
this.d3D12DescriptorHeap.Dispose();
}
}
}
+8 -5
ファイルの表示
@@ -15,17 +15,20 @@ namespace ComputeSharp.Exceptions
/// <summary>
/// Creates a new <see cref="GraphicsDeviceMismatchException"/> instance
/// </summary>
internal GraphicsDeviceMismatchException(GraphicsDevice device, GraphicsResource resource) : base(GetExceptionMessage(device, resource)) { }
internal GraphicsDeviceMismatchException(GraphicsDevice device, GraphicsResource resource)
: base(GetExceptionMessage(device, resource))
{
}
// Gets a proper exception message for a pair of device and resource
[Pure]
private static string GetExceptionMessage(GraphicsDevice device, GraphicsResource resource)
private static unsafe string GetExceptionMessage(GraphicsDevice device, GraphicsResource resource)
{
StringBuilder builder = new StringBuilder();
builder.AppendLine("Invalid pairing of graphics devices used to run a compute shader and allocate memory buffers.");
// Check if the device is effectively the same but with two instances pointing to the same adapter
if (device.NativeDevice.AdapterLuid == resource.GraphicsDevice.NativeDevice.AdapterLuid)
if (device.D3D12Device->GetAdapterLuid().Equals(resource.GraphicsDevice.D3D12Device->GetAdapterLuid()))
{
builder.AppendLine("The graphics devices used to allocate buffers and run the shader must be the same instance, not just be using the same physical device.");
builder.AppendLine("You can still run different shaders on different devices, but a shader run on one device must only use buffers allocated by the same device instance.");
@@ -33,8 +36,8 @@ namespace ComputeSharp.Exceptions
else
{
// Actually different devices
builder.AppendLine($"The target device to run the compute shader is \"{device.Name}\" (id: {device.NativeDevice.AdapterLuid}).");
builder.AppendLine($"The buffer of type {resource.GetType().ToFriendlyString()} was allocated on device \"{resource.GraphicsDevice.Name}\" (id: {resource.GraphicsDevice.NativeDevice.AdapterLuid}).");
builder.AppendLine($"The target device to run the compute shader is \"{device.Name}\" (id: {device.D3D12Device->GetAdapterLuid()}).");
builder.AppendLine($"The buffer of type {resource.GetType().ToFriendlyString()} was allocated on device \"{resource.GraphicsDevice.Name}\" (id: {resource.GraphicsDevice.D3D12Device->GetAdapterLuid()}).");
builder.AppendLine("Make sure to always allocate buffers on the same device used to actually run the code that accesses them.");
}
+140 -132
ファイルの表示
@@ -1,198 +1,206 @@
using System;
using ComputeSharp.Core.Interop;
using ComputeSharp.Graphics.Commands;
using Vortice.Direct3D12;
using Vortice.DXGI;
using CommandList = ComputeSharp.Graphics.Commands.CommandList;
using Direct3DFeatureLevel = Vortice.Direct3D.FeatureLevel;
using ComputeSharp.Graphics.Extensions;
using ComputeSharp.Graphics.Helpers;
using System.Runtime.CompilerServices;
using TerraFX.Interop;
using static TerraFX.Interop.D3D12_COMMAND_LIST_TYPE;
using static TerraFX.Interop.D3D12_FEATURE;
namespace ComputeSharp.Graphics
{
/// <summary>
/// A <see langword="class"/> that represents a DX12.1-compatible GPU device that can be used to run compute shaders
/// A <see langword="class"/> that represents a DX12.1-compatible GPU device that can be used to run compute shaders.
/// </summary>
public sealed class GraphicsDevice : IDisposable
public sealed unsafe class GraphicsDevice : NativeObject
{
/// <summary>
/// Gets the <see cref="FeatureLevel"/> value that needs to be supported by GPUs mapped to a <see cref="GraphicsDevice"/> instance
/// The underlying <see cref="ID3D12Device"/> wrapped by the current instance.
/// </summary>
public const Direct3DFeatureLevel FeatureLevel = Direct3DFeatureLevel.Level_12_1;
private ComPtr<ID3D12Device> d3D12Device;
/// <summary>
/// The <see cref="ID3D12CommandQueue"/> instance to use for compute operations
/// The <see cref="ID3D12CommandQueue"/> instance to use for compute operations.
/// </summary>
private readonly ID3D12CommandQueue NativeComputeCommandQueue;
private ComPtr<ID3D12CommandQueue> d3D12ComputeCommandQueue;
/// <summary>
/// The <see cref="ID3D12CommandQueue"/> instance to use for copy operations
/// The <see cref="ID3D12CommandQueue"/> instance to use for copy operations.
/// </summary>
private readonly ID3D12CommandQueue NativeCopyCommandQueue;
private ComPtr<ID3D12CommandQueue> d3D12CopyCommandQueue;
/// <summary>
/// Creates a new <see cref="GraphicsDevice"/> instance for the input <see cref="ID3D12Device"/>
/// The <see cref="ID3D12Fence"/> instance used for compute operations.
/// </summary>
/// <param name="device">The <see cref="ID3D12Device"/> to use for the new <see cref="GraphicsDevice"/> instance</param>
/// <param name="description">The available info for the new <see cref="GraphicsDevice"/> instance</param>
public GraphicsDevice(ID3D12Device device, AdapterDescription description)
private ComPtr<ID3D12Fence> d3D12ComputeFence;
/// <summary>
/// The <see cref="ID3D12Fence"/> instance used for copy operations.
/// </summary>
private ComPtr<ID3D12Fence> d3D12CopyFence;
/// <summary>
/// The <see cref="ID3D12CommandAllocatorPool"/> instance for compute operations.
/// </summary>
private readonly ID3D12CommandAllocatorPool computeCommandAllocatorPool;
/// <summary>
/// Gets the <see cref="ID3D12CommandAllocatorPool"/> instance for copy operations.
/// </summary>
private readonly ID3D12CommandAllocatorPool copyCommandAllocatorPool;
/// <summary>
/// The <see cref="DescriptorAllocator"/> instance to use when allocating new buffers.
/// </summary>
private DescriptorAllocator shaderResourceViewDescriptorAllocator;
/// <summary>
/// The next fence value for compute operations using <see cref="d3D12ComputeCommandQueue"/>.
/// </summary>
private ulong nextD3D12ComputeFenceValue = 1;
/// <summary>
/// The next fence value for copy operations using <see cref="d3D12CopyCommandQueue"/>.
/// </summary>
private ulong nextD3D12CopyFenceValue = 1;
/// <summary>
/// Creates a new <see cref="GraphicsDevice"/> instance for the input <see cref="ID3D12Device"/>.
/// </summary>
/// <param name="device">The <see cref="ID3D12Device"/> to use for the new <see cref="GraphicsDevice"/> instance.</param>
/// <param name="description">The available info for the new <see cref="GraphicsDevice"/> instance.</param>
internal GraphicsDevice(ComPtr<ID3D12Device> d3d12device, DXGI_ADAPTER_DESC1* dxgiDescription1)
{
NativeDevice = device;
Name = description.Description;
MemorySize = description.DedicatedVideoMemory;
ComputeUnits = device.Options1.TotalLaneCount;
WavefrontSize = device.Options1.WaveLaneCountMin;
this.d3D12Device = d3d12device;
this.d3D12ComputeCommandQueue = d3d12device.Get()->CreateCommandQueue(D3D12_COMMAND_LIST_TYPE_COMPUTE);
this.d3D12CopyCommandQueue = d3d12device.Get()->CreateCommandQueue(D3D12_COMMAND_LIST_TYPE_COPY);
this.d3D12ComputeFence = d3d12device.Get()->CreateFence();
this.d3D12CopyFence = d3d12device.Get()->CreateFence();
NativeComputeCommandQueue = NativeDevice.CreateCommandQueue(new CommandQueueDescription(CommandListType.Compute));
NativeCopyCommandQueue = NativeDevice.CreateCommandQueue(new CommandQueueDescription(CommandListType.Copy));
this.computeCommandAllocatorPool = new ID3D12CommandAllocatorPool(D3D12_COMMAND_LIST_TYPE_COMPUTE);
this.copyCommandAllocatorPool = new ID3D12CommandAllocatorPool(D3D12_COMMAND_LIST_TYPE_COPY);
this.shaderResourceViewDescriptorAllocator = new DescriptorAllocator(d3d12device);
ComputeAllocatorPool = new CommandAllocatorPool(this, CommandListType.Compute);
CopyAllocatorPool = new CommandAllocatorPool(this, CommandListType.Copy);
Name = new string((char*)dxgiDescription1->Description);
MemorySize = dxgiDescription1->DedicatedVideoMemory;
NativeComputeFence = NativeDevice.CreateFence(0);
NativeCopyFence = NativeDevice.CreateFence(0);
var d3D12Options1Data = d3d12device.Get()->CheckFeatureSupport<D3D12_FEATURE_DATA_D3D12_OPTIONS1>(D3D12_FEATURE_D3D12_OPTIONS1);
ShaderResourceViewAllocator = new DescriptorAllocator(NativeDevice);
ComputeUnits = d3D12Options1Data.TotalLaneCount;
WavefrontSize = d3D12Options1Data.WaveLaneCountMin;
}
/// <summary>
/// Gets the name of the current <see cref="GraphicsDevice"/> instance
/// Gets the name of the current <see cref="GraphicsDevice"/> instance.
/// </summary>
public string Name { get; }
/// <summary>
/// Gets the size of the dedicated video memory for the current <see cref="GraphicsDevice"/> instance
/// Gets the size of the dedicated video memory for the current <see cref="GraphicsDevice"/> instance.
/// </summary>
public long MemorySize { get; }
public nuint MemorySize { get; }
/// <summary>
/// Gets the number of total lanes on the current device (eg. CUDA cores on an nVidia GPU)
/// Gets the number of total lanes on the current device (eg. CUDA cores on an nVidia GPU).
/// </summary>
public int ComputeUnits { get; }
public uint ComputeUnits { get; }
/// <summary>
/// Gets the number of lanes in a SIMD wave on the current device (also known as "wavefront size" or "warp width")
/// Gets the number of lanes in a SIMD wave on the current device (also known as "wavefront size" or "warp width").
/// </summary>
public int WavefrontSize { get; }
public uint WavefrontSize { get; }
/// <summary>
/// Gets the <see cref="ID3D12Device"/> object wrapped by the current instance
/// Gets the underlying <see cref="ID3D12Device"/> wrapped by the current instance.
/// </summary>
internal ID3D12Device NativeDevice { get; }
internal ID3D12Device* D3D12Device => this.d3D12Device;
/// <summary>
/// Gets the <see cref="DescriptorAllocator"/> object for the current instance, used when allocating new buffers
/// </summary>
internal DescriptorAllocator ShaderResourceViewAllocator { get; set; }
/// <summary>
/// Gets the <see cref="CommandAllocatorPool"/> instance for compute operations
/// </summary>
internal CommandAllocatorPool ComputeAllocatorPool { get; }
/// <summary>
/// Gets the <see cref="CommandAllocatorPool"/> instance for copy operations
/// </summary>
internal CommandAllocatorPool CopyAllocatorPool { get; }
/// <summary>
/// Gets the <see cref="ID3D12Fence"/> instance used for compute operations
/// </summary>
internal ID3D12Fence NativeComputeFence { get; }
/// <summary>
/// Gets the <see cref="ID3D12Fence"/> instance used for copy operations
/// </summary>
internal ID3D12Fence NativeCopyFence { get; }
/// <summary>
/// Gets the next fence value for compute operations
/// </summary>
internal long NextComputeFenceValue { get; private set; } = 1;
/// <summary>
/// Gets the next fence value for copy operations
/// </summary>
internal long NextCopyFenceValue { get; private set; } = 1;
/// <summary>
/// Creates a <see cref="ID3D12RootSignature"/> instance from a description
/// </summary>
/// <param name="rootSignatureDescription">A <see cref="VersionedRootSignatureDescription"/> instance with the info for the new <see cref="ID3D12RootSignature"/> object to create</param>
/// <returns>A new <see cref="ID3D12RootSignature"/> instance to use in a compute shader</returns>
internal ID3D12RootSignature CreateRootSignature(VersionedRootSignatureDescription rootSignatureDescription)
/// <inheritdoc cref="DescriptorAllocator.Allocate"/>
internal void AllocateShaderResourceViewDescriptorHandles(
out D3D12_CPU_DESCRIPTOR_HANDLE d3d12CpuDescriptorHandle,
out D3D12_GPU_DESCRIPTOR_HANDLE d3d12GpuDescriptorHandle)
{
return NativeDevice.CreateRootSignature(0, rootSignatureDescription);
this.shaderResourceViewDescriptorAllocator.Allocate(out d3d12CpuDescriptorHandle, out d3d12GpuDescriptorHandle);
}
/// <summary>
/// Executes a <see cref="CommandList"/> and waits for the GPU to finish processing it
/// </summary>
/// <param name="commandList">The input <see cref="CommandList"/> to execute</param>
internal void ExecuteCommandList(CommandList commandList)
/// <inheritdoc cref="ID3D12CommandAllocatorPool.GetCommandAllocator"/>
/// <param name="d3d12CommandListType">The type of command allocator to rent.</param>
internal ComPtr<ID3D12CommandAllocator> GetCommandAllocator(D3D12_COMMAND_LIST_TYPE d3d12CommandListType)
{
ID3D12Fence fence = commandList.CommandListType switch
return d3d12CommandListType switch
{
CommandListType.Compute => NativeComputeFence,
CommandListType.Copy => NativeCopyFence,
_ => throw new NotSupportedException("This command list type is not supported.")
D3D12_COMMAND_LIST_TYPE_COMPUTE => this.computeCommandAllocatorPool.GetCommandAllocator(this.d3D12Device, this.d3D12ComputeFence),
D3D12_COMMAND_LIST_TYPE_COPY => this.computeCommandAllocatorPool.GetCommandAllocator(this.d3D12Device, this.d3D12CopyFence),
_ => throw null!
};
long fenceValue = GetFenceValueForCommandList(commandList);
if (fenceValue <= fence.CompletedValue) return;
fence.SetEventOnCompletion(fenceValue, default(IntPtr));
}
/// <summary>
/// Executes a <see cref="CommandList"/> and, signals and retrieves the following fence value
/// Sets the descriptor heap for a given <see cref="ID3D12GraphicsCommandList"/> instance.
/// </summary>
/// <param name="commandList">The input <see cref="CommandList"/> to execute</param>
/// <returns>The value of the new fence to wait for</returns>
private long GetFenceValueForCommandList(CommandList commandList)
/// <param name="d3D12GraphicsCommandList">The input <see cref="ID3D12GraphicsCommandList"/> instance to use.</param>
internal void SetDescriptorHeapForCommandList(ID3D12GraphicsCommandList* d3D12GraphicsCommandList)
{
CommandAllocatorPool commandAllocatorPool;
ID3D12CommandQueue commandQueue;
ID3D12Fence fence;
long fenceValue;
ID3D12DescriptorHeap* d3D12DescriptorHeap = this.shaderResourceViewDescriptorAllocator.D3D12DescriptorHeap;
switch (commandList.CommandListType)
d3D12GraphicsCommandList->SetDescriptorHeaps(1, &d3D12DescriptorHeap);
}
/// <summary>
/// Executes a given command list and waits for the operation to be completed.
/// </summary>
/// <param name="commandList">The input <see cref="CommandList"/> to execute.</param>
internal void ExecuteCommandList(ref CommandList commandList)
{
ref readonly ID3D12CommandAllocatorPool commandAllocatorPool = ref Unsafe.NullRef<ID3D12CommandAllocatorPool>();
ID3D12CommandQueue* d3D12CommandQueue;
ID3D12Fence* d3D12Fence;
ulong d3D12FenceValue;
// Get the target command queue, fence and pool for the list type
switch (commandList.D3d12CommandListType)
{
case CommandListType.Compute:
commandAllocatorPool = ComputeAllocatorPool;
commandQueue = NativeComputeCommandQueue;
fence = NativeComputeFence;
fenceValue = NextComputeFenceValue++;
case D3D12_COMMAND_LIST_TYPE_COMPUTE:
commandAllocatorPool = ref this.computeCommandAllocatorPool;
d3D12CommandQueue = this.d3D12ComputeCommandQueue;
d3D12Fence = this.d3D12ComputeFence;
d3D12FenceValue = this.nextD3D12ComputeFenceValue++;
break;
case CommandListType.Copy:
commandAllocatorPool = CopyAllocatorPool;
commandQueue = NativeCopyCommandQueue;
fence = NativeCopyFence;
fenceValue = NextCopyFenceValue++;
case D3D12_COMMAND_LIST_TYPE_COPY:
commandAllocatorPool = ref this.copyCommandAllocatorPool;
d3D12CommandQueue = this.d3D12CopyCommandQueue;
d3D12Fence = this.d3D12CopyFence;
d3D12FenceValue = this.nextD3D12CopyFenceValue++;
break;
default: throw new NotSupportedException($"Unsupported command list of type {commandList.CommandListType}");
default: throw null!;
}
commandAllocatorPool.Enqueue(commandList.CommandAllocator, fenceValue);
commandQueue.ExecuteCommandLists(commandList.NativeCommandList);
commandQueue.Signal(fence, fenceValue);
// Execute the command list and signal to the target fence
d3D12CommandQueue->ExecuteCommandLists(1, commandList.GetD3D12CommandListAddressOf());
return fenceValue;
d3D12CommandQueue->Signal(d3D12Fence, d3D12FenceValue).Assert();
// If the fence value hasn't been reached, wait until the operation completes
if (d3D12FenceValue > d3D12Fence->GetCompletedValue())
{
d3D12Fence->SetEventOnCompletion(d3D12FenceValue, default).Assert();
}
// Enqueue the command allocator pool so that it can be reused later
commandAllocatorPool.Enqueue(commandList.DetachD3D12CommandAllocator());
}
/// <inheritdoc/>
public void Dispose()
protected override void OnDispose()
{
ShaderResourceViewAllocator.Dispose();
ComputeAllocatorPool.Dispose();
CopyAllocatorPool.Dispose();
NativeComputeCommandQueue.Dispose();
NativeCopyCommandQueue.Dispose();
NativeComputeFence.Dispose();
NativeCopyFence.Dispose();
NativeDevice.Dispose();
this.d3D12Device.Dispose();
this.d3D12ComputeCommandQueue.Dispose();
this.d3D12CopyCommandQueue.Dispose();
this.d3D12ComputeFence.Dispose();
this.d3D12CopyFence.Dispose();
this.computeCommandAllocatorPool.Dispose();
this.copyCommandAllocatorPool.Dispose();
this.shaderResourceViewDescriptorAllocator.Dispose();
}
}
}
-206
ファイルの表示
@@ -1,206 +0,0 @@
using ComputeSharp.Core.Interop;
using ComputeSharp.Graphics.Commands;
using ComputeSharp.Graphics.Extensions;
using ComputeSharp.Graphics.Helpers;
using System.Runtime.CompilerServices;
using TerraFX.Interop;
using static TerraFX.Interop.D3D12_COMMAND_LIST_TYPE;
using static TerraFX.Interop.D3D12_FEATURE;
namespace ComputeSharp.Graphics
{
/// <summary>
/// A <see langword="class"/> that represents a DX12.1-compatible GPU device that can be used to run compute shaders.
/// </summary>
public sealed unsafe class GraphicsDevice2 : NativeObject
{
/// <summary>
/// The underlying <see cref="ID3D12Device"/> wrapped by the current instance.
/// </summary>
private ComPtr<ID3D12Device> d3D12Device;
/// <summary>
/// The <see cref="ID3D12CommandQueue"/> instance to use for compute operations.
/// </summary>
private ComPtr<ID3D12CommandQueue> d3D12ComputeCommandQueue;
/// <summary>
/// The <see cref="ID3D12CommandQueue"/> instance to use for copy operations.
/// </summary>
private ComPtr<ID3D12CommandQueue> d3D12CopyCommandQueue;
/// <summary>
/// The <see cref="ID3D12Fence"/> instance used for compute operations.
/// </summary>
private ComPtr<ID3D12Fence> d3D12ComputeFence;
/// <summary>
/// The <see cref="ID3D12Fence"/> instance used for copy operations.
/// </summary>
private ComPtr<ID3D12Fence> d3D12CopyFence;
/// <summary>
/// The <see cref="ID3D12CommandAllocatorPool"/> instance for compute operations.
/// </summary>
private readonly ID3D12CommandAllocatorPool computeCommandAllocatorPool;
/// <summary>
/// Gets the <see cref="ID3D12CommandAllocatorPool"/> instance for copy operations.
/// </summary>
private readonly ID3D12CommandAllocatorPool copyCommandAllocatorPool;
/// <summary>
/// The <see cref="DescriptorAllocator2"/> instance to use when allocating new buffers.
/// </summary>
private DescriptorAllocator2 shaderResourceViewDescriptorAllocator;
/// <summary>
/// The next fence value for compute operations using <see cref="d3D12ComputeCommandQueue"/>.
/// </summary>
private ulong nextD3D12ComputeFenceValue = 1;
/// <summary>
/// The next fence value for copy operations using <see cref="d3D12CopyCommandQueue"/>.
/// </summary>
private ulong nextD3D12CopyFenceValue = 1;
/// <summary>
/// Creates a new <see cref="GraphicsDevice2"/> instance for the input <see cref="ID3D12Device"/>.
/// </summary>
/// <param name="device">The <see cref="ID3D12Device"/> to use for the new <see cref="GraphicsDevice2"/> instance.</param>
/// <param name="description">The available info for the new <see cref="GraphicsDevice2"/> instance.</param>
internal GraphicsDevice2(ComPtr<ID3D12Device> d3d12device, DXGI_ADAPTER_DESC1* dxgiDescription1)
{
this.d3D12Device = d3d12device;
this.d3D12ComputeCommandQueue = d3d12device.Get()->CreateCommandQueue(D3D12_COMMAND_LIST_TYPE_COMPUTE);
this.d3D12CopyCommandQueue = d3d12device.Get()->CreateCommandQueue(D3D12_COMMAND_LIST_TYPE_COPY);
this.d3D12ComputeFence = d3d12device.Get()->CreateFence();
this.d3D12CopyFence = d3d12device.Get()->CreateFence();
this.computeCommandAllocatorPool = new ID3D12CommandAllocatorPool(D3D12_COMMAND_LIST_TYPE_COMPUTE);
this.copyCommandAllocatorPool = new ID3D12CommandAllocatorPool(D3D12_COMMAND_LIST_TYPE_COPY);
this.shaderResourceViewDescriptorAllocator = new DescriptorAllocator2(d3d12device);
Name = new string((char*)dxgiDescription1->Description);
MemorySize = dxgiDescription1->DedicatedVideoMemory;
var d3D12Options1Data = d3d12device.Get()->CheckFeatureSupport<D3D12_FEATURE_DATA_D3D12_OPTIONS1>(D3D12_FEATURE_D3D12_OPTIONS1);
ComputeUnits = d3D12Options1Data.TotalLaneCount;
WavefrontSize = d3D12Options1Data.WaveLaneCountMin;
}
/// <summary>
/// Gets the name of the current <see cref="GraphicsDevice"/> instance.
/// </summary>
public string Name { get; }
/// <summary>
/// Gets the size of the dedicated video memory for the current <see cref="GraphicsDevice"/> instance.
/// </summary>
public nuint MemorySize { get; }
/// <summary>
/// Gets the number of total lanes on the current device (eg. CUDA cores on an nVidia GPU).
/// </summary>
public uint ComputeUnits { get; }
/// <summary>
/// Gets the number of lanes in a SIMD wave on the current device (also known as "wavefront size" or "warp width").
/// </summary>
public uint WavefrontSize { get; }
/// <summary>
/// Gets the underlying <see cref="ID3D12Device"/> wrapped by the current instance.
/// </summary>
internal ID3D12Device* D3D12Device => this.d3D12Device;
/// <inheritdoc cref="DescriptorAllocator2.Allocate"/>
internal void AllocateShaderResourceViewDescriptorHandles(
out D3D12_CPU_DESCRIPTOR_HANDLE d3d12CpuDescriptorHandle,
out D3D12_GPU_DESCRIPTOR_HANDLE d3d12GpuDescriptorHandle)
{
this.shaderResourceViewDescriptorAllocator.Allocate(out d3d12CpuDescriptorHandle, out d3d12GpuDescriptorHandle);
}
/// <inheritdoc cref="ID3D12CommandAllocatorPool.GetCommandAllocator"/>
/// <param name="d3d12CommandListType">The type of command allocator to rent.</param>
internal ComPtr<ID3D12CommandAllocator> GetCommandAllocator(D3D12_COMMAND_LIST_TYPE d3d12CommandListType)
{
return d3d12CommandListType switch
{
D3D12_COMMAND_LIST_TYPE_COMPUTE => this.computeCommandAllocatorPool.GetCommandAllocator(this.d3D12Device, this.d3D12ComputeFence),
D3D12_COMMAND_LIST_TYPE_COPY => this.computeCommandAllocatorPool.GetCommandAllocator(this.d3D12Device, this.d3D12CopyFence),
_ => throw null!
};
}
/// <summary>
/// Sets the descriptor heap for a given <see cref="ID3D12GraphicsCommandList"/> instance.
/// </summary>
/// <param name="d3D12GraphicsCommandList">The input <see cref="ID3D12GraphicsCommandList"/> instance to use.</param>
internal void SetDescriptorHeapForCommandList(ID3D12GraphicsCommandList* d3D12GraphicsCommandList)
{
ID3D12DescriptorHeap* d3D12DescriptorHeap = this.shaderResourceViewDescriptorAllocator.D3D12DescriptorHeap;
d3D12GraphicsCommandList->SetDescriptorHeaps(1, &d3D12DescriptorHeap);
}
/// <summary>
/// Executes a given command list and waits for the operation to be completed.
/// </summary>
/// <param name="commandList">The input <see cref="CommandList2"/> to execute.</param>
internal void ExecuteCommandList(ref CommandList2 commandList)
{
ref readonly ID3D12CommandAllocatorPool commandAllocatorPool = ref Unsafe.NullRef<ID3D12CommandAllocatorPool>();
ID3D12CommandQueue* d3D12CommandQueue;
ID3D12Fence* d3D12Fence;
ulong d3D12FenceValue;
// Get the target command queue, fence and pool for the list type
switch (commandList.D3d12CommandListType)
{
case D3D12_COMMAND_LIST_TYPE_COMPUTE:
commandAllocatorPool = ref this.computeCommandAllocatorPool;
d3D12CommandQueue = this.d3D12ComputeCommandQueue;
d3D12Fence = this.d3D12ComputeFence;
d3D12FenceValue = this.nextD3D12ComputeFenceValue++;
break;
case D3D12_COMMAND_LIST_TYPE_COPY:
commandAllocatorPool = ref this.copyCommandAllocatorPool;
d3D12CommandQueue = this.d3D12CopyCommandQueue;
d3D12Fence = this.d3D12CopyFence;
d3D12FenceValue = this.nextD3D12CopyFenceValue++;
break;
default: throw null!;
}
// Execute the command list and signal to the target fence
d3D12CommandQueue->ExecuteCommandLists(1, commandList.GetD3D12CommandListAddressOf());
d3D12CommandQueue->Signal(d3D12Fence, d3D12FenceValue).Assert();
// If the fence value hasn't been reached, wait until the operation completes
if (d3D12FenceValue > d3D12Fence->GetCompletedValue())
{
d3D12Fence->SetEventOnCompletion(d3D12FenceValue, default).Assert();
}
// Enqueue the command allocator pool so that it can be reused later
commandAllocatorPool.Enqueue(commandList.DetachD3D12CommandAllocator());
}
/// <inheritdoc/>
protected override void OnDispose()
{
this.d3D12Device.Dispose();
this.d3D12ComputeCommandQueue.Dispose();
this.d3D12CopyCommandQueue.Dispose();
this.d3D12ComputeFence.Dispose();
this.d3D12CopyFence.Dispose();
this.computeCommandAllocatorPool.Dispose();
this.copyCommandAllocatorPool.Dispose();
this.shaderResourceViewDescriptorAllocator.Dispose();
}
}
}
+111 -23
ファイルの表示
@@ -1,46 +1,134 @@
using System.Collections.Generic;
using System;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using Vortice.Direct3D;
using Vortice.Direct3D12;
using Vortice.DXGI;
using TerraFX.Interop;
using FX = TerraFX.Interop.Windows;
using HRESULT = System.Int32;
namespace ComputeSharp.Graphics.Helpers
{
/// <summary>
/// A <see langword="class"/> with methods to inspect the available devices on the current machine
/// A <see langword="class"/> with methods to inspect the available devices on the current machine.
/// </summary>
internal static class DeviceHelper
{
/// <summary>
/// Gets a collection of all the supported devices on the current machine
/// Gets whether or not there is a default device available, without creating it.
/// </summary>
/// <returns>The collection of <see cref="ID3D12Device"/> objects with support for DX12.1</returns>
/// <returns>Whether or not there is a device supporting at least DX12.0.</returns>
[Pure]
public static IReadOnlyList<(ID3D12Device, AdapterDescription)> QueryAllSupportedDevices()
public static unsafe bool IsDefaultDeviceAvailable()
{
if (!DXGI.CreateDXGIFactory1(out IDXGIFactory1 factory).Success) return new (ID3D12Device, AdapterDescription)[0];
try
DXGI_ADAPTER_DESC1 dxgiDescription1;
return TryGetDefaultDevice(null, &dxgiDescription1);
}
/// <summary>
/// Gets the default <see cref="GraphicsDevice"/> instance.
/// </summary>
/// <returns>The default <see cref="GraphicsDevice"/> instance supporting at least DX12.0.</returns>
/// <exception cref="NotSupportedException">Thrown when a default device is not available.</exception>
public static unsafe GraphicsDevice GetDefaultDevice()
{
using ComPtr<ID3D12Device> d3d12device = default;
DXGI_ADAPTER_DESC1 dxgiDescription1;
if (TryGetDefaultDevice(d3d12device.GetAddressOf(), &dxgiDescription1))
{
List<(ID3D12Device, AdapterDescription)> devices = new List<(ID3D12Device, AdapterDescription)>();
return new GraphicsDevice(d3d12device.Move(), &dxgiDescription1);
}
int i = 0;
static GraphicsDevice Throw()
{
throw new NotSupportedException("There isn't a supported GPU device on the current machine");
}
while (factory.EnumAdapters1(i++, out IDXGIAdapter1? adapter).Success && !(adapter is null))
return Throw();
}
/// <summary>
/// Tries to check or create a default <see cref="ID3D12Device"/> object.
/// </summary>
/// <param name="d3d12device">A pointer to the <see cref="ID3D12Device"/> object to create, or <see langword="null"/>.</param>
/// <param name="dxgiDescription1">A pointer to the <see cref="DXGI_ADAPTER_DESC1"/> value for the device found.</param>
/// <returns>Whether a default device was found with the requested feature level.</returns>
public static unsafe bool TryGetDefaultDevice(ID3D12Device** d3d12device, DXGI_ADAPTER_DESC1* dxgiDescription1)
{
using ComPtr<IDXGIFactory4> dxgiFactory4 = default;
Guid dxgiFactory4Guid = FX.IID_IDXGIFactory4;
EnableDebugMode();
FX.CreateDXGIFactory2(IDXGIFactoryCreationFlags, &dxgiFactory4Guid, dxgiFactory4.GetVoidAddressOf()).Assert();
uint i = 0;
while (true)
{
using ComPtr<IDXGIAdapter1> dxgiAdapter1 = default;
HRESULT enumAdapters1Result = dxgiFactory4.Get()->EnumAdapters1(i++, dxgiAdapter1.GetAddressOf());
if (enumAdapters1Result == FX.DXGI_ERROR_NOT_FOUND)
{
if (adapter.Description.DedicatedVideoMemory == 0) continue;
if (D3D12.D3D12CreateDevice(adapter, FeatureLevel.Level_12_0, out ID3D12Device device).Success)
{
devices.Add((device, adapter.Description));
}
return false;
}
return devices;
enumAdapters1Result.Assert();
dxgiAdapter1.Get()->GetDesc1(dxgiDescription1).Assert();
if (dxgiDescription1->DedicatedVideoMemory == 0) continue;
Guid d3d12DeviceGuid = FX.IID_ID3D12Device;
HRESULT createDeviceResult = FX.D3D12CreateDevice(
dxgiAdapter1.Upcast<IDXGIAdapter1, IUnknown>().Get(),
D3D_FEATURE_LEVEL.D3D_FEATURE_LEVEL_12_0,
&d3d12DeviceGuid,
(void**)d3d12device);
if (FX.SUCCEEDED(createDeviceResult))
{
return true;
}
}
finally
}
/// <summary>
/// The creation flags for <see cref="IDXGIFactory"/> instances.
/// </summary>
private const uint IDXGIFactoryCreationFlags =
#if DEBUG
FX.DXGI_CREATE_FACTORY_DEBUG;
#else
0;
#endif
/// <summary>
/// Enables the debug layer for DirectX APIs.
/// </summary>
[Conditional("DEBUG")]
private static unsafe void EnableDebugMode()
{
using ComPtr<ID3D12Debug> d3D12Debug = default;
using ComPtr<ID3D12Debug1> d3D12Debug1 = default;
Guid d3D12DebugGuid = FX.IID_ID3D12Debug;
FX.D3D12GetDebugInterface(&d3D12DebugGuid, d3D12Debug.GetVoidAddressOf()).Assert();
d3D12Debug.Get()->EnableDebugLayer();
Guid d3D12Debug1Guid = FX.IID_ID3D12Debug1;
if (FX.SUCCEEDED(d3D12Debug.CopyTo(d3D12Debug1.GetAddressOf())))
{
// Explicit using statement
factory?.Dispose();
d3D12Debug1.Get()->SetEnableGPUBasedValidation(FX.TRUE);
d3D12Debug1.Get()->SetEnableSynchronizedCommandQueueValidation(FX.TRUE);
}
}
}
-135
ファイルの表示
@@ -1,135 +0,0 @@
using System;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using TerraFX.Interop;
using FX = TerraFX.Interop.Windows;
using HRESULT = System.Int32;
namespace ComputeSharp.Graphics.Helpers
{
/// <summary>
/// A <see langword="class"/> with methods to inspect the available devices on the current machine.
/// </summary>
internal static class DeviceHelper2
{
/// <summary>
/// Gets whether or not there is a default device available, without creating it.
/// </summary>
/// <returns>Whether or not there is a device supporting at least DX12.0.</returns>
[Pure]
public static unsafe bool IsDefaultDeviceAvailable()
{
DXGI_ADAPTER_DESC1 dxgiDescription1;
return TryGetDefaultDevice(null, &dxgiDescription1);
}
/// <summary>
/// Gets the default <see cref="GraphicsDevice2"/> instance.
/// </summary>
/// <returns>The default <see cref="GraphicsDevice2"/> instance supporting at least DX12.0.</returns>
/// <exception cref="NotSupportedException">Thrown when a default device is not available.</exception>
public static unsafe GraphicsDevice2 GetDefaultDevice()
{
using ComPtr<ID3D12Device> d3d12device = default;
DXGI_ADAPTER_DESC1 dxgiDescription1;
if (TryGetDefaultDevice(d3d12device.GetAddressOf(), &dxgiDescription1))
{
return new GraphicsDevice2(d3d12device.Move(), &dxgiDescription1);
}
static GraphicsDevice2 Throw()
{
throw new NotSupportedException("There isn't a supported GPU device on the current machine");
}
return Throw();
}
/// <summary>
/// Tries to check or create a default <see cref="ID3D12Device"/> object.
/// </summary>
/// <param name="d3d12device">A pointer to the <see cref="ID3D12Device"/> object to create, or <see langword="null"/>.</param>
/// <param name="dxgiDescription1">A pointer to the <see cref="DXGI_ADAPTER_DESC1"/> value for the device found.</param>
/// <returns>Whether a default device was found with the requested feature level.</returns>
public static unsafe bool TryGetDefaultDevice(ID3D12Device** d3d12device, DXGI_ADAPTER_DESC1* dxgiDescription1)
{
using ComPtr<IDXGIFactory4> dxgiFactory4 = default;
Guid dxgiFactory4Guid = FX.IID_IDXGIFactory4;
EnableDebugMode();
FX.CreateDXGIFactory2(IDXGIFactoryCreationFlags, &dxgiFactory4Guid, dxgiFactory4.GetVoidAddressOf()).Assert();
uint i = 0;
while (true)
{
using ComPtr<IDXGIAdapter1> dxgiAdapter1 = default;
HRESULT enumAdapters1Result = dxgiFactory4.Get()->EnumAdapters1(i++, dxgiAdapter1.GetAddressOf());
if (enumAdapters1Result == FX.DXGI_ERROR_NOT_FOUND)
{
return false;
}
enumAdapters1Result.Assert();
dxgiAdapter1.Get()->GetDesc1(dxgiDescription1).Assert();
if (dxgiDescription1->DedicatedVideoMemory == 0) continue;
Guid d3d12DeviceGuid = FX.IID_ID3D12Device;
HRESULT createDeviceResult = FX.D3D12CreateDevice(
dxgiAdapter1.Upcast<IDXGIAdapter1, IUnknown>().Get(),
D3D_FEATURE_LEVEL.D3D_FEATURE_LEVEL_12_0,
&d3d12DeviceGuid,
(void**)d3d12device);
if (FX.SUCCEEDED(createDeviceResult))
{
return true;
}
}
}
/// <summary>
/// The creation flags for <see cref="IDXGIFactory"/> instances.
/// </summary>
private const uint IDXGIFactoryCreationFlags =
#if DEBUG
FX.DXGI_CREATE_FACTORY_DEBUG;
#else
0;
#endif
/// <summary>
/// Enables the debug layer for DirectX APIs.
/// </summary>
[Conditional("DEBUG")]
private static unsafe void EnableDebugMode()
{
using ComPtr<ID3D12Debug> d3D12Debug = default;
using ComPtr<ID3D12Debug1> d3D12Debug1 = default;
Guid d3D12DebugGuid = FX.IID_ID3D12Debug;
FX.D3D12GetDebugInterface(&d3D12DebugGuid, d3D12Debug.GetVoidAddressOf()).Assert();
d3D12Debug.Get()->EnableDebugLayer();
Guid d3D12Debug1Guid = FX.IID_ID3D12Debug1;
if (FX.SUCCEEDED(d3D12Debug.CopyTo(d3D12Debug1.GetAddressOf())))
{
d3D12Debug1.Get()->SetEnableGPUBasedValidation(FX.TRUE);
d3D12Debug1.Get()->SetEnableSynchronizedCommandQueueValidation(FX.TRUE);
}
}
}
}
-1
ファイルの表示
@@ -10,7 +10,6 @@
<PackageReference Include="ICSharpCode.Decompiler" Version="5.0.2.5153" />
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="3.7.0" />
<PackageReference Include="Stubble.Core" Version="1.9.3" />
<PackageReference Include="Vortice.Dxc" Version="1.8.6" />
</ItemGroup>
<ItemGroup>
-204
ファイルの表示
@@ -1,204 +0,0 @@
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Runtime.CompilerServices;
using ComputeSharp.Graphics;
using ComputeSharp.Graphics.Commands;
using ComputeSharp.Shaders.Extensions;
using ComputeSharp.Shaders.Renderer;
using ComputeSharp.Shaders.Renderer.Models;
using ComputeSharp.Shaders.Translation;
using ComputeSharp.Shaders.Translation.Interop;
using ComputeSharp.Shaders.Translation.Models;
using TerraFX.Interop;
using static TerraFX.Interop.D3D12_COMMAND_LIST_TYPE;
namespace ComputeSharp.Shaders
{
/// <summary>
/// A <see langword="class"/> with helper methods to support <see cref="ShaderRunner2{T}"/>.
/// This type is primarily needed to avoid having fields being repeated per generic instantiation.
/// </summary>
internal static class ShaderRunner2
{
/// <summary>
/// A thread-safe map of reusable GPU buffers for captured locals.
/// </summary>
[ThreadStatic]
private static ConditionalWeakTable<GraphicsDevice2, ConstantBuffer2<Int4>>? variablesBuffers;
/// <summary>
/// Gets the reusable <see cref="ConstantBuffer2{T}"/> instance for a shader invocation.
/// </summary>
/// <param name="device">The <see cref="GraphicsDevice2"/> to use to run the shader.</param>
/// <returns>The reusable <see cref="ConstantBuffer2{T}"/> instance to populate.</returns>
[Pure]
public static ConstantBuffer2<Int4> GetVariablesBuffer(GraphicsDevice2 device)
{
ConditionalWeakTable<GraphicsDevice2, ConstantBuffer2<Int4>> map = variablesBuffers ??= new();
return map.GetValue(device, gpu => new ConstantBuffer2<Int4>(gpu, 4096));
}
}
/// <summary>
/// A <see langword="class"/> responsible for performing all the necessary operations to compile and run a compute shader.
/// </summary>
/// <typeparam name="T">The type of compute shader to run.</typeparam>
internal static class ShaderRunner2<T>
where T : struct, IComputeShader
{
/// <summary>
/// The mapping used to cache and reuse compiled shaders.
/// </summary>
private static readonly Dictionary<ShaderKey, CachedShader2<T>> ShadersCache = new();
/// <summary>
/// Compiles and runs the input shader on a target <see cref="GraphicsDevice2"/> instance, with the specified parameters.
/// </summary>
/// <param name="device">The <see cref="GraphicsDevice2"/> to use to run the shader.</param>
/// <param name="x">The number of iterations to run on the X axis.</param>
/// <param name="y">The number of iterations to run on the Y axis.</param>
/// <param name="z">The number of iterations to run on the Z axis.</param>
/// <param name="shader">The input <typeparamref name="T"/> instance representing the compute shader to run.</param>
public static void Run(GraphicsDevice2 device, int x, int y, int z, in T shader)
{
// Calculate the optimized thread num values
int threadsX, threadsY = 1, threadsZ = 1;
if (y == 1 && z == 1) threadsX = (int)device.WavefrontSize;
else if (z == 1) threadsX = threadsY = 8;
else threadsX = threadsY = threadsZ = 4;
Run(device, x, y, z, threadsX, threadsY, threadsZ, shader);
}
/// <summary>
/// Compiles and runs the input shader on a target <see cref="GraphicsDevice2"/> instance, with the specified parameters.
/// </summary>
/// <param name="device">The <see cref="GraphicsDevice2"/> to use to run the shader.</param>
/// <param name="x">The number of iterations to run on the X axis.</param>
/// <param name="y">The number of iterations to run on the Y axis.</param>
/// <param name="z">The number of iterations to run on the Z axis.</param>
/// <param name="threadsX">The number of threads in each thread group for the X axis.</param>
/// <param name="threadsY">The number of threads in each thread group for the Y axis.</param>
/// <param name="threadsZ">The number of threads in each thread group for the Z axis.</param>
/// <param name="shader">The input <typeparamref name="T"/> instance representing the compute shader to run.</param>
public static void Run(
GraphicsDevice2 device,
int x, int y, int z,
int threadsX, int threadsY, int threadsZ,
in T shader)
{
// Create the shader key
ShaderKey key = new(ShaderHashCodeProvider.GetHashCode(shader), threadsX, threadsY, threadsZ);
CachedShader2<T> shaderData;
PipelineData? pipelineData;
lock (ShadersCache)
{
// Get or preload the shader
if (!ShadersCache.TryGetValue(key, out shaderData))
{
LoadShader(threadsX, threadsY, threadsZ, shader, out shaderData);
// Cache for later use
ShadersCache.Add(key, shaderData);
}
// Create the reusable pipeline state
if (!shaderData.CachedPipelines.TryGetValue(device, out pipelineData))
{
CreatePipelineData(device, shaderData, out pipelineData);
}
}
// Create the commands list and set the pipeline state
using CommandList2 commandList = new(device, D3D12_COMMAND_LIST_TYPE_COMPUTE);
commandList.SetPipelineData(pipelineData);
// Extract the dispatch data for the shader invocation
using DispatchData2 dispatchData = shaderData.Loader.GetDispatchData(shader, x, y, z);
// Load the captured buffers
ReadOnlySpan<D3D12_GPU_DESCRIPTOR_HANDLE> resources = dispatchData.Resources;
for (int i = 0; i < resources.Length; i++)
{
commandList.SetComputeRootDescriptorTable(i + 1, resources[i]);
}
// Initialize the loop targets and the captured values
ConstantBuffer2<Int4> variablesBuffer = ShaderRunner2.GetVariablesBuffer(device);
variablesBuffer.SetData(dispatchData.Variables);
commandList.SetComputeRootDescriptorTable(0, variablesBuffer.D3D12GpuDescriptorHandle);
// Calculate the dispatch values
int
groupsX = Math.DivRem(x, threadsX, out int modX) + (modX == 0 ? 0 : 1),
groupsY = Math.DivRem(y, threadsY, out int modY) + (modY == 0 ? 0 : 1),
groupsZ = Math.DivRem(z, threadsZ, out int modZ) + (modZ == 0 ? 0 : 1);
// Dispatch and wait for completion
commandList.Dispatch(groupsX, groupsY, groupsZ);
commandList.ExecuteAndWaitForCompletion();
}
/// <summary>
/// Loads a shader with the specified parameters.
/// </summary>
/// <param name="threadsX">The number of threads in each thread group for the X axis.</param>
/// <param name="threadsY">The number of threads in each thread group for the Y axis.</param>
/// <param name="threadsZ">The number of threads in each thread group for the Z axis.</param>
/// <param name="shader">The input <typeparamref name="T"/> instance representing the compute shader to run.</param>
/// <param name="shaderData">The <see cref="CachedShader2{T}"/> instance to return with the cached shader data.</param>
[MethodImpl(MethodImplOptions.NoInlining)]
private static void LoadShader(int threadsX, int threadsY, int threadsZ, in T shader, out CachedShader2<T> shaderData)
{
// Load the input shader
ShaderLoader2<T> shaderLoader = ShaderLoader2<T>.Load(shader);
// Render the loaded shader
string shaderSource = ShaderRenderer.Instance.Render(new ShaderInfo
{
BuffersList = shaderLoader.HslsBuffersInfo,
FieldsList = shaderLoader.FieldsInfo,
NumThreadsX = threadsX,
NumThreadsY = threadsY,
NumThreadsZ = threadsZ,
ThreadsIdsVariableName = shaderLoader.ThreadsIdsVariableName,
ShaderBody = shaderLoader.MethodBody,
FunctionsList = shaderLoader.FunctionsInfo,
LocalFunctionsList = shaderLoader.LocalFunctionsInfo
});
// Compile the loaded shader to HLSL bytecode
IDxcBlobObject shaderBytecode = new(ShaderCompiler2.CompileShader(shaderSource));
// Get the cached shader data
shaderData = new CachedShader2<T>(shaderLoader, shaderBytecode);
}
/// <summary>
/// Creates and caches a <see cref="PipelineData"/> instance for a given shader.
/// </summary>
/// <param name="device">The <see cref="GraphicsDevice2"/> to use to run the shader.</param>
/// <param name="shaderData">The <see cref="CachedShader2{T}"/> instance with the data on the loaded shader.</param>
/// <param name="pipelineData">The resulting <see cref="PipelineData"/> instance to use to run the shader.</param>
[MethodImpl(MethodImplOptions.NoInlining)]
private static unsafe void CreatePipelineData(GraphicsDevice2 device, in CachedShader2<T> shaderData, out PipelineData pipelineData)
{
using ComPtr<ID3D12RootSignature> d3D12RootSignature = device.D3D12Device->CreateRootSignature(shaderData.Loader.D3D12DescriptorRanges1);
D3D12_SHADER_BYTECODE d3D12ShaderBytecode = new((ID3DBlob*)shaderData.Bytecode.DxcBlob);
using ComPtr<ID3D12PipelineState> d3D12PipelineState = device.D3D12Device->CreateComputePipelineState(d3D12RootSignature.Get(), d3D12ShaderBytecode);
pipelineData = new PipelineData(d3D12RootSignature.Move(), d3D12PipelineState.Move());
shaderData.CachedPipelines.Add(device, pipelineData);
}
}
}
+69 -63
ファイルの表示
@@ -3,14 +3,15 @@ using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Runtime.CompilerServices;
using ComputeSharp.Graphics;
using ComputeSharp.Graphics.Buffers.Abstract;
using ComputeSharp.Graphics.Commands;
using ComputeSharp.Shaders.Extensions;
using ComputeSharp.Shaders.Renderer;
using ComputeSharp.Shaders.Renderer.Models;
using ComputeSharp.Shaders.Translation;
using ComputeSharp.Shaders.Translation.Interop;
using ComputeSharp.Shaders.Translation.Models;
using Vortice.Direct3D12;
using CommandList = ComputeSharp.Graphics.Commands.CommandList;
using PipelineState = ComputeSharp.Graphics.Commands.PipelineState;
using TerraFX.Interop;
using static TerraFX.Interop.D3D12_COMMAND_LIST_TYPE;
namespace ComputeSharp.Shaders
{
@@ -21,45 +22,50 @@ namespace ComputeSharp.Shaders
internal static class ShaderRunner
{
/// <summary>
/// A thread-safe map of reusable GPU buffers for captured locals
/// A thread-safe map of reusable GPU buffers for captured locals.
/// </summary>
[ThreadStatic]
private static ConditionalWeakTable<GraphicsDevice, ConstantBuffer<Int4>>? variablesBuffers;
/// <summary>
/// Gets the reusable <see cref="ConstantBuffer{T}"/> instance for a shader invocation
/// Gets the reusable <see cref="ConstantBuffer{T}"/> instance for a shader invocation.
/// </summary>
/// <param name="device">The <see cref="GraphicsDevice"/> to use to run the shader</param>
/// <returns>The reusable <see cref="ConstantBuffer{T}"/> instance to populate</returns>
/// <param name="device">The <see cref="GraphicsDevice"/> to use to run the shader.</param>
/// <returns>The reusable <see cref="ConstantBuffer{T}"/> instance to populate.</returns>
[Pure]
public static ConstantBuffer<Int4> GetVariablesBuffer(GraphicsDevice device)
{
var map = variablesBuffers ??= new ConditionalWeakTable<GraphicsDevice, ConstantBuffer<Int4>>();
ConditionalWeakTable<GraphicsDevice, ConstantBuffer<Int4>> map = variablesBuffers ??= new();
return map.GetValue(device, gpu => new ConstantBuffer<Int4>(gpu, 4096));
}
}
/// <summary>
/// A <see langword="class"/> responsible for performing all the necessary operations to compile and run a compute shader
/// A <see langword="class"/> responsible for performing all the necessary operations to compile and run a compute shader.
/// </summary>
/// <typeparam name="T">The type of compute shader to run</typeparam>
/// <typeparam name="T">The type of compute shader to run.</typeparam>
internal static class ShaderRunner<T>
where T : struct, IComputeShader
{
/// <summary>
/// Compiles and runs the input shader on a target <see cref="GraphicsDevice"/> instance, with the specified parameters
/// The mapping used to cache and reuse compiled shaders.
/// </summary>
/// <param name="device">The <see cref="GraphicsDevice"/> to use to run the shader</param>
/// <param name="x">The number of iterations to run on the X axis</param>
/// <param name="y">The number of iterations to run on the Y axis</param>
/// <param name="z">The number of iterations to run on the Z axis</param>
/// <param name="shader">The input <typeparamref name="T"/> instance representing the compute shader to run</param>
private static readonly Dictionary<ShaderKey, CachedShader<T>> ShadersCache = new();
/// <summary>
/// Compiles and runs the input shader on a target <see cref="GraphicsDevice"/> instance, with the specified parameters.
/// </summary>
/// <param name="device">The <see cref="GraphicsDevice"/> to use to run the shader.</param>
/// <param name="x">The number of iterations to run on the X axis.</param>
/// <param name="y">The number of iterations to run on the Y axis.</param>
/// <param name="z">The number of iterations to run on the Z axis.</param>
/// <param name="shader">The input <typeparamref name="T"/> instance representing the compute shader to run.</param>
public static void Run(GraphicsDevice device, int x, int y, int z, in T shader)
{
// Calculate the optimized thread num values
int threadsX, threadsY = 1, threadsZ = 1;
if (y == 1 && z == 1) threadsX = device.WavefrontSize;
if (y == 1 && z == 1) threadsX = (int)device.WavefrontSize;
else if (z == 1) threadsX = threadsY = 8;
else threadsX = threadsY = threadsZ = 4;
@@ -67,21 +73,16 @@ namespace ComputeSharp.Shaders
}
/// <summary>
/// The mapping used to cache and reuse compiled shaders
/// Compiles and runs the input shader on a target <see cref="GraphicsDevice"/> instance, with the specified parameters.
/// </summary>
private static readonly Dictionary<ShaderKey, CachedShader<T>> ShadersCache = new Dictionary<ShaderKey, CachedShader<T>>();
/// <summary>
/// Compiles and runs the input shader on a target <see cref="GraphicsDevice"/> instance, with the specified parameters
/// </summary>
/// <param name="device">The <see cref="GraphicsDevice"/> to use to run the shader</param>
/// <param name="x">The number of iterations to run on the X axis</param>
/// <param name="y">The number of iterations to run on the Y axis</param>
/// <param name="z">The number of iterations to run on the Z axis</param>
/// <param name="threadsX">The number of threads in each thread group for the X axis</param>
/// <param name="threadsY">The number of threads in each thread group for the Y axis</param>
/// <param name="threadsZ">The number of threads in each thread group for the Z axis</param>
/// <param name="shader">The input <typeparamref name="T"/> instance representing the compute shader to run</param>
/// <param name="device">The <see cref="GraphicsDevice"/> to use to run the shader.</param>
/// <param name="x">The number of iterations to run on the X axis.</param>
/// <param name="y">The number of iterations to run on the Y axis.</param>
/// <param name="z">The number of iterations to run on the Z axis.</param>
/// <param name="threadsX">The number of threads in each thread group for the X axis.</param>
/// <param name="threadsY">The number of threads in each thread group for the Y axis.</param>
/// <param name="threadsZ">The number of threads in each thread group for the Z axis.</param>
/// <param name="shader">The input <typeparamref name="T"/> instance representing the compute shader to run.</param>
public static void Run(
GraphicsDevice device,
int x, int y, int z,
@@ -89,9 +90,9 @@ namespace ComputeSharp.Shaders
in T shader)
{
// Create the shader key
ShaderKey key = new ShaderKey(ShaderHashCodeProvider.GetHashCode(shader), threadsX, threadsY, threadsZ);
ShaderKey key = new(ShaderHashCodeProvider.GetHashCode(shader), threadsX, threadsY, threadsZ);
CachedShader<T> shaderData;
PipelineState? pipelineState;
PipelineData? pipelineData;
lock (ShadersCache)
{
@@ -105,21 +106,23 @@ namespace ComputeSharp.Shaders
}
// Create the reusable pipeline state
if (!shaderData.CachedPipelines.TryGetValue(device, out pipelineState))
if (!shaderData.CachedPipelines.TryGetValue(device, out pipelineData))
{
CreatePipelineState(device, shaderData, out pipelineState);
CreatePipelineData(device, shaderData, out pipelineData);
}
}
// Create the commands list and set the pipeline state
using CommandList commandList = new CommandList(device, CommandListType.Compute);
commandList.SetPipelineState(pipelineState);
using CommandList commandList = new(device, D3D12_COMMAND_LIST_TYPE_COMPUTE);
commandList.SetPipelineData(pipelineData);
// Extract the dispatch data for the shader invocation
using DispatchData dispatchData = shaderData.Loader.GetDispatchData(shader, x, y, z);
// Load the captured buffers
Span<GraphicsResource> resources = dispatchData.Resources;
ReadOnlySpan<D3D12_GPU_DESCRIPTOR_HANDLE> resources = dispatchData.Resources;
for (int i = 0; i < resources.Length; i++)
{
commandList.SetComputeRootDescriptorTable(i + 1, resources[i]);
@@ -127,8 +130,10 @@ namespace ComputeSharp.Shaders
// Initialize the loop targets and the captured values
ConstantBuffer<Int4> variablesBuffer = ShaderRunner.GetVariablesBuffer(device);
variablesBuffer.SetData(dispatchData.Variables);
commandList.SetComputeRootDescriptorTable(0, variablesBuffer);
commandList.SetComputeRootDescriptorTable(0, variablesBuffer.D3D12GpuDescriptorHandle);
// Calculate the dispatch values
int
@@ -142,13 +147,13 @@ namespace ComputeSharp.Shaders
}
/// <summary>
/// Loads a shader with the specified parameters
/// Loads a shader with the specified parameters.
/// </summary>
/// <param name="threadsX">The number of threads in each thread group for the X axis</param>
/// <param name="threadsY">The number of threads in each thread group for the Y axis</param>
/// <param name="threadsZ">The number of threads in each thread group for the Z axis</param>
/// <param name="shader">The input <typeparamref name="T"/> instance representing the compute shader to run</param>
/// <param name="shaderData">The <see cref="CachedShader{T}"/> instance to return with the cached shader data</param>
/// <param name="threadsX">The number of threads in each thread group for the X axis.</param>
/// <param name="threadsY">The number of threads in each thread group for the Y axis.</param>
/// <param name="threadsZ">The number of threads in each thread group for the Z axis.</param>
/// <param name="shader">The input <typeparamref name="T"/> instance representing the compute shader to run.</param>
/// <param name="shaderData">The <see cref="CachedShader{T}"/> instance to return with the cached shader data.</param>
[MethodImpl(MethodImplOptions.NoInlining)]
private static void LoadShader(int threadsX, int threadsY, int threadsZ, in T shader, out CachedShader<T> shaderData)
{
@@ -158,41 +163,42 @@ namespace ComputeSharp.Shaders
// Render the loaded shader
string shaderSource = ShaderRenderer.Instance.Render(new ShaderInfo
{
BuffersList = shaderLoader.BuffersList,
FieldsList = shaderLoader.FieldsList,
BuffersList = shaderLoader.HslsBuffersInfo,
FieldsList = shaderLoader.FieldsInfo,
NumThreadsX = threadsX,
NumThreadsY = threadsY,
NumThreadsZ = threadsZ,
ThreadsIdsVariableName = shaderLoader.ThreadsIdsVariableName,
ShaderBody = shaderLoader.MethodBody,
FunctionsList = shaderLoader.FunctionsList,
LocalFunctionsList = shaderLoader.LocalFunctionsList
FunctionsList = shaderLoader.FunctionsInfo,
LocalFunctionsList = shaderLoader.LocalFunctionsInfo
});
// Compile the loaded shader to HLSL bytecode
ShaderBytecode shaderBytecode = ShaderCompiler.CompileShader(shaderSource);
IDxcBlobObject shaderBytecode = new(ShaderCompiler.CompileShader(shaderSource));
// Get the cached shader data
shaderData = new CachedShader<T>(shaderLoader, shaderBytecode);
}
/// <summary>
/// Creates and caches a <see cref="PipelineState"/> instance for a given shader
/// Creates and caches a <see cref="PipelineData"/> instance for a given shader.
/// </summary>
/// <param name="device">The <see cref="GraphicsDevice"/> to use to run the shader</param>
/// <param name="shaderData">The <see cref="CachedShader{T}"/> instance with the data on the loaded shader</param>
/// <param name="pipelineState">The resulting <see cref="PipelineState"/> instance to use to run the shader</param>
/// <param name="device">The <see cref="GraphicsDevice"/> to use to run the shader.</param>
/// <param name="shaderData">The <see cref="CachedShader{T}"/> instance with the data on the loaded shader.</param>
/// <param name="pipelineData">The resulting <see cref="PipelineData"/> instance to use to run the shader.</param>
[MethodImpl(MethodImplOptions.NoInlining)]
private static void CreatePipelineState(GraphicsDevice device, in CachedShader<T> shaderData, out PipelineState pipelineState)
private static unsafe void CreatePipelineData(GraphicsDevice device, in CachedShader<T> shaderData, out PipelineData pipelineData)
{
// Create the root signature for the pipeline and get the pipeline state
RootSignatureDescription1 rootSignatureDescription = new RootSignatureDescription1(RootSignatureFlags.None, shaderData.Loader.RootParameters);
VersionedRootSignatureDescription versionedRootSignatureDescription = new VersionedRootSignatureDescription(rootSignatureDescription);
ID3D12RootSignature rootSignature = device.CreateRootSignature(versionedRootSignatureDescription);
pipelineState = new PipelineState(device, rootSignature, shaderData.Bytecode);
using ComPtr<ID3D12RootSignature> d3D12RootSignature = device.D3D12Device->CreateRootSignature(shaderData.Loader.D3D12DescriptorRanges1);
// Cache the pipeline state for the target device
shaderData.CachedPipelines.Add(device, pipelineState);
D3D12_SHADER_BYTECODE d3D12ShaderBytecode = new((ID3DBlob*)shaderData.Bytecode.DxcBlob);
using ComPtr<ID3D12PipelineState> d3D12PipelineState = device.D3D12Device->CreateComputePipelineState(d3D12RootSignature.Get(), d3D12ShaderBytecode);
pipelineData = new PipelineData(d3D12RootSignature.Move(), d3D12PipelineState.Move());
shaderData.CachedPipelines.Add(device, pipelineData);
}
}
}
+5 -5
ファイルの表示
@@ -9,13 +9,13 @@ namespace ComputeSharp.Shaders.Translation.Models
/// A <see langword="struct"/> that contains info on a cached shader.
/// </summary>
/// <typeparam name="T">The type of compute shader in use.</typeparam>
internal readonly struct CachedShader2<T>
internal readonly struct CachedShader<T>
where T : struct, IComputeShader
{
/// <summary>
/// The <see cref="ShaderLoader2{T}"/> instance with the shader metadata.
/// The <see cref="ShaderLoader{T}"/> instance with the shader metadata.
/// </summary>
public readonly ShaderLoader2<T> Loader;
public readonly ShaderLoader<T> Loader;
/// <summary>
/// The compiled shader bytecode.
@@ -25,14 +25,14 @@ namespace ComputeSharp.Shaders.Translation.Models
/// <summary>
/// The map of cached <see cref="PipelineData"/> instances for each GPU in use.
/// </summary>
public readonly ConditionalWeakTable<GraphicsDevice2, PipelineData> CachedPipelines;
public readonly ConditionalWeakTable<GraphicsDevice, PipelineData> CachedPipelines;
/// <summary>
/// Creates a new <see cref="CachedShader{T}"/> instance with the specified parameters.
/// </summary>
/// <param name="loader">The <see cref="ShaderLoader{T}"/> instance with the shader metadata.</param>
/// <param name="bytecode">The compiled shader bytecode.</param>
public CachedShader2(ShaderLoader2<T> loader, IDxcBlobObject bytecode)
public CachedShader(ShaderLoader<T> loader, IDxcBlobObject bytecode)
{
Loader = loader;
Bytecode = bytecode;
-42
ファイルの表示
@@ -1,42 +0,0 @@
using System.Runtime.CompilerServices;
using ComputeSharp.Graphics;
using ComputeSharp.Graphics.Commands;
using Vortice.Direct3D12;
namespace ComputeSharp.Shaders.Translation.Models
{
/// <summary>
/// A <see langword="struct"/> that contains info on a cached shader
/// </summary>
/// <typeparam name="T">The type of compute shader in use</typeparam>
internal readonly struct CachedShader<T>
where T : struct, IComputeShader
{
/// <summary>
/// The <see cref="ShaderLoader{T}"/> instance with the shader metadata
/// </summary>
public readonly ShaderLoader<T> Loader;
/// <summary>
/// The compiled shader bytecode
/// </summary>
public readonly ShaderBytecode Bytecode;
/// <summary>
/// The map of cached <see cref="PipelineState"/> instances for each GPU in use.
/// </summary>
public readonly ConditionalWeakTable<GraphicsDevice, PipelineState> CachedPipelines;
/// <summary>
/// Creates a new <see cref="CachedShader{T}"/> instance with the specified parameters
/// </summary>
/// <param name="loader">The <see cref="ShaderLoader{T}"/> instance with the shader metadata</param>
/// <param name="bytecode">The compiled shader bytecode</param>
public CachedShader(ShaderLoader<T> loader, ShaderBytecode bytecode)
{
Loader = loader;
Bytecode = bytecode;
CachedPipelines = new ConditionalWeakTable<GraphicsDevice, PipelineState>();
}
}
}
+43 -37
ファイルの表示
@@ -3,80 +3,86 @@ using System.Buffers;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using ComputeSharp.Graphics.Buffers.Abstract;
using TerraFX.Interop;
namespace ComputeSharp.Shaders.Translation.Models
{
/// <summary>
/// A <see langword="struct"/> that contains all the captured data to dispatch a shader
/// A <see langword="struct"/> that contains all the captured data to dispatch a shader.
/// </summary>
internal readonly ref struct DispatchData
{
/// <summary>
/// The <see cref="GraphicsResource"/> array with the captured buffers
/// The <see cref="D3D12_GPU_DESCRIPTOR_HANDLE"/> array with the captured buffers.
/// </summary>
private readonly GraphicsResource[] ResourcesArray;
private readonly D3D12_GPU_DESCRIPTOR_HANDLE[] resourcesArray;
/// <summary>
/// The number of <see cref="GraphicsResource"/> instances in <see cref="ResourcesArray"/>
/// The number of <see cref="GraphicsResource"/> instances in <see cref="resourcesArray"/>.
/// </summary>
private readonly int ResourcesCount;
private readonly int resourcesCount;
/// <summary>
/// The <see cref="byte"/> array with all the captured variables, with proper padding
/// The <see cref="byte"/> array with all the captured variables, with proper padding.
/// </summary>
private readonly byte[] VariablesArray;
private readonly byte[] variablesArray;
/// <summary>
/// The actual size in bytes to use from <see cref="VariablesArray"/>
/// The actual size in bytes to use from <see cref="variablesArray"/>.
/// </summary>
private readonly int VariablesByteSize;
private readonly int variablesByteSize;
/// <summary>
/// Creates a new <see cref="DispatchData"/> instance with the specified parameters
/// Creates a new <see cref="DispatchData"/> instance with the specified parameters.
/// </summary>
/// <param name="resourcesArray">The <see cref="GraphicsResource"/> array with the captured buffers</param>
/// <param name="resourcesCount">The number of <see cref="GraphicsResource"/> instances in <see cref="ResourcesArray"/></param>
/// <param name="variablesArray">The <see cref="byte"/> array with all the captured variables, with proper padding</param>
/// <param name="variablesByteSize">The actual size in bytes to use from <see cref="VariablesArray"/></param>
public DispatchData(GraphicsResource[] resourcesArray, int resourcesCount, byte[] variablesArray, int variablesByteSize)
/// <param name="resourcesArray">The <see cref="D3D12_GPU_DESCRIPTOR_HANDLE"/> array with the captured buffers.</param>
/// <param name="resourcesCount">The number of <see cref="D3D12_GPU_DESCRIPTOR_HANDLE"/> instances in <see cref="resourcesArray"/>.</param>
/// <param name="variablesArray">The <see cref="byte"/> array with all the captured variables, with proper padding.</param>
/// <param name="variablesByteSize">The actual size in bytes to use from <see cref="variablesArray"/>.</param>
public DispatchData(D3D12_GPU_DESCRIPTOR_HANDLE[] resourcesArray, int resourcesCount, byte[] variablesArray, int variablesByteSize)
{
ResourcesArray = resourcesArray;
VariablesArray = variablesArray;
ResourcesCount = resourcesCount;
VariablesByteSize = variablesByteSize;
this.resourcesArray = resourcesArray;
this.variablesArray = variablesArray;
this.resourcesCount = resourcesCount;
this.variablesByteSize = variablesByteSize;
}
/// <summary>
/// Gets a <see cref="Span{T}"/> with all the captured buffers
/// Gets a <see cref="ReadOnlySpan{T}"/> with all the captured buffers.
/// </summary>
public Span<GraphicsResource> Resources
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => ResourcesArray.AsSpan(0, ResourcesCount);
}
/// <summary>
/// Gets a <see cref="Span{T}"/> with the padded data representing all the captured variables
/// </summary>
public Span<Int4> Variables
public ReadOnlySpan<D3D12_GPU_DESCRIPTOR_HANDLE> Resources
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
ref Int4 r = ref Unsafe.As<byte, Int4>(ref VariablesArray[0]);
bool mod = (VariablesByteSize & 15) > 0;
int length = VariablesByteSize / 4 + Unsafe.As<bool, byte>(ref mod);
return MemoryMarshal.CreateSpan(ref r, length);
ref D3D12_GPU_DESCRIPTOR_HANDLE r0 = ref MemoryMarshal.GetArrayDataReference(this.resourcesArray);
return MemoryMarshal.CreateReadOnlySpan(ref r0, this.resourcesCount);
}
}
/// <summary>
/// Implements the <see cref="IDisposable.Dispose"/> method and returns the rented buffers
/// Gets a <see cref="ReadOnlySpan{T}"/> with the padded data representing all the captured variables.
/// </summary>
public ReadOnlySpan<Int4> Variables
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
ref byte r0 = ref MemoryMarshal.GetArrayDataReference(this.variablesArray);
ref Int4 r1 = ref Unsafe.As<byte, Int4>(ref r0);
bool mod = (this.variablesByteSize & 15) > 0;
int length = variablesByteSize / 4 + Unsafe.As<bool, byte>(ref mod);
return MemoryMarshal.CreateReadOnlySpan(ref r1, length);
}
}
/// <inheritdoc cref="IDisposable.Dispose"/>
public void Dispose()
{
ArrayPool<GraphicsResource>.Shared.Return(ResourcesArray, true);
ArrayPool<byte>.Shared.Return(VariablesArray);
ArrayPool<D3D12_GPU_DESCRIPTOR_HANDLE>.Shared.Return(this.resourcesArray);
ArrayPool<byte>.Shared.Return(this.variablesArray);
}
}
}
-88
ファイルの表示
@@ -1,88 +0,0 @@
using System;
using System.Buffers;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using ComputeSharp.Graphics.Buffers.Abstract;
using TerraFX.Interop;
namespace ComputeSharp.Shaders.Translation.Models
{
/// <summary>
/// A <see langword="struct"/> that contains all the captured data to dispatch a shader.
/// </summary>
internal readonly ref struct DispatchData2
{
/// <summary>
/// The <see cref="D3D12_GPU_DESCRIPTOR_HANDLE"/> array with the captured buffers.
/// </summary>
private readonly D3D12_GPU_DESCRIPTOR_HANDLE[] resourcesArray;
/// <summary>
/// The number of <see cref="GraphicsResource"/> instances in <see cref="resourcesArray"/>.
/// </summary>
private readonly int resourcesCount;
/// <summary>
/// The <see cref="byte"/> array with all the captured variables, with proper padding.
/// </summary>
private readonly byte[] variablesArray;
/// <summary>
/// The actual size in bytes to use from <see cref="variablesArray"/>.
/// </summary>
private readonly int variablesByteSize;
/// <summary>
/// Creates a new <see cref="DispatchData"/> instance with the specified parameters.
/// </summary>
/// <param name="resourcesArray">The <see cref="D3D12_GPU_DESCRIPTOR_HANDLE"/> array with the captured buffers.</param>
/// <param name="resourcesCount">The number of <see cref="D3D12_GPU_DESCRIPTOR_HANDLE"/> instances in <see cref="resourcesArray"/>.</param>
/// <param name="variablesArray">The <see cref="byte"/> array with all the captured variables, with proper padding.</param>
/// <param name="variablesByteSize">The actual size in bytes to use from <see cref="variablesArray"/>.</param>
public DispatchData2(D3D12_GPU_DESCRIPTOR_HANDLE[] resourcesArray, int resourcesCount, byte[] variablesArray, int variablesByteSize)
{
this.resourcesArray = resourcesArray;
this.variablesArray = variablesArray;
this.resourcesCount = resourcesCount;
this.variablesByteSize = variablesByteSize;
}
/// <summary>
/// Gets a <see cref="ReadOnlySpan{T}"/> with all the captured buffers.
/// </summary>
public ReadOnlySpan<D3D12_GPU_DESCRIPTOR_HANDLE> Resources
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
ref D3D12_GPU_DESCRIPTOR_HANDLE r0 = ref MemoryMarshal.GetArrayDataReference(this.resourcesArray);
return MemoryMarshal.CreateReadOnlySpan(ref r0, this.resourcesCount);
}
}
/// <summary>
/// Gets a <see cref="ReadOnlySpan{T}"/> with the padded data representing all the captured variables.
/// </summary>
public ReadOnlySpan<Int4> Variables
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
ref byte r0 = ref MemoryMarshal.GetArrayDataReference(this.variablesArray);
ref Int4 r1 = ref Unsafe.As<byte, Int4>(ref r0);
bool mod = (this.variablesByteSize & 15) > 0;
int length = variablesByteSize / 4 + Unsafe.As<bool, byte>(ref mod);
return MemoryMarshal.CreateReadOnlySpan(ref r1, length);
}
}
/// <inheritdoc cref="IDisposable.Dispose"/>
public void Dispose()
{
ArrayPool<D3D12_GPU_DESCRIPTOR_HANDLE>.Shared.Return(this.resourcesArray);
ArrayPool<byte>.Shared.Return(this.variablesArray);
}
}
}
+120 -22
ファイルの表示
@@ -1,42 +1,140 @@
using System.Diagnostics.Contracts;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using System.Runtime.CompilerServices;
using ComputeSharp.Exceptions;
using Vortice.Direct3D12;
using Vortice.Dxc;
using ComputeSharp.Graphics.Helpers;
using TerraFX.Interop;
using FX = TerraFX.Interop.Windows;
namespace ComputeSharp.Shaders.Translation
{
/// <summary>
/// A <see langword="class"/> that uses the <see cref="DxcCompiler"/> APIs to compile compute shaders
/// A <see langword="class"/> that uses the DXC APIs to compile compute shaders.
/// </summary>
internal static class ShaderCompiler
internal static unsafe class ShaderCompiler
{
/// <summary>
/// The <see cref="IDxcLibrary"/> instance to use to create the bytecode for HLSL sources
/// The <see cref="IDxcCompiler"/> instance to use to create the bytecode for HLSL sources.
/// </summary>
private static readonly IDxcLibrary Library = Dxc.CreateDxcLibrary();
private static readonly ComPtr<IDxcCompiler> DxcCompiler;
/// <summary>
/// Compiles a new HLSL shader from the input source code
/// The <see cref="IDxcLibrary"/> instance to use to work with <see cref="DxcCompiler"/>.
/// </summary>
/// <param name="source">The HLSL source code to compile</param>
/// <returns>The bytecode for the compiled shader</returns>
[Pure]
public static ShaderBytecode CompileShader(string source)
private static readonly ComPtr<IDxcLibrary> DxcLibrary;
/// <summary>
/// The <see cref="IDxcIncludeHandler"/> instance used to compile shaders with <see cref="DxcCompiler"/>.
/// </summary>
private static readonly ComPtr<IDxcIncludeHandler> DxcIncludeHandler;
/// <summary>
/// Initializes <see cref="DxcCompiler"/>, <see cref="DxcLibrary"/> and <see cref="DxcIncludeHandler"/>
/// </summary>
static ShaderCompiler()
{
var result = DxcCompiler.Compile(DxcShaderStage.ComputeShader, source, "CSMain", string.Empty, new DxcCompilerOptions { ShaderModel = DxcShaderModel.Model6_1 });
using ComPtr<IDxcCompiler> dxcCompiler = default;
using ComPtr<IDxcLibrary> dxcLibrary = default;
using ComPtr<IDxcIncludeHandler> dxcIncludeHandler = default;
// Get the compiled bytecode in case of success
if (result.GetStatus() == 0)
Guid dxcCompilerCLGuid = FX.CLSID_DxcCompiler;
Guid dxcCompilerGuid = FX.IID_IDxcCompiler;
Guid dxcLibraryCLGuid = FX.CLSID_DxcLibrary;
Guid dxcLibraryGuid = FX.IID_IDxcLibrary;
FX.DxcCreateInstance(&dxcCompilerCLGuid, &dxcCompilerGuid, dxcCompiler.GetVoidAddressOf()).Assert();
FX.DxcCreateInstance(&dxcLibraryCLGuid, &dxcLibraryGuid, dxcLibrary.GetVoidAddressOf()).Assert();
dxcLibrary.Get()->CreateIncludeHandler(dxcIncludeHandler.GetAddressOf()).Assert();
DxcCompiler = dxcCompiler;
DxcLibrary = dxcLibrary;
DxcIncludeHandler = dxcIncludeHandler;
}
/// <summary>
/// Compiles a new HLSL shader from the input source code.
/// </summary>
/// <param name="source">The HLSL source code to compile.</param>
/// <returns>The bytecode for the compiled shader.</returns>
[Pure]
public static ComPtr<IDxcBlob> CompileShader(ReadOnlySpan<char> source)
{
using ComPtr<IDxcBlobEncoding> dxcBlobEncoding = default;
using ComPtr<IDxcOperationResult> dxcOperationResult = default;
using ComPtr<IDxcBlob> dxcBlobBytecode = default;
// Get the encoded blob from the source code
fixed (char* p = source)
{
IDxcBlob blob = result.GetResult();
byte[] bytecode = Dxc.GetBytesFromBlob(blob);
return bytecode;
DxcLibrary.Get()->CreateBlobWithEncodingOnHeapCopy(
p,
(uint)source.Length * 2,
1200,
dxcBlobEncoding.GetAddressOf()).Assert();
}
// Compile error
string resultText = Dxc.GetStringFromBlob(Library, result.GetErrors());
throw new HlslCompilationException(resultText);
// Try to compile the new compute shader
fixed (char* entryPoint = "CSMain")
fixed (char* shaderProfile = "cs_6_1")
fixed (char* optimization = "-O3")
{
char nullTerminator = '\0';
DxcCompiler.Get()->Compile(
dxcBlobEncoding.Upcast<IDxcBlobEncoding, IDxcBlob>().Get(),
(ushort*)&nullTerminator,
(ushort*)entryPoint,
(ushort*)shaderProfile,
(ushort**)&optimization,
1,
null,
0,
DxcIncludeHandler.Get(),
dxcOperationResult.GetAddressOf()).Assert();
}
int status;
dxcOperationResult.Get()->GetStatus(&status).Assert();
// The compilation was successful, so we can extract the shader bytecode
if (status == 0)
{
dxcOperationResult.Get()->GetResult(dxcBlobBytecode.GetAddressOf()).Assert();
return dxcBlobBytecode.Move();
}
return ThrowHslsCompilationException(dxcOperationResult);
}
/// <summary>
/// Throws an exception when a shader compilation fails.
/// </summary>
/// <param name="dxcOperationResult">The input (faulting) operation.</param>
/// <returns>This method always throws and never actually returs.</returns>
[DoesNotReturn]
[MethodImpl(MethodImplOptions.NoInlining)]
private static ComPtr<IDxcBlob> ThrowHslsCompilationException(ComPtr<IDxcOperationResult> dxcOperationResult)
{
using ComPtr<IDxcBlobEncoding> dxcBlobEncodingError = default;
dxcOperationResult.Get()->GetErrorBuffer(dxcBlobEncodingError.GetAddressOf()).Assert();
using ComPtr<IDxcBlobUtf16> dxcBlobUtf16Error = default;
DxcLibrary.Get()->GetBlobAsUtf16(
dxcBlobEncodingError.Upcast<IDxcBlobEncoding, IDxcBlob>().Get(),
dxcBlobUtf16Error.Upcast<IDxcBlobUtf16, IDxcBlobEncoding>().GetAddressOf()).Assert();
string message = new string(
(char*)dxcBlobUtf16Error.Get()->GetStringPointer(),
0,
checked((int)dxcBlobUtf16Error.Get()->GetStringLength()));
throw new HlslCompilationException(message);
}
}
}
-140
ファイルの表示
@@ -1,140 +0,0 @@
using System;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using System.Runtime.CompilerServices;
using ComputeSharp.Exceptions;
using ComputeSharp.Graphics.Helpers;
using TerraFX.Interop;
using FX = TerraFX.Interop.Windows;
namespace ComputeSharp.Shaders.Translation
{
/// <summary>
/// A <see langword="class"/> that uses the DXC APIs to compile compute shaders.
/// </summary>
internal static unsafe class ShaderCompiler2
{
/// <summary>
/// The <see cref="IDxcCompiler"/> instance to use to create the bytecode for HLSL sources.
/// </summary>
private static readonly ComPtr<IDxcCompiler> DxcCompiler;
/// <summary>
/// The <see cref="IDxcLibrary"/> instance to use to work with <see cref="DxcCompiler"/>.
/// </summary>
private static readonly ComPtr<IDxcLibrary> DxcLibrary;
/// <summary>
/// The <see cref="IDxcIncludeHandler"/> instance used to compile shaders with <see cref="DxcCompiler"/>.
/// </summary>
private static readonly ComPtr<IDxcIncludeHandler> DxcIncludeHandler;
/// <summary>
/// Initializes <see cref="DxcCompiler"/>, <see cref="DxcLibrary"/> and <see cref="DxcIncludeHandler"/>
/// </summary>
static ShaderCompiler2()
{
using ComPtr<IDxcCompiler> dxcCompiler = default;
using ComPtr<IDxcLibrary> dxcLibrary = default;
using ComPtr<IDxcIncludeHandler> dxcIncludeHandler = default;
Guid dxcCompilerCLGuid = FX.CLSID_DxcCompiler;
Guid dxcCompilerGuid = FX.IID_IDxcCompiler;
Guid dxcLibraryCLGuid = FX.CLSID_DxcLibrary;
Guid dxcLibraryGuid = FX.IID_IDxcLibrary;
FX.DxcCreateInstance(&dxcCompilerCLGuid, &dxcCompilerGuid, dxcCompiler.GetVoidAddressOf()).Assert();
FX.DxcCreateInstance(&dxcLibraryCLGuid, &dxcLibraryGuid, dxcLibrary.GetVoidAddressOf()).Assert();
dxcLibrary.Get()->CreateIncludeHandler(dxcIncludeHandler.GetAddressOf()).Assert();
DxcCompiler = dxcCompiler;
DxcLibrary = dxcLibrary;
DxcIncludeHandler = dxcIncludeHandler;
}
/// <summary>
/// Compiles a new HLSL shader from the input source code.
/// </summary>
/// <param name="source">The HLSL source code to compile.</param>
/// <returns>The bytecode for the compiled shader.</returns>
[Pure]
public static ComPtr<IDxcBlob> CompileShader(ReadOnlySpan<char> source)
{
using ComPtr<IDxcBlobEncoding> dxcBlobEncoding = default;
using ComPtr<IDxcOperationResult> dxcOperationResult = default;
using ComPtr<IDxcBlob> dxcBlobBytecode = default;
// Get the encoded blob from the source code
fixed (char* p = source)
{
DxcLibrary.Get()->CreateBlobWithEncodingOnHeapCopy(
p,
(uint)source.Length * 2,
1200,
dxcBlobEncoding.GetAddressOf()).Assert();
}
// Try to compile the new compute shader
fixed (char* entryPoint = "CSMain")
fixed (char* shaderProfile = "cs_6_1")
fixed (char* optimization = "-O3")
{
char nullTerminator = '\0';
DxcCompiler.Get()->Compile(
dxcBlobEncoding.Upcast<IDxcBlobEncoding, IDxcBlob>().Get(),
(ushort*)&nullTerminator,
(ushort*)entryPoint,
(ushort*)shaderProfile,
(ushort**)&optimization,
1,
null,
0,
DxcIncludeHandler.Get(),
dxcOperationResult.GetAddressOf()).Assert();
}
int status;
dxcOperationResult.Get()->GetStatus(&status).Assert();
// The compilation was successful, so we can extract the shader bytecode
if (status == 0)
{
dxcOperationResult.Get()->GetResult(dxcBlobBytecode.GetAddressOf()).Assert();
return dxcBlobBytecode.Move();
}
return ThrowHslsCompilationException(dxcOperationResult);
}
/// <summary>
/// Throws an exception when a shader compilation fails.
/// </summary>
/// <param name="dxcOperationResult">The input (faulting) operation.</param>
/// <returns>This method always throws and never actually returs.</returns>
[DoesNotReturn]
[MethodImpl(MethodImplOptions.NoInlining)]
private static ComPtr<IDxcBlob> ThrowHslsCompilationException(ComPtr<IDxcOperationResult> dxcOperationResult)
{
using ComPtr<IDxcBlobEncoding> dxcBlobEncodingError = default;
dxcOperationResult.Get()->GetErrorBuffer(dxcBlobEncodingError.GetAddressOf()).Assert();
using ComPtr<IDxcBlobUtf16> dxcBlobUtf16Error = default;
DxcLibrary.Get()->GetBlobAsUtf16(
dxcBlobEncodingError.Upcast<IDxcBlobEncoding, IDxcBlob>().Get(),
dxcBlobUtf16Error.Upcast<IDxcBlobUtf16, IDxcBlobEncoding>().GetAddressOf()).Assert();
string message = new string(
(char*)dxcBlobUtf16Error.Get()->GetStringPointer(),
0,
checked((int)dxcBlobUtf16Error.Get()->GetStringLength()));
throw new HlslCompilationException(message);
}
}
}
-144
ファイルの表示
@@ -1,144 +0,0 @@
using System;
using System.Buffers;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using ComputeSharp.Graphics.Buffers;
using ComputeSharp.Shaders.Mappings;
using ComputeSharp.Shaders.Translation.Models;
using TerraFX.Interop;
namespace ComputeSharp.Shaders.Translation
{
/// <inheritdoc cref="ShaderLoader2{T}"/>
internal sealed partial class ShaderLoader2<T>
{
/// <summary>
/// A <see langword="delegate"/> that loads all the captured members from a shader instance.
/// </summary>
/// <param name="shader">The shader instance to load the data from.</param>
/// <param name="r0">A reference to the buffer with all the captured <see cref="D3D12_GPU_DESCRIPTOR_HANDLE"/> instances.</param>
/// <param name="r1">A reference to the buffer to use to store all the captured value types.</param>
private delegate void DispatchDataLoader(in T shader, ref D3D12_GPU_DESCRIPTOR_HANDLE r0, ref byte r1);
/// <summary>
/// The number of captured graphics resources (buffers).
/// </summary>
private int totalResourceCount;
/// <summary>
/// The size in bytes of the buffer with the captured variables.
/// </summary>
/// <remarks>Initially set to 3 <see cref="int"/> values for X, Y and Z threads counts.</remarks>
private int totalVariablesByteSize = 3 * sizeof(int);
/// <summary>
/// The cached <see cref="DispatchDataLoader"/> instance to load dispatch data before execution.
/// </summary>
private DispatchDataLoader? dispatchDataLoader;
/// <summary>
/// The <see cref="List{T}"/> of <see cref="ReadableMember"/> instances mapping the captured variables in the current shader.
/// </summary>
private readonly List<ReadableMember> capturedMembers = new();
/// <summary>
/// Gets a new <see cref="DispatchData2"/> instance with all the captured data for the current shader instance.
/// </summary>
/// <param name="shader">The input <typeparamref name="T"/> instance representing the compute shader to run.</param>
/// <param name="x">The number of iterations to run on the X axis.</param>
/// <param name="y">The number of iterations to run on the Y axis.</param>
/// <param name="z">The number of iterations to run on the Z axis.</param>
[Pure]
public DispatchData2 GetDispatchData(in T shader, int x, int y, int z)
{
// Resources and variables buffers
D3D12_GPU_DESCRIPTOR_HANDLE[] resources = ArrayPool<D3D12_GPU_DESCRIPTOR_HANDLE>.Shared.Rent(this.totalResourceCount);
byte[] variables = ArrayPool<byte>.Shared.Rent(this.totalVariablesByteSize);
ref D3D12_GPU_DESCRIPTOR_HANDLE r0 = ref MemoryMarshal.GetArrayDataReference(resources);
ref byte r1 = ref MemoryMarshal.GetArrayDataReference(variables);
// Set the x, y and z counters
Unsafe.As<byte, int>(ref r1) = x;
Unsafe.Add(ref Unsafe.As<byte, int>(ref r1), 1) = y;
Unsafe.Add(ref Unsafe.As<byte, int>(ref r1), 2) = z;
// Invoke the dynamic method to extract the captured data
this.dispatchDataLoader!(shader, ref r0, ref r1);
return new DispatchData2(resources, this.totalResourceCount, variables, this.totalVariablesByteSize);
}
/// <summary>
/// Builds a new <see cref="DispatchDataLoader"/> instance that loads the dispatch data for the current shader type.
/// </summary>
private void BuildDispatchDataLoader()
{
this.dispatchDataLoader = DynamicMethod<DispatchDataLoader>.New(il =>
{
foreach (ReadableMember member in this.capturedMembers)
{
if (HlslKnownTypes.IsKnownBufferType(member.MemberType))
{
// Load the offset address into the resource buffers
il.Emit(OpCodes.Ldarg_1);
if (totalResourceCount > 0)
{
il.EmitAddOffset<D3D12_GPU_DESCRIPTOR_HANDLE>(this.totalResourceCount);
}
il.Emit(OpCodes.Ldarg_0);
il.EmitReadMember(member);
// Access Buffer<T>.D3D12GpuDescriptorHandle
FieldInfo gpuDescriptorInfo = member.MemberType.GetField(
nameof(Buffer2<byte>.D3D12GpuDescriptorHandle),
BindingFlags.NonPublic | BindingFlags.Instance)!;
il.EmitReadMember(gpuDescriptorInfo);
il.EmitStoreToAddress(member.MemberType);
this.totalResourceCount++;
}
else if (HlslKnownTypes.IsKnownScalarType(member.MemberType) ||
HlslKnownTypes.IsKnownVectorType(member.MemberType))
{
// Calculate the right offset with 16-bytes padding (HLSL constant buffer)
int size = member.MemberType == typeof(bool)
? sizeof(uint)
: Marshal.SizeOf(member.MemberType); // bool is 4 bytes in HLSL
if (this.totalVariablesByteSize % 16 > 16 - size)
{
this.totalVariablesByteSize += 16 - this.totalVariablesByteSize % 16;
}
// Load the target address into the variables buffer
il.Emit(OpCodes.Ldarg_2);
il.EmitAddOffset(totalVariablesByteSize);
this.totalVariablesByteSize += size;
}
else throw new InvalidOperationException($"Invalid captured member of type {member.MemberType}");
// Load the reference to the input delegate if the member is not static
if (!member.IsStatic)
{
il.Emit(OpCodes.Ldarg_0);
}
// Read the current member and store it to the target address
il.EmitReadMember(member);
il.EmitStoreToAddress(member.MemberType);
}
il.Emit(OpCodes.Ret);
});
}
}
}
-355
ファイルの表示
@@ -1,355 +0,0 @@
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
using ComputeSharp.Graphics.Extensions;
using ComputeSharp.Shaders.Mappings;
using ComputeSharp.Shaders.Renderer.Models.Fields;
using ComputeSharp.Shaders.Renderer.Models.Fields.Abstract;
using ComputeSharp.Shaders.Renderer.Models.Functions;
using ComputeSharp.Shaders.Translation.Enums;
using ComputeSharp.Shaders.Translation.Models;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using TerraFX.Interop;
using static TerraFX.Interop.D3D12_DESCRIPTOR_RANGE_TYPE;
using ParameterInfo = ComputeSharp.Shaders.Renderer.Models.Functions.ParameterInfo;
#pragma warning disable CS8618 // Non-nullable field is uninitialized
namespace ComputeSharp.Shaders.Translation
{
/// <summary>
/// A <see langword="class"/> responsible for loading and processing shaders of a given type.
/// </summary>
/// <typeparam name="T">The type of compute shader currently in use.</typeparam>
internal sealed partial class ShaderLoader2<T>
where T : struct, IComputeShader
{
/// <summary>
/// The number of constant buffers to define in the shader.
/// </summary>
private uint constantBuffersCount;
/// <summary>
/// The number of readonly buffers to define in the shader.
/// </summary>
private uint readOnlyBuffersCount;
/// <summary>
/// The number of read write buffers to define in the shader.
/// </summary>
private uint readWriteBuffersCount;
/// <summary>
/// The <see cref="List{T}"/> of <see cref="D3D12_DESCRIPTOR_RANGE1"/> items that are required to load the captured values.
/// </summary>
private readonly List<D3D12_DESCRIPTOR_RANGE1> d3D12DescriptorRanges1 = new();
/// <summary>
/// The <see cref="List{T}"/> with the <see cref="HlslBufferInfo"/> items for the shader fields.
/// </summary>
private readonly List<HlslBufferInfo> hlslBuffersInfo = new();
/// <summary>
/// The <see cref="List{T}"/> with the <see cref="CapturedFieldInfo"/> items for the shader fields.
/// </summary>
private readonly List<CapturedFieldInfo> fieldsInfo = new();
/// <summary>
/// The <see cref="List{T}"/> with the <see cref="FunctionInfo"/> items for the shader functions.
/// </summary>
private readonly List<FunctionInfo> functionsInfo = new();
/// <summary>
/// The <see cref="List{T}"/> with the <see cref="FunctionInfo"/> items for the shader local functions.
/// </summary>
private readonly List<LocalFunctionInfo> localFunctionsInfo = new();
/// <summary>
/// Creates a new <see cref="ShaderLoader2{T}"/> instance.
/// </summary>
private ShaderLoader2()
{
}
/// <summary>
/// Gets a <see cref="Span{T}"/> with the loaded <see cref="D3D12_DESCRIPTOR_RANGE1"/> items for the shader.
/// </summary>
public ReadOnlySpan<D3D12_DESCRIPTOR_RANGE1> D3D12DescriptorRanges1
{
get => CollectionsMarshal.AsSpan(this.d3D12DescriptorRanges1);
}
/// <summary>
/// Gets the name of the <see cref="ThreadIds"/> variable used as input for the shader method.
/// </summary>
public string ThreadsIdsVariableName { get; private set; }
/// <summary>
/// Gets the generated source code for the method in the current shader.
/// </summary>
public string MethodBody { get; private set; }
/// <summary>
/// Gets the collection of <see cref="HlslBufferInfo"/> items for the shader fields.
/// </summary>
public IReadOnlyList<HlslBufferInfo> HslsBuffersInfo => this.hlslBuffersInfo;
/// <summary>
/// Gets the collection of <see cref="CapturedFieldInfo"/> items for the shader fields.
/// </summary>
public IReadOnlyList<CapturedFieldInfo> FieldsInfo => this.fieldsInfo;
/// <summary>
/// Gets the collection of <see cref="FunctionInfo"/> items for the shader.
/// </summary>
public IReadOnlyList<FunctionInfo> FunctionsInfo => this.functionsInfo;
/// <summary>
/// Gets the collection of <see cref="LocalFunctionInfo"/> items for the shader.
/// </summary>
public IReadOnlyList<LocalFunctionInfo> LocalFunctionsInfo => this.localFunctionsInfo;
/// <summary>
/// Loads and processes an input<typeparamref name="T"/> shadeer
/// </summary>
/// <param name="shader">The <typeparamref name="T"/> instance to use to build the shader</param>
/// <returns>A new <see cref="ShaderLoader"/> instance representing the input shader</returns>
[Pure]
public static ShaderLoader2<T> Load(in T shader)
{
ShaderLoader2<T> @this = new ShaderLoader2<T>();
// Reading members through reflection requires an object parameter,
// so here we're just boxing the input shader once to avoid allocating
// it multiple times in the managed heap while processing the shader.
object box = shader;
@this.LoadFieldsInfo(box);
@this.LoadMethodSource(box);
@this.BuildDispatchDataLoader();
return @this;
}
/// <summary>
/// Loads the fields info for the current shader being loaded
/// </summary>
/// <param name="shader">The boxed <typeparamref name="T"/> instance to use to build the shader</param>
private void LoadFieldsInfo(object shader)
{
IReadOnlyList<FieldInfo> shaderFields = typeof(T).GetFields(
BindingFlags.Instance |
BindingFlags.Static |
BindingFlags.Public |
BindingFlags.NonPublic).ToArray();
if (shaderFields.Count == 0) throw new InvalidOperationException("Empty shader body");
// Descriptor for the buffer for captured scalar/vector variables
D3D12_DESCRIPTOR_RANGE1.Init(
out D3D12_DESCRIPTOR_RANGE1 d3D12DescriptorRange1,
D3D12_DESCRIPTOR_RANGE_TYPE_CBV,
1,
this.constantBuffersCount++);
this.d3D12DescriptorRanges1.Add(d3D12DescriptorRange1);
// Inspect the captured fields
foreach (FieldInfo fieldInfo in shaderFields)
{
LoadFieldInfo(shader, fieldInfo);
}
}
/// <summary>
/// Loads a specified <see cref="ReadableMember"/> and adds it to the shader model
/// </summary>
/// <param name="shader">The boxed <typeparamref name="T"/> instance to use to build the shader</param>
/// <param name="memberInfo">The target <see cref="ReadableMember"/> to load</param>
/// <param name="name">The optional explicit name to use for the field</param>
private void LoadFieldInfo(object shader, ReadableMember memberInfo, string? name = null)
{
Type fieldType = memberInfo.MemberType;
string fieldName = HlslKnownKeywords.GetMappedName(name ?? memberInfo.Name);
// Constant buffer
if (HlslKnownTypes.IsConstantBufferType(fieldType))
{
D3D12_DESCRIPTOR_RANGE1.Init(
out D3D12_DESCRIPTOR_RANGE1 d3D12DescriptorRange1,
D3D12_DESCRIPTOR_RANGE_TYPE_CBV,
1,
this.constantBuffersCount++);
this.d3D12DescriptorRanges1.Add(d3D12DescriptorRange1);
this.capturedMembers.Add(memberInfo);
string typeName = HlslKnownTypes.GetMappedName(fieldType.GenericTypeArguments[0]);
this.hlslBuffersInfo.Add(new ConstantBufferFieldInfo(fieldType, typeName, fieldName, (int)this.constantBuffersCount));
}
else if (HlslKnownTypes.IsReadOnlyBufferType(fieldType))
{
// Root parameter for a readonly buffer
D3D12_DESCRIPTOR_RANGE1.Init(
out D3D12_DESCRIPTOR_RANGE1 d3D12DescriptorRange1,
D3D12_DESCRIPTOR_RANGE_TYPE_SRV,
1,
this.readOnlyBuffersCount++);
this.d3D12DescriptorRanges1.Add(d3D12DescriptorRange1);
this.capturedMembers.Add(memberInfo);
string typeName = HlslKnownTypes.GetMappedName(fieldType);
this.hlslBuffersInfo.Add(new ReadOnlyBufferFieldInfo(fieldType, typeName, fieldName, (int)this.readOnlyBuffersCount));
}
else if (HlslKnownTypes.IsReadWriteBufferType(fieldType))
{
// Root parameter for a read write buffer
D3D12_DESCRIPTOR_RANGE1.Init(
out D3D12_DESCRIPTOR_RANGE1 d3D12DescriptorRange1,
D3D12_DESCRIPTOR_RANGE_TYPE_UAV,
1,
this.readWriteBuffersCount++);
this.d3D12DescriptorRanges1.Add(d3D12DescriptorRange1);
this.capturedMembers.Add(memberInfo);
string typeName = HlslKnownTypes.GetMappedName(fieldType);
this.hlslBuffersInfo.Add(new ReadWriteBufferFieldInfo(fieldType, typeName, fieldName, (int)this.readWriteBuffersCount));
}
else if (HlslKnownTypes.IsKnownScalarType(fieldType) || HlslKnownTypes.IsKnownVectorType(fieldType))
{
this.capturedMembers.Add(memberInfo);
string typeName = HlslKnownTypes.GetMappedName(fieldType);
this.fieldsInfo.Add(new CapturedFieldInfo(fieldType, typeName, fieldName));
}
else if (fieldType.IsDelegate() &&
memberInfo.GetValue(shader) is Delegate func &&
(func.Method.IsStatic || func.Method.DeclaringType!.IsStatelessDelegateContainer()) &&
(HlslKnownTypes.IsKnownScalarType(func.Method.ReturnType) || HlslKnownTypes.IsKnownVectorType(func.Method.ReturnType)) &&
fieldType.GenericTypeArguments.All(type => HlslKnownTypes.IsKnownScalarType(type) ||
HlslKnownTypes.IsKnownVectorType(type)))
{
// Captured static delegates with a return type
LoadStaticMethodSource(shader, fieldName, func.Method);
}
else throw new ArgumentException($"Invalid captured variable of type {fieldType} with name \"{memberInfo.Name}\"");
}
/// <summary>
/// Loads the entry method for the current shader being loaded
/// </summary>
/// <param name="shader">The boxed <typeparamref name="T"/> instance to use to build the shader</param>
private void LoadMethodSource(object shader)
{
// Decompile the shader method
MethodInfo methodInfo = typeof(T).GetMethod(nameof(IComputeShader.Execute))!;
MethodDecompiler.Instance.GetSyntaxTree(methodInfo, MethodType.Execute, out MethodDeclarationSyntax root, out SemanticModel semanticModel);
// Rewrite the shader method (eg. to fix the type declarations)
ShaderSyntaxRewriter syntaxRewriter = new ShaderSyntaxRewriter(semanticModel, typeof(T));
root = (MethodDeclarationSyntax)syntaxRewriter.Visit(root);
// Extract the implicit local functions
var locals = root.DescendantNodes().OfType<LocalFunctionStatementSyntax>().ToArray();
root = root.RemoveNodes(locals, SyntaxRemoveOptions.KeepNoTrivia)!;
foreach (var local in locals)
{
string alignedLocal = local.ToFullString().RemoveLeftPadding().Trim(' ', '\r', '\n');
alignedLocal = Regex.Replace(alignedLocal, @"(?<=\W)(\d+)[fFdD]", m => m.Groups[1].Value);
alignedLocal = HlslKnownKeywords.GetMappedText(alignedLocal);
this.localFunctionsInfo.Add(new LocalFunctionInfo(alignedLocal));
}
// Register the captured static members
foreach (var member in syntaxRewriter.StaticMembers)
{
LoadFieldInfo(shader, member.Value, member.Key);
}
// Register the captured static methods
foreach (var method in syntaxRewriter.StaticMethods)
{
LoadStaticMethodSource(shader, method.Key, method.Value);
}
// Get the thread ids identifier name and shader method body
ThreadsIdsVariableName = root.ParameterList.Parameters.First().Identifier.Text;
MethodBody = root.Body!.ToFullString();
// Additional preprocessing
MethodBody = Regex.Replace(MethodBody, @"(?<=\W)(\d+)[fFdD]", m => m.Groups[1].Value);
MethodBody = MethodBody.TrimEnd('\n', '\r', ' ');
MethodBody = HlslKnownKeywords.GetMappedText(MethodBody);
}
/// <summary>
/// Loads additional static methods used by the shader
/// </summary>
/// <param name="shader">The boxed <typeparamref name="T"/> instance to use to build the shader</param>
/// <param name="name">The HLSL name of the new method to load</param>
/// <param name="methodInfo">The <see cref="MethodInfo"/> instance for the method to load</param>
private void LoadStaticMethodSource(object shader, string name, MethodInfo methodInfo)
{
// Decompile the target method
MethodDecompiler.Instance.GetSyntaxTree(methodInfo, MethodType.Static, out MethodDeclarationSyntax root, out SemanticModel semanticModel);
// Rewrite the method
ShaderSyntaxRewriter syntaxRewriter = new ShaderSyntaxRewriter(semanticModel, methodInfo.DeclaringType!);
root = (MethodDeclarationSyntax)syntaxRewriter.Visit(root);
// Register the captured static members
foreach (var member in syntaxRewriter.StaticMembers)
{
LoadFieldInfo(shader, member.Value, member.Key);
}
// Register the captured static methods
foreach (var method in syntaxRewriter.StaticMethods)
{
LoadStaticMethodSource(shader, method.Key, method.Value);
}
// Get the function parameters
IReadOnlyList<ParameterInfo> parameters = (
from parameter in root.ParameterList.Parameters.Select((p, i) => (Node: p, Index: i))
let modifiers = parameter.Node.Modifiers
let type = parameter.Node.Type!.ToFullString()
let parameterName = parameter.Node.Identifier.ToFullString()
let last = parameter.Index == root.ParameterList.Parameters.Count - 1
select new ParameterInfo(modifiers, type, parameterName, last)).ToArray();
// Get the function body
string body = root.Body!.ToFullString();
body = Regex.Replace(body, @"(?<=\W)(\d+)[fFdD]", m => m.Groups[1].Value);
body = body.TrimEnd('\n', '\r', ' ');
body = HlslKnownKeywords.GetMappedText(body);
// Get the final function info instance
FunctionInfo functionInfo = new FunctionInfo(
methodInfo.ReturnType,
$"{methodInfo.DeclaringType!.FullName}{Type.Delimiter}{methodInfo.Name}",
string.Join(", ", methodInfo.GetParameters().Select(p => $"{p.ParameterType.ToFriendlyString()} {p.Name}")),
root.ReturnType.ToString(),
name,
parameters,
body);
this.functionsInfo.Add(functionInfo);
}
}
}
+70 -37
ファイルの表示
@@ -2,12 +2,14 @@
using System.Buffers;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using ComputeSharp.Graphics.Buffers.Abstract;
using ComputeSharp.Graphics.Buffers;
using ComputeSharp.Shaders.Mappings;
using ComputeSharp.Shaders.Translation.Models;
using TerraFX.Interop;
namespace ComputeSharp.Shaders.Translation
{
@@ -15,46 +17,50 @@ namespace ComputeSharp.Shaders.Translation
internal sealed partial class ShaderLoader<T>
{
/// <summary>
/// The number of captured graphics resources (buffers)
/// A <see langword="delegate"/> that loads all the captured members from a shader instance.
/// </summary>
private int _ResourcesCount;
/// <param name="shader">The shader instance to load the data from.</param>
/// <param name="r0">A reference to the buffer with all the captured <see cref="D3D12_GPU_DESCRIPTOR_HANDLE"/> instances.</param>
/// <param name="r1">A reference to the buffer to use to store all the captured value types.</param>
private delegate void DispatchDataLoader(in T shader, ref D3D12_GPU_DESCRIPTOR_HANDLE r0, ref byte r1);
/// <summary>
/// The size in bytes of the buffer with the captured variables
/// The number of captured graphics resources (buffers).
/// </summary>
private int _VariablesByteSize = 3 * sizeof(int); // X, Y and Z threads count
// The cached loader method
private DispatchDataLoader? _DispatchDataLoader;
private int totalResourceCount;
/// <summary>
/// The <see cref="List{T}"/> of <see cref="ReadableMember"/> instances mapping the captured variables in the current shader
/// The size in bytes of the buffer with the captured variables.
/// </summary>
private readonly List<ReadableMember> _CapturedMembers = new List<ReadableMember>();
/// <remarks>Initially set to 3 <see cref="int"/> values for X, Y and Z threads counts.</remarks>
private int totalVariablesByteSize = 3 * sizeof(int);
/// <summary>
/// A <see langword="delegate"/> that loads all the captured members from a shader instance
/// The cached <see cref="DispatchDataLoader"/> instance to load dispatch data before execution.
/// </summary>
/// <param name="shader">The shader instance to load the data from</param>
/// <param name="r0">A reference to the buffer with all the captured <see cref="GraphicsResource"/> instances</param>
/// <param name="r1">A reference to the buffer to use to store all the captured value types</param>
private delegate void DispatchDataLoader(in T shader, ref GraphicsResource r0, ref byte r1);
private DispatchDataLoader? dispatchDataLoader;
/// <summary>
/// Gets a new <see cref="DispatchData"/> instance with all the captured data for the current shader instance
/// The <see cref="List{T}"/> of <see cref="ReadableMember"/> instances mapping the captured variables in the current shader.
/// </summary>
/// <param name="shader">The input <typeparamref name="T"/> instance representing the compute shader to run</param>
/// <param name="x">The number of iterations to run on the X axis</param>
/// <param name="y">The number of iterations to run on the Y axis</param>
/// <param name="z">The number of iterations to run on the Z axis</param>
private readonly List<ReadableMember> capturedMembers = new();
/// <summary>
/// Gets a new <see cref="DispatchData"/> instance with all the captured data for the current shader instance.
/// </summary>
/// <param name="shader">The input <typeparamref name="T"/> instance representing the compute shader to run.</param>
/// <param name="x">The number of iterations to run on the X axis.</param>
/// <param name="y">The number of iterations to run on the Y axis.</param>
/// <param name="z">The number of iterations to run on the Z axis.</param>
[Pure]
public DispatchData GetDispatchData(in T shader, int x, int y, int z)
{
// Resources and variables buffers
GraphicsResource[] resources = ArrayPool<GraphicsResource>.Shared.Rent(_ResourcesCount);
byte[] variables = ArrayPool<byte>.Shared.Rent(_VariablesByteSize);
ref GraphicsResource r0 = ref resources[0];
ref byte r1 = ref variables[0];
D3D12_GPU_DESCRIPTOR_HANDLE[] resources = ArrayPool<D3D12_GPU_DESCRIPTOR_HANDLE>.Shared.Rent(this.totalResourceCount);
byte[] variables = ArrayPool<byte>.Shared.Rent(this.totalVariablesByteSize);
ref D3D12_GPU_DESCRIPTOR_HANDLE r0 = ref MemoryMarshal.GetArrayDataReference(resources);
ref byte r1 = ref MemoryMarshal.GetArrayDataReference(variables);
// Set the x, y and z counters
Unsafe.As<byte, int>(ref r1) = x;
@@ -62,42 +68,69 @@ namespace ComputeSharp.Shaders.Translation
Unsafe.Add(ref Unsafe.As<byte, int>(ref r1), 2) = z;
// Invoke the dynamic method to extract the captured data
_DispatchDataLoader!(shader, ref r0, ref r1);
this.dispatchDataLoader!(shader, ref r0, ref r1);
return new DispatchData(resources, _ResourcesCount, variables, _VariablesByteSize);
return new DispatchData(resources, this.totalResourceCount, variables, this.totalVariablesByteSize);
}
/// <summary>
/// Builds a new <see cref="DispatchDataLoader"/> instance that loads the dispatch data for the current shader type
/// Builds a new <see cref="DispatchDataLoader"/> instance that loads the dispatch data for the current shader type.
/// </summary>
private void BuildDispatchDataLoader()
{
_DispatchDataLoader = DynamicMethod<DispatchDataLoader>.New(il =>
this.dispatchDataLoader = DynamicMethod<DispatchDataLoader>.New(il =>
{
foreach (ReadableMember member in _CapturedMembers)
foreach (ReadableMember member in this.capturedMembers)
{
if (HlslKnownTypes.IsKnownBufferType(member.MemberType))
{
// Load the offset address into the resource buffers
il.Emit(OpCodes.Ldarg_1);
if (_ResourcesCount > 0) il.EmitAddOffset<GraphicsResource>(_ResourcesCount);
_ResourcesCount++;
if (totalResourceCount > 0)
{
il.EmitAddOffset<D3D12_GPU_DESCRIPTOR_HANDLE>(this.totalResourceCount);
}
il.Emit(OpCodes.Ldarg_0);
il.EmitReadMember(member);
// Access Buffer<T>.D3D12GpuDescriptorHandle
FieldInfo gpuDescriptorInfo = member.MemberType.GetField(
nameof(Buffer<byte>.D3D12GpuDescriptorHandle),
BindingFlags.NonPublic | BindingFlags.Instance)!;
il.EmitReadMember(gpuDescriptorInfo);
il.EmitStoreToAddress(member.MemberType);
this.totalResourceCount++;
}
else if (HlslKnownTypes.IsKnownScalarType(member.MemberType) || HlslKnownTypes.IsKnownVectorType(member.MemberType))
else if (HlslKnownTypes.IsKnownScalarType(member.MemberType) ||
HlslKnownTypes.IsKnownVectorType(member.MemberType))
{
// Calculate the right offset with 16-bytes padding (HLSL constant buffer)
int size = member.MemberType == typeof(bool) ? sizeof(uint) : Marshal.SizeOf(member.MemberType); // bool is 4 bytes in HLSL
if (_VariablesByteSize % 16 > 16 - size) _VariablesByteSize += 16 - _VariablesByteSize % 16;
int size = member.MemberType == typeof(bool)
? sizeof(uint)
: Marshal.SizeOf(member.MemberType); // bool is 4 bytes in HLSL
if (this.totalVariablesByteSize % 16 > 16 - size)
{
this.totalVariablesByteSize += 16 - this.totalVariablesByteSize % 16;
}
// Load the target address into the variables buffer
il.Emit(OpCodes.Ldarg_2);
il.EmitAddOffset(_VariablesByteSize);
_VariablesByteSize += size;
il.EmitAddOffset(totalVariablesByteSize);
this.totalVariablesByteSize += size;
}
else throw new InvalidOperationException($"Invalid captured member of type {member.MemberType}");
// Load the reference to the input delegate if the member is not static
if (!member.IsStatic) il.Emit(OpCodes.Ldarg_0);
if (!member.IsStatic)
{
il.Emit(OpCodes.Ldarg_0);
}
// Read the current member and store it to the target address
il.EmitReadMember(member);
+96 -51
ファイルの表示
@@ -3,6 +3,7 @@ using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
using ComputeSharp.Graphics.Extensions;
using ComputeSharp.Shaders.Mappings;
@@ -13,7 +14,8 @@ using ComputeSharp.Shaders.Translation.Enums;
using ComputeSharp.Shaders.Translation.Models;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Vortice.Direct3D12;
using TerraFX.Interop;
using static TerraFX.Interop.D3D12_DESCRIPTOR_RANGE_TYPE;
using ParameterInfo = ComputeSharp.Shaders.Renderer.Models.Functions.ParameterInfo;
#pragma warning disable CS8618 // Non-nullable field is uninitialized
@@ -21,81 +23,96 @@ using ParameterInfo = ComputeSharp.Shaders.Renderer.Models.Functions.ParameterIn
namespace ComputeSharp.Shaders.Translation
{
/// <summary>
/// A <see langword="class"/> responsible for loading and processing shaders of a given type
/// A <see langword="class"/> responsible for loading and processing shaders of a given type.
/// </summary>
/// <typeparam name="T">The type of compute shader currently in use</typeparam>
/// <typeparam name="T">The type of compute shader currently in use.</typeparam>
internal sealed partial class ShaderLoader<T>
where T : struct, IComputeShader
{
/// <summary>
/// Creates a new <see cref="ShaderLoader{T}"/> instance
/// The number of constant buffers to define in the shader.
/// </summary>
private ShaderLoader() { }
private uint constantBuffersCount;
/// <summary>
/// The number of constant buffers to define in the shader
/// The number of readonly buffers to define in the shader.
/// </summary>
private int _ConstantBuffersCount;
private uint readOnlyBuffersCount;
/// <summary>
/// The number of readonly buffers to define in the shader
/// The number of read write buffers to define in the shader.
/// </summary>
private int _ReadOnlyBuffersCount;
private uint readWriteBuffersCount;
/// <summary>
/// The number of read write buffers to define in the shader
/// The <see cref="List{T}"/> of <see cref="D3D12_DESCRIPTOR_RANGE1"/> items that are required to load the captured values.
/// </summary>
private int _ReadWriteBuffersCount;
private readonly List<D3D12_DESCRIPTOR_RANGE1> d3D12DescriptorRanges1 = new();
/// <summary>
/// The <see cref="List{T}"/> of <see cref="DescriptorRange1"/> items that are required to load the captured values
/// The <see cref="List{T}"/> with the <see cref="HlslBufferInfo"/> items for the shader fields.
/// </summary>
private readonly List<DescriptorRange1> DescriptorRanges = new List<DescriptorRange1>();
private RootParameter1[]? _RootParameters;
private readonly List<HlslBufferInfo> hlslBuffersInfo = new();
/// <summary>
/// Gets the <see cref="RootParameter1"/> array for the current shader
/// The <see cref="List{T}"/> with the <see cref="CapturedFieldInfo"/> items for the shader fields.
/// </summary>
public RootParameter1[] RootParameters => _RootParameters ??= DescriptorRanges.Select(range => new RootParameter1(new RootDescriptorTable1(range), ShaderVisibility.All)).ToArray();
private readonly List<HlslBufferInfo> _BuffersList = new List<HlslBufferInfo>();
private readonly List<CapturedFieldInfo> fieldsInfo = new();
/// <summary>
/// Gets the collection of <see cref="HlslBufferInfo"/> items for the shader fields
/// The <see cref="List{T}"/> with the <see cref="FunctionInfo"/> items for the shader functions.
/// </summary>
public IReadOnlyList<HlslBufferInfo> BuffersList => _BuffersList;
private readonly List<CapturedFieldInfo> _FieldsList = new List<CapturedFieldInfo>();
private readonly List<FunctionInfo> functionsInfo = new();
/// <summary>
/// Gets the collection of <see cref="CapturedFieldInfo"/> items for the shader fields
/// The <see cref="List{T}"/> with the <see cref="FunctionInfo"/> items for the shader local functions.
/// </summary>
public IReadOnlyList<CapturedFieldInfo> FieldsList => _FieldsList;
private readonly List<LocalFunctionInfo> localFunctionsInfo = new();
/// <summary>
/// Gets the name of the <see cref="ThreadIds"/> variable used as input for the shader method
/// Creates a new <see cref="ShaderLoader{T}"/> instance.
/// </summary>
private ShaderLoader()
{
}
/// <summary>
/// Gets a <see cref="Span{T}"/> with the loaded <see cref="D3D12_DESCRIPTOR_RANGE1"/> items for the shader.
/// </summary>
public ReadOnlySpan<D3D12_DESCRIPTOR_RANGE1> D3D12DescriptorRanges1
{
get => CollectionsMarshal.AsSpan(this.d3D12DescriptorRanges1);
}
/// <summary>
/// Gets the name of the <see cref="ThreadIds"/> variable used as input for the shader method.
/// </summary>
public string ThreadsIdsVariableName { get; private set; }
/// <summary>
/// Gets the generated source code for the method in the current shader
/// Gets the generated source code for the method in the current shader.
/// </summary>
public string MethodBody { get; private set; }
private readonly List<FunctionInfo> _FunctionsList = new List<FunctionInfo>();
/// <summary>
/// Gets the collection of <see cref="HlslBufferInfo"/> items for the shader fields.
/// </summary>
public IReadOnlyList<HlslBufferInfo> HslsBuffersInfo => this.hlslBuffersInfo;
/// <summary>
/// Gets the collection of <see cref="FunctionInfo"/> items for the shader
/// Gets the collection of <see cref="CapturedFieldInfo"/> items for the shader fields.
/// </summary>
public IReadOnlyList<FunctionInfo> FunctionsList => _FunctionsList;
private readonly List<LocalFunctionInfo> _LocalFunctionsList = new List<LocalFunctionInfo>();
public IReadOnlyList<CapturedFieldInfo> FieldsInfo => this.fieldsInfo;
/// <summary>
/// Gets the collection of <see cref="LocalFunctionInfo"/> items for the shader
/// Gets the collection of <see cref="FunctionInfo"/> items for the shader.
/// </summary>
public IReadOnlyList<LocalFunctionInfo> LocalFunctionsList => _LocalFunctionsList;
public IReadOnlyList<FunctionInfo> FunctionsInfo => this.functionsInfo;
/// <summary>
/// Gets the collection of <see cref="LocalFunctionInfo"/> items for the shader.
/// </summary>
public IReadOnlyList<LocalFunctionInfo> LocalFunctionsInfo => this.localFunctionsInfo;
/// <summary>
/// Loads and processes an input<typeparamref name="T"/> shadeer
@@ -107,9 +124,9 @@ namespace ComputeSharp.Shaders.Translation
{
ShaderLoader<T> @this = new ShaderLoader<T>();
/* Reading members through reflection requires an object parameter,
* so here we're just boxing the input shader once to avoid allocating
* it multiple times in the managed heap while processing the shader. */
// Reading members through reflection requires an object parameter,
// so here we're just boxing the input shader once to avoid allocating
// it multiple times in the managed heap while processing the shader.
object box = shader;
@this.LoadFieldsInfo(box);
@@ -134,7 +151,13 @@ namespace ComputeSharp.Shaders.Translation
if (shaderFields.Count == 0) throw new InvalidOperationException("Empty shader body");
// Descriptor for the buffer for captured scalar/vector variables
DescriptorRanges.Add(new DescriptorRange1(DescriptorRangeType.ConstantBufferView, 1, _ConstantBuffersCount++));
D3D12_DESCRIPTOR_RANGE1.Init(
out D3D12_DESCRIPTOR_RANGE1 d3D12DescriptorRange1,
D3D12_DESCRIPTOR_RANGE_TYPE_CBV,
1,
this.constantBuffersCount++);
this.d3D12DescriptorRanges1.Add(d3D12DescriptorRange1);
// Inspect the captured fields
foreach (FieldInfo fieldInfo in shaderFields)
@@ -157,39 +180,61 @@ namespace ComputeSharp.Shaders.Translation
// Constant buffer
if (HlslKnownTypes.IsConstantBufferType(fieldType))
{
DescriptorRanges.Add(new DescriptorRange1(DescriptorRangeType.ConstantBufferView, 1, _ConstantBuffersCount));
D3D12_DESCRIPTOR_RANGE1.Init(
out D3D12_DESCRIPTOR_RANGE1 d3D12DescriptorRange1,
D3D12_DESCRIPTOR_RANGE_TYPE_CBV,
1,
this.constantBuffersCount++);
_CapturedMembers.Add(memberInfo);
this.d3D12DescriptorRanges1.Add(d3D12DescriptorRange1);
this.capturedMembers.Add(memberInfo);
string typeName = HlslKnownTypes.GetMappedName(fieldType.GenericTypeArguments[0]);
_BuffersList.Add(new ConstantBufferFieldInfo(fieldType, typeName, fieldName, _ConstantBuffersCount++));
this.hlslBuffersInfo.Add(new ConstantBufferFieldInfo(fieldType, typeName, fieldName, (int)this.constantBuffersCount));
}
else if (HlslKnownTypes.IsReadOnlyBufferType(fieldType))
{
// Root parameter for a readonly buffer
DescriptorRanges.Add(new DescriptorRange1(DescriptorRangeType.ShaderResourceView, 1, _ReadOnlyBuffersCount));
D3D12_DESCRIPTOR_RANGE1.Init(
out D3D12_DESCRIPTOR_RANGE1 d3D12DescriptorRange1,
D3D12_DESCRIPTOR_RANGE_TYPE_SRV,
1,
this.readOnlyBuffersCount++);
_CapturedMembers.Add(memberInfo);
this.d3D12DescriptorRanges1.Add(d3D12DescriptorRange1);
this.capturedMembers.Add(memberInfo);
string typeName = HlslKnownTypes.GetMappedName(fieldType);
_BuffersList.Add(new ReadOnlyBufferFieldInfo(fieldType, typeName, fieldName, _ReadOnlyBuffersCount++));
this.hlslBuffersInfo.Add(new ReadOnlyBufferFieldInfo(fieldType, typeName, fieldName, (int)this.readOnlyBuffersCount));
}
else if (HlslKnownTypes.IsReadWriteBufferType(fieldType))
{
// Root parameter for a read write buffer
DescriptorRanges.Add(new DescriptorRange1(DescriptorRangeType.UnorderedAccessView, 1, _ReadWriteBuffersCount));
D3D12_DESCRIPTOR_RANGE1.Init(
out D3D12_DESCRIPTOR_RANGE1 d3D12DescriptorRange1,
D3D12_DESCRIPTOR_RANGE_TYPE_UAV,
1,
this.readWriteBuffersCount++);
_CapturedMembers.Add(memberInfo);
this.d3D12DescriptorRanges1.Add(d3D12DescriptorRange1);
this.capturedMembers.Add(memberInfo);
string typeName = HlslKnownTypes.GetMappedName(fieldType);
_BuffersList.Add(new ReadWriteBufferFieldInfo(fieldType, typeName, fieldName, _ReadWriteBuffersCount++));
this.hlslBuffersInfo.Add(new ReadWriteBufferFieldInfo(fieldType, typeName, fieldName, (int)this.readWriteBuffersCount));
}
else if (HlslKnownTypes.IsKnownScalarType(fieldType) || HlslKnownTypes.IsKnownVectorType(fieldType))
{
_CapturedMembers.Add(memberInfo);
this.capturedMembers.Add(memberInfo);
string typeName = HlslKnownTypes.GetMappedName(fieldType);
_FieldsList.Add(new CapturedFieldInfo(fieldType, typeName, fieldName));
this.fieldsInfo.Add(new CapturedFieldInfo(fieldType, typeName, fieldName));
}
else if (fieldType.IsDelegate() &&
memberInfo.GetValue(shader) is Delegate func &&
@@ -227,7 +272,7 @@ namespace ComputeSharp.Shaders.Translation
alignedLocal = Regex.Replace(alignedLocal, @"(?<=\W)(\d+)[fFdD]", m => m.Groups[1].Value);
alignedLocal = HlslKnownKeywords.GetMappedText(alignedLocal);
_LocalFunctionsList.Add(new LocalFunctionInfo(alignedLocal));
this.localFunctionsInfo.Add(new LocalFunctionInfo(alignedLocal));
}
// Register the captured static members
@@ -304,7 +349,7 @@ namespace ComputeSharp.Shaders.Translation
parameters,
body);
_FunctionsList.Add(functionInfo);
this.functionsInfo.Add(functionInfo);
}
}
}
+3 -6
ファイルの表示
@@ -2,7 +2,7 @@
<package >
<metadata>
<id>ComputeSharp</id>
<version>1.4.1</version>
<version>2.0.0</version>
<title>ComputeSharp</title>
<authors>Sergio Pedri</authors>
<owners>Sergio Pedri</owners>
@@ -10,19 +10,16 @@
<projectUrl>https://github.com/Sergio0694/ComputeSharp</projectUrl>
<iconUrl>https://i.imgur.com/ntvmD6P.png</iconUrl>
<requireLicenseAcceptance>false</requireLicenseAcceptance>
<description>A .NET Standard 2.1 library to run C# code in parallel on the GPU through DX12 and dynamically generated HLSL compute shaders</description>
<description>A .NET 5 library to run C# code in parallel on the GPU through DX12 and dynamically generated HLSL compute shaders</description>
<releaseNotes>New interlocked intrinsics APIs, performance and memory optimizations</releaseNotes>
<copyright>Copyright (c) 2020 Sergio Pedri</copyright>
<tags>dotnet net netcore netstandard csharp library graphics shader hlsl compute gpu</tags>
<repository type="git" url="https://github.com/Sergio0694/ComputeSharp.git" branch="master" />
<dependencies>
<dependency id="Microsoft.Windows.SDK.Contracts" version="10.0.19041.1" />
<dependency id="Microsoft.Toolkit.HighPerformance" version="6.1.1" />
<dependency id="Vortice.Direct3D12" version="1.8.6" />
<dependency id="TerraFX.Interop.Windows" version="10.0.19041-beta1" />
<dependency id="ICSharpCode.Decompiler" version="5.0.2.5153" />
<dependency id="Microsoft.CodeAnalysis.CSharp" version="3.7.0" />
<dependency id="Stubble.Core" version="1.9.3" />
<dependency id="Vortice.Dxc" version="1.8.6" />
</dependencies>
</metadata>
</package>
+30 -30
ファイルの表示
@@ -4,17 +4,17 @@ using ComputeSharp.Shaders;
namespace ComputeSharp
{
/// <summary>
/// A <see langword="class"/> that contains extension methods for the <see cref="GraphicsDevice"/> type, used to run compute shaders
/// A <see langword="class"/> that contains extension methods for the <see cref="GraphicsDevice"/> type, used to run compute shaders.
/// </summary>
public static class GraphicsDeviceExtensions
public static class GraphicsDevice2Extensions
{
/// <summary>
/// Compiles and runs the input shader on a target <see cref="GraphicsDevice"/> instance, with the specified parameters
/// Compiles and runs the input shader on a target <see cref="GraphicsDevice"/> instance, with the specified parameters.
/// </summary>
/// <typeparam name="T">The type of compute shader to run</typeparam>
/// <param name="device">The <see cref="GraphicsDevice"/> to use to run the shader</param>
/// <param name="x">The number of iterations to run on the X axis</param>
/// <param name="shader">The input <typeparamref name="T"/> instance representing the compute shader to run</param>
/// <typeparam name="T">The type of compute shader to run.</typeparam>
/// <param name="device">The <see cref="GraphicsDevice"/> to use to run the shader.</param>
/// <param name="x">The number of iterations to run on the X axis.</param>
/// <param name="shader">The input <typeparamref name="T"/> instance representing the compute shader to run.</param>
public static void For<T>(this GraphicsDevice device, int x, in T shader)
where T : struct, IComputeShader
{
@@ -22,13 +22,13 @@ namespace ComputeSharp
}
/// <summary>
/// Compiles and runs the input shader on a target <see cref="GraphicsDevice"/> instance, with the specified parameters
/// Compiles and runs the input shader on a target <see cref="GraphicsDevice"/> instance, with the specified parameters.
/// </summary>
/// <typeparam name="T">The type of compute shader to run</typeparam>
/// <param name="device">The <see cref="GraphicsDevice"/> to use to run the shader</param>
/// <param name="x">The number of iterations to run on the X axis</param>
/// <param name="y">The number of iterations to run on the Y axis</param>
/// <param name="shader">The input <typeparamref name="T"/> instance representing the compute shader to run</param>
/// <typeparam name="T">The type of compute shader to run.</typeparam>
/// <param name="device">The <see cref="GraphicsDevice"/> to use to run the shader.</param>
/// <param name="x">The number of iterations to run on the X axis.</param>
/// <param name="y">The number of iterations to run on the Y axis.</param>
/// <param name="shader">The input <typeparamref name="T"/> instance representing the compute shader to run.</param>
public static void For<T>(this GraphicsDevice device, int x, int y, in T shader)
where T : struct, IComputeShader
{
@@ -36,14 +36,14 @@ namespace ComputeSharp
}
/// <summary>
/// Compiles and runs the input shader on a target <see cref="GraphicsDevice"/> instance, with the specified parameters
/// Compiles and runs the input shader on a target <see cref="GraphicsDevice"/> instance, with the specified parameters.
/// </summary>
/// <typeparam name="T">The type of compute shader to run</typeparam>
/// <param name="device">The <see cref="GraphicsDevice"/> to use to run the shader</param>
/// <param name="x">The number of iterations to run on the X axis</param>
/// <param name="y">The number of iterations to run on the Y axis</param>
/// <param name="z">The number of iterations to run on the Z axis</param>
/// <param name="shader">The input <typeparamref name="T"/> instance representing the compute shader to run</param>
/// <typeparam name="T">The type of compute shader to run.</typeparam>
/// <param name="device">The <see cref="GraphicsDevice"/> to use to run the shader.</param>
/// <param name="x">The number of iterations to run on the X axis.</param>
/// <param name="y">The number of iterations to run on the Y axis.</param>
/// <param name="z">The number of iterations to run on the Z axis.</param>
/// <param name="shader">The input <typeparamref name="T"/> instance representing the compute shader to run.</param>
public static void For<T>(this GraphicsDevice device, int x, int y, int z, in T shader)
where T : struct, IComputeShader
{
@@ -51,17 +51,17 @@ namespace ComputeSharp
}
/// <summary>
/// Compiles and runs the input shader on a target <see cref="GraphicsDevice"/> instance, with the specified parameters
/// Compiles and runs the input shader on a target <see cref="GraphicsDevice"/> instance, with the specified parameters.
/// </summary>
/// <typeparam name="T">The type of compute shader to run</typeparam>
/// <param name="device">The <see cref="GraphicsDevice"/> to use to run the shader</param>
/// <param name="x">The number of iterations to run on the X axis</param>
/// <param name="y">The number of iterations to run on the Y axis</param>
/// <param name="z">The number of iterations to run on the Z axis</param>
/// <param name="threadsX">The number of threads in each thread group for the X axis</param>
/// <param name="threadsY">The number of threads in each thread group for the Y axis</param>
/// <param name="threadsZ">The number of threads in each thread group for the Z axis</param>
/// <param name="shader">The input <typeparamref name="T"/> instance representing the compute shader to run</param>
/// <typeparam name="T">The type of compute shader to run.</typeparam>
/// <param name="device">The <see cref="GraphicsDevice"/> to use to run the shader.</param>
/// <param name="x">The number of iterations to run on the X axis.</param>
/// <param name="y">The number of iterations to run on the Y axis.</param>
/// <param name="z">The number of iterations to run on the Z axis.</param>
/// <param name="threadsX">The number of threads in each thread group for the X axis.</param>
/// <param name="threadsY">The number of threads in each thread group for the Y axis.</param>
/// <param name="threadsZ">The number of threads in each thread group for the Z axis.</param>
/// <param name="shader">The input <typeparamref name="T"/> instance representing the compute shader to run.</param>
public static void For<T>(
this GraphicsDevice device,
int x, int y, int z,
+10 -35
ファイルの表示
@@ -1,55 +1,30 @@
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
using ComputeSharp.Graphics;
using ComputeSharp.Graphics.Helpers;
using Vortice.Direct3D12;
using Vortice.DXGI;
namespace ComputeSharp
{
/// <summary>
/// A <see langword="class"/> that acts as an entry-point for all the library APIs, exposing the available GPU devices
/// A <see langword="class"/> that acts as an entry-point for all the library APIs, exposing the available GPU devices.
/// </summary>
public static class Gpu
{
/// <summary>
/// Initializes the <see cref="Devices"/> field and <see cref="IsSupported"/> property
/// The <see cref="Lazy{T}"/> instance used to produce the default device for <see cref="Default"/>.
/// </summary>
static Gpu()
{
Devices = DeviceHelper.QueryAllSupportedDevices();
IsSupported = Devices.Any();
if (IsSupported)
{
_Default = new GraphicsDevice(Devices[0].Device, Devices[0].Description);
}
}
private static readonly Lazy<GraphicsDevice> DefaultFactory = new(DeviceHelper.GetDefaultDevice);
/// <summary>
/// The loaded collection of supported devices and descriptions
/// Gets whether or not the <see cref="Gpu"/> APIs can be used on the
/// current machine (ie. if there is at least a supported GPU device).
/// </summary>
private static readonly IReadOnlyList<(ID3D12Device Device, AdapterDescription Description)> Devices;
private static readonly GraphicsDevice? _Default;
public static bool IsSupported => DeviceHelper.IsDefaultDeviceAvailable();
/// <summary>
/// Gets the default <see cref="GraphicsDevice"/> instance for the current machine
/// Gets the default <see cref="GraphicsDevice"/> instance for the current machine.
/// </summary>
public static GraphicsDevice Default => _Default ?? throw new NotSupportedException("There isn't a supported GPU device on the current machine");
/// <summary>
/// Gets whether or not the <see cref="Gpu"/> APIs can be used on the current machine (ie. if there is at least a supported GPU device)
/// </summary>
public static bool IsSupported { get; }
/// <summary>
/// Enumerates all the available <see cref="GraphicsDevice"/> objects on the current machine
/// </summary>
/// <returns>A sequence of supported <see cref="GraphicsDevice"/> objects that can be used to run compute shaders</returns>
[Pure]
public static IEnumerable<GraphicsDevice> EnumerateDevices() => Devices.Select(device => new GraphicsDevice(device.Device, device.Description));
/// <exception cref="NotSupportedException">Thrown when a default device is not available.</exception>
/// <remarks>Make sure to check <see cref="IsSupported"/> before accessing this property.</remarks>
public static GraphicsDevice Default => DefaultFactory.Value;
}
}
-30
ファイルの表示
@@ -1,30 +0,0 @@
using System;
using ComputeSharp.Graphics;
using ComputeSharp.Graphics.Helpers;
namespace ComputeSharp
{
/// <summary>
/// A <see langword="class"/> that acts as an entry-point for all the library APIs, exposing the available GPU devices.
/// </summary>
public static class Gpu2
{
/// <summary>
/// The <see cref="Lazy{T}"/> instance used to produce the default device for <see cref="Default"/>.
/// </summary>
private static readonly Lazy<GraphicsDevice2> DefaultFactory = new(DeviceHelper2.GetDefaultDevice);
/// <summary>
/// Gets whether or not the <see cref="Gpu"/> APIs can be used on the
/// current machine (ie. if there is at least a supported GPU device).
/// </summary>
public static bool IsSupported => DeviceHelper2.IsDefaultDeviceAvailable();
/// <summary>
/// Gets the default <see cref="GraphicsDevice2"/> instance for the current machine.
/// </summary>
/// <exception cref="NotSupportedException">Thrown when a default device is not available.</exception>
/// <remarks>Make sure to check <see cref="IsSupported"/> before accessing this property.</remarks>
public static GraphicsDevice2 Default => DefaultFactory.Value;
}
}