threedog 1.1.0 → 1.3.0

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