bubel-ecs/source/ecs/manager.d

639 lines
19 KiB
D

module ecs.manager;
import std.experimental.allocator.mallocator : Mallocator, AlignedMallocator;
import std.experimental.allocator;
import std.traits;
import std.algorithm : max;
import std.conv : to;
import core.stdc.string;
import core.stdc.stdlib;
import ecs.system;
import ecs.entity;
import ecs.vector;
import ecs.hash_map;
import ecs.id_manager;
import ecs.entity_allocator;
alias gEM = EntityManager.instance;
class EntityManager
{
static void initialize()
{
instance = Mallocator.instance.make!EntityManager;
}
static void destory()
{
Mallocator.instance.dispose(instance);
instance = null;
}
void registerSystem(Sys)(int priority)
{
alias types = Parameters!(Sys.update);
System system;
static string genCall()()
{
string ret = "s.update(*cast(Entity*)data_pointer,";
foreach (i; 1 .. (Parameters!(Sys.update)).length)
{
ret ~= "*cast(types[" ~ i.to!string ~ "]*)(data_pointer + data.deltas[" ~ (i - 1)
.to!string ~ "]),";
}
ret ~= ");";
return ret;
}
static string genCompList()()
{
string ret = "uint comp;";
foreach (i; 1 .. (Parameters!(Sys.update)).length)
{
ret ~= "comp = components_map.get(types[" ~ i.to!string ~ "].stringof, ushort.max);\n
if(comp == ushort.max)assert(0,\"Can't register system \\\"" ~ Sys.stringof
~ "\\\" due to non existing component \\\"\"~types[" ~ i.to!string ~ "].stringof~\"\\\".\");
system.m_components[" ~ (i - 1)
.to!string ~ "] = comp;";
}
return ret;
}
static if (hasMember!(Sys, "update"))
{
static void callUpdate(ref CallData data, void* entity)
{
static if (hasMember!(Sys, "update"))
{
Sys* s = cast(Sys*) data.system.m_system_pointer;
EntitiesBlock* block = data.info.first_block;
while (block !is null)
{
void* data_pointer = block.dataBegin();
foreach (i; 0 .. block.entities_count)
{
mixin(genCall());
data_pointer += data.info.size;
}
block = block.next_block;
}
}
}
system.m_update = &callUpdate;
}
static if (hasMember!(Sys, "onEnable"))
{
static void callEnable(void* system_pointer)
{
Sys* s = cast(Sys*) system_pointer;
s.onEnable();
}
system.m_enable = &callEnable;
}
static if (hasMember!(Sys, "onDisable"))
{
static void callDisable(void* system_pointer)
{
Sys* s = cast(Sys*) system_pointer;
s.onDisable();
}
system.m_disable = &callDisable;
}
system.m_system_pointer = cast(void*) Mallocator.instance.make!Sys;
system.m_priority = priority;
system.m_components = Mallocator.instance.makeArray!uint(types.length - 1);
mixin(genCompList());
systems.add(system);
systems[$ - 1].enable();
foreach (info; &entities_infos.byValue)
{
addEntityCaller(*info, cast(uint)systems.length - 1);
}
updateEntityCallers();
}
void registerComponent(Comp)()
{
ComponentInfo info;
static if (!(hasMember!(Comp, "component_id")) || !is(typeof(Comp.component_id) == ushort))
{
static assert(0, "Component should have \"__gshared ushort component_id");
}
static if (hasMember!(Comp, "onDestroy") && isFunction!(Comp.onDestroy)
&& is(ReturnType!(Comp.onDestroy) == void)
&& Parameters!(Comp.onDestroy).length == 0)
{
static void callDestroy(void* pointer)
{
(cast(Comp*) pointer).onDestroy();
}
info.destroy_callback = &callDestroy;
}
info.size = Comp.sizeof;
info.aligment = Comp.alignof; //8;
info.init_data = Mallocator.instance.makeArray!ubyte(Comp.sizeof);
*cast(Comp*) info.init_data.ptr = Comp.init; // = Comp();
components.add(info);
Comp.component_id = cast(ushort)(components.length - 1);
components_map.add(Comp.stringof, cast(uint)(components.length - 1));
}
void update()
{
foreach (info; &entities_infos.byValue)
{
foreach (data; info.callers)
{
if (data.system.enabled)
(cast(SytemFuncType) data.system.m_update)(data, null); //caller(call_data,null);
}
}
}
static void alignNum(ref ushort num, ushort aligment)
{
num = cast(ushort)((num + aligment - 1) & (-cast(int) aligment)); //num += aligment - (num & (aligment - 1));
}
EntityTemplate* allocateTemplate(ushort[] components_ids)
{
extern (C) static int compareUShorts(const void* a, const void* b)
{
ushort _a = *cast(ushort*) a;
ushort _b = *cast(ushort*) b;
if (_a < _b)
return -1;
else if (_a == _b)
return 0;
else
return 1;
}
ushort[] ids = (cast(ushort*) alloca(ushort.sizeof * components_ids.length))[0
.. components_ids.length];
ids[0 .. $] = components_ids[];
qsort(ids.ptr, ids.length, ushort.sizeof, &compareUShorts);
{
uint j = 1;
foreach (i; 1 .. ids.length)
{
if (ids[i] != ids[j - 1])
{
ids[j] = ids[i];
j++;
}
else
debug assert(0, "Duplicated components in template!!!");
}
ids = ids[0 .. j];
}
EntityInfo* info = getEntityInfo(ids);
EntityTemplate* temp = Mallocator.instance.make!EntityTemplate;
temp.entity_data = Mallocator.instance.makeArray!ubyte(info.size);
temp.info = info;
//fill components with default data
foreach (comp; info.components)
{
temp.entity_data[info.deltas[comp] .. info.deltas[comp] + components[comp].size]
= components[comp].init_data;
}
return temp;
}
EntityInfo* getEntityInfo(ushort[] ids)
{
EntityInfo* info = entities_infos.get(ids, null);
if (info is null)
{
info = Mallocator.instance.make!EntityInfo;
info.components = Mallocator.instance.makeArray(ids);
info.deltas = Mallocator.instance.makeArray!ushort(ids[$ - 1] + 1);
info.size = EntityID.sizeof;
info.alignment = EntityID.alignof;
foreach (i, id; ids)
{
info.alignment = max(info.alignment, components[id].aligment);
alignNum(info.size, components[id].aligment);
info.deltas[id] = info.size;
info.size += components[id].size;
}
alignNum(info.size, info.alignment);
foreach (uint i, ref system; systems)
{
if (system.m_update is null)
continue;
addEntityCaller(*info, i);
}
updateEntityCallers();
entities_infos.add(info.components, info);
}
return info;
}
void updateEntityCallers()
{
foreach(entity;&entities_infos.byValue)
{
foreach(ref caller;entity.callers)
{
caller.system = &systems[caller.system_id];
}
}
}
void addEntityCaller(ref EntityInfo entity, uint system_id)
{
System* system = &systems[system_id];
CallData call_data = CallData(system_id, system, &entity, null);
ushort[] deltas = (cast(ushort*) alloca(system.m_components.length * ushort.sizeof))[0
.. system.m_components.length];
foreach (i, id; system.m_components)
{
deltas[i] = ushort.max;
foreach (i2, id2; entity.components)
{
if (id2 == id)
{
deltas[i] = entity.deltas[id2];
break;
}
}
if (deltas[i] == ushort.max)
{
deltas = null;
break;
}
}
if (deltas)
{
call_data.deltas = Mallocator.instance.makeArray(deltas); //Mallocator.instance.makeArray!ushort(system.m_components.length);
uint index = 0;
for(;index<entity.callers.length;index++)
{
CallData* caller = &entity.callers[index];
if(caller.system.priority >= call_data.system.priority)break;
}
entity.callers.add(call_data,index);
}
}
Entity* getEntity(EntityID id)
{
return cast(Entity*) id_manager.getEntityPointer(id);
}
void addComponents(Components...)(EntityID entity_id, Components comps)
{
const uint num = Components.length;
Entity* entity = id_manager.getEntityPointer(entity_id);
EntitiesBlock* block = getMetaData(entity);
EntityInfo* info = block.type_data;
ushort[] ids = (cast(ushort*) alloca(ushort.sizeof * (info.components.length + num)))[0
.. info.components.length + num];
ushort[num] new_ids;
static foreach (i, comp; Components)
{
new_ids[i] = comp.component_id;
}
void*[num] pointers;
static foreach (i, comp; comps)
{
pointers[i] = &comp;
}
uint j = 0;
uint k = 0;
foreach (ref id; ids)
{
if (k >= new_ids.length)
{
id = info.components[j++];
continue;
}
if (j >= info.components.length)
{
id = new_ids[k++];
continue;
}
debug if (new_ids[k] == info.components[j])
assert(0, "Trying to add already existing component!");
if (new_ids[k] < info.components[j])
{
id = new_ids[k++];
}
else
id = info.components[j++];
}
EntityInfo* new_info = getEntityInfo(ids);
EntitiesBlock* new_block = findBlockWithFreeSpace(new_info);
void* start = new_block.dataBegin() + new_block.entities_count * new_info.size;
Entity* new_entity = cast(Entity*) start;
new_entity.id = entity.id;
new_entity.updateID();
new_block.entities_count++;
//removeEntityNoID(entity, block);
j = 0;
k = 0;
foreach (ref id; ids)
{
if (k >= new_ids.length)
{
memcpy(cast(void*) new_entity + new_info.deltas[id],
cast(void*) entity + info.deltas[info.components[j]],
components[info.components[j]].size); //id = info.components[j++];
j++;
}
else if (j >= info.components.length)
{
memcpy(cast(void*) new_entity + new_info.deltas[id],
pointers[k], components[new_ids[k]].size); //id = new_ids[k++];
k++;
}
else if (id == new_ids[k])
{
memcpy(cast(void*) new_entity + new_info.deltas[id],
pointers[k], components[new_ids[k]].size); //id = new_ids[k++];
k++;
}
else
{
memcpy(cast(void*) new_entity + new_info.deltas[id],
cast(void*) entity + info.deltas[info.components[j]],
components[info.components[j]].size); //id = info.components[j++];
j++;
}
}
removeEntityNoID(entity, block);
}
void freeTemplate(EntityTemplate* template_)
{
Mallocator.instance.dispose(template_.entity_data);
Mallocator.instance.dispose(template_);
}
ref Entity addEntity(EntityTemplate* tmpl)
{
EntitiesBlock* block = findBlockWithFreeSpace(tmpl.info);
void* start = block.dataBegin() + block.entities_count * tmpl.info.size;
memcpy(start, tmpl.entity_data.ptr, tmpl.info.size);
Entity* entity = cast(Entity*) start;
entity.id = id_manager.getNewID();
entity.updateID();
block.entities_count++;
return *entity;
}
EntitiesBlock* findBlockWithFreeSpace(EntityInfo* info)
{
EntitiesBlock* previous_block;
EntitiesBlock* block = info.first_with_free_space;
while (1)
{
if (block is null)
{
block = cast(EntitiesBlock*) allocator.getBlock();//AlignedMallocator.instance.alignedAllocate(page_size, page_size);
*block = EntitiesBlock(info);
if (previous_block is null)
{
info.first_block = block;
block.id = 0;
}
else
{
previous_block.next_block = block;
block.id = previous_block.id + 1;
}
info.first_with_free_space = block;
break; // new block certainly has free space
}
// check if there is enought space
if (block.dataDelta() + (block.entities_count + 1) * info.size > page_size)
{
previous_block = block;
block = block.next_block;
continue;
}
info.first_with_free_space = block;
break; // block exists and bounds check passed
}
return block;
}
void removeEntity(EntityID id)
{
//get entity and block meta data pointers
Entity* entity = id_manager.getEntityPointer(id);
if (entity is null)
return; //return if entity doesn't exist
EntitiesBlock* block = getMetaData(entity);
id_manager.releaseID(id); //release id from manager
removeEntityNoID(entity, block, true);
}
private void removeEntityNoID(Entity* entity, EntitiesBlock* block,
bool call_destructors = false)
{
//pos is Entity number in block
void* data_begin = block.dataBegin();
uint pos = cast(int)(cast(void*) entity - data_begin) / block.type_data.size;
block.entities_count--;
//set "first_with_free_space" if should it be
if (block.type_data.first_with_free_space.id > block.id)
block.type_data.first_with_free_space = block;
if(call_destructors)
{
void* data = data_begin + pos * block.type_data.size;
foreach(comp;block.type_data.components)
{
if(components[comp].destroy_callback)
{
components[comp].destroy_callback(data + block.type_data.deltas[comp]);
}
}
}
if (pos == block.entities_count)
return;
//copy memory of last entity to position of removed entity
void* src = data_begin + block.entities_count * block.type_data.size;
void* dst = data_begin + pos * block.type_data.size;
memcpy(dst, src, block.type_data.size);
//update pointer for moved entity ID
entity = cast(Entity*) dst;
entity.updateID();
}
/************************************************************************************************************************
*functions return MetaData of page.
*
*params:
*pointer = pointer to any data of entity (i.e. component data pointer)
*/
EntitiesBlock* getMetaData(void* pointer)
{
return cast(EntitiesBlock*)(cast(size_t) pointer & (~cast(size_t)(page_size - 1)));
}
struct ComponentInfo
{
ushort size;
ushort aligment;
ubyte[] init_data;
void function(void* pointer) destroy_callback;
}
/************************************************************************************************************************
*Entity type info.
*/
struct EntityInfo
{
///entity components
ushort[] components;
///deltas in memory for components
ushort[] deltas;
///aligment of whole entity
ushort alignment;
///size of entity (with alignment respect)
ushort size;
///pointer to first block/page
EntitiesBlock* first_block;
///a hint for allocations
EntitiesBlock* first_with_free_space; // a hint for allocations, should have empty space in it but doesn't have to
///array of CallData. Contain data for System calls.
Vector!(CallData) callers;
}
/************************************************************************************************************************
*Meta data of every block of entities (contained at the begining of block).
*/
struct EntitiesBlock
{
///return distance (in bytes) from begin of block to data
uint dataDelta()
{
ushort dif = EntitiesBlock.sizeof;
alignNum(dif, type_data.alignment);
return dif;
}
///return pointer to first element in block
void* dataBegin()
{
ushort dif = EntitiesBlock.sizeof;
alignNum(dif, type_data.alignment);
return cast(void*)&this + dif;
}
///pointer to Entity type info
EntityInfo* type_data;
///number of entities in block
uint entities_count;
///block id
uint id;
///pointer to next block/page
EntitiesBlock* next_block;
//there is a loooot of data (4kB, pure magic)
}
/************************************************************************************************************************
*Structure with data used to calling System calls.
*/
struct CallData
{
///system ID. Used to update system pointer after system reload.
uint system_id;
///pointer to used system
System* system;
///poiner to Entity type info
EntityManager.EntityInfo* info;
///deltas for components
ushort[] deltas;
}
alias SytemFuncType = void function(ref EntityManager.CallData data, void* entity);
///Single page size. Must be power of two.
enum page_size = 4096;
///Number of pages in block.
enum pages_in_block = 128;
IDManager id_manager;
EntityAllocator allocator;
HashMap!(ushort[], EntityInfo*) entities_infos;
HashMap!(string, uint) components_map;
Vector!System systems;
Vector!ComponentInfo components;
__gshared EntityManager instance;
}
/*
static ulong defaultHashFunc(T)(auto ref T t)
{
ulong ret = 0;
foreach(id;t)
{
ret = ret
}
}*/