@plasius/gpu-renderer 0.1.13 → 0.1.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -20,14 +20,28 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
20
20
  var index_exports = {};
21
21
  __export(index_exports, {
22
22
  bindRendererToXrManager: () => bindRendererToXrManager,
23
+ createDefaultWavefrontSceneObjects: () => createDefaultWavefrontSceneObjects,
23
24
  createGpuRenderer: () => createGpuRenderer,
24
25
  createRayTracingRenderPlan: () => createRayTracingRenderPlan,
25
26
  createRendererDebugHooks: () => createRendererDebugHooks,
27
+ createWavefrontBvhBuildLevels: () => createWavefrontBvhBuildLevels,
28
+ createWavefrontBvhSortStages: () => createWavefrontBvhSortStages,
29
+ createWavefrontEmissiveTriangleIndexSource: () => createWavefrontEmissiveTriangleIndexSource,
30
+ createWavefrontGpuMeshSource: () => createWavefrontGpuMeshSource,
31
+ createWavefrontMeshAcceleration: () => createWavefrontMeshAcceleration,
32
+ createWavefrontPathTracingComputeConfig: () => createWavefrontPathTracingComputeConfig,
33
+ createWavefrontPathTracingComputeRenderer: () => createWavefrontPathTracingComputeRenderer,
26
34
  createWavefrontPathTracingPlan: () => createWavefrontPathTracingPlan,
27
35
  defaultRendererClearColor: () => defaultRendererClearColor,
28
36
  defaultRendererWorkerProfile: () => defaultRendererWorkerProfile,
37
+ estimateWavefrontPathTracingMemory: () => estimateWavefrontPathTracingMemory,
29
38
  getRendererWorkerManifest: () => getRendererWorkerManifest,
30
39
  getRendererWorkerProfile: () => getRendererWorkerProfile,
40
+ normalizeWavefrontMesh: () => normalizeWavefrontMesh,
41
+ normalizeWavefrontSceneObject: () => normalizeWavefrontSceneObject,
42
+ packWavefrontBvhNodes: () => packWavefrontBvhNodes,
43
+ packWavefrontSceneObjects: () => packWavefrontSceneObjects,
44
+ packWavefrontTriangles: () => packWavefrontTriangles,
31
45
  rendererAccelerationStructureUpdateClasses: () => rendererAccelerationStructureUpdateClasses,
32
46
  rendererDebugOwner: () => rendererDebugOwner,
33
47
  rendererRayTracingStageOrder: () => rendererRayTracingStageOrder,
@@ -40,9 +54,3233 @@ __export(index_exports, {
40
54
  rendererWorkerProfileNames: () => rendererWorkerProfileNames,
41
55
  rendererWorkerProfiles: () => rendererWorkerProfiles,
42
56
  rendererWorkerQueueClass: () => rendererWorkerQueueClass,
43
- supportsWebGpu: () => supportsWebGpu
57
+ supportsWavefrontPathTracingCompute: () => supportsWavefrontPathTracingCompute,
58
+ supportsWebGpu: () => supportsWebGpu,
59
+ wavefrontMaterialKinds: () => wavefrontMaterialKinds,
60
+ wavefrontPathTracingComputeLimits: () => wavefrontPathTracingComputeLimits,
61
+ wavefrontSceneObjectKinds: () => wavefrontSceneObjectKinds
44
62
  });
45
63
  module.exports = __toCommonJS(index_exports);
64
+
65
+ // src/wavefront-compute.js
66
+ var DEFAULT_WIDTH = 1280;
67
+ var DEFAULT_HEIGHT = 720;
68
+ var DEFAULT_MAX_DEPTH = 6;
69
+ var DEFAULT_TILE_SIZE = 128;
70
+ var DEFAULT_SAMPLES_PER_PIXEL = 1;
71
+ var DEFAULT_SCENE_OBJECT_CAPACITY = 128;
72
+ var WORKGROUP_SIZE = 64;
73
+ var RAY_RECORD_BYTES = 80;
74
+ var HIT_RECORD_BYTES = 208;
75
+ var SCENE_OBJECT_RECORD_BYTES = 96;
76
+ var MESH_VERTEX_RECORD_BYTES = 48;
77
+ var MESH_RANGE_RECORD_BYTES = 96;
78
+ var TRIANGLE_RECORD_BYTES = 208;
79
+ var BVH_NODE_RECORD_BYTES = 48;
80
+ var BVH_LEAF_REF_RECORD_BYTES = 16;
81
+ var EMISSIVE_TRIANGLE_INDEX_BYTES = 4;
82
+ var ACCUMULATION_RECORD_BYTES = 16;
83
+ var CONFIG_BUFFER_BYTES = 256;
84
+ var COUNTER_BUFFER_BYTES = 16;
85
+ var MATERIAL_DIFFUSE = 0;
86
+ var MATERIAL_METAL = 1;
87
+ var MATERIAL_DIELECTRIC = 2;
88
+ var MATERIAL_TRANSPARENT = 3;
89
+ var MATERIAL_EMISSIVE = 4;
90
+ var OBJECT_KIND_SPHERE = 1;
91
+ var OBJECT_KIND_BOX = 2;
92
+ var DEFAULT_CAMERA = Object.freeze({
93
+ position: Object.freeze([0, 1.15, 5.6]),
94
+ target: Object.freeze([0, 0.65, 0]),
95
+ up: Object.freeze([0, 1, 0]),
96
+ fovYDegrees: 46
97
+ });
98
+ var DEFAULT_ENVIRONMENT_COLOR = Object.freeze([0.35, 0.43, 0.49, 1]);
99
+ var DEFAULT_AMBIENT_COLOR = Object.freeze([0.018, 0.022, 0.026, 1]);
100
+ var DEFAULT_ENVIRONMENT_LIGHTING = Object.freeze({
101
+ horizonColor: Object.freeze([0.46, 0.56, 0.68, 1]),
102
+ zenithColor: Object.freeze([0.04, 0.08, 0.16, 1]),
103
+ sunDirection: Object.freeze([0.22, 0.88, 0.42]),
104
+ sunColor: Object.freeze([2.8, 2.65, 2.35, 1]),
105
+ intensity: 1,
106
+ mode: 0,
107
+ exposure: 1
108
+ });
109
+ var wavefrontPathTracingComputeLimits = Object.freeze({
110
+ workgroupSize: WORKGROUP_SIZE,
111
+ rayRecordBytes: RAY_RECORD_BYTES,
112
+ hitRecordBytes: HIT_RECORD_BYTES,
113
+ sceneObjectRecordBytes: SCENE_OBJECT_RECORD_BYTES,
114
+ meshVertexRecordBytes: MESH_VERTEX_RECORD_BYTES,
115
+ meshRangeRecordBytes: MESH_RANGE_RECORD_BYTES,
116
+ triangleRecordBytes: TRIANGLE_RECORD_BYTES,
117
+ bvhNodeRecordBytes: BVH_NODE_RECORD_BYTES,
118
+ bvhLeafReferenceRecordBytes: BVH_LEAF_REF_RECORD_BYTES,
119
+ emissiveTriangleIndexBytes: EMISSIVE_TRIANGLE_INDEX_BYTES,
120
+ emissiveTriangleMetadataRecordBytes: BVH_NODE_RECORD_BYTES,
121
+ accumulationRecordBytes: ACCUMULATION_RECORD_BYTES
122
+ });
123
+ var wavefrontSceneObjectKinds = Object.freeze({
124
+ sphere: OBJECT_KIND_SPHERE,
125
+ box: OBJECT_KIND_BOX
126
+ });
127
+ var wavefrontMaterialKinds = Object.freeze({
128
+ diffuse: MATERIAL_DIFFUSE,
129
+ metal: MATERIAL_METAL,
130
+ dielectric: MATERIAL_DIELECTRIC,
131
+ transparent: MATERIAL_TRANSPARENT,
132
+ emissive: MATERIAL_EMISSIVE
133
+ });
134
+ function readPositiveInteger(name, value, fallback) {
135
+ if (value === void 0 || value === null) {
136
+ return fallback;
137
+ }
138
+ const numeric = Number(value);
139
+ if (!Number.isInteger(numeric) || numeric <= 0) {
140
+ throw new Error(`${name} must be a positive integer.`);
141
+ }
142
+ return numeric;
143
+ }
144
+ function readNonNegativeInteger(name, value, fallback) {
145
+ if (value === void 0 || value === null) {
146
+ return fallback;
147
+ }
148
+ const numeric = Number(value);
149
+ if (!Number.isInteger(numeric) || numeric < 0) {
150
+ throw new Error(`${name} must be a non-negative integer.`);
151
+ }
152
+ return numeric;
153
+ }
154
+ function readFiniteNumber(name, value, fallback) {
155
+ if (value === void 0 || value === null) {
156
+ return fallback;
157
+ }
158
+ const numeric = Number(value);
159
+ if (!Number.isFinite(numeric)) {
160
+ throw new Error(`${name} must be a finite number.`);
161
+ }
162
+ return numeric;
163
+ }
164
+ function assertAnalyticDisplayQualityPolicy(options = {}) {
165
+ const meshes = Array.isArray(options.meshes) ? options.meshes : options.mesh ? [options.mesh] : [];
166
+ if (options.displayQuality === true && meshes.length === 0) {
167
+ throw new Error(
168
+ "Display-quality path tracing requires mesh BVH triangle intersections. The analytic sphere/box wavefront renderer is debug-only."
169
+ );
170
+ }
171
+ }
172
+ function clamp(value, min, max) {
173
+ return Math.max(min, Math.min(max, value));
174
+ }
175
+ function asVec3(value, fallback) {
176
+ if (!Array.isArray(value) && !(ArrayBuffer.isView(value) && value.length >= 3)) {
177
+ return [...fallback];
178
+ }
179
+ return [
180
+ readFiniteNumber("vector[0]", value[0], fallback[0]),
181
+ readFiniteNumber("vector[1]", value[1], fallback[1]),
182
+ readFiniteNumber("vector[2]", value[2], fallback[2])
183
+ ];
184
+ }
185
+ function asColor(value, fallback = [1, 1, 1, 1]) {
186
+ if (!Array.isArray(value) && !(ArrayBuffer.isView(value) && value.length >= 3)) {
187
+ return [...fallback];
188
+ }
189
+ return [
190
+ clamp(readFiniteNumber("color[0]", value[0], fallback[0]), 0, 64),
191
+ clamp(readFiniteNumber("color[1]", value[1], fallback[1]), 0, 64),
192
+ clamp(readFiniteNumber("color[2]", value[2], fallback[2]), 0, 64),
193
+ clamp(readFiniteNumber("color[3]", value[3], fallback[3] ?? 1), 0, 1)
194
+ ];
195
+ }
196
+ function emissionPower(emission) {
197
+ return Math.max(0, emission?.[0] ?? 0) + Math.max(0, emission?.[1] ?? 0) + Math.max(0, emission?.[2] ?? 0);
198
+ }
199
+ function asUnitVec3(value, fallback) {
200
+ const vector = asVec3(value, fallback);
201
+ return normalize(vector, fallback);
202
+ }
203
+ function add(a, b) {
204
+ return [a[0] + b[0], a[1] + b[1], a[2] + b[2]];
205
+ }
206
+ function subtract(a, b) {
207
+ return [a[0] - b[0], a[1] - b[1], a[2] - b[2]];
208
+ }
209
+ function scale(a, scalar) {
210
+ return [a[0] * scalar, a[1] * scalar, a[2] * scalar];
211
+ }
212
+ function cross(a, b) {
213
+ return [
214
+ a[1] * b[2] - a[2] * b[1],
215
+ a[2] * b[0] - a[0] * b[2],
216
+ a[0] * b[1] - a[1] * b[0]
217
+ ];
218
+ }
219
+ function normalize(value, fallback = [0, 0, 1]) {
220
+ const length = Math.hypot(value[0], value[1], value[2]);
221
+ if (!Number.isFinite(length) || length <= 1e-6) {
222
+ return [...fallback];
223
+ }
224
+ return [value[0] / length, value[1] / length, value[2] / length];
225
+ }
226
+ function getArrayLikeLength(value) {
227
+ return Array.isArray(value) || ArrayBuffer.isView(value) ? value.length : 0;
228
+ }
229
+ function readVector(values, index, componentCount, fallback) {
230
+ const offset = index * componentCount;
231
+ const output = [];
232
+ for (let component = 0; component < componentCount; component += 1) {
233
+ output.push(readFiniteNumber("mesh attribute", values?.[offset + component], fallback[component] ?? 0));
234
+ }
235
+ return output;
236
+ }
237
+ function readVector2(values, index, fallback = [0, 0]) {
238
+ return readVector(values, index, 2, fallback);
239
+ }
240
+ function triangleBounds(v0, v1, v2) {
241
+ return {
242
+ min: [
243
+ Math.min(v0[0], v1[0], v2[0]),
244
+ Math.min(v0[1], v1[1], v2[1]),
245
+ Math.min(v0[2], v1[2], v2[2])
246
+ ],
247
+ max: [
248
+ Math.max(v0[0], v1[0], v2[0]),
249
+ Math.max(v0[1], v1[1], v2[1]),
250
+ Math.max(v0[2], v1[2], v2[2])
251
+ ]
252
+ };
253
+ }
254
+ function mergeBounds(left, right) {
255
+ if (!left) {
256
+ return {
257
+ min: [...right.min],
258
+ max: [...right.max]
259
+ };
260
+ }
261
+ return {
262
+ min: [
263
+ Math.min(left.min[0], right.min[0]),
264
+ Math.min(left.min[1], right.min[1]),
265
+ Math.min(left.min[2], right.min[2])
266
+ ],
267
+ max: [
268
+ Math.max(left.max[0], right.max[0]),
269
+ Math.max(left.max[1], right.max[1]),
270
+ Math.max(left.max[2], right.max[2])
271
+ ]
272
+ };
273
+ }
274
+ function boundsCentroid(bounds) {
275
+ return [
276
+ (bounds.min[0] + bounds.max[0]) * 0.5,
277
+ (bounds.min[1] + bounds.max[1]) * 0.5,
278
+ (bounds.min[2] + bounds.max[2]) * 0.5
279
+ ];
280
+ }
281
+ function readMaterialKind(value) {
282
+ if (typeof value === "number") {
283
+ return clamp(Math.trunc(value), MATERIAL_DIFFUSE, MATERIAL_EMISSIVE);
284
+ }
285
+ switch (value) {
286
+ case "metal":
287
+ case "reflective":
288
+ return MATERIAL_METAL;
289
+ case "dielectric":
290
+ case "refractive":
291
+ case "glass":
292
+ return MATERIAL_DIELECTRIC;
293
+ case "transparent":
294
+ case "transmission":
295
+ return MATERIAL_TRANSPARENT;
296
+ case "emissive":
297
+ case "light":
298
+ return MATERIAL_EMISSIVE;
299
+ case "diffuse":
300
+ default:
301
+ return MATERIAL_DIFFUSE;
302
+ }
303
+ }
304
+ function readObjectKind(value) {
305
+ if (typeof value === "number") {
306
+ return value === OBJECT_KIND_BOX ? OBJECT_KIND_BOX : OBJECT_KIND_SPHERE;
307
+ }
308
+ switch (value) {
309
+ case "box":
310
+ case "aabb":
311
+ case "bounds":
312
+ return OBJECT_KIND_BOX;
313
+ case "sphere":
314
+ default:
315
+ return OBJECT_KIND_SPHERE;
316
+ }
317
+ }
318
+ function deriveBounds(input) {
319
+ if (Array.isArray(input?.min) && Array.isArray(input?.max)) {
320
+ const min = asVec3(input.min, [-0.5, -0.5, -0.5]);
321
+ const max = asVec3(input.max, [0.5, 0.5, 0.5]);
322
+ return {
323
+ center: scale(add(min, max), 0.5),
324
+ halfExtent: scale(subtract(max, min), 0.5).map((value) => Math.max(value, 1e-3))
325
+ };
326
+ }
327
+ if (Array.isArray(input?.bounds?.min) && Array.isArray(input?.bounds?.max)) {
328
+ return deriveBounds(input.bounds);
329
+ }
330
+ return null;
331
+ }
332
+ function normalizeWavefrontSceneObject(input = {}, index = 0) {
333
+ const bounds = deriveBounds(input);
334
+ const kind = readObjectKind(input.kind ?? input.type ?? (bounds ? "box" : "sphere"));
335
+ const center = asVec3(input.center ?? input.position ?? bounds?.center, [0, 0, 0]);
336
+ const radius = readFiniteNumber("radius", input.radius, 0.5);
337
+ const halfExtent = kind === OBJECT_KIND_SPHERE ? [Math.max(radius, 1e-3), Math.max(radius, 1e-3), Math.max(radius, 1e-3)] : asVec3(
338
+ input.halfExtent ?? input.halfExtents ?? input.extents ?? bounds?.halfExtent,
339
+ [0.5, 0.5, 0.5]
340
+ ).map((value) => Math.max(value, 1e-3));
341
+ const materialKind = readMaterialKind(input.materialKind ?? input.material?.kind);
342
+ const color = asColor(
343
+ input.color ?? input.baseColor ?? input.albedo ?? input.material?.color ?? input.material?.baseColor,
344
+ [0.72, 0.72, 0.68, 1]
345
+ );
346
+ const emission = asColor(
347
+ input.emission ?? input.emissive ?? input.material?.emission ?? input.material?.emissive,
348
+ [0, 0, 0, 1]
349
+ );
350
+ return Object.freeze({
351
+ id: readNonNegativeInteger("id", input.id, index + 1),
352
+ kind,
353
+ materialKind: emission[0] > 0 || emission[1] > 0 || emission[2] > 0 ? MATERIAL_EMISSIVE : materialKind,
354
+ flags: readNonNegativeInteger("flags", input.flags, 0),
355
+ center: Object.freeze(center),
356
+ halfExtent: Object.freeze(halfExtent),
357
+ color: Object.freeze(color),
358
+ emission: Object.freeze(emission),
359
+ roughness: clamp(readFiniteNumber("roughness", input.roughness ?? input.material?.roughness, 0.72), 0, 1),
360
+ metallic: clamp(readFiniteNumber("metallic", input.metallic ?? input.material?.metallic, 0), 0, 1),
361
+ opacity: clamp(readFiniteNumber("opacity", input.opacity ?? input.material?.opacity, color[3] ?? 1), 0, 1),
362
+ ior: clamp(readFiniteNumber("ior", input.ior ?? input.material?.ior, 1.45), 1, 3)
363
+ });
364
+ }
365
+ function createDefaultWavefrontSceneObjects() {
366
+ return Object.freeze([
367
+ normalizeWavefrontSceneObject({
368
+ type: "box",
369
+ id: 1,
370
+ center: [0, -0.08, 0],
371
+ halfExtent: [3.25, 0.08, 3.25],
372
+ color: [0.45, 0.53, 0.54, 1],
373
+ roughness: 0.5
374
+ }),
375
+ normalizeWavefrontSceneObject({
376
+ type: "box",
377
+ id: 2,
378
+ center: [0, 1.25, -1.65],
379
+ halfExtent: [2.45, 1.45, 0.08],
380
+ color: [0.42, 0.41, 0.38, 1],
381
+ roughness: 0.85
382
+ }),
383
+ normalizeWavefrontSceneObject({
384
+ type: "sphere",
385
+ id: 3,
386
+ center: [-0.9, 0.72, 0.05],
387
+ radius: 0.72,
388
+ color: [0.76, 0.72, 0.64, 1],
389
+ materialKind: "metal",
390
+ roughness: 0.08,
391
+ metallic: 0.7
392
+ }),
393
+ normalizeWavefrontSceneObject({
394
+ type: "sphere",
395
+ id: 4,
396
+ center: [0.85, 0.65, -0.05],
397
+ radius: 0.58,
398
+ color: [0.68, 0.82, 0.86, 0.72],
399
+ materialKind: "dielectric",
400
+ roughness: 0.02,
401
+ opacity: 0.72,
402
+ ior: 1.35
403
+ }),
404
+ normalizeWavefrontSceneObject({
405
+ type: "sphere",
406
+ id: 5,
407
+ center: [0, 2.55, -0.65],
408
+ radius: 0.34,
409
+ color: [1, 0.94, 0.78, 1],
410
+ emission: [7.2, 6.5, 4.2, 1],
411
+ materialKind: "emissive"
412
+ })
413
+ ]);
414
+ }
415
+ function normalizeWavefrontMesh(input = {}, meshIndex = 0) {
416
+ const positions = input.positions;
417
+ const positionLength = getArrayLikeLength(positions);
418
+ if (positionLength < 9 || positionLength % 3 !== 0) {
419
+ throw new Error("Wavefront mesh positions must contain at least three vec3 vertices.");
420
+ }
421
+ const vertexCount = positionLength / 3;
422
+ const indices = getArrayLikeLength(input.indices) > 0 ? Array.from(input.indices, (value) => readNonNegativeInteger("mesh index", value, 0)) : Array.from({ length: vertexCount }, (_, index) => index);
423
+ if (indices.length < 3 || indices.length % 3 !== 0) {
424
+ throw new Error("Wavefront mesh indices must contain complete triangles.");
425
+ }
426
+ if (indices.some((index) => index >= vertexCount)) {
427
+ throw new Error("Wavefront mesh index references a vertex outside the position buffer.");
428
+ }
429
+ const normals = getArrayLikeLength(input.normals) >= positionLength ? Array.from(input.normals, (value) => readFiniteNumber("mesh normal", value, 0)) : null;
430
+ const uvs = getArrayLikeLength(input.uvs ?? input.texcoords ?? input.uv) >= vertexCount * 2 ? Array.from(
431
+ input.uvs ?? input.texcoords ?? input.uv,
432
+ (value) => readFiniteNumber("mesh uv", value, 0)
433
+ ) : null;
434
+ const materialKind = readMaterialKind(input.materialKind ?? input.material?.kind);
435
+ const color = asColor(
436
+ input.color ?? input.baseColor ?? input.albedo ?? input.material?.color ?? input.material?.baseColor,
437
+ [0.72, 0.72, 0.68, 1]
438
+ );
439
+ const emission = asColor(
440
+ input.emission ?? input.emissive ?? input.material?.emission ?? input.material?.emissive,
441
+ [0, 0, 0, 1]
442
+ );
443
+ return Object.freeze({
444
+ id: readNonNegativeInteger("mesh id", input.id, meshIndex + 1),
445
+ positions: Object.freeze(Array.from(positions, (value) => readFiniteNumber("mesh position", value, 0))),
446
+ indices: Object.freeze(indices),
447
+ normals: normals ? Object.freeze(normals) : null,
448
+ uvs: uvs ? Object.freeze(uvs) : null,
449
+ materialKind: emission[0] > 0 || emission[1] > 0 || emission[2] > 0 ? MATERIAL_EMISSIVE : materialKind,
450
+ flags: readNonNegativeInteger("mesh flags", input.flags, 0),
451
+ materialRefId: readNonNegativeInteger(
452
+ "mesh materialRefId",
453
+ input.materialRefId ?? input.material?.id ?? input.materialId,
454
+ meshIndex
455
+ ),
456
+ mediumRefId: readNonNegativeInteger(
457
+ "mesh mediumRefId",
458
+ input.mediumRefId ?? input.medium?.id ?? input.mediumId,
459
+ 0
460
+ ),
461
+ color: Object.freeze(color),
462
+ emission: Object.freeze(emission),
463
+ roughness: clamp(readFiniteNumber("roughness", input.roughness ?? input.material?.roughness, 0.72), 0, 1),
464
+ metallic: clamp(readFiniteNumber("metallic", input.metallic ?? input.material?.metallic, 0), 0, 1),
465
+ opacity: clamp(readFiniteNumber("opacity", input.opacity ?? input.material?.opacity, color[3] ?? 1), 0, 1),
466
+ ior: clamp(readFiniteNumber("ior", input.ior ?? input.material?.ior, 1.45), 1, 3)
467
+ });
468
+ }
469
+ function createMeshTriangleRecords(meshes) {
470
+ const source = Array.isArray(meshes) ? meshes : [];
471
+ let nextTriangleId = 0;
472
+ return source.flatMap((meshInput, meshIndex) => {
473
+ const mesh = normalizeWavefrontMesh(meshInput, meshIndex);
474
+ const triangles = [];
475
+ for (let index = 0; index < mesh.indices.length; index += 3) {
476
+ const a = mesh.indices[index];
477
+ const b = mesh.indices[index + 1];
478
+ const c = mesh.indices[index + 2];
479
+ const v0 = readVector(mesh.positions, a, 3, [0, 0, 0]);
480
+ const v1 = readVector(mesh.positions, b, 3, [0, 0, 0]);
481
+ const v2 = readVector(mesh.positions, c, 3, [0, 0, 0]);
482
+ const faceNormal = normalize(cross(subtract(v1, v0), subtract(v2, v0)), [0, 1, 0]);
483
+ const n0 = mesh.normals ? normalize(readVector(mesh.normals, a, 3, faceNormal), faceNormal) : faceNormal;
484
+ const n1 = mesh.normals ? normalize(readVector(mesh.normals, b, 3, faceNormal), faceNormal) : faceNormal;
485
+ const n2 = mesh.normals ? normalize(readVector(mesh.normals, c, 3, faceNormal), faceNormal) : faceNormal;
486
+ const uv0 = mesh.uvs ? readVector2(mesh.uvs, a) : [0, 0];
487
+ const uv1 = mesh.uvs ? readVector2(mesh.uvs, b) : [0, 0];
488
+ const uv2 = mesh.uvs ? readVector2(mesh.uvs, c) : [0, 0];
489
+ const bounds = triangleBounds(v0, v1, v2);
490
+ triangles.push(
491
+ Object.freeze({
492
+ triangleId: nextTriangleId,
493
+ meshId: mesh.id,
494
+ materialKind: mesh.materialKind,
495
+ flags: mesh.flags,
496
+ materialRefId: mesh.materialRefId,
497
+ mediumRefId: mesh.mediumRefId,
498
+ v0: Object.freeze(v0),
499
+ v1: Object.freeze(v1),
500
+ v2: Object.freeze(v2),
501
+ n0: Object.freeze(n0),
502
+ n1: Object.freeze(n1),
503
+ n2: Object.freeze(n2),
504
+ uv0: Object.freeze(uv0),
505
+ uv1: Object.freeze(uv1),
506
+ uv2: Object.freeze(uv2),
507
+ color: mesh.color,
508
+ emission: mesh.emission,
509
+ material: Object.freeze([mesh.roughness, mesh.metallic, mesh.opacity, mesh.ior]),
510
+ bounds: Object.freeze({
511
+ min: Object.freeze(bounds.min),
512
+ max: Object.freeze(bounds.max)
513
+ }),
514
+ centroid: Object.freeze(boundsCentroid(bounds))
515
+ })
516
+ );
517
+ nextTriangleId += 1;
518
+ }
519
+ return triangles;
520
+ });
521
+ }
522
+ function chooseSplitAxis(triangles) {
523
+ const centroidBounds = triangles.reduce(
524
+ (bounds, triangle) => {
525
+ const pointBounds = { min: triangle.centroid, max: triangle.centroid };
526
+ return mergeBounds(bounds, pointBounds);
527
+ },
528
+ null
529
+ );
530
+ const extent = subtract(centroidBounds.max, centroidBounds.min);
531
+ if (extent[0] >= extent[1] && extent[0] >= extent[2]) {
532
+ return 0;
533
+ }
534
+ return extent[1] >= extent[2] ? 1 : 2;
535
+ }
536
+ function buildBvh(triangles, maxLeafTriangles = 4) {
537
+ if (triangles.length === 0) {
538
+ return Object.freeze({ nodes: Object.freeze([]), triangles: Object.freeze([]) });
539
+ }
540
+ const nodes = [];
541
+ const orderedTriangles = [];
542
+ function buildNode(nodeTriangles) {
543
+ const nodeIndex = nodes.length;
544
+ nodes.push(null);
545
+ const bounds = nodeTriangles.reduce((current, triangle) => mergeBounds(current, triangle.bounds), null);
546
+ if (nodeTriangles.length <= maxLeafTriangles) {
547
+ const firstTriangle = orderedTriangles.length;
548
+ orderedTriangles.push(...nodeTriangles);
549
+ nodes[nodeIndex] = Object.freeze({
550
+ bounds: Object.freeze({
551
+ min: Object.freeze(bounds.min),
552
+ max: Object.freeze(bounds.max)
553
+ }),
554
+ firstTriangle,
555
+ triangleCount: nodeTriangles.length,
556
+ leftChild: 0,
557
+ rightChild: 0
558
+ });
559
+ return nodeIndex;
560
+ }
561
+ const axis = chooseSplitAxis(nodeTriangles);
562
+ const sorted = [...nodeTriangles].sort((left, right) => left.centroid[axis] - right.centroid[axis]);
563
+ const midpoint = Math.max(1, Math.floor(sorted.length / 2));
564
+ const leftChild = buildNode(sorted.slice(0, midpoint));
565
+ const rightChild = buildNode(sorted.slice(midpoint));
566
+ nodes[nodeIndex] = Object.freeze({
567
+ bounds: Object.freeze({
568
+ min: Object.freeze(bounds.min),
569
+ max: Object.freeze(bounds.max)
570
+ }),
571
+ firstTriangle: leftChild,
572
+ triangleCount: 0,
573
+ leftChild,
574
+ rightChild
575
+ });
576
+ return nodeIndex;
577
+ }
578
+ buildNode(triangles);
579
+ return Object.freeze({
580
+ nodes: Object.freeze(nodes),
581
+ triangles: Object.freeze(orderedTriangles)
582
+ });
583
+ }
584
+ function createWavefrontMeshAcceleration(meshes = []) {
585
+ const source = Array.isArray(meshes) ? meshes : [meshes];
586
+ const triangles = createMeshTriangleRecords(source);
587
+ return buildBvh(triangles);
588
+ }
589
+ function estimateMeshSourceShape(meshes) {
590
+ const source = Array.isArray(meshes) ? meshes : [];
591
+ return source.reduce(
592
+ (shape, meshInput, meshIndex) => {
593
+ const mesh = normalizeWavefrontMesh(meshInput, meshIndex);
594
+ return {
595
+ vertexCount: shape.vertexCount + mesh.positions.length / 3,
596
+ indexCount: shape.indexCount + mesh.indices.length,
597
+ meshCount: shape.meshCount + 1,
598
+ triangleCount: shape.triangleCount + mesh.indices.length / 3
599
+ };
600
+ },
601
+ {
602
+ vertexCount: 0,
603
+ indexCount: 0,
604
+ meshCount: 0,
605
+ triangleCount: 0
606
+ }
607
+ );
608
+ }
609
+ function estimateBinaryBvhNodeCapacity(triangleCount) {
610
+ return triangleCount <= 0 ? 0 : Math.max(1, triangleCount * 2 - 1);
611
+ }
612
+ function nextPowerOfTwo(value) {
613
+ if (value <= 1) {
614
+ return Math.max(0, value);
615
+ }
616
+ return 2 ** Math.ceil(Math.log2(value));
617
+ }
618
+ function estimateBvhLeafSortCapacity(triangleCount) {
619
+ return triangleCount <= 0 ? 0 : nextPowerOfTwo(triangleCount);
620
+ }
621
+ function createWavefrontBvhSortStages(itemCountInput) {
622
+ const itemCount = readNonNegativeInteger("itemCount", itemCountInput, 0);
623
+ const sortCount = estimateBvhLeafSortCapacity(itemCount);
624
+ if (sortCount <= 1) {
625
+ return Object.freeze([]);
626
+ }
627
+ const stages = [];
628
+ for (let sequenceSize = 2; sequenceSize <= sortCount; sequenceSize *= 2) {
629
+ for (let compareDistance = sequenceSize / 2; compareDistance >= 1; compareDistance /= 2) {
630
+ stages.push(
631
+ Object.freeze({
632
+ compareDistance,
633
+ sequenceSize
634
+ })
635
+ );
636
+ }
637
+ }
638
+ return Object.freeze(stages);
639
+ }
640
+ function createWavefrontBvhBuildLevels(triangleCountInput) {
641
+ const triangleCount = readNonNegativeInteger("triangleCount", triangleCountInput, 0);
642
+ const internalCount = Math.max(0, triangleCount - 1);
643
+ if (internalCount === 0) {
644
+ return Object.freeze([]);
645
+ }
646
+ const levels = [];
647
+ let depth = 0;
648
+ while (Math.pow(2, depth) - 1 < internalCount) {
649
+ depth += 1;
650
+ }
651
+ for (let level = depth - 1; level >= 0; level -= 1) {
652
+ const start = Math.pow(2, level) - 1;
653
+ const end = Math.min(Math.pow(2, level + 1) - 2, internalCount - 1);
654
+ if (end >= start) {
655
+ levels.push(
656
+ Object.freeze({
657
+ start,
658
+ count: end - start + 1
659
+ })
660
+ );
661
+ }
662
+ }
663
+ return Object.freeze(levels);
664
+ }
665
+ function resolveAccelerationBuildMode(options = {}) {
666
+ const mode = options.accelerationBuildMode ?? (options.displayQuality === true ? "gpu" : "cpu-debug");
667
+ if (mode !== "gpu" && mode !== "cpu-debug") {
668
+ throw new Error('accelerationBuildMode must be either "gpu" or "cpu-debug".');
669
+ }
670
+ if (options.displayQuality === true && mode !== "gpu") {
671
+ throw new Error("Display-quality path tracing requires GPU-built mesh acceleration.");
672
+ }
673
+ return mode;
674
+ }
675
+ function createWavefrontGpuMeshSource(meshes = []) {
676
+ const source = Array.isArray(meshes) ? meshes : [meshes];
677
+ const normalized = source.map((meshInput, meshIndex) => normalizeWavefrontMesh(meshInput, meshIndex));
678
+ const vertexCount = normalized.reduce((count, mesh) => count + mesh.positions.length / 3, 0);
679
+ const indexCount = normalized.reduce((count, mesh) => count + mesh.indices.length, 0);
680
+ const triangleCount = Math.floor(indexCount / 3);
681
+ const vertexBytes = new ArrayBuffer(Math.max(1, vertexCount) * MESH_VERTEX_RECORD_BYTES);
682
+ const indexBytes = new ArrayBuffer(Math.max(1, indexCount) * 4);
683
+ const meshBytes = new ArrayBuffer(Math.max(1, normalized.length) * MESH_RANGE_RECORD_BYTES);
684
+ const vertexFloats = new Float32Array(vertexBytes);
685
+ const indexUints = new Uint32Array(indexBytes);
686
+ const meshUints = new Uint32Array(meshBytes);
687
+ const meshFloats = new Float32Array(meshBytes);
688
+ let vertexCursor = 0;
689
+ let indexCursor = 0;
690
+ let triangleCursor = 0;
691
+ normalized.forEach((mesh, meshIndex) => {
692
+ const meshVertexBase = vertexCursor;
693
+ const meshIndexBase = indexCursor;
694
+ const meshTriangleBase = triangleCursor;
695
+ const meshVertexCount = mesh.positions.length / 3;
696
+ for (let vertexIndex = 0; vertexIndex < meshVertexCount; vertexIndex += 1) {
697
+ const recordOffset = (vertexCursor + vertexIndex) * (MESH_VERTEX_RECORD_BYTES / 4);
698
+ const position = readVector(mesh.positions, vertexIndex, 3, [0, 0, 0]);
699
+ const normal = mesh.normals ? readVector(mesh.normals, vertexIndex, 3, [0, 0, 0]) : [0, 0, 0];
700
+ const uv = mesh.uvs ? readVector2(mesh.uvs, vertexIndex) : [0, 0];
701
+ vertexFloats[recordOffset] = position[0];
702
+ vertexFloats[recordOffset + 1] = position[1];
703
+ vertexFloats[recordOffset + 2] = position[2];
704
+ vertexFloats[recordOffset + 3] = 1;
705
+ vertexFloats[recordOffset + 4] = normal[0];
706
+ vertexFloats[recordOffset + 5] = normal[1];
707
+ vertexFloats[recordOffset + 6] = normal[2];
708
+ vertexFloats[recordOffset + 7] = mesh.normals ? 1 : 0;
709
+ vertexFloats[recordOffset + 8] = uv[0];
710
+ vertexFloats[recordOffset + 9] = uv[1];
711
+ vertexFloats[recordOffset + 10] = mesh.uvs ? 1 : 0;
712
+ vertexFloats[recordOffset + 11] = 0;
713
+ }
714
+ mesh.indices.forEach((indexValue, localIndex) => {
715
+ indexUints[indexCursor + localIndex] = meshVertexBase + indexValue;
716
+ });
717
+ const meshOffset = meshIndex * (MESH_RANGE_RECORD_BYTES / 4);
718
+ meshUints[meshOffset] = mesh.id;
719
+ meshUints[meshOffset + 1] = mesh.materialKind;
720
+ meshUints[meshOffset + 2] = mesh.flags;
721
+ meshUints[meshOffset + 3] = mesh.materialRefId;
722
+ meshUints[meshOffset + 4] = mesh.mediumRefId;
723
+ meshUints[meshOffset + 5] = meshIndexBase;
724
+ meshUints[meshOffset + 6] = mesh.indices.length;
725
+ meshUints[meshOffset + 7] = meshTriangleBase;
726
+ meshUints[meshOffset + 8] = mesh.indices.length / 3;
727
+ meshUints[meshOffset + 9] = meshVertexBase;
728
+ meshUints[meshOffset + 10] = meshVertexCount;
729
+ meshUints[meshOffset + 11] = 0;
730
+ const floatOffset = meshOffset;
731
+ writeVec4(meshFloats, floatOffset * 4 + 48, mesh.color);
732
+ writeVec4(meshFloats, floatOffset * 4 + 64, mesh.emission);
733
+ writeVec4(meshFloats, floatOffset * 4 + 80, [
734
+ mesh.roughness,
735
+ mesh.metallic,
736
+ mesh.opacity,
737
+ mesh.ior
738
+ ]);
739
+ vertexCursor += meshVertexCount;
740
+ indexCursor += mesh.indices.length;
741
+ triangleCursor += mesh.indices.length / 3;
742
+ });
743
+ return Object.freeze({
744
+ vertices: Object.freeze({
745
+ buffer: vertexBytes,
746
+ count: vertexCount,
747
+ recordBytes: MESH_VERTEX_RECORD_BYTES
748
+ }),
749
+ indices: Object.freeze({
750
+ buffer: indexBytes,
751
+ count: indexCount,
752
+ recordBytes: 4
753
+ }),
754
+ meshes: Object.freeze({
755
+ buffer: meshBytes,
756
+ records: Object.freeze(normalized),
757
+ count: normalized.length,
758
+ recordBytes: MESH_RANGE_RECORD_BYTES
759
+ }),
760
+ triangleCount,
761
+ bvhNodeCapacity: estimateBinaryBvhNodeCapacity(triangleCount)
762
+ });
763
+ }
764
+ function createWavefrontEmissiveTriangleIndexSource(meshes = [], capacityInput) {
765
+ const source = Array.isArray(meshes) ? meshes : [meshes];
766
+ const normalized = source.map((meshInput, meshIndex) => normalizeWavefrontMesh(meshInput, meshIndex));
767
+ const indices = [];
768
+ let triangleCursor = 0;
769
+ normalized.forEach((mesh) => {
770
+ const triangleCount = Math.floor(mesh.indices.length / 3);
771
+ const isEmissive = mesh.materialKind === MATERIAL_EMISSIVE || emissionPower(mesh.emission) > 1e-4;
772
+ if (isEmissive) {
773
+ for (let triangleOffset = 0; triangleOffset < triangleCount; triangleOffset += 1) {
774
+ indices.push(triangleCursor + triangleOffset);
775
+ }
776
+ }
777
+ triangleCursor += triangleCount;
778
+ });
779
+ const capacity = Math.max(
780
+ indices.length,
781
+ readNonNegativeInteger("emissiveTriangleCapacity", capacityInput, indices.length)
782
+ );
783
+ const bytes = new ArrayBuffer(capacity * EMISSIVE_TRIANGLE_INDEX_BYTES);
784
+ const uints = new Uint32Array(bytes);
785
+ uints.fill(4294967295);
786
+ indices.forEach((triangleIndex, index) => {
787
+ uints[index] = triangleIndex;
788
+ });
789
+ return Object.freeze({
790
+ buffer: bytes,
791
+ indices: Object.freeze(indices),
792
+ count: indices.length,
793
+ capacity,
794
+ recordBytes: EMISSIVE_TRIANGLE_INDEX_BYTES
795
+ });
796
+ }
797
+ function normalizeSceneObjects(sceneObjects, useDefaultScene = true) {
798
+ const source = Array.isArray(sceneObjects) && sceneObjects.length > 0 ? sceneObjects : useDefaultScene ? createDefaultWavefrontSceneObjects() : [];
799
+ return source.map((object, index) => normalizeWavefrontSceneObject(object, index));
800
+ }
801
+ function normalizeMeshes(options = {}) {
802
+ if (Array.isArray(options.meshes)) {
803
+ return options.meshes;
804
+ }
805
+ if (options.mesh) {
806
+ return [options.mesh];
807
+ }
808
+ return [];
809
+ }
810
+ function resolveEnvironmentLighting(input, environmentColor, ambientColor) {
811
+ const source = input ?? {};
812
+ return Object.freeze({
813
+ environmentColor: Object.freeze(asColor(source.environmentColor, environmentColor)),
814
+ ambientColor: Object.freeze(asColor(source.ambientColor, ambientColor)),
815
+ horizonColor: Object.freeze(asColor(source.horizonColor, environmentColor)),
816
+ zenithColor: Object.freeze(asColor(source.zenithColor, DEFAULT_ENVIRONMENT_LIGHTING.zenithColor)),
817
+ sunDirection: Object.freeze(asUnitVec3(source.sunDirection, DEFAULT_ENVIRONMENT_LIGHTING.sunDirection)),
818
+ sunColor: Object.freeze(asColor(source.sunColor, DEFAULT_ENVIRONMENT_LIGHTING.sunColor)),
819
+ intensity: Math.max(1e-4, readFiniteNumber("environmentLighting.intensity", source.intensity, DEFAULT_ENVIRONMENT_LIGHTING.intensity)),
820
+ mode: readNonNegativeInteger("environmentLighting.mode", source.mode, DEFAULT_ENVIRONMENT_LIGHTING.mode),
821
+ exposure: Math.max(1e-4, readFiniteNumber("environmentLighting.exposure", source.exposure, DEFAULT_ENVIRONMENT_LIGHTING.exposure))
822
+ });
823
+ }
824
+ function getCanvasDimension(canvas, key, fallback) {
825
+ const value = Number(canvas?.[key]);
826
+ if (Number.isFinite(value) && value > 0) {
827
+ return Math.trunc(value);
828
+ }
829
+ return fallback;
830
+ }
831
+ function resolveCamera(input, width, height) {
832
+ const camera = input ?? DEFAULT_CAMERA;
833
+ const position = asVec3(camera.position, DEFAULT_CAMERA.position);
834
+ const target = asVec3(camera.target, DEFAULT_CAMERA.target);
835
+ const upInput = normalize(asVec3(camera.up, DEFAULT_CAMERA.up), DEFAULT_CAMERA.up);
836
+ const forward = normalize(subtract(target, position), [0, 0, -1]);
837
+ const right = normalize(cross(forward, upInput), [1, 0, 0]);
838
+ const up = normalize(cross(right, forward), [0, 1, 0]);
839
+ const fovYDegrees = clamp(
840
+ readFiniteNumber("camera.fovYDegrees", camera.fovYDegrees ?? camera.fov, DEFAULT_CAMERA.fovYDegrees),
841
+ 10,
842
+ 120
843
+ );
844
+ const aspect = width / Math.max(1, height);
845
+ const tanHalfFovY = Math.tan(fovYDegrees * Math.PI / 360);
846
+ return Object.freeze({
847
+ position: Object.freeze(position),
848
+ forward: Object.freeze(forward),
849
+ right: Object.freeze(right),
850
+ up: Object.freeze(up),
851
+ fovYDegrees,
852
+ aspect,
853
+ tanHalfFovY
854
+ });
855
+ }
856
+ function estimateWavefrontPathTracingMemory(options = {}) {
857
+ const tilePixelCapacity = readPositiveInteger(
858
+ "tilePixelCapacity",
859
+ options.tilePixelCapacity,
860
+ DEFAULT_TILE_SIZE * DEFAULT_TILE_SIZE
861
+ );
862
+ const sceneObjectCapacity = readPositiveInteger(
863
+ "sceneObjectCapacity",
864
+ options.sceneObjectCapacity,
865
+ DEFAULT_SCENE_OBJECT_CAPACITY
866
+ );
867
+ const triangleCapacity = readNonNegativeInteger("triangleCapacity", options.triangleCapacity, 0);
868
+ const bvhNodeCapacity = readNonNegativeInteger("bvhNodeCapacity", options.bvhNodeCapacity, 0);
869
+ const bvhLeafSortCapacity = readNonNegativeInteger(
870
+ "bvhLeafSortCapacity",
871
+ options.bvhLeafSortCapacity,
872
+ 0
873
+ );
874
+ const emissiveTriangleCapacity = readNonNegativeInteger(
875
+ "emissiveTriangleCapacity",
876
+ options.emissiveTriangleCapacity,
877
+ 0
878
+ );
879
+ const queueBytes = tilePixelCapacity * RAY_RECORD_BYTES;
880
+ const hitBytes = tilePixelCapacity * HIT_RECORD_BYTES;
881
+ const accumulationBytes = tilePixelCapacity * ACCUMULATION_RECORD_BYTES;
882
+ const sceneObjectBytes = sceneObjectCapacity * SCENE_OBJECT_RECORD_BYTES;
883
+ const triangleBytes = triangleCapacity * TRIANGLE_RECORD_BYTES;
884
+ const bvhNodeBytes = bvhNodeCapacity * BVH_NODE_RECORD_BYTES;
885
+ const bvhLeafReferenceBytes = bvhLeafSortCapacity * BVH_LEAF_REF_RECORD_BYTES;
886
+ const emissiveTriangleMetadataBytes = emissiveTriangleCapacity * BVH_NODE_RECORD_BYTES;
887
+ return Object.freeze({
888
+ queueBytes,
889
+ queuePairBytes: queueBytes * 2,
890
+ hitBytes,
891
+ accumulationBytes,
892
+ sceneObjectBytes,
893
+ triangleBytes,
894
+ bvhNodeBytes,
895
+ bvhLeafReferenceBytes,
896
+ emissiveTriangleMetadataBytes,
897
+ configBytes: CONFIG_BUFFER_BYTES,
898
+ counterBytes: COUNTER_BUFFER_BYTES,
899
+ totalHotBufferBytes: queueBytes * 2 + hitBytes + accumulationBytes + sceneObjectBytes + triangleBytes + bvhNodeBytes + bvhLeafReferenceBytes + emissiveTriangleMetadataBytes + CONFIG_BUFFER_BYTES + COUNTER_BUFFER_BYTES
900
+ });
901
+ }
902
+ function createWavefrontPathTracingComputeConfig(options = {}) {
903
+ assertAnalyticDisplayQualityPolicy(options);
904
+ const accelerationBuildMode = resolveAccelerationBuildMode(options);
905
+ const canvas = options.canvas;
906
+ const width = readPositiveInteger("width", options.width, getCanvasDimension(canvas, "width", DEFAULT_WIDTH));
907
+ const height = readPositiveInteger("height", options.height, getCanvasDimension(canvas, "height", DEFAULT_HEIGHT));
908
+ const maxDepth = clamp(readPositiveInteger("maxDepth", options.maxDepth, DEFAULT_MAX_DEPTH), 1, 16);
909
+ const tileSize = clamp(readPositiveInteger("tileSize", options.tileSize, DEFAULT_TILE_SIZE), 16, 512);
910
+ const samplesPerPixel = clamp(
911
+ readPositiveInteger("samplesPerPixel", options.samplesPerPixel, DEFAULT_SAMPLES_PER_PIXEL),
912
+ 1,
913
+ 64
914
+ );
915
+ const tilePixelCapacity = readPositiveInteger(
916
+ "tilePixelCapacity",
917
+ options.tilePixelCapacity,
918
+ tileSize * tileSize
919
+ );
920
+ const meshes = normalizeMeshes(options);
921
+ const meshSourceShape = estimateMeshSourceShape(meshes);
922
+ const gpuMeshSource = meshes.length > 0 ? createWavefrontGpuMeshSource(meshes) : createWavefrontGpuMeshSource([]);
923
+ const meshAcceleration = accelerationBuildMode === "cpu-debug" ? createWavefrontMeshAcceleration(meshes) : Object.freeze({ nodes: Object.freeze([]), triangles: Object.freeze([]) });
924
+ const emissiveTriangleIndices = createWavefrontEmissiveTriangleIndexSource(
925
+ meshes,
926
+ options.emissiveTriangleCapacity
927
+ );
928
+ const triangleCount = accelerationBuildMode === "gpu" ? meshSourceShape.triangleCount : meshAcceleration.triangles.length;
929
+ const bvhNodeCount = accelerationBuildMode === "gpu" ? estimateBinaryBvhNodeCapacity(triangleCount) : meshAcceleration.nodes.length;
930
+ const sceneObjects = Object.freeze(
931
+ normalizeSceneObjects(options.sceneObjects, meshes.length === 0)
932
+ );
933
+ const sceneObjectCapacity = Math.max(
934
+ sceneObjects.length,
935
+ readPositiveInteger("sceneObjectCapacity", options.sceneObjectCapacity, DEFAULT_SCENE_OBJECT_CAPACITY)
936
+ );
937
+ const triangleCapacity = Math.max(
938
+ triangleCount,
939
+ readNonNegativeInteger("triangleCapacity", options.triangleCapacity, triangleCount)
940
+ );
941
+ const bvhNodeCapacity = Math.max(
942
+ accelerationBuildMode === "gpu" ? estimateBinaryBvhNodeCapacity(triangleCount) : bvhNodeCount,
943
+ readNonNegativeInteger(
944
+ "bvhNodeCapacity",
945
+ options.bvhNodeCapacity,
946
+ accelerationBuildMode === "gpu" ? estimateBinaryBvhNodeCapacity(triangleCount) : bvhNodeCount
947
+ )
948
+ );
949
+ const bvhLeafSortCapacity = accelerationBuildMode === "gpu" ? estimateBvhLeafSortCapacity(triangleCount) : 0;
950
+ const bvhSortStages = accelerationBuildMode === "gpu" ? createWavefrontBvhSortStages(triangleCount) : Object.freeze([]);
951
+ const bvhBuildLevels = accelerationBuildMode === "gpu" ? createWavefrontBvhBuildLevels(triangleCount) : Object.freeze([]);
952
+ const camera = resolveCamera(options.camera, width, height);
953
+ const environmentColor = Object.freeze(asColor(options.environmentColor, DEFAULT_ENVIRONMENT_COLOR));
954
+ const ambientColor = Object.freeze(asColor(options.ambientColor, DEFAULT_AMBIENT_COLOR));
955
+ const environmentLighting = resolveEnvironmentLighting(
956
+ options.environmentLighting,
957
+ environmentColor,
958
+ ambientColor
959
+ );
960
+ return Object.freeze({
961
+ width,
962
+ height,
963
+ maxDepth,
964
+ tileSize,
965
+ samplesPerPixel,
966
+ tilePixelCapacity,
967
+ sceneObjects,
968
+ sceneObjectCount: sceneObjects.length,
969
+ sceneObjectCapacity,
970
+ accelerationBuildMode,
971
+ gpuAccelerationBuildRequired: accelerationBuildMode === "gpu" && triangleCount > 0,
972
+ gpuMeshSource,
973
+ meshAcceleration,
974
+ emissiveTriangleIndices,
975
+ emissiveTriangleCount: emissiveTriangleIndices.count,
976
+ emissiveTriangleCapacity: emissiveTriangleIndices.capacity,
977
+ triangleCount,
978
+ triangleCapacity,
979
+ bvhNodeCount,
980
+ bvhNodeCapacity,
981
+ bvhLeafSortCapacity,
982
+ bvhSortStages,
983
+ bvhBuildLevels,
984
+ camera,
985
+ environmentColor: environmentLighting.environmentColor,
986
+ ambientColor: environmentLighting.ambientColor,
987
+ environmentLighting,
988
+ displayQuality: options.displayQuality === true,
989
+ requiresMeshBvhForDisplayQuality: true,
990
+ denoise: options.denoise !== false,
991
+ frameIndex: readNonNegativeInteger("frameIndex", options.frameIndex, 0),
992
+ memory: estimateWavefrontPathTracingMemory({
993
+ tilePixelCapacity,
994
+ sceneObjectCapacity,
995
+ triangleCapacity,
996
+ bvhNodeCapacity,
997
+ bvhLeafSortCapacity,
998
+ emissiveTriangleCapacity: emissiveTriangleIndices.capacity
999
+ })
1000
+ });
1001
+ }
1002
+ function supportsWavefrontPathTracingCompute(options = {}) {
1003
+ const navigatorRef = options.navigator ?? globalThis.navigator;
1004
+ return typeof navigatorRef?.gpu?.requestAdapter === "function";
1005
+ }
1006
+ function getGpuUsageConstants() {
1007
+ if (typeof GPUBufferUsage === "undefined" || typeof GPUTextureUsage === "undefined" || typeof GPUShaderStage === "undefined") {
1008
+ throw new Error("WebGPU runtime unavailable. Required GPU constants are missing.");
1009
+ }
1010
+ return {
1011
+ buffer: GPUBufferUsage,
1012
+ texture: GPUTextureUsage,
1013
+ shader: GPUShaderStage,
1014
+ map: typeof GPUMapMode === "undefined" ? null : GPUMapMode
1015
+ };
1016
+ }
1017
+ function resolveCanvas(canvasOrSelector, documentRef = globalThis.document) {
1018
+ if (typeof canvasOrSelector === "string") {
1019
+ const resolved = documentRef?.querySelector?.(canvasOrSelector);
1020
+ if (!resolved) {
1021
+ throw new Error(`Unable to find canvas for selector: ${canvasOrSelector}`);
1022
+ }
1023
+ return resolved;
1024
+ }
1025
+ if (canvasOrSelector?.getContext) {
1026
+ return canvasOrSelector;
1027
+ }
1028
+ const fallback = documentRef?.querySelector?.("canvas[data-plasius-wavefront-path-tracing]");
1029
+ if (!fallback) {
1030
+ throw new Error("A canvas is required for WebGPU wavefront path tracing.");
1031
+ }
1032
+ return fallback;
1033
+ }
1034
+ function writeVec4(floatView, byteOffset, value) {
1035
+ const index = byteOffset / 4;
1036
+ floatView[index] = value[0] ?? 0;
1037
+ floatView[index + 1] = value[1] ?? 0;
1038
+ floatView[index + 2] = value[2] ?? 0;
1039
+ floatView[index + 3] = value[3] ?? 0;
1040
+ }
1041
+ function packWavefrontSceneObjects(sceneObjects, capacity = sceneObjects.length) {
1042
+ const normalized = Array.isArray(sceneObjects) && sceneObjects.length === 0 ? [] : normalizeSceneObjects(sceneObjects);
1043
+ if (normalized.length > capacity) {
1044
+ throw new Error(
1045
+ `Scene object capacity ${capacity} is too small for ${normalized.length} objects.`
1046
+ );
1047
+ }
1048
+ const bytes = new ArrayBuffer(Math.max(1, capacity) * SCENE_OBJECT_RECORD_BYTES);
1049
+ const uintView = new Uint32Array(bytes);
1050
+ const floatView = new Float32Array(bytes);
1051
+ normalized.forEach((object, index) => {
1052
+ const byteOffset = index * SCENE_OBJECT_RECORD_BYTES;
1053
+ const u32 = byteOffset / 4;
1054
+ uintView[u32] = object.kind;
1055
+ uintView[u32 + 1] = object.id;
1056
+ uintView[u32 + 2] = object.materialKind;
1057
+ uintView[u32 + 3] = object.flags;
1058
+ writeVec4(floatView, byteOffset + 16, [...object.center, 0]);
1059
+ writeVec4(floatView, byteOffset + 32, [...object.halfExtent, 0]);
1060
+ writeVec4(floatView, byteOffset + 48, object.color);
1061
+ writeVec4(floatView, byteOffset + 64, object.emission);
1062
+ writeVec4(floatView, byteOffset + 80, [
1063
+ object.roughness,
1064
+ object.metallic,
1065
+ object.opacity,
1066
+ object.ior
1067
+ ]);
1068
+ });
1069
+ return Object.freeze({
1070
+ buffer: bytes,
1071
+ objects: Object.freeze(normalized),
1072
+ count: normalized.length,
1073
+ capacity
1074
+ });
1075
+ }
1076
+ function packWavefrontTriangles(triangles, capacity = triangles.length) {
1077
+ if (triangles.length > capacity) {
1078
+ throw new Error(`Triangle capacity ${capacity} is too small for ${triangles.length} triangles.`);
1079
+ }
1080
+ const bytes = new ArrayBuffer(Math.max(1, capacity) * TRIANGLE_RECORD_BYTES);
1081
+ const uintView = new Uint32Array(bytes);
1082
+ const floatView = new Float32Array(bytes);
1083
+ triangles.forEach((triangle, index) => {
1084
+ const byteOffset = index * TRIANGLE_RECORD_BYTES;
1085
+ const u32 = byteOffset / 4;
1086
+ uintView[u32] = triangle.triangleId;
1087
+ uintView[u32 + 1] = triangle.meshId;
1088
+ uintView[u32 + 2] = triangle.materialKind;
1089
+ uintView[u32 + 3] = triangle.flags;
1090
+ uintView[u32 + 4] = triangle.materialRefId;
1091
+ uintView[u32 + 5] = triangle.mediumRefId;
1092
+ uintView[u32 + 6] = 0;
1093
+ uintView[u32 + 7] = 0;
1094
+ writeVec4(floatView, byteOffset + 32, [...triangle.v0, 0]);
1095
+ writeVec4(floatView, byteOffset + 48, [...triangle.v1, 0]);
1096
+ writeVec4(floatView, byteOffset + 64, [...triangle.v2, 0]);
1097
+ writeVec4(floatView, byteOffset + 80, [...triangle.n0, 0]);
1098
+ writeVec4(floatView, byteOffset + 96, [...triangle.n1, 0]);
1099
+ writeVec4(floatView, byteOffset + 112, [...triangle.n2, 0]);
1100
+ writeVec4(floatView, byteOffset + 128, [...triangle.uv0, ...triangle.uv1]);
1101
+ writeVec4(floatView, byteOffset + 144, [...triangle.uv2, 0, 0]);
1102
+ writeVec4(floatView, byteOffset + 160, triangle.color);
1103
+ writeVec4(floatView, byteOffset + 176, triangle.emission);
1104
+ writeVec4(floatView, byteOffset + 192, triangle.material);
1105
+ });
1106
+ return Object.freeze({
1107
+ buffer: bytes,
1108
+ triangles: Object.freeze(triangles),
1109
+ count: triangles.length,
1110
+ capacity
1111
+ });
1112
+ }
1113
+ function packWavefrontBvhNodes(nodes, capacity = nodes.length) {
1114
+ if (nodes.length > capacity) {
1115
+ throw new Error(`BVH node capacity ${capacity} is too small for ${nodes.length} nodes.`);
1116
+ }
1117
+ const bytes = new ArrayBuffer(Math.max(1, capacity) * BVH_NODE_RECORD_BYTES);
1118
+ const uintView = new Uint32Array(bytes);
1119
+ const floatView = new Float32Array(bytes);
1120
+ nodes.forEach((node, index) => {
1121
+ const byteOffset = index * BVH_NODE_RECORD_BYTES;
1122
+ const u32 = byteOffset / 4;
1123
+ writeVec4(floatView, byteOffset, [...node.bounds.min, 0]);
1124
+ writeVec4(floatView, byteOffset + 16, [...node.bounds.max, 0]);
1125
+ uintView[u32 + 8] = node.triangleCount > 0 ? node.firstTriangle : node.leftChild;
1126
+ uintView[u32 + 9] = node.triangleCount;
1127
+ uintView[u32 + 10] = node.rightChild;
1128
+ uintView[u32 + 11] = 0;
1129
+ });
1130
+ return Object.freeze({
1131
+ buffer: bytes,
1132
+ nodes: Object.freeze(nodes),
1133
+ count: nodes.length,
1134
+ capacity
1135
+ });
1136
+ }
1137
+ function createConfigPayload(config, tile, frameIndex, buildRange = {}) {
1138
+ const bytes = new ArrayBuffer(CONFIG_BUFFER_BYTES);
1139
+ const data = new DataView(bytes);
1140
+ const floatView = new Float32Array(bytes);
1141
+ const sampleIndex = buildRange.sampleIndex ?? 0;
1142
+ const sampleWeight = buildRange.sampleWeight ?? 1;
1143
+ data.setUint32(0, config.width, true);
1144
+ data.setUint32(4, config.height, true);
1145
+ data.setUint32(8, tile.x, true);
1146
+ data.setUint32(12, tile.y, true);
1147
+ data.setUint32(16, tile.width, true);
1148
+ data.setUint32(20, tile.height, true);
1149
+ data.setUint32(24, tile.width * tile.height, true);
1150
+ data.setUint32(28, config.maxDepth, true);
1151
+ data.setUint32(32, config.sceneObjectCount, true);
1152
+ data.setUint32(36, frameIndex, true);
1153
+ data.setUint32(40, config.denoise ? 1 : 0, true);
1154
+ data.setUint32(44, config.triangleCount, true);
1155
+ data.setUint32(48, config.bvhNodeCount, true);
1156
+ data.setUint32(52, config.displayQuality ? 1 : 0, true);
1157
+ data.setUint32(56, config.gpuMeshSource.meshes.count, true);
1158
+ data.setUint32(60, config.bvhNodeCapacity, true);
1159
+ writeVec4(floatView, 64, [...config.camera.position, 1]);
1160
+ writeVec4(floatView, 80, [...config.camera.forward, 0]);
1161
+ writeVec4(floatView, 96, [...config.camera.right, 0]);
1162
+ writeVec4(floatView, 112, [...config.camera.up, 0]);
1163
+ writeVec4(floatView, 128, [
1164
+ config.camera.tanHalfFovY,
1165
+ config.camera.aspect,
1166
+ sampleWeight,
1167
+ sampleIndex
1168
+ ]);
1169
+ writeVec4(floatView, 144, config.environmentColor);
1170
+ writeVec4(floatView, 160, config.ambientColor);
1171
+ writeVec4(floatView, 176, config.environmentLighting.horizonColor);
1172
+ writeVec4(floatView, 192, config.environmentLighting.zenithColor);
1173
+ writeVec4(floatView, 208, [
1174
+ ...config.environmentLighting.sunDirection,
1175
+ config.environmentLighting.intensity
1176
+ ]);
1177
+ writeVec4(floatView, 224, config.environmentLighting.sunColor);
1178
+ data.setUint32(240, buildRange.start ?? 0, true);
1179
+ data.setUint32(244, buildRange.count ?? 0, true);
1180
+ data.setUint32(248, buildRange.sortItemCount ?? 0, true);
1181
+ data.setUint32(252, config.emissiveTriangleCount ?? 0, true);
1182
+ return bytes;
1183
+ }
1184
+ function createTiles(width, height, tileSize) {
1185
+ const tiles = [];
1186
+ for (let y = 0; y < height; y += tileSize) {
1187
+ for (let x = 0; x < width; x += tileSize) {
1188
+ tiles.push(
1189
+ Object.freeze({
1190
+ x,
1191
+ y,
1192
+ width: Math.min(tileSize, width - x),
1193
+ height: Math.min(tileSize, height - y)
1194
+ })
1195
+ );
1196
+ }
1197
+ }
1198
+ return Object.freeze(tiles);
1199
+ }
1200
+ function clampTileSizeForDevice(config, device) {
1201
+ const limit = Number(device?.limits?.maxStorageBufferBindingSize);
1202
+ if (!Number.isFinite(limit) || limit <= 0) {
1203
+ return config.tileSize;
1204
+ }
1205
+ const maxPixelsByRay = Math.floor(limit / RAY_RECORD_BYTES);
1206
+ const maxPixelsByHit = Math.floor(limit / HIT_RECORD_BYTES);
1207
+ const maxPixels = Math.max(256, Math.min(maxPixelsByRay, maxPixelsByHit));
1208
+ if (config.tilePixelCapacity <= maxPixels) {
1209
+ return config.tileSize;
1210
+ }
1211
+ return Math.max(16, Math.floor(Math.sqrt(maxPixels)));
1212
+ }
1213
+ function createBuffer(device, usage, size, label) {
1214
+ return device.createBuffer({
1215
+ label,
1216
+ size: Math.max(4, size),
1217
+ usage
1218
+ });
1219
+ }
1220
+ function alignTo(value, alignment) {
1221
+ const resolvedAlignment = Math.max(1, alignment);
1222
+ return Math.ceil(value / resolvedAlignment) * resolvedAlignment;
1223
+ }
1224
+ async function getPipelineDiagnostics(shaderModule) {
1225
+ if (typeof shaderModule?.compilationInfo !== "function") {
1226
+ return "";
1227
+ }
1228
+ try {
1229
+ const info = await shaderModule.compilationInfo();
1230
+ const messages = info.messages ?? [];
1231
+ if (messages.length === 0) {
1232
+ return "";
1233
+ }
1234
+ return messages.map((message) => {
1235
+ const line = message.lineNum ?? "?";
1236
+ const column = message.linePos ?? "?";
1237
+ return `line ${line}:${column} ${message.message}`;
1238
+ }).join("\n");
1239
+ } catch {
1240
+ return "";
1241
+ }
1242
+ }
1243
+ async function createComputePipeline(device, shaderModule, layout, entryPoint, label) {
1244
+ const descriptor = {
1245
+ label,
1246
+ layout,
1247
+ compute: {
1248
+ module: shaderModule,
1249
+ entryPoint
1250
+ }
1251
+ };
1252
+ try {
1253
+ if (typeof device.createComputePipelineAsync === "function") {
1254
+ return await device.createComputePipelineAsync(descriptor);
1255
+ }
1256
+ return device.createComputePipeline(descriptor);
1257
+ } catch (error) {
1258
+ const diagnostics = await getPipelineDiagnostics(shaderModule);
1259
+ const suffix = diagnostics ? `
1260
+ ${diagnostics}` : "";
1261
+ throw new Error(`WGSL compilation failed for ${label}: ${error.message}${suffix}`, {
1262
+ cause: error
1263
+ });
1264
+ }
1265
+ }
1266
+ async function createRenderPipeline(device, descriptor) {
1267
+ if (typeof device.createRenderPipelineAsync === "function") {
1268
+ return device.createRenderPipelineAsync(descriptor);
1269
+ }
1270
+ return device.createRenderPipeline(descriptor);
1271
+ }
1272
+ var WAVEFRONT_COMPUTE_WGSL = `
1273
+ const RAY_FLAG_GUIDED_EMISSIVE: u32 = 1u;
1274
+
1275
+ struct RayRecord {
1276
+ rayId: u32,
1277
+ parentRayId: u32,
1278
+ sourcePixelId: u32,
1279
+ sampleId: u32,
1280
+ bounce: u32,
1281
+ mediumRefId: u32,
1282
+ flags: u32,
1283
+ pad0: u32,
1284
+ origin: vec4<f32>,
1285
+ direction: vec4<f32>,
1286
+ throughput: vec4<f32>,
1287
+ };
1288
+
1289
+ struct HitRecord {
1290
+ rayId: u32,
1291
+ sourcePixelId: u32,
1292
+ hitType: u32,
1293
+ objectId: u32,
1294
+ materialKind: u32,
1295
+ frontFace: u32,
1296
+ primitiveId: u32,
1297
+ materialRefId: u32,
1298
+ mediumRefId: u32,
1299
+ pad0: u32,
1300
+ pad1: u32,
1301
+ pad2: u32,
1302
+ distance: f32,
1303
+ pad3: vec3<f32>,
1304
+ position: vec4<f32>,
1305
+ geometricNormal: vec4<f32>,
1306
+ shadingNormal: vec4<f32>,
1307
+ barycentric: vec4<f32>,
1308
+ uv: vec4<f32>,
1309
+ color: vec4<f32>,
1310
+ emission: vec4<f32>,
1311
+ material: vec4<f32>,
1312
+ };
1313
+
1314
+ struct SceneObject {
1315
+ kind: u32,
1316
+ objectId: u32,
1317
+ materialKind: u32,
1318
+ flags: u32,
1319
+ center: vec4<f32>,
1320
+ halfExtent: vec4<f32>,
1321
+ color: vec4<f32>,
1322
+ emission: vec4<f32>,
1323
+ material: vec4<f32>,
1324
+ };
1325
+
1326
+ struct TriangleRecord {
1327
+ triangleId: u32,
1328
+ meshId: u32,
1329
+ materialKind: u32,
1330
+ flags: u32,
1331
+ materialRefId: u32,
1332
+ mediumRefId: u32,
1333
+ pad0: u32,
1334
+ pad1: u32,
1335
+ v0: vec4<f32>,
1336
+ v1: vec4<f32>,
1337
+ v2: vec4<f32>,
1338
+ n0: vec4<f32>,
1339
+ n1: vec4<f32>,
1340
+ n2: vec4<f32>,
1341
+ uv0uv1: vec4<f32>,
1342
+ uv2Pad: vec4<f32>,
1343
+ color: vec4<f32>,
1344
+ emission: vec4<f32>,
1345
+ material: vec4<f32>,
1346
+ };
1347
+
1348
+ struct BvhNode {
1349
+ boundsMin: vec4<f32>,
1350
+ boundsMax: vec4<f32>,
1351
+ childOrFirst: u32,
1352
+ triangleCount: u32,
1353
+ rightChild: u32,
1354
+ pad0: u32,
1355
+ };
1356
+
1357
+ struct BvhLeafRef {
1358
+ key: u32,
1359
+ triangleIndex: u32,
1360
+ pad0: u32,
1361
+ pad1: u32,
1362
+ };
1363
+
1364
+ struct ScatterResult {
1365
+ direction: vec4<f32>,
1366
+ flags: u32,
1367
+ pad0: u32,
1368
+ pad1: u32,
1369
+ pad2: u32,
1370
+ };
1371
+
1372
+ struct MeshVertex {
1373
+ position: vec4<f32>,
1374
+ normal: vec4<f32>,
1375
+ uv: vec4<f32>,
1376
+ };
1377
+
1378
+ struct MeshRange {
1379
+ meshId: u32,
1380
+ materialKind: u32,
1381
+ flags: u32,
1382
+ materialRefId: u32,
1383
+ mediumRefId: u32,
1384
+ firstIndex: u32,
1385
+ indexCount: u32,
1386
+ firstTriangle: u32,
1387
+ triangleCount: u32,
1388
+ firstVertex: u32,
1389
+ vertexCount: u32,
1390
+ pad0: u32,
1391
+ color: vec4<f32>,
1392
+ emission: vec4<f32>,
1393
+ material: vec4<f32>,
1394
+ };
1395
+
1396
+ struct FrameConfig {
1397
+ canvasWidth: u32,
1398
+ canvasHeight: u32,
1399
+ tileX: u32,
1400
+ tileY: u32,
1401
+ tileWidth: u32,
1402
+ tileHeight: u32,
1403
+ tilePixelCount: u32,
1404
+ maxDepth: u32,
1405
+ sceneObjectCount: u32,
1406
+ frameIndex: u32,
1407
+ denoise: u32,
1408
+ triangleCount: u32,
1409
+ bvhNodeCount: u32,
1410
+ displayQuality: u32,
1411
+ meshSourceCount: u32,
1412
+ bvhNodeCapacity: u32,
1413
+ cameraPosition: vec4<f32>,
1414
+ cameraForward: vec4<f32>,
1415
+ cameraRight: vec4<f32>,
1416
+ cameraUp: vec4<f32>,
1417
+ projectionAndSampling: vec4<f32>,
1418
+ environmentColor: vec4<f32>,
1419
+ ambientColor: vec4<f32>,
1420
+ environmentHorizonColor: vec4<f32>,
1421
+ environmentZenithColor: vec4<f32>,
1422
+ environmentSunDirectionIntensity: vec4<f32>,
1423
+ environmentSunColor: vec4<f32>,
1424
+ bvhBuildNodeStart: u32,
1425
+ bvhBuildNodeCount: u32,
1426
+ bvhSortItemCount: u32,
1427
+ emissiveTriangleCount: u32,
1428
+ };
1429
+
1430
+ struct Counters {
1431
+ activeCount: atomic<u32>,
1432
+ nextCount: atomic<u32>,
1433
+ terminatedCount: atomic<u32>,
1434
+ hitCount: atomic<u32>,
1435
+ };
1436
+
1437
+ struct Candidate {
1438
+ hit: u32,
1439
+ distance: f32,
1440
+ geometricNormal: vec3<f32>,
1441
+ shadingNormal: vec3<f32>,
1442
+ barycentric: vec3<f32>,
1443
+ uv: vec2<f32>,
1444
+ frontFace: u32,
1445
+ triangleIndex: u32,
1446
+ primitiveId: u32,
1447
+ materialRefId: u32,
1448
+ mediumRefId: u32,
1449
+ };
1450
+
1451
+ @group(0) @binding(0) var<storage, read_write> activeQueue: array<RayRecord>;
1452
+ @group(0) @binding(1) var<storage, read_write> nextQueue: array<RayRecord>;
1453
+ @group(0) @binding(2) var<storage, read_write> hits: array<HitRecord>;
1454
+ @group(0) @binding(3) var<storage, read_write> accumulation: array<vec4<f32>>;
1455
+ @group(0) @binding(4) var<storage, read> sceneObjects: array<SceneObject>;
1456
+ @group(0) @binding(5) var<uniform> config: FrameConfig;
1457
+ @group(0) @binding(6) var<storage, read_write> counters: Counters;
1458
+ @group(0) @binding(7) var outputImage: texture_storage_2d<rgba8unorm, write>;
1459
+ @group(0) @binding(8) var<storage, read_write> triangles: array<TriangleRecord>;
1460
+ @group(0) @binding(9) var<storage, read_write> bvhNodes: array<BvhNode>;
1461
+ @group(0) @binding(10) var<storage, read> meshVertices: array<MeshVertex>;
1462
+ @group(0) @binding(11) var<storage, read> meshIndices: array<u32>;
1463
+ @group(0) @binding(12) var<storage, read> meshRanges: array<MeshRange>;
1464
+ @group(0) @binding(13) var<storage, read_write> bvhLeafRefs: array<BvhLeafRef>;
1465
+ @group(0) @binding(14) var denoiseInputRadiance: texture_2d<f32>;
1466
+ @group(0) @binding(15) var denoisedRadianceImage: texture_storage_2d<rgba16float, write>;
1467
+ @group(0) @binding(16) var radianceImage: texture_storage_2d<rgba16float, write>;
1468
+ @group(0) @binding(17) var finalDenoiseInputRadiance: texture_2d<f32>;
1469
+ @group(0) @binding(18) var denoisedOutputImage: texture_storage_2d<rgba8unorm, write>;
1470
+
1471
+ fn hash_u32(value: u32) -> u32 {
1472
+ var x = value;
1473
+ x = ((x >> 16u) ^ x) * 0x45d9f3bu;
1474
+ x = ((x >> 16u) ^ x) * 0x45d9f3bu;
1475
+ x = (x >> 16u) ^ x;
1476
+ return x;
1477
+ }
1478
+
1479
+ fn mix_seed(pixelId: u32, sampleId: u32, bounce: u32, frameIndex: u32, dimension: u32) -> u32 {
1480
+ var x =
1481
+ (pixelId * 747796405u) ^
1482
+ (sampleId * 2891336453u) ^
1483
+ (bounce * 277803737u) ^
1484
+ (frameIndex * 1442695041u) ^
1485
+ (dimension * 1597334677u);
1486
+ x = x ^ (x >> 16u);
1487
+ x = x * 0x7feb352du;
1488
+ x = x ^ (x >> 15u);
1489
+ x = x * 0x846ca68bu;
1490
+ x = x ^ (x >> 16u);
1491
+ return x;
1492
+ }
1493
+
1494
+ fn random01(seed: u32) -> f32 {
1495
+ return f32(hash_u32(seed) & 0x00ffffffu) / 16777215.0;
1496
+ }
1497
+
1498
+ fn safe_normalize(value: vec3<f32>, fallback: vec3<f32>) -> vec3<f32> {
1499
+ let len = length(value);
1500
+ if (len <= 0.000001) {
1501
+ return fallback;
1502
+ }
1503
+ return value / len;
1504
+ }
1505
+
1506
+ fn saturate(value: f32) -> f32 {
1507
+ return clamp(value, 0.0, 1.0);
1508
+ }
1509
+
1510
+ fn environment_radiance(direction: vec3<f32>) -> vec3<f32> {
1511
+ let rayDirection = safe_normalize(direction, vec3<f32>(0.0, 1.0, 0.0));
1512
+ let upFactor = saturate(rayDirection.y * 0.5 + 0.5);
1513
+ let sunDirection = safe_normalize(
1514
+ config.environmentSunDirectionIntensity.xyz,
1515
+ vec3<f32>(0.0, 1.0, 0.0)
1516
+ );
1517
+ let sunGlow = pow(saturate(dot(rayDirection, sunDirection)), 192.0);
1518
+ let gradient =
1519
+ config.environmentHorizonColor.xyz * (1.0 - upFactor) +
1520
+ config.environmentZenithColor.xyz * upFactor;
1521
+ return (
1522
+ gradient +
1523
+ config.environmentSunColor.xyz * sunGlow
1524
+ ) * max(config.environmentSunDirectionIntensity.w, 0.0001);
1525
+ }
1526
+
1527
+ fn default_mesh_range() -> MeshRange {
1528
+ return MeshRange(
1529
+ 0u,
1530
+ 0u,
1531
+ 0u,
1532
+ 0u,
1533
+ 0u,
1534
+ 0u,
1535
+ 0u,
1536
+ 0u,
1537
+ 0u,
1538
+ 0u,
1539
+ 0u,
1540
+ 0u,
1541
+ vec4<f32>(0.72, 0.72, 0.68, 1.0),
1542
+ vec4<f32>(0.0),
1543
+ vec4<f32>(0.72, 0.0, 1.0, 1.45)
1544
+ );
1545
+ }
1546
+
1547
+ fn mesh_range_for_triangle(triangleIndex: u32) -> MeshRange {
1548
+ var selected = default_mesh_range();
1549
+ for (var meshIndex = 0u; meshIndex < config.meshSourceCount; meshIndex = meshIndex + 1u) {
1550
+ let mesh = meshRanges[meshIndex];
1551
+ let triangleStart = mesh.firstTriangle;
1552
+ let triangleEnd = mesh.firstTriangle + mesh.triangleCount;
1553
+ if (triangleIndex >= triangleStart && triangleIndex < triangleEnd) {
1554
+ selected = mesh;
1555
+ break;
1556
+ }
1557
+ }
1558
+ return selected;
1559
+ }
1560
+
1561
+ fn node_bounds_min(left: BvhNode, right: BvhNode) -> vec3<f32> {
1562
+ return min(left.boundsMin.xyz, right.boundsMin.xyz);
1563
+ }
1564
+
1565
+ fn node_bounds_max(left: BvhNode, right: BvhNode) -> vec3<f32> {
1566
+ return max(left.boundsMax.xyz, right.boundsMax.xyz);
1567
+ }
1568
+
1569
+ fn ordered_float_key(value: f32) -> u32 {
1570
+ let bits = bitcast<u32>(value);
1571
+ let sign = bits & 0x80000000u;
1572
+ let mask = select(0x80000000u, 0xffffffffu, sign != 0u);
1573
+ return bits ^ mask;
1574
+ }
1575
+
1576
+ fn split_by_3(value: u32) -> u32 {
1577
+ var x = value & 0x000003ffu;
1578
+ x = (x | (x << 16u)) & 0x030000ffu;
1579
+ x = (x | (x << 8u)) & 0x0300f00fu;
1580
+ x = (x | (x << 4u)) & 0x030c30c3u;
1581
+ x = (x | (x << 2u)) & 0x09249249u;
1582
+ return x;
1583
+ }
1584
+
1585
+ fn morton_key_from_centroid(centroid: vec3<f32>) -> u32 {
1586
+ let x = (ordered_float_key(centroid.x) >> 12u) & 0x000003ffu;
1587
+ let y = (ordered_float_key(centroid.y) >> 12u) & 0x000003ffu;
1588
+ let z = (ordered_float_key(centroid.z) >> 12u) & 0x000003ffu;
1589
+ return (split_by_3(x) << 2u) | (split_by_3(y) << 1u) | split_by_3(z);
1590
+ }
1591
+
1592
+ fn leaf_ref_less(left: BvhLeafRef, right: BvhLeafRef) -> bool {
1593
+ if (left.key < right.key) {
1594
+ return true;
1595
+ }
1596
+ if (left.key > right.key) {
1597
+ return false;
1598
+ }
1599
+ return left.triangleIndex < right.triangleIndex;
1600
+ }
1601
+
1602
+ @compute @workgroup_size(64)
1603
+ fn prepareMeshTrianglesAndLeaves(@builtin(global_invocation_id) globalId: vec3<u32>) {
1604
+ let triangleIndex = globalId.x;
1605
+ if (triangleIndex >= config.triangleCount) {
1606
+ if (triangleIndex < config.bvhSortItemCount) {
1607
+ bvhLeafRefs[triangleIndex] = BvhLeafRef(0xffffffffu, 0xffffffffu, 0u, 0u);
1608
+ }
1609
+ return;
1610
+ }
1611
+
1612
+ let mesh = mesh_range_for_triangle(triangleIndex);
1613
+ let localTriangle = triangleIndex - mesh.firstTriangle;
1614
+ let indexOffset = mesh.firstIndex + localTriangle * 3u;
1615
+ let index0 = meshIndices[indexOffset];
1616
+ let index1 = meshIndices[indexOffset + 1u];
1617
+ let index2 = meshIndices[indexOffset + 2u];
1618
+ let vertex0 = meshVertices[index0];
1619
+ let vertex1 = meshVertices[index1];
1620
+ let vertex2 = meshVertices[index2];
1621
+ let edge1 = vertex1.position.xyz - vertex0.position.xyz;
1622
+ let edge2 = vertex2.position.xyz - vertex0.position.xyz;
1623
+ let centroid = (vertex0.position.xyz + vertex1.position.xyz + vertex2.position.xyz) / 3.0;
1624
+ let faceNormal = safe_normalize(cross(edge1, edge2), vec3<f32>(0.0, 1.0, 0.0));
1625
+ let n0 = select(faceNormal, safe_normalize(vertex0.normal.xyz, faceNormal), vertex0.normal.w > 0.5);
1626
+ let n1 = select(faceNormal, safe_normalize(vertex1.normal.xyz, faceNormal), vertex1.normal.w > 0.5);
1627
+ let n2 = select(faceNormal, safe_normalize(vertex2.normal.xyz, faceNormal), vertex2.normal.w > 0.5);
1628
+ let uv0 = select(vec2<f32>(0.0), vertex0.uv.xy, vertex0.uv.z > 0.5);
1629
+ let uv1 = select(vec2<f32>(0.0), vertex1.uv.xy, vertex1.uv.z > 0.5);
1630
+ let uv2 = select(vec2<f32>(0.0), vertex2.uv.xy, vertex2.uv.z > 0.5);
1631
+
1632
+ triangles[triangleIndex] = TriangleRecord(
1633
+ triangleIndex,
1634
+ mesh.meshId,
1635
+ mesh.materialKind,
1636
+ mesh.flags,
1637
+ mesh.materialRefId,
1638
+ mesh.mediumRefId,
1639
+ 0u,
1640
+ 0u,
1641
+ vec4<f32>(vertex0.position.xyz, 0.0),
1642
+ vec4<f32>(vertex1.position.xyz, 0.0),
1643
+ vec4<f32>(vertex2.position.xyz, 0.0),
1644
+ vec4<f32>(n0, 0.0),
1645
+ vec4<f32>(n1, 0.0),
1646
+ vec4<f32>(n2, 0.0),
1647
+ vec4<f32>(uv0, uv1),
1648
+ vec4<f32>(uv2, 0.0, 0.0),
1649
+ mesh.color,
1650
+ mesh.emission,
1651
+ mesh.material
1652
+ );
1653
+
1654
+ let leafBase = config.triangleCount - 1u;
1655
+ let nodeIndex = leafBase + triangleIndex;
1656
+ let boundsMin = min(vertex0.position.xyz, min(vertex1.position.xyz, vertex2.position.xyz));
1657
+ let boundsMax = max(vertex0.position.xyz, max(vertex1.position.xyz, vertex2.position.xyz));
1658
+ bvhLeafRefs[triangleIndex] = BvhLeafRef(
1659
+ morton_key_from_centroid(centroid),
1660
+ triangleIndex,
1661
+ 0u,
1662
+ 0u
1663
+ );
1664
+ bvhNodes[nodeIndex] = BvhNode(
1665
+ vec4<f32>(boundsMin, 0.0),
1666
+ vec4<f32>(boundsMax, 0.0),
1667
+ triangleIndex,
1668
+ 1u,
1669
+ 0u,
1670
+ 0u
1671
+ );
1672
+ }
1673
+
1674
+ @compute @workgroup_size(64)
1675
+ fn sortBvhLeafRefs(@builtin(global_invocation_id) globalId: vec3<u32>) {
1676
+ let index = globalId.x;
1677
+ let sortCount = config.bvhSortItemCount;
1678
+ if (sortCount <= 1u || index >= sortCount) {
1679
+ return;
1680
+ }
1681
+
1682
+ let compareDistance = config.bvhBuildNodeStart;
1683
+ let sequenceSize = config.bvhBuildNodeCount;
1684
+ if (compareDistance == 0u || sequenceSize == 0u) {
1685
+ return;
1686
+ }
1687
+
1688
+ let partner = index ^ compareDistance;
1689
+ if (partner <= index || partner >= sortCount) {
1690
+ return;
1691
+ }
1692
+
1693
+ let left = bvhLeafRefs[index];
1694
+ let right = bvhLeafRefs[partner];
1695
+ let ascending = (index & sequenceSize) == 0u;
1696
+ let leftIsLess = leaf_ref_less(left, right);
1697
+ let rightIsLess = leaf_ref_less(right, left);
1698
+ let shouldSwap = select(leftIsLess, rightIsLess, ascending);
1699
+ if (shouldSwap) {
1700
+ bvhLeafRefs[index] = right;
1701
+ bvhLeafRefs[partner] = left;
1702
+ }
1703
+ }
1704
+
1705
+ @compute @workgroup_size(64)
1706
+ fn writeSortedBvhLeaves(@builtin(global_invocation_id) globalId: vec3<u32>) {
1707
+ let sortedIndex = globalId.x;
1708
+ if (sortedIndex >= config.triangleCount || config.triangleCount == 0u) {
1709
+ return;
1710
+ }
1711
+
1712
+ let leafRef = bvhLeafRefs[sortedIndex];
1713
+ if (leafRef.triangleIndex >= config.triangleCount) {
1714
+ return;
1715
+ }
1716
+
1717
+ let triangle = triangles[leafRef.triangleIndex];
1718
+ let boundsMin = min(triangle.v0.xyz, min(triangle.v1.xyz, triangle.v2.xyz));
1719
+ let boundsMax = max(triangle.v0.xyz, max(triangle.v1.xyz, triangle.v2.xyz));
1720
+ let leafBase = config.triangleCount - 1u;
1721
+ let nodeIndex = leafBase + sortedIndex;
1722
+ bvhNodes[nodeIndex] = BvhNode(
1723
+ vec4<f32>(boundsMin, 0.0),
1724
+ vec4<f32>(boundsMax, 0.0),
1725
+ leafRef.triangleIndex,
1726
+ 1u,
1727
+ 0u,
1728
+ 0u
1729
+ );
1730
+ }
1731
+
1732
+ @compute @workgroup_size(64)
1733
+ fn buildBvhInternalLevel(@builtin(global_invocation_id) globalId: vec3<u32>) {
1734
+ if (config.triangleCount <= 1u || globalId.x >= config.bvhBuildNodeCount) {
1735
+ return;
1736
+ }
1737
+
1738
+ let internalCount = config.triangleCount - 1u;
1739
+ let nodeIndex = config.bvhBuildNodeStart + globalId.x;
1740
+ if (nodeIndex >= internalCount || nodeIndex >= config.bvhNodeCapacity) {
1741
+ return;
1742
+ }
1743
+
1744
+ let leftIndex = nodeIndex * 2u + 1u;
1745
+ let rightIndex = nodeIndex * 2u + 2u;
1746
+ if (rightIndex >= config.bvhNodeCapacity || rightIndex >= config.bvhNodeCount) {
1747
+ return;
1748
+ }
1749
+
1750
+ let left = bvhNodes[leftIndex];
1751
+ let right = bvhNodes[rightIndex];
1752
+ bvhNodes[nodeIndex] = BvhNode(
1753
+ vec4<f32>(node_bounds_min(left, right), 0.0),
1754
+ vec4<f32>(node_bounds_max(left, right), 0.0),
1755
+ leftIndex,
1756
+ 0u,
1757
+ rightIndex,
1758
+ 0u
1759
+ );
1760
+ }
1761
+
1762
+ fn make_ray(pixelIndex: u32) -> RayRecord {
1763
+ let localX = pixelIndex % config.tileWidth;
1764
+ let localY = pixelIndex / config.tileWidth;
1765
+ let px = config.tileX + localX;
1766
+ let py = config.tileY + localY;
1767
+ let sampleId = u32(config.projectionAndSampling.w);
1768
+ let sourcePixelId = py * config.canvasWidth + px;
1769
+ let jitterX = random01(mix_seed(sourcePixelId, sampleId, 0u, config.frameIndex, 1u)) - 0.5;
1770
+ let jitterY = random01(mix_seed(sourcePixelId, sampleId, 0u, config.frameIndex, 2u)) - 0.5;
1771
+ let ndcX = ((f32(px) + 0.5 + jitterX * 0.35) / f32(config.canvasWidth)) * 2.0 - 1.0;
1772
+ let ndcY = 1.0 - ((f32(py) + 0.5 + jitterY * 0.35) / f32(config.canvasHeight)) * 2.0;
1773
+ let viewX = ndcX * config.projectionAndSampling.x * config.projectionAndSampling.y;
1774
+ let viewY = ndcY * config.projectionAndSampling.x;
1775
+ let direction = safe_normalize(
1776
+ config.cameraForward.xyz + config.cameraRight.xyz * viewX + config.cameraUp.xyz * viewY,
1777
+ config.cameraForward.xyz
1778
+ );
1779
+ return RayRecord(
1780
+ pixelIndex,
1781
+ 0xffffffffu,
1782
+ sourcePixelId,
1783
+ sampleId,
1784
+ 0u,
1785
+ 0u,
1786
+ 0u,
1787
+ 0u,
1788
+ vec4<f32>(config.cameraPosition.xyz, 1.0),
1789
+ vec4<f32>(direction, 0.0),
1790
+ vec4<f32>(1.0, 1.0, 1.0, 1.0)
1791
+ );
1792
+ }
1793
+
1794
+ fn make_miss(ray: RayRecord) -> HitRecord {
1795
+ let radiance = environment_radiance(ray.direction.xyz);
1796
+ return HitRecord(
1797
+ ray.rayId,
1798
+ ray.sourcePixelId,
1799
+ 2u,
1800
+ 0u,
1801
+ 0u,
1802
+ 1u,
1803
+ 0u,
1804
+ 0u,
1805
+ 0u,
1806
+ 0u,
1807
+ 0u,
1808
+ 0u,
1809
+ -1.0,
1810
+ vec3<f32>(0.0),
1811
+ vec4<f32>(ray.origin.xyz + ray.direction.xyz * 1000.0, 1.0),
1812
+ vec4<f32>(-ray.direction.xyz, 0.0),
1813
+ vec4<f32>(-ray.direction.xyz, 0.0),
1814
+ vec4<f32>(0.0),
1815
+ vec4<f32>(0.0),
1816
+ vec4<f32>(radiance, 1.0),
1817
+ vec4<f32>(0.0),
1818
+ vec4<f32>(1.0, 0.0, 1.0, 1.0)
1819
+ );
1820
+ }
1821
+
1822
+ fn intersect_sphere(ray: RayRecord, object: SceneObject) -> Candidate {
1823
+ let oc = ray.origin.xyz - object.center.xyz;
1824
+ let radius = max(object.halfExtent.x, 0.001);
1825
+ let halfB = dot(oc, ray.direction.xyz);
1826
+ let c = dot(oc, oc) - radius * radius;
1827
+ let discriminant = halfB * halfB - c;
1828
+ if (discriminant < 0.0) {
1829
+ return no_candidate();
1830
+ }
1831
+ let sqrtD = sqrt(discriminant);
1832
+ var distance = -halfB - sqrtD;
1833
+ if (distance <= 0.001) {
1834
+ distance = -halfB + sqrtD;
1835
+ }
1836
+ if (distance <= 0.001) {
1837
+ return no_candidate();
1838
+ }
1839
+ let position = ray.origin.xyz + ray.direction.xyz * distance;
1840
+ let outward = safe_normalize((position - object.center.xyz) / radius, vec3<f32>(0.0, 1.0, 0.0));
1841
+ let frontFace = select(0u, 1u, dot(ray.direction.xyz, outward) < 0.0);
1842
+ let normal = select(-outward, outward, frontFace == 1u);
1843
+ return surface_candidate(
1844
+ distance,
1845
+ normal,
1846
+ normal,
1847
+ vec3<f32>(1.0, 0.0, 0.0),
1848
+ vec2<f32>(0.0),
1849
+ frontFace,
1850
+ 0xffffffffu,
1851
+ object.objectId,
1852
+ object.objectId,
1853
+ 0u
1854
+ );
1855
+ }
1856
+
1857
+ fn safe_inverse(value: f32) -> f32 {
1858
+ if (abs(value) < 0.000001) {
1859
+ return select(-1000000.0, 1000000.0, value >= 0.0);
1860
+ }
1861
+ return 1.0 / value;
1862
+ }
1863
+
1864
+ fn intersect_box(ray: RayRecord, object: SceneObject) -> Candidate {
1865
+ let boxMin = object.center.xyz - object.halfExtent.xyz;
1866
+ let boxMax = object.center.xyz + object.halfExtent.xyz;
1867
+ let inv = vec3<f32>(
1868
+ safe_inverse(ray.direction.x),
1869
+ safe_inverse(ray.direction.y),
1870
+ safe_inverse(ray.direction.z)
1871
+ );
1872
+ let t0 = (boxMin - ray.origin.xyz) * inv;
1873
+ let t1 = (boxMax - ray.origin.xyz) * inv;
1874
+ let tNear = min(t0, t1);
1875
+ let tFar = max(t0, t1);
1876
+ let entry = max(max(tNear.x, tNear.y), tNear.z);
1877
+ let exit = min(min(tFar.x, tFar.y), tFar.z);
1878
+ if (exit < max(entry, 0.001)) {
1879
+ return no_candidate();
1880
+ }
1881
+ let distance = max(entry, 0.001);
1882
+ let position = ray.origin.xyz + ray.direction.xyz * distance;
1883
+ let rel = (position - object.center.xyz) / max(object.halfExtent.xyz, vec3<f32>(0.001));
1884
+ let absRel = abs(rel);
1885
+ var outward = vec3<f32>(0.0, 1.0, 0.0);
1886
+ if (absRel.x >= absRel.y && absRel.x >= absRel.z) {
1887
+ outward = vec3<f32>(select(-1.0, 1.0, rel.x >= 0.0), 0.0, 0.0);
1888
+ } else if (absRel.y >= absRel.z) {
1889
+ outward = vec3<f32>(0.0, select(-1.0, 1.0, rel.y >= 0.0), 0.0);
1890
+ } else {
1891
+ outward = vec3<f32>(0.0, 0.0, select(-1.0, 1.0, rel.z >= 0.0));
1892
+ }
1893
+ let frontFace = select(0u, 1u, dot(ray.direction.xyz, outward) < 0.0);
1894
+ let normal = select(-outward, outward, frontFace == 1u);
1895
+ return surface_candidate(
1896
+ distance,
1897
+ normal,
1898
+ normal,
1899
+ vec3<f32>(1.0, 0.0, 0.0),
1900
+ vec2<f32>(0.0),
1901
+ frontFace,
1902
+ 0xffffffffu,
1903
+ object.objectId,
1904
+ object.objectId,
1905
+ 0u
1906
+ );
1907
+ }
1908
+
1909
+ fn intersect_bounds(ray: RayRecord, boundsMin: vec3<f32>, boundsMax: vec3<f32>, nearest: f32) -> bool {
1910
+ let inv = vec3<f32>(
1911
+ safe_inverse(ray.direction.x),
1912
+ safe_inverse(ray.direction.y),
1913
+ safe_inverse(ray.direction.z)
1914
+ );
1915
+ let t0 = (boundsMin - ray.origin.xyz) * inv;
1916
+ let t1 = (boundsMax - ray.origin.xyz) * inv;
1917
+ let tNear = min(t0, t1);
1918
+ let tFar = max(t0, t1);
1919
+ let entry = max(max(tNear.x, tNear.y), tNear.z);
1920
+ let exit = min(min(tFar.x, tFar.y), tFar.z);
1921
+ return exit >= max(entry, 0.001) && entry <= nearest;
1922
+ }
1923
+
1924
+ fn repair_shading_normal(geometricNormal: vec3<f32>, shadingNormal: vec3<f32>) -> vec3<f32> {
1925
+ var normal = safe_normalize(shadingNormal, geometricNormal);
1926
+ if (dot(normal, geometricNormal) < 0.0) {
1927
+ normal = -normal;
1928
+ }
1929
+ return normal;
1930
+ }
1931
+
1932
+ fn no_candidate() -> Candidate {
1933
+ return Candidate(
1934
+ 0u,
1935
+ 0.0,
1936
+ vec3<f32>(0.0, 1.0, 0.0),
1937
+ vec3<f32>(0.0, 1.0, 0.0),
1938
+ vec3<f32>(0.0),
1939
+ vec2<f32>(0.0),
1940
+ 1u,
1941
+ 0xffffffffu,
1942
+ 0xffffffffu,
1943
+ 0u,
1944
+ 0u
1945
+ );
1946
+ }
1947
+
1948
+ fn surface_candidate(
1949
+ distance: f32,
1950
+ geometricNormal: vec3<f32>,
1951
+ shadingNormal: vec3<f32>,
1952
+ barycentric: vec3<f32>,
1953
+ uv: vec2<f32>,
1954
+ frontFace: u32,
1955
+ triangleIndex: u32,
1956
+ primitiveId: u32,
1957
+ materialRefId: u32,
1958
+ mediumRefId: u32
1959
+ ) -> Candidate {
1960
+ return Candidate(
1961
+ 1u,
1962
+ distance,
1963
+ geometricNormal,
1964
+ shadingNormal,
1965
+ barycentric,
1966
+ uv,
1967
+ frontFace,
1968
+ triangleIndex,
1969
+ primitiveId,
1970
+ materialRefId,
1971
+ mediumRefId
1972
+ );
1973
+ }
1974
+
1975
+ fn intersect_triangle(ray: RayRecord, triangle: TriangleRecord, triangleIndex: u32) -> Candidate {
1976
+ let edge1 = triangle.v1.xyz - triangle.v0.xyz;
1977
+ let edge2 = triangle.v2.xyz - triangle.v0.xyz;
1978
+ let pvec = cross(ray.direction.xyz, edge2);
1979
+ let det = dot(edge1, pvec);
1980
+ if (abs(det) < 0.0000001) {
1981
+ return no_candidate();
1982
+ }
1983
+
1984
+ let invDet = 1.0 / det;
1985
+ let tvec = ray.origin.xyz - triangle.v0.xyz;
1986
+ let u = dot(tvec, pvec) * invDet;
1987
+ if (u < 0.0 || u > 1.0) {
1988
+ return no_candidate();
1989
+ }
1990
+
1991
+ let qvec = cross(tvec, edge1);
1992
+ let v = dot(ray.direction.xyz, qvec) * invDet;
1993
+ if (v < 0.0 || u + v > 1.0) {
1994
+ return no_candidate();
1995
+ }
1996
+
1997
+ let distance = dot(edge2, qvec) * invDet;
1998
+ if (distance <= 0.001) {
1999
+ return no_candidate();
2000
+ }
2001
+
2002
+ let geometric = safe_normalize(cross(edge1, edge2), vec3<f32>(0.0, 1.0, 0.0));
2003
+ let frontFace = select(0u, 1u, dot(ray.direction.xyz, geometric) < 0.0);
2004
+ let orientedGeometric = select(-geometric, geometric, frontFace == 1u);
2005
+ let w = 1.0 - u - v;
2006
+ let interpolated =
2007
+ triangle.n0.xyz * w +
2008
+ triangle.n1.xyz * u +
2009
+ triangle.n2.xyz * v;
2010
+ let shading = repair_shading_normal(orientedGeometric, interpolated);
2011
+ let barycentric = vec3<f32>(w, u, v);
2012
+ let uv =
2013
+ triangle.uv0uv1.xy * w +
2014
+ triangle.uv0uv1.zw * u +
2015
+ triangle.uv2Pad.xy * v;
2016
+ return surface_candidate(
2017
+ distance,
2018
+ orientedGeometric,
2019
+ shading,
2020
+ barycentric,
2021
+ uv,
2022
+ frontFace,
2023
+ triangleIndex,
2024
+ triangle.triangleId,
2025
+ triangle.materialRefId,
2026
+ triangle.mediumRefId
2027
+ );
2028
+ }
2029
+
2030
+ fn intersect_bvh(ray: RayRecord, initialNearest: f32) -> Candidate {
2031
+ var nearest = initialNearest;
2032
+ var best = no_candidate();
2033
+ if (config.bvhNodeCount == 0u || config.triangleCount == 0u) {
2034
+ return best;
2035
+ }
2036
+
2037
+ var stack = array<u32, 64>();
2038
+ var stackSize = 1u;
2039
+ stack[0] = 0u;
2040
+
2041
+ loop {
2042
+ if (stackSize == 0u) {
2043
+ break;
2044
+ }
2045
+
2046
+ stackSize = stackSize - 1u;
2047
+ let nodeIndex = stack[stackSize];
2048
+ if (nodeIndex >= config.bvhNodeCount) {
2049
+ continue;
2050
+ }
2051
+
2052
+ let node = bvhNodes[nodeIndex];
2053
+ if (!intersect_bounds(ray, node.boundsMin.xyz, node.boundsMax.xyz, nearest)) {
2054
+ continue;
2055
+ }
2056
+
2057
+ if (node.triangleCount > 0u) {
2058
+ for (var offset = 0u; offset < node.triangleCount; offset = offset + 1u) {
2059
+ let triangleIndex = node.childOrFirst + offset;
2060
+ if (triangleIndex >= config.triangleCount) {
2061
+ continue;
2062
+ }
2063
+ let current = intersect_triangle(ray, triangles[triangleIndex], triangleIndex);
2064
+ if (current.hit == 1u && current.distance < nearest) {
2065
+ nearest = current.distance;
2066
+ best = current;
2067
+ }
2068
+ }
2069
+ } else {
2070
+ if (stackSize + 2u <= 64u) {
2071
+ stack[stackSize] = node.childOrFirst;
2072
+ stack[stackSize + 1u] = node.rightChild;
2073
+ stackSize = stackSize + 2u;
2074
+ }
2075
+ }
2076
+ }
2077
+
2078
+ return best;
2079
+ }
2080
+
2081
+ fn emission_power(emission: vec4<f32>) -> f32 {
2082
+ return emission.x + emission.y + emission.z;
2083
+ }
2084
+
2085
+ fn sample_weight() -> f32 {
2086
+ return max(config.projectionAndSampling.z, 0.000001);
2087
+ }
2088
+
2089
+ fn clamp_sample_radiance(value: vec3<f32>) -> vec3<f32> {
2090
+ return min(max(value, vec3<f32>(0.0)), vec3<f32>(4.0));
2091
+ }
2092
+
2093
+ fn tone_map_radiance(value: vec3<f32>) -> vec3<f32> {
2094
+ let mapped = value / (vec3<f32>(1.0) + value);
2095
+ return pow(clamp(mapped, vec3<f32>(0.0), vec3<f32>(1.0)), vec3<f32>(1.0 / 2.2));
2096
+ }
2097
+
2098
+ fn denoise_range_space(value: vec3<f32>) -> vec3<f32> {
2099
+ return value / (vec3<f32>(1.0) + value);
2100
+ }
2101
+
2102
+ @compute @workgroup_size(64)
2103
+ fn generatePrimaryRays(@builtin(global_invocation_id) globalId: vec3<u32>) {
2104
+ let index = globalId.x;
2105
+ if (index == 0u) {
2106
+ atomicStore(&counters.activeCount, config.tilePixelCount);
2107
+ atomicStore(&counters.nextCount, 0u);
2108
+ atomicStore(&counters.terminatedCount, 0u);
2109
+ atomicStore(&counters.hitCount, 0u);
2110
+ }
2111
+ if (index >= config.tilePixelCount) {
2112
+ return;
2113
+ }
2114
+ activeQueue[index] = make_ray(index);
2115
+ if (u32(config.projectionAndSampling.w) == 0u) {
2116
+ accumulation[index] = vec4<f32>(0.0);
2117
+ }
2118
+ }
2119
+
2120
+ @compute @workgroup_size(64)
2121
+ fn intersectActiveQueue(@builtin(global_invocation_id) globalId: vec3<u32>) {
2122
+ let index = globalId.x;
2123
+ let activeCount = atomicLoad(&counters.activeCount);
2124
+ if (index >= activeCount) {
2125
+ return;
2126
+ }
2127
+ let ray = activeQueue[index];
2128
+ var nearest = 1000000.0;
2129
+ var hitObject = SceneObject(
2130
+ 0u,
2131
+ 0u,
2132
+ 0u,
2133
+ 0u,
2134
+ vec4<f32>(0.0),
2135
+ vec4<f32>(0.0),
2136
+ vec4<f32>(0.0),
2137
+ vec4<f32>(0.0),
2138
+ vec4<f32>(1.0, 0.0, 1.0, 1.0)
2139
+ );
2140
+ var candidate = no_candidate();
2141
+ var hitTriangle = TriangleRecord(
2142
+ 0u,
2143
+ 0u,
2144
+ 0u,
2145
+ 0u,
2146
+ 0u,
2147
+ 0u,
2148
+ 0u,
2149
+ 0u,
2150
+ vec4<f32>(0.0),
2151
+ vec4<f32>(0.0),
2152
+ vec4<f32>(0.0),
2153
+ vec4<f32>(0.0, 1.0, 0.0, 0.0),
2154
+ vec4<f32>(0.0, 1.0, 0.0, 0.0),
2155
+ vec4<f32>(0.0, 1.0, 0.0, 0.0),
2156
+ vec4<f32>(0.0),
2157
+ vec4<f32>(0.0),
2158
+ vec4<f32>(0.0),
2159
+ vec4<f32>(0.0),
2160
+ vec4<f32>(1.0, 0.0, 1.0, 1.0)
2161
+ );
2162
+
2163
+ for (var objectIndex = 0u; objectIndex < config.sceneObjectCount; objectIndex = objectIndex + 1u) {
2164
+ let object = sceneObjects[objectIndex];
2165
+ var current = no_candidate();
2166
+ if (object.kind == 1u) {
2167
+ current = intersect_sphere(ray, object);
2168
+ } else if (object.kind == 2u) {
2169
+ current = intersect_box(ray, object);
2170
+ }
2171
+ if (current.hit == 1u && current.distance < nearest) {
2172
+ nearest = current.distance;
2173
+ hitObject = object;
2174
+ candidate = current;
2175
+ }
2176
+ }
2177
+
2178
+ let meshCandidate = intersect_bvh(ray, nearest);
2179
+ if (meshCandidate.hit == 1u && meshCandidate.distance < nearest) {
2180
+ nearest = meshCandidate.distance;
2181
+ candidate = meshCandidate;
2182
+ hitTriangle = triangles[meshCandidate.triangleIndex];
2183
+ }
2184
+
2185
+ if (candidate.hit == 0u) {
2186
+ hits[index] = make_miss(ray);
2187
+ return;
2188
+ }
2189
+
2190
+ let position = ray.origin.xyz + ray.direction.xyz * candidate.distance;
2191
+ let hitMaterialKind = select(hitObject.materialKind, hitTriangle.materialKind, candidate.triangleIndex != 0xffffffffu);
2192
+ let hitObjectId = select(hitObject.objectId, hitTriangle.meshId, candidate.triangleIndex != 0xffffffffu);
2193
+ let hitColor = select(hitObject.color, hitTriangle.color, candidate.triangleIndex != 0xffffffffu);
2194
+ let hitEmission = select(hitObject.emission, hitTriangle.emission, candidate.triangleIndex != 0xffffffffu);
2195
+ let hitMaterial = select(hitObject.material, hitTriangle.material, candidate.triangleIndex != 0xffffffffu);
2196
+ let hitPrimitiveId = select(candidate.primitiveId, hitTriangle.triangleId, candidate.triangleIndex != 0xffffffffu);
2197
+ let hitMaterialRefId = select(candidate.materialRefId, hitTriangle.materialRefId, candidate.triangleIndex != 0xffffffffu);
2198
+ let hitMediumRefId = select(candidate.mediumRefId, hitTriangle.mediumRefId, candidate.triangleIndex != 0xffffffffu);
2199
+ var hitType = 0u;
2200
+ if (hitMaterialKind == 4u || emission_power(hitEmission) > 0.0001) {
2201
+ hitType = 1u;
2202
+ } else if (hitMaterialKind == 3u || hitMaterial.z < 0.999) {
2203
+ hitType = 3u;
2204
+ }
2205
+ atomicAdd(&counters.hitCount, 1u);
2206
+ hits[index] = HitRecord(
2207
+ ray.rayId,
2208
+ ray.sourcePixelId,
2209
+ hitType,
2210
+ hitObjectId,
2211
+ hitMaterialKind,
2212
+ candidate.frontFace,
2213
+ hitPrimitiveId,
2214
+ hitMaterialRefId,
2215
+ hitMediumRefId,
2216
+ 0u,
2217
+ 0u,
2218
+ 0u,
2219
+ candidate.distance,
2220
+ vec3<f32>(0.0),
2221
+ vec4<f32>(position, 1.0),
2222
+ vec4<f32>(candidate.geometricNormal, 0.0),
2223
+ vec4<f32>(candidate.shadingNormal, 0.0),
2224
+ vec4<f32>(candidate.barycentric, 0.0),
2225
+ vec4<f32>(candidate.uv, 0.0, 0.0),
2226
+ hitColor,
2227
+ hitEmission,
2228
+ hitMaterial
2229
+ );
2230
+ }
2231
+
2232
+ fn offset_origin(position: vec3<f32>, normal: vec3<f32>) -> vec3<f32> {
2233
+ return position + normal * 0.0025;
2234
+ }
2235
+
2236
+ fn random_unit_vector(seed: u32) -> vec3<f32> {
2237
+ let z = random01(seed) * 2.0 - 1.0;
2238
+ let a = random01(seed + 11u) * 6.28318530718;
2239
+ let r = sqrt(max(0.0, 1.0 - z * z));
2240
+ return vec3<f32>(r * cos(a), r * sin(a), z);
2241
+ }
2242
+
2243
+ fn schlick(cosine: f32, refractionRatio: f32) -> f32 {
2244
+ var r0 = (1.0 - refractionRatio) / (1.0 + refractionRatio);
2245
+ r0 = r0 * r0;
2246
+ return r0 + (1.0 - r0) * pow(1.0 - cosine, 5.0);
2247
+ }
2248
+
2249
+ fn refract_direction(unitDirection: vec3<f32>, normal: vec3<f32>, etaRatio: f32) -> vec3<f32> {
2250
+ let cosTheta = min(dot(-unitDirection, normal), 1.0);
2251
+ let rOutPerp = etaRatio * (unitDirection + cosTheta * normal);
2252
+ let rOutParallel = -sqrt(abs(1.0 - dot(rOutPerp, rOutPerp))) * normal;
2253
+ return safe_normalize(rOutPerp + rOutParallel, reflect(unitDirection, normal));
2254
+ }
2255
+
2256
+ fn sample_emissive_triangle_direction(hit: HitRecord, seed: u32, fallback: vec3<f32>) -> vec3<f32> {
2257
+ if (config.emissiveTriangleCount == 0u) {
2258
+ return fallback;
2259
+ }
2260
+ let lightSlot = min(u32(random01(seed + 71u) * f32(config.emissiveTriangleCount)), config.emissiveTriangleCount - 1u);
2261
+ let lightMetadata = bvhNodes[config.bvhNodeCapacity + lightSlot];
2262
+ let triangleIndex = lightMetadata.childOrFirst;
2263
+ if (triangleIndex >= config.triangleCount) {
2264
+ return fallback;
2265
+ }
2266
+
2267
+ let lightTriangle = triangles[triangleIndex];
2268
+ let r1 = random01(seed + 101u);
2269
+ let r2 = random01(seed + 193u);
2270
+ let root = sqrt(r1);
2271
+ let b0 = 1.0 - root;
2272
+ let b1 = root * (1.0 - r2);
2273
+ let b2 = root * r2;
2274
+ let lightPoint =
2275
+ lightTriangle.v0.xyz * b0 +
2276
+ lightTriangle.v1.xyz * b1 +
2277
+ lightTriangle.v2.xyz * b2;
2278
+ return safe_normalize(lightPoint - hit.position.xyz, fallback);
2279
+ }
2280
+
2281
+ fn scatter_direction(ray: RayRecord, hit: HitRecord, seed: u32) -> ScatterResult {
2282
+ let roughness = clamp(hit.material.x, 0.0, 1.0);
2283
+ if (hit.materialKind == 1u) {
2284
+ return ScatterResult(
2285
+ vec4<f32>(
2286
+ safe_normalize(
2287
+ reflect(ray.direction.xyz, hit.shadingNormal.xyz) + random_unit_vector(seed) * roughness,
2288
+ hit.shadingNormal.xyz
2289
+ ),
2290
+ 0.0
2291
+ ),
2292
+ 0u,
2293
+ 0u,
2294
+ 0u,
2295
+ 0u
2296
+ );
2297
+ }
2298
+
2299
+ if (hit.materialKind == 2u || hit.materialKind == 3u) {
2300
+ let ior = max(hit.material.w, 1.01);
2301
+ let etaRatio = select(ior, 1.0 / ior, hit.frontFace == 1u);
2302
+ let cosTheta = min(dot(-ray.direction.xyz, hit.shadingNormal.xyz), 1.0);
2303
+ let sinTheta = sqrt(max(0.0, 1.0 - cosTheta * cosTheta));
2304
+ let cannotRefract = etaRatio * sinTheta > 1.0;
2305
+ let reflectChance = schlick(cosTheta, etaRatio);
2306
+ if (cannotRefract || random01(seed + 23u) < reflectChance) {
2307
+ return ScatterResult(vec4<f32>(reflect(ray.direction.xyz, hit.shadingNormal.xyz), 0.0), 0u, 0u, 0u, 0u);
2308
+ }
2309
+ return ScatterResult(vec4<f32>(refract_direction(ray.direction.xyz, hit.shadingNormal.xyz, etaRatio), 0.0), 0u, 0u, 0u, 0u);
2310
+ }
2311
+
2312
+ let randomDiffuse = safe_normalize(
2313
+ hit.shadingNormal.xyz + random_unit_vector(seed),
2314
+ hit.shadingNormal.xyz
2315
+ );
2316
+ let guidedLight = sample_emissive_triangle_direction(hit, seed, randomDiffuse);
2317
+ let canSampleLight = dot(hit.shadingNormal.xyz, guidedLight) > -0.04;
2318
+ let guideProbability = select(0.38, 0.72, ray.bounce == 0u);
2319
+ let useGuidedLight = canSampleLight && random01(seed + 37u) < guideProbability;
2320
+ return ScatterResult(
2321
+ vec4<f32>(select(randomDiffuse, guidedLight, useGuidedLight), 0.0),
2322
+ select(0u, RAY_FLAG_GUIDED_EMISSIVE, useGuidedLight),
2323
+ 0u,
2324
+ 0u,
2325
+ 0u
2326
+ );
2327
+ }
2328
+
2329
+ @compute @workgroup_size(64)
2330
+ fn resolveSurfaceRecords(@builtin(global_invocation_id) globalId: vec3<u32>) {
2331
+ let index = globalId.x;
2332
+ let activeCount = atomicLoad(&counters.activeCount);
2333
+ if (index >= activeCount) {
2334
+ return;
2335
+ }
2336
+
2337
+ let ray = activeQueue[index];
2338
+ let hit = hits[index];
2339
+ var contribution = vec3<f32>(0.0);
2340
+
2341
+ if (hit.hitType == 1u) {
2342
+ let guidedLightWeight = select(1.0, 0.24, (ray.flags & RAY_FLAG_GUIDED_EMISSIVE) != 0u);
2343
+ contribution = clamp_sample_radiance(
2344
+ ray.throughput.xyz * max(hit.emission.xyz, hit.color.xyz) * guidedLightWeight
2345
+ );
2346
+ accumulation[ray.rayId] =
2347
+ accumulation[ray.rayId] + vec4<f32>(contribution * sample_weight(), 1.0);
2348
+ atomicAdd(&counters.terminatedCount, 1u);
2349
+ return;
2350
+ }
2351
+
2352
+ if (hit.hitType == 2u) {
2353
+ contribution = clamp_sample_radiance(ray.throughput.xyz * max(hit.color.xyz, config.ambientColor.xyz));
2354
+ accumulation[ray.rayId] =
2355
+ accumulation[ray.rayId] + vec4<f32>(contribution * sample_weight(), 1.0);
2356
+ atomicAdd(&counters.terminatedCount, 1u);
2357
+ return;
2358
+ }
2359
+
2360
+ if (ray.bounce + 1u >= config.maxDepth) {
2361
+ accumulation[ray.rayId] =
2362
+ accumulation[ray.rayId] +
2363
+ vec4<f32>(ray.throughput.xyz * config.ambientColor.xyz * sample_weight(), 1.0);
2364
+ atomicAdd(&counters.terminatedCount, 1u);
2365
+ return;
2366
+ }
2367
+
2368
+ let seed = mix_seed(ray.sourcePixelId, ray.sampleId, ray.bounce, config.frameIndex, 11u);
2369
+ let scatter = scatter_direction(ray, hit, seed);
2370
+ let nextIndex = atomicAdd(&counters.nextCount, 1u);
2371
+ if (nextIndex >= config.tilePixelCount) {
2372
+ return;
2373
+ }
2374
+ let color = clamp(hit.color.xyz, vec3<f32>(0.0), vec3<f32>(1.0));
2375
+ let opacity = clamp(hit.material.z, 0.0, 1.0);
2376
+ let materialEnergy = select(0.68, 0.92, hit.materialKind == 1u || hit.materialKind == 2u);
2377
+ let transparentEnergy = select(materialEnergy, 0.9, hit.hitType == 3u);
2378
+ let throughput = ray.throughput.xyz * mix(vec3<f32>(1.0), color, max(opacity, 0.18)) * transparentEnergy;
2379
+ nextQueue[nextIndex] = RayRecord(
2380
+ ray.rayId,
2381
+ ray.rayId,
2382
+ ray.sourcePixelId,
2383
+ ray.sampleId,
2384
+ ray.bounce + 1u,
2385
+ ray.mediumRefId,
2386
+ scatter.flags,
2387
+ 0u,
2388
+ vec4<f32>(offset_origin(hit.position.xyz, hit.shadingNormal.xyz), 1.0),
2389
+ scatter.direction,
2390
+ vec4<f32>(throughput, ray.throughput.w)
2391
+ );
2392
+ }
2393
+
2394
+ @compute @workgroup_size(1)
2395
+ fn compactAndSwapQueues(@builtin(global_invocation_id) globalId: vec3<u32>) {
2396
+ if (globalId.x > 0u) {
2397
+ return;
2398
+ }
2399
+ let nextCount = atomicLoad(&counters.nextCount);
2400
+ atomicStore(&counters.activeCount, min(nextCount, config.tilePixelCount));
2401
+ atomicStore(&counters.nextCount, 0u);
2402
+ }
2403
+
2404
+ @compute @workgroup_size(64)
2405
+ fn accumulateTerminalRadiance(@builtin(global_invocation_id) globalId: vec3<u32>) {
2406
+ let index = globalId.x;
2407
+ if (index >= config.tilePixelCount) {
2408
+ return;
2409
+ }
2410
+ let localX = index % config.tileWidth;
2411
+ let localY = index / config.tileWidth;
2412
+ let pixel = vec2<i32>(i32(config.tileX + localX), i32(config.tileY + localY));
2413
+ let radiance = max(accumulation[index].xyz, vec3<f32>(0.0));
2414
+
2415
+ textureStore(radianceImage, pixel, vec4<f32>(radiance, 1.0));
2416
+ if (config.denoise == 0u) {
2417
+ textureStore(outputImage, pixel, vec4<f32>(tone_map_radiance(radiance), 1.0));
2418
+ }
2419
+ }
2420
+
2421
+ @compute @workgroup_size(8, 8)
2422
+ fn denoiseLinearRadiance(@builtin(global_invocation_id) globalId: vec3<u32>) {
2423
+ let x = globalId.x;
2424
+ let y = globalId.y;
2425
+ if (x >= config.canvasWidth || y >= config.canvasHeight) {
2426
+ return;
2427
+ }
2428
+
2429
+ let pixel = vec2<i32>(i32(x), i32(y));
2430
+ let center = textureLoad(denoiseInputRadiance, pixel, 0).xyz;
2431
+ var sum = center * 1.4;
2432
+ var totalWeight = 1.4;
2433
+ let centerRange = denoise_range_space(center);
2434
+
2435
+ for (var oy = -2i; oy <= 2i; oy = oy + 1i) {
2436
+ for (var ox = -2i; ox <= 2i; ox = ox + 1i) {
2437
+ if (ox == 0i && oy == 0i) {
2438
+ continue;
2439
+ }
2440
+ let sx = clamp(i32(x) + ox, 0i, i32(config.canvasWidth) - 1i);
2441
+ let sy = clamp(i32(y) + oy, 0i, i32(config.canvasHeight) - 1i);
2442
+ let sampleColor = textureLoad(denoiseInputRadiance, vec2<i32>(sx, sy), 0).xyz;
2443
+ let colorDistance = length(denoise_range_space(sampleColor) - centerRange);
2444
+ let rangeWeight = 1.0 / (1.0 + colorDistance * 7.0);
2445
+ let distanceWeight = 1.0 / (1.0 + f32(ox * ox + oy * oy) * 0.24);
2446
+ let diagonalWeight = select(1.0, 0.78, abs(ox) + abs(oy) > 2i);
2447
+ let weight = rangeWeight * diagonalWeight * distanceWeight;
2448
+ sum = sum + sampleColor * weight;
2449
+ totalWeight = totalWeight + weight;
2450
+ }
2451
+ }
2452
+
2453
+ let filtered = sum / max(totalWeight, 0.0001);
2454
+ let outlier = saturate(length(denoise_range_space(center) - denoise_range_space(filtered)) * 2.4);
2455
+ let color = min(mix(center, filtered, 0.52 + outlier * 0.18), vec3<f32>(16.0));
2456
+ textureStore(denoisedRadianceImage, pixel, vec4<f32>(color, 1.0));
2457
+ }
2458
+
2459
+ @compute @workgroup_size(8, 8)
2460
+ fn resolveDenoisedOutputImage(@builtin(global_invocation_id) globalId: vec3<u32>) {
2461
+ let x = globalId.x;
2462
+ let y = globalId.y;
2463
+ if (x >= config.canvasWidth || y >= config.canvasHeight) {
2464
+ return;
2465
+ }
2466
+
2467
+ let pixel = vec2<i32>(i32(x), i32(y));
2468
+ let center = textureLoad(finalDenoiseInputRadiance, pixel, 0).xyz;
2469
+ var sum = center * 1.25;
2470
+ var totalWeight = 1.25;
2471
+ let centerRange = denoise_range_space(center);
2472
+
2473
+ for (var oy = -1i; oy <= 1i; oy = oy + 1i) {
2474
+ for (var ox = -1i; ox <= 1i; ox = ox + 1i) {
2475
+ if (ox == 0i && oy == 0i) {
2476
+ continue;
2477
+ }
2478
+ let sx = clamp(i32(x) + ox, 0i, i32(config.canvasWidth) - 1i);
2479
+ let sy = clamp(i32(y) + oy, 0i, i32(config.canvasHeight) - 1i);
2480
+ let sampleColor = textureLoad(finalDenoiseInputRadiance, vec2<i32>(sx, sy), 0).xyz;
2481
+ let colorDistance = length(denoise_range_space(sampleColor) - centerRange);
2482
+ let rangeWeight = 1.0 / (1.0 + colorDistance * 9.0);
2483
+ let distanceWeight = 1.0 / (1.0 + f32(ox * ox + oy * oy) * 0.4);
2484
+ let weight = rangeWeight * distanceWeight;
2485
+ sum = sum + sampleColor * weight;
2486
+ totalWeight = totalWeight + weight;
2487
+ }
2488
+ }
2489
+
2490
+ let filtered = sum / max(totalWeight, 0.0001);
2491
+ let outlier = saturate(length(denoise_range_space(center) - denoise_range_space(filtered)) * 2.8);
2492
+ let radiance = min(mix(center, filtered, 0.28 + outlier * 0.12), vec3<f32>(16.0));
2493
+ textureStore(denoisedOutputImage, pixel, vec4<f32>(tone_map_radiance(radiance), 1.0));
2494
+ }
2495
+ `;
2496
+ var PRESENT_WGSL = `
2497
+ struct VertexOut {
2498
+ @builtin(position) position: vec4<f32>,
2499
+ @location(0) uv: vec2<f32>,
2500
+ };
2501
+
2502
+ @vertex
2503
+ fn vertexMain(@builtin(vertex_index) vertexIndex: u32) -> VertexOut {
2504
+ var positions = array<vec2<f32>, 3>(
2505
+ vec2<f32>(-1.0, -1.0),
2506
+ vec2<f32>(3.0, -1.0),
2507
+ vec2<f32>(-1.0, 3.0)
2508
+ );
2509
+ var uvs = array<vec2<f32>, 3>(
2510
+ vec2<f32>(0.0, 1.0),
2511
+ vec2<f32>(2.0, 1.0),
2512
+ vec2<f32>(0.0, -1.0)
2513
+ );
2514
+ var out: VertexOut;
2515
+ out.position = vec4<f32>(positions[vertexIndex], 0.0, 1.0);
2516
+ out.uv = uvs[vertexIndex];
2517
+ return out;
2518
+ }
2519
+
2520
+ @group(0) @binding(0) var renderTexture: texture_2d<f32>;
2521
+ @group(0) @binding(1) var renderSampler: sampler;
2522
+
2523
+ @fragment
2524
+ fn fragmentMain(in: VertexOut) -> @location(0) vec4<f32> {
2525
+ return textureSample(renderTexture, renderSampler, in.uv);
2526
+ }
2527
+ `;
2528
+ async function createWavefrontPathTracingComputeRenderer(options = {}) {
2529
+ assertAnalyticDisplayQualityPolicy(options);
2530
+ const constants = getGpuUsageConstants();
2531
+ const navigatorRef = options.navigator ?? globalThis.navigator;
2532
+ if (!supportsWavefrontPathTracingCompute({ navigator: navigatorRef })) {
2533
+ throw new Error("WebGPU wavefront path tracing requires navigator.gpu.");
2534
+ }
2535
+ const canvas = resolveCanvas(options.canvas, options.document);
2536
+ const initialConfig = createWavefrontPathTracingComputeConfig({
2537
+ ...options,
2538
+ canvas
2539
+ });
2540
+ const adapter = await navigatorRef.gpu.requestAdapter({
2541
+ powerPreference: options.powerPreference ?? "high-performance"
2542
+ });
2543
+ if (!adapter) {
2544
+ throw new Error("Unable to acquire a WebGPU adapter for wavefront path tracing.");
2545
+ }
2546
+ const device = await adapter.requestDevice();
2547
+ const context = canvas.getContext("webgpu");
2548
+ if (!context || typeof context.configure !== "function") {
2549
+ throw new Error("Canvas WebGPU context does not support configure().");
2550
+ }
2551
+ const format = options.format ?? (typeof navigatorRef.gpu.getPreferredCanvasFormat === "function" ? navigatorRef.gpu.getPreferredCanvasFormat() : "bgra8unorm");
2552
+ let config = initialConfig;
2553
+ const safeTileSize = clampTileSizeForDevice(config, device);
2554
+ if (safeTileSize !== config.tileSize) {
2555
+ config = createWavefrontPathTracingComputeConfig({
2556
+ ...options,
2557
+ canvas,
2558
+ width: config.width,
2559
+ height: config.height,
2560
+ tileSize: safeTileSize
2561
+ });
2562
+ }
2563
+ canvas.width = config.width;
2564
+ canvas.height = config.height;
2565
+ context.configure({
2566
+ device,
2567
+ format,
2568
+ alphaMode: options.alpha === true ? "premultiplied" : "opaque"
2569
+ });
2570
+ const bufferUsage = constants.buffer.STORAGE | constants.buffer.COPY_DST;
2571
+ const rayQueueBytes = config.tilePixelCapacity * RAY_RECORD_BYTES;
2572
+ const hitBytes = config.tilePixelCapacity * HIT_RECORD_BYTES;
2573
+ const accumulationBytes = config.tilePixelCapacity * ACCUMULATION_RECORD_BYTES;
2574
+ const activeQueue = createBuffer(device, bufferUsage, rayQueueBytes, "plasius.wavefront.activeQueue");
2575
+ const nextQueue = createBuffer(device, bufferUsage, rayQueueBytes, "plasius.wavefront.nextQueue");
2576
+ const hitBuffer = createBuffer(device, bufferUsage, hitBytes, "plasius.wavefront.hitBuffer");
2577
+ const accumulationBuffer = createBuffer(
2578
+ device,
2579
+ bufferUsage,
2580
+ accumulationBytes,
2581
+ "plasius.wavefront.accumulation"
2582
+ );
2583
+ const sceneObjectBuffer = createBuffer(
2584
+ device,
2585
+ constants.buffer.STORAGE | constants.buffer.COPY_DST,
2586
+ config.sceneObjectCapacity * SCENE_OBJECT_RECORD_BYTES,
2587
+ "plasius.wavefront.sceneObjects"
2588
+ );
2589
+ const triangleBuffer = createBuffer(
2590
+ device,
2591
+ constants.buffer.STORAGE | constants.buffer.COPY_DST,
2592
+ Math.max(1, config.triangleCapacity) * TRIANGLE_RECORD_BYTES,
2593
+ "plasius.wavefront.triangles"
2594
+ );
2595
+ const bvhNodeBuffer = createBuffer(
2596
+ device,
2597
+ constants.buffer.STORAGE | constants.buffer.COPY_DST,
2598
+ Math.max(1, config.bvhNodeCapacity + config.emissiveTriangleCapacity) * BVH_NODE_RECORD_BYTES,
2599
+ "plasius.wavefront.bvhNodes"
2600
+ );
2601
+ const meshVertexBuffer = createBuffer(
2602
+ device,
2603
+ constants.buffer.STORAGE | constants.buffer.COPY_DST,
2604
+ Math.max(1, config.gpuMeshSource.vertices.count) * MESH_VERTEX_RECORD_BYTES,
2605
+ "plasius.wavefront.meshVertices"
2606
+ );
2607
+ const meshIndexBuffer = createBuffer(
2608
+ device,
2609
+ constants.buffer.STORAGE | constants.buffer.COPY_DST,
2610
+ Math.max(1, config.gpuMeshSource.indices.count) * 4,
2611
+ "plasius.wavefront.meshIndices"
2612
+ );
2613
+ const meshRangeBuffer = createBuffer(
2614
+ device,
2615
+ constants.buffer.STORAGE | constants.buffer.COPY_DST,
2616
+ Math.max(1, config.gpuMeshSource.meshes.count) * MESH_RANGE_RECORD_BYTES,
2617
+ "plasius.wavefront.meshRanges"
2618
+ );
2619
+ const bvhLeafRefBuffer = createBuffer(
2620
+ device,
2621
+ constants.buffer.STORAGE | constants.buffer.COPY_DST,
2622
+ Math.max(1, config.bvhLeafSortCapacity) * BVH_LEAF_REF_RECORD_BYTES,
2623
+ "plasius.wavefront.bvhLeafRefs"
2624
+ );
2625
+ const configBuffer = createBuffer(
2626
+ device,
2627
+ constants.buffer.UNIFORM | constants.buffer.COPY_DST,
2628
+ CONFIG_BUFFER_BYTES,
2629
+ "plasius.wavefront.frameConfig"
2630
+ );
2631
+ const uniformOffsetAlignment = Number(device?.limits?.minUniformBufferOffsetAlignment);
2632
+ const configBufferStride = alignTo(
2633
+ CONFIG_BUFFER_BYTES,
2634
+ Number.isFinite(uniformOffsetAlignment) && uniformOffsetAlignment > 0 ? uniformOffsetAlignment : CONFIG_BUFFER_BYTES
2635
+ );
2636
+ const bvhBuildConfigSlots = 1 + config.bvhSortStages.length + config.bvhBuildLevels.length;
2637
+ const bvhBuildConfigBuffer = createBuffer(
2638
+ device,
2639
+ constants.buffer.UNIFORM | constants.buffer.COPY_DST,
2640
+ Math.max(1, bvhBuildConfigSlots) * configBufferStride,
2641
+ "plasius.wavefront.bvhBuildConfig"
2642
+ );
2643
+ const counterBuffer = createBuffer(
2644
+ device,
2645
+ constants.buffer.STORAGE | constants.buffer.COPY_DST,
2646
+ COUNTER_BUFFER_BYTES,
2647
+ "plasius.wavefront.counters"
2648
+ );
2649
+ let packedScene = packWavefrontSceneObjects(config.sceneObjects, config.sceneObjectCapacity);
2650
+ device.queue.writeBuffer(sceneObjectBuffer, 0, packedScene.buffer);
2651
+ const packedTriangles = packWavefrontTriangles(
2652
+ config.meshAcceleration.triangles,
2653
+ Math.max(1, config.triangleCapacity)
2654
+ );
2655
+ const packedBvhNodes = packWavefrontBvhNodes(
2656
+ config.meshAcceleration.nodes,
2657
+ Math.max(1, config.bvhNodeCapacity + config.emissiveTriangleCapacity)
2658
+ );
2659
+ const packedBvhNodeUints = new Uint32Array(packedBvhNodes.buffer);
2660
+ config.emissiveTriangleIndices.indices.forEach((triangleIndex, index) => {
2661
+ const nodeOffset = (config.bvhNodeCapacity + index) * (BVH_NODE_RECORD_BYTES / 4);
2662
+ packedBvhNodeUints[nodeOffset + 8] = triangleIndex;
2663
+ });
2664
+ device.queue.writeBuffer(triangleBuffer, 0, packedTriangles.buffer);
2665
+ device.queue.writeBuffer(bvhNodeBuffer, 0, packedBvhNodes.buffer);
2666
+ device.queue.writeBuffer(meshVertexBuffer, 0, config.gpuMeshSource.vertices.buffer);
2667
+ device.queue.writeBuffer(meshIndexBuffer, 0, config.gpuMeshSource.indices.buffer);
2668
+ device.queue.writeBuffer(meshRangeBuffer, 0, config.gpuMeshSource.meshes.buffer);
2669
+ const radianceTexture = device.createTexture({
2670
+ label: "plasius.wavefront.radiance",
2671
+ size: { width: config.width, height: config.height },
2672
+ format: "rgba16float",
2673
+ usage: constants.texture.STORAGE_BINDING | constants.texture.TEXTURE_BINDING
2674
+ });
2675
+ const radianceView = radianceTexture.createView();
2676
+ const denoiseScratchTexture = device.createTexture({
2677
+ label: "plasius.wavefront.denoiseScratch",
2678
+ size: { width: config.width, height: config.height },
2679
+ format: "rgba16float",
2680
+ usage: constants.texture.STORAGE_BINDING | constants.texture.TEXTURE_BINDING
2681
+ });
2682
+ const denoiseScratchView = denoiseScratchTexture.createView();
2683
+ const outputTexture = device.createTexture({
2684
+ label: "plasius.wavefront.output",
2685
+ size: { width: config.width, height: config.height },
2686
+ format: "rgba8unorm",
2687
+ usage: constants.texture.STORAGE_BINDING | constants.texture.TEXTURE_BINDING | constants.texture.COPY_SRC
2688
+ });
2689
+ const outputView = outputTexture.createView();
2690
+ const sampler = device.createSampler({
2691
+ label: "plasius.wavefront.presentSampler",
2692
+ magFilter: "nearest",
2693
+ minFilter: "nearest"
2694
+ });
2695
+ const traceBindGroupLayout = device.createBindGroupLayout({
2696
+ label: "plasius.wavefront.traceBindGroupLayout",
2697
+ entries: [
2698
+ { binding: 0, visibility: constants.shader.COMPUTE, buffer: { type: "storage" } },
2699
+ { binding: 1, visibility: constants.shader.COMPUTE, buffer: { type: "storage" } },
2700
+ { binding: 2, visibility: constants.shader.COMPUTE, buffer: { type: "storage" } },
2701
+ { binding: 3, visibility: constants.shader.COMPUTE, buffer: { type: "storage" } },
2702
+ { binding: 4, visibility: constants.shader.COMPUTE, buffer: { type: "read-only-storage" } },
2703
+ {
2704
+ binding: 5,
2705
+ visibility: constants.shader.COMPUTE,
2706
+ buffer: { type: "uniform", hasDynamicOffset: true, minBindingSize: CONFIG_BUFFER_BYTES }
2707
+ },
2708
+ { binding: 6, visibility: constants.shader.COMPUTE, buffer: { type: "storage" } },
2709
+ {
2710
+ binding: 7,
2711
+ visibility: constants.shader.COMPUTE,
2712
+ storageTexture: { access: "write-only", format: "rgba8unorm" }
2713
+ },
2714
+ { binding: 8, visibility: constants.shader.COMPUTE, buffer: { type: "storage" } },
2715
+ { binding: 9, visibility: constants.shader.COMPUTE, buffer: { type: "storage" } },
2716
+ {
2717
+ binding: 16,
2718
+ visibility: constants.shader.COMPUTE,
2719
+ storageTexture: { access: "write-only", format: "rgba16float" }
2720
+ }
2721
+ ]
2722
+ });
2723
+ const accelerationBindGroupLayout = device.createBindGroupLayout({
2724
+ label: "plasius.wavefront.accelerationBindGroupLayout",
2725
+ entries: [
2726
+ {
2727
+ binding: 5,
2728
+ visibility: constants.shader.COMPUTE,
2729
+ buffer: { type: "uniform", hasDynamicOffset: true, minBindingSize: CONFIG_BUFFER_BYTES }
2730
+ },
2731
+ { binding: 8, visibility: constants.shader.COMPUTE, buffer: { type: "storage" } },
2732
+ { binding: 9, visibility: constants.shader.COMPUTE, buffer: { type: "storage" } },
2733
+ { binding: 10, visibility: constants.shader.COMPUTE, buffer: { type: "read-only-storage" } },
2734
+ { binding: 11, visibility: constants.shader.COMPUTE, buffer: { type: "read-only-storage" } },
2735
+ { binding: 12, visibility: constants.shader.COMPUTE, buffer: { type: "read-only-storage" } },
2736
+ { binding: 13, visibility: constants.shader.COMPUTE, buffer: { type: "storage" } }
2737
+ ]
2738
+ });
2739
+ const denoiseRadianceBindGroupLayout = device.createBindGroupLayout({
2740
+ label: "plasius.wavefront.denoiseRadianceBindGroupLayout",
2741
+ entries: [
2742
+ {
2743
+ binding: 5,
2744
+ visibility: constants.shader.COMPUTE,
2745
+ buffer: { type: "uniform", hasDynamicOffset: true, minBindingSize: CONFIG_BUFFER_BYTES }
2746
+ },
2747
+ {
2748
+ binding: 14,
2749
+ visibility: constants.shader.COMPUTE,
2750
+ texture: { sampleType: "float" }
2751
+ },
2752
+ {
2753
+ binding: 15,
2754
+ visibility: constants.shader.COMPUTE,
2755
+ storageTexture: { access: "write-only", format: "rgba16float" }
2756
+ }
2757
+ ]
2758
+ });
2759
+ const denoiseResolveBindGroupLayout = device.createBindGroupLayout({
2760
+ label: "plasius.wavefront.denoiseResolveBindGroupLayout",
2761
+ entries: [
2762
+ {
2763
+ binding: 5,
2764
+ visibility: constants.shader.COMPUTE,
2765
+ buffer: { type: "uniform", hasDynamicOffset: true, minBindingSize: CONFIG_BUFFER_BYTES }
2766
+ },
2767
+ {
2768
+ binding: 17,
2769
+ visibility: constants.shader.COMPUTE,
2770
+ texture: { sampleType: "float" }
2771
+ },
2772
+ {
2773
+ binding: 18,
2774
+ visibility: constants.shader.COMPUTE,
2775
+ storageTexture: { access: "write-only", format: "rgba8unorm" }
2776
+ }
2777
+ ]
2778
+ });
2779
+ const tracePipelineLayout = device.createPipelineLayout({
2780
+ label: "plasius.wavefront.tracePipelineLayout",
2781
+ bindGroupLayouts: [traceBindGroupLayout]
2782
+ });
2783
+ const accelerationPipelineLayout = device.createPipelineLayout({
2784
+ label: "plasius.wavefront.accelerationPipelineLayout",
2785
+ bindGroupLayouts: [accelerationBindGroupLayout]
2786
+ });
2787
+ const denoiseRadiancePipelineLayout = device.createPipelineLayout({
2788
+ label: "plasius.wavefront.denoiseRadiancePipelineLayout",
2789
+ bindGroupLayouts: [denoiseRadianceBindGroupLayout]
2790
+ });
2791
+ const denoiseResolvePipelineLayout = device.createPipelineLayout({
2792
+ label: "plasius.wavefront.denoiseResolvePipelineLayout",
2793
+ bindGroupLayouts: [denoiseResolveBindGroupLayout]
2794
+ });
2795
+ const computeShader = device.createShaderModule({
2796
+ label: "plasius.wavefront.computeShader",
2797
+ code: WAVEFRONT_COMPUTE_WGSL
2798
+ });
2799
+ const pipelines = {
2800
+ prepareMeshTrianglesAndLeaves: await createComputePipeline(
2801
+ device,
2802
+ computeShader,
2803
+ accelerationPipelineLayout,
2804
+ "prepareMeshTrianglesAndLeaves",
2805
+ "plasius.wavefront.prepareMeshTrianglesAndLeaves"
2806
+ ),
2807
+ sortBvhLeafRefs: await createComputePipeline(
2808
+ device,
2809
+ computeShader,
2810
+ accelerationPipelineLayout,
2811
+ "sortBvhLeafRefs",
2812
+ "plasius.wavefront.sortBvhLeafRefs"
2813
+ ),
2814
+ writeSortedBvhLeaves: await createComputePipeline(
2815
+ device,
2816
+ computeShader,
2817
+ accelerationPipelineLayout,
2818
+ "writeSortedBvhLeaves",
2819
+ "plasius.wavefront.writeSortedBvhLeaves"
2820
+ ),
2821
+ buildBvhInternalLevel: await createComputePipeline(
2822
+ device,
2823
+ computeShader,
2824
+ accelerationPipelineLayout,
2825
+ "buildBvhInternalLevel",
2826
+ "plasius.wavefront.buildBvhInternalLevel"
2827
+ ),
2828
+ generatePrimaryRays: await createComputePipeline(
2829
+ device,
2830
+ computeShader,
2831
+ tracePipelineLayout,
2832
+ "generatePrimaryRays",
2833
+ "plasius.wavefront.generatePrimaryRays"
2834
+ ),
2835
+ intersectActiveQueue: await createComputePipeline(
2836
+ device,
2837
+ computeShader,
2838
+ tracePipelineLayout,
2839
+ "intersectActiveQueue",
2840
+ "plasius.wavefront.intersectActiveQueue"
2841
+ ),
2842
+ resolveSurfaceRecords: await createComputePipeline(
2843
+ device,
2844
+ computeShader,
2845
+ tracePipelineLayout,
2846
+ "resolveSurfaceRecords",
2847
+ "plasius.wavefront.resolveSurfaceRecords"
2848
+ ),
2849
+ compactAndSwapQueues: await createComputePipeline(
2850
+ device,
2851
+ computeShader,
2852
+ tracePipelineLayout,
2853
+ "compactAndSwapQueues",
2854
+ "plasius.wavefront.compactAndSwapQueues"
2855
+ ),
2856
+ accumulateTerminalRadiance: await createComputePipeline(
2857
+ device,
2858
+ computeShader,
2859
+ tracePipelineLayout,
2860
+ "accumulateTerminalRadiance",
2861
+ "plasius.wavefront.accumulateTerminalRadiance"
2862
+ ),
2863
+ denoiseLinearRadiance: await createComputePipeline(
2864
+ device,
2865
+ computeShader,
2866
+ denoiseRadiancePipelineLayout,
2867
+ "denoiseLinearRadiance",
2868
+ "plasius.wavefront.denoiseLinearRadiance"
2869
+ ),
2870
+ resolveDenoisedOutputImage: await createComputePipeline(
2871
+ device,
2872
+ computeShader,
2873
+ denoiseResolvePipelineLayout,
2874
+ "resolveDenoisedOutputImage",
2875
+ "plasius.wavefront.resolveDenoisedOutputImage"
2876
+ )
2877
+ };
2878
+ function createTraceBindGroup(activeBuffer, nextBuffer, label, frameConfigBuffer = configBuffer) {
2879
+ return device.createBindGroup({
2880
+ label,
2881
+ layout: traceBindGroupLayout,
2882
+ entries: [
2883
+ { binding: 0, resource: { buffer: activeBuffer } },
2884
+ { binding: 1, resource: { buffer: nextBuffer } },
2885
+ { binding: 2, resource: { buffer: hitBuffer } },
2886
+ { binding: 3, resource: { buffer: accumulationBuffer } },
2887
+ { binding: 4, resource: { buffer: sceneObjectBuffer } },
2888
+ { binding: 5, resource: { buffer: frameConfigBuffer, size: CONFIG_BUFFER_BYTES } },
2889
+ { binding: 6, resource: { buffer: counterBuffer } },
2890
+ { binding: 7, resource: outputView },
2891
+ { binding: 8, resource: { buffer: triangleBuffer } },
2892
+ { binding: 9, resource: { buffer: bvhNodeBuffer } },
2893
+ { binding: 16, resource: radianceView }
2894
+ ]
2895
+ });
2896
+ }
2897
+ const bindGroups = [
2898
+ createTraceBindGroup(activeQueue, nextQueue, "plasius.wavefront.bind.activeNext"),
2899
+ createTraceBindGroup(nextQueue, activeQueue, "plasius.wavefront.bind.nextActive")
2900
+ ];
2901
+ const bvhBuildBindGroup = device.createBindGroup({
2902
+ label: "plasius.wavefront.bind.bvhBuild",
2903
+ layout: accelerationBindGroupLayout,
2904
+ entries: [
2905
+ { binding: 5, resource: { buffer: bvhBuildConfigBuffer, size: CONFIG_BUFFER_BYTES } },
2906
+ { binding: 8, resource: { buffer: triangleBuffer } },
2907
+ { binding: 9, resource: { buffer: bvhNodeBuffer } },
2908
+ { binding: 10, resource: { buffer: meshVertexBuffer } },
2909
+ { binding: 11, resource: { buffer: meshIndexBuffer } },
2910
+ { binding: 12, resource: { buffer: meshRangeBuffer } },
2911
+ { binding: 13, resource: { buffer: bvhLeafRefBuffer } }
2912
+ ]
2913
+ });
2914
+ function createDenoiseRadianceBindGroup(inputView, targetView, label) {
2915
+ return device.createBindGroup({
2916
+ label,
2917
+ layout: denoiseRadianceBindGroupLayout,
2918
+ entries: [
2919
+ { binding: 5, resource: { buffer: configBuffer, size: CONFIG_BUFFER_BYTES } },
2920
+ { binding: 14, resource: inputView },
2921
+ { binding: 15, resource: targetView }
2922
+ ]
2923
+ });
2924
+ }
2925
+ function createDenoiseResolveBindGroup(inputView, targetView, label) {
2926
+ return device.createBindGroup({
2927
+ label,
2928
+ layout: denoiseResolveBindGroupLayout,
2929
+ entries: [
2930
+ { binding: 5, resource: { buffer: configBuffer, size: CONFIG_BUFFER_BYTES } },
2931
+ { binding: 17, resource: inputView },
2932
+ { binding: 18, resource: targetView }
2933
+ ]
2934
+ });
2935
+ }
2936
+ const denoiseRadianceBindGroup = createDenoiseRadianceBindGroup(
2937
+ radianceView,
2938
+ denoiseScratchView,
2939
+ "plasius.wavefront.bind.denoise.radianceToScratch"
2940
+ );
2941
+ const denoiseResolveBindGroup = createDenoiseResolveBindGroup(
2942
+ denoiseScratchView,
2943
+ outputView,
2944
+ "plasius.wavefront.bind.denoise.scratchToOutput"
2945
+ );
2946
+ const presentBindGroupLayout = device.createBindGroupLayout({
2947
+ label: "plasius.wavefront.presentBindGroupLayout",
2948
+ entries: [
2949
+ { binding: 0, visibility: constants.shader.FRAGMENT, texture: { sampleType: "float" } },
2950
+ { binding: 1, visibility: constants.shader.FRAGMENT, sampler: { type: "filtering" } }
2951
+ ]
2952
+ });
2953
+ const presentShader = device.createShaderModule({
2954
+ label: "plasius.wavefront.presentShader",
2955
+ code: PRESENT_WGSL
2956
+ });
2957
+ const presentPipeline = await createRenderPipeline(device, {
2958
+ label: "plasius.wavefront.presentPipeline",
2959
+ layout: device.createPipelineLayout({
2960
+ label: "plasius.wavefront.presentPipelineLayout",
2961
+ bindGroupLayouts: [presentBindGroupLayout]
2962
+ }),
2963
+ vertex: { module: presentShader, entryPoint: "vertexMain" },
2964
+ fragment: {
2965
+ module: presentShader,
2966
+ entryPoint: "fragmentMain",
2967
+ targets: [{ format }]
2968
+ },
2969
+ primitive: { topology: "triangle-list" }
2970
+ });
2971
+ const presentBindGroup = device.createBindGroup({
2972
+ label: "plasius.wavefront.presentBindGroup",
2973
+ layout: presentBindGroupLayout,
2974
+ entries: [
2975
+ { binding: 0, resource: outputView },
2976
+ { binding: 1, resource: sampler }
2977
+ ]
2978
+ });
2979
+ let frame = 0;
2980
+ const tiles = createTiles(config.width, config.height, config.tileSize);
2981
+ function dispatchGpuAccelerationBuild(frameIndex) {
2982
+ if (!config.gpuAccelerationBuildRequired) {
2983
+ return;
2984
+ }
2985
+ const buildTile = tiles[0] ?? { x: 0, y: 0, width: 1, height: 1 };
2986
+ const encoder = device.createCommandEncoder({
2987
+ label: `plasius.wavefront.buildAcceleration.${frameIndex}`
2988
+ });
2989
+ device.queue.writeBuffer(
2990
+ bvhBuildConfigBuffer,
2991
+ 0,
2992
+ createConfigPayload(config, buildTile, frameIndex, {
2993
+ sortItemCount: config.bvhLeafSortCapacity
2994
+ })
2995
+ );
2996
+ config.bvhSortStages.forEach((sortStage, stageIndex) => {
2997
+ device.queue.writeBuffer(
2998
+ bvhBuildConfigBuffer,
2999
+ (stageIndex + 1) * configBufferStride,
3000
+ createConfigPayload(config, buildTile, frameIndex, {
3001
+ start: sortStage.compareDistance,
3002
+ count: sortStage.sequenceSize,
3003
+ sortItemCount: config.bvhLeafSortCapacity
3004
+ })
3005
+ );
3006
+ });
3007
+ const buildLevelConfigStart = 1 + config.bvhSortStages.length;
3008
+ config.bvhBuildLevels.forEach((buildLevel, levelIndex) => {
3009
+ device.queue.writeBuffer(
3010
+ bvhBuildConfigBuffer,
3011
+ (buildLevelConfigStart + levelIndex) * configBufferStride,
3012
+ createConfigPayload(config, buildTile, frameIndex, buildLevel)
3013
+ );
3014
+ });
3015
+ const passEncoder = encoder.beginComputePass({
3016
+ label: "plasius.wavefront.buildAccelerationPass"
3017
+ });
3018
+ passEncoder.setBindGroup(0, bvhBuildBindGroup, [0]);
3019
+ passEncoder.setPipeline(pipelines.prepareMeshTrianglesAndLeaves);
3020
+ passEncoder.dispatchWorkgroups(Math.ceil(config.bvhLeafSortCapacity / WORKGROUP_SIZE));
3021
+ passEncoder.setPipeline(pipelines.sortBvhLeafRefs);
3022
+ for (let stageIndex = 0; stageIndex < config.bvhSortStages.length; stageIndex += 1) {
3023
+ passEncoder.setBindGroup(0, bvhBuildBindGroup, [
3024
+ (stageIndex + 1) * configBufferStride
3025
+ ]);
3026
+ passEncoder.dispatchWorkgroups(Math.ceil(config.bvhLeafSortCapacity / WORKGROUP_SIZE));
3027
+ }
3028
+ passEncoder.setBindGroup(0, bvhBuildBindGroup, [0]);
3029
+ passEncoder.setPipeline(pipelines.writeSortedBvhLeaves);
3030
+ passEncoder.dispatchWorkgroups(Math.ceil(config.triangleCount / WORKGROUP_SIZE));
3031
+ passEncoder.setPipeline(pipelines.buildBvhInternalLevel);
3032
+ for (let levelIndex = 0; levelIndex < config.bvhBuildLevels.length; levelIndex += 1) {
3033
+ const buildLevel = config.bvhBuildLevels[levelIndex];
3034
+ passEncoder.setBindGroup(0, bvhBuildBindGroup, [
3035
+ (buildLevelConfigStart + levelIndex) * configBufferStride
3036
+ ]);
3037
+ passEncoder.dispatchWorkgroups(Math.ceil(buildLevel.count / WORKGROUP_SIZE));
3038
+ }
3039
+ passEncoder.end();
3040
+ device.queue.submit([encoder.finish()]);
3041
+ }
3042
+ function dispatchTileSample(tile, frameIndex, sampleIndex) {
3043
+ const sampleWeight = 1 / config.samplesPerPixel;
3044
+ const configPayload = createConfigPayload(config, tile, frameIndex, {
3045
+ sampleIndex,
3046
+ sampleWeight
3047
+ });
3048
+ device.queue.writeBuffer(configBuffer, 0, configPayload);
3049
+ const encoder = device.createCommandEncoder({
3050
+ label: `plasius.wavefront.frame.${frameIndex}.tile.${tile.x}.${tile.y}.sample.${sampleIndex}`
3051
+ });
3052
+ const passEncoder = encoder.beginComputePass({
3053
+ label: "plasius.wavefront.computePass"
3054
+ });
3055
+ const tileWorkgroups = Math.ceil(tile.width * tile.height / WORKGROUP_SIZE);
3056
+ const capacityWorkgroups = Math.ceil(config.tilePixelCapacity / WORKGROUP_SIZE);
3057
+ passEncoder.setBindGroup(0, bindGroups[0], [0]);
3058
+ passEncoder.setPipeline(pipelines.generatePrimaryRays);
3059
+ passEncoder.dispatchWorkgroups(tileWorkgroups);
3060
+ for (let bounceIndex = 0; bounceIndex < config.maxDepth; bounceIndex += 1) {
3061
+ passEncoder.setBindGroup(0, bindGroups[bounceIndex % 2], [0]);
3062
+ passEncoder.setPipeline(pipelines.intersectActiveQueue);
3063
+ passEncoder.dispatchWorkgroups(capacityWorkgroups);
3064
+ passEncoder.setPipeline(pipelines.resolveSurfaceRecords);
3065
+ passEncoder.dispatchWorkgroups(capacityWorkgroups);
3066
+ passEncoder.setPipeline(pipelines.compactAndSwapQueues);
3067
+ passEncoder.dispatchWorkgroups(1);
3068
+ }
3069
+ passEncoder.end();
3070
+ device.queue.submit([encoder.finish()]);
3071
+ }
3072
+ function dispatchTileOutput(tile, frameIndex) {
3073
+ const configPayload = createConfigPayload(config, tile, frameIndex, {
3074
+ sampleIndex: 0,
3075
+ sampleWeight: 1 / config.samplesPerPixel
3076
+ });
3077
+ device.queue.writeBuffer(configBuffer, 0, configPayload);
3078
+ const encoder = device.createCommandEncoder({
3079
+ label: `plasius.wavefront.frame.${frameIndex}.tile.${tile.x}.${tile.y}.output`
3080
+ });
3081
+ const passEncoder = encoder.beginComputePass({
3082
+ label: "plasius.wavefront.outputPass"
3083
+ });
3084
+ const tileWorkgroups = Math.ceil(tile.width * tile.height / WORKGROUP_SIZE);
3085
+ passEncoder.setBindGroup(0, bindGroups[0], [0]);
3086
+ passEncoder.setPipeline(pipelines.accumulateTerminalRadiance);
3087
+ passEncoder.dispatchWorkgroups(tileWorkgroups);
3088
+ passEncoder.end();
3089
+ device.queue.submit([encoder.finish()]);
3090
+ }
3091
+ function dispatchTile(tile, frameIndex) {
3092
+ for (let sampleIndex = 0; sampleIndex < config.samplesPerPixel; sampleIndex += 1) {
3093
+ dispatchTileSample(tile, frameIndex, sampleIndex);
3094
+ }
3095
+ dispatchTileOutput(tile, frameIndex);
3096
+ }
3097
+ function dispatchDenoise(frameIndex) {
3098
+ if (!config.denoise) {
3099
+ return;
3100
+ }
3101
+ device.queue.writeBuffer(
3102
+ configBuffer,
3103
+ 0,
3104
+ createConfigPayload(
3105
+ config,
3106
+ { x: 0, y: 0, width: config.width, height: config.height },
3107
+ frameIndex,
3108
+ { sampleIndex: 0, sampleWeight: 1 / config.samplesPerPixel }
3109
+ )
3110
+ );
3111
+ const encoder = device.createCommandEncoder({
3112
+ label: `plasius.wavefront.frame.${frameIndex}.denoise`
3113
+ });
3114
+ const radiancePass = encoder.beginComputePass({
3115
+ label: "plasius.wavefront.denoiseRadiancePass"
3116
+ });
3117
+ radiancePass.setBindGroup(0, denoiseRadianceBindGroup, [0]);
3118
+ radiancePass.setPipeline(pipelines.denoiseLinearRadiance);
3119
+ radiancePass.dispatchWorkgroups(Math.ceil(config.width / 8), Math.ceil(config.height / 8));
3120
+ radiancePass.end();
3121
+ const resolvePass = encoder.beginComputePass({
3122
+ label: "plasius.wavefront.denoiseResolvePass"
3123
+ });
3124
+ resolvePass.setBindGroup(0, denoiseResolveBindGroup, [0]);
3125
+ resolvePass.setPipeline(pipelines.resolveDenoisedOutputImage);
3126
+ resolvePass.dispatchWorkgroups(Math.ceil(config.width / 8), Math.ceil(config.height / 8));
3127
+ resolvePass.end();
3128
+ device.queue.submit([encoder.finish()]);
3129
+ }
3130
+ function present() {
3131
+ const texture = context.getCurrentTexture();
3132
+ const encoder = device.createCommandEncoder({
3133
+ label: `plasius.wavefront.present.${frame}`
3134
+ });
3135
+ const passEncoder = encoder.beginRenderPass({
3136
+ label: "plasius.wavefront.presentPass",
3137
+ colorAttachments: [
3138
+ {
3139
+ view: texture.createView(),
3140
+ clearValue: { r: 0, g: 0, b: 0, a: 1 },
3141
+ loadOp: "clear",
3142
+ storeOp: "store"
3143
+ }
3144
+ ]
3145
+ });
3146
+ passEncoder.setPipeline(presentPipeline);
3147
+ passEncoder.setBindGroup(0, presentBindGroup);
3148
+ passEncoder.draw(3);
3149
+ passEncoder.end();
3150
+ device.queue.submit([encoder.finish()]);
3151
+ }
3152
+ function renderOnce() {
3153
+ frame += 1;
3154
+ dispatchGpuAccelerationBuild(frame + config.frameIndex);
3155
+ for (const tile of tiles) {
3156
+ dispatchTile(tile, frame + config.frameIndex);
3157
+ }
3158
+ dispatchDenoise(frame + config.frameIndex);
3159
+ present();
3160
+ return Object.freeze({
3161
+ frame,
3162
+ width: config.width,
3163
+ height: config.height,
3164
+ maxDepth: config.maxDepth,
3165
+ tiles: tiles.length,
3166
+ tileSize: config.tileSize,
3167
+ samplesPerPixel: config.samplesPerPixel,
3168
+ screenRays: config.width * config.height,
3169
+ primaryRays: config.width * config.height * config.samplesPerPixel,
3170
+ sceneObjectCount: config.sceneObjectCount,
3171
+ triangleCount: config.triangleCount,
3172
+ emissiveTriangleCount: config.emissiveTriangleCount,
3173
+ bvhNodeCount: config.bvhNodeCount,
3174
+ displayQuality: config.displayQuality,
3175
+ accelerationBuildMode: config.accelerationBuildMode,
3176
+ gpuAccelerationBuildRequired: config.gpuAccelerationBuildRequired,
3177
+ memory: config.memory
3178
+ });
3179
+ }
3180
+ async function readOutputProbe(optionsForProbe = {}) {
3181
+ const mapMode = constants.map;
3182
+ if (!mapMode) {
3183
+ throw new Error("GPUMapMode.READ is unavailable in this environment.");
3184
+ }
3185
+ const x = clamp(readNonNegativeInteger("x", optionsForProbe.x, Math.floor(config.width / 2)), 0, config.width - 1);
3186
+ const y = clamp(readNonNegativeInteger("y", optionsForProbe.y, Math.floor(config.height / 2)), 0, config.height - 1);
3187
+ const readback = device.createBuffer({
3188
+ label: "plasius.wavefront.outputProbe",
3189
+ size: 256,
3190
+ usage: constants.buffer.COPY_DST | constants.buffer.MAP_READ
3191
+ });
3192
+ const encoder = device.createCommandEncoder({
3193
+ label: "plasius.wavefront.outputProbe.copy"
3194
+ });
3195
+ encoder.copyTextureToBuffer(
3196
+ { texture: outputTexture, origin: { x, y } },
3197
+ { buffer: readback, bytesPerRow: 256, rowsPerImage: 1 },
3198
+ { width: 1, height: 1, depthOrArrayLayers: 1 }
3199
+ );
3200
+ device.queue.submit([encoder.finish()]);
3201
+ await readback.mapAsync(mapMode.READ);
3202
+ const bytes = new Uint8Array(readback.getMappedRange()).slice(0, 4);
3203
+ readback.unmap();
3204
+ readback.destroy?.();
3205
+ return Object.freeze({
3206
+ x,
3207
+ y,
3208
+ rgba: Object.freeze(Array.from(bytes)),
3209
+ luminance: (0.2126 * bytes[0] + 0.7152 * bytes[1] + 0.0722 * bytes[2]) / 255
3210
+ });
3211
+ }
3212
+ function updateSceneObjects(sceneObjects) {
3213
+ const nextPackedScene = packWavefrontSceneObjects(sceneObjects, config.sceneObjectCapacity);
3214
+ packedScene = nextPackedScene;
3215
+ config = createWavefrontPathTracingComputeConfig({
3216
+ ...options,
3217
+ canvas,
3218
+ width: config.width,
3219
+ height: config.height,
3220
+ maxDepth: config.maxDepth,
3221
+ tileSize: config.tileSize,
3222
+ samplesPerPixel: config.samplesPerPixel,
3223
+ sceneObjectCapacity: config.sceneObjectCapacity,
3224
+ sceneObjects: packedScene.objects,
3225
+ frameIndex: config.frameIndex
3226
+ });
3227
+ device.queue.writeBuffer(sceneObjectBuffer, 0, packedScene.buffer);
3228
+ return config;
3229
+ }
3230
+ function getSnapshot() {
3231
+ return Object.freeze({
3232
+ frame,
3233
+ width: config.width,
3234
+ height: config.height,
3235
+ maxDepth: config.maxDepth,
3236
+ tiles: tiles.length,
3237
+ tileSize: config.tileSize,
3238
+ samplesPerPixel: config.samplesPerPixel,
3239
+ sceneObjectCount: config.sceneObjectCount,
3240
+ triangleCount: config.triangleCount,
3241
+ emissiveTriangleCount: config.emissiveTriangleCount,
3242
+ bvhNodeCount: config.bvhNodeCount,
3243
+ displayQuality: config.displayQuality,
3244
+ accelerationBuildMode: config.accelerationBuildMode,
3245
+ gpuAccelerationBuildRequired: config.gpuAccelerationBuildRequired,
3246
+ memory: config.memory
3247
+ });
3248
+ }
3249
+ function destroy() {
3250
+ activeQueue.destroy?.();
3251
+ nextQueue.destroy?.();
3252
+ hitBuffer.destroy?.();
3253
+ accumulationBuffer.destroy?.();
3254
+ sceneObjectBuffer.destroy?.();
3255
+ triangleBuffer.destroy?.();
3256
+ bvhNodeBuffer.destroy?.();
3257
+ meshVertexBuffer.destroy?.();
3258
+ meshIndexBuffer.destroy?.();
3259
+ meshRangeBuffer.destroy?.();
3260
+ bvhLeafRefBuffer.destroy?.();
3261
+ configBuffer.destroy?.();
3262
+ bvhBuildConfigBuffer.destroy?.();
3263
+ counterBuffer.destroy?.();
3264
+ radianceTexture.destroy?.();
3265
+ denoiseScratchTexture.destroy?.();
3266
+ outputTexture.destroy?.();
3267
+ context.unconfigure?.();
3268
+ }
3269
+ return Object.freeze({
3270
+ canvas,
3271
+ context,
3272
+ device,
3273
+ format,
3274
+ config,
3275
+ renderOnce,
3276
+ readOutputProbe,
3277
+ updateSceneObjects,
3278
+ getSnapshot,
3279
+ destroy
3280
+ });
3281
+ }
3282
+
3283
+ // src/index.js
46
3284
  var DEFAULT_CLEAR_COLOR = Object.freeze([0.07, 0.11, 0.18, 1]);
47
3285
  var DEFAULT_CANVAS_SELECTOR = "canvas[data-plasius-gpu-renderer]";
48
3286
  var rendererDebugOwner = "renderer";
@@ -280,9 +3518,9 @@ function buildWavefrontBounceSchedule(maxDepth) {
280
3518
  );
281
3519
  }
282
3520
  function createWavefrontPathTracingPlan(options = {}) {
283
- const maxDepth = options.maxDepth === void 0 ? 6 : readPositiveInteger("maxDepth", options.maxDepth);
284
- const queueCapacity = options.queueCapacity === void 0 ? 8192 : readPositiveInteger("queueCapacity", options.queueCapacity);
285
- const accumulationResetEpoch = options.accumulationResetEpoch === void 0 ? 0 : readNonNegativeInteger("accumulationResetEpoch", options.accumulationResetEpoch);
3521
+ const maxDepth = options.maxDepth === void 0 ? 6 : readPositiveInteger2("maxDepth", options.maxDepth);
3522
+ const queueCapacity = options.queueCapacity === void 0 ? 8192 : readPositiveInteger2("queueCapacity", options.queueCapacity);
3523
+ const accumulationResetEpoch = options.accumulationResetEpoch === void 0 ? 0 : readNonNegativeInteger2("accumulationResetEpoch", options.accumulationResetEpoch);
286
3524
  const explicitLightSampling = options.explicitLightSampling === true;
287
3525
  return Object.freeze({
288
3526
  schemaVersion: rendererWavefrontBufferSchemaVersion,
@@ -889,13 +4127,13 @@ function readPositiveNumber(name, value) {
889
4127
  }
890
4128
  return value;
891
4129
  }
892
- function readPositiveInteger(name, value) {
4130
+ function readPositiveInteger2(name, value) {
893
4131
  if (!Number.isInteger(value) || value <= 0) {
894
4132
  throw new Error(`${name} must be a positive integer.`);
895
4133
  }
896
4134
  return value;
897
4135
  }
898
- function readNonNegativeInteger(name, value) {
4136
+ function readNonNegativeInteger2(name, value) {
899
4137
  if (!Number.isInteger(value) || value < 0) {
900
4138
  throw new Error(`${name} must be a non-negative integer.`);
901
4139
  }
@@ -1011,7 +4249,7 @@ function readDocument(documentOverride) {
1011
4249
  }
1012
4250
  return doc;
1013
4251
  }
1014
- function resolveCanvas(canvasOrSelector, documentOverride) {
4252
+ function resolveCanvas2(canvasOrSelector, documentOverride) {
1015
4253
  if (canvasOrSelector && typeof canvasOrSelector === "object") {
1016
4254
  return canvasOrSelector;
1017
4255
  }
@@ -1089,7 +4327,7 @@ async function createGpuRenderer(options = {}) {
1089
4327
  throw new Error("Unable to obtain GPU adapter.");
1090
4328
  }
1091
4329
  const device = await adapter.requestDevice();
1092
- const targetCanvas = resolveCanvas(canvas, documentOverride);
4330
+ const targetCanvas = resolveCanvas2(canvas, documentOverride);
1093
4331
  const context = targetCanvas.getContext?.("webgpu");
1094
4332
  if (!context) {
1095
4333
  throw new Error("Unable to obtain WebGPU canvas context.");
@@ -1330,14 +4568,28 @@ var defaultRendererClearColor = DEFAULT_CLEAR_COLOR;
1330
4568
  // Annotate the CommonJS export names for ESM import in node:
1331
4569
  0 && (module.exports = {
1332
4570
  bindRendererToXrManager,
4571
+ createDefaultWavefrontSceneObjects,
1333
4572
  createGpuRenderer,
1334
4573
  createRayTracingRenderPlan,
1335
4574
  createRendererDebugHooks,
4575
+ createWavefrontBvhBuildLevels,
4576
+ createWavefrontBvhSortStages,
4577
+ createWavefrontEmissiveTriangleIndexSource,
4578
+ createWavefrontGpuMeshSource,
4579
+ createWavefrontMeshAcceleration,
4580
+ createWavefrontPathTracingComputeConfig,
4581
+ createWavefrontPathTracingComputeRenderer,
1336
4582
  createWavefrontPathTracingPlan,
1337
4583
  defaultRendererClearColor,
1338
4584
  defaultRendererWorkerProfile,
4585
+ estimateWavefrontPathTracingMemory,
1339
4586
  getRendererWorkerManifest,
1340
4587
  getRendererWorkerProfile,
4588
+ normalizeWavefrontMesh,
4589
+ normalizeWavefrontSceneObject,
4590
+ packWavefrontBvhNodes,
4591
+ packWavefrontSceneObjects,
4592
+ packWavefrontTriangles,
1341
4593
  rendererAccelerationStructureUpdateClasses,
1342
4594
  rendererDebugOwner,
1343
4595
  rendererRayTracingStageOrder,
@@ -1350,6 +4602,10 @@ var defaultRendererClearColor = DEFAULT_CLEAR_COLOR;
1350
4602
  rendererWorkerProfileNames,
1351
4603
  rendererWorkerProfiles,
1352
4604
  rendererWorkerQueueClass,
1353
- supportsWebGpu
4605
+ supportsWavefrontPathTracingCompute,
4606
+ supportsWebGpu,
4607
+ wavefrontMaterialKinds,
4608
+ wavefrontPathTracingComputeLimits,
4609
+ wavefrontSceneObjectKinds
1354
4610
  });
1355
4611
  //# sourceMappingURL=index.cjs.map