castle-web-cli 0.4.232 → 0.4.234

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 (587) hide show
  1. package/dist/agent-failures.d.ts +8 -0
  2. package/dist/agent-failures.js +19 -2
  3. package/dist/agent-prompts.d.ts +1 -1
  4. package/dist/agent-prompts.js +10 -3
  5. package/dist/agent.d.ts +64 -3
  6. package/dist/agent.js +170 -81
  7. package/dist/api.d.ts +11 -0
  8. package/dist/api.js +43 -0
  9. package/dist/bundle.d.ts +64 -0
  10. package/dist/bundle.js +558 -2
  11. package/dist/castle-host/host.d.ts +18 -2
  12. package/dist/castle-host/host.js +844 -39
  13. package/dist/castleJson.d.ts +23 -2
  14. package/dist/castleJson.js +46 -2
  15. package/dist/check.d.ts +3 -1
  16. package/dist/check.js +20 -3
  17. package/dist/chunkLoader.d.ts +3 -0
  18. package/dist/chunkLoader.js +111 -0
  19. package/dist/devParty.d.ts +26 -0
  20. package/dist/devParty.js +231 -0
  21. package/dist/devSaveStorage.js +4 -0
  22. package/dist/devSessionStorage.js +50 -2
  23. package/dist/devSocial.d.ts +24 -0
  24. package/dist/devSocial.js +70 -0
  25. package/dist/ide.d.ts +2 -0
  26. package/dist/ide.js +119 -15
  27. package/dist/importPinMismatch.d.ts +22 -0
  28. package/dist/importPinMismatch.js +77 -0
  29. package/dist/importRegression.js +3 -15
  30. package/dist/imports.d.ts +10 -3
  31. package/dist/imports.js +88 -20
  32. package/dist/index.js +11 -4
  33. package/dist/init.js +1 -1
  34. package/dist/platformDoc.js +22 -0
  35. package/dist/routerFences.d.ts +5 -0
  36. package/dist/routerFences.js +12 -2
  37. package/dist/save-deck.d.ts +25 -1
  38. package/dist/save-deck.js +178 -9
  39. package/dist/serve.js +32 -11
  40. package/dist/shell/assets/{index-D2tWM896.js → index-DulbYIJm.js} +97 -97
  41. package/dist/shell/assets/index-MVLfNYd9.css +1 -0
  42. package/dist/shell/index.html +2 -2
  43. package/dist/taskSteer.d.ts +13 -0
  44. package/dist/taskSteer.js +22 -2
  45. package/dist/vitePlugins.d.ts +2 -1
  46. package/dist/vitePlugins.js +13 -0
  47. package/kits/base/castle.json +1 -1
  48. package/kits/base/package-lock.json +1 -1
  49. package/kits/base/sdk/README.md +339 -5
  50. package/kits/base/sdk/avatar.d.ts +6 -2
  51. package/kits/base/sdk/avatar.js +12 -4
  52. package/kits/base/sdk/castle.d.ts +7 -3
  53. package/kits/base/sdk/castle.js +2 -0
  54. package/kits/base/sdk/commands.d.ts +176 -1
  55. package/kits/base/sdk/commands.js +3 -0
  56. package/kits/base/sdk/display.d.ts +3 -0
  57. package/kits/base/sdk/display.js +9 -3
  58. package/kits/base/sdk/hub.d.ts +37 -6
  59. package/kits/base/sdk/hub.js +63 -4
  60. package/kits/base/sdk/multiplayer.d.ts +7 -1
  61. package/kits/base/sdk/multiplayer.js +148 -32
  62. package/kits/base/sdk/multiplayerProtocol.d.ts +2 -0
  63. package/kits/base/sdk/party.d.ts +23 -0
  64. package/kits/base/sdk/party.js +91 -0
  65. package/kits/base/sdk/reconnectBudget.d.ts +23 -0
  66. package/kits/base/sdk/reconnectBudget.js +96 -0
  67. package/kits/base/sdk/save.d.ts +38 -1
  68. package/kits/base/sdk/save.js +81 -7
  69. package/kits/base/sdk/server/hub.d.ts +117 -0
  70. package/kits/base/sdk/server/hub.js +119 -2
  71. package/kits/base/sdk/server/platformHandle.d.ts +43 -1
  72. package/kits/base/sdk/server/storage.d.ts +17 -0
  73. package/kits/base/sdk/server/storage.js +65 -3
  74. package/kits/base/sdk/server/wrapper.d.ts +43 -6
  75. package/kits/base/sdk/server/wrapper.js +93 -9
  76. package/kits/base/sdk/social.d.ts +9 -0
  77. package/kits/base/sdk/social.js +5 -0
  78. package/kits/hub-game/CLAUDE.md +451 -13
  79. package/kits/hub-game/README.md +63 -0
  80. package/kits/hub-game/blueprints/avatar-10.scene +28 -0
  81. package/kits/hub-game/blueprints/avatar-11.scene +28 -0
  82. package/kits/hub-game/blueprints/avatar-12.scene +28 -0
  83. package/kits/hub-game/blueprints/avatar-13.scene +28 -0
  84. package/kits/hub-game/blueprints/avatar-14.scene +28 -0
  85. package/kits/hub-game/blueprints/avatar-15.scene +28 -0
  86. package/kits/hub-game/blueprints/avatar-4.scene +28 -0
  87. package/kits/hub-game/blueprints/avatar-5.scene +28 -0
  88. package/kits/hub-game/blueprints/avatar-6.scene +28 -0
  89. package/kits/hub-game/blueprints/avatar-7.scene +28 -0
  90. package/kits/hub-game/blueprints/avatar-8.scene +28 -0
  91. package/kits/hub-game/blueprints/avatar-9.scene +28 -0
  92. package/kits/hub-game/castle.json +5 -5
  93. package/kits/hub-game/code/client/act.js +312 -0
  94. package/kits/hub-game/code/client/actionLayout.js +147 -0
  95. package/kits/hub-game/code/client/actionOverflow.js +556 -0
  96. package/kits/hub-game/code/client/actorBudget.js +47 -0
  97. package/kits/hub-game/code/client/arrivalCamera.js +50 -0
  98. package/kits/hub-game/code/client/askSlot.js +117 -0
  99. package/kits/hub-game/code/client/attention.js +11 -2
  100. package/kits/hub-game/code/client/avatar.js +311 -35
  101. package/kits/hub-game/code/client/avatarCap.js +228 -0
  102. package/kits/hub-game/code/client/avatarColors.js +70 -0
  103. package/kits/hub-game/code/client/avatarFaces.js +21 -0
  104. package/kits/hub-game/code/client/avatarShare.js +253 -0
  105. package/kits/hub-game/code/client/backVisibility.js +13 -0
  106. package/kits/hub-game/code/client/ballot.js +472 -0
  107. package/kits/hub-game/code/client/build.js +38 -0
  108. package/kits/hub-game/code/client/chat.js +41 -5
  109. package/kits/hub-game/code/client/chatModeration.js +5 -0
  110. package/kits/hub-game/code/client/chrome.js +2144 -160
  111. package/kits/hub-game/code/client/companion.js +716 -0
  112. package/kits/hub-game/code/client/companionDress.js +99 -0
  113. package/kits/hub-game/code/client/crowdNames.js +241 -0
  114. package/kits/hub-game/code/client/decor.js +515 -0
  115. package/kits/hub-game/code/client/defaultEnvironment.js +194 -0
  116. package/kits/hub-game/code/client/doorErrors.js +39 -0
  117. package/kits/hub-game/code/client/earned.js +131 -0
  118. package/kits/hub-game/code/client/emoteBubble.js +75 -0
  119. package/kits/hub-game/code/client/fall.js +18 -0
  120. package/kits/hub-game/code/client/farAvatars.js +233 -0
  121. package/kits/hub-game/code/client/firstJoin.js +9 -2
  122. package/kits/hub-game/code/client/fpsTelemetry.js +50 -0
  123. package/kits/hub-game/code/client/frameBatch.js +5 -0
  124. package/kits/hub-game/code/client/grab.js +368 -29
  125. package/kits/hub-game/code/client/hookLayer.js +385 -20
  126. package/kits/hub-game/code/client/hudCopy.js +51 -0
  127. package/kits/hub-game/code/client/hudRate.js +20 -0
  128. package/kits/hub-game/code/client/idle.js +177 -24
  129. package/kits/hub-game/code/client/interestCap.js +81 -0
  130. package/kits/hub-game/code/client/invites.js +231 -0
  131. package/kits/hub-game/code/client/joinError.js +9 -0
  132. package/kits/hub-game/code/client/keys.js +36 -0
  133. package/kits/hub-game/code/client/labelsNear.js +234 -0
  134. package/kits/hub-game/code/client/landscapeLayout.js +17 -0
  135. package/kits/hub-game/code/client/layoutCache.js +264 -0
  136. package/kits/hub-game/code/client/loadTelemetry.js +20 -0
  137. package/kits/hub-game/code/client/loadingCover.js +148 -0
  138. package/kits/hub-game/code/client/loadingEntry.js +8 -0
  139. package/kits/hub-game/code/client/menuIcons.js +34 -0
  140. package/kits/hub-game/code/client/menuRows.js +43 -0
  141. package/kits/hub-game/code/client/modelReady.js +7 -0
  142. package/kits/hub-game/code/client/pack.js +6 -2
  143. package/kits/hub-game/code/client/packFormat.js +3 -3
  144. package/kits/hub-game/code/client/padCueArrival.js +23 -0
  145. package/kits/hub-game/code/client/padCues.js +112 -0
  146. package/kits/hub-game/code/client/padOccupancy.js +88 -0
  147. package/kits/hub-game/code/client/padReadability.js +26 -0
  148. package/kits/hub-game/code/client/padRings.js +69 -0
  149. package/kits/hub-game/code/client/pushVisit.js +14 -0
  150. package/kits/hub-game/code/client/quality.js +205 -0
  151. package/kits/hub-game/code/client/qualityEntry.js +55 -0
  152. package/kits/hub-game/code/client/rehello.js +167 -0
  153. package/kits/hub-game/code/client/safeLayout.js +338 -0
  154. package/kits/hub-game/code/client/safeStyle.js +42 -0
  155. package/kits/hub-game/code/client/say.js +12 -3
  156. package/kits/hub-game/code/client/shot.js +146 -0
  157. package/kits/hub-game/code/client/shotFit.js +56 -0
  158. package/kits/hub-game/code/client/signIn.js +28 -0
  159. package/kits/hub-game/code/client/sound.js +63 -8
  160. package/kits/hub-game/code/client/soundscape.js +1151 -0
  161. package/kits/hub-game/code/client/soundscapeActions.js +99 -0
  162. package/kits/hub-game/code/client/soundscapeAmbience.js +453 -0
  163. package/kits/hub-game/code/client/soundscapeBaked.js +143 -0
  164. package/kits/hub-game/code/client/soundscapeBusker.js +217 -0
  165. package/kits/hub-game/code/client/soundscapeCourt.js +200 -0
  166. package/kits/hub-game/code/client/soundscapeCrowd.js +331 -0
  167. package/kits/hub-game/code/client/soundscapeCues.js +362 -0
  168. package/kits/hub-game/code/client/soundscapeMap.js +181 -0
  169. package/kits/hub-game/code/client/soundscapeMarket.js +176 -0
  170. package/kits/hub-game/code/client/soundscapeMusic.js +126 -0
  171. package/kits/hub-game/code/client/soundscapeMusicEngine.js +460 -0
  172. package/kits/hub-game/code/client/soundscapeSimlish.js +737 -0
  173. package/kits/hub-game/code/client/soundscapeSongs.js +127 -0
  174. package/kits/hub-game/code/client/soundscapeSongsRound3.js +63 -0
  175. package/kits/hub-game/code/client/soundscapeSynthesis.js +168 -0
  176. package/kits/hub-game/code/client/soundscapeUi.js +211 -0
  177. package/kits/hub-game/code/client/soundscapeVoice.js +1209 -0
  178. package/kits/hub-game/code/client/soundscapeWaves.js +206 -0
  179. package/kits/hub-game/code/client/spin.js +101 -0
  180. package/kits/hub-game/code/client/state.js +162 -1
  181. package/kits/hub-game/code/client/stuck.js +259 -0
  182. package/kits/hub-game/code/client/talk.js +714 -59
  183. package/kits/hub-game/code/client/tiers.js +543 -52
  184. package/kits/hub-game/code/client/toastBand.js +37 -0
  185. package/kits/hub-game/code/client/together.js +39 -2
  186. package/kits/hub-game/code/client/visibility.js +43 -0
  187. package/kits/hub-game/code/client/weakestLookBake.js +92 -0
  188. package/kits/hub-game/code/client/weakestTier.js +295 -0
  189. package/kits/hub-game/code/client/wear.js +461 -170
  190. package/kits/hub-game/code/client/worldLabels.js +241 -0
  191. package/kits/hub-game/code/client/yours.js +200 -0
  192. package/kits/hub-game/code/companionSpec.js +45 -0
  193. package/kits/hub-game/code/npcDisplayText.js +55 -0
  194. package/kits/hub-game/code/privateText.js +7 -0
  195. package/kits/hub-game/code/server/act.js +124 -0
  196. package/kits/hub-game/code/server/actions.js +138 -0
  197. package/kits/hub-game/code/server/actors.js +11 -2
  198. package/kits/hub-game/code/server/analytics.js +83 -0
  199. package/kits/hub-game/code/server/anonymousEntry.js +49 -0
  200. package/kits/hub-game/code/server/arrivalPose.js +36 -0
  201. package/kits/hub-game/code/server/ask.js +155 -0
  202. package/kits/hub-game/code/server/ballot.js +539 -0
  203. package/kits/hub-game/code/server/cells.js +100 -0
  204. package/kits/hub-game/code/server/companion.js +107 -0
  205. package/kits/hub-game/code/server/cues.js +70 -0
  206. package/kits/hub-game/code/server/decor.js +269 -0
  207. package/kits/hub-game/code/server/doorAnalytics.js +52 -0
  208. package/kits/hub-game/code/server/earned.js +478 -0
  209. package/kits/hub-game/code/server/frameBatch.js +183 -0
  210. package/kits/hub-game/code/server/friendBests.js +166 -0
  211. package/kits/hub-game/code/server/friendsAmong.js +272 -0
  212. package/kits/hub-game/code/server/history.js +7 -0
  213. package/kits/hub-game/code/server/hub.js +2510 -95
  214. package/kits/hub-game/code/server/idle.js +60 -12
  215. package/kits/hub-game/code/server/index.js +28 -6
  216. package/kits/hub-game/code/server/invites.js +19 -0
  217. package/kits/hub-game/code/server/labels.js +36 -2
  218. package/kits/hub-game/code/server/loadAbandon.js +106 -0
  219. package/kits/hub-game/code/server/manifest.js +586 -7
  220. package/kits/hub-game/code/server/menu.js +161 -0
  221. package/kits/hub-game/code/server/npcs.js +1025 -113
  222. package/kits/hub-game/code/server/observe.js +408 -0
  223. package/kits/hub-game/code/server/padOccupancy.js +85 -0
  224. package/kits/hub-game/code/server/party.js +2 -2
  225. package/kits/hub-game/code/server/players.js +30 -0
  226. package/kits/hub-game/code/server/resumePose.js +152 -0
  227. package/kits/hub-game/code/server/say.js +1 -1
  228. package/kits/hub-game/code/server/shot.js +110 -0
  229. package/kits/hub-game/code/server/standing.js +123 -0
  230. package/kits/hub-game/code/server/storageLimit.js +187 -0
  231. package/kits/hub-game/code/server/vis.js +175 -0
  232. package/kits/hub-game/code/server/wear.js +12 -0
  233. package/kits/hub-game/code/server/yours.js +59 -0
  234. package/kits/hub-game/code/shared/act.js +35 -0
  235. package/kits/hub-game/code/shared/cues.js +9 -0
  236. package/kits/hub-game/code/shared/danceIdle.js +28 -0
  237. package/kits/hub-game/code/shared/decor.js +41 -0
  238. package/kits/hub-game/code/shared/loadStages.js +12 -0
  239. package/kits/hub-game/code/shared/quality.js +74 -0
  240. package/kits/hub-game/code/shared/say.js +2 -0
  241. package/kits/hub-game/code/shared/shot.js +53 -0
  242. package/kits/hub-game/code/shared/spin.js +57 -0
  243. package/kits/hub-game/code/systems/hub.js +1753 -202
  244. package/kits/hub-game/docs/analytics.md +279 -0
  245. package/kits/hub-game/docs/content-pack.md +1 -1
  246. package/kits/hub-game/docs/contract.md +3475 -77
  247. package/kits/hub-game/docs/home-pieces.md +71 -0
  248. package/kits/hub-game/docs/observed-progress.md +252 -0
  249. package/kits/hub-game/main.jsx +2 -0
  250. package/kits/hub-game/models/avatar-10.pxmodel +28 -0
  251. package/kits/hub-game/models/avatar-11.pxmodel +28 -0
  252. package/kits/hub-game/models/avatar-12.pxmodel +27 -0
  253. package/kits/hub-game/models/avatar-13.pxmodel +24 -0
  254. package/kits/hub-game/models/avatar-14.pxmodel +29 -0
  255. package/kits/hub-game/models/avatar-15.pxmodel +24 -0
  256. package/kits/hub-game/models/avatar-4.pxmodel +29 -0
  257. package/kits/hub-game/models/avatar-5.pxmodel +27 -0
  258. package/kits/hub-game/models/avatar-6.pxmodel +26 -0
  259. package/kits/hub-game/models/avatar-7.pxmodel +25 -0
  260. package/kits/hub-game/models/avatar-8.pxmodel +24 -0
  261. package/kits/hub-game/models/avatar-9.pxmodel +30 -0
  262. package/kits/hub-game/models/earned/badge-round.pxmodel +100 -0
  263. package/kits/hub-game/models/earned/badge-shield.pxmodel +117 -0
  264. package/kits/hub-game/models/earned/badge-star.pxmodel +87 -0
  265. package/kits/hub-game/models/earned/belt-plain.pxmodel +72 -0
  266. package/kits/hub-game/models/earned/held-ball.pxmodel +43 -0
  267. package/kits/hub-game/models/earned/held-lantern.pxmodel +85 -0
  268. package/kits/hub-game/models/earned/held-net.pxmodel +57 -0
  269. package/kits/hub-game/models/earned/held-trophy.pxmodel +109 -0
  270. package/kits/hub-game/models/earned/pin-round.pxmodel +62 -0
  271. package/kits/hub-game/models/earned/sash-plain.pxmodel +66 -0
  272. package/kits/hub-game/models/earned/square/belt-plain.pxmodel +104 -0
  273. package/kits/hub-game/models/earned/square/sash-plain.pxmodel +98 -0
  274. package/kits/hub-game/models/hats/bat-clip.pxmodel +206 -0
  275. package/kits/hub-game/models/hats/beekeeper.pxmodel +149 -0
  276. package/kits/hub-game/models/hats/cap.pxmodel +162 -0
  277. package/kits/hub-game/models/hats/captain.pxmodel +178 -0
  278. package/kits/hub-game/models/hats/crooked-top.pxmodel +172 -0
  279. package/kits/hub-game/models/hats/flower-crown.pxmodel +451 -0
  280. package/kits/hub-game/models/hats/foam-crown.pxmodel +179 -0
  281. package/kits/hub-game/models/hats/lantern.pxmodel +230 -0
  282. package/kits/hub-game/models/hats/laurel.pxmodel +533 -0
  283. package/kits/hub-game/models/hats/lighthouse.pxmodel +96 -0
  284. package/kits/hub-game/models/hats/sailor.pxmodel +141 -0
  285. package/kits/hub-game/models/hats/souwester.pxmodel +131 -0
  286. package/kits/hub-game/models/hats/straw.pxmodel +139 -0
  287. package/kits/hub-game/models/hats/sunflower.pxmodel +406 -0
  288. package/kits/hub-game/models/hats/sweatband.pxmodel +112 -0
  289. package/kits/hub-game/models/hats/witch.pxmodel +147 -0
  290. package/kits/hub-game/package-lock.json +10 -1
  291. package/kits/hub-game/package.json +6 -2
  292. package/kits/hub-game/play/player.js +142 -0
  293. package/kits/hub-game/play/registry.js +47 -0
  294. package/kits/hub-game/play.jsx +37 -0
  295. package/kits/hub-game/scripts/check.mjs +117 -16
  296. package/kits/hub-game/scripts/companion-follower-wire.json +1 -0
  297. package/kits/hub-game/scripts/fixtures/decor-keyless-draw.json +132 -0
  298. package/kits/hub-game/scripts/fixtures/decor-keyless.json +293 -0
  299. package/kits/hub-game/scripts/fixtures/engine-models-stub.mjs +26 -0
  300. package/kits/hub-game/scripts/fixtures/fake-dom.mjs +123 -0
  301. package/kits/hub-game/scripts/fixtures/interest-legacy.json +385 -0
  302. package/kits/hub-game/scripts/fixtures/npc-notes-v1.77.jsonl +4 -0
  303. package/kits/hub-game/scripts/fixtures/vis-shared-wire.json +1 -0
  304. package/kits/hub-game/scripts/gen-avatars.mjs +933 -16
  305. package/kits/hub-game/scripts/gen-earned.mjs +285 -0
  306. package/kits/hub-game/scripts/gen-hats.mjs +827 -0
  307. package/kits/hub-game/scripts/grab.before-orbit.mjs +400 -0
  308. package/kits/hub-game/scripts/pose-storage-fixture.mjs +46 -0
  309. package/kits/hub-game/scripts/soundscape-wave-analysis.mjs +125 -0
  310. package/kits/hub-game/scripts/test-act-client.mjs +186 -0
  311. package/kits/hub-game/scripts/test-act.mjs +171 -0
  312. package/kits/hub-game/scripts/test-action-layout.mjs +80 -0
  313. package/kits/hub-game/scripts/test-action-observers.mjs +46 -0
  314. package/kits/hub-game/scripts/test-actions-client.mjs +853 -0
  315. package/kits/hub-game/scripts/test-actions.mjs +298 -0
  316. package/kits/hub-game/scripts/test-actor-budget.mjs +44 -0
  317. package/kits/hub-game/scripts/test-actors.mjs +38 -23
  318. package/kits/hub-game/scripts/test-analytics.mjs +76 -0
  319. package/kits/hub-game/scripts/test-anonymous-entry.mjs +28 -0
  320. package/kits/hub-game/scripts/test-arrival-pose-server.mjs +196 -0
  321. package/kits/hub-game/scripts/test-arrival-pose.mjs +24 -0
  322. package/kits/hub-game/scripts/test-ask-client.mjs +358 -0
  323. package/kits/hub-game/scripts/test-ask-slot.mjs +85 -0
  324. package/kits/hub-game/scripts/test-ask.mjs +269 -0
  325. package/kits/hub-game/scripts/test-attention.mjs +10 -1
  326. package/kits/hub-game/scripts/test-avatar-cap.mjs +379 -0
  327. package/kits/hub-game/scripts/test-avatar-colors.mjs +72 -0
  328. package/kits/hub-game/scripts/test-avatar-models.mjs +181 -0
  329. package/kits/hub-game/scripts/test-avatar-share.mjs +318 -0
  330. package/kits/hub-game/scripts/test-avatar-wire.mjs +792 -0
  331. package/kits/hub-game/scripts/test-avatar.mjs +584 -7
  332. package/kits/hub-game/scripts/test-back-visibility.mjs +82 -0
  333. package/kits/hub-game/scripts/test-ballot.mjs +1008 -0
  334. package/kits/hub-game/scripts/test-ban-join.mjs +121 -13
  335. package/kits/hub-game/scripts/test-build.mjs +49 -0
  336. package/kits/hub-game/scripts/test-cells.mjs +71 -0
  337. package/kits/hub-game/scripts/test-chat.mjs +863 -0
  338. package/kits/hub-game/scripts/test-classic.mjs +2 -0
  339. package/kits/hub-game/scripts/test-companion-chat.mjs +216 -0
  340. package/kits/hub-game/scripts/test-companion-client.mjs +1167 -0
  341. package/kits/hub-game/scripts/test-companion.mjs +259 -0
  342. package/kits/hub-game/scripts/test-control-layout-dom.mjs +120 -0
  343. package/kits/hub-game/scripts/test-crowd-names.mjs +205 -0
  344. package/kits/hub-game/scripts/test-decor-client.mjs +344 -0
  345. package/kits/hub-game/scripts/test-decor.mjs +464 -0
  346. package/kits/hub-game/scripts/test-default-environment-root.mjs +95 -0
  347. package/kits/hub-game/scripts/test-default-environment.mjs +267 -0
  348. package/kits/hub-game/scripts/test-door-analytics.mjs +58 -0
  349. package/kits/hub-game/scripts/test-door-jump.mjs +100 -0
  350. package/kits/hub-game/scripts/test-earned-client.mjs +459 -0
  351. package/kits/hub-game/scripts/test-earned.mjs +1224 -0
  352. package/kits/hub-game/scripts/test-emote-bubble.mjs +110 -0
  353. package/kits/hub-game/scripts/test-far-avatars.mjs +340 -0
  354. package/kits/hub-game/scripts/test-fps-telemetry.mjs +112 -0
  355. package/kits/hub-game/scripts/test-frame-batch.mjs +252 -0
  356. package/kits/hub-game/scripts/test-fresh-friends.mjs +118 -0
  357. package/kits/hub-game/scripts/test-friend-bests.mjs +435 -0
  358. package/kits/hub-game/scripts/test-grab-orbit.mjs +961 -0
  359. package/kits/hub-game/scripts/test-grab.mjs +7 -0
  360. package/kits/hub-game/scripts/test-hats.mjs +422 -168
  361. package/kits/hub-game/scripts/test-high-only.mjs +170 -0
  362. package/kits/hub-game/scripts/test-hub-leaving.mjs +203 -0
  363. package/kits/hub-game/scripts/test-hub-ops.mjs +758 -2
  364. package/kits/hub-game/scripts/test-hub-trip.mjs +1594 -12
  365. package/kits/hub-game/scripts/test-hud-clear.mjs +484 -57
  366. package/kits/hub-game/scripts/test-hud-defects-dom.mjs +100 -0
  367. package/kits/hub-game/scripts/test-hud-rate.mjs +224 -0
  368. package/kits/hub-game/scripts/test-hud-safe-visibility-dom.mjs +83 -0
  369. package/kits/hub-game/scripts/test-idle.mjs +427 -1
  370. package/kits/hub-game/scripts/test-interest-cap.mjs +36 -0
  371. package/kits/hub-game/scripts/test-interest-cells.mjs +513 -0
  372. package/kits/hub-game/scripts/test-interest-client.mjs +118 -0
  373. package/kits/hub-game/scripts/test-interest.mjs +15 -0
  374. package/kits/hub-game/scripts/test-invites-client.mjs +430 -0
  375. package/kits/hub-game/scripts/test-invites.mjs +109 -0
  376. package/kits/hub-game/scripts/test-keys.mjs +46 -1
  377. package/kits/hub-game/scripts/test-labels.mjs +664 -0
  378. package/kits/hub-game/scripts/test-landscape-layout.mjs +194 -0
  379. package/kits/hub-game/scripts/test-list-scroll-dom.mjs +49 -0
  380. package/kits/hub-game/scripts/test-load-abandon.mjs +246 -0
  381. package/kits/hub-game/scripts/test-loading-cover.mjs +162 -0
  382. package/kits/hub-game/scripts/test-manifest.mjs +472 -0
  383. package/kits/hub-game/scripts/test-menu-client.mjs +585 -0
  384. package/kits/hub-game/scripts/test-menu.mjs +319 -0
  385. package/kits/hub-game/scripts/test-npcs.mjs +2528 -13
  386. package/kits/hub-game/scripts/test-object-entry.mjs +76 -0
  387. package/kits/hub-game/scripts/test-observed.mjs +745 -0
  388. package/kits/hub-game/scripts/test-pack.mjs +7 -0
  389. package/kits/hub-game/scripts/test-pad-cues.mjs +304 -0
  390. package/kits/hub-game/scripts/test-pad-occupancy.mjs +177 -0
  391. package/kits/hub-game/scripts/test-picker.mjs +541 -0
  392. package/kits/hub-game/scripts/test-placement-cache.mjs +690 -0
  393. package/kits/hub-game/scripts/test-progress-reset.mjs +559 -0
  394. package/kits/hub-game/scripts/test-push-visit.mjs +26 -0
  395. package/kits/hub-game/scripts/test-quality.mjs +385 -0
  396. package/kits/hub-game/scripts/test-rehello.mjs +1733 -0
  397. package/kits/hub-game/scripts/test-relations-among.mjs +222 -0
  398. package/kits/hub-game/scripts/test-relations-refresh.mjs +188 -0
  399. package/kits/hub-game/scripts/test-resume-action-order.mjs +598 -0
  400. package/kits/hub-game/scripts/test-resume-held.mjs +239 -0
  401. package/kits/hub-game/scripts/test-resume-pose.mjs +142 -0
  402. package/kits/hub-game/scripts/test-safe-events-dom.mjs +116 -0
  403. package/kits/hub-game/scripts/test-safe-layout.mjs +330 -0
  404. package/kits/hub-game/scripts/test-say.mjs +1 -1
  405. package/kits/hub-game/scripts/test-shot.mjs +901 -0
  406. package/kits/hub-game/scripts/test-signin-client.mjs +45 -0
  407. package/kits/hub-game/scripts/test-soundscape.mjs +5437 -0
  408. package/kits/hub-game/scripts/test-spin.mjs +314 -0
  409. package/kits/hub-game/scripts/test-standing.mjs +449 -0
  410. package/kits/hub-game/scripts/test-storage-limit.mjs +333 -0
  411. package/kits/hub-game/scripts/test-stuck.mjs +1904 -0
  412. package/kits/hub-game/scripts/test-talk-overlay-dom.mjs +130 -0
  413. package/kits/hub-game/scripts/test-tier-cells.mjs +706 -0
  414. package/kits/hub-game/scripts/test-tiers-render.mjs +412 -0
  415. package/kits/hub-game/scripts/test-tiers.mjs +476 -2
  416. package/kits/hub-game/scripts/test-toast-band.mjs +61 -0
  417. package/kits/hub-game/scripts/test-try-on.mjs +22 -22
  418. package/kits/hub-game/scripts/test-vis.mjs +770 -0
  419. package/kits/hub-game/scripts/test-visibility.mjs +134 -0
  420. package/kits/hub-game/scripts/test-weakest-tier.mjs +924 -0
  421. package/kits/hub-game/scripts/test-world-labels.mjs +367 -0
  422. package/kits/hub-game/scripts/test-yours-chrome.mjs +210 -0
  423. package/kits/hub-game/scripts/test-yours.mjs +403 -0
  424. package/kits/multiplayer-3d/CLAUDE.md +50 -0
  425. package/kits/multiplayer-3d/castle.json +5 -5
  426. package/kits/multiplayer-3d/code/client/avatars.js +7 -0
  427. package/kits/multiplayer-3d/code/client/gait.js +65 -0
  428. package/kits/multiplayer-3d/code/client/joinFailure.js +27 -0
  429. package/kits/multiplayer-3d/code/client/nameTags.js +59 -4
  430. package/kits/multiplayer-3d/code/client/resumeGate.js +139 -0
  431. package/kits/multiplayer-3d/code/options.js +5 -0
  432. package/kits/multiplayer-3d/code/server/ownership.js +10 -2
  433. package/kits/multiplayer-3d/code/server/sceneBodies.js +12 -0
  434. package/kits/multiplayer-3d/code/server/world.js +7 -0
  435. package/kits/multiplayer-3d/code/systems/multiplayer.js +443 -34
  436. package/kits/multiplayer-3d/package-lock.json +8 -1
  437. package/kits/multiplayer-3d/package.json +3 -1
  438. package/kits/multiplayer-3d/scripts/fixtures/README.md +11 -0
  439. package/kits/multiplayer-3d/scripts/fixtures/ownership-legacy.json +2 -0
  440. package/kits/multiplayer-3d/scripts/ownership-harness.mjs +102 -0
  441. package/kits/multiplayer-3d/scripts/ownership-loader.mjs +46 -0
  442. package/kits/multiplayer-3d/scripts/ownership-worker.mjs +15 -0
  443. package/kits/multiplayer-3d/scripts/record-ownership-session.mjs +98 -0
  444. package/kits/multiplayer-3d/scripts/test-eligible-claims.mjs +167 -0
  445. package/kits/multiplayer-3d/scripts/test-join-watchdog.mjs +436 -0
  446. package/kits/multiplayer-3d/scripts/test-own-name-tag.mjs +247 -0
  447. package/kits/multiplayer-3d/scripts/test-resume-gate.mjs +624 -0
  448. package/kits/physics-2d/CLAUDE.md +19 -1
  449. package/kits/physics-2d/castle.json +2 -2
  450. package/kits/physics-2d/engine/frozenActors.js +233 -0
  451. package/kits/physics-2d/engine/scene.js +337 -3
  452. package/kits/physics-2d/engine/skyKey.js +129 -0
  453. package/kits/physics-2d/engine/stillClock.js +106 -0
  454. package/kits/physics-2d/engine/updateBudget.js +21 -0
  455. package/kits/physics-2d/eslint.config.js +1 -1
  456. package/kits/physics-2d/play/behaviors/AnalogStick.js +198 -0
  457. package/kits/physics-2d/play/behaviors/Camera.js +40 -0
  458. package/kits/physics-2d/play/behaviors/Collider.js +122 -0
  459. package/kits/physics-2d/play/behaviors/Draggable.js +115 -0
  460. package/kits/physics-2d/play/behaviors/Goal.js +46 -0
  461. package/kits/physics-2d/play/behaviors/Joints.js +126 -0
  462. package/kits/physics-2d/play/behaviors/Layout.js +71 -0
  463. package/kits/physics-2d/play/behaviors/RigidBody.js +57 -0
  464. package/kits/physics-2d/play/behaviors/Slingshot.js +142 -0
  465. package/kits/physics-2d/play/behaviors/SoundPlayer.js +263 -0
  466. package/kits/physics-2d/play/behaviors/Sprite.js +406 -0
  467. package/kits/physics-2d/play/behaviors/Style.js +209 -0
  468. package/kits/physics-2d/play/behaviors/Text.js +85 -0
  469. package/kits/physics-2d/play/behaviors/Video.js +93 -0
  470. package/kits/physics-2d/scripts/test-skip-unchanged.mjs +326 -1
  471. package/kits/physics-3d/CLAUDE.md +42 -529
  472. package/kits/physics-3d/behaviors/Body.jsx +3 -0
  473. package/kits/physics-3d/behaviors/Model.jsx +3 -0
  474. package/kits/physics-3d/behaviors/Player.jsx +661 -87
  475. package/kits/physics-3d/behaviors/Shape.jsx +3 -0
  476. package/kits/physics-3d/behaviors/Solid.jsx +3 -0
  477. package/kits/physics-3d/behaviors/Transform.jsx +3 -0
  478. package/kits/physics-3d/castle.json +3 -3
  479. package/kits/physics-3d/docs/engine-camera.md +542 -0
  480. package/kits/physics-3d/docs/engine-frame-cap.md +136 -0
  481. package/kits/physics-3d/docs/engine-load.md +149 -0
  482. package/kits/physics-3d/docs/engine-look.md +114 -0
  483. package/kits/physics-3d/docs/engine-shadows.md +372 -0
  484. package/kits/physics-3d/docs/engine-skip-work.md +187 -0
  485. package/kits/physics-3d/docs/engine-sky.md +198 -0
  486. package/kits/physics-3d/docs/engine-static-actors.md +226 -0
  487. package/kits/physics-3d/docs/engine-view.md +37 -0
  488. package/kits/physics-3d/docs/pxmodel-format.md +9 -1
  489. package/kits/physics-3d/engine3d/PlayOnly3D.jsx +5 -1
  490. package/kits/physics-3d/engine3d/Scene3DPlayer.jsx +19 -277
  491. package/kits/physics-3d/engine3d/actornode.js +87 -0
  492. package/kits/physics-3d/engine3d/animationBudget.js +23 -0
  493. package/kits/physics-3d/engine3d/branches.js +3 -13
  494. package/kits/physics-3d/engine3d/cage.js +2 -7
  495. package/kits/physics-3d/engine3d/cageops.js +2 -17
  496. package/kits/physics-3d/engine3d/dataBehaviors.js +12 -0
  497. package/kits/physics-3d/engine3d/editorWorld.js +6 -0
  498. package/kits/physics-3d/engine3d/emptynodes.js +232 -0
  499. package/kits/physics-3d/engine3d/framecap.js +99 -0
  500. package/kits/physics-3d/engine3d/frozenphysics.js +140 -0
  501. package/kits/physics-3d/engine3d/frozenstatics.js +273 -0
  502. package/kits/physics-3d/engine3d/gait.js +126 -0
  503. package/kits/physics-3d/engine3d/initialModelFiles.js +18 -0
  504. package/kits/physics-3d/engine3d/kithooks.js +47 -0
  505. package/kits/physics-3d/engine3d/look.js +514 -48
  506. package/kits/physics-3d/engine3d/lookbake.js +208 -0
  507. package/kits/physics-3d/engine3d/materialpresets.js +2 -0
  508. package/kits/physics-3d/engine3d/modelFiles.js +3 -17
  509. package/kits/physics-3d/engine3d/modelMath.js +49 -0
  510. package/kits/physics-3d/engine3d/modelready.js +16 -0
  511. package/kits/physics-3d/engine3d/motion.js +39 -10
  512. package/kits/physics-3d/engine3d/nearshadows.js +106 -21
  513. package/kits/physics-3d/engine3d/optimize.js +9 -5
  514. package/kits/physics-3d/engine3d/orbitinput.js +522 -10
  515. package/kits/physics-3d/engine3d/orbitlens.js +48 -0
  516. package/kits/physics-3d/engine3d/ownmodel.js +213 -0
  517. package/kits/physics-3d/engine3d/partgeometry.js +1 -16
  518. package/kits/physics-3d/engine3d/paths.js +1 -9
  519. package/kits/physics-3d/engine3d/playTimings.js +50 -0
  520. package/kits/physics-3d/engine3d/playerRun.js +372 -0
  521. package/kits/physics-3d/engine3d/pxmodel.js +42 -11
  522. package/kits/physics-3d/engine3d/rapier.js +27 -0
  523. package/kits/physics-3d/engine3d/scatter.js +1 -11
  524. package/kits/physics-3d/engine3d/shadowfade.js +890 -0
  525. package/kits/physics-3d/engine3d/sky.js +547 -0
  526. package/kits/physics-3d/engine3d/skylife.js +306 -0
  527. package/kits/physics-3d/engine3d/squarefirst.js +177 -0
  528. package/kits/physics-3d/engine3d/stillshadows.js +399 -0
  529. package/kits/physics-3d/engine3d/sweep.js +1 -25
  530. package/kits/physics-3d/engine3d/unchanged.js +11 -0
  531. package/kits/physics-3d/engine3d/viewrange.js +52 -0
  532. package/kits/physics-3d/engine3d/world3d.js +1253 -76
  533. package/kits/physics-3d/eslint.config.js +2 -1
  534. package/kits/physics-3d/main.jsx +10 -2
  535. package/kits/physics-3d/package-lock.json +7 -0
  536. package/kits/physics-3d/package.json +5 -1
  537. package/kits/physics-3d/play/behaviors/Body.js +31 -0
  538. package/kits/physics-3d/play/behaviors/Door.js +37 -0
  539. package/kits/physics-3d/play/behaviors/Lookable.js +16 -0
  540. package/kits/physics-3d/play/behaviors/Model.js +23 -0
  541. package/kits/physics-3d/play/behaviors/Pickup.js +46 -0
  542. package/kits/physics-3d/play/behaviors/Player.js +1204 -0
  543. package/kits/physics-3d/play/behaviors/Shape.js +47 -0
  544. package/kits/physics-3d/play/behaviors/Solid.js +16 -0
  545. package/kits/physics-3d/play/behaviors/Transform.js +29 -0
  546. package/kits/physics-3d/pnpm-lock.yaml +8 -0
  547. package/kits/physics-3d/scripts/bench-shadow-fade.mjs +37 -0
  548. package/kits/physics-3d/scripts/build-rapier-gz.mjs +56 -0
  549. package/kits/physics-3d/scripts/frozen-statics-fixture.mjs +141 -0
  550. package/kits/physics-3d/scripts/look-baseline.mjs +155 -0
  551. package/kits/physics-3d/scripts/test-camera-follow.mjs +5 -1
  552. package/kits/physics-3d/scripts/test-camera-orbit.mjs +2613 -82
  553. package/kits/physics-3d/scripts/test-drop-empty-parts.mjs +2 -2
  554. package/kits/physics-3d/scripts/test-empty-gait-hints.mjs +89 -0
  555. package/kits/physics-3d/scripts/test-frame-cap-bob.mjs +438 -0
  556. package/kits/physics-3d/scripts/test-frame-cap.mjs +452 -0
  557. package/kits/physics-3d/scripts/test-frozen-nested.mjs +49 -0
  558. package/kits/physics-3d/scripts/test-frozen-statics-legacy-physics2d.mjs +123 -0
  559. package/kits/physics-3d/scripts/test-frozen-statics.mjs +434 -0
  560. package/kits/physics-3d/scripts/test-gait.mjs +387 -0
  561. package/kits/physics-3d/scripts/test-look-bake.mjs +1056 -0
  562. package/kits/physics-3d/scripts/test-model-parse-cache.mjs +92 -0
  563. package/kits/physics-3d/scripts/test-near-shadows.mjs +5 -2
  564. package/kits/physics-3d/scripts/test-orbit-shadow-fade.mjs +2001 -0
  565. package/kits/physics-3d/scripts/test-orbit-shift-lock.mjs +582 -0
  566. package/kits/physics-3d/scripts/test-orbit-shot.mjs +657 -0
  567. package/kits/physics-3d/scripts/test-orbit-view.mjs +230 -0
  568. package/kits/physics-3d/scripts/test-rapier-gz.mjs +106 -0
  569. package/kits/physics-3d/scripts/test-skip-empty-nodes.mjs +845 -0
  570. package/kits/physics-3d/scripts/test-sky.mjs +2470 -0
  571. package/kits/physics-3d/scripts/test-square-first.mjs +921 -0
  572. package/kits/physics-3d/scripts/test-static-actors.mjs +10 -1
  573. package/kits/physics-3d/scripts/test-static-physics.mjs +4 -1
  574. package/kits/physics-3d/scripts/test-static-scenery.mjs +2174 -0
  575. package/kits/physics-3d/scripts/test-steady-hover.mjs +7 -2
  576. package/kits/physics-3d/scripts/test-still-shadows.mjs +477 -0
  577. package/kits/physics-3d/scripts/test-view-range.mjs +260 -0
  578. package/kits/physics-3d/systems/physics3d.js +419 -9
  579. package/kits/real-time/castle.json +2 -2
  580. package/kits/real-time/code/client/connection.js +33 -10
  581. package/kits/real-time/code/client/gameHooks.js +2 -0
  582. package/kits/real-time/code/client/joinOverlay.js +9 -4
  583. package/kits/real-time/code/server/gameHooks.js +7 -0
  584. package/kits/real-time/code/server/session.js +102 -22
  585. package/kits/real-time/package-lock.json +1 -1
  586. package/package.json +2 -2
  587. package/dist/shell/assets/index-Cf61cNfT.css +0 -1
@@ -0,0 +1,2174 @@
1
+ // `"engine": { "staticActors": true }` (engine3d/world3d.js and actornode.js,
2
+ // systems/physics3d.js, physics-2d engine/scene.js; docs/engine-static-actors.md has the terms),
3
+ // on the real SceneRuntime, the real physics system over a stand-in rapier
4
+ // (rapier itself is not installed where this runs), the real `syncActors` and
5
+ // `renderWorld`, and real models.
6
+ //
7
+ // Every scenario is played twice, frame for frame: in a scene that set the
8
+ // key, and in the same scene, marks and all, that did not. After every frame
9
+ // the two must agree in everything a frame is made of: each drawn object's
10
+ // geometry, material and world matrix, which nodes are in the scene, every
11
+ // Transform, every body, and every `update` a behaviour got.
12
+ //
13
+ // - Still frames: the marked actors are left out and their nodes frozen.
14
+ // - Every writer, followed on the frame it writes: `scene.touch` then a
15
+ // component written, added, removed; a despawn and a spawn; hub-game's own
16
+ // `applyVisibility` and `applyTints` (the real HubSystem); a network pose
17
+ // (multiplayer-3d's `applyPose`); `scene.physics3d`; `setBehaviors`.
18
+ // - A write without a touch is not followed, and the audit
19
+ // (`world.auditStatic`) finds it.
20
+ // - What still actors share, followed with no touch: a model file edited,
21
+ // the look switched, the scene itself moved.
22
+ // - hub-game's levers (the real `makeLevers`): frozen nodes taken out of the
23
+ // scene and put back.
24
+ // - Scenes that ask and scenes that do not in one world; a pass entered from
25
+ // inside another, both orders, returning and throwing, on its own frame.
26
+ // - The rule all three loops are written to: the still set is adopted only
27
+ // after an ordinary pass has completed without throwing; while a pass, or
28
+ // anything it calls back into, is running, nothing is frozen and no still
29
+ // state is trusted; any interruption leaves the next pass ordinary. A
30
+ // behaviour, a node listener, rapier's step and a collision callback each
31
+ // throw, and each walks, draws, syncs and updates the scene from inside an
32
+ // ordinary pass and a settled one.
33
+ // - Inert: without `skipUnchangedActors`, in the editor's world, with
34
+ // `instanceModels`; nothing left after a dispose.
35
+ //
36
+ // test-static-actors.mjs runs it (`npm run check`).
37
+ import assert from 'node:assert/strict';
38
+ import * as THREE from 'three';
39
+ import { EffectComposer } from 'three/examples/jsm/postprocessing/EffectComposer.js';
40
+ import fs from 'node:fs';
41
+ import path from 'node:path';
42
+ import { register } from 'node:module';
43
+ import { fileURLToPath } from 'node:url';
44
+ // Its import registers the resolver the kit's modules need under node.
45
+ import { makeWorld } from './test-static-passes.mjs';
46
+ import { drawn } from './test-drop-empty-parts.mjs';
47
+
48
+ // A rapier that keeps what the system asks of it: bodies with a type and a
49
+ // place, moved only by the system. Dynamic bodies fall to the ground.
50
+ const rapier = `
51
+ export const init = async () => {};
52
+ export const RigidBodyType = { Dynamic: 0, Fixed: 1, KinematicPositionBased: 2, KinematicVelocityBased: 3 };
53
+ export const ActiveEvents = { COLLISION_EVENTS: 1 };
54
+ export const QueryFilterFlags = { EXCLUDE_SENSORS: 1, EXCLUDE_DYNAMIC: 2, EXCLUDE_KINEMATIC: 4 };
55
+ export class Ball { constructor(radius) { this.radius = radius; } }
56
+ class Desc {
57
+ constructor(type) { this.type = type; this.at = { x: 0, y: 0, z: 0 }; }
58
+ setTranslation(x, y, z) { this.at = { x, y, z }; return this; }
59
+ setRotation() { return this; } setGravityScale() { return this; } lockRotations() { return this; }
60
+ setLinearDamping() { return this; } setAngularDamping() { return this; } setCcdEnabled() { return this; } setCanSleep() { return this; }
61
+ }
62
+ export const RigidBodyDesc = { dynamic: () => new Desc(0), fixed: () => new Desc(1), kinematicPositionBased: () => new Desc(2) };
63
+ const collider = () => new Proxy({}, { get: (t, k, self) => () => self });
64
+ export const ColliderDesc = { ball: collider, capsule: collider, cylinder: collider, cuboid: collider };
65
+ export class Ray { constructor(origin, dir) { this.origin = origin; this.dir = dir; } }
66
+ export class EventQueue { drainCollisionEvents() {} free() {} }
67
+ class Body {
68
+ constructor(desc) { this.type = desc.type; this.pos = { ...desc.at }; this.rot = { x: 0, y: 0, z: 0, w: 1 }; this.vel = { x: 0, y: 0, z: 0 }; this.sets = 0; }
69
+ bodyType() { return this.type; } isDynamic() { return this.type === 0; } mass() { return 1; } numColliders() { return 1; }
70
+ translation() { return { ...this.pos }; } rotation() { return { ...this.rot }; } linvel() { return { ...this.vel }; } angvel() { return { x: 0, y: 0, z: 0 }; }
71
+ setLinvel(v) { this.vel = { x: v.x, y: v.y, z: v.z }; } setAngvel() {}
72
+ setTranslation(p) { this.pos = { x: p.x, y: p.y, z: p.z }; this.sets += 1; } setRotation(q) { this.rot = { ...q }; }
73
+ setNextKinematicTranslation(p) { this.pos = { x: p.x, y: p.y, z: p.z }; } setNextKinematicRotation(q) { this.rot = { ...q }; }
74
+ applyImpulse(j) { for (const k of ['x', 'y', 'z']) this.vel[k] += j[k]; } addForce() {} resetForces() {} wakeUp() {} isSleeping() { return false; }
75
+ }
76
+ export class World {
77
+ constructor(gravity) { this.gravity = gravity; this.bodies = new Set(); this.timestep = 1 / 60; this.handles = 0; }
78
+ createRigidBody(desc) { const body = new Body(desc); this.bodies.add(body); return body; }
79
+ // Queries, as much of them as says which fixed bodies the world holds and
80
+ // where: a collider is a point at its body's place.
81
+ createCollider(desc, body) {
82
+ const collider = { handle: (this.handles += 1), body, projectPoint: () => ({ point: { ...body.pos }, isInside: false }) };
83
+ body.collider = collider;
84
+ return collider;
85
+ }
86
+ removeRigidBody(body) { this.bodies.delete(body); }
87
+ fixedColliders() { return [...this.bodies].filter((body) => body.type === 1 && body.collider).map((body) => body.collider); }
88
+ castRay(ray, max) {
89
+ let best = null;
90
+ for (const collider of this.fixedColliders()) {
91
+ const p = collider.body.pos;
92
+ const along = (p.x - ray.origin.x) * ray.dir.x + (p.y - ray.origin.y) * ray.dir.y + (p.z - ray.origin.z) * ray.dir.z;
93
+ const off = Math.hypot(p.x - ray.origin.x - ray.dir.x * along, p.y - ray.origin.y - ray.dir.y * along, p.z - ray.origin.z - ray.dir.z * along);
94
+ if (along > 0 && along <= max && off < 0.01 && (!best || along < best.timeOfImpact)) best = { timeOfImpact: along, collider };
95
+ }
96
+ return best;
97
+ }
98
+ castShape() { return null; }
99
+ intersectionWithShape() { return null; }
100
+ intersectionsWithShape(point, rotation, shape, each) {
101
+ for (const collider of this.fixedColliders()) {
102
+ const p = collider.body.pos;
103
+ if (Math.hypot(p.x - point.x, p.y - point.y, p.z - point.z) <= shape.radius) each(collider);
104
+ }
105
+ }
106
+ step() {
107
+ for (const body of this.bodies) {
108
+ if (body.type !== 0) continue;
109
+ body.vel.y += this.gravity.y * this.timestep;
110
+ for (const k of ['x', 'y', 'z']) body.pos[k] += body.vel[k] * this.timestep;
111
+ if (body.pos.y < 0.5) { body.pos.y = 0.5; body.vel.y = 0; }
112
+ }
113
+ }
114
+ free() {}
115
+ }
116
+ `;
117
+ const names = fs.readFileSync(new URL('../../physics-2d/engine/files.js', import.meta.url), 'utf8').match(/^export (?:const|function|async function|let) [A-Za-z0-9_]+/gm) ?? [];
118
+ const filesStub = names
119
+ .map((line) => line.split(' ').pop())
120
+ .map((name) => `export const ${name} = ${name.startsWith('initial') ? '{}' : name === 'parseJsonFile' ? '(p, text) => ({ value: JSON.parse(text) })' : '() => null'};`)
121
+ .join(' ');
122
+ const stubs = {
123
+ 'castle-web-sdk': `export const castle = {}; export default {}; export const resolveDeckFile = (name) => String(name).replace(/^\\.\\//, ''); export const deckPrefixOf = () => ''; export const IMPORTS_DIR = 'imports'; export const IMPORTS_PREFIX = 'imports/';`,
124
+ files: filesStub,
125
+ systemRegistry: `export const systemInstallers = [];`,
126
+ fonts: `export const deckFontFamily = 'sans-serif';`,
127
+ rapier,
128
+ };
129
+ const hooks = `
130
+ import { existsSync } from 'node:fs';
131
+ import { fileURLToPath } from 'node:url';
132
+ const stubs = ${JSON.stringify(stubs)};
133
+ const stub = (name) => ({ url: 'data:text/javascript,' + encodeURIComponent(stubs[name]), shortCircuit: true });
134
+ export async function resolve(specifier, context, next) {
135
+ const isRapier = specifier === '@dimforge/rapier3d-compat' ||
136
+ ((specifier.startsWith('.') || specifier.startsWith('file:')) &&
137
+ new URL(specifier, context.parentURL).href.endsWith('/kits/physics-3d/engine3d/rapier.js'));
138
+ const parent = context.parentURL ?? '';
139
+ if (specifier === 'castle-web-sdk') return stub(specifier);
140
+ if (isRapier && parent.endsWith('?still')) return stub('rapier');
141
+ if (/\\?still$/.test(specifier)) return { url: new URL(specifier, parent).href, shortCircuit: true };
142
+ const kit = /^@imports\\/castle\\.([a-z0-9-]+)\\/(.*)$/.exec(specifier);
143
+ if (kit) specifier = parent.replace(/\\/kits\\/.*/, '/kits/' + kit[1] + '/') + kit[2];
144
+ if (parent.includes('/physics-2d/engine/') || specifier.includes('/physics-2d/engine/')) {
145
+ const own = /(?:^|\\/)(files|systemRegistry|fonts)(\\.js)?$/.exec(specifier);
146
+ if (own) return stub(own[1]);
147
+ }
148
+ if ((specifier.startsWith('.') || specifier.startsWith('file:')) && parent.includes('/kits/') && !/\\.(m?js|jsx|json)(\\?.*)?$/.test(specifier)) {
149
+ const base = new URL(specifier, parent).href;
150
+ for (const ext of ['.js', '.jsx']) if (existsSync(fileURLToPath(base + ext))) return next(base + ext, context);
151
+ }
152
+ return next(specifier, context);
153
+ }`;
154
+ register(`data:text/javascript,${encodeURIComponent(hooks)}`);
155
+
156
+ const { syncActors, syncGround, updatePhysicsDebug, resizeWorld, renderWorld, disposeWorld } = await import('../engine3d/world3d.js');
157
+ const { isFrozen } = await import('../engine3d/actornode.js');
158
+ const { setLookEnabled } = await import('../engine3d/look.js');
159
+ const { SceneRuntime } = await import('../../physics-2d/engine/scene.js');
160
+ const { Physics3DSystem } = await import('../systems/physics3d.js?still');
161
+
162
+ const DT = 1 / 60;
163
+ const KIT = fileURLToPath(new URL('..', import.meta.url));
164
+ const REPO = path.join(KIT, '..', '..');
165
+ let checks = 0;
166
+ const ok = (value, message) => {
167
+ checks += 1;
168
+ assert.ok(value, message);
169
+ };
170
+ const equal = (a, b, message) => {
171
+ checks += 1;
172
+ assert.deepEqual(a, b, message);
173
+ };
174
+
175
+ //
176
+ // The scene
177
+ //
178
+
179
+ const model = (name) => fs.readFileSync(path.join(KIT, 'models', name), 'utf8');
180
+ const BARREL = 'models/barrel.pxmodel';
181
+ const ROCK = 'models/rock.pxmodel';
182
+ const TREE = 'models/tree.pxmodel';
183
+ const WALKER = 'models/player.pxmodel';
184
+ const NOTHING = 'models/nothing.pxmodel';
185
+ const baseFiles = () => ({
186
+ [BARREL]: model('barrel.pxmodel'),
187
+ [ROCK]: model('rock.pxmodel'),
188
+ [TREE]: model('tree.pxmodel'),
189
+ [WALKER]: model('player.pxmodel'),
190
+ [NOTHING]: JSON.stringify({ format: 'pxmodel', name: 'Nothing', look: false, parts: [] }),
191
+ });
192
+
193
+ // The component classes: the kit's own have no `update`; `Mover` and
194
+ // `Counter` do, and `Late` gains one part way through a scenario.
195
+ const log = [];
196
+ const quiet = (name, defaultProps = {}) => class { static behaviorName = name; static defaultProps = defaultProps; };
197
+ const Transform = quiet('Transform', { x: 0, y: 0, z: 0, rotationX: 0, rotationY: 0, rotationZ: 0 });
198
+ class Mover {
199
+ static behaviorName = 'Mover';
200
+ static defaultProps = { speed: 1 };
201
+ update(actor, scene, dt) {
202
+ actor.components.Transform.x += this.props.speed * dt;
203
+ actor.components.Transform.rotationY += 3;
204
+ log.push(`${scene.tag} Mover ${actor.id}`);
205
+ }
206
+ }
207
+ class Counter {
208
+ static behaviorName = 'Counter';
209
+ static defaultProps = {};
210
+ update(actor, scene) {
211
+ log.push(`${scene.tag} Counter ${actor.id}`);
212
+ // What a scenario has this behaviour do from inside the update loop.
213
+ scene.fromUpdate?.();
214
+ }
215
+ }
216
+ const lateWith = (acts) =>
217
+ acts
218
+ ? class {
219
+ static behaviorName = 'Late';
220
+ static defaultProps = {};
221
+ update(actor, scene) {
222
+ actor.components.Transform.z += 0.01;
223
+ log.push(`${scene.tag} Late ${actor.id}`);
224
+ }
225
+ }
226
+ : quiet('Late');
227
+ const classesWith = (lateActs = false) => [Transform, quiet('Shape'), quiet('Model'), quiet('Solid'), quiet('Body', { type: 'fixed' }), quiet('Lookable'), Mover, Counter, lateWith(lateActs)];
228
+
229
+ const at = (x, z, more = {}) => ({ x, y: 0, z, rotationY: 30, ...more });
230
+ const box = (color = '#8899aa') => ({ kind: 'box', width: 1, height: 2, depth: 1, color });
231
+ // `s*` are marked and still; the others are marked and cannot be, or are not marked.
232
+ function sceneActors() {
233
+ const actors = [];
234
+ for (let i = 0; i < 6; i++) actors.push({ id: `s-barrel-${i}`, static: true, components: { Transform: at(i * 3, 0), Shape: box(), Model: { file: BARREL }, Solid: {} } });
235
+ for (let i = 0; i < 4; i++) actors.push({ id: `s-rock-${i}`, static: true, components: { Transform: at(i * 3, 4), Model: { file: ROCK, scale: 1.5, yOffset: 0.1 } } });
236
+ for (let i = 0; i < 4; i++) actors.push({ id: `s-box-${i}`, static: true, components: { Transform: at(i * 3, 8, { rotationX: 10 }), Shape: box('#aa5533'), Solid: {} } });
237
+ actors.push({ id: 's-tree', static: true, components: { Transform: at(40, 0), Model: { file: TREE }, Lookable: { text: 'a tree' } } });
238
+ actors.push({ id: 's-wall', static: true, components: { Transform: at(20, 12), Shape: box(), Model: { file: NOTHING }, Solid: {} } });
239
+ actors.push({ id: 's-late', static: true, components: { Transform: at(20, 16), Shape: box('#3355aa'), Late: {} } });
240
+ actors.push({ id: 's-marker', static: true, components: { Lookable: { text: 'no Transform' } } });
241
+ // Marked, and never still: a walking model, a Body, a component that updates.
242
+ actors.push({ id: 'm-walker', static: true, components: { Transform: at(-4, 0), Shape: box(), Model: { file: WALKER } } });
243
+ actors.push({ id: 'm-body', static: true, components: { Transform: at(-4, 4, { y: 3 }), Shape: box(), Body: { type: 'dynamic' } } });
244
+ actors.push({ id: 'm-mover', static: true, components: { Transform: at(-4, 8), Shape: box(), Mover: { speed: 2 } } });
245
+ // Not marked.
246
+ actors.push({ id: 'l-mover', components: { Transform: at(-8, 0), Model: { file: WALKER }, Mover: {} } });
247
+ actors.push({ id: 'l-counter', components: { Transform: at(-8, 4), Shape: box(), Counter: {} } });
248
+ actors.push({ id: 'l-lamp', components: { Transform: at(-8, 8), Shape: { kind: 'sphere', radius: 0.4, color: '#ffee88', emissive: '#ffee88' } } });
249
+ actors.push({ id: 'l-door', components: { Transform: at(-8, 12), Shape: box('#553311'), Body: { type: 'kinematic' }, Solid: {} } });
250
+ // Marked and still, and the last a pass comes to.
251
+ actors.push({ id: 's-last', static: true, components: { Transform: at(-12, 0), Shape: box('#667788'), Solid: {} } });
252
+ return actors;
253
+ }
254
+ const STILL = sceneActors().filter((a) => a.id.startsWith('s-')).map((a) => a.id);
255
+
256
+ const engineOf = (keyed, { skip = true, drop = false, bake = false, shadows = 0 } = {}) => ({
257
+ ...(skip ? { skipUnchangedActors: true } : {}),
258
+ ...(drop ? { dropEmptyParts: true } : {}),
259
+ ...(bake ? { look: { bake: 'deferred' } } : {}),
260
+ ...(shadows > 0 ? { shadows: { distance: shadows } } : {}),
261
+ ...(keyed ? { staticActors: true } : {}),
262
+ });
263
+
264
+ // A world as the player has it, drawn by a composer that only walks the
265
+ // scene, and a runtime with the physics system on it.
266
+ function makeSide(keyed, options = {}) {
267
+ const files = baseFiles();
268
+ const data = { name: 'Scenery', ground: { color: '#445566' }, engine: engineOf(keyed, options), actors: options.actors ?? sceneActors() };
269
+ const runtime = new SceneRuntime(data, classesWith(), {}, files, 'scenes/main.scene');
270
+ runtime.tag = keyed ? 'on' : 'off';
271
+ const system = new Physics3DSystem();
272
+ runtime.registerSystem(system);
273
+ system.attach(runtime);
274
+ const world = makeWorld();
275
+ world.composer = { render: () => world.scene.updateMatrixWorld() };
276
+ runtime.three = world;
277
+ return { keyed, world, runtime, system, files, data };
278
+ }
279
+
280
+ function frame(side, runtime = side.runtime) {
281
+ runtime.update(DT);
282
+ syncActors(side.world, runtime, {}, DT);
283
+ renderWorld(side.world, runtime);
284
+ }
285
+
286
+ // Everything a frame is made of.
287
+ function stateOf(side, runtime = side.runtime) {
288
+ const { world, system } = side;
289
+ const lines = drawn(world).map((line) => `drawn ${line}`);
290
+ for (const [id, entry] of world.nodes) {
291
+ const p = entry.node.position;
292
+ lines.push(`node ${id} ${entry.node.parent === world.scene ? 'in' : 'out'} ${p.x},${p.y},${p.z} ${entry.node.quaternion.toArray().join(',')} ${entry.node.scale.x} ${entry.sig.length}`);
293
+ }
294
+ for (const actor of runtime.getActors()) {
295
+ const t = actor.components.Transform;
296
+ lines.push(`actor ${actor.id} ${Object.keys(actor.components).join(',')} ${t ? [t.x, t.y, t.z, t.rotationX, t.rotationY, t.rotationZ].join(',') : ''} ${JSON.stringify(actor.components.Shape ?? null)}`);
297
+ }
298
+ for (const [id, entry] of system.bodies) {
299
+ const { pos, rot, type } = entry.body;
300
+ lines.push(`body ${id} ${type} ${pos.x},${pos.y},${pos.z} ${rot.x},${rot.y},${rot.z},${rot.w} ${entry.sig}`);
301
+ }
302
+ return lines.sort();
303
+ }
304
+
305
+ function same(pair, what, runtimes = null) {
306
+ const a = stateOf(pair.off, runtimes?.off);
307
+ const b = stateOf(pair.on, runtimes?.on);
308
+ checks += 1;
309
+ for (let i = 0; i < Math.max(a.length, b.length); i++) {
310
+ if (a[i] === b[i]) continue;
311
+ const [x, y] = [String(a[i]).split('|'), String(b[i]).split('|')];
312
+ const fields = x.map((field, n) => (field === y[n] ? null : `${field.slice(0, 260)} / ${String(y[n]).slice(0, 260)}`)).filter(Boolean);
313
+ assert.fail(`${what}: without the key / with it\n ${x[0].slice(0, 80)}\n ${fields.join('\n ')}`);
314
+ }
315
+ const strip = (tag) => log.filter((line) => line.startsWith(`${tag} `)).map((line) => line.slice(tag.length));
316
+ assert.deepEqual(strip('on'), strip('off'), `${what}: the same updates were called`);
317
+ }
318
+
319
+ // The two sides, warmed until the keyed one has settled.
320
+ async function makePair(options = {}) {
321
+ log.length = 0;
322
+ const pair = { off: makeSide(false, options), on: makeSide(true, options) };
323
+ // rapier's (stand-in) init resolves on its own time.
324
+ await new Promise((resolve) => setTimeout(resolve, 0));
325
+ // A look baked later is baked by the clock, a little a frame: the two
326
+ // sides are compared once it is done, not while.
327
+ if (options.bake) for (let i = 0; i < 6; i++) for (const side of [pair.off, pair.on]) frame(side);
328
+ else play(pair, 6, 'warming up');
329
+ return pair;
330
+ }
331
+
332
+ function play(pair, frames, what, each = null) {
333
+ for (let i = 0; i < frames; i++) {
334
+ for (const side of [pair.off, pair.on]) {
335
+ each?.(side, i);
336
+ frame(side);
337
+ }
338
+ same(pair, `${what}, frame ${i}`);
339
+ }
340
+ }
341
+
342
+ // Does the same to both sides, then plays.
343
+ function both(pair, what, act, frames = 4) {
344
+ for (const side of [pair.off, pair.on]) act(side);
345
+ play(pair, frames, what);
346
+ }
347
+
348
+ // What a system's keeper holds that a pass entering now would trust: its
349
+ // adoption, if it was made or confirmed at the count as it now stands.
350
+ const adoptedBy = (keeper) => (keeper && keeper.adopted && keeper.adopted.at === keeper.passes ? keeper.adopted : null);
351
+ const nodeOf = (side, id) => side.world.nodes.get(id).node;
352
+ const frozen = (side) => STILL.filter((id) => side.world.nodes.has(id) && isFrozen(nodeOf(side, id)));
353
+ const stillIds = (side) => [...(side.runtime.stillActors ?? [])].map((actor) => actor.id);
354
+ const settled = (side) => Boolean(adoptedBy(side.world.stillKeeper)) && adoptedBy(side.world.stillKeeper).version === side.runtime.stillVersion;
355
+
356
+ //
357
+ // Still frames
358
+ //
359
+
360
+ async function stillFrames() {
361
+ for (const drop of [false, true]) {
362
+ const pair = await makePair({ drop });
363
+ const { on, off } = pair;
364
+ equal(stillIds(on).sort(), [...STILL].sort(), 'the marked actors that can be are still; a walker, a Body and an updater are not');
365
+ equal(off.runtime.stillActors, null, 'without the key no actor is still');
366
+ ok(!off.world.stillKeeper && !off.system.stillKeeper && !('epoch' in off.world.skipping), 'and the world keeps nothing');
367
+ for (const [, entry] of off.world.nodes) ok(!Object.hasOwn(entry.node, 'updateMatrixWorld') && !('frozenAt' in entry.node), 'no node is told it may freeze');
368
+ ok(settled(on), 'the world has adopted the still set');
369
+ equal(adoptedBy(on.world.stillKeeper).count, STILL.length - 1, 'every still actor with a Transform has its node');
370
+ equal(frozen(on).length, STILL.length - 1, 'and every one of those nodes is frozen');
371
+ ok(!isFrozen(nodeOf(on, 'l-lamp')) && !isFrozen(nodeOf(on, 'm-walker')), 'no other node is');
372
+ equal(adoptedBy(on.system.stillKeeper)?.bodies, STILL.length - 1, 'the physics system has adopted their bodies');
373
+ const sets = () => STILL.map((id) => on.system.bodies.get(id)?.body.sets ?? 0).join();
374
+ const before = sets();
375
+ play(pair, 30, `still frames${drop ? ', dropEmptyParts' : ''}`);
376
+ ok(settled(on) && frozen(on).length === STILL.length - 1, 'thirty frames on it is still settled');
377
+ equal(sets(), before, 'and no still body was pushed again');
378
+ }
379
+ }
380
+
381
+ // With the look baked after the models are drawn (`"engine": { "look":
382
+ // { "bake": "deferred" } }`): the baking is done a little a frame, into the
383
+ // geometries of nodes that are meanwhile frozen, and the picture it ends on is
384
+ // the one without the key.
385
+ async function withTheLookBakedLater() {
386
+ const pair = await makePair({ bake: true });
387
+ const { on, off } = pair;
388
+ ok(on.runtime.bakesLookLater === true && on.world.lookBake, 'the scene bakes its look later');
389
+ for (let i = 0; i < 400 && (on.world.lookBake.pending > 0 || off.world.lookBake.pending > 0); i++) {
390
+ for (const side of [off, on]) frame(side);
391
+ }
392
+ equal([on.world.lookBake.pending, off.world.lookBake.pending], [0, 0], 'the baking ends');
393
+ play(pair, 3, 'the look baked later');
394
+ ok(settled(on) && frozen(on).length === STILL.length - 1, 'with the scenery still and frozen throughout');
395
+ }
396
+
397
+ // The orbit camera asks the physics world what stands in its way
398
+ // (`scene.physics3d.castRayFixed`, `castBallFixed`, `nearFixed`): fixed
399
+ // bodies. A still actor's body is one, made and put in its place by the
400
+ // ordinary pass before the first settled one, and found there on settled
401
+ // frames by every one of those queries. (The stand-in rapier's queries treat
402
+ // a collider as a point at its body's place; that is enough to say which
403
+ // bodies the world holds and where.)
404
+ async function fixedBodiesAreFound() {
405
+ const side = (await makePair()).on;
406
+ const phys = side.runtime.physics3d;
407
+ ok(adoptedBy(side.system.stillKeeper)?.bodies > 0 && settled(side), 'settled');
408
+ const solid = STILL.filter((id) => side.runtime.getActor(id).components.Shape);
409
+ const ask = (when) => {
410
+ for (const id of solid) {
411
+ const t = side.runtime.getActor(id).components.Transform;
412
+ const at = { x: t.x, y: t.y, z: t.z };
413
+ const from = { x: t.x, y: t.y, z: t.z - 3 };
414
+ const dir = { x: 0, y: 0, z: 1 };
415
+ equal(phys.castRayFixed(from, dir, 3.5)?.actorId, id, `${when}: castRayFixed meets ${id}`);
416
+ equal(phys.castBallFixed(from, dir, 3.5, 0.2)?.actorId, id, `${when}: castBallFixed meets ${id}`);
417
+ ok(phys.nearFixed(at, 0.5).some((found) => found.actorId === id), `${when}: nearFixed finds ${id}`);
418
+ }
419
+ };
420
+ ask('settled');
421
+ for (let i = 0; i < 30; i++) frame(side);
422
+ ok(settled(side) && adoptedBy(side.system.stillKeeper), 'still settled thirty frames on');
423
+ ask('thirty settled frames on');
424
+ // One touched and moved is found where it now is.
425
+ side.runtime.touch('s-box-0');
426
+ side.runtime.getActor('s-box-0').components.Transform.x += 20;
427
+ frame(side);
428
+ frame(side);
429
+ ask('after a touch');
430
+ }
431
+
432
+ // The marked actors really are left alone: a write with no touch is not
433
+ // followed, a touch makes the actor ordinary from that frame, and the audit
434
+ // finds a write that had none.
435
+ async function touchAndAudit() {
436
+ const pair = await makePair();
437
+ const { on } = pair;
438
+ const warned = [];
439
+ const warn = console.warn;
440
+ console.warn = (text) => warned.push(text);
441
+ try {
442
+ // No touch: not followed, in the scene that asked.
443
+ on.runtime.getActor('s-box-0').components.Transform.x += 5;
444
+ frame(on);
445
+ equal(nodeOf(on, 's-box-0').position.x, 0, 'a still actor written without a touch is not followed');
446
+ ok(settled(on), 'and nothing noticed');
447
+ // The audit does notice, says what, and touches it.
448
+ on.world.auditStatic = Infinity;
449
+ frame(on);
450
+ equal(on.world.staticAuditFailures?.map((f) => f.id), ['s-box-0'], 'the audit finds it');
451
+ ok(/Transform/.test(on.world.staticAuditFailures[0].what) && warned.length === 1 && warned[0].includes('s-box-0'), 'and says what');
452
+ ok(!stillIds(on).includes('s-box-0'), 'and touches it');
453
+ frame(on);
454
+ equal(nodeOf(on, 's-box-0').position.x, 5, 'so it is followed from then on');
455
+ // A node posed from outside, an object under one, a component the node or
456
+ // the body is built from.
457
+ on.world.staticAuditFailures.length = 0;
458
+ for (let i = 0; i < 3; i++) frame(on);
459
+ ok(settled(on), 'settled again');
460
+ nodeOf(on, 's-box-1').position.y += 1;
461
+ nodeOf(on, 's-barrel-1').children[0].scale.x = 2;
462
+ on.runtime.getActor('s-box-2').components.Shape.color = '#00ff00';
463
+ on.runtime.getActor('s-rock-1').components.Solid = {};
464
+ frame(on);
465
+ const found = Object.fromEntries(on.world.staticAuditFailures.map((f) => [f.id, f.what]));
466
+ equal(Object.keys(found).sort(), ['s-barrel-1', 's-box-1', 's-box-2', 's-rock-1'], 'the audit finds each kind of write');
467
+ ok(/where it is/.test(found['s-box-1']) && /under it/.test(found['s-barrel-1']) && /(built|made) from/.test(found['s-box-2']) && /body is made from/.test(found['s-rock-1']), JSON.stringify(found));
468
+ // A clean scene audits clean.
469
+ on.world.staticAuditFailures.length = 0;
470
+ for (let i = 0; i < 6; i++) frame(on);
471
+ equal(on.world.staticAuditFailures, [], 'with nothing written the audit finds nothing');
472
+ ok(settled(on) && frozen(on).length > 0);
473
+ } finally {
474
+ console.warn = warn;
475
+ }
476
+ }
477
+
478
+ //
479
+ // Writers
480
+ //
481
+
482
+ async function importHub() {
483
+ const file = path.join(REPO, 'kits/hub-game/code/systems/hub.js');
484
+ if (!fs.existsSync(file)) return null;
485
+ const { installSystem } = await import(file);
486
+ const state = await import(path.join(REPO, 'kits/hub-game/code/client/state.js'));
487
+ const make = () => {
488
+ let system = null;
489
+ installSystem({ registerSystem: (made) => (system = made) });
490
+ return system;
491
+ };
492
+ return { hub: state.hub, make };
493
+ }
494
+
495
+ async function writers() {
496
+ const pair = await makePair();
497
+ const { on } = pair;
498
+ const touched = (side, id, write) => {
499
+ side.runtime.touch(id);
500
+ write(side.runtime.getActor(id));
501
+ };
502
+ // Each is checked on the frame of the write and the three after.
503
+ both(pair, 'a touch and a Transform written', (side) => touched(side, 's-barrel-0', (a) => Object.assign(a.components.Transform, { x: 7, y: 1, rotationY: 80 })));
504
+ ok(!stillIds(on).includes('s-barrel-0') && settled(on), 'a touched actor is not still; the rest are settled again');
505
+ ok(!isFrozen(nodeOf(on, 's-barrel-0')) && isFrozen(nodeOf(on, 's-barrel-1')));
506
+ both(pair, 'a Shape written in place', (side) => touched(side, 's-box-0', (a) => (a.components.Shape.color = '#ff00ff')));
507
+ both(pair, 'a component added', (side) => touched(side, 's-rock-0', (a) => (a.components.Solid = {})));
508
+ both(pair, 'a component removed', (side) => touched(side, 's-barrel-2', (a) => delete a.components.Solid));
509
+ both(pair, 'a Model put on another file', (side) => touched(side, 's-rock-1', (a) => (a.components.Model.file = TREE)));
510
+ both(pair, 'a touched actor moved every frame', (side) => side.runtime.touch('s-box-1'));
511
+ play(pair, 5, 'moved every frame', (side) => (side.runtime.getActor('s-box-1').components.Transform.z += 0.1));
512
+ both(pair, 'a still actor despawned', (side) => side.runtime.despawnActor('s-barrel-3'));
513
+ ok(!on.world.nodes.has('s-barrel-3') && !on.system.bodies.has('s-barrel-3'), 'its node and its body are gone');
514
+ both(pair, 'an actor spawned', (side) => side.runtime.spawnActor({ id: 'spawned', static: true, components: { Transform: at(0, -4), Shape: box('#11aa55'), Solid: {} } }));
515
+ ok(!stillIds(on).includes('spawned'), 'a spawned actor is never still, marked or not');
516
+ both(pair, 'a live actor despawned', (side) => side.runtime.despawnActor('l-counter'));
517
+ ok(settled(on), 'and the scenery settles again');
518
+
519
+ // scene.physics3d.
520
+ both(pair, 'physics3d.setVelocity', (side) => side.runtime.physics3d.setVelocity(side.runtime.getActor('s-box-2'), { x: 0, y: 0, z: 0 }));
521
+ ok(!stillIds(on).includes('s-box-2'), 'an actor handed to scene.physics3d is touched');
522
+ ok(stillIds(on).includes('s-box-3') && Boolean(on.runtime.physics3d.bodyOf('s-box-3')) && stillIds(on).includes('s-box-3'), 'asking for a body is not a touch');
523
+
524
+ // multiplayer-3d's network pose: the system touches, then writes with this.
525
+ const { applyPose } = await import(path.join(REPO, 'kits/multiplayer-3d/code/client/poses.js')).catch(() => ({ applyPose: null }));
526
+ if (applyPose) {
527
+ both(pair, 'a network pose', (side) => {
528
+ side.runtime.touch('s-tree');
529
+ applyPose(side.runtime.getActor('s-tree').components.Transform, [41, 0.5, 2, 0, 0.3826834, 0, 0.9238795]);
530
+ });
531
+ }
532
+
533
+ // hub-game: the place hides, shows and tints, through the real system.
534
+ const Hub = await importHub();
535
+ if (Hub) {
536
+ const systems = { off: Hub.make(), on: Hub.make() };
537
+ const apply = (side) => {
538
+ const system = systems[side.keyed ? 'on' : 'off'];
539
+ system.applyVisibility(side.runtime);
540
+ system.applyTints(side.runtime);
541
+ };
542
+ const each = (side) => apply(side);
543
+ Hub.hub.hidden = new Set(['s-barrel-4']);
544
+ Hub.hub.tints = { 's-box-3': '#ff8800', 'l-lamp': '#00ffcc' };
545
+ play(pair, 4, 'hub.hide and hub.tint', each);
546
+ ok(on.runtime.getActor('s-barrel-4').components.Transform.y < -100 && nodeOf(on, 's-barrel-4').position.y < -100, 'the hidden actor is dropped out of sight, node and all');
547
+ equal(on.runtime.getActor('s-box-3').components.Shape.color, '#ff8800');
548
+ ok(!stillIds(on).includes('s-barrel-4') && !stillIds(on).includes('s-box-3'), 'hub-game touched what it wrote');
549
+ Hub.hub.hidden = new Set();
550
+ Hub.hub.tints = { 'l-lamp': '#00ffcc' };
551
+ play(pair, 4, 'hub.show and the tint taken off', each);
552
+ equal(nodeOf(on, 's-barrel-4').position.y, 0, 'shown again where it was');
553
+ Hub.hub.tints = {};
554
+ }
555
+
556
+ // The behaviour classes change: one a still actor has gains an `update`.
557
+ ok(stillIds(on).includes('s-late'));
558
+ both(pair, 'setBehaviors', (side) => side.runtime.setBehaviors(classesWith(true)), 5);
559
+ ok(!stillIds(on).includes('s-late') && log.some((line) => line === 'on Late s-late'), 'the actor whose class now updates is run');
560
+ both(pair, 'setBehaviors back', (side) => side.runtime.setBehaviors(classesWith(false)), 3);
561
+ ok(stillIds(on).includes('s-late'), 'and is still again when it no longer does');
562
+ ok(!stillIds(on).includes('s-barrel-0'), 'but nothing touched comes back');
563
+ return Boolean(Hub);
564
+ }
565
+
566
+ // What still actors share is watched for them.
567
+ async function sharedInputs() {
568
+ const pair = await makePair();
569
+ const { on } = pair;
570
+ // Audited throughout: none of this is a still actor changed with no touch.
571
+ on.world.auditStatic = Infinity;
572
+ both(pair, 'a model file edited', (side) => (side.files[BARREL] = side.files[BARREL].replace('"parts"', '"triangles":900,"parts"')));
573
+ ok(settled(on) && stillIds(on).includes('s-barrel-0'), 'followed with no touch, and settled again');
574
+ both(pair, 'the look switched off', () => setLookEnabled(false));
575
+ both(pair, 'the look switched on', () => setLookEnabled(true));
576
+ // The scene itself moved: before a pass, and between a pass and its draw.
577
+ both(pair, 'the scene moved', (side) => side.world.scene.position.set(3, 0, -2));
578
+ for (const side of [pair.off, pair.on]) {
579
+ side.runtime.update(DT);
580
+ syncActors(side.world, side.runtime, {}, DT);
581
+ side.world.scene.rotation.y = 0.4;
582
+ renderWorld(side.world, side.runtime);
583
+ }
584
+ same(pair, 'the scene turned after the pass and before the draw');
585
+ play(pair, 3, 'and after');
586
+ ok(settled(on) && frozen(on).length === STILL.length - 1, 'settled again under the moved scene');
587
+ equal(on.world.staticAuditFailures ?? [], [], 'and the audit found no fault in any of it');
588
+ }
589
+
590
+ //
591
+ // hub-game's levers
592
+ //
593
+
594
+ async function levers() {
595
+ const file = path.join(REPO, 'kits/hub-game/code/client/tiers.js');
596
+ if (!fs.existsSync(file)) return false;
597
+ const { makeLevers } = await import(file);
598
+ const pair = await makePair();
599
+ const { on, off } = pair;
600
+ const lv = { off: makeLevers(), on: makeLevers() };
601
+ let now = 0;
602
+ const camera = (x) => {
603
+ for (const side of [off, on]) side.world.camera.position.set(x, 2, 0);
604
+ };
605
+ const apply = (side) => {
606
+ const scene = { scenePath: side.runtime.scenePath, data: side.runtime.data, readFromFile: () => side.data, getActor: (id) => side.runtime.getActor(id) };
607
+ lv[side.keyed ? 'on' : 'off'].apply(side.world, scene, now);
608
+ };
609
+ const run = (frames, what) => {
610
+ for (let i = 0; i < frames; i++) {
611
+ now += 600;
612
+ for (const side of [off, on]) {
613
+ apply(side);
614
+ frame(side);
615
+ }
616
+ same(pair, `${what}, frame ${i}`);
617
+ }
618
+ };
619
+ const out = (side) => [...side.world.nodes].filter(([, entry]) => entry.node.parent !== side.world.scene).map(([id]) => id);
620
+ camera(-200);
621
+ run(3, 'the low picture, everything far');
622
+ ok(out(on).includes('s-barrel-0') && out(on).includes('s-tree'), 'far scenery is out of the scene');
623
+ equal(out(on), out(off), 'the same nodes with the key');
624
+ const t = on.runtime.getActor('s-tree').components.Transform;
625
+ equal(nodeOf(on, 's-tree').position.toArray(), [t.x, t.y, t.z], "a node that is out still has its actor's place, which the levers read");
626
+ // Walking up to it: frozen nodes come back, drawn where they were.
627
+ camera(0);
628
+ run(3, 'the camera among the barrels');
629
+ ok(!out(on).includes('s-barrel-0') && isFrozen(nodeOf(on, 's-barrel-0')), 'a node put back is in the scene and frozen');
630
+ ok(out(on).includes('s-tree'), 'and the far ones are still out');
631
+ // Something thaws the world while a node is out; it comes back right.
632
+ for (const side of [off, on]) {
633
+ side.runtime.touch('s-barrel-5');
634
+ side.runtime.getActor('s-barrel-5').components.Transform.z = 1.5;
635
+ // And an actor is touched and moved while its own node is out.
636
+ side.runtime.touch('s-tree');
637
+ side.runtime.getActor('s-tree').components.Transform.x = 12;
638
+ }
639
+ run(2, 'a touch while nodes are out');
640
+ camera(40);
641
+ run(3, 'the camera by the tree');
642
+ ok(!out(on).includes('s-tree') && nodeOf(on, 's-tree').position.x === 12, 'the moved actor comes back where it now is');
643
+ camera(0);
644
+ run(3, 'and back');
645
+ for (const side of [off, on]) lv[side.keyed ? 'on' : 'off'].restore(side.world);
646
+ play(pair, 3, 'the levers put everything back');
647
+ equal(out(on), [], 'every node is in the scene');
648
+ ok(settled(on));
649
+ return true;
650
+ }
651
+
652
+ //
653
+ // Scenes, worlds, passes
654
+ //
655
+
656
+ // A second scene for the same world: other actors under the same ids.
657
+ function otherData(keyed) {
658
+ const actors = sceneActors().filter((a) => !/^(m-body|l-door)$/.test(a.id));
659
+ for (const actor of actors) if (actor.components.Transform) actor.components.Transform.z += 30;
660
+ return { name: 'Other', ground: { color: '#445566' }, engine: engineOf(keyed), actors };
661
+ }
662
+
663
+ async function scenes() {
664
+ // One runtime loading a scene that does not ask, then the one that does.
665
+ for (const resident of [false, true]) {
666
+ const pair = await makePair();
667
+ const { on } = pair;
668
+ const load = (side, data, scenePath) => {
669
+ if (resident) side.runtime.residentScenes = new Set(['scenes/main.scene', 'scenes/other.scene']);
670
+ side.runtime.scenePath = scenePath;
671
+ side.runtime.load(structuredClone(data));
672
+ };
673
+ const what = resident ? 'a door trip, the first scene resident' : 'one scene after another';
674
+ both(pair, `${what}: a scene that does not ask`, (side) => load(side, otherData(false), 'scenes/other.scene'), 5);
675
+ ok(!adoptedBy(on.world.stillKeeper) && on.runtime.stillActors === null && frozen(on).length === 0 && !adoptedBy(on.system.stillKeeper), 'nothing is held still in it');
676
+ both(pair, `${what}: and back`, (side) => load(side, side.data, 'scenes/main.scene'), 6);
677
+ ok(settled(on) && frozen(on).length === STILL.length - 1 && adoptedBy(on.system.stillKeeper)?.bodies === STILL.length - 1, 'the first scene settles again');
678
+ both(pair, `${what}: a scene that asks too`, (side) => load(side, otherData(side.keyed), 'scenes/other.scene'), 6);
679
+ ok(settled(on) && frozen(on).length > 0);
680
+ both(pair, `${what}: and back again`, (side) => load(side, side.data, 'scenes/main.scene'), 6);
681
+ ok(settled(on));
682
+ }
683
+ // Two runtimes turn about on one world: each pass is the runtime's own.
684
+ const pair = await makePair();
685
+ const others = {};
686
+ for (const side of [pair.off, pair.on]) {
687
+ const runtime = new SceneRuntime(otherData(false), classesWith(), {}, side.files, 'scenes/main.scene');
688
+ runtime.tag = side.keyed ? 'on' : 'off';
689
+ others[side.keyed ? 'on' : 'off'] = runtime;
690
+ }
691
+ for (let i = 0; i < 6; i++) {
692
+ for (const side of [pair.off, pair.on]) frame(side);
693
+ same(pair, `turn about: the scene that asks, round ${i}`);
694
+ for (const side of [pair.off, pair.on]) {
695
+ const other = others[side.keyed ? 'on' : 'off'];
696
+ syncActors(side.world, other, {}, DT);
697
+ renderWorld(side.world, other);
698
+ }
699
+ equal(drawn(pair.on.world), drawn(pair.off.world), `turn about: the one that does not, round ${i}`);
700
+ ok(!adoptedBy(pair.on.world.stillKeeper), 'a pass of another runtime leaves nothing adopted');
701
+ }
702
+ }
703
+
704
+ // A settled pass stops being alone part way: a live actor's node is built, and
705
+ // a listener told of it syncs another scene, built the other way, in the same
706
+ // world. Every actor the interrupted pass has not yet passed is placed as
707
+ // `syncActors` places it, still ones included, on that frame.
708
+ async function insideAPass() {
709
+ for (const outerKeyed of [true, false]) {
710
+ for (const throws of [false, true]) {
711
+ const what = `a pass of a scene that ${outerKeyed ? 'asks' : 'does not ask'}, entered by one that ${outerKeyed ? 'does not' : 'does'}${throws ? ', which throws' : ''}`;
712
+ // `on` is the pair's keyed side where the keys are as named; `off` plays
713
+ // the same two scenes with no key anywhere.
714
+ // The lamp, which is not still, comes first: what interrupts the pass
715
+ // happens before any still actor has been passed.
716
+ const lampFirst = () => {
717
+ const actors = sceneActors();
718
+ return [...actors.filter((a) => a.id === 'l-lamp'), ...actors.filter((a) => a.id !== 'l-lamp')];
719
+ };
720
+ const pair = await makePair({ actors: lampFirst() });
721
+ const sides = [pair.off, pair.on];
722
+ const inner = {};
723
+ const outer = {};
724
+ for (const side of sides) {
725
+ const tag = side.keyed ? 'on' : 'off';
726
+ const make = (data) => {
727
+ const runtime = new SceneRuntime(data, classesWith(), {}, side.files, 'scenes/inner.scene');
728
+ runtime.tag = tag;
729
+ return runtime;
730
+ };
731
+ if (outerKeyed) {
732
+ outer[tag] = side.runtime;
733
+ inner[tag] = make(otherData(false));
734
+ } else {
735
+ // The outer scene does not ask; the inner one does (on the keyed side).
736
+ side.runtime.load({ ...structuredClone(side.runtime.data), engine: engineOf(false) });
737
+ outer[tag] = side.runtime;
738
+ inner[tag] = make(otherData(side.keyed));
739
+ }
740
+ }
741
+ for (let i = 0; i < 6; i++) for (const side of sides) frame(side);
742
+ if (outerKeyed) ok(settled(pair.on), `${what}: settled before`);
743
+ const results = {};
744
+ for (const side of sides) {
745
+ const tag = side.keyed ? 'on' : 'off';
746
+ let entered = 0;
747
+ const listener = () => {
748
+ if (entered++ > 0) return;
749
+ syncActors(side.world, inner[tag], {}, DT);
750
+ if (throws) throw new Error('from the listener');
751
+ };
752
+ // The lamp's colour written (it is not still, so with no touch): its
753
+ // node is built again in this pass, and the scene tells the listener.
754
+ side.runtime.getActor('l-lamp').components.Shape.color = '#ee2244';
755
+ side.runtime.update(DT);
756
+ side.world.scene.addEventListener('childadded', listener);
757
+ try {
758
+ syncActors(side.world, outer[tag], {}, DT);
759
+ results[tag] = 'returned';
760
+ } catch (error) {
761
+ if (error instanceof assert.AssertionError) throw error;
762
+ results[tag] = `threw ${error.message}`;
763
+ } finally {
764
+ side.world.scene.removeEventListener('childadded', listener);
765
+ }
766
+ ok(entered > 0, `${what}: the listener ran`);
767
+ ok(!adoptedBy(side.world.stillKeeper), `${what}: nothing is left adopted`);
768
+ renderWorld(side.world, outer[tag]);
769
+ }
770
+ equal(results.on, results.off, `${what}: ended the same way`);
771
+ same(pair, `${what}: the interrupted pass's own frame`);
772
+ play(pair, 5, `${what}: the frames after`);
773
+ if (outerKeyed) ok(settled(pair.on) && frozen(pair.on).length > 0, `${what}: and settles again`);
774
+ }
775
+ }
776
+ }
777
+
778
+ //
779
+ // Interruptions
780
+ //
781
+
782
+ // What a still actor's node, and a live one's, read as right now.
783
+ function glimpse(side) {
784
+ side.world.scene.updateMatrixWorld();
785
+ return ['s-barrel-1', 's-box-1', 's-tree', 'l-lamp'].map((id) => {
786
+ const entry = side.world.nodes.get(id);
787
+ return entry ? `${id} ${entry.node.parent === side.world.scene} ${Array.from(entry.node.matrixWorld.elements).join(',')}` : `${id} none`;
788
+ });
789
+ }
790
+
791
+ // What code that is not the engine's may do to the scene from inside a pass.
792
+ const REENTRIES = {
793
+ 'walks the scene': () => {},
794
+ 'draws it': (side) => renderWorld(side.world, side.runtime),
795
+ 'syncs it': (side) => syncActors(side.world, side.runtime, {}, DT),
796
+ 'updates it': (side) => side.runtime.update(DT),
797
+ };
798
+
799
+ // The two sides brought to a pass that will be settled (only a live actor's
800
+ // look has changed) or ordinary (the scene itself moved, a still actor
801
+ // touched and moved as well).
802
+ function before(side, kind) {
803
+ side.runtime.getActor('l-lamp').components.Shape.color = kind === 'settled' ? '#11ee22' : '#ee2211';
804
+ if (kind === 'settled') return;
805
+ side.world.scene.position.set(7, 0, 0);
806
+ side.runtime.touch('s-box-1');
807
+ side.runtime.getActor('s-box-1').components.Transform.x += 2;
808
+ }
809
+
810
+ function leftOrdinary(side, what) {
811
+ ok(!adoptedBy(side.world.stillKeeper) && frozen(side).length === 0, `${what}: nothing is adopted or frozen in the world`);
812
+ }
813
+
814
+ async function interruptions() {
815
+ // A node listener, told of a live actor's node built in the pass.
816
+ for (const kind of ['settled', 'ordinary']) {
817
+ for (const [does, reenter] of Object.entries(REENTRIES)) {
818
+ for (const throws of [false, true]) {
819
+ const what = `a listener ${does} from inside a pass that began ${kind}${throws ? ', and throws' : ''}`;
820
+ const pair = await makePair();
821
+ const seen = {};
822
+ const ended = {};
823
+ for (const side of [pair.off, pair.on]) {
824
+ const tag = side.keyed ? 'on' : 'off';
825
+ before(side, kind);
826
+ side.runtime.update(DT);
827
+ if (side.keyed && kind === 'settled') ok(settled(side), `${what}: settled until then`);
828
+ let entered = 0;
829
+ const listener = () => {
830
+ if (entered++ > 0) return;
831
+ reenter(side);
832
+ seen[tag] = glimpse(side);
833
+ if (side.keyed) ok(frozen(side).length === 0, `${what}: nothing is frozen while it runs`);
834
+ if (throws) throw new Error('from the listener');
835
+ };
836
+ side.world.scene.addEventListener('childadded', listener);
837
+ try {
838
+ syncActors(side.world, side.runtime, {}, DT);
839
+ ended[tag] = 'returned';
840
+ } catch (error) {
841
+ if (error instanceof assert.AssertionError) throw error;
842
+ ended[tag] = `threw ${error.message}`;
843
+ } finally {
844
+ side.world.scene.removeEventListener('childadded', listener);
845
+ }
846
+ ok(entered > 0, `${what}: the listener ran`);
847
+ leftOrdinary(side, what);
848
+ renderWorld(side.world, side.runtime);
849
+ }
850
+ equal(seen.on, seen.off, `${what}: what it saw`);
851
+ equal(ended.on, ended.off, `${what}: how the pass ended`);
852
+ same(pair, `${what}: the frame`);
853
+ play(pair, 5, `${what}: the frames after`);
854
+ ok(settled(pair.on) && frozen(pair.on).length > 0, `${what}: settled again`);
855
+ }
856
+ }
857
+ }
858
+
859
+ // A behaviour, from inside the update loop.
860
+ for (const kind of ['settled', 'ordinary']) {
861
+ for (const [does, reenter] of Object.entries(REENTRIES)) {
862
+ if (does === 'updates it') continue; // physics-2d's own test plays an update inside an update
863
+ for (const throws of [false, true]) {
864
+ const what = `a behaviour ${does} from inside an update that began ${kind}${throws ? ', and throws' : ''}`;
865
+ const pair = await makePair();
866
+ const seen = {};
867
+ const ended = {};
868
+ for (const side of [pair.off, pair.on]) {
869
+ const tag = side.keyed ? 'on' : 'off';
870
+ before(side, kind);
871
+ let entered = 0;
872
+ side.runtime.fromUpdate = () => {
873
+ if (entered++ > 0) return;
874
+ reenter(side);
875
+ seen[tag] = glimpse(side);
876
+ if (throws) throw new Error('from the behaviour');
877
+ };
878
+ try {
879
+ side.runtime.update(DT);
880
+ ended[tag] = 'returned';
881
+ } catch (error) {
882
+ if (error instanceof assert.AssertionError) throw error;
883
+ ended[tag] = `threw ${error.message}`;
884
+ }
885
+ side.runtime.fromUpdate = null;
886
+ ok(entered > 0, `${what}: the behaviour ran`);
887
+ syncActors(side.world, side.runtime, {}, DT);
888
+ renderWorld(side.world, side.runtime);
889
+ }
890
+ equal(seen.on, seen.off, `${what}: what it saw`);
891
+ equal(ended.on, ended.off, `${what}: how the update ended`);
892
+ same(pair, `${what}: the frame`);
893
+ play(pair, 5, `${what}: the frames after`);
894
+ ok(settled(pair.on) && adoptedBy(pair.on.system.stillKeeper), `${what}: settled again`);
895
+ }
896
+ }
897
+ }
898
+
899
+ // The physics pass: rapier's step throws; a collision callback throws; a
900
+ // collision callback updates the scene.
901
+ const faults = {
902
+ "rapier's step throws": (side, state) => {
903
+ const step = side.system.world.step;
904
+ side.system.world.step = function () {
905
+ side.system.world.step = step;
906
+ state.ran = true;
907
+ throw new Error('from the step');
908
+ };
909
+ },
910
+ 'a collision callback throws': (side, state) => {
911
+ side.system.dispatchCallbacks = function (scene) {
912
+ delete side.system.dispatchCallbacks;
913
+ this.dispatchCallbacks(scene);
914
+ state.ran = true;
915
+ throw new Error('from a collision callback');
916
+ };
917
+ },
918
+ 'a collision callback updates the scene': (side, state) => {
919
+ side.system.dispatchCallbacks = function (scene) {
920
+ delete side.system.dispatchCallbacks;
921
+ this.dispatchCallbacks(scene);
922
+ state.ran = true;
923
+ state.stillInside = Boolean(adoptedBy(side.system.stillKeeper));
924
+ scene.update(DT);
925
+ state.stillAfterInner = Boolean(adoptedBy(side.system.stillKeeper));
926
+ };
927
+ },
928
+ 'a collision callback updates the scene, and throws': (side, state) => {
929
+ side.system.dispatchCallbacks = function (scene) {
930
+ delete side.system.dispatchCallbacks;
931
+ this.dispatchCallbacks(scene);
932
+ state.ran = true;
933
+ scene.update(DT);
934
+ throw new Error('from a collision callback');
935
+ };
936
+ },
937
+ };
938
+ for (const kind of ['settled', 'ordinary']) {
939
+ for (const [fault, arm] of Object.entries(faults)) {
940
+ const what = `${fault}, in a physics pass that began ${kind}`;
941
+ const pair = await makePair();
942
+ const ended = {};
943
+ for (const side of [pair.off, pair.on]) {
944
+ const tag = side.keyed ? 'on' : 'off';
945
+ const state = {};
946
+ before(side, kind);
947
+ if (side.keyed && kind === 'settled') ok(Boolean(adoptedBy(side.system.stillKeeper)), `${what}: the bodies are adopted until then`);
948
+ arm(side, state);
949
+ try {
950
+ side.runtime.update(DT);
951
+ ended[tag] = 'returned';
952
+ } catch (error) {
953
+ if (error instanceof assert.AssertionError) throw error;
954
+ ended[tag] = `threw ${error.message}`;
955
+ }
956
+ ok(state.ran, `${what}: it happened`);
957
+ if (side.keyed) {
958
+ if (ended[tag] !== 'returned') ok(!adoptedBy(side.system.stillKeeper), `${what}: nothing is adopted after a throw`);
959
+ if ('stillInside' in state) ok(!state.stillInside && !state.stillAfterInner, `${what}: nothing is adopted while the pass runs, nor by the pass inside it`);
960
+ }
961
+ syncActors(side.world, side.runtime, {}, DT);
962
+ renderWorld(side.world, side.runtime);
963
+ }
964
+ equal(ended.on, ended.off, `${what}: how the update ended`);
965
+ same(pair, `${what}: the frame`);
966
+ play(pair, 5, `${what}: the frames after`);
967
+ ok(settled(pair.on) && adoptedBy(pair.on.system.stillKeeper)?.bodies > 0, `${what}: settled again`);
968
+ }
969
+ }
970
+
971
+ // An ordinary pass that calls nothing out: nothing is adopted or frozen
972
+ // from before its first actor. (The pass asks the runtime for its actors
973
+ // just before the first; that is where this looks.)
974
+ {
975
+ const pair = await makePair();
976
+ const { on } = pair;
977
+ ok(settled(on) && frozen(on).length > 0);
978
+ const looks = [];
979
+ const getActors = on.runtime.getActors.bind(on.runtime);
980
+ let inSync = false;
981
+ on.runtime.getActors = () => {
982
+ if (inSync) looks.push([on.world.stillKeeper.adopted !== null, frozen(on).length]);
983
+ return getActors();
984
+ };
985
+ const pass = () => {
986
+ on.runtime.update(DT);
987
+ inSync = true;
988
+ syncActors(on.world, on.runtime, {}, DT);
989
+ inSync = false;
990
+ renderWorld(on.world, on.runtime);
991
+ };
992
+ pass();
993
+ equal(looks.pop(), [true, STILL.length - 1], 'a settled pass runs with the set adopted');
994
+ on.runtime.touch('s-box-2');
995
+ pass();
996
+ equal(looks.pop(), [false, 0], 'an ordinary pass begins with nothing adopted and nothing frozen');
997
+ delete on.runtime.getActors;
998
+ }
999
+
1000
+ // A touch thaws at once: an actor touched and then posed by its node is
1001
+ // drawn posed by the next draw, and walked posed by the next walk, with no
1002
+ // pass in between; so is every other still actor's node, from then on.
1003
+ for (const [does, look] of Object.entries({ 'drawn': (side) => renderWorld(side.world, side.runtime), 'walked': (side) => side.world.scene.updateMatrixWorld() })) {
1004
+ const pair = await makePair();
1005
+ const seen = {};
1006
+ for (const side of [pair.off, pair.on]) {
1007
+ side.runtime.touch('s-box-1');
1008
+ nodeOf(side, 's-box-1').position.y += 1.5;
1009
+ nodeOf(side, 's-barrel-1').children[0].rotation.y = 0.4; // not touched: outside the terms, and followed all the same once anything is
1010
+ look(side);
1011
+ seen[side.keyed ? 'on' : 'off'] = glimpse(side);
1012
+ }
1013
+ equal(seen.on, seen.off, `touched, posed and ${does}, with no pass in between`);
1014
+ ok(frozen(pair.on).length === 0, 'a touch thaws every node');
1015
+ play(pair, 4, `touched, posed and ${does}: the frames after`);
1016
+ }
1017
+
1018
+ // A frozen node put under another parent by its deck is computed there.
1019
+ {
1020
+ const pair = await makePair();
1021
+ const seen = {};
1022
+ for (const side of [pair.off, pair.on]) {
1023
+ const holder = new side.world.scene.constructor();
1024
+ holder.position.set(0, 4, 0);
1025
+ side.world.scene.add(holder);
1026
+ holder.add(nodeOf(side, 's-barrel-1'));
1027
+ side.world.scene.updateMatrixWorld();
1028
+ seen[side.keyed ? 'on' : 'off'] = glimpse(side);
1029
+ }
1030
+ equal(seen.on, seen.off, 'a frozen node moved under another parent');
1031
+ }
1032
+
1033
+ // The scene's own matrix, written every way three.js reads it, between a
1034
+ // pass and its draw: whatever the draw will make of it is what is asked.
1035
+ const rootWrites = {
1036
+ 'its position': (scene) => scene.position.set(5, 0, 0),
1037
+ 'its local matrix by hand, with matrixAutoUpdate off': (scene) => {
1038
+ scene.matrixAutoUpdate = false;
1039
+ scene.matrix.makeTranslation(5, 0, 0);
1040
+ scene.matrixWorldNeedsUpdate = true;
1041
+ },
1042
+ 'its local matrix by hand, without the flag (three.js leaves the world matrix as it is)': (scene) => {
1043
+ scene.matrixAutoUpdate = false;
1044
+ scene.matrix.makeTranslation(5, 0, 0);
1045
+ },
1046
+ 'its world matrix by hand, with every update off': (scene) => {
1047
+ scene.matrixAutoUpdate = false;
1048
+ scene.matrixWorldAutoUpdate = false;
1049
+ scene.matrixWorld.makeTranslation(0, 3, 0);
1050
+ },
1051
+ 'a parent given to it, moved': (scene) => {
1052
+ const parent = new scene.constructor();
1053
+ parent.position.set(0, 0, 4);
1054
+ parent.updateMatrixWorld();
1055
+ parent.add(scene);
1056
+ },
1057
+ };
1058
+ for (const [what, write] of Object.entries(rootWrites)) {
1059
+ for (const when of ['before the pass', 'between the pass and the draw']) {
1060
+ const pair = await makePair();
1061
+ for (const side of [pair.off, pair.on]) {
1062
+ if (when === 'before the pass') write(side.world.scene);
1063
+ side.runtime.update(DT);
1064
+ syncActors(side.world, side.runtime, {}, DT);
1065
+ if (when !== 'before the pass') write(side.world.scene);
1066
+ // The draw, as three.js's renderer does it to the scene.
1067
+ side.world.composer = { render: () => side.world.scene.matrixWorldAutoUpdate === true && side.world.scene.updateMatrixWorld() };
1068
+ renderWorld(side.world, side.runtime);
1069
+ }
1070
+ same(pair, `the scene moved by ${what}, ${when}`);
1071
+ for (let i = 0; i < 4; i++) {
1072
+ for (const side of [pair.off, pair.on]) {
1073
+ side.runtime.update(DT);
1074
+ syncActors(side.world, side.runtime, {}, DT);
1075
+ renderWorld(side.world, side.runtime);
1076
+ }
1077
+ same(pair, `the scene moved by ${what}, ${when}: frame ${i} after`);
1078
+ }
1079
+ }
1080
+ }
1081
+ }
1082
+
1083
+ //
1084
+ // Every interruption, enumerated
1085
+ //
1086
+
1087
+ // For the world's pass and the physics pass (physics-2d's own test does the
1088
+ // runtime's update): a pass that began settled and one that began ordinary,
1089
+ // each interrupted every way a pass can be. After each, the system has
1090
+ // nothing adopted, and its next pass is ordinary and visits every actor (a
1091
+ // still actor's Transform written with no touch is followed by it, which
1092
+ // only an ordinary pass does).
1093
+ const anotherRuntime = (side, change = (data) => data) => {
1094
+ const data = change(structuredClone(side.data));
1095
+ const runtime = new SceneRuntime(data, classesWith(), {}, side.files, 'scenes/main.scene');
1096
+ runtime.tag = 'another';
1097
+ return runtime;
1098
+ };
1099
+
1100
+ function once(target, event, act) {
1101
+ let ran = 0;
1102
+ const listener = () => {
1103
+ if (ran++ > 0) return;
1104
+ target.removeEventListener(event, listener);
1105
+ act();
1106
+ };
1107
+ target.addEventListener(event, listener);
1108
+ return () => {
1109
+ target.removeEventListener(event, listener);
1110
+ return ran > 0;
1111
+ };
1112
+ }
1113
+
1114
+ const worldInterruptions = {
1115
+ // The lamp's look has changed: its node is built in the loop, and the
1116
+ // scene tells a listener.
1117
+ 'throws in the loop (a listener, as a node is built)': (side) =>
1118
+ once(side.world.scene, 'childadded', () => {
1119
+ throw new Error('in the loop');
1120
+ }),
1121
+ // A live actor is gone: its node is released after the loop.
1122
+ 'throws in a later stage (a listener, as a node is released after the loop)': (side) => {
1123
+ side.runtime.getActor('l-lamp').components.Shape.color = lampColor(side);
1124
+ side.runtime.despawnActor('l-counter');
1125
+ return once(side.world.scene, 'childremoved', () => {
1126
+ throw new Error('after the loop');
1127
+ });
1128
+ },
1129
+ 're-entered, and the pass inside returns': (side) => once(side.world.scene, 'childadded', () => syncActors(side.world, side.runtime, {}, DT)),
1130
+ 're-entered, and the pass inside throws and is caught': (side) => {
1131
+ const inner = anotherRuntime(side);
1132
+ inner.getActors = () => {
1133
+ throw new Error('inside');
1134
+ };
1135
+ return once(side.world.scene, 'childadded', () => {
1136
+ assert.throws(() => syncActors(side.world, inner, {}, DT), /inside/);
1137
+ });
1138
+ },
1139
+ 're-entered by a different runtime': (side) => {
1140
+ const other = anotherRuntime(side);
1141
+ return once(side.world.scene, 'childadded', () => syncActors(side.world, other, {}, DT));
1142
+ },
1143
+ };
1144
+ const lampColor = (side) => side.authoredLamp ?? (side.authoredLamp = side.runtime.getActor('l-lamp').components.Shape.color);
1145
+
1146
+ const physicsInterruptions = {
1147
+ 'throws in the loop (as a body is looked up)': (side) => {
1148
+ const state = { ran: false };
1149
+ side.system.bodyFor = function () {
1150
+ delete side.system.bodyFor;
1151
+ state.ran = true;
1152
+ throw new Error('in the loop');
1153
+ };
1154
+ return () => state.ran;
1155
+ },
1156
+ "throws in a later stage (rapier's step)": (side) => {
1157
+ const state = { ran: false };
1158
+ const step = side.system.world.step;
1159
+ side.system.world.step = function () {
1160
+ side.system.world.step = step;
1161
+ state.ran = true;
1162
+ throw new Error('in the step');
1163
+ };
1164
+ return () => state.ran;
1165
+ },
1166
+ 're-entered from a collision callback, and the pass inside returns': (side) =>
1167
+ fromCallbacks(side, (system, scene) => {
1168
+ // The pass inside is ordinary whatever the one around it is: it follows
1169
+ // a still actor written with no touch.
1170
+ const t = scene.getActor('s-rock-2').components.Transform;
1171
+ t.z += 5;
1172
+ system.afterBehaviors(scene, DT);
1173
+ equal(system.bodies.get('s-rock-2').body.pos.z, t.z, 'a pass entered from inside another visits every body');
1174
+ scene.touch('s-rock-2');
1175
+ }),
1176
+ // A review's repro: the callback catches what the pass inside threw.
1177
+ 're-entered from a collision callback, and the pass inside throws and is caught': (side) =>
1178
+ fromCallbacks(side, (system, scene) => {
1179
+ const step = system.world.step;
1180
+ system.world.step = function () {
1181
+ system.world.step = step;
1182
+ throw new Error('inside');
1183
+ };
1184
+ assert.throws(() => system.afterBehaviors(scene, DT), /inside/);
1185
+ }),
1186
+ // A review's repro: another runtime's pass, entered from inside this one's
1187
+ // on the same physics system, moves a fixed body from where it stood to x =
1188
+ // 100. The original runtime's next pass must put it back.
1189
+ 're-entered by a different runtime, which moves a still body': (side) => {
1190
+ const other = anotherRuntime(side, (data) => {
1191
+ data.actors.find((a) => a.id === 's-box-3').components.Transform.x = 100;
1192
+ return data;
1193
+ });
1194
+ return fromCallbacks(side, (system) => {
1195
+ system.afterBehaviors(other, DT);
1196
+ equal(system.bodies.get('s-box-3').body.pos.x, 100, 'the other runtime moved the body');
1197
+ });
1198
+ },
1199
+ };
1200
+
1201
+ // Has the system's collision callbacks, once, do `act` after they are dispatched.
1202
+ function fromCallbacks(side, act) {
1203
+ const state = { ran: false };
1204
+ side.system.dispatchCallbacks = function (scene) {
1205
+ delete side.system.dispatchCallbacks;
1206
+ this.dispatchCallbacks(scene);
1207
+ state.ran = true;
1208
+ act(this, scene);
1209
+ };
1210
+ return () => state.ran;
1211
+ }
1212
+
1213
+ async function enumerated() {
1214
+ const rows = [];
1215
+ for (const began of ['settled', 'ordinary']) {
1216
+ for (const [how, arm] of Object.entries(worldInterruptions)) {
1217
+ const what = `the world's pass, begun ${began}: ${how}`;
1218
+ const side = (await makePair()).on;
1219
+ ok(adoptedBy(side.world.stillKeeper) && frozen(side).length > 0, `${what}: settled before`);
1220
+ lampColor(side);
1221
+ side.runtime.getActor('l-lamp').components.Shape.color = '#12ef34';
1222
+ if (began === 'ordinary') side.runtime.touch('s-box-1');
1223
+ side.runtime.update(DT);
1224
+ const ran = arm(side);
1225
+ let ended = 'returned';
1226
+ try {
1227
+ syncActors(side.world, side.runtime, {}, DT);
1228
+ } catch (error) {
1229
+ if (error instanceof assert.AssertionError) throw error;
1230
+ ended = `threw ${error.message}`;
1231
+ }
1232
+ ok(ran(), `${what}: it happened`);
1233
+ equal(adoptedBy(side.world.stillKeeper), null, `${what}: nothing is adopted`);
1234
+ equal(frozen(side).length, 0, `${what}: nothing is frozen`);
1235
+ renderWorld(side.world, side.runtime);
1236
+ // The next pass: ordinary, every actor.
1237
+ const t = side.runtime.getActor('s-box-3').components.Transform;
1238
+ t.x += 9;
1239
+ syncActors(side.world, side.runtime, {}, DT);
1240
+ equal(nodeOf(side, 's-box-3').position.x, t.x, `${what}: the next pass visits every actor`);
1241
+ renderWorld(side.world, side.runtime);
1242
+ side.runtime.touch('s-box-3');
1243
+ for (let i = 0; i < 4; i++) frame(side);
1244
+ ok(adoptedBy(side.world.stillKeeper) && frozen(side).length > 0, `${what}: and settles again`);
1245
+ rows.push(`${what} -> ${ended}; next pass ordinary`);
1246
+ }
1247
+ for (const [how, arm] of Object.entries(physicsInterruptions)) {
1248
+ const what = `the physics pass, begun ${began}: ${how}`;
1249
+ const side = (await makePair()).on;
1250
+ ok(adoptedBy(side.system.stillKeeper)?.bodies > 0, `${what}: settled before`);
1251
+ if (began === 'ordinary') side.runtime.touch('s-box-1');
1252
+ const authoredX = side.runtime.getActor('s-box-3').components.Transform.x;
1253
+ const ran = arm(side);
1254
+ let ended = 'returned';
1255
+ try {
1256
+ side.runtime.update(DT);
1257
+ } catch (error) {
1258
+ if (error instanceof assert.AssertionError) throw error;
1259
+ ended = `threw ${error.message}`;
1260
+ }
1261
+ ok(ran(), `${what}: it happened`);
1262
+ equal(adoptedBy(side.system.stillKeeper), null, `${what}: nothing is adopted`);
1263
+ // The next pass: ordinary, every body.
1264
+ const t = side.runtime.getActor('s-box-2').components.Transform;
1265
+ t.x += 9;
1266
+ side.runtime.update(DT);
1267
+ equal(side.system.bodies.get('s-box-2').body.pos.x, t.x, `${what}: the next pass visits every body`);
1268
+ equal(side.system.bodies.get('s-box-3').body.pos.x, authoredX, `${what}: and every still body is where its actor is`);
1269
+ side.runtime.touch('s-box-2');
1270
+ for (let i = 0; i < 4; i++) frame(side);
1271
+ ok(adoptedBy(side.system.stillKeeper)?.bodies > 0, `${what}: and settles again`);
1272
+ rows.push(`${what} -> ${ended}; next pass ordinary`);
1273
+ }
1274
+ }
1275
+ if (process.env.STILL_TABLE) console.log(rows.join('\n'));
1276
+ return rows.length;
1277
+ }
1278
+
1279
+ //
1280
+ // Entry points
1281
+ //
1282
+
1283
+ // The keeper of a world, and of a physics system, sees every entry into and
1284
+ // exit from that system's work, of every kind and by any runtime. An outer
1285
+ // pass of each kind (plain: a scene with no `skipUnchangedActors`; ordinary;
1286
+ // settled), a pass entered from inside it of each kind (the same runtime
1287
+ // again, another plain runtime, another runtime that asks), which returns or
1288
+ // throws and is caught. After each: nothing is adopted; a frame drawn after
1289
+ // the outer pass shows what the outer pass wrote; and the next pass of the
1290
+ // scene that asks visits every still actor or body.
1291
+ const plainRuntime = (side, engine = {}) =>
1292
+ anotherRuntime(side, (data) => {
1293
+ data.engine = engine;
1294
+ return data;
1295
+ });
1296
+ // A scene that skips and does not ask to hold anything still.
1297
+ const skippingRuntime = (side) => plainRuntime(side, { skipUnchangedActors: true });
1298
+ const LAMP = '#12ef34';
1299
+ // The lamp as the outer pass has it, so that a pass inside builds nothing and
1300
+ // is, by everything but the keeper, alone.
1301
+ const withLamp = (runtime) => {
1302
+ runtime.getActor('l-lamp').components.Shape.color = LAMP;
1303
+ return runtime;
1304
+ };
1305
+
1306
+ function innerRuntimes(side, outer) {
1307
+ return {
1308
+ 'the same runtime': () => outer,
1309
+ 'another runtime, plain': () => withLamp(plainRuntime(side)),
1310
+ 'another runtime, that asks': () => withLamp(anotherRuntime(side)),
1311
+ };
1312
+ }
1313
+
1314
+ // Calls `enter(runtime)` with the pass inside returning, or throwing and caught.
1315
+ function inside(runtime, how, enter) {
1316
+ if (how === 'returns') {
1317
+ enter(runtime);
1318
+ return;
1319
+ }
1320
+ const getActors = runtime.getActors;
1321
+ runtime.getActors = () => {
1322
+ runtime.getActors = getActors;
1323
+ if (getActors === Object.getPrototypeOf(runtime).getActors) delete runtime.getActors;
1324
+ throw new Error('inside');
1325
+ };
1326
+ assert.throws(() => enter(runtime), /inside/);
1327
+ }
1328
+
1329
+ async function entryPoints() {
1330
+ const rows = [];
1331
+ for (const outerKind of ['plain', 'skipping (not asking)', 'ordinary', 'settled']) {
1332
+ for (const how of ['returns', 'throws and is caught']) {
1333
+ for (const innerName of Object.keys(innerRuntimes(null, null))) {
1334
+ // The world.
1335
+ {
1336
+ const what = `the world: a ${outerKind} pass, entered by ${innerName}, which ${how}`;
1337
+ const side = (await makePair()).on;
1338
+ const keyed = side.runtime;
1339
+ ok(adoptedBy(side.world.stillKeeper) && frozen(side).length > 0, `${what}: settled before`);
1340
+ const outer = outerKind === 'plain' ? plainRuntime(side) : outerKind === 'skipping (not asking)' ? skippingRuntime(side) : keyed;
1341
+ // What the outer pass is to write, and the node built in it that
1342
+ // tells the listener.
1343
+ const wrote = outerKind === 'settled' ? 'l-door' : 's-last';
1344
+ if (outerKind === 'ordinary') keyed.touch(wrote);
1345
+ outer.getActor(wrote).components.Transform.x = 100;
1346
+ withLamp(outer);
1347
+ const inner = innerRuntimes(side, outer)[innerName]();
1348
+ // The pass inside is entered three times, and drawn each time: were
1349
+ // it allowed to adopt, its nodes would be frozen by the third.
1350
+ const ran = once(side.world.scene, 'childadded', () =>
1351
+ inside(inner, how, (runtime) => {
1352
+ for (let i = 0; i < 3; i++) {
1353
+ syncActors(side.world, runtime, {}, DT);
1354
+ renderWorld(side.world, runtime);
1355
+ }
1356
+ })
1357
+ );
1358
+ syncActors(side.world, outer, {}, DT);
1359
+ ok(ran(), `${what}: it happened`);
1360
+ equal(adoptedBy(side.world.stillKeeper), null, `${what}: nothing is adopted`);
1361
+ equal(frozen(side).length, 0, `${what}: nothing is frozen`);
1362
+ renderWorld(side.world, outer);
1363
+ equal(nodeOf(side, wrote).matrixWorld.elements[12], 100, `${what}: the frame drawn after it shows what it wrote`);
1364
+ // The next pass of the scene that asks: ordinary, every actor.
1365
+ const t = keyed.getActor('s-box-3').components.Transform;
1366
+ t.x += 9;
1367
+ syncActors(side.world, keyed, {}, DT);
1368
+ equal(nodeOf(side, 's-box-3').position.x, t.x, `${what}: the next pass visits every still actor`);
1369
+ rows.push(what);
1370
+ }
1371
+ // The physics system.
1372
+ {
1373
+ const what = `physics: a ${outerKind} pass, entered by ${innerName}, which ${how}`;
1374
+ const side = (await makePair()).on;
1375
+ const keyed = side.runtime;
1376
+ const system = side.system;
1377
+ ok(adoptedBy(system.stillKeeper)?.bodies > 0, `${what}: settled before`);
1378
+ const outer = outerKind === 'plain' ? plainRuntime(side) : outerKind === 'skipping (not asking)' ? skippingRuntime(side) : keyed;
1379
+ if (outerKind === 'ordinary') keyed.touch('s-box-1');
1380
+ const inner = innerRuntimes(side, outer)[innerName]();
1381
+ const ran = fromCallbacks(side, (sys) =>
1382
+ inside(inner, how, (runtime) => {
1383
+ for (let i = 0; i < 3; i++) sys.afterBehaviors(runtime, DT);
1384
+ })
1385
+ );
1386
+ system.afterBehaviors(outer, DT);
1387
+ ok(ran(), `${what}: it happened`);
1388
+ equal(adoptedBy(system.stillKeeper), null, `${what}: nothing is adopted`);
1389
+ // The next pass of the scene that asks: ordinary, every body.
1390
+ const t = keyed.getActor('s-box-3').components.Transform;
1391
+ t.x += 9;
1392
+ const sets = system.bodies.get('s-box-3').body.sets;
1393
+ system.afterBehaviors(keyed, DT);
1394
+ equal(system.bodies.get('s-box-3').body.pos.x, t.x, `${what}: the next pass visits every still body`);
1395
+ ok(system.bodies.get('s-box-3').body.sets > sets, `${what}: (it was pushed)`);
1396
+ rows.push(what);
1397
+ }
1398
+ }
1399
+ }
1400
+ }
1401
+
1402
+ // A pass that holds nothing still and calls nothing out (a scene that skips
1403
+ // and does not ask, or a plain one; nothing built, no listener): what it
1404
+ // writes to a node another scene had frozen is drawn.
1405
+ for (const [kind, make] of [['skipping (not asking)', skippingRuntime], ['plain', plainRuntime]]) {
1406
+ const what = `the world: a ${kind} pass that calls nothing out`;
1407
+ const side = (await makePair()).on;
1408
+ ok(isFrozen(nodeOf(side, 's-last')), `${what}: the node is frozen before`);
1409
+ const other = make(side);
1410
+ other.getActor('s-last').components.Transform.x = 100;
1411
+ syncActors(side.world, other, {}, DT);
1412
+ equal(adoptedBy(side.world.stillKeeper), null, `${what}: nothing is adopted`);
1413
+ renderWorld(side.world, other);
1414
+ equal(nodeOf(side, 's-last').matrixWorld.elements[12], 100, `${what}: the frame drawn after it shows what it wrote`);
1415
+ rows.push(what);
1416
+ }
1417
+
1418
+ // A keeper made DURING a pass it never saw enter: a world, and a physics
1419
+ // system, that have only ever run a plain scene; from inside a plain pass a
1420
+ // scene that asks is synced, more than once. It must not adopt there.
1421
+ {
1422
+ const what = 'a keeper made inside a plain pass of the world';
1423
+ const side = (await makePair()).on;
1424
+ const world = makeWorld();
1425
+ world.composer = { render: () => world.scene.updateMatrixWorld() };
1426
+ const plain = plainRuntime(side);
1427
+ for (let i = 0; i < 3; i++) syncActors(world, plain, {}, DT);
1428
+ ok(!world.stillKeeper, `${what}: none yet`);
1429
+ const asks = anotherRuntime(side);
1430
+ plain.getActor('l-lamp').components.Shape.color = '#12ef34';
1431
+ plain.getActor('s-last').components.Transform.x = 100;
1432
+ const looks = [];
1433
+ const ran = once(world.scene, 'childadded', () => {
1434
+ for (let i = 0; i < 4; i++) {
1435
+ syncActors(world, asks, {}, DT);
1436
+ renderWorld(world, asks);
1437
+ looks.push(adoptedBy(world.stillKeeper) === null && [...world.nodes.values()].every((entry) => !isFrozen(entry.node)));
1438
+ }
1439
+ });
1440
+ syncActors(world, plain, {}, DT);
1441
+ ok(ran() && Boolean(world.stillKeeper), `${what}: it was made`);
1442
+ equal(looks, [true, true, true, true], `${what}: nothing is adopted or frozen while the plain pass runs`);
1443
+ renderWorld(world, plain);
1444
+ equal(world.nodes.get('s-last').node.matrixWorld.elements[12], 100, `${what}: the frame drawn after it shows what it wrote`);
1445
+ for (let i = 0; i < 4; i++) {
1446
+ syncActors(world, asks, {}, DT);
1447
+ renderWorld(world, asks);
1448
+ }
1449
+ ok(adoptedBy(world.stillKeeper), `${what}: and the scene that asks settles once the plain pass is over`);
1450
+ rows.push(what);
1451
+ }
1452
+ {
1453
+ const what = 'a keeper made inside a plain pass of the physics system';
1454
+ const side = (await makePair()).on;
1455
+ const system = new Physics3DSystem();
1456
+ const plain = plainRuntime(side);
1457
+ system.attach(plain);
1458
+ await new Promise((resolve) => setTimeout(resolve, 0));
1459
+ for (let i = 0; i < 3; i++) system.afterBehaviors(plain, DT);
1460
+ ok(!system.stillKeeper, `${what}: none yet`);
1461
+ const asks = anotherRuntime(side);
1462
+ const looks = [];
1463
+ system.dispatchCallbacks = function (scene) {
1464
+ delete system.dispatchCallbacks;
1465
+ this.dispatchCallbacks(scene);
1466
+ for (let i = 0; i < 4; i++) {
1467
+ this.afterBehaviors(asks, DT);
1468
+ looks.push(adoptedBy(system.stillKeeper) === null);
1469
+ }
1470
+ };
1471
+ system.afterBehaviors(plain, DT);
1472
+ ok(Boolean(system.stillKeeper), `${what}: it was made`);
1473
+ equal(looks, [true, true, true, true], `${what}: nothing is adopted while the plain pass runs`);
1474
+ for (let i = 0; i < 3; i++) system.afterBehaviors(asks, DT);
1475
+ ok(adoptedBy(system.stillKeeper)?.bodies > 0, `${what}: and the scene that asks settles once the plain pass is over`);
1476
+ rows.push(what);
1477
+ }
1478
+
1479
+ // Two repros of a review, as given.
1480
+ // 1. The plain path of the world: a sync of a scene that asks, called from
1481
+ // the plain pass's `childadded` listener, must not adopt and freeze; the
1482
+ // plain pass then writes position.x = 100 and its draw shows it.
1483
+ {
1484
+ const side = (await makePair()).on;
1485
+ const plain = plainRuntime(side);
1486
+ withLamp(plain);
1487
+ withLamp(side.runtime);
1488
+ plain.getActor('s-last').components.Transform.x = 100;
1489
+ once(side.world.scene, 'childadded', () => {
1490
+ for (let i = 0; i < 3; i++) {
1491
+ syncActors(side.world, side.runtime, {}, DT);
1492
+ renderWorld(side.world, side.runtime);
1493
+ }
1494
+ });
1495
+ syncActors(side.world, plain, {}, DT);
1496
+ equal(nodeOf(side, 's-last').position.x, 100, 'the plain pass wrote position.x = 100');
1497
+ renderWorld(side.world, plain);
1498
+ equal(nodeOf(side, 's-last').matrixWorld.elements[12], 100, 'and its draw leaves matrixWorld.x = 100, as without the key');
1499
+ }
1500
+ // 2. The plain path of the physics system: a pass of a scene that asks,
1501
+ // entered from the plain pass's collision callback, must not leave an
1502
+ // adoption behind; the next pass of that scene visits the still body.
1503
+ {
1504
+ const side = (await makePair()).on;
1505
+ const system = side.system;
1506
+ const plain = plainRuntime(side);
1507
+ fromCallbacks(side, (sys) => {
1508
+ for (let i = 0; i < 3; i++) sys.afterBehaviors(side.runtime, DT);
1509
+ });
1510
+ system.afterBehaviors(plain, DT);
1511
+ equal(adoptedBy(system.stillKeeper), null, 'no adoption survives the plain pass');
1512
+ const body = system.bodies.get('s-box-2').body;
1513
+ const sets = body.sets;
1514
+ side.runtime.getActor('s-box-2').components.Transform.x = 55;
1515
+ system.afterBehaviors(side.runtime, DT);
1516
+ ok(body.sets > sets && body.pos.x === 55, 'the next pass of the scene that asks visits the still body');
1517
+ }
1518
+ if (process.env.STILL_TABLE) console.log(rows.join('\n'));
1519
+ return rows.length;
1520
+ }
1521
+
1522
+ // Disposal listeners outside a pass see no adoption and no frozen node.
1523
+ async function disposalListeners() {
1524
+ const reenter = (side, object, what, after = () => {}) => once(object, 'dispose', () => {
1525
+ for (let i = 0; i < 3; i++) {
1526
+ syncActors(side.world, side.runtime, {}, DT);
1527
+ side.world.scene.updateMatrixWorld();
1528
+ equal(adoptedBy(side.world.stillKeeper), null, `${what}: nested sync ${i} cannot adopt`);
1529
+ equal(frozen(side).length, 0, `${what}: nested walk ${i} cannot freeze`);
1530
+ }
1531
+ after();
1532
+ });
1533
+ const observe = (side, object, what) => {
1534
+ const looks = [];
1535
+ object.addEventListener('dispose', () => {
1536
+ const adopted = Boolean(side.world.stillKeeper.adopted);
1537
+ const frozen = [...side.world.nodes.values(), ...[...side.world.parked.values()].flatMap((nodes) => [...nodes.values()])].some((entry) => isFrozen(entry.node));
1538
+ looks.push({ adopted, frozen });
1539
+ equal({ adopted, frozen }, { adopted: false, frozen: false }, `${what}: inside the dispose listener`);
1540
+ });
1541
+ return looks;
1542
+ };
1543
+ // The harness has no WebGL renderer: its composer allocates real three.js
1544
+ // render targets as the renderer would, on the shadow attached for drawing.
1545
+ const side = (await makePair({ shadows: 40 })).on;
1546
+ const { world, runtime } = side;
1547
+ const sun = new THREE.DirectionalLight();
1548
+ sun.castShadow = true;
1549
+ sun.shadow.mapSize.set(2048, 2048);
1550
+ Object.assign(sun.shadow.camera, { near: 0.5, far: 50, top: 85, bottom: -35, left: -75, right: 75 });
1551
+ sun.shadow.camera.updateProjectionMatrix();
1552
+ world.scene.add(sun);
1553
+ world.renderer.shadowMap = { enabled: true, autoUpdate: true, type: THREE.PCFSoftShadowMap };
1554
+ world.composer.render = () => {
1555
+ world.scene.updateMatrixWorld();
1556
+ sun.shadow.map ??= new THREE.WebGLRenderTarget(sun.shadow.mapSize.x, sun.shadow.mapSize.y);
1557
+ };
1558
+ for (let i = 0; i < 3; i++) frame(side);
1559
+ let map = world.nearShadows?.shadow?.map;
1560
+ ok(map, 'world disposal: the near-shadow path made a map');
1561
+ // Count the keeper's settled entries and verify none is demoted (which
1562
+ // would thaw by moving the epoch) while the near-shadow fit is unchanged.
1563
+ const keeper = world.stillKeeper;
1564
+ const begin = keeper.begin;
1565
+ const passes = [];
1566
+ keeper.begin = function (version) {
1567
+ const pass = begin.call(this, version);
1568
+ passes.push(pass);
1569
+ return pass;
1570
+ };
1571
+ const epoch = world.skipping.epoch;
1572
+ for (let i = 1; i <= 30; i++) {
1573
+ frame(side);
1574
+ ok(settled(side), `unchanged near shadows, frame ${i}: adoption survives`);
1575
+ equal(frozen(side).length, STILL.length - 1, `unchanged near shadows, frame ${i}: still nodes stay frozen`);
1576
+ equal(world.skipping.epoch, epoch, `unchanged near shadows, frame ${i}: no pass was demoted`);
1577
+ }
1578
+ equal(passes.length, 30, 'unchanged near shadows: thirty actor passes');
1579
+ ok(passes.slice(1).every((pass) => pass.settled), 'unchanged near shadows: frames 2..30 ran settled passes');
1580
+ ok(settled(side), 'unchanged near shadows: adoption present after frame 30');
1581
+ equal(world.nearShadows.shadow.map, map, 'unchanged near shadows: the same map survives thirty frames');
1582
+
1583
+ const blur = new THREE.WebGLRenderTarget(4, 4);
1584
+ world.nearShadows.shadow.mapPass = blur;
1585
+ const entered = reenter(side, map, 'leaving near shadows');
1586
+ const left = observe(side, map, 'leaving near shadows, later map listener');
1587
+ const blurred = observe(side, blur, 'leaving near shadows, blur map');
1588
+ renderWorld(world); // No distance: leave the mode and dispose its map.
1589
+ ok(entered(), 'leaving near shadows: the first listener synced three times');
1590
+ equal(left, [{ adopted: false, frozen: false }], 'leaving near shadows: the map listener ran');
1591
+ equal(blurred, [{ adopted: false, frozen: false }], 'leaving near shadows: the blur listener ran');
1592
+ equal(keeper.running, 0, 'leaving near shadows: the bracket exited');
1593
+ equal(adoptedBy(keeper), null, 'leaving near shadows: no adoption survives');
1594
+ equal(frozen(side).length, 0, 'leaving near shadows: every node thawed');
1595
+ frame(side);
1596
+ equal(passes.at(-1).settled, false, 'after a map disposal: the next frame is ordinary');
1597
+ frame(side);
1598
+ equal(passes.at(-1).settled, true, 'after a map disposal: the following frame runs settled');
1599
+ ok(settled(side) && frozen(side).length === STILL.length - 1, 'after a map disposal: the world settles and freezes again');
1600
+ // A throwing first map still releases the blur map inside the same bracket.
1601
+ map = world.nearShadows.shadow.map;
1602
+ const throwingBlur = new THREE.WebGLRenderTarget(4, 4);
1603
+ world.nearShadows.shadow.mapPass = throwingBlur;
1604
+ reenter(side, map, 'throwing near-shadow release');
1605
+ const throwingBlurs = observe(side, throwingBlur, 'throwing near-shadow release, blur map');
1606
+ once(map, 'dispose', () => { throw new Error('listener failed'); });
1607
+ assert.throws(() => renderWorld(world), /listener failed/);
1608
+ equal(throwingBlurs, [{ adopted: false, frozen: false }], 'throwing near-shadow release: the blur map was still released');
1609
+ equal(keeper.running, 0, 'throwing near-shadow release: the bracket exited');
1610
+ frame(side);
1611
+ equal(passes.at(-1).settled, false, 'throwing near-shadow release: the next frame is ordinary');
1612
+ frame(side);
1613
+ ok(passes.at(-1).settled && settled(side) && frozen(side).length > 0, 'throwing near-shadow release: later frames settle');
1614
+ delete keeper.begin;
1615
+ map = world.nearShadows?.shadow?.map;
1616
+ ok(map, 'world disposal: near shadows have a map again');
1617
+ ok(settled(side) && frozen(side).length > 0, 'world disposal: adopted and frozen before disposal');
1618
+ const disposedBlur = new THREE.WebGLRenderTarget(4, 4);
1619
+ world.nearShadows.shadow.mapPass = disposedBlur;
1620
+ const disposedEntry = reenter(side, map, 'world disposal');
1621
+ const looks = observe(side, map, 'world disposal, later map listener');
1622
+ const disposedBlurs = observe(side, disposedBlur, 'world disposal, blur map');
1623
+ once(map, 'dispose', () => { throw new Error('listener failed'); });
1624
+ assert.throws(() => disposeWorld(world), /listener failed/);
1625
+ ok(disposedEntry(), 'world disposal: the first listener synced three times');
1626
+ equal(looks, [{ adopted: false, frozen: false }], 'world disposal: the near-shadow map listener ran');
1627
+ equal(disposedBlurs, [{ adopted: false, frozen: false }], 'world disposal: the blur listener ran');
1628
+ equal(keeper.running, 0, 'world disposal: the bracket exited');
1629
+ frame(side);
1630
+ equal(adoptedBy(keeper), null, 'world disposal: even a later frame never adopts');
1631
+ equal(frozen(side).length, 0, 'world disposal: even a later frame never freezes');
1632
+ sun.shadow.map.dispose();
1633
+ runtime.dispose();
1634
+
1635
+ for (const throws of [false, true]) for (const kind of ['ground replacement', 'physics debug', 'resize', 'editor lens return']) {
1636
+ const what = `${kind}${throws ? ', throwing' : ''}`;
1637
+ const side = (await makePair()).on;
1638
+ const { world } = side;
1639
+ ok(settled(side) && frozen(side).length > 0, `${what}: adopted and frozen before disposal`);
1640
+ let object;
1641
+ let second;
1642
+ let call;
1643
+ let after = () => {};
1644
+ const composer = world.composer;
1645
+ if (kind === 'ground replacement') {
1646
+ object = world.ground.material;
1647
+ side.runtime.data.ground = { color: '#abcdef' };
1648
+ call = () => syncGround(world, side.runtime.data.ground, {});
1649
+ } else if (kind === 'physics debug') {
1650
+ object = new THREE.BufferGeometry();
1651
+ second = new THREE.BufferGeometry();
1652
+ after = () => second.dispose();
1653
+ world.debugLines = { geometry: object };
1654
+ call = () => updatePhysicsDebug(world, { vertices: new Float32Array(0), colors: new Float32Array(0) });
1655
+ } else if (kind === 'resize') {
1656
+ world.renderer.getPixelRatio = () => 1;
1657
+ world.renderer.setSize = () => {};
1658
+ world.composer = new EffectComposer(world.renderer, new THREE.WebGLRenderTarget(1, 1));
1659
+ object = world.composer.renderTarget1;
1660
+ second = world.composer.renderTarget2;
1661
+ call = () => resizeWorld(world, 2, 2);
1662
+ } else {
1663
+ object = new THREE.BufferGeometry();
1664
+ world.orbitLens = { fov: world.camera.fov + 10 };
1665
+ const project = world.camera.updateProjectionMatrix;
1666
+ world.camera.updateProjectionMatrix = function () {
1667
+ this.updateProjectionMatrix = project;
1668
+ project.call(this);
1669
+ object.dispose();
1670
+ };
1671
+ call = () => renderWorld(world);
1672
+ }
1673
+ const ran = reenter(side, object, what, after);
1674
+ const looks = observe(side, object, what);
1675
+ const later = second ? observe(side, second, `${what}, second object`) : null;
1676
+ // Throw only after the observers, to verify the bracket exits on errors.
1677
+ if (throws) once(object, 'dispose', () => { throw new Error('listener failed'); });
1678
+ if (throws) assert.throws(call, /listener failed/);
1679
+ else call();
1680
+ ok(ran(), `${what}: the first listener synced three times`);
1681
+ equal(looks, [{ adopted: false, frozen: false }], `${what}: the dispose listener ran`);
1682
+ if (later && (!throws || kind === 'physics debug')) equal(later, [{ adopted: false, frozen: false }], `${what}: the second object sees no still state`);
1683
+ world.composer = composer;
1684
+ equal(world.stillKeeper.running, 0, `${what}: the bracket exited`);
1685
+ equal(adoptedBy(world.stillKeeper), null, `${what}: no adoption survives`);
1686
+ const keeper = world.stillKeeper;
1687
+ const begin = keeper.begin;
1688
+ const settledPasses = [];
1689
+ keeper.begin = function (version) {
1690
+ const pass = begin.call(this, version);
1691
+ settledPasses.push(pass);
1692
+ return pass;
1693
+ };
1694
+ frame(side);
1695
+ equal(settledPasses[0].settled, false, `${what}: the next frame is ordinary`);
1696
+ frame(side);
1697
+ equal(settledPasses.at(-1).settled, true, `${what}: a later frame settles`);
1698
+ ok(settled(side) && frozen(side).length > 0, `${what}: later frames can freeze again`);
1699
+ delete keeper.begin;
1700
+ disposeWorld(world);
1701
+ side.runtime.dispose();
1702
+ }
1703
+
1704
+ // Even a keyless world keeps the same callback across frames and mode
1705
+ // recreation; stable rendering allocates no new release function.
1706
+ const keyless = (await makePair({ shadows: 40 })).off;
1707
+ for (let i = 0; i < 3; i++) frame(keyless);
1708
+ const callback = keyless.world.nearShadowCall;
1709
+ ok(typeof callback === 'function' && !keyless.world.stillKeeper, 'keyless near shadows: one callback and no keeper');
1710
+ for (let i = 0; i < 30; i++) {
1711
+ frame(keyless);
1712
+ equal(keyless.world.nearShadowCall, callback, `keyless near shadows, frame ${i}: the world reuses its callback`);
1713
+ equal(keyless.world.nearShadows.onCallout, callback, `keyless near shadows, frame ${i}: the state reuses its callback`);
1714
+ }
1715
+ renderWorld(keyless.world);
1716
+ frame(keyless);
1717
+ equal(keyless.world.nearShadows.onCallout, callback, 'keyless near shadows: recreating the mode reuses the callback too');
1718
+ disposeWorld(keyless.world);
1719
+ keyless.runtime.dispose();
1720
+ }
1721
+
1722
+ // A keeper made during a call-out must see the operation it never saw enter.
1723
+ // Keep the repros independent so a failure reports every affected entry point.
1724
+ async function keeperMadeInCallouts() {
1725
+ const failures = [];
1726
+ for (const throwing of [false, true]) for (const kind of ['resize', 'physics debug', 'ground replacement', 'editor lens return', 'near-shadow release', 'world disposal']) {
1727
+ const what = `keeper made inside ${kind}${throwing ? ', throwing' : ''}`;
1728
+ try {
1729
+ const shadows = kind === 'near-shadow release' || kind === 'world disposal';
1730
+ const side = (await makePair({ shadows: shadows ? 40 : 0 })).off;
1731
+ const { world } = side;
1732
+ const keyed = anotherRuntime(side, (data) => {
1733
+ data.engine.staticActors = true;
1734
+ return data;
1735
+ });
1736
+ keyed.three = world;
1737
+ const composer = world.composer;
1738
+ let first;
1739
+ let second;
1740
+ let call;
1741
+ let after = () => {};
1742
+ let sun;
1743
+ if (kind === 'resize') {
1744
+ world.renderer.getPixelRatio = () => 1;
1745
+ world.renderer.setSize = () => {};
1746
+ world.composer = new EffectComposer(world.renderer, new THREE.WebGLRenderTarget(1, 1));
1747
+ first = world.composer.renderTarget1;
1748
+ second = world.composer.renderTarget2;
1749
+ call = () => resizeWorld(world, 2, 2);
1750
+ } else if (kind === 'physics debug') {
1751
+ first = new THREE.BufferGeometry();
1752
+ second = new THREE.BufferGeometry();
1753
+ world.debugLines = { geometry: first };
1754
+ after = () => second.dispose();
1755
+ call = () => updatePhysicsDebug(world, { vertices: new Float32Array(0), colors: new Float32Array(0) });
1756
+ } else if (kind === 'ground replacement') {
1757
+ first = second = world.ground.material;
1758
+ keyed.data.ground = { color: '#abcdef' };
1759
+ call = () => syncGround(world, keyed.data.ground, {});
1760
+ } else if (kind === 'editor lens return') {
1761
+ first = second = new THREE.BufferGeometry();
1762
+ world.orbitLens = { fov: world.camera.fov + 10 };
1763
+ const project = world.camera.updateProjectionMatrix;
1764
+ world.camera.updateProjectionMatrix = function () {
1765
+ this.updateProjectionMatrix = project;
1766
+ project.call(this);
1767
+ first.dispose();
1768
+ };
1769
+ call = () => renderWorld(world);
1770
+ } else {
1771
+ sun = new THREE.DirectionalLight();
1772
+ sun.castShadow = true;
1773
+ sun.shadow.mapSize.set(2048, 2048);
1774
+ Object.assign(sun.shadow.camera, { near: 0.5, far: 50, top: 85, bottom: -35, left: -75, right: 75 });
1775
+ sun.shadow.camera.updateProjectionMatrix();
1776
+ world.scene.add(sun);
1777
+ world.renderer.shadowMap = { enabled: true, autoUpdate: true, type: THREE.PCFSoftShadowMap };
1778
+ world.composer.render = () => {
1779
+ world.scene.updateMatrixWorld();
1780
+ sun.shadow.map ??= new THREE.WebGLRenderTarget(sun.shadow.mapSize.x, sun.shadow.mapSize.y);
1781
+ };
1782
+ for (let i = 0; i < 3; i++) frame(side);
1783
+ first = world.nearShadows.shadow.map;
1784
+ second = new THREE.WebGLRenderTarget(4, 4);
1785
+ world.nearShadows.shadow.mapPass = second;
1786
+ call = kind === 'world disposal' ? () => disposeWorld(world) : () => renderWorld(world);
1787
+ }
1788
+ ok(!world.stillKeeper && world.unkept === 0, `${what}: previously keyless, no keeper`);
1789
+ // The resize repro: target 1's listener makes a keeper by syncing a
1790
+ // keyed scene four times and walking matrices; target 2 observes it.
1791
+ const ran = once(first, 'dispose', () => {
1792
+ for (let i = 0; i < 4; i++) {
1793
+ syncActors(world, keyed, {}, DT);
1794
+ world.scene.updateMatrixWorld();
1795
+ }
1796
+ after();
1797
+ });
1798
+ const looks = [];
1799
+ once(second, 'dispose', () => {
1800
+ const state = {
1801
+ adopted: Boolean(adoptedBy(world.stillKeeper)),
1802
+ frozen: [...world.nodes.values()].some((entry) => isFrozen(entry.node)),
1803
+ running: world.stillKeeper.running,
1804
+ unkept: world.unkept,
1805
+ };
1806
+ looks.push(state);
1807
+ equal({ adopted: state.adopted, frozen: state.frozen, running: state.running }, { adopted: false, frozen: false, running: 0 }, `${what}: the later listener`);
1808
+ ok(state.unkept > 0, `${what}: the later listener sees the operation counted`);
1809
+ });
1810
+ // Throw after the later observer, including when it is a second map.
1811
+ if (throwing) once(second, 'dispose', () => { throw new Error('listener failed'); });
1812
+ if (throwing) assert.throws(call, /listener failed/);
1813
+ else call();
1814
+ ok(ran() && looks.length === 1 && world.stillKeeper, `${what}: the keeper was made and the later listener ran`);
1815
+ equal(world.unkept, 0, `${what}: unkept returns to zero`);
1816
+ equal(adoptedBy(world.stillKeeper), null, `${what}: no adoption survives`);
1817
+ equal(frozen({ world }).length, 0, `${what}: no node stays frozen`);
1818
+ if (kind === 'resize') world.composer = composer;
1819
+ const keeper = world.stillKeeper;
1820
+ const begin = keeper.begin;
1821
+ const passes = [];
1822
+ keeper.begin = function (version) {
1823
+ const pass = begin.call(this, version);
1824
+ passes.push(pass);
1825
+ return pass;
1826
+ };
1827
+ frame(side, keyed);
1828
+ equal(passes[0].settled, false, `${what}: the next frame is ordinary`);
1829
+ for (let i = 0; i < 4; i++) frame(side, keyed);
1830
+ if (kind === 'world disposal') {
1831
+ ok(passes.every((pass) => !pass.settled) && !adoptedBy(keeper) && frozen({ world }).length === 0, `${what}: a disposed world never adopts again`);
1832
+ } else {
1833
+ ok(passes.at(-1).settled && adoptedBy(keeper) && frozen({ world }).length > 0, `${what}: later frames settle and freeze again`);
1834
+ }
1835
+ delete keeper.begin;
1836
+ disposeWorld(world);
1837
+ if (sun?.shadow.map) sun.shadow.map.dispose();
1838
+ keyed.dispose();
1839
+ side.runtime.dispose();
1840
+ } catch (error) {
1841
+ failures.push(`${what}: ${error.message}`);
1842
+ }
1843
+ }
1844
+ equal(failures, [], 'keepers made inside call-outs: every entry point, returning and throwing');
1845
+ }
1846
+
1847
+ // Sky disposals are call-outs too: both keys on, with a real sky record and
1848
+ // settled scenery. Check the listener's entry and re-entry, across resources.
1849
+ async function skyDisposalListeners() {
1850
+ // A keyed runtime drawing in another world, or a disposed world, cannot
1851
+ // make a record and must not allocate the world's lazy callback either.
1852
+ const absent = makeWorld();
1853
+ absent.composer = { render: () => absent.scene.updateMatrixWorld() };
1854
+ renderWorld(absent);
1855
+ equal(absent.skyCall, undefined, 'no sky key: no call-out callback');
1856
+ renderWorld(absent, { sky: {}, three: makeWorld() });
1857
+ equal(absent.skyCall, undefined, 'foreign sky runtime: no call-out callback');
1858
+ disposeWorld(absent);
1859
+ renderWorld(absent, { sky: {}, three: absent });
1860
+ equal(absent.skyCall, undefined, 'disposed world without a sky record: no call-out callback');
1861
+ for (const kind of ['shed without hook', 'shed', 'load', 'dispose', 'prepare', 'settle']) {
1862
+ const what = `sky ${kind}`;
1863
+ const side = makeSide(true);
1864
+ const { world, runtime } = side;
1865
+ for (let i = 0; i < 3; i++) frame(side);
1866
+ equal(world.skyCall, undefined, `${what}: no callback before a sky record`);
1867
+ const data = structuredClone(side.data);
1868
+ data.engine.sky = { zones: [
1869
+ { id: 'home', color: '#aabbcc', art: 'drawings/home.webp' },
1870
+ { id: 'away', color: '#334455', art: 'drawings/away.webp', box: [50, -100, 150, 100] },
1871
+ ] };
1872
+ data.actors.find((actor) => actor.id === 'l-lamp').components.Player = {};
1873
+ runtime.setBehaviors([...classesWith(), quiet('Player')]);
1874
+ for (const art of ['drawings/home.webp', 'drawings/away.webp']) {
1875
+ runtime.sprites[art] = { kind: 'image', ready: true, failed: false, image: { width: 32, height: 16 } };
1876
+ }
1877
+ runtime.load(data);
1878
+ await new Promise((resolve) => setTimeout(resolve, 0));
1879
+ for (let i = 0; i < 6; i++) frame(side);
1880
+ ok(settled(side) && frozen(side).length > 0, `${what}: adopted and frozen before disposal`);
1881
+ const record = world.sky;
1882
+ ok(record && record.textures.size === 2, `${what}: a sky with a texture`);
1883
+ const callback = world.skyCall;
1884
+ ok(typeof callback === 'function' && record.onCallout === callback, `${what}: the record uses the world's callback`);
1885
+ const epoch = world.skipping.epoch;
1886
+ for (let i = 0; i < 3; i++) frame(side);
1887
+ equal(world.skyCall, callback, `${what}: unchanged frames reuse the callback`);
1888
+ equal(world.skipping.epoch, epoch, `${what}: unchanged sky frames keep frozen nodes`);
1889
+ const transform = runtime.actorWith('Player').components.Transform;
1890
+ const startX = transform.x;
1891
+ const beforeCrossing = { adopted: adoptedBy(world.stillKeeper), frozen: frozen(side) };
1892
+ for (const x of [49, 51, 49, 100, startX]) {
1893
+ transform.x = x;
1894
+ renderWorld(world, runtime);
1895
+ equal(world.skipping.epoch, epoch, `${what}: crossing runs no outsideCall/thaw`);
1896
+ equal({ adopted: adoptedBy(world.stillKeeper), frozen: frozen(side) }, beforeCrossing, `${what}: crossing keeps adopted and frozen scenery`);
1897
+ }
1898
+ const looks = [];
1899
+ for (const item of record.owned()) {
1900
+ const resource = item.isTexture ? 'texture' : item.isMaterial ? 'material' : 'geometry';
1901
+ item.addEventListener('dispose', () => {
1902
+ const state = { adopted: Boolean(world.stillKeeper.adopted), frozen: frozen(side).length > 0 };
1903
+ looks.push(resource);
1904
+ equal(state, { adopted: false, frozen: false }, `${what}: ${resource} listener entry`);
1905
+ for (let i = 0; i < 3; i++) {
1906
+ syncActors(world, runtime, {}, DT);
1907
+ renderWorld(world, runtime);
1908
+ equal({ adopted: Boolean(world.stillKeeper.adopted), frozen: frozen(side).length > 0 },
1909
+ { adopted: false, frozen: false }, `${what}: ${resource} listener nested sync ${i}`);
1910
+ }
1911
+ });
1912
+ }
1913
+ if (kind.startsWith('shed')) {
1914
+ delete runtime.sprites['drawings/home.webp']; // Art removal sheds home's cached texture.
1915
+ if (kind === 'shed without hook') {
1916
+ record.onCallout = undefined;
1917
+ try {
1918
+ assert.throws(() => renderWorld(world, runtime), (err) => {
1919
+ equal(err.actual, { adopted: true, frozen: true }, `${what}: the unguarded listener sees the old state`);
1920
+ return err.message.includes('texture listener entry');
1921
+ });
1922
+ } finally {
1923
+ record.onCallout = callback;
1924
+ }
1925
+ equal(looks, ['texture', 'texture', 'geometry', 'material'], `${what}: all listeners still ran after the first failure`);
1926
+ equal(world.sky, null, `${what}: the failing frame leaves no record`);
1927
+ disposeWorld(world);
1928
+ runtime.dispose();
1929
+ continue;
1930
+ } else renderWorld(world, runtime);
1931
+ } else if (kind === 'load') {
1932
+ const keyless = structuredClone(data);
1933
+ delete keyless.engine.sky; // The static keys stay on.
1934
+ runtime.load(keyless);
1935
+ } else if (kind === 'dispose') {
1936
+ disposeWorld(world);
1937
+ } else if (kind === 'prepare') {
1938
+ renderWorld(world); // An editor has no key: release before drawing.
1939
+ } else {
1940
+ world.composer.render = () => {
1941
+ world.composer.render = () => world.scene.updateMatrixWorld();
1942
+ world.scene.updateMatrixWorld();
1943
+ const keyless = structuredClone(data);
1944
+ delete keyless.engine.sky;
1945
+ runtime.load(keyless); // A load during the draw releases at settle.
1946
+ };
1947
+ renderWorld(world, runtime);
1948
+ world.composer.render = () => world.scene.updateMatrixWorld();
1949
+ }
1950
+ equal(looks, kind === 'shed' ? ['texture'] : ['texture', 'texture', 'geometry', 'material'], `${what}: every resource listener ran`);
1951
+ equal(world.skyDepth, 0, `${what}: sky depth returns to zero`);
1952
+ equal(world.stillKeeper.running, 0, `${what}: call-out bracket exits`);
1953
+ equal(adoptedBy(world.stillKeeper), null, `${what}: no adoption survives`);
1954
+ equal(frozen(side).length, 0, `${what}: no frozen node survives`);
1955
+ if (kind !== 'shed') equal(world.sky, null, `${what}: the record is released`);
1956
+ else equal(record.mesh.parent, null, `${what}: the retained dome is detached`);
1957
+ const keeper = world.stillKeeper;
1958
+ const begin = keeper.begin;
1959
+ const passes = [];
1960
+ keeper.begin = function (version) {
1961
+ const pass = begin.call(this, version);
1962
+ passes.push(pass);
1963
+ return pass;
1964
+ };
1965
+ frame(side);
1966
+ equal(passes.at(-1).settled, false, `${what}: the next frame is ordinary`);
1967
+ for (let i = 0; i < 4; i++) frame(side);
1968
+ equal(world.skyCall, callback, `${what}: recreation and keyless frames reuse the world's callback`);
1969
+ if (kind === 'dispose') {
1970
+ ok(passes.every((pass) => !pass.settled) && !adoptedBy(keeper) && frozen(side).length === 0,
1971
+ `${what}: a disposed world never adopts again`);
1972
+ } else {
1973
+ ok(passes.at(-1).settled && settled(side) && frozen(side).length > 0, `${what}: later frames settle again`);
1974
+ }
1975
+ delete keeper.begin;
1976
+ disposeWorld(world);
1977
+ runtime.dispose();
1978
+ }
1979
+ }
1980
+
1981
+ // The sky/static review's three entry points, collected so a pre-fix run
1982
+ // reports every regression instead of stopping after the first one.
1983
+ async function skyReviewRegressions() {
1984
+ const failures = [];
1985
+ const runCase = async (name, check) => {
1986
+ const side = makeSide(true);
1987
+ const { world, runtime } = side;
1988
+ const data = structuredClone(side.data);
1989
+ data.engine.sky = { zones: [{ id: 'home', color: '#aabbcc', art: 'drawings/review.webp' }] };
1990
+ runtime.sprites['drawings/review.webp'] = { kind: 'image', ready: !name.startsWith('art '), failed: false, image: { width: 32, height: 16 } };
1991
+ runtime.load(data);
1992
+ await new Promise((resolve) => setTimeout(resolve, 0));
1993
+ for (let i = 0; i < 6; i++) frame(side);
1994
+ try {
1995
+ await check(side);
1996
+ } catch (err) {
1997
+ failures.push(`${name}: ${err.message}`);
1998
+ } finally {
1999
+ delete world.camera.updateProjectionMatrix;
2000
+ world.renderer.dispose = () => {};
2001
+ try { disposeWorld(world); } catch { /* The case may leave throwing listeners behind. */ }
2002
+ runtime.dispose();
2003
+ }
2004
+ };
2005
+ for (const source of ['fields', 'slot', 'nonplain']) await runCase(`art ${source}`, (side) => {
2006
+ const { world, runtime } = side;
2007
+ ok(settled(side) && frozen(side).length > 0, 'art getter: settled before the read');
2008
+ const art = runtime.sprites['drawings/review.webp'];
2009
+ const seen = [];
2010
+ const getter = (field) => () => {
2011
+ seen.push({ adopted: Boolean(world.stillKeeper.adopted), frozen: frozen(side).length > 0 });
2012
+ for (let i = 0; i < 3; i++) syncActors(world, runtime, {}, DT);
2013
+ return field === 'ready' ? true : { width: 32, height: 16 };
2014
+ };
2015
+ if (source === 'fields') {
2016
+ for (const field of ['ready', 'image']) Object.defineProperty(art, field, { configurable: true, get: getter(field) });
2017
+ } else if (source === 'slot') {
2018
+ art.ready = true;
2019
+ Object.defineProperty(runtime.sprites, 'drawings/review.webp', { configurable: true, get() {
2020
+ getter('ready')();
2021
+ return art;
2022
+ } });
2023
+ } else {
2024
+ runtime.sprites['drawings/review.webp'] = Object.create({ ...art, ready: true });
2025
+ }
2026
+ const warnings = [];
2027
+ const warn = console.warn;
2028
+ console.warn = (message) => warnings.push(message);
2029
+ const passes = [];
2030
+ const begin = world.stillKeeper.begin;
2031
+ world.stillKeeper.begin = function (version) {
2032
+ const pass = begin.call(this, version);
2033
+ passes.push(pass);
2034
+ return pass;
2035
+ };
2036
+ try {
2037
+ const startEpoch = world.skipping.epoch;
2038
+ for (let i = 0; i < 6; i++) frame(side);
2039
+ equal(seen, [], 'art getter: ready/image getter calls = 0');
2040
+ equal(world.sky.material.uniforms.hasFrom.value, 0, 'art getter: zone draws its flat colour');
2041
+ equal(world.sky.textures.size, 0, 'art getter: no texture retained');
2042
+ equal(warnings.length, 1, 'art getter: exactly one warning');
2043
+ ok(warnings[0].includes('home') && warnings[0].includes('drawings/review.webp'), 'art getter: warning names zone and art');
2044
+ const epoch = world.skipping.epoch;
2045
+ const adoption = world.stillKeeper.adopted;
2046
+ renderWorld(world, runtime);
2047
+ equal(world.stillKeeper.adopted, adoption, 'art getter: adoption undisturbed');
2048
+ equal(world.skipping.epoch, epoch, 'art getter: nodes stay frozen');
2049
+ equal(epoch, startEpoch, 'art getter: all reads preserve frozen nodes');
2050
+ ok(passes.every((pass) => pass.settled) && settled(side), 'art getter: frames keep settling');
2051
+ runtime.load(structuredClone(side.data)); // Keyless, then recreate the sky in this world.
2052
+ const data = structuredClone(side.data);
2053
+ data.engine.sky = { zones: [{ id: 'home', color: '#aabbcc', art: 'drawings/review.webp' }] };
2054
+ runtime.load(data);
2055
+ for (let i = 0; i < 4; i++) frame(side);
2056
+ equal(warnings.length, 1, 'art getter: one warning per world across record recreation');
2057
+ } finally {
2058
+ console.warn = warn;
2059
+ delete world.stillKeeper.begin;
2060
+ }
2061
+ });
2062
+ await runCase('lens cleanup', ({ world }) => {
2063
+ const owned = [...world.sky.owned()];
2064
+ const disposed = [];
2065
+ for (const item of owned) item.addEventListener('dispose', () => disposed.push(item));
2066
+ const order = [];
2067
+ const lensError = new Error('lens return failed');
2068
+ world.orbitLens = { fov: world.camera.fov + 1 };
2069
+ world.camera.updateProjectionMatrix = () => { order.push('lens'); throw lensError; };
2070
+ // Real near-shadow release exercises its disposal listener too.
2071
+ const map = new THREE.WebGLRenderTarget(4, 4);
2072
+ map.addEventListener('dispose', () => { order.push('near'); throw new Error('near release failed'); });
2073
+ world.nearShadows = { depth: 0, frame: null, shadow: { release: () => map.dispose() } };
2074
+ world.sky.material.addEventListener('dispose', () => { order.push('sky'); throw new Error('sky release failed'); });
2075
+ world.renderer.dispose = () => { order.push('nodes'); throw new Error('renderer release failed'); };
2076
+ let thrown;
2077
+ try { disposeWorld(world); } catch (err) { thrown = err; }
2078
+ equal({ skyLive: Boolean(world.sky), resourcesDisposed: disposed.length, nearLive: Boolean(world.nearShadows), lensErrorKept: thrown === lensError },
2079
+ { skyLive: false, resourcesDisposed: owned.length, nearLive: false, lensErrorKept: true }, 'lens cleanup: all stages run and the first error wins');
2080
+ equal(world.sky, null, 'lens cleanup: sky record released despite lens failure');
2081
+ equal(disposed, owned, 'lens cleanup: every sky resource disposed');
2082
+ equal(order, ['lens', 'sky', 'near', 'nodes'], 'lens cleanup: all four stages run in order; first error wins');
2083
+ equal(world.nearShadows, null, 'lens cleanup: near shadows dropped');
2084
+ equal(world.nodes.size, 0, 'lens cleanup: nodes disposed');
2085
+ equal(world.stillKeeper.running, 0, 'lens cleanup: keeper bracket exited');
2086
+ world.renderer.dispose = () => {};
2087
+ });
2088
+ for (const kind of ['world disposal', 'physics reset']) await runCase(`throw 0 at ${kind}`, ({ world, runtime, system }) => {
2089
+ world.sky.material.addEventListener('dispose', () => { throw 0; });
2090
+ let outcome = null;
2091
+ try {
2092
+ if (kind === 'world disposal') disposeWorld(world);
2093
+ else system.reset(runtime);
2094
+ } catch (err) {
2095
+ outcome = { err };
2096
+ }
2097
+ equal(outcome, { err: 0 }, `throw 0 at ${kind}: the exact thrown value escapes`);
2098
+ equal(world.sky, null, `throw 0 at ${kind}: cleanup still ran`);
2099
+ equal(world.stillKeeper.running, 0, `throw 0 at ${kind}: keeper bracket exited`);
2100
+ });
2101
+ equal(failures, [], 'sky review regressions');
2102
+ console.log('sky review: getter calls 0, flat colour, one warning per zone/world, adoption preserved; lens cleanup and throw 0 passed');
2103
+ }
2104
+
2105
+ // Where the key does nothing, and what a dispose leaves.
2106
+ async function inert() {
2107
+ // Without `skipUnchangedActors`.
2108
+ const plain = await makePair({ skip: false });
2109
+ ok(plain.on.runtime.keepsStaticActors === false && plain.on.runtime.stillActors === null, 'without skipUnchangedActors the key is not on');
2110
+ play(plain, 4, 'without skipUnchangedActors');
2111
+ ok(!adoptedBy(plain.on.world.stillKeeper) && !adoptedBy(plain.on.system.stillKeeper));
2112
+ // The editor's world, and a world that draws copies together.
2113
+ for (const [what, set] of [
2114
+ ['the editor', (world) => (world.staticActorsOff = true)],
2115
+ ['instanceModels', (world) => (world.instanceModels = true)],
2116
+ ]) {
2117
+ const pair = await makePair();
2118
+ for (const side of [pair.off, pair.on]) set(side.world);
2119
+ for (const side of [pair.off, pair.on]) side.runtime.touch('l-lamp');
2120
+ play(pair, 5, what);
2121
+ ok(!adoptedBy(pair.on.world.stillKeeper) && frozen(pair.on).length === 0, `${what}: nothing is held still`);
2122
+ // An actor written with no touch is followed there, as it always was.
2123
+ both(pair, `${what}: a marked actor written`, (side) => (side.runtime.getActor('s-box-0').components.Transform.x += 2));
2124
+ if (what === 'the editor') equal(nodeOf(pair.on, 's-box-0').position.x, 2);
2125
+ }
2126
+ // A pass that throws leaves nothing adopted; a dispose leaves nothing at all.
2127
+ const pair = await makePair();
2128
+ const { on } = pair;
2129
+ ok(settled(on));
2130
+ on.world.scene.userData.groundHeight = () => {
2131
+ throw new Error('no ground');
2132
+ };
2133
+ on.runtime.getActor('l-mover').components.Transform.x += 1;
2134
+ assert.throws(() => syncActors(on.world, on.runtime, {}, DT), /no ground/);
2135
+ ok(!adoptedBy(on.world.stillKeeper) && frozen(on).length === 0, 'a pass that throws leaves nothing adopted and nothing frozen');
2136
+ delete on.world.scene.userData.groundHeight;
2137
+ for (let i = 0; i < 4; i++) frame(on);
2138
+ ok(settled(on) && frozen(on).length === STILL.length - 1, 'and the scene settles again');
2139
+ const nodes = STILL.filter((id) => on.world.nodes.has(id)).map((id) => nodeOf(on, id));
2140
+ const epoch = on.world.skipping.epoch;
2141
+ disposeWorld(on.world);
2142
+ ok(!adoptedBy(on.world.stillKeeper) && on.world.skipping.epoch > epoch && nodes.every((node) => !isFrozen(node)), 'a disposed world holds nothing still');
2143
+ on.runtime.dispose();
2144
+ ok(!adoptedBy(on.system.stillKeeper), 'nor does its physics');
2145
+ // What a frozen node holds is numbers.
2146
+ const side = (await makePair()).on;
2147
+ const node = nodeOf(side, 's-barrel-0');
2148
+ equal([typeof node.freezes, typeof node.frozenAt], ['number', 'number']);
2149
+ equal(Object.keys(adoptedBy(side.world.stillKeeper)).sort(), ['arts', 'at', 'count', 'cursor', 'drops', 'epoch', 'files', 'made', 'version']);
2150
+ }
2151
+
2152
+ export async function run() {
2153
+ checks = 0;
2154
+ await skyReviewRegressions();
2155
+ await stillFrames();
2156
+ await fixedBodiesAreFound();
2157
+ await withTheLookBakedLater();
2158
+ await touchAndAudit();
2159
+ const withHub = await writers();
2160
+ await sharedInputs();
2161
+ const withLevers = await levers();
2162
+ await scenes();
2163
+ await insideAPass();
2164
+ await interruptions();
2165
+ const enumeratedCases = (await enumerated()) + (await entryPoints());
2166
+ await disposalListeners();
2167
+ await keeperMadeInCallouts();
2168
+ await skyDisposalListeners();
2169
+ await inert();
2170
+ setLookEnabled(true);
2171
+ return `${checks} static-scenery checks, ${enumeratedCases} interruptions enumerated, key on against off frame for frame (on a stand-in rapier${withHub ? ", with hub-game's own hide, show and tint" : ''}${withLevers ? ' and its levers' : ''})`;
2172
+ }
2173
+
2174
+ if (process.argv[1] === fileURLToPath(import.meta.url)) console.log(await run());