You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
31 lines
1.1 KiB
31 lines
1.1 KiB
2 years ago
|
using System;
|
||
|
using System.Runtime.CompilerServices;
|
||
|
using static flecs_hub.flecs;
|
||
|
|
||
|
namespace gaemstone.ECS;
|
||
|
|
||
|
public static class ComponentExtensions
|
||
|
{
|
||
|
public unsafe static EntityRef InitComponent(this EntityRef entity, Type type)
|
||
|
=> (EntityRef)typeof(ComponentExtensions)
|
||
|
.GetMethod(nameof(InitComponent), new[] { typeof(EntityRef) })!
|
||
|
.MakeGenericMethod(type).Invoke(null, new[]{ entity })!;
|
||
|
|
||
|
public unsafe static EntityRef InitComponent<T>(this EntityRef entity)
|
||
|
{
|
||
|
if (typeof(T).IsPrimitive) throw new ArgumentException(
|
||
|
"Must not be primitive");
|
||
|
if (typeof(T).IsValueType && RuntimeHelpers.IsReferenceOrContainsReferences<T>()) throw new ArgumentException(
|
||
|
"Struct component must satisfy the unmanaged constraint. " +
|
||
|
"Consider making it a class if you need to store references.");
|
||
|
|
||
|
var size = Unsafe.SizeOf<T>();
|
||
|
var typeInfo = new ecs_type_info_t
|
||
|
{ size = size, alignment = size };
|
||
|
var componentDesc = new ecs_component_desc_t
|
||
|
{ entity = entity, type = typeInfo };
|
||
|
ecs_component_init(entity.World, &componentDesc);
|
||
|
return entity.CreateLookup(typeof(T));
|
||
|
}
|
||
|
}
|