threedog 2.2.0 → 2.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 (197) hide show
  1. package/CHANGELOG.md +36 -0
  2. package/README.md +4 -4
  3. package/core/assets/Animator.js +66 -12
  4. package/core/assets/ik.js +144 -18
  5. package/core/assets/maskLayer.js +377 -0
  6. package/core/assets/rootMotion.js +148 -0
  7. package/core/audio/Audio.js +100 -4
  8. package/core/base/errorCodes.js +6 -369
  9. package/core/base/errorCodesModules.js +378 -0
  10. package/core/engine/Engine.js +8 -5
  11. package/core/engine/Loading.js +8 -4
  12. package/core/engine/copies.js +1 -1
  13. package/core/engine/headlessLoad.js +15 -4
  14. package/core/engine/lifecycle.js +1 -0
  15. package/core/engine/loop.js +23 -3
  16. package/core/engine/moduleSlots.js +3 -7
  17. package/core/engine/modules.js +30 -58
  18. package/core/engine/startup.js +3 -3
  19. package/core/input/Input.js +7 -3
  20. package/core/input/inputContext.js +3 -2
  21. package/core/input/inputSeat.js +1 -1
  22. package/core/inspect/DebugOverrides.js +1 -1
  23. package/core/inspect/Describe.js +7 -2
  24. package/core/inspect/describeRender.js +4 -1
  25. package/core/inspect/describeText.js +2 -2
  26. package/core/inspect/metadata.generated.js +380 -74
  27. package/core/inspect/pictureMenu.js +2 -0
  28. package/core/inspect/pictureWriters.js +4 -3
  29. package/core/ops/Ops.js +9 -3
  30. package/core/ops/actor.js +10 -0
  31. package/core/ops/control.js +17 -6
  32. package/core/ops/holds.js +1 -1
  33. package/core/ops/opsAtomic.js +6 -1
  34. package/core/ops/opsGuard.js +2 -2
  35. package/core/ops/owned.js +37 -11
  36. package/core/ops/sharedPoint.js +5 -1
  37. package/core/ops/stacks.js +30 -7
  38. package/core/saves/Saves.js +0 -2
  39. package/core/saves/saveApply.js +7 -7
  40. package/core/saves/session.js +6 -3
  41. package/core/saves/stateReplace.js +71 -41
  42. package/core/scene/Rays.js +74 -26
  43. package/core/scene/canvasBox.js +9 -0
  44. package/core/scene/gameLights.js +19 -11
  45. package/core/scene/sceneDelta.js +8 -4
  46. package/core/scene/sceneMethods.js +2 -1
  47. package/core/stream/chunkStream.js +21 -0
  48. package/core/stream/dirtyWatch.js +37 -0
  49. package/core/time/skip.js +9 -6
  50. package/core/time/time.js +72 -18
  51. package/docs/AI.md +22 -21
  52. package/docs/API.md +5 -4
  53. package/docs/CODEMAP.md +16 -10
  54. package/docs/COMMANDS.md +5 -5
  55. package/docs/CONVENTIONS.md +9 -25
  56. package/docs/api/ambience.md +1 -0
  57. package/docs/api/assets.md +10 -3
  58. package/docs/api/audio.md +5 -3
  59. package/docs/api/decals.md +16 -0
  60. package/docs/api/engine.md +1 -0
  61. package/docs/api/tools.md +3 -1
  62. package/docs/api/water.md +3 -0
  63. package/docs/recipes/09-materials-lights-models.md +15 -1
  64. package/docs/recipes/13-animation.md +51 -10
  65. package/docs/recipes/16-dev-bridge.md +4 -4
  66. package/docs/recipes/31-audio.md +15 -9
  67. package/docs/recipes/34-environment-lighting.md +11 -1
  68. package/docs/recipes/44-water-weather-hooks.md +1 -0
  69. package/examples/action/.threedog/content-index.json +1 -0
  70. package/examples/perf-island/.threedog/content-index.json +1 -0
  71. package/examples/plain-picture/.threedog/content-index.json +1 -0
  72. package/examples/rc2d/.threedog/content-index.json +1 -0
  73. package/examples/styletest/.threedog/content-index.json +1 -0
  74. package/examples/techniques/outlines-and-rim/main.js +1 -1
  75. package/examples/techniques/procedural-surface/main.js +1 -1
  76. package/examples/techniques/stylized-shading/main.js +1 -1
  77. package/examples/webgpu-tsl/.threedog/content-index.json +1 -0
  78. package/examples/world/.threedog/content-index.json +1 -0
  79. package/index.d.ts +6 -2
  80. package/index.js +3 -2
  81. package/llms.txt +11 -10
  82. package/modules/ambience/Ambience.js +97 -15
  83. package/modules/camera/common.js +18 -12
  84. package/modules/characters/Character.js +30 -3
  85. package/modules/characters/NPC.js +2 -5
  86. package/modules/characters/astar.js +45 -14
  87. package/modules/characters/movers/rapier.js +53 -41
  88. package/modules/characters/movers/simple.js +37 -24
  89. package/modules/characters/npcView.js +2 -2
  90. package/modules/characters/pathAsync.js +3 -3
  91. package/modules/collision/contract.js +2 -2
  92. package/modules/content/index.js +3 -0
  93. package/modules/content/models.js +11 -4
  94. package/modules/content/templates.js +11 -11
  95. package/modules/debug/DebugPanel.js +1 -0
  96. package/modules/decals/Decals.js +393 -0
  97. package/modules/decals/index.js +1 -0
  98. package/modules/gameplay/Container.js +2 -0
  99. package/modules/gameplay/Containers.js +17 -3
  100. package/modules/gameplay/Dialogue.js +1 -1
  101. package/modules/gameplay/Interactions.js +7 -6
  102. package/modules/gameplay/Inventory.js +5 -1
  103. package/modules/gameplay/Quests.js +4 -3
  104. package/modules/gameplay/inventoryOps.js +2 -2
  105. package/modules/gameplay/pickups.js +32 -12
  106. package/modules/gameplay/questSave.js +2 -2
  107. package/modules/grid/index.js +8 -2
  108. package/modules/hud/index.js +1 -1
  109. package/modules/level/heightfield.js +1 -0
  110. package/modules/level/index.js +3 -2
  111. package/modules/level/nodes.js +2 -1
  112. package/modules/lights/index.js +27 -4
  113. package/modules/lights/slots.js +33 -16
  114. package/modules/nav/contract.js +4 -4
  115. package/modules/nav/index.js +6 -2
  116. package/modules/net/Client.js +24 -11
  117. package/modules/net/Host.js +73 -20
  118. package/modules/net/index.js +33 -21
  119. package/modules/net/sync.js +38 -8
  120. package/modules/net/transports.js +7 -3
  121. package/modules/particles/Particles.js +11 -4
  122. package/modules/particles/contract.js +6 -6
  123. package/modules/particles/effect.js +0 -1
  124. package/modules/rigid/RigidBodies.js +69 -57
  125. package/modules/rigid/Vehicles.js +8 -7
  126. package/modules/rigid/ragdoll.js +4 -6
  127. package/modules/rigid/rapierCompat.js +90 -0
  128. package/modules/rigid/sync.js +2 -5
  129. package/modules/settings/Settings.js +10 -4
  130. package/modules/sky/Sky.js +10 -2
  131. package/modules/sky/environment.js +29 -13
  132. package/modules/sky/frame.js +2 -2
  133. package/modules/sky/shader.js +5 -2
  134. package/modules/sky/skyModule.js +2 -2
  135. package/modules/swarm/Swarm.js +3 -2
  136. package/modules/swarm/grid.js +12 -7
  137. package/modules/terrain/ChunkManager.js +16 -26
  138. package/modules/triggers/index.js +5 -6
  139. package/modules/vegetation/draw.js +62 -26
  140. package/modules/vegetation/groundChunks.js +8 -22
  141. package/modules/water/Water.js +152 -24
  142. package/modules/water/surface.js +43 -20
  143. package/modules/weather/weatherDraw.js +4 -1
  144. package/modules/world/World.js +21 -2
  145. package/modules/world/index.js +5 -0
  146. package/modules/world/persist.js +1 -0
  147. package/modules/world/records.js +3 -1
  148. package/modules/world/sim.js +3 -2
  149. package/modules/world/simFar.js +4 -2
  150. package/modules/world/state.js +7 -1
  151. package/package.json +2 -2
  152. package/presets.js +30 -0
  153. package/render/PostFX.js +24 -17
  154. package/render/backend.js +72 -31
  155. package/render/cascades.js +25 -14
  156. package/render/cascades.tsl.js +32 -21
  157. package/render/fogLook.js +2 -1
  158. package/render/fx/detail.tsl.js +3 -0
  159. package/render/fx/library.tsl.js +1 -1
  160. package/render/fx/particles.tsl.js +4 -18
  161. package/render/fx/pcss.tsl.js +2 -2
  162. package/render/fx/postWebGPU.tsl.js +47 -25
  163. package/render/fx/sky.tsl.js +6 -18
  164. package/render/fx/uniforms.tsl.js +16 -0
  165. package/render/fx/water.tsl.js +24 -5
  166. package/render/fxNumbers.js +2 -0
  167. package/render/impostor.tsl.js +10 -6
  168. package/render/lights.js +6 -6
  169. package/render/occlusion.js +17 -6
  170. package/render/patches.js +40 -28
  171. package/render/postWebGL.js +6 -4
  172. package/render/reflectionProbes.js +302 -0
  173. package/render/shaderErrors.js +18 -8
  174. package/render/shadowCache.tsl.js +10 -5
  175. package/render/shadows.js +70 -49
  176. package/render/threeCompat.js +166 -0
  177. package/types/core.d.ts +33 -3
  178. package/types/gameplay.d.ts +80 -0
  179. package/types/generated/core/audio/Audio.d.ts +18 -1
  180. package/types/generated/core/ops/Ops.d.ts +2 -1
  181. package/types/generated/core/ops/control.d.ts +7 -3
  182. package/types/generated/core/saves/session.d.ts +4 -1
  183. package/types/generated/modules/ambience/Ambience.d.ts +6 -0
  184. package/types/generated/modules/debug/DebugPanel.d.ts +1 -0
  185. package/types/generated/modules/grid/index.d.ts +27 -3
  186. package/types/generated/modules/net/index.d.ts +8 -3
  187. package/types/generated/modules/sky/Sky.d.ts +1 -0
  188. package/types/generated/modules/water/Water.d.ts +15 -0
  189. package/types/generated/modules/world/index.d.ts +5 -0
  190. package/types/generated/render/patches.d.ts +5 -0
  191. package/types/physics.d.ts +66 -9
  192. package/types/tsl.d.ts +2 -0
  193. package/types/world.d.ts +2 -0
  194. package/ui/Parts.js +3 -2
  195. package/docs/MIGRATING-0.7.md +0 -39
  196. package/docs/MIGRATING-0.8.md +0 -171
  197. package/modules/rigid/refresh.js +0 -10
package/render/patches.js CHANGED
@@ -115,7 +115,11 @@ function clash(list, p, fresh) { // fresh: the CODE keys this call adds, so a
115
115
  return '';
116
116
  }
117
117
 
118
- const LISTS = new WeakMap(); // material -> its patches (not userData: that gets JSON-cloned and exported to glTF)
118
+ // Single per-material patch record (not userData: that gets JSON-cloned and exported to glTF): { list, shadows }
119
+ const MAT_STATE = new WeakMap();
120
+ const stateOf = m => MAT_STATE.get(m);
121
+ const ensureState = m => { let s = MAT_STATE.get(m); if (!s) MAT_STATE.set(m, s = { list: [], shadows: null }); return s; };
122
+ const listOf = m => MAT_STATE.get(m)?.list;
119
123
 
120
124
  // A list read back from a material (engine.<module>.patches) comes through applyEffects a second time: already placed, it stays as it is.
121
125
  // Placing it again would wrap its code in a second marker, and the 'same cacheKey, different code' check would then reject the module's own patch.
@@ -196,11 +200,11 @@ function apply(shader, list, m, renderer) {
196
200
  */
197
201
  export function patchMaterial(material, patches, { strict = true } = {}) {
198
202
  const m = /** @type {any} */ (material);
199
- let list = LISTS.get(m);
203
+ let list = listOf(m);
200
204
  // NodeMaterials take no onBeforeCompile / GLSL program key (three keys them by their nodes): the list alone, turned into nodes below
201
- if (!list && m.isNodeMaterial) LISTS.set(m, list = []);
205
+ if (!list && m.isNodeMaterial) list = ensureState(m).list;
202
206
  if (!list) {
203
- LISTS.set(m, list = []);
207
+ list = ensureState(m).list;
204
208
  // 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).
205
209
  // 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;
206
210
  // 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.
@@ -256,7 +260,7 @@ export function patchMaterial(material, patches, { strict = true } = {}) {
256
260
 
257
261
  /** The TSL side of a classic material: its nodes follow the list (rebuilt on the next read) when threedog/tsl is loaded; WebGL games skip it */
258
262
  function changedClassic(m) {
259
- webgpuPartOrNull('nodePatches')?.invalidate(m, () => LISTS.get(m) ?? []);
263
+ webgpuPartOrNull('nodePatches')?.invalidate(m, () => listOf(m) ?? []);
260
264
  if (!Object.hasOwn(m, NODE_KEY)) Object.defineProperty(m, NODE_KEY, { configurable: true, enumerable: true, get: () => nodeKey(m) });
261
265
  }
262
266
 
@@ -275,7 +279,7 @@ const idOf = o => { let i = IDS.get(o); if (i === undefined) IDS.set(o, i = ++ne
275
279
  const tslFunctions = t => typeof t === 'function' ? [t] : t && typeof t === 'object' ? Object.values(t).flatMap(tslFunctions) : [];
276
280
  function nodeKey(m) {
277
281
  const ids = [];
278
- for (const p of LISTS.get(m) ?? []) {
282
+ for (const p of listOf(m) ?? []) {
279
283
  for (const u in p.uniforms ?? {}) if (!engineUniformName(p.uniforms[u])) ids.push(idOf(p.uniforms[u]));
280
284
  for (const f of tslFunctions(p.tsl)) ids.push(idOf(f));
281
285
  }
@@ -333,7 +337,7 @@ export function dressNodeTwins(r) {
333
337
  lib.fromMaterial = material => {
334
338
  const twin = from(material);
335
339
  if (!twin || twin === material) return twin;
336
- const list = LISTS.get(material) ?? [];
340
+ const list = listOf(material) ?? [];
337
341
  // every twin goes through dress (Lambert / Phong get scene.environment's diffuse light as on WebGL); only a patched one needs threedog/tsl
338
342
  const part = list.length ? nodePatches(material) : webgpuPartOrNull('nodePatches');
339
343
  return part ? part.dress(twin, material, list) : twin;
@@ -346,7 +350,7 @@ notePatch('node-twin-dress', "renderer.library.fromMaterial of a WebGPURenderer:
346
350
  // start() on WebGPURenderer, and each object added later: a classic material whose patches cannot all run there (a GLSL-only patch, a slot
347
351
  // with no node place) is named instead of drawing without its picture
348
352
  addWebGPURule(m => {
349
- const list = !m.isNodeMaterial ? LISTS.get(m) : null;
353
+ const list = !m.isNodeMaterial ? listOf(m) : null;
350
354
  return list?.length ? webgpuPartOrNull('nodePatches')?.problem(m, list) ?? null : null;
351
355
  });
352
356
 
@@ -381,7 +385,7 @@ function withProviders(patches, list) {
381
385
  * @returns {string[]}
382
386
  * @experimental
383
387
  */
384
- export function materialPatches(material) { return (LISTS.get(material) || []).map(p => p.name); }
388
+ export function materialPatches(material) { return (listOf(material) || []).map(p => p.name); }
385
389
 
386
390
  /**
387
391
  * The patches on a material with the slots (or raw anchors) their code goes into, read from the threedog:begin markers (engine.inspect.materials)
@@ -390,7 +394,7 @@ export function materialPatches(material) { return (LISTS.get(material) || []).m
390
394
  * @returns {{ name: string, slots: string[] }[]}
391
395
  */
392
396
  export function materialPatchSlots(material) {
393
- return (LISTS.get(material) || []).map(p => ({ name: p.name, slots: [...new Set([...JSON.stringify(p.glsl ?? {}).matchAll(/threedog:begin patch=\S+ slot=([\w.-]+)/g)].map(m => m[1]))] }));
397
+ return (listOf(material) || []).map(p => ({ name: p.name, slots: [...new Set([...JSON.stringify(p.glsl ?? {}).matchAll(/threedog:begin patch=\S+ slot=([\w.-]+)/g)].map(m => m[1]))] }));
394
398
  }
395
399
 
396
400
  let hotRev = 0;
@@ -414,13 +418,13 @@ export function replacePatchCode(materials, old, neu) {
414
418
  for (const kk of Object.keys(v)) if (kk !== 'uniforms' && swap(v, kk, depth + 1)) hit = true;
415
419
  return hit;
416
420
  };
417
- for (const m of materials) for (const p of LISTS.get(m) || []) {
421
+ for (const m of materials) for (const p of listOf(m) || []) {
418
422
  if (seen.has(p)) continue;
419
423
  seen.add(p);
420
424
  const hit = ['glsl', 'pars', 'shadowVertex'].map(k => swap(p, k)).some(Boolean);
421
425
  if (hit) { p.cacheKey = `${String(p.cacheKey ?? '').replace(/~hot\d+$/, '')}~hot${++hotRev}`; changed.add(p); }
422
426
  }
423
- const out = materials.filter(m => (LISTS.get(m) || []).some(p => changed.has(p)));
427
+ const out = materials.filter(m => (listOf(m) || []).some(p => changed.has(p)));
424
428
  for (const m of out) { dropShadow(m); m.needsUpdate = true; if (!(/** @type {any} */ (m).isNodeMaterial)) changedClassic(m); }
425
429
  return out;
426
430
  }
@@ -430,7 +434,7 @@ export function replacePatchCode(materials, old, neu) {
430
434
  * @param {Material} material
431
435
  * @returns {ShaderPatch[]}
432
436
  */
433
- export function patchesOf(material) { return [...(LISTS.get(material) ?? [])]; }
437
+ export function patchesOf(material) { return [...(listOf(material) ?? [])]; }
434
438
 
435
439
  /**
436
440
  * Take the patch named `name` off a material (no-op when absent); returns the material.
@@ -440,7 +444,7 @@ export function patchesOf(material) { return [...(LISTS.get(material) ?? [])]; }
440
444
  * @returns {Material}
441
445
  */
442
446
  export function unpatchMaterial(material, name) {
443
- const list = LISTS.get(material), i = list ? list.findIndex(p => p.name === name) : -1;
447
+ const list = listOf(material), i = list ? list.findIndex(p => p.name === name) : -1;
444
448
  if (i >= 0) {
445
449
  list.splice(i, 1); dropShadow(material); material.needsUpdate = true;
446
450
  if (/** @type {any} */ (material).isNodeMaterial) nodePatches(material).apply(material, list); else changedClassic(material);
@@ -456,9 +460,7 @@ const NOT_CARRIED = /^(?:is[A-Z]|_)|^(?:id|uuid|version|type|userData|clippingPl
456
460
  /** The game's part under engine wrappers (WRAPPED), else the value itself */
457
461
  const gamePart = v => { while (typeof v === 'function' && v[WRAPPED]) v = v[WRAPPED](); return v; };
458
462
  /**
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
463
+ * Clone a material keeping engine shader patches and instance hooks (`material.clone()` drops them).
462
464
  * @template {Material} M @param {M} from @returns {M}
463
465
  */
464
466
  export function cloneMaterial(from) {
@@ -483,7 +485,7 @@ export function cloneMaterial(from) {
483
485
  * @returns {Material}
484
486
  */
485
487
  export function copyPatches(from, to) {
486
- const list = LISTS.get(from);
488
+ const list = listOf(from);
487
489
  if (!list?.length || from === to) return to;
488
490
  copyTerms(from, to); // the copy carries the cloud / season terms, so a later engine.shaderTerms call reaches it too
489
491
  deriving = true; // already checked on `from`
@@ -510,14 +512,14 @@ export function isEngineMade(m) { return MADE.has(m); }
510
512
 
511
513
  // ---------- shadows follow vertex-moving patches ----------
512
514
  // Depth / distance materials carrying the material's vertex-moving patches; undefined when nothing moves. Cached per material
513
- // and kind; patchMaterial and material.dispose() drop (and dispose) the cached ones, so patches added later are picked up.
514
- const shadowMats = new WeakMap();
515
+ // and kind inside MAT_STATE; patchMaterial and material.dispose() drop (and dispose) the cached ones, so patches added later are picked up.
515
516
  function dropShadow(material) {
516
- const byKind = shadowMats.get(material);
517
- if (byKind) for (const k in byKind) byKind[k]?.dispose();
518
- shadowMats.delete(material);
517
+ const s = stateOf(material);
518
+ if (!s?.shadows) return;
519
+ for (const k in s.shadows) s.shadows[k]?.dispose();
520
+ s.shadows = null;
519
521
  }
520
- const moves = m => !!LISTS.get(m)?.some(p => p.shadow);
522
+ const moves = m => !!listOf(m)?.some(p => p.shadow);
521
523
  /**
522
524
  * Whether the material carries a vertex-moving patch (shadow: true, e.g. wind). Such code reads object space (position.y, the model
523
525
  * origin), so baking these meshes into world space (merging, HLOD proxies) would change how they move.
@@ -526,13 +528,23 @@ const moves = m => !!LISTS.get(m)?.some(p => p.shadow);
526
528
  * @returns {boolean}
527
529
  */
528
530
  export function movesVertices(material) { return [].concat(material).some(moves); }
531
+ /** Keep only vertex-stage TSL slots for a derived depth / distance shadow material so fragment slots (lighting, roughness, color) do not fail on unlit depth twins */
532
+ function shadowTsl(tsl) {
533
+ if (!tsl || typeof tsl !== 'object') return undefined;
534
+ const out = {};
535
+ if (tsl.shadowPosition) out.position = tsl.shadowPosition;
536
+ else if (tsl.position) out.position = tsl.position;
537
+ if (tsl.clipPosition) out.clipPosition = tsl.clipPosition;
538
+ return Object.keys(out).length ? out : undefined;
539
+ }
529
540
  function shadowMaterial(material, kind) {
530
- let byKind = shadowMats.get(material);
531
- if (!byKind) shadowMats.set(material, byKind = {});
541
+ const s = ensureState(material);
542
+ const byKind = (s.shadows ??= {});
532
543
  if (kind in byKind) return byKind[kind];
533
544
  // shadowPosition slot code goes only into the shadow material, replacing the same patch's position code (use when the shadow must differ from the color pass)
534
- const moving = LISTS.get(material).filter(p => p.shadow).map(p => ({ ...p, needs: { data: p.needs?.data }, conflicts: undefined,
535
- glsl: { vertex: p.shadowVertex ? { ...p.glsl?.vertex, ...p.shadowVertex } : p.glsl?.vertex } }));
545
+ const moving = s.list.filter(p => p.shadow).map(p => ({ ...p, needs: { data: p.needs?.data }, conflicts: undefined,
546
+ glsl: p.glsl || p.shadowVertex ? { vertex: p.shadowVertex ? { ...p.glsl?.vertex, ...p.shadowVertex } : p.glsl?.vertex } : undefined,
547
+ tsl: shadowTsl(p.tsl) }));
536
548
  // three copies side, alphaTest, map and clipping from the drawn material onto the depth material on every draw
537
549
  const base = kind === 'depth' ? new THREE.MeshDepthMaterial() : new THREE.MeshDistanceMaterial();
538
550
  deriving = true; // vertex-only copies of patches already checked on the source material
@@ -16,6 +16,7 @@ import { OutputPass } from 'three/addons/postprocessing/OutputPass.js';
16
16
  import { FusedPass, groupFuse, checkDepthOrder } from './fuse.js';
17
17
  import { codedError } from '../core/base/errorHints.js';
18
18
  import { holdShadowRedraw, MSAA_SAMPLES, borrowRenderer } from './backend.js';
19
+ import { syncComposerSize, firstOpaqueObject } from './threeCompat.js';
19
20
  import { notePatch, patchOn } from '../core/scene/threePatches.js';
20
21
 
21
22
  // One FusedPass per group of neighboring fuse effects, kept while the same effects stay grouped (a changed group recompiles once)
@@ -72,8 +73,7 @@ function holdAfterScene(post, pass) {
72
73
  const _css = new THREE.Vector2();
73
74
  function follow(post) {
74
75
  const c = post.composer, r = post.engine.renderer, s = r.getSize(_css), pr = r.getPixelRatio();
75
- if (c._pixelRatio !== pr) c.setPixelRatio(pr);
76
- if (c._width !== s.x || c._height !== s.y) c.setSize(s.x, s.y);
76
+ syncComposerSize(c, s.x, s.y, pr);
77
77
  }
78
78
  /** composer.render with the shadow switch put back afterwards, even when a pass throws */
79
79
  function composerRender(post, dt) {
@@ -111,7 +111,7 @@ function toneBackground(post, draw) {
111
111
  post._toneBg = true;
112
112
  try {
113
113
  draw();
114
- const m = r.renderLists.get(post.engine.scene, 0).opaque[0]?.object;
114
+ const m = firstOpaqueObject(r, post.engine.scene);
115
115
  if (!m || !BG_MATERIALS.includes(m.material?.name) || post._bgMeshes.has(m)) return;
116
116
  post._bgMeshes.add(m);
117
117
  const before = m.onBeforeRender;
@@ -166,7 +166,7 @@ ${was.fog_fragment}
166
166
  };
167
167
  put();
168
168
  notePatch('fog-linear', "three's fog_pars_fragment, tonemapping_fragment and fog_fragment shader chunks: fog is mixed in linear space before the tone curve when drawing to the canvas, as under the composer and on WebGPU (render/postWebGL.js)",
169
- () => { C.tonemapping_fragment = was.tonemapping_fragment; }, { scope: 'page', lost: 'with no effect on, distant fog is mixed after tone mapping in output space: it changes colour when the first effect turns on and leaves a seam against a tone-mapped sky backdrop' });
169
+ () => { C.fog_pars_fragment = was.fog_pars_fragment; C.tonemapping_fragment = was.tonemapping_fragment; C.fog_fragment = was.fog_fragment; }, { scope: 'page', lost: 'with no effect on, distant fog is mixed after tone mapping in output space: it changes colour when the first effect turns on and leaves a seam against a tone-mapped sky backdrop' });
170
170
  }
171
171
 
172
172
  /** Canvas frames without a renderOnce(target) after which an effect-free engine gives the composer targets back */
@@ -219,6 +219,7 @@ export const webglPost = {
219
219
  post._scenePass = new RenderPass(scene, camera);
220
220
  post._output = new OutputPass();
221
221
  }
222
+ post._scenePass.scene = scene;
222
223
  post._scenePass.camera = camera;
223
224
  const c = post.composer, on = post._sorted().filter(e => e.enabled);
224
225
  for (const e of on) if (!e._impl && !e._def.fuse) {
@@ -245,6 +246,7 @@ export const webglPost = {
245
246
  post._bgTex?.dispose(); post._bgTex = null;
246
247
  if (!post.composer) return;
247
248
  post._scenePass.dispose(); post._output.dispose();
249
+ for (const rt of [post.composer.renderTarget1, post.composer.renderTarget2]) rt?.depthTexture?.dispose();
248
250
  post.composer.dispose(); post.composer = null;
249
251
  },
250
252
  sceneTarget(post) {
@@ -0,0 +1,302 @@
1
+ // Local reflection probes (mixed into Engine.prototype): prefiltered PMREM environment captures for bounded zones (rooms, caves, tunnels, courtyards).
2
+ // Unlike scene.environment (one global map for the whole world, making indoor metal reflect outdoor sky) and bakeProbes (diffuse SH only, no specular),
3
+ // each reflection probe captures the scene from `position` into a half-float PMREM texture and assigns it to reflective materials inside `bounds`
4
+ // (tightest volume wins when zones nest; dynamic objects tracked with probe.addTarget(obj) switch zones automatically as they move).
5
+ // Works on both WebGLRenderer and WebGPURenderer, reusing the WebGPU render target across rebakes so materials do not recompile.
6
+ import * as THREE from 'three';
7
+ import { engineOwned } from '../core/scene/things.js';
8
+ import { readParams } from '../core/base/params.js';
9
+ import { codedError } from '../core/base/errorHints.js';
10
+ import { fmt } from '../core/base/validate.js';
11
+ import { vec3 } from '../core/base/math.js';
12
+ import { isWebGPU, webgpuPart, freshFrame, onRendererSwap } from './backend.js';
13
+ import { mats } from './lit.js';
14
+
15
+ const SCHEMA = {
16
+ bounds: { type: 'object', desc: 'THREE.Box3 or { min, max } world volume where this reflection probe applies' },
17
+ position: { type: 'any', optional: true, desc: 'capture origin (default: center of bounds)' },
18
+ resolution: { type: 'int', optional: true, min: 16, max: 512, desc: 'PMREM size in px (default 256, 128 on low tier)' },
19
+ near: { type: 'number', default: 0.1, min: 0.01, desc: 'capture near plane in meters' },
20
+ far: { type: 'number', default: 100, min: 0.2, desc: 'capture far plane in meters' },
21
+ intensity: { type: 'number', default: 1, min: 0, desc: 'multiplier on bound materials envMapIntensity' },
22
+ autoAssign: { type: 'bool', default: true, desc: 'bind static meshes currently inside bounds automatically' },
23
+ include: { type: 'function', optional: true, desc: '(object) => bool: objects returning false are hidden while capturing' },
24
+ owner: { type: 'string', default: 'game', desc: 'who created the probe (describe().render.reflectionProbes)' },
25
+ };
26
+
27
+ const BAD_BOUNDS = 'engine.addReflectionProbe({ bounds }): bounds must be a THREE.Box3 or { min: [x, y, z], max: [x, y, z] } with max >= min on every axis; got {got}';
28
+
29
+ const probeList = e => (e._reflectionProbes ??= new Set());
30
+ const matOrigins = new WeakMap();
31
+ const _center = new THREE.Vector3(), _size = new THREE.Vector3(), _objBox = new THREE.Box3(), _pos = new THREE.Vector3();
32
+
33
+ function readBox(bounds) {
34
+ if (!bounds || typeof bounds !== 'object' || !bounds.min || !bounds.max) {
35
+ throw codedError('probes-option', fmt(BAD_BOUNDS, { got: JSON.stringify(bounds) }));
36
+ }
37
+ const min = vec3(bounds.min), max = vec3(bounds.max);
38
+ 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) {
39
+ throw codedError('probes-option', fmt(BAD_BOUNDS, { got: JSON.stringify({ min, max }) }));
40
+ }
41
+ return new THREE.Box3(min.clone(), max.clone());
42
+ }
43
+
44
+ function volumeOf(box) {
45
+ box.getSize(_size);
46
+ return Math.max(1e-6, _size.x) * Math.max(1e-6, _size.y) * Math.max(1e-6, _size.z);
47
+ }
48
+
49
+ function takesEnv(m) {
50
+ return !!(m && ('envMap' in m) && (m.isMeshStandardMaterial || m.isMeshPhysicalMaterial || m.isMeshLambertMaterial || m.isMeshPhongMaterial
51
+ || m.isMeshStandardNodeMaterial || m.isMeshPhysicalNodeMaterial));
52
+ }
53
+
54
+ function rememberMat(m) {
55
+ if (!matOrigins.has(m)) matOrigins.set(m, { envMap: m.envMap ?? null, intensity: m.envMapIntensity ?? 1, owner: null });
56
+ return matOrigins.get(m);
57
+ }
58
+
59
+ /** Pick the smallest-volume live probe whose bounds contain worldPoint, or null */
60
+ function bestProbeAt(e, worldPoint) {
61
+ const list = e._reflectionProbes;
62
+ if (!list?.size) return null;
63
+ let best = null, bestVol = Infinity;
64
+ for (const p of list) {
65
+ if (!p._dead && p.box.containsPoint(worldPoint)) {
66
+ const v = p._vol;
67
+ if (v < bestVol) { bestVol = v; best = p; }
68
+ }
69
+ }
70
+ return best;
71
+ }
72
+
73
+ function assignMat(m, probe) {
74
+ const orig = rememberMat(m);
75
+ const nextMap = probe ? probe.texture : orig.envMap;
76
+ const nextInt = probe ? orig.intensity * probe.intensity : orig.intensity;
77
+ const changedMap = (m.envMap ?? null) !== nextMap;
78
+ orig.owner = probe;
79
+ m.envMap = nextMap;
80
+ if ('envMapIntensity' in m) m.envMapIntensity = nextInt;
81
+ if (changedMap) m.needsUpdate = true;
82
+ }
83
+
84
+ function reassignAllStatic(e) {
85
+ for (const p of probeList(e)) if (!p._dead && p._auto) p._bindStatic();
86
+ }
87
+
88
+ function drawReflectionProbes(e, scene) {
89
+ const list = [...probeList(e)].filter(p => !p._dead);
90
+ if (!list.length) return () => {};
91
+ const group = engineOwned('debug', new THREE.Group());
92
+ group.name = 'debug:reflectionProbes';
93
+ const sphereGeo = new THREE.SphereGeometry(0.35, 16, 12);
94
+ const disposables = [sphereGeo];
95
+ for (const p of list) {
96
+ const mat = new THREE.MeshStandardMaterial({ color: 0xffffff, metalness: 1, roughness: 0.05, envMap: p.texture, envMapIntensity: p.intensity });
97
+ disposables.push(mat);
98
+ const orb = new THREE.Mesh(sphereGeo, mat);
99
+ orb.position.copy(p.position);
100
+ const helper = new THREE.Box3Helper(p.box, 0xcccccc);
101
+ disposables.push(helper.geometry, helper.material);
102
+ group.add(orb, helper);
103
+ }
104
+ scene.add(group);
105
+ return () => { group.removeFromParent(); for (const d of disposables) d.dispose(); };
106
+ }
107
+
108
+ class LocalReflectionProbe {
109
+ constructor(e, o, box, pos) {
110
+ this._e = e;
111
+ this.box = box;
112
+ this._vol = volumeOf(box);
113
+ this.position = pos;
114
+ this._resGiven = o.resolution ?? null;
115
+ this.near = o.near;
116
+ this.far = o.far;
117
+ this.intensity = o.intensity;
118
+ this._auto = o.autoAssign;
119
+ this._include = o.include ?? null;
120
+ this.owner = o.owner;
121
+ this._pmrem = null;
122
+ this._target = null;
123
+ this._boundMats = new Set();
124
+ this._dynamic = new Set();
125
+ this._dynHook = null;
126
+ this._dead = false;
127
+ this.bakeMs = 0;
128
+ this._swap = onRendererSwap(e, () => {
129
+ this._pmrem?.dispose(); this._pmrem = null;
130
+ this._target?.dispose(); this._target = null;
131
+ if (!this._dead && e.ready) this.bake();
132
+ });
133
+ this._restored = e.events.on('page:contextrestored', () => { if (!this._dead) this.bake(); });
134
+ probeList(e).add(this);
135
+ this.bake();
136
+ }
137
+
138
+ get texture() { return this._target?.texture ?? null; }
139
+
140
+ _size() { return this._resGiven ?? (this._e.tier === 'low' ? 128 : 256); }
141
+
142
+ /** Re-capture the local scene from `position` into the prefiltered PMREM map */
143
+ bake() {
144
+ if (this._dead) return this;
145
+ const e = this._e, r = e.renderer;
146
+ const gpu = isWebGPU(r);
147
+ if (gpu && typeof r.hasInitialized === 'function' && !r.hasInitialized()) return this;
148
+ const t0 = performance.now();
149
+ this._pmrem ??= new (gpu ? webgpuPart('classes', 'engine.addReflectionProbe').PMREMGenerator : THREE.PMREMGenerator)(r);
150
+ const hide = [];
151
+ e.scene.traverse(x => {
152
+ if (!x.visible) return;
153
+ if (x.name === 'debug:reflectionProbes' || (this._include && (x.isMesh || x.isPoints || x.isLine || x.isSprite) && !this._include(x))) hide.push(x);
154
+ });
155
+ const old = this._target;
156
+ let next = null;
157
+ for (const x of hide) x.visible = false;
158
+ try {
159
+ freshFrame(r);
160
+ const opts = gpu ? { size: this._size(), position: this.position, renderTarget: old } : { size: this._size(), position: this.position };
161
+ next = this._pmrem.fromScene(e.scene, 0, this.near, this.far, opts);
162
+ } finally {
163
+ for (const x of hide) x.visible = true;
164
+ }
165
+ if (old && old !== next) old.dispose();
166
+ this._target = next;
167
+ this.bakeMs = performance.now() - t0;
168
+ if (this._auto) reassignAllStatic(e);
169
+ for (const m of this._boundMats) if (matOrigins.get(m)?.owner === this) assignMat(m, this);
170
+ this._updateDynamic();
171
+ return this;
172
+ }
173
+
174
+ /** @internal */
175
+ _bindStatic() {
176
+ this._e.scene.updateMatrixWorld(true);
177
+ this._e.scene.traverseVisible(o => {
178
+ if (!o.isMesh || o.userData?.moving || o.isSkinnedMesh) return;
179
+ if (!o.geometry?.boundingBox) o.geometry?.computeBoundingBox?.();
180
+ if (o.geometry?.boundingBox) _objBox.copy(o.geometry.boundingBox).applyMatrix4(o.matrixWorld).getCenter(_center);
181
+ else o.getWorldPosition(_center);
182
+ const winner = bestProbeAt(this._e, _center);
183
+ if (winner !== this) return;
184
+ for (const m of mats(o)) if (takesEnv(m)) {
185
+ this._boundMats.add(m);
186
+ assignMat(m, this);
187
+ }
188
+ });
189
+ }
190
+
191
+ /**
192
+ * Bind an Object3D subtree or a Material to local reflection probes: static materials get this probe immediately, and an Object3D passed with
193
+ * `{ follow: true }` (default true for Object3D) updates its zone automatically as it moves between indoor and outdoor bounds. Returns `{ remove() }`.
194
+ * @param {any} target
195
+ * @param {{ follow?: boolean }} [opts]
196
+ * @returns {{ remove(): void }}
197
+ */
198
+ addTarget(target, { follow = true } = {}) {
199
+ if (!target || typeof target !== 'object') throw codedError('probes-option', 'reflectionProbe.addTarget(target): target must be a three.js Object3D or Material');
200
+ if (target.isMaterial) {
201
+ if (takesEnv(target)) { this._boundMats.add(target); assignMat(target, this); }
202
+ return { remove: () => { this._boundMats.delete(target); if (matOrigins.get(target)?.owner === this) assignMat(target, null); } };
203
+ }
204
+ if (!target.isObject3D) throw codedError('probes-option', 'reflectionProbe.addTarget(target): target must be an Object3D or Material');
205
+ const touched = new Set();
206
+ const applyZone = probe => {
207
+ target.traverse(o => {
208
+ if (!o.isMesh) return;
209
+ for (const m of mats(o)) if (takesEnv(m)) { touched.add(m); assignMat(m, probe); }
210
+ });
211
+ };
212
+ if (!follow) {
213
+ applyZone(this);
214
+ return { remove: () => { for (const m of touched) if (matOrigins.get(m)?.owner === this) assignMat(m, null); touched.clear(); } };
215
+ }
216
+ const rec = { target, last: undefined, applyZone, touched };
217
+ this._dynamic.add(rec);
218
+ this._ensureDynHook();
219
+ this._stepRec(rec);
220
+ return {
221
+ remove: () => {
222
+ if (!this._dynamic.delete(rec)) return;
223
+ for (const m of touched) assignMat(m, null);
224
+ touched.clear();
225
+ if (!this._dynamic.size) { this._dynHook?.remove(); this._dynHook = null; }
226
+ },
227
+ };
228
+ }
229
+
230
+ /** @internal */
231
+ _ensureDynHook() {
232
+ if (this._dynHook) return;
233
+ this._dynHook = this._e.onFrame(() => this._updateDynamic());
234
+ }
235
+
236
+ /** @internal */
237
+ _stepRec(rec) {
238
+ rec.target.getWorldPosition(_pos);
239
+ const probe = bestProbeAt(this._e, _pos);
240
+ if (probe !== rec.last) { rec.last = probe; rec.applyZone(probe); }
241
+ }
242
+
243
+ /** @internal */
244
+ _updateDynamic() {
245
+ for (const rec of this._dynamic) this._stepRec(rec);
246
+ }
247
+
248
+ /** describe().render.reflectionProbes row @internal */
249
+ info() {
250
+ const p = this.position, r = v => Math.round(v * 100) / 100;
251
+ this.box.getSize(_size);
252
+ return {
253
+ owner: this.owner, position: [r(p.x), r(p.y), r(p.z)],
254
+ size: [r(_size.x), r(_size.y), r(_size.z)], resolution: this._size(),
255
+ materials: this._boundMats.size, tracked: this._dynamic.size, bakeMs: Math.round(this.bakeMs),
256
+ };
257
+ }
258
+
259
+ /** Remove the probe, restore every material it owned (or hand it to an enclosing probe), and free GPU memory */
260
+ remove() {
261
+ if (this._dead) return;
262
+ this._dead = true;
263
+ probeList(this._e).delete(this);
264
+ this._dynHook?.remove(); this._dynHook = null;
265
+ for (const rec of this._dynamic) {
266
+ const fallback = bestProbeAt(this._e, rec.target.getWorldPosition(_pos));
267
+ rec.applyZone(fallback);
268
+ }
269
+ this._dynamic.clear();
270
+ for (const m of this._boundMats) if (matOrigins.get(m)?.owner === this) assignMat(m, null);
271
+ this._boundMats.clear();
272
+ reassignAllStatic(this._e);
273
+ for (const p of probeList(this._e)) if (!p._dead) p._updateDynamic();
274
+ this._swap.remove();
275
+ this._restored.remove();
276
+ this._target?.dispose(); this._target = null;
277
+ this._pmrem?.dispose(); this._pmrem = null;
278
+ }
279
+ }
280
+
281
+ /** Mixed into Engine.prototype (core/engine/Engine.js) */
282
+ export const reflectionProbeMethods = {
283
+ /**
284
+ * Capture a local prefiltered PMREM reflection probe for `bounds` (rooms, caves, tunnels, courtyards) so metallic and glossy surfaces inside `bounds`
285
+ * reflect their local surroundings instead of the outdoor sky. Nested bounds pick the smallest enclosing volume; moving objects added with
286
+ * `probe.addTarget(player.root)` transition between zones automatically. Returns a handle `{ texture, box, position, bake(), addTarget(), remove() }`.
287
+ * @example const roomProbe = engine.addReflectionProbe({ bounds: { min: [-8, 0, -8], max: [8, 4, 8] } });
288
+ * @param {{ bounds: THREE.Box3 | { min: any, max: any }, position?: any, resolution?: number, near?: number, far?: number, intensity?: number, autoAssign?: boolean, include?: (o: THREE.Object3D) => boolean, owner?: string }} opts
289
+ * @returns {import('../types/core').ReflectionProbe}
290
+ * @experimental
291
+ */
292
+ addReflectionProbe(opts) {
293
+ const o = readParams('engine.addReflectionProbe()', SCHEMA, opts);
294
+ const box = readBox(o.bounds);
295
+ const pos = o.position != null ? vec3(o.position).clone() : box.getCenter(new THREE.Vector3());
296
+ this._reflectionProbeView ??= this.debug?.defineView('reflectionProbes', {
297
+ what: 'each reflection probe as a mirror sphere at its capture point with its bounds box',
298
+ apply: scene => drawReflectionProbes(this, scene),
299
+ });
300
+ return new LocalReflectionProbe(this, o, box, pos);
301
+ },
302
+ };
@@ -6,6 +6,7 @@
6
6
  // if the game set onShaderError itself, do not override it.
7
7
  import { setConsoleFunction, getConsoleFunction } from 'three';
8
8
  import { isWebGPU, findNodeBuild } from './backend.js';
9
+ import { nodeBuilderStateOf } from './threeCompat.js';
9
10
  import { materialPatches } from './patches.js';
10
11
  import { notePatch, patchOn } from '../core/scene/threePatches.js';
11
12
 
@@ -152,23 +153,32 @@ function explainBuildError(message) {
152
153
  const ro = findNodeBuild(() => true), named = /\[threedog\] (patch|post effect) '/.test(message);
153
154
  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). `
154
155
  + (/\[vertex-inputs\]/.test(message) ? 'The vertex inputs counted above are the cause (render/vertexInputs.js).'
156
+ : /\[texture-bindings\]/.test(message) ? 'The texture / sampler bindings counted above are the cause (render/bindingLimits.js).'
155
157
  : named ? 'The patch or post effect named above returned the node that failed.'
156
158
  : "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 ...)");
157
159
  }
158
160
 
159
- let consoleHooked = false;
161
+ const consoleHook = { hooked: false, prev: /** @type {any} */ (null), wrap: /** @type {any} */ (null) };
162
+ notePatch('three-console-hook', "three's setConsoleFunction (page-wide): appends material and patch context after three's WebGPU pipeline and TSL build-error logs (render/shaderErrors.js)",
163
+ () => {
164
+ if (consoleHook.hooked && getConsoleFunction() === consoleHook.wrap) setConsoleFunction(consoleHook.prev);
165
+ consoleHook.hooked = false; consoleHook.prev = null; consoleHook.wrap = null;
166
+ },
167
+ { scope: 'page', lost: "WebGPU pipeline and TSL build errors print three's raw log without naming the material or patches" });
160
168
  /** Wrap three's console function once per page: three's own message first, then the explanation for a pipeline failure */
161
169
  function hookThreeConsole() {
162
- if (consoleHooked) return;
163
- consoleHooked = true;
164
- const prev = getConsoleFunction();
165
- setConsoleFunction((type, message, ...params) => {
170
+ if (consoleHook.hooked || !patchOn('three-console-hook')) return;
171
+ consoleHook.hooked = true;
172
+ const prev = consoleHook.prev = getConsoleFunction();
173
+ const wrap = consoleHook.wrap = (type, message, ...params) => {
166
174
  if (prev) prev(type, message, ...params);
167
175
  else if (params[0]?.isStackTrace) console[type](params[0].getError(message)); // what three prints when no function is set
168
176
  else console[type](message, ...params);
177
+ if (!patchOn('three-console-hook')) return;
169
178
  const why = type === 'error' ? explainPipelineError(String(message)) || explainBuildError(String(message)) : '';
170
179
  if (why) console.error(why);
171
- });
180
+ };
181
+ setConsoleFunction(wrap);
172
182
  }
173
183
 
174
184
  /** @param {any} r a WebGPURenderer */
@@ -176,8 +186,8 @@ function nameNodeErrors(r) {
176
186
  const d = r.debug;
177
187
  if (d && !d.onShaderError) d.onShaderError = (gl, program, vs, fs) => {
178
188
  const src = [gl.getShaderSource(vs), gl.getShaderSource(fs)];
179
- // _nodeBuilderState, not getNodeBuilderState(): reading must never start a build from inside an error report
180
- const ro = findNodeBuild(x => { const s = x._nodeBuilderState; return !!s && (s.vertexShader === src[0] || s.fragmentShader === src[1]); });
189
+ // nodeBuilderStateOf reads the already-built state without triggering a new build from inside an error report
190
+ const ro = findNodeBuild(x => { const s = nodeBuilderStateOf(x); return !!s && (s.vertexShader === src[0] || s.fragmentShader === src[1]); });
181
191
  const logs = [];
182
192
  for (const { stage, sh, log } of stageLogs(gl, vs, fs)) {
183
193
  const lines = (gl.getShaderSource(sh) || '').split('\n');
@@ -55,6 +55,7 @@ class CachedShadowNode extends Base {
55
55
  if (!builder.renderer.backend.isWebGPUBackend) return made;
56
56
  const cache = super.setupRenderTarget(shadow, builder);
57
57
  made.depthTexture.type = cache.depthTexture.type = FloatType;
58
+ this._cache?.depthTexture?.dispose();
58
59
  this._cache?.dispose();
59
60
  this._cache = cache.shadowMap;
60
61
  this._stale = this._fresh = true;
@@ -99,10 +100,13 @@ class CachedShadowNode extends Base {
99
100
  this._kept = new WeakSet();
100
101
  this._instanced.clear();
101
102
  this._filling = true;
102
- renderer.setRenderTarget(cache);
103
- super.renderShadow(frame);
104
- this._filling = false;
105
- renderer.setRenderTarget(shadowMap);
103
+ try {
104
+ renderer.setRenderTarget(cache);
105
+ super.renderShadow(frame);
106
+ } finally {
107
+ this._filling = false;
108
+ renderer.setRenderTarget(shadowMap);
109
+ }
106
110
  this._matrix.copy(shadow.matrix);
107
111
  this._stale = this._due = false; this._since = 0; this._fills++;
108
112
  }
@@ -116,11 +120,12 @@ class CachedShadowNode extends Base {
116
120
  /** @param {(object: any) => boolean} isStatic */
117
121
  set(isStatic) { this._isStatic = isStatic; this.redraw(); }
118
122
  redraw() { this._stale = true; /** @type {any} */ (this.light).shadow.needsUpdate = true; }
119
- dispose() { this._cache?.dispose(); this._cache = null; super.dispose(); }
123
+ dispose() { this._cache?.depthTexture?.dispose(); this._cache?.dispose(); this._cache = null; super.dispose(); }
120
124
  /** Switch off: the light gets three's own shadow node back */
121
125
  drop() {
122
126
  const light = /** @type {any} */ (this.light);
123
127
  delete light.shadow.shadowNode; // three tests `!== undefined`: null would count as a node
128
+ this.dispose();
124
129
  rebuildShadow(light);
125
130
  }
126
131
  }