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
@@ -1,15 +1,18 @@
1
1
  # 52 Around the picture: reading it back, the post chain, who writes what
2
2
 
3
- **In this recipe**: Atmosphere · Surfaces · Post effect chain · Who writes it
3
+ > **Covers:** around the picture code: reading it back, the post effect chain, who writes which value.
4
+ > **Use when:** adding a post effect or finding who set a picture value.
5
+ > **Shortest:** `engine.post.add(pass)`.
6
+ > **Sections:** Atmosphere fog, sky · Surfaces ground, plants, cloud · Post effect chain · Who writes it the
4
7
 
5
8
  The picture is plain three.js in a `picture/` folder that reads `engine.uniforms` ([recipe 62](62-picture-code.md)). This page covers what sits around that code: reading the picture back,
6
9
  trying a value out, and the engine pieces it talks to.
7
10
 
8
11
  ```js
9
- engine.describe('picture').picture; // tone, exposure, fog, environment, background, every light, shadows: what three.js holds now
10
- const h = engine.debug.override('me', engine.renderer, 'toneMappingExposure', 3); // try a value on any three.js object; held above your picture/ code
11
- h.remove(); // back to what your code writes (engine.debug.clear('me') takes every override of that owner)
12
- engine.catalog('post'); // a capability's entries and what it holds now; also 'shadows'
12
+ engine.describe('picture').picture; // tone, exposure, fog, environment, background, every light, shadows: what three.js holds now
13
+ const h = engine.debug.override('me', engine.renderer, 'toneMappingExposure', 3); // try a value on any three.js object; held above your picture/ code
14
+ h.remove(); // back to what your code writes (engine.debug.clear('me') takes every override of that owner)
15
+ engine.catalog('post'); // a capability's entries and what it holds now; also 'shadows'
13
16
  ```
14
17
 
15
18
  Which knob changes what on screen, and how to judge it for your picture: [recipe 60](60-judge-the-picture.md). Where picture code sits among the other ways to customize: `../CONVENTIONS.md` "Customization ladder".
@@ -29,18 +32,18 @@ Fog and the placeholder lights: [recipe 34](34-environment-lighting.md). The sky
29
32
  ## Surfaces: ground, plants, cloud shadow, season
30
33
 
31
34
  ```js fragment
32
- engine.terrain.material = myGroundMaterial; // plain three.js on the module; terrain({ colors, shading, detail }) are its start values (recipe 28)
33
- engine.uniforms.uWindFreq.value = 1.5; engine.uniforms.uWindAmp.value = 0.5; // signals: live on every plant, planted ones too
35
+ engine.terrain.material = myGroundMaterial; // plain three.js on the module; terrain({ colors, shading, detail }) are its start values (recipe 28)
36
+ engine.uniforms.uWindFreq.value = 1.5; engine.uniforms.uWindAmp.value = 0.5; // signals: live on every plant, planted ones too
34
37
  engine.vegetation.define('grass', { geometry, wind: { amplitude: 0.05, glsl, tsl } }); // your own sway: threedogWind(...) / tsl: (ctx) => moved position (recipe 36)
35
- engine.vegetation.color({ glsl: 'diffuseColor.rgb *= 0.8;', tsl: c => c.color.mul(0.8) }); // code in the color slot, live on planted species
38
+ engine.vegetation.color({ glsl: 'diffuseColor.rgb *= 0.8;', tsl: c => c.color.mul(0.8) }); // code in the color slot, live on planted species
36
39
  engine.shaderTerms.cloudShadow({ glsl: 'reflectedLight.directDiffuse *= myShade(vThreedogWorld);', tsl: c => ({ directDiffuse: c.directDiffuse.mul(myShadeNode) }) });
37
- engine.shaderTerms.cloudShadow(false); // no engine cloud shadow anywhere: draw your own
38
- engine.shaderTerms.season(kind => ({ glsl: 'diffuseColor.rgb = mix(diffuseColor.rgb, vec3(1.0), uGroundCover.y);', tsl: c => myTint(c, kind) })); // your own season / snow tint
40
+ engine.shaderTerms.cloudShadow(false); // no engine cloud shadow anywhere: draw your own
41
+ engine.shaderTerms.season(kind => ({ glsl: 'diffuseColor.rgb = mix(diffuseColor.rgb, vec3(1.0), uGroundCover.y);', tsl: c => myTint(c, kind) })); // your own season / snow tint
39
42
  ```
40
43
 
41
44
  - Wind is signals: `engine.uniforms.uWind` (weather), `uWindFreq`, `uWindAmp`. A three.js material of yours sways with `applyEffects(mat, { wind: 0.03 })`; your own shader calls `threedogWind(position, origin, amplitude)` (`#include <threedog_wind>`) or `wind(position, origin, amplitude)` (`threedog/tsl`).
42
45
  - The whole plant picture is replaced as a module: `engine.use(myPlants, { replaces: 'vegetation-draw' })`.
43
- - `engine.shaderTerms.cloudShadow(spec)` and `engine.shaderTerms.season(spec)` put your own patch (`{ glsl, tsl, uniforms?, pars?, slot? }`, slot `lighting` / `color` by default) in place of the engine's on every material that carries the term, including ones built before the call; `false` removes the term; the handle's `remove()` gives the engine's back. The signals stay bound: `uWeatherCloud, uCloudShadow*` and `threedogCloudShadow(worldPos)`; `uFoliageTint` / `uGroundTint` / `uFoliageMix` / `uGroundMix`, `uGroundCover` (cover amount alone, x foliage, y ground) and `threedogSeason(color, kind)` (TSL: `season(color, kind)`). `season` also takes `kind => spec` (kind `'foliage'` | `'ground'`). Each renderer draws its own form, and a missing one throws by name.
46
+ - `engine.shaderTerms.cloudShadow(spec)` and `engine.shaderTerms.season(spec)` put your own patch (`{ glsl, tsl, uniforms?, pars?, slot? }`, slot `lighting` / `color` by default) in place of the engine's on every material that carries the term, including ones built earlier; `false` removes the term; the handle's `remove()` gives the engine's back. The signals stay bound: `uWeatherCloud, uCloudShadow*` and `threedogCloudShadow(worldPos)`; `uFoliageTint` / `uGroundTint` / `uFoliageMix` / `uGroundMix`, `uGroundCover` (cover amount alone, x foliage, y ground) and `threedogSeason(color, kind)` (TSL: `season(color, kind)`). `season` also takes `kind => spec` (`'foliage'` | `'ground'`). A missing renderer form throws by name.
44
47
  - Cloud shadow values are signals: `engine.uniforms.uCloudShadow` (darkest, 0 = none), `uCloudShadowScale`, `uCloudShadowSpeed`. The term sits on engine materials and on what you pass to `applyEffects(mat)`; your own shader calls `threedogCloudShadow(worldPos)` (GLSL) or `cloudShadow(positionWorld)` (`threedog/tsl`). The engine adds it to no other material.
45
48
 
46
49
  ## Post effect chain
@@ -50,40 +53,39 @@ in**: game code and the game's `plugins/` folder (a file that exports the Pass o
50
53
  effect has a name, a handle and a row in `describe().slots` and `describe().render.post`. It returns `{ name, enabled, set(params), remove() }`, and
51
54
  `engine.post.get(name)` returns the same handle. A wrong shape throws with nothing added.
52
55
 
53
- `x` is a plain three.js Pass (WebGL), a TSL node function `(input, ctx) => node` (WebGPU), or an effect `{ name, create, node, fuse, slot, order, params, update, needsDepth, needsBuffers, backend, skipOnLowTier, facts }`: both renderers when it gives `create` and `node`, or a `fuse`. `create(ctx) => pass` returns any three.js postprocessing Pass, built the first time the effect is on, and `update?(pass, params)` applies new params (on WebGPU `node`: recipe 56). The optional ones: `needsBuffers` lists extra scene outputs on WebGPU, `backend: 'webgpu'` marks an effect the WebGL2 backend cannot run, `skipOnLowTier` holds it when `engine.tier` is 'low', `facts` adds a line to `describe().render.post`.
56
+ `x` is a plain three.js Pass (WebGL), a TSL node function `(input, ctx) => node` (WebGPU), or an effect `{ name, create, node, fuse, slot, order, params, update, needsDepth, needsBuffers, backend, skipOnLowTier, facts }`: both renderers when it gives `create` and `node`, or a `fuse`. `create(ctx) => pass` returns any three.js postprocessing Pass, built the first time the effect is on, and `update?(pass, params)` applies new params (on WebGPU `node`: recipe 56). Optional: `needsBuffers` (extra scene outputs, WebGPU), `backend: 'webgpu'` (the WebGL2 backend cannot run it), `skipOnLowTier` (held on `engine.tier` 'low'), `facts` (a line in `describe().render.post`).
57
+
58
+ **An extra render inside your own effect** (a mask pass, a depth of selected objects): draw it in `ctx.borrowRenderer(renderer, () => { renderer.setRenderTarget(myTarget); renderer.render(scene, camera); }, { scene, camera })`. The render target, viewport, scissor, clear color, tone mapping and the scene's override material, background and fog come back afterwards, also when the draw throws; targets and materials stay the effect's to dispose. `clean: true` (WebGPU) starts from three's reset state for a quad inside a node frame. Restoring by hand and forgetting one makes the next effect draw into your target.
54
59
 
55
60
  Each runs in a slot, then by `order` (low first): `scene` (replaces the scene render, one at a time, e.g. pixelation) -> `hdr` (linear color: outline, AO, bloom) -> `tone` (replaces the tone-mapping output, one at a time; it must output display color) -> `ldr` (sRGB: LUT, palette, grain, vignette) -> `final` (FXAA / SMAA).
56
61
 
57
- A plain Pass is placed by its kind: one that renders `engine.scene` itself (`RenderPixelatedPass`, `SSAARenderPass`, `TAARenderPass`) goes in `scene` and replaces the engine's scene render (the scene is drawn once; a second one throws), FXAA / SMAA / TAA in `final`, any other in `hdr` after the effects already there (`ldr` when you added it after an OutputPass); a RenderPass of `engine.scene` and an OutputPass are skipped (the engine has them). Without `{ name }` it is listed by class or shader name (`CopyShader#1`); its `remove()` does not dispose it.
62
+ A plain Pass is placed by its kind: one that renders `engine.scene` itself (`RenderPixelatedPass`, `SSAARenderPass`, `TAARenderPass`) goes in `scene` and replaces the engine's scene render (a second one throws), FXAA / SMAA / TAA in `final`, any other in `hdr` after the effects already there (`ldr` when you added it after an OutputPass); a RenderPass of `engine.scene` and an OutputPass are skipped (the engine has them). Without `{ name }` it is listed by class or shader name (`CopyShader#1`); its `remove()` does not dispose it.
58
63
 
59
- To read the chain: `engine.post.object()` and `engine.post.targets()`; both stay the engine's (it rebuilds passes, resizes, disposes), so change the chain through `engine.post`; to take the built chain over, `engine.post.own()` (`own(false)` gives it back). A game that renders the canvas itself (its own composer) takes the frame: the engine stops drawing and warns once `[own-frame]`.
64
+ To read the chain: `engine.post.object()` and `engine.post.targets()`; both stay the engine's (it rebuilds, resizes, disposes), so change the chain through `engine.post`, or take it over with `engine.post.own()` (`own(false)` gives it back). A game that renders the canvas itself (its own composer) takes the frame: the engine stops drawing and warns once `[own-frame]`.
60
65
  ```js fragment
61
- import { bloom, outline, vignette, lut } from '@threedog/post-effects'; // shared effects come from the add-on
66
+ import { bloom, outline, vignette, lut } from '@threedog/post-effects'; // shared effects come from the add-on
62
67
  import { LUTPass } from 'three/addons/postprocessing/LUTPass.js';
63
68
  const line = engine.post.add(outline({ thickness: 1.5 })); engine.post.add(vignette());
64
- line.enabled = false; // pauses it in place; a settings restriction above this still holds it off
65
- engine.post.get('vignette').set({ strength: 0.6 }); // params by name; an unknown name throws
66
- if (engine.tier !== 'low') engine.post.add(bloom()); // the heavy ones are the game's call on weak devices
69
+ line.enabled = false; // pauses it in place; a settings restriction above this still holds it off
70
+ engine.post.get('vignette').set({ strength: 0.6 }); // params by name; an unknown name throws
71
+ if (engine.tier !== 'low') engine.post.add(bloom()); // the heavy ones are the game's call on weak devices
67
72
  engine.post.add({ name: 'myLut', slot: 'ldr', params: { lut: myLut }, create: ({ params }) => new LUTPass({ lut: params.lut }) });
68
73
  // a plugin file brings the same effect with no main.js line: plugins/10-bloom.js
69
74
  export default bloom({ strength: 0.2 });
70
75
  ```
71
- - `bloom({ strength, radius, threshold })`, defaults 0.35, 0.5, 0.85: `strength` is how much glow is added, `radius` how far it spreads (0 to 1), `threshold` the brightness a pixel needs before it
72
- glows at all. It reads linear color before the tone curve, so a surface brighter than 1 glows hard however small it is: if the frame washes out, raise `threshold` or lower that surface's brightness
73
- before lowering `strength`. On the WebGPU route three's own `BloomNode` is also open to you through `engine.post.add({ node })`.
76
+ - `bloom({ strength, radius, threshold })`, defaults 0.35, 0.5, 0.85 (glow added, spread 0 to 1, brightness a pixel needs to glow). It reads linear color before the tone curve, so a
77
+ surface brighter than 1 glows hard however small: if the frame washes out, raise `threshold` or dim that surface before lowering `strength`. On the WebGPU route three's own `BloomNode` is also open to you through `engine.post.add({ node })`.
74
78
  - The engine ships no effects. `@threedog/post-effects` (import only what you use) has `bloom`, `ao`, `outline`, `dof` (all `hdr`; outline and dof read depth) and `lut` (contrast / saturation / warm-cool / optional 3D LUT, or
75
- `paletteLut(colors)` for a fixed palette), `grain`, `vignette`, `chromatic` (`ldr`), each on both routes. `voxelGI`, `temporalAA`, `sunShafts`, `lightVolumes` exist only on WebGPU: `@threedog/post-effects/tsl`. Materials and lighting as TSL: `threedog/tsl`; the three.js layers the engine keeps (`RESERVED_LAYERS`): `threedog/layers`.
79
+ `paletteLut(colors)` for a fixed palette), `grain`, `vignette`, `chromatic` (`ldr`), each on both routes. `voxelGI`, `reflections`, `temporalAA`, `sunShafts`, `lightVolumes`, `autoExposure` exist only on WebGPU: `@threedog/post-effects/tsl`. Materials and lighting as TSL: `threedog/tsl`; the three.js layers the engine keeps (`RESERVED_LAYERS`): `threedog/layers`.
76
80
  An added effect is on (`enabled: false` adds it off, for `handle.enabled = true` later). The heavy ones (`bloom`, `ao`, `dof`, outline `normal`/`both`) are the game's call on weak devices (`threedog shot` renders the desktop tier, `--tier low` checks the low one).
77
81
  - Depth: an effect that reads scene depth (`needsDepth: true`, e.g. `outline`) must run before any pass that swaps buffers (a `ShaderPass`, a
78
- scene-slot pixelation pass, the tone-mapping output). A chain that breaks this throws when the effect is added or enabled, naming both effects;
82
+ scene-slot pixelation pass, the tone-mapping output). The rule is checked over every added effect, on or off (one held by a preset or a low tier included), so an order that would break throws at the `add`, naming both effects, and turning an effect on or off never throws for order;
79
83
  give the depth reader a lower `order`. `dof` keeps the scene depth (`pass.keepsDepth = true`), so `dof` and `outline` can both be on while `dof`
80
84
  has the lower `order` (default: dof 5, outline 10). The other order throws.
81
- - Order of glow and a step-style grade (posterize, palette snap, a few-level LUT). Glow is a smooth falloff; a grade that snaps every pixel to a few levels, run **after** it, cuts that falloff into flat
82
- plateaus, and the middle ones read as a grey stain around a light, not as light. It shows in any style that mixes glow with banded color and gets worse the fewer levels the grade has, and the default
83
- order is the bad one (`bloom` is `hdr`, a grade `ldr`). Ways out, by the picture you want: (1) grade first, glow after: give the grade `slot: 'hdr'` and an `order` lower than bloom's (the halo may then
84
- use colors outside the palette: fine for soft light, wrong for a strict palette); (2) keep the grade last and make the glow stepped on purpose, one or two clean rings; (3) drop the glow and paint the light
85
- (emissive sprites, a lighter ring in the art). Judge it with a `threedog shot` close on one bright light against a dark ground: a gradient (1) or deliberate rings (2) are fine; a grey flat disc is the trap.
86
- This was reasoned on a one-dimensional model of the two orders, not yet checked with the real passes.
85
+ - Glow and a step-style grade (posterize, palette snap, a few-level LUT): a grade run **after** glow cuts its falloff into flat plateaus that read as a grey stain around a light,
86
+ worse the fewer levels, and the default order is that one (`bloom` is `hdr`, a grade `ldr`). Ways out: (1) grade first: the grade gets `slot: 'hdr'` and an `order` below bloom's (the halo may
87
+ leave the palette); (2) keep the grade last and make the glow stepped on purpose; (3) drop the glow and paint the light. Judge on a `threedog shot` close on one bright light against a dark ground:
88
+ a grey flat disc is the trap. (Reasoned on a one-dimensional model, not yet checked with the real passes.)
87
89
  - On / off: `engine.post.get('bloom').enabled = false` for every effect, whoever added it, pauses it where it is (place and params stay); `engine.plugins.off('<file>')` unloads a plugin (the effect leaves the chain; `on` plugs it again; a pack's file: `'<pack>/<file>'`). Either way
88
90
  it comes back in the same place: inside a slot `order` decides, and equal orders keep the order the names were first added in. There is no `createEngine({ post })`. The switch is the shared point `post.<name>.enabled`: `enabled` writes its game layer, a hold of your own goes through `engine.mod('post.bloom.enabled', { owner, set, layer })`, and reading `enabled` gives what runs now.
89
91
  The settings menu shows `bloom` / `ao` toggles only when effects with those names exist; a toggle the player turns off sits on the settings layer of that point, above the game and any hold (`describe().render.post` reads `writer: 'settings'`). MSAA is `engine.post.antialias = on` and works with every effect on.
@@ -101,7 +103,7 @@ export default bloom({ strength: 0.2 });
101
103
  Other GTAOPass settings (`samples`, `thickness`, `output`): `engine.post.object().passes.find(p => p.gtaoMaterial)`.
102
104
 
103
105
  ### dof: blur the background (focus blur, bokeh, miniature, tilt shift, cinematic)
104
- `dof` from `@threedog/post-effects` blurs what is away from the focus distance: `engine.post.add(dof({ focus: 8, range: 3, maxBlur: 5 }))`, then `engine.post.get('dof').set({ focus: distanceToTarget })` each frame for a follow focus. A small `range` and a large `maxBlur` read as a miniature; a long `range` as a soft cinematic backdrop. It is not a shadow setting (`engine.shadows` blur is edge softness).
106
+ `dof` from `@threedog/post-effects` blurs what is away from the focus distance: `engine.post.add(dof({ focus: 8, range: 3, maxBlur: 5 }))`, then `engine.post.get('dof').set({ focus: distanceToTarget })` each frame for a follow focus. A small `range` and a large `maxBlur` read as a miniature; a long `range` as a soft backdrop. Not a shadow setting (`engine.shadows` blur is edge softness).
105
107
 
106
108
  ## Who writes it: the ownership table
107
109
 
@@ -111,8 +113,7 @@ Each of them is registered once (`core/ops/owned.js`), and every one behaves the
111
113
  - **Engine** (default): the engine writes it. Adjust it while the engine keeps driving: the `set` call in the table.
112
114
  - **Taken** (`manual`): `engine.autoView.manual('far' | 'fov' | 'pixelRatio')` stops the engine writing it; the three.js value is yours.
113
115
  `manual(key, false)` (or the handle's `remove()`) gives it back. No module option starts a value taken over.
114
- - **Written directly** without `manual`: the engine notices, **stops writing it and keeps your value**, and warns once with the `manual` call and the
115
- hand-back call. This happens in release builds too (only the warning is dev-only), so a game behaves the same with and without checks.
116
+ - **Written directly** without `manual`: the engine **stops writing it and keeps your value**, in release builds too, and warns once (dev) with the `manual` and hand-back calls.
116
117
  - A `timeline.tween` on an object is a temporary takeover of that object only: no warning, no hand-over (other objects stay checked).
117
118
 
118
119
  `engine.describe().owned` lists every registered value and who writes it now, as `writer` (`engine`, `manual:game`, `three (engine yielded)`).
@@ -124,6 +125,7 @@ Each of them is registered once (`core/ops/owned.js`), and every one behaves the
124
125
  | `background` | sky | sky: a backdrop color or skybox every frame; with the dome the dome hides when you take it | `scene.background = x` (the dome hides); whole sky: `engine.sky.replace(texture \| object3D)` | `engine.sky.backdrop = '#335577'` |
125
126
  | `view.aspect` | view | every resize | `engine.autoView.manual('aspect')` | - |
126
127
  | `sky.sunDir` | view | `sky()` each frame, from the time and `engine.sky.orbit` (the same vector as `uSunDir`) | `engine.autoView.manual('sunDir')` | - |
128
+ | `sky.environment` | sky | the map in the `into` you gave `engine.sky.environment({ into })`, rebuilt after its interval when the sky changed (never without that call) | `scene.environment = x` or `engine.sky.environment().remove()`; `engine.sky.environment({ into })` again gives it back | `engine.sky.environment({ interval })` |
127
129
  | `view.far` | view | terrain view range (`terrain.viewChunks`) | `engine.autoView.manual('far')` | - |
128
130
  | `view.fov` | view | the settings menu fov slider, camera modules (first person / rts fov, fixed shots, back to the install fov on a switch) | `engine.autoView.manual('fov')` | - |
129
131
  | `view.pixelRatio` | view | adaptive resolution, about once a second while slow | `engine.autoView.manual('pixelRatio')` | `engine.setPixelRatio(1.5)` |
@@ -1,5 +1,10 @@
1
1
  # The ground up close: options, crisp color borders, normals, diagnosis
2
2
 
3
+ > **Covers:** the ground up close: approaches, crisp borders, lighting normals, diagnosis.
4
+ > **Use when:** the ground looks wrong at short range.
5
+ > **Shortest:** `terrain({ shading: 'texture' })` is one of the approaches.
6
+ > **Sections:** Approaches pick by the · Crisp borders shading 'texture' · Lighting normals normals and · Symptom, causes, options
7
+
3
8
  Not a standard recipe. Several pictures are right for different games, and none is the default. **Decide from the reference images first**: is the
4
9
  ground flat color shapes, a painted surface, a photographic texture, or a few lit polygons? Then pick a row. If the ground already looks wrong,
5
10
  jump to the symptoms.
@@ -61,7 +66,7 @@ texture mode it is sampled per pixel, so `patches: { size: 20, levels: 4 }` give
61
66
  - `normalFn(i, j, h, cell) => [nx, ny, nz]` replaces the smooth normal at grid point `(i, j)`; `h(i, j)` reads a grid-point height, `cell` is the
62
67
  spacing in meters. Pure like `height` / `groundType`. The engine normalizes the result. Default: central difference of the four neighbors.
63
68
  ```js
64
- terrain({ normalFn: (i, j, h, cell) => [(h(i - 1, j) - h(i + 1, j)) / cell, 4, (h(i, j - 1) - h(i, j + 1)) / cell] }) // gentler lighting on slopes
69
+ terrain({ normalFn: (i, j, h, cell) => [(h(i - 1, j) - h(i + 1, j)) / cell, 4, (h(i, j - 1) - h(i, j + 1)) / cell] }) // gentler lighting on slopes
65
70
  ```
66
71
  `normals` and `normalFn` change light only, never height or collision. `engine.terrain.recolor({ normals: 'flat' })` changes it at run time (rebuilds the chunks).
67
72
 
@@ -1,21 +1,26 @@
1
1
  # Shared values, exclusive slots, time channels and wrapping module methods
2
2
 
3
+ > **Covers:** shared values (`engine.mod`), exclusive slots, time channels, wrapping and replacing modules.
4
+ > **Use when:** several systems change one value, or a module needs replacing.
5
+ > **Shortest:** `engine.mod('move.speed', { owner, mul: 0.5 })`.
6
+ > **Sections:** The rules in full · Picture points follow the · Time channels · Fixed-step order onFixed fn · Wrapping a module method · Replacing a module · Who holds what
7
+
3
8
  A shared value is something several owners change: the game, a module, an effect. Name it, say who you are, say how you change it:
4
9
 
5
10
  ```js
6
- engine.time.channel('enemies'); // a channel of your own exists once you name it (world, player and calendar are built in)
7
- const slow = engine.mod('time.enemies', { owner: 'bullet-time', mul: 0.35, for: 2 }); // bullet time; slow.remove() ends it early
8
- engine.mod('time.world', { owner: 'hitstop', set: 0, layer: 'system', for: 0.06 }); // decide on a higher layer: hides everything below
11
+ engine.time.channel('enemies'); // a channel of your own exists once you name it (world, player and calendar are built in)
12
+ const slow = engine.mod('time.enemies', { owner: 'bullet-time', mul: 0.35, for: 2 }); // bullet time; slow.remove() ends it early
13
+ engine.mod('time.world', { owner: 'hitstop', set: 0, layer: 'system', for: 0.06 }); // decide on a higher layer: hides everything below
9
14
 
10
15
  const storm = () => ({ name: 'storm', type: 'rules', install(e, ctx) {
11
- ctx.mod('time.world', { mul: 0.8, layer: 'effect' }); // inside a module: owned by it, gone when the module goes
16
+ ctx.mod('time.world', { mul: 0.8, layer: 'effect' }); // inside a module: owned by it, gone when the module goes
12
17
  } });
13
18
 
14
- const myBag = () => ({ name: 'myBag', type: 'rules', provides: ['inventory'], install(e) { /* ... */ } }); // only one may hold 'inventory'
15
- engine.use(myBag(), { replaces: 'inventory' }); // swap the engine's part: the old one leaves with all its changes
19
+ const myBag = () => ({ name: 'myBag', type: 'rules', provides: ['inventory'], install(e) { /* ... */ } }); // only one may hold 'inventory'
20
+ engine.use(myBag(), { replaces: 'inventory' }); // swap the engine's part: the old one leaves with all its changes
16
21
  const shop = () => ({ name: 'shop', type: 'rules', requires: ['inventory'] }); // depend on the slot, not on a module name
17
22
 
18
- engine.describe().shared['time.world']; // { value: 0.8, writer: 'default', how: 'default 1 × storm 0.8', also: [{ owner: 'storm', ... }] }
23
+ engine.describe().shared['time.world']; // { value: 0.8, writer: 'default', how: 'default 1 × storm 0.8', also: [{ owner: 'storm', ... }] }
19
24
  ```
20
25
 
21
26
  What to remember:
@@ -23,7 +28,7 @@ What to remember:
23
28
  it. You never pick a layer by hand unless you want to: game code and game modules write `'game'` (the default); effects pass `layer: 'effect'`.
24
29
  - **`mul` / `add` to cooperate, `set` to decide.** Any number of owners can multiply and add. Two owners `set` the same value on the same layer is
25
30
  an error (in development and release alike) that names both lines and gives three copyable fixes; copy one. The earlier value stays.
26
- - **`replaces` to swap an engine part** that `provides` a slot; a second provider without it is the error `shared-taken`. What the old part issued goes with it: read `engine.<slot>` where you use it, and keep the issuer beside any handle so you can compare (`if (from !== engine.rigid) { from = engine.rigid; crate = from.addBox(mesh); }`). Version numbers count per module, so they cannot tell two modules apart. The engine's own props, NPCs, pickups, cars and movers do this; a rider leaves a rigid car when rigid goes. `world` is the exception: it owns every record, so install your world before the modules that need it. Once they are installed, or after `start()`, `replaces: 'world'` and `unuse('world')` are refused (`module-replaces`, `module-unuse`) and nothing changes. A factory that gives two modules goes in whole: `engine.use(terrain(o), { replaces: 'terrain' })` swaps its drawing part too. A module of your own wraps `world.present`, `world.simulate`, `rays.addProvider`, `input.touchButton` and `assets.onSwap` in `ctx.track(...)`, so they leave with it.
31
+ - **`replaces` to swap an engine part** that `provides` a slot; a second provider without it is the error `shared-taken`. What the old part issued goes with it: read `engine.<slot>` where you use it, and keep the issuer beside any handle so you can compare (`if (from !== engine.rigid) { from = engine.rigid; crate = from.addBox(mesh); }`). Version numbers count per module, so they cannot tell two modules apart. The engine's own props, NPCs, pickups, cars and movers do this; a rider leaves a rigid car when rigid goes. `world` is the exception: it owns every record, so install your world before the modules that need it; once they are installed, or after `start()`, `replaces: 'world'` and `unuse('world')` are refused (`module-replaces`, `module-unuse`). A factory that gives two modules goes in whole: `engine.use(terrain(o), { replaces: 'terrain' })` swaps its drawing part too. A module of your own wraps `world.present`, `world.simulate`, `rays.addProvider`, `input.touchButton` and `assets.onSwap` in `ctx.track(...)`, so they leave with it.
27
32
  - Every handle ends with `h.remove()` (`engine.mod`, `ctx.mod`, `input.gate`, `wrap`, `freeze`, `takeCamera`); it drops only your own entry.
28
33
 
29
34
  Only things several parties commonly write are shared values: time speeds and the calendar rate, pause / freeze / camera holders, move stats,
@@ -31,10 +36,10 @@ input gates; shadow on / quality and post parameters are on them too. Your own o
31
36
  materials and textures are plain three.js: never registered, never a conflict. Which tool to reach for: `../CONVENTIONS.md` "Customization ladder".
32
37
 
33
38
  ```js
34
- engine.mod('time.player', { owner: 'haste', mul: 1.2, for: 5 }); // haste on the player
35
- const menu = engine.freeze('pause-menu'); /* ... */ menu.remove(); // pause menu: the picture, UI and ambient uTime (wind, water, clouds) keep running; { ambient: true } stops those too
36
- engine.input.gate('jump', { owner: 'stun', for: 1.5 }); // no jumping while stunned
37
- engine.wrap(engine.inventory, 'add', (next, id, n = 1, o) => // a weight rule on top of the engine's inventory
39
+ engine.mod('time.player', { owner: 'haste', mul: 1.2, for: 5 }); // haste on the player
40
+ const menu = engine.freeze('pause-menu'); /* ... */ menu.remove(); // pause menu: the picture, UI and ambient uTime (wind, water, clouds) keep running; { still: true } stops those too
41
+ engine.input.gate('jump', { owner: 'stun', for: 1.5 }); // no jumping while stunned
42
+ engine.wrap(engine.inventory, 'add', (next, id, n = 1, o) => // a weight rule on top of the engine's inventory
38
43
  carried() + weightOf(id) * n > 30 ? { ok: false, code: 'tooHeavy' } : next(id, n, o), { owner: 'weight' });
39
44
  ```
40
45
 
@@ -62,15 +67,18 @@ engine.wrap(engine.inventory, 'add', (next, id, n = 1, o) =>
62
67
  - Base values are yours: `player.speed = 6` is always fine; modifiers go through `engine.mod('move.speed', { owner, id: 'player', mul })`.
63
68
  - Your own point: `engine.stacks.define('damageTaken', { per: true, min: 0 })`, then `engine.stacks.get('damageTaken').value(enemyId)`;
64
69
  `kind: 'value'` holds a color, a string or a flag (set only), `kind: 'one'` is an exclusive slot (what `provides` makes).
70
+ - "What is being changed right now": `engine.describeText()` has one line `Values being changed now: move.speed[player] 6 → 4.2 (default 6 × haste 1.4 × mud 0.5), …`,
71
+ read from `engine.stacks.changed()` (the dev panel shows the same list): the points off their base or capped by a setting, furthest first, at most five.
72
+ `engine.stacks.define(name, { important: true })` keeps a point on that line even at its base and before the cap, for the few values a reader must always see.
65
73
  - Saved: `engine` to `effect` entries. Not saved: `settings` (the settings module re-applies the player's choices), `system`, `debug`.
66
74
 
67
75
  ## Picture points follow the same rule
68
76
  `shadows.enabled`, `post.<name>.enabled`, `sky.tint`, `sky.flash` and `ground.cover` are shared points like the rest.
69
77
  `sky.tint`, `ground.cover` (blend by amount) and `sky.flash` (adds) are written with `engine.mod`.
70
78
  ```js
71
- const hold = engine.mod('shadows.enabled', { owner: 'cutscene', layer: 'system', set: false }); // decides over the game
72
- engine.describe().shared['shadows.enabled']; // who decided and who is hidden
73
- hold.remove(); // the handle ends yours
79
+ const hold = engine.mod('shadows.enabled', { owner: 'cutscene', layer: 'system', set: false }); // decides over the game
80
+ engine.describe().shared['shadows.enabled']; // who decided and who is hidden
81
+ hold.remove(); // the handle ends yours
74
82
  ```
75
83
  - The exact number whatever else is stacked: set on `{ layer: 'system' }` (the player's settings can still lower it), or write the three.js value.
76
84
  - The settings menu only restricts (`shadows` off is `shadows.enabled` set false on the settings layer), so neither a game's nor a cutscene's `enabled: true`
@@ -81,7 +89,7 @@ hold.remove();
81
89
 
82
90
  - `engine.onFixed(dt => moveEnemies(dt), { channel: 'enemies' })`: dt is that channel's scaled dt. Without `channel` dt is real (1/60): cooldowns
83
91
  and UI timers are not slowed by bullet time by accident.
84
- - `engine.characters.createPlayer` drives the player on channel `'player'`; `new Character(engine, { channel })` picks one for other characters.
92
+ - `engine.characters.addPlayer` drives the player on channel `'player'`; `new Character(engine, { channel })` picks one for other characters.
85
93
  - `engine.world.simulate('slime', { near, far, channel: 'enemies' })`: near and far dt follow the channel too (NPCs: their own channel).
86
94
  - `engine.clock.rate` is the calendar speed (fast-forward a day), separate from the channels.
87
95
  - One time source: `engine.time.tick` is the only counter; `engine.time.now('real' | 'ambient' | 'calendar' | channel)` are read-only views of it
@@ -107,13 +115,13 @@ checks that need this step's player position). The order never depends on which
107
115
 
108
116
  Two modules that each want to be "the" one (a sky, a tone-mapping stage, an inventory) declare an exclusive slot: `provides: ['inventory']`.
109
117
  Other modules `requires: ['inventory']` and work with whichever holds it. `engine.use(myInventory(), { replaces: 'inventory' })` unloads the
110
- holder (its tracked handles, its `ctx.mod` entries, its `dispose`) before the new install, and puts it back if that fails, with its save data and content sections. Either way the holder is a fresh install, so `module:restored` fires with the fresh modules once their `init` is done: content sections load again, as a `content.load` on a running game would (a newcomer with its own format may refuse a pack written for the old holder: that part stays out, with a warning naming the pack), and what game code defined on the old holder by hand it defines again on that event. Level walls and solid props need no event: they go into whichever `collision` or `collider3d` is installed, also one that came late or came back.
118
+ holder (its tracked handles, its `ctx.mod` entries, its `dispose`) before the new install, and puts it back if that fails, with its save data and content sections. Either way the holder is a fresh install, so `module:restored` fires with the fresh modules once their `init` is done: content sections load again, as a `content.load` on a running game would (a newcomer with its own format may refuse a pack written for the old holder: that part stays out, with a warning naming the pack); game code redefines on that event what it defined by hand on the old holder. Level walls and solid props need no event: they go into whichever `collision` or `collider3d` is installed, also one that came late or came back.
111
119
 
112
120
  Most replaceable modules have a contract (`modules/gameplay/*.contract.js`, `modules/*/contract.js`; object contract `modules/characters/vehicle.contract.js`; the rest and what cannot be replaced: CONVENTIONS.md "What can be replaced"): the api, fields, ops, events
113
- and save keys other code relies on, and nothing more (the engine's callers use only that surface). `runContract(contract, () => myInventory(), { check })`
121
+ and save keys other code relies on, and nothing more (the engine's callers use only that surface). `await runContract(contract, () => myInventory(), { check })`
114
122
  from `@threedog/tools/contract` checks a replacement (in a game installed from npm too); `tests/contract/` in the engine's repository (not shipped) holds small
115
123
  whole replacements such as `fakeInventory.js`.
116
- A camera module's `prepare` hook: `runContract(contract, () => myCamera(), { check, prepare: e => { e.camera = ... } })` adds what it needs to the
124
+ A camera module's `prepare` hook: `await runContract(contract, () => myCamera(), { check, prepare: e => { e.camera = ... } })` adds what it needs to the
117
125
  small engine. A vehicle is checked as an object: `runContract(vehicleContract, () => myBoat, { check })`.
118
126
 
119
127
  ## Who holds what
@@ -1,40 +1,39 @@
1
1
  # WebGPU and your own TSL materials
2
2
 
3
- **In this recipe**: WebGPU or WebGL · Turning it on, fallbacks · A minimal TSL material · The engine's values as nodes · The engine's shader
4
- functions · Patches with a `tsl` field (lighting hooks) · Sky and fog hooks · Post effects as nodes · A consistent style · Mistakes, each with the fix · Drawn wrong without a thrown error · GLSL to TSL
3
+ > **Covers:** the WebGPU route: TSL materials, engine values as nodes, patches with `tsl`.
4
+ > **Use when:** a new game (WebGPU is the default) needs its own shaders.
5
+ > **Shortest:** `createEngine({ renderer: 'webgpu' })`.
6
+ > **Sections:** WebGPU or WebGL · Turning it on · A minimal TSL material · The engine's values as · The engine's shader functions · Patches with a tsl · Half-transparent surfaces and fog · Sky and fog hooks · Post effects as nodes · Textures from nodes bake · A consistent style · Dropping a mesh whose · Mistakes, each with the · Drawn wrong without a · GLSL to TSL
5
7
 
6
8
  On the WebGPU route a game draws with three.js node materials (`MeshStandardNodeMaterial` ...) and writes shaders in TSL, three's shading
7
- language in JavaScript. Learn TSL from three itself: the [TSL guide](https://github.com/mrdoob/three.js/wiki/Three.js-Shading-Language) and
8
- the [WebGPU examples](https://threejs.org/examples/?q=webgpu) are written for exactly this renderer. The engine adds nothing you must use:
9
- its wind, cloud shadows, season tint and the rest are ordinary TSL functions in `threedog/tsl`, called where you want them. A whole small
10
- scene written this way: `threedog examples pull webgpu-tsl`.
9
+ language in JavaScript. Learn TSL from three: the [TSL guide](https://github.com/mrdoob/three.js/wiki/Three.js-Shading-Language) and
10
+ the [WebGPU examples](https://threejs.org/examples/?q=webgpu). The engine's wind, cloud shadows, season tint and the rest are ordinary TSL
11
+ functions in `threedog/tsl`, used where you want them. A whole small scene: `threedog examples pull webgpu-tsl`.
11
12
 
12
13
  Rules (correctness, not taste): `import 'threedog/tsl'` comes first in `main.js`; GLSL does not run here (`ShaderMaterial`, `RawShaderMaterial`,
13
14
  `onBeforeCompile`, three.js `Pass` objects, GLSL-only patches and hooks), and each one fails by name instead of drawing nothing.
14
15
 
15
16
  ## WebGPU or WebGL
16
- `threedog new-game` and `threedog init` start a game on WebGPU with TSL (`main.js` imports `threedog/tsl` first and calls `createEngine({ renderer: 'webgpu' })`). `--webgl` starts it on GLSL instead. `createEngine` called without `renderer` still builds a WebGL renderer. When the browser has no WebGPU the game keeps running on three's WebGL2 backend, and `engine.describe().renderer` says why. How to decide:
17
- - WebGPU + TSL (the default for a new game): the picture is built from TSL, you write shaders in JavaScript and compose them as functions, or start from a three.js WebGPU example, and effects that exist only as node materials are open to you.
18
- - `--webgl` + GLSL: the game already has GLSL (ShaderMaterials, `onBeforeCompile`, a three.js `Pass`), or must run best on modest hardware where plain WebGL draws a frame fastest, or start-up time matters more than the shading style. Recipe 43 is the GLSL route for the same tasks.
19
- - Check on the hardware you care about: `threedog inspect perf` on both routes, same scene. On an integrated GPU expect WebGPU to take longer per frame than plain WebGL, the WebGL2 backend longer still, and the first WebGPU frame to come later (shader compilation).
17
+ `threedog new-game` and `threedog init` start a game on WebGPU with TSL (`main.js` imports `threedog/tsl` first and calls `createEngine({ renderer: 'webgpu' })`). `--webgl` starts it on GLSL. `createEngine` without `renderer` builds a WebGL renderer. Without browser WebGPU the game runs on three's WebGL2 backend (`engine.describe().renderer` says why). How to decide:
18
+ - WebGPU + TSL (the default): shaders are JavaScript functions you compose, three's WebGPU examples apply, and node-only effects are open to you.
19
+ - `--webgl` + GLSL (recipe 43): the game already has GLSL (ShaderMaterials, `onBeforeCompile`, a three.js `Pass`), must run best on modest hardware, or start-up time matters more.
20
+ - Measure on the hardware you care about (`threedog inspect perf`, both routes, same scene): on an integrated GPU expect WebGPU slower per frame than plain WebGL, the WebGL2 backend slower still, and a later first frame (shader compilation).
20
21
 
21
22
  ## Turning it on
22
23
  ```js
23
- import 'threedog/tsl'; // first line: brings three/webgpu and the node versions of the engine's sky, post chain and patches
24
+ import 'threedog/tsl'; // first line: brings three/webgpu and the node versions of the engine's sky, post chain and patches
24
25
  import { createEngine } from 'threedog';
25
26
 
26
27
  const engine = createEngine({ canvas: document.getElementById('view'), renderer: 'webgpu' });
27
- await engine.start(); // start() initializes the renderer, so createEngine stays synchronous
28
- console.log(engine.describe().renderer); // { requested: 'webgpu', backend: 'webgpu' | 'webgl2' | 'webgl', reason }
28
+ await engine.start(); // start() initializes the renderer, so createEngine stays synchronous
29
+ console.log(engine.describe().renderer); // { requested: 'webgpu', backend: 'webgpu' | 'webgl2' | 'webgl', reason }
29
30
  ```
30
31
  Your own `new WebGPURenderer(...)` as `renderer` goes the same way (the engine configures only a renderer it built, recipe 50). When the
31
32
  browser gives no WebGPU, `fallback` decides, and the console says once which one happened (`[threedog] WebGPU unavailable (...)`):
32
33
  - `'webgl2'` (default): the same WebGPURenderer on its WebGL2 backend. Your TSL keeps working; frames are slower than plain WebGL.
33
34
  - `'webgl'`: a `WebGLRenderer` instead. Faster, but node materials cannot draw there (`start()` fails when the scene has one). The engine's
34
- own materials (terrain, vegetation, water) are plain three.js materials with both a GLSL and a tsl form of each patch, so they
35
- draw on either renderer with the same picture. What engine modules built before `start()` is rebuilt for WebGLRenderer there: the post chain,
36
- the sky dome (with the `engine.sky.clouds` / `layer` hooks set so far), fog, cascaded shadows, particles, rain and snow. Your own objects are not:
37
- build node materials after `start()` when `engine.describe().renderer.backend !== 'webgl'`.
35
+ own materials and what its modules built before `start()` (post chain, sky dome with its hooks, fog, cascaded shadows, particles, rain, snow) draw the same
36
+ picture there. Your own objects do not switch: build node materials after `start()` when `engine.describe().renderer.backend !== 'webgl'`.
38
37
  - `'error'`: `start()` rejects; the game shows its own message.
39
38
 
40
39
  ## A minimal TSL material
@@ -44,7 +43,7 @@ import { MeshStandardNodeMaterial } from 'three/webgpu';
44
43
  import { color, positionWorld, sin } from 'three/tsl';
45
44
 
46
45
  const mat = new MeshStandardNodeMaterial({ roughness: 0.5 });
47
- mat.colorNode = color(0x4080ff).mul(sin(positionWorld.y.mul(4)).mul(0.25).add(0.75)); // bands by world height
46
+ mat.colorNode = color(0x4080ff).mul(sin(positionWorld.y.mul(4)).mul(0.25).add(0.75)); // bands by world height
48
47
  engine.add(new THREE.Mesh(new THREE.TorusKnotGeometry(0.6, 0.2, 128, 16), mat));
49
48
  ```
50
49
  A node material is lit, shadowed and fogged by three like its plain twin; you replace only the inputs you set (`colorNode`, `positionNode`,
@@ -55,7 +54,7 @@ Node names come from `three/tsl` (`Object.keys(await import('three/tsl'))` lists
55
54
  ## The engine's values as nodes: `uniforms(engine)`
56
55
  `uniforms(engine)` returns `engine.uniforms` as TSL nodes with the same names: `uTime`, `uWind`, `uWeatherCloud`, `uSunDir`, `uSunColor`, `uDaylight`
57
56
  (0 at night, 1 at noon), `uTimeOfDay`, `uFoliageTint`, `uGroundTint` ... (the list: `uniforms` in [the engine API](../api/engine.md)). The node reads the
58
- engine's value each render, so weather, the calendar and the sky move your material with no per-frame code.
57
+ engine's value each render: no per-frame code.
59
58
  ```js
60
59
  import * as THREE from 'three';
61
60
  import { MeshStandardNodeMaterial } from 'three/webgpu';
@@ -63,10 +62,10 @@ import { color, float, sin, smoothstep, uniform } from 'three/tsl';
63
62
  import { uniforms } from 'threedog/tsl';
64
63
 
65
64
  const u = uniforms(engine);
66
- const glow = uniform(3); // a value of your own: change glow.value from game code (an op, a quest step)
65
+ const glow = uniform(3); // a value of your own: change glow.value from game code (an op, a quest step)
67
66
  const lantern = new MeshStandardNodeMaterial({ color: 0x3a2a18 });
68
67
  const night = smoothstep(0.3, 0.9, float(1).sub(u.uDaylight));
69
- lantern.emissiveNode = color(0xffa040).mul(night.mul(glow)).mul(sin(u.uTime.mul(7)).mul(0.08).add(0.92)); // lights up at dusk, flickers
68
+ lantern.emissiveNode = color(0xffa040).mul(night.mul(glow)).mul(sin(u.uTime.mul(7)).mul(0.08).add(0.92)); // lights up at dusk, flickers
70
69
  engine.add(new THREE.Mesh(new THREE.OctahedronGeometry(0.3), lantern));
71
70
  ```
72
71
 
@@ -95,13 +94,15 @@ import { wind, objectOrigin, cloudShadow, season } from 'threedog/tsl';
95
94
 
96
95
  const flag = new MeshLambertNodeMaterial({ side: THREE.DoubleSide });
97
96
  flag.colorNode = season(mix(color(0x803020), color(0xd06040), uv().x), 0).mul(cloudShadow(positionWorld));
98
- flag.positionNode = positionLocal.add(wind(positionGeometry, objectOrigin(), float(0.4))); // its shadow sways too
97
+ flag.positionNode = positionLocal.add(wind(positionGeometry, objectOrigin(), float(0.4))); // its shadow sways too
99
98
  const mesh = new THREE.Mesh(new THREE.PlaneGeometry(1.2, 0.8, 12, 8).translate(0.6, 2.2, 0), flag);
100
99
  mesh.castShadow = true;
101
100
  engine.add(mesh);
102
101
  ```
103
- three's shadow pass draws with the material's `positionNode`, so whatever moves vertices there moves their shadow: no depth material to keep
104
- in step. With an `InstancedMesh` whose instances are rotated or scaled, the offset must turn with each instance; the patch form below does that.
102
+ three's shadow pass draws with the material's `positionNode`, so the shadow moves too. On an `InstancedMesh` with rotated or scaled instances the offset must turn with each (`instanceOffset`, or the patch form below).
103
+
104
+ A program takes 16 vertex inputs on most devices; past that the build stops with a `[vertex-inputs]` error that counts what stacked up and how to
105
+ fit. `objectOrigin()` costs 1 per program, `instanceOffset()` 3 more.
105
106
 
106
107
  ## Patches with a `tsl` field (optional convenience)
107
108
  `applyEffects(mat, { wind, season, clouds, patches })` (recipe 43) works on node materials: the engine's own patches carry a TSL version, and a
@@ -135,14 +136,14 @@ import { applyEffects } from 'threedog';
135
136
  const coolShade = { name: 'coolShade', slot: 'lighting', tsl: {
136
137
  start: c => { c.state.lit = c.tsl.float(1).toVar('coolShadeLit'); },
137
138
  direct: (light, c) => { if (light.directional && light.shadow) c.state.lit.assign(light.shadow); },
138
- after: c => ({ indirectDiffuse: c.indirectDiffuse.mul(c.tsl.mix(c.tsl.vec3(0.8, 0.9, 1.25), c.tsl.vec3(1), c.state.lit)) }), // bluer fill in shadow
139
+ after: c => ({ indirectDiffuse: c.indirectDiffuse.mul(c.tsl.mix(c.tsl.vec3(0.8, 0.9, 1.25), c.tsl.vec3(1), c.state.lit)) }), // bluer fill in shadow
139
140
  } };
140
141
  const rock = applyEffects(new MeshStandardNodeMaterial({ color: 0x9a9080 }), { patches: [coolShade] });
141
142
  engine.add(new THREE.Mesh(new THREE.DodecahedronGeometry(1), rock));
142
143
  ```
143
144
 
144
- ## Half-transparent surfaces and fog differ from plain WebGL
145
- WebGL straight to the canvas tone-maps and encodes each material first, then applies fog and blends in display values. WebGPU, and WebGL with any `engine.post` effect on, fog and blend in linear and tone-map once. Those two match pixel for pixel, opaque unfogged surfaces match on all three, and half-transparent or fogged ones shift on the straight WebGL path, more in dim scenes. So on WebGL turning the first post effect on can move those surfaces a little. This is how three.js's renderers work, not a fault to fix in your scene.
145
+ ## Half-transparent surfaces differ from plain WebGL, fog does not
146
+ Fog is mixed in linear space before tone mapping on every path (WebGPU, WebGL with an effect on, and WebGL straight to the canvas, where the engine's `fog-linear` patch moves three's fog mix before the tone curve), so fog does not change colour when the first post effect turns on. Half-transparent and additive surfaces still differ: WebGL straight to the canvas blends them in display values after tone mapping; WebGPU, and WebGL with any `engine.post` effect on, blend in linear and tone-map once. They shift a little on the straight WebGL path (more in dim scenes), and the first post effect can move them there. This is three.js's own model, not a fault in your scene.
146
147
 
147
148
  ## Sky and fog hooks
148
149
  The engine's sky dome has a node version; nothing changes in how you set it (recipe 08). The GLSL hooks (`engine.sky.clouds`, `engine.sky.layer`
@@ -159,14 +160,45 @@ not rebuild), `ctx.tsl` is three/tsl, `ctx.scenePass` the scene pass (depth: `ct
159
160
  ```js
160
161
  engine.post.add({ name: 'warmGrade', slot: 'ldr', params: { amount: 0.3 },
161
162
  node: (input, { tsl, p }) => tsl.vec4(tsl.mix(input.rgb, input.rgb.mul(tsl.vec3(1.05, 0.95, 0.8)), p.amount), input.a) });
162
- engine.post.get('warmGrade').set({ amount: 0.5 }); // a uniform write, no rebuild
163
+ engine.post.get('warmGrade').set({ amount: 0.5 }); // a uniform write, no rebuild
163
164
  ```
164
165
  `ldr` runs after tone mapping (display colors 0-1); something that should glow or bleed belongs in `hdr`. An effect with only `create`
165
166
  (a three.js `Pass`) stops with its name.
166
167
 
168
+ ## Textures from nodes: bake with `rtt`, tile without seams
169
+ `rtt` with `autoUpdate: false` draws a node into a texture once, so a costly pattern is not computed per pixel per frame. Seamless: blend four copies
170
+ shifted by one period, weighted by the position in the tile (a little softer mid-tile). Textures from different sources read as one style only once
171
+ brought to one way of drawing (recipe 05 §2d).
172
+ ```js
173
+ import * as THREE from 'three';
174
+ import { MeshStandardNodeMaterial } from 'three/webgpu';
175
+ import { rtt, uv, vec2, vec3, mix, color, mx_fractal_noise_float } from 'three/tsl';
176
+
177
+ const noise = p => mx_fractal_noise_float(vec3(p, 0)).mul(0.5).add(0.5);
178
+ const seamless = (st, period) => { // st: uv over one tile, period: noise cells per tile
179
+ const p = st.mul(period), top = mix(noise(p), noise(p.sub(vec2(period, 0))), st.x);
180
+ return mix(top, mix(noise(p.sub(vec2(0, period))), noise(p.sub(vec2(period, period))), st.x), st.y);
181
+ };
182
+ const baked = rtt(seamless(uv(), 4), 512, 512, { type: THREE.UnsignedByteType, autoUpdate: false });
183
+ baked.value.wrapS = baked.value.wrapT = THREE.RepeatWrapping;
184
+ baked.uvNode = uv().mul(6); // 6 x 6 tiles; set on the node itself (a .sample() copy leaves the bake out of the frame)
185
+ const mat = new MeshStandardNodeMaterial();
186
+ mat.colorNode = mix(color(0x6b5640), color(0xa89070), baked.r);
187
+ engine.add(new THREE.Mesh(new THREE.PlaneGeometry(4, 4), mat));
188
+ ```
189
+ Save it (dev, after a frame drew it; WebGPU renderer; width a multiple of 64; values are linear, right for masks and heights). No UVs to
190
+ follow (rocks, cliffs): project from three sides. Check either alone: `threedog gallery --shots --material <name> --mode albedo` (recipe 05).
191
+ ```js fragment
192
+ import { triplanarTexture, texture, float } from 'three/tsl';
193
+ const r = /** @type {any} */ (engine.renderer), px = await r.readRenderTargetPixelsAsync(baked.renderTarget, 0, 0, 512, 512);
194
+ const c = Object.assign(document.createElement('canvas'), { width: 512, height: 512 });
195
+ c.getContext('2d').putImageData(new ImageData(new Uint8ClampedArray(px.buffer), 512, 512), 0, 0);
196
+ c.toBlob(b => Object.assign(document.createElement('a'), { href: URL.createObjectURL(b), download: 'mask.png' }).click());
197
+ rock.colorNode = triplanarTexture(texture(rockMap), null, null, float(0.5)); // rockMap: RepeatWrapping
198
+ ```
199
+
167
200
  ## A consistent style
168
- A style reads as one when every surface answers the same few questions the same way. Decide these once, in one place of `picture/`, and let materials share the answers; a
169
- look built material by material drifts. Working example: `examples/techniques/three-looks/` (page `/technique-looks.html`), the same models three ways.
201
+ A style reads as one when every surface answers the same few questions the same way: decide them once in `picture/` and let materials share the answers. Working example: `examples/techniques/three-looks/` (page `/technique-looks.html`), the same models three ways.
170
202
 
171
203
  | Question | Where it lives | With |
172
204
  |---|---|---|
@@ -181,12 +213,12 @@ look built material by material drifts. Working example: `examples/techniques/th
181
213
  import { MeshToonNodeMaterial } from 'three/webgpu';
182
214
  import { rampTexture } from 'threedog';
183
215
  import { celLighting } from 'threedog/tsl';
184
- const ramp = rampTexture([0x7a84c8, 0xd0d4f0, 0xffffff]); // example colors: the light in each band, dark to light, from the game's palette; one ramp for the whole game
216
+ const ramp = rampTexture([0x7a84c8, 0xd0d4f0, 0xffffff]); // example colors: the light in each band, dark to light, from the game's palette; one ramp for the whole game
185
217
  const mat = new MeshToonNodeMaterial({ color: 0xe08050, gradientMap: ramp });
186
- mat.setupLightingModel = celLighting; // colored bands; a cast shadow reads the dark end of the ramp, so it is the same flat color as the side turned away
218
+ mat.setupLightingModel = celLighting; // colored bands; a cast shadow reads the dark end of the ramp, so it is the same flat color as the side turned away
187
219
  ```
188
- three's toon alone is enough for gray bands: it reads only the red channel of `gradientMap`, and a cast shadow drops to the ambient light. Choose it when that is the picture you
189
- want; `celLighting` when shade has a color or cast shadows belong to the bands. The ramp's width sets where bands fall, the left half being the side turned away.
220
+ three's toon alone gives gray bands (it reads only the red channel of `gradientMap`, and a cast shadow drops to the ambient light); `celLighting` when shade has a color or
221
+ cast shadows belong to the bands. The ramp's width sets where bands fall, the left half being the side turned away.
190
222
 
191
223
  **Same tools, different pictures**: a paper cut-out is two bands and no line; ink wash is a gray palette through `paletteLut` with soft fog; a neon night is a dark ramp with `bloom` and
192
224
  emissive lines; a storybook is soft ramp edges (`rampTexture(ramp, soften)`) with a warm grade; a retro handheld is a four-color `paletteLut` with `posterize` before it.
@@ -196,12 +228,11 @@ emissive lines; a storybook is soft ramp edges (`rampTexture(ramp, soften)`) wit
196
228
  - Cover the object you just changed. If the rest of the frame tells you the same story about light, the style is holding; if one material looks lit by another sun, its answers differ.
197
229
  - Is every shade in the frame leaning the same way? A cast shadow and a turned-away side that disagree read as two renderers.
198
230
  - A flat look with soft or stair-stepped shadow edges: the shadow map is showing. Raise its resolution for the area in view, or soften the ramp a little.
199
- - Count what the picture really holds, not what you meant: most common colors, saturation, light-dark spread (`window.techTest.measure` in the example is one way). A palette look with
200
- many stray colors has something running after the `lut`; grain and vignette belong before it there.
201
- - Put an effect in the stage that matches what it reads. A grade written for finished colors looks wrong before the tone curve, and a glow after it stops glowing.
231
+ - Count what the picture really holds (common colors, saturation, light-dark spread): a palette look with many stray colors has something running after the `lut`.
232
+ - Put an effect in the stage that matches what it reads: a grade for finished colors goes after the tone curve, a glow before it.
202
233
 
203
234
  ## Dropping a mesh whose material lives on
204
- A game has nothing to do here. WebGPURenderer keeps a record of every mesh it drew, and neither `scene.remove` nor `geometry.dispose()` frees it while the material stays in use. So every few seconds the engine looks for meshes that have left every Scene and frees theirs, after 4 to 8 seconds out. Adding such a mesh back is fine: its record is rebuilt.
235
+ Nothing to do: WebGPURenderer keeps a record of every mesh it drew while the material stays in use, so the engine frees the records of meshes 4 to 8 seconds out of every Scene (`webgpu-record-sweep` in `THREE.md`). Adding one back rebuilds it.
205
236
 
206
237
  Two things stay yours:
207
238
  - Call `geometry.dispose()` (or use `engine.remove`) when a mesh is gone for good. Only you know it will not come back. A steady climb of unused geometries warns in dev, with the code `geometry-undisposed`.
@@ -272,19 +303,19 @@ import { RenderTarget } from 'three/webgpu';
272
303
  // wrong: your own requestAnimationFrame loop calling engine.renderer.render(...); the engine runs the only loop and its post chain
273
304
  const minimap = new RenderTarget(256, 256), top = new THREE.OrthographicCamera(-20, 20, 20, -20, 0.1, 100);
274
305
  top.position.set(0, 50, 0); top.lookAt(0, 0, 0);
275
- engine.onFrame(() => engine.renderOnce(minimap, top)); // one extra picture per frame; a fresh node frame each call
306
+ engine.onFrame(() => engine.renderOnce(minimap, top)); // one extra picture per frame; a fresh node frame each call
307
+ // with a camera the target is linear and not tone mapped (renderOnce(minimap) with no camera would be display pixels): use minimap.texture on a material or a TSL node, which encodes it; a readback is dark
276
308
  ```
277
309
  ```js
278
310
  import { RenderPipeline } from 'three/webgpu';
279
311
 
280
312
  // wrong: new PostProcessing(renderer) from older three examples (three 0.187 names it RenderPipeline), and a second pipeline beside the engine's
281
- console.log(engine.post.object()?.pipeline instanceof RenderPipeline); // the engine's own, once its chain is built; add effects with engine.post.add
313
+ console.log(engine.post.object()?.pipeline instanceof RenderPipeline); // the engine's own, once its chain is built; add effects with engine.post.add
282
314
  ```
283
315
  Also: three's `uniform` takes a value, not a `{ value }` object, so passing it `engine.uniforms.uWind` throws; use `uniforms(engine).uWind`.
284
316
  A type mismatch never errors: look at the result (`engine.debug.view('lighting')`, `threedog shot`).
285
- Many materials, many programs: WebGPURenderer builds one program per distinct set of patch uniform objects. Materials given the same
286
- `detail` / `lighting` options through `applyEffects` share theirs, so a hundred stones build one; a patch you write once and pass
287
- to every material shares too, a fresh patch object per material builds one program each.
317
+ WebGPURenderer builds one program per distinct set of patch uniform objects: the same `applyEffects` options, or one patch object passed to every material,
318
+ share one; a fresh patch object per material builds one program each.
288
319
 
289
320
  ## Drawn wrong without a thrown error
290
321
  These come from WebGPURenderer in three.js r187. Nothing throws and the engine's start check does not name them, so the picture is what shows them.