@tinypoly/gpu-renderer 0.2.5 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/ARCHITECTURE.md +48 -10
- package/README.md +2 -0
- package/dist/accumulator.d.ts.map +1 -1
- package/dist/accumulator.js +1 -0
- package/dist/accumulator.js.map +1 -1
- package/dist/denoise.js +2 -2
- package/dist/denoise.js.map +1 -1
- package/dist/device.d.ts.map +1 -1
- package/dist/device.js +9 -0
- package/dist/device.js.map +1 -1
- package/dist/frameLayout.d.ts.map +1 -1
- package/dist/frameLayout.js +5 -0
- package/dist/frameLayout.js.map +1 -1
- package/dist/geometry.d.ts +48 -8
- package/dist/geometry.d.ts.map +1 -1
- package/dist/geometry.js +409 -134
- package/dist/geometry.js.map +1 -1
- package/dist/grass.d.ts.map +1 -1
- package/dist/grass.js +2 -1
- package/dist/grass.js.map +1 -1
- package/dist/imageResolve.js +2 -2
- package/dist/imageResolve.js.map +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/dist/instancing.d.ts +100 -0
- package/dist/instancing.d.ts.map +1 -0
- package/dist/instancing.js +286 -0
- package/dist/instancing.js.map +1 -0
- package/dist/lights.d.ts.map +1 -1
- package/dist/lights.js +8 -5
- package/dist/lights.js.map +1 -1
- package/dist/memoryProbe.d.ts +76 -0
- package/dist/memoryProbe.d.ts.map +1 -0
- package/dist/memoryProbe.js +197 -0
- package/dist/memoryProbe.js.map +1 -0
- package/dist/oidnPass.d.ts +6 -0
- package/dist/oidnPass.d.ts.map +1 -1
- package/dist/oidnPass.js +18 -1
- package/dist/oidnPass.js.map +1 -1
- package/dist/pathTracePass.d.ts +15 -2
- package/dist/pathTracePass.d.ts.map +1 -1
- package/dist/pathTracePass.js +38 -16
- package/dist/pathTracePass.js.map +1 -1
- package/dist/renderer.d.ts +13 -0
- package/dist/renderer.d.ts.map +1 -1
- package/dist/renderer.js +248 -41
- package/dist/renderer.js.map +1 -1
- package/dist/sceneUpload.d.ts +26 -8
- package/dist/sceneUpload.d.ts.map +1 -1
- package/dist/sceneUpload.js +97 -27
- package/dist/sceneUpload.js.map +1 -1
- package/dist/shaderModule.d.ts.map +1 -1
- package/dist/shaderModule.js +2 -1
- package/dist/shaderModule.js.map +1 -1
- package/dist/skyBake.d.ts.map +1 -1
- package/dist/skyBake.js +5 -3
- package/dist/skyBake.js.map +1 -1
- package/dist/texturePack.d.ts +43 -3
- package/dist/texturePack.d.ts.map +1 -1
- package/dist/texturePack.js +209 -37
- package/dist/texturePack.js.map +1 -1
- package/dist/wgsl/bvh.wgsl.d.ts +5 -1
- package/dist/wgsl/bvh.wgsl.d.ts.map +1 -1
- package/dist/wgsl/bvh.wgsl.js +105 -15
- 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 +92 -11
- package/dist/wgsl/common.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 +24 -14
- 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 +11 -0
- package/dist/wgsl/texture.wgsl.js.map +1 -1
- package/package.json +1 -1
- package/src/accumulator.ts +1 -0
- package/src/denoise.ts +2 -2
- package/src/device.ts +12 -0
- package/src/frameLayout.ts +5 -0
- package/src/geometry.ts +527 -133
- package/src/grass.ts +2 -1
- package/src/imageResolve.ts +2 -2
- package/src/index.ts +1 -0
- package/src/instancing.ts +415 -0
- package/src/lights.ts +9 -5
- package/src/memoryProbe.ts +275 -0
- package/src/oidnPass.ts +21 -1
- package/src/pathTracePass.ts +42 -18
- package/src/renderer.ts +308 -47
- package/src/sceneUpload.ts +139 -36
- package/src/shaderModule.ts +2 -1
- package/src/skyBake.ts +5 -3
- package/src/texturePack.ts +274 -43
- package/src/wgsl/bvh.wgsl.ts +105 -15
- package/src/wgsl/common.wgsl.ts +92 -11
- package/src/wgsl/surface.wgsl.ts +24 -14
- package/src/wgsl/texture.wgsl.ts +11 -0
package/dist/wgsl/bvh.wgsl.js
CHANGED
|
@@ -4,6 +4,10 @@
|
|
|
4
4
|
* The positions are uploaded in the hierarchy's leaf order, so a leaf is a run of triangles read straight off the
|
|
5
5
|
* buffer; the scene's own triangle number is looked up once, for the hit a trace returns. Every other reader goes the
|
|
6
6
|
* other way, from a triangle number to where its corners sit.
|
|
7
|
+
*
|
|
8
|
+
* With INSTANCES compiled in, a leaf with a count of -1 is an instance: the ray is taken into its object space and
|
|
9
|
+
* the traversal goes on in its prototype's hierarchy, with a marker on the stack that brings it back to world space.
|
|
10
|
+
* The distance along the ray is the same in both spaces, since the direction is transformed and not normalized.
|
|
7
11
|
*/
|
|
8
12
|
export const BVH_WGSL = /* wgsl */ `
|
|
9
13
|
/** A corner of the triangle at this position of the hierarchy's leaf order. */
|
|
@@ -18,8 +22,37 @@ fn leafOf(triangle: u32) -> u32 {
|
|
|
18
22
|
return indices[frame.leafOffset + triangle];
|
|
19
23
|
}
|
|
20
24
|
|
|
25
|
+
/** A corner of a triangle a hit named, in world space. */
|
|
21
26
|
fn triangleVertex(triangle: u32, corner: u32) -> vec3<f32> {
|
|
22
|
-
|
|
27
|
+
let instance = instanceOf(triangle);
|
|
28
|
+
let p = leafVertex(leafOf(storedTriangle(triangle, instance)), corner);
|
|
29
|
+
|
|
30
|
+
if (instance != NO_INSTANCE) {
|
|
31
|
+
return instancePoint(instance, p);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
return p;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** The stack entry that leaves an instance: the traversal goes back to world space. */
|
|
38
|
+
const RETURN_ENTRY: u32 = 0xffffffffu;
|
|
39
|
+
|
|
40
|
+
/** A huge finite reciprocal instead of an infinite one: an axis aligned slab would otherwise produce 0 * inf. */
|
|
41
|
+
fn rayInverse(direction: vec3<f32>) -> vec3<f32> {
|
|
42
|
+
let signs = select(vec3<f32>(-1.0), vec3<f32>(1.0), direction >= vec3<f32>(0.0));
|
|
43
|
+
|
|
44
|
+
return signs / max(abs(direction), vec3<f32>(1e-20));
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** The number a hit goes by, from where it sits in the leaf order and the instance it was found in. */
|
|
48
|
+
fn namedTriangle(at: u32, instance: u32) -> u32 {
|
|
49
|
+
let stored = orderedTriangle(at);
|
|
50
|
+
|
|
51
|
+
if (INSTANCES && instance != NO_INSTANCE) {
|
|
52
|
+
return instanceWord(instance, 26u) + stored - instanceWord(instance, 25u);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
return stored;
|
|
23
56
|
}
|
|
24
57
|
|
|
25
58
|
/** Moller-Trumbore. Returns the distance in x and the barycentric coordinates in yz, or a negative distance. */
|
|
@@ -127,7 +160,7 @@ fn waitingLeaf(entry: u32) -> vec2<i32> {
|
|
|
127
160
|
* A leaf is tested at the top of the next step, the one place the loop tests triangles, which keeps the kernel small.
|
|
128
161
|
* This visits what the binary tree's traversal visited, in the same order, so it finds the same hit.
|
|
129
162
|
*/
|
|
130
|
-
fn traceScene(
|
|
163
|
+
fn traceScene(worldOrigin: vec3<f32>, worldDirection: vec3<f32>, maxDistance: f32) -> Hit {
|
|
131
164
|
var hit: Hit;
|
|
132
165
|
hit.distance = maxDistance;
|
|
133
166
|
hit.triangle = NO_HIT;
|
|
@@ -138,12 +171,15 @@ fn traceScene(origin: vec3<f32>, direction: vec3<f32>, maxDistance: f32) -> Hit
|
|
|
138
171
|
return hit;
|
|
139
172
|
}
|
|
140
173
|
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
174
|
+
var origin = worldOrigin;
|
|
175
|
+
var direction = worldDirection;
|
|
176
|
+
var inverse = rayInverse(direction);
|
|
177
|
+
// The instance the traversal is inside, and the one the closest hit so far was found in.
|
|
178
|
+
var instance = NO_INSTANCE;
|
|
179
|
+
var hitInstance = NO_INSTANCE;
|
|
144
180
|
|
|
145
|
-
var stack: array<u32,
|
|
146
|
-
var enters: array<f32,
|
|
181
|
+
var stack: array<u32, BVH_STACK>;
|
|
182
|
+
var enters: array<f32, BVH_STACK>;
|
|
147
183
|
var depth = 0u;
|
|
148
184
|
var current = 0u;
|
|
149
185
|
// A leaf to test before anything else: its link, and its triangle count, zero when there is none.
|
|
@@ -151,10 +187,32 @@ fn traceScene(origin: vec3<f32>, direction: vec3<f32>, maxDistance: f32) -> Hit
|
|
|
151
187
|
|
|
152
188
|
loop {
|
|
153
189
|
if (leaf.y > 0) {
|
|
190
|
+
let before = hit.distance;
|
|
191
|
+
|
|
154
192
|
intersectLeaf(leaf.x, leaf.y, origin, direction, &hit);
|
|
193
|
+
|
|
194
|
+
if (INSTANCES && hit.distance < before) {
|
|
195
|
+
hitInstance = instance;
|
|
196
|
+
}
|
|
197
|
+
|
|
155
198
|
leaf.y = 0;
|
|
156
199
|
}
|
|
157
200
|
|
|
201
|
+
if (INSTANCES && leaf.y < 0) {
|
|
202
|
+
leaf.y = 0;
|
|
203
|
+
|
|
204
|
+
if (depth < BVH_STACK) {
|
|
205
|
+
instance = u32(-1 - leaf.x);
|
|
206
|
+
stack[depth] = RETURN_ENTRY;
|
|
207
|
+
enters[depth] = -1.0;
|
|
208
|
+
depth = depth + 1u;
|
|
209
|
+
origin = instanceToObject(instance, worldOrigin, 1.0);
|
|
210
|
+
direction = instanceToObject(instance, worldDirection, 0.0);
|
|
211
|
+
inverse = rayInverse(direction);
|
|
212
|
+
current = instanceWord(instance, 24u);
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
|
|
158
216
|
if (current == NO_NODE) {
|
|
159
217
|
if (depth == 0u) {
|
|
160
218
|
break;
|
|
@@ -169,6 +227,14 @@ fn traceScene(origin: vec3<f32>, direction: vec3<f32>, maxDistance: f32) -> Hit
|
|
|
169
227
|
|
|
170
228
|
let entry = stack[depth];
|
|
171
229
|
|
|
230
|
+
if (INSTANCES && entry == RETURN_ENTRY) {
|
|
231
|
+
instance = NO_INSTANCE;
|
|
232
|
+
origin = worldOrigin;
|
|
233
|
+
direction = worldDirection;
|
|
234
|
+
inverse = rayInverse(direction);
|
|
235
|
+
continue;
|
|
236
|
+
}
|
|
237
|
+
|
|
172
238
|
if ((entry & LEAF_ENTRY) != 0u) {
|
|
173
239
|
leaf = waitingLeaf(entry);
|
|
174
240
|
continue;
|
|
@@ -198,7 +264,7 @@ fn traceScene(origin: vec3<f32>, direction: vec3<f32>, maxDistance: f32) -> Hit
|
|
|
198
264
|
}
|
|
199
265
|
|
|
200
266
|
// The builder caps its depth so the far children always fit; the guard keeps a malformed tree inside the stack.
|
|
201
|
-
if (farEnter < 1e30 && depth <
|
|
267
|
+
if (farEnter < 1e30 && depth < BVH_STACK) {
|
|
202
268
|
stack[depth] = select(u32(farLink), leafEntry(parent, leftFirst), farLink < 0);
|
|
203
269
|
enters[depth] = farEnter;
|
|
204
270
|
depth = depth + 1u;
|
|
@@ -206,7 +272,7 @@ fn traceScene(origin: vec3<f32>, direction: vec3<f32>, maxDistance: f32) -> Hit
|
|
|
206
272
|
}
|
|
207
273
|
|
|
208
274
|
if (hit.triangle != NO_HIT) {
|
|
209
|
-
hit.triangle =
|
|
275
|
+
hit.triangle = namedTriangle(hit.triangle, hitInstance);
|
|
210
276
|
}
|
|
211
277
|
|
|
212
278
|
return hit;
|
|
@@ -217,15 +283,17 @@ fn traceScene(origin: vec3<f32>, direction: vec3<f32>, maxDistance: f32) -> Hit
|
|
|
217
283
|
* closest: what a shadow ray asks when every surface it could meet blocks it. Returns that triangle, or NO_HIT. The
|
|
218
284
|
* right child goes first and the left one waits, the order the binary tree's traversal took.
|
|
219
285
|
*/
|
|
220
|
-
fn traceAny(
|
|
286
|
+
fn traceAny(worldOrigin: vec3<f32>, worldDirection: vec3<f32>, maxDistance: f32) -> u32 {
|
|
221
287
|
if (frame.triangleCount == 0u) {
|
|
222
288
|
return NO_HIT;
|
|
223
289
|
}
|
|
224
290
|
|
|
225
|
-
|
|
226
|
-
|
|
291
|
+
var origin = worldOrigin;
|
|
292
|
+
var direction = worldDirection;
|
|
293
|
+
var inverse = rayInverse(direction);
|
|
294
|
+
var instance = NO_INSTANCE;
|
|
227
295
|
|
|
228
|
-
var stack: array<u32,
|
|
296
|
+
var stack: array<u32, BVH_STACK>;
|
|
229
297
|
var depth = 0u;
|
|
230
298
|
var current = 0u;
|
|
231
299
|
var leaf = vec2<i32>(0, 0);
|
|
@@ -235,12 +303,26 @@ fn traceAny(origin: vec3<f32>, direction: vec3<f32>, maxDistance: f32) -> u32 {
|
|
|
235
303
|
let found = anyInLeaf(leaf.x, leaf.y, origin, direction, maxDistance);
|
|
236
304
|
|
|
237
305
|
if (found != NO_HIT) {
|
|
238
|
-
return
|
|
306
|
+
return namedTriangle(found, instance);
|
|
239
307
|
}
|
|
240
308
|
|
|
241
309
|
leaf.y = 0;
|
|
242
310
|
}
|
|
243
311
|
|
|
312
|
+
if (INSTANCES && leaf.y < 0) {
|
|
313
|
+
leaf.y = 0;
|
|
314
|
+
|
|
315
|
+
if (depth < BVH_STACK) {
|
|
316
|
+
instance = u32(-1 - leaf.x);
|
|
317
|
+
stack[depth] = RETURN_ENTRY;
|
|
318
|
+
depth = depth + 1u;
|
|
319
|
+
origin = instanceToObject(instance, worldOrigin, 1.0);
|
|
320
|
+
direction = instanceToObject(instance, worldDirection, 0.0);
|
|
321
|
+
inverse = rayInverse(direction);
|
|
322
|
+
current = instanceWord(instance, 24u);
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
|
|
244
326
|
if (current == NO_NODE) {
|
|
245
327
|
if (depth == 0u) {
|
|
246
328
|
break;
|
|
@@ -250,6 +332,14 @@ fn traceAny(origin: vec3<f32>, direction: vec3<f32>, maxDistance: f32) -> u32 {
|
|
|
250
332
|
|
|
251
333
|
let entry = stack[depth];
|
|
252
334
|
|
|
335
|
+
if (INSTANCES && entry == RETURN_ENTRY) {
|
|
336
|
+
instance = NO_INSTANCE;
|
|
337
|
+
origin = worldOrigin;
|
|
338
|
+
direction = worldDirection;
|
|
339
|
+
inverse = rayInverse(direction);
|
|
340
|
+
continue;
|
|
341
|
+
}
|
|
342
|
+
|
|
253
343
|
if ((entry & LEAF_ENTRY) != 0u) {
|
|
254
344
|
leaf = waitingLeaf(entry);
|
|
255
345
|
continue;
|
|
@@ -277,7 +367,7 @@ fn traceAny(origin: vec3<f32>, direction: vec3<f32>, maxDistance: f32) -> u32 {
|
|
|
277
367
|
}
|
|
278
368
|
}
|
|
279
369
|
|
|
280
|
-
if (rightHit && leftHit && depth <
|
|
370
|
+
if (rightHit && leftHit && depth < BVH_STACK) {
|
|
281
371
|
stack[depth] = select(u32(node.leftLink), leafEntry(parent, false), node.leftLink < 0);
|
|
282
372
|
depth = depth + 1u;
|
|
283
373
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bvh.wgsl.js","sourceRoot":"","sources":["../../src/wgsl/bvh.wgsl.ts"],"names":[],"mappings":"AAAA
|
|
1
|
+
{"version":3,"file":"bvh.wgsl.js","sourceRoot":"","sources":["../../src/wgsl/bvh.wgsl.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AACH,MAAM,CAAC,MAAM,QAAQ,GAAG,UAAU,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA8WlC,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"common.wgsl.d.ts","sourceRoot":"","sources":["../../src/wgsl/common.wgsl.ts"],"names":[],"mappings":"AAIA,6EAA6E;AAC7E,eAAO,MAAM,WAAW,
|
|
1
|
+
{"version":3,"file":"common.wgsl.d.ts","sourceRoot":"","sources":["../../src/wgsl/common.wgsl.ts"],"names":[],"mappings":"AAIA,6EAA6E;AAC7E,eAAO,MAAM,WAAW,QA6RvB,CAAC"}
|
package/dist/wgsl/common.wgsl.js
CHANGED
|
@@ -136,13 +136,16 @@ const TEXTURE_TABLE: u32 = ${TEXTURE_TABLE}u;
|
|
|
136
136
|
// A WebGPU device only has to offer eight storage buffers per stage, so arrays of the same kind share one binding and
|
|
137
137
|
// the uniform says where the second one starts. See sceneUpload.ts, which joins them.
|
|
138
138
|
@group(0) @binding(0) var<uniform> frame: Frame;
|
|
139
|
-
// Nine coordinates per triangle, in the hierarchy's leaf order: see leafOf in bvh.wgsl.ts.
|
|
139
|
+
// Nine coordinates per stored triangle, in the hierarchy's leaf order: see leafOf in bvh.wgsl.ts. A prototype's are
|
|
140
|
+
// in object space.
|
|
140
141
|
@group(0) @binding(1) var<storage, read> positions: array<f32>;
|
|
141
|
-
//
|
|
142
|
-
// frame.varyingOffset.
|
|
142
|
+
// Per vertex: the UV sets from frame.uvOffset and vertex colours from frame.colorOffset; then shader varyings, per
|
|
143
|
+
// corner, from frame.varyingOffset.
|
|
143
144
|
@group(0) @binding(2) var<storage, read> attributes: array<f32>;
|
|
144
|
-
// One material index per triangle, then the hierarchy's triangle order from frame.orderOffset on (the
|
|
145
|
-
// position of the leaf order), then from frame.leafOffset on the other way (the position of
|
|
145
|
+
// One material index per triangle a hit can name, then the hierarchy's triangle order from frame.orderOffset on (the
|
|
146
|
+
// stored triangle at each position of the leaf order), then from frame.leafOffset on the other way (the position of
|
|
147
|
+
// each stored triangle), the instance of every instanced triangle from frame.instanceOffset, the three vertices of each
|
|
148
|
+
// stored triangle from frame.cornerOffset and every vertex's folded normal from frame.normalOffset.
|
|
146
149
|
@group(0) @binding(3) var<storage, read> indices: array<u32>;
|
|
147
150
|
@group(0) @binding(4) var<storage, read> materials: array<Material>;
|
|
148
151
|
@group(0) @binding(5) var<storage, read> nodes: array<BvhNode>;
|
|
@@ -162,24 +165,102 @@ fn orderedTriangle(at: u32) -> u32 {
|
|
|
162
165
|
return indices[frame.orderOffset + at];
|
|
163
166
|
}
|
|
164
167
|
|
|
165
|
-
/**
|
|
166
|
-
|
|
167
|
-
|
|
168
|
+
/** What a triangle of the scene's own belongs to: no instance. */
|
|
169
|
+
const NO_INSTANCE: u32 = 0xffffffffu;
|
|
170
|
+
|
|
171
|
+
/** The instance a triangle a hit named belongs to, or NO_INSTANCE for one of the scene's own. */
|
|
172
|
+
fn instanceOf(triangle: u32) -> u32 {
|
|
173
|
+
if (!INSTANCES || triangle < frame.sceneTriangles) {
|
|
174
|
+
return NO_INSTANCE;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
return indices[frame.instanceOffset + triangle - frame.sceneTriangles];
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/** One word of an instance's record: see INSTANCE_WORDS in instancing.ts. */
|
|
181
|
+
fn instanceWord(instance: u32, word: u32) -> u32 {
|
|
182
|
+
return textures[frame.instanceData + instance * 28u + word];
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/** A row of an instance's transforms: 0 to 2 take object space to world, 3 to 5 back. */
|
|
186
|
+
fn instanceRow(instance: u32, row: u32) -> vec4<f32> {
|
|
187
|
+
let at = frame.instanceData + instance * 28u + row * 4u;
|
|
188
|
+
|
|
189
|
+
return vec4<f32>(bitcast<f32>(textures[at]), bitcast<f32>(textures[at + 1u]), bitcast<f32>(textures[at + 2u]),
|
|
190
|
+
bitcast<f32>(textures[at + 3u]));
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/** Where a named triangle is stored: itself, or for an instance's, the prototype's triangle it repeats. */
|
|
194
|
+
fn storedTriangle(triangle: u32, instance: u32) -> u32 {
|
|
195
|
+
if (instance == NO_INSTANCE) {
|
|
196
|
+
return triangle;
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
return instanceWord(instance, 25u) + triangle - instanceWord(instance, 26u);
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/** A point of an instance's prototype, in world space. */
|
|
203
|
+
fn instancePoint(instance: u32, p: vec3<f32>) -> vec3<f32> {
|
|
204
|
+
let q = vec4<f32>(p, 1.0);
|
|
205
|
+
|
|
206
|
+
return vec3<f32>(dot(instanceRow(instance, 0u), q), dot(instanceRow(instance, 1u), q), dot(instanceRow(instance, 2u), q));
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/** A world space point (w 1) or direction (w 0), in an instance's object space. */
|
|
210
|
+
fn instanceToObject(instance: u32, v: vec3<f32>, w: f32) -> vec3<f32> {
|
|
211
|
+
let q = vec4<f32>(v, w);
|
|
212
|
+
|
|
213
|
+
return vec3<f32>(dot(instanceRow(instance, 3u), q), dot(instanceRow(instance, 4u), q), dot(instanceRow(instance, 5u), q));
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/** An object space normal in world space, by the inverse transpose; not normalized. */
|
|
217
|
+
fn instanceNormal(instance: u32, n: vec3<f32>) -> vec3<f32> {
|
|
218
|
+
return n.x * instanceRow(instance, 3u).xyz + n.y * instanceRow(instance, 4u).xyz + n.z * instanceRow(instance, 5u).xyz;
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/** The three vertices of a triangle a hit named. */
|
|
222
|
+
fn triangleCorners(triangle: u32) -> vec3<u32> {
|
|
223
|
+
let at = frame.cornerOffset + storedTriangle(triangle, instanceOf(triangle)) * 3u;
|
|
224
|
+
|
|
225
|
+
return vec3<u32>(indices[at], indices[at + 1u], indices[at + 2u]);
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/** One UV set of a vertex: four components, two per set. */
|
|
229
|
+
fn vertexUv(vertex: u32, channel: u32) -> vec2<f32> {
|
|
230
|
+
let at = frame.uvOffset + vertex * 4u + channel * 2u;
|
|
168
231
|
|
|
169
232
|
return vec2<f32>(attributes[at], attributes[at + 1u]);
|
|
170
233
|
}
|
|
171
234
|
|
|
172
|
-
/** A
|
|
173
|
-
fn
|
|
235
|
+
/** A vertex's colour, or white when the scene has none. */
|
|
236
|
+
fn vertexColor(vertex: u32) -> vec4<f32> {
|
|
174
237
|
if (frame.hasColors == 0u) {
|
|
175
238
|
return vec4<f32>(1.0);
|
|
176
239
|
}
|
|
177
240
|
|
|
178
|
-
let at = frame.colorOffset +
|
|
241
|
+
let at = frame.colorOffset + vertex * 4u;
|
|
179
242
|
|
|
180
243
|
return vec4<f32>(attributes[at], attributes[at + 1u], attributes[at + 2u], attributes[at + 3u]);
|
|
181
244
|
}
|
|
182
245
|
|
|
246
|
+
/** A normal folded onto an octahedron in two signed 16 bit halves, as sceneUpload.ts folds it; zero for NO_NORMAL. */
|
|
247
|
+
fn vertexNormal(vertex: u32) -> vec3<f32> {
|
|
248
|
+
let code = indices[frame.normalOffset + vertex];
|
|
249
|
+
|
|
250
|
+
if (code == 0x80008000u) {
|
|
251
|
+
return vec3<f32>(0.0);
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
let e = unpack2x16snorm(code);
|
|
255
|
+
var n = vec3<f32>(e.x, e.y, 1.0 - abs(e.x) - abs(e.y));
|
|
256
|
+
let t = max(-n.z, 0.0);
|
|
257
|
+
|
|
258
|
+
n.x = n.x + select(t, -t, n.x >= 0.0);
|
|
259
|
+
n.y = n.y + select(t, -t, n.y >= 0.0);
|
|
260
|
+
|
|
261
|
+
return normalize(n);
|
|
262
|
+
}
|
|
263
|
+
|
|
183
264
|
fn extraFloat(at: u32) -> f32 {
|
|
184
265
|
return bitcast<f32>(textures[at]);
|
|
185
266
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"common.wgsl.js","sourceRoot":"","sources":["../../src/wgsl/common.wgsl.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AACjD,OAAO,EAAE,aAAa,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAC;AACtE,OAAO,EAAE,WAAW,EAAE,UAAU,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAC;AAE3E,6EAA6E;AAC7E,MAAM,CAAC,MAAM,WAAW,GAAG,UAAU,CAAC;EACpC,YAAY,CAAC,IAAI;;;;;;;;;;;;;;;EAejB,eAAe,CAAC,IAAI;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;6BAqFO,aAAa,CAAC,QAAQ;6BACtB,aAAa,CAAC,QAAQ;4BACvB,aAAa,CAAC,OAAO;0BACvB,aAAa,CAAC,KAAK;yBACpB,aAAa,CAAC,IAAI;0BACjB,aAAa,CAAC,KAAK;2BAClB,aAAa,CAAC,MAAM;0BACrB,aAAa,CAAC,KAAK;2BAClB,aAAa,CAAC,MAAM;2BACpB,aAAa,CAAC,MAAM;2BACpB,aAAa,CAAC,MAAM;;;;;;;;;;;;;;;;2BAgBpB,WAAW;0BACZ,UAAU;6BACP,aAAa
|
|
1
|
+
{"version":3,"file":"common.wgsl.js","sourceRoot":"","sources":["../../src/wgsl/common.wgsl.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AACjD,OAAO,EAAE,aAAa,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAC;AACtE,OAAO,EAAE,WAAW,EAAE,UAAU,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAC;AAE3E,6EAA6E;AAC7E,MAAM,CAAC,MAAM,WAAW,GAAG,UAAU,CAAC;EACpC,YAAY,CAAC,IAAI;;;;;;;;;;;;;;;EAejB,eAAe,CAAC,IAAI;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;6BAqFO,aAAa,CAAC,QAAQ;6BACtB,aAAa,CAAC,QAAQ;4BACvB,aAAa,CAAC,OAAO;0BACvB,aAAa,CAAC,KAAK;yBACpB,aAAa,CAAC,IAAI;0BACjB,aAAa,CAAC,KAAK;2BAClB,aAAa,CAAC,MAAM;0BACrB,aAAa,CAAC,KAAK;2BAClB,aAAa,CAAC,MAAM;2BACpB,aAAa,CAAC,MAAM;2BACpB,aAAa,CAAC,MAAM;;;;;;;;;;;;;;;;2BAgBpB,WAAW;0BACZ,UAAU;6BACP,aAAa;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA4JzC,CAAC"}
|
|
@@ -6,5 +6,5 @@
|
|
|
6
6
|
* CPU renderer follows too: roughness from green, metalness from blue, the alpha map from green, clearcoat from red,
|
|
7
7
|
* its roughness from green, sheen roughness from alpha, and so on.
|
|
8
8
|
*/
|
|
9
|
-
export declare const SURFACE_WGSL = "\nstruct Surface {\n // The shading normal, maps applied, facing the ray.\n normal: vec3<f32>,\n albedo: vec3<f32>,\n // What the surface radiates by itself: its emission, or the whole colour of a material Three does not light.\n emissive: vec3<f32>,\n // The dielectric's reflectance at normal incidence and at grazing angles, before metalness turns it to the albedo.\n specularColor: vec3<f32>,\n specularF90: f32,\n roughness: f32,\n metalness: f32,\n // How much of the surface actually covers this point: a cutout, a transparency or a discarded fragment.\n opacity: f32,\n // Three's diffuseColor.a, which blending other than normal weighs the surface by.\n alpha: f32,\n flags: u32,\n kind: u32,\n // Share of the diffuse layer that lets light through, with metal already taken out of it.\n transmission: f32,\n ior: f32,\n thickness: f32,\n dispersion: f32,\n // What a unit of distance inside the volume absorbs, per channel: zero for a volume that never darkens.\n absorption: vec3<f32>,\n // The interpolated normal facing the ray, before any map: thin walls, shadow rays and the clearcoat read this one.\n facing: vec3<f32>,\n // Whether the ray arrived from the side the normals point to, which is the outside of a closed volume.\n front: bool,\n clearcoat: f32,\n clearcoatRoughness: f32,\n clearcoatNormal: vec3<f32>,\n sheenColor: vec3<f32>,\n sheenRoughness: f32,\n iridescence: f32,\n iridescenceFresnel: vec3<f32>,\n // Anisotropic GGX: its strength, the roughness along the tangent, and the tangent frame it stretches along.\n anisotropy: f32,\n alphaT: f32,\n anisotropyT: vec3<f32>,\n anisotropyB: vec3<f32>,\n shininess: f32,\n // Phong's specular map, which scales its highlight.\n specularStrength: f32,\n gradientMap: u32,\n // The material's own environment map, which the paths leaving it see instead of the scene's.\n envMap: u32,\n envMapIntensity: f32,\n // Basic, Lambert and Phong blend their environment map over the lit colour: what the map shows here, and how much.\n legacyEnv: vec3<f32>,\n legacyAmount: f32,\n combine: u32,\n // Light a light map bakes into this point, which only the camera sees: the path traces the rest itself.\n lightMap: vec3<f32>,\n blending: u32,\n material: u32,\n // Share of the diffuse layer that scatters inside the material instead of at its surface.\n subsurface: f32,\n // What a translucent surface lets through to its far side, diffusely: grass blades. Zero for everything else.\n translucent: vec3<f32>,\n};\n\n/** Barycentric weights of the two trailing vertices, for a point drawn uniformly over a triangle's area. */\nfn triangleBarycentric(u: vec2<f32>) -> vec2<f32> {\n let root = sqrt(u.x);\n\n return vec2<f32>(1.0 - root, u.y * root);\n}\n\nfn trianglePointAt(triangle: u32, bary: vec2<f32>) -> vec3<f32> {\n return triangleVertex(triangle, 0u) * (1.0 - bary.x - bary.y)\n + triangleVertex(triangle, 1u) * bary.x\n + triangleVertex(triangle, 2u) * bary.y;\n}\n\nfn triangleUv(triangle: u32, bary: vec2<f32>, channel: u32) -> vec2<f32> {\n return attributeUv(triangle, 0u, channel) * (1.0 - bary.x - bary.y)\n + attributeUv(triangle, 1u, channel) * bary.x\n + attributeUv(triangle, 2u, channel) * bary.y;\n}\n\nfn triangleColor(triangle: u32, bary: vec2<f32>) -> vec4<f32> {\n return attributeColor(triangle, 0u) * (1.0 - bary.x - bary.y)\n + attributeColor(triangle, 1u) * bary.x\n + attributeColor(triangle, 2u) * bary.y;\n}\n\n/** A map slot, sampled through the UV set the texture asks for. Missing maps read as one, so a multiply is always safe. */\nfn sampleMap(index: u32, triangle: u32, bary: vec2<f32>) -> vec4<f32> {\n if (index == NO_TEXTURE) {\n return vec4<f32>(1.0);\n }\n\n return sampleTextureAt(index, triangleUv(triangle, bary, textureInfo(index).channel));\n}\n\n/** Whether the ray sees the side Three calls the front: the winding, which packing keeps counter-clockwise. */\nfn isFrontFace(triangle: u32, direction: vec3<f32>) -> bool {\n return dot(triangleNormal(triangle), direction) < 0.0;\n}\n\n/** Three culls the side a material does not draw. */\nfn isCulled(material: u32, triangle: u32, direction: vec3<f32>) -> bool {\n let side = materials[material].side;\n let front = isFrontFace(triangle, direction);\n\n return (side == SIDE_FRONT && !front) || (side == SIDE_BACK && front);\n}\n\n/** What the triangle radiates at this point, its emissive map included so direct and indirect light agree on it. */\nfn emissionAt(triangle: u32, bary: vec2<f32>) -> vec3<f32> {\n let m = materialIndexOf(triangle);\n\n // An unlit material emits its colour as the camera would see it, so a bounce ray finds what a light sample counted.\n if ((materials[m].flags & MATERIAL_UNLIT_LIGHT) != 0u) {\n var color = materials[m].color.rgb * sampleMap(materials[m].map, triangle, bary).rgb;\n\n if ((materials[m].flags & MATERIAL_VERTEX_COLORS) != 0u) {\n color = color * triangleColor(triangle, bary).rgb;\n }\n\n return color;\n }\n\n let map = sampleMap(materials[m].emissiveMap, triangle, bary);\n\n return materials[m].emissive.rgb * materials[m].emissive.w * map.rgb;\n}\n\n/** Three's material clipping planes: a point on the far side of one (or of all, with clipIntersection) is cut away. */\nfn isClipped(m: u32, point: vec3<f32>) -> bool {\n let count = materials[m].clipCount;\n\n if (count == 0u) {\n return false;\n }\n\n let intersection = (materials[m].flags & MATERIAL_CLIP_INTERSECTION) != 0u;\n var every = true;\n\n for (var i = 0u; i < count; i = i + 1u) {\n let plane = extraVec4(materials[m].clipStart + i * 4u);\n let outside = dot(plane.xyz, point) + plane.w < 0.0;\n\n if (outside && !intersection) {\n return true;\n }\n\n every = every && outside;\n }\n\n return intersection && every;\n}\n\n/** How large one pixel is at this point, in world units: what a one pixel wide line covers. */\nfn pixelFootprint(point: vec3<f32>) -> f32 {\n let scale = 2.0 / (frame.projection[1][1] * f32(frame.resolution.y));\n\n if (frame.cameraKind == 1u) {\n return scale;\n }\n\n return scale * max(-(frame.worldToCamera * vec4<f32>(point, 1.0)).z, 1e-6);\n}\n\nfn edgeDistance(point: vec3<f32>, a: vec3<f32>, b: vec3<f32>) -> f32 {\n let edge = b - a;\n\n return length(cross(point - a, edge)) / max(length(edge), 1e-20);\n}\n\n/** A wireframe draws only the edges of each triangle, one pixel wide as WebGL draws every line. */\nfn onWireframe(triangle: u32, point: vec3<f32>) -> bool {\n let a = triangleVertex(triangle, 0u);\n let b = triangleVertex(triangle, 1u);\n let c = triangleVertex(triangle, 2u);\n let nearest = min(edgeDistance(point, a, b), min(edgeDistance(point, b, c), edgeDistance(point, c, a)));\n\n return nearest <= 0.5 * pixelFootprint(point);\n}\n\n/** Three's diffuseColor.a: opacity, the colour map's alpha, the alpha map's green and the vertex alpha. */\nfn materialAlpha(m: u32, triangle: u32, bary: vec2<f32>) -> f32 {\n return materialAlphaFrom(m, triangle, bary, sampleMap(materials[m].map, triangle, bary));\n}\n\n/** The same, from the colour map's texel at this point. Multiplied in the order resolveSurface multiplies it. */\nfn materialAlphaFrom(m: u32, triangle: u32, bary: vec2<f32>, base: vec4<f32>) -> f32 {\n var alpha = materials[m].color.w * base.a * sampleMap(materials[m].alphaMap, triangle, bary).g;\n\n if ((materials[m].flags & MATERIAL_VERTEX_COLORS) != 0u) {\n alpha = alpha * triangleColor(triangle, bary).a;\n }\n\n return alpha;\n}\n\n/**\n * How much of the surface is there, from its alpha the way Three's chunks use it: alphaTest cuts, alphaHash keeps the\n * share, and only a transparent material with normal blending lets the rest through; an opaque one sets alpha to one.\n */\nfn coverageOf(m: u32, alpha: f32) -> f32 {\n if (materials[m].alphaTest > 0.0 && alpha < materials[m].alphaTest) {\n return 0.0;\n }\n\n var coverage = 1.0;\n\n if ((materials[m].flags & MATERIAL_ALPHA_HASH) != 0u) {\n coverage = clamp(alpha, 0.0, 1.0);\n }\n\n if ((materials[m].flags & MATERIAL_TRANSPARENT) != 0u && materials[m].blending == BLEND_NORMAL) {\n coverage = coverage * clamp(alpha, 0.0, 1.0);\n }\n\n return coverage;\n}\n\n/** Barycentrics on the triangle's plane of a ray, extrapolated past its edges: where a neighbouring pixel lands. */\nfn planeBarycentric(triangle: u32, origin: vec3<f32>, direction: vec3<f32>, fallback: vec2<f32>) -> vec2<f32> {\n let a = triangleVertex(triangle, 0u);\n let e1 = triangleVertex(triangle, 1u) - a;\n let e2 = triangleVertex(triangle, 2u) - a;\n let n = cross(e1, e2);\n let denominator = dot(n, direction);\n\n if (abs(denominator) < 1e-20) {\n return fallback;\n }\n\n let p = origin + direction * (dot(n, a - origin) / denominator) - a;\n let d00 = dot(e1, e1);\n let d01 = dot(e1, e2);\n let d11 = dot(e2, e2);\n let d20 = dot(p, e1);\n let d21 = dot(p, e2);\n let det = d00 * d11 - d01 * d01;\n\n if (abs(det) < 1e-30) {\n return fallback;\n }\n\n return vec2<f32>((d11 * d20 - d01 * d21) / det, (d00 * d21 - d01 * d20) / det);\n}\n\n/** The camera ray through a point given in normalized device coordinates: origin on the near plane, and its length. */\nfn ndcRay(ndc: vec2<f32>) -> array<vec4<f32>, 2> {\n let nearView = frame.inverseProjection * vec4<f32>(ndc, -1.0, 1.0);\n let farView = frame.inverseProjection * vec4<f32>(ndc, 1.0, 1.0);\n let near = (frame.cameraToWorld * vec4<f32>(nearView.xyz / nearView.w, 1.0)).xyz;\n let far = (frame.cameraToWorld * vec4<f32>(farView.xyz / farView.w, 1.0)).xyz;\n let span = far - near;\n let extent = max(length(span), 1e-20);\n\n return array<vec4<f32>, 2>(vec4<f32>(near, 0.0), vec4<f32>(span / extent, extent));\n}\n\n/** What a fragment shader knows about the point it runs at, in GL's own terms. */\nfn shaderInputAt(m: u32, triangle: u32, bary: vec2<f32>, direction: vec3<f32>) -> ShaderInput {\n var input: ShaderInput;\n let point = trianglePointAt(triangle, bary);\n let view = frame.worldToCamera * vec4<f32>(point, 1.0);\n let clip = frame.projection * view;\n let w = select(clip.w, 1e-20, abs(clip.w) < 1e-20);\n let ndc = clip.xyz / w;\n let size = vec2<f32>(frame.resolution);\n let pixel = (ndc.xy * 0.5 + 0.5) * size;\n let right = ndcRay(vec2<f32>(ndc.x + 2.0 / size.x, ndc.y));\n let above = ndcRay(vec2<f32>(ndc.x, ndc.y + 2.0 / size.y));\n\n input.data = materials[m].shaderData;\n input.material = m;\n input.triangle = triangle;\n input.frontFacing = isFrontFace(triangle, direction);\n input.bary = bary;\n input.baryDx = planeBarycentric(triangle, right[0].xyz, right[1].xyz, bary);\n input.baryDy = planeBarycentric(triangle, above[0].xyz, above[1].xyz, bary);\n input.fragCoord = vec4<f32>(pixel, ndc.z * 0.5 + 0.5, 1.0 / w);\n let uv = triangleUv(triangle, bary, 0u);\n input.uv = uv;\n input.fragColor = vec4<f32>(0.0, 0.0, 0.0, 1.0);\n // A point's quad carries gl_PointCoord in its first UV set, with v running up as a texture's does.\n input.pointCoord = vec2<f32>(uv.x, 1.0 - uv.y);\n input.direction = direction;\n input.diffuseColor = vec4<f32>(1.0);\n input.normal = vec3<f32>(0.0, 0.0, 1.0);\n input.geometryNormal = vec3<f32>(0.0, 0.0, 1.0);\n input.roughness = 1.0;\n input.metalness = 0.0;\n input.emissive = vec3<f32>(0.0);\n input.viewPosition = -view.xyz;\n\n return input;\n}\n\n/** World to view space for a direction, which is the space Three's shaders keep their normals in. */\nfn toView(direction: vec3<f32>) -> vec3<f32> {\n return normalize((frame.worldToCamera * vec4<f32>(direction, 0.0)).xyz);\n}\n\nfn toWorld(direction: vec3<f32>) -> vec3<f32> {\n return normalize((frame.cameraToWorld * vec4<f32>(direction, 0.0)).xyz);\n}\n\n/**\n * How much of the surface covers this point for a shadow ray: the same alpha, cut, clipping and wireframe the camera\n * sees, and a shader's own discard. Blending other than normal is handled by the caller.\n */\nfn coverageAt(triangle: u32, bary: vec2<f32>, direction: vec3<f32>) -> f32 {\n let m = materialIndexOf(triangle);\n let flags = materials[m].flags;\n\n if (materials[m].clipCount > 0u || (flags & MATERIAL_WIREFRAME) != 0u) {\n let point = trianglePointAt(triangle, bary);\n\n if (isClipped(m, point)) {\n return 0.0;\n }\n\n if ((flags & MATERIAL_WIREFRAME) != 0u && !onWireframe(triangle, point)) {\n return 0.0;\n }\n }\n\n var alpha = materialAlpha(m, triangle, bary);\n\n if (materials[m].program != NO_PROGRAM) {\n var input = shaderInputAt(m, triangle, bary, direction);\n input.diffuseColor = vec4<f32>(materials[m].color.rgb, alpha);\n let output = runProgram(materials[m].program, input);\n\n if (output.discarded) {\n return 0.0;\n }\n\n alpha = select(output.color.a, output.diffuseColor.a, (flags & MATERIAL_PATCHED) != 0u);\n }\n\n return coverageOf(m, alpha);\n}\n\n/** A tangent frame from the triangle's own UVs, which is what Three's tangents amount to for a flat triangle. */\nstruct TangentFrame {\n tangent: vec3<f32>,\n bitangent: vec3<f32>,\n valid: bool,\n};\n\nfn tangentFrame(triangle: u32, channel: u32, normal: vec3<f32>) -> TangentFrame {\n var tangents: TangentFrame;\n tangents.valid = false;\n\n let p0 = triangleVertex(triangle, 0u);\n let edge1 = triangleVertex(triangle, 1u) - p0;\n let edge2 = triangleVertex(triangle, 2u) - p0;\n let uv0 = attributeUv(triangle, 0u, channel);\n let delta1 = attributeUv(triangle, 1u, channel) - uv0;\n let delta2 = attributeUv(triangle, 2u, channel) - uv0;\n let determinant = delta1.x * delta2.y - delta2.x * delta1.y;\n\n // A triangle with no UV area has no tangent frame to offer.\n if (abs(determinant) < 1e-16) {\n let basis = orthonormalBasis(normal);\n tangents.tangent = basis[0];\n tangents.bitangent = basis[1];\n\n return tangents;\n }\n\n let raw = (edge1 * delta2.y - edge2 * delta1.y) / determinant;\n // Made perpendicular to the shading normal, so a map tilts the interpolated normal rather than the flat one.\n let tangent = normalize(raw - normal * dot(normal, raw));\n\n if (!all(tangent == tangent)) {\n let basis = orthonormalBasis(normal);\n tangents.tangent = basis[0];\n tangents.bitangent = basis[1];\n\n return tangents;\n }\n\n tangents.tangent = tangent;\n tangents.bitangent = cross(normal, tangent) * select(-1.0, 1.0, determinant >= 0.0);\n tangents.valid = true;\n\n return tangents;\n}\n\n/** A tangent space normal map over a normal, scaled the way Three's normalScale scales it. */\nfn tangentNormal(index: u32, triangle: u32, bary: vec2<f32>, normal: vec3<f32>, scale: vec2<f32>) -> vec3<f32> {\n if (index == NO_TEXTURE) {\n return normal;\n }\n\n let channel = textureInfo(index).channel;\n let tangents = tangentFrame(triangle, channel, normal);\n\n if (!tangents.valid) {\n return normal;\n }\n\n let texel = sampleTextureAt(index, triangleUv(triangle, bary, channel)).xyz * 2.0 - 1.0;\n let mapped = normalize(\n tangents.tangent * (texel.x * scale.x)\n + tangents.bitangent * (texel.y * scale.y)\n + normal * texel.z);\n\n return select(mapped, normal, !all(mapped == mapped));\n}\n\n/** The normal the material asks for: an object space or tangent space normal map, or else a bump map. */\nfn mappedNormal(m: u32, triangle: u32, bary: vec2<f32>, normal: vec3<f32>) -> vec3<f32> {\n let normalMap = materials[m].normalMap;\n\n if (normalMap != NO_TEXTURE && (materials[m].flags & MATERIAL_OBJECT_NORMAL_MAP) != 0u) {\n let texel = sampleMap(normalMap, triangle, bary).xyz * 2.0 - 1.0;\n let world = normalize(vec3<f32>(\n dot(materials[m].normalRow0.xyz, texel),\n dot(materials[m].normalRow1.xyz, texel),\n dot(materials[m].normalRow2.xyz, texel)));\n\n // Seen from behind, a double sided surface turns its map around with it.\n return select(world, -world, dot(world, normal) < 0.0);\n }\n\n if (normalMap != NO_TEXTURE) {\n return tangentNormal(normalMap, triangle, bary, normal, vec2<f32>(materials[m].normalScaleX, materials[m].normalScaleY));\n }\n\n let bumpMap = materials[m].bumpMap;\n\n if (bumpMap != NO_TEXTURE) {\n // The CPU renderer's bump: the height's change over one texel, along the tangent frame of the map's UVs.\n let info = textureInfo(bumpMap);\n let channel = info.channel;\n let tangents = tangentFrame(triangle, channel, normal);\n let uv = triangleUv(triangle, bary, channel);\n let du = 1.0 / f32(max(info.size.x, 1u));\n let dv = 1.0 / f32(max(info.size.y, 1u));\n let scale = materials[m].bumpScale;\n let height = sampleTextureAt(bumpMap, uv).x;\n let dx = (sampleTextureAt(bumpMap, uv + vec2<f32>(du, 0.0)).x - height) * scale;\n let dy = (sampleTextureAt(bumpMap, uv + vec2<f32>(0.0, dv)).x - height) * scale;\n let bumped = normalize(normal - (tangents.tangent * dx + tangents.bitangent * dy));\n\n return select(bumped, normal, !all(bumped == bumped));\n }\n\n return normal;\n}\n\n/** The interpolated vertex normal as the mesh authored it, pointing out of a closed volume. */\nfn authoredNormal(triangle: u32, bary: vec2<f32>) -> vec3<f32> {\n let base = triangle * 9u;\n let n0 = vec3<f32>(attributes[base], attributes[base + 1u], attributes[base + 2u]);\n let n1 = vec3<f32>(attributes[base + 3u], attributes[base + 4u], attributes[base + 5u]);\n let n2 = vec3<f32>(attributes[base + 6u], attributes[base + 7u], attributes[base + 8u]);\n\n return normalize(n0 * (1.0 - bary.x - bary.y) + n1 * bary.x + n2 * bary.y);\n}\n\n/** The interpolated vertex normal, or the face's for flat shading, turned to face the ray. */\nfn interpolatedNormal(m: u32, triangle: u32, bary: vec2<f32>, direction: vec3<f32>) -> vec3<f32> {\n var normal = authoredNormal(triangle, bary);\n\n if ((materials[m].flags & MATERIAL_FLAT) != 0u || !all(normal == normal)) {\n normal = triangleNormal(triangle);\n }\n\n return select(normal, -normal, dot(normal, direction) > 0.0);\n}\n\n/** Three's transmission at this point: the factor, its map's red channel, and none of it on metal. */\nfn transmissionAt(m: u32, triangle: u32, bary: vec2<f32>, metalness: f32) -> f32 {\n if (materials[m].transmission <= 0.0) {\n return 0.0;\n }\n\n let map = sampleMap(materials[m].transmissionMap, triangle, bary).r;\n\n return clamp(materials[m].transmission * map, 0.0, 1.0) * (1.0 - metalness);\n}\n\n/** Beer-Lambert: the colour reached at the attenuation distance fixes how fast each channel fades. */\nfn absorptionOf(m: u32) -> vec3<f32> {\n let attenuation = materials[m].attenuation;\n\n if (attenuation.w <= 0.0) {\n return vec3<f32>(0.0);\n }\n\n return -log(max(attenuation.rgb, vec3<f32>(1e-6))) / attenuation.w;\n}\n\n/** Three's evalSensitivity: the XYZ response of a thin film, Fourier-fitted, in linear sRGB. */\nfn filmSensitivity(opd: f32, shift: vec3<f32>) -> vec3<f32> {\n let phase = 2.0 * PI * opd * 1.0e-9;\n let value = vec3<f32>(5.4856e-13, 4.4201e-13, 5.2481e-13);\n let position = vec3<f32>(1.6810e+06, 1.7953e+06, 2.2084e+06);\n let variance = vec3<f32>(4.3278e+09, 9.3046e+09, 6.6121e+09);\n var xyz = value * sqrt(2.0 * PI * variance) * cos(position * phase + shift) * exp(-phase * phase * variance);\n\n xyz.x = xyz.x + 9.7470e-14 * sqrt(2.0 * PI * 4.5282e+09) * cos(2.2399e+06 * phase + shift.x)\n * exp(-4.5282e+09 * phase * phase);\n xyz = xyz / 1.0685e-7;\n\n return mat3x3<f32>(\n vec3<f32>(3.2404542, -0.9692660, 0.0556434),\n vec3<f32>(-1.5371385, 1.8760108, -0.2040259),\n vec3<f32>(-0.4985314, 0.0415560, 1.0572252)) * xyz;\n}\n\nfn schlick3(f0: vec3<f32>, f90: f32, cosine: f32) -> vec3<f32> {\n let t = 1.0 - cosine;\n let k = t * t * t * t * t;\n\n return f0 + (vec3<f32>(f90) - f0) * k;\n}\n\n/** Three's evalIridescence (Belcour and Barla 2017): the Fresnel of a thin film over a base of reflectance baseF0. */\nfn evalIridescence(filmIor: f32, cosTheta1: f32, thickness: f32, baseF0: vec3<f32>) -> vec3<f32> {\n let ior = mix(1.0, filmIor, smoothstep(0.0, 0.03, thickness));\n let sinTheta2Sq = (1.0 / ior) * (1.0 / ior) * (1.0 - cosTheta1 * cosTheta1);\n let cosTheta2Sq = 1.0 - sinTheta2Sq;\n\n if (cosTheta2Sq < 0.0) {\n return vec3<f32>(1.0);\n }\n\n let cosTheta2 = sqrt(cosTheta2Sq);\n let r0 = ((ior - 1.0) / (ior + 1.0)) * ((ior - 1.0) / (ior + 1.0));\n let r12 = r0 + (1.0 - r0) * pow(1.0 - cosTheta1, 5.0);\n let t121 = 1.0 - r12;\n let phi12 = select(0.0, PI, ior < 1.0);\n let phi21 = PI - phi12;\n let root = sqrt(clamp(baseF0, vec3<f32>(0.0), vec3<f32>(0.9999)));\n let baseIor = (vec3<f32>(1.0) + root) / (vec3<f32>(1.0) - root);\n let r1 = ((baseIor - vec3<f32>(ior)) / (baseIor + vec3<f32>(ior))) * ((baseIor - vec3<f32>(ior)) / (baseIor + vec3<f32>(ior)));\n let r23 = schlick3(r1, 1.0, cosTheta2);\n let phi23 = select(vec3<f32>(0.0), vec3<f32>(PI), baseIor < vec3<f32>(ior));\n let opd = 2.0 * ior * thickness * cosTheta2;\n let phi = vec3<f32>(phi21) + phi23;\n let r123 = clamp(r12 * r23, vec3<f32>(1e-5), vec3<f32>(0.9999));\n let r123Root = sqrt(r123);\n let rs = t121 * t121 * r23 / (vec3<f32>(1.0) - r123);\n var intensity = vec3<f32>(r12) + rs;\n var cm = rs - vec3<f32>(t121);\n\n for (var m = 1; m <= 2; m = m + 1) {\n cm = cm * r123Root;\n intensity = intensity + cm * 2.0 * filmSensitivity(f32(m) * opd, f32(m) * phi);\n }\n\n return max(intensity, vec3<f32>(0.0));\n}\n\n/** Three's toon ramp: the gradient map across dot(n, l) from -1 to 1, or a single step at 0.7 without one. */\nfn toonRamp(gradientMap: u32, cosine: f32) -> f32 {\n let coordinate = cosine * 0.5 + 0.5;\n\n if (gradientMap == NO_TEXTURE) {\n return select(0.7, 1.0, coordinate >= 0.7);\n }\n\n return sampleTextureRaw(gradientMap, vec2<f32>(coordinate, 0.0)).r;\n}\n\n/**\n * Whether a material's coverage can be told from its maps alone, before the rest of the surface is read: no shader that\n * might rewrite the alpha or discard, normal blending, and something that makes it partial at all.\n */\nfn coverageFirst(m: u32) -> bool {\n let flags = materials[m].flags;\n let blending = materials[m].blending;\n\n return materials[m].program == NO_PROGRAM\n && (blending == BLEND_NORMAL || blending == BLEND_NONE)\n && (materials[m].alphaTest > 0.0 || (flags & (MATERIAL_ALPHA_HASH | MATERIAL_TRANSPARENT)) != 0u);\n}\n\n/** Everything the lobes need about one point of one triangle. */\nfn resolveSurface(triangle: u32, bary: vec2<f32>, direction: vec3<f32>) -> Surface {\n let m = materialIndexOf(triangle);\n\n return resolveSurfaceFrom(triangle, bary, direction, sampleMap(materials[m].map, triangle, bary));\n}\n\n/** The same, from the colour map's texel at this point, for a caller that already read it. */\nfn resolveSurfaceFrom(triangle: u32, bary: vec2<f32>, direction: vec3<f32>, base: vec4<f32>) -> Surface {\n let m = materialIndexOf(triangle);\n let flags = materials[m].flags;\n let kind = materials[m].kind;\n let facing = interpolatedNormal(m, triangle, bary, direction);\n let view = -direction;\n var surface: Surface;\n\n surface.material = m;\n surface.flags = flags;\n surface.kind = kind;\n surface.blending = materials[m].blending;\n surface.facing = facing;\n surface.front = dot(authoredNormal(triangle, bary), direction) < 0.0;\n surface.normal = mappedNormal(m, triangle, bary, facing);\n\n // A normal map may tilt past the horizon, where the surface would be lit from behind itself.\n if (dot(surface.normal, view) <= 0.0) {\n surface.normal = facing;\n }\n\n var albedo = materials[m].color.rgb * base.rgb;\n var alpha = materials[m].color.w * base.a * sampleMap(materials[m].alphaMap, triangle, bary).g;\n\n if ((flags & MATERIAL_VERTEX_COLORS) != 0u) {\n let color = triangleColor(triangle, bary);\n albedo = albedo * color.rgb;\n alpha = alpha * color.a;\n }\n\n var roughness = materials[m].specular.w * sampleMap(materials[m].roughnessMap, triangle, bary).g;\n var metalness = materials[m].metalness * sampleMap(materials[m].metalnessMap, triangle, bary).b;\n var emissive = vec3<f32>(0.0);\n\n // An unlit light's colour is added as what it shows, below; emissionAt gives the same colour to light samples.\n if ((flags & MATERIAL_UNLIT_LIGHT) == 0u) {\n emissive = emissionAt(triangle, bary);\n }\n\n surface.opacity = 1.0;\n\n // A built-in material's hooks run on its values before lighting, in Three's view space; a shader material's output\n // is the colour itself.\n if (materials[m].program != NO_PROGRAM) {\n var input = shaderInputAt(m, triangle, bary, direction);\n input.diffuseColor = vec4<f32>(albedo, alpha);\n input.normal = toView(surface.normal);\n input.geometryNormal = toView(facing);\n input.roughness = roughness;\n input.metalness = metalness;\n input.emissive = emissive;\n let output = runProgram(materials[m].program, input);\n\n if (output.discarded) {\n surface.opacity = 0.0;\n }\n\n if ((flags & MATERIAL_PATCHED) != 0u) {\n albedo = output.diffuseColor.rgb;\n alpha = output.diffuseColor.a;\n roughness = output.roughness;\n metalness = output.metalness;\n emissive = output.emissive;\n let normal = toWorld(output.normal);\n\n if (all(normal == normal)) {\n surface.normal = select(normal, -normal, dot(normal, view) < 0.0);\n }\n } else {\n albedo = output.color.rgb;\n alpha = output.color.a;\n }\n }\n\n surface.opacity = surface.opacity * coverageOf(m, alpha);\n surface.alpha = alpha;\n surface.albedo = albedo;\n surface.roughness = clamp(roughness, 0.0525, 1.0);\n surface.metalness = clamp(metalness, 0.0, 1.0);\n surface.emissive = emissive;\n surface.transmission = transmissionAt(m, triangle, bary, surface.metalness);\n surface.ior = max(materials[m].ior, 1.0);\n surface.thickness = materials[m].thickness * sampleMap(materials[m].thicknessMap, triangle, bary).g;\n surface.dispersion = materials[m].dispersion;\n surface.subsurface = select(0.0, materials[m].subsurface.w, frame.subsurfaceEnabled != 0u);\n surface.absorption = absorptionOf(m);\n surface.shininess = materials[m].shininess;\n surface.specularStrength = sampleMap(materials[m].specularMap, triangle, bary).r;\n surface.gradientMap = materials[m].gradientMap;\n surface.envMap = NO_TEXTURE;\n surface.envMapIntensity = materials[m].envMapIntensity;\n surface.legacyAmount = 0.0;\n surface.legacyEnv = vec3<f32>(0.0);\n surface.combine = materials[m].combine;\n surface.lightMap = vec3<f32>(0.0);\n surface.clearcoat = 0.0;\n surface.iridescence = 0.0;\n surface.anisotropy = 0.0;\n surface.sheenColor = vec3<f32>(0.0);\n surface.specularColor = materials[m].specular.rgb;\n surface.specularF90 = 1.0;\n\n if ((flags & MATERIAL_PBR) != 0u) {\n if ((flags & MATERIAL_SPECULAR) != 0u) {\n // A physical material: the index of refraction, the specular colour and intensity and their maps.\n let intensity = materials[m].specularIntensity * sampleMap(materials[m].specularIntensityMap, triangle, bary).a;\n let color = materials[m].specular.rgb * sampleMap(materials[m].specularColorMap, triangle, bary).rgb;\n\n surface.specularColor = min(materials[m].dielectric * color, vec3<f32>(1.0)) * intensity;\n surface.specularF90 = mix(intensity, 1.0, surface.metalness);\n } else {\n // Three's standard material has no index of refraction and reflects 0.04.\n surface.specularColor = vec3<f32>(0.04);\n }\n\n surface.envMap = materials[m].envMap;\n\n if (materials[m].clearcoat > 0.0) {\n surface.clearcoat = clamp(materials[m].clearcoat * sampleMap(materials[m].clearcoatMap, triangle, bary).r, 0.0, 1.0);\n surface.clearcoatRoughness = clamp(\n materials[m].clearcoatRoughness * sampleMap(materials[m].clearcoatRoughnessMap, triangle, bary).g, 0.0525, 1.0);\n // The coat ignores the base's normal map: it has its own, over the interpolated normal.\n surface.clearcoatNormal = tangentNormal(materials[m].clearcoatNormalMap, triangle, bary, facing,\n vec2<f32>(materials[m].clearcoatNormalScaleX, materials[m].clearcoatNormalScaleY));\n\n if (dot(surface.clearcoatNormal, view) <= 0.0) {\n surface.clearcoatNormal = facing;\n }\n }\n\n if (any(materials[m].sheen.rgb > vec3<f32>(0.0))) {\n let map = sampleMap(materials[m].sheenRoughnessMap, triangle, bary).a;\n surface.sheenColor = materials[m].sheen.rgb * sampleMap(materials[m].sheenColorMap, triangle, bary).rgb;\n surface.sheenRoughness = clamp(materials[m].sheen.w, 0.0001, 1.0) * map;\n }\n\n if (materials[m].iridescence > 0.0) {\n var thickness = materials[m].iridescenceThicknessMax;\n\n if (materials[m].iridescenceThicknessMap != NO_TEXTURE) {\n thickness = mix(materials[m].iridescenceThicknessMin, materials[m].iridescenceThicknessMax,\n sampleMap(materials[m].iridescenceThicknessMap, triangle, bary).g);\n }\n\n if (thickness > 0.0) {\n surface.iridescence = clamp(\n materials[m].iridescence * sampleMap(materials[m].iridescenceMap, triangle, bary).r, 0.0, 1.0);\n\n let nv = clamp(dot(surface.normal, view), 0.0, 1.0);\n surface.iridescenceFresnel = mix(\n evalIridescence(materials[m].iridescenceIor, nv, thickness, surface.specularColor),\n evalIridescence(materials[m].iridescenceIor, nv, thickness, albedo),\n surface.metalness);\n }\n }\n\n if (materials[m].anisotropy != 0.0) {\n let rotation = materials[m].anisotropyRotation;\n var vector = vec2<f32>(cos(rotation), sin(rotation)) * materials[m].anisotropy;\n let channel = select(0u, textureInfo(materials[m].anisotropyMap).channel, materials[m].anisotropyMap != NO_TEXTURE);\n let tangents = tangentFrame(triangle, channel, surface.normal);\n\n if (materials[m].anisotropyMap != NO_TEXTURE) {\n let polar = sampleMap(materials[m].anisotropyMap, triangle, bary).rgb;\n let turn = mat2x2<f32>(vector.x, vector.y, -vector.y, vector.x);\n vector = turn * normalize(2.0 * polar.rg - vec2<f32>(1.0)) * polar.b;\n }\n\n let strength = length(vector);\n let along = select(vector / max(strength, 1e-20), vec2<f32>(1.0, 0.0), strength == 0.0);\n\n surface.anisotropy = clamp(strength, 0.0, 1.0);\n surface.alphaT = mix(surface.roughness * surface.roughness, 1.0, surface.anisotropy * surface.anisotropy);\n surface.anisotropyT = tangents.tangent * along.x + tangents.bitangent * along.y;\n surface.anisotropyB = tangents.bitangent * along.x - tangents.tangent * along.y;\n }\n } else if (materials[m].envMap != NO_TEXTURE\n && (kind == KIND_BASIC || kind == KIND_LAMBERT || kind == KIND_PHONG)) {\n // Basic, Lambert and Phong blend their own map over the lit colour, mirrored or bent the way the map says.\n let info = textureInfo(materials[m].envMap);\n let bent = refract(direction, surface.normal, materials[m].refractionRatio);\n let lookup = select(reflect(direction, surface.normal), bent, (info.flags & 16u) != 0u && any(bent != vec3<f32>(0.0)));\n\n surface.legacyEnv = sampleEquirect(materials[m].envMap, lookup).rgb * materials[m].envMapIntensity;\n surface.legacyAmount = clamp(materials[m].reflectivity * surface.specularStrength, 0.0, 1.0);\n }\n\n if (materials[m].lightMap != NO_TEXTURE) {\n let baked = sampleMap(materials[m].lightMap, triangle, bary).rgb * materials[m].lightMapIntensity;\n surface.lightMap = baked * albedo * (1.0 - surface.metalness) / PI;\n }\n\n // A material Three does not light reads as its own colour, which in a path tracer is the same as emitting it.\n if ((flags & MATERIAL_LIT) == 0u) {\n var color = albedo;\n\n if (kind == KIND_NORMAL) {\n color = toView(surface.normal) * 0.5 + 0.5;\n } else if (kind == KIND_DEPTH) {\n let clip = frame.projection * (frame.worldToCamera * vec4<f32>(trianglePointAt(triangle, bary), 1.0));\n color = vec3<f32>(1.0 - (clip.z / clip.w * 0.5 + 0.5));\n } else if (kind == KIND_MATCAP) {\n let point = trianglePointAt(triangle, bary);\n let viewDirection = normalize(-(frame.worldToCamera * vec4<f32>(point, 1.0)).xyz);\n let x = normalize(vec3<f32>(viewDirection.z, 0.0, -viewDirection.x));\n let y = cross(viewDirection, x);\n let normal = toView(surface.normal);\n let uv = vec2<f32>(dot(x, normal), dot(y, normal)) * 0.495 + 0.5;\n var matcap = vec3<f32>(mix(0.2, 0.8, uv.y));\n\n if (materials[m].matcap != NO_TEXTURE) {\n matcap = sampleTextureRaw(materials[m].matcap, uv).rgb;\n }\n\n color = albedo * matcap;\n } else if (kind == KIND_BASIC && materials[m].lightMap != NO_TEXTURE) {\n // A basic material with a light map shows the map's light instead of full brightness.\n color = albedo * sampleMap(materials[m].lightMap, triangle, bary).rgb * materials[m].lightMapIntensity / PI;\n }\n\n if (surface.legacyAmount > 0.0) {\n let amount = surface.legacyAmount;\n\n if (surface.combine == 1u) {\n color = mix(color, surface.legacyEnv, amount);\n } else if (surface.combine == 2u) {\n color = color + surface.legacyEnv * amount;\n } else {\n color = mix(color, color * surface.legacyEnv, amount);\n }\n\n surface.legacyAmount = 0.0;\n }\n\n surface.emissive = surface.emissive + color;\n surface.lightMap = vec3<f32>(0.0);\n }\n\n return surface;\n}\n";
|
|
9
|
+
export declare const SURFACE_WGSL = "\nstruct Surface {\n // The shading normal, maps applied, facing the ray.\n normal: vec3<f32>,\n albedo: vec3<f32>,\n // What the surface radiates by itself: its emission, or the whole colour of a material Three does not light.\n emissive: vec3<f32>,\n // The dielectric's reflectance at normal incidence and at grazing angles, before metalness turns it to the albedo.\n specularColor: vec3<f32>,\n specularF90: f32,\n roughness: f32,\n metalness: f32,\n // How much of the surface actually covers this point: a cutout, a transparency or a discarded fragment.\n opacity: f32,\n // Three's diffuseColor.a, which blending other than normal weighs the surface by.\n alpha: f32,\n flags: u32,\n kind: u32,\n // Share of the diffuse layer that lets light through, with metal already taken out of it.\n transmission: f32,\n ior: f32,\n thickness: f32,\n dispersion: f32,\n // What a unit of distance inside the volume absorbs, per channel: zero for a volume that never darkens.\n absorption: vec3<f32>,\n // The interpolated normal facing the ray, before any map: thin walls, shadow rays and the clearcoat read this one.\n facing: vec3<f32>,\n // Whether the ray arrived from the side the normals point to, which is the outside of a closed volume.\n front: bool,\n clearcoat: f32,\n clearcoatRoughness: f32,\n clearcoatNormal: vec3<f32>,\n sheenColor: vec3<f32>,\n sheenRoughness: f32,\n iridescence: f32,\n iridescenceFresnel: vec3<f32>,\n // Anisotropic GGX: its strength, the roughness along the tangent, and the tangent frame it stretches along.\n anisotropy: f32,\n alphaT: f32,\n anisotropyT: vec3<f32>,\n anisotropyB: vec3<f32>,\n shininess: f32,\n // Phong's specular map, which scales its highlight.\n specularStrength: f32,\n gradientMap: u32,\n // The material's own environment map, which the paths leaving it see instead of the scene's.\n envMap: u32,\n envMapIntensity: f32,\n // Basic, Lambert and Phong blend their environment map over the lit colour: what the map shows here, and how much.\n legacyEnv: vec3<f32>,\n legacyAmount: f32,\n combine: u32,\n // Light a light map bakes into this point, which only the camera sees: the path traces the rest itself.\n lightMap: vec3<f32>,\n blending: u32,\n material: u32,\n // Share of the diffuse layer that scatters inside the material instead of at its surface.\n subsurface: f32,\n // What a translucent surface lets through to its far side, diffusely: grass blades. Zero for everything else.\n translucent: vec3<f32>,\n};\n\n/** Barycentric weights of the two trailing vertices, for a point drawn uniformly over a triangle's area. */\nfn triangleBarycentric(u: vec2<f32>) -> vec2<f32> {\n let root = sqrt(u.x);\n\n return vec2<f32>(1.0 - root, u.y * root);\n}\n\nfn trianglePointAt(triangle: u32, bary: vec2<f32>) -> vec3<f32> {\n return triangleVertex(triangle, 0u) * (1.0 - bary.x - bary.y)\n + triangleVertex(triangle, 1u) * bary.x\n + triangleVertex(triangle, 2u) * bary.y;\n}\n\nfn triangleUv(triangle: u32, bary: vec2<f32>, channel: u32) -> vec2<f32> {\n let corners = triangleCorners(triangle);\n\n return vertexUv(corners.x, channel) * (1.0 - bary.x - bary.y)\n + vertexUv(corners.y, channel) * bary.x\n + vertexUv(corners.z, channel) * bary.y;\n}\n\nfn triangleColor(triangle: u32, bary: vec2<f32>) -> vec4<f32> {\n let corners = triangleCorners(triangle);\n\n return vertexColor(corners.x) * (1.0 - bary.x - bary.y)\n + vertexColor(corners.y) * bary.x\n + vertexColor(corners.z) * bary.y;\n}\n\n/** A map slot, sampled through the UV set the texture asks for. Missing maps read as one, so a multiply is always safe. */\nfn sampleMap(index: u32, triangle: u32, bary: vec2<f32>) -> vec4<f32> {\n if (index == NO_TEXTURE) {\n return vec4<f32>(1.0);\n }\n\n return sampleTextureAt(index, triangleUv(triangle, bary, textureInfo(index).channel));\n}\n\n/** Whether the ray sees the side Three calls the front: the winding, which packing keeps counter-clockwise. */\nfn isFrontFace(triangle: u32, direction: vec3<f32>) -> bool {\n return dot(triangleNormal(triangle), direction) < 0.0;\n}\n\n/** Three culls the side a material does not draw. */\nfn isCulled(material: u32, triangle: u32, direction: vec3<f32>) -> bool {\n let side = materials[material].side;\n let front = isFrontFace(triangle, direction);\n\n return (side == SIDE_FRONT && !front) || (side == SIDE_BACK && front);\n}\n\n/** What the triangle radiates at this point, its emissive map included so direct and indirect light agree on it. */\nfn emissionAt(triangle: u32, bary: vec2<f32>) -> vec3<f32> {\n let m = materialIndexOf(triangle);\n\n // An unlit material emits its colour as the camera would see it, so a bounce ray finds what a light sample counted.\n if ((materials[m].flags & MATERIAL_UNLIT_LIGHT) != 0u) {\n var color = materials[m].color.rgb * sampleMap(materials[m].map, triangle, bary).rgb;\n\n if ((materials[m].flags & MATERIAL_VERTEX_COLORS) != 0u) {\n color = color * triangleColor(triangle, bary).rgb;\n }\n\n return color;\n }\n\n let map = sampleMap(materials[m].emissiveMap, triangle, bary);\n\n return materials[m].emissive.rgb * materials[m].emissive.w * map.rgb;\n}\n\n/** Three's material clipping planes: a point on the far side of one (or of all, with clipIntersection) is cut away. */\nfn isClipped(m: u32, point: vec3<f32>) -> bool {\n let count = materials[m].clipCount;\n\n if (count == 0u) {\n return false;\n }\n\n let intersection = (materials[m].flags & MATERIAL_CLIP_INTERSECTION) != 0u;\n var every = true;\n\n for (var i = 0u; i < count; i = i + 1u) {\n let plane = extraVec4(materials[m].clipStart + i * 4u);\n let outside = dot(plane.xyz, point) + plane.w < 0.0;\n\n if (outside && !intersection) {\n return true;\n }\n\n every = every && outside;\n }\n\n return intersection && every;\n}\n\n/** How large one pixel is at this point, in world units: what a one pixel wide line covers. */\nfn pixelFootprint(point: vec3<f32>) -> f32 {\n let scale = 2.0 / (frame.projection[1][1] * f32(frame.resolution.y));\n\n if (frame.cameraKind == 1u) {\n return scale;\n }\n\n return scale * max(-(frame.worldToCamera * vec4<f32>(point, 1.0)).z, 1e-6);\n}\n\nfn edgeDistance(point: vec3<f32>, a: vec3<f32>, b: vec3<f32>) -> f32 {\n let edge = b - a;\n\n return length(cross(point - a, edge)) / max(length(edge), 1e-20);\n}\n\n/** A wireframe draws only the edges of each triangle, one pixel wide as WebGL draws every line. */\nfn onWireframe(triangle: u32, point: vec3<f32>) -> bool {\n let a = triangleVertex(triangle, 0u);\n let b = triangleVertex(triangle, 1u);\n let c = triangleVertex(triangle, 2u);\n let nearest = min(edgeDistance(point, a, b), min(edgeDistance(point, b, c), edgeDistance(point, c, a)));\n\n return nearest <= 0.5 * pixelFootprint(point);\n}\n\n/** Three's diffuseColor.a: opacity, the colour map's alpha, the alpha map's green and the vertex alpha. */\nfn materialAlpha(m: u32, triangle: u32, bary: vec2<f32>) -> f32 {\n return materialAlphaFrom(m, triangle, bary, sampleMap(materials[m].map, triangle, bary));\n}\n\n/** The same, from the colour map's texel at this point. Multiplied in the order resolveSurface multiplies it. */\nfn materialAlphaFrom(m: u32, triangle: u32, bary: vec2<f32>, base: vec4<f32>) -> f32 {\n var alpha = materials[m].color.w * base.a * sampleMap(materials[m].alphaMap, triangle, bary).g;\n\n if ((materials[m].flags & MATERIAL_VERTEX_COLORS) != 0u) {\n alpha = alpha * triangleColor(triangle, bary).a;\n }\n\n return alpha;\n}\n\n/**\n * How much of the surface is there, from its alpha the way Three's chunks use it: alphaTest cuts, alphaHash keeps the\n * share, and only a transparent material with normal blending lets the rest through; an opaque one sets alpha to one.\n */\nfn coverageOf(m: u32, alpha: f32) -> f32 {\n if (materials[m].alphaTest > 0.0 && alpha < materials[m].alphaTest) {\n return 0.0;\n }\n\n var coverage = 1.0;\n\n if ((materials[m].flags & MATERIAL_ALPHA_HASH) != 0u) {\n coverage = clamp(alpha, 0.0, 1.0);\n }\n\n if ((materials[m].flags & MATERIAL_TRANSPARENT) != 0u && materials[m].blending == BLEND_NORMAL) {\n coverage = coverage * clamp(alpha, 0.0, 1.0);\n }\n\n return coverage;\n}\n\n/** Barycentrics on the triangle's plane of a ray, extrapolated past its edges: where a neighbouring pixel lands. */\nfn planeBarycentric(triangle: u32, origin: vec3<f32>, direction: vec3<f32>, fallback: vec2<f32>) -> vec2<f32> {\n let a = triangleVertex(triangle, 0u);\n let e1 = triangleVertex(triangle, 1u) - a;\n let e2 = triangleVertex(triangle, 2u) - a;\n let n = cross(e1, e2);\n let denominator = dot(n, direction);\n\n if (abs(denominator) < 1e-20) {\n return fallback;\n }\n\n let p = origin + direction * (dot(n, a - origin) / denominator) - a;\n let d00 = dot(e1, e1);\n let d01 = dot(e1, e2);\n let d11 = dot(e2, e2);\n let d20 = dot(p, e1);\n let d21 = dot(p, e2);\n let det = d00 * d11 - d01 * d01;\n\n if (abs(det) < 1e-30) {\n return fallback;\n }\n\n return vec2<f32>((d11 * d20 - d01 * d21) / det, (d00 * d21 - d01 * d20) / det);\n}\n\n/** The camera ray through a point given in normalized device coordinates: origin on the near plane, and its length. */\nfn ndcRay(ndc: vec2<f32>) -> array<vec4<f32>, 2> {\n let nearView = frame.inverseProjection * vec4<f32>(ndc, -1.0, 1.0);\n let farView = frame.inverseProjection * vec4<f32>(ndc, 1.0, 1.0);\n let near = (frame.cameraToWorld * vec4<f32>(nearView.xyz / nearView.w, 1.0)).xyz;\n let far = (frame.cameraToWorld * vec4<f32>(farView.xyz / farView.w, 1.0)).xyz;\n let span = far - near;\n let extent = max(length(span), 1e-20);\n\n return array<vec4<f32>, 2>(vec4<f32>(near, 0.0), vec4<f32>(span / extent, extent));\n}\n\n/** What a fragment shader knows about the point it runs at, in GL's own terms. */\nfn shaderInputAt(m: u32, triangle: u32, bary: vec2<f32>, direction: vec3<f32>) -> ShaderInput {\n var input: ShaderInput;\n let point = trianglePointAt(triangle, bary);\n let view = frame.worldToCamera * vec4<f32>(point, 1.0);\n let clip = frame.projection * view;\n let w = select(clip.w, 1e-20, abs(clip.w) < 1e-20);\n let ndc = clip.xyz / w;\n let size = vec2<f32>(frame.resolution);\n let pixel = (ndc.xy * 0.5 + 0.5) * size;\n let right = ndcRay(vec2<f32>(ndc.x + 2.0 / size.x, ndc.y));\n let above = ndcRay(vec2<f32>(ndc.x, ndc.y + 2.0 / size.y));\n\n input.data = materials[m].shaderData;\n input.material = m;\n input.triangle = triangle;\n input.frontFacing = isFrontFace(triangle, direction);\n input.bary = bary;\n input.baryDx = planeBarycentric(triangle, right[0].xyz, right[1].xyz, bary);\n input.baryDy = planeBarycentric(triangle, above[0].xyz, above[1].xyz, bary);\n input.fragCoord = vec4<f32>(pixel, ndc.z * 0.5 + 0.5, 1.0 / w);\n let uv = triangleUv(triangle, bary, 0u);\n input.uv = uv;\n input.fragColor = vec4<f32>(0.0, 0.0, 0.0, 1.0);\n // A point's quad carries gl_PointCoord in its first UV set, with v running up as a texture's does.\n input.pointCoord = vec2<f32>(uv.x, 1.0 - uv.y);\n input.direction = direction;\n input.diffuseColor = vec4<f32>(1.0);\n input.normal = vec3<f32>(0.0, 0.0, 1.0);\n input.geometryNormal = vec3<f32>(0.0, 0.0, 1.0);\n input.roughness = 1.0;\n input.metalness = 0.0;\n input.emissive = vec3<f32>(0.0);\n input.viewPosition = -view.xyz;\n\n return input;\n}\n\n/** World to view space for a direction, which is the space Three's shaders keep their normals in. */\nfn toView(direction: vec3<f32>) -> vec3<f32> {\n return normalize((frame.worldToCamera * vec4<f32>(direction, 0.0)).xyz);\n}\n\nfn toWorld(direction: vec3<f32>) -> vec3<f32> {\n return normalize((frame.cameraToWorld * vec4<f32>(direction, 0.0)).xyz);\n}\n\n/**\n * How much of the surface covers this point for a shadow ray: the same alpha, cut, clipping and wireframe the camera\n * sees, and a shader's own discard. Blending other than normal is handled by the caller.\n */\nfn coverageAt(triangle: u32, bary: vec2<f32>, direction: vec3<f32>) -> f32 {\n let m = materialIndexOf(triangle);\n let flags = materials[m].flags;\n\n if (materials[m].clipCount > 0u || (flags & MATERIAL_WIREFRAME) != 0u) {\n let point = trianglePointAt(triangle, bary);\n\n if (isClipped(m, point)) {\n return 0.0;\n }\n\n if ((flags & MATERIAL_WIREFRAME) != 0u && !onWireframe(triangle, point)) {\n return 0.0;\n }\n }\n\n var alpha = materialAlpha(m, triangle, bary);\n\n if (materials[m].program != NO_PROGRAM) {\n var input = shaderInputAt(m, triangle, bary, direction);\n input.diffuseColor = vec4<f32>(materials[m].color.rgb, alpha);\n let output = runProgram(materials[m].program, input);\n\n if (output.discarded) {\n return 0.0;\n }\n\n alpha = select(output.color.a, output.diffuseColor.a, (flags & MATERIAL_PATCHED) != 0u);\n }\n\n return coverageOf(m, alpha);\n}\n\n/** A tangent frame from the triangle's own UVs, which is what Three's tangents amount to for a flat triangle. */\nstruct TangentFrame {\n tangent: vec3<f32>,\n bitangent: vec3<f32>,\n valid: bool,\n};\n\nfn tangentFrame(triangle: u32, channel: u32, normal: vec3<f32>) -> TangentFrame {\n var tangents: TangentFrame;\n tangents.valid = false;\n\n let p0 = triangleVertex(triangle, 0u);\n let edge1 = triangleVertex(triangle, 1u) - p0;\n let edge2 = triangleVertex(triangle, 2u) - p0;\n let corners = triangleCorners(triangle);\n let uv0 = vertexUv(corners.x, channel);\n let delta1 = vertexUv(corners.y, channel) - uv0;\n let delta2 = vertexUv(corners.z, channel) - uv0;\n let determinant = delta1.x * delta2.y - delta2.x * delta1.y;\n\n // A triangle with no UV area has no tangent frame to offer.\n if (abs(determinant) < 1e-16) {\n let basis = orthonormalBasis(normal);\n tangents.tangent = basis[0];\n tangents.bitangent = basis[1];\n\n return tangents;\n }\n\n let raw = (edge1 * delta2.y - edge2 * delta1.y) / determinant;\n // Made perpendicular to the shading normal, so a map tilts the interpolated normal rather than the flat one.\n let tangent = normalize(raw - normal * dot(normal, raw));\n\n if (!all(tangent == tangent)) {\n let basis = orthonormalBasis(normal);\n tangents.tangent = basis[0];\n tangents.bitangent = basis[1];\n\n return tangents;\n }\n\n tangents.tangent = tangent;\n tangents.bitangent = cross(normal, tangent) * select(-1.0, 1.0, determinant >= 0.0);\n tangents.valid = true;\n\n return tangents;\n}\n\n/** A tangent space normal map over a normal, scaled the way Three's normalScale scales it. */\nfn tangentNormal(index: u32, triangle: u32, bary: vec2<f32>, normal: vec3<f32>, scale: vec2<f32>) -> vec3<f32> {\n if (index == NO_TEXTURE) {\n return normal;\n }\n\n let channel = textureInfo(index).channel;\n let tangents = tangentFrame(triangle, channel, normal);\n\n if (!tangents.valid) {\n return normal;\n }\n\n let texel = sampleTextureAt(index, triangleUv(triangle, bary, channel)).xyz * 2.0 - 1.0;\n let mapped = normalize(\n tangents.tangent * (texel.x * scale.x)\n + tangents.bitangent * (texel.y * scale.y)\n + normal * texel.z);\n\n return select(mapped, normal, !all(mapped == mapped));\n}\n\n/** The normal the material asks for: an object space or tangent space normal map, or else a bump map. */\nfn mappedNormal(m: u32, triangle: u32, bary: vec2<f32>, normal: vec3<f32>) -> vec3<f32> {\n let normalMap = materials[m].normalMap;\n\n if (normalMap != NO_TEXTURE && (materials[m].flags & MATERIAL_OBJECT_NORMAL_MAP) != 0u) {\n let texel = sampleMap(normalMap, triangle, bary).xyz * 2.0 - 1.0;\n let world = normalize(vec3<f32>(\n dot(materials[m].normalRow0.xyz, texel),\n dot(materials[m].normalRow1.xyz, texel),\n dot(materials[m].normalRow2.xyz, texel)));\n\n // Seen from behind, a double sided surface turns its map around with it.\n return select(world, -world, dot(world, normal) < 0.0);\n }\n\n if (normalMap != NO_TEXTURE) {\n return tangentNormal(normalMap, triangle, bary, normal, vec2<f32>(materials[m].normalScaleX, materials[m].normalScaleY));\n }\n\n let bumpMap = materials[m].bumpMap;\n\n if (bumpMap != NO_TEXTURE) {\n // The CPU renderer's bump: the height's change over one texel, along the tangent frame of the map's UVs.\n let info = textureInfo(bumpMap);\n let channel = info.channel;\n let tangents = tangentFrame(triangle, channel, normal);\n let uv = triangleUv(triangle, bary, channel);\n let du = 1.0 / f32(max(info.size.x, 1u));\n let dv = 1.0 / f32(max(info.size.y, 1u));\n let scale = materials[m].bumpScale;\n let height = sampleTextureAt(bumpMap, uv).x;\n let dx = (sampleTextureAt(bumpMap, uv + vec2<f32>(du, 0.0)).x - height) * scale;\n let dy = (sampleTextureAt(bumpMap, uv + vec2<f32>(0.0, dv)).x - height) * scale;\n let bumped = normalize(normal - (tangents.tangent * dx + tangents.bitangent * dy));\n\n return select(bumped, normal, !all(bumped == bumped));\n }\n\n return normal;\n}\n\n/** The interpolated vertex normal as the mesh authored it, pointing out of a closed volume. */\nfn authoredNormal(triangle: u32, bary: vec2<f32>) -> vec3<f32> {\n let instance = instanceOf(triangle);\n let at = frame.cornerOffset + storedTriangle(triangle, instance) * 3u;\n let n = vertexNormal(indices[at]) * (1.0 - bary.x - bary.y)\n + vertexNormal(indices[at + 1u]) * bary.x\n + vertexNormal(indices[at + 2u]) * bary.y;\n\n if (instance != NO_INSTANCE) {\n return normalize(instanceNormal(instance, n));\n }\n\n return normalize(n);\n}\n\n/** The interpolated vertex normal, or the face's for flat shading, turned to face the ray. */\nfn interpolatedNormal(m: u32, triangle: u32, bary: vec2<f32>, direction: vec3<f32>) -> vec3<f32> {\n var normal = authoredNormal(triangle, bary);\n\n if ((materials[m].flags & MATERIAL_FLAT) != 0u || !all(normal == normal)) {\n normal = triangleNormal(triangle);\n }\n\n return select(normal, -normal, dot(normal, direction) > 0.0);\n}\n\n/** Three's transmission at this point: the factor, its map's red channel, and none of it on metal. */\nfn transmissionAt(m: u32, triangle: u32, bary: vec2<f32>, metalness: f32) -> f32 {\n if (materials[m].transmission <= 0.0) {\n return 0.0;\n }\n\n let map = sampleMap(materials[m].transmissionMap, triangle, bary).r;\n\n return clamp(materials[m].transmission * map, 0.0, 1.0) * (1.0 - metalness);\n}\n\n/** Beer-Lambert: the colour reached at the attenuation distance fixes how fast each channel fades. */\nfn absorptionOf(m: u32) -> vec3<f32> {\n let attenuation = materials[m].attenuation;\n\n if (attenuation.w <= 0.0) {\n return vec3<f32>(0.0);\n }\n\n return -log(max(attenuation.rgb, vec3<f32>(1e-6))) / attenuation.w;\n}\n\n/** Three's evalSensitivity: the XYZ response of a thin film, Fourier-fitted, in linear sRGB. */\nfn filmSensitivity(opd: f32, shift: vec3<f32>) -> vec3<f32> {\n let phase = 2.0 * PI * opd * 1.0e-9;\n let value = vec3<f32>(5.4856e-13, 4.4201e-13, 5.2481e-13);\n let position = vec3<f32>(1.6810e+06, 1.7953e+06, 2.2084e+06);\n let variance = vec3<f32>(4.3278e+09, 9.3046e+09, 6.6121e+09);\n var xyz = value * sqrt(2.0 * PI * variance) * cos(position * phase + shift) * exp(-phase * phase * variance);\n\n xyz.x = xyz.x + 9.7470e-14 * sqrt(2.0 * PI * 4.5282e+09) * cos(2.2399e+06 * phase + shift.x)\n * exp(-4.5282e+09 * phase * phase);\n xyz = xyz / 1.0685e-7;\n\n return mat3x3<f32>(\n vec3<f32>(3.2404542, -0.9692660, 0.0556434),\n vec3<f32>(-1.5371385, 1.8760108, -0.2040259),\n vec3<f32>(-0.4985314, 0.0415560, 1.0572252)) * xyz;\n}\n\nfn schlick3(f0: vec3<f32>, f90: f32, cosine: f32) -> vec3<f32> {\n let t = 1.0 - cosine;\n let k = t * t * t * t * t;\n\n return f0 + (vec3<f32>(f90) - f0) * k;\n}\n\n/** Three's evalIridescence (Belcour and Barla 2017): the Fresnel of a thin film over a base of reflectance baseF0. */\nfn evalIridescence(filmIor: f32, cosTheta1: f32, thickness: f32, baseF0: vec3<f32>) -> vec3<f32> {\n let ior = mix(1.0, filmIor, smoothstep(0.0, 0.03, thickness));\n let sinTheta2Sq = (1.0 / ior) * (1.0 / ior) * (1.0 - cosTheta1 * cosTheta1);\n let cosTheta2Sq = 1.0 - sinTheta2Sq;\n\n if (cosTheta2Sq < 0.0) {\n return vec3<f32>(1.0);\n }\n\n let cosTheta2 = sqrt(cosTheta2Sq);\n let r0 = ((ior - 1.0) / (ior + 1.0)) * ((ior - 1.0) / (ior + 1.0));\n let r12 = r0 + (1.0 - r0) * pow(1.0 - cosTheta1, 5.0);\n let t121 = 1.0 - r12;\n let phi12 = select(0.0, PI, ior < 1.0);\n let phi21 = PI - phi12;\n let root = sqrt(clamp(baseF0, vec3<f32>(0.0), vec3<f32>(0.9999)));\n let baseIor = (vec3<f32>(1.0) + root) / (vec3<f32>(1.0) - root);\n let r1 = ((baseIor - vec3<f32>(ior)) / (baseIor + vec3<f32>(ior))) * ((baseIor - vec3<f32>(ior)) / (baseIor + vec3<f32>(ior)));\n let r23 = schlick3(r1, 1.0, cosTheta2);\n let phi23 = select(vec3<f32>(0.0), vec3<f32>(PI), baseIor < vec3<f32>(ior));\n let opd = 2.0 * ior * thickness * cosTheta2;\n let phi = vec3<f32>(phi21) + phi23;\n let r123 = clamp(r12 * r23, vec3<f32>(1e-5), vec3<f32>(0.9999));\n let r123Root = sqrt(r123);\n let rs = t121 * t121 * r23 / (vec3<f32>(1.0) - r123);\n var intensity = vec3<f32>(r12) + rs;\n var cm = rs - vec3<f32>(t121);\n\n for (var m = 1; m <= 2; m = m + 1) {\n cm = cm * r123Root;\n intensity = intensity + cm * 2.0 * filmSensitivity(f32(m) * opd, f32(m) * phi);\n }\n\n return max(intensity, vec3<f32>(0.0));\n}\n\n/** Three's toon ramp: the gradient map across dot(n, l) from -1 to 1, or a single step at 0.7 without one. */\nfn toonRamp(gradientMap: u32, cosine: f32) -> f32 {\n let coordinate = cosine * 0.5 + 0.5;\n\n if (gradientMap == NO_TEXTURE) {\n return select(0.7, 1.0, coordinate >= 0.7);\n }\n\n return sampleTextureRaw(gradientMap, vec2<f32>(coordinate, 0.0)).r;\n}\n\n/**\n * Whether a material's coverage can be told from its maps alone, before the rest of the surface is read: no shader that\n * might rewrite the alpha or discard, normal blending, and something that makes it partial at all.\n */\nfn coverageFirst(m: u32) -> bool {\n let flags = materials[m].flags;\n let blending = materials[m].blending;\n\n return materials[m].program == NO_PROGRAM\n && (blending == BLEND_NORMAL || blending == BLEND_NONE)\n && (materials[m].alphaTest > 0.0 || (flags & (MATERIAL_ALPHA_HASH | MATERIAL_TRANSPARENT)) != 0u);\n}\n\n/** Everything the lobes need about one point of one triangle. */\nfn resolveSurface(triangle: u32, bary: vec2<f32>, direction: vec3<f32>) -> Surface {\n let m = materialIndexOf(triangle);\n\n return resolveSurfaceFrom(triangle, bary, direction, sampleMap(materials[m].map, triangle, bary));\n}\n\n/** The same, from the colour map's texel at this point, for a caller that already read it. */\nfn resolveSurfaceFrom(triangle: u32, bary: vec2<f32>, direction: vec3<f32>, base: vec4<f32>) -> Surface {\n let m = materialIndexOf(triangle);\n let flags = materials[m].flags;\n let kind = materials[m].kind;\n let facing = interpolatedNormal(m, triangle, bary, direction);\n let view = -direction;\n var surface: Surface;\n\n surface.material = m;\n surface.flags = flags;\n surface.kind = kind;\n surface.blending = materials[m].blending;\n surface.facing = facing;\n surface.front = dot(authoredNormal(triangle, bary), direction) < 0.0;\n surface.normal = mappedNormal(m, triangle, bary, facing);\n\n // A normal map may tilt past the horizon, where the surface would be lit from behind itself.\n if (dot(surface.normal, view) <= 0.0) {\n surface.normal = facing;\n }\n\n var albedo = materials[m].color.rgb * base.rgb;\n var alpha = materials[m].color.w * base.a * sampleMap(materials[m].alphaMap, triangle, bary).g;\n\n if ((flags & MATERIAL_VERTEX_COLORS) != 0u) {\n let color = triangleColor(triangle, bary);\n albedo = albedo * color.rgb;\n alpha = alpha * color.a;\n }\n\n var roughness = materials[m].specular.w * sampleMap(materials[m].roughnessMap, triangle, bary).g;\n var metalness = materials[m].metalness * sampleMap(materials[m].metalnessMap, triangle, bary).b;\n var emissive = vec3<f32>(0.0);\n\n // An unlit light's colour is added as what it shows, below; emissionAt gives the same colour to light samples.\n if ((flags & MATERIAL_UNLIT_LIGHT) == 0u) {\n emissive = emissionAt(triangle, bary);\n }\n\n surface.opacity = 1.0;\n\n // A built-in material's hooks run on its values before lighting, in Three's view space; a shader material's output\n // is the colour itself.\n if (materials[m].program != NO_PROGRAM) {\n var input = shaderInputAt(m, triangle, bary, direction);\n input.diffuseColor = vec4<f32>(albedo, alpha);\n input.normal = toView(surface.normal);\n input.geometryNormal = toView(facing);\n input.roughness = roughness;\n input.metalness = metalness;\n input.emissive = emissive;\n let output = runProgram(materials[m].program, input);\n\n if (output.discarded) {\n surface.opacity = 0.0;\n }\n\n if ((flags & MATERIAL_PATCHED) != 0u) {\n albedo = output.diffuseColor.rgb;\n alpha = output.diffuseColor.a;\n roughness = output.roughness;\n metalness = output.metalness;\n emissive = output.emissive;\n let normal = toWorld(output.normal);\n\n if (all(normal == normal)) {\n surface.normal = select(normal, -normal, dot(normal, view) < 0.0);\n }\n } else {\n albedo = output.color.rgb;\n alpha = output.color.a;\n }\n }\n\n surface.opacity = surface.opacity * coverageOf(m, alpha);\n surface.alpha = alpha;\n surface.albedo = albedo;\n surface.roughness = clamp(roughness, 0.0525, 1.0);\n surface.metalness = clamp(metalness, 0.0, 1.0);\n surface.emissive = emissive;\n surface.transmission = transmissionAt(m, triangle, bary, surface.metalness);\n surface.ior = max(materials[m].ior, 1.0);\n surface.thickness = materials[m].thickness * sampleMap(materials[m].thicknessMap, triangle, bary).g;\n surface.dispersion = materials[m].dispersion;\n surface.subsurface = select(0.0, materials[m].subsurface.w, frame.subsurfaceEnabled != 0u);\n surface.absorption = absorptionOf(m);\n surface.shininess = materials[m].shininess;\n surface.specularStrength = sampleMap(materials[m].specularMap, triangle, bary).r;\n surface.gradientMap = materials[m].gradientMap;\n surface.envMap = NO_TEXTURE;\n surface.envMapIntensity = materials[m].envMapIntensity;\n surface.legacyAmount = 0.0;\n surface.legacyEnv = vec3<f32>(0.0);\n surface.combine = materials[m].combine;\n surface.lightMap = vec3<f32>(0.0);\n surface.clearcoat = 0.0;\n surface.iridescence = 0.0;\n surface.anisotropy = 0.0;\n surface.sheenColor = vec3<f32>(0.0);\n surface.specularColor = materials[m].specular.rgb;\n surface.specularF90 = 1.0;\n\n if ((flags & MATERIAL_PBR) != 0u) {\n if ((flags & MATERIAL_SPECULAR) != 0u) {\n // A physical material: the index of refraction, the specular colour and intensity and their maps.\n let intensity = materials[m].specularIntensity * sampleMap(materials[m].specularIntensityMap, triangle, bary).a;\n let color = materials[m].specular.rgb * sampleMap(materials[m].specularColorMap, triangle, bary).rgb;\n\n surface.specularColor = min(materials[m].dielectric * color, vec3<f32>(1.0)) * intensity;\n surface.specularF90 = mix(intensity, 1.0, surface.metalness);\n } else {\n // Three's standard material has no index of refraction and reflects 0.04.\n surface.specularColor = vec3<f32>(0.04);\n }\n\n surface.envMap = materials[m].envMap;\n\n if (materials[m].clearcoat > 0.0) {\n surface.clearcoat = clamp(materials[m].clearcoat * sampleMap(materials[m].clearcoatMap, triangle, bary).r, 0.0, 1.0);\n surface.clearcoatRoughness = clamp(\n materials[m].clearcoatRoughness * sampleMap(materials[m].clearcoatRoughnessMap, triangle, bary).g, 0.0525, 1.0);\n // The coat ignores the base's normal map: it has its own, over the interpolated normal.\n surface.clearcoatNormal = tangentNormal(materials[m].clearcoatNormalMap, triangle, bary, facing,\n vec2<f32>(materials[m].clearcoatNormalScaleX, materials[m].clearcoatNormalScaleY));\n\n if (dot(surface.clearcoatNormal, view) <= 0.0) {\n surface.clearcoatNormal = facing;\n }\n }\n\n if (any(materials[m].sheen.rgb > vec3<f32>(0.0))) {\n let map = sampleMap(materials[m].sheenRoughnessMap, triangle, bary).a;\n surface.sheenColor = materials[m].sheen.rgb * sampleMap(materials[m].sheenColorMap, triangle, bary).rgb;\n surface.sheenRoughness = clamp(materials[m].sheen.w, 0.0001, 1.0) * map;\n }\n\n if (materials[m].iridescence > 0.0) {\n var thickness = materials[m].iridescenceThicknessMax;\n\n if (materials[m].iridescenceThicknessMap != NO_TEXTURE) {\n thickness = mix(materials[m].iridescenceThicknessMin, materials[m].iridescenceThicknessMax,\n sampleMap(materials[m].iridescenceThicknessMap, triangle, bary).g);\n }\n\n if (thickness > 0.0) {\n surface.iridescence = clamp(\n materials[m].iridescence * sampleMap(materials[m].iridescenceMap, triangle, bary).r, 0.0, 1.0);\n\n let nv = clamp(dot(surface.normal, view), 0.0, 1.0);\n surface.iridescenceFresnel = mix(\n evalIridescence(materials[m].iridescenceIor, nv, thickness, surface.specularColor),\n evalIridescence(materials[m].iridescenceIor, nv, thickness, albedo),\n surface.metalness);\n }\n }\n\n if (materials[m].anisotropy != 0.0) {\n let rotation = materials[m].anisotropyRotation;\n var vector = vec2<f32>(cos(rotation), sin(rotation)) * materials[m].anisotropy;\n let channel = select(0u, textureInfo(materials[m].anisotropyMap).channel, materials[m].anisotropyMap != NO_TEXTURE);\n let tangents = tangentFrame(triangle, channel, surface.normal);\n\n if (materials[m].anisotropyMap != NO_TEXTURE) {\n let polar = sampleMap(materials[m].anisotropyMap, triangle, bary).rgb;\n let turn = mat2x2<f32>(vector.x, vector.y, -vector.y, vector.x);\n vector = turn * normalize(2.0 * polar.rg - vec2<f32>(1.0)) * polar.b;\n }\n\n let strength = length(vector);\n let along = select(vector / max(strength, 1e-20), vec2<f32>(1.0, 0.0), strength == 0.0);\n\n surface.anisotropy = clamp(strength, 0.0, 1.0);\n surface.alphaT = mix(surface.roughness * surface.roughness, 1.0, surface.anisotropy * surface.anisotropy);\n surface.anisotropyT = tangents.tangent * along.x + tangents.bitangent * along.y;\n surface.anisotropyB = tangents.bitangent * along.x - tangents.tangent * along.y;\n }\n } else if (materials[m].envMap != NO_TEXTURE\n && (kind == KIND_BASIC || kind == KIND_LAMBERT || kind == KIND_PHONG)) {\n // Basic, Lambert and Phong blend their own map over the lit colour, mirrored or bent the way the map says.\n let info = textureInfo(materials[m].envMap);\n let bent = refract(direction, surface.normal, materials[m].refractionRatio);\n let lookup = select(reflect(direction, surface.normal), bent, (info.flags & 16u) != 0u && any(bent != vec3<f32>(0.0)));\n\n surface.legacyEnv = sampleEquirect(materials[m].envMap, lookup).rgb * materials[m].envMapIntensity;\n surface.legacyAmount = clamp(materials[m].reflectivity * surface.specularStrength, 0.0, 1.0);\n }\n\n if (materials[m].lightMap != NO_TEXTURE) {\n let baked = sampleMap(materials[m].lightMap, triangle, bary).rgb * materials[m].lightMapIntensity;\n surface.lightMap = baked * albedo * (1.0 - surface.metalness) / PI;\n }\n\n // A material Three does not light reads as its own colour, which in a path tracer is the same as emitting it.\n if ((flags & MATERIAL_LIT) == 0u) {\n var color = albedo;\n\n if (kind == KIND_NORMAL) {\n color = toView(surface.normal) * 0.5 + 0.5;\n } else if (kind == KIND_DEPTH) {\n let clip = frame.projection * (frame.worldToCamera * vec4<f32>(trianglePointAt(triangle, bary), 1.0));\n color = vec3<f32>(1.0 - (clip.z / clip.w * 0.5 + 0.5));\n } else if (kind == KIND_MATCAP) {\n let point = trianglePointAt(triangle, bary);\n let viewDirection = normalize(-(frame.worldToCamera * vec4<f32>(point, 1.0)).xyz);\n let x = normalize(vec3<f32>(viewDirection.z, 0.0, -viewDirection.x));\n let y = cross(viewDirection, x);\n let normal = toView(surface.normal);\n let uv = vec2<f32>(dot(x, normal), dot(y, normal)) * 0.495 + 0.5;\n var matcap = vec3<f32>(mix(0.2, 0.8, uv.y));\n\n if (materials[m].matcap != NO_TEXTURE) {\n matcap = sampleTextureRaw(materials[m].matcap, uv).rgb;\n }\n\n color = albedo * matcap;\n } else if (kind == KIND_BASIC && materials[m].lightMap != NO_TEXTURE) {\n // A basic material with a light map shows the map's light instead of full brightness.\n color = albedo * sampleMap(materials[m].lightMap, triangle, bary).rgb * materials[m].lightMapIntensity / PI;\n }\n\n if (surface.legacyAmount > 0.0) {\n let amount = surface.legacyAmount;\n\n if (surface.combine == 1u) {\n color = mix(color, surface.legacyEnv, amount);\n } else if (surface.combine == 2u) {\n color = color + surface.legacyEnv * amount;\n } else {\n color = mix(color, color * surface.legacyEnv, amount);\n }\n\n surface.legacyAmount = 0.0;\n }\n\n surface.emissive = surface.emissive + color;\n surface.lightMap = vec3<f32>(0.0);\n }\n\n return surface;\n}\n";
|
|
10
10
|
//# sourceMappingURL=surface.wgsl.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"surface.wgsl.d.ts","sourceRoot":"","sources":["../../src/wgsl/surface.wgsl.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AACH,eAAO,MAAM,YAAY,
|
|
1
|
+
{"version":3,"file":"surface.wgsl.d.ts","sourceRoot":"","sources":["../../src/wgsl/surface.wgsl.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AACH,eAAO,MAAM,YAAY,o3hCAu0BxB,CAAC"}
|
|
@@ -82,15 +82,19 @@ fn trianglePointAt(triangle: u32, bary: vec2<f32>) -> vec3<f32> {
|
|
|
82
82
|
}
|
|
83
83
|
|
|
84
84
|
fn triangleUv(triangle: u32, bary: vec2<f32>, channel: u32) -> vec2<f32> {
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
85
|
+
let corners = triangleCorners(triangle);
|
|
86
|
+
|
|
87
|
+
return vertexUv(corners.x, channel) * (1.0 - bary.x - bary.y)
|
|
88
|
+
+ vertexUv(corners.y, channel) * bary.x
|
|
89
|
+
+ vertexUv(corners.z, channel) * bary.y;
|
|
88
90
|
}
|
|
89
91
|
|
|
90
92
|
fn triangleColor(triangle: u32, bary: vec2<f32>) -> vec4<f32> {
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
93
|
+
let corners = triangleCorners(triangle);
|
|
94
|
+
|
|
95
|
+
return vertexColor(corners.x) * (1.0 - bary.x - bary.y)
|
|
96
|
+
+ vertexColor(corners.y) * bary.x
|
|
97
|
+
+ vertexColor(corners.z) * bary.y;
|
|
94
98
|
}
|
|
95
99
|
|
|
96
100
|
/** A map slot, sampled through the UV set the texture asks for. Missing maps read as one, so a multiply is always safe. */
|
|
@@ -362,9 +366,10 @@ fn tangentFrame(triangle: u32, channel: u32, normal: vec3<f32>) -> TangentFrame
|
|
|
362
366
|
let p0 = triangleVertex(triangle, 0u);
|
|
363
367
|
let edge1 = triangleVertex(triangle, 1u) - p0;
|
|
364
368
|
let edge2 = triangleVertex(triangle, 2u) - p0;
|
|
365
|
-
let
|
|
366
|
-
let
|
|
367
|
-
let
|
|
369
|
+
let corners = triangleCorners(triangle);
|
|
370
|
+
let uv0 = vertexUv(corners.x, channel);
|
|
371
|
+
let delta1 = vertexUv(corners.y, channel) - uv0;
|
|
372
|
+
let delta2 = vertexUv(corners.z, channel) - uv0;
|
|
368
373
|
let determinant = delta1.x * delta2.y - delta2.x * delta1.y;
|
|
369
374
|
|
|
370
375
|
// A triangle with no UV area has no tangent frame to offer.
|
|
@@ -460,12 +465,17 @@ fn mappedNormal(m: u32, triangle: u32, bary: vec2<f32>, normal: vec3<f32>) -> ve
|
|
|
460
465
|
|
|
461
466
|
/** The interpolated vertex normal as the mesh authored it, pointing out of a closed volume. */
|
|
462
467
|
fn authoredNormal(triangle: u32, bary: vec2<f32>) -> vec3<f32> {
|
|
463
|
-
let
|
|
464
|
-
let
|
|
465
|
-
let
|
|
466
|
-
|
|
468
|
+
let instance = instanceOf(triangle);
|
|
469
|
+
let at = frame.cornerOffset + storedTriangle(triangle, instance) * 3u;
|
|
470
|
+
let n = vertexNormal(indices[at]) * (1.0 - bary.x - bary.y)
|
|
471
|
+
+ vertexNormal(indices[at + 1u]) * bary.x
|
|
472
|
+
+ vertexNormal(indices[at + 2u]) * bary.y;
|
|
473
|
+
|
|
474
|
+
if (instance != NO_INSTANCE) {
|
|
475
|
+
return normalize(instanceNormal(instance, n));
|
|
476
|
+
}
|
|
467
477
|
|
|
468
|
-
return normalize(
|
|
478
|
+
return normalize(n);
|
|
469
479
|
}
|
|
470
480
|
|
|
471
481
|
/** The interpolated vertex normal, or the face's for flat shading, turned to face the ray. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"surface.wgsl.js","sourceRoot":"","sources":["../../src/wgsl/surface.wgsl.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AACH,MAAM,CAAC,MAAM,YAAY,GAAG,UAAU,CAAC
|
|
1
|
+
{"version":3,"file":"surface.wgsl.js","sourceRoot":"","sources":["../../src/wgsl/surface.wgsl.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AACH,MAAM,CAAC,MAAM,YAAY,GAAG,UAAU,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAu0BtC,CAAC"}
|