mani-game-engine 1.0.0-pre.5 → 1.0.0-pre.50

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/src/gameEngine.ts CHANGED
@@ -1,411 +1,472 @@
1
- import {Action, Class, EngineSignals, GameEnginePlugin, OnFixedUpdateParams, OnUpdateParams, Service, System} from './types';
2
- import {Signal, SignalBinding} from 'mani-signal';
3
- import {Entity} from './entity';
4
- import {ID, putIfAbsent} from 'mani-injector';
5
- import {EcsInjector, signalHandlers, staticSignalHandlers} from './ecsInjector';
6
- import {Clock} from './clock';
7
- import {SystemContext} from './systemContext';
8
-
9
- type AddEntry = [Entity, () => void];
10
- type RemoveEntry = [Entity, () => void];
11
-
12
- const defaultOptions = {
13
- fixedDeltaTime: 1 / 60,
14
- plugins: [] as GameEnginePlugin[],
15
- };
16
-
17
- export type GameEngineOptions = Partial<typeof defaultOptions>;
18
- declare global {
19
- interface GameEngineActions {
20
- 'testAction': string
21
- }
22
- }
23
-
24
- type GameEngineActionParams<K extends keyof GameEngineActions> = GameEngineActions[K];
25
- type GameAction<K extends keyof GameEngineActions> = (engine: GameEngine, params: GameEngineActionParams<K>) => Promise<any> | any;
26
-
27
- export class GameEngine {
28
-
29
- readonly onPrepare: Signal;
30
- readonly onStart: Signal;
31
- readonly onRender: Signal<OnUpdateParams>;
32
- readonly onUpdate: Signal<OnUpdateParams>;
33
- readonly onFixedUpdate: Signal<OnFixedUpdateParams>;
34
- readonly onPostPhysics: Signal<OnFixedUpdateParams>;
35
- readonly onLateUpdate: Signal<OnUpdateParams>;
36
-
37
- private readonly onEarlyUpdateSet = new Set<System>();
38
- private readonly onUpdateSet = new Set<System>();
39
- private readonly onFixedUpdateSet = new Set<System>();
40
- private readonly onPreFixedUpdateSet = new Set<System>();
41
- private readonly onPhysicsUpdateSet = new Set<System>();
42
- private readonly onPostPhysicsUpdateSet = new Set<System>();
43
- private readonly onLateUpdateSet = new Set<System>();
44
- private readonly onRenderUpdateSet = new Set<System>();
45
-
46
- private readonly entitySystemMap = new Map<Entity, SystemContext[]>();
47
-
48
- private readonly serviceClasses = new Set<Class<Service>>();
49
- private readonly services: Service[] = [];
50
-
51
- private framePromise!: Promise<any>;
52
- private resolveFrame: () => void = () => undefined;
53
-
54
- private addQueue: AddEntry[] = [];
55
- private removeQueue: RemoveEntry[] = [];
56
-
57
- private _started = false;
58
-
59
- get started(): boolean { return this._started; }
60
-
61
- private _frameCount = 0;
62
- get frameCount(): number { return this._frameCount; }
63
-
64
- private _fixedFrameCount = 0;
65
- get fixedFrameCount(): number { return this._fixedFrameCount; }
66
-
67
- get numEntities(): number { return this.entitySystemMap.size;}
68
-
69
- // TODO inject clock into game engine
70
- // TODO inject space into game engine
71
-
72
- static createDefault(options?: GameEngineOptions) {
73
- const opts = {...defaultOptions, ...options};
74
- const clock = new Clock({
75
- fixedDeltaTime: opts.fixedDeltaTime,
76
- autoStart: false,
77
- });
78
- const injector = new EcsInjector<Class<System>>();
79
- const engine = new GameEngine(injector, clock);
80
- engine.installPlugins(opts.plugins);
81
- return engine;
82
- }
83
-
84
- static createDefaultWithInjector(injector: EcsInjector<Class<System>>, options?: GameEngineOptions) {
85
- const opts = {...defaultOptions, ...options};
86
- const clock = new Clock({
87
- fixedDeltaTime: opts.fixedDeltaTime,
88
- autoStart: false,
89
- });
90
- const engine = new GameEngine(injector, clock);
91
- engine.installPlugins(opts.plugins);
92
- return engine;
93
- }
94
-
95
- constructor(
96
- readonly injector: EcsInjector<Class<System>>,
97
- readonly clock: Clock,
98
- ) {
99
- this.injector.map(GameEngine).toValue(this);
100
-
101
- this.onPrepare = this.injector.getSignal(EngineSignals.OnPrepare);
102
- this.onStart = this.injector.getSignal(EngineSignals.OnStart);
103
- this.onRender = this.injector.getSignal(EngineSignals.OnRender);
104
- this.onFixedUpdate = this.injector.getSignal(EngineSignals.OnFixedUpdate);
105
- this.onUpdate = this.injector.getSignal(EngineSignals.OnUpdate);
106
- this.onLateUpdate = this.injector.getSignal(EngineSignals.OnLateUpdate);
107
- this.onPostPhysics = this.injector.getSignal(EngineSignals.OnPostPhysics);
108
-
109
- this.setupClock();
110
- this.prepareFrame();
111
- }
112
-
113
- private setupClock() {
114
- this.clock.onPrepare.add(this.prepareFrame, this);
115
-
116
- this.clock.onEarlyUpdate.add(({time, deltaTime}) => {
117
- for (const system of this.onEarlyUpdateSet) {
118
- system.onEarlyUpdate!(time, deltaTime);
119
- }
120
- });
121
-
122
- this.clock.onFixedUpdate.add((params) => {
123
- const {time, deltaTime} = params;
124
- for (const system of this.onPreFixedUpdateSet) {
125
- system.onPreFixedUpdate!();
126
- }
127
- for (const system of this.onFixedUpdateSet) {
128
- system.onFixedUpdate!(time, deltaTime);
129
- }
130
- this.onFixedUpdate.dispatch(params);
131
- for (const system of this.onPhysicsUpdateSet) {
132
- system.onPhysicsUpdate!(time, deltaTime);
133
- }
134
- this.onPostPhysics.dispatch(params);
135
- for (const system of this.onPostPhysicsUpdateSet) {
136
- system.onPostPhysicsUpdate!(time, deltaTime);
137
- }
138
- this._fixedFrameCount++;
139
- });
140
-
141
- // TODO: update from outside
142
- this.clock.onUpdate.add(onUpdateParams => {
143
- const {time, deltaTime, alpha} = onUpdateParams;
144
- for (const system of this.onUpdateSet) {
145
- system.onUpdate!(time, deltaTime, alpha);
146
- }
147
- //TODO: merge with framerate to single signal?
148
-
149
- this.onUpdate.dispatch(onUpdateParams);
150
- for (const system of this.onLateUpdateSet) {
151
- system.onLateUpdate!(time, deltaTime, alpha);
152
- }
153
- this.onLateUpdate.dispatch(onUpdateParams);
154
-
155
- for (const system of this.onRenderUpdateSet) {
156
- system.onRender!(time, deltaTime, alpha);
157
- }
158
- this.onRender.dispatch(onUpdateParams);
159
- this._frameCount++;
160
- });
161
- }
162
-
163
- private installPlugins(plugins: GameEnginePlugin[]) {
164
- plugins.forEach(plugin => {
165
- plugin.onPrepare && plugin.onPrepare(this);
166
- });
167
- plugins.forEach(plugin => {
168
- plugin.onStart && plugin.onStart(this);
169
- });
170
- }
171
-
172
- registerSystem(systemClass: Class<System>): void {
173
- this.mapStaticAnnotatedSignals(systemClass);
174
- if (this._started) throw new Error('Register Systems before engine is started');
175
- this.injector.registerSystem(systemClass);
176
- }
177
-
178
- registerService(serviceClass: Class<Service>): void {
179
- this.mapStaticAnnotatedSignals(serviceClass);
180
- if (this._started) throw new Error('Register Services before engine is started');
181
- this.injector.map(serviceClass).toSingleton();
182
- this.serviceClasses.add(serviceClass);
183
- }
184
-
185
- getService<T extends Class<Service>>(serviceClass: T): InstanceType<T> {
186
- return this.injector.get(serviceClass);
187
- }
188
-
189
- start() {
190
- this._started = true;
191
- //TODO: throw when registering services or systems when engine is running
192
- for (const serviceClass of this.serviceClasses) {
193
- const service = this.injector.get(serviceClass);
194
- this.addService(service);
195
- }
196
- this.clock.start();
197
- this.onStart.dispatch();
198
- }
199
-
200
- addService(service: Service): void {
201
- this.mapAnnotatedSignals(service);
202
- service.onStart && service.onStart();
203
- service.onPreFixedUpdate && this.onPreFixedUpdateSet.add(service);
204
- service.onFixedUpdate && this.onFixedUpdateSet.add(service);
205
- service.onUpdate && this.onUpdateSet.add(service);
206
- service.onLateUpdate && this.onLateUpdateSet.add(service);
207
- service.onPhysicsUpdate && this.onPhysicsUpdateSet.add(service);
208
- service.onPostPhysicsUpdate && this.onPostPhysicsUpdateSet.add(service);
209
- service.onRender && this.onRenderUpdateSet.add(service);
210
- this.services.push(service);
211
- }
212
-
213
- add(entity: Entity) {
214
- return new Promise(resolve => this.addQueue.push([entity, resolve]));
215
- }
216
-
217
- waitFrame() {
218
- return this.framePromise;
219
- }
220
-
221
- async remove(entity: Entity) {
222
- if ((<any>entity).markRemoval) return;
223
- (<any>entity).markRemoval = true;
224
- return new Promise(resolve => this.removeQueue.push([entity, resolve]));
225
- }
226
-
227
- stop() {
228
- // this.injector.dispose();
229
- this.clock.stop();
230
- }
231
-
232
- runAction<T extends Action>(action: T): ReturnType<T> {
233
- return action(this);
234
- }
235
-
236
- getSignal<T>(signalId: ID): Signal<T> {
237
- return this.injector.getSignal<T>(signalId);
238
- }
239
-
240
- private signalMappings = new Map<Class, [string, Signal][]>();
241
- private staticSignalMappings = new Map<Class, [string, Signal][]>();
242
- private signalMapBindings = new Map<Object, SignalBinding[]>();
243
-
244
- // TODO: staticSignalMapBindings needed if we want to unregister Services or Systems
245
-
246
- private mapStaticAnnotatedSignals(target: Class) {
247
- let staticSignalMap = this.getStaticSignalMap(target);
248
- if (staticSignalMap.length === 0) return;
249
-
250
- const bindings = [];
251
- for (const [key, signal] of staticSignalMap) {
252
- bindings.push(signal.add((<any>target)[key], target));
253
- }
254
- // TODO: ignore bindings for now (store them if we implement unregister Service or Systems
255
- }
256
-
257
- private mapAnnotatedSignals(target: Object) {
258
- const signalMap = this.getSignalMap(target.constructor);
259
- if (signalMap.length === 0) return;
260
-
261
- const bindings = [];
262
- for (const [key, signal] of signalMap) {
263
- bindings.push(signal.add((<any>target)[key], target));
264
- }
265
- this.signalMapBindings.set(target, bindings);
266
- }
267
-
268
- private unmapAnnotatedSignals(target: Object) {
269
- const signalBindings = this.signalMapBindings.get(target);
270
- if (!signalBindings) return;
271
- for (const binding of signalBindings) {
272
- binding.detach();
273
- }
274
- }
275
-
276
- private getSignalMap(target: Function) {
277
- // TODO: we could speed thinks up by introducing "invisible" flags on the systems/services to avoid a map check
278
- return putIfAbsent(this.signalMappings, target, (): [string, Signal][] => {
279
- const handlers = signalHandlers.get(target);
280
- if (!handlers) return [];
281
- const result: [string, Signal][] = [];
282
- for (const [key, signalId] of handlers) {
283
- result.push([key, this.getSignal(signalId)]);
284
- }
285
- return result;
286
- });
287
- }
288
-
289
- private getStaticSignalMap(target: Class) {
290
- // TODO: we could speed thinks up by introducing "invisible" flags on the systems/services to avoid a map check
291
- return putIfAbsent(this.staticSignalMappings, target, (): [string, Signal][] => {
292
- const handlers = staticSignalHandlers.get(target);
293
- if (!handlers) return [];
294
- const result: [string, Signal][] = [];
295
- for (const [key, signalId] of handlers) {
296
- result.push([key, this.getSignal(signalId)]);
297
- }
298
- return result;
299
- });
300
- }
301
-
302
- dispose() {
303
- this.clock.stop();
304
- for (const systems of this.entitySystemMap.values()) {
305
- for (const system of systems) {
306
- system.system.onEnd && system.system.onEnd();
307
- }
308
- }
309
- for (const service of this.services) {
310
- service.onEnd && service.onEnd();
311
- }
312
- }
313
-
314
- private prepareFrame() {
315
-
316
- for (const [entity, resolve] of this.removeQueue) {
317
- const entities = entity.getAllEntities();
318
- for (const entity of entities) {
319
- (<any>entity).markRemoval = false;
320
- if (!(<any>entity).gameEngine) {
321
- console.log(entity);
322
- // throw new Error('Entity not active');
323
- }
324
- (<any>entity).gameEngine = undefined;
325
-
326
- const systemContexts = this.entitySystemMap.get(entity);
327
- this.entitySystemMap.delete(entity);
328
- if (systemContexts) {
329
- for (const context of systemContexts) {
330
- context.dispose();
331
- const system = context.system;
332
- this.unmapAnnotatedSignals(system);
333
- system.onEnd && system.onEnd();
334
- system.onPreFixedUpdate && this.onPreFixedUpdateSet.delete(system);
335
- system.onFixedUpdate && this.onFixedUpdateSet.delete(system);
336
- system.onEarlyUpdate && this.onEarlyUpdateSet.delete(system);
337
- system.onUpdate && this.onUpdateSet.delete(system);
338
- system.onLateUpdate && this.onLateUpdateSet.delete(system);
339
- system.onPhysicsUpdate && this.onPhysicsUpdateSet.delete(system);
340
- system.onPostPhysicsUpdate && this.onPostPhysicsUpdateSet.delete(system);
341
- system.onRender && this.onRenderUpdateSet.delete(system);
342
- }
343
- }
344
- entity.onRemove.dispatch();
345
- }
346
-
347
- resolve();
348
- }
349
- this.removeQueue = [];
350
-
351
- for (const [entity, resolve] of this.addQueue) {
352
- const preparePromises = [];
353
- const nexSystemContexts: SystemContext[] = [];
354
- const entities = entity.getAllEntities();
355
- for (const entity of entities) {
356
- if ((<any>entity).gameEngine) throw new Error('Entity already added to a gameEngine');
357
- (<any>entity).gameEngine = this;
358
- const systemContexts = this.injector.createSystems(entity);
359
- for (const context of systemContexts) {
360
- // TODO: implement synced mode where async onPrepares aren't allowed
361
- context.system.onPrepare && preparePromises.push(context.system.onPrepare());
362
- nexSystemContexts.push(context);
363
- }
364
- this.entitySystemMap.set(entity, systemContexts);
365
- }
366
-
367
- const startSystems = () => {
368
- // TODO: check if a "global" method is faster than this inner method
369
- for (const context of nexSystemContexts) {
370
- const system = context.system;
371
- this.mapAnnotatedSignals(system);
372
- system.onStart && system.onStart();
373
- system.onPreFixedUpdate && this.onPreFixedUpdateSet.add(system);
374
- system.onFixedUpdate && this.onFixedUpdateSet.add(system);
375
- system.onEarlyUpdate && this.onEarlyUpdateSet.add(system);
376
- system.onUpdate && this.onUpdateSet.add(system);
377
- system.onLateUpdate && this.onLateUpdateSet.add(system);
378
- system.onPhysicsUpdate && this.onPhysicsUpdateSet.add(system);
379
- system.onPostPhysicsUpdate && this.onPostPhysicsUpdateSet.add(system);
380
- system.onRender && this.onRenderUpdateSet.add(system);
381
- }
382
- resolve();
383
- };
384
-
385
- // Promise.all doesnt resolve immediately when there are no promises bu
386
- if (preparePromises.length === 0) {
387
- startSystems();
388
- } else {
389
- Promise.all(preparePromises).then(startSystems);
390
- }
391
- }
392
- this.addQueue = [];
393
- // create promise for next frame
394
- this.resolveFrame();
395
- this.framePromise = new Promise<any>(resolve => {
396
- this.resolveFrame = resolve;
397
- });
398
- this.onPrepare.dispatch();
399
- }
400
- }
401
- //
402
- // type RunSpread<T> = T extends undefined
403
- // ? []
404
- // : [T];
405
- //
406
- // export type GameActionMapping = { id: string, action: GameAction<any> }
407
- //
408
- // export function createGameAction<K extends keyof GameEngineActions>(id: K, action: GameAction<K>): GameActionMapping {
409
- // return {id, action};
410
- // }
411
- //
1
+ import {Action, Class, EngineSignals, GameEnginePlugin, OnFixedUpdateParams, OnUpdateParams, Service, System} from './types';
2
+ import {Signal, SignalBinding} from 'mani-signal';
3
+ import {Entity} from './entity';
4
+ import {EcsInjector, signalHandlers, staticSignalHandlers} from './ecsInjector';
5
+ import {Clock, GameClock} from './clock';
6
+ import {SystemContext} from './systemContext';
7
+ import {ID, putIfAbsent} from './injector';
8
+
9
+ type AddEntry = [Entity, () => void];
10
+ type RemoveEntry = [Entity, () => void];
11
+
12
+ const defaultOptions = {
13
+ fixedDeltaTime: 1 / 60,
14
+ plugins: [] as GameEnginePlugin[],
15
+ };
16
+
17
+ export type GameEngineOptions = Partial<typeof defaultOptions>;
18
+ declare global {
19
+ interface GameEngineActions {
20
+ 'testAction': string;
21
+ }
22
+ }
23
+
24
+ type GameEngineActionParams<K extends keyof GameEngineActions> = GameEngineActions[K];
25
+ type GameAction<K extends keyof GameEngineActions> = (engine: GameEngine, params: GameEngineActionParams<K>) => Promise<any> | any;
26
+
27
+ let id = 0;
28
+ export class GameEngine {
29
+ readonly id = id++;
30
+ readonly onPrepare: Signal;
31
+ readonly onStart: Signal;
32
+ readonly onEnd: Signal;
33
+ readonly onRender: Signal<OnUpdateParams>;
34
+ readonly onUpdate: Signal<OnUpdateParams>;
35
+ readonly onFixedUpdate: Signal<OnFixedUpdateParams>;
36
+ readonly onPrePhysicsUpdate: Signal<OnFixedUpdateParams>;
37
+ readonly onPhysicsUpdate: Signal<OnFixedUpdateParams>;
38
+ readonly onPostPhysicsUpdate: Signal<OnFixedUpdateParams>;
39
+ readonly onLateFixedUpdate: Signal<OnFixedUpdateParams>;
40
+ readonly onLateUpdate: Signal<OnUpdateParams>;
41
+ readonly onAddEntity: Signal<Entity>;
42
+ readonly onRemoveEntity: Signal<Entity>;
43
+
44
+
45
+ private readonly onEarlyUpdateSet = new Set<System>();
46
+ private readonly onUpdateSet = new Set<System>();
47
+ private readonly onFixedUpdateSet = new Set<System>();
48
+ private readonly onPreFixedUpdateSet = new Set<System>();
49
+ private readonly onPhysicsUpdateSet = new Set<System>();
50
+ private readonly onPrePhysicsUpdateSet = new Set<System>();
51
+ private readonly onPostPhysicsUpdateSet = new Set<System>();
52
+ private readonly onLateFixedUpdateSet = new Set<System>();
53
+ private readonly onLateUpdateSet = new Set<System>();
54
+ private readonly onRenderUpdateSet = new Set<System>();
55
+ private readonly onAddEntitySet = new Set<System>();
56
+ private readonly onRemoveEntitySet = new Set<System>();
57
+
58
+
59
+ // TODO: for performance, we could store the systems directly in the entity
60
+ private readonly entitySystemMap = new Map<Entity, Set<SystemContext>>();
61
+
62
+ private readonly serviceClasses = new Set<Class<Service>>();
63
+ private readonly services: Service[] = [];
64
+
65
+ private framePromise!: Promise<any>;
66
+ private resolveFrame: () => void = () => undefined;
67
+
68
+ private addQueue: AddEntry[] = [];
69
+ private removeQueue: RemoveEntry[] = [];
70
+
71
+ private _started = false;
72
+
73
+
74
+ get started(): boolean { return this._started; }
75
+
76
+ private _frameCount = 0;
77
+ get frameCount(): number { return this._frameCount; }
78
+
79
+ private _fixedFrameCount = 0;
80
+ get fixedFrameCount(): number { return this._fixedFrameCount; }
81
+
82
+ get numEntities(): number { return this.entitySystemMap.size;}
83
+
84
+ // TODO inject clock into game engine
85
+ // TODO inject space into game engine
86
+
87
+ constructor(
88
+ readonly injector: EcsInjector<Class<System>>,
89
+ readonly clock: Clock,
90
+ ) {
91
+ this.injector.map(GameEngine).toValue(this);
92
+
93
+ this.onPrepare = this.injector.getSignal(EngineSignals.OnPrepare);
94
+ this.onStart = this.injector.getSignal(EngineSignals.OnStart);
95
+ this.onEnd = this.injector.getSignal(EngineSignals.OnEnd);
96
+ this.onRender = this.injector.getSignal(EngineSignals.OnRender);
97
+ this.onFixedUpdate = this.injector.getSignal(EngineSignals.OnFixedUpdate);
98
+ this.onUpdate = this.injector.getSignal(EngineSignals.OnUpdate);
99
+ this.onLateUpdate = this.injector.getSignal(EngineSignals.OnLateUpdate);
100
+ this.onPrePhysicsUpdate = this.injector.getSignal(EngineSignals.OnPrePhysicsUpdate);
101
+ this.onPhysicsUpdate = this.injector.getSignal(EngineSignals.OnPhysicsUpdate);
102
+ this.onPostPhysicsUpdate = this.injector.getSignal(EngineSignals.OnPostPhysicsUpdate);
103
+ this.onLateFixedUpdate = this.injector.getSignal(EngineSignals.onLateFixedUpdate);
104
+
105
+ this.onAddEntity = this.injector.getSignal(EngineSignals.OnAddEntity);
106
+ this.onRemoveEntity = this.injector.getSignal(EngineSignals.OnRemoveEntity);
107
+
108
+ this.setupClock();
109
+ this.prepareFrame();
110
+ }
111
+
112
+ static createDefault(options?: GameEngineOptions) {
113
+ const opts = {...defaultOptions, ...options};
114
+ const clock = new GameClock({
115
+ fixedDeltaTime: opts.fixedDeltaTime,
116
+ autoStart: false,
117
+ });
118
+ const injector = new EcsInjector<Class<System>>();
119
+ const engine = new GameEngine(injector, clock);
120
+ engine.installPlugins(opts.plugins);
121
+ return engine;
122
+ }
123
+
124
+ static createDefaultWithInjector(injector: EcsInjector<Class<System>>, options?: GameEngineOptions) {
125
+ const opts = {...defaultOptions, ...options};
126
+ const clock = new GameClock({
127
+ fixedDeltaTime: opts.fixedDeltaTime,
128
+ autoStart: false,
129
+ });
130
+ const engine = new GameEngine(injector, clock);
131
+ engine.installPlugins(opts.plugins);
132
+ return engine;
133
+ }
134
+
135
+ addService(service: Service): void {
136
+ this.mapAnnotatedSignals(service);
137
+ service.onStart && service.onStart();
138
+ service.onPreFixedUpdate && this.onPreFixedUpdateSet.add(service);
139
+ service.onFixedUpdate && this.onFixedUpdateSet.add(service);
140
+ service.onUpdate && this.onUpdateSet.add(service);
141
+ service.onLateUpdate && this.onLateUpdateSet.add(service);
142
+ service.onPrePhysicsUpdate && this.onPrePhysicsUpdateSet.add(service);
143
+ service.onPhysicsUpdate && this.onPhysicsUpdateSet.add(service);
144
+ service.onPostPhysicsUpdate && this.onPostPhysicsUpdateSet.add(service);
145
+ service.onLateFixedUpdate && this.onLateFixedUpdateSet.add(service);
146
+ service.onRender && this.onRenderUpdateSet.add(service);
147
+ service.onAddEntity && this.onAddEntitySet.add(service);
148
+ service.onRemoveEntity && this.onRemoveEntitySet.add(service);
149
+ this.services.push(service);
150
+ }
151
+
152
+ installPlugins(plugins: GameEnginePlugin[]) {
153
+ plugins.forEach(plugin => {
154
+ plugin.onPrepare && plugin.onPrepare(this);
155
+ });
156
+ plugins.forEach(plugin => {
157
+ plugin.onStart && plugin.onStart(this);
158
+ });
159
+ }
160
+
161
+ registerSystem(systemClass: Class<System>): void {
162
+ this.mapStaticAnnotatedSignals(systemClass);
163
+ if (this._started) throw new Error('Register Systems before engine is started');
164
+ this.injector.registerSystem(systemClass);
165
+ }
166
+
167
+ registerService(serviceClass: Class<Service>): void {
168
+ this.mapStaticAnnotatedSignals(serviceClass);
169
+ if (this._started) throw new Error('Register Services before engine is started');
170
+ this.injector.map(serviceClass).toSingleton();
171
+ this.serviceClasses.add(serviceClass);
172
+ }
173
+
174
+ getService<T extends Class<Service>>(serviceClass: T): InstanceType<T> {
175
+ return this.injector.get(serviceClass);
176
+ }
177
+
178
+ start() {
179
+ this._started = true;
180
+ //TODO: throw when registering services or systems when engine is running
181
+ for (const serviceClass of this.serviceClasses) {
182
+ const service = this.injector.get(serviceClass);
183
+ this.addService(service);
184
+ }
185
+ this.clock.start();
186
+ this.onStart.dispatch();
187
+ }
188
+
189
+ private setupClock() {
190
+ this.clock.onPrepare.add(this.prepareFrame, this);
191
+
192
+ this.clock.onEarlyUpdate.add(({time, deltaTime}) => {
193
+ for (const system of this.onEarlyUpdateSet) {
194
+ system.onEarlyUpdate!(time, deltaTime);
195
+ }
196
+ });
197
+
198
+ this.clock.onFixedUpdate.add((params) => {
199
+ const {time, deltaTime} = params;
200
+ for (const system of this.onPreFixedUpdateSet) {
201
+ system.onPreFixedUpdate!(time, deltaTime);
202
+ }
203
+ for (const system of this.onFixedUpdateSet) {
204
+ system.onFixedUpdate!(time, deltaTime);
205
+ }
206
+ this.onFixedUpdate.dispatch(params);
207
+ for (const system of this.onPhysicsUpdateSet) {
208
+ system.onPhysicsUpdate!(time, deltaTime);
209
+ }
210
+ this.onPhysicsUpdate.dispatch(params);
211
+ this.onPostPhysicsUpdate.dispatch(params);
212
+ for (const system of this.onPostPhysicsUpdateSet) {
213
+ system.onPostPhysicsUpdate!(time, deltaTime);
214
+ }
215
+ this.onLateFixedUpdate.dispatch(params);
216
+ for (const system of this.onLateFixedUpdateSet) {
217
+ system.onLateFixedUpdate!(time, deltaTime);
218
+ }
219
+ this._fixedFrameCount++;
220
+ });
221
+
222
+ // TODO: update from outside
223
+ this.clock.onUpdate.add(onUpdateParams => {
224
+ const {time, deltaTime, alpha} = onUpdateParams;
225
+ for (const system of this.onUpdateSet) {
226
+ system.onUpdate!(time, deltaTime, alpha);
227
+ }
228
+ //TODO: merge with framerate to single signal?
229
+
230
+ this.onUpdate.dispatch(onUpdateParams);
231
+ for (const system of this.onLateUpdateSet) {
232
+ system.onLateUpdate!(time, deltaTime, alpha);
233
+ }
234
+ this.onLateUpdate.dispatch(onUpdateParams);
235
+
236
+ for (const system of this.onRenderUpdateSet) {
237
+ system.onRender!(time, deltaTime, alpha);
238
+ }
239
+ this.onRender.dispatch(onUpdateParams);
240
+ this._frameCount++;
241
+ });
242
+ }
243
+
244
+ add(entity: Entity) {
245
+ return new Promise<void>(resolve => this.addQueue.push([entity, resolve]));
246
+ }
247
+
248
+ waitFrame() {
249
+ return this.framePromise;
250
+ }
251
+
252
+ async remove(entity: Entity) {
253
+ if ((<any>entity).markRemoval) return;
254
+ (<any>entity).markRemoval = true;
255
+ return new Promise<void>(resolve => this.removeQueue.push([entity, resolve]));
256
+ }
257
+
258
+ stop() {
259
+ // this.injector.dispose();
260
+ this.clock.stop();
261
+ }
262
+
263
+ runAction<T extends Action>(action: T): ReturnType<T> {
264
+ return action(this);
265
+ }
266
+
267
+ getSignal<T>(signalId: ID): Signal<T> {
268
+ return this.injector.getSignal<T>(signalId);
269
+ }
270
+
271
+ private signalMappings = new Map<Class, [string, Signal][]>();
272
+ private staticSignalMappings = new Map<Class, [string, Signal][]>();
273
+ private signalMapBindings = new Map<Object, SignalBinding[]>();
274
+
275
+ // TODO: staticSignalMapBindings needed if we want to unregister Services or Systems
276
+
277
+ private mapStaticAnnotatedSignals(target: Class) {
278
+ let staticSignalMap = this.getStaticSignalMap(target);
279
+ if (staticSignalMap.length === 0) return;
280
+
281
+ const bindings = [];
282
+ for (const [key, signal] of staticSignalMap) {
283
+ bindings.push(signal.add((<any>target)[key], target));
284
+ }
285
+ // TODO: ignore bindings for now (store them if we implement unregister Service or Systems
286
+ }
287
+
288
+ private mapAnnotatedSignals(target: Object) {
289
+ const signalMap = this.getSignalMap(target.constructor);
290
+ if (signalMap.length === 0) return;
291
+
292
+ const bindings = [];
293
+ for (const [key, signal] of signalMap) {
294
+ bindings.push(signal.add((<any>target)[key], target));
295
+ }
296
+ this.signalMapBindings.set(target, bindings);
297
+ }
298
+
299
+ private unmapAnnotatedSignals(target: Object) {
300
+ const signalBindings = this.signalMapBindings.get(target);
301
+ if (!signalBindings) return;
302
+ for (const binding of signalBindings) {
303
+ binding.detach();
304
+ }
305
+ }
306
+
307
+ private getSignalMap(target: Function) {
308
+ // TODO: we could speed thinks up by introducing "invisible" flags on the systems/services to avoid a map check
309
+ return putIfAbsent(this.signalMappings, target, (): [string, Signal][] => {
310
+ const handlers = signalHandlers.get(target);
311
+ if (!handlers) return [];
312
+ const result: [string, Signal][] = [];
313
+ for (const [key, signalId] of handlers) {
314
+ result.push([key, this.getSignal(signalId)]);
315
+ }
316
+ return result;
317
+ });
318
+ }
319
+
320
+ private getStaticSignalMap(target: Class) {
321
+ // TODO: we could speed thinks up by introducing "invisible" flags on the systems/services to avoid a map check
322
+ return putIfAbsent(this.staticSignalMappings, target, (): [string, Signal][] => {
323
+ const handlers = staticSignalHandlers.get(target);
324
+ if (!handlers) return [];
325
+ const result: [string, Signal][] = [];
326
+ for (const [key, signalId] of handlers) {
327
+ result.push([key, this.getSignal(signalId)]);
328
+ }
329
+ return result;
330
+ });
331
+ }
332
+
333
+ dispose() {
334
+ this.clock.stop();
335
+ this.clock.dispose();
336
+ for (const systems of this.entitySystemMap.values()) {
337
+ for (const system of systems) {
338
+ system.system.onEnd && system.system.onEnd();
339
+ }
340
+ }
341
+ for (const service of this.services) {
342
+ service.onEnd && service.onEnd();
343
+ }
344
+ this.onEnd.dispatch();
345
+ }
346
+
347
+ private prepareFrame() {
348
+ for (const [entity, resolve] of this.removeQueue) {
349
+ const entities = entity.getAllEntities();
350
+ for (const entity of entities) {
351
+ (<any>entity).markRemoval = false;
352
+ if (!(<any>entity).gameEngine) {
353
+ console.log(entity);
354
+ // throw new Error('Entity not active');
355
+ }
356
+ (<any>entity).gameEngine = undefined;
357
+
358
+ const systemContexts = this.entitySystemMap.get(entity);
359
+ this.entitySystemMap.delete(entity);
360
+ if (systemContexts) {
361
+ for (const context of systemContexts) {
362
+ this.disposeContext(context);
363
+ }
364
+ }
365
+ entity.onRemove.dispatch();
366
+ entity.onRemove.detachAll();
367
+
368
+ for (const system of this.onRemoveEntitySet) {
369
+ system.onRemoveEntity!(entity);
370
+ }
371
+ }
372
+
373
+ resolve();
374
+ }
375
+ this.removeQueue = [];
376
+
377
+ for (const [entity, resolve] of this.addQueue) {
378
+
379
+ const preparePromises = [];
380
+ const nextSystemContexts: SystemContext[] = [];
381
+ const entities = entity.getAllEntities();
382
+ for (const entity of entities) {
383
+ if ((<any>entity).gameEngine) throw new Error('Entity already added to a gameEngine');
384
+ (<any>entity).gameEngine = this;
385
+ const systemContexts = this.injector.createSystemsForEntity(entity);
386
+ for (const context of systemContexts) {
387
+ // TODO: implement synced mode where async onPrepares aren't allowed
388
+ context.system.onPrepare && preparePromises.push(context.system.onPrepare());
389
+ nextSystemContexts.push(context);
390
+ }
391
+ this.entitySystemMap.set(entity, systemContexts);
392
+ }
393
+
394
+ const entityWasAdded = ()=> {
395
+ for (const system of this.onAddEntitySet) {
396
+ system.onAddEntity!(entity);
397
+ }
398
+ resolve();
399
+ }
400
+
401
+ // Promise.all doesnt resolve immediately when there are no promises bu
402
+ if (preparePromises.length === 0) {
403
+ this.startSystems(nextSystemContexts, entityWasAdded);
404
+ } else {
405
+ Promise.all(preparePromises).then(() => this.startSystems(nextSystemContexts, entityWasAdded));
406
+ }
407
+ }
408
+ this.addQueue = [];
409
+ // create promise for next frame
410
+ this.resolveFrame();
411
+ this.framePromise = new Promise<void>(resolve => {
412
+ this.resolveFrame = resolve;
413
+ });
414
+ this.onPrepare.dispatch();
415
+ }
416
+
417
+ private startSystems(contexts: Iterable<SystemContext>, then?: () => void) {
418
+ for (const context of contexts) {
419
+ const system = context.system;
420
+ this.mapAnnotatedSignals(system);
421
+ system.onStart && system.onStart();
422
+ system.onPreFixedUpdate && this.onPreFixedUpdateSet.add(system);
423
+ system.onFixedUpdate && this.onFixedUpdateSet.add(system);
424
+ system.onUpdate && this.onUpdateSet.add(system);
425
+ system.onLateUpdate && this.onLateUpdateSet.add(system);
426
+ system.onPhysicsUpdate && this.onPhysicsUpdateSet.add(system);
427
+ system.onPrePhysicsUpdate && this.onPrePhysicsUpdateSet.add(system);
428
+ system.onPostPhysicsUpdate && this.onPostPhysicsUpdateSet.add(system);
429
+ system.onLateFixedUpdate && this.onLateFixedUpdateSet.add(system);
430
+ system.onRender && this.onRenderUpdateSet.add(system);
431
+ system.onAddEntity && this.onAddEntitySet.add(system);
432
+ system.onRemoveEntity && this.onRemoveEntitySet.add(system);
433
+ }
434
+ then?.();
435
+ };
436
+
437
+ private disposeContext(context: SystemContext<System>) {
438
+ const system = context.system;
439
+
440
+ // if onEnd returns a promise, we need to wait for it to finish before we can dispose the system
441
+ const onEndPromise = system.onEnd && system.onEnd();
442
+ if (onEndPromise instanceof Promise) {
443
+ onEndPromise.then(() => {
444
+ context.dispose();
445
+ });
446
+ } else {
447
+ context.dispose();
448
+ }
449
+
450
+ this.unmapAnnotatedSignals(system);
451
+ system.onPreFixedUpdate && this.onPreFixedUpdateSet.delete(system);
452
+ system.onFixedUpdate && this.onFixedUpdateSet.delete(system);
453
+ system.onUpdate && this.onUpdateSet.delete(system);
454
+ system.onLateUpdate && this.onLateUpdateSet.delete(system);
455
+ system.onPhysicsUpdate && this.onPhysicsUpdateSet.delete(system);
456
+ system.onPrePhysicsUpdate && this.onPrePhysicsUpdateSet.delete(system);
457
+ system.onPostPhysicsUpdate && this.onPostPhysicsUpdateSet.delete(system);
458
+ system.onLateFixedUpdate && this.onLateFixedUpdateSet.delete(system);
459
+ system.onRender && this.onRenderUpdateSet.delete(system);
460
+ }
461
+ }
462
+ //
463
+ // type RunSpread<T> = T extends undefined
464
+ // ? []
465
+ // : [T];
466
+ //
467
+ // export type GameActionMapping = { id: string, action: GameAction<any> }
468
+ //
469
+ // export function createGameAction<K extends keyof GameEngineActions>(id: K, action: GameAction<K>): GameActionMapping {
470
+ // return {id, action};
471
+ // }
472
+ //