ecspresso 0.16.0 → 0.16.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/entity-manager.d.ts +10 -4
- package/dist/index.js +2 -2
- package/dist/index.js.map +7 -5
- package/dist/query-cache.d.ts +46 -0
- package/dist/query-match.d.ts +14 -0
- package/dist/reactive-query-manager.d.ts +0 -3
- package/package.json +1 -1
package/dist/entity-manager.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { Entity, FilteredEntity, RemoveEntityOptions, HierarchyEntry, HierarchyIteratorOptions } from "./types";
|
|
2
|
+
import QueryCache from "./query-cache";
|
|
2
3
|
export default class EntityManager<ComponentTypes> {
|
|
3
4
|
private nextId;
|
|
4
5
|
private entities;
|
|
@@ -35,6 +36,13 @@ export default class EntityManager<ComponentTypes> {
|
|
|
35
36
|
private _afterComponentRemovedHooks;
|
|
36
37
|
private _beforeEntityRemovedHooks;
|
|
37
38
|
private _afterParentChangedHooks;
|
|
39
|
+
/**
|
|
40
|
+
* Incrementally-maintained query result cache. Caches the static portion
|
|
41
|
+
* (with / without / parentHas) of each registered query shape and is
|
|
42
|
+
* updated via the lifecycle hook arrays above. Lazily created on the
|
|
43
|
+
* first cacheable query lookup.
|
|
44
|
+
*/
|
|
45
|
+
private readonly _queryCache;
|
|
38
46
|
private _batchingDepth;
|
|
39
47
|
private _batchedEntityIds;
|
|
40
48
|
/** Component keys being added in the current addComponents batch, if any.
|
|
@@ -83,10 +91,8 @@ export default class EntityManager<ComponentTypes> {
|
|
|
83
91
|
* Returns the same array reference for convenience.
|
|
84
92
|
*/
|
|
85
93
|
getEntitiesWithQueryInto<WithComponents extends keyof ComponentTypes = never, WithoutComponents extends keyof ComponentTypes = never>(output: Array<FilteredEntity<ComponentTypes, WithComponents extends never ? never : WithComponents, WithoutComponents extends never ? never : WithoutComponents>>, required?: ReadonlyArray<WithComponents>, excluded?: ReadonlyArray<WithoutComponents>, changed?: ReadonlyArray<keyof ComponentTypes>, changeThreshold?: number, parentHas?: ReadonlyArray<keyof ComponentTypes>): Array<FilteredEntity<ComponentTypes, WithComponents extends never ? never : WithComponents, WithoutComponents extends never ? never : WithoutComponents>>;
|
|
86
|
-
/**
|
|
87
|
-
|
|
88
|
-
*/
|
|
89
|
-
private parentHasComponents;
|
|
94
|
+
/** Test-only accessor for the internal query cache. @internal */
|
|
95
|
+
get _queryCacheForTesting(): QueryCache<ComponentTypes>;
|
|
90
96
|
removeEntity(entityId: number, options?: RemoveEntityOptions): boolean;
|
|
91
97
|
/**
|
|
92
98
|
* Internal method to remove a single entity without cascade logic
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var jj=((j)=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(j,{get:(D,$)=>(typeof require<"u"?require:D)[$]}):j)(function(j){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+j+'" is not supported')});class E{parentMap=new Map;childrenMap=new Map;_bfsQueue=[];setParent(j,D){if(j===D)throw Error(`Cannot set entity ${j} as its own parent`);if(this.wouldCreateCycle(j,D))throw Error("Cannot set parent: would create circular reference");let $=this.parentMap.get(j);if($!==void 0){let J=this.childrenMap.get($);if(J){let X=J.indexOf(j);if(X!==-1)J.splice(X,1)}}this.parentMap.set(j,D);let G=this.childrenMap.get(D);if(G)G.push(j);else this.childrenMap.set(D,[j]);return this}removeParent(j){let D=this.parentMap.get(j);if(D===void 0)return!1;let $=this.childrenMap.get(D);if($){let G=$.indexOf(j);if(G!==-1)$.splice(G,1)}return this.parentMap.delete(j),!0}getParent(j){return this.parentMap.get(j)??null}getChildren(j){let D=this.childrenMap.get(j);return D?[...D]:[]}getChildAt(j,D){if(D<0)return null;let $=this.childrenMap.get(j);if(!$||D>=$.length)return null;return $[D]??null}getChildIndex(j,D){let $=this.childrenMap.get(j);if(!$)return-1;return $.indexOf(D)}removeEntity(j){let D=this.parentMap.get(j)??null;if(D!==null){let J=this.childrenMap.get(D);if(J){let X=J.indexOf(j);if(X!==-1)J.splice(X,1)}}this.parentMap.delete(j);let $=this.childrenMap.get(j)??[],G=[...$];for(let J of $)this.parentMap.delete(J);return this.childrenMap.delete(j),{oldParent:D,orphanedChildren:G}}getAncestors(j){let D=[],$=this.parentMap.get(j);while($!==void 0)D.push($),$=this.parentMap.get($);return D}getDescendants(j){let D=[],$=this.childrenMap.get(j);if(!$)return D;let G=$.slice().reverse();while(G.length>0){let J=G.pop();D.push(J);let X=this.childrenMap.get(J);if(X)for(let Z=X.length-1;Z>=0;Z--)G.push(X[Z])}return D}getRoot(j){let D=j,$=this.parentMap.get(D);while($!==void 0)D=$,$=this.parentMap.get(D);return D}getSiblings(j){let D=this.parentMap.get(j);if(D===void 0)return[];let $=this.childrenMap.get(D);if(!$)return[];return $.filter((G)=>G!==j)}isDescendantOf(j,D){if(j===D)return!1;let $=this.parentMap.get(j);while($!==void 0){if($===D)return!0;$=this.parentMap.get($)}return!1}isAncestorOf(j,D){return this.isDescendantOf(D,j)}get hasHierarchy(){return this.childrenMap.size>0}getRootEntities(){let j=[];for(let D of this.childrenMap.keys())if(!this.parentMap.has(D))j.push(D);return j}wouldCreateCycle(j,D){let $=D;while($!==void 0){if($===j)return!0;$=this.parentMap.get($)}return!1}forEachInHierarchy(j,D){let $=D?.roots??this.getRootEntities(),G=this._bfsQueue;G.length=0;for(let J of $)G.push(J,-1,0);for(let J=0;J<G.length;J+=3){let X=G[J],Z=G[J+1],F=G[J+2];j(X,Z===-1?null:Z,F);let _=this.childrenMap.get(X);if(_){let Q=F+1;for(let B of _)G.push(B,X,Q)}}}*hierarchyIterator(j){let D=j?.roots??this.getRootEntities(),$=[];for(let G of D)$.push({entityId:G,parentId:null,depth:0});for(let G of $){yield G;let J=this.childrenMap.get(G.entityId);if(J)for(let X of J)$.push({entityId:X,parentId:G.entityId,depth:G.depth+1})}}}function k(j,D){for(let $ of D)if(!($ in j))return!1;return!0}function I(j,D){for(let $ of D)if($ in j)return!0;return!1}function u(j,D,$){if(!j)return!1;for(let G of D)if((j.get(G)??-1)>$)return!0;return!1}class g{callbacks=[];_iterDepth=0;_pendingRemovals=[];add(j){this.callbacks.push(j)}remove(j){if(this._iterDepth>0){this._pendingRemovals.push(j);return}let D=this.callbacks.indexOf(j);if(D!==-1)this.callbacks.splice(D,1)}invoke(j){this._iterDepth++;let D=this.callbacks.length;for(let $=0;$<D;$++){let G=this.callbacks[$];if(G)G(j)}if(this._iterDepth--,this._iterDepth===0&&this._pendingRemovals.length>0){for(let $ of this._pendingRemovals){let G=this.callbacks.indexOf($);if(G!==-1)this.callbacks.splice(G,1)}this._pendingRemovals.length=0}}}class R{nextId=1;entities=new Map;componentIndices=new Map;addedCallbacks=new Map;removedCallbacks=new Map;hierarchyManager=new E;disposeCallbacks=new Map;changeSeqs=new Map;_changeSeq=0;_afterComponentAddedHooks=[];_afterEntityMutatedHooks=[];_afterComponentRemovedHooks=[];_beforeEntityRemovedHooks=[];_afterParentChangedHooks=[];_batchingDepth=0;_batchedEntityIds=new Set;_pendingBatchKeys=null;get entityCount(){return this.entities.size}createEntity(){let j=this.nextId++,D={id:j,components:{}};return this.entities.set(j,D),D}registerDispose(j,D){this.disposeCallbacks.set(j,D)}getDisposeCallbacks(){return this.disposeCallbacks}invokeDispose(j,D,$){let G=this.disposeCallbacks.get(j);if(!G)return;try{G({value:D,entityId:$})}catch(J){console.warn(`Component dispose callback for '${String(j)}' threw:`,J)}}addComponent(j,D,$){let G=this.entities.get(j);if(!G)throw Error(`Cannot add component '${String(D)}': Entity with ID ${j} does not exist`);let J=G.components[D];if(J!==void 0)this.invokeDispose(D,J,G.id);if(G.components[D]=$,!this.componentIndices.has(D))this.componentIndices.set(D,new Set);this.componentIndices.get(D)?.add(G.id);let X=this.addedCallbacks.get(D);if(X)X.invoke({value:$,entity:G});this._batchingDepth++;for(let Z of this._afterComponentAddedHooks)Z(G.id,D);if(this._batchedEntityIds.add(G.id),this._batchingDepth--,this._batchingDepth===0){for(let Z of this._batchedEntityIds)for(let F of this._afterEntityMutatedHooks)F(Z);this._batchedEntityIds.clear()}return this}addComponents(j,D){let $=this.entities.get(j);if(!$)throw Error(`Cannot add components: Entity with ID ${j} does not exist`);let G=this._pendingBatchKeys;this._pendingBatchKeys=new Set(Object.keys(D)),this._batchingDepth++;for(let J in D)this.addComponent($.id,J,D[J]);if(this._batchingDepth--,this._pendingBatchKeys=G,this._batchingDepth===0){for(let J of this._batchedEntityIds)for(let X of this._afterEntityMutatedHooks)X(J);this._batchedEntityIds.clear()}return this}removeComponent(j,D){let $=this.entities.get(j);if(!$)throw Error(`Cannot remove component '${String(D)}': Entity with ID ${j} does not exist`);let G=$.components[D];if(G!==void 0)this.invokeDispose(D,G,$.id);delete $.components[D];let J=this.removedCallbacks.get(D);if(J&&G!==void 0)J.invoke({value:G,entity:$});if(this.componentIndices.get(D)?.delete($.id),G!==void 0)for(let X of this._afterComponentRemovedHooks)X($.id,D);return this}getComponent(j,D){return this.entities.get(j)?.components[D]}getEntitiesWithQuery(j=[],D=[],$,G,J){return this.getEntitiesWithQueryInto([],j,D,$,G,J)}getEntitiesWithQueryInto(j,D=[],$=[],G,J,X){j.length=0;let Z=G!==void 0&&G.length>0&&J!==void 0,F=X!==void 0&&X.length>0;if(D.length===0){if($.length===0&&!Z&&!F){for(let W of this.entities.values())j.push(W);return j}for(let W of this.entities.values()){if($.length>0&&I(W.components,$))continue;if(Z&&!u(this.changeSeqs.get(W.id),G,J))continue;if(F&&!this.parentHasComponents(W.id,X))continue;j.push(W)}return j}let _=D[0];if(_===void 0)return j;let Q=_,B=this.componentIndices.get(_)?.size??0;for(let W=1;W<D.length;W++){let Y=D[W];if(Y===void 0)continue;let O=this.componentIndices.get(Y)?.size??0;if(O<B)Q=Y,B=O}let L=this.componentIndices.get(Q);if(!L||L.size===0)return j;for(let W of L){let Y=this.entities.get(W);if(!Y)continue;if(!k(Y.components,D))continue;if($.length>0&&I(Y.components,$))continue;if(Z&&!u(this.changeSeqs.get(W),G,J))continue;if(F&&!this.parentHasComponents(W,X))continue;j.push(Y)}return j}parentHasComponents(j,D){let $=this.hierarchyManager.getParent(j);if($===null)return!1;let G=this.entities.get($);if(!G)return!1;return k(G.components,D)}removeEntity(j,D){let $=this.entities.get(j);if(!$)return!1;if(D?.cascade??!0){let J=this.hierarchyManager.getDescendants($.id);for(let X=J.length-1;X>=0;X--){let Z=J[X];if(Z===void 0)continue;for(let F of this._beforeEntityRemovedHooks)F(Z)}for(let X of this._beforeEntityRemovedHooks)X($.id);for(let X=J.length-1;X>=0;X--){let Z=J[X];if(Z===void 0)continue;this.removeEntityInternal(Z)}}else for(let J of this._beforeEntityRemovedHooks)J($.id);return this.removeEntityInternal($.id)}removeEntityInternal(j){let D=this.entities.get(j);if(!D)return!1;this.hierarchyManager.removeEntity(j);for(let $ of Object.keys(D.components)){let G=D.components[$];if(G!==void 0){this.invokeDispose($,G,D.id);let J=this.removedCallbacks.get($);if(J)J.invoke({value:G,entity:D})}this.componentIndices.get($)?.delete(D.id)}return this.changeSeqs.delete(D.id),this.entities.delete(D.id)}getEntity(j){return this.entities.get(j)}onComponentAdded(j,D){let $=D,G=this.addedCallbacks.get(j);if(!G)G=new g,this.addedCallbacks.set(j,G);return G.add($),()=>{this.addedCallbacks.get(j)?.remove($)}}onComponentRemoved(j,D){let $=D,G=this.removedCallbacks.get(j);if(!G)G=new g,this.removedCallbacks.set(j,G);return G.add($),()=>{this.removedCallbacks.get(j)?.remove($)}}onAfterComponentAdded(j){return this._afterComponentAddedHooks.push(j),()=>{let D=this._afterComponentAddedHooks.indexOf(j);if(D!==-1)this._afterComponentAddedHooks.splice(D,1)}}onAfterEntityMutated(j){return this._afterEntityMutatedHooks.push(j),()=>{let D=this._afterEntityMutatedHooks.indexOf(j);if(D!==-1)this._afterEntityMutatedHooks.splice(D,1)}}onAfterComponentRemoved(j){return this._afterComponentRemovedHooks.push(j),()=>{let D=this._afterComponentRemovedHooks.indexOf(j);if(D!==-1)this._afterComponentRemovedHooks.splice(D,1)}}onBeforeEntityRemoved(j){return this._beforeEntityRemovedHooks.push(j),()=>{let D=this._beforeEntityRemovedHooks.indexOf(j);if(D!==-1)this._beforeEntityRemovedHooks.splice(D,1)}}onAfterParentChanged(j){return this._afterParentChangedHooks.push(j),()=>{let D=this._afterParentChangedHooks.indexOf(j);if(D!==-1)this._afterParentChangedHooks.splice(D,1)}}get changeSeq(){return this._changeSeq}markChanged(j,D){let $=++this._changeSeq,G=this.changeSeqs.get(j);if(!G)G=new Map,this.changeSeqs.set(j,G);G.set(D,$)}getChangeSeq(j,D){return this.changeSeqs.get(j)?.get(D)??-1}spawnChild(j,D){let $=this.createEntity();return this.addComponents($.id,D),this.setParent($.id,j),$}setParent(j,D){this.hierarchyManager.setParent(j,D);for(let $ of this._afterParentChangedHooks)$(j);return this}removeParent(j){let D=this.hierarchyManager.removeParent(j);if(D)for(let $ of this._afterParentChangedHooks)$(j);return D}getParent(j){return this.hierarchyManager.getParent(j)}getChildren(j){return this.hierarchyManager.getChildren(j)}getChildAt(j,D){return this.hierarchyManager.getChildAt(j,D)}getChildIndex(j,D){return this.hierarchyManager.getChildIndex(j,D)}getAncestors(j){return this.hierarchyManager.getAncestors(j)}getDescendants(j){return this.hierarchyManager.getDescendants(j)}getRoot(j){return this.hierarchyManager.getRoot(j)}getSiblings(j){return this.hierarchyManager.getSiblings(j)}isDescendantOf(j,D){return this.hierarchyManager.isDescendantOf(j,D)}isAncestorOf(j,D){return this.hierarchyManager.isAncestorOf(j,D)}get hasHierarchy(){return this.hierarchyManager.hasHierarchy}getRootEntities(){return this.hierarchyManager.getRootEntities()}forEachInHierarchy(j,D){this.hierarchyManager.forEachInHierarchy(j,D)}hierarchyIterator(j){return this.hierarchyManager.hierarchyIterator(j)}}class w{handlers=new Map;subscribe(j,D){return this.addHandler(j,D,!1)}once(j,D){return this.addHandler(j,D,!0)}unsubscribe(j,D){let $=this.handlers.get(j);if(!$)return!1;let G=$.findIndex((J)=>J.callback===D);if(G===-1)return!1;return $.splice(G,1),!0}addHandler(j,D,$){let G=this.handlers.get(j);if(!G)G=[],this.handlers.set(j,G);let J={callback:D,once:$};return G.push(J),()=>{let X=this.handlers.get(j);if(X){let Z=X.indexOf(J);if(Z!==-1)X.splice(Z,1)}}}publish(...[j,D]){let $=this.handlers.get(j);if(!$||$.length===0)return;let G=!1,J=$.length;for(let X=0;X<J&&X<$.length;X++){let Z=$[X];if(!Z)continue;if(Z.callback(D),Z.once)G=!0}if(G){for(let X=$.length-1;X>=0;X--)if($[X]?.once)$.splice(X,1)}}clear(){this.handlers.clear()}clearEvent(j){this.handlers.delete(j)}}var v=Symbol("resource-direct");function r(j){return{[v]:j}}function f(j){if(typeof j==="object"&&j!==null&&!Array.isArray(j))return{...j};return{$value:j}}function a(j,D){if(typeof j==="object"&&j!==null&&!Array.isArray(j)){let $=j;for(let G in D)if(!Object.is($[G],D[G]))return!0;return!1}return!Object.is(j,D.$value)}function n(j){return typeof j==="object"&&j!==null&&"factory"in j&&typeof j.factory==="function"}function t(j){return typeof j==="object"&&j!==null&&v in j}function m(j,D){let $=[],G=new Set,J=new Set;function X(Z,F=[]){if(G.has(Z))return;if(J.has(Z))throw Error(`Circular resource dependency: ${[...F,Z].join(" -> ")}`);J.add(Z);for(let _ of D(Z)){let Q=j.find((B)=>B===_);if(Q)X(Q,[...F,Z])}J.delete(Z),G.add(Z),$.push(Z)}for(let Z of j)X(Z);return $}class S{resources=new Map;resourceFactories=new Map;resourceDependencies=new Map;resourceDisposers=new Map;initializedResourceKeys=new Set;_changeSubscribers=new Map;_observedSnapshots=new Map;add(j,D){let $=(G)=>{this.resources.set(j,G),this.initializedResourceKeys.add(j),this.resourceDependencies.set(j,[])};if(n(D)){if(this.resourceFactories.set(j,D.factory),this.resourceDependencies.set(j,D.dependsOn??[]),D.onDispose)this.resourceDisposers.set(j,D.onDispose)}else if(t(D))$(D[v]);else if(typeof D==="function")this.resourceFactories.set(j,D),this.resourceDependencies.set(j,[]);else $(D);return this}tryGet(j,...D){if(!this.has(j))return;return this.get(j,...D)}get(j,...D){let $=this.resources.get(j);if($!==void 0)return $;let G=this.resourceFactories.get(j);if(G===void 0)throw Error(`Resource ${String(j)} not found`);let J=D[0],X=G(J);if(!(X instanceof Promise))this.resources.set(j,X),this.initializedResourceKeys.add(j);return X}has(j){return this.resources.has(j)||this.resourceFactories.has(j)}remove(j){let D=this.resources.delete(j),$=this.resourceFactories.delete(j);return this.resourceDependencies.delete(j),this.resourceDisposers.delete(j),this.initializedResourceKeys.delete(j),D||$}getKeys(){let j=new Set([...this.resources.keys(),...this.resourceFactories.keys()]);return Array.from(j)}needsInitialization(j){return this.resourceFactories.has(j)&&!this.initializedResourceKeys.has(j)}getPendingInitializationKeys(){return Array.from(this.resourceFactories.keys()).filter((j)=>!this.initializedResourceKeys.has(j))}async initializeResource(j,...D){if(!this.resourceFactories.has(j)||this.initializedResourceKeys.has(j))return;let $=this.resourceFactories.get(j);if(!$)return;let G=D[0],J=await $(G);this.resources.set(j,J),this.initializedResourceKeys.add(j),this.resourceFactories.delete(j)}async initializeResources(...j){let D=j.slice(1),$=D.length===0?this.getPendingInitializationKeys():D;if($.length===0)return;let G=m($,(J)=>[...this.resourceDependencies.get(J)??[]]);for(let J of G)await this.initializeResource(J,...j.slice(0,1))}getDependencies(j){return this.resourceDependencies.get(j)??[]}async disposeResource(j,...D){if(!this.resources.has(j)&&!this.resourceFactories.has(j))return!1;if(this.initializedResourceKeys.has(j)){let $=this.resourceDisposers.get(j),G=this.resources.get(j);if($&&G!==void 0){let J=D[0];await $(G,J)}}return this.resources.delete(j),this.resourceFactories.delete(j),this.resourceDependencies.delete(j),this.resourceDisposers.delete(j),this.initializedResourceKeys.delete(j),this._changeSubscribers.delete(j),!0}onResourceChange(j,D){let $=this._changeSubscribers.get(j),G=$??new Set;if(!$){this._changeSubscribers.set(j,G);let X=this.resources.get(j);this._observedSnapshots.set(j,f(X))}let J=D;return G.add(J),()=>{if(G.delete(J),G.size===0)this._changeSubscribers.delete(j),this._observedSnapshots.delete(j)}}notifyChange(j,D,$){if(Object.is(D,$))return;let G=this._changeSubscribers.get(j);if(!G||G.size===0)return;if(this._observedSnapshots.has(j))this._observedSnapshots.set(j,f(D));let J=[...G];for(let X of J)X(D,$)}isObserved(j){return this._observedSnapshots.has(j)}flushObserved(){if(this._observedSnapshots.size===0)return;for(let[j,D]of this._observedSnapshots){let $=this.resources.get(j);if(!a($,D))continue;let G="$value"in D?D.$value:D,J=f($),X=this._changeSubscribers.get(j);for(let Z of X)Z($,G);this._observedSnapshots.set(j,J)}}async disposeResources(...j){let D=Array.from(this.initializedResourceKeys);if(D.length===0)return;let $=m(D,(G)=>[...this.resourceDependencies.get(G)??[]]).reverse();for(let G of $)await this.disposeResource(G,...j)}}class T{queries=new Map;entityManager;_hasParentHasQueries=!1;constructor(j){this.entityManager=j}get hasParentHasQueries(){return this._hasParentHasQueries}addQuery(j,D){let $={definition:D,matchingEntities:new Set};if(this.queries.set(j,$),D.parentHas?.length)this._hasParentHasQueries=!0;let G=this.entityManager.getEntitiesWithQuery(D.with,D.without??[]);for(let J of G)if(this.entityMatchesQuery(J,$.definition))$.matchingEntities.add(J.id),$.definition.onEnter?.(J)}removeQuery(j){let D=this.queries.delete(j);if(D)this._recalcParentHasFlag();return D}entityMatchesQuery(j,D){for(let $ of D.with)if(!($ in j.components))return!1;if(D.without){for(let $ of D.without)if($ in j.components)return!1}if(D.parentHas?.length){let $=this.entityManager.getParent(j.id);if($===null)return!1;let G=this.entityManager.getEntity($);if(!G)return!1;for(let J of D.parentHas)if(!(J in G.components))return!1}return!0}_applyQueryTransition(j,D){let $=D.matchingEntities.has(j.id),G=this.entityMatchesQuery(j,D.definition);if(!$&&G)D.matchingEntities.add(j.id),D.definition.onEnter?.(j);else if($&&!G)D.matchingEntities.delete(j.id),D.definition.onExit?.(j.id)}onComponentAdded(j,D){for(let[,$]of this.queries)this._applyQueryTransition(j,$);if(this._hasParentHasQueries)this._recheckChildren(j.id)}onComponentRemoved(j,D){for(let[,$]of this.queries)this._applyQueryTransition(j,$);if(this._hasParentHasQueries)this._recheckChildren(j.id)}onEntityRemoved(j){for(let[D,$]of this.queries)if($.matchingEntities.has(j))$.matchingEntities.delete(j),$.definition.onExit?.(j)}recheckEntity(j){for(let[,D]of this.queries)this._applyQueryTransition(j,D)}recheckEntityAndChildren(j){if(this.recheckEntity(j),this._hasParentHasQueries)this._recheckChildren(j.id)}_recheckChildren(j){let D=this.entityManager.getChildren(j);for(let $ of D){let G=this.entityManager.getEntity($);if(G)this.recheckEntity(G)}}_recalcParentHasFlag(){this._hasParentHasQueries=!1;for(let[,j]of this.queries)if(j.definition.parentHas?.length){this._hasParentHasQueries=!0;return}}}class x{parent;commands=[];constructor(j){this.parent=j}removeEntity(j,D){this.commands.push(($)=>{$.removeEntity(j,D)})}addComponent(j,D,$){this.commands.push((G)=>{G.addComponent(j,D,$)})}removeComponent(j,D){this.commands.push(($)=>{$.removeComponent(j,D)})}spawn(j,D){let $=this._resolveScope(D);this.commands.push((G)=>{G.spawn(j,$)})}spawnChild(j,D,$){let G=this._resolveScope($);this.commands.push((J)=>{J.spawnChild(j,D,G)})}_resolveScope(j){if(j?.scope!==void 0)return j;let D=this.parent?._getActiveScopeHint();if(!D)return j;return{scope:D}}addComponents(j,D){this.commands.push(($)=>{$.addComponents(j,D)})}setParent(j,D){this.commands.push(($)=>{$.setParent(j,D)})}mutateComponent(j,D,$){this.commands.push((G)=>{G.mutateComponent(j,D,$)})}markChanged(j,D){this.commands.push(($)=>{$.markChanged(j,D)})}removeParent(j){this.commands.push((D)=>{D.removeParent(j)})}playback(j){for(let D of this.commands)try{D(j)}catch($){console.warn("CommandBuffer: Command failed during playback:",$)}this.commands.length=0}clear(){this.commands.length=0}get length(){return this.commands.length}}class l{_id;constructor(j){this._id=j}_systemDefaults;setSystemDefaults(j){return this._systemDefaults=j,this}withComponentTypes(){return this}withEventTypes(){return this}withResourceTypes(){return this}withAssetTypes(){return this}withScreenTypes(){return this}withLabels(){return this}withGroups(){return this}withAssetGroupNames(){return this}withReactiveQueryNames(){return this}requires(){return this}install(j){return{id:this._id,install:j,...this._systemDefaults?{systemDefaults:this._systemDefaults}:{}}}}function V(j){return new l(j)}var s="__each";class C{_label;queries={};singletons={};processFunction;detachFunction;initializeFunction;eventHandlers;_priority=0;_phase="update";_groups=[];_inScreens;_excludeScreens;_requiredAssets;_runWhenEmpty=!1;_entityEnterHandlers={};_resourceKeys;constructor(j,D){this._label=j;if(D){if(D.phase!==void 0)this._phase=D.phase;if(D.priority!==void 0)this._priority=D.priority;if(D.inScreens!==void 0)this._inScreens=D.inScreens;if(D.excludeScreens!==void 0)this._excludeScreens=D.excludeScreens}}get label(){return this._label}_createSystemObject(){let j={label:this._label,entityQueries:this.queries,priority:this._priority,phase:this._phase};if(Object.keys(this.singletons).length>0)j.entitySingletons=this.singletons;if(this.processFunction)j.process=this.processFunction;if(this.detachFunction)j.onDetach=this.detachFunction;if(this.initializeFunction)j.onInitialize=this.initializeFunction;if(this.eventHandlers)j.eventHandlers=this.eventHandlers;if(this._groups.length>0)j.groups=[...this._groups];if(this._inScreens)j.inScreens=this._inScreens;if(this._excludeScreens)j.excludeScreens=this._excludeScreens;if(this._requiredAssets)j.requiredAssets=this._requiredAssets;if(this._runWhenEmpty)j.runWhenEmpty=!0;if(Object.keys(this._entityEnterHandlers).length>0)j.onEntityEnter={...this._entityEnterHandlers};return j}setPriority(j){return this._priority=j,this}inPhase(j){return this._phase=j,this}inGroup(j){if(!this._groups.includes(j))this._groups.push(j);return this}inScreens(j){return this._inScreens=[...j],this}excludeScreens(j){return this._excludeScreens=[...j],this}requiresAssets(j){return this._requiredAssets=[...j],this}runWhenEmpty(){return this._runWhenEmpty=!0,this}withResources(j){return this._resourceKeys=[...j],this}addQuery(j,D){let $=this;return $.queries={...this.queries,[j]:D},$}addSingleton(j,D){let $=this;return $.singletons={...this.singletons,[j]:D},$}setProcess(j){return this.processFunction=this._wrapWithResources(j),this}_wrapWithResources(j){if(!this._resourceKeys?.length)return j;let D=this._resourceKeys,$={},G=!1;return(J)=>{for(let X of D)if(!G||J.ecs.isResourceObserved(X))$[X]=J.ecs.getResource(X);G=!0,J.resources=$,j(J)}}setProcessEach(j,D){let $=this;if(Object.keys($.queries).length>0||Object.keys($.singletons).length>0||$.processFunction!==void 0)throw Error("setProcessEach requires a SystemBuilder with no prior queries, singletons, or process function. Use addQuery + setProcess for multi-query systems.");$.queries.__each=j;let G={entity:void 0,dt:0,ecs:void 0,resources:void 0},J=j.mutates&&j.mutates.length>0?j.mutates:void 0,X=(Z)=>{let F=Z,_=F.queries.__each;if(!_)return;G.dt=F.dt,G.ecs=F.ecs,G.resources=F.resources;for(let Q=0;Q<_.length;Q++){let B=_[Q];if(!B)continue;G.entity=B;let L=D(G);if(J===void 0||L===!1)continue;for(let W=0;W<J.length;W++){let Y=J[W];if(Y!==void 0)F.ecs.markChanged(B.id,Y)}}};return $.processFunction=$._wrapWithResources(X),this}setOnEntityEnter(j,D){return this._entityEnterHandlers[j]=D,this}setOnDetach(j){return this.detachFunction=j,this}setOnInitialize(j){return this.initializeFunction=j,this}setEventHandlers(j){return this.eventHandlers=j,this}}function i(j,D,$){let G=new Set,J=[D];while(J.length>0){let X=J.pop();if(X===void 0)break;if(X===j)throw Error(`Circular required component dependency: '${String(j)}' -> '${String(D)}' -> ... -> '${String(j)}'`);if(G.has(X))continue;G.add(X);let Z=$(X);if(Z)for(let F of Z)J.push(F.component)}}var c="0.16.0";class z{assets=new Map;groups=new Map;eventBus=null;setEventBus(j){this.eventBus=j}register(j,D){if(this.assets.set(j,{definition:D,status:"pending"}),D.group){let $=this.groups.get(D.group)??new Set;$.add(j),this.groups.set(D.group,$)}}async loadEagerAssets(){let j=[];for(let[D,$]of this.assets)if($.definition.eager&&$.status==="pending")j.push(D);await Promise.all(j.map((D)=>this.loadAsset(D)))}async loadAsset(j){let D=this.assets.get(j);if(!D)throw Error(`Asset '${String(j)}' not found`);if(D.status==="loaded"&&D.value!==void 0)return D.value;if(D.status==="loading"&&D.loadPromise)return D.loadPromise;if(D.status==="failed")D.status="pending";D.status="loading",D.loadPromise=D.definition.loader();try{let $=await D.loadPromise;return D.value=$,D.status="loaded",D.loadPromise=void 0,this.eventBus?.publish("assetLoaded",{key:j}),this.checkGroupProgress(D.definition.group),$}catch($){let G=$ instanceof Error?$:Error(String($));throw D.status="failed",D.error=G,D.loadPromise=void 0,this.eventBus?.publish("assetFailed",{key:j,error:G}),G}}async loadAssetGroup(j){let D=this.groups.get(j);if(!D||D.size===0)throw Error(`Asset group '${j}' not found or empty`);await Promise.all(Array.from(D).map(($)=>this.loadAsset($)))}get(j){let D=this.assets.get(j);if(!D)throw Error(`Asset '${String(j)}' not found`);if(D.status!=="loaded"||D.value===void 0)throw Error(`Asset '${String(j)}' is not loaded (status: ${D.status})`);return D.value}tryGet(j){let D=this.assets.get(j);if(!D||D.status!=="loaded")return;return D.value}getHandle(j){let D=this.assets.get(j);if(!D)throw Error(`Asset '${String(j)}' not found`);let $=this;return{get status(){return D.status},get isLoaded(){return D.status==="loaded"},get(){return $.get(j)},tryGet(){return $.tryGet(j)}}}getStatus(j){let D=this.assets.get(j);if(!D)throw Error(`Asset '${String(j)}' not found`);return D.status}isLoaded(j){return this.assets.get(j)?.status==="loaded"}isGroupLoaded(j){let D=this.groups.get(j);if(!D||D.size===0)return!1;for(let $ of D){let G=this.assets.get($);if(!G||G.status!=="loaded")return!1}return!0}getGroupProgress(j){return this.getGroupProgressDetails(j).progress}getGroupProgressDetails(j){let D=this.groups.get(j);if(!D||D.size===0)return{loaded:0,total:0,progress:0};let $=0;for(let J of D)if(this.assets.get(J)?.status==="loaded")$++;let G=D.size;return{loaded:$,total:G,progress:$/G}}checkGroupProgress(j){if(!j||!this.eventBus)return;let D=j,$=this.getGroupProgressDetails(D);if(this.eventBus.publish("assetGroupProgress",{group:D,...$}),$.loaded===$.total)this.eventBus.publish("assetGroupLoaded",{group:D})}createResource(){let j=this;return{getStatus(D){return j.getStatus(D)},isLoaded(D){return j.isLoaded(D)},isGroupLoaded(D){return j.isGroupLoaded(D)},getGroupProgress(D){return j.getGroupProgress(D)},get(D){return j.get(D)},tryGet(D){return j.tryGet(D)},getHandle(D){return j.getHandle(D)}}}getKeys(){return Array.from(this.assets.keys())}getGroupNames(){return Array.from(this.groups.keys())}getGroupKeys(j){let D=this.groups.get(j);return D?Array.from(D):[]}}class d{manager;constructor(j){this.manager=j}add(j,D){return this.manager.register(j,{loader:D,eager:!0}),this}addWithConfig(j,D){return this.manager.register(j,D),this}addGroup(j,D){for(let[$,G]of Object.entries(D))this.manager.register($,{loader:G,eager:!1,group:j});return this}getManager(){return this.manager}}function N(j){return new d(j??new z)}class H{screens=new Map;currentScreen=null;screenStack=[];eventBus=null;assetManager=null;ecs=null;setDependencies(j,D,$){this.eventBus=j,this.assetManager=D,this.ecs=$}requireEcs(){if(!this.ecs)throw Error("ScreenManager: dependencies not set. Call setDependencies() first.");return this.ecs}register(j,D){this.screens.set(j,{definition:D})}async setScreen(j,D){let $=this.screens.get(j);if(!$)throw Error(`Screen '${String(j)}' not found`);await this.verifyRequiredAssets($.definition.requiredAssets,$.definition.requiredAssetGroups);while(this.screenStack.length>0){let J=this.screenStack.pop();if(J)await this.exitScreen(J.name)}if(this.currentScreen)await this.exitScreen(this.currentScreen.name);let G=$.definition.initialState(D);this.currentScreen={name:j,config:D,state:G},await $.definition.onEnter?.({config:D,ecs:this.requireEcs()}),this.eventBus?.publish("screenEnter",{screen:j,config:D})}async pushScreen(j,D){let $=this.screens.get(j);if(!$)throw Error(`Screen '${String(j)}' not found`);if(await this.verifyRequiredAssets($.definition.requiredAssets,$.definition.requiredAssetGroups),this.currentScreen)this.screenStack.push(this.currentScreen);let G=$.definition.initialState(D);this.currentScreen={name:j,config:D,state:G},await $.definition.onEnter?.({config:D,ecs:this.requireEcs()}),this.eventBus?.publish("screenPush",{screen:j,config:D})}async popScreen(){if(this.screenStack.length===0)throw Error("Cannot pop screen: stack is empty");if(this.currentScreen)await this.exitScreen(this.currentScreen.name),this.eventBus?.publish("screenPop",{screen:this.currentScreen.name});this.currentScreen=this.screenStack.pop()??null}async exitScreen(j){let D=this.screens.get(j);if(D?.definition.onExit)await D.definition.onExit(this.requireEcs());this.eventBus?.publish("screenExit",{screen:j})}async verifyRequiredAssets(j,D){if(!this.assetManager)return;if(j){for(let $ of j)if(!this.assetManager.isLoaded($))await this.assetManager.loadAsset($)}if(D){for(let $ of D)if(!this.assetManager.isGroupLoaded($))await this.assetManager.loadAssetGroup($)}}getCurrentScreen(){return this.currentScreen?.name??null}getConfig(j){if(!this.currentScreen)throw Error("No current screen");if(j!==void 0&&this.currentScreen.name!==j)throw Error(`Expected current screen '${String(j)}', but current is '${String(this.currentScreen.name)}'`);return this.currentScreen.config}tryGetConfig(j){if(!this.currentScreen)return;if(j!==void 0&&this.currentScreen.name!==j)return;return this.currentScreen.config}getState(j){if(!this.currentScreen)throw Error("No current screen");if(j!==void 0&&this.currentScreen.name!==j)throw Error(`Expected current screen '${String(j)}', but current is '${String(this.currentScreen.name)}'`);return this.currentScreen.state}tryGetState(j){if(!this.currentScreen)return;if(j!==void 0&&this.currentScreen.name!==j)return;return this.currentScreen.state}updateState(j,D){if(!this.currentScreen)throw Error("No current screen");if(D!==void 0&&this.currentScreen.name!==D)throw Error(`Expected current screen '${String(D)}', but current is '${String(this.currentScreen.name)}'`);let $=typeof j==="function"?j(this.currentScreen.state):j;this.currentScreen.state={...this.currentScreen.state,...$}}getStackDepth(){return this.screenStack.length}isOverlay(){return this.screenStack.length>0}isActive(j){if(this.currentScreen?.name===j)return!0;return this.screenStack.some((D)=>D.name===j)}isCurrent(j){return this.currentScreen?.name===j}createResource(){let j=this;return{get current(){return j.getCurrentScreen()},get config(){return j.tryGetConfig()??null},get state(){return j.tryGetState()??null},set state(D){if(j.currentScreen&&D!==null)j.currentScreen.state=D},get stack(){return j.screenStack},get isOverlay(){return j.isOverlay()},get stackDepth(){return j.getStackDepth()},isActive(D){return j.isActive(D)},isCurrent(D){return j.isCurrent(D)}}}getScreenNames(){return Array.from(this.screens.keys())}hasScreen(j){return this.screens.has(j)}}class y{manager;constructor(j){this.manager=j}add(j,D){return this.manager.register(j,D),this}getManager(){return this.manager}}function b(j){return new y(j??new H)}class p{assetConfigurator=null;screenConfigurator=null;pendingResources=[];pendingDisposeCallbacks=[];pendingRequiredComponents=[];pendingPlugins=[];_fixedDt=null;constructor(){}withPlugin(j){return this.pendingPlugins.push(j),this}withComponentTypes(){return this}withEventTypes(){return this}withResourceTypes(){return this}withResource(j,D){return this.pendingResources.push({key:j,value:D}),this}withDispose(j,D){return this.pendingDisposeCallbacks.push({key:j,callback:D}),this}withRequired(j,D,$){return this.pendingRequiredComponents.push({trigger:j,required:D,factory:$}),this}withAssets(j){let D=N();return j(D),this.assetConfigurator=D,this}withScreens(j){let D=b();return j(D),this.screenConfigurator=D,this}withFixedTimestep(j){return this._fixedDt=j,this}withReactiveQueryNames(){return this}pluginFactory(){return(j)=>V(j.id).install(j.install)}build(){let j=new P;for(let D of this.pendingPlugins)j._installPluginUnchecked(D);for(let{key:D,value:$}of this.pendingResources)j.addResource(D,$);for(let{key:D,callback:$}of this.pendingDisposeCallbacks)j.registerDispose(D,$);for(let{trigger:D,required:$,factory:G}of this.pendingRequiredComponents)j.registerRequired(D,$,G);if(this.assetConfigurator)j._setAssetManager(this.assetConfigurator.getManager());else if(j._hasPendingPluginAssets())j._setAssetManager(new z);if(this.screenConfigurator)j._setScreenManager(this.screenConfigurator.getManager());else if(j._hasPendingPluginScreens())j._setScreenManager(new H);if(this._fixedDt!==null)j._setFixedDt(this._fixedDt);return j}}var o=["preUpdate","fixedUpdate","update","postUpdate","render"];class P{static VERSION=c;_entityManager;_eventBus;_resourceManager;_commandBuffer;_systems=[];_phaseSystems={preUpdate:[],fixedUpdate:[],update:[],postUpdate:[],render:[]};_installedPlugins=new Set;_pluginCleanups=new Map;_currentSystemDefaults;_screenScopedEntities=new Map;_entityScreenScope=new Map;_activeScopeHint=null;_disabledGroups=new Set;_assetManager=null;_screenManager=null;_reactiveQueryManager;_postUpdateHooks=[];_currentTick=0;_systemLastSeqs=new Map;_changeThreshold=0;_fixedDt=0.016666666666666666;_fixedAccumulator=0;_interpolationAlpha=0;_maxFixedSteps=8;_requiredComponents=new Map;_pendingPluginAssets=[];_pendingPluginScreens=[];_diagnosticsEnabled=!1;_systemTimings=new Map;_phaseTimings={preUpdate:0,fixedUpdate:0,update:0,postUpdate:0,render:0};_entityEnterTracking=new Map;_entityEnterFrameSet=new Set;_systemContexts=new WeakMap;_singletonScratch=[];_pendingFinalizers=[];_batchingRegistrations=!1;_initializeFired=!1;_systemsInitialized=new WeakSet;constructor(){this._entityManager=new R,this._eventBus=new w,this._resourceManager=new S,this._reactiveQueryManager=new T(this._entityManager),this._commandBuffer=new x(this),this._subscribeLifecycleHooks()}_subscribeLifecycleHooks(){this._entityManager.onAfterComponentAdded((j,D)=>{this._entityManager.markChanged(j,D);let $=this._requiredComponents.get(D);if($){let G=this._entityManager.getEntity(j);if(G){let J=G.components[D];for(let{component:X,factory:Z}of $){if(this._entityManager._pendingBatchKeys?.has(X))continue;if(!(X in G.components))this._entityManager.addComponent(j,X,Z(J))}}}}),this._entityManager.onAfterEntityMutated((j)=>{let D=this._entityManager.getEntity(j);if(D)this._reactiveQueryManager.recheckEntityAndChildren(D)}),this._entityManager.onAfterComponentRemoved((j,D)=>{let $=this._entityManager.getEntity(j);if($)this._reactiveQueryManager.onComponentRemoved($,D)}),this._entityManager.onBeforeEntityRemoved((j)=>{this._reactiveQueryManager.onEntityRemoved(j);let D=this._entityScreenScope.get(j);if(D!==void 0)this._entityScreenScope.delete(j),this._screenScopedEntities.get(D)?.delete(j)}),this._entityManager.onAfterParentChanged((j)=>{if(this._reactiveQueryManager.hasParentHasQueries){let D=this._entityManager.getEntity(j);if(D)this._reactiveQueryManager.recheckEntity(D)}})}static create(){return new p}addSystem(j){let D=new C(j,this._currentSystemDefaults);return this._pendingFinalizers.push(()=>{this._registerSystem(D._createSystemObject())}),D}_finalizePendingBuilders(){if(this._pendingFinalizers.length===0)return;this._batchingRegistrations=!0;while(this._pendingFinalizers.length>0){let j=this._pendingFinalizers;this._pendingFinalizers=[];for(let D of j)D()}this._batchingRegistrations=!1,this._rebuildPhaseSystems()}update(j){this._finalizePendingBuilders();let D=this._screenManager?.getCurrentScreen()??null,$=this._diagnosticsEnabled;this._runPhase("preUpdate",j,D,$);let G=$?performance.now():0;this._fixedAccumulator+=j;let J=0;while(this._fixedAccumulator>=this._fixedDt&&J<this._maxFixedSteps)this._executePhase(this._phaseSystems.fixedUpdate,this._fixedDt,D),this._commandBuffer.playback(this),this._fixedAccumulator-=this._fixedDt,J++;if(this._fixedAccumulator>=this._fixedDt)this._fixedAccumulator=0;if($)this._phaseTimings.fixedUpdate=performance.now()-G;this._interpolationAlpha=this._fixedAccumulator/this._fixedDt,this._runPhase("update",j,D,$),this._runPhase("postUpdate",j,D,$);for(let X of this._postUpdateHooks)X({ecs:this,dt:j});this._runPhase("render",j,D,$),this._resourceManager.flushObserved(),this._changeThreshold=this._entityManager.changeSeq,this._currentTick++}_executePhase(j,D,$){for(let G of j){if(!G.process&&!G.onEntityEnter)continue;if(G.groups?.length){let L=!1;for(let W of G.groups)if(this._disabledGroups.has(W)){L=!0;break}if(L)continue}if(G.inScreens?.length){if($===null||!G.inScreens.includes($))continue}if(G.excludeScreens?.length){if($!==null&&G.excludeScreens.includes($))continue}if(G.requiredAssets?.length&&this._assetManager){let L=!0;for(let W of G.requiredAssets)if(!this._assetManager.isLoaded(W)){L=!1;break}if(!L)continue}let J=this._systemLastSeqs.get(G)??0;this._changeThreshold=J;let X=this._systemContexts.get(G);if(!X)X={queries:{},dt:0,ecs:this},this._systemContexts.set(G,X);X.dt=D;let Z=X.queries,F=!1,_=!1;if(G.entityQueries)for(let L in G.entityQueries){_=!0;let W=G.entityQueries[L];if(W){let O=Z[L]??(Z[L]=[]);if(this._entityManager.getEntitiesWithQueryInto(O,W.with,W.without||[],W.changed,W.changed?this._changeThreshold:void 0,W.parentHas),O.length)F=!0}}if(G.entitySingletons){let L=this._singletonScratch;for(let W in G.entitySingletons){_=!0;let Y=G.entitySingletons[W];if(Y){if(this._entityManager.getEntitiesWithQueryInto(L,Y.with,Y.without||[],Y.changed,Y.changed?this._changeThreshold:void 0,Y.parentHas),Z[W]=L[0],L.length)F=!0}}}let Q=this._entityEnterTracking.get(G);if(Q&&G.onEntityEnter)for(let L in G.onEntityEnter){let W=Z[L],Y=Q.get(L);if(!W||!Y)continue;let O=G.onEntityEnter[L];if(!O)continue;let A=this._entityEnterFrameSet;A.clear();for(let K of W)if(A.add(K.id),!Y.has(K.id))Y.add(K.id),O({entity:K,ecs:this});for(let K of Y)if(!A.has(K))Y.delete(K)}if(G.process){if(F||G.runWhenEmpty||!_){let W=this._activeScopeHint;this._activeScopeHint=G.inScreens?.length&&$!==null?$:null;let Y=this._diagnosticsEnabled?performance.now():0;try{G.process(X)}finally{if(this._activeScopeHint=W,this._diagnosticsEnabled)this._systemTimings.set(G.label,performance.now()-Y)}}}let B=G._autoMarkPairs;if(B){let L=this._entityManager;for(let W=0;W<B.length;W++){let Y=B[W];if(!Y)continue;let O=Y.mutates,A=O.length;if(Y.kind==="list"){let K=Z[Y.queryName];if(!K)continue;for(let U=0;U<K.length;U++){let M=K[U];if(!M)continue;for(let q=0;q<A;q++){let h=O[q];if(h!==void 0)L.markChanged(M.id,h)}}}else{let K=Z[Y.queryName];if(!K)continue;for(let U=0;U<A;U++){let M=O[U];if(M!==void 0)L.markChanged(K.id,M)}}}}this._systemLastSeqs.set(G,this._entityManager.changeSeq)}}_runPhase(j,D,$,G){if(G){let J=performance.now();this._executePhase(this._phaseSystems[j],D,$),this._phaseTimings[j]=performance.now()-J}else this._executePhase(this._phaseSystems[j],D,$);this._commandBuffer.playback(this)}async initialize(){if(this._finalizePendingBuilders(),await this.initializeResources(),this._assetManager)this._assetManager.setEventBus(this._eventBus),await this._assetManager.loadEagerAssets(),this._resourceManager.add("$assets",this._assetManager.createResource());if(this._screenManager){let j=this._eventBus;this._screenManager.setDependencies(j,this._assetManager,this),this._resourceManager.add("$screen",this._screenManager.createResource()),j.subscribe("screenExit",({screen:D})=>{let $=this._screenScopedEntities.get(D);if(!$||$.size===0)return;this._screenScopedEntities.delete(D);for(let G of Array.from($))this._entityScreenScope.delete(G),this.removeEntity(G)})}for(let j of this._systems){if(this._systemsInitialized.has(j))continue;this._systemsInitialized.add(j),await j.onInitialize?.(this)}this._initializeFired=!0}async initializeResources(...j){await this._resourceManager.initializeResources(this,...j)}_rebuildPhaseSystems(){for(let j of o)this._phaseSystems[j]=[];for(let j of this._systems){let D=j.phase??"update";this._phaseSystems[D].push(j)}for(let j of o)this._phaseSystems[j].sort((D,$)=>{let G=D.priority??0;return($.priority??0)-G})}updateSystemPriority(j,D){this._finalizePendingBuilders();let $=this._systems.find((G)=>G.label===j);if(!$)return!1;return $.priority=D,this._rebuildPhaseSystems(),!0}updateSystemPhase(j,D){this._finalizePendingBuilders();let $=this._systems.find((G)=>G.label===j);if(!$)return!1;return $.phase=D,this._rebuildPhaseSystems(),!0}get interpolationAlpha(){return this._interpolationAlpha}get fixedDt(){return this._fixedDt}disableSystemGroup(j){this._disabledGroups.add(j)}enableSystemGroup(j){this._disabledGroups.delete(j)}isSystemGroupEnabled(j){return!this._disabledGroups.has(j)}getSystemsInGroup(j){return this._finalizePendingBuilders(),this._systems.filter((D)=>D.groups?.includes(j)).map((D)=>D.label)}removeSystem(j){this._finalizePendingBuilders();let D=this._systems.findIndex((G)=>G.label===j);if(D===-1)return!1;let $=this._systems[D];if(!$)return!1;if($.onDetach)$.onDetach(this);return this._systems.splice(D,1),this._systemLastSeqs.delete($),this._entityEnterTracking.delete($),this._systemsInitialized.delete($),this._rebuildPhaseSystems(),!0}_registerSystem(j){if(this._systems.push(j),this._systemLastSeqs.set(j,this._changeThreshold),!this._batchingRegistrations)this._rebuildPhaseSystems();let D=[];if(j.entityQueries)for(let $ in j.entityQueries){if($===s)continue;let J=j.entityQueries[$]?.mutates;if(J&&J.length>0)D.push({queryName:$,mutates:J,kind:"list"})}if(j.entitySingletons)for(let $ in j.entitySingletons){let J=j.entitySingletons[$]?.mutates;if(J&&J.length>0)D.push({queryName:$,mutates:J,kind:"singleton"})}if(j._autoMarkPairs=D.length>0?D:null,j.onEntityEnter){let $=new Map;for(let G in j.onEntityEnter)$.set(G,new Set);this._entityEnterTracking.set(j,$)}if(j.eventHandlers)for(let $ in j.eventHandlers){let G=j.eventHandlers[$];if(G)this._eventBus.subscribe($,(J)=>{G({data:J,ecs:this})})}if(this._initializeFired&&!this._systemsInitialized.has(j)){this._systemsInitialized.add(j);let $=j.onInitialize?.(this);if($ instanceof Promise)$.catch((G)=>{console.error(`onInitialize for system "${j.label}" rejected:`,G)})}}hasResource(j){return this._resourceManager.has(j)}getResource(j){if(!this._resourceManager.has(j))throw Error(`Resource '${String(j)}' not found. Available resources: [${this.getResourceKeys().map((D)=>String(D)).join(", ")}]`);return this._resourceManager.get(j,this)}tryGetResource(j){let D=j;if(!this._resourceManager.has(D))return;return this._resourceManager.get(D,this)}addResource(j,D){return this._resourceManager.add(j,D),this}removeResource(j){return this._resourceManager.remove(j)}async disposeResource(j){return this._resourceManager.disposeResource(j,this)}async disposeResources(){return this._resourceManager.disposeResources(this)}updateResource(j,D){let $=this.getResource(j),G=D($);return this._resourceManager.add(j,G),this._resourceManager.notifyChange(j,G,$),this}setResource(j,D){let $=this.tryGetResource(j);if(this._resourceManager.add(j,D),$!==void 0)this._resourceManager.notifyChange(j,D,$);return this}onResourceChange(j,D){return this._resourceManager.onResourceChange(j,D)}isResourceObserved(j){return this._resourceManager.isObserved(j)}getResourceKeys(){return this._resourceManager.getKeys()}resourceNeedsInitialization(j){return this._resourceManager.needsInitialization(j)}getEntity(j){return this._entityManager.getEntity(j)}getComponent(j,D){return this._entityManager.getComponent(j,D)}addComponent(j,D,$){this._entityManager.addComponent(j,D,$)}addComponents(j,D){this._entityManager.addComponents(j,D)}removeComponent(j,D){this._entityManager.removeComponent(j,D)}hasComponent(j,D){return this._entityManager.getComponent(j,D)!==void 0}spawn(j,D){let $=this._entityManager.createEntity();return this._entityManager.addComponents($.id,j),this._applyScreenScope($.id,D),$}_getActiveScopeHint(){return this._activeScopeHint}_applyScreenScope(j,D){let $=D?.scope!==void 0?D.scope:this._activeScopeHint;if($===null)return;let G=this._screenScopedEntities.get($)??new Set;G.add(j),this._screenScopedEntities.set($,G),this._entityScreenScope.set(j,$)}getEntitiesWithQuery(j,D=[],$,G){return this._entityManager.getEntitiesWithQuery(j,D,$,$?this._changeThreshold:void 0,G)}getSingleton(j,D=[]){let $=this._entityManager.getEntitiesWithQuery(j,D);if($.length===0)throw Error(`getSingleton: no entity matches query with=[${String(j)}] without=[${String(D)}]`);if($.length>1)throw Error(`getSingleton: expected 1 entity but found ${$.length} matching query with=[${String(j)}] without=[${String(D)}]`);let G=$[0];if(!G)throw Error("getSingleton: unexpected empty result");return G}tryGetSingleton(j,D=[]){let $=this._entityManager.getEntitiesWithQuery(j,D);if($.length===0)return;if($.length>1)throw Error(`tryGetSingleton: expected 0 or 1 entity but found ${$.length} matching query with=[${String(j)}] without=[${String(D)}]`);return $[0]}removeEntity(j,D){return this._entityManager.removeEntity(j,D)}spawnChild(j,D,$){let G=this._entityManager.spawnChild(j,D);return this._emitHierarchyChanged(G.id,null,j),this._applyScreenScope(G.id,$),G}setParent(j,D){let $=this._entityManager.getParent(j);return this._entityManager.setParent(j,D),this._emitHierarchyChanged(j,$,D),this}removeParent(j){let D=this._entityManager.getParent(j),$=this._entityManager.removeParent(j);if($)this._emitHierarchyChanged(j,D,null);return $}getParent(j){return this._entityManager.getParent(j)}getChildren(j){return this._entityManager.getChildren(j)}getChildAt(j,D){return this._entityManager.getChildAt(j,D)}getChildIndex(j,D){return this._entityManager.getChildIndex(j,D)}getAncestors(j){return this._entityManager.getAncestors(j)}getDescendants(j){return this._entityManager.getDescendants(j)}getRoot(j){return this._entityManager.getRoot(j)}getSiblings(j){return this._entityManager.getSiblings(j)}isDescendantOf(j,D){return this._entityManager.isDescendantOf(j,D)}isAncestorOf(j,D){return this._entityManager.isAncestorOf(j,D)}getRootEntities(){return this._entityManager.getRootEntities()}forEachInHierarchy(j,D){this._entityManager.forEachInHierarchy(j,D)}hierarchyIterator(j){return this._entityManager.hierarchyIterator(j)}_emitHierarchyChanged(j,D,$){this._eventBus.publish("hierarchyChanged",{entityId:j,oldParent:D,newParent:$})}get installedPlugins(){return Array.from(this._installedPlugins)}get entityManager(){return this._entityManager}get eventBus(){return this._finalizePendingBuilders(),this._eventBus}get commands(){return this._commandBuffer}get currentTick(){return this._currentTick}get changeThreshold(){return this._changeThreshold}enableDiagnostics(j){if(this._diagnosticsEnabled=j,!j)this._systemTimings.clear(),this._phaseTimings={preUpdate:0,fixedUpdate:0,update:0,postUpdate:0,render:0}}get diagnosticsEnabled(){return this._diagnosticsEnabled}get systemTimings(){return this._systemTimings}get phaseTimings(){return this._phaseTimings}get entityCount(){return this._entityManager.entityCount}mutateComponent(j,D,$){let G=this._entityManager.getComponent(j,D);if(G===void 0)throw Error(`Entity ${j} does not have component "${String(D)}"`);return $(G),this._entityManager.markChanged(j,D),G}markChanged(j,D){this._entityManager.markChanged(j,D)}registerDispose(j,D){this._entityManager.registerDispose(j,D)}registerRequired(j,D,$){if(String(j)===String(D))throw Error(`Cannot require a component to depend on itself: '${String(j)}'`);let G=this._requiredComponents.get(j)??[];if(G.some((J)=>J.component===D))throw Error(`Required component '${String(D)}' already registered for trigger '${String(j)}'`);this._checkRequiredCycle(j,D),G.push({component:D,factory:$}),this._requiredComponents.set(j,G)}_checkRequiredCycle(j,D){i(j,D,($)=>this._requiredComponents.get($))}onComponentAdded(j,D){return this._entityManager.onComponentAdded(j,D)}onComponentRemoved(j,D){return this._entityManager.onComponentRemoved(j,D)}addReactiveQuery(j,D){this._reactiveQueryManager.addQuery(j,D)}removeReactiveQuery(j){return this._reactiveQueryManager.removeQuery(j)}on(j,D){return this._eventBus.subscribe(j,D)}off(j,D){return this._eventBus.unsubscribe(j,D)}onPostUpdate(j){return this._postUpdateHooks.push(j),()=>{let D=this._postUpdateHooks.indexOf(j);if(D!==-1)this._postUpdateHooks.splice(D,1)}}requireAssetManager(){if(!this._assetManager)throw Error("Asset manager not configured. Use withAssets() in builder.");return this._assetManager}getAsset(j){return this.requireAssetManager().get(j)}tryGetAsset(j){return this._assetManager?.tryGet(j)}getAssetHandle(j){return this.requireAssetManager().getHandle(j)}isAssetLoaded(j){return this._assetManager?.isLoaded(j)??!1}async loadAsset(j){return this.requireAssetManager().loadAsset(j)}async loadAssetGroup(j){return this.requireAssetManager().loadAssetGroup(j)}isAssetGroupLoaded(j){return this._assetManager?.isGroupLoaded(j)??!1}getAssetGroupProgress(j){return this._assetManager?.getGroupProgress(j)??0}requireScreenManager(){if(!this._screenManager)throw Error("Screen manager not configured. Use withScreens() in builder.");return this._screenManager}async setScreen(j,D){return this.requireScreenManager().setScreen(j,D)}async pushScreen(j,D){return this.requireScreenManager().pushScreen(j,D)}async popScreen(){return this.requireScreenManager().popScreen()}getCurrentScreen(){return this._screenManager?.getCurrentScreen()??null}getScreenConfig(j){return this.requireScreenManager().getConfig(j)}tryGetScreenConfig(j){return this._screenManager?.tryGetConfig(j)??void 0}getScreenState(j){return this.requireScreenManager().getState(j)}tryGetScreenState(j){return this._screenManager?.tryGetState(j)??void 0}updateScreenState(j,D){if(typeof j==="string")this.requireScreenManager().updateState(D,j);else this.requireScreenManager().updateState(j)}isCurrentScreen(j){return this._screenManager?.isCurrent(j)??!1}isScreenActive(j){return this._screenManager?.isActive(j)??!1}getScreenStackDepth(){return this._screenManager?.getStackDepth()??0}onScreenEnter(j,D){let $=this._eventBus,G=(Z)=>{if(Z.screen!==j)return;D({config:Z.config,ecs:this})},J=$.subscribe("screenEnter",G),X=$.subscribe("screenPush",G);return()=>{J(),X()}}onScreenExit(j,D){return this._eventBus.subscribe("screenExit",(G)=>{if(G.screen!==j)return;D({ecs:this})})}_setAssetManager(j){this._assetManager=j;for(let[D,$]of this._pendingPluginAssets)this._assetManager.register(D,$);this._pendingPluginAssets=[]}_setScreenManager(j){this._screenManager=j;for(let[D,$]of this._pendingPluginScreens)this._screenManager.register(D,$);this._pendingPluginScreens=[]}_hasPendingPluginAssets(){return this._pendingPluginAssets.length>0}_hasPendingPluginScreens(){return this._pendingPluginScreens.length>0}_setFixedDt(j){this._fixedDt=j}_registerAsset(j,D){this._pendingPluginAssets.push([j,D])}_registerScreen(j,D){this._pendingPluginScreens.push([j,D])}installPlugin(j){return this._installPluginUnchecked(j)}_installPluginUnchecked(j){if(this._installedPlugins.has(j.id))return this;this._installedPlugins.add(j.id);let D=[];this._pluginCleanups.set(j.id,D);let $=(J)=>{D.push(J)},G=this._currentSystemDefaults;this._currentSystemDefaults=j.systemDefaults;try{j.install(this,$)}finally{this._currentSystemDefaults=G}return this}uninstallPlugin(j){if(!this._installedPlugins.has(j))return!1;let D=this._pluginCleanups.get(j);if(this._pluginCleanups.delete(j),this._installedPlugins.delete(j),D)for(let $=D.length-1;$>=0;$--){let G=D[$];if(!G)continue;try{G()}catch(J){console.warn(`Plugin '${j}' cleanup threw:`,J)}}return!0}dispose(){let j=Array.from(this._installedPlugins);for(let D=j.length-1;D>=0;D--){let $=j[D];if($!==void 0)this.uninstallPlugin($)}}pluginFactory(){return(j)=>V(j.id).install(j.install)}getHelpers(j){return j(this)}}function vj(j){return j}function bj(j,D){return{x:j,y:D}}function pj(){return{x:0,y:0}}function hj(j,D){return{x:j.x+D.x,y:j.y+D.y}}function kj(j,D){return{x:j.x-D.x,y:j.y-D.y}}function Ij(j,D){return{x:j.x*D,y:j.y*D}}function uj(j){return{x:-j.x,y:-j.y}}function mj(j,D){return j.x*D.x+j.y*D.y}function lj(j,D){return j.x*D.y-j.y*D.x}function sj(j){return j.x*j.x+j.y*j.y}function ij(j){return Math.sqrt(j.x*j.x+j.y*j.y)}function cj(j){let D=Math.sqrt(j.x*j.x+j.y*j.y);if(D===0)return{x:0,y:0};return{x:j.x/D,y:j.y/D}}function dj(j,D){let $=j.x-D.x,G=j.y-D.y;return $*$+G*G}function yj(j,D){let $=j.x-D.x,G=j.y-D.y;return Math.sqrt($*$+G*G)}function oj(j,D,$=0.0000000001){return Math.abs(j.x-D.x)<=$&&Math.abs(j.y-D.y)<=$}function rj(j,D,$){return{x:j,y:D,z:$}}function aj(){return{x:0,y:0,z:0}}function nj(j,D){return{x:j.x+D.x,y:j.y+D.y,z:j.z+D.z}}function tj(j,D){return{x:j.x-D.x,y:j.y-D.y,z:j.z-D.z}}function ej(j,D){return{x:j.x*D,y:j.y*D,z:j.z*D}}function j3(j){return{x:-j.x,y:-j.y,z:-j.z}}function D3(j,D){return j.x*D.x+j.y*D.y+j.z*D.z}function $3(j,D){return{x:j.y*D.z-j.z*D.y,y:j.z*D.x-j.x*D.z,z:j.x*D.y-j.y*D.x}}function G3(j){return j.x*j.x+j.y*j.y+j.z*j.z}function J3(j){return Math.sqrt(j.x*j.x+j.y*j.y+j.z*j.z)}function X3(j){let D=Math.sqrt(j.x*j.x+j.y*j.y+j.z*j.z);if(D===0)return{x:0,y:0,z:0};return{x:j.x/D,y:j.y/D,z:j.z/D}}function Z3(j,D){let $=j.x-D.x,G=j.y-D.y,J=j.z-D.z;return $*$+G*G+J*J}function W3(j,D){let $=j.x-D.x,G=j.y-D.y,J=j.z-D.z;return Math.sqrt($*$+G*G+J*J)}function Y3(j,D,$=0.0000000001){return Math.abs(j.x-D.x)<=$&&Math.abs(j.y-D.y)<=$&&Math.abs(j.z-D.z)<=$}var M3=P;export{aj as vec3Zero,tj as vec3Sub,ej as vec3Scale,X3 as vec3Normalize,j3 as vec3Negate,G3 as vec3LengthSq,J3 as vec3Length,Y3 as vec3Equals,D3 as vec3Dot,Z3 as vec3DistanceSq,W3 as vec3Distance,$3 as vec3Cross,nj as vec3Add,rj as vec3,pj as vec2Zero,kj as vec2Sub,Ij as vec2Scale,cj as vec2Normalize,uj as vec2Negate,sj as vec2LengthSq,ij as vec2Length,oj as vec2Equals,mj as vec2Dot,dj as vec2DistanceSq,yj as vec2Distance,lj as vec2Cross,hj as vec2Add,bj as vec2,r as directValue,V as definePlugin,M3 as default,b as createScreenConfigurator,vj as createQueryDefinition,N as createAssetConfigurator,C as SystemBuilder,H as ScreenManager,z as AssetManager};
|
|
1
|
+
var $j=((j)=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(j,{get:(D,$)=>(typeof require<"u"?require:D)[$]}):j)(function(j){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+j+'" is not supported')});class H{parentMap=new Map;childrenMap=new Map;_bfsQueue=[];setParent(j,D){if(j===D)throw Error(`Cannot set entity ${j} as its own parent`);if(this.wouldCreateCycle(j,D))throw Error("Cannot set parent: would create circular reference");let $=this.parentMap.get(j);if($!==void 0){let J=this.childrenMap.get($);if(J){let X=J.indexOf(j);if(X!==-1)J.splice(X,1)}}this.parentMap.set(j,D);let G=this.childrenMap.get(D);if(G)G.push(j);else this.childrenMap.set(D,[j]);return this}removeParent(j){let D=this.parentMap.get(j);if(D===void 0)return!1;let $=this.childrenMap.get(D);if($){let G=$.indexOf(j);if(G!==-1)$.splice(G,1)}return this.parentMap.delete(j),!0}getParent(j){return this.parentMap.get(j)??null}getChildren(j){let D=this.childrenMap.get(j);return D?[...D]:[]}getChildAt(j,D){if(D<0)return null;let $=this.childrenMap.get(j);if(!$||D>=$.length)return null;return $[D]??null}getChildIndex(j,D){let $=this.childrenMap.get(j);if(!$)return-1;return $.indexOf(D)}removeEntity(j){let D=this.parentMap.get(j)??null;if(D!==null){let J=this.childrenMap.get(D);if(J){let X=J.indexOf(j);if(X!==-1)J.splice(X,1)}}this.parentMap.delete(j);let $=this.childrenMap.get(j)??[],G=[...$];for(let J of $)this.parentMap.delete(J);return this.childrenMap.delete(j),{oldParent:D,orphanedChildren:G}}getAncestors(j){let D=[],$=this.parentMap.get(j);while($!==void 0)D.push($),$=this.parentMap.get($);return D}getDescendants(j){let D=[],$=this.childrenMap.get(j);if(!$)return D;let G=$.slice().reverse();while(G.length>0){let J=G.pop();D.push(J);let X=this.childrenMap.get(J);if(X)for(let Z=X.length-1;Z>=0;Z--)G.push(X[Z])}return D}getRoot(j){let D=j,$=this.parentMap.get(D);while($!==void 0)D=$,$=this.parentMap.get(D);return D}getSiblings(j){let D=this.parentMap.get(j);if(D===void 0)return[];let $=this.childrenMap.get(D);if(!$)return[];return $.filter((G)=>G!==j)}isDescendantOf(j,D){if(j===D)return!1;let $=this.parentMap.get(j);while($!==void 0){if($===D)return!0;$=this.parentMap.get($)}return!1}isAncestorOf(j,D){return this.isDescendantOf(D,j)}get hasHierarchy(){return this.childrenMap.size>0}getRootEntities(){let j=[];for(let D of this.childrenMap.keys())if(!this.parentMap.has(D))j.push(D);return j}wouldCreateCycle(j,D){let $=D;while($!==void 0){if($===j)return!0;$=this.parentMap.get($)}return!1}forEachInHierarchy(j,D){let $=D?.roots??this.getRootEntities(),G=this._bfsQueue;G.length=0;for(let J of $)G.push(J,-1,0);for(let J=0;J<G.length;J+=3){let X=G[J],Z=G[J+1],W=G[J+2];j(X,Z===-1?null:Z,W);let A=this.childrenMap.get(X);if(A){let L=W+1;for(let B of A)G.push(B,X,L)}}}*hierarchyIterator(j){let D=j?.roots??this.getRootEntities(),$=[];for(let G of D)$.push({entityId:G,parentId:null,depth:0});for(let G of $){yield G;let J=this.childrenMap.get(G.entityId);if(J)for(let X of J)$.push({entityId:X,parentId:G.entityId,depth:G.depth+1})}}}function R(j,D,$,G,J){let X=j.components;for(let Z of D)if(!(Z in X))return!1;if($){for(let Z of $)if(Z in X)return!1}if(G&&G.length>0){let Z=J.getParent(j.id);if(Z===null)return!1;let W=J.getEntity(Z);if(!W)return!1;let A=W.components;for(let L of G)if(!(L in A))return!1}return!0}function a(j,D,$){let G=j.length===0?"":[...j].map(String).sort().join(","),J=D.length===0?"":[...D].map(String).sort().join(","),X=$.length===0?"":[...$].map(String).sort().join(",");return`${G}|${J}|${X}`}class S{host;caches=new Map;byComp=new Map;byParentComp=new Map;constructor(j){this.host=j}getOrCreate(j,D,$){let G=a(j,D,$),J=this.caches.get(G);if(J)return J.members;let X={with:[...j],without:[...D],parentHas:[...$],members:new Set};this.caches.set(G,X);for(let Z of X.with)v(this.byComp,Z,X);for(let Z of X.without)v(this.byComp,Z,X);for(let Z of X.parentHas)v(this.byParentComp,Z,X);return this.populate(X),X.members}get cacheCount(){return this.caches.size}populate(j){let D=this.host,$=j.with;if($.length===0){for(let Z of D.allEntities())if(this.matches(Z,j))j.members.add(Z.id);return}let G=$[0];if(G===void 0)return;let J=D.componentIndex(G)?.size??0;for(let Z=1;Z<$.length;Z++){let W=$[Z];if(W===void 0)continue;let A=D.componentIndex(W)?.size??0;if(A<J)G=W,J=A}let X=D.componentIndex(G);if(!X||X.size===0)return;for(let Z of X){let W=D.getEntity(Z);if(!W)continue;if(this.matches(W,j))j.members.add(Z)}}matches(j,D){return R(j,D.with,D.without,D.parentHas,this.host)}reeval(j,D){let $=this.host.getEntity(j);if(!$){D.members.delete(j);return}if(this.matches($,D))D.members.add(j);else D.members.delete(j)}onComponentChanged(j,D){let $=this.byComp.get(D);if($)for(let J of $)this.reeval(j,J);let G=this.byParentComp.get(D);if(G&&G.length>0){let J=this.host.getChildren(j);if(J.length>0)for(let X of G)for(let Z of J)this.reeval(Z,X)}}onParentChanged(j){for(let D of this.caches.values())if(D.parentHas.length>0)this.reeval(j,D)}onEntityRemoved(j){let D=!1;for(let G of this.caches.values())if(G.members.delete(j),G.parentHas.length>0)D=!0;if(!D)return;let $=this.host.getChildren(j);if($.length===0)return;for(let G of this.caches.values()){if(G.parentHas.length===0)continue;for(let J of $)G.members.delete(J)}}}function v(j,D,$){let G=j.get(D);if(G)G.push($);else j.set(D,[$])}function m(j,D,$){if(!j)return!1;for(let G of D)if((j.get(G)??-1)>$)return!0;return!1}class N{callbacks=[];_iterDepth=0;_pendingRemovals=[];add(j){this.callbacks.push(j)}remove(j){if(this._iterDepth>0){this._pendingRemovals.push(j);return}let D=this.callbacks.indexOf(j);if(D!==-1)this.callbacks.splice(D,1)}invoke(j){this._iterDepth++;let D=this.callbacks.length;for(let $=0;$<D;$++){let G=this.callbacks[$];if(G)G(j)}if(this._iterDepth--,this._iterDepth===0&&this._pendingRemovals.length>0){for(let $ of this._pendingRemovals){let G=this.callbacks.indexOf($);if(G!==-1)this.callbacks.splice(G,1)}this._pendingRemovals.length=0}}}class T{nextId=1;entities=new Map;componentIndices=new Map;addedCallbacks=new Map;removedCallbacks=new Map;hierarchyManager=new H;disposeCallbacks=new Map;changeSeqs=new Map;_changeSeq=0;_afterComponentAddedHooks=[];_afterEntityMutatedHooks=[];_afterComponentRemovedHooks=[];_beforeEntityRemovedHooks=[];_afterParentChangedHooks=[];_queryCache=new S({getEntity:(j)=>this.entities.get(j),getParent:(j)=>this.hierarchyManager.getParent(j),getChildren:(j)=>this.hierarchyManager.getChildren(j),allEntities:()=>this.entities.values(),componentIndex:(j)=>this.componentIndices.get(j)});_batchingDepth=0;_batchedEntityIds=new Set;_pendingBatchKeys=null;get entityCount(){return this.entities.size}createEntity(){let j=this.nextId++,D={id:j,components:{}};return this.entities.set(j,D),D}registerDispose(j,D){this.disposeCallbacks.set(j,D)}getDisposeCallbacks(){return this.disposeCallbacks}invokeDispose(j,D,$){let G=this.disposeCallbacks.get(j);if(!G)return;try{G({value:D,entityId:$})}catch(J){console.warn(`Component dispose callback for '${String(j)}' threw:`,J)}}addComponent(j,D,$){let G=this.entities.get(j);if(!G)throw Error(`Cannot add component '${String(D)}': Entity with ID ${j} does not exist`);let J=G.components[D];if(J!==void 0)this.invokeDispose(D,J,G.id);if(G.components[D]=$,!this.componentIndices.has(D))this.componentIndices.set(D,new Set);this.componentIndices.get(D)?.add(G.id);let X=this.addedCallbacks.get(D);if(X)X.invoke({value:$,entity:G});this._queryCache.onComponentChanged(G.id,D),this._batchingDepth++;for(let Z of this._afterComponentAddedHooks)Z(G.id,D);if(this._batchedEntityIds.add(G.id),this._batchingDepth--,this._batchingDepth===0){for(let Z of this._batchedEntityIds)for(let W of this._afterEntityMutatedHooks)W(Z);this._batchedEntityIds.clear()}return this}addComponents(j,D){let $=this.entities.get(j);if(!$)throw Error(`Cannot add components: Entity with ID ${j} does not exist`);let G=this._pendingBatchKeys;this._pendingBatchKeys=new Set(Object.keys(D)),this._batchingDepth++;for(let J in D)this.addComponent($.id,J,D[J]);if(this._batchingDepth--,this._pendingBatchKeys=G,this._batchingDepth===0){for(let J of this._batchedEntityIds)for(let X of this._afterEntityMutatedHooks)X(J);this._batchedEntityIds.clear()}return this}removeComponent(j,D){let $=this.entities.get(j);if(!$)throw Error(`Cannot remove component '${String(D)}': Entity with ID ${j} does not exist`);let G=$.components[D];if(G!==void 0)this.invokeDispose(D,G,$.id);delete $.components[D];let J=this.removedCallbacks.get(D);if(J&&G!==void 0)J.invoke({value:G,entity:$});if(this.componentIndices.get(D)?.delete($.id),G!==void 0){this._queryCache.onComponentChanged($.id,D);for(let X of this._afterComponentRemovedHooks)X($.id,D)}return this}getComponent(j,D){return this.entities.get(j)?.components[D]}getEntitiesWithQuery(j=[],D=[],$,G,J){return this.getEntitiesWithQueryInto([],j,D,$,G,J)}getEntitiesWithQueryInto(j,D=[],$=[],G,J,X){j.length=0;let Z=G!==void 0&&G.length>0&&J!==void 0,W=X!==void 0&&X.length>0;if(D.length===0&&$.length===0&&!W){if(!Z){for(let L of this.entities.values())j.push(L);return j}for(let L of this.entities.values()){if(!m(this.changeSeqs.get(L.id),G,J))continue;j.push(L)}return j}let A=this._queryCache.getOrCreate(D,$,X??[]);if(A.size===0)return j;if(Z){for(let L of A){if(!m(this.changeSeqs.get(L),G,J))continue;let B=this.entities.get(L);if(!B)continue;j.push(B)}return j}for(let L of A){let B=this.entities.get(L);if(!B)continue;j.push(B)}return j}get _queryCacheForTesting(){return this._queryCache}removeEntity(j,D){let $=this.entities.get(j);if(!$)return!1;if(D?.cascade??!0){let J=this.hierarchyManager.getDescendants($.id);for(let X=J.length-1;X>=0;X--){let Z=J[X];if(Z===void 0)continue;this._queryCache.onEntityRemoved(Z);for(let W of this._beforeEntityRemovedHooks)W(Z)}this._queryCache.onEntityRemoved($.id);for(let X of this._beforeEntityRemovedHooks)X($.id);for(let X=J.length-1;X>=0;X--){let Z=J[X];if(Z===void 0)continue;this.removeEntityInternal(Z)}}else{this._queryCache.onEntityRemoved($.id);for(let J of this._beforeEntityRemovedHooks)J($.id)}return this.removeEntityInternal($.id)}removeEntityInternal(j){let D=this.entities.get(j);if(!D)return!1;this.hierarchyManager.removeEntity(j);for(let $ of Object.keys(D.components)){let G=D.components[$];if(G!==void 0){this.invokeDispose($,G,D.id);let J=this.removedCallbacks.get($);if(J)J.invoke({value:G,entity:D})}this.componentIndices.get($)?.delete(D.id)}return this.changeSeqs.delete(D.id),this.entities.delete(D.id)}getEntity(j){return this.entities.get(j)}onComponentAdded(j,D){let $=D,G=this.addedCallbacks.get(j);if(!G)G=new N,this.addedCallbacks.set(j,G);return G.add($),()=>{this.addedCallbacks.get(j)?.remove($)}}onComponentRemoved(j,D){let $=D,G=this.removedCallbacks.get(j);if(!G)G=new N,this.removedCallbacks.set(j,G);return G.add($),()=>{this.removedCallbacks.get(j)?.remove($)}}onAfterComponentAdded(j){return this._afterComponentAddedHooks.push(j),()=>{let D=this._afterComponentAddedHooks.indexOf(j);if(D!==-1)this._afterComponentAddedHooks.splice(D,1)}}onAfterEntityMutated(j){return this._afterEntityMutatedHooks.push(j),()=>{let D=this._afterEntityMutatedHooks.indexOf(j);if(D!==-1)this._afterEntityMutatedHooks.splice(D,1)}}onAfterComponentRemoved(j){return this._afterComponentRemovedHooks.push(j),()=>{let D=this._afterComponentRemovedHooks.indexOf(j);if(D!==-1)this._afterComponentRemovedHooks.splice(D,1)}}onBeforeEntityRemoved(j){return this._beforeEntityRemovedHooks.push(j),()=>{let D=this._beforeEntityRemovedHooks.indexOf(j);if(D!==-1)this._beforeEntityRemovedHooks.splice(D,1)}}onAfterParentChanged(j){return this._afterParentChangedHooks.push(j),()=>{let D=this._afterParentChangedHooks.indexOf(j);if(D!==-1)this._afterParentChangedHooks.splice(D,1)}}get changeSeq(){return this._changeSeq}markChanged(j,D){let $=++this._changeSeq,G=this.changeSeqs.get(j);if(!G)G=new Map,this.changeSeqs.set(j,G);G.set(D,$)}getChangeSeq(j,D){return this.changeSeqs.get(j)?.get(D)??-1}spawnChild(j,D){let $=this.createEntity();return this.addComponents($.id,D),this.setParent($.id,j),$}setParent(j,D){this.hierarchyManager.setParent(j,D),this._queryCache.onParentChanged(j);for(let $ of this._afterParentChangedHooks)$(j);return this}removeParent(j){let D=this.hierarchyManager.removeParent(j);if(D){this._queryCache.onParentChanged(j);for(let $ of this._afterParentChangedHooks)$(j)}return D}getParent(j){return this.hierarchyManager.getParent(j)}getChildren(j){return this.hierarchyManager.getChildren(j)}getChildAt(j,D){return this.hierarchyManager.getChildAt(j,D)}getChildIndex(j,D){return this.hierarchyManager.getChildIndex(j,D)}getAncestors(j){return this.hierarchyManager.getAncestors(j)}getDescendants(j){return this.hierarchyManager.getDescendants(j)}getRoot(j){return this.hierarchyManager.getRoot(j)}getSiblings(j){return this.hierarchyManager.getSiblings(j)}isDescendantOf(j,D){return this.hierarchyManager.isDescendantOf(j,D)}isAncestorOf(j,D){return this.hierarchyManager.isAncestorOf(j,D)}get hasHierarchy(){return this.hierarchyManager.hasHierarchy}getRootEntities(){return this.hierarchyManager.getRootEntities()}forEachInHierarchy(j,D){this.hierarchyManager.forEachInHierarchy(j,D)}hierarchyIterator(j){return this.hierarchyManager.hierarchyIterator(j)}}class x{handlers=new Map;subscribe(j,D){return this.addHandler(j,D,!1)}once(j,D){return this.addHandler(j,D,!0)}unsubscribe(j,D){let $=this.handlers.get(j);if(!$)return!1;let G=$.findIndex((J)=>J.callback===D);if(G===-1)return!1;return $.splice(G,1),!0}addHandler(j,D,$){let G=this.handlers.get(j);if(!G)G=[],this.handlers.set(j,G);let J={callback:D,once:$};return G.push(J),()=>{let X=this.handlers.get(j);if(X){let Z=X.indexOf(J);if(Z!==-1)X.splice(Z,1)}}}publish(...[j,D]){let $=this.handlers.get(j);if(!$||$.length===0)return;let G=!1,J=$.length;for(let X=0;X<J&&X<$.length;X++){let Z=$[X];if(!Z)continue;if(Z.callback(D),Z.once)G=!0}if(G){for(let X=$.length-1;X>=0;X--)if($[X]?.once)$.splice(X,1)}}clear(){this.handlers.clear()}clearEvent(j){this.handlers.delete(j)}}var p=Symbol("resource-direct");function n(j){return{[p]:j}}function b(j){if(typeof j==="object"&&j!==null&&!Array.isArray(j))return{...j};return{$value:j}}function t(j,D){if(typeof j==="object"&&j!==null&&!Array.isArray(j)){let $=j;for(let G in D)if(!Object.is($[G],D[G]))return!0;return!1}return!Object.is(j,D.$value)}function e(j){return typeof j==="object"&&j!==null&&"factory"in j&&typeof j.factory==="function"}function jj(j){return typeof j==="object"&&j!==null&&p in j}function l(j,D){let $=[],G=new Set,J=new Set;function X(Z,W=[]){if(G.has(Z))return;if(J.has(Z))throw Error(`Circular resource dependency: ${[...W,Z].join(" -> ")}`);J.add(Z);for(let A of D(Z)){let L=j.find((B)=>B===A);if(L)X(L,[...W,Z])}J.delete(Z),G.add(Z),$.push(Z)}for(let Z of j)X(Z);return $}class w{resources=new Map;resourceFactories=new Map;resourceDependencies=new Map;resourceDisposers=new Map;initializedResourceKeys=new Set;_changeSubscribers=new Map;_observedSnapshots=new Map;add(j,D){let $=(G)=>{this.resources.set(j,G),this.initializedResourceKeys.add(j),this.resourceDependencies.set(j,[])};if(e(D)){if(this.resourceFactories.set(j,D.factory),this.resourceDependencies.set(j,D.dependsOn??[]),D.onDispose)this.resourceDisposers.set(j,D.onDispose)}else if(jj(D))$(D[p]);else if(typeof D==="function")this.resourceFactories.set(j,D),this.resourceDependencies.set(j,[]);else $(D);return this}tryGet(j,...D){if(!this.has(j))return;return this.get(j,...D)}get(j,...D){let $=this.resources.get(j);if($!==void 0)return $;let G=this.resourceFactories.get(j);if(G===void 0)throw Error(`Resource ${String(j)} not found`);let J=D[0],X=G(J);if(!(X instanceof Promise))this.resources.set(j,X),this.initializedResourceKeys.add(j);return X}has(j){return this.resources.has(j)||this.resourceFactories.has(j)}remove(j){let D=this.resources.delete(j),$=this.resourceFactories.delete(j);return this.resourceDependencies.delete(j),this.resourceDisposers.delete(j),this.initializedResourceKeys.delete(j),D||$}getKeys(){let j=new Set([...this.resources.keys(),...this.resourceFactories.keys()]);return Array.from(j)}needsInitialization(j){return this.resourceFactories.has(j)&&!this.initializedResourceKeys.has(j)}getPendingInitializationKeys(){return Array.from(this.resourceFactories.keys()).filter((j)=>!this.initializedResourceKeys.has(j))}async initializeResource(j,...D){if(!this.resourceFactories.has(j)||this.initializedResourceKeys.has(j))return;let $=this.resourceFactories.get(j);if(!$)return;let G=D[0],J=await $(G);this.resources.set(j,J),this.initializedResourceKeys.add(j),this.resourceFactories.delete(j)}async initializeResources(...j){let D=j.slice(1),$=D.length===0?this.getPendingInitializationKeys():D;if($.length===0)return;let G=l($,(J)=>[...this.resourceDependencies.get(J)??[]]);for(let J of G)await this.initializeResource(J,...j.slice(0,1))}getDependencies(j){return this.resourceDependencies.get(j)??[]}async disposeResource(j,...D){if(!this.resources.has(j)&&!this.resourceFactories.has(j))return!1;if(this.initializedResourceKeys.has(j)){let $=this.resourceDisposers.get(j),G=this.resources.get(j);if($&&G!==void 0){let J=D[0];await $(G,J)}}return this.resources.delete(j),this.resourceFactories.delete(j),this.resourceDependencies.delete(j),this.resourceDisposers.delete(j),this.initializedResourceKeys.delete(j),this._changeSubscribers.delete(j),!0}onResourceChange(j,D){let $=this._changeSubscribers.get(j),G=$??new Set;if(!$){this._changeSubscribers.set(j,G);let X=this.resources.get(j);this._observedSnapshots.set(j,b(X))}let J=D;return G.add(J),()=>{if(G.delete(J),G.size===0)this._changeSubscribers.delete(j),this._observedSnapshots.delete(j)}}notifyChange(j,D,$){if(Object.is(D,$))return;let G=this._changeSubscribers.get(j);if(!G||G.size===0)return;if(this._observedSnapshots.has(j))this._observedSnapshots.set(j,b(D));let J=[...G];for(let X of J)X(D,$)}isObserved(j){return this._observedSnapshots.has(j)}flushObserved(){if(this._observedSnapshots.size===0)return;for(let[j,D]of this._observedSnapshots){let $=this.resources.get(j);if(!t($,D))continue;let G="$value"in D?D.$value:D,J=b($),X=this._changeSubscribers.get(j);for(let Z of X)Z($,G);this._observedSnapshots.set(j,J)}}async disposeResources(...j){let D=Array.from(this.initializedResourceKeys);if(D.length===0)return;let $=l(D,(G)=>[...this.resourceDependencies.get(G)??[]]).reverse();for(let G of $)await this.disposeResource(G,...j)}}class q{queries=new Map;entityManager;_hasParentHasQueries=!1;constructor(j){this.entityManager=j}get hasParentHasQueries(){return this._hasParentHasQueries}addQuery(j,D){let $={definition:D,matchingEntities:new Set};if(this.queries.set(j,$),D.parentHas?.length)this._hasParentHasQueries=!0;let G=this.entityManager.getEntitiesWithQuery(D.with,D.without??[]);for(let J of G)if(this.entityMatchesQuery(J,$.definition))$.matchingEntities.add(J.id),$.definition.onEnter?.(J)}removeQuery(j){let D=this.queries.delete(j);if(D)this._recalcParentHasFlag();return D}entityMatchesQuery(j,D){return R(j,D.with,D.without,D.parentHas,this.entityManager)}_applyQueryTransition(j,D){let $=D.matchingEntities.has(j.id),G=this.entityMatchesQuery(j,D.definition);if(!$&&G)D.matchingEntities.add(j.id),D.definition.onEnter?.(j);else if($&&!G)D.matchingEntities.delete(j.id),D.definition.onExit?.(j.id)}onComponentAdded(j,D){for(let[,$]of this.queries)this._applyQueryTransition(j,$);if(this._hasParentHasQueries)this._recheckChildren(j.id)}onComponentRemoved(j,D){for(let[,$]of this.queries)this._applyQueryTransition(j,$);if(this._hasParentHasQueries)this._recheckChildren(j.id)}onEntityRemoved(j){for(let[D,$]of this.queries)if($.matchingEntities.has(j))$.matchingEntities.delete(j),$.definition.onExit?.(j)}recheckEntity(j){for(let[,D]of this.queries)this._applyQueryTransition(j,D)}recheckEntityAndChildren(j){if(this.recheckEntity(j),this._hasParentHasQueries)this._recheckChildren(j.id)}_recheckChildren(j){let D=this.entityManager.getChildren(j);for(let $ of D){let G=this.entityManager.getEntity($);if(G)this.recheckEntity(G)}}_recalcParentHasFlag(){this._hasParentHasQueries=!1;for(let[,j]of this.queries)if(j.definition.parentHas?.length){this._hasParentHasQueries=!0;return}}}class C{parent;commands=[];constructor(j){this.parent=j}removeEntity(j,D){this.commands.push(($)=>{$.removeEntity(j,D)})}addComponent(j,D,$){this.commands.push((G)=>{G.addComponent(j,D,$)})}removeComponent(j,D){this.commands.push(($)=>{$.removeComponent(j,D)})}spawn(j,D){let $=this._resolveScope(D);this.commands.push((G)=>{G.spawn(j,$)})}spawnChild(j,D,$){let G=this._resolveScope($);this.commands.push((J)=>{J.spawnChild(j,D,G)})}_resolveScope(j){if(j?.scope!==void 0)return j;let D=this.parent?._getActiveScopeHint();if(!D)return j;return{scope:D}}addComponents(j,D){this.commands.push(($)=>{$.addComponents(j,D)})}setParent(j,D){this.commands.push(($)=>{$.setParent(j,D)})}mutateComponent(j,D,$){this.commands.push((G)=>{G.mutateComponent(j,D,$)})}markChanged(j,D){this.commands.push(($)=>{$.markChanged(j,D)})}removeParent(j){this.commands.push((D)=>{D.removeParent(j)})}playback(j){for(let D of this.commands)try{D(j)}catch($){console.warn("CommandBuffer: Command failed during playback:",$)}this.commands.length=0}clear(){this.commands.length=0}get length(){return this.commands.length}}class s{_id;constructor(j){this._id=j}_systemDefaults;setSystemDefaults(j){return this._systemDefaults=j,this}withComponentTypes(){return this}withEventTypes(){return this}withResourceTypes(){return this}withAssetTypes(){return this}withScreenTypes(){return this}withLabels(){return this}withGroups(){return this}withAssetGroupNames(){return this}withReactiveQueryNames(){return this}requires(){return this}install(j){return{id:this._id,install:j,...this._systemDefaults?{systemDefaults:this._systemDefaults}:{}}}}function E(j){return new s(j)}var c="__each";class g{_label;queries={};singletons={};processFunction;detachFunction;initializeFunction;eventHandlers;_priority=0;_phase="update";_groups=[];_inScreens;_excludeScreens;_requiredAssets;_runWhenEmpty=!1;_entityEnterHandlers={};_resourceKeys;constructor(j,D){this._label=j;if(D){if(D.phase!==void 0)this._phase=D.phase;if(D.priority!==void 0)this._priority=D.priority;if(D.inScreens!==void 0)this._inScreens=D.inScreens;if(D.excludeScreens!==void 0)this._excludeScreens=D.excludeScreens}}get label(){return this._label}_createSystemObject(){let j={label:this._label,entityQueries:this.queries,priority:this._priority,phase:this._phase};if(Object.keys(this.singletons).length>0)j.entitySingletons=this.singletons;if(this.processFunction)j.process=this.processFunction;if(this.detachFunction)j.onDetach=this.detachFunction;if(this.initializeFunction)j.onInitialize=this.initializeFunction;if(this.eventHandlers)j.eventHandlers=this.eventHandlers;if(this._groups.length>0)j.groups=[...this._groups];if(this._inScreens)j.inScreens=this._inScreens;if(this._excludeScreens)j.excludeScreens=this._excludeScreens;if(this._requiredAssets)j.requiredAssets=this._requiredAssets;if(this._runWhenEmpty)j.runWhenEmpty=!0;if(Object.keys(this._entityEnterHandlers).length>0)j.onEntityEnter={...this._entityEnterHandlers};return j}setPriority(j){return this._priority=j,this}inPhase(j){return this._phase=j,this}inGroup(j){if(!this._groups.includes(j))this._groups.push(j);return this}inScreens(j){return this._inScreens=[...j],this}excludeScreens(j){return this._excludeScreens=[...j],this}requiresAssets(j){return this._requiredAssets=[...j],this}runWhenEmpty(){return this._runWhenEmpty=!0,this}withResources(j){return this._resourceKeys=[...j],this}addQuery(j,D){let $=this;return $.queries={...this.queries,[j]:D},$}addSingleton(j,D){let $=this;return $.singletons={...this.singletons,[j]:D},$}setProcess(j){return this.processFunction=this._wrapWithResources(j),this}_wrapWithResources(j){if(!this._resourceKeys?.length)return j;let D=this._resourceKeys,$={},G=!1;return(J)=>{for(let X of D)if(!G||J.ecs.isResourceObserved(X))$[X]=J.ecs.getResource(X);G=!0,J.resources=$,j(J)}}setProcessEach(j,D){let $=this;if(Object.keys($.queries).length>0||Object.keys($.singletons).length>0||$.processFunction!==void 0)throw Error("setProcessEach requires a SystemBuilder with no prior queries, singletons, or process function. Use addQuery + setProcess for multi-query systems.");$.queries.__each=j;let G={entity:void 0,dt:0,ecs:void 0,resources:void 0},J=j.mutates&&j.mutates.length>0?j.mutates:void 0,X=(Z)=>{let W=Z,A=W.queries.__each;if(!A)return;G.dt=W.dt,G.ecs=W.ecs,G.resources=W.resources;for(let L=0;L<A.length;L++){let B=A[L];if(!B)continue;G.entity=B;let _=D(G);if(J===void 0||_===!1)continue;for(let Y=0;Y<J.length;Y++){let F=J[Y];if(F!==void 0)W.ecs.markChanged(B.id,F)}}};return $.processFunction=$._wrapWithResources(X),this}setOnEntityEnter(j,D){return this._entityEnterHandlers[j]=D,this}setOnDetach(j){return this.detachFunction=j,this}setOnInitialize(j){return this.initializeFunction=j,this}setEventHandlers(j){return this.eventHandlers=j,this}}function i(j,D,$){let G=new Set,J=[D];while(J.length>0){let X=J.pop();if(X===void 0)break;if(X===j)throw Error(`Circular required component dependency: '${String(j)}' -> '${String(D)}' -> ... -> '${String(j)}'`);if(G.has(X))continue;G.add(X);let Z=$(X);if(Z)for(let W of Z)J.push(W.component)}}var d="0.16.1";class z{assets=new Map;groups=new Map;eventBus=null;setEventBus(j){this.eventBus=j}register(j,D){if(this.assets.set(j,{definition:D,status:"pending"}),D.group){let $=this.groups.get(D.group)??new Set;$.add(j),this.groups.set(D.group,$)}}async loadEagerAssets(){let j=[];for(let[D,$]of this.assets)if($.definition.eager&&$.status==="pending")j.push(D);await Promise.all(j.map((D)=>this.loadAsset(D)))}async loadAsset(j){let D=this.assets.get(j);if(!D)throw Error(`Asset '${String(j)}' not found`);if(D.status==="loaded"&&D.value!==void 0)return D.value;if(D.status==="loading"&&D.loadPromise)return D.loadPromise;if(D.status==="failed")D.status="pending";D.status="loading",D.loadPromise=D.definition.loader();try{let $=await D.loadPromise;return D.value=$,D.status="loaded",D.loadPromise=void 0,this.eventBus?.publish("assetLoaded",{key:j}),this.checkGroupProgress(D.definition.group),$}catch($){let G=$ instanceof Error?$:Error(String($));throw D.status="failed",D.error=G,D.loadPromise=void 0,this.eventBus?.publish("assetFailed",{key:j,error:G}),G}}async loadAssetGroup(j){let D=this.groups.get(j);if(!D||D.size===0)throw Error(`Asset group '${j}' not found or empty`);await Promise.all(Array.from(D).map(($)=>this.loadAsset($)))}get(j){let D=this.assets.get(j);if(!D)throw Error(`Asset '${String(j)}' not found`);if(D.status!=="loaded"||D.value===void 0)throw Error(`Asset '${String(j)}' is not loaded (status: ${D.status})`);return D.value}tryGet(j){let D=this.assets.get(j);if(!D||D.status!=="loaded")return;return D.value}getHandle(j){let D=this.assets.get(j);if(!D)throw Error(`Asset '${String(j)}' not found`);let $=this;return{get status(){return D.status},get isLoaded(){return D.status==="loaded"},get(){return $.get(j)},tryGet(){return $.tryGet(j)}}}getStatus(j){let D=this.assets.get(j);if(!D)throw Error(`Asset '${String(j)}' not found`);return D.status}isLoaded(j){return this.assets.get(j)?.status==="loaded"}isGroupLoaded(j){let D=this.groups.get(j);if(!D||D.size===0)return!1;for(let $ of D){let G=this.assets.get($);if(!G||G.status!=="loaded")return!1}return!0}getGroupProgress(j){return this.getGroupProgressDetails(j).progress}getGroupProgressDetails(j){let D=this.groups.get(j);if(!D||D.size===0)return{loaded:0,total:0,progress:0};let $=0;for(let J of D)if(this.assets.get(J)?.status==="loaded")$++;let G=D.size;return{loaded:$,total:G,progress:$/G}}checkGroupProgress(j){if(!j||!this.eventBus)return;let D=j,$=this.getGroupProgressDetails(D);if(this.eventBus.publish("assetGroupProgress",{group:D,...$}),$.loaded===$.total)this.eventBus.publish("assetGroupLoaded",{group:D})}createResource(){let j=this;return{getStatus(D){return j.getStatus(D)},isLoaded(D){return j.isLoaded(D)},isGroupLoaded(D){return j.isGroupLoaded(D)},getGroupProgress(D){return j.getGroupProgress(D)},get(D){return j.get(D)},tryGet(D){return j.tryGet(D)},getHandle(D){return j.getHandle(D)}}}getKeys(){return Array.from(this.assets.keys())}getGroupNames(){return Array.from(this.groups.keys())}getGroupKeys(j){let D=this.groups.get(j);return D?Array.from(D):[]}}class y{manager;constructor(j){this.manager=j}add(j,D){return this.manager.register(j,{loader:D,eager:!0}),this}addWithConfig(j,D){return this.manager.register(j,D),this}addGroup(j,D){for(let[$,G]of Object.entries(D))this.manager.register($,{loader:G,eager:!1,group:j});return this}getManager(){return this.manager}}function k(j){return new y(j??new z)}class P{screens=new Map;currentScreen=null;screenStack=[];eventBus=null;assetManager=null;ecs=null;setDependencies(j,D,$){this.eventBus=j,this.assetManager=D,this.ecs=$}requireEcs(){if(!this.ecs)throw Error("ScreenManager: dependencies not set. Call setDependencies() first.");return this.ecs}register(j,D){this.screens.set(j,{definition:D})}async setScreen(j,D){let $=this.screens.get(j);if(!$)throw Error(`Screen '${String(j)}' not found`);await this.verifyRequiredAssets($.definition.requiredAssets,$.definition.requiredAssetGroups);while(this.screenStack.length>0){let J=this.screenStack.pop();if(J)await this.exitScreen(J.name)}if(this.currentScreen)await this.exitScreen(this.currentScreen.name);let G=$.definition.initialState(D);this.currentScreen={name:j,config:D,state:G},await $.definition.onEnter?.({config:D,ecs:this.requireEcs()}),this.eventBus?.publish("screenEnter",{screen:j,config:D})}async pushScreen(j,D){let $=this.screens.get(j);if(!$)throw Error(`Screen '${String(j)}' not found`);if(await this.verifyRequiredAssets($.definition.requiredAssets,$.definition.requiredAssetGroups),this.currentScreen)this.screenStack.push(this.currentScreen);let G=$.definition.initialState(D);this.currentScreen={name:j,config:D,state:G},await $.definition.onEnter?.({config:D,ecs:this.requireEcs()}),this.eventBus?.publish("screenPush",{screen:j,config:D})}async popScreen(){if(this.screenStack.length===0)throw Error("Cannot pop screen: stack is empty");if(this.currentScreen)await this.exitScreen(this.currentScreen.name),this.eventBus?.publish("screenPop",{screen:this.currentScreen.name});this.currentScreen=this.screenStack.pop()??null}async exitScreen(j){let D=this.screens.get(j);if(D?.definition.onExit)await D.definition.onExit(this.requireEcs());this.eventBus?.publish("screenExit",{screen:j})}async verifyRequiredAssets(j,D){if(!this.assetManager)return;if(j){for(let $ of j)if(!this.assetManager.isLoaded($))await this.assetManager.loadAsset($)}if(D){for(let $ of D)if(!this.assetManager.isGroupLoaded($))await this.assetManager.loadAssetGroup($)}}getCurrentScreen(){return this.currentScreen?.name??null}getConfig(j){if(!this.currentScreen)throw Error("No current screen");if(j!==void 0&&this.currentScreen.name!==j)throw Error(`Expected current screen '${String(j)}', but current is '${String(this.currentScreen.name)}'`);return this.currentScreen.config}tryGetConfig(j){if(!this.currentScreen)return;if(j!==void 0&&this.currentScreen.name!==j)return;return this.currentScreen.config}getState(j){if(!this.currentScreen)throw Error("No current screen");if(j!==void 0&&this.currentScreen.name!==j)throw Error(`Expected current screen '${String(j)}', but current is '${String(this.currentScreen.name)}'`);return this.currentScreen.state}tryGetState(j){if(!this.currentScreen)return;if(j!==void 0&&this.currentScreen.name!==j)return;return this.currentScreen.state}updateState(j,D){if(!this.currentScreen)throw Error("No current screen");if(D!==void 0&&this.currentScreen.name!==D)throw Error(`Expected current screen '${String(D)}', but current is '${String(this.currentScreen.name)}'`);let $=typeof j==="function"?j(this.currentScreen.state):j;this.currentScreen.state={...this.currentScreen.state,...$}}getStackDepth(){return this.screenStack.length}isOverlay(){return this.screenStack.length>0}isActive(j){if(this.currentScreen?.name===j)return!0;return this.screenStack.some((D)=>D.name===j)}isCurrent(j){return this.currentScreen?.name===j}createResource(){let j=this;return{get current(){return j.getCurrentScreen()},get config(){return j.tryGetConfig()??null},get state(){return j.tryGetState()??null},set state(D){if(j.currentScreen&&D!==null)j.currentScreen.state=D},get stack(){return j.screenStack},get isOverlay(){return j.isOverlay()},get stackDepth(){return j.getStackDepth()},isActive(D){return j.isActive(D)},isCurrent(D){return j.isCurrent(D)}}}getScreenNames(){return Array.from(this.screens.keys())}hasScreen(j){return this.screens.has(j)}}class o{manager;constructor(j){this.manager=j}add(j,D){return this.manager.register(j,D),this}getManager(){return this.manager}}function I(j){return new o(j??new P)}class h{assetConfigurator=null;screenConfigurator=null;pendingResources=[];pendingDisposeCallbacks=[];pendingRequiredComponents=[];pendingPlugins=[];_fixedDt=null;constructor(){}withPlugin(j){return this.pendingPlugins.push(j),this}withComponentTypes(){return this}withEventTypes(){return this}withResourceTypes(){return this}withResource(j,D){return this.pendingResources.push({key:j,value:D}),this}withDispose(j,D){return this.pendingDisposeCallbacks.push({key:j,callback:D}),this}withRequired(j,D,$){return this.pendingRequiredComponents.push({trigger:j,required:D,factory:$}),this}withAssets(j){let D=k();return j(D),this.assetConfigurator=D,this}withScreens(j){let D=I();return j(D),this.screenConfigurator=D,this}withFixedTimestep(j){return this._fixedDt=j,this}withReactiveQueryNames(){return this}pluginFactory(){return(j)=>E(j.id).install(j.install)}build(){let j=new V;for(let D of this.pendingPlugins)j._installPluginUnchecked(D);for(let{key:D,value:$}of this.pendingResources)j.addResource(D,$);for(let{key:D,callback:$}of this.pendingDisposeCallbacks)j.registerDispose(D,$);for(let{trigger:D,required:$,factory:G}of this.pendingRequiredComponents)j.registerRequired(D,$,G);if(this.assetConfigurator)j._setAssetManager(this.assetConfigurator.getManager());else if(j._hasPendingPluginAssets())j._setAssetManager(new z);if(this.screenConfigurator)j._setScreenManager(this.screenConfigurator.getManager());else if(j._hasPendingPluginScreens())j._setScreenManager(new P);if(this._fixedDt!==null)j._setFixedDt(this._fixedDt);return j}}var r=["preUpdate","fixedUpdate","update","postUpdate","render"];class V{static VERSION=d;_entityManager;_eventBus;_resourceManager;_commandBuffer;_systems=[];_phaseSystems={preUpdate:[],fixedUpdate:[],update:[],postUpdate:[],render:[]};_installedPlugins=new Set;_pluginCleanups=new Map;_currentSystemDefaults;_screenScopedEntities=new Map;_entityScreenScope=new Map;_activeScopeHint=null;_disabledGroups=new Set;_assetManager=null;_screenManager=null;_reactiveQueryManager;_postUpdateHooks=[];_currentTick=0;_systemLastSeqs=new Map;_changeThreshold=0;_fixedDt=0.016666666666666666;_fixedAccumulator=0;_interpolationAlpha=0;_maxFixedSteps=8;_requiredComponents=new Map;_pendingPluginAssets=[];_pendingPluginScreens=[];_diagnosticsEnabled=!1;_systemTimings=new Map;_phaseTimings={preUpdate:0,fixedUpdate:0,update:0,postUpdate:0,render:0};_entityEnterTracking=new Map;_entityEnterFrameSet=new Set;_systemContexts=new WeakMap;_singletonScratch=[];_pendingFinalizers=[];_batchingRegistrations=!1;_initializeFired=!1;_systemsInitialized=new WeakSet;constructor(){this._entityManager=new T,this._eventBus=new x,this._resourceManager=new w,this._reactiveQueryManager=new q(this._entityManager),this._commandBuffer=new C(this),this._subscribeLifecycleHooks()}_subscribeLifecycleHooks(){this._entityManager.onAfterComponentAdded((j,D)=>{this._entityManager.markChanged(j,D);let $=this._requiredComponents.get(D);if($){let G=this._entityManager.getEntity(j);if(G){let J=G.components[D];for(let{component:X,factory:Z}of $){if(this._entityManager._pendingBatchKeys?.has(X))continue;if(!(X in G.components))this._entityManager.addComponent(j,X,Z(J))}}}}),this._entityManager.onAfterEntityMutated((j)=>{let D=this._entityManager.getEntity(j);if(D)this._reactiveQueryManager.recheckEntityAndChildren(D)}),this._entityManager.onAfterComponentRemoved((j,D)=>{let $=this._entityManager.getEntity(j);if($)this._reactiveQueryManager.onComponentRemoved($,D)}),this._entityManager.onBeforeEntityRemoved((j)=>{this._reactiveQueryManager.onEntityRemoved(j);let D=this._entityScreenScope.get(j);if(D!==void 0)this._entityScreenScope.delete(j),this._screenScopedEntities.get(D)?.delete(j)}),this._entityManager.onAfterParentChanged((j)=>{if(this._reactiveQueryManager.hasParentHasQueries){let D=this._entityManager.getEntity(j);if(D)this._reactiveQueryManager.recheckEntity(D)}})}static create(){return new h}addSystem(j){let D=new g(j,this._currentSystemDefaults);return this._pendingFinalizers.push(()=>{this._registerSystem(D._createSystemObject())}),D}_finalizePendingBuilders(){if(this._pendingFinalizers.length===0)return;this._batchingRegistrations=!0;while(this._pendingFinalizers.length>0){let j=this._pendingFinalizers;this._pendingFinalizers=[];for(let D of j)D()}this._batchingRegistrations=!1,this._rebuildPhaseSystems()}update(j){this._finalizePendingBuilders();let D=this._screenManager?.getCurrentScreen()??null,$=this._diagnosticsEnabled;this._runPhase("preUpdate",j,D,$);let G=$?performance.now():0;this._fixedAccumulator+=j;let J=0;while(this._fixedAccumulator>=this._fixedDt&&J<this._maxFixedSteps)this._executePhase(this._phaseSystems.fixedUpdate,this._fixedDt,D),this._commandBuffer.playback(this),this._fixedAccumulator-=this._fixedDt,J++;if(this._fixedAccumulator>=this._fixedDt)this._fixedAccumulator=0;if($)this._phaseTimings.fixedUpdate=performance.now()-G;this._interpolationAlpha=this._fixedAccumulator/this._fixedDt,this._runPhase("update",j,D,$),this._runPhase("postUpdate",j,D,$);for(let X of this._postUpdateHooks)X({ecs:this,dt:j});this._runPhase("render",j,D,$),this._resourceManager.flushObserved(),this._changeThreshold=this._entityManager.changeSeq,this._currentTick++}_executePhase(j,D,$){for(let G of j){if(!G.process&&!G.onEntityEnter)continue;if(G.groups?.length){let _=!1;for(let Y of G.groups)if(this._disabledGroups.has(Y)){_=!0;break}if(_)continue}if(G.inScreens?.length){if($===null||!G.inScreens.includes($))continue}if(G.excludeScreens?.length){if($!==null&&G.excludeScreens.includes($))continue}if(G.requiredAssets?.length&&this._assetManager){let _=!0;for(let Y of G.requiredAssets)if(!this._assetManager.isLoaded(Y)){_=!1;break}if(!_)continue}let J=this._systemLastSeqs.get(G)??0;this._changeThreshold=J;let X=this._systemContexts.get(G);if(!X)X={queries:{},dt:0,ecs:this},this._systemContexts.set(G,X);X.dt=D;let Z=X.queries,W=!1,A=!1;if(G.entityQueries)for(let _ in G.entityQueries){A=!0;let Y=G.entityQueries[_];if(Y){let Q=Z[_]??(Z[_]=[]);if(this._entityManager.getEntitiesWithQueryInto(Q,Y.with,Y.without||[],Y.changed,Y.changed?this._changeThreshold:void 0,Y.parentHas),Q.length)W=!0}}if(G.entitySingletons){let _=this._singletonScratch;for(let Y in G.entitySingletons){A=!0;let F=G.entitySingletons[Y];if(F){if(this._entityManager.getEntitiesWithQueryInto(_,F.with,F.without||[],F.changed,F.changed?this._changeThreshold:void 0,F.parentHas),Z[Y]=_[0],_.length)W=!0}}}let L=this._entityEnterTracking.get(G);if(L&&G.onEntityEnter)for(let _ in G.onEntityEnter){let Y=Z[_],F=L.get(_);if(!Y||!F)continue;let Q=G.onEntityEnter[_];if(!Q)continue;let K=this._entityEnterFrameSet;K.clear();for(let O of Y)if(K.add(O.id),!F.has(O.id))F.add(O.id),Q({entity:O,ecs:this});for(let O of F)if(!K.has(O))F.delete(O)}if(G.process){if(W||G.runWhenEmpty||!A){let Y=this._activeScopeHint;this._activeScopeHint=G.inScreens?.length&&$!==null?$:null;let F=this._diagnosticsEnabled?performance.now():0;try{G.process(X)}finally{if(this._activeScopeHint=Y,this._diagnosticsEnabled)this._systemTimings.set(G.label,performance.now()-F)}}}let B=G._autoMarkPairs;if(B){let _=this._entityManager;for(let Y=0;Y<B.length;Y++){let F=B[Y];if(!F)continue;let Q=F.mutates,K=Q.length;if(F.kind==="list"){let O=Z[F.queryName];if(!O)continue;for(let U=0;U<O.length;U++){let M=O[U];if(!M)continue;for(let f=0;f<K;f++){let u=Q[f];if(u!==void 0)_.markChanged(M.id,u)}}}else{let O=Z[F.queryName];if(!O)continue;for(let U=0;U<K;U++){let M=Q[U];if(M!==void 0)_.markChanged(O.id,M)}}}}this._systemLastSeqs.set(G,this._entityManager.changeSeq)}}_runPhase(j,D,$,G){if(G){let J=performance.now();this._executePhase(this._phaseSystems[j],D,$),this._phaseTimings[j]=performance.now()-J}else this._executePhase(this._phaseSystems[j],D,$);this._commandBuffer.playback(this)}async initialize(){if(this._finalizePendingBuilders(),await this.initializeResources(),this._assetManager)this._assetManager.setEventBus(this._eventBus),await this._assetManager.loadEagerAssets(),this._resourceManager.add("$assets",this._assetManager.createResource());if(this._screenManager){let j=this._eventBus;this._screenManager.setDependencies(j,this._assetManager,this),this._resourceManager.add("$screen",this._screenManager.createResource()),j.subscribe("screenExit",({screen:D})=>{let $=this._screenScopedEntities.get(D);if(!$||$.size===0)return;this._screenScopedEntities.delete(D);for(let G of Array.from($))this._entityScreenScope.delete(G),this.removeEntity(G)})}for(let j of this._systems){if(this._systemsInitialized.has(j))continue;this._systemsInitialized.add(j),await j.onInitialize?.(this)}this._initializeFired=!0}async initializeResources(...j){await this._resourceManager.initializeResources(this,...j)}_rebuildPhaseSystems(){for(let j of r)this._phaseSystems[j]=[];for(let j of this._systems){let D=j.phase??"update";this._phaseSystems[D].push(j)}for(let j of r)this._phaseSystems[j].sort((D,$)=>{let G=D.priority??0;return($.priority??0)-G})}updateSystemPriority(j,D){this._finalizePendingBuilders();let $=this._systems.find((G)=>G.label===j);if(!$)return!1;return $.priority=D,this._rebuildPhaseSystems(),!0}updateSystemPhase(j,D){this._finalizePendingBuilders();let $=this._systems.find((G)=>G.label===j);if(!$)return!1;return $.phase=D,this._rebuildPhaseSystems(),!0}get interpolationAlpha(){return this._interpolationAlpha}get fixedDt(){return this._fixedDt}disableSystemGroup(j){this._disabledGroups.add(j)}enableSystemGroup(j){this._disabledGroups.delete(j)}isSystemGroupEnabled(j){return!this._disabledGroups.has(j)}getSystemsInGroup(j){return this._finalizePendingBuilders(),this._systems.filter((D)=>D.groups?.includes(j)).map((D)=>D.label)}removeSystem(j){this._finalizePendingBuilders();let D=this._systems.findIndex((G)=>G.label===j);if(D===-1)return!1;let $=this._systems[D];if(!$)return!1;if($.onDetach)$.onDetach(this);return this._systems.splice(D,1),this._systemLastSeqs.delete($),this._entityEnterTracking.delete($),this._systemsInitialized.delete($),this._rebuildPhaseSystems(),!0}_registerSystem(j){if(this._systems.push(j),this._systemLastSeqs.set(j,this._changeThreshold),!this._batchingRegistrations)this._rebuildPhaseSystems();let D=[];if(j.entityQueries)for(let $ in j.entityQueries){if($===c)continue;let J=j.entityQueries[$]?.mutates;if(J&&J.length>0)D.push({queryName:$,mutates:J,kind:"list"})}if(j.entitySingletons)for(let $ in j.entitySingletons){let J=j.entitySingletons[$]?.mutates;if(J&&J.length>0)D.push({queryName:$,mutates:J,kind:"singleton"})}if(j._autoMarkPairs=D.length>0?D:null,j.onEntityEnter){let $=new Map;for(let G in j.onEntityEnter)$.set(G,new Set);this._entityEnterTracking.set(j,$)}if(j.eventHandlers)for(let $ in j.eventHandlers){let G=j.eventHandlers[$];if(G)this._eventBus.subscribe($,(J)=>{G({data:J,ecs:this})})}if(this._initializeFired&&!this._systemsInitialized.has(j)){this._systemsInitialized.add(j);let $=j.onInitialize?.(this);if($ instanceof Promise)$.catch((G)=>{console.error(`onInitialize for system "${j.label}" rejected:`,G)})}}hasResource(j){return this._resourceManager.has(j)}getResource(j){if(!this._resourceManager.has(j))throw Error(`Resource '${String(j)}' not found. Available resources: [${this.getResourceKeys().map((D)=>String(D)).join(", ")}]`);return this._resourceManager.get(j,this)}tryGetResource(j){let D=j;if(!this._resourceManager.has(D))return;return this._resourceManager.get(D,this)}addResource(j,D){return this._resourceManager.add(j,D),this}removeResource(j){return this._resourceManager.remove(j)}async disposeResource(j){return this._resourceManager.disposeResource(j,this)}async disposeResources(){return this._resourceManager.disposeResources(this)}updateResource(j,D){let $=this.getResource(j),G=D($);return this._resourceManager.add(j,G),this._resourceManager.notifyChange(j,G,$),this}setResource(j,D){let $=this.tryGetResource(j);if(this._resourceManager.add(j,D),$!==void 0)this._resourceManager.notifyChange(j,D,$);return this}onResourceChange(j,D){return this._resourceManager.onResourceChange(j,D)}isResourceObserved(j){return this._resourceManager.isObserved(j)}getResourceKeys(){return this._resourceManager.getKeys()}resourceNeedsInitialization(j){return this._resourceManager.needsInitialization(j)}getEntity(j){return this._entityManager.getEntity(j)}getComponent(j,D){return this._entityManager.getComponent(j,D)}addComponent(j,D,$){this._entityManager.addComponent(j,D,$)}addComponents(j,D){this._entityManager.addComponents(j,D)}removeComponent(j,D){this._entityManager.removeComponent(j,D)}hasComponent(j,D){return this._entityManager.getComponent(j,D)!==void 0}spawn(j,D){let $=this._entityManager.createEntity();return this._entityManager.addComponents($.id,j),this._applyScreenScope($.id,D),$}_getActiveScopeHint(){return this._activeScopeHint}_applyScreenScope(j,D){let $=D?.scope!==void 0?D.scope:this._activeScopeHint;if($===null)return;let G=this._screenScopedEntities.get($)??new Set;G.add(j),this._screenScopedEntities.set($,G),this._entityScreenScope.set(j,$)}getEntitiesWithQuery(j,D=[],$,G){return this._entityManager.getEntitiesWithQuery(j,D,$,$?this._changeThreshold:void 0,G)}getSingleton(j,D=[]){let $=this._entityManager.getEntitiesWithQuery(j,D);if($.length===0)throw Error(`getSingleton: no entity matches query with=[${String(j)}] without=[${String(D)}]`);if($.length>1)throw Error(`getSingleton: expected 1 entity but found ${$.length} matching query with=[${String(j)}] without=[${String(D)}]`);let G=$[0];if(!G)throw Error("getSingleton: unexpected empty result");return G}tryGetSingleton(j,D=[]){let $=this._entityManager.getEntitiesWithQuery(j,D);if($.length===0)return;if($.length>1)throw Error(`tryGetSingleton: expected 0 or 1 entity but found ${$.length} matching query with=[${String(j)}] without=[${String(D)}]`);return $[0]}removeEntity(j,D){return this._entityManager.removeEntity(j,D)}spawnChild(j,D,$){let G=this._entityManager.spawnChild(j,D);return this._emitHierarchyChanged(G.id,null,j),this._applyScreenScope(G.id,$),G}setParent(j,D){let $=this._entityManager.getParent(j);return this._entityManager.setParent(j,D),this._emitHierarchyChanged(j,$,D),this}removeParent(j){let D=this._entityManager.getParent(j),$=this._entityManager.removeParent(j);if($)this._emitHierarchyChanged(j,D,null);return $}getParent(j){return this._entityManager.getParent(j)}getChildren(j){return this._entityManager.getChildren(j)}getChildAt(j,D){return this._entityManager.getChildAt(j,D)}getChildIndex(j,D){return this._entityManager.getChildIndex(j,D)}getAncestors(j){return this._entityManager.getAncestors(j)}getDescendants(j){return this._entityManager.getDescendants(j)}getRoot(j){return this._entityManager.getRoot(j)}getSiblings(j){return this._entityManager.getSiblings(j)}isDescendantOf(j,D){return this._entityManager.isDescendantOf(j,D)}isAncestorOf(j,D){return this._entityManager.isAncestorOf(j,D)}getRootEntities(){return this._entityManager.getRootEntities()}forEachInHierarchy(j,D){this._entityManager.forEachInHierarchy(j,D)}hierarchyIterator(j){return this._entityManager.hierarchyIterator(j)}_emitHierarchyChanged(j,D,$){this._eventBus.publish("hierarchyChanged",{entityId:j,oldParent:D,newParent:$})}get installedPlugins(){return Array.from(this._installedPlugins)}get entityManager(){return this._entityManager}get eventBus(){return this._finalizePendingBuilders(),this._eventBus}get commands(){return this._commandBuffer}get currentTick(){return this._currentTick}get changeThreshold(){return this._changeThreshold}enableDiagnostics(j){if(this._diagnosticsEnabled=j,!j)this._systemTimings.clear(),this._phaseTimings={preUpdate:0,fixedUpdate:0,update:0,postUpdate:0,render:0}}get diagnosticsEnabled(){return this._diagnosticsEnabled}get systemTimings(){return this._systemTimings}get phaseTimings(){return this._phaseTimings}get entityCount(){return this._entityManager.entityCount}mutateComponent(j,D,$){let G=this._entityManager.getComponent(j,D);if(G===void 0)throw Error(`Entity ${j} does not have component "${String(D)}"`);return $(G),this._entityManager.markChanged(j,D),G}markChanged(j,D){this._entityManager.markChanged(j,D)}registerDispose(j,D){this._entityManager.registerDispose(j,D)}registerRequired(j,D,$){if(String(j)===String(D))throw Error(`Cannot require a component to depend on itself: '${String(j)}'`);let G=this._requiredComponents.get(j)??[];if(G.some((J)=>J.component===D))throw Error(`Required component '${String(D)}' already registered for trigger '${String(j)}'`);this._checkRequiredCycle(j,D),G.push({component:D,factory:$}),this._requiredComponents.set(j,G)}_checkRequiredCycle(j,D){i(j,D,($)=>this._requiredComponents.get($))}onComponentAdded(j,D){return this._entityManager.onComponentAdded(j,D)}onComponentRemoved(j,D){return this._entityManager.onComponentRemoved(j,D)}addReactiveQuery(j,D){this._reactiveQueryManager.addQuery(j,D)}removeReactiveQuery(j){return this._reactiveQueryManager.removeQuery(j)}on(j,D){return this._eventBus.subscribe(j,D)}off(j,D){return this._eventBus.unsubscribe(j,D)}onPostUpdate(j){return this._postUpdateHooks.push(j),()=>{let D=this._postUpdateHooks.indexOf(j);if(D!==-1)this._postUpdateHooks.splice(D,1)}}requireAssetManager(){if(!this._assetManager)throw Error("Asset manager not configured. Use withAssets() in builder.");return this._assetManager}getAsset(j){return this.requireAssetManager().get(j)}tryGetAsset(j){return this._assetManager?.tryGet(j)}getAssetHandle(j){return this.requireAssetManager().getHandle(j)}isAssetLoaded(j){return this._assetManager?.isLoaded(j)??!1}async loadAsset(j){return this.requireAssetManager().loadAsset(j)}async loadAssetGroup(j){return this.requireAssetManager().loadAssetGroup(j)}isAssetGroupLoaded(j){return this._assetManager?.isGroupLoaded(j)??!1}getAssetGroupProgress(j){return this._assetManager?.getGroupProgress(j)??0}requireScreenManager(){if(!this._screenManager)throw Error("Screen manager not configured. Use withScreens() in builder.");return this._screenManager}async setScreen(j,D){return this.requireScreenManager().setScreen(j,D)}async pushScreen(j,D){return this.requireScreenManager().pushScreen(j,D)}async popScreen(){return this.requireScreenManager().popScreen()}getCurrentScreen(){return this._screenManager?.getCurrentScreen()??null}getScreenConfig(j){return this.requireScreenManager().getConfig(j)}tryGetScreenConfig(j){return this._screenManager?.tryGetConfig(j)??void 0}getScreenState(j){return this.requireScreenManager().getState(j)}tryGetScreenState(j){return this._screenManager?.tryGetState(j)??void 0}updateScreenState(j,D){if(typeof j==="string")this.requireScreenManager().updateState(D,j);else this.requireScreenManager().updateState(j)}isCurrentScreen(j){return this._screenManager?.isCurrent(j)??!1}isScreenActive(j){return this._screenManager?.isActive(j)??!1}getScreenStackDepth(){return this._screenManager?.getStackDepth()??0}onScreenEnter(j,D){let $=this._eventBus,G=(Z)=>{if(Z.screen!==j)return;D({config:Z.config,ecs:this})},J=$.subscribe("screenEnter",G),X=$.subscribe("screenPush",G);return()=>{J(),X()}}onScreenExit(j,D){return this._eventBus.subscribe("screenExit",(G)=>{if(G.screen!==j)return;D({ecs:this})})}_setAssetManager(j){this._assetManager=j;for(let[D,$]of this._pendingPluginAssets)this._assetManager.register(D,$);this._pendingPluginAssets=[]}_setScreenManager(j){this._screenManager=j;for(let[D,$]of this._pendingPluginScreens)this._screenManager.register(D,$);this._pendingPluginScreens=[]}_hasPendingPluginAssets(){return this._pendingPluginAssets.length>0}_hasPendingPluginScreens(){return this._pendingPluginScreens.length>0}_setFixedDt(j){this._fixedDt=j}_registerAsset(j,D){this._pendingPluginAssets.push([j,D])}_registerScreen(j,D){this._pendingPluginScreens.push([j,D])}installPlugin(j){return this._installPluginUnchecked(j)}_installPluginUnchecked(j){if(this._installedPlugins.has(j.id))return this;this._installedPlugins.add(j.id);let D=[];this._pluginCleanups.set(j.id,D);let $=(J)=>{D.push(J)},G=this._currentSystemDefaults;this._currentSystemDefaults=j.systemDefaults;try{j.install(this,$)}finally{this._currentSystemDefaults=G}return this}uninstallPlugin(j){if(!this._installedPlugins.has(j))return!1;let D=this._pluginCleanups.get(j);if(this._pluginCleanups.delete(j),this._installedPlugins.delete(j),D)for(let $=D.length-1;$>=0;$--){let G=D[$];if(!G)continue;try{G()}catch(J){console.warn(`Plugin '${j}' cleanup threw:`,J)}}return!0}dispose(){let j=Array.from(this._installedPlugins);for(let D=j.length-1;D>=0;D--){let $=j[D];if($!==void 0)this.uninstallPlugin($)}}pluginFactory(){return(j)=>E(j.id).install(j.install)}getHelpers(j){return j(this)}}function uj(j){return j}function lj(j,D){return{x:j,y:D}}function sj(){return{x:0,y:0}}function cj(j,D){return{x:j.x+D.x,y:j.y+D.y}}function ij(j,D){return{x:j.x-D.x,y:j.y-D.y}}function dj(j,D){return{x:j.x*D,y:j.y*D}}function yj(j){return{x:-j.x,y:-j.y}}function oj(j,D){return j.x*D.x+j.y*D.y}function rj(j,D){return j.x*D.y-j.y*D.x}function aj(j){return j.x*j.x+j.y*j.y}function nj(j){return Math.sqrt(j.x*j.x+j.y*j.y)}function tj(j){let D=Math.sqrt(j.x*j.x+j.y*j.y);if(D===0)return{x:0,y:0};return{x:j.x/D,y:j.y/D}}function ej(j,D){let $=j.x-D.x,G=j.y-D.y;return $*$+G*G}function j3(j,D){let $=j.x-D.x,G=j.y-D.y;return Math.sqrt($*$+G*G)}function D3(j,D,$=0.0000000001){return Math.abs(j.x-D.x)<=$&&Math.abs(j.y-D.y)<=$}function $3(j,D,$){return{x:j,y:D,z:$}}function G3(){return{x:0,y:0,z:0}}function J3(j,D){return{x:j.x+D.x,y:j.y+D.y,z:j.z+D.z}}function X3(j,D){return{x:j.x-D.x,y:j.y-D.y,z:j.z-D.z}}function Z3(j,D){return{x:j.x*D,y:j.y*D,z:j.z*D}}function W3(j){return{x:-j.x,y:-j.y,z:-j.z}}function Y3(j,D){return j.x*D.x+j.y*D.y+j.z*D.z}function F3(j,D){return{x:j.y*D.z-j.z*D.y,y:j.z*D.x-j.x*D.z,z:j.x*D.y-j.y*D.x}}function L3(j){return j.x*j.x+j.y*j.y+j.z*j.z}function _3(j){return Math.sqrt(j.x*j.x+j.y*j.y+j.z*j.z)}function A3(j){let D=Math.sqrt(j.x*j.x+j.y*j.y+j.z*j.z);if(D===0)return{x:0,y:0,z:0};return{x:j.x/D,y:j.y/D,z:j.z/D}}function B3(j,D){let $=j.x-D.x,G=j.y-D.y,J=j.z-D.z;return $*$+G*G+J*J}function O3(j,D){let $=j.x-D.x,G=j.y-D.y,J=j.z-D.z;return Math.sqrt($*$+G*G+J*J)}function Q3(j,D,$=0.0000000001){return Math.abs(j.x-D.x)<=$&&Math.abs(j.y-D.y)<=$&&Math.abs(j.z-D.z)<=$}var w3=V;export{G3 as vec3Zero,X3 as vec3Sub,Z3 as vec3Scale,A3 as vec3Normalize,W3 as vec3Negate,L3 as vec3LengthSq,_3 as vec3Length,Q3 as vec3Equals,Y3 as vec3Dot,B3 as vec3DistanceSq,O3 as vec3Distance,F3 as vec3Cross,J3 as vec3Add,$3 as vec3,sj as vec2Zero,ij as vec2Sub,dj as vec2Scale,tj as vec2Normalize,yj as vec2Negate,aj as vec2LengthSq,nj as vec2Length,D3 as vec2Equals,oj as vec2Dot,ej as vec2DistanceSq,j3 as vec2Distance,rj as vec2Cross,cj as vec2Add,lj as vec2,n as directValue,E as definePlugin,w3 as default,I as createScreenConfigurator,uj as createQueryDefinition,k as createAssetConfigurator,g as SystemBuilder,P as ScreenManager,z as AssetManager};
|
|
2
2
|
|
|
3
|
-
//# debugId=
|
|
3
|
+
//# debugId=F8BB117EED11301264756E2164756E21
|
|
4
4
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1,12 +1,14 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
|
-
"sources": ["../src/hierarchy-manager.ts", "../src/entity-manager.ts", "../src/event-bus.ts", "../src/resource-manager.ts", "../src/reactive-query-manager.ts", "../src/command-buffer.ts", "../src/plugin.ts", "../src/system-builder.ts", "../src/utils/check-required-cycle.ts", "../src/asset-manager.ts", "../src/screen-manager.ts", "../src/ecspresso-builder.ts", "../src/ecspresso.ts", "../src/types.ts", "../src/utils/math.ts", "../src/index.ts"],
|
|
3
|
+
"sources": ["../src/hierarchy-manager.ts", "../src/query-match.ts", "../src/query-cache.ts", "../src/entity-manager.ts", "../src/event-bus.ts", "../src/resource-manager.ts", "../src/reactive-query-manager.ts", "../src/command-buffer.ts", "../src/plugin.ts", "../src/system-builder.ts", "../src/utils/check-required-cycle.ts", "../src/asset-manager.ts", "../src/screen-manager.ts", "../src/ecspresso-builder.ts", "../src/ecspresso.ts", "../src/types.ts", "../src/utils/math.ts", "../src/index.ts"],
|
|
4
4
|
"sourcesContent": [
|
|
5
5
|
"import type { HierarchyEntry, HierarchyIteratorOptions } from \"./types\";\n\n/**\n * Manages parent-child relationships between entities.\n * Handles hierarchy storage, validation, and traversal operations.\n */\nexport default class HierarchyManager {\n\t/** childId -> parentId */\n\tprivate parentMap: Map<number, number> = new Map();\n\t/** parentId -> ordered childIds */\n\tprivate childrenMap: Map<number, number[]> = new Map();\n\t/** Pre-allocated flat BFS queue for forEachInHierarchy [entityId, parentId (-1=null), depth, ...] */\n\tprivate _bfsQueue: number[] = [];\n\n\t/**\n\t * Set the parent of an entity.\n\t * @param childId The entity to set as a child\n\t * @param parentId The entity to set as the parent\n\t * @throws Error if this would create a circular reference or self-parenting\n\t */\n\tsetParent(childId: number, parentId: number): this {\n\t\tif (childId === parentId) {\n\t\t\tthrow new Error(`Cannot set entity ${childId} as its own parent`);\n\t\t}\n\n\t\t// Check for circular reference by walking up from the prospective parent\n\t\tif (this.wouldCreateCycle(childId, parentId)) {\n\t\t\tthrow new Error('Cannot set parent: would create circular reference');\n\t\t}\n\n\t\t// Remove from old parent's children list if exists\n\t\tconst oldParent = this.parentMap.get(childId);\n\t\tif (oldParent !== undefined) {\n\t\t\tconst oldChildren = this.childrenMap.get(oldParent);\n\t\t\tif (oldChildren) {\n\t\t\t\tconst idx = oldChildren.indexOf(childId);\n\t\t\t\tif (idx !== -1) {\n\t\t\t\t\toldChildren.splice(idx, 1);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Set new parent\n\t\tthis.parentMap.set(childId, parentId);\n\n\t\t// Add to new parent's children list\n\t\tconst children = this.childrenMap.get(parentId);\n\t\tif (children) {\n\t\t\tchildren.push(childId);\n\t\t} else {\n\t\t\tthis.childrenMap.set(parentId, [childId]);\n\t\t}\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Remove the parent relationship for an entity (orphan it).\n\t * @param childId The entity to orphan\n\t * @returns true if a parent was removed, false if entity had no parent\n\t */\n\tremoveParent(childId: number): boolean {\n\t\tconst parentId = this.parentMap.get(childId);\n\t\tif (parentId === undefined) {\n\t\t\treturn false;\n\t\t}\n\n\t\t// Remove from parent's children list\n\t\tconst children = this.childrenMap.get(parentId);\n\t\tif (children) {\n\t\t\tconst idx = children.indexOf(childId);\n\t\t\tif (idx !== -1) {\n\t\t\t\tchildren.splice(idx, 1);\n\t\t\t}\n\t\t}\n\n\t\tthis.parentMap.delete(childId);\n\t\treturn true;\n\t}\n\n\t/**\n\t * Get the parent of an entity.\n\t * @param entityId The entity to get the parent of\n\t * @returns The parent entity ID, or null if no parent\n\t */\n\tgetParent(entityId: number): number | null {\n\t\treturn this.parentMap.get(entityId) ?? null;\n\t}\n\n\t/**\n\t * Get all children of an entity in insertion order.\n\t * @param parentId The parent entity\n\t * @returns Readonly array of child entity IDs\n\t */\n\tgetChildren(parentId: number): readonly number[] {\n\t\tconst children = this.childrenMap.get(parentId);\n\t\treturn children ? [...children] : [];\n\t}\n\n\t/**\n\t * Get a child at a specific index.\n\t * @param parentId The parent entity\n\t * @param index The index of the child\n\t * @returns The child entity ID, or null if index is out of bounds\n\t */\n\tgetChildAt(parentId: number, index: number): number | null {\n\t\tif (index < 0) return null;\n\t\tconst children = this.childrenMap.get(parentId);\n\t\tif (!children || index >= children.length) return null;\n\t\treturn children[index] ?? null;\n\t}\n\n\t/**\n\t * Get the index of a child within its parent's children list.\n\t * @param parentId The parent entity\n\t * @param childId The child entity to find\n\t * @returns The index of the child, or -1 if not found\n\t */\n\tgetChildIndex(parentId: number, childId: number): number {\n\t\tconst children = this.childrenMap.get(parentId);\n\t\tif (!children) return -1;\n\t\treturn children.indexOf(childId);\n\t}\n\n\t/**\n\t * Remove an entity from the hierarchy (called when entity is destroyed).\n\t * Orphans any children and removes from parent's children list.\n\t * @param entityId The entity being removed\n\t * @returns Information about the removal (oldParent and orphanedChildren)\n\t */\n\tremoveEntity(entityId: number): { oldParent: number | null; orphanedChildren: number[] } {\n\t\tconst oldParent = this.parentMap.get(entityId) ?? null;\n\n\t\t// Remove from parent's children list\n\t\tif (oldParent !== null) {\n\t\t\tconst parentChildren = this.childrenMap.get(oldParent);\n\t\t\tif (parentChildren) {\n\t\t\t\tconst idx = parentChildren.indexOf(entityId);\n\t\t\t\tif (idx !== -1) {\n\t\t\t\t\tparentChildren.splice(idx, 1);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tthis.parentMap.delete(entityId);\n\n\t\t// Orphan all children\n\t\tconst children = this.childrenMap.get(entityId) ?? [];\n\t\tconst orphanedChildren = [...children];\n\t\tfor (const childId of children) {\n\t\t\tthis.parentMap.delete(childId);\n\t\t}\n\t\tthis.childrenMap.delete(entityId);\n\n\t\treturn { oldParent, orphanedChildren };\n\t}\n\n\t/**\n\t * Get all ancestors of an entity in order [parent, grandparent, ...].\n\t * @param entityId The entity to get ancestors of\n\t * @returns Readonly array of ancestor entity IDs\n\t */\n\tgetAncestors(entityId: number): readonly number[] {\n\t\tconst ancestors: number[] = [];\n\t\tlet current = this.parentMap.get(entityId);\n\t\twhile (current !== undefined) {\n\t\t\tancestors.push(current);\n\t\t\tcurrent = this.parentMap.get(current);\n\t\t}\n\t\treturn ancestors;\n\t}\n\n\t/**\n\t * Get all descendants of an entity in depth-first order.\n\t * @param entityId The entity to get descendants of\n\t * @returns Readonly array of descendant entity IDs\n\t */\n\tgetDescendants(entityId: number): readonly number[] {\n\t\tconst descendants: number[] = [];\n\t\tconst initialChildren = this.childrenMap.get(entityId);\n\t\tif (!initialChildren) return descendants;\n\n\t\t// Use push/pop (O(1)) instead of shift/unshift (O(n)).\n\t\t// Seed stack in reverse so pop() yields children in original order.\n\t\tconst stack = initialChildren.slice().reverse();\n\n\t\twhile (stack.length > 0) {\n\t\t\tconst current = stack.pop() as number;\n\t\t\tdescendants.push(current);\n\t\t\tconst children = this.childrenMap.get(current);\n\t\t\tif (children) {\n\t\t\t\tfor (let i = children.length - 1; i >= 0; i--) {\n\t\t\t\t\tstack.push(children[i] as number);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn descendants;\n\t}\n\n\t/**\n\t * Get the root ancestor of an entity (topmost parent), or self if no parent.\n\t * @param entityId The entity to get the root of\n\t * @returns The root entity ID\n\t */\n\tgetRoot(entityId: number): number {\n\t\tlet current = entityId;\n\t\tlet parent = this.parentMap.get(current);\n\t\twhile (parent !== undefined) {\n\t\t\tcurrent = parent;\n\t\t\tparent = this.parentMap.get(current);\n\t\t}\n\t\treturn current;\n\t}\n\n\t/**\n\t * Get siblings of an entity (other children of the same parent).\n\t * @param entityId The entity to get siblings of\n\t * @returns Readonly array of sibling entity IDs\n\t */\n\tgetSiblings(entityId: number): readonly number[] {\n\t\tconst parentId = this.parentMap.get(entityId);\n\t\tif (parentId === undefined) return [];\n\n\t\tconst children = this.childrenMap.get(parentId);\n\t\tif (!children) return [];\n\n\t\treturn children.filter(id => id !== entityId);\n\t}\n\n\t/**\n\t * Check if an entity is a descendant of another entity.\n\t * @param entityId The potential descendant\n\t * @param ancestorId The potential ancestor\n\t * @returns true if entityId is a descendant of ancestorId\n\t */\n\tisDescendantOf(entityId: number, ancestorId: number): boolean {\n\t\tif (entityId === ancestorId) return false;\n\n\t\tlet current = this.parentMap.get(entityId);\n\t\twhile (current !== undefined) {\n\t\t\tif (current === ancestorId) return true;\n\t\t\tcurrent = this.parentMap.get(current);\n\t\t}\n\t\treturn false;\n\t}\n\n\t/**\n\t * Check if an entity is an ancestor of another entity.\n\t * @param entityId The potential ancestor\n\t * @param descendantId The potential descendant\n\t * @returns true if entityId is an ancestor of descendantId\n\t */\n\tisAncestorOf(entityId: number, descendantId: number): boolean {\n\t\treturn this.isDescendantOf(descendantId, entityId);\n\t}\n\n\t/**\n\t * Returns true when at least one parent-child relationship exists.\n\t * O(1) — checks Map size, no iteration.\n\t */\n\tget hasHierarchy(): boolean {\n\t\treturn this.childrenMap.size > 0;\n\t}\n\n\t/**\n\t * Get all root entities (entities that have children but no parent).\n\t * @returns Readonly array of root entity IDs\n\t */\n\tgetRootEntities(): readonly number[] {\n\t\tconst roots: number[] = [];\n\t\tfor (const parentId of this.childrenMap.keys()) {\n\t\t\tif (!this.parentMap.has(parentId)) {\n\t\t\t\troots.push(parentId);\n\t\t\t}\n\t\t}\n\t\treturn roots;\n\t}\n\n\t/**\n\t * Check if setting a parent would create a cycle.\n\t * A cycle would occur if the prospective parent is a descendant of the child.\n\t */\n\tprivate wouldCreateCycle(childId: number, parentId: number): boolean {\n\t\tlet current: number | undefined = parentId;\n\t\twhile (current !== undefined) {\n\t\t\tif (current === childId) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tcurrent = this.parentMap.get(current);\n\t\t}\n\t\treturn false;\n\t}\n\n\t/**\n\t * Traverse the hierarchy in parent-first (breadth-first) order.\n\t * Parents are guaranteed to be visited before their children.\n\t * @param callback Function called for each entity with (entityId, parentId, depth)\n\t * @param options Optional traversal options (roots to filter to specific subtrees)\n\t */\n\tforEachInHierarchy(\n\t\tcallback: (entityId: number, parentId: number | null, depth: number) => void,\n\t\toptions?: HierarchyIteratorOptions\n\t): void {\n\t\tconst roots = options?.roots ?? this.getRootEntities();\n\t\t// Flat queue with stride 3: [entityId, parentId (-1 for null), depth, ...]\n\t\tconst queue = this._bfsQueue;\n\t\tqueue.length = 0;\n\n\t\tfor (const id of roots) {\n\t\t\tqueue.push(id, -1, 0);\n\t\t}\n\n\t\tfor (let i = 0; i < queue.length; i += 3) {\n\t\t\tconst entityId = queue[i]!;\n\t\t\tconst rawParent = queue[i + 1]!;\n\t\t\tconst depth = queue[i + 2]!;\n\n\t\t\tcallback(entityId, rawParent === -1 ? null : rawParent, depth);\n\n\t\t\tconst children = this.childrenMap.get(entityId);\n\t\t\tif (children) {\n\t\t\t\tconst childDepth = depth + 1;\n\t\t\t\tfor (const childId of children) {\n\t\t\t\t\tqueue.push(childId, entityId, childDepth);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Generator-based hierarchy traversal in parent-first (breadth-first) order.\n\t * Supports early termination via break.\n\t * @param options Optional traversal options (roots to filter to specific subtrees)\n\t * @yields HierarchyEntry for each entity in parent-first order\n\t */\n\t*hierarchyIterator(options?: HierarchyIteratorOptions): Generator<HierarchyEntry, void, unknown> {\n\t\tconst roots = options?.roots ?? this.getRootEntities();\n\t\tconst queue: HierarchyEntry[] = [];\n\n\t\t// Initialize queue with root entities\n\t\tfor (const id of roots) {\n\t\t\tqueue.push({ entityId: id, parentId: null, depth: 0 });\n\t\t}\n\n\t\tfor (const current of queue) {\n\t\t\tyield current;\n\n\t\t\tconst children = this.childrenMap.get(current.entityId);\n\t\t\tif (children) {\n\t\t\t\tfor (const childId of children) {\n\t\t\t\t\tqueue.push({\n\t\t\t\t\t\tentityId: childId,\n\t\t\t\t\t\tparentId: current.entityId,\n\t\t\t\t\t\tdepth: current.depth + 1\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n",
|
|
6
|
-
"import type { Entity, FilteredEntity, RemoveEntityOptions, HierarchyEntry, HierarchyIteratorOptions } from \"./types\";\nimport HierarchyManager from \"./hierarchy-manager\";\n\n/** Returns true if `components` contains ALL keys in `required`. */\nfunction hasAllComponents(\n\tcomponents: Record<string | number | symbol, unknown>,\n\trequired: ReadonlyArray<string | number | symbol>,\n): boolean {\n\tfor (const key of required) {\n\t\tif (!(key in components)) return false;\n\t}\n\treturn true;\n}\n\n/** Returns true if `components` contains ANY key in `excluded`. */\nfunction hasAnyComponent(\n\tcomponents: Record<string | number | symbol, unknown>,\n\texcluded: ReadonlyArray<string | number | symbol>,\n): boolean {\n\tfor (const key of excluded) {\n\t\tif (key in components) return true;\n\t}\n\treturn false;\n}\n\n/** Returns true if any component in `changed` was modified after `threshold`. */\nfunction hasChangedComponent(\n\tentitySeqs: Map<string | number | symbol, number> | undefined,\n\tchanged: ReadonlyArray<string | number | symbol>,\n\tthreshold: number,\n): boolean {\n\tif (!entitySeqs) return false;\n\tfor (const key of changed) {\n\t\tif ((entitySeqs.get(key) ?? -1) > threshold) return true;\n\t}\n\treturn false;\n}\n\ntype ComponentCallback<ComponentTypes> = (ctx: { value: unknown; entity: Entity<ComponentTypes> }) => void;\n\n/**\n * Manages zero-allocation callback iteration with safe mid-iteration unsubscribe.\n * During iteration, unsubscribes are deferred. Snapshot length guarantees all\n * callbacks registered at call time execute. Compaction runs when iteration ends.\n */\nclass CallbackList<ComponentTypes> {\n\tprivate readonly callbacks: ComponentCallback<ComponentTypes>[] = [];\n\tprivate _iterDepth = 0;\n\tprivate _pendingRemovals: ComponentCallback<ComponentTypes>[] = [];\n\n\tadd(cb: ComponentCallback<ComponentTypes>): void {\n\t\tthis.callbacks.push(cb);\n\t}\n\n\tremove(cb: ComponentCallback<ComponentTypes>): void {\n\t\tif (this._iterDepth > 0) {\n\t\t\tthis._pendingRemovals.push(cb);\n\t\t\treturn;\n\t\t}\n\t\tconst idx = this.callbacks.indexOf(cb);\n\t\tif (idx !== -1) this.callbacks.splice(idx, 1);\n\t}\n\n\tinvoke(ctx: { value: unknown; entity: Entity<ComponentTypes> }): void {\n\t\tthis._iterDepth++;\n\t\tconst len = this.callbacks.length;\n\t\tfor (let i = 0; i < len; i++) {\n\t\t\tconst cb = this.callbacks[i];\n\t\t\tif (cb) cb(ctx);\n\t\t}\n\t\tthis._iterDepth--;\n\t\tif (this._iterDepth === 0 && this._pendingRemovals.length > 0) {\n\t\t\tfor (const cb of this._pendingRemovals) {\n\t\t\t\tconst idx = this.callbacks.indexOf(cb);\n\t\t\t\tif (idx !== -1) this.callbacks.splice(idx, 1);\n\t\t\t}\n\t\t\tthis._pendingRemovals.length = 0;\n\t\t}\n\t}\n}\n\nexport default\nclass EntityManager<ComponentTypes> {\n\tprivate nextId: number = 1;\n\tprivate entities: Map<number, Entity<ComponentTypes>> = new Map();\n\tprivate componentIndices: Map<keyof ComponentTypes, Set<number>> = new Map();\n\t/**\n\t * Callbacks registered for component additions\n\t */\n\tprivate addedCallbacks: Map<keyof ComponentTypes, CallbackList<ComponentTypes>> = new Map();\n\t/**\n\t * Callbacks registered for component removals\n\t */\n\tprivate removedCallbacks: Map<keyof ComponentTypes, CallbackList<ComponentTypes>> = new Map();\n\t/**\n\t * Hierarchy manager for parent-child relationships\n\t */\n\tprivate hierarchyManager: HierarchyManager = new HierarchyManager();\n\t/**\n\t * Per-type component dispose callbacks.\n\t * Called when a component is removed (explicit removal, entity destruction, or replacement).\n\t */\n\tprivate disposeCallbacks: Map<keyof ComponentTypes, (ctx: { value: unknown; entityId: number }) => void> = new Map();\n\t/**\n\t * Per-entity per-component change sequence tracking.\n\t * Maps entityId -> (componentName -> sequence number when last changed)\n\t */\n\tprivate changeSeqs: Map<number, Map<keyof ComponentTypes, number>> = new Map();\n\t/**\n\t * Monotonic sequence counter for change detection.\n\t * Each markChanged call increments this and stamps the new value.\n\t */\n\tprivate _changeSeq: number = 0;\n\n\t// ==================== Lifecycle Hook Arrays ====================\n\tprivate _afterComponentAddedHooks: Array<(entityId: number, componentName: keyof ComponentTypes) => void> = [];\n\tprivate _afterEntityMutatedHooks: Array<(entityId: number) => void> = [];\n\tprivate _afterComponentRemovedHooks: Array<(entityId: number, componentName: keyof ComponentTypes) => void> = [];\n\tprivate _beforeEntityRemovedHooks: Array<(entityId: number) => void> = [];\n\tprivate _afterParentChangedHooks: Array<(childId: number) => void> = [];\n\n\t// ==================== Batching Fields ====================\n\tprivate _batchingDepth: number = 0;\n\tprivate _batchedEntityIds: Set<number> = new Set();\n\t/** Component keys being added in the current addComponents batch, if any.\n\t * Used by required component resolution to skip auto-adding explicitly provided components. */\n\t_pendingBatchKeys: ReadonlySet<keyof ComponentTypes> | null = null;\n\n\tget entityCount(): number {\n\t\treturn this.entities.size;\n\t}\n\n\tcreateEntity(): Entity<ComponentTypes> {\n\t\tconst id = this.nextId++;\n\t\tconst entity: Entity<ComponentTypes> = { id, components: {} };\n\t\tthis.entities.set(id, entity);\n\t\treturn entity;\n\t}\n\n\t/**\n\t * Register a dispose callback for a component type.\n\t * Called when a component is removed (explicit removal, entity destruction, or replacement).\n\t * Later registrations replace earlier ones for the same component type.\n\t * @param componentName The component type to register disposal for\n\t * @param callback Function receiving the component value being disposed and the entity ID\n\t */\n\tregisterDispose<ComponentName extends keyof ComponentTypes>(\n\t\tcomponentName: ComponentName,\n\t\tcallback: (ctx: { value: ComponentTypes[ComponentName]; entityId: number }) => void\n\t): void {\n\t\tthis.disposeCallbacks.set(componentName, callback as (ctx: { value: unknown; entityId: number }) => void);\n\t}\n\n\t/**\n\t * Get all registered dispose callbacks.\n\t * @internal Used by ECSpresso for plugin installation\n\t */\n\tgetDisposeCallbacks(): Map<keyof ComponentTypes, (ctx: { value: unknown; entityId: number }) => void> {\n\t\treturn this.disposeCallbacks;\n\t}\n\n\t/**\n\t * Invoke the dispose callback for a component, if registered.\n\t * Errors are caught and logged to prevent blocking removal.\n\t */\n\tprivate invokeDispose<ComponentName extends keyof ComponentTypes>(\n\t\tcomponentName: ComponentName,\n\t\tvalue: ComponentTypes[ComponentName],\n\t\tentityId: number\n\t): void {\n\t\tconst cb = this.disposeCallbacks.get(componentName);\n\t\tif (!cb) return;\n\t\ttry {\n\t\t\tcb({ value, entityId });\n\t\t} catch (error) {\n\t\t\tconsole.warn(`Component dispose callback for '${String(componentName)}' threw:`, error);\n\t\t}\n\t}\n\n\t// TODO: Component object pooling if(/when) garbage collection is an issue...?\n\taddComponent<ComponentName extends keyof ComponentTypes>(\n\t\tentityId: number,\n\t\tcomponentName: ComponentName,\n\t\tdata: ComponentTypes[ComponentName]\n\t) {\n\t\tconst entity = this.entities.get(entityId);\n\n\t\tif (!entity) {\n\t\t\tthrow new Error(`Cannot add component '${String(componentName)}': Entity with ID ${entityId} does not exist`);\n\t\t}\n\n\t\t// Dispose old value if replacing an existing component\n\t\tconst existing = entity.components[componentName];\n\t\tif (existing !== undefined) {\n\t\t\tthis.invokeDispose(componentName, existing as ComponentTypes[ComponentName], entity.id);\n\t\t}\n\n\t\tentity.components[componentName] = data;\n\n\t\t// Update component index\n\t\tif (!this.componentIndices.has(componentName)) {\n\t\t\tthis.componentIndices.set(componentName, new Set());\n\t\t}\n\t\tthis.componentIndices.get(componentName)?.add(entity.id);\n\t\t// Trigger added callbacks (index-based iteration; unsubscribe nulls slots, compacted after)\n\t\tconst callbacks = this.addedCallbacks.get(componentName);\n\t\tif (callbacks) {\n\t\t\tcallbacks.invoke({ value: data, entity });\n\t\t}\n\n\t\t// Fire afterComponentAdded hooks (may trigger recursive addComponent)\n\t\tthis._batchingDepth++;\n\t\tfor (const hook of this._afterComponentAddedHooks) {\n\t\t\thook(entity.id, componentName);\n\t\t}\n\t\tthis._batchedEntityIds.add(entity.id);\n\t\tthis._batchingDepth--;\n\n\t\t// Flush afterEntityMutated when outermost batch completes\n\t\tif (this._batchingDepth === 0) {\n\t\t\tfor (const entityId of this._batchedEntityIds) {\n\t\t\t\tfor (const hook of this._afterEntityMutatedHooks) {\n\t\t\t\t\thook(entityId);\n\t\t\t\t}\n\t\t\t}\n\t\t\tthis._batchedEntityIds.clear();\n\t\t}\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Add multiple components to an entity at once\n\t * @param entityId Entity ID to add components to\n\t * @param components Object with component names as keys and component data as values\n\t */\n\taddComponents<\n\t\tT extends { [K in keyof ComponentTypes]?: ComponentTypes[K] }\n\t>(\n\t\tentityId: number,\n\t\tcomponents: T & Record<Exclude<keyof T, keyof ComponentTypes>, never>\n\t) {\n\t\tconst entity = this.entities.get(entityId);\n\n\t\tif (!entity) {\n\t\t\tthrow new Error(`Cannot add components: Entity with ID ${entityId} does not exist`);\n\t\t}\n\n\t\tconst outerPending = this._pendingBatchKeys;\n\t\tthis._pendingBatchKeys = new Set(Object.keys(components) as (keyof ComponentTypes)[]);\n\t\tthis._batchingDepth++;\n\t\tfor (const componentName in components) {\n\t\t\tthis.addComponent(\n\t\t\t\tentity.id,\n\t\t\t\tcomponentName as keyof ComponentTypes,\n\t\t\t\tcomponents[componentName as keyof T] as ComponentTypes[keyof ComponentTypes]\n\t\t\t);\n\t\t}\n\t\tthis._batchingDepth--;\n\t\tthis._pendingBatchKeys = outerPending;\n\n\t\tif (this._batchingDepth === 0) {\n\t\t\tfor (const entityId of this._batchedEntityIds) {\n\t\t\t\tfor (const hook of this._afterEntityMutatedHooks) {\n\t\t\t\t\thook(entityId);\n\t\t\t\t}\n\t\t\t}\n\t\t\tthis._batchedEntityIds.clear();\n\t\t}\n\n\t\treturn this;\n\t}\n\n\tremoveComponent<ComponentName extends keyof ComponentTypes>(\n\t\tentityId: number,\n\t\tcomponentName: ComponentName\n\t) {\n\t\tconst entity = this.entities.get(entityId);\n\n\t\tif (!entity) {\n\t\t\tthrow new Error(`Cannot remove component '${String(componentName)}': Entity with ID ${entityId} does not exist`);\n\t\t}\n\t\t// Get old value for callbacks\n\t\tconst oldValue = entity.components[componentName] as ComponentTypes[ComponentName] | undefined;\n\n\t\t// Invoke dispose before deletion and removal callbacks\n\t\tif (oldValue !== undefined) {\n\t\t\tthis.invokeDispose(componentName, oldValue, entity.id);\n\t\t}\n\n\t\tdelete entity.components[componentName];\n\n\t\t// Trigger removed callbacks (index-based iteration; unsubscribe nulls slots, compacted after)\n\t\tconst removeCbs = this.removedCallbacks.get(componentName);\n\t\tif (removeCbs && oldValue !== undefined) {\n\t\t\tremoveCbs.invoke({ value: oldValue, entity });\n\t\t}\n\n\t\t// Update component index\n\t\tthis.componentIndices.get(componentName)?.delete(entity.id);\n\n\t\t// Fire afterComponentRemoved hooks (only if component was present)\n\t\tif (oldValue !== undefined) {\n\t\t\tfor (const hook of this._afterComponentRemovedHooks) {\n\t\t\t\thook(entity.id, componentName);\n\t\t\t}\n\t\t}\n\n\t\treturn this;\n\t}\n\n\tgetComponent<ComponentName extends keyof ComponentTypes>(entityId: number, componentName: ComponentName): ComponentTypes[ComponentName] | undefined {\n\t\treturn this.entities.get(entityId)?.components[componentName];\n\t}\n\n\tgetEntitiesWithQuery<\n\t\tWithComponents extends keyof ComponentTypes = never,\n\t\tWithoutComponents extends keyof ComponentTypes = never\n\t>(\n\t\trequired: ReadonlyArray<WithComponents> = [],\n\t\texcluded: ReadonlyArray<WithoutComponents> = [],\n\t\tchanged?: ReadonlyArray<keyof ComponentTypes>,\n\t\tchangeThreshold?: number,\n\t\tparentHas?: ReadonlyArray<keyof ComponentTypes>,\n\t): Array<FilteredEntity<ComponentTypes, WithComponents extends never ? never : WithComponents, WithoutComponents extends never ? never : WithoutComponents>> {\n\t\treturn this.getEntitiesWithQueryInto([], required, excluded, changed, changeThreshold, parentHas);\n\t}\n\n\t/**\n\t * Fill an existing array with entities matching the query, clearing it first.\n\t * Returns the same array reference for convenience.\n\t */\n\tgetEntitiesWithQueryInto<\n\t\tWithComponents extends keyof ComponentTypes = never,\n\t\tWithoutComponents extends keyof ComponentTypes = never\n\t>(\n\t\toutput: Array<FilteredEntity<ComponentTypes, WithComponents extends never ? never : WithComponents, WithoutComponents extends never ? never : WithoutComponents>>,\n\t\trequired: ReadonlyArray<WithComponents> = [],\n\t\texcluded: ReadonlyArray<WithoutComponents> = [],\n\t\tchanged?: ReadonlyArray<keyof ComponentTypes>,\n\t\tchangeThreshold?: number,\n\t\tparentHas?: ReadonlyArray<keyof ComponentTypes>,\n\t): Array<FilteredEntity<ComponentTypes, WithComponents extends never ? never : WithComponents, WithoutComponents extends never ? never : WithoutComponents>> {\n\t\toutput.length = 0;\n\n\t\tconst hasChangedFilter = changed !== undefined && changed.length > 0 && changeThreshold !== undefined;\n\t\tconst hasParentHasFilter = parentHas !== undefined && parentHas.length > 0;\n\n\t\t// Runtime query filtering guarantees WithComponents/WithoutComponents constraints,\n\t\t// but TypeScript can't narrow Entity<CT> to FilteredEntity from imperative logic.\n\t\ttype ResultEntry = FilteredEntity<ComponentTypes, WithComponents extends never ? never : WithComponents, WithoutComponents extends never ? never : WithoutComponents>;\n\n\t\tif (required.length === 0) {\n\t\t\tif (excluded.length === 0 && !hasChangedFilter && !hasParentHasFilter) {\n\t\t\t\tfor (const entity of this.entities.values()) {\n\t\t\t\t\toutput.push(entity as unknown as ResultEntry);\n\t\t\t\t}\n\t\t\t\treturn output;\n\t\t\t}\n\n\t\t\tfor (const entity of this.entities.values()) {\n\t\t\t\tif (excluded.length > 0 && hasAnyComponent(entity.components, excluded)) continue;\n\t\t\t\tif (hasChangedFilter && !hasChangedComponent(this.changeSeqs.get(entity.id), changed, changeThreshold)) continue;\n\t\t\t\tif (hasParentHasFilter && !this.parentHasComponents(entity.id, parentHas)) continue;\n\t\t\t\toutput.push(entity as unknown as ResultEntry);\n\t\t\t}\n\t\t\treturn output;\n\t\t}\n\n\t\t// Find the component with the smallest entity set to start with\n\t\tconst firstRequired = required[0];\n\t\tif (firstRequired === undefined) return output;\n\t\tlet smallestComponent: WithComponents = firstRequired;\n\t\tlet smallestSize = this.componentIndices.get(firstRequired)?.size ?? 0;\n\t\t// Start at 1 — firstRequired is already the initial candidate\n\t\tfor (let i = 1; i < required.length; i++) {\n\t\t\tconst comp = required[i];\n\t\t\tif (comp === undefined) continue;\n\t\t\tconst size = this.componentIndices.get(comp)?.size ?? 0;\n\t\t\tif (size < smallestSize) {\n\t\t\t\tsmallestComponent = comp;\n\t\t\t\tsmallestSize = size;\n\t\t\t}\n\t\t}\n\n\t\t// Start with the entities from the smallest component set\n\t\tconst candidateSet = this.componentIndices.get(smallestComponent);\n\t\tif (!candidateSet || candidateSet.size === 0) {\n\t\t\treturn output;\n\t\t}\n\n\t\tfor (const id of candidateSet) {\n\t\t\tconst entity = this.entities.get(id);\n\t\t\tif (!entity) continue;\n\t\t\tif (!hasAllComponents(entity.components, required)) continue;\n\t\t\tif (excluded.length > 0 && hasAnyComponent(entity.components, excluded)) continue;\n\t\t\tif (hasChangedFilter && !hasChangedComponent(this.changeSeqs.get(id), changed, changeThreshold)) continue;\n\t\t\tif (hasParentHasFilter && !this.parentHasComponents(id, parentHas)) continue;\n\t\t\toutput.push(entity as unknown as ResultEntry);\n\t\t}\n\n\t\treturn output;\n\t}\n\n\t/**\n\t * Check if an entity's direct parent has all specified components\n\t */\n\tprivate parentHasComponents(entityId: number, components: ReadonlyArray<keyof ComponentTypes>): boolean {\n\t\tconst parentId = this.hierarchyManager.getParent(entityId);\n\t\tif (parentId === null) return false;\n\n\t\tconst parentEntity = this.entities.get(parentId);\n\t\tif (!parentEntity) return false;\n\n\t\treturn hasAllComponents(parentEntity.components, components);\n\t}\n\n\tremoveEntity(entityId: number, options?: RemoveEntityOptions): boolean {\n\t\tconst entity = this.entities.get(entityId);\n\n\t\tif (!entity) return false;\n\n\t\tconst cascade = options?.cascade ?? true;\n\n\t\tif (cascade) {\n\t\t\t// Get all descendants first (depth-first order)\n\t\t\tconst descendants = this.hierarchyManager.getDescendants(entity.id);\n\t\t\t// Fire beforeEntityRemoved for descendants (reverse: children before parents)\n\t\t\tfor (let i = descendants.length - 1; i >= 0; i--) {\n\t\t\t\tconst descendantId = descendants[i];\n\t\t\t\tif (descendantId === undefined) continue;\n\t\t\t\tfor (const hook of this._beforeEntityRemovedHooks) {\n\t\t\t\t\thook(descendantId);\n\t\t\t\t}\n\t\t\t}\n\t\t\t// Fire beforeEntityRemoved for the entity itself\n\t\t\tfor (const hook of this._beforeEntityRemovedHooks) {\n\t\t\t\thook(entity.id);\n\t\t\t}\n\t\t\t// Now do actual removal (descendants in reverse order)\n\t\t\tfor (let i = descendants.length - 1; i >= 0; i--) {\n\t\t\t\tconst descendantId = descendants[i];\n\t\t\t\tif (descendantId === undefined) continue;\n\t\t\t\tthis.removeEntityInternal(descendantId);\n\t\t\t}\n\t\t} else {\n\t\t\t// Fire beforeEntityRemoved for just this entity\n\t\t\tfor (const hook of this._beforeEntityRemovedHooks) {\n\t\t\t\thook(entity.id);\n\t\t\t}\n\t\t}\n\n\t\treturn this.removeEntityInternal(entity.id);\n\t}\n\n\t/**\n\t * Internal method to remove a single entity without cascade logic\n\t */\n\tprivate removeEntityInternal(entityId: number): boolean {\n\t\tconst entity = this.entities.get(entityId);\n\t\tif (!entity) return false;\n\n\t\t// Clean up hierarchy\n\t\tthis.hierarchyManager.removeEntity(entityId);\n\n\t\t// Trigger disposal and removal callbacks for each component before removing the entity\n\t\tfor (const componentName of Object.keys(entity.components) as Array<keyof ComponentTypes>) {\n\t\t\tconst oldValue = entity.components[componentName];\n\n\t\t\tif (oldValue !== undefined) {\n\t\t\t\t// Invoke dispose before removal callbacks\n\t\t\t\tthis.invokeDispose(componentName, oldValue as ComponentTypes[keyof ComponentTypes], entity.id);\n\n\t\t\t\t// Trigger removed callbacks (index-based iteration; unsubscribe nulls slots, compacted after)\n\t\t\t\tconst removeCbs = this.removedCallbacks.get(componentName);\n\t\t\t\tif (removeCbs) {\n\t\t\t\t\tremoveCbs.invoke({ value: oldValue, entity });\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Remove entity from component indices\n\t\t\tthis.componentIndices.get(componentName)?.delete(entity.id);\n\t\t}\n\n\t\t// Clean up change sequences\n\t\tthis.changeSeqs.delete(entity.id);\n\n\t\t// Remove the entity itself\n\t\treturn this.entities.delete(entity.id);\n\t}\n\n\tgetEntity(entityId: number): Entity<ComponentTypes> | undefined {\n\t\treturn this.entities.get(entityId);\n\t}\n\n\t/**\n\t * Register a callback when a specific component is added to any entity\n\t * @param componentName The component key\n\t * @param handler Function receiving the new component value and the entity\n\t * @returns Unsubscribe function to remove the callback\n\t */\n\tonComponentAdded<ComponentName extends keyof ComponentTypes>(\n\t\tcomponentName: ComponentName,\n\t\thandler: (ctx: { value: ComponentTypes[ComponentName]; entity: Entity<ComponentTypes> }) => void\n\t): () => void {\n\t\tconst widened = handler as ComponentCallback<ComponentTypes>;\n\t\tlet list = this.addedCallbacks.get(componentName);\n\t\tif (!list) {\n\t\t\tlist = new CallbackList();\n\t\t\tthis.addedCallbacks.set(componentName, list);\n\t\t}\n\t\tlist.add(widened);\n\t\treturn () => {\n\t\t\tthis.addedCallbacks.get(componentName)?.remove(widened);\n\t\t};\n\t}\n\n\t/**\n\t * Register a callback when a specific component is removed from any entity\n\t * @param componentName The component key\n\t * @param handler Function receiving the old component value and the entity\n\t * @returns Unsubscribe function to remove the callback\n\t */\n\tonComponentRemoved<ComponentName extends keyof ComponentTypes>(\n\t\tcomponentName: ComponentName,\n\t\thandler: (ctx: { value: ComponentTypes[ComponentName]; entity: Entity<ComponentTypes> }) => void\n\t): () => void {\n\t\tconst widened = handler as ComponentCallback<ComponentTypes>;\n\t\tlet list = this.removedCallbacks.get(componentName);\n\t\tif (!list) {\n\t\t\tlist = new CallbackList();\n\t\t\tthis.removedCallbacks.set(componentName, list);\n\t\t}\n\t\tlist.add(widened);\n\t\treturn () => {\n\t\t\tthis.removedCallbacks.get(componentName)?.remove(widened);\n\t\t};\n\t}\n\n\t// ==================== Lifecycle Hook Registration ====================\n\n\tonAfterComponentAdded(hook: (entityId: number, componentName: keyof ComponentTypes) => void): () => void {\n\t\tthis._afterComponentAddedHooks.push(hook);\n\t\treturn () => {\n\t\t\tconst idx = this._afterComponentAddedHooks.indexOf(hook);\n\t\t\tif (idx !== -1) this._afterComponentAddedHooks.splice(idx, 1);\n\t\t};\n\t}\n\n\tonAfterEntityMutated(hook: (entityId: number) => void): () => void {\n\t\tthis._afterEntityMutatedHooks.push(hook);\n\t\treturn () => {\n\t\t\tconst idx = this._afterEntityMutatedHooks.indexOf(hook);\n\t\t\tif (idx !== -1) this._afterEntityMutatedHooks.splice(idx, 1);\n\t\t};\n\t}\n\n\tonAfterComponentRemoved(hook: (entityId: number, componentName: keyof ComponentTypes) => void): () => void {\n\t\tthis._afterComponentRemovedHooks.push(hook);\n\t\treturn () => {\n\t\t\tconst idx = this._afterComponentRemovedHooks.indexOf(hook);\n\t\t\tif (idx !== -1) this._afterComponentRemovedHooks.splice(idx, 1);\n\t\t};\n\t}\n\n\tonBeforeEntityRemoved(hook: (entityId: number) => void): () => void {\n\t\tthis._beforeEntityRemovedHooks.push(hook);\n\t\treturn () => {\n\t\t\tconst idx = this._beforeEntityRemovedHooks.indexOf(hook);\n\t\t\tif (idx !== -1) this._beforeEntityRemovedHooks.splice(idx, 1);\n\t\t};\n\t}\n\n\tonAfterParentChanged(hook: (childId: number) => void): () => void {\n\t\tthis._afterParentChangedHooks.push(hook);\n\t\treturn () => {\n\t\t\tconst idx = this._afterParentChangedHooks.indexOf(hook);\n\t\t\tif (idx !== -1) this._afterParentChangedHooks.splice(idx, 1);\n\t\t};\n\t}\n\n\t// ==================== Change Detection Methods ====================\n\n\t/**\n\t * The current monotonic change sequence value.\n\t * Each markChanged call increments this before stamping.\n\t */\n\tget changeSeq(): number {\n\t\treturn this._changeSeq;\n\t}\n\n\t/**\n\t * Mark a component as changed on an entity, stamping the next sequence number.\n\t * @param entityId The entity ID\n\t * @param componentName The component that changed\n\t */\n\tmarkChanged<K extends keyof ComponentTypes>(entityId: number, componentName: K): void {\n\t\tconst seq = ++this._changeSeq;\n\t\tlet entitySeqs = this.changeSeqs.get(entityId);\n\t\tif (!entitySeqs) {\n\t\t\tentitySeqs = new Map();\n\t\t\tthis.changeSeqs.set(entityId, entitySeqs);\n\t\t}\n\t\tentitySeqs.set(componentName, seq);\n\t}\n\n\t/**\n\t * Get the sequence number at which a component was last changed on an entity\n\t * @param entityId The entity ID\n\t * @param componentName The component to check\n\t * @returns The sequence number when last changed, or -1 if never changed\n\t */\n\tgetChangeSeq<K extends keyof ComponentTypes>(entityId: number, componentName: K): number {\n\t\treturn this.changeSeqs.get(entityId)?.get(componentName) ?? -1;\n\t}\n\n\t// ==================== Hierarchy Methods ====================\n\n\t/**\n\t * Create an entity as a child of another entity with initial components\n\t * @param parentId The parent entity ID\n\t * @param components Initial components to add\n\t * @returns The created child entity\n\t */\n\tspawnChild<T extends { [K in keyof ComponentTypes]?: ComponentTypes[K] }>(\n\t\tparentId: number,\n\t\tcomponents: T & Record<Exclude<keyof T, keyof ComponentTypes>, never>\n\t): FilteredEntity<ComponentTypes, keyof T & keyof ComponentTypes> {\n\t\tconst entity = this.createEntity();\n\t\tthis.addComponents(entity.id, components);\n\t\tthis.setParent(entity.id, parentId);\n\t\treturn entity as FilteredEntity<ComponentTypes, keyof T & keyof ComponentTypes>;\n\t}\n\n\t/**\n\t * Set the parent of an entity\n\t * @param childId The entity ID to set as a child\n\t * @param parentId The entity ID to set as the parent\n\t */\n\tsetParent(childId: number, parentId: number): this {\n\t\tthis.hierarchyManager.setParent(childId, parentId);\n\t\tfor (const hook of this._afterParentChangedHooks) {\n\t\t\thook(childId);\n\t\t}\n\t\treturn this;\n\t}\n\n\t/**\n\t * Remove the parent relationship for an entity (orphan it)\n\t * @param childId The entity ID to orphan\n\t * @returns true if a parent was removed, false if entity had no parent\n\t */\n\tremoveParent(childId: number): boolean {\n\t\tconst result = this.hierarchyManager.removeParent(childId);\n\t\tif (result) {\n\t\t\tfor (const hook of this._afterParentChangedHooks) {\n\t\t\t\thook(childId);\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}\n\n\t/**\n\t * Get the parent of an entity\n\t * @param entityId The entity ID to get the parent of\n\t * @returns The parent entity ID, or null if no parent\n\t */\n\tgetParent(entityId: number): number | null {\n\t\treturn this.hierarchyManager.getParent(entityId);\n\t}\n\n\t/**\n\t * Get all children of an entity in insertion order\n\t * @param parentId The parent entity ID\n\t * @returns Readonly array of child entity IDs\n\t */\n\tgetChildren(parentId: number): readonly number[] {\n\t\treturn this.hierarchyManager.getChildren(parentId);\n\t}\n\n\t/**\n\t * Get a child at a specific index\n\t * @param parentId The parent entity ID\n\t * @param index The index of the child\n\t * @returns The child entity ID, or null if index is out of bounds\n\t */\n\tgetChildAt(parentId: number, index: number): number | null {\n\t\treturn this.hierarchyManager.getChildAt(parentId, index);\n\t}\n\n\t/**\n\t * Get the index of a child within its parent's children list\n\t * @param parentId The parent entity ID\n\t * @param childId The child entity ID to find\n\t * @returns The index of the child, or -1 if not found\n\t */\n\tgetChildIndex(parentId: number, childId: number): number {\n\t\treturn this.hierarchyManager.getChildIndex(parentId, childId);\n\t}\n\n\t/**\n\t * Get all ancestors of an entity in order [parent, grandparent, ...]\n\t * @param entityId The entity ID to get ancestors of\n\t * @returns Readonly array of ancestor entity IDs\n\t */\n\tgetAncestors(entityId: number): readonly number[] {\n\t\treturn this.hierarchyManager.getAncestors(entityId);\n\t}\n\n\t/**\n\t * Get all descendants of an entity in depth-first order\n\t * @param entityId The entity ID to get descendants of\n\t * @returns Readonly array of descendant entity IDs\n\t */\n\tgetDescendants(entityId: number): readonly number[] {\n\t\treturn this.hierarchyManager.getDescendants(entityId);\n\t}\n\n\t/**\n\t * Get the root ancestor of an entity (topmost parent), or self if no parent\n\t * @param entityId The entity ID to get the root of\n\t * @returns The root entity ID\n\t */\n\tgetRoot(entityId: number): number {\n\t\treturn this.hierarchyManager.getRoot(entityId);\n\t}\n\n\t/**\n\t * Get siblings of an entity (other children of the same parent)\n\t * @param entityId The entity ID to get siblings of\n\t * @returns Readonly array of sibling entity IDs\n\t */\n\tgetSiblings(entityId: number): readonly number[] {\n\t\treturn this.hierarchyManager.getSiblings(entityId);\n\t}\n\n\t/**\n\t * Check if an entity is a descendant of another entity\n\t * @param entityId The potential descendant ID\n\t * @param ancestorId The potential ancestor ID\n\t * @returns true if entityId is a descendant of ancestorId\n\t */\n\tisDescendantOf(entityId: number, ancestorId: number): boolean {\n\t\treturn this.hierarchyManager.isDescendantOf(entityId, ancestorId);\n\t}\n\n\t/**\n\t * Check if an entity is an ancestor of another entity\n\t * @param entityId The potential ancestor ID\n\t * @param descendantId The potential descendant ID\n\t * @returns true if entityId is an ancestor of descendantId\n\t */\n\tisAncestorOf(entityId: number, descendantId: number): boolean {\n\t\treturn this.hierarchyManager.isAncestorOf(entityId, descendantId);\n\t}\n\n\t/**\n\t * Returns true when at least one parent-child relationship exists.\n\t */\n\tget hasHierarchy(): boolean {\n\t\treturn this.hierarchyManager.hasHierarchy;\n\t}\n\n\t/**\n\t * Get all root entities (entities that have children but no parent)\n\t * @returns Readonly array of root entity IDs\n\t */\n\tgetRootEntities(): readonly number[] {\n\t\treturn this.hierarchyManager.getRootEntities();\n\t}\n\n\t/**\n\t * Traverse the hierarchy in parent-first (breadth-first) order.\n\t * Parents are guaranteed to be visited before their children.\n\t * @param callback Function called for each entity with (entityId, parentId, depth)\n\t * @param options Optional traversal options (roots to filter to specific subtrees)\n\t */\n\tforEachInHierarchy(\n\t\tcallback: (entityId: number, parentId: number | null, depth: number) => void,\n\t\toptions?: HierarchyIteratorOptions\n\t): void {\n\t\tthis.hierarchyManager.forEachInHierarchy(callback, options);\n\t}\n\n\t/**\n\t * Generator-based hierarchy traversal in parent-first (breadth-first) order.\n\t * Supports early termination via break.\n\t * @param options Optional traversal options (roots to filter to specific subtrees)\n\t * @yields HierarchyEntry for each entity in parent-first order\n\t */\n\thierarchyIterator(options?: HierarchyIteratorOptions): Generator<HierarchyEntry, void, unknown> {\n\t\treturn this.hierarchyManager.hierarchyIterator(options);\n\t}\n}\n",
|
|
6
|
+
"import type { Entity } from \"./types\";\n\n/** Minimal lookup surface needed to evaluate `parentHas`. */\nexport interface MatchHost<ComponentTypes> {\n\tgetEntity(entityId: number): Entity<ComponentTypes> | undefined;\n\tgetParent(entityId: number): number | null;\n}\n\n/**\n * Returns true when `entity` matches the static portion of a query shape:\n * has every `with` component, no `without` component, and (if `parentHas`)\n * a direct parent that has every `parentHas` component. Shared between\n * QueryCache (membership maintenance) and ReactiveQueryManager (enter/exit\n * dispatch) so both use the same predicate.\n */\nexport function entityMatchesShape<ComponentTypes>(\n\tentity: Entity<ComponentTypes>,\n\twithC: ReadonlyArray<keyof ComponentTypes>,\n\twithoutC: ReadonlyArray<keyof ComponentTypes> | undefined,\n\tparentHas: ReadonlyArray<keyof ComponentTypes> | undefined,\n\thost: MatchHost<ComponentTypes>,\n): boolean {\n\tconst comps = entity.components as Record<keyof ComponentTypes, unknown>;\n\tfor (const c of withC) {\n\t\tif (!(c in comps)) return false;\n\t}\n\tif (withoutC) {\n\t\tfor (const c of withoutC) {\n\t\t\tif (c in comps) return false;\n\t\t}\n\t}\n\tif (parentHas && parentHas.length > 0) {\n\t\tconst parentId = host.getParent(entity.id);\n\t\tif (parentId === null) return false;\n\t\tconst parent = host.getEntity(parentId);\n\t\tif (!parent) return false;\n\t\tconst parentComps = parent.components as Record<keyof ComponentTypes, unknown>;\n\t\tfor (const c of parentHas) {\n\t\t\tif (!(c in parentComps)) return false;\n\t\t}\n\t}\n\treturn true;\n}\n",
|
|
7
|
+
"import type { Entity } from \"./types\";\nimport { entityMatchesShape, type MatchHost } from \"./query-match\";\n\n/**\n * Host interface that QueryCache uses to read EntityManager state.\n * Decouples QueryCache from EntityManager's private fields.\n */\nexport interface QueryCacheHost<ComponentTypes> extends MatchHost<ComponentTypes> {\n\tgetChildren(parentId: number): readonly number[];\n\tallEntities(): IterableIterator<Entity<ComponentTypes>>;\n\tcomponentIndex(component: keyof ComponentTypes): Set<number> | undefined;\n}\n\ninterface CacheEntry<ComponentTypes> {\n\twith: ReadonlyArray<keyof ComponentTypes>;\n\twithout: ReadonlyArray<keyof ComponentTypes>;\n\tparentHas: ReadonlyArray<keyof ComponentTypes>;\n\tmembers: Set<number>;\n}\n\nfunction makeKey(\n\twithC: ReadonlyArray<PropertyKey>,\n\twithoutC: ReadonlyArray<PropertyKey>,\n\tparentHas: ReadonlyArray<PropertyKey>,\n): string {\n\tconst a = withC.length === 0 ? '' : [...withC].map(String).sort().join(',');\n\tconst b = withoutC.length === 0 ? '' : [...withoutC].map(String).sort().join(',');\n\tconst c = parentHas.length === 0 ? '' : [...parentHas].map(String).sort().join(',');\n\treturn `${a}|${b}|${c}`;\n}\n\n/**\n * Maintains incrementally-updated Sets of entity IDs matching the static\n * portion of registered query shapes (with / without / parentHas).\n * EntityManager calls the on* hooks on component add/remove, entity\n * removal, and parent change. The `changed` filter is applied as a\n * post-pass by the caller, since its threshold advances each tick.\n */\nexport default class QueryCache<ComponentTypes> {\n\tprivate readonly host: QueryCacheHost<ComponentTypes>;\n\tprivate readonly caches: Map<string, CacheEntry<ComponentTypes>> = new Map();\n\tprivate readonly byComp: Map<keyof ComponentTypes, Array<CacheEntry<ComponentTypes>>> = new Map();\n\tprivate readonly byParentComp: Map<keyof ComponentTypes, Array<CacheEntry<ComponentTypes>>> = new Map();\n\n\tconstructor(host: QueryCacheHost<ComponentTypes>) {\n\t\tthis.host = host;\n\t}\n\n\t/**\n\t * Returns the Set of entity IDs matching the (with, without, parentHas)\n\t * shape. Caches are interned by canonical shape — identical shapes share\n\t * a single Set across systems. Cold-start populates by iterating the\n\t * smallest matching component index.\n\t */\n\tgetOrCreate(\n\t\twithC: ReadonlyArray<keyof ComponentTypes>,\n\t\twithoutC: ReadonlyArray<keyof ComponentTypes>,\n\t\tparentHas: ReadonlyArray<keyof ComponentTypes>,\n\t): Set<number> {\n\t\tconst key = makeKey(withC, withoutC, parentHas);\n\t\tconst existing = this.caches.get(key);\n\t\tif (existing) return existing.members;\n\n\t\tconst entry: CacheEntry<ComponentTypes> = {\n\t\t\twith: [...withC],\n\t\t\twithout: [...withoutC],\n\t\t\tparentHas: [...parentHas],\n\t\t\tmembers: new Set(),\n\t\t};\n\t\tthis.caches.set(key, entry);\n\n\t\tfor (const c of entry.with) pushTo(this.byComp, c, entry);\n\t\tfor (const c of entry.without) pushTo(this.byComp, c, entry);\n\t\tfor (const c of entry.parentHas) pushTo(this.byParentComp, c, entry);\n\n\t\tthis.populate(entry);\n\t\treturn entry.members;\n\t}\n\n\t/** Test-only: returns the number of distinct interned shapes. */\n\tget cacheCount(): number {\n\t\treturn this.caches.size;\n\t}\n\n\tprivate populate(entry: CacheEntry<ComponentTypes>): void {\n\t\tconst host = this.host;\n\t\tconst required = entry.with;\n\t\tif (required.length === 0) {\n\t\t\tfor (const e of host.allEntities()) {\n\t\t\t\tif (this.matches(e, entry)) entry.members.add(e.id);\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\tlet smallest = required[0];\n\t\tif (smallest === undefined) return;\n\t\tlet smallestSize = host.componentIndex(smallest)?.size ?? 0;\n\t\tfor (let i = 1; i < required.length; i++) {\n\t\t\tconst c = required[i];\n\t\t\tif (c === undefined) continue;\n\t\t\tconst s = host.componentIndex(c)?.size ?? 0;\n\t\t\tif (s < smallestSize) { smallest = c; smallestSize = s; }\n\t\t}\n\t\tconst candidates = host.componentIndex(smallest);\n\t\tif (!candidates || candidates.size === 0) return;\n\t\tfor (const id of candidates) {\n\t\t\tconst e = host.getEntity(id);\n\t\t\tif (!e) continue;\n\t\t\tif (this.matches(e, entry)) entry.members.add(id);\n\t\t}\n\t}\n\n\tprivate matches(entity: Entity<ComponentTypes>, entry: CacheEntry<ComponentTypes>): boolean {\n\t\treturn entityMatchesShape(entity, entry.with, entry.without, entry.parentHas, this.host);\n\t}\n\n\tprivate reeval(entityId: number, entry: CacheEntry<ComponentTypes>): void {\n\t\tconst e = this.host.getEntity(entityId);\n\t\tif (!e) {\n\t\t\tentry.members.delete(entityId);\n\t\t\treturn;\n\t\t}\n\t\tif (this.matches(e, entry)) {\n\t\t\tentry.members.add(entityId);\n\t\t} else {\n\t\t\tentry.members.delete(entityId);\n\t\t}\n\t}\n\n\tonComponentChanged(entityId: number, componentName: keyof ComponentTypes): void {\n\t\tconst direct = this.byComp.get(componentName);\n\t\tif (direct) {\n\t\t\tfor (const cache of direct) this.reeval(entityId, cache);\n\t\t}\n\t\tconst parentRel = this.byParentComp.get(componentName);\n\t\tif (parentRel && parentRel.length > 0) {\n\t\t\tconst children = this.host.getChildren(entityId);\n\t\t\tif (children.length > 0) {\n\t\t\t\tfor (const cache of parentRel) {\n\t\t\t\t\tfor (const childId of children) this.reeval(childId, cache);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tonParentChanged(childId: number): void {\n\t\tfor (const entry of this.caches.values()) {\n\t\t\tif (entry.parentHas.length > 0) this.reeval(childId, entry);\n\t\t}\n\t}\n\n\t/**\n\t * Drops the entity from every cache. For parentHas caches, also drops\n\t * direct children — once this entity is gone, the parent-link severs\n\t * and children stop matching. Cascade-removed children fire their own\n\t * beforeRemoved first, so the extra delete is a harmless no-op there.\n\t */\n\tonEntityRemoved(entityId: number): void {\n\t\tlet anyParentHas = false;\n\t\tfor (const entry of this.caches.values()) {\n\t\t\tentry.members.delete(entityId);\n\t\t\tif (entry.parentHas.length > 0) anyParentHas = true;\n\t\t}\n\t\tif (!anyParentHas) return;\n\t\tconst children = this.host.getChildren(entityId);\n\t\tif (children.length === 0) return;\n\t\tfor (const entry of this.caches.values()) {\n\t\t\tif (entry.parentHas.length === 0) continue;\n\t\t\tfor (const cid of children) entry.members.delete(cid);\n\t\t}\n\t}\n}\n\nfunction pushTo<K, V>(map: Map<K, V[]>, key: K, value: V): void {\n\tconst existing = map.get(key);\n\tif (existing) {\n\t\texisting.push(value);\n\t} else {\n\t\tmap.set(key, [value]);\n\t}\n}\n",
|
|
8
|
+
"import type { Entity, FilteredEntity, RemoveEntityOptions, HierarchyEntry, HierarchyIteratorOptions } from \"./types\";\nimport HierarchyManager from \"./hierarchy-manager\";\nimport QueryCache from \"./query-cache\";\n\n/** Returns true if any component in `changed` was modified after `threshold`. */\nfunction hasChangedComponent(\n\tentitySeqs: Map<string | number | symbol, number> | undefined,\n\tchanged: ReadonlyArray<string | number | symbol>,\n\tthreshold: number,\n): boolean {\n\tif (!entitySeqs) return false;\n\tfor (const key of changed) {\n\t\tif ((entitySeqs.get(key) ?? -1) > threshold) return true;\n\t}\n\treturn false;\n}\n\ntype ComponentCallback<ComponentTypes> = (ctx: { value: unknown; entity: Entity<ComponentTypes> }) => void;\n\n/**\n * Manages zero-allocation callback iteration with safe mid-iteration unsubscribe.\n * During iteration, unsubscribes are deferred. Snapshot length guarantees all\n * callbacks registered at call time execute. Compaction runs when iteration ends.\n */\nclass CallbackList<ComponentTypes> {\n\tprivate readonly callbacks: ComponentCallback<ComponentTypes>[] = [];\n\tprivate _iterDepth = 0;\n\tprivate _pendingRemovals: ComponentCallback<ComponentTypes>[] = [];\n\n\tadd(cb: ComponentCallback<ComponentTypes>): void {\n\t\tthis.callbacks.push(cb);\n\t}\n\n\tremove(cb: ComponentCallback<ComponentTypes>): void {\n\t\tif (this._iterDepth > 0) {\n\t\t\tthis._pendingRemovals.push(cb);\n\t\t\treturn;\n\t\t}\n\t\tconst idx = this.callbacks.indexOf(cb);\n\t\tif (idx !== -1) this.callbacks.splice(idx, 1);\n\t}\n\n\tinvoke(ctx: { value: unknown; entity: Entity<ComponentTypes> }): void {\n\t\tthis._iterDepth++;\n\t\tconst len = this.callbacks.length;\n\t\tfor (let i = 0; i < len; i++) {\n\t\t\tconst cb = this.callbacks[i];\n\t\t\tif (cb) cb(ctx);\n\t\t}\n\t\tthis._iterDepth--;\n\t\tif (this._iterDepth === 0 && this._pendingRemovals.length > 0) {\n\t\t\tfor (const cb of this._pendingRemovals) {\n\t\t\t\tconst idx = this.callbacks.indexOf(cb);\n\t\t\t\tif (idx !== -1) this.callbacks.splice(idx, 1);\n\t\t\t}\n\t\t\tthis._pendingRemovals.length = 0;\n\t\t}\n\t}\n}\n\nexport default\nclass EntityManager<ComponentTypes> {\n\tprivate nextId: number = 1;\n\tprivate entities: Map<number, Entity<ComponentTypes>> = new Map();\n\tprivate componentIndices: Map<keyof ComponentTypes, Set<number>> = new Map();\n\t/**\n\t * Callbacks registered for component additions\n\t */\n\tprivate addedCallbacks: Map<keyof ComponentTypes, CallbackList<ComponentTypes>> = new Map();\n\t/**\n\t * Callbacks registered for component removals\n\t */\n\tprivate removedCallbacks: Map<keyof ComponentTypes, CallbackList<ComponentTypes>> = new Map();\n\t/**\n\t * Hierarchy manager for parent-child relationships\n\t */\n\tprivate hierarchyManager: HierarchyManager = new HierarchyManager();\n\t/**\n\t * Per-type component dispose callbacks.\n\t * Called when a component is removed (explicit removal, entity destruction, or replacement).\n\t */\n\tprivate disposeCallbacks: Map<keyof ComponentTypes, (ctx: { value: unknown; entityId: number }) => void> = new Map();\n\t/**\n\t * Per-entity per-component change sequence tracking.\n\t * Maps entityId -> (componentName -> sequence number when last changed)\n\t */\n\tprivate changeSeqs: Map<number, Map<keyof ComponentTypes, number>> = new Map();\n\t/**\n\t * Monotonic sequence counter for change detection.\n\t * Each markChanged call increments this and stamps the new value.\n\t */\n\tprivate _changeSeq: number = 0;\n\n\t// ==================== Lifecycle Hook Arrays ====================\n\tprivate _afterComponentAddedHooks: Array<(entityId: number, componentName: keyof ComponentTypes) => void> = [];\n\tprivate _afterEntityMutatedHooks: Array<(entityId: number) => void> = [];\n\tprivate _afterComponentRemovedHooks: Array<(entityId: number, componentName: keyof ComponentTypes) => void> = [];\n\tprivate _beforeEntityRemovedHooks: Array<(entityId: number) => void> = [];\n\tprivate _afterParentChangedHooks: Array<(childId: number) => void> = [];\n\n\t/**\n\t * Incrementally-maintained query result cache. Caches the static portion\n\t * (with / without / parentHas) of each registered query shape and is\n\t * updated via the lifecycle hook arrays above. Lazily created on the\n\t * first cacheable query lookup.\n\t */\n\tprivate readonly _queryCache: QueryCache<ComponentTypes> = new QueryCache<ComponentTypes>({\n\t\tgetEntity: (id) => this.entities.get(id),\n\t\tgetParent: (id) => this.hierarchyManager.getParent(id),\n\t\tgetChildren: (id) => this.hierarchyManager.getChildren(id),\n\t\tallEntities: () => this.entities.values(),\n\t\tcomponentIndex: (c) => this.componentIndices.get(c),\n\t});\n\n\t// ==================== Batching Fields ====================\n\tprivate _batchingDepth: number = 0;\n\tprivate _batchedEntityIds: Set<number> = new Set();\n\t/** Component keys being added in the current addComponents batch, if any.\n\t * Used by required component resolution to skip auto-adding explicitly provided components. */\n\t_pendingBatchKeys: ReadonlySet<keyof ComponentTypes> | null = null;\n\n\tget entityCount(): number {\n\t\treturn this.entities.size;\n\t}\n\n\tcreateEntity(): Entity<ComponentTypes> {\n\t\tconst id = this.nextId++;\n\t\tconst entity: Entity<ComponentTypes> = { id, components: {} };\n\t\tthis.entities.set(id, entity);\n\t\treturn entity;\n\t}\n\n\t/**\n\t * Register a dispose callback for a component type.\n\t * Called when a component is removed (explicit removal, entity destruction, or replacement).\n\t * Later registrations replace earlier ones for the same component type.\n\t * @param componentName The component type to register disposal for\n\t * @param callback Function receiving the component value being disposed and the entity ID\n\t */\n\tregisterDispose<ComponentName extends keyof ComponentTypes>(\n\t\tcomponentName: ComponentName,\n\t\tcallback: (ctx: { value: ComponentTypes[ComponentName]; entityId: number }) => void\n\t): void {\n\t\tthis.disposeCallbacks.set(componentName, callback as (ctx: { value: unknown; entityId: number }) => void);\n\t}\n\n\t/**\n\t * Get all registered dispose callbacks.\n\t * @internal Used by ECSpresso for plugin installation\n\t */\n\tgetDisposeCallbacks(): Map<keyof ComponentTypes, (ctx: { value: unknown; entityId: number }) => void> {\n\t\treturn this.disposeCallbacks;\n\t}\n\n\t/**\n\t * Invoke the dispose callback for a component, if registered.\n\t * Errors are caught and logged to prevent blocking removal.\n\t */\n\tprivate invokeDispose<ComponentName extends keyof ComponentTypes>(\n\t\tcomponentName: ComponentName,\n\t\tvalue: ComponentTypes[ComponentName],\n\t\tentityId: number\n\t): void {\n\t\tconst cb = this.disposeCallbacks.get(componentName);\n\t\tif (!cb) return;\n\t\ttry {\n\t\t\tcb({ value, entityId });\n\t\t} catch (error) {\n\t\t\tconsole.warn(`Component dispose callback for '${String(componentName)}' threw:`, error);\n\t\t}\n\t}\n\n\t// TODO: Component object pooling if(/when) garbage collection is an issue...?\n\taddComponent<ComponentName extends keyof ComponentTypes>(\n\t\tentityId: number,\n\t\tcomponentName: ComponentName,\n\t\tdata: ComponentTypes[ComponentName]\n\t) {\n\t\tconst entity = this.entities.get(entityId);\n\n\t\tif (!entity) {\n\t\t\tthrow new Error(`Cannot add component '${String(componentName)}': Entity with ID ${entityId} does not exist`);\n\t\t}\n\n\t\t// Dispose old value if replacing an existing component\n\t\tconst existing = entity.components[componentName];\n\t\tif (existing !== undefined) {\n\t\t\tthis.invokeDispose(componentName, existing as ComponentTypes[ComponentName], entity.id);\n\t\t}\n\n\t\tentity.components[componentName] = data;\n\n\t\t// Update component index\n\t\tif (!this.componentIndices.has(componentName)) {\n\t\t\tthis.componentIndices.set(componentName, new Set());\n\t\t}\n\t\tthis.componentIndices.get(componentName)?.add(entity.id);\n\t\t// Trigger added callbacks (index-based iteration; unsubscribe nulls slots, compacted after)\n\t\tconst callbacks = this.addedCallbacks.get(componentName);\n\t\tif (callbacks) {\n\t\t\tcallbacks.invoke({ value: data, entity });\n\t\t}\n\n\t\t// Update query cache before user hooks so any hook-driven query sees fresh state\n\t\tthis._queryCache.onComponentChanged(entity.id, componentName);\n\n\t\t// Fire afterComponentAdded hooks (may trigger recursive addComponent)\n\t\tthis._batchingDepth++;\n\t\tfor (const hook of this._afterComponentAddedHooks) {\n\t\t\thook(entity.id, componentName);\n\t\t}\n\t\tthis._batchedEntityIds.add(entity.id);\n\t\tthis._batchingDepth--;\n\n\t\t// Flush afterEntityMutated when outermost batch completes\n\t\tif (this._batchingDepth === 0) {\n\t\t\tfor (const entityId of this._batchedEntityIds) {\n\t\t\t\tfor (const hook of this._afterEntityMutatedHooks) {\n\t\t\t\t\thook(entityId);\n\t\t\t\t}\n\t\t\t}\n\t\t\tthis._batchedEntityIds.clear();\n\t\t}\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Add multiple components to an entity at once\n\t * @param entityId Entity ID to add components to\n\t * @param components Object with component names as keys and component data as values\n\t */\n\taddComponents<\n\t\tT extends { [K in keyof ComponentTypes]?: ComponentTypes[K] }\n\t>(\n\t\tentityId: number,\n\t\tcomponents: T & Record<Exclude<keyof T, keyof ComponentTypes>, never>\n\t) {\n\t\tconst entity = this.entities.get(entityId);\n\n\t\tif (!entity) {\n\t\t\tthrow new Error(`Cannot add components: Entity with ID ${entityId} does not exist`);\n\t\t}\n\n\t\tconst outerPending = this._pendingBatchKeys;\n\t\tthis._pendingBatchKeys = new Set(Object.keys(components) as (keyof ComponentTypes)[]);\n\t\tthis._batchingDepth++;\n\t\tfor (const componentName in components) {\n\t\t\tthis.addComponent(\n\t\t\t\tentity.id,\n\t\t\t\tcomponentName as keyof ComponentTypes,\n\t\t\t\tcomponents[componentName as keyof T] as ComponentTypes[keyof ComponentTypes]\n\t\t\t);\n\t\t}\n\t\tthis._batchingDepth--;\n\t\tthis._pendingBatchKeys = outerPending;\n\n\t\tif (this._batchingDepth === 0) {\n\t\t\tfor (const entityId of this._batchedEntityIds) {\n\t\t\t\tfor (const hook of this._afterEntityMutatedHooks) {\n\t\t\t\t\thook(entityId);\n\t\t\t\t}\n\t\t\t}\n\t\t\tthis._batchedEntityIds.clear();\n\t\t}\n\n\t\treturn this;\n\t}\n\n\tremoveComponent<ComponentName extends keyof ComponentTypes>(\n\t\tentityId: number,\n\t\tcomponentName: ComponentName\n\t) {\n\t\tconst entity = this.entities.get(entityId);\n\n\t\tif (!entity) {\n\t\t\tthrow new Error(`Cannot remove component '${String(componentName)}': Entity with ID ${entityId} does not exist`);\n\t\t}\n\t\t// Get old value for callbacks\n\t\tconst oldValue = entity.components[componentName] as ComponentTypes[ComponentName] | undefined;\n\n\t\t// Invoke dispose before deletion and removal callbacks\n\t\tif (oldValue !== undefined) {\n\t\t\tthis.invokeDispose(componentName, oldValue, entity.id);\n\t\t}\n\n\t\tdelete entity.components[componentName];\n\n\t\t// Trigger removed callbacks (index-based iteration; unsubscribe nulls slots, compacted after)\n\t\tconst removeCbs = this.removedCallbacks.get(componentName);\n\t\tif (removeCbs && oldValue !== undefined) {\n\t\t\tremoveCbs.invoke({ value: oldValue, entity });\n\t\t}\n\n\t\t// Update component index\n\t\tthis.componentIndices.get(componentName)?.delete(entity.id);\n\n\t\t// Fire afterComponentRemoved hooks (only if component was present)\n\t\tif (oldValue !== undefined) {\n\t\t\tthis._queryCache.onComponentChanged(entity.id, componentName);\n\t\t\tfor (const hook of this._afterComponentRemovedHooks) {\n\t\t\t\thook(entity.id, componentName);\n\t\t\t}\n\t\t}\n\n\t\treturn this;\n\t}\n\n\tgetComponent<ComponentName extends keyof ComponentTypes>(entityId: number, componentName: ComponentName): ComponentTypes[ComponentName] | undefined {\n\t\treturn this.entities.get(entityId)?.components[componentName];\n\t}\n\n\tgetEntitiesWithQuery<\n\t\tWithComponents extends keyof ComponentTypes = never,\n\t\tWithoutComponents extends keyof ComponentTypes = never\n\t>(\n\t\trequired: ReadonlyArray<WithComponents> = [],\n\t\texcluded: ReadonlyArray<WithoutComponents> = [],\n\t\tchanged?: ReadonlyArray<keyof ComponentTypes>,\n\t\tchangeThreshold?: number,\n\t\tparentHas?: ReadonlyArray<keyof ComponentTypes>,\n\t): Array<FilteredEntity<ComponentTypes, WithComponents extends never ? never : WithComponents, WithoutComponents extends never ? never : WithoutComponents>> {\n\t\treturn this.getEntitiesWithQueryInto([], required, excluded, changed, changeThreshold, parentHas);\n\t}\n\n\t/**\n\t * Fill an existing array with entities matching the query, clearing it first.\n\t * Returns the same array reference for convenience.\n\t */\n\tgetEntitiesWithQueryInto<\n\t\tWithComponents extends keyof ComponentTypes = never,\n\t\tWithoutComponents extends keyof ComponentTypes = never\n\t>(\n\t\toutput: Array<FilteredEntity<ComponentTypes, WithComponents extends never ? never : WithComponents, WithoutComponents extends never ? never : WithoutComponents>>,\n\t\trequired: ReadonlyArray<WithComponents> = [],\n\t\texcluded: ReadonlyArray<WithoutComponents> = [],\n\t\tchanged?: ReadonlyArray<keyof ComponentTypes>,\n\t\tchangeThreshold?: number,\n\t\tparentHas?: ReadonlyArray<keyof ComponentTypes>,\n\t): Array<FilteredEntity<ComponentTypes, WithComponents extends never ? never : WithComponents, WithoutComponents extends never ? never : WithoutComponents>> {\n\t\toutput.length = 0;\n\n\t\tconst hasChangedFilter = changed !== undefined && changed.length > 0 && changeThreshold !== undefined;\n\n\t\t// Runtime query filtering guarantees WithComponents/WithoutComponents constraints,\n\t\t// but TypeScript can't narrow Entity<CT> to FilteredEntity from imperative logic.\n\t\ttype ResultEntry = FilteredEntity<ComponentTypes, WithComponents extends never ? never : WithComponents, WithoutComponents extends never ? never : WithoutComponents>;\n\n\t\t// Empty static shape: walk all entities. Cheaper than maintaining a\n\t\t// cache that mirrors the entity set.\n\t\tconst hasParentHasFilter = parentHas !== undefined && parentHas.length > 0;\n\t\tif (required.length === 0 && excluded.length === 0 && !hasParentHasFilter) {\n\t\t\tif (!hasChangedFilter) {\n\t\t\t\tfor (const entity of this.entities.values()) {\n\t\t\t\t\toutput.push(entity as unknown as ResultEntry);\n\t\t\t\t}\n\t\t\t\treturn output;\n\t\t\t}\n\t\t\tfor (const entity of this.entities.values()) {\n\t\t\t\tif (!hasChangedComponent(this.changeSeqs.get(entity.id), changed, changeThreshold)) continue;\n\t\t\t\toutput.push(entity as unknown as ResultEntry);\n\t\t\t}\n\t\t\treturn output;\n\t\t}\n\n\t\tconst members = this._queryCache.getOrCreate(\n\t\t\trequired as ReadonlyArray<keyof ComponentTypes>,\n\t\t\texcluded as ReadonlyArray<keyof ComponentTypes>,\n\t\t\t(parentHas ?? []) as ReadonlyArray<keyof ComponentTypes>,\n\t\t);\n\n\t\tif (members.size === 0) return output;\n\n\t\tif (hasChangedFilter) {\n\t\t\tfor (const id of members) {\n\t\t\t\tif (!hasChangedComponent(this.changeSeqs.get(id), changed, changeThreshold)) continue;\n\t\t\t\tconst entity = this.entities.get(id);\n\t\t\t\tif (!entity) continue;\n\t\t\t\toutput.push(entity as unknown as ResultEntry);\n\t\t\t}\n\t\t\treturn output;\n\t\t}\n\n\t\tfor (const id of members) {\n\t\t\tconst entity = this.entities.get(id);\n\t\t\tif (!entity) continue;\n\t\t\toutput.push(entity as unknown as ResultEntry);\n\t\t}\n\n\t\treturn output;\n\t}\n\n\t/** Test-only accessor for the internal query cache. @internal */\n\tget _queryCacheForTesting(): QueryCache<ComponentTypes> {\n\t\treturn this._queryCache;\n\t}\n\n\tremoveEntity(entityId: number, options?: RemoveEntityOptions): boolean {\n\t\tconst entity = this.entities.get(entityId);\n\n\t\tif (!entity) return false;\n\n\t\tconst cascade = options?.cascade ?? true;\n\n\t\tif (cascade) {\n\t\t\t// Get all descendants first (depth-first order)\n\t\t\tconst descendants = this.hierarchyManager.getDescendants(entity.id);\n\t\t\t// Fire beforeEntityRemoved for descendants (reverse: children before parents)\n\t\t\tfor (let i = descendants.length - 1; i >= 0; i--) {\n\t\t\t\tconst descendantId = descendants[i];\n\t\t\t\tif (descendantId === undefined) continue;\n\t\t\t\tthis._queryCache.onEntityRemoved(descendantId);\n\t\t\t\tfor (const hook of this._beforeEntityRemovedHooks) {\n\t\t\t\t\thook(descendantId);\n\t\t\t\t}\n\t\t\t}\n\t\t\t// Fire beforeEntityRemoved for the entity itself\n\t\t\tthis._queryCache.onEntityRemoved(entity.id);\n\t\t\tfor (const hook of this._beforeEntityRemovedHooks) {\n\t\t\t\thook(entity.id);\n\t\t\t}\n\t\t\t// Now do actual removal (descendants in reverse order)\n\t\t\tfor (let i = descendants.length - 1; i >= 0; i--) {\n\t\t\t\tconst descendantId = descendants[i];\n\t\t\t\tif (descendantId === undefined) continue;\n\t\t\t\tthis.removeEntityInternal(descendantId);\n\t\t\t}\n\t\t} else {\n\t\t\t// Fire beforeEntityRemoved for just this entity\n\t\t\tthis._queryCache.onEntityRemoved(entity.id);\n\t\t\tfor (const hook of this._beforeEntityRemovedHooks) {\n\t\t\t\thook(entity.id);\n\t\t\t}\n\t\t}\n\n\t\treturn this.removeEntityInternal(entity.id);\n\t}\n\n\t/**\n\t * Internal method to remove a single entity without cascade logic\n\t */\n\tprivate removeEntityInternal(entityId: number): boolean {\n\t\tconst entity = this.entities.get(entityId);\n\t\tif (!entity) return false;\n\n\t\t// Clean up hierarchy\n\t\tthis.hierarchyManager.removeEntity(entityId);\n\n\t\t// Trigger disposal and removal callbacks for each component before removing the entity\n\t\tfor (const componentName of Object.keys(entity.components) as Array<keyof ComponentTypes>) {\n\t\t\tconst oldValue = entity.components[componentName];\n\n\t\t\tif (oldValue !== undefined) {\n\t\t\t\t// Invoke dispose before removal callbacks\n\t\t\t\tthis.invokeDispose(componentName, oldValue as ComponentTypes[keyof ComponentTypes], entity.id);\n\n\t\t\t\t// Trigger removed callbacks (index-based iteration; unsubscribe nulls slots, compacted after)\n\t\t\t\tconst removeCbs = this.removedCallbacks.get(componentName);\n\t\t\t\tif (removeCbs) {\n\t\t\t\t\tremoveCbs.invoke({ value: oldValue, entity });\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Remove entity from component indices\n\t\t\tthis.componentIndices.get(componentName)?.delete(entity.id);\n\t\t}\n\n\t\t// Clean up change sequences\n\t\tthis.changeSeqs.delete(entity.id);\n\n\t\t// Remove the entity itself\n\t\treturn this.entities.delete(entity.id);\n\t}\n\n\tgetEntity(entityId: number): Entity<ComponentTypes> | undefined {\n\t\treturn this.entities.get(entityId);\n\t}\n\n\t/**\n\t * Register a callback when a specific component is added to any entity\n\t * @param componentName The component key\n\t * @param handler Function receiving the new component value and the entity\n\t * @returns Unsubscribe function to remove the callback\n\t */\n\tonComponentAdded<ComponentName extends keyof ComponentTypes>(\n\t\tcomponentName: ComponentName,\n\t\thandler: (ctx: { value: ComponentTypes[ComponentName]; entity: Entity<ComponentTypes> }) => void\n\t): () => void {\n\t\tconst widened = handler as ComponentCallback<ComponentTypes>;\n\t\tlet list = this.addedCallbacks.get(componentName);\n\t\tif (!list) {\n\t\t\tlist = new CallbackList();\n\t\t\tthis.addedCallbacks.set(componentName, list);\n\t\t}\n\t\tlist.add(widened);\n\t\treturn () => {\n\t\t\tthis.addedCallbacks.get(componentName)?.remove(widened);\n\t\t};\n\t}\n\n\t/**\n\t * Register a callback when a specific component is removed from any entity\n\t * @param componentName The component key\n\t * @param handler Function receiving the old component value and the entity\n\t * @returns Unsubscribe function to remove the callback\n\t */\n\tonComponentRemoved<ComponentName extends keyof ComponentTypes>(\n\t\tcomponentName: ComponentName,\n\t\thandler: (ctx: { value: ComponentTypes[ComponentName]; entity: Entity<ComponentTypes> }) => void\n\t): () => void {\n\t\tconst widened = handler as ComponentCallback<ComponentTypes>;\n\t\tlet list = this.removedCallbacks.get(componentName);\n\t\tif (!list) {\n\t\t\tlist = new CallbackList();\n\t\t\tthis.removedCallbacks.set(componentName, list);\n\t\t}\n\t\tlist.add(widened);\n\t\treturn () => {\n\t\t\tthis.removedCallbacks.get(componentName)?.remove(widened);\n\t\t};\n\t}\n\n\t// ==================== Lifecycle Hook Registration ====================\n\n\tonAfterComponentAdded(hook: (entityId: number, componentName: keyof ComponentTypes) => void): () => void {\n\t\tthis._afterComponentAddedHooks.push(hook);\n\t\treturn () => {\n\t\t\tconst idx = this._afterComponentAddedHooks.indexOf(hook);\n\t\t\tif (idx !== -1) this._afterComponentAddedHooks.splice(idx, 1);\n\t\t};\n\t}\n\n\tonAfterEntityMutated(hook: (entityId: number) => void): () => void {\n\t\tthis._afterEntityMutatedHooks.push(hook);\n\t\treturn () => {\n\t\t\tconst idx = this._afterEntityMutatedHooks.indexOf(hook);\n\t\t\tif (idx !== -1) this._afterEntityMutatedHooks.splice(idx, 1);\n\t\t};\n\t}\n\n\tonAfterComponentRemoved(hook: (entityId: number, componentName: keyof ComponentTypes) => void): () => void {\n\t\tthis._afterComponentRemovedHooks.push(hook);\n\t\treturn () => {\n\t\t\tconst idx = this._afterComponentRemovedHooks.indexOf(hook);\n\t\t\tif (idx !== -1) this._afterComponentRemovedHooks.splice(idx, 1);\n\t\t};\n\t}\n\n\tonBeforeEntityRemoved(hook: (entityId: number) => void): () => void {\n\t\tthis._beforeEntityRemovedHooks.push(hook);\n\t\treturn () => {\n\t\t\tconst idx = this._beforeEntityRemovedHooks.indexOf(hook);\n\t\t\tif (idx !== -1) this._beforeEntityRemovedHooks.splice(idx, 1);\n\t\t};\n\t}\n\n\tonAfterParentChanged(hook: (childId: number) => void): () => void {\n\t\tthis._afterParentChangedHooks.push(hook);\n\t\treturn () => {\n\t\t\tconst idx = this._afterParentChangedHooks.indexOf(hook);\n\t\t\tif (idx !== -1) this._afterParentChangedHooks.splice(idx, 1);\n\t\t};\n\t}\n\n\t// ==================== Change Detection Methods ====================\n\n\t/**\n\t * The current monotonic change sequence value.\n\t * Each markChanged call increments this before stamping.\n\t */\n\tget changeSeq(): number {\n\t\treturn this._changeSeq;\n\t}\n\n\t/**\n\t * Mark a component as changed on an entity, stamping the next sequence number.\n\t * @param entityId The entity ID\n\t * @param componentName The component that changed\n\t */\n\tmarkChanged<K extends keyof ComponentTypes>(entityId: number, componentName: K): void {\n\t\tconst seq = ++this._changeSeq;\n\t\tlet entitySeqs = this.changeSeqs.get(entityId);\n\t\tif (!entitySeqs) {\n\t\t\tentitySeqs = new Map();\n\t\t\tthis.changeSeqs.set(entityId, entitySeqs);\n\t\t}\n\t\tentitySeqs.set(componentName, seq);\n\t}\n\n\t/**\n\t * Get the sequence number at which a component was last changed on an entity\n\t * @param entityId The entity ID\n\t * @param componentName The component to check\n\t * @returns The sequence number when last changed, or -1 if never changed\n\t */\n\tgetChangeSeq<K extends keyof ComponentTypes>(entityId: number, componentName: K): number {\n\t\treturn this.changeSeqs.get(entityId)?.get(componentName) ?? -1;\n\t}\n\n\t// ==================== Hierarchy Methods ====================\n\n\t/**\n\t * Create an entity as a child of another entity with initial components\n\t * @param parentId The parent entity ID\n\t * @param components Initial components to add\n\t * @returns The created child entity\n\t */\n\tspawnChild<T extends { [K in keyof ComponentTypes]?: ComponentTypes[K] }>(\n\t\tparentId: number,\n\t\tcomponents: T & Record<Exclude<keyof T, keyof ComponentTypes>, never>\n\t): FilteredEntity<ComponentTypes, keyof T & keyof ComponentTypes> {\n\t\tconst entity = this.createEntity();\n\t\tthis.addComponents(entity.id, components);\n\t\tthis.setParent(entity.id, parentId);\n\t\treturn entity as FilteredEntity<ComponentTypes, keyof T & keyof ComponentTypes>;\n\t}\n\n\t/**\n\t * Set the parent of an entity\n\t * @param childId The entity ID to set as a child\n\t * @param parentId The entity ID to set as the parent\n\t */\n\tsetParent(childId: number, parentId: number): this {\n\t\tthis.hierarchyManager.setParent(childId, parentId);\n\t\tthis._queryCache.onParentChanged(childId);\n\t\tfor (const hook of this._afterParentChangedHooks) {\n\t\t\thook(childId);\n\t\t}\n\t\treturn this;\n\t}\n\n\t/**\n\t * Remove the parent relationship for an entity (orphan it)\n\t * @param childId The entity ID to orphan\n\t * @returns true if a parent was removed, false if entity had no parent\n\t */\n\tremoveParent(childId: number): boolean {\n\t\tconst result = this.hierarchyManager.removeParent(childId);\n\t\tif (result) {\n\t\t\tthis._queryCache.onParentChanged(childId);\n\t\t\tfor (const hook of this._afterParentChangedHooks) {\n\t\t\t\thook(childId);\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}\n\n\t/**\n\t * Get the parent of an entity\n\t * @param entityId The entity ID to get the parent of\n\t * @returns The parent entity ID, or null if no parent\n\t */\n\tgetParent(entityId: number): number | null {\n\t\treturn this.hierarchyManager.getParent(entityId);\n\t}\n\n\t/**\n\t * Get all children of an entity in insertion order\n\t * @param parentId The parent entity ID\n\t * @returns Readonly array of child entity IDs\n\t */\n\tgetChildren(parentId: number): readonly number[] {\n\t\treturn this.hierarchyManager.getChildren(parentId);\n\t}\n\n\t/**\n\t * Get a child at a specific index\n\t * @param parentId The parent entity ID\n\t * @param index The index of the child\n\t * @returns The child entity ID, or null if index is out of bounds\n\t */\n\tgetChildAt(parentId: number, index: number): number | null {\n\t\treturn this.hierarchyManager.getChildAt(parentId, index);\n\t}\n\n\t/**\n\t * Get the index of a child within its parent's children list\n\t * @param parentId The parent entity ID\n\t * @param childId The child entity ID to find\n\t * @returns The index of the child, or -1 if not found\n\t */\n\tgetChildIndex(parentId: number, childId: number): number {\n\t\treturn this.hierarchyManager.getChildIndex(parentId, childId);\n\t}\n\n\t/**\n\t * Get all ancestors of an entity in order [parent, grandparent, ...]\n\t * @param entityId The entity ID to get ancestors of\n\t * @returns Readonly array of ancestor entity IDs\n\t */\n\tgetAncestors(entityId: number): readonly number[] {\n\t\treturn this.hierarchyManager.getAncestors(entityId);\n\t}\n\n\t/**\n\t * Get all descendants of an entity in depth-first order\n\t * @param entityId The entity ID to get descendants of\n\t * @returns Readonly array of descendant entity IDs\n\t */\n\tgetDescendants(entityId: number): readonly number[] {\n\t\treturn this.hierarchyManager.getDescendants(entityId);\n\t}\n\n\t/**\n\t * Get the root ancestor of an entity (topmost parent), or self if no parent\n\t * @param entityId The entity ID to get the root of\n\t * @returns The root entity ID\n\t */\n\tgetRoot(entityId: number): number {\n\t\treturn this.hierarchyManager.getRoot(entityId);\n\t}\n\n\t/**\n\t * Get siblings of an entity (other children of the same parent)\n\t * @param entityId The entity ID to get siblings of\n\t * @returns Readonly array of sibling entity IDs\n\t */\n\tgetSiblings(entityId: number): readonly number[] {\n\t\treturn this.hierarchyManager.getSiblings(entityId);\n\t}\n\n\t/**\n\t * Check if an entity is a descendant of another entity\n\t * @param entityId The potential descendant ID\n\t * @param ancestorId The potential ancestor ID\n\t * @returns true if entityId is a descendant of ancestorId\n\t */\n\tisDescendantOf(entityId: number, ancestorId: number): boolean {\n\t\treturn this.hierarchyManager.isDescendantOf(entityId, ancestorId);\n\t}\n\n\t/**\n\t * Check if an entity is an ancestor of another entity\n\t * @param entityId The potential ancestor ID\n\t * @param descendantId The potential descendant ID\n\t * @returns true if entityId is an ancestor of descendantId\n\t */\n\tisAncestorOf(entityId: number, descendantId: number): boolean {\n\t\treturn this.hierarchyManager.isAncestorOf(entityId, descendantId);\n\t}\n\n\t/**\n\t * Returns true when at least one parent-child relationship exists.\n\t */\n\tget hasHierarchy(): boolean {\n\t\treturn this.hierarchyManager.hasHierarchy;\n\t}\n\n\t/**\n\t * Get all root entities (entities that have children but no parent)\n\t * @returns Readonly array of root entity IDs\n\t */\n\tgetRootEntities(): readonly number[] {\n\t\treturn this.hierarchyManager.getRootEntities();\n\t}\n\n\t/**\n\t * Traverse the hierarchy in parent-first (breadth-first) order.\n\t * Parents are guaranteed to be visited before their children.\n\t * @param callback Function called for each entity with (entityId, parentId, depth)\n\t * @param options Optional traversal options (roots to filter to specific subtrees)\n\t */\n\tforEachInHierarchy(\n\t\tcallback: (entityId: number, parentId: number | null, depth: number) => void,\n\t\toptions?: HierarchyIteratorOptions\n\t): void {\n\t\tthis.hierarchyManager.forEachInHierarchy(callback, options);\n\t}\n\n\t/**\n\t * Generator-based hierarchy traversal in parent-first (breadth-first) order.\n\t * Supports early termination via break.\n\t * @param options Optional traversal options (roots to filter to specific subtrees)\n\t * @yields HierarchyEntry for each entity in parent-first order\n\t */\n\thierarchyIterator(options?: HierarchyIteratorOptions): Generator<HierarchyEntry, void, unknown> {\n\t\treturn this.hierarchyManager.hierarchyIterator(options);\n\t}\n}\n",
|
|
7
9
|
"interface EventHandler<T> {\n\tcallback: (data: T) => void;\n\tonce: boolean;\n}\n\nexport default\nclass EventBus<EventTypes> {\n\tprivate handlers: Map<keyof EventTypes, Array<EventHandler<any>>> = new Map();\n\n\t/**\n\t * Subscribe to an event\n\t */\n\tsubscribe<E extends keyof EventTypes>(\n\t\teventType: E,\n\t\tcallback: (data: EventTypes[E]) => void\n\t): () => void {\n\t\treturn this.addHandler(eventType, callback, false);\n\t}\n\n\t/**\n\t * Subscribe to an event once\n\t */\n\tonce<E extends keyof EventTypes>(\n\t\teventType: E,\n\t\tcallback: (data: EventTypes[E]) => void\n\t): () => void {\n\t\treturn this.addHandler(eventType, callback, true);\n\t}\n\n\t/**\n\t * Unsubscribe a specific callback from an event by reference\n\t * @returns true if the callback was found and removed, false otherwise\n\t */\n\tunsubscribe<E extends keyof EventTypes>(\n\t\teventType: E,\n\t\tcallback: (data: EventTypes[E]) => void\n\t): boolean {\n\t\tconst handlers = this.handlers.get(eventType);\n\t\tif (!handlers) return false;\n\n\t\tconst index = handlers.findIndex(h => h.callback === callback);\n\t\tif (index === -1) return false;\n\n\t\thandlers.splice(index, 1);\n\t\treturn true;\n\t}\n\n\t/**\n\t * Internal method to add an event handler\n\t */\n\tprivate addHandler<E extends keyof EventTypes>(\n\t\teventType: E,\n\t\tcallback: (data: EventTypes[E]) => void,\n\t\tonce: boolean\n\t): () => void {\n\t\tlet handlers = this.handlers.get(eventType);\n\t\tif (!handlers) {\n\t\t\thandlers = [];\n\t\t\tthis.handlers.set(eventType, handlers);\n\t\t}\n\n\t\tconst handler: EventHandler<any> = {\n\t\t\tcallback,\n\t\t\tonce\n\t\t};\n\n\t\thandlers.push(handler);\n\n\t\t// Return unsubscribe function\n\t\treturn () => {\n\t\t\tconst handlers = this.handlers.get(eventType);\n\t\t\tif (handlers) {\n\t\t\t\tconst index = handlers.indexOf(handler);\n\t\t\t\tif (index !== -1) {\n\t\t\t\t\thandlers.splice(index, 1);\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\t}\n\n\t/**\n\t * Publish an event. Data is required unless EventTypes[E] extends void | undefined.\n\t * Zero-allocation hot path: uses index-based iteration with a snapshot length\n\t * so handlers added mid-publish are not called in the same publish cycle.\n\t */\n\tpublish<E extends keyof EventTypes>(\n\t\t...[eventType, data]: EventTypes[E] extends void | undefined\n\t\t\t? [eventType: E, data?: EventTypes[E]]\n\t\t\t: [eventType: E, data: EventTypes[E]]\n\t): void {\n\t\tconst handlers = this.handlers.get(eventType);\n\t\tif (!handlers || handlers.length === 0) return;\n\n\t\t// Snapshot length prevents calling handlers added mid-publish\n\t\tlet hasOnce = false;\n\t\tconst len = handlers.length;\n\t\tfor (let i = 0; i < len && i < handlers.length; i++) {\n\t\t\tconst handler = handlers[i];\n\t\t\tif (!handler) continue;\n\t\t\thandler.callback(data as EventTypes[E]);\n\t\t\tif (handler.once) hasOnce = true;\n\t\t}\n\n\t\t// Reverse splice to remove once-handlers without shifting earlier indices\n\t\tif (hasOnce) {\n\t\t\tfor (let i = handlers.length - 1; i >= 0; i--) {\n\t\t\t\tif (handlers[i]?.once) {\n\t\t\t\t\thandlers.splice(i, 1);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tclear(): void {\n\t\tthis.handlers.clear();\n\t}\n\n\tclearEvent<E extends keyof EventTypes>(eventType: E): void {\n\t\tthis.handlers.delete(eventType);\n\t}\n}\n",
|
|
8
10
|
"/**\n * Resource factory with declared dependencies and optional disposal callback\n */\nexport interface ResourceFactoryWithDeps<T, Context = unknown, D extends string = string> {\n\tdependsOn?: readonly D[];\n\tfactory: (context: Context) => T | Promise<T>;\n\tonDispose?: (resource: T, context: Context) => void | Promise<void>;\n}\n\n/** @internal */\nexport const RESOURCE_DIRECT: unique symbol = Symbol('resource-direct');\n\n/**\n * Branded wrapper for storing a value as-is, bypassing factory detection.\n * The value is carried on the symbol key to avoid structural conflicts\n * with user resource types that have a `value` property.\n * Create via the `directValue()` helper.\n */\nexport interface ResourceDirectValue<T> {\n\t[RESOURCE_DIRECT]: T;\n}\n\n/**\n * Wrap a value to store it as-is, bypassing factory detection.\n * Use when the resource itself is a function or class that should not be invoked.\n *\n * @example\n * ```ts\n * import { directValue } from 'ecspresso';\n * world.addResource('handler', directValue(myFunction));\n * world.addResource('MyClass', directValue(MyClass));\n * ```\n */\nexport function directValue<T>(value: T): ResourceDirectValue<T> {\n\treturn { [RESOURCE_DIRECT]: value };\n}\n\n/**\n * Create a shallow snapshot of a value for change detection.\n * For objects, copies own enumerable properties one level deep.\n * For primitives, wraps in { $value } so reference changes are caught.\n */\nfunction shallowSnapshot(value: unknown): Record<string, unknown> {\n\tif (typeof value === 'object' && value !== null && !Array.isArray(value)) {\n\t\treturn { ...value as Record<string, unknown> };\n\t}\n\treturn { $value: value };\n}\n\n/**\n * Compare a live value against a snapshot taken by shallowSnapshot.\n * Returns true if any shallow property differs.\n */\nfunction shallowChanged(current: unknown, snapshot: Record<string, unknown>): boolean {\n\tif (typeof current === 'object' && current !== null && !Array.isArray(current)) {\n\t\tconst obj = current as Record<string, unknown>;\n\t\tfor (const k in snapshot) {\n\t\t\tif (!Object.is(obj[k], snapshot[k])) return true;\n\t\t}\n\t\treturn false;\n\t}\n\treturn !Object.is(current, snapshot['$value']);\n}\n\n/**\n * Type guard for detecting { factory } pattern (with optional dependsOn and onDispose)\n */\nfunction isFactoryWithDeps<T>(resource: unknown): resource is ResourceFactoryWithDeps<T> {\n\treturn (\n\t\ttypeof resource === 'object' &&\n\t\tresource !== null &&\n\t\t'factory' in resource &&\n\t\ttypeof (resource as ResourceFactoryWithDeps<T>).factory === 'function'\n\t);\n}\n\n/**\n * Type guard for detecting { value } wrapper pattern (branded with symbol)\n */\nfunction isDirectValue<T>(resource: unknown): resource is ResourceDirectValue<T> {\n\treturn (\n\t\ttypeof resource === 'object' &&\n\t\tresource !== null &&\n\t\tRESOURCE_DIRECT in resource\n\t);\n}\n\n/**\n * Topological sort with cycle detection\n */\nfunction topologicalSort<K extends string>(\n\tkeys: readonly K[],\n\tgetDeps: (key: K) => readonly string[]\n): K[] {\n\tconst sorted: K[] = [];\n\tconst visited = new Set<K>();\n\tconst visiting = new Set<K>();\n\n\tfunction visit(key: K, path: K[] = []): void {\n\t\tif (visited.has(key)) return;\n\t\tif (visiting.has(key)) {\n\t\t\tthrow new Error(`Circular resource dependency: ${[...path, key].join(' -> ')}`);\n\t\t}\n\n\t\tvisiting.add(key);\n\t\tfor (const dep of getDeps(key)) {\n\t\t\tconst found = keys.find(k => k === dep);\n\t\t\tif (found) {\n\t\t\t\tvisit(found, [...path, key]);\n\t\t\t}\n\t\t}\n\t\tvisiting.delete(key);\n\t\tvisited.add(key);\n\t\tsorted.push(key);\n\t}\n\n\tfor (const key of keys) {\n\t\tvisit(key);\n\t}\n\treturn sorted;\n}\n\n/**\n * When Context is unknown (default), context args are optional.\n * When Context is a specific type (e.g. ECSpresso<...>), context is required.\n */\ntype ContextArgs<Context> = unknown extends Context ? [context?: Context] : [context: Context];\n\nexport default\nclass ResourceManager<\n\tResourceTypes extends Record<string, any> = Record<string, any>,\n\tContext = unknown,\n> {\n\tprivate resources: Map<keyof ResourceTypes, any> = new Map();\n\tprivate resourceFactories: Map<keyof ResourceTypes, (context: Context) => any | Promise<any>> = new Map();\n\tprivate resourceDependencies: Map<keyof ResourceTypes, readonly (keyof ResourceTypes & string)[]> = new Map();\n\tprivate resourceDisposers: Map<keyof ResourceTypes, (resource: any, context: Context) => void | Promise<void>> = new Map();\n\tprivate initializedResourceKeys: Set<keyof ResourceTypes> = new Set();\n\tprivate _changeSubscribers: Map<keyof ResourceTypes, Set<(newValue: any, oldValue: any) => void>> = new Map();\n\t/** Shallow snapshots of observed resources, keyed by resource key */\n\tprivate _observedSnapshots: Map<keyof ResourceTypes, Record<string, unknown>> = new Map();\n\n\t/**\n\t * Add a resource to the manager.\n\t *\n\t * Resolution order:\n\t * 1. `{ factory, dependsOn?, onDispose? }` → factory with optional deps/disposal\n\t * 2. `{ value }` → direct value wrapper (use to store functions/classes as-is)\n\t * 3. `typeof === 'function'` → bare factory (no deps)\n\t * 4. Anything else → direct value\n\t *\n\t * @param label The resource key\n\t * @param resource The resource value, a factory function, or a factory with dependencies\n\t * @returns The resource manager instance for chaining\n\t */\n\tadd<K extends keyof ResourceTypes>(\n\t\tlabel: K,\n\t\tresource:\n\t\t\t| ResourceTypes[K]\n\t\t\t| ((context: Context) => ResourceTypes[K] | Promise<ResourceTypes[K]>)\n\t\t\t| ResourceFactoryWithDeps<ResourceTypes[K], Context, keyof ResourceTypes & string>\n\t\t\t| ResourceDirectValue<ResourceTypes[K]>,\n\t) {\n\t\tconst storeValue = (value: unknown) => {\n\t\t\tthis.resources.set(label, value);\n\t\t\tthis.initializedResourceKeys.add(label);\n\t\t\tthis.resourceDependencies.set(label, []);\n\t\t};\n\n\t\tif (isFactoryWithDeps<ResourceTypes[K]>(resource)) {\n\t\t\t// Factory with optional dependencies and/or onDispose\n\t\t\tthis.resourceFactories.set(label, resource.factory as (context: Context) => any | Promise<any>);\n\t\t\t// Type guard narrows to default D=string; the call-site constraint ensures correctness\n\t\t\tthis.resourceDependencies.set(label, (resource.dependsOn ?? []) as readonly (keyof ResourceTypes & string)[]);\n\t\t\tif (resource.onDispose) {\n\t\t\t\tthis.resourceDisposers.set(label, resource.onDispose as (resource: any, context: Context) => void | Promise<void>);\n\t\t\t}\n\t\t} else if (isDirectValue<ResourceTypes[K]>(resource)) {\n\t\t\tstoreValue(resource[RESOURCE_DIRECT]);\n\t\t} else if (typeof resource === 'function') {\n\t\t\t// Bare function → treat as factory (no dependencies)\n\t\t\tthis.resourceFactories.set(label, resource as (context: Context) => any | Promise<any>);\n\t\t\tthis.resourceDependencies.set(label, []);\n\t\t} else {\n\t\t\tstoreValue(resource);\n\t\t}\n\t\treturn this;\n\t}\n\n\t/**\n\t * Try to get a resource from the manager.\n\t * Returns the resource value if it exists, or undefined if not found.\n\t * Like `get`, initializes factory resources on first access.\n\t * @param label The resource key\n\t * @param context Context to pass to factory functions (usually the ECSpresso instance)\n\t * @returns The resource value, or undefined if not found\n\t * @see get — the throwing alternative\n\t */\n\ttryGet<K extends keyof ResourceTypes>(\n\t\tlabel: K,\n\t\t...args: ContextArgs<Context>\n\t): ResourceTypes[K] | undefined {\n\t\tif (!this.has(label)) return undefined;\n\t\treturn this.get(label, ...args);\n\t}\n\n\t/**\n\t * Get a resource from the manager\n\t * @param label The resource key\n\t * @param context Context to pass to factory functions (usually the ECSpresso instance)\n\t * @returns The resource value\n\t * @throws Error if resource not found\n\t * @see tryGet — the non-throwing alternative\n\t */\n\tget<K extends keyof ResourceTypes>(\n\t\tlabel: K,\n\t\t...args: ContextArgs<Context>\n\t): ResourceTypes[K] {\n\t\t// Check if we already have the initialized resource\n\t\tconst resource = this.resources.get(label);\n\t\tif (resource !== undefined) {\n\t\t\treturn resource;\n\t\t}\n\n\t\t// Check if we have a factory for this resource\n\t\tconst factory = this.resourceFactories.get(label);\n\t\tif (factory === undefined) {\n\t\t\tthrow new Error(`Resource ${String(label)} not found`);\n\t\t}\n\n\t\t// Initialize the resource, passing the context\n\t\tconst context = args[0] as Context;\n\t\tconst initializedResource = factory(context);\n\n\t\t// If it's not a Promise, store it immediately\n\t\tif (!(initializedResource instanceof Promise)) {\n\t\t\tthis.resources.set(label, initializedResource);\n\t\t\tthis.initializedResourceKeys.add(label);\n\t\t}\n\n\t\treturn initializedResource;\n\t}\n\n\t/**\n\t * Check if a resource exists\n\t * @param label The resource key\n\t * @returns True if the resource exists\n\t */\n\thas<K extends keyof ResourceTypes>(label: K): boolean {\n\t\treturn this.resources.has(label) || this.resourceFactories.has(label);\n\t}\n\n\t/**\n\t * Remove a resource (without calling onDispose)\n\t * @param label The resource key\n\t * @returns True if the resource was removed\n\t */\n\tremove<K extends keyof ResourceTypes>(label: K): boolean {\n\t\tconst resourceRemoved = this.resources.delete(label);\n\t\tconst factoryRemoved = this.resourceFactories.delete(label);\n\t\tthis.resourceDependencies.delete(label);\n\t\tthis.resourceDisposers.delete(label);\n\t\tthis.initializedResourceKeys.delete(label);\n\t\treturn resourceRemoved || factoryRemoved;\n\t}\n\n\t/**\n\t * Get all resource keys\n\t * @returns Array of resource keys\n\t */\n\tgetKeys(): Array<keyof ResourceTypes> {\n\t\tconst keys = new Set([\n\t\t\t...this.resources.keys(),\n\t\t\t...this.resourceFactories.keys()\n\t\t]);\n\t\treturn Array.from(keys);\n\t}\n\n\t/**\n\t * Check if a resource needs to be initialized\n\t * @param label The resource key\n\t * @returns True if the resource needs initialization\n\t */\n\tneedsInitialization<K extends keyof ResourceTypes>(label: K): boolean {\n\t\treturn this.resourceFactories.has(label) && !this.initializedResourceKeys.has(label);\n\t}\n\n\t/**\n\t * Get all resource keys that need to be initialized\n\t * @returns Array of resource keys that need initialization\n\t */\n\tgetPendingInitializationKeys(): Array<keyof ResourceTypes> {\n\t\treturn Array\n\t\t\t.from(this.resourceFactories.keys())\n\t\t\t.filter(key => !this.initializedResourceKeys.has(key));\n\t}\n\n\t/**\n\t * Initialize a specific resource if it's a factory function\n\t * @param label The resource key\n\t * @param context Context to pass to factory functions\n\t * @returns Promise that resolves when the resource is initialized\n\t */\n\tasync initializeResource<K extends keyof ResourceTypes>(\n\t\tlabel: K,\n\t\t...args: ContextArgs<Context>\n\t): Promise<void> {\n\t\tif (!this.resourceFactories.has(label) || this.initializedResourceKeys.has(label)) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst factory = this.resourceFactories.get(label);\n\t\tif (!factory) return;\n\t\tconst context = args[0] as Context;\n\t\tconst initializedResource = await factory(context);\n\t\tthis.resources.set(label, initializedResource);\n\t\tthis.initializedResourceKeys.add(label);\n\t\tthis.resourceFactories.delete(label);\n\t}\n\n\t/**\n\t * Initialize specific resources or all resources that haven't been initialized yet.\n\t * Resources are initialized in topological order based on their dependencies.\n\t * @param context Context to pass to factory functions (usually the ECSpresso instance)\n\t * @param keys Optional array of resource keys to initialize\n\t * @returns Promise that resolves when the specified resources are initialized\n\t */\n\tasync initializeResources<K extends keyof ResourceTypes>(\n\t\t...args: [...ContextArgs<Context>, ...K[]]\n\t): Promise<void> {\n\t\t// First arg is context (when Context is typed), remaining are keys\n\t\tconst keys = args.slice(1) as K[];\n\n\t\t// Determine which keys to initialize\n\t\tconst keysToInit = keys.length === 0\n\t\t\t? this.getPendingInitializationKeys()\n\t\t\t: keys;\n\n\t\t// If no keys to initialize, we're done\n\t\tif (keysToInit.length === 0) return;\n\n\t\t// Sort keys topologically based on dependencies\n\t\tconst sortedKeys = topologicalSort(\n\t\t\tkeysToInit as readonly (keyof ResourceTypes & string)[],\n\t\t\t(key) => [...(this.resourceDependencies.get(key) ?? [])]\n\t\t);\n\n\t\t// Initialize in order (sequentially to respect dependencies)\n\t\tfor (const key of sortedKeys) {\n\t\t\tawait this.initializeResource(key, ...args.slice(0, 1) as ContextArgs<Context>);\n\t\t}\n\t}\n\n\t/**\n\t * Get the dependencies of a resource\n\t * @param label The resource key\n\t * @returns Array of resource keys that this resource depends on\n\t */\n\tgetDependencies<K extends keyof ResourceTypes>(label: K): readonly (keyof ResourceTypes & string)[] {\n\t\treturn this.resourceDependencies.get(label) ?? [];\n\t}\n\n\t/**\n\t * Dispose a single resource, calling its onDispose callback if it exists\n\t * @param label The resource key to dispose\n\t * @param context Context to pass to the onDispose callback\n\t * @returns True if the resource existed and was disposed, false if it didn't exist\n\t */\n\tasync disposeResource<K extends keyof ResourceTypes>(\n\t\tlabel: K,\n\t\t...args: ContextArgs<Context>\n\t): Promise<boolean> {\n\t\tif (!this.resources.has(label) && !this.resourceFactories.has(label)) {\n\t\t\treturn false;\n\t\t}\n\n\t\t// Only call onDispose if the resource was initialized\n\t\tif (this.initializedResourceKeys.has(label)) {\n\t\t\tconst disposer = this.resourceDisposers.get(label);\n\t\t\tconst resource = this.resources.get(label);\n\t\t\tif (disposer && resource !== undefined) {\n\t\t\t\tconst context = args[0] as Context;\n\t\t\t\tawait disposer(resource, context);\n\t\t\t}\n\t\t}\n\n\t\t// Clean up all tracking\n\t\tthis.resources.delete(label);\n\t\tthis.resourceFactories.delete(label);\n\t\tthis.resourceDependencies.delete(label);\n\t\tthis.resourceDisposers.delete(label);\n\t\tthis.initializedResourceKeys.delete(label);\n\t\tthis._changeSubscribers.delete(label);\n\n\t\treturn true;\n\t}\n\n\t/**\n\t * Subscribe to changes for a specific resource key.\n\t *\n\t * Subscribing marks the resource as \"observed.\" Observed resources:\n\t * - Are re-resolved each frame by `withResources` (no stale cache)\n\t * - Are shallow-diffed at the end of each frame via `flushObserved()`,\n\t * so in-place mutations are detected and subscribers notified\n\t *\n\t * When the last subscriber unsubscribes, the resource reverts to\n\t * normal (cached, no per-frame diff).\n\t *\n\t * @param key The resource key to watch\n\t * @param callback Function called with (newValue, oldValue) when the resource changes\n\t * @returns Unsubscribe function\n\t */\n\tonResourceChange<K extends keyof ResourceTypes>(\n\t\tkey: K,\n\t\tcallback: (newValue: ResourceTypes[K], oldValue: ResourceTypes[K]) => void\n\t): () => void {\n\t\tconst existing = this._changeSubscribers.get(key);\n\t\tconst subscribers = existing ?? new Set<(newValue: any, oldValue: any) => void>();\n\t\tif (!existing) {\n\t\t\tthis._changeSubscribers.set(key, subscribers);\n\t\t\t// First subscriber — take a shallow snapshot for per-frame diffing\n\t\t\tconst current = this.resources.get(key);\n\t\t\tthis._observedSnapshots.set(key, shallowSnapshot(current));\n\t\t}\n\t\tconst wrapped = callback as (newValue: any, oldValue: any) => void;\n\t\tsubscribers.add(wrapped);\n\n\t\treturn () => {\n\t\t\tsubscribers.delete(wrapped);\n\t\t\tif (subscribers.size === 0) {\n\t\t\t\tthis._changeSubscribers.delete(key);\n\t\t\t\tthis._observedSnapshots.delete(key);\n\t\t\t}\n\t\t};\n\t}\n\n\t/**\n\t * Notify subscribers of a resource value change.\n\t * Skips notification if the value is unchanged (via Object.is).\n\t * @param key The resource key that changed\n\t * @param newValue The new resource value\n\t * @param oldValue The previous resource value\n\t */\n\tnotifyChange<K extends keyof ResourceTypes>(\n\t\tkey: K,\n\t\tnewValue: ResourceTypes[K],\n\t\toldValue: ResourceTypes[K]\n\t): void {\n\t\tif (Object.is(newValue, oldValue)) return;\n\t\tconst subscribers = this._changeSubscribers.get(key);\n\t\tif (!subscribers || subscribers.size === 0) return;\n\t\t// Update snapshot so flushObserved doesn't double-fire for this change\n\t\tif (this._observedSnapshots.has(key)) {\n\t\t\tthis._observedSnapshots.set(key, shallowSnapshot(newValue));\n\t\t}\n\t\tconst subscriberSnapshot = [...subscribers];\n\t\tfor (const cb of subscriberSnapshot) {\n\t\t\tcb(newValue, oldValue);\n\t\t}\n\t}\n\n\t/**\n\t * Whether a resource has active change subscribers.\n\t * Observed resources should not be cached by systems — they need\n\t * to be re-resolved each frame so external mutations are visible.\n\t */\n\tisObserved<K extends keyof ResourceTypes>(key: K): boolean {\n\t\treturn this._observedSnapshots.has(key);\n\t}\n\n\t/**\n\t * Diff all observed resources against their snapshots.\n\t * Fires subscribers for any resource whose shallow properties changed\n\t * since the last snapshot, then updates the snapshot.\n\t * Call once per frame after all systems have run.\n\t */\n\tflushObserved(): void {\n\t\tif (this._observedSnapshots.size === 0) return;\n\t\tfor (const [key, snapshot] of this._observedSnapshots) {\n\t\t\tconst current = this.resources.get(key);\n\t\t\tif (!shallowChanged(current, snapshot)) continue;\n\n\t\t\t// Reconstruct the old value from the snapshot encoding\n\t\t\tconst oldValue = '$value' in snapshot ? snapshot['$value'] : snapshot;\n\t\t\tconst newSnapshot = shallowSnapshot(current);\n\t\t\tconst subscribers = this._changeSubscribers.get(key)!;\n\t\t\tfor (const cb of subscribers) {\n\t\t\t\tcb(current, oldValue);\n\t\t\t}\n\t\t\tthis._observedSnapshots.set(key, newSnapshot);\n\t\t}\n\t}\n\n\t/**\n\t * Dispose all initialized resources in reverse dependency order.\n\t * Resources that depend on others are disposed first.\n\t * @param context Context to pass to onDispose callbacks\n\t */\n\tasync disposeResources(\n\t\t...args: ContextArgs<Context>\n\t): Promise<void> {\n\t\t// Get only initialized resource keys\n\t\tconst initializedKeys = Array.from(this.initializedResourceKeys);\n\n\t\tif (initializedKeys.length === 0) return;\n\n\t\t// Sort in dependency order, then reverse for disposal\n\t\tconst sortedKeys = topologicalSort(\n\t\t\tinitializedKeys as readonly (keyof ResourceTypes & string)[],\n\t\t\t(key) => [...(this.resourceDependencies.get(key) ?? [])]\n\t\t).reverse();\n\n\t\t// Dispose in reverse dependency order\n\t\tfor (const key of sortedKeys) {\n\t\t\tawait this.disposeResource(key, ...args);\n\t\t}\n\t}\n}\n",
|
|
9
|
-
"import type { Entity, FilteredEntity } from \"./types\";\nimport type EntityManager from \"./entity-manager\";\n\n/**\n * Definition for a reactive query with enter/exit callbacks\n */\nexport interface ReactiveQueryDefinition<\n\tComponentTypes extends Record<string, any>,\n\tWithComponents extends keyof ComponentTypes = keyof ComponentTypes,\n\tWithoutComponents extends keyof ComponentTypes = never,\n\tOptionalComponents extends keyof ComponentTypes = never,\n> {\n\t/** Components the entity must have */\n\twith: ReadonlyArray<WithComponents>;\n\t/** Components the entity must not have */\n\twithout?: ReadonlyArray<WithoutComponents>;\n\t/** Components to include in the entity type but not require for matching */\n\toptional?: ReadonlyArray<OptionalComponents>;\n\t/** Components the entity's direct parent must have */\n\tparentHas?: ReadonlyArray<keyof ComponentTypes>;\n\t/** Called when an entity starts matching the query */\n\tonEnter?: (entity: FilteredEntity<ComponentTypes, WithComponents, WithoutComponents, OptionalComponents>) => void;\n\t/** Called when an entity stops matching the query (receives just the ID since entity may be gone) */\n\tonExit?: (entityId: number) => void;\n}\n\ninterface StoredQuery<ComponentTypes extends Record<string, any>> {\n\tdefinition: ReactiveQueryDefinition<ComponentTypes, any, any, any>;\n\tmatchingEntities: Set<number>;\n}\n\n/**\n * Manages reactive queries that trigger callbacks when entities enter/exit query matches\n */\nexport default class ReactiveQueryManager<ComponentTypes extends Record<string, any>, QueryNames extends string = string> {\n\tprivate queries: Map<string, StoredQuery<ComponentTypes>> = new Map();\n\tprivate entityManager: EntityManager<ComponentTypes>;\n\t/** Whether any registered query uses parentHas */\n\tprivate _hasParentHasQueries: boolean = false;\n\n\tconstructor(entityManager: EntityManager<ComponentTypes>) {\n\t\tthis.entityManager = entityManager;\n\t}\n\n\t/**\n\t * Whether any registered reactive query uses parentHas filters\n\t */\n\tget hasParentHasQueries(): boolean {\n\t\treturn this._hasParentHasQueries;\n\t}\n\n\t/**\n\t * Add a reactive query\n\t * @param name Unique name for the query\n\t * @param definition Query definition with callbacks\n\t */\n\taddQuery<\n\t\tWithComponents extends keyof ComponentTypes,\n\t\tWithoutComponents extends keyof ComponentTypes = never,\n\t\tOptionalComponents extends keyof ComponentTypes = never,\n\t>(\n\t\tname: QueryNames,\n\t\tdefinition: ReactiveQueryDefinition<ComponentTypes, WithComponents, WithoutComponents, OptionalComponents>\n\t): void {\n\t\tconst storedQuery: StoredQuery<ComponentTypes> = {\n\t\t\tdefinition,\n\t\t\tmatchingEntities: new Set(),\n\t\t};\n\n\t\tthis.queries.set(name, storedQuery);\n\n\t\t// Update parentHas flag\n\t\tif (definition.parentHas?.length) {\n\t\t\tthis._hasParentHasQueries = true;\n\t\t}\n\n\t\t// Check existing entities for initial matches\n\t\tconst existingMatches = this.entityManager.getEntitiesWithQuery(\n\t\t\tdefinition.with as ReadonlyArray<keyof ComponentTypes>,\n\t\t\t(definition.without ?? []) as ReadonlyArray<keyof ComponentTypes>\n\t\t);\n\n\t\tfor (const entity of existingMatches) {\n\t\t\tif (this.entityMatchesQuery(entity, storedQuery.definition)) {\n\t\t\t\tstoredQuery.matchingEntities.add(entity.id);\n\t\t\t\tstoredQuery.definition.onEnter?.(entity as FilteredEntity<ComponentTypes, any, any, any>);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Remove a reactive query\n\t * @param name Name of the query to remove\n\t * @returns true if the query existed and was removed\n\t */\n\tremoveQuery(name: QueryNames): boolean {\n\t\tconst result = this.queries.delete(name);\n\n\t\t// Recalculate parentHas flag\n\t\tif (result) {\n\t\t\tthis._recalcParentHasFlag();\n\t\t}\n\n\t\treturn result;\n\t}\n\n\
|
|
11
|
+
"import type { Entity, FilteredEntity } from \"./types\";\nimport type EntityManager from \"./entity-manager\";\nimport { entityMatchesShape } from \"./query-match\";\n\n/**\n * Definition for a reactive query with enter/exit callbacks\n */\nexport interface ReactiveQueryDefinition<\n\tComponentTypes extends Record<string, any>,\n\tWithComponents extends keyof ComponentTypes = keyof ComponentTypes,\n\tWithoutComponents extends keyof ComponentTypes = never,\n\tOptionalComponents extends keyof ComponentTypes = never,\n> {\n\t/** Components the entity must have */\n\twith: ReadonlyArray<WithComponents>;\n\t/** Components the entity must not have */\n\twithout?: ReadonlyArray<WithoutComponents>;\n\t/** Components to include in the entity type but not require for matching */\n\toptional?: ReadonlyArray<OptionalComponents>;\n\t/** Components the entity's direct parent must have */\n\tparentHas?: ReadonlyArray<keyof ComponentTypes>;\n\t/** Called when an entity starts matching the query */\n\tonEnter?: (entity: FilteredEntity<ComponentTypes, WithComponents, WithoutComponents, OptionalComponents>) => void;\n\t/** Called when an entity stops matching the query (receives just the ID since entity may be gone) */\n\tonExit?: (entityId: number) => void;\n}\n\ninterface StoredQuery<ComponentTypes extends Record<string, any>> {\n\tdefinition: ReactiveQueryDefinition<ComponentTypes, any, any, any>;\n\tmatchingEntities: Set<number>;\n}\n\n/**\n * Manages reactive queries that trigger callbacks when entities enter/exit query matches\n */\nexport default class ReactiveQueryManager<ComponentTypes extends Record<string, any>, QueryNames extends string = string> {\n\tprivate queries: Map<string, StoredQuery<ComponentTypes>> = new Map();\n\tprivate entityManager: EntityManager<ComponentTypes>;\n\t/** Whether any registered query uses parentHas */\n\tprivate _hasParentHasQueries: boolean = false;\n\n\tconstructor(entityManager: EntityManager<ComponentTypes>) {\n\t\tthis.entityManager = entityManager;\n\t}\n\n\t/**\n\t * Whether any registered reactive query uses parentHas filters\n\t */\n\tget hasParentHasQueries(): boolean {\n\t\treturn this._hasParentHasQueries;\n\t}\n\n\t/**\n\t * Add a reactive query\n\t * @param name Unique name for the query\n\t * @param definition Query definition with callbacks\n\t */\n\taddQuery<\n\t\tWithComponents extends keyof ComponentTypes,\n\t\tWithoutComponents extends keyof ComponentTypes = never,\n\t\tOptionalComponents extends keyof ComponentTypes = never,\n\t>(\n\t\tname: QueryNames,\n\t\tdefinition: ReactiveQueryDefinition<ComponentTypes, WithComponents, WithoutComponents, OptionalComponents>\n\t): void {\n\t\tconst storedQuery: StoredQuery<ComponentTypes> = {\n\t\t\tdefinition,\n\t\t\tmatchingEntities: new Set(),\n\t\t};\n\n\t\tthis.queries.set(name, storedQuery);\n\n\t\t// Update parentHas flag\n\t\tif (definition.parentHas?.length) {\n\t\t\tthis._hasParentHasQueries = true;\n\t\t}\n\n\t\t// Check existing entities for initial matches\n\t\tconst existingMatches = this.entityManager.getEntitiesWithQuery(\n\t\t\tdefinition.with as ReadonlyArray<keyof ComponentTypes>,\n\t\t\t(definition.without ?? []) as ReadonlyArray<keyof ComponentTypes>\n\t\t);\n\n\t\tfor (const entity of existingMatches) {\n\t\t\tif (this.entityMatchesQuery(entity, storedQuery.definition)) {\n\t\t\t\tstoredQuery.matchingEntities.add(entity.id);\n\t\t\t\tstoredQuery.definition.onEnter?.(entity as FilteredEntity<ComponentTypes, any, any, any>);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Remove a reactive query\n\t * @param name Name of the query to remove\n\t * @returns true if the query existed and was removed\n\t */\n\tremoveQuery(name: QueryNames): boolean {\n\t\tconst result = this.queries.delete(name);\n\n\t\t// Recalculate parentHas flag\n\t\tif (result) {\n\t\t\tthis._recalcParentHasFlag();\n\t\t}\n\n\t\treturn result;\n\t}\n\n\tprivate entityMatchesQuery(\n\t\tentity: Entity<ComponentTypes>,\n\t\tdefinition: ReactiveQueryDefinition<ComponentTypes, any, any, any>\n\t): boolean {\n\t\treturn entityMatchesShape(\n\t\t\tentity,\n\t\t\tdefinition.with as ReadonlyArray<keyof ComponentTypes>,\n\t\t\tdefinition.without as ReadonlyArray<keyof ComponentTypes> | undefined,\n\t\t\tdefinition.parentHas,\n\t\t\tthis.entityManager,\n\t\t);\n\t}\n\n\t/**\n\t * Apply enter/exit transitions for a single query against an entity.\n\t * Fires onEnter when entity starts matching, onExit when it stops.\n\t */\n\tprivate _applyQueryTransition(entity: Entity<ComponentTypes>, query: StoredQuery<ComponentTypes>): void {\n\t\tconst wasMatching = query.matchingEntities.has(entity.id);\n\t\tconst nowMatches = this.entityMatchesQuery(entity, query.definition);\n\n\t\tif (!wasMatching && nowMatches) {\n\t\t\tquery.matchingEntities.add(entity.id);\n\t\t\tquery.definition.onEnter?.(entity as FilteredEntity<ComponentTypes, any, any, any>);\n\t\t} else if (wasMatching && !nowMatches) {\n\t\t\tquery.matchingEntities.delete(entity.id);\n\t\t\tquery.definition.onExit?.(entity.id);\n\t\t}\n\t}\n\n\t/**\n\t * Called when a component is added to an entity\n\t * Checks all queries for potential enter/exit events\n\t */\n\tonComponentAdded(entity: Entity<ComponentTypes>, _componentName: keyof ComponentTypes): void {\n\t\tfor (const [, query] of this.queries) {\n\t\t\tthis._applyQueryTransition(entity, query);\n\t\t}\n\n\t\tif (this._hasParentHasQueries) {\n\t\t\tthis._recheckChildren(entity.id);\n\t\t}\n\t}\n\n\t/**\n\t * Called when a component is removed from an entity\n\t * Checks all queries for potential enter/exit events\n\t */\n\tonComponentRemoved(entity: Entity<ComponentTypes>, _componentName: keyof ComponentTypes): void {\n\t\tfor (const [, query] of this.queries) {\n\t\t\tthis._applyQueryTransition(entity, query);\n\t\t}\n\n\t\tif (this._hasParentHasQueries) {\n\t\t\tthis._recheckChildren(entity.id);\n\t\t}\n\t}\n\n\t/**\n\t * Called when an entity is removed\n\t * Triggers onExit for all queries the entity was matching\n\t */\n\tonEntityRemoved(entityId: number): void {\n\t\tfor (const [_name, query] of this.queries) {\n\t\t\tif (query.matchingEntities.has(entityId)) {\n\t\t\t\tquery.matchingEntities.delete(entityId);\n\t\t\t\tquery.definition.onExit?.(entityId);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Recheck an entity against all queries (used after batch component additions)\n\t * Fires enter/exit callbacks as appropriate based on current state vs tracked state\n\t */\n\trecheckEntity(entity: Entity<ComponentTypes>): void {\n\t\tfor (const [, query] of this.queries) {\n\t\t\tthis._applyQueryTransition(entity, query);\n\t\t}\n\t}\n\n\t/**\n\t * Recheck an entity and its children against all queries.\n\t * Used after component mutations to handle both the entity's own queries\n\t * and parentHas queries on its children.\n\t */\n\trecheckEntityAndChildren(entity: Entity<ComponentTypes>): void {\n\t\tthis.recheckEntity(entity);\n\t\tif (this._hasParentHasQueries) {\n\t\t\tthis._recheckChildren(entity.id);\n\t\t}\n\t}\n\n\t/**\n\t * Recheck all children of a parent entity against parentHas queries.\n\t * Called when a component is added/removed from a parent entity.\n\t */\n\tprivate _recheckChildren(parentId: number): void {\n\t\tconst children = this.entityManager.getChildren(parentId);\n\t\tfor (const childId of children) {\n\t\t\tconst childEntity = this.entityManager.getEntity(childId);\n\t\t\tif (childEntity) {\n\t\t\t\tthis.recheckEntity(childEntity);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Recalculate the _hasParentHasQueries flag from all registered queries\n\t */\n\tprivate _recalcParentHasFlag(): void {\n\t\tthis._hasParentHasQueries = false;\n\t\tfor (const [, query] of this.queries) {\n\t\t\tif (query.definition.parentHas?.length) {\n\t\t\t\tthis._hasParentHasQueries = true;\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t}\n}\n",
|
|
10
12
|
"import type ECSpresso from './ecspresso';\nimport type { RemoveEntityOptions } from './types';\nimport type { WorldConfig, EmptyConfig } from './type-utils';\n\n/**\n * CommandBuffer queues structural changes to be executed later.\n * This prevents ordering issues when modifying entities during system execution.\n *\n * Commands are executed in FIFO order when playback() is called.\n *\n * @example\n * ```typescript\n * // In a system\n * ecs.commands.removeEntity(entityId);\n * ecs.commands.spawn({ position: { x: 0, y: 0 } });\n *\n * // Later (automatically at end of update())\n * ecs.commands.playback(ecs);\n * ```\n */\nexport default class CommandBuffer<\n\tCfg extends WorldConfig = EmptyConfig,\n> {\n\tprivate commands: Array<(ecs: ECSpresso<Cfg>) => void> = [];\n\n\t/**\n\t * @param parent Owning ECS instance, used to read the active scope hint at\n\t * queue time so screen-gated spawns get auto-scoped on playback. Optional\n\t * so the buffer can be constructed standalone in tests.\n\t */\n\tconstructor(private readonly parent?: ECSpresso<Cfg>) {}\n\n\t/**\n\t * Queue an entity removal command\n\t * @param entityId The entity ID to remove\n\t * @param options Optional removal options (cascade, etc.)\n\t */\n\tremoveEntity(entityId: number, options?: RemoveEntityOptions): void {\n\t\tthis.commands.push((ecs) => {\n\t\t\tecs.removeEntity(entityId, options);\n\t\t});\n\t}\n\n\t/**\n\t * Queue a component addition command\n\t * @param entityId The entity ID\n\t * @param componentName The name of the component to add\n\t * @param componentValue The component data\n\t */\n\taddComponent<K extends keyof Cfg['components']>(\n\t\tentityId: number,\n\t\tcomponentName: K,\n\t\tcomponentValue: Cfg['components'][K]\n\t): void {\n\t\tthis.commands.push((ecs) => {\n\t\t\tecs.addComponent(entityId, componentName, componentValue);\n\t\t});\n\t}\n\n\t/**\n\t * Queue a component removal command\n\t * @param entityId The entity ID\n\t * @param componentName The name of the component to remove\n\t */\n\tremoveComponent<K extends keyof Cfg['components']>(\n\t\tentityId: number,\n\t\tcomponentName: K\n\t): void {\n\t\tthis.commands.push((ecs) => {\n\t\t\tecs.removeComponent(entityId, componentName);\n\t\t});\n\t}\n\n\t/**\n\t * Queue an entity spawn command\n\t * @param components The initial components for the new entity\n\t * @returns void (entity ID not available until playback)\n\t */\n\tspawn<T extends { [K in keyof Cfg['components']]?: Cfg['components'][K] }>(\n\t\tcomponents: T & Record<Exclude<keyof T, keyof Cfg['components']>, never>,\n\t\toptions?: { scope?: (keyof Cfg['screens'] & string) | null }\n\t): void {\n\t\tconst resolved = this._resolveScope(options);\n\t\tthis.commands.push((ecs) => {\n\t\t\tecs.spawn(components, resolved);\n\t\t});\n\t}\n\n\t/**\n\t * Queue a child entity spawn command\n\t * @param parentId The parent entity ID\n\t * @param components The initial components for the new child entity\n\t */\n\tspawnChild<T extends { [K in keyof Cfg['components']]?: Cfg['components'][K] }>(\n\t\tparentId: number,\n\t\tcomponents: T & Record<Exclude<keyof T, keyof Cfg['components']>, never>,\n\t\toptions?: { scope?: (keyof Cfg['screens'] & string) | null }\n\t): void {\n\t\tconst resolved = this._resolveScope(options);\n\t\tthis.commands.push((ecs) => {\n\t\t\tecs.spawnChild(parentId, components, resolved);\n\t\t});\n\t}\n\n\t/**\n\t * Snapshot the parent ECS's active scope hint at queue time when the\n\t * caller didn't pass an explicit scope. Without this, playback (after the\n\t * tick ends) would see a null hint and the gated system's screen intent\n\t * would be lost.\n\t */\n\tprivate _resolveScope(\n\t\toptions: { scope?: (keyof Cfg['screens'] & string) | null } | undefined,\n\t): { scope?: (keyof Cfg['screens'] & string) | null } | undefined {\n\t\tif (options?.scope !== undefined) return options;\n\t\tconst hint = this.parent?._getActiveScopeHint();\n\t\tif (!hint) return options;\n\t\treturn { scope: hint };\n\t}\n\n\t/**\n\t * Queue multiple component additions\n\t * @param entityId The entity ID\n\t * @param components Object with component names as keys and component data as values\n\t */\n\taddComponents<T extends { [K in keyof Cfg['components']]?: Cfg['components'][K] }>(\n\t\tentityId: number,\n\t\tcomponents: T & Record<Exclude<keyof T, keyof Cfg['components']>, never>\n\t): void {\n\t\tthis.commands.push((ecs) => {\n\t\t\tecs.addComponents(entityId, components);\n\t\t});\n\t}\n\n\t/**\n\t * Queue a parent assignment command\n\t * @param childId The child entity ID\n\t * @param parentId The parent entity ID\n\t */\n\tsetParent(childId: number, parentId: number): void {\n\t\tthis.commands.push((ecs) => {\n\t\t\tecs.setParent(childId, parentId);\n\t\t});\n\t}\n\n\t/**\n\t * Queue a component mutation command.\n\t * The mutator runs during playback, receiving the component for in-place mutation.\n\t * Automatically marks the component as changed.\n\t * @param entityId The entity ID\n\t * @param componentName The component to mutate\n\t * @param mutator A function that receives the component value for in-place mutation\n\t */\n\tmutateComponent<K extends keyof Cfg['components']>(\n\t\tentityId: number,\n\t\tcomponentName: K,\n\t\tmutator: (value: Cfg['components'][K]) => void\n\t): void {\n\t\tthis.commands.push((ecs) => {\n\t\t\tecs.mutateComponent(entityId, componentName, mutator);\n\t\t});\n\t}\n\n\t/**\n\t * Queue a markChanged command\n\t * @param entityId The entity ID\n\t * @param componentName The component to mark as changed\n\t */\n\tmarkChanged<K extends keyof Cfg['components']>(entityId: number, componentName: K): void {\n\t\tthis.commands.push((ecs) => {\n\t\t\tecs.markChanged(entityId, componentName);\n\t\t});\n\t}\n\n\t/**\n\t * Queue a parent removal command\n\t * @param childId The child entity ID\n\t */\n\tremoveParent(childId: number): void {\n\t\tthis.commands.push((ecs) => {\n\t\t\tecs.removeParent(childId);\n\t\t});\n\t}\n\n\t/**\n\t * Execute all queued commands in FIFO order.\n\t * Errors from individual commands are caught and logged, but do not stop playback.\n\t * @param ecs The ECSpresso instance to execute commands on\n\t */\n\tplayback(\n\t\tecs: ECSpresso<Cfg>\n\t): void {\n\t\t// Execute all commands, catching errors to prevent one bad command from stopping all playback\n\t\tfor (const command of this.commands) {\n\t\t\ttry {\n\t\t\t\tcommand(ecs);\n\t\t\t} catch (error) {\n\t\t\t\t// Log error but continue with remaining commands\n\t\t\t\t// This matches Unity DOTS behavior where invalid commands are silently skipped\n\t\t\t\tconsole.warn('CommandBuffer: Command failed during playback:', error);\n\t\t\t}\n\t\t}\n\n\t\t// Clear the queue\n\t\tthis.commands.length = 0;\n\t}\n\n\t/**\n\t * Clear all queued commands without executing them\n\t */\n\tclear(): void {\n\t\tthis.commands.length = 0;\n\t}\n\n\t/**\n\t * Get the number of queued commands\n\t * @returns The number of commands waiting to be executed\n\t */\n\tget length(): number {\n\t\treturn this.commands.length;\n\t}\n}\n",
|
|
11
13
|
"import type ECSpresso from './ecspresso';\nimport type { SystemPhase } from './types';\nimport type {\n\tWorldConfig,\n\tEmptyConfig,\n\tMergeConfigs,\n\tWithComponents,\n\tWithEvents,\n\tWithResources,\n\tWithAssets,\n\tWithScreens,\n} from './type-utils';\n\n/**\n * Registrar passed as the second argument to a plugin's `install` function.\n * Each registered disposer runs (in reverse order) when the plugin is\n * uninstalled via `world.uninstallPlugin(id)` or when `world.dispose()` is called.\n */\nexport type PluginCleanupRegistrar = (fn: () => void) => void;\n\n/**\n * Defaults applied to every system created via `world.addSystem(...)` inside\n * a plugin's install function. Per-system builder calls (`.inPhase(...)`,\n * `.inScreens([...])`, `.setPriority(...)`) always override the default.\n */\nexport interface SystemDefaults<Cfg extends WorldConfig = EmptyConfig> {\n\tinScreens?: ReadonlyArray<keyof Cfg['screens'] & string>;\n\texcludeScreens?: ReadonlyArray<keyof Cfg['screens'] & string>;\n\tphase?: SystemPhase;\n\tpriority?: number;\n}\n\n/**\n * Plugin interface for ECSpresso. A plugin is a plain object with an `install`\n * function that configures a world directly, plus phantom properties for\n * compile-time type extraction.\n *\n * @typeParam Cfg - The WorldConfig this plugin provides (components, events, resources, etc.)\n * @typeParam Requires - The WorldConfig this plugin requires from other plugins\n */\nexport interface Plugin<\n\tCfg extends WorldConfig = EmptyConfig,\n\tRequires extends WorldConfig = EmptyConfig,\n\tLabels extends string = never,\n\tGroups extends string = never,\n\tAssetGroupNames extends string = never,\n\tReactiveQueryNames extends string = never,\n> {\n\treadonly id: string;\n\treadonly install: (world: ECSpresso<MergeConfigs<Cfg, Requires>>, onCleanup: PluginCleanupRegistrar) => void;\n\t/**\n\t * Default system configuration applied to every `world.addSystem(...)` call\n\t * made inside the plugin's install function. Explicit per-system calls\n\t * override. Set via `PluginBuilder.setSystemDefaults(...)`.\n\t */\n\treadonly systemDefaults?: SystemDefaults<MergeConfigs<Cfg, Requires>>;\n\t// Phantom type for structural extraction (never set at runtime)\n\treadonly _cfg?: Cfg;\n\treadonly _requires?: Requires;\n\t// Phantom types for positional extraction (never set at runtime)\n\treadonly _labels?: Labels;\n\treadonly _groups?: Groups;\n\treadonly _assetGroupNames?: AssetGroupNames;\n\treadonly _reactiveQueryNames?: ReactiveQueryNames;\n}\n\n/**\n * Common configuration options shared by most plugins.\n * Plugin-specific options interfaces extend this with additional fields.\n */\nexport interface BasePluginOptions<G extends string = string> {\n\t/** System group name for all systems registered by this plugin */\n\tsystemGroup?: G;\n\t/** Priority for the plugin's primary system (default varies per plugin) */\n\tpriority?: number;\n\t/** Execution phase for the plugin's primary system */\n\tphase?: SystemPhase;\n}\n\n/**\n * Fluent builder for defining plugins. Mirrors `ECSpressoBuilder`'s\n * type-accumulator pattern: each `.withXxx<T>()` call threads `T` into the\n * appropriate WorldConfig slot at the type level, with no runtime cost.\n *\n * Terminal call is `.install(fn)` which returns the finalized `Plugin<...>`.\n *\n * @example\n * ```typescript\n * const myPlugin = definePlugin('my-plugin')\n * .withComponentTypes<MyComponents>()\n * .withEventTypes<MyEvents>()\n * .withResourceTypes<MyResources>()\n * .install((world) => {\n * world.addSystem('foo').setProcess(() => {});\n * });\n * ```\n */\nexport class PluginBuilder<\n\tCfg extends WorldConfig = EmptyConfig,\n\tRequires extends WorldConfig = EmptyConfig,\n\tLabels extends string = never,\n\tGroups extends string = never,\n\tAssetGroupNames extends string = never,\n\tReactiveQueryNames extends string = never,\n> {\n\tconstructor(private readonly _id: string) {}\n\n\tprivate _systemDefaults?: SystemDefaults<MergeConfigs<Cfg, Requires>>;\n\n\t/**\n\t * Set defaults applied to every system created via `world.addSystem(...)`\n\t * inside this plugin's install function. Calling again replaces the\n\t * previous defaults wholesale (not merge). Per-system builder calls\n\t * override defaults.\n\t */\n\tsetSystemDefaults(\n\t\tdefaults: SystemDefaults<MergeConfigs<Cfg, Requires>>,\n\t): this {\n\t\tthis._systemDefaults = defaults;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Declare component types this plugin provides.\n\t * Pure type-level operation with no runtime cost.\n\t */\n\twithComponentTypes<T extends Record<string, any>>(): PluginBuilder<\n\t\tWithComponents<Cfg, T>,\n\t\tRequires,\n\t\tLabels,\n\t\tGroups,\n\t\tAssetGroupNames,\n\t\tReactiveQueryNames\n\t> {\n\t\treturn this as unknown as PluginBuilder<\n\t\t\tWithComponents<Cfg, T>,\n\t\t\tRequires,\n\t\t\tLabels,\n\t\t\tGroups,\n\t\t\tAssetGroupNames,\n\t\t\tReactiveQueryNames\n\t\t>;\n\t}\n\n\t/**\n\t * Declare event types this plugin provides.\n\t * Pure type-level operation with no runtime cost.\n\t */\n\twithEventTypes<T extends Record<string, any>>(): PluginBuilder<\n\t\tWithEvents<Cfg, T>,\n\t\tRequires,\n\t\tLabels,\n\t\tGroups,\n\t\tAssetGroupNames,\n\t\tReactiveQueryNames\n\t> {\n\t\treturn this as unknown as PluginBuilder<\n\t\t\tWithEvents<Cfg, T>,\n\t\t\tRequires,\n\t\t\tLabels,\n\t\t\tGroups,\n\t\t\tAssetGroupNames,\n\t\t\tReactiveQueryNames\n\t\t>;\n\t}\n\n\t/**\n\t * Declare resource types this plugin provides.\n\t * Pure type-level operation with no runtime cost.\n\t */\n\twithResourceTypes<T extends Record<string, any>>(): PluginBuilder<\n\t\tWithResources<Cfg, T>,\n\t\tRequires,\n\t\tLabels,\n\t\tGroups,\n\t\tAssetGroupNames,\n\t\tReactiveQueryNames\n\t> {\n\t\treturn this as unknown as PluginBuilder<\n\t\t\tWithResources<Cfg, T>,\n\t\t\tRequires,\n\t\t\tLabels,\n\t\t\tGroups,\n\t\t\tAssetGroupNames,\n\t\t\tReactiveQueryNames\n\t\t>;\n\t}\n\n\t/**\n\t * Declare asset types this plugin provides.\n\t * Pure type-level operation with no runtime cost.\n\t */\n\twithAssetTypes<T extends Record<string, unknown>>(): PluginBuilder<\n\t\tWithAssets<Cfg, T>,\n\t\tRequires,\n\t\tLabels,\n\t\tGroups,\n\t\tAssetGroupNames,\n\t\tReactiveQueryNames\n\t> {\n\t\treturn this as unknown as PluginBuilder<\n\t\t\tWithAssets<Cfg, T>,\n\t\t\tRequires,\n\t\t\tLabels,\n\t\t\tGroups,\n\t\t\tAssetGroupNames,\n\t\t\tReactiveQueryNames\n\t\t>;\n\t}\n\n\t/**\n\t * Declare screen types this plugin provides.\n\t * Pure type-level operation with no runtime cost.\n\t */\n\twithScreenTypes<T extends Record<string, any>>(): PluginBuilder<\n\t\tWithScreens<Cfg, T>,\n\t\tRequires,\n\t\tLabels,\n\t\tGroups,\n\t\tAssetGroupNames,\n\t\tReactiveQueryNames\n\t> {\n\t\treturn this as unknown as PluginBuilder<\n\t\t\tWithScreens<Cfg, T>,\n\t\t\tRequires,\n\t\t\tLabels,\n\t\t\tGroups,\n\t\t\tAssetGroupNames,\n\t\t\tReactiveQueryNames\n\t\t>;\n\t}\n\n\t/**\n\t * Declare system labels this plugin registers.\n\t * Pure type-level operation with no runtime cost.\n\t */\n\twithLabels<L extends string>(): PluginBuilder<\n\t\tCfg,\n\t\tRequires,\n\t\tLabels | L,\n\t\tGroups,\n\t\tAssetGroupNames,\n\t\tReactiveQueryNames\n\t> {\n\t\treturn this as unknown as PluginBuilder<\n\t\t\tCfg,\n\t\t\tRequires,\n\t\t\tLabels | L,\n\t\t\tGroups,\n\t\t\tAssetGroupNames,\n\t\t\tReactiveQueryNames\n\t\t>;\n\t}\n\n\t/**\n\t * Declare system groups this plugin uses.\n\t * Pure type-level operation with no runtime cost.\n\t */\n\twithGroups<G extends string>(): PluginBuilder<\n\t\tCfg,\n\t\tRequires,\n\t\tLabels,\n\t\tGroups | G,\n\t\tAssetGroupNames,\n\t\tReactiveQueryNames\n\t> {\n\t\treturn this as unknown as PluginBuilder<\n\t\t\tCfg,\n\t\t\tRequires,\n\t\t\tLabels,\n\t\t\tGroups | G,\n\t\t\tAssetGroupNames,\n\t\t\tReactiveQueryNames\n\t\t>;\n\t}\n\n\t/**\n\t * Declare asset group names this plugin uses.\n\t * Pure type-level operation with no runtime cost.\n\t */\n\twithAssetGroupNames<N extends string>(): PluginBuilder<\n\t\tCfg,\n\t\tRequires,\n\t\tLabels,\n\t\tGroups,\n\t\tAssetGroupNames | N,\n\t\tReactiveQueryNames\n\t> {\n\t\treturn this as unknown as PluginBuilder<\n\t\t\tCfg,\n\t\t\tRequires,\n\t\t\tLabels,\n\t\t\tGroups,\n\t\t\tAssetGroupNames | N,\n\t\t\tReactiveQueryNames\n\t\t>;\n\t}\n\n\t/**\n\t * Declare reactive query names this plugin registers.\n\t * Pure type-level operation with no runtime cost.\n\t */\n\twithReactiveQueryNames<N extends string>(): PluginBuilder<\n\t\tCfg,\n\t\tRequires,\n\t\tLabels,\n\t\tGroups,\n\t\tAssetGroupNames,\n\t\tReactiveQueryNames | N\n\t> {\n\t\treturn this as unknown as PluginBuilder<\n\t\t\tCfg,\n\t\t\tRequires,\n\t\t\tLabels,\n\t\t\tGroups,\n\t\t\tAssetGroupNames,\n\t\t\tReactiveQueryNames | N\n\t\t>;\n\t}\n\n\t/**\n\t * Declare dependencies this plugin requires from other plugins.\n\t * Accepts a pre-built `WorldConfig` type (typically a named alias like\n\t * `TransformWorldConfig`). The install callback will see these types\n\t * merged into its world parameter.\n\t * Pure type-level operation with no runtime cost.\n\t */\n\trequires<R extends WorldConfig>(): PluginBuilder<\n\t\tCfg,\n\t\tR,\n\t\tLabels,\n\t\tGroups,\n\t\tAssetGroupNames,\n\t\tReactiveQueryNames\n\t> {\n\t\treturn this as unknown as PluginBuilder<\n\t\t\tCfg,\n\t\t\tR,\n\t\t\tLabels,\n\t\t\tGroups,\n\t\t\tAssetGroupNames,\n\t\t\tReactiveQueryNames\n\t\t>;\n\t}\n\n\t/**\n\t * Terminal method. Provide the install function and receive the finalized\n\t * `Plugin<...>` object. The install function receives a world typed as\n\t * `ECSpresso<MergeConfigs<Cfg, Requires>>` — meaning it can use both the\n\t * types this plugin provides and the types it declared via `.requires<>()`.\n\t */\n\tinstall(\n\t\tinstall: (world: ECSpresso<MergeConfigs<Cfg, Requires>>, onCleanup: PluginCleanupRegistrar) => void\n\t): Plugin<Cfg, Requires, Labels, Groups, AssetGroupNames, ReactiveQueryNames> {\n\t\treturn {\n\t\t\tid: this._id,\n\t\t\tinstall,\n\t\t\t...(this._systemDefaults ? { systemDefaults: this._systemDefaults } : {}),\n\t\t} as Plugin<Cfg, Requires, Labels, Groups, AssetGroupNames, ReactiveQueryNames>;\n\t}\n}\n\n/**\n * Entry point for the fluent plugin builder. Pass the plugin id and chain\n * type-accumulator methods, terminating with `.install(fn)`.\n *\n * @example\n * ```typescript\n * const myPlugin = definePlugin('my-plugin')\n * .withComponentTypes<MyComponents>()\n * .withResourceTypes<MyResources>()\n * .install((world) => { ... });\n * ```\n */\nexport function definePlugin(id: string): PluginBuilder {\n\treturn new PluginBuilder(id);\n}\n",
|
|
12
14
|
"import type ECSpresso from \"./ecspresso\";\nimport type { SystemDefaults } from \"./plugin\";\nimport type { FilteredEntity, QueryDefinition, System, SystemPhase } from \"./types\";\nimport type { WorldConfig, EmptyConfig } from \"./type-utils\";\n\nexport const PROCESS_EACH_QUERY = '__each' as const;\ntype ProcessEachKey = typeof PROCESS_EACH_QUERY;\n\n/**\n * Builder class for creating type-safe ECS Systems with proper query inference.\n * Systems are automatically registered with their ECSpresso instance when\n * finalized (at the start of initialize() or update()).\n */\nexport class SystemBuilder<\n\tCfg extends WorldConfig = EmptyConfig,\n\tQueries extends Record<string, QueryDefinition<Cfg['components']>> = {},\n\tLabel extends string = string,\n\tSysGroups extends string = never,\n\tResourceKeys extends keyof Cfg['resources'] = never,\n\tSingletons extends Record<string, QueryDefinition<Cfg['components']>> = {},\n> {\n\tprivate queries: Queries = {} as Queries;\n\tprivate singletons: Singletons = {} as Singletons;\n\tprivate processFunction?: InternalProcessFunction<Cfg, Queries, Singletons>;\n\tprivate detachFunction?: LifecycleFunction<Cfg>;\n\tprivate initializeFunction?: LifecycleFunction<Cfg>;\n\tprivate eventHandlers?: {\n\t\t[EventName in keyof Cfg['events']]?: (ctx: {\n\t\t\tdata: Cfg['events'][EventName];\n\t\t\tecs: ECSpresso<Cfg>;\n\t\t}) => void;\n\t};\n\tprivate _priority = 0;\n\tprivate _phase: SystemPhase = 'update';\n\tprivate _groups: string[] = [];\n\tprivate _inScreens?: ReadonlyArray<keyof Cfg['screens'] & string>;\n\tprivate _excludeScreens?: ReadonlyArray<keyof Cfg['screens'] & string>;\n\tprivate _requiredAssets?: ReadonlyArray<keyof Cfg['assets'] & string>;\n\tprivate _runWhenEmpty = false;\n\tprivate _entityEnterHandlers: Record<string, (ctx: { entity: any; ecs: any }) => void> = {};\n\tprivate _resourceKeys?: string[];\n\n\tconstructor(private _label: string, defaults?: SystemDefaults<Cfg>) {\n\t\tif (defaults) {\n\t\t\tif (defaults.phase !== undefined) this._phase = defaults.phase;\n\t\t\tif (defaults.priority !== undefined) this._priority = defaults.priority;\n\t\t\tif (defaults.inScreens !== undefined) this._inScreens = defaults.inScreens;\n\t\t\tif (defaults.excludeScreens !== undefined) this._excludeScreens = defaults.excludeScreens;\n\t\t}\n\t}\n\n\tget label() {\n\t\treturn this._label;\n\t}\n\n\t/**\n\t * Create a system object with all configured properties.\n\t * @internal Used by ECSpresso to finalize and register the system\n\t */\n\t_createSystemObject(): System<Cfg, any, any> {\n\t\tconst system: System<Cfg, any, any> = {\n\t\t\tlabel: this._label,\n\t\t\tentityQueries: this.queries,\n\t\t\tpriority: this._priority,\n\t\t\tphase: this._phase,\n\t\t};\n\n\t\tif (Object.keys(this.singletons).length > 0) {\n\t\t\tsystem.entitySingletons = this.singletons as Record<string, QueryDefinition<Cfg['components']>>;\n\t\t}\n\n\t\tif (this.processFunction) {\n\t\t\tsystem.process = this.processFunction;\n\t\t}\n\n\t\tif (this.detachFunction) {\n\t\t\tsystem.onDetach = this.detachFunction;\n\t\t}\n\n\t\tif (this.initializeFunction) {\n\t\t\tsystem.onInitialize = this.initializeFunction;\n\t\t}\n\n\t\tif (this.eventHandlers) {\n\t\t\tsystem.eventHandlers = this.eventHandlers;\n\t\t}\n\n\t\tif (this._groups.length > 0) {\n\t\t\tsystem.groups = [...this._groups];\n\t\t}\n\n\t\tif (this._inScreens) {\n\t\t\tsystem.inScreens = this._inScreens;\n\t\t}\n\n\t\tif (this._excludeScreens) {\n\t\t\tsystem.excludeScreens = this._excludeScreens;\n\t\t}\n\n\t\tif (this._requiredAssets) {\n\t\t\tsystem.requiredAssets = this._requiredAssets;\n\t\t}\n\n\t\tif (this._runWhenEmpty) {\n\t\t\tsystem.runWhenEmpty = true;\n\t\t}\n\n\t\tif (Object.keys(this._entityEnterHandlers).length > 0) {\n\t\t\tsystem.onEntityEnter = { ...this._entityEnterHandlers };\n\t\t}\n\n\t\treturn system;\n\t}\n\n\t/**\n\t * Set the priority of this system. Systems with higher priority values\n\t * execute before those with lower values. Systems with the same priority\n\t * execute in the order they were registered.\n\t * @param priority The priority value (default: 0)\n\t * @returns This SystemBuilder instance for method chaining\n\t */\n\tsetPriority(priority: number): this {\n\t\tthis._priority = priority;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Set the execution phase for this system.\n\t * Systems are grouped by phase and executed in order:\n\t * preUpdate -> fixedUpdate -> update -> postUpdate -> render\n\t * @param phase The phase to assign this system to (default: 'update')\n\t * @returns This SystemBuilder instance for method chaining\n\t */\n\tinPhase(phase: SystemPhase): this {\n\t\tthis._phase = phase;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Add this system to a group. Systems can belong to multiple groups.\n\t * When any group a system belongs to is disabled, the system will be skipped.\n\t * @param groupName The name of the group to add the system to\n\t * @returns This SystemBuilder instance for method chaining\n\t */\n\tinGroup<G extends string>(groupName: G): SystemBuilder<Cfg, Queries, Label, SysGroups | G, ResourceKeys, Singletons> {\n\t\tif (!this._groups.includes(groupName)) {\n\t\t\tthis._groups.push(groupName);\n\t\t}\n\t\treturn this as any;\n\t}\n\n\t/**\n\t * Restrict this system to only run in specified screens.\n\t * System will be skipped during update() when the current screen\n\t * is not in this list.\n\t * @param screens Array of screen names where this system should run\n\t * @returns This SystemBuilder instance for method chaining\n\t */\n\tinScreens(screens: ReadonlyArray<keyof Cfg['screens'] & string>): this {\n\t\tthis._inScreens = [...screens];\n\t\treturn this;\n\t}\n\n\t/**\n\t * Exclude this system from running in specified screens.\n\t * System will be skipped during update() when the current screen\n\t * is in this list.\n\t * @param screens Array of screen names where this system should NOT run\n\t * @returns This SystemBuilder instance for method chaining\n\t */\n\texcludeScreens(screens: ReadonlyArray<keyof Cfg['screens'] & string>): this {\n\t\tthis._excludeScreens = [...screens];\n\t\treturn this;\n\t}\n\n\t/**\n\t * Require specific assets to be loaded for this system to run.\n\t * System will be skipped during update() if any required asset\n\t * is not loaded.\n\t * @param assets Array of asset keys that must be loaded\n\t * @returns This SystemBuilder instance for method chaining\n\t */\n\trequiresAssets(assets: ReadonlyArray<keyof Cfg['assets'] & string>): this {\n\t\tthis._requiredAssets = [...assets];\n\t\treturn this;\n\t}\n\n\t/**\n\t * Allow this system to run even when all queries return zero entities.\n\t * By default, systems with queries are skipped when no entities match.\n\t */\n\trunWhenEmpty(): this {\n\t\tthis._runWhenEmpty = true;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Declare resource dependencies for this system. Resources are resolved\n\t * once (on first process call) and the same object is reused every frame.\n\t * The resolved resources are available as ctx.resources in setProcess.\n\t * @param keys Array of resource keys to resolve\n\t * @returns This SystemBuilder instance for method chaining\n\t */\n\twithResources<RK extends keyof Cfg['resources'] & string>(\n\t\tkeys: readonly RK[]\n\t): SystemBuilder<Cfg, Queries, Label, SysGroups, RK, Singletons> {\n\t\t(this as any)._resourceKeys = [...keys];\n\t\treturn this as any;\n\t}\n\n\t/**\n\t * Add a query definition to the system.\n\t *\n\t * When `mutates` is declared, every iterated entity is automatically\n\t * `markChanged`'d for each listed component after the system's\n\t * `process()` returns. Components in `with` but absent from `mutates`\n\t * are narrowed to `Readonly<T>` in the iteration entity type.\n\t */\n\taddQuery<\n\t\tQueryName extends string,\n\t\tWithComponents extends keyof Cfg['components'],\n\t\tWithoutComponents extends keyof Cfg['components'] = never,\n\t\tOptionalComponents extends keyof Cfg['components'] = never,\n\t\tMutatesComponents extends WithComponents = WithComponents,\n\t\tNewQueries extends Queries & Record<QueryName, QueryDefinition<Cfg['components'], WithComponents, WithoutComponents, OptionalComponents, MutatesComponents>> =\n\t\t\tQueries & Record<QueryName, QueryDefinition<Cfg['components'], WithComponents, WithoutComponents, OptionalComponents, MutatesComponents>>\n\t>(\n\t\tname: QueryName,\n\t\tdefinition: {\n\t\t\twith: ReadonlyArray<WithComponents>;\n\t\t\twithout?: ReadonlyArray<WithoutComponents>;\n\t\t\tchanged?: ReadonlyArray<WithComponents>;\n\t\t\toptional?: ReadonlyArray<OptionalComponents>;\n\t\t\tparentHas?: ReadonlyArray<keyof Cfg['components']>;\n\t\t\tmutates?: ReadonlyArray<MutatesComponents>;\n\t\t}\n\t): SystemBuilder<Cfg, NewQueries, Label, SysGroups, ResourceKeys, Singletons> {\n\t\t// Cast is needed because TypeScript can't preserve the type information\n\t\t// when modifying an object property\n\t\tconst newBuilder = this as any;\n\t\tnewBuilder.queries = {\n\t\t\t...this.queries,\n\t\t\t[name]: definition,\n\t\t};\n\t\treturn newBuilder;\n\t}\n\n\t/**\n\t * Add a singleton query — a named query that yields a single\n\t * `FilteredEntity | undefined` instead of an array. Surfaces on the\n\t * process context's `queries` object alongside regular queries.\n\t *\n\t * When multiple entities match, the first is returned (no error). Use\n\t * the instance-level `getSingleton` / `tryGetSingleton` helpers on\n\t * `ECSpresso` if you need strictness guarantees.\n\t *\n\t * When `mutates` is declared, the resolved entity is automatically\n\t * `markChanged`'d for each listed component after the system's\n\t * `process()` returns. Components in `with` but absent from `mutates`\n\t * are narrowed to `Readonly<T>` in the iteration entity type.\n\t */\n\taddSingleton<\n\t\tSingletonName extends string,\n\t\tWithComponents extends keyof Cfg['components'],\n\t\tWithoutComponents extends keyof Cfg['components'] = never,\n\t\tOptionalComponents extends keyof Cfg['components'] = never,\n\t\tMutatesComponents extends WithComponents = WithComponents,\n\t\tNewSingletons extends Singletons & Record<SingletonName, QueryDefinition<Cfg['components'], WithComponents, WithoutComponents, OptionalComponents, MutatesComponents>> =\n\t\t\tSingletons & Record<SingletonName, QueryDefinition<Cfg['components'], WithComponents, WithoutComponents, OptionalComponents, MutatesComponents>>\n\t>(\n\t\tname: SingletonName,\n\t\tdefinition: {\n\t\t\twith: ReadonlyArray<WithComponents>;\n\t\t\twithout?: ReadonlyArray<WithoutComponents>;\n\t\t\tchanged?: ReadonlyArray<WithComponents>;\n\t\t\toptional?: ReadonlyArray<OptionalComponents>;\n\t\t\tparentHas?: ReadonlyArray<keyof Cfg['components']>;\n\t\t\tmutates?: ReadonlyArray<MutatesComponents>;\n\t\t}\n\t): SystemBuilder<Cfg, Queries, Label, SysGroups, ResourceKeys, NewSingletons> {\n\t\tconst newBuilder = this as any;\n\t\tnewBuilder.singletons = {\n\t\t\t...this.singletons,\n\t\t\t[name]: definition,\n\t\t};\n\t\treturn newBuilder;\n\t}\n\n\t/**\n\t * Set the system's process function that runs each update.\n\t * The callback receives a single context object { queries, dt, ecs, resources? }.\n\t * The context is pre-allocated per system and reused every frame.\n\t * @param process Function to process entities matching the system's queries each update\n\t * @returns This SystemBuilder instance for method chaining\n\t */\n\tsetProcess(\n\t\tprocess: ProcessFunction<Cfg, Queries, ResourceKeys, Singletons>\n\t): this {\n\t\tthis.processFunction = this._wrapWithResources(process as (ctx: unknown) => void);\n\t\treturn this;\n\t}\n\n\tprivate _wrapWithResources(\n\t\tprocess: (ctx: unknown) => void,\n\t): InternalProcessFunction<Cfg, Queries, Singletons> {\n\t\tif (!this._resourceKeys?.length) {\n\t\t\treturn process as unknown as InternalProcessFunction<Cfg, Queries, Singletons>;\n\t\t}\n\t\tconst keys = this._resourceKeys;\n\t\tconst resolved: Record<string, unknown> = {};\n\t\tlet initialized = false;\n\t\treturn ((ctx) => {\n\t\t\tfor (const key of keys) {\n\t\t\t\tif (!initialized || ctx.ecs.isResourceObserved(key as keyof Cfg['resources'] & string)) {\n\t\t\t\t\tresolved[key] = ctx.ecs.getResource(key as keyof Cfg['resources'] & string);\n\t\t\t\t}\n\t\t\t}\n\t\t\tinitialized = true;\n\t\t\t(ctx as Record<string, unknown>)['resources'] = resolved;\n\t\t\tprocess(ctx);\n\t\t}) as InternalProcessFunction<Cfg, Queries, Singletons>;\n\t}\n\n\t/**\n\t * Inline-query terminator: define a single query and a per-entity callback\n\t * in one call. Collapses the common `addQuery` + `setProcess` + for-loop\n\t * pattern into a single chain step.\n\t *\n\t * Only valid on a builder with no prior queries or process function —\n\t * TypeScript narrows `this` to `never` otherwise, and a runtime guard\n\t * throws for untyped callers. For multi-query systems use\n\t * `addQuery` + `setProcess`.\n\t *\n\t * When `mutates` is declared, the callback may `return false` to skip the\n\t * auto-mark for that specific entity. Returning `true`, `undefined`, or\n\t * any other value stamps all components listed in `mutates`. Components\n\t * in `with` but absent from `mutates` are narrowed to `Readonly<T>` on\n\t * the per-entity iteration type.\n\t *\n\t * @param definition Inline query definition (with / without / optional / changed / parentHas / mutates)\n\t * @param process Callback invoked once per matching entity each frame\n\t */\n\tsetProcessEach<\n\t\tW extends keyof Cfg['components'],\n\t\tWO extends keyof Cfg['components'] = never,\n\t\tO extends keyof Cfg['components'] = never,\n\t\tM extends W = W,\n\t>(\n\t\tthis: [keyof Queries] extends [never]\n\t\t\t? [keyof Singletons] extends [never]\n\t\t\t\t? SystemBuilder<Cfg, Queries, Label, SysGroups, ResourceKeys, Singletons>\n\t\t\t\t: never\n\t\t\t: never,\n\t\tdefinition: {\n\t\t\twith: ReadonlyArray<W>;\n\t\t\twithout?: ReadonlyArray<WO>;\n\t\t\toptional?: ReadonlyArray<O>;\n\t\t\tchanged?: ReadonlyArray<W>;\n\t\t\tparentHas?: ReadonlyArray<keyof Cfg['components']>;\n\t\t\tmutates?: ReadonlyArray<M>;\n\t\t},\n\t\tprocess: (ctx: {\n\t\t\tentity: FilteredEntity<Cfg['components'], W, WO, O, M>;\n\t\t\tdt: number;\n\t\t\tecs: ECSpresso<Cfg>;\n\t\t} & ([ResourceKeys] extends [never]\n\t\t\t? {}\n\t\t\t: { resources: { readonly [K in ResourceKeys]: Cfg['resources'][K] } })\n\t\t) => boolean | void,\n\t): SystemBuilder<\n\t\tCfg,\n\t\tQueries & Record<ProcessEachKey, QueryDefinition<Cfg['components'], W, WO, O, M>>,\n\t\tLabel,\n\t\tSysGroups,\n\t\tResourceKeys,\n\t\tSingletons\n\t> {\n\t\t// The conditional `this:` parameter cannot be introspected in the body — cast to access private fields.\n\t\tconst self = this as unknown as {\n\t\t\tqueries: Record<string, unknown>;\n\t\t\tsingletons: Record<string, unknown>;\n\t\t\tprocessFunction?: unknown;\n\t\t\t_wrapWithResources(fn: (ctx: unknown) => void): InternalProcessFunction<Cfg, Queries, Singletons>;\n\t\t};\n\n\t\tif (Object.keys(self.queries).length > 0 || Object.keys(self.singletons).length > 0 || self.processFunction !== undefined) {\n\t\t\tthrow new Error(\n\t\t\t\t'setProcessEach requires a SystemBuilder with no prior queries, singletons, or process function. ' +\n\t\t\t\t'Use addQuery + setProcess for multi-query systems.',\n\t\t\t);\n\t\t}\n\n\t\tself.queries[PROCESS_EACH_QUERY] = definition;\n\n\t\tconst perEntityCtx = {\n\t\t\tentity: undefined as unknown,\n\t\t\tdt: 0,\n\t\t\tecs: undefined as unknown,\n\t\t\tresources: undefined as unknown,\n\t\t};\n\n\t\tconst mutates = definition.mutates && definition.mutates.length > 0\n\t\t\t? definition.mutates as ReadonlyArray<keyof Cfg['components']>\n\t\t\t: undefined;\n\n\t\tconst iterate = (ctx: unknown) => {\n\t\t\tconst frameCtx = ctx as {\n\t\t\t\tqueries: Record<string, ReadonlyArray<{ id: number }>>;\n\t\t\t\tdt: number;\n\t\t\t\tecs: { markChanged: (id: number, name: keyof Cfg['components']) => void };\n\t\t\t\tresources?: unknown;\n\t\t\t};\n\t\t\tconst entities = frameCtx.queries[PROCESS_EACH_QUERY];\n\t\t\tif (!entities) return;\n\t\t\tperEntityCtx.dt = frameCtx.dt;\n\t\t\tperEntityCtx.ecs = frameCtx.ecs;\n\t\t\tperEntityCtx.resources = frameCtx.resources;\n\t\t\tfor (let i = 0; i < entities.length; i++) {\n\t\t\t\tconst entity = entities[i];\n\t\t\t\tif (!entity) continue;\n\t\t\t\tperEntityCtx.entity = entity;\n\t\t\t\tconst result = (process as (c: unknown) => boolean | void)(perEntityCtx);\n\t\t\t\tif (mutates === undefined || result === false) continue;\n\t\t\t\tfor (let j = 0; j < mutates.length; j++) {\n\t\t\t\t\tconst name = mutates[j];\n\t\t\t\t\tif (name !== undefined) frameCtx.ecs.markChanged(entity.id, name);\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\n\t\tself.processFunction = self._wrapWithResources(iterate);\n\t\treturn this as unknown as SystemBuilder<\n\t\t\tCfg,\n\t\t\tQueries & Record<ProcessEachKey, QueryDefinition<Cfg['components'], W, WO, O, M>>,\n\t\t\tLabel,\n\t\t\tSysGroups,\n\t\t\tResourceKeys,\n\t\t\tSingletons\n\t\t>;\n\t}\n\n\t/**\n\t * Register a callback that fires once per entity the first time it appears\n\t * in a query's results. Fires before process. Automatic cleanup when entity\n\t * leaves the query so re-entry fires the callback again.\n\t * @param queryName Name of a query previously added via addQuery\n\t * @param callback Function called with the entity and ecs instance\n\t * @returns This SystemBuilder instance for method chaining\n\t */\n\tsetOnEntityEnter<QN extends keyof Queries & string>(\n\t\tqueryName: QN,\n\t\tcallback: (ctx: {\n\t\t\tentity: FilteredEntity<\n\t\t\t\tCfg['components'],\n\t\t\t\tQueries[QN] extends QueryDefinition<Cfg['components'], infer W> ? W : never,\n\t\t\t\tQueries[QN] extends QueryDefinition<Cfg['components'], any, infer WO> ? WO : never,\n\t\t\t\tQueries[QN] extends QueryDefinition<Cfg['components'], any, any, infer O> ? O : never\n\t\t\t>;\n\t\t\tecs: ECSpresso<Cfg>;\n\t\t}) => void,\n\t): this {\n\t\tthis._entityEnterHandlers[queryName] = callback;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Set the onDetach lifecycle hook\n\t * Called when the system is removed from the ECS\n\t * @param onDetach Function to run when this system is detached from the ECS\n\t * @returns This SystemBuilder instance for method chaining\n\t */\n\tsetOnDetach(\n\t\tonDetach: LifecycleFunction<Cfg>\n\t): this {\n\t\tthis.detachFunction = onDetach;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Set the onInitialize lifecycle hook.\n\t *\n\t * Fires exactly once per system. For systems added before `initialize()`,\n\t * the hook is awaited inside `initialize()` itself. For systems added\n\t * after `initialize()` has returned, the hook fires on registration (at\n\t * the next `update()`'s finalize step) — async hooks run fire-and-forget,\n\t * so don't rely on completion ordering against the first `process` call.\n\t *\n\t * @param onInitialize Function to run when this system is initialized\n\t * @returns This SystemBuilder instance for method chaining\n\t */\n\tsetOnInitialize(\n\t\tonInitialize: LifecycleFunction<Cfg>\n\t): this {\n\t\tthis.initializeFunction = onInitialize;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Set event handlers for the system\n\t * These handlers will be automatically subscribed when the system is attached\n\t * @param handlers Object mapping event names to handler functions\n\t * @returns This SystemBuilder instance for method chaining\n\t */\n\tsetEventHandlers(\n\t\thandlers: {\n\t\t\t[EventName in keyof Cfg['events']]?: (ctx: {\n\t\t\t\tdata: Cfg['events'][EventName];\n\t\t\t\tecs: ECSpresso<Cfg>;\n\t\t\t}) => void;\n\t\t}\n\t): this {\n\t\tthis.eventHandlers = handlers;\n\t\treturn this;\n\t}\n}\n\n// Helper type definitions\n\ntype QueryResults<\n\tComponentTypes extends Record<string, any>,\n\tQueries extends Record<string, QueryDefinition<ComponentTypes>>,\n\tSingletons extends Record<string, QueryDefinition<ComponentTypes>> = {},\n> = {\n\t[QueryName in keyof Queries]: QueryName extends string\n\t\t? FilteredEntity<\n\t\t\tComponentTypes,\n\t\t\tQueries[QueryName] extends QueryDefinition<ComponentTypes, infer W> ? W : never,\n\t\t\tQueries[QueryName] extends QueryDefinition<ComponentTypes, any, infer WO> ? WO : never,\n\t\t\tQueries[QueryName] extends QueryDefinition<ComponentTypes, any, any, infer O> ? O : never,\n\t\t\t// Fallback: if M isn't inferable, use W so everything in `with`\n\t\t\t// stays writable (matches pre-mutates behavior).\n\t\t\tQueries[QueryName] extends QueryDefinition<ComponentTypes, infer W2, any, any, infer M>\n\t\t\t\t? (unknown extends M ? W2 : M)\n\t\t\t\t: never\n\t\t>[]\n\t\t: never;\n} & {\n\t[SingletonName in keyof Singletons]: SingletonName extends string\n\t\t? FilteredEntity<\n\t\t\tComponentTypes,\n\t\t\tSingletons[SingletonName] extends QueryDefinition<ComponentTypes, infer W> ? W : never,\n\t\t\tSingletons[SingletonName] extends QueryDefinition<ComponentTypes, any, infer WO> ? WO : never,\n\t\t\tSingletons[SingletonName] extends QueryDefinition<ComponentTypes, any, any, infer O> ? O : never,\n\t\t\tSingletons[SingletonName] extends QueryDefinition<ComponentTypes, infer W2, any, any, infer M>\n\t\t\t\t? (unknown extends M ? W2 : M)\n\t\t\t\t: never\n\t\t> | undefined\n\t\t: never;\n};\n\n/**\n * Context object passed to system process functions.\n * Pre-allocated per system and reused every frame (zero per-frame allocation).\n * When resources are declared via withResources(), the context includes a\n * `resources` field with the resolved values (cached once on first call).\n */\nexport type ProcessContext<\n\tCfg extends WorldConfig,\n\tQueries extends Record<string, QueryDefinition<Cfg['components']>>,\n\tResourceKeys extends keyof Cfg['resources'] = never,\n\tSingletons extends Record<string, QueryDefinition<Cfg['components']>> = {},\n> = {\n\tqueries: QueryResults<Cfg['components'], Queries, Singletons>;\n\tdt: number;\n\tecs: ECSpresso<Cfg>;\n} & ([ResourceKeys] extends [never]\n\t? {}\n\t: { resources: { readonly [K in ResourceKeys]: Cfg['resources'][K] } });\n\n/**\n * Function signature for system process methods.\n * Receives a single context object with queries, dt, ecs, and optionally resources.\n */\ntype ProcessFunction<\n\tCfg extends WorldConfig,\n\tQueries extends Record<string, QueryDefinition<Cfg['components']>>,\n\tResourceKeys extends keyof Cfg['resources'] = never,\n\tSingletons extends Record<string, QueryDefinition<Cfg['components']>> = {},\n> = (ctx: ProcessContext<Cfg, Queries, ResourceKeys, Singletons>) => void;\n\n/**\n * Internal process function used for storage on System objects.\n * When resources are declared, the SystemBuilder wraps the user's function\n * to resolve and cache resources on the context object.\n */\ntype InternalProcessFunction<\n\tCfg extends WorldConfig,\n\tQueries extends Record<string, QueryDefinition<Cfg['components']>>,\n\tSingletons extends Record<string, QueryDefinition<Cfg['components']>> = {},\n> = (ctx: ProcessContext<Cfg, Queries, never, Singletons>) => void;\n\n/**\n * Type for system lifecycle functions\n * These can be asynchronous\n */\ntype LifecycleFunction<Cfg extends WorldConfig> = (\n\tecs: ECSpresso<Cfg>,\n) => void | Promise<void>;\n",
|
|
@@ -19,7 +21,7 @@
|
|
|
19
21
|
"/**\n * Shared vector math utilities for ECSpresso bundles.\n * All functions are pure — they return new vectors, never mutate inputs.\n */\n\n/**\n * A 2D vector with x and y components.\n */\nexport interface Vector2D {\n\tx: number;\n\ty: number;\n}\n\n/**\n * Create a Vector2D from x and y components.\n */\nexport function vec2(x: number, y: number): Vector2D {\n\treturn { x, y };\n}\n\n/**\n * Return a zero vector {x: 0, y: 0}.\n */\nexport function vec2Zero(): Vector2D {\n\treturn { x: 0, y: 0 };\n}\n\n/**\n * Add two vectors component-wise.\n */\nexport function vec2Add(a: Vector2D, b: Vector2D): Vector2D {\n\treturn { x: a.x + b.x, y: a.y + b.y };\n}\n\n/**\n * Subtract b from a component-wise.\n */\nexport function vec2Sub(a: Vector2D, b: Vector2D): Vector2D {\n\treturn { x: a.x - b.x, y: a.y - b.y };\n}\n\n/**\n * Scale a vector by a scalar.\n */\nexport function vec2Scale(v: Vector2D, scalar: number): Vector2D {\n\treturn { x: v.x * scalar, y: v.y * scalar };\n}\n\n/**\n * Negate a vector (flip both components).\n */\nexport function vec2Negate(v: Vector2D): Vector2D {\n\treturn { x: -v.x, y: -v.y };\n}\n\n/**\n * Compute the dot product of two vectors.\n */\nexport function vec2Dot(a: Vector2D, b: Vector2D): number {\n\treturn a.x * b.x + a.y * b.y;\n}\n\n/**\n * Compute the 2D cross product (scalar z-component of the 3D cross product).\n */\nexport function vec2Cross(a: Vector2D, b: Vector2D): number {\n\treturn a.x * b.y - a.y * b.x;\n}\n\n/**\n * Compute the squared length of a vector. Avoids sqrt when only comparing magnitudes.\n */\nexport function vec2LengthSq(v: Vector2D): number {\n\treturn v.x * v.x + v.y * v.y;\n}\n\n/**\n * Compute the length (magnitude) of a vector.\n */\nexport function vec2Length(v: Vector2D): number {\n\treturn Math.sqrt(v.x * v.x + v.y * v.y);\n}\n\n/**\n * Return a unit vector in the same direction. Returns zero vector if input is zero-length.\n */\nexport function vec2Normalize(v: Vector2D): Vector2D {\n\tconst len = Math.sqrt(v.x * v.x + v.y * v.y);\n\tif (len === 0) return { x: 0, y: 0 };\n\treturn { x: v.x / len, y: v.y / len };\n}\n\n/**\n * Compute the squared distance between two points. Avoids sqrt when only comparing.\n */\nexport function vec2DistanceSq(a: Vector2D, b: Vector2D): number {\n\tconst dx = a.x - b.x;\n\tconst dy = a.y - b.y;\n\treturn dx * dx + dy * dy;\n}\n\n/**\n * Compute the distance between two points.\n */\nexport function vec2Distance(a: Vector2D, b: Vector2D): number {\n\tconst dx = a.x - b.x;\n\tconst dy = a.y - b.y;\n\treturn Math.sqrt(dx * dx + dy * dy);\n}\n\n/**\n * Check if two vectors are approximately equal within an epsilon tolerance.\n */\nexport function vec2Equals(a: Vector2D, b: Vector2D, epsilon = 1e-10): boolean {\n\treturn Math.abs(a.x - b.x) <= epsilon && Math.abs(a.y - b.y) <= epsilon;\n}\n\n// ==================== Vector3D ====================\n\n/**\n * A 3D vector with x, y, and z components.\n */\nexport interface Vector3D {\n\tx: number;\n\ty: number;\n\tz: number;\n}\n\n/**\n * Create a Vector3D from x, y, and z components.\n */\nexport function vec3(x: number, y: number, z: number): Vector3D {\n\treturn { x, y, z };\n}\n\n/**\n * Return a zero vector {x: 0, y: 0, z: 0}.\n */\nexport function vec3Zero(): Vector3D {\n\treturn { x: 0, y: 0, z: 0 };\n}\n\n/**\n * Add two vectors component-wise.\n */\nexport function vec3Add(a: Vector3D, b: Vector3D): Vector3D {\n\treturn { x: a.x + b.x, y: a.y + b.y, z: a.z + b.z };\n}\n\n/**\n * Subtract b from a component-wise.\n */\nexport function vec3Sub(a: Vector3D, b: Vector3D): Vector3D {\n\treturn { x: a.x - b.x, y: a.y - b.y, z: a.z - b.z };\n}\n\n/**\n * Scale a vector by a scalar.\n */\nexport function vec3Scale(v: Vector3D, scalar: number): Vector3D {\n\treturn { x: v.x * scalar, y: v.y * scalar, z: v.z * scalar };\n}\n\n/**\n * Negate a vector (flip all components).\n */\nexport function vec3Negate(v: Vector3D): Vector3D {\n\treturn { x: -v.x, y: -v.y, z: -v.z };\n}\n\n/**\n * Compute the dot product of two vectors.\n */\nexport function vec3Dot(a: Vector3D, b: Vector3D): number {\n\treturn a.x * b.x + a.y * b.y + a.z * b.z;\n}\n\n/**\n * Compute the cross product of two vectors.\n */\nexport function vec3Cross(a: Vector3D, b: Vector3D): Vector3D {\n\treturn {\n\t\tx: a.y * b.z - a.z * b.y,\n\t\ty: a.z * b.x - a.x * b.z,\n\t\tz: a.x * b.y - a.y * b.x,\n\t};\n}\n\n/**\n * Compute the squared length of a vector. Avoids sqrt when only comparing magnitudes.\n */\nexport function vec3LengthSq(v: Vector3D): number {\n\treturn v.x * v.x + v.y * v.y + v.z * v.z;\n}\n\n/**\n * Compute the length (magnitude) of a vector.\n */\nexport function vec3Length(v: Vector3D): number {\n\treturn Math.sqrt(v.x * v.x + v.y * v.y + v.z * v.z);\n}\n\n/**\n * Return a unit vector in the same direction. Returns zero vector if input is zero-length.\n */\nexport function vec3Normalize(v: Vector3D): Vector3D {\n\tconst len = Math.sqrt(v.x * v.x + v.y * v.y + v.z * v.z);\n\tif (len === 0) return { x: 0, y: 0, z: 0 };\n\treturn { x: v.x / len, y: v.y / len, z: v.z / len };\n}\n\n/**\n * Compute the squared distance between two points. Avoids sqrt when only comparing.\n */\nexport function vec3DistanceSq(a: Vector3D, b: Vector3D): number {\n\tconst dx = a.x - b.x;\n\tconst dy = a.y - b.y;\n\tconst dz = a.z - b.z;\n\treturn dx * dx + dy * dy + dz * dz;\n}\n\n/**\n * Compute the distance between two points.\n */\nexport function vec3Distance(a: Vector3D, b: Vector3D): number {\n\tconst dx = a.x - b.x;\n\tconst dy = a.y - b.y;\n\tconst dz = a.z - b.z;\n\treturn Math.sqrt(dx * dx + dy * dy + dz * dz);\n}\n\n/**\n * Check if two vectors are approximately equal within an epsilon tolerance.\n */\nexport function vec3Equals(a: Vector3D, b: Vector3D, epsilon = 1e-10): boolean {\n\treturn Math.abs(a.x - b.x) <= epsilon && Math.abs(a.y - b.y) <= epsilon && Math.abs(a.z - b.z) <= epsilon;\n}\n",
|
|
20
22
|
"import ECSpresso from './ecspresso';\nimport { SystemBuilder, type ProcessContext } from './system-builder';\nimport { type Plugin, type BasePluginOptions, type PluginCleanupRegistrar, definePlugin } from './plugin';\n\nexport * from './types';\nexport * from './asset-types';\nexport * from './screen-types';\nexport * from './utils/math';\nexport type { ReactiveQueryDefinition } from './reactive-query-manager';\nexport { default as AssetManager, createAssetConfigurator } from './asset-manager';\nexport { default as ScreenManager, createScreenConfigurator } from './screen-manager';\nexport { SystemBuilder, type ProcessContext };\nexport { type Plugin, type BasePluginOptions, type PluginCleanupRegistrar, definePlugin };\nexport { directValue, type ResourceDirectValue } from './resource-manager';\nexport default ECSpresso;\n"
|
|
21
23
|
],
|
|
22
|
-
"mappings": "4PAMA,MAAqB,CAAiB,CAE7B,UAAiC,IAAI,IAErC,YAAqC,IAAI,IAEzC,UAAsB,CAAC,EAQ/B,SAAS,CAAC,EAAiB,EAAwB,CAClD,GAAI,IAAY,EACf,MAAU,MAAM,qBAAqB,qBAA2B,EAIjE,GAAI,KAAK,iBAAiB,EAAS,CAAQ,EAC1C,MAAU,MAAM,oDAAoD,EAIrE,IAAM,EAAY,KAAK,UAAU,IAAI,CAAO,EAC5C,GAAI,IAAc,OAAW,CAC5B,IAAM,EAAc,KAAK,YAAY,IAAI,CAAS,EAClD,GAAI,EAAa,CAChB,IAAM,EAAM,EAAY,QAAQ,CAAO,EACvC,GAAI,IAAQ,GACX,EAAY,OAAO,EAAK,CAAC,GAM5B,KAAK,UAAU,IAAI,EAAS,CAAQ,EAGpC,IAAM,EAAW,KAAK,YAAY,IAAI,CAAQ,EAC9C,GAAI,EACH,EAAS,KAAK,CAAO,EAErB,UAAK,YAAY,IAAI,EAAU,CAAC,CAAO,CAAC,EAGzC,OAAO,KAQR,YAAY,CAAC,EAA0B,CACtC,IAAM,EAAW,KAAK,UAAU,IAAI,CAA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E,EACb,EAAK,EAAE,EAAI,EAAE,EACb,EAAK,EAAE,EAAI,EAAE,EACnB,OAAO,EAAK,EAAK,EAAK,EAAK,EAAK,EAM1B,SAAS,EAAY,CAAC,EAAa,EAAqB,CAC9D,IAAM,EAAK,EAAE,EAAI,EAAE,EACb,EAAK,EAAE,EAAI,EAAE,EACb,EAAK,EAAE,EAAI,EAAE,EACnB,OAAO,KAAK,KAAK,EAAK,EAAK,EAAK,EAAK,EAAK,CAAE,EAMtC,SAAS,EAAU,CAAC,EAAa,EAAa,EAAU,aAAgB,CAC9E,OAAO,KAAK,IAAI,EAAE,EAAI,EAAE,CAAC,GAAK,GAAW,KAAK,IAAI,EAAE,EAAI,EAAE,CAAC,GAAK,GAAW,KAAK,IAAI,EAAE,EAAI,EAAE,CAAC,GAAK,EC7NnG,IAAe",
|
|
25
|
+
"debugId": "F8BB117EED11301264756E2164756E21",
|
|
24
26
|
"names": []
|
|
25
27
|
}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import type { Entity } from "./types";
|
|
2
|
+
import { type MatchHost } from "./query-match";
|
|
3
|
+
/**
|
|
4
|
+
* Host interface that QueryCache uses to read EntityManager state.
|
|
5
|
+
* Decouples QueryCache from EntityManager's private fields.
|
|
6
|
+
*/
|
|
7
|
+
export interface QueryCacheHost<ComponentTypes> extends MatchHost<ComponentTypes> {
|
|
8
|
+
getChildren(parentId: number): readonly number[];
|
|
9
|
+
allEntities(): IterableIterator<Entity<ComponentTypes>>;
|
|
10
|
+
componentIndex(component: keyof ComponentTypes): Set<number> | undefined;
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* Maintains incrementally-updated Sets of entity IDs matching the static
|
|
14
|
+
* portion of registered query shapes (with / without / parentHas).
|
|
15
|
+
* EntityManager calls the on* hooks on component add/remove, entity
|
|
16
|
+
* removal, and parent change. The `changed` filter is applied as a
|
|
17
|
+
* post-pass by the caller, since its threshold advances each tick.
|
|
18
|
+
*/
|
|
19
|
+
export default class QueryCache<ComponentTypes> {
|
|
20
|
+
private readonly host;
|
|
21
|
+
private readonly caches;
|
|
22
|
+
private readonly byComp;
|
|
23
|
+
private readonly byParentComp;
|
|
24
|
+
constructor(host: QueryCacheHost<ComponentTypes>);
|
|
25
|
+
/**
|
|
26
|
+
* Returns the Set of entity IDs matching the (with, without, parentHas)
|
|
27
|
+
* shape. Caches are interned by canonical shape — identical shapes share
|
|
28
|
+
* a single Set across systems. Cold-start populates by iterating the
|
|
29
|
+
* smallest matching component index.
|
|
30
|
+
*/
|
|
31
|
+
getOrCreate(withC: ReadonlyArray<keyof ComponentTypes>, withoutC: ReadonlyArray<keyof ComponentTypes>, parentHas: ReadonlyArray<keyof ComponentTypes>): Set<number>;
|
|
32
|
+
/** Test-only: returns the number of distinct interned shapes. */
|
|
33
|
+
get cacheCount(): number;
|
|
34
|
+
private populate;
|
|
35
|
+
private matches;
|
|
36
|
+
private reeval;
|
|
37
|
+
onComponentChanged(entityId: number, componentName: keyof ComponentTypes): void;
|
|
38
|
+
onParentChanged(childId: number): void;
|
|
39
|
+
/**
|
|
40
|
+
* Drops the entity from every cache. For parentHas caches, also drops
|
|
41
|
+
* direct children — once this entity is gone, the parent-link severs
|
|
42
|
+
* and children stop matching. Cascade-removed children fire their own
|
|
43
|
+
* beforeRemoved first, so the extra delete is a harmless no-op there.
|
|
44
|
+
*/
|
|
45
|
+
onEntityRemoved(entityId: number): void;
|
|
46
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import type { Entity } from "./types";
|
|
2
|
+
/** Minimal lookup surface needed to evaluate `parentHas`. */
|
|
3
|
+
export interface MatchHost<ComponentTypes> {
|
|
4
|
+
getEntity(entityId: number): Entity<ComponentTypes> | undefined;
|
|
5
|
+
getParent(entityId: number): number | null;
|
|
6
|
+
}
|
|
7
|
+
/**
|
|
8
|
+
* Returns true when `entity` matches the static portion of a query shape:
|
|
9
|
+
* has every `with` component, no `without` component, and (if `parentHas`)
|
|
10
|
+
* a direct parent that has every `parentHas` component. Shared between
|
|
11
|
+
* QueryCache (membership maintenance) and ReactiveQueryManager (enter/exit
|
|
12
|
+
* dispatch) so both use the same predicate.
|
|
13
|
+
*/
|
|
14
|
+
export declare function entityMatchesShape<ComponentTypes>(entity: Entity<ComponentTypes>, withC: ReadonlyArray<keyof ComponentTypes>, withoutC: ReadonlyArray<keyof ComponentTypes> | undefined, parentHas: ReadonlyArray<keyof ComponentTypes> | undefined, host: MatchHost<ComponentTypes>): boolean;
|
|
@@ -42,9 +42,6 @@ export default class ReactiveQueryManager<ComponentTypes extends Record<string,
|
|
|
42
42
|
* @returns true if the query existed and was removed
|
|
43
43
|
*/
|
|
44
44
|
removeQuery(name: QueryNames): boolean;
|
|
45
|
-
/**
|
|
46
|
-
* Check if an entity matches a query definition
|
|
47
|
-
*/
|
|
48
45
|
private entityMatchesQuery;
|
|
49
46
|
/**
|
|
50
47
|
* Apply enter/exit transitions for a single query against an entity.
|