@nodetool-ai/game-runtime 0.8.1 → 0.8.3
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/README.md +43 -0
- package/dist/.nodetool-build-stamp +1 -1
- package/dist/audio-mixer-references.d.ts +10 -0
- package/dist/audio-mixer-references.d.ts.map +1 -0
- package/dist/audio-mixer-references.js +21 -0
- package/dist/audio-mixer-references.js.map +1 -0
- package/dist/audio-source-ops.d.ts +24 -0
- package/dist/audio-source-ops.d.ts.map +1 -0
- package/dist/audio-source-ops.js +27 -0
- package/dist/audio-source-ops.js.map +1 -0
- package/dist/authoring-identity.d.ts +3 -0
- package/dist/authoring-identity.d.ts.map +1 -0
- package/dist/authoring-identity.js +12 -0
- package/dist/authoring-identity.js.map +1 -0
- package/dist/authoring-reconcile.d.ts +23 -0
- package/dist/authoring-reconcile.d.ts.map +1 -0
- package/dist/authoring-reconcile.js +375 -0
- package/dist/authoring-reconcile.js.map +1 -0
- package/dist/autoplay.d.ts.map +1 -1
- package/dist/autoplay.js +32 -5
- package/dist/autoplay.js.map +1 -1
- package/dist/document-ops.d.ts +2657 -368
- package/dist/document-ops.d.ts.map +1 -1
- package/dist/document-ops.js +135 -16
- package/dist/document-ops.js.map +1 -1
- package/dist/document-ops3d.d.ts +13390 -0
- package/dist/document-ops3d.d.ts.map +1 -0
- package/dist/document-ops3d.js +493 -0
- package/dist/document-ops3d.js.map +1 -0
- package/dist/gameplay/lifecycle.d.ts +91 -0
- package/dist/gameplay/lifecycle.d.ts.map +1 -0
- package/dist/gameplay/lifecycle.js +135 -0
- package/dist/gameplay/lifecycle.js.map +1 -0
- package/dist/index.d.ts +10 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +10 -0
- package/dist/index.js.map +1 -1
- package/dist/open-session.d.ts +32 -0
- package/dist/open-session.d.ts.map +1 -0
- package/dist/open-session.js +51 -0
- package/dist/open-session.js.map +1 -0
- package/dist/ownership-ops.d.ts +45 -0
- package/dist/ownership-ops.d.ts.map +1 -0
- package/dist/ownership-ops.js +173 -0
- package/dist/ownership-ops.js.map +1 -0
- package/dist/prepared-collider3d.d.ts +11 -0
- package/dist/prepared-collider3d.d.ts.map +1 -0
- package/dist/prepared-collider3d.js +41 -0
- package/dist/prepared-collider3d.js.map +1 -0
- package/dist/sample3d.d.ts +4 -0
- package/dist/sample3d.d.ts.map +1 -0
- package/dist/sample3d.js +62 -0
- package/dist/sample3d.js.map +1 -0
- package/dist/script-clock.d.ts +19 -0
- package/dist/script-clock.d.ts.map +1 -0
- package/dist/script-clock.js +32 -0
- package/dist/script-clock.js.map +1 -0
- package/dist/script-declarations.d.ts +7 -0
- package/dist/script-declarations.d.ts.map +1 -0
- package/dist/script-declarations.js +99 -0
- package/dist/script-declarations.js.map +1 -0
- package/dist/script-lifecycle.d.ts +108 -0
- package/dist/script-lifecycle.d.ts.map +1 -0
- package/dist/script-lifecycle.js +253 -0
- package/dist/script-lifecycle.js.map +1 -0
- package/dist/script-params.d.ts +25 -0
- package/dist/script-params.d.ts.map +1 -0
- package/dist/script-params.js +63 -0
- package/dist/script-params.js.map +1 -0
- package/dist/script-persistence.d.ts +3 -0
- package/dist/script-persistence.d.ts.map +1 -0
- package/dist/script-persistence.js +67 -0
- package/dist/script-persistence.js.map +1 -0
- package/dist/script-props.d.ts +21 -0
- package/dist/script-props.d.ts.map +1 -0
- package/dist/script-props.js +42 -0
- package/dist/script-props.js.map +1 -0
- package/dist/script-transport.d.ts +5 -0
- package/dist/script-transport.d.ts.map +1 -0
- package/dist/script-transport.js +64 -0
- package/dist/script-transport.js.map +1 -0
- package/dist/script-types.d.ts +5 -1
- package/dist/script-types.d.ts.map +1 -1
- package/dist/script-types.js +13 -11
- package/dist/script-types.js.map +1 -1
- package/dist/script-types3d.d.ts +6 -0
- package/dist/script-types3d.d.ts.map +1 -0
- package/dist/script-types3d.js +28 -0
- package/dist/script-types3d.js.map +1 -0
- package/dist/script-world.d.ts +41 -0
- package/dist/script-world.d.ts.map +1 -0
- package/dist/script-world.js +169 -0
- package/dist/script-world.js.map +1 -0
- package/dist/scripts.d.ts +107 -4
- package/dist/scripts.d.ts.map +1 -1
- package/dist/scripts.js +513 -111
- package/dist/scripts.js.map +1 -1
- package/dist/scripts3d.d.ts +34 -0
- package/dist/scripts3d.d.ts.map +1 -0
- package/dist/scripts3d.js +14 -0
- package/dist/scripts3d.js.map +1 -0
- package/dist/session.d.ts +8 -3
- package/dist/session.d.ts.map +1 -1
- package/dist/session.js +249 -795
- package/dist/session.js.map +1 -1
- package/dist/session3d.d.ts +30 -0
- package/dist/session3d.d.ts.map +1 -0
- package/dist/session3d.js +603 -0
- package/dist/session3d.js.map +1 -0
- package/dist/spatial3d/camera.d.ts +7 -0
- package/dist/spatial3d/camera.d.ts.map +1 -0
- package/dist/spatial3d/camera.js +43 -0
- package/dist/spatial3d/camera.js.map +1 -0
- package/dist/spatial3d/digest.d.ts +4 -0
- package/dist/spatial3d/digest.d.ts.map +1 -0
- package/dist/spatial3d/digest.js +30 -0
- package/dist/spatial3d/digest.js.map +1 -0
- package/dist/spatial3d/layers.d.ts +30 -0
- package/dist/spatial3d/layers.d.ts.map +1 -0
- package/dist/spatial3d/layers.js +93 -0
- package/dist/spatial3d/layers.js.map +1 -0
- package/dist/spatial3d/math.d.ts +23 -0
- package/dist/spatial3d/math.d.ts.map +1 -0
- package/dist/spatial3d/math.js +39 -0
- package/dist/spatial3d/math.js.map +1 -0
- package/dist/spatial3d/state.d.ts +37 -0
- package/dist/spatial3d/state.d.ts.map +1 -0
- package/dist/spatial3d/state.js +4 -0
- package/dist/spatial3d/state.js.map +1 -0
- package/dist/spatial3d/world.d.ts +68 -0
- package/dist/spatial3d/world.d.ts.map +1 -0
- package/dist/spatial3d/world.js +446 -0
- package/dist/spatial3d/world.js.map +1 -0
- package/dist/systems/animation-graph3d.d.ts +24 -0
- package/dist/systems/animation-graph3d.d.ts.map +1 -0
- package/dist/systems/animation-graph3d.js +262 -0
- package/dist/systems/animation-graph3d.js.map +1 -0
- package/dist/systems/animation3d.d.ts +3 -0
- package/dist/systems/animation3d.d.ts.map +1 -0
- package/dist/systems/animation3d.js +14 -0
- package/dist/systems/animation3d.js.map +1 -0
- package/dist/systems/character3d.d.ts +3 -0
- package/dist/systems/character3d.d.ts.map +1 -0
- package/dist/systems/character3d.js +6 -0
- package/dist/systems/character3d.js.map +1 -0
- package/dist/systems/collision2d.d.ts +27 -0
- package/dist/systems/collision2d.d.ts.map +1 -0
- package/dist/systems/collision2d.js +154 -0
- package/dist/systems/collision2d.js.map +1 -0
- package/dist/systems/contacts2d.d.ts +3 -0
- package/dist/systems/contacts2d.d.ts.map +1 -0
- package/dist/systems/contacts2d.js +36 -0
- package/dist/systems/contacts2d.js.map +1 -0
- package/dist/systems/contacts3d.d.ts +3 -0
- package/dist/systems/contacts3d.d.ts.map +1 -0
- package/dist/systems/contacts3d.js +55 -0
- package/dist/systems/contacts3d.js.map +1 -0
- package/dist/systems/context2d.d.ts +41 -0
- package/dist/systems/context2d.d.ts.map +1 -0
- package/dist/systems/context2d.js +2 -0
- package/dist/systems/context2d.js.map +1 -0
- package/dist/systems/context3d.d.ts +67 -0
- package/dist/systems/context3d.d.ts.map +1 -0
- package/dist/systems/context3d.js +2 -0
- package/dist/systems/context3d.js.map +1 -0
- package/dist/systems/gameplay2d.d.ts +3 -0
- package/dist/systems/gameplay2d.d.ts.map +1 -0
- package/dist/systems/gameplay2d.js +88 -0
- package/dist/systems/gameplay2d.js.map +1 -0
- package/dist/systems/gameplay3d.d.ts +4 -0
- package/dist/systems/gameplay3d.d.ts.map +1 -0
- package/dist/systems/gameplay3d.js +170 -0
- package/dist/systems/gameplay3d.js.map +1 -0
- package/dist/systems/hierarchy3d.d.ts +3 -0
- package/dist/systems/hierarchy3d.d.ts.map +1 -0
- package/dist/systems/hierarchy3d.js +27 -0
- package/dist/systems/hierarchy3d.js.map +1 -0
- package/dist/systems/input2d.d.ts +3 -0
- package/dist/systems/input2d.d.ts.map +1 -0
- package/dist/systems/input2d.js +6 -0
- package/dist/systems/input2d.js.map +1 -0
- package/dist/systems/input3d.d.ts +3 -0
- package/dist/systems/input3d.d.ts.map +1 -0
- package/dist/systems/input3d.js +16 -0
- package/dist/systems/input3d.js.map +1 -0
- package/dist/systems/physics2d.d.ts +3 -0
- package/dist/systems/physics2d.d.ts.map +1 -0
- package/dist/systems/physics2d.js +244 -0
- package/dist/systems/physics2d.js.map +1 -0
- package/dist/systems/physics3d.d.ts +3 -0
- package/dist/systems/physics3d.d.ts.map +1 -0
- package/dist/systems/physics3d.js +4 -0
- package/dist/systems/physics3d.js.map +1 -0
- package/dist/systems/pipeline.d.ts +23 -0
- package/dist/systems/pipeline.d.ts.map +1 -0
- package/dist/systems/pipeline.js +65 -0
- package/dist/systems/pipeline.js.map +1 -0
- package/dist/systems/presentation2d.d.ts +9 -0
- package/dist/systems/presentation2d.d.ts.map +1 -0
- package/dist/systems/presentation2d.js +240 -0
- package/dist/systems/presentation2d.js.map +1 -0
- package/dist/systems/presentation3d.d.ts +9 -0
- package/dist/systems/presentation3d.d.ts.map +1 -0
- package/dist/systems/presentation3d.js +115 -0
- package/dist/systems/presentation3d.js.map +1 -0
- package/dist/systems/scripts2d.d.ts +7 -0
- package/dist/systems/scripts2d.d.ts.map +1 -0
- package/dist/systems/scripts2d.js +274 -0
- package/dist/systems/scripts2d.js.map +1 -0
- package/dist/systems/scripts3d.d.ts +7 -0
- package/dist/systems/scripts3d.d.ts.map +1 -0
- package/dist/systems/scripts3d.js +262 -0
- package/dist/systems/scripts3d.js.map +1 -0
- package/dist/systems/state2d.d.ts +65 -0
- package/dist/systems/state2d.d.ts.map +1 -0
- package/dist/systems/state2d.js +2 -0
- package/dist/systems/state2d.js.map +1 -0
- package/dist/systems/tick2d.d.ts +7 -0
- package/dist/systems/tick2d.d.ts.map +1 -0
- package/dist/systems/tick2d.js +15 -0
- package/dist/systems/tick2d.js.map +1 -0
- package/dist/systems/tick3d.d.ts +7 -0
- package/dist/systems/tick3d.d.ts.map +1 -0
- package/dist/systems/tick3d.js +17 -0
- package/dist/systems/tick3d.js.map +1 -0
- package/dist/validate-animation-graph3d.d.ts +8 -0
- package/dist/validate-animation-graph3d.d.ts.map +1 -0
- package/dist/validate-animation-graph3d.js +115 -0
- package/dist/validate-animation-graph3d.js.map +1 -0
- package/dist/validate.d.ts +5 -0
- package/dist/validate.d.ts.map +1 -1
- package/dist/validate.js +61 -2
- package/dist/validate.js.map +1 -1
- package/dist/validate3d.d.ts +20 -0
- package/dist/validate3d.d.ts.map +1 -0
- package/dist/validate3d.js +325 -0
- package/dist/validate3d.js.map +1 -0
- package/package.json +10 -3
package/dist/scripts.js
CHANGED
|
@@ -1,4 +1,10 @@
|
|
|
1
1
|
import { z } from "zod";
|
|
2
|
+
import { gameNonSpatialScriptCommand, gameUiScriptCommand, resolveGameScriptParams } from "@nodetool-ai/protocol";
|
|
3
|
+
import { defaultScriptCallClock, startScriptCallTimer } from "./script-clock.js";
|
|
4
|
+
import { commitScriptHooks, planScriptHooks, scriptHookIssue, SCRIPT_LIFECYCLE_DISPATCH } from "./script-lifecycle.js";
|
|
5
|
+
import { canPersistGameScript } from "./script-persistence.js";
|
|
6
|
+
import { gameScriptValue, scriptHandleResult } from "./script-transport.js";
|
|
7
|
+
import { ScriptWorldSnapshot } from "./script-world.js";
|
|
2
8
|
const encoder = new TextEncoder();
|
|
3
9
|
const finite = z.number().finite();
|
|
4
10
|
const color = z.string().regex(/^#[0-9a-fA-F]{6}$/);
|
|
@@ -7,17 +13,18 @@ export const gameScriptCommand = z.discriminatedUnion("kind", [
|
|
|
7
13
|
z.strictObject({ kind: z.literal("setPosition"), x: finite, y: finite }),
|
|
8
14
|
z.strictObject({ kind: z.literal("setVisual"), tint: color.optional(), opacity: finite.min(0).max(1).optional(),
|
|
9
15
|
rotation: finite.optional(), scaleX: finite.positive().optional(), scaleY: finite.positive().optional(), flipX: z.boolean().optional() }),
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
fontId: z.string().min(1).optional() }),
|
|
14
|
-
z.strictObject({ kind: z.literal("emit"), event: z.string().min(1).max(128) }),
|
|
16
|
+
gameNonSpatialScriptCommand.options[0],
|
|
17
|
+
gameNonSpatialScriptCommand.options[1],
|
|
18
|
+
gameNonSpatialScriptCommand.options[2],
|
|
15
19
|
z.strictObject({ kind: z.literal("spawn"), prefabId: z.string().min(1), x: finite.optional(), y: finite.optional(),
|
|
16
20
|
velocityX: finite.optional(), velocityY: finite.optional() }),
|
|
17
|
-
|
|
18
|
-
|
|
21
|
+
gameNonSpatialScriptCommand.options[3],
|
|
22
|
+
gameNonSpatialScriptCommand.options[4],
|
|
23
|
+
gameNonSpatialScriptCommand.options[5],
|
|
24
|
+
gameNonSpatialScriptCommand.options[6],
|
|
25
|
+
gameNonSpatialScriptCommand.options[7],
|
|
26
|
+
gameUiScriptCommand
|
|
19
27
|
]);
|
|
20
|
-
const result = z.strictObject({ state: z.json(), commands: z.array(gameScriptCommand) });
|
|
21
28
|
export function scriptSourceKey(sceneId, entityId, behaviorIndex) {
|
|
22
29
|
return JSON.stringify([sceneId, entityId, behaviorIndex]);
|
|
23
30
|
}
|
|
@@ -25,18 +32,16 @@ export function hasGameScripts(document) {
|
|
|
25
32
|
return document.scenes.some((scene) => scene.entities.some((entity) => entity.behaviors.some((behavior) => behavior.kind === "script")));
|
|
26
33
|
}
|
|
27
34
|
function evaluate(context, code) {
|
|
28
|
-
const
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
35
|
+
const value = scriptHandleResult(context, context.evalCode(code, "game-script.js", { type: "global" }));
|
|
36
|
+
try {
|
|
37
|
+
return context.dump(value);
|
|
38
|
+
}
|
|
39
|
+
finally {
|
|
40
|
+
value.dispose();
|
|
33
41
|
}
|
|
34
|
-
const value = context.dump(evaluation.value);
|
|
35
|
-
evaluation.value.dispose();
|
|
36
|
-
return value;
|
|
37
42
|
}
|
|
38
|
-
function initializeContext(context, seed) {
|
|
39
|
-
|
|
43
|
+
function initializeContext(context, seed, helpers) {
|
|
44
|
+
return scriptHandleResult(context, context.evalCode(`
|
|
40
45
|
globalThis.Date = undefined;
|
|
41
46
|
Object.defineProperty(globalThis, "__gameRandom", {
|
|
42
47
|
value: (() => {
|
|
@@ -50,15 +55,82 @@ function initializeContext(context, seed) {
|
|
|
50
55
|
})(), writable: false, configurable: false
|
|
51
56
|
});
|
|
52
57
|
Object.defineProperty(Math, "random", { value: __gameRandom, writable: false, configurable: false });
|
|
53
|
-
|
|
58
|
+
${helpers}
|
|
59
|
+
`, "game-transport.js", { type: "global" }));
|
|
60
|
+
}
|
|
61
|
+
function interrupted(budget) {
|
|
62
|
+
return new Error(`Game script interrupted: ${budget} budget exceeded`);
|
|
54
63
|
}
|
|
55
64
|
function assertBeforeDeadline(deadline, budget) {
|
|
56
65
|
if (performance.now() >= deadline) {
|
|
57
|
-
throw
|
|
66
|
+
throw interrupted(budget);
|
|
58
67
|
}
|
|
59
68
|
}
|
|
60
|
-
|
|
61
|
-
|
|
69
|
+
const EMPTY_PROPS = Object.freeze({});
|
|
70
|
+
function propsOf(table, id) {
|
|
71
|
+
return Object.hasOwn(table, id) ? table[id] : EMPTY_PROPS;
|
|
72
|
+
}
|
|
73
|
+
function disposeRealm(realm) {
|
|
74
|
+
realm.setWorldReader(undefined);
|
|
75
|
+
realm.worldGetter.dispose();
|
|
76
|
+
realm.queryJson.dispose();
|
|
77
|
+
realm.defineData.dispose();
|
|
78
|
+
realm.invoke.dispose();
|
|
79
|
+
realm.context.dispose();
|
|
80
|
+
}
|
|
81
|
+
/** Bounds the validated entry-scene realms held until the first batch, about 30 KiB each. */
|
|
82
|
+
const PREPARED_REALM_LIMIT = 64;
|
|
83
|
+
const SCRIPT_BATCH_MS = 50;
|
|
84
|
+
/** Prepare-time allowance for the warm-up batch, which runs before any tick budget starts. */
|
|
85
|
+
const WARMUP_BATCH_MS = 1000;
|
|
86
|
+
const WARMUP_SOURCES = [
|
|
87
|
+
["warmup:fresh", "(input) => { const world = input.world; return { state: { tick: input.tick, entities: world.length, ids: world.map((entity) => entity.id) }, commands: [] }; }"],
|
|
88
|
+
["warmup:persistent", "(input) => ({ state: [input.state, input.world], commands: [] })"]
|
|
89
|
+
];
|
|
90
|
+
/** Warms the lifecycle-object path, only for documents that use it. */
|
|
91
|
+
const HOOK_WARMUP_SOURCE = ["warmup:hooks", "({ onStart(input) { after(1, \"tick\"); }, tick() {}, onUpdate(input) { return { state: [input.state, input.world] }; } })"];
|
|
92
|
+
// One envelope per command schema, so its parser is compiled once per process instead of once per runner.
|
|
93
|
+
const envelopeSchemas = new WeakMap();
|
|
94
|
+
const warmedCommandSchemas = new WeakSet();
|
|
95
|
+
const warmedHookSchemas = new WeakSet();
|
|
96
|
+
const compiledSchemas = new WeakSet();
|
|
97
|
+
/**
|
|
98
|
+
* Zod compiles each object schema's parser the first time it sees an object. Doing that here keeps the
|
|
99
|
+
* compilation out of the first batch that emits a given command kind, where it would count against the tick budget.
|
|
100
|
+
*/
|
|
101
|
+
function compileObjectParsers(schema) {
|
|
102
|
+
if (compiledSchemas.has(schema)) {
|
|
103
|
+
return;
|
|
104
|
+
}
|
|
105
|
+
compiledSchemas.add(schema);
|
|
106
|
+
const def = schema._zod.def;
|
|
107
|
+
const children = [];
|
|
108
|
+
if (def["type"] === "object") {
|
|
109
|
+
z.safeParse(schema, {});
|
|
110
|
+
children.push(...Object.values(def["shape"]), def["catchall"]);
|
|
111
|
+
}
|
|
112
|
+
for (const key of ["innerType", "element", "in", "out", "keyType", "valueType", "left", "right", "rest"]) {
|
|
113
|
+
children.push(def[key]);
|
|
114
|
+
}
|
|
115
|
+
for (const key of ["options", "items"]) {
|
|
116
|
+
if (Array.isArray(def[key])) {
|
|
117
|
+
children.push(...def[key]);
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
for (const child of children) {
|
|
121
|
+
if (child instanceof z.core.$ZodType) {
|
|
122
|
+
compileObjectParsers(child);
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
export async function prepareIsolatedGameScripts(document, commandSchema, payloadExpression, options = {}) {
|
|
127
|
+
const callClock = options.callClock ?? defaultScriptCallClock;
|
|
128
|
+
let envelope = envelopeSchemas.get(commandSchema);
|
|
129
|
+
if (envelope === undefined) {
|
|
130
|
+
envelope = z.object({ value: z.strictObject({ state: z.json(), commands: z.array(commandSchema) }), rngState: z.number().int().nonnegative() });
|
|
131
|
+
envelopeSchemas.set(commandSchema, envelope);
|
|
132
|
+
}
|
|
133
|
+
const envelopeSchema = envelope;
|
|
62
134
|
const [{ newQuickJSWASMModuleFromVariant }, quickJsVariantModule] = await Promise.all([
|
|
63
135
|
import("quickjs-emscripten-core"),
|
|
64
136
|
import("@jitl/quickjs-ng-wasmfile-release-sync")
|
|
@@ -69,133 +141,463 @@ export async function prepareGameScripts(document) {
|
|
|
69
141
|
runtime.setMemoryLimit(16 * 1024 * 1024);
|
|
70
142
|
runtime.setMaxStackSize(256 * 1024);
|
|
71
143
|
const sources = new Map();
|
|
144
|
+
// Resolved `input.params` JSON per behavior definition. Values are document data, so this is serialized once per session.
|
|
145
|
+
const paramsJson = new Map();
|
|
146
|
+
const persistentSources = new Set();
|
|
147
|
+
const hookSources = new Set();
|
|
148
|
+
const eventSources = new Set();
|
|
149
|
+
const realms = new Map();
|
|
150
|
+
// Validated entry-scene realms, kept so the first tick does not compile every proven-safe script inside its budget.
|
|
151
|
+
const prepared = new Map();
|
|
152
|
+
const releasePrepared = () => {
|
|
153
|
+
for (const realm of prepared.values()) {
|
|
154
|
+
disposeRealm(realm);
|
|
155
|
+
}
|
|
156
|
+
prepared.clear();
|
|
157
|
+
};
|
|
158
|
+
const disposeRealms = () => {
|
|
159
|
+
for (const realm of realms.values()) {
|
|
160
|
+
disposeRealm(realm);
|
|
161
|
+
}
|
|
162
|
+
realms.clear();
|
|
163
|
+
releasePrepared();
|
|
164
|
+
};
|
|
165
|
+
const retain = (keys) => {
|
|
166
|
+
for (const [key, realm] of realms) {
|
|
167
|
+
if (!keys.has(key)) {
|
|
168
|
+
disposeRealm(realm);
|
|
169
|
+
realms.delete(key);
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
};
|
|
173
|
+
// Host-only setup. Creating a context can run a QuickJS cycle collection of earlier disposed contexts.
|
|
174
|
+
// Only lifecycle-object realms install the hook dispatcher, so function realms evaluate the same helpers as before.
|
|
175
|
+
const createRealmShell = (seed, persistent, hooks = false) => {
|
|
176
|
+
const context = runtime.newContext();
|
|
177
|
+
let invoke;
|
|
178
|
+
let defineData;
|
|
179
|
+
let queryJson;
|
|
180
|
+
let worldGetter;
|
|
181
|
+
let worldReader;
|
|
182
|
+
try {
|
|
183
|
+
worldGetter = persistent ? context.newFunction("legacyWorld", () => {
|
|
184
|
+
if (!worldReader) {
|
|
185
|
+
throw new Error("Legacy world read outside an active script call");
|
|
186
|
+
}
|
|
187
|
+
return worldReader();
|
|
188
|
+
}) : context.undefined.dup();
|
|
189
|
+
// Capture pristine helpers together, without introducing bindings visible to user source.
|
|
190
|
+
const helpers = initializeContext(context, seed, `[
|
|
191
|
+
((define) => (object, key, value) => {
|
|
192
|
+
define(object, key, { value, writable: true, enumerable: true, configurable: true });
|
|
193
|
+
})(Object.defineProperty),
|
|
194
|
+
((stringify) => (value) => {
|
|
195
|
+
const json = stringify(value);
|
|
196
|
+
if (typeof json !== "string" || json.length > 4096) { throw new Error("world query arguments exceed 4096 characters or are not JSON"); }
|
|
197
|
+
return json;
|
|
198
|
+
})(JSON.stringify),
|
|
199
|
+
((defineProperty${hooks ? ", dispatch" : ""}) => (data, getWorld, rngState) => {
|
|
200
|
+
${persistent ? "" : "data = JSON.parse(data);"}
|
|
201
|
+
const payload = ${payloadExpression};
|
|
202
|
+
${persistent ? `defineProperty(payload, "world", {
|
|
203
|
+
enumerable: true, configurable: true, get: getWorld,
|
|
204
|
+
set(value) { defineProperty(this, "world", { value, writable: true, enumerable: true, configurable: true }); }
|
|
205
|
+
});` : ""}
|
|
206
|
+
const value = ${hooks ? "dispatch(__gameScript, payload, data.call.steps)" : "__gameScript(payload)"};
|
|
207
|
+
return JSON.stringify({ value, rngState: ${persistent ? "rngState" : "__gameRandom.state"} });
|
|
208
|
+
})(Object.defineProperty${hooks ? `, ${SCRIPT_LIFECYCLE_DISPATCH}` : ""})]`);
|
|
209
|
+
try {
|
|
210
|
+
defineData = context.getProp(helpers, 0);
|
|
211
|
+
queryJson = context.getProp(helpers, 1);
|
|
212
|
+
invoke = context.getProp(helpers, 2);
|
|
213
|
+
}
|
|
214
|
+
finally {
|
|
215
|
+
helpers.dispose();
|
|
216
|
+
}
|
|
217
|
+
return { context, invoke, defineData, queryJson, worldGetter, setWorldReader: (reader) => { worldReader = reader; } };
|
|
218
|
+
}
|
|
219
|
+
catch (error) {
|
|
220
|
+
worldGetter?.dispose();
|
|
221
|
+
queryJson?.dispose();
|
|
222
|
+
defineData?.dispose();
|
|
223
|
+
invoke?.dispose();
|
|
224
|
+
context.dispose();
|
|
225
|
+
throw error;
|
|
226
|
+
}
|
|
227
|
+
};
|
|
228
|
+
/** Evaluates user source in the shell, which this takes ownership of. */
|
|
229
|
+
const loadSource = (shell, sourceKey, source, hooks) => {
|
|
230
|
+
try {
|
|
231
|
+
if (evaluate(shell.context, `globalThis.__gameScript = (${source}); typeof __gameScript`) !== (hooks ? "object" : "function")) {
|
|
232
|
+
throw new Error(`Game script ${sourceKey} must be a ${hooks ? "lifecycle object" : "function expression"}`);
|
|
233
|
+
}
|
|
234
|
+
return { ...shell, sourceKey };
|
|
235
|
+
}
|
|
236
|
+
catch (error) {
|
|
237
|
+
disposeRealm(shell);
|
|
238
|
+
throw error;
|
|
239
|
+
}
|
|
240
|
+
};
|
|
241
|
+
/** Prepare-time evaluation: a function, or a lifecycle object whose hooks pass `scriptHookIssue`. */
|
|
242
|
+
const inspectSource = (sourceKey, source, persistent) => {
|
|
243
|
+
const shell = createRealmShell(0, persistent);
|
|
244
|
+
try {
|
|
245
|
+
const kind = evaluate(shell.context, `globalThis.__gameScript = (${source}); typeof __gameScript`);
|
|
246
|
+
let onEvent = false;
|
|
247
|
+
if (kind !== "function") {
|
|
248
|
+
const shape = kind === "object" && !persistent ? evaluate(shell.context, `(() => { const hooks = __gameScript;
|
|
249
|
+
if (hooks === null || Array.isArray(hooks)) { return null; }
|
|
250
|
+
const keys = Object.keys(hooks);
|
|
251
|
+
return [keys, keys.filter((key) => typeof hooks[key] === "function")]; })()`) : null;
|
|
252
|
+
if (!Array.isArray(shape)) {
|
|
253
|
+
throw new Error(`Game script ${sourceKey} must be a function expression or a lifecycle object`);
|
|
254
|
+
}
|
|
255
|
+
const issue = scriptHookIssue(shape[0], shape[1]);
|
|
256
|
+
if (issue !== undefined) {
|
|
257
|
+
throw new Error(`Game script ${sourceKey}: ${issue}`);
|
|
258
|
+
}
|
|
259
|
+
onEvent = shape[1].includes("onEvent");
|
|
260
|
+
}
|
|
261
|
+
return { realm: { ...shell, sourceKey }, hooks: kind !== "function", onEvent };
|
|
262
|
+
}
|
|
263
|
+
catch (error) {
|
|
264
|
+
disposeRealm(shell);
|
|
265
|
+
throw error;
|
|
266
|
+
}
|
|
267
|
+
};
|
|
72
268
|
try {
|
|
73
269
|
for (const scene of document.scenes) {
|
|
74
270
|
for (const entity of scene.entities) {
|
|
75
271
|
entity.behaviors.forEach((behavior, index) => {
|
|
76
|
-
if (behavior.kind !== "script") {
|
|
272
|
+
if (behavior.kind !== "script" || behavior.source === undefined) {
|
|
77
273
|
return;
|
|
78
274
|
}
|
|
79
275
|
const key = scriptSourceKey(scene.id, entity.id, index);
|
|
80
|
-
const context = runtime.newContext();
|
|
81
276
|
try {
|
|
82
277
|
const deadline = performance.now() + 100;
|
|
83
278
|
runtime.setInterruptHandler(() => performance.now() >= deadline);
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
279
|
+
const persistent = canPersistGameScript(behavior.source);
|
|
280
|
+
const { realm, hooks, onEvent } = inspectSource(key, behavior.source, persistent);
|
|
281
|
+
if (persistent) {
|
|
282
|
+
persistentSources.add(key);
|
|
283
|
+
}
|
|
284
|
+
if (hooks) {
|
|
285
|
+
hookSources.add(key);
|
|
286
|
+
}
|
|
287
|
+
if (onEvent) {
|
|
288
|
+
eventSources.add(key);
|
|
289
|
+
}
|
|
290
|
+
// Inactive scenes and prefab definitions are validated without retaining their realms.
|
|
291
|
+
if (persistent && scene.id === document.entrySceneId && prepared.size < PREPARED_REALM_LIMIT) {
|
|
292
|
+
prepared.set(key, realm);
|
|
293
|
+
}
|
|
294
|
+
else {
|
|
295
|
+
disposeRealm(realm);
|
|
87
296
|
}
|
|
88
297
|
}
|
|
89
298
|
catch (error) {
|
|
90
299
|
throw new Error(`Game script ${key} could not be prepared: ${error instanceof Error ? error.message : String(error)}`);
|
|
91
300
|
}
|
|
92
|
-
finally {
|
|
93
|
-
context.dispose();
|
|
94
|
-
}
|
|
95
301
|
sources.set(key, behavior.source);
|
|
302
|
+
if (behavior.params !== undefined) {
|
|
303
|
+
paramsJson.set(key, JSON.stringify(resolveGameScriptParams(behavior.params, behavior.values)));
|
|
304
|
+
}
|
|
96
305
|
});
|
|
97
306
|
}
|
|
98
307
|
}
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
const
|
|
109
|
-
if (
|
|
110
|
-
|
|
111
|
-
}
|
|
112
|
-
|
|
308
|
+
const execute = (calls, input, rngState, world, batchMs) => {
|
|
309
|
+
const started = performance.now();
|
|
310
|
+
const batchDeadline = started + batchMs;
|
|
311
|
+
// This limits the logical tick payload, which carries each entity's props once.
|
|
312
|
+
// Each isolated call gets its own JSON copy with props attached to the entries scripts read.
|
|
313
|
+
// Params belong to a behavior definition, so calls that share one count its params once, as a table keyed by source.
|
|
314
|
+
let paramsTable = "";
|
|
315
|
+
const counted = new Set();
|
|
316
|
+
for (const call of paramsJson.size === 0 ? [] : calls) {
|
|
317
|
+
const params = paramsJson.get(call.sourceKey);
|
|
318
|
+
if (params === undefined || counted.has(call.sourceKey)) {
|
|
319
|
+
continue;
|
|
320
|
+
}
|
|
321
|
+
paramsTable += `${counted.size > 0 ? "," : ""}${JSON.stringify(call.sourceKey)}:${params}`;
|
|
322
|
+
counted.add(call.sourceKey);
|
|
323
|
+
}
|
|
324
|
+
const logical = JSON.stringify({ calls, input, rngState });
|
|
325
|
+
const serialized = counted.size === 0 ? logical : `${logical.slice(0, -1)},"params":{${paramsTable}}}`;
|
|
326
|
+
const inputBytes = encoder.encode(serialized).byteLength;
|
|
327
|
+
if (inputBytes > 64 * 1024) {
|
|
328
|
+
throw new Error(`Game script input exceeds 64 KiB (${inputBytes} bytes, ${calls.length} calls, tick ${input.tick})`);
|
|
329
|
+
}
|
|
330
|
+
const batchBudget = `batch ${batchMs} ms at tick ${input.tick}`;
|
|
331
|
+
assertBeforeDeadline(batchDeadline, batchBudget);
|
|
332
|
+
const { props: propsTable, ...scriptInput } = input;
|
|
333
|
+
// Scripts read props on each world entry. The copies exist only in this guest-facing JSON.
|
|
334
|
+
let worldJson;
|
|
335
|
+
const scriptWorldJson = () => worldJson ??= JSON.stringify(propsTable === undefined ? scriptInput.world
|
|
336
|
+
: scriptInput.world.map((entity) => ({ ...entity, props: propsOf(propsTable, entity.id) })));
|
|
337
|
+
let fullInputJson;
|
|
338
|
+
const inputJson = () => {
|
|
339
|
+
if (fullInputJson === undefined) {
|
|
340
|
+
const { world: _world, ...withoutWorld } = scriptInput;
|
|
341
|
+
const rest = JSON.stringify(withoutWorld);
|
|
342
|
+
fullInputJson = `${rest.slice(0, -1)}${rest.length > 2 ? "," : ""}"world":${scriptWorldJson()}}`;
|
|
343
|
+
}
|
|
344
|
+
return fullInputJson;
|
|
345
|
+
};
|
|
346
|
+
let persistentInputJson;
|
|
347
|
+
const inputJsonWithoutWorld = () => {
|
|
348
|
+
if (persistentInputJson === undefined) {
|
|
349
|
+
const { world: _world, ...withoutWorld } = scriptInput;
|
|
350
|
+
persistentInputJson = JSON.stringify(withoutWorld);
|
|
351
|
+
}
|
|
352
|
+
return persistentInputJson;
|
|
353
|
+
};
|
|
354
|
+
const callJson = (call, plan) => {
|
|
355
|
+
// A lifecycle call shows its hooks the record's inner state and receives its hook steps instead of host facts.
|
|
356
|
+
const guest = plan === undefined ? call : { ...call, state: plan.state, lifecycle: undefined, steps: plan.steps };
|
|
357
|
+
return JSON.stringify(propsTable === undefined ? guest : { ...guest, props: propsOf(propsTable, call.entityId) });
|
|
358
|
+
};
|
|
359
|
+
let hostWorld;
|
|
360
|
+
const getHostWorld = () => hostWorld ??= new ScriptWorldSnapshot(world ?? input.world, propsTable);
|
|
361
|
+
let legacyWorld;
|
|
362
|
+
let legacyWorldReady = false;
|
|
363
|
+
const readLegacyWorld = () => {
|
|
364
|
+
if (!legacyWorldReady) {
|
|
365
|
+
// Parse the tick-start world only when a persistent script reads it.
|
|
366
|
+
legacyWorld = JSON.parse(scriptWorldJson());
|
|
367
|
+
legacyWorldReady = true;
|
|
368
|
+
}
|
|
369
|
+
return legacyWorld;
|
|
370
|
+
};
|
|
371
|
+
let nextRngState = rngState;
|
|
372
|
+
let serializedResultsBytes = 0;
|
|
373
|
+
let commandCount = 0;
|
|
374
|
+
const byEntity = Object.create(null);
|
|
375
|
+
const results = [];
|
|
376
|
+
for (const call of calls) {
|
|
113
377
|
assertBeforeDeadline(batchDeadline, batchBudget);
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
378
|
+
const source = sources.get(call.sourceKey);
|
|
379
|
+
if (source === undefined) {
|
|
380
|
+
throw new Error(`Game script source ${call.sourceKey} is missing for ${call.entityId} at tick ${input.tick}`);
|
|
381
|
+
}
|
|
382
|
+
let callStarted = performance.now();
|
|
383
|
+
let callExceeded = () => false;
|
|
384
|
+
const checkCallDeadline = () => {
|
|
385
|
+
assertBeforeDeadline(batchDeadline, batchBudget);
|
|
386
|
+
if (callExceeded()) {
|
|
387
|
+
throw interrupted(`call ${call.maxTickMs} ms for ${call.entityId} at tick ${input.tick}`);
|
|
388
|
+
}
|
|
389
|
+
};
|
|
390
|
+
runtime.setInterruptHandler(() => performance.now() >= batchDeadline);
|
|
391
|
+
const persistent = persistentSources.has(call.sourceKey);
|
|
392
|
+
let realm = realms.get(call.stateKey);
|
|
393
|
+
let shell;
|
|
394
|
+
let worldHandle;
|
|
395
|
+
let worldCall;
|
|
396
|
+
try {
|
|
397
|
+
if (realm && realm.sourceKey !== call.sourceKey) {
|
|
398
|
+
disposeRealm(realm);
|
|
399
|
+
realms.delete(call.stateKey);
|
|
400
|
+
realm = undefined;
|
|
401
|
+
}
|
|
402
|
+
if (!realm && persistent) {
|
|
403
|
+
realm = prepared.get(call.sourceKey);
|
|
404
|
+
prepared.delete(call.sourceKey);
|
|
405
|
+
}
|
|
406
|
+
// Context setup is host work, so it counts against the batch budget only. The call budget starts
|
|
407
|
+
// before any user source is evaluated, so the script's own execution limit is unchanged.
|
|
408
|
+
const hooks = hookSources.has(call.sourceKey);
|
|
409
|
+
if (!realm) {
|
|
410
|
+
shell = createRealmShell(nextRngState, persistent, hooks);
|
|
411
|
+
}
|
|
120
412
|
assertBeforeDeadline(batchDeadline, batchBudget);
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
413
|
+
callStarted = performance.now();
|
|
414
|
+
callExceeded = startScriptCallTimer(callClock, call.maxTickMs);
|
|
415
|
+
runtime.setInterruptHandler(() => performance.now() >= batchDeadline || callExceeded());
|
|
416
|
+
if (shell) {
|
|
417
|
+
const loading = shell;
|
|
418
|
+
shell = undefined;
|
|
419
|
+
realm = loadSource(loading, call.sourceKey, source, hooks);
|
|
420
|
+
}
|
|
421
|
+
if (!realm) {
|
|
422
|
+
throw new Error("Game script realm was not created");
|
|
423
|
+
}
|
|
424
|
+
if (persistent) {
|
|
425
|
+
realms.set(call.stateKey, realm);
|
|
426
|
+
}
|
|
427
|
+
const { context, invoke, defineData, worldGetter } = realm;
|
|
428
|
+
if (!persistent) {
|
|
429
|
+
worldCall = getHostWorld().install(context, checkCallDeadline, realm.defineData, realm.queryJson);
|
|
430
|
+
}
|
|
431
|
+
checkCallDeadline();
|
|
432
|
+
// The shared input is serialized once per tick; only the call is serialized per call.
|
|
433
|
+
const params = paramsJson.get(call.sourceKey);
|
|
434
|
+
const plan = hooks ? planScriptHooks(call.state, call.lifecycle, input.tick) : undefined;
|
|
435
|
+
const data = `{"call":${callJson(call, plan)},"input":${persistent ? inputJsonWithoutWorld() : inputJson()},"rngState":${JSON.stringify(nextRngState)}${params === undefined ? "" : `,"params":${params}`}}`;
|
|
436
|
+
checkCallDeadline();
|
|
437
|
+
const normalized = persistent ? JSON.parse(data) : data;
|
|
438
|
+
let argument;
|
|
439
|
+
let seed;
|
|
440
|
+
let output;
|
|
133
441
|
try {
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
442
|
+
argument = gameScriptValue(context, normalized, defineData, persistent);
|
|
443
|
+
seed = context.newNumber(nextRngState);
|
|
444
|
+
realm.setWorldReader(() => {
|
|
445
|
+
checkCallDeadline();
|
|
446
|
+
worldHandle ??= gameScriptValue(context, readLegacyWorld(), defineData, true);
|
|
447
|
+
checkCallDeadline();
|
|
448
|
+
return worldHandle.dup();
|
|
449
|
+
});
|
|
450
|
+
const value = scriptHandleResult(context, context.callFunction(invoke, context.undefined, argument, worldGetter, seed));
|
|
451
|
+
try {
|
|
452
|
+
output = context.dump(value);
|
|
138
453
|
}
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
checkCallDeadline();
|
|
142
|
-
const output = evaluate(context, `(() => {
|
|
143
|
-
const data = JSON.parse(${JSON.stringify(data)});
|
|
144
|
-
const value = __gameScript({
|
|
145
|
-
tick: data.input.tick, pressed: data.input.pressed, justPressed: data.input.justPressed,
|
|
146
|
-
events: data.input.events, entity: {
|
|
147
|
-
id: data.call.entityId, source: data.call.source, x: data.call.x, y: data.call.y,
|
|
148
|
-
velocityX: data.call.velocityX, velocityY: data.call.velocityY,
|
|
149
|
-
touching: data.call.touching
|
|
150
|
-
}, world: data.input.world, state: data.call.state, random: __gameRandom
|
|
151
|
-
});
|
|
152
|
-
return JSON.stringify({ value, rngState: __gameRandom.state });
|
|
153
|
-
})()`);
|
|
154
|
-
if (typeof output !== "string") {
|
|
155
|
-
throw new Error("Output is not JSON");
|
|
454
|
+
finally {
|
|
455
|
+
value.dispose();
|
|
156
456
|
}
|
|
157
|
-
|
|
158
|
-
const rawOutputBytes = encoder.encode(output).byteLength;
|
|
159
|
-
if (rawOutputBytes > 64 * 1024) {
|
|
160
|
-
throw new Error(`Output exceeds 64 KiB (${rawOutputBytes} bytes in call ${results.length + 1})`);
|
|
161
|
-
}
|
|
162
|
-
const parsed = JSON.parse(output);
|
|
163
|
-
const envelope = z.object({ value: result, rngState: z.number().int().nonnegative() }).parse(parsed);
|
|
164
|
-
if (envelope.value.commands.length > call.maxCommands) {
|
|
165
|
-
throw new Error(`Game script command limit exceeded for ${call.entityId}`);
|
|
166
|
-
}
|
|
167
|
-
const itemBytes = encoder.encode(JSON.stringify({ entityId: call.entityId, value: envelope.value })).byteLength;
|
|
168
|
-
serializedResultsBytes += itemBytes + (results.length > 0 ? 1 : 0);
|
|
169
|
-
const outputBytes = encoder.encode(JSON.stringify({ results: [], rngState: envelope.rngState })).byteLength + serializedResultsBytes;
|
|
170
|
-
if (outputBytes > 64 * 1024) {
|
|
171
|
-
throw new Error(`Output exceeds 64 KiB (${outputBytes} bytes across ${results.length + 1} calls)`);
|
|
172
|
-
}
|
|
173
|
-
checkCallDeadline();
|
|
174
|
-
commandCount += envelope.value.commands.length;
|
|
175
|
-
nextRngState = envelope.rngState;
|
|
176
|
-
results.push({ entityId: call.entityId, state: envelope.value.state, commands: envelope.value.commands });
|
|
177
|
-
}
|
|
178
|
-
catch (error) {
|
|
179
|
-
throw new Error(`Game script ${call.sourceKey} for ${call.entityId} at tick ${input.tick} failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
457
|
+
worldCall?.assertWithinLimit();
|
|
180
458
|
}
|
|
181
459
|
finally {
|
|
182
|
-
|
|
460
|
+
realm.setWorldReader(undefined);
|
|
461
|
+
argument?.dispose();
|
|
462
|
+
seed?.dispose();
|
|
463
|
+
}
|
|
464
|
+
if (typeof output !== "string") {
|
|
465
|
+
throw new Error("Output is not JSON");
|
|
183
466
|
}
|
|
184
467
|
checkCallDeadline();
|
|
185
|
-
const
|
|
186
|
-
|
|
468
|
+
const rawOutputBytes = encoder.encode(output).byteLength;
|
|
469
|
+
if (rawOutputBytes > 64 * 1024) {
|
|
470
|
+
throw new Error(`Output exceeds 64 KiB (${rawOutputBytes} bytes in call ${results.length + 1})`);
|
|
471
|
+
}
|
|
472
|
+
const parsed = JSON.parse(output);
|
|
473
|
+
const envelope = envelopeSchema.parse(parsed);
|
|
474
|
+
const value = plan === undefined ? envelope.value
|
|
475
|
+
: { state: commitScriptHooks(envelope.value.state, plan, input.tick), commands: envelope.value.commands };
|
|
476
|
+
if (value.commands.length > call.maxCommands) {
|
|
477
|
+
throw new Error(`Game script command limit exceeded for ${call.entityId}`);
|
|
478
|
+
}
|
|
479
|
+
const itemBytes = encoder.encode(JSON.stringify({ entityId: call.entityId, value })).byteLength;
|
|
480
|
+
serializedResultsBytes += itemBytes + (results.length > 0 ? 1 : 0);
|
|
481
|
+
const outputBytes = encoder.encode(JSON.stringify({ results: [], rngState: envelope.rngState })).byteLength + serializedResultsBytes;
|
|
482
|
+
if (outputBytes > 64 * 1024) {
|
|
483
|
+
throw new Error(`Output exceeds 64 KiB (${outputBytes} bytes across ${results.length + 1} calls)`);
|
|
484
|
+
}
|
|
485
|
+
checkCallDeadline();
|
|
486
|
+
commandCount += value.commands.length;
|
|
487
|
+
nextRngState = envelope.rngState;
|
|
488
|
+
results.push({ entityId: call.entityId, state: value.state, commands: value.commands });
|
|
489
|
+
}
|
|
490
|
+
catch (error) {
|
|
491
|
+
// A failed batch cannot retain partially evaluated realms.
|
|
492
|
+
worldHandle?.dispose();
|
|
493
|
+
worldHandle = undefined;
|
|
494
|
+
if (shell) {
|
|
495
|
+
disposeRealm(shell);
|
|
496
|
+
shell = undefined;
|
|
497
|
+
}
|
|
498
|
+
if (!persistent && realm) {
|
|
499
|
+
disposeRealm(realm);
|
|
500
|
+
realm = undefined;
|
|
501
|
+
}
|
|
502
|
+
disposeRealms();
|
|
503
|
+
throw new Error(`Game script ${call.sourceKey} for ${call.entityId} at tick ${input.tick} failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
504
|
+
}
|
|
505
|
+
finally {
|
|
506
|
+
worldCall?.end();
|
|
507
|
+
worldHandle?.dispose();
|
|
508
|
+
if (!persistent && realm) {
|
|
509
|
+
disposeRealm(realm);
|
|
510
|
+
}
|
|
511
|
+
}
|
|
512
|
+
checkCallDeadline();
|
|
513
|
+
const previous = byEntity[call.entityId] ?? { durationMs: 0, calls: 0 };
|
|
514
|
+
byEntity[call.entityId] = { durationMs: previous.durationMs + performance.now() - callStarted, calls: previous.calls + 1 };
|
|
515
|
+
}
|
|
516
|
+
assertBeforeDeadline(batchDeadline, batchBudget);
|
|
517
|
+
return { results, rngState: nextRngState, stats: { durationMs: performance.now() - started, commands: commandCount, calls: calls.length, byEntity } };
|
|
518
|
+
};
|
|
519
|
+
const warmCalls = !warmedCommandSchemas.has(commandSchema);
|
|
520
|
+
const warmHooks = hookSources.size > 0 && !warmedHookSchemas.has(commandSchema);
|
|
521
|
+
const warmups = [...(warmCalls ? WARMUP_SOURCES : []), ...(warmHooks ? [HOOK_WARMUP_SOURCE] : [])];
|
|
522
|
+
if (warmups.length > 0) {
|
|
523
|
+
// Run the per-call path once before any tick budget starts, so first-use costs in this process
|
|
524
|
+
// (host and zod parser compilation, QuickJS warm-up) are paid here instead of by the first batch.
|
|
525
|
+
compileObjectParsers(commandSchema);
|
|
526
|
+
const warmupCalls = warmups.map(([key, source]) => {
|
|
527
|
+
sources.set(key, source);
|
|
528
|
+
if (canPersistGameScript(source)) {
|
|
529
|
+
persistentSources.add(key);
|
|
530
|
+
}
|
|
531
|
+
if (key === HOOK_WARMUP_SOURCE[0]) {
|
|
532
|
+
hookSources.add(key);
|
|
533
|
+
}
|
|
534
|
+
return { sourceKey: key, stateKey: key, entityId: key, source: key, state: null, maxCommands: 0, maxTickMs: WARMUP_BATCH_MS };
|
|
535
|
+
});
|
|
536
|
+
try {
|
|
537
|
+
execute(warmupCalls, { tick: 0, world: [] }, 0, [], WARMUP_BATCH_MS);
|
|
538
|
+
if (warmCalls) {
|
|
539
|
+
warmedCommandSchemas.add(commandSchema);
|
|
540
|
+
}
|
|
541
|
+
if (warmHooks) {
|
|
542
|
+
warmedHookSchemas.add(commandSchema);
|
|
543
|
+
}
|
|
544
|
+
}
|
|
545
|
+
catch {
|
|
546
|
+
// The warm-up is only an optimization. Its error path already disposed every realm, including the
|
|
547
|
+
// prepared ones, so batches create realms on demand as they do past PREPARED_REALM_LIMIT. The next runner warms again.
|
|
548
|
+
}
|
|
549
|
+
finally {
|
|
550
|
+
retain(new Set());
|
|
551
|
+
for (const [key] of warmups) {
|
|
552
|
+
sources.delete(key);
|
|
553
|
+
persistentSources.delete(key);
|
|
554
|
+
hookSources.delete(key);
|
|
555
|
+
}
|
|
556
|
+
}
|
|
557
|
+
}
|
|
558
|
+
return {
|
|
559
|
+
hookSources,
|
|
560
|
+
eventSources,
|
|
561
|
+
retain,
|
|
562
|
+
run(calls, input, rngState, world) {
|
|
563
|
+
try {
|
|
564
|
+
retain(new Set(calls.map((call) => call.stateKey)));
|
|
565
|
+
if (calls.length === 0) {
|
|
566
|
+
return { results: [], rngState, stats: { durationMs: 0, commands: 0, calls: 0, byEntity: {} } };
|
|
567
|
+
}
|
|
568
|
+
return execute(calls, input, rngState, world, SCRIPT_BATCH_MS);
|
|
569
|
+
}
|
|
570
|
+
catch (error) {
|
|
571
|
+
disposeRealms();
|
|
572
|
+
throw error;
|
|
573
|
+
}
|
|
574
|
+
finally {
|
|
575
|
+
// Entities without a call in the first batch were not active at start. Later activations compile on demand.
|
|
576
|
+
releasePrepared();
|
|
187
577
|
}
|
|
188
|
-
assertBeforeDeadline(batchDeadline, batchBudget);
|
|
189
|
-
return { results, rngState: nextRngState, stats: { durationMs: performance.now() - started, commands: commandCount, calls: calls.length, byEntity } };
|
|
190
578
|
},
|
|
191
579
|
dispose() {
|
|
580
|
+
disposeRealms();
|
|
192
581
|
runtime.dispose();
|
|
193
582
|
}
|
|
194
583
|
};
|
|
195
584
|
}
|
|
196
585
|
catch (error) {
|
|
586
|
+
disposeRealms();
|
|
197
587
|
runtime.dispose();
|
|
198
588
|
throw error;
|
|
199
589
|
}
|
|
200
590
|
}
|
|
591
|
+
export function prepareGameScripts(document, options) {
|
|
592
|
+
return prepareIsolatedGameScripts(document, gameScriptCommand, `{
|
|
593
|
+
tick: data.input.tick, pressed: data.input.pressed, justPressed: data.input.justPressed,
|
|
594
|
+
events: data.input.events, entity: {
|
|
595
|
+
id: data.call.entityId, source: data.call.source, x: data.call.x, y: data.call.y,
|
|
596
|
+
velocityX: data.call.velocityX, velocityY: data.call.velocityY, touching: data.call.touching,
|
|
597
|
+
...(data.call.props === undefined ? undefined
|
|
598
|
+
: { tags: data.call.tags, props: data.call.props, rotation: data.call.rotation, active: data.call.active })
|
|
599
|
+
}, world: data.input.world, state: data.call.state, random: __gameRandom,
|
|
600
|
+
...(data.params === undefined ? undefined : { params: data.params })
|
|
601
|
+
}`, options);
|
|
602
|
+
}
|
|
201
603
|
//# sourceMappingURL=scripts.js.map
|