@driftengine/entities 3.61.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/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright 2026 Drift Technologies
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/NOTICE ADDED
@@ -0,0 +1,9 @@
1
+ DriftEngine
2
+ Copyright 2026 Drift Technologies
3
+
4
+ This product includes software developed at Drift Technologies
5
+ (https://github.com/drftrun/driftengine).
6
+
7
+ Licensed under the Apache License, Version 2.0. Section 4(d) of that licence
8
+ requires this NOTICE to be reproduced in any derivative work you distribute,
9
+ in the source, the documentation, or a display generated by the work.
package/README.md ADDED
@@ -0,0 +1,93 @@
1
+ # @driftengine/entities
2
+
3
+ Entities with generational identity, component storage, queries, systems with declared reads and
4
+ writes, prefabs and scene serialization.
5
+
6
+ **It imports no other engine package.** An entity model that knew what a `Transform` was would be an
7
+ entity model that knew it had a scene — and the argument for declared reads and writes is that a
8
+ declaration is about a component _id_ rather than about what the component means.
9
+
10
+ It also **declares no component types**. A consumer writes the ones its world needs, or takes them
11
+ from whichever package owns the subsystem.
12
+
13
+ ```ts
14
+ import { EntityAllocator } from '@driftengine/entities';
15
+
16
+ const entities = new EntityAllocator();
17
+ const player = entities.create();
18
+ entities.destroy(player);
19
+ entities.alive(player); // false — and the entity that takes the slot is a different handle
20
+ ```
21
+
22
+ ## The handle
23
+
24
+ An entity is one number: a 26-bit index and a 27-bit generation, combined arithmetically. **The
25
+ generation is what stops a stale handle addressing a live entity** — an index freed and reused makes
26
+ every old reference silently valid, pointing at a different thing with no error anywhere.
27
+
28
+ The conventional packed `Uint32` splits 24 and 8, so a slot's 257th reuse hands back a handle
29
+ identical to its first. This split gives sixty-seven million entities and 134 million reuses of each
30
+ slot, and costs four bytes per stored entity because a handle lives in a `Float64Array`.
31
+
32
+ 26 + 27 is the whole 53-bit budget, exactly. There is no headroom, deliberately, and a test asserts
33
+ the top handle so that is discovered here rather than in a wrong comparison.
34
+
35
+ ## Systems declare what they touch
36
+
37
+ ```ts
38
+ const schedule = buildSchedule([
39
+ { name: 'hunger', writes: [Hunger], everyTicks: 60, run(view) { … } },
40
+ { name: 'decay', reads: [Hunger], writes: [Health], after: ['hunger'], run(view) { … } },
41
+ ]);
42
+ runSchedule(world, schedule, tick);
43
+ ```
44
+
45
+ **The declaration is enforced.** A system that writes something it did not declare is refused
46
+ naming both — a schedule derived from a lie is worse than no schedule. `writes` implies `reads`.
47
+
48
+ Order is declaration order, adjusted only by `after`, which is topologically sorted with
49
+ declaration order as the tie-break. A cycle in `after` is refused naming the systems.
50
+
51
+ `everyTicks` strides the **fixed step** and is never a rate in seconds: a rate in wall-clock time
52
+ leaves the determinism contract on its first dropped frame.
53
+
54
+ **Destroying from inside a system is deferred** to after it returns. A removal swaps the last dense
55
+ entry into the hole, so removing mid-walk moves an entity the cursor has already passed into a
56
+ position it has already visited — and that entity is never seen, silently, and only whichever one
57
+ happened to be last. `create` and `add` are immediate, and a newly added entity may be visited in
58
+ the same pass.
59
+
60
+ ## Prefabs and scenes
61
+
62
+ ```ts
63
+ const guard = definePrefab('guard', [
64
+ [Health, { current: 100 }],
65
+ [Perception, { sightRange: 40 }],
66
+ ]);
67
+ const spawned = instantiate(world, guard, { Perception: { sightRange: 60 } });
68
+
69
+ const scene = serializeWorld(world, [Health, Perception]);
70
+ const result = deserializeWorld(fresh, scene, [Health, Perception]);
71
+ ```
72
+
73
+ **A prefab is a value with no link back to its instances.** A live link is what an editor wants,
74
+ and it costs every instance a record of which fields it has overridden; Track K can add that record
75
+ without changing what a prefab is.
76
+
77
+ **A scene addresses every value by a stable field id**, never a name and never a position. A field
78
+ inserted in the middle would renumber everything after it, and a save would then load the right
79
+ names with the wrong values — worse than failing, because it looks like it worked.
80
+
81
+ Loading across a change goes through `driftscript`'s migration, unchanged: a field added since
82
+ arrives with its default, one removed is dropped, and one whose **type** changed is refused naming
83
+ it. Nothing is written into the world until every entity has migrated, so a refusal on the fifth
84
+ does not leave four behind.
85
+
86
+ Entity references are **remapped** on load rather than preserved, because a saved handle's slot may
87
+ be live in the world being loaded into. That only works for fields declared `Entity`; a number that
88
+ happens to hold one is a number.
89
+
90
+ ## Documentation
91
+
92
+ This file is the reference, including the five things the model refuses and what
93
+ would reverse each.
@@ -0,0 +1,136 @@
1
+ /**
2
+ * What an entity *is*, and the allocator that hands them out.
3
+ *
4
+ * An entity is a handle and nothing else — no object, no class, no fields. What it *has* lives in
5
+ * component stores keyed by it, which is the whole arrangement, and it is why an entity can be a
6
+ * number in a typed array rather than something a frame has to chase a pointer to.
7
+ *
8
+ * ---
9
+ *
10
+ * ## The generation, and why it may not wrap
11
+ *
12
+ * **An index freed and reused makes every old reference to it silently valid** — pointing at a
13
+ * different thing, of a different kind, with no error anywhere. That is the failure the generation
14
+ * exists to prevent, so the only question worth deciding is how long before it wraps and brings the
15
+ * failure back.
16
+ *
17
+ * The conventional answer is a packed 32-bit handle, twenty-four bits of index and eight of
18
+ * generation. It makes a slot's 257th reuse hand back a handle **identical** to its first. Here the
19
+ * split is 26 and 27, combined arithmetically rather than by shifting, because a shift is 32-bit in
20
+ * JavaScript and a double is exact to 53: sixty-seven million entities, and 134 million reuses of
21
+ * each slot before a repeat.
22
+ *
23
+ * **26 + 27 is the whole 53-bit budget, with nothing spare**, so the largest handle is
24
+ * `Number.MAX_SAFE_INTEGER` itself. A third field in a handle, or one more bit of either, stops the
25
+ * arithmetic being exact — and the failure then is a handle that compares equal to a different one,
26
+ * which is the same hole the generation was added to close. A test asserts the top handle rather
27
+ * than leaving that to be discovered.
28
+ *
29
+ * **The cost is that a handle is eight bytes rather than four**, because it lives in a
30
+ * `Float64Array` and not a `Uint32Array`. That is paid on entity *lists* rather than on component
31
+ * data, which is where the bytes actually are.
32
+ *
33
+ * **What would make this wrong** is a consumer with more than 67 million live entities, at which
34
+ * point the split moves and every stored scene has to be rewritten — which is why the two numbers
35
+ * are here, once, and every site goes through `packEntity` rather than writing the arithmetic.
36
+ */
37
+ /** One past the highest index a handle can carry: 2^26, or 67,108,864 entities. */
38
+ export declare const ENTITY_INDEX_CEILING = 67108864;
39
+ /** One past the highest generation: 2^27, or 134,217,728 reuses of one slot. */
40
+ export declare const ENTITY_GENERATION_CEILING = 134217728;
41
+ /**
42
+ * An entity handle.
43
+ *
44
+ * A plain number so it stores in a typed array and compares with `===`. It is opaque: reading the
45
+ * index or the generation out of one is what `entityIndex` and `entityGeneration` are for, and code
46
+ * that does the arithmetic itself is code that has to be found when the split moves.
47
+ */
48
+ export type Entity = number;
49
+ export declare function packEntity(index: number, generation: number): Entity;
50
+ export declare function entityIndex(entity: Entity): number;
51
+ export declare function entityGeneration(entity: Entity): number;
52
+ /**
53
+ * An allocator's whole position, for a rewind.
54
+ *
55
+ * **Reused between saves rather than made per save.** A rollback loop takes one of these sixty
56
+ * times a second, so the arrays are grown to the allocator's own capacity once and then written
57
+ * over; the fields are mutable for that reason and not because a caller should touch them.
58
+ *
59
+ * The free queue is held as a count and a typed array instead of the `number[]` the allocator
60
+ * keeps, so a save is a memcpy. **Its order is part of the state**, not an incidental detail: the
61
+ * queue is first-in-first-out precisely so slot wear spreads, and restoring the same slots in a
62
+ * different order hands out different handles on the next create.
63
+ */
64
+ export interface AllocatorSnapshot {
65
+ generations: Uint32Array;
66
+ live: Uint8Array;
67
+ free: Int32Array;
68
+ freeCount: number;
69
+ highWater: number;
70
+ aliveCount: number;
71
+ }
72
+ export declare function createAllocatorSnapshot(): AllocatorSnapshot;
73
+ export interface EntityAllocatorOptions {
74
+ /**
75
+ * How many slots this allocator may ever hand out.
76
+ *
77
+ * Present so a test can reach the refusal without allocating sixty-seven million slots. A
78
+ * consumer has no reason to set it, and setting it low does not save memory — the arrays grow on
79
+ * demand either way.
80
+ */
81
+ readonly ceiling?: number;
82
+ }
83
+ /**
84
+ * Slots, their generations, and a queue of the ones that are free.
85
+ *
86
+ * **The free list is first-in-first-out**, and that is what makes the generation ceiling a number
87
+ * about the pool rather than about one slot. A stack hands the same slot straight back, so one
88
+ * spawn-and-destroy pair in a loop burns that slot's whole range while every other slot sits
89
+ * unused. A queue spreads the wear.
90
+ *
91
+ * The cost is that a freed slot is not reused until every other freed slot has been, so a workload
92
+ * that churns a handful of entities touches more of the arrays than a stack would. That is a cache
93
+ * argument against a correctness one, and correctness wins.
94
+ */
95
+ export declare class EntityAllocator {
96
+ /** Generation per slot. Index `i` holds the generation of whatever lives at index `i` now. */
97
+ private generations;
98
+ /** Whether slot `i` is currently handed out. */
99
+ private live;
100
+ /** Freed slots, oldest first. A plain array: a queue that grows, drained from the front. */
101
+ private readonly free;
102
+ /** How far into the arrays this allocator has ever reached. */
103
+ private highWater;
104
+ private alive_;
105
+ private readonly ceiling;
106
+ constructor(options?: EntityAllocatorOptions);
107
+ get liveCount(): number;
108
+ create(): Entity;
109
+ /**
110
+ * Free an entity's slot. `false` when the handle was already stale, which is not an error.
111
+ *
112
+ * A caller destroying something twice is a caller that lost track, and the honest answer is that
113
+ * there was nothing to destroy — the same shape `patchModule` and `Scope.leave` use.
114
+ */
115
+ destroy(entity: Entity): boolean;
116
+ alive(entity: Entity): boolean;
117
+ /**
118
+ * Copy this allocator's position into a slot, growing the slot's arrays if it has not held one
119
+ * this large before.
120
+ *
121
+ * **`highWater` bounds every copy**, because slots beyond it have never been handed out and their
122
+ * generations are zero on both sides. That is what keeps the cost proportional to the world rather
123
+ * than to the arrays' capacity.
124
+ */
125
+ saveInto(slot: AllocatorSnapshot): void;
126
+ /**
127
+ * Put this allocator back to a saved position.
128
+ *
129
+ * **Slots between the saved `highWater` and the current one are cleared rather than left**, and
130
+ * that is the whole difference between a restore and a partial one. An entity created after the
131
+ * save has a live slot the save knows nothing about; leaving it live would leave an entity in the
132
+ * world that the snapshot says does not exist, and its handle would keep answering `alive`.
133
+ */
134
+ loadFrom(slot: AllocatorSnapshot): void;
135
+ private grow;
136
+ }
package/dist/entity.js ADDED
@@ -0,0 +1,201 @@
1
+ /**
2
+ * What an entity *is*, and the allocator that hands them out.
3
+ *
4
+ * An entity is a handle and nothing else — no object, no class, no fields. What it *has* lives in
5
+ * component stores keyed by it, which is the whole arrangement, and it is why an entity can be a
6
+ * number in a typed array rather than something a frame has to chase a pointer to.
7
+ *
8
+ * ---
9
+ *
10
+ * ## The generation, and why it may not wrap
11
+ *
12
+ * **An index freed and reused makes every old reference to it silently valid** — pointing at a
13
+ * different thing, of a different kind, with no error anywhere. That is the failure the generation
14
+ * exists to prevent, so the only question worth deciding is how long before it wraps and brings the
15
+ * failure back.
16
+ *
17
+ * The conventional answer is a packed 32-bit handle, twenty-four bits of index and eight of
18
+ * generation. It makes a slot's 257th reuse hand back a handle **identical** to its first. Here the
19
+ * split is 26 and 27, combined arithmetically rather than by shifting, because a shift is 32-bit in
20
+ * JavaScript and a double is exact to 53: sixty-seven million entities, and 134 million reuses of
21
+ * each slot before a repeat.
22
+ *
23
+ * **26 + 27 is the whole 53-bit budget, with nothing spare**, so the largest handle is
24
+ * `Number.MAX_SAFE_INTEGER` itself. A third field in a handle, or one more bit of either, stops the
25
+ * arithmetic being exact — and the failure then is a handle that compares equal to a different one,
26
+ * which is the same hole the generation was added to close. A test asserts the top handle rather
27
+ * than leaving that to be discovered.
28
+ *
29
+ * **The cost is that a handle is eight bytes rather than four**, because it lives in a
30
+ * `Float64Array` and not a `Uint32Array`. That is paid on entity *lists* rather than on component
31
+ * data, which is where the bytes actually are.
32
+ *
33
+ * **What would make this wrong** is a consumer with more than 67 million live entities, at which
34
+ * point the split moves and every stored scene has to be rewritten — which is why the two numbers
35
+ * are here, once, and every site goes through `packEntity` rather than writing the arithmetic.
36
+ */
37
+ /** One past the highest index a handle can carry: 2^26, or 67,108,864 entities. */
38
+ export const ENTITY_INDEX_CEILING = 67_108_864;
39
+ /** One past the highest generation: 2^27, or 134,217,728 reuses of one slot. */
40
+ export const ENTITY_GENERATION_CEILING = 134_217_728;
41
+ export function packEntity(index, generation) {
42
+ return index + generation * ENTITY_INDEX_CEILING;
43
+ }
44
+ export function entityIndex(entity) {
45
+ return entity % ENTITY_INDEX_CEILING;
46
+ }
47
+ export function entityGeneration(entity) {
48
+ return Math.floor(entity / ENTITY_INDEX_CEILING);
49
+ }
50
+ export function createAllocatorSnapshot() {
51
+ return {
52
+ generations: new Uint32Array(0),
53
+ live: new Uint8Array(0),
54
+ free: new Int32Array(0),
55
+ freeCount: 0,
56
+ highWater: 0,
57
+ aliveCount: 0,
58
+ };
59
+ }
60
+ /**
61
+ * Slots, their generations, and a queue of the ones that are free.
62
+ *
63
+ * **The free list is first-in-first-out**, and that is what makes the generation ceiling a number
64
+ * about the pool rather than about one slot. A stack hands the same slot straight back, so one
65
+ * spawn-and-destroy pair in a loop burns that slot's whole range while every other slot sits
66
+ * unused. A queue spreads the wear.
67
+ *
68
+ * The cost is that a freed slot is not reused until every other freed slot has been, so a workload
69
+ * that churns a handful of entities touches more of the arrays than a stack would. That is a cache
70
+ * argument against a correctness one, and correctness wins.
71
+ */
72
+ export class EntityAllocator {
73
+ /** Generation per slot. Index `i` holds the generation of whatever lives at index `i` now. */
74
+ generations = new Uint32Array(64);
75
+ /** Whether slot `i` is currently handed out. */
76
+ live = new Uint8Array(64);
77
+ /** Freed slots, oldest first. A plain array: a queue that grows, drained from the front. */
78
+ free = [];
79
+ /** How far into the arrays this allocator has ever reached. */
80
+ highWater = 0;
81
+ alive_ = 0;
82
+ ceiling;
83
+ constructor(options = {}) {
84
+ this.ceiling = options.ceiling ?? ENTITY_INDEX_CEILING;
85
+ }
86
+ get liveCount() {
87
+ return this.alive_;
88
+ }
89
+ create() {
90
+ /* `shift` is O(n) on a large array and this is not a per-frame path — an entity is created when
91
+ something enters the world. A ring buffer is the fix if a profile ever says so. */
92
+ const recycled = this.free.shift();
93
+ if (recycled !== undefined) {
94
+ this.live[recycled] = 1;
95
+ this.alive_ += 1;
96
+ return packEntity(recycled, this.generations[recycled]);
97
+ }
98
+ if (this.highWater >= this.ceiling) {
99
+ throw new Error(`this world has handed out ${this.ceiling} entities, which is its index ceiling. Nothing ` +
100
+ 'is wrapped or reused: a handle beyond the ceiling would repeat one that is already ' +
101
+ 'live, and answering the wrong entity is worse than refusing.');
102
+ }
103
+ const index = this.highWater;
104
+ this.highWater += 1;
105
+ this.grow(index + 1);
106
+ this.live[index] = 1;
107
+ this.alive_ += 1;
108
+ return packEntity(index, this.generations[index]);
109
+ }
110
+ /**
111
+ * Free an entity's slot. `false` when the handle was already stale, which is not an error.
112
+ *
113
+ * A caller destroying something twice is a caller that lost track, and the honest answer is that
114
+ * there was nothing to destroy — the same shape `patchModule` and `Scope.leave` use.
115
+ */
116
+ destroy(entity) {
117
+ if (!this.alive(entity))
118
+ return false;
119
+ const index = entityIndex(entity);
120
+ this.live[index] = 0;
121
+ /*
122
+ * The generation moves on **destroy**, not on the next create, so a handle stops being live the
123
+ * moment it is destroyed rather than the moment somebody happens to take its slot. Moving it
124
+ * later would leave a window in which a destroyed handle still answered `alive`.
125
+ */
126
+ const next = (this.generations[index] + 1) % ENTITY_GENERATION_CEILING;
127
+ this.generations[index] = next;
128
+ this.free.push(index);
129
+ this.alive_ -= 1;
130
+ return true;
131
+ }
132
+ alive(entity) {
133
+ const index = entityIndex(entity);
134
+ if (index >= this.highWater)
135
+ return false;
136
+ return this.live[index] === 1 && this.generations[index] === entityGeneration(entity);
137
+ }
138
+ /**
139
+ * Copy this allocator's position into a slot, growing the slot's arrays if it has not held one
140
+ * this large before.
141
+ *
142
+ * **`highWater` bounds every copy**, because slots beyond it have never been handed out and their
143
+ * generations are zero on both sides. That is what keeps the cost proportional to the world rather
144
+ * than to the arrays' capacity.
145
+ */
146
+ saveInto(slot) {
147
+ const reach = this.highWater;
148
+ if (slot.generations.length < reach)
149
+ slot.generations = new Uint32Array(reach);
150
+ if (slot.live.length < reach)
151
+ slot.live = new Uint8Array(reach);
152
+ if (slot.free.length < this.free.length)
153
+ slot.free = new Int32Array(this.free.length);
154
+ for (let i = 0; i < reach; i++) {
155
+ slot.generations[i] = this.generations[i];
156
+ slot.live[i] = this.live[i];
157
+ }
158
+ for (let i = 0; i < this.free.length; i++)
159
+ slot.free[i] = this.free[i];
160
+ slot.freeCount = this.free.length;
161
+ slot.highWater = reach;
162
+ slot.aliveCount = this.alive_;
163
+ }
164
+ /**
165
+ * Put this allocator back to a saved position.
166
+ *
167
+ * **Slots between the saved `highWater` and the current one are cleared rather than left**, and
168
+ * that is the whole difference between a restore and a partial one. An entity created after the
169
+ * save has a live slot the save knows nothing about; leaving it live would leave an entity in the
170
+ * world that the snapshot says does not exist, and its handle would keep answering `alive`.
171
+ */
172
+ loadFrom(slot) {
173
+ this.grow(slot.highWater);
174
+ for (let i = 0; i < slot.highWater; i++) {
175
+ this.generations[i] = slot.generations[i];
176
+ this.live[i] = slot.live[i];
177
+ }
178
+ for (let i = slot.highWater; i < this.highWater; i++) {
179
+ this.generations[i] = 0;
180
+ this.live[i] = 0;
181
+ }
182
+ this.free.length = 0;
183
+ for (let i = 0; i < slot.freeCount; i++)
184
+ this.free.push(slot.free[i]);
185
+ this.highWater = slot.highWater;
186
+ this.alive_ = slot.aliveCount;
187
+ }
188
+ grow(needed) {
189
+ if (needed <= this.generations.length)
190
+ return;
191
+ let size = this.generations.length;
192
+ while (size < needed)
193
+ size *= 2;
194
+ const generations = new Uint32Array(size);
195
+ generations.set(this.generations);
196
+ this.generations = generations;
197
+ const live = new Uint8Array(size);
198
+ live.set(this.live);
199
+ this.live = live;
200
+ }
201
+ }