@nodetool-ai/game-runtime 0.8.1
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/dist/.nodetool-build-stamp +1 -0
- package/dist/autoplay.d.ts +43 -0
- package/dist/autoplay.d.ts.map +1 -0
- package/dist/autoplay.js +332 -0
- package/dist/autoplay.js.map +1 -0
- package/dist/document-ops.d.ts +1588 -0
- package/dist/document-ops.d.ts.map +1 -0
- package/dist/document-ops.js +475 -0
- package/dist/document-ops.js.map +1 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +7 -0
- package/dist/index.js.map +1 -0
- package/dist/physics.d.ts +44 -0
- package/dist/physics.d.ts.map +1 -0
- package/dist/physics.js +151 -0
- package/dist/physics.js.map +1 -0
- package/dist/sample.d.ts +4 -0
- package/dist/sample.d.ts.map +1 -0
- package/dist/sample.js +34 -0
- package/dist/sample.js.map +1 -0
- package/dist/script-types.d.ts +3 -0
- package/dist/script-types.d.ts.map +1 -0
- package/dist/script-types.js +29 -0
- package/dist/script-types.js.map +1 -0
- package/dist/scripts.d.ts +116 -0
- package/dist/scripts.d.ts.map +1 -0
- package/dist/scripts.js +201 -0
- package/dist/scripts.js.map +1 -0
- package/dist/session.d.ts +33 -0
- package/dist/session.d.ts.map +1 -0
- package/dist/session.js +1100 -0
- package/dist/session.js.map +1 -0
- package/dist/validate.d.ts +14 -0
- package/dist/validate.d.ts.map +1 -0
- package/dist/validate.js +289 -0
- package/dist/validate.js.map +1 -0
- package/dist/visual-animation.d.ts +11 -0
- package/dist/visual-animation.d.ts.map +1 -0
- package/dist/visual-animation.js +35 -0
- package/dist/visual-animation.js.map +1 -0
- package/package.json +38 -0
package/dist/session.js
ADDED
|
@@ -0,0 +1,1100 @@
|
|
|
1
|
+
import { gameSnapshot } from "@nodetool-ai/protocol";
|
|
2
|
+
import { validateGame } from "./validate.js";
|
|
3
|
+
import { evaluateVisual } from "./visual-animation.js";
|
|
4
|
+
import { FACE_LEFT, FACE_RIGHT, faceOf, queryTiles, sweepBox, tileCollision } from "./physics.js";
|
|
5
|
+
import { hasGameScripts, prepareGameScripts, scriptSourceKey } from "./scripts.js";
|
|
6
|
+
function overlaps(a, b) {
|
|
7
|
+
const ac = a.definition.collider2d;
|
|
8
|
+
const bc = b.definition.collider2d;
|
|
9
|
+
if (!ac || !bc || !a.active || !b.active) {
|
|
10
|
+
return false;
|
|
11
|
+
}
|
|
12
|
+
return Math.abs(a.x - b.x) * 2 < ac.width + bc.width &&
|
|
13
|
+
Math.abs(a.y - b.y) * 2 < ac.height + bc.height;
|
|
14
|
+
}
|
|
15
|
+
const MAX_EVENTS_PER_TICK = 512;
|
|
16
|
+
const MAX_SPAWNED_INSTANCES = 1024;
|
|
17
|
+
function contactKey(a, b) {
|
|
18
|
+
return a < b ? JSON.stringify([a, b]) : JSON.stringify([b, a]);
|
|
19
|
+
}
|
|
20
|
+
function canCollide(a, b) {
|
|
21
|
+
const ac = a.definition.collider2d;
|
|
22
|
+
const bc = b.definition.collider2d;
|
|
23
|
+
return Boolean(ac && bc && a.active && b.active &&
|
|
24
|
+
((ac.mask ?? 0xffffffff) & (bc.category ?? 1)) !== 0 &&
|
|
25
|
+
((bc.mask ?? 0xffffffff) & (ac.category ?? 1)) !== 0);
|
|
26
|
+
}
|
|
27
|
+
function colliderBox(state) {
|
|
28
|
+
const collider = state.definition.collider2d;
|
|
29
|
+
return collider ? { x: state.x, y: state.y, halfWidth: collider.width / 2, halfHeight: collider.height / 2 } : undefined;
|
|
30
|
+
}
|
|
31
|
+
/** Sweep one entity's collider through a displacement against another entity's collider. */
|
|
32
|
+
function sweepAabb(moving, other, dx, dy) {
|
|
33
|
+
const a = colliderBox(moving);
|
|
34
|
+
const b = colliderBox(other);
|
|
35
|
+
if (!a || !b) {
|
|
36
|
+
return undefined;
|
|
37
|
+
}
|
|
38
|
+
return sweepBox(a, b, dx, dy, Boolean(moving.definition.collider2d?.sensor || other.definition.collider2d?.sensor));
|
|
39
|
+
}
|
|
40
|
+
function obstaclesOf(state, minX, minY, maxX, maxY, into) {
|
|
41
|
+
const entity = state.definition;
|
|
42
|
+
const collider = entity.collider2d;
|
|
43
|
+
if (collider && Math.abs(state.x - (minX + maxX) / 2) * 2 <= maxX - minX + collider.width &&
|
|
44
|
+
Math.abs(state.y - (minY + maxY) / 2) * 2 <= maxY - minY + collider.height) {
|
|
45
|
+
into.push({ owner: state, box: { x: state.x, y: state.y, halfWidth: collider.width / 2, halfHeight: collider.height / 2 },
|
|
46
|
+
solid: entity.body2d?.type === "static", sensor: collider.sensor, oneWay: collider.oneWay ?? false, internal: 0,
|
|
47
|
+
category: collider.category ?? 1, mask: collider.mask ?? 0xffffffff });
|
|
48
|
+
}
|
|
49
|
+
const tilemap = entity.tilemap;
|
|
50
|
+
if (tilemap && tilemap.tiles.length > 0) {
|
|
51
|
+
for (const tile of queryTiles(tileCollision(tilemap), minX - state.x, minY - state.y, maxX - state.x, maxY - state.y)) {
|
|
52
|
+
into.push({ owner: state, box: { x: state.x + tile.x, y: state.y + tile.y, halfWidth: tile.halfWidth, halfHeight: tile.halfHeight },
|
|
53
|
+
solid: true, sensor: false, oneWay: tile.oneWay, internal: tile.internal,
|
|
54
|
+
category: tilemap.category ?? 1, mask: tilemap.mask ?? 0xffffffff });
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
function canCollideObstacle(state, obstacle) {
|
|
59
|
+
const collider = state.definition.collider2d;
|
|
60
|
+
return Boolean(collider && obstacle.owner.active && obstacle.owner !== state &&
|
|
61
|
+
((collider.mask ?? 0xffffffff) & obstacle.category) !== 0 &&
|
|
62
|
+
(obstacle.mask & (collider.category ?? 1)) !== 0);
|
|
63
|
+
}
|
|
64
|
+
const TOUCH_EPSILON = 1e-3;
|
|
65
|
+
const RIDE_EPSILON = 0.02;
|
|
66
|
+
function initialState(entity, world, spawnTick = 0) {
|
|
67
|
+
const health = entity.behaviors.find((behavior) => behavior.kind === "health");
|
|
68
|
+
const patrol = entity.behaviors.find((behavior) => behavior.kind === "patrol");
|
|
69
|
+
const state = {
|
|
70
|
+
definition: entity,
|
|
71
|
+
spawnTick,
|
|
72
|
+
x: world.x,
|
|
73
|
+
y: world.y,
|
|
74
|
+
previousX: world.x,
|
|
75
|
+
previousY: world.y,
|
|
76
|
+
rotation: world.rotation,
|
|
77
|
+
scaleX: world.scaleX,
|
|
78
|
+
scaleY: world.scaleY,
|
|
79
|
+
velocityX: entity.body2d?.velocity.x ?? 0,
|
|
80
|
+
velocityY: entity.body2d?.velocity.y ?? 0,
|
|
81
|
+
active: !entity.templateOnly
|
|
82
|
+
};
|
|
83
|
+
if (health?.kind === "health") {
|
|
84
|
+
state.health = health.maximum;
|
|
85
|
+
}
|
|
86
|
+
if (patrol?.kind === "patrol") {
|
|
87
|
+
state.patrolOrigin = patrol.axis === "x" ? state.x : state.y;
|
|
88
|
+
state.patrolDirection = 1;
|
|
89
|
+
}
|
|
90
|
+
return state;
|
|
91
|
+
}
|
|
92
|
+
function initialSceneStates(scene, spawnTick = 0) {
|
|
93
|
+
const definitions = new Map(scene.entities.map((entity) => [entity.id, entity]));
|
|
94
|
+
const children = new Map();
|
|
95
|
+
const queue = [];
|
|
96
|
+
for (const entity of scene.entities) {
|
|
97
|
+
if (!entity.parentId) {
|
|
98
|
+
queue.push(entity.id);
|
|
99
|
+
}
|
|
100
|
+
else {
|
|
101
|
+
const siblings = children.get(entity.parentId) ?? [];
|
|
102
|
+
siblings.push(entity.id);
|
|
103
|
+
children.set(entity.parentId, siblings);
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
const transforms = new Map();
|
|
107
|
+
for (let head = 0; head < queue.length; head += 1) {
|
|
108
|
+
const id = queue[head];
|
|
109
|
+
const entity = definitions.get(id);
|
|
110
|
+
if (!entity)
|
|
111
|
+
continue;
|
|
112
|
+
const local = entity.transform2d;
|
|
113
|
+
const ancestor = entity.parentId ? transforms.get(entity.parentId) : undefined;
|
|
114
|
+
if (!ancestor) {
|
|
115
|
+
const world = { x: local.x, y: local.y, rotation: local.rotation, scaleX: local.scaleX, scaleY: local.scaleY };
|
|
116
|
+
transforms.set(entity.id, world);
|
|
117
|
+
}
|
|
118
|
+
else {
|
|
119
|
+
const x = local.x * ancestor.scaleX;
|
|
120
|
+
const y = local.y * ancestor.scaleY;
|
|
121
|
+
const cos = Math.cos(ancestor.rotation);
|
|
122
|
+
const sin = Math.sin(ancestor.rotation);
|
|
123
|
+
transforms.set(entity.id, {
|
|
124
|
+
x: ancestor.x + x * cos - y * sin,
|
|
125
|
+
y: ancestor.y + x * sin + y * cos,
|
|
126
|
+
rotation: ancestor.rotation + local.rotation,
|
|
127
|
+
scaleX: ancestor.scaleX * local.scaleX,
|
|
128
|
+
scaleY: ancestor.scaleY * local.scaleY
|
|
129
|
+
});
|
|
130
|
+
}
|
|
131
|
+
for (const childId of children.get(id) ?? [])
|
|
132
|
+
queue.push(childId);
|
|
133
|
+
}
|
|
134
|
+
return scene.entities.map((entity) => {
|
|
135
|
+
const world = transforms.get(entity.id);
|
|
136
|
+
if (!world)
|
|
137
|
+
throw new Error(`Missing world transform for ${entity.id}`);
|
|
138
|
+
return initialState(entity, world, spawnTick);
|
|
139
|
+
});
|
|
140
|
+
}
|
|
141
|
+
/** The animator's current frame: the clip a script selected, or the default frames from spawn. */
|
|
142
|
+
function animationFrame(state, tick) {
|
|
143
|
+
const animator = state.definition.animator;
|
|
144
|
+
if (!animator)
|
|
145
|
+
return undefined;
|
|
146
|
+
const clip = (state.animation !== undefined ? animator.clips?.[state.animation] : undefined) ?? animator;
|
|
147
|
+
const age = tick - (state.animation !== undefined ? state.animationTick ?? state.spawnTick : state.spawnTick);
|
|
148
|
+
const index = Math.floor(Math.max(0, age) / clip.ticksPerFrame);
|
|
149
|
+
return clip.frames[clip.loop ? index % clip.frames.length : Math.min(index, clip.frames.length - 1)];
|
|
150
|
+
}
|
|
151
|
+
const MAX_LIGHTS = 32;
|
|
152
|
+
function frameFor(document, scene, states, tick, score, won, hud) {
|
|
153
|
+
const cameraState = states.find((state) => state.active && state.definition.camera2d);
|
|
154
|
+
const camera = cameraState?.definition.camera2d;
|
|
155
|
+
const sprites = [];
|
|
156
|
+
const tiles = [];
|
|
157
|
+
const cameraX = cameraState?.x ?? 0;
|
|
158
|
+
const cameraY = cameraState?.y ?? 0;
|
|
159
|
+
// Tiles and lights outside the view plus a margin never reach the renderer, so large levels stay cheap.
|
|
160
|
+
const viewHalfWidth = (camera?.width ?? 16) / (2 * (camera?.zoom ?? 1));
|
|
161
|
+
const viewHalfHeight = (camera?.height ?? 9) / (2 * (camera?.zoom ?? 1));
|
|
162
|
+
const cullHalfWidth = viewHalfWidth * 1.5 + 2;
|
|
163
|
+
const cullHalfHeight = viewHalfHeight * 1.5 + 2;
|
|
164
|
+
const entityLights = [];
|
|
165
|
+
for (const state of states) {
|
|
166
|
+
if (!state.active) {
|
|
167
|
+
continue;
|
|
168
|
+
}
|
|
169
|
+
const entity = state.definition;
|
|
170
|
+
if (entity.sprite) {
|
|
171
|
+
const spriteDefinition = entity.sprite;
|
|
172
|
+
const binding = document.assets[entity.sprite.assetId];
|
|
173
|
+
const age = tick - state.spawnTick;
|
|
174
|
+
const lifetime = entity.behaviors.find((behavior) => behavior.kind === "lifetime");
|
|
175
|
+
const progress = lifetime?.kind === "lifetime" ? Math.min(1, age / lifetime.ticks) : 0;
|
|
176
|
+
const previousProgress = lifetime?.kind === "lifetime" ? Math.min(1, Math.max(0, age - 1) / lifetime.ticks) : 0;
|
|
177
|
+
const lifeScale = lifetime?.kind === "lifetime" ? 1 + (lifetime.endScale - 1) * progress : 1;
|
|
178
|
+
const previousLifeScale = lifetime?.kind === "lifetime" ? 1 + (lifetime.endScale - 1) * previousProgress : 1;
|
|
179
|
+
const lifeOpacity = lifetime?.kind === "lifetime" && lifetime.fade ? 1 - progress : 1;
|
|
180
|
+
const previousLifeOpacity = lifetime?.kind === "lifetime" && lifetime.fade ? 1 - previousProgress : 1;
|
|
181
|
+
const visual = state.visual;
|
|
182
|
+
const authored = evaluateVisual(entity, age, state.rotation, state.scaleX, state.scaleY);
|
|
183
|
+
const previousAuthored = evaluateVisual(entity, Math.max(0, age - 1), state.rotation, state.scaleX, state.scaleY);
|
|
184
|
+
const opacity = (visual?.opacity ?? authored.opacity) * lifeOpacity;
|
|
185
|
+
const previousOpacity = (visual?.opacity ?? previousAuthored.opacity) * previousLifeOpacity;
|
|
186
|
+
const sprite = {
|
|
187
|
+
entityId: entity.id,
|
|
188
|
+
assetId: entity.sprite.assetId,
|
|
189
|
+
x: state.x,
|
|
190
|
+
y: state.y,
|
|
191
|
+
previousX: state.previousX,
|
|
192
|
+
previousY: state.previousY,
|
|
193
|
+
rotation: visual?.rotation ?? authored.rotation,
|
|
194
|
+
previousRotation: visual?.rotation ?? previousAuthored.rotation,
|
|
195
|
+
scaleX: (visual?.scaleX ?? authored.scaleX) * lifeScale,
|
|
196
|
+
previousScaleX: (visual?.scaleX ?? previousAuthored.scaleX) * previousLifeScale,
|
|
197
|
+
scaleY: (visual?.scaleY ?? authored.scaleY) * lifeScale,
|
|
198
|
+
previousScaleY: (visual?.scaleY ?? previousAuthored.scaleY) * previousLifeScale,
|
|
199
|
+
width: entity.sprite.width,
|
|
200
|
+
height: entity.sprite.height,
|
|
201
|
+
layer: entity.sprite.layer
|
|
202
|
+
};
|
|
203
|
+
const spriteFrame = animationFrame(state, tick) ?? entity.sprite.frame ?? binding?.frame;
|
|
204
|
+
if (document.schemaVersion === 2 && binding) {
|
|
205
|
+
const sourceWidth = spriteFrame?.width ?? binding.trim?.sourceWidth ?? binding.width;
|
|
206
|
+
const sourceHeight = spriteFrame?.height ?? binding.trim?.sourceHeight ?? binding.height;
|
|
207
|
+
const renderedWidth = spriteFrame?.width ?? binding.width;
|
|
208
|
+
const renderedHeight = spriteFrame?.height ?? binding.height;
|
|
209
|
+
const cropX = spriteFrame ? 0 : binding.trim?.x ?? 0;
|
|
210
|
+
const cropY = spriteFrame ? 0 : binding.trim?.y ?? 0;
|
|
211
|
+
const anchorOffset = (rotation, scaleX, scaleY) => {
|
|
212
|
+
const x = ((cropX + renderedWidth / 2) / sourceWidth - binding.pivot.x) * spriteDefinition.width * scaleX;
|
|
213
|
+
const y = (binding.pivot.y - (cropY + renderedHeight / 2) / sourceHeight) * spriteDefinition.height * scaleY;
|
|
214
|
+
const cosine = Math.cos(rotation);
|
|
215
|
+
const sine = Math.sin(rotation);
|
|
216
|
+
return { x: x * cosine - y * sine, y: x * sine + y * cosine };
|
|
217
|
+
};
|
|
218
|
+
const current = anchorOffset(sprite.rotation, sprite.scaleX, sprite.scaleY);
|
|
219
|
+
const previous = anchorOffset(sprite.previousRotation ?? sprite.rotation, sprite.previousScaleX ?? sprite.scaleX, sprite.previousScaleY ?? sprite.scaleY);
|
|
220
|
+
sprite.x += current.x;
|
|
221
|
+
sprite.y += current.y;
|
|
222
|
+
sprite.previousX += previous.x;
|
|
223
|
+
sprite.previousY += previous.y;
|
|
224
|
+
sprite.width *= renderedWidth / sourceWidth;
|
|
225
|
+
sprite.height *= renderedHeight / sourceHeight;
|
|
226
|
+
}
|
|
227
|
+
if (spriteFrame) {
|
|
228
|
+
sprite.frame = { ...spriteFrame };
|
|
229
|
+
}
|
|
230
|
+
const tint = visual?.tint ?? authored.tint;
|
|
231
|
+
if (tint)
|
|
232
|
+
sprite.tint = tint;
|
|
233
|
+
const previousTint = visual?.tint ?? previousAuthored.tint;
|
|
234
|
+
if (previousTint)
|
|
235
|
+
sprite.previousTint = previousTint;
|
|
236
|
+
if (opacity !== 1 || entity.sprite.opacity !== undefined)
|
|
237
|
+
sprite.opacity = Math.max(0, Math.min(1, opacity));
|
|
238
|
+
if (previousOpacity !== 1 || entity.sprite.opacity !== undefined)
|
|
239
|
+
sprite.previousOpacity = Math.max(0, Math.min(1, previousOpacity));
|
|
240
|
+
if (entity.sprite.blend === "additive")
|
|
241
|
+
sprite.blend = "additive";
|
|
242
|
+
if (entity.sprite.unlit)
|
|
243
|
+
sprite.unlit = true;
|
|
244
|
+
const facing = entity.sprite.faceMotion;
|
|
245
|
+
const turned = facing !== undefined && state.velocityX !== 0 && (state.velocityX < 0) !== (facing === "left");
|
|
246
|
+
if (visual?.flipX ?? (entity.sprite.flipX || turned))
|
|
247
|
+
sprite.flipX = true;
|
|
248
|
+
if (document.assets[entity.sprite.assetId]?.sampling === "linear")
|
|
249
|
+
sprite.sampling = "linear";
|
|
250
|
+
sprites.push(sprite);
|
|
251
|
+
}
|
|
252
|
+
if (entity.tilemap) {
|
|
253
|
+
for (const tile of entity.tilemap.tiles) {
|
|
254
|
+
if (Math.abs(state.x + tile.x - cameraX) - tile.width / 2 > cullHalfWidth ||
|
|
255
|
+
Math.abs(state.y + tile.y - cameraY) - tile.height / 2 > cullHalfHeight) {
|
|
256
|
+
continue;
|
|
257
|
+
}
|
|
258
|
+
const item = {
|
|
259
|
+
entityId: entity.id,
|
|
260
|
+
assetId: entity.tilemap.assetId,
|
|
261
|
+
x: state.x + tile.x,
|
|
262
|
+
y: state.y + tile.y,
|
|
263
|
+
width: tile.width,
|
|
264
|
+
height: tile.height,
|
|
265
|
+
layer: entity.tilemap.layer
|
|
266
|
+
};
|
|
267
|
+
const tileFrame = tile.frame ?? document.assets[entity.tilemap.assetId]?.frame;
|
|
268
|
+
if (tileFrame) {
|
|
269
|
+
item.frame = { ...tileFrame };
|
|
270
|
+
}
|
|
271
|
+
if (document.assets[entity.tilemap.assetId]?.sampling === "linear")
|
|
272
|
+
item.sampling = "linear";
|
|
273
|
+
tiles.push(item);
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
if (entity.light2d && scene.lighting) {
|
|
277
|
+
const light = entity.light2d;
|
|
278
|
+
const x = state.x + (light.offset?.x ?? 0);
|
|
279
|
+
const y = state.y + (light.offset?.y ?? 0);
|
|
280
|
+
if (Math.abs(x - cameraX) - light.radius <= viewHalfWidth && Math.abs(y - cameraY) - light.radius <= viewHalfHeight) {
|
|
281
|
+
entityLights.push({ x, y, color: light.color, intensity: light.intensity, radius: light.radius, falloff: light.falloff,
|
|
282
|
+
distance: Math.hypot(x - cameraX, y - cameraY) });
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
sprites.sort((a, b) => a.layer - b.layer);
|
|
287
|
+
tiles.sort((a, b) => a.layer - b.layer);
|
|
288
|
+
const frame = {
|
|
289
|
+
gameId: document.id,
|
|
290
|
+
fonts: Object.fromEntries(Object.entries(document.assets).filter(([, binding]) => binding.mediaKind === "font")),
|
|
291
|
+
tick,
|
|
292
|
+
width: camera?.width ?? 16,
|
|
293
|
+
height: camera?.height ?? 9,
|
|
294
|
+
pixelsPerUnit: document.pixelsPerUnit,
|
|
295
|
+
camera: { x: cameraState?.x ?? 0, y: cameraState?.y ?? 0, previousX: cameraState?.previousX ?? 0, previousY: cameraState?.previousY ?? 0, zoom: camera?.zoom ?? 1 },
|
|
296
|
+
sprites,
|
|
297
|
+
tiles,
|
|
298
|
+
backgrounds: (scene.backgrounds ?? []).map((layer) => document.assets[layer.assetId]?.sampling === "linear" ? { ...layer, sampling: "linear" } : layer),
|
|
299
|
+
// A script label with the id of a built-in label replaces it.
|
|
300
|
+
hud: [
|
|
301
|
+
...(usesCollectibles(document) && !hud.has("score") ? [{ id: "score", text: `Score: ${score}`, x: 16, y: 16 }] : []),
|
|
302
|
+
...(won && !hud.has("win") ? [{ id: "win", text: "You win!", x: 16, y: 48 }] : []),
|
|
303
|
+
...[...hud.values()].map((label) => ({ ...label }))
|
|
304
|
+
]
|
|
305
|
+
};
|
|
306
|
+
if (scene.lighting) {
|
|
307
|
+
// Entity lights follow their entities; the nearest ones fill the slots the scene's fixed lights leave.
|
|
308
|
+
const free = Math.max(0, MAX_LIGHTS - scene.lighting.points.length);
|
|
309
|
+
const moving = entityLights.sort((a, b) => a.distance - b.distance).slice(0, free)
|
|
310
|
+
.map(({ distance: _distance, ...point }) => point);
|
|
311
|
+
frame.lighting = moving.length === 0 ? scene.lighting : { ...scene.lighting, points: [...scene.lighting.points, ...moving] };
|
|
312
|
+
}
|
|
313
|
+
return frame;
|
|
314
|
+
}
|
|
315
|
+
function usesCollectibles(document) {
|
|
316
|
+
return document.scenes.some((scene) => scene.entities.some((entity) => entity.behaviors.some((behavior) => behavior.kind === "collectible" || behavior.kind === "winWhenCollected")));
|
|
317
|
+
}
|
|
318
|
+
/** One session owns mutable simulation state. All boundaries remain plain data. */
|
|
319
|
+
function createGameSessionWithRunner(value, seed, savedSnapshot, eventSink, scriptRunner) {
|
|
320
|
+
const validation = validateGame(value);
|
|
321
|
+
if (!validation.valid || !validation.document) {
|
|
322
|
+
throw new Error(`Invalid game: ${validation.errors.join("; ")}`);
|
|
323
|
+
}
|
|
324
|
+
const document = validation.document;
|
|
325
|
+
if (!Number.isSafeInteger(seed) || seed < 0) {
|
|
326
|
+
throw new Error("Game seed must be a nonnegative safe integer");
|
|
327
|
+
}
|
|
328
|
+
if (hasGameScripts(document) && !scriptRunner) {
|
|
329
|
+
throw new Error("Scripted games require createScriptedGameSession");
|
|
330
|
+
}
|
|
331
|
+
let sceneId = document.entrySceneId;
|
|
332
|
+
const initialScene = document.scenes.find((candidate) => candidate.id === sceneId);
|
|
333
|
+
if (!initialScene) {
|
|
334
|
+
throw new Error(`Missing entry scene ${sceneId}`);
|
|
335
|
+
}
|
|
336
|
+
let scene = initialScene;
|
|
337
|
+
let music = scene.music ? {
|
|
338
|
+
voiceId: `scene:${scene.id}:music`, assetId: scene.music.assetId, startTick: 0,
|
|
339
|
+
volume: scene.music.volume, fadeInTicks: scene.music.fadeInTicks, fadeOutTicks: scene.music.fadeOutTicks
|
|
340
|
+
} : null;
|
|
341
|
+
let states = initialSceneStates(scene);
|
|
342
|
+
let tick = 0;
|
|
343
|
+
let score = 0;
|
|
344
|
+
let won = false;
|
|
345
|
+
let rngState = seed >>> 0;
|
|
346
|
+
let spawnSequence = 0;
|
|
347
|
+
let previousEvents = [];
|
|
348
|
+
let activeContacts = new Map();
|
|
349
|
+
let scriptState = {};
|
|
350
|
+
let hud = new Map();
|
|
351
|
+
let disposed = false;
|
|
352
|
+
let failed = false;
|
|
353
|
+
if (savedSnapshot) {
|
|
354
|
+
const parsed = gameSnapshot.parse(savedSnapshot);
|
|
355
|
+
if (parsed.gameRevision !== document.revision || parsed.engineVersion !== document.engineVersion) {
|
|
356
|
+
throw new Error("Save revision or engine version does not match the game");
|
|
357
|
+
}
|
|
358
|
+
const savedScene = document.scenes.find((candidate) => candidate.id === parsed.sceneId);
|
|
359
|
+
if (!savedScene) {
|
|
360
|
+
throw new Error(`Save refers to missing scene ${parsed.sceneId}`);
|
|
361
|
+
}
|
|
362
|
+
scene = savedScene;
|
|
363
|
+
sceneId = savedScene.id;
|
|
364
|
+
music = parsed.music ?? (savedScene.music ? {
|
|
365
|
+
voiceId: `scene:${savedScene.id}:music`, assetId: savedScene.music.assetId, startTick: parsed.tick,
|
|
366
|
+
volume: savedScene.music.volume, fadeInTicks: savedScene.music.fadeInTicks, fadeOutTicks: savedScene.music.fadeOutTicks
|
|
367
|
+
} : null);
|
|
368
|
+
if (music && (!savedScene.music || music.assetId !== savedScene.music.assetId || music.voiceId !== `scene:${savedScene.id}:music` || music.startTick > parsed.tick)) {
|
|
369
|
+
throw new Error("Save music does not match the scene");
|
|
370
|
+
}
|
|
371
|
+
states = initialSceneStates(savedScene, parsed.tick);
|
|
372
|
+
const byId = new Map(parsed.entities.map((entity) => [entity.id, entity]));
|
|
373
|
+
if (byId.size !== parsed.entities.length || states.some((state) => !byId.has(state.definition.id))) {
|
|
374
|
+
throw new Error("Save entity set does not match the game revision");
|
|
375
|
+
}
|
|
376
|
+
for (const saved of parsed.entities) {
|
|
377
|
+
if (!saved.sourceId) {
|
|
378
|
+
if (!savedScene.entities.some((entity) => entity.id === saved.id)) {
|
|
379
|
+
throw new Error(`Save has unknown entity ${saved.id}`);
|
|
380
|
+
}
|
|
381
|
+
continue;
|
|
382
|
+
}
|
|
383
|
+
const source = savedScene.entities.find((entity) => entity.id === saved.sourceId && entity.templateOnly);
|
|
384
|
+
if (!source) {
|
|
385
|
+
throw new Error(`Save refers to missing spawn template ${saved.sourceId}`);
|
|
386
|
+
}
|
|
387
|
+
const sourceState = states.find((state) => state.definition.id === source.id);
|
|
388
|
+
if (!sourceState)
|
|
389
|
+
throw new Error(`Missing spawn template state ${source.id}`);
|
|
390
|
+
const spawned = initialState({ ...source, id: saved.id, templateOnly: false }, sourceState, saved.spawnTick ?? 0);
|
|
391
|
+
states.push({ ...spawned, sourceId: source.id });
|
|
392
|
+
}
|
|
393
|
+
for (const state of states) {
|
|
394
|
+
const saved = byId.get(state.definition.id);
|
|
395
|
+
if (!saved) {
|
|
396
|
+
continue;
|
|
397
|
+
}
|
|
398
|
+
state.x = saved.x;
|
|
399
|
+
state.y = saved.y;
|
|
400
|
+
state.previousX = saved.previousX;
|
|
401
|
+
state.previousY = saved.previousY;
|
|
402
|
+
state.velocityX = saved.velocityX;
|
|
403
|
+
state.velocityY = saved.velocityY;
|
|
404
|
+
state.spawnTick = saved.spawnTick ?? 0;
|
|
405
|
+
state.active = saved.active;
|
|
406
|
+
state.health = saved.health;
|
|
407
|
+
state.patrolOrigin = saved.patrolOrigin;
|
|
408
|
+
state.patrolDirection = saved.patrolDirection;
|
|
409
|
+
state.animation = saved.animation;
|
|
410
|
+
state.animationTick = saved.animationTick;
|
|
411
|
+
const visual = {};
|
|
412
|
+
if (saved.flipX !== undefined)
|
|
413
|
+
visual.flipX = saved.flipX;
|
|
414
|
+
if (saved.rotation !== undefined)
|
|
415
|
+
visual.rotation = saved.rotation;
|
|
416
|
+
if (saved.scaleX !== undefined)
|
|
417
|
+
visual.scaleX = saved.scaleX;
|
|
418
|
+
if (saved.scaleY !== undefined)
|
|
419
|
+
visual.scaleY = saved.scaleY;
|
|
420
|
+
if (saved.tint !== undefined)
|
|
421
|
+
visual.tint = saved.tint;
|
|
422
|
+
if (saved.opacity !== undefined)
|
|
423
|
+
visual.opacity = saved.opacity;
|
|
424
|
+
state.visual = Object.keys(visual).length > 0 ? visual : undefined;
|
|
425
|
+
}
|
|
426
|
+
tick = parsed.tick;
|
|
427
|
+
score = parsed.score;
|
|
428
|
+
won = parsed.won;
|
|
429
|
+
rngState = parsed.rngState;
|
|
430
|
+
spawnSequence = parsed.spawnSequence;
|
|
431
|
+
previousEvents = structuredClone(parsed.pendingEvents);
|
|
432
|
+
activeContacts = new Map(parsed.activeContacts.map((pair) => [contactKey(pair.entityId, pair.otherId), { ...pair, normalX: 0, normalY: 0 }]));
|
|
433
|
+
scriptState = structuredClone(parsed.scriptState);
|
|
434
|
+
hud = new Map(parsed.hud.map((label) => [label.id, { ...label }]));
|
|
435
|
+
}
|
|
436
|
+
function snapshot() {
|
|
437
|
+
if (disposed) {
|
|
438
|
+
throw new Error("Game session is disposed");
|
|
439
|
+
}
|
|
440
|
+
if (failed) {
|
|
441
|
+
throw new Error("Game session stopped after a failed step");
|
|
442
|
+
}
|
|
443
|
+
return {
|
|
444
|
+
gameRevision: document.revision,
|
|
445
|
+
engineVersion: "1",
|
|
446
|
+
sceneId,
|
|
447
|
+
tick,
|
|
448
|
+
rngState,
|
|
449
|
+
score,
|
|
450
|
+
won,
|
|
451
|
+
music: music ? { ...music } : null,
|
|
452
|
+
spawnSequence,
|
|
453
|
+
pendingEvents: structuredClone(previousEvents),
|
|
454
|
+
activeContacts: [...activeContacts.values()].map(({ entityId, otherId, sensor }) => ({ entityId, otherId, sensor })),
|
|
455
|
+
scriptState: structuredClone(scriptState),
|
|
456
|
+
hud: [...hud.values()].map((label) => ({ ...label })),
|
|
457
|
+
entities: states.map((state) => {
|
|
458
|
+
const entity = {
|
|
459
|
+
id: state.definition.id,
|
|
460
|
+
x: state.x,
|
|
461
|
+
y: state.y,
|
|
462
|
+
previousX: state.previousX,
|
|
463
|
+
previousY: state.previousY,
|
|
464
|
+
velocityX: state.velocityX,
|
|
465
|
+
velocityY: state.velocityY,
|
|
466
|
+
active: state.active
|
|
467
|
+
};
|
|
468
|
+
entity.spawnTick = state.spawnTick;
|
|
469
|
+
if (state.sourceId) {
|
|
470
|
+
entity.sourceId = state.sourceId;
|
|
471
|
+
}
|
|
472
|
+
if (state.visual)
|
|
473
|
+
Object.assign(entity, state.visual);
|
|
474
|
+
if (state.health !== undefined)
|
|
475
|
+
entity.health = state.health;
|
|
476
|
+
if (state.patrolOrigin !== undefined)
|
|
477
|
+
entity.patrolOrigin = state.patrolOrigin;
|
|
478
|
+
if (state.patrolDirection !== undefined)
|
|
479
|
+
entity.patrolDirection = state.patrolDirection;
|
|
480
|
+
if (state.animation !== undefined)
|
|
481
|
+
entity.animation = state.animation;
|
|
482
|
+
if (state.animationTick !== undefined)
|
|
483
|
+
entity.animationTick = state.animationTick;
|
|
484
|
+
return entity;
|
|
485
|
+
})
|
|
486
|
+
};
|
|
487
|
+
}
|
|
488
|
+
function isSpawnedId(entityId) {
|
|
489
|
+
const separator = entityId.lastIndexOf("#");
|
|
490
|
+
const prefabId = entityId.slice(0, separator);
|
|
491
|
+
return separator > 0 && scene.entities.some((entity) => entity.templateOnly && entity.id === prefabId);
|
|
492
|
+
}
|
|
493
|
+
function gravityScaleOf(state) {
|
|
494
|
+
return scene.gravity && state.definition.body2d?.type === "kinematic" ? state.definition.body2d.gravityScale ?? 1 : 0;
|
|
495
|
+
}
|
|
496
|
+
function obstacleStates() {
|
|
497
|
+
return states.filter((state) => state.active && state.definition.body2d?.type !== "kinematic" &&
|
|
498
|
+
(state.definition.collider2d !== undefined || (state.definition.tilemap?.tiles.length ?? 0) > 0));
|
|
499
|
+
}
|
|
500
|
+
/** Solid obstacles that could block this body, near its collider grown by a margin. */
|
|
501
|
+
function solidsNear(state, margin, only) {
|
|
502
|
+
const box = colliderBox(state);
|
|
503
|
+
if (!box || box && state.definition.collider2d?.sensor)
|
|
504
|
+
return [];
|
|
505
|
+
const found = [];
|
|
506
|
+
for (const other of only ? [only] : obstacleStates()) {
|
|
507
|
+
if (other !== state) {
|
|
508
|
+
obstaclesOf(other, box.x - box.halfWidth - margin, box.y - box.halfHeight - margin, box.x + box.halfWidth + margin, box.y + box.halfHeight + margin, found);
|
|
509
|
+
}
|
|
510
|
+
}
|
|
511
|
+
return found.filter((obstacle) => obstacle.solid && !obstacle.sensor && canCollideObstacle(state, obstacle));
|
|
512
|
+
}
|
|
513
|
+
/** Sides of the collider that rest against a solid. A one-way solid supports only from below. */
|
|
514
|
+
function touchingOf(state) {
|
|
515
|
+
const box = colliderBox(state);
|
|
516
|
+
const touching = { down: false, up: false, left: false, right: false };
|
|
517
|
+
if (!box)
|
|
518
|
+
return touching;
|
|
519
|
+
for (const obstacle of solidsNear(state, TOUCH_EPSILON)) {
|
|
520
|
+
const o = obstacle.box;
|
|
521
|
+
const overlapX = Math.min(box.x + box.halfWidth, o.x + o.halfWidth) - Math.max(box.x - box.halfWidth, o.x - o.halfWidth);
|
|
522
|
+
const overlapY = Math.min(box.y + box.halfHeight, o.y + o.halfHeight) - Math.max(box.y - box.halfHeight, o.y - o.halfHeight);
|
|
523
|
+
if (overlapX > TOUCH_EPSILON && Math.abs(box.y - box.halfHeight - (o.y + o.halfHeight)) <= TOUCH_EPSILON)
|
|
524
|
+
touching.down = true;
|
|
525
|
+
if (obstacle.oneWay)
|
|
526
|
+
continue;
|
|
527
|
+
if (overlapX > TOUCH_EPSILON && Math.abs(box.y + box.halfHeight - (o.y - o.halfHeight)) <= TOUCH_EPSILON)
|
|
528
|
+
touching.up = true;
|
|
529
|
+
if (overlapY > TOUCH_EPSILON && (obstacle.internal & FACE_RIGHT) === 0 &&
|
|
530
|
+
Math.abs(box.x - box.halfWidth - (o.x + o.halfWidth)) <= TOUCH_EPSILON)
|
|
531
|
+
touching.left = true;
|
|
532
|
+
if (overlapY > TOUCH_EPSILON && (obstacle.internal & FACE_LEFT) === 0 &&
|
|
533
|
+
Math.abs(box.x + box.halfWidth - (o.x - o.halfWidth)) <= TOUCH_EPSILON)
|
|
534
|
+
touching.right = true;
|
|
535
|
+
}
|
|
536
|
+
return touching;
|
|
537
|
+
}
|
|
538
|
+
/** Whether the body rests on top of one of the platform's solids. */
|
|
539
|
+
function standsOn(body, platform) {
|
|
540
|
+
const box = colliderBox(body);
|
|
541
|
+
if (!box)
|
|
542
|
+
return false;
|
|
543
|
+
return solidsNear(body, RIDE_EPSILON, platform).some(({ box: o }) => Math.min(box.x + box.halfWidth, o.x + o.halfWidth) - Math.max(box.x - box.halfWidth, o.x - o.halfWidth) > TOUCH_EPSILON &&
|
|
544
|
+
Math.abs(box.y - box.halfHeight - (o.y + o.halfHeight)) <= RIDE_EPSILON);
|
|
545
|
+
}
|
|
546
|
+
/** Whether ground continues just past the body's leading edge. */
|
|
547
|
+
function solidBelowAhead(state, direction) {
|
|
548
|
+
const box = colliderBox(state);
|
|
549
|
+
if (!box)
|
|
550
|
+
return false;
|
|
551
|
+
const probeX = state.x + direction * (box.halfWidth + 0.05);
|
|
552
|
+
const probeY = state.y - box.halfHeight - 0.1;
|
|
553
|
+
return solidsNear(state, 0.3).some(({ box: o }) => Math.abs(probeX - o.x) <= o.halfWidth && Math.abs(probeY - o.y) <= o.halfHeight);
|
|
554
|
+
}
|
|
555
|
+
function step(input) {
|
|
556
|
+
if (disposed) {
|
|
557
|
+
throw new Error("Game session is disposed");
|
|
558
|
+
}
|
|
559
|
+
if (failed) {
|
|
560
|
+
throw new Error("Game session stopped after a failed step");
|
|
561
|
+
}
|
|
562
|
+
const pressed = new Set(input.pressed);
|
|
563
|
+
for (const action of pressed) {
|
|
564
|
+
if (!document.inputActions.includes(action)) {
|
|
565
|
+
throw new Error(`Unknown input action ${action}`);
|
|
566
|
+
}
|
|
567
|
+
}
|
|
568
|
+
try {
|
|
569
|
+
const events = [];
|
|
570
|
+
const emit = (event) => {
|
|
571
|
+
if (events.length >= MAX_EVENTS_PER_TICK) {
|
|
572
|
+
failed = true;
|
|
573
|
+
throw new Error(`Game event limit exceeded (${MAX_EVENTS_PER_TICK} per tick)`);
|
|
574
|
+
}
|
|
575
|
+
events.push(event);
|
|
576
|
+
eventSink?.(structuredClone(event));
|
|
577
|
+
};
|
|
578
|
+
const queuedDespawns = new Set();
|
|
579
|
+
const queuedSpawns = [];
|
|
580
|
+
let transitionTo;
|
|
581
|
+
const scriptCalls = [];
|
|
582
|
+
for (const state of states) {
|
|
583
|
+
state.previousX = state.x;
|
|
584
|
+
state.previousY = state.y;
|
|
585
|
+
if (!state.active) {
|
|
586
|
+
continue;
|
|
587
|
+
}
|
|
588
|
+
const entity = state.definition;
|
|
589
|
+
for (const [index, behavior] of entity.behaviors.entries()) {
|
|
590
|
+
if (behavior.kind === "movement") {
|
|
591
|
+
const dx = Number(pressed.has(behavior.right)) - Number(pressed.has(behavior.left));
|
|
592
|
+
const dy = Number(pressed.has(behavior.up)) - Number(pressed.has(behavior.down));
|
|
593
|
+
const length = Math.hypot(dx, dy) || 1;
|
|
594
|
+
state.velocityX = (dx / length) * behavior.speed;
|
|
595
|
+
state.velocityY = (dy / length) * behavior.speed;
|
|
596
|
+
}
|
|
597
|
+
else if (behavior.kind === "patrol") {
|
|
598
|
+
const coordinate = behavior.axis === "x" ? state.x : state.y;
|
|
599
|
+
const origin = state.patrolOrigin ?? coordinate;
|
|
600
|
+
// Only travel away from the origin turns the body, so a wall at the limit cannot cancel a turn.
|
|
601
|
+
if ((coordinate - origin) * (state.patrolDirection ?? 1) >= behavior.distance) {
|
|
602
|
+
state.patrolDirection = state.patrolDirection === 1 ? -1 : 1;
|
|
603
|
+
}
|
|
604
|
+
const speed = behavior.speed * (state.patrolDirection ?? 1);
|
|
605
|
+
// A body under gravity keeps its fall speed while it walks.
|
|
606
|
+
const falls = gravityScaleOf(state) !== 0;
|
|
607
|
+
state.velocityX = behavior.axis === "x" ? speed : falls ? state.velocityX : 0;
|
|
608
|
+
state.velocityY = behavior.axis === "y" ? speed : falls ? state.velocityY : 0;
|
|
609
|
+
}
|
|
610
|
+
else if (behavior.kind === "sceneTransition" && previousEvents.some((event) => event.kind === "trigger" && event.event === behavior.onEvent)) {
|
|
611
|
+
transitionTo = behavior.sceneId;
|
|
612
|
+
}
|
|
613
|
+
else if (behavior.kind === "spawn" && previousEvents.some((event) => event.kind === "trigger" && event.event === behavior.onEvent)) {
|
|
614
|
+
queuedSpawns.push({ prefabId: behavior.prefabId });
|
|
615
|
+
}
|
|
616
|
+
else if (behavior.kind === "lifetime" && tick - state.spawnTick >= behavior.ticks) {
|
|
617
|
+
queuedDespawns.add(entity.id);
|
|
618
|
+
}
|
|
619
|
+
else if (behavior.kind === "script") {
|
|
620
|
+
const sourceKey = scriptSourceKey(scene.id, state.sourceId ?? entity.id, index);
|
|
621
|
+
const stateKey = scriptSourceKey(scene.id, entity.id, index);
|
|
622
|
+
scriptCalls.push({ sourceKey, stateKey, entityId: entity.id, source: state.sourceId ?? entity.id, state: scriptState[stateKey] ?? null,
|
|
623
|
+
x: state.x, y: state.y, velocityX: state.velocityX, velocityY: state.velocityY,
|
|
624
|
+
touching: touchingOf(state),
|
|
625
|
+
maxCommands: behavior.maxCommands, maxTickMs: behavior.maxTickMs });
|
|
626
|
+
}
|
|
627
|
+
}
|
|
628
|
+
}
|
|
629
|
+
let scriptStats;
|
|
630
|
+
if (scriptRunner && scriptCalls.length > 0) {
|
|
631
|
+
const world = states
|
|
632
|
+
.filter((state) => state.active && (state.definition.collider2d || state.definition.camera2d))
|
|
633
|
+
.map((state) => ({ id: state.definition.id, source: state.sourceId ?? state.definition.id, x: state.x, y: state.y }));
|
|
634
|
+
const batch = scriptRunner.run(scriptCalls, { tick, pressed: [...pressed], justPressed: input.justPressed, events: previousEvents, world }, rngState);
|
|
635
|
+
const byId = new Map(states.map((state) => [state.definition.id, state]));
|
|
636
|
+
for (const item of batch.results) {
|
|
637
|
+
for (const command of item.commands) {
|
|
638
|
+
if (command.kind === "spawn" && !scene.entities.some((entity) => entity.id === command.prefabId && entity.templateOnly)) {
|
|
639
|
+
throw new Error(`Game script uses missing prefab ${command.prefabId}`);
|
|
640
|
+
}
|
|
641
|
+
if (command.kind === "sceneTransition" && !document.scenes.some((candidate) => candidate.id === command.sceneId)) {
|
|
642
|
+
throw new Error(`Game script uses missing scene ${command.sceneId}`);
|
|
643
|
+
}
|
|
644
|
+
if (command.kind === "playAnimation" && !byId.get(item.entityId)?.definition.animator?.clips?.[command.clip]) {
|
|
645
|
+
throw new Error(`Game script plays missing animation clip ${command.clip} on ${item.entityId}`);
|
|
646
|
+
}
|
|
647
|
+
if (command.kind === "hud" && command.fontId && document.assets[command.fontId]?.mediaKind !== "font") {
|
|
648
|
+
throw new Error(`Game script uses missing font ${command.fontId}`);
|
|
649
|
+
}
|
|
650
|
+
// A spawned instance can expire in the tick before a script reacts to its contact.
|
|
651
|
+
if (command.kind === "despawn" && !byId.get(command.entityId)?.active && !isSpawnedId(command.entityId)) {
|
|
652
|
+
throw new Error(`Game script uses missing entity ${command.entityId}`);
|
|
653
|
+
}
|
|
654
|
+
}
|
|
655
|
+
}
|
|
656
|
+
for (const [index, item] of batch.results.entries()) {
|
|
657
|
+
const call = scriptCalls[index];
|
|
658
|
+
scriptState[call.stateKey] = item.state;
|
|
659
|
+
const state = byId.get(item.entityId);
|
|
660
|
+
if (!state)
|
|
661
|
+
throw new Error(`Game script entity ${item.entityId} disappeared`);
|
|
662
|
+
for (const command of item.commands) {
|
|
663
|
+
if (command.kind === "setVelocity") {
|
|
664
|
+
state.velocityX = command.x;
|
|
665
|
+
state.velocityY = command.y;
|
|
666
|
+
}
|
|
667
|
+
else if (command.kind === "setPosition") {
|
|
668
|
+
state.x = command.x;
|
|
669
|
+
state.y = command.y;
|
|
670
|
+
state.previousX = command.x;
|
|
671
|
+
state.previousY = command.y;
|
|
672
|
+
}
|
|
673
|
+
else if (command.kind === "setVisual") {
|
|
674
|
+
const { kind: _kind, ...visual } = command;
|
|
675
|
+
state.visual = { ...state.visual, ...visual };
|
|
676
|
+
}
|
|
677
|
+
else if (command.kind === "playAnimation") {
|
|
678
|
+
// Replaying the current clip continues it, so scripts can request a clip every tick.
|
|
679
|
+
if (state.animation !== command.clip) {
|
|
680
|
+
state.animation = command.clip;
|
|
681
|
+
state.animationTick = tick + 1;
|
|
682
|
+
}
|
|
683
|
+
}
|
|
684
|
+
else if (command.kind === "hud") {
|
|
685
|
+
const { kind: _kind, ...label } = command;
|
|
686
|
+
if (label.text === "")
|
|
687
|
+
hud.delete(label.id);
|
|
688
|
+
else
|
|
689
|
+
hud.set(label.id, label);
|
|
690
|
+
}
|
|
691
|
+
else if (command.kind === "emit") {
|
|
692
|
+
emit({ kind: "trigger", event: command.event, entityId: item.entityId });
|
|
693
|
+
}
|
|
694
|
+
else if (command.kind === "spawn") {
|
|
695
|
+
const { kind: _kind, ...spawn } = command;
|
|
696
|
+
queuedSpawns.push(spawn);
|
|
697
|
+
}
|
|
698
|
+
else if (command.kind === "despawn") {
|
|
699
|
+
queuedDespawns.add(command.entityId);
|
|
700
|
+
}
|
|
701
|
+
else if (command.kind === "sceneTransition") {
|
|
702
|
+
transitionTo = command.sceneId;
|
|
703
|
+
}
|
|
704
|
+
}
|
|
705
|
+
}
|
|
706
|
+
rngState = batch.rngState;
|
|
707
|
+
scriptStats = batch.stats;
|
|
708
|
+
}
|
|
709
|
+
const dt = 1 / document.tickRate;
|
|
710
|
+
const motionStarts = new Map(states.map((state) => [state.definition.id, { x: state.x, y: state.y }]));
|
|
711
|
+
const currentContacts = new Map();
|
|
712
|
+
const recordContact = (moving, other, hit) => {
|
|
713
|
+
const key = contactKey(moving.definition.id, other.definition.id);
|
|
714
|
+
if (!currentContacts.has(key)) {
|
|
715
|
+
if (events.length + currentContacts.size >= MAX_EVENTS_PER_TICK) {
|
|
716
|
+
throw new Error(`Game event limit exceeded (${MAX_EVENTS_PER_TICK} per tick)`);
|
|
717
|
+
}
|
|
718
|
+
currentContacts.set(key, {
|
|
719
|
+
entityId: moving.definition.id,
|
|
720
|
+
otherId: other.definition.id,
|
|
721
|
+
sensor: Boolean(moving.definition.collider2d?.sensor || other.definition.collider2d?.sensor),
|
|
722
|
+
normalX: hit.normalX,
|
|
723
|
+
normalY: hit.normalY
|
|
724
|
+
});
|
|
725
|
+
}
|
|
726
|
+
};
|
|
727
|
+
const kinematic = states.filter((state) => state.active && state.definition.body2d?.type === "kinematic");
|
|
728
|
+
const obstacles = obstacleStates();
|
|
729
|
+
const gravity = scene.gravity;
|
|
730
|
+
if (gravity) {
|
|
731
|
+
for (const state of kinematic) {
|
|
732
|
+
const scale = gravityScaleOf(state);
|
|
733
|
+
state.velocityX += gravity.x * scale * dt;
|
|
734
|
+
state.velocityY += gravity.y * scale * dt;
|
|
735
|
+
}
|
|
736
|
+
}
|
|
737
|
+
// Static bodies with a velocity are moving solids. They move first and carry the bodies that
|
|
738
|
+
// stand on them; a body in the way is pushed out along the motion.
|
|
739
|
+
const carries = new Map();
|
|
740
|
+
for (const platform of states) {
|
|
741
|
+
if (!platform.active || platform.definition.body2d?.type !== "static" || platform.velocityX === 0 && platform.velocityY === 0) {
|
|
742
|
+
continue;
|
|
743
|
+
}
|
|
744
|
+
const dx = platform.velocityX * dt;
|
|
745
|
+
const dy = platform.velocityY * dt;
|
|
746
|
+
const riders = kinematic.filter((body) => !carries.has(body) && standsOn(body, platform));
|
|
747
|
+
platform.x += dx;
|
|
748
|
+
platform.y += dy;
|
|
749
|
+
for (const rider of riders)
|
|
750
|
+
carries.set(rider, { dx, dy, platform });
|
|
751
|
+
for (const body of kinematic) {
|
|
752
|
+
const box = colliderBox(body);
|
|
753
|
+
if (!box || carries.get(body)?.platform === platform || body.definition.collider2d?.sensor)
|
|
754
|
+
continue;
|
|
755
|
+
const found = [];
|
|
756
|
+
obstaclesOf(platform, body.x - box.halfWidth, body.y - box.halfHeight, body.x + box.halfWidth, body.y + box.halfHeight, found);
|
|
757
|
+
for (const obstacle of found) {
|
|
758
|
+
if (!obstacle.solid || obstacle.sensor || obstacle.oneWay || !canCollideObstacle(body, obstacle))
|
|
759
|
+
continue;
|
|
760
|
+
const o = obstacle.box;
|
|
761
|
+
if (Math.abs(body.x - o.x) >= box.halfWidth + o.halfWidth - TOUCH_EPSILON ||
|
|
762
|
+
Math.abs(body.y - o.y) >= box.halfHeight + o.halfHeight - TOUCH_EPSILON)
|
|
763
|
+
continue;
|
|
764
|
+
if (Math.abs(dy) >= Math.abs(dx))
|
|
765
|
+
body.y = o.y + Math.sign(dy) * (o.halfHeight + box.halfHeight);
|
|
766
|
+
else
|
|
767
|
+
body.x = o.x + Math.sign(dx) * (o.halfWidth + box.halfWidth);
|
|
768
|
+
}
|
|
769
|
+
}
|
|
770
|
+
}
|
|
771
|
+
const moveBody = (state, dx, dy, exclude) => {
|
|
772
|
+
const collider = state.definition.collider2d;
|
|
773
|
+
const blocked = { blockedX: 0, blockedY: 0 };
|
|
774
|
+
if (!collider)
|
|
775
|
+
return blocked;
|
|
776
|
+
const halfWidth = collider.width / 2;
|
|
777
|
+
const halfHeight = collider.height / 2;
|
|
778
|
+
let remainingX = dx;
|
|
779
|
+
let remainingY = dy;
|
|
780
|
+
for (let pass = 0; pass < 2 && (remainingX !== 0 || remainingY !== 0); pass += 1) {
|
|
781
|
+
const box = { x: state.x, y: state.y, halfWidth, halfHeight };
|
|
782
|
+
const found = [];
|
|
783
|
+
const minX = state.x - halfWidth + Math.min(0, remainingX);
|
|
784
|
+
const maxX = state.x + halfWidth + Math.max(0, remainingX);
|
|
785
|
+
const minY = state.y - halfHeight + Math.min(0, remainingY);
|
|
786
|
+
const maxY = state.y + halfHeight + Math.max(0, remainingY);
|
|
787
|
+
for (const other of obstacles) {
|
|
788
|
+
if (other !== state && other !== exclude)
|
|
789
|
+
obstaclesOf(other, minX, minY, maxX, maxY, found);
|
|
790
|
+
}
|
|
791
|
+
const hits = [];
|
|
792
|
+
for (const obstacle of found) {
|
|
793
|
+
if (!canCollideObstacle(state, obstacle))
|
|
794
|
+
continue;
|
|
795
|
+
const hit = sweepBox(box, obstacle.box, remainingX, remainingY, obstacle.sensor || collider.sensor);
|
|
796
|
+
if (!hit)
|
|
797
|
+
continue;
|
|
798
|
+
const blocks = obstacle.solid && !obstacle.sensor && !collider.sensor;
|
|
799
|
+
if (blocks) {
|
|
800
|
+
// A face shared with a neighboring tile is inside the wall, so it never stops a body.
|
|
801
|
+
if ((obstacle.internal & faceOf(hit)) !== 0)
|
|
802
|
+
continue;
|
|
803
|
+
// A one-way solid stops only a body that falls onto its top from above.
|
|
804
|
+
if (obstacle.oneWay && !(hit.normalY > 0 && state.y - halfHeight >= obstacle.box.y + obstacle.box.halfHeight - TOUCH_EPSILON))
|
|
805
|
+
continue;
|
|
806
|
+
}
|
|
807
|
+
hits.push({ obstacle, hit, blocks });
|
|
808
|
+
}
|
|
809
|
+
hits.sort((a, b) => a.hit.time - b.hit.time ||
|
|
810
|
+
(a.obstacle.owner.definition.id < b.obstacle.owner.definition.id ? -1 : a.obstacle.owner.definition.id > b.obstacle.owner.definition.id ? 1 : 0));
|
|
811
|
+
const solid = hits.find((item) => item.blocks);
|
|
812
|
+
const travel = solid?.hit.time ?? 1;
|
|
813
|
+
for (const { obstacle, hit, blocks } of hits) {
|
|
814
|
+
if (hit.time > travel) {
|
|
815
|
+
break;
|
|
816
|
+
}
|
|
817
|
+
if (!blocks || obstacle === solid?.obstacle) {
|
|
818
|
+
recordContact(state, obstacle.owner, hit);
|
|
819
|
+
}
|
|
820
|
+
}
|
|
821
|
+
state.x += remainingX * travel;
|
|
822
|
+
state.y += remainingY * travel;
|
|
823
|
+
if (!solid) {
|
|
824
|
+
break;
|
|
825
|
+
}
|
|
826
|
+
if (solid.hit.normalX !== 0)
|
|
827
|
+
blocked.blockedX = solid.hit.normalX;
|
|
828
|
+
if (solid.hit.normalY !== 0)
|
|
829
|
+
blocked.blockedY = solid.hit.normalY;
|
|
830
|
+
remainingX = solid.hit.normalX === 0 ? remainingX * (1 - travel) : 0;
|
|
831
|
+
remainingY = solid.hit.normalY === 0 ? remainingY * (1 - travel) : 0;
|
|
832
|
+
}
|
|
833
|
+
return blocked;
|
|
834
|
+
};
|
|
835
|
+
for (const state of kinematic) {
|
|
836
|
+
if (!state.definition.collider2d) {
|
|
837
|
+
state.x += state.velocityX * dt;
|
|
838
|
+
state.y += state.velocityY * dt;
|
|
839
|
+
continue;
|
|
840
|
+
}
|
|
841
|
+
const carry = carries.get(state);
|
|
842
|
+
if (carry)
|
|
843
|
+
moveBody(state, carry.dx, carry.dy, carry.platform);
|
|
844
|
+
const { blockedX, blockedY } = moveBody(state, state.velocityX * dt, state.velocityY * dt, undefined);
|
|
845
|
+
// A blocked body loses the velocity that pushed into the solid, so gravity cannot build up while resting.
|
|
846
|
+
if (blockedX * state.velocityX < 0)
|
|
847
|
+
state.velocityX = 0;
|
|
848
|
+
if (blockedY * state.velocityY < 0)
|
|
849
|
+
state.velocityY = 0;
|
|
850
|
+
const patrol = state.definition.behaviors.find((behavior) => behavior.kind === "patrol");
|
|
851
|
+
if (patrol?.kind === "patrol" && patrol.axis === "x") {
|
|
852
|
+
const direction = state.patrolDirection ?? 1;
|
|
853
|
+
const ledge = patrol.turnAtLedges && touchingOf(state).down && !solidBelowAhead(state, direction);
|
|
854
|
+
if (blockedX === -direction || ledge)
|
|
855
|
+
state.patrolDirection = direction === 1 ? -1 : 1;
|
|
856
|
+
}
|
|
857
|
+
}
|
|
858
|
+
for (let index = 0; index < states.length; index += 1) {
|
|
859
|
+
const state = states[index];
|
|
860
|
+
if (!state.active || state.definition.body2d?.type !== "kinematic") {
|
|
861
|
+
continue;
|
|
862
|
+
}
|
|
863
|
+
for (let otherIndex = index + 1; otherIndex < states.length; otherIndex += 1) {
|
|
864
|
+
const other = states[otherIndex];
|
|
865
|
+
if (other.definition.body2d?.type !== "kinematic" || !canCollide(state, other)) {
|
|
866
|
+
continue;
|
|
867
|
+
}
|
|
868
|
+
const stateStart = motionStarts.get(state.definition.id);
|
|
869
|
+
const otherStart = motionStarts.get(other.definition.id);
|
|
870
|
+
if (!stateStart || !otherStart) {
|
|
871
|
+
continue;
|
|
872
|
+
}
|
|
873
|
+
const relativeX = (state.x - stateStart.x) - (other.x - otherStart.x);
|
|
874
|
+
const relativeY = (state.y - stateStart.y) - (other.y - otherStart.y);
|
|
875
|
+
const atStart = { ...state, x: stateStart.x, y: stateStart.y };
|
|
876
|
+
const targetAtStart = { ...other, x: otherStart.x, y: otherStart.y };
|
|
877
|
+
const hit = sweepAabb(atStart, targetAtStart, relativeX, relativeY);
|
|
878
|
+
if (hit) {
|
|
879
|
+
recordContact(state, other, hit);
|
|
880
|
+
}
|
|
881
|
+
}
|
|
882
|
+
}
|
|
883
|
+
const recordTouch = (state, other, a, b) => {
|
|
884
|
+
const horizontalGap = Math.abs(a.x - b.x) - (a.halfWidth + b.halfWidth);
|
|
885
|
+
const verticalGap = Math.abs(a.y - b.y) - (a.halfHeight + b.halfHeight);
|
|
886
|
+
const horizontal = horizontalGap >= verticalGap;
|
|
887
|
+
recordContact(state, other, { time: 0, normalX: horizontal ? Math.sign(a.x - b.x) : 0, normalY: horizontal ? 0 : Math.sign(a.y - b.y) });
|
|
888
|
+
};
|
|
889
|
+
for (const state of kinematic) {
|
|
890
|
+
const box = colliderBox(state);
|
|
891
|
+
if (!box) {
|
|
892
|
+
continue;
|
|
893
|
+
}
|
|
894
|
+
for (const other of kinematic) {
|
|
895
|
+
if (state !== other && canCollide(state, other) && overlaps(state, other)) {
|
|
896
|
+
recordTouch(state, other, box, colliderBox(other));
|
|
897
|
+
}
|
|
898
|
+
}
|
|
899
|
+
const found = [];
|
|
900
|
+
for (const other of obstacles) {
|
|
901
|
+
if (other !== state)
|
|
902
|
+
obstaclesOf(other, box.x - box.halfWidth, box.y - box.halfHeight, box.x + box.halfWidth, box.y + box.halfHeight, found);
|
|
903
|
+
}
|
|
904
|
+
for (const obstacle of found) {
|
|
905
|
+
if (!canCollideObstacle(state, obstacle))
|
|
906
|
+
continue;
|
|
907
|
+
const o = obstacle.box;
|
|
908
|
+
const gapX = Math.abs(box.x - o.x) - (box.halfWidth + o.halfWidth);
|
|
909
|
+
const gapY = Math.abs(box.y - o.y) - (box.halfHeight + o.halfHeight);
|
|
910
|
+
const overlapping = gapX < 0 && gapY < 0;
|
|
911
|
+
const touching = gapX <= 0 && gapY <= 0 && obstacle.solid && !obstacle.sensor;
|
|
912
|
+
if (overlapping || touching)
|
|
913
|
+
recordTouch(state, obstacle.owner, box, o);
|
|
914
|
+
}
|
|
915
|
+
}
|
|
916
|
+
const stateById = new Map(states.map((state) => [state.definition.id, state]));
|
|
917
|
+
for (const [key, pair] of currentContacts) {
|
|
918
|
+
const phase = activeContacts.has(key) ? "stay" : "enter";
|
|
919
|
+
emit({ kind: "contact", entityId: pair.entityId, otherId: pair.otherId, phase, normalX: pair.normalX, normalY: pair.normalY });
|
|
920
|
+
if (phase !== "enter") {
|
|
921
|
+
continue;
|
|
922
|
+
}
|
|
923
|
+
const state = stateById.get(pair.entityId);
|
|
924
|
+
const other = stateById.get(pair.otherId);
|
|
925
|
+
if (!state || !other) {
|
|
926
|
+
continue;
|
|
927
|
+
}
|
|
928
|
+
for (const [actor, target] of [[state, other], [other, state]]) {
|
|
929
|
+
if (actor.definition.body2d?.type !== "kinematic") {
|
|
930
|
+
continue;
|
|
931
|
+
}
|
|
932
|
+
for (const behavior of target.definition.behaviors) {
|
|
933
|
+
// Sensors detect contact but never collect, so patrolling hazards leave pickups alone.
|
|
934
|
+
if (behavior.kind === "collectible" && !actor.definition.collider2d?.sensor && !queuedDespawns.has(target.definition.id)) {
|
|
935
|
+
queuedDespawns.add(target.definition.id);
|
|
936
|
+
score += behavior.score;
|
|
937
|
+
emit({ kind: "collected", entityId: target.definition.id, byId: actor.definition.id, score: behavior.score });
|
|
938
|
+
}
|
|
939
|
+
else if (behavior.kind === "trigger") {
|
|
940
|
+
emit({ kind: "trigger", event: behavior.event, entityId: target.definition.id });
|
|
941
|
+
}
|
|
942
|
+
}
|
|
943
|
+
}
|
|
944
|
+
}
|
|
945
|
+
for (const [key, pair] of activeContacts) {
|
|
946
|
+
if (!currentContacts.has(key)) {
|
|
947
|
+
emit({ kind: "contact", entityId: pair.entityId, otherId: pair.otherId, phase: "exit", normalX: 0, normalY: 0 });
|
|
948
|
+
}
|
|
949
|
+
}
|
|
950
|
+
activeContacts = currentContacts;
|
|
951
|
+
for (const state of states) {
|
|
952
|
+
if (queuedDespawns.has(state.definition.id)) {
|
|
953
|
+
state.active = false;
|
|
954
|
+
}
|
|
955
|
+
for (const behavior of state.definition.behaviors) {
|
|
956
|
+
if (behavior.kind === "winWhenCollected" && !won && score >= behavior.count) {
|
|
957
|
+
won = true;
|
|
958
|
+
emit({ kind: "win", score });
|
|
959
|
+
}
|
|
960
|
+
}
|
|
961
|
+
const audio = state.definition.audioSource;
|
|
962
|
+
if (audio && events.some((event) => (event.kind === audio.onEvent && (event.kind !== "collected" || event.entityId === state.definition.id)) ||
|
|
963
|
+
(event.kind === "trigger" && event.event === audio.onEvent))) {
|
|
964
|
+
emit({ kind: "audio", action: "start", assetId: audio.assetId,
|
|
965
|
+
voiceId: `effect:${sceneId}:${state.definition.id}:${tick + 1}:${events.length}`,
|
|
966
|
+
loop: false, volume: audio.volume, fadeInTicks: 0, fadeOutTicks: 0 });
|
|
967
|
+
}
|
|
968
|
+
}
|
|
969
|
+
if (queuedDespawns.size > 0) {
|
|
970
|
+
// Spawned instances leave the world when despawned; authored entities stay as inactive state.
|
|
971
|
+
states = states.filter((state) => {
|
|
972
|
+
if (!state.sourceId || !queuedDespawns.has(state.definition.id))
|
|
973
|
+
return true;
|
|
974
|
+
state.definition.behaviors.forEach((behavior, index) => {
|
|
975
|
+
if (behavior.kind === "script")
|
|
976
|
+
delete scriptState[scriptSourceKey(scene.id, state.definition.id, index)];
|
|
977
|
+
});
|
|
978
|
+
return false;
|
|
979
|
+
});
|
|
980
|
+
}
|
|
981
|
+
if (states.filter((state) => state.sourceId).length + queuedSpawns.length > MAX_SPAWNED_INSTANCES) {
|
|
982
|
+
failed = true;
|
|
983
|
+
throw new Error(`Game spawned instance limit exceeded (${MAX_SPAWNED_INSTANCES})`);
|
|
984
|
+
}
|
|
985
|
+
for (const spawn of queuedSpawns) {
|
|
986
|
+
const prefabId = spawn.prefabId;
|
|
987
|
+
const source = scene.entities.find((entity) => entity.id === prefabId && entity.templateOnly);
|
|
988
|
+
if (!source) {
|
|
989
|
+
throw new Error(`Missing spawn template ${prefabId}`);
|
|
990
|
+
}
|
|
991
|
+
spawnSequence += 1;
|
|
992
|
+
const sourceState = states.find((state) => state.definition.id === source.id);
|
|
993
|
+
if (!sourceState)
|
|
994
|
+
throw new Error(`Missing spawn template state ${source.id}`);
|
|
995
|
+
const spawned = initialState({ ...source, id: `${prefabId}#${spawnSequence}`, templateOnly: false }, sourceState, tick + 1);
|
|
996
|
+
if (spawn.x !== undefined)
|
|
997
|
+
spawned.x = spawned.previousX = spawn.x;
|
|
998
|
+
if (spawn.y !== undefined)
|
|
999
|
+
spawned.y = spawned.previousY = spawn.y;
|
|
1000
|
+
if (spawn.velocityX !== undefined)
|
|
1001
|
+
spawned.velocityX = spawn.velocityX;
|
|
1002
|
+
if (spawn.velocityY !== undefined)
|
|
1003
|
+
spawned.velocityY = spawn.velocityY;
|
|
1004
|
+
states.push({ ...spawned, sourceId: prefabId });
|
|
1005
|
+
}
|
|
1006
|
+
if (transitionTo) {
|
|
1007
|
+
const nextScene = document.scenes.find((candidate) => candidate.id === transitionTo);
|
|
1008
|
+
if (!nextScene) {
|
|
1009
|
+
throw new Error(`Missing scene ${transitionTo}`);
|
|
1010
|
+
}
|
|
1011
|
+
scene = nextScene;
|
|
1012
|
+
sceneId = nextScene.id;
|
|
1013
|
+
music = nextScene.music ? {
|
|
1014
|
+
voiceId: `scene:${sceneId}:music`, assetId: nextScene.music.assetId, startTick: tick + 1,
|
|
1015
|
+
volume: nextScene.music.volume, fadeInTicks: nextScene.music.fadeInTicks, fadeOutTicks: nextScene.music.fadeOutTicks
|
|
1016
|
+
} : null;
|
|
1017
|
+
states = initialSceneStates(nextScene, tick + 1);
|
|
1018
|
+
activeContacts = new Map();
|
|
1019
|
+
spawnSequence = 0;
|
|
1020
|
+
scriptState = {};
|
|
1021
|
+
hud = new Map();
|
|
1022
|
+
emit({ kind: "sceneTransition", sceneId });
|
|
1023
|
+
}
|
|
1024
|
+
previousEvents = structuredClone(events);
|
|
1025
|
+
rngState = (Math.imul(1664525, rngState) + 1013904223) >>> 0;
|
|
1026
|
+
tick += 1;
|
|
1027
|
+
const result = { tick, events, frame: frameFor(document, scene, states, tick, score, won, hud) };
|
|
1028
|
+
if (scriptStats) {
|
|
1029
|
+
return { ...result, scriptStats };
|
|
1030
|
+
}
|
|
1031
|
+
return result;
|
|
1032
|
+
}
|
|
1033
|
+
catch (error) {
|
|
1034
|
+
failed = true;
|
|
1035
|
+
throw error;
|
|
1036
|
+
}
|
|
1037
|
+
}
|
|
1038
|
+
return {
|
|
1039
|
+
step,
|
|
1040
|
+
frame() {
|
|
1041
|
+
if (disposed) {
|
|
1042
|
+
throw new Error("Game session is disposed");
|
|
1043
|
+
}
|
|
1044
|
+
if (failed) {
|
|
1045
|
+
throw new Error("Game session stopped after a failed step");
|
|
1046
|
+
}
|
|
1047
|
+
return frameFor(document, scene, states, tick, score, won, hud);
|
|
1048
|
+
},
|
|
1049
|
+
inspect(query) {
|
|
1050
|
+
const current = snapshot();
|
|
1051
|
+
return { tick, sceneId, score, won, entities: query?.entityId ? current.entities.filter((entity) => entity.id === query.entityId) : current.entities };
|
|
1052
|
+
},
|
|
1053
|
+
snapshot,
|
|
1054
|
+
dispose() {
|
|
1055
|
+
disposed = true;
|
|
1056
|
+
states = [];
|
|
1057
|
+
previousEvents = [];
|
|
1058
|
+
scriptRunner?.dispose();
|
|
1059
|
+
}
|
|
1060
|
+
};
|
|
1061
|
+
}
|
|
1062
|
+
export function createGameSession(document, seed, savedSnapshot, eventSink) {
|
|
1063
|
+
return createGameSessionWithRunner(document, seed, savedSnapshot, eventSink);
|
|
1064
|
+
}
|
|
1065
|
+
export async function createScriptedGameSession(document, seed, savedSnapshot, eventSink) {
|
|
1066
|
+
const validation = validateGame(document);
|
|
1067
|
+
if (!validation.valid || !validation.document)
|
|
1068
|
+
throw new Error(`Invalid game: ${validation.errors.join("; ")}`);
|
|
1069
|
+
if (!hasGameScripts(validation.document))
|
|
1070
|
+
return createGameSession(validation.document, seed, savedSnapshot, eventSink);
|
|
1071
|
+
const runner = await prepareGameScripts(validation.document);
|
|
1072
|
+
try {
|
|
1073
|
+
return createGameSessionWithRunner(validation.document, seed, savedSnapshot, eventSink, runner);
|
|
1074
|
+
}
|
|
1075
|
+
catch (error) {
|
|
1076
|
+
runner.dispose();
|
|
1077
|
+
throw error;
|
|
1078
|
+
}
|
|
1079
|
+
}
|
|
1080
|
+
export async function replayScriptedGame(document, seed, inputs, snapshot) {
|
|
1081
|
+
const session = await createScriptedGameSession(document, seed, snapshot);
|
|
1082
|
+
try {
|
|
1083
|
+
const steps = inputs.map((input) => session.step(input));
|
|
1084
|
+
return { snapshot: session.snapshot(), steps };
|
|
1085
|
+
}
|
|
1086
|
+
finally {
|
|
1087
|
+
session.dispose();
|
|
1088
|
+
}
|
|
1089
|
+
}
|
|
1090
|
+
export function replayGame(document, seed, inputs, snapshot) {
|
|
1091
|
+
const session = createGameSession(document, seed, snapshot);
|
|
1092
|
+
try {
|
|
1093
|
+
const steps = inputs.map((input) => session.step(input));
|
|
1094
|
+
return { snapshot: session.snapshot(), steps };
|
|
1095
|
+
}
|
|
1096
|
+
finally {
|
|
1097
|
+
session.dispose();
|
|
1098
|
+
}
|
|
1099
|
+
}
|
|
1100
|
+
//# sourceMappingURL=session.js.map
|