ecspresso 0.5.0 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +379 -9
- package/dist/bundle.d.ts +5 -2
- package/dist/bundles/renderers/pixi.d.ts +235 -0
- package/dist/bundles/renderers/pixi.js +4 -0
- package/dist/bundles/renderers/pixi.js.map +13 -0
- package/dist/bundles/utils/bounds.d.ts +186 -0
- package/dist/bundles/utils/collision.d.ts +201 -0
- package/dist/bundles/utils/movement.d.ts +83 -0
- package/dist/bundles/utils/timers.d.ts +169 -0
- package/dist/bundles/utils/timers.js +4 -0
- package/dist/bundles/utils/timers.js.map +12 -0
- package/dist/bundles/utils/transform.d.ts +148 -0
- package/dist/command-buffer.d.ts +90 -0
- package/dist/ecspresso.d.ts +137 -3
- package/dist/entity-manager.d.ts +19 -3
- package/dist/hierarchy-manager.d.ts +15 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +2 -2
- package/dist/index.js.map +13 -11
- package/dist/reactive-query-manager.d.ts +59 -0
- package/dist/resource-manager.d.ts +37 -5
- package/dist/system-builder.d.ts +8 -0
- package/dist/types.d.ts +22 -0
- package/package.json +23 -3
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Timer Bundle for ECSpresso
|
|
3
|
+
*
|
|
4
|
+
* Provides ECS-native timers following the "data, not callbacks" philosophy.
|
|
5
|
+
* Timers are components processed each frame, automatically cleaned up when entities are removed.
|
|
6
|
+
*/
|
|
7
|
+
import Bundle from '../../bundle';
|
|
8
|
+
/**
|
|
9
|
+
* Data structure published when a timer completes.
|
|
10
|
+
* Use this type when defining timer completion events in your EventTypes interface.
|
|
11
|
+
*
|
|
12
|
+
* @example
|
|
13
|
+
* ```typescript
|
|
14
|
+
* interface Events {
|
|
15
|
+
* hideMessage: TimerEventData;
|
|
16
|
+
* spawnWave: TimerEventData;
|
|
17
|
+
* }
|
|
18
|
+
* ```
|
|
19
|
+
*/
|
|
20
|
+
export interface TimerEventData {
|
|
21
|
+
/** The entity ID that the timer belongs to */
|
|
22
|
+
entityId: number;
|
|
23
|
+
/** The timer's configured duration in seconds */
|
|
24
|
+
duration: number;
|
|
25
|
+
/** The actual elapsed time (may exceed duration slightly) */
|
|
26
|
+
elapsed: number;
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* Extracts event names from EventTypes that have TimerEventData as their payload.
|
|
30
|
+
* This ensures only compatible events can be used with timer.onComplete.
|
|
31
|
+
*/
|
|
32
|
+
export type TimerEventName<EventTypes extends Record<string, any>> = {
|
|
33
|
+
[K in keyof EventTypes]: EventTypes[K] extends TimerEventData ? K : never;
|
|
34
|
+
}[keyof EventTypes];
|
|
35
|
+
/**
|
|
36
|
+
* Timer component data structure.
|
|
37
|
+
* Use `justFinished` to detect timer completion in your systems.
|
|
38
|
+
*
|
|
39
|
+
* @template EventTypes The event types from your ECS
|
|
40
|
+
*/
|
|
41
|
+
export interface Timer<EventTypes extends Record<string, any>> {
|
|
42
|
+
/** Time accumulated so far (seconds) */
|
|
43
|
+
elapsed: number;
|
|
44
|
+
/** Target duration (seconds) */
|
|
45
|
+
duration: number;
|
|
46
|
+
/** Whether timer repeats after completion */
|
|
47
|
+
repeat: boolean;
|
|
48
|
+
/** Whether timer is currently running */
|
|
49
|
+
active: boolean;
|
|
50
|
+
/** True for one frame after timer completes */
|
|
51
|
+
justFinished: boolean;
|
|
52
|
+
/** Optional event name to publish when timer completes. Must be an event with TimerEventData payload. */
|
|
53
|
+
onComplete?: TimerEventName<EventTypes>;
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Component types provided by the timer bundle.
|
|
57
|
+
* Extend your component types with this interface.
|
|
58
|
+
*
|
|
59
|
+
* @template EventTypes The event types from your ECS
|
|
60
|
+
*
|
|
61
|
+
* @example
|
|
62
|
+
* ```typescript
|
|
63
|
+
* interface GameComponents extends TimerComponentTypes<GameEvents> {
|
|
64
|
+
* velocity: { x: number; y: number };
|
|
65
|
+
* player: true;
|
|
66
|
+
* }
|
|
67
|
+
* ```
|
|
68
|
+
*/
|
|
69
|
+
export interface TimerComponentTypes<EventTypes extends Record<string, any>> {
|
|
70
|
+
timer: Timer<EventTypes>;
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* Configuration options for the timer bundle.
|
|
74
|
+
*/
|
|
75
|
+
export interface TimerBundleOptions {
|
|
76
|
+
/** System group name (default: 'timers') */
|
|
77
|
+
systemGroup?: string;
|
|
78
|
+
/** Priority for timer update system (default: 0) */
|
|
79
|
+
priority?: number;
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* Options for timer creation
|
|
83
|
+
*
|
|
84
|
+
* @template EventTypes The event types from your ECS
|
|
85
|
+
*/
|
|
86
|
+
export interface TimerOptions<EventTypes extends Record<string, any>> {
|
|
87
|
+
/** Event name to publish when timer completes. Must be an event with TimerEventData payload. */
|
|
88
|
+
onComplete?: TimerEventName<EventTypes>;
|
|
89
|
+
}
|
|
90
|
+
/**
|
|
91
|
+
* Create a one-shot timer that fires once after the specified duration.
|
|
92
|
+
*
|
|
93
|
+
* @template EventTypes The event types from your ECS (must be explicitly provided)
|
|
94
|
+
* @param duration Duration in seconds until the timer completes
|
|
95
|
+
* @param options Optional configuration including event name
|
|
96
|
+
* @returns Component object suitable for spreading into spawn()
|
|
97
|
+
*
|
|
98
|
+
* @example
|
|
99
|
+
* ```typescript
|
|
100
|
+
* // Timer without event
|
|
101
|
+
* ecs.spawn({
|
|
102
|
+
* ...createTimer<GameEvents>(2),
|
|
103
|
+
* explosion: true,
|
|
104
|
+
* });
|
|
105
|
+
*
|
|
106
|
+
* // Timer that publishes an event on completion
|
|
107
|
+
* ecs.spawn({
|
|
108
|
+
* ...createTimer<GameEvents>(1.5, { onComplete: 'hideMessage' }),
|
|
109
|
+
* });
|
|
110
|
+
* ```
|
|
111
|
+
*/
|
|
112
|
+
export declare function createTimer<EventTypes extends Record<string, any>>(duration: number, options?: TimerOptions<EventTypes>): Pick<TimerComponentTypes<EventTypes>, 'timer'>;
|
|
113
|
+
/**
|
|
114
|
+
* Create a repeating timer that fires every `duration` seconds.
|
|
115
|
+
*
|
|
116
|
+
* @template EventTypes The event types from your ECS (must be explicitly provided)
|
|
117
|
+
* @param duration Duration in seconds between each timer completion
|
|
118
|
+
* @param options Optional configuration including event name
|
|
119
|
+
* @returns Component object suitable for spreading into spawn()
|
|
120
|
+
*
|
|
121
|
+
* @example
|
|
122
|
+
* ```typescript
|
|
123
|
+
* // Timer without event
|
|
124
|
+
* ecs.spawn({
|
|
125
|
+
* ...createRepeatingTimer<GameEvents>(5),
|
|
126
|
+
* spawner: true,
|
|
127
|
+
* });
|
|
128
|
+
*
|
|
129
|
+
* // Repeating timer that publishes an event each cycle
|
|
130
|
+
* ecs.spawn({
|
|
131
|
+
* ...createRepeatingTimer<GameEvents>(3, { onComplete: 'spawnWave' }),
|
|
132
|
+
* });
|
|
133
|
+
* ```
|
|
134
|
+
*/
|
|
135
|
+
export declare function createRepeatingTimer<EventTypes extends Record<string, any>>(duration: number, options?: TimerOptions<EventTypes>): Pick<TimerComponentTypes<EventTypes>, 'timer'>;
|
|
136
|
+
/**
|
|
137
|
+
* Create a timer bundle for ECSpresso.
|
|
138
|
+
*
|
|
139
|
+
* This bundle provides:
|
|
140
|
+
* - Timer update system that processes all timer components each frame
|
|
141
|
+
* - `justFinished` flag pattern for one-frame completion detection
|
|
142
|
+
* - Automatic cleanup when entities are removed
|
|
143
|
+
*
|
|
144
|
+
* @example
|
|
145
|
+
* ```typescript
|
|
146
|
+
* const ecs = ECSpresso
|
|
147
|
+
* .create<Components, Events, Resources>()
|
|
148
|
+
* .withBundle(createTimerBundle())
|
|
149
|
+
* .build();
|
|
150
|
+
*
|
|
151
|
+
* // Spawn entity with timer
|
|
152
|
+
* ecs.spawn({
|
|
153
|
+
* ...createRepeatingTimer(5),
|
|
154
|
+
* spawner: true,
|
|
155
|
+
* });
|
|
156
|
+
*
|
|
157
|
+
* // React to timer completion in a system
|
|
158
|
+
* ecs.addSystem('spawn-on-timer')
|
|
159
|
+
* .addQuery('spawners', { with: ['timer', 'spawner'] })
|
|
160
|
+
* .setProcess((queries, _dt, ecs) => {
|
|
161
|
+
* for (const { components } of queries.spawners) {
|
|
162
|
+
* if (components.timer.justFinished) {
|
|
163
|
+
* ecs.spawn({ enemy: true });
|
|
164
|
+
* }
|
|
165
|
+
* }
|
|
166
|
+
* });
|
|
167
|
+
* ```
|
|
168
|
+
*/
|
|
169
|
+
export declare function createTimerBundle<EventTypes extends Record<string, any>>(options?: TimerBundleOptions): Bundle<TimerComponentTypes<EventTypes>, EventTypes, {}>;
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
var $=Object.create;var{getPrototypeOf:G,defineProperty:Z,getOwnPropertyNames:q}=Object;var z=Object.prototype.hasOwnProperty;var P=(j,x,F)=>{F=j!=null?$(G(j)):{};let K=x||!j||!j.__esModule?Z(F,"default",{value:j,enumerable:!0}):F;for(let H of q(j))if(!z.call(K,H))Z(K,H,{get:()=>j[H],enumerable:!0});return K};var W=((j)=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(j,{get:(x,F)=>(typeof require<"u"?require:x)[F]}):j)(function(j){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+j+'" is not supported')});class Y{_label;_ecspresso;_bundle;queries={};processFunction;detachFunction;initializeFunction;eventHandlers;_priority=0;_isRegistered=!1;_groups=[];_inScreens;_excludeScreens;_requiredAssets;constructor(j,x=null,F=null){this._label=j;this._ecspresso=x;this._bundle=F}get label(){return this._label}get bundle(){return this._bundle}get ecspresso(){return this._ecspresso}_autoRegister(){if(this._isRegistered||!this._ecspresso)return;let j=this._buildSystemObject();X(j,this._ecspresso),this._isRegistered=!0}_buildSystemObject(){return this._createSystemObject()}_createSystemObject(){let j={label:this._label,entityQueries:this.queries,priority:this._priority};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;return j}setPriority(j){return this._priority=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}addQuery(j,x){let F=this;return F.queries={...this.queries,[j]:x},F}setProcess(j){return this.processFunction=j,this}registerAndContinue(){if(!this._ecspresso)throw Error(`Cannot register system '${this._label}': SystemBuilder is not attached to an ECSpresso instance. Use Bundle.addSystem() or ECSpresso.addSystem() instead.`);return this._autoRegister(),this._ecspresso}and(){if(this._ecspresso)return this._autoRegister(),this._ecspresso;if(this._bundle)return this._bundle;throw Error(`Cannot use and() on system '${this._label}': not attached to ECSpresso or Bundle.`)}setOnDetach(j){return this.detachFunction=j,this}setOnInitialize(j){return this.initializeFunction=j,this}setEventHandlers(j){return this.eventHandlers=j,this}build(j){let x=this._createSystemObject();if(this._ecspresso)X(x,this._ecspresso);if(j)X(x,j);return this}}function X(j,x){x._registerSystem(j)}function D(j,x){return new Y(j,x)}function _(j,x){return new Y(j,null,x)}function C(){return`bundle_${Date.now().toString(36)}_${Math.random().toString(36).substring(2,9)}`}class U{_systems=[];_resources=new Map;_assets=new Map;_assetGroups=new Map;_screens=new Map;_id;constructor(j){this._id=j||C()}get id(){return this._id}set id(j){this._id=j}addSystem(j){if(typeof j==="string"){let x=_(j,this);return this._systems.push(x),x}else return this._systems.push(j),j}addResource(j,x){return this._resources.set(j,x),this}addAsset(j,x,F){return this._assets.set(j,{loader:x,eager:F?.eager??!0,group:F?.group}),this}addAssetGroup(j,x){let F=new Map;for(let[K,H]of Object.entries(x))F.set(K,H),this._assets.set(K,{loader:H,eager:!1,group:j});return this._assetGroups.set(j,F),this}addScreen(j,x){return this._screens.set(j,x),this}getAssets(){return new Map(this._assets)}getScreens(){return new Map(this._screens)}_setResource(j,x){this._resources.set(j,x)}_setAsset(j,x){this._assets.set(j,x)}_setScreen(j,x){this._screens.set(j,x)}getSystems(){return this._systems.map((j)=>j.build())}registerSystemsWithEcspresso(j){for(let x of this._systems)x.build(j)}getResources(){return new Map(this._resources)}getResource(j){return this._resources.get(j)}getSystemBuilders(){return[...this._systems]}hasResource(j){return this._resources.has(j)}}function O(j,...x){if(x.length===0)return new U(j);let F=new U(j);for(let K of x){for(let H of K.getSystemBuilders())F.addSystem(H);for(let[H,M]of K.getResources().entries())F._setResource(H,M);for(let[H,M]of K.getAssets().entries())F._setAsset(H,M);for(let[H,M]of K.getScreens().entries())F._setScreen(H,M)}return F}function T(j,x){return{timer:{elapsed:0,duration:j,repeat:!1,active:!0,justFinished:!1,onComplete:x?.onComplete}}}function S(j,x){return{timer:{elapsed:0,duration:j,repeat:!0,active:!0,justFinished:!1,onComplete:x?.onComplete}}}function k(j){let{systemGroup:x="timers",priority:F=0}=j??{},K=new U("timers");K.addSystem("timer-update").setPriority(F).inGroup(x).addQuery("timers",{with:["timer"]}).setProcess((M,V,Q)=>{for(let R of M.timers){let{timer:J}=R.components;if(J.justFinished=!1,!J.active)continue;if(J.elapsed+=V,J.elapsed<J.duration)continue;if(J.repeat)while(J.elapsed>=J.duration)J.justFinished=!0,H(Q,R.id,J),J.elapsed-=J.duration;else J.justFinished=!0,H(Q,R.id,J),J.active=!1,Q.commands.removeEntity(R.id)}}).and();function H(M,V,Q){if(!Q.onComplete)return;let R={entityId:V,duration:Q.duration,elapsed:Q.elapsed};M.eventBus.publish(Q.onComplete,R)}return K}export{k as createTimerBundle,T as createTimer,S as createRepeatingTimer};
|
|
2
|
+
|
|
3
|
+
//# debugId=8A5D1E808447563C64756E2164756E21
|
|
4
|
+
//# sourceMappingURL=timers.js.map
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/system-builder.ts", "../src/bundle.ts", "../src/bundles/utils/timers.ts"],
|
|
4
|
+
"sourcesContent": [
|
|
5
|
+
"import Bundle from \"./bundle\";\nimport ECSpresso from \"./ecspresso\";\nimport type { FilteredEntity, System } from \"./types\";\n\n/**\n * Builder class for creating type-safe ECS Systems with proper query inference\n */\nexport class SystemBuilder<\n\tComponentTypes extends Record<string, any> = Record<string, any>,\n\tEventTypes extends Record<string, any> = Record<string, any>,\n\tResourceTypes extends Record<string, any> = Record<string, any>,\n\tQueries extends Record<string, QueryDefinition<ComponentTypes>> = {},\n> {\n\tprivate queries: Queries = {} as Queries;\n\tprivate processFunction?: ProcessFunction<ComponentTypes, EventTypes, ResourceTypes, Queries>;\n\tprivate detachFunction?: LifecycleFunction<ComponentTypes, EventTypes, ResourceTypes>;\n\tprivate initializeFunction?: LifecycleFunction<ComponentTypes, EventTypes, ResourceTypes>;\n\tprivate eventHandlers?: {\n\t\t[EventName in keyof EventTypes]?: {\n\t\t\thandler(\n\t\t\t\tdata: EventTypes[EventName],\n\t\t\t\tecs: ECSpresso<\n\t\t\t\t\tComponentTypes,\n\t\t\t\t\tEventTypes,\n\t\t\t\t\tResourceTypes\n\t\t\t\t>,\n\t\t\t): void;\n\t\t};\n\t};\n\tprivate _priority = 0; // Default priority is 0\n\tprivate _isRegistered = false; // Track if system has been auto-registered\n\tprivate _groups: string[] = [];\n\tprivate _inScreens?: string[];\n\tprivate _excludeScreens?: string[];\n\tprivate _requiredAssets?: string[];\n\n\tconstructor(\n\t\tprivate _label: string,\n\t\tprivate _ecspresso: ECSpresso<ComponentTypes, EventTypes, ResourceTypes> | null = null,\n\t\tprivate _bundle: Bundle<ComponentTypes, EventTypes, ResourceTypes> | null = null,\n\t) {}\n\n\tget label() {\n\t\treturn this._label;\n\t}\n\n\t/**\n\t * Returns the associated bundle if one was provided in the constructor\n\t */\n\tget bundle() {\n\t\treturn this._bundle;\n\t}\n\n\t/**\n\t * Returns the associated ECSpresso instance if one was provided in the constructor\n\t */\n\tget ecspresso() {\n\t\treturn this._ecspresso;\n\t}\n\n\t/**\n\t * Auto-register this system with its ECSpresso instance if not already registered\n\t * @private\n\t */\n\tprivate _autoRegister(): void {\n\t\tif (this._isRegistered || !this._ecspresso) return;\n\t\t\n\t\tconst system = this._buildSystemObject();\n\t\tregisterSystemWithEcspresso(system, this._ecspresso);\n\t\tthis._isRegistered = true;\n\t}\n\n\t/**\n\t * Create the system object without registering it\n\t * @private\n\t */\n\tprivate _buildSystemObject(): System<ComponentTypes, any, any, EventTypes, ResourceTypes> {\n\t\treturn this._createSystemObject();\n\t}\n\n\t/**\n\t * Create a system object with all configured properties\n\t * @private\n\t */\n\tprivate _createSystemObject(): System<ComponentTypes, any, any, EventTypes, ResourceTypes> {\n\t\tconst system: System<ComponentTypes, any, any, EventTypes, ResourceTypes> = {\n\t\t\tlabel: this._label,\n\t\t\tentityQueries: this.queries,\n\t\t\tpriority: this._priority,\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\treturn system;\n\t}\n\n\t// TODO: Should this be a setter?\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 * 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(groupName: string): this {\n\t\tif (!this._groups.includes(groupName)) {\n\t\t\tthis._groups.push(groupName);\n\t\t}\n\t\treturn this;\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<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<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<string>): this {\n\t\tthis._requiredAssets = [...assets];\n\t\treturn this;\n\t}\n\n\t/**\n\t * Add a query definition to the system\n\t */\n\taddQuery<\n\t\tQueryName extends string,\n\t\tWithComponents extends keyof ComponentTypes,\n\t\tWithoutComponents extends keyof ComponentTypes = never,\n\t\tNewQueries extends Queries & Record<QueryName, QueryDefinition<ComponentTypes, WithComponents, WithoutComponents>> =\n\t\t\tQueries & Record<QueryName, QueryDefinition<ComponentTypes, WithComponents, WithoutComponents>>\n\t>(\n\t\tname: QueryName,\n\t\tdefinition: {\n\t\t\twith: ReadonlyArray<WithComponents>;\n\t\t\twithout?: ReadonlyArray<WithoutComponents>;\n\t\t}\n\t): this extends SystemBuilderWithEcspresso<ComponentTypes, EventTypes, ResourceTypes, Queries>\n\t\t? SystemBuilderWithEcspresso<ComponentTypes, EventTypes, ResourceTypes, NewQueries>\n\t\t: this extends SystemBuilderWithBundle<ComponentTypes, EventTypes, ResourceTypes, Queries>\n\t\t\t? SystemBuilderWithBundle<ComponentTypes, EventTypes, ResourceTypes, NewQueries>\n\t\t\t: SystemBuilder<ComponentTypes, EventTypes, ResourceTypes, NewQueries> {\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 * Set the system's process function that runs each update\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<ComponentTypes, EventTypes, ResourceTypes, Queries>\n\t): this {\n\t\tthis.processFunction = process;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Register this system with its ECSpresso instance and return the ECSpresso for chaining\n\t * This enables seamless method chaining: .registerAndContinue().addSystem(...)\n\t * @returns ECSpresso instance if attached to one, otherwise throws an error\n\t */\n\tregisterAndContinue(): ECSpresso<ComponentTypes, EventTypes, ResourceTypes> {\n\t\tif (!this._ecspresso) {\n\t\t\tthrow new Error(`Cannot register system '${this._label}': SystemBuilder is not attached to an ECSpresso instance. Use Bundle.addSystem() or ECSpresso.addSystem() instead.`);\n\t\t}\n\t\t\n\t\tthis._autoRegister();\n\t\treturn this._ecspresso;\n\t}\n\n\t/**\n\t * Complete this system and return the parent container for seamless chaining\n\t * - For ECSpresso-attached builders: registers the system and returns ECSpresso\n\t * - For Bundle-attached builders: returns the Bundle\n\t * This method is typed via the specialized interfaces (SystemBuilderWithEcspresso, SystemBuilderWithBundle)\n\t */\n\tand(): ECSpresso<ComponentTypes, EventTypes, ResourceTypes> | Bundle<ComponentTypes, EventTypes, ResourceTypes> {\n\t\tif (this._ecspresso) {\n\t\t\tthis._autoRegister();\n\t\t\treturn this._ecspresso;\n\t\t}\n\n\t\tif (this._bundle) {\n\t\t\treturn this._bundle;\n\t\t}\n\n\t\tthrow new Error(`Cannot use and() on system '${this._label}': not attached to ECSpresso or Bundle.`);\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<ComponentTypes, EventTypes, ResourceTypes>\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 * Called when the system is initialized via ECSpresso.initialize() method\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<ComponentTypes, EventTypes, ResourceTypes>\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 EventTypes]?: {\n\t\t\t\thandler(\n\t\t\t\t\tdata: EventTypes[EventName],\n\t\t\t\t\tecs: ECSpresso<ComponentTypes, EventTypes, ResourceTypes>\n\t\t\t\t): void;\n\t\t\t};\n\t\t}\n\t): this {\n\t\tthis.eventHandlers = handlers;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Build the final system object\n\t */\n\tbuild(ecspresso?: ECSpresso<ComponentTypes, EventTypes, ResourceTypes>) {\n\t\tconst system = this._createSystemObject();\n\n\t\tif (this._ecspresso) {\n\t\t\tregisterSystemWithEcspresso(system, this._ecspresso);\n\t\t}\n\n\t\tif(ecspresso) {\n\t\t\tregisterSystemWithEcspresso(system, ecspresso);\n\t\t}\n\n\t\treturn this;\n\t}\n}\n\n/**\n * Helper function to register a system with an ECSpresso instance\n * This handles attaching the system and setting up event handlers\n * @internal Used by SystemBuilder and Bundle\n */\nexport function registerSystemWithEcspresso<\n\tComponentTypes extends Record<string, any>,\n\tEventTypes extends Record<string, any>,\n\tResourceTypes extends Record<string, any>\n>(\n\tsystem: System<ComponentTypes, any, any, EventTypes, ResourceTypes>,\n\tecspresso: ECSpresso<ComponentTypes, EventTypes, ResourceTypes>\n) {\n\t// Use the new internal registration method instead of direct property access\n\tecspresso._registerSystem(system);\n}\n\n// Helper type definitions\ntype QueryDefinition<\n\tComponentTypes,\n\tWithComponents extends keyof ComponentTypes = any,\n\tWithoutComponents extends keyof ComponentTypes = any,\n> = {\n\twith: ReadonlyArray<WithComponents>;\n\twithout?: ReadonlyArray<WithoutComponents>;\n};\n\ntype QueryResults<\n\tComponentTypes,\n\tQueries 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, any> ? W : never,\n\t\t\tQueries[QueryName] extends QueryDefinition<ComponentTypes, any, infer WO> ? WO : never\n\t\t>[]\n\t\t: never;\n};\n\n/**\n * Function signature for system process methods\n * @param queries Results of entity queries defined by the system\n * @param deltaTime Time elapsed since last update in seconds\n * @param ecs The ECSpresso instance providing access to all ECS functionality\n */\ntype ProcessFunction<\n\tComponentTypes extends Record<string, any>,\n\tEventTypes extends Record<string, any>,\n\tResourceTypes extends Record<string, any>,\n\tQueries extends Record<string, QueryDefinition<ComponentTypes>>,\n> = (\n\tqueries: QueryResults<ComponentTypes, Queries>,\n\tdeltaTime: number,\n\tecs: ECSpresso<\n\t\tComponentTypes,\n\t\tEventTypes,\n\t\tResourceTypes\n\t>\n) => void;\n\n/**\n * Type for system initialization functions\n * These can be asynchronous\n */\ntype LifecycleFunction<\n\tComponentTypes extends Record<string, any>,\n\tEventTypes extends Record<string, any>,\n\tResourceTypes extends Record<string, any>,\n> = (\n\tecs: ECSpresso<\n\t\tComponentTypes,\n\t\tEventTypes,\n\t\tResourceTypes\n\t>,\n) => void | Promise<void>;\n\n/**\n * Create a SystemBuilder attached to an ECSpresso instance\n * Helper function used by ECSpresso.addSystem\n */\nexport function createEcspressoSystemBuilder<\n\tComponentTypes extends Record<string, any>,\n\tEventTypes extends Record<string, any>,\n\tResourceTypes extends Record<string, any>\n>(\n\tlabel: string,\n\tecspresso: ECSpresso<ComponentTypes, EventTypes, ResourceTypes>\n): SystemBuilderWithEcspresso<ComponentTypes, EventTypes, ResourceTypes> {\n\treturn new SystemBuilder<ComponentTypes, EventTypes, ResourceTypes>(\n\t\tlabel,\n\t\tecspresso\n\t) as SystemBuilderWithEcspresso<ComponentTypes, EventTypes, ResourceTypes>;\n}\n\n/**\n * Create a SystemBuilder attached to a Bundle\n * Helper function used by Bundle.addSystem\n */\nexport function createBundleSystemBuilder<\n\tComponentTypes extends Record<string, any>,\n\tEventTypes extends Record<string, any>,\n\tResourceTypes extends Record<string, any>\n>(\n\tlabel: string,\n\tbundle: Bundle<ComponentTypes, EventTypes, ResourceTypes>\n): SystemBuilderWithBundle<ComponentTypes, EventTypes, ResourceTypes> {\n\treturn new SystemBuilder<ComponentTypes, EventTypes, ResourceTypes>(\n\t\tlabel,\n\t\tnull,\n\t\tbundle\n\t) as SystemBuilderWithBundle<ComponentTypes, EventTypes, ResourceTypes>;\n}\n\n// Type interfaces for specialized SystemBuilders\n\n/**\n * SystemBuilder with a guaranteed non-null reference to an ECSpresso instance\n */\nexport interface SystemBuilderWithEcspresso<\n\tComponentTypes extends Record<string, any>,\n\tEventTypes extends Record<string, any>,\n\tResourceTypes extends Record<string, any>,\n\tQueries extends Record<string, QueryDefinition<ComponentTypes>> = {}\n> extends SystemBuilder<ComponentTypes, EventTypes, ResourceTypes, Queries> {\n\treadonly ecspresso: ECSpresso<ComponentTypes, EventTypes, ResourceTypes>;\n\t\n\t/**\n\t * Complete this system and return ECSpresso for seamless chaining\n\t * Automatically registers the system when called\n\t */\n\tand(): ECSpresso<ComponentTypes, EventTypes, ResourceTypes>;\n}\n\n/**\n * SystemBuilder with a guaranteed non-null reference to a Bundle\n */\nexport interface SystemBuilderWithBundle<\n\tComponentTypes extends Record<string, any>,\n\tEventTypes extends Record<string, any>,\n\tResourceTypes extends Record<string, any>,\n\tQueries extends Record<string, QueryDefinition<ComponentTypes>> = {}\n> extends SystemBuilder<ComponentTypes, EventTypes, ResourceTypes, Queries> {\n\treadonly bundle: Bundle<ComponentTypes, EventTypes, ResourceTypes>;\n\n\t/**\n\t * Complete this system and return the Bundle for chaining\n\t * Enables fluent API: bundle.addSystem(...).and().addSystem(...)\n\t */\n\tand(): Bundle<ComponentTypes, EventTypes, ResourceTypes>;\n}\n",
|
|
6
|
+
"import { createBundleSystemBuilder, SystemBuilderWithBundle } from './system-builder';\nimport type ECSpresso from './ecspresso';\nimport type { AssetDefinition } from './asset-types';\nimport type { ScreenDefinition } from './screen-types';\n\n/**\n * Generates a unique ID for a bundle\n */\nfunction generateBundleId(): string {\n\treturn `bundle_${Date.now().toString(36)}_${Math.random().toString(36).substring(2, 9)}`;\n}\n\n/**\n * Bundle class that encapsulates a set of components, resources, events, and systems\n * that can be merged into a ECSpresso instance\n */\nexport default class Bundle<\n\tComponentTypes extends Record<string, any> = {},\n\tEventTypes extends Record<string, any> = {},\n\tResourceTypes extends Record<string, any> = {},\n\tAssetTypes extends Record<string, unknown> = {},\n\tScreenStates extends Record<string, ScreenDefinition<any, any>> = {},\n> {\n\tprivate _systems: SystemBuilderWithBundle<ComponentTypes, EventTypes, ResourceTypes, any>[] = [];\n\tprivate _resources: Map<keyof ResourceTypes, ResourceTypes[keyof ResourceTypes]> = new Map();\n\tprivate _assets: Map<string, AssetDefinition<unknown>> = new Map();\n\tprivate _assetGroups: Map<string, Map<string, () => Promise<unknown>>> = new Map();\n\tprivate _screens: Map<string, ScreenDefinition<any, any>> = new Map();\n\tprivate _id: string;\n\n\tconstructor(id?: string) {\n\t\tthis._id = id || generateBundleId();\n\t}\n\n\t/**\n\t * Get the unique ID of this bundle\n\t */\n\tget id(): string {\n\t\treturn this._id;\n\t}\n\n\t/**\n\t * Set the ID of this bundle\n\t * @internal Used by combineBundles\n\t */\n\tset id(value: string) {\n\t\tthis._id = value;\n\t}\n\n\t/**\n\t * Add a system to this bundle, by label (creating a new builder) or by reusing an existing one\n\t */\n\taddSystem<Q extends Record<string, any>>(builder: SystemBuilderWithBundle<ComponentTypes, EventTypes, ResourceTypes, Q>): SystemBuilderWithBundle<ComponentTypes, EventTypes, ResourceTypes, Q>;\n\taddSystem(label: string): SystemBuilderWithBundle<ComponentTypes, EventTypes, ResourceTypes, {}>;\n\taddSystem(builderOrLabel: string | SystemBuilderWithBundle<ComponentTypes, EventTypes, ResourceTypes, any>) {\n\t\tif (typeof builderOrLabel === 'string') {\n\t\t\tconst system = createBundleSystemBuilder<ComponentTypes, EventTypes, ResourceTypes>(builderOrLabel, this);\n\t\t\tthis._systems.push(system);\n\t\t\treturn system;\n\t\t} else {\n\t\t\tthis._systems.push(builderOrLabel);\n\t\t\treturn builderOrLabel;\n\t\t}\n\t}\n\n\t/**\n\t * Add a resource to this bundle\n\t * @param label The resource key\n\t * @param resource The resource value, a factory function, or a factory with dependencies\n\t */\n\taddResource<K extends keyof ResourceTypes>(\n\t\tlabel: K,\n\t\tresource:\n\t\t\t| ResourceTypes[K]\n\t\t\t| ((ecs: ECSpresso<ComponentTypes, EventTypes, ResourceTypes>) => ResourceTypes[K] | Promise<ResourceTypes[K]>)\n\t\t\t| { dependsOn: readonly string[]; factory: (ecs: ECSpresso<ComponentTypes, EventTypes, ResourceTypes>) => ResourceTypes[K] | Promise<ResourceTypes[K]> }\n\t) {\n\t\t// We need this cast because TypeScript doesn't recognize that a value of type\n\t\t// ResourceTypes[K] | (() => ResourceTypes[K] | Promise<ResourceTypes[K]>) | { dependsOn, factory }\n\t\t// can be properly assigned to Map<keyof ResourceTypes, ResourceTypes[keyof ResourceTypes]>\n\t\tthis._resources.set(label, resource as unknown as ResourceTypes[K]);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Add an asset to this bundle\n\t * @param key The asset key\n\t * @param loader Function that loads and returns the asset\n\t * @param options Optional asset configuration\n\t */\n\taddAsset<K extends string, T>(\n\t\tkey: K,\n\t\tloader: () => Promise<T>,\n\t\toptions?: { eager?: boolean; group?: string }\n\t): Bundle<ComponentTypes, EventTypes, ResourceTypes, AssetTypes & Record<K, T>, ScreenStates> {\n\t\tthis._assets.set(key, {\n\t\t\tloader,\n\t\t\teager: options?.eager ?? true,\n\t\t\tgroup: options?.group,\n\t\t});\n\t\treturn this as unknown as Bundle<ComponentTypes, EventTypes, ResourceTypes, AssetTypes & Record<K, T>, ScreenStates>;\n\t}\n\n\t/**\n\t * Add a group of assets to this bundle\n\t * @param groupName The group name\n\t * @param assets Object mapping asset keys to loader functions\n\t */\n\taddAssetGroup<G extends string, T extends Record<string, () => Promise<unknown>>>(\n\t\tgroupName: G,\n\t\tassets: T\n\t): Bundle<ComponentTypes, EventTypes, ResourceTypes, AssetTypes & { [K in keyof T]: Awaited<ReturnType<T[K]>> }, ScreenStates> {\n\t\tconst groupAssets = new Map<string, () => Promise<unknown>>();\n\t\tfor (const [key, loader] of Object.entries(assets)) {\n\t\t\tgroupAssets.set(key, loader as () => Promise<unknown>);\n\t\t\tthis._assets.set(key, {\n\t\t\t\tloader: loader as () => Promise<unknown>,\n\t\t\t\teager: false,\n\t\t\t\tgroup: groupName,\n\t\t\t});\n\t\t}\n\t\tthis._assetGroups.set(groupName, groupAssets);\n\t\treturn this as unknown as Bundle<ComponentTypes, EventTypes, ResourceTypes, AssetTypes & { [K in keyof T]: Awaited<ReturnType<T[K]>> }, ScreenStates>;\n\t}\n\n\t/**\n\t * Add a screen to this bundle\n\t * @param name The screen name\n\t * @param definition The screen definition\n\t */\n\taddScreen<K extends string, Config extends Record<string, unknown>, State extends Record<string, unknown>>(\n\t\tname: K,\n\t\tdefinition: ScreenDefinition<Config, State>\n\t): Bundle<ComponentTypes, EventTypes, ResourceTypes, AssetTypes, ScreenStates & Record<K, ScreenDefinition<Config, State>>> {\n\t\tthis._screens.set(name, definition);\n\t\treturn this as unknown as Bundle<ComponentTypes, EventTypes, ResourceTypes, AssetTypes, ScreenStates & Record<K, ScreenDefinition<Config, State>>>;\n\t}\n\n\t/**\n\t * Get all asset definitions in this bundle\n\t */\n\tgetAssets(): Map<string, AssetDefinition<unknown>> {\n\t\treturn new Map(this._assets);\n\t}\n\n\t/**\n\t * Get all screen definitions in this bundle\n\t */\n\tgetScreens(): Map<string, ScreenDefinition<any, any>> {\n\t\treturn new Map(this._screens);\n\t}\n\n\t/**\n\t * Internal method to set a resource\n\t * @internal Used by mergeBundles\n\t */\n\t_setResource(key: string, value: unknown): void {\n\t\tthis._resources.set(key as keyof ResourceTypes, value as ResourceTypes[keyof ResourceTypes]);\n\t}\n\n\t/**\n\t * Internal method to set an asset definition\n\t * @internal Used by mergeBundles\n\t */\n\t_setAsset(key: string, definition: AssetDefinition<unknown>): void {\n\t\tthis._assets.set(key, definition);\n\t}\n\n\t/**\n\t * Internal method to set a screen definition\n\t * @internal Used by mergeBundles\n\t */\n\t_setScreen(name: string, definition: ScreenDefinition<any, any>): void {\n\t\tthis._screens.set(name, definition);\n\t}\n\n\t/**\n\t * Get all systems defined in this bundle\n\t * Returns built System objects instead of SystemBuilders\n\t */\n\tgetSystems() {\n\t\treturn this._systems.map(system => system.build());\n\t}\n\n\t/**\n\t * Register all systems in this bundle with an ECSpresso instance\n\t * @internal Used by ECSpresso when adding a bundle\n\t */\n\tregisterSystemsWithEcspresso(ecspresso: ECSpresso<ComponentTypes, EventTypes, ResourceTypes>) {\n\t\tfor (const systemBuilder of this._systems) {\n\t\t\tsystemBuilder.build(ecspresso);\n\t\t}\n\t}\n\n\t/**\n\t * Get all resources defined in this bundle\n\t */\n\tgetResources(): Map<keyof ResourceTypes, ResourceTypes[keyof ResourceTypes]> {\n\t\treturn new Map(this._resources);\n\t}\n\n\t/**\n\t * Get a specific resource by key\n\t * @param key The resource key\n\t * @returns The resource value or undefined if not found\n\t */\n\tgetResource<K extends keyof ResourceTypes>(key: K): ResourceTypes[K] {\n\t\treturn this._resources.get(key) as ResourceTypes[K];\n\t}\n\n\t/**\n\t * Get all system builders in this bundle\n\t */\n\tgetSystemBuilders(): SystemBuilderWithBundle<ComponentTypes, EventTypes, ResourceTypes, any>[] {\n\t\treturn [...this._systems];\n\t}\n\n\t/**\n\t * Check if this bundle has a specific resource\n\t * @param key The resource key to check\n\t * @returns True if the resource exists\n\t */\n\thasResource<K extends keyof ResourceTypes>(key: K): boolean {\n\t\treturn this._resources.has(key);\n\t}\n}\n\n/**\n * Utility type to check if two types are exactly the same\n */\ntype Exactly<T, U> = T extends U ? U extends T ? true : false : false;\n\n/**\n * Simplified type constraint for bundle compatibility\n * Ensures that overlapping keys have exactly the same types\n */\ntype CompatibleBundles<\n\tC1 extends Record<string, any>,\n\tC2 extends Record<string, any>,\n\tE1 extends Record<string, any>,\n\tE2 extends Record<string, any>,\n\tR1 extends Record<string, any>,\n\tR2 extends Record<string, any>,\n\tA1 extends Record<string, unknown> = {},\n\tA2 extends Record<string, unknown> = {},\n\tS1 extends Record<string, ScreenDefinition<any, any>> = {},\n\tS2 extends Record<string, ScreenDefinition<any, any>> = {},\n> = {\n\t[K in keyof C1 & keyof C2]: Exactly<C1[K], C2[K]> extends true ? C1[K] : never;\n} & {\n\t[K in keyof E1 & keyof E2]: Exactly<E1[K], E2[K]> extends true ? E1[K] : never;\n} & {\n\t[K in keyof R1 & keyof R2]: Exactly<R1[K], R2[K]> extends true ? R1[K] : never;\n} & {\n\t[K in keyof A1 & keyof A2]: Exactly<A1[K], A2[K]> extends true ? A1[K] : never;\n} & {\n\t[K in keyof S1 & keyof S2]: Exactly<S1[K], S2[K]> extends true ? S1[K] : never;\n};\n\n/**\n * Function that merges multiple bundles into a single bundle\n */\nexport function mergeBundles<\n\tC1 extends Record<string, any>,\n\tE1 extends Record<string, any>,\n\tR1 extends Record<string, any>,\n\tA1 extends Record<string, unknown>,\n\tS1 extends Record<string, ScreenDefinition<any, any>>,\n\tC2 extends Record<string, any>,\n\tE2 extends Record<string, any>,\n\tR2 extends Record<string, any>,\n\tA2 extends Record<string, unknown>,\n\tS2 extends Record<string, ScreenDefinition<any, any>>,\n>(\n\tid: string,\n\tbundle1: Bundle<C1, E1, R1, A1, S1>,\n\tbundle2: Bundle<C2, E2, R2, A2, S2> & CompatibleBundles<C1, C2, E1, E2, R1, R2, A1, A2, S1, S2>\n): Bundle<C1 & C2, E1 & E2, R1 & R2, A1 & A2, S1 & S2>;\n\nexport function mergeBundles<\n\tComponentTypes extends Record<string, any>,\n\tEventTypes extends Record<string, any>,\n\tResourceTypes extends Record<string, any>,\n\tAssetTypes extends Record<string, unknown>,\n\tScreenStates extends Record<string, ScreenDefinition<any, any>>,\n>(\n\tid: string,\n\t...bundles: Array<Bundle<ComponentTypes, EventTypes, ResourceTypes, AssetTypes, ScreenStates>>\n): Bundle<ComponentTypes, EventTypes, ResourceTypes, AssetTypes, ScreenStates>;\n\nexport function mergeBundles(\n\tid: string,\n\t...bundles: Array<Bundle<any, any, any, any, any>>\n): Bundle<any, any, any, any, any> {\n\tif (bundles.length === 0) {\n\t\treturn new Bundle(id);\n\t}\n\n\tconst combined = new Bundle(id);\n\n\tfor (const bundle of bundles) {\n\t\tfor (const system of bundle.getSystemBuilders()) {\n\t\t\t// reuse the full builder so we carry over queries, hooks, and handlers\n\t\t\tcombined.addSystem(system);\n\t\t}\n\n\t\t// Add resources from this bundle\n\t\tfor (const [label, resource] of bundle.getResources().entries()) {\n\t\t\tcombined._setResource(label as string, resource);\n\t\t}\n\n\t\t// Add assets from this bundle\n\t\tfor (const [key, definition] of bundle.getAssets().entries()) {\n\t\t\tcombined._setAsset(key, definition);\n\t\t}\n\n\t\t// Add screens from this bundle\n\t\tfor (const [name, definition] of bundle.getScreens().entries()) {\n\t\t\tcombined._setScreen(name, definition);\n\t\t}\n\t}\n\n\treturn combined;\n}\n",
|
|
7
|
+
"/**\n * Timer Bundle for ECSpresso\n *\n * Provides ECS-native timers following the \"data, not callbacks\" philosophy.\n * Timers are components processed each frame, automatically cleaned up when entities are removed.\n */\n\nimport Bundle from '../../bundle';\n\n// ==================== Event Types ====================\n\n/**\n * Data structure published when a timer completes.\n * Use this type when defining timer completion events in your EventTypes interface.\n *\n * @example\n * ```typescript\n * interface Events {\n * hideMessage: TimerEventData;\n * spawnWave: TimerEventData;\n * }\n * ```\n */\nexport interface TimerEventData {\n\t/** The entity ID that the timer belongs to */\n\tentityId: number;\n\t/** The timer's configured duration in seconds */\n\tduration: number;\n\t/** The actual elapsed time (may exceed duration slightly) */\n\telapsed: number;\n}\n\n// ==================== Component Types ====================\n\n/**\n * Extracts event names from EventTypes that have TimerEventData as their payload.\n * This ensures only compatible events can be used with timer.onComplete.\n */\nexport type TimerEventName<EventTypes extends Record<string, any>> = {\n\t[K in keyof EventTypes]: EventTypes[K] extends TimerEventData ? K : never\n}[keyof EventTypes];\n\n/**\n * Timer component data structure.\n * Use `justFinished` to detect timer completion in your systems.\n *\n * @template EventTypes The event types from your ECS\n */\nexport interface Timer<EventTypes extends Record<string, any>> {\n\t/** Time accumulated so far (seconds) */\n\telapsed: number;\n\t/** Target duration (seconds) */\n\tduration: number;\n\t/** Whether timer repeats after completion */\n\trepeat: boolean;\n\t/** Whether timer is currently running */\n\tactive: boolean;\n\t/** True for one frame after timer completes */\n\tjustFinished: boolean;\n\t/** Optional event name to publish when timer completes. Must be an event with TimerEventData payload. */\n\tonComplete?: TimerEventName<EventTypes>;\n}\n\n/**\n * Component types provided by the timer bundle.\n * Extend your component types with this interface.\n *\n * @template EventTypes The event types from your ECS\n *\n * @example\n * ```typescript\n * interface GameComponents extends TimerComponentTypes<GameEvents> {\n * velocity: { x: number; y: number };\n * player: true;\n * }\n * ```\n */\nexport interface TimerComponentTypes<EventTypes extends Record<string, any>> {\n\ttimer: Timer<EventTypes>;\n}\n\n// ==================== Bundle Options ====================\n\n/**\n * Configuration options for the timer bundle.\n */\nexport interface TimerBundleOptions {\n\t/** System group name (default: 'timers') */\n\tsystemGroup?: string;\n\t/** Priority for timer update system (default: 0) */\n\tpriority?: number;\n}\n\n// ==================== Helper Functions ====================\n\n/**\n * Options for timer creation\n *\n * @template EventTypes The event types from your ECS\n */\nexport interface TimerOptions<EventTypes extends Record<string, any>> {\n\t/** Event name to publish when timer completes. Must be an event with TimerEventData payload. */\n\tonComplete?: TimerEventName<EventTypes>;\n}\n\n/**\n * Create a one-shot timer that fires once after the specified duration.\n *\n * @template EventTypes The event types from your ECS (must be explicitly provided)\n * @param duration Duration in seconds until the timer completes\n * @param options Optional configuration including event name\n * @returns Component object suitable for spreading into spawn()\n *\n * @example\n * ```typescript\n * // Timer without event\n * ecs.spawn({\n * ...createTimer<GameEvents>(2),\n * explosion: true,\n * });\n *\n * // Timer that publishes an event on completion\n * ecs.spawn({\n * ...createTimer<GameEvents>(1.5, { onComplete: 'hideMessage' }),\n * });\n * ```\n */\nexport function createTimer<EventTypes extends Record<string, any>>(\n\tduration: number,\n\toptions?: TimerOptions<EventTypes>\n): Pick<TimerComponentTypes<EventTypes>, 'timer'> {\n\treturn {\n\t\ttimer: {\n\t\t\telapsed: 0,\n\t\t\tduration,\n\t\t\trepeat: false,\n\t\t\tactive: true,\n\t\t\tjustFinished: false,\n\t\t\tonComplete: options?.onComplete,\n\t\t},\n\t};\n}\n\n/**\n * Create a repeating timer that fires every `duration` seconds.\n *\n * @template EventTypes The event types from your ECS (must be explicitly provided)\n * @param duration Duration in seconds between each timer completion\n * @param options Optional configuration including event name\n * @returns Component object suitable for spreading into spawn()\n *\n * @example\n * ```typescript\n * // Timer without event\n * ecs.spawn({\n * ...createRepeatingTimer<GameEvents>(5),\n * spawner: true,\n * });\n *\n * // Repeating timer that publishes an event each cycle\n * ecs.spawn({\n * ...createRepeatingTimer<GameEvents>(3, { onComplete: 'spawnWave' }),\n * });\n * ```\n */\nexport function createRepeatingTimer<EventTypes extends Record<string, any>>(\n\tduration: number,\n\toptions?: TimerOptions<EventTypes>\n): Pick<TimerComponentTypes<EventTypes>, 'timer'> {\n\treturn {\n\t\ttimer: {\n\t\t\telapsed: 0,\n\t\t\tduration,\n\t\t\trepeat: true,\n\t\t\tactive: true,\n\t\t\tjustFinished: false,\n\t\t\tonComplete: options?.onComplete,\n\t\t},\n\t};\n}\n\n// ==================== Bundle Factory ====================\n\n/**\n * Create a timer bundle for ECSpresso.\n *\n * This bundle provides:\n * - Timer update system that processes all timer components each frame\n * - `justFinished` flag pattern for one-frame completion detection\n * - Automatic cleanup when entities are removed\n *\n * @example\n * ```typescript\n * const ecs = ECSpresso\n * .create<Components, Events, Resources>()\n * .withBundle(createTimerBundle())\n * .build();\n *\n * // Spawn entity with timer\n * ecs.spawn({\n * ...createRepeatingTimer(5),\n * spawner: true,\n * });\n *\n * // React to timer completion in a system\n * ecs.addSystem('spawn-on-timer')\n * .addQuery('spawners', { with: ['timer', 'spawner'] })\n * .setProcess((queries, _dt, ecs) => {\n * for (const { components } of queries.spawners) {\n * if (components.timer.justFinished) {\n * ecs.spawn({ enemy: true });\n * }\n * }\n * });\n * ```\n */\nexport function createTimerBundle<EventTypes extends Record<string, any>>(\n\toptions?: TimerBundleOptions\n): Bundle<TimerComponentTypes<EventTypes>, EventTypes, {}> {\n\tconst {\n\t\tsystemGroup = 'timers',\n\t\tpriority = 0,\n\t} = options ?? {};\n\n\tconst bundle = new Bundle<TimerComponentTypes<EventTypes>, EventTypes, {}>('timers');\n\n\tbundle\n\t\t.addSystem('timer-update')\n\t\t.setPriority(priority)\n\t\t.inGroup(systemGroup)\n\t\t.addQuery('timers', {\n\t\t\twith: ['timer'] as const,\n\t\t})\n\t\t.setProcess((queries, deltaTime, ecs) => {\n\t\t\tfor (const entity of queries.timers) {\n\t\t\t\tconst { timer } = entity.components;\n\n\t\t\t\t// Reset justFinished flag from previous frame\n\t\t\t\ttimer.justFinished = false;\n\n\t\t\t\t// Skip inactive timers\n\t\t\t\tif (!timer.active) continue;\n\n\t\t\t\t// Accumulate time\n\t\t\t\ttimer.elapsed += deltaTime;\n\n\t\t\t\t// Check if timer completed\n\t\t\t\tif (timer.elapsed < timer.duration) continue;\n\n\t\t\t\t// Timer completed - handle based on repeat mode\n\t\t\t\tif (timer.repeat) {\n\t\t\t\t\t// Handle multiple cycles in one frame\n\t\t\t\t\twhile (timer.elapsed >= timer.duration) {\n\t\t\t\t\t\ttimer.justFinished = true;\n\t\t\t\t\t\tpublishTimerEvent(ecs, entity.id, timer);\n\t\t\t\t\t\ttimer.elapsed -= timer.duration;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\t// One-shot timer\n\t\t\t\t\ttimer.justFinished = true;\n\t\t\t\t\tpublishTimerEvent(ecs, entity.id, timer);\n\t\t\t\t\ttimer.active = false;\n\t\t\t\t\t// Auto-remove one-shot timer entities after completion.\n\t\t\t\t\t// If configurability is needed in the future, add an autoRemove option to TimerOptions.\n\t\t\t\t\tecs.commands.removeEntity(entity.id);\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t\t.and();\n\n\t/**\n\t * Publishes timer completion event if onComplete is specified.\n\t * Type assertion needed: TypeScript can't infer that TimerEventName<EventTypes>\n\t * maps to events with TimerEventData payloads, even though that's what the type enforces.\n\t */\n\tfunction publishTimerEvent(\n\t\tecs: { eventBus: { publish: (event: any, data: any) => void } },\n\t\tentityId: number,\n\t\ttimer: Timer<EventTypes>\n\t): void {\n\t\tif (!timer.onComplete) return;\n\t\tconst eventData: TimerEventData = {\n\t\t\tentityId,\n\t\t\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archical transform propagation following Bevy's Transform/GlobalTransform pattern.
|
|
5
|
+
* LocalTransform is modified by user code; WorldTransform is computed automatically.
|
|
6
|
+
*
|
|
7
|
+
* @see https://docs.rs/bevy/latest/bevy/transform/components/struct.GlobalTransform.html
|
|
8
|
+
*/
|
|
9
|
+
import Bundle from '../../bundle';
|
|
10
|
+
/**
|
|
11
|
+
* Local transform relative to parent (or world if no parent).
|
|
12
|
+
* This is the transform you modify directly.
|
|
13
|
+
*/
|
|
14
|
+
export interface LocalTransform {
|
|
15
|
+
x: number;
|
|
16
|
+
y: number;
|
|
17
|
+
rotation: number;
|
|
18
|
+
scaleX: number;
|
|
19
|
+
scaleY: number;
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Computed world transform (accumulated from parent chain).
|
|
23
|
+
* Read-only - managed by the transform propagation system.
|
|
24
|
+
*/
|
|
25
|
+
export interface WorldTransform {
|
|
26
|
+
x: number;
|
|
27
|
+
y: number;
|
|
28
|
+
rotation: number;
|
|
29
|
+
scaleX: number;
|
|
30
|
+
scaleY: number;
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Component types provided by the transform bundle.
|
|
34
|
+
* Extend your component types with this interface.
|
|
35
|
+
*
|
|
36
|
+
* @example
|
|
37
|
+
* ```typescript
|
|
38
|
+
* interface GameComponents extends TransformComponentTypes {
|
|
39
|
+
* sprite: Sprite;
|
|
40
|
+
* velocity: { x: number; y: number };
|
|
41
|
+
* }
|
|
42
|
+
* ```
|
|
43
|
+
*/
|
|
44
|
+
export interface TransformComponentTypes {
|
|
45
|
+
localTransform: LocalTransform;
|
|
46
|
+
worldTransform: WorldTransform;
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* Configuration options for the transform bundle.
|
|
50
|
+
*/
|
|
51
|
+
export interface TransformBundleOptions {
|
|
52
|
+
/** System group name (default: 'transform') */
|
|
53
|
+
systemGroup?: string;
|
|
54
|
+
/** Priority for transform propagation (default: 500, runs after physics/movement) */
|
|
55
|
+
priority?: number;
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* Default local transform values.
|
|
59
|
+
*/
|
|
60
|
+
export declare const DEFAULT_LOCAL_TRANSFORM: Readonly<LocalTransform>;
|
|
61
|
+
/**
|
|
62
|
+
* Default world transform values.
|
|
63
|
+
*/
|
|
64
|
+
export declare const DEFAULT_WORLD_TRANSFORM: Readonly<WorldTransform>;
|
|
65
|
+
/**
|
|
66
|
+
* Create a local transform component with position only.
|
|
67
|
+
* Uses default rotation (0) and scale (1, 1).
|
|
68
|
+
*
|
|
69
|
+
* @param x The x coordinate
|
|
70
|
+
* @param y The y coordinate
|
|
71
|
+
* @returns Component object suitable for spreading into spawn()
|
|
72
|
+
*
|
|
73
|
+
* @example
|
|
74
|
+
* ```typescript
|
|
75
|
+
* ecs.spawn({
|
|
76
|
+
* ...createLocalTransform(100, 200),
|
|
77
|
+
* sprite,
|
|
78
|
+
* });
|
|
79
|
+
* ```
|
|
80
|
+
*/
|
|
81
|
+
export declare function createLocalTransform(x: number, y: number): Pick<TransformComponentTypes, 'localTransform'>;
|
|
82
|
+
/**
|
|
83
|
+
* Create a world transform component with position only.
|
|
84
|
+
* Typically used alongside createLocalTransform for initial state.
|
|
85
|
+
*
|
|
86
|
+
* @param x The x coordinate
|
|
87
|
+
* @param y The y coordinate
|
|
88
|
+
* @returns Component object suitable for spreading into spawn()
|
|
89
|
+
*/
|
|
90
|
+
export declare function createWorldTransform(x: number, y: number): Pick<TransformComponentTypes, 'worldTransform'>;
|
|
91
|
+
/**
|
|
92
|
+
* Options for creating a full transform.
|
|
93
|
+
*/
|
|
94
|
+
export interface TransformOptions {
|
|
95
|
+
rotation?: number;
|
|
96
|
+
scaleX?: number;
|
|
97
|
+
scaleY?: number;
|
|
98
|
+
/** Uniform scale (overrides scaleX/scaleY if provided) */
|
|
99
|
+
scale?: number;
|
|
100
|
+
}
|
|
101
|
+
/**
|
|
102
|
+
* Create both local and world transform components.
|
|
103
|
+
* World transform is initialized to match local transform.
|
|
104
|
+
*
|
|
105
|
+
* @param x The x coordinate
|
|
106
|
+
* @param y The y coordinate
|
|
107
|
+
* @param options Optional rotation and scale
|
|
108
|
+
* @returns Component object suitable for spreading into spawn()
|
|
109
|
+
*
|
|
110
|
+
* @example
|
|
111
|
+
* ```typescript
|
|
112
|
+
* ecs.spawn({
|
|
113
|
+
* ...createTransform(100, 200),
|
|
114
|
+
* sprite,
|
|
115
|
+
* });
|
|
116
|
+
*
|
|
117
|
+
* // With rotation and scale
|
|
118
|
+
* ecs.spawn({
|
|
119
|
+
* ...createTransform(100, 200, { rotation: Math.PI / 4, scale: 2 }),
|
|
120
|
+
* sprite,
|
|
121
|
+
* });
|
|
122
|
+
* ```
|
|
123
|
+
*/
|
|
124
|
+
export declare function createTransform(x: number, y: number, options?: TransformOptions): TransformComponentTypes;
|
|
125
|
+
/**
|
|
126
|
+
* Create a transform bundle for ECSpresso.
|
|
127
|
+
*
|
|
128
|
+
* This bundle provides:
|
|
129
|
+
* - Transform propagation system that computes world transforms from local transforms
|
|
130
|
+
* - Parent-first traversal ensures parents are processed before children
|
|
131
|
+
* - Supports full transform hierarchy (position, rotation, scale)
|
|
132
|
+
*
|
|
133
|
+
* @example
|
|
134
|
+
* ```typescript
|
|
135
|
+
* const ecs = ECSpresso
|
|
136
|
+
* .create<Components, Events, Resources>()
|
|
137
|
+
* .withBundle(createTransformBundle())
|
|
138
|
+
* .withBundle(createMovementBundle())
|
|
139
|
+
* .build();
|
|
140
|
+
*
|
|
141
|
+
* // Spawn entity with transform
|
|
142
|
+
* ecs.spawn({
|
|
143
|
+
* ...createTransform(100, 200),
|
|
144
|
+
* velocity: { x: 50, y: 0 },
|
|
145
|
+
* });
|
|
146
|
+
* ```
|
|
147
|
+
*/
|
|
148
|
+
export declare function createTransformBundle(options?: TransformBundleOptions): Bundle<TransformComponentTypes, {}, {}>;
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import type ECSpresso from './ecspresso';
|
|
2
|
+
import type { RemoveEntityOptions } from './types';
|
|
3
|
+
/**
|
|
4
|
+
* CommandBuffer queues structural changes to be executed later.
|
|
5
|
+
* This prevents ordering issues when modifying entities during system execution.
|
|
6
|
+
*
|
|
7
|
+
* Commands are executed in FIFO order when playback() is called.
|
|
8
|
+
*
|
|
9
|
+
* @example
|
|
10
|
+
* ```typescript
|
|
11
|
+
* // In a system
|
|
12
|
+
* ecs.commands.removeEntity(entityId);
|
|
13
|
+
* ecs.commands.spawn({ position: { x: 0, y: 0 } });
|
|
14
|
+
*
|
|
15
|
+
* // Later (automatically at end of update())
|
|
16
|
+
* ecs.commands.playback(ecs);
|
|
17
|
+
* ```
|
|
18
|
+
*/
|
|
19
|
+
export default class CommandBuffer<ComponentTypes extends Record<string, any> = {}, EventTypes extends Record<string, any> = {}, ResourceTypes extends Record<string, any> = {}> {
|
|
20
|
+
private commands;
|
|
21
|
+
/**
|
|
22
|
+
* Queue an entity removal command
|
|
23
|
+
* @param entityId The ID of the entity to remove
|
|
24
|
+
* @param options Optional removal options (cascade, etc.)
|
|
25
|
+
*/
|
|
26
|
+
removeEntity(entityId: number, options?: RemoveEntityOptions): void;
|
|
27
|
+
/**
|
|
28
|
+
* Queue a component addition command
|
|
29
|
+
* @param entityId The ID of the entity
|
|
30
|
+
* @param componentName The name of the component to add
|
|
31
|
+
* @param componentValue The component data
|
|
32
|
+
*/
|
|
33
|
+
addComponent<K extends keyof ComponentTypes>(entityId: number, componentName: K, componentValue: ComponentTypes[K]): void;
|
|
34
|
+
/**
|
|
35
|
+
* Queue a component removal command
|
|
36
|
+
* @param entityId The ID of the entity
|
|
37
|
+
* @param componentName The name of the component to remove
|
|
38
|
+
*/
|
|
39
|
+
removeComponent<K extends keyof ComponentTypes>(entityId: number, componentName: K): void;
|
|
40
|
+
/**
|
|
41
|
+
* Queue an entity spawn command
|
|
42
|
+
* @param components The initial components for the new entity
|
|
43
|
+
* @returns void (entity ID not available until playback)
|
|
44
|
+
*/
|
|
45
|
+
spawn<T extends {
|
|
46
|
+
[K in keyof ComponentTypes]?: ComponentTypes[K];
|
|
47
|
+
}>(components: T & Record<Exclude<keyof T, keyof ComponentTypes>, never>): void;
|
|
48
|
+
/**
|
|
49
|
+
* Queue a child entity spawn command
|
|
50
|
+
* @param parentId The ID of the parent entity
|
|
51
|
+
* @param components The initial components for the new child entity
|
|
52
|
+
*/
|
|
53
|
+
spawnChild<T extends {
|
|
54
|
+
[K in keyof ComponentTypes]?: ComponentTypes[K];
|
|
55
|
+
}>(parentId: number, components: T & Record<Exclude<keyof T, keyof ComponentTypes>, never>): void;
|
|
56
|
+
/**
|
|
57
|
+
* Queue multiple component additions
|
|
58
|
+
* @param entityId The ID of the entity
|
|
59
|
+
* @param components Object with component names as keys and component data as values
|
|
60
|
+
*/
|
|
61
|
+
addComponents<T extends {
|
|
62
|
+
[K in keyof ComponentTypes]?: ComponentTypes[K];
|
|
63
|
+
}>(entityId: number, components: T & Record<Exclude<keyof T, keyof ComponentTypes>, never>): void;
|
|
64
|
+
/**
|
|
65
|
+
* Queue a parent assignment command
|
|
66
|
+
* @param childId The ID of the child entity
|
|
67
|
+
* @param parentId The ID of the parent entity
|
|
68
|
+
*/
|
|
69
|
+
setParent(childId: number, parentId: number): void;
|
|
70
|
+
/**
|
|
71
|
+
* Queue a parent removal command
|
|
72
|
+
* @param childId The ID of the child entity
|
|
73
|
+
*/
|
|
74
|
+
removeParent(childId: number): void;
|
|
75
|
+
/**
|
|
76
|
+
* Execute all queued commands in FIFO order.
|
|
77
|
+
* Errors from individual commands are caught and logged, but do not stop playback.
|
|
78
|
+
* @param ecs The ECSpresso instance to execute commands on
|
|
79
|
+
*/
|
|
80
|
+
playback<AssetTypes extends Record<string, any> = {}, ScreenStates extends Record<string, any> = {}>(ecs: ECSpresso<ComponentTypes, EventTypes, ResourceTypes, AssetTypes, ScreenStates>): void;
|
|
81
|
+
/**
|
|
82
|
+
* Clear all queued commands without executing them
|
|
83
|
+
*/
|
|
84
|
+
clear(): void;
|
|
85
|
+
/**
|
|
86
|
+
* Get the number of queued commands
|
|
87
|
+
* @returns The number of commands waiting to be executed
|
|
88
|
+
*/
|
|
89
|
+
get length(): number;
|
|
90
|
+
}
|