@daneren2005/shared-memory-ecs 1.5.1 → 1.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (32) hide show
  1. package/README.md +222 -44
  2. package/dist/actions/add-component-worker.d.ts +3 -0
  3. package/dist/actions/build-worker-entity.d.ts +4 -2
  4. package/dist/actions/create-entity-worker.d.ts +2 -2
  5. package/dist/actions/kill-entity-worker.d.ts +2 -2
  6. package/dist/actions/remove-component-worker.d.ts +3 -0
  7. package/dist/component-definition.d.ts +2 -0
  8. package/dist/create-system-worker-DURlIMia.js +345 -0
  9. package/dist/create-system-worker-DURlIMia.js.map +1 -0
  10. package/dist/entity-class.d.ts +51 -0
  11. package/dist/entity-component.d.ts +7 -2
  12. package/dist/entity-factory.d.ts +21 -5
  13. package/dist/entity.d.ts +11 -2
  14. package/dist/index.d.ts +15 -8
  15. package/dist/index.js +379 -166
  16. package/dist/index.js.map +1 -1
  17. package/dist/systems/{component-system.d.ts → entity-worker-system.d.ts} +39 -18
  18. package/dist/systems/system.d.ts +1 -1
  19. package/dist/systems/worker-system.d.ts +22 -0
  20. package/dist/systems/workers/apply-query-delta.d.ts +1 -1
  21. package/dist/systems/workers/create-entity-system-worker.d.ts +8 -0
  22. package/dist/systems/workers/create-system-worker.d.ts +9 -0
  23. package/dist/systems/workers/entity-system-web-worker.d.ts +18 -0
  24. package/dist/systems/workers/{component-worker-message.d.ts → entity-system-worker-message.d.ts} +8 -4
  25. package/dist/worker.d.ts +10 -6
  26. package/dist/worker.js +2 -2
  27. package/dist/world.d.ts +17 -17
  28. package/package.json +2 -1
  29. package/dist/create-component-worker-BM942gjg.js +0 -288
  30. package/dist/create-component-worker-BM942gjg.js.map +0 -1
  31. package/dist/systems/workers/component-web-worker.d.ts +0 -17
  32. package/dist/systems/workers/create-component-worker.d.ts +0 -8
@@ -0,0 +1,345 @@
1
+ import e from "@daneren2005/shared-memory-objects/memory-heap";
2
+ import { getPointer as t } from "@daneren2005/shared-memory-objects/utils/pointer";
3
+ import n from "@daneren2005/shared-memory-objects/shared-pool";
4
+ import r from "@daneren2005/shared-memory-objects/constant-string";
5
+ //#region src/memory-component.ts
6
+ var i = class e {
7
+ heap;
8
+ pool;
9
+ constructor(e, t, r, i) {
10
+ this.heap = e, this.pool = i ? new n(e, i) : new n(e, {
11
+ type: t,
12
+ dataLength: r
13
+ });
14
+ }
15
+ static fromSharedMemory(t, n) {
16
+ return new e(t, Uint32Array, 1, n);
17
+ }
18
+ getSharedMemory() {
19
+ return this.pool.getSharedMemory();
20
+ }
21
+ get length() {
22
+ return this.pool.length;
23
+ }
24
+ get rawLength() {
25
+ return this.pool.bufferLength;
26
+ }
27
+ create(e) {
28
+ return this.pool.push(e);
29
+ }
30
+ getBlock(e) {
31
+ return this.pool.at(e);
32
+ }
33
+ get(e, t) {
34
+ return this.pool.get(e, t);
35
+ }
36
+ set(e, t, n) {
37
+ let r = this.pool.at(e);
38
+ r[t] = n;
39
+ }
40
+ delete(e) {
41
+ this.pool.deleteIndex(e);
42
+ }
43
+ clear() {
44
+ this.pool.clear();
45
+ }
46
+ }, a = class {
47
+ heap;
48
+ byValue = /* @__PURE__ */ new Map();
49
+ byPointer = /* @__PURE__ */ new Map();
50
+ constructor(e) {
51
+ this.heap = e;
52
+ }
53
+ getOrCreate(e) {
54
+ let t = this.byValue.get(e);
55
+ if (t) return t;
56
+ let n = new r(this.heap, e);
57
+ return this.byValue.set(e, n), this.byPointer.set(n.pointer, e), n;
58
+ }
59
+ getString(e) {
60
+ if (e === 0) return "";
61
+ let n = this.byPointer.get(e);
62
+ if (n !== void 0) return n;
63
+ let i = t(e);
64
+ if (this.heap.buffers[i.bufferPosition] === void 0) return;
65
+ let a = new r(this.heap, i).value;
66
+ return this.byPointer.set(e, a), a;
67
+ }
68
+ clear() {
69
+ this.byValue.forEach((e) => e.free()), this.byValue.clear(), this.byPointer.clear();
70
+ }
71
+ };
72
+ //#endregion
73
+ //#region src/systems/workers/apply-query-delta.ts
74
+ function o(e, t) {
75
+ if (t.removed.length) {
76
+ let n = new Set(t.removed);
77
+ e = e.filter((e) => !n.has(e.entityId));
78
+ }
79
+ if (t.added.length) {
80
+ let n = /* @__PURE__ */ new Map();
81
+ e.forEach((e, t) => n.set(e.entityId, t));
82
+ for (let r of t.added) {
83
+ let t = n.get(r.entityId);
84
+ t === void 0 ? (n.set(r.entityId, e.length), e.push(r)) : e[t] = r;
85
+ }
86
+ }
87
+ return e;
88
+ }
89
+ //#endregion
90
+ //#region src/actions/build-worker-entity.ts
91
+ function s(e, t, n, r, i) {
92
+ let a = t[e.type] ?? {};
93
+ if (i && Object.prototype.hasOwnProperty.call(e, "class")) throw Error("Entity class comes from its type template and cannot be supplied by a worker config");
94
+ let o = {
95
+ ...a,
96
+ ...e
97
+ }, s = typeof a.class == "string" ? a.class : void 0, c = Object.keys(n);
98
+ if (i) {
99
+ if (a.type !== e.type) throw Error(`Entity template ${e.type} must declare the same type`);
100
+ let t = s ? i[s] : void 0;
101
+ if (!t) throw Error(`Entity type ${e.type} has unknown class ${s ?? ""}`);
102
+ c = t.components;
103
+ }
104
+ let l = r.allocateEid(), u = {};
105
+ for (let e of c) {
106
+ if (e === "entity") continue;
107
+ let t = n[e];
108
+ if (!t) throw Error(`Entity class ${s ?? ""} contains unknown component ${e}`);
109
+ t.loadInFinishLoading || t.loadProperties.some((e) => e in o) && (u[e] = r.allocateComponentBlock(e, t.toBlock(o)));
110
+ }
111
+ return {
112
+ eid: l,
113
+ type: e.type,
114
+ class: s,
115
+ isStatic: o.isStatic,
116
+ components: u
117
+ };
118
+ }
119
+ function c(e, t, n, r) {
120
+ if (e === "entity") throw Error("The entity component cannot be added at runtime");
121
+ let i = n[e];
122
+ if (!i) throw Error(`Unknown component: ${e}`);
123
+ if (i.loadInFinishLoading) throw Error(`Component ${e} requires main-thread finishLoading and cannot be added in a worker`);
124
+ return {
125
+ name: e,
126
+ index: r.allocateComponentBlock(e, i.toBlock(t))
127
+ };
128
+ }
129
+ //#endregion
130
+ //#region src/component.ts
131
+ var l = class {
132
+ index;
133
+ block;
134
+ constructor(e, t) {
135
+ this.block = e, this.index = t;
136
+ }
137
+ }, u = 0, d = 1, f = 2, p = 3, m = class extends l {
138
+ cache;
139
+ constructor(e, t, n) {
140
+ super(e, t), this.cache = n;
141
+ }
142
+ get type() {
143
+ return this.cache.getString(this.block[2]) ?? "";
144
+ }
145
+ get class() {
146
+ return this.cache.getString(this.block[3]) ?? "";
147
+ }
148
+ get dead() {
149
+ return this.block[0] === 1;
150
+ }
151
+ set dead(e) {
152
+ this.block[0] = +!!e;
153
+ }
154
+ get isStatic() {
155
+ return this.block[1] === 1;
156
+ }
157
+ set isStatic(e) {
158
+ this.block[1] = +!!e;
159
+ }
160
+ }, h = {
161
+ type: Uint32Array,
162
+ size: 4,
163
+ loadProperties: ["type", "isStatic"],
164
+ toBlock(e, t) {
165
+ let n = t.world.constantStrings, r = e.type ? n.getOrCreate(e.type).pointer : 0, i = e.class ? n.getOrCreate(e.class).pointer : 0;
166
+ return [
167
+ +!!e.dead,
168
+ +!!e.isStatic,
169
+ r,
170
+ i
171
+ ];
172
+ },
173
+ attach(e, t, n) {
174
+ return new m(t.getBlock(n), n, e.world.constantStrings);
175
+ },
176
+ save(e) {
177
+ let t = {};
178
+ return e.type && (t.type = e.type), e.dead && (t.dead = !0), t;
179
+ }
180
+ };
181
+ //#endregion
182
+ //#region src/actions/kill-entity-worker.ts
183
+ function g(e, t, n) {
184
+ let r = t.entity;
185
+ r && (r[0] = 1), n.entityDied(e);
186
+ }
187
+ //#endregion
188
+ //#region src/actions/create-entity-worker.ts
189
+ function _(e, t, n) {
190
+ if (!e.buildEntityDescriptor) throw Error("createEntityWorker requires the system to be registered with createsEntities: true and the component registry passed to createEntitySystemWorker");
191
+ n.createEntity(e.buildEntityDescriptor(t));
192
+ }
193
+ //#endregion
194
+ //#region src/actions/add-component-worker.ts
195
+ function v(e, t, n, r, i) {
196
+ if (!e.buildComponentDescriptor) throw Error("addComponentWorker requires addsComponents: true and the component registry passed to createEntitySystemWorker");
197
+ i.addComponent(t, e.buildComponentDescriptor(String(n), r));
198
+ }
199
+ //#endregion
200
+ //#region src/actions/remove-component-worker.ts
201
+ function y(e, t, n) {
202
+ n.removeComponent(e, t);
203
+ }
204
+ //#endregion
205
+ //#region src/systems/workers/create-entity-system-worker.ts
206
+ function b(t, n, r) {
207
+ let l = [], u = {}, d, f, p, m = {}, h, g, _, v = !1, y = (e) => p?.getString(e) ?? "";
208
+ t.onmessage = function(b) {
209
+ let S = b.data;
210
+ if (S.type === "init") x(t, { type: "init-complete" });
211
+ else if (S.type === "load") {
212
+ if (S.heap && (f = new e(S.heap), p = new a(f), f.addOnGrowBufferHandlers((e) => x(t, {
213
+ type: "grow-buffer-from-worker",
214
+ buffer: e
215
+ }))), f && S.sharedMemory) {
216
+ m = {};
217
+ for (let e of Object.keys(S.sharedMemory.components)) m[e] = i.fromSharedMemory(f, S.sharedMemory.components[e]);
218
+ h = f.getSharedAlloc(S.sharedMemory.eidCounter);
219
+ }
220
+ g = S.factoryConfigs, _ = S.factoryClasses, v = !!S.addsComponents, d = n.init?.(S.data) ?? void 0, x(t, { type: "loaded" });
221
+ } else if (S.type === "grow-buffer") f && f.buffers[S.buffer.bufferPosition] === void 0 && f.addSharedBuffer(S.buffer);
222
+ else if (S.type === "reset") {
223
+ l = [];
224
+ for (let e of Object.keys(u)) delete u[e];
225
+ d = void 0;
226
+ } else if (S.type === "run") {
227
+ d && Object.assign(S.world, d), S.world.getString = y, S.world.heap = f;
228
+ let e = {
229
+ allocateEid: () => h ? Atomics.add(h.data, 0, 1) + 1 : 0,
230
+ allocateComponentBlock: (e, t) => m[e].create(t)
231
+ };
232
+ S.world.allocate = e, g && r && (S.world.buildEntityDescriptor = (t) => s(t, g, r, e, _)), v && r && (S.world.buildComponentDescriptor = (t, n) => c(t, n, r, e));
233
+ let i = performance.now(), a = [], p = {}, b = [], C = [], w = [];
234
+ l = o(l, S.entities);
235
+ let T = {};
236
+ Object.entries(S.queries).forEach(([e, t]) => {
237
+ let n = o(u[e] ?? [], t);
238
+ u[e] = n, T[e] = n;
239
+ });
240
+ let E = {
241
+ entityComponentChanged(e, t, n, r) {
242
+ a.push({
243
+ entityId: e,
244
+ event: "component-property-updated",
245
+ args: [
246
+ t,
247
+ n,
248
+ r
249
+ ]
250
+ });
251
+ },
252
+ emitEntityEvent(e, t, ...n) {
253
+ a.push({
254
+ entityId: e,
255
+ event: t,
256
+ args: n
257
+ });
258
+ },
259
+ emitSystemEvent(e, t) {
260
+ (p[e] ?? (p[e] = [])).push(t);
261
+ },
262
+ entityDied(e) {
263
+ a.push({
264
+ entityId: e,
265
+ event: "death",
266
+ args: []
267
+ });
268
+ },
269
+ createEntity(e) {
270
+ b.push(e);
271
+ },
272
+ addComponent(e, t) {
273
+ C.push({
274
+ type: "add",
275
+ entityId: e,
276
+ component: t
277
+ });
278
+ },
279
+ removeComponent(e, t) {
280
+ C.push({
281
+ type: "remove",
282
+ entityId: e,
283
+ componentName: String(t)
284
+ });
285
+ }
286
+ }, D = !1;
287
+ if (n.preRun) try {
288
+ n.preRun(S.world, l, T, E);
289
+ } catch (e) {
290
+ D = !0, w.push({
291
+ error: e,
292
+ phase: "preRun"
293
+ });
294
+ }
295
+ D || l.forEach((e) => {
296
+ try {
297
+ n(S.world, e.entityId, e.components, T, E);
298
+ } catch (t) {
299
+ w.push({
300
+ error: t,
301
+ phase: "update",
302
+ entityId: e.entityId
303
+ });
304
+ }
305
+ }), n.entityRemoved && S.entities.removed.forEach((e) => {
306
+ try {
307
+ n.entityRemoved(S.world, e, E);
308
+ } catch (t) {
309
+ w.push({
310
+ error: t,
311
+ phase: "entityRemoved",
312
+ entityId: e
313
+ });
314
+ }
315
+ });
316
+ let O = performance.now() - i;
317
+ x(t, {
318
+ type: "run-complete",
319
+ generation: S.generation,
320
+ runTime: O,
321
+ events: a,
322
+ systemEvents: p,
323
+ created: b,
324
+ componentChanges: C,
325
+ errors: w
326
+ });
327
+ }
328
+ };
329
+ }
330
+ function x(e, t) {
331
+ e.postMessage(t);
332
+ }
333
+ //#endregion
334
+ //#region src/systems/workers/create-system-worker.ts
335
+ function S(e) {
336
+ let t = (() => {});
337
+ return t.preRun = (t, n, r, i) => e(t, r, i), e.init && (t.init = e.init), e.entityRemoved && (t.entityRemoved = e.entityRemoved), t;
338
+ }
339
+ function C(e, t, n) {
340
+ b(e, S(t), n);
341
+ }
342
+ //#endregion
343
+ export { a as _, v as a, p as c, f as d, h as f, o as g, s as h, y as i, u as l, c as m, S as n, _ as o, l as p, b as r, g as s, C as t, d as u, i as v };
344
+
345
+ //# sourceMappingURL=create-system-worker-DURlIMia.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"create-system-worker-DURlIMia.js","names":[],"sources":["../src/memory-component.ts","../src/constant-string-cache.ts","../src/systems/workers/apply-query-delta.ts","../src/actions/build-worker-entity.ts","../src/component.ts","../src/entity-component.ts","../src/actions/kill-entity-worker.ts","../src/actions/create-entity-worker.ts","../src/actions/add-component-worker.ts","../src/actions/remove-component-worker.ts","../src/systems/workers/create-entity-system-worker.ts","../src/systems/workers/create-system-worker.ts"],"sourcesContent":["import SharedPool from '@daneren2005/shared-memory-objects/shared-pool';\nimport type { SharedPoolMemory } from '@daneren2005/shared-memory-objects/shared-pool';\nimport type MemoryHeap from '@daneren2005/shared-memory-objects/memory-heap';\nimport type { TypedArrayConstructor } from '@daneren2005/shared-memory-objects/interfaces/typed-array-constructor';\n\nexport type ComponentTypedArray = Uint32Array | Int32Array | Float32Array | Float64Array;\n\n// Backed by a SharedPool: all bookkeeping lives in the shared heap, so a worker can reconstruct a handle over\n// the same pool (pass the owner's getSharedMemory() as `memory`) and allocate/read blocks off-thread.\nexport default class MemoryComponent<T extends ComponentTypedArray = ComponentTypedArray> {\n\theap: MemoryHeap;\n\tpool: SharedPool<T>;\n\n\tconstructor(heap: MemoryHeap, type: TypedArrayConstructor<T>, dataLength: number, memory?: SharedPoolMemory) {\n\t\tthis.heap = heap;\n\t\tthis.pool = memory\n\t\t\t? new SharedPool<T>(heap, memory)\n\t\t\t: new SharedPool<T>(heap, {\n\t\t\t\ttype,\n\t\t\t\tdataLength,\n\t\t\t});\n\t}\n\n\t// Reconstructs a handle over an existing pool (from the owner's getSharedMemory()) — used in a worker, where the\n\t// pool's type/dataLength are already recorded in the heap header, so no definition is needed.\n\tstatic fromSharedMemory<T extends ComponentTypedArray = ComponentTypedArray>(heap: MemoryHeap, memory: SharedPoolMemory): MemoryComponent<T> {\n\t\treturn new MemoryComponent<T>(heap, Uint32Array as unknown as TypedArrayConstructor<T>, 1, memory);\n\t}\n\n\tgetSharedMemory(): SharedPoolMemory {\n\t\treturn this.pool.getSharedMemory();\n\t}\n\n\tget length() {\n\t\treturn this.pool.length;\n\t}\n\tget rawLength() {\n\t\treturn this.pool.bufferLength;\n\t}\n\n\tcreate(values: Array<number>): number {\n\t\treturn this.pool.push(values);\n\t}\n\n\tgetBlock(index: number): T {\n\t\treturn this.pool.at(index);\n\t}\n\tget(index: number, dataIndex: number): number {\n\t\treturn this.pool.get(index, dataIndex);\n\t}\n\tset(index: number, dataIndex: number, value: number) {\n\t\tlet array = this.pool.at(index);\n\t\tarray[dataIndex] = value;\n\t}\n\n\tdelete(index: number) {\n\t\tthis.pool.deleteIndex(index);\n\t}\n\tclear() {\n\t\tthis.pool.clear();\n\t}\n}\n","import ConstantString from '@daneren2005/shared-memory-objects/constant-string';\nimport { getPointer } from '@daneren2005/shared-memory-objects/utils/pointer';\nimport type MemoryHeap from '@daneren2005/shared-memory-objects/memory-heap';\n\n// Interns immutable strings in the heap and resolves them back from a pointer. Every distinct value is allocated\n// once as a single ConstantString shared by all users (15 \"Space Ship\" entities point at one allocation), and a\n// pointer resolves to its string through a Map hit before ever rebuilding it from memory. Both sides of the\n// worker boundary hold one: the main thread creates + interns; a worker (with a heap reconstructed from the same\n// SharedArrayBuffers) only ever resolves pointers and caches the results.\nexport default class ConstantStringCache {\n\tprivate heap: MemoryHeap;\n\t// value -> the one interned allocation. Only the creating (main) thread populates this; it owns the memory.\n\tprivate byValue = new Map<string, ConstantString>();\n\t// pointer -> value: the fast lookup every thread checks before touching memory.\n\tprivate byPointer = new Map<number, string>();\n\n\tconstructor(heap: MemoryHeap) {\n\t\tthis.heap = heap;\n\t}\n\n\t// Dedupes on value, so repeated types share a single ConstantString. Main-thread only.\n\tgetOrCreate(value: string): ConstantString {\n\t\tlet existing = this.byValue.get(value);\n\t\tif(existing) {\n\t\t\treturn existing;\n\t\t}\n\n\t\tconst string = new ConstantString(this.heap, value);\n\t\tthis.byValue.set(value, string);\n\t\tthis.byPointer.set(string.pointer, value);\n\n\t\treturn string;\n\t}\n\n\t// pointer -> string, checking the cache before rebuilding from memory. A pointer of 0 is the empty string; a\n\t// pointer into a buffer that has not synced to this thread yet returns undefined.\n\tgetString(pointer: number): string | undefined {\n\t\tif(pointer === 0) {\n\t\t\treturn '';\n\t\t}\n\n\t\tlet cached = this.byPointer.get(pointer);\n\t\tif(cached !== undefined) {\n\t\t\treturn cached;\n\t\t}\n\n\t\tconst memory = getPointer(pointer);\n\t\tif(this.heap.buffers[memory.bufferPosition] === undefined) {\n\t\t\treturn undefined;\n\t\t}\n\n\t\tconst value = new ConstantString(this.heap, memory).value;\n\t\tthis.byPointer.set(pointer, value);\n\n\t\treturn value;\n\t}\n\n\t// Frees every allocation this cache owns and empties the lookups. A worker's cache owns nothing (it only ever\n\t// resolved views), so this just drops its pointer lookups.\n\tclear() {\n\t\tthis.byValue.forEach(string => string.free());\n\t\tthis.byValue.clear();\n\t\tthis.byPointer.clear();\n\t}\n}\n","import type { EntityUpdateComponents, QueryDelta, UpdateEntityConfigObject } from '../entity-worker-system';\n\n// Applies a run's delta to a query's persistent list: drop the entities that left, upsert those that joined or\n// changed. A steady-state run carries empty arrays and returns the list untouched. Returns the list (removals\n// rebuild it via filter), so callers must store the returned reference back.\nexport function applyQueryDelta<T extends EntityUpdateComponents>(\n\tlist: Array<UpdateEntityConfigObject<T>>,\n\tdelta: QueryDelta<T>,\n): Array<UpdateEntityConfigObject<T>> {\n\tif(delta.removed.length) {\n\t\tconst removedSet = new Set(delta.removed);\n\t\tlist = list.filter(entry => !removedSet.has(entry.entityId));\n\t}\n\n\tif(delta.added.length) {\n\t\t// Index existing members so a re-added entity replaces its entry in place instead of duplicating.\n\t\tconst indexByEid = new Map<number, number>();\n\t\tlist.forEach((entry, index) => indexByEid.set(entry.entityId, index));\n\n\t\tfor(let entity of delta.added) {\n\t\t\tconst existing = indexByEid.get(entity.entityId);\n\t\t\tif(existing !== undefined) {\n\t\t\t\tlist[existing] = entity;\n\t\t\t} else {\n\t\t\t\tindexByEid.set(entity.entityId, list.length);\n\t\t\t\tlist.push(entity);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn list;\n}\n","import type { WorkerAllocator, WorkerCreateEntityConfig, WorkerCreatedComponent, WorkerCreatedEntity } from '../systems/entity-worker-system';\nimport type { WorkerEntityClassRegistry } from '../entity-class';\n\n// The slice of a component definition worker-side creation needs. Both the game's ComponentDefinitionMap and the\n// world's RegisteredComponentRegistry satisfy it.\nexport interface WorkerCreatableComponent {\n\tloadProperties: Array<string>\n\tloadInFinishLoading?: boolean\n\ttoBlock(config: Record<string, unknown>): Array<number>\n}\nexport type WorkerCreateRegistry = { [name: string]: WorkerCreatableComponent };\nexport type FactoryConfigs = { [type: string]: Record<string, unknown> };\n\n// Turns a factory-style config ({ type, ...overrides }) into a WorkerCreatedEntity, off-thread: layers the type's\n// factory template under the overrides, mints an id, and allocates + writes each triggered component's block via its\n// toBlock(). The always-present `entity` component is NOT built here - the main thread builds it on adopt (interning\n// the type is main-thread-only), reading `type`/`isStatic` off this descriptor. Shared by the real worker and the\n// main-thread fallback so both behave identically.\nexport function buildWorkerEntity(\n\tconfig: WorkerCreateEntityConfig,\n\tfactoryConfigs: FactoryConfigs,\n\tregistry: WorkerCreateRegistry,\n\tallocator: WorkerAllocator,\n\tclasses?: WorkerEntityClassRegistry,\n): WorkerCreatedEntity {\n\tconst template = factoryConfigs[config.type] ?? {};\n\tif(classes && Object.prototype.hasOwnProperty.call(config, 'class')) {\n\t\tthrow new Error('Entity class comes from its type template and cannot be supplied by a worker config');\n\t}\n\tconst merged: Record<string, unknown> = { ...template, ...config };\n\tconst entityClass = typeof template.class === 'string' ? template.class : undefined;\n\tlet componentNames = Object.keys(registry);\n\tif(classes) {\n\t\tif(template.type !== config.type) {\n\t\t\tthrow new Error(`Entity template ${config.type} must declare the same type`);\n\t\t}\n\t\tconst definition = entityClass ? classes[entityClass] : undefined;\n\t\tif(!definition) {\n\t\t\tthrow new Error(`Entity type ${config.type} has unknown class ${entityClass ?? ''}`);\n\t\t}\n\t\tcomponentNames = definition.components;\n\t}\n\n\tconst eid = allocator.allocateEid();\n\tconst components: { [name: string]: number } = {};\n\tfor(let name of componentNames) {\n\t\t// The entity component is always built on the main thread when the descriptor is adopted (interning the type),\n\t\t// never off-thread - skip it here whether or not the registry includes it.\n\t\tif(name === 'entity') {\n\t\t\tcontinue;\n\t\t}\n\t\tconst definition = registry[name];\n\t\tif(!definition) {\n\t\t\tthrow new Error(`Entity class ${entityClass ?? ''} contains unknown component ${name}`);\n\t\t}\n\t\t// Deferred components need the whole world (other entities) that a worker doesn't have; skip them.\n\t\tif(definition.loadInFinishLoading) {\n\t\t\tcontinue;\n\t\t}\n\t\tif(definition.loadProperties.some(prop => prop in merged)) {\n\t\t\tcomponents[name] = allocator.allocateComponentBlock(name, definition.toBlock(merged));\n\t\t}\n\t}\n\n\treturn {\n\t\teid,\n\t\ttype: config.type,\n\t\tclass: entityClass,\n\t\tisStatic: merged.isStatic as boolean | undefined,\n\t\tcomponents,\n\t};\n}\n\nexport function buildWorkerComponent(\n\tname: string,\n\tconfig: Record<string, unknown>,\n\tregistry: WorkerCreateRegistry,\n\tallocator: WorkerAllocator,\n): WorkerCreatedComponent {\n\tif(name === 'entity') {\n\t\tthrow new Error('The entity component cannot be added at runtime');\n\t}\n\tconst definition = registry[name];\n\tif(!definition) {\n\t\tthrow new Error(`Unknown component: ${name}`);\n\t}\n\tif(definition.loadInFinishLoading) {\n\t\tthrow new Error(`Component ${name} requires main-thread finishLoading and cannot be added in a worker`);\n\t}\n\n\treturn {\n\t\tname,\n\t\tindex: allocator.allocateComponentBlock(name, definition.toBlock(config)),\n\t};\n}\n","import type { ComponentTypedArray } from './memory-component';\nimport type { BaseComponent } from './component-definition';\n\n// Base class for a memory-backed component accessor. Subclass it, declare prototype get/set accessors over\n// `this.block` indexed by the component's exported *_INDEX constants, and return `new YourComponent(block, index)`\n// from `attach`. Because the accessors live on one shared prototype - not fresh closures captured per entity -\n// reads off thousands of entities every frame stay monomorphic and inline, and constructing a component allocates\n// just the instance instead of a closure per accessor. Components that own no extra memory need nothing else; a\n// subclass that does can take more constructor args (the entity, another pool) and store them as fields.\nexport default abstract class Component<T extends ComponentTypedArray = ComponentTypedArray> implements BaseComponent {\n\treadonly index: number;\n\treadonly block: T;\n\n\tconstructor(block: T, index: number) {\n\t\tthis.block = block;\n\t\tthis.index = index;\n\t}\n}\n","import type { ComponentDefinition } from './component-definition';\nimport Component from './component';\nimport type ConstantStringCache from './constant-string-cache';\n\nexport interface EntityComponent {\n\tindex: number\n\treadonly type: string\n\treadonly class: string\n\tdead: boolean\n\tisStatic: boolean\n}\n\nexport interface EntityComponentConfig {\n\ttype: string\n\tisStatic?: boolean\n}\n\nexport interface EntityClassConfig {\n\treadonly class: string\n}\n\nexport interface EntityComponentSerialization {\n\ttype?: string\n\tdead?: boolean\n}\n\nexport const DEAD_INDEX = 0;\nexport const STATIC_INDEX = 1;\nexport const TYPE_INDEX = 2;\nexport const CLASS_INDEX = 3;\n\n// Identity strings are interned, so the accessor needs the world's cache to resolve their pointers.\nclass EntityComponentImpl extends Component<Uint32Array> implements EntityComponent {\n\tprivate cache: ConstantStringCache;\n\n\tconstructor(block: Uint32Array, index: number, cache: ConstantStringCache) {\n\t\tsuper(block, index);\n\t\tthis.cache = cache;\n\t}\n\n\tget type() {\n\t\treturn this.cache.getString(this.block[TYPE_INDEX]) ?? '';\n\t}\n\tget class() {\n\t\treturn this.cache.getString(this.block[CLASS_INDEX]) ?? '';\n\t}\n\tget dead() {\n\t\treturn this.block[DEAD_INDEX] === 1;\n\t}\n\tset dead(value: boolean) {\n\t\tthis.block[DEAD_INDEX] = value ? 1 : 0;\n\t}\n\tget isStatic() {\n\t\treturn this.block[STATIC_INDEX] === 1;\n\t}\n\tset isStatic(value: boolean) {\n\t\tthis.block[STATIC_INDEX] = value ? 1 : 0;\n\t}\n}\n\nexport const entityDefinition: ComponentDefinition<EntityComponent, Uint32Array, EntityComponentConfig & Partial<EntityClassConfig>, EntityComponentSerialization> = {\n\ttype: Uint32Array,\n\tsize: 4,\n\tloadProperties: ['type', 'isStatic'],\n\t// The only component that reads the entity (never worker-created): it interns its identity strings through the heap and\n\t// stores the pointer. `entity` is always passed here since loadComponent runs on the main thread.\n\ttoBlock(config, entity) {\n\t\tconst cache = entity!.world.constantStrings;\n\t\tconst typePointer = config.type ? cache.getOrCreate(config.type).pointer : 0;\n\t\tconst classPointer = config.class ? cache.getOrCreate(config.class).pointer : 0;\n\t\treturn [config.dead ? 1 : 0, config.isStatic ? 1 : 0, typePointer, classPointer];\n\t},\n\tattach(entity, memory, index) {\n\t\treturn new EntityComponentImpl(memory.getBlock(index), index, entity.world.constantStrings);\n\t},\n\tsave(component) {\n\t\tconst config: EntityComponentSerialization = {};\n\t\tif(component.type) {\n\t\t\tconfig.type = component.type;\n\t\t}\n\t\tif(component.dead) {\n\t\t\tconfig.dead = true;\n\t\t}\n\n\t\treturn config;\n\t},\n};\n","import type { ComponentTypedArray } from '../memory-component';\nimport type { EntityWorkerSystemCallbacks, EntityUpdateComponents } from '../systems/entity-worker-system';\nimport { DEAD_INDEX } from '../entity-component';\n\n// Worker-side killEntity: flags the entity dead in its block and reports the death back via callbacks. The\n// entity component must be in the system's query for its block to be available here.\nexport default function killEntityWorker(entityId: number, components: EntityUpdateComponents, callbacks: EntityWorkerSystemCallbacks): void {\n\tconst block = (components as { entity?: ComponentTypedArray }).entity;\n\tif(block) {\n\t\tblock[DEAD_INDEX] = 1;\n\t}\n\n\tcallbacks.entityDied(entityId);\n}\n","import type { EntityWorkerSystemCallbacks, EntityWorkerSystemWorld, WorkerCreateEntityConfig } from '../systems/entity-worker-system';\n\n// Worker-side entity creation from a factory config. The worker merges the selected type template, resolves its\n// optional class, mints a unique id, and allocates + writes every allowed, triggered component block\n// directly into the shared pools (off-thread) via each component's toBlock(). It reports the descriptor back; the main\n// thread adopts it on run-complete (world.adoptEntity), building the `entity` component and class wrapper there\n// worker-written blocks, so the entity first exists on the following frame.\n//\n// Requires the system to be registered with `createsEntities: true` and its worker entry to pass the component\n// registry to createEntitySystemWorker (so the worker has each component's toBlock).\nexport default function createEntityWorker(world: EntityWorkerSystemWorld, config: WorkerCreateEntityConfig, callbacks: EntityWorkerSystemCallbacks): void {\n\tif(!world.buildEntityDescriptor) {\n\t\tthrow new Error('createEntityWorker requires the system to be registered with createsEntities: true and the component registry passed to createEntitySystemWorker');\n\t}\n\n\tcallbacks.createEntity(world.buildEntityDescriptor(config));\n}\n","import type { ComponentMap } from '../component-definition';\nimport type { EntityWorkerSystemCallbacks, EntityWorkerSystemWorld } from '../systems/entity-worker-system';\n\n// Allocates a component block in the worker and asks the main thread to attach it after the run. The entity's\n// current query snapshot is intentionally unchanged until the next run.\nexport default function addComponentWorker<C extends ComponentMap, K extends keyof C>(\n\tworld: EntityWorkerSystemWorld,\n\tentityId: number,\n\tcomponentName: K,\n\tconfig: Record<string, unknown>,\n\tcallbacks: EntityWorkerSystemCallbacks<C>,\n): void {\n\tif(!world.buildComponentDescriptor) {\n\t\tthrow new Error('addComponentWorker requires addsComponents: true and the component registry passed to createEntitySystemWorker');\n\t}\n\n\tcallbacks.addComponent(entityId, world.buildComponentDescriptor(String(componentName), config));\n}\n","import type { ComponentMap } from '../component-definition';\nimport type { EntityWorkerSystemCallbacks } from '../systems/entity-worker-system';\n\n// Requests a main-thread detach after the worker run. Shared memory is freed only after every system that could\n// still hold the old block has completed a run.\nexport default function removeComponentWorker<C extends ComponentMap, K extends keyof C>(\n\tentityId: number,\n\tcomponentName: K,\n\tcallbacks: EntityWorkerSystemCallbacks<C>,\n): void {\n\tcallbacks.removeComponent(entityId, componentName);\n}\n","import MemoryHeap from '@daneren2005/shared-memory-objects/memory-heap';\nimport type AllocatedMemory from '@daneren2005/shared-memory-objects/allocated-memory';\nimport type EntitySystemWorkerMessage from './entity-system-worker-message';\nimport type { EntityEvent, SystemEvents, WorkerRunError } from './entity-system-worker-message';\nimport ConstantStringCache from '../../constant-string-cache';\nimport MemoryComponent from '../../memory-component';\nimport type { ComponentDefinitionMap, ComponentMap } from '../../component-definition';\nimport type {\n\tEntityWorkerSystemCallbacks, EntityWorkerSystemWorld, EntityQueryComponents, EntityUpdateComponents,\n\tEntityUpdateFunction, QueryDelta, UpdateEntityConfigObject, WorkerComponentChange, WorkerCreatedEntity,\n} from '../entity-worker-system';\nimport { buildWorkerComponent, buildWorkerEntity, type FactoryConfigs } from '../../actions/build-worker-entity';\nimport type { WorkerEntityClassRegistry } from '../../entity-class';\nimport { applyQueryDelta } from './apply-query-delta';\n\n// The slice of the worker global scope createEntitySystemWorker touches. Passing `self` explicitly (rather than\n// using the global) lets runners like @vitest/web-worker, which inject `self` as a module local, drive it.\nexport interface EntitySystemWorkerScope {\n\tonmessage: ((e: MessageEvent) => void) | null\n\tpostMessage(message: EntitySystemWorkerMessage): void\n}\n\nexport default function createEntitySystemWorker<\n\tC extends ComponentMap,\n\tT extends EntityUpdateComponents<C>,\n\tW extends EntityWorkerSystemWorld = EntityWorkerSystemWorld,\n\tD = unknown,\n>(scope: EntitySystemWorkerScope, updateFunction: EntityUpdateFunction<C, T, W, D>, definitions?: ComponentDefinitionMap) {\n\t// Persistent lists, carried across runs and mutated by each run's delta (see applyQueryDelta).\n\tlet entities: Array<UpdateEntityConfigObject<T>> = [];\n\tconst queryEntities: { [key: string]: Array<UpdateEntityConfigObject<T>> } = {};\n\t// What updateFunction.init returned: persistent state (e.g. a seeded RNG) merged onto `world` each run.\n\tlet worldExtension: Partial<W> | undefined;\n\tlet heap: MemoryHeap | undefined;\n\tlet stringCache: ConstantStringCache | undefined;\n\t// Reconstructed pool handles over the world's shared state, plus the factory templates - for off-thread entity\n\t// allocation. `definitions` (passed by the game's worker entry) supplies each component's toBlock/loadProperties.\n\tlet pools: { [name: string]: MemoryComponent } = {};\n\tlet eidCounter: AllocatedMemory | undefined;\n\tlet factoryConfigs: FactoryConfigs | undefined;\n\tlet factoryClasses: WorkerEntityClassRegistry | undefined;\n\tlet addsComponents = false;\n\tconst getString = (pointer: number): string => stringCache?.getString(pointer) ?? '';\n\n\tscope.onmessage = function(e) {\n\t\tconst message = e.data as EntitySystemWorkerMessage<W, D>;\n\n\t\tif(message.type === 'init') {\n\t\t\tpostMessageTyped(scope, {\n\t\t\t\ttype: 'init-complete',\n\t\t\t});\n\t\t} else if(message.type === 'load') {\n\t\t\tif(message.heap) {\n\t\t\t\theap = new MemoryHeap(message.heap);\n\t\t\t\tstringCache = new ConstantStringCache(heap);\n\t\t\t\t// Report any buffer this worker grows (while allocating off-thread) back to the main thread, which adopts\n\t\t\t\t// it and fans it out to sibling workers.\n\t\t\t\theap.addOnGrowBufferHandlers(buffer => postMessageTyped(scope, { type: 'grow-buffer-from-worker', buffer }));\n\t\t\t}\n\t\t\tif(heap && message.sharedMemory) {\n\t\t\t\tpools = {};\n\t\t\t\tfor(const name of Object.keys(message.sharedMemory.components)) {\n\t\t\t\t\tpools[name] = MemoryComponent.fromSharedMemory(heap, message.sharedMemory.components[name]);\n\t\t\t\t}\n\t\t\t\teidCounter = heap.getSharedAlloc(message.sharedMemory.eidCounter);\n\t\t\t}\n\t\t\tfactoryConfigs = message.factoryConfigs;\n\t\t\tfactoryClasses = message.factoryClasses;\n\t\t\taddsComponents = !!message.addsComponents;\n\t\t\tworldExtension = updateFunction.init?.(message.data) ?? undefined;\n\t\t\tpostMessageTyped(scope, {\n\t\t\t\ttype: 'loaded',\n\t\t\t});\n\t\t} else if(message.type === 'grow-buffer') {\n\t\t\t// Never replace a buffer this worker already holds: the main thread fans a worker-grown buffer back out to\n\t\t\t// every worker (including the one that grew it), and overwriting our own live MemoryBuffer would discard its\n\t\t\t// allocation bookkeeping. The SharedArrayBuffer at that position is already the same one.\n\t\t\tif(heap && heap.buffers[message.buffer.bufferPosition] === undefined) {\n\t\t\t\theap.addSharedBuffer(message.buffer);\n\t\t\t}\n\t\t} else if(message.type === 'reset') {\n\t\t\t// Drop the persistent lists so a reused world starts empty; worldExtension is refreshed by the next load.\n\t\t\tentities = [];\n\t\t\tfor(const key of Object.keys(queryEntities)) {\n\t\t\t\tdelete queryEntities[key];\n\t\t\t}\n\t\t\tworldExtension = undefined;\n\t\t} else if(message.type === 'run') {\n\t\t\tif(worldExtension) {\n\t\t\t\tObject.assign(message.world, worldExtension);\n\t\t\t}\n\t\t\tmessage.world.getString = getString;\n\t\t\tmessage.world.heap = heap;\n\t\t\tconst allocator = {\n\t\t\t\tallocateEid: () => eidCounter ? Atomics.add(eidCounter.data, 0, 1) + 1 : 0,\n\t\t\t\tallocateComponentBlock: (name: string, values: Array<number>) => pools[name].create(values),\n\t\t\t};\n\t\t\tmessage.world.allocate = allocator;\n\t\t\t// Only a system registered with createsEntities (factoryConfigs shipped) whose worker entry passed the\n\t\t\t// component definitions can create entities from a config.\n\t\t\tif(factoryConfigs && definitions) {\n\t\t\t\tmessage.world.buildEntityDescriptor = config => buildWorkerEntity(config, factoryConfigs!, definitions, allocator, factoryClasses);\n\t\t\t}\n\t\t\tif(addsComponents && definitions) {\n\t\t\t\tmessage.world.buildComponentDescriptor = (name, config) => buildWorkerComponent(name, config, definitions, allocator);\n\t\t\t}\n\t\t\tconst start = performance.now();\n\t\t\tlet entityEvents: Array<EntityEvent> = [];\n\t\t\tlet systemEvents: SystemEvents = {};\n\t\t\tlet createdEntities: Array<WorkerCreatedEntity> = [];\n\t\t\tlet componentChanges: Array<WorkerComponentChange> = [];\n\t\t\tlet errors: Array<WorkerRunError> = [];\n\n\t\t\tentities = applyQueryDelta(entities, message.entities as QueryDelta<T>);\n\n\t\t\tlet queries: EntityQueryComponents<C> = {};\n\t\t\tObject.entries(message.queries).forEach(([queryKey, delta]) => {\n\t\t\t\tconst list = applyQueryDelta(queryEntities[queryKey] ?? [], delta as QueryDelta<T>);\n\t\t\t\tqueryEntities[queryKey] = list;\n\t\t\t\tqueries[queryKey] = list;\n\t\t\t});\n\n\t\t\tlet callbacks: EntityWorkerSystemCallbacks<C> = {\n\t\t\t\tentityComponentChanged<K extends keyof C, P extends keyof C[K]>(entityId: number, componentName: K, prop: P, value: C[K][P]) {\n\t\t\t\t\tentityEvents.push({\n\t\t\t\t\t\tentityId,\n\t\t\t\t\t\tevent: 'component-property-updated',\n\t\t\t\t\t\targs: [componentName, prop, value],\n\t\t\t\t\t});\n\t\t\t\t},\n\t\t\t\temitEntityEvent(entityId: number, event: string, ...args: Array<unknown>) {\n\t\t\t\t\tentityEvents.push({\n\t\t\t\t\t\tentityId,\n\t\t\t\t\t\tevent,\n\t\t\t\t\t\targs,\n\t\t\t\t\t});\n\t\t\t\t},\n\t\t\t\temitSystemEvent(event: string, entityId: number) {\n\t\t\t\t\t(systemEvents[event] ?? (systemEvents[event] = [])).push(entityId);\n\t\t\t\t},\n\t\t\t\tentityDied(entityId: number) {\n\t\t\t\t\tentityEvents.push({\n\t\t\t\t\t\tentityId,\n\t\t\t\t\t\tevent: 'death',\n\t\t\t\t\t\targs: [],\n\t\t\t\t\t});\n\t\t\t\t},\n\t\t\t\tcreateEntity(entity: WorkerCreatedEntity) {\n\t\t\t\t\tcreatedEntities.push(entity);\n\t\t\t\t},\n\t\t\t\taddComponent(entityId, component) {\n\t\t\t\t\tcomponentChanges.push({ type: 'add', entityId, component });\n\t\t\t\t},\n\t\t\t\tremoveComponent(entityId, componentName) {\n\t\t\t\t\tcomponentChanges.push({ type: 'remove', entityId, componentName: String(componentName) });\n\t\t\t\t},\n\t\t\t};\n\t\t\tlet preRunFailed = false;\n\t\t\tif(updateFunction.preRun) {\n\t\t\t\ttry {\n\t\t\t\t\tupdateFunction.preRun(message.world, entities, queries, callbacks);\n\t\t\t\t} catch(err) {\n\t\t\t\t\tpreRunFailed = true;\n\t\t\t\t\terrors.push({ error: err as Error, phase: 'preRun' });\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// preRun sets up the run's state; if it threw, skip the entity loop rather than run over half-prepared data.\n\t\t\tif(!preRunFailed) {\n\t\t\t\tentities.forEach(entity => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tupdateFunction(message.world, entity.entityId, entity.components, queries, callbacks);\n\t\t\t\t\t} catch(err) {\n\t\t\t\t\t\t// One entity failing must not stop the rest of the run.\n\t\t\t\t\t\terrors.push({ error: err as Error, phase: 'update', entityId: entity.entityId });\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tif(updateFunction.entityRemoved) {\n\t\t\t\tmessage.entities.removed.forEach(entityId => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tupdateFunction.entityRemoved!(message.world, entityId, callbacks);\n\t\t\t\t\t} catch(err) {\n\t\t\t\t\t\terrors.push({ error: err as Error, phase: 'entityRemoved', entityId });\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\t\t\tconst runTime = performance.now() - start;\n\n\t\t\tpostMessageTyped(scope, {\n\t\t\t\ttype: 'run-complete',\n\t\t\t\tgeneration: message.generation,\n\t\t\t\trunTime,\n\t\t\t\tevents: entityEvents,\n\t\t\t\tsystemEvents,\n\t\t\t\tcreated: createdEntities,\n\t\t\t\tcomponentChanges,\n\t\t\t\terrors,\n\t\t\t});\n\t\t}\n\t};\n}\n\nfunction postMessageTyped(scope: EntitySystemWorkerScope, message: EntitySystemWorkerMessage) {\n\tscope.postMessage(message);\n}\n","import createEntitySystemWorker, { type EntitySystemWorkerScope } from './create-entity-system-worker';\nimport type { ComponentDefinitionMap, ComponentMap } from '../../component-definition';\nimport type {\n\tEntityWorkerSystemCallbacks, EntityWorkerSystemWorld, EntityQueryComponents, EntityUpdateComponents,\n\tEntityUpdateFunction, EntityUpdateInitFunction, EntityRemovedFunction,\n} from '../entity-worker-system';\n\n// A WorkerSystem's single per-run function: called once per run over the named sub-queries, not once per entity.\n// Optional `init`/`entityRemoved` mirror EntityUpdateFunction's hooks.\nexport type WorkerSystemRunFunction<\n\tC extends ComponentMap,\n\tW extends EntityWorkerSystemWorld = EntityWorkerSystemWorld,\n\tD = unknown,\n> = ((world: W, queries: EntityQueryComponents<C>, callbacks: EntityWorkerSystemCallbacks<C>) => void) & {\n\tinit?: EntityUpdateInitFunction<W, D>\n\tentityRemoved?: EntityRemovedFunction<C, W>\n};\n\n// A WorkerSystem reuses the EntityWorkerSystem worker machinery: the single run function becomes `preRun` (which runs\n// once with query access) and the per-entity body is a no-op, since a WorkerSystem never populates its main query.\nexport function toEntityUpdateFunction<\n\tC extends ComponentMap,\n\tW extends EntityWorkerSystemWorld = EntityWorkerSystemWorld,\n\tD = unknown,\n>(run: WorkerSystemRunFunction<C, W, D>): EntityUpdateFunction<C, EntityUpdateComponents<C>, W, D> {\n\tconst updateFunction = (() => {}) as EntityUpdateFunction<C, EntityUpdateComponents<C>, W, D>;\n\tupdateFunction.preRun = (world, _entities, queries, callbacks) => run(world, queries, callbacks);\n\tif(run.init) {\n\t\tupdateFunction.init = run.init;\n\t}\n\tif(run.entityRemoved) {\n\t\tupdateFunction.entityRemoved = run.entityRemoved;\n\t}\n\n\treturn updateFunction;\n}\n\n// Worker entry helper for a WorkerSystem (mirrors createEntitySystemWorker). Pass the component registry only for a\n// worker that creates entities.\nexport default function createSystemWorker<\n\tC extends ComponentMap,\n\tW extends EntityWorkerSystemWorld = EntityWorkerSystemWorld,\n\tD = unknown,\n>(scope: EntitySystemWorkerScope, runFunction: WorkerSystemRunFunction<C, W, D>, definitions?: ComponentD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;IACtE;GACD,CAAC;GAEF,IAAM,IAAU,YAAY,IAAI,IAAI;GAEpC,EAAiB,GAAO;IACvB,MAAM;IACN,YAAY,EAAQ;IACpB;IACA,QAAQ;IACR;IACA,SAAS;IACT;IACA;GACD,CAAC;EACF;CACD;AACD;AAEA,SAAS,EAAiB,GAAgC,GAAoC;CAC7F,EAAM,YAAY,CAAO;AAC1B;;;AC1LA,SAAgB,EAId,GAAiG;CAClG,IAAM,WAAwB,CAAC;CAS/B,OARA,EAAe,UAAU,GAAO,GAAW,GAAS,MAAc,EAAI,GAAO,GAAS,CAAS,GAC5F,EAAI,SACN,EAAe,OAAO,EAAI,OAExB,EAAI,kBACN,EAAe,gBAAgB,EAAI,gBAG7B;AACR;AAIA,SAAwB,EAItB,GAAgC,GAA+C,GAAsC;CACtH,EAAyB,GAAO,EAAuB,CAAW,GAAG,CAAW;AACjF"}
@@ -0,0 +1,51 @@
1
+ import type { ComponentDefinitionMap, EntityConfigOf } from './component-definition';
2
+ export type EntityClassConstructor = abstract new (...args: never[]) => {
3
+ readonly eid: number;
4
+ };
5
+ export interface EntityClassDefinition {
6
+ entity: EntityClassConstructor;
7
+ components: ReadonlyArray<string>;
8
+ }
9
+ export type EntityClassRegistry = Record<string, EntityClassDefinition>;
10
+ declare const ENTITY_CLASSES_TYPE: unique symbol;
11
+ export type DefinedEntityClasses<R extends ComponentDefinitionMap, Classes extends EntityClassRegistry> = Classes & {
12
+ readonly [ENTITY_CLASSES_TYPE]: R;
13
+ };
14
+ export type EntityInstancesOf<Classes extends EntityClassRegistry> = InstanceType<Classes[keyof Classes & string]['entity']>;
15
+ type RegistryOf<Classes extends EntityClassRegistry> = Classes extends DefinedEntityClasses<infer R, EntityClassRegistry> ? R : never;
16
+ type ComponentKeysOf<Definition> = Definition extends {
17
+ components: ReadonlyArray<infer K>;
18
+ } ? K : never;
19
+ export type EntityClassTemplateConfig<Classes extends EntityClassRegistry, ClassName extends keyof Classes & string, R extends ComponentDefinitionMap = RegistryOf<Classes>> = EntityConfigOf<Pick<R, Extract<ComponentKeysOf<Classes[ClassName]>, keyof R>>> & {
20
+ type: string;
21
+ class: ClassName;
22
+ };
23
+ export type EntityTemplateConfigOf<Classes extends EntityClassRegistry> = {
24
+ [ClassName in keyof Classes & string]: EntityClassTemplateConfig<Classes, ClassName>;
25
+ }[keyof Classes & string];
26
+ export type EntityInstanceConfigOf<Classes extends EntityClassRegistry> = EntityTemplateConfigOf<Classes> extends infer Config ? Config extends object ? Omit<Config, 'class'> & {
27
+ class?: never;
28
+ } : never : never;
29
+ type EntityClassInput<R extends ComponentDefinitionMap> = Record<string, {
30
+ entity: EntityClassConstructor;
31
+ components: ReadonlyArray<keyof R & string>;
32
+ }>;
33
+ type ExactEntityConfig<Classes extends EntityClassRegistry, ClassName extends keyof Classes & string, Type, Config> = Config & EntityClassTemplateConfig<Classes, ClassName> & {
34
+ type: Type;
35
+ } & Record<Exclude<keyof Config, keyof EntityClassTemplateConfig<Classes, ClassName>>, never>;
36
+ type CheckedEntityConfig<Classes extends EntityClassRegistry, Type, Config> = Config extends {
37
+ class: infer ClassName;
38
+ } ? ClassName extends keyof Classes & string ? ExactEntityConfig<Classes, ClassName, Type, Config> : never : never;
39
+ type CheckedEntityConfigs<Classes extends EntityClassRegistry, Configs> = {
40
+ [K in keyof Configs]: CheckedEntityConfig<Classes, K, Configs[K]>;
41
+ };
42
+ export declare function defineEntityClasses<R extends ComponentDefinitionMap, const Classes extends EntityClassInput<R>>(_registry: R, classes: Classes): DefinedEntityClasses<R, Classes>;
43
+ export declare function defineEntityConfigs<Classes extends EntityClassRegistry, const Configs extends Record<string, {
44
+ type: string;
45
+ class: keyof Classes & string;
46
+ }>>(_classes: Classes, configs: Configs & CheckedEntityConfigs<Classes, Configs>): Configs;
47
+ export interface WorkerEntityClassDefinition {
48
+ components: Array<string>;
49
+ }
50
+ export type WorkerEntityClassRegistry = Record<string, WorkerEntityClassDefinition>;
51
+ export {};
@@ -1,7 +1,8 @@
1
1
  import type { ComponentDefinition } from './component-definition';
2
2
  export interface EntityComponent {
3
3
  index: number;
4
- type: string;
4
+ readonly type: string;
5
+ readonly class: string;
5
6
  dead: boolean;
6
7
  isStatic: boolean;
7
8
  }
@@ -9,6 +10,9 @@ export interface EntityComponentConfig {
9
10
  type: string;
10
11
  isStatic?: boolean;
11
12
  }
13
+ export interface EntityClassConfig {
14
+ readonly class: string;
15
+ }
12
16
  export interface EntityComponentSerialization {
13
17
  type?: string;
14
18
  dead?: boolean;
@@ -16,4 +20,5 @@ export interface EntityComponentSerialization {
16
20
  export declare const DEAD_INDEX = 0;
17
21
  export declare const STATIC_INDEX = 1;
18
22
  export declare const TYPE_INDEX = 2;
19
- export declare const entityDefinition: ComponentDefinition<EntityComponent, Uint32Array, EntityComponentConfig, EntityComponentSerialization>;
23
+ export declare const CLASS_INDEX = 3;
24
+ export declare const entityDefinition: ComponentDefinition<EntityComponent, Uint32Array, EntityComponentConfig & Partial<EntityClassConfig>, EntityComponentSerialization>;
@@ -1,16 +1,32 @@
1
1
  import BaseEntity from './entity';
2
2
  import type BaseWorld from './world';
3
3
  import type { ComponentDefinitionMap, ComponentMap } from './component-definition';
4
- export default class EntityFactory<C extends ComponentMap = ComponentMap, Cfg = any> {
5
- world: BaseWorld<ComponentDefinitionMap, C, Cfg>;
4
+ import type { EntityClassRegistry, WorkerEntityClassRegistry } from './entity-class';
5
+ export default class EntityFactory<C extends ComponentMap = ComponentMap, Cfg = any, E extends BaseEntity<C, Cfg> = BaseEntity<C, Cfg>> {
6
+ world: BaseWorld<ComponentDefinitionMap, C, Cfg, E>;
6
7
  configs: {
7
8
  [type: string]: Cfg;
8
9
  };
10
+ classes: EntityClassRegistry;
11
+ private allowedComponents;
9
12
  constructor(configs?: {
10
13
  [type: string]: Cfg;
11
- });
14
+ }, classes?: EntityClassRegistry);
12
15
  register(type: string, config: Cfg): void;
16
+ setWorld(world: BaseWorld<ComponentDefinitionMap, C, Cfg, E>): void;
13
17
  getConfig(config: Cfg): Cfg;
14
- loadEntity(config: Cfg, created?: boolean): BaseEntity<C, Cfg>;
15
- protected createEntity(config: Cfg): BaseEntity<C, Cfg>;
18
+ loadEntity(config: Cfg, created?: boolean): E;
19
+ createAdoptedEntity(type: string, entityClass: string | undefined, eid: number): E;
20
+ isComponentAllowed(entityClass: string | undefined, component: string): boolean;
21
+ getWorkerClasses(): WorkerEntityClassRegistry | undefined;
22
+ getAllowedComponentsForConfig(config: Cfg | undefined): ReadonlySet<string> | undefined;
23
+ protected createEntity(config: Cfg): E;
24
+ private get hasClasses();
25
+ private getClassDefinition;
26
+ private getAllowedComponents;
27
+ private constructEntity;
28
+ private validateTemplate;
29
+ private validateResolvedConfig;
30
+ private validateTypeClass;
31
+ private validateComponentTriggers;
16
32
  }
package/dist/entity.d.ts CHANGED
@@ -6,12 +6,17 @@ export default class BaseEntity<C extends ComponentMap = ComponentMap, Cfg = any
6
6
  readonly eid: number;
7
7
  config?: Cfg;
8
8
  world: BaseWorld<ComponentDefinitionMap, C, Cfg>;
9
+ private componentMemoryDeletionScheduled;
10
+ private allowedComponents?;
9
11
  components: Partial<C> & {
10
12
  entity: EntityComponent;
11
13
  };
12
- constructor(world: BaseWorld<ComponentDefinitionMap, C, Cfg>, config?: Cfg, adoptEid?: number);
14
+ constructor(world: BaseWorld<ComponentDefinitionMap, C, Cfg>, config?: Cfg, adoptEid?: number, allowedComponents?: ReadonlySet<string>);
15
+ get id(): number;
16
+ get dead(): boolean;
17
+ get type(): string;
13
18
  loadComponent<K extends keyof C>(name: K, config: any, emitAdded?: boolean): C[K];
14
- attachComponent<K extends keyof C>(name: K, index: number): C[K];
19
+ attachComponent<K extends keyof C>(name: K, index: number, emitAdded?: boolean): C[K];
15
20
  removeComponent<K extends keyof C>(name: K): void;
16
21
  setComponent<K extends keyof C, P extends keyof C[K]>(componentName: K, prop: P, value: C[K][P]): void;
17
22
  /**
@@ -23,4 +28,8 @@ export default class BaseEntity<C extends ComponentMap = ComponentMap, Cfg = any
23
28
  load(config: Cfg): void;
24
29
  save(): Cfg;
25
30
  finishLoading(): void;
31
+ private isComponentAllowed;
32
+ setAllowedComponents(allowedComponents: ReadonlySet<string> | undefined): void;
33
+ private assertComponentAllowed;
34
+ private assertComponentPropertyMutable;
26
35
  }
package/dist/index.d.ts CHANGED
@@ -2,12 +2,16 @@ export { default as BaseWorld } from './world';
2
2
  export type { WorldOptions, WorldConfig } from './world';
3
3
  export { default as BaseEntity } from './entity';
4
4
  export { default as EntityFactory } from './entity-factory';
5
- export { entityDefinition, DEAD_INDEX, STATIC_INDEX, TYPE_INDEX } from './entity-component';
5
+ export { defineEntityClasses, defineEntityConfigs } from './entity-class';
6
+ export type { DefinedEntityClasses, EntityClassConstructor, EntityClassDefinition, EntityClassRegistry, EntityClassTemplateConfig, EntityInstanceConfigOf, EntityInstancesOf, EntityTemplateConfigOf, } from './entity-class';
7
+ export { entityDefinition, CLASS_INDEX, DEAD_INDEX, STATIC_INDEX, TYPE_INDEX } from './entity-component';
6
8
  export { default as ConstantStringCache } from './constant-string-cache';
7
- export type { EntityComponent, EntityComponentConfig, EntityComponentSerialization, } from './entity-component';
9
+ export type { EntityComponent, EntityClassConfig, EntityComponentConfig, EntityComponentSerialization, } from './entity-component';
8
10
  export { default as killEntity } from './actions/kill-entity';
9
11
  export { default as killEntityWorker } from './actions/kill-entity-worker';
10
12
  export { default as createEntityWorker } from './actions/create-entity-worker';
13
+ export { default as addComponentWorker } from './actions/add-component-worker';
14
+ export { default as removeComponentWorker } from './actions/remove-component-worker';
11
15
  export { default as PerformanceTiming, DEFAULT_TICKS_BETWEEN_UPDATES } from './performance-timing';
12
16
  export type { TimingStats, SystemTimingStats, PerformanceStats, PerformanceTimingOptions, } from './performance-timing';
13
17
  export { default as MemoryComponent } from './memory-component';
@@ -20,10 +24,13 @@ export { default as IterableSystem } from './systems/iterable-system';
20
24
  export type { IterableSystemConfig } from './systems/iterable-system';
21
25
  export { default as EntitySystem } from './systems/entity-system';
22
26
  export type { EntitySystemConfig } from './systems/entity-system';
23
- export { default as ComponentSystem } from './systems/component-system';
24
- export type { ComponentSystemConfig, ComponentSystemQuery, ComponentSystemWorld, ComponentSystemCallbacks, WorkerAllocator, WorkerCreateEntityConfig, WorkerCreatedEntity, EntityUpdateComponents, EntityQueryComponents, EntityUpdateFunction, EntityUpdateInitFunction, EntityUpdatePreRunFunction, EntityRemovedFunction, UpdateEntityConfig, UpdateEntityConfigObject, } from './systems/component-system';
27
+ export { default as EntityWorkerSystem } from './systems/entity-worker-system';
28
+ export { default as WorkerSystem } from './systems/worker-system';
29
+ export type { WorkerSystemConfig, WorkerSystemRunFunction } from './systems/worker-system';
30
+ export type { EntityWorkerSystemConfig, EntityWorkerSystemQuery, EntityWorkerSystemWorld, EntityWorkerSystemCallbacks, WorkerAllocator, WorkerCreateEntityConfig, WorkerCreatedEntity, WorkerCreatedComponent, WorkerComponentChange, EntityUpdateComponents, EntityQueryComponents, EntityUpdateFunction, EntityUpdateInitFunction, EntityUpdatePreRunFunction, EntityRemovedFunction, UpdateEntityConfig, UpdateEntityConfigObject, } from './systems/entity-worker-system';
25
31
  export { default as WebWorker } from './systems/workers/web-worker';
26
- export { default as ComponentWebWorker } from './systems/workers/component-web-worker';
27
- export { default as createComponentWorker } from './systems/workers/create-component-worker';
28
- export type { default as ComponentWorkerMessage } from './systems/workers/component-worker-message';
29
- export type { EntityEvent, SystemEvents } from './systems/workers/component-worker-message';
32
+ export { default as EntitySystemWebWorker } from './systems/workers/entity-system-web-worker';
33
+ export { default as createEntitySystemWorker } from './systems/workers/create-entity-system-worker';
34
+ export { default as createSystemWorker } from './systems/workers/create-system-worker';
35
+ export type { default as EntitySystemWorkerMessage } from './systems/workers/entity-system-worker-message';
36
+ export type { EntityEvent, SystemEvents } from './systems/workers/entity-system-worker-message';