@margoengine/ecs 0.0.0-stage → 0.1.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 +294 -3
- 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 +30 -0
- package/dist/objects.js +50 -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 +44 -0
- package/dist/relation-query.js +79 -0
- package/dist/relations.d.ts +70 -0
- package/dist/relations.js +93 -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 +107 -6
package/dist/index.js
ADDED
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
import { Schedule as e } from "./schedule.js";
|
|
2
|
+
import { ChangeTracker as t } from "./changes.js";
|
|
3
|
+
import { Query as n } from "./query.js";
|
|
4
|
+
import { Relation as r } from "./relations.js";
|
|
5
|
+
import { MargoError as i } from "@margoengine/math/errors";
|
|
6
|
+
//#region src/index.ts
|
|
7
|
+
var a = 1e6, o = class {
|
|
8
|
+
constructor(e, t, n = !1) {
|
|
9
|
+
if (this.world = e, this.size = 0, this.observers = [], !n && !Object.keys(t).length) throw TypeError("Empty component schema; give at least one field, e.g. {x: Float32Array}");
|
|
10
|
+
this.sparse = e.allocate(Int32Array, -1), this.entities = e.allocate(Uint32Array), this.fields = Object.fromEntries(Object.entries(t).map(([t, n]) => {
|
|
11
|
+
if (![
|
|
12
|
+
Float32Array,
|
|
13
|
+
Float64Array,
|
|
14
|
+
Int32Array,
|
|
15
|
+
Uint32Array,
|
|
16
|
+
Uint8Array
|
|
17
|
+
].includes(n)) throw TypeError("Unsupported component storage; use Float32Array, Float64Array, Int32Array, Uint32Array or Uint8Array");
|
|
18
|
+
return [t, e.allocate(n)];
|
|
19
|
+
})), this.columns = Object.values(this.fields);
|
|
20
|
+
}
|
|
21
|
+
index(e) {
|
|
22
|
+
if (!this.world.alive(e)) return -1;
|
|
23
|
+
let t = this.sparse[e % this.world.stride];
|
|
24
|
+
return t >= 0 && this.entities[t] === e ? t : -1;
|
|
25
|
+
}
|
|
26
|
+
has(e) {
|
|
27
|
+
return this.index(e) >= 0;
|
|
28
|
+
}
|
|
29
|
+
add(e, t = {}) {
|
|
30
|
+
this.world.check(e), this.validateValues(t);
|
|
31
|
+
let n = Object.keys(t), r = this.index(e), i = r < 0;
|
|
32
|
+
i && (r = this.size, this.initializeRow(r, t), this.size++, this.sparse[e % this.world.stride] = r, this.entities[r] = e);
|
|
33
|
+
for (let e of n) this.fields[e][r] = t[e];
|
|
34
|
+
let a = this.observers;
|
|
35
|
+
if (i) for (let t = 0; t < a.length; t++) a[t].onAdd(e);
|
|
36
|
+
else if (n.length) for (let t = 0; t < a.length; t++) a[t].onChange(e);
|
|
37
|
+
return r;
|
|
38
|
+
}
|
|
39
|
+
validateValues(e) {
|
|
40
|
+
let t = Object.keys(e);
|
|
41
|
+
for (let n of t) {
|
|
42
|
+
let t = e[n], r = this.fields[n];
|
|
43
|
+
if (!Object.hasOwn(this.fields, n) || typeof t != "number" || !Number.isFinite(t) || r instanceof Float32Array && !Number.isFinite(Math.fround(t)) || r instanceof Int32Array && (!Number.isInteger(t) || t < -2147483648 || t > 2147483647) || r instanceof Uint32Array && (!Number.isInteger(t) || t < 0 || t > 4294967295) || r instanceof Uint8Array && (!Number.isInteger(t) || t < 0 || t > 255)) throw RangeError("Invalid component data; pass finite numbers that fit the field type");
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
initializeRow(e, t = {}) {
|
|
47
|
+
for (let t of this.columns) t[e] = 0;
|
|
48
|
+
}
|
|
49
|
+
moveRow(e, t) {
|
|
50
|
+
if (e !== t) for (let n of this.columns) n[e] = n[t];
|
|
51
|
+
}
|
|
52
|
+
touch(e) {
|
|
53
|
+
if (this.index(e) < 0) return !1;
|
|
54
|
+
let t = this.observers;
|
|
55
|
+
for (let n = 0; n < t.length; n++) t[n].onChange(e);
|
|
56
|
+
return !0;
|
|
57
|
+
}
|
|
58
|
+
remove(e) {
|
|
59
|
+
let t = this.index(e);
|
|
60
|
+
if (t < 0) return !1;
|
|
61
|
+
let n = --this.size;
|
|
62
|
+
if (this.sparse[e % this.world.stride] = -1, t !== n) {
|
|
63
|
+
let e = this.entities[n];
|
|
64
|
+
this.entities[t] = e, this.sparse[e % this.world.stride] = t;
|
|
65
|
+
}
|
|
66
|
+
this.moveRow(t, n);
|
|
67
|
+
let r = this.observers;
|
|
68
|
+
for (let t = 0; t < r.length; t++) r[t].onRemove(e);
|
|
69
|
+
return !0;
|
|
70
|
+
}
|
|
71
|
+
}, s = class {
|
|
72
|
+
constructor(e = 4096, t = e) {
|
|
73
|
+
if (this.capacity = e, this.stride = t, this.components = /* @__PURE__ */ new Set(), !Number.isSafeInteger(t) || t < 1 || t > a) throw RangeError("Invalid ECS limit; use an integer from 1 to 1000000");
|
|
74
|
+
if (!Number.isSafeInteger(e) || e < 1 || e > t) throw RangeError(`Invalid ECS capacity; use an integer from 1 to ${t}`);
|
|
75
|
+
this.live = this.allocate(Uint8Array), this.generations = this.allocate(Uint32Array), this.free = this.allocate(Uint32Array), this.freeCount = 0, this.release(0, e);
|
|
76
|
+
}
|
|
77
|
+
allocate(e, t = 0) {
|
|
78
|
+
let n = new e(this.capacity);
|
|
79
|
+
return t && n.fill(t), n;
|
|
80
|
+
}
|
|
81
|
+
get available() {
|
|
82
|
+
return this.freeCount;
|
|
83
|
+
}
|
|
84
|
+
reserve(e) {
|
|
85
|
+
if (!Number.isSafeInteger(e) || e < 0 || e > this.stride) throw RangeError("Invalid ECS reservation; use a free-slot count from zero to world.stride");
|
|
86
|
+
for (; this.freeCount < e;) this.grow();
|
|
87
|
+
}
|
|
88
|
+
entities(e) {
|
|
89
|
+
let t = 0;
|
|
90
|
+
for (let n = 0; n < this.capacity; n++) if (this.live[n] === 1) {
|
|
91
|
+
if (t === e.length) throw RangeError("Entity output is too small; allocate world.capacity entries");
|
|
92
|
+
e[t++] = this.generations[n] * this.stride + n;
|
|
93
|
+
}
|
|
94
|
+
return t;
|
|
95
|
+
}
|
|
96
|
+
release(e, t) {
|
|
97
|
+
for (let n = t - 1; n >= e; n--) this.free[this.freeCount++] = n;
|
|
98
|
+
}
|
|
99
|
+
grow() {
|
|
100
|
+
throw RangeError("Entity capacity exhausted; destroy entities or create the World with a larger capacity");
|
|
101
|
+
}
|
|
102
|
+
alive(e) {
|
|
103
|
+
if (!Number.isSafeInteger(e) || e < 0 || e > 4294967295) return !1;
|
|
104
|
+
let t = e % this.stride;
|
|
105
|
+
return !!this.live[t] && Math.floor(e / this.stride) === this.generations[t];
|
|
106
|
+
}
|
|
107
|
+
destroying(e) {
|
|
108
|
+
return this.alive(e) && this.live[e % this.stride] === 2;
|
|
109
|
+
}
|
|
110
|
+
check(e) {
|
|
111
|
+
if (!this.alive(e)) throw new i("state", "Entity is stale or destroyed; check world.alive(entity) before using a stored id");
|
|
112
|
+
}
|
|
113
|
+
create() {
|
|
114
|
+
this.freeCount || this.grow();
|
|
115
|
+
let e = this.free[--this.freeCount];
|
|
116
|
+
return this.live[e] = 1, this.generations[e] * this.stride + e;
|
|
117
|
+
}
|
|
118
|
+
destroy(e) {
|
|
119
|
+
this.check(e);
|
|
120
|
+
let t = e % this.stride;
|
|
121
|
+
if (this.live[t] !== 2) {
|
|
122
|
+
this.live[t] = 2;
|
|
123
|
+
for (let t of this.components) t.remove(e);
|
|
124
|
+
this.live[t] = 0, (this.generations[t] + 1) * this.stride + t <= 4294967295 && (this.generations[t]++, this.free[this.freeCount++] = t);
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
attach(e) {
|
|
128
|
+
this.components.add(e);
|
|
129
|
+
}
|
|
130
|
+
detach(e) {
|
|
131
|
+
this.components.delete(e);
|
|
132
|
+
}
|
|
133
|
+
component(e) {
|
|
134
|
+
let t = new o(this, e);
|
|
135
|
+
return this.components.add(t), t;
|
|
136
|
+
}
|
|
137
|
+
tag() {
|
|
138
|
+
let e = new o(this, {}, !0);
|
|
139
|
+
return this.components.add(e), e;
|
|
140
|
+
}
|
|
141
|
+
query(e, t) {
|
|
142
|
+
if (!e.length || e.some((e) => e.world !== this)) throw TypeError("Query needs components of this world");
|
|
143
|
+
let n = e[0];
|
|
144
|
+
for (let t = 1; t < e.length; t++) e[t].size < n.size && (n = e[t]);
|
|
145
|
+
let r = 0, i = this.stride, a = this.live, o = this.generations, s = n.entities, c = n.size, l = e.length;
|
|
146
|
+
for (let n = 0; n < c; n++) {
|
|
147
|
+
let c = s[n], u = c % i;
|
|
148
|
+
if (!a[u] || Math.floor(c / i) !== o[u]) continue;
|
|
149
|
+
let d = !0;
|
|
150
|
+
for (let t = 0; t < l; t++) {
|
|
151
|
+
let n = e[t], r = n.sparse[u];
|
|
152
|
+
if (r < 0 || n.entities[r] !== c) {
|
|
153
|
+
d = !1;
|
|
154
|
+
break;
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
if (d) {
|
|
158
|
+
if (r === t.length) throw RangeError("Query output is too small; pass a Uint32Array at least as long as the entity count (world.capacity always fits)");
|
|
159
|
+
t[r++] = c;
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
return r;
|
|
163
|
+
}
|
|
164
|
+
};
|
|
165
|
+
//#endregion
|
|
166
|
+
export { t as ChangeTracker, o as Component, n as Query, r as Relation, e as Schedule, s as World };
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { Component, type ArrayConstructor, type Entity, type World } from './index.js';
|
|
2
|
+
/** A reference field with a fresh default per row. Values retain identity, including functions and cycles. */
|
|
3
|
+
export interface ObjectField<T = unknown> {
|
|
4
|
+
/** Called for each new row; default is undefined. */
|
|
5
|
+
readonly create: () => T;
|
|
6
|
+
}
|
|
7
|
+
/** Declare a JS value field. Pass a factory for independent mutable defaults. */
|
|
8
|
+
export declare function objectField<T = unknown>(create?: () => T): ObjectField<T>;
|
|
9
|
+
/** Mixed reference/numeric component schema. */
|
|
10
|
+
export type ObjectSchema = Record<string, ArrayConstructor | ObjectField>;
|
|
11
|
+
/** Value of one field of a mixed schema. */
|
|
12
|
+
export type ObjectValue<T> = T extends ObjectField<infer V> ? V : number;
|
|
13
|
+
/** Packed mixed fields, indexed with component.index(entity). */
|
|
14
|
+
export type ObjectFields<S extends ObjectSchema> = {
|
|
15
|
+
[K in keyof S]: S[K] extends ArrayConstructor ? InstanceType<S[K]> : ObjectValue<S[K]>[];
|
|
16
|
+
};
|
|
17
|
+
/** A query-compatible component with arbitrary JS fields beside packed numeric arrays. */
|
|
18
|
+
export declare class ObjectComponent<S extends ObjectSchema> extends Component<Record<never, never>> {
|
|
19
|
+
readonly fields: ObjectFields<S>;
|
|
20
|
+
private readonly objects;
|
|
21
|
+
/** @throws TypeError for an empty schema, invalid factory or unsupported numeric constructor. */
|
|
22
|
+
constructor(world: World, schema: S);
|
|
23
|
+
/** Add or update a row atomically after validation; omitted new object fields use their factories. */
|
|
24
|
+
add(entity: Entity, values?: Partial<{
|
|
25
|
+
[K in keyof S]: ObjectValue<S[K]>;
|
|
26
|
+
}>): number;
|
|
27
|
+
protected validateValues(values: Record<string, unknown>): void;
|
|
28
|
+
protected initializeRow(row: number, values?: Record<string, unknown>): void;
|
|
29
|
+
protected moveRow(row: number, last: number): void;
|
|
30
|
+
}
|
package/dist/objects.js
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { Component as e } from "./index.js";
|
|
2
|
+
//#region src/objects.ts
|
|
3
|
+
function t(e = (() => void 0)) {
|
|
4
|
+
if (typeof e != "function") throw TypeError("Invalid object field factory; pass a function");
|
|
5
|
+
return Object.freeze({ create: e });
|
|
6
|
+
}
|
|
7
|
+
var n = class extends e {
|
|
8
|
+
constructor(e, t) {
|
|
9
|
+
let n = [], r = {};
|
|
10
|
+
for (let [e, i] of Object.entries(t)) typeof i == "object" && i && typeof i.create == "function" ? n.push([e, i]) : Object.defineProperty(r, e, {
|
|
11
|
+
value: i,
|
|
12
|
+
enumerable: !0
|
|
13
|
+
});
|
|
14
|
+
if (!Object.keys(t).length) throw TypeError("Empty object schema; declare at least one field");
|
|
15
|
+
super(e, r, !0), this.objects = n;
|
|
16
|
+
for (let [e] of n) Object.defineProperty(this.fields, e, {
|
|
17
|
+
value: [],
|
|
18
|
+
enumerable: !0
|
|
19
|
+
});
|
|
20
|
+
e.attach(this);
|
|
21
|
+
}
|
|
22
|
+
add(e, t = {}) {
|
|
23
|
+
return super.add(e, t);
|
|
24
|
+
}
|
|
25
|
+
validateValues(e) {
|
|
26
|
+
let t = {};
|
|
27
|
+
for (let [n, r] of Object.entries(e)) {
|
|
28
|
+
if (!Object.hasOwn(this.fields, n)) throw RangeError("Unknown object component field; use a schema field");
|
|
29
|
+
Array.isArray(this.fields[n]) || Object.defineProperty(t, n, {
|
|
30
|
+
value: r,
|
|
31
|
+
enumerable: !0
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
super.validateValues(t);
|
|
35
|
+
}
|
|
36
|
+
initializeRow(e, t = {}) {
|
|
37
|
+
let n = this.objects.map(([e, n]) => Object.hasOwn(t, e) ? t[e] : n.create());
|
|
38
|
+
super.initializeRow(e);
|
|
39
|
+
for (let t = 0; t < this.objects.length; t++) this.fields[this.objects[t][0]][e] = n[t];
|
|
40
|
+
}
|
|
41
|
+
moveRow(e, t) {
|
|
42
|
+
super.moveRow(e, t);
|
|
43
|
+
for (let [n] of this.objects) {
|
|
44
|
+
let r = this.fields[n];
|
|
45
|
+
e !== t && (r[e] = r[t]), r.length = t;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
};
|
|
49
|
+
//#endregion
|
|
50
|
+
export { n as ObjectComponent, t as objectField };
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import type { NumericArray } from './index.js';
|
|
2
|
+
/** Stable packed shared component view for one system execution. */
|
|
3
|
+
export interface SharedComponentView {
|
|
4
|
+
/** Read the first count ids. Structural edits are confined to the calling thread between updates. */
|
|
5
|
+
readonly entities: Uint32Array;
|
|
6
|
+
/** Shared sparse row lookup by entity slot. Use sharedIndex to check the generation. */
|
|
7
|
+
readonly rows: Int32Array;
|
|
8
|
+
/** Slot spacing in entity ids. */
|
|
9
|
+
readonly stride: number;
|
|
10
|
+
/** Occupied packed rows. */
|
|
11
|
+
readonly count: number;
|
|
12
|
+
/** Shared numeric field arrays. Only declared writes may be mutated. */
|
|
13
|
+
readonly fields: Readonly<Record<string, NumericArray>>;
|
|
14
|
+
}
|
|
15
|
+
/** Resolve a live packed row from a worker view, rejecting stale generations. */
|
|
16
|
+
export declare function sharedIndex(view: SharedComponentView, entity: number): number;
|
|
17
|
+
/** Worker system invocation; retain neither views nor asynchronous work after the function settles. */
|
|
18
|
+
export interface ParallelContext {
|
|
19
|
+
/** Seconds in this update. */
|
|
20
|
+
readonly delta: number;
|
|
21
|
+
/** Accumulated successful update time, including this update. */
|
|
22
|
+
readonly elapsed: number;
|
|
23
|
+
/** Zero-based successful update index. */
|
|
24
|
+
readonly tick: number;
|
|
25
|
+
/** Only the named components declared in reads or writes. */
|
|
26
|
+
readonly components: Readonly<Record<string, SharedComponentView>>;
|
|
27
|
+
}
|
|
28
|
+
/** Browser Worker or an equivalent app-provided worker endpoint. */
|
|
29
|
+
export interface ParallelEndpoint {
|
|
30
|
+
/** Send a structured-clone message. Shared buffers are shared, never transferred. */
|
|
31
|
+
postMessage(message: unknown): void;
|
|
32
|
+
/** Receive messages or endpoint failures. */
|
|
33
|
+
addEventListener(type: string, listener: EventListener): void;
|
|
34
|
+
/** Detach a listener. */
|
|
35
|
+
removeEventListener(type: string, listener: EventListener): void;
|
|
36
|
+
}
|
|
37
|
+
/** Owned worker endpoint. Termination must stop all shared-memory writes before resolving. */
|
|
38
|
+
export interface ParallelWorker extends ParallelEndpoint {
|
|
39
|
+
/** Stop immediately. Promise-returning hosts are awaited before releasing the world lock. */
|
|
40
|
+
terminate(): void | Promise<unknown>;
|
|
41
|
+
}
|
|
42
|
+
/** Install the worker-side module dispatcher on a dedicated worker endpoint; returns its cleanup function. */
|
|
43
|
+
export declare function serveParallelSystems(endpoint: ParallelEndpoint): () => void;
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import { Component, World, type Entity, type NumericArray, type Schema, type ComponentStore } from './index.js';
|
|
2
|
+
import type { ParallelWorker } from './parallel-runtime.js';
|
|
3
|
+
export { serveParallelSystems, sharedIndex } from './parallel-runtime.js';
|
|
4
|
+
export type { ParallelWorker, ParallelEndpoint, ParallelContext, SharedComponentView } from './parallel-runtime.js';
|
|
5
|
+
/** A numeric component whose membership can change only between shared worker updates. */
|
|
6
|
+
export declare class SharedComponent<S extends Schema = Schema> extends Component<S> {
|
|
7
|
+
/** Shared entity-slot lookup, maintained before observers run. Resolve generations with sharedIndex. */
|
|
8
|
+
readonly rows: Int32Array;
|
|
9
|
+
private adding?;
|
|
10
|
+
private removing?;
|
|
11
|
+
/** Prefer SharedWorld.component/tag, which register this store for cleanup. */
|
|
12
|
+
constructor(world: SharedWorld, schema: S, tag?: boolean);
|
|
13
|
+
add(entity: Entity, values?: Partial<Record<keyof S, number>>): number;
|
|
14
|
+
remove(entity: Entity): boolean;
|
|
15
|
+
protected initializeRow(row: number, values?: Partial<Record<keyof S, number>>): void;
|
|
16
|
+
protected moveRow(row: number, last: number): void;
|
|
17
|
+
touch(entity: Entity): boolean;
|
|
18
|
+
}
|
|
19
|
+
/** Fixed-capacity world with SharedArrayBuffer fields and guarded structural mutation during worker updates. */
|
|
20
|
+
export declare class SharedWorld extends World {
|
|
21
|
+
/** Allocate fixed-length shared storage; requires cross-origin isolation in browsers. */
|
|
22
|
+
allocate<T extends NumericArray>(Type: new (length: number) => T, fill?: number): T;
|
|
23
|
+
create(): Entity;
|
|
24
|
+
destroy(entity: Entity): void;
|
|
25
|
+
reserve(count: number): void;
|
|
26
|
+
attach(store: {
|
|
27
|
+
remove(entity: Entity): unknown;
|
|
28
|
+
}): void;
|
|
29
|
+
detach(store: {
|
|
30
|
+
remove(entity: Entity): unknown;
|
|
31
|
+
}): void;
|
|
32
|
+
component<S extends Schema>(schema: S): SharedComponent<S>;
|
|
33
|
+
tag(): SharedComponent<Record<never, never>>;
|
|
34
|
+
}
|
|
35
|
+
/** One module system and its declared memory accesses. */
|
|
36
|
+
export interface ParallelSystem {
|
|
37
|
+
/** Unique system name. */
|
|
38
|
+
name: string;
|
|
39
|
+
/** Absolute module URL; native module imports are cached inside workers. */
|
|
40
|
+
module: string | URL;
|
|
41
|
+
/** Named function export. Default 'default'. */
|
|
42
|
+
exportName?: string;
|
|
43
|
+
/** Read-only component names. Default none. */
|
|
44
|
+
reads?: readonly string[];
|
|
45
|
+
/** Read/write component names. Default none. Conflicts serialize in dependency order. */
|
|
46
|
+
writes?: readonly string[];
|
|
47
|
+
/** Explicit successors. Default none. */
|
|
48
|
+
before?: readonly string[];
|
|
49
|
+
/** Explicit predecessors. Default none. */
|
|
50
|
+
after?: readonly string[];
|
|
51
|
+
}
|
|
52
|
+
/** Worker pool ownership, capacity and deadlines. */
|
|
53
|
+
export interface ParallelOptions {
|
|
54
|
+
/** Worker count, 1 to 32. Default 2. */
|
|
55
|
+
workers?: number;
|
|
56
|
+
/** Hard deadline per dispatched system in milliseconds. Range 1 to 2147483647; default 30000. Failure closes the schedule. */
|
|
57
|
+
timeout?: number;
|
|
58
|
+
/** Worker factory, for embedding or Node adapters. Default a dedicated browser worker. */
|
|
59
|
+
workerFactory?: () => ParallelWorker;
|
|
60
|
+
}
|
|
61
|
+
/** Conflict-aware worker system scheduler over stable shared numeric component rows. */
|
|
62
|
+
export declare class ParallelSchedule {
|
|
63
|
+
readonly world: SharedWorld;
|
|
64
|
+
private readonly systems;
|
|
65
|
+
private readonly stores;
|
|
66
|
+
private readonly slots;
|
|
67
|
+
private readonly workerCount;
|
|
68
|
+
private readonly timeout;
|
|
69
|
+
private readonly factory;
|
|
70
|
+
private stopping?;
|
|
71
|
+
private stopped;
|
|
72
|
+
private running;
|
|
73
|
+
private sequence;
|
|
74
|
+
private tick;
|
|
75
|
+
private elapsed;
|
|
76
|
+
private failure?;
|
|
77
|
+
private terminationFailed;
|
|
78
|
+
/** @throws RangeError for invalid worker count/deadline; TypeError for nonshared or foreign components. */
|
|
79
|
+
constructor(world: SharedWorld, components: Readonly<Record<string, ComponentStore>>, options?: ParallelOptions);
|
|
80
|
+
/** Add a module system. Missing dependency names/cycles reject when compiling order or running an update. */
|
|
81
|
+
add(system: ParallelSystem): this;
|
|
82
|
+
private graph;
|
|
83
|
+
private levels;
|
|
84
|
+
/** Return concurrent groups after explicit dependencies and read/write hazards are applied. */
|
|
85
|
+
order(): string[][];
|
|
86
|
+
private slot;
|
|
87
|
+
private dispatch;
|
|
88
|
+
/**
|
|
89
|
+
* Run independent systems concurrently and serialize declared conflicts. Locks structure until every worker settles.
|
|
90
|
+
* Callers must not write raw shared arrays or retain worker tasks across the returned promise.
|
|
91
|
+
* After success, written components are touched for change trackers. Failure/abort terminates all workers,
|
|
92
|
+
* closes this schedule and can leave partial field writes; no system is silently repeated.
|
|
93
|
+
* @throws MargoError 'state' for concurrent updates, worker failures or cycles, 'timeout' for deadlines, 'disposed' after stop.
|
|
94
|
+
*/
|
|
95
|
+
update(delta: number, { signal }?: {
|
|
96
|
+
signal?: AbortSignal;
|
|
97
|
+
}): Promise<void>;
|
|
98
|
+
/** Terminate owned workers and reject pending calls; await termination before reusing shared fields. Idempotent. */
|
|
99
|
+
stop(): Promise<void>;
|
|
100
|
+
[Symbol.asyncDispose](): Promise<void>;
|
|
101
|
+
private check;
|
|
102
|
+
}
|
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 {};
|