Files

53 lines
1.8 KiB
C#

using System.Numerics;
using System.Runtime.InteropServices;
using System.Text.Json;
namespace ReFuel.Gltf.Serialization
{
public static class SerdesUtil
{
public static T ToSingleMatrix<T>(this JsonElement element, int rows, int columns, in T identity = default) where T : unmanaged
{
if (element.ValueKind != JsonValueKind.Array)
throw new Exception("Expected matrix to be an array.");
var enumerator = element.EnumerateArray();
T m = identity;
Span<float> view = MemoryMarshal.Cast<T, float>(MemoryMarshal.CreateSpan(ref m, 1));
for (int x = 0; x < columns; x++)
for (int y = 0; y < rows && enumerator.MoveNext(); y++)
{
if (!enumerator.Current.TryGetSingle(out float v))
throw new Exception("Expected a floating point number as matrix elements.");
view[x + columns * y] = v;
}
return m;
}
public static T ToSingleVector<T>(this JsonElement element, int components, in T identity = default)
where T : unmanaged
{
if (element.ValueKind != JsonValueKind.Array)
throw new Exception("Expected vector to be an array.");
var enumerator = element.EnumerateArray();
T vec = identity;
Span<float> view = MemoryMarshal.Cast<T, float>(MemoryMarshal.CreateSpan(ref vec, 1));
for (int i = 0; i < components && enumerator.MoveNext(); i++)
{
if (!enumerator.Current.TryGetSingle(out float v))
throw new Exception("Expected a floating point number as vector elements.");
view[i] = v;
}
return vec;
}
}
}