mani-game-engine 1.0.0-pre.10 → 1.0.0-pre.100

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/entity.ts CHANGED
@@ -1,116 +1,257 @@
1
1
  import {GameEngine} from './gameEngine';
2
2
  import {Signal} from 'mani-signal';
3
3
  import {Class} from './types';
4
- import {entityComponents} from './ecsInjector';
4
+ import {ID, putIfAbsent} from './injector';
5
+ import {EcsInjector} from './ecsInjector';
5
6
 
6
7
  let idCounter = 0;
7
8
 
9
+ export type RemoveOptions = { dispose: boolean };
8
10
  export class Entity {
9
11
 
10
- readonly id: number;
11
- readonly children = new Set<Entity>();
12
- private gameEngine?: GameEngine;
12
+ readonly children = new Set<Entity>();
13
+ readonly gameEngine?: GameEngine;
14
+ readonly onAdd = new Signal();
13
15
 
14
- // TODO: use single rootEntity class instead of undefined?
15
- private _parent?: Entity;
16
- readonly parentChanged = new Signal();
17
- readonly onRemove = new Signal();
18
- private markRemoval = false;
16
+ get isAdded() {
17
+ return !!this.gameEngine;
18
+ }
19
19
 
20
- constructor() {
21
- this.id = idCounter++;
20
+ // TODO: use single rootEntity class instead of undefined?
21
+ private _parent?: Entity;
22
+ readonly parentChanged = new Signal();
23
+ readonly onRemove = new Signal();
24
+ private _detached = false;
25
+ readonly _signalMap: Map<ID, Signal> = new Map<ID, Signal>();
26
+
27
+ // this is filled by the injector
28
+ private _components?: Map<Class, InstanceType<any>>;
29
+ get components(): ReadonlyMap<Class, InstanceType<any>> {
30
+ if (!this._components) {
31
+ this._components = new Map<Class, InstanceType<any>>();
32
+ EcsInjector.entityComponents.get(this.constructor as Class)!.forEach((field, componentClass) =>
33
+ this._components!.set(componentClass, (this as any)[field]));
22
34
  }
35
+ return this._components;
36
+ }
23
37
 
24
- async onBeforeRemove?(): Promise<void>;
38
+ private _dynamicComponents = new Map<Class, InstanceType<any>>();
25
39
 
26
- private setParent(parent: Entity | undefined) {
27
- if (parent === this._parent) {
28
- //TODO: i think this check can be removed
29
- throw Error('same parent');
30
- }
31
- this._parent = parent;
32
- this.parentChanged.dispatch();
40
+ readonly dynamicComponentAdded = new Signal<InstanceType<any>>();
41
+ readonly dynamicComponentRemoved = new Signal<InstanceType<any>>();
42
+
43
+ get dynamicComponents(): ReadonlyMap<Class, InstanceType<any>> {
44
+ return this._dynamicComponents;
45
+ }
46
+
47
+ // TODO: move the logic to gameEngine?
48
+ addDynamicComponent<T extends Class>(component: InstanceType<T>): this {
49
+ if (this.hasDynamicComponentClass(component.constructor)) {
50
+ throw new Error('component of this class already added');
51
+ }
52
+ if (!this.gameEngine) {
53
+ this._dynamicComponents.set(component.constructor as T, component);
54
+ this.dynamicComponentAdded.dispatch(component);
55
+ return this;
33
56
  }
34
57
 
35
- get parent(): Entity | undefined {
36
- return this._parent;
58
+ this.gameEngine.maybeDefer(() => {
59
+ this._dynamicComponents.set(component.constructor as T, component);
60
+ this.dynamicComponentAdded.dispatch(component);
61
+ // it could be that we are within the system creation loop (component is added within a constructor of a system)
62
+ const systemContexts = this.gameEngine!.injector.createSystemsForDynamicComponents(component.constructor, this);
63
+
64
+ if (!systemContexts) return this;
65
+ const preparePromises = [];
66
+ for (const context of systemContexts) {
67
+ context.system.onPrepare && preparePromises.push(context.system.onPrepare());
68
+ }
69
+ for (const context of systemContexts) {
70
+ this.gameEngine!['entitySystemMap'].get(this)?.add(context);
71
+ // (this.gameEngine as any).addSystemContextSetToMap(this, systemContexts);
72
+ }
73
+
74
+ if (preparePromises.length === 0) {
75
+ this.gameEngine!['startSystems'](systemContexts, () => {});
76
+ } else {
77
+ Promise.all(preparePromises).then(() => this.gameEngine?.['startSystems'](systemContexts));
78
+ }
79
+ });
80
+ return this;
81
+ }
82
+
83
+ hasDynamicComponentClass<T extends Class>(componentClass: T): boolean {
84
+ return this._dynamicComponents.has(componentClass);
85
+ }
86
+
87
+ // TODO: move the logic to gameEngine?
88
+ removeDynamicComponentClass<T extends Class>(componentClass: T) {
89
+ if (!this.gameEngine) {
90
+ if (!this._dynamicComponents.has(componentClass)) {
91
+ throw new Error('component not found: ' + JSON.stringify(componentClass));
92
+ }
93
+ this._dynamicComponents.delete(componentClass);
94
+ this.dynamicComponentRemoved.dispatch(this._dynamicComponents.get(componentClass)!);
95
+ return;
37
96
  }
38
97
 
39
- getComponent<T extends Class>(componentClass: T): InstanceType<T> | undefined {
40
- const componentMap = entityComponents.get(this.constructor as Class);
41
- if (!componentMap) {
42
- throw new Error(`No components in entity of type '${this.constructor.name}'.`);
98
+ this.gameEngine.maybeDefer(() => {
99
+ const systemContexts = this.gameEngine?.['entitySystemMap'].get(this);
100
+ systemContexts?.forEach(systemContext => {
101
+ const systemToDependencies = this.gameEngine?.injector['dynamicComponentDependencyMap'];
102
+ const dependencies = systemToDependencies?.get((systemContext.system as any).constructor);
103
+ if (!dependencies) return;
104
+ if (dependencies.some(dependency => dependency.type === componentClass)) {
105
+ this.gameEngine?.['disposeContext']?.(systemContext);
106
+ systemContexts?.delete(systemContext);
107
+ }
108
+ });
109
+ const component = this._dynamicComponents.get(componentClass);
110
+ if (!this._dynamicComponents.delete(componentClass)) {
111
+ throw new Error('component not found: ' + JSON.stringify(componentClass));
43
112
  }
44
- const key = componentMap.get(componentClass as T);
45
- return key && (<any>this)[key];
113
+ this.dynamicComponentRemoved.dispatch(component);
114
+ },
115
+ );}
116
+
117
+ removeDynamicComponent<T extends Class>(component: InstanceType<T>) {
118
+ this.removeDynamicComponentClass(component.constructor as T);
119
+ }
120
+
121
+ getDynamicComponent<T extends Class>(componentClass: T): InstanceType<T> | undefined {
122
+ return this._dynamicComponents.get(componentClass);
123
+ }
124
+
125
+ getDynamicComponentOrThrow<T extends Class>(componentClass: T): InstanceType<T> {
126
+ const component = this._dynamicComponents.get(componentClass);
127
+ if (!component) {
128
+ throw new Error(`DynamicComponent '${componentClass.name}' not found in entity of type '${this.constructor.name}'.`);
46
129
  }
130
+ return component;
131
+ }
47
132
 
48
- async add(entity: Entity) {
49
- if (entity.parent === this) {
50
- throw new Error('Entity is already a child');
51
- }
52
- if (entity === this) {
53
- throw new Error('Could not add Entity as a child of itself.');
54
- }
133
+ get detached(): boolean { return this._detached; }
55
134
 
56
- if (entity.parent) {
57
- entity.parent.children.delete(entity);
58
- }
59
- this.children.add(entity);
60
- entity.setParent(this);
61
-
62
- if (entity.gameEngine) {
63
- if (this.gameEngine !== entity.gameEngine) {
64
- throw new Error('cant add an active to a passive entity');
65
- }
66
- } else {
67
- if (this.gameEngine) {
68
-
69
- await this.gameEngine.add(entity);
70
- }
71
- }
135
+ async onBeforeRemove?(): Promise<void>;
72
136
 
73
- // TODO: systems should be informed so they can do stuff (renderer system should add object 3d etc...)
137
+ getSignal<T>(id: ID): Signal<T> {
138
+ return putIfAbsent(this._signalMap, id, () => new Signal<any>());
139
+ }
74
140
 
75
- if (this.gameEngine && this.gameEngine !== entity.gameEngine) {
141
+ private setParent(parent: Entity | undefined) {
142
+ if (parent === this._parent) {
143
+ //TODO: i think this check can be removed
144
+ throw Error('same parent');
145
+ }
146
+ this._parent = parent;
147
+ this.parentChanged.dispatch();
148
+ }
76
149
 
77
- }
150
+ get parent(): Entity | undefined {
151
+ return this._parent;
152
+ }
153
+
154
+ getComponent<T extends Class>(componentClass: T): InstanceType<T> | undefined {
155
+ const componentMap = EcsInjector.entityComponents.get(this.constructor as Class);
156
+ if (!componentMap) {
157
+ throw new Error(`No components in entity of type '${this.constructor.name}'.`);
78
158
  }
159
+ const key = componentMap.get(componentClass as T);
160
+ return key && (<any>this)[key];
161
+ }
79
162
 
80
- async remove(entity: Entity) {
81
- if (!this.children.delete(entity)) {
82
- throw new Error('Could not remove. Entity is not a child.');
83
- }
84
- entity.setParent(undefined);
85
- if (this.gameEngine) {
86
- return await this.gameEngine.remove(entity);
87
- }
163
+ getComponentOrThrow<T extends Class>(componentClass: T): InstanceType<T> {
164
+ const componentMap = EcsInjector.entityComponents.get(this.constructor as Class);
165
+ if (!componentMap) {
166
+ throw new Error(`No components in entity of type '${this.constructor.name}'.`);
88
167
  }
168
+ const key = componentMap.get(componentClass as T);
169
+ if (!key) {
170
+ throw new Error(`Component '${componentClass.name}' not found in entity of type '${this.constructor.name}'.`);
171
+ }
172
+ return (<any>this)[key];
173
+ }
89
174
 
90
- async detach() {
91
- if (this.parent) {
92
- await this.parent.remove(this);
93
- } else {
94
- if (!this.gameEngine) {
95
- throw new Error('entity isn\'t attached to a parent or the game engine');
96
- }
97
- await this.gameEngine.remove(this);
98
- }
175
+ async add(entity: Entity) {
176
+ if (entity.parent === this) {
177
+ throw new Error('Entity is already a child');
178
+ }
179
+ if (entity === this) {
180
+ throw new Error('Could not add Entity as a child of itself.');
99
181
  }
100
182
 
101
- has(entity: Entity) {
102
- return this.children.has(entity);
183
+ if (entity.parent) {
184
+ entity.parent.children.delete(entity);
103
185
  }
186
+ this.children.add(entity);
187
+ entity.setParent(this);
104
188
 
105
- /**
106
- * this includes the entity itself
107
- * @param target
108
- */
109
- getAllEntities(target: Entity[] = []) {
110
- target.push(this);
111
- for (const child of this.children) {
112
- child.getAllEntities(target);
113
- }
114
- return target;
189
+ if (entity.gameEngine) {
190
+ if (this.gameEngine !== entity.gameEngine) {
191
+ throw new Error('cant add an active to a passive entity');
192
+ }
193
+ } else {
194
+ if (this.gameEngine) {
195
+
196
+ await this.gameEngine.add(entity);
197
+ }
198
+ }
199
+
200
+ // TODO: systems should be informed so they can do stuff (renderer system should add object 3d etc...)
201
+
202
+ if (this.gameEngine && this.gameEngine !== entity.gameEngine) {
203
+
204
+ }
205
+ }
206
+
207
+ async remove(entity: Entity, options?: RemoveOptions) {
208
+ if (!this.children.delete(entity)) {
209
+ throw new Error('Could not remove. Entity is not a child.');
210
+ }
211
+ entity.setParent(undefined);
212
+ if (this.gameEngine) {
213
+ return await this.gameEngine.remove(entity, options);
214
+ }
215
+ entity._signalMap.forEach(signal => signal.detachAll());
216
+ }
217
+
218
+ dispose() {
219
+ this._signalMap.forEach(signal => signal.detachAll());
220
+ }
221
+
222
+ async detach(options?: RemoveOptions) {
223
+ if (this._detached) {
224
+ throw new Error('entity already detached');
115
225
  }
226
+ this._detached = true;
227
+ // TODO: mark for detach and prevent another call, because this.gameEngine is set to undefined until next frame
228
+ if (this.parent) {
229
+ await this.parent.remove(this, options);
230
+ } else {
231
+ if (!this.gameEngine) {
232
+ throw new Error('entity isn\'t attached to a parent or the game engine');
233
+ }
234
+ await this.gameEngine.remove(this, options);
235
+ }
236
+ }
237
+
238
+ has(entity: Entity) {
239
+ return this.children.has(entity);
240
+ }
241
+
242
+ /**
243
+ * this includes the entity itself
244
+ * @param target
245
+ */
246
+ getAllEntities(target: Entity[] = []) {
247
+ target.push(this);
248
+ for (const child of this.children) {
249
+ child.getAllEntities(target);
250
+ }
251
+ return target;
252
+ }
253
+
254
+ hasDynamicComponents() {
255
+ return this._dynamicComponents.size > 0;
256
+ }
116
257
  }