@flare-engine/ecs 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,438 +1,556 @@
1
- // src/component.ts
2
- var nextComponentId = 0;
1
+ import { Signal } from "@flare-engine/events";
2
+ //#region src/component.ts
3
+ let nextComponentId = 0;
4
+ /**
5
+ * Define a new component type.
6
+ *
7
+ * @param name Debug name for the component.
8
+ * @param defaults Factory function returning default values, or undefined for tag components.
9
+ */
3
10
  function defineComponent(name, defaults) {
4
- const id = nextComponentId++;
5
- if (id >= 32) {
6
- throw new Error(`Maximum 32 component types exceeded (defining "${name}")`);
7
- }
8
- return {
9
- id,
10
- bit: 1 << id,
11
- name,
12
- create: defaults ?? (() => void 0)
13
- };
11
+ const id = nextComponentId++;
12
+ if (id >= 32) throw new Error(`Maximum 32 component types exceeded (defining "${name}")`);
13
+ return {
14
+ id,
15
+ bit: 1 << id,
16
+ name,
17
+ create: defaults ?? (() => void 0)
18
+ };
14
19
  }
20
+ /**
21
+ * Reset the component ID counter. Only for testing.
22
+ * @internal
23
+ */
15
24
  function _resetComponentIds() {
16
- nextComponentId = 0;
25
+ nextComponentId = 0;
17
26
  }
18
-
19
- // src/query.ts
20
- import { Signal } from "@flare-engine/events";
27
+ //#endregion
28
+ //#region src/components.ts
29
+ /**
30
+ * Built-in ECS components using @flare-engine/math types.
31
+ */
32
+ /** 2D position component. */
33
+ const Position = defineComponent("Position", () => ({
34
+ x: 0,
35
+ y: 0
36
+ }));
37
+ /** 2D velocity component. */
38
+ const Velocity = defineComponent("Velocity", () => ({
39
+ x: 0,
40
+ y: 0
41
+ }));
42
+ /** Rotation in radians. */
43
+ const Rotation = defineComponent("Rotation", () => ({ angle: 0 }));
44
+ /** 2D scale component. */
45
+ const Scale = defineComponent("Scale", () => ({
46
+ x: 1,
47
+ y: 1
48
+ }));
49
+ /** Parent entity reference. */
50
+ const Parent = defineComponent("Parent", () => ({ entity: 0 }));
51
+ /** Countdown timer in seconds; entity expires when remaining reaches 0. */
52
+ const Lifetime = defineComponent("Lifetime", () => ({ remaining: 0 }));
53
+ /** Pins an entity's position to a target entity plus a fixed offset. */
54
+ const Follower = defineComponent("Follower", () => ({
55
+ target: 0,
56
+ offsetX: 0,
57
+ offsetY: 0
58
+ }));
59
+ //#endregion
60
+ //#region src/fsm.ts
61
+ /**
62
+ * Lightweight finite state machine. ~100 LOC.
63
+ *
64
+ * Manages named states with onEnter/onExit/onUpdate hooks
65
+ * and string-keyed transitions.
66
+ */
67
+ var FSM = class {
68
+ _current;
69
+ _states = /* @__PURE__ */ new Map();
70
+ _transitions = /* @__PURE__ */ new Map();
71
+ _context;
72
+ constructor(...args) {
73
+ this._context = args[0];
74
+ }
75
+ /** The currently active state, or undefined if none. */
76
+ get current() {
77
+ return this._current;
78
+ }
79
+ /** Register a state. */
80
+ addState(state) {
81
+ this._states.set(state.name, state);
82
+ return this;
83
+ }
84
+ /**
85
+ * Register a transition.
86
+ * When `trigger` fires in `fromState`, transition to `toState`.
87
+ */
88
+ addTransition(fromState, trigger, toState) {
89
+ let map = this._transitions.get(fromState);
90
+ if (!map) {
91
+ map = /* @__PURE__ */ new Map();
92
+ this._transitions.set(fromState, map);
93
+ }
94
+ map.set(trigger, toState);
95
+ return this;
96
+ }
97
+ /** Set the initial state (calls onEnter). */
98
+ start(stateName) {
99
+ const state = this._states.get(stateName);
100
+ if (!state) return;
101
+ this._current = state;
102
+ state.onEnter?.(this._context);
103
+ }
104
+ /** Fire a trigger. If a matching transition exists, switch states. */
105
+ trigger(name) {
106
+ if (!this._current) return;
107
+ const transitions = this._transitions.get(this._current.name);
108
+ if (!transitions) return;
109
+ const target = transitions.get(name);
110
+ if (target === void 0) return;
111
+ const next = this._states.get(target);
112
+ if (!next) return;
113
+ this._current.onExit?.(this._context);
114
+ this._current = next;
115
+ next.onEnter?.(this._context);
116
+ }
117
+ /** Update the current state. */
118
+ update(dt) {
119
+ this._current?.onUpdate?.(dt, this._context);
120
+ }
121
+ };
122
+ //#endregion
123
+ //#region src/prefab.ts
124
+ /**
125
+ * Define a prefab — a template for spawning entities with a fixed set of components.
126
+ *
127
+ * @param name Debug name.
128
+ * @param entries Array of [componentDef, data?] tuples.
129
+ */
130
+ function definePrefab(name, ...entries) {
131
+ const components = entries.map(([def, data]) => ({
132
+ def,
133
+ data
134
+ }));
135
+ return {
136
+ name,
137
+ spawn(world) {
138
+ const entity = world.spawn();
139
+ for (const entry of components) {
140
+ const data = typeof entry.data === "function" ? entry.data() : entry.data;
141
+ world.add(entity, entry.def, data);
142
+ }
143
+ return entity;
144
+ }
145
+ };
146
+ }
147
+ //#endregion
148
+ //#region src/query.ts
149
+ /**
150
+ * Query matches entities based on component archetypes.
151
+ *
152
+ * Uses bitmask matching: entity archetype & requiredMask === requiredMask
153
+ * and entity archetype & excludedMask === 0.
154
+ */
21
155
  var Query = class {
22
- /** Bitmask of required components. */
23
- requiredMask;
24
- /** Bitmask of excluded components. */
25
- excludedMask;
26
- /** Fires when an entity is added to this query's results. */
27
- onEntityAdded = new Signal();
28
- /** Fires when an entity is removed from this query's results. */
29
- onEntityRemoved = new Signal();
30
- /** Sorted array of matching entity IDs. */
31
- entities = [];
32
- /** Set for O(1) membership check. */
33
- entitySet = /* @__PURE__ */ new Set();
34
- constructor(requiredMask, excludedMask) {
35
- this.requiredMask = requiredMask;
36
- this.excludedMask = excludedMask;
37
- }
38
- /** Check if an archetype matches this query. */
39
- matches(archetype) {
40
- return (archetype & this.requiredMask) === this.requiredMask && (archetype & this.excludedMask) === 0;
41
- }
42
- /** @internal — called by World when an entity's archetype changes. */
43
- _check(entityId, archetype) {
44
- const isMatch = this.matches(archetype);
45
- const wasMatch = this.entitySet.has(entityId);
46
- if (isMatch && !wasMatch) {
47
- this.entitySet.add(entityId);
48
- this.entities.push(entityId);
49
- this.onEntityAdded.emit(entityId);
50
- } else if (!isMatch && wasMatch) {
51
- this.entitySet.delete(entityId);
52
- const idx = this.entities.indexOf(entityId);
53
- if (idx !== -1) this.entities.splice(idx, 1);
54
- this.onEntityRemoved.emit(entityId);
55
- }
56
- }
57
- /** @internal — called by World when an entity is removed entirely. */
58
- _remove(entityId) {
59
- if (this.entitySet.has(entityId)) {
60
- this.entitySet.delete(entityId);
61
- const idx = this.entities.indexOf(entityId);
62
- if (idx !== -1) this.entities.splice(idx, 1);
63
- this.onEntityRemoved.emit(entityId);
64
- }
65
- }
66
- /** Iterate matching entity IDs. */
67
- [Symbol.iterator]() {
68
- return this.entities[Symbol.iterator]();
69
- }
70
- /** Number of matching entities. */
71
- get count() {
72
- return this.entities.length;
73
- }
74
- /** Check if an entity matches this query. */
75
- has(entityId) {
76
- return this.entitySet.has(entityId);
77
- }
156
+ /** Bitmask of required components. */
157
+ requiredMask;
158
+ /** Bitmask of excluded components. */
159
+ excludedMask;
160
+ /** Fires when an entity is added to this query's results. */
161
+ onEntityAdded = new Signal();
162
+ /** Fires when an entity is removed from this query's results. */
163
+ onEntityRemoved = new Signal();
164
+ /** Sorted array of matching entity IDs. */
165
+ entities = [];
166
+ /** Set for O(1) membership check. */
167
+ entitySet = /* @__PURE__ */ new Set();
168
+ constructor(requiredMask, excludedMask) {
169
+ this.requiredMask = requiredMask;
170
+ this.excludedMask = excludedMask;
171
+ }
172
+ /** Check if an archetype matches this query. */
173
+ matches(archetype) {
174
+ return (archetype & this.requiredMask) === this.requiredMask && (archetype & this.excludedMask) === 0;
175
+ }
176
+ /** @internal — called by World when an entity's archetype changes. */
177
+ _check(entityId, archetype) {
178
+ const isMatch = this.matches(archetype);
179
+ const wasMatch = this.entitySet.has(entityId);
180
+ if (isMatch && !wasMatch) {
181
+ this.entitySet.add(entityId);
182
+ this.entities.push(entityId);
183
+ this.onEntityAdded.emit(entityId);
184
+ } else if (!isMatch && wasMatch) {
185
+ this.entitySet.delete(entityId);
186
+ const idx = this.entities.indexOf(entityId);
187
+ if (idx !== -1) this.entities.splice(idx, 1);
188
+ this.onEntityRemoved.emit(entityId);
189
+ }
190
+ }
191
+ /** @internal — called by World when an entity is removed entirely. */
192
+ _remove(entityId) {
193
+ if (this.entitySet.has(entityId)) {
194
+ this.entitySet.delete(entityId);
195
+ const idx = this.entities.indexOf(entityId);
196
+ if (idx !== -1) this.entities.splice(idx, 1);
197
+ this.onEntityRemoved.emit(entityId);
198
+ }
199
+ }
200
+ /** Iterate matching entity IDs. */
201
+ [Symbol.iterator]() {
202
+ return this.entities[Symbol.iterator]();
203
+ }
204
+ /** Number of matching entities. */
205
+ get count() {
206
+ return this.entities.length;
207
+ }
208
+ /** Check if an entity matches this query. */
209
+ has(entityId) {
210
+ return this.entitySet.has(entityId);
211
+ }
78
212
  };
213
+ /** Builder for creating queries with .with() / .without() chaining. */
79
214
  var QueryBuilder = class {
80
- required = 0;
81
- excluded = 0;
82
- with(...components) {
83
- for (const c of components) {
84
- this.required |= c.bit;
85
- }
86
- return this;
87
- }
88
- without(...components) {
89
- for (const c of components) {
90
- this.excluded |= c.bit;
91
- }
92
- return this;
93
- }
94
- /** Build the query (called internally by World). */
95
- build() {
96
- return new Query(this.required, this.excluded);
97
- }
98
- };
99
-
100
- // src/world.ts
101
- var World = class {
102
- nextId = 1;
103
- archetypes = /* @__PURE__ */ new Map();
104
- // entityId → bitmask
105
- componentStores = /* @__PURE__ */ new Map();
106
- // componentId → (entityId → data)
107
- queries = [];
108
- systems = [];
109
- systemsSorted = false;
110
- /** Create a new entity. Returns the entity ID. */
111
- spawn() {
112
- const id = this.nextId++;
113
- this.archetypes.set(id, 0);
114
- return id;
115
- }
116
- /** Remove an entity and all its components. */
117
- destroy(entityId) {
118
- const arch = this.archetypes.get(entityId);
119
- if (arch === void 0) return;
120
- for (const [, store] of this.componentStores) {
121
- store.delete(entityId);
122
- }
123
- this.archetypes.delete(entityId);
124
- for (const query of this.queries) {
125
- query._remove(entityId);
126
- }
127
- }
128
- /** Add a component to an entity. */
129
- add(entityId, def, data) {
130
- const arch = this.archetypes.get(entityId);
131
- if (arch === void 0) return;
132
- let store = this.componentStores.get(def.id);
133
- if (!store) {
134
- store = /* @__PURE__ */ new Map();
135
- this.componentStores.set(def.id, store);
136
- }
137
- store.set(entityId, data !== void 0 ? data : def.create());
138
- const newArch = arch | def.bit;
139
- this.archetypes.set(entityId, newArch);
140
- for (const query of this.queries) {
141
- query._check(entityId, newArch);
142
- }
143
- }
144
- /** Remove a component from an entity. */
145
- remove(entityId, def) {
146
- const arch = this.archetypes.get(entityId);
147
- if (arch === void 0) return;
148
- const store = this.componentStores.get(def.id);
149
- if (store) store.delete(entityId);
150
- const newArch = arch & ~def.bit;
151
- this.archetypes.set(entityId, newArch);
152
- for (const query of this.queries) {
153
- query._check(entityId, newArch);
154
- }
155
- }
156
- /** Get component data for an entity. */
157
- get(entityId, def) {
158
- const store = this.componentStores.get(def.id);
159
- return store?.get(entityId);
160
- }
161
- /** Check if entity has a component. */
162
- has(entityId, def) {
163
- const arch = this.archetypes.get(entityId);
164
- return arch !== void 0 && (arch & def.bit) !== 0;
165
- }
166
- /** Check if entity exists. */
167
- exists(entityId) {
168
- return this.archetypes.has(entityId);
169
- }
170
- /**
171
- * Create a query. Queries auto-update as entities change.
172
- * Use the QueryBuilder-style chaining:
173
- * world.query(Position, Velocity)
174
- * Or use the builder:
175
- * world.queryBuilder().with(Position).without(Dead).build()
176
- */
177
- query(...components) {
178
- let mask = 0;
179
- for (const c of components) {
180
- mask |= c.bit;
181
- }
182
- const q = new Query(mask, 0);
183
- this.queries.push(q);
184
- for (const [entityId, arch] of this.archetypes) {
185
- q._check(entityId, arch);
186
- }
187
- return q;
188
- }
189
- /** Create a QueryBuilder for complex queries (with/without). */
190
- queryBuilder() {
191
- return new _WorldQueryBuilder(this);
192
- }
193
- /** Register a system function. Lower priority runs first. */
194
- addSystem(fn, priority = 0) {
195
- this.systems.push({ fn, priority });
196
- this.systemsSorted = false;
197
- }
198
- /** Remove a system. */
199
- removeSystem(fn) {
200
- const idx = this.systems.findIndex((s) => s.fn === fn);
201
- if (idx !== -1) this.systems.splice(idx, 1);
202
- }
203
- /** Run all systems in priority order. */
204
- step(dt) {
205
- if (!this.systemsSorted) {
206
- this.systems.sort((a, b) => a.priority - b.priority);
207
- this.systemsSorted = true;
208
- }
209
- for (const sys of this.systems) {
210
- sys.fn(this, dt);
211
- }
212
- }
213
- /** @internal Register a query for auto-update. */
214
- _registerQuery(q) {
215
- this.queries.push(q);
216
- for (const [entityId, arch] of this.archetypes) {
217
- q._check(entityId, arch);
218
- }
219
- }
220
- };
221
- var _WorldQueryBuilder = class extends QueryBuilder {
222
- world;
223
- constructor(world) {
224
- super();
225
- this.world = world;
226
- }
227
- build() {
228
- const q = super.build();
229
- this.world._registerQuery(q);
230
- return q;
231
- }
215
+ required = 0;
216
+ excluded = 0;
217
+ with(...components) {
218
+ for (const c of components) this.required |= c.bit;
219
+ return this;
220
+ }
221
+ without(...components) {
222
+ for (const c of components) this.excluded |= c.bit;
223
+ return this;
224
+ }
225
+ /** Build the query (called internally by World). */
226
+ build() {
227
+ return new Query(this.required, this.excluded);
228
+ }
232
229
  };
233
-
234
- // src/system.ts
230
+ //#endregion
231
+ //#region src/system.ts
232
+ /**
233
+ * Define a system that processes entities matching a query.
234
+ *
235
+ * Returns a SystemDef that can be added to a World via world.addSystem().
236
+ * The system function receives the query's matching entities, dt, and world.
237
+ *
238
+ * Usage:
239
+ * const q = world.query(Position, Velocity);
240
+ * const moveSys = defineSystem(q, (entities, dt, world) => {
241
+ * for (const id of entities) { ... }
242
+ * });
243
+ * world.addSystem(moveSys._worldFn);
244
+ */
235
245
  function defineSystem(query, fn) {
236
- const worldFn = (world, dt) => {
237
- fn(query, dt, world);
238
- };
239
- return { query, fn, _worldFn: worldFn };
246
+ const worldFn = (world, dt) => {
247
+ fn(query, dt, world);
248
+ };
249
+ return {
250
+ query,
251
+ fn,
252
+ _worldFn: worldFn
253
+ };
240
254
  }
241
-
242
- // src/prefab.ts
243
- function definePrefab(name, ...entries) {
244
- const components = entries.map(([def, data]) => ({
245
- def,
246
- data
247
- }));
248
- return {
249
- name,
250
- spawn(world) {
251
- const entity = world.spawn();
252
- for (const entry of components) {
253
- const data = typeof entry.data === "function" ? entry.data() : entry.data;
254
- world.add(entity, entry.def, data);
255
- }
256
- return entity;
257
- }
258
- };
259
- }
260
-
261
- // src/fsm.ts
262
- var FSM = class {
263
- _current;
264
- _states = /* @__PURE__ */ new Map();
265
- _transitions = /* @__PURE__ */ new Map();
266
- _context;
267
- constructor(...args) {
268
- this._context = args[0];
269
- }
270
- /** The currently active state, or undefined if none. */
271
- get current() {
272
- return this._current;
273
- }
274
- /** Register a state. */
275
- addState(state) {
276
- this._states.set(state.name, state);
277
- return this;
278
- }
279
- /**
280
- * Register a transition.
281
- * When `trigger` fires in `fromState`, transition to `toState`.
282
- */
283
- addTransition(fromState, trigger, toState) {
284
- let map = this._transitions.get(fromState);
285
- if (!map) {
286
- map = /* @__PURE__ */ new Map();
287
- this._transitions.set(fromState, map);
288
- }
289
- map.set(trigger, toState);
290
- return this;
291
- }
292
- /** Set the initial state (calls onEnter). */
293
- start(stateName) {
294
- const state = this._states.get(stateName);
295
- if (!state) return;
296
- this._current = state;
297
- state.onEnter?.(this._context);
298
- }
299
- /** Fire a trigger. If a matching transition exists, switch states. */
300
- trigger(name) {
301
- if (!this._current) return;
302
- const transitions = this._transitions.get(this._current.name);
303
- if (!transitions) return;
304
- const target = transitions.get(name);
305
- if (target === void 0) return;
306
- const next = this._states.get(target);
307
- if (!next) return;
308
- this._current.onExit?.(this._context);
309
- this._current = next;
310
- next.onEnter?.(this._context);
311
- }
312
- /** Update the current state. */
313
- update(dt) {
314
- this._current?.onUpdate?.(dt, this._context);
315
- }
316
- };
317
-
318
- // src/components.ts
319
- var Position = defineComponent("Position", () => ({
320
- x: 0,
321
- y: 0
322
- }));
323
- var Velocity = defineComponent("Velocity", () => ({
324
- x: 0,
325
- y: 0
326
- }));
327
- var Rotation = defineComponent("Rotation", () => ({
328
- angle: 0
329
- }));
330
- var Scale = defineComponent("Scale", () => ({ x: 1, y: 1 }));
331
- var Parent = defineComponent("Parent", () => ({
332
- entity: 0
333
- }));
334
- var Lifetime = defineComponent("Lifetime", () => ({
335
- remaining: 0
336
- }));
337
- var Follower = defineComponent(
338
- "Follower",
339
- () => ({ target: 0, offsetX: 0, offsetY: 0 })
340
- );
341
-
342
- // src/systems.ts
255
+ //#endregion
256
+ //#region src/systems.ts
257
+ /**
258
+ * createMovementSystem — integrates Position by Velocity * dt each frame.
259
+ *
260
+ * Recommended priority: run BEFORE createFollowerSystem (0).
261
+ */
343
262
  function createMovementSystem(world) {
344
- const q = world.query(Position, Velocity);
345
- return defineSystem(q, (entities, dt, w) => {
346
- for (const id of entities) {
347
- const pos = w.get(id, Position);
348
- const vel = w.get(id, Velocity);
349
- pos.x += vel.x * dt;
350
- pos.y += vel.y * dt;
351
- }
352
- });
263
+ return defineSystem(world.query(Position, Velocity), (entities, dt, w) => {
264
+ for (const id of entities) {
265
+ const pos = w.get(id, Position);
266
+ const vel = w.get(id, Velocity);
267
+ pos.x += vel.x * dt;
268
+ pos.y += vel.y * dt;
269
+ }
270
+ });
353
271
  }
272
+ /**
273
+ * createLifetimeSystem — decrements Lifetime.remaining each frame.
274
+ * Entities whose remaining reaches <= 0 are collected, then onExpire is called
275
+ * for each AFTER the read loop.
276
+ *
277
+ * Deferred removal: destroying inside a live for…of over query.entities splices
278
+ * the array mid-iteration and would skip entities. Collect first, act after.
279
+ *
280
+ * The scratch array is closure-owned and grow-only — zero steady-state alloc.
281
+ *
282
+ * @param onExpire Destroy / pool policy — ecs never destroys on its own.
283
+ */
354
284
  function createLifetimeSystem(world, onExpire) {
355
- const q = world.query(Lifetime);
356
- const scratch = [];
357
- return defineSystem(q, (entities, dt, w) => {
358
- scratch.length = 0;
359
- for (const id of entities) {
360
- const life = w.get(id, Lifetime);
361
- life.remaining -= dt;
362
- if (life.remaining <= 0) {
363
- scratch.push(id);
364
- }
365
- }
366
- for (let i = 0; i < scratch.length; i++) {
367
- onExpire(scratch[i], w);
368
- }
369
- });
285
+ const q = world.query(Lifetime);
286
+ const scratch = [];
287
+ return defineSystem(q, (entities, dt, w) => {
288
+ scratch.length = 0;
289
+ for (const id of entities) {
290
+ const life = w.get(id, Lifetime);
291
+ life.remaining -= dt;
292
+ if (life.remaining <= 0) scratch.push(id);
293
+ }
294
+ for (let i = 0; i < scratch.length; i++) onExpire(scratch[i], w);
295
+ });
370
296
  }
297
+ /**
298
+ * createBoundsCullSystem — culls entities whose Position falls outside bounds.
299
+ * Reads bounds LIVE each frame so callers can mutate it to follow a camera.
300
+ * Entities outside are collected, then onCull is called for each after the read loop.
301
+ *
302
+ * Deferred removal: same splice-during-iteration reason as createLifetimeSystem.
303
+ *
304
+ * Recommended priority: run AFTER createMovementSystem and createFollowerSystem.
305
+ *
306
+ * @param bounds Mutable bounding box read each frame.
307
+ * @param onCull Destroy / pool policy — ecs never destroys on its own.
308
+ */
371
309
  function createBoundsCullSystem(world, bounds, onCull) {
372
- const q = world.query(Position);
373
- const scratch = [];
374
- return defineSystem(q, (entities, _dt, w) => {
375
- scratch.length = 0;
376
- for (const id of entities) {
377
- const pos = w.get(id, Position);
378
- if (pos.x < bounds.minX || pos.x > bounds.maxX || pos.y < bounds.minY || pos.y > bounds.maxY) {
379
- scratch.push(id);
380
- }
381
- }
382
- for (let i = 0; i < scratch.length; i++) {
383
- onCull(scratch[i], w);
384
- }
385
- });
310
+ const q = world.query(Position);
311
+ const scratch = [];
312
+ return defineSystem(q, (entities, _dt, w) => {
313
+ scratch.length = 0;
314
+ for (const id of entities) {
315
+ const pos = w.get(id, Position);
316
+ if (pos.x < bounds.minX || pos.x > bounds.maxX || pos.y < bounds.minY || pos.y > bounds.maxY) scratch.push(id);
317
+ }
318
+ for (let i = 0; i < scratch.length; i++) onCull(scratch[i], w);
319
+ });
386
320
  }
321
+ /**
322
+ * createFollowerSystem — pins each Follower entity's Position to
323
+ * target.Position + (offsetX, offsetY).
324
+ * If the target is gone or has no Position, the entity is silently skipped.
325
+ *
326
+ * Recommended priority: run AFTER createMovementSystem (1) so the target's
327
+ * position is already integrated before the follower snaps to it.
328
+ */
387
329
  function createFollowerSystem(world) {
388
- const q = world.query(Position, Follower);
389
- return defineSystem(q, (entities, _dt, w) => {
390
- for (const id of entities) {
391
- const follower = w.get(id, Follower);
392
- const t = w.get(follower.target, Position);
393
- if (t === void 0) continue;
394
- const pos = w.get(id, Position);
395
- pos.x = t.x + follower.offsetX;
396
- pos.y = t.y + follower.offsetY;
397
- }
398
- });
330
+ return defineSystem(world.query(Position, Follower), (entities, _dt, w) => {
331
+ for (const id of entities) {
332
+ const follower = w.get(id, Follower);
333
+ const t = w.get(follower.target, Position);
334
+ if (t === void 0) continue;
335
+ const pos = w.get(id, Position);
336
+ pos.x = t.x + follower.offsetX;
337
+ pos.y = t.y + follower.offsetY;
338
+ }
339
+ });
399
340
  }
341
+ /**
342
+ * createOrphanCullSystem — fires onOrphan for each Follower whose target entity
343
+ * no longer exists. Does NOT move or destroy anything itself.
344
+ *
345
+ * Split from createFollowerSystem so games that want to orphan-cull can opt in
346
+ * without coupling destruction to the follower pin logic.
347
+ *
348
+ * Recommended priority: run AFTER createFollowerSystem (2) so the follower is
349
+ * pinned before orphans are detected.
350
+ *
351
+ * Deferred removal: same splice-during-iteration reason as createLifetimeSystem.
352
+ *
353
+ * @param onOrphan Called once per orphaned entity after the read loop.
354
+ */
400
355
  function createOrphanCullSystem(world, onOrphan) {
401
- const q = world.query(Follower);
402
- const scratch = [];
403
- return defineSystem(q, (entities, _dt, w) => {
404
- scratch.length = 0;
405
- for (const id of entities) {
406
- const follower = w.get(id, Follower);
407
- if (!w.exists(follower.target)) {
408
- scratch.push(id);
409
- }
410
- }
411
- for (let i = 0; i < scratch.length; i++) {
412
- onOrphan(scratch[i], w);
413
- }
414
- });
356
+ const q = world.query(Follower);
357
+ const scratch = [];
358
+ return defineSystem(q, (entities, _dt, w) => {
359
+ scratch.length = 0;
360
+ for (const id of entities) {
361
+ const follower = w.get(id, Follower);
362
+ if (!w.exists(follower.target)) scratch.push(id);
363
+ }
364
+ for (let i = 0; i < scratch.length; i++) onOrphan(scratch[i], w);
365
+ });
415
366
  }
416
- export {
417
- FSM,
418
- Follower,
419
- Lifetime,
420
- Parent,
421
- Position,
422
- Query,
423
- QueryBuilder,
424
- Rotation,
425
- Scale,
426
- Velocity,
427
- World,
428
- _resetComponentIds,
429
- createBoundsCullSystem,
430
- createFollowerSystem,
431
- createLifetimeSystem,
432
- createMovementSystem,
433
- createOrphanCullSystem,
434
- defineComponent,
435
- definePrefab,
436
- defineSystem
367
+ //#endregion
368
+ //#region src/world.ts
369
+ /**
370
+ * World is the central ECS container.
371
+ *
372
+ * Entities are integer IDs. Components are stored in per-component Maps.
373
+ * Archetype bitmasks enable fast query matching.
374
+ */
375
+ var World = class {
376
+ nextId = 1;
377
+ archetypes = /* @__PURE__ */ new Map();
378
+ componentStores = /* @__PURE__ */ new Map();
379
+ queries = [];
380
+ queryIterDepth = 0;
381
+ pendingQueryRemove = null;
382
+ systems = [];
383
+ systemsSorted = false;
384
+ /** Create a new entity. Returns the entity ID. */
385
+ spawn() {
386
+ const id = this.nextId++;
387
+ this.archetypes.set(id, 0);
388
+ return id;
389
+ }
390
+ /** Remove an entity and all its components. */
391
+ destroy(entityId) {
392
+ if (this.archetypes.get(entityId) === void 0) return;
393
+ for (const [, store] of this.componentStores) store.delete(entityId);
394
+ this.archetypes.delete(entityId);
395
+ this.queryIterDepth++;
396
+ try {
397
+ for (const query of this.queries) query._remove(entityId);
398
+ } finally {
399
+ this.endQueryIteration();
400
+ }
401
+ }
402
+ /** Add a component to an entity. */
403
+ add(entityId, def, data) {
404
+ const arch = this.archetypes.get(entityId);
405
+ if (arch === void 0) return;
406
+ let store = this.componentStores.get(def.id);
407
+ if (!store) {
408
+ store = /* @__PURE__ */ new Map();
409
+ this.componentStores.set(def.id, store);
410
+ }
411
+ store.set(entityId, data !== void 0 ? data : def.create());
412
+ const newArch = arch | def.bit;
413
+ this.archetypes.set(entityId, newArch);
414
+ this.queryIterDepth++;
415
+ try {
416
+ for (const query of this.queries) query._check(entityId, newArch);
417
+ } finally {
418
+ this.endQueryIteration();
419
+ }
420
+ }
421
+ /** Remove a component from an entity. */
422
+ remove(entityId, def) {
423
+ const arch = this.archetypes.get(entityId);
424
+ if (arch === void 0) return;
425
+ const store = this.componentStores.get(def.id);
426
+ if (store) store.delete(entityId);
427
+ const newArch = arch & ~def.bit;
428
+ this.archetypes.set(entityId, newArch);
429
+ this.queryIterDepth++;
430
+ try {
431
+ for (const query of this.queries) query._check(entityId, newArch);
432
+ } finally {
433
+ this.endQueryIteration();
434
+ }
435
+ }
436
+ /** Get component data for an entity. */
437
+ get(entityId, def) {
438
+ return this.componentStores.get(def.id)?.get(entityId);
439
+ }
440
+ /** Check if entity has a component. */
441
+ has(entityId, def) {
442
+ const arch = this.archetypes.get(entityId);
443
+ return arch !== void 0 && (arch & def.bit) !== 0;
444
+ }
445
+ /** Check if entity exists. */
446
+ exists(entityId) {
447
+ return this.archetypes.has(entityId);
448
+ }
449
+ /** Number of live entities. */
450
+ get entityCount() {
451
+ return this.archetypes.size;
452
+ }
453
+ /**
454
+ * Walk every live entity ID. Iterates the live archetype map directly, with no
455
+ * array snapshot. Archetype changes (add/remove component) keep the same entity
456
+ * keys, so iteration is stable across them. Destroying entities inside the
457
+ * callback is safe, but entities spawned inside it are visited in the same pass
458
+ * (live Map iteration) — don't spawn from within.
459
+ */
460
+ forEachEntity(cb) {
461
+ for (const entityId of this.archetypes.keys()) cb(entityId);
462
+ }
463
+ /**
464
+ * Create a query. Queries auto-update as entities change.
465
+ * Use the QueryBuilder-style chaining:
466
+ * world.query(Position, Velocity)
467
+ * Or use the builder:
468
+ * world.queryBuilder().with(Position).without(Dead).build()
469
+ */
470
+ query(...components) {
471
+ let mask = 0;
472
+ for (const c of components) mask |= c.bit;
473
+ const q = new Query(mask, 0);
474
+ this.queries.push(q);
475
+ for (const [entityId, arch] of this.archetypes) q._check(entityId, arch);
476
+ return q;
477
+ }
478
+ /** Create a QueryBuilder for complex queries (with/without). */
479
+ queryBuilder() {
480
+ return new _WorldQueryBuilder(this);
481
+ }
482
+ /**
483
+ * Dispose a query created by `query()` or `queryBuilder().build()`. Afterwards
484
+ * the world stops updating it, so it no longer costs spawn/add/remove iteration
485
+ * time. The query is left inert — drop the reference to let it be collected.
486
+ *
487
+ * Safe to call from within a Query signal handler (e.g. a one-shot
488
+ * `onEntityAdded` that disposes its own query): the removal is deferred until
489
+ * the in-progress mutation finishes iterating, so no other query is skipped.
490
+ */
491
+ removeQuery(q) {
492
+ if (this.queryIterDepth > 0) {
493
+ if (this.pendingQueryRemove === null) this.pendingQueryRemove = [];
494
+ this.pendingQueryRemove.push(q);
495
+ return;
496
+ }
497
+ const idx = this.queries.indexOf(q);
498
+ if (idx !== -1) this.queries.splice(idx, 1);
499
+ }
500
+ /** @internal End a query-notify loop; flush any removeQuery deferred during it. */
501
+ endQueryIteration() {
502
+ this.queryIterDepth--;
503
+ if (this.queryIterDepth === 0 && this.pendingQueryRemove !== null) {
504
+ for (const q of this.pendingQueryRemove) {
505
+ const idx = this.queries.indexOf(q);
506
+ if (idx !== -1) this.queries.splice(idx, 1);
507
+ }
508
+ this.pendingQueryRemove.length = 0;
509
+ }
510
+ }
511
+ /** Register a system function. Lower priority runs first. */
512
+ addSystem(fn, priority = 0) {
513
+ this.systems.push({
514
+ fn,
515
+ priority
516
+ });
517
+ this.systemsSorted = false;
518
+ }
519
+ /** Remove a system. */
520
+ removeSystem(fn) {
521
+ const idx = this.systems.findIndex((s) => s.fn === fn);
522
+ if (idx !== -1) this.systems.splice(idx, 1);
523
+ }
524
+ /** Run all systems in priority order. */
525
+ step(dt) {
526
+ if (!this.systemsSorted) {
527
+ this.systems.sort((a, b) => a.priority - b.priority);
528
+ this.systemsSorted = true;
529
+ }
530
+ for (const sys of this.systems) sys.fn(this, dt);
531
+ }
532
+ /** @internal Register a query for auto-update. */
533
+ _registerQuery(q) {
534
+ this.queries.push(q);
535
+ for (const [entityId, arch] of this.archetypes) q._check(entityId, arch);
536
+ }
537
+ };
538
+ /**
539
+ * Internal query builder that auto-registers with a World.
540
+ */
541
+ var _WorldQueryBuilder = class extends QueryBuilder {
542
+ world;
543
+ constructor(world) {
544
+ super();
545
+ this.world = world;
546
+ }
547
+ build() {
548
+ const q = super.build();
549
+ this.world._registerQuery(q);
550
+ return q;
551
+ }
437
552
  };
553
+ //#endregion
554
+ export { FSM, Follower, Lifetime, Parent, Position, Query, QueryBuilder, Rotation, Scale, Velocity, World, _resetComponentIds, createBoundsCullSystem, createFollowerSystem, createLifetimeSystem, createMovementSystem, createOrphanCullSystem, defineComponent, definePrefab, defineSystem };
555
+
438
556
  //# sourceMappingURL=index.mjs.map