Nerfed/Nerfed.Runtime/Serialization/ComponentHelper.cs

68 lines
2.8 KiB
C#
Raw Permalink Normal View History

2024-11-02 21:59:35 +01:00
using System.Numerics;
using ImGuiNET;
using MoonTools.ECS;
using Nerfed.Runtime.Components;
namespace Nerfed.Runtime.Serialization;
public static class ComponentHelper
{
2024-11-13 21:11:50 +01:00
// Auto generate this.
2024-11-02 21:59:35 +01:00
public static readonly Dictionary<Type, Func<World, Entity, ValueType>> GetComponentByType = new()
{
{ typeof(LocalTransform), (world, entity) => world.Get<LocalTransform>(entity) },
{ typeof(Root), (world, entity) => world.Get<Root>(entity) },
};
2024-11-13 21:11:50 +01:00
// Auto generate this.
2024-11-02 21:59:35 +01:00
public static readonly Dictionary<Type, Action<World, Entity, ValueType>> SetComponentByType = new()
{
{ typeof(LocalTransform), (world, entity, component) => world.Set(entity, (LocalTransform)component) },
{ typeof(Root), (world, entity, component) => world.Set(entity, (Root)component) },
};
2024-11-13 21:11:50 +01:00
// Auto generate this, but it should only contain user assignable components (so something like 'root' should be excluded).
// Maybe use an attribute for this.
public static readonly Dictionary<Type, Action<World, Entity>> AddComponentByType = new()
{
{ typeof(LocalTransform), (world, entity) => world.Set(entity, LocalTransform.Identity) },
};
2024-11-02 21:59:35 +01:00
2024-11-13 21:11:50 +01:00
// Auto generate this, but also keep the option for 'custom inspectors'.
// Maybe via attribute?
2024-11-02 21:59:35 +01:00
public static readonly Dictionary<Type, Action<World, Entity>> ComponentInspectorByType = new()
{
{
typeof(LocalTransform), (world, entity) =>
{
(Vector3 position, Quaternion rotation, Vector3 scale) = world.Get<LocalTransform>(entity);
Vector3 eulerAngles = MathEx.ToEulerAngles(rotation);
eulerAngles = new Vector3(float.RadiansToDegrees(eulerAngles.X), float.RadiansToDegrees(eulerAngles.Y), float.RadiansToDegrees(eulerAngles.Z));
bool isDirty = false;
ImGui.BeginGroup();
ImGui.Text($"{nameof(LocalTransform)}");
2024-11-13 21:11:50 +01:00
isDirty |= ImGui.DragFloat3("Position", ref position, 0.2f, float.MinValue, float.MaxValue /*, "%f0 m" */); // TODO: right format.
2024-11-02 21:59:35 +01:00
isDirty |= ImGui.DragFloat3("Rotation", ref eulerAngles);
isDirty |= ImGui.DragFloat3("Scale", ref scale);
ImGui.EndGroup();
if (!isDirty)
{
return;
}
eulerAngles = new Vector3(float.DegreesToRadians(eulerAngles.X), float.DegreesToRadians(eulerAngles.Y), float.DegreesToRadians(eulerAngles.Z));
world.Set(entity, new LocalTransform(position, MathEx.ToQuaternion(eulerAngles), scale));
}
},
{
typeof(Root), (world, entity) =>
{
ImGui.BeginGroup();
ImGui.Text($"{nameof(Root)}");
ImGui.EndGroup();
}
},
};
}