threedog 1.0.1 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (364) hide show
  1. package/CHANGELOG.md +90 -0
  2. package/README.md +1 -1
  3. package/core/assets/Animator.js +41 -3
  4. package/core/assets/Assets.js +100 -24
  5. package/core/assets/assetEntry.js +73 -20
  6. package/core/assets/assetHot.js +68 -16
  7. package/core/assets/assetLoad.js +6 -6
  8. package/core/assets/assetLod.js +9 -2
  9. package/core/assets/assetManifest.js +12 -2
  10. package/core/assets/assetPart.js +54 -0
  11. package/core/assets/ik.js +271 -0
  12. package/core/assets/modelNeeds.js +37 -0
  13. package/core/assets/namedModel.js +102 -29
  14. package/core/assets/nodeVisibility.js +15 -0
  15. package/core/audio/Audio.js +36 -4
  16. package/core/audio/audioReverb.js +99 -0
  17. package/core/audio/audioRules.js +1 -1
  18. package/core/audio/audioVoice.js +1 -1
  19. package/core/base/Events.js +14 -4
  20. package/core/base/Random.js +1 -1
  21. package/core/base/Vars.js +1 -1
  22. package/core/base/docRef.js +51 -0
  23. package/core/base/errorCodes.js +178 -126
  24. package/core/base/errorHints.js +9 -7
  25. package/core/base/errors.js +25 -10
  26. package/core/base/events.generated.js +2 -0
  27. package/core/base/freeParts.js +76 -0
  28. package/core/base/math.js +28 -0
  29. package/core/base/sections.js +5 -5
  30. package/core/base/validate.js +31 -3
  31. package/core/engine/Engine.js +16 -6
  32. package/core/engine/Loading.js +5 -3
  33. package/core/engine/copies.js +1 -1
  34. package/core/engine/headlessLoad.js +4 -1
  35. package/core/engine/lifecycle.js +32 -16
  36. package/core/engine/loop.js +71 -27
  37. package/core/engine/moduleSlots.js +2 -2
  38. package/core/engine/moduleTypes.js +3 -3
  39. package/core/engine/modules.js +65 -39
  40. package/core/engine/page.js +6 -3
  41. package/core/engine/services.js +6 -5
  42. package/core/engine/startup.js +5 -5
  43. package/core/input/Input.js +28 -14
  44. package/core/input/inputContext.js +28 -16
  45. package/core/input/inputKeyboard.js +31 -3
  46. package/core/input/inputPad.js +4 -0
  47. package/core/input/inputPointer.js +2 -1
  48. package/core/input/inputSeat.js +1 -1
  49. package/core/inspect/Budget.js +109 -19
  50. package/core/inspect/DebugOverrides.js +28 -4
  51. package/core/inspect/Describe.js +17 -9
  52. package/core/inspect/Inspect.js +4 -2
  53. package/core/inspect/InspectMaterials.js +3 -1
  54. package/core/inspect/InspectPerf.js +19 -9
  55. package/core/inspect/InspectScene.js +32 -7
  56. package/core/inspect/MaterialInfo.js +19 -2
  57. package/core/inspect/UrlState.js +46 -27
  58. package/core/inspect/catalog.js +28 -9
  59. package/core/inspect/debugView.js +2 -1
  60. package/core/inspect/describeRender.js +25 -13
  61. package/core/inspect/describeText.js +14 -6
  62. package/core/inspect/lightWatch.js +1 -1
  63. package/core/inspect/metadata.generated.js +35 -17
  64. package/core/inspect/pictureChecks.js +148 -0
  65. package/core/inspect/pictureMenu.js +84 -0
  66. package/core/inspect/pictureWriters.js +26 -6
  67. package/core/inspect/textureBytes.js +12 -2
  68. package/core/inspect/toolDoor.js +2 -4
  69. package/core/ops/Ops.js +11 -4
  70. package/core/ops/holds.js +27 -10
  71. package/core/ops/opsAtomic.js +15 -7
  72. package/core/ops/opsGuard.js +2 -2
  73. package/core/ops/opsRun.js +8 -7
  74. package/core/ops/sharedPoint.js +72 -21
  75. package/core/ops/stacks.js +56 -16
  76. package/core/saves/SaveStore.js +9 -3
  77. package/core/saves/Saves.js +32 -23
  78. package/core/saves/saveApply.js +96 -44
  79. package/core/saves/saveIds.js +1 -1
  80. package/core/saves/saveVersions.js +7 -5
  81. package/core/saves/session.js +17 -8
  82. package/core/saves/stateReplace.js +34 -15
  83. package/core/scene/Rays.js +52 -10
  84. package/core/scene/Views.js +13 -7
  85. package/core/scene/adaptive.js +144 -21
  86. package/core/scene/drawOnly.js +17 -0
  87. package/core/scene/gameLights.js +44 -3
  88. package/core/scene/sceneMethods.js +13 -11
  89. package/core/scene/stepPoses.js +11 -3
  90. package/core/scene/targeting.js +5 -3
  91. package/core/scene/thingOps.js +1 -1
  92. package/core/scene/tier.js +15 -0
  93. package/core/stream/Batching.js +30 -7
  94. package/core/stream/Stream.js +26 -7
  95. package/core/stream/batchGroups.js +2 -2
  96. package/core/stream/chunkStream.js +7 -5
  97. package/core/stream/prepare.js +77 -0
  98. package/core/time/skip.js +3 -1
  99. package/core/time/time.js +4 -2
  100. package/docs/AI.md +82 -83
  101. package/docs/API.md +16 -16
  102. package/docs/CODEMAP.md +16 -11
  103. package/docs/COMMANDS.md +31 -33
  104. package/docs/CONVENTIONS.md +37 -49
  105. package/docs/MIGRATING-0.8.md +2 -2
  106. package/docs/MIGRATING-1.0.md +2 -2
  107. package/docs/THREE.md +28 -35
  108. package/docs/api/assets.md +3 -1
  109. package/docs/api/audio.md +4 -2
  110. package/docs/api/budget.md +5 -0
  111. package/docs/api/cameraRig.md +2 -2
  112. package/docs/api/characters.md +10 -8
  113. package/docs/api/collision.md +6 -4
  114. package/docs/api/engine.md +16 -16
  115. package/docs/api/events.md +3 -2
  116. package/docs/api/ground.md +6 -5
  117. package/docs/api/hud.md +4 -2
  118. package/docs/api/input.md +5 -5
  119. package/docs/api/particles.md +2 -1
  120. package/docs/api/photo.md +3 -0
  121. package/docs/api/post.md +7 -4
  122. package/docs/api/quests.md +2 -2
  123. package/docs/api/rays.md +1 -2
  124. package/docs/api/saves.md +7 -7
  125. package/docs/api/settings.md +2 -2
  126. package/docs/api/tools.md +3 -1
  127. package/docs/api/vars.md +1 -1
  128. package/docs/api/vegetation.md +4 -2
  129. package/docs/api/world.md +1 -1
  130. package/docs/recipes/01-new-game.md +16 -17
  131. package/docs/recipes/02-npc.md +22 -18
  132. package/docs/recipes/03-items-pickups.md +37 -35
  133. package/docs/recipes/04-quests.md +15 -10
  134. package/docs/recipes/05-props-bake.md +101 -95
  135. package/docs/recipes/06-clock-events.md +28 -28
  136. package/docs/recipes/07-flow-scenes-pause.md +29 -26
  137. package/docs/recipes/08-weather-sky.md +52 -64
  138. package/docs/recipes/09-materials-lights-models.md +26 -17
  139. package/docs/recipes/10-blender-level.md +15 -10
  140. package/docs/recipes/11-vehicles.md +12 -7
  141. package/docs/recipes/12-navmesh.md +44 -26
  142. package/docs/recipes/13-animation.md +56 -45
  143. package/docs/recipes/14-custom-module.md +21 -18
  144. package/docs/recipes/15-perf.md +61 -55
  145. package/docs/recipes/16-dev-bridge.md +23 -33
  146. package/docs/recipes/18-world.md +36 -42
  147. package/docs/recipes/19-shooting-picking.md +20 -15
  148. package/docs/recipes/20-content-actions-save.md +48 -56
  149. package/docs/recipes/21-camera.md +45 -54
  150. package/docs/recipes/22-shop-gold.md +12 -7
  151. package/docs/recipes/23-ops.md +25 -23
  152. package/docs/recipes/26-ui-parts.md +67 -47
  153. package/docs/recipes/27-net.md +12 -7
  154. package/docs/recipes/28-terrain.md +24 -21
  155. package/docs/recipes/29-grid.md +32 -27
  156. package/docs/recipes/30-templates.md +21 -20
  157. package/docs/recipes/31-audio.md +39 -22
  158. package/docs/recipes/32-action-game.md +19 -14
  159. package/docs/recipes/33-stream-sources.md +15 -11
  160. package/docs/recipes/34-environment-lighting.md +126 -70
  161. package/docs/recipes/35-picture-from-reference.md +8 -8
  162. package/docs/recipes/36-ground-plants.md +27 -21
  163. package/docs/recipes/40-scene.md +19 -28
  164. package/docs/recipes/43-shader-patches-surfaces.md +15 -12
  165. package/docs/recipes/44-water-weather-hooks.md +34 -31
  166. package/docs/recipes/45-cascaded-shadows.md +35 -26
  167. package/docs/recipes/46-blender-art-route.md +6 -1
  168. package/docs/recipes/49-game-module-contract.md +13 -8
  169. package/docs/recipes/50-own-renderer.md +6 -2
  170. package/docs/recipes/51-capability-catalog.md +15 -8
  171. package/docs/recipes/52-around-the-picture.md +34 -32
  172. package/docs/recipes/53-ground-up-close.md +6 -1
  173. package/docs/recipes/55-mods-time-wrap.md +27 -19
  174. package/docs/recipes/56-webgpu-tsl.md +74 -43
  175. package/docs/recipes/57-control.md +18 -13
  176. package/docs/recipes/58-input.md +26 -16
  177. package/docs/recipes/59-depth-post-effects.md +8 -3
  178. package/docs/recipes/60-judge-the-picture.md +9 -8
  179. package/docs/recipes/61-deploy.md +5 -0
  180. package/docs/recipes/62-picture-code.md +70 -79
  181. package/docs/recipes/63-third-person-start.md +47 -45
  182. package/docs/recipes/64-particles.md +22 -10
  183. package/docs/recipes/65-swarm.md +18 -13
  184. package/docs/recipes/66-common-tasks.md +38 -35
  185. package/examples/action/GAMEMAP.md +2 -3
  186. package/examples/action/main.js +3 -3
  187. package/examples/action/picture/lights.js +3 -1
  188. package/examples/perf-island/GAMEMAP.md +3 -3
  189. package/examples/perf-island/picture/lights.js +2 -1
  190. package/examples/plain-picture/GAMEMAP.md +1 -1
  191. package/examples/rc2d/GAMEMAP.md +1 -1
  192. package/examples/styletest/GAMEMAP.md +2 -2
  193. package/examples/styletest/main.js +1 -1
  194. package/examples/techniques/interior-light/README.md +3 -3
  195. package/examples/techniques/interior-light/interiorLight.js +2 -4
  196. package/examples/techniques/interior-light/picture/lights.js +2 -1
  197. package/examples/techniques/modular-building/picture/lights.js +3 -1
  198. package/examples/techniques/outlines-and-rim/picture/lights.js +3 -1
  199. package/examples/techniques/procedural-animation/README.md +1 -1
  200. package/examples/techniques/procedural-animation/main.js +1 -1
  201. package/examples/webgpu-tsl/GAMEMAP.md +1 -1
  202. package/examples/world/GAMEMAP.md +2 -3
  203. package/examples/world/art/humanoid.js +1 -1
  204. package/examples/world/main.js +6 -3
  205. package/index.d.ts +2 -2
  206. package/llms.txt +101 -0
  207. package/modules/ambience/Ambience.js +21 -5
  208. package/modules/calendar/index.js +9 -5
  209. package/modules/calendar/schedule.js +23 -8
  210. package/modules/camera/FirstPersonCamera.js +3 -1
  211. package/modules/camera/FollowCamera.js +10 -5
  212. package/modules/camera/RtsCamera.js +4 -3
  213. package/modules/camera/common.js +70 -8
  214. package/modules/camera/contract.js +1 -1
  215. package/modules/characters/Character.js +16 -10
  216. package/modules/characters/NPC.js +31 -19
  217. package/modules/characters/assetModel.js +14 -9
  218. package/modules/characters/astar.js +6 -1
  219. package/modules/characters/contract.js +2 -2
  220. package/modules/characters/index.js +34 -22
  221. package/modules/characters/movers/manual.js +1 -1
  222. package/modules/characters/movers/rapier.js +17 -2
  223. package/modules/characters/movers/simple.js +1 -1
  224. package/modules/characters/movers/support.js +16 -7
  225. package/modules/characters/npcAvoid.js +2 -2
  226. package/modules/characters/npcSim.js +3 -2
  227. package/modules/characters/pathAsync.js +24 -8
  228. package/modules/characters/pathJob.js +1 -1
  229. package/modules/characters/player.js +10 -9
  230. package/modules/characters/playerStrings.js +5 -5
  231. package/modules/characters/proceduralRig.js +5 -5
  232. package/modules/characters/useModel.js +6 -0
  233. package/modules/characters/walkTo.js +1 -1
  234. package/modules/collision/Collision.js +29 -18
  235. package/modules/collision/grid.js +22 -4
  236. package/modules/content/index.js +3 -1
  237. package/modules/content/loader.js +1 -1
  238. package/modules/content/models.js +82 -33
  239. package/modules/content/props.js +2 -1
  240. package/modules/content/rules.js +11 -5
  241. package/modules/content/templates.js +3 -3
  242. package/modules/content/words.js +2 -2
  243. package/modules/debug/DebugPanel.js +9 -9
  244. package/modules/flow/index.js +9 -6
  245. package/modules/gameplay/Dialogue.js +34 -20
  246. package/modules/gameplay/Interactions.js +19 -15
  247. package/modules/gameplay/Inventory.js +9 -4
  248. package/modules/gameplay/Quests.js +12 -10
  249. package/modules/gameplay/pickups.js +23 -11
  250. package/modules/grid/index.js +1 -1
  251. package/modules/grid/preview.js +2 -2
  252. package/modules/grid/tiles.js +1 -1
  253. package/modules/hlod/index.js +4 -1
  254. package/modules/hud/index.js +47 -10
  255. package/modules/hud/parts.js +28 -9
  256. package/modules/level/geometry.js +8 -3
  257. package/modules/level/index.js +10 -5
  258. package/modules/level/load.js +4 -2
  259. package/modules/lights/sources.js +1 -1
  260. package/modules/music/Music.js +22 -4
  261. package/modules/nav/index.js +20 -10
  262. package/modules/particles/Particles.js +31 -14
  263. package/modules/particles/effect.js +20 -5
  264. package/modules/particles/lit.js +72 -0
  265. package/modules/photo/Photo.js +72 -28
  266. package/modules/photo/pathTrace.js +106 -0
  267. package/modules/rigid/RigidBodies.js +23 -14
  268. package/modules/rigid/Vehicles.js +3 -13
  269. package/modules/rigid/sync.js +2 -1
  270. package/modules/settings/Settings.js +52 -20
  271. package/modules/settings/apply.js +23 -9
  272. package/modules/settings/sections.js +39 -6
  273. package/modules/settings/strings.js +2 -0
  274. package/modules/settings/view.js +19 -3
  275. package/modules/sky/dome.js +15 -3
  276. package/modules/sky/environment.js +28 -12
  277. package/modules/sky/fog.js +1 -1
  278. package/modules/sky/frame.js +6 -1
  279. package/modules/sky/shader.js +4 -3
  280. package/modules/sky/skyModule.js +8 -4
  281. package/modules/swarm/Swarm.js +1 -1
  282. package/modules/terrain/ChunkManager.js +61 -15
  283. package/modules/terrain/chunkJob.js +2 -2
  284. package/modules/terrain/index.js +20 -5
  285. package/modules/terrain/terrainEdit.js +8 -4
  286. package/modules/terrain/terrainTexture.js +4 -2
  287. package/modules/timeline/Timeline.js +4 -3
  288. package/modules/timeline/Tween.js +3 -0
  289. package/modules/timeline/letterbox.js +1 -0
  290. package/modules/triggers/index.js +36 -17
  291. package/modules/vegetation/Vegetation.js +81 -19
  292. package/modules/vegetation/densityMap.js +13 -8
  293. package/modules/vegetation/draw.js +147 -24
  294. package/modules/vegetation/groundChunks.js +20 -5
  295. package/modules/vegetation/index.js +3 -3
  296. package/modules/vegetation/modelGeometry.js +9 -4
  297. package/modules/water/Water.js +11 -8
  298. package/modules/weather/Weather.js +7 -2
  299. package/modules/weather/shaders.js +25 -5
  300. package/modules/weather/weatherDraw.js +20 -6
  301. package/modules/world/World.js +2 -1
  302. package/modules/world/index.js +2 -2
  303. package/modules/world/persist.js +6 -2
  304. package/modules/world/views.js +15 -2
  305. package/package.json +4 -1
  306. package/presets.js +5 -5
  307. package/render/PostFX.js +84 -41
  308. package/render/backend.js +137 -16
  309. package/render/cascades.js +3 -1
  310. package/render/cascades.tsl.js +2 -0
  311. package/render/daylight.js +7 -1
  312. package/render/detail.js +7 -4
  313. package/render/effects.js +27 -8
  314. package/render/fogLook.js +24 -0
  315. package/render/fuse.js +5 -2
  316. package/render/fx/detail.tsl.js +9 -7
  317. package/render/fx/index.js +7 -2
  318. package/render/fx/library.tsl.js +1 -0
  319. package/render/fx/lightShaft.tsl.js +114 -0
  320. package/render/fx/noise.tsl.js +25 -8
  321. package/render/fx/objectOrigin.tsl.js +39 -10
  322. package/render/fx/particles.tsl.js +23 -6
  323. package/render/fx/patchNodes.tsl.js +17 -12
  324. package/render/fx/pcss.tsl.js +51 -0
  325. package/render/fx/postWebGPU.tsl.js +89 -29
  326. package/render/fx/sky.tsl.js +3 -9
  327. package/render/fxNumbers.js +10 -4
  328. package/render/impostor.tsl.js +107 -0
  329. package/render/lighting.js +33 -1
  330. package/render/lightmap.js +42 -28
  331. package/render/lights.js +19 -3
  332. package/render/materials.js +6 -4
  333. package/render/mergeCommon.js +4 -1
  334. package/render/occlusion.js +14 -4
  335. package/render/patches.js +79 -41
  336. package/render/postRuns.js +32 -0
  337. package/render/postWebGL.js +97 -10
  338. package/render/probes.js +10 -14
  339. package/render/shaderErrors.js +2 -1
  340. package/render/shadowCache.tsl.js +33 -5
  341. package/render/shadows.js +42 -16
  342. package/render/slots.js +8 -5
  343. package/render/vertexInputs.js +52 -0
  344. package/types/core.d.ts +114 -46
  345. package/types/gameplay.d.ts +56 -23
  346. package/types/generated/core/audio/Audio.d.ts +27 -1
  347. package/types/generated/core/base/Random.d.ts +1 -1
  348. package/types/generated/core/input/Input.d.ts +6 -8
  349. package/types/generated/core/input/inputSeat.d.ts +1 -1
  350. package/types/generated/core/inspect/Budget.d.ts +26 -0
  351. package/types/generated/core/inspect/DebugOverrides.d.ts +0 -2
  352. package/types/generated/core/saves/Saves.d.ts +10 -7
  353. package/types/generated/core/saves/session.d.ts +8 -2
  354. package/types/generated/core/scene/Rays.d.ts +1 -3
  355. package/types/generated/modules/particles/Particles.d.ts +1 -1
  356. package/types/generated/modules/world/World.d.ts +2 -1
  357. package/types/generated/render/PostFX.d.ts +35 -9
  358. package/types/physics.d.ts +43 -11
  359. package/types/pixel.d.ts +1 -1
  360. package/types/tsl.d.ts +62 -1
  361. package/types/world.d.ts +12 -3
  362. package/ui/Focus.js +7 -5
  363. package/ui/Parts.js +1 -1
  364. package/ui/touchPart.js +6 -3
@@ -0,0 +1,84 @@
1
+ // engine.catalog('picture'): every picture capability on one line each: on now, can it run here, rough cost, one way to turn it on, where it is
2
+ // explained, what it cannot do. Capabilities only, never values: no row says how strong or which color. Read live, so nothing drifts:
3
+ // three's own features: the small table below (the only list in the engine; each row reads its "on" off the scene and renderer)
4
+ // post effects in the chain: their own definition's `about` (@threedog/post-effects puts it on every effect), "runs here" from the chain's rule
5
+ // effects not added yet: `offered` (factories with .about); the dev bridge passes the ones of @threedog/post-effects, which the engine never imports
6
+ import * as THREE from 'three';
7
+ import { runsHere } from '../../render/postRuns.js';
8
+ import { isWebGPU, backendName } from '../../render/backend.js';
9
+ import { pictureChecks } from './pictureChecks.js';
10
+ import { sceneFog, sceneEnvironment } from './describeRender.js';
11
+
12
+ const R34 = s => `recipes/34-environment-lighting.md §"${s}"`, EXTRAS = R34('Soft shadows, area lights, translucency, lens flare');
13
+
14
+ /** What the scene holds that no single field says: walked once per menu (the menu is asked for, never per frame) */
15
+ function sceneHas(scene) {
16
+ const has = { area: false, sss: false, flare: false, probes: false };
17
+ scene.traverse(o => {
18
+ if (o.isRectAreaLight) has.area = true;
19
+ if (o.isLensflare || o.isLensflareMesh) has.flare = true;
20
+ if (o.isLightProbeGrid) has.probes = true;
21
+ if (o.isMesh) for (const m of Array.isArray(o.material) ? o.material : [o.material]) if (m?.isMeshSSSNodeMaterial) has.sss = true;
22
+ });
23
+ return has;
24
+ }
25
+
26
+ /**
27
+ * three.js's own picture features. Each row: on(e, has), runs (renderers it runs on), cost, on-line, recipe, limits.
28
+ * Why here and not on three's classes: three carries no such facts; this is the one table, the effects carry their own.
29
+ */
30
+ const THREE_ROWS = [
31
+ { id: 'fog', on: e => !!sceneFog(e.scene), cost: 'low', how: 'engine.scene.fog = new THREE.Fog(color, near, far)', recipe: R34('Fog: plain three.js, signals, your own math'),
32
+ limits: 'color by distance only: no height, no light in it (recipes/59 for a fog that reads depth)' },
33
+ { id: 'environment map', on: e => !!sceneEnvironment(e.scene), cost: 'low', how: 'engine.scene.environment = pmrem.fromScene(new RoomEnvironment()).texture', recipe: R34('Environment maps'),
34
+ limits: 'one map seen from one point for the whole scene: no local reflections, no shadow in it (indoors gets sky light)' },
35
+ { id: 'tone curve', on: e => e.renderer.toneMapping !== THREE.NoToneMapping, cost: 'low', how: 'engine.renderer.toneMapping = THREE.AgXToneMapping', recipe: R34('Exposure and the tone curve'),
36
+ limits: 'one curve and one exposure for the whole screen (autoExposure for one that adapts, WebGPU)' },
37
+ { id: 'shadows', on: e => !!e.renderer.shadowMap?.enabled && someLight(e.scene, l => l.castShadow), cost: 'medium', how: 'light.castShadow = true; mesh.castShadow = mesh.receiveShadow = true',
38
+ recipe: 'recipes/45-cascaded-shadows.md', limits: 'one box per light: nothing outside it casts; each cascade or point light face is another render of the scene' },
39
+ { id: 'lightmap', on: e => !!e._lightmap, cost: 'low', how: "await engine.loadLightmap('light/level.lightmap') (threedog bake light)", recipe: R34('Lightmaps (baked light on what never moves)'),
40
+ limits: 'only what never moves; a moved mesh keeps its old light, a new light is not in it' },
41
+ { id: 'light probes', on: (e, has) => !!e._probeSets?.size || has.probes, cost: 'low', how: 'await engine.bakeProbes({ bounds, spacing })', recipe: R34('Light probes (baked indirect light)'),
42
+ limits: 'soft indirect light only, no reflections; light blends between probes, so thin walls leak' },
43
+ { id: 'area lights', on: (e, has) => has.area, cost: 'medium', how: 'engine.scene.add(new THREE.RectAreaLight(color, intensity, w, h))', recipe: EXTRAS,
44
+ limits: 'no shadows; lights MeshStandard / MeshPhysical only' },
45
+ { id: 'translucency (SSS)', on: (e, has) => has.sss, webgpuOnly: true, cost: 'low', how: 'new THREE.MeshSSSNodeMaterial({ ... }) (three/webgpu)', recipe: EXTRAS,
46
+ limits: 'a per-light approximation, not light traveling through the volume' },
47
+ { id: 'lens flare', on: (e, has) => has.flare, cost: 'low', how: 'light.add(lensflare) (LensflareMesh on WebGPU, Lensflare on WebGL)', recipe: EXTRAS,
48
+ limits: 'follows one light; hidden only by what the depth test sees' },
49
+ ];
50
+ export function someLight(scene, test) { let hit = false; scene.traverseVisible(o => { if (o.isLight && test(o)) hit = true; }); return hit; }
51
+
52
+ /** "yes", or why not: the chain's own rule for effects (runsHere), the renderer kind for three's WebGPU-only features */
53
+ const runsText = w => (w ? `${w.held ? 'held' : 'no'}: ${w.why}` : 'yes');
54
+ // an effect not added yet, as the shape the rule reads: about.webgpuOnly = node only; otherwise both renderers (the spec checks each effect says so truly)
55
+ const NOOP = () => {}, asDef = a => ({ create: a.webgpuOnly ? undefined : NOOP, node: NOOP, backend: a.backend, skipOnLowTier: a.skipOnLowTier });
56
+
57
+ function postRow(e, name, about, inChain) {
58
+ const a = about ?? {};
59
+ return { id: name, from: about ? (a.webgpuOnly ? '@threedog/post-effects/tsl' : '@threedog/post-effects') : 'game', on: inChain ? !!inChain.enabled : false,
60
+ runs: runsText(inChain ? runsHere(inChain._def, e) : runsHere(asDef(a), e)), cost: a.cost ?? 'unknown', how: a.on ?? (inChain ? 'in the chain (the game\'s own effect)' : ''),
61
+ recipe: a.recipe ?? 'recipes/52-around-the-picture.md §"Post effect chain"', limits: a.limits ?? 'not declared (give the effect an about field)' };
62
+ }
63
+
64
+ /**
65
+ * The picture menu. @param {any} e @param {{ offered?: any[] }} [o] offered: effect factories (with .about) or { name, ...about }
66
+ * @returns {{ id: 'picture', kind: 'menu', env: any, rows: any[], checks: { id: string, text: string }[], more: string | null }}
67
+ */
68
+ export function pictureMenu(e, { offered = [] } = {}) {
69
+ const r = e.renderer, webgpu = isWebGPU(r), has = sceneHas(e.scene);
70
+ const rows = THREE_ROWS.map(t => ({ id: t.id, from: 'three', on: !!t.on(e, has), runs: t.webgpuOnly && !webgpu ? 'no: WebGPURenderer only' : 'yes',
71
+ cost: t.cost, how: t.how, recipe: t.recipe, limits: t.limits }));
72
+ const chain = e.post?._list ?? [], names = new Set(chain.map(h => h.name));
73
+ for (const h of chain) rows.push(postRow(e, h.name, h._def.about, h));
74
+ let listed = 0;
75
+ for (const x of offered) {
76
+ const about = typeof x === 'function' ? x.about : x, name = typeof x === 'function' ? x.name : x?.name;
77
+ if (!about || !name || names.has(name)) continue;
78
+ names.add(name); listed++;
79
+ rows.push(postRow(e, name, about, null));
80
+ }
81
+ return { id: 'picture', kind: 'menu', env: { renderer: webgpu ? 'WebGPURenderer' : 'WebGLRenderer', backend: webgpu ? backendName(r) : 'webgl', tier: e.tier },
82
+ rows, checks: pictureChecks(e),
83
+ more: listed ? null : "effects not added yet: threedog catalog picture lists them, or engine.catalog('picture', { offered: Object.values(await import('@threedog/post-effects')) })" };
84
+ }
@@ -112,6 +112,7 @@ class Writers {
112
112
  const s = e.scene, r = e.renderer;
113
113
  this.number(r, 'toneMapping', this.named('renderer.toneMapping', NOT.start));
114
114
  this.number(r, 'toneMappingExposure', this.named('renderer.toneMappingExposure', NOT.start));
115
+ this.number(r.shadowMap, 'enabled', this.named('renderer.shadowMap.enabled', NOT.start)); // the shared point is engine.shadows.enabled; a direct write here is reported like any other
115
116
  for (const k of ['environmentIntensity', 'backgroundIntensity']) this.number(s, k, this.named('scene.' + k, NOT.start));
116
117
  this.number(s, 'environment', this.named('scene.environment', NOT.none));
117
118
  const bg = this.named('scene.background', NOT.start);
@@ -129,21 +130,40 @@ class Writers {
129
130
  for (const o of e._owned?.values() ?? []) this.owned(o); // the view's values exist before this tool does
130
131
  }
131
132
 
133
+ /**
134
+ * A removed watch gives its property back: the accessor answers to the next live record that shares it, and when none is left the plain value returns.
135
+ * Why: the accessor stays with the first record that hooked it; without this a later watch on the same property, or another record sharing it, recorded nothing
136
+ */
137
+ release(rec) {
138
+ rec.stopped = true;
139
+ const at = rec.at3, live = (rec.sharers ?? []).filter(s => !s.stopped);
140
+ if (!at || at.mine.get(at.key) !== rec) return;
141
+ if (live.length) {
142
+ const [next, ...rest] = live;
143
+ next.same = null; next.at3 = at; next.sharers = rest; for (const s of rest) s.same = next;
144
+ at.mine.set(at.key, next);
145
+ } else {
146
+ const v = at.o[at.key]; // no live record: back to a plain property
147
+ at.mine.delete(at.key);
148
+ Object.defineProperty(at.o, at.key, { value: v, writable: true, configurable: true, enumerable: true });
149
+ }
150
+ }
151
+
132
152
  named(label, why) { const r = newRec(why, () => label); this.top.set(label, r); return r; }
133
153
 
134
154
  /** Own accessor for one plain value; false when the object has none to replace. Reads and writes pass straight through */
135
155
  slot(o, key, rec, after) {
136
156
  let mine = this.hooked.get(o);
137
157
  const had = mine?.get(key);
138
- if (had) { if (had !== rec) rec.same = real(had); return true; }
158
+ if (had) { if (had !== rec) { rec.same = had; (had.sharers ??= []).push(rec); } return true; }
139
159
  const d = Object.getOwnPropertyDescriptor(o, key);
140
160
  if (!d || !('value' in d) || !d.configurable) { if (rec.why !== NOT.none || !d) rec.why = NOT.own; return false; }
141
161
  if (!mine) this.hooked.set(o, mine = new Map());
142
- mine.set(key, rec);
162
+ mine.set(key, rec); rec.at3 = { o, mine, key };
143
163
  let v = d.value;
144
164
  const t = this;
145
165
  Object.defineProperty(o, key, { configurable: true, enumerable: d.enumerable, get: () => v,
146
- set(x) { if (x === v) return; v = x; t.wrote(rec); after?.(x); } });
166
+ set(x) { if (x === v) return; v = x; t.wrote(mine.get(key) ?? rec); after?.(x); } }); // mine.get: whoever answers for the property now (release may hand it on)
147
167
  return true;
148
168
  }
149
169
  number(o, key, rec) { this.slot(o, key, rec); }
@@ -187,7 +207,7 @@ class Writers {
187
207
  if (!watching) rec.why = NOT.hidden;
188
208
  real(rec).close = true;
189
209
  // the accessors stay, like threePatches.off: they pass values through, and another record may be answering through them
190
- return { watching, remove: () => { if (this.top.get(label) === rec) this.top.delete(label); real(rec).close = false; } };
210
+ return { watching, remove: () => { if (this.top.get(label) === rec) this.top.delete(label); real(rec).close = false; this.release(rec); } };
191
211
  }
192
212
  /** A color held in a property: the components, and the property itself (light.color = other replaces the object the components were on) */
193
213
  color(o, key, rec) {
@@ -228,7 +248,7 @@ class Writers {
228
248
 
229
249
  /** The hot path: runs on every write that changed a value. No stack unless the header's rules ask for one */
230
250
  wrote(hit) {
231
- if (page.off || this.drawing || this.e._probing) return;
251
+ if (page.off || this.dead || hit.stopped || this.drawing || this.e._probing) return; // stopped: its watch was removed; dead: the engine was disposed. The accessors stay, but do no tracking
232
252
  const rec = real(hit), fr = this.frame;
233
253
  rec.wrote = fr;
234
254
  if (rec.f !== fr) {
@@ -414,7 +434,7 @@ class Writers {
414
434
  frameStart() { this.view.sync(); if (this.hooksRan) this.frame++; this.hooksRan = true; }
415
435
  /** After the draw. The fixed steps before the next hooks count with that next frame, which is what they lead to */
416
436
  frameEnd() { this.drawing = false; this.frame++; this.hooksRan = false; }
417
- dispose() { this.view.remove(); this.roots.remove(); }
437
+ dispose() { this.dead = true; this.view.remove(); this.roots.remove(); }
418
438
  }
419
439
 
420
440
  /** @param {any} e */
@@ -1,7 +1,7 @@
1
1
  // Estimated GPU bytes of a three.js texture (engine.inspect.materials / engine.inspect.perf). An estimate: three.js does not report VRAM.
2
2
  // Compressed / data textures: their data size; images: width x height x bytes per texel, x 4/3 with mipmaps, x 6 for a cube.
3
- const PER_CHANNEL = { 1009: 1, 1010: 1, 1011: 2, 1012: 2, 1013: 4, 1014: 4, 1015: 4, 1016: 2 }; // three's type constants UnsignedByte ... HalfFloat
4
- const CHANNELS = { 1021: 1, 1022: 3, 1023: 4, 1024: 1, 1025: 2, 1028: 1, 1030: 2, 1033: 4 }; // Alpha, RGB, RGBA, Luminance, LuminanceAlpha, Red, RG, RGBAInteger
3
+ const PER_CHANNEL = { 1009: 1, 1010: 1, 1011: 2, 1012: 2, 1013: 4, 1014: 4, 1015: 4, 1016: 2, 1020: 4 }; // three's type constants UnsignedByte ... HalfFloat, UnsignedInt248
4
+ const CHANNELS = { 1021: 1, 1022: 3, 1023: 4, 1024: 1, 1025: 2, 1026: 1, 1027: 1, 1028: 1, 1030: 2, 1033: 4 }; // Alpha, RGB, RGBA, Luminance, LuminanceAlpha, Depth, DepthStencil, Red, RG, RGBAInteger
5
5
 
6
6
  /** @param {any} t a THREE.Texture @returns {number} estimated bytes on the GPU (0 when unknown) */
7
7
  export function textureBytes(t) {
@@ -16,5 +16,15 @@ export function textureBytes(t) {
16
16
  return Math.round(w * h * d * texel * mips * faces.length);
17
17
  }
18
18
 
19
+ /**
20
+ * Estimated bytes of the shadow maps of the scene's lights (color and depth). Why here: on WebGLRenderer three counts no bytes, and a shadow map is often the biggest
21
+ * texture a game has while no material slot holds it, so a scene of procedural materials read 0 MB with 2048x2048 maps in memory @param {any} scene
22
+ */
23
+ export function shadowMapBytes(scene) {
24
+ let b = 0;
25
+ scene.traverse(o => { const m = o.isLight && o.castShadow ? o.shadow?.map : null; if (m) b += textureBytes(m.texture) + textureBytes(m.depthTexture); });
26
+ return b;
27
+ }
28
+
19
29
  /** Bytes as a short MB / KB string @param {number} b */
20
30
  export const mb = b => b >= 1048576 ? `${(b / 1048576).toFixed(1)} MB` : `${Math.round(b / 1024)} KB`;
@@ -1,5 +1,5 @@
1
- // engine._tools: the one door packages/tools has into the engine's internals, for what no game needs: draw a frame while halted, run the frame hooks, hand a halt back, read the
2
- // frame cost. Why a door and not the private names: about twenty sites in tools called them directly, so renaming one in core broke a tool with no error until it ran. Now core can
1
+ // engine._tools: the one door packages/tools has into the engine's internals, for what no game needs: draw a frame while halted, run the frame hooks, hand a halt back, read
2
+ // the light watch. Why a door and not the private names: about twenty sites in tools called them directly, so renaming one in core broke a tool with no error until it ran. Now core can
3
3
  // rename freely behind these words, and rule R68 fails any other reach from packages/tools. Internal: on no public page, not in the types.
4
4
  /** @param {any} e @returns {any} */
5
5
  export const toolDoor = e => ({
@@ -9,8 +9,6 @@ export const toolDoor = e => ({
9
9
  frameHooks: (dt, halted) => e._frameHooks(dt, halted),
10
10
  /** Hand back the halt this owner took @param {string} owner */
11
11
  resume: owner => e._unhalt(owner),
12
- /** Main-thread ms of the last real-time frame */
13
- get cpuMs() { return e._cpuMs ?? 0; },
14
12
  /** What the light watch saw (lightWatch.js) */
15
13
  get lightWatch() { return e._lightWatch; },
16
14
  /** The picture check is rendering: what it changes and puts back is not the game's */
package/core/ops/Ops.js CHANGED
@@ -10,7 +10,7 @@
10
10
  // which lands "after step N" and replays the same. Args must be plain data and self-contained (aim direction goes in the args).
11
11
  // The guard (ops.guard) backs "don't go around it": in dev, saved gameplay state written outside loading, fixed steps and ops
12
12
  // is reported (see recipes/23-ops.md). Dev argument checks live in opsCheck.js.
13
- import { DEV, fmt, missingText, warnOnce } from '../base/validate.js';
13
+ import { DEV, fmt, missingText, warnOnce, syncOnly } from '../base/validate.js';
14
14
  import { checkTypeRule, asModule } from '../engine/moduleTypes.js';
15
15
  import { checkDef, checkArgs, devError, SOURCES } from './opsCheck.js';
16
16
  import { coded, codedError } from '../base/errorHints.js';
@@ -50,7 +50,7 @@ export class Ops {
50
50
  /** @internal true while route() is held: every write outside allow() is reported, even in fixed steps and ops (own movement, world.move, excepted) */ this._client = false;
51
51
  /** Counter that only goes up: each committed op, undo, load and rollback bumps it (a failed op that changed nothing does not); every run result carries it, so "did anything change since I looked" is one compare */
52
52
  this.revision = 0;
53
- /** @internal depth of atomic runs in progress, and after hooks waiting for the outermost one to commit */ this._txDepth = 0; this._txAfter = [];
53
+ /** @internal depth of atomic runs in progress, and after hooks waiting for the outermost one to commit */ this._txDepth = 0; this._txAfter = []; /** @internal op:rolledBack announcements waiting for the failed run to leave the stack (opsAtomic.js) */ this._rolled = [];
54
54
  this.historySize = 256;
55
55
  }
56
56
  /** @internal Stamp a failed result with the current revision */
@@ -166,7 +166,14 @@ export class Ops {
166
166
  _as(name, ctx, fn) {
167
167
  const prev = this._last;
168
168
  this._stack.push(name); this._last = ctx;
169
- try { return fn(); } finally { this._stack.pop(); this._last = prev; }
169
+ try { return fn(); } finally { this._stack.pop(); this._last = prev; this._drainRolled(); }
170
+ }
171
+ /** @internal Tell the queued op:rolledBack announcements (opsAtomic.js) once the ops stack is empty again: called where it empties (runOp, _as). One drain at a time; ones queued while it runs go out in the same loop (guarded like the other loops) */
172
+ _drainRolled() {
173
+ if (this._draining || this._stack.length) return;
174
+ this._draining = true;
175
+ try { for (let n = 0; this._rolled.length && n < 16; n++) for (const say of this._rolled.splice(0)) say(); }
176
+ finally { this._draining = false; this._rolled.length = 0; } // past the guard the rest is dropped, not left for an unrelated op
170
177
  }
171
178
 
172
179
  /**
@@ -311,7 +318,7 @@ export class Ops {
311
318
  if (!d.can) return true;
312
319
  const prev = this._inCan; this._inCan = d.name;
313
320
  let r;
314
- try { r = d.can(this.engine, args, ctx); } finally { this._inCan = prev; }
321
+ try { r = d.can(this.engine, args, ctx); syncOnly(r, `can() of op '${d.name}'`, true); } finally { this._inCan = prev; }
315
322
  if (r === true || (typeof r === 'string' && r) || isStructured(r)) return r;
316
323
  const msg = fmt(STRINGS.canResult, { name: d.name, got: JSON.stringify(r) ?? 'undefined' });
317
324
  if (DEV) throw devError(msg);
package/core/ops/holds.js CHANGED
@@ -6,10 +6,12 @@
6
6
  // engine.freeze('menu') is engine.mod('freeze', { owner: 'menu' }) with the loop's side effects added (ending the last halt restarts the loop).
7
7
  // One entry per mechanism: the handle's remove() ends a halt / freeze (there is no engine.resume / engine.unfreeze).
8
8
  import { warnOnce } from '../base/validate.js';
9
+ import { readParams, keysSchema } from '../base/params.js';
9
10
  import { coded } from '../base/errorHints.js';
10
11
  import { ownerArgs } from './sharedPoint.js';
11
12
  import { viewHold } from '../scene/view.js';
12
13
 
14
+ const FREEZE_KEYS = keysSchema(['owner', 'kind', 'still']); // an unknown key (the old ambient) throws in dev with a did-you-mean
13
15
  // The halt / freeze handle is { owner, remove() } only: no chaining, so each is ended in exactly one way.
14
16
  function handle(owner, remove) { return { owner, remove }; }
15
17
 
@@ -21,13 +23,22 @@ function handle(owner, remove) { return { owner, remove }; }
21
23
  * @param {any} engine
22
24
  */
23
25
  export function defineHoldStacks(engine) {
24
- engine.stacks.define('freeze', { kind: 'any', save: false }); // who froze gameplay
26
+ engine.stacks.define('freeze', { kind: 'any', save: false, onChange: () => engine.input?._kbSync?.() }); // who froze gameplay; a freeze gives the page's key lock back (inputKeyboard.js)
25
27
  engine.stacks.define('halt', { kind: 'any', save: false, onChange: () => { // who stopped the loop; it restarts only when empty
26
28
  if (engine.stacks.get('halt').size()) engine.halted = true;
27
29
  else if (!engine.disposed) { engine.halted = false; engine._loop(); }
28
30
  engine.page._sync(); // a page hold is about the real-time loop: there is none while the loop is stopped (core/engine/page.js)
29
31
  } });
30
- engine.stacks.define('camera', { kind: 'top', save: false, onChange: () => viewHold(engine) }); // who holds the camera; the latest is in charge (cameraOverride)
32
+ // who holds the camera; the latest is in charge (cameraOverride). A claim that is in charge again after a newer one left gets its opts.onTop() called: it holds the camera
33
+ // but the newer holder moved it, so the holder puts its pose back (a named view). Claims are new objects per take, so "seen on top before" is the identity of one claim
34
+ const onTopBefore = new WeakSet(); let top = null;
35
+ engine.stacks.define('camera', { kind: 'top', save: false, onChange: () => {
36
+ viewHold(engine);
37
+ const t = engine.stacks.get('camera').value() ?? null;
38
+ if (t === top) return;
39
+ top = t;
40
+ if (t) { if (onTopBefore.has(t) && !engine.disposed) t.onTop?.(); onTopBefore.add(t); } // not after dispose: a shot's async release would write a camera that is gone
41
+ } });
31
42
  }
32
43
 
33
44
  export const holdMethods = {
@@ -65,21 +76,22 @@ export const holdMethods = {
65
76
  // have unfrozen. step() obeys freezes as well. Same owner rules as every stack (core/ops/stacks.js).
66
77
  /**
67
78
  * Freeze gameplay for owner (default 'game'; freeze({ owner, kind }) works too). kind 'title' marks a title screen waiting for start (runState 'title-frozen').
68
- * Ambient motion (uniforms.uTime: wind, water, clouds), skeletal animation and particles keep moving behind the freeze, as behind a pause menu; ambient: true stops them too
69
- * (a photo, a cutscene still; the page's own hold). UI and the camera stay live.
79
+ * Ambient motion (uniforms.uTime: wind, water, clouds), skeletal animation and particles keep moving behind the freeze, as behind a pause menu; still: true stops them too
80
+ * (a photo, a cutscene still; the page's own hold).. UI and the camera stay live.
70
81
  * Returns a handle whose remove() releases this owner's freeze. Same as engine.mod('freeze', { owner }) plus the kind.
71
- * @param {string | { owner?: string, kind?: 'title', ambient?: boolean }} [owner] @param {{ kind?: 'title', ambient?: boolean }} [opts]
82
+ * @param {string | { owner?: string, kind?: 'title', still?: boolean }} [owner] @param {{ kind?: 'title', still?: boolean }} [opts]
72
83
  * @returns {{ owner: string, remove(): void }}
73
84
  */
74
85
  freeze(owner, opts) {
75
86
  const a = ownerArgs(owner, opts);
76
- const h = this.stacks.get('freeze').take({ owner: a.owner, value: { kind: a.opts.kind ?? null, ambient: !!a.opts.ambient } });
87
+ readParams('engine.freeze()', FREEZE_KEYS, a.opts);
88
+ const h = this.stacks.get('freeze').take({ owner: a.owner, value: { kind: a.opts.kind ?? null, still: !!a.opts.still } });
77
89
  return handle(a.owner, h.remove);
78
90
  },
79
91
  /** True while someone has frozen gameplay */
80
92
  get frozen() { return this.stacks.get('freeze').value(); },
81
- /** True while a freeze asked for a full still (freeze(owner, { ambient: true })): code that moves things on frame dt reads this, as animation and particles do */
82
- get still() { const F = this.stacks.get('freeze'); return F.size() > 0 && F.entries().some(h => h.value?.ambient); }, // read per character and animator: nothing built while no one froze
93
+ /** True while a freeze asked for a full still (freeze(owner, { still: true })): code that moves things on frame dt reads this, as animation and particles do */
94
+ get still() { const F = this.stacks.get('freeze'); return F.size() > 0 && F.entries().some(h => h.value?.still); }, // read per character and animator: nothing built while no one froze
83
95
  /**
84
96
  * The one answer to "why is the page (not) advancing"; the dev bridge and the MCP tools copy it as-is.
85
97
  * state: 'loading' | 'title-frozen' (a freeze of kind 'title' is up, waiting for start) | 'halted' (the loop is stopped: a test, the bridge, a headless page)
@@ -94,7 +106,7 @@ export const holdMethods = {
94
106
  const lv = this.loading?.view();
95
107
  const state = !this.ready || !lv?.done ? 'loading' : F.entries().some(d => d.value.kind === 'title') ? 'title-frozen'
96
108
  : this.halted ? 'halted' : F.size() ? 'frozen' : 'running';
97
- const blockedBy = this.input.holders.filter(h => !h.pass).map(h => h.context);
109
+ const blockedBy = this.input.blockedBy();
98
110
  if (F.has('error')) blockedBy.push('error');
99
111
  if (lv?.blocked) blockedBy.push('loading');
100
112
  return { state, owners, blockedBy };
@@ -125,7 +137,7 @@ export const holdMethods = {
125
137
  const HOLD_STACKS = { halt: 'halt', freeze: 'freeze', camera: 'camera', debugView: 'debug.view' };
126
138
  /**
127
139
  * Everyone who holds something, in one place (empty parts left out): halt / freeze / camera / debugView [{ owner, at }]; input [{ context, owner,
128
- * pass }] (pushed input contexts); gates { action: [owners] } (input.gate). Every other shared value is in describe().shared (core/ops/stacks.js).
140
+ * pass }] (pushed input contexts); gates { action: [owners] } (input.gate); shadowed { action: [causes] } (input.blockedBy). Every other shared value is in describe().shared (core/ops/stacks.js).
129
141
  * Lives here, next to the hold stacks it reads, so describe() and the input-holds test use the same function (no second copy).
130
142
  * "Why can't I move / why is time slow" is answered here without knowing which module did it.
131
143
  */
@@ -136,5 +148,10 @@ export function describeHolds(e) {
136
148
  const g = e.stacks.has('input.gate') ? e.stacks.get('input.gate') : null, gates = {};
137
149
  for (const id of g?.ids() ?? []) if (g.size(id)) gates[id] = g.names(id);
138
150
  if (Object.keys(gates).length) out.gates = gates;
151
+ // actions whose own context is on the stack but a pass-through context above binds the same key: the one block holds.input does not already show,
152
+ // with every cause input.blockedBy gives
153
+ const shadowed = {};
154
+ for (const a of e.input.actions.keys()) { const why = e.input.blockedBy(a); if (why.some(w => w.startsWith('shadowed-by:'))) shadowed[a] = why; }
155
+ if (Object.keys(shadowed).length) out.shadowed = shadowed;
139
156
  return out;
140
157
  }
@@ -3,13 +3,18 @@
3
3
  // - it costs one save of those parts per atomic run: fine for a shop / craft op, not for a per-frame op in a huge world;
4
4
  // - events already emitted, and anything outside the atomic parts (sound, animation, DOM, other modules' saves), are NOT undone: put such side effects in the op's `after`;
5
5
  // - ops called from an atomic run join it: their `after` hooks wait for the outermost commit.
6
- // Which parts: the ones whose module declared saves.register(key, { atomic: true }) (core names no module; a game's own part can opt in the same way). An engine part that does
7
- // not says why in notAtomic: a part nobody asked stays changed while the rest rolls back (rule R66).
6
+ // Which parts: the ones whose module declared saves.define(key, { atomic: true }) (core names no module; a game's own part can opt in the same way). An engine part that does
7
+ // not says why in notAtomic: a part nobody asked stays changed while the rest rolls back (rule R67).
8
8
  // Rollback does not run afterLoad hooks (no model rebuild): atomic state must be plain data a load restores by itself. Events the load would emit are muted
9
- // (the run's own events already went out and cannot be recalled), and the trace gets one 'ops:rollback' note.
9
+ // (the run's own events already went out and cannot be recalled), the trace gets one 'ops:rollback' note, and once events are on again one public 'op:rolledBack' { op, parts }
10
+ // goes out, for what is derived from the run's events.
11
+ // The parts go back through the loop every load uses (restoreParts, saveApply.js): a part that throws is reported and the rest still go back. The rollback is
12
+ // synchronous, like run, can and the hooks: an atomic part's load() that returns a Promise is refused (engine-misuse) and not waited for. Were it waited for,
13
+ // the outer op of a failed nested one would commit first and the pending load write the old value over it later, its change events past the mute. The world keeps the models of records that came back unchanged (world/persist.js), so a failed shop op does not tear down the scene.
10
14
 
11
15
  import { reportError } from '../base/errors.js';
12
16
  import { codedError } from '../base/errorHints.js';
17
+ import { restoreParts } from '../saves/saveApply.js';
13
18
 
14
19
  /** Copy the atomic parts: [[key, provider, plain copy or null]] @internal */
15
20
  export function snapshot(e) {
@@ -23,16 +28,19 @@ export function snapshot(e) {
23
28
  function restored(e, k, p, d) {
24
29
  if (d != null || p.save() == null) return d;
25
30
  const S = e.session, parts = S._base ? S._baseData().parts : {}, base = Object.hasOwn(parts, k) ? parts[k] : null;
26
- if (base == null) reportError(e, codedError('save-load-threw', `atomic op rollback: save part '${k}' keeps what the op wrote: its save() gave nothing before the op and it has no new-game state to go back to`), 'ops rollback', { soft: true });
31
+ if (base == null) reportError(e, codedError('rollback-incomplete', `atomic op rollback: save part '${k}' keeps what the op wrote: its save() gave nothing before the op and it has no new-game state to go back to`), 'ops rollback');
27
32
  return base ?? null;
28
33
  }
29
34
 
30
35
  /** Put a snapshot back (guarded writes allowed, change events muted) @internal */
31
- export function rollback(e, snap) {
32
- const ev = e.events;
36
+ export function rollback(e, snap, op) {
37
+ const ev = e.events, list = [];
38
+ for (const [k, p, d] of snap) { const back = restored(e, k, p, d); if (back != null) list.push([k, p, structuredClone(back)]); }
33
39
  ev.muted = (ev.muted || 0) + 1;
34
- try { e.ops.allow(() => { for (const [k, p, d] of snap) { const back = restored(e, k, p, d); if (back != null) p.load(structuredClone(back)); } }); } finally { ev.muted--; }
40
+ try { e.ops.allow(() => restoreParts(e.saves, list, 'atomic op rollback')); } finally { ev.muted--; }
35
41
  if (ev.traceSize > 0) ev.note('ops:rollback', { data: { parts: snap.length } });
42
+ // the run's own events (quest:step, ...) went out and cannot be recalled: this one tells what is derived from them (a HUD marker) to read the state again
43
+ e.ops._rolled.push(() => ev.emit('op:rolledBack', { op, parts: snap.length })); // told by runOp once the failed run is off the stack and out of the transaction: a listener's op is then an ordinary top-level one
36
44
  }
37
45
 
38
46
  /** Mark the history entries a rolled-back run left behind (committed nested ops deeper than it) as failed with code 'rolledBack' @internal */
@@ -7,9 +7,9 @@ import { fmt, warnOnce } from '../base/validate.js';
7
7
  const STRINGS = {
8
8
  canWrote: "{name}'s can changed state ({where}). can is read-only; change state in run",
9
9
  guard: "[engine] gameplay state changed outside a fixed step or an op: {where}{at}.\n"
10
- + "Change state from UI buttons and timers through an op: engine.ops.run('name', args); put simulation in a module's fixed or world.simulate. See recipes/23-ops.md",
10
+ + "Change state from UI buttons and timers through an op: engine.ops.run('name', args); put simulation in a module's fixed or world.simulate. See recipes/23-ops.md §5",
11
11
  clientGuard: "[engine] net client changed shared state locally: {where}{at}.\n"
12
- + "On a client the host owns the state; request the change with engine.ops.run (op defined with net: 'peer'). See recipes/27-net.md",
12
+ + "On a client the host owns the state; request the change with engine.ops.run (op defined with net: 'peer'). See recipes/27-net.md §2",
13
13
  };
14
14
 
15
15
  /** Warn once per call site when `where` writes state outside the allowed places; throws when called from inside a can() */
@@ -1,6 +1,6 @@
1
1
  // ops.run itself (split out of Ops.js). Order: can -> log -> [snapshot if atomic] -> run -> commit (revision + 1, after hook) or fail (rollback if atomic).
2
2
  // A run that returns or throws a structured failure { ok: false, code, facts?, nextActions? } counts as failed, like a can that said no (see opsFail.js).
3
- import { DEV, fmt } from '../base/validate.js';
3
+ import { DEV, fmt, syncOnly } from '../base/validate.js';
4
4
  import { devError, argRange } from './opsCheck.js';
5
5
  import { reportError } from '../base/errors.js';
6
6
  import { failure, isRunFailure, opsBlocked } from './opsFail.js';
@@ -14,10 +14,10 @@ const RUN_STRINGS = {
14
14
  };
15
15
 
16
16
  /** Undo an atomic run's writes; a failing rollback is reported, never thrown over the original failure */
17
- function undoWrites(ops, e, snap, where, seq, depth) {
17
+ function undoWrites(ops, e, snap, name, where, seq, depth) {
18
18
  ops.revision++; // the revision only goes up: a rollback is a new state, never "the old number again"
19
19
  markRolledBack(ops, seq, depth);
20
- try { rollback(e, snap); } catch (err) { reportError(e, err, where + ' rollback'); }
20
+ try { rollback(e, snap, name); } catch (err) { reportError(e, err, where + ' rollback'); }
21
21
  }
22
22
 
23
23
  /** @internal Called by Ops.run */
@@ -52,19 +52,19 @@ export function runOp(ops, name, args, opts) {
52
52
  if (ev.traceSize > 0) ev._cur = `op:${name}#${seq}`;
53
53
  if (atomic) snap = snapshot(e);
54
54
  let value;
55
- try { value = d.run(e, args, ctx); } catch (err) { if (!isRunFailure(err)) throw err; value = err; }
55
+ try { value = d.run(e, args, ctx); if (ops._txDepth > 0) syncOnly(value, where, true); } catch (err) { if (!isRunFailure(err)) throw err; value = err; } // a Promise value is an error only inside a transaction (an atomic op, or a run nested in one): it would report success, then write or fail outside the rollback. A plain op may return one as its value (interaction.use, photo.trace)
56
56
  if (isRunFailure(value)) {
57
- if (snap) { undoWrites(ops, e, snap, where, seq, depth); ops._txAfter.length = mark; }
57
+ if (snap) { undoWrites(ops, e, snap, name, where, seq, depth); ops._txAfter.length = mark; }
58
58
  return failed(failure(value), h.seq === seq ? h : null);
59
59
  }
60
60
  ops.revision++;
61
61
  if (d.after) {
62
- const hook = () => { try { d.after(e, args, value, ctx); } catch (err) { reportError(e, err, where + ' after'); } };
62
+ const hook = () => { try { syncOnly(d.after(e, args, value, ctx), where + ' after'); } catch (err) { reportError(e, err, where + ' after'); } };
63
63
  if (ops._txDepth > 0) ops._txAfter.push(() => ops._as(name, ctx, hook)); else hook(); // in or inside an atomic run: queue, so hooks run in commit order (nested first) when the outermost one ends; off the stack by then, so with its ctx
64
64
  }
65
65
  return { ok: true, value, revision: ops.revision };
66
66
  } catch (err) {
67
- if (snap) { undoWrites(ops, e, snap, where, seq, depth); ops._txAfter.length = mark; }
67
+ if (snap) { undoWrites(ops, e, snap, name, where, seq, depth); ops._txAfter.length = mark; }
68
68
  if (err?.opsDevError) throw err;
69
69
  // a bad value that came in as an argument is the caller's mistake, not a broken game: refused like a can that said no, so gameplay does not freeze on it.
70
70
  // Only that one: a NaN the op worked out itself is a bug in the game, and goes on to stop it where it happened
@@ -77,5 +77,6 @@ export function runOp(ops, name, args, opts) {
77
77
  } finally {
78
78
  ops._stack.pop(); ops._last = prevCtx; ev._cur = prevCause;
79
79
  if (atomic && --ops._txDepth === 0) { const q = ops._txAfter.splice(0); for (const f of q) f(); } // outermost atomic op ended: its queued after hooks run now (empty after a rollback)
80
+ ops._drainRolled(); // op:rolledBack, now that nothing of the failed run is left
80
81
  }
81
82
  }