@tinypoly/gpu-renderer 0.0.4 → 0.1.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.
- package/ARCHITECTURE.md +81 -10
- package/README.md +53 -5
- package/dist/atmosphere.d.ts +21 -0
- package/dist/atmosphere.d.ts.map +1 -0
- package/dist/atmosphere.js +72 -0
- package/dist/atmosphere.js.map +1 -0
- package/dist/bvh.d.ts +11 -6
- package/dist/bvh.d.ts.map +1 -1
- package/dist/bvh.js +64 -11
- package/dist/bvh.js.map +1 -1
- package/dist/denoise.d.ts +17 -2
- package/dist/denoise.d.ts.map +1 -1
- package/dist/denoise.js +95 -27
- package/dist/denoise.js.map +1 -1
- package/dist/dispatchScheduler.d.ts +11 -4
- package/dist/dispatchScheduler.d.ts.map +1 -1
- package/dist/dispatchScheduler.js +14 -7
- package/dist/dispatchScheduler.js.map +1 -1
- package/dist/frameLayout.d.ts.map +1 -1
- package/dist/frameLayout.js +18 -0
- package/dist/frameLayout.js.map +1 -1
- package/dist/geometry.d.ts.map +1 -1
- package/dist/geometry.js +6 -3
- package/dist/geometry.js.map +1 -1
- package/dist/index.d.ts +4 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -0
- package/dist/index.js.map +1 -1
- package/dist/lensPass.d.ts +60 -0
- package/dist/lensPass.d.ts.map +1 -0
- package/dist/lensPass.js +235 -0
- package/dist/lensPass.js.map +1 -0
- package/dist/lightTree.d.ts +43 -0
- package/dist/lightTree.d.ts.map +1 -0
- package/dist/lightTree.js +107 -0
- package/dist/lightTree.js.map +1 -0
- package/dist/lights.d.ts +19 -1
- package/dist/lights.d.ts.map +1 -1
- package/dist/lights.js +63 -1
- package/dist/lights.js.map +1 -1
- package/dist/materialLayout.d.ts +24 -0
- package/dist/materialLayout.d.ts.map +1 -1
- package/dist/materialLayout.js +36 -1
- package/dist/materialLayout.js.map +1 -1
- package/dist/pathTracePass.d.ts +6 -3
- package/dist/pathTracePass.d.ts.map +1 -1
- package/dist/pathTracePass.js +16 -10
- package/dist/pathTracePass.js.map +1 -1
- package/dist/renderer.d.ts +19 -7
- package/dist/renderer.d.ts.map +1 -1
- package/dist/renderer.js +198 -36
- package/dist/renderer.js.map +1 -1
- package/dist/sceneUpload.d.ts +19 -1
- package/dist/sceneUpload.d.ts.map +1 -1
- package/dist/sceneUpload.js +25 -3
- package/dist/sceneUpload.js.map +1 -1
- package/dist/settings.d.ts +136 -0
- package/dist/settings.d.ts.map +1 -0
- package/dist/settings.js +100 -0
- package/dist/settings.js.map +1 -0
- package/dist/subsurface.d.ts +76 -0
- package/dist/subsurface.d.ts.map +1 -0
- package/dist/subsurface.js +70 -0
- package/dist/subsurface.js.map +1 -0
- package/dist/texturePack.d.ts +16 -4
- package/dist/texturePack.d.ts.map +1 -1
- package/dist/texturePack.js +61 -8
- package/dist/texturePack.js.map +1 -1
- package/dist/volumeContainment.d.ts +17 -0
- package/dist/volumeContainment.d.ts.map +1 -0
- package/dist/volumeContainment.js +61 -0
- package/dist/volumeContainment.js.map +1 -0
- package/dist/wgsl/bsdf.wgsl.d.ts +1 -1
- package/dist/wgsl/bsdf.wgsl.d.ts.map +1 -1
- package/dist/wgsl/bsdf.wgsl.js +35 -3
- package/dist/wgsl/bsdf.wgsl.js.map +1 -1
- package/dist/wgsl/bvh.wgsl.d.ts +8 -2
- package/dist/wgsl/bvh.wgsl.d.ts.map +1 -1
- package/dist/wgsl/bvh.wgsl.js +167 -96
- package/dist/wgsl/bvh.wgsl.js.map +1 -1
- package/dist/wgsl/common.wgsl.d.ts.map +1 -1
- package/dist/wgsl/common.wgsl.js +24 -7
- package/dist/wgsl/common.wgsl.js.map +1 -1
- package/dist/wgsl/lens.wgsl.d.ts +17 -0
- package/dist/wgsl/lens.wgsl.d.ts.map +1 -0
- package/dist/wgsl/lens.wgsl.js +315 -0
- package/dist/wgsl/lens.wgsl.js.map +1 -0
- package/dist/wgsl/lights.wgsl.d.ts +1 -1
- package/dist/wgsl/lights.wgsl.d.ts.map +1 -1
- package/dist/wgsl/lights.wgsl.js +206 -33
- package/dist/wgsl/lights.wgsl.js.map +1 -1
- package/dist/wgsl/pathTrace.wgsl.d.ts +1 -1
- package/dist/wgsl/pathTrace.wgsl.d.ts.map +1 -1
- package/dist/wgsl/pathTrace.wgsl.js +410 -25
- package/dist/wgsl/pathTrace.wgsl.js.map +1 -1
- package/dist/wgsl/random.wgsl.d.ts +1 -1
- package/dist/wgsl/random.wgsl.d.ts.map +1 -1
- package/dist/wgsl/random.wgsl.js +9 -17
- package/dist/wgsl/random.wgsl.js.map +1 -1
- package/dist/wgsl/sampling.wgsl.d.ts +1 -1
- package/dist/wgsl/sampling.wgsl.d.ts.map +1 -1
- package/dist/wgsl/sampling.wgsl.js +25 -0
- package/dist/wgsl/sampling.wgsl.js.map +1 -1
- package/dist/wgsl/surface.wgsl.d.ts +1 -1
- package/dist/wgsl/surface.wgsl.d.ts.map +1 -1
- package/dist/wgsl/surface.wgsl.js +47 -4
- package/dist/wgsl/surface.wgsl.js.map +1 -1
- package/dist/wgsl/texture.wgsl.d.ts +1 -1
- package/dist/wgsl/texture.wgsl.d.ts.map +1 -1
- package/dist/wgsl/texture.wgsl.js +10 -11
- package/dist/wgsl/texture.wgsl.js.map +1 -1
- package/package.json +1 -1
- package/src/atmosphere.ts +95 -0
- package/src/bvh.ts +81 -12
- package/src/denoise.ts +110 -27
- package/src/dispatchScheduler.ts +16 -7
- package/src/frameLayout.ts +18 -0
- package/src/geometry.ts +6 -2
- package/src/index.ts +13 -0
- package/src/lensPass.ts +299 -0
- package/src/lightTree.ts +172 -0
- package/src/lights.ts +90 -2
- package/src/materialLayout.ts +52 -1
- package/src/pathTracePass.ts +19 -10
- package/src/renderer.ts +258 -43
- package/src/sceneUpload.ts +41 -4
- package/src/settings.ts +234 -0
- package/src/subsurface.ts +153 -0
- package/src/texturePack.ts +80 -13
- package/src/volumeContainment.ts +81 -0
- package/src/wgsl/bsdf.wgsl.ts +35 -3
- package/src/wgsl/bvh.wgsl.ts +167 -96
- package/src/wgsl/common.wgsl.ts +24 -7
- package/src/wgsl/lens.wgsl.ts +314 -0
- package/src/wgsl/lights.wgsl.ts +206 -33
- package/src/wgsl/pathTrace.wgsl.ts +410 -25
- package/src/wgsl/random.wgsl.ts +9 -17
- package/src/wgsl/sampling.wgsl.ts +25 -0
- package/src/wgsl/surface.wgsl.ts +47 -4
- package/src/wgsl/texture.wgsl.ts +10 -11
package/dist/wgsl/lights.wgsl.js
CHANGED
|
@@ -41,7 +41,8 @@ fn lightByProbability(u: f32) -> Light {
|
|
|
41
41
|
|
|
42
42
|
let middle = (low + high) / 2u;
|
|
43
43
|
|
|
44
|
-
|
|
44
|
+
// The probabilities packed tight in the texture buffer: the same floats as lights[].cdf, a word apart.
|
|
45
|
+
if (extraFloat(frame.lightCdf + middle) > u) {
|
|
45
46
|
high = middle;
|
|
46
47
|
} else {
|
|
47
48
|
low = middle + 1u;
|
|
@@ -51,11 +52,143 @@ fn lightByProbability(u: f32) -> Light {
|
|
|
51
52
|
return lights[low];
|
|
52
53
|
}
|
|
53
54
|
|
|
55
|
+
const TREE_NODE_WORDS: u32 = 16u;
|
|
56
|
+
const TREE_LEAF: u32 = 0x80000000u;
|
|
57
|
+
const TREE_ROOT_PARENT: u32 = 0xffffffffu;
|
|
58
|
+
const NO_LIGHT: u32 = 0xffffffffu;
|
|
59
|
+
|
|
54
60
|
/**
|
|
55
|
-
*
|
|
56
|
-
*
|
|
61
|
+
* How much the lights under a node of the light tree can deliver to a point: their power over the square of the
|
|
62
|
+
* distance, times how well their cone of directions and the receiving surface face each other, each widened by the
|
|
63
|
+
* angle the node's box takes from the point (Conty Estevez and Kulla's importance). A point inside the box rules
|
|
64
|
+
* nothing out. A zero normal is a receiver that takes light from everywhere, such as a point in a volume.
|
|
57
65
|
*/
|
|
58
|
-
fn
|
|
66
|
+
fn lightNodeImportance(node: u32, position: vec3<f32>, normal: vec3<f32>) -> f32 {
|
|
67
|
+
let at = frame.lightTree + node * TREE_NODE_WORDS;
|
|
68
|
+
let low = extraVec4(at);
|
|
69
|
+
let high = extraVec4(at + 4u);
|
|
70
|
+
let cone = extraVec4(at + 8u);
|
|
71
|
+
|
|
72
|
+
if (low.w <= 0.0) {
|
|
73
|
+
return 0.0;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
let centre = (low.xyz + high.xyz) * 0.5;
|
|
77
|
+
let radius = length(high.xyz - low.xyz) * 0.5;
|
|
78
|
+
let offset = position - centre;
|
|
79
|
+
let distance2 = dot(offset, offset);
|
|
80
|
+
|
|
81
|
+
if (distance2 <= radius * radius) {
|
|
82
|
+
return low.w / max(radius * radius, 1e-12);
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
let distance = sqrt(distance2);
|
|
86
|
+
let spread = asin(clamp(radius / distance, 0.0, 1.0));
|
|
87
|
+
var orientation = 1.0;
|
|
88
|
+
|
|
89
|
+
// A cone of minus one is the whole sphere: such lights shine towards every point alike.
|
|
90
|
+
if (high.w > -1.0) {
|
|
91
|
+
let theta = acos(clamp(dot(cone.xyz, offset / distance), -1.0, 1.0));
|
|
92
|
+
let past = max(0.0, theta - acos(high.w) - spread);
|
|
93
|
+
|
|
94
|
+
orientation = select(0.0, cos(past), past <= acos(clamp(cone.w, -1.0, 1.0)));
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
var facing = 1.0;
|
|
98
|
+
|
|
99
|
+
if (any(normal != vec3<f32>(0.0))) {
|
|
100
|
+
let past = max(0.0, acos(clamp(dot(normal, -offset / distance), -1.0, 1.0)) - spread);
|
|
101
|
+
|
|
102
|
+
facing = select(0.0, cos(past), past < 0.5 * PI);
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
return low.w * orientation * facing / distance2;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** The chance of stepping from a node of the tree to each of its children, from this point. */
|
|
109
|
+
fn lightChildOdds(left: u32, right: u32, position: vec3<f32>, normal: vec3<f32>) -> vec2<f32> {
|
|
110
|
+
var importance = vec2<f32>(0.0);
|
|
111
|
+
|
|
112
|
+
// One loop over the two children, so the importance is written into the kernel once per walk.
|
|
113
|
+
for (var k = 0u; k < 2u; k = k + 1u) {
|
|
114
|
+
importance[k] = lightNodeImportance(select(right, left, k == 0u), position, normal);
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
let total = importance.x + importance.y;
|
|
118
|
+
|
|
119
|
+
return select(importance / total, vec2<f32>(0.0), total <= 0.0);
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/** A light picked down the tree by importance from this point, with the chance of picking it; NO_LIGHT for none. */
|
|
123
|
+
fn sampleLightTree(position: vec3<f32>, normal: vec3<f32>, u: f32, pdf: ptr<function, f32>,
|
|
124
|
+
density: ptr<function, f32>) -> u32 {
|
|
125
|
+
var node = 0u;
|
|
126
|
+
var chance = 1.0;
|
|
127
|
+
var x = u;
|
|
128
|
+
|
|
129
|
+
for (var depth = 0u; depth < 64u; depth = depth + 1u) {
|
|
130
|
+
let at = frame.lightTree + node * TREE_NODE_WORDS;
|
|
131
|
+
let first = textures[at + 12u];
|
|
132
|
+
|
|
133
|
+
if ((first & TREE_LEAF) != 0u) {
|
|
134
|
+
*pdf = chance;
|
|
135
|
+
*density = extraFloat(at + 13u);
|
|
136
|
+
|
|
137
|
+
return first & ~TREE_LEAF;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
let second = textures[at + 13u];
|
|
141
|
+
let odds = lightChildOdds(first, second, position, normal);
|
|
142
|
+
|
|
143
|
+
if (odds.x + odds.y <= 0.0) {
|
|
144
|
+
return NO_LIGHT;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
if (x < odds.x) {
|
|
148
|
+
node = first;
|
|
149
|
+
chance = chance * odds.x;
|
|
150
|
+
x = x / odds.x;
|
|
151
|
+
} else {
|
|
152
|
+
node = second;
|
|
153
|
+
chance = chance * odds.y;
|
|
154
|
+
x = (x - odds.x) / max(odds.y, 1e-20);
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
x = min(x, 0.99999994);
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
return NO_LIGHT;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/** The chance the tree would have picked the local light at this index from this point, walked up from its leaf. */
|
|
164
|
+
fn lightTreePdf(index: u32, position: vec3<f32>, normal: vec3<f32>) -> f32 {
|
|
165
|
+
var node = textures[frame.lightLeaves + index];
|
|
166
|
+
var chance = extraFloat(frame.lightTree + node * TREE_NODE_WORDS + 13u);
|
|
167
|
+
|
|
168
|
+
for (var depth = 0u; depth < 64u; depth = depth + 1u) {
|
|
169
|
+
let parent = textures[frame.lightTree + node * TREE_NODE_WORDS + 14u];
|
|
170
|
+
|
|
171
|
+
if (parent == TREE_ROOT_PARENT) {
|
|
172
|
+
return chance;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
let at = frame.lightTree + parent * TREE_NODE_WORDS;
|
|
176
|
+
let first = textures[at + 12u];
|
|
177
|
+
let odds = lightChildOdds(first, textures[at + 13u], position, normal);
|
|
178
|
+
|
|
179
|
+
chance = chance * select(odds.y, odds.x, node == first);
|
|
180
|
+
node = parent;
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
return 0.0;
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/**
|
|
187
|
+
* The area density with which direct sampling from this point would have picked a point on this triangle, or zero if
|
|
188
|
+
* it never would. Only the leading entries are emissive triangles, and they are in triangle order, so one binary search
|
|
189
|
+
* finds the entry; the tree, when there is one, says how likely it was from here.
|
|
190
|
+
*/
|
|
191
|
+
fn lightPdfOfTriangle(triangle: u32, position: vec3<f32>, normal: vec3<f32>) -> f32 {
|
|
59
192
|
var low = 0u;
|
|
60
193
|
var high = frame.areaLightCount;
|
|
61
194
|
|
|
@@ -65,9 +198,13 @@ fn lightPdfOfTriangle(triangle: u32) -> f32 {
|
|
|
65
198
|
}
|
|
66
199
|
|
|
67
200
|
let middle = (low + high) / 2u;
|
|
68
|
-
let candidate =
|
|
201
|
+
let candidate = textures[frame.lightTriangles + middle];
|
|
69
202
|
|
|
70
203
|
if (candidate == triangle) {
|
|
204
|
+
if (frame.lightTree != 0u) {
|
|
205
|
+
return frame.localLightPick * lightTreePdf(middle, position, normal);
|
|
206
|
+
}
|
|
207
|
+
|
|
71
208
|
return lights[middle].pdf;
|
|
72
209
|
}
|
|
73
210
|
|
|
@@ -127,12 +264,27 @@ fn rectanglePoint(light: Light, u: vec2<f32>) -> vec3<f32> {
|
|
|
127
264
|
* Where the light that pick selects arrives from, and how much of it. u places the point on a surface light or spreads a
|
|
128
265
|
* point light's shadow, so the same two dimensions serve every kind.
|
|
129
266
|
*/
|
|
130
|
-
fn sampleLight(position: vec3<f32>, pick: f32, u: vec2<f32>) -> LightSample {
|
|
267
|
+
fn sampleLight(position: vec3<f32>, normal: vec3<f32>, pick: f32, u: vec2<f32>) -> LightSample {
|
|
131
268
|
if (frame.lightCount == 0u) {
|
|
132
269
|
return noLight();
|
|
133
270
|
}
|
|
134
271
|
|
|
135
|
-
|
|
272
|
+
// The lights in the scene go through the tree, by what they can deliver here; what lies outside it by its weight.
|
|
273
|
+
if (frame.lightTree != 0u && pick < frame.localLightPick) {
|
|
274
|
+
var chance = 0.0;
|
|
275
|
+
var density = 1.0;
|
|
276
|
+
let index = sampleLightTree(position, normal, pick / frame.localLightPick, &chance, &density);
|
|
277
|
+
|
|
278
|
+
if (index == NO_LIGHT || chance <= 0.0) {
|
|
279
|
+
return noLight();
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
return sampleLightEntry(lights[index], frame.localLightPick * chance * density, position, u);
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
let light = lightByProbability(pick);
|
|
286
|
+
|
|
287
|
+
return sampleLightEntry(light, light.pdf, position, u);
|
|
136
288
|
}
|
|
137
289
|
|
|
138
290
|
/** Three's spotLightMap: inside the projection's frustum the texture tints the light; outside it leaves it alone. */
|
|
@@ -159,7 +311,8 @@ fn spotLightTint(light: Light, position: vec3<f32>) -> vec3<f32> {
|
|
|
159
311
|
return sampleTextureRaw(map, projected.xy).rgb;
|
|
160
312
|
}
|
|
161
313
|
|
|
162
|
-
|
|
314
|
+
/** pdf is the chance of picking this light, times the area density of a point on it where it has an area. */
|
|
315
|
+
fn sampleLightEntry(light: Light, pdf: f32, position: vec3<f32>, u: vec2<f32>) -> LightSample {
|
|
163
316
|
var sample: LightSample;
|
|
164
317
|
sample.valid = true;
|
|
165
318
|
sample.kind = light.kind;
|
|
@@ -175,7 +328,7 @@ fn sampleLightEntry(light: Light, position: vec3<f32>, u: vec2<f32>) -> LightSam
|
|
|
175
328
|
return noLight();
|
|
176
329
|
}
|
|
177
330
|
|
|
178
|
-
let density =
|
|
331
|
+
let density = pdf * drawn.pdf;
|
|
179
332
|
|
|
180
333
|
sample.direction = drawn.direction;
|
|
181
334
|
sample.distance = 1e30;
|
|
@@ -190,7 +343,7 @@ fn sampleLightEntry(light: Light, position: vec3<f32>, u: vec2<f32>) -> LightSam
|
|
|
190
343
|
sample.direction = spreadDirection(light.direction, u);
|
|
191
344
|
sample.distance = 1e30;
|
|
192
345
|
// The colour already carries the intensity, which for a directional light is the irradiance it delivers.
|
|
193
|
-
sample.value = light.color /
|
|
346
|
+
sample.value = light.color / pdf;
|
|
194
347
|
|
|
195
348
|
return sample;
|
|
196
349
|
}
|
|
@@ -219,7 +372,7 @@ fn sampleLightEntry(light: Light, position: vec3<f32>, u: vec2<f32>) -> LightSam
|
|
|
219
372
|
|
|
220
373
|
// Stop just short of the light so its own surface is not reported as the blocker.
|
|
221
374
|
sample.distance = distance * (1.0 - 1e-3);
|
|
222
|
-
let density =
|
|
375
|
+
let density = pdf * distanceSquared / cosLight;
|
|
223
376
|
// The emissive map is read at the very point that was sampled, so this agrees with what a bounce ray would find.
|
|
224
377
|
let emission = select(light.color, emissionAt(light.triangle, bary), area);
|
|
225
378
|
|
|
@@ -259,7 +412,7 @@ fn sampleLightEntry(light: Light, position: vec3<f32>, u: vec2<f32>) -> LightSam
|
|
|
259
412
|
|
|
260
413
|
sample.direction = spreadDirection(towards, u);
|
|
261
414
|
sample.distance = distance;
|
|
262
|
-
sample.value = light.color * (power /
|
|
415
|
+
sample.value = light.color * (power / pdf);
|
|
263
416
|
|
|
264
417
|
if (light.kind == LIGHT_SPOT) {
|
|
265
418
|
sample.value = sample.value * spotLightTint(light, position);
|
|
@@ -276,7 +429,7 @@ fn blocksAll(m: u32) -> bool {
|
|
|
276
429
|
let flags = materials[m].flags;
|
|
277
430
|
let blending = materials[m].blending;
|
|
278
431
|
|
|
279
|
-
return (flags & (MATERIAL_TRANSPARENT | MATERIAL_ALPHA_HASH | MATERIAL_WIREFRAME)) == 0u
|
|
432
|
+
return (flags & (MATERIAL_TRANSPARENT | MATERIAL_ALPHA_HASH | MATERIAL_WIREFRAME | MATERIAL_VOLUME)) == 0u
|
|
280
433
|
&& materials[m].alphaTest <= 0.0
|
|
281
434
|
&& materials[m].transmission <= 0.0
|
|
282
435
|
&& materials[m].clipCount == 0u
|
|
@@ -332,45 +485,63 @@ fn blendColor(triangle: u32, bary: vec2<f32>) -> vec3<f32> {
|
|
|
332
485
|
/**
|
|
333
486
|
* How much of the light this sample came from reaches the shaded point. A surface that only partly covers its triangle
|
|
334
487
|
* blocks the ray only that often, which is what makes a cutout leaf cast a cutout shadow; a thin transmissive wall
|
|
335
|
-
* lets its own share through, tinted.
|
|
488
|
+
* lets its own share through, tinted. A volume's boundary lets the ray in or out, and the medium inside takes its
|
|
489
|
+
* share over the distance between; medium is the density at the shaded point itself, zero outside any volume.
|
|
336
490
|
*/
|
|
337
|
-
fn lightTransmittance(
|
|
338
|
-
|
|
339
|
-
|
|
491
|
+
fn lightTransmittance(position: vec3<f32>, chosen: LightSample, rng: ptr<function, PathSampler>, skipMaterial: u32,
|
|
492
|
+
medium: f32) -> vec3<f32> {
|
|
493
|
+
// A light that casts no shadow is blocked by nothing, but a medium on the way still takes its share: then the walk
|
|
494
|
+
// below only looks for volumes and passes every other surface.
|
|
495
|
+
if (!chosen.occlude && !VOLUMES) {
|
|
340
496
|
return vec3<f32>(1.0);
|
|
341
497
|
}
|
|
342
498
|
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
499
|
+
if (chosen.occlude) {
|
|
500
|
+
// Most blockers are plainly opaque, and for those any triangle on the way settles it: the search stops at the
|
|
501
|
+
// first one found instead of looking for the closest. Anything that lets light through goes the long way below.
|
|
502
|
+
let first = traceAny(position, chosen.direction, chosen.distance);
|
|
346
503
|
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
504
|
+
if (first == NO_HIT) {
|
|
505
|
+
return vec3<f32>(exp(-medium * chosen.distance));
|
|
506
|
+
}
|
|
350
507
|
|
|
351
|
-
|
|
508
|
+
let firstMaterial = materialIndexOf(first);
|
|
352
509
|
|
|
353
|
-
|
|
354
|
-
|
|
510
|
+
if (firstMaterial != skipMaterial && blocksAll(firstMaterial)) {
|
|
511
|
+
return vec3<f32>(0.0);
|
|
512
|
+
}
|
|
355
513
|
}
|
|
356
514
|
|
|
357
515
|
var origin = position;
|
|
358
516
|
var remaining = chosen.distance;
|
|
359
517
|
var through = vec3<f32>(1.0);
|
|
518
|
+
// The medium the ray is in, and how far along the ray it entered it.
|
|
519
|
+
var density = medium;
|
|
520
|
+
var travelled = 0.0;
|
|
521
|
+
var enteredAt = 0.0;
|
|
360
522
|
|
|
361
523
|
for (var skip = 0u; skip < MAX_SHADOW_SKIPS; skip = skip + 1u) {
|
|
362
524
|
let blocker = traceScene(origin, chosen.direction, remaining);
|
|
363
525
|
|
|
364
526
|
if (blocker.triangle == NO_HIT) {
|
|
365
|
-
return through;
|
|
527
|
+
return through * exp(-density * (travelled + remaining - enteredAt));
|
|
366
528
|
}
|
|
367
529
|
|
|
368
530
|
let bary = vec2<f32>(blocker.u, blocker.v);
|
|
369
531
|
let m = materialIndexOf(blocker.triangle);
|
|
370
532
|
let blending = materials[m].blending;
|
|
371
533
|
|
|
372
|
-
|
|
373
|
-
|
|
534
|
+
if (VOLUMES && (materials[m].flags & MATERIAL_VOLUME) != 0u) {
|
|
535
|
+
let at = travelled + blocker.distance;
|
|
536
|
+
|
|
537
|
+
if (dot(authoredNormal(blocker.triangle, bary), chosen.direction) < 0.0) {
|
|
538
|
+
density = select(0.0, materials[m].volume.w, frame.volumesEnabled != 0u);
|
|
539
|
+
enteredAt = at;
|
|
540
|
+
} else {
|
|
541
|
+
through = through * exp(-density * (at - enteredAt));
|
|
542
|
+
density = 0.0;
|
|
543
|
+
}
|
|
544
|
+
} else if (chosen.occlude && m != skipMaterial && materials[m].kind != KIND_SHADOW && blending != BLEND_ADDITIVE) {
|
|
374
545
|
let coverage = coverageAt(blocker.triangle, bary, chosen.direction);
|
|
375
546
|
|
|
376
547
|
if (blending == BLEND_MULTIPLY) {
|
|
@@ -389,13 +560,15 @@ fn lightTransmittance(
|
|
|
389
560
|
// The ray carries on from just past the surface it saw through.
|
|
390
561
|
origin = origin + chosen.direction * (blocker.distance + RAY_EPSILON);
|
|
391
562
|
remaining = remaining - blocker.distance - RAY_EPSILON;
|
|
563
|
+
travelled = travelled + blocker.distance + RAY_EPSILON;
|
|
392
564
|
|
|
393
565
|
if (remaining <= RAY_EPSILON) {
|
|
394
|
-
return through;
|
|
566
|
+
return through * exp(-density * (travelled - enteredAt));
|
|
395
567
|
}
|
|
396
568
|
}
|
|
397
569
|
|
|
398
|
-
|
|
570
|
+
// Too many surfaces to see through: a shadow ray gives up dark, a ray that only counts the media keeps what it has.
|
|
571
|
+
return select(vec3<f32>(0.0), through, !chosen.occlude);
|
|
399
572
|
}
|
|
400
573
|
|
|
401
574
|
/**
|
|
@@ -417,13 +590,13 @@ fn shadowMaskAt(position: vec3<f32>, rng: ptr<function, PathSampler>) -> f32 {
|
|
|
417
590
|
continue;
|
|
418
591
|
}
|
|
419
592
|
|
|
420
|
-
let chosen = sampleLightEntry(light, position, sample2D(rng));
|
|
593
|
+
let chosen = sampleLightEntry(light, light.pdf, position, sample2D(rng));
|
|
421
594
|
|
|
422
595
|
if (!chosen.valid) {
|
|
423
596
|
continue;
|
|
424
597
|
}
|
|
425
598
|
|
|
426
|
-
let visible = luminanceOf(lightTransmittance(position, chosen, rng, NO_MATERIAL));
|
|
599
|
+
let visible = luminanceOf(lightTransmittance(position, chosen, rng, NO_MATERIAL, 0.0));
|
|
427
600
|
|
|
428
601
|
shadow = max(shadow, 1.0 - clamp(visible, 0.0, 1.0));
|
|
429
602
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"lights.wgsl.js","sourceRoot":"","sources":["../../src/wgsl/lights.wgsl.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AACH,MAAM,CAAC,MAAM,WAAW,GAAG,UAAU,CAAC
|
|
1
|
+
{"version":3,"file":"lights.wgsl.js","sourceRoot":"","sources":["../../src/wgsl/lights.wgsl.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AACH,MAAM,CAAC,MAAM,WAAW,GAAG,UAAU,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAqlBrC,CAAC"}
|
|
@@ -10,5 +10,5 @@
|
|
|
10
10
|
* reflection: culled faces, the background, Three's fog, a light map's baked light and the coverage a transparent
|
|
11
11
|
* background turns into alpha. Transmission keeps a path on that line, as Three's transmission shows what is behind.
|
|
12
12
|
*/
|
|
13
|
-
export declare const PATH_TRACE_WGSL = "\n/** Light from an ambient or hemisphere light, which this renderer turns into an equally bright surrounding. */\nfn ambientRadiance(direction: vec3<f32>) -> vec3<f32> {\n let latitude = clamp(dot(direction, frame.ambientAxis.xyz) * 0.5 + 0.5, 0.0, 1.0);\n\n return mix(frame.ambientGround.rgb, frame.ambientSky.rgb, latitude) + probeRadiance(direction);\n}\n\n/**\n * A LightProbe's light. Three's coefficients are radiance projected on the SH3 basis, which its shader convolves with\n * the cosine to get irradiance; evaluated directly they are the surrounding that delivers exactly that irradiance.\n */\nfn probeRadiance(d: vec3<f32>) -> vec3<f32> {\n let radiance = frame.probe0.rgb * 0.282095\n + frame.probe1.rgb * (0.488603 * d.y)\n + frame.probe2.rgb * (0.488603 * d.z)\n + frame.probe3.rgb * (0.488603 * d.x)\n + frame.probe4.rgb * (1.092548 * d.x * d.y)\n + frame.probe5.rgb * (1.092548 * d.y * d.z)\n + frame.probe6.rgb * (0.315392 * (3.0 * d.z * d.z - 1.0))\n + frame.probe7.rgb * (1.092548 * d.x * d.z)\n + frame.probe8.rgb * (0.546274 * (d.x * d.x - d.y * d.y));\n\n return max(radiance, vec3<f32>(0.0));\n}\n\n/** What the camera sees where nothing is in the way, as the background setting says. */\nfn backgroundRadiance(direction: vec3<f32>) -> vec3<f32> {\n if (frame.background.w == 1.0) {\n return frame.background.rgb;\n }\n\n // A procedural sky paints the background without the strength it lights with, and its foreground over it.\n if (frame.skyProgram != NO_PROGRAM || frame.skyIntensity > 0.0) {\n if (frame.skyBackground == 0u) {\n return vec3<f32>(0.0);\n }\n\n if (frame.skyProgram != NO_PROGRAM) {\n var input: ShaderInput;\n input.data = frame.skyData;\n input.direction = direction;\n input.diffuseColor = vec4<f32>(1.0);\n\n return runProgram(frame.skyProgram, input).color.rgb;\n }\n\n return environmentRadiance(direction) / frame.skyIntensity;\n }\n\n return environmentRadiance(direction);\n}\n\n/**\n * How much of the sky a bounce ray that escaped keeps. Direct sampling aims at the bright parts of an image too, so the\n * two share it; when direct sampling took all of it, as it does from a toon surface, the bounce keeps none.\n */\nfn escapeWeight(direction: vec3<f32>, bsdfPdf: f32, lightsOwnDirect: bool) -> f32 {\n if (frame.environmentPick <= 0.0) {\n return 1.0;\n }\n\n if (lightsOwnDirect) {\n return 0.0;\n }\n\n if (bsdfPdf <= 0.0) {\n return 1.0;\n }\n\n return misWeight(bsdfPdf, frame.environmentPick * environmentPdf(direction));\n}\n\n/** Scales a contribution down to the luminance ceiling, which trades a little bias for the fireflies it removes. */\nfn clampIndirect(contribution: vec3<f32>) -> vec3<f32> {\n let luminance = luminanceOf(contribution);\n\n if (frame.clampIndirect <= 0.0 || luminance <= frame.clampIndirect) {\n return contribution;\n }\n\n return contribution * (frame.clampIndirect / luminance);\n}\n\n/**\n * How much of the emission a bounce ray found the renderer keeps. Direct sampling had its own chance at this triangle,\n * and the heuristic splits the two so neither counts it twice.\n */\nfn emissionWeight(hit: Hit, direction: vec3<f32>, bsdfPdf: f32, lightsOwnDirect: bool) -> f32 {\n if (frame.areaLightCount == 0u) {\n return 1.0;\n }\n\n let areaPdf = lightPdfOfTriangle(hit.triangle);\n\n if (areaPdf <= 0.0) {\n return 1.0;\n }\n\n if (lightsOwnDirect) {\n return 0.0;\n }\n\n if (bsdfPdf <= 0.0) {\n return 1.0;\n }\n\n let cosLight = max(abs(dot(triangleNormal(hit.triangle), direction)), 1e-6);\n\n return misWeight(bsdfPdf, areaPdf * hit.distance * hit.distance / cosLight);\n}\n\n/** One shadow ray from the surface towards a light, weighted against the chance the bounce would have found it too. */\nfn directLight(\n surface: Surface,\n position: vec3<f32>,\n view: vec3<f32>,\n pick: f32,\n u: vec2<f32>,\n rng: ptr<function, PathSampler>,\n diffusePart: ptr<function, vec3<f32>>) -> vec3<f32> {\n *diffusePart = vec3<f32>(0.0);\n\n let chosen = sampleLight(position, pick, u);\n\n if (!chosen.valid) {\n return vec3<f32>(0.0);\n }\n\n // A material with its own environment map sees that map in place of the scene's surroundings.\n if (chosen.kind == LIGHT_ENVIRONMENT && surface.envMap != NO_TEXTURE) {\n return vec3<f32>(0.0);\n }\n\n let reflected = evaluateBsdf(surface, view, chosen.direction);\n\n if (all(reflected.value <= vec3<f32>(0.0))) {\n return vec3<f32>(0.0);\n }\n\n let toon = surface.kind == KIND_TOON;\n // Three's shadow map leaves a toon mesh's own far side unshadowed; tracing through the mesh would not.\n let skip = select(NO_MATERIAL, surface.material, toon && dot(surface.normal, chosen.direction) < 0.1);\n let through = lightTransmittance(position, chosen, rng, skip);\n\n if (all(through <= vec3<f32>(0.0))) {\n return vec3<f32>(0.0);\n }\n\n // A light that no bounce ray could have found keeps its whole contribution; an emissive triangle shares it. A toon\n // surface takes all of its direct light this way, because its bounce is not the lobe that lit it.\n let weight = select(1.0, misWeight(chosen.misPdf, reflected.pdf), chosen.misPdf > 0.0 && reflected.pdf > 0.0 && !toon);\n\n let light = chosen.value * through * weight;\n\n // The share of it the diffuse lobe reflects, which the denoiser filters apart from the specular one.\n *diffusePart = min(diffuseValue(surface, view, chosen.direction), reflected.value) * light;\n\n return reflected.value * light;\n}\n\n/** Three's fog factor at a view depth: linear between near and far, or exponential squared. */\nfn fogFactor(depth: f32, kind: f32) -> f32 {\n if (kind == 2.0) {\n let density = frame.fogParams.z;\n\n return clamp(1.0 - exp(-density * density * depth * depth), 0.0, 1.0);\n }\n\n return smoothstep(frame.fogParams.x, frame.fogParams.y, depth);\n}\n\n/** The colour the diffuse signal is divided by at this surface; white where the surface shows what it emits. */\nfn diffuseGuide(surface: Surface) -> vec3<f32> {\n if ((surface.flags & MATERIAL_LIT) == 0u) {\n return vec3<f32>(1.0);\n }\n\n return surface.albedo * (1.0 - surface.metalness) * (1.0 - clamp(surface.transmission, 0.0, 1.0));\n}\n\nstruct PathResult {\n radiance: vec3<f32>,\n alpha: f32,\n // How far along the camera ray the first surface it stopped at is, or 1e30 when it stopped at none.\n depth: f32,\n // The denoiser's two signals: what of the radiance came through the first surface's diffuse lobe (and what the camera\n // sees directly), the rest being specular, and what guides each at that surface.\n diffuse: vec3<f32>,\n diffuseAlbedo: vec3<f32>,\n specularAlbedo: vec3<f32>,\n normal: vec3<f32>,\n // Along the camera ray to the first surface, its roughness, and how far the specular continuation went from it.\n guideDistance: f32,\n roughness: f32,\n specularDistance: f32,\n};\n\n/** How many surfaces a path may pass through without scattering (cutouts, culled faces, glass) before it gives up. */\nconst MAX_STEPS: u32 = 64u;\n\nfn traceRadiance(\n rayOrigin: vec3<f32>, rayDirection: vec3<f32>, rayLength: f32, rng: ptr<function, PathSampler>) -> PathResult {\n var radiance = vec3<f32>(0.0);\n var throughput = vec3<f32>(1.0);\n var origin = rayOrigin;\n var direction = rayDirection;\n var limit = rayLength;\n // Solid angle density of the current direction; zero for the camera ray, which no light sampling competes with.\n var bsdfPdf = 0.0;\n // What the volume the ray is travelling through absorbs per unit of distance; zero outside any.\n var absorption = vec3<f32>(0.0);\n // Still on the camera's own line of sight, which transmission keeps a path on.\n var primary = true;\n // Still the camera ray itself, in a straight line: only this one is culled and clipped by the far plane.\n var straight = true;\n var alpha = 0.0;\n var bounce = 0u;\n // The vertex the path last scattered at took all of its direct light by sampling lights: a toon surface.\n var lightsOwnDirect = false;\n // That vertex's own environment map, which a ray escaping from it sees instead of the scene's.\n var escapeMap = NO_TEXTURE;\n var escapeIntensity = 1.0;\n // Which colour a dispersive path carries, once a dispersive volume has split it; all three before that.\n var channel = vec3<f32>(1.0);\n // Three's fog, laid over everything the camera sees through the first surface.\n var fogged = false;\n var fogAmount = 0.0;\n var fogStart = vec3<f32>(0.0);\n var fogThroughput = vec3<f32>(0.0);\n // A built-in material's hooks after <opaque_fragment> edit the colour the camera sees of it, which is everything the\n // path gathers from that surface on.\n var afterMaterial = NO_MATERIAL;\n var afterTriangle = 0u;\n var afterBary = vec2<f32>(0.0);\n var afterDirection = vec3<f32>(0.0);\n var afterAlbedo = vec4<f32>(0.0);\n var afterStart = vec3<f32>(0.0);\n var afterThroughput = vec3<f32>(0.0);\n var depth = 1e30;\n // The denoiser's guides, taken at the first surface the camera ray stops at.\n var guided = false;\n var diffuseAlbedo = vec3<f32>(1.0);\n var specularAlbedoGuide = vec3<f32>(1.0);\n var guideNormal = vec3<f32>(0.0);\n var guideDistance = 1e6;\n var guideRoughness = 1.0;\n // Where the path first scattered, which decides which of the two signals the rest of it feeds.\n var split = false;\n var splitBase = vec3<f32>(0.0);\n var splitDirect = vec3<f32>(0.0);\n var splitDirectDiffuse = vec3<f32>(0.0);\n var splitDiffuse = true;\n var waitingForSpecular = false;\n var specularDistance = 1e6;\n\n for (var step = 0u; step < MAX_STEPS; step = step + 1u) {\n let hit = traceScene(origin, direction, limit);\n\n // The specular continuation's first hit: how far the reflection the denoiser filters actually is.\n if (waitingForSpecular) {\n specularDistance = select(min(hit.distance, 1e6), 1e6, hit.triangle == NO_HIT);\n waitingForSpecular = false;\n }\n\n if (hit.triangle == NO_HIT) {\n if (primary) {\n // A transparent background leaves the pixel empty, which its alpha says.\n if (frame.background.w != 2.0) {\n alpha = 1.0;\n radiance = radiance + throughput * backgroundRadiance(direction);\n }\n } else {\n var sky = ambientRadiance(direction);\n\n if (escapeMap != NO_TEXTURE) {\n sky = sky + sampleEquirect(escapeMap, direction).rgb * escapeIntensity;\n } else {\n sky = sky + environmentRadiance(direction) * escapeWeight(direction, bsdfPdf, lightsOwnDirect);\n }\n\n let contribution = throughput * sky;\n\n radiance = radiance + select(contribution, clampIndirect(contribution), bounce > 1u);\n }\n\n break;\n }\n\n throughput = throughput * exp(-absorption * hit.distance);\n\n let bary = vec2<f32>(hit.u, hit.v);\n let point = origin + direction * hit.distance;\n let m = materialIndexOf(hit.triangle);\n\n // Every vertex draws the same dimensions in the same order, whatever the path then does with them.\n let coverage = sample2D(rng);\n let pick = sample2D(rng);\n let lightSample = sample2D(rng);\n let lobe = sample2D(rng);\n let bounceSample = sample2D(rng);\n\n // Three culls the side a material does not draw. Only the camera's rays are culled: a mesh still casts shadows and\n // holds light in from both sides.\n // A planar capture drops what lies behind its plane, for the camera's own ray.\n let clipped = any(frame.clipPlane != vec4<f32>(0.0)) && dot(frame.clipPlane.xyz, point) + frame.clipPlane.w < 0.0;\n\n if (straight && (clipped || isCulled(m, hit.triangle, direction))) {\n origin = point + direction * RAY_EPSILON;\n limit = limit - hit.distance;\n continue;\n }\n\n if (isClipped(m, point)\n || ((materials[m].flags & MATERIAL_WIREFRAME) != 0u && !onWireframe(hit.triangle, point))) {\n origin = point + direction * RAY_EPSILON;\n limit = select(1e30, limit - hit.distance, straight);\n continue;\n }\n\n let surface = resolveSurface(hit.triangle, bary, direction);\n\n // Blending other than normal: the surface adds its light to, or filters, whatever is behind it, and the path goes on.\n if (surface.blending == BLEND_ADDITIVE || surface.blending == BLEND_MULTIPLY || surface.blending == BLEND_SUBTRACTIVE) {\n // Three blends these with the fragment's alpha whether or not the material is transparent.\n let strength = surface.opacity * clamp(surface.alpha, 0.0, 1.0);\n let color = select(surface.albedo, surface.emissive, (surface.flags & MATERIAL_LIT) == 0u);\n\n if (surface.blending == BLEND_ADDITIVE) {\n var added = surface.emissive;\n\n if ((surface.flags & MATERIAL_LIT) != 0u) {\n var unused: vec3<f32>;\n added = added + directLight(surface, point + surface.normal * RAY_EPSILON, -direction, pick.x, lightSample, rng,\n &unused);\n }\n\n radiance = radiance + throughput * added * strength;\n } else if (surface.blending == BLEND_MULTIPLY) {\n throughput = throughput * mix(vec3<f32>(1.0), color, strength);\n } else {\n throughput = throughput * (vec3<f32>(1.0) - color * strength);\n }\n\n origin = point + direction * RAY_EPSILON;\n limit = select(1e30, limit - hit.distance, straight);\n continue;\n }\n\n // A surface that only partly covers its triangle lets the ray straight through the rest of the time. The direction\n // does not change, so the density that found it still stands and the next hit is weighted against the same one.\n if (surface.opacity < 1.0 && coverage.x >= surface.opacity) {\n origin = point + direction * RAY_EPSILON;\n limit = select(1e30, limit - hit.distance, straight);\n continue;\n }\n\n // Three's ShadowMaterial shows its colour only where a light is blocked, and nothing elsewhere.\n if (surface.kind == KIND_SHADOW) {\n let shadow = shadowMaskAt(point + surface.facing * RAY_EPSILON, rng);\n\n if (coverage.y >= shadow * clamp(materials[m].color.w, 0.0, 1.0)) {\n origin = point + direction * RAY_EPSILON;\n limit = select(1e30, limit - hit.distance, straight);\n continue;\n }\n\n if (primary) {\n alpha = 1.0;\n }\n\n radiance = radiance + throughput * surface.albedo;\n break;\n }\n\n if (straight && depth >= 1e30) {\n depth = length(point - rayOrigin);\n }\n\n if (straight && !guided) {\n guided = true;\n diffuseAlbedo = diffuseGuide(surface);\n specularAlbedoGuide = select(specularAlbedo(surface, -direction), vec3<f32>(1.0), (surface.flags & MATERIAL_LIT) == 0u);\n guideNormal = surface.normal;\n guideDistance = length(point - rayOrigin);\n guideRoughness = surface.roughness;\n\n if (surface.kind == KIND_PHONG) {\n // Phong's exponent as the roughness of the GGX lobe that is about as wide.\n guideRoughness = pow(2.0 / (surface.shininess + 2.0), 0.25);\n }\n }\n\n if (primary) {\n alpha = 1.0;\n\n if (!fogged && afterMaterial == NO_MATERIAL && materials[m].afterProgram != NO_PROGRAM) {\n afterMaterial = m;\n afterTriangle = hit.triangle;\n afterBary = bary;\n afterDirection = direction;\n afterAlbedo = vec4<f32>(surface.albedo, surface.alpha);\n afterStart = radiance;\n afterThroughput = throughput;\n }\n\n if (!fogged) {\n let everySurface = frame.fogParams.w > 0.0;\n let kind = frame.fogColor.w;\n\n if (everySurface || (kind > 0.0 && (surface.flags & MATERIAL_FOG) != 0u)) {\n let depth = -(frame.worldToCamera * vec4<f32>(point, 1.0)).z;\n\n fogged = true;\n fogAmount = fogFactor(depth, select(kind, 1.0, everySurface));\n fogStart = radiance;\n fogThroughput = throughput;\n }\n }\n\n radiance = radiance + throughput * surface.lightMap;\n }\n\n if (any(surface.emissive > vec3<f32>(0.0))) {\n let contribution = throughput * surface.emissive * emissionWeight(hit, direction, bsdfPdf, lightsOwnDirect);\n\n // Seen by the camera or one bounce away this is direct light and stays exact; deeper it may be clamped.\n radiance = radiance + select(contribution, clampIndirect(contribution), bounce > 1u);\n }\n\n // Three does not light a basic, points, line or sprite material, so nothing carries on from one.\n if ((surface.flags & MATERIAL_LIT) == 0u || bounce >= frame.bounces) {\n break;\n }\n\n // Lambert and Phong blend their own environment map over the lit colour, which here is a share of the path.\n if (surface.legacyAmount > 0.0) {\n let amount = surface.legacyAmount;\n\n if (surface.combine == 1u) {\n radiance = radiance + throughput * surface.legacyEnv * amount;\n throughput = throughput * (1.0 - amount);\n } else if (surface.combine == 2u) {\n radiance = radiance + throughput * surface.legacyEnv * amount;\n } else {\n throughput = throughput * mix(vec3<f32>(1.0), surface.legacyEnv, amount);\n }\n }\n\n let view = -direction;\n var next = direction;\n var nextOrigin = point + direction * RAY_EPSILON;\n\n // Transmission replaces part of the diffuse layer, so that share of the time the surface is a dielectric instead.\n // Choosing it in proportion to its weight leaves both halves unweighted, and only the opaque half aims at a light.\n if (surface.transmission > 0.0 && lobe.y < surface.transmission) {\n var ior = surface.ior;\n\n // Three's dispersion: each colour refracts with its own index, spread around the material's. The path picks one\n // colour the first time it enters such a volume and carries only that one from then on.\n if (surface.dispersion > 0.0 && surface.thickness > 0.0) {\n if (all(channel == vec3<f32>(1.0))) {\n let which = min(u32(coverage.y * 3.0), 2u);\n\n channel = vec3<f32>(select(0.0, 1.0, which == 0u), select(0.0, 1.0, which == 1u), select(0.0, 1.0, which == 2u));\n throughput = throughput * channel * 3.0;\n }\n\n let spread = (ior - 1.0) * 0.025 * surface.dispersion;\n\n ior = dot(channel, vec3<f32>(ior - spread, ior, ior + spread));\n }\n\n let crossing = sampleDielectric(surface, view, ior, lobe.y / surface.transmission, bounceSample);\n\n if (!crossing.valid) {\n break;\n }\n\n // Bending or reflecting off glass is the specular signal.\n if (!split && !crossing.straight) {\n split = true;\n splitBase = radiance;\n splitDiffuse = false;\n waitingForSpecular = true;\n }\n\n throughput = throughput * crossing.weight;\n\n // Straight through a thin wall the direction stands, and with it the density that will weigh the next hit.\n if (!crossing.straight) {\n straight = false;\n next = crossing.direction;\n nextOrigin = point + surface.normal * select(RAY_EPSILON, -RAY_EPSILON, crossing.crossed);\n // A direction no light sampling could have produced: whatever the path finds next keeps its whole value.\n bsdfPdf = 0.0;\n lightsOwnDirect = false;\n escapeMap = surface.envMap;\n escapeIntensity = surface.envMapIntensity;\n\n if (crossing.crossed) {\n absorption = select(vec3<f32>(0.0), surface.absorption, surface.front);\n } else {\n primary = false;\n }\n }\n\n if (!primary) {\n bounce = bounce + 1u;\n }\n } else {\n let position = point + surface.normal * RAY_EPSILON;\n var directDiffuse: vec3<f32>;\n let direct = throughput * directLight(surface, position, view, pick.x, lightSample, rng, &directDiffuse);\n let added = select(direct, clampIndirect(direct), bounce > 0u);\n let before = radiance;\n\n radiance = radiance + added;\n\n let scattered = sampleBsdf(surface, view, lobe.x, bounceSample);\n\n // The first scatter splits the path: its direct light by lobe, and everything after it by the lobe it chose.\n if (!split) {\n split = true;\n splitBase = before;\n splitDirect = added;\n splitDirectDiffuse = throughput * directDiffuse * select(1.0, luminanceOf(added) / max(luminanceOf(direct), 1e-20),\n bounce > 0u);\n splitDiffuse = !scattered.valid || scattered.diffuse;\n waitingForSpecular = scattered.valid && !scattered.diffuse;\n }\n\n if (!scattered.valid) {\n break;\n }\n\n throughput = throughput * scattered.weight;\n bsdfPdf = scattered.pdf;\n lightsOwnDirect = surface.kind == KIND_TOON;\n escapeMap = surface.envMap;\n escapeIntensity = surface.envMapIntensity;\n next = scattered.direction;\n nextOrigin = position;\n primary = false;\n straight = false;\n bounce = bounce + 1u;\n }\n\n // A path that carries almost nothing is ended by chance rather than by a cut, which keeps the estimate unbiased.\n let survival = max(throughput.r, max(throughput.g, throughput.b));\n\n if (survival <= 0.0) {\n break;\n }\n\n if (survival < 0.2) {\n if (pick.y > survival) {\n break;\n }\n\n throughput = throughput / survival;\n }\n\n origin = nextOrigin;\n limit = select(1e30, limit - hit.distance, straight);\n direction = next;\n }\n\n // The diffuse signal: everything before the first scatter, its diffuse direct light, and the rest if the diffuse lobe\n // carried the path on. A path that never scattered is all diffuse, which is what the camera sees directly.\n var diffuse = radiance;\n\n if (split) {\n let after = radiance - splitBase - splitDirect;\n diffuse = splitBase + splitDirectDiffuse + select(vec3<f32>(0.0), after, splitDiffuse);\n }\n\n if (afterMaterial != NO_MATERIAL && all(afterThroughput > vec3<f32>(0.0))) {\n var input = shaderInputAt(afterMaterial, afterTriangle, afterBary, afterDirection);\n input.data = materials[afterMaterial].afterData;\n input.diffuseColor = afterAlbedo;\n input.fragColor = vec4<f32>((radiance - afterStart) / afterThroughput, 1.0);\n\n let edited = runProgram(materials[afterMaterial].afterProgram, input);\n\n radiance = afterStart + afterThroughput * edited.color.rgb;\n // A hook rewrites the colour as a whole: there is no split left to keep.\n diffuse = radiance;\n }\n\n // Three lays its fog after the hooks, over what they made of the surface.\n if (fogged) {\n let fog = frame.fogColor.rgb * fogThroughput * fogAmount;\n\n radiance = fogStart + (radiance - fogStart) * (1.0 - fogAmount) + fog;\n // What came before the fogged surface is diffuse, so the fog's own colour joins that signal.\n diffuse = fogStart + (diffuse - fogStart) * (1.0 - fogAmount) + fog;\n }\n\n var result: PathResult;\n result.radiance = radiance;\n result.alpha = alpha;\n result.depth = depth;\n result.diffuse = diffuse;\n result.diffuseAlbedo = diffuseAlbedo;\n result.specularAlbedo = specularAlbedoGuide;\n result.normal = guideNormal;\n result.guideDistance = guideDistance;\n result.roughness = guideRoughness;\n result.specularDistance = specularDistance;\n\n return result;\n}\n\n/** A point on the lens: a disk, or Three-free polygon bokeh shaped as the CPU renderer shapes it. */\nfn lensPoint(u: vec2<f32>) -> vec2<f32> {\n var radius = sqrt(u.x) * frame.lens.x;\n let angle = u.y * 2.0 * PI;\n let blades = frame.lens.z;\n\n if (blades >= 3.0) {\n let wedge = 2.0 * PI / blades;\n radius = radius * cos(PI / blades) / cos((angle - floor(angle / wedge) * wedge) - PI / blades);\n }\n\n return vec2<f32>(cos(angle), sin(angle)) * radius;\n}\n\n/**\n * Where a sample's camera ray starts, which way it points and how far it may go, for any camera: the ray is cast through\n * the inverse of the camera's own projection, from the near plane to the far one, which clip it as Three clips a\n * fragment. A lens moves the origin across its aperture and aims at the point in focus.\n */\nfn cameraRay(pixel: vec2<u32>, jitter: vec2<f32>, lens: vec2<f32>) -> array<vec4<f32>, 2> {\n let uv = (vec2<f32>(pixel) + jitter) / vec2<f32>(frame.resolution);\n let ndc = vec2<f32>(uv.x * 2.0 - 1.0, 1.0 - uv.y * 2.0);\n let ray = ndcRay(ndc);\n\n if (frame.lens.x <= 0.0 || frame.cameraKind == 1u) {\n return ray;\n }\n\n let position = frame.cameraToWorld[3].xyz;\n let forward = -normalize(frame.cameraToWorld[2].xyz);\n let focus = position + ray[1].xyz * (frame.lens.y / max(dot(ray[1].xyz, forward), 1e-6));\n let offset = lensPoint(lens);\n let origin = position + normalize(frame.cameraToWorld[0].xyz) * offset.x + normalize(frame.cameraToWorld[1].xyz) * offset.y;\n\n return array<vec4<f32>, 2>(vec4<f32>(origin, 0.0), vec4<f32>(normalize(focus - origin), 1e30));\n}\n\n/** The window depth GL would store for the first surface the camera ray stopped at: one where it stopped at none. */\nfn windowDepth(point: vec3<f32>, distance: f32) -> f32 {\n if (distance >= 1e30) {\n return 1.0;\n }\n\n let clip = frame.projection * (frame.worldToCamera * vec4<f32>(point, 1.0));\n\n return clamp(clip.z / clip.w * 0.5 + 0.5, 0.0, 1.0);\n}\n\n/** smoothstep as the CPU renderer writes it, which also holds when the two edges meet. */\nfn edge(low: f32, high: f32, value: f32) -> f32 {\n let t = select(select(0.0, 1.0, value >= high), clamp((value - low) / (high - low), 0.0, 1.0), high > low);\n\n return t * t * (3.0 - 2.0 * t);\n}\n\n/** How much of what lies at this point the fog lets through to the camera. */\nfn fogVisibility(point: vec3<f32>) -> f32 {\n let everySurface = frame.fogParams.w > 0.0;\n let kind = frame.fogColor.w;\n\n if (!everySurface && kind <= 0.0) {\n return 1.0;\n }\n\n let depth = -(frame.worldToCamera * vec4<f32>(point, 1.0)).z;\n\n return 1.0 - fogFactor(depth, select(kind, 1.0, everySurface));\n}\n\n/** The most volumetric lights one view ray marches through. */\nconst MAX_VOLUMETRIC: u32 = 8u;\n\n/**\n * Steps of one march. The CPU renderer marches 64 once per pixel; here every path marches, a few hundred times a\n * pixel, each at its own random offset, so a few steps a path add up to a finer integral than 64 once, at a fraction of\n * the shadow rays.\n */\nconst MARCH_STEPS: u32 = 8u;\n\n/**\n * The CPU renderer's volumetric lights (volumetricLight.js): one march across the union of every light's\n * reach along the view ray, Henyey-Greenstein scattering towards the camera, a shadow ray for a spot light that casts\n * one, and the same compression of the sum before it is added over the image.\n */\nfn volumetricGlow(origin: vec3<f32>, direction: vec3<f32>, distance: f32, jitter: f32) -> vec3<f32> {\n let count = min(frame.volumetricCount, MAX_VOLUMETRIC);\n let far = min(distance, 40.0);\n var tStart = far;\n var tEnd = 0.0;\n\n for (var k = 0u; k < count; k = k + 1u) {\n let at = frame.volumetricData + k * 20u;\n let position = extraVec4(at).xyz;\n let spot = extraFloat(at + 3u) > 0.5;\n let axis = extraVec4(at + 4u).xyz;\n let radius = extraFloat(at + 7u);\n let outer = extraFloat(at + 15u);\n let delta = origin - position;\n let b = dot(delta, direction);\n let disc = b * b - dot(delta, delta) + radius * radius;\n\n if (disc <= 0.0) {\n continue;\n }\n\n let start = max(0.0, -b - sqrt(disc));\n let end = min(far, -b + sqrt(disc));\n\n if (end <= start) {\n continue;\n }\n\n var cuts = array<f32, 4>(start, end, end, end);\n var cutCount = 2u;\n let cone = cos(outer);\n\n if (spot) {\n let ar = dot(axis, direction);\n let ac = dot(axis, delta);\n let cos2 = cone * cone;\n let qa = ar * ar - cos2;\n let qb = ar * ac - dot(direction, delta) * cos2;\n let qc = ac * ac - dot(delta, delta) * cos2;\n let discriminant = qb * qb - qa * qc;\n var roots = array<f32, 2>(-1.0, -1.0);\n\n if (abs(qa) < 1e-8) {\n if (abs(qb) > 1e-8) {\n roots[0] = -qc / (2.0 * qb);\n }\n } else if (discriminant >= 0.0) {\n roots[0] = (-qb - sqrt(discriminant)) / qa;\n roots[1] = (-qb + sqrt(discriminant)) / qa;\n }\n\n for (var r = 0u; r < 2u; r = r + 1u) {\n if (roots[r] > start && roots[r] < end) {\n cuts[cutCount] = roots[r];\n cutCount = cutCount + 1u;\n }\n }\n\n // Sort the few cuts in place.\n for (var i = 1u; i < cutCount; i = i + 1u) {\n var j = i;\n\n loop {\n if (j == 0u || cuts[j - 1u] <= cuts[j]) {\n break;\n }\n\n let swap = cuts[j];\n cuts[j] = cuts[j - 1u];\n cuts[j - 1u] = swap;\n j = j - 1u;\n }\n }\n }\n\n for (var segment = 1u; segment < cutCount; segment = segment + 1u) {\n let lo = cuts[segment - 1u];\n let hi = cuts[segment];\n\n if (spot && dot(normalize(delta + direction * ((lo + hi) * 0.5)), axis) < cone) {\n continue;\n }\n\n tStart = min(tStart, lo);\n tEnd = max(tEnd, hi);\n }\n }\n\n if (tEnd <= tStart) {\n return vec3<f32>(0.0);\n }\n\n let step = (tEnd - tStart) / f32(MARCH_STEPS);\n var transmittance: array<f32, 8>;\n\n for (var k = 0u; k < count; k = k + 1u) {\n transmittance[k] = exp(-extraFloat(frame.volumetricData + k * 20u + 11u) * tStart);\n }\n\n var result = vec3<f32>(0.0);\n\n for (var i = 0u; i < MARCH_STEPS; i = i + 1u) {\n let t = tStart + (f32(i) + jitter) * step;\n let p = origin + direction * t;\n let fogged = fogVisibility(p);\n\n if (fogged <= 0.0001) {\n break;\n }\n\n var lit = false;\n\n for (var k = 0u; k < count; k = k + 1u) {\n if (transmittance[k] <= 0.003) {\n continue;\n }\n\n lit = true;\n\n let at = frame.volumetricData + k * 20u;\n let position = extraVec4(at).xyz;\n let spot = extraFloat(at + 3u) > 0.5;\n let axis = extraVec4(at + 4u).xyz;\n let color = extraVec4(at + 8u).rgb;\n let density = extraFloat(at + 11u);\n let angle = extraFloat(at + 12u);\n let penumbra = extraFloat(at + 13u);\n let range = extraFloat(at + 14u);\n let outer = extraFloat(at + 15u);\n let spread = extraFloat(at + 16u);\n let anisotropy = extraFloat(at + 17u);\n let casts = extraFloat(at + 18u) > 0.5;\n let toLight = position - p;\n let dist = length(toLight);\n let toward = toLight / max(dist, 1e-20);\n var attenuation = exp(-dist / (select(10.0, range, range > 0.0) * 0.3));\n\n if (range > 0.0) {\n attenuation = attenuation * (1.0 - edge(range * 0.8, range, dist));\n }\n\n if (spot) {\n let along = -dot(toward, axis);\n let inner = cos(angle * (1.0 - penumbra));\n let core = edge(cos(angle), inner, along);\n let scattered = spread * pow(edge(cos(outer), inner, along), 2.0);\n\n attenuation = attenuation * select(core, max(core, scattered), spread > 0.0);\n }\n\n if (attenuation <= 0.0001) {\n continue;\n }\n\n // Shadowing follows Three's volumetric lights, which only have shadow maps for spots.\n if (spot && casts && frame.shadowsEnabled != 0u && traceAny(p, toward, dist * (1.0 - 1e-3)) != NO_HIT) {\n continue;\n }\n\n let cosine = dot(toward, direction);\n let g = anisotropy;\n let phase = select((1.0 - g * g) / pow(1.0 + g * g - 2.0 * g * cosine, 1.5), 1.0, g == 0.0);\n\n // The air between the camera and this point, exactly: a long step evaluated at its start would overstate it.\n result = result + color * (attenuation * density * step * exp(-density * t) * fogged * phase * 1.5);\n }\n\n if (!lit) {\n break;\n }\n\n for (var k = 0u; k < count; k = k + 1u) {\n transmittance[k] = transmittance[k] * exp(-extraFloat(frame.volumetricData + k * 20u + 11u) * step);\n }\n }\n\n return result / (vec3<f32>(1.0) + result);\n}\n\n/**\n * How far a pixel's estimate may still be from its mean: the standard error of its luminance, over the square root of\n * the luminance, which is roughly how visible that error is once the image is encoded for display.\n */\nfn pixelError(pixel: vec2<u32>) -> f32 {\n let index = pixel.y * frame.resolution.x + pixel.x;\n let sum = accumulation[index];\n\n if (sum.w < 2.0) {\n return 1e30;\n }\n\n let squares = accumulation[frame.pixelCount + index];\n let diffuse = accumulation[4u * frame.pixelCount + index].rgb;\n\n // Each of the denoiser's signals has its own variance; the pixel has converged when both have.\n return max(\n channelError(luminanceOf(diffuse) / sum.w, squares.z / sum.w, sum.w),\n channelError(luminanceOf(sum.rgb - diffuse) / sum.w, squares.w / sum.w, sum.w));\n}\n\nfn channelError(mean: f32, square: f32, samples: f32) -> f32 {\n let variance = max(square - mean * mean, 0.0);\n\n return sqrt(variance / samples) / sqrt(max(mean, 0.0) + 1e-3);\n}\n\n/**\n * Whether a pixel has converged, judged over its neighbourhood: a rare bright path lands in one pixel, and a pixel\n * judged alone would stop where its neighbours had not yet seen one and leave that area too dark.\n */\nfn converged(pixel: vec2<u32>) -> bool {\n for (var dy = -1; dy <= 1; dy = dy + 1) {\n for (var dx = -1; dx <= 1; dx = dx + 1) {\n let x = clamp(i32(pixel.x) + dx, 0, i32(frame.resolution.x) - 1);\n let y = clamp(i32(pixel.y) + dy, 0, i32(frame.resolution.y) - 1);\n\n if (pixelError(vec2<u32>(u32(x), u32(y))) > frame.adaptiveThreshold) {\n return false;\n }\n }\n }\n\n return true;\n}\n\n@compute @workgroup_size(8, 8, 1)\nfn main(@builtin(global_invocation_id) id: vec3<u32>) {\n if (id.x >= frame.bandSize.x || id.y >= frame.bandSize.y) {\n return;\n }\n\n let pixel = frame.bandOrigin + id.xy;\n\n if (pixel.x >= frame.resolution.x || pixel.y >= frame.resolution.y) {\n return;\n }\n\n let index = pixel.y * frame.resolution.x + pixel.x;\n\n // Adaptive sampling: a pixel whose neighbourhood has converged takes no more samples, which leaves the pass to\n // the pixels that still need them.\n if (frame.adaptiveMin > 0u && accumulation[index].w >= f32(frame.adaptiveMin) && converged(pixel)) {\n return;\n }\n\n var radiance = vec3<f32>(0.0);\n var alpha = 0.0;\n var depthSum = 0.0;\n var diffuseSquares = 0.0;\n var specularSquares = 0.0;\n var diffuseSum = vec3<f32>(0.0);\n var diffuseAlbedoSum = vec3<f32>(0.0);\n var specularAlbedoSum = vec3<f32>(0.0);\n var normalSum = vec3<f32>(0.0);\n var distanceSum = 0.0;\n var roughnessSum = 0.0;\n var specularDistanceSum = 0.0;\n\n for (var s = 0u; s < frame.sampleCount; s = s + 1u) {\n var rng = makeSampler(pixel, frame.sampleIndex + s);\n let jitter = sample2D(&rng);\n let lens = sample2D(&rng);\n let ray = cameraRay(pixel, jitter, lens);\n let result = traceRadiance(ray[0].xyz, ray[1].xyz, ray[1].w, &rng);\n var sampleAlpha = result.alpha;\n\n var sampled = result.radiance;\n var sampledDiffuse = result.diffuse;\n\n if (frame.volumetricCount > 0u) {\n let glow = volumetricGlow(ray[0].xyz, ray[1].xyz, result.depth, sample2D(&rng).x);\n\n // As the CPU renderer composites it: added over the image, and raising the coverage just enough to hold it.\n sampled = sampled + glow;\n sampledDiffuse = sampledDiffuse + glow;\n sampleAlpha = max(sampleAlpha, max3(glow));\n }\n\n let sampledSpecular = sampled - sampledDiffuse;\n\n radiance = radiance + sampled;\n diffuseSum = diffuseSum + sampledDiffuse;\n diffuseSquares = diffuseSquares + luminanceOf(sampledDiffuse) * luminanceOf(sampledDiffuse);\n specularSquares = specularSquares + luminanceOf(sampledSpecular) * luminanceOf(sampledSpecular);\n diffuseAlbedoSum = diffuseAlbedoSum + result.diffuseAlbedo;\n specularAlbedoSum = specularAlbedoSum + result.specularAlbedo;\n normalSum = normalSum + result.normal;\n distanceSum = distanceSum + result.guideDistance;\n roughnessSum = roughnessSum + result.roughness;\n specularDistanceSum = specularDistanceSum + result.specularDistance;\n\n alpha = alpha + sampleAlpha;\n depthSum = depthSum + windowDepth(ray[0].xyz + ray[1].xyz * min(result.depth, 1e20), result.depth);\n }\n\n let coverage = accumulation[frame.pixelCount + index];\n accumulation[index] = accumulation[index] + vec4<f32>(radiance, f32(frame.sampleCount));\n accumulation[frame.pixelCount + index] = vec4<f32>(\n coverage.x + alpha, coverage.y + depthSum, coverage.z + diffuseSquares, coverage.w + specularSquares);\n // The denoiser's signals and guides, summed like the radiance so they average over the pixel's samples.\n let pc = frame.pixelCount;\n accumulation[2u * pc + index] = accumulation[2u * pc + index] + vec4<f32>(diffuseAlbedoSum, roughnessSum);\n accumulation[3u * pc + index] = accumulation[3u * pc + index] + vec4<f32>(normalSum, distanceSum);\n accumulation[4u * pc + index] = accumulation[4u * pc + index] + vec4<f32>(diffuseSum, specularDistanceSum);\n accumulation[5u * pc + index] = accumulation[5u * pc + index] + vec4<f32>(specularAlbedoSum, 0.0);\n // This row still has work: every pixel that traced writes the same value, so the race is harmless.\n accumulation[6u * pc + pixel.y] = vec4<f32>(1.0);\n}\n";
|
|
13
|
+
export declare const PATH_TRACE_WGSL = "\n/** Light from an ambient or hemisphere light, which this renderer turns into an equally bright surrounding. */\nfn ambientRadiance(direction: vec3<f32>) -> vec3<f32> {\n let latitude = clamp(dot(direction, frame.ambientAxis.xyz) * 0.5 + 0.5, 0.0, 1.0);\n\n return mix(frame.ambientGround.rgb, frame.ambientSky.rgb, latitude) + probeRadiance(direction);\n}\n\n/**\n * A LightProbe's light. Three's coefficients are radiance projected on the SH3 basis, which its shader convolves with\n * the cosine to get irradiance; evaluated directly they are the surrounding that delivers exactly that irradiance.\n */\nfn probeRadiance(d: vec3<f32>) -> vec3<f32> {\n let radiance = frame.probe0.rgb * 0.282095\n + frame.probe1.rgb * (0.488603 * d.y)\n + frame.probe2.rgb * (0.488603 * d.z)\n + frame.probe3.rgb * (0.488603 * d.x)\n + frame.probe4.rgb * (1.092548 * d.x * d.y)\n + frame.probe5.rgb * (1.092548 * d.y * d.z)\n + frame.probe6.rgb * (0.315392 * (3.0 * d.z * d.z - 1.0))\n + frame.probe7.rgb * (1.092548 * d.x * d.z)\n + frame.probe8.rgb * (0.546274 * (d.x * d.x - d.y * d.y));\n\n return max(radiance, vec3<f32>(0.0));\n}\n\n/** What the camera sees where nothing is in the way, as the background setting says. */\nfn backgroundRadiance(direction: vec3<f32>) -> vec3<f32> {\n if (frame.background.w == 1.0) {\n return frame.background.rgb;\n }\n\n // A procedural sky paints the background without the strength it lights with, and its foreground over it.\n if (frame.skyProgram != NO_PROGRAM || frame.skyIntensity > 0.0) {\n if (frame.skyBackground == 0u) {\n return vec3<f32>(0.0);\n }\n\n if (frame.skyProgram != NO_PROGRAM) {\n var input: ShaderInput;\n input.data = frame.skyData;\n input.direction = direction;\n input.diffuseColor = vec4<f32>(1.0);\n\n return runProgram(frame.skyProgram, input).color.rgb;\n }\n\n return environmentRadiance(direction) / frame.skyIntensity;\n }\n\n return environmentRadiance(direction);\n}\n\n/**\n * How much of the sky a bounce ray that escaped keeps. Direct sampling aims at the bright parts of an image too, so the\n * two share it; when direct sampling took all of it, as it does from a toon surface, the bounce keeps none.\n */\nfn escapeWeight(direction: vec3<f32>, bsdfPdf: f32, lightsOwnDirect: bool) -> f32 {\n if (frame.environmentPick <= 0.0) {\n return 1.0;\n }\n\n if (lightsOwnDirect) {\n return 0.0;\n }\n\n if (bsdfPdf <= 0.0) {\n return 1.0;\n }\n\n return misWeight(bsdfPdf, frame.environmentPick * environmentPdf(direction));\n}\n\n/** Scales a contribution down to the luminance ceiling, which trades a little bias for the fireflies it removes. */\nfn clampIndirect(contribution: vec3<f32>) -> vec3<f32> {\n let luminance = luminanceOf(contribution);\n\n if (frame.clampIndirect <= 0.0 || luminance <= frame.clampIndirect) {\n return contribution;\n }\n\n return contribution * (frame.clampIndirect / luminance);\n}\n\n/**\n * How much of the emission a bounce ray found the renderer keeps. Direct sampling had its own chance at this triangle,\n * and the heuristic splits the two so neither counts it twice.\n */\nfn emissionWeight(hit: Hit, direction: vec3<f32>, bsdfPdf: f32, lightsOwnDirect: bool, scatteredAt: vec3<f32>,\n normal: vec3<f32>) -> f32 {\n if (frame.areaLightCount == 0u) {\n return 1.0;\n }\n\n // From the vertex the bounce left, which is where direct sampling would have picked it from.\n let areaPdf = lightPdfOfTriangle(hit.triangle, scatteredAt, normal);\n\n if (areaPdf <= 0.0) {\n return 1.0;\n }\n\n if (lightsOwnDirect) {\n return 0.0;\n }\n\n if (bsdfPdf <= 0.0) {\n return 1.0;\n }\n\n let cosLight = max(abs(dot(triangleNormal(hit.triangle), direction)), 1e-6);\n\n return misWeight(bsdfPdf, areaPdf * hit.distance * hit.distance / cosLight);\n}\n\n/**\n * The normal the light tree weighs lights by, or none where light from behind the surface counts too: a point in a\n * volume, a toon ramp read all round, a clearcoat that may face what its base turns from, and transmission.\n */\nfn treeNormal(surface: Surface) -> vec3<f32> {\n if (surface.kind == KIND_VOLUME || surface.kind == KIND_TOON || surface.clearcoat > 0.0 || surface.transmission > 0.0) {\n return vec3<f32>(0.0);\n }\n\n return surface.normal;\n}\n\n/** One shadow ray from the surface towards a light, weighted against the chance the bounce would have found it too. */\nfn directLight(\n surface: Surface,\n position: vec3<f32>,\n view: vec3<f32>,\n pick: f32,\n u: vec2<f32>,\n rng: ptr<function, PathSampler>,\n diffusePart: ptr<function, vec3<f32>>,\n medium: f32) -> vec3<f32> {\n *diffusePart = vec3<f32>(0.0);\n\n let chosen = sampleLight(position, treeNormal(surface), pick, u);\n\n if (!chosen.valid) {\n return vec3<f32>(0.0);\n }\n\n // A material with its own environment map sees that map in place of the scene's surroundings.\n if (chosen.kind == LIGHT_ENVIRONMENT && surface.envMap != NO_TEXTURE) {\n return vec3<f32>(0.0);\n }\n\n let reflected = evaluateBsdf(surface, view, chosen.direction);\n\n if (all(reflected.value <= vec3<f32>(0.0))) {\n return vec3<f32>(0.0);\n }\n\n let toon = surface.kind == KIND_TOON;\n // Three's shadow map leaves a toon mesh's own far side unshadowed; tracing through the mesh would not.\n let skip = select(NO_MATERIAL, surface.material, toon && dot(surface.normal, chosen.direction) < 0.1);\n let through = lightTransmittance(position, chosen, rng, skip, medium);\n\n if (all(through <= vec3<f32>(0.0))) {\n return vec3<f32>(0.0);\n }\n\n // A light that no bounce ray could have found keeps its whole contribution; an emissive triangle shares it. A toon\n // surface takes all of its direct light this way, because its bounce is not the lobe that lit it.\n let weight = select(1.0, misWeight(chosen.misPdf, reflected.pdf), chosen.misPdf > 0.0 && reflected.pdf > 0.0 && !toon);\n\n let light = chosen.value * through * weight;\n\n // The share of it the diffuse lobe reflects, which the denoiser filters apart from the specular one.\n *diffusePart = min(diffuseValue(surface, view, chosen.direction), reflected.value) * light;\n\n return reflected.value * light;\n}\n\n/** Three's fog factor at a view depth: linear between near and far, or exponential squared. */\nfn fogFactor(depth: f32, kind: f32) -> f32 {\n if (kind == 2.0) {\n let density = frame.fogParams.z;\n\n return clamp(1.0 - exp(-density * density * depth * depth), 0.0, 1.0);\n }\n\n return smoothstep(frame.fogParams.x, frame.fogParams.y, depth);\n}\n\n/** The colour the diffuse signal is divided by at this surface; white where the surface shows what it emits. */\nfn diffuseGuide(surface: Surface) -> vec3<f32> {\n if ((surface.flags & MATERIAL_LIT) == 0u) {\n return vec3<f32>(1.0);\n }\n\n return surface.albedo * (1.0 - surface.metalness) * (1.0 - clamp(surface.transmission, 0.0, 1.0));\n}\n\n/**\n * How often a vertex on a material that scatters inside takes the walk into it instead of its surface lobes: by the\n * share of the light each accounts for, as lobeWeights chooses between lobes. Never all of the time, so the specular\n * layer on top stays reachable.\n */\nfn subsurfaceChance(surface: Surface, view: vec3<f32>) -> f32 {\n if (surface.subsurface <= 0.0 || (surface.flags & MATERIAL_PBR) == 0u) {\n return 0.0;\n }\n\n let diffuse = luminanceOf(surface.albedo * (1.0 - surface.metalness)) * coatTransmittance(surface, view);\n let inside = diffuse * surface.subsurface;\n let outside = diffuse * (1.0 - surface.subsurface) + luminanceOf(specularAlbedo(surface, view)) + 0.02;\n\n return clamp(inside / max(inside + outside, 1e-6), 0.0, 0.95);\n}\n\n/**\n * The single scattering albedo that gives this multiple scattering albedo in a semi-infinite medium: van de Hulst's\n * relation, inverted as Cycles inverts it for its random walk. What the material's colour says it reflects in all\n * is what light keeps at each scattering inside it.\n */\nfn subsurfaceAlbedo(albedo: vec3<f32>) -> vec3<f32> {\n let a = clamp(albedo, vec3<f32>(0.0), vec3<f32>(0.999));\n let s = 4.09712 + 4.20863 * a - sqrt(9.59217 + 41.6808 * a + 17.7126 * a * a);\n\n return vec3<f32>(1.0) - s * s;\n}\n\n/**\n * How far the walk goes before it next scatters, drawn for one colour picked in proportion to what the path still\n * carries of it. choice keeps those odds, which the next step weighs its distance by over all three colours, so each\n * colour keeps its own mean free path and the estimate stays exact (spectral MIS, as Cycles' random walk does it).\n */\nfn walkDistance(throughput: vec3<f32>, sigma: vec3<f32>, u: vec2<f32>, choice: ptr<function, vec3<f32>>) -> f32 {\n let weights = max(throughput, vec3<f32>(0.0));\n let total = weights.x + weights.y + weights.z;\n let odds = select(vec3<f32>(1.0 / 3.0), weights / total, total > 0.0);\n let chosen = select(select(sigma.z, sigma.y, u.x < odds.x + odds.y), sigma.x, u.x < odds.x);\n\n *choice = odds;\n\n return -log(max(1.0 - u.y, 1e-12)) / chosen;\n}\n\n/**\n * Where a walk leaves the material: a white Lambert surface facing out, as Cycles leaves its random walk. The colour\n * was taken inside, scattering by scattering, so nothing tints the light again on the way out.\n */\nfn subsurfaceExit(m: u32, triangle: u32, bary: vec2<f32>, direction: vec3<f32>) -> Surface {\n var surface: Surface;\n // Turned to face against the reversed ray: outwards, the side the walk is leaving through.\n let out = interpolatedNormal(m, triangle, bary, -direction);\n\n surface.normal = out;\n surface.facing = out;\n surface.albedo = vec3<f32>(1.0);\n surface.flags = MATERIAL_LIT;\n surface.kind = KIND_LAMBERT;\n surface.opacity = 1.0;\n surface.alpha = 1.0;\n surface.blending = BLEND_NORMAL;\n surface.material = m;\n surface.roughness = 1.0;\n surface.ior = 1.5;\n surface.specularF90 = 1.0;\n surface.envMap = NO_TEXTURE;\n surface.envMapIntensity = 1.0;\n surface.gradientMap = NO_TEXTURE;\n\n return surface;\n}\n\n/** A point inside a volume where the light scatters: the medium's phase function in place of a surface's lobes. */\nfn volumePoint(direction: vec3<f32>, albedo: vec3<f32>, anisotropy: f32) -> Surface {\n var surface: Surface;\n\n surface.normal = -direction;\n surface.facing = -direction;\n surface.albedo = albedo;\n surface.flags = MATERIAL_LIT;\n surface.kind = KIND_VOLUME;\n surface.anisotropy = anisotropy;\n surface.opacity = 1.0;\n surface.alpha = 1.0;\n surface.blending = BLEND_NORMAL;\n surface.material = NO_MATERIAL;\n surface.roughness = 1.0;\n surface.ior = 1.0;\n surface.specularF90 = 1.0;\n surface.envMap = NO_TEXTURE;\n surface.envMapIntensity = 1.0;\n surface.gradientMap = NO_TEXTURE;\n\n return surface;\n}\n\n/**\n * The shading normal with the edges near it rounded, as Cycles' bevel node rounds them, by one probe a sample. A\n * point is drawn on a disk of the bevel radius around the shaded point, across an axis picked along the normal half\n * the time and along each tangent a quarter; a short ray along that axis through it finds the surface of the same\n * material there, and that surface's normal turns this one by as much as it differs from the normal here. Over the\n * samples a pixel takes, the normal blends from one face to the next within the radius of every edge, so a box reads\n * as a machined one. A probe that finds nothing, or a normal turned away from the view, leaves the normal as it was.\n */\nfn bevelNormal(m: u32, point: vec3<f32>, surface: Surface, view: vec3<f32>, radius: f32, u: vec2<f32>,\n v: vec2<f32>) -> vec3<f32> {\n let basis = orthonormalBasis(surface.facing);\n var axis = basis[2];\n var first = basis[0];\n var second = basis[1];\n\n if (v.x >= 0.5) {\n axis = select(basis[1], basis[0], v.x < 0.75);\n first = select(basis[2], basis[1], v.x < 0.75);\n second = select(basis[0], basis[2], v.x < 0.75);\n }\n\n let reach = radius * sqrt(u.x);\n let angle = 2.0 * PI * u.y;\n let across = point + first * (reach * cos(angle)) + second * (reach * sin(angle));\n // Along the axis one way or the other at random, from the far edge of the radius across it.\n let way = select(-1.0, 1.0, v.y < 0.5);\n let hit = traceScene(across - axis * (radius * way), axis * way, 2.0 * radius);\n\n if (hit.triangle == NO_HIT || materialIndexOf(hit.triangle) != m) {\n return surface.normal;\n }\n\n // The authored normal there, turned the way this side's own is: the facing normal is the authored one, or its reverse.\n let there = authoredNormal(hit.triangle, vec2<f32>(hit.u, hit.v)) * select(-1.0, 1.0, surface.front);\n let turned = normalize(surface.normal + there - surface.facing);\n\n return select(surface.normal, turned, dot(turned, view) > 0.0 && all(turned == turned));\n}\n\nstruct PathResult {\n radiance: vec3<f32>,\n alpha: f32,\n // How far along the camera ray the first surface it stopped at is, or 1e30 when it stopped at none.\n depth: f32,\n // The denoiser's two signals: what of the radiance came through the first surface's diffuse lobe (and what the camera\n // sees directly), the rest being specular, and what guides each at that surface.\n diffuse: vec3<f32>,\n diffuseAlbedo: vec3<f32>,\n specularAlbedo: vec3<f32>,\n normal: vec3<f32>,\n // Along the camera ray to the first surface, its roughness, and how far the specular continuation went from it.\n guideDistance: f32,\n roughness: f32,\n specularDistance: f32,\n // How much of the first surface scatters light inside, which the denoiser relaxes its tests over.\n subsurface: f32,\n};\n\n/** How many surfaces a path may pass through without scattering (cutouts, culled faces, glass) before it gives up. */\nconst MAX_STEPS: u32 = 64u;\n\n/** Scatterings one walk inside a material may take; the roulette ends most walks well before. */\nconst MAX_WALK: u32 = 128u;\n\nfn traceRadiance(\n rayOrigin: vec3<f32>, rayDirection: vec3<f32>, rayLength: f32, rng: ptr<function, PathSampler>) -> PathResult {\n var radiance = vec3<f32>(0.0);\n var throughput = vec3<f32>(1.0);\n var origin = rayOrigin;\n var direction = rayDirection;\n var limit = rayLength;\n // Solid angle density of the current direction; zero for the camera ray, which no light sampling competes with.\n var bsdfPdf = 0.0;\n // What the volume the ray is travelling through absorbs per unit of distance; zero outside any.\n var absorption = vec3<f32>(0.0);\n // Still on the camera's own line of sight, which transmission keeps a path on.\n var primary = true;\n // Still the camera ray itself, in a straight line: only this one is culled and clipped by the far plane.\n var straight = true;\n var alpha = 0.0;\n var bounce = 0u;\n // The vertex the path last scattered at took all of its direct light by sampling lights: a toon surface.\n var lightsOwnDirect = false;\n // Where the path last scattered and the normal the light tree weighed lights by there, for the heuristic's other half.\n var lastPosition = rayOrigin;\n var lastNormal = vec3<f32>(0.0);\n // That vertex's own environment map, which a ray escaping from it sees instead of the scene's.\n var escapeMap = NO_TEXTURE;\n var escapeIntensity = 1.0;\n // Which colour a dispersive path carries, once a dispersive volume has split it; all three before that.\n var channel = vec3<f32>(1.0);\n // Three's fog, laid over everything the camera sees through the first surface.\n var fogged = false;\n var fogAmount = 0.0;\n var fogStart = vec3<f32>(0.0);\n var fogThroughput = vec3<f32>(0.0);\n // The air between the camera and the first surface it sees: aerial perspective.\n var hazed = false;\n var hazeDistance = 0.0;\n var hazeStart = vec3<f32>(0.0);\n var hazeThroughput = vec3<f32>(0.0);\n var hazeDirection = vec3<f32>(0.0);\n // A built-in material's hooks after <opaque_fragment> edit the colour the camera sees of it, which is everything the\n // path gathers from that surface on.\n var afterMaterial = NO_MATERIAL;\n var afterTriangle = 0u;\n var afterBary = vec2<f32>(0.0);\n var afterDirection = vec3<f32>(0.0);\n var afterAlbedo = vec4<f32>(0.0);\n var afterStart = vec3<f32>(0.0);\n var afterThroughput = vec3<f32>(0.0);\n var depth = 1e30;\n // The denoiser's guides, taken at the first surface the camera ray stops at.\n var guided = false;\n var diffuseAlbedo = vec3<f32>(1.0);\n var specularAlbedoGuide = vec3<f32>(1.0);\n var guideNormal = vec3<f32>(0.0);\n var guideDistance = 1e6;\n var guideRoughness = 1.0;\n var guideSubsurface = 0.0;\n // Where the path first scattered, which decides which of the two signals the rest of it feeds.\n var split = false;\n var splitBase = vec3<f32>(0.0);\n var splitDirect = vec3<f32>(0.0);\n var splitDirectDiffuse = vec3<f32>(0.0);\n var splitDiffuse = true;\n var waitingForSpecular = false;\n var specularDistance = 1e6;\n // Inside a material that scatters light, between two scatterings: its extinction and single scattering albedo per\n // colour, its anisotropy, the odds each colour had when the current step's distance was drawn, and the steps so far.\n var inMedium = false;\n var sigma = vec3<f32>(0.0);\n var walkAlbedo = vec3<f32>(0.0);\n var walkG = 0.0;\n var walkOdds = vec3<f32>(0.0);\n var walkSteps = 0u;\n // Inside a volume: its density per unit of distance, what it keeps at each scattering and its anisotropy. A camera\n // inside one starts there.\n var inVolume = false;\n var volumeDensity = 0.0;\n var volumeAlbedo = vec3<f32>(0.0);\n var volumeG = 0.0;\n\n if (VOLUMES && frame.cameraVolume != NO_MATERIAL && frame.volumesEnabled != 0u) {\n inVolume = true;\n volumeDensity = materials[frame.cameraVolume].volume.w;\n volumeAlbedo = materials[frame.cameraVolume].volume.rgb;\n volumeG = materials[frame.cameraVolume].volumeAnisotropy;\n }\n\n for (var step = 0u; step < MAX_STEPS + MAX_WALK; step = step + 1u) {\n let hit = traceScene(origin, direction, limit);\n\n // Every vertex draws the same dimensions in the same order, whatever the path then does with them.\n let coverage = sample2D(rng);\n let pick = sample2D(rng);\n let lightSample = sample2D(rng);\n let lobe = sample2D(rng);\n let bounceSample = sample2D(rng);\n var mediumSample = vec2<f32>(0.0);\n var bevelSample = vec4<f32>(0.0);\n\n if (VOLUMES) {\n mediumSample = sample2D(rng);\n }\n\n if (BEVEL) {\n bevelSample = vec4<f32>(sample2D(rng), sample2D(rng));\n }\n\n // The walk left the material here, and the surface below is its way out rather than what the material shows.\n var exiting = false;\n\n if (SUBSURFACE_WALK && inMedium) {\n if (hit.triangle == NO_HIT) {\n // Nothing within the drawn distance: the light scatters there, keeping each colour's share of the medium.\n let travelled = exp(-sigma * limit);\n let density = dot(walkOdds, sigma * travelled);\n\n throughput = throughput * sigma * walkAlbedo * travelled / max(density, 1e-20);\n walkSteps = walkSteps + 1u;\n\n let survival = max3(throughput);\n\n if (walkSteps >= MAX_WALK || survival <= 0.0) {\n break;\n }\n\n if (survival < 0.2) {\n if (coverage.x > survival) {\n break;\n }\n\n throughput = throughput / survival;\n }\n\n origin = origin + direction * limit;\n direction = sampleHenyeyGreenstein(direction, walkG, lobe);\n limit = walkDistance(throughput, sigma, pick, &walkOdds);\n continue;\n }\n\n // The walk reached the surface before scattering again: the chance of travelling that far, per colour.\n let travelled = exp(-sigma * hit.distance);\n\n throughput = throughput * travelled / max(dot(walkOdds, travelled), 1e-20);\n inMedium = false;\n exiting = true;\n }\n\n // Inside a volume, the medium may stop the ray before whatever it hit. The distance is drawn now that the segment's\n // length is known, which a homogeneous medium allows; one grey density makes the weight of either outcome one.\n var scatterAt = -1.0;\n\n if (VOLUMES && inVolume && !exiting) {\n let free = -log(max(1.0 - mediumSample.x, 1e-12)) / max(volumeDensity, 1e-12);\n\n if (free < select(hit.distance, limit, hit.triangle == NO_HIT)) {\n scatterAt = free;\n }\n }\n\n let scattering = scatterAt >= 0.0;\n\n // The specular continuation's first hit: how far the reflection the denoiser filters actually is.\n if (waitingForSpecular) {\n specularDistance = select(min(hit.distance, 1e6), 1e6, hit.triangle == NO_HIT);\n waitingForSpecular = false;\n }\n\n if (hit.triangle == NO_HIT && !scattering) {\n if (primary) {\n // A transparent background leaves the pixel empty, which its alpha says.\n if (frame.background.w != 2.0) {\n alpha = 1.0;\n radiance = radiance + throughput * backgroundRadiance(direction);\n }\n } else {\n var sky = ambientRadiance(direction);\n\n if (escapeMap != NO_TEXTURE) {\n sky = sky + sampleEquirect(escapeMap, direction).rgb * escapeIntensity;\n } else {\n sky = sky + environmentRadiance(direction) * escapeWeight(direction, bsdfPdf, lightsOwnDirect);\n }\n\n let contribution = throughput * sky;\n\n radiance = radiance + select(contribution, clampIndirect(contribution), bounce > 1u);\n }\n\n break;\n }\n\n let travel = select(hit.distance, scatterAt, scattering);\n\n throughput = throughput * exp(-absorption * travel);\n\n let bary = vec2<f32>(hit.u, hit.v);\n let point = origin + direction * travel;\n var m = 0u;\n\n if (!scattering) {\n m = materialIndexOf(hit.triangle);\n }\n\n var surface: Surface;\n\n if (SUBSURFACE_WALK && exiting) {\n surface = subsurfaceExit(m, hit.triangle, bary, direction);\n // Seen from outside, along its normal: the side the light leaves through.\n direction = -surface.normal;\n } else if (VOLUMES && scattering) {\n surface = volumePoint(direction, volumeAlbedo, volumeG);\n } else {\n\n // A volume's boundary is not a surface: the ray goes in or out, and the medium is what it meets.\n if (VOLUMES && (materials[m].flags & MATERIAL_VOLUME) != 0u) {\n if (dot(authoredNormal(hit.triangle, bary), direction) < 0.0) {\n if (frame.volumesEnabled != 0u) {\n inVolume = true;\n volumeDensity = materials[m].volume.w;\n volumeAlbedo = materials[m].volume.rgb;\n volumeG = materials[m].volumeAnisotropy;\n }\n } else {\n inVolume = false;\n }\n\n origin = point + direction * RAY_EPSILON;\n limit = select(1e30, limit - hit.distance, straight);\n continue;\n }\n\n // Three culls the side a material does not draw. Only the camera's rays are culled: a mesh still casts shadows and\n // holds light in from both sides.\n // A planar capture drops what lies behind its plane, for the camera's own ray.\n let clipped = any(frame.clipPlane != vec4<f32>(0.0)) && dot(frame.clipPlane.xyz, point) + frame.clipPlane.w < 0.0;\n\n if (straight && (clipped || isCulled(m, hit.triangle, direction))) {\n origin = point + direction * RAY_EPSILON;\n limit = limit - hit.distance;\n continue;\n }\n\n if (isClipped(m, point)\n || ((materials[m].flags & MATERIAL_WIREFRAME) != 0u && !onWireframe(hit.triangle, point))) {\n origin = point + direction * RAY_EPSILON;\n limit = select(1e30, limit - hit.distance, straight);\n continue;\n }\n\n let base = sampleMap(materials[m].map, hit.triangle, bary);\n\n // A cutout lets the ray through before anything else about the surface is read: the normal map, the other maps and\n // the lobes would only be thrown away. The draw and the comparison are the ones made below, so nothing changes.\n if (coverageFirst(m)) {\n let opacity = coverageOf(m, materialAlphaFrom(m, hit.triangle, bary, base));\n\n if (opacity < 1.0 && coverage.x >= opacity) {\n origin = point + direction * RAY_EPSILON;\n limit = select(1e30, limit - hit.distance, straight);\n continue;\n }\n }\n\n surface = resolveSurfaceFrom(hit.triangle, bary, direction, base);\n\n if (BEVEL && frame.bevelEnabled != 0u && materials[m].bevel > 0.0) {\n surface.normal = bevelNormal(m, point, surface, -direction, materials[m].bevel, bevelSample.xy, bevelSample.zw);\n }\n }\n\n // Blending other than normal: the surface adds its light to, or filters, whatever is behind it, and the path goes on.\n if (surface.blending == BLEND_ADDITIVE || surface.blending == BLEND_MULTIPLY || surface.blending == BLEND_SUBTRACTIVE) {\n // Three blends these with the fragment's alpha whether or not the material is transparent.\n let strength = surface.opacity * clamp(surface.alpha, 0.0, 1.0);\n let color = select(surface.albedo, surface.emissive, (surface.flags & MATERIAL_LIT) == 0u);\n\n if (surface.blending == BLEND_ADDITIVE) {\n var added = surface.emissive;\n\n if ((surface.flags & MATERIAL_LIT) != 0u) {\n var unused: vec3<f32>;\n added = added + directLight(surface, point + surface.normal * RAY_EPSILON, -direction, pick.x, lightSample, rng,\n &unused, select(0.0, volumeDensity, inVolume));\n }\n\n radiance = radiance + throughput * added * strength;\n } else if (surface.blending == BLEND_MULTIPLY) {\n throughput = throughput * mix(vec3<f32>(1.0), color, strength);\n } else {\n throughput = throughput * (vec3<f32>(1.0) - color * strength);\n }\n\n origin = point + direction * RAY_EPSILON;\n limit = select(1e30, limit - hit.distance, straight);\n continue;\n }\n\n // A surface that only partly covers its triangle lets the ray straight through the rest of the time. The direction\n // does not change, so the density that found it still stands and the next hit is weighted against the same one.\n if (surface.opacity < 1.0 && coverage.x >= surface.opacity) {\n origin = point + direction * RAY_EPSILON;\n limit = select(1e30, limit - hit.distance, straight);\n continue;\n }\n\n // Three's ShadowMaterial shows its colour only where a light is blocked, and nothing elsewhere.\n if (surface.kind == KIND_SHADOW) {\n let shadow = shadowMaskAt(point + surface.facing * RAY_EPSILON, rng);\n\n if (coverage.y >= shadow * clamp(materials[m].color.w, 0.0, 1.0)) {\n origin = point + direction * RAY_EPSILON;\n limit = select(1e30, limit - hit.distance, straight);\n continue;\n }\n\n if (primary) {\n alpha = 1.0;\n }\n\n radiance = radiance + throughput * surface.albedo;\n break;\n }\n\n if (straight && depth >= 1e30) {\n depth = length(point - rayOrigin);\n }\n\n if (straight && !guided) {\n guided = true;\n diffuseAlbedo = diffuseGuide(surface);\n specularAlbedoGuide = select(specularAlbedo(surface, -direction), vec3<f32>(1.0), (surface.flags & MATERIAL_LIT) == 0u);\n guideNormal = surface.normal;\n guideDistance = length(point - rayOrigin);\n guideRoughness = surface.roughness;\n guideSubsurface = select(0.0, surface.subsurface, SUBSURFACE_WALK);\n\n if (surface.kind == KIND_PHONG) {\n // Phong's exponent as the roughness of the GGX lobe that is about as wide.\n guideRoughness = pow(2.0 / (surface.shininess + 2.0), 0.25);\n }\n }\n\n if (primary) {\n alpha = 1.0;\n\n if (!scattering && !fogged && afterMaterial == NO_MATERIAL && materials[m].afterProgram != NO_PROGRAM) {\n afterMaterial = m;\n afterTriangle = hit.triangle;\n afterBary = bary;\n afterDirection = direction;\n afterAlbedo = vec4<f32>(surface.albedo, surface.alpha);\n afterStart = radiance;\n afterThroughput = throughput;\n }\n\n if (!fogged) {\n let everySurface = frame.fogParams.w > 0.0;\n let kind = frame.fogColor.w;\n\n if (everySurface || (kind > 0.0 && (surface.flags & MATERIAL_FOG) != 0u)) {\n let depth = -(frame.worldToCamera * vec4<f32>(point, 1.0)).z;\n\n fogged = true;\n fogAmount = fogFactor(depth, select(kind, 1.0, everySurface));\n fogStart = radiance;\n fogThroughput = throughput;\n }\n }\n\n if (!hazed && frame.atmosphereColor.w > 0.0) {\n hazed = true;\n // From the eye, where the camera ray only starts on the near plane; an orthographic view has no eye.\n hazeDistance = length(point - select(frame.cameraToWorld[3].xyz, rayOrigin, frame.cameraKind == 1u));\n hazeStart = radiance;\n hazeThroughput = throughput;\n hazeDirection = direction;\n }\n\n radiance = radiance + throughput * surface.lightMap;\n }\n\n if (any(surface.emissive > vec3<f32>(0.0))) {\n let contribution = throughput * surface.emissive * emissionWeight(hit, direction, bsdfPdf, lightsOwnDirect, lastPosition, lastNormal);\n\n // Seen by the camera or one bounce away this is direct light and stays exact; deeper it may be clamped.\n radiance = radiance + select(contribution, clampIndirect(contribution), bounce > 1u);\n }\n\n // Three does not light a basic, points, line or sprite material, so nothing carries on from one.\n if ((surface.flags & MATERIAL_LIT) == 0u || bounce >= frame.bounces) {\n break;\n }\n\n // Lambert and Phong blend their own environment map over the lit colour, which here is a share of the path.\n if (surface.legacyAmount > 0.0) {\n let amount = surface.legacyAmount;\n\n if (surface.combine == 1u) {\n radiance = radiance + throughput * surface.legacyEnv * amount;\n throughput = throughput * (1.0 - amount);\n } else if (surface.combine == 2u) {\n radiance = radiance + throughput * surface.legacyEnv * amount;\n } else {\n throughput = throughput * mix(vec3<f32>(1.0), surface.legacyEnv, amount);\n }\n }\n\n let view = -direction;\n var next = direction;\n var nextOrigin = point + direction * RAY_EPSILON;\n\n // Transmission replaces part of the diffuse layer, so that share of the time the surface is a dielectric instead.\n // Choosing it in proportion to its weight leaves both halves unweighted, and only the opaque half aims at a light.\n if (surface.transmission > 0.0 && lobe.y < surface.transmission) {\n var ior = surface.ior;\n\n // Three's dispersion: each colour refracts with its own index, spread around the material's. The path picks one\n // colour the first time it enters such a volume and carries only that one from then on.\n if (surface.dispersion > 0.0 && surface.thickness > 0.0) {\n if (all(channel == vec3<f32>(1.0))) {\n let which = min(u32(coverage.y * 3.0), 2u);\n\n channel = vec3<f32>(select(0.0, 1.0, which == 0u), select(0.0, 1.0, which == 1u), select(0.0, 1.0, which == 2u));\n throughput = throughput * channel * 3.0;\n }\n\n let spread = (ior - 1.0) * 0.025 * surface.dispersion;\n\n ior = dot(channel, vec3<f32>(ior - spread, ior, ior + spread));\n }\n\n let crossing = sampleDielectric(surface, view, ior, lobe.y / surface.transmission, bounceSample);\n\n if (!crossing.valid) {\n break;\n }\n\n // Bending or reflecting off glass is the specular signal.\n if (!split && !crossing.straight) {\n split = true;\n splitBase = radiance;\n splitDiffuse = false;\n waitingForSpecular = true;\n }\n\n throughput = throughput * crossing.weight;\n\n // Straight through a thin wall the direction stands, and with it the density that will weigh the next hit.\n if (!crossing.straight) {\n straight = false;\n next = crossing.direction;\n nextOrigin = point + surface.normal * select(RAY_EPSILON, -RAY_EPSILON, crossing.crossed);\n // A direction no light sampling could have produced: whatever the path finds next keeps its whole value.\n bsdfPdf = 0.0;\n lightsOwnDirect = false;\n escapeMap = surface.envMap;\n escapeIntensity = surface.envMapIntensity;\n\n if (crossing.crossed) {\n absorption = select(vec3<f32>(0.0), surface.absorption, surface.front);\n } else {\n primary = false;\n }\n }\n\n if (!primary) {\n bounce = bounce + 1u;\n }\n } else {\n // Light that enters the material: a random walk inside it from here, in place of the share of the diffuse\n // layer that scatters inside. Chosen by chance, so neither branch is weighted against the other.\n var chance = 0.0;\n\n if (SUBSURFACE_WALK) {\n chance = subsurfaceChance(surface, view);\n }\n\n if (SUBSURFACE_WALK && lobe.x < chance) {\n let medium = materials[surface.material].subsurface;\n\n throughput = throughput\n * ((1.0 - surface.metalness) * surface.subsurface * coatTransmittance(surface, view) / chance);\n sigma = vec3<f32>(1.0) / max(medium.rgb, vec3<f32>(1e-6));\n walkAlbedo = subsurfaceAlbedo(surface.albedo);\n walkG = materials[surface.material].subsurfaceAnisotropy;\n walkSteps = 0u;\n\n // Light that scattered inside is diffuse light, which is the signal it feeds.\n if (!split) {\n split = true;\n splitBase = radiance;\n splitDiffuse = true;\n }\n\n inMedium = true;\n primary = false;\n straight = false;\n bsdfPdf = 0.0;\n lightsOwnDirect = false;\n escapeMap = NO_TEXTURE;\n bounce = bounce + 1u;\n direction = cosineDirection(-surface.facing, bounceSample);\n origin = point - surface.facing * RAY_EPSILON;\n limit = walkDistance(throughput, sigma, pick, &walkOdds);\n continue;\n }\n\n throughput = throughput / (1.0 - chance);\n\n let position = point + surface.normal * RAY_EPSILON;\n var directDiffuse: vec3<f32>;\n let direct = throughput * directLight(surface, position, view, pick.x, lightSample, rng, &directDiffuse,\n select(0.0, volumeDensity, inVolume));\n let added = select(direct, clampIndirect(direct), bounce > 0u);\n let before = radiance;\n\n radiance = radiance + added;\n\n let scattered = sampleBsdf(surface, view, (lobe.x - chance) / (1.0 - chance), bounceSample);\n\n // The first scatter splits the path: its direct light by lobe, and everything after it by the lobe it chose.\n if (!split) {\n split = true;\n splitBase = before;\n splitDirect = added;\n splitDirectDiffuse = throughput * directDiffuse * select(1.0, luminanceOf(added) / max(luminanceOf(direct), 1e-20),\n bounce > 0u);\n splitDiffuse = !scattered.valid || scattered.diffuse;\n waitingForSpecular = scattered.valid && !scattered.diffuse;\n }\n\n if (!scattered.valid) {\n break;\n }\n\n throughput = throughput * scattered.weight;\n bsdfPdf = scattered.pdf;\n lastPosition = position;\n lastNormal = treeNormal(surface);\n lightsOwnDirect = surface.kind == KIND_TOON;\n escapeMap = surface.envMap;\n escapeIntensity = surface.envMapIntensity;\n next = scattered.direction;\n nextOrigin = position;\n primary = false;\n straight = false;\n bounce = bounce + 1u;\n }\n\n // A path that carries almost nothing is ended by chance rather than by a cut, which keeps the estimate unbiased.\n let survival = max(throughput.r, max(throughput.g, throughput.b));\n\n if (survival <= 0.0) {\n break;\n }\n\n if (survival < frame.rouletteThreshold && bounce >= frame.rouletteStart) {\n if (pick.y > survival) {\n break;\n }\n\n throughput = throughput / survival;\n }\n\n origin = nextOrigin;\n limit = select(1e30, limit - hit.distance, straight);\n direction = next;\n }\n\n // The diffuse signal: everything before the first scatter, its diffuse direct light, and the rest if the diffuse lobe\n // carried the path on. A path that never scattered is all diffuse, which is what the camera sees directly.\n var diffuse = radiance;\n\n if (split) {\n let after = radiance - splitBase - splitDirect;\n diffuse = splitBase + splitDirectDiffuse + select(vec3<f32>(0.0), after, splitDiffuse);\n }\n\n if (afterMaterial != NO_MATERIAL && all(afterThroughput > vec3<f32>(0.0))) {\n var input = shaderInputAt(afterMaterial, afterTriangle, afterBary, afterDirection);\n input.data = materials[afterMaterial].afterData;\n input.diffuseColor = afterAlbedo;\n input.fragColor = vec4<f32>((radiance - afterStart) / afterThroughput, 1.0);\n\n let edited = runProgram(materials[afterMaterial].afterProgram, input);\n\n radiance = afterStart + afterThroughput * edited.color.rgb;\n // A hook rewrites the colour as a whole: there is no split left to keep.\n diffuse = radiance;\n }\n\n // Three lays its fog after the hooks, over what they made of the surface.\n if (fogged) {\n let fog = frame.fogColor.rgb * fogThroughput * fogAmount;\n\n radiance = fogStart + (radiance - fogStart) * (1.0 - fogAmount) + fog;\n // What came before the fogged surface is diffuse, so the fog's own colour joins that signal.\n diffuse = fogStart + (diffuse - fogStart) * (1.0 - fogAmount) + fog;\n }\n\n // The air takes its share of what lies behind it and adds the light it scatters towards the camera; the background,\n // which already is the sky, is left as it is.\n if (hazed) {\n let through = exp(-frame.atmosphereExtinction.rgb * hazeDistance);\n // The sun lights the air by the phase function of what fills it: Rayleigh's for clean air, a forward lobe for haze\n // (Henyey-Greenstein at 0.76), which is what makes the air glow towards the sun.\n let turn = dot(hazeDirection, frame.atmosphereSun.xyz);\n let phase = mix(3.0 / (16.0 * PI) * (1.0 + turn * turn), henyeyGreenstein(turn, 0.76), frame.atmosphereExtinction.w);\n let air = frame.atmosphereColor.rgb + frame.atmosphereSunColor.rgb * phase;\n let glow = air * hazeThroughput * (vec3<f32>(1.0) - through);\n\n radiance = hazeStart + (radiance - hazeStart) * through + glow;\n diffuse = hazeStart + (diffuse - hazeStart) * through + glow;\n }\n\n var result: PathResult;\n result.radiance = radiance;\n result.alpha = alpha;\n result.depth = depth;\n result.diffuse = diffuse;\n result.diffuseAlbedo = diffuseAlbedo;\n result.specularAlbedo = specularAlbedoGuide;\n result.normal = guideNormal;\n result.guideDistance = guideDistance;\n result.roughness = guideRoughness;\n result.specularDistance = specularDistance;\n result.subsurface = guideSubsurface;\n\n return result;\n}\n\n/** A point on the lens: a disk, or Three-free polygon bokeh shaped as the CPU renderer shapes it. */\nfn lensPoint(u: vec2<f32>) -> vec2<f32> {\n var radius = sqrt(u.x) * frame.lens.x;\n let angle = u.y * 2.0 * PI;\n let blades = frame.lens.z;\n\n if (blades >= 3.0) {\n let wedge = 2.0 * PI / blades;\n radius = radius * cos(PI / blades) / cos((angle - floor(angle / wedge) * wedge) - PI / blades);\n }\n\n return vec2<f32>(cos(angle), sin(angle)) * radius;\n}\n\n/**\n * Where a sample's camera ray starts, which way it points and how far it may go, for any camera: the ray is cast through\n * the inverse of the camera's own projection, from the near plane to the far one, which clip it as Three clips a\n * fragment. A lens moves the origin across its aperture and aims at the point in focus.\n */\nfn cameraRay(pixel: vec2<u32>, jitter: vec2<f32>, lens: vec2<f32>) -> array<vec4<f32>, 2> {\n let uv = (vec2<f32>(pixel) + jitter) / vec2<f32>(frame.resolution);\n var ndc = vec2<f32>(uv.x * 2.0 - 1.0, 1.0 - uv.y * 2.0);\n\n // A lens's radial distortion: the pixel sees the scene at a radius scaled by the square of its own, which is one at\n // the corners. Positive reaches further out at the edges (barrel), negative less far (pincushion).\n if (frame.lensDistortion != 0.0) {\n let aspect = f32(frame.resolution.x) / f32(frame.resolution.y);\n let radius2 = (ndc.x * ndc.x * aspect * aspect + ndc.y * ndc.y) / (aspect * aspect + 1.0);\n\n ndc = ndc * (1.0 + frame.lensDistortion * radius2);\n }\n\n let ray = ndcRay(ndc);\n\n if (frame.lens.x <= 0.0 || frame.cameraKind == 1u) {\n return ray;\n }\n\n let position = frame.cameraToWorld[3].xyz;\n let forward = -normalize(frame.cameraToWorld[2].xyz);\n let focus = position + ray[1].xyz * (frame.lens.y / max(dot(ray[1].xyz, forward), 1e-6));\n let offset = lensPoint(lens);\n let origin = position + normalize(frame.cameraToWorld[0].xyz) * offset.x + normalize(frame.cameraToWorld[1].xyz) * offset.y;\n\n return array<vec4<f32>, 2>(vec4<f32>(origin, 0.0), vec4<f32>(normalize(focus - origin), 1e30));\n}\n\n/** The window depth GL would store for the first surface the camera ray stopped at: one where it stopped at none. */\nfn windowDepth(point: vec3<f32>, distance: f32) -> f32 {\n if (distance >= 1e30) {\n return 1.0;\n }\n\n let clip = frame.projection * (frame.worldToCamera * vec4<f32>(point, 1.0));\n\n return clamp(clip.z / clip.w * 0.5 + 0.5, 0.0, 1.0);\n}\n\n/** smoothstep as the CPU renderer writes it, which also holds when the two edges meet. */\nfn edge(low: f32, high: f32, value: f32) -> f32 {\n let t = select(select(0.0, 1.0, value >= high), clamp((value - low) / (high - low), 0.0, 1.0), high > low);\n\n return t * t * (3.0 - 2.0 * t);\n}\n\n/** How much of what lies at this point the fog lets through to the camera. */\nfn fogVisibility(point: vec3<f32>) -> f32 {\n let everySurface = frame.fogParams.w > 0.0;\n let kind = frame.fogColor.w;\n\n if (!everySurface && kind <= 0.0) {\n return 1.0;\n }\n\n let depth = -(frame.worldToCamera * vec4<f32>(point, 1.0)).z;\n\n return 1.0 - fogFactor(depth, select(kind, 1.0, everySurface));\n}\n\n/** The most volumetric lights one view ray marches through. */\nconst MAX_VOLUMETRIC: u32 = 8u;\n\n/**\n * Steps of one march. The CPU renderer marches 64 once per pixel; here every path marches, a few hundred times a\n * pixel, each at its own random offset, so a few steps a path add up to a finer integral than 64 once, at a fraction of\n * the shadow rays.\n */\nconst MARCH_STEPS: u32 = 8u;\n\n/**\n * The CPU renderer's volumetric lights (volumetricLight.js): one march across the union of every light's\n * reach along the view ray, Henyey-Greenstein scattering towards the camera, a shadow ray for a spot light that casts\n * one, and the same compression of the sum before it is added over the image.\n */\nfn volumetricGlow(origin: vec3<f32>, direction: vec3<f32>, distance: f32, jitter: f32) -> vec3<f32> {\n let count = min(frame.volumetricCount, MAX_VOLUMETRIC);\n let far = min(distance, 40.0);\n var tStart = far;\n var tEnd = 0.0;\n\n for (var k = 0u; k < count; k = k + 1u) {\n let at = frame.volumetricData + k * 20u;\n let position = extraVec4(at).xyz;\n let spot = extraFloat(at + 3u) > 0.5;\n let axis = extraVec4(at + 4u).xyz;\n let radius = extraFloat(at + 7u);\n let outer = extraFloat(at + 15u);\n let delta = origin - position;\n let b = dot(delta, direction);\n let disc = b * b - dot(delta, delta) + radius * radius;\n\n if (disc <= 0.0) {\n continue;\n }\n\n let start = max(0.0, -b - sqrt(disc));\n let end = min(far, -b + sqrt(disc));\n\n if (end <= start) {\n continue;\n }\n\n var cuts = array<f32, 4>(start, end, end, end);\n var cutCount = 2u;\n let cone = cos(outer);\n\n if (spot) {\n let ar = dot(axis, direction);\n let ac = dot(axis, delta);\n let cos2 = cone * cone;\n let qa = ar * ar - cos2;\n let qb = ar * ac - dot(direction, delta) * cos2;\n let qc = ac * ac - dot(delta, delta) * cos2;\n let discriminant = qb * qb - qa * qc;\n var roots = array<f32, 2>(-1.0, -1.0);\n\n if (abs(qa) < 1e-8) {\n if (abs(qb) > 1e-8) {\n roots[0] = -qc / (2.0 * qb);\n }\n } else if (discriminant >= 0.0) {\n roots[0] = (-qb - sqrt(discriminant)) / qa;\n roots[1] = (-qb + sqrt(discriminant)) / qa;\n }\n\n for (var r = 0u; r < 2u; r = r + 1u) {\n if (roots[r] > start && roots[r] < end) {\n cuts[cutCount] = roots[r];\n cutCount = cutCount + 1u;\n }\n }\n\n // Sort the few cuts in place.\n for (var i = 1u; i < cutCount; i = i + 1u) {\n var j = i;\n\n loop {\n if (j == 0u || cuts[j - 1u] <= cuts[j]) {\n break;\n }\n\n let swap = cuts[j];\n cuts[j] = cuts[j - 1u];\n cuts[j - 1u] = swap;\n j = j - 1u;\n }\n }\n }\n\n for (var segment = 1u; segment < cutCount; segment = segment + 1u) {\n let lo = cuts[segment - 1u];\n let hi = cuts[segment];\n\n if (spot && dot(normalize(delta + direction * ((lo + hi) * 0.5)), axis) < cone) {\n continue;\n }\n\n tStart = min(tStart, lo);\n tEnd = max(tEnd, hi);\n }\n }\n\n if (tEnd <= tStart) {\n return vec3<f32>(0.0);\n }\n\n let step = (tEnd - tStart) / f32(MARCH_STEPS);\n var transmittance: array<f32, 8>;\n\n for (var k = 0u; k < count; k = k + 1u) {\n transmittance[k] = exp(-extraFloat(frame.volumetricData + k * 20u + 11u) * tStart);\n }\n\n var result = vec3<f32>(0.0);\n\n for (var i = 0u; i < MARCH_STEPS; i = i + 1u) {\n let t = tStart + (f32(i) + jitter) * step;\n let p = origin + direction * t;\n let fogged = fogVisibility(p);\n\n if (fogged <= 0.0001) {\n break;\n }\n\n var lit = false;\n\n for (var k = 0u; k < count; k = k + 1u) {\n if (transmittance[k] <= 0.003) {\n continue;\n }\n\n lit = true;\n\n let at = frame.volumetricData + k * 20u;\n let position = extraVec4(at).xyz;\n let spot = extraFloat(at + 3u) > 0.5;\n let axis = extraVec4(at + 4u).xyz;\n let color = extraVec4(at + 8u).rgb;\n let density = extraFloat(at + 11u);\n let angle = extraFloat(at + 12u);\n let penumbra = extraFloat(at + 13u);\n let range = extraFloat(at + 14u);\n let outer = extraFloat(at + 15u);\n let spread = extraFloat(at + 16u);\n let anisotropy = extraFloat(at + 17u);\n let casts = extraFloat(at + 18u) > 0.5;\n let toLight = position - p;\n let dist = length(toLight);\n let toward = toLight / max(dist, 1e-20);\n var attenuation = exp(-dist / (select(10.0, range, range > 0.0) * 0.3));\n\n if (range > 0.0) {\n attenuation = attenuation * (1.0 - edge(range * 0.8, range, dist));\n }\n\n if (spot) {\n let along = -dot(toward, axis);\n let inner = cos(angle * (1.0 - penumbra));\n let core = edge(cos(angle), inner, along);\n let scattered = spread * pow(edge(cos(outer), inner, along), 2.0);\n\n attenuation = attenuation * select(core, max(core, scattered), spread > 0.0);\n }\n\n if (attenuation <= 0.0001) {\n continue;\n }\n\n // Shadowing follows Three's volumetric lights, which only have shadow maps for spots.\n if (spot && casts && frame.shadowsEnabled != 0u && traceAny(p, toward, dist * (1.0 - 1e-3)) != NO_HIT) {\n continue;\n }\n\n let cosine = dot(toward, direction);\n let g = anisotropy;\n let phase = select((1.0 - g * g) / pow(1.0 + g * g - 2.0 * g * cosine, 1.5), 1.0, g == 0.0);\n\n // The air between the camera and this point, exactly: a long step evaluated at its start would overstate it.\n result = result + color * (attenuation * density * step * exp(-density * t) * fogged * phase * 1.5);\n }\n\n if (!lit) {\n break;\n }\n\n for (var k = 0u; k < count; k = k + 1u) {\n transmittance[k] = transmittance[k] * exp(-extraFloat(frame.volumetricData + k * 20u + 11u) * step);\n }\n }\n\n return result / (vec3<f32>(1.0) + result);\n}\n\n/**\n * How far a pixel's estimate may still be from its mean: the standard error of its luminance, over the square root of\n * the luminance, which is roughly how visible that error is once the image is encoded for display.\n */\nfn pixelError(pixel: vec2<u32>) -> f32 {\n let index = pixel.y * frame.resolution.x + pixel.x;\n let sum = accumulation[index];\n\n if (sum.w < 2.0) {\n return 1e30;\n }\n\n let squares = accumulation[frame.pixelCount + index];\n let diffuse = accumulation[4u * frame.pixelCount + index].rgb;\n\n // Each of the denoiser's signals has its own variance; the pixel has converged when both have.\n return max(\n channelError(luminanceOf(diffuse) / sum.w, squares.z / sum.w, sum.w),\n channelError(luminanceOf(sum.rgb - diffuse) / sum.w, squares.w / sum.w, sum.w));\n}\n\nfn channelError(mean: f32, square: f32, samples: f32) -> f32 {\n let variance = max(square - mean * mean, 0.0);\n\n return sqrt(variance / samples) / sqrt(max(mean, 0.0) + 1e-3);\n}\n\n/**\n * Whether a pixel has converged, judged over its neighbourhood: a rare bright path lands in one pixel, and a pixel\n * judged alone would stop where its neighbours had not yet seen one and leave that area too dark.\n */\nfn converged(pixel: vec2<u32>) -> bool {\n for (var dy = -1; dy <= 1; dy = dy + 1) {\n for (var dx = -1; dx <= 1; dx = dx + 1) {\n let x = clamp(i32(pixel.x) + dx, 0, i32(frame.resolution.x) - 1);\n let y = clamp(i32(pixel.y) + dy, 0, i32(frame.resolution.y) - 1);\n\n if (pixelError(vec2<u32>(u32(x), u32(y))) > frame.adaptiveThreshold) {\n return false;\n }\n }\n }\n\n return true;\n}\n\n@compute @workgroup_size(8, 8, 1)\nfn main(@builtin(global_invocation_id) id: vec3<u32>) {\n if (id.x >= frame.bandSize.x || id.y >= frame.bandSize.y) {\n return;\n }\n\n let pixel = frame.bandOrigin + id.xy;\n\n if (pixel.x >= frame.resolution.x || pixel.y >= frame.resolution.y) {\n return;\n }\n\n let index = pixel.y * frame.resolution.x + pixel.x;\n\n // Adaptive sampling: a pixel whose neighbourhood has converged takes no more samples, which leaves the pass to\n // the pixels that still need them.\n if (frame.adaptiveMin > 0u && accumulation[index].w >= f32(frame.adaptiveMin) && converged(pixel)) {\n return;\n }\n\n var radiance = vec3<f32>(0.0);\n var alpha = 0.0;\n var depthSum = 0.0;\n var diffuseSquares = 0.0;\n var specularSquares = 0.0;\n var diffuseSum = vec3<f32>(0.0);\n var diffuseAlbedoSum = vec3<f32>(0.0);\n var specularAlbedoSum = vec3<f32>(0.0);\n var normalSum = vec3<f32>(0.0);\n var distanceSum = 0.0;\n var roughnessSum = 0.0;\n var specularDistanceSum = 0.0;\n var subsurfaceSum = 0.0;\n\n for (var s = 0u; s < frame.sampleCount; s = s + 1u) {\n var rng = makeSampler(pixel, frame.sampleIndex + s);\n let jitter = sample2D(&rng);\n let lens = sample2D(&rng);\n let ray = cameraRay(pixel, jitter, lens);\n let result = traceRadiance(ray[0].xyz, ray[1].xyz, ray[1].w, &rng);\n var sampleAlpha = result.alpha;\n\n var sampled = result.radiance;\n var sampledDiffuse = result.diffuse;\n\n if (frame.volumetricCount > 0u) {\n let glow = volumetricGlow(ray[0].xyz, ray[1].xyz, result.depth, sample2D(&rng).x);\n\n // As the CPU renderer composites it: added over the image, and raising the coverage just enough to hold it.\n sampled = sampled + glow;\n sampledDiffuse = sampledDiffuse + glow;\n sampleAlpha = max(sampleAlpha, max3(glow));\n }\n\n let sampledSpecular = sampled - sampledDiffuse;\n\n radiance = radiance + sampled;\n diffuseSum = diffuseSum + sampledDiffuse;\n diffuseSquares = diffuseSquares + luminanceOf(sampledDiffuse) * luminanceOf(sampledDiffuse);\n specularSquares = specularSquares + luminanceOf(sampledSpecular) * luminanceOf(sampledSpecular);\n diffuseAlbedoSum = diffuseAlbedoSum + result.diffuseAlbedo;\n specularAlbedoSum = specularAlbedoSum + result.specularAlbedo;\n normalSum = normalSum + result.normal;\n distanceSum = distanceSum + result.guideDistance;\n roughnessSum = roughnessSum + result.roughness;\n specularDistanceSum = specularDistanceSum + result.specularDistance;\n subsurfaceSum = subsurfaceSum + result.subsurface;\n\n alpha = alpha + sampleAlpha;\n depthSum = depthSum + windowDepth(ray[0].xyz + ray[1].xyz * min(result.depth, 1e20), result.depth);\n }\n\n let coverage = accumulation[frame.pixelCount + index];\n accumulation[index] = accumulation[index] + vec4<f32>(radiance, f32(frame.sampleCount));\n accumulation[frame.pixelCount + index] = vec4<f32>(\n coverage.x + alpha, coverage.y + depthSum, coverage.z + diffuseSquares, coverage.w + specularSquares);\n // The denoiser's signals and guides, summed like the radiance so they average over the pixel's samples.\n let pc = frame.pixelCount;\n accumulation[2u * pc + index] = accumulation[2u * pc + index] + vec4<f32>(diffuseAlbedoSum, roughnessSum);\n accumulation[3u * pc + index] = accumulation[3u * pc + index] + vec4<f32>(normalSum, distanceSum);\n accumulation[4u * pc + index] = accumulation[4u * pc + index] + vec4<f32>(diffuseSum, specularDistanceSum);\n accumulation[5u * pc + index] = accumulation[5u * pc + index] + vec4<f32>(specularAlbedoSum, subsurfaceSum);\n // This row still has work: every pixel that traced writes the same value, so the race is harmless.\n accumulation[6u * pc + pixel.y] = vec4<f32>(1.0);\n}\n";
|
|
14
14
|
//# sourceMappingURL=pathTrace.wgsl.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"pathTrace.wgsl.d.ts","sourceRoot":"","sources":["../../src/wgsl/pathTrace.wgsl.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AACH,eAAO,MAAM,eAAe,
|
|
1
|
+
{"version":3,"file":"pathTrace.wgsl.d.ts","sourceRoot":"","sources":["../../src/wgsl/pathTrace.wgsl.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AACH,eAAO,MAAM,eAAe,ktpDA+2C3B,CAAC"}
|