diff --git a/src/ComputeSharp.Graphics/Buffers/Extensions/GraphicsResourceExtensions.cs b/src/ComputeSharp.Graphics/Buffers/Extensions/GraphicsResourceExtensions.cs
index 7ab8bb98..d454a8f7 100644
--- a/src/ComputeSharp.Graphics/Buffers/Extensions/GraphicsResourceExtensions.cs
+++ b/src/ComputeSharp.Graphics/Buffers/Extensions/GraphicsResourceExtensions.cs
@@ -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
{
///
- /// The that maps types to the necessary data to create buffers, for quick lookup
- ///
- private static readonly Dictionary TypeMapping = new Dictionary();
-
- ///
- /// Allocates a new constant buffer with the specified generic value
+ /// Allocates a new constant buffer with the specified generic values
///
/// The instance to use to allocate the buffer
- /// The input to copy to the allocated buffer
+ /// The input sequence to copy to the allocated buffer
/// A constant instance (as a ) with the input data
[Pure]
- public static GraphicsResource AllocateConstantBufferFromReflectedSingleValue(this GraphicsDevice device, object data)
+ public static GraphicsResource AllocateConstantBufferFromReflectedValues(this GraphicsDevice device, IReadOnlyList data)
{
- Type dataType = data.GetType();
- if (!TypeMapping.TryGetValue(dataType, out var info))
+ Span temporarySpan = stackalloc Vector4[data.Count];
+ ref byte r0 = ref Unsafe.As(ref temporarySpan.GetPinnableReference());
+ int offset = 0;
+
+ // Local method to write a value in the temporary buffer
+ void WriteValue(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.SetData), new[] { arrayType });
-
- // Cache for later reuse
- TypeMapping.Add(dataType, info);
+ int size = Unsafe.SizeOf();
+ if (offset % 16 > 16 - size) offset += 16 - offset % 16;
+ Unsafe.As(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(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 buffer = new ConstantBuffer(device, data.Count);
+ buffer.SetData(temporarySpan);
return buffer;
}
diff --git a/src/ComputeSharp.Shaders/Mappings/HlslKnownMethods.cs b/src/ComputeSharp.Shaders/Mappings/HlslKnownMethods.cs
index 143e087e..f06116e5 100644
--- a/src/ComputeSharp.Shaders/Mappings/HlslKnownMethods.cs
+++ b/src/ComputeSharp.Shaders/Mappings/HlslKnownMethods.cs
@@ -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)"
};
///
diff --git a/src/ComputeSharp.Shaders/Mappings/HlslKnownTypes.cs b/src/ComputeSharp.Shaders/Mappings/HlslKnownTypes.cs
index 56a9a633..0140ed18 100644
--- a/src/ComputeSharp.Shaders/Mappings/HlslKnownTypes.cs
+++ b/src/ComputeSharp.Shaders/Mappings/HlslKnownTypes.cs
@@ -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);
///
/// Checks whether or not the input type is a value
diff --git a/src/ComputeSharp.Shaders/Renderer/Models/Fields/Abstract/HlslBufferInfo.cs b/src/ComputeSharp.Shaders/Renderer/Models/Fields/Abstract/HlslBufferInfo.cs
index e5c0044e..cc41114a 100644
--- a/src/ComputeSharp.Shaders/Renderer/Models/Fields/Abstract/HlslBufferInfo.cs
+++ b/src/ComputeSharp.Shaders/Renderer/Models/Fields/Abstract/HlslBufferInfo.cs
@@ -3,7 +3,7 @@
///
/// A that contains info on a shader buffer field
///
- internal abstract class HlslBufferInfo : FieldInfo
+ internal abstract class HlslBufferInfo : CapturedFieldInfo
{
///
/// Gets or sets the index of the current buffer, relative to its own type
diff --git a/src/ComputeSharp.Shaders/Renderer/Models/Fields/Abstract/FieldInfo.cs b/src/ComputeSharp.Shaders/Renderer/Models/Fields/CapturedFieldInfo.cs
similarity index 73%
rename from src/ComputeSharp.Shaders/Renderer/Models/Fields/Abstract/FieldInfo.cs
rename to src/ComputeSharp.Shaders/Renderer/Models/Fields/CapturedFieldInfo.cs
index 8c60411e..a037c8b4 100644
--- a/src/ComputeSharp.Shaders/Renderer/Models/Fields/Abstract/FieldInfo.cs
+++ b/src/ComputeSharp.Shaders/Renderer/Models/Fields/CapturedFieldInfo.cs
@@ -1,9 +1,9 @@
-namespace ComputeSharp.Shaders.Renderer.Models.Fields.Abstract
+namespace ComputeSharp.Shaders.Renderer.Models.Fields
{
///
/// A that contains info on a shader field
///
- internal abstract class FieldInfo
+ internal class CapturedFieldInfo
{
///
/// Gets or sets the type of the current field
@@ -16,11 +16,11 @@
public string FieldName { get; set; }
///
- /// Creates a new instance with the specified parameters
+ /// Creates a new instance with the specified parameters
///
/// The type of the current field
/// The name of the current field
- protected FieldInfo(string fieldType, string fieldName)
+ public CapturedFieldInfo(string fieldType, string fieldName)
{
FieldType = fieldType;
FieldName = fieldName;
diff --git a/src/ComputeSharp.Shaders/Renderer/Models/Fields/ConstantBufferFieldInfo.cs b/src/ComputeSharp.Shaders/Renderer/Models/Fields/ConstantBufferFieldInfo.cs
index ca47d290..5dff2be0 100644
--- a/src/ComputeSharp.Shaders/Renderer/Models/Fields/ConstantBufferFieldInfo.cs
+++ b/src/ComputeSharp.Shaders/Renderer/Models/Fields/ConstantBufferFieldInfo.cs
@@ -8,25 +8,16 @@ namespace ComputeSharp.Shaders.Renderer.Models.Fields
internal sealed class ConstantBufferFieldInfo : HlslBufferInfo
{
///
- /// Gets whether or not the current instance represents a constant buffer (always )
+ /// Gets whether or not the current instance represents a constant buffer (always )
///
public bool IsConstantBuffer { get; } = true;
- ///
- /// Gets whether or not this constant buffer actually contains a single, explicit variable
- ///
- public bool IsSingleValue { get; }
-
///
/// Creates a new instance with the specified parameters
///
/// The type of the current field
/// The name of the current field
/// The index of the current constant buffer field
- /// Whether or not this constant buffer actually contains a single, explicit variable
- 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) { }
}
}
diff --git a/src/ComputeSharp.Shaders/Renderer/Models/Fields/ReadOnlyBufferFieldInfo.cs b/src/ComputeSharp.Shaders/Renderer/Models/Fields/ReadOnlyBufferFieldInfo.cs
index a8d826ee..6bba7e0a 100644
--- a/src/ComputeSharp.Shaders/Renderer/Models/Fields/ReadOnlyBufferFieldInfo.cs
+++ b/src/ComputeSharp.Shaders/Renderer/Models/Fields/ReadOnlyBufferFieldInfo.cs
@@ -8,7 +8,7 @@ namespace ComputeSharp.Shaders.Renderer.Models.Fields
internal sealed class ReadOnlyBufferFieldInfo : HlslBufferInfo
{
///
- /// Gets whether or not the current instance represents a readonly buffer (always )
+ /// Gets whether or not the current instance represents a readonly buffer (always )
///
public bool IsReadOnlyBuffer { get; } = true;
diff --git a/src/ComputeSharp.Shaders/Renderer/Models/Fields/ReadWriteBufferFieldInfo.cs b/src/ComputeSharp.Shaders/Renderer/Models/Fields/ReadWriteBufferFieldInfo.cs
index 170260dc..5dbf8d02 100644
--- a/src/ComputeSharp.Shaders/Renderer/Models/Fields/ReadWriteBufferFieldInfo.cs
+++ b/src/ComputeSharp.Shaders/Renderer/Models/Fields/ReadWriteBufferFieldInfo.cs
@@ -8,7 +8,7 @@ namespace ComputeSharp.Shaders.Renderer.Models.Fields
internal sealed class ReadWriteBufferFieldInfo : HlslBufferInfo
{
///
- /// Gets whether or not the current instance represents a read write buffer (always )
+ /// Gets whether or not the current instance represents a read write buffer (always )
///
public bool IsReadWriteBuffer { get; } = true;
diff --git a/src/ComputeSharp.Shaders/Renderer/Models/Fields/StaticScalarFieldInfo.cs b/src/ComputeSharp.Shaders/Renderer/Models/Fields/StaticScalarFieldInfo.cs
deleted file mode 100644
index 670abc20..00000000
--- a/src/ComputeSharp.Shaders/Renderer/Models/Fields/StaticScalarFieldInfo.cs
+++ /dev/null
@@ -1,31 +0,0 @@
-using ComputeSharp.Shaders.Renderer.Models.Fields.Abstract;
-
-namespace ComputeSharp.Shaders.Renderer.Models.Fields
-{
- ///
- /// A that contains info on a static scalar field
- ///
- internal sealed class StaticScalarFieldInfo : FieldInfo
- {
- ///
- /// Gets whether or not the current instance represents a static scalar value (always )
- ///
- public bool IsStaticScalarField { get; } = true;
-
- ///
- /// Gets or sets the value to set for the current field
- ///
- public object FieldValue { get; set; }
-
- ///
- /// Creates a new instance with the specified parameters
- ///
- /// The type of the current field
- /// The name of the current field
- /// The static value to assign to the current field
- public StaticScalarFieldInfo(string fieldType, string fieldName, object fieldValue) : base(fieldType, fieldName)
- {
- FieldValue = fieldValue;
- }
- }
-}
diff --git a/src/ComputeSharp.Shaders/Renderer/Models/ShaderInfo.cs b/src/ComputeSharp.Shaders/Renderer/Models/ShaderInfo.cs
index 255c797a..8dc33e8b 100644
--- a/src/ComputeSharp.Shaders/Renderer/Models/ShaderInfo.cs
+++ b/src/ComputeSharp.Shaders/Renderer/Models/ShaderInfo.cs
@@ -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
{
///
- /// Gets the list of fields being present in the current shader
+ /// Gets the list of captured buffers being present in the current shader
///
- public IReadOnlyList FieldsList { get; set; }
+ public IReadOnlyList BuffersList { get; set; }
///
- /// 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
///
- public int ThreadsX { get; set; }
-
- ///
- /// Gets or sets the total number of threads to run on the Y axis
- ///
- public int ThreadsY { get; set; }
-
- ///
- /// Gets or sets the total number of threads to run on the Z axis
- ///
- public int ThreadsZ { get; set; }
+ public IReadOnlyList FieldsList { get; set; }
///
/// Gets or sets the number of threads in the X group
diff --git a/src/ComputeSharp.Shaders/Renderer/Templates/ShaderTemplate.mustache b/src/ComputeSharp.Shaders/Renderer/Templates/ShaderTemplate.mustache
index 382629c2..f0910d08 100644
--- a/src/ComputeSharp.Shaders/Renderer/Templates/ShaderTemplate.mustache
+++ b/src/ComputeSharp.Shaders/Renderer/Templates/ShaderTemplate.mustache
@@ -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}}
}
diff --git a/src/ComputeSharp.Shaders/ShaderRunner.cs b/src/ComputeSharp.Shaders/ShaderRunner.cs
index 5acaac28..09cf2fd2 100644
--- a/src/ComputeSharp.Shaders/ShaderRunner.cs
+++ b/src/ComputeSharp.Shaders/ShaderRunner.cs
@@ -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 buffers = new List();
- 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 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();
- }
}
}
}
diff --git a/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs b/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs
index feeba23f..3ac67495 100644
--- a/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs
+++ b/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs
@@ -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
///
public RootParameter[] RootParameters { get; private set; }
+ private readonly List<(int, GraphicsResource)> _Buffers = new List<(int, GraphicsResource)>();
+
///
/// Gets the ordered collection of buffers used as fields in the current shader
///
- public IReadOnlyList<(int Index, GraphicsResource Resource)> Buffers { get; private set; }
+ public IReadOnlyList<(int Index, GraphicsResource Resource)> Buffers => _Buffers;
+
+ private readonly List _BuffersList = new List();
///
- /// Gets the ordered collection of captured variables that need to be assigned to constant buffers
+ /// Gets the collection of items for the shader fields
///
- public IReadOnlyList<(int Index, object Value)> CapturedConstantBufferValues { get; private set; }
+ public IReadOnlyList BuffersList => _BuffersList;
- private readonly List _FieldsInfo = new List();
+ private readonly List _FieldsList = new List();
///
- /// Gets the collection of items for the shader fields
+ /// Gets the collection of items for the shader fields
///
- public IReadOnlyList FieldsInfo => _FieldsInfo;
+ public IReadOnlyList FieldsList => _FieldsList;
+
+ private readonly List _FieldValuesList = new List();
+
+ ///
+ /// Gets the collection of values of the captured fields for the current shader
+ ///
+ public IReadOnlyList FieldValuesList => _FieldValuesList;
///
/// Gets the name of the variable used as input for the shader method
@@ -105,81 +117,66 @@ namespace ComputeSharp.Shaders.Translation
///
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 descriptorRanges = new List();
- 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;
}
///
diff --git a/tests/ComputeSharp.NetCore.Tests.Internals/BufferTests.cs b/tests/ComputeSharp.NetCore.Tests.Internals/BufferTests.cs
index cf24f066..cf67acc9 100644
--- a/tests/ComputeSharp.NetCore.Tests.Internals/BufferTests.cs
+++ b/tests/ComputeSharp.NetCore.Tests.Internals/BufferTests.cs
@@ -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 buffer = (ConstantBuffer)Gpu.Default.AllocateConstantBufferFromReflectedSingleValue(value);
- int[] result = buffer.GetData();
+ using ConstantBuffer buffer = (ConstantBuffer)Gpu.Default.AllocateConstantBufferFromReflectedValues(values);
+ Vector4[] data = buffer.GetData();
+ ref byte r0 = ref Unsafe.As(ref data[0]);
- Assert.IsTrue(result.Length == 1);
- Assert.IsTrue((int)value == result[0]);
- }
+ int i = Unsafe.As(ref Unsafe.Add(ref r0, 0)); // 0 -> 3, sizeof(int) == 4
+ double d = Unsafe.As(ref Unsafe.Add(ref r0, 4)); // 4 -> 11, sizeof(double) == 8
+ Vector2 v2 = Unsafe.As(ref Unsafe.Add(ref r0, 16)); // 16 -> 23, sizeof(Vector2) == 8
+ float f = Unsafe.As(ref Unsafe.Add(ref r0, 024)); // 24 -> 27, sizeof(float) == 4
- [TestMethod]
- public void ReadWriteBufferGetSetDataFromSingleValueFloat()
- {
- object value = 3.14f;
-
- using ConstantBuffer buffer = (ConstantBuffer)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);
}
}
}