-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathworld.ts
More file actions
1256 lines (1106 loc) · 43.3 KB
/
world.ts
File metadata and controls
1256 lines (1106 loc) · 43.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { Archetype, MISSING_COMPONENT } from "./archetype";
import { ComponentChangeset } from "./changeset";
import { CommandBuffer, type Command } from "./command-buffer";
import type { ComponentId, EntityId, WildcardRelationId } from "./entity";
import {
decodeRelationId,
EntityIdManager,
getComponentIdByName,
getComponentNameById,
getDetailedIdType,
isCascadeDeleteComponent,
isDontFragmentComponent,
isExclusiveComponent,
isRelationId,
relation,
} from "./entity";
import { MultiMap } from "./multi-map";
import { Query } from "./query";
import { serializeQueryFilter, type QueryFilter } from "./query-filter";
import type { System } from "./system";
import { SystemScheduler } from "./system-scheduler";
import type { ComponentTuple, LifecycleHook } from "./types";
import { getOrCreateWithSideEffect } from "./utils";
/**
* World class for ECS architecture
* Manages entities, components, and systems
*/
export class World<UpdateParams extends any[] = []> {
// Core data structures for entity and archetype management
/** Manages allocation and deallocation of entity IDs */
private entityIdManager = new EntityIdManager();
/** Array of all archetypes in the world */
private archetypes: Archetype[] = [];
/** Maps archetype signatures (component type signatures) to archetype instances */
private archetypeBySignature = new Map<string, Archetype>();
/** Maps entity IDs to their current archetype */
private entityToArchetype = new Map<EntityId, Archetype>();
/** Maps component types to arrays of archetypes that contain them */
private archetypesByComponent = new Map<EntityId<any>, Archetype[]>();
/** Tracks which entities reference each entity as a component type */
private entityReferences = new Map<EntityId, MultiMap<EntityId, EntityId>>();
/** Storage for dontFragment relations - maps entity ID to a map of relation type to component data */
private dontFragmentRelations: Map<EntityId, Map<EntityId<any>, any>> = new Map();
// Query management
/** Array of all active queries for archetype change notifications */
private queries: Query[] = [];
/** Cache for queries keyed by component types and filter signatures */
private queryCache = new Map<string, { query: Query; refCount: number }>();
// System management
/** Schedules and executes systems in dependency order */
private systemScheduler = new SystemScheduler<UpdateParams>();
// Command execution
/** Buffers structural changes for deferred execution */
private commandBuffer = new CommandBuffer((entityId, commands) => this.executeEntityCommands(entityId, commands));
// Lifecycle and configuration
/** Stores lifecycle hooks for component and relation events */
private hooks = new Map<EntityId<any>, Set<LifecycleHook<any>>>();
/**
* Create a new World.
* If an optional snapshot object is provided (previously produced by `world.serialize()`),
* the world will be restored from that snapshot. The snapshot may contain non-JSON values.
*/
constructor(snapshot?: SerializedWorld) {
// If snapshot provided, restore world state
if (snapshot && typeof snapshot === "object") {
if (snapshot.entityManager) {
this.entityIdManager.deserializeState(snapshot.entityManager);
}
// Restore entities and their components
if (Array.isArray(snapshot.entities)) {
for (const entry of snapshot.entities) {
const entityId = entry.id as EntityId;
const componentsArray: SerializedComponent[] = entry.components || [];
const componentMap = new Map<EntityId<any>, any>();
const componentTypes: EntityId<any>[] = [];
for (const componentEntry of componentsArray) {
const componentTypeRaw = componentEntry.type;
let componentType: EntityId<any>;
if (typeof componentTypeRaw === "number") {
componentType = componentTypeRaw as EntityId<any>;
} else if (typeof componentTypeRaw === "string") {
// Component name lookup
const compId = getComponentIdByName(componentTypeRaw);
if (compId === undefined) {
throw new Error(`Unknown component name in snapshot: ${componentTypeRaw}`);
}
componentType = compId;
} else if (
typeof componentTypeRaw === "object" &&
componentTypeRaw !== null &&
typeof componentTypeRaw.component === "string"
) {
// Component name lookup
const compId = getComponentIdByName(componentTypeRaw.component);
if (compId === undefined) {
throw new Error(`Unknown component name in snapshot: ${componentTypeRaw.component}`);
}
if (typeof componentTypeRaw.target === "string") {
const targetCompId = getComponentIdByName(componentTypeRaw.target);
if (targetCompId === undefined) {
throw new Error(`Unknown target component name in snapshot: ${componentTypeRaw.target}`);
}
componentType = relation(compId, targetCompId);
} else {
componentType = relation(compId, componentTypeRaw.target as EntityId);
}
} else {
throw new Error(`Invalid component type in snapshot: ${JSON.stringify(componentTypeRaw)}`);
}
componentMap.set(componentType, componentEntry.value);
componentTypes.push(componentType);
}
const archetype = this.ensureArchetype(componentTypes);
archetype.addEntity(entityId, componentMap);
this.entityToArchetype.set(entityId, archetype);
// Update reverse index based on component types
for (const compType of componentTypes) {
const detailedType = getDetailedIdType(compType);
if (detailedType.type === "entity-relation") {
const targetEntityId = detailedType.targetId!;
this.trackEntityReference(entityId, compType, targetEntityId);
} else if (detailedType.type === "entity") {
this.trackEntityReference(entityId, compType, compType);
}
}
}
}
}
}
/**
* Generate a signature string for component types array
* @returns A string signature for the component types
*/
private createArchetypeSignature(componentTypes: EntityId<any>[]): string {
return componentTypes.join(",");
}
/**
* Create a new entity
* @returns The ID of the newly created entity
*/
new(): EntityId {
const entityId = this.entityIdManager.allocate();
// Create empty archetype for entities with no components
let emptyArchetype = this.ensureArchetype([]);
emptyArchetype.addEntity(entityId, new Map());
this.entityToArchetype.set(entityId, emptyArchetype);
return entityId;
}
/**
* Destroy an entity and remove all its components (immediate execution)
*/
private destroyEntityImmediate(entityId: EntityId): void {
// Implement BFS-style cascade deletion for entity relations where cascade is enabled
const queue: EntityId[] = [entityId];
const visited = new Set<EntityId>();
while (queue.length > 0) {
const cur = queue.shift()!;
if (visited.has(cur)) continue;
visited.add(cur);
const archetype = this.entityToArchetype.get(cur);
if (!archetype) {
continue; // Entity doesn't exist
}
// Collect references to this entity and iterate
const componentReferences = Array.from(this.getEntityReferences(cur));
for (const [sourceEntityId, componentType] of componentReferences) {
// For each referencing entity, decide whether to cascade delete or simply remove the component
const sourceArchetype = this.entityToArchetype.get(sourceEntityId);
if (!sourceArchetype) continue;
const detailedType = getDetailedIdType(componentType);
// Cascade only applies to entity relations (not component-relation)
if (detailedType.type === "entity-relation" && isCascadeDeleteComponent(detailedType.componentId!)) {
// Enqueue the referencing entity for deletion (cascade)
if (!visited.has(sourceEntityId)) {
queue.push(sourceEntityId);
}
continue;
}
// Non-cascade behavior: remove the relation component from the source entity
const currentComponents = new Map<EntityId<any>, any>();
let removedComponent = sourceArchetype.get(sourceEntityId, componentType);
for (const archetypeComponentType of sourceArchetype.componentTypes) {
if (archetypeComponentType !== componentType) {
const componentData = sourceArchetype.get(sourceEntityId, archetypeComponentType);
currentComponents.set(archetypeComponentType, componentData);
}
}
const newArchetype = this.ensureArchetype(currentComponents.keys());
// Remove from current archetype
sourceArchetype.removeEntity(sourceEntityId);
if (sourceArchetype.getEntities().length === 0) {
this.cleanupEmptyArchetype(sourceArchetype);
}
// Add to new archetype
newArchetype.addEntity(sourceEntityId, currentComponents);
this.entityToArchetype.set(sourceEntityId, newArchetype);
// Remove from component reverse index
this.untrackEntityReference(sourceEntityId, componentType, cur);
// Trigger component removed hooks
this.triggerLifecycleHooks(sourceEntityId, new Map(), new Map([[componentType, removedComponent]]));
}
// Clean up the reverse index for this entity
this.entityReferences.delete(cur);
// Remove the entity itself
archetype.removeEntity(cur);
if (archetype.getEntities().length === 0) {
this.cleanupEmptyArchetype(archetype);
}
this.entityToArchetype.delete(cur);
this.entityIdManager.deallocate(cur);
}
}
/**
* Check if an entity exists
*/
exists(entityId: EntityId): boolean {
return this.entityToArchetype.has(entityId);
}
/**
* Add a component to an entity (deferred)
*/
set(entityId: EntityId, componentType: EntityId<void>): void;
set<T>(entityId: EntityId, componentType: EntityId<T>, component: NoInfer<T>): void;
set(entityId: EntityId, componentType: EntityId, component?: any): void {
if (!this.exists(entityId)) {
throw new Error(`Entity ${entityId} does not exist`);
}
// Validate component type
const detailedType = getDetailedIdType(componentType);
if (detailedType.type === "invalid") {
throw new Error(`Invalid component type: ${componentType}`);
}
if (detailedType.type === "wildcard-relation") {
throw new Error(`Cannot directly add wildcard relation components: ${componentType}`);
}
this.commandBuffer.set(entityId, componentType, component);
}
/**
* Remove a component from an entity (deferred)
*/
remove<T>(entityId: EntityId, componentType: EntityId<T>): void {
if (!this.exists(entityId)) {
throw new Error(`Entity ${entityId} does not exist`);
}
// Validate component type
const detailedType = getDetailedIdType(componentType);
if (detailedType.type === "invalid") {
throw new Error(`Invalid component type: ${componentType}`);
}
this.commandBuffer.remove(entityId, componentType);
}
/**
* Destroy an entity and remove all its components (deferred)
*/
delete(entityId: EntityId): void {
this.commandBuffer.delete(entityId);
}
/**
* Check if an entity has a specific component
*/
has<T>(entityId: EntityId, componentType: EntityId<T>): boolean {
const archetype = this.entityToArchetype.get(entityId);
if (!archetype) {
return false;
}
// Check regular archetype components
if (archetype.componentTypes.includes(componentType)) {
return true;
}
// Check dontFragment relations
const detailedType = getDetailedIdType(componentType);
if (
(detailedType.type === "entity-relation" || detailedType.type === "component-relation") &&
isDontFragmentComponent(detailedType.componentId!)
) {
// Check if entity has this dontFragment relation in the shared storage
return this.dontFragmentRelations.get(entityId)?.has(componentType) ?? false;
}
return false;
}
/**
* Get component data for a specific entity and wildcard relation type
* Returns an array of all matching relation instances
* @param entityId The entity
* @param componentType The wildcard relation type
* @returns Array of [targetEntityId, componentData] pairs for all matching relations
*/
get<T>(entityId: EntityId, componentType: WildcardRelationId<T>): [EntityId<unknown>, T][];
/**
* Get component data for a specific entity and component type
* @param entityId The entity
* @param componentType The component type
* @returns The component data
*/
get<T>(entityId: EntityId, componentType: EntityId<T>): T;
get<T>(entityId: EntityId, componentType: EntityId<T> | WildcardRelationId<T>): T | [EntityId<unknown>, any][] {
const archetype = this.entityToArchetype.get(entityId);
if (!archetype) {
throw new Error(`Entity ${entityId} does not exist`);
}
// Check if entity has the component before attempting to get it
// Note: undefined is a valid component value, so we cannot use undefined to check existence
const detailedType = getDetailedIdType(componentType);
if (detailedType.type !== "wildcard-relation") {
// For regular components, check if the component type exists in the archetype or dontFragmentRelations
const inArchetype = archetype.componentTypes.includes(componentType);
const isDontFragment =
(detailedType.type === "entity-relation" || detailedType.type === "component-relation") &&
isDontFragmentComponent(detailedType.componentId!);
// For dontFragment relations, check if it exists in the dontFragmentRelations storage
const hasComponent =
inArchetype || (isDontFragment && this.dontFragmentRelations.get(entityId)?.has(componentType));
if (!hasComponent) {
throw new Error(
`Entity ${entityId} does not have component ${componentType}. Use has() to check component existence before calling get().`,
);
}
}
return archetype.get(entityId, componentType);
}
/**
* Register a system with optional dependencies
*/
registerSystem(system: System<UpdateParams>, additionalDeps: System<UpdateParams>[] = []): void {
this.systemScheduler.addSystem(system, additionalDeps);
}
/**
* Register a lifecycle hook for component or wildcard relation events
*/
hook<T>(componentType: EntityId<T>, hook: LifecycleHook<T>): void {
if (!this.hooks.has(componentType)) {
this.hooks.set(componentType, new Set());
}
this.hooks.get(componentType)!.add(hook);
if (hook.on_init !== undefined) {
this.archetypesByComponent.get(componentType)?.forEach((archetype) => {
const entities = archetype.getEntityToIndexMap();
const componentData = archetype.getComponentData<T>(componentType);
for (const [entity, index] of entities) {
const data = componentData[index];
const value = (data === MISSING_COMPONENT ? undefined : data) as T;
hook.on_init?.(entity, componentType, value);
}
});
}
}
/**
* Unregister a lifecycle hook for component or wildcard relation events
*/
unhook<T>(componentType: EntityId<T>, hook: LifecycleHook<T>): void {
const hooks = this.hooks.get(componentType);
if (hooks) {
hooks.delete(hook);
if (hooks.size === 0) {
this.hooks.delete(componentType);
}
}
}
/**
* Mark a component as exclusive relation
* @deprecated This method has been removed. Use component options instead: component({ exclusive: true })
* @throws Always throws an error directing to the new API
*/
setExclusive(componentId: EntityId): void {
throw new Error("setExclusive has been removed. Use component options instead: component({ exclusive: true })");
}
/**
* Mark a component as cascade-delete relation
* @deprecated This method has been removed. Use component options instead: component({ cascadeDelete: true })
* @throws Always throws an error directing to the new API
*/
setCascadeDelete(componentId: EntityId): void {
throw new Error(
"setCascadeDelete has been removed. Use component options instead: component({ cascadeDelete: true })",
);
}
/**
* Update the world (run all systems in dependency order)
* This function is synchronous when all systems are synchronous,
* and asynchronous (returns a Promise) when any system is asynchronous.
*/
update(...params: UpdateParams): Promise<void> | void {
const result = this.systemScheduler.update(...params);
if (result instanceof Promise) {
return result.then(() => this.commandBuffer.execute());
} else {
this.commandBuffer.execute();
}
}
/**
* Execute all deferred commands immediately without running systems
*/
sync(): void {
this.commandBuffer.execute();
}
/**
* Create a cached query for efficient entity lookups
* @returns A Query object for the specified component types and filter
*/
createQuery(componentTypes: EntityId<any>[], filter: QueryFilter = {}): Query {
// Build a deterministic key for the query (component types sorted + filter negative components sorted)
const sortedTypes = [...componentTypes].sort((a, b) => a - b);
const filterKey = serializeQueryFilter(filter);
const key = `${this.createArchetypeSignature(sortedTypes)}${filterKey ? `|${filterKey}` : ""}`;
const cached = this.queryCache.get(key);
if (cached) {
cached.refCount++;
return cached.query;
}
const query = new Query(this, sortedTypes, filter);
this.queryCache.set(key, { query, refCount: 1 });
return query;
}
/**
* @internal Register a query for archetype update notifications
*/
_registerQuery(query: Query): void {
this.queries.push(query);
}
/**
* @internal Unregister a query
*/
_unregisterQuery(query: Query): void {
const index = this.queries.indexOf(query);
if (index !== -1) {
this.queries.splice(index, 1);
}
}
/**
* Release a query reference obtained from createQuery.
* Decrements the refCount and fully disposes the query when it reaches zero.
*/
releaseQuery(query: Query): void {
for (const [k, v] of this.queryCache.entries()) {
if (v.query === query) {
v.refCount--;
if (v.refCount <= 0) {
this.queryCache.delete(k);
this._unregisterQuery(query);
// Fully dispose the query (will unregister it from notification list)
v.query._disposeInternal();
}
return;
}
}
}
/**
* @internal Get archetypes that match specific component types (for internal use by queries)
*/
getMatchingArchetypes(componentTypes: EntityId<any>[]): Archetype[] {
if (componentTypes.length === 0) {
return [...this.archetypes];
}
// Separate regular components from wildcard relations
const regularComponents: EntityId<any>[] = [];
const wildcardRelations: { componentId: EntityId<any>; relationId: EntityId<any> }[] = [];
for (const componentType of componentTypes) {
const detailedType = getDetailedIdType(componentType);
if (detailedType.type === "wildcard-relation") {
wildcardRelations.push({
componentId: detailedType.componentId!,
relationId: componentType,
});
} else {
regularComponents.push(componentType);
}
}
// Get archetypes for regular components
let matchingArchetypes: Archetype[] = [];
if (regularComponents.length > 0) {
const sortedRegularTypes = [...regularComponents].sort((a, b) => a - b);
if (sortedRegularTypes.length === 1) {
const componentType = sortedRegularTypes[0]!;
matchingArchetypes = this.archetypesByComponent.get(componentType) || [];
} else {
// Multi-component query - find intersection of archetypes
const archetypeLists = sortedRegularTypes.map((type) => this.archetypesByComponent.get(type) || []);
const firstList = archetypeLists[0] || [];
const intersection = new Set<Archetype>();
// Find archetypes that contain all required components
for (const archetype of firstList) {
let hasAllComponents = true;
for (let listIndex = 1; listIndex < archetypeLists.length; listIndex++) {
const otherList = archetypeLists[listIndex]!;
if (!otherList.includes(archetype)) {
hasAllComponents = false;
break;
}
}
if (hasAllComponents) {
intersection.add(archetype);
}
}
matchingArchetypes = Array.from(intersection);
}
} else {
// No regular components, start with all archetypes
matchingArchetypes = [...this.archetypes];
}
// Filter by wildcard relations
for (const wildcard of wildcardRelations) {
// Keep only archetypes that have the component (including dontFragment relations)
matchingArchetypes = matchingArchetypes.filter((archetype) =>
archetype.hasRelationWithComponentId(wildcard.componentId),
);
}
return matchingArchetypes;
}
/**
* Query entities with specific components
* @returns Array of entity IDs that have all the specified components
*/
query(componentTypes: EntityId<any>[]): EntityId[];
query<const T extends readonly EntityId<any>[]>(
componentTypes: T,
includeComponents: true,
): Array<{
entity: EntityId;
components: ComponentTuple<T>;
}>;
query(
componentTypes: EntityId<any>[],
includeComponents?: boolean,
):
| EntityId[]
| Array<{
entity: EntityId;
components: any;
}> {
const matchingArchetypes = this.getMatchingArchetypes(componentTypes);
if (includeComponents) {
const result: Array<{
entity: EntityId;
components: any;
}> = [];
for (const archetype of matchingArchetypes) {
const entitiesWithData = archetype.getEntitiesWithComponents(componentTypes as EntityId<any>[]);
result.push(...entitiesWithData);
}
return result;
} else {
const result: EntityId[] = [];
for (const archetype of matchingArchetypes) {
result.push(...archetype.getEntities());
}
return result;
}
}
/**
* @internal Execute commands for a single entity (for internal use by CommandBuffer)
* @returns ComponentChangeset describing the changes made
*/
executeEntityCommands(entityId: EntityId, commands: Command[]): ComponentChangeset {
const changeset = new ComponentChangeset();
// Handle entity destruction
if (commands.some((cmd) => cmd.type === "destroy")) {
this.destroyEntityImmediate(entityId);
return changeset;
}
const currentArchetype = this.entityToArchetype.get(entityId);
if (!currentArchetype) {
return changeset;
}
// Process commands to build changeset
this.processCommands(entityId, currentArchetype, commands, changeset);
// Apply changes to entity
const removedComponents = this.applyChangeset(entityId, currentArchetype, changeset);
// Update entity reference tracking
this.updateEntityReferences(entityId, changeset);
// Trigger lifecycle hooks
this.triggerLifecycleHooks(entityId, changeset.adds, removedComponents);
return changeset;
}
/**
* Process commands and populate the changeset
*/
private processCommands(
entityId: EntityId,
currentArchetype: Archetype,
commands: Command[],
changeset: ComponentChangeset,
): void {
for (const command of commands) {
if (command.type === "set" && command.componentType) {
this.processSetCommand(entityId, currentArchetype, command.componentType, command.component, changeset);
} else if (command.type === "delete" && command.componentType) {
this.processDeleteCommand(entityId, currentArchetype, command.componentType, changeset);
}
}
}
/**
* Process a set command, handling exclusive relations
*/
private processSetCommand(
entityId: EntityId,
currentArchetype: Archetype,
componentType: EntityId<any>,
component: any,
changeset: ComponentChangeset,
): void {
const detailedType = getDetailedIdType(componentType);
// Handle exclusive relations by removing existing relations with the same base component
if (
(detailedType.type === "entity-relation" || detailedType.type === "component-relation") &&
isExclusiveComponent(detailedType.componentId!)
) {
this.removeExclusiveRelations(entityId, currentArchetype, detailedType.componentId!, changeset);
}
changeset.set(componentType, component);
}
/**
* Remove all relations with the same base component (for exclusive relations)
*/
private removeExclusiveRelations(
entityId: EntityId,
currentArchetype: Archetype,
baseComponentId: EntityId<any>,
changeset: ComponentChangeset,
): void {
// Check archetype components
for (const componentType of currentArchetype.componentTypes) {
if (this.isRelationWithComponent(componentType, baseComponentId)) {
changeset.delete(componentType);
}
}
// Check dontFragment relations
const entityData = currentArchetype.getEntity(entityId);
if (entityData) {
for (const [componentType] of entityData) {
if (currentArchetype.componentTypes.includes(componentType)) continue;
if (this.isRelationWithComponent(componentType, baseComponentId)) {
changeset.delete(componentType);
}
}
}
}
/**
* Check if a component type is a relation with the given base component
*/
private isRelationWithComponent(componentType: EntityId<any>, baseComponentId: EntityId<any>): boolean {
const detailedType = getDetailedIdType(componentType);
return (
(detailedType.type === "entity-relation" || detailedType.type === "component-relation") &&
detailedType.componentId === baseComponentId
);
}
/**
* Process a delete command, handling wildcard relations
*/
private processDeleteCommand(
entityId: EntityId,
currentArchetype: Archetype,
componentType: EntityId<any>,
changeset: ComponentChangeset,
): void {
const detailedType = getDetailedIdType(componentType);
if (detailedType.type === "wildcard-relation") {
this.removeWildcardRelations(entityId, currentArchetype, detailedType.componentId!, changeset);
} else {
changeset.delete(componentType);
}
}
/**
* Remove all relations matching a wildcard component ID
*/
private removeWildcardRelations(
entityId: EntityId,
currentArchetype: Archetype,
baseComponentId: EntityId<any>,
changeset: ComponentChangeset,
): void {
// Check archetype components
for (const componentType of currentArchetype.componentTypes) {
if (this.isRelationWithComponent(componentType, baseComponentId)) {
changeset.delete(componentType);
}
}
// Check dontFragment relations
const entityData = currentArchetype.getEntity(entityId);
if (entityData) {
for (const [componentType] of entityData) {
if (currentArchetype.componentTypes.includes(componentType)) continue;
if (this.isRelationWithComponent(componentType, baseComponentId)) {
changeset.delete(componentType);
}
}
}
}
/**
* Apply changeset to entity, moving to new archetype if needed
* @returns Map of removed components with their data
*/
private applyChangeset(
entityId: EntityId,
currentArchetype: Archetype,
changeset: ComponentChangeset,
): Map<EntityId<any>, any> {
const currentEntityData = currentArchetype.getEntity(entityId);
const allCurrentComponentTypes = currentEntityData
? Array.from(currentEntityData.keys())
: currentArchetype.componentTypes;
const finalComponentTypes = changeset.getFinalComponentTypes(allCurrentComponentTypes);
const removedComponents = new Map<EntityId<any>, any>();
if (finalComponentTypes) {
// Move to new archetype
this.moveEntityToNewArchetype(entityId, currentArchetype, finalComponentTypes, changeset, removedComponents);
} else {
// Update in same archetype
this.updateEntityInSameArchetype(entityId, currentArchetype, changeset, removedComponents);
}
return removedComponents;
}
/**
* Move entity to a new archetype with updated components
*/
private moveEntityToNewArchetype(
entityId: EntityId,
currentArchetype: Archetype,
finalComponentTypes: EntityId<any>[],
changeset: ComponentChangeset,
removedComponents: Map<EntityId<any>, any>,
): void {
const newArchetype = this.ensureArchetype(finalComponentTypes);
const currentComponents = currentArchetype.removeEntity(entityId)!;
// Track removed components
for (const componentType of changeset.removes) {
removedComponents.set(componentType, currentComponents.get(componentType));
}
// Add to new archetype with updated components
newArchetype.addEntity(entityId, changeset.applyTo(currentComponents));
this.entityToArchetype.set(entityId, newArchetype);
// Cleanup empty archetype
if (currentArchetype.getEntities().length === 0) {
this.cleanupEmptyArchetype(currentArchetype);
}
}
/**
* Update entity in same archetype (no archetype change needed)
*/
private updateEntityInSameArchetype(
entityId: EntityId,
currentArchetype: Archetype,
changeset: ComponentChangeset,
removedComponents: Map<EntityId<any>, any>,
): void {
const currentComponents = currentArchetype.getEntity(entityId)!;
const hasDontFragmentChanges = this.hasDontFragmentChanges(changeset);
// Track removed dontFragment components
if (hasDontFragmentChanges) {
for (const componentType of changeset.removes) {
const detailedType = getDetailedIdType(componentType);
if (
(detailedType.type === "entity-relation" || detailedType.type === "component-relation") &&
isDontFragmentComponent(detailedType.componentId!)
) {
removedComponents.set(componentType, currentComponents.get(componentType));
}
}
}
if (hasDontFragmentChanges) {
// Re-add entity with updated components
this.readdEntityWithUpdatedComponents(entityId, currentArchetype, currentComponents, changeset);
} else {
// Direct update for non-dontFragment components
for (const [componentType, component] of changeset.adds) {
currentArchetype.set(entityId, componentType, component);
}
}
}
/**
* Check if changeset contains dontFragment relation changes
*/
private hasDontFragmentChanges(changeset: ComponentChangeset): boolean {
for (const componentType of changeset.removes) {
const detailedType = getDetailedIdType(componentType);
if (
(detailedType.type === "entity-relation" || detailedType.type === "component-relation") &&
isDontFragmentComponent(detailedType.componentId!)
) {
return true;
}
}
for (const [componentType] of changeset.adds) {
const detailedType = getDetailedIdType(componentType);
if (
(detailedType.type === "entity-relation" || detailedType.type === "component-relation") &&
isDontFragmentComponent(detailedType.componentId!)
) {
return true;
}
}
return false;
}
/**
* Remove and re-add entity with updated components (for dontFragment changes)
*/
private readdEntityWithUpdatedComponents(
entityId: EntityId,
archetype: Archetype,
currentComponents: Map<EntityId<any>, any>,
changeset: ComponentChangeset,
): void {
const newComponents = new Map<EntityId<any>, any>();
// Copy current components except those marked for removal
for (const [ct, value] of currentComponents) {
if (!changeset.removes.has(ct)) {
newComponents.set(ct, value);
}
}
// Add new components from changeset
for (const [ct, value] of changeset.adds) {
newComponents.set(ct, value);
}
archetype.removeEntity(entityId);
archetype.addEntity(entityId, newComponents);
}
/**
* Update entity reference tracking based on changeset
*/
private updateEntityReferences(entityId: EntityId, changeset: ComponentChangeset): void {
// Remove references for removed components
for (const componentType of changeset.removes) {
const detailedType = getDetailedIdType(componentType);
if (detailedType.type === "entity-relation") {
this.untrackEntityReference(entityId, componentType, detailedType.targetId!);
} else if (detailedType.type === "entity") {
this.untrackEntityReference(entityId, componentType, componentType);
}
}
// Add references for added components
for (const [componentType] of changeset.adds) {
const detailedType = getDetailedIdType(componentType);
if (detailedType.type === "entity-relation") {
this.trackEntityReference(entityId, componentType, detailedType.targetId!);
} else if (detailedType.type === "entity") {
this.trackEntityReference(entityId, componentType, componentType);
}
}
}
/**
* Get or create an archetype for the given component types
* Filters out dontFragment relations from the archetype signature
* @returns The archetype for the given component types (excluding dontFragment relations)
*/
private ensureArchetype(componentTypes: Iterable<EntityId<any>>): Archetype {
const regularTypes = this.filterRegularComponentTypes(componentTypes);
const sortedTypes = regularTypes.sort((a, b) => a - b);
const hashKey = this.createArchetypeSignature(sortedTypes);
return getOrCreateWithSideEffect(this.archetypeBySignature, hashKey, () => this.createNewArchetype(sortedTypes));
}
/**
* Filter out dontFragment relations from component types
*/
private filterRegularComponentTypes(componentTypes: Iterable<EntityId<any>>): EntityId<any>[] {
const regularTypes: EntityId<any>[] = [];
for (const componentType of componentTypes) {
const detailedType = getDetailedIdType(componentType);
// Skip dontFragment relations from archetype signature
if (
(detailedType.type === "entity-relation" || detailedType.type === "component-relation") &&
isDontFragmentComponent(detailedType.componentId!)
) {
continue;
}
regularTypes.push(componentType);
}
return regularTypes;
}
/**
* Create a new archetype and register it with all tracking structures
*/
private createNewArchetype(componentTypes: EntityId<any>[]): Archetype {
const newArchetype = new Archetype(componentTypes, this.dontFragmentRelations);
this.archetypes.push(newArchetype);