genaray / Arch

A high-performance C# based Archetype & Chunks Entity Component System (ECS) with optional multithreading.
Apache License 2.0
867 stars 73 forks source link

Alternative to Dictionary<T, int> #67

Closed Donaut closed 1 year ago

Donaut commented 1 year ago

In dotnext they created a generic class with a static read-only int field each time somebody accesses the generic class with a new type the static field is incremented. And thus creating a compile-time dictionary. TypeMap There was a discussion about it too somewhere in the c# runtime repository but sadly I lost that.

genaray commented 1 year ago

Thanks! :) Haven't seen that one. I will take a look at it.

Donaut commented 1 year ago

Hello, I have good news :). The idea works like a charm. Below is a sample code of how it looks.

var world = new World();

// Approach 1: Builders
var builder = new ArcheTypeInfo.Builder();
builder.AddComponent<int>();
builder.AddComponent<ulong>();
var archeTypeInfo = builder.Build(); // We want to avoid creating new ArcheTypes every time so we need a way to locate already existing ArcheTypes. ArcheTypeInfo is a struct that is used as a dictionary key for locating already existing ArcheTypes.
var entity = world.CreateEntity(archeTypeInfo);

// Approach 2: Generic methods that use the builder internally.
// world.CreateEntity<T0..T9>(in T0..T9) If we dont want to use the builder approach. It's a little bit slower than the builder approach.

// Set method with multiple generics so we can quickly assign data for each component type.
entity.Set<T0..T9>(in T0..T9);
genaray commented 1 year ago

Thats great! :)

Just some questions:

However i think the .create call with generics should stay aswell since thats a nice api for quick prototyping, it also sets the values in the same step which is also quite nice :)

Donaut commented 1 year ago

Currently, I don't have a fully working sample. There is no concept of ComponenTypes. A Type is just converted into an index, which is then used to place them inside an array. The more components there is the bigger the array.

genaray commented 1 year ago

There is no concept of ComponenTypes

Well this is a problem, i think such an approach does not exclude the concept of componenttypes however. ComponentTypes are pretty important for the underlying chunks and store meta data such as byte size and in the future if the component is managed or not ^^ But if a type can be converted to an index, it can also be converted to the componenttype with that approach i guess.