threedog 1.0.1 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (364) hide show
  1. package/CHANGELOG.md +90 -0
  2. package/README.md +1 -1
  3. package/core/assets/Animator.js +41 -3
  4. package/core/assets/Assets.js +100 -24
  5. package/core/assets/assetEntry.js +73 -20
  6. package/core/assets/assetHot.js +68 -16
  7. package/core/assets/assetLoad.js +6 -6
  8. package/core/assets/assetLod.js +9 -2
  9. package/core/assets/assetManifest.js +12 -2
  10. package/core/assets/assetPart.js +54 -0
  11. package/core/assets/ik.js +271 -0
  12. package/core/assets/modelNeeds.js +37 -0
  13. package/core/assets/namedModel.js +102 -29
  14. package/core/assets/nodeVisibility.js +15 -0
  15. package/core/audio/Audio.js +36 -4
  16. package/core/audio/audioReverb.js +99 -0
  17. package/core/audio/audioRules.js +1 -1
  18. package/core/audio/audioVoice.js +1 -1
  19. package/core/base/Events.js +14 -4
  20. package/core/base/Random.js +1 -1
  21. package/core/base/Vars.js +1 -1
  22. package/core/base/docRef.js +51 -0
  23. package/core/base/errorCodes.js +178 -126
  24. package/core/base/errorHints.js +9 -7
  25. package/core/base/errors.js +25 -10
  26. package/core/base/events.generated.js +2 -0
  27. package/core/base/freeParts.js +76 -0
  28. package/core/base/math.js +28 -0
  29. package/core/base/sections.js +5 -5
  30. package/core/base/validate.js +31 -3
  31. package/core/engine/Engine.js +16 -6
  32. package/core/engine/Loading.js +5 -3
  33. package/core/engine/copies.js +1 -1
  34. package/core/engine/headlessLoad.js +4 -1
  35. package/core/engine/lifecycle.js +32 -16
  36. package/core/engine/loop.js +71 -27
  37. package/core/engine/moduleSlots.js +2 -2
  38. package/core/engine/moduleTypes.js +3 -3
  39. package/core/engine/modules.js +65 -39
  40. package/core/engine/page.js +6 -3
  41. package/core/engine/services.js +6 -5
  42. package/core/engine/startup.js +5 -5
  43. package/core/input/Input.js +28 -14
  44. package/core/input/inputContext.js +28 -16
  45. package/core/input/inputKeyboard.js +31 -3
  46. package/core/input/inputPad.js +4 -0
  47. package/core/input/inputPointer.js +2 -1
  48. package/core/input/inputSeat.js +1 -1
  49. package/core/inspect/Budget.js +109 -19
  50. package/core/inspect/DebugOverrides.js +28 -4
  51. package/core/inspect/Describe.js +17 -9
  52. package/core/inspect/Inspect.js +4 -2
  53. package/core/inspect/InspectMaterials.js +3 -1
  54. package/core/inspect/InspectPerf.js +19 -9
  55. package/core/inspect/InspectScene.js +32 -7
  56. package/core/inspect/MaterialInfo.js +19 -2
  57. package/core/inspect/UrlState.js +46 -27
  58. package/core/inspect/catalog.js +28 -9
  59. package/core/inspect/debugView.js +2 -1
  60. package/core/inspect/describeRender.js +25 -13
  61. package/core/inspect/describeText.js +14 -6
  62. package/core/inspect/lightWatch.js +1 -1
  63. package/core/inspect/metadata.generated.js +35 -17
  64. package/core/inspect/pictureChecks.js +148 -0
  65. package/core/inspect/pictureMenu.js +84 -0
  66. package/core/inspect/pictureWriters.js +26 -6
  67. package/core/inspect/textureBytes.js +12 -2
  68. package/core/inspect/toolDoor.js +2 -4
  69. package/core/ops/Ops.js +11 -4
  70. package/core/ops/holds.js +27 -10
  71. package/core/ops/opsAtomic.js +15 -7
  72. package/core/ops/opsGuard.js +2 -2
  73. package/core/ops/opsRun.js +8 -7
  74. package/core/ops/sharedPoint.js +72 -21
  75. package/core/ops/stacks.js +56 -16
  76. package/core/saves/SaveStore.js +9 -3
  77. package/core/saves/Saves.js +32 -23
  78. package/core/saves/saveApply.js +96 -44
  79. package/core/saves/saveIds.js +1 -1
  80. package/core/saves/saveVersions.js +7 -5
  81. package/core/saves/session.js +17 -8
  82. package/core/saves/stateReplace.js +34 -15
  83. package/core/scene/Rays.js +52 -10
  84. package/core/scene/Views.js +13 -7
  85. package/core/scene/adaptive.js +144 -21
  86. package/core/scene/drawOnly.js +17 -0
  87. package/core/scene/gameLights.js +44 -3
  88. package/core/scene/sceneMethods.js +13 -11
  89. package/core/scene/stepPoses.js +11 -3
  90. package/core/scene/targeting.js +5 -3
  91. package/core/scene/thingOps.js +1 -1
  92. package/core/scene/tier.js +15 -0
  93. package/core/stream/Batching.js +30 -7
  94. package/core/stream/Stream.js +26 -7
  95. package/core/stream/batchGroups.js +2 -2
  96. package/core/stream/chunkStream.js +7 -5
  97. package/core/stream/prepare.js +77 -0
  98. package/core/time/skip.js +3 -1
  99. package/core/time/time.js +4 -2
  100. package/docs/AI.md +82 -83
  101. package/docs/API.md +16 -16
  102. package/docs/CODEMAP.md +16 -11
  103. package/docs/COMMANDS.md +31 -33
  104. package/docs/CONVENTIONS.md +37 -49
  105. package/docs/MIGRATING-0.8.md +2 -2
  106. package/docs/MIGRATING-1.0.md +2 -2
  107. package/docs/THREE.md +28 -35
  108. package/docs/api/assets.md +3 -1
  109. package/docs/api/audio.md +4 -2
  110. package/docs/api/budget.md +5 -0
  111. package/docs/api/cameraRig.md +2 -2
  112. package/docs/api/characters.md +10 -8
  113. package/docs/api/collision.md +6 -4
  114. package/docs/api/engine.md +16 -16
  115. package/docs/api/events.md +3 -2
  116. package/docs/api/ground.md +6 -5
  117. package/docs/api/hud.md +4 -2
  118. package/docs/api/input.md +5 -5
  119. package/docs/api/particles.md +2 -1
  120. package/docs/api/photo.md +3 -0
  121. package/docs/api/post.md +7 -4
  122. package/docs/api/quests.md +2 -2
  123. package/docs/api/rays.md +1 -2
  124. package/docs/api/saves.md +7 -7
  125. package/docs/api/settings.md +2 -2
  126. package/docs/api/tools.md +3 -1
  127. package/docs/api/vars.md +1 -1
  128. package/docs/api/vegetation.md +4 -2
  129. package/docs/api/world.md +1 -1
  130. package/docs/recipes/01-new-game.md +16 -17
  131. package/docs/recipes/02-npc.md +22 -18
  132. package/docs/recipes/03-items-pickups.md +37 -35
  133. package/docs/recipes/04-quests.md +15 -10
  134. package/docs/recipes/05-props-bake.md +101 -95
  135. package/docs/recipes/06-clock-events.md +28 -28
  136. package/docs/recipes/07-flow-scenes-pause.md +29 -26
  137. package/docs/recipes/08-weather-sky.md +52 -64
  138. package/docs/recipes/09-materials-lights-models.md +26 -17
  139. package/docs/recipes/10-blender-level.md +15 -10
  140. package/docs/recipes/11-vehicles.md +12 -7
  141. package/docs/recipes/12-navmesh.md +44 -26
  142. package/docs/recipes/13-animation.md +56 -45
  143. package/docs/recipes/14-custom-module.md +21 -18
  144. package/docs/recipes/15-perf.md +61 -55
  145. package/docs/recipes/16-dev-bridge.md +23 -33
  146. package/docs/recipes/18-world.md +36 -42
  147. package/docs/recipes/19-shooting-picking.md +20 -15
  148. package/docs/recipes/20-content-actions-save.md +48 -56
  149. package/docs/recipes/21-camera.md +45 -54
  150. package/docs/recipes/22-shop-gold.md +12 -7
  151. package/docs/recipes/23-ops.md +25 -23
  152. package/docs/recipes/26-ui-parts.md +67 -47
  153. package/docs/recipes/27-net.md +12 -7
  154. package/docs/recipes/28-terrain.md +24 -21
  155. package/docs/recipes/29-grid.md +32 -27
  156. package/docs/recipes/30-templates.md +21 -20
  157. package/docs/recipes/31-audio.md +39 -22
  158. package/docs/recipes/32-action-game.md +19 -14
  159. package/docs/recipes/33-stream-sources.md +15 -11
  160. package/docs/recipes/34-environment-lighting.md +126 -70
  161. package/docs/recipes/35-picture-from-reference.md +8 -8
  162. package/docs/recipes/36-ground-plants.md +27 -21
  163. package/docs/recipes/40-scene.md +19 -28
  164. package/docs/recipes/43-shader-patches-surfaces.md +15 -12
  165. package/docs/recipes/44-water-weather-hooks.md +34 -31
  166. package/docs/recipes/45-cascaded-shadows.md +35 -26
  167. package/docs/recipes/46-blender-art-route.md +6 -1
  168. package/docs/recipes/49-game-module-contract.md +13 -8
  169. package/docs/recipes/50-own-renderer.md +6 -2
  170. package/docs/recipes/51-capability-catalog.md +15 -8
  171. package/docs/recipes/52-around-the-picture.md +34 -32
  172. package/docs/recipes/53-ground-up-close.md +6 -1
  173. package/docs/recipes/55-mods-time-wrap.md +27 -19
  174. package/docs/recipes/56-webgpu-tsl.md +74 -43
  175. package/docs/recipes/57-control.md +18 -13
  176. package/docs/recipes/58-input.md +26 -16
  177. package/docs/recipes/59-depth-post-effects.md +8 -3
  178. package/docs/recipes/60-judge-the-picture.md +9 -8
  179. package/docs/recipes/61-deploy.md +5 -0
  180. package/docs/recipes/62-picture-code.md +70 -79
  181. package/docs/recipes/63-third-person-start.md +47 -45
  182. package/docs/recipes/64-particles.md +22 -10
  183. package/docs/recipes/65-swarm.md +18 -13
  184. package/docs/recipes/66-common-tasks.md +38 -35
  185. package/examples/action/GAMEMAP.md +2 -3
  186. package/examples/action/main.js +3 -3
  187. package/examples/action/picture/lights.js +3 -1
  188. package/examples/perf-island/GAMEMAP.md +3 -3
  189. package/examples/perf-island/picture/lights.js +2 -1
  190. package/examples/plain-picture/GAMEMAP.md +1 -1
  191. package/examples/rc2d/GAMEMAP.md +1 -1
  192. package/examples/styletest/GAMEMAP.md +2 -2
  193. package/examples/styletest/main.js +1 -1
  194. package/examples/techniques/interior-light/README.md +3 -3
  195. package/examples/techniques/interior-light/interiorLight.js +2 -4
  196. package/examples/techniques/interior-light/picture/lights.js +2 -1
  197. package/examples/techniques/modular-building/picture/lights.js +3 -1
  198. package/examples/techniques/outlines-and-rim/picture/lights.js +3 -1
  199. package/examples/techniques/procedural-animation/README.md +1 -1
  200. package/examples/techniques/procedural-animation/main.js +1 -1
  201. package/examples/webgpu-tsl/GAMEMAP.md +1 -1
  202. package/examples/world/GAMEMAP.md +2 -3
  203. package/examples/world/art/humanoid.js +1 -1
  204. package/examples/world/main.js +6 -3
  205. package/index.d.ts +2 -2
  206. package/llms.txt +101 -0
  207. package/modules/ambience/Ambience.js +21 -5
  208. package/modules/calendar/index.js +9 -5
  209. package/modules/calendar/schedule.js +23 -8
  210. package/modules/camera/FirstPersonCamera.js +3 -1
  211. package/modules/camera/FollowCamera.js +10 -5
  212. package/modules/camera/RtsCamera.js +4 -3
  213. package/modules/camera/common.js +70 -8
  214. package/modules/camera/contract.js +1 -1
  215. package/modules/characters/Character.js +16 -10
  216. package/modules/characters/NPC.js +31 -19
  217. package/modules/characters/assetModel.js +14 -9
  218. package/modules/characters/astar.js +6 -1
  219. package/modules/characters/contract.js +2 -2
  220. package/modules/characters/index.js +34 -22
  221. package/modules/characters/movers/manual.js +1 -1
  222. package/modules/characters/movers/rapier.js +17 -2
  223. package/modules/characters/movers/simple.js +1 -1
  224. package/modules/characters/movers/support.js +16 -7
  225. package/modules/characters/npcAvoid.js +2 -2
  226. package/modules/characters/npcSim.js +3 -2
  227. package/modules/characters/pathAsync.js +24 -8
  228. package/modules/characters/pathJob.js +1 -1
  229. package/modules/characters/player.js +10 -9
  230. package/modules/characters/playerStrings.js +5 -5
  231. package/modules/characters/proceduralRig.js +5 -5
  232. package/modules/characters/useModel.js +6 -0
  233. package/modules/characters/walkTo.js +1 -1
  234. package/modules/collision/Collision.js +29 -18
  235. package/modules/collision/grid.js +22 -4
  236. package/modules/content/index.js +3 -1
  237. package/modules/content/loader.js +1 -1
  238. package/modules/content/models.js +82 -33
  239. package/modules/content/props.js +2 -1
  240. package/modules/content/rules.js +11 -5
  241. package/modules/content/templates.js +3 -3
  242. package/modules/content/words.js +2 -2
  243. package/modules/debug/DebugPanel.js +9 -9
  244. package/modules/flow/index.js +9 -6
  245. package/modules/gameplay/Dialogue.js +34 -20
  246. package/modules/gameplay/Interactions.js +19 -15
  247. package/modules/gameplay/Inventory.js +9 -4
  248. package/modules/gameplay/Quests.js +12 -10
  249. package/modules/gameplay/pickups.js +23 -11
  250. package/modules/grid/index.js +1 -1
  251. package/modules/grid/preview.js +2 -2
  252. package/modules/grid/tiles.js +1 -1
  253. package/modules/hlod/index.js +4 -1
  254. package/modules/hud/index.js +47 -10
  255. package/modules/hud/parts.js +28 -9
  256. package/modules/level/geometry.js +8 -3
  257. package/modules/level/index.js +10 -5
  258. package/modules/level/load.js +4 -2
  259. package/modules/lights/sources.js +1 -1
  260. package/modules/music/Music.js +22 -4
  261. package/modules/nav/index.js +20 -10
  262. package/modules/particles/Particles.js +31 -14
  263. package/modules/particles/effect.js +20 -5
  264. package/modules/particles/lit.js +72 -0
  265. package/modules/photo/Photo.js +72 -28
  266. package/modules/photo/pathTrace.js +106 -0
  267. package/modules/rigid/RigidBodies.js +23 -14
  268. package/modules/rigid/Vehicles.js +3 -13
  269. package/modules/rigid/sync.js +2 -1
  270. package/modules/settings/Settings.js +52 -20
  271. package/modules/settings/apply.js +23 -9
  272. package/modules/settings/sections.js +39 -6
  273. package/modules/settings/strings.js +2 -0
  274. package/modules/settings/view.js +19 -3
  275. package/modules/sky/dome.js +15 -3
  276. package/modules/sky/environment.js +28 -12
  277. package/modules/sky/fog.js +1 -1
  278. package/modules/sky/frame.js +6 -1
  279. package/modules/sky/shader.js +4 -3
  280. package/modules/sky/skyModule.js +8 -4
  281. package/modules/swarm/Swarm.js +1 -1
  282. package/modules/terrain/ChunkManager.js +61 -15
  283. package/modules/terrain/chunkJob.js +2 -2
  284. package/modules/terrain/index.js +20 -5
  285. package/modules/terrain/terrainEdit.js +8 -4
  286. package/modules/terrain/terrainTexture.js +4 -2
  287. package/modules/timeline/Timeline.js +4 -3
  288. package/modules/timeline/Tween.js +3 -0
  289. package/modules/timeline/letterbox.js +1 -0
  290. package/modules/triggers/index.js +36 -17
  291. package/modules/vegetation/Vegetation.js +81 -19
  292. package/modules/vegetation/densityMap.js +13 -8
  293. package/modules/vegetation/draw.js +147 -24
  294. package/modules/vegetation/groundChunks.js +20 -5
  295. package/modules/vegetation/index.js +3 -3
  296. package/modules/vegetation/modelGeometry.js +9 -4
  297. package/modules/water/Water.js +11 -8
  298. package/modules/weather/Weather.js +7 -2
  299. package/modules/weather/shaders.js +25 -5
  300. package/modules/weather/weatherDraw.js +20 -6
  301. package/modules/world/World.js +2 -1
  302. package/modules/world/index.js +2 -2
  303. package/modules/world/persist.js +6 -2
  304. package/modules/world/views.js +15 -2
  305. package/package.json +4 -1
  306. package/presets.js +5 -5
  307. package/render/PostFX.js +84 -41
  308. package/render/backend.js +137 -16
  309. package/render/cascades.js +3 -1
  310. package/render/cascades.tsl.js +2 -0
  311. package/render/daylight.js +7 -1
  312. package/render/detail.js +7 -4
  313. package/render/effects.js +27 -8
  314. package/render/fogLook.js +24 -0
  315. package/render/fuse.js +5 -2
  316. package/render/fx/detail.tsl.js +9 -7
  317. package/render/fx/index.js +7 -2
  318. package/render/fx/library.tsl.js +1 -0
  319. package/render/fx/lightShaft.tsl.js +114 -0
  320. package/render/fx/noise.tsl.js +25 -8
  321. package/render/fx/objectOrigin.tsl.js +39 -10
  322. package/render/fx/particles.tsl.js +23 -6
  323. package/render/fx/patchNodes.tsl.js +17 -12
  324. package/render/fx/pcss.tsl.js +51 -0
  325. package/render/fx/postWebGPU.tsl.js +89 -29
  326. package/render/fx/sky.tsl.js +3 -9
  327. package/render/fxNumbers.js +10 -4
  328. package/render/impostor.tsl.js +107 -0
  329. package/render/lighting.js +33 -1
  330. package/render/lightmap.js +42 -28
  331. package/render/lights.js +19 -3
  332. package/render/materials.js +6 -4
  333. package/render/mergeCommon.js +4 -1
  334. package/render/occlusion.js +14 -4
  335. package/render/patches.js +79 -41
  336. package/render/postRuns.js +32 -0
  337. package/render/postWebGL.js +97 -10
  338. package/render/probes.js +10 -14
  339. package/render/shaderErrors.js +2 -1
  340. package/render/shadowCache.tsl.js +33 -5
  341. package/render/shadows.js +42 -16
  342. package/render/slots.js +8 -5
  343. package/render/vertexInputs.js +52 -0
  344. package/types/core.d.ts +114 -46
  345. package/types/gameplay.d.ts +56 -23
  346. package/types/generated/core/audio/Audio.d.ts +27 -1
  347. package/types/generated/core/base/Random.d.ts +1 -1
  348. package/types/generated/core/input/Input.d.ts +6 -8
  349. package/types/generated/core/input/inputSeat.d.ts +1 -1
  350. package/types/generated/core/inspect/Budget.d.ts +26 -0
  351. package/types/generated/core/inspect/DebugOverrides.d.ts +0 -2
  352. package/types/generated/core/saves/Saves.d.ts +10 -7
  353. package/types/generated/core/saves/session.d.ts +8 -2
  354. package/types/generated/core/scene/Rays.d.ts +1 -3
  355. package/types/generated/modules/particles/Particles.d.ts +1 -1
  356. package/types/generated/modules/world/World.d.ts +2 -1
  357. package/types/generated/render/PostFX.d.ts +35 -9
  358. package/types/physics.d.ts +43 -11
  359. package/types/pixel.d.ts +1 -1
  360. package/types/tsl.d.ts +62 -1
  361. package/types/world.d.ts +12 -3
  362. package/ui/Focus.js +7 -5
  363. package/ui/Parts.js +1 -1
  364. package/ui/touchPart.js +6 -3
@@ -109,10 +109,12 @@ export function mergeColored(parts, { flat = true } = {}) {
109
109
  if (!flat && !g0.attributes.normal) g0.computeVertexNormals();
110
110
  const g = g0.index ? g0.toNonIndexed() : flat ? g0.clone() : g0; // flat rewrites normals: never on the caller's geometry
111
111
  if (flat) g.computeVertexNormals();
112
- const c = new THREE.Color(hex), p = g.attributes.position.array, n = g.attributes.normal.array;
113
- for (let i = 0; i < p.length; i++) { pos.push(p[i]); nor.push(n[i]); }
114
- for (let i = 0; i < p.length / 3; i++) col.push(c.r, c.g, c.b);
115
- if (keepUV) for (const v of g.attributes.uv.array) uv.push(v);
112
+ // by getX / getY (not .array): an interleaved attribute's array holds the other attributes too, and its length is not the vertex count
113
+ const c = new THREE.Color(hex), p = g.attributes.position, n = g.attributes.normal, t = keepUV && g.attributes.uv;
114
+ for (let i = 0; i < p.count; i++) {
115
+ pos.push(p.getX(i), p.getY(i), p.getZ(i)); nor.push(n.getX(i), n.getY(i), n.getZ(i)); col.push(c.r, c.g, c.b);
116
+ if (t) uv.push(t.getX(i), t.getY(i));
117
+ }
116
118
  }
117
119
  const g = new THREE.BufferGeometry();
118
120
  g.setAttribute('position', new THREE.Float32BufferAttribute(pos, 3));
@@ -1,6 +1,9 @@
1
1
  // Merge geometries that came from different meshes: hlod proxies, a many-material model made into one vegetation species.
2
2
  import { mergeGeometries } from 'three/addons/utils/BufferGeometryUtils.js';
3
3
 
4
+ /** The attribute names every geometry has: what mergeCommon keeps @param {import('three').BufferGeometry[]} geos @returns {string[]} */
5
+ export const commonAttributes = geos => Object.keys(geos[0].attributes).filter(n => geos.every(g => g.attributes[n]));
6
+
4
7
  /**
5
8
  * One geometry from geometries the caller owns (clones): only the attributes all of them have stay, no morph targets, and an index only if
6
9
  * all have one. The inputs are spent: they are changed, then disposed.
@@ -8,7 +11,7 @@ import { mergeGeometries } from 'three/addons/utils/BufferGeometryUtils.js';
8
11
  * @returns {import('three').BufferGeometry}
9
12
  */
10
13
  export function mergeCommon(geos, groups = false) {
11
- const names = Object.keys(geos[0].attributes).filter(n => geos.every(g => g.attributes[n]));
14
+ const names = commonAttributes(geos);
12
15
  const indexed = geos.every(g => g.index);
13
16
  const ready = geos.map(g => {
14
17
  const h = indexed || !g.index ? g : g.toNonIndexed();
@@ -26,7 +26,7 @@ notePatch('occlusion-layers-test', "layers.test on the Layers of a mesh occlusio
26
26
  const { occlusionHidden: HIDDEN_LAYER, occlusionBox: BOX_LAYER } = RESERVED_LAYERS;
27
27
  const HIDE_AFTER = 2;
28
28
  const DELAY = 3; // frames between a box being drawn and its result being read, at worst
29
- const LIGHT_WALK = 60; // frames between looks for new shadow lights
29
+ const LIGHT_WALK = 60; // frames between looks for a game's new shadow lights; the engine's own say so (shadowLightsAdded)
30
30
 
31
31
  /** The mask bit of the batch layer, where a far original waits (hlod, assets.lod); three keeps layer masks unsigned */
32
32
  export const FAR_BIT = (1 << RESERVED_LAYERS.batched) >>> 0;
@@ -71,6 +71,7 @@ export class Occlusion {
71
71
  /** @internal */ this._root = null;
72
72
  /** @internal */ this._hook = null;
73
73
  /** @internal the layer bits this added to each shadow camera, taken back when culling goes off */ this._shadowBits = new Map();
74
+ /** @internal walk the shadow lights in frames up to this one (shadowLightsAdded) */ this._walkUntil = 0;
74
75
  const test = THREE.Layers.prototype.test;
75
76
  /** @internal layers.test of a hidden mesh; `this` is its Layers @this {THREE.Layers} @param {THREE.Layers} layers */ this._unseen = function (layers) { return layers !== engine.camera.layers && test.call(this, layers); };
76
77
  // a restored context holds none of the old queries: one still pending would never answer and its item would stay hidden. Each item starts over and shows until new answers say otherwise
@@ -118,6 +119,12 @@ export class Occlusion {
118
119
  if (this._on) this._box(it);
119
120
  return { remove: () => { this._unbox(it); this._items.delete(it); } };
120
121
  }
122
+ /**
123
+ * The engine made shadow lights (cascades built or rebuilt on a settings or tier change): look at the shadow cameras in the next two frames, not at the next timed walk.
124
+ * Why: a fresh light's camera lacks the hidden layer, so what culling hides vanished from its shadow for up to LIGHT_WALK frames (~1 s). Two frames: WebGPU's cascade
125
+ * node makes its lights in its first render, after this frame's look. A game's own lights stay on the timed walk (a scene walk each frame would cost every game) @internal
126
+ */
127
+ shadowLightsAdded() { this._walkUntil = this._frameNo + 2; }
121
128
  /** The item's box mesh, its query hooks on the renderer in use */
122
129
  _box(it) {
123
130
  if (!it.read) it.box ??= it.meshes.reduce((b, m) => b.expandByObject(m), new THREE.Box3());
@@ -212,19 +219,22 @@ export class Occlusion {
212
219
  it.box.getCenter(center); it.box.getSize(size);
213
220
  const pad = Math.max(size.length() * 0.02, Number.isFinite(moved) ? moved * DELAY : 0);
214
221
  grown.copy(it.box).expandByScalar(pad);
215
- const inside = grown.distanceToPoint(here) <= cam.near * 2;
222
+ // standing on its ground (the camera over its x/z footprint, a batch's 256 m cell, an hlod cell): what is around the camera is drawn whatever stands in front, so its
223
+ // box costs a draw call (filling the screen from inside) and a query that never hides it. Not tested at all: no box, no query, shown. Skipping a test only culls less
224
+ const inside = grown.distanceToPoint(here) <= cam.near * 2 || (here.x >= grown.min.x && here.x <= grown.max.x && here.z >= grown.min.z && here.z <= grown.max.z);
225
+ if (inside) { this._show(it); it.proxy.visible = false; it.runs = 0; it.pad = pad; continue; }
216
226
  const seenLast = n - it.drawn <= 1;
217
227
  // an answer covers a camera move as far as the growth its box had when asked; a cut beyond that is a different view, however big the item is
218
228
  if (moved * DELAY > it.pad) it.wait = n + DELAY;
219
229
  it.pad = pad;
220
230
  if (n <= it.wait || !seenLast) it.runs = 0;
221
- const hide = seenLast && !inside && it.runs >= HIDE_AFTER;
231
+ const hide = seenLast && it.runs >= HIDE_AFTER;
222
232
  if (hide && !it.hidden) { this._hide(it); hidNow = true; } else if (!hide) this._show(it);
223
233
  grown.getSize(size);
224
234
  it.proxy.matrix.makeScale(size.x, size.y, size.z).setPosition(center);
225
235
  it.proxy.matrixWorldNeedsUpdate = true;
226
236
  }
227
- if (hidNow || n % LIGHT_WALK === 0) this._shadowCameras(cam);
237
+ if (hidNow || n <= this._walkUntil || n % LIGHT_WALK === 0) this._shadowCameras(cam);
228
238
  }
229
239
  /** @internal */
230
240
  dispose() { this.enabled = false; this._swap.remove(); this._restored.remove(); this._items.clear(); this._material?.dispose(); }
package/render/patches.js CHANGED
@@ -13,7 +13,7 @@
13
13
  // renderer when the program compiles, so one material works under any engine and two engines on a page each drive their own time and weather.
14
14
  // A patch that moves vertices (shadow: true) owns its shadow: meshes using the material get matching depth and distance
15
15
  // materials automatically (see the customDepthMaterial / customDistanceMaterial defaults below), callers never set them.
16
- // material.clone() does not carry patches (three's Material.copy skips onBeforeCompile): a game applies the effects to the clone again (recipes/09); engine code calls copyPatches(from, to).
16
+ // material.clone() does not carry patches (three's Material.copy skips onBeforeCompile): a game applies the effects to the clone again (recipes/09); engine code copies with cloneMaterial(from).
17
17
  //
18
18
  // Composition contract (each part is checked, so a bad combination fails loudly in development instead of rendering wrong):
19
19
  // needs.data program inputs the code reads, named like three's program parameters ('instancing', 'instancingColor',
@@ -87,9 +87,12 @@ function missing(m, p) {
87
87
  // Why a patch cannot join the material's list, or '' (composition rules from the header)
88
88
  let deriving = false; // re-entrancy flag, set and cleared inside one synchronous call (never across a frame)
89
89
  const CODE = new Map(); // name=cacheKey -> GLSL text, to catch a cacheKey that does not follow the code
90
- const replaced = p => ['vertex', 'fragment'].flatMap(st => Object.entries(p.glsl?.[st] || {}).filter(([, c]) => typeof c === 'object' && c.replace != null).map(([k]) => st + k));
90
+ // one patch per chunk: a replace, or a slot flagged exclusive (fog sits before tonemapping_fragment, but two fog mixes would stack); the marker names the slot
91
+ const EXCLUSIVE = SLOT_NAMES.filter(n => SLOTS[n].exclusive).map(n => `slot=${n}
92
+ `);
93
+ const replaced = p => ['vertex', 'fragment'].flatMap(st => Object.entries(p.glsl?.[st] || {}).filter(([, c]) => typeof c === 'object' && (c.replace != null || EXCLUSIVE.some(m => (c.before ?? '').includes(m)))).map(([k]) => st + k));
91
94
  const DATA = ['instancing', 'instancingColor', 'vertexColors', 'skinning', 'batching'];
92
- function clash(list, p) {
95
+ function clash(list, p, fresh) { // fresh: the CODE keys this call adds, so a failed batch can take them back
93
96
  for (const d of p.needs?.data || []) if (!DATA.includes(d)) {
94
97
  const near = closest(d, DATA);
95
98
  return `patch '${p.name}' needs.data names '${d}', which is not a program input; use ${DATA.join(' | ')}` + (near ? ` (did you mean '${near}'?)` : '');
@@ -108,7 +111,7 @@ function clash(list, p) {
108
111
  const key = p.name + '=' + (p.cacheKey ?? ''), code = JSON.stringify(p.glsl ?? {}).replace(/\/\/ threedog:(begin|end)[^\\"]*/g, '');
109
112
  if (CODE.has(key) && CODE.get(key) !== code)
110
113
  return `patch '${p.name}' produced different GLSL under the same cacheKey '${p.cacheKey ?? ''}'; put every value that changes the code into cacheKey`;
111
- CODE.set(key, code);
114
+ if (!CODE.has(key)) { CODE.set(key, code); fresh?.push(key); }
112
115
  return '';
113
116
  }
114
117
 
@@ -139,7 +142,12 @@ function sharedOnce(pars, src) {
139
142
  const uniforms = new Set(Array.from(expander()(src).matchAll(DECL), m => m[1])), expand = expander();
140
143
  return pars.map(code => expand(code).replace(DECL, (all, name) => uniforms.has(name) ? '' : (uniforms.add(name), all)));
141
144
  }
142
- const PROTO_COMPILE = THREE.Material.prototype.onBeforeCompile;
145
+ const PROTO_COMPILE = THREE.Material.prototype.onBeforeCompile, PROTO_KEY = THREE.Material.prototype.customProgramCacheKey;
146
+ // An engine wrapper put on a material instance (this file's onBeforeCompile / customProgramCacheKey, render/fx/patchNodes.tsl.js's setup methods)
147
+ // carries this key: a function handing back the game's part it wraps (null / three's method when the game had none). The WebGPU route names
148
+ // only the game's GLSL hook by it (render/backend.js), and cloneMaterial carries the game's part instead of a wrapper bound to the original
149
+ /** @internal */
150
+ export const WRAPPED = Symbol.for('threedog.patchWrapper');
143
151
 
144
152
  function apply(shader, list, m, renderer) {
145
153
  for (const p of list) for (const d of p.needs?.data || []) if (!shader[d]) {
@@ -196,12 +204,13 @@ export function patchMaterial(material, patches, { strict = true } = {}) {
196
204
  // the game's own onBeforeCompile / customProgramCacheKey: those there before patching and those assigned after patching are all kept here and run first (user decision 5, 2026-11-02).
197
205
  // Why an instance accessor instead of a warning: before, a game assigning `m.onBeforeCompile = fn` later silently overwrote the wrapper, losing wind / cloud shadow / season;
198
206
  // with a warning an AI could only copy it into the chained form, an extra step for nothing. Now assignment replaces only "the game's part", engine patches still follow, and both apply.
199
- let game = m.onBeforeCompile, gameKey = Object.hasOwn(m, 'customProgramCacheKey') ? m.customProgramCacheKey : null;
207
+ let game = m.onBeforeCompile, gameKey = Object.hasOwn(m, 'customProgramCacheKey') || (!m.isNodeMaterial && m.customProgramCacheKey !== PROTO_KEY) ? m.customProgramCacheKey : null; // own, or a subclass's override on its prototype (a NodeMaterial's is three's own, keyed by its nodes)
200
208
  const own = game !== PROTO_COMPILE;
201
209
  const wrapper = function (shader, renderer) { if (game && game !== PROTO_COMPILE) game.call(this, shader, renderer); apply(shader, list, m, renderer); };
202
210
  // the wrapper marks itself as the engine's and hands out the game's part: the WebGPU route names only the game's GLSL hook (render/backend.js)
203
- wrapper[Symbol.for('threedog.patchWrapper')] = () => game;
211
+ wrapper[WRAPPED] = () => game;
204
212
  const key = () => (gameKey ? gameKey.call(m) : game && game !== PROTO_COMPILE ? game.toString() : '') + '|threedog:' + list.map(p => p.name + '=' + (p.cacheKey ?? '')).join(',');
213
+ key[WRAPPED] = () => gameKey; // cloneMaterial carries the game's own key function, not this one (it reads this material's list)
205
214
  if (!patchOn('material-compile-accessor')) { m.onBeforeCompile = wrapper; m.customProgramCacheKey = key; } // three's plain properties: a later assignment replaces both
206
215
  else {
207
216
  Object.defineProperty(m, 'onBeforeCompile', { configurable: true, enumerable: own, get: () => wrapper, set(fn) { game = fn; m.needsUpdate = true; } });
@@ -210,34 +219,36 @@ export function patchMaterial(material, patches, { strict = true } = {}) {
210
219
  m.addEventListener('dispose', () => dropShadow(m));
211
220
  }
212
221
  // slot form is converted to anchor form at the entry (one internal representation), so the later conflict / shadow / cacheKey checks are the same for both forms; derived ones (copyPatches / shadow material) are already converted
213
- const before = list.slice();
214
- for (const p of deriving ? patches : withProviders(patches, list).map(anchored)) {
215
- // a GLSL-only patch on a NodeMaterial throws even when not strict: skipping it would draw the material without its picture, silently
216
- if (m.isNodeMaterial && !deriving && p.tsl == null) throw codedError('shader-patch', `[threedog] patch '${p.name}' has no tsl version; add tsl: (ctx) => ..., or keep this material on WebGLRenderer (${m.type} is a NodeMaterial)`);
217
- const nodeGap = m.isNodeMaterial && !deriving ? nodePatches(m).gaps(m, p) : '';
218
- if (nodeGap) {
219
- if (strict) throw codedError('shader-patch', `[threedog] ${nodeGap}`);
220
- warnOnce(coded('shader-patch', `[threedog] ${nodeGap}; skipped`));
221
- continue;
222
- }
223
- const bad = deriving ? '' : clash(list, p);
224
- if (bad) {
225
- if (strict) throw codedError('shader-patch', `[threedog] ${bad}`);
226
- warnOnce(coded('shader-patch', `[threedog] ${bad}; patch '${p.name}' skipped`));
227
- continue;
228
- }
229
- const gaps = missing(m, p);
230
- if (gaps?.length) {
231
- const msg = `patch '${p.name}' needs ${gaps.join(', ')}, which ${m.type} does not have`;
232
- if (strict) throw codedError('shader-patch', msg + '; use a material that has these chunks, or #include the threedog_* chunks in your own shader');
233
- warnOnce(coded('shader-patch', '[threedog] ' + msg + '; skipped'));
234
- continue;
222
+ const before = list.slice(), fresh = [];
223
+ try { // any throw (a strict clash, a missing chunk, the NodeMaterial build) puts the list back: a rejected batch leaves no earlier patch installed
224
+ for (const p of deriving ? patches : withProviders(patches, list).map(anchored)) {
225
+ // a GLSL-only patch on a NodeMaterial throws even when not strict: skipping it would draw the material without its picture, silently
226
+ if (m.isNodeMaterial && !deriving && p.tsl == null) throw codedError('shader-patch', `[threedog] patch '${p.name}' has no tsl version; add tsl: (ctx) => ..., or keep this material on WebGLRenderer (${m.type} is a NodeMaterial)`);
227
+ const nodeGap = m.isNodeMaterial && !deriving ? nodePatches(m).gaps(m, p) : '';
228
+ if (nodeGap) {
229
+ if (strict) throw codedError('shader-patch', `[threedog] ${nodeGap}`);
230
+ warnOnce(coded('shader-patch', `[threedog] ${nodeGap}; skipped`));
231
+ continue;
232
+ }
233
+ const bad = deriving ? '' : clash(list, p, fresh);
234
+ if (bad) {
235
+ if (strict) throw codedError('shader-patch', `[threedog] ${bad}`);
236
+ warnOnce(coded('shader-patch', `[threedog] ${bad}; patch '${p.name}' skipped`));
237
+ continue;
238
+ }
239
+ const gaps = missing(m, p);
240
+ if (gaps?.length) {
241
+ const msg = `patch '${p.name}' needs ${gaps.join(', ')}, which ${m.type} does not have`;
242
+ if (strict) throw codedError('shader-patch', msg + '; use a material that has these chunks, or #include the threedog_* chunks in your own shader');
243
+ warnOnce(coded('shader-patch', '[threedog] ' + msg + '; skipped'));
244
+ continue;
245
+ }
246
+ const i = list.findIndex(q => q.name === p.name);
247
+ if (i >= 0) list[i] = p; else list.push(p);
235
248
  }
236
- const i = list.findIndex(q => q.name === p.name);
237
- if (i >= 0) list[i] = p; else list.push(p);
238
- }
239
- if (m.isNodeMaterial) try { nodePatches(m).apply(m, list); } catch (e) { list.splice(0, list.length, ...before); throw e; }
240
- else changedClassic(m);
249
+ if (m.isNodeMaterial) nodePatches(m).apply(m, list);
250
+ } catch (e) { list.splice(0, list.length, ...before); for (const k of fresh) CODE.delete(k); throw e; }
251
+ if (!m.isNodeMaterial) changedClassic(m);
241
252
  dropShadow(m);
242
253
  m.needsUpdate = true;
243
254
  return m;
@@ -437,10 +448,36 @@ export function unpatchMaterial(material, name) {
437
448
  return material;
438
449
  }
439
450
 
451
+ // What three's clone leaves behind. NodeMaterial.copy (and Material.copy's fixed list) carries only properties a fresh instance of the class
452
+ // already has, so what a game set on the instance itself was dropped: its own lighting (mat.setupLightingModel = celLighting, the cel.tsl.js
453
+ // example), its own onBeforeCompile, a field its class never declares. The copy then drew with three's plain lighting (Pigforest: every
454
+ // vegetation model tree lost its toon look). Skipped as three's copy skips them: '_' internals, is* flags, ids, userData (copied by three)
455
+ const NOT_CARRIED = /^(?:is[A-Z]|_)|^(?:id|uuid|version|type|userData|clippingPlanes)$/;
456
+ /** The game's part under engine wrappers (WRAPPED), else the value itself */
457
+ const gamePart = v => { while (typeof v === 'function' && v[WRAPPED]) v = v[WRAPPED](); return v; };
458
+ /**
459
+ * The engine's material copy: from.clone(), plus what the game put on the instance itself (above), plus from's engine patches, each once.
460
+ * Every engine copy of a material goes through here (vegetation models, tinted characters and pickups, terrain textures, batching).
461
+ * @internal
462
+ * @template {Material} M @param {M} from @returns {M}
463
+ */
464
+ export function cloneMaterial(from) {
465
+ const to = /** @type {any} */ (from.clone());
466
+ for (const k of Object.getOwnPropertyNames(from)) {
467
+ if (NOT_CARRIED.test(k) || Object.hasOwn(to, k)) continue; // own on the copy: three's copy already carried it (or the class makes it)
468
+ const d = /** @type {PropertyDescriptor} */ (Object.getOwnPropertyDescriptor(from, k)), raw = d.get ? d.get.call(from) : d.value;
469
+ // an accessor is the engine's (a classic material's patch chains, the node key: copyPatches makes them again) unless it hands out a
470
+ // wrapper of the game's part (onBeforeCompile, customProgramCacheKey); three's copy skips accessors of the game's as well
471
+ if (d.get && !raw?.[WRAPPED]) continue;
472
+ const v = gamePart(raw);
473
+ if (v != null && v !== to[k]) to[k] = v; // null / three's own method: nothing of the game's there
474
+ }
475
+ return /** @type {M} */ (copyPatches(from, to));
476
+ }
477
+
440
478
  /**
441
- * Give `to` the patches of `from`, e.g. after `from.clone()` (three's Material.copy does not carry onBeforeCompile, so a clone
442
- * starts without patches). Returns `to`.
443
- * @internal engine code that clones materials (vegetation fromModel) calls it
479
+ * Give `to` the patches of `from` (three's Material.copy does not carry onBeforeCompile, so a clone starts without patches). Returns `to`.
480
+ * @internal a copy made from `from` goes through cloneMaterial, which calls this; alone it gives the patches to another material
444
481
  * @param {Material} from
445
482
  * @param {Material} to
446
483
  * @returns {Material}
@@ -458,15 +495,16 @@ export function copyPatches(from, to) {
458
495
  // applyEffects to opt in. WeakSet, not userData: userData is carried by clone and written into the file on glTF export, so a game material cloned from an engine one would be mistaken for it.
459
496
  const MADE = new WeakSet();
460
497
  /**
461
- * Record a material as engine-made (terrain, vegetation clones, water); returns it.
498
+ * Record a material (terrain, vegetation clones, water) or a texture as engine-made; returns it. It is also the creator record engine.dispose reads
499
+ * (core/engine/lifecycle.js): only a marked material or texture is freed there, a texture never because the material it sits on is the engine's.
462
500
  * @internal
463
- * @template {Material} M @param {M} m @returns {M}
501
+ * @template {Material | import('three').Texture} M @param {M} m @returns {M}
464
502
  */
465
503
  export function markEngineMade(m) { MADE.add(m); return m; }
466
504
  /**
467
- * Whether the engine made this material (see markEngineMade); a game's `new THREE.*Material` is false.
505
+ * Whether the engine made this material or texture (see markEngineMade); a game's `new THREE.*Material` is false.
468
506
  * @internal
469
- * @param {Material} m @returns {boolean}
507
+ * @param {Material | import('three').Texture} m @returns {boolean}
470
508
  */
471
509
  export function isEngineMade(m) { return MADE.has(m); }
472
510
 
@@ -0,0 +1,32 @@
1
+ // Where a post effect definition can run: one rule for the chain (PostFX _held, postWebGL / postWebGPU when they refuse one) and the picture
2
+ // menu (core/inspect/pictureMenu.js), so the menu's "runs here" never disagrees with what the chain does. Its own file: postWebGPU.tsl.js
3
+ // and core/inspect read it without importing the whole chain.
4
+ import { isWebGPU, backendName } from './backend.js';
5
+
6
+ /** The warning for a pass or node that converts to display colour itself while the engine's output stage does it too (PostFX.add, postWebGPU build). @param {string} what */
7
+ export const OUTPUT_TWICE = what => `post effect '${what}' converts to display colour itself (gamma / renderOutput), and the engine's output stage (tone mapping + output color space) runs too, so the picture is converted twice. ` +
8
+ "If it is meant to BE the output stage, add it with { slot: 'tone' } (it replaces the engine's); otherwise remove the conversion from it";
9
+
10
+ /** WebGLRenderer runs it: a create() (a three.js Pass) or a GLSL fuse snippet @param {any} d */
11
+ export const runsOnWebGL = d => typeof d.create === 'function' || !!d.fuse?.glsl;
12
+ /** WebGPURenderer runs it: a node(), or a fuse with a tsl part @param {any} d */
13
+ export const runsOnWebGPU = d => (d.fuse ? typeof d.fuse.tsl === 'function' : typeof d.node === 'function');
14
+
15
+ /**
16
+ * Whether an effect definition can run on this engine's renderer now: null = yes, { held: true, why } = the device or tier holds it (the game's
17
+ * value stays), { held: false, why } = it cannot run on the renderer the game chose (switching it on throws by name).
18
+ * @param {{ create?: any, node?: any, fuse?: any, backend?: string, skipOnLowTier?: boolean }} d @param {any} e @returns {{ held: boolean, why: string } | null}
19
+ */
20
+ export function runsHere(d, e) {
21
+ const r = e.renderer, gpu = isWebGPU(r);
22
+ if (!gpu && !runsOnWebGL(d)) return e.post?._fellBack
23
+ ? { held: true, why: 'this device has no WebGPU (start() fell back to WebGLRenderer)' }
24
+ : { held: false, why: 'WebGPU only, and the game chose WebGLRenderer (switching it on throws)' }; // before the tier: the mistake must show on every machine
25
+ if (gpu && !runsOnWebGPU(d)) return { held: false, why: d.fuse ? 'its fuse is GLSL only; WebGPURenderer needs fuse.tsl (switching it on throws)'
26
+ : 'it has create() only; WebGPURenderer needs node() (switching it on throws)' };
27
+ if (d.backend === 'webgpu' && gpu && backendName(r) !== 'webgpu') return { held: true, why: r.backend?.parameters?.forceWebGL
28
+ ? "needs three's WebGPU backend; the game chose WebGL2 (forceWebGL: true)"
29
+ : "needs three's WebGPU backend; this device has none, so WebGPURenderer runs on its WebGL2 fallback" };
30
+ if (d.skipOnLowTier && e.tier === 'low') return { held: true, why: "engine.tier is 'low' and the effect declares skipOnLowTier" };
31
+ return null;
32
+ }
@@ -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
 
@@ -115,7 +115,8 @@ function explainBuildError(message) {
115
115
  // 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
116
  const ro = findNodeBuild(() => true), named = /\[threedog\] (patch|post effect) '/.test(message);
117
117
  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.'
118
+ + (/\[vertex-inputs\]/.test(message) ? 'The vertex inputs counted above are the cause (render/vertexInputs.js).'
119
+ : named ? 'The patch or post effect named above returned the node that failed.'
119
120
  : "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
121
  }
121
122