@flare-engine/ecs 0.4.13 → 0.4.14

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/README.md CHANGED
@@ -72,7 +72,7 @@ const Bullet = definePrefab(
72
72
  );
73
73
  ```
74
74
 
75
- See [API spec](https://github.com/grzott/flare-engine/blob/main/docs/design/api-specs.md#flare-engineecs--8kb-gzip).
75
+ See [API spec](https://github.com/grzott/flare-engine/blob/main/docs/design/api-specs.md#flare-engineecs).
76
76
 
77
77
  ## License
78
78
 
package/dist/index.d.mts CHANGED
@@ -8,9 +8,19 @@ import { Vec2 } from "@flare-engine/math";
8
8
  */
9
9
  /** A unique component definition. */
10
10
  interface ComponentDef<T> {
11
- /** Internal unique ID (auto-assigned). */
11
+ /**
12
+ * Internal unique ID (auto-assigned).
13
+ * @deprecated Removed in 0.5.0. A `World` no longer keys storage by it, and it comes from a
14
+ * module-global counter, so it depends on import order and must never be persisted. Key by the
15
+ * definition object itself instead (e.g. a `Map<ComponentDef<unknown>, …>`).
16
+ */
12
17
  readonly id: number;
13
- /** Bitmask for this component (1 << id). */
18
+ /**
19
+ * Bitmask for this component (1 << id).
20
+ * @deprecated Removed in 0.5.0, which lifts the 32-type cap: `1 << id` wraps from the 33rd
21
+ * definition on. A `World` no longer keys storage by it. Key by the definition object itself
22
+ * instead (e.g. a `Map<ComponentDef<unknown>, …>`).
23
+ */
14
24
  readonly bit: number;
15
25
  /** Component name for debugging. */
16
26
  readonly name: string;
@@ -27,6 +37,8 @@ export declare function defineComponent<T = undefined>(name: string, defaults?:
27
37
  /**
28
38
  * Reset the component ID counter. Only for testing.
29
39
  * @internal
40
+ * @deprecated Removed in 0.5.0 together with the global counter it resets. Each `World` keys
41
+ * storage by the definition object, so isolating storage between tests needs no reset.
30
42
  */
31
43
  export declare function _resetComponentIds(): void;
32
44
  /**
@@ -105,9 +117,17 @@ export declare class FSM<C = undefined> {
105
117
  * it off the frame path.
106
118
  */
107
119
  export declare class Query {
108
- /** Bitmask of required components. */
120
+ /**
121
+ * Bitmask of required components.
122
+ * @deprecated Leaves the public API in 0.5.0, which sizes masks per World. Build queries with
123
+ * `world.query()` / `world.queryBuilder()` and test membership with `query.has(entity)`.
124
+ */
109
125
  readonly requiredMask: number;
110
- /** Bitmask of excluded components. */
126
+ /**
127
+ * Bitmask of excluded components.
128
+ * @deprecated Leaves the public API in 0.5.0, which sizes masks per World. Build queries with
129
+ * `world.query()` / `world.queryBuilder()` and test membership with `query.has(entity)`.
130
+ */
111
131
  readonly excludedMask: number;
112
132
  /** Fires when an entity is added to this query's results. */
113
133
  readonly onEntityAdded: Signal<number>;
@@ -121,8 +141,16 @@ export declare class Query {
121
141
  * rather than with the number of removals.
122
142
  */
123
143
  private index;
144
+ /**
145
+ * @deprecated Leaves the public API in 0.5.0, which sizes masks per World, so a raw mask stops
146
+ * being a valid argument. Build queries with `world.query()` / `world.queryBuilder()`.
147
+ */
124
148
  constructor(requiredMask: number, excludedMask: number);
125
- /** Check if an archetype matches this query. */
149
+ /**
150
+ * Check if an archetype matches this query.
151
+ * @deprecated Leaves the public API in 0.5.0, which sizes masks per World, so a raw archetype
152
+ * mask stops being a valid argument. Test membership with `query.has(entity)`.
153
+ */
126
154
  matches(archetype: number): boolean;
127
155
  /** @internal — called by World when an entity's archetype changes. */
128
156
  _check(entityId: number, archetype: number): void;
@@ -202,7 +230,10 @@ export declare class QueryBuilder {
202
230
  export declare class World {
203
231
  private nextId;
204
232
  private archetypes;
205
- private componentStores;
233
+ private slots;
234
+ private usedBits;
235
+ private stores;
236
+ private storesByBit;
206
237
  private queries;
207
238
  private queryIterDepth;
208
239
  private pendingQueryRemove;
@@ -220,6 +251,16 @@ export declare class World {
220
251
  get<T>(entityId: number, def: ComponentDef<T>): T | undefined;
221
252
  /** Check if entity has a component. */
222
253
  has(entityId: number, def: ComponentDef<unknown>): boolean;
254
+ /**
255
+ * The slot a definition holds in this World, assigned on first use. Within one
256
+ * copy of the package ids are unique, so every definition keeps its own `bit`
257
+ * and query masks stay the OR of `def.bit`. Only a definition whose bit is
258
+ * already held here (a second copy of the package, a hand-built literal, reuse
259
+ * after `_resetComponentIds`) gets another one, where it used to share storage.
260
+ */
261
+ private slotFor;
262
+ /** Mask for a set of definitions. Checks room for all of them before assigning any slot. */
263
+ private maskOf;
223
264
  /** Check if entity exists. */
224
265
  exists(entityId: number): boolean;
225
266
  /** Number of live entities. */
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.mts","names":["_$__component_js0.ComponentDef"],"sources":["../src/component.ts","../src/components.ts","../src/fsm.ts","../src/query.ts","../src/world.ts","../src/prefab.ts","../src/system.ts","../src/systems.ts"],"mappings":";;;;;;;;;UAQiB,aAAa;;WAEnB;;WAEA;;WAEA;;EAET,UAAU;;;;;;;;wBAWI,gBAAgB,eAAe,cAAc,iBAAiB,IAAI,aAAa;;;;;wBAiB/E;;;;;qBCpCH,UAAQA,aAAA;;qBAMR,UAAQA,aAAA;;qBAMR,UAAAA;EAAoC;;;qBAKpC,OAAKA,aAAA;;qBAGL,QAAAA;EAAmC;;;qBAKnC,UAAAA;EAAwC;;;qBAKxC,UAAAA;EAAqC;EAAiB;EAAiB;;;UCrCnE,MAAM;WACZ;EACT,SAAS,SAAS;EAClB,QAAQ,SAAS;EACjB,UAAU,YAAY,SAAS;;;;;;;;qBASpB,IAAI;UACP;UACA;UACA;UACA;EAEI,eAAG,MAAM,4BAA4B,SAAS;;MAKtD,WAAW,MAAM;;EAKrB,SAAS,OAAO,MAAM;;;;;EAStB,cAAc,mBAAmB,iBAAiB;;EAWlD,MAAM;;EAQN,QAAQ;;EAcR,OAAO;;;;;;;;;;;;;;;qBCxDI;;WAEF;;WAEA;;WAGA,eAAa;;WAEb,iBAAe;UAEhB;;;;;;;UAOA;EAEI,YAAA,sBAAsB;;EAMlC,QAAQ;;EAOR,OAAO,kBAAkB;;EAezB,QAAQ;;;;;;;;;;;UAiBA;;;;;;;;;;;;;;;;;;;;;;;;;MAkCJ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uBACd,OAAO,OACP,WAAW,gBAAgB,OAAO,iBACjC"}
1
+ {"version":3,"file":"index.d.mts","names":["_$__component_js0.ComponentDef"],"sources":["../src/component.ts","../src/components.ts","../src/fsm.ts","../src/query.ts","../src/world.ts","../src/prefab.ts","../src/system.ts","../src/systems.ts"],"mappings":";;;;;;;;;UAQiB,aAAa;;;;;;;WAOnB;;;;;;;WAOA;;WAEA;;EAET,UAAU;;;;;;;;wBAWI,gBAAgB,eAAe,cAAc,iBAAiB,IAAI,aAAa;;;;;;;wBAmB/E;;;;;qBChDH,UAAQA,aAAA;;qBAMR,UAAQA,aAAA;;qBAMR,UAAAA;EAAoC;;;qBAKpC,OAAKA,aAAA;;qBAGL,QAAAA;EAAmC;;;qBAKnC,UAAAA;EAAwC;;;qBAKxC,UAAAA;EAAqC;EAAiB;EAAiB;;;UCrCnE,MAAM;WACZ;EACT,SAAS,SAAS;EAClB,QAAQ,SAAS;EACjB,UAAU,YAAY,SAAS;;;;;;;;qBASpB,IAAI;UACP;UACA;UACA;UACA;EAEI,eAAG,MAAM,4BAA4B,SAAS;;MAKtD,WAAW,MAAM;;EAKrB,SAAS,OAAO,MAAM;;;;;EAStB,cAAc,mBAAmB,iBAAiB;;EAWlD,MAAM;;EAQN,QAAQ;;EAcR,OAAO;;;;;;;;;;;;;;;qBCxDI;;;;;;WAMF;;;;;;WAMA;;WAGA,eAAa;;WAEb,iBAAe;UAEhB;;;;;;;UAOA;;;;;EAMI,YAAA,sBAAsB;;;;;;EAUlC,QAAQ;;EAOR,OAAO,kBAAkB;;EAezB,QAAQ;;;;;;;;;;;UAiBA;;;;;;;;;;;;;;;;;;;;;;;;;MAkCJ;;;;;;GASH,OAAO,aAAa;;MAKjB;;EAKJ,IAAI;;;;;;;;;;qBAaO;UACH;UACA;mBACS;EAEL,YAAA,WAAW,GAAG;EAI1B,QAAQ,YAAY;EAKpB,WAAW,YAAY;;EAMvB,SAAS;;;;;;;;qBCvKE;UACH;UACA;UACA;UACA;UACA;UACA;UAGA;UACA;UACA;UACA;UAIA;;EAGR;;EAOA,QAAQ;;EAeR,IAAI,GAAG,kBAAkB,KAAK,aAAa,IAAI,OAAO;;EActD,OAAO,GAAG,kBAAkB,KAAK,aAAa;;EAe9C,IAAI,GAAG,kBAAkB,KAAK,aAAa,KAAK;;EAKhD,IAAI,kBAAkB,KAAK;;;;;;;;UAcnB;;UAmBA;;EAkBR,OAAO;;MAKH;;;;;;;;EAWJ,cAAc,KAAK;;;;;;;;EAanB,SAAS,YAAY,0BAA0B;;EAO/C,gBAAgB;;UAKR;;;;;;;;;;EAgBR,YAAY,GAAG;;UAWP;;UAkBA;;EAYR,UAAU,KAAK,OAAO,OAAO,qBAAqB;;EAMlD,aAAa,KAAK,OAAO,OAAO;;EAMhC,KAAK;;;UClPU;WACN;;EAET,MAAM,OAAO;;;;;;;;;;;;;wBAcC,aACd,iBACG,UAAU,yDACZ;;KC1BS,YAAY,OAAO,OAAO,YAAY,OAAO;;UAGxC;WACN,OAAO;WACP,IAAI;;;;;WAKJ,UAAU,OAAO,OAAO;;WAExB,WAAW,OAAO,OAAO;;;;;;;;;;;;;;;;;;;;;wBAsBpB,aAAa,OAAO,OAAO,IAAI,WAAW;;;;;UC5BzC;WACN;WACA;WACA;WACA;;;;;;;wBAQK,qBAAqB,OAAO,QAAQ;;;;;;;;;;;;;;;;;;wBA+BpC,qBACd,OAAO,OACP,WAAW,gBAAgB,OAAO,gBAClC,QAAQ,QACP;;;;;;;;;;;;;;;;;;;wBAsCa,uBACd,OAAO,OACP,QAAQ,YACR,SAAS,gBAAgB,OAAO,gBAChC,QAAQ,QACP;;;;;;;;;wBAgCa,qBAAqB,OAAO,QAAQ;;;;;;;;;;;;;;;wBA8BpC,uBACd,OAAO,OACP,WAAW,gBAAgB,OAAO,iBACjC"}
package/dist/index.d.ts CHANGED
@@ -8,9 +8,19 @@ import { Signal } from "@flare-engine/events";
8
8
  */
9
9
  /** A unique component definition. */
10
10
  interface ComponentDef<T> {
11
- /** Internal unique ID (auto-assigned). */
11
+ /**
12
+ * Internal unique ID (auto-assigned).
13
+ * @deprecated Removed in 0.5.0. A `World` no longer keys storage by it, and it comes from a
14
+ * module-global counter, so it depends on import order and must never be persisted. Key by the
15
+ * definition object itself instead (e.g. a `Map<ComponentDef<unknown>, …>`).
16
+ */
12
17
  readonly id: number;
13
- /** Bitmask for this component (1 << id). */
18
+ /**
19
+ * Bitmask for this component (1 << id).
20
+ * @deprecated Removed in 0.5.0, which lifts the 32-type cap: `1 << id` wraps from the 33rd
21
+ * definition on. A `World` no longer keys storage by it. Key by the definition object itself
22
+ * instead (e.g. a `Map<ComponentDef<unknown>, …>`).
23
+ */
14
24
  readonly bit: number;
15
25
  /** Component name for debugging. */
16
26
  readonly name: string;
@@ -27,6 +37,8 @@ export declare function defineComponent<T = undefined>(name: string, defaults?:
27
37
  /**
28
38
  * Reset the component ID counter. Only for testing.
29
39
  * @internal
40
+ * @deprecated Removed in 0.5.0 together with the global counter it resets. Each `World` keys
41
+ * storage by the definition object, so isolating storage between tests needs no reset.
30
42
  */
31
43
  export declare function _resetComponentIds(): void;
32
44
  /**
@@ -105,9 +117,17 @@ export declare class FSM<C = undefined> {
105
117
  * it off the frame path.
106
118
  */
107
119
  export declare class Query {
108
- /** Bitmask of required components. */
120
+ /**
121
+ * Bitmask of required components.
122
+ * @deprecated Leaves the public API in 0.5.0, which sizes masks per World. Build queries with
123
+ * `world.query()` / `world.queryBuilder()` and test membership with `query.has(entity)`.
124
+ */
109
125
  readonly requiredMask: number;
110
- /** Bitmask of excluded components. */
126
+ /**
127
+ * Bitmask of excluded components.
128
+ * @deprecated Leaves the public API in 0.5.0, which sizes masks per World. Build queries with
129
+ * `world.query()` / `world.queryBuilder()` and test membership with `query.has(entity)`.
130
+ */
111
131
  readonly excludedMask: number;
112
132
  /** Fires when an entity is added to this query's results. */
113
133
  readonly onEntityAdded: Signal<number>;
@@ -121,8 +141,16 @@ export declare class Query {
121
141
  * rather than with the number of removals.
122
142
  */
123
143
  private index;
144
+ /**
145
+ * @deprecated Leaves the public API in 0.5.0, which sizes masks per World, so a raw mask stops
146
+ * being a valid argument. Build queries with `world.query()` / `world.queryBuilder()`.
147
+ */
124
148
  constructor(requiredMask: number, excludedMask: number);
125
- /** Check if an archetype matches this query. */
149
+ /**
150
+ * Check if an archetype matches this query.
151
+ * @deprecated Leaves the public API in 0.5.0, which sizes masks per World, so a raw archetype
152
+ * mask stops being a valid argument. Test membership with `query.has(entity)`.
153
+ */
126
154
  matches(archetype: number): boolean;
127
155
  /** @internal — called by World when an entity's archetype changes. */
128
156
  _check(entityId: number, archetype: number): void;
@@ -202,7 +230,10 @@ export declare class QueryBuilder {
202
230
  export declare class World {
203
231
  private nextId;
204
232
  private archetypes;
205
- private componentStores;
233
+ private slots;
234
+ private usedBits;
235
+ private stores;
236
+ private storesByBit;
206
237
  private queries;
207
238
  private queryIterDepth;
208
239
  private pendingQueryRemove;
@@ -220,6 +251,16 @@ export declare class World {
220
251
  get<T>(entityId: number, def: ComponentDef<T>): T | undefined;
221
252
  /** Check if entity has a component. */
222
253
  has(entityId: number, def: ComponentDef<unknown>): boolean;
254
+ /**
255
+ * The slot a definition holds in this World, assigned on first use. Within one
256
+ * copy of the package ids are unique, so every definition keeps its own `bit`
257
+ * and query masks stay the OR of `def.bit`. Only a definition whose bit is
258
+ * already held here (a second copy of the package, a hand-built literal, reuse
259
+ * after `_resetComponentIds`) gets another one, where it used to share storage.
260
+ */
261
+ private slotFor;
262
+ /** Mask for a set of definitions. Checks room for all of them before assigning any slot. */
263
+ private maskOf;
223
264
  /** Check if entity exists. */
224
265
  exists(entityId: number): boolean;
225
266
  /** Number of live entities. */
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","names":["_$__component_js0.ComponentDef"],"sources":["../src/component.ts","../src/components.ts","../src/fsm.ts","../src/query.ts","../src/world.ts","../src/prefab.ts","../src/system.ts","../src/systems.ts"],"mappings":";;;;;;;;;UAQiB,aAAa;;WAEnB;;WAEA;;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anB,SAAS,YAAY,0BAA0B;;EAW/C,gBAAgB;;UAKR;;;;;;;;;;EAgBR,YAAY,GAAG;;UAWP;;UAkBA;;EAYR,UAAU,KAAK,OAAO,OAAO,qBAAqB;;EAMlD,aAAa,KAAK,OAAO,OAAO;;EAMhC,KAAK;;;UCnMU;WACN;;EAET,MAAM,OAAO;;;;;;;;;;;;;wBAcC,aACd,iBACG,UAAU,yDACZ;;KC1BS,YAAY,OAAO,OAAO,YAAY,OAAO;;UAGxC;WACN,OAAO;WACP,IAAI;;;;;WAKJ,UAAU,OAAO,OAAO;;WAExB,WAAW,OAAO,OAAO;;;;;;;;;;;;;;;;;;;;;wBAsBpB,aAAa,OAAO,OAAO,IAAI,WAAW;;;;;UC5BzC;WACN;WACA;WACA;WACA;;;;;;;wBAQK,qBAAqB,OAAO,QAAQ;;;;;;;;;;;;;;;;;;wBA+BpC,qBACd,OAAO,OACP,WAAW,gBAAgB,OAAO,gBAClC,QAAQ,QACP;;;;;;;;;;;;;;;;;;;wBAsCa,uBACd,OAAO,OACP,QAAQ,YACR,SAAS,gBAAgB,OAAO,gBAChC,QAAQ,QACP;;;;;;;;;wBAgCa,qBAAqB,OAAO,QAAQ;;;;;;;;;;;;;;;wBA8BpC,uBACd,OAAO,OACP,WAAW,gBAAgB,OAAO,iBACjC"}
1
+ {"version":3,"file":"index.d.ts","names":["_$__component_js0.ComponentDef"],"sources":["../src/component.ts","../src/components.ts","../src/fsm.ts","../src/query.ts","../src/world.ts","../src/prefab.ts","../src/system.ts","../src/systems.ts"],"mappings":";;;;;;;;;UAQiB,aAAa;;;;;;;WAOnB;;;;;;;WAOA;;WAEA;;EAET,UAAU;;;;;;;;wBAWI,gBAAgB,eAAe,cAAc,iBAAiB,IAAI,aAAa;;;;;;;wBAmB/E;;;;;qBChDH,UAAQA,aAAA;;qBAMR,UAAQA,aAAA;;qBAMR,UAAAA;EAAoC;;;qBAKpC,OAAKA,aAAA;;qBAGL,QAAAA;EAAmC;;;qBAKnC,UA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O;;EAMhC,KAAK;;;UClPU;WACN;;EAET,MAAM,OAAO;;;;;;;;;;;;;wBAcC,aACd,iBACG,UAAU,yDACZ;;KC1BS,YAAY,OAAO,OAAO,YAAY,OAAO;;UAGxC;WACN,OAAO;WACP,IAAI;;;;;WAKJ,UAAU,OAAO,OAAO;;WAExB,WAAW,OAAO,OAAO;;;;;;;;;;;;;;;;;;;;;wBAsBpB,aAAa,OAAO,OAAO,IAAI,WAAW;;;;;UC5BzC;WACN;WACA;WACA;WACA;;;;;;;wBAQK,qBAAqB,OAAO,QAAQ;;;;;;;;;;;;;;;;;;wBA+BpC,qBACd,OAAO,OACP,WAAW,gBAAgB,OAAO,gBAClC,QAAQ,QACP;;;;;;;;;;;;;;;;;;;wBAsCa,uBACd,OAAO,OACP,QAAQ,YACR,SAAS,gBAAgB,OAAO,gBAChC,QAAQ,QACP;;;;;;;;;wBAgCa,qBAAqB,OAAO,QAAQ;;;;;;;;;;;;;;;wBA8BpC,uBACd,OAAO,OACP,WAAW,gBAAgB,OAAO,iBACjC"}
package/dist/index.js CHANGED
@@ -21,6 +21,8 @@ function defineComponent(name, defaults) {
21
21
  /**
22
22
  * Reset the component ID counter. Only for testing.
23
23
  * @internal
24
+ * @deprecated Removed in 0.5.0 together with the global counter it resets. Each `World` keys
25
+ * storage by the definition object, so isolating storage between tests needs no reset.
24
26
  */
25
27
  function _resetComponentIds() {
26
28
  nextComponentId = 0;
@@ -162,9 +164,17 @@ function definePrefab(name, ...entries) {
162
164
  * it off the frame path.
163
165
  */
164
166
  var Query = class {
165
- /** Bitmask of required components. */
167
+ /**
168
+ * Bitmask of required components.
169
+ * @deprecated Leaves the public API in 0.5.0, which sizes masks per World. Build queries with
170
+ * `world.query()` / `world.queryBuilder()` and test membership with `query.has(entity)`.
171
+ */
166
172
  requiredMask;
167
- /** Bitmask of excluded components. */
173
+ /**
174
+ * Bitmask of excluded components.
175
+ * @deprecated Leaves the public API in 0.5.0, which sizes masks per World. Build queries with
176
+ * `world.query()` / `world.queryBuilder()` and test membership with `query.has(entity)`.
177
+ */
168
178
  excludedMask;
169
179
  /** Fires when an entity is added to this query's results. */
170
180
  onEntityAdded = new _flare_engine_events.Signal();
@@ -178,11 +188,19 @@ var Query = class {
178
188
  * rather than with the number of removals.
179
189
  */
180
190
  index = /* @__PURE__ */ new Map();
191
+ /**
192
+ * @deprecated Leaves the public API in 0.5.0, which sizes masks per World, so a raw mask stops
193
+ * being a valid argument. Build queries with `world.query()` / `world.queryBuilder()`.
194
+ */
181
195
  constructor(requiredMask, excludedMask) {
182
196
  this.requiredMask = requiredMask;
183
197
  this.excludedMask = excludedMask;
184
198
  }
185
- /** Check if an archetype matches this query. */
199
+ /**
200
+ * Check if an archetype matches this query.
201
+ * @deprecated Leaves the public API in 0.5.0, which sizes masks per World, so a raw archetype
202
+ * mask stops being a valid argument. Test membership with `query.has(entity)`.
203
+ */
186
204
  matches(archetype) {
187
205
  return (archetype & this.requiredMask) === this.requiredMask && (archetype & this.excludedMask) === 0;
188
206
  }
@@ -285,11 +303,11 @@ var QueryBuilder = class {
285
303
  this.register = register;
286
304
  }
287
305
  with(...components) {
288
- for (const c of components) this.required |= c.bit;
306
+ this.required |= (maskResolvers.get(this) ?? orBits)(components);
289
307
  return this;
290
308
  }
291
309
  without(...components) {
292
- for (const c of components) this.excluded |= c.bit;
310
+ this.excluded |= (maskResolvers.get(this) ?? orBits)(components);
293
311
  return this;
294
312
  }
295
313
  /** Build the query and register it with the owning World. */
@@ -299,6 +317,17 @@ var QueryBuilder = class {
299
317
  return q;
300
318
  }
301
319
  };
320
+ const maskResolvers = /* @__PURE__ */ new WeakMap();
321
+ /** World-only (not exported from the package): route a builder's masks through the World's registry. */
322
+ function bindMaskResolver(builder, maskOf) {
323
+ maskResolvers.set(builder, maskOf);
324
+ return builder;
325
+ }
326
+ function orBits(defs) {
327
+ let mask = 0;
328
+ for (const c of defs) mask |= c.bit;
329
+ return mask;
330
+ }
302
331
  // src/system.ts
303
332
  /**
304
333
  * Define a system that processes entities matching a query.
@@ -463,6 +492,7 @@ function createOrphanCullSystem(world, onOrphan) {
463
492
  });
464
493
  }
465
494
  // src/world.ts
495
+ const MAX_COMPONENT_TYPES = 32;
466
496
  /**
467
497
  * World is the central ECS container.
468
498
  *
@@ -472,7 +502,10 @@ function createOrphanCullSystem(world, onOrphan) {
472
502
  var World = class {
473
503
  nextId = 1;
474
504
  archetypes = /* @__PURE__ */ new Map();
475
- componentStores = /* @__PURE__ */ new Map();
505
+ slots = /* @__PURE__ */ new Map();
506
+ usedBits = 0;
507
+ stores = /* @__PURE__ */ new Map();
508
+ storesByBit = new Array(MAX_COMPONENT_TYPES).fill(void 0);
476
509
  queries = [];
477
510
  queryIterDepth = 0;
478
511
  pendingQueryRemove = null;
@@ -486,8 +519,9 @@ var World = class {
486
519
  }
487
520
  /** Remove an entity and all its components. */
488
521
  destroy(entityId) {
489
- if (this.archetypes.get(entityId) === void 0) return;
490
- for (const [, store] of this.componentStores) store.delete(entityId);
522
+ const arch = this.archetypes.get(entityId);
523
+ if (arch === void 0) return;
524
+ for (let m = arch; m !== 0; m &= m - 1) this.storesByBit[31 - Math.clz32(m & -m)]?.delete(entityId);
491
525
  this.archetypes.delete(entityId);
492
526
  this.notifyQueries(entityId, 0, true);
493
527
  }
@@ -495,13 +529,9 @@ var World = class {
495
529
  add(entityId, def, data) {
496
530
  const arch = this.archetypes.get(entityId);
497
531
  if (arch === void 0) return;
498
- let store = this.componentStores.get(def.id);
499
- if (!store) {
500
- store = /* @__PURE__ */ new Map();
501
- this.componentStores.set(def.id, store);
502
- }
503
- store.set(entityId, data !== void 0 ? data : def.create());
504
- const newArch = arch | def.bit;
532
+ const slot = this.slotFor(def);
533
+ slot.store.set(entityId, data !== void 0 ? data : def.create());
534
+ const newArch = arch | slot.bit;
505
535
  this.archetypes.set(entityId, newArch);
506
536
  this.notifyQueries(entityId, newArch, false);
507
537
  }
@@ -509,20 +539,59 @@ var World = class {
509
539
  remove(entityId, def) {
510
540
  const arch = this.archetypes.get(entityId);
511
541
  if (arch === void 0) return;
512
- const store = this.componentStores.get(def.id);
513
- if (store) store.delete(entityId);
514
- const newArch = arch & ~def.bit;
542
+ const slot = this.slots.get(def);
543
+ if (slot === void 0) return;
544
+ slot.store.delete(entityId);
545
+ const newArch = arch & ~slot.bit;
515
546
  this.archetypes.set(entityId, newArch);
516
547
  this.notifyQueries(entityId, newArch, false);
517
548
  }
518
549
  /** Get component data for an entity. */
519
550
  get(entityId, def) {
520
- return this.componentStores.get(def.id)?.get(entityId);
551
+ return this.stores.get(def)?.get(entityId);
521
552
  }
522
553
  /** Check if entity has a component. */
523
554
  has(entityId, def) {
555
+ const slot = this.slots.get(def);
556
+ if (slot === void 0) return false;
524
557
  const arch = this.archetypes.get(entityId);
525
- return arch !== void 0 && (arch & def.bit) !== 0;
558
+ return arch !== void 0 && (arch & slot.bit) !== 0;
559
+ }
560
+ /**
561
+ * The slot a definition holds in this World, assigned on first use. Within one
562
+ * copy of the package ids are unique, so every definition keeps its own `bit`
563
+ * and query masks stay the OR of `def.bit`. Only a definition whose bit is
564
+ * already held here (a second copy of the package, a hand-built literal, reuse
565
+ * after `_resetComponentIds`) gets another one, where it used to share storage.
566
+ */
567
+ slotFor(def) {
568
+ const known = this.slots.get(def);
569
+ if (known !== void 0) return known;
570
+ const free = ~this.usedBits;
571
+ if (free === 0) throw capacityError(def);
572
+ const own = def.bit | 0;
573
+ const bit = own !== 0 && (own & own - 1) === 0 && (own & free) !== 0 ? own : free & -free;
574
+ const slot = {
575
+ bit,
576
+ store: /* @__PURE__ */ new Map()
577
+ };
578
+ this.slots.set(def, slot);
579
+ this.stores.set(def, slot.store);
580
+ this.usedBits |= bit;
581
+ this.storesByBit[31 - Math.clz32(bit)] = slot.store;
582
+ return slot;
583
+ }
584
+ /** Mask for a set of definitions. Checks room for all of them before assigning any slot. */
585
+ maskOf(defs) {
586
+ let room = MAX_COMPONENT_TYPES - this.slots.size;
587
+ let i = 0;
588
+ for (const def of defs) {
589
+ if (!this.slots.has(def) && defs.indexOf(def) === i && room-- === 0) throw capacityError(def);
590
+ i++;
591
+ }
592
+ let mask = 0;
593
+ for (const def of defs) mask |= this.slotFor(def).bit;
594
+ return mask;
526
595
  }
527
596
  /** Check if entity exists. */
528
597
  exists(entityId) {
@@ -550,15 +619,13 @@ var World = class {
550
619
  * world.queryBuilder().with(Position).without(Dead).build()
551
620
  */
552
621
  query(...components) {
553
- let mask = 0;
554
- for (const c of components) mask |= c.bit;
555
- const q = new Query(mask, 0);
622
+ const q = new Query(this.maskOf(components), 0);
556
623
  this.register(q);
557
624
  return q;
558
625
  }
559
626
  /** Create a QueryBuilder for complex queries (with/without). */
560
627
  queryBuilder() {
561
- return new QueryBuilder((q) => this.register(q));
628
+ return bindMaskResolver(new QueryBuilder((q) => this.register(q)), (defs) => this.maskOf(defs));
562
629
  }
563
630
  /** Track a query and populate it with the entities that already match. */
564
631
  register(q) {
@@ -626,6 +693,9 @@ var World = class {
626
693
  for (const sys of this.systems) sys.fn(this, dt);
627
694
  }
628
695
  };
696
+ function capacityError(def) {
697
+ return /* @__PURE__ */ new Error(`A World holds at most 32 component types (registering "${def.name}")`);
698
+ }
629
699
  exports.FSM = FSM;
630
700
  exports.Follower = Follower;
631
701
  exports.Lifetime = Lifetime;
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["Signal"],"sources":["../src/component.ts","../src/components.ts","../src/fsm.ts","../src/prefab.ts","../src/query.ts","../src/system.ts","../src/systems.ts","../src/world.ts"],"sourcesContent":["/**\n * Component definition and factory.\n *\n * Components are plain data objects. Each component type gets a unique\n * bit for archetype-based query matching.\n */\n\n/** A unique component definition. */\nexport interface ComponentDef<T> {\n /** Internal unique ID (auto-assigned). */\n readonly id: number;\n /** Bitmask for this component (1 << id). */\n readonly bit: number;\n /** Component name for debugging. */\n readonly name: string;\n /** Create a new instance with default values. */\n create(): T;\n}\n\nlet nextComponentId = 0;\n\n/**\n * Define a new component type.\n *\n * @param name Debug name for the component.\n * @param defaults Factory function returning default values, or undefined for tag components.\n */\nexport function defineComponent<T = undefined>(name: string, defaults?: () => T): ComponentDef<T> {\n const id = nextComponentId++;\n if (id >= 32) {\n throw new Error(`Maximum 32 component types exceeded (defining \"${name}\")`);\n }\n return {\n id,\n bit: 1 << id,\n name,\n create: defaults ?? (() => undefined as T),\n };\n}\n\n/**\n * Reset the component ID counter. Only for testing.\n * @internal\n */\nexport function _resetComponentIds(): void {\n nextComponentId = 0;\n}\n","import type { Vec2 } from '@flare-engine/math';\nimport { defineComponent } from './component.js';\n\n/**\n * Built-in ECS components using @flare-engine/math types.\n */\n\n/** 2D position component. */\nexport const Position = defineComponent<Vec2>('Position', () => ({\n x: 0,\n y: 0,\n}));\n\n/** 2D velocity component. */\nexport const Velocity = defineComponent<Vec2>('Velocity', () => ({\n x: 0,\n y: 0,\n}));\n\n/** Rotation in radians. */\nexport const Rotation = defineComponent<{ angle: number }>('Rotation', () => ({\n angle: 0,\n}));\n\n/** 2D scale component. */\nexport const Scale = defineComponent<Vec2>('Scale', () => ({ x: 1, y: 1 }));\n\n/** Parent entity reference. */\nexport const Parent = defineComponent<{ entity: number }>('Parent', () => ({\n entity: 0,\n}));\n\n/** Countdown timer in seconds; entity expires when remaining reaches 0. */\nexport const Lifetime = defineComponent<{ remaining: number }>('Lifetime', () => ({\n remaining: 0,\n}));\n\n/** Pins an entity's position to a target entity plus a fixed offset. */\nexport const Follower = defineComponent<{ target: number; offsetX: number; offsetY: number }>(\n 'Follower',\n () => ({ target: 0, offsetX: 0, offsetY: 0 }),\n);\n","/** A state in the FSM. */\nexport interface State<C = undefined> {\n readonly name: string;\n onEnter?(context: C): void;\n onExit?(context: C): void;\n onUpdate?(dt: number, context: C): void;\n}\n\n/**\n * Lightweight finite state machine. ~100 LOC.\n *\n * Manages named states with onEnter/onExit/onUpdate hooks\n * and string-keyed transitions.\n */\nexport class FSM<C = undefined> {\n private _current: State<C> | undefined;\n private _states = new Map<string, State<C>>();\n private _transitions = new Map<string, Map<string, string>>();\n private _context: C;\n\n constructor(...args: C extends undefined ? [] : [context: C]) {\n this._context = args[0] as C;\n }\n\n /** The currently active state, or undefined if none. */\n get current(): State<C> | undefined {\n return this._current;\n }\n\n /** Register a state. */\n addState(state: State<C>): this {\n this._states.set(state.name, state);\n return this;\n }\n\n /**\n * Register a transition.\n * When `trigger` fires in `fromState`, transition to `toState`.\n */\n addTransition(fromState: string, trigger: string, toState: string): this {\n let map = this._transitions.get(fromState);\n if (!map) {\n map = new Map();\n this._transitions.set(fromState, map);\n }\n map.set(trigger, toState);\n return this;\n }\n\n /** Set the initial state (calls onEnter). */\n start(stateName: string): void {\n const state = this._states.get(stateName);\n if (!state) return;\n this._current = state;\n state.onEnter?.(this._context);\n }\n\n /** Fire a trigger. If a matching transition exists, switch states. */\n trigger(name: string): void {\n if (!this._current) return;\n const transitions = this._transitions.get(this._current.name);\n if (!transitions) return;\n const target = transitions.get(name);\n if (target === undefined) return;\n const next = this._states.get(target);\n if (!next) return;\n this._current.onExit?.(this._context);\n this._current = next;\n next.onEnter?.(this._context);\n }\n\n /** Update the current state. */\n update(dt: number): void {\n this._current?.onUpdate?.(dt, this._context);\n }\n}\n","import type { ComponentDef } from './component.js';\nimport type { World } from './world.js';\n\n/** A component entry in a prefab definition. */\ninterface PrefabEntry<T> {\n def: ComponentDef<T>;\n data?: T | (() => T);\n}\n\n/** A prefab factory that spawns entities with pre-defined components. */\nexport interface Prefab {\n readonly name: string;\n /** Spawn an entity with this prefab's components. */\n spawn(world: World): number;\n}\n\n/**\n * Define a prefab — a template for spawning entities with a fixed set of components.\n *\n * Plain-object data is stored by reference and shared by every spawn; pass\n * `() => T` for per-entity mutable state. This mirrors `world.add(entity, def,\n * data)`, which stores the object it is given — so the object form is for\n * data no entity will mutate, and the factory runs once per spawn.\n *\n * @param name Debug name.\n * @param entries Array of [componentDef, data?] tuples.\n */\nexport function definePrefab(\n name: string,\n ...entries: [ComponentDef<unknown>, (unknown | (() => unknown))?][]\n): Prefab {\n const components: PrefabEntry<unknown>[] = entries.map(([def, data]) => ({\n def,\n data,\n }));\n\n return {\n name,\n spawn(world: World): number {\n const entity = world.spawn();\n for (const entry of components) {\n const data =\n typeof entry.data === 'function' ? (entry.data as () => unknown)() : entry.data;\n world.add(entity, entry.def, data);\n }\n return entity;\n },\n };\n}\n","import { Signal } from '@flare-engine/events';\nimport type { ComponentDef } from './component.js';\n\n/**\n * Query matches entities based on component archetypes.\n *\n * Uses bitmask matching: entity archetype & requiredMask === requiredMask\n * and entity archetype & excludedMask === 0.\n *\n * Two ways to walk the matches:\n * - `entities` — the live id array, for an indexed `for` loop. Allocates\n * nothing; this is the form for systems and anything else that runs per frame.\n * - `for...of` — the convenience form. It creates an iterator, and on Hermes\n * (React Native) one `{ value, done }` object per entity per pass, so keep\n * it off the frame path.\n */\nexport class Query {\n /** Bitmask of required components. */\n readonly requiredMask: number;\n /** Bitmask of excluded components. */\n readonly excludedMask: number;\n\n /** Fires when an entity is added to this query's results. */\n readonly onEntityAdded = new Signal<number>();\n /** Fires when an entity is removed from this query's results. */\n readonly onEntityRemoved = new Signal<number>();\n\n private ids: number[] = [];\n /**\n * `entityId -> index into ids`. Serves membership *and* position, which\n * is what makes removal O(1): the previous pair of a `Set` plus `indexOf`\n * made every removal a linear scan, so churn cost grew as `n * removals`\n * rather than with the number of removals.\n */\n private index = new Map<number, number>();\n\n constructor(requiredMask: number, excludedMask: number) {\n this.requiredMask = requiredMask;\n this.excludedMask = excludedMask;\n }\n\n /** Check if an archetype matches this query. */\n matches(archetype: number): boolean {\n return (\n (archetype & this.requiredMask) === this.requiredMask && (archetype & this.excludedMask) === 0\n );\n }\n\n /** @internal — called by World when an entity's archetype changes. */\n _check(entityId: number, archetype: number): void {\n const isMatch = this.matches(archetype);\n const wasMatch = this.index.has(entityId);\n\n if (isMatch && !wasMatch) {\n this.index.set(entityId, this.ids.length);\n this.ids.push(entityId);\n this.onEntityAdded.emit(entityId);\n } else if (!isMatch && wasMatch) {\n this.swapRemove(entityId);\n this.onEntityRemoved.emit(entityId);\n }\n }\n\n /** @internal — called by World when an entity is removed entirely. */\n _remove(entityId: number): void {\n if (this.index.has(entityId)) {\n this.swapRemove(entityId);\n this.onEntityRemoved.emit(entityId);\n }\n }\n\n /**\n * O(1) removal: move the last element into the hole and shorten by one.\n *\n * Order-preserving removal cannot be O(1) here — `splice` shifts every later\n * element, and a position map would then need every shifted index rewritten,\n * so it costs the same scan it was meant to remove. A tombstone would keep\n * order but puts a branch in iteration, which at realistic churn runs far\n * more often than removal and would slow the steady-state path to speed up\n * the rare one.\n */\n private swapRemove(entityId: number): void {\n const idx = this.index.get(entityId) as number;\n const last = this.ids.length - 1;\n const lastId = this.ids[last] as number;\n this.ids[idx] = lastId;\n this.index.set(lastId, idx);\n this.ids.pop();\n this.index.delete(entityId);\n }\n\n /**\n * Matching entity IDs — the live array, not a copy, so reading it allocates\n * nothing and it reflects every add and remove as it happens. Walk it by\n * index on hot paths:\n *\n * const ids = query.entities;\n * for (let i = 0; i < ids.length; i++) { const id = ids[i]!; ... }\n *\n * Because it is live, destroying an entity or changing its components mid-walk\n * swap-removes from this array under the loop and skips an entity: collect\n * first and act after, as the built-in systems do.\n *\n * Order is not guaranteed. Entities are appended as they begin matching and\n * removed by swapping the last element into the hole, so the order reflects\n * match history, not id. It was previously documented as \"sorted\", which was\n * never true: `_check` has always plain-`push`ed, so an entity that starts\n * matching later lands after entities with higher ids (spawn 1,2,3 then add\n * the missing component to 3 first and the array reads `[3, 1, 2]`).\n *\n * The one consumer that cares is `render-system`, whose `sortByDrawOrder` is\n * a *stable* insertion sort on `z` alone — so this order is the tie-break\n * between equal-`z` sprites. It is deliberately not a guarantee: depend on\n * `z`, not on the order entities happen to occupy here.\n */\n get entities(): readonly number[] {\n return this.ids;\n }\n\n /**\n * Iterate matching entity IDs. Convenience form: it allocates an iterator,\n * and on Hermes a result object per entity — walk `entities` by index on\n * hot paths.\n */\n [Symbol.iterator](): IterableIterator<number> {\n return this.ids[Symbol.iterator]();\n }\n\n /** Number of matching entities. */\n get count(): number {\n return this.ids.length;\n }\n\n /** Check if an entity matches this query. */\n has(entityId: number): boolean {\n return this.index.has(entityId);\n }\n}\n\n/**\n * Builder for creating queries with .with() / .without() chaining.\n *\n * Obtain one from `world.queryBuilder()`. `build()` hands the finished Query to\n * the World it came from, which is what keeps it populated; the registration\n * hook is a required constructor argument so a builder cannot exist without a\n * World behind it, and the orphan `new QueryBuilder().build()` does not compile.\n */\nexport class QueryBuilder {\n private required = 0;\n private excluded = 0;\n private readonly register: (q: Query) => void;\n\n constructor(register: (q: Query) => void) {\n this.register = register;\n }\n\n with(...components: ComponentDef<unknown>[]): this {\n for (const c of components) {\n this.required |= c.bit;\n }\n return this;\n }\n\n without(...components: ComponentDef<unknown>[]): this {\n for (const c of components) {\n this.excluded |= c.bit;\n }\n return this;\n }\n\n /** Build the query and register it with the owning World. */\n build(): Query {\n const q = new Query(this.required, this.excluded);\n this.register(q);\n return q;\n }\n}\n","import type { Query } from './query.js';\nimport type { World } from './world.js';\n\n/** A system function that processes entities matching a query. */\nexport type SystemFn = (query: Query, dt: number, world: World) => void;\n\n/** A defined system with its query and function. */\nexport interface SystemDef {\n readonly query: Query;\n readonly fn: SystemFn;\n /**\n * The wrapper to register on the World via `world.addSystem(sys.worldFn)`;\n * pass the same reference to `removeSystem`.\n */\n readonly worldFn: (world: World, dt: number) => void;\n /** @deprecated Use `worldFn` — the same function reference. Removed in the next planned minor. */\n readonly _worldFn: (world: World, dt: number) => void;\n}\n\n/**\n * Define a system that processes entities matching a query.\n *\n * Returns a SystemDef that can be added to a World via world.addSystem().\n * The system function receives the query's matching entities, dt, and world.\n *\n * Usage:\n * const q = world.query(Position, Velocity);\n * const moveSys = defineSystem(q, (query, dt, world) => {\n * const ids = query.entities;\n * for (let i = 0; i < ids.length; i++) { const id = ids[i]!; ... }\n * });\n * world.addSystem(moveSys.worldFn);\n *\n * Walk `query.entities` by index — that is the zero-alloc form. `for...of`\n * over the query works too but allocates an iterator per loop (and, on\n * Hermes, a result object per entity), which per system per frame is exactly\n * what a system must not do.\n */\nexport function defineSystem(query: Query, fn: SystemFn): SystemDef {\n const worldFn = (world: World, dt: number) => {\n fn(query, dt, world);\n };\n return { query, fn, worldFn, _worldFn: worldFn };\n}\n","import { Follower, Lifetime, Position, Velocity } from './components.js';\nimport type { Query } from './query.js';\nimport type { SystemDef } from './system.js';\nimport { defineSystem } from './system.js';\nimport type { World } from './world.js';\n\n/**\n * Plain camera-space bounding box used by createBoundsCullSystem.\n * Keep plain numbers — do NOT import physics AABB/Bounds (layer inversion).\n */\nexport interface CullBounds {\n readonly minX: number;\n readonly minY: number;\n readonly maxX: number;\n readonly maxY: number;\n}\n\n/**\n * createMovementSystem — integrates Position by Velocity * dt each frame.\n *\n * Recommended priority: run BEFORE createFollowerSystem (0).\n */\nexport function createMovementSystem(world: World): SystemDef {\n const q = world.query(Position, Velocity);\n return defineSystem(q, (query, dt, w) => {\n const ids = query.entities;\n for (let i = 0; i < ids.length; i++) {\n const id = ids[i]!;\n const pos = w.get(id, Position)!;\n const vel = w.get(id, Velocity)!;\n pos.x += vel.x * dt;\n pos.y += vel.y * dt;\n }\n });\n}\n\n/**\n * createLifetimeSystem — decrements Lifetime.remaining each frame.\n * Entities whose remaining reaches <= 0 are collected, then onExpire is called\n * for each AFTER the read loop.\n *\n * Deferred removal: destroying inside a live walk of query.entities swap-removes\n * from the array mid-iteration and would skip entities. Collect first, act after.\n *\n * The scratch array is closure-owned and grow-only — zero steady-state alloc.\n *\n * @param onExpire Destroy / pool policy — ecs never destroys on its own.\n * @param query Optional caller-supplied Query. When omitted the system\n * registers world.query(Lifetime) itself. Pass a narrower\n * query to avoid scanning unrelated Lifetime holders and to\n * share an already-registered query (eliminates duplicate\n * World.query registration cost).\n */\nexport function createLifetimeSystem(\n world: World,\n onExpire: (entity: number, world: World) => void,\n query?: Query,\n): SystemDef {\n const q = query ?? world.query(Lifetime);\n const scratch: number[] = [];\n return defineSystem(q, (query, dt, w) => {\n scratch.length = 0;\n const ids = query.entities;\n for (let i = 0; i < ids.length; i++) {\n const id = ids[i]!;\n const life = w.get(id, Lifetime)!;\n life.remaining -= dt;\n if (life.remaining <= 0) {\n scratch.push(id);\n }\n }\n for (let i = 0; i < scratch.length; i++) {\n onExpire(scratch[i]!, w);\n }\n });\n}\n\n/**\n * createBoundsCullSystem — culls entities whose Position falls outside bounds.\n * Reads bounds LIVE each frame so callers can mutate it to follow a camera.\n * Entities outside are collected, then onCull is called for each after the read loop.\n *\n * Deferred removal: same splice-during-iteration reason as createLifetimeSystem.\n *\n * Recommended priority: run AFTER createMovementSystem and createFollowerSystem.\n *\n * @param bounds Mutable bounding box read each frame.\n * @param onCull Destroy / pool policy — ecs never destroys on its own.\n * @param query Optional caller-supplied Query. When omitted the system\n * registers world.query(Position) itself, scanning all\n * Position holders. Pass a narrower query (e.g. bullets\n * only) to avoid scanning unrelated entities such as\n * scrolling backgrounds, and to share an already-registered\n * query with the caller.\n */\nexport function createBoundsCullSystem(\n world: World,\n bounds: CullBounds,\n onCull: (entity: number, world: World) => void,\n query?: Query,\n): SystemDef {\n const q = query ?? world.query(Position);\n const scratch: number[] = [];\n return defineSystem(q, (query, _dt, w) => {\n scratch.length = 0;\n const ids = query.entities;\n for (let i = 0; i < ids.length; i++) {\n const id = ids[i]!;\n const pos = w.get(id, Position)!;\n if (\n pos.x < bounds.minX ||\n pos.x > bounds.maxX ||\n pos.y < bounds.minY ||\n pos.y > bounds.maxY\n ) {\n scratch.push(id);\n }\n }\n for (let i = 0; i < scratch.length; i++) {\n onCull(scratch[i]!, w);\n }\n });\n}\n\n/**\n * createFollowerSystem — pins each Follower entity's Position to\n * target.Position + (offsetX, offsetY).\n * If the target is gone or has no Position, the entity is silently skipped.\n *\n * Recommended priority: run AFTER createMovementSystem (1) so the target's\n * position is already integrated before the follower snaps to it.\n */\nexport function createFollowerSystem(world: World): SystemDef {\n const q = world.query(Position, Follower);\n return defineSystem(q, (query, _dt, w) => {\n const ids = query.entities;\n for (let i = 0; i < ids.length; i++) {\n const id = ids[i]!;\n const follower = w.get(id, Follower)!;\n const t = w.get(follower.target, Position);\n if (t === undefined) continue;\n const pos = w.get(id, Position)!;\n pos.x = t.x + follower.offsetX;\n pos.y = t.y + follower.offsetY;\n }\n });\n}\n\n/**\n * createOrphanCullSystem — fires onOrphan for each Follower whose target entity\n * no longer exists. Does NOT move or destroy anything itself.\n *\n * Split from createFollowerSystem so games that want to orphan-cull can opt in\n * without coupling destruction to the follower pin logic.\n *\n * Recommended priority: run AFTER createFollowerSystem (2) so the follower is\n * pinned before orphans are detected.\n *\n * Deferred removal: same splice-during-iteration reason as createLifetimeSystem.\n *\n * @param onOrphan Called once per orphaned entity after the read loop.\n */\nexport function createOrphanCullSystem(\n world: World,\n onOrphan: (entity: number, world: World) => void,\n): SystemDef {\n const q = world.query(Follower);\n const scratch: number[] = [];\n return defineSystem(q, (query, _dt, w) => {\n scratch.length = 0;\n const ids = query.entities;\n for (let i = 0; i < ids.length; i++) {\n const id = ids[i]!;\n const follower = w.get(id, Follower)!;\n if (!w.exists(follower.target)) {\n scratch.push(id);\n }\n }\n for (let i = 0; i < scratch.length; i++) {\n onOrphan(scratch[i]!, w);\n }\n });\n}\n","import type { ComponentDef } from './component.js';\nimport { Query, QueryBuilder } from './query.js';\n\n/**\n * World is the central ECS container.\n *\n * Entities are integer IDs. Components are stored in per-component Maps.\n * Archetype bitmasks enable fast query matching.\n */\nexport class World {\n private nextId = 1;\n private archetypes = new Map<number, number>(); // entityId → bitmask\n private componentStores = new Map<number, Map<number, unknown>>(); // componentId → (entityId → data)\n private queries: Query[] = [];\n private queryIterDepth = 0;\n private pendingQueryRemove: Query[] | null = null;\n private systems: {\n fn: (world: World, dt: number) => void;\n priority: number;\n }[] = [];\n private systemsSorted = false;\n\n /** Create a new entity. Returns the entity ID. */\n spawn(): number {\n const id = this.nextId++;\n this.archetypes.set(id, 0);\n return id;\n }\n\n /** Remove an entity and all its components. */\n destroy(entityId: number): void {\n const arch = this.archetypes.get(entityId);\n if (arch === undefined) return;\n\n // Remove from all component stores\n for (const [, store] of this.componentStores) {\n store.delete(entityId);\n }\n\n this.archetypes.delete(entityId);\n\n this.notifyQueries(entityId, 0, true);\n }\n\n /** Add a component to an entity. */\n add<T>(entityId: number, def: ComponentDef<T>, data?: T): void {\n const arch = this.archetypes.get(entityId);\n if (arch === undefined) return;\n\n // Store component data\n let store = this.componentStores.get(def.id);\n if (!store) {\n store = new Map();\n this.componentStores.set(def.id, store);\n }\n store.set(entityId, data !== undefined ? data : def.create());\n\n // Update archetype\n const newArch = arch | def.bit;\n this.archetypes.set(entityId, newArch);\n\n this.notifyQueries(entityId, newArch, false);\n }\n\n /** Remove a component from an entity. */\n remove<T>(entityId: number, def: ComponentDef<T>): void {\n const arch = this.archetypes.get(entityId);\n if (arch === undefined) return;\n\n const store = this.componentStores.get(def.id);\n if (store) store.delete(entityId);\n\n const newArch = arch & ~def.bit;\n this.archetypes.set(entityId, newArch);\n\n this.notifyQueries(entityId, newArch, false);\n }\n\n /** Get component data for an entity. */\n get<T>(entityId: number, def: ComponentDef<T>): T | undefined {\n const store = this.componentStores.get(def.id);\n return store?.get(entityId) as T | undefined;\n }\n\n /** Check if entity has a component. */\n has(entityId: number, def: ComponentDef<unknown>): boolean {\n const arch = this.archetypes.get(entityId);\n return arch !== undefined && (arch & def.bit) !== 0;\n }\n\n /** Check if entity exists. */\n exists(entityId: number): boolean {\n return this.archetypes.has(entityId);\n }\n\n /** Number of live entities. */\n get entityCount(): number {\n return this.archetypes.size;\n }\n\n /**\n * Walk every live entity ID. Iterates the live archetype map directly, with no\n * array snapshot. Archetype changes (add/remove component) keep the same entity\n * keys, so iteration is stable across them. Destroying entities inside the\n * callback is safe, but entities spawned inside it are visited in the same pass\n * (live Map iteration) — don't spawn from within.\n */\n forEachEntity(cb: (entity: number) => void): void {\n for (const entityId of this.archetypes.keys()) {\n cb(entityId);\n }\n }\n\n /**\n * Create a query. Queries auto-update as entities change.\n * Use the QueryBuilder-style chaining:\n * world.query(Position, Velocity)\n * Or use the builder:\n * world.queryBuilder().with(Position).without(Dead).build()\n */\n query(...components: ComponentDef<unknown>[]): Query {\n let mask = 0;\n for (const c of components) {\n mask |= c.bit;\n }\n const q = new Query(mask, 0);\n this.register(q);\n return q;\n }\n\n /** Create a QueryBuilder for complex queries (with/without). */\n queryBuilder(): QueryBuilder {\n return new QueryBuilder((q) => this.register(q));\n }\n\n /** Track a query and populate it with the entities that already match. */\n private register(q: Query): void {\n this.queries.push(q);\n for (const [entityId, arch] of this.archetypes) {\n q._check(entityId, arch);\n }\n }\n\n /**\n * Dispose a query created by `query()` or `queryBuilder().build()`. Afterwards\n * the world stops updating it, so it no longer costs spawn/add/remove iteration\n * time. The query is left inert — drop the reference to let it be collected.\n *\n * Safe to call from within a Query signal handler (e.g. a one-shot\n * `onEntityAdded` that disposes its own query): the removal is deferred until\n * the in-progress mutation finishes iterating, so no other query is skipped.\n */\n removeQuery(q: Query): void {\n if (this.queryIterDepth > 0) {\n if (this.pendingQueryRemove === null) this.pendingQueryRemove = [];\n this.pendingQueryRemove.push(q);\n return;\n }\n const idx = this.queries.indexOf(q);\n if (idx !== -1) this.queries.splice(idx, 1);\n }\n\n /** Notify queries in order, deferring any removeQuery until the loop unwinds. */\n private notifyQueries(entityId: number, arch: number, destroyed: boolean): void {\n this.queryIterDepth++;\n try {\n if (destroyed) {\n for (const query of this.queries) {\n query._remove(entityId);\n }\n } else {\n for (const query of this.queries) {\n query._check(entityId, arch);\n }\n }\n } finally {\n this.endQueryIteration();\n }\n }\n\n /** @internal End a query-notify loop; flush any removeQuery deferred during it. */\n private endQueryIteration(): void {\n this.queryIterDepth--;\n if (this.queryIterDepth === 0 && this.pendingQueryRemove !== null) {\n for (const q of this.pendingQueryRemove) {\n const idx = this.queries.indexOf(q);\n if (idx !== -1) this.queries.splice(idx, 1);\n }\n this.pendingQueryRemove.length = 0;\n }\n }\n\n /** Register a system function. Lower priority runs first. */\n addSystem(fn: (world: World, dt: number) => void, priority = 0): void {\n this.systems.push({ fn, priority });\n this.systemsSorted = false;\n }\n\n /** Remove a system. */\n removeSystem(fn: (world: World, dt: number) => void): void {\n const idx = this.systems.findIndex((s) => s.fn === fn);\n if (idx !== -1) this.systems.splice(idx, 1);\n }\n\n /** Run all systems in priority order. */\n step(dt: number): void {\n if (!this.systemsSorted) {\n this.systems.sort((a, b) => a.priority - b.priority);\n this.systemsSorted = true;\n }\n for (const sys of this.systems) {\n sys.fn(this, dt);\n }\n }\n}\n"],"mappings":";;;AAmBA,IAAI,kBAAkB;;;;;;;AAQtB,SAAgB,gBAA+B,MAAc,UAAqC;CAChG,MAAM,KAAK;CACX,IAAI,MAAM,IACR,MAAM,IAAI,MAAM,kDAAkD,KAAK,GAAG;CAE5E,OAAO;EACL;EACA,KAAK,KAAK;EACV;EACA,QAAQ,mBAAmB,KAAA;CAC7B;AACF;;;;;AAMA,SAAgB,qBAA2B;CACzC,kBAAkB;AACpB;;;;;;ACtCA,MAAa,WAAW,gBAAsB,mBAAmB;CAC/D,GAAG;CACH,GAAG;AACL,EAAE;;AAGF,MAAa,WAAW,gBAAsB,mBAAmB;CAC/D,GAAG;CACH,GAAG;AACL,EAAE;;AAGF,MAAa,WAAW,gBAAmC,mBAAmB,EAC5E,OAAO,EACT,EAAE;;AAGF,MAAa,QAAQ,gBAAsB,gBAAgB;CAAE,GAAG;CAAG,GAAG;AAAE,EAAE;;AAG1E,MAAa,SAAS,gBAAoC,iBAAiB,EACzE,QAAQ,EACV,EAAE;;AAGF,MAAa,WAAW,gBAAuC,mBAAmB,EAChF,WAAW,EACb,EAAE;;AAGF,MAAa,WAAW,gBACtB,mBACO;CAAE,QAAQ;CAAG,SAAS;CAAG,SAAS;AAAE,EAC7C;;;;;;;;AC3BA,IAAa,MAAb,MAAgC;CACtB;CACA,0BAAU,IAAI,IAAsB;CACpC,+BAAe,IAAI,IAAiC;CACpD;CAER,YAAY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gB;CACvB;;CAGA,aAAa,IAA8C;EACzD,MAAM,MAAM,KAAK,QAAQ,WAAW,MAAM,EAAE,OAAO,EAAE;EACrD,IAAI,QAAQ,IAAI,KAAK,QAAQ,OAAO,KAAK,CAAC;CAC5C;;CAGA,KAAK,IAAkB;EACrB,IAAI,CAAC,KAAK,eAAe;GACvB,KAAK,QAAQ,MAAM,GAAG,MAAM,EAAE,WAAW,EAAE,QAAQ;GACnD,KAAK,gBAAgB;EACvB;EACA,KAAK,MAAM,OAAO,KAAK,SACrB,IAAI,GAAG,MAAM,EAAE;CAEnB;AACF"}
1
+ {"version":3,"file":"index.js","names":["Signal"],"sources":["../src/component.ts","../src/components.ts","../src/fsm.ts","../src/prefab.ts","../src/query.ts","../src/system.ts","../src/systems.ts","../src/world.ts"],"sourcesContent":["/**\n * Component definition and factory.\n *\n * Components are plain data objects. Each component type gets a unique\n * bit for archetype-based query matching.\n */\n\n/** A unique component definition. */\nexport interface ComponentDef<T> {\n /**\n * Internal unique ID (auto-assigned).\n * @deprecated Removed in 0.5.0. A `World` no longer keys storage by it, and it comes from a\n * module-global counter, so it depends on import order and must never be persisted. Key by the\n * definition object itself instead (e.g. a `Map<ComponentDef<unknown>, …>`).\n */\n readonly id: number;\n /**\n * Bitmask for this component (1 << id).\n * @deprecated Removed in 0.5.0, which lifts the 32-type cap: `1 << id` wraps from the 33rd\n * definition on. A `World` no longer keys storage by it. Key by the definition object itself\n * instead (e.g. a `Map<ComponentDef<unknown>, …>`).\n */\n readonly bit: number;\n /** Component name for debugging. */\n readonly name: string;\n /** Create a new instance with default values. */\n create(): T;\n}\n\nlet nextComponentId = 0;\n\n/**\n * Define a new component type.\n *\n * @param name Debug name for the component.\n * @param defaults Factory function returning default values, or undefined for tag components.\n */\nexport function defineComponent<T = undefined>(name: string, defaults?: () => T): ComponentDef<T> {\n const id = nextComponentId++;\n if (id >= 32) {\n throw new Error(`Maximum 32 component types exceeded (defining \"${name}\")`);\n }\n return {\n id,\n bit: 1 << id,\n name,\n create: defaults ?? (() => undefined as T),\n };\n}\n\n/**\n * Reset the component ID counter. Only for testing.\n * @internal\n * @deprecated Removed in 0.5.0 together with the global counter it resets. Each `World` keys\n * storage by the definition object, so isolating storage between tests needs no reset.\n */\nexport function _resetComponentIds(): void {\n nextComponentId = 0;\n}\n","import type { Vec2 } from '@flare-engine/math';\nimport { defineComponent } from './component.js';\n\n/**\n * Built-in ECS components using @flare-engine/math types.\n */\n\n/** 2D position component. */\nexport const Position = defineComponent<Vec2>('Position', () => ({\n x: 0,\n y: 0,\n}));\n\n/** 2D velocity component. */\nexport const Velocity = defineComponent<Vec2>('Velocity', () => ({\n x: 0,\n y: 0,\n}));\n\n/** Rotation in radians. */\nexport const Rotation = defineComponent<{ angle: number }>('Rotation', () => ({\n angle: 0,\n}));\n\n/** 2D scale component. */\nexport const Scale = defineComponent<Vec2>('Scale', () => ({ x: 1, y: 1 }));\n\n/** Parent entity reference. */\nexport const Parent = defineComponent<{ entity: number }>('Parent', () => ({\n entity: 0,\n}));\n\n/** Countdown timer in seconds; entity expires when remaining reaches 0. */\nexport const Lifetime = defineComponent<{ remaining: number }>('Lifetime', () => ({\n remaining: 0,\n}));\n\n/** Pins an entity's position to a target entity plus a fixed offset. */\nexport const Follower = defineComponent<{ target: number; offsetX: number; offsetY: number }>(\n 'Follower',\n () => ({ target: 0, offsetX: 0, offsetY: 0 }),\n);\n","/** A state in the FSM. */\nexport interface State<C = undefined> {\n readonly name: string;\n onEnter?(context: C): void;\n onExit?(context: C): void;\n onUpdate?(dt: number, context: C): void;\n}\n\n/**\n * Lightweight finite state machine. ~100 LOC.\n *\n * Manages named states with onEnter/onExit/onUpdate hooks\n * and string-keyed transitions.\n */\nexport class FSM<C = undefined> {\n private _current: State<C> | undefined;\n private _states = new Map<string, State<C>>();\n private _transitions = new Map<string, Map<string, string>>();\n private _context: C;\n\n constructor(...args: C extends undefined ? [] : [context: C]) {\n this._context = args[0] as C;\n }\n\n /** The currently active state, or undefined if none. */\n get current(): State<C> | undefined {\n return this._current;\n }\n\n /** Register a state. */\n addState(state: State<C>): this {\n this._states.set(state.name, state);\n return this;\n }\n\n /**\n * Register a transition.\n * When `trigger` fires in `fromState`, transition to `toState`.\n */\n addTransition(fromState: string, trigger: string, toState: string): this {\n let map = this._transitions.get(fromState);\n if (!map) {\n map = new Map();\n this._transitions.set(fromState, map);\n }\n map.set(trigger, toState);\n return this;\n }\n\n /** Set the initial state (calls onEnter). */\n start(stateName: string): void {\n const state = this._states.get(stateName);\n if (!state) return;\n this._current = state;\n state.onEnter?.(this._context);\n }\n\n /** Fire a trigger. If a matching transition exists, switch states. */\n trigger(name: string): void {\n if (!this._current) return;\n const transitions = this._transitions.get(this._current.name);\n if (!transitions) return;\n const target = transitions.get(name);\n if (target === undefined) return;\n const next = this._states.get(target);\n if (!next) return;\n this._current.onExit?.(this._context);\n this._current = next;\n next.onEnter?.(this._context);\n }\n\n /** Update the current state. */\n update(dt: number): void {\n this._current?.onUpdate?.(dt, this._context);\n }\n}\n","import type { ComponentDef } from './component.js';\nimport type { World } from './world.js';\n\n/** A component entry in a prefab definition. */\ninterface PrefabEntry<T> {\n def: ComponentDef<T>;\n data?: T | (() => T);\n}\n\n/** A prefab factory that spawns entities with pre-defined components. */\nexport interface Prefab {\n readonly name: string;\n /** Spawn an entity with this prefab's components. */\n spawn(world: World): number;\n}\n\n/**\n * Define a prefab — a template for spawning entities with a fixed set of components.\n *\n * Plain-object data is stored by reference and shared by every spawn; pass\n * `() => T` for per-entity mutable state. This mirrors `world.add(entity, def,\n * data)`, which stores the object it is given — so the object form is for\n * data no entity will mutate, and the factory runs once per spawn.\n *\n * @param name Debug name.\n * @param entries Array of [componentDef, data?] tuples.\n */\nexport function definePrefab(\n name: string,\n ...entries: [ComponentDef<unknown>, (unknown | (() => unknown))?][]\n): Prefab {\n const components: PrefabEntry<unknown>[] = entries.map(([def, data]) => ({\n def,\n data,\n }));\n\n return {\n name,\n spawn(world: World): number {\n const entity = world.spawn();\n for (const entry of components) {\n const data =\n typeof entry.data === 'function' ? (entry.data as () => unknown)() : entry.data;\n world.add(entity, entry.def, data);\n }\n return entity;\n },\n };\n}\n","import { Signal } from '@flare-engine/events';\nimport type { ComponentDef } from './component.js';\n\n/**\n * Query matches entities based on component archetypes.\n *\n * Uses bitmask matching: entity archetype & requiredMask === requiredMask\n * and entity archetype & excludedMask === 0.\n *\n * Two ways to walk the matches:\n * - `entities` — the live id array, for an indexed `for` loop. Allocates\n * nothing; this is the form for systems and anything else that runs per frame.\n * - `for...of` — the convenience form. It creates an iterator, and on Hermes\n * (React Native) one `{ value, done }` object per entity per pass, so keep\n * it off the frame path.\n */\nexport class Query {\n /**\n * Bitmask of required components.\n * @deprecated Leaves the public API in 0.5.0, which sizes masks per World. Build queries with\n * `world.query()` / `world.queryBuilder()` and test membership with `query.has(entity)`.\n */\n readonly requiredMask: number;\n /**\n * Bitmask of excluded components.\n * @deprecated Leaves the public API in 0.5.0, which sizes masks per World. Build queries with\n * `world.query()` / `world.queryBuilder()` and test membership with `query.has(entity)`.\n */\n readonly excludedMask: number;\n\n /** Fires when an entity is added to this query's results. */\n readonly onEntityAdded = new Signal<number>();\n /** Fires when an entity is removed from this query's results. */\n readonly onEntityRemoved = new Signal<number>();\n\n private ids: number[] = [];\n /**\n * `entityId -> index into ids`. Serves membership *and* position, which\n * is what makes removal O(1): the previous pair of a `Set` plus `indexOf`\n * made every removal a linear scan, so churn cost grew as `n * removals`\n * rather than with the number of removals.\n */\n private index = new Map<number, number>();\n\n /**\n * @deprecated Leaves the public API in 0.5.0, which sizes masks per World, so a raw mask stops\n * being a valid argument. Build queries with `world.query()` / `world.queryBuilder()`.\n */\n constructor(requiredMask: number, excludedMask: number) {\n this.requiredMask = requiredMask;\n this.excludedMask = excludedMask;\n }\n\n /**\n * Check if an archetype matches this query.\n * @deprecated Leaves the public API in 0.5.0, which sizes masks per World, so a raw archetype\n * mask stops being a valid argument. Test membership with `query.has(entity)`.\n */\n matches(archetype: number): boolean {\n return (\n (archetype & this.requiredMask) === this.requiredMask && (archetype & this.excludedMask) === 0\n );\n }\n\n /** @internal — called by World when an entity's archetype changes. */\n _check(entityId: number, archetype: number): void {\n const isMatch = this.matches(archetype);\n const wasMatch = this.index.has(entityId);\n\n if (isMatch && !wasMatch) {\n this.index.set(entityId, this.ids.length);\n this.ids.push(entityId);\n this.onEntityAdded.emit(entityId);\n } else if (!isMatch && wasMatch) {\n this.swapRemove(entityId);\n this.onEntityRemoved.emit(entityId);\n }\n }\n\n /** @internal — called by World when an entity is removed entirely. */\n _remove(entityId: number): void {\n if (this.index.has(entityId)) {\n this.swapRemove(entityId);\n this.onEntityRemoved.emit(entityId);\n }\n }\n\n /**\n * O(1) removal: move the last element into the hole and shorten by one.\n *\n * Order-preserving removal cannot be O(1) here — `splice` shifts every later\n * element, and a position map would then need every shifted index rewritten,\n * so it costs the same scan it was meant to remove. A tombstone would keep\n * order but puts a branch in iteration, which at realistic churn runs far\n * more often than removal and would slow the steady-state path to speed up\n * the rare one.\n */\n private swapRemove(entityId: number): void {\n const idx = this.index.get(entityId) as number;\n const last = this.ids.length - 1;\n const lastId = this.ids[last] as number;\n this.ids[idx] = lastId;\n this.index.set(lastId, idx);\n this.ids.pop();\n this.index.delete(entityId);\n }\n\n /**\n * Matching entity IDs — the live array, not a copy, so reading it allocates\n * nothing and it reflects every add and remove as it happens. Walk it by\n * index on hot paths:\n *\n * const ids = query.entities;\n * for (let i = 0; i < ids.length; i++) { const id = ids[i]!; ... }\n *\n * Because it is live, destroying an entity or changing its components mid-walk\n * swap-removes from this array under the loop and skips an entity: collect\n * first and act after, as the built-in systems do.\n *\n * Order is not guaranteed. Entities are appended as they begin matching and\n * removed by swapping the last element into the hole, so the order reflects\n * match history, not id. It was previously documented as \"sorted\", which was\n * never true: `_check` has always plain-`push`ed, so an entity that starts\n * matching later lands after entities with higher ids (spawn 1,2,3 then add\n * the missing component to 3 first and the array reads `[3, 1, 2]`).\n *\n * The one consumer that cares is `render-system`, whose `sortByDrawOrder` is\n * a *stable* insertion sort on `z` alone — so this order is the tie-break\n * between equal-`z` sprites. It is deliberately not a guarantee: depend on\n * `z`, not on the order entities happen to occupy here.\n */\n get entities(): readonly number[] {\n return this.ids;\n }\n\n /**\n * Iterate matching entity IDs. Convenience form: it allocates an iterator,\n * and on Hermes a result object per entity — walk `entities` by index on\n * hot paths.\n */\n [Symbol.iterator](): IterableIterator<number> {\n return this.ids[Symbol.iterator]();\n }\n\n /** Number of matching entities. */\n get count(): number {\n return this.ids.length;\n }\n\n /** Check if an entity matches this query. */\n has(entityId: number): boolean {\n return this.index.has(entityId);\n }\n}\n\n/**\n * Builder for creating queries with .with() / .without() chaining.\n *\n * Obtain one from `world.queryBuilder()`. `build()` hands the finished Query to\n * the World it came from, which is what keeps it populated; the registration\n * hook is a required constructor argument so a builder cannot exist without a\n * World behind it, and the orphan `new QueryBuilder().build()` does not compile.\n */\nexport class QueryBuilder {\n private required = 0;\n private excluded = 0;\n private readonly register: (q: Query) => void;\n\n constructor(register: (q: Query) => void) {\n this.register = register;\n }\n\n with(...components: ComponentDef<unknown>[]): this {\n this.required |= (maskResolvers.get(this) ?? orBits)(components);\n return this;\n }\n\n without(...components: ComponentDef<unknown>[]): this {\n this.excluded |= (maskResolvers.get(this) ?? orBits)(components);\n return this;\n }\n\n /** Build the query and register it with the owning World. */\n build(): Query {\n const q = new Query(this.required, this.excluded);\n this.register(q);\n return q;\n }\n}\n\ntype MaskOf = (defs: readonly ComponentDef<unknown>[]) => number;\n\n// Kept off QueryBuilder's public surface: the mask representation is not part of\n// the contract (#173), so the World attaches its resolver here, not through the\n// constructor. A builder without one ORs each `def.bit`.\nconst maskResolvers = new WeakMap<QueryBuilder, MaskOf>();\n\n/** World-only (not exported from the package): route a builder's masks through the World's registry. */\nexport function bindMaskResolver(builder: QueryBuilder, maskOf: MaskOf): QueryBuilder {\n maskResolvers.set(builder, maskOf);\n return builder;\n}\n\nfunction orBits(defs: readonly ComponentDef<unknown>[]): number {\n let mask = 0;\n for (const c of defs) {\n mask |= c.bit;\n }\n return mask;\n}\n","import type { Query } from './query.js';\nimport type { World } from './world.js';\n\n/** A system function that processes entities matching a query. */\nexport type SystemFn = (query: Query, dt: number, world: World) => void;\n\n/** A defined system with its query and function. */\nexport interface SystemDef {\n readonly query: Query;\n readonly fn: SystemFn;\n /**\n * The wrapper to register on the World via `world.addSystem(sys.worldFn)`;\n * pass the same reference to `removeSystem`.\n */\n readonly worldFn: (world: World, dt: number) => void;\n /** @deprecated Use `worldFn` — the same function reference. Removed in the next planned minor. */\n readonly _worldFn: (world: World, dt: number) => void;\n}\n\n/**\n * Define a system that processes entities matching a query.\n *\n * Returns a SystemDef that can be added to a World via world.addSystem().\n * The system function receives the query's matching entities, dt, and world.\n *\n * Usage:\n * const q = world.query(Position, Velocity);\n * const moveSys = defineSystem(q, (query, dt, world) => {\n * const ids = query.entities;\n * for (let i = 0; i < ids.length; i++) { const id = ids[i]!; ... }\n * });\n * world.addSystem(moveSys.worldFn);\n *\n * Walk `query.entities` by index — that is the zero-alloc form. `for...of`\n * over the query works too but allocates an iterator per loop (and, on\n * Hermes, a result object per entity), which per system per frame is exactly\n * what a system must not do.\n */\nexport function defineSystem(query: Query, fn: SystemFn): SystemDef {\n const worldFn = (world: World, dt: number) => {\n fn(query, dt, world);\n };\n return { query, fn, worldFn, _worldFn: worldFn };\n}\n","import { Follower, Lifetime, Position, Velocity } from './components.js';\nimport type { Query } from './query.js';\nimport type { SystemDef } from './system.js';\nimport { defineSystem } from './system.js';\nimport type { World } from './world.js';\n\n/**\n * Plain camera-space bounding box used by createBoundsCullSystem.\n * Keep plain numbers — do NOT import physics AABB/Bounds (layer inversion).\n */\nexport interface CullBounds {\n readonly minX: number;\n readonly minY: number;\n readonly maxX: number;\n readonly maxY: number;\n}\n\n/**\n * createMovementSystem — integrates Position by Velocity * dt each frame.\n *\n * Recommended priority: run BEFORE createFollowerSystem (0).\n */\nexport function createMovementSystem(world: World): SystemDef {\n const q = world.query(Position, Velocity);\n return defineSystem(q, (query, dt, w) => {\n const ids = query.entities;\n for (let i = 0; i < ids.length; i++) {\n const id = ids[i]!;\n const pos = w.get(id, Position)!;\n const vel = w.get(id, Velocity)!;\n pos.x += vel.x * dt;\n pos.y += vel.y * dt;\n }\n });\n}\n\n/**\n * createLifetimeSystem — decrements Lifetime.remaining each frame.\n * Entities whose remaining reaches <= 0 are collected, then onExpire is called\n * for each AFTER the read loop.\n *\n * Deferred removal: destroying inside a live walk of query.entities swap-removes\n * from the array mid-iteration and would skip entities. Collect first, act after.\n *\n * The scratch array is closure-owned and grow-only — zero steady-state alloc.\n *\n * @param onExpire Destroy / pool policy — ecs never destroys on its own.\n * @param query Optional caller-supplied Query. When omitted the system\n * registers world.query(Lifetime) itself. Pass a narrower\n * query to avoid scanning unrelated Lifetime holders and to\n * share an already-registered query (eliminates duplicate\n * World.query registration cost).\n */\nexport function createLifetimeSystem(\n world: World,\n onExpire: (entity: number, world: World) => void,\n query?: Query,\n): SystemDef {\n const q = query ?? world.query(Lifetime);\n const scratch: number[] = [];\n return defineSystem(q, (query, dt, w) => {\n scratch.length = 0;\n const ids = query.entities;\n for (let i = 0; i < ids.length; i++) {\n const id = ids[i]!;\n const life = w.get(id, Lifetime)!;\n life.remaining -= dt;\n if (life.remaining <= 0) {\n scratch.push(id);\n }\n }\n for (let i = 0; i < scratch.length; i++) {\n onExpire(scratch[i]!, w);\n }\n });\n}\n\n/**\n * createBoundsCullSystem — culls entities whose Position falls outside bounds.\n * Reads bounds LIVE each frame so callers can mutate it to follow a camera.\n * Entities outside are collected, then onCull is called for each after the read loop.\n *\n * Deferred removal: same splice-during-iteration reason as createLifetimeSystem.\n *\n * Recommended priority: run AFTER createMovementSystem and createFollowerSystem.\n *\n * @param bounds Mutable bounding box read each frame.\n * @param onCull Destroy / pool policy — ecs never destroys on its own.\n * @param query Optional caller-supplied Query. When omitted the system\n * registers world.query(Position) itself, scanning all\n * Position holders. Pass a narrower query (e.g. bullets\n * only) to avoid scanning unrelated entities such as\n * scrolling backgrounds, and to share an already-registered\n * query with the caller.\n */\nexport function createBoundsCullSystem(\n world: World,\n bounds: CullBounds,\n onCull: (entity: number, world: World) => void,\n query?: Query,\n): SystemDef {\n const q = query ?? world.query(Position);\n const scratch: number[] = [];\n return defineSystem(q, (query, _dt, w) => {\n scratch.length = 0;\n const ids = query.entities;\n for (let i = 0; i < ids.length; i++) {\n const id = ids[i]!;\n const pos = w.get(id, Position)!;\n if (\n pos.x < bounds.minX ||\n pos.x > bounds.maxX ||\n pos.y < bounds.minY ||\n pos.y > bounds.maxY\n ) {\n scratch.push(id);\n }\n }\n for (let i = 0; i < scratch.length; i++) {\n onCull(scratch[i]!, w);\n }\n });\n}\n\n/**\n * createFollowerSystem — pins each Follower entity's Position to\n * target.Position + (offsetX, offsetY).\n * If the target is gone or has no Position, the entity is silently skipped.\n *\n * Recommended priority: run AFTER createMovementSystem (1) so the target's\n * position is already integrated before the follower snaps to it.\n */\nexport function createFollowerSystem(world: World): SystemDef {\n const q = world.query(Position, Follower);\n return defineSystem(q, (query, _dt, w) => {\n const ids = query.entities;\n for (let i = 0; i < ids.length; i++) {\n const id = ids[i]!;\n const follower = w.get(id, Follower)!;\n const t = w.get(follower.target, Position);\n if (t === undefined) continue;\n const pos = w.get(id, Position)!;\n pos.x = t.x + follower.offsetX;\n pos.y = t.y + follower.offsetY;\n }\n });\n}\n\n/**\n * createOrphanCullSystem — fires onOrphan for each Follower whose target entity\n * no longer exists. Does NOT move or destroy anything itself.\n *\n * Split from createFollowerSystem so games that want to orphan-cull can opt in\n * without coupling destruction to the follower pin logic.\n *\n * Recommended priority: run AFTER createFollowerSystem (2) so the follower is\n * pinned before orphans are detected.\n *\n * Deferred removal: same splice-during-iteration reason as createLifetimeSystem.\n *\n * @param onOrphan Called once per orphaned entity after the read loop.\n */\nexport function createOrphanCullSystem(\n world: World,\n onOrphan: (entity: number, world: World) => void,\n): SystemDef {\n const q = world.query(Follower);\n const scratch: number[] = [];\n return defineSystem(q, (query, _dt, w) => {\n scratch.length = 0;\n const ids = query.entities;\n for (let i = 0; i < ids.length; i++) {\n const id = ids[i]!;\n const follower = w.get(id, Follower)!;\n if (!w.exists(follower.target)) {\n scratch.push(id);\n }\n }\n for (let i = 0; i < scratch.length; i++) {\n onOrphan(scratch[i]!, w);\n }\n });\n}\n","import type { ComponentDef } from './component.js';\nimport { bindMaskResolver, Query, QueryBuilder } from './query.js';\n\ninterface ComponentSlot {\n readonly bit: number;\n readonly store: Map<number, unknown>; // entityId → data\n}\n\nconst MAX_COMPONENT_TYPES = 32;\n\n/**\n * World is the central ECS container.\n *\n * Entities are integer IDs. Components are stored in per-component Maps.\n * Archetype bitmasks enable fast query matching.\n */\nexport class World {\n private nextId = 1;\n private archetypes = new Map<number, number>(); // entityId → bitmask\n private slots = new Map<ComponentDef<unknown>, ComponentSlot>();\n private usedBits = 0;\n private stores = new Map<ComponentDef<unknown>, Map<number, unknown>>();\n private storesByBit: (Map<number, unknown> | undefined)[] = new Array(MAX_COMPONENT_TYPES).fill(\n undefined,\n );\n private queries: Query[] = [];\n private queryIterDepth = 0;\n private pendingQueryRemove: Query[] | null = null;\n private systems: {\n fn: (world: World, dt: number) => void;\n priority: number;\n }[] = [];\n private systemsSorted = false;\n\n /** Create a new entity. Returns the entity ID. */\n spawn(): number {\n const id = this.nextId++;\n this.archetypes.set(id, 0);\n return id;\n }\n\n /** Remove an entity and all its components. */\n destroy(entityId: number): void {\n const arch = this.archetypes.get(entityId);\n if (arch === undefined) return;\n\n // Clear the lowest set bit each pass, so only the stores this entity is in are touched.\n for (let m = arch; m !== 0; m &= m - 1) {\n this.storesByBit[31 - Math.clz32(m & -m)]?.delete(entityId);\n }\n\n this.archetypes.delete(entityId);\n\n this.notifyQueries(entityId, 0, true);\n }\n\n /** Add a component to an entity. */\n add<T>(entityId: number, def: ComponentDef<T>, data?: T): void {\n const arch = this.archetypes.get(entityId);\n if (arch === undefined) return;\n\n const slot = this.slotFor(def);\n slot.store.set(entityId, data !== undefined ? data : def.create());\n\n const newArch = arch | slot.bit;\n this.archetypes.set(entityId, newArch);\n\n this.notifyQueries(entityId, newArch, false);\n }\n\n /** Remove a component from an entity. */\n remove<T>(entityId: number, def: ComponentDef<T>): void {\n const arch = this.archetypes.get(entityId);\n if (arch === undefined) return;\n\n const slot = this.slots.get(def);\n if (slot === undefined) return;\n slot.store.delete(entityId);\n\n const newArch = arch & ~slot.bit;\n this.archetypes.set(entityId, newArch);\n\n this.notifyQueries(entityId, newArch, false);\n }\n\n /** Get component data for an entity. */\n get<T>(entityId: number, def: ComponentDef<T>): T | undefined {\n return this.stores.get(def)?.get(entityId) as T | undefined;\n }\n\n /** Check if entity has a component. */\n has(entityId: number, def: ComponentDef<unknown>): boolean {\n const slot = this.slots.get(def);\n if (slot === undefined) return false;\n const arch = this.archetypes.get(entityId);\n return arch !== undefined && (arch & slot.bit) !== 0;\n }\n\n /**\n * The slot a definition holds in this World, assigned on first use. Within one\n * copy of the package ids are unique, so every definition keeps its own `bit`\n * and query masks stay the OR of `def.bit`. Only a definition whose bit is\n * already held here (a second copy of the package, a hand-built literal, reuse\n * after `_resetComponentIds`) gets another one, where it used to share storage.\n */\n private slotFor(def: ComponentDef<unknown>): ComponentSlot {\n const known = this.slots.get(def);\n if (known !== undefined) return known;\n\n const free = ~this.usedBits;\n if (free === 0) throw capacityError(def);\n const own = def.bit | 0;\n const isFreeSingleBit = own !== 0 && (own & (own - 1)) === 0 && (own & free) !== 0;\n const bit = isFreeSingleBit ? own : free & -free;\n\n const slot: ComponentSlot = { bit, store: new Map() };\n this.slots.set(def, slot);\n this.stores.set(def, slot.store);\n this.usedBits |= bit;\n this.storesByBit[31 - Math.clz32(bit)] = slot.store;\n return slot;\n }\n\n /** Mask for a set of definitions. Checks room for all of them before assigning any slot. */\n private maskOf(defs: readonly ComponentDef<unknown>[]): number {\n let room = MAX_COMPONENT_TYPES - this.slots.size;\n let i = 0;\n for (const def of defs) {\n if (!this.slots.has(def) && defs.indexOf(def) === i && room-- === 0) {\n throw capacityError(def);\n }\n i++;\n }\n\n let mask = 0;\n for (const def of defs) {\n mask |= this.slotFor(def).bit;\n }\n return mask;\n }\n\n /** Check if entity exists. */\n exists(entityId: number): boolean {\n return this.archetypes.has(entityId);\n }\n\n /** Number of live entities. */\n get entityCount(): number {\n return this.archetypes.size;\n }\n\n /**\n * Walk every live entity ID. Iterates the live archetype map directly, with no\n * array snapshot. Archetype changes (add/remove component) keep the same entity\n * keys, so iteration is stable across them. Destroying entities inside the\n * callback is safe, but entities spawned inside it are visited in the same pass\n * (live Map iteration) — don't spawn from within.\n */\n forEachEntity(cb: (entity: number) => void): void {\n for (const entityId of this.archetypes.keys()) {\n cb(entityId);\n }\n }\n\n /**\n * Create a query. Queries auto-update as entities change.\n * Use the QueryBuilder-style chaining:\n * world.query(Position, Velocity)\n * Or use the builder:\n * world.queryBuilder().with(Position).without(Dead).build()\n */\n query(...components: ComponentDef<unknown>[]): Query {\n const q = new Query(this.maskOf(components), 0);\n this.register(q);\n return q;\n }\n\n /** Create a QueryBuilder for complex queries (with/without). */\n queryBuilder(): QueryBuilder {\n return bindMaskResolver(new QueryBuilder((q) => this.register(q)), (defs) => this.maskOf(defs));\n }\n\n /** Track a query and populate it with the entities that already match. */\n private register(q: Query): void {\n this.queries.push(q);\n for (const [entityId, arch] of this.archetypes) {\n q._check(entityId, arch);\n }\n }\n\n /**\n * Dispose a query created by `query()` or `queryBuilder().build()`. Afterwards\n * the world stops updating it, so it no longer costs spawn/add/remove iteration\n * time. The query is left inert — drop the reference to let it be collected.\n *\n * Safe to call from within a Query signal handler (e.g. a one-shot\n * `onEntityAdded` that disposes its own query): the removal is deferred until\n * the in-progress mutation finishes iterating, so no other query is skipped.\n */\n removeQuery(q: Query): void {\n if (this.queryIterDepth > 0) {\n if (this.pendingQueryRemove === null) this.pendingQueryRemove = [];\n this.pendingQueryRemove.push(q);\n return;\n }\n const idx = this.queries.indexOf(q);\n if (idx !== -1) this.queries.splice(idx, 1);\n }\n\n /** Notify queries in order, deferring any removeQuery until the loop unwinds. */\n private notifyQueries(entityId: number, arch: number, destroyed: boolean): void {\n this.queryIterDepth++;\n try {\n if (destroyed) {\n for (const query of this.queries) {\n query._remove(entityId);\n }\n } else {\n for (const query of this.queries) {\n query._check(entityId, arch);\n }\n }\n } finally {\n this.endQueryIteration();\n }\n }\n\n /** @internal End a query-notify loop; flush any removeQuery deferred during it. */\n private endQueryIteration(): void {\n this.queryIterDepth--;\n if (this.queryIterDepth === 0 && this.pendingQueryRemove !== null) {\n for (const q of this.pendingQueryRemove) {\n const idx = this.queries.indexOf(q);\n if (idx !== -1) this.queries.splice(idx, 1);\n }\n this.pendingQueryRemove.length = 0;\n }\n }\n\n /** Register a system function. Lower priority runs first. */\n addSystem(fn: (world: World, dt: number) => void, priority = 0): void {\n this.systems.push({ fn, priority });\n this.systemsSorted = false;\n }\n\n /** Remove a system. */\n removeSystem(fn: (world: World, dt: number) => void): void {\n const idx = this.systems.findIndex((s) => s.fn === fn);\n if (idx !== -1) this.systems.splice(idx, 1);\n }\n\n /** Run all systems in priority order. */\n step(dt: number): void {\n if (!this.systemsSorted) {\n this.systems.sort((a, b) => a.priority - b.priority);\n this.systemsSorted = true;\n }\n for (const sys of this.systems) {\n sys.fn(this, dt);\n }\n }\n}\n\nfunction capacityError(def: ComponentDef<unknown>): Error {\n return new Error(`A World holds at most 32 component types (registering \"${def.name}\")`);\n}\n"],"mappings":";;;AA6BA,IAAI,kBAAkB;;;;;;;AAQtB,SAAgB,gBAA+B,MAAc,UAAqC;CAChG,MAAM,KAAK;CACX,IAAI,MAAM,IACR,MAAM,IAAI,MAAM,kDAAkD,KAAK,GAAG;CAE5E,OAAO;EACL;EACA,KAAK,KAAK;EACV;EACA,QAAQ,mBAAmB,KAAA;CAC7B;AACF;;;;;;;AAQA,SAAgB,qBAA2B;CACzC,kBAAkB;AACpB;;;;;;AClDA,MAAa,WAAW,gBAAsB,mBAAmB;CAC/D,GAAG;CAC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AQ,IAAI,KAAK,QAAQ,OAAO,KAAK,CAAC;CAC5C;;CAGQ,cAAc,UAAkB,MAAc,WAA0B;EAC9E,KAAK;EACL,IAAI;GACF,IAAI,WACF,KAAK,MAAM,SAAS,KAAK,SACvB,MAAM,QAAQ,QAAQ;QAGxB,KAAK,MAAM,SAAS,KAAK,SACvB,MAAM,OAAO,UAAU,IAAI;EAGjC,UAAU;GACR,KAAK,kBAAkB;EACzB;CACF;;CAGQ,oBAA0B;EAChC,KAAK;EACL,IAAI,KAAK,mBAAmB,KAAK,KAAK,uBAAuB,MAAM;GACjE,KAAK,MAAM,KAAK,KAAK,oBAAoB;IACvC,MAAM,MAAM,KAAK,QAAQ,QAAQ,CAAC;IAClC,IAAI,QAAQ,IAAI,KAAK,QAAQ,OAAO,KAAK,CAAC;GAC5C;GACA,KAAK,mBAAmB,SAAS;EACnC;CACF;;CAGA,UAAU,IAAwC,WAAW,GAAS;EACpE,KAAK,QAAQ,KAAK;GAAE;GAAI;EAAS,CAAC;EAClC,KAAK,gBAAgB;CACvB;;CAGA,aAAa,IAA8C;EACzD,MAAM,MAAM,KAAK,QAAQ,WAAW,MAAM,EAAE,OAAO,EAAE;EACrD,IAAI,QAAQ,IAAI,KAAK,QAAQ,OAAO,KAAK,CAAC;CAC5C;;CAGA,KAAK,IAAkB;EACrB,IAAI,CAAC,KAAK,eAAe;GACvB,KAAK,QAAQ,MAAM,GAAG,MAAM,EAAE,WAAW,EAAE,QAAQ;GACnD,KAAK,gBAAgB;EACvB;EACA,KAAK,MAAM,OAAO,KAAK,SACrB,IAAI,GAAG,MAAM,EAAE;CAEnB;AACF;AAEA,SAAS,cAAc,KAAmC;CACxD,uBAAO,IAAI,MAAM,0DAA0D,IAAI,KAAK,GAAG;AACzF"}
package/dist/index.mjs CHANGED
@@ -20,6 +20,8 @@ function defineComponent(name, defaults) {
20
20
  /**
21
21
  * Reset the component ID counter. Only for testing.
22
22
  * @internal
23
+ * @deprecated Removed in 0.5.0 together with the global counter it resets. Each `World` keys
24
+ * storage by the definition object, so isolating storage between tests needs no reset.
23
25
  */
24
26
  function _resetComponentIds() {
25
27
  nextComponentId = 0;
@@ -161,9 +163,17 @@ function definePrefab(name, ...entries) {
161
163
  * it off the frame path.
162
164
  */
163
165
  var Query = class {
164
- /** Bitmask of required components. */
166
+ /**
167
+ * Bitmask of required components.
168
+ * @deprecated Leaves the public API in 0.5.0, which sizes masks per World. Build queries with
169
+ * `world.query()` / `world.queryBuilder()` and test membership with `query.has(entity)`.
170
+ */
165
171
  requiredMask;
166
- /** Bitmask of excluded components. */
172
+ /**
173
+ * Bitmask of excluded components.
174
+ * @deprecated Leaves the public API in 0.5.0, which sizes masks per World. Build queries with
175
+ * `world.query()` / `world.queryBuilder()` and test membership with `query.has(entity)`.
176
+ */
167
177
  excludedMask;
168
178
  /** Fires when an entity is added to this query's results. */
169
179
  onEntityAdded = new Signal();
@@ -177,11 +187,19 @@ var Query = class {
177
187
  * rather than with the number of removals.
178
188
  */
179
189
  index = /* @__PURE__ */ new Map();
190
+ /**
191
+ * @deprecated Leaves the public API in 0.5.0, which sizes masks per World, so a raw mask stops
192
+ * being a valid argument. Build queries with `world.query()` / `world.queryBuilder()`.
193
+ */
180
194
  constructor(requiredMask, excludedMask) {
181
195
  this.requiredMask = requiredMask;
182
196
  this.excludedMask = excludedMask;
183
197
  }
184
- /** Check if an archetype matches this query. */
198
+ /**
199
+ * Check if an archetype matches this query.
200
+ * @deprecated Leaves the public API in 0.5.0, which sizes masks per World, so a raw archetype
201
+ * mask stops being a valid argument. Test membership with `query.has(entity)`.
202
+ */
185
203
  matches(archetype) {
186
204
  return (archetype & this.requiredMask) === this.requiredMask && (archetype & this.excludedMask) === 0;
187
205
  }
@@ -284,11 +302,11 @@ var QueryBuilder = class {
284
302
  this.register = register;
285
303
  }
286
304
  with(...components) {
287
- for (const c of components) this.required |= c.bit;
305
+ this.required |= (maskResolvers.get(this) ?? orBits)(components);
288
306
  return this;
289
307
  }
290
308
  without(...components) {
291
- for (const c of components) this.excluded |= c.bit;
309
+ this.excluded |= (maskResolvers.get(this) ?? orBits)(components);
292
310
  return this;
293
311
  }
294
312
  /** Build the query and register it with the owning World. */
@@ -298,6 +316,17 @@ var QueryBuilder = class {
298
316
  return q;
299
317
  }
300
318
  };
319
+ const maskResolvers = /* @__PURE__ */ new WeakMap();
320
+ /** World-only (not exported from the package): route a builder's masks through the World's registry. */
321
+ function bindMaskResolver(builder, maskOf) {
322
+ maskResolvers.set(builder, maskOf);
323
+ return builder;
324
+ }
325
+ function orBits(defs) {
326
+ let mask = 0;
327
+ for (const c of defs) mask |= c.bit;
328
+ return mask;
329
+ }
301
330
  // src/system.ts
302
331
  /**
303
332
  * Define a system that processes entities matching a query.
@@ -462,6 +491,7 @@ function createOrphanCullSystem(world, onOrphan) {
462
491
  });
463
492
  }
464
493
  // src/world.ts
494
+ const MAX_COMPONENT_TYPES = 32;
465
495
  /**
466
496
  * World is the central ECS container.
467
497
  *
@@ -471,7 +501,10 @@ function createOrphanCullSystem(world, onOrphan) {
471
501
  var World = class {
472
502
  nextId = 1;
473
503
  archetypes = /* @__PURE__ */ new Map();
474
- componentStores = /* @__PURE__ */ new Map();
504
+ slots = /* @__PURE__ */ new Map();
505
+ usedBits = 0;
506
+ stores = /* @__PURE__ */ new Map();
507
+ storesByBit = new Array(MAX_COMPONENT_TYPES).fill(void 0);
475
508
  queries = [];
476
509
  queryIterDepth = 0;
477
510
  pendingQueryRemove = null;
@@ -485,8 +518,9 @@ var World = class {
485
518
  }
486
519
  /** Remove an entity and all its components. */
487
520
  destroy(entityId) {
488
- if (this.archetypes.get(entityId) === void 0) return;
489
- for (const [, store] of this.componentStores) store.delete(entityId);
521
+ const arch = this.archetypes.get(entityId);
522
+ if (arch === void 0) return;
523
+ for (let m = arch; m !== 0; m &= m - 1) this.storesByBit[31 - Math.clz32(m & -m)]?.delete(entityId);
490
524
  this.archetypes.delete(entityId);
491
525
  this.notifyQueries(entityId, 0, true);
492
526
  }
@@ -494,13 +528,9 @@ var World = class {
494
528
  add(entityId, def, data) {
495
529
  const arch = this.archetypes.get(entityId);
496
530
  if (arch === void 0) return;
497
- let store = this.componentStores.get(def.id);
498
- if (!store) {
499
- store = /* @__PURE__ */ new Map();
500
- this.componentStores.set(def.id, store);
501
- }
502
- store.set(entityId, data !== void 0 ? data : def.create());
503
- const newArch = arch | def.bit;
531
+ const slot = this.slotFor(def);
532
+ slot.store.set(entityId, data !== void 0 ? data : def.create());
533
+ const newArch = arch | slot.bit;
504
534
  this.archetypes.set(entityId, newArch);
505
535
  this.notifyQueries(entityId, newArch, false);
506
536
  }
@@ -508,20 +538,59 @@ var World = class {
508
538
  remove(entityId, def) {
509
539
  const arch = this.archetypes.get(entityId);
510
540
  if (arch === void 0) return;
511
- const store = this.componentStores.get(def.id);
512
- if (store) store.delete(entityId);
513
- const newArch = arch & ~def.bit;
541
+ const slot = this.slots.get(def);
542
+ if (slot === void 0) return;
543
+ slot.store.delete(entityId);
544
+ const newArch = arch & ~slot.bit;
514
545
  this.archetypes.set(entityId, newArch);
515
546
  this.notifyQueries(entityId, newArch, false);
516
547
  }
517
548
  /** Get component data for an entity. */
518
549
  get(entityId, def) {
519
- return this.componentStores.get(def.id)?.get(entityId);
550
+ return this.stores.get(def)?.get(entityId);
520
551
  }
521
552
  /** Check if entity has a component. */
522
553
  has(entityId, def) {
554
+ const slot = this.slots.get(def);
555
+ if (slot === void 0) return false;
523
556
  const arch = this.archetypes.get(entityId);
524
- return arch !== void 0 && (arch & def.bit) !== 0;
557
+ return arch !== void 0 && (arch & slot.bit) !== 0;
558
+ }
559
+ /**
560
+ * The slot a definition holds in this World, assigned on first use. Within one
561
+ * copy of the package ids are unique, so every definition keeps its own `bit`
562
+ * and query masks stay the OR of `def.bit`. Only a definition whose bit is
563
+ * already held here (a second copy of the package, a hand-built literal, reuse
564
+ * after `_resetComponentIds`) gets another one, where it used to share storage.
565
+ */
566
+ slotFor(def) {
567
+ const known = this.slots.get(def);
568
+ if (known !== void 0) return known;
569
+ const free = ~this.usedBits;
570
+ if (free === 0) throw capacityError(def);
571
+ const own = def.bit | 0;
572
+ const bit = own !== 0 && (own & own - 1) === 0 && (own & free) !== 0 ? own : free & -free;
573
+ const slot = {
574
+ bit,
575
+ store: /* @__PURE__ */ new Map()
576
+ };
577
+ this.slots.set(def, slot);
578
+ this.stores.set(def, slot.store);
579
+ this.usedBits |= bit;
580
+ this.storesByBit[31 - Math.clz32(bit)] = slot.store;
581
+ return slot;
582
+ }
583
+ /** Mask for a set of definitions. Checks room for all of them before assigning any slot. */
584
+ maskOf(defs) {
585
+ let room = MAX_COMPONENT_TYPES - this.slots.size;
586
+ let i = 0;
587
+ for (const def of defs) {
588
+ if (!this.slots.has(def) && defs.indexOf(def) === i && room-- === 0) throw capacityError(def);
589
+ i++;
590
+ }
591
+ let mask = 0;
592
+ for (const def of defs) mask |= this.slotFor(def).bit;
593
+ return mask;
525
594
  }
526
595
  /** Check if entity exists. */
527
596
  exists(entityId) {
@@ -549,15 +618,13 @@ var World = class {
549
618
  * world.queryBuilder().with(Position).without(Dead).build()
550
619
  */
551
620
  query(...components) {
552
- let mask = 0;
553
- for (const c of components) mask |= c.bit;
554
- const q = new Query(mask, 0);
621
+ const q = new Query(this.maskOf(components), 0);
555
622
  this.register(q);
556
623
  return q;
557
624
  }
558
625
  /** Create a QueryBuilder for complex queries (with/without). */
559
626
  queryBuilder() {
560
- return new QueryBuilder((q) => this.register(q));
627
+ return bindMaskResolver(new QueryBuilder((q) => this.register(q)), (defs) => this.maskOf(defs));
561
628
  }
562
629
  /** Track a query and populate it with the entities that already match. */
563
630
  register(q) {
@@ -625,6 +692,9 @@ var World = class {
625
692
  for (const sys of this.systems) sys.fn(this, dt);
626
693
  }
627
694
  };
695
+ function capacityError(def) {
696
+ return /* @__PURE__ */ new Error(`A World holds at most 32 component types (registering "${def.name}")`);
697
+ }
628
698
  export { FSM, Follower, Lifetime, Parent, Position, Query, QueryBuilder, Rotation, Scale, Velocity, World, _resetComponentIds, createBoundsCullSystem, createFollowerSystem, createLifetimeSystem, createMovementSystem, createOrphanCullSystem, defineComponent, definePrefab, defineSystem };
629
699
 
630
700
  //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":[],"sources":["../src/component.ts","../src/components.ts","../src/fsm.ts","../src/prefab.ts","../src/query.ts","../src/system.ts","../src/systems.ts","../src/world.ts"],"sourcesContent":["/**\n * Component definition and factory.\n *\n * Components are plain data objects. Each component type gets a unique\n * bit for archetype-based query matching.\n */\n\n/** A unique component definition. */\nexport interface ComponentDef<T> {\n /** Internal unique ID (auto-assigned). */\n readonly id: number;\n /** Bitmask for this component (1 << id). */\n readonly bit: number;\n /** Component name for debugging. */\n readonly name: string;\n /** Create a new instance with default values. */\n create(): T;\n}\n\nlet nextComponentId = 0;\n\n/**\n * Define a new component type.\n *\n * @param name Debug name for the component.\n * @param defaults Factory function returning default values, or undefined for tag components.\n */\nexport function defineComponent<T = undefined>(name: string, defaults?: () => T): ComponentDef<T> {\n const id = nextComponentId++;\n if (id >= 32) {\n throw new Error(`Maximum 32 component types exceeded (defining \"${name}\")`);\n }\n return {\n id,\n bit: 1 << id,\n name,\n create: defaults ?? (() => undefined as T),\n };\n}\n\n/**\n * Reset the component ID counter. Only for testing.\n * @internal\n */\nexport function _resetComponentIds(): void {\n nextComponentId = 0;\n}\n","import type { Vec2 } from '@flare-engine/math';\nimport { defineComponent } from './component.js';\n\n/**\n * Built-in ECS components using @flare-engine/math types.\n */\n\n/** 2D position component. */\nexport const Position = defineComponent<Vec2>('Position', () => ({\n x: 0,\n y: 0,\n}));\n\n/** 2D velocity component. */\nexport const Velocity = defineComponent<Vec2>('Velocity', () => ({\n x: 0,\n y: 0,\n}));\n\n/** Rotation in radians. */\nexport const Rotation = defineComponent<{ angle: number }>('Rotation', () => ({\n angle: 0,\n}));\n\n/** 2D scale component. */\nexport const Scale = defineComponent<Vec2>('Scale', () => ({ x: 1, y: 1 }));\n\n/** Parent entity reference. */\nexport const Parent = defineComponent<{ entity: number }>('Parent', () => ({\n entity: 0,\n}));\n\n/** Countdown timer in seconds; entity expires when remaining reaches 0. */\nexport const Lifetime = defineComponent<{ remaining: number }>('Lifetime', () => ({\n remaining: 0,\n}));\n\n/** Pins an entity's position to a target entity plus a fixed offset. */\nexport const Follower = defineComponent<{ target: number; offsetX: number; offsetY: number }>(\n 'Follower',\n () => ({ target: 0, offsetX: 0, offsetY: 0 }),\n);\n","/** A state in the FSM. */\nexport interface State<C = undefined> {\n readonly name: string;\n onEnter?(context: C): void;\n onExit?(context: C): void;\n onUpdate?(dt: number, context: C): void;\n}\n\n/**\n * Lightweight finite state machine. ~100 LOC.\n *\n * Manages named states with onEnter/onExit/onUpdate hooks\n * and string-keyed transitions.\n */\nexport class FSM<C = undefined> {\n private _current: State<C> | undefined;\n private _states = new Map<string, State<C>>();\n private _transitions = new Map<string, Map<string, string>>();\n private _context: C;\n\n constructor(...args: C extends undefined ? [] : [context: C]) {\n this._context = args[0] as C;\n }\n\n /** The currently active state, or undefined if none. */\n get current(): State<C> | undefined {\n return this._current;\n }\n\n /** Register a state. */\n addState(state: State<C>): this {\n this._states.set(state.name, state);\n return this;\n }\n\n /**\n * Register a transition.\n * When `trigger` fires in `fromState`, transition to `toState`.\n */\n addTransition(fromState: string, trigger: string, toState: string): this {\n let map = this._transitions.get(fromState);\n if (!map) {\n map = new Map();\n this._transitions.set(fromState, map);\n }\n map.set(trigger, toState);\n return this;\n }\n\n /** Set the initial state (calls onEnter). */\n start(stateName: string): void {\n const state = this._states.get(stateName);\n if (!state) return;\n this._current = state;\n state.onEnter?.(this._context);\n }\n\n /** Fire a trigger. If a matching transition exists, switch states. */\n trigger(name: string): void {\n if (!this._current) return;\n const transitions = this._transitions.get(this._current.name);\n if (!transitions) return;\n const target = transitions.get(name);\n if (target === undefined) return;\n const next = this._states.get(target);\n if (!next) return;\n this._current.onExit?.(this._context);\n this._current = next;\n next.onEnter?.(this._context);\n }\n\n /** Update the current state. */\n update(dt: number): void {\n this._current?.onUpdate?.(dt, this._context);\n }\n}\n","import type { ComponentDef } from './component.js';\nimport type { World } from './world.js';\n\n/** A component entry in a prefab definition. */\ninterface PrefabEntry<T> {\n def: ComponentDef<T>;\n data?: T | (() => T);\n}\n\n/** A prefab factory that spawns entities with pre-defined components. */\nexport interface Prefab {\n readonly name: string;\n /** Spawn an entity with this prefab's components. */\n spawn(world: World): number;\n}\n\n/**\n * Define a prefab — a template for spawning entities with a fixed set of components.\n *\n * Plain-object data is stored by reference and shared by every spawn; pass\n * `() => T` for per-entity mutable state. This mirrors `world.add(entity, def,\n * data)`, which stores the object it is given — so the object form is for\n * data no entity will mutate, and the factory runs once per spawn.\n *\n * @param name Debug name.\n * @param entries Array of [componentDef, data?] tuples.\n */\nexport function definePrefab(\n name: string,\n ...entries: [ComponentDef<unknown>, (unknown | (() => unknown))?][]\n): Prefab {\n const components: PrefabEntry<unknown>[] = entries.map(([def, data]) => ({\n def,\n data,\n }));\n\n return {\n name,\n spawn(world: World): number {\n const entity = world.spawn();\n for (const entry of components) {\n const data =\n typeof entry.data === 'function' ? (entry.data as () => unknown)() : entry.data;\n world.add(entity, entry.def, data);\n }\n return entity;\n },\n };\n}\n","import { Signal } from '@flare-engine/events';\nimport type { ComponentDef } from './component.js';\n\n/**\n * Query matches entities based on component archetypes.\n *\n * Uses bitmask matching: entity archetype & requiredMask === requiredMask\n * and entity archetype & excludedMask === 0.\n *\n * Two ways to walk the matches:\n * - `entities` — the live id array, for an indexed `for` loop. Allocates\n * nothing; this is the form for systems and anything else that runs per frame.\n * - `for...of` — the convenience form. It creates an iterator, and on Hermes\n * (React Native) one `{ value, done }` object per entity per pass, so keep\n * it off the frame path.\n */\nexport class Query {\n /** Bitmask of required components. */\n readonly requiredMask: number;\n /** Bitmask of excluded components. */\n readonly excludedMask: number;\n\n /** Fires when an entity is added to this query's results. */\n readonly onEntityAdded = new Signal<number>();\n /** Fires when an entity is removed from this query's results. */\n readonly onEntityRemoved = new Signal<number>();\n\n private ids: number[] = [];\n /**\n * `entityId -> index into ids`. Serves membership *and* position, which\n * is what makes removal O(1): the previous pair of a `Set` plus `indexOf`\n * made every removal a linear scan, so churn cost grew as `n * removals`\n * rather than with the number of removals.\n */\n private index = new Map<number, number>();\n\n constructor(requiredMask: number, excludedMask: number) {\n this.requiredMask = requiredMask;\n this.excludedMask = excludedMask;\n }\n\n /** Check if an archetype matches this query. */\n matches(archetype: number): boolean {\n return (\n (archetype & this.requiredMask) === this.requiredMask && (archetype & this.excludedMask) === 0\n );\n }\n\n /** @internal — called by World when an entity's archetype changes. */\n _check(entityId: number, archetype: number): void {\n const isMatch = this.matches(archetype);\n const wasMatch = this.index.has(entityId);\n\n if (isMatch && !wasMatch) {\n this.index.set(entityId, this.ids.length);\n this.ids.push(entityId);\n this.onEntityAdded.emit(entityId);\n } else if (!isMatch && wasMatch) {\n this.swapRemove(entityId);\n this.onEntityRemoved.emit(entityId);\n }\n }\n\n /** @internal — called by World when an entity is removed entirely. */\n _remove(entityId: number): void {\n if (this.index.has(entityId)) {\n this.swapRemove(entityId);\n this.onEntityRemoved.emit(entityId);\n }\n }\n\n /**\n * O(1) removal: move the last element into the hole and shorten by one.\n *\n * Order-preserving removal cannot be O(1) here — `splice` shifts every later\n * element, and a position map would then need every shifted index rewritten,\n * so it costs the same scan it was meant to remove. A tombstone would keep\n * order but puts a branch in iteration, which at realistic churn runs far\n * more often than removal and would slow the steady-state path to speed up\n * the rare one.\n */\n private swapRemove(entityId: number): void {\n const idx = this.index.get(entityId) as number;\n const last = this.ids.length - 1;\n const lastId = this.ids[last] as number;\n this.ids[idx] = lastId;\n this.index.set(lastId, idx);\n this.ids.pop();\n this.index.delete(entityId);\n }\n\n /**\n * Matching entity IDs — the live array, not a copy, so reading it allocates\n * nothing and it reflects every add and remove as it happens. Walk it by\n * index on hot paths:\n *\n * const ids = query.entities;\n * for (let i = 0; i < ids.length; i++) { const id = ids[i]!; ... }\n *\n * Because it is live, destroying an entity or changing its components mid-walk\n * swap-removes from this array under the loop and skips an entity: collect\n * first and act after, as the built-in systems do.\n *\n * Order is not guaranteed. Entities are appended as they begin matching and\n * removed by swapping the last element into the hole, so the order reflects\n * match history, not id. It was previously documented as \"sorted\", which was\n * never true: `_check` has always plain-`push`ed, so an entity that starts\n * matching later lands after entities with higher ids (spawn 1,2,3 then add\n * the missing component to 3 first and the array reads `[3, 1, 2]`).\n *\n * The one consumer that cares is `render-system`, whose `sortByDrawOrder` is\n * a *stable* insertion sort on `z` alone — so this order is the tie-break\n * between equal-`z` sprites. It is deliberately not a guarantee: depend on\n * `z`, not on the order entities happen to occupy here.\n */\n get entities(): readonly number[] {\n return this.ids;\n }\n\n /**\n * Iterate matching entity IDs. Convenience form: it allocates an iterator,\n * and on Hermes a result object per entity — walk `entities` by index on\n * hot paths.\n */\n [Symbol.iterator](): IterableIterator<number> {\n return this.ids[Symbol.iterator]();\n }\n\n /** Number of matching entities. */\n get count(): number {\n return this.ids.length;\n }\n\n /** Check if an entity matches this query. */\n has(entityId: number): boolean {\n return this.index.has(entityId);\n }\n}\n\n/**\n * Builder for creating queries with .with() / .without() chaining.\n *\n * Obtain one from `world.queryBuilder()`. `build()` hands the finished Query to\n * the World it came from, which is what keeps it populated; the registration\n * hook is a required constructor argument so a builder cannot exist without a\n * World behind it, and the orphan `new QueryBuilder().build()` does not compile.\n */\nexport class QueryBuilder {\n private required = 0;\n private excluded = 0;\n private readonly register: (q: Query) => void;\n\n constructor(register: (q: Query) => void) {\n this.register = register;\n }\n\n with(...components: ComponentDef<unknown>[]): this {\n for (const c of components) {\n this.required |= c.bit;\n }\n return this;\n }\n\n without(...components: ComponentDef<unknown>[]): this {\n for (const c of components) {\n this.excluded |= c.bit;\n }\n return this;\n }\n\n /** Build the query and register it with the owning World. */\n build(): Query {\n const q = new Query(this.required, this.excluded);\n this.register(q);\n return q;\n }\n}\n","import type { Query } from './query.js';\nimport type { World } from './world.js';\n\n/** A system function that processes entities matching a query. */\nexport type SystemFn = (query: Query, dt: number, world: World) => void;\n\n/** A defined system with its query and function. */\nexport interface SystemDef {\n readonly query: Query;\n readonly fn: SystemFn;\n /**\n * The wrapper to register on the World via `world.addSystem(sys.worldFn)`;\n * pass the same reference to `removeSystem`.\n */\n readonly worldFn: (world: World, dt: number) => void;\n /** @deprecated Use `worldFn` — the same function reference. Removed in the next planned minor. */\n readonly _worldFn: (world: World, dt: number) => void;\n}\n\n/**\n * Define a system that processes entities matching a query.\n *\n * Returns a SystemDef that can be added to a World via world.addSystem().\n * The system function receives the query's matching entities, dt, and world.\n *\n * Usage:\n * const q = world.query(Position, Velocity);\n * const moveSys = defineSystem(q, (query, dt, world) => {\n * const ids = query.entities;\n * for (let i = 0; i < ids.length; i++) { const id = ids[i]!; ... }\n * });\n * world.addSystem(moveSys.worldFn);\n *\n * Walk `query.entities` by index — that is the zero-alloc form. `for...of`\n * over the query works too but allocates an iterator per loop (and, on\n * Hermes, a result object per entity), which per system per frame is exactly\n * what a system must not do.\n */\nexport function defineSystem(query: Query, fn: SystemFn): SystemDef {\n const worldFn = (world: World, dt: number) => {\n fn(query, dt, world);\n };\n return { query, fn, worldFn, _worldFn: worldFn };\n}\n","import { Follower, Lifetime, Position, Velocity } from './components.js';\nimport type { Query } from './query.js';\nimport type { SystemDef } from './system.js';\nimport { defineSystem } from './system.js';\nimport type { World } from './world.js';\n\n/**\n * Plain camera-space bounding box used by createBoundsCullSystem.\n * Keep plain numbers — do NOT import physics AABB/Bounds (layer inversion).\n */\nexport interface CullBounds {\n readonly minX: number;\n readonly minY: number;\n readonly maxX: number;\n readonly maxY: number;\n}\n\n/**\n * createMovementSystem — integrates Position by Velocity * dt each frame.\n *\n * Recommended priority: run BEFORE createFollowerSystem (0).\n */\nexport function createMovementSystem(world: World): SystemDef {\n const q = world.query(Position, Velocity);\n return defineSystem(q, (query, dt, w) => {\n const ids = query.entities;\n for (let i = 0; i < ids.length; i++) {\n const id = ids[i]!;\n const pos = w.get(id, Position)!;\n const vel = w.get(id, Velocity)!;\n pos.x += vel.x * dt;\n pos.y += vel.y * dt;\n }\n });\n}\n\n/**\n * createLifetimeSystem — decrements Lifetime.remaining each frame.\n * Entities whose remaining reaches <= 0 are collected, then onExpire is called\n * for each AFTER the read loop.\n *\n * Deferred removal: destroying inside a live walk of query.entities swap-removes\n * from the array mid-iteration and would skip entities. Collect first, act after.\n *\n * The scratch array is closure-owned and grow-only — zero steady-state alloc.\n *\n * @param onExpire Destroy / pool policy — ecs never destroys on its own.\n * @param query Optional caller-supplied Query. When omitted the system\n * registers world.query(Lifetime) itself. Pass a narrower\n * query to avoid scanning unrelated Lifetime holders and to\n * share an already-registered query (eliminates duplicate\n * World.query registration cost).\n */\nexport function createLifetimeSystem(\n world: World,\n onExpire: (entity: number, world: World) => void,\n query?: Query,\n): SystemDef {\n const q = query ?? world.query(Lifetime);\n const scratch: number[] = [];\n return defineSystem(q, (query, dt, w) => {\n scratch.length = 0;\n const ids = query.entities;\n for (let i = 0; i < ids.length; i++) {\n const id = ids[i]!;\n const life = w.get(id, Lifetime)!;\n life.remaining -= dt;\n if (life.remaining <= 0) {\n scratch.push(id);\n }\n }\n for (let i = 0; i < scratch.length; i++) {\n onExpire(scratch[i]!, w);\n }\n });\n}\n\n/**\n * createBoundsCullSystem — culls entities whose Position falls outside bounds.\n * Reads bounds LIVE each frame so callers can mutate it to follow a camera.\n * Entities outside are collected, then onCull is called for each after the read loop.\n *\n * Deferred removal: same splice-during-iteration reason as createLifetimeSystem.\n *\n * Recommended priority: run AFTER createMovementSystem and createFollowerSystem.\n *\n * @param bounds Mutable bounding box read each frame.\n * @param onCull Destroy / pool policy — ecs never destroys on its own.\n * @param query Optional caller-supplied Query. When omitted the system\n * registers world.query(Position) itself, scanning all\n * Position holders. Pass a narrower query (e.g. bullets\n * only) to avoid scanning unrelated entities such as\n * scrolling backgrounds, and to share an already-registered\n * query with the caller.\n */\nexport function createBoundsCullSystem(\n world: World,\n bounds: CullBounds,\n onCull: (entity: number, world: World) => void,\n query?: Query,\n): SystemDef {\n const q = query ?? world.query(Position);\n const scratch: number[] = [];\n return defineSystem(q, (query, _dt, w) => {\n scratch.length = 0;\n const ids = query.entities;\n for (let i = 0; i < ids.length; i++) {\n const id = ids[i]!;\n const pos = w.get(id, Position)!;\n if (\n pos.x < bounds.minX ||\n pos.x > bounds.maxX ||\n pos.y < bounds.minY ||\n pos.y > bounds.maxY\n ) {\n scratch.push(id);\n }\n }\n for (let i = 0; i < scratch.length; i++) {\n onCull(scratch[i]!, w);\n }\n });\n}\n\n/**\n * createFollowerSystem — pins each Follower entity's Position to\n * target.Position + (offsetX, offsetY).\n * If the target is gone or has no Position, the entity is silently skipped.\n *\n * Recommended priority: run AFTER createMovementSystem (1) so the target's\n * position is already integrated before the follower snaps to it.\n */\nexport function createFollowerSystem(world: World): SystemDef {\n const q = world.query(Position, Follower);\n return defineSystem(q, (query, _dt, w) => {\n const ids = query.entities;\n for (let i = 0; i < ids.length; i++) {\n const id = ids[i]!;\n const follower = w.get(id, Follower)!;\n const t = w.get(follower.target, Position);\n if (t === undefined) continue;\n const pos = w.get(id, Position)!;\n pos.x = t.x + follower.offsetX;\n pos.y = t.y + follower.offsetY;\n }\n });\n}\n\n/**\n * createOrphanCullSystem — fires onOrphan for each Follower whose target entity\n * no longer exists. Does NOT move or destroy anything itself.\n *\n * Split from createFollowerSystem so games that want to orphan-cull can opt in\n * without coupling destruction to the follower pin logic.\n *\n * Recommended priority: run AFTER createFollowerSystem (2) so the follower is\n * pinned before orphans are detected.\n *\n * Deferred removal: same splice-during-iteration reason as createLifetimeSystem.\n *\n * @param onOrphan Called once per orphaned entity after the read loop.\n */\nexport function createOrphanCullSystem(\n world: World,\n onOrphan: (entity: number, world: World) => void,\n): SystemDef {\n const q = world.query(Follower);\n const scratch: number[] = [];\n return defineSystem(q, (query, _dt, w) => {\n scratch.length = 0;\n const ids = query.entities;\n for (let i = 0; i < ids.length; i++) {\n const id = ids[i]!;\n const follower = w.get(id, Follower)!;\n if (!w.exists(follower.target)) {\n scratch.push(id);\n }\n }\n for (let i = 0; i < scratch.length; i++) {\n onOrphan(scratch[i]!, w);\n }\n });\n}\n","import type { ComponentDef } from './component.js';\nimport { Query, QueryBuilder } from './query.js';\n\n/**\n * World is the central ECS container.\n *\n * Entities are integer IDs. Components are stored in per-component Maps.\n * Archetype bitmasks enable fast query matching.\n */\nexport class World {\n private nextId = 1;\n private archetypes = new Map<number, number>(); // entityId → bitmask\n private componentStores = new Map<number, Map<number, unknown>>(); // componentId → (entityId → data)\n private queries: Query[] = [];\n private queryIterDepth = 0;\n private pendingQueryRemove: Query[] | null = null;\n private systems: {\n fn: (world: World, dt: number) => void;\n priority: number;\n }[] = [];\n private systemsSorted = false;\n\n /** Create a new entity. Returns the entity ID. */\n spawn(): number {\n const id = this.nextId++;\n this.archetypes.set(id, 0);\n return id;\n }\n\n /** Remove an entity and all its components. */\n destroy(entityId: number): void {\n const arch = this.archetypes.get(entityId);\n if (arch === undefined) return;\n\n // Remove from all component stores\n for (const [, store] of this.componentStores) {\n store.delete(entityId);\n }\n\n this.archetypes.delete(entityId);\n\n this.notifyQueries(entityId, 0, true);\n }\n\n /** Add a component to an entity. */\n add<T>(entityId: number, def: ComponentDef<T>, data?: T): void {\n const arch = this.archetypes.get(entityId);\n if (arch === undefined) return;\n\n // Store component data\n let store = this.componentStores.get(def.id);\n if (!store) {\n store = new Map();\n this.componentStores.set(def.id, store);\n }\n store.set(entityId, data !== undefined ? data : def.create());\n\n // Update archetype\n const newArch = arch | def.bit;\n this.archetypes.set(entityId, newArch);\n\n this.notifyQueries(entityId, newArch, false);\n }\n\n /** Remove a component from an entity. */\n remove<T>(entityId: number, def: ComponentDef<T>): void {\n const arch = this.archetypes.get(entityId);\n if (arch === undefined) return;\n\n const store = this.componentStores.get(def.id);\n if (store) store.delete(entityId);\n\n const newArch = arch & ~def.bit;\n this.archetypes.set(entityId, newArch);\n\n this.notifyQueries(entityId, newArch, false);\n }\n\n /** Get component data for an entity. */\n get<T>(entityId: number, def: ComponentDef<T>): T | undefined {\n const store = this.componentStores.get(def.id);\n return store?.get(entityId) as T | undefined;\n }\n\n /** Check if entity has a component. */\n has(entityId: number, def: ComponentDef<unknown>): boolean {\n const arch = this.archetypes.get(entityId);\n return arch !== undefined && (arch & def.bit) !== 0;\n }\n\n /** Check if entity exists. */\n exists(entityId: number): boolean {\n return this.archetypes.has(entityId);\n }\n\n /** Number of live entities. */\n get entityCount(): number {\n return this.archetypes.size;\n }\n\n /**\n * Walk every live entity ID. Iterates the live archetype map directly, with no\n * array snapshot. Archetype changes (add/remove component) keep the same entity\n * keys, so iteration is stable across them. Destroying entities inside the\n * callback is safe, but entities spawned inside it are visited in the same pass\n * (live Map iteration) — don't spawn from within.\n */\n forEachEntity(cb: (entity: number) => void): void {\n for (const entityId of this.archetypes.keys()) {\n cb(entityId);\n }\n }\n\n /**\n * Create a query. Queries auto-update as entities change.\n * Use the QueryBuilder-style chaining:\n * world.query(Position, Velocity)\n * Or use the builder:\n * world.queryBuilder().with(Position).without(Dead).build()\n */\n query(...components: ComponentDef<unknown>[]): Query {\n let mask = 0;\n for (const c of components) {\n mask |= c.bit;\n }\n const q = new Query(mask, 0);\n this.register(q);\n return q;\n }\n\n /** Create a QueryBuilder for complex queries (with/without). */\n queryBuilder(): QueryBuilder {\n return new QueryBuilder((q) => this.register(q));\n }\n\n /** Track a query and populate it with the entities that already match. */\n private register(q: Query): void {\n this.queries.push(q);\n for (const [entityId, arch] of this.archetypes) {\n q._check(entityId, arch);\n }\n }\n\n /**\n * Dispose a query created by `query()` or `queryBuilder().build()`. Afterwards\n * the world stops updating it, so it no longer costs spawn/add/remove iteration\n * time. The query is left inert — drop the reference to let it be collected.\n *\n * Safe to call from within a Query signal handler (e.g. a one-shot\n * `onEntityAdded` that disposes its own query): the removal is deferred until\n * the in-progress mutation finishes iterating, so no other query is skipped.\n */\n removeQuery(q: Query): void {\n if (this.queryIterDepth > 0) {\n if (this.pendingQueryRemove === null) this.pendingQueryRemove = [];\n this.pendingQueryRemove.push(q);\n return;\n }\n const idx = this.queries.indexOf(q);\n if (idx !== -1) this.queries.splice(idx, 1);\n }\n\n /** Notify queries in order, deferring any removeQuery until the loop unwinds. */\n private notifyQueries(entityId: number, arch: number, destroyed: boolean): void {\n this.queryIterDepth++;\n try {\n if (destroyed) {\n for (const query of this.queries) {\n query._remove(entityId);\n }\n } else {\n for (const query of this.queries) {\n query._check(entityId, arch);\n }\n }\n } finally {\n this.endQueryIteration();\n }\n }\n\n /** @internal End a query-notify loop; flush any removeQuery deferred during it. */\n private endQueryIteration(): void {\n this.queryIterDepth--;\n if (this.queryIterDepth === 0 && this.pendingQueryRemove !== null) {\n for (const q of this.pendingQueryRemove) {\n const idx = this.queries.indexOf(q);\n if (idx !== -1) this.queries.splice(idx, 1);\n }\n this.pendingQueryRemove.length = 0;\n }\n }\n\n /** Register a system function. Lower priority runs first. */\n addSystem(fn: (world: World, dt: number) => void, priority = 0): void {\n this.systems.push({ fn, priority });\n this.systemsSorted = false;\n }\n\n /** Remove a system. */\n removeSystem(fn: (world: World, dt: number) => void): void {\n const idx = this.systems.findIndex((s) => s.fn === fn);\n if (idx !== -1) this.systems.splice(idx, 1);\n }\n\n /** Run all systems in priority order. */\n step(dt: number): void {\n if (!this.systemsSorted) {\n this.systems.sort((a, b) => a.priority - b.priority);\n this.systemsSorted = true;\n }\n for (const sys of this.systems) {\n sys.fn(this, dt);\n }\n }\n}\n"],"mappings":";;AAmBA,IAAI,kBAAkB;;;;;;;AAQtB,SAAgB,gBAA+B,MAAc,UAAqC;CAChG,MAAM,KAAK;CACX,IAAI,MAAM,IACR,MAAM,IAAI,MAAM,kDAAkD,KAAK,GAAG;CAE5E,OAAO;EACL;EACA,KAAK,KAAK;EACV;EACA,QAAQ,mBAAmB,KAAA;CAC7B;AACF;;;;;AAMA,SAAgB,qBAA2B;CACzC,kBAAkB;AACpB;;;;;;ACtCA,MAAa,WAAW,gBAAsB,mBAAmB;CAC/D,GA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WACF,KAAK,MAAM,SAAS,KAAK,SACvB,MAAM,QAAQ,QAAQ;QAGxB,KAAK,MAAM,SAAS,KAAK,SACvB,MAAM,OAAO,UAAU,IAAI;EAGjC,UAAU;GACR,KAAK,kBAAkB;EACzB;CACF;;CAGQ,oBAA0B;EAChC,KAAK;EACL,IAAI,KAAK,mBAAmB,KAAK,KAAK,uBAAuB,MAAM;GACjE,KAAK,MAAM,KAAK,KAAK,oBAAoB;IACvC,MAAM,MAAM,KAAK,QAAQ,QAAQ,CAAC;IAClC,IAAI,QAAQ,IAAI,KAAK,QAAQ,OAAO,KAAK,CAAC;GAC5C;GACA,KAAK,mBAAmB,SAAS;EACnC;CACF;;CAGA,UAAU,IAAwC,WAAW,GAAS;EACpE,KAAK,QAAQ,KAAK;GAAE;GAAI;EAAS,CAAC;EAClC,KAAK,gBAAgB;CACvB;;CAGA,aAAa,IAA8C;EACzD,MAAM,MAAM,KAAK,QAAQ,WAAW,MAAM,EAAE,OAAO,EAAE;EACrD,IAAI,QAAQ,IAAI,KAAK,QAAQ,OAAO,KAAK,CAAC;CAC5C;;CAGA,KAAK,IAAkB;EACrB,IAAI,CAAC,KAAK,eAAe;GACvB,KAAK,QAAQ,MAAM,GAAG,MAAM,EAAE,WAAW,EAAE,QAAQ;GACnD,KAAK,gBAAgB;EACvB;EACA,KAAK,MAAM,OAAO,KAAK,SACrB,IAAI,GAAG,MAAM,EAAE;CAEnB;AACF"}
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../src/component.ts","../src/components.ts","../src/fsm.ts","../src/prefab.ts","../src/query.ts","../src/system.ts","../src/systems.ts","../src/world.ts"],"sourcesContent":["/**\n * Component definition and factory.\n *\n * Components are plain data objects. Each component type gets a unique\n * bit for archetype-based query matching.\n */\n\n/** A unique component definition. */\nexport interface ComponentDef<T> {\n /**\n * Internal unique ID (auto-assigned).\n * @deprecated Removed in 0.5.0. A `World` no longer keys storage by it, and it comes from a\n * module-global counter, so it depends on import order and must never be persisted. Key by the\n * definition object itself instead (e.g. a `Map<ComponentDef<unknown>, …>`).\n */\n readonly id: number;\n /**\n * Bitmask for this component (1 << id).\n * @deprecated Removed in 0.5.0, which lifts the 32-type cap: `1 << id` wraps from the 33rd\n * definition on. A `World` no longer keys storage by it. Key by the definition object itself\n * instead (e.g. a `Map<ComponentDef<unknown>, …>`).\n */\n readonly bit: number;\n /** Component name for debugging. */\n readonly name: string;\n /** Create a new instance with default values. */\n create(): T;\n}\n\nlet nextComponentId = 0;\n\n/**\n * Define a new component type.\n *\n * @param name Debug name for the component.\n * @param defaults Factory function returning default values, or undefined for tag components.\n */\nexport function defineComponent<T = undefined>(name: string, defaults?: () => T): ComponentDef<T> {\n const id = nextComponentId++;\n if (id >= 32) {\n throw new Error(`Maximum 32 component types exceeded (defining \"${name}\")`);\n }\n return {\n id,\n bit: 1 << id,\n name,\n create: defaults ?? (() => undefined as T),\n };\n}\n\n/**\n * Reset the component ID counter. Only for testing.\n * @internal\n * @deprecated Removed in 0.5.0 together with the global counter it resets. Each `World` keys\n * storage by the definition object, so isolating storage between tests needs no reset.\n */\nexport function _resetComponentIds(): void {\n nextComponentId = 0;\n}\n","import type { Vec2 } from '@flare-engine/math';\nimport { defineComponent } from './component.js';\n\n/**\n * Built-in ECS components using @flare-engine/math types.\n */\n\n/** 2D position component. */\nexport const Position = defineComponent<Vec2>('Position', () => ({\n x: 0,\n y: 0,\n}));\n\n/** 2D velocity component. */\nexport const Velocity = defineComponent<Vec2>('Velocity', () => ({\n x: 0,\n y: 0,\n}));\n\n/** Rotation in radians. */\nexport const Rotation = defineComponent<{ angle: number }>('Rotation', () => ({\n angle: 0,\n}));\n\n/** 2D scale component. */\nexport const Scale = defineComponent<Vec2>('Scale', () => ({ x: 1, y: 1 }));\n\n/** Parent entity reference. */\nexport const Parent = defineComponent<{ entity: number }>('Parent', () => ({\n entity: 0,\n}));\n\n/** Countdown timer in seconds; entity expires when remaining reaches 0. */\nexport const Lifetime = defineComponent<{ remaining: number }>('Lifetime', () => ({\n remaining: 0,\n}));\n\n/** Pins an entity's position to a target entity plus a fixed offset. */\nexport const Follower = defineComponent<{ target: number; offsetX: number; offsetY: number }>(\n 'Follower',\n () => ({ target: 0, offsetX: 0, offsetY: 0 }),\n);\n","/** A state in the FSM. */\nexport interface State<C = undefined> {\n readonly name: string;\n onEnter?(context: C): void;\n onExit?(context: C): void;\n onUpdate?(dt: number, context: C): void;\n}\n\n/**\n * Lightweight finite state machine. ~100 LOC.\n *\n * Manages named states with onEnter/onExit/onUpdate hooks\n * and string-keyed transitions.\n */\nexport class FSM<C = undefined> {\n private _current: State<C> | undefined;\n private _states = new Map<string, State<C>>();\n private _transitions = new Map<string, Map<string, string>>();\n private _context: C;\n\n constructor(...args: C extends undefined ? [] : [context: C]) {\n this._context = args[0] as C;\n }\n\n /** The currently active state, or undefined if none. */\n get current(): State<C> | undefined {\n return this._current;\n }\n\n /** Register a state. */\n addState(state: State<C>): this {\n this._states.set(state.name, state);\n return this;\n }\n\n /**\n * Register a transition.\n * When `trigger` fires in `fromState`, transition to `toState`.\n */\n addTransition(fromState: string, trigger: string, toState: string): this {\n let map = this._transitions.get(fromState);\n if (!map) {\n map = new Map();\n this._transitions.set(fromState, map);\n }\n map.set(trigger, toState);\n return this;\n }\n\n /** Set the initial state (calls onEnter). */\n start(stateName: string): void {\n const state = this._states.get(stateName);\n if (!state) return;\n this._current = state;\n state.onEnter?.(this._context);\n }\n\n /** Fire a trigger. If a matching transition exists, switch states. */\n trigger(name: string): void {\n if (!this._current) return;\n const transitions = this._transitions.get(this._current.name);\n if (!transitions) return;\n const target = transitions.get(name);\n if (target === undefined) return;\n const next = this._states.get(target);\n if (!next) return;\n this._current.onExit?.(this._context);\n this._current = next;\n next.onEnter?.(this._context);\n }\n\n /** Update the current state. */\n update(dt: number): void {\n this._current?.onUpdate?.(dt, this._context);\n }\n}\n","import type { ComponentDef } from './component.js';\nimport type { World } from './world.js';\n\n/** A component entry in a prefab definition. */\ninterface PrefabEntry<T> {\n def: ComponentDef<T>;\n data?: T | (() => T);\n}\n\n/** A prefab factory that spawns entities with pre-defined components. */\nexport interface Prefab {\n readonly name: string;\n /** Spawn an entity with this prefab's components. */\n spawn(world: World): number;\n}\n\n/**\n * Define a prefab — a template for spawning entities with a fixed set of components.\n *\n * Plain-object data is stored by reference and shared by every spawn; pass\n * `() => T` for per-entity mutable state. This mirrors `world.add(entity, def,\n * data)`, which stores the object it is given — so the object form is for\n * data no entity will mutate, and the factory runs once per spawn.\n *\n * @param name Debug name.\n * @param entries Array of [componentDef, data?] tuples.\n */\nexport function definePrefab(\n name: string,\n ...entries: [ComponentDef<unknown>, (unknown | (() => unknown))?][]\n): Prefab {\n const components: PrefabEntry<unknown>[] = entries.map(([def, data]) => ({\n def,\n data,\n }));\n\n return {\n name,\n spawn(world: World): number {\n const entity = world.spawn();\n for (const entry of components) {\n const data =\n typeof entry.data === 'function' ? (entry.data as () => unknown)() : entry.data;\n world.add(entity, entry.def, data);\n }\n return entity;\n },\n };\n}\n","import { Signal } from '@flare-engine/events';\nimport type { ComponentDef } from './component.js';\n\n/**\n * Query matches entities based on component archetypes.\n *\n * Uses bitmask matching: entity archetype & requiredMask === requiredMask\n * and entity archetype & excludedMask === 0.\n *\n * Two ways to walk the matches:\n * - `entities` — the live id array, for an indexed `for` loop. Allocates\n * nothing; this is the form for systems and anything else that runs per frame.\n * - `for...of` — the convenience form. It creates an iterator, and on Hermes\n * (React Native) one `{ value, done }` object per entity per pass, so keep\n * it off the frame path.\n */\nexport class Query {\n /**\n * Bitmask of required components.\n * @deprecated Leaves the public API in 0.5.0, which sizes masks per World. Build queries with\n * `world.query()` / `world.queryBuilder()` and test membership with `query.has(entity)`.\n */\n readonly requiredMask: number;\n /**\n * Bitmask of excluded components.\n * @deprecated Leaves the public API in 0.5.0, which sizes masks per World. Build queries with\n * `world.query()` / `world.queryBuilder()` and test membership with `query.has(entity)`.\n */\n readonly excludedMask: number;\n\n /** Fires when an entity is added to this query's results. */\n readonly onEntityAdded = new Signal<number>();\n /** Fires when an entity is removed from this query's results. */\n readonly onEntityRemoved = new Signal<number>();\n\n private ids: number[] = [];\n /**\n * `entityId -> index into ids`. Serves membership *and* position, which\n * is what makes removal O(1): the previous pair of a `Set` plus `indexOf`\n * made every removal a linear scan, so churn cost grew as `n * removals`\n * rather than with the number of removals.\n */\n private index = new Map<number, number>();\n\n /**\n * @deprecated Leaves the public API in 0.5.0, which sizes masks per World, so a raw mask stops\n * being a valid argument. Build queries with `world.query()` / `world.queryBuilder()`.\n */\n constructor(requiredMask: number, excludedMask: number) {\n this.requiredMask = requiredMask;\n this.excludedMask = excludedMask;\n }\n\n /**\n * Check if an archetype matches this query.\n * @deprecated Leaves the public API in 0.5.0, which sizes masks per World, so a raw archetype\n * mask stops being a valid argument. Test membership with `query.has(entity)`.\n */\n matches(archetype: number): boolean {\n return (\n (archetype & this.requiredMask) === this.requiredMask && (archetype & this.excludedMask) === 0\n );\n }\n\n /** @internal — called by World when an entity's archetype changes. */\n _check(entityId: number, archetype: number): void {\n const isMatch = this.matches(archetype);\n const wasMatch = this.index.has(entityId);\n\n if (isMatch && !wasMatch) {\n this.index.set(entityId, this.ids.length);\n this.ids.push(entityId);\n this.onEntityAdded.emit(entityId);\n } else if (!isMatch && wasMatch) {\n this.swapRemove(entityId);\n this.onEntityRemoved.emit(entityId);\n }\n }\n\n /** @internal — called by World when an entity is removed entirely. */\n _remove(entityId: number): void {\n if (this.index.has(entityId)) {\n this.swapRemove(entityId);\n this.onEntityRemoved.emit(entityId);\n }\n }\n\n /**\n * O(1) removal: move the last element into the hole and shorten by one.\n *\n * Order-preserving removal cannot be O(1) here — `splice` shifts every later\n * element, and a position map would then need every shifted index rewritten,\n * so it costs the same scan it was meant to remove. A tombstone would keep\n * order but puts a branch in iteration, which at realistic churn runs far\n * more often than removal and would slow the steady-state path to speed up\n * the rare one.\n */\n private swapRemove(entityId: number): void {\n const idx = this.index.get(entityId) as number;\n const last = this.ids.length - 1;\n const lastId = this.ids[last] as number;\n this.ids[idx] = lastId;\n this.index.set(lastId, idx);\n this.ids.pop();\n this.index.delete(entityId);\n }\n\n /**\n * Matching entity IDs — the live array, not a copy, so reading it allocates\n * nothing and it reflects every add and remove as it happens. Walk it by\n * index on hot paths:\n *\n * const ids = query.entities;\n * for (let i = 0; i < ids.length; i++) { const id = ids[i]!; ... }\n *\n * Because it is live, destroying an entity or changing its components mid-walk\n * swap-removes from this array under the loop and skips an entity: collect\n * first and act after, as the built-in systems do.\n *\n * Order is not guaranteed. Entities are appended as they begin matching and\n * removed by swapping the last element into the hole, so the order reflects\n * match history, not id. It was previously documented as \"sorted\", which was\n * never true: `_check` has always plain-`push`ed, so an entity that starts\n * matching later lands after entities with higher ids (spawn 1,2,3 then add\n * the missing component to 3 first and the array reads `[3, 1, 2]`).\n *\n * The one consumer that cares is `render-system`, whose `sortByDrawOrder` is\n * a *stable* insertion sort on `z` alone — so this order is the tie-break\n * between equal-`z` sprites. It is deliberately not a guarantee: depend on\n * `z`, not on the order entities happen to occupy here.\n */\n get entities(): readonly number[] {\n return this.ids;\n }\n\n /**\n * Iterate matching entity IDs. Convenience form: it allocates an iterator,\n * and on Hermes a result object per entity — walk `entities` by index on\n * hot paths.\n */\n [Symbol.iterator](): IterableIterator<number> {\n return this.ids[Symbol.iterator]();\n }\n\n /** Number of matching entities. */\n get count(): number {\n return this.ids.length;\n }\n\n /** Check if an entity matches this query. */\n has(entityId: number): boolean {\n return this.index.has(entityId);\n }\n}\n\n/**\n * Builder for creating queries with .with() / .without() chaining.\n *\n * Obtain one from `world.queryBuilder()`. `build()` hands the finished Query to\n * the World it came from, which is what keeps it populated; the registration\n * hook is a required constructor argument so a builder cannot exist without a\n * World behind it, and the orphan `new QueryBuilder().build()` does not compile.\n */\nexport class QueryBuilder {\n private required = 0;\n private excluded = 0;\n private readonly register: (q: Query) => void;\n\n constructor(register: (q: Query) => void) {\n this.register = register;\n }\n\n with(...components: ComponentDef<unknown>[]): this {\n this.required |= (maskResolvers.get(this) ?? orBits)(components);\n return this;\n }\n\n without(...components: ComponentDef<unknown>[]): this {\n this.excluded |= (maskResolvers.get(this) ?? orBits)(components);\n return this;\n }\n\n /** Build the query and register it with the owning World. */\n build(): Query {\n const q = new Query(this.required, this.excluded);\n this.register(q);\n return q;\n }\n}\n\ntype MaskOf = (defs: readonly ComponentDef<unknown>[]) => number;\n\n// Kept off QueryBuilder's public surface: the mask representation is not part of\n// the contract (#173), so the World attaches its resolver here, not through the\n// constructor. A builder without one ORs each `def.bit`.\nconst maskResolvers = new WeakMap<QueryBuilder, MaskOf>();\n\n/** World-only (not exported from the package): route a builder's masks through the World's registry. */\nexport function bindMaskResolver(builder: QueryBuilder, maskOf: MaskOf): QueryBuilder {\n maskResolvers.set(builder, maskOf);\n return builder;\n}\n\nfunction orBits(defs: readonly ComponentDef<unknown>[]): number {\n let mask = 0;\n for (const c of defs) {\n mask |= c.bit;\n }\n return mask;\n}\n","import type { Query } from './query.js';\nimport type { World } from './world.js';\n\n/** A system function that processes entities matching a query. */\nexport type SystemFn = (query: Query, dt: number, world: World) => void;\n\n/** A defined system with its query and function. */\nexport interface SystemDef {\n readonly query: Query;\n readonly fn: SystemFn;\n /**\n * The wrapper to register on the World via `world.addSystem(sys.worldFn)`;\n * pass the same reference to `removeSystem`.\n */\n readonly worldFn: (world: World, dt: number) => void;\n /** @deprecated Use `worldFn` — the same function reference. Removed in the next planned minor. */\n readonly _worldFn: (world: World, dt: number) => void;\n}\n\n/**\n * Define a system that processes entities matching a query.\n *\n * Returns a SystemDef that can be added to a World via world.addSystem().\n * The system function receives the query's matching entities, dt, and world.\n *\n * Usage:\n * const q = world.query(Position, Velocity);\n * const moveSys = defineSystem(q, (query, dt, world) => {\n * const ids = query.entities;\n * for (let i = 0; i < ids.length; i++) { const id = ids[i]!; ... }\n * });\n * world.addSystem(moveSys.worldFn);\n *\n * Walk `query.entities` by index — that is the zero-alloc form. `for...of`\n * over the query works too but allocates an iterator per loop (and, on\n * Hermes, a result object per entity), which per system per frame is exactly\n * what a system must not do.\n */\nexport function defineSystem(query: Query, fn: SystemFn): SystemDef {\n const worldFn = (world: World, dt: number) => {\n fn(query, dt, world);\n };\n return { query, fn, worldFn, _worldFn: worldFn };\n}\n","import { Follower, Lifetime, Position, Velocity } from './components.js';\nimport type { Query } from './query.js';\nimport type { SystemDef } from './system.js';\nimport { defineSystem } from './system.js';\nimport type { World } from './world.js';\n\n/**\n * Plain camera-space bounding box used by createBoundsCullSystem.\n * Keep plain numbers — do NOT import physics AABB/Bounds (layer inversion).\n */\nexport interface CullBounds {\n readonly minX: number;\n readonly minY: number;\n readonly maxX: number;\n readonly maxY: number;\n}\n\n/**\n * createMovementSystem — integrates Position by Velocity * dt each frame.\n *\n * Recommended priority: run BEFORE createFollowerSystem (0).\n */\nexport function createMovementSystem(world: World): SystemDef {\n const q = world.query(Position, Velocity);\n return defineSystem(q, (query, dt, w) => {\n const ids = query.entities;\n for (let i = 0; i < ids.length; i++) {\n const id = ids[i]!;\n const pos = w.get(id, Position)!;\n const vel = w.get(id, Velocity)!;\n pos.x += vel.x * dt;\n pos.y += vel.y * dt;\n }\n });\n}\n\n/**\n * createLifetimeSystem — decrements Lifetime.remaining each frame.\n * Entities whose remaining reaches <= 0 are collected, then onExpire is called\n * for each AFTER the read loop.\n *\n * Deferred removal: destroying inside a live walk of query.entities swap-removes\n * from the array mid-iteration and would skip entities. Collect first, act after.\n *\n * The scratch array is closure-owned and grow-only — zero steady-state alloc.\n *\n * @param onExpire Destroy / pool policy — ecs never destroys on its own.\n * @param query Optional caller-supplied Query. When omitted the system\n * registers world.query(Lifetime) itself. Pass a narrower\n * query to avoid scanning unrelated Lifetime holders and to\n * share an already-registered query (eliminates duplicate\n * World.query registration cost).\n */\nexport function createLifetimeSystem(\n world: World,\n onExpire: (entity: number, world: World) => void,\n query?: Query,\n): SystemDef {\n const q = query ?? world.query(Lifetime);\n const scratch: number[] = [];\n return defineSystem(q, (query, dt, w) => {\n scratch.length = 0;\n const ids = query.entities;\n for (let i = 0; i < ids.length; i++) {\n const id = ids[i]!;\n const life = w.get(id, Lifetime)!;\n life.remaining -= dt;\n if (life.remaining <= 0) {\n scratch.push(id);\n }\n }\n for (let i = 0; i < scratch.length; i++) {\n onExpire(scratch[i]!, w);\n }\n });\n}\n\n/**\n * createBoundsCullSystem — culls entities whose Position falls outside bounds.\n * Reads bounds LIVE each frame so callers can mutate it to follow a camera.\n * Entities outside are collected, then onCull is called for each after the read loop.\n *\n * Deferred removal: same splice-during-iteration reason as createLifetimeSystem.\n *\n * Recommended priority: run AFTER createMovementSystem and createFollowerSystem.\n *\n * @param bounds Mutable bounding box read each frame.\n * @param onCull Destroy / pool policy — ecs never destroys on its own.\n * @param query Optional caller-supplied Query. When omitted the system\n * registers world.query(Position) itself, scanning all\n * Position holders. Pass a narrower query (e.g. bullets\n * only) to avoid scanning unrelated entities such as\n * scrolling backgrounds, and to share an already-registered\n * query with the caller.\n */\nexport function createBoundsCullSystem(\n world: World,\n bounds: CullBounds,\n onCull: (entity: number, world: World) => void,\n query?: Query,\n): SystemDef {\n const q = query ?? world.query(Position);\n const scratch: number[] = [];\n return defineSystem(q, (query, _dt, w) => {\n scratch.length = 0;\n const ids = query.entities;\n for (let i = 0; i < ids.length; i++) {\n const id = ids[i]!;\n const pos = w.get(id, Position)!;\n if (\n pos.x < bounds.minX ||\n pos.x > bounds.maxX ||\n pos.y < bounds.minY ||\n pos.y > bounds.maxY\n ) {\n scratch.push(id);\n }\n }\n for (let i = 0; i < scratch.length; i++) {\n onCull(scratch[i]!, w);\n }\n });\n}\n\n/**\n * createFollowerSystem — pins each Follower entity's Position to\n * target.Position + (offsetX, offsetY).\n * If the target is gone or has no Position, the entity is silently skipped.\n *\n * Recommended priority: run AFTER createMovementSystem (1) so the target's\n * position is already integrated before the follower snaps to it.\n */\nexport function createFollowerSystem(world: World): SystemDef {\n const q = world.query(Position, Follower);\n return defineSystem(q, (query, _dt, w) => {\n const ids = query.entities;\n for (let i = 0; i < ids.length; i++) {\n const id = ids[i]!;\n const follower = w.get(id, Follower)!;\n const t = w.get(follower.target, Position);\n if (t === undefined) continue;\n const pos = w.get(id, Position)!;\n pos.x = t.x + follower.offsetX;\n pos.y = t.y + follower.offsetY;\n }\n });\n}\n\n/**\n * createOrphanCullSystem — fires onOrphan for each Follower whose target entity\n * no longer exists. Does NOT move or destroy anything itself.\n *\n * Split from createFollowerSystem so games that want to orphan-cull can opt in\n * without coupling destruction to the follower pin logic.\n *\n * Recommended priority: run AFTER createFollowerSystem (2) so the follower is\n * pinned before orphans are detected.\n *\n * Deferred removal: same splice-during-iteration reason as createLifetimeSystem.\n *\n * @param onOrphan Called once per orphaned entity after the read loop.\n */\nexport function createOrphanCullSystem(\n world: World,\n onOrphan: (entity: number, world: World) => void,\n): SystemDef {\n const q = world.query(Follower);\n const scratch: number[] = [];\n return defineSystem(q, (query, _dt, w) => {\n scratch.length = 0;\n const ids = query.entities;\n for (let i = 0; i < ids.length; i++) {\n const id = ids[i]!;\n const follower = w.get(id, Follower)!;\n if (!w.exists(follower.target)) {\n scratch.push(id);\n }\n }\n for (let i = 0; i < scratch.length; i++) {\n onOrphan(scratch[i]!, w);\n }\n });\n}\n","import type { ComponentDef } from './component.js';\nimport { bindMaskResolver, Query, QueryBuilder } from './query.js';\n\ninterface ComponentSlot {\n readonly bit: number;\n readonly store: Map<number, unknown>; // entityId → data\n}\n\nconst MAX_COMPONENT_TYPES = 32;\n\n/**\n * World is the central ECS container.\n *\n * Entities are integer IDs. Components are stored in per-component Maps.\n * Archetype bitmasks enable fast query matching.\n */\nexport class World {\n private nextId = 1;\n private archetypes = new Map<number, number>(); // entityId → bitmask\n private slots = new Map<ComponentDef<unknown>, ComponentSlot>();\n private usedBits = 0;\n private stores = new Map<ComponentDef<unknown>, Map<number, unknown>>();\n private storesByBit: (Map<number, unknown> | undefined)[] = new Array(MAX_COMPONENT_TYPES).fill(\n undefined,\n );\n private queries: Query[] = [];\n private queryIterDepth = 0;\n private pendingQueryRemove: Query[] | null = null;\n private systems: {\n fn: (world: World, dt: number) => void;\n priority: number;\n }[] = [];\n private systemsSorted = false;\n\n /** Create a new entity. Returns the entity ID. */\n spawn(): number {\n const id = this.nextId++;\n this.archetypes.set(id, 0);\n return id;\n }\n\n /** Remove an entity and all its components. */\n destroy(entityId: number): void {\n const arch = this.archetypes.get(entityId);\n if (arch === undefined) return;\n\n // Clear the lowest set bit each pass, so only the stores this entity is in are touched.\n for (let m = arch; m !== 0; m &= m - 1) {\n this.storesByBit[31 - Math.clz32(m & -m)]?.delete(entityId);\n }\n\n this.archetypes.delete(entityId);\n\n this.notifyQueries(entityId, 0, true);\n }\n\n /** Add a component to an entity. */\n add<T>(entityId: number, def: ComponentDef<T>, data?: T): void {\n const arch = this.archetypes.get(entityId);\n if (arch === undefined) return;\n\n const slot = this.slotFor(def);\n slot.store.set(entityId, data !== undefined ? data : def.create());\n\n const newArch = arch | slot.bit;\n this.archetypes.set(entityId, newArch);\n\n this.notifyQueries(entityId, newArch, false);\n }\n\n /** Remove a component from an entity. */\n remove<T>(entityId: number, def: ComponentDef<T>): void {\n const arch = this.archetypes.get(entityId);\n if (arch === undefined) return;\n\n const slot = this.slots.get(def);\n if (slot === undefined) return;\n slot.store.delete(entityId);\n\n const newArch = arch & ~slot.bit;\n this.archetypes.set(entityId, newArch);\n\n this.notifyQueries(entityId, newArch, false);\n }\n\n /** Get component data for an entity. */\n get<T>(entityId: number, def: ComponentDef<T>): T | undefined {\n return this.stores.get(def)?.get(entityId) as T | undefined;\n }\n\n /** Check if entity has a component. */\n has(entityId: number, def: ComponentDef<unknown>): boolean {\n const slot = this.slots.get(def);\n if (slot === undefined) return false;\n const arch = this.archetypes.get(entityId);\n return arch !== undefined && (arch & slot.bit) !== 0;\n }\n\n /**\n * The slot a definition holds in this World, assigned on first use. Within one\n * copy of the package ids are unique, so every definition keeps its own `bit`\n * and query masks stay the OR of `def.bit`. Only a definition whose bit is\n * already held here (a second copy of the package, a hand-built literal, reuse\n * after `_resetComponentIds`) gets another one, where it used to share storage.\n */\n private slotFor(def: ComponentDef<unknown>): ComponentSlot {\n const known = this.slots.get(def);\n if (known !== undefined) return known;\n\n const free = ~this.usedBits;\n if (free === 0) throw capacityError(def);\n const own = def.bit | 0;\n const isFreeSingleBit = own !== 0 && (own & (own - 1)) === 0 && (own & free) !== 0;\n const bit = isFreeSingleBit ? own : free & -free;\n\n const slot: ComponentSlot = { bit, store: new Map() };\n this.slots.set(def, slot);\n this.stores.set(def, slot.store);\n this.usedBits |= bit;\n this.storesByBit[31 - Math.clz32(bit)] = slot.store;\n return slot;\n }\n\n /** Mask for a set of definitions. Checks room for all of them before assigning any slot. */\n private maskOf(defs: readonly ComponentDef<unknown>[]): number {\n let room = MAX_COMPONENT_TYPES - this.slots.size;\n let i = 0;\n for (const def of defs) {\n if (!this.slots.has(def) && defs.indexOf(def) === i && room-- === 0) {\n throw capacityError(def);\n }\n i++;\n }\n\n let mask = 0;\n for (const def of defs) {\n mask |= this.slotFor(def).bit;\n }\n return mask;\n }\n\n /** Check if entity exists. */\n exists(entityId: number): boolean {\n return this.archetypes.has(entityId);\n }\n\n /** Number of live entities. */\n get entityCount(): number {\n return this.archetypes.size;\n }\n\n /**\n * Walk every live entity ID. Iterates the live archetype map directly, with no\n * array snapshot. Archetype changes (add/remove component) keep the same entity\n * keys, so iteration is stable across them. Destroying entities inside the\n * callback is safe, but entities spawned inside it are visited in the same pass\n * (live Map iteration) — don't spawn from within.\n */\n forEachEntity(cb: (entity: number) => void): void {\n for (const entityId of this.archetypes.keys()) {\n cb(entityId);\n }\n }\n\n /**\n * Create a query. Queries auto-update as entities change.\n * Use the QueryBuilder-style chaining:\n * world.query(Position, Velocity)\n * Or use the builder:\n * world.queryBuilder().with(Position).without(Dead).build()\n */\n query(...components: ComponentDef<unknown>[]): Query {\n const q = new Query(this.maskOf(components), 0);\n this.register(q);\n return q;\n }\n\n /** Create a QueryBuilder for complex queries (with/without). */\n queryBuilder(): QueryBuilder {\n return bindMaskResolver(new QueryBuilder((q) => this.register(q)), (defs) => this.maskOf(defs));\n }\n\n /** Track a query and populate it with the entities that already match. */\n private register(q: Query): void {\n this.queries.push(q);\n for (const [entityId, arch] of this.archetypes) {\n q._check(entityId, arch);\n }\n }\n\n /**\n * Dispose a query created by `query()` or `queryBuilder().build()`. Afterwards\n * the world stops updating it, so it no longer costs spawn/add/remove iteration\n * time. The query is left inert — drop the reference to let it be collected.\n *\n * Safe to call from within a Query signal handler (e.g. a one-shot\n * `onEntityAdded` that disposes its own query): the removal is deferred until\n * the in-progress mutation finishes iterating, so no other query is skipped.\n */\n removeQuery(q: Query): void {\n if (this.queryIterDepth > 0) {\n if (this.pendingQueryRemove === null) this.pendingQueryRemove = [];\n this.pendingQueryRemove.push(q);\n return;\n }\n const idx = this.queries.indexOf(q);\n if (idx !== -1) this.queries.splice(idx, 1);\n }\n\n /** Notify queries in order, deferring any removeQuery until the loop unwinds. */\n private notifyQueries(entityId: number, arch: number, destroyed: boolean): void {\n this.queryIterDepth++;\n try {\n if (destroyed) {\n for (const query of this.queries) {\n query._remove(entityId);\n }\n } else {\n for (const query of this.queries) {\n query._check(entityId, arch);\n }\n }\n } finally {\n this.endQueryIteration();\n }\n }\n\n /** @internal End a query-notify loop; flush any removeQuery deferred during it. */\n private endQueryIteration(): void {\n this.queryIterDepth--;\n if (this.queryIterDepth === 0 && this.pendingQueryRemove !== null) {\n for (const q of this.pendingQueryRemove) {\n const idx = this.queries.indexOf(q);\n if (idx !== -1) this.queries.splice(idx, 1);\n }\n this.pendingQueryRemove.length = 0;\n }\n }\n\n /** Register a system function. Lower priority runs first. */\n addSystem(fn: (world: World, dt: number) => void, priority = 0): void {\n this.systems.push({ fn, priority });\n this.systemsSorted = false;\n }\n\n /** Remove a system. */\n removeSystem(fn: (world: World, dt: number) => void): void {\n const idx = this.systems.findIndex((s) => s.fn === fn);\n if (idx !== -1) this.systems.splice(idx, 1);\n }\n\n /** Run all systems in priority order. */\n step(dt: number): void {\n if (!this.systemsSorted) {\n this.systems.sort((a, b) => a.priority - b.priority);\n this.systemsSorted = true;\n }\n for (const sys of this.systems) {\n sys.fn(this, dt);\n }\n }\n}\n\nfunction capacityError(def: ComponentDef<unknown>): Error {\n return new Error(`A World holds at most 32 component types (registering \"${def.name}\")`);\n}\n"],"mappings":";;AA6BA,IAAI,kBAAkB;;;;;;;AAQtB,SAAgB,gBAA+B,MAAc,UAAqC;CAChG,MAAM,KAAK;CACX,IAAI,MAAM,IACR,MAAM,IAAI,MAAM,kDAAkD,KAAK,GAAG;CAE5E,OAAO;EACL;EACA,KAAK,KAAK;EACV;EACA,QAAQ,mBAAmB,KAAA;CAC7B;AACF;;;;;;;AAQA,SAAgB,qBAA2B;CACzC,kBAAkB;AACpB;;;;;;AClDA,MAAa,WAAW,gBAAsB,mBAAmB;CAC/D,GAAG;CACH,GAAG;AACL,EAAE;;AAGF,MAAa,WAAW,gBAAsB,mBAAmB;CAC/D,GAAG;CACH,GAAG;AACL,EAAE;;AAGF,MAAa,WAAW,gBAAmC,mBAAmB,EAC5E,OAAO,EACT,EAAE;;AAGF,MAAa,QAAQ,gBAAsB,gBAAgB;CAAE,GAAG;CAAG,GAAG;AAAE,EAAE;;AAG1E,MAAa,SAAS,gBAAoC,iBAAiB,EACzE,QAAQ,EACV,EAAE;;AAGF,MAAa,WAAW,gBAAuC,mBAAmB,EAChF,WAAW,EACb,EAAE;;AAGF,MAAa,WAAW,gBACtB,mBACO;CAAE,QAAQ;CAAG,SAAS;CAAG,SAAS;AAAE,EAC7C;;;;;;;;AC3BA,IAAa,MAAb,MAAgC;CACtB;CACA,0BAAU,IAAI,IAAsB;CACpC,+BAAe,IAAI,IAAiC;CACpD;CAER,YAAY,GAAG,MAA+C;EAC5D,KAAK,WAAW,KAAK;CACvB;;CAGA,IAAI,UAAgC;EAClC,OAAO,KAAK;CACd;;CAGA,SAAS,OAAuB;EAC9B,KAAK,QAAQ,IAAI,MAAM,MAAM,KAAK;EAClC,OAAO;CACT;;;;;CA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EACrD,IAAI,QAAQ,IAAI,KAAK,QAAQ,OAAO,KAAK,CAAC;CAC5C;;CAGA,KAAK,IAAkB;EACrB,IAAI,CAAC,KAAK,eAAe;GACvB,KAAK,QAAQ,MAAM,GAAG,MAAM,EAAE,WAAW,EAAE,QAAQ;GACnD,KAAK,gBAAgB;EACvB;EACA,KAAK,MAAM,OAAO,KAAK,SACrB,IAAI,GAAG,MAAM,EAAE;CAEnB;AACF;AAEA,SAAS,cAAc,KAAmC;CACxD,uBAAO,IAAI,MAAM,0DAA0D,IAAI,KAAK,GAAG;AACzF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@flare-engine/ecs",
3
- "version": "0.4.13",
3
+ "version": "0.4.14",
4
4
  "description": "Entity-Component-System with archetype queries",
5
5
  "keywords": ["flare-engine", "ecs", "entity-component-system", "react-native", "typescript"],
6
6
  "license": "Apache-2.0",
@@ -37,8 +37,8 @@
37
37
  "typecheck": "tsc --noEmit"
38
38
  },
39
39
  "dependencies": {
40
- "@flare-engine/events": "^0.4.13",
41
- "@flare-engine/math": "^0.4.13"
40
+ "@flare-engine/events": "^0.4.14",
41
+ "@flare-engine/math": "^0.4.14"
42
42
  },
43
43
  "engines": {
44
44
  "node": ">=20"