threedog 0.2.1 → 0.5.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 (593) hide show
  1. package/CHANGELOG.md +290 -0
  2. package/README.md +9 -8
  3. package/core/Animator.js +15 -12
  4. package/core/Assets.js +71 -16
  5. package/core/Audio.js +45 -38
  6. package/core/Baked.js +32 -8
  7. package/core/Batching.js +102 -15
  8. package/core/Budget.js +39 -18
  9. package/core/Clock.js +40 -80
  10. package/core/DebugOverrides.js +45 -10
  11. package/core/Describe.js +104 -43
  12. package/core/Engine.js +183 -59
  13. package/core/Events.js +4 -1
  14. package/core/I18n.js +25 -13
  15. package/core/Input.js +168 -79
  16. package/core/Inspect.js +2 -2
  17. package/core/InspectMaterials.js +85 -0
  18. package/core/InspectPerf.js +61 -0
  19. package/core/InspectScene.js +13 -2
  20. package/core/Loading.js +2 -1
  21. package/core/Ops.js +50 -9
  22. package/core/Random.js +9 -2
  23. package/core/Rays.js +5 -5
  24. package/core/SaveStore.js +41 -9
  25. package/core/Saves.js +71 -15
  26. package/core/Stream.js +14 -10
  27. package/core/Threads.js +26 -7
  28. package/core/UrlState.js +25 -9
  29. package/core/Views.js +9 -6
  30. package/core/actor.js +1 -1
  31. package/core/adaptive.js +93 -0
  32. package/core/assetEntry.js +22 -5
  33. package/core/assetHot.js +176 -0
  34. package/core/assetLoad.js +38 -11
  35. package/core/assetManifest.js +48 -9
  36. package/core/assetReport.js +1 -1
  37. package/core/audioRules.js +13 -11
  38. package/core/audioVoice.js +69 -42
  39. package/core/canvasBox.js +1 -2
  40. package/core/catalog.js +5 -2
  41. package/core/cells.js +62 -0
  42. package/core/checks.js +10 -8
  43. package/core/chunkStream.js +87 -0
  44. package/core/control.js +149 -0
  45. package/core/copies.js +32 -0
  46. package/core/dayTime.js +12 -6
  47. package/core/debugView.js +82 -15
  48. package/core/describeRender.js +37 -17
  49. package/core/describeText.js +41 -21
  50. package/core/engineCamera.js +32 -0
  51. package/core/errorCodes.js +438 -19
  52. package/core/errorHints.js +37 -141
  53. package/core/errors.js +31 -8
  54. package/core/events.generated.js +12 -7
  55. package/core/gameLights.js +62 -0
  56. package/core/grayMap.js +20 -0
  57. package/core/grid.js +14 -13
  58. package/core/gridLoad.js +2 -1
  59. package/core/ground.js +6 -4
  60. package/core/headlessLoad.js +55 -0
  61. package/core/holds.js +78 -50
  62. package/core/inputContext.js +11 -7
  63. package/core/inputDefaults.js +24 -21
  64. package/core/inputPad.js +1 -1
  65. package/core/inputPointer.js +1 -1
  66. package/core/inputTouch.js +2 -2
  67. package/core/lifecycle.js +48 -12
  68. package/core/lightWatch.js +6 -4
  69. package/core/look/coreParts.js +137 -30
  70. package/core/look/part.js +175 -95
  71. package/core/look/points.js +255 -0
  72. package/core/look/report.js +34 -17
  73. package/core/look/shadowPart.js +63 -0
  74. package/core/look/state.js +45 -0
  75. package/core/look/write.js +12 -28
  76. package/core/loop.js +100 -41
  77. package/core/math.js +11 -3
  78. package/core/moduleSlots.js +75 -0
  79. package/core/moduleTypes.js +73 -0
  80. package/core/modules.js +145 -27
  81. package/core/movement.js +2 -2
  82. package/core/namedModel.js +70 -0
  83. package/core/opsCheck.js +3 -3
  84. package/core/opsFail.js +15 -6
  85. package/core/opsGuard.js +4 -4
  86. package/core/opsRun.js +4 -3
  87. package/core/owned.js +168 -0
  88. package/core/page.js +2 -1
  89. package/core/params.js +30 -8
  90. package/core/plugins.js +277 -0
  91. package/core/saveApply.js +99 -17
  92. package/core/saveFiles.js +8 -6
  93. package/core/saveValues.js +46 -0
  94. package/core/saveVersions.js +20 -3
  95. package/core/scatter.js +48 -19
  96. package/core/sceneDelta.js +203 -0
  97. package/core/sceneMethods.js +35 -30
  98. package/core/screenToGround.js +1 -1
  99. package/core/services.js +27 -11
  100. package/core/session.js +28 -25
  101. package/core/shaderCost.js +78 -0
  102. package/core/shadowTypes.js +2 -1
  103. package/core/sharedPoint.js +317 -0
  104. package/core/skip.js +36 -28
  105. package/core/stackFrames.js +34 -0
  106. package/core/stacks.js +166 -0
  107. package/core/startup.js +153 -11
  108. package/core/streamSources.js +0 -11
  109. package/core/styleParts.js +63 -47
  110. package/core/targeting.js +1 -1
  111. package/core/textureBytes.js +20 -0
  112. package/core/thingExplain.js +2 -2
  113. package/core/thingOps.js +29 -6
  114. package/core/things.js +21 -11
  115. package/core/threadPure.js +7 -3
  116. package/core/threePatches.js +47 -0
  117. package/core/tier.js +21 -10
  118. package/core/time.js +236 -0
  119. package/core/uiClock.js +25 -0
  120. package/core/util.js +7 -1
  121. package/core/validate.js +65 -86
  122. package/core/wrap.js +106 -0
  123. package/docs/AI.md +87 -100
  124. package/docs/API.md +32 -28
  125. package/docs/CODEMAP.md +220 -147
  126. package/docs/COMMANDS.md +56 -35
  127. package/docs/CONVENTIONS.md +90 -28
  128. package/docs/MIGRATING-0.3.md +248 -0
  129. package/docs/MIGRATING-0.4.md +228 -0
  130. package/docs/MIGRATING-0.5.md +68 -0
  131. package/docs/PERF.md +35 -7
  132. package/docs/THREE.md +79 -27
  133. package/docs/api/ambience.md +0 -1
  134. package/docs/api/assets.md +11 -9
  135. package/docs/api/audio.md +10 -14
  136. package/docs/api/calendar.md +41 -0
  137. package/docs/api/cameraRig.md +16 -5
  138. package/docs/api/characters.md +38 -23
  139. package/docs/api/clock.md +6 -5
  140. package/docs/api/collision.md +9 -6
  141. package/docs/api/content.md +6 -4
  142. package/docs/api/dialogue.md +9 -9
  143. package/docs/api/engine.md +63 -60
  144. package/docs/api/events.md +19 -14
  145. package/docs/api/grids.md +3 -3
  146. package/docs/api/ground.md +1 -1
  147. package/docs/api/hud.md +2 -2
  148. package/docs/api/i18n.md +1 -1
  149. package/docs/api/input.md +11 -6
  150. package/docs/api/interactions.md +7 -5
  151. package/docs/api/inventory.md +17 -16
  152. package/docs/api/level.md +0 -1
  153. package/docs/api/lightPool.md +3 -1
  154. package/docs/api/music.md +1 -1
  155. package/docs/api/nav.md +3 -0
  156. package/docs/api/openWorld.md +2 -1
  157. package/docs/api/particles.md +2 -2
  158. package/docs/api/photo.md +0 -2
  159. package/docs/api/pickups.md +15 -0
  160. package/docs/api/post.md +5 -4
  161. package/docs/api/quests.md +2 -3
  162. package/docs/api/rigid.md +16 -14
  163. package/docs/api/saves.md +6 -4
  164. package/docs/api/settings.md +2 -3
  165. package/docs/api/sky.md +11 -44
  166. package/docs/api/stream.md +1 -1
  167. package/docs/api/style.md +28 -26
  168. package/docs/api/terrain.md +9 -6
  169. package/docs/api/terrainLook.md +10 -0
  170. package/docs/api/timeline.md +3 -4
  171. package/docs/api/tools.md +29 -13
  172. package/docs/api/triggers.md +5 -10
  173. package/docs/api/vegetation.md +11 -8
  174. package/docs/api/vegetationLook.md +10 -0
  175. package/docs/api/water.md +4 -20
  176. package/docs/api/weather.md +5 -15
  177. package/docs/api/weatherLook.md +10 -0
  178. package/docs/api/world.md +2 -1
  179. package/docs/recipes/01-new-game.md +48 -34
  180. package/docs/recipes/02-npc.md +24 -7
  181. package/docs/recipes/03-items-pickups.md +35 -21
  182. package/docs/recipes/04-quests.md +12 -5
  183. package/docs/recipes/05-props-bake.md +151 -15
  184. package/docs/recipes/06-clock-events.md +100 -52
  185. package/docs/recipes/07-flow-scenes-pause.md +40 -9
  186. package/docs/recipes/08-weather-sky.md +145 -36
  187. package/docs/recipes/{09-style-pack.md → 09-style.md} +101 -52
  188. package/docs/recipes/10-blender-level.md +14 -2
  189. package/docs/recipes/11-vehicles.md +64 -7
  190. package/docs/recipes/13-animation.md +14 -6
  191. package/docs/recipes/14-custom-module.md +61 -29
  192. package/docs/recipes/15-perf.md +30 -9
  193. package/docs/recipes/16-dev-bridge.md +61 -37
  194. package/docs/recipes/18-world.md +16 -6
  195. package/docs/recipes/19-shooting-picking.md +6 -6
  196. package/docs/recipes/20-content-actions-save.md +55 -17
  197. package/docs/recipes/21-camera.md +49 -16
  198. package/docs/recipes/22-shop-gold.md +3 -3
  199. package/docs/recipes/23-ops.md +16 -10
  200. package/docs/recipes/26-ui-parts.md +61 -12
  201. package/docs/recipes/27-net.md +11 -5
  202. package/docs/recipes/28-terrain.md +34 -1
  203. package/docs/recipes/29-grid.md +34 -16
  204. package/docs/recipes/30-templates.md +64 -12
  205. package/docs/recipes/31-audio.md +20 -12
  206. package/docs/recipes/32-action-game.md +35 -2
  207. package/docs/recipes/34-environment-lighting.md +26 -3
  208. package/docs/recipes/35-style-from-reference.md +88 -19
  209. package/docs/recipes/36-sky-ground-plant-looks.md +18 -18
  210. package/docs/recipes/37-terrain-look-hooks.md +3 -2
  211. package/docs/recipes/38-environment-look-hooks.md +37 -26
  212. package/docs/recipes/40-scene.md +16 -13
  213. package/docs/recipes/41-thing-registry.md +11 -7
  214. package/docs/recipes/42-terrain-shape.md +2 -2
  215. package/docs/recipes/43-shader-patches-surface-looks.md +158 -76
  216. package/docs/recipes/44-water-weather-look-hooks.md +26 -17
  217. package/docs/recipes/45-cascaded-shadows.md +16 -7
  218. package/docs/recipes/47-island-snow-backdrop.md +7 -7
  219. package/docs/recipes/48-make-material.md +11 -6
  220. package/docs/recipes/49-game-module-contract.md +30 -17
  221. package/docs/recipes/50-own-renderer.md +2 -2
  222. package/docs/recipes/51-capability-catalog.md +3 -3
  223. package/docs/recipes/52-look.md +197 -61
  224. package/docs/recipes/53-ground-up-close.md +1 -1
  225. package/docs/recipes/54-three-idioms.md +88 -0
  226. package/docs/recipes/55-mods-time-wrap.md +112 -0
  227. package/docs/recipes/56-webgpu-tsl.md +260 -0
  228. package/docs/recipes/57-control.md +65 -0
  229. package/docs/recipes/58-input.md +57 -0
  230. package/docs/recipes/59-depth-post-effects.md +83 -0
  231. package/docs/recipes/60-judge-the-picture.md +55 -0
  232. package/examples/action/.threedog/content-index.json +1 -0
  233. package/examples/action/GAMEMAP.md +17 -13
  234. package/examples/action/assets.js +8 -0
  235. package/examples/action/content/actions.js +1 -1
  236. package/examples/action/content/audio.js +5 -5
  237. package/examples/action/look.js +1 -1
  238. package/examples/action/main.js +10 -14
  239. package/examples/action/models.js +24 -23
  240. package/examples/pullable.json +111 -0
  241. package/examples/rc2d/.threedog/content-index.json +1 -0
  242. package/examples/rc2d/GAMEMAP.md +83 -0
  243. package/examples/rc2d/README.md +52 -0
  244. package/examples/rc2d/main.js +63 -0
  245. package/examples/rc2d/rc2d.js +197 -0
  246. package/examples/rc2d/shaders.js +144 -0
  247. package/examples/sheepisland/.threedog/content-index.json +1 -0
  248. package/examples/sheepisland/GAMEMAP.md +13 -11
  249. package/examples/sheepisland/assets.js +5 -0
  250. package/examples/sheepisland/main.js +17 -12
  251. package/examples/sheepisland/style/index.js +6 -6
  252. package/examples/styletest/.threedog/content-index.json +1 -0
  253. package/examples/styletest/GAMEMAP.md +15 -16
  254. package/examples/styletest/assets.js +6 -0
  255. package/examples/styletest/content/templates.js +1 -1
  256. package/examples/styletest/content/vegetation.js +1 -1
  257. package/examples/styletest/look.js +1 -1
  258. package/examples/styletest/main.js +17 -16
  259. package/examples/styletest/models.js +1 -1
  260. package/examples/styletest/params.js +3 -3
  261. package/examples/techniques/contact-shadows/README.md +92 -0
  262. package/examples/techniques/contact-shadows/contactShadows.js +51 -0
  263. package/examples/techniques/contact-shadows/main.js +53 -0
  264. package/examples/techniques/day-night-grade/README.md +86 -0
  265. package/examples/techniques/day-night-grade/dayNightGrade.js +76 -0
  266. package/examples/techniques/day-night-grade/main.js +51 -0
  267. package/examples/techniques/interior-light/README.md +103 -0
  268. package/examples/techniques/interior-light/interiorLight.js +45 -0
  269. package/examples/techniques/interior-light/main.js +124 -0
  270. package/examples/techniques/modular-building/README.md +125 -0
  271. package/examples/techniques/modular-building/kit.js +426 -0
  272. package/examples/techniques/modular-building/main.js +47 -0
  273. package/examples/techniques/night-lights/README.md +94 -0
  274. package/examples/techniques/night-lights/main.js +70 -0
  275. package/examples/techniques/night-lights/nightLights.js +91 -0
  276. package/examples/techniques/outlines-and-rim/README.md +59 -0
  277. package/examples/techniques/outlines-and-rim/main.js +84 -0
  278. package/examples/techniques/outlines-and-rim/outlines.js +64 -0
  279. package/examples/techniques/procedural-animation/README.md +77 -0
  280. package/examples/techniques/procedural-animation/creature.js +44 -0
  281. package/examples/techniques/procedural-animation/main.js +45 -0
  282. package/examples/techniques/procedural-animation/proceduralAnim.js +118 -0
  283. package/examples/techniques/procedural-surface/README.md +67 -0
  284. package/examples/techniques/procedural-surface/main.js +103 -0
  285. package/examples/techniques/procedural-surface/surface.js +120 -0
  286. package/examples/techniques/stylized-shading/README.md +75 -0
  287. package/examples/techniques/stylized-shading/main.js +93 -0
  288. package/examples/techniques/stylized-shading/shading.js +131 -0
  289. package/examples/techniques/sun-and-key-light/README.md +135 -0
  290. package/examples/techniques/sun-and-key-light/keyLight.js +53 -0
  291. package/examples/techniques/sun-and-key-light/main.js +95 -0
  292. package/examples/techniques/wet-road/README.md +99 -0
  293. package/examples/techniques/wet-road/main.js +68 -0
  294. package/examples/techniques/wet-road/wetRoad.js +209 -0
  295. package/examples/webgpu-tsl/.threedog/content-index.json +1 -0
  296. package/examples/webgpu-tsl/GAMEMAP.md +84 -0
  297. package/examples/webgpu-tsl/README.md +42 -0
  298. package/examples/webgpu-tsl/main.js +21 -0
  299. package/examples/webgpu-tsl/tslScene.js +75 -0
  300. package/examples/world/.threedog/content-index.json +1 -0
  301. package/examples/world/GAMEMAP.md +22 -15
  302. package/examples/world/art/humanoid.js +42 -0
  303. package/examples/world/art/index.js +11 -0
  304. package/examples/world/art/models.js +58 -0
  305. package/examples/world/art/shapes.js +9 -0
  306. package/examples/world/assets.js +6 -0
  307. package/examples/world/content/audio.js +5 -5
  308. package/examples/world/content/npcs.js +1 -1
  309. package/examples/world/content/props.js +1 -1
  310. package/examples/world/content/rules.js +1 -1
  311. package/examples/world/content/templates.js +1 -1
  312. package/examples/world/content/vegetation.js +1 -1
  313. package/examples/world/main.js +17 -13
  314. package/examples/world/style/index.js +61 -0
  315. package/examples/world/style/plugins/10-bloom.js +5 -0
  316. package/index.d.ts +44 -45
  317. package/index.js +26 -22
  318. package/llms.txt +11 -4
  319. package/modules/ambience/Ambience.js +34 -23
  320. package/modules/calendar/Calendar.js +163 -0
  321. package/modules/calendar/contract.js +21 -0
  322. package/modules/calendar/index.js +81 -0
  323. package/modules/{sky → calendar}/schedule.js +17 -16
  324. package/modules/calendar/seasons.js +55 -0
  325. package/modules/camera/FirstPersonCamera.js +6 -15
  326. package/modules/camera/FixedCamera.js +33 -15
  327. package/modules/camera/FollowCamera.js +90 -16
  328. package/modules/camera/RtsCamera.js +18 -17
  329. package/modules/camera/common.js +70 -19
  330. package/modules/camera/contract.js +17 -0
  331. package/modules/camera/projection.js +11 -24
  332. package/modules/characters/Character.js +177 -42
  333. package/modules/characters/NPC.js +87 -36
  334. package/modules/characters/assetModel.js +4 -13
  335. package/modules/characters/behaviors.js +2 -1
  336. package/modules/characters/contract.js +13 -0
  337. package/modules/characters/footsteps.js +1 -1
  338. package/modules/characters/index.js +87 -49
  339. package/modules/characters/moveHelpers.js +4 -5
  340. package/modules/characters/movers/common.js +97 -19
  341. package/modules/characters/movers/manual.js +20 -0
  342. package/modules/characters/movers/rapier.js +19 -16
  343. package/modules/characters/movers/simple.js +14 -11
  344. package/modules/characters/movers/support.js +172 -0
  345. package/modules/characters/npcAvoid.js +47 -42
  346. package/modules/characters/npcSim.js +12 -8
  347. package/modules/characters/npcView.js +44 -16
  348. package/modules/characters/pathAsync.js +7 -3
  349. package/modules/characters/playerStrings.js +4 -3
  350. package/modules/characters/proceduralRig.js +2 -1
  351. package/modules/characters/useModel.js +1 -1
  352. package/modules/characters/vehicle.contract.js +21 -0
  353. package/modules/characters/walkTo.js +21 -7
  354. package/modules/collision/Collision.js +65 -25
  355. package/modules/collision/grid.js +8 -6
  356. package/modules/content/explain.js +2 -2
  357. package/modules/content/fields.js +102 -0
  358. package/modules/content/ids.js +8 -6
  359. package/modules/content/index.js +96 -27
  360. package/modules/content/loader.js +45 -33
  361. package/modules/content/models.js +11 -40
  362. package/modules/content/packs.js +6 -5
  363. package/modules/content/parts.js +41 -0
  364. package/modules/content/props.js +16 -9
  365. package/modules/content/rules.js +58 -0
  366. package/modules/content/stages.js +80 -0
  367. package/modules/content/templates.js +121 -30
  368. package/modules/debug/DebugPanel.js +24 -17
  369. package/modules/flow/contract.js +16 -0
  370. package/modules/flow/index.js +21 -15
  371. package/modules/gameplay/Container.js +41 -32
  372. package/modules/gameplay/Containers.js +30 -15
  373. package/modules/gameplay/Dialogue.js +113 -55
  374. package/modules/gameplay/Interactions.js +193 -67
  375. package/modules/gameplay/Inventory.js +69 -73
  376. package/modules/gameplay/Quests.js +75 -39
  377. package/modules/gameplay/boxOps.js +3 -3
  378. package/modules/gameplay/dialogue.contract.js +21 -0
  379. package/modules/gameplay/dialogueBox.js +4 -2
  380. package/modules/gameplay/dialogueBubbles.js +116 -0
  381. package/modules/gameplay/interactionPrompt.js +4 -1
  382. package/modules/gameplay/interactions.contract.js +16 -0
  383. package/modules/gameplay/inventory.contract.js +23 -0
  384. package/modules/gameplay/inventoryOps.js +18 -16
  385. package/modules/gameplay/pickups.js +268 -85
  386. package/modules/gameplay/questLog.js +4 -4
  387. package/modules/gameplay/quests.contract.js +17 -0
  388. package/modules/grid/Grid.js +92 -50
  389. package/modules/grid/Layer.js +14 -13
  390. package/modules/grid/index.js +60 -36
  391. package/modules/grid/ops.js +20 -18
  392. package/modules/grid/preview.js +15 -16
  393. package/modules/grid/strings.js +12 -0
  394. package/modules/grid/tiles.js +6 -5
  395. package/modules/hlod/index.js +51 -19
  396. package/modules/hud/index.js +35 -20
  397. package/modules/hud/parts.js +20 -7
  398. package/modules/level/heightfield.js +3 -1
  399. package/modules/level/index.js +45 -20
  400. package/modules/level/nodes.js +4 -3
  401. package/modules/lights/index.js +42 -18
  402. package/modules/music/Music.js +38 -21
  403. package/modules/music/rules.js +1 -1
  404. package/modules/nav/index.js +48 -42
  405. package/modules/net/Client.js +13 -6
  406. package/modules/net/Host.js +19 -5
  407. package/modules/net/Net.js +2 -1
  408. package/modules/net/index.js +13 -8
  409. package/modules/net/sync.js +9 -8
  410. package/modules/net/transports.js +77 -27
  411. package/modules/particles/Particles.js +23 -14
  412. package/modules/particles/contract.js +17 -0
  413. package/modules/particles/effect.js +39 -11
  414. package/modules/photo/Photo.js +53 -36
  415. package/modules/rigid/RigidBodies.js +194 -32
  416. package/modules/rigid/Vehicles.js +18 -15
  417. package/modules/rigid/sync.js +62 -17
  418. package/modules/settings/Settings.js +57 -52
  419. package/modules/settings/apply.js +38 -3
  420. package/modules/settings/sections.js +5 -3
  421. package/modules/settings/strings.js +3 -2
  422. package/modules/settings/view.js +5 -3
  423. package/modules/sky/Sky.js +88 -176
  424. package/modules/sky/cascades.js +86 -25
  425. package/modules/sky/cascades.tsl.js +82 -0
  426. package/modules/sky/clouds.js +34 -19
  427. package/modules/sky/domeLayers.js +30 -15
  428. package/modules/sky/environment.js +83 -13
  429. package/modules/sky/fog.js +140 -95
  430. package/modules/sky/frame.js +112 -44
  431. package/modules/sky/look.js +22 -19
  432. package/modules/sky/lookFog.js +48 -52
  433. package/modules/sky/lookShadow.js +53 -41
  434. package/modules/sky/lookSky.js +82 -21
  435. package/modules/sky/season.js +21 -0
  436. package/modules/sky/shader.js +41 -19
  437. package/modules/sky/shadow.js +44 -20
  438. package/modules/sky/skyModule.js +45 -33
  439. package/modules/sky/tint.js +61 -0
  440. package/modules/terrain/ChunkManager.js +175 -108
  441. package/modules/terrain/chunkJob.js +1 -1
  442. package/modules/terrain/chunkQueries.js +6 -4
  443. package/modules/terrain/index.js +105 -50
  444. package/modules/terrain/look.js +83 -0
  445. package/modules/terrain/lookGround.js +21 -16
  446. package/modules/terrain/terrainDefaults.js +1 -1
  447. package/modules/terrain/terrainEdit.js +18 -20
  448. package/modules/terrain/terrainGen.js +5 -3
  449. package/modules/terrain/terrainIsland.js +5 -4
  450. package/modules/terrain/terrainShape.js +12 -12
  451. package/modules/terrain/terrainShapeMain.js +8 -7
  452. package/modules/terrain/terrainTexture.js +21 -19
  453. package/modules/timeline/Timeline.js +95 -43
  454. package/modules/timeline/Tween.js +18 -10
  455. package/modules/timeline/letterbox.js +2 -2
  456. package/modules/timeline/shots.js +5 -1
  457. package/modules/triggers/index.js +107 -76
  458. package/modules/vegetation/Vegetation.js +186 -110
  459. package/modules/vegetation/densityMap.js +62 -0
  460. package/modules/vegetation/groundChunks.js +52 -58
  461. package/modules/vegetation/index.js +32 -11
  462. package/modules/vegetation/look.js +119 -0
  463. package/modules/vegetation/lookWind.js +71 -10
  464. package/modules/vegetation/modelGeometry.js +3 -2
  465. package/modules/vegetation/nearFade.js +8 -2
  466. package/modules/water/Water.js +65 -27
  467. package/modules/water/look.js +29 -18
  468. package/modules/water/surface.js +64 -25
  469. package/modules/water/surfaceDefaults.js +3 -0
  470. package/modules/weather/Weather.js +62 -104
  471. package/modules/weather/look.js +1 -2
  472. package/modules/weather/particles.js +24 -9
  473. package/modules/weather/strings.js +2 -2
  474. package/modules/weather/weatherLook.js +135 -0
  475. package/modules/world/World.js +24 -7
  476. package/modules/world/explain.js +1 -1
  477. package/modules/world/index.js +18 -4
  478. package/modules/world/persist.js +62 -2
  479. package/modules/world/pos.js +3 -2
  480. package/modules/world/records.js +8 -6
  481. package/modules/world/sim.js +60 -20
  482. package/modules/world/simFar.js +4 -3
  483. package/modules/world/state.js +3 -2
  484. package/modules/world/thingSource.js +1 -1
  485. package/modules/world/views.js +7 -5
  486. package/package.json +7 -3
  487. package/presets.js +41 -27
  488. package/render/PostFX.js +145 -120
  489. package/render/backend.js +440 -0
  490. package/render/detail.js +120 -39
  491. package/render/effects.js +130 -38
  492. package/render/engineUniforms.js +10 -1
  493. package/render/fuse.js +5 -4
  494. package/render/fx/cloudShadow.tsl.js +16 -0
  495. package/render/fx/detail.tsl.js +66 -0
  496. package/render/fx/index.js +26 -0
  497. package/render/fx/lighting.tsl.js +28 -0
  498. package/render/fx/nodeErrors.tsl.js +68 -0
  499. package/render/fx/noise.tsl.js +12 -0
  500. package/render/fx/objectOrigin.tsl.js +42 -0
  501. package/render/fx/particles.tsl.js +139 -0
  502. package/render/fx/patchNodes.tsl.js +403 -0
  503. package/render/fx/postWebGPU.tsl.js +158 -0
  504. package/render/fx/season.tsl.js +13 -0
  505. package/render/fx/sky.tsl.js +260 -0
  506. package/render/fx/uniforms.tsl.js +67 -0
  507. package/render/fx/water.tsl.js +53 -0
  508. package/render/fx/wind.tsl.js +22 -0
  509. package/render/fxNumbers.js +36 -0
  510. package/render/hotGlsl.js +24 -0
  511. package/render/lighting.js +66 -14
  512. package/render/lights.js +223 -4
  513. package/render/lookGlow.js +139 -0
  514. package/render/lookSurface.js +99 -36
  515. package/render/materials.js +71 -52
  516. package/render/modeling.js +73 -0
  517. package/render/ownFrame.js +76 -0
  518. package/render/patches.js +311 -34
  519. package/render/postLook.js +124 -46
  520. package/render/postWebGL.js +197 -0
  521. package/render/probes.js +231 -0
  522. package/render/shaderErrors.js +154 -0
  523. package/render/slots.js +165 -0
  524. package/render/surface.js +53 -17
  525. package/render/terms.js +211 -0
  526. package/render/uniformDecl.js +3 -2
  527. package/types/common.d.ts +2 -2
  528. package/types/core.d.ts +614 -240
  529. package/types/gameplay.d.ts +482 -312
  530. package/types/generated/core/Audio.d.ts +26 -42
  531. package/types/generated/core/Batching.d.ts +6 -2
  532. package/types/generated/core/Budget.d.ts +2 -8
  533. package/types/generated/core/DebugOverrides.d.ts +44 -3
  534. package/types/generated/core/I18n.d.ts +2 -2
  535. package/types/generated/core/Input.d.ts +102 -31
  536. package/types/generated/core/Ops.d.ts +31 -0
  537. package/types/generated/core/Random.d.ts +2 -2
  538. package/types/generated/core/Saves.d.ts +10 -2
  539. package/types/generated/core/Stream.d.ts +1 -1
  540. package/types/generated/core/Threads.d.ts +4 -1
  541. package/types/generated/core/Views.d.ts +0 -1
  542. package/types/generated/core/audioVoice.d.ts +17 -9
  543. package/types/generated/core/control.d.ts +55 -0
  544. package/types/generated/core/session.d.ts +2 -1
  545. package/types/generated/modules/ambience/Ambience.d.ts +0 -9
  546. package/types/generated/modules/calendar/Calendar.d.ts +84 -0
  547. package/types/generated/modules/calendar/index.d.ts +10 -0
  548. package/types/generated/modules/debug/DebugPanel.d.ts +2 -2
  549. package/types/generated/modules/grid/Grid.d.ts +61 -25
  550. package/types/generated/modules/grid/Layer.d.ts +5 -5
  551. package/types/generated/modules/grid/index.d.ts +29 -17
  552. package/types/generated/modules/music/Music.d.ts +5 -3
  553. package/types/generated/modules/net/index.d.ts +3 -3
  554. package/types/generated/modules/net/transports.d.ts +12 -3
  555. package/types/generated/modules/particles/Particles.d.ts +1 -1
  556. package/types/generated/modules/sky/Sky.d.ts +12 -104
  557. package/types/generated/modules/sky/skyModule.d.ts +1 -1
  558. package/types/generated/modules/timeline/Timeline.d.ts +8 -6
  559. package/types/generated/modules/weather/Weather.d.ts +17 -18
  560. package/types/generated/modules/weather/weatherLook.d.ts +12 -0
  561. package/types/generated/modules/world/World.d.ts +18 -3
  562. package/types/generated/render/PostFX.d.ts +67 -30
  563. package/types/generated/render/materials.d.ts +26 -20
  564. package/types/generated/render/modeling.d.ts +30 -0
  565. package/types/generated/render/patches.d.ts +16 -2
  566. package/types/generated/ui/UI.d.ts +6 -3
  567. package/types/nav.d.ts +6 -0
  568. package/types/physics.d.ts +137 -44
  569. package/types/style.d.ts +109 -81
  570. package/types/tsl.d.ts +86 -0
  571. package/types/world.d.ts +158 -110
  572. package/ui/Focus.js +25 -14
  573. package/ui/LoadingScreen.js +1 -1
  574. package/ui/Parts.js +27 -11
  575. package/ui/UI.js +20 -10
  576. package/ui/cursor.js +115 -0
  577. package/ui/defaults.js +15 -11
  578. package/ui/theme.js +9 -6
  579. package/ui/touchPart.js +1 -1
  580. package/core/claims.js +0 -51
  581. package/core/look/layers.js +0 -136
  582. package/core/renamed.js +0 -22
  583. package/docs/api/entities.md +0 -61
  584. package/examples/styletest/overrides.js +0 -33
  585. package/examples/styletest/panel.js +0 -135
  586. package/modules/entities/Entities.js +0 -243
  587. package/modules/entities/build.js +0 -25
  588. package/modules/entities/index.js +0 -4
  589. package/modules/sky/calendar.js +0 -80
  590. package/modules/sky/layers.js +0 -69
  591. package/modules/terrain/chunkLevels.js +0 -40
  592. package/modules/terrain/mountTerrain.js +0 -32
  593. package/modules/world/cells.js +0 -42
@@ -0,0 +1,231 @@
1
+ // Baked light probes. A grid of SH probes from the scene (bake / load / JSON), fed into one scene LightProbe each frame.
2
+ // Why only plain three.js (CubeCamera, LightProbeGenerator, LightProbe, no GLSL): it runs on both renderers, and the game can
3
+ // read or replace every piece (handle.probe is an ordinary LightProbe; handle.sample feeds the game's own).
4
+ // How the light reaches materials: one scene LightProbe whose SH is interpolated (trilinear) at a followed point every frame. Every lit material
5
+ // already reads scene light probes, so nothing is patched and no program changes when the point moves.
6
+ // shortcut: one SH for the whole scene (at the followed point): an object far from that point gets the light of where the point is, not its own.
7
+ // Upgrade when a scene needs per-object light (a dark cave next to a bright square, both on screen): give each mesh its own SH (a material
8
+ // uniform fed from sample()), or a 3D texture the shader reads; both need a material patch, which this scaffold avoids.
9
+ import { engineOwned } from '../core/things.js';
10
+ import * as THREE from 'three';
11
+ import { LightProbeGenerator } from 'three/addons/lights/LightProbeGenerator.js';
12
+ import { readParams } from '../core/params.js';
13
+ import { codedError } from '../core/errorHints.js';
14
+ import { defineOwned, dropOwned } from '../core/owned.js';
15
+ import { vec3 } from '../core/math.js';
16
+ import { cubeRender, cubeTarget } from './backend.js';
17
+
18
+ const FORMAT = 'threedog-probes', VERSION = 1, MAX_PROBES = 4096, SH = 27;
19
+ const BAKE = {
20
+ bounds: { type: 'object', desc: 'THREE.Box3 or { min, max } (positions) the grid spans' },
21
+ spacing: { type: 'number', min: 0.01, desc: 'largest distance between neighbour probes, meters' },
22
+ resolution: { type: 'int', default: 16, min: 4, max: 256, desc: 'cube face size in px per probe (SH keeps only low frequencies: 16 is plenty)' },
23
+ include: { type: 'function', optional: true, desc: '(object) => bool: meshes that return false are hidden while baking (the player, moving props)' },
24
+ height: { type: 'number', optional: true, desc: 'one layer at this height above engine.surface(x, z) instead of a 3D grid' },
25
+ follow: { type: 'any', default: 'focus', desc: "where the scene probe samples: 'focus' | 'camera' | Object3D | () => position | false (no scene probe)" },
26
+ owner: { type: 'string', default: 'game', desc: 'who made the set (describe().render.probes)' },
27
+ };
28
+ const LOAD = { follow: BAKE.follow, owner: BAKE.owner };
29
+ const STRINGS = {
30
+ bounds: 'engine.bakeProbes({ bounds }): bounds must be a THREE.Box3 or { min: [x, y, z], max: [x, y, z] } with max >= min on every axis; got {got}',
31
+ tooMany: 'engine.bakeProbes(): {n} probes ({dims}) is more than {max}; raise spacing (each probe costs 6 renders and a GPU read back)',
32
+ follow: "{where}: follow must be 'focus', 'camera', an Object3D, a function returning a position, or false; got {got}",
33
+ data: 'engine.loadProbes(json): {why}. Pass what handle.toJSON() returned (format \'' + FORMAT + '\', version ' + VERSION + ')',
34
+ };
35
+ const sets = e => (e._probeSets ??= new Set());
36
+
37
+ /** Grid layout from bounds + spacing: counts per axis and the actual step (<= spacing, so the grid ends exactly on the bounds) */
38
+ function layout(bounds, spacing, height) {
39
+ const min = vec3(bounds.min), max = vec3(bounds.max);
40
+ if (![min.x, min.y, min.z, max.x, max.y, max.z].every(Number.isFinite) || max.x < min.x || max.y < min.y || max.z < min.z) {
41
+ throw codedError('probes-option', STRINGS.bounds.replace('{got}', JSON.stringify({ min, max })));
42
+ }
43
+ const size = new THREE.Vector3().subVectors(max, min);
44
+ const n = s => Math.max(1, Math.ceil(s / spacing - 1e-6) + 1);
45
+ const counts = [n(size.x), height == null ? n(size.y) : 1, n(size.z)];
46
+ const step = [size.x, size.y, size.z].map((s, i) => (counts[i] > 1 ? s / (counts[i] - 1) : 0));
47
+ return { origin: [min.x, min.y, min.z], step, counts };
48
+ }
49
+
50
+ /** World position of grid point i of data { origin, step, counts, height } */
51
+ function gridPoint(e, d, i, out) {
52
+ const [nx, ny] = d.counts, ix = i % nx, iy = Math.floor(i / nx) % ny, iz = Math.floor(i / (nx * ny));
53
+ out.set(d.origin[0] + ix * d.step[0], d.origin[1] + iy * d.step[1], d.origin[2] + iz * d.step[2]);
54
+ if (d.height != null) { const g = e.surface(out.x, out.z); out.y = (Number.isFinite(g) ? g : 0) + d.height; }
55
+ return out;
56
+ }
57
+
58
+ /** Refuse a follow value before any work: bakeProbes checks it first, so a typo does not cost a whole bake (6 renders per probe) and then throw */
59
+ function checkFollow(follow, where) {
60
+ if (!(follow === false || follow === 'focus' || follow === 'camera' || follow?.isObject3D || typeof follow === 'function')) {
61
+ throw codedError('probes-option', STRINGS.follow.replace('{where}', where).replace('{got}', String(follow)));
62
+ }
63
+ }
64
+
65
+ /** A probe set: grid data + the scene probe that follows a point. Made by bakeProbes / loadProbes only (they checked follow) */
66
+ class ProbeSet {
67
+ constructor(e, data, { follow, owner, source }) {
68
+ Object.assign(this, { _e: e, origin: data.origin, step: data.step, counts: data.counts, height: data.height ?? null, sh: data.sh, owner, source, follow });
69
+ this.count = this.counts[0] * this.counts[1] * this.counts[2];
70
+ /** bake time in ms (null for a loaded set) */ this.bakeMs = data.bakeMs ?? null;
71
+ /** the scene LightProbe fed from the grid (null with follow: false); its intensity is the game's (three's default 1) */
72
+ this.probe = null;
73
+ if (follow !== false) {
74
+ this.probe = new THREE.LightProbe(); this.probe.name = 'probes:' + owner;
75
+ e.scene.add(engineOwned('probes', this.probe));
76
+ // the engine writes probe.sh every frame: a game that writes it itself (its own SH) takes it over, the engine yields (core/owned.js)
77
+ const n = e._probeN = (e._probeN ?? 0) + 1; // unique per engine: a reused id would replace another live set's record
78
+ this._owned = defineOwned(e, { id: `probes.sh#${n}`, part: 'lights', key: 'probes', read: () => this.probe.sh.toArray(), objects: [this.probe],
79
+ levels: { manual: "engine.look.lights.manual('probes')" } });
80
+ this._tmp = new THREE.Vector3();
81
+ this._frame = e.onFrame(() => this._update());
82
+ this._update();
83
+ }
84
+ sets(e).add(this);
85
+ }
86
+ _update() {
87
+ const o = this._owned, f = this.follow, e = this._e, p = this._tmp;
88
+ o.check();
89
+ if (o.on) {
90
+ if (f === 'camera') p.copy(e.camera.position); else if (f?.isObject3D) f.getWorldPosition(p); else if (typeof f === 'function') vec3(f(), p); else vec3(e.focus, p);
91
+ this.sample(p, this.probe.sh);
92
+ }
93
+ o.mark();
94
+ }
95
+ /**
96
+ * The interpolated SH at a position (trilinear between the 8 grid probes around it; outside the grid the nearest edge). With height mode y is ignored.
97
+ * @param {any} pos any position form (Vector3, Object3D, [x, y, z], { x, y, z })
98
+ * @param {THREE.SphericalHarmonics3 | THREE.LightProbe} [target] written in place (a LightProbe's sh); a new SphericalHarmonics3 when omitted
99
+ * @returns {THREE.SphericalHarmonics3}
100
+ */
101
+ sample(pos, target) {
102
+ const sh = target?.isLightProbe ? target.sh : target ?? new THREE.SphericalHarmonics3();
103
+ const v = vec3(pos, this._s ??= new THREE.Vector3()), [nx, ny, nz] = this.counts, c = sh.coefficients;
104
+ const axis = (x, i) => { const n = this.counts[i]; if (n < 2) return [0, 0, 0]; const t = Math.min(n - 1, Math.max(0, (x - this.origin[i]) / this.step[i])), a = Math.min(n - 2, Math.floor(t)); return [a, a + 1, t - a]; };
105
+ const [x0, x1, fx] = axis(v.x, 0), [y0, y1, fy] = this.height == null ? axis(v.y, 1) : [0, 0, 0], [z0, z1, fz] = axis(v.z, 2);
106
+ for (const k of c) k.set(0, 0, 0);
107
+ const add = (ix, iy, iz, w) => {
108
+ if (w === 0) return;
109
+ const b = ((iz * ny + iy) * nx + ix) * SH;
110
+ for (let j = 0; j < 9; j++) c[j].x += this.sh[b + j * 3] * w, c[j].y += this.sh[b + j * 3 + 1] * w, c[j].z += this.sh[b + j * 3 + 2] * w;
111
+ };
112
+ for (const [iz, wz] of [[z0, 1 - fz], [z1, fz]]) for (const [iy, wy] of [[y0, 1 - fy], [y1, fy]]) for (const [ix, wx] of [[x0, 1 - fx], [x1, fx]]) add(ix, iy, iz, wx * wy * wz);
113
+ return sh;
114
+ }
115
+ /** World position of probe i (height mode: on the ground + height) @param {number} i @param {THREE.Vector3} [out] */
116
+ point(i, out = new THREE.Vector3()) { return gridPoint(this._e, this, i, out); }
117
+ /** Plain data to ship as a file and give to engine.loadProbes (SH rounded to 5 decimals) */
118
+ toJSON() {
119
+ return { format: FORMAT, version: VERSION, origin: this.origin, step: this.step, counts: this.counts, height: this.height,
120
+ sh: Array.from(this.sh, v => Math.round(v * 1e5) / 1e5) };
121
+ }
122
+ /** describe().render.probes row */
123
+ info() {
124
+ return { count: this.count, counts: this.counts, step: this.step.map(s => Math.round(s * 100) / 100), source: this.source, owner: this.owner,
125
+ follow: this.follow === false ? false : typeof this.follow === 'string' ? this.follow : this.follow?.isObject3D ? `object ${this.follow.name || this.follow.id}` : 'function',
126
+ writer: this._owned ? this._owned.info().writer : null, ...(this.bakeMs != null ? { bakeMs: Math.round(this.bakeMs) } : {}) };
127
+ }
128
+ /** Take the scene probe out and stop updating it; the data stays readable (sample, toJSON). Safe to call twice */
129
+ remove() {
130
+ if (!sets(this._e).delete(this)) return;
131
+ this._frame?.remove(); this.probe?.removeFromParent();
132
+ if (this._owned) dropOwned(this._e, [this._owned]);
133
+ }
134
+ }
135
+
136
+ /** Render one cube at p and turn it into SH. Hidden objects are restored before the async read back, so normal frames never see them hidden */
137
+ async function bakeOne(e, cam, rt, p, hide) {
138
+ cam.position.copy(p); cam.updateMatrixWorld();
139
+ for (const o of hide) o.visible = false;
140
+ try { cubeRender(e.renderer, e.scene, cam); } finally { for (const o of hide) o.visible = true; }
141
+ return (await LightProbeGenerator.fromCubeRenderTarget(e.renderer, rt)).sh.toArray();
142
+ }
143
+
144
+ /** The debug view: one dot per probe, colored by its average (DC) light, over the real look */
145
+ function drawProbes(e, scene) {
146
+ const list = [...sets(e)], n = list.reduce((s, x) => s + x.count, 0);
147
+ if (!n) return () => {};
148
+ const geo = new THREE.SphereGeometry(0.15, 8, 6), mat = new THREE.MeshBasicMaterial({ toneMapped: false }); // debug overlay only
149
+ const dots = new THREE.InstancedMesh(geo, mat, n), m = new THREE.Matrix4(), p = new THREE.Vector3(), c = new THREE.Color();
150
+ let k = 0;
151
+ for (const s of list) for (let i = 0; i < s.count; i++, k++) {
152
+ dots.setMatrixAt(k, m.makeTranslation(s.point(i, p)));
153
+ const b = i * SH, Y00 = 0.282095; // the SH constant term times Y00 is the probe's average radiance
154
+ dots.setColorAt(k, c.setRGB(s.sh[b] * Y00, s.sh[b + 1] * Y00, s.sh[b + 2] * Y00));
155
+ }
156
+ dots.name = 'debug:probes'; scene.add(engineOwned('debug', dots));
157
+ return () => { dots.removeFromParent(); geo.dispose(); mat.dispose(); dots.dispose(); };
158
+ }
159
+ function addSet(e, data, o) {
160
+ e._probeView ??= e.debug?.defineView('probes', { what: 'each light probe as a dot colored by its average light', apply: scene => drawProbes(e, scene) });
161
+ return new ProbeSet(e, data, o);
162
+ }
163
+
164
+ /** Check a loaded file's shape; every problem is a coded refusal, never a half-applied grid */
165
+ function readData(json) {
166
+ const bad = why => codedError('probes-data', STRINGS.data.replace('{why}', why));
167
+ if (!json || typeof json !== 'object') throw bad(`got ${typeof json}`);
168
+ if (json.format !== FORMAT) throw bad(`format is ${JSON.stringify(json.format)}`);
169
+ if (json.version !== VERSION) throw bad(`version ${JSON.stringify(json.version)} is not supported`);
170
+ const tri = (k, ok) => { const v = json[k]; if (!Array.isArray(v) || v.length !== 3 || !v.every(ok)) throw bad(`${k} must be 3 numbers, got ${JSON.stringify(v)}`); return v; };
171
+ const counts = tri('counts', x => Number.isInteger(x) && x >= 1), origin = tri('origin', Number.isFinite), step = tri('step', x => Number.isFinite(x) && x >= 0);
172
+ // sample() divides by the step on every axis with 2+ probes: a 0 there gave NaN light (a black picture, no error)
173
+ const flat = [0, 1, 2].find(i => counts[i] > 1 && !(step[i] > 0));
174
+ if (flat !== undefined) throw bad(`step[${flat}] is ${step[flat]} while counts[${flat}] is ${counts[flat]}: an axis with 2 or more probes needs a step above 0`);
175
+ const n = counts[0] * counts[1] * counts[2];
176
+ if (n > MAX_PROBES) throw bad(`${n} probes is more than ${MAX_PROBES}`);
177
+ if (json.height != null && !Number.isFinite(json.height)) throw bad('height must be a number or null');
178
+ if (!Array.isArray(json.sh) || json.sh.length !== n * SH) throw bad(`sh must hold ${n} x ${SH} numbers, got ${Array.isArray(json.sh) ? json.sh.length : typeof json.sh}`);
179
+ const sh = Float32Array.from(json.sh);
180
+ if (!sh.every(Number.isFinite)) throw bad('sh holds a value that is not a finite number');
181
+ return { origin, step, counts, height: json.height ?? null, sh };
182
+ }
183
+
184
+ /** Mixed into Engine.prototype (core/Engine.js) */
185
+ export const probeMethods = {
186
+ /**
187
+ * Bake a grid of light probes from the scene as it is now: a cube render at every grid point, turned into spherical harmonics (three's
188
+ * LightProbeGenerator), then one scene `LightProbe` that follows a point (`follow`, default the camera focus) and takes the light
189
+ * interpolated there every frame. The probe light adds to whatever ambient light the scene has (hemi, environment): lower those yourself
190
+ * where the probes take over. A load-time cost, not per frame: 6 renders + a GPU read back per probe, awaited one probe at a time so the page
191
+ * keeps drawing; ship the result with `toJSON()` + `engine.loadProbes(json)` instead of baking at every start.
192
+ * Render targets and cube cameras are disposed before it resolves. Adding the probe changes the light setup: bake at start-up, not mid-play.
193
+ * @example const probes = await engine.bakeProbes({ bounds: { min: [-20, 0, -20], max: [20, 6, 20] }, spacing: 4, include: o => !o.userData.moving });
194
+ * probes.sample(npc.position, npcProbe); // your own probe for one object
195
+ * saveFile('probes.json', JSON.stringify(probes.toJSON()));
196
+ * @param {{ bounds: THREE.Box3 | { min: any, max: any }, spacing: number, resolution?: number, include?: (o: THREE.Object3D) => boolean,
197
+ * height?: number, follow?: 'focus' | 'camera' | THREE.Object3D | (() => any) | false, owner?: string }} opts
198
+ * @returns {Promise<import('../types/core').ProbeSet>}
199
+ */
200
+ async bakeProbes(opts) {
201
+ const o = readParams('engine.bakeProbes()', BAKE, opts);
202
+ checkFollow(o.follow, 'engine.bakeProbes()');
203
+ const { origin, step, counts } = layout(o.bounds, o.spacing, o.height), n = counts[0] * counts[1] * counts[2];
204
+ if (n > MAX_PROBES) throw codedError('probes-option', STRINGS.tooMany.replace('{n}', n).replace('{dims}', counts.join(' x ')).replace('{max}', MAX_PROBES));
205
+ const t0 = performance.now(); // measure
206
+ const rt = cubeTarget(this.renderer, THREE, o.resolution, { type: THREE.HalfFloatType, generateMipmaps: false });
207
+ const cam = new THREE.CubeCamera(0.05, this.camera.far, rt);
208
+ // hidden while each cube renders: meshes the filter rejects, and every scene probe (an earlier set lighting the capture would count twice)
209
+ const hide = [];
210
+ this.scene.traverse(x => { if (x.visible && (x.isLightProbe || (o.include && (x.isMesh || x.isPoints || x.isLine || x.isSprite) && !o.include(x)))) hide.push(x); });
211
+ const data = { origin, step, counts, height: o.height ?? null, sh: new Float32Array(n * SH) };
212
+ const p = new THREE.Vector3();
213
+ try {
214
+ for (let i = 0; i < n; i++) data.sh.set(await bakeOne(this, cam, rt, gridPoint(this, data, i, p), hide), i * SH);
215
+ } finally { rt.dispose(); }
216
+ data.bakeMs = performance.now() - t0; // measure
217
+ return addSet(this, data, { follow: o.follow, owner: o.owner, source: 'bake' });
218
+ },
219
+ /**
220
+ * A probe set from a file made by `handle.toJSON()` (no baking). A wrong shape is refused with code `probes-data` and nothing is added.
221
+ * @example const probes = engine.loadProbes(await (await fetch('probes.json')).json());
222
+ * @param {object} json
223
+ * @param {{ follow?: 'focus' | 'camera' | THREE.Object3D | (() => any) | false, owner?: string }} [opts]
224
+ * @returns {import('../types/core').ProbeSet}
225
+ */
226
+ loadProbes(json, opts) {
227
+ const o = readParams('engine.loadProbes()', LOAD, opts);
228
+ checkFollow(o.follow, 'engine.loadProbes()');
229
+ return addSet(this, readData(json), { follow: o.follow, owner: o.owner, source: 'file' });
230
+ },
231
+ };
@@ -0,0 +1,154 @@
1
+ // Shader errors naming the patch and slot.
2
+ // Design: docs/plans/done/2026-11-02-look-architecture.md §4g.
3
+ // Why: patch code is injected into the middle of three's shader, and the original error gives only "line 812", so an AI cannot tell which patch is wrong. On injection slots.js's mark() adds
4
+ // `// threedog:begin patch=x slot=y` / `// threedog:end` before and after each piece; here, going up from the error line number, find the nearest begin marker and report the patch name and slot.
5
+ // three has a hook renderer.debug.onShaderError: once set, three no longer prints on its own, so the original error is printed in full here too (nothing from plain three.js is lost).
6
+ // if the game set onShaderError itself, do not override it.
7
+ import { setConsoleFunction, getConsoleFunction } from 'three';
8
+ import { isWebGPU, findNodeBuild } from './backend.js';
9
+ import { materialPatches } from './patches.js';
10
+
11
+ const BEGIN = /^\s*\/\/ threedog:begin patch=(\S+) slot=(\S+)/, END = /^\s*\/\/ threedog:end/;
12
+ // a GLSL file served by the vite preset's threedog-live plugin (shader hot reload, render/hotGlsl.js): `// threedog:begin file=<path>`
13
+ const FILE = /^\s*\/\/ threedog:begin file=(\S+)/;
14
+
15
+ /**
16
+ * Which patch (and slot) source line `n` (1-based) falls in, or null when it is in the material's own code
17
+ * @internal
18
+ * @param {string[]} lines @param {number} n
19
+ * @returns {{ patch: string | null, slot: string | null, file?: string } | null} file: 'path:line' when the line is in a hot-reloadable GLSL file
20
+ */
21
+ function patchAt(lines, n) {
22
+ // markers nest (a file's code inside a patch), so walk down to line n keeping the open blocks
23
+ const open = [];
24
+ for (let i = 0; i < Math.min(n, lines.length) - 1; i++) {
25
+ const l = lines[i];
26
+ if (END.test(l)) { open.pop(); continue; }
27
+ const m = BEGIN.exec(l), f = FILE.exec(l);
28
+ if (m) open.push({ patch: m[1], slot: m[2] }); else if (f) open.push({ file: f[1], first: i + 2 });
29
+ }
30
+ const p = open.findLast(o => o.patch), f = open.findLast(o => o.file);
31
+ if (!p && !f) return null;
32
+ return { patch: p?.patch ?? null, slot: p?.slot ?? null, ...(f && { file: `${f.file}:${n - f.first + 1}` }) };
33
+ }
34
+
35
+ /**
36
+ * Explain one failed shader stage: '[threedog] shader error in patch 'x' (slot y) ...' per error line, or a note that the error is in
37
+ * the material's own code with the list of engine patches present.
38
+ * @internal
39
+ * @param {'vertex' | 'fragment'} stage @param {string} source @param {string} log
40
+ * @returns {string}
41
+ */
42
+ function explainShaderError(stage, source, log) {
43
+ const lines = source.split('\n'), patches = [...new Set(lines.map(l => BEGIN.exec(l)?.[1]).filter(Boolean))];
44
+ const out = [];
45
+ for (const row of log.split('\n')) {
46
+ const m = /ERROR:\s*\d+:(\d+):/.exec(row);
47
+ if (!m) continue;
48
+ const n = +m[1], at = patchAt(lines, n), snippet = (lines[n - 1] ?? '').trim();
49
+ const where = at && [at.file && `file ${at.file}`, at.patch && `patch '${at.patch}' (slot ${at.slot})`].filter(Boolean).join(', ');
50
+ out.push(at ? `[threedog] shader error in ${where}, ${stage} shader: ${row.trim()} | ${snippet}`
51
+ : `[threedog] shader error in the material's own ${stage} code (not in a patch; patches in this program: ${patches.join(', ') || 'none'}): ${row.trim()} | ${snippet}`);
52
+ }
53
+ return out.join('\n');
54
+ }
55
+
56
+ /**
57
+ * Hook renderer.debug.onShaderError (when nothing else holds it) so compile errors name the patch and slot.
58
+ * @internal core/Engine.js
59
+ * @param {import('three').WebGLRenderer} renderer
60
+ */
61
+ export function nameShaderErrors(renderer) {
62
+ const d = /** @type {any} */ (renderer).debug;
63
+ if (isWebGPU(renderer)) { nameNodeErrors(renderer); return; }
64
+ if (!d || d.onShaderError) return;
65
+ d.onShaderError = (gl, program, vs, fs) => {
66
+ const parts = [];
67
+ for (const [stage, sh] of /** @type {const} */ ([['vertex', vs], ['fragment', fs]])) {
68
+ const log = gl.getShaderInfoLog(sh) || '';
69
+ if (gl.getShaderParameter(sh, gl.COMPILE_STATUS) && !log.trim()) continue;
70
+ // always append the full original log after the explanation: the explanation picks only `ERROR: n:m:` lines and drops warnings and others; the file header promised "no line of the original error is lost"
71
+ const why = explainShaderError(stage, gl.getShaderSource(sh) || '', log);
72
+ parts.push(why ? `${why}\n[threedog] ${stage} shader log:\n${log.trim()}` : `[threedog] ${stage} shader: ${log.trim()}`);
73
+ }
74
+ const link = gl.getProgramInfoLog(program) || '';
75
+ console.error(parts.join('\n') + (link.trim() ? `\n[threedog] program link: ${link.trim()}` : '') + '\n(raw anchors and slots: render/slots.js)');
76
+ };
77
+ }
78
+
79
+ // ---------- WebGPURenderer (docs/plans/2026-11-03-webgpu-phase2.md §4 "shader error location") ----------
80
+ // What exists there: a tsl patch's own JS error is caught where it runs and named `patch 'x' (slot y)` with the game's line on top of its stack
81
+ // (render/fx/patchNodes.tsl.js run()); an error while three builds the node a patch or a post effect returned carries the same name
82
+ // (render/fx/nodeErrors.tsl.js), and three's 'TSL:' build-error log gets one more line naming the material and mesh. A compile error comes later, from code three generated from nodes, and that code has no patch markers
83
+ // (TSL writes it; there is nothing to put them in), so the line cannot be mapped to a patch. What this names instead: the material and mesh
84
+ // whose program failed and the patches on it. Two hooks reach it: on the WebGL2 backend three calls debug.onShaderError like WebGLRenderer;
85
+ // on the WebGPU backend there is no callback, three reports pipeline failures (popErrorScope + getCompilationInfo, with WGSL line excerpts)
86
+ // through its console function only, so the engine wraps that once (setConsoleFunction, a game's own wrapper still runs) and adds one line.
87
+ // Not covered: errors the device raises outside a pipeline build (renderer.onError, three's uncaptured-error handler) keep three's own message.
88
+ const NODE_HINT = "node programs have no patch markers (TSL writes them): take the listed patches off one at a time (applyEffects), or read the program with renderer.debug.getShaderAsync(scene, camera, mesh); a patch's own JS error is named patch 'x' (slot y) where it runs";
89
+
90
+ /** "MeshLambertNodeMaterial 'leaf' (#12) on Mesh 'tree'; patches on it: wind, clouds" @param {any} ro a three RenderObject */
91
+ function nodeOwner(ro) {
92
+ const m = ro.material, o = ro.object, p = materialPatches(m);
93
+ return `${m.type}${m.name ? ` '${m.name}'` : ''} (#${m.id}) on ${o?.type ?? 'object'} '${o?.name || '(unnamed)'}'; patches on it: ${p.join(', ') || 'none'}`;
94
+ }
95
+
96
+ /**
97
+ * The explanation for one three console message, or '' (not a pipeline failure)
98
+ * @internal exported for tests/backend; three reaches it through the console hook
99
+ * @param {string} message
100
+ * @returns {string}
101
+ */
102
+ export function explainPipelineError(message) {
103
+ const m = /Render pipeline creation failed \(renderPipeline_.*_(\d+)\)/.exec(message);
104
+ if (!m) return '';
105
+ const ro = findNodeBuild(x => x.material?.id === +m[1]);
106
+ return `[threedog] WebGPU pipeline failed for ${ro ? nodeOwner(ro) : `material #${m[1]} (not among the recent builds)`}: ${NODE_HINT}. three's WGSL lines follow.`;
107
+ }
108
+
109
+ /** The explanation for three's node build-error log ('THREE.TSL: TypeError: ...', NodeManager), or '' (another message) @param {string} message */
110
+ function explainBuildError(message) {
111
+ if (!/^THREE\.TSL: \w*Error: /.test(message)) return '';
112
+ // three logs right after building the stand-in for the failed one, with the same render object: the newest build is the one that failed
113
+ const ro = findNodeBuild(() => true), named = /\[threedog\] (patch|post effect) '/.test(message);
114
+ return `[threedog] node build failed for ${ro ? nodeOwner(ro) : 'a material not among the recent builds'}; three draws it with a plain NodeMaterial instead (the black or white mesh). `
115
+ + (named ? 'The patch or post effect named above returned the node that failed.'
116
+ : "Not inside a patch's or post effect's node (those are named when they fail): look at the material's own nodes (colorNode, positionNode ...)");
117
+ }
118
+
119
+ let consoleHooked = false;
120
+ /** Wrap three's console function once per page: three's message as before, then the explanation for a pipeline failure */
121
+ function hookThreeConsole() {
122
+ if (consoleHooked) return;
123
+ consoleHooked = true;
124
+ const prev = getConsoleFunction();
125
+ setConsoleFunction((type, message, ...params) => {
126
+ if (prev) prev(type, message, ...params);
127
+ else if (params[0]?.isStackTrace) console[type](params[0].getError(message)); // what three prints when no function is set
128
+ else console[type](message, ...params);
129
+ const why = type === 'error' ? explainPipelineError(String(message)) || explainBuildError(String(message)) : '';
130
+ if (why) console.error(why);
131
+ });
132
+ }
133
+
134
+ /** @param {any} r a WebGPURenderer */
135
+ function nameNodeErrors(r) {
136
+ const d = r.debug;
137
+ if (d && !d.onShaderError) d.onShaderError = (gl, program, vs, fs) => {
138
+ const src = [gl.getShaderSource(vs), gl.getShaderSource(fs)];
139
+ // _nodeBuilderState, not getNodeBuilderState(): reading must never start a build from inside an error report
140
+ const ro = findNodeBuild(x => { const s = x._nodeBuilderState; return !!s && (s.vertexShader === src[0] || s.fragmentShader === src[1]); });
141
+ const logs = [];
142
+ for (const [stage, sh] of /** @type {const} */ ([['vertex', vs], ['fragment', fs]])) {
143
+ const log = gl.getShaderInfoLog(sh) || '';
144
+ if (gl.getShaderParameter(sh, gl.COMPILE_STATUS) && !log.trim()) continue;
145
+ const lines = (gl.getShaderSource(sh) || '').split('\n');
146
+ const rows = log.split('\n').filter(l => /ERROR:/.test(l)).map(l => { const n = /ERROR:\s*\d+:(\d+):/.exec(l)?.[1]; return n ? `${l.trim()} | ${lines[+n - 1]?.trim() ?? ''}` : l.trim(); });
147
+ logs.push(`[threedog] ${stage} shader log:\n${rows.join('\n') || log.trim()}`);
148
+ }
149
+ const link = gl.getProgramInfoLog(program) || '';
150
+ console.error(`[threedog] shader error in a node program (WebGPURenderer, WebGL2 backend) for ${ro ? nodeOwner(ro) : 'a material not among the recent builds'}: ${NODE_HINT}\n`
151
+ + logs.join('\n') + (link.trim() ? `\n[threedog] program link: ${link.trim()}` : ''));
152
+ };
153
+ hookThreeConsole();
154
+ }
@@ -0,0 +1,165 @@
1
+ import { codedError } from '../core/errorHints.js';
2
+ // Semantic patch slots. The one table that says where a patch's code goes. A patch names a slot ('position', 'color', 'lighting'...),
3
+ // this table maps the slot to a GLSL injection point on WebGLRenderer (a three.js `#include <chunk>` plus before / after / replace) and to where
4
+ // render/fx/patchNodes.tsl.js puts the patch's tsl on a NodeMaterial (`node`: { prop } a node property, { setup } code run inside that three
5
+ // setup method, null = WebGL only). patchNodes.tsl.js builds its slot map from this column, so the table cannot promise a mapping the code lacks.
6
+ // nodeMeaning: what is different on the NodeMaterial side, said here once (it is printed in the recipe 43 table).
7
+ // Why one table: patches, built-in effects (wind / cloud shadow / season / detail / lighting / CSM), error messages and the recipe 43 table all read from here,
8
+ // the WebGPU route only needed the node column and no patch changed; the anchor strings appear once here, not scattered across effects each writing their own.
9
+ // Raw anchors (`glsl: { vertex|fragment: { <chunk>: code } }`) stay as the expert exit: plain three.js knowledge, WebGL only.
10
+ /** @typedef {{ stage: 'vertex' | 'fragment', anchor: string, at: 'after' | 'before' | 'replace', shadowOnly?: boolean, scope: string, meaning: string,
11
+ * node: { prop?: string, setup?: string } | null, nodeMeaning?: string }} Slot */
12
+
13
+ /** @type {Record<string, Slot>} */
14
+ export const SLOTS = {
15
+ position: { stage: 'vertex', anchor: 'begin_vertex', at: 'after', node: { prop: 'positionNode' },
16
+ scope: 'transformed (vec3, object space, write), position, normal, uv',
17
+ meaning: 'move vertices in object space, before skinning / instancing / the model matrix',
18
+ nodeMeaning: "the same place (the engine runs the chain before three's instancing; a game's own positionNode still applies after it)" },
19
+ shadowPosition: { stage: 'vertex', anchor: 'begin_vertex', at: 'after', shadowOnly: true, node: { prop: 'castShadowPositionNode' },
20
+ scope: 'transformed (vec3, object space, write), position',
21
+ meaning: 'vertex code for the shadow passes only (depth / point-light distance), replacing this patch\'s position code there' },
22
+ clipPosition: { stage: 'vertex', anchor: 'project_vertex', at: 'after', node: { prop: 'vertexNode' },
23
+ scope: 'transformed, mvPosition (view space), gl_Position (clip space, write)',
24
+ meaning: 'after projection: snap or offset on screen, or write world-space varyings' },
25
+ map: { stage: 'fragment', anchor: 'map_fragment', at: 'after', node: { prop: 'colorNode' },
26
+ scope: 'diffuseColor (vec4, write; the map applied, vertex colors not yet)',
27
+ meaning: 'the base color / texture, before vertex colors and every color patch' },
28
+ color: { stage: 'fragment', anchor: 'color_fragment', at: 'after', node: { setup: 'setupDiffuseColor' },
29
+ scope: 'diffuseColor (vec4, write; map and vertex colors already applied), vUv when the material has a map',
30
+ meaning: 'the surface (diffuse) color before lighting' },
31
+ normal: { stage: 'fragment', anchor: 'normal_fragment_maps', at: 'after', node: { setup: 'setupNormal' },
32
+ scope: 'normal (vec3, view space, write), faceDirection, vViewPosition',
33
+ meaning: 'the shading normal (bump, detail) after normal / bump maps' },
34
+ roughness: { stage: 'fragment', anchor: 'roughnessmap_fragment', at: 'after', node: { prop: 'roughnessNode' },
35
+ scope: 'roughnessFactor (float, write); MeshStandard / MeshPhysical only',
36
+ meaning: 'roughness after the roughness map' },
37
+ emissive: { stage: 'fragment', anchor: 'emissivemap_fragment', at: 'after', node: { prop: 'emissiveNode' },
38
+ scope: 'totalEmissiveRadiance (vec3, write), diffuseColor',
39
+ meaning: 'emitted light after the emissive map' },
40
+ lightsPars: { stage: 'fragment', anchor: 'shadowmap_pars_fragment', at: 'after', node: null,
41
+ nodeMeaning: "TSL has no declaration area: the light's direction and shadow come to the lighting slot's direct(light, ctx) hook",
42
+ scope: 'declarations; three\'s light structs, getShadow() and directionalLights[] are already declared',
43
+ meaning: 'functions that call three\'s light / shadow helpers (pars goes before them)' },
44
+ lightingModel: { stage: 'fragment', anchor: 'lights_fragment_begin', at: 'replace', node: null,
45
+ nodeMeaning: "use the lighting slot's hooks { start, light, direct, after }, or a NodeMaterial with your own setupLightingModel",
46
+ scope: 'geometryPosition, geometryNormal, material, reflectedLight; your code replaces three\'s light loop',
47
+ meaning: 'replace how lights are summed (one patch per material may take it)' },
48
+ lighting: { stage: 'fragment', anchor: 'lights_fragment_end', at: 'after', node: { setup: 'setupLightingModel' },
49
+ scope: 'reflectedLight.directDiffuse / directSpecular / indirectDiffuse (write), normal, diffuseColor, vViewPosition',
50
+ meaning: 'after lights are summed: cloud shadows, wrap, shadow tint, rim',
51
+ nodeMeaning: "hooks { start, light, direct, after }: light(light, ctx) returns a new color for one light before three lights the surface with it (what GLSL does by wrapping three's light info in lightsPars), direct(light, ctx) sees each light in three's loop and adds to its own sums, which join the summed light at the patch's place in the list, then its after() runs: the same order as WebGL" },
52
+ output: { stage: 'fragment', anchor: 'opaque_fragment', at: 'before', node: { setup: 'setupOutput' },
53
+ scope: 'outgoingLight (vec3, write), diffuseColor.a',
54
+ meaning: 'the final lit color, before fog and tone mapping' },
55
+ // fog as two slots, like lightsPars / lightingModel: functions cannot sit inside main(), and they must come after three's fog uniforms
56
+ // (declared in fog_pars_fragment), which the top-of-shader pars precedes. The sky's custom fog kinds and look.fog's hook go through these
57
+ // (modules/sky/fog.js) instead of rewriting THREE.ShaderChunk.fog_* for the whole page
58
+ fogPars: { stage: 'fragment', anchor: 'fog_pars_fragment', at: 'after', node: null,
59
+ nodeMeaning: 'fog on WebGPU is scene.fogNode (the sky fog kinds and look.fog hooks have a tsl form)',
60
+ scope: 'declarations; fogColor and fogNear / fogFar or fogDensity are already declared (inside #ifdef USE_FOG)',
61
+ meaning: 'fog functions that read three\'s fog uniforms (wrap them in #ifdef USE_FOG)' },
62
+ fog: { stage: 'fragment', anchor: 'fog_fragment', at: 'replace', node: null,
63
+ nodeMeaning: 'fog on WebGPU is scene.fogNode (the sky fog kinds and look.fog hooks have a tsl form)',
64
+ scope: 'gl_FragColor (write, tone mapped already), fogColor, vFogDepth, fogNear / fogFar or fogDensity (inside #ifdef USE_FOG)',
65
+ meaning: 'replace how fog mixes into the final color (one patch per material may take it)' },
66
+ };
67
+ export const SLOT_NAMES = Object.keys(SLOTS);
68
+ /** The lighting slot's hook names on the TSL side (render/fx/patchNodes.tsl.js) */
69
+ export const LIGHT_HOOKS = ['start', 'light', 'direct', 'after'];
70
+ /** Slots a patch's tsl can use (the node column is not null) */
71
+ const NODE_SLOTS = SLOT_NAMES.filter(n => SLOTS[n].node);
72
+
73
+ const isObj = v => v != null && typeof v === 'object' && !Array.isArray(v);
74
+ /** Whether a patch uses the slot form (slot: / glsl keyed by slot names) rather than raw anchors (glsl: { vertex, fragment }) */
75
+ const slotForm = p => p.slot != null || typeof p.glsl === 'string' || (isObj(p.glsl) && !('vertex' in p.glsl) && !('fragment' in p.glsl));
76
+ const EXIT = "or the raw-anchor exit glsl: { vertex|fragment: { <three.js chunk>: code } } (WebGL only)";
77
+
78
+ /** Marker comments around injected code, so a compile error can be traced back to the patch and slot (render/shaderErrors.js) */
79
+ const mark = (patch, slot, code) => `// threedog:begin patch=${patch} slot=${slot}\n${code}\n// threedog:end`;
80
+
81
+ /**
82
+ * Turn a slot-form patch into the raw-anchor form patches.js applies (one internal representation, so shadows, conflicts and
83
+ * cacheKey checks work the same for both). Raw-form patches come back with their code marked (slot=<chunk>). Throws on an unknown slot.
84
+ * { name, slot: 'color', glsl: 'code', pars? } one slot
85
+ * { name, glsl: { position: 'code', color: 'code' }, pars? } several slots
86
+ * pars: declarations at the top of every stage the patch touches, or { vertex, fragment } to place them per stage.
87
+ * @internal patches.js
88
+ * @param {any} p
89
+ * @returns {any} a new patch object (p itself is not changed)
90
+ */
91
+ export function toAnchors(p) {
92
+ if (!p || typeof p !== 'object') return p;
93
+ if (p.tsl != null) p = { ...p, tsl: tslSlots(p) };
94
+ // a TSL-only patch has no GLSL to place: it drops slot / pars like the slot form does and keeps tsl (NodeMaterials only)
95
+ if (p.tsl != null && p.glsl == null) { const { slot, pars, ...rest } = p; return rest; }
96
+ if (!slotForm(p)) {
97
+ if (p.pars !== undefined) throw codedError('shader-patch', `[threedog] patch '${p.name}': top-level pars goes with slot names; in the raw-anchor form put it at glsl.vertex.pars / glsl.fragment.pars`);
98
+ if (p.glsl == null) return p;
99
+ const glsl = {};
100
+ for (const st of ['vertex', 'fragment']) if (p.glsl[st]) {
101
+ glsl[st] = {};
102
+ for (const [k, c] of Object.entries(p.glsl[st])) glsl[st][k] = k === 'pars' ? c : typeof c === 'string' ? mark(p.name, k, c)
103
+ : { ...c, ...(c.before ? { before: mark(p.name, k, c.before) } : {}), ...(c.after ? { after: mark(p.name, k, c.after) } : {}), ...(c.replace != null ? { replace: mark(p.name, k, c.replace) } : {}) };
104
+ }
105
+ const extra = Object.keys(p.glsl).filter(k => k !== 'vertex' && k !== 'fragment');
106
+ if (extra.length) throw codedError('shader-patch', `[threedog] patch '${p.name}' mixes raw stages (vertex / fragment) with '${extra.join("', '")}'; use slot names only: ${SLOT_NAMES.join(' | ')}, ${EXIT}`);
107
+ return { ...p, glsl };
108
+ }
109
+ /** @type {Record<string, string>} */
110
+ let bySlot;
111
+ if (p.slot != null) {
112
+ if (typeof p.glsl !== 'string') throw codedError('shader-patch', `[threedog] patch '${p.name}' names slot '${p.slot}', so glsl is that slot's code as a string; for several slots write glsl: { ${SLOT_NAMES[0]}: '...', color: '...' }`);
113
+ bySlot = { [p.slot]: p.glsl };
114
+ } else if (typeof p.glsl === 'string') throw codedError('shader-patch', `[threedog] patch '${p.name}' has glsl code but no slot; add slot: ${SLOT_NAMES.join(' | ')}, ${EXIT}`);
115
+ else bySlot = p.glsl;
116
+ const glsl = { vertex: {}, fragment: {} }, shadow = {}, used = new Set();
117
+ for (const [name, code] of Object.entries(bySlot)) {
118
+ const s = SLOTS[name];
119
+ if (!s) throw codedError('shader-patch', `[threedog] patch '${p.name}': unknown slot '${name}'; use ${SLOT_NAMES.join(' | ')}, ${EXIT}`);
120
+ if (typeof code !== 'string') throw codedError('shader-patch', `[threedog] patch '${p.name}' slot '${name}' must be GLSL code as a string; got ${typeof code}`);
121
+ const marked = mark(p.name, name, code);
122
+ if (s.shadowOnly) { shadow[s.anchor] = marked; used.add('vertex'); continue; }
123
+ glsl[s.stage][s.anchor] = s.at === 'after' ? marked : { [s.at]: marked };
124
+ used.add(s.stage);
125
+ }
126
+ if (p.pars != null) {
127
+ // pars goes first in each stage: same JSON as the hand-written anchor form { pars, <chunk>: code }, so the cacheKey "same key, same code" check recognizes it as the same piece
128
+ const put = (st, text) => { glsl[st] = { pars: text, ...glsl[st] }; };
129
+ if (typeof p.pars === 'string') for (const st of used) put(st, p.pars);
130
+ else if (isObj(p.pars)) for (const st of /** @type {const} */ (['vertex', 'fragment'])) { if (p.pars[st]) put(st, p.pars[st]); }
131
+ else throw codedError('shader-patch', `[threedog] patch '${p.name}': pars is GLSL declarations as a string, or { vertex, fragment }`);
132
+ }
133
+ const { slot, pars, ...rest } = p;
134
+ const out = { ...rest, glsl: { ...(Object.keys(glsl.vertex).length ? { vertex: glsl.vertex } : {}), ...(Object.keys(glsl.fragment).length ? { fragment: glsl.fragment } : {}) } };
135
+ // shadowPosition: code only for the depth / distance materials (patches.js shadowMaterial), so the patch counts as moving its shadow
136
+ if (Object.keys(shadow).length) { out.shadowVertex = shadow; out.shadow = true; }
137
+ return out;
138
+ }
139
+
140
+ /**
141
+ * A patch's tsl field as { slot: code } (WebGPU route, render/fx/patchNodes.tsl.js applies it): tsl: (ctx) => node goes to the patch's
142
+ * slot; tsl: { position: fn, color: fn } names several. Throws on an unknown slot, and on lightsPars, which TSL does not have.
143
+ * @param {any} p
144
+ * @returns {Record<string, any>}
145
+ */
146
+ function tslSlots(p) {
147
+ // slot: 'lighting' + tsl: { start, light, direct, after } is that slot's hook object, not a slot map (no slot has those names)
148
+ const hooks = isObj(p.tsl) && p.slot != null && Object.keys(p.tsl).length > 0 && Object.keys(p.tsl).every(k => LIGHT_HOOKS.includes(k));
149
+ const by = typeof p.tsl === 'function' || hooks ? (p.slot != null ? { [p.slot]: p.tsl } : null) : isObj(p.tsl) ? p.tsl : undefined;
150
+ if (by === null) throw codedError('shader-patch', `[threedog] patch '${p.name}' has a tsl function but no slot; add slot: ${SLOT_NAMES.join(' | ')}, or write tsl: { <slot>: (ctx) => node }`);
151
+ if (by === undefined) throw codedError('shader-patch', `[threedog] patch '${p.name}': tsl is (ctx) => node with slot:, or { <slot>: (ctx) => node }; got ${typeof p.tsl}`);
152
+ for (const name of Object.keys(by)) {
153
+ // TSL has no declaration area: the sun direction and shadow value lightsPars code reads come to the lighting slot's direct() hook instead
154
+ if (name === 'lightsPars') throw codedError('shader-patch', `[threedog] patch '${p.name}': slot 'lightsPars' does not exist on WebGPU (TSL has no declaration area); read the light's direction and shadow in the lighting slot's direct hook: tsl: { lighting: { direct(light, ctx) { ... }, after(ctx) { ... } } }`);
155
+ if (!SLOTS[name]) throw codedError('shader-patch', `[threedog] patch '${p.name}': unknown tsl slot '${name}'; use ${NODE_SLOTS.join(' | ')}`);
156
+ if (!SLOTS[name].node) throw codedError('shader-patch', `[threedog] patch '${p.name}': slot '${name}' is WebGL only (${SLOTS[name].nodeMeaning}); tsl slots: ${NODE_SLOTS.join(' | ')}`);
157
+ }
158
+ return by;
159
+ }
160
+
161
+ /** The node column as text: the property, the setup method the code runs in, or WebGL only @param {Slot} s */
162
+ const nodeText = s => !s.node ? 'WebGL only' : s.node.prop ? `\`${s.node.prop}\`` : `inside \`${s.node.setup}\``;
163
+ /** The slot table as a markdown table; recipe 43 holds a copy that threedog check R42 compares (it imports this) @internal */
164
+ export const slotTable = () => ['| slot | GLSL (WebGL) | WebGPU (NodeMaterial) | in scope | meaning |', '|---|---|---|---|---|',
165
+ ...SLOT_NAMES.map(n => { const s = SLOTS[n]; return `| \`${n}\` | ${s.at} \`${s.anchor}\`${s.shadowOnly ? ' (shadow passes)' : ''} | ${nodeText(s)} | ${s.scope} | ${s.meaning}${s.nodeMeaning ? `; WebGPU: ${s.nodeMeaning}` : ''} |`; })].join('\n');