threedog 2.2.2 → 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 (194) hide show
  1. package/CHANGELOG.md +20 -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 +22 -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 +371 -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/gameLights.js +19 -11
  44. package/core/scene/sceneDelta.js +8 -4
  45. package/core/stream/chunkStream.js +21 -0
  46. package/core/stream/dirtyWatch.js +37 -0
  47. package/core/time/skip.js +9 -6
  48. package/core/time/time.js +72 -18
  49. package/docs/AI.md +22 -21
  50. package/docs/API.md +5 -4
  51. package/docs/CODEMAP.md +16 -10
  52. package/docs/COMMANDS.md +5 -5
  53. package/docs/CONVENTIONS.md +9 -25
  54. package/docs/api/ambience.md +1 -0
  55. package/docs/api/assets.md +10 -3
  56. package/docs/api/audio.md +5 -3
  57. package/docs/api/decals.md +16 -0
  58. package/docs/api/engine.md +1 -0
  59. package/docs/api/tools.md +3 -1
  60. package/docs/api/water.md +3 -0
  61. package/docs/recipes/09-materials-lights-models.md +15 -1
  62. package/docs/recipes/13-animation.md +51 -10
  63. package/docs/recipes/16-dev-bridge.md +1 -1
  64. package/docs/recipes/31-audio.md +15 -9
  65. package/docs/recipes/34-environment-lighting.md +11 -1
  66. package/docs/recipes/44-water-weather-hooks.md +1 -0
  67. package/examples/action/.threedog/content-index.json +1 -0
  68. package/examples/perf-island/.threedog/content-index.json +1 -0
  69. package/examples/plain-picture/.threedog/content-index.json +1 -0
  70. package/examples/rc2d/.threedog/content-index.json +1 -0
  71. package/examples/styletest/.threedog/content-index.json +1 -0
  72. package/examples/techniques/outlines-and-rim/main.js +1 -1
  73. package/examples/techniques/procedural-surface/main.js +1 -1
  74. package/examples/techniques/stylized-shading/main.js +1 -1
  75. package/examples/webgpu-tsl/.threedog/content-index.json +1 -0
  76. package/examples/world/.threedog/content-index.json +1 -0
  77. package/index.d.ts +6 -2
  78. package/index.js +3 -2
  79. package/llms.txt +11 -10
  80. package/modules/ambience/Ambience.js +97 -15
  81. package/modules/camera/common.js +18 -12
  82. package/modules/characters/Character.js +30 -3
  83. package/modules/characters/NPC.js +2 -5
  84. package/modules/characters/astar.js +45 -14
  85. package/modules/characters/movers/rapier.js +53 -41
  86. package/modules/characters/movers/simple.js +37 -24
  87. package/modules/characters/npcView.js +2 -2
  88. package/modules/characters/pathAsync.js +3 -3
  89. package/modules/collision/contract.js +2 -2
  90. package/modules/content/index.js +3 -0
  91. package/modules/content/models.js +11 -4
  92. package/modules/content/templates.js +11 -11
  93. package/modules/debug/DebugPanel.js +1 -0
  94. package/modules/decals/Decals.js +393 -0
  95. package/modules/decals/index.js +1 -0
  96. package/modules/gameplay/Container.js +2 -0
  97. package/modules/gameplay/Containers.js +17 -3
  98. package/modules/gameplay/Dialogue.js +1 -1
  99. package/modules/gameplay/Interactions.js +7 -6
  100. package/modules/gameplay/Inventory.js +5 -1
  101. package/modules/gameplay/Quests.js +4 -3
  102. package/modules/gameplay/inventoryOps.js +2 -2
  103. package/modules/gameplay/pickups.js +32 -12
  104. package/modules/gameplay/questSave.js +2 -2
  105. package/modules/grid/index.js +8 -2
  106. package/modules/hud/index.js +1 -1
  107. package/modules/level/heightfield.js +1 -0
  108. package/modules/level/index.js +3 -2
  109. package/modules/level/nodes.js +2 -1
  110. package/modules/lights/index.js +27 -4
  111. package/modules/lights/slots.js +33 -16
  112. package/modules/nav/contract.js +4 -4
  113. package/modules/nav/index.js +6 -2
  114. package/modules/net/Client.js +24 -11
  115. package/modules/net/Host.js +73 -20
  116. package/modules/net/index.js +33 -21
  117. package/modules/net/sync.js +38 -8
  118. package/modules/net/transports.js +7 -3
  119. package/modules/particles/Particles.js +11 -4
  120. package/modules/particles/contract.js +6 -6
  121. package/modules/particles/effect.js +0 -1
  122. package/modules/rigid/RigidBodies.js +69 -57
  123. package/modules/rigid/Vehicles.js +8 -7
  124. package/modules/rigid/ragdoll.js +4 -6
  125. package/modules/rigid/rapierCompat.js +90 -0
  126. package/modules/rigid/sync.js +2 -5
  127. package/modules/settings/Settings.js +10 -4
  128. package/modules/sky/Sky.js +10 -2
  129. package/modules/sky/environment.js +29 -13
  130. package/modules/sky/frame.js +2 -2
  131. package/modules/sky/shader.js +5 -2
  132. package/modules/sky/skyModule.js +2 -2
  133. package/modules/swarm/Swarm.js +3 -2
  134. package/modules/swarm/grid.js +12 -7
  135. package/modules/terrain/ChunkManager.js +16 -26
  136. package/modules/triggers/index.js +5 -6
  137. package/modules/vegetation/draw.js +62 -26
  138. package/modules/vegetation/groundChunks.js +8 -22
  139. package/modules/water/Water.js +152 -24
  140. package/modules/water/surface.js +43 -20
  141. package/modules/weather/weatherDraw.js +4 -1
  142. package/modules/world/World.js +21 -2
  143. package/modules/world/index.js +5 -0
  144. package/modules/world/persist.js +1 -0
  145. package/modules/world/records.js +3 -1
  146. package/modules/world/sim.js +3 -2
  147. package/modules/world/simFar.js +4 -2
  148. package/modules/world/state.js +7 -1
  149. package/package.json +2 -2
  150. package/presets.js +30 -0
  151. package/render/PostFX.js +24 -17
  152. package/render/backend.js +72 -31
  153. package/render/cascades.js +25 -14
  154. package/render/cascades.tsl.js +32 -21
  155. package/render/fogLook.js +2 -1
  156. package/render/fx/library.tsl.js +1 -1
  157. package/render/fx/particles.tsl.js +4 -18
  158. package/render/fx/pcss.tsl.js +2 -2
  159. package/render/fx/postWebGPU.tsl.js +47 -25
  160. package/render/fx/sky.tsl.js +6 -18
  161. package/render/fx/uniforms.tsl.js +16 -0
  162. package/render/fx/water.tsl.js +24 -5
  163. package/render/fxNumbers.js +2 -0
  164. package/render/impostor.tsl.js +10 -6
  165. package/render/lights.js +6 -6
  166. package/render/occlusion.js +17 -6
  167. package/render/patches.js +40 -28
  168. package/render/postWebGL.js +6 -4
  169. package/render/reflectionProbes.js +302 -0
  170. package/render/shaderErrors.js +18 -8
  171. package/render/shadowCache.tsl.js +10 -5
  172. package/render/shadows.js +70 -49
  173. package/render/threeCompat.js +166 -0
  174. package/types/core.d.ts +33 -3
  175. package/types/gameplay.d.ts +80 -0
  176. package/types/generated/core/audio/Audio.d.ts +18 -1
  177. package/types/generated/core/ops/Ops.d.ts +2 -1
  178. package/types/generated/core/ops/control.d.ts +7 -3
  179. package/types/generated/core/saves/session.d.ts +4 -1
  180. package/types/generated/modules/ambience/Ambience.d.ts +6 -0
  181. package/types/generated/modules/debug/DebugPanel.d.ts +1 -0
  182. package/types/generated/modules/grid/index.d.ts +27 -3
  183. package/types/generated/modules/net/index.d.ts +8 -3
  184. package/types/generated/modules/sky/Sky.d.ts +1 -0
  185. package/types/generated/modules/water/Water.d.ts +15 -0
  186. package/types/generated/modules/world/index.d.ts +5 -0
  187. package/types/generated/render/patches.d.ts +5 -0
  188. package/types/physics.d.ts +66 -9
  189. package/types/tsl.d.ts +2 -0
  190. package/types/world.d.ts +2 -0
  191. package/ui/Parts.js +3 -2
  192. package/docs/MIGRATING-0.7.md +0 -39
  193. package/docs/MIGRATING-0.8.md +0 -171
  194. package/modules/rigid/refresh.js +0 -10
@@ -15,7 +15,7 @@
15
15
  import * as TSL from 'three/tsl';
16
16
  import { Sprite, PointsNodeMaterial, LineBasicNodeMaterial, InstancedBufferAttribute, DataTexture, SRGBColorSpace,
17
17
  NormalBlending, AdditiveBlending } from 'three/webgpu';
18
- import { valueNode } from './uniforms.tsl.js';
18
+ import { uniformNodes } from './uniforms.tsl.js';
19
19
  import { registerWebGPUPart } from '../backend.js';
20
20
 
21
21
  const { Fn, texture, cameraProjectionMatrix, instancedDynamicBufferAttribute, attribute, varying, positionGeometry, modelViewMatrix, screenDPR, uv, viewportLinearDepth, cameraNear, cameraFar,
@@ -32,20 +32,6 @@ const { Fn, texture, cameraProjectionMatrix, instancedDynamicBufferAttribute, at
32
32
  /** A per-instance attribute node of the given node type @type {<T extends string>(a: any, type: T) => N<T>} */
33
33
  const at = (a, type) => /** @type {any} */ (instancedDynamicBufferAttribute(a, type));
34
34
 
35
- /**
36
- * { value } objects -> uniform nodes reading them each render (uniforms.tsl.js valueNode, the engine's one read-back form)
37
- * @param {Record<string, { value: any }>} u @returns {any} ParticleNodes or WeatherNodes: node types follow the values (valueNode)
38
- */
39
- function nodesOf(u) {
40
- const n = {};
41
- for (const [k, o] of Object.entries(u)) {
42
- const v = o.value;
43
- if (typeof v !== 'number' && !v?.isVector2 && !v?.isVector3 && !v?.isColor) continue; // textures go through mapSlot; a game's other own uniforms only meant something to its GLSL
44
- n[k] = valueNode(o);
45
- }
46
- return n;
47
- }
48
-
49
35
  // sRGB like the textures games load, so swapping in a real one does not change the colour conversion the node was built with
50
36
  const white = () => { const t = new DataTexture(new Uint8Array([255, 255, 255, 255]), 1, 1); t.colorSpace = SRGBColorSpace; t.needsUpdate = true; return t; };
51
37
 
@@ -87,7 +73,7 @@ const pointCoord = () => vec2(uv().x, uv().y.oneMinus());
87
73
  function particles({ attrs, count, fog, additive, maxPixels, soft }) {
88
74
  const u = { uScale: { value: 400 }, uMaxPx: { value: maxPixels }, uHasMap: { value: 0 }, uMap: { value: null }, ...(soft ? { uSoft: { value: soft } } : {}) };
89
75
  const m = new PointsNodeMaterial({ transparent: true, depthWrite: false, fog, sizeAttenuation: false, blending: additive ? AdditiveBlending : NormalBlending });
90
- /** @type {ParticleNodes} */ const U = nodesOf(u);
76
+ /** @type {ParticleNodes} */ const U = uniformNodes(u);
91
77
  const map = mapSlot(u, m);
92
78
  const pos = at(attrs.aPos, 'vec3'), size = at(attrs.aSize, 'float'), alpha = at(attrs.aAlpha, 'float');
93
79
  m.positionNode = pos;
@@ -125,7 +111,7 @@ const wrap = (U, p, dx, dz) => {
125
111
 
126
112
  /** Weather streaks (LineSegments, 1px like WebGL lines): same attributes and uniforms as lineVert / lineFrag */
127
113
  function weatherLines(u) {
128
- /** @type {WeatherNodes} */ const U = nodesOf(u);
114
+ /** @type {WeatherNodes} */ const U = uniformNodes(u);
129
115
  const m = new LineBasicNodeMaterial({ transparent: true, depthWrite: false });
130
116
  const end = attribute('aEnd', 'float');
131
117
  m.positionNode = Fn(() => {
@@ -140,7 +126,7 @@ function weatherLines(u) {
140
126
  /** Weather sprites (snow, drops): `geo`'s positions become the instances (geo itself is not drawn); same uniforms as pointVert / pointFrag(shape) */
141
127
  function weatherPoints(u, geo, shape) {
142
128
  const m = new PointsNodeMaterial({ transparent: true, depthWrite: false, sizeAttenuation: false });
143
- /** @type {WeatherNodes} */ const U = nodesOf(u);
129
+ /** @type {WeatherNodes} */ const U = uniformNodes(u);
144
130
  const map = mapSlot(u, m), src = geo.getAttribute('position');
145
131
  const a = new InstancedBufferAttribute(src.array, 3), p = at(a, 'vec3');
146
132
  const w = wrap(U, p, () => sin(U.uSway.mul(0.7).add(p.y)).mul(U.uSwayAmp), () => cos(U.uSway.mul(0.5).add(p.x)).mul(U.uSwayAmp));
@@ -34,7 +34,7 @@ export function pcss({ lightSize = 0.04, samples = 16, maxDistance = 4 } = {}) {
34
34
  const blocked = float(0).toVar(), gap = float(0).toVar();
35
35
  const reach = float(lightSize * maxDistance).div(width).max(texel);
36
36
  Loop(search, ({ i }) => {
37
- const uv = shadowCoord.xy.add(vogelDiskSample(i, search, phi).mul(reach));
37
+ const uv = shadowCoord.xy.add(vogelDiskSample(i, float(search), phi).mul(reach));
38
38
  blocked.addAssign(lit(uv, shadowCoord.z).oneMinus());
39
39
  for (let k = 0; k < 4; k++) {
40
40
  const from = steps[k - 1] ?? 0, band = steps[k] - from, u = ign.add(float(i).mul(4).add(k).mul(0.618034)).fract();
@@ -45,7 +45,7 @@ export function pcss({ lightSize = 0.04, samples = 16, maxDistance = 4 } = {}) {
45
45
  // edge width in shadow-map uv, never under one texel; then plain percentage-closer filtering at that width
46
46
  const radius = min(distance.mul(lightSize).div(width), reach).max(texel);
47
47
  const sum = float(0).toVar();
48
- Loop(taps, ({ i }) => { sum.addAssign(lit(shadowCoord.xy.add(vogelDiskSample(i, taps, phi).mul(radius)), shadowCoord.z)); });
48
+ Loop(taps, ({ i }) => { sum.addAssign(lit(shadowCoord.xy.add(vogelDiskSample(i, float(taps), phi).mul(radius)), shadowCoord.z)); });
49
49
  return sum.div(taps);
50
50
  });
51
51
  }
@@ -20,17 +20,26 @@ import { nameNodeBuild, lostStatements } from './nodeErrors.tsl.js';
20
20
  const { pass, renderOutput, uniform, screenUV, screenSize, time, convertToTexture, mrt, output, normalView, diffuseColor, velocity, metalness, roughness, vec2, vec4 } = TSL;
21
21
 
22
22
  // What PostEffect.needsBuffers can ask of the scene render. Raw, not packed into other encodings: display nodes read them as they are.
23
- // metalRough is the one exception in storage, not in meaning: both are 0 to 1, so they share one 8-bit target (three's SSR example does the same), a quarter of a half-float one
23
+ // diffuse and metalRough fit in 8-bit targets (rgba8unorm, 4 bytes per sample vs 8 for half-float), halving MRT bandwidth and byte budget
24
24
  const BUFFERS = { normal: normalView, diffuse: diffuseColor, velocity, metalRough: vec2(metalness, roughness) };
25
- const BYTE_BUFFERS = ['metalRough'];
26
- // velocity fills only xy of its target: with both asked, metalRough rides in its zw, one target fewer (output + normal + diffuse + velocity is WebGPU's default ceiling)
25
+ const BYTE_BUFFERS = ['diffuse', 'metalRough'];
26
+ // velocity fills only xy of its target: with both asked, metalRough rides in its zw, one target fewer (output + normal + diffuse + velocity fits WebGPU's default ceiling)
27
27
  const VELOCITY_METAL_ROUGH = vec4(/** @type {any} */ (velocity), BUFFERS.metalRough); // three types the velocity node as no vec2
28
+ const NO_ROOM = Object.freeze({ attachments: Infinity, bytes: Infinity });
28
29
 
29
- /** How many scene targets the device takes. Every target here is rgba16float or rgba8unorm, 8 bytes per sample each in WebGPU's table, so bytes reduce to a count; Infinity before the device exists */
30
+ /** Resolve static or param-dependent needsBuffers on an effect handle */
31
+ const buffersOf = e => {
32
+ const b = e._def.needsBuffers;
33
+ return (typeof b === 'function' ? b(e.params) : b) ?? [];
34
+ };
35
+
36
+ /** How many scene targets and per-pixel bytes the device takes (output/normal/velocity = 8 B, BYTE_BUFFERS = 4 B); Infinity before the device exists */
30
37
  function roomOf(r) {
31
- const be = r.backend, l = be?.device?.limits, gl = be?.gl;; if (!l && !gl) return Infinity;
38
+ const be = r.backend, l = be?.device?.limits, gl = be?.gl; if (!l && !gl) return NO_ROOM;
32
39
  // read once per backend: render() asks every frame, and a GL query there would be a sync call each frame
33
- if (!rooms.has(be)) rooms.set(be, l ? Math.min(l.maxColorAttachments, Math.floor(l.maxColorAttachmentBytesPerSample / 8)) : gl.getParameter(gl.MAX_DRAW_BUFFERS));
40
+ if (!rooms.has(be)) rooms.set(be, Object.freeze(l
41
+ ? { attachments: l.maxColorAttachments, bytes: l.maxColorAttachmentBytesPerSample }
42
+ : { attachments: gl.getParameter(gl.MAX_DRAW_BUFFERS), bytes: Infinity }));
34
43
  return rooms.get(be);
35
44
  }
36
45
  const rooms = new WeakMap();
@@ -101,16 +110,22 @@ const webgpuPost = {
101
110
  targets: () => null,
102
111
  /**
103
112
  * Param change: number / color params only write their uniforms; another kind (a texture, a mode string), a value of another kind than its
104
- * uniform (a Color for a param that started as a number: the uniform is replaced), or a param node() read as a plain value from ctx.params
105
- * (built into the graph as a constant, so its uniform reaches nothing), rebuilds the chain, as WebGL rebuilds an effect without update(). true = handled
113
+ * uniform (a Color for a param that started as a number, or a live value replacing null: the uniform is replaced / added), or a param node() read as a plain value from ctx.params
114
+ * (built into the graph as a constant, so its uniform reaches nothing), asks the caller (PostFX._change) to rebuild the chain. Returns true when a rebuild is needed.
106
115
  */
107
116
  set(post, h, p) {
108
- if (Object.entries(p).every(([k, v]) => fits(h._u?.[k], v) && !h._read?.has(k))) { for (const [k, v] of Object.entries(p)) writeUniform(h._u[k], v); return true; }
117
+ const bufChanged = typeof h._def.needsBuffers === 'function' && buffersOf(h).join(',') !== (h._bufKey ?? '');
118
+ if (!bufChanged && Object.entries(p).every(([k, v]) => fits(h._u?.[k], v) && !h._read?.has(k))) { for (const [k, v] of Object.entries(p)) writeUniform(h._u[k], v); return false; }
109
119
  for (const [k, v] of Object.entries(p)) {
110
120
  if (fits(h._u?.[k], v)) writeUniform(h._u[k], v);
111
- else if (h._u?.[k] && kindOf(v)) h._u[k] = liveUniform(v);
121
+ else if (h._u) {
122
+ if (kindOf(v)) h._u[k] = liveUniform(v);
123
+ else delete h._u[k];
124
+ }
112
125
  }
113
- if (h.enabled) { h._impl?.dispose?.(); h._impl = null; post._pipe && (post._pipe.key = null); post._sync(); }
126
+ if (!h.enabled || (!post._own.on && post._pipe)) return false;
127
+ h._impl?.dispose?.(false); h._impl = null;
128
+ if (post._pipe) post._pipe.key = null;
114
129
  return true;
115
130
  },
116
131
  samples: post => (post.active ? post._pipe?.samples ?? (post._aa ? MSAA_SAMPLES : 0) : post.engine.renderer.samples),
@@ -121,34 +136,41 @@ const webgpuPost = {
121
136
  const on = post._sorted().filter(e => e.enabled);
122
137
  // nothing on: the frame goes straight to the canvas, so the scene pass's color, depth and MSAA targets are freed now, not at engine.dispose
123
138
  // (postWebGL.js frees its composer targets the same way); the next effect builds a new pipeline (GPT review l2-render 6)
124
- if (!on.length) { for (const e of post._list) { e._impl?.dispose?.(); e._impl = null; } webgpuPost.dispose(post); return; }
139
+ if (!on.length) { for (const e of post._list) { e._impl?.dispose?.(true); e._impl = null; } webgpuPost.dispose(post); return; }
125
140
  // the union over the effects that are on, in one fixed order: one setMRT for all of them, and none at all (no extra targets) when nobody asks
126
- const buffers = Object.keys(BUFFERS).filter(b => on.some(e => e._def.needsBuffers?.includes(b)));
141
+ const buffers = Object.keys(BUFFERS).filter(b => on.some(e => buffersOf(e).includes(b)));
127
142
  const packed = buffers.includes('velocity') && buffers.includes('metalRough'), room = roomOf(renderer);
128
143
  const targets = Object.fromEntries(buffers.filter(b => !(packed && b === 'metalRough')).map(b => [b, packed && b === 'velocity' ? VELOCITY_METAL_ROUGH : BUFFERS[b]]));
144
+ const targetNames = Object.keys(targets);
129
145
  // over the device's limit three's pipeline validation fails naming no effect; checked before anything is torn down, so add() rolls back cleanly
130
- const n = 1 + Object.keys(targets).length;
131
- if (n > room) throw codedError('post-effect', `[threedog] post effects ${on.filter(e => e._def.needsBuffers?.length).map(e => `${e.name} (${e._def.needsBuffers.join(', ')})`).join(', ')} ` +
132
- `need ${n} scene targets (${n * 8} bytes per pixel), this device takes ${room} (${room * 8} bytes): turn off the one that matters least`);
146
+ const n = 1 + targetNames.length;
147
+ const bytes = 8 + targetNames.reduce((sum, b) => sum + (BYTE_BUFFERS.includes(b) ? 4 : 8), 0);
148
+ if (n > room.attachments || bytes > room.bytes) {
149
+ const needBytes = Number.isFinite(room.bytes) ? bytes : n * 8;
150
+ const maxBytes = Number.isFinite(room.bytes) ? room.bytes : room.attachments * 8;
151
+ throw codedError('post-effect', `[threedog] post effects ${on.filter(e => buffersOf(e).length).map(e => `${e.name} (${buffersOf(e).join(', ')})`).join(', ')} ` +
152
+ `need ${n} scene targets (${needBytes} bytes per pixel), this device takes ${room.attachments} (${maxBytes} bytes): turn off the one that matters least`);
153
+ }
133
154
  // velocity means a temporal resolve follows: it is the antialiasing, and MSAA under it would only cost
134
155
  const samples = post._aa && !buffers.includes('velocity') ? MSAA_SAMPLES : 0;
135
156
  for (const e of on) if (!runsOnWebGPU(e._def)) throw e._def.fuse ? glslOnly(e) : onlyCreate(e); // the rule the picture menu's "runs here" reads too
157
+ for (const e of on) e._bufKey = buffersOf(e).join(',');
136
158
  // Same effects, same build, same samples: the graph is current (a set() of a number param never gets here)
137
- const key = `${samples}|${buffers}|${room}|${on.map(e => e.name).join(',')}`;
138
- if (post._pipe?.key === key && post._pipe.camera === camera) return;
159
+ const key = `${samples}|${buffers}|${room.attachments}:${room.bytes}|${on.map(e => e.name).join(',')}`;
160
+ if (post._pipe?.key === key && post._pipe.camera === camera && post._pipe.scene === scene) return;
139
161
  let P = post._pipe;
140
162
  if (!P) P = post._pipe = { pipeline: new RenderPipeline(renderer), scenePass: null, samples: -1, buffers: '', key: null, order: [] };
141
163
  P.key = null; // the graph is coming down: when a node() throws below, PostFX syncs the old list again, and that sync must rebuild, not find its key current
142
164
  P.room = room; P.packed = packed;
143
- if (P.samples !== samples || P.buffers !== `${buffers}` || P.camera !== camera) {
144
- P.scenePass?.dispose(); P.scenePass = pass(scene, camera, { samples }); P.samples = samples; P.buffers = `${buffers}`; P.camera = camera;
165
+ if (P.samples !== samples || P.buffers !== `${buffers}` || P.camera !== camera || P.scene !== scene) {
166
+ P.scenePass?.dispose(); P.scenePass = pass(scene, camera, { samples }); P.samples = samples; P.buffers = `${buffers}`; P.camera = camera; P.scene = scene;
145
167
  if (buffers.length) P.scenePass.setMRT(mrt({ output, ...targets }));
146
- for (const b of Object.keys(targets)) if (BYTE_BUFFERS.includes(b)) P.scenePass.getTexture(b).type = UnsignedByteType;
168
+ for (const b of targetNames) if (BYTE_BUFFERS.includes(b)) P.scenePass.getTexture(b).type = UnsignedByteType;
147
169
  P.stages = []; // a new scene pass (samples, MRT, camera): every stage reads it, none is kept
148
170
  }
149
171
  const size = post._size();
150
172
  const ctxOf = (e, made) => ({ engine: post.engine, scene, camera, width: size.x, height: size.y, params: paramsOf(e), scenePass: P.scenePass,
151
- buffer: b => (b === 'metalRough' && P.packed ? P.scenePass.getTextureNode('velocity').zw : P.scenePass.getTextureNode(b)), tsl: TSL, fx: FX, display: displayFor(made), p: uniformsOf(e), borrowRenderer });
173
+ buffer: b => (b === 'metalRough' && P.packed ? P.scenePass.getTextureNode('velocity').zw : buffers.includes(b) ? P.scenePass.getTextureNode(b) : null), tsl: TSL, fx: FX, display: displayFor(made), p: uniformsOf(e), borrowRenderer });
152
174
  // the effect's node is built only when the pipeline first draws: errors then, and statements lost outside an Fn, name the effect
153
175
  const run = (e, color) => {
154
176
  const label = `[threedog] post effect '${e.name}'`;
@@ -156,7 +178,7 @@ const webgpuPost = {
156
178
  };
157
179
  const build = (e, color) => {
158
180
  const made = [];
159
- e._impl = { nodes: made, dispose() { for (const n of made) n.dispose?.(); made.length = 0; } };
181
+ e._impl = { nodes: made, dispose(final = false) { for (const n of made) n.dispose?.(final); made.length = 0; } };
160
182
  e._read = new Set(); e._building = true;
161
183
  try {
162
184
  if (e._def.fuse) {
@@ -183,8 +205,8 @@ const webgpuPost = {
183
205
  const was = P.stages ?? [];
184
206
  let k = 0;
185
207
  while (k < want.length && k < was.length && was[k].e === want[k] && (typeof want[k] === 'string' || want[k]._impl === was[k].impl)) k++;
186
- const kept = new Set(was.slice(0, k).map(s => s.e));
187
- for (const e of post._list) if (!kept.has(e)) { e._impl?.dispose?.(); e._impl = null; }
208
+ const kept = new Set(was.slice(0, k).map(s => s.e)), onSet = new Set(on);
209
+ for (const e of post._list) if (!kept.has(e)) { e._impl?.dispose?.(!onSet.has(e)); e._impl = null; }
188
210
  const stages = was.slice(0, k);
189
211
  P.stages = stages; // set before the build: a node() that throws below leaves only stages that are still whole
190
212
  let color = k ? stages[k - 1].out : P.scenePass.getTextureNode();
@@ -13,13 +13,13 @@ import * as TSL from 'three/tsl';
13
13
  import { MeshBasicNodeMaterial, BackSide } from 'three/webgpu';
14
14
  import { noise, hash } from './noise.tsl.js';
15
15
  import * as FX from './library.tsl.js';
16
- import { uniforms as engineUniforms, valueNode } from './uniforms.tsl.js';
16
+ import { uniformNodes } from './uniforms.tsl.js';
17
17
  import { codedError } from '../../core/base/errorHints.js';
18
18
  import { registerWebGPUPart } from '../backend.js';
19
19
  import { SKY as K } from '../fxNumbers.js';
20
20
 
21
21
  const { Fn, positionGeometry, varying, float, vec2, vec3, vec4, select, mix, pow, max, dot,
22
- floor, step, smoothstep, clamp, normalize, If } = TSL;
22
+ floor, step, smoothstep, clamp, normalize, If, interleavedGradientNoise, screenCoordinate } = TSL;
23
23
 
24
24
  /** @template {string} T @typedef {import('three/webgpu').Node<T>} N */
25
25
  /**
@@ -33,20 +33,6 @@ const { Fn, positionGeometry, varying, float, vec2, vec3, vec4, select, mix, pow
33
33
  * uCloudSoft: N<'float'>, uCloudRelief: N<'float'>, uFogBand: N<'float'>, [k: string]: any }} SkyNodes
34
34
  */
35
35
 
36
- /** sky.uniforms -> nodes: engine.uniforms entries through uniforms(engine), the sky's own { value } objects read back every render */
37
- /** @returns {SkyNodes} */
38
- function nodesOf(u, engine) {
39
- const E = engineUniforms(engine), n = /** @type {SkyNodes} */ ({});
40
- for (const [k, o] of Object.entries(u)) {
41
- if (engine.uniforms[k] === o) { n[k] = E[k]; continue; } // shared object (makeSkyUniforms puts engine.uniforms.uSunDir in): no second node
42
- const v = o.value;
43
- if (typeof v !== 'number' && !v?.isVector2 && !v?.isVector3 && !v?.isColor) continue;
44
- // read back every render, also for vectors / colors: uFogColor is a getter (the fog object's color, which a game may replace)
45
- n[k] = valueNode(o);
46
- }
47
- return n;
48
- }
49
-
50
36
  /** clouds dim toward SKY.nightDim at night (GLSL nightDim + (1 - nightDim) * (1 - night)) */
51
37
  const nightDim = (/** @type {SkyNodes} */ U) => U.uNight.oneMinus().mul(1 - K.nightDim).add(K.nightDim);
52
38
 
@@ -145,6 +131,8 @@ function domeColor(U, kind, clouds, layers) {
145
131
  const L = runHook(l.where, l.tsl, { ...base, color: col }).toVar();
146
132
  if (l.blend === 'add') col.addAssign(L.rgb.mul(L.a)); else col.assign(mix(col, L.rgb, L.a));
147
133
  }
134
+ // subtle deterministic 8-bit de-banding scaled in linear space (~0.5 LSB after sRGB encoding)
135
+ col.addAssign(interleavedGradientNoise(screenCoordinate).sub(0.5).mul(1 / 255).mul(col.max(0.001).sqrt()));
148
136
  return vec4(col, 1);
149
137
  })();
150
138
  }
@@ -156,7 +144,7 @@ function domeColor(U, kind, clouds, layers) {
156
144
  * @param {{ clouds?: any, layers?: any[] }} [hooks] clouds hook value and resolved dome layers (shader.js / dome.js resolve them)
157
145
  */
158
146
  function domeMaterial(u, st, kind, engine, hooks = {}) {
159
- const m = new MeshBasicNodeMaterial({ side: BackSide, depthWrite: false, depthTest: false, fog: false });
147
+ const m = new MeshBasicNodeMaterial({ side: BackSide, depthWrite: false, depthTest: false, fog: false, dithering: true });
160
148
  setHooks(m, u, kind, engine, hooks);
161
149
  return m;
162
150
  }
@@ -166,7 +154,7 @@ function domeMaterial(u, st, kind, engine, hooks = {}) {
166
154
  * (one recompile, like the GLSL dome's new fragment text). The nodes are made again here: a hook may have brought uniforms of its own.
167
155
  */
168
156
  function setHooks(m, u, kind, engine, { clouds = null, layers = [] } = {}) {
169
- const U = nodesOf(u, engine), fn = checkHooks(clouds, layers, U);
157
+ /** @type {SkyNodes} */ const U = uniformNodes(u, engine), fn = checkHooks(clouds, layers, U);
170
158
  m.colorNode = domeColor(U, kind, fn, layers);
171
159
  m.needsUpdate = true;
172
160
  }
@@ -29,6 +29,22 @@ function readBack(read, initial = read()) {
29
29
  /** readBack over a { value } object: o.value every render @param {{ value: any }} o @returns {any} */
30
30
  export const valueNode = o => readBack(() => o.value);
31
31
 
32
+ /**
33
+ * Turn a table of { value } uniforms into read-back nodes, skipping textures and unsupported values.
34
+ * When `engine` is passed, entries that share an object with `engine.uniforms` reuse its cached `uniforms(engine)` node.
35
+ * @param {Record<string, { value: any }>} u @param {any} [engine] @returns {any}
36
+ */
37
+ export function uniformNodes(u, engine = null) {
38
+ const E = engine ? uniforms(engine) : null, eu = engine?.uniforms, n = {};
39
+ for (const [k, o] of Object.entries(u)) {
40
+ if (eu && eu[k] === o) { n[k] = E[k]; continue; }
41
+ const v = o.value;
42
+ if (typeof v !== 'number' && !v?.isVector2 && !v?.isVector3 && !v?.isVector4 && !v?.isColor) continue;
43
+ n[k] = valueNode(o);
44
+ }
45
+ return n;
46
+ }
47
+
32
48
  const CACHE = new WeakMap(); // engine.uniforms object -> { uTime: node, uWind: node, ... }
33
49
 
34
50
  /** @param {Record<string, { value: any }>} U */
@@ -1,14 +1,13 @@
1
- // TSL waterWave() / waterSurface() / waterFresnel(): the water patches of modules/water (waves, waterSurface, fresnel) as TSL.
1
+ // TSL waterWave() / waterRipple() / waterSurface() / waterFresnel(): the water patches of modules/water (waves, waterSurface, waterRipples, fresnel) as TSL.
2
2
  // - waterWave(p, t): line for line the built-in GLSL threedogWaterWave (surface.js WAVE). Like the GLSL `waves` patch, feed it the world position
3
3
  // of the undisplaced vertex times waveScale and time times waveSpeed, and add wave * waveHeight to the vertex y (a positionNode: positionLocal + vec3(0, h, 0)).
4
+ // - waterRipple(xz, count, slots): concentric expanding wave packets from engine.water.ripple() and wading wakes, gated on count > 0.5.
4
5
  // - waterSurface(spec): the GLSL surface function is generated per water shader (builtSurface: depthColor / foam decide which lines exist), so the TSL side
5
6
  // is a builder too: it returns an Fn with the exact GLSL signature threedogWaterSurface(base, wave, facing, worldPos, time) -> vec4 (rgb, opacity).
6
7
  // - waterFresnel(color, normal, viewDir, strength, towards): the expression of the `fresnel` patch (Water.js, output slot), grazing angles toward
7
8
  // `towards` (the engine passes the fog color). GLSL has it inline, not as a function; the inputs are the ones that expression reads.
8
- // Why this split: waves needs nothing from waterSurface, waterSurface needs the wave height and world position waves hands over (GLSL varyings
9
- // vThreedogWave / vThreedogWaterPos, `needs: waves`); in TSL a value used in the fragment is carried over by three, so the caller just reuses the node.
10
- import { Fn, vec4, float, color, sin, cos, mix, pow, clamp, smoothstep, abs, dot } from 'three/tsl';
11
- import { WAVE as W, WAVE_MAX, DEPTH, FOAM, FRESNEL_POWER } from '../fxNumbers.js';
9
+ import { Fn, If, vec4, float, color, sin, cos, mix, pow, clamp, smoothstep, abs, dot, length } from 'three/tsl';
10
+ import { WAVE as W, WAVE_MAX, DEPTH, FOAM, FRESNEL_POWER, RIPPLE } from '../fxNumbers.js';
12
11
 
13
12
  /** @template {string} T @typedef {import('three/webgpu').Node<T>} N */
14
13
 
@@ -17,6 +16,26 @@ export const waterWave = Fn(/** @param {[N<'vec3'>, N<'float'>]} a */ ([p, t]) =
17
16
  sin(p.x.mul(W.x[0]).add(t.mul(W.x[1]))).mul(W.x[2]).add(cos(p.z.mul(W.z[0]).add(t.mul(W.z[1]))).mul(W.z[2]))
18
17
  .add(sin(p.x.add(p.z).mul(W.xz[0]).add(t.mul(W.xz[1]))).mul(W.xz[2])));
19
18
 
19
+ /**
20
+ * Concentric wave-packet sum over the 8 ripple slots; 0 when count <= 0.5
21
+ * @experimental
22
+ */
23
+ export function waterRipple(xz, count, slots) {
24
+ return Fn(() => {
25
+ const sum = float(0).toVar();
26
+ If(count.greaterThan(0.5), () => {
27
+ const invW = 1 / RIPPLE.width;
28
+ for (let i = 0; i < slots.length; i++) {
29
+ const r = slots[i];
30
+ const delta = length(xz.sub(r.xy)).sub(r.z);
31
+ const env = clamp(float(1).sub(abs(delta).mul(invW)), 0, 1);
32
+ sum.addAssign(sin(delta.mul(RIPPLE.freq)).mul(env).mul(env).mul(r.w));
33
+ }
34
+ });
35
+ return sum;
36
+ })();
37
+ }
38
+
20
39
  /** @param {any} v @returns {N<'float'>} */
21
40
  const f1 = v => (v?.isNode ? v : float(v));
22
41
  /** @param {any} v @returns {N<'vec3'> | N<'color'>} */
@@ -43,3 +43,5 @@ export const FRESNEL_POWER = 3;
43
43
  /** Fallbacks when a style gives depthColor / foam without some values (light / dark neutral grays: the blend shows, no water color is picked) */
44
44
  export const DEPTH = { shallow: 0xaaaaaa, deep: 0x555555, curve: 1 };
45
45
  export const FOAM = { color: 0xffffff, start: 0.55, end: 0.85, opacity: 1 };
46
+ /** Interactive water ripples (modules/water/Water.js, surface.js, render/fx/water.tsl.js): slots, ring packet width (m), wave number (rad/m), vertex lift, crest sheen */
47
+ export const RIPPLE = Object.freeze({ slots: 8, width: 1.35, freq: 9.5, lift: 0.08, sheen: 0.28 });
@@ -6,7 +6,7 @@
6
6
  // WebGPU route only (also WebGPURenderer's WebGL2 backend); registered as a WebGPU part like the other .tsl.js files, so WebGL bundles stay as they are.
7
7
  import * as THREE from 'three/webgpu'; // three/webgpu, not three: threedog/tsl stays WebGL-free (both share three.core.js)
8
8
  import { MeshBasicNodeMaterial, MeshLambertNodeMaterial, MeshStandardNodeMaterial, MeshToonNodeMaterial } from 'three/webgpu';
9
- import { attribute, cameraPosition, cameraViewMatrix, positionGeometry, vec2, vec3, vec4, float, int, atan, cos, sin, floor, fract, texture, varying, uv, normalLocal, faceDirection, uniform } from 'three/tsl';
9
+ import { attribute, cameraPosition, cameraViewMatrix, positionGeometry, vec2, vec3, vec4, float, int, atan, cos, sin, floor, fract, mod, select, smoothstep, texture, varying, uv, normalLocal, faceDirection, uniform, interleavedGradientNoise, screenCoordinate } from 'three/tsl';
10
10
  import { registerWebGPUPart, holdRenderer, releaseRenderer } from './backend.js';
11
11
  import { season } from './fx/season.tsl.js';
12
12
 
@@ -39,8 +39,8 @@ function normalMaterial(m) {
39
39
  */
40
40
  function bake(renderer, src, { views = 8, size = 128 } = {}) {
41
41
  const b = bounds(src.geometry);
42
- // depth > 1: an array texture, one layer per view (three sets isArrayTexture from the depth)
43
- const mk = () => new THREE.RenderTarget(size, size, { depth: views, type: THREE.HalfFloatType, generateMipmaps: true, minFilter: THREE.LinearMipmapLinearFilter, magFilter: THREE.LinearFilter });
42
+ // depth > 1: an array texture, one layer per view (three sets isArrayTexture from the depth); 8-bit RGBA halves VRAM and bandwidth for [0..1] albedo and packed normals
43
+ const mk = () => new THREE.RenderTarget(size, size, { depth: views, type: THREE.UnsignedByteType, generateMipmaps: true, minFilter: THREE.LinearMipmapLinearFilter, magFilter: THREE.LinearFilter });
44
44
  const scene = new THREE.Scene(), holder = new THREE.Group(), mesh = new THREE.Mesh(src.geometry, src.material);
45
45
  holder.add(mesh); scene.add(holder, new THREE.AmbientLight(0xffffff, Math.PI));
46
46
  const cam = new THREE.OrthographicCamera(-b.radius, b.radius, b.minY + b.height, b.minY, 0.01, b.radius * 6);
@@ -83,14 +83,18 @@ function cardMaterial(src, b) {
83
83
  m.alphaTest = 0.5;
84
84
  const N = b.views, center = attribute('aCenter', 'vec3'), shape = attribute('aShape', 'vec3');
85
85
  const toCam = cameraPosition.sub(center), ang = /** @type {any} */ (atan)(toCam.x, toCam.z); // the camera's yaw seen from the plant
86
- // nearest baked view in the plant's own frame; fract keeps it positive whatever the yaw (a % of a negative stays negative in WGSL)
87
- const cell = floor(fract(ang.sub(shape.x).div(TAU).add(0.5 / N).add(4)).mul(N));
86
+ // continuous view coordinate in the plant's own frame; fract keeps it positive whatever the yaw (a % of a negative stays negative in WGSL)
87
+ const viewPos = fract(ang.sub(shape.x).div(TAU).add(4)).mul(N);
88
88
  const right = vec3(cos(ang), 0, sin(ang).negate());
89
89
  const across = uniform(b.radius * 2), up = uniform(b.height), minY = uniform(b.minY);
90
90
  const pg = /** @type {any} */ (positionGeometry);
91
91
  m.positionNode = center.add(right.mul(pg.x.mul(across).mul(shape.y))).add(vec3(0, pg.y.mul(up).add(minY).mul(shape.z), 0));
92
+ // screen-space IGN dithering smoothly blends adjacent view slices near each 45-degree boundary with a single texture fetch per pixel
93
+ const vPos = /** @type {any} */ (varying(viewPos)), lo = floor(vPos), hi = mod(lo.add(1), N);
94
+ const blend = smoothstep(0.25, 0.75, fract(vPos));
95
+ const pick = select(blend.greaterThan(interleavedGradientNoise(screenCoordinate)), hi, lo);
92
96
  // the layers come out upside down against the card's uv on both WebGPU backends (render-target rows), so read them flipped
93
- const layer = int(/** @type {any} */ (varying(cell)).add(0.5)), st = vec2(uv().x, uv().y.oneMinus());
97
+ const layer = int(pick.add(0.5)), st = vec2(uv().x, uv().y.oneMinus());
94
98
  const alb = texture(b.albedo, st).depth(layer);
95
99
  // the season tint the mesh gets from its patches (effects on), so autumn reaches the far cards too; the bake itself is untinted
96
100
  const rgb = alb.rgb.mul(attribute('aTint', 'vec3'));
package/render/lights.js CHANGED
@@ -6,13 +6,13 @@ import { engineOwned } from '../core/scene/things.js';
6
6
  import * as THREE from 'three';
7
7
  import { defineOwned } from '../core/ops/owned.js';
8
8
 
9
- const BOX = 30, SNAP = 0.5;
9
+ const BOX = 26, SNAP = 0.5;
10
10
 
11
11
  /** @param {any} engine @returns {{ sun: THREE.DirectionalLight, hemi: THREE.HemisphereLight }} */
12
12
  export function createDefaultLights(engine, { add = true } = {}) {
13
- const hemi = new THREE.HemisphereLight(0xffffff, 0x555555, 1.2);
14
- const sun = new THREE.DirectionalLight(0xffffff, 2);
15
- sun.position.set(40, 80, 30); // above and to the side, so faces read with some shading
13
+ const hemi = new THREE.HemisphereLight(0xffffff, 0x606060, 0.95);
14
+ const sun = new THREE.DirectionalLight(0xffffff, 1.85);
15
+ sun.position.set(45, 75, 35); // above and to the side, balanced so neutral surfaces read with crisp form without blowing highlights out
16
16
  sun.castShadow = true; // the engine's light casts; whether anything draws shadows is engine.shadows.enabled (render/shadows.js)
17
17
  // the one place these defaults live: nothing writes them later, a sky included, so what a game writes on engine.lights.sun stays.
18
18
  // 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
@@ -25,7 +25,7 @@ export function createDefaultLights(engine, { add = true } = {}) {
25
25
  let map = sizeFor();
26
26
  sun.shadow.mapSize.set(map, map);
27
27
  sc.left = sc.bottom = -BOX; sc.right = sc.top = BOX; sc.near = 1; sc.far = 250; sc.updateProjectionMatrix();
28
- sun.shadow.bias = -0.0001; sun.shadow.normalBias = 0.04; sun.shadow.radius = radiusFor(map);
28
+ sun.shadow.bias = -0.0001; sun.shadow.normalBias = 0.025; sun.shadow.radius = radiusFor(map);
29
29
  // add: false (createEngine({ lights: false })): the objects still exist so engine.lights.sun / hemi and the sky module never hit undefined, but they
30
30
  // 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
31
31
  // 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
@@ -59,7 +59,7 @@ export function followFocus(e) {
59
59
  if (held && held !== e._oBaseFollow) return;
60
60
  // registered again whenever it is not the current one (a box came and went)
61
61
  const o = held ?? (e._oBaseFollow = defineOwned(e, {
62
- id: 'shadow.follow', part: 'shadow', key: 'follow', read: () => sun.target.position.toArray(), objects: [sun.target, sun.target.position],
62
+ id: 'shadow.follow', part: 'shadow', key: 'follow', read: out => { const p = sun.target.position; return out ? (out[0] = p.x, out[1] = p.y, out[2] = p.z, out.length = 3, out) : p.toArray(); }, objects: [sun.target, sun.target.position],
63
63
  levels: { manual: 'engine.shadows.box(engine.lights.sun, { follow: false })', back: "engine.shadows.box(engine.lights.sun, { follow: 'focus' })" } }));
64
64
  if (!o._snap) o.mark();
65
65
  o.check();
@@ -15,6 +15,7 @@
15
15
  // once the scene is drawn (_sceneDrawn), every display.pass on WebGPU renders without it.
16
16
  import * as THREE from 'three';
17
17
  import { isWebGPU, onRendererSwap } from './backend.js';
18
+ import { wrapOcclusionReadback } from './threeCompat.js';
18
19
  import { codedError } from '../core/base/errorHints.js';
19
20
  import { engineOwned } from '../core/scene/things.js';
20
21
  import { notePatch } from '../core/scene/threePatches.js';
@@ -51,8 +52,7 @@ function quietReadback(renderer) {
51
52
  quiet.add(b);
52
53
  notePatch('occlusion-readback', 'resolveOccludedAsync of the WebGPU backend, that one instance, once engine.occlusion is on: an AbortError from a buffer destroyed with the renderer is dropped', null,
53
54
  { scope: 'the renderer in use', lost: 'disposing an engine while occlusion answers are on their way reports an unhandled rejection' });
54
- const read = b.resolveOccludedAsync;
55
- b.resolveOccludedAsync = function (c) { return read.call(this, c).catch(err => { if (err?.name !== 'AbortError') throw err; }); };
55
+ wrapOcclusionReadback(b, err => err?.name === 'AbortError');
56
56
  }
57
57
 
58
58
  const unitBox = new THREE.BoxGeometry(1, 1, 1);
@@ -91,7 +91,7 @@ export class Occlusion {
91
91
  this.engine.scene.add(this._root);
92
92
  this._material ??= new THREE.MeshBasicMaterial({ colorWrite: false, depthWrite: false, side: THREE.DoubleSide });
93
93
  for (const it of this._items) this._box(it);
94
- this._hook = this.engine.onRender(() => this._frame());
94
+ this._hook = this.engine.onBeforeDraw ? this.engine.onBeforeDraw(() => this._frame()) : this.engine.onRender(() => this._frame());
95
95
  } else {
96
96
  this._hook?.remove(); this._hook = null;
97
97
  for (const it of this._items) this._unbox(it);
@@ -99,7 +99,7 @@ export class Occlusion {
99
99
  cam.layers.disable(BOX_LAYER);
100
100
  for (const [c, bits] of this._shadowBits) c.layers.mask &= ~bits;
101
101
  this._shadowBits.clear();
102
- this._last = null;
102
+ this._last = null; this._cam = null;
103
103
  }
104
104
  }
105
105
  /** What it does now: { watched, hidden, trianglesSkipped } (items, items hidden this frame, triangles not drawn this frame) */
@@ -145,15 +145,19 @@ export class Occlusion {
145
145
  it.drawn = this._frameNo;
146
146
  if (it.pending) return;
147
147
  const gl = r.getContext();
148
+ if (gl.isContextLost()) return;
148
149
  it.query ??= gl.createQuery();
150
+ if (!it.query) return;
149
151
  gl.beginQuery(gl.ANY_SAMPLES_PASSED_CONSERVATIVE, it.query);
150
152
  it.open = true;
151
153
  };
152
154
  p.onAfterRender = r => {
153
155
  if (!it.open) return;
154
156
  const gl = r.getContext();
157
+ it.open = false;
158
+ if (gl.isContextLost()) return;
155
159
  gl.endQuery(gl.ANY_SAMPLES_PASSED_CONSERVATIVE);
156
- it.open = false; it.pending = true;
160
+ it.pending = true;
157
161
  };
158
162
  }
159
163
  this._root.add(p);
@@ -174,6 +178,7 @@ export class Occlusion {
174
178
  _read(it) {
175
179
  if (!it.pending) return;
176
180
  const gl = this.engine.renderer.getContext();
181
+ if (gl.isContextLost() || !it.query) return;
177
182
  if (!gl.getQueryParameter(it.query, gl.QUERY_RESULT_AVAILABLE)) return;
178
183
  it.runs = gl.getQueryParameter(it.query, gl.QUERY_RESULT) ? 0 : it.runs + 1;
179
184
  it.pending = false;
@@ -193,18 +198,24 @@ export class Occlusion {
193
198
  */
194
199
  _shadowCameras(cam) {
195
200
  const want = (cam.layers.mask & ~(1 << BOX_LAYER)) | (1 << HIDDEN_LAYER);
201
+ const seen = new Set();
196
202
  // OR, never a plain write: a shadow camera can hold layers of its own (a first-person body on the camera's hide layer). Only what was added is noted, so off takes back no more
197
203
  const add = l => {
198
- const c = l.shadow?.camera, bits = c ? want & ~c.layers.mask : 0;
204
+ const c = l.shadow?.camera;
205
+ if (!c) return;
206
+ seen.add(c);
207
+ const bits = want & ~c.layers.mask;
199
208
  if (bits) { c.layers.mask |= bits; this._shadowBits.set(c, (this._shadowBits.get(c) ?? 0) | bits); }
200
209
  };
201
210
  this.engine.scene.traverse(o => { if (o.isLight && o.castShadow) { add(o); o.shadow?.shadowNode?.lights?.forEach(add); } });
211
+ for (const [c, bits] of this._shadowBits) if (!seen.has(c)) { c.layers.mask &= ~bits; this._shadowBits.delete(c); }
202
212
  }
203
213
  /** The WebGL chain, right after its scene render: the passes after it may render this camera again (outline's views, GTAO's normals, a game's Pass); _frame puts the layer back @internal */
204
214
  _sceneDrawn() { if (this._on) this.engine.camera.layers.disable(BOX_LAYER); }
205
215
  /** Once a frame, before the render: read what the last frames saw, decide who is drawn, place the boxes @internal */
206
216
  _frame() {
207
217
  const cam = this.engine.camera, n = ++this._frameNo;
218
+ if (this._cam && this._cam !== cam) this._cam.layers.disable(BOX_LAYER);
208
219
  cam.layers.enable(BOX_LAYER);
209
220
  cam.getWorldPosition(here);
210
221
  const moved = this._last && cam === this._cam ? here.distanceTo(this._last) : Infinity;