-
Notifications
You must be signed in to change notification settings - Fork 0
/
raytracer.wgsl
401 lines (323 loc) · 11.2 KB
/
raytracer.wgsl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
struct Uniforms {
viewProjectionMatrix: mat4x4f,
}
@group(0) @binding(0) var<uniform> uniforms: Uniforms;
struct VertexInput {
@location(0) position: vec2f,
@location(1) texCoord: vec2f,
}
struct VertexOutput {
@builtin(position) position: vec4f,
@location(0) texCoord: vec2f,
}
@vertex
fn vsMain(in: VertexInput) -> VertexOutput {
var out: VertexOutput;
out.position = uniforms.viewProjectionMatrix * vec4f(in.position, 0.0, 1.0);
out.texCoord = in.texCoord;
return out;
}
// render params bind group
@group(1) @binding(0) var<uniform> renderParams: RenderParams;
// scene bind group
// TODO: these are `read` only buffers. How can I create a buffer layout type which allows this?
// Annotating these as read causes validation failures.
@group(2) @binding(0) var<storage, read_write> bvhNodes: array<BvhNode>;
@group(2) @binding(1) var<storage, read_write> triangles: array<Triangle>;
@group(2) @binding(2) var<storage, read_write> normals: array<array<vec3f, 3>>;
@group(2) @binding(3) var<storage, read_write> texCoords: array<array<vec2f, 3>>;
@group(2) @binding(4) var<storage, read_write> textureDescriptorIndices: array<u32>;
@group(2) @binding(5) var<storage, read_write> textureDescriptors: array<TextureDescriptor>;
@group(2) @binding(6) var<storage, read_write> textures: array<u32>;
@fragment
fn fsMain(in: VertexOutput) -> @location(0) vec4f {
let u = in.texCoord.x;
let v = in.texCoord.y;
let dimensions = renderParams.frameData.dimensions;
let frameCount = renderParams.frameData.frameCount;
let j = u32(u * f32(dimensions.x));
let i = u32(v * f32(dimensions.y));
var rngState = initRng(vec2(j, i), dimensions, frameCount);
let primaryRay = generateCameraRay(renderParams.camera, &rngState, u, v);
let rgb = rayColor(primaryRay, &rngState);
return vec4f(rgb, 1f);
}
const EPSILON = 0.00001f;
const PI = 3.1415927f;
const FRAC_1_PI = 0.31830987f;
const FRAC_PI_2 = 1.5707964f;
const T_MIN = 0.001f;
const T_MAX = 10000f;
const NUM_BOUNCES = 4u;
const UNIFORM_HEMISPHERE_MULTIPLIER = 2f * PI;
struct RenderParams {
frameData: FrameData,
camera: Camera,
}
struct FrameData {
dimensions: vec2u,
frameCount: u32,
}
struct Camera {
origin: vec3f,
lowerLeftCorner: vec3f,
horizontal: vec3f,
vertical: vec3f,
lensRadius: f32,
}
struct Aabb {
min: vec3f,
max: vec3f,
}
struct BvhNode {
aabb: Aabb,
trianglesOffset: u32,
secondChildOffset: u32,
triangleCount: u32,
splitAxis: u32,
}
// TODO: rename to positions
struct Triangle {
v0: vec3f,
v1: vec3f,
v2: vec3f,
}
struct Ray {
origin: vec3f,
direction: vec3f
}
struct Intersection {
p: vec3f,
n: vec3f,
uv: vec2f,
triangleIdx: u32,
}
struct TriangleHit {
p: vec3f,
b: vec3f,
t: f32,
}
struct Scatter {
wi: vec3f,
throughput: vec3f,
}
fn rayColor(primaryRay: Ray, rngState: ptr<function, u32>) -> vec3f {
var ray = primaryRay;
var color = vec3(0f);
var throughput = vec3(1f);
for (var bounces = 0u; bounces < NUM_BOUNCES; bounces += 1u) {
var intersection: Intersection;
if rayIntersectBvh(ray, T_MAX, &intersection) {
let p = intersection.p;
let scatter = evalImplicitLambertian(intersection, rngState);
ray = Ray(p, scatter.wi);
throughput *= scatter.throughput;
} else {
let unitDirection = normalize(ray.direction);
let t = 0.5f * (unitDirection.y + 1f);
let skyColor = (1f - t) * vec3(1f, 1f, 1f) + t * vec3(0.5f, 0.7f, 1f);
color += throughput * skyColor;
break;
}
}
return color;
}
fn generateCameraRay(camera: Camera, rngState: ptr<function, u32>, u: f32, v: f32) -> Ray {
let origin = camera.origin;
let direction = camera.lowerLeftCorner + u * camera.horizontal + v * camera.vertical - origin;
return Ray(origin, direction);
}
fn evalImplicitLambertian(hit: Intersection, rngState: ptr<function, u32>) -> Scatter {
let v = rngNextInCosineWeightedHemisphere(rngState);
let onb = pixarOnb(hit.n);
let wi = onb * v;
let textureDesc = textureDescriptors[textureDescriptorIndices[hit.triangleIdx]];
let uv = hit.uv;
let albedo = textureLookup(textureDesc, uv);
return Scatter(wi, albedo);
}
fn pixarOnb(n: vec3f) -> mat3x3f {
// https://www.jcgt.org/published/0006/01/01/paper-lowres.pdf
let s = select(-1f, 1f, n.z >= 0f);
let a = -1f / (s + n.z);
let b = n.x * n.y * a;
let u = vec3(1f + s * n.x * n.x * a, s * b, -s * n.x);
let v = vec3(b, s + n.y * n.y * a, -n.y);
return mat3x3(u, v, n);
}
fn rayIntersectBvh(ray: Ray, rayTMax: f32, hit: ptr<function, Intersection>) -> bool {
let intersector = rayAabbIntersector(ray);
var toVisitOffset = 0u;
var currentNodeIdx = 0u;
var nodesToVisit: array<u32, 32u>;
var didIntersect: bool = false;
var tmax = rayTMax;
loop {
let node: BvhNode = bvhNodes[currentNodeIdx];
if rayIntersectAabb(intersector, node.aabb, tmax) {
if node.triangleCount > 0u {
for (var idx = 0u; idx < node.triangleCount; idx = idx + 1u) {
let triangle: Triangle = triangles[node.trianglesOffset + idx];
var trihit: TriangleHit;
if rayIntersectTriangle(ray, triangle, tmax, &trihit) {
tmax = trihit.t;
let b = trihit.b;
let p = trihit.p;
let triangleIdx = node.trianglesOffset + idx;
let ns = normals[triangleIdx];
let n = b[0] * ns[0] + b[1] * ns[1] + b[2] * ns[2];
let uvs = texCoords[triangleIdx];
let uv = b[0] * uvs[0] + b[1] * uvs[1] + b[2] * uvs[2];
*hit = Intersection(p, n, uv, triangleIdx);
didIntersect = true;
}
}
if toVisitOffset == 0u {
break;
}
toVisitOffset -= 1u;
currentNodeIdx = nodesToVisit[toVisitOffset];
} else {
// Is intersector.invDir[node.splitAxis] < 0f? If so, visit second child first.
if intersector.dirNeg[node.splitAxis] == 1u {
nodesToVisit[toVisitOffset] = currentNodeIdx + 1u;
currentNodeIdx = node.secondChildOffset;
} else {
nodesToVisit[toVisitOffset] = node.secondChildOffset;
currentNodeIdx = currentNodeIdx + 1u;
}
toVisitOffset += 1u;
}
} else {
if toVisitOffset == 0u {
break;
}
toVisitOffset -= 1u;
currentNodeIdx = nodesToVisit[toVisitOffset];
}
}
return didIntersect;
}
struct RayAabbIntersector {
origin: vec3f,
invDir: vec3f,
dirNeg: vec3u,
}
@must_use
fn rayAabbIntersector(ray: Ray) -> RayAabbIntersector {
let invDirection = vec3f(1f / ray.direction.x, 1f / ray.direction.y, 1f / ray.direction.z);
return RayAabbIntersector(
ray.origin,
invDirection,
vec3u(select(0u, 1u, (invDirection.x < 0f)), select(0u, 1u, (invDirection.y < 0f)), select(0u, 1u, (invDirection.z < 0f)))
);
}
@must_use
fn rayIntersectAabb(intersector: RayAabbIntersector, aabb: Aabb, rayTMax: f32) -> bool {
let bounds: array<vec3f, 2> = array(aabb.min, aabb.max);
var tmin: f32 = (bounds[intersector.dirNeg[0u]].x - intersector.origin.x) * intersector.invDir.x;
var tmax: f32 = (bounds[1u - intersector.dirNeg[0u]].x - intersector.origin.x) * intersector.invDir.x;
let tymin: f32 = (bounds[intersector.dirNeg[1u]].y - intersector.origin.y) * intersector.invDir.y;
let tymax: f32 = (bounds[1 - intersector.dirNeg[1u]].y - intersector.origin.y) * intersector.invDir.y;
if (tmin > tymax) || (tymin > tmax) {
return false;
}
tmin = max(tymin, tmin);
tmax = min(tymax, tmax);
let tzmin: f32 = (bounds[intersector.dirNeg[2u]].z - intersector.origin.z) * intersector.invDir.z;
let tzmax: f32 = (bounds[1 - intersector.dirNeg[2u]].z - intersector.origin.z) * intersector.invDir.z;
if (tmin > tzmax) || (tzmin > tmax) {
return false;
}
tmin = max(tzmin, tmin);
tmax = min(tzmax, tmax);
return (tmin < rayTMax) && (tmax > 0.0);
}
fn rayIntersectTriangle(ray: Ray, tri: Triangle, tmax: f32, hit: ptr<function, TriangleHit>) -> bool {
// Mäller-Trumbore algorithm
// https://en.wikipedia.org/wiki/Möller–Trumbore_intersection_algorithm
let e1 = tri.v1 - tri.v0;
let e2 = tri.v2 - tri.v0;
let h = cross(ray.direction, e2);
let det = dot(e1, h);
if det > -EPSILON && det < EPSILON {
return false;
}
let invDet = 1.0f / det;
let s = ray.origin - tri.v0;
let u = invDet * dot(s, h);
if u < 0.0f || u > 1.0f {
return false;
}
let q = cross(s, e1);
let v = invDet * dot(ray.direction, q);
if v < 0.0f || u + v > 1.0f {
return false;
}
let t = invDet * dot(e2, q);
if t > EPSILON && t < tmax {
// https://www.scratchapixel.com/lessons/3d-basic-rendering/ray-tracing-rendering-a-triangle/moller-trumbore-ray-triangle-intersection.html
// e1 = v1 - v0
// e2 = v2 - v0
// -> p = v0 + u * e1 + v * e2
let p = tri.v0 + u * e1 + v * e2;
let b = vec3f(1f - u - v, u, v);
*hit = TriangleHit(p, b, t);
return true;
} else {
return false;
}
}
struct TextureDescriptor {
width: u32,
height: u32,
offset: u32,
}
@must_use
fn textureLookup(desc: TextureDescriptor, uv: vec2f) -> vec3f {
let u = clamp(uv.x, 0f, 1f);
let v = clamp(uv.y, 0f, 1f);
let j = u32(u * f32(desc.width));
let i = u32(v * f32(desc.height));
let idx = i * desc.width + j;
let rgba = textures[desc.offset + idx];
return vec3f(f32(rgba & 0xffu), f32((rgba >> 8u) & 0xffu), f32((rgba >> 16u) & 0xffu)) / 255f;
}
@must_use
fn rngNextInCosineWeightedHemisphere(state: ptr<function, u32>) -> vec3f {
let r1 = rngNextFloat(state);
let r2 = rngNextFloat(state);
let sqrtR2 = sqrt(r2);
let z = sqrt(1f - r2);
let phi = 2f * PI * r1;
let x = cos(phi) * sqrtR2;
let y = sin(phi) * sqrtR2;
return vec3(x, y, z);
}
@must_use
fn initRng(pixel: vec2u, resolution: vec2u, frame: u32) -> u32 {
// Adapted from https://github.com/boksajak/referencePT
let seed = dot(pixel, vec2u(1u, resolution.x)) ^ jenkinsHash(frame);
return jenkinsHash(seed);
}
@must_use
fn jenkinsHash(input: u32) -> u32 {
var x = input;
x += x << 10u;
x ^= x >> 6u;
x += x << 3u;
x ^= x >> 11u;
x += x << 15u;
return x;
}
fn rngNextFloat(state: ptr<function, u32>) -> f32 {
rngNextInt(state);
return f32(*state) / f32(0xffffffffu);
}
fn rngNextInt(state: ptr<function, u32>) {
// PCG random number generator
// Based on https://www.shadertoy.com/view/XlGcRh
let oldState = *state + 747796405u + 2891336453u;
let word = ((oldState >> ((oldState >> 28u) + 4u)) ^ oldState) * 277803737u;
*state = (word >> 22u) ^ word;
}