From 7c3c642fad62faef20684ee0883ac89b12a284b8 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Thu, 19 Sep 2019 15:08:34 +0200 Subject: [PATCH] More code refactoring, removed all legacy code --- .../Extensions/GraphicsResourceExtensions.cs | 80 ------------- .../Models/ReadableMember.GetValue.cs | 108 ------------------ .../Translation/Models/ReadableMember.cs | 30 +++-- .../Translation/ShaderLoader.IL.cs | 8 +- .../Translation/ShaderLoader.cs | 8 -- .../BufferTests.cs | 35 ------ 6 files changed, 30 insertions(+), 239 deletions(-) delete mode 100644 src/ComputeSharp.Graphics/Buffers/Extensions/GraphicsResourceExtensions.cs delete mode 100644 src/ComputeSharp.Shaders/Translation/Models/ReadableMember.GetValue.cs delete mode 100644 tests/ComputeSharp.Tests.Internals/BufferTests.cs diff --git a/src/ComputeSharp.Graphics/Buffers/Extensions/GraphicsResourceExtensions.cs b/src/ComputeSharp.Graphics/Buffers/Extensions/GraphicsResourceExtensions.cs deleted file mode 100644 index 23cd38a7..00000000 --- a/src/ComputeSharp.Graphics/Buffers/Extensions/GraphicsResourceExtensions.cs +++ /dev/null @@ -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 -{ - /// - /// A with extension methods for the type to allocate generic resources - /// - internal static class GraphicsResourceExtensions - { - /// - /// Allocates a new constant buffer with the specified generic values - /// - /// The instance to use to allocate the buffer - /// The input sequence to copy to the allocated buffer - /// A constant instance (as a ) with the input data - [Pure] - public static GraphicsResource AllocateConstantBufferFromReflectedValues(this GraphicsDevice device, IReadOnlyList data) - { - 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 - { - int size = Unsafe.SizeOf(); - if (offset % 16 > 16 - size) offset += 16 - offset % 16; - Unsafe.As(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(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 buffer = new ConstantBuffer(device, data.Count); - buffer.SetData(temporarySpan); - - return buffer; - } - } -} diff --git a/src/ComputeSharp.Shaders/Translation/Models/ReadableMember.GetValue.cs b/src/ComputeSharp.Shaders/Translation/Models/ReadableMember.GetValue.cs deleted file mode 100644 index 70e665c6..00000000 --- a/src/ComputeSharp.Shaders/Translation/Models/ReadableMember.GetValue.cs +++ /dev/null @@ -1,108 +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 - { - /// - /// The mapping of members to getter delegates - /// - private static readonly Dictionary GettersMapping = new Dictionary(); - - /// - /// The local instance, if already loaded - /// - private Getter? _Getter; - - /// - /// Ensures the dynamic accessor for the current instance is loaded and ready to use - /// - 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); - } - } - } - - /// - /// Returns the value of the wrapped member for the current instance - /// - /// The target instance to use to read the value from - /// This method doesn't ensure that the accessor is available - /// The dynamic accessor is not available - [Pure] - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public object DangerousGetValue(object? instance) => _Getter!(instance); - - /// - /// Returns the value of the wrapped member for the current instance - /// - /// The target instance to use to read the value from - [Pure] - public object GetValue(object? instance) - { - PreloadAccessor(); - return _Getter!(instance); - } - - /// - /// A that represents a getter for a specific member - /// - /// The source object to get the member from - /// The value of the member, upcast to - private delegate object Getter(object? obj); - - /// - /// Gets or sets the list of parent members to access the current one from the root instance - /// - public IReadOnlyList? Parents { get; set; } - - /// - /// Builds a dynamic IL method to retrieve the value of the current member - /// - [Pure] - private Getter BuildDynamicGetter() - { - return DynamicMethod.New(il => - { - // Info for hierarchical access - ReadableMember[] hierarchy = (Parents ?? Array.Empty()).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); - il.EmitCastOrUnbox(hierarchy[0].DeclaringType); - } - - // Unroll the member access - foreach (ReadableMember member in hierarchy) - { - il.EmitReadMember(member); - } - - // 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); - }); - } - } -} diff --git a/src/ComputeSharp.Shaders/Translation/Models/ReadableMember.cs b/src/ComputeSharp.Shaders/Translation/Models/ReadableMember.cs index 5b26c690..d20dd74e 100644 --- a/src/ComputeSharp.Shaders/Translation/Models/ReadableMember.cs +++ b/src/ComputeSharp.Shaders/Translation/Models/ReadableMember.cs @@ -1,4 +1,6 @@ using System; +using System.Collections.Generic; +using System.Diagnostics.Contracts; using System.Reflection; namespace ComputeSharp.Shaders.Translation.Models @@ -6,13 +8,8 @@ namespace ComputeSharp.Shaders.Translation.Models /// /// A that wraps a readable member of another and provides access to it /// - internal sealed partial class ReadableMember + internal sealed class ReadableMember { - /// - /// The id of the current member - /// - private readonly string Id; - /// /// The object wrapped by the current instance /// @@ -25,7 +22,6 @@ namespace ComputeSharp.Shaders.Translation.Models private ReadableMember(MemberInfo memberInfo) { // General properties - Id = $"{memberInfo.DeclaringType.FullName}{Type.Delimiter}{memberInfo.Name}"; Member = memberInfo; Name = memberInfo.Name; DeclaringType = memberInfo.DeclaringType; @@ -66,6 +62,26 @@ namespace ComputeSharp.Shaders.Translation.Models /// public Type MemberType { get; } + /// + /// Gets or sets the list of parent members to access the current one from the root instance + /// + public IReadOnlyList? Parents { get; set; } + + /// + /// Returns the value of the wrapped member for the current instance + /// + /// The target instance to use to read the value from + [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") + }; + } + /// /// Converts a object into a instance /// diff --git a/src/ComputeSharp.Shaders/Translation/ShaderLoader.IL.cs b/src/ComputeSharp.Shaders/Translation/ShaderLoader.IL.cs index 5e365681..5ee94f91 100644 --- a/src/ComputeSharp.Shaders/Translation/ShaderLoader.IL.cs +++ b/src/ComputeSharp.Shaders/Translation/ShaderLoader.IL.cs @@ -51,6 +51,13 @@ namespace ComputeSharp.Shaders.Translation [Pure] public DispatchData GetDispatchData(Action 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.Shared.Rent(_ResourcesCount); byte[] variables = ArrayPool.Shared.Rent(_VariablesByteSize); @@ -63,7 +70,6 @@ namespace ComputeSharp.Shaders.Translation Unsafe.Add(ref Unsafe.As(ref r1), 2) = z; // Invoke the dynamic method to extract the captured data - DispatchDataLoader loader = _DispatchDataLoader ??= BuildDispatchDataLoader(); loader(action.Target, ref r0, ref r1); return new DispatchData(resources, _ResourcesCount, variables, _VariablesByteSize); diff --git a/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs b/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs index ca422307..dfc6a2ae 100644 --- a/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs +++ b/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs @@ -223,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(); } /// diff --git a/tests/ComputeSharp.Tests.Internals/BufferTests.cs b/tests/ComputeSharp.Tests.Internals/BufferTests.cs deleted file mode 100644 index 0ef723d2..00000000 --- a/tests/ComputeSharp.Tests.Internals/BufferTests.cs +++ /dev/null @@ -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 buffer = (ConstantBuffer)Gpu.Default.AllocateConstantBufferFromReflectedValues(values); - Vector4[] data = buffer.GetData(); - ref byte r0 = ref Unsafe.As(ref data[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, 24)); // 24 -> 27, sizeof(float) == 4 - Vector4 v4 = Unsafe.As(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); - } - } -}