@driftengine/core 4.3.0 → 4.4.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 (215) hide show
  1. package/CHANGELOG.json +261 -0
  2. package/README.md +1 -1
  3. package/dist/cinematic/cameraPath.d.ts +53 -0
  4. package/dist/cinematic/cameraPath.js +118 -0
  5. package/dist/environment/daylight.d.ts +77 -0
  6. package/dist/environment/daylight.js +77 -0
  7. package/dist/geometry/meshConcat.d.ts +9 -0
  8. package/dist/geometry/meshConcat.js +101 -0
  9. package/dist/index.d.ts +12 -2
  10. package/dist/index.js +14 -1
  11. package/dist/render/backend/createRenderer.d.ts +13 -1
  12. package/dist/render/backend/createRenderer.js +6 -5
  13. package/dist/render/backend/webgl2/renderer.d.ts +147 -1
  14. package/dist/render/backend/webgl2/renderer.js +402 -23
  15. package/dist/render/backend/webgpu/buffers.js +46 -8
  16. package/dist/render/backend/webgpu/depthPass.d.ts +81 -3
  17. package/dist/render/backend/webgpu/depthPass.js +75 -14
  18. package/dist/render/backend/webgpu/exposurePass.d.ts +39 -0
  19. package/dist/render/backend/webgpu/exposurePass.js +190 -0
  20. package/dist/render/backend/webgpu/fieldCompose.d.ts +11 -0
  21. package/dist/render/backend/webgpu/fieldCompose.js +13 -0
  22. package/dist/render/backend/webgpu/flatPass.d.ts +3 -1
  23. package/dist/render/backend/webgpu/flatPass.js +12 -5
  24. package/dist/render/backend/webgpu/particlePass.d.ts +8 -0
  25. package/dist/render/backend/webgpu/particlePass.js +1 -0
  26. package/dist/render/backend/webgpu/postPass.d.ts +12 -2
  27. package/dist/render/backend/webgpu/probeBake.d.ts +59 -3
  28. package/dist/render/backend/webgpu/probeBake.js +97 -7
  29. package/dist/render/backend/webgpu/probeTargets.d.ts +65 -0
  30. package/dist/render/backend/webgpu/probeTargets.js +180 -0
  31. package/dist/render/backend/webgpu/renderer.d.ts +174 -11
  32. package/dist/render/backend/webgpu/renderer.js +675 -249
  33. package/dist/render/backend/webgpu/scatterPass.js +7 -7
  34. package/dist/render/backend/webgpu/shaders/clusterBin.wgsl.d.ts +1 -1
  35. package/dist/render/backend/webgpu/skinPaletteRing.d.ts +4 -0
  36. package/dist/render/backend/webgpu/skinPaletteRing.js +9 -0
  37. package/dist/render/backend/webgpu/skyPass.js +5 -1
  38. package/dist/render/backend/webgpu/uniformRing.d.ts +31 -1
  39. package/dist/render/backend/webgpu/uniformRing.js +53 -3
  40. package/dist/render/bloomChain.d.ts +6 -0
  41. package/dist/render/bloomChain.js +8 -0
  42. package/dist/render/clusteredLights.d.ts +19 -11
  43. package/dist/render/clusteredLights.js +96 -45
  44. package/dist/render/cutoutCaster.d.ts +23 -0
  45. package/dist/render/cutoutCaster.js +20 -0
  46. package/dist/render/driftLight/bake.d.ts +34 -0
  47. package/dist/render/driftLight/bake.js +95 -0
  48. package/dist/render/driftLight/falloff.d.ts +16 -0
  49. package/dist/render/driftLight/falloff.js +23 -0
  50. package/dist/render/driftLight/layout.d.ts +59 -0
  51. package/dist/render/driftLight/layout.js +138 -0
  52. package/dist/render/driftLight/lightField.d.ts +108 -0
  53. package/dist/render/driftLight/lightField.js +179 -0
  54. package/dist/render/driftLight/uniforms.d.ts +28 -0
  55. package/dist/render/driftLight/uniforms.js +41 -0
  56. package/dist/render/driftLight/visibility.d.ts +18 -0
  57. package/dist/render/driftLight/visibility.js +47 -0
  58. package/dist/render/emptyTexture.d.ts +6 -0
  59. package/dist/render/emptyTexture.js +19 -0
  60. package/dist/render/exposurePass.d.ts +48 -0
  61. package/dist/render/exposurePass.js +172 -0
  62. package/dist/render/flameLight.d.ts +71 -0
  63. package/dist/render/flameLight.js +63 -0
  64. package/dist/render/gi/bounceLights.d.ts +34 -0
  65. package/dist/render/gi/bounceLights.js +66 -0
  66. package/dist/render/gi/fieldReach.d.ts +12 -0
  67. package/dist/render/gi/fieldReach.js +62 -0
  68. package/dist/render/gi/globalField.d.ts +8 -0
  69. package/dist/render/gi/globalField.js +31 -0
  70. package/dist/render/gi/probeTrace.d.ts +3 -1
  71. package/dist/render/gi/probeTrace.js +3 -1
  72. package/dist/render/gpuCapability.js +19 -4
  73. package/dist/render/lightBudget.d.ts +11 -0
  74. package/dist/render/lightBudget.js +11 -0
  75. package/dist/render/pointLightSelection.d.ts +16 -0
  76. package/dist/render/pointLightSelection.js +178 -83
  77. package/dist/render/probeGrid.d.ts +11 -1
  78. package/dist/render/probeGrid.js +5 -2
  79. package/dist/render/probeSweeps.d.ts +45 -0
  80. package/dist/render/probeSweeps.js +77 -0
  81. package/dist/render/reflectionProbe.d.ts +43 -1
  82. package/dist/render/reflectionProbe.js +17 -3
  83. package/dist/render/renderQuality.d.ts +3 -1
  84. package/dist/render/rendererHarness.d.ts +9 -0
  85. package/dist/render/rendererHarness.js +18 -3
  86. package/dist/render/sceneTarget.d.ts +20 -0
  87. package/dist/render/sceneTarget.js +62 -1
  88. package/dist/render/shaders/agx.d.ts +31 -0
  89. package/dist/render/shaders/agx.js +81 -0
  90. package/dist/render/shaders/ambientOcclusion.d.ts +24 -5
  91. package/dist/render/shaders/ambientOcclusion.js +120 -63
  92. package/dist/render/shaders/cutoutCoverage.d.ts +31 -0
  93. package/dist/render/shaders/cutoutCoverage.js +40 -0
  94. package/dist/render/shaders/depth.d.ts +25 -0
  95. package/dist/render/shaders/depth.js +69 -3
  96. package/dist/render/shaders/exposure.d.ts +52 -0
  97. package/dist/render/shaders/exposure.js +124 -0
  98. package/dist/render/shaders/filmLook.d.ts +47 -0
  99. package/dist/render/shaders/filmLook.js +98 -0
  100. package/dist/render/shaders/flat/directionalShadow.js +35 -4
  101. package/dist/render/shaders/flat/driftLight.d.ts +29 -0
  102. package/dist/render/shaders/flat/driftLight.js +75 -0
  103. package/dist/render/shaders/flat/index.js +5 -0
  104. package/dist/render/shaders/flat/lobes.js +13 -0
  105. package/dist/render/shaders/flat/main.d.ts +1 -1
  106. package/dist/render/shaders/flat/main.js +68 -9
  107. package/dist/render/shaders/flat/preamble.js +23 -5
  108. package/dist/render/shaders/flat/probeGrid.js +46 -3
  109. package/dist/render/shaders/generated/ambientOcclusion.wgsl.d.ts +1 -1
  110. package/dist/render/shaders/generated/ambientOcclusion.wgsl.js +1 -1
  111. package/dist/render/shaders/generated/depth.wgsl.d.ts +100 -0
  112. package/dist/render/shaders/generated/depth.wgsl.js +100 -0
  113. package/dist/render/shaders/generated/exposure.wgsl.d.ts +42 -0
  114. package/dist/render/shaders/generated/exposure.wgsl.js +48 -0
  115. package/dist/render/shaders/generated/flat.wgsl.d.ts +1800 -1344
  116. package/dist/render/shaders/generated/flat.wgsl.js +1816 -1360
  117. package/dist/render/shaders/generated/localExposure.wgsl.d.ts +18 -0
  118. package/dist/render/shaders/generated/localExposure.wgsl.js +24 -0
  119. package/dist/render/shaders/generated/rush.wgsl.d.ts +40 -10
  120. package/dist/render/shaders/generated/rush.wgsl.js +40 -10
  121. package/dist/render/shaders/generated/temporalResolve.wgsl.d.ts +1 -1
  122. package/dist/render/shaders/generated/temporalResolve.wgsl.js +1 -1
  123. package/dist/render/shaders/gi/driftLight.wgsl.d.ts +16 -0
  124. package/dist/render/shaders/gi/driftLight.wgsl.js +49 -0
  125. package/dist/render/shaders/gi/probeBake.wgsl.d.ts +29 -4
  126. package/dist/render/shaders/gi/probeBake.wgsl.js +190 -20
  127. package/dist/render/shaders/globalMedium.js +4 -0
  128. package/dist/render/shaders/localExposure.d.ts +35 -0
  129. package/dist/render/shaders/localExposure.js +138 -0
  130. package/dist/render/shaders/prefilter.d.ts +1 -1
  131. package/dist/render/shaders/prefilter.js +6 -0
  132. package/dist/render/shaders/rush.js +33 -5
  133. package/dist/render/shaders/tangentFrame.d.ts +1 -1
  134. package/dist/render/shaders/tangentFrame.js +15 -3
  135. package/dist/render/shaders/temporalResolve.js +39 -1
  136. package/dist/render/shadowCasters.d.ts +5 -3
  137. package/dist/render/shadowMap.js +13 -0
  138. package/dist/render/surfaceTexture.d.ts +5 -0
  139. package/package.json +6 -6
  140. package/scripts/gpuCompute.mjs +24 -3
  141. package/scripts/png.mjs +23 -12
  142. package/src/cinematic/cameraPath.ts +178 -0
  143. package/src/environment/daylight.ts +152 -0
  144. package/src/geometry/meshConcat.ts +100 -0
  145. package/src/index.ts +32 -0
  146. package/src/render/backend/createRenderer.ts +22 -6
  147. package/src/render/backend/webgl2/renderer.ts +439 -20
  148. package/src/render/backend/webgpu/buffers.ts +51 -8
  149. package/src/render/backend/webgpu/depthPass.ts +78 -10
  150. package/src/render/backend/webgpu/exposurePass.ts +234 -0
  151. package/src/render/backend/webgpu/fieldCompose.ts +15 -0
  152. package/src/render/backend/webgpu/flatPass.ts +10 -2
  153. package/src/render/backend/webgpu/particlePass.ts +9 -0
  154. package/src/render/backend/webgpu/probeBake.ts +143 -9
  155. package/src/render/backend/webgpu/probeTargets.ts +211 -0
  156. package/src/render/backend/webgpu/renderer.ts +801 -270
  157. package/src/render/backend/webgpu/scatterPass.ts +7 -7
  158. package/src/render/backend/webgpu/skinPaletteRing.ts +10 -0
  159. package/src/render/backend/webgpu/skyPass.ts +5 -1
  160. package/src/render/backend/webgpu/uniformRing.ts +49 -3
  161. package/src/render/bloomChain.ts +9 -0
  162. package/src/render/clusteredLights.ts +108 -63
  163. package/src/render/cutoutCaster.ts +44 -0
  164. package/src/render/driftLight/bake.ts +125 -0
  165. package/src/render/driftLight/falloff.ts +26 -0
  166. package/src/render/driftLight/layout.ts +177 -0
  167. package/src/render/driftLight/lightField.ts +227 -0
  168. package/src/render/driftLight/uniforms.ts +61 -0
  169. package/src/render/driftLight/visibility.ts +58 -0
  170. package/src/render/emptyTexture.ts +41 -0
  171. package/src/render/exposurePass.ts +186 -0
  172. package/src/render/flameLight.ts +135 -0
  173. package/src/render/gi/bounceLights.ts +68 -0
  174. package/src/render/gi/fieldReach.ts +74 -0
  175. package/src/render/gi/globalField.ts +39 -0
  176. package/src/render/gi/probeTrace.ts +3 -1
  177. package/src/render/gpuCapability.ts +18 -5
  178. package/src/render/lightBudget.ts +12 -0
  179. package/src/render/pointLightSelection.ts +191 -79
  180. package/src/render/probeGrid.ts +13 -2
  181. package/src/render/probeSweeps.ts +80 -0
  182. package/src/render/reflectionProbe.ts +54 -2
  183. package/src/render/renderQuality.ts +3 -1
  184. package/src/render/rendererHarness.ts +25 -3
  185. package/src/render/sceneTarget.ts +75 -1
  186. package/src/render/shaders/ambientOcclusion.ts +125 -63
  187. package/src/render/shaders/cutoutCoverage.ts +43 -0
  188. package/src/render/shaders/depth.ts +80 -3
  189. package/src/render/shaders/exposure.ts +128 -0
  190. package/src/render/shaders/filmLook.ts +111 -0
  191. package/src/render/shaders/flat/directionalShadow.ts +35 -4
  192. package/src/render/shaders/flat/driftLight.ts +75 -0
  193. package/src/render/shaders/flat/index.ts +5 -0
  194. package/src/render/shaders/flat/lobes.ts +13 -0
  195. package/src/render/shaders/flat/main.ts +68 -9
  196. package/src/render/shaders/flat/preamble.ts +23 -5
  197. package/src/render/shaders/flat/probeGrid.ts +46 -3
  198. package/src/render/shaders/generated/ambientOcclusion.wgsl.ts +1 -1
  199. package/src/render/shaders/generated/depth.wgsl.ts +103 -0
  200. package/src/render/shaders/generated/exposure.wgsl.ts +51 -0
  201. package/src/render/shaders/generated/flat.wgsl.ts +1816 -1360
  202. package/src/render/shaders/generated/localExposure.wgsl.ts +26 -0
  203. package/src/render/shaders/generated/rush.wgsl.ts +40 -10
  204. package/src/render/shaders/generated/temporalResolve.wgsl.ts +1 -1
  205. package/src/render/shaders/gi/driftLight.wgsl.ts +49 -0
  206. package/src/render/shaders/gi/probeBake.wgsl.ts +191 -20
  207. package/src/render/shaders/globalMedium.ts +4 -0
  208. package/src/render/shaders/localExposure.ts +154 -0
  209. package/src/render/shaders/prefilter.ts +6 -0
  210. package/src/render/shaders/rush.ts +33 -5
  211. package/src/render/shaders/tangentFrame.ts +15 -3
  212. package/src/render/shaders/temporalResolve.ts +39 -1
  213. package/src/render/shadowCasters.ts +5 -3
  214. package/src/render/shadowMap.ts +14 -0
  215. package/src/render/surfaceTexture.ts +5 -0
@@ -27,11 +27,20 @@ import { glslIsFarDepth, glslSceneDepthToNdc } from '../depthConvention.js';
27
27
  /**
28
28
  * The estimate. Writes one channel: 1 is open sky, 0 is fully enclosed.
29
29
  *
30
- * The estimator is the Alchemy/scalable-AO one — for each neighbour, the vector v from this
31
- * surface to it, weighted max(0, v·n) / (v·v). Two properties earn it its place over a
32
- * hemisphere of offset points: nothing has to be oriented, so there is no tangent frame and
33
- * no rotation matrix per pixel, and the 1 / v·v term falls away on its own, so a neighbour
34
- * further off contributes less without a second range test doing it by hand.
30
+ * **Horizons, not neighbours: ground-truth ambient occlusion (Jimenez et al. 2016).** Each pixel
31
+ * walks two lines across the screen, both ways, and keeps the highest thing it can see along each
32
+ * half: the horizon. The sky left between the two horizons of a line, weighted by the cosine to the
33
+ * surface's own normal, is that line's visibility in closed form, and two lines a pixel with the
34
+ * rotation tile below turning them is the hemisphere. It replaced a sum over twelve neighbours that
35
+ * counted anything within the radius as a blocker, however thin: cloth hanging a hand in front of a
36
+ * column darkened the column behind it, which read as a halo round every curtain in a courtyard.
37
+ *
38
+ * **What stops the halo is two rules about the horizon**, both the paper's. A sample fades out of
39
+ * the horizon as it approaches the radius, so a far wall does not shade a floor; and once the walk
40
+ * has passed the highest sample, the horizon sinks back toward what it sees next, so a thin thing
41
+ * in front raises it only while the walk is behind that thing. What that gives up is the shade under
42
+ * a thick object seen edge on, which reads as a thin one; the thickness is a constant because depth
43
+ * alone cannot say how deep anything is.
35
44
  */
36
45
  export const AO_FRAG = `#version 300 es
37
46
  precision highp float;
@@ -68,16 +77,18 @@ uniform float uRadius;
68
77
 
69
78
  out float fragColor;
70
79
 
71
- /** How many depths each pixel compares itself against. Fixed, so the cost is fixed. */
72
- const int AO_TAPS = 12;
80
+ /** Lines across the screen a pixel walks, each both ways. Fixed, so the cost is fixed. */
81
+ const int AO_SLICES = 2;
82
+ /** Depth samples each way along a line: two lines, two ways, six steps is 24 a pixel. */
83
+ const int AO_STEPS = 6;
73
84
  /**
74
- * The golden angle, in radians.
85
+ * How far the horizon sinks back toward each later sample once the walk has passed the highest one.
75
86
  *
76
- * Successive taps turned by it never line up into spokes, which a rational fraction of a
77
- * turn does: a kernel that repeats a direction is blind along it, and it is blind the same
78
- * way in every pixel, so it reads as a pattern in the surface rather than as noise.
87
+ * The paper's thickness heuristic. At zero anything within the radius shades for good, which is the
88
+ * halo; at one a horizon lasts one sample and a real corner loses its shade. A fifth keeps a corner,
89
+ * whose samples keep rising, and lets a curtain's shade drop within the few samples past its edge.
79
90
  */
80
- const float AO_GOLDEN_ANGLE = 2.39996323;
91
+ const float AO_THIN = 0.2;
81
92
  /**
82
93
  * How far the sampling may reach across the frame, whatever the depth says.
83
94
  *
@@ -86,25 +97,6 @@ const float AO_GOLDEN_ANGLE = 2.39996323;
86
97
  * being contact shading and becomes an expensive wide darkening. 6% of the frame.
87
98
  */
88
99
  const float AO_MAX_REACH_UV = 0.06;
89
- /**
90
- * Self-occlusion guard, as a fraction of the pixel's own view depth.
91
- *
92
- * Depth is quantised, so a flat surface samples itself very slightly in front of itself and
93
- * every flat surface in the world comes back faintly dirty. The error grows with distance,
94
- * which is why the guard is proportional to depth rather than a constant.
95
- */
96
- const float AO_BIAS = 0.004;
97
- /**
98
- * The floor under the 1 / (v·v) weighting, in square metres.
99
- *
100
- * Not a guard against dividing by zero, which is what a value near the float epsilon would
101
- * be. The nearest taps land about a centimetre away, where v·v is 1e-4 and the weight is ten
102
- * thousand — so a depth quantised to a millimetre yields several units of occlusion out of
103
- * nothing at all. Measured that way first, with 1e-4 here: a flat floor came back as static.
104
- * A hundredth of a square metre is a tenth of a metre of separation, which is the scale
105
- * below which two samples are the same surface rather than one occluding the other.
106
- */
107
- const float AO_EPSILON = 0.01;
108
100
  /**
109
101
  * How many times further one neighbour may be than the other before the pair straddles an edge.
110
102
  *
@@ -133,6 +125,17 @@ vec3 viewPosition(vec2 uv, float depth) {
133
125
  return view.xyz / view.w;
134
126
  }
135
127
 
128
+ /**
129
+ * The cosine-weighted sky between two horizon angles h0 < 0 < h1, measured from the eye, for a
130
+ * normal at the angle given in the same plane: the paper's closed form. 1 for an open plane facing
131
+ * the eye.
132
+ */
133
+ float gtaoArc(float h0, float h1, float normal) {
134
+ float c = cos(normal);
135
+ float s2 = 2.0 * sin(normal);
136
+ return 0.25 * (-cos(2.0 * h0 - normal) + c + h0 * s2) + 0.25 * (-cos(2.0 * h1 - normal) + c + h1 * s2);
137
+ }
138
+
136
139
  void main() {
137
140
  /*
138
141
  * One output pixel, in UV, along each axis.
@@ -214,15 +217,16 @@ void main() {
214
217
  vec3 n = normalize(cross(dpdx, dpdy));
215
218
  /*
216
219
  * Turned to face the eye. Which sign the cross product comes out with is a fact about the
217
- * screen-space winding and the handedness of the projection, and a normal pointing away
218
- * from the camera makes every v·n come back zero, which is a frame with no occlusion in it
219
- * anywhere. In view space the eye is the origin, so a normal facing it satisfies n·p < 0.
220
+ * screen-space winding and the handedness of the projection, and a normal pointing away from the
221
+ * camera puts every horizon behind the surface. In view space the eye is the origin, so a normal
222
+ * facing it satisfies n·p < 0.
220
223
  */
221
224
  if (dot(n, p) > 0.0) n = -n;
225
+ vec3 toEye = normalize(-p);
222
226
 
223
227
  /*
224
- * The radius as a fraction of the frame. A metre subtends less of the screen the further
225
- * away it is, which is the entire reason this is computed per pixel rather than handed in.
228
+ * The radius as a fraction of the frame. A metre subtends less of the screen the further away it
229
+ * is, which is the entire reason this is computed per pixel rather than handed in.
226
230
  */
227
231
  vec2 reach = min(
228
232
  uRadius * uProjScale * 0.5 / max(-p.z, 1e-3),
@@ -230,41 +234,77 @@ void main() {
230
234
  );
231
235
 
232
236
  /*
233
- * A rotation that repeats every four pixels: sixteen distinct turns laid out over a 4x4
234
- * tile. Paired with the four-wide blur that follows, every blurred pixel averages all
235
- * sixteen, which is what makes twelve taps enough. A per-pixel hash would decorrelate
236
- * neighbours better in principle and is worse here, because the blur can then only soften
237
- * the noise rather than complete the kernel.
237
+ * A rotation that repeats every four pixels: sixteen turns laid out over a 4x4 tile, spanning the
238
+ * quarter turn between one line and the next, so the eight-wide blur that follows averages every
239
+ * turn of both lines. The first step's distance is staggered by the same tile, so neighbouring
240
+ * pixels do not all sample the same rings either.
238
241
  */
239
242
  float tile = mod(gl_FragCoord.x, 4.0) + 4.0 * mod(gl_FragCoord.y, 4.0);
240
- float turn = tile * (6.2831853 / 16.0);
241
-
242
- float sum = 0.0;
243
- for (int i = 0; i < AO_TAPS; i++) {
244
- float t = (float(i) + 0.5) / float(AO_TAPS);
245
- float angle = turn + float(i) * AO_GOLDEN_ANGLE;
246
- /* The square root spreads the taps evenly over the disk; without it they crowd the
247
- centre, where they are measuring the pixel's own depth. */
248
- vec2 uv = vUv + vec2(cos(angle), sin(angle)) * sqrt(t) * reach;
243
+ float turn = tile * (1.5707963 / 16.0);
244
+ float stagger = fract(tile * 0.618034);
245
+ /* One output pixel along each axis, in UV. */
246
+ vec2 pixel = vec2(length(stepX), length(stepY));
249
247
 
248
+ float visible = 0.0;
249
+ for (int slice = 0; slice < AO_SLICES; slice++) {
250
+ float angle = turn + float(slice) * (3.1415927 / float(AO_SLICES));
251
+ /*
252
+ * **Even in pixels, not in UV.** A UV step across a wide frame is longer than one down it, so
253
+ * turns spread evenly in UV crowd toward the horizontal once they reach the screen, and on a
254
+ * floor the horizontal lines are the ones that see least of its normal: every flat floor and
255
+ * ceiling came back at 0.82 open, measured, where the construction gives 0.97. A pixel is as
256
+ * wide as it is tall in view space, so a direction even in pixels is even in the world. It is
257
+ * scaled here into UV, and the reach is taken down the frame, whose UV is the same pixels.
258
+ */
259
+ vec2 screen = vec2(cos(angle) * pixel.x / pixel.y, sin(angle));
250
260
  /*
251
- * textureLod, not texture, and it is the rule rather than a preference: this sample sits
252
- * inside a loop whose iterations a compiler cannot prove uniform, and an implicit
253
- * derivative there is what lets one flatten the body and pay for every arm. The fetch is
254
- * identical — the depth texture has one storage level and NEAREST filters, so there is no
255
- * mip for a derivative to select. See AGENTS.md, 2026-08-07.
261
+ * The line in view space, taken through the same reconstruction the samples use: a step along
262
+ * the screen at this pixel's own depth, so the samples lie in the plane the arc is measured in
263
+ * whatever the frame's aspect and whichever way a backend's clip space counts up.
256
264
  */
257
- float sampled = textureLod(uDepth, uv, 0.0).r;
258
- if (${glslIsFarDepth('sampled')}) continue;
265
+ vec3 along = normalize(viewPosition(vUv + screen * 1e-3, depth) - p);
266
+ vec3 across = normalize(along - toEye * dot(along, toEye));
267
+ vec3 axis = cross(across, toEye);
268
+ /* The normal projected into the line's plane, and its angle from the eye toward +across. */
269
+ vec3 projected = n - axis * dot(n, axis);
270
+ float projectedLength = length(projected);
271
+ if (projectedLength < 1e-4) continue;
272
+ float normalAngle = atan(dot(projected, across), dot(projected, toEye));
259
273
 
260
- vec3 v = viewPosition(uv, sampled) - p;
261
- float vv = dot(v, v);
262
- /* Past the radius it is a different surface rather than a neighbour of this one. */
263
- if (vv > uRadius * uRadius) continue;
264
- sum += max(0.0, dot(v, n) - AO_BIAS * (-p.z)) / (vv + AO_EPSILON);
274
+ /* The highest cosine seen each way. */
275
+ float horizon0 = -1.0;
276
+ float horizon1 = -1.0;
277
+ for (int k = 0; k < AO_STEPS; k++) {
278
+ float t = (float(k) + stagger) / float(AO_STEPS);
279
+ /* Squared, so the steps crowd the pixel, where contact shade lives. */
280
+ vec2 stride = screen * reach.y * (t * t + 0.5 / float(AO_STEPS * AO_STEPS));
281
+ for (int side = 0; side < 2; side++) {
282
+ vec2 uv = side == 0 ? vUv - stride : vUv + stride;
283
+ /*
284
+ * textureLod, not texture, and it is the rule rather than a preference: this sits inside a
285
+ * loop whose iterations a compiler cannot prove uniform. The depth texture has one level and
286
+ * NEAREST filters, so the fetch is identical. See AGENTS.md, 2026-08-07.
287
+ */
288
+ float sampled = textureLod(uDepth, uv, 0.0).r;
289
+ if (${glslIsFarDepth('sampled')}) continue;
290
+ vec3 v = viewPosition(uv, sampled) - p;
291
+ float distance2 = dot(v, v);
292
+ if (distance2 < 1e-8) continue;
293
+ float cosine = dot(v, toEye) * inversesqrt(distance2);
294
+ /* Faded to nothing at the radius: a far wall is not an occluder of this surface. */
295
+ float fade = clamp(1.0 - distance2 / (uRadius * uRadius), 0.0, 1.0);
296
+ cosine = mix(-1.0, cosine, fade);
297
+ if (side == 0) horizon0 = cosine > horizon0 ? cosine : mix(horizon0, cosine, AO_THIN);
298
+ else horizon1 = cosine > horizon1 ? cosine : mix(horizon1, cosine, AO_THIN);
299
+ }
300
+ }
301
+ /* Angles from the eye, negative toward -across, and never below the surface's own tangent. */
302
+ float h0 = max(-acos(clamp(horizon0, -1.0, 1.0)), normalAngle - 1.5707963);
303
+ float h1 = min(acos(clamp(horizon1, -1.0, 1.0)), normalAngle + 1.5707963);
304
+ visible += projectedLength * gtaoArc(h0, h1, normalAngle);
265
305
  }
266
306
 
267
- fragColor = clamp(1.0 - 2.0 * uRadius * sum / float(AO_TAPS), 0.0, 1.0);
307
+ fragColor = clamp(visible / float(AO_SLICES), 0.0, 1.0);
268
308
  }
269
309
  `;
270
310
  /**
@@ -350,3 +390,20 @@ void main() {
350
390
  fragColor = weight > 0.0 ? sum / weight : textureLod(uAo, vUv, 0.0).r;
351
391
  }
352
392
  `;
393
+ /**
394
+ * The estimate's closed form, written out once more so a test can pin it to hand-derived values:
395
+ * the cosine-weighted sky between horizon angles `h0 < 0 < h1` for a normal at `normal`, all in
396
+ * radians from the eye within one line's plane.
397
+ */
398
+ export function gtaoArc(h0, h1, normal) {
399
+ const c = Math.cos(normal);
400
+ const s2 = 2 * Math.sin(normal);
401
+ return (0.25 * (-Math.cos(2 * h0 - normal) + c + h0 * s2) +
402
+ 0.25 * (-Math.cos(2 * h1 - normal) + c + h1 * s2));
403
+ }
404
+ /** One step of a horizon: up to a higher sample, or a fifth of the way down toward a lower one. */
405
+ export function nextHorizon(horizon, cosine) {
406
+ return cosine > horizon ? cosine : horizon + (cosine - horizon) * AO_THIN;
407
+ }
408
+ /** The shader's thickness heuristic. See `AO_THIN` inside `AO_FRAG`. */
409
+ export const AO_THIN = 0.2;
@@ -0,0 +1,31 @@
1
+ /**
2
+ * A cutout that keeps its coverage down the mip chain.
3
+ *
4
+ * **Averaging alpha thins everything that is thinner than a texel.** Each level of a mip chain is
5
+ * the mean of four texels of the one above, so a needle one texel wide on a clear background is 0.5
6
+ * at the next level, 0.25 at the one after, and gone against a cutoff of 0.5 two levels down. A
7
+ * tree that is dense up close then stands bare a few metres off, which on a bought courtyard was a
8
+ * cypress drawn as bare branches at 1280 pixels across and in full leaf at 2000.
9
+ *
10
+ * **So the test scales alpha up by the level it is sampling**: a quarter more per level, the figure
11
+ * Ben Golus measured on foliage in "Anti-aliased Alpha Test" (2017). Only the test sees the scaled
12
+ * value; what a translucent draw blends with is the texture's own alpha, and a material with no
13
+ * cutoff is untouched. What it gives up is exactness: coverage is held roughly rather than measured
14
+ * per image, which Ignacio Castaño's method would do at upload from a readback this engine does not
15
+ * make. What would make it wrong is an image whose mips were built to keep coverage already, which
16
+ * this would then thicken.
17
+ *
18
+ * The level is estimated from the texture coordinate's screen derivatives, the isotropic formula;
19
+ * a sampler with anisotropic filtering reads a lower level at a grazing angle, so there a cutout
20
+ * comes out slightly fuller than its own mip would have made it.
21
+ */
22
+ /** How much more alpha each mip level down is credited with in the test. */
23
+ export declare const CUTOUT_MIP_SCALE = 0.25;
24
+ /**
25
+ * `cutoutAlpha(alpha, texels)`: the alpha the cutout test should see, for a sample at `texels`, the
26
+ * texture coordinate times the texture's size. Called in uniform control flow, since it takes
27
+ * derivatives.
28
+ */
29
+ export declare const CUTOUT_COVERAGE_GLSL: string;
30
+ /** The same, given the level, for a test to pin: what the shader compares against the cutoff. */
31
+ export declare function cutoutAlpha(alpha: number, level: number): number;
@@ -0,0 +1,40 @@
1
+ /**
2
+ * A cutout that keeps its coverage down the mip chain.
3
+ *
4
+ * **Averaging alpha thins everything that is thinner than a texel.** Each level of a mip chain is
5
+ * the mean of four texels of the one above, so a needle one texel wide on a clear background is 0.5
6
+ * at the next level, 0.25 at the one after, and gone against a cutoff of 0.5 two levels down. A
7
+ * tree that is dense up close then stands bare a few metres off, which on a bought courtyard was a
8
+ * cypress drawn as bare branches at 1280 pixels across and in full leaf at 2000.
9
+ *
10
+ * **So the test scales alpha up by the level it is sampling**: a quarter more per level, the figure
11
+ * Ben Golus measured on foliage in "Anti-aliased Alpha Test" (2017). Only the test sees the scaled
12
+ * value; what a translucent draw blends with is the texture's own alpha, and a material with no
13
+ * cutoff is untouched. What it gives up is exactness: coverage is held roughly rather than measured
14
+ * per image, which Ignacio Castaño's method would do at upload from a readback this engine does not
15
+ * make. What would make it wrong is an image whose mips were built to keep coverage already, which
16
+ * this would then thicken.
17
+ *
18
+ * The level is estimated from the texture coordinate's screen derivatives, the isotropic formula;
19
+ * a sampler with anisotropic filtering reads a lower level at a grazing angle, so there a cutout
20
+ * comes out slightly fuller than its own mip would have made it.
21
+ */
22
+ /** How much more alpha each mip level down is credited with in the test. */
23
+ export const CUTOUT_MIP_SCALE = 0.25;
24
+ /**
25
+ * `cutoutAlpha(alpha, texels)`: the alpha the cutout test should see, for a sample at `texels`, the
26
+ * texture coordinate times the texture's size. Called in uniform control flow, since it takes
27
+ * derivatives.
28
+ */
29
+ export const CUTOUT_COVERAGE_GLSL = `
30
+ float cutoutAlpha(float alpha, vec2 texels) {
31
+ vec2 dx = dFdx(texels);
32
+ vec2 dy = dFdy(texels);
33
+ float level = max(0.0, 0.5 * log2(max(dot(dx, dx), dot(dy, dy))));
34
+ return alpha * (1.0 + level * ${CUTOUT_MIP_SCALE.toFixed(2)});
35
+ }
36
+ `;
37
+ /** The same, given the level, for a test to pin: what the shader compares against the cutoff. */
38
+ export function cutoutAlpha(alpha, level) {
39
+ return alpha * (1 + Math.max(0, level) * CUTOUT_MIP_SCALE);
40
+ }
@@ -11,4 +11,29 @@ export declare const DEPTH_SKINNED_VERT: string;
11
11
  * a missing variant, and is the shape the per-draw ring exists to prevent one level up.
12
12
  */
13
13
  export declare const DEPTH_INSTANCED_VERT: string;
14
+ /**
15
+ * The variants a cutout caster casts through: a leaf card, a chain link, a fence, whose shape is in
16
+ * its texture's alpha rather than in its geometry.
17
+ *
18
+ * **Variants, not a uniform gate on the plain program**, for this file's own reason: a gate would
19
+ * need the UV, a varying and a bound texture on every opaque caster, and a branch on a varying is
20
+ * not provably uniform, which forbids the implicit derivative the sample below wants. A variant
21
+ * leaves every opaque caster byte for byte as it was. What it costs is one more program each, and
22
+ * a skinned cutout, which nothing has asked for, is not among them.
23
+ */
24
+ export declare const DEPTH_CUTOUT_VERT: string;
25
+ export declare const DEPTH_INSTANCED_CUTOUT_VERT: string;
14
26
  export declare const DEPTH_FRAG = "#version 300 es\nprecision highp float;\nin vec4 vLightPosition;\n\nuniform highp sampler2D uPreviousShadowMap;\nuniform int uPeelShadowLayer;\n\nvoid main() {\n if (uPeelShadowLayer != 0) {\n vec3 p = vLightPosition.xyz / vLightPosition.w;\n vec2 uv = p.xy * 0.5 + 0.5;\n float previousDepth = texture(uPreviousShadowMap, uv).r;\n // Discard the already-recorded surface and everything in front of it. The\n // ordinary depth test then stores the next independently fading occluder.\n if (gl_FragCoord.z <= previousDepth + 0.00001) discard;\n }\n}\n";
27
+ /**
28
+ * The cutout caster's depth: the plain pass, and a texel of alpha under the cutoff writes nothing.
29
+ *
30
+ * **The sample is the first statement, in uniform control flow**, so its implicit derivative picks
31
+ * the mip the shadow map's texel footprint wants; inside a branch it would be undefined (AGENTS.md,
32
+ * 2026-08-07). The peel's own sample becomes an explicit-level fetch for the same reason, and is
33
+ * bit for bit what it was: that map has one level and a nearest sampler. The discard is last, so
34
+ * nothing samples after it.
35
+ *
36
+ * `uCutoutMap` is declared after `uPreviousShadowMap`, so the peel keeps its bindings and the cutout
37
+ * map takes the next.
38
+ */
39
+ export declare const DEPTH_CUTOUT_FRAG: string;
@@ -1,4 +1,5 @@
1
1
  import { resolveConditionals } from './conditionals.js';
2
+ import { CUTOUT_COVERAGE_GLSL } from './cutoutCoverage.js';
2
3
  import { SKINNING_GLSL } from './skinning.js';
3
4
  import { CHANNEL_ATTRIBUTE, CHANNEL_BEND } from './vertexChannel.js';
4
5
  /**
@@ -55,7 +56,22 @@ ${CHANNEL_ATTRIBUTE}
55
56
  ${CHANNEL_BEND}
56
57
  #endif
57
58
 
59
+ #if CUTOUT
60
+ /*
61
+ * **What a cutout caster adds, and where.** The UV at location 5, where every mesh carries it; two
62
+ * uniforms declared after every other, so no field of the plain variant moves and a binder written
63
+ * against it stays right for this one; and two outputs after vLightPosition, which keeps location 0.
64
+ */
65
+ layout(location = 5) in vec2 aUv;
66
+ uniform vec2 uUvScale;
67
+ uniform float uAlphaCutout;
68
+ #endif
69
+
58
70
  out vec4 vLightPosition;
71
+ #if CUTOUT
72
+ out vec2 vUv;
73
+ flat out float vAlphaCutout;
74
+ #endif
59
75
 
60
76
  void main() {
61
77
  #if SKINNED
@@ -79,12 +95,16 @@ void main() {
79
95
  #endif
80
96
  vLightPosition = uLightViewProj * vec4(bent, world.w);
81
97
  gl_Position = vLightPosition;
98
+ #if CUTOUT
99
+ vUv = aUv * uUvScale;
100
+ vAlphaCutout = uAlphaCutout;
101
+ #endif
82
102
  }
83
103
  `;
84
104
  /** The rigid variant: the world, a prop, a mesh with no rig behind it. */
85
- export const DEPTH_VERT = resolveConditionals(DEPTH_VERT_SOURCE, { SKINNED: false, INSTANCED: false }, 'depth');
105
+ export const DEPTH_VERT = resolveConditionals(DEPTH_VERT_SOURCE, { SKINNED: false, INSTANCED: false, CUTOUT: false }, 'depth');
86
106
  /** The skinned variant, which reads a joint palette and moves the vertex by it. */
87
- export const DEPTH_SKINNED_VERT = resolveConditionals(DEPTH_VERT_SOURCE, { SKINNED: true, INSTANCED: false }, 'depth-skinned');
107
+ export const DEPTH_SKINNED_VERT = resolveConditionals(DEPTH_VERT_SOURCE, { SKINNED: true, INSTANCED: false, CUTOUT: false }, 'depth-skinned');
88
108
  /**
89
109
  * The variant an instanced draw casts its shadow through.
90
110
  *
@@ -93,7 +113,19 @@ export const DEPTH_SKINNED_VERT = resolveConditionals(DEPTH_VERT_SOURCE, { SKINN
93
113
  * right place and the rest stacked underneath it, which reads as a lighting fault rather than as
94
114
  * a missing variant, and is the shape the per-draw ring exists to prevent one level up.
95
115
  */
96
- export const DEPTH_INSTANCED_VERT = resolveConditionals(DEPTH_VERT_SOURCE, { SKINNED: false, INSTANCED: true }, 'depth-instanced');
116
+ export const DEPTH_INSTANCED_VERT = resolveConditionals(DEPTH_VERT_SOURCE, { SKINNED: false, INSTANCED: true, CUTOUT: false }, 'depth-instanced');
117
+ /**
118
+ * The variants a cutout caster casts through: a leaf card, a chain link, a fence, whose shape is in
119
+ * its texture's alpha rather than in its geometry.
120
+ *
121
+ * **Variants, not a uniform gate on the plain program**, for this file's own reason: a gate would
122
+ * need the UV, a varying and a bound texture on every opaque caster, and a branch on a varying is
123
+ * not provably uniform, which forbids the implicit derivative the sample below wants. A variant
124
+ * leaves every opaque caster byte for byte as it was. What it costs is one more program each, and
125
+ * a skinned cutout, which nothing has asked for, is not among them.
126
+ */
127
+ export const DEPTH_CUTOUT_VERT = resolveConditionals(DEPTH_VERT_SOURCE, { SKINNED: false, INSTANCED: false, CUTOUT: true }, 'depth-cutout');
128
+ export const DEPTH_INSTANCED_CUTOUT_VERT = resolveConditionals(DEPTH_VERT_SOURCE, { SKINNED: false, INSTANCED: true, CUTOUT: true }, 'depth-instanced-cutout');
97
129
  export const DEPTH_FRAG = `#version 300 es
98
130
  precision highp float;
99
131
  in vec4 vLightPosition;
@@ -112,3 +144,37 @@ void main() {
112
144
  }
113
145
  }
114
146
  `;
147
+ /**
148
+ * The cutout caster's depth: the plain pass, and a texel of alpha under the cutoff writes nothing.
149
+ *
150
+ * **The sample is the first statement, in uniform control flow**, so its implicit derivative picks
151
+ * the mip the shadow map's texel footprint wants; inside a branch it would be undefined (AGENTS.md,
152
+ * 2026-08-07). The peel's own sample becomes an explicit-level fetch for the same reason, and is
153
+ * bit for bit what it was: that map has one level and a nearest sampler. The discard is last, so
154
+ * nothing samples after it.
155
+ *
156
+ * `uCutoutMap` is declared after `uPreviousShadowMap`, so the peel keeps its bindings and the cutout
157
+ * map takes the next.
158
+ */
159
+ export const DEPTH_CUTOUT_FRAG = `#version 300 es
160
+ precision highp float;
161
+ in vec4 vLightPosition;
162
+ in vec2 vUv;
163
+ flat in float vAlphaCutout;
164
+
165
+ uniform highp sampler2D uPreviousShadowMap;
166
+ uniform int uPeelShadowLayer;
167
+ uniform highp sampler2D uCutoutMap;
168
+ ${CUTOUT_COVERAGE_GLSL}
169
+ void main() {
170
+ /* Credited for its mip level as the surface's own test is, so a leaf casts the shape it draws. */
171
+ float alpha = cutoutAlpha(texture(uCutoutMap, vUv).a, vUv * vec2(textureSize(uCutoutMap, 0)));
172
+ if (uPeelShadowLayer != 0) {
173
+ vec3 p = vLightPosition.xyz / vLightPosition.w;
174
+ vec2 uv = p.xy * 0.5 + 0.5;
175
+ float previousDepth = textureLod(uPreviousShadowMap, uv, 0.0).r;
176
+ if (gl_FragCoord.z <= previousDepth + 0.00001) discard;
177
+ }
178
+ if (alpha < vAlphaCutout) discard;
179
+ }
180
+ `;
@@ -0,0 +1,52 @@
1
+ /**
2
+ * Eye adaptation: the frame's own brightness, measured on the GPU and followed over time.
3
+ *
4
+ * **A fixed exposure is right for one view and wrong for the next.** A courtyard with the sun on
5
+ * its upper walls and its floor in the shade of a 19 m wall is several stops darker at ground level
6
+ * than from the gallery, and an exposure set for one draws the other either clipped or black. A
7
+ * camera meters and an eye adapts; this does both, from the finished scene, with no readback.
8
+ *
9
+ * **Two passes, both tiny.** The meter writes a 32×32 grid, each texel the mean of 8×8 taps of log
10
+ * luminance over its share of the frame. The adaptation reads all 1,024 of them in one texel,
11
+ * averages them into the frame's log-mean luminance, and moves the held value toward it by a blend
12
+ * the caller's frame time decides. The composite reads the held value and scales the scene toward
13
+ * middle grey. Log luminance, because an eye's response is to ratios: one sunlit pixel beside a
14
+ * dark frame should not set the exposure the way an arithmetic mean lets it.
15
+ *
16
+ * What it gives up is metering by region: every pixel counts the same, so a small bright window in
17
+ * a dark room pulls less than a photographer's spot meter would. What would change it is a scene
18
+ * that needs a subject held at a brightness, and the answer then is a centre weight in the meter.
19
+ */
20
+ /** Texels a side in the meter's grid, and taps a side within each. */
21
+ export declare const METER_GRID = 32;
22
+ export declare const METER_TAPS = 8;
23
+ /** The luminance the meter clamps to, in stops: a black pixel is not minus infinity. */
24
+ export declare const METER_MIN_LOG2 = -12;
25
+ export declare const METER_MAX_LOG2 = 8;
26
+ /** What full adaptation brings the frame's log-mean luminance to: middle grey. */
27
+ export declare const ADAPTED_KEY = 0.18;
28
+ /** The furthest adaptation moves the exposure either way, in stops. A black loading screen is not a
29
+ * reason to multiply the next frame by a thousand. */
30
+ export declare const ADAPT_RANGE_STOPS = 6;
31
+ /**
32
+ * How fast the held brightness follows the measured one, per second: 1.5 closes about 78% of the
33
+ * way in a second. An eye takes longer to open than to close, and a camera's meter is faster than
34
+ * either; one rate is what a scene that cuts between shots can predict.
35
+ */
36
+ export declare const ADAPT_RATE = 1.5;
37
+ export declare const EXPOSURE_METER_FRAG: string;
38
+ export declare const EXPOSURE_ADAPT_FRAG: string;
39
+ /**
40
+ * `uAutoExposure`, `uExposureHeld` and `autoExposureGain`, for the composite. The gain scales scene
41
+ * light before the tone curve, toward the key by the fraction the caller asked for.
42
+ */
43
+ export declare const AUTO_EXPOSURE_GLSL: string;
44
+ /**
45
+ * The fraction of the way toward this frame's measurement to move, after `dtSec` seconds. A cut,
46
+ * or a first frame with nothing held, snaps.
47
+ */
48
+ export declare function adaptBlend(dtSec: number, snap: boolean): number;
49
+ /** The scene's gain for a held log-mean `heldLog2` at `strength`, as the composite computes it. */
50
+ export declare function autoExposureGain(heldLog2: number, strength: number): number;
51
+ /** An adaptation strength as the shader takes it: 0 to 1, anything else off. */
52
+ export declare function clampAutoExposure(strength: number): number;
@@ -0,0 +1,124 @@
1
+ /**
2
+ * Eye adaptation: the frame's own brightness, measured on the GPU and followed over time.
3
+ *
4
+ * **A fixed exposure is right for one view and wrong for the next.** A courtyard with the sun on
5
+ * its upper walls and its floor in the shade of a 19 m wall is several stops darker at ground level
6
+ * than from the gallery, and an exposure set for one draws the other either clipped or black. A
7
+ * camera meters and an eye adapts; this does both, from the finished scene, with no readback.
8
+ *
9
+ * **Two passes, both tiny.** The meter writes a 32×32 grid, each texel the mean of 8×8 taps of log
10
+ * luminance over its share of the frame. The adaptation reads all 1,024 of them in one texel,
11
+ * averages them into the frame's log-mean luminance, and moves the held value toward it by a blend
12
+ * the caller's frame time decides. The composite reads the held value and scales the scene toward
13
+ * middle grey. Log luminance, because an eye's response is to ratios: one sunlit pixel beside a
14
+ * dark frame should not set the exposure the way an arithmetic mean lets it.
15
+ *
16
+ * What it gives up is metering by region: every pixel counts the same, so a small bright window in
17
+ * a dark room pulls less than a photographer's spot meter would. What would change it is a scene
18
+ * that needs a subject held at a brightness, and the answer then is a centre weight in the meter.
19
+ */
20
+ /** Texels a side in the meter's grid, and taps a side within each. */
21
+ export const METER_GRID = 32;
22
+ export const METER_TAPS = 8;
23
+ /** The luminance the meter clamps to, in stops: a black pixel is not minus infinity. */
24
+ export const METER_MIN_LOG2 = -12;
25
+ export const METER_MAX_LOG2 = 8;
26
+ /** What full adaptation brings the frame's log-mean luminance to: middle grey. */
27
+ export const ADAPTED_KEY = 0.18;
28
+ /** The furthest adaptation moves the exposure either way, in stops. A black loading screen is not a
29
+ * reason to multiply the next frame by a thousand. */
30
+ export const ADAPT_RANGE_STOPS = 6;
31
+ /**
32
+ * How fast the held brightness follows the measured one, per second: 1.5 closes about 78% of the
33
+ * way in a second. An eye takes longer to open than to close, and a camera's meter is faster than
34
+ * either; one rate is what a scene that cuts between shots can predict.
35
+ */
36
+ export const ADAPT_RATE = 1.5;
37
+ export const EXPOSURE_METER_FRAG = `#version 300 es
38
+ precision highp float;
39
+
40
+ in vec2 vUv;
41
+
42
+ /** The finished scene, in scene light, before any exposure or curve. */
43
+ uniform highp sampler2D uScene;
44
+
45
+ out float fragColor;
46
+
47
+ void main() {
48
+ /* This texel's corner, and taps spread evenly over its share of the frame. */
49
+ vec2 corner = vUv - vec2(0.5 / ${METER_GRID.toFixed(1)});
50
+ float sum = 0.0;
51
+ for (int y = 0; y < ${METER_TAPS}; y++) {
52
+ for (int x = 0; x < ${METER_TAPS}; x++) {
53
+ vec2 uv = corner + (vec2(float(x), float(y)) + 0.5) / ${(METER_GRID * METER_TAPS).toFixed(1)};
54
+ vec3 c = textureLod(uScene, uv, 0.0).rgb;
55
+ float luma = dot(c, vec3(0.2126, 0.7152, 0.0722));
56
+ sum += clamp(log2(max(luma, 1e-8)), ${METER_MIN_LOG2.toFixed(1)}, ${METER_MAX_LOG2.toFixed(1)});
57
+ }
58
+ }
59
+ fragColor = sum / ${(METER_TAPS * METER_TAPS).toFixed(1)};
60
+ }
61
+ `;
62
+ export const EXPOSURE_ADAPT_FRAG = `#version 300 es
63
+ precision highp float;
64
+
65
+ /** The meter's grid of log luminances. */
66
+ uniform highp sampler2D uMeter;
67
+ /** The brightness held from the frames before, in stops, one texel. */
68
+ uniform highp sampler2D uHeld;
69
+ /** How far toward this frame's measurement to move: 1 snaps, 0 holds. */
70
+ uniform float uBlend;
71
+
72
+ out float fragColor;
73
+
74
+ void main() {
75
+ float sum = 0.0;
76
+ for (int y = 0; y < ${METER_GRID}; y++) {
77
+ for (int x = 0; x < ${METER_GRID}; x++) {
78
+ sum += texelFetch(uMeter, ivec2(x, y), 0).r;
79
+ }
80
+ }
81
+ float measured = sum / ${(METER_GRID * METER_GRID).toFixed(1)};
82
+ float held = texelFetch(uHeld, ivec2(0, 0), 0).r;
83
+ fragColor = mix(held, measured, uBlend);
84
+ }
85
+ `;
86
+ /**
87
+ * `uAutoExposure`, `uExposureHeld` and `autoExposureGain`, for the composite. The gain scales scene
88
+ * light before the tone curve, toward the key by the fraction the caller asked for.
89
+ */
90
+ export const AUTO_EXPOSURE_GLSL = `
91
+ /** How far the frame adapts toward middle grey, 0 to 1. 0 is off and the whole of the off path. */
92
+ uniform float uAutoExposure;
93
+ /** The held log-mean luminance, in stops, one texel. */
94
+ uniform highp sampler2D uExposureHeld;
95
+
96
+ float autoExposureGain() {
97
+ if (uAutoExposure <= 0.0) return 1.0;
98
+ float held = texelFetch(uExposureHeld, ivec2(0, 0), 0).r;
99
+ float stops = uAutoExposure * (${Math.log2(ADAPTED_KEY).toFixed(6)} - held);
100
+ return exp2(clamp(stops, -${ADAPT_RANGE_STOPS.toFixed(1)}, ${ADAPT_RANGE_STOPS.toFixed(1)}));
101
+ }
102
+ `;
103
+ /**
104
+ * The fraction of the way toward this frame's measurement to move, after `dtSec` seconds. A cut,
105
+ * or a first frame with nothing held, snaps.
106
+ */
107
+ export function adaptBlend(dtSec, snap) {
108
+ if (snap)
109
+ return 1;
110
+ if (!(dtSec > 0))
111
+ return 0;
112
+ return 1 - Math.exp(-ADAPT_RATE * dtSec);
113
+ }
114
+ /** The scene's gain for a held log-mean `heldLog2` at `strength`, as the composite computes it. */
115
+ export function autoExposureGain(heldLog2, strength) {
116
+ if (!(strength > 0))
117
+ return 1;
118
+ const stops = strength * (Math.log2(ADAPTED_KEY) - heldLog2);
119
+ return 2 ** Math.min(Math.max(stops, -ADAPT_RANGE_STOPS), ADAPT_RANGE_STOPS);
120
+ }
121
+ /** An adaptation strength as the shader takes it: 0 to 1, anything else off. */
122
+ export function clampAutoExposure(strength) {
123
+ return Number.isFinite(strength) ? Math.min(Math.max(strength, 0), 1) : 0;
124
+ }