Merge pull request #58 from Sergio0694/feature_shader-fields-loading-speedup
Shader fields loading speedup
このコミットが含まれているのは:
11ファイル変更
+492
-305
検索条件に一致するファイルはありません
@@ -1,80 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.Contracts;
|
||||
using System.Numerics;
|
||||
using System.Runtime.CompilerServices;
|
||||
using ComputeSharp.Graphics.Buffers.Abstract;
|
||||
|
||||
namespace ComputeSharp.Graphics.Buffers.Extensions
|
||||
{
|
||||
/// <summary>
|
||||
/// A <see langword="class"/> with extension methods for the <see cref="GraphicsDevice"/> type to allocate generic resources
|
||||
/// </summary>
|
||||
internal static class GraphicsResourceExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// 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"/> 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 AllocateConstantBufferFromReflectedValues(this GraphicsDevice device, IReadOnlyList<object> data)
|
||||
{
|
||||
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
|
||||
{
|
||||
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;
|
||||
}
|
||||
|
||||
// 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 Bool2 b2: WriteValue(b2, ref r0); break;
|
||||
case Bool3 b3: WriteValue(b3, ref r0); break;
|
||||
case Bool4 b4: WriteValue(b4, ref r0); break;
|
||||
case int i: WriteValue(i, ref r0); break;
|
||||
case Int2 i2: WriteValue(i2, ref r0); break;
|
||||
case Int3 i3: WriteValue(i3, ref r0); break;
|
||||
case Int4 i4: WriteValue(i4, ref r0); break;
|
||||
case uint u: WriteValue(u, ref r0); break;
|
||||
case UInt2 ui2: WriteValue(ui2, ref r0); break;
|
||||
case UInt3 ui3: WriteValue(ui3, ref r0); break;
|
||||
case UInt4 ui4: WriteValue(ui4, ref r0); break;
|
||||
case float f: WriteValue(f, ref r0); break;
|
||||
case Float2 f2: WriteValue(f2, ref r0); break;
|
||||
case Float3 f3: WriteValue(f3, ref r0); break;
|
||||
case Float4 f4: WriteValue(f4, 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;
|
||||
case double d: WriteValue(d, ref r0); break;
|
||||
case Double2 d2: WriteValue(d2, ref r0); break;
|
||||
case Double3 d3: WriteValue(d3, ref r0); break;
|
||||
case Double4 d4: WriteValue(d4, 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace System.Reflection.Emit
|
||||
{
|
||||
/// <summary>
|
||||
/// A <see langword="class"/> that provides extension methods for the <see langword="ILGenerator"/> type
|
||||
/// </summary>
|
||||
internal static class ILGeneratorExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// Puts the appropriate <see langword="unbox"/> or <see langword="castclass"/> instruction to unbox/cast a value onto the stream of instructions
|
||||
/// </summary>
|
||||
/// <param name="il">The input <see cref="ILGenerator"/> instance to use to emit instructions</param>
|
||||
/// <param name="type">The type of value to convert</param>
|
||||
public static void EmitCastOrUnbox(this ILGenerator il, Type type)
|
||||
{
|
||||
il.Emit(type.IsValueType ? OpCodes.Unbox : OpCodes.Castclass, type);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Puts the appropriate <see langword="ldloc"/> instruction to read a local variable onto the stream of instructions
|
||||
/// </summary>
|
||||
/// <param name="il">The input <see cref="ILGenerator"/> instance to use to emit instructions</param>
|
||||
/// <param name="index">The index of the local variable to load</param>
|
||||
public static void EmitLoadLocal(this ILGenerator il, int index)
|
||||
{
|
||||
if (index <= 3)
|
||||
{
|
||||
il.Emit(index switch
|
||||
{
|
||||
0 => OpCodes.Ldloc_0,
|
||||
1 => OpCodes.Ldloc_1,
|
||||
2 => OpCodes.Ldloc_2,
|
||||
3 => OpCodes.Ldloc_3,
|
||||
_ => throw new InvalidOperationException($"Invalid local variable index [{index}]")
|
||||
});
|
||||
}
|
||||
else if (index <= 255) il.Emit(OpCodes.Ldloc_S, (byte)index);
|
||||
else if (index <= 65534) il.Emit(OpCodes.Ldloc, (short)index);
|
||||
else throw new ArgumentOutOfRangeException($"Invalid local index {index}");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Puts the appropriate <see langword="stloc"/> instruction to write a local variable onto the stream of instructions
|
||||
/// </summary>
|
||||
/// <param name="il">The input <see cref="ILGenerator"/> instance to use to emit instructions</param>
|
||||
/// <param name="index">The index of the local variable to store</param>
|
||||
public static void EmitStoreLocal(this ILGenerator il, int index)
|
||||
{
|
||||
if (index <= 3)
|
||||
{
|
||||
il.Emit(index switch
|
||||
{
|
||||
0 => OpCodes.Stloc_0,
|
||||
1 => OpCodes.Stloc_1,
|
||||
2 => OpCodes.Stloc_2,
|
||||
3 => OpCodes.Stloc_3,
|
||||
_ => throw new InvalidOperationException($"Invalid local variable index [{index}]")
|
||||
});
|
||||
}
|
||||
else if (index <= 255) il.Emit(OpCodes.Stloc_S, (byte)index);
|
||||
else if (index <= 65534) il.Emit(OpCodes.Stloc, (short)index);
|
||||
else throw new ArgumentOutOfRangeException($"Invalid local index {index}");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Puts the appropriate <see langword="ldsfld"/>, <see langword="ldfld"/>, <see langword="call"/> or <see langword="callvirt"/> instruction to read a member onte the stream of instructions
|
||||
/// </summary>
|
||||
/// <param name="il">The input <see cref="ILGenerator"/> instance to use to emit instructions</param>
|
||||
/// <param name="member">The member to read</param>
|
||||
public static void EmitReadMember(this ILGenerator il, MemberInfo member)
|
||||
{
|
||||
switch (member)
|
||||
{
|
||||
case FieldInfo field:
|
||||
il.Emit(field.IsStatic ? OpCodes.Ldsfld : OpCodes.Ldfld, field);
|
||||
break;
|
||||
case PropertyInfo property when property.CanRead:
|
||||
il.EmitCall(property.GetMethod.IsStatic ? OpCodes.Call : OpCodes.Callvirt, property.GetMethod, null);
|
||||
break;
|
||||
default: throw new ArgumentException($"The input {member.GetType()} instance can't be read");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Puts the appropriate <see langword="ldc.i4"/>, <see langword="conv.i"/> and <see langword="add"/> instructions to advance a reference onto the stream of instructions
|
||||
/// </summary>
|
||||
/// <typeparam name="T">The type of reference at the top of the stack</typeparam>
|
||||
/// <param name="il">The input <see cref="ILGenerator"/> instance to use to emit instructions</param>
|
||||
/// <param name="offset">The offset to use to advance the current reference on top of the execution stack</param>
|
||||
public static void EmitAddOffset<T>(this ILGenerator il, int offset) => il.EmitAddOffset(Unsafe.SizeOf<T>() * offset);
|
||||
|
||||
/// <summary>
|
||||
/// Puts the appropriate <see langword="ldc.i4"/>, <see langword="conv.i"/> and <see langword="add"/> instructions to advance a reference onto the stream of instructions
|
||||
/// </summary>
|
||||
/// <param name="il">The input <see cref="ILGenerator"/> instance to use to emit instructions</param>
|
||||
/// <param name="offset">The offset in bytes to use to advance the current reference on top of the execution stack</param>
|
||||
public static void EmitAddOffset(this ILGenerator il, int offset)
|
||||
{
|
||||
// Push the offset to the stack
|
||||
if (offset < 128) il.Emit(OpCodes.Ldc_I4, offset);
|
||||
else if (offset < 0) il.Emit(OpCodes.Ldc_I4_S, (sbyte)offset);
|
||||
else if (offset <= 8)
|
||||
{
|
||||
il.Emit(offset switch
|
||||
{
|
||||
0 => OpCodes.Ldc_I4_0,
|
||||
1 => OpCodes.Ldc_I4_1,
|
||||
2 => OpCodes.Ldc_I4_2,
|
||||
3 => OpCodes.Ldc_I4_3,
|
||||
4 => OpCodes.Ldc_I4_4,
|
||||
5 => OpCodes.Ldc_I4_5,
|
||||
6 => OpCodes.Ldc_I4_6,
|
||||
7 => OpCodes.Ldc_I4_7,
|
||||
8 => OpCodes.Ldc_I4_8,
|
||||
_ => throw new InvalidOperationException($"Invalid offset value [{offset}]")
|
||||
});
|
||||
}
|
||||
else if (offset <= 127) il.Emit(OpCodes.Ldc_I4_S, (byte)offset);
|
||||
else il.Emit(OpCodes.Ldc_I4, offset);
|
||||
|
||||
// Converts the offset to native int and adds to the address
|
||||
il.Emit(OpCodes.Conv_I);
|
||||
il.Emit(OpCodes.Add);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Puts the appropriate <see langword="stind"/> or <see langword="stobj"/> instruction to write to a reference onto the stream of instructions
|
||||
/// </summary>
|
||||
/// <param name="il">The input <see cref="ILGenerator"/> instance to use to emit instructions</param>
|
||||
/// <param name="type">The type of value being written to the current reference on top of the execution stack</param>
|
||||
public static void EmitStoreToAddress(this ILGenerator il, Type type)
|
||||
{
|
||||
if (type.IsValueType)
|
||||
{
|
||||
// Pick the optimal opcode to set a value type
|
||||
OpCode opcode = Marshal.SizeOf(type) switch
|
||||
{
|
||||
// Use the faster op codes for sizes <= 8
|
||||
1 when type == typeof(bool) || type == typeof(byte) || type == typeof(sbyte) => OpCodes.Stind_I1,
|
||||
2 when type == typeof(short) || type == typeof(ushort) => OpCodes.Stind_I2,
|
||||
4 when type == typeof(float) => OpCodes.Stind_R4,
|
||||
4 when type == typeof(int) || type == typeof(uint) => OpCodes.Stind_I4,
|
||||
8 when type == typeof(double) => OpCodes.Stind_R8,
|
||||
8 when type == typeof(long) || type == typeof(ulong) => OpCodes.Stind_I8,
|
||||
|
||||
// Default to stobj for all other value types
|
||||
_ => OpCodes.Stobj
|
||||
};
|
||||
|
||||
// Also pass the type token if stobj is used
|
||||
if (opcode == OpCodes.Stobj) il.Emit(opcode, type);
|
||||
else il.Emit(opcode);
|
||||
}
|
||||
else il.Emit(OpCodes.Stind_Ref);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -93,6 +93,16 @@ namespace ComputeSharp.Shaders.Mappings
|
||||
type == typeof(Vector3) ||
|
||||
type == typeof(Vector4);
|
||||
|
||||
/// <summary>
|
||||
/// Checks whether or not the input type is a known buffer type
|
||||
/// </summary>
|
||||
/// <param name="type">The input <see cref="Type"/> instance to check</param>
|
||||
/// <returns>A <see langword="bool"/> indicating whether the input <see cref="Type"/> is in fact a known buffer type</returns>
|
||||
[Pure]
|
||||
public static bool IsKnownBufferType(Type type) => IsConstantBufferType(type) ||
|
||||
IsReadOnlyBufferType(type) ||
|
||||
IsReadWriteBufferType(type);
|
||||
|
||||
/// <summary>
|
||||
/// Checks whether or not the input type is a <see cref="ConstantBuffer{T}"/> value
|
||||
/// </summary>
|
||||
|
||||
@@ -1,9 +1,7 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using ComputeSharp.Graphics;
|
||||
using ComputeSharp.Graphics.Buffers.Abstract;
|
||||
using ComputeSharp.Graphics.Buffers.Extensions;
|
||||
using ComputeSharp.Shaders.Renderer;
|
||||
using ComputeSharp.Shaders.Renderer.Models;
|
||||
using ComputeSharp.Shaders.Translation;
|
||||
@@ -103,15 +101,19 @@ namespace ComputeSharp.Shaders
|
||||
using CommandList commandList = new CommandList(device, CommandListType.Compute);
|
||||
commandList.SetPipelineState(pipelineState);
|
||||
|
||||
// Extract the dispatch data for the shader invocation
|
||||
using DispatchData dispatchData = shaderData.Loader.GetDispatchData(action, x, y, z);
|
||||
|
||||
// Load the captured buffers
|
||||
foreach (var buffer in shaderData.Loader.GetBuffers(action))
|
||||
Span<GraphicsResource> resources = dispatchData.Resources;
|
||||
for (int i = 0; i < resources.Length; i++)
|
||||
{
|
||||
commandList.SetComputeRootDescriptorTable(buffer.Index, buffer.Resource);
|
||||
commandList.SetComputeRootDescriptorTable(i + 1, resources[i]);
|
||||
}
|
||||
|
||||
// Initialize the loop targets
|
||||
IReadOnlyList<object> variables = new object[] { (uint)x, (uint)y, (uint)z }.Concat(shaderData.Loader.GetVariables(action)).ToArray();
|
||||
using GraphicsResource variablesBuffer = device.AllocateConstantBufferFromReflectedValues(variables);
|
||||
Span<Int4> variables = dispatchData.Variables;
|
||||
using GraphicsResource variablesBuffer = device.AllocateConstantBuffer(variables);
|
||||
commandList.SetComputeRootDescriptorTable(0, variablesBuffer);
|
||||
|
||||
// Calculate the dispatch values
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
using System;
|
||||
using System.Buffers;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
using ComputeSharp.Graphics.Buffers.Abstract;
|
||||
|
||||
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 DispatchData
|
||||
{
|
||||
/// <summary>
|
||||
/// The <see cref="GraphicsResource"/> array with the captured buffers
|
||||
/// </summary>
|
||||
private readonly GraphicsResource[] 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="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)
|
||||
{
|
||||
ResourcesArray = resourcesArray;
|
||||
VariablesArray = variablesArray;
|
||||
ResourcesCount = resourcesCount;
|
||||
VariablesByteSize = variablesByteSize;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets a <see cref="Span{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
|
||||
{
|
||||
[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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Implements the <see cref="IDisposable.Dispose"/> method and returns the rented buffers
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
ArrayPool<GraphicsResource>.Shared.Return(ResourcesArray);
|
||||
ArrayPool<byte>.Shared.Return(VariablesArray);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,113 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.Contracts;
|
||||
using System.Linq;
|
||||
using System.Reflection.Emit;
|
||||
using System.Runtime.CompilerServices;
|
||||
|
||||
namespace ComputeSharp.Shaders.Translation.Models
|
||||
{
|
||||
internal sealed partial class ReadableMember
|
||||
{
|
||||
/// <summary>
|
||||
/// The mapping of members to getter delegates
|
||||
/// </summary>
|
||||
private static readonly Dictionary<string, Getter> GettersMapping = new Dictionary<string, Getter>();
|
||||
|
||||
/// <summary>
|
||||
/// The local <see cref="Getter"/> instance, if already loaded
|
||||
/// </summary>
|
||||
private Getter? _Getter;
|
||||
|
||||
/// <summary>
|
||||
/// Ensures the dynamic accessor for the current instance is loaded and ready to use
|
||||
/// </summary>
|
||||
public void PreloadAccessor()
|
||||
{
|
||||
if (_Getter == null)
|
||||
{
|
||||
/* If the local delegate is available, use it and save the dictionary
|
||||
* access entirely. If it's not, try to get the delegate from the dictionary
|
||||
* first. This can save unnecessary overhead if a delegate for the same member has
|
||||
* already been built, eg. if it belongs to a captured field that is used by two different
|
||||
* shaders in the same closure. Once the getter is built, cache it and invoke it */
|
||||
if (GettersMapping.TryGetValue(Id, out Getter getter)) _Getter = getter;
|
||||
else
|
||||
{
|
||||
_Getter = getter = BuildDynamicGetter();
|
||||
GettersMapping.Add(Id, getter);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the value of the wrapped member for the current instance
|
||||
/// </summary>
|
||||
/// <param name="instance">The target instance to use to read the value from</param>
|
||||
/// <remarks>This method doesn't ensure that the accessor is available</remarks>
|
||||
/// <exception cref="NullReferenceException">The dynamic accessor is not available</exception>
|
||||
[Pure]
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public object DangerousGetValue(object? instance) => _Getter!(instance);
|
||||
|
||||
/// <summary>
|
||||
/// Returns the value of the wrapped member for the current instance
|
||||
/// </summary>
|
||||
/// <param name="instance">The target instance to use to read the value from</param>
|
||||
[Pure]
|
||||
public object GetValue(object? instance)
|
||||
{
|
||||
PreloadAccessor();
|
||||
return _Getter!(instance);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A <see langword="delegate"/> that represents a getter for a specific member
|
||||
/// </summary>
|
||||
/// <param name="obj">The source object to get the member from</param>
|
||||
/// <returns>The value of the member, upcast to <see cref="object"/></returns>
|
||||
private delegate object Getter(object? obj);
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the list of parent members to access the current one from the root instance
|
||||
/// </summary>
|
||||
public IEnumerable<ReadableMember>? Parents { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Builds a dynamic IL method to retrieve the value of the current member
|
||||
/// </summary>
|
||||
[Pure]
|
||||
private Getter BuildDynamicGetter()
|
||||
{
|
||||
return DynamicMethod<Getter>.New(il =>
|
||||
{
|
||||
// Info for hierarchical access
|
||||
ReadableMember[] hierarchy = (Parents ?? Array.Empty<ReadableMember>()).Concat(new[] { this }).ToArray();
|
||||
|
||||
// Load the argument (the object instance) and cast it to the right type, if needed
|
||||
if (!IsStatic)
|
||||
{
|
||||
il.Emit(OpCodes.Ldarg_0);
|
||||
|
||||
Type unboxType = hierarchy[0].DeclaringType;
|
||||
il.Emit(unboxType.IsValueType ? OpCodes.Unbox : OpCodes.Castclass, unboxType);
|
||||
}
|
||||
|
||||
// Unroll the member access
|
||||
foreach (ReadableMember member in hierarchy)
|
||||
{
|
||||
// Get the member value with the appropriate method
|
||||
if (member.Property != null) il.EmitCall(member.IsStatic ? OpCodes.Call : OpCodes.Callvirt, member.Property.GetMethod, null);
|
||||
else if (member.Field != null) il.Emit(member.IsStatic ? OpCodes.Ldsfld : OpCodes.Ldfld, member.Field);
|
||||
else throw new InvalidOperationException("Field and property can't both be null at the same time");
|
||||
}
|
||||
|
||||
// Box the value, if needed
|
||||
if (MemberType.IsValueType) il.Emit(OpCodes.Box, MemberType);
|
||||
|
||||
// Return the member value from the top of the evaluation stack
|
||||
il.Emit(OpCodes.Ret);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,6 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.Contracts;
|
||||
using System.Reflection;
|
||||
|
||||
namespace ComputeSharp.Shaders.Translation.Models
|
||||
@@ -6,22 +8,12 @@ namespace ComputeSharp.Shaders.Translation.Models
|
||||
/// <summary>
|
||||
/// A <see langword="class"/> that wraps a readable member of another <see langword="class"/> and provides access to it
|
||||
/// </summary>
|
||||
internal sealed partial class ReadableMember
|
||||
internal sealed class ReadableMember
|
||||
{
|
||||
/// <summary>
|
||||
/// The id of the current member
|
||||
/// The <see cref="MemberInfo"/> object wrapped by the current instance
|
||||
/// </summary>
|
||||
private readonly string Id;
|
||||
|
||||
/// <summary>
|
||||
/// The <see cref="FieldInfo"/> object wrapped by the current instance, if present
|
||||
/// </summary>
|
||||
private readonly FieldInfo? Field;
|
||||
|
||||
/// <summary>
|
||||
/// The <see cref="PropertyInfo"/> object wrapped by the current instance, if present
|
||||
/// </summary>
|
||||
private readonly PropertyInfo? Property;
|
||||
private readonly MemberInfo Member;
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="ReadableMember"/> instance with the given parameters
|
||||
@@ -30,22 +22,22 @@ namespace ComputeSharp.Shaders.Translation.Models
|
||||
private ReadableMember(MemberInfo memberInfo)
|
||||
{
|
||||
// General properties
|
||||
Member = memberInfo;
|
||||
Name = memberInfo.Name;
|
||||
Id = $"{memberInfo.DeclaringType.FullName}{Type.Delimiter}{Name}";
|
||||
DeclaringType = memberInfo.DeclaringType;
|
||||
|
||||
// Type specific properties
|
||||
if (memberInfo is FieldInfo fieldInfo)
|
||||
{
|
||||
Field = fieldInfo;
|
||||
IsStatic = Field.IsStatic;
|
||||
MemberType = Field.FieldType;
|
||||
Member = fieldInfo;
|
||||
IsStatic = fieldInfo.IsStatic;
|
||||
MemberType = fieldInfo.FieldType;
|
||||
}
|
||||
else if (memberInfo is PropertyInfo propertyInfo)
|
||||
{
|
||||
Property = propertyInfo;
|
||||
IsStatic = Property.GetMethod.IsStatic;
|
||||
MemberType = Property.PropertyType;
|
||||
Member = propertyInfo;
|
||||
IsStatic = propertyInfo.GetMethod.IsStatic;
|
||||
MemberType = propertyInfo.PropertyType;
|
||||
}
|
||||
else throw new InvalidOperationException("Field and property can't both be null at the same time");
|
||||
}
|
||||
@@ -70,6 +62,26 @@ namespace ComputeSharp.Shaders.Translation.Models
|
||||
/// </summary>
|
||||
public Type MemberType { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the list of parent members to access the current one from the root instance
|
||||
/// </summary>
|
||||
public IReadOnlyList<ReadableMember>? Parents { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Returns the value of the wrapped member for the current instance
|
||||
/// </summary>
|
||||
/// <param name="instance">The target instance to use to read the value from</param>
|
||||
[Pure]
|
||||
public object GetValue(object? instance)
|
||||
{
|
||||
return Member switch
|
||||
{
|
||||
FieldInfo field => field.GetValue(instance),
|
||||
PropertyInfo property => property.GetValue(instance),
|
||||
_ => throw new InvalidOperationException("Field and property can't both be null at the same time")
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Converts a <see cref="FieldInfo"/> object into a <see cref="ReadableMember"/> instance
|
||||
/// </summary>
|
||||
@@ -81,5 +93,23 @@ namespace ComputeSharp.Shaders.Translation.Models
|
||||
/// </summary>
|
||||
/// <param name="property">The input <see cref="PropertyInfo"/> object to wrap</param>
|
||||
public static implicit operator ReadableMember(PropertyInfo property) => new ReadableMember(property);
|
||||
|
||||
/// <summary>
|
||||
/// Converts a <see cref="ReadableMember"/> object into a <see cref="MemberInfo"/> instance
|
||||
/// </summary>
|
||||
/// <param name="member">The input <see cref="ReadableMember"/> object to unwrap</param>
|
||||
public static implicit operator MemberInfo(ReadableMember member) => member.Member;
|
||||
|
||||
/// <summary>
|
||||
/// Converts a <see cref="ReadableMember"/> object into a <see cref="FieldInfo"/> instance
|
||||
/// </summary>
|
||||
/// <param name="member">The input <see cref="ReadableMember"/> object to unwrap</param>
|
||||
public static implicit operator FieldInfo(ReadableMember member) => (FieldInfo)member.Member;
|
||||
|
||||
/// <summary>
|
||||
/// Converts a <see cref="ReadableMember"/> object into a <see cref="PropertyInfo"/> instance
|
||||
/// </summary>
|
||||
/// <param name="member">The input <see cref="ReadableMember"/> object to unwrap</param>
|
||||
public static implicit operator PropertyInfo(ReadableMember member) => (PropertyInfo)member.Member;
|
||||
}
|
||||
}
|
||||
@@ -98,14 +98,14 @@ namespace ComputeSharp.Shaders.Translation
|
||||
|
||||
// hash = hash * 17 + field.Method.GetHashCode();
|
||||
il.Emit(OpCodes.Ldarg_0);
|
||||
il.Emit(OpCodes.Ldc_I4, 17);
|
||||
il.Emit(OpCodes.Ldc_I4_S, (byte)17);
|
||||
il.Emit(OpCodes.Mul);
|
||||
il.Emit(OpCodes.Ldloc_0);
|
||||
il.Emit(OpCodes.Ldfld, fieldInfo);
|
||||
il.EmitCall(OpCodes.Callvirt, getMethodInfo, null);
|
||||
il.EmitCall(OpCodes.Callvirt, getHashCodeInfo, null);
|
||||
il.Emit(OpCodes.Add);
|
||||
il.Emit(OpCodes.Starg_S, 0);
|
||||
il.Emit(OpCodes.Starg_S, (byte)0);
|
||||
|
||||
il.MarkLabel(label);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,176 @@
|
||||
using System;
|
||||
using System.Buffers;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.Contracts;
|
||||
using System.Linq;
|
||||
using System.Reflection.Emit;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
using ComputeSharp.Graphics.Buffers.Abstract;
|
||||
using ComputeSharp.Shaders.Mappings;
|
||||
using ComputeSharp.Shaders.Translation.Models;
|
||||
|
||||
namespace ComputeSharp.Shaders.Translation
|
||||
{
|
||||
/// <inheritdoc cref="ShaderLoader"/>
|
||||
internal sealed partial class ShaderLoader
|
||||
{
|
||||
/// <summary>
|
||||
/// The number of captured graphics resources (buffers)
|
||||
/// </summary>
|
||||
private int _ResourcesCount;
|
||||
|
||||
/// <summary>
|
||||
/// The size in bytes of the buffer with the captured variables
|
||||
/// </summary>
|
||||
private int _VariablesByteSize = 3 * sizeof(int); // X, Y and Z threads count
|
||||
|
||||
// The cached loader method
|
||||
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 List<ReadableMember>();
|
||||
|
||||
/// <summary>
|
||||
/// A <see langword="delegate"/> that loads all the captured members from a shader closure
|
||||
/// </summary>
|
||||
/// <param name="obj">The shader closure 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(object obj, ref GraphicsResource r0, ref byte r1);
|
||||
|
||||
/// <summary>
|
||||
/// Gets a new <see cref="DispatchData"/> instance with all the captured data for the current shader instance
|
||||
/// </summary>
|
||||
/// <param name="action">The input <see cref="Action{T}"/> 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(Action<ThreadIds> action, int x, int y, int z)
|
||||
{
|
||||
/* Create the data loader instance, if not available already.
|
||||
* This will also initialize the other local fields in the shader
|
||||
* loader class, which are used to rent the buffers used to store
|
||||
* the captured resources and variables. This is why this call
|
||||
* has to be the first one in this method, it must NOT be moved */
|
||||
DispatchDataLoader loader = _DispatchDataLoader ??= BuildDispatchDataLoader();
|
||||
|
||||
// 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];
|
||||
|
||||
// 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
|
||||
loader(action.Target, ref r0, ref r1);
|
||||
|
||||
return new DispatchData(resources, _ResourcesCount, variables, _VariablesByteSize);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds a new <see cref="DispatchDataLoader"/> instance that loads the dispatch data for the current shader type
|
||||
/// </summary>
|
||||
[Pure]
|
||||
private DispatchDataLoader BuildDispatchDataLoader()
|
||||
{
|
||||
// Mapping of parent members to index of the relative local variable
|
||||
var map =
|
||||
_CapturedMembers
|
||||
.Where(m => !m.IsStatic && m.Parents != null)
|
||||
.SelectMany(m => m.Parents)
|
||||
.Distinct()
|
||||
.Select((m, i) => (Member: m, Index: i))
|
||||
.ToDictionary(p => (object)p.Member, p => p.Index + 1);
|
||||
object root = new object(); // Placeholder
|
||||
map.Add(root, 0);
|
||||
|
||||
// Set of indices of the loaded parent members
|
||||
HashSet<int> loaded = new HashSet<int>(new[] { 0 });
|
||||
|
||||
// Build the dynamic IL method
|
||||
return DynamicMethod<DispatchDataLoader>.New(il =>
|
||||
{
|
||||
// Loads a given member on the top of the execution stack
|
||||
void LoadMember(ReadableMember member)
|
||||
{
|
||||
if (!member.IsStatic)
|
||||
{
|
||||
// Load the parent instance on the execution stack if the member isn't static
|
||||
int index = map[member.Parents?.Last() ?? root];
|
||||
if (loaded.Contains(index)) il.EmitLoadLocal(index);
|
||||
else
|
||||
{
|
||||
// Seek upwards to find the most in depth loaded parent
|
||||
int i = member.Parents!.Count - 1;
|
||||
while (i > 0 && !loaded.Contains(map[member.Parents[i]])) i--;
|
||||
|
||||
// Load the local variables for all the parents of the current member
|
||||
if (i == 0) il.EmitLoadLocal(0);
|
||||
for (; i < member.Parents.Count; i++)
|
||||
{
|
||||
il.Emit(OpCodes.Ldfld, member.Parents[i]);
|
||||
il.EmitStoreLocal(map[member.Parents[i]]);
|
||||
il.EmitLoadLocal(map[member.Parents[i]]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
il.EmitReadMember(member);
|
||||
}
|
||||
|
||||
// Declare the local variables
|
||||
il.DeclareLocal(ShaderType);
|
||||
foreach (ReadableMember member in map.OrderBy(p => p.Value).Skip(1).Select(p => p.Key))
|
||||
{
|
||||
il.DeclareLocal(member.MemberType);
|
||||
}
|
||||
|
||||
// Cast the closure instance and assign it to the local variable
|
||||
il.Emit(OpCodes.Ldarg_0);
|
||||
il.EmitCastOrUnbox(ShaderType);
|
||||
il.Emit(OpCodes.Stloc_0);
|
||||
|
||||
// Handle all the captured members, both resources and variables
|
||||
foreach (ReadableMember member in _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++;
|
||||
}
|
||||
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;
|
||||
|
||||
// Load the target address into the variables buffer
|
||||
il.Emit(OpCodes.Ldarg_2);
|
||||
il.EmitAddOffset(_VariablesByteSize);
|
||||
_VariablesByteSize += size;
|
||||
}
|
||||
else throw new InvalidOperationException($"Invalid captured member of type {member.MemberType}");
|
||||
|
||||
/* Load the current member accordingly.
|
||||
* When this method returns, the value of the current
|
||||
* member will be at the top of the execution stack */
|
||||
LoadMember(member);
|
||||
|
||||
il.EmitStoreToAddress(member.MemberType);
|
||||
}
|
||||
|
||||
il.Emit(OpCodes.Ret);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,6 @@ using System.Diagnostics.Contracts;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Text.RegularExpressions;
|
||||
using ComputeSharp.Graphics.Buffers.Abstract;
|
||||
using ComputeSharp.Graphics.Extensions;
|
||||
using ComputeSharp.Shaders.Mappings;
|
||||
using ComputeSharp.Shaders.Renderer.Models.Fields;
|
||||
@@ -24,7 +23,7 @@ namespace ComputeSharp.Shaders.Translation
|
||||
/// <summary>
|
||||
/// A <see langword="class"/> responsible for loading and processing <see cref="Action{T}"/> instances
|
||||
/// </summary>
|
||||
internal sealed class ShaderLoader
|
||||
internal sealed partial class ShaderLoader
|
||||
{
|
||||
/// <summary>
|
||||
/// The <see cref="Action{T}"/> that represents the shader to load
|
||||
@@ -73,41 +72,6 @@ namespace ComputeSharp.Shaders.Translation
|
||||
/// </summary>
|
||||
public RootParameter1[] RootParameters => _RootParameters ??= DescriptorRanges.Select(range => new RootParameter1(new RootDescriptorTable1(range), ShaderVisibility.All)).ToArray();
|
||||
|
||||
/// <summary>
|
||||
/// The <see cref="List{T}"/> of <see cref="ReadableMember"/> instances mapping the captured buffers in the current shader
|
||||
/// </summary>
|
||||
private readonly List<ReadableMember> _BufferMembers = new List<ReadableMember>();
|
||||
|
||||
/// <summary>
|
||||
/// Gets the ordered collection of buffers used as fields in the current shader
|
||||
/// </summary>
|
||||
/// <param name="action">The <see cref="Action{T}"/> to use to build the shader</param>
|
||||
public IEnumerable<(int Index, GraphicsResource Resource)> GetBuffers(Action<ThreadIds> action)
|
||||
{
|
||||
int index = 1;
|
||||
foreach (var item in _BufferMembers)
|
||||
{
|
||||
yield return (index++, (GraphicsResource)item.DangerousGetValue(action.Target));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The <see cref="List{T}"/> of <see cref="ReadableMember"/> instances mapping the captured scalar/vector variables in the current shader
|
||||
/// </summary>
|
||||
private readonly List<ReadableMember> _VariableMembers = new List<ReadableMember>();
|
||||
|
||||
/// <summary>
|
||||
/// Gets the collection of values of the captured fields for the current shader
|
||||
/// </summary>
|
||||
/// <param name="action">The <see cref="Action{T}"/> to use to build the shader</param>
|
||||
public IEnumerable<object> GetVariables(Action<ThreadIds> action)
|
||||
{
|
||||
foreach (var item in _VariableMembers)
|
||||
{
|
||||
yield return item.DangerousGetValue(action.Target);
|
||||
}
|
||||
}
|
||||
|
||||
private readonly List<HlslBufferInfo> _BuffersList = new List<HlslBufferInfo>();
|
||||
|
||||
/// <summary>
|
||||
@@ -198,7 +162,7 @@ namespace ComputeSharp.Shaders.Translation
|
||||
|
||||
// Track the buffer field
|
||||
memberInfo.Parents = parents;
|
||||
_BufferMembers.Add(memberInfo);
|
||||
_CapturedMembers.Add(memberInfo);
|
||||
|
||||
string typeName = HlslKnownTypes.GetMappedName(fieldType.GenericTypeArguments[0]);
|
||||
_BuffersList.Add(new ConstantBufferFieldInfo(fieldType, typeName, fieldName, _ConstantBuffersCount++));
|
||||
@@ -210,7 +174,7 @@ namespace ComputeSharp.Shaders.Translation
|
||||
|
||||
// Track the buffer field
|
||||
memberInfo.Parents = parents;
|
||||
_BufferMembers.Add(memberInfo);
|
||||
_CapturedMembers.Add(memberInfo);
|
||||
|
||||
string typeName = HlslKnownTypes.GetMappedName(fieldType);
|
||||
_BuffersList.Add(new ReadOnlyBufferFieldInfo(fieldType, typeName, fieldName, _ReadOnlyBuffersCount++));
|
||||
@@ -222,7 +186,7 @@ namespace ComputeSharp.Shaders.Translation
|
||||
|
||||
// Track the buffer field
|
||||
memberInfo.Parents = parents;
|
||||
_BufferMembers.Add(memberInfo);
|
||||
_CapturedMembers.Add(memberInfo);
|
||||
|
||||
string typeName = HlslKnownTypes.GetMappedName(fieldType);
|
||||
_BuffersList.Add(new ReadWriteBufferFieldInfo(fieldType, typeName, fieldName, _ReadWriteBuffersCount++));
|
||||
@@ -231,7 +195,7 @@ namespace ComputeSharp.Shaders.Translation
|
||||
{
|
||||
// Register the captured field
|
||||
memberInfo.Parents = parents;
|
||||
_VariableMembers.Add(memberInfo);
|
||||
_CapturedMembers.Add(memberInfo);
|
||||
|
||||
string typeName = HlslKnownTypes.GetMappedName(fieldType);
|
||||
_FieldsList.Add(new CapturedFieldInfo(fieldType, typeName, fieldName));
|
||||
@@ -259,14 +223,6 @@ namespace ComputeSharp.Shaders.Translation
|
||||
// Captured static delegates with a return type
|
||||
LoadStaticMethodSource(fieldName, func.Method);
|
||||
}
|
||||
|
||||
/* Build the dynamic IL accessor for the current member, if one is
|
||||
* not available already. This is done during while the shader is
|
||||
* being loaded and not just when needed because the internal cache
|
||||
* system for the accessors is not thread safe. Preloading the accessor here
|
||||
* leverages the external lock around the shader loading, ensuring
|
||||
* that no race conditions occur when accessing the cached mapping */
|
||||
memberInfo.PreloadAccessor();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -1,35 +0,0 @@
|
||||
using System;
|
||||
using System.Numerics;
|
||||
using System.Runtime.CompilerServices;
|
||||
using ComputeSharp.Graphics.Buffers.Extensions;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
|
||||
namespace ComputeSharp.Tests.Internals
|
||||
{
|
||||
[TestClass]
|
||||
[TestCategory("Buffers")]
|
||||
public class BufferTests
|
||||
{
|
||||
[TestMethod]
|
||||
public void ConstantBufferGetSetFromGenericValues()
|
||||
{
|
||||
object[] values = { 7, 3.14, Vector2.UnitX, 3.14f, new Vector4(7.14f, 7.15f, 7.77f, 2.55f) };
|
||||
|
||||
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]);
|
||||
|
||||
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, 24)); // 24 -> 27, sizeof(float) == 4
|
||||
Vector4 v4 = Unsafe.As<byte, Vector4>(ref Unsafe.Add(ref r0, 32)); // 32 -> 47, sizeof(Vector4) == 16
|
||||
|
||||
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);
|
||||
Assert.IsTrue((Vector4)values[4] == v4);
|
||||
}
|
||||
}
|
||||
}
|
||||
新しいイシューから参照
ユーザーをブロックする