threedog 2.2.2 → 2.3.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 (194) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/README.md +4 -4
  3. package/core/assets/Animator.js +66 -12
  4. package/core/assets/ik.js +144 -18
  5. package/core/assets/maskLayer.js +377 -0
  6. package/core/assets/rootMotion.js +148 -0
  7. package/core/audio/Audio.js +100 -4
  8. package/core/base/errorCodes.js +6 -369
  9. package/core/base/errorCodesModules.js +378 -0
  10. package/core/engine/Engine.js +8 -5
  11. package/core/engine/Loading.js +8 -4
  12. package/core/engine/copies.js +1 -1
  13. package/core/engine/headlessLoad.js +15 -4
  14. package/core/engine/lifecycle.js +1 -0
  15. package/core/engine/loop.js +22 -3
  16. package/core/engine/moduleSlots.js +3 -7
  17. package/core/engine/modules.js +30 -58
  18. package/core/engine/startup.js +3 -3
  19. package/core/input/Input.js +7 -3
  20. package/core/input/inputContext.js +3 -2
  21. package/core/input/inputSeat.js +1 -1
  22. package/core/inspect/DebugOverrides.js +1 -1
  23. package/core/inspect/Describe.js +7 -2
  24. package/core/inspect/describeRender.js +4 -1
  25. package/core/inspect/describeText.js +2 -2
  26. package/core/inspect/metadata.generated.js +371 -74
  27. package/core/inspect/pictureMenu.js +2 -0
  28. package/core/inspect/pictureWriters.js +4 -3
  29. package/core/ops/Ops.js +9 -3
  30. package/core/ops/actor.js +10 -0
  31. package/core/ops/control.js +17 -6
  32. package/core/ops/holds.js +1 -1
  33. package/core/ops/opsAtomic.js +6 -1
  34. package/core/ops/opsGuard.js +2 -2
  35. package/core/ops/owned.js +37 -11
  36. package/core/ops/sharedPoint.js +5 -1
  37. package/core/ops/stacks.js +30 -7
  38. package/core/saves/Saves.js +0 -2
  39. package/core/saves/saveApply.js +7 -7
  40. package/core/saves/session.js +6 -3
  41. package/core/saves/stateReplace.js +71 -41
  42. package/core/scene/Rays.js +74 -26
  43. package/core/scene/gameLights.js +19 -11
  44. package/core/scene/sceneDelta.js +8 -4
  45. package/core/stream/chunkStream.js +21 -0
  46. package/core/stream/dirtyWatch.js +37 -0
  47. package/core/time/skip.js +9 -6
  48. package/core/time/time.js +72 -18
  49. package/docs/AI.md +22 -21
  50. package/docs/API.md +5 -4
  51. package/docs/CODEMAP.md +16 -10
  52. package/docs/COMMANDS.md +5 -5
  53. package/docs/CONVENTIONS.md +9 -25
  54. package/docs/api/ambience.md +1 -0
  55. package/docs/api/assets.md +10 -3
  56. package/docs/api/audio.md +5 -3
  57. package/docs/api/decals.md +16 -0
  58. package/docs/api/engine.md +1 -0
  59. package/docs/api/tools.md +3 -1
  60. package/docs/api/water.md +3 -0
  61. package/docs/recipes/09-materials-lights-models.md +15 -1
  62. package/docs/recipes/13-animation.md +51 -10
  63. package/docs/recipes/16-dev-bridge.md +1 -1
  64. package/docs/recipes/31-audio.md +15 -9
  65. package/docs/recipes/34-environment-lighting.md +11 -1
  66. package/docs/recipes/44-water-weather-hooks.md +1 -0
  67. package/examples/action/.threedog/content-index.json +1 -0
  68. package/examples/perf-island/.threedog/content-index.json +1 -0
  69. package/examples/plain-picture/.threedog/content-index.json +1 -0
  70. package/examples/rc2d/.threedog/content-index.json +1 -0
  71. package/examples/styletest/.threedog/content-index.json +1 -0
  72. package/examples/techniques/outlines-and-rim/main.js +1 -1
  73. package/examples/techniques/procedural-surface/main.js +1 -1
  74. package/examples/techniques/stylized-shading/main.js +1 -1
  75. package/examples/webgpu-tsl/.threedog/content-index.json +1 -0
  76. package/examples/world/.threedog/content-index.json +1 -0
  77. package/index.d.ts +6 -2
  78. package/index.js +3 -2
  79. package/llms.txt +11 -10
  80. package/modules/ambience/Ambience.js +97 -15
  81. package/modules/camera/common.js +18 -12
  82. package/modules/characters/Character.js +30 -3
  83. package/modules/characters/NPC.js +2 -5
  84. package/modules/characters/astar.js +45 -14
  85. package/modules/characters/movers/rapier.js +53 -41
  86. package/modules/characters/movers/simple.js +37 -24
  87. package/modules/characters/npcView.js +2 -2
  88. package/modules/characters/pathAsync.js +3 -3
  89. package/modules/collision/contract.js +2 -2
  90. package/modules/content/index.js +3 -0
  91. package/modules/content/models.js +11 -4
  92. package/modules/content/templates.js +11 -11
  93. package/modules/debug/DebugPanel.js +1 -0
  94. package/modules/decals/Decals.js +393 -0
  95. package/modules/decals/index.js +1 -0
  96. package/modules/gameplay/Container.js +2 -0
  97. package/modules/gameplay/Containers.js +17 -3
  98. package/modules/gameplay/Dialogue.js +1 -1
  99. package/modules/gameplay/Interactions.js +7 -6
  100. package/modules/gameplay/Inventory.js +5 -1
  101. package/modules/gameplay/Quests.js +4 -3
  102. package/modules/gameplay/inventoryOps.js +2 -2
  103. package/modules/gameplay/pickups.js +32 -12
  104. package/modules/gameplay/questSave.js +2 -2
  105. package/modules/grid/index.js +8 -2
  106. package/modules/hud/index.js +1 -1
  107. package/modules/level/heightfield.js +1 -0
  108. package/modules/level/index.js +3 -2
  109. package/modules/level/nodes.js +2 -1
  110. package/modules/lights/index.js +27 -4
  111. package/modules/lights/slots.js +33 -16
  112. package/modules/nav/contract.js +4 -4
  113. package/modules/nav/index.js +6 -2
  114. package/modules/net/Client.js +24 -11
  115. package/modules/net/Host.js +73 -20
  116. package/modules/net/index.js +33 -21
  117. package/modules/net/sync.js +38 -8
  118. package/modules/net/transports.js +7 -3
  119. package/modules/particles/Particles.js +11 -4
  120. package/modules/particles/contract.js +6 -6
  121. package/modules/particles/effect.js +0 -1
  122. package/modules/rigid/RigidBodies.js +69 -57
  123. package/modules/rigid/Vehicles.js +8 -7
  124. package/modules/rigid/ragdoll.js +4 -6
  125. package/modules/rigid/rapierCompat.js +90 -0
  126. package/modules/rigid/sync.js +2 -5
  127. package/modules/settings/Settings.js +10 -4
  128. package/modules/sky/Sky.js +10 -2
  129. package/modules/sky/environment.js +29 -13
  130. package/modules/sky/frame.js +2 -2
  131. package/modules/sky/shader.js +5 -2
  132. package/modules/sky/skyModule.js +2 -2
  133. package/modules/swarm/Swarm.js +3 -2
  134. package/modules/swarm/grid.js +12 -7
  135. package/modules/terrain/ChunkManager.js +16 -26
  136. package/modules/triggers/index.js +5 -6
  137. package/modules/vegetation/draw.js +62 -26
  138. package/modules/vegetation/groundChunks.js +8 -22
  139. package/modules/water/Water.js +152 -24
  140. package/modules/water/surface.js +43 -20
  141. package/modules/weather/weatherDraw.js +4 -1
  142. package/modules/world/World.js +21 -2
  143. package/modules/world/index.js +5 -0
  144. package/modules/world/persist.js +1 -0
  145. package/modules/world/records.js +3 -1
  146. package/modules/world/sim.js +3 -2
  147. package/modules/world/simFar.js +4 -2
  148. package/modules/world/state.js +7 -1
  149. package/package.json +2 -2
  150. package/presets.js +30 -0
  151. package/render/PostFX.js +24 -17
  152. package/render/backend.js +72 -31
  153. package/render/cascades.js +25 -14
  154. package/render/cascades.tsl.js +32 -21
  155. package/render/fogLook.js +2 -1
  156. package/render/fx/library.tsl.js +1 -1
  157. package/render/fx/particles.tsl.js +4 -18
  158. package/render/fx/pcss.tsl.js +2 -2
  159. package/render/fx/postWebGPU.tsl.js +47 -25
  160. package/render/fx/sky.tsl.js +6 -18
  161. package/render/fx/uniforms.tsl.js +16 -0
  162. package/render/fx/water.tsl.js +24 -5
  163. package/render/fxNumbers.js +2 -0
  164. package/render/impostor.tsl.js +10 -6
  165. package/render/lights.js +6 -6
  166. package/render/occlusion.js +17 -6
  167. package/render/patches.js +40 -28
  168. package/render/postWebGL.js +6 -4
  169. package/render/reflectionProbes.js +302 -0
  170. package/render/shaderErrors.js +18 -8
  171. package/render/shadowCache.tsl.js +10 -5
  172. package/render/shadows.js +70 -49
  173. package/render/threeCompat.js +166 -0
  174. package/types/core.d.ts +33 -3
  175. package/types/gameplay.d.ts +80 -0
  176. package/types/generated/core/audio/Audio.d.ts +18 -1
  177. package/types/generated/core/ops/Ops.d.ts +2 -1
  178. package/types/generated/core/ops/control.d.ts +7 -3
  179. package/types/generated/core/saves/session.d.ts +4 -1
  180. package/types/generated/modules/ambience/Ambience.d.ts +6 -0
  181. package/types/generated/modules/debug/DebugPanel.d.ts +1 -0
  182. package/types/generated/modules/grid/index.d.ts +27 -3
  183. package/types/generated/modules/net/index.d.ts +8 -3
  184. package/types/generated/modules/sky/Sky.d.ts +1 -0
  185. package/types/generated/modules/water/Water.d.ts +15 -0
  186. package/types/generated/modules/world/index.d.ts +5 -0
  187. package/types/generated/render/patches.d.ts +5 -0
  188. package/types/physics.d.ts +66 -9
  189. package/types/tsl.d.ts +2 -0
  190. package/types/world.d.ts +2 -0
  191. package/ui/Parts.js +3 -2
  192. package/docs/MIGRATING-0.7.md +0 -39
  193. package/docs/MIGRATING-0.8.md +0 -171
  194. package/modules/rigid/refresh.js +0 -10
@@ -0,0 +1,378 @@
1
+ // Module and domain error codes (merged into ERROR_CODES by errorCodes.js).
2
+ // Plain data with no imports (node tools load ERROR_CODES through threedog/error-hints).
3
+
4
+ /** @type {Record<string, { fix: string, docs: string[], brief?: boolean }>} */
5
+ export const MODULE_ERROR_CODES = {
6
+ 'ambience-rule': {
7
+ docs: ['api/ambience.md', 'api/audio.md'],
8
+ fix: 'An ambience rule names no sound: give sound: a name registered in audio.sounds, or use a reverb / filter acoustic zone rule without sound.' },
9
+ 'camera-clamped': {
10
+ docs: ['recipes/21-camera.md', 'api/cameraRig.md'],
11
+ fix: 'A camera value the game asked for is outside the range of the rig, so the rig kept it inside, as documented. Widen the range the message names: followCamera({ minDistance, maxDistance, minPitch, maxPitch }), or set it on engine.cameraRig.' },
12
+ 'camera-option': {
13
+ docs: ['recipes/21-camera.md §6', 'api/cameraRig.md'],
14
+ fix: 'A camera option is wrong: projection is \'perspective\' or \'orthographic\' (orthographic needs size > 0 and an EngineCamera or a real OrthographicCamera), engine.camera takes a THREE.PerspectiveCamera or THREE.OrthographicCamera, ' +
15
+ 'ground / shots use the values the message lists.' },
16
+ 'character-option': {
17
+ docs: ['api/characters.md', 'recipes/13-animation.md', 'recipes/02-npc.md'],
18
+ fix: "A character / NPC option or model name is wrong: the message names the option and the accepted forms, and an unknown model lists the registered ones. An NPC's interact is { op: 'name', args?, ... } or null; characters.support(object, { carry, id }) takes an Object3D with meshes, a listed carry mode and a unique id." },
19
+ 'collision-misuse': {
20
+ docs: ['api/collision.md'],
21
+ fix: 'A collision call got a wrong argument, e.g. collision.addBlocked needs fn(x, z) => boolean.' },
22
+ 'content-id': {
23
+ docs: ['recipes/20-content-actions-save.md §"Save format"', 'api/content.md'],
24
+ fix: 'A content id is invalid (contains # or /) or defined twice across content files, or a rename table is malformed. Ids are ' +
25
+ 'unique per kind across files; saves match on them, so rename through the rename table.' },
26
+ 'content-misuse': {
27
+ docs: ['recipes/20-content-actions-save.md', 'api/content.md'],
28
+ fix: 'content.load / content files hold something the loader cannot use (an unknown key, a rule needing a module that is not ' +
29
+ 'installed, a malformed field table). Install the module named in the message or fix the entry it points at.' },
30
+ 'content-pack': {
31
+ docs: ['recipes/20-content-actions-save.md §1b', 'api/content.md'],
32
+ fix: 'A content pack is not a plain object, carries code where data is expected, or defines a key another pack already has. ' +
33
+ 'Give each pack its own ids.' },
34
+ 'content-template': {
35
+ docs: ['recipes/30-templates.md', 'api/content.md'],
36
+ fix: 'A content template definition or instance is invalid (missing model, an onUse without op, a key that is not a template ' +
37
+ 'field, a module it needs not installed). The message names the template and the field to fix.' },
38
+ 'inventory-misuse': {
39
+ docs: ['recipes/03-items-pickups.md', 'api/inventory.md'],
40
+ fix: "inventory.define(id): an item id may not contain '#', which marks entry keys (sword#3). Pick an id without it." },
41
+ 'grids-misuse': {
42
+ docs: ['recipes/29-grid.md', 'api/grids.md'],
43
+ fix: "grids(): a grid or item name is unknown or defined twice, a mapping lacks toCell / center, or a layer / preview material is not a three.js material or has nothing to draw on. Use a listed name, or the form in the message." },
44
+ 'content-layer-ignored': {
45
+ docs: ['recipes/05-props-bake.md'],
46
+ fix: 'collide.layer works on an upright prop only (a tilted one is held by collider3d, which has no layers): stand the model up, or drop the layer; until then it stops every mover.' },
47
+ 'level-layer-ignored': {
48
+ docs: ['recipes/10-blender-level.md §1', 'api/level.md'],
49
+ fix: 'The custom property layer on a col_ mesh must be one non-empty text (the name a character lists in passes). Fix it in Blender; until then the wall stops every mover.' },
50
+ 'level-node': {
51
+ docs: ['recipes/10-blender-level.md', 'api/level.md'],
52
+ fix: 'A level node points at content that is not defined, clashes with another record, or is used before the level loaded. Define ' +
53
+ 'the content id, or wait for level:loaded.' },
54
+ 'light-type': {
55
+ docs: ['api/lightPool.md'],
56
+ fix: 'lights / lightPool got a light type it does not pool. Use one of the listed types and reserve slots for it.' },
57
+ 'music-track': {
58
+ docs: ['api/music.md'],
59
+ fix: 'A music track is defined twice or has neither url nor stems. Define each track once with { url } or { stems }.' },
60
+ 'net-option': {
61
+ docs: ['recipes/27-net.md', 'api/net.md'],
62
+ fix: 'net() needs role \'host\' or \'client\' and a transport; reconnect() is for clients only.' },
63
+ 'rigid-misuse': {
64
+ docs: ['recipes/11-physics.md §3', 'api/rigid.md'],
65
+ fix: "The message says which: an id already used by another body or vehicle (give each its own id); a mesh that another body or a character already owns (one object, one physics owner: remove the first, or give the second its own object); joints lost when newGame / a load rebuilt the physics world (re-create them in a rigid:rebuilt listener, recipe 11 section 3 \"Joints\"); rigid.ragdoll() got something it cannot drive (a skinned character out of its vehicle, with the bones named when they cannot be read); or a moving body left the terrain colliders and froze (raise rigid({ terrainRing }) if it must keep moving there, recipe 11 section 3)." },
66
+ 'settings-row': {
67
+ docs: ['api/settings.md'],
68
+ fix: 'A settings row nobody owns or nobody draws. settings.set() with a key no row owns: use a listed key, add the tab that has the row (settings({ sections })) or define it: settings.define(key, default, apply). A defined row the menu cannot draw, in a missing tab, or drawn twice: give it min/max or options, a tab that exists, or menu: false when your own tab draws it.' },
69
+ 'settings-tab': {
70
+ docs: ['api/settings.md'],
71
+ fix: 'settings({ sections }) contains a built-in section that does not exist. Use a listed name, or register one with engine.settings.addSection(id, { title, render }).' },
72
+ 'time-owner-conflict': {
73
+ docs: ['recipes/06-clock-events.md §"The time table: read the current game time"', 'api/calendar.md'],
74
+ fix: 'calendar() and sky({ time }) both set the time of day. calendar owns time while it is installed: move the starting time to calendar({ time }) and remove sky({ time }).' },
75
+ 'save-provider-changed': {
76
+ docs: ['recipes/20-content-actions-save.md §"Save failures and versions"', 'api/saves.md'],
77
+ fix: 'The module of a save part was unloaded or replaced while an earlier part of the same load was still loading, so the data read for it has nobody to take it. The load failed and rolled back (the data stays in the save). Do not unload or replace modules while a load is in flight; retry the load.' },
78
+ 'rollback-incomplete': {
79
+ docs: ['recipes/20-content-actions-save.md §"Save failures and versions"', 'api/saves.md'],
80
+ fix: 'A rollback could not restore one save part: its save() gave nothing before and it has no new-game state to go back to, so it keeps what the failed load or op wrote. ' +
81
+ 'Make that part\'s save() return restorable data (or give it a new-game state), then reload the page before retrying.' },
82
+ 'clock-time': {
83
+ docs: ['recipes/06-clock-events.md', 'api/calendar.md'],
84
+ fix: "A clock time (?time= in the URL, calendar({ time }), sky({ time }), a schedule's at, calendar.at / between, skip({ to })) is 'HH:MM' such as '18:30' or a fraction of the day 0-1 such as 0.75; words like 'night' are not times." },
85
+ 'calendar-option': {
86
+ docs: ['recipes/06-clock-events.md', 'api/calendar.md'],
87
+ fix: 'A calendar option, season name or scenario season is wrong (day length not > 0, a season list entry without name / days, a season the ' +
88
+ 'calendar does not have). Day, time, seasons and hours per day are calendar({...}) options; sky({ time }) is only the fixed time drawn without a calendar.' },
89
+ 'sky-option': {
90
+ docs: ['recipes/08-weather-sky.md', 'api/sky.md'],
91
+ fix: 'A sky or clouds option has a wrong value (day length, days and seasons are calendar() options). Own GLSL goes through ' +
92
+ 'engine.sky.clouds() and engine.sky.layer(), not an option key. The message lists the accepted values.' },
93
+ 'terrain-chunk-failed': {
94
+ docs: ['recipes/28-terrain.md §7', 'api/terrain.md'],
95
+ fix: 'A terrain chunk failed on every try and stays empty (no ground, no collision there). Usually the height / groundType / placement rule ' +
96
+ 'throws at that spot: fix what it reads, then engine.terrain.retry() sends the failed chunks again (terrain:chunkFailed names each one).' },
97
+ 'terrain-option': {
98
+ docs: ['recipes/28-terrain.md', 'api/terrain.md'],
99
+ fix: 'A terrain option or terrain edit is wrong (shape mask missing, a brush number not a number, an unknown paint). Use the form ' +
100
+ 'in the message.' },
101
+ 'vegetation-option': {
102
+ docs: ['api/vegetation.md', 'recipes/36-ground-plants.md §"Plants and wind"'],
103
+ fix: 'A vegetation option is wrong: positions entries, densityMap form, fade range or a model with several materials. Fix the ' +
104
+ 'entry the message points at.' },
105
+ 'vegetation-ignored': {
106
+ docs: ['api/vegetation.md', 'recipes/36-ground-plants.md §"Plants and wind"'],
107
+ fix: 'A model given to vegetation.define has an attribute (uv, color ...) on only some meshes; one instanced geometry keeps only what every mesh has, so its ' +
108
+ 'material draws without it. Give every mesh the attribute (a plain uv / white color on the parts that need none), or define the parts as separate species.' },
109
+ 'water-option': {
110
+ docs: ['api/water.md', 'recipes/44-water-weather-hooks.md'],
111
+ fix: 'A water option is wrong; own GLSL goes through engine.water.shader({ wave, surface }) and must define the function the message names.' },
112
+ 'weather-option': {
113
+ docs: ['api/weather.md', 'recipes/44-water-weather-hooks.md'],
114
+ fix: "A weather type, field, pool, particle definition or weather.set argument is wrong. The message lists the defined types and the accepted forms." },
115
+ 'world-option': {
116
+ docs: ['recipes/18-world.md', 'api/world.md'],
117
+ fix: 'A world option is wrong (an anchor shape, a simulate channel that is not a time channel). Use the form in the message.' },
118
+ 'material-option': {
119
+ docs: ['recipes/09-materials-lights-models.md §1', 'recipes/43-shader-patches-surfaces.md §"Ready-made effects: `detail`"'],
120
+ fix: 'A material / surface / detail / lighting spec is wrong: an unknown type, texture slot or setting, or GLSL that does not define ' +
121
+ 'the function the slot expects. The message names the key and the accepted values.' },
122
+ 'post-effect': {
123
+ docs: ['api/post.md', 'recipes/52-around-the-picture.md §"Post effect chain"'],
124
+ fix: 'A post effect is malformed or clashes: engine.post.add takes a three.js Pass, a node function (WebGPU) or { name, create | node | fuse }, ' +
125
+ 'with a unique name and a known slot. Change an existing effect with its handle (engine.post.get(name).set(params), .enabled); add one with engine.post.add (the one way).' },
126
+ 'post-effect-failed': {
127
+ docs: ['recipes/52-around-the-picture.md §"Post effect chain"'],
128
+ fix: "The device could not build the shader of a post effect's own pass (a driver compiler error, or a device limit), so the engine holds that effect off and " +
129
+ 'the frame draws without it. The message ends with what the device said. Same picture on other devices: nothing to do. ' +
130
+ 'To run it here: change the option the error points at, then remove the effect and add it again.' },
131
+ 'own-frame': {
132
+ docs: ['THREE.md', 'recipes/52-around-the-picture.md §"Post effect chain"'],
133
+ fix: 'The game draws the canvas itself (its own composer.render() / renderer.render outside engine.onRender), so the engine yielded ' +
134
+ 'the frame. Intended: nothing to do. To get the engine frame back delete your render call; to add a pass to it use engine.post.add(pass).' },
135
+ 'shader-patch': {
136
+ docs: ['recipes/43-shader-patches-surfaces.md §"Patch a slot"'],
137
+ fix: 'A shader patch is malformed: glsl goes with a slot name (a string per slot), raw anchors use vertex / fragment, and the ' +
138
+ 'material must provide what the patch needs. The message lists the slot names.' },
139
+ 'renderer-backend': {
140
+ docs: ['recipes/50-own-renderer.md'],
141
+ fix: "The WebGPU route could not start as asked: WebGPU is unavailable with fallback: 'error', a NodeMaterial met fallback: 'webgl' " +
142
+ "(WebGLRenderer cannot draw TSL; use fallback: 'webgl2'), a WebGL-only material is in the scene, or threedog/tsl is not imported. The message names which." },
143
+ 'photo-path-trace': {
144
+ docs: ['recipes/26-ui-parts.md §"Photo mode: the picture"', 'api/photo.md'],
145
+ fix: "photo.trace() could not trace: the game's import is missing (npm i -D three-gpu-pathtracer three-mesh-bvh, then photo({ pathTracer: () => import('three-gpu-pathtracer/webgpu') }), or 'three-gpu-pathtracer' on WebGL), " +
146
+ 'the page runs the WebGL2 fallback, no sample arrived in time, a traced photo is still accumulating, or the engine was disposed. The message names which.' },
147
+ 'ui-misuse': {
148
+ docs: ['recipes/26-ui-parts.md', 'api/hud.md'],
149
+ fix: 'A UI part, theme or toast call is wrong (an unknown part or verb, a value of the wrong type, the engine not passed first). ' +
150
+ 'The message lists the defined parts and the accepted forms.' },
151
+ 'module-needs': {
152
+ docs: ['recipes/14-custom-module.md', 'recipes/18-world.md', 'api/engine.md'],
153
+ fix: "A call needs a module that is not installed or not ready yet (the data of NPCs, props and pickups lives in world(), pickups need interactions(), timeline say needs dialogue(), rigid bodies need engine.start() first). Install the module named in the message before the one that needs it (openWorld() already includes world()), or call after engine:ready." },
154
+ 'tween-property': {
155
+ docs: ['api/timeline.md'],
156
+ fix: 'A tween names a property path that does not exist or is not a number / color / vector. Check the path (a.b.c) against the object.' },
157
+ 'level-size': {
158
+ docs: ['api/level.md'],
159
+ fix: 'The level is larger than the heightfield resolution allows, so the cell was enlarged (coarser ground). Pass a larger ' +
160
+ 'cellSize on purpose, or split the level.' },
161
+ 'nav-build': {
162
+ docs: ['recipes/12-navmesh.md', 'api/nav.md'],
163
+ fix: 'The navmesh could not be built from this geometry; paths fall back. The message has the builder\'s reason (usually too few ' +
164
+ 'walkable triangles or wrong cell sizes).' },
165
+ 'fog-fallback': {
166
+ docs: ['recipes/56-webgpu-tsl.md §"Sky and fog hooks"', 'recipes/34-environment-lighting.md §"Fog: plain three.js, signals, your own math"'],
167
+ fix: "On WebGPU the engine reads the color of scene.fogNode = fog(color, factor) only when color is a THREE.Color, color(..) or uniform(Color) (new THREE.Color(0xaabbcc), color(0xaabbcc)). With a computed color the sky dome's fog band, the water's grazing reflection and the horizon check cannot follow your fog. Give fog() a color(..) or uniform(Color), or set scene.fog too." },
168
+ 'nav-fallback': {
169
+ docs: ['recipes/12-navmesh.md §5', 'api/nav.md'],
170
+ fix: 'nav() builds its mesh from the ground of a level. With none (procedural terrain, or a level still loading) paths use collision A*: they work but ignore nav links, crowds and floor changes. Load a level for a navmesh, or ignore this if A* is what you want.' },
171
+ 'nav-link': {
172
+ docs: ['recipes/12-navmesh.md §6', 'api/nav.md'],
173
+ fix: 'A nav link needs both ends within its radius of the mesh (which stops about the agent radius short of every edge) and within maxClimb of its height, and the places ' +
174
+ 'where they meet the mesh in the same tile or neighbouring tiles (a tile is tileSize x cellSize meters). Move the end onto walkable ground, raise radius, split a long link in two, or raise tileSize.' },
175
+ 'nav-height': {
176
+ docs: ['recipes/12-navmesh.md §5', 'api/nav.md'],
177
+ fix: 'A height given to a path or a stop is more than a body height from every walkable surface at that spot, so the nearest surface was used. Leave y out to mean the ground, or give the height of the floor you mean.' },
178
+ 'grid-overlap': {
179
+ docs: ['recipes/29-grid.md §2', 'api/grids.md'],
180
+ fix: 'Two grid items claim the same cell; the second is skipped. Move one, or remove the other first.' },
181
+ 'grid-orphan': {
182
+ docs: ['recipes/29-grid.md §2', 'api/grids.md'],
183
+ fix: 'A placed record names an item the content no longer defines, so it has no size and takes no cells; the record is kept. Define the item again, or remove the record with grid.remove.' },
184
+ 'module-requires': {
185
+ docs: ['recipes/14-custom-module.md §2', 'api/engine.md'],
186
+ fix: "A module requires a capability ('world', 'inventory') no installed module provides yet. Install the engine's part of that name first (engine.use(world(), mine())), or your own module with provides: ['<name>'] (a typo is suggested in the message)." },
187
+ 'module-provides': {
188
+ docs: ['recipes/14-custom-module.md §2'],
189
+ fix: "provides is a list of exclusive slot names (provides: ['inventory']); a slot name must not be a shared value's name." },
190
+ 'module-replaces': {
191
+ docs: ['recipes/14-custom-module.md §2'],
192
+ fix: "engine.use(mine(), { replaces: 'slot' }): an installed module must hold the slot, a module in the same call must provide it, and no other module may require the old one by its module name (require the slot). The world holds every record, so it is never replaced under modules that use it or after start(): install your world before the modules that need it." },
193
+ 'module-cycle': {
194
+ docs: ['recipes/14-custom-module.md §2'],
195
+ fix: 'before / after constraints of two or more modules point at each other. Remove one of them or give a module a different stage.' },
196
+ 'module-type': {
197
+ docs: ['recipes/14-custom-module.md §"Type: what the module"'],
198
+ fix: "A module's type names what it owns: 'rules' (game logic, the default), 'world' | 'picture' | 'actor' | 'ui' | 'net' | 'tool' (core/engine/moduleTypes.js). This one is not a type: a typo?" },
199
+ 'module-type-rule': {
200
+ docs: ['recipes/14-custom-module.md §"Type: what the module"'],
201
+ fix: 'A warning, the call went through: a module did something its type does not usually own (a picture module defining an op or writing world records, a ui module binding keys or registering a save part). Move that part into a module of the right type, or change the type, as the message says, or leave it if the game means it.' },
202
+ 'module-stage': {
203
+ docs: ['recipes/14-custom-module.md §2'],
204
+ fix: 'Modules sort by stage (+ before / after), not by number. Use one of the listed stage names.' },
205
+ 'module-name': {
206
+ docs: ['recipes/14-custom-module.md'],
207
+ fix: 'The module name becomes engine.<name>; it must not be an existing engine property, another module name or a capability another module provides (requires and engine.<name> would reach different modules).' },
208
+ 'module-handle': {
209
+ docs: ['recipes/14-custom-module.md §2', 'api/engine.md'],
210
+ fix: "ctx.track(handle) (the ctx install / init receive) and engine.session.track(handle) take something with remove(), such as the result of events.on / onFixed / clock.after; ctx.borrow(obj, values) takes two objects, and one property has one holder at a time: end the first borrow, or use a shared point (engine.mod) when several parties want the value. A handle tracked after its module was unloaded (an async init resuming after replaces / unload) is removed at once: check what the init does after its await." },
211
+ 'module-called': {
212
+ docs: ['recipes/01-new-game.md', 'api/engine.md'],
213
+ fix: 'engine.use() takes the module object: write engine.use(sky()), not engine.use(sky).' },
214
+ 'describe-name': {
215
+ docs: ['recipes/16-dev-bridge.md', 'api/engine.md'],
216
+ fix: 'describe.add names share one namespace with the standard fields and module names. Pick a unique name.' },
217
+ 'input-keys': {
218
+ docs: ['recipes/01-new-game.md', 'api/input.md'],
219
+ fix: "Keys are names like 'KeyE', 'Space', 'PadA', 'Mouse0'. The engine binds no gameplay key on its own and modules take no keys option: bind the action the module declares, createEngine({ bindings: { ...presets.bindings.<name> } }) or engine.input.bind('<action>', ['KeyX']); [] = deliberately no key." },
220
+ 'interaction-option': {
221
+ docs: ['api/interactions.md', 'recipes/03-items-pickups.md'],
222
+ fix: "interactions.add(): hold is seconds the key stays down (a number >= 0), radius is meters > 0 (Infinity = from anywhere), counter is a HUD counter name, and a once item needs its own stable id or mesh.name. Fix the option the message names." },
223
+ 'hud-option': {
224
+ docs: ['api/hud.md', 'recipes/26-ui-parts.md'],
225
+ fix: "A hud element option is wrong: anchor is one of the listed corners / edges, a counter value is a number or text, and hud.bump needs a counter that shows a number. Fix the option the message names." },
226
+ 'describe-threw': {
227
+ docs: ['recipes/14-custom-module.md §2', 'api/engine.md'],
228
+ fix: "A module's describe(e, ctx) hook threw; describe() put { error, code } under that module's name and kept the rest. Fix the " +
229
+ 'hook named in the message (it must return plain data or nothing).' },
230
+ 'world-plain': {
231
+ docs: ['recipes/18-world.md §9', 'api/world.md'],
232
+ fix: "A saved record holds a three.js object, function or class instance. World data must be JSON-like (it is saved and may go to a worker): write { x, y, z } for a vector. A model: world.present('crate', { build: rec => mesh }), then world.view(id) gets it. Nothing to save: world.add(rec, { save: false }) may hold anything." },
233
+ 'pickup-misuse': {
234
+ docs: ['recipes/03-items-pickups.md', 'api/inventory.md'],
235
+ fix: "pickups.spawn() got a wrong value (give is an item id, which needs inventory(), or a function (e, { actor }) => result; radius is a positive number), or engine.pickups.material got something that is not a three.js material." },
236
+ 'world-id': {
237
+ docs: ['recipes/18-world.md', 'api/world.md', 'recipes/03-items-pickups.md'],
238
+ fix: "Two things claim one id: every world record (props, pickups, NPCs, template instances) shares one id space. Omit id to auto-number, give each its own id, or use world.set(id, patch) to update the existing record." },
239
+ 'world-record': {
240
+ docs: ['recipes/18-world.md', 'api/world.md'],
241
+ fix: 'The id was never added, was removed, or is misspelled. world.query({ kind }) lists what exists.' },
242
+ 'world-add': {
243
+ docs: ['recipes/18-world.md', 'api/world.md'],
244
+ fix: 'world.add({ kind, position, ... }) needs a kind; initial records need a stable id; id and kind of an existing record cannot be changed by set().' },
245
+ 'world-present': {
246
+ docs: ['recipes/18-world.md', 'api/world.md'],
247
+ fix: 'present(kind, { build }) must return a three.js object (or use show: rec => false to hide). Errors inside build also land here.' },
248
+ 'bad-position': {
249
+ docs: ['CONVENTIONS.md', 'api/world.md'],
250
+ fix: "A position was NaN, out of range or the wrong shape: a Vector3 used like an array (v[0]), a missing field, a division by zero upstream, or the old (x, z) number form. A position is one argument: a Vector3, [x, y, z] or { x, z }; a 2-element [x, z] array does not work." },
251
+ 'state-value': {
252
+ docs: ['recipes/16-dev-bridge.md'],
253
+ fix: 'applyState got a value it cannot use: the message names the key and the accepted forms. Nothing was applied.' },
254
+ 'content-place': {
255
+ docs: ['recipes/20-content-actions-save.md §1b', 'api/content.md'],
256
+ fix: 'content.load references a place that has no coordinates, or needs world() for props / pickups. Give the place in content.load({ places }) or add the marker to the level.' },
257
+ 'container': {
258
+ docs: ['recipes/03-items-pickups.md §"Chests / corpses"', 'api/inventory.md'],
259
+ fix: 'Container id / capacity / count was invalid, or a container used in transfer was never created. Create it first with inventory.container(id, { capacity }).' },
260
+ 'npc-behavior': {
261
+ docs: ['recipes/02-npc.md §"Changing behavior / custom"', 'api/characters.md'],
262
+ fix: 'The schedule / behavior name is unknown. Register it with engine.npcs.behavior(name, { near, far }) before npcs.add, or use a listed built-in.' },
263
+ 'unknown-option': {
264
+ docs: ['api/engine.md', 'CONVENTIONS.md'],
265
+ fix: 'An options key is misspelled or does not exist for this call (ignored, so the feature silently does nothing). Use the suggested key or one of the listed options.' },
266
+ 'unknown-name': {
267
+ docs: ['CONVENTIONS.md', 'api/engine.md'],
268
+ fix: 'A name (action, item, asset, weather, text key, ...) was never registered or has a typo. The message lists the registered names.' },
269
+ 'event-typo': {
270
+ docs: ['api/events.md'],
271
+ fix: "This event name is one letter or so from an engine event, and nothing emits it. Use the suggested name; if this really is a new event of your own, ignore the warning." },
272
+ 'owned-prop': {
273
+ docs: ['recipes/52-around-the-picture.md §"Who writes it"', 'THREE.md'],
274
+ fix: 'The engine wrote this value on its own (sky, camera, fog distance ...); your direct write took it over, so the engine no longer changes it. Intended: say so with the manual() call in the message. Not intended: give it back with manual(key, false) and adjust it with set(...).' },
275
+ 'picture-held': {
276
+ docs: ['recipes/62-picture-code.md §3f'],
277
+ fix: 'A picture value is held by a part (provides) and other code wrote it, so one of the two never reaches the screen. Delete the stray write; or swap the holder with engine.use(mine(), { replaces: slot }); or, when both need a say, make it a shared value the holder reads (recipes/62-picture-code.md §3f).' },
278
+ 'picture-leftover': {
279
+ docs: ['recipes/62-picture-code.md §3f'],
280
+ fix: "A picture part was removed and what it added stayed. In its install, hand each thing to ctx.track({ remove() { ... } }) (or undo it in dispose), so it goes with the part (recipes/62-picture-code.md §3f)." },
281
+ 'module-unuse': {
282
+ docs: ['recipes/14-custom-module.md §2'],
283
+ fix: "engine.unuse(name): the module must be installed, and no other module may still require it or a slot only it provides. Unload the dependent first, or swap the provider with engine.use(mine(), { replaces: 'slot' })." },
284
+ 'picture-conflict': {
285
+ brief: true,
286
+ docs: ['recipes/62-picture-code.md §3e'],
287
+ fix: 'Two places write this value, so one write never shows. Pick the one that owns the value and delete the other, or turn the second into a signal the owner reads (recipes/62-picture-code.md §3c). Both lines are in the message.' },
288
+ 'camera-kind': {
289
+ docs: ['recipes/21-camera.md', 'api/cameraRig.md'],
290
+ fix: 'setCamera() got an unknown camera kind. Use one of the listed kinds; for a camera of your own, take it with engine.takeCamera(owner) and place engine.camera yourself (recipes/21-camera.md).' },
291
+ 'camera-none': {
292
+ docs: ['recipes/21-camera.md', 'api/cameraRig.md'],
293
+ fix: 'setCamera() switches between camera kinds once a camera module is installed. Install one first: engine.use(fixedCamera({ position, lookAt })) (or followCamera / firstPersonCamera / rtsCamera), or name one: openWorld({ camera: \'follow\' }).' },
294
+ 'movement': {
295
+ docs: ['api/characters.md', 'api/engine.md'],
296
+ fix: "createEngine({ movement }): every movement value is a number > 0. A typo in a name gives undefined; the message names the key." },
297
+ 'commit-fallback': {
298
+ docs: ['api/jobs.md'],
299
+ fix: "commits.request() needs fallback: () => result. Async results apply at fixed steps; when a result is late, the fallback computes it on the main thread, so the outcome never depends on machine speed." },
300
+ 'asset-critical': {
301
+ docs: ['recipes/05-props-bake.md §3', 'api/assets.md'],
302
+ fix: 'An asset marked critical: true in the manifest (or an engine.loading.track step) failed, so start() stopped instead of starting a broken game. The line names the file, HTTP status and manifest. Fix the path or the file; if the game can run without it, drop critical so it falls back. engine.loading.list({ phase: "failed" }) or threedog loading shows every failure.' },
303
+ 'asset-missing-ref': {
304
+ docs: ['recipes/05-props-bake.md', 'api/assets.md'],
305
+ fix: 'The model file loaded, but a file it references (texture image or .bin) is missing, usually after moving the .gltf without its folder or a case mismatch in the referenced name. Export as .glb (everything in one file) or copy the referenced files next to it.' },
306
+ 'asset-needs': {
307
+ docs: ['recipes/05-props-bake.md §2f', 'api/assets.md'],
308
+ fix: 'A model file lacks a node or animation clip its manifest entry declares in needs: { nodes, clips }, usually a re-export that dropped or renamed it. The line names each missing part and the closest name in the file. Restore it in the model (Blender: keep the name, check the action is not unused and has a fake user or is in an NLA track), or change needs. `threedog assets check` reads the same declaration from the glb without running the game.' },
309
+ 'asset-not-loaded': {
310
+ docs: ['api/assets.md', 'recipes/05-props-bake.md'],
311
+ fix: 'assets.modelNow only hands out a model something already loaded; it never starts a load. A code-built model loads too (built, or read from the bake cache). Write `modelNow(name) ?? await model(name)`, or mark it preload: true and await assets.preload() before the code that must not wait.' },
312
+ 'asset-lod': {
313
+ docs: ['recipes/15-perf.md §4a', 'api/assets.md'],
314
+ fix: 'assets.lod and a prop\'s lod need level files from `threedog assets optimize --lod` (skipped models say why in its report), distances as rising meters, and levels made from the same version of the model. A LOD object is never batched, so for many copies of a light model drop lod and let engine.batching draw them.',
315
+ },
316
+ 'asset-fallback-cycle': {
317
+ docs: ['api/assets.md'],
318
+ fix: 'Entries name each other as fallback (A falls back to B, B back to A), so a failed load would wait on itself forever. The line lists the chain. Give one of them no fallback, or point it at a file that loads.' },
319
+ 'asset-load': {
320
+ docs: ['api/assets.md', 'recipes/05-props-bake.md'],
321
+ fix: "Read the reason in the message first. \"called before the backend is initialized\" means the load ran before engine.start() finished: await engine.start() first, or register the file in a manifest. Otherwise the file was not found (404) or is not valid. Check the path (files under public/ are served from /), the extension, and the case of the name. A file that is not critical falls back (a registered fallback, a stand-in texture, silence) and the game runs on; engine.loading.get(name) has the details." },
322
+ 'audio-unsupported': {
323
+ docs: ['api/audio.md'],
324
+ fix: 'No AudioContext in this browser / test environment. Guard calls with typeof AudioContext, or skip audio in headless tests.' },
325
+ 'indexeddb': {
326
+ docs: ['api/saves.md', 'recipes/20-content-actions-save.md §"Save failures and versions"'],
327
+ fix: 'Saves use IndexedDB, which is blocked in private windows and some embedded browsers. Test in a normal window, or export / import the save as a file.' },
328
+ 'gameplay-frozen': {
329
+ docs: ['recipes/16-dev-bridge.md §8', 'recipes/14-custom-module.md §2'],
330
+ fix: 'In dev / tests a gameplay error freezes the game on purpose, so half-applied state is not mistaken for normal. Read the error printed with it (engine.error has where + message), fix it, reload.' },
331
+ 'canvas-released': {
332
+ docs: ['api/engine.md'],
333
+ fix: 'engine.dispose() gave the WebGL context back to the browser, so that canvas cannot draw again. Create the new engine on a new canvas, or dispose the old one with engine.dispose({ keepContext: true }).' },
334
+ 'dispose-options': {
335
+ docs: ['api/engine.md'],
336
+ fix: 'engine.dispose() takes nothing or { keepContext: true }.' },
337
+ 'tsl-misuse': {
338
+ docs: ['recipes/43-shader-patches-surfaces.md'],
339
+ fix: "A threedog/tsl function cannot work here; the message says why. Usually: pass the engine, draw with the engine renderer, on a Mesh or InstancedMesh." },
340
+ 'vertex-inputs': {
341
+ docs: ['recipes/56-webgpu-tsl.md §"The engine\'s shader"'],
342
+ fix: "One program needs more vertex inputs than the device has (16 on most; WebGPU also 8 vertex buffers). The message counts what stacked up: geometry attributes the " +
343
+ "material reads, the instance matrix (4) and color (1), last frame's matrix for temporalAA's velocity buffer (4), engine patches, your own attribute nodes. " +
344
+ 'Drop what is not read, pack per-instance values into one vec4, or move them to a storage buffer (instancedArray from three/tsl); temporalAA off frees 4.' },
345
+ 'texture-bindings': {
346
+ docs: ['recipes/56-webgpu-tsl.md §"The engine\'s shader"'],
347
+ fix: "One shader stage binds more sampled textures or samplers than the device allows (16 each on most). The message names the material and counts them, with the shadow maps " +
348
+ "and environment / cube maps among them. Use fewer texture layers, pack maps into one texture's channels, or cast shadows from fewer lights." },
349
+ 'webgpu-needs-tsl': {
350
+ docs: ['recipes/56-webgpu-tsl.md §"Turning it on"'],
351
+ fix: "On WebGPURenderer the engine draws with node materials. Either threedog/tsl is not loaded (add import 'threedog/tsl' at the top of the entry), " +
352
+ 'or a part is written only as GLSL text: give it a tsl form too (a patch: tsl next to glsl; sky / fog hooks: { glsl, tsl }; a weather glsl spec: ' +
353
+ 'create(engine) returning your own node-material object). The message names the part.' },
354
+ 'swarm-full': {
355
+ docs: ['recipes/65-swarm.md §"Time, saves, limits"'],
356
+ fix: 'The swarm holds capacity objects and spawn returned -1, so that object does not exist. Raise capacity in engine.swarm({ capacity }), or remove objects sooner; describe().swarm.<name>.dropped counts the refused spawns.' },
357
+ 'swarm-handle': {
358
+ docs: ['recipes/65-swarm.md §"The id rule"'],
359
+ fix: 'free takes a handle, not a row: rows move when objects are removed. Inside onStep or near pass d.id[i]; to remove the object onStep is on, return false.' },
360
+ 'swarm-step': {
361
+ docs: ['recipes/65-swarm.md'],
362
+ fix: "swarm.onStep(fn) sets the one function that runs every fixed step: pass a function, once at setup, not from onFixed. Do several jobs in one function, or h.remove() the old one first." },
363
+ 'swarm-field': {
364
+ docs: ['recipes/65-swarm.md'],
365
+ fix: 'spawn() was given a name that is no column. Columns are x, y, z, the names in engine.swarm({ fields }), and with { color: true } r, g, b and the spawn key color.' },
366
+ 'swarm-name': {
367
+ docs: ['recipes/65-swarm.md §"Time, saves, limits"'],
368
+ fix: 'Swarm names are unique: they are the keys in describe() and in saves. Pick another name, or dispose() the old swarm first.' },
369
+ 'swarm-disposed': {
370
+ docs: ['recipes/65-swarm.md §"Time, saves, limits"'],
371
+ fix: 'This swarm was disposed. Make a new one with engine.swarm(options), or keep it and call clear() to empty it.' },
372
+ 'module-disabled': {
373
+ docs: ['recipes/14-custom-module.md §2'],
374
+ fix: 'A picture or ui module (particles, sky, music, a panel...) threw and was switched off; the game keeps running without it. The error printed with it is the real cause.' },
375
+ 'decal-option': {
376
+ docs: ['recipes/09-materials-lights-models.md §"Surface decals"', 'api/decals.md'],
377
+ fix: 'engine.decals (define, add, material) got a wrong argument: define takes a non-empty name first, add takes a position or raycast hit and an optional defined kind.' },
378
+ };
@@ -46,6 +46,7 @@ import { defineTerms } from '../../render/terms.js';
46
46
  import { defineView, defineTone, checkCamera } from '../scene/view.js';
47
47
  import { nameShaderErrors } from '../../render/shaderErrors.js';
48
48
  import { probeMethods } from '../../render/probes.js';
49
+ import { reflectionProbeMethods } from '../../render/reflectionProbes.js';
49
50
  import { lightmapMethods } from '../../render/lightmap.js';
50
51
  import { headlessSettled } from './headlessLoad.js';
51
52
  import { coded, codedError } from '../base/errorHints.js';
@@ -223,6 +224,8 @@ export class Engine {
223
224
  /** @internal installs (engine._modInst tokens) whose critical block was already reported */ this._modFatal = new WeakSet();
224
225
  this.waterBodies = [];
225
226
  clearHooks(this);
227
+ /** @internal lightweight pre-draw hooks (loop.js onBeforeDraw) */ this._beforeDraw = [];
228
+ /** @internal reused render hook context (loop.js _render) */ this._renderCtx = { renderer: null, scene: null, camera: null, dt: 0 };
226
229
  this._hookErrors = new Set(); // places that already reported an error (once per place, see errors.js)
227
230
  this.error = null; // gameplay error in dev/test: { where, message, cause?, docs? }; gameplay is frozen (see errors.js)
228
231
  /**
@@ -285,7 +288,7 @@ export class Engine {
285
288
  this._camera = cam;
286
289
  movedOwned(this, new Map([[old, cam], [old.position, cam.position], [old.quaternion, cam.quaternion]]));
287
290
  const c = this.renderer.domElement;
288
- this._oAspect.drive(c.width / c.height); // the buffer, as a resize leaves it: with pixelSize it is not the canvas box
291
+ if (c.width > 0 && c.height > 0) this._oAspect.drive(c.width / c.height); // the buffer, as a resize leaves it: with pixelSize it is not the canvas box
289
292
  }
290
293
 
291
294
  get waterLevel() { return this.ground.waterLevel; }
@@ -367,9 +370,9 @@ export class Engine {
367
370
  */
368
371
  setCamera(kind, opts) {
369
372
  const o = opts && typeof opts === 'object' ? `{ ${Object.keys(opts).join(', ')} }` : '';
370
- throw codedError('camera-none', `engine.setCamera('${kind}'${o ? ', ' + o : ''}) needs a camera module, and none is installed (openWorld({ camera }) `
371
- + `installs the one you name, camera: false installs none; a bare scene has none): install the kind you want once, engine.use(${kind === 'firstPerson' ? 'firstPersonCamera' : kind === 'rts' ? 'rtsCamera' : kind === 'follow' ? 'followCamera' : 'fixedCamera'}(${o})), `
372
- + `then setCamera switches between kinds`);
373
+ const factory = typeof kind === 'string' && /^\w+$/.test(kind) ? `${kind}Camera` : 'camera';
374
+ throw codedError('camera-none', `engine.setCamera('${kind}'${o ? ', ' + o : ''}) needs a camera capability provider, and none is installed: `
375
+ + `install one once with engine.use(${factory}(${o})), then setCamera switches between kinds`);
373
376
  }
374
377
 
375
378
  /** @internal Display name of a module (loading screen): module.<name> from the string table, else the module's own label */
@@ -377,5 +380,5 @@ export class Engine {
377
380
  }
378
381
 
379
382
  // Mix in by property descriptor (Object.assign would evaluate getters on the spot and lose them)
380
- for (const part of [loopMethods, holdMethods, startupMethods, groundMethods, actorMethods, moduleMethods, lifecycleMethods, skipMethods, checkMethods, resizeMethods, sceneMethods, probeMethods, lightmapMethods])
383
+ for (const part of [loopMethods, holdMethods, startupMethods, groundMethods, actorMethods, moduleMethods, lifecycleMethods, skipMethods, checkMethods, resizeMethods, sceneMethods, probeMethods, reflectionProbeMethods, lightmapMethods])
381
384
  Object.defineProperties(Engine.prototype, Object.getOwnPropertyDescriptors(part));
@@ -7,6 +7,8 @@
7
7
  // progress 0-1, critical, error { message, url, status }, missing (referenced files that failed), fallback, source { manifest, url, version, bytes, animations }.
8
8
  // Finished is not the same as succeeded: view().done says nothing is pending, view().ok says nothing failed.
9
9
 
10
+ import { unreadyModules } from './headlessLoad.js';
11
+
10
12
  const END = new Set(['done', 'failed']);
11
13
  const VERB = { queued: 'queued', download: 'downloading', decode: 'decoding', upload: 'uploading to the GPU', build: 'building', module: 'waiting for module' };
12
14
  const LIST_MAX = 8; // describe stays short: the full list is engine.loading.list()
@@ -61,17 +63,19 @@ export class Loading {
61
63
  */
62
64
  _limit(p, lastSign, fail) {
63
65
  let timer;
66
+ const sig = this.engine.signal;
67
+ const end = () => { clearTimeout(timer); sig?.removeEventListener('abort', end); };
64
68
  const over = new Promise((_, rej) => {
65
69
  const look = () => {
66
70
  const last = lastSign();
67
- if (last == null || this.engine.disposed) return;
71
+ if (last == null || this.engine.disposed || sig?.aborted) return;
68
72
  const left = this.timeoutMs - (performance.now() - last); // measure
69
73
  if (left > 0) timer = setTimeout(look, Math.min(left, 2 ** 31 - 1)); // main-loop: a wall clock, because what it guards may be why no frame runs
70
- else rej(fail());
74
+ else { end(); rej(fail()); }
71
75
  };
72
76
  look();
73
77
  });
74
- const end = () => clearTimeout(timer);
78
+ if (sig && !sig.aborted) sig.addEventListener('abort', end, { once: true });
75
79
  p.then(end, end);
76
80
  return Promise.race([p, over]);
77
81
  }
@@ -126,7 +130,7 @@ export class Loading {
126
130
  /** Pending items: unfinished tasks + modules whose isReady is false + the stream's required builds (live, not stored) */
127
131
  _pending() {
128
132
  const e = this.engine, out = [...this.tasks.values()].filter(t => !END.has(t.state));
129
- for (const m of e.modules.values()) if (m.isReady && !m.isReady(e)) out.push(Object.assign(new Task(m.name, 'module', { critical: true }), { state: 'build', label: e.moduleName(m) }));
133
+ for (const m of unreadyModules(e)) out.push(Object.assign(new Task(m.name, 'module', { critical: true }), { state: 'build', label: e.moduleName(m) }));
130
134
  if (!e.stream.ready) out.push(Object.assign(new Task('stream', 'stream', { critical: true }), { state: 'build' }));
131
135
  return out;
132
136
  }
@@ -6,7 +6,7 @@
6
6
  // A hot reload re-runs the same file (same path, a ?t= query): that is one copy, not two, so the path without the query decides.
7
7
  import { coded } from '../base/errorHints.js';
8
8
 
9
- export const VERSION = '2.2.2'; // kept equal to package.json by the "[guard] engine copies" spec
9
+ export const VERSION = '2.3.0'; // kept equal to package.json by the "[guard] engine copies" spec
10
10
 
11
11
  const KEY = Symbol.for('threedog.engine.copies');
12
12
 
@@ -14,11 +14,18 @@ import { DEV, warnOnce } from '../base/validate.js';
14
14
  import { coded, codedError } from '../base/errorHints.js';
15
15
 
16
16
  const TICK_MS = 16; // one loading frame per ~60 Hz tick: the same pace a live loop gives the workers
17
+ const IDLE_MS = 100; // slower poll once settled, so an idle headless engine burns minimal CPU
18
+
19
+ /** Running modules whose isReady(e) is false (failed / disabled / blocked modules are skipped so a non-critical failure never stalls start or loading) @internal */
20
+ export function unreadyModules(e) {
21
+ const out = [];
22
+ for (const m of e.modules.values()) if ((e._runsHooks ? e._runsHooks(m.name) : true) && m.isReady && !m.isReady(e)) out.push(m);
23
+ return out;
24
+ }
17
25
 
18
26
  /** Modules whose isReady(e) is false, plus the stream when its required nearby builds are not done ([] = settled) */
19
27
  export function unsettled(e) {
20
- const who = [];
21
- for (const m of e.modules.values()) if (m.isReady && !m.isReady(e)) who.push(m.name);
28
+ const who = unreadyModules(e).map(m => m.name);
22
29
  if (!e.stream.ready) who.push('the stream (required nearby builds)');
23
30
  return who;
24
31
  }
@@ -51,9 +58,13 @@ export function whenSettled(e, valid = () => true, rearm = false) {
51
58
  export function startHeadlessLoad(e) {
52
59
  if (!e.headless || e._headlessLoad) return;
53
60
  const s = e._headlessLoad = { watching: false, stalled: false };
61
+ let timer;
62
+ const stop = () => clearTimeout(timer);
63
+ e.signal?.addEventListener('abort', stop, { once: true });
54
64
  const tick = () => {
55
65
  if (e.disposed) return;
56
- if (!unsettled(e).length) s.stalled = false;
66
+ const busy = unsettled(e).length > 0;
67
+ if (!busy) s.stalled = false;
57
68
  else {
58
69
  if (!s.watching && !s.stalled) {
59
70
  s.watching = true;
@@ -63,7 +74,7 @@ export function startHeadlessLoad(e) {
63
74
  // (no input.endFrame: a key a test pressed before its next step() must still read as just pressed there)
64
75
  e._frameHooks(0, true);
65
76
  }
66
- setTimeout(tick, TICK_MS); // main-loop: a headless engine's stand-in for the live frame loop while something is loading
77
+ timer = setTimeout(tick, busy ? TICK_MS : IDLE_MS); // main-loop: a headless engine's stand-in for the live frame loop while something is loading
67
78
  };
68
79
  tick();
69
80
  }
@@ -89,6 +89,7 @@ export const lifecycleMethods = {
89
89
  tidy(() => this._gameLights?.dispose());
90
90
  tidy(() => this._picture?.dispose()); // dev tool: its scene watchers go with the engine
91
91
  tidy(() => this.debug.dispose()); // before the scene is disposed: undoes every diagnostic override and view (puts swapped materials back)
92
+ tidy(() => { for (const p of [...(this._reflectionProbes ?? [])]) p.remove(); });
92
93
  for (const part of [this.saves, this.audio, this.time, this.commits, this.jobs, this.threads, this.stream, this.batching, this.rays, this.events]) tidy(() => part.dispose());
93
94
  clearHooks(this); this._afterTick = null;
94
95
  tidy(() => this.assets.forget(this.scene)); // references and leases first: each model copy gives its lease back, its animator stops
@@ -65,7 +65,7 @@ function closeProfFrame(p) {
65
65
  const CATCHUP_MS = STEP * 2000;
66
66
  // Dev message (console): which hook failed
67
67
  const STRINGS = {
68
- onFixed: 'onFixed callback', onFrame: 'onFrame callback', animate: 'animator update', onRender: 'onRender callback', clock: 'clock timer', render: 'render',
68
+ onFixed: 'onFixed callback', onFrame: 'onFrame callback', animate: 'animator update', onBeforeDraw: 'onBeforeDraw callback', onRender: 'onRender callback', clock: 'clock timer', render: 'render',
69
69
  hook: '{kind} hook of module {name}',
70
70
  stepStart: 'engine.step() ran while start() is still loading: no game time passes, only frame hooks run. Wait for it first: await engine.start(); engine.step(1)',
71
71
  stepSession: 'engine.step() ran while a new game, load or quit is still replacing the state: the step plays on a half-replaced world. Wait for it first: await engine.session.load(slot); engine.step(1)',
@@ -162,12 +162,18 @@ export const loopMethods = {
162
162
  gpu?.begin();
163
163
  // engine.onRender: camera and batching are final here. 'before' may render into its own targets (counted in renderer.info and the render phase)
164
164
  const before = hooks ? this._onRender.before : [], after = hooks ? this._onRender.after : [];
165
- const ctx = before.length || after.length ? { renderer: r, scene: this.scene, camera: this.camera, dt } : null;
165
+ const beforeDraw = hooks && this._beforeDraw?.length ? this._beforeDraw : null;
166
+ const ctx = beforeDraw || before.length || after.length ? (this._renderCtx ??= { renderer: r, scene: this.scene, camera: this.camera, dt }) : null;
167
+ if (ctx) { ctx.renderer = r; ctx.scene = this.scene; ctx.camera = this.camera; ctx.dt = dt; }
166
168
  // the game drew the canvas itself since the last engine frame (own composer / render loop): it holds the frame, the engine yields (render/ownFrame.js)
167
169
  const draws = engineDraws(this), own = this._ownFrame;
168
170
  if (own) own.inside++;
169
171
  this._poses.draw(); // moving things draw between the last two fixed steps (stepPoses.js); undone below, gameplay never sees it
170
172
  try {
173
+ if (beforeDraw) for (let i = 0; i < beforeDraw.length; i++) {
174
+ const f = beforeDraw[i];
175
+ if (live(this, '_beforeDraw', beforeDraw, f)) safe(this, STRINGS.onBeforeDraw, f, null, undefined, ctx);
176
+ }
171
177
  for (const f of before) { if (!live(this._onRender, 'before', before, f)) continue; safe(this, STRINGS.onRender, drawHook, null, undefined, f, ctx); r.setRenderTarget(null); }
172
178
  this.shadows._frame(); // a game light's cascades, after 'before': picture code aims its light there, and the placement must be what is drawn (render/shadows.js)
173
179
  this._checkBackendAdds(); // WebGPU route: a WebGL-only material added since the last frame is named, not drawn blank (startup.js)
@@ -296,7 +302,7 @@ export const loopMethods = {
296
302
  c3 = performance.now(); // measure
297
303
  if (this._readyAt != null && this.ready) firstFrame(this, c3);
298
304
  } finally { this.input.endFrame(); }
299
- this._runHooks('afterRender', dt);
305
+ if (this.ready) this._runHooks('afterRender', dt);
300
306
  const c4 = performance.now(), P = this._cpuPhases; // measure
301
307
  P.fixed = c1 - c0; P.frame = c2 - c1; P.render = c3 - c2; P.afterRender = c4 - c3;
302
308
  this._cpuMs = c4 - c0;
@@ -348,6 +354,19 @@ export const loopMethods = {
348
354
  return describe ? this.describe() : null; // describe: false for internal loops that ignore the result (describe() walks every module)
349
355
  },
350
356
 
357
+ /**
358
+ * @internal Lightweight pre-draw callback: runs in _render right after _poses.draw() and before external onRender hooks, without holdRenderer.
359
+ * For internal subsystems that update scene/uniform/cull state without changing render targets or viewports. Returns a handle { remove() }.
360
+ * @param {(ctx: { renderer: any, scene: any, camera: any, dt: number }) => void} fn
361
+ * @returns {{ remove(): void }}
362
+ */
363
+ onBeforeDraw(fn) {
364
+ if (typeof fn !== 'function') throw codedError('engine-misuse', `engine.onBeforeDraw(fn): fn must be a function, got ${typeof fn}`);
365
+ const list = this._beforeDraw ?? (this._beforeDraw = []);
366
+ list.push(fn);
367
+ return { remove: () => { if (this._beforeDraw) this._beforeDraw = this._beforeDraw.filter(f => f !== fn); } };
368
+ },
369
+
351
370
  // Adaptive resolution (core/scene/adaptive.js): judged on frame cost; tests drive it with explicit cost / compiled values
352
371
  _adapt(dt, cost = Math.max(this._cpuMs, this._gpu?.ms ?? 0), compiled = !!this._compiled, gpuKnown = this._gpu?.ms != null) { adapt(this, dt, cost, compiled, gpuKnown); },
353
372
  };