@@ -15,6 +15,7 @@ namespace pg
1515 *
1616 * - removeEntity(entityId or entityInstance): Remove an entity from the ECS
1717 * - getEntity(entityId): Get entity data as a table
18+ * - getEntities(componentName): Get all entities with the specified component as a table of entity tables
1819 * - sendEvent(eventName, key1, value1, key2, value2, ...): Send an event
1920 * - attachComponent(entityId or entityInstance, componentName, prop1, value1, prop2, value2, ...):
2021 * Attach a StandardComponent to an entity with properties
@@ -48,6 +49,12 @@ namespace pg
4849 * // Remove an entity
4950 * ecs.removeEntity(playerId)
5051 *
52+ * // Get all entities with a specific component
53+ * var allPlayers = ecs.getEntities("Player")
54+ * for (var player : allPlayers) {
55+ * __dprint("Player entity: " + player.__entityId)
56+ * }
57+ *
5158 * // ========== Creating Systems from Scripts ==========
5259 *
5360 * // Create a player management system
@@ -650,6 +657,52 @@ namespace pg
650657 return inst;
651658 });
652659
660+ addNativeFunction (" getEntities" , [ecsRefCopy](VM* vm, int argCount, Value* args) -> Value {
661+ if (argCount != 1 )
662+ {
663+ throw std::runtime_error (" getEntities expects exactly 1 argument (componentName)" );
664+ }
665+
666+ if (!IS_STRING (args[0 ]))
667+ {
668+ throw std::runtime_error (" getEntities expects a string component name" );
669+ }
670+
671+ auto componentName = vm->asString (args[0 ]);
672+
673+ // Create a vector to hold all entity tables
674+ Value vectorValue = vm->createVector ();
675+ ObjVector* vector = vm->asVector (vectorValue);
676+
677+ // Get the component owner from the registry
678+ auto * owner = ecsRefCopy->getComponentRegistry ()->retrieveStandardComponent (componentName);
679+
680+ if (!owner)
681+ {
682+ throw std::runtime_error (" getEntities: Standard Component '" + componentName + " ' not found in ECS" );
683+ }
684+
685+ // Get all components of this type from the owner
686+ auto componentView = owner->view ();
687+
688+ for (auto * component : componentView)
689+ {
690+ // Get the full entity with ALL components, not just the requested one
691+ auto * entity = ecsRefCopy->getEntity (component->entityId );
692+ if (entity)
693+ {
694+ // Serialize the complete entity with all its components
695+ Value entityTable = serializeEntityToTable (vm, ecsRefCopy, entity);
696+ vector->fields .push_back (vm->retainValue (entityTable));
697+ }
698+ }
699+
700+ LOG_MILE (" Ecs Compiled Module" , " getEntities(\" " << componentName << " \" ) returned "
701+ << vector->fields .size () << " entities" );
702+
703+ return vectorValue;
704+ });
705+
653706 }
654707 };
655708}
0 commit comments