commit 6ac4021fa425b7e10320dd1a80f53c78205091fa
parent 3d3d4d89e5a3cf96fc92664cdfbd8df224c09317
Author: bsandro <email@bsandro.tech>
Date: Mon, 7 Sep 2026 23:21:46 +0300
component finder by type helper
Diffstat:
5 files changed, 28 insertions(+), 11 deletions(-)
diff --git a/components/ranged.h b/components/ranged.h
@@ -0,0 +1,6 @@
+#pragma once
+
+typedef struct Ranged {
+ int agility;
+ int range;
+} Ranged;
diff --git a/core/ecs/entity.c b/core/ecs/entity.c
@@ -18,3 +18,12 @@ bool Entity_Add_Component(Entity *e, Component c) {
arrput(e->components, c);
return true;
}
+
+Component * Entity_Find_Component(Entity *e, ComponentType t) {
+ for (int i=0;i<arrlen(e->components);++i) {
+ if (e->components[i].type==t) {
+ return &e->components[i];
+ }
+ }
+ return NULL;
+}
diff --git a/core/ecs/entity.h b/core/ecs/entity.h
@@ -10,3 +10,4 @@ typedef struct Entity {
Entity * Entity_New(int id);
bool Entity_Add_Component(Entity *e, Component c);
+Component * Entity_Find_Component(Entity *e, ComponentType t);
diff --git a/main.c b/main.c
@@ -9,7 +9,7 @@ int main(int argc, char **argv) {
World w;
Map_init(&w.map, 3, 4);
puts("map init ok");
-
+ int turn = 0;
System actions = {0};
actions.run = actions_run;
World_addSystem(&w, &actions);
@@ -27,9 +27,13 @@ int main(int argc, char **argv) {
return 1;
fin:
- int turn = 0;
while (World_runSystems(&w)) {
printf("[turn %3d] world systems run ok\n", turn++);
+ // safeguard
+ if (turn >= 1000) {
+ puts("turns limit reached");
+ break;
+ }
}
puts("ok");
diff --git a/systems/actions.c b/systems/actions.c
@@ -1,6 +1,7 @@
#include <stdbool.h>
#include <stdio.h>
#include "stb_ds.h"
+#include "core/ecs/entity.h"
#include "systems/actions.h"
#include "core/world.h"
@@ -8,15 +9,11 @@ bool actions_run(World *w) {
printf("actions_run world %p\n", (void *)w);
bool ret = false;
for (int i=0;i<arrlen(w->entities);++i) {
- for (int j=0;j<arrlen(w->entities[i].components);++j) {
- // @todo wrap the component finder in macros or function
- if (w->entities[i].components[j].type==COMPONENT_ACTIONS) {
- for (int k=0;k<arrlen(w->entities[i].components[j].actions.items);++k) {
- if (w->entities[i].components[j].actions.items[k].run(&w->entities[i], w)) {
- ret = true;
- break;
- }
- }
+ Component *comp = Entity_Find_Component(&w->entities[i], COMPONENT_ACTIONS);
+ if (comp==NULL) continue;
+ for (int j=0;j<arrlen(comp->actions.items);++j) {
+ if (comp->actions.items[j].run(&w->entities[i], w)) {
+ ret = true;
break;
}
}