@vgai/engine 0.5.13 → 0.5.14

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 (192) hide show
  1. package/dist/adapter/adapter-module.d.ts +447 -0
  2. package/dist/adapter/adapter-module.d.ts.map +1 -0
  3. package/dist/adapter/adapter-module.js +308 -0
  4. package/dist/adapter/authoring.d.ts +357 -10
  5. package/dist/adapter/authoring.d.ts.map +1 -1
  6. package/dist/adapter/authoring.js +87 -1
  7. package/dist/adapter/constraint.d.ts +9 -3
  8. package/dist/adapter/constraint.d.ts.map +1 -1
  9. package/dist/adapter/finders/finder-result.d.ts +28 -0
  10. package/dist/adapter/finders/finder-result.d.ts.map +1 -0
  11. package/dist/adapter/finders/finder-result.js +10 -0
  12. package/dist/adapter/finders/index.d.ts +38 -0
  13. package/dist/adapter/finders/index.d.ts.map +1 -0
  14. package/dist/adapter/finders/index.js +41 -0
  15. package/dist/adapter/finders/prefabs-from-stories.d.ts +64 -0
  16. package/dist/adapter/finders/prefabs-from-stories.d.ts.map +1 -0
  17. package/dist/adapter/finders/prefabs-from-stories.js +92 -0
  18. package/dist/adapter/finders/scenes-from-entrypoint-selection.d.ts +67 -0
  19. package/dist/adapter/finders/scenes-from-entrypoint-selection.d.ts.map +1 -0
  20. package/dist/adapter/finders/scenes-from-entrypoint-selection.js +226 -0
  21. package/dist/adapter/first-party-systems.d.ts.map +1 -1
  22. package/dist/adapter/first-party-systems.js +29 -0
  23. package/dist/adapter/index.d.ts +7 -3
  24. package/dist/adapter/index.d.ts.map +1 -1
  25. package/dist/adapter/index.js +5 -2
  26. package/dist/adapter/ingest/contract-system-adapters.d.ts +24 -1
  27. package/dist/adapter/ingest/contract-system-adapters.d.ts.map +1 -1
  28. package/dist/adapter/ingest/contract-system-adapters.js +100 -34
  29. package/dist/adapter/ingest/game-contract.d.ts +188 -2
  30. package/dist/adapter/ingest/game-contract.d.ts.map +1 -1
  31. package/dist/adapter/ingest/game-contract.js +107 -0
  32. package/dist/adapter/ingest/mount-readiness.d.ts +84 -0
  33. package/dist/adapter/ingest/mount-readiness.d.ts.map +1 -0
  34. package/dist/adapter/ingest/mount-readiness.js +81 -0
  35. package/dist/adapter/ingest/scene-capture.d.ts +91 -2
  36. package/dist/adapter/ingest/scene-capture.d.ts.map +1 -1
  37. package/dist/adapter/ingest/scene-capture.js +110 -18
  38. package/dist/adapter/ingest/structural-ids.d.ts +11 -5
  39. package/dist/adapter/ingest/structural-ids.d.ts.map +1 -1
  40. package/dist/adapter/ingest/structural-ids.js +18 -9
  41. package/dist/adapter/ingest/upstream-pin.d.ts +4 -2
  42. package/dist/adapter/ingest/upstream-pin.d.ts.map +1 -1
  43. package/dist/adapter/ingest/upstream-pin.js +4 -2
  44. package/dist/adapter/ingest/visible-capture-window.d.ts +116 -0
  45. package/dist/adapter/ingest/visible-capture-window.d.ts.map +1 -0
  46. package/dist/adapter/ingest/visible-capture-window.js +141 -0
  47. package/dist/adapter/loop-gate-report.d.ts +3 -4
  48. package/dist/adapter/loop-gate-report.d.ts.map +1 -1
  49. package/dist/adapter/loop-gate-report.js +3 -4
  50. package/dist/adapter/root-adapter.d.ts +22 -2
  51. package/dist/adapter/root-adapter.d.ts.map +1 -1
  52. package/dist/adapter/setup-three-root-adapter.d.ts.map +1 -1
  53. package/dist/adapter/setup-three-root-adapter.js +15 -0
  54. package/dist/adapter/system-adapter.d.ts +161 -2
  55. package/dist/adapter/system-adapter.d.ts.map +1 -1
  56. package/dist/adapter/system-adapter.js +18 -1
  57. package/dist/animation/camera-ownership.d.ts +4 -2
  58. package/dist/animation/camera-ownership.d.ts.map +1 -1
  59. package/dist/animation/camera-ownership.js +58 -1
  60. package/dist/animation/runtime-inspection.d.ts +70 -0
  61. package/dist/animation/runtime-inspection.d.ts.map +1 -0
  62. package/dist/animation/runtime-inspection.js +25 -0
  63. package/dist/animation/xstate-animation-binding.d.ts +9 -1
  64. package/dist/animation/xstate-animation-binding.d.ts.map +1 -1
  65. package/dist/animation/xstate-animation-binding.js +48 -1
  66. package/dist/asset-formats/material.d.ts +1 -1
  67. package/dist/asset-formats/mesh.d.ts +1 -1
  68. package/dist/asset-formats/particles.d.ts +13 -0
  69. package/dist/asset-formats/particles.d.ts.map +1 -1
  70. package/dist/asset-formats/particles.js +28 -0
  71. package/dist/behavior/xstate-inspection.d.ts +24 -0
  72. package/dist/behavior/xstate-inspection.d.ts.map +1 -0
  73. package/dist/behavior/xstate-inspection.js +25 -0
  74. package/dist/core/game-loop.d.ts +7 -5
  75. package/dist/core/game-loop.d.ts.map +1 -1
  76. package/dist/core/game-loop.js +39 -18
  77. package/dist/core/types.d.ts +11 -12
  78. package/dist/core/types.d.ts.map +1 -1
  79. package/dist/data/data-asset.js +1 -1
  80. package/dist/dev/instruments.d.ts.map +1 -1
  81. package/dist/dev/instruments.js +5 -1
  82. package/dist/dev/render-debug-adapter.d.ts +19 -2
  83. package/dist/dev/render-debug-adapter.d.ts.map +1 -1
  84. package/dist/dev/render-debug-adapter.js +10 -0
  85. package/dist/ecs/user-data.d.ts +10 -2
  86. package/dist/ecs/user-data.d.ts.map +1 -1
  87. package/dist/ecs/user-data.js +6 -2
  88. package/dist/input/binding-identity.d.ts +10 -0
  89. package/dist/input/binding-identity.d.ts.map +1 -0
  90. package/dist/input/binding-identity.js +36 -0
  91. package/dist/input/input-manager.d.ts +18 -185
  92. package/dist/input/input-manager.d.ts.map +1 -1
  93. package/dist/input/input-manager.js +78 -68
  94. package/dist/manifest/load.d.ts +14 -0
  95. package/dist/manifest/load.d.ts.map +1 -1
  96. package/dist/manifest/load.js +6 -1
  97. package/dist/manifest/schema.d.ts +18 -0
  98. package/dist/manifest/schema.d.ts.map +1 -1
  99. package/dist/manifest/schema.js +64 -7
  100. package/dist/pixi/authoring.d.ts +27 -0
  101. package/dist/pixi/authoring.d.ts.map +1 -1
  102. package/dist/pixi/authoring.js +10 -3
  103. package/dist/pixi/index.d.ts +1 -1
  104. package/dist/pixi/index.d.ts.map +1 -1
  105. package/dist/pixi/index.js +1 -1
  106. package/dist/pixi/ingest.d.ts +8 -0
  107. package/dist/pixi/ingest.d.ts.map +1 -1
  108. package/dist/pixi/ingest.js +10 -1
  109. package/dist/pixi/render-pass-bracket.d.ts +56 -0
  110. package/dist/pixi/render-pass-bracket.d.ts.map +1 -0
  111. package/dist/pixi/render-pass-bracket.js +98 -0
  112. package/dist/pixi/scene-capture.d.ts +32 -1
  113. package/dist/pixi/scene-capture.d.ts.map +1 -1
  114. package/dist/pixi/scene-capture.js +21 -9
  115. package/dist/pixi/system-adapters.d.ts +29 -0
  116. package/dist/pixi/system-adapters.d.ts.map +1 -1
  117. package/dist/pixi/system-adapters.js +27 -0
  118. package/dist/render/particles-factory.d.ts +16 -2
  119. package/dist/render/particles-factory.d.ts.map +1 -1
  120. package/dist/render/particles-factory.js +88 -5
  121. package/dist/render/soft-particle-depth.d.ts +149 -0
  122. package/dist/render/soft-particle-depth.d.ts.map +1 -0
  123. package/dist/render/soft-particle-depth.js +305 -0
  124. package/dist/render/voxel-surface.d.ts +117 -0
  125. package/dist/render/voxel-surface.d.ts.map +1 -0
  126. package/dist/render/voxel-surface.js +263 -0
  127. package/dist/runtime/create-runtime.js +7 -0
  128. package/dist/runtime/debug-bridge.d.ts +15 -15
  129. package/dist/runtime/debug-bridge.d.ts.map +1 -1
  130. package/dist/runtime/debug-bridge.js +27 -26
  131. package/dist/runtime/game.d.ts.map +1 -1
  132. package/dist/runtime/game.js +1 -2
  133. package/dist/setup/setup-particles.d.ts.map +1 -1
  134. package/dist/setup/setup-particles.js +9 -0
  135. package/dist/world3d-react/r3f-adapter.d.ts.map +1 -1
  136. package/dist/world3d-react/r3f-adapter.js +42 -3
  137. package/dist/world3d-react/rapier-physics-bridge.d.ts.map +1 -1
  138. package/dist/world3d-react/rapier-physics-bridge.js +201 -11
  139. package/dist-config/config.js.map +1 -1
  140. package/package.json +4 -2
  141. package/schemas/engine-capabilities.json +12 -12
  142. package/schemas/vgai-project.schema.json +41 -2
  143. package/src/adapter/adapter-module.ts +607 -0
  144. package/src/adapter/authoring.ts +440 -10
  145. package/src/adapter/constraint.ts +10 -3
  146. package/src/adapter/finders/finder-result.ts +29 -0
  147. package/src/adapter/finders/index.ts +62 -0
  148. package/src/adapter/finders/prefabs-from-stories.ts +142 -0
  149. package/src/adapter/finders/scenes-from-entrypoint-selection.ts +304 -0
  150. package/src/adapter/first-party-systems.ts +30 -0
  151. package/src/adapter/index.ts +32 -1
  152. package/src/adapter/ingest/contract-system-adapters.ts +116 -32
  153. package/src/adapter/ingest/game-contract.ts +265 -2
  154. package/src/adapter/ingest/mount-readiness.ts +140 -0
  155. package/src/adapter/ingest/scene-capture.ts +199 -22
  156. package/src/adapter/ingest/structural-ids.ts +21 -9
  157. package/src/adapter/ingest/upstream-pin.ts +4 -2
  158. package/src/adapter/ingest/visible-capture-window.ts +213 -0
  159. package/src/adapter/loop-gate-report.ts +3 -4
  160. package/src/adapter/root-adapter.ts +22 -2
  161. package/src/adapter/setup-three-root-adapter.ts +16 -0
  162. package/src/adapter/system-adapter.ts +188 -2
  163. package/src/animation/camera-ownership.ts +68 -3
  164. package/src/animation/runtime-inspection.ts +104 -0
  165. package/src/animation/xstate-animation-binding.ts +53 -1
  166. package/src/asset-formats/particles.ts +31 -0
  167. package/src/behavior/xstate-inspection.ts +51 -0
  168. package/src/core/game-loop.ts +39 -17
  169. package/src/core/types.ts +11 -12
  170. package/src/data/data-asset.ts +1 -1
  171. package/src/dev/instruments.ts +5 -1
  172. package/src/dev/render-debug-adapter.ts +22 -2
  173. package/src/ecs/user-data.ts +10 -2
  174. package/src/input/binding-identity.ts +37 -0
  175. package/src/input/input-manager.ts +93 -68
  176. package/src/manifest/load.ts +23 -2
  177. package/src/manifest/schema.ts +76 -7
  178. package/src/pixi/authoring.ts +37 -5
  179. package/src/pixi/index.ts +2 -0
  180. package/src/pixi/ingest.ts +15 -2
  181. package/src/pixi/render-pass-bracket.ts +117 -0
  182. package/src/pixi/scene-capture.ts +63 -13
  183. package/src/pixi/system-adapters.ts +41 -0
  184. package/src/render/particles-factory.ts +89 -6
  185. package/src/render/soft-particle-depth.ts +336 -0
  186. package/src/render/voxel-surface.ts +358 -0
  187. package/src/runtime/create-runtime.ts +7 -0
  188. package/src/runtime/debug-bridge.ts +32 -31
  189. package/src/runtime/game.ts +1 -2
  190. package/src/setup/setup-particles.ts +9 -0
  191. package/src/world3d-react/r3f-adapter.tsx +48 -2
  192. package/src/world3d-react/rapier-physics-bridge.tsx +249 -11
@@ -2,13 +2,16 @@
2
2
  /**
3
3
  * Converts ParticlesDescriptor JSON → three.quarks ParticleSystem.
4
4
  *
5
- * Shared between the editor entity-factory and the runtime scene-loader.
5
+ * A published engine entry point (the export map is the wildcard `./*`): the
6
+ * one in-repo caller is the godot-compat capability's `createCpuParticles3D`,
7
+ * and user games outside this repo reach it directly.
6
8
  * The schema mirrors quarks' native JSON format, so most fields pass through
7
9
  * directly to quarks' fromJSON or constructor methods.
8
10
  */
9
11
  import { ApplyForce, ChangeEmitDirection, CircleEmitter, ColorGeneratorFromJSON, ColorOverLife, ConeEmitter, DonutEmitter, ForceOverLife, FrameOverLife, GravityForce, GridEmitter, HemisphereEmitter, LimitSpeedOverLife, Noise, OrbitOverLife, PointEmitter, Vector3 as QVector3, RectangleEmitter, RotationOverLife, SizeOverLife, SpeedOverLife, SphereEmitter, TurbulenceField, ValueGeneratorFromJSON, WidthOverLength, } from 'quarks.core';
10
12
  import * as THREE from 'three';
11
13
  import { ParticleSystem, RenderMode } from 'three.quarks';
14
+ import { armSoftParticleDepth, disarmSoftParticleDepth } from './soft-particle-depth';
12
15
  // --- Render mode mapping ---
13
16
  const RENDER_MODE_MAP = {
14
17
  billboard: RenderMode.BillBoard,
@@ -20,15 +23,79 @@ const RENDER_MODE_MAP = {
20
23
  };
21
24
  // --- Texture loader (shared cache) ---
22
25
  import { textureLoader } from '../loader';
26
+ const WRAP = {
27
+ clamp: THREE.ClampToEdgeWrapping,
28
+ repeat: THREE.RepeatWrapping,
29
+ mirror: THREE.MirroredRepeatWrapping,
30
+ };
31
+ /** `minFilter` is where the two sampler axes MEET — `filter` chooses linear vs nearest and
32
+ * `mipmaps` chooses whether the mip chain is sampled at all — and three spells the four
33
+ * combinations as four constants. A table rather than nested conditionals, which read as a
34
+ * puzzle. (`magFilter` has no mip half; it is the `filter` axis alone.) */
35
+ const MIN_FILTER = {
36
+ 'linear/mips': THREE.LinearMipmapLinearFilter,
37
+ 'linear/no-mips': THREE.LinearFilter,
38
+ 'nearest/mips': THREE.NearestMipmapNearestFilter,
39
+ 'nearest/no-mips': THREE.NearestFilter,
40
+ };
23
41
  const particleTexCache = new Map();
24
- function loadParticleTexture(url) {
25
- const cached = particleTexCache.get(url);
42
+ /**
43
+ * The sprite texture for a material's `map`, loaded once per URL+sampler.
44
+ *
45
+ * Two things are decided here rather than left to three's loader defaults:
46
+ *
47
+ * - **COLOUR SPACE.** `THREE.TextureLoader` leaves `colorSpace` at `NoColorSpace`, which tells
48
+ * three the texels are already linear — so an ordinary sRGB PNG sprite is composited
49
+ * UNDECODED and every mid-tone comes out far too bright. A `map` is a colour texture by
50
+ * definition (three's own `GLTFLoader` states `SRGBColorSpace` on `baseColorTexture` for the
51
+ * same reason), so this states sRGB unconditionally. It is not a descriptor field: there is no
52
+ * correct second value for this slot. Measured 2026-08-14 against real Godot 3.6/GLES3 — a
53
+ * 128,128,128 sprite read back 0.5015 there and 0.7373 here, and after this line 0.5019; the
54
+ * whole A/B is in `godot-compat/cpu-particles-3d.ts`'s header.
55
+ * - **SAMPLER.** `material.mapSampler`, when the descriptor carries one. The cache key includes
56
+ * it because two emitters may name ONE image and want different sampling of it — a URL-only
57
+ * key would hand the second one the first's configured texture.
58
+ *
59
+ * `flipY` is deliberately untouched: the billboard quad this shader draws is built by
60
+ * `three.quarks` with three's own V-up UVs, so three's `flipY = true` is the consistent half of
61
+ * that pair.
62
+ */
63
+ function loadParticleTexture(url, sampler) {
64
+ const key = sampler === undefined ? url : `${url}\u0000${JSON.stringify(sampler)}`;
65
+ const cached = particleTexCache.get(key);
26
66
  if (cached)
27
67
  return cached;
28
68
  const tex = textureLoader.load(url);
29
- particleTexCache.set(url, tex);
69
+ tex.colorSpace = THREE.SRGBColorSpace;
70
+ if (sampler !== undefined)
71
+ applyMapSampler(tex, sampler);
72
+ particleTexCache.set(key, tex);
30
73
  return tex;
31
74
  }
75
+ /** One `mapSampler` onto three's own texture properties. An unstated field is left at three's
76
+ * default rather than restated — see {@link loadParticleTexture}. */
77
+ function applyMapSampler(tex, sampler) {
78
+ if (sampler.wrap !== undefined) {
79
+ tex.wrapS = WRAP[sampler.wrap];
80
+ tex.wrapT = WRAP[sampler.wrap];
81
+ }
82
+ if (sampler.filter !== undefined || sampler.mipmaps !== undefined) {
83
+ // An unstated axis takes three's own default, which is linear and mipmapped.
84
+ const filter = sampler.filter ?? 'linear';
85
+ const mips = sampler.mipmaps === false ? 'no-mips' : 'mips';
86
+ if (sampler.filter !== undefined) {
87
+ tex.magFilter = filter === 'linear' ? THREE.LinearFilter : THREE.NearestFilter;
88
+ }
89
+ tex.minFilter = MIN_FILTER[`${filter}/${mips}`];
90
+ }
91
+ if (sampler.mipmaps !== undefined)
92
+ tex.generateMipmaps = sampler.mipmaps;
93
+ // Anisotropy rides through unclamped: three's own `WebGLTextures` uploads
94
+ // `Math.min(texture.anisotropy, capabilities.getMaxAnisotropy())`, so the renderer's real
95
+ // capability is what binds and a second clamp here would have no effect.
96
+ if (sampler.anisotropy !== undefined)
97
+ tex.anisotropy = sampler.anisotropy;
98
+ }
32
99
  // --- Helpers ---
33
100
  /** Strip keys with undefined values so exactOptionalPropertyTypes is satisfied. */
34
101
  function defined(obj) {
@@ -116,7 +183,7 @@ function createBehavior(json) {
116
183
  function createParticleMaterial(mat) {
117
184
  const textures = {};
118
185
  if (mat.map)
119
- textures['map'] = loadParticleTexture(mat.map);
186
+ textures['map'] = loadParticleTexture(mat.map, mat.mapSampler);
120
187
  const blending = mat.blending === 'normal' ? THREE.NormalBlending : THREE.AdditiveBlending;
121
188
  const transparent = mat.transparent !== false;
122
189
  const depthWrite = mat.depthWrite ?? false;
@@ -316,15 +383,31 @@ export function scrubParticleSystemTo(system, time, step = 1 / 60) {
316
383
  }
317
384
  /**
318
385
  * Register a particle system with a BatchedRenderer.
386
+ *
387
+ * This is also the ONE seat that arms the scene-depth prepass: a system built
388
+ * with `softParticles` compiles its batch with three.quarks' `SOFT_PARTICLES`
389
+ * define, which samples a `depthTexture` uniform nothing else in this engine
390
+ * would ever fill (see `render/soft-particle-depth.ts` for what an unfilled one
391
+ * does to the frame). Arming here — rather than in
392
+ * {@link createParticleSystemFromData} — is what makes it correct: the uniform
393
+ * lives on the BATCH, and no batch exists until a renderer is handed the
394
+ * system.
319
395
  */
320
396
  export function registerParticleSystem(batchedRenderer, system) {
321
397
  batchedRenderer.addSystem(system);
398
+ if (system.softParticles)
399
+ armSoftParticleDepth(batchedRenderer);
322
400
  }
323
401
  /**
324
402
  * Unregister a particle system from a BatchedRenderer.
403
+ *
404
+ * Disarms the depth prepass — one decrement against the arming above, so a
405
+ * renderer hosting several soft systems stays armed until its last one leaves.
325
406
  */
326
407
  export function unregisterParticleSystem(batchedRenderer, system) {
327
408
  batchedRenderer.deleteSystem(system);
409
+ if (system.softParticles)
410
+ disarmSoftParticleDepth(batchedRenderer);
328
411
  }
329
412
  /**
330
413
  * Default particle data for creating a new particle emitter via AddSectionMenu.
@@ -0,0 +1,149 @@
1
+ /**
2
+ * Scene DEPTH for three.quarks' soft particles — the pass that makes
3
+ * `ParticlesDescriptor.softParticles` a real effect instead of a footgun.
4
+ *
5
+ * ## What three.quarks needs, and what it does when nobody supplies it
6
+ *
7
+ * A batch built with `softParticles` compiles its fragment stage with
8
+ * `SOFT_PARTICLES` defined, which brings in these two chunks verbatim
9
+ * (`three.quarks@0.16.0`, `src/shaders/chunks/soft_pars_fragment.glsl.ts` and
10
+ * `soft_fragment.glsl.ts`):
11
+ *
12
+ * ```glsl
13
+ * uniform sampler2D depthTexture;
14
+ * uniform vec4 projParams;
15
+ * uniform vec2 softParams;
16
+ *
17
+ * varying vec4 projPosition;
18
+ * varying float linearDepth;
19
+ *
20
+ * #define SOFT_NEAR_FADE softParams.x
21
+ * #define SOFT_INV_FADE_DISTANCE softParams.y
22
+ *
23
+ * #define zNear projParams.x
24
+ * #define zFar projParams.y
25
+ *
26
+ * float linearize_depth(float d)
27
+ * {
28
+ * return (zFar * zNear) / (zFar - d * (zFar - zNear));
29
+ * }
30
+ * ```
31
+ *
32
+ * ```glsl
33
+ * vec2 p2 = projPosition.xy / projPosition.w;
34
+ *
35
+ * p2 = 0.5 * p2 + 0.5;
36
+ *
37
+ * float readDepth = texture2D(depthTexture, p2.xy).r;
38
+ * float viewDepth = linearize_depth(readDepth);
39
+ *
40
+ * float softParticlesFade = saturate(SOFT_INV_FADE_DISTANCE * ((viewDepth - SOFT_NEAR_FADE) - linearDepth));
41
+ *
42
+ * gl_FragColor *= softParticlesFade;
43
+ * ```
44
+ *
45
+ * `depthTexture` is a `new Uniform(null)` until something calls
46
+ * `BatchedRenderer.setDepthTexture` / `VFXBatch.applyDepthTexture`
47
+ * (`BatchedRenderer.ts:191-196`, `VFXBatch.ts:93-101`). With it null the sampler
48
+ * reads black, `readDepth` is `0`, `viewDepth` collapses to `zNear`, and
49
+ * `softParticlesFade` saturates to `0` — every particle multiplied away. That is
50
+ * the failure this module exists to make impossible: {@link farDepthTexture} is
51
+ * bound to every `BatchedRenderer` this engine constructs, so the WORST case is
52
+ * `readDepth = 1` ⇒ `viewDepth = zFar` ⇒ fade `1`, i.e. pixel-identical to a
53
+ * batch that never had `SOFT_PARTICLES` at all.
54
+ *
55
+ * ## The pass, and what it costs
56
+ *
57
+ * The fade needs the depth of the geometry BEHIND the particle, which cannot be
58
+ * the depth attachment the particle is being drawn into (sampling a texture
59
+ * attached to the bound framebuffer is a feedback loop). So it is a real
60
+ * PREPASS: one extra `renderer.render(scene, camera)` into a depth-only target,
61
+ * with the armed particle renderers and every transparent surface hidden and a
62
+ * colour-write-disabled override material in place.
63
+ *
64
+ * That cost is paid ONLY while something is armed. {@link armSoftParticleDepth}
65
+ * is called from `particles-factory.ts`'s `registerParticleSystem` when the
66
+ * system it is registering asked for `softParticles`; with the registry empty
67
+ * {@link SoftParticleDepthPass.render} returns before it touches the scene, so a
68
+ * world with no soft particles pays one `Set.size` read per frame and nothing
69
+ * else. Armed, per frame per camera it costs: one scene traverse (to find the
70
+ * transparent surfaces to hide), one extra geometry-only scene draw with shadow
71
+ * updates suppressed, and a drawing-buffer-sized depth target
72
+ * (`UnsignedIntType` depth + an unread RGBA8 colour attachment ≈ 8
73
+ * bytes/pixel).
74
+ *
75
+ * ## Why TRANSPARENT surfaces are hidden
76
+ *
77
+ * Godot's own `DEPTH_TEXTURE` — the one `proximity_fade_enabled` samples — is
78
+ * the OPAQUE pass's depth: `BaseMaterial3D`'s default `depth_draw_opaque` means
79
+ * a transparent material contributes no depth. Reproducing that is not
80
+ * cosmetic; without it the starter kit's coin would fade its stars against the
81
+ * translucent glow quad sitting in front of them rather than against the floor.
82
+ *
83
+ * ## Resource ownership
84
+ *
85
+ * - {@link farDepthTexture}'s 1x1 texture is a module singleton, created on
86
+ * first use and NEVER disposed: it is bound into every renderer's uniforms as
87
+ * the safe default, so there is no moment at which the last user is known.
88
+ * One texel, one allocation per process.
89
+ * - The armed-renderer registry is written by exactly two functions,
90
+ * {@link armSoftParticleDepth} / {@link disarmSoftParticleDepth}, whose only
91
+ * callers are `registerParticleSystem` / `unregisterParticleSystem`.
92
+ * - The render target and override material belong to the
93
+ * {@link SoftParticleDepthPass} instance and die with its `dispose()`. The
94
+ * pass itself is owned by whichever adapter mount created it (the R3F adapter
95
+ * and `setup-three-root-adapter`), and that mount's teardown is the one path
96
+ * allowed to end it.
97
+ */
98
+ import * as THREE from 'three';
99
+ import type { BatchedRenderer } from 'three.quarks';
100
+ /**
101
+ * A 1x1 texture whose red channel is 1.0 — "the depth buffer says nothing is in
102
+ * front of anything".
103
+ *
104
+ * Bound to a `BatchedRenderer` the moment it is constructed, so a batch that
105
+ * later compiles with `SOFT_PARTICLES` inherits it (`BatchedRenderer.addSystem`
106
+ * applies `this.depthTexture` to each batch it creates). Feeding
107
+ * `linearize_depth` a `1.0` yields `(zFar * zNear) / (zFar - (zFar - zNear))`,
108
+ * which is `zFar`, so the fade term is `saturate(k * (zFar - linearDepth))` — 1
109
+ * for every fragment in front of the far plane. The fade is INERT rather than
110
+ * wrong, which is what makes an undriven surface (a design-time preview, a host
111
+ * with no pass) render exactly as it did before soft particles existed.
112
+ */
113
+ export declare function farDepthTexture(): THREE.DataTexture;
114
+ /** Record that `renderer` hosts one more soft-particle system, so passes stop skipping it. */
115
+ export declare function armSoftParticleDepth(renderer: BatchedRenderer): void;
116
+ /**
117
+ * The other half of {@link armSoftParticleDepth}. On the LAST soft system the
118
+ * renderer is dropped from the registry and handed the inert far-depth default
119
+ * back, so a batch that outlives its registration never keeps sampling a scene
120
+ * depth nobody is refreshing.
121
+ */
122
+ export declare function disarmSoftParticleDepth(renderer: BatchedRenderer): void;
123
+ /** Test/diagnostic read of the registry — how many renderers a pass would consider. */
124
+ export declare function armedSoftParticleRendererCount(): number;
125
+ /** The subset of `THREE.WebGLRenderer` this pass drives, so a host can supply its own. */
126
+ export interface SoftParticleDepthRenderer {
127
+ getDrawingBufferSize(target: THREE.Vector2): THREE.Vector2;
128
+ getRenderTarget(): THREE.WebGLRenderTarget | null;
129
+ setRenderTarget(target: THREE.WebGLRenderTarget | null): void;
130
+ render(scene: THREE.Object3D, camera: THREE.Camera): void;
131
+ /** Optional because a stub renderer legitimately has none — see {@link SoftParticleDepthPass}. */
132
+ readonly shadowMap?: {
133
+ autoUpdate: boolean;
134
+ needsUpdate: boolean;
135
+ };
136
+ }
137
+ export interface SoftParticleDepthPass {
138
+ /**
139
+ * Draw scene depth and hand it to every armed renderer under `scene`.
140
+ *
141
+ * A no-op — not one draw call, not one traversal — while nothing is armed.
142
+ * Call it after gameplay has moved the frame's transforms and before the
143
+ * frame is drawn.
144
+ */
145
+ render(renderer: SoftParticleDepthRenderer, scene: THREE.Scene, camera: THREE.Camera): void;
146
+ dispose(): void;
147
+ }
148
+ export declare function createSoftParticleDepthPass(): SoftParticleDepthPass;
149
+ //# sourceMappingURL=soft-particle-depth.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"soft-particle-depth.d.ts","sourceRoot":"","sources":["../../src/render/soft-particle-depth.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgGG;AAEH,OAAO,KAAK,KAAK,MAAM,OAAO,CAAC;AAC/B,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC;AAepD;;;;;;;;;;;;GAYG;AACH,wBAAgB,eAAe,IAAI,KAAK,CAAC,WAAW,CAOnD;AAED,8FAA8F;AAC9F,wBAAgB,oBAAoB,CAAC,QAAQ,EAAE,eAAe,GAAG,IAAI,CAEpE;AAED;;;;;GAKG;AACH,wBAAgB,uBAAuB,CAAC,QAAQ,EAAE,eAAe,GAAG,IAAI,CAQvE;AAED,uFAAuF;AACvF,wBAAgB,8BAA8B,IAAI,MAAM,CAEvD;AAED,0FAA0F;AAC1F,MAAM,WAAW,yBAAyB;IACxC,oBAAoB,CAAC,MAAM,EAAE,KAAK,CAAC,OAAO,GAAG,KAAK,CAAC,OAAO,CAAC;IAC3D,eAAe,IAAI,KAAK,CAAC,iBAAiB,GAAG,IAAI,CAAC;IAClD,eAAe,CAAC,MAAM,EAAE,KAAK,CAAC,iBAAiB,GAAG,IAAI,GAAG,IAAI,CAAC;IAC9D,MAAM,CAAC,KAAK,EAAE,KAAK,CAAC,QAAQ,EAAE,MAAM,EAAE,KAAK,CAAC,MAAM,GAAG,IAAI,CAAC;IAC1D,kGAAkG;IAClG,QAAQ,CAAC,SAAS,CAAC,EAAE;QAAE,UAAU,EAAE,OAAO,CAAC;QAAC,WAAW,EAAE,OAAO,CAAA;KAAE,CAAC;CACpE;AAED,MAAM,WAAW,qBAAqB;IACpC;;;;;;OAMG;IACH,MAAM,CAAC,QAAQ,EAAE,yBAAyB,EAAE,KAAK,EAAE,KAAK,CAAC,KAAK,EAAE,MAAM,EAAE,KAAK,CAAC,MAAM,GAAG,IAAI,CAAC;IAC5F,OAAO,IAAI,IAAI,CAAC;CACjB;AA+CD,wBAAgB,2BAA2B,IAAI,qBAAqB,CA0GnE"}
@@ -0,0 +1,305 @@
1
+ /**
2
+ * Scene DEPTH for three.quarks' soft particles — the pass that makes
3
+ * `ParticlesDescriptor.softParticles` a real effect instead of a footgun.
4
+ *
5
+ * ## What three.quarks needs, and what it does when nobody supplies it
6
+ *
7
+ * A batch built with `softParticles` compiles its fragment stage with
8
+ * `SOFT_PARTICLES` defined, which brings in these two chunks verbatim
9
+ * (`three.quarks@0.16.0`, `src/shaders/chunks/soft_pars_fragment.glsl.ts` and
10
+ * `soft_fragment.glsl.ts`):
11
+ *
12
+ * ```glsl
13
+ * uniform sampler2D depthTexture;
14
+ * uniform vec4 projParams;
15
+ * uniform vec2 softParams;
16
+ *
17
+ * varying vec4 projPosition;
18
+ * varying float linearDepth;
19
+ *
20
+ * #define SOFT_NEAR_FADE softParams.x
21
+ * #define SOFT_INV_FADE_DISTANCE softParams.y
22
+ *
23
+ * #define zNear projParams.x
24
+ * #define zFar projParams.y
25
+ *
26
+ * float linearize_depth(float d)
27
+ * {
28
+ * return (zFar * zNear) / (zFar - d * (zFar - zNear));
29
+ * }
30
+ * ```
31
+ *
32
+ * ```glsl
33
+ * vec2 p2 = projPosition.xy / projPosition.w;
34
+ *
35
+ * p2 = 0.5 * p2 + 0.5;
36
+ *
37
+ * float readDepth = texture2D(depthTexture, p2.xy).r;
38
+ * float viewDepth = linearize_depth(readDepth);
39
+ *
40
+ * float softParticlesFade = saturate(SOFT_INV_FADE_DISTANCE * ((viewDepth - SOFT_NEAR_FADE) - linearDepth));
41
+ *
42
+ * gl_FragColor *= softParticlesFade;
43
+ * ```
44
+ *
45
+ * `depthTexture` is a `new Uniform(null)` until something calls
46
+ * `BatchedRenderer.setDepthTexture` / `VFXBatch.applyDepthTexture`
47
+ * (`BatchedRenderer.ts:191-196`, `VFXBatch.ts:93-101`). With it null the sampler
48
+ * reads black, `readDepth` is `0`, `viewDepth` collapses to `zNear`, and
49
+ * `softParticlesFade` saturates to `0` — every particle multiplied away. That is
50
+ * the failure this module exists to make impossible: {@link farDepthTexture} is
51
+ * bound to every `BatchedRenderer` this engine constructs, so the WORST case is
52
+ * `readDepth = 1` ⇒ `viewDepth = zFar` ⇒ fade `1`, i.e. pixel-identical to a
53
+ * batch that never had `SOFT_PARTICLES` at all.
54
+ *
55
+ * ## The pass, and what it costs
56
+ *
57
+ * The fade needs the depth of the geometry BEHIND the particle, which cannot be
58
+ * the depth attachment the particle is being drawn into (sampling a texture
59
+ * attached to the bound framebuffer is a feedback loop). So it is a real
60
+ * PREPASS: one extra `renderer.render(scene, camera)` into a depth-only target,
61
+ * with the armed particle renderers and every transparent surface hidden and a
62
+ * colour-write-disabled override material in place.
63
+ *
64
+ * That cost is paid ONLY while something is armed. {@link armSoftParticleDepth}
65
+ * is called from `particles-factory.ts`'s `registerParticleSystem` when the
66
+ * system it is registering asked for `softParticles`; with the registry empty
67
+ * {@link SoftParticleDepthPass.render} returns before it touches the scene, so a
68
+ * world with no soft particles pays one `Set.size` read per frame and nothing
69
+ * else. Armed, per frame per camera it costs: one scene traverse (to find the
70
+ * transparent surfaces to hide), one extra geometry-only scene draw with shadow
71
+ * updates suppressed, and a drawing-buffer-sized depth target
72
+ * (`UnsignedIntType` depth + an unread RGBA8 colour attachment ≈ 8
73
+ * bytes/pixel).
74
+ *
75
+ * ## Why TRANSPARENT surfaces are hidden
76
+ *
77
+ * Godot's own `DEPTH_TEXTURE` — the one `proximity_fade_enabled` samples — is
78
+ * the OPAQUE pass's depth: `BaseMaterial3D`'s default `depth_draw_opaque` means
79
+ * a transparent material contributes no depth. Reproducing that is not
80
+ * cosmetic; without it the starter kit's coin would fade its stars against the
81
+ * translucent glow quad sitting in front of them rather than against the floor.
82
+ *
83
+ * ## Resource ownership
84
+ *
85
+ * - {@link farDepthTexture}'s 1x1 texture is a module singleton, created on
86
+ * first use and NEVER disposed: it is bound into every renderer's uniforms as
87
+ * the safe default, so there is no moment at which the last user is known.
88
+ * One texel, one allocation per process.
89
+ * - The armed-renderer registry is written by exactly two functions,
90
+ * {@link armSoftParticleDepth} / {@link disarmSoftParticleDepth}, whose only
91
+ * callers are `registerParticleSystem` / `unregisterParticleSystem`.
92
+ * - The render target and override material belong to the
93
+ * {@link SoftParticleDepthPass} instance and die with its `dispose()`. The
94
+ * pass itself is owned by whichever adapter mount created it (the R3F adapter
95
+ * and `setup-three-root-adapter`), and that mount's teardown is the one path
96
+ * allowed to end it.
97
+ */
98
+ import * as THREE from 'three';
99
+ /**
100
+ * The renderers hosting at least one system that asked for `softParticles`, and
101
+ * HOW MANY — a renderer may batch several emitters and must stay armed until
102
+ * the last one leaves.
103
+ *
104
+ * Module-scoped because the pass is per-MOUNT while a renderer is per-emitter:
105
+ * two worlds may be mounted at once and each pass filters this map down to the
106
+ * renderers actually parented under the scene it is rendering.
107
+ */
108
+ const armed = new Map();
109
+ let farDepth;
110
+ /**
111
+ * A 1x1 texture whose red channel is 1.0 — "the depth buffer says nothing is in
112
+ * front of anything".
113
+ *
114
+ * Bound to a `BatchedRenderer` the moment it is constructed, so a batch that
115
+ * later compiles with `SOFT_PARTICLES` inherits it (`BatchedRenderer.addSystem`
116
+ * applies `this.depthTexture` to each batch it creates). Feeding
117
+ * `linearize_depth` a `1.0` yields `(zFar * zNear) / (zFar - (zFar - zNear))`,
118
+ * which is `zFar`, so the fade term is `saturate(k * (zFar - linearDepth))` — 1
119
+ * for every fragment in front of the far plane. The fade is INERT rather than
120
+ * wrong, which is what makes an undriven surface (a design-time preview, a host
121
+ * with no pass) render exactly as it did before soft particles existed.
122
+ */
123
+ export function farDepthTexture() {
124
+ if (farDepth === undefined) {
125
+ farDepth = new THREE.DataTexture(new Uint8Array([255, 255, 255, 255]), 1, 1);
126
+ farDepth.name = 'soft-particle-far-depth';
127
+ farDepth.needsUpdate = true;
128
+ }
129
+ return farDepth;
130
+ }
131
+ /** Record that `renderer` hosts one more soft-particle system, so passes stop skipping it. */
132
+ export function armSoftParticleDepth(renderer) {
133
+ armed.set(renderer, (armed.get(renderer) ?? 0) + 1);
134
+ }
135
+ /**
136
+ * The other half of {@link armSoftParticleDepth}. On the LAST soft system the
137
+ * renderer is dropped from the registry and handed the inert far-depth default
138
+ * back, so a batch that outlives its registration never keeps sampling a scene
139
+ * depth nobody is refreshing.
140
+ */
141
+ export function disarmSoftParticleDepth(renderer) {
142
+ const remaining = (armed.get(renderer) ?? 0) - 1;
143
+ if (remaining > 0) {
144
+ armed.set(renderer, remaining);
145
+ return;
146
+ }
147
+ if (!armed.delete(renderer))
148
+ return;
149
+ renderer.setDepthTexture(farDepthTexture());
150
+ }
151
+ /** Test/diagnostic read of the registry — how many renderers a pass would consider. */
152
+ export function armedSoftParticleRendererCount() {
153
+ return armed.size;
154
+ }
155
+ /** Is `node` inside `root`'s subtree? Walks parents, so it is O(depth), not O(scene). */
156
+ function isUnder(node, root) {
157
+ for (let at = node; at !== null; at = at.parent) {
158
+ if (at === root)
159
+ return true;
160
+ }
161
+ return false;
162
+ }
163
+ /** Godot's `depth_draw_opaque`: a transparent surface contributes no depth. */
164
+ function drawsIntoDepth(object) {
165
+ const material = object.material;
166
+ if (material === undefined)
167
+ return true;
168
+ return Array.isArray(material)
169
+ ? !material.every((entry) => entry.transparent)
170
+ : !material.transparent;
171
+ }
172
+ /**
173
+ * The three renderer members this prepass CANNOT do without — the render-target
174
+ * swap it draws through, and the buffer size it sizes that target from.
175
+ *
176
+ * A real `WebGLRenderer` has all of them. A DESIGN-TIME settle does not: a
177
+ * stand-in that only has to answer `render` mounts a world so the editor can
178
+ * read it, and reaching for `getDrawingBufferSize` on one threw
179
+ * `renderer.getDrawingBufferSize is not a function` out of the first driven
180
+ * frame — so a world whose particles merely *declare* a proximity fade could
181
+ * not be settled at all. A prepass is an EFFECT: with no renderer to run it on,
182
+ * the right answer is the inert far-depth default every batch is already bound
183
+ * to (see {@link farDepthTexture}), which is pixel-identical to a batch that
184
+ * never asked for soft particles. So this degrades, loudly and once, instead of
185
+ * taking the frame down with it.
186
+ */
187
+ const REQUIRED_RENDERER_MEMBERS = [
188
+ 'getDrawingBufferSize',
189
+ 'getRenderTarget',
190
+ 'setRenderTarget',
191
+ 'render',
192
+ ];
193
+ /** The required members `renderer` does not implement, in declaration order. */
194
+ function missingRendererMembers(renderer) {
195
+ const held = renderer;
196
+ return REQUIRED_RENDERER_MEMBERS.filter((name) => typeof held[name] !== 'function');
197
+ }
198
+ export function createSoftParticleDepthPass() {
199
+ let target = null;
200
+ /** Warned about already — one line per pass, not one per frame. */
201
+ let warnedIncapable = false;
202
+ const override = new THREE.MeshBasicMaterial({ colorWrite: false });
203
+ override.name = 'soft-particle-depth-prepass';
204
+ const size = new THREE.Vector2();
205
+ const hidden = [];
206
+ const resize = (width, height) => {
207
+ if (target !== null && target.width === width && target.height === height)
208
+ return target;
209
+ target?.dispose();
210
+ const depthTexture = new THREE.DepthTexture(width, height, THREE.UnsignedIntType);
211
+ depthTexture.name = 'soft-particle-scene-depth';
212
+ const next = new THREE.WebGLRenderTarget(width, height, { depthBuffer: true, depthTexture });
213
+ target = next;
214
+ return next;
215
+ };
216
+ return {
217
+ render(renderer, scene, camera) {
218
+ if (armed.size === 0)
219
+ return;
220
+ const consumers = [];
221
+ for (const candidate of armed.keys()) {
222
+ if (isUnder(candidate, scene))
223
+ consumers.push(candidate);
224
+ }
225
+ if (consumers.length === 0)
226
+ return;
227
+ // See REQUIRED_RENDERER_MEMBERS: a renderer that cannot swap render
228
+ // targets cannot run a prepass, and the frame is worth more than the
229
+ // fade. Every consumer keeps the far-depth default it was armed with.
230
+ const missing = missingRendererMembers(renderer);
231
+ if (missing.length > 0) {
232
+ if (!warnedIncapable) {
233
+ warnedIncapable = true;
234
+ // biome-ignore lint/suspicious/noConsole: deliberate loud degrade — the documented alternative to throwing out of the frame
235
+ console.warn(`soft-particle depth prepass skipped: this renderer implements none of ${missing.join(', ')}. ` +
236
+ `${String(consumers.length)} particle batch(es) keep the inert far-depth default, so they ` +
237
+ 'draw unfaded — the same pixels as a batch that never declared a proximity fade. A real ' +
238
+ 'WebGLRenderer has these; a design-time settle stand-in does not.');
239
+ }
240
+ return;
241
+ }
242
+ renderer.getDrawingBufferSize(size);
243
+ const width = Math.max(1, Math.floor(size.x));
244
+ const height = Math.max(1, Math.floor(size.y));
245
+ const rt = resize(width, height);
246
+ // Hidden for the prepass: the particles themselves (they are what samples
247
+ // this depth) and every transparent surface (Godot's opaque-only depth).
248
+ hidden.length = 0;
249
+ for (const consumer of consumers) {
250
+ if (consumer.visible) {
251
+ consumer.visible = false;
252
+ hidden.push(consumer);
253
+ }
254
+ }
255
+ scene.traverse((object) => {
256
+ if (!object.visible)
257
+ return;
258
+ if (drawsIntoDepth(object))
259
+ return;
260
+ object.visible = false;
261
+ hidden.push(object);
262
+ });
263
+ const previousTarget = renderer.getRenderTarget();
264
+ const previousOverride = scene.overrideMaterial;
265
+ // three re-renders every shadow map on EVERY `render()` call while
266
+ // `shadowMap.autoUpdate` is on, so without this the prepass would double
267
+ // the frame's shadow cost for a pass that writes depth and nothing else.
268
+ // Both flags are restored below; the frame's own draw re-renders them.
269
+ const shadows = renderer.shadowMap;
270
+ const previousAutoUpdate = shadows?.autoUpdate ?? false;
271
+ const previousNeedsUpdate = shadows?.needsUpdate ?? false;
272
+ if (shadows !== undefined) {
273
+ shadows.autoUpdate = false;
274
+ shadows.needsUpdate = false;
275
+ }
276
+ scene.overrideMaterial = override;
277
+ try {
278
+ renderer.setRenderTarget(rt);
279
+ renderer.render(scene, camera);
280
+ }
281
+ finally {
282
+ renderer.setRenderTarget(previousTarget);
283
+ scene.overrideMaterial = previousOverride;
284
+ if (shadows !== undefined) {
285
+ shadows.autoUpdate = previousAutoUpdate;
286
+ shadows.needsUpdate = previousNeedsUpdate;
287
+ }
288
+ for (const object of hidden)
289
+ object.visible = true;
290
+ hidden.length = 0;
291
+ }
292
+ for (const consumer of consumers)
293
+ consumer.setDepthTexture(rt.depthTexture);
294
+ },
295
+ dispose() {
296
+ // Every consumer this pass fed now points at a texture that is about to
297
+ // go away. Hand them the inert default back rather than a disposed one.
298
+ for (const candidate of armed.keys())
299
+ candidate.setDepthTexture(farDepthTexture());
300
+ target?.dispose();
301
+ target = null;
302
+ override.dispose();
303
+ },
304
+ };
305
+ }