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 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; } } }