@nodetool-ai/game-runtime 0.8.1 → 0.8.2

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.
Files changed (238) hide show
  1. package/README.md +43 -0
  2. package/dist/.nodetool-build-stamp +1 -1
  3. package/dist/audio-mixer-references.d.ts +10 -0
  4. package/dist/audio-mixer-references.d.ts.map +1 -0
  5. package/dist/audio-mixer-references.js +21 -0
  6. package/dist/audio-mixer-references.js.map +1 -0
  7. package/dist/audio-source-ops.d.ts +24 -0
  8. package/dist/audio-source-ops.d.ts.map +1 -0
  9. package/dist/audio-source-ops.js +27 -0
  10. package/dist/audio-source-ops.js.map +1 -0
  11. package/dist/authoring-identity.d.ts +3 -0
  12. package/dist/authoring-identity.d.ts.map +1 -0
  13. package/dist/authoring-identity.js +12 -0
  14. package/dist/authoring-identity.js.map +1 -0
  15. package/dist/authoring-reconcile.d.ts +23 -0
  16. package/dist/authoring-reconcile.d.ts.map +1 -0
  17. package/dist/authoring-reconcile.js +375 -0
  18. package/dist/authoring-reconcile.js.map +1 -0
  19. package/dist/autoplay.d.ts.map +1 -1
  20. package/dist/autoplay.js +32 -5
  21. package/dist/autoplay.js.map +1 -1
  22. package/dist/document-ops.d.ts +2657 -368
  23. package/dist/document-ops.d.ts.map +1 -1
  24. package/dist/document-ops.js +135 -16
  25. package/dist/document-ops.js.map +1 -1
  26. package/dist/document-ops3d.d.ts +13390 -0
  27. package/dist/document-ops3d.d.ts.map +1 -0
  28. package/dist/document-ops3d.js +493 -0
  29. package/dist/document-ops3d.js.map +1 -0
  30. package/dist/gameplay/lifecycle.d.ts +91 -0
  31. package/dist/gameplay/lifecycle.d.ts.map +1 -0
  32. package/dist/gameplay/lifecycle.js +135 -0
  33. package/dist/gameplay/lifecycle.js.map +1 -0
  34. package/dist/index.d.ts +10 -0
  35. package/dist/index.d.ts.map +1 -1
  36. package/dist/index.js +10 -0
  37. package/dist/index.js.map +1 -1
  38. package/dist/open-session.d.ts +32 -0
  39. package/dist/open-session.d.ts.map +1 -0
  40. package/dist/open-session.js +51 -0
  41. package/dist/open-session.js.map +1 -0
  42. package/dist/ownership-ops.d.ts +45 -0
  43. package/dist/ownership-ops.d.ts.map +1 -0
  44. package/dist/ownership-ops.js +173 -0
  45. package/dist/ownership-ops.js.map +1 -0
  46. package/dist/prepared-collider3d.d.ts +11 -0
  47. package/dist/prepared-collider3d.d.ts.map +1 -0
  48. package/dist/prepared-collider3d.js +41 -0
  49. package/dist/prepared-collider3d.js.map +1 -0
  50. package/dist/sample3d.d.ts +4 -0
  51. package/dist/sample3d.d.ts.map +1 -0
  52. package/dist/sample3d.js +62 -0
  53. package/dist/sample3d.js.map +1 -0
  54. package/dist/script-clock.d.ts +19 -0
  55. package/dist/script-clock.d.ts.map +1 -0
  56. package/dist/script-clock.js +32 -0
  57. package/dist/script-clock.js.map +1 -0
  58. package/dist/script-declarations.d.ts +7 -0
  59. package/dist/script-declarations.d.ts.map +1 -0
  60. package/dist/script-declarations.js +99 -0
  61. package/dist/script-declarations.js.map +1 -0
  62. package/dist/script-lifecycle.d.ts +108 -0
  63. package/dist/script-lifecycle.d.ts.map +1 -0
  64. package/dist/script-lifecycle.js +253 -0
  65. package/dist/script-lifecycle.js.map +1 -0
  66. package/dist/script-params.d.ts +25 -0
  67. package/dist/script-params.d.ts.map +1 -0
  68. package/dist/script-params.js +63 -0
  69. package/dist/script-params.js.map +1 -0
  70. package/dist/script-persistence.d.ts +3 -0
  71. package/dist/script-persistence.d.ts.map +1 -0
  72. package/dist/script-persistence.js +67 -0
  73. package/dist/script-persistence.js.map +1 -0
  74. package/dist/script-props.d.ts +21 -0
  75. package/dist/script-props.d.ts.map +1 -0
  76. package/dist/script-props.js +42 -0
  77. package/dist/script-props.js.map +1 -0
  78. package/dist/script-transport.d.ts +5 -0
  79. package/dist/script-transport.d.ts.map +1 -0
  80. package/dist/script-transport.js +64 -0
  81. package/dist/script-transport.js.map +1 -0
  82. package/dist/script-types.d.ts +5 -1
  83. package/dist/script-types.d.ts.map +1 -1
  84. package/dist/script-types.js +13 -11
  85. package/dist/script-types.js.map +1 -1
  86. package/dist/script-types3d.d.ts +6 -0
  87. package/dist/script-types3d.d.ts.map +1 -0
  88. package/dist/script-types3d.js +28 -0
  89. package/dist/script-types3d.js.map +1 -0
  90. package/dist/script-world.d.ts +41 -0
  91. package/dist/script-world.d.ts.map +1 -0
  92. package/dist/script-world.js +169 -0
  93. package/dist/script-world.js.map +1 -0
  94. package/dist/scripts.d.ts +107 -4
  95. package/dist/scripts.d.ts.map +1 -1
  96. package/dist/scripts.js +513 -111
  97. package/dist/scripts.js.map +1 -1
  98. package/dist/scripts3d.d.ts +34 -0
  99. package/dist/scripts3d.d.ts.map +1 -0
  100. package/dist/scripts3d.js +14 -0
  101. package/dist/scripts3d.js.map +1 -0
  102. package/dist/session.d.ts +8 -3
  103. package/dist/session.d.ts.map +1 -1
  104. package/dist/session.js +249 -795
  105. package/dist/session.js.map +1 -1
  106. package/dist/session3d.d.ts +30 -0
  107. package/dist/session3d.d.ts.map +1 -0
  108. package/dist/session3d.js +603 -0
  109. package/dist/session3d.js.map +1 -0
  110. package/dist/spatial3d/camera.d.ts +7 -0
  111. package/dist/spatial3d/camera.d.ts.map +1 -0
  112. package/dist/spatial3d/camera.js +43 -0
  113. package/dist/spatial3d/camera.js.map +1 -0
  114. package/dist/spatial3d/digest.d.ts +4 -0
  115. package/dist/spatial3d/digest.d.ts.map +1 -0
  116. package/dist/spatial3d/digest.js +30 -0
  117. package/dist/spatial3d/digest.js.map +1 -0
  118. package/dist/spatial3d/layers.d.ts +30 -0
  119. package/dist/spatial3d/layers.d.ts.map +1 -0
  120. package/dist/spatial3d/layers.js +93 -0
  121. package/dist/spatial3d/layers.js.map +1 -0
  122. package/dist/spatial3d/math.d.ts +23 -0
  123. package/dist/spatial3d/math.d.ts.map +1 -0
  124. package/dist/spatial3d/math.js +39 -0
  125. package/dist/spatial3d/math.js.map +1 -0
  126. package/dist/spatial3d/state.d.ts +37 -0
  127. package/dist/spatial3d/state.d.ts.map +1 -0
  128. package/dist/spatial3d/state.js +4 -0
  129. package/dist/spatial3d/state.js.map +1 -0
  130. package/dist/spatial3d/world.d.ts +68 -0
  131. package/dist/spatial3d/world.d.ts.map +1 -0
  132. package/dist/spatial3d/world.js +446 -0
  133. package/dist/spatial3d/world.js.map +1 -0
  134. package/dist/systems/animation-graph3d.d.ts +24 -0
  135. package/dist/systems/animation-graph3d.d.ts.map +1 -0
  136. package/dist/systems/animation-graph3d.js +262 -0
  137. package/dist/systems/animation-graph3d.js.map +1 -0
  138. package/dist/systems/animation3d.d.ts +3 -0
  139. package/dist/systems/animation3d.d.ts.map +1 -0
  140. package/dist/systems/animation3d.js +14 -0
  141. package/dist/systems/animation3d.js.map +1 -0
  142. package/dist/systems/character3d.d.ts +3 -0
  143. package/dist/systems/character3d.d.ts.map +1 -0
  144. package/dist/systems/character3d.js +6 -0
  145. package/dist/systems/character3d.js.map +1 -0
  146. package/dist/systems/collision2d.d.ts +27 -0
  147. package/dist/systems/collision2d.d.ts.map +1 -0
  148. package/dist/systems/collision2d.js +154 -0
  149. package/dist/systems/collision2d.js.map +1 -0
  150. package/dist/systems/contacts2d.d.ts +3 -0
  151. package/dist/systems/contacts2d.d.ts.map +1 -0
  152. package/dist/systems/contacts2d.js +36 -0
  153. package/dist/systems/contacts2d.js.map +1 -0
  154. package/dist/systems/contacts3d.d.ts +3 -0
  155. package/dist/systems/contacts3d.d.ts.map +1 -0
  156. package/dist/systems/contacts3d.js +55 -0
  157. package/dist/systems/contacts3d.js.map +1 -0
  158. package/dist/systems/context2d.d.ts +41 -0
  159. package/dist/systems/context2d.d.ts.map +1 -0
  160. package/dist/systems/context2d.js +2 -0
  161. package/dist/systems/context2d.js.map +1 -0
  162. package/dist/systems/context3d.d.ts +67 -0
  163. package/dist/systems/context3d.d.ts.map +1 -0
  164. package/dist/systems/context3d.js +2 -0
  165. package/dist/systems/context3d.js.map +1 -0
  166. package/dist/systems/gameplay2d.d.ts +3 -0
  167. package/dist/systems/gameplay2d.d.ts.map +1 -0
  168. package/dist/systems/gameplay2d.js +88 -0
  169. package/dist/systems/gameplay2d.js.map +1 -0
  170. package/dist/systems/gameplay3d.d.ts +4 -0
  171. package/dist/systems/gameplay3d.d.ts.map +1 -0
  172. package/dist/systems/gameplay3d.js +170 -0
  173. package/dist/systems/gameplay3d.js.map +1 -0
  174. package/dist/systems/hierarchy3d.d.ts +3 -0
  175. package/dist/systems/hierarchy3d.d.ts.map +1 -0
  176. package/dist/systems/hierarchy3d.js +27 -0
  177. package/dist/systems/hierarchy3d.js.map +1 -0
  178. package/dist/systems/input2d.d.ts +3 -0
  179. package/dist/systems/input2d.d.ts.map +1 -0
  180. package/dist/systems/input2d.js +6 -0
  181. package/dist/systems/input2d.js.map +1 -0
  182. package/dist/systems/input3d.d.ts +3 -0
  183. package/dist/systems/input3d.d.ts.map +1 -0
  184. package/dist/systems/input3d.js +16 -0
  185. package/dist/systems/input3d.js.map +1 -0
  186. package/dist/systems/physics2d.d.ts +3 -0
  187. package/dist/systems/physics2d.d.ts.map +1 -0
  188. package/dist/systems/physics2d.js +244 -0
  189. package/dist/systems/physics2d.js.map +1 -0
  190. package/dist/systems/physics3d.d.ts +3 -0
  191. package/dist/systems/physics3d.d.ts.map +1 -0
  192. package/dist/systems/physics3d.js +4 -0
  193. package/dist/systems/physics3d.js.map +1 -0
  194. package/dist/systems/pipeline.d.ts +23 -0
  195. package/dist/systems/pipeline.d.ts.map +1 -0
  196. package/dist/systems/pipeline.js +65 -0
  197. package/dist/systems/pipeline.js.map +1 -0
  198. package/dist/systems/presentation2d.d.ts +9 -0
  199. package/dist/systems/presentation2d.d.ts.map +1 -0
  200. package/dist/systems/presentation2d.js +240 -0
  201. package/dist/systems/presentation2d.js.map +1 -0
  202. package/dist/systems/presentation3d.d.ts +9 -0
  203. package/dist/systems/presentation3d.d.ts.map +1 -0
  204. package/dist/systems/presentation3d.js +115 -0
  205. package/dist/systems/presentation3d.js.map +1 -0
  206. package/dist/systems/scripts2d.d.ts +7 -0
  207. package/dist/systems/scripts2d.d.ts.map +1 -0
  208. package/dist/systems/scripts2d.js +274 -0
  209. package/dist/systems/scripts2d.js.map +1 -0
  210. package/dist/systems/scripts3d.d.ts +7 -0
  211. package/dist/systems/scripts3d.d.ts.map +1 -0
  212. package/dist/systems/scripts3d.js +262 -0
  213. package/dist/systems/scripts3d.js.map +1 -0
  214. package/dist/systems/state2d.d.ts +65 -0
  215. package/dist/systems/state2d.d.ts.map +1 -0
  216. package/dist/systems/state2d.js +2 -0
  217. package/dist/systems/state2d.js.map +1 -0
  218. package/dist/systems/tick2d.d.ts +7 -0
  219. package/dist/systems/tick2d.d.ts.map +1 -0
  220. package/dist/systems/tick2d.js +15 -0
  221. package/dist/systems/tick2d.js.map +1 -0
  222. package/dist/systems/tick3d.d.ts +7 -0
  223. package/dist/systems/tick3d.d.ts.map +1 -0
  224. package/dist/systems/tick3d.js +17 -0
  225. package/dist/systems/tick3d.js.map +1 -0
  226. package/dist/validate-animation-graph3d.d.ts +8 -0
  227. package/dist/validate-animation-graph3d.d.ts.map +1 -0
  228. package/dist/validate-animation-graph3d.js +115 -0
  229. package/dist/validate-animation-graph3d.js.map +1 -0
  230. package/dist/validate.d.ts +5 -0
  231. package/dist/validate.d.ts.map +1 -1
  232. package/dist/validate.js +61 -2
  233. package/dist/validate.js.map +1 -1
  234. package/dist/validate3d.d.ts +20 -0
  235. package/dist/validate3d.d.ts.map +1 -0
  236. package/dist/validate3d.js +325 -0
  237. package/dist/validate3d.js.map +1 -0
  238. package/package.json +10 -3
package/dist/session.js CHANGED
@@ -1,74 +1,20 @@
1
+ import { frameFor } from "./systems/presentation2d.js";
2
+ import { contactKey } from "./systems/collision2d.js";
3
+ import { stepScripts2D } from "./systems/scripts2d.js";
4
+ import { stepContacts2D } from "./systems/contacts2d.js";
5
+ import { stepGameplay2D } from "./systems/gameplay2d.js";
6
+ import { stepPresentation2D, readStepResult2D } from "./systems/presentation2d.js";
1
7
  import { gameSnapshot } from "@nodetool-ai/protocol";
8
+ import { initialGameplayState, runGameplayTick } from "./gameplay/lifecycle.js";
2
9
  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;
10
+ import { hasGameScripts, prepareGameScripts } from "./scripts.js";
11
+ import { statefulGameSystem } from "./systems/pipeline.js";
12
+ import { create2DSystemPipeline } from "./systems/tick2d.js";
66
13
  function initialState(entity, world, spawnTick = 0) {
67
- const health = entity.behaviors.find((behavior) => behavior.kind === "health");
68
14
  const patrol = entity.behaviors.find((behavior) => behavior.kind === "patrol");
69
15
  const state = {
70
16
  definition: entity,
71
- spawnTick,
17
+ ...initialGameplayState(entity, spawnTick),
72
18
  x: world.x,
73
19
  y: world.y,
74
20
  previousX: world.x,
@@ -77,11 +23,10 @@ function initialState(entity, world, spawnTick = 0) {
77
23
  scaleX: world.scaleX,
78
24
  scaleY: world.scaleY,
79
25
  velocityX: entity.body2d?.velocity.x ?? 0,
80
- velocityY: entity.body2d?.velocity.y ?? 0,
81
- active: !entity.templateOnly
26
+ velocityY: entity.body2d?.velocity.y ?? 0
82
27
  };
83
- if (health?.kind === "health") {
84
- state.health = health.maximum;
28
+ if (entity.props !== undefined) {
29
+ state.props = structuredClone(entity.props);
85
30
  }
86
31
  if (patrol?.kind === "patrol") {
87
32
  state.patrolOrigin = patrol.axis === "x" ? state.x : state.y;
@@ -138,185 +83,8 @@ function initialSceneStates(scene, spawnTick = 0) {
138
83
  return initialState(entity, world, spawnTick);
139
84
  });
140
85
  }
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
86
  /** One session owns mutable simulation state. All boundaries remain plain data. */
319
- function createGameSessionWithRunner(value, seed, savedSnapshot, eventSink, scriptRunner) {
87
+ function createGameSessionWithRunner(value, seed, savedSnapshot, eventSink, scriptRunner, options = {}) {
320
88
  const validation = validateGame(value);
321
89
  if (!validation.valid || !validation.document) {
322
90
  throw new Error(`Invalid game: ${validation.errors.join("; ")}`);
@@ -334,10 +102,16 @@ function createGameSessionWithRunner(value, seed, savedSnapshot, eventSink, scri
334
102
  throw new Error(`Missing entry scene ${sceneId}`);
335
103
  }
336
104
  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;
105
+ let music = scene.music
106
+ ? {
107
+ voiceId: `scene:${scene.id}:music`,
108
+ assetId: scene.music.assetId,
109
+ startTick: 0,
110
+ volume: scene.music.volume,
111
+ fadeInTicks: scene.music.fadeInTicks,
112
+ fadeOutTicks: scene.music.fadeOutTicks
113
+ }
114
+ : null;
341
115
  let states = initialSceneStates(scene);
342
116
  let tick = 0;
343
117
  let score = 0;
@@ -348,10 +122,10 @@ function createGameSessionWithRunner(value, seed, savedSnapshot, eventSink, scri
348
122
  let activeContacts = new Map();
349
123
  let scriptState = {};
350
124
  let hud = new Map();
125
+ let ui = new Map();
351
126
  let disposed = false;
352
127
  let failed = false;
353
- if (savedSnapshot) {
354
- const parsed = gameSnapshot.parse(savedSnapshot);
128
+ function restoreSavedSnapshot(parsed) {
355
129
  if (parsed.gameRevision !== document.revision || parsed.engineVersion !== document.engineVersion) {
356
130
  throw new Error("Save revision or engine version does not match the game");
357
131
  }
@@ -361,11 +135,23 @@ function createGameSessionWithRunner(value, seed, savedSnapshot, eventSink, scri
361
135
  }
362
136
  scene = savedScene;
363
137
  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)) {
138
+ music =
139
+ parsed.music ??
140
+ (savedScene.music
141
+ ? {
142
+ voiceId: `scene:${savedScene.id}:music`,
143
+ assetId: savedScene.music.assetId,
144
+ startTick: parsed.tick,
145
+ volume: savedScene.music.volume,
146
+ fadeInTicks: savedScene.music.fadeInTicks,
147
+ fadeOutTicks: savedScene.music.fadeOutTicks
148
+ }
149
+ : null);
150
+ if (music &&
151
+ (!savedScene.music ||
152
+ music.assetId !== savedScene.music.assetId ||
153
+ music.voiceId !== `scene:${savedScene.id}:music` ||
154
+ music.startTick > parsed.tick)) {
369
155
  throw new Error("Save music does not match the scene");
370
156
  }
371
157
  states = initialSceneStates(savedScene, parsed.tick);
@@ -403,6 +189,12 @@ function createGameSessionWithRunner(value, seed, savedSnapshot, eventSink, scri
403
189
  state.velocityY = saved.velocityY;
404
190
  state.spawnTick = saved.spawnTick ?? 0;
405
191
  state.active = saved.active;
192
+ if (saved.props !== undefined) {
193
+ if (document.schemaVersion !== 4) {
194
+ throw new Error(`Save entity ${saved.id} props require schema version 4`);
195
+ }
196
+ state.props = structuredClone(saved.props);
197
+ }
406
198
  state.health = saved.health;
407
199
  state.patrolOrigin = saved.patrolOrigin;
408
200
  state.patrolDirection = saved.patrolDirection;
@@ -432,6 +224,7 @@ function createGameSessionWithRunner(value, seed, savedSnapshot, eventSink, scri
432
224
  activeContacts = new Map(parsed.activeContacts.map((pair) => [contactKey(pair.entityId, pair.otherId), { ...pair, normalX: 0, normalY: 0 }]));
433
225
  scriptState = structuredClone(parsed.scriptState);
434
226
  hud = new Map(parsed.hud.map((label) => [label.id, { ...label }]));
227
+ ui = new Map(Object.entries(structuredClone(parsed.ui ?? {})));
435
228
  }
436
229
  function snapshot() {
437
230
  if (disposed) {
@@ -440,9 +233,9 @@ function createGameSessionWithRunner(value, seed, savedSnapshot, eventSink, scri
440
233
  if (failed) {
441
234
  throw new Error("Game session stopped after a failed step");
442
235
  }
443
- return {
236
+ const saved = {
444
237
  gameRevision: document.revision,
445
- engineVersion: "1",
238
+ engineVersion: document.engineVersion,
446
239
  sceneId,
447
240
  tick,
448
241
  rngState,
@@ -469,6 +262,9 @@ function createGameSessionWithRunner(value, seed, savedSnapshot, eventSink, scri
469
262
  if (state.sourceId) {
470
263
  entity.sourceId = state.sourceId;
471
264
  }
265
+ if (state.props !== undefined) {
266
+ entity.props = structuredClone(state.props);
267
+ }
472
268
  if (state.visual)
473
269
  Object.assign(entity, state.visual);
474
270
  if (state.health !== undefined)
@@ -484,74 +280,169 @@ function createGameSessionWithRunner(value, seed, savedSnapshot, eventSink, scri
484
280
  return entity;
485
281
  })
486
282
  };
283
+ // Left out until a script changes the HUD tree, so snapshots of games without one keep their bytes.
284
+ if (ui.size > 0) {
285
+ saved.ui = structuredClone(Object.fromEntries(ui));
286
+ }
287
+ return saved;
487
288
  }
488
289
  function isSpawnedId(entityId) {
489
290
  const separator = entityId.lastIndexOf("#");
490
291
  const prefabId = entityId.slice(0, separator);
491
292
  return separator > 0 && scene.entities.some((entity) => entity.templateOnly && entity.id === prefabId);
492
293
  }
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
- }
294
+ let presentationEvents = [];
295
+ const scripts = statefulGameSystem("scripts", stepScripts2D, () => ({ scriptState: structuredClone(scriptState), rngState, pendingEvents: structuredClone(previousEvents) }), (saved) => {
296
+ if (!saved?.scriptState || saved.rngState === undefined || !saved.pendingEvents) {
297
+ throw new Error("Missing script system state");
510
298
  }
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;
299
+ scriptState = structuredClone(saved.scriptState);
300
+ rngState = saved.rngState;
301
+ previousEvents = structuredClone(saved.pendingEvents);
302
+ });
303
+ const contacts = statefulGameSystem("contacts", stepContacts2D, () => ({ activeContacts: [...activeContacts.values()].map(({ entityId, otherId, sensor }) => ({ entityId, otherId, sensor })) }), (saved) => {
304
+ if (!saved?.activeContacts) {
305
+ throw new Error("Missing contact system state");
535
306
  }
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);
307
+ activeContacts = new Map(saved.activeContacts.map((pair) => [contactKey(pair.entityId, pair.otherId), { ...pair, normalX: 0, normalY: 0 }]));
308
+ });
309
+ const gameplay = statefulGameSystem("gameplay", stepGameplay2D, () => ({ gameplaySnapshot: snapshot() }), (saved) => {
310
+ if (!saved?.gameplaySnapshot) {
311
+ throw new Error("Missing gameplay system state");
312
+ }
313
+ restoreSavedSnapshot(saved.gameplaySnapshot);
314
+ });
315
+ const presentation = statefulGameSystem("presentation", stepPresentation2D, () => null, () => {
316
+ presentationEvents = [];
317
+ });
318
+ const pipeline = create2DSystemPipeline({ scripts, contacts, gameplay, presentation });
319
+ pipeline.init(document, scene);
320
+ if (savedSnapshot) {
321
+ const normalized = gameSnapshot.parse(savedSnapshot);
322
+ pipeline.restore({
323
+ input: null,
324
+ scripts: normalized,
325
+ physics: null,
326
+ contacts: normalized,
327
+ gameplay: { gameplaySnapshot: normalized },
328
+ presentation: null
329
+ });
554
330
  }
331
+ const systemContext = {
332
+ input: { pressed: [], justPressed: [] },
333
+ pressed: new Set(),
334
+ scriptCalls: [],
335
+ queues: { despawns: new Set(), spawns: [] },
336
+ scriptStats: undefined,
337
+ observations: new Map(),
338
+ queuedDespawns: new Set(),
339
+ queuedSpawns: [],
340
+ result: undefined,
341
+ events: [],
342
+ emit: () => { },
343
+ get states() {
344
+ return states;
345
+ },
346
+ set states(value) {
347
+ states = value;
348
+ },
349
+ get scene() {
350
+ return scene;
351
+ },
352
+ set scene(value) {
353
+ scene = value;
354
+ },
355
+ get scriptState() {
356
+ return scriptState;
357
+ },
358
+ set scriptState(value) {
359
+ scriptState = value;
360
+ },
361
+ get tick() {
362
+ return tick;
363
+ },
364
+ set tick(value) {
365
+ tick = value;
366
+ },
367
+ get previousEvents() {
368
+ return previousEvents;
369
+ },
370
+ set previousEvents(value) {
371
+ previousEvents = value;
372
+ },
373
+ scriptRunner,
374
+ get rngState() {
375
+ return rngState;
376
+ },
377
+ set rngState(value) {
378
+ rngState = value;
379
+ },
380
+ document,
381
+ isSpawnedId,
382
+ get hud() {
383
+ return hud;
384
+ },
385
+ set hud(value) {
386
+ hud = value;
387
+ },
388
+ get ui() {
389
+ return ui;
390
+ },
391
+ set ui(value) {
392
+ ui = value;
393
+ },
394
+ get activeContacts() {
395
+ return activeContacts;
396
+ },
397
+ set activeContacts(value) {
398
+ activeContacts = value;
399
+ },
400
+ get score() {
401
+ return score;
402
+ },
403
+ set score(value) {
404
+ score = value;
405
+ },
406
+ get won() {
407
+ return won;
408
+ },
409
+ set won(value) {
410
+ won = value;
411
+ },
412
+ get sceneId() {
413
+ return sceneId;
414
+ },
415
+ set sceneId(value) {
416
+ sceneId = value;
417
+ },
418
+ get failed() {
419
+ return failed;
420
+ },
421
+ set failed(value) {
422
+ failed = value;
423
+ },
424
+ get spawnSequence() {
425
+ return spawnSequence;
426
+ },
427
+ set spawnSequence(value) {
428
+ spawnSequence = value;
429
+ },
430
+ initialState,
431
+ get music() {
432
+ return music;
433
+ },
434
+ set music(value) {
435
+ music = value;
436
+ },
437
+ initialSceneStates,
438
+ get presentationEvents() {
439
+ return presentationEvents;
440
+ },
441
+ set presentationEvents(value) {
442
+ presentationEvents = value;
443
+ },
444
+ frameFor
445
+ };
555
446
  function step(input) {
556
447
  if (disposed) {
557
448
  throw new Error("Game session is disposed");
@@ -559,483 +450,40 @@ function createGameSessionWithRunner(value, seed, savedSnapshot, eventSink, scri
559
450
  if (failed) {
560
451
  throw new Error("Game session stopped after a failed step");
561
452
  }
562
- const pressed = new Set(input.pressed);
563
- for (const action of pressed) {
453
+ const pressed = new Set();
454
+ for (const action of input.pressed) {
564
455
  if (!document.inputActions.includes(action)) {
565
456
  throw new Error(`Unknown input action ${action}`);
566
457
  }
567
458
  }
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
- }
459
+ return runGameplayTick(({ events, emit }) => {
460
+ systemContext.input = input;
461
+ systemContext.pressed = pressed;
462
+ systemContext.queuedDespawns = new Set();
463
+ systemContext.queuedSpawns = [];
464
+ systemContext.queues = { despawns: systemContext.queuedDespawns, spawns: systemContext.queuedSpawns };
465
+ systemContext.scriptCalls = [];
466
+ systemContext.scriptStats = undefined;
467
+ systemContext.result = undefined;
468
+ systemContext.events = events;
469
+ systemContext.emit = emit;
470
+ const timings = options.recordTimings ? pipeline.stepTimed(systemContext) : undefined;
471
+ if (!options.recordTimings) {
472
+ pipeline.step(systemContext);
628
473
  }
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) {
474
+ const result = readStepResult2D(systemContext);
475
+ return timings ? { ...result, timings } : result;
476
+ }, () => {
1034
477
  failed = true;
1035
- throw error;
1036
- }
478
+ scriptRunner?.retain?.(new Set());
479
+ }, eventSink);
1037
480
  }
1038
481
  return {
482
+ takePresentationEvents() {
483
+ const pending = presentationEvents;
484
+ presentationEvents = [];
485
+ return pending;
486
+ },
1039
487
  step,
1040
488
  frame() {
1041
489
  if (disposed) {
@@ -1044,11 +492,17 @@ function createGameSessionWithRunner(value, seed, savedSnapshot, eventSink, scri
1044
492
  if (failed) {
1045
493
  throw new Error("Game session stopped after a failed step");
1046
494
  }
1047
- return frameFor(document, scene, states, tick, score, won, hud);
495
+ return frameFor(document, scene, states, tick, score, won, hud, ui);
1048
496
  },
1049
497
  inspect(query) {
1050
498
  const current = snapshot();
1051
- return { tick, sceneId, score, won, entities: query?.entityId ? current.entities.filter((entity) => entity.id === query.entityId) : current.entities };
499
+ return {
500
+ tick,
501
+ sceneId,
502
+ score,
503
+ won,
504
+ entities: query?.entityId ? current.entities.filter((entity) => entity.id === query.entityId) : current.entities
505
+ };
1052
506
  },
1053
507
  snapshot,
1054
508
  dispose() {
@@ -1059,18 +513,18 @@ function createGameSessionWithRunner(value, seed, savedSnapshot, eventSink, scri
1059
513
  }
1060
514
  };
1061
515
  }
1062
- export function createGameSession(document, seed, savedSnapshot, eventSink) {
1063
- return createGameSessionWithRunner(document, seed, savedSnapshot, eventSink);
516
+ export function createGameSession(document, seed, savedSnapshot, eventSink, options = {}) {
517
+ return createGameSessionWithRunner(document, seed, savedSnapshot, eventSink, undefined, options);
1064
518
  }
1065
- export async function createScriptedGameSession(document, seed, savedSnapshot, eventSink) {
519
+ export async function createScriptedGameSession(document, seed, savedSnapshot, eventSink, options = {}) {
1066
520
  const validation = validateGame(document);
1067
521
  if (!validation.valid || !validation.document)
1068
522
  throw new Error(`Invalid game: ${validation.errors.join("; ")}`);
1069
523
  if (!hasGameScripts(validation.document))
1070
- return createGameSession(validation.document, seed, savedSnapshot, eventSink);
524
+ return createGameSession(validation.document, seed, savedSnapshot, eventSink, options);
1071
525
  const runner = await prepareGameScripts(validation.document);
1072
526
  try {
1073
- return createGameSessionWithRunner(validation.document, seed, savedSnapshot, eventSink, runner);
527
+ return createGameSessionWithRunner(validation.document, seed, savedSnapshot, eventSink, runner, options);
1074
528
  }
1075
529
  catch (error) {
1076
530
  runner.dispose();