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
@@ -29,6 +29,7 @@ import { registerWebGPUPart } from '../backend.js';
29
29
  import { engineUniformName } from '../engineUniforms.js';
30
30
  import { SLOTS, LIGHT_HOOKS as HOOKS } from '../slots.js';
31
31
  import { notePatch } from '../../core/scene/threePatches.js';
32
+ const WRAPPED = Symbol.for('threedog.patchWrapper'); // the same key as render/patches.js WRAPPED (a registry symbol, so this WebGL-free file need not import it)
32
33
  import { nameNodeBuild, lostStatements } from './nodeErrors.tsl.js';
33
34
 
34
35
  const { Fn, positionLocal, modelViewProjection, materialColor, materialRoughness, materialEmissive, materialNormal, diffuseColor, vec3 } = TSL;
@@ -69,7 +70,10 @@ const PROPS = Object.fromEntries(Object.entries(SLOTS).filter(([, s]) => s.node?
69
70
  return [n, [s.node.prop, DEFAULTS[s.node.prop]]];
70
71
  }));
71
72
  // position chains, by their stand-in node: what setupPosition runs before three's morph / skinning / instancing steps
72
- const PRE = new WeakMap();
73
+ // The registry lives on the shared wrapper below (a second copy of this module, hot reload or another URL, finds the first copy's wrapper and must fill the same map)
74
+ const setupPosition = NodeMaterial.prototype.setupPosition;
75
+ /** @type {WeakMap<object, any>} */
76
+ const PRE = /** @type {any} */ (setupPosition)._threedogPre ?? new WeakMap();
73
77
  /**
74
78
  * The stand-in for a position chain: evaluates to the game's own value (or positionLocal, i.e. leaves three's result as it is) where three
75
79
  * applies positionNode, while the chain itself runs at the start of setupPosition. Its cache key is the chain's, so a different chain is a
@@ -83,13 +87,12 @@ function preMarker(chain, base) {
83
87
  }
84
88
  // Why the prototype and not each material: three's shadow pass draws with its own NodeMaterial, handed our positionNode / castShadowPositionNode
85
89
  // (Renderer._getShadowNodes), and the shadow must sway exactly like the surface. Only materials carrying one of our stand-ins are affected.
86
- const setupPosition = NodeMaterial.prototype.setupPosition;
87
- if (!(/** @type {{ _threedogPre?: boolean }} */ (/** @type {unknown} */ (setupPosition)))._threedogPre) { // already wrapped (module loaded twice)
90
+ if (!(/** @type {any} */ (setupPosition))._threedogPre) { // already wrapped (module loaded twice)
88
91
  NodeMaterial.prototype.setupPosition = Object.assign(function (builder) {
89
92
  const chain = PRE.get(this.positionNode);
90
93
  if (chain) positionLocal.assign(TSL.subBuild(chain, 'POSITION', 'vec3'));
91
94
  return setupPosition.call(this, builder);
92
- }, { _threedogPre: true });
95
+ }, { _threedogPre: PRE });
93
96
  notePatch('node-setup-position', 'NodeMaterial.prototype.setupPosition: runs the vertex-moving patch chain before three builds the position (WebGPU wind and its shadow)',
94
97
  () => { NodeMaterial.prototype.setupPosition = setupPosition; }, { lost: 'on WebGPURenderer, wind and other vertex-moving patches no longer move vertices or their shadow' });
95
98
  }
@@ -181,14 +184,16 @@ function accessors(target, st, enumerable) {
181
184
  }
182
185
  }
183
186
 
187
+ /** fn, marked as the engine's wrapper of inner (the game's own method or three's): cloneMaterial carries inner, never fn, which runs this material's st */
188
+ const wrapper = (fn, inner) => Object.assign(fn, { [WRAPPED]: () => inner });
184
189
  /** Wrap three's setup methods of the NodeMaterial m (a patched one, or a classic material's node twin) to run st's color / normal / output / lighting code */
185
190
  function wrapSetup(m, st, src) {
186
191
  const ctx = extra => ({ fx: FX, tsl: TSL, material: src, ...extra });
187
192
  const diffuse = m.setupDiffuseColor, normal = m.setupNormal, output = m.setupOutput, model = m.setupLightingModel;
188
- m.setupDiffuseColor = function (builder) { const r = diffuse.call(this, builder); if (st.color) diffuseColor.assign(st.color); return r; };
189
- m.setupNormal = function (builder) { return chain(st.list, 'normal', normal.call(this, builder), ctx({ builder })); };
190
- m.setupOutput = function (builder, node) { return output.call(this, builder, chain(st.list, 'output', node, ctx({ builder }))); };
191
- m.setupLightingModel = function (builder) {
193
+ m.setupDiffuseColor = wrapper(function (builder) { const r = diffuse.call(this, builder); if (st.color) diffuseColor.assign(st.color); return r; }, diffuse);
194
+ m.setupNormal = wrapper(function (builder) { return chain(st.list, 'normal', normal.call(this, builder), ctx({ builder })); }, normal);
195
+ m.setupOutput = wrapper(function (builder, node) { return output.call(this, builder, chain(st.list, 'output', node, ctx({ builder }))); }, output);
196
+ m.setupLightingModel = wrapper(function (builder) {
192
197
  const lm = model.call(this, builder);
193
198
  const hooks = st.list.filter(p => codeOf(p, 'lighting')).map(p => [p, hooksOf(codeOf(p, 'lighting'))]);
194
199
  if (!lm || !hooks.length) return lm;
@@ -232,7 +237,7 @@ function wrapSetup(m, st, src) {
232
237
  return r;
233
238
  };
234
239
  return lm;
235
- };
240
+ }, model);
236
241
  }
237
242
 
238
243
  /** Install the accessors and method wrappers once on a NodeMaterial patched directly */
@@ -244,14 +249,14 @@ function install(m) {
244
249
  // clone() carries no patches (as on the GLSL side, where Material.copy skips onBeforeCompile): the copy gets the game's own values, not the
245
250
  // chains, so a clone without copyPatches is the plain material and one with copyPatches has each effect once
246
251
  const clone = m.clone, key = m.customProgramCacheKey;
247
- m.clone = function () {
252
+ m.clone = wrapper(function () {
248
253
  const c = clone.call(this);
249
254
  for (const [prop] of Object.values(PROPS)) if (c[prop] === st.out[prop]) c[prop] = st.own[prop];
250
255
  return c;
251
- };
256
+ }, clone);
252
257
  // three keys NodeMaterial programs by their node properties only; code added inside the setup methods is not one, so two materials
253
258
  // differing only in a color / normal / output / lighting patch would share a program. st.key is built from those patches' node graphs
254
- m.customProgramCacheKey = function () { return key.call(this) + (st.key ? '|threedog:' + st.key : ''); };
259
+ m.customProgramCacheKey = wrapper(function () { return key.call(this) + (st.key ? '|threedog:' + st.key : ''); }, key);
255
260
  return st;
256
261
  }
257
262
 
@@ -0,0 +1,51 @@
1
+ // TSL pcss(): a shadow filter whose edge softens with the distance from caster to receiver (percentage-closer soft shadows), for light.shadow.filterNode.
2
+ // The game assigns it; the engine never does: light.shadow.filterNode = pcss({ lightSize: 0.04 }).
3
+ // Why comparisons only, with no raw depth read: the shadow map keeps three's compare sampler, which WebGL2 refuses to read as plain depth
4
+ // (a sampler type that disagrees with the texture's compare mode fails the draw) and which sunShafts reads too. So the blocker search asks
5
+ // "is a caster at least t nearer the light here?" at four depths t and adds the answers up: the area under that curve is the average distance.
6
+ // Each t is jittered inside its band (per tap and pixel), so on average the estimate is continuous: a sloped caster's edge widens smoothly, not in four steps.
7
+ // Directional lights only (orthographic shadow cameras, the engine's cascades included): depth there is linear, so a depth step is a world distance.
8
+ import { Fn, Loop, float, texture, reference, screenCoordinate, interleavedGradientNoise, vogelDiskSample, max, min } from 'three/tsl';
9
+ import { codedError } from '../../core/base/errorHints.js';
10
+
11
+ /** @typedef {import('three/webgpu').Node} N */
12
+
13
+ /**
14
+ * @param {{ lightSize?: number, samples?: number, maxDistance?: number }} [o]
15
+ * lightSize: how wide the edge grows per world unit between caster and receiver (the sun is about 0.01, a hazy sky 0.05);
16
+ * samples: taps of the final filter (the search takes half, at least 4); maxDistance: world units from caster to receiver beyond which the edge stops growing.
17
+ * @returns {any} a filter for light.shadow.filterNode
18
+ */
19
+ export function pcss({ lightSize = 0.04, samples = 16, maxDistance = 4 } = {}) {
20
+ if (!(lightSize >= 0 && samples >= 1 && maxDistance > 0)) throw codedError('tsl-misuse', `threedog/tsl pcss(): lightSize >= 0, samples >= 1 and maxDistance > 0 (got ${lightSize}, ${samples}, ${maxDistance})`);
21
+ const taps = Math.round(samples), search = Math.max(4, taps >> 1);
22
+ // depths asked in the search, squared steps so a caster close to its receiver (the hard part) is told apart finely
23
+ const steps = [1, 2, 3, 4].map(k => maxDistance * (k / 4) ** 2);
24
+ return Fn(/** @param {any} a @param {any} builder */ ({ depthTexture, shadowCoord, shadow, depthLayer }, builder) => {
25
+ const cam = shadow.camera;
26
+ if (!cam.isOrthographicCamera) throw codedError('tsl-misuse', 'threedog/tsl pcss(): only for a DirectionalLight (an orthographic shadow camera); a spot or point light keeps three\'s filter');
27
+ const lit = (/** @type {N} */ uv, /** @type {any} */ z) => { let d = /** @type {any} */ (texture(depthTexture, uv)); if (depthTexture.isArrayTexture) d = d.depth(depthLayer); return d.compare(z); };
28
+ // per world unit, in shadow-map depth (0 at near, 1 at far, flipped with a reversed depth buffer) and in shadow-map uv (the camera's width)
29
+ const perUnit = float(builder.renderer.reversedDepthBuffer ? -1 : 1).div(reference('far', 'float', cam).sub(reference('near', 'float', cam)));
30
+ const width = reference('right', 'float', cam).sub(reference('left', 'float', cam)).div(reference('zoom', 'float', cam));
31
+ const texel = float(1).div(reference('mapSize', 'vec2', shadow).x);
32
+ const ign = interleavedGradientNoise(screenCoordinate.xy), phi = ign.mul(6.283185307);
33
+ // blocker search over the widest edge that can occur here
34
+ const blocked = float(0).toVar(), gap = float(0).toVar();
35
+ const reach = float(lightSize * maxDistance).div(width).max(texel);
36
+ Loop(search, ({ i }) => {
37
+ const uv = shadowCoord.xy.add(vogelDiskSample(i, search, phi).mul(reach));
38
+ blocked.addAssign(lit(uv, shadowCoord.z).oneMinus());
39
+ for (let k = 0; k < 4; k++) {
40
+ const from = steps[k - 1] ?? 0, band = steps[k] - from, u = ign.add(float(i).mul(4).add(k).mul(0.618034)).fract();
41
+ gap.addAssign(lit(uv, shadowCoord.z.sub(perUnit.mul(u.mul(band).add(from)))).oneMinus().mul(band));
42
+ }
43
+ });
44
+ const distance = gap.div(max(blocked, 1e-4));
45
+ // edge width in shadow-map uv, never under one texel; then plain percentage-closer filtering at that width
46
+ const radius = min(distance.mul(lightSize).div(width), reach).max(texel);
47
+ const sum = float(0).toVar();
48
+ Loop(taps, ({ i }) => { sum.addAssign(lit(shadowCoord.xy.add(vogelDiskSample(i, taps, phi).mul(radius)), shadowCoord.z)); });
49
+ return sum.div(taps);
50
+ });
51
+ }
@@ -4,20 +4,35 @@
4
4
  // just nested calls, so three compiles them into one fullscreen pass and fuse.js's merging is not needed here (nor loaded).
5
5
  // Registered with render/backend.js when threedog/tsl loads (see PostFX.js for why not an import). Only three/webgpu, three/tsl and three's TSL display
6
6
  // nodes are imported: this file must never pull EffectComposer or other WebGL code.
7
- import { RenderPipeline } from 'three/webgpu';
7
+ import { RenderPipeline, UnsignedByteType } from 'three/webgpu';
8
8
  import * as TSL from 'three/tsl';
9
9
  import { bloom } from 'three/addons/tsl/display/BloomNode.js';
10
10
  import { ao } from 'three/addons/tsl/display/GTAONode.js';
11
11
  import { codedError } from '../../core/base/errorHints.js';
12
- import { registerWebGPUPart, MSAA_SAMPLES } from '../backend.js';
12
+ import { warnOnce } from '../../core/base/validate.js';
13
+ import { runsOnWebGPU, OUTPUT_TWICE } from '../postRuns.js';
14
+ import { registerWebGPUPart, MSAA_SAMPLES, borrowRenderer } from '../backend.js';
13
15
  import { RESERVED_LAYERS } from '../layers.js';
14
16
  import * as FX from './library.tsl.js';
15
17
  import { nameNodeBuild, lostStatements } from './nodeErrors.tsl.js';
16
18
 
17
- const { pass, renderOutput, uniform, screenUV, screenSize, time, convertToTexture, mrt, output, normalView, diffuseColor, velocity } = TSL;
19
+ const { pass, renderOutput, uniform, screenUV, screenSize, time, convertToTexture, mrt, output, normalView, diffuseColor, velocity, metalness, roughness, vec2, vec4 } = TSL;
18
20
 
19
- // What PostEffect.needsBuffers can ask of the scene render. Raw, not packed: display nodes read them as they are
20
- const BUFFERS = { normal: normalView, diffuse: diffuseColor, velocity };
21
+ // What PostEffect.needsBuffers can ask of the scene render. Raw, not packed into other encodings: display nodes read them as they are.
22
+ // metalRough is the one exception in storage, not in meaning: both are 0 to 1, so they share one 8-bit target (three's SSR example does the same), a quarter of a half-float one
23
+ const BUFFERS = { normal: normalView, diffuse: diffuseColor, velocity, metalRough: vec2(metalness, roughness) };
24
+ const BYTE_BUFFERS = ['metalRough'];
25
+ // velocity fills only xy of its target: with both asked, metalRough rides in its zw, one target fewer (output + normal + diffuse + velocity is WebGPU's default ceiling)
26
+ const VELOCITY_METAL_ROUGH = vec4(/** @type {any} */ (velocity), BUFFERS.metalRough); // three types the velocity node as no vec2
27
+
28
+ /** How many scene targets the device takes. Every target here is rgba16float or rgba8unorm, 8 bytes per sample each in WebGPU's table, so bytes reduce to a count; Infinity before the device exists */
29
+ function roomOf(r) {
30
+ const be = r.backend, l = be?.device?.limits, gl = be?.gl;; if (!l && !gl) return Infinity;
31
+ // read once per backend: render() asks every frame, and a GL query there would be a sync call each frame
32
+ if (!rooms.has(be)) rooms.set(be, l ? Math.min(l.maxColorAttachments, Math.floor(l.maxColorAttachmentBytesPerSample / 8)) : gl.getParameter(gl.MAX_DRAW_BUFFERS));
33
+ return rooms.get(be);
34
+ }
35
+ const rooms = new WeakMap();
21
36
 
22
37
  /** Which uniform a param value makes: 'number' (numbers, booleans as 0 / 1), a color or vector kind, or null: anything else rebuilds the chain when it changes */
23
38
  const kindOf = v => (typeof v === 'number' || typeof v === 'boolean' ? 'number' : v?.isColor ? 'color' : v?.isVector2 ? 'vec2' : v?.isVector3 ? 'vec3' : v?.isVector4 ? 'vec4' : null);
@@ -71,13 +86,15 @@ function extraPass(scene, camera, opts) {
71
86
  return n;
72
87
  }
73
88
 
89
+ const SCENE = 'scene render', OUTPUT = 'output (tone mapping)'; // the engine's own stages in P.stages and post.order
90
+
74
91
  const onlyCreate = e => codedError('post-effect', `[threedog] post effect '${e.name}' has only create() (a three.js Pass, WebGLRenderer only); on WebGPURenderer give it ` +
75
92
  `node: (input, ctx) => colorNode, e.g. node: (input, { tsl, p }) => tsl.vec4(input.rgb.mul(p.amount), input.a) (recipe 52)`);
76
93
  const glslOnly = e => codedError('post-effect', `[threedog] post effect '${e.name}': its fuse snippet is GLSL only; on WebGPURenderer add fuse.tsl: ` +
77
94
  `(color, uv, t) => color, e.g. tsl: (color, uv, { tsl, p }) => tsl.vec4(color.rgb.mul(p.amount), color.a) (recipe 52)`);
78
95
 
79
96
  const webgpuPost = {
80
- init(post) { post._pipe = null; },
97
+ init(post) { post._pipe = null; post._pipeOut = null; },
81
98
  object: post => (post._pipe ? { pipeline: post._pipe.pipeline, scenePass: post._pipe.scenePass } : null),
82
99
  // The pass node owns its render targets and resizes them with the renderer; nothing is handed out as ping-pong targets on this backend
83
100
  targets: () => null,
@@ -96,30 +113,41 @@ const webgpuPost = {
96
113
  return true;
97
114
  },
98
115
  samples: post => (post.active ? post._pipe?.samples ?? (post._aa ? MSAA_SAMPLES : 0) : post.engine.renderer.samples),
99
- setAntialias(post) { if (post._pipe) post._pipe.key = null; },
116
+ // nothing here: sync's key holds the effective samples, so a switch under a temporal resolve (samples stay 0) rebuilds nothing
117
+ setAntialias() {},
100
118
  sync(post) {
101
119
  const { renderer, scene, camera } = post.engine;
102
120
  const on = post._sorted().filter(e => e.enabled);
121
+ // nothing on: the frame goes straight to the canvas, so the scene pass's color, depth and MSAA targets are freed now, not at engine.dispose
122
+ // (postWebGL.js frees its composer targets the same way); the next effect builds a new pipeline (GPT review l2-render 6)
123
+ if (!on.length) { for (const e of post._list) { e._impl?.dispose?.(); e._impl = null; } webgpuPost.dispose(post); return; }
103
124
  // the union over the effects that are on, in one fixed order: one setMRT for all of them, and none at all (no extra targets) when nobody asks
104
125
  const buffers = Object.keys(BUFFERS).filter(b => on.some(e => e._def.needsBuffers?.includes(b)));
126
+ const packed = buffers.includes('velocity') && buffers.includes('metalRough'), room = roomOf(renderer);
127
+ const targets = Object.fromEntries(buffers.filter(b => !(packed && b === 'metalRough')).map(b => [b, packed && b === 'velocity' ? VELOCITY_METAL_ROUGH : BUFFERS[b]]));
128
+ // over the device's limit three's pipeline validation fails naming no effect; checked before anything is torn down, so add() rolls back cleanly
129
+ const n = 1 + Object.keys(targets).length;
130
+ if (n > room) throw codedError('post-effect', `[threedog] post effects ${on.filter(e => e._def.needsBuffers?.length).map(e => `${e.name} (${e._def.needsBuffers.join(', ')})`).join(', ')} ` +
131
+ `need ${n} scene targets (${n * 8} bytes per pixel), this device takes ${room} (${room * 8} bytes): turn off the one that matters least`);
105
132
  // velocity means a temporal resolve follows: it is the antialiasing, and MSAA under it would only cost
106
133
  const samples = post._aa && !buffers.includes('velocity') ? MSAA_SAMPLES : 0;
107
- for (const e of on) if (e._def.fuse ? typeof e._def.fuse.tsl !== 'function' : typeof e._def.node !== 'function') throw e._def.fuse ? glslOnly(e) : onlyCreate(e);
134
+ for (const e of on) if (!runsOnWebGPU(e._def)) throw e._def.fuse ? glslOnly(e) : onlyCreate(e); // the rule the picture menu's "runs here" reads too
108
135
  // Same effects, same build, same samples: the graph is current (a set() of a number param never gets here)
109
- const key = `${samples}|${buffers}|${on.map(e => e.name).join(',')}`;
136
+ const key = `${samples}|${buffers}|${room}|${on.map(e => e.name).join(',')}`;
110
137
  if (post._pipe?.key === key && post._pipe.camera === camera) return;
111
138
  let P = post._pipe;
112
139
  if (!P) P = post._pipe = { pipeline: new RenderPipeline(renderer), scenePass: null, samples: -1, buffers: '', key: null, order: [] };
113
140
  P.key = null; // the graph is coming down: when a node() throws below, PostFX syncs the old list again, and that sync must rebuild, not find its key current
141
+ P.room = room; P.packed = packed;
114
142
  if (P.samples !== samples || P.buffers !== `${buffers}` || P.camera !== camera) {
115
143
  P.scenePass?.dispose(); P.scenePass = pass(scene, camera, { samples }); P.samples = samples; P.buffers = `${buffers}`; P.camera = camera;
116
- if (buffers.length) P.scenePass.setMRT(mrt({ output, ...Object.fromEntries(buffers.map(b => [b, BUFFERS[b]])) }));
144
+ if (buffers.length) P.scenePass.setMRT(mrt({ output, ...targets }));
145
+ for (const b of Object.keys(targets)) if (BYTE_BUFFERS.includes(b)) P.scenePass.getTexture(b).type = UnsignedByteType;
146
+ P.stages = []; // a new scene pass (samples, MRT, camera): every stage reads it, none is kept
117
147
  }
118
- // Every structural change rebuilds every effect's nodes: an effect's input is the node before it, which changed too
119
- for (const e of post._list) { e._impl?.dispose?.(); e._impl = null; }
120
- const size = post._size(), order = [];
148
+ const size = post._size();
121
149
  const ctxOf = (e, made) => ({ engine: post.engine, scene, camera, width: size.x, height: size.y, params: paramsOf(e), scenePass: P.scenePass,
122
- tsl: TSL, fx: FX, display: displayFor(made), p: uniformsOf(e) });
150
+ buffer: b => (b === 'metalRough' && P.packed ? P.scenePass.getTextureNode('velocity').zw : P.scenePass.getTextureNode(b)), tsl: TSL, fx: FX, display: displayFor(made), p: uniformsOf(e), borrowRenderer });
123
151
  // the effect's node is built only when the pipeline first draws: errors then, and statements lost outside an Fn, name the effect
124
152
  const run = (e, color) => {
125
153
  const label = `[threedog] post effect '${e.name}'`;
@@ -128,29 +156,64 @@ const webgpuPost = {
128
156
  const build = (e, color) => {
129
157
  const made = [];
130
158
  e._impl = { nodes: made, dispose() { for (const n of made) n.dispose?.(); made.length = 0; } };
131
- order.push(e.name);
132
159
  e._read = new Set(); e._building = true;
133
160
  try {
134
161
  if (e._def.fuse) {
135
162
  const f = e._def.fuse, c = ctxOf(e, made);
136
163
  return f.tsl(color, screenUV, { ...c, time, resolution: screenSize, input: f.reads ? c.display.texture(color) : null });
137
164
  }
138
- return e._def.node(color, ctxOf(e, made));
165
+ const out = e._def.node(color, ctxOf(e, made));
166
+ // a node that calls renderOutput() itself is tone mapped a second time by the engine's own output stage: said once, never guessed away
167
+ // (an output stage the INPUT already had is the engine's own, for ldr / final effects)
168
+ if (e.slot !== 'tone' && out?.traverse) {
169
+ const had = new Set(); color.traverse(x => x.isRenderOutputNode && had.add(x));
170
+ let again = false; out.traverse(x => { if (x.isRenderOutputNode && !had.has(x)) again = true; });
171
+ if (again) warnOnce(OUTPUT_TWICE(e.name));
172
+ }
173
+ return out;
139
174
  } finally { e._building = false; }
140
175
  };
141
176
  const slot = s => on.filter(e => e.slot === s);
142
- let color = P.scenePass.getTextureNode();
143
- const sceneFx = slot('scene')[0];
144
- if (sceneFx) color = run(sceneFx, color); else order.push('scene render');
145
- for (const e of slot('hdr')) color = run(e, color);
146
- const toneFx = slot('tone')[0]; // a game's tone stage replaces renderOutput (it outputs display color itself)
147
- if (toneFx) color = run(toneFx, color); else { color = renderOutput(color); order.push('output (tone mapping)'); }
148
- for (const e of [...slot('ldr'), ...slot('final')]) color = run(e, color);
177
+ // the chain as stages: an effect handle, or the engine's own 'scene render' / 'output (tone mapping)' (a game's tone stage replaces renderOutput)
178
+ const want = [slot('scene')[0] ?? SCENE, ...slot('hdr'), slot('tone')[0] ?? OUTPUT, ...slot('ldr'), ...slot('final')];
179
+ // Why stages are kept: an effect's input is the node before it, so only what follows the first changed stage has to be rebuilt. Toggling a
180
+ // cheap final effect left voxel GI re-voxelising and TRAA / reflections losing their history (GPT review l2-render 5). A stage is the same when
181
+ // it is the same effect at the same place and still holds the nodes it was built with (set() of a baked-in param or freeImpl dropped them)
182
+ const was = P.stages ?? [];
183
+ let k = 0;
184
+ while (k < want.length && k < was.length && was[k].e === want[k] && (typeof want[k] === 'string' || want[k]._impl === was[k].impl)) k++;
185
+ const kept = new Set(was.slice(0, k).map(s => s.e));
186
+ for (const e of post._list) if (!kept.has(e)) { e._impl?.dispose?.(); e._impl = null; }
187
+ const stages = was.slice(0, k);
188
+ P.stages = stages; // set before the build: a node() that throws below leaves only stages that are still whole
189
+ let color = k ? stages[k - 1].out : P.scenePass.getTextureNode();
190
+ for (const w of want.slice(k)) {
191
+ if (w === OUTPUT) color = renderOutput(color);
192
+ else if (w !== SCENE) color = run(w, color);
193
+ stages.push({ e: w, impl: typeof w === 'string' ? null : w._impl, out: color });
194
+ }
195
+ const order = stages.map(s => (typeof s.e === 'string' ? s.e : s.e.name));
149
196
  P.pipeline.outputColorTransform = false;
150
197
  P.pipeline.outputNode = color; P.pipeline.needsUpdate = true;
151
198
  P.output = color; P.order = order; P.key = key;
152
199
  },
200
+ /**
201
+ * The effect whose own pass draws with this material, or null: a display node keeps its fullscreen materials as plain fields (three's GTAO, bloom,
202
+ * godrays, SSR ...). Stages in chain order, each read through the node it handed back: an effect's output contains the stages before it, so the
203
+ * first stage that has the material owns it. An effect that is only an expression is compiled into the next pass with its neighbors and owns none.
204
+ */
205
+ ownerOf(post, id) {
206
+ const is = m => m?.isMaterial && m.id === id, has = n => Object.values(n).some(v => (Array.isArray(v) ? v.some(is) : is(v)));
207
+ for (const s of post._pipe?.stages ?? []) {
208
+ if (typeof s.e === 'string') continue;
209
+ let found = !!s.impl?.nodes.some(has);
210
+ if (!found) s.out?.traverse?.(n => { found ||= has(n); });
211
+ if (found) return s.e;
212
+ }
213
+ return null;
214
+ },
153
215
  dispose(post) {
216
+ if (post._pipeOut) { post._pipeOut.scenePass.dispose(); post._pipeOut.pipeline.dispose(); post._pipeOut = null; }
154
217
  const P = post._pipe;
155
218
  if (!P) return;
156
219
  P.scenePass?.dispose(); P.pipeline.dispose(); post._pipe = null;
@@ -159,7 +222,8 @@ const webgpuPost = {
159
222
  sceneTarget: () => null,
160
223
  // target: the pipeline's last quad draws into the renderer's current target (pass() nodes put it back after their own renders)
161
224
  render(post, dt, target = null) {
162
- if (!post._pipe) post._sync();
225
+ // a chain built before start() had no device to check against: the first frame after it rebuilds once and checks (sync's key holds the room)
226
+ if (!post._pipe || post._pipe.room !== roomOf(post.engine.renderer)) post._sync();
163
227
  onTarget(post.engine.renderer, target, () => post._pipe.pipeline.render());
164
228
  },
165
229
  /**
@@ -171,15 +235,26 @@ const webgpuPost = {
171
235
  * MSAA: the renderer's own samples (made with the default antialias), so an effect-free frame needs no pipeline; a runtime switch away from
172
236
  * them runs the pipeline with pass() samples (PostFX active).
173
237
  */
174
- direct(post, target = null) { const { renderer, scene, camera } = post.engine; onTarget(renderer, target, () => renderer.render(scene, camera)); },
238
+ direct(post, target = null) {
239
+ const { renderer, scene, camera } = post.engine;
240
+ if (!target) { renderer.render(scene, camera); return; }
241
+ // a target gets the canvas's pixels too (tone mapped, output color space): three's plain draw into a target is linear. A small pipeline, scene pass -> renderOutput,
242
+ // kept for the next call (a minimap asks every frame) and freed with the chain
243
+ let O = post._pipeOut;
244
+ if (!O || O.camera !== camera || O.scene !== scene) { // engine.scene / engine.camera can be replaced: the pass node holds the ones it was made with
245
+ O?.scenePass.dispose(); O?.pipeline.dispose();
246
+ const scenePass = pass(scene, camera, { samples: 0 }), pipeline = new RenderPipeline(renderer);
247
+ pipeline.outputColorTransform = false; pipeline.outputNode = renderOutput(scenePass.getTextureNode());
248
+ O = post._pipeOut = { pipeline, scenePass, camera, scene };
249
+ }
250
+ onTarget(renderer, target, () => O.pipeline.render());
251
+ },
175
252
  };
176
253
 
177
- /** Run draw with target set (null: as it is, the canvas), then put the previous target back */
254
+ /** Run draw with target set (null: as it is, the canvas), the renderer borrowed and given back */
178
255
  function onTarget(r, target, draw) {
179
256
  if (!target) { draw(); return; }
180
- const prev = r.getRenderTarget();
181
- r.setRenderTarget(target);
182
- try { draw(); } finally { r.setRenderTarget(prev); }
257
+ borrowRenderer(r, () => { r.setRenderTarget(target); draw(); });
183
258
  }
184
259
 
185
260
  registerWebGPUPart('post', Object.freeze(webgpuPost));
@@ -11,7 +11,7 @@
11
11
  // only GLSL throws [webgpu-needs-tsl] by name on this renderer; the GLSL form keeps drawing on WebGLRenderer unchanged.
12
12
  import * as TSL from 'three/tsl';
13
13
  import { MeshBasicNodeMaterial, BackSide } from 'three/webgpu';
14
- import { noise } from './noise.tsl.js';
14
+ import { noise, hash } from './noise.tsl.js';
15
15
  import * as FX from './library.tsl.js';
16
16
  import { uniforms as engineUniforms, valueNode } from './uniforms.tsl.js';
17
17
  import { codedError } from '../../core/base/errorHints.js';
@@ -19,7 +19,7 @@ import { registerWebGPUPart } from '../backend.js';
19
19
  import { SKY as K } from '../fxNumbers.js';
20
20
 
21
21
  const { Fn, positionGeometry, varying, float, vec2, vec3, vec4, select, mix, pow, max, dot,
22
- floor, fract, step, smoothstep, clamp, normalize, If } = TSL;
22
+ floor, step, smoothstep, clamp, normalize, If } = TSL;
23
23
 
24
24
  /** @template {string} T @typedef {import('three/webgpu').Node<T>} N */
25
25
  /**
@@ -47,12 +47,6 @@ function nodesOf(u, engine) {
47
47
  return n;
48
48
  }
49
49
 
50
- /** GLSL h3 (the star hash) */
51
- const h3 = Fn(/** @param {[N<'vec3'>]} a */ ([p0]) => {
52
- const p = fract(p0.mul(K.starMul).add(K.starAdd)).mul(K.starScale);
53
- return fract(p.x.mul(p.y).mul(p.z).mul(p.x.add(p.y).add(p.z)));
54
- });
55
-
56
50
  /** clouds dim toward SKY.nightDim at night (GLSL nightDim + (1 - nightDim) * (1 - night)) */
57
51
  const nightDim = (/** @type {SkyNodes} */ U) => U.uNight.oneMinus().mul(1 - K.nightDim).add(K.nightDim);
58
52
 
@@ -141,7 +135,7 @@ function domeColor(U, kind, clouds, layers) {
141
135
  col.assign(mix(col, cl.rgb, cl.a)); clA.assign(cl.a);
142
136
  });
143
137
  // stars behind the clouds, dimmed by the weather's cover (see the GLSL comment in shader.js)
144
- const star = step(U.uStars.oneMinus(), h3(g)).mul(U.uNight).mul(smoothstep(0, K.starFade, d.y)).mul(clA.oneMinus())
138
+ const star = step(U.uStars.oneMinus(), hash(vec2(g.x.add(g.z.mul(K.starZ)), g.y))).mul(U.uNight).mul(smoothstep(0, K.starFade, d.y)).mul(clA.oneMinus())
145
139
  .mul(clamp(U.uWeatherCloud, 0, 1).mul(U.uStarCloudDim).oneMinus());
146
140
  col.addAssign(vec3(star));
147
141
  // fog band (fog.js DOME_FOG): always built, switched by uFogBand
@@ -6,18 +6,24 @@
6
6
 
7
7
  /** threedogWind: sway = sin(t * (speed + gust * uWind) + origin . phase) * weight + sin(t * speed2 + origin . phase2) * weight2; lean along x, side share on z */
8
8
  export const WIND = Object.freeze({ speed: 1.2, gust: 0.6, phase: [0.31, 0.23], weight: 0.6, speed2: 2.9, phase2: [0.77, -0.4], weight2: 0.4, lean: 0.4, side: 0.6 });
9
- /** threedogHash: fract(sin(dot(p, dir)) * scale) */
10
- export const HASH = Object.freeze({ dir: [127.1, 311.7], scale: 43758.5453 });
9
+ /** threedogHash: the x of pcg2d (Jarzynski & Olano 2020, "Hash Functions for GPU Rendering") on p's float bits (public) or the cell floor(p) (engine noise), as uints:
10
+ * v = v * mul + add; v.x += v.y * mul; v.y += v.x * mul; v ^= v >> 16; v.x += v.y * mul; x ^= x >> 16; value = (x >> 8) / 2^24, so 0 <= value < 1.
11
+ * Why integers and not the usual sin hash: sin of large arguments differs between GPUs and between GLSL and WGSL, so WebGL and WebGPU drew different
12
+ * patterns; uint multiply / xor / shift wrap the same way everywhere, and a 24-bit uint turns into a float exactly. */
13
+ export const HASH = Object.freeze({ mul: 1664525, add: 1013904223 });
14
+ /** A whole-cell offset as the uint it adds to a cell's first pcg2d step (n * mul, wrapped to 32 bits): what the dabs add per salt @param {number} n */
15
+ export const hashOffset = n => Math.imul(n, HASH.mul) >>> 0;
11
16
  /** threedogCloudShadow: two noise octaves (weight, then weight2 at octave x the scale), cover edge width */
12
17
  export const CLOUD = Object.freeze({ weight: 0.65, octave: 2.3, weight2: 0.35, edge: 0.25 });
13
18
 
14
19
  /** threedogDetailNoise (render/detail.js): fbm octave step (p = p * lacunarity + offset), paper = fbm * paper[0] + stretched noise * paper[1]
15
20
  * at (x * paperStretch[0], y * paperStretch[1]); stroke = smoothstep(stroke[0], stroke[1], fbm(x, y * strokeStretch)); dabs: first weight, then * dabFall per octave */
16
21
  export const DETAIL = Object.freeze({ lacunarity: 2.03, offset: 17, paper: [0.65, 0.35], paperStretch: [7, 0.9], stroke: [0.15, 0.85], strokeStretch: 1.7, dabWeight: 0.85, dabFall: 0.6 });
17
- /** The sky dome (modules/sky/shader.js, clouds.js): star hash h3 = fract(p * mul + add) * scale; sun glow power; sun-below-horizon cut-off;
22
+ /** The sky dome (modules/sky/shader.js, clouds.js): stars = threedogHash of the star cell g as (g.x + g.z * starZ, g.y) (no two cells of a
23
+ * star grid up to starZ / 2 per side share a value); sun glow power; sun-below-horizon cut-off;
18
24
  * stars fade in over dir.y 0..starFade; clouds dim to nightDim at night; plane tone smoothstep(tone); cumulus fbm step / normalizer,
19
25
  * sun-ward probe step, cover share, core width, shading (rim boost, core darkening) */
20
- export const SKY = Object.freeze({ starMul: 0.3183099, starAdd: 0.1, starScale: 17, glowPower: 12, sunCut: 0.05, starFade: 0.25, nightDim: 0.35,
26
+ export const SKY = Object.freeze({ starZ: 4096, glowPower: 12, sunCut: 0.05, starFade: 0.25, nightDim: 0.35,
21
27
  planeTone: [0.3, 0.8], lacunarity: 2.03, offset: 3.7, norm: 0.9375, toSun: 0.12, cover: 0.9, core: 0.35, rim: 0.5, coreDark: 0.45 });
22
28
 
23
29
  /** Luminance weights: Rec. 709 for light (render/lighting.js, the sky's own light), Rec. 601 for a detail texture's alpha. Two sets on purpose: moving either shifts pictures */
@@ -0,0 +1,107 @@
1
+ // Impostor cards for far plants (vegetation.define({ impostor })): bake N views around a model into array textures (albedo + normal, alpha = coverage),
2
+ // then draw each far plant as a card that turns to the camera and samples the nearest view, lit live through the baked normals.
3
+ // Why bake from the species' own model and materials: the card keeps the game's colours, alpha cut and lighting model; the engine adds no look.
4
+ // Why one array layer per view (not a flat atlas): low mips of neighbouring views never bleed into each other.
5
+ // Why a ring of views (not octahedral): far trees are seen from near eye level in a follow camera, and a ring spends every texel on the side views.
6
+ // WebGPU route only (also WebGPURenderer's WebGL2 backend); registered as a WebGPU part like the other .tsl.js files, so WebGL bundles stay as they are.
7
+ import * as THREE from 'three/webgpu'; // three/webgpu, not three: threedog/tsl stays WebGL-free (both share three.core.js)
8
+ import { MeshBasicNodeMaterial, MeshLambertNodeMaterial, MeshStandardNodeMaterial, MeshToonNodeMaterial } from 'three/webgpu';
9
+ import { attribute, cameraPosition, cameraViewMatrix, positionGeometry, vec2, vec3, vec4, float, int, atan, cos, sin, floor, fract, texture, varying, uv, normalLocal, faceDirection, uniform } from 'three/tsl';
10
+ import { registerWebGPUPart, holdRenderer, releaseRenderer } from './backend.js';
11
+ import { season } from './fx/season.tsl.js';
12
+
13
+ const TAU = Math.PI * 2;
14
+
15
+ /** Bounds of a plant around its own vertical axis: the card spans [-r, r] across and [minY, maxY] up (plants stand on their origin) */
16
+ function bounds(geometry) {
17
+ const p = geometry.attributes.position;
18
+ let r = 0, lo = Infinity, hi = -Infinity;
19
+ for (let i = 0; i < p.count; i++) { r = Math.max(r, Math.hypot(p.getX(i), p.getZ(i))); lo = Math.min(lo, p.getY(i)); hi = Math.max(hi, p.getY(i)); }
20
+ // a small margin so mip filtering of the outermost leaves never reaches the card edge
21
+ const m = 1.04, h = (hi - lo) || 1;
22
+ return { radius: (r || 0.5) * m, minY: lo - h * (m - 1) / 2, height: h * m };
23
+ }
24
+
25
+ /** What a material renders into the normal layers: its object-space normal packed 0..1, and its own alpha cut so leaf cards keep their outline */
26
+ function normalMaterial(m) {
27
+ const alpha = m?.map ? texture(m.map, uv()).a : float(1);
28
+ const n = new MeshBasicNodeMaterial({ side: m?.side ?? THREE.FrontSide });
29
+ n.colorNode = vec4(normalLocal.mul(faceDirection).normalize().mul(0.5).add(0.5), alpha);
30
+ n.alphaTest = m?.alphaTest || (m?.transparent || m?.map ? 0.5 : 0);
31
+ return n;
32
+ }
33
+
34
+ /**
35
+ * Render the views. src: { geometry, material (one or an array matching the geometry's groups) }, the species' own, unpatched.
36
+ * Albedo comes from the game's materials under a white ambient light of intensity PI: three's diffuse BRDF divides irradiance by PI, so the
37
+ * layer holds the surface colour (vertex colours and maps included) with no sun baked in; the live scene lights the card.
38
+ * @returns {{ albedo: THREE.Texture, normal: THREE.Texture, views: number, radius: number, minY: number, height: number, dispose(): void }}
39
+ */
40
+ function bake(renderer, src, { views = 8, size = 128 } = {}) {
41
+ const b = bounds(src.geometry);
42
+ // depth > 1: an array texture, one layer per view (three sets isArrayTexture from the depth)
43
+ const mk = () => new THREE.RenderTarget(size, size, { depth: views, type: THREE.HalfFloatType, generateMipmaps: true, minFilter: THREE.LinearMipmapLinearFilter, magFilter: THREE.LinearFilter });
44
+ const scene = new THREE.Scene(), holder = new THREE.Group(), mesh = new THREE.Mesh(src.geometry, src.material);
45
+ holder.add(mesh); scene.add(holder, new THREE.AmbientLight(0xffffff, Math.PI));
46
+ const cam = new THREE.OrthographicCamera(-b.radius, b.radius, b.minY + b.height, b.minY, 0.01, b.radius * 6);
47
+ cam.position.set(0, 0, b.radius * 3); cam.lookAt(0, 0, 0); cam.updateMatrixWorld();
48
+ const albedo = mk(), normal = mk(), normals = [src.material].flat().map(normalMaterial);
49
+ let done = false;
50
+ // the renderer is borrowed mid-frame: everything the bake changes is put back, whether it finishes or throws (render/backend.js holdRenderer)
51
+ const held = holdRenderer(renderer);
52
+ try {
53
+ renderer.setClearColor(0x000000, 0); renderer.autoClear = true;
54
+ for (const [rt, mat] of [[albedo, src.material], [normal, Array.isArray(src.material) ? normals : normals[0]]]) {
55
+ mesh.material = mat;
56
+ for (let i = 0; i < views; i++) {
57
+ // view i is the plant seen from yaw i/N around it: turning the plant by -yaw shows that side to a camera on +Z (the card's maths in cardMaterial)
58
+ holder.rotation.y = -i * TAU / views; holder.updateMatrixWorld(true);
59
+ renderer.setRenderTarget(rt, i);
60
+ renderer.render(scene, cam);
61
+ }
62
+ }
63
+ done = true;
64
+ } finally {
65
+ releaseRenderer(held);
66
+ for (const n of normals) n.dispose();
67
+ if (!done) { albedo.dispose(); normal.dispose(); } // a failed bake leaves no render targets behind
68
+ }
69
+ return { albedo: albedo.texture, normal: normal.texture, views, ...b, dispose() { albedo.dispose(); normal.dispose(); } };
70
+ }
71
+
72
+ /**
73
+ * The card material. Per instance (InstancedBufferGeometry): aCenter (world position of the plant), aShape (yaw, across scale, up scale; 0 scale =
74
+ * felled, the card collapses to a point), aTint (instance colour, as InstancedMesh's instanceColor tints the mesh). The material class follows the
75
+ * species' first material (toon stays toon, unlit stays unlit), so the card answers the scene's lights the way the mesh does.
76
+ */
77
+ function cardMaterial(src, b) {
78
+ const m0 = [src.material].flat()[0], type = m0?.type ?? '';
79
+ const C = /Toon/.test(type) ? MeshToonNodeMaterial : /Basic/.test(type) ? MeshBasicNodeMaterial : /Lambert|Phong/.test(type) ? MeshLambertNodeMaterial : MeshStandardNodeMaterial;
80
+ const m = /** @type {any} */ (new C());
81
+ if (m0?.gradientMap && 'gradientMap' in m) m.gradientMap = m0.gradientMap;
82
+ if (m.isMeshStandardNodeMaterial) { m.roughness = m0?.roughness ?? 1; m.metalness = 0; }
83
+ m.alphaTest = 0.5;
84
+ const N = b.views, center = attribute('aCenter', 'vec3'), shape = attribute('aShape', 'vec3');
85
+ const toCam = cameraPosition.sub(center), ang = /** @type {any} */ (atan)(toCam.x, toCam.z); // the camera's yaw seen from the plant
86
+ // nearest baked view in the plant's own frame; fract keeps it positive whatever the yaw (a % of a negative stays negative in WGSL)
87
+ const cell = floor(fract(ang.sub(shape.x).div(TAU).add(0.5 / N).add(4)).mul(N));
88
+ const right = vec3(cos(ang), 0, sin(ang).negate());
89
+ const across = uniform(b.radius * 2), up = uniform(b.height), minY = uniform(b.minY);
90
+ const pg = /** @type {any} */ (positionGeometry);
91
+ m.positionNode = center.add(right.mul(pg.x.mul(across).mul(shape.y))).add(vec3(0, pg.y.mul(up).add(minY).mul(shape.z), 0));
92
+ // the layers come out upside down against the card's uv on both WebGPU backends (render-target rows), so read them flipped
93
+ const layer = int(/** @type {any} */ (varying(cell)).add(0.5)), st = vec2(uv().x, uv().y.oneMinus());
94
+ const alb = texture(b.albedo, st).depth(layer);
95
+ // the season tint the mesh gets from its patches (effects on), so autumn reaches the far cards too; the bake itself is untinted
96
+ const rgb = alb.rgb.mul(attribute('aTint', 'vec3'));
97
+ m.colorNode = vec4(src.season ? season(rgb, 0) : rgb, alb.a);
98
+ if (!m.isMeshBasicNodeMaterial) {
99
+ // baked normal is in the plant's own frame: turn it by the plant's yaw into the world, then into view space (what normalNode takes)
100
+ const n = texture(b.normal, st).depth(layer).rgb.mul(2).sub(1), y = shape.x, c = cos(y), s = sin(y);
101
+ const world = vec3(n.x.mul(c).add(n.z.mul(s)), n.y, n.z.mul(c).sub(n.x.mul(s)));
102
+ m.normalNode = cameraViewMatrix.mul(vec4(world, 0)).xyz.normalize();
103
+ }
104
+ return m;
105
+ }
106
+
107
+ registerWebGPUPart('impostor', Object.freeze({ bake, cardMaterial }));
@@ -38,8 +38,40 @@ vec3 threedogRim(vec3 normal, vec3 viewDir, vec3 color, float strength, float po
38
38
  Object.assign(THREE.ShaderChunk, { threedog_lighting: LIGHTING_CHUNK }); // the same registry effects.js fills
39
39
 
40
40
  // Functions need getShadow and the light uniforms, which exist only after these includes: they go after shadowmap_pars_fragment
41
+ // With cascades (render/cascades.js, the 'csm' patch: USE_CSM) the sun is N directional lights with one color and direction, one shadow map each: the shadow is
42
+ // the map of the cascade this fragment's depth falls in, picked the way three's CSMShader picks it (linear depth against CSM_cascades; the last one takes the rest).
43
+ // Cascade 0 alone read as "lit" past its far edge, so wrap added sun light inside shadows and shadowTint went missing there.
44
+ // With CSM_FADE (the engine default) CSMShader adds each cascade's light weighted by its margin ratio and fades the last one out; the sun's light is linear
45
+ // in the shadow factor, so the same sum on the factor gives the same result, from the same CSM_cascades values.
41
46
  const SUN = `float threedogSunShadow(){
42
- #if NUM_DIR_LIGHTS > 0 && defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0
47
+ #if NUM_DIR_LIGHTS > 0 && defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0 && defined( USE_CSM ) && defined( CSM_CASCADES )
48
+ float s = 1.0, sh, linearDepth = vViewPosition.z / ( shadowFar - cameraNear );
49
+ #ifdef CSM_FADE
50
+ vec2 cascade; float cascadeCenter, margin, csmx, csmy, ratio; bool lastOne;
51
+ s = 0.0; // each cascade adds its share (CSMShader: reflectedLight = mix( before, before + this cascade's light, ratio ))
52
+ #endif
53
+ #pragma unroll_loop_start
54
+ for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {
55
+ #ifdef CSM_FADE
56
+ cascade = CSM_cascades[ i ]; cascadeCenter = ( cascade.x + cascade.y ) / 2.0;
57
+ margin = 0.25 * pow( linearDepth < cascadeCenter ? cascade.x : cascade.y, 2.0 );
58
+ csmx = cascade.x - margin / 2.0; csmy = cascade.y + margin / 2.0; lastOne = UNROLLED_LOOP_INDEX == CSM_CASCADES - 1;
59
+ if ( linearDepth >= csmx && ( linearDepth < csmy || lastOne ) ) {
60
+ ratio = clamp( min( linearDepth - csmx, csmy - linearDepth ) / margin, 0.0, 1.0 );
61
+ sh = receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLightShadows[ i ].shadowMapSize, directionalLightShadows[ i ].shadowIntensity,
62
+ directionalLightShadows[ i ].shadowBias, directionalLightShadows[ i ].shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;
63
+ sh = mix( 1.0, sh, lastOne && linearDepth > cascadeCenter ? ratio : 1.0 ); // the last cascade fades out to unshadowed
64
+ s += sh * ( !lastOne || linearDepth < cascadeCenter ? ratio : 1.0 ); // neighbours cross over across the margin
65
+ }
66
+ #else
67
+ if ( linearDepth >= CSM_cascades[ i ].x && linearDepth < CSM_cascades[ i ].y ) // past the last far edge three lights unshadowed: s stays 1
68
+ s = receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLightShadows[ i ].shadowMapSize, directionalLightShadows[ i ].shadowIntensity,
69
+ directionalLightShadows[ i ].shadowBias, directionalLightShadows[ i ].shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;
70
+ #endif
71
+ }
72
+ #pragma unroll_loop_end
73
+ return s;
74
+ #elif NUM_DIR_LIGHTS > 0 && defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0
43
75
  return receiveShadow ? getShadow( directionalShadowMap[ 0 ], directionalLightShadows[ 0 ].shadowMapSize, directionalLightShadows[ 0 ].shadowIntensity,
44
76
  directionalLightShadows[ 0 ].shadowBias, directionalLightShadows[ 0 ].shadowRadius, vDirectionalShadowCoord[ 0 ] ) : 1.0;
45
77
  #else