Merge pull request #22 from Sergio0694/feature_shader-caching

Aggregated buffer for captured variables
このコミットが含まれているのは:
Sergio Pedri authored and GitHub committed 2019-08-17 11:15:00 +02:00
コミット e1cb51fd12
14ファイル変更
+135 -209

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

+39 -34
ファイルの表示
@@ -1,9 +1,8 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Reflection;
using System.Numerics;
using System.Runtime.CompilerServices;
using ComputeSharp.Graphics.Buffers.Abstract;
namespace ComputeSharp.Graphics.Buffers.Extensions
@@ -14,45 +13,51 @@ namespace ComputeSharp.Graphics.Buffers.Extensions
internal static class GraphicsResourceExtensions
{
/// <summary>
/// The <see cref="Dictionary{TKey,TValue}"/> that maps types to the necessary data to create buffers, for quick lookup
/// </summary>
private static readonly Dictionary<Type, (ConstructorInfo Constructor, IList Array, MethodInfo Setter)> TypeMapping = new Dictionary<Type, (ConstructorInfo, IList, MethodInfo)>();
/// <summary>
/// Allocates a new constant buffer with the specified generic value
/// Allocates a new constant buffer with the specified generic values
/// </summary>
/// <param name="device">The <see cref="GraphicsDevice"/> instance to use to allocate the buffer</param>
/// <param name="data">The input <see cref="object"/> to copy to the allocated buffer</param>
/// <param name="data">The input <see cref="object"/> sequence to copy to the allocated buffer</param>
/// <returns>A constant <see cref="ConstantBuffer{T}"/> instance (as a <see cref="GraphicsResource"/>) with the input data</returns>
[Pure]
public static GraphicsResource AllocateConstantBufferFromReflectedSingleValue(this GraphicsDevice device, object data)
public static GraphicsResource AllocateConstantBufferFromReflectedValues(this GraphicsDevice device, IReadOnlyList<object> data)
{
Type dataType = data.GetType();
if (!TypeMapping.TryGetValue(dataType, out var info))
Span<Vector4> temporarySpan = stackalloc Vector4[data.Count];
ref byte r0 = ref Unsafe.As<Vector4, byte>(ref temporarySpan.GetPinnableReference());
int offset = 0;
// Local method to write a value in the temporary buffer
void WriteValue<T>(T value, ref byte target) where T : unmanaged
{
// Get the generic buffer constructor
Type bufferType = typeof(ConstantBuffer<>).MakeGenericType(dataType);
info.Constructor = bufferType.GetConstructors(BindingFlags.Instance | BindingFlags.NonPublic).First();
// Create the reusable array
Type arrayType = dataType.MakeArrayType();
ConstructorInfo[] arrayConstructors = arrayType.GetConstructors(BindingFlags.CreateInstance
| BindingFlags.Public
| BindingFlags.Instance
| BindingFlags.OptionalParamBinding);
info.Array = (IList)arrayConstructors[0].Invoke(new object[] { 1 });
// Set the input data to the new buffer
info.Setter = bufferType.GetMethod(nameof(HlslBuffer<byte>.SetData), new[] { arrayType });
// Cache for later reuse
TypeMapping.Add(dataType, info);
int size = Unsafe.SizeOf<T>();
if (offset % 16 > 16 - size) offset += 16 - offset % 16;
Unsafe.As<byte, T>(ref Unsafe.Add(ref target, offset)) = value;
offset += size;
}
// Create the buffer and set the content
GraphicsResource buffer = (GraphicsResource)info.Constructor.Invoke(new object[] { device, 1 });
info.Array[0] = data;
info.Setter.Invoke(buffer, new object[] { info.Array });
// Iterate on the input values and write them with the proper padding
for (int j = 0; j < data.Count; j++)
{
switch (data[j])
{
case bool b:
uint ub = default;
Unsafe.As<uint, bool>(ref ub) = b;
WriteValue(ub, ref r0);
break;
case int i: WriteValue(i, ref r0); break;
case uint u: WriteValue(u, ref r0); break;
case float f: WriteValue(f, ref r0); break;
case double d: WriteValue(d, ref r0); break;
case Vector2 v2: WriteValue(v2, ref r0); break;
case Vector3 v3: WriteValue(v3, ref r0); break;
case Vector4 v4: WriteValue(v4, ref r0); break;
default: throw new InvalidOperationException($"Invalid item of type {data[j].GetType()}");
}
}
// Create the array to return
ConstantBuffer<Vector4> buffer = new ConstantBuffer<Vector4>(device, data.Count);
buffer.SetData(temporarySpan);
return buffer;
}
+1 -22
ファイルの表示
@@ -59,28 +59,7 @@ namespace ComputeSharp.Shaders.Mappings
["System.Numerics.Vector4.Transform"] = "mul",
["System.Numerics.Vector4.Normalize"] = "normalize",
["System.Numerics.Vector4.Zero"] = "(float4)0",
["System.Numerics.Vector4.One"] = "float4(1.0f, 1.0f, 1.0f, 1.0f)",
// Matrix4x4
["System.Numerics.Matrix4x4.Multiply"] = "mul",
["System.Numerics.Matrix4x4.Transpose"] = "transpose",
["System.Numerics.Matrix4x4.Translation"] = "[3].xyz",
["System.Numerics.Matrix4x4.M11"] = "[0][0]",
["System.Numerics.Matrix4x4.M12"] = "[0][1]",
["System.Numerics.Matrix4x4.M13"] = "[0][2]",
["System.Numerics.Matrix4x4.M14"] = "[0][3]",
["System.Numerics.Matrix4x4.M21"] = "[1][0]",
["System.Numerics.Matrix4x4.M22"] = "[1][1]",
["System.Numerics.Matrix4x4.M23"] = "[1][2]",
["System.Numerics.Matrix4x4.M24"] = "[1][3]",
["System.Numerics.Matrix4x4.M31"] = "[2][0]",
["System.Numerics.Matrix4x4.M32"] = "[2][1]",
["System.Numerics.Matrix4x4.M33"] = "[2][2]",
["System.Numerics.Matrix4x4.M34"] = "[2][3]",
["System.Numerics.Matrix4x4.M41"] = "[3][0]",
["System.Numerics.Matrix4x4.M42"] = "[3][1]",
["System.Numerics.Matrix4x4.M43"] = "[3][2]",
["System.Numerics.Matrix4x4.M44"] = "[3][3]"
["System.Numerics.Vector4.One"] = "float4(1.0f, 1.0f, 1.0f, 1.0f)"
};
/// <summary>
+1 -3
ファイルの表示
@@ -25,7 +25,6 @@ namespace ComputeSharp.Shaders.Mappings
[typeof(Vector2).FullName] = "float2",
[typeof(Vector3).FullName] = "float3",
[typeof(Vector4).FullName] = "float4",
[typeof(Matrix4x4).FullName] = "float4x4",
[typeof(ThreadIds).FullName] = "uint3",
[typeof(ReadOnlyBuffer<>).FullName] = "StructuredBuffer",
[typeof(ReadWriteBuffer<>).FullName] = "RWStructuredBuffer"
@@ -51,8 +50,7 @@ namespace ComputeSharp.Shaders.Mappings
[Pure]
public static bool IsKnownVectorType(Type type) => type == typeof(Vector2) ||
type == typeof(Vector3) ||
type == typeof(Vector4) ||
type == typeof(Matrix4x4);
type == typeof(Vector4);
/// <summary>
/// Checks whether or not the input type is a <see cref="ConstantBuffer{T}"/> value
+1 -1
ファイルの表示
@@ -3,7 +3,7 @@
/// <summary>
/// A <see langword="class"/> that contains info on a shader buffer field
/// </summary>
internal abstract class HlslBufferInfo : FieldInfo
internal abstract class HlslBufferInfo : CapturedFieldInfo
{
/// <summary>
/// Gets or sets the index of the current buffer, relative to its own type
@@ -1,9 +1,9 @@
namespace ComputeSharp.Shaders.Renderer.Models.Fields.Abstract
namespace ComputeSharp.Shaders.Renderer.Models.Fields
{
/// <summary>
/// A <see langword="class"/> that contains info on a shader field
/// </summary>
internal abstract class FieldInfo
internal class CapturedFieldInfo
{
/// <summary>
/// Gets or sets the type of the current field
@@ -16,11 +16,11 @@
public string FieldName { get; set; }
/// <summary>
/// Creates a new <see cref="FieldInfo"/> instance with the specified parameters
/// Creates a new <see cref="CapturedFieldInfo"/> instance with the specified parameters
/// </summary>
/// <param name="fieldType">The type of the current field</param>
/// <param name="fieldName">The name of the current field</param>
protected FieldInfo(string fieldType, string fieldName)
public CapturedFieldInfo(string fieldType, string fieldName)
{
FieldType = fieldType;
FieldName = fieldName;
+2 -11
ファイルの表示
@@ -8,25 +8,16 @@ namespace ComputeSharp.Shaders.Renderer.Models.Fields
internal sealed class ConstantBufferFieldInfo : HlslBufferInfo
{
/// <summary>
/// Gets whether or not the current <see cref="FieldInfo"/> instance represents a constant buffer (always <see langword="true"/>)
/// Gets whether or not the current <see cref="CapturedFieldInfo"/> instance represents a constant buffer (always <see langword="true"/>)
/// </summary>
public bool IsConstantBuffer { get; } = true;
/// <summary>
/// Gets whether or not this constant buffer actually contains a single, explicit variable
/// </summary>
public bool IsSingleValue { get; }
/// <summary>
/// Creates a new <see cref="ConstantBufferFieldInfo"/> instance with the specified parameters
/// </summary>
/// <param name="fieldType">The type of the current field</param>
/// <param name="fieldName">The name of the current field</param>
/// <param name="bufferIndex">The index of the current constant buffer field</param>
/// <param name="singleValue">Whether or not this constant buffer actually contains a single, explicit variable</param>
public ConstantBufferFieldInfo(string fieldType, string fieldName, int bufferIndex, bool singleValue) : base(fieldType, fieldName, bufferIndex)
{
IsSingleValue = singleValue;
}
public ConstantBufferFieldInfo(string fieldType, string fieldName, int bufferIndex) : base(fieldType, fieldName, bufferIndex) { }
}
}
+1 -1
ファイルの表示
@@ -8,7 +8,7 @@ namespace ComputeSharp.Shaders.Renderer.Models.Fields
internal sealed class ReadOnlyBufferFieldInfo : HlslBufferInfo
{
/// <summary>
/// Gets whether or not the current <see cref="FieldInfo"/> instance represents a readonly buffer (always <see langword="true"/>)
/// Gets whether or not the current <see cref="CapturedFieldInfo"/> instance represents a readonly buffer (always <see langword="true"/>)
/// </summary>
public bool IsReadOnlyBuffer { get; } = true;
+1 -1
ファイルの表示
@@ -8,7 +8,7 @@ namespace ComputeSharp.Shaders.Renderer.Models.Fields
internal sealed class ReadWriteBufferFieldInfo : HlslBufferInfo
{
/// <summary>
/// Gets whether or not the current <see cref="FieldInfo"/> instance represents a read write buffer (always <see langword="true"/>)
/// Gets whether or not the current <see cref="CapturedFieldInfo"/> instance represents a read write buffer (always <see langword="true"/>)
/// </summary>
public bool IsReadWriteBuffer { get; } = true;
-31
ファイルの表示
@@ -1,31 +0,0 @@
using ComputeSharp.Shaders.Renderer.Models.Fields.Abstract;
namespace ComputeSharp.Shaders.Renderer.Models.Fields
{
/// <summary>
/// A <see langword="class"/> that contains info on a static scalar field
/// </summary>
internal sealed class StaticScalarFieldInfo : FieldInfo
{
/// <summary>
/// Gets whether or not the current <see cref="FieldInfo"/> instance represents a static scalar value (always <see langword="true"/>)
/// </summary>
public bool IsStaticScalarField { get; } = true;
/// <summary>
/// Gets or sets the value to set for the current field
/// </summary>
public object FieldValue { get; set; }
/// <summary>
/// Creates a new <see cref="StaticScalarFieldInfo"/> instance with the specified parameters
/// </summary>
/// <param name="fieldType">The type of the current field</param>
/// <param name="fieldName">The name of the current field</param>
/// <param name="fieldValue">The static value to assign to the current field</param>
public StaticScalarFieldInfo(string fieldType, string fieldName, object fieldValue) : base(fieldType, fieldName)
{
FieldValue = fieldValue;
}
}
}
+5 -14
ファイルの表示
@@ -1,4 +1,5 @@
using System.Collections.Generic;
using ComputeSharp.Shaders.Renderer.Models.Fields;
using ComputeSharp.Shaders.Renderer.Models.Fields.Abstract;
#pragma warning disable CS8618 // Non-nullable field is uninitialized
@@ -11,24 +12,14 @@ namespace ComputeSharp.Shaders.Renderer.Models
internal sealed class ShaderInfo
{
/// <summary>
/// Gets the list of fields being present in the current shader
/// Gets the list of captured buffers being present in the current shader
/// </summary>
public IReadOnlyList<FieldInfo> FieldsList { get; set; }
public IReadOnlyList<HlslBufferInfo> BuffersList { get; set; }
/// <summary>
/// Gets or sets the total number of threads to run on the X axis
/// Gets the list of captured variables being present in the current shader
/// </summary>
public int ThreadsX { get; set; }
/// <summary>
/// Gets or sets the total number of threads to run on the Y axis
/// </summary>
public int ThreadsY { get; set; }
/// <summary>
/// Gets or sets the total number of threads to run on the Z axis
/// </summary>
public int ThreadsZ { get; set; }
public IReadOnlyList<CapturedFieldInfo> FieldsList { get; set; }
/// <summary>
/// Gets or sets the number of threads in the X group
+22 -13
ファイルの表示
@@ -1,32 +1,41 @@
{{#FieldsList}}
{{!Static scalar}}
{{#IsStaticScalarField}}
static {{&FieldType}} {{FieldName}} = {{FieldValue}};
{{/IsStaticScalarField}}
{{!Constant buffer}}
{{!Captured variables buffer}}
cbuffer __Variables__Buffer : register(b0)
{
uint __x__;
uint __y__;
uint __z__;
{{#FieldsList}}
{{&FieldType}} {{FieldName}};
{{/FieldsList}}
}
{{#BuffersList}}
{{#IsConstantBuffer}}
{{!Constant buffer}}
cbuffer {{FieldName}}Buffer : register(b{{BufferIndex}})
{
{{&FieldType}} {{FieldName}}{{^IsSingleValue}}[2]{{/IsSingleValue}};
{{&FieldType}} {{FieldName}}[2];
}
{{/IsConstantBuffer}}
{{!Readonly buffer}}
{{#IsReadOnlyBuffer}}
{{!Readonly buffer}}
{{&FieldType}} {{FieldName}} : register(t{{BufferIndex}});
{{/IsReadOnlyBuffer}}
{{!Read write buffer}}
{{#IsReadWriteBuffer}}
{{!Read write buffer}}
{{&FieldType}} {{FieldName}} : SV_DispatchThreadId : register(u{{BufferIndex}});
{{/IsReadWriteBuffer}}
{{/BuffersList}}
{{/FieldsList}}
{{!Shader entry point}}
[Shader("compute")]
[NumThreads({{NumThreadsX}}, {{NumThreadsY}}, {{NumThreadsZ}})]
void CSMain(uint3 {{ThreadsIdsVariableName}} : SV_DispatchThreadId)
{
if ({{ThreadsIdsVariableName}}.x < {{ThreadsX}} &&
{{ThreadsIdsVariableName}}.y < {{ThreadsY}} &&
{{ThreadsIdsVariableName}}.z < {{ThreadsZ}})
if ({{ThreadsIdsVariableName}}.x < __x__ &&
{{ThreadsIdsVariableName}}.y < __y__ &&
{{ThreadsIdsVariableName}}.z < __z__)
{{&ShaderBody}}
}
+7 -18
ファイルの表示
@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
using System.Linq;
using ComputeSharp.Graphics;
using ComputeSharp.Graphics.Buffers.Abstract;
using ComputeSharp.Graphics.Buffers.Extensions;
@@ -65,10 +66,8 @@ namespace ComputeSharp.Shaders
// Render the loaded shader
ShaderInfo shaderInfo = new ShaderInfo
{
FieldsList = shaderLoader.FieldsInfo,
ThreadsX = x,
ThreadsY = y,
ThreadsZ = z,
BuffersList = shaderLoader.BuffersList,
FieldsList = shaderLoader.FieldsList,
NumThreadsX = threadsX,
NumThreadsY = threadsY,
NumThreadsZ = threadsZ,
@@ -95,24 +94,14 @@ namespace ComputeSharp.Shaders
commandList.SetComputeRootDescriptorTable(buffer.Index, buffer.Resource);
}
// Load the captured variables
List<GraphicsResource> buffers = new List<GraphicsResource>();
foreach (var variable in shaderLoader.CapturedConstantBufferValues)
{
GraphicsResource resource = device.AllocateConstantBufferFromReflectedSingleValue(variable.Value);
commandList.SetComputeRootDescriptorTable(variable.Index, resource);
buffers.Add(resource);
}
// Initialize the loop targets
IReadOnlyList<object> variables = new object[] { (uint)x, (uint)y, (uint)z }.Concat(shaderLoader.FieldValuesList).ToArray();
using GraphicsResource variablesBuffer = device.AllocateConstantBufferFromReflectedValues(variables);
commandList.SetComputeRootDescriptorTable(0, variablesBuffer);
// Dispatch and wait for completion
commandList.Dispatch(groupsX, groupsY, groupsZ);
commandList.Flush();
// Free the allocated resources
foreach (GraphicsResource resource in buffers)
{
resource.Dispose();
}
}
}
}
+36 -39
ファイルの表示
@@ -2,14 +2,15 @@
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
using ComputeSharp.Graphics.Buffers.Abstract;
using ComputeSharp.Shaders.Mappings;
using ComputeSharp.Shaders.Renderer.Models.Fields;
using ComputeSharp.Shaders.Renderer.Models.Fields.Abstract;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using SharpDX.Direct3D12;
using FieldInfo = ComputeSharp.Shaders.Renderer.Models.Fields.Abstract.FieldInfo;
#pragma warning disable CS8618 // Non-nullable field is uninitialized
@@ -57,22 +58,33 @@ namespace ComputeSharp.Shaders.Translation
/// </summary>
public RootParameter[] RootParameters { get; private set; }
private readonly List<(int, GraphicsResource)> _Buffers = new List<(int, GraphicsResource)>();
/// <summary>
/// Gets the ordered collection of buffers used as fields in the current shader
/// </summary>
public IReadOnlyList<(int Index, GraphicsResource Resource)> Buffers { get; private set; }
public IReadOnlyList<(int Index, GraphicsResource Resource)> Buffers => _Buffers;
private readonly List<HlslBufferInfo> _BuffersList = new List<HlslBufferInfo>();
/// <summary>
/// Gets the ordered collection of captured variables that need to be assigned to constant buffers
/// Gets the collection of <see cref="HlslBufferInfo"/> items for the shader fields
/// </summary>
public IReadOnlyList<(int Index, object Value)> CapturedConstantBufferValues { get; private set; }
public IReadOnlyList<HlslBufferInfo> BuffersList => _BuffersList;
private readonly List<FieldInfo> _FieldsInfo = new List<FieldInfo>();
private readonly List<CapturedFieldInfo> _FieldsList = new List<CapturedFieldInfo>();
/// <summary>
/// Gets the collection of <see cref="FieldInfo"/> items for the shader fields
/// Gets the collection of <see cref="CapturedFieldInfo"/> items for the shader fields
/// </summary>
public IReadOnlyList<FieldInfo> FieldsInfo => _FieldsInfo;
public IReadOnlyList<CapturedFieldInfo> FieldsList => _FieldsList;
private readonly List<object> _FieldValuesList = new List<object>();
/// <summary>
/// Gets the collection of values of the captured fields for the current shader
/// </summary>
public IReadOnlyList<object> FieldValuesList => _FieldValuesList;
/// <summary>
/// Gets the name of the <see cref="ThreadIds"/> variable used as input for the shader method
@@ -105,81 +117,66 @@ namespace ComputeSharp.Shaders.Translation
/// </summary>
private void LoadFieldsInfo()
{
if (FieldsInfo.Count > 0) throw new InvalidOperationException("Shader fields already loaded");
if (ShaderFields.Any(fieldInfo => fieldInfo.IsStatic)) throw new InvalidOperationException("Empty shader body");
List<DescriptorRange> descriptorRanges = new List<DescriptorRange>();
List<(int, GraphicsResource)> buffers = new List<(int, GraphicsResource)>();
List<(int, object)> variables = new List<(int, object)>();
int constantBuffersCount = 0;
int readOnlyBuffersCount = 0;
int readWriteBuffersCount = 0;
foreach (System.Reflection.FieldInfo fieldInfo in ShaderFields)
// Descriptor for the buffer for captured scalar/vector variables
descriptorRanges.Add(new DescriptorRange(DescriptorRangeType.ConstantBufferView, 1, constantBuffersCount++));
// Inspect the captured fields
foreach (FieldInfo fieldInfo in ShaderFields)
{
Type fieldType = fieldInfo.FieldType;
string fieldName = fieldInfo.Name;
object fieldValue = fieldInfo.GetValue(ShaderInstance);
FieldInfo processedFieldInfo;
// Constant buffer
if (HlslKnownTypes.IsConstantBufferType(fieldType))
{
DescriptorRange range = new DescriptorRange(DescriptorRangeType.ConstantBufferView, 1, constantBuffersCount);
descriptorRanges.Add(range);
descriptorRanges.Add(new DescriptorRange(DescriptorRangeType.ConstantBufferView, 1, constantBuffersCount));
// Reference to the underlying buffer
buffers.Add((descriptorRanges.Count - 1, (GraphicsResource)fieldValue));
_Buffers.Add((descriptorRanges.Count - 1, (GraphicsResource)fieldValue));
string typeName = HlslKnownTypes.GetMappedName(fieldType.GenericTypeArguments[0]);
processedFieldInfo = new ConstantBufferFieldInfo(typeName, fieldName, constantBuffersCount++, false);
_BuffersList.Add(new ConstantBufferFieldInfo(typeName, fieldName, constantBuffersCount++));
}
else if (HlslKnownTypes.IsReadOnlyBufferType(fieldType))
{
// Root parameter for a readonly buffer
DescriptorRange range = new DescriptorRange(DescriptorRangeType.ShaderResourceView, 1, readOnlyBuffersCount);
descriptorRanges.Add(range);
descriptorRanges.Add(new DescriptorRange(DescriptorRangeType.ShaderResourceView, 1, readOnlyBuffersCount));
// Reference to the underlying buffer
buffers.Add((descriptorRanges.Count - 1, (GraphicsResource)fieldValue));
_Buffers.Add((descriptorRanges.Count - 1, (GraphicsResource)fieldValue));
string typeName = HlslKnownTypes.GetMappedName(fieldType);
processedFieldInfo = new ReadOnlyBufferFieldInfo(typeName, fieldName, readOnlyBuffersCount++);
_BuffersList.Add(new ReadOnlyBufferFieldInfo(typeName, fieldName, readOnlyBuffersCount++));
}
else if (HlslKnownTypes.IsReadWriteBufferType(fieldType))
{
// Root parameter for a read write buffer
DescriptorRange range = new DescriptorRange(DescriptorRangeType.UnorderedAccessView, 1, readWriteBuffersCount);
descriptorRanges.Add(range);
descriptorRanges.Add(new DescriptorRange(DescriptorRangeType.UnorderedAccessView, 1, readWriteBuffersCount));
// Reference to the underlying buffer
buffers.Add((descriptorRanges.Count - 1, (GraphicsResource)fieldValue));
_Buffers.Add((descriptorRanges.Count - 1, (GraphicsResource)fieldValue));
string typeName = HlslKnownTypes.GetMappedName(fieldType);
processedFieldInfo = new ReadWriteBufferFieldInfo(typeName, fieldName, readWriteBuffersCount++);
_BuffersList.Add(new ReadWriteBufferFieldInfo(typeName, fieldName, readWriteBuffersCount++));
}
else if (HlslKnownTypes.IsKnownScalarType(fieldType) || HlslKnownTypes.IsKnownVectorType(fieldType))
{
// Constant buffer
DescriptorRange range = new DescriptorRange(DescriptorRangeType.ConstantBufferView, 1, constantBuffersCount);
descriptorRanges.Add(range);
// Register the captured value
variables.Add((descriptorRanges.Count - 1, fieldValue));
// Constant buffer field
// Register the captured field
_FieldValuesList.Add(fieldValue);
string typeName = HlslKnownTypes.GetMappedName(fieldType);
processedFieldInfo = new ConstantBufferFieldInfo(typeName, fieldName, constantBuffersCount++, true);
_FieldsList.Add(new CapturedFieldInfo(typeName, fieldName));
}
else throw new NotSupportedException($"Unsupported field of type {fieldType.FullName}");
_FieldsInfo.Add(processedFieldInfo);
}
RootParameters = descriptorRanges.Select(range => new RootParameter(ShaderVisibility.All, range)).ToArray();
Buffers = buffers;
CapturedConstantBufferValues = variables;
}
/// <summary>
+15 -17
ファイルの表示
@@ -1,4 +1,6 @@
using System;
using System.Numerics;
using System.Runtime.CompilerServices;
using ComputeSharp.Graphics.Buffers;
using ComputeSharp.Graphics.Buffers.Extensions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
@@ -10,27 +12,23 @@ namespace ComputeSharp.NetCore.Tests.Internals
public class BufferTests
{
[TestMethod]
public void ReadWriteBufferGetSetDataFromSingleValueInt()
public void ConstantBufferGetSetFromGenericValues()
{
object value = 77;
object[] values = { 7, 3.14, Vector2.UnitX, 3.14f };
using ConstantBuffer<int> buffer = (ConstantBuffer<int>)Gpu.Default.AllocateConstantBufferFromReflectedSingleValue(value);
int[] result = buffer.GetData();
using ConstantBuffer<Vector4> buffer = (ConstantBuffer<Vector4>)Gpu.Default.AllocateConstantBufferFromReflectedValues(values);
Vector4[] data = buffer.GetData();
ref byte r0 = ref Unsafe.As<Vector4, byte>(ref data[0]);
Assert.IsTrue(result.Length == 1);
Assert.IsTrue((int)value == result[0]);
}
int i = Unsafe.As<byte, int>(ref Unsafe.Add(ref r0, 0)); // 0 -> 3, sizeof(int) == 4
double d = Unsafe.As<byte, double>(ref Unsafe.Add(ref r0, 4)); // 4 -> 11, sizeof(double) == 8
Vector2 v2 = Unsafe.As<byte, Vector2>(ref Unsafe.Add(ref r0, 16)); // 16 -> 23, sizeof(Vector2) == 8
float f = Unsafe.As<byte, float>(ref Unsafe.Add(ref r0, 024)); // 24 -> 27, sizeof(float) == 4
[TestMethod]
public void ReadWriteBufferGetSetDataFromSingleValueFloat()
{
object value = 3.14f;
using ConstantBuffer<float> buffer = (ConstantBuffer<float>)Gpu.Default.AllocateConstantBufferFromReflectedSingleValue(value);
float[] result = buffer.GetData();
Assert.IsTrue(result.Length == 1);
Assert.IsTrue(MathF.Abs(result[0] - (float)value) < 0.0001f);
Assert.IsTrue((int)values[0] == i);
Assert.IsTrue(Math.Abs((double)values[1] - d) < 0.0001);
Assert.IsTrue((Vector2)values[2] == v2);
Assert.IsTrue(MathF.Abs((float)values[3] - f) < 0.0001);
}
}
}