@plasius/gpu-renderer 0.1.13 → 0.1.15

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