threedog 1.1.0 → 1.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 (370) hide show
  1. package/CHANGELOG.md +893 -798
  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 +187 -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 +17 -7
  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 +8 -7
  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 +50 -28
  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 +36 -15
  85. package/core/scene/adaptive.js +144 -21
  86. package/core/scene/drawOnly.js +17 -0
  87. package/core/scene/gameLights.js +47 -4
  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 +17 -11
  103. package/docs/COMMANDS.md +139 -142
  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 +30 -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/characters.md +10 -8
  112. package/docs/api/collision.md +6 -4
  113. package/docs/api/engine.md +16 -16
  114. package/docs/api/events.md +3 -2
  115. package/docs/api/ground.md +6 -5
  116. package/docs/api/hud.md +4 -2
  117. package/docs/api/input.md +5 -5
  118. package/docs/api/particles.md +2 -1
  119. package/docs/api/photo.md +3 -0
  120. package/docs/api/post.md +7 -4
  121. package/docs/api/quests.md +2 -2
  122. package/docs/api/rays.md +1 -2
  123. package/docs/api/saves.md +7 -7
  124. package/docs/api/settings.md +2 -2
  125. package/docs/api/tools.md +3 -1
  126. package/docs/api/vars.md +1 -1
  127. package/docs/api/vegetation.md +4 -2
  128. package/docs/api/world.md +1 -1
  129. package/docs/recipes/01-new-game.md +16 -17
  130. package/docs/recipes/02-npc.md +22 -18
  131. package/docs/recipes/03-items-pickups.md +37 -35
  132. package/docs/recipes/04-quests.md +15 -10
  133. package/docs/recipes/05-props-bake.md +101 -95
  134. package/docs/recipes/06-clock-events.md +28 -28
  135. package/docs/recipes/07-flow-scenes-pause.md +29 -26
  136. package/docs/recipes/08-weather-sky.md +52 -64
  137. package/docs/recipes/09-materials-lights-models.md +26 -17
  138. package/docs/recipes/10-blender-level.md +15 -10
  139. package/docs/recipes/11-vehicles.md +12 -7
  140. package/docs/recipes/12-navmesh.md +44 -26
  141. package/docs/recipes/13-animation.md +56 -45
  142. package/docs/recipes/14-custom-module.md +21 -18
  143. package/docs/recipes/15-perf.md +61 -55
  144. package/docs/recipes/16-dev-bridge.md +24 -33
  145. package/docs/recipes/18-world.md +36 -42
  146. package/docs/recipes/19-shooting-picking.md +20 -15
  147. package/docs/recipes/20-content-actions-save.md +48 -56
  148. package/docs/recipes/21-camera.md +45 -54
  149. package/docs/recipes/22-shop-gold.md +12 -7
  150. package/docs/recipes/23-ops.md +25 -23
  151. package/docs/recipes/26-ui-parts.md +67 -47
  152. package/docs/recipes/27-net.md +12 -7
  153. package/docs/recipes/28-terrain.md +24 -21
  154. package/docs/recipes/29-grid.md +32 -27
  155. package/docs/recipes/30-templates.md +21 -20
  156. package/docs/recipes/31-audio.md +39 -22
  157. package/docs/recipes/32-action-game.md +19 -14
  158. package/docs/recipes/33-stream-sources.md +15 -11
  159. package/docs/recipes/34-environment-lighting.md +126 -70
  160. package/docs/recipes/35-picture-from-reference.md +8 -8
  161. package/docs/recipes/36-ground-plants.md +27 -21
  162. package/docs/recipes/40-scene.md +19 -28
  163. package/docs/recipes/43-shader-patches-surfaces.md +15 -12
  164. package/docs/recipes/44-water-weather-hooks.md +34 -31
  165. package/docs/recipes/45-cascaded-shadows.md +35 -26
  166. package/docs/recipes/46-blender-art-route.md +7 -2
  167. package/docs/recipes/49-game-module-contract.md +13 -8
  168. package/docs/recipes/50-own-renderer.md +6 -2
  169. package/docs/recipes/51-capability-catalog.md +15 -8
  170. package/docs/recipes/52-around-the-picture.md +34 -32
  171. package/docs/recipes/53-ground-up-close.md +6 -1
  172. package/docs/recipes/55-mods-time-wrap.md +27 -19
  173. package/docs/recipes/56-webgpu-tsl.md +75 -43
  174. package/docs/recipes/57-control.md +18 -13
  175. package/docs/recipes/58-input.md +26 -16
  176. package/docs/recipes/59-depth-post-effects.md +8 -3
  177. package/docs/recipes/60-judge-the-picture.md +10 -9
  178. package/docs/recipes/61-deploy.md +5 -0
  179. package/docs/recipes/62-picture-code.md +72 -79
  180. package/docs/recipes/63-third-person-start.md +48 -45
  181. package/docs/recipes/64-particles.md +22 -10
  182. package/docs/recipes/65-swarm.md +18 -13
  183. package/docs/recipes/66-common-tasks.md +38 -35
  184. package/examples/action/.threedog/content-index.json +1 -1
  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/.threedog/content-index.json +1 -1
  189. package/examples/perf-island/GAMEMAP.md +3 -3
  190. package/examples/perf-island/picture/lights.js +2 -1
  191. package/examples/plain-picture/GAMEMAP.md +1 -1
  192. package/examples/rc2d/GAMEMAP.md +1 -1
  193. package/examples/styletest/.threedog/content-index.json +1 -1
  194. package/examples/styletest/GAMEMAP.md +2 -2
  195. package/examples/styletest/main.js +1 -1
  196. package/examples/techniques/interior-light/README.md +3 -3
  197. package/examples/techniques/interior-light/interiorLight.js +2 -4
  198. package/examples/techniques/interior-light/picture/lights.js +2 -1
  199. package/examples/techniques/modular-building/picture/lights.js +3 -1
  200. package/examples/techniques/outlines-and-rim/picture/lights.js +3 -1
  201. package/examples/techniques/procedural-animation/README.md +1 -1
  202. package/examples/techniques/procedural-animation/main.js +1 -1
  203. package/examples/webgpu-tsl/GAMEMAP.md +1 -1
  204. package/examples/world/.threedog/content-index.json +1 -1
  205. package/examples/world/GAMEMAP.md +2 -3
  206. package/examples/world/art/humanoid.js +1 -1
  207. package/examples/world/main.js +6 -3
  208. package/index.d.ts +2 -2
  209. package/llms.txt +101 -0
  210. package/modules/ambience/Ambience.js +21 -5
  211. package/modules/calendar/index.js +9 -5
  212. package/modules/calendar/schedule.js +23 -8
  213. package/modules/camera/FirstPersonCamera.js +3 -1
  214. package/modules/camera/FollowCamera.js +10 -5
  215. package/modules/camera/RtsCamera.js +4 -3
  216. package/modules/camera/common.js +70 -8
  217. package/modules/camera/contract.js +1 -1
  218. package/modules/characters/Character.js +16 -10
  219. package/modules/characters/NPC.js +31 -19
  220. package/modules/characters/assetModel.js +14 -9
  221. package/modules/characters/astar.js +6 -1
  222. package/modules/characters/contract.js +2 -2
  223. package/modules/characters/index.js +34 -22
  224. package/modules/characters/movers/manual.js +1 -1
  225. package/modules/characters/movers/rapier.js +17 -2
  226. package/modules/characters/movers/simple.js +1 -1
  227. package/modules/characters/movers/support.js +16 -7
  228. package/modules/characters/npcAvoid.js +2 -2
  229. package/modules/characters/npcSim.js +3 -2
  230. package/modules/characters/pathAsync.js +24 -8
  231. package/modules/characters/pathJob.js +1 -1
  232. package/modules/characters/player.js +10 -9
  233. package/modules/characters/playerStrings.js +5 -5
  234. package/modules/characters/proceduralRig.js +5 -5
  235. package/modules/characters/useModel.js +6 -0
  236. package/modules/characters/walkTo.js +1 -1
  237. package/modules/collision/Collision.js +29 -18
  238. package/modules/collision/grid.js +22 -4
  239. package/modules/content/index.js +3 -1
  240. package/modules/content/loader.js +1 -1
  241. package/modules/content/models.js +82 -33
  242. package/modules/content/props.js +2 -1
  243. package/modules/content/rules.js +11 -5
  244. package/modules/content/templates.js +3 -3
  245. package/modules/content/words.js +2 -2
  246. package/modules/debug/DebugPanel.js +9 -9
  247. package/modules/flow/index.js +9 -6
  248. package/modules/gameplay/Dialogue.js +34 -20
  249. package/modules/gameplay/Interactions.js +19 -15
  250. package/modules/gameplay/Inventory.js +9 -4
  251. package/modules/gameplay/Quests.js +12 -10
  252. package/modules/gameplay/pickups.js +23 -11
  253. package/modules/grid/index.js +1 -1
  254. package/modules/grid/preview.js +2 -2
  255. package/modules/grid/tiles.js +1 -1
  256. package/modules/hlod/index.js +4 -1
  257. package/modules/hud/index.js +47 -10
  258. package/modules/hud/parts.js +28 -9
  259. package/modules/level/geometry.js +8 -3
  260. package/modules/level/index.js +10 -5
  261. package/modules/level/load.js +4 -2
  262. package/modules/lights/sources.js +1 -1
  263. package/modules/music/Music.js +22 -4
  264. package/modules/nav/index.js +20 -10
  265. package/modules/particles/Particles.js +31 -14
  266. package/modules/particles/effect.js +20 -5
  267. package/modules/particles/lit.js +72 -0
  268. package/modules/photo/Photo.js +72 -28
  269. package/modules/photo/pathTrace.js +106 -0
  270. package/modules/rigid/RigidBodies.js +23 -14
  271. package/modules/rigid/Vehicles.js +3 -13
  272. package/modules/rigid/sync.js +2 -1
  273. package/modules/settings/Settings.js +52 -20
  274. package/modules/settings/apply.js +23 -9
  275. package/modules/settings/sections.js +39 -6
  276. package/modules/settings/strings.js +2 -0
  277. package/modules/settings/view.js +19 -3
  278. package/modules/sky/dome.js +15 -3
  279. package/modules/sky/environment.js +28 -12
  280. package/modules/sky/fog.js +1 -1
  281. package/modules/sky/frame.js +6 -1
  282. package/modules/sky/shader.js +4 -3
  283. package/modules/sky/skyModule.js +8 -4
  284. package/modules/swarm/Swarm.js +1 -1
  285. package/modules/terrain/ChunkManager.js +61 -15
  286. package/modules/terrain/chunkJob.js +2 -2
  287. package/modules/terrain/index.js +20 -5
  288. package/modules/terrain/terrainEdit.js +8 -4
  289. package/modules/terrain/terrainTexture.js +4 -2
  290. package/modules/timeline/Timeline.js +4 -3
  291. package/modules/timeline/Tween.js +3 -0
  292. package/modules/timeline/letterbox.js +1 -0
  293. package/modules/triggers/index.js +36 -17
  294. package/modules/vegetation/Vegetation.js +81 -19
  295. package/modules/vegetation/densityMap.js +13 -8
  296. package/modules/vegetation/draw.js +147 -24
  297. package/modules/vegetation/groundChunks.js +20 -5
  298. package/modules/vegetation/index.js +3 -3
  299. package/modules/vegetation/modelGeometry.js +9 -4
  300. package/modules/water/Water.js +11 -8
  301. package/modules/weather/Weather.js +7 -2
  302. package/modules/weather/shaders.js +25 -5
  303. package/modules/weather/weatherDraw.js +20 -6
  304. package/modules/world/World.js +2 -1
  305. package/modules/world/index.js +2 -2
  306. package/modules/world/persist.js +6 -2
  307. package/modules/world/views.js +15 -2
  308. package/package.json +5 -1
  309. package/presets.js +5 -5
  310. package/render/PostFX.js +102 -42
  311. package/render/backend.js +142 -16
  312. package/render/bindingLimits.js +59 -0
  313. package/render/cascades.js +3 -1
  314. package/render/cascades.tsl.js +2 -0
  315. package/render/daylight.js +7 -1
  316. package/render/detail.js +7 -4
  317. package/render/effects.js +27 -8
  318. package/render/fogLook.js +24 -0
  319. package/render/fuse.js +5 -2
  320. package/render/fx/compareLevel.tsl.js +23 -0
  321. package/render/fx/detail.tsl.js +9 -7
  322. package/render/fx/index.js +9 -2
  323. package/render/fx/library.tsl.js +1 -0
  324. package/render/fx/lightShaft.tsl.js +114 -0
  325. package/render/fx/noise.tsl.js +25 -8
  326. package/render/fx/objectOrigin.tsl.js +39 -10
  327. package/render/fx/particles.tsl.js +23 -6
  328. package/render/fx/patchNodes.tsl.js +17 -12
  329. package/render/fx/pcss.tsl.js +51 -0
  330. package/render/fx/postWebGPU.tsl.js +104 -29
  331. package/render/fx/sky.tsl.js +3 -9
  332. package/render/fxNumbers.js +10 -4
  333. package/render/impostor.tsl.js +107 -0
  334. package/render/lighting.js +33 -1
  335. package/render/lightmap.js +42 -28
  336. package/render/lights.js +19 -3
  337. package/render/materials.js +6 -4
  338. package/render/mergeCommon.js +4 -1
  339. package/render/occlusion.js +14 -4
  340. package/render/patches.js +79 -41
  341. package/render/postRuns.js +32 -0
  342. package/render/postWebGL.js +97 -10
  343. package/render/probes.js +10 -14
  344. package/render/shaderErrors.js +44 -7
  345. package/render/shadowCache.tsl.js +33 -5
  346. package/render/shadows.js +42 -16
  347. package/render/slots.js +8 -5
  348. package/render/vertexInputs.js +52 -0
  349. package/types/core.d.ts +115 -47
  350. package/types/gameplay.d.ts +56 -23
  351. package/types/generated/core/audio/Audio.d.ts +27 -1
  352. package/types/generated/core/base/Random.d.ts +1 -1
  353. package/types/generated/core/input/Input.d.ts +6 -8
  354. package/types/generated/core/input/inputSeat.d.ts +1 -1
  355. package/types/generated/core/inspect/Budget.d.ts +26 -0
  356. package/types/generated/core/inspect/DebugOverrides.d.ts +0 -2
  357. package/types/generated/core/saves/Saves.d.ts +10 -7
  358. package/types/generated/core/saves/session.d.ts +8 -2
  359. package/types/generated/core/scene/Rays.d.ts +1 -3
  360. package/types/generated/core/scene/Views.d.ts +17 -3
  361. package/types/generated/modules/particles/Particles.d.ts +1 -1
  362. package/types/generated/modules/world/World.d.ts +2 -1
  363. package/types/generated/render/PostFX.d.ts +35 -9
  364. package/types/physics.d.ts +796 -764
  365. package/types/pixel.d.ts +1 -1
  366. package/types/tsl.d.ts +62 -1
  367. package/types/world.d.ts +12 -3
  368. package/ui/Focus.js +7 -5
  369. package/ui/Parts.js +1 -1
  370. package/ui/touchPart.js +6 -3
@@ -15,10 +15,28 @@ import { RenderPass } from 'three/addons/postprocessing/RenderPass.js';
15
15
  import { OutputPass } from 'three/addons/postprocessing/OutputPass.js';
16
16
  import { FusedPass, groupFuse, checkDepthOrder } from './fuse.js';
17
17
  import { codedError } from '../core/base/errorHints.js';
18
- import { holdShadowRedraw, MSAA_SAMPLES } from './backend.js';
18
+ import { holdShadowRedraw, MSAA_SAMPLES, borrowRenderer } from './backend.js';
19
19
  import { notePatch, patchOn } from '../core/scene/threePatches.js';
20
20
 
21
21
  // One FusedPass per group of neighboring fuse effects, kept while the same effects stay grouped (a changed group recompiles once)
22
+ /**
23
+ * Does this effect swap the composer's buffers (so a depth reader after it finds another target's depth)? A fuse group always does (one FusedPass).
24
+ * An effect never on yet has no pass: one is built to read its flags and disposed (a game's own pass is read as it is), and the answer is kept on the handle.
25
+ * @param {any} post @param {any} e @returns {boolean}
26
+ */
27
+ function swaps(post, e) {
28
+ if (e._def.fuse) return true;
29
+ const p = e._impl ?? e._def._pass;
30
+ if (p) return !!(p.needsSwap && !p.keepsDepth);
31
+ if (e._swaps !== undefined) return e._swaps;
32
+ if (typeof e._def.create !== 'function') return false; // node-only: sync names it when it is on
33
+ const { scene, camera } = post.engine, size = post._size();
34
+ const probe = e._def.create({ engine: post.engine, scene, camera, width: size.x, height: size.y, params: e.params, borrowRenderer });
35
+ e._swaps = !!(probe?.needsSwap && !probe.keepsDepth);
36
+ probe?.dispose?.();
37
+ return e._swaps;
38
+ }
39
+
22
40
  function fuseEntry(post, group, used) {
23
41
  const key = group.map(e => e.name).join('+'), old = post._fused.get(key);
24
42
  let pass = old && old.items.every((e, i) => e === group[i]) ? old : null;
@@ -72,9 +90,9 @@ function toTarget(post, dt, target) {
72
90
  const c = post.composer, r = post.engine.renderer;
73
91
  c.renderToScreen = false;
74
92
  try { webglPost.render(post, dt); } finally { c.renderToScreen = true; }
75
- const prev = r.getRenderTarget();
76
93
  c.copyPass.renderToScreen = false;
77
- try { c.copyPass.render(r, target, c.readBuffer); } finally { r.setRenderTarget(prev); }
94
+ borrowRenderer(r, () => c.copyPass.render(r, target, c.readBuffer));
95
+ post._tgtIdle = 0; // with no effect on the targets stay for the next renderOnce(target) (a minimap asks every frame); direct() frees them after IDLE_FRAMES frames without one
78
96
  }
79
97
 
80
98
  // The meshes three draws a texture background with (WebGLBackground's plane and box), by their material names
@@ -102,10 +120,62 @@ function toneBackground(post, draw) {
102
120
  } finally { post._toneBg = false; }
103
121
  }
104
122
 
123
+ // Fog in the same space as the chain. three mixes fog after tone mapping and the output encoding, with the fog colour in output space, when a material
124
+ // draws to the canvas; under the composer (a render target) it mixes in linear space and OutputPass tone-maps the result. So the far fog changed colour
125
+ // whenever the chain turned on or off, and met a tone-mapped sky backdrop with a seam. WebGPU already mixes before tone mapping on both paths. The rule:
126
+ // fog is mixed in linear space BEFORE any output conversion (tone curve or colour encoding; with or without a tone curve, toneMapped or not). So the mix
127
+ // goes first in tonemapping_fragment (always before colorspace_fragment), from the fog colour decoded back from the output space (probe below; a render
128
+ // target is linear and needs no decode). THREEDOG_FOG_DONE is set by whichever fog code runs first: fog_fragment skips its mix when it is set, and the
129
+ // injection is skipped when a custom shader already ran fog_fragment before the tone chunk (fogFactor would be declared twice). A shader without the fog
130
+ // chunks (THREEDOG_FOG_PARS) keeps three's code. The decode assumes an sRGB or linear output; a wide-gamut output keeps three's unconverted fog colour.
131
+ // threedogFogColor / threedogFogFactor are what the fog slot (render/slots.js) reads too, so a patch that wants default fog writes the same mix.
132
+ const FOG_FNS = `
133
+ #ifdef USE_FOG
134
+ vec3 threedogFogColor() { return linearToOutputTexel( vec4( vec3( 0.2 ), 1.0 ) ).x > 0.25 ? sRGBTransferEOTF( vec4( fogColor, 1.0 ) ).rgb : fogColor; }
135
+ float threedogFogFactor() {
136
+ #ifdef FOG_EXP2
137
+ return 1.0 - exp( - fogDensity * fogDensity * vFogDepth * vFogDepth );
138
+ #else
139
+ return smoothstep( fogNear, fogFar, vFogDepth );
140
+ #endif
141
+ }
142
+ #endif
143
+ `;
144
+ const FOG_LINEAR = `
145
+ #if defined( USE_FOG ) && defined( THREEDOG_FOG_PARS ) && ! defined( THREEDOG_FOG_DONE )
146
+ gl_FragColor.rgb = mix( gl_FragColor.rgb, threedogFogColor(), threedogFogFactor() );
147
+ #define THREEDOG_FOG_DONE
148
+ #endif
149
+ `;
150
+ {
151
+ // the originals live on the page (a symbol), not in this module: a second evaluation of this file (hot reload, a second copy) would take the patched chunks as the originals
152
+ const C = THREE.ShaderChunk, KEY = Symbol.for('threedog.fogChunks');
153
+ const was = C[KEY] ??= Object.fromEntries(['fog_pars_fragment', 'tonemapping_fragment', 'fog_fragment'].map(n => [n, C[n]])); // by name, not R42's patch-slot anchors
154
+ const put = () => {
155
+ C.fog_pars_fragment = `${was.fog_pars_fragment}
156
+ #ifdef USE_FOG
157
+ #define THREEDOG_FOG_PARS
158
+ #endif
159
+ ${FOG_FNS}`;
160
+ C.tonemapping_fragment = FOG_LINEAR + was.tonemapping_fragment;
161
+ C.fog_fragment = `#ifndef THREEDOG_FOG_DONE
162
+ ${was.fog_fragment}
163
+ #define THREEDOG_FOG_DONE
164
+ #endif
165
+ `;
166
+ };
167
+ put();
168
+ notePatch('fog-linear', "three's fog_pars_fragment, tonemapping_fragment and fog_fragment shader chunks: fog is mixed in linear space before the tone curve when drawing to the canvas, as under the composer and on WebGPU (render/postWebGL.js)",
169
+ () => { C.tonemapping_fragment = was.tonemapping_fragment; }, { scope: 'page', lost: 'with no effect on, distant fog is mixed after tone mapping in output space: it changes colour when the first effect turns on and leaves a seam against a tone-mapped sky backdrop' });
170
+ }
171
+
172
+ /** Canvas frames without a renderOnce(target) after which an effect-free engine gives the composer targets back */
173
+ const IDLE_FRAMES = 120;
174
+
105
175
  export const webglPost = {
106
176
  /** @param {any} post */
107
177
  init(post) {
108
- /** @internal */ post._fused = /** @type {Map<string, FusedPass>} */ (new Map()); post._scenePass = null; post._output = null;
178
+ /** @internal */ post._fused = /** @type {Map<string, FusedPass>} */ (new Map()); post._scenePass = null; post._output = null; post._tgtIdle = 0;
109
179
  /** @internal three's background meshes already hooked (toneBackground) */ post._bgMeshes = new WeakSet(); post._toneBg = false;
110
180
  },
111
181
  object: post => post.composer,
@@ -118,10 +188,26 @@ export const webglPost = {
118
188
  refresh(post) { for (const p of post._fused.values()) p.refresh(); },
119
189
  samples: post => (post.active ? post.composer?.renderTarget1.samples ?? (post._aa ? MSAA_SAMPLES : 0) : post._ownAA ? MSAA_SAMPLES : 0),
120
190
  setAntialias(post, on) {
121
- if (post.composer) for (const rt of [post.composer.renderTarget1, post.composer.renderTarget2]) { rt.samples = on ? MSAA_SAMPLES : 0; rt.dispose(); }
191
+ const samples = on ? MSAA_SAMPLES : 0; // only a real change of samples frees the targets
192
+ if (post.composer) for (const rt of [post.composer.renderTarget1, post.composer.renderTarget2]) if (rt.samples !== samples) { rt.samples = samples; rt.dispose(); }
122
193
  },
123
194
  // Rebuild the pass chain from the list: scene (or the default RenderPass) -> hdr -> tone (or the default OutputPass) -> ldr -> final.
124
195
  // Only enabled effects are in the chain; an implementation is built the first time its effect is on and kept after.
196
+ /**
197
+ * The depth-order rule, the one copy, over the chain as it can run in any on / off state: every added effect counts as on, the scene slot as the
198
+ * worse of its effect and the plain RenderPass (which never swaps), the tone slot as the worse of its effect and the default OutputPass (which always
199
+ * swaps, and runs whenever the tone effect is off), keeping the tone effect's own depth read. Why every state: an order that breaks only once a held
200
+ * effect turns on (ao held by a low preset, outline after it) was accepted at add() and threw later inside the settings switch that turned ao on,
201
+ * half-applied. Its one caller is PostFX._change, the gate every list or params change goes through, so the refusal lands at that call.
202
+ */
203
+ checkOrder(post) {
204
+ const all = post._sorted();
205
+ if (!all.some(e => e._def.needsDepth)) return;
206
+ const by = s => all.filter(e => e.slot === s), flag = e => ({ name: e.name, _def: e._def, _impl: { needsSwap: swaps(post, e), keepsDepth: false } });
207
+ const scene = by('scene')[0], tone = by('tone')[0];
208
+ checkDepthOrder([scene ? flag(scene) : { name: 'scene render', _impl: { needsSwap: false } }, ...by('hdr').map(flag),
209
+ { name: tone ? tone.name : 'output (tone mapping)', _def: { needsDepth: !!tone?._def.needsDepth }, _impl: { needsSwap: true, keepsDepth: false } }, ...by('ldr').map(flag), ...by('final').map(flag)]);
210
+ },
125
211
  sync(post) {
126
212
  const { renderer, scene, camera } = post.engine, size = post._size();
127
213
  if (!post.composer) {
@@ -137,7 +223,7 @@ export const webglPost = {
137
223
  const c = post.composer, on = post._sorted().filter(e => e.enabled);
138
224
  for (const e of on) if (!e._impl && !e._def.fuse) {
139
225
  if (typeof e._def.create !== 'function') throw codedError('post-effect', `post effect '${e.name}' has only node() (a TSL node, WebGPURenderer only) and this game chose WebGLRenderer: use createEngine({ renderer: 'webgpu' }), or give it create: (ctx) => pass (a three.js postprocessing Pass)`);
140
- e._impl = e._def.create({ engine: post.engine, scene, camera, width: size.x, height: size.y, params: e.params });
226
+ e._impl = e._def.create({ engine: post.engine, scene, camera, width: size.x, height: size.y, params: e.params, borrowRenderer });
141
227
  if (!e._impl || typeof e._impl.render !== 'function') { e._impl = null; throw codedError('post-effect', `post effect '${e.name}': create() must return a pass with render() (a three.js postprocessing Pass)`); }
142
228
  }
143
229
  const used = new Set();
@@ -145,7 +231,6 @@ export const webglPost = {
145
231
  const named = [slot('scene')[0] ?? { name: 'scene render', _impl: post._scenePass }, ...slot('hdr'),
146
232
  slot('tone')[0] ?? { name: 'output (tone mapping)', _impl: post._output }, ...slot('ldr'), ...slot('final')];
147
233
  for (const [k, p] of post._fused) if (!used.has(k)) { p.dispose(); post._fused.delete(k); }
148
- checkDepthOrder(named);
149
234
  // Effects reading depth (outline) need a depth texture on both ping-pong targets; added once, kept
150
235
  if (on.some(e => e._def.needsDepth)) for (const rt of [c.renderTarget1, c.renderTarget2]) if (!rt.depthTexture) { rt.depthTexture = new THREE.DepthTexture(size.x, size.y); rt.dispose(); }
151
236
  c.passes = named.map(e => e._impl);
@@ -167,7 +252,7 @@ export const webglPost = {
167
252
  return post.composer?.renderTarget1 ?? null; // RenderPass draws into readBuffer, which is renderTarget1 or its twin (same format: same program key)
168
253
  },
169
254
  render(post, dt, target = null) {
170
- if (!post.composer) post._sync();
255
+ if (!post.composer) webglPost.sync(post); // post._sync() does nothing with no effect on, and renderOnce(target) still goes through scene + output
171
256
  follow(post);
172
257
  if (target) { toTarget(post, dt, target); return; }
173
258
  // no background: RenderPass clears the half-float target with whatever clear value three last set, which after the previous frame's
@@ -190,8 +275,10 @@ export const webglPost = {
190
275
  */
191
276
  direct(post, target = null) {
192
277
  const { renderer: r, scene: s, camera } = post.engine, bg = s.background;
193
- // a render target gets the scene as three draws into one (linear, no tone mapping); post.active is what gives the canvas's pixels
194
- if (target) { const prev = r.getRenderTarget(); r.setRenderTarget(target); try { r.render(s, camera); } finally { r.setRenderTarget(prev); } return; }
278
+ // exactly once, IDLE_FRAMES canvas frames after the last renderOnce(target): the targets it left allocated go back (three allocates them again on the next use)
279
+ if (!target && post.composer && !post.active && ++post._tgtIdle === IDLE_FRAMES) for (const rt of [post.composer.renderTarget1, post.composer.renderTarget2]) rt.dispose();
280
+ // a target gets the canvas's pixels too (tone mapped, output color space), whether or not an effect is on: through the scene + output passes, which are the chain with nothing added
281
+ if (target) { webglPost.render(post, 0, target); return; }
195
282
  if (r.toneMapping !== THREE.NoToneMapping && bg?.isTexture && THREE.ColorManagement.getTransfer(bg.colorSpace) === THREE.SRGBTransfer) {
196
283
  toneBackground(post, () => r.render(s, camera)); return;
197
284
  }
package/render/probes.js CHANGED
@@ -16,7 +16,8 @@ import { codedError, coded } from '../core/base/errorHints.js';
16
16
  import { warnOnce, fmt } from '../core/base/validate.js';
17
17
  import { vec3 } from '../core/base/math.js';
18
18
  import { isWebGPU, webgpuPart, freshFrame, readLayer, onRendererSwap } from './backend.js';
19
- import { mats, lit, noteFillLight, noteEnvironment } from './lit.js';
19
+ import { mats, lit } from './lit.js';
20
+ import { litTwice } from '../core/inspect/pictureChecks.js';
20
21
 
21
22
  const FORMAT = 'threedog-probes', VERSION = 2, MAX_PROBES = 4096, SH = 27;
22
23
  const CHUNK = 8; // probes baked per turn of the event loop, so the page keeps drawing during a long bake
@@ -37,7 +38,6 @@ const STRINGS = {
37
38
  outside: '{n} lit object(s) reach outside the probe grid ({names}): the part outside gets no probe light and can go black. Widen bounds, or add light there. describe().render.probes lists them',
38
39
  filled: 'engine.bakeProbes(): {n} probe(s) saw a pixel that is not a number (a shader dividing by zero or taking pow of a negative; first at {at}) and took the light of their nearest good neighbours. Fix that material, or leave it out with include',
39
40
  noLight: 'engine.bakeProbes(): every probe saw a pixel that is not a number, so nothing usable was baked. A material in view writes NaN (a shader dividing by zero or taking pow of a negative): fix it, or leave it out with include',
40
- doubled: 'probe light is added on top of {what}, which the bake already saw, so that light counts twice. Lower it where the probes take over, or bake without it',
41
41
  };
42
42
  const sets = e => (e._probeSets ??= new Set());
43
43
 
@@ -109,21 +109,17 @@ function toBase64(bytes) {
109
109
  return btoa(s);
110
110
  }
111
111
 
112
- /** Visible lit meshes no set fully holds, and everything else in the scene that adds light the bake already saw. Runs on describe() and when a set is added, never per frame */
112
+ /** Visible lit meshes no set fully holds (light counted twice is a picture check: core/inspect/pictureChecks.js). Runs on describe() and when a set is added, never per frame */
113
113
  function probeChecks(e) {
114
- const boxes = [...sets(e)].map(s => s.box), b = new THREE.Box3(), outside = [], doubled = [];
115
- let mapped = 0;
114
+ const boxes = [...sets(e)].map(s => s.box), b = new THREE.Box3(), outside = [];
116
115
  e.scene.traverseVisible(o => {
117
- if (noteFillLight(o, doubled) || !o.isMesh || !mats(o).some(lit)) return;
118
- if (mats(o).some(m => m.lightMap)) mapped++;
116
+ if (!o.isMesh || !mats(o).some(lit)) return;
119
117
  const src = o.isInstancedMesh ? o : o.geometry;
120
118
  if (!src.boundingBox) src.computeBoundingBox();
121
119
  b.copy(src.boundingBox).applyMatrix4(o.matrixWorld);
122
120
  if (!boxes.some(x => x.containsBox(b))) outside.push(o.name || `${o.type} ${o.id}`);
123
121
  });
124
- noteEnvironment(e.scene, doubled);
125
- if (mapped) doubled.push(`material.lightMap on ${mapped} mesh(es)`);
126
- return { outside, doubled };
122
+ return { outside };
127
123
  }
128
124
 
129
125
  /**
@@ -199,9 +195,9 @@ class ProbeSet {
199
195
  }
200
196
  /** describe().render.probes row */
201
197
  info() {
202
- const { outside, doubled } = probeChecks(this._e);
198
+ const { outside } = probeChecks(this._e);
203
199
  return { count: this.count, counts: this.counts, step: this.step.map(s => Math.round(s * 100) / 100), source: this.source, owner: this.owner,
204
- outside: { count: outside.length, names: outside.slice(0, 3) }, doubled, ...(this.bakeMs != null ? { bakeMs: Math.round(this.bakeMs) } : {}) };
200
+ outside: { count: outside.length, names: outside.slice(0, 3) }, ...(this.bakeMs != null ? { bakeMs: Math.round(this.bakeMs) } : {}) };
205
201
  }
206
202
  /** Take the grid out of the scene and free its texture; the data stays readable (sample, toJSON). Safe to call twice */
207
203
  remove() {
@@ -227,9 +223,9 @@ function drawProbes(e, scene) {
227
223
  }
228
224
  function addSet(e, data, o) {
229
225
  e._probeView ??= e.debug?.defineView('probes', { what: 'each light probe as a dot colored by its average light', apply: scene => drawProbes(e, scene) });
230
- const set = new ProbeSet(e, data, o), { outside, doubled } = probeChecks(e);
226
+ const set = new ProbeSet(e, data, o), { outside } = probeChecks(e), twice = litTwice(e);
231
227
  if (outside.length) warnOnce(coded('probes-check', fmt(STRINGS.outside, { n: outside.length, names: outside.slice(0, 3).join(', ') })));
232
- if (doubled.length) warnOnce(coded('probes-check', fmt(STRINGS.doubled, { what: doubled.join(', ') })));
228
+ if (twice) warnOnce(coded('probes-check', twice));
233
229
  return set;
234
230
  }
235
231
 
@@ -7,6 +7,7 @@
7
7
  import { setConsoleFunction, getConsoleFunction } from 'three';
8
8
  import { isWebGPU, findNodeBuild } from './backend.js';
9
9
  import { materialPatches } from './patches.js';
10
+ import { notePatch, patchOn } from '../core/scene/threePatches.js';
10
11
 
11
12
  const BEGIN = /^\s*\/\/ threedog:begin patch=(\S+) slot=(\S+)/, END = /^\s*\/\/ threedog:end/;
12
13
  // a GLSL file served by the vite preset's threedog-live plugin (shader hot reload, render/hotGlsl.js): `// threedog:begin file=<path>`
@@ -63,10 +64,11 @@ function stageLogs(gl, vs, fs) {
63
64
  * Hook renderer.debug.onShaderError (when nothing else holds it) so compile errors name the patch and slot.
64
65
  * @internal core/engine/Engine.js
65
66
  * @param {import('three').WebGLRenderer} renderer
67
+ * @param {(materialId: number) => string} [onFail] WebGPU: called when the device refused a pipeline of that material; returns what was done about it ('' = nothing)
66
68
  */
67
- export function nameShaderErrors(renderer) {
69
+ export function nameShaderErrors(renderer, onFail) {
68
70
  const d = /** @type {any} */ (renderer).debug;
69
- if (isWebGPU(renderer)) { nameNodeErrors(renderer); return; }
71
+ if (isWebGPU(renderer)) { if (onFail) ON_FAIL.set(renderer, onFail); nameNodeErrors(renderer); return; }
70
72
  if (!d || d.onShaderError) return;
71
73
  d.onShaderError = (gl, program, vs, fs) => {
72
74
  const parts = [];
@@ -103,10 +105,44 @@ function nodeOwner(ro) {
103
105
  * @returns {string}
104
106
  */
105
107
  function explainPipelineError(message) {
106
- const m = /Render pipeline creation failed \(renderPipeline_.*_(\d+)\)/.exec(message);
107
- if (!m) return '';
108
- const ro = findNodeBuild(x => x.material?.id === +m[1]);
109
- return `[threedog] WebGPU pipeline failed for ${ro ? nodeOwner(ro) : `material #${m[1]} (not among the recent builds)`}: ${NODE_HINT}. three's WGSL lines follow.`;
108
+ const m = /[Rr]ender pipeline creation failed \(renderPipeline_.*_(\d+)\)/.exec(message); // 'Async render pipeline ...' from compileAsync too
109
+ return m ? `${pipelineFailed(+m[1])} three's WGSL lines follow.` : '';
110
+ }
111
+
112
+ // renderer -> what the engine does about a pipeline that failed for one material (core/engine/Engine.js gives it): the post chain holds the effect
113
+ // that draws with it. Why here: the device reports a failed pipeline by its label only, and this file is where a label becomes a material and its owner.
114
+ const ON_FAIL = new WeakMap();
115
+ /** "[threedog] WebGPU pipeline failed for <owner>: <what the engine did about it, or how to find the cause>." @param {number} id material id @param {any} [r] the renderer, when the report came with one */
116
+ function pipelineFailed(id, r) {
117
+ const ro = findNodeBuild(x => x.material?.id === id), did = ON_FAIL.get(r ?? ro?.renderer)?.(id);
118
+ return `[threedog] WebGPU pipeline failed for ${ro ? nodeOwner(ro) : `material #${id} (not among the recent builds)`}: ${did || NODE_HINT}.`;
119
+ }
120
+
121
+ // What three's own scope misses: it wraps pipeline creation in a 'validation' error scope, and a shader the driver's compiler refuses (FXC on D3D)
122
+ // is a GPUInternalError, no validation error. The pipeline stays invalid, three keeps drawing with it, and every frame that does is lost. So the
123
+ // device's createRenderPipeline gets an 'internal' scope of its own: the failure then arrives with the pipeline's label, whatever words the browser
124
+ // uses for it. three's async path (compileAsync) reports such a failure itself, through the console line explainPipelineError reads.
125
+ notePatch('pipeline-internal-scope', "createRenderPipeline of the WebGPURenderer's GPUDevice: an 'internal' error scope around three's call, so a pipeline the driver's compiler refuses is named with its material, and a post effect that owns it is held", () => {},
126
+ { scope: 'engine renderer', lost: 'a pipeline the driver refuses keeps failing every frame with no name, and its post effect stays on' });
127
+ const scoped = new WeakSet();
128
+ /** @internal core/engine/startup.js, once the renderer has its device @param {any} r a WebGPURenderer */
129
+ export function watchPipelineBuilds(r) {
130
+ const device = r?.backend?.device;
131
+ if (!device?.pushErrorScope || scoped.has(device)) return;
132
+ scoped.add(device);
133
+ const create = device.createRenderPipeline;
134
+ device.createRenderPipeline = function (desc) {
135
+ if (!patchOn('pipeline-internal-scope')) return create.call(this, desc);
136
+ const label = String(desc?.label ?? ''); // read now: three reuses one descriptor object and resets it after the call
137
+ this.pushErrorScope('internal');
138
+ try { return create.call(this, desc); }
139
+ finally {
140
+ this.popErrorScope().then(err => {
141
+ const m = err && /^renderPipeline_.*_(\d+)$/.exec(label);
142
+ if (m) console.error(`${pipelineFailed(+m[1], r)} The device said: ${err.message}`);
143
+ }, () => { /* the device was lost: its own report covers it */ });
144
+ }
145
+ };
110
146
  }
111
147
 
112
148
  /** The explanation for three's node build-error log ('THREE.TSL: TypeError: ...', NodeManager), or '' (another message) @param {string} message */
@@ -115,7 +151,8 @@ function explainBuildError(message) {
115
151
  // three logs right after building the stand-in for the failed one, with the same render object: the newest build is the one that failed
116
152
  const ro = findNodeBuild(() => true), named = /\[threedog\] (patch|post effect) '/.test(message);
117
153
  return `[threedog] node build failed for ${ro ? nodeOwner(ro) : 'a material not among the recent builds'}; three draws it with a plain NodeMaterial instead (the black or white mesh). `
118
- + (named ? 'The patch or post effect named above returned the node that failed.'
154
+ + (/\[vertex-inputs\]/.test(message) ? 'The vertex inputs counted above are the cause (render/vertexInputs.js).'
155
+ : named ? 'The patch or post effect named above returned the node that failed.'
119
156
  : "Not inside a patch's or post effect's node (those are named when they fail): look at the material's own nodes (colorNode, positionNode ...)");
120
157
  }
121
158
 
@@ -3,7 +3,9 @@
3
3
  // Why copy then draw and not a second lookup in the shader: the light's map holds the whole answer again, so no material, filter or custom shadow node changes.
4
4
  // Why one filter on the shadow draw and a kept set: only what the static pass really drew may be skipped later. A static object that came after that pass (a streamed
5
5
  // block), or was outside the box then, still draws with the moving things, so it casts a shadow without any redraw. An InstancedMesh is kept with its instance version: batching
6
- // moves, adds and drops instances and replaces whole batches on its own, so a changed version or a mesh gone from the scene redraws the kept map with no call from the game.
6
+ // moves, adds and drops instances and replaces whole batches on its own, so a changed geometry or shadow flag, or a mesh hidden or gone from the scene, redraws the kept map with
7
+ // no call from the game; a changed instance version draws that mesh live and redraws the kept map at most once every REFILL_EVERY shadow frames.
8
+ // With renderer.shadowMap.transmitted the map's color (the tint a castShadowNode writes) is copied too: three reads it beside the depth.
7
9
  // Why float depth: the depth24plus three picks cannot be a WebGPU copy source. The opted-in light's depth is more precise, nothing else changes.
8
10
  // shortcut: one plain map only. Cascades build their own shadow nodes inside three's CSMShadowNode; upgrade if a game needs kept far cascades.
9
11
  import { FloatType, Matrix4, ShadowNode } from 'three/webgpu';
@@ -11,6 +13,21 @@ import { registerWebGPUPart, rebuildShadow } from './backend.js';
11
13
  import { notePatch } from '../core/scene/threePatches.js';
12
14
  import { warnOnce } from '../core/base/validate.js';
13
15
 
16
+ // A kept InstancedMesh still draws what the kept map holds: same instances, same geometry, still casting, still shown in the scene. Why more than the
17
+ // instance version: vegetation rings swap a chunk's geometry, hide it past maxRing, stop its shadow past shadowRing, and drop a chunk by removing
18
+ // its group (the mesh keeps that parent), all without touching instances, so the kept map showed shadows of plants no longer there
19
+ const keptAs = m => ({ v: m.instanceMatrix.version, geo: m.geometry });
20
+ /** @param {any} m @param {{ v: number, geo: any }} k @param {boolean} [anyVersion] true: everything but the instances as kept */
21
+ function drawsAsKept(m, k, anyVersion = false) {
22
+ if ((!anyVersion && m.instanceMatrix.version !== k.v) || m.geometry !== k.geo || !m.castShadow) return false;
23
+ for (let o = m; o; o = o.parent) { if (!o.visible) return false; if (o.isScene) return true; }
24
+ return false; // no longer under a scene
25
+ }
26
+ // Shadow frames between two refills caused by instance writes alone. Why: while streaming, batching joins, drops or moves an instance almost every frame, and each
27
+ // write refilled the whole kept map (dearer than no cache). Meanwhile the changed mesh draws with the moving things, so a joined instance casts at once; an instance
28
+ // that left or moved leaves its old shadow in the kept map until the refill (at most this many shadow frames, ~0.13 s at 60). Geometry, shadow flag, hiding, a mesh
29
+ // gone from the scene and a moved light still refill at once
30
+ const REFILL_EVERY = 8;
14
31
  const Base = /** @type {any} */ (ShadowNode); // @types/three declares none of the methods a shadow node subclass overrides
15
32
 
16
33
  class CachedShadowNode extends Base {
@@ -21,9 +38,12 @@ class CachedShadowNode extends Base {
21
38
  this._isStatic = isStatic; // underscore names: three walks a node's public fields looking for child nodes
22
39
  this._cache = null;
23
40
  this._kept = new WeakSet();
24
- this._instanced = new Map(); // the InstancedMeshes in the kept map -> their instance version then
41
+ this._instanced = new Map(); // the InstancedMeshes in the kept map -> how they were drawn then (keptAs)
25
42
  this._filling = false; // true during the static pass
26
43
  this._stale = true;
44
+ this._due = false; // an instance write is waiting for its refill (REFILL_EVERY)
45
+ this._since = 0; // shadow frames since the last refill
46
+ this._fills = 0; // refills so far (tests read it)
27
47
  this._fresh = true; // the light's map has no GPU texture yet, or a new size: the copy needs one
28
48
  this._matrix = new Matrix4();
29
49
  this._base = null; this._draw = null;
@@ -49,7 +69,7 @@ class CachedShadowNode extends Base {
49
69
  if (this._filling) {
50
70
  if (!this._isStatic(object)) return;
51
71
  this._kept.add(object);
52
- if (object.isInstancedMesh) this._instanced.set(object, object.instanceMatrix.version);
72
+ if (object.isInstancedMesh) this._instanced.set(object, keptAs(object));
53
73
  } else if (this._kept.has(object)) return;
54
74
  base(object, ...rest);
55
75
  };
@@ -67,7 +87,13 @@ class CachedShadowNode extends Base {
67
87
  if (shadowMap.width !== width || shadowMap.height !== height) this._stale = this._fresh = true;
68
88
  shadow.updateMatrices(light);
69
89
  if (!shadow.matrix.equals(this._matrix)) this._stale = true; // the light or its box moved: every kept pixel is in the wrong place
70
- for (const [mesh, version] of this._instanced) if (!mesh.parent || mesh.instanceMatrix.version !== version) this._stale = true;
90
+ this._since++;
91
+ for (const [mesh, kept] of this._instanced) {
92
+ if (drawsAsKept(mesh, kept)) continue;
93
+ if (!drawsAsKept(mesh, kept, true)) { this._stale = true; break; }
94
+ this._kept.delete(mesh); this._instanced.delete(mesh); this._due = true; // instances only: drawn live until the refill
95
+ }
96
+ if (this._due && this._since >= REFILL_EVERY) this._stale = true;
71
97
  if (this._stale) {
72
98
  cache.setSize(width, height, cache.depth);
73
99
  this._kept = new WeakSet();
@@ -78,10 +104,12 @@ class CachedShadowNode extends Base {
78
104
  this._filling = false;
79
105
  renderer.setRenderTarget(shadowMap);
80
106
  this._matrix.copy(shadow.matrix);
81
- this._stale = false;
107
+ this._stale = this._due = false; this._since = 0; this._fills++;
82
108
  }
83
109
  if (this._fresh) { shadowMap.setSize(width, height, shadowMap.depth); renderer.initRenderTarget(shadowMap); this._fresh = false; }
84
110
  renderer.copyTextureToTexture(cache.depthTexture, shadowMap.depthTexture);
111
+ // transmitted shadows: three reads the tint the static pass wrote from the color attachment, so the kept color comes along with the depth (GPT review l2-render 7)
112
+ if (renderer.shadowMap.transmitted) renderer.copyTextureToTexture(cache.texture, shadowMap.texture);
85
113
  renderer.autoClear = false; // the copied depth is the start of this pass; updateShadow restores the renderer's state after it
86
114
  super.renderShadow(frame);
87
115
  }
package/render/shadows.js CHANGED
@@ -14,6 +14,7 @@ import { warnOnce, fmt } from '../core/base/validate.js';
14
14
  import { readParams } from '../core/base/params.js';
15
15
  import { defineOwned, dropOwned, ownedRow } from '../core/ops/owned.js';
16
16
  import { isWebGPU, onRendererSwap, setShadowUpdate, shadowsOn, webgpuPart } from './backend.js';
17
+ import { onTierChange } from '../core/scene/tier.js';
17
18
  import { CASCADE_DEFAULTS, CASCADE_SPLITS, createCascades, dropCascades, includeInCascades } from './cascades.js';
18
19
 
19
20
  const WHERE = 'engine.shadows.cascades';
@@ -23,7 +24,7 @@ const PARAMS = {
23
24
  split: { type: 'any', default: CASCADE_DEFAULTS.split, desc: "'practical' | 'uniform' | 'logarithmic' | (count, near, far, out) => void" },
24
25
  fade: { type: 'bool', default: CASCADE_DEFAULTS.fade, desc: 'cross-fade at the borders' },
25
26
  lightMargin: { type: 'number', default: CASCADE_DEFAULTS.lightMargin, min: 0, desc: 'meters behind each cascade box toward the light still caught as casters' },
26
- low: { type: 'object', optional: true, desc: 'on low-tier devices: { count } (default 1, one map that follows the camera)' },
27
+ low: { type: 'object', optional: true, desc: 'on low-tier devices: { count } (default 1, one map that follows the camera and reaches maxFar / count, as sharp as an average cascade)' },
27
28
  };
28
29
  const STRINGS = {
29
30
  light: `${WHERE}(light): needs a three.js DirectionalLight (cascades split a parallel light's shadow); got {got}`,
@@ -31,6 +32,7 @@ const STRINGS = {
31
32
  cast: `${WHERE}(light): set light.castShadow = true first; the engine does not write that on your light`,
32
33
  twice: `${WHERE}(light): this engine already has a cascades handle; change it with handle.set({ ... }) or call handle.remove() first (an engine draws one set)`,
33
34
  boxed: `${WHERE}(light): this light has a shadow box, and both place the light; call the box handle's remove() first`,
35
+ other: `${WHERE}(light): {got} also casts a directional shadow; on WebGLRenderer the cascades must be the scene's only shadow-casting DirectionalLight. Set castShadow = false on it (engine.lights.sun.castShadow = false for the engine sun) or put the cascades on that light instead`,
34
36
  split: `${WHERE}: split must be ${CASCADE_SPLITS.map(s => `'${s}'`).join(' | ')} or a function (count, near, far, out) => void; got {got}`,
35
37
  low: `${WHERE}: low must be { count } with a whole number 1 to 4; got {got}`,
36
38
  };
@@ -42,7 +44,7 @@ const BOX_PARAMS = {
42
44
  follow: { type: 'any', default: 'focus', desc: "what the box centers on: 'focus' (engine.focus) | 'camera' | an Object3D | () => Vector3 | false (it stays on the light's target)" },
43
45
  extent: { type: 'number', optional: true, min: 1, desc: "half size of the box in meters; left out: the light's own shadow camera stays as it is" },
44
46
  snap: { type: 'any', default: 0.5, desc: "center snap grid in meters, or 'texel' (one shadow pixel: no shimmer on a moving camera)" },
45
- ahead: { type: 'number', default: 0, desc: 'meters the center is shifted in front of the view' },
47
+ ahead: { type: 'number', default: 0, desc: 'meters the center is shifted in front of a level view (less as the view tilts down, 0 straight down)' },
46
48
  };
47
49
  const BUDGET = 'engine.shadows.budget';
48
50
  const MAP = 'engine.shadows.mapSize';
@@ -67,7 +69,9 @@ function boxCenter(e, light) {
67
69
  else if (o.follow?.isObject3D) o.follow.getWorldPosition(at);
68
70
  else if (typeof o.follow === 'function') at.copy(o.follow());
69
71
  else at.copy(e.focus);
70
- if (o.ahead) { cam.getWorldDirection(ahead); ahead.y = 0; if (ahead.lengthSq() > 1e-6) at.addScaledVector(ahead.normalize(), o.ahead); }
72
+ // ahead along the level part of the view, scaled by it (not normalized): a view tilting toward straight down slides the shift to 0 smoothly. Normalized
73
+ // with a cut-off, a near-vertical camera jumped the whole shift for a tiny turn and a straight-down one got none
74
+ if (o.ahead) { cam.getWorldDirection(ahead); ahead.y = 0; at.addScaledVector(ahead, o.ahead); }
71
75
  let now;
72
76
  if (o.snap === 'texel') {
73
77
  // the light-space right and up axes (matching the shadow camera lookAt), rounded to one shadow pixel along each
@@ -196,15 +200,14 @@ function ownBudget(e, light, first) {
196
200
  * @param {any} e @param {boolean} on
197
201
  */
198
202
  function switchShadows(e, on) {
199
- if (shadowsOn(e) === on) return; // nothing changed: no scene walk, no recompile
200
203
  e.renderer.shadowMap.enabled = on;
201
204
  e.scene.traverse(o => { if (o.material) [].concat(o.material).forEach(m => { m.needsUpdate = true; }); });
202
205
  e.events.emit('settings:shadows', on);
203
206
  }
204
207
 
205
208
  /** The running handle's cascades. The WebGL half keeps what the game wrote apart from the placement; see the header */
206
- function ownCascades(e, light, first) {
207
- let o = readOptions(first), c = null, key = '', own = null, box = null;
209
+ function ownCascades(e, light, first, gameExtent = () => undefined) {
210
+ let o = readOptions(first), c = null, key = '', own = null, box = null, sunSize = null; // sunSize: puts the engine sun's box size back
208
211
  const proxy = new THREE.Object3D(), placed = new THREE.Vector3(), dir = new THREE.Vector3();
209
212
  const readGame = () => {
210
213
  if (light.target !== proxy) { own.target = light.target; light.target = proxy; }
@@ -212,6 +215,7 @@ function ownCascades(e, light, first) {
212
215
  };
213
216
  const off = () => {
214
217
  box?.remove(); box = null;
218
+ sunSize?.(); sunSize = null;
215
219
  if (!c) return;
216
220
  if (own) { readGame(); light.position.copy(own.position); light.target = own.target; own = null; }
217
221
  dropCascades(e);
@@ -219,14 +223,26 @@ function ownCascades(e, light, first) {
219
223
  };
220
224
  const sync = () => {
221
225
  const n = e.tier === 'low' ? o.low?.count ?? 1 : o.count; // low tier: one map unless the game says so
222
- const want = (n > 1 ? [n, o.maxFar, o.fade, o.lightMargin, o.split] : [o.maxFar, o.lightMargin]).join('|');
226
+ const want = (n > 1 ? [n, o.maxFar, o.fade, o.lightMargin, o.split] : [o.count, o.maxFar, o.lightMargin]).join('|'); // one map's size reads count too
223
227
  if (want === key) return;
224
228
  off();
225
229
  key = want;
226
230
  if (n <= 1) {
227
- // one map still has to cover what the cascades would: left alone it stays three's default 10 m box where the game put the light. Centered on the camera, as far
228
- // as maxFar each way and lightMargin behind, as the cascades reach. The engine sun needs none: a sky's box or the baseline follow (render/lights.js) moves it
229
- if (light !== e.lights?.sun) box = gameBox(e, light, { follow: 'camera', extent: o.maxFar, snap: 'texel' }, o.lightMargin + o.maxFar);
231
+ // one map still has to reach out from the camera: left alone it stays three's default 10 m box where the game put the light. It follows the camera, lightMargin
232
+ // behind. Its size keeps the texel size of the maps it stands in for: maxFar x n / count each way, i.e. all of maxFar when the game asked for one map, maxFar / count
233
+ // when the low tier cut the count. Why: the low tier saves the extra shadow passes, not texels; one map stretched over all of maxFar had count times the texels of an
234
+ // average cascade (120 m on 2048: 12 cm texels, and PCF's blur is radius x texel), a soft smear near the camera. The low tier draws shadows less far instead, and
235
+ // shifts the box half its size ahead so fewer texels go behind the view (half, not all: a steep camera still sees the ground just behind its feet).
236
+ // The engine sun is placed by a sky's box or the baseline follow (render/lights.js), so it only gets the size
237
+ const ext = Math.min(o.maxFar, Math.max(1, o.maxFar * n / o.count)); // the cut size never under the box's 1 m minimum, so a small maxFar that worked still works
238
+ if (light !== e.lights?.sun) box = gameBox(e, light, { follow: 'camera', extent: ext, ahead: n < o.count ? ext / 2 : 0, snap: 'texel' }, o.lightMargin + ext);
239
+ else if (gameExtent() === undefined) {
240
+ // the engine sun gets the same reach: its placement stays with the sky or the baseline follow, only the box goes from the 30 m baseline to ext (and back with remove).
241
+ // Like gameBox: an extent the game set with engine.shadows.box(sun, { extent }) wins, and if it sets one meanwhile, remove leaves it as the game left it
242
+ const sc = light.shadow.camera, was = { left: sc.left, right: sc.right, top: sc.top, bottom: sc.bottom };
243
+ setExtent(light, ext);
244
+ sunSize = () => { if (sc.right !== ext) return; Object.assign(sc, was); sc.updateProjectionMatrix(); };
245
+ }
230
246
  return;
231
247
  }
232
248
  c = createCascades(e, light, { ...o, cascades: n }, WHERE);
@@ -239,8 +255,9 @@ function ownCascades(e, light, first) {
239
255
  if (l.isDirectionalLight && l.castShadow && l.visible && !c.lights.includes(l)) warnOnce(`${WHERE}: DirectionalLight '${l.name || l.uuid.slice(0, 8)}' casts shadows too, which breaks the cascade order; set castShadow = false on it`);
240
256
  });
241
257
  };
258
+ sync(); // first, so a request that throws (a bad split callback) returns no handle and leaves no listener behind
242
259
  const swap = onRendererSwap(e, () => { if (c?.isCascadeNode) { off(); sync(); } }); // fallback 'webgl': the shadow node has no meaning on the new renderer
243
- sync();
260
+ const tier = onTierChange(e, sync); // the map count reads engine.tier: a preset switched while running rebuilds once (sync's key skips the rest)
244
261
  return {
245
262
  frame() {
246
263
  box?.frame();
@@ -255,7 +272,7 @@ function ownCascades(e, light, first) {
255
272
  proxy.updateMatrixWorld(); // not in the scene: nothing else refreshes it
256
273
  },
257
274
  set(next) { o = readOptions({ ...o, ...next }); sync(); },
258
- remove() { off(); swap.remove(); },
275
+ remove() { off(); swap.remove(); tier.remove(); },
259
276
  get csm() { return c; },
260
277
  /** the light while one map's box places it, else null */
261
278
  get boxed() { return box ? light : null; },
@@ -299,8 +316,10 @@ export function defineShadows(e, { owned }) {
299
316
  const boxes = new Map(), budgets = new Map(), caches = new Map();
300
317
  if (owned) e.renderer.shadowMap.enabled = true; // the placeholder sun casts, so things read as standing on the ground; the switch below turns it off
301
318
  // one point, because separate switches (an option, a method, the settings menu) each decided on their own and disagreed about what is on
302
- const point = e.stacks.define('shadows.enabled', { kind: 'value', base: shadowsOn(e), save: false, manual: "engine.mod('shadows.enabled', { owner, layer: 'system', set })",
303
- onChange: () => switchShadows(e, !!point.value()) });
319
+ // `shown` = the value this switch last applied, compared instead of the renderer's flag: a direct write to renderer.shadowMap.enabled (the picture writers report it) is not undone by a change that left the shared value as it was; no change: no scene walk, no recompile
320
+ let shown = shadowsOn(e);
321
+ const point = e.stacks.define('shadows.enabled', { kind: 'value', base: shown, save: false, manual: "engine.mod('shadows.enabled', { owner, layer: 'system', set })",
322
+ onChange: () => { const on = !!point.value(); if (on !== shown) switchShadows(e, shown = on); } });
304
323
  const hold = (map, light, h) => {
305
324
  const remove = () => { e.signal.removeEventListener('abort', remove); if (map.get(light) !== h) return; h.remove(); map.delete(light); };
306
325
  map.set(light, h);
@@ -321,7 +340,7 @@ export function defineShadows(e, { owned }) {
321
340
  },
322
341
  /**
323
342
  * Cascaded shadows for a DirectionalLight: sharp near the camera, wide far away, following the camera. The light stays yours: color, intensity and shadow
324
- * values are read from it. Low-tier devices get one map, which follows the camera, unless `low: { count }` says otherwise. WebGPURenderer needs `import 'threedog/tsl'`.
343
+ * values are read from it. Low-tier devices get one map, which follows the camera and reaches maxFar / count (shadows nearer, as sharp as an average cascade), unless `low: { count }` says otherwise. WebGPURenderer needs `import 'threedog/tsl'`.
325
344
  * @example
326
345
  * const sun = new THREE.DirectionalLight('#fff4e0', 3); sun.position.set(40, 80, 30); sun.castShadow = true; engine.scene.add(sun);
327
346
  * const shadows = engine.shadows.cascades(sun, { count: 3, maxFar: 150 });
@@ -337,7 +356,14 @@ export function defineShadows(e, { owned }) {
337
356
  if (live) fail('twice');
338
357
  if (caches.has(light)) refuse(`${WHERE}(light): this light keeps a cached shadow, which works on one plain map; call the cache handle's remove() first`);
339
358
  if (boxes.has(light) && light !== e.lights.sun) fail('boxed');
340
- const set = ownCascades(e, light, options);
359
+ // three's WebGL CSM shader (lights_fragment_begin) reads CSM_cascades[i] for every shadow-casting DirectionalLight, so one more than the cascades
360
+ // indexes past the array and every patched material fails to compile. Refused here, by name, instead of a shader error on the first frame
361
+ if (!e.renderer.isWebGPURenderer) {
362
+ let other = null;
363
+ e.scene.traverse(o => { if (!other && o.isDirectionalLight && o !== light && o.castShadow) other = o; });
364
+ if (other) fail('other', other === e.lights.sun ? 'engine.lights.sun' : other.name || 'another DirectionalLight');
365
+ }
366
+ const set = ownCascades(e, light, options, () => boxes.get(light)?.options?.extent);
341
367
  live = set;
342
368
  const remove = () => { e.signal.removeEventListener('abort', remove); if (live !== set) return; set.remove(); live = null; };
343
369
  e.signal.addEventListener('abort', remove, { once: true });
package/render/slots.js CHANGED
@@ -9,7 +9,7 @@ import { isObject } from '../core/base/util.js';
9
9
  // the WebGPU route only needed the node column and no patch changed; the anchor strings appear once here, not scattered across effects each writing their own.
10
10
  // Raw anchors (`glsl: { vertex|fragment: { <chunk>: code } }`) stay as the expert exit: plain three.js knowledge, WebGL only.
11
11
  /** @typedef {{ stage: 'vertex' | 'fragment', anchor: string, at: 'after' | 'before' | 'replace', shadowOnly?: boolean, scope: string, meaning: string,
12
- * node: { prop?: string, setup?: string } | null, nodeMeaning?: string }} Slot */
12
+ * node: { prop?: string, setup?: string } | null, nodeMeaning?: string, closes?: string, exclusive?: boolean }} Slot */
13
13
 
14
14
  /** @type {Record<string, Slot>} */
15
15
  export const SLOTS = {
@@ -60,10 +60,12 @@ export const SLOTS = {
60
60
  nodeMeaning: 'fog on WebGPU is scene.fogNode, set by the game',
61
61
  scope: 'declarations; fogColor and fogNear / fogFar or fogDensity are already declared (inside #ifdef USE_FOG)',
62
62
  meaning: 'fog functions that read three\'s fog uniforms (wrap them in #ifdef USE_FOG)' },
63
- fog: { stage: 'fragment', anchor: 'fog_fragment', at: 'replace', node: null,
63
+ // the engine mixes fog in linear space first thing in tonemapping_fragment (render/postWebGL.js), so this slot sits right before it and closes
64
+ // with THREEDOG_FOG_DONE: the patch IS the one fog mix, the engine's is skipped (a second mix on a tone-mapped colour was the bug)
65
+ fog: { stage: 'fragment', anchor: 'tonemapping_fragment', at: 'before', closes: '#define THREEDOG_FOG_DONE', exclusive: true, node: null,
64
66
  nodeMeaning: 'fog on WebGPU is scene.fogNode, set by the game',
65
- scope: 'gl_FragColor (write, tone mapped already), fogColor, vFogDepth, fogNear / fogFar or fogDensity (inside #ifdef USE_FOG)',
66
- meaning: 'replace how fog mixes into the final color (one patch per material may take it)' },
67
+ scope: 'gl_FragColor (write; linear, before tone mapping), vFogDepth, threedogFogColor() (fog colour, linear), threedogFogFactor() (0..1, the same curve three uses), fogColor (as three has it) and fogNear / fogFar or fogDensity (all inside #ifdef USE_FOG)',
68
+ meaning: 'replace how fog mixes into the final color: the only fog mix, in linear space before tone mapping and the output encoding (one patch per material may take it)' },
67
69
  };
68
70
  export const SLOT_NAMES = Object.keys(SLOTS);
69
71
  /** The lighting slot's hook names on the TSL side (render/fx/patchNodes.tsl.js) */
@@ -118,7 +120,8 @@ export function toAnchors(p) {
118
120
  const s = SLOTS[name];
119
121
  if (!s) throw codedError('shader-patch', `[threedog] patch '${p.name}': unknown slot '${name}'; use ${SLOT_NAMES.join(' | ')}, ${EXIT}`);
120
122
  if (typeof code !== 'string') throw codedError('shader-patch', `[threedog] patch '${p.name}' slot '${name}' must be GLSL code as a string; got ${typeof code}`);
121
- const marked = mark(p.name, name, code);
123
+ const marked = mark(p.name, name, s.closes ? `${code}
124
+ ${s.closes}` : code); // closes: a line the engine adds after the code (fog: THREEDOG_FOG_DONE)
122
125
  if (s.shadowOnly) { shadow[s.anchor] = marked; used.add('vertex'); continue; }
123
126
  glsl[s.stage][s.anchor] = s.at === 'after' ? marked : { [s.at]: marked };
124
127
  used.add(s.stage);