BeanCheeseBurrito / Flecs.NET

A C# wrapper for flecs
MIT License
145 stars 18 forks source link

Use C# arrays as pluggable storage for managed types #21

Open BeanCheeseBurrito opened 7 months ago

BeanCheeseBurrito commented 7 months ago

When pluggable storages are added to flecs, pinned C# arrays should be used as storage for managed types.

Performance - Special unboxing code is required per every iteration in the current design. Using plain C# arrays will remove this overhead and bring the performance of managed component iteration on par with native C# ECS frameworks/libraries.

Memory Allocations - This will greatly reduce memory consumption due to only needing a single GCHandle and Box<T> object to be allocated per column instead of per component.

Debugging - With the current setup, it is not possible to inspect the contents of a column for both managed and unmanaged types inside a debugger due to the GCHandle indirection and unboxing step required for managed objects. Switching to C# array storage will replace the Column<T> type with the Span<T> type and allow the contents of components to be displayed in the debugger.

Pointer APIs - Pointer-based APIs in Flecs.NET are currently restricted to unmanaged types only. This restriction can be removed entirely as using pinned C# arrays will allow us to retrieve pointers to managed component references. This is a prerequisite to being able to properly implement serialization and deserialization for managed types.

// Pointer-based iteration
Query.Iter((Iter it, Position* p, Velocity* v) => { });

// Span-based iteration
Query.Iter((Iter it, Span<Position> p, Span<Velocity> v) => { });

// Get raw pointers to managed objects.
Position* p = e.GetPtr<Position>();
BeanCheeseBurrito commented 3 weeks ago

Allocating pinned arrays for managed types is only possible in .NET 8 and above. The minimum target version has been changed from .NET Standard 2.1 to .NET 8 in this PR https://github.com/BeanCheeseBurrito/Flecs.NET/pull/42. The Unity package will no longer be updated.