zecsy/zecsy.h
2025-03-20 20:09:25 +03:00

140 lines
2.4 KiB
C

#ifndef __ZECSY_H
#define __ZECSY_H
#ifndef ZECSY_MAX_COMPONENTS
#define ZECSY_MAX_COMPONENTS 128
#endif // !ZECSY_MAX_COMPONENTS
#define STB_DS_IMPLEMENTATION
#include "stb_ds.h"
#include <stdlib.h>
#include <stddef.h>
#include <stdint.h>
typedef struct
{
uint32_t bitset[(ZECSY_MAX_COMPONENTS + 31) / 32];
} archetype_signature;
#define RESERVED_ENTITY_ID 0
typedef size_t entity_id;
typedef size_t component_id;
typedef struct
{
const char* name;
component_id id;
size_t size;
} component_info;
typedef struct
{
struct{entity_id key; archetype_signature value;}* entity_map;
entity_id entity_id_counter;
entity_id alive_entities;
} world;
void make_world(world** w);
void destroy_world(world** w);
entity_id make_entity(world* w);
void destroy_entity(world* w, entity_id e);
int is_alive(world* w, entity_id e);
archetype_signature arhetype_of(world* w, entity_id e);
int is_same(archetype_signature a, archetype_signature b);
#endif // !__ZECSY_H
#define ZECSY_IMPLEMENTATION //TODO: REMOVE
#ifdef ZECSY_IMPLEMENTATION
void make_world(world** w)
{
if(!w)
return;
(*w) = malloc(sizeof(world));
(**w) = (world)
{
.entity_map = NULL,
.entity_id_counter = RESERVED_ENTITY_ID + 1,
.alive_entities = 0,
};
}
void destroy_world(world** w)
{
if(!w || !(*w))
return;
if((*w)->entity_map)
hmfree((*w)->entity_map);
free((*w));
(*w) = NULL;
}
entity_id make_entity(world* w)
{
entity_id e = RESERVED_ENTITY_ID;
if(w)
{
e = w->entity_id_counter++;
hmput(w->entity_map, e, (archetype_signature){0});
w->alive_entities++;
}
return e;
}
void destroy_entity(world* w, entity_id e)
{
if(w)
hmdel(w->entity_map, e);
}
int is_alive(world* w, entity_id e)
{
if(w)
{
return hmgeti(w->entity_map, e) != -1;
}
return 0;
}
archetype_signature arhetype_of(world* w, entity_id e)
{
if(w)
{
int index = hmgeti(w->entity_map, e);
if(index >= 0)
{
return w->entity_map[index].value;
}
}
return (archetype_signature){0};
}
int is_same(archetype_signature a, archetype_signature b)
{
for(int i = 0; i < sizeof(a.bitset) / sizeof(a.bitset[0]); ++i)
{
if(a.bitset[i] != b.bitset[i])
{
return 0;
}
}
return 1;
}
#endif // ZECSY_IMPLEMENTATION