@margoengine/ecs 0.0.0-stage → 1.0.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 +201 -0
- package/NOTICE +4 -0
- package/README.md +486 -2
- package/dist/changes.d.ts +39 -0
- package/dist/changes.js +63 -0
- package/dist/coroutines.d.ts +82 -0
- package/dist/coroutines.js +97 -0
- package/dist/engine.d.ts +80 -0
- package/dist/engine.js +164 -0
- package/dist/growable.d.ts +23 -0
- package/dist/growable.js +28 -0
- package/dist/index.d.ts +145 -0
- package/dist/index.js +166 -0
- package/dist/objects.d.ts +43 -0
- package/dist/objects.js +78 -0
- package/dist/parallel-runtime.d.ts +43 -0
- package/dist/parallel.d.ts +102 -0
- package/dist/parallel.js +280 -0
- package/dist/parallel.worker.d.ts +1 -0
- package/dist/query.d.ts +42 -0
- package/dist/query.js +61 -0
- package/dist/reactive.d.ts +59 -0
- package/dist/reactive.js +106 -0
- package/dist/relation-query.d.ts +77 -0
- package/dist/relation-query.js +123 -0
- package/dist/relations.d.ts +72 -0
- package/dist/relations.js +99 -0
- package/dist/schedule.d.ts +82 -0
- package/dist/schedule.js +109 -0
- package/dist/scripts.d.ts +182 -0
- package/dist/scripts.js +278 -0
- package/dist/serialize-codec.d.ts +34 -0
- package/dist/serialize.d.ts +34 -0
- package/dist/serialize.js +355 -0
- package/dist/workers/parallel.js +1 -0
- package/package.json +105 -4
package/dist/parallel.js
ADDED
|
@@ -0,0 +1,280 @@
|
|
|
1
|
+
import { Component as e, World as t } from "./index.js";
|
|
2
|
+
import { MargoError as n } from "@margoengine/math/errors";
|
|
3
|
+
//#region src/parallel-runtime.ts
|
|
4
|
+
function r(e, t) {
|
|
5
|
+
if (!Number.isInteger(t) || t < 0 || t > 4294967295) return -1;
|
|
6
|
+
let n = e.rows[t % e.stride];
|
|
7
|
+
return n >= 0 && n < e.count && e.entities[n] === t ? n : -1;
|
|
8
|
+
}
|
|
9
|
+
function i(e) {
|
|
10
|
+
let t = !1, n = !1, r = (r) => {
|
|
11
|
+
let i = r.data;
|
|
12
|
+
if (!i || i.tag !== "margo-ecs-parallel" || !Number.isSafeInteger(i.id)) return;
|
|
13
|
+
let a = (t, r) => {
|
|
14
|
+
n || e.postMessage({
|
|
15
|
+
tag: i.tag,
|
|
16
|
+
id: i.id,
|
|
17
|
+
ok: t,
|
|
18
|
+
error: r
|
|
19
|
+
});
|
|
20
|
+
};
|
|
21
|
+
t ? a(!1, "Worker already running; dispatch one system at a time") : (t = !0, (async () => {
|
|
22
|
+
try {
|
|
23
|
+
if (typeof i.module != "string" || typeof i.exportName != "string" || !i.context) throw TypeError("Invalid parallel message; dispatch a named module with a context");
|
|
24
|
+
let e = await import(
|
|
25
|
+
/* @vite-ignore */
|
|
26
|
+
i.module
|
|
27
|
+
);
|
|
28
|
+
if (!Object.hasOwn(e, i.exportName) || typeof e[i.exportName] != "function") throw TypeError("Parallel system export is missing; export a system function from the module");
|
|
29
|
+
await e[i.exportName](i.context), a(!0);
|
|
30
|
+
} catch (e) {
|
|
31
|
+
a(!1, e instanceof Error ? e.message : String(e));
|
|
32
|
+
} finally {
|
|
33
|
+
t = !1;
|
|
34
|
+
}
|
|
35
|
+
})());
|
|
36
|
+
};
|
|
37
|
+
return e.addEventListener("message", r), () => {
|
|
38
|
+
n = !0, e.removeEventListener("message", r);
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
//#endregion
|
|
42
|
+
//#region src/parallel.ts
|
|
43
|
+
var a = /* @__PURE__ */ new WeakSet();
|
|
44
|
+
function o(e) {
|
|
45
|
+
if (a.has(e)) throw new n("state", "Parallel systems are running; await update before changing component membership or entity lifetime");
|
|
46
|
+
}
|
|
47
|
+
var s = class extends e {
|
|
48
|
+
constructor(e, t, n = !1) {
|
|
49
|
+
super(e, t, n), this.rows = e.allocate(Int32Array, -1), e.attach(this);
|
|
50
|
+
}
|
|
51
|
+
add(e, t = {}) {
|
|
52
|
+
o(this.world), this.adding = e;
|
|
53
|
+
try {
|
|
54
|
+
return super.add(e, t);
|
|
55
|
+
} finally {
|
|
56
|
+
this.adding = void 0;
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
remove(e) {
|
|
60
|
+
o(this.world), this.removing = e;
|
|
61
|
+
try {
|
|
62
|
+
return super.remove(e);
|
|
63
|
+
} finally {
|
|
64
|
+
this.removing = void 0;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
initializeRow(e, t = {}) {
|
|
68
|
+
super.initializeRow(e, t), this.rows[this.adding % this.world.stride] = e;
|
|
69
|
+
}
|
|
70
|
+
moveRow(e, t) {
|
|
71
|
+
super.moveRow(e, t), this.rows[this.removing % this.world.stride] = -1, e < this.size && (this.rows[this.entities[e] % this.world.stride] = e);
|
|
72
|
+
}
|
|
73
|
+
touch(e) {
|
|
74
|
+
return o(this.world), super.touch(e);
|
|
75
|
+
}
|
|
76
|
+
}, c = class extends t {
|
|
77
|
+
allocate(e, t = 0) {
|
|
78
|
+
if (typeof SharedArrayBuffer > "u" || "document" in globalThis && !globalThis.crossOriginIsolated) throw new n("unsupported", "Shared ECS needs cross-origin isolation; serve COOP same-origin and COEP require-corp headers");
|
|
79
|
+
let r = e, i = new r(new SharedArrayBuffer(this.capacity * r.BYTES_PER_ELEMENT));
|
|
80
|
+
return t && i.fill(t), i;
|
|
81
|
+
}
|
|
82
|
+
create() {
|
|
83
|
+
return o(this), super.create();
|
|
84
|
+
}
|
|
85
|
+
destroy(e) {
|
|
86
|
+
o(this), super.destroy(e);
|
|
87
|
+
}
|
|
88
|
+
reserve(e) {
|
|
89
|
+
o(this), super.reserve(e);
|
|
90
|
+
}
|
|
91
|
+
attach(e) {
|
|
92
|
+
o(this), super.attach(e);
|
|
93
|
+
}
|
|
94
|
+
detach(e) {
|
|
95
|
+
o(this), super.detach(e);
|
|
96
|
+
}
|
|
97
|
+
component(e) {
|
|
98
|
+
return o(this), new s(this, e);
|
|
99
|
+
}
|
|
100
|
+
tag() {
|
|
101
|
+
return o(this), new s(this, {}, !0);
|
|
102
|
+
}
|
|
103
|
+
}, l = class {
|
|
104
|
+
constructor(e, t, r = {}) {
|
|
105
|
+
if (this.world = e, this.systems = [], this.slots = [], this.stopped = !1, this.running = !1, this.sequence = 0, this.tick = 0, this.elapsed = 0, this.terminationFailed = !1, !(e instanceof c)) throw TypeError("Parallel schedule needs a SharedWorld; create shared component stores before scheduling");
|
|
106
|
+
if (this.workerCount = r.workers ?? 2, this.timeout = r.timeout ?? 3e4, !Number.isInteger(this.workerCount) || this.workerCount < 1 || this.workerCount > 32 || !Number.isFinite(this.timeout) || this.timeout < 1 || this.timeout > 2147483647) throw RangeError("Invalid parallel options; use 1 to 32 workers and a deadline from 1 to 2147483647 ms");
|
|
107
|
+
if (this.stores = new Map(Object.entries(t)), [...this.stores.values()].some((t) => t.world !== e || !(t instanceof s) || !(t.entities.buffer instanceof SharedArrayBuffer) || Object.values(t.fields).some((e) => !(e.buffer instanceof SharedArrayBuffer)))) throw TypeError("Parallel components must belong to this SharedWorld; create them with world.component or world.tag");
|
|
108
|
+
this.factory = r.workerFactory ?? (() => {
|
|
109
|
+
if (typeof Worker > "u") throw new n("unsupported", "No browser Worker available; provide workerFactory for this host");
|
|
110
|
+
return new Worker(new URL("./workers/parallel.js?no-inline",
|
|
111
|
+
import.meta.url
|
|
112
|
+
));
|
|
113
|
+
});
|
|
114
|
+
}
|
|
115
|
+
add(e) {
|
|
116
|
+
if (this.check(), this.running) throw new n("state", "Parallel update is running; add systems between updates");
|
|
117
|
+
if (typeof e.name != "string" || !e.name.trim() || this.systems.some((t) => t.name === e.name) || !e.module || [
|
|
118
|
+
e.reads,
|
|
119
|
+
e.writes,
|
|
120
|
+
e.before,
|
|
121
|
+
e.after
|
|
122
|
+
].some((e) => e !== void 0 && (!Array.isArray(e) || e.some((e) => typeof e != "string" || !e.trim()))) || e.exportName !== void 0 && (typeof e.exportName != "string" || !e.exportName.trim())) throw TypeError("Invalid parallel system; supply a unique name and absolute module URL");
|
|
123
|
+
let t = [...new Set(e.reads ?? [])], r = [...new Set(e.writes ?? [])];
|
|
124
|
+
if ([...t, ...r].some((e) => !this.stores.has(e))) throw TypeError("Unknown parallel component; use names registered with this schedule");
|
|
125
|
+
let i = new URL(String(e.module));
|
|
126
|
+
return this.systems.push({
|
|
127
|
+
name: e.name,
|
|
128
|
+
module: i.href,
|
|
129
|
+
exportName: e.exportName ?? "default",
|
|
130
|
+
reads: t,
|
|
131
|
+
writes: r,
|
|
132
|
+
before: [...e.before ?? []],
|
|
133
|
+
after: [...e.after ?? []]
|
|
134
|
+
}), this;
|
|
135
|
+
}
|
|
136
|
+
graph() {
|
|
137
|
+
let e = [...this.systems], t = new Map(e.map((e) => [e.name, e])), r = new Map(e.map((e) => [e, /* @__PURE__ */ new Set()])), i = (e, t) => {
|
|
138
|
+
if (!e || !t) throw new n("state", "Parallel dependency is missing; register every named predecessor/successor");
|
|
139
|
+
r.get(e).add(t);
|
|
140
|
+
};
|
|
141
|
+
for (let n of e) {
|
|
142
|
+
for (let e of n.before) i(n, t.get(e));
|
|
143
|
+
for (let e of n.after) i(t.get(e), n);
|
|
144
|
+
}
|
|
145
|
+
let a = this.levels(e, r).flat(), o = (e) => new Set(e.flatMap((e) => {
|
|
146
|
+
let t = this.stores.get(e);
|
|
147
|
+
return [
|
|
148
|
+
t.entities.buffer,
|
|
149
|
+
t.rows.buffer,
|
|
150
|
+
...Object.values(t.fields).map((e) => e.buffer)
|
|
151
|
+
];
|
|
152
|
+
})), s = new Map(a.map((e) => [e, {
|
|
153
|
+
reads: o(e.reads),
|
|
154
|
+
writes: o(e.writes)
|
|
155
|
+
}]));
|
|
156
|
+
for (let e = 0; e < a.length; e++) for (let t = e + 1; t < a.length; t++) {
|
|
157
|
+
let n = a[e], r = a[t], o = s.get(n), c = s.get(r);
|
|
158
|
+
([...o.writes].some((e) => c.reads.has(e) || c.writes.has(e)) || [...c.writes].some((e) => o.reads.has(e))) && i(n, r);
|
|
159
|
+
}
|
|
160
|
+
return {
|
|
161
|
+
systems: e,
|
|
162
|
+
edges: r
|
|
163
|
+
};
|
|
164
|
+
}
|
|
165
|
+
levels(e, t) {
|
|
166
|
+
let r = new Set(e), i = /* @__PURE__ */ new Set(), a = [];
|
|
167
|
+
for (; r.size;) {
|
|
168
|
+
let o = e.filter((n) => r.has(n) && e.every((e) => !t.get(e).has(n) || i.has(e)));
|
|
169
|
+
if (!o.length) throw new n("state", "Parallel system dependencies form a cycle; remove a before/after edge");
|
|
170
|
+
a.push(o);
|
|
171
|
+
for (let e of o) i.add(e), r.delete(e);
|
|
172
|
+
}
|
|
173
|
+
return a;
|
|
174
|
+
}
|
|
175
|
+
order() {
|
|
176
|
+
this.check();
|
|
177
|
+
let e = this.graph();
|
|
178
|
+
return this.levels(e.systems, e.edges).map((e) => e.map((e) => e.name));
|
|
179
|
+
}
|
|
180
|
+
slot() {
|
|
181
|
+
let e = this.factory(), t = {};
|
|
182
|
+
return t.worker = e, t.message = (e) => {
|
|
183
|
+
let r = e.data, i = t.pending;
|
|
184
|
+
i && r && r.tag === "margo-ecs-parallel" && r.id === i.id && (clearTimeout(i.timer), t.pending = void 0, r.ok === !0 ? i.resolve() : i.reject(new n("state", "Parallel system failed: " + String(r.error) + "; inspect the module and recreate the schedule")));
|
|
185
|
+
}, t.error = (e) => {
|
|
186
|
+
let r = t.pending;
|
|
187
|
+
this.failure = new n("state", "Parallel worker failed; inspect its module and recreate the schedule"), r && (clearTimeout(r.timer), t.pending = void 0, r.reject(this.failure));
|
|
188
|
+
}, e.addEventListener("message", t.message), e.addEventListener("error", t.error), e.addEventListener("messageerror", t.error), this.slots.push(t), t;
|
|
189
|
+
}
|
|
190
|
+
dispatch(e, t, r) {
|
|
191
|
+
let i = {};
|
|
192
|
+
for (let e of /* @__PURE__ */ new Set([...t.reads, ...t.writes])) {
|
|
193
|
+
let t = this.stores.get(e);
|
|
194
|
+
Object.defineProperty(i, e, {
|
|
195
|
+
value: {
|
|
196
|
+
entities: t.entities,
|
|
197
|
+
rows: t.rows,
|
|
198
|
+
stride: this.world.stride,
|
|
199
|
+
count: t.size,
|
|
200
|
+
fields: t.fields
|
|
201
|
+
},
|
|
202
|
+
enumerable: !0
|
|
203
|
+
});
|
|
204
|
+
}
|
|
205
|
+
let a = {
|
|
206
|
+
delta: r,
|
|
207
|
+
elapsed: this.elapsed + r,
|
|
208
|
+
tick: this.tick,
|
|
209
|
+
components: i
|
|
210
|
+
};
|
|
211
|
+
return new Promise((r, i) => {
|
|
212
|
+
let o = ++this.sequence, s = setTimeout(() => {
|
|
213
|
+
e.pending = void 0, i(new n("timeout", "Parallel system exceeded its deadline; inspect the module and recreate the schedule"));
|
|
214
|
+
}, this.timeout);
|
|
215
|
+
e.pending = {
|
|
216
|
+
id: o,
|
|
217
|
+
resolve: r,
|
|
218
|
+
reject: i,
|
|
219
|
+
timer: s
|
|
220
|
+
};
|
|
221
|
+
try {
|
|
222
|
+
e.worker.postMessage({
|
|
223
|
+
tag: "margo-ecs-parallel",
|
|
224
|
+
id: o,
|
|
225
|
+
module: t.module,
|
|
226
|
+
exportName: t.exportName,
|
|
227
|
+
context: a
|
|
228
|
+
});
|
|
229
|
+
} catch (t) {
|
|
230
|
+
clearTimeout(s), e.pending = void 0, i(t);
|
|
231
|
+
}
|
|
232
|
+
});
|
|
233
|
+
}
|
|
234
|
+
async update(e, { signal: t } = {}) {
|
|
235
|
+
if (this.check(), t?.throwIfAborted(), this.failure) throw await this.stop(), this.failure;
|
|
236
|
+
if (!Number.isFinite(e) || e < 0 || !Number.isFinite(this.elapsed + e)) throw RangeError("Invalid parallel delta; use finite nonnegative seconds");
|
|
237
|
+
if (this.running || a.has(this.world)) throw new n("state", "Shared world already has an update; await it before scheduling more systems");
|
|
238
|
+
let r = this.graph(), i = this.levels(r.systems, r.edges);
|
|
239
|
+
this.running = !0, a.add(this.world);
|
|
240
|
+
let o, s = () => {
|
|
241
|
+
o = t?.reason;
|
|
242
|
+
for (let e of this.slots) {
|
|
243
|
+
let t = e.pending;
|
|
244
|
+
t && (clearTimeout(t.timer), e.pending = void 0, t.reject(o));
|
|
245
|
+
}
|
|
246
|
+
};
|
|
247
|
+
t?.addEventListener("abort", s, { once: !0 });
|
|
248
|
+
try {
|
|
249
|
+
for (let n of i) for (let r = 0; r < n.length; r += this.workerCount) {
|
|
250
|
+
t?.throwIfAborted();
|
|
251
|
+
let i = n.slice(r, r + this.workerCount);
|
|
252
|
+
await Promise.all(i.map((t, n) => this.dispatch(this.slots[n] ?? this.slot(), t, e)));
|
|
253
|
+
}
|
|
254
|
+
t?.throwIfAborted(), this.elapsed += e, this.tick++;
|
|
255
|
+
} catch (e) {
|
|
256
|
+
throw await this.stop(), o === void 0 ? e : o;
|
|
257
|
+
} finally {
|
|
258
|
+
t?.removeEventListener("abort", s), this.terminationFailed || a.delete(this.world), this.running = !1;
|
|
259
|
+
}
|
|
260
|
+
let c = new Set(this.systems.flatMap((e) => e.writes).map((e) => this.stores.get(e)));
|
|
261
|
+
for (let e of c) for (let t of [...e.entities.subarray(0, e.size)]) e.touch(t);
|
|
262
|
+
}
|
|
263
|
+
stop() {
|
|
264
|
+
return this.stopping ||= (this.stopped = !0, Promise.resolve().then(async () => {
|
|
265
|
+
if ((await Promise.allSettled(this.slots.map(async (e) => {
|
|
266
|
+
let t = e.pending;
|
|
267
|
+
t && (clearTimeout(t.timer), e.pending = void 0, t.reject(new n("disposed", "Parallel schedule stopped; create a new schedule before updating"))), e.worker.removeEventListener("message", e.message), e.worker.removeEventListener("error", e.error), e.worker.removeEventListener("messageerror", e.error), await e.worker.terminate();
|
|
268
|
+
}))).some((e) => e.status === "rejected")) throw this.terminationFailed = !0, new n("state", "Parallel worker termination failed; stop the host before accessing shared fields");
|
|
269
|
+
this.slots.length = 0;
|
|
270
|
+
})), this.stopping;
|
|
271
|
+
}
|
|
272
|
+
[Symbol.asyncDispose]() {
|
|
273
|
+
return this.stop();
|
|
274
|
+
}
|
|
275
|
+
check() {
|
|
276
|
+
if (this.stopped) throw new n("disposed", "Parallel schedule stopped; create a new schedule before updating");
|
|
277
|
+
}
|
|
278
|
+
};
|
|
279
|
+
//#endregion
|
|
280
|
+
export { l as ParallelSchedule, s as SharedComponent, c as SharedWorld, i as serveParallelSystems, r as sharedIndex };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
package/dist/query.d.ts
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import type { ComponentStore as Component, Entity, World } from './index.js';
|
|
2
|
+
/** Terms of a {@link Query}. Tags from `world.tag()` work in all three lists. */
|
|
3
|
+
export interface QueryTerms {
|
|
4
|
+
/** An entity must have every one of these. At least one. */
|
|
5
|
+
with: readonly Component[];
|
|
6
|
+
/** An entity must have none of these. Default none. */
|
|
7
|
+
without?: readonly Component[];
|
|
8
|
+
/** An entity may have these or not; they never change the match, only the rows given to `forEach`. Default none. */
|
|
9
|
+
optional?: readonly Component[];
|
|
10
|
+
}
|
|
11
|
+
/** A reusable set of terms: required components, excluded components and optional ones. */
|
|
12
|
+
export declare class Query {
|
|
13
|
+
readonly world: World;
|
|
14
|
+
private readonly required;
|
|
15
|
+
private readonly excluded;
|
|
16
|
+
private readonly reads;
|
|
17
|
+
private readonly rows;
|
|
18
|
+
private matches;
|
|
19
|
+
private visiting;
|
|
20
|
+
/** @throws TypeError when `with` is empty or a term belongs to another world. */
|
|
21
|
+
constructor(world: World, terms: QueryTerms);
|
|
22
|
+
/** Fill the private match list; `world.query` does the intersection and the rows that fail `without` drop out. */
|
|
23
|
+
private collect;
|
|
24
|
+
private allowed;
|
|
25
|
+
/**
|
|
26
|
+
* Write the matching entities into caller-owned `output`; returns how many. Optional terms have no effect here.
|
|
27
|
+
* @throws RangeError when `output` is too small (`world.capacity` entries always fit).
|
|
28
|
+
* @throws MargoError `'state'` when called from this query's own `forEach`.
|
|
29
|
+
*/
|
|
30
|
+
run(output: Uint32Array): number;
|
|
31
|
+
/**
|
|
32
|
+
* Call `visit` for each match with its rows: `rows[i]` is the row in the i-th `with` term, then the `optional` terms
|
|
33
|
+
* in order, -1 for an optional term the entity lacks. `rows` is reused, so read it during the call.
|
|
34
|
+
*
|
|
35
|
+
* The match list is taken first, so `visit` may add, remove and destroy freely: rows are looked up just before each
|
|
36
|
+
* call, and an entity that stopped matching meanwhile is passed over. Entities that start matching are not visited.
|
|
37
|
+
* Returns the number of calls made.
|
|
38
|
+
* @throws MargoError `'state'` when called from this query's own `forEach`; a second Query object may nest.
|
|
39
|
+
*/
|
|
40
|
+
forEach(visit: (entity: Entity, rows: Int32Array) => void): number;
|
|
41
|
+
private enter;
|
|
42
|
+
}
|
package/dist/query.js
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import { MargoError as e } from "@margoengine/math/errors";
|
|
2
|
+
//#region src/query.ts
|
|
3
|
+
var t = class {
|
|
4
|
+
constructor(e, t) {
|
|
5
|
+
this.world = e, this.matches = /* @__PURE__ */ new Uint32Array(), this.visiting = !1;
|
|
6
|
+
let n = [...t.with ?? []], r = [...t.without ?? []], i = [...t.optional ?? []];
|
|
7
|
+
if (!n.length || [
|
|
8
|
+
...n,
|
|
9
|
+
...r,
|
|
10
|
+
...i
|
|
11
|
+
].some((t) => t.world !== e)) throw TypeError("Query needs components of this world; pass at least one in with");
|
|
12
|
+
this.required = n, this.excluded = r, this.reads = [...n, ...i], this.rows = new Int32Array(this.reads.length);
|
|
13
|
+
}
|
|
14
|
+
collect() {
|
|
15
|
+
let { world: e, excluded: t } = this;
|
|
16
|
+
this.matches.length < e.capacity && (this.matches = new Uint32Array(e.capacity));
|
|
17
|
+
let n = this.matches, r = e.query(this.required, n);
|
|
18
|
+
if (!t.length) return r;
|
|
19
|
+
let i = 0;
|
|
20
|
+
for (let e = 0; e < r; e++) {
|
|
21
|
+
let t = n[e];
|
|
22
|
+
this.allowed(t) && (n[i++] = t);
|
|
23
|
+
}
|
|
24
|
+
return i;
|
|
25
|
+
}
|
|
26
|
+
allowed(e) {
|
|
27
|
+
let { excluded: t } = this;
|
|
28
|
+
for (let n = 0; n < t.length; n++) if (t[n].index(e) >= 0) return !1;
|
|
29
|
+
return !0;
|
|
30
|
+
}
|
|
31
|
+
run(e) {
|
|
32
|
+
this.enter();
|
|
33
|
+
let t = this.collect();
|
|
34
|
+
if (e.length < t) throw RangeError("Query output is too small; pass a Uint32Array at least as long as the entity count (world.capacity always fits)");
|
|
35
|
+
return e.set(this.matches.subarray(0, t)), t;
|
|
36
|
+
}
|
|
37
|
+
forEach(e) {
|
|
38
|
+
this.enter();
|
|
39
|
+
let { reads: t, rows: n, required: r } = this, i = r.length, a = this.collect(), o = this.matches, s = 0;
|
|
40
|
+
this.visiting = !0;
|
|
41
|
+
try {
|
|
42
|
+
next: for (let r = 0; r < a; r++) {
|
|
43
|
+
let a = o[r];
|
|
44
|
+
for (let e = 0; e < t.length; e++) {
|
|
45
|
+
let r = t[e].index(a);
|
|
46
|
+
if (r < 0 && e < i) continue next;
|
|
47
|
+
n[e] = r;
|
|
48
|
+
}
|
|
49
|
+
this.allowed(a) && (e(a, n), s++);
|
|
50
|
+
}
|
|
51
|
+
} finally {
|
|
52
|
+
this.visiting = !1;
|
|
53
|
+
}
|
|
54
|
+
return s;
|
|
55
|
+
}
|
|
56
|
+
enter() {
|
|
57
|
+
if (this.visiting) throw new e("state", "Query is inside its own forEach; use a second Query for a nested loop");
|
|
58
|
+
}
|
|
59
|
+
};
|
|
60
|
+
//#endregion
|
|
61
|
+
export { t as Query };
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import type { Entity, World } from './index.js';
|
|
2
|
+
import type { QueryTerms } from './query.js';
|
|
3
|
+
/** Per-query structural transitions delivered by flush(). */
|
|
4
|
+
export interface QueryListener {
|
|
5
|
+
/** Entity entered the query. Default no callback. */
|
|
6
|
+
onEnter?: (entity: Entity) => void;
|
|
7
|
+
/** Entity exited the query. Its id can be stale after destruction. Default no callback. */
|
|
8
|
+
onExit?: (entity: Entity) => void;
|
|
9
|
+
}
|
|
10
|
+
/** An incrementally maintained component query with independent enter/exit events. */
|
|
11
|
+
export declare class ReactiveQuery {
|
|
12
|
+
readonly world: World;
|
|
13
|
+
private readonly required;
|
|
14
|
+
private readonly excluded;
|
|
15
|
+
private readonly reads;
|
|
16
|
+
private readonly watched;
|
|
17
|
+
private readonly dense;
|
|
18
|
+
private readonly positions;
|
|
19
|
+
private readonly listeners;
|
|
20
|
+
private events;
|
|
21
|
+
private stopped;
|
|
22
|
+
private visiting;
|
|
23
|
+
private flushing;
|
|
24
|
+
private readonly observer;
|
|
25
|
+
/** @throws TypeError when with is empty or a component belongs to another world. */
|
|
26
|
+
constructor(world: World, terms: QueryTerms);
|
|
27
|
+
/** Number of cached matches. No world scan. */
|
|
28
|
+
get size(): number;
|
|
29
|
+
/** True when the entity is in the current cache. */
|
|
30
|
+
has(entity: Entity): boolean;
|
|
31
|
+
private matches;
|
|
32
|
+
private refresh;
|
|
33
|
+
/**
|
|
34
|
+
* Subscribe to future transitions; initial:true immediately visits current entries for this listener alone.
|
|
35
|
+
* Returns an idempotent unsubscribe function.
|
|
36
|
+
* @throws MargoError 'disposed' after stop.
|
|
37
|
+
*/
|
|
38
|
+
subscribe(listener: QueryListener, { initial }?: {
|
|
39
|
+
initial?: boolean;
|
|
40
|
+
}): () => void;
|
|
41
|
+
/**
|
|
42
|
+
* Deliver queued transitions in order. Listener mutations queue transitions for the next flush.
|
|
43
|
+
* An error propagates; already delivered transitions are not replayed, remaining transitions stay pending.
|
|
44
|
+
* @throws MargoError 'state' for nested flush, or 'disposed' after stop.
|
|
45
|
+
*/
|
|
46
|
+
flush(): number;
|
|
47
|
+
/** Write cached ids without scanning components; throws RangeError for an undersized output. */
|
|
48
|
+
run(output: Uint32Array): number;
|
|
49
|
+
/**
|
|
50
|
+
* Snapshot cached ids, then resolve current rows. Newly entered matches wait until the next iteration.
|
|
51
|
+
* Rows are reused and ordered with then optional (-1 when absent).
|
|
52
|
+
* @throws MargoError 'state' for a nested iteration, or 'disposed' after stop.
|
|
53
|
+
*/
|
|
54
|
+
forEach(visit: (entity: Entity, rows: Int32Array) => void): number;
|
|
55
|
+
/** Detach observers and release cached ids, transitions and listeners. Idempotent. */
|
|
56
|
+
stop(): void;
|
|
57
|
+
[Symbol.dispose]: () => void;
|
|
58
|
+
private check;
|
|
59
|
+
}
|
package/dist/reactive.js
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
import { MargoError as e } from "@margoengine/math/errors";
|
|
2
|
+
//#region src/reactive.ts
|
|
3
|
+
var t = class {
|
|
4
|
+
constructor(e, t) {
|
|
5
|
+
if (this.world = e, this.dense = [], this.positions = /* @__PURE__ */ new Map(), this.listeners = /* @__PURE__ */ new Set(), this.events = [], this.stopped = !1, this.visiting = !1, this.flushing = !1, this.observer = {
|
|
6
|
+
onAdd: (e) => this.refresh(e),
|
|
7
|
+
onRemove: (e) => this.refresh(e),
|
|
8
|
+
onChange: () => {}
|
|
9
|
+
}, this.required = [...t.with], this.excluded = [...t.without ?? []], this.reads = [...this.required, ...t.optional ?? []], this.watched = [.../* @__PURE__ */ new Set([...this.required, ...this.excluded])], !this.required.length || [...this.watched, ...this.reads].some((t) => t.world !== e)) throw TypeError("Invalid reactive query; pass at least one required component and only components of this world");
|
|
10
|
+
let n = this.required[0];
|
|
11
|
+
for (let e of this.required) e.size < n.size && (n = e);
|
|
12
|
+
for (let e = 0; e < n.size; e++) this.refresh(n.entities[e]);
|
|
13
|
+
this.events.length = 0;
|
|
14
|
+
for (let e of this.watched) e.observers.push(this.observer);
|
|
15
|
+
}
|
|
16
|
+
get size() {
|
|
17
|
+
return this.dense.length;
|
|
18
|
+
}
|
|
19
|
+
has(e) {
|
|
20
|
+
return this.positions.has(e);
|
|
21
|
+
}
|
|
22
|
+
matches(e) {
|
|
23
|
+
return this.world.alive(e) && !this.world.destroying(e) && this.required.every((t) => t.has(e)) && this.excluded.every((t) => !t.has(e));
|
|
24
|
+
}
|
|
25
|
+
refresh(e) {
|
|
26
|
+
if (this.stopped) return;
|
|
27
|
+
let t = this.positions.get(e), n = this.matches(e);
|
|
28
|
+
if (n && t === void 0) this.positions.set(e, this.dense.length), this.dense.push(e), this.listeners.size && this.events.push([
|
|
29
|
+
!0,
|
|
30
|
+
e,
|
|
31
|
+
[...this.listeners]
|
|
32
|
+
]);
|
|
33
|
+
else if (!n && t !== void 0) {
|
|
34
|
+
let n = this.dense.pop();
|
|
35
|
+
t < this.dense.length && (this.dense[t] = n, this.positions.set(n, t)), this.positions.delete(e), this.listeners.size && this.events.push([
|
|
36
|
+
!1,
|
|
37
|
+
e,
|
|
38
|
+
[...this.listeners]
|
|
39
|
+
]);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
subscribe(e, { initial: t = !1 } = {}) {
|
|
43
|
+
if (this.check(), this.listeners.add(e), t) for (let t of [...this.dense]) {
|
|
44
|
+
if (!this.listeners.has(e) || this.stopped) break;
|
|
45
|
+
e.onEnter?.(t);
|
|
46
|
+
}
|
|
47
|
+
return () => {
|
|
48
|
+
this.listeners.delete(e);
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
flush() {
|
|
52
|
+
if (this.check(), this.flushing) throw new e("state", "Reactive query is flushing; flush again after callbacks return");
|
|
53
|
+
this.flushing = !0;
|
|
54
|
+
let t = this.events;
|
|
55
|
+
this.events = [];
|
|
56
|
+
let n = 0;
|
|
57
|
+
try {
|
|
58
|
+
for (let e = 0; e < t.length && !this.stopped; e++) {
|
|
59
|
+
let [r, i, a] = t[e];
|
|
60
|
+
n++;
|
|
61
|
+
for (let e of a) {
|
|
62
|
+
if (this.stopped) break;
|
|
63
|
+
this.listeners.has(e) && (r ? e.onEnter : e.onExit)?.(i);
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
} finally {
|
|
67
|
+
!this.stopped && n < t.length && (this.events = [...t.slice(n), ...this.events]), this.flushing = !1;
|
|
68
|
+
}
|
|
69
|
+
return n;
|
|
70
|
+
}
|
|
71
|
+
run(e) {
|
|
72
|
+
if (this.check(), e.length < this.size) throw RangeError("Reactive query output is too small; allocate at least query.size entries");
|
|
73
|
+
return e.set(this.dense), this.size;
|
|
74
|
+
}
|
|
75
|
+
forEach(t) {
|
|
76
|
+
if (this.check(), this.visiting) throw new e("state", "Reactive query is visiting; use another query to nest iteration");
|
|
77
|
+
let n = [...this.dense], r = new Int32Array(this.reads.length), i = 0;
|
|
78
|
+
this.visiting = !0;
|
|
79
|
+
try {
|
|
80
|
+
for (let e of n) !this.stopped && this.positions.has(e) && (this.reads.forEach((t, n) => {
|
|
81
|
+
r[n] = t.index(e);
|
|
82
|
+
}), t(e, r), i++);
|
|
83
|
+
} finally {
|
|
84
|
+
this.visiting = !1;
|
|
85
|
+
}
|
|
86
|
+
return i;
|
|
87
|
+
}
|
|
88
|
+
stop() {
|
|
89
|
+
if (!this.stopped) {
|
|
90
|
+
this.stopped = !0;
|
|
91
|
+
for (let e of this.watched) {
|
|
92
|
+
let t = e.observers.indexOf(this.observer);
|
|
93
|
+
t >= 0 && e.observers.splice(t, 1);
|
|
94
|
+
}
|
|
95
|
+
this.positions.clear(), this.dense.length = 0, this.events.length = 0, this.listeners.clear();
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
[Symbol.dispose ?? Symbol()]() {
|
|
99
|
+
this.stop();
|
|
100
|
+
}
|
|
101
|
+
check() {
|
|
102
|
+
if (this.stopped) throw new e("disposed", "Reactive query stopped; create a new query before reading or subscribing");
|
|
103
|
+
}
|
|
104
|
+
};
|
|
105
|
+
//#endregion
|
|
106
|
+
export { t as ReactiveQuery };
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import type { ComponentStore as Component, Entity, World } from './index.js';
|
|
2
|
+
import { type Relation } from './relations.js';
|
|
3
|
+
/** Target written for an optional pair term that has no pair. */
|
|
4
|
+
export declare const NO_TARGET = 4294967295;
|
|
5
|
+
/** A pair term: a relation (or every relation), a target (or every target) and components required on the target. */
|
|
6
|
+
export interface RelationTerm {
|
|
7
|
+
/** Relationship owned by this world, or '*' for every relation of the world that is not stopped. */
|
|
8
|
+
relation: Relation | '*';
|
|
9
|
+
/** Exact target id, or '*' for every target. Default '*'. */
|
|
10
|
+
target?: Entity | '*';
|
|
11
|
+
/** Components required on the target, with rows returned in term order. Default none. */
|
|
12
|
+
with?: readonly Component[];
|
|
13
|
+
}
|
|
14
|
+
/** Source component filters and relationship pair terms. */
|
|
15
|
+
export interface RelationQueryTerms {
|
|
16
|
+
/** Required pair terms. Wildcards enumerate every combination. Default none; needs a term here or in `with`. */
|
|
17
|
+
relations?: readonly RelationTerm[];
|
|
18
|
+
/**
|
|
19
|
+
* Optional pair terms, after the required ones in target columns: every matching pair is enumerated like a
|
|
20
|
+
* required term, and a source with none gets one match with target {@link NO_TARGET} and target rows -1.
|
|
21
|
+
* Default none.
|
|
22
|
+
*/
|
|
23
|
+
optionalRelations?: readonly RelationTerm[];
|
|
24
|
+
/** Excluded pair terms: a source with any matching pair is left out. Default none. */
|
|
25
|
+
withoutRelations?: readonly RelationTerm[];
|
|
26
|
+
/** Required source components. Default none. */
|
|
27
|
+
with?: readonly Component[];
|
|
28
|
+
/** Excluded source components. Default none. */
|
|
29
|
+
without?: readonly Component[];
|
|
30
|
+
/** Optional source components; rows use -1 when absent. Default none. */
|
|
31
|
+
optional?: readonly Component[];
|
|
32
|
+
}
|
|
33
|
+
/** A relation join query returning source rows, matched targets and target component rows. */
|
|
34
|
+
export declare class RelationQuery {
|
|
35
|
+
readonly world: World;
|
|
36
|
+
private readonly required;
|
|
37
|
+
private readonly optionalTerms;
|
|
38
|
+
private readonly excludedTerms;
|
|
39
|
+
private readonly with;
|
|
40
|
+
private readonly without;
|
|
41
|
+
private readonly optional;
|
|
42
|
+
private visiting;
|
|
43
|
+
private scratch;
|
|
44
|
+
/**
|
|
45
|
+
* @throws TypeError with no required pair term and no `with` component, for an invalid relation or target, or for
|
|
46
|
+
* terms of another world.
|
|
47
|
+
*/
|
|
48
|
+
constructor(world: World, terms: RelationQueryTerms);
|
|
49
|
+
/** Target columns: required pair terms, then optional ones. */
|
|
50
|
+
get termCount(): number;
|
|
51
|
+
/** A target buffer that fits every target of one source (`world.capacity`), grown with a growable world. */
|
|
52
|
+
private buffer;
|
|
53
|
+
private relationsOf;
|
|
54
|
+
private targetOk;
|
|
55
|
+
/** Every pair of the term, grouped by source. */
|
|
56
|
+
private pairs;
|
|
57
|
+
/** True when `source` has a pair matching an excluded term now. */
|
|
58
|
+
private excluded;
|
|
59
|
+
private allowed;
|
|
60
|
+
private collect;
|
|
61
|
+
/**
|
|
62
|
+
* Write sources (repeated for each matching pair combination) and optional target columns, one per required and
|
|
63
|
+
* then optional pair term; an absent optional pair writes {@link NO_TARGET}.
|
|
64
|
+
* @throws RangeError when any output is too small, or target column count differs from the term count.
|
|
65
|
+
*/
|
|
66
|
+
run(output: Uint32Array, targets?: readonly Uint32Array[]): number;
|
|
67
|
+
/**
|
|
68
|
+
* Visit snapshot matches, rechecking membership and resolving current rows before each call.
|
|
69
|
+
* Source rows are with then optional. Target rows flatten each pair term's with list, required terms then optional
|
|
70
|
+
* ones, and are -1 for an absent optional pair. `relations` holds the relation each term matched (useful with a
|
|
71
|
+
* relation wildcard), undefined for an absent optional pair.
|
|
72
|
+
* Callback arrays are reused. Added pairs wait for the next call; removed pairs, and sources that gained an excluded
|
|
73
|
+
* pair, are passed over.
|
|
74
|
+
* @throws MargoError 'state' for a nested call on this query.
|
|
75
|
+
*/
|
|
76
|
+
forEach(visit: (source: Entity, rows: Int32Array, targets: Uint32Array, targetRows: Int32Array, relations: readonly (Relation | undefined)[]) => void): number;
|
|
77
|
+
}
|