@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/schedule.js
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
import { MargoError as e } from "@margoengine/math/errors";
|
|
2
|
+
//#region src/schedule.ts
|
|
3
|
+
var t = (e, t) => {
|
|
4
|
+
if (e === void 0) return [];
|
|
5
|
+
if (!Array.isArray(e) || e.some((e) => typeof e != "string")) throw TypeError(`System ${t} is not a list of names; pass an array of system names`);
|
|
6
|
+
return [...e];
|
|
7
|
+
};
|
|
8
|
+
function n(t, n) {
|
|
9
|
+
let r = new Map(t.map((e) => [e, 0]));
|
|
10
|
+
for (let e of t) for (let t of n.get(e) ?? []) r.set(t, r.get(t) + 1);
|
|
11
|
+
let i = [];
|
|
12
|
+
for (; i.length < t.length;) {
|
|
13
|
+
let a = t.find((e) => r.get(e) === 0);
|
|
14
|
+
if (!a) {
|
|
15
|
+
let n = t.filter((e) => r.get(e) > 0).map((e) => e.name);
|
|
16
|
+
throw new e("state", `System order has a cycle among ${n.join(", ")}; remove a before or after`);
|
|
17
|
+
}
|
|
18
|
+
r.set(a, -1), i.push(a);
|
|
19
|
+
for (let e of n.get(a) ?? []) r.set(e, r.get(e) - 1);
|
|
20
|
+
}
|
|
21
|
+
return i;
|
|
22
|
+
}
|
|
23
|
+
var r = class {
|
|
24
|
+
constructor({ step: e = 1 / 60, maxSteps: t = 8 } = {}) {
|
|
25
|
+
if (this.dropped = 0, this.entries = /* @__PURE__ */ new Map(), this.framePhase = [], this.accumulator = 0, this.steps = 0, this.frames = 0, this.clock = 0, this.running = !1, this.time = {
|
|
26
|
+
delta: 0,
|
|
27
|
+
elapsed: 0,
|
|
28
|
+
tick: 0,
|
|
29
|
+
alpha: 0,
|
|
30
|
+
fixed: !1
|
|
31
|
+
}, !Number.isFinite(e) || e <= 0) throw RangeError("Invalid schedule step; use a finite number of seconds above 0, e.g. 1 / 60");
|
|
32
|
+
if (!Number.isSafeInteger(t) || t < 1) throw RangeError("Invalid schedule maxSteps; use a positive integer, e.g. 8");
|
|
33
|
+
this.step = e, this.maxSteps = t;
|
|
34
|
+
}
|
|
35
|
+
add(e, n, r = {}) {
|
|
36
|
+
if (typeof e != "string" || !e) throw TypeError("Invalid system name; pass a non-empty string");
|
|
37
|
+
if (this.entries.has(e)) throw TypeError(`System ${e} already exists; remove it or use another name`);
|
|
38
|
+
if (typeof n != "function") throw TypeError("Invalid system; pass a function");
|
|
39
|
+
let { when: i, fixed: a = !1 } = r;
|
|
40
|
+
if (i !== void 0 && typeof i != "function") throw TypeError("Invalid system condition; pass a function that returns a boolean");
|
|
41
|
+
let o = t(r.before, "before"), s = t(r.after, "after");
|
|
42
|
+
return this.entries.set(e, {
|
|
43
|
+
name: e,
|
|
44
|
+
run: n,
|
|
45
|
+
before: o,
|
|
46
|
+
after: s,
|
|
47
|
+
when: i,
|
|
48
|
+
fixed: !!a,
|
|
49
|
+
removed: !1
|
|
50
|
+
}), this.fixedPhase = void 0, this;
|
|
51
|
+
}
|
|
52
|
+
remove(e) {
|
|
53
|
+
let t = this.entries.get(e);
|
|
54
|
+
return t ? (t.removed = !0, this.entries.delete(e), this.fixedPhase = void 0, !0) : !1;
|
|
55
|
+
}
|
|
56
|
+
has(e) {
|
|
57
|
+
return this.entries.has(e);
|
|
58
|
+
}
|
|
59
|
+
order() {
|
|
60
|
+
return this.resolve(), [...this.fixedPhase, ...this.framePhase].map((e) => e.name);
|
|
61
|
+
}
|
|
62
|
+
update(t) {
|
|
63
|
+
if (this.running) throw new e("state", "Schedule is already updating; do not call update from a system");
|
|
64
|
+
if (!Number.isFinite(t) || t < 0) throw RangeError("Invalid schedule delta; pass a finite number of seconds, 0 or more");
|
|
65
|
+
this.resolve();
|
|
66
|
+
let n = this.step, r = this.time, i = this.fixedPhase, a = this.framePhase;
|
|
67
|
+
this.running = !0;
|
|
68
|
+
try {
|
|
69
|
+
this.accumulator += t;
|
|
70
|
+
let e = 0;
|
|
71
|
+
for (r.delta = n, r.alpha = 0, r.fixed = !0; this.accumulator >= n && e < this.maxSteps;) this.accumulator -= n, e++, r.tick = ++this.steps, r.elapsed = this.steps * n, this.pass(i);
|
|
72
|
+
if (this.dropped = 0, this.accumulator >= n) {
|
|
73
|
+
let e = this.accumulator % n;
|
|
74
|
+
this.dropped = this.accumulator - e, this.accumulator = e;
|
|
75
|
+
}
|
|
76
|
+
return this.clock += t, r.delta = t, r.elapsed = this.clock, r.tick = ++this.frames, r.alpha = this.accumulator / n, r.fixed = !1, this.pass(a), e;
|
|
77
|
+
} finally {
|
|
78
|
+
this.running = !1;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
pass(e) {
|
|
82
|
+
let t = this.time;
|
|
83
|
+
for (let n = 0; n < e.length; n++) {
|
|
84
|
+
let r = e[n];
|
|
85
|
+
!r.removed && (!r.when || r.when(t)) && r.run(t);
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
resolve() {
|
|
89
|
+
if (this.fixedPhase) return;
|
|
90
|
+
let t = /* @__PURE__ */ new Map(), r = (n, r) => {
|
|
91
|
+
if (n.fixed && !r.fixed) return;
|
|
92
|
+
if (!n.fixed && r.fixed) throw new e("state", `Frame system ${n.name} cannot run before fixed system ${r.name}; the fixed phase runs first, so drop the order or make both fixed`);
|
|
93
|
+
let i = t.get(n);
|
|
94
|
+
i ? i.push(r) : t.set(n, [r]);
|
|
95
|
+
}, i = (t, n) => {
|
|
96
|
+
let r = this.entries.get(t);
|
|
97
|
+
if (!r) throw new e("state", `System ${n.name} is ordered against ${t}, which is missing; add it`);
|
|
98
|
+
return r;
|
|
99
|
+
}, a = [...this.entries.values()];
|
|
100
|
+
for (let e of a) {
|
|
101
|
+
for (let t of e.before) r(e, i(t, e));
|
|
102
|
+
for (let t of e.after) r(i(t, e), e);
|
|
103
|
+
}
|
|
104
|
+
let o = n(a.filter((e) => !e.fixed), t);
|
|
105
|
+
this.fixedPhase = n(a.filter((e) => e.fixed), t), this.framePhase = o;
|
|
106
|
+
}
|
|
107
|
+
};
|
|
108
|
+
//#endregion
|
|
109
|
+
export { r as Schedule };
|
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
import type { Entity, World } from './index.js';
|
|
2
|
+
import type { Schedule } from './schedule.js';
|
|
3
|
+
/** Value kinds of a script attribute. `vec2`, `vec3` and `vec4` hold number arrays; `color` is `[r, g, b, a]` in 0..1; `asset` is an id string. */
|
|
4
|
+
export type AttributeType = 'number' | 'boolean' | 'string' | 'enum' | 'vec2' | 'vec3' | 'vec4' | 'color' | 'entity' | 'asset';
|
|
5
|
+
/** One declared attribute. `default` is validated when the script is defined. */
|
|
6
|
+
export interface AttributeSpec {
|
|
7
|
+
type: AttributeType;
|
|
8
|
+
/** Default value. Default: 0, false, '', the first option, zeros, [1, 1, 1, 1] for color, or null for entity and asset. */
|
|
9
|
+
default?: unknown;
|
|
10
|
+
/** Smallest number, or smallest vector/color element. Default none. */
|
|
11
|
+
min?: number;
|
|
12
|
+
/** Largest number, or largest vector/color element. Default none. */
|
|
13
|
+
max?: number;
|
|
14
|
+
/** Allowed values of an `enum` (strings or numbers). Required for `enum`. */
|
|
15
|
+
options?: readonly (string | number)[];
|
|
16
|
+
/** Label for an inspector. Default: the attribute name. */
|
|
17
|
+
title?: string;
|
|
18
|
+
/** Asset kind hint for an inspector ('texture', 'model'...). Default none. */
|
|
19
|
+
assetKind?: string;
|
|
20
|
+
}
|
|
21
|
+
/** Attribute declarations by name. */
|
|
22
|
+
export type AttributeSpecs = Record<string, AttributeSpec>;
|
|
23
|
+
/** A live attribute value set (getters and setters that validate). */
|
|
24
|
+
export type AttributeValues = Record<string, any>;
|
|
25
|
+
/** A running script. Hooks are called with it as `this`. */
|
|
26
|
+
export interface ScriptInstance {
|
|
27
|
+
readonly entity: Entity;
|
|
28
|
+
readonly world: World;
|
|
29
|
+
readonly type: ScriptType;
|
|
30
|
+
/** Validated attributes; assigning one runs `onAttributeChange`. */
|
|
31
|
+
readonly attributes: AttributeValues;
|
|
32
|
+
/** Free-form state the script owns; it survives a hot reload. */
|
|
33
|
+
state: Record<string, any>;
|
|
34
|
+
/** True while the instance receives updates. Assign to enable or disable it. */
|
|
35
|
+
enabled: boolean;
|
|
36
|
+
/** True after `initialize` ran, until `destroy`. */
|
|
37
|
+
readonly initialized: boolean;
|
|
38
|
+
}
|
|
39
|
+
/** Lifecycle hooks of a script. All optional. */
|
|
40
|
+
export interface ScriptHooks {
|
|
41
|
+
/** Once, on the first update after the instance is added and enabled. `onEnable` runs just before it. */
|
|
42
|
+
initialize?(this: ScriptInstance): void;
|
|
43
|
+
/** Once, after every `initialize` of that batch has run. */
|
|
44
|
+
postInitialize?(this: ScriptInstance): void;
|
|
45
|
+
/** Every `Scripts.update`, with the frame time. */
|
|
46
|
+
update?(this: ScriptInstance, dt: number): void;
|
|
47
|
+
/** Every `Scripts.update`, after all `update` hooks. */
|
|
48
|
+
postUpdate?(this: ScriptInstance, dt: number): void;
|
|
49
|
+
/** Every `Scripts.fixedUpdate`, with the fixed step. */
|
|
50
|
+
fixedUpdate?(this: ScriptInstance, step: number): void;
|
|
51
|
+
onEnable?(this: ScriptInstance): void;
|
|
52
|
+
onDisable?(this: ScriptInstance): void;
|
|
53
|
+
/** An attribute was assigned a different value. */
|
|
54
|
+
onAttributeChange?(this: ScriptInstance, name: string, value: any, previous: any): void;
|
|
55
|
+
/** Instance removed, entity destroyed, or registry disposed; `onDisable` ran first when it was enabled. */
|
|
56
|
+
destroy?(this: ScriptInstance): void;
|
|
57
|
+
/** Hot reload: called on the instance of the NEW type with the type it replaces, to migrate `state`. */
|
|
58
|
+
swap?(this: ScriptInstance, previous: ScriptType): void;
|
|
59
|
+
}
|
|
60
|
+
/** Definition passed to {@link defineScript}. */
|
|
61
|
+
export interface ScriptDefinition extends ScriptHooks {
|
|
62
|
+
/** Unique name within a registry; hot reload matches by it. */
|
|
63
|
+
name: string;
|
|
64
|
+
attributes?: AttributeSpecs;
|
|
65
|
+
/** Run order across instances, lowest first, ties by order of `add`. Default 0. */
|
|
66
|
+
priority?: number;
|
|
67
|
+
}
|
|
68
|
+
/** A defined script type. */
|
|
69
|
+
export interface ScriptType extends ScriptHooks {
|
|
70
|
+
readonly name: string;
|
|
71
|
+
readonly priority: number;
|
|
72
|
+
readonly attributes: Readonly<Record<string, Readonly<AttributeSpec & {
|
|
73
|
+
title: string;
|
|
74
|
+
}>>>;
|
|
75
|
+
}
|
|
76
|
+
/** The hook that failed, for {@link ScriptsOptions.onError}. */
|
|
77
|
+
export type ScriptHook = keyof ScriptHooks;
|
|
78
|
+
/** Settings of {@link Scripts}. */
|
|
79
|
+
export interface ScriptsOptions {
|
|
80
|
+
/**
|
|
81
|
+
* Called for every error a script throws, so one failing script never stops the others. Default: errors are
|
|
82
|
+
* collected and rethrown after the pass as one MargoError `'failed'` whose `cause` is the first.
|
|
83
|
+
*/
|
|
84
|
+
onError?: (error: unknown, info: {
|
|
85
|
+
script: ScriptInstance;
|
|
86
|
+
hook: ScriptHook;
|
|
87
|
+
}) => void;
|
|
88
|
+
}
|
|
89
|
+
/** Options of {@link Scripts.add}. */
|
|
90
|
+
export interface AddScriptOptions {
|
|
91
|
+
/** Attribute values; others use defaults. */
|
|
92
|
+
values?: Record<string, unknown>;
|
|
93
|
+
/** Start enabled. Default true. */
|
|
94
|
+
enabled?: boolean;
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* Declare a script type: typed attributes plus lifecycle hooks. Register it with {@link Scripts.register}.
|
|
98
|
+
* @throws TypeError for a missing name, an unknown attribute type or a hook that is not a function.
|
|
99
|
+
* @throws RangeError for a default outside its own min/max or options.
|
|
100
|
+
*/
|
|
101
|
+
export declare function defineScript(def: ScriptDefinition): ScriptType;
|
|
102
|
+
/**
|
|
103
|
+
* Script components for a {@link World}: add scripts to entities, run their hooks, hot reload them. One registry per
|
|
104
|
+
* world; nothing is global. `using scripts = new Scripts(world)` destroys every instance at scope end.
|
|
105
|
+
*/
|
|
106
|
+
export declare class Scripts {
|
|
107
|
+
readonly world: World;
|
|
108
|
+
private readonly options;
|
|
109
|
+
private readonly types;
|
|
110
|
+
private all;
|
|
111
|
+
private readonly byEntity;
|
|
112
|
+
private pending;
|
|
113
|
+
private seq;
|
|
114
|
+
private errors;
|
|
115
|
+
private busy;
|
|
116
|
+
private disposed;
|
|
117
|
+
private readonly store;
|
|
118
|
+
constructor(world: World, options?: ScriptsOptions);
|
|
119
|
+
/** Register a script type; it must be registered before `add`. @throws TypeError when the name is taken (use {@link Scripts.reload}). */
|
|
120
|
+
register(type: ScriptType): this;
|
|
121
|
+
/** The registered type of that name, or undefined. */
|
|
122
|
+
get(name: string): ScriptType | undefined;
|
|
123
|
+
/** Inspector schema of every registered type, as plain JSON-safe data. */
|
|
124
|
+
schema(): {
|
|
125
|
+
name: string;
|
|
126
|
+
priority: number;
|
|
127
|
+
attributes: {
|
|
128
|
+
name: string;
|
|
129
|
+
type: AttributeType;
|
|
130
|
+
default: unknown;
|
|
131
|
+
title: string;
|
|
132
|
+
}[];
|
|
133
|
+
}[];
|
|
134
|
+
/**
|
|
135
|
+
* Attach a script to an entity, after the scripts it already has. Its hooks start on the next update or fixedUpdate.
|
|
136
|
+
* @throws MargoError `'state'` for a stale entity, an unregistered type or a disposed registry.
|
|
137
|
+
* @throws RangeError for an unknown or invalid attribute value.
|
|
138
|
+
*/
|
|
139
|
+
add(entity: Entity, type: ScriptType | string, { values, enabled }?: AddScriptOptions): ScriptInstance;
|
|
140
|
+
/** Instances on an entity, in the order they were added. */
|
|
141
|
+
on(entity: Entity): readonly ScriptInstance[];
|
|
142
|
+
/**
|
|
143
|
+
* Remove one instance, or every script of an entity (only those of `type` when given). Each runs `onDisable` (when
|
|
144
|
+
* enabled) then `destroy` if it had been initialised. Returns the number removed.
|
|
145
|
+
*/
|
|
146
|
+
remove(target: ScriptInstance | Entity, type?: ScriptType | string): number;
|
|
147
|
+
/** Run pending `onEnable`, `initialize` and `postInitialize` hooks now; `update` and `fixedUpdate` call this first. */
|
|
148
|
+
flush(): void;
|
|
149
|
+
/** One frame: flush, then `update` of every enabled instance, then `postUpdate`. @throws RangeError for a negative or non-finite `dt`. */
|
|
150
|
+
update(dt: number): void;
|
|
151
|
+
/** One fixed step: flush, then `fixedUpdate` of every enabled instance. */
|
|
152
|
+
fixedUpdate(step: number): void;
|
|
153
|
+
/** Add a frame system `scripts` (update, postUpdate) and a fixed system `scripts.fixed` (fixedUpdate) to a {@link Schedule}. */
|
|
154
|
+
install(schedule: Schedule, options?: {
|
|
155
|
+
before?: readonly string[];
|
|
156
|
+
after?: readonly string[];
|
|
157
|
+
}): this;
|
|
158
|
+
/**
|
|
159
|
+
* Hot reload: replace the registered type of the same name with a new implementation. Instances stay, with their
|
|
160
|
+
* attribute values (kept where the attribute still exists and is valid, otherwise reset to the new default), `state`,
|
|
161
|
+
* enabled flag and order. The new type's `swap(previous)` runs on each to migrate state. `initialize` runs again
|
|
162
|
+
* only with `reinitialize: true` (after `onDisable` and `destroy` of the old version, with `state` cleared).
|
|
163
|
+
* A type that is not registered yet is just registered. Returns the number of instances swapped.
|
|
164
|
+
*/
|
|
165
|
+
reload(next: ScriptType, { reinitialize }?: {
|
|
166
|
+
reinitialize?: boolean;
|
|
167
|
+
}): number;
|
|
168
|
+
/** Destroy every instance and detach from the world. Safe to call twice. */
|
|
169
|
+
[Symbol.dispose](): void;
|
|
170
|
+
/** Same as `[Symbol.dispose]()`. */
|
|
171
|
+
dispose(): void;
|
|
172
|
+
private live;
|
|
173
|
+
private sortAll;
|
|
174
|
+
private shape;
|
|
175
|
+
private setEnabled;
|
|
176
|
+
private kill;
|
|
177
|
+
private removeAll;
|
|
178
|
+
private call;
|
|
179
|
+
private step;
|
|
180
|
+
/** Run `body`; errors collected without an onError handler are rethrown once, at the end of the outermost pass. */
|
|
181
|
+
private pass;
|
|
182
|
+
}
|
package/dist/scripts.js
ADDED
|
@@ -0,0 +1,278 @@
|
|
|
1
|
+
import { MargoError as e } from "@margoengine/math/errors";
|
|
2
|
+
import { hexColor as t } from "@margoengine/math/color";
|
|
3
|
+
//#region src/scripts.ts
|
|
4
|
+
var n = {
|
|
5
|
+
vec2: 2,
|
|
6
|
+
vec3: 3,
|
|
7
|
+
vec4: 4,
|
|
8
|
+
color: 4
|
|
9
|
+
}, r = [
|
|
10
|
+
"number",
|
|
11
|
+
"boolean",
|
|
12
|
+
"string",
|
|
13
|
+
"enum",
|
|
14
|
+
"entity",
|
|
15
|
+
"asset",
|
|
16
|
+
...Object.keys(n)
|
|
17
|
+
], i = [
|
|
18
|
+
"initialize",
|
|
19
|
+
"postInitialize",
|
|
20
|
+
"update",
|
|
21
|
+
"postUpdate",
|
|
22
|
+
"fixedUpdate",
|
|
23
|
+
"onEnable",
|
|
24
|
+
"onDisable",
|
|
25
|
+
"onAttributeChange",
|
|
26
|
+
"destroy",
|
|
27
|
+
"swap"
|
|
28
|
+
], a = (e) => e.length <= 7 ? t(e) : void 0, o = (e, t, n) => /* @__PURE__ */ RangeError(`Invalid ${t.type} attribute ${e}: ${n}`);
|
|
29
|
+
function s(e, t, r) {
|
|
30
|
+
let { type: i, min: s = -Infinity, max: c = Infinity } = t;
|
|
31
|
+
if (i === "number") {
|
|
32
|
+
if (typeof r != "number" || !Number.isFinite(r)) throw o(e, t, "use a finite number");
|
|
33
|
+
if (r < s || r > c) throw o(e, t, `${r} is outside ${s}..${c}`);
|
|
34
|
+
return r;
|
|
35
|
+
}
|
|
36
|
+
if (i === "boolean") {
|
|
37
|
+
if (typeof r != "boolean") throw o(e, t, "use true or false");
|
|
38
|
+
return r;
|
|
39
|
+
}
|
|
40
|
+
if (i === "string") {
|
|
41
|
+
if (typeof r != "string") throw o(e, t, "use a string");
|
|
42
|
+
return r;
|
|
43
|
+
}
|
|
44
|
+
if (i === "enum") {
|
|
45
|
+
if (!t.options.includes(r)) throw o(e, t, `use one of ${t.options.join(", ")}`);
|
|
46
|
+
return r;
|
|
47
|
+
}
|
|
48
|
+
if (i === "entity") {
|
|
49
|
+
if (r !== null && !(Number.isInteger(r) && r >= 0)) throw o(e, t, "use an entity id or null");
|
|
50
|
+
return r;
|
|
51
|
+
}
|
|
52
|
+
if (i === "asset") {
|
|
53
|
+
if (r !== null && (typeof r != "string" || !r)) throw o(e, t, "use an asset id string or null");
|
|
54
|
+
return r;
|
|
55
|
+
}
|
|
56
|
+
let l = n[i], u = i === "color" && typeof r == "string" ? a(r) : r;
|
|
57
|
+
if (!(Array.isArray(u) || ArrayBuffer.isView(u)) || u.length !== l) throw o(e, t, `use ${l} numbers${i === "color" ? " or a #rrggbb string" : ""}`);
|
|
58
|
+
let d = Array.from(u), f = i === "color" ? Math.max(s, 0) : s, p = i === "color" ? Math.min(c, 1) : c;
|
|
59
|
+
for (let n of d) {
|
|
60
|
+
if (typeof n != "number" || !Number.isFinite(n)) throw o(e, t, "use finite numbers");
|
|
61
|
+
if (n < f || n > p) throw o(e, t, `${n} is outside ${f}..${p}`);
|
|
62
|
+
}
|
|
63
|
+
return d;
|
|
64
|
+
}
|
|
65
|
+
var c = (e, t) => Array.isArray(e) && Array.isArray(t) ? e.length === t.length && e.every((e, n) => e === t[n]) : e === t, l = (e) => Array.isArray(e) ? [...e] : e;
|
|
66
|
+
function u(e) {
|
|
67
|
+
switch (e.type) {
|
|
68
|
+
case "number": return 0;
|
|
69
|
+
case "boolean": return !1;
|
|
70
|
+
case "string": return "";
|
|
71
|
+
case "enum": return e.options[0];
|
|
72
|
+
case "color": return [
|
|
73
|
+
1,
|
|
74
|
+
1,
|
|
75
|
+
1,
|
|
76
|
+
1
|
|
77
|
+
];
|
|
78
|
+
case "entity":
|
|
79
|
+
case "asset": return null;
|
|
80
|
+
default: return Array(n[e.type]).fill(0);
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
function d(e) {
|
|
84
|
+
if (!e || typeof e.name != "string" || !e.name) throw TypeError("Invalid script; give it a non-empty name");
|
|
85
|
+
let t = {};
|
|
86
|
+
for (let [n, i] of Object.entries(e.attributes ?? {})) {
|
|
87
|
+
if (!i || !r.includes(i.type)) throw TypeError(`Unknown attribute type for ${e.name}.${n}; use number, boolean, string, enum, vec2, vec3, vec4, color, entity or asset`);
|
|
88
|
+
if (i.type === "enum" && (!Array.isArray(i.options) || !i.options.length)) throw TypeError(`Enum attribute ${e.name}.${n} needs a non-empty options list`);
|
|
89
|
+
let a = {
|
|
90
|
+
...i,
|
|
91
|
+
title: i.title ?? n
|
|
92
|
+
};
|
|
93
|
+
a.default = s(n, a, i.default === void 0 ? u(a) : i.default), t[n] = Object.freeze(a);
|
|
94
|
+
}
|
|
95
|
+
let n = {
|
|
96
|
+
name: e.name,
|
|
97
|
+
priority: e.priority ?? 0,
|
|
98
|
+
attributes: Object.freeze(t)
|
|
99
|
+
};
|
|
100
|
+
for (let t of i) if (e[t] !== void 0) {
|
|
101
|
+
if (typeof e[t] != "function") throw TypeError(`Script ${e.name} hook ${t} is not a function; pass a function or leave the hook out`);
|
|
102
|
+
n[t] = e[t];
|
|
103
|
+
}
|
|
104
|
+
return Object.freeze(n);
|
|
105
|
+
}
|
|
106
|
+
var f = class {
|
|
107
|
+
constructor(e, t = {}) {
|
|
108
|
+
this.world = e, this.options = t, this.types = /* @__PURE__ */ new Map(), this.all = [], this.byEntity = /* @__PURE__ */ new Map(), this.pending = [], this.seq = 0, this.errors = [], this.busy = !1, this.disposed = !1, this.store = { remove: (e) => this.removeAll(e) }, e.attach(this.store);
|
|
109
|
+
}
|
|
110
|
+
register(e) {
|
|
111
|
+
if (this.live(), this.types.has(e.name)) throw TypeError(`Script ${e.name} is already registered; use reload to replace it`);
|
|
112
|
+
return this.types.set(e.name, e), this;
|
|
113
|
+
}
|
|
114
|
+
get(e) {
|
|
115
|
+
return this.types.get(e);
|
|
116
|
+
}
|
|
117
|
+
schema() {
|
|
118
|
+
return [...this.types.values()].map((e) => ({
|
|
119
|
+
name: e.name,
|
|
120
|
+
priority: e.priority,
|
|
121
|
+
attributes: Object.entries(e.attributes).map(([e, t]) => JSON.parse(JSON.stringify({
|
|
122
|
+
name: e,
|
|
123
|
+
...t
|
|
124
|
+
})))
|
|
125
|
+
}));
|
|
126
|
+
}
|
|
127
|
+
add(t, n, { values: r = {}, enabled: i = !0 } = {}) {
|
|
128
|
+
this.live(), this.world.check(t);
|
|
129
|
+
let a = typeof n == "string" ? n : n.name, o = this.types.get(a);
|
|
130
|
+
if (!o) throw new e("state", `Script ${a} is not registered; call register first`);
|
|
131
|
+
for (let e of Object.keys(r)) if (!(e in o.attributes)) throw RangeError(`Unknown attribute ${e} for script ${o.name}; declare it in attributes`);
|
|
132
|
+
let c = {
|
|
133
|
+
entity: t,
|
|
134
|
+
world: this.world,
|
|
135
|
+
type: o,
|
|
136
|
+
state: {},
|
|
137
|
+
attributes: {},
|
|
138
|
+
values: {},
|
|
139
|
+
seq: this.seq++,
|
|
140
|
+
dead: !1,
|
|
141
|
+
isInitialized: !1,
|
|
142
|
+
isEnabled: !!i
|
|
143
|
+
};
|
|
144
|
+
for (let [e, t] of Object.entries(o.attributes)) c.values[e] = s(e, t, e in r ? r[e] : t.default);
|
|
145
|
+
this.shape(c), Object.defineProperties(c, {
|
|
146
|
+
enabled: {
|
|
147
|
+
enumerable: !0,
|
|
148
|
+
get: () => c.isEnabled,
|
|
149
|
+
set: (e) => this.setEnabled(c, !!e)
|
|
150
|
+
},
|
|
151
|
+
initialized: {
|
|
152
|
+
enumerable: !0,
|
|
153
|
+
get: () => c.isInitialized
|
|
154
|
+
}
|
|
155
|
+
}), this.all.push(c), this.sortAll();
|
|
156
|
+
let l = this.byEntity.get(t);
|
|
157
|
+
return l ? l.push(c) : this.byEntity.set(t, [c]), this.pending.push(c), c;
|
|
158
|
+
}
|
|
159
|
+
on(e) {
|
|
160
|
+
return this.byEntity.get(e) ?? [];
|
|
161
|
+
}
|
|
162
|
+
remove(e, t) {
|
|
163
|
+
if (this.live(), typeof e != "number") return +!!this.kill(e);
|
|
164
|
+
let n = typeof t == "string" ? t : t?.name, r = (this.byEntity.get(e) ?? []).filter((e) => n === void 0 || e.type.name === n);
|
|
165
|
+
return this.pass(() => r.forEach((e) => this.kill(e))), r.length;
|
|
166
|
+
}
|
|
167
|
+
flush() {
|
|
168
|
+
this.live(), this.pass(() => {
|
|
169
|
+
for (;;) {
|
|
170
|
+
let e = this.pending.filter((e) => !e.dead && e.isEnabled);
|
|
171
|
+
if (!e.length) break;
|
|
172
|
+
this.pending = this.pending.filter((e) => !e.dead && !e.isEnabled), e.sort((e, t) => e.type.priority - t.type.priority || e.seq - t.seq);
|
|
173
|
+
for (let t of e) t.dead || t.isInitialized || (this.call(t, "onEnable"), t.isInitialized = !0, this.call(t, "initialize"));
|
|
174
|
+
for (let t of e) t.dead || this.call(t, "postInitialize");
|
|
175
|
+
}
|
|
176
|
+
});
|
|
177
|
+
}
|
|
178
|
+
update(e) {
|
|
179
|
+
this.step(e, ["update", "postUpdate"]);
|
|
180
|
+
}
|
|
181
|
+
fixedUpdate(e) {
|
|
182
|
+
this.step(e, ["fixedUpdate"]);
|
|
183
|
+
}
|
|
184
|
+
install(e, t = {}) {
|
|
185
|
+
return e.add("scripts.fixed", (e) => this.fixedUpdate(e.delta), { fixed: !0 }), e.add("scripts", (e) => this.update(e.delta), t), this;
|
|
186
|
+
}
|
|
187
|
+
reload(e, { reinitialize: t = !1 } = {}) {
|
|
188
|
+
this.live();
|
|
189
|
+
let n = this.types.get(e.name);
|
|
190
|
+
if (this.types.set(e.name, e), !n) return 0;
|
|
191
|
+
let r = 0;
|
|
192
|
+
return this.pass(() => {
|
|
193
|
+
for (let i of this.all.filter((e) => e.type === n)) {
|
|
194
|
+
let a = t && i.isInitialized;
|
|
195
|
+
a && (i.isEnabled && this.call(i, "onDisable"), this.call(i, "destroy"));
|
|
196
|
+
let o = i.values;
|
|
197
|
+
i.type = e, i.values = {};
|
|
198
|
+
for (let [t, n] of Object.entries(e.attributes)) try {
|
|
199
|
+
i.values[t] = t in o ? s(t, n, o[t]) : l(n.default);
|
|
200
|
+
} catch {
|
|
201
|
+
i.values[t] = l(n.default);
|
|
202
|
+
}
|
|
203
|
+
this.shape(i), a && (i.isInitialized = !1, i.state = {}, this.pending.push(i)), this.call(i, "swap", n), r++;
|
|
204
|
+
}
|
|
205
|
+
this.sortAll();
|
|
206
|
+
}), r;
|
|
207
|
+
}
|
|
208
|
+
[Symbol.dispose]() {
|
|
209
|
+
this.disposed || (this.disposed = !0, this.world.detach(this.store), this.pass(() => [...this.all].forEach((e) => this.kill(e))));
|
|
210
|
+
}
|
|
211
|
+
dispose() {
|
|
212
|
+
this[Symbol.dispose]();
|
|
213
|
+
}
|
|
214
|
+
live() {
|
|
215
|
+
if (this.disposed) throw new e("disposed", "Scripts is disposed; create a new Scripts");
|
|
216
|
+
}
|
|
217
|
+
sortAll() {
|
|
218
|
+
this.all.sort((e, t) => e.type.priority - t.type.priority || e.seq - t.seq);
|
|
219
|
+
}
|
|
220
|
+
shape(e) {
|
|
221
|
+
let t = {};
|
|
222
|
+
for (let [n, r] of Object.entries(e.type.attributes)) Object.defineProperty(t, n, {
|
|
223
|
+
enumerable: !0,
|
|
224
|
+
get: () => l(e.values[n]),
|
|
225
|
+
set: (t) => {
|
|
226
|
+
let i = s(n, r, t), a = e.values[n];
|
|
227
|
+
c(a, i) || (e.values[n] = i, e.isInitialized && !e.dead && this.pass(() => this.call(e, "onAttributeChange", n, l(i), l(a))));
|
|
228
|
+
}
|
|
229
|
+
});
|
|
230
|
+
e.attributes = Object.freeze(t);
|
|
231
|
+
}
|
|
232
|
+
setEnabled(e, t) {
|
|
233
|
+
e.dead || e.isEnabled === t || (e.isEnabled = t, e.isInitialized ? this.pass(() => this.call(e, t ? "onEnable" : "onDisable")) : t && !this.pending.includes(e) && this.pending.push(e));
|
|
234
|
+
}
|
|
235
|
+
kill(e) {
|
|
236
|
+
if (e.dead) return !1;
|
|
237
|
+
e.dead = !0, this.all = this.all.filter((t) => t !== e), this.pending = this.pending.filter((t) => t !== e);
|
|
238
|
+
let t = (this.byEntity.get(e.entity) ?? []).filter((t) => t !== e);
|
|
239
|
+
return t.length ? this.byEntity.set(e.entity, t) : this.byEntity.delete(e.entity), e.isInitialized &&= (this.pass(() => {
|
|
240
|
+
e.isEnabled && this.call(e, "onDisable"), this.call(e, "destroy");
|
|
241
|
+
}), !1), !0;
|
|
242
|
+
}
|
|
243
|
+
removeAll(e) {
|
|
244
|
+
this.pass(() => [...this.byEntity.get(e) ?? []].forEach((e) => this.kill(e)));
|
|
245
|
+
}
|
|
246
|
+
call(e, t, ...n) {
|
|
247
|
+
let r = e.type[t];
|
|
248
|
+
if (r) try {
|
|
249
|
+
r.apply(e, n);
|
|
250
|
+
} catch (n) {
|
|
251
|
+
this.options.onError ? this.options.onError(n, {
|
|
252
|
+
script: e,
|
|
253
|
+
hook: t
|
|
254
|
+
}) : this.errors.push(n);
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
step(e, t) {
|
|
258
|
+
if (this.live(), !Number.isFinite(e) || e < 0) throw RangeError("Invalid script delta; pass a finite number of seconds, 0 or more");
|
|
259
|
+
this.flush(), this.pass(() => {
|
|
260
|
+
for (let n of t) for (let t of [...this.all]) !t.dead && t.isEnabled && t.isInitialized && this.call(t, n, e);
|
|
261
|
+
});
|
|
262
|
+
}
|
|
263
|
+
pass(t) {
|
|
264
|
+
if (this.busy) return t();
|
|
265
|
+
this.busy = !0;
|
|
266
|
+
try {
|
|
267
|
+
t();
|
|
268
|
+
} finally {
|
|
269
|
+
this.busy = !1;
|
|
270
|
+
}
|
|
271
|
+
if (this.errors.length) {
|
|
272
|
+
let t = this.errors.length, n = new e("failed", `${t} script hook${t > 1 ? "s" : ""} threw; the first error is in cause, or pass onError to handle each`);
|
|
273
|
+
throw Object.defineProperty(n, "cause", { value: this.errors[0] }), this.errors = [], n;
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
};
|
|
277
|
+
//#endregion
|
|
278
|
+
export { f as Scripts, d as defineScript };
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
/** App-owned encoding for values that have no portable representation, such as asset references. */
|
|
2
|
+
export interface SnapshotValueCodec {
|
|
3
|
+
/** Stable wire name, unique in one codec list. */
|
|
4
|
+
name: string;
|
|
5
|
+
/** True for values owned by this codec. */
|
|
6
|
+
test(value: unknown): boolean;
|
|
7
|
+
/** Return supported portable data, not executable source. */
|
|
8
|
+
encode(value: unknown): unknown;
|
|
9
|
+
/** Reconstruct a value from portable data. Custom cycles must use app keys. */
|
|
10
|
+
decode(value: unknown): unknown;
|
|
11
|
+
}
|
|
12
|
+
/** Snapshot I/O limits and cancellation. */
|
|
13
|
+
export interface SnapshotOptions {
|
|
14
|
+
/** Abort asynchronous compression, decompression and hashing. Default none. */
|
|
15
|
+
signal?: AbortSignal;
|
|
16
|
+
/** Maximum packet and expanded text bytes. Default 64 MiB. */
|
|
17
|
+
maxBytes?: number;
|
|
18
|
+
/** App reference codecs. Default none. */
|
|
19
|
+
codecs?: readonly SnapshotValueCodec[];
|
|
20
|
+
}
|
|
21
|
+
/** Base64 text of `bytes`; uses the built-in encoder where the runtime has one (Node 26, current browsers). */
|
|
22
|
+
export declare function bytesToBase64(bytes: Uint8Array): string;
|
|
23
|
+
/** Bytes of canonical padded base64 `text`; throws SyntaxError on anything else, as the built-in strict decoder does. */
|
|
24
|
+
export declare function base64ToBytes(text: string): Uint8Array;
|
|
25
|
+
/** Lower-case hexadecimal text of `bytes`; uses the built-in encoder where the runtime has one. */
|
|
26
|
+
export declare function bytesToHex(bytes: Uint8Array): string;
|
|
27
|
+
/** Encode a portable identity graph, preserving cycles and shared buffers. */
|
|
28
|
+
export declare function encodeGraph(root: unknown, codecs?: readonly SnapshotValueCodec[]): string;
|
|
29
|
+
/** Decode a bounded graph without setting prototypes or evaluating code. */
|
|
30
|
+
export declare function decodeGraph(text: string, codecs?: readonly SnapshotValueCodec[]): unknown;
|
|
31
|
+
/** Validate I/O bounds before allocation. */
|
|
32
|
+
export declare function byteLimit(options: SnapshotOptions): number;
|
|
33
|
+
/** Compress/decompress with native bounded streams; cancellation rejects without partial state. */
|
|
34
|
+
export declare function transform(bytes: Uint8Array, decompress: boolean, options: SnapshotOptions): Promise<Uint8Array>;
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import type { ComponentStore, Entity, World } from './index.js';
|
|
2
|
+
import { type SnapshotOptions } from './serialize-codec.js';
|
|
3
|
+
export type { SnapshotOptions, SnapshotValueCodec } from './serialize-codec.js';
|
|
4
|
+
/** Restore options. Entity mappings translate remote ids without resurrecting stale local handles. */
|
|
5
|
+
export interface SnapshotRestoreOptions extends SnapshotOptions {
|
|
6
|
+
/** Mapping returned by the previous restore. Default identity for the world's current ids. */
|
|
7
|
+
entities?: ReadonlyMap<Entity, Entity>;
|
|
8
|
+
}
|
|
9
|
+
/** Binary snapshots of named components and entity lifetime, independent of save or rendering packages. */
|
|
10
|
+
export declare class WorldSerializer {
|
|
11
|
+
readonly world: World;
|
|
12
|
+
private readonly stores;
|
|
13
|
+
/** @throws TypeError for empty selection, foreign stores, unsupported fields or duplicate codec names. */
|
|
14
|
+
constructor(world: World, components: Readonly<Record<string, ComponentStore>>);
|
|
15
|
+
/** Capture chosen fields, shared reference graphs, all live entity ids and component membership. */
|
|
16
|
+
snapshot(options?: SnapshotOptions): Promise<Uint8Array>;
|
|
17
|
+
/**
|
|
18
|
+
* Validate the complete packet before changing membership, then restore selected fields and entity lifetime.
|
|
19
|
+
* Surviving entities retain unselected components. Removed entities are destroyed. New entities get safe local ids.
|
|
20
|
+
* Return a fresh remote-to-local map for later snapshots/deltas and app-owned entity-reference fields.
|
|
21
|
+
* Observer exceptions propagate after their underlying mutation, as with Component.add.
|
|
22
|
+
* @throws TypeError for malformed packets, incompatible schemas, invalid mappings or unsupported values.
|
|
23
|
+
* @throws RangeError for byte limits, graph limits or insufficient entity capacity, before entity mutation.
|
|
24
|
+
*/
|
|
25
|
+
restore(packet: Uint8Array, options?: SnapshotRestoreOptions): Promise<Map<Entity, Entity>>;
|
|
26
|
+
}
|
|
27
|
+
/** Create a baseline-checked binary delta, comparing fixed 256-character blocks using native string comparisons. */
|
|
28
|
+
export declare function createDelta(before: Uint8Array, after: Uint8Array, options?: SnapshotOptions): Promise<Uint8Array>;
|
|
29
|
+
/**
|
|
30
|
+
* Apply a delta to its exact baseline and return a complete snapshot. Both fingerprints are checked.
|
|
31
|
+
* For undo, createDelta(after,before) creates the inverse. No world mutation occurs here.
|
|
32
|
+
* @throws TypeError for corrupt, out-of-order or wrong-baseline deltas.
|
|
33
|
+
*/
|
|
34
|
+
export declare function applyDelta(before: Uint8Array, delta: Uint8Array, options?: SnapshotOptions): Promise<Uint8Array>;
|