98 lines
2.6 KiB
C
98 lines
2.6 KiB
C
/**
|
|
* Copyright (c) 2026 Dominic Masters
|
|
*
|
|
* This software is released under the MIT License.
|
|
* https://opensource.org/licenses/MIT
|
|
*/
|
|
|
|
#include "entitymanager.h"
|
|
#include "component/display/entityposition.h"
|
|
#include "util/memory.h"
|
|
#include "assert/assert.h"
|
|
|
|
void entityInit(const entityid_t entityId) {
|
|
entity_t *ent = &ENTITY_MANAGER.entities[entityId];
|
|
|
|
memoryZero(ent, sizeof(entity_t));
|
|
|
|
// Mark all component types not using this entity.
|
|
for(
|
|
componenttype_t compType = 0;
|
|
compType < COMPONENT_TYPE_COUNT;
|
|
compType++
|
|
) {
|
|
ENTITY_MANAGER.entitiesWithComponent[
|
|
compType * ENTITY_COUNT_MAX + entityId
|
|
] = COMPONENT_ID_INVALID;
|
|
}
|
|
|
|
ent->state |= ENTITY_STATE_ACTIVE;
|
|
}
|
|
|
|
componentid_t entityAddComponent(
|
|
const entityid_t entityId,
|
|
const componenttype_t type
|
|
) {
|
|
componentindex_t compInd;
|
|
entity_t *ent = &ENTITY_MANAGER.entities[entityId];
|
|
|
|
for(componentid_t i = 0; i < ENTITY_COMPONENT_COUNT_MAX; i++) {
|
|
compInd = componentGetIndex(entityId, i);
|
|
if(ENTITY_MANAGER.components[compInd].type != COMPONENT_TYPE_NULL) {
|
|
assertTrue(
|
|
ENTITY_MANAGER.components[compInd].type != type,
|
|
"Entity already has component of this type"
|
|
);
|
|
continue;
|
|
}
|
|
componentInit(entityId, i, type);
|
|
ENTITY_MANAGER.entitiesWithComponent[
|
|
type * ENTITY_COUNT_MAX + entityId
|
|
] = i;
|
|
return i;
|
|
}
|
|
|
|
assertUnreachable("Entity has no more component slots available");
|
|
return COMPONENT_ID_INVALID;
|
|
}
|
|
|
|
componentid_t entityGetComponent(
|
|
const entityid_t entityId,
|
|
const componenttype_t type
|
|
) {
|
|
componentid_t compId = ENTITY_MANAGER.entitiesWithComponent[
|
|
type * ENTITY_COUNT_MAX + entityId
|
|
];
|
|
if(compId == COMPONENT_ID_INVALID) return compId;
|
|
assertTrue(
|
|
ENTITY_MANAGER.components[componentGetIndex(entityId, compId)].type == type,
|
|
"Component type mismatch"
|
|
);
|
|
return compId;
|
|
}
|
|
|
|
void entityDisposeDeep(const entityid_t entityId) {
|
|
componentid_t posComp = entityGetComponent(entityId, COMPONENT_TYPE_POSITION);
|
|
if(posComp != COMPONENT_ID_INVALID) {
|
|
entityPositionDisposeDeep(entityId, posComp);
|
|
} else {
|
|
entityDispose(entityId);
|
|
}
|
|
}
|
|
|
|
void entityDispose(const entityid_t entityId) {
|
|
componentindex_t compInd;
|
|
entity_t *ent = &ENTITY_MANAGER.entities[entityId];
|
|
|
|
for(componentid_t i = 0; i < ENTITY_COMPONENT_COUNT_MAX; i++) {
|
|
compInd = componentGetIndex(entityId, i);
|
|
componenttype_t type = ENTITY_MANAGER.components[compInd].type;
|
|
if(type == COMPONENT_TYPE_NULL) continue;
|
|
ENTITY_MANAGER.entitiesWithComponent[
|
|
type * ENTITY_COUNT_MAX + entityId
|
|
] = COMPONENT_ID_INVALID;
|
|
componentDispose(entityId, i);
|
|
}
|
|
|
|
ent->state = 0;
|
|
} |