Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Add Cook FORMAT-v2 packer, Cycles host session, and lobe probe (#894)

Nguyen Xuan And4ed95ae9937
diff --git a/changes/894-cook-cycles-kernel.md b/changes/894-cook-cycles-kernel.md
new file mode 100644
index 00000000..6e0c458f
--- /dev/null
+++ b/changes/894-cook-cycles-kernel.md
@@ -0,0 +1 @@
+- Add the Cook `FORMAT-v2` scene packer (`pack-input-v2.mjs`), multi-BLAS/TLAS Cycles host session, and `probeCyclesLobe` entry-point runner in `packages/render-native`.
diff --git a/packages/render-native/build.mjs b/packages/render-native/build.mjs
index f5f15848..75222827 100644
--- a/packages/render-native/build.mjs
+++ b/packages/render-native/build.mjs
@@ -1,19 +1,32 @@
// Builds the native addon with cargo and copies it to build/render-native.node.
// Windows must target MSVC: the default GNU toolchain crashes any wgpu 30 program before main.
import { spawnSync } from 'node:child_process';
-import { copyFileSync, mkdirSync } from 'node:fs';
+import { copyFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
import { dirname, join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
const packageDirectory = dirname(fileURLToPath(import.meta.url));
const targetArguments = process.platform === 'win32' ? ['--target', 'x86_64-pc-windows-msvc'] : [];
-const build = spawnSync('cargo', ['build', '--release', ...targetArguments], { cwd: packageDirectory, stdio: 'inherit' });
-if (build.status !== 0) process.exit(build.status ?? 1);
-
const targetDirectory = process.env.CARGO_TARGET_DIR
? resolve(packageDirectory, process.env.CARGO_TARGET_DIR)
: join(packageDirectory, 'target');
const releaseDirectory = join(targetDirectory, ...(targetArguments.length > 0 ? [targetArguments[1]] : []), 'release');
+const worktreeStampPath = join(releaseDirectory, '.render-native-package-dir');
+if (process.env.CARGO_TARGET_DIR) {
+ const previousPackageDirectory = existsSync(worktreeStampPath) ? readFileSync(worktreeStampPath, 'utf8').trim() : '';
+ if (previousPackageDirectory !== packageDirectory) {
+ spawnSync('cargo', ['clean', '-p', 'render-native', '--release', ...targetArguments], {
+ cwd: packageDirectory,
+ stdio: 'inherit',
+ });
+ }
+}
+
+const build = spawnSync('cargo', ['build', '--release', ...targetArguments], { cwd: packageDirectory, stdio: 'inherit' });
+if (build.status !== 0) process.exit(build.status ?? 1);
+if (process.env.CARGO_TARGET_DIR) {
+ writeFileSync(worktreeStampPath, `${packageDirectory}\n`);
+}
const libraryName = { win32: 'render_native.dll', darwin: 'librender_native.dylib', linux: 'librender_native.so' }[process.platform];
mkdirSync(join(packageDirectory, 'build'), { recursive: true });
copyFileSync(join(releaseDirectory, libraryName), join(packageDirectory, 'build', 'render-native.node'));
diff --git a/packages/render-native/build.rs b/packages/render-native/build.rs
index 4aeaf110..23d8146b 100644
--- a/packages/render-native/build.rs
+++ b/packages/render-native/build.rs
@@ -4,8 +4,10 @@ use std::path::{Component, Path, PathBuf};
fn parse_manifest_entries(manifest_text: &str) -> Vec<String> {
let mut entries = Vec::new();
- for raw_line in manifest_text.lines() {
- let without_comment = raw_line.split('#').next().unwrap_or("");
+ let without_file_bom = manifest_text.trim_start_matches('\u{feff}');
+ for raw_line in without_file_bom.lines() {
+ let without_line_bom = raw_line.trim_start_matches('\u{feff}');
+ let without_comment = without_line_bom.split('#').next().unwrap_or("");
let trimmed = without_comment.trim();
if !trimmed.is_empty() {
entries.push(trimmed.to_string());
@@ -49,7 +51,9 @@ fn main() {
let cycles_directory = PathBuf::from("src").join("cycles");
let manifest_path = cycles_directory.join("kernel-manifest.txt");
+ let bootstrap_path = cycles_directory.join("bootstrap_main.wgsl");
println!("cargo:rerun-if-changed={}", manifest_path.display());
+ println!("cargo:rerun-if-changed={}", bootstrap_path.display());
let manifest_text = fs::read_to_string(&manifest_path)
.unwrap_or_else(|error| panic!("Could not read {}: {error}", manifest_path.display()));
diff --git a/packages/render-native/index.mjs b/packages/render-native/index.mjs
index d1343bf9..a434252c 100644
--- a/packages/render-native/index.mjs
+++ b/packages/render-native/index.mjs
@@ -5,7 +5,24 @@ import { createRequire } from 'node:module';
import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
+import {
+ FORMAT_V2_MAGIC,
+ FORMAT_V2_VERSION,
+ STRUCT_STRIDES_V2,
+ buildNativeInputV2,
+ packMaterialRecordV2,
+ upgradeNativeInputV1ToV2,
+} from './pack-input-v2.mjs';
+
export { buildNativeInput, buildNativeTexelInput } from './pack-input.mjs';
+export {
+ FORMAT_V2_MAGIC,
+ FORMAT_V2_VERSION,
+ STRUCT_STRIDES_V2,
+ buildNativeInputV2,
+ packMaterialRecordV2,
+ upgradeNativeInputV1ToV2,
+};
const PACKAGE_DIRECTORY = dirname(fileURLToPath(import.meta.url));
const ADDON_PATH = join(PACKAGE_DIRECTORY, 'build', 'render-native.node');
@@ -37,9 +54,110 @@ export function resolveNativeKernel(kernel) {
* average of `samples` paths) with the adapter name and timings in seconds. `maxSeconds` makes the trace fail once it has
* run that long. `kernel` selects `"legacy"` (default) or `"cycles"` (falling back to `JS67_NATIVE_KERNEL` when omitted).
*/
-export function traceNative(input, { width, height, samples, maxSeconds, kernel } = {}) {
+export function traceNative(input, options = {}) {
+ const { width, height, samples, maxSeconds, kernel, samplesPerDispatch, bootstrapKernel } = options;
const selectedKernel = resolveNativeKernel(kernel);
- return loadAddon().traceScene(input, { width, height, samples, maxSeconds, kernel: selectedKernel });
+ const addon = loadAddon();
+ if (selectedKernel === 'legacy') {
+ if (input?.schemaVersion === FORMAT_V2_VERSION) {
+ throw new TypeError(
+ 'Cannot pass a FORMAT-v2 scene input to kernel "legacy": pass kernel "cycles" or build a v1 input with buildNativeInput.'
+ );
+ }
+ return addon.traceScene(input, { width, height, samples, maxSeconds, kernel: selectedKernel });
+ }
+ const v2Input = input?.schemaVersion === FORMAT_V2_VERSION
+ ? input
+ : upgradeNativeInputV1ToV2(input, options);
+ return addon.traceSceneCycles(v2Input, {
+ width,
+ height,
+ samples,
+ samplesPerDispatch,
+ maxSeconds,
+ bootstrapKernel,
+ });
+}
+
+function buildProbeKernelParams({ width, height, mode, seed, wo, frontFace, materialCount, textureCount }) {
+ const buffer = new ArrayBuffer(STRUCT_STRIDES_V2.kernelParams);
+ const f32 = new Float32Array(buffer);
+ const u32 = new Uint32Array(buffer);
+ const length = Math.hypot(wo[0], wo[1], wo[2]);
+ if (!(length > 1e-12) || !wo.every(Number.isFinite)) {
+ throw new RangeError('probeCyclesLobe option `wo` must be a non-zero finite 3D vector.');
+ }
+ u32[0] = FORMAT_V2_MAGIC;
+ u32[1] = FORMAT_V2_VERSION;
+ u32[2] = width >>> 0;
+ u32[3] = height >>> 0;
+ u32[4] = 0;
+ u32[5] = 1;
+ u32[6] = 1;
+ u32[7] = (seed ?? 1) >>> 0;
+ u32[8] = (mode ?? 0) >>> 0;
+ u32[23] = materialCount >>> 0;
+ u32[27] = textureCount >>> 0;
+ f32[31] = frontFace === false ? -1.0 : 1.0;
+ f32[32] = wo[0] / length;
+ f32[33] = wo[1] / length;
+ f32[34] = wo[2] / length;
+ f32[35] = 1e30;
+ f32[72] = 1.0;
+ return new Uint8Array(buffer);
+}
+
+/**
+ * Dispatches entry point `"test_lobe_samples"` on the assembled Cycles shader and returns the raw un-divided
+ * `Float32Array` of all 4 `film_accumulation` planes (`4 * width * height * 4` floats).
+ */
+export function probeCyclesLobe(options = {}) {
+ const width = options.width ?? 512;
+ const height = options.height ?? 512;
+ if (!Number.isInteger(width) || width < 1 || !Number.isInteger(height) || height < 1) {
+ throw new RangeError('probeCyclesLobe requires positive integer `width` and `height`.');
+ }
+ const wo = options.wo ?? [0, 0, 1];
+ if (!Array.isArray(wo) && !ArrayBuffer.isView(wo) || wo.length !== 3) {
+ throw new TypeError('probeCyclesLobe option `wo` must hold 3 numbers.');
+ }
+
+ let materials;
+ if (options.materialBytes !== undefined) {
+ if (!(options.materialBytes instanceof Uint8Array) || options.materialBytes.byteLength < STRUCT_STRIDES_V2.material || options.materialBytes.byteLength % STRUCT_STRIDES_V2.material !== 0) {
+ throw new TypeError(`probeCyclesLobe option \`materialBytes\` must be a Uint8Array of a positive multiple of ${STRUCT_STRIDES_V2.material} bytes.`);
+ }
+ materials = options.materialBytes;
+ } else {
+ materials = packMaterialRecordV2(options.material ?? {}, null).bytes;
+ }
+
+ const materialCount = materials.byteLength / STRUCT_STRIDES_V2.material;
+ const textureDescriptors = options.textureDescriptors;
+ const textureCount = textureDescriptors ? Math.floor(textureDescriptors.byteLength / STRUCT_STRIDES_V2.textureDescriptor) : 0;
+ const kernelParams = options.kernelParams instanceof Uint8Array
+ ? options.kernelParams
+ : buildProbeKernelParams({
+ width,
+ height,
+ mode: options.mode ?? 0,
+ seed: options.seed ?? 1,
+ wo,
+ frontFace: options.frontFace ?? true,
+ materialCount,
+ textureCount,
+ });
+
+ return loadAddon().probeCyclesLobe({
+ width,
+ height,
+ kernelParams,
+ materials,
+ textureDescriptors,
+ textureTexels: options.textureTexels,
+ maxSeconds: options.maxSeconds,
+ bootstrapKernel: options.bootstrapKernel,
+ });
}
/**
diff --git a/packages/render-native/pack-input-v2.mjs b/packages/render-native/pack-input-v2.mjs
new file mode 100644
index 00000000..d26e2382
--- /dev/null
+++ b/packages/render-native/pack-input-v2.mjs
@@ -0,0 +1,2534 @@
+// Packs a 67js trace scene (or upgrades a legacy v1 input) into the FORMAT-v2 binary tables read by the Cycles-parity
+// native kernel (`FORMAT-v2.md` and `src/cycles/abi.wgsl`). Pure typed arrays with zero Node-only imports.
+
+export const FORMAT_V2_MAGIC = 0x36375054;
+export const FORMAT_V2_VERSION = 2;
+export const INVALID_INDEX_V2 = 0xffffffff;
+
+export const STRUCT_STRIDES_V2 = Object.freeze({
+ kernelParams: 320,
+ instance: 160,
+ triangle: 224,
+ material: 256,
+ emissiveTriangle: 96,
+ light: 128,
+ lightTreeNode: 64,
+ textureDescriptor: 32,
+});
+
+const KERNEL_FLAG_USE_LIGHT_TREE = 1;
+const KERNEL_FLAG_HAS_VOLUME = 2;
+const KERNEL_FLAG_HAS_SUBSURFACE = 4;
+const KERNEL_FLAG_ORTHOGRAPHIC_CAMERA = 8;
+const KERNEL_FLAG_ADAPTIVE_SAMPLING = 16;
+const KERNEL_FLAG_TRANSPARENT_BACKGROUND = 32;
+
+const INSTANCE_DEFAULT_VISIBILITY = 1 | 2 | 4 | 8 | 16 | 32;
+const INSTANCE_FLAG_NEGATIVE_SCALE = 64;
+
+const TRIANGLE_FLAG_SMOOTH_NORMALS = 1;
+const TRIANGLE_FLAG_HAS_VERTEX_COLORS = 2;
+const TRIANGLE_FLAG_HAS_UV1 = 4;
+const TRIANGLE_FLAG_HAS_TANGENTS = 8;
+const TRIANGLE_FLAG_DOUBLE_SIDED = 16;
+
+const LIGHT_TYPE_POINT = 0;
+const LIGHT_TYPE_SPOT = 1;
+const LIGHT_TYPE_AREA_RECT = 2;
+const LIGHT_TYPE_AREA_DISK = 3;
+const LIGHT_TYPE_SUN = 4;
+
+const LIGHT_FLAG_CAST_SHADOW = 1;
+const LIGHT_FLAG_MULTIPLE_IMPORTANCE = 2;
+const LIGHT_FLAG_CAMERA_VISIBLE = 4;
+const LIGHT_FLAG_PORTAL = 8;
+const LIGHT_FLAG_NORMALIZE = 16;
+
+const MATERIAL_FLAG_MULTISCATTER_GGX = 1;
+const MATERIAL_FLAG_THIN_WALLED = 2;
+const MATERIAL_FLAG_TRANSPARENT_SHADOW = 4;
+const MATERIAL_FLAG_DOUBLE_SIDED = 8;
+const MATERIAL_FLAG_EMISSIVE_MIS = 16;
+const MATERIAL_FLAG_F82_METALLIC = 32;
+
+const ALPHA_MODE_OPAQUE = 0;
+const ALPHA_MODE_MASK = 1;
+const ALPHA_MODE_BLEND = 2;
+
+const TEXTURE_FORMAT_RGBA8_UNORM = 0;
+const TEXTURE_FORMAT_RGBA8_SRGB = 1;
+const TEXTURE_FORMAT_RGBA32_FLOAT = 2;
+const TEXTURE_FORMAT_RG16_FLOAT = 3;
+
+const DEFAULT_HDRI_RADIANCE_LIMIT = 16;
+const SUN_DEFAULT_HALF_ANGLE = Math.PI / 360;
+const IDENTITY_MATRIX_4X4 = Object.freeze([
+ 1, 0, 0, 0,
+ 0, 1, 0, 0,
+ 0, 0, 1, 0,
+ 0, 0, 0, 1,
+]);
+
+function srgbByteToLinearTable() {
+ const table = new Float32Array(256);
+ for (let byteValue = 0; byteValue < 256; byteValue++) {
+ const encoded = byteValue / 255;
+ table[byteValue] = encoded <= 0.04045 ? encoded / 12.92 : ((encoded + 0.055) / 1.055) ** 2.4;
+ }
+ return table;
+}
+
+const SRGB_BYTE_TO_LINEAR = srgbByteToLinearTable();
+
+function luminance(rgb) {
+ return 0.2126 * rgb[0] + 0.7152 * rgb[1] + 0.0722 * rgb[2];
+}
+
+function normalizeVec3(vector, fallback = [0, 0, 1]) {
+ const x = Number(vector?.[0] ?? 0);
+ const y = Number(vector?.[1] ?? 0);
+ const z = Number(vector?.[2] ?? 0);
+ const length = Math.hypot(x, y, z);
+ if (!(length > 1e-12)) {
+ return [fallback[0], fallback[1], fallback[2]];
+ }
+ return [x / length, y / length, z / length];
+}
+
+function crossVec3(first, second) {
+ return [
+ first[1] * second[2] - first[2] * second[1],
+ first[2] * second[0] - first[0] * second[2],
+ first[0] * second[1] - first[1] * second[0],
+ ];
+}
+
+function dotVec3(first, second) {
+ return first[0] * second[0] + first[1] * second[1] + first[2] * second[2];
+}
+
+function orthonormalBasis(direction) {
+ const axisZ = normalizeVec3(direction, [0, 0, 1]);
+ const guide = Math.abs(axisZ[1]) < 0.999 ? [0, 1, 0] : [1, 0, 0];
+ const axisU = normalizeVec3(crossVec3(guide, axisZ), [1, 0, 0]);
+ const axisV = normalizeVec3(crossVec3(axisZ, axisU), [0, 1, 0]);
+ return { axisU, axisV };
+}
+
+function deterministicUnitHash(seedValue) {
+ let state = (seedValue >>> 0) + 0x9e3779b9;
+ state = Math.imul(state ^ (state >>> 16), 0x85ebca6b) >>> 0;
+ state = Math.imul(state ^ (state >>> 13), 0xc2b2ae35) >>> 0;
+ state = (state ^ (state >>> 16)) >>> 0;
+ return state / 4294967296;
+}
+
+function resolveLightMaskWords(lightMask, lightMaskHi) {
+ if (lightMask === undefined || lightMask === null || lightMask < 0) {
+ return { lo: 0xffffffff, hi: lightMaskHi === undefined ? 0xffffffff : lightMaskHi >>> 0 };
+ }
+ return {
+ lo: lightMask >>> 0,
+ hi: lightMaskHi === undefined ? 0 : lightMaskHi >>> 0,
+ };
+}
+
+function lightBitMaskWords(bitIndex, explicitMaskLo, explicitMaskHi) {
+ if (explicitMaskLo !== undefined) {
+ return { lo: explicitMaskLo >>> 0, hi: (explicitMaskHi ?? 0) >>> 0 };
+ }
+ if (!Number.isInteger(bitIndex) || bitIndex < 0) {
+ return { lo: 0xffffffff, hi: 0xffffffff };
+ }
+ if (bitIndex < 32) {
+ return { lo: (1 << bitIndex) >>> 0, hi: 0 };
+ }
+ if (bitIndex < 64) {
+ return { lo: 0, hi: (1 << (bitIndex - 32)) >>> 0 };
+ }
+ return { lo: 0xffffffff, hi: 0xffffffff };
+}
+
+function decomposeAffineMatrix(columnMajorMatrix = IDENTITY_MATRIX_4X4) {
+ const m00 = Number(columnMajorMatrix[0]);
+ const m10 = Number(columnMajorMatrix[1]);
+ const m20 = Number(columnMajorMatrix[2]);
+ const m01 = Number(columnMajorMatrix[4]);
+ const m11 = Number(columnMajorMatrix[5]);
+ const m21 = Number(columnMajorMatrix[6]);
+ const m02 = Number(columnMajorMatrix[8]);
+ const m12 = Number(columnMajorMatrix[9]);
+ const m22 = Number(columnMajorMatrix[10]);
+ const tx = Number(columnMajorMatrix[12]);
+ const ty = Number(columnMajorMatrix[13]);
+ const tz = Number(columnMajorMatrix[14]);
+
+ const c00 = m11 * m22 - m12 * m21;
+ const c01 = m12 * m20 - m10 * m22;
+ const c02 = m10 * m21 - m11 * m20;
+ const c10 = m02 * m21 - m01 * m22;
+ const c11 = m00 * m22 - m02 * m20;
+ const c12 = m01 * m20 - m00 * m21;
+ const c20 = m01 * m12 - m02 * m11;
+ const c21 = m02 * m10 - m00 * m12;
+ const c22 = m00 * m11 - m01 * m10;
+ const determinant = m00 * c00 + m01 * c01 + m02 * c02;
+ if (!Number.isFinite(determinant) || Math.abs(determinant) < 1e-18) {
+ throw new RangeError('Instance affine transform matrix is singular or non-finite.');
+ }
+ const invDet = 1 / determinant;
+ const im00 = c00 * invDet;
+ const im01 = c10 * invDet;
+ const im02 = c20 * invDet;
+ const im10 = c01 * invDet;
+ const im11 = c11 * invDet;
+ const im12 = c21 * invDet;
+ const im20 = c02 * invDet;
+ const im21 = c12 * invDet;
+ const im22 = c22 * invDet;
+
+ const itx = -(im00 * tx + im01 * ty + im02 * tz);
+ const ity = -(im10 * tx + im11 * ty + im12 * tz);
+ const itz = -(im20 * tx + im21 * ty + im22 * tz);
+
+ return {
+ objectToWorld: [
+ m00, m01, m02, tx,
+ m10, m11, m12, ty,
+ m20, m21, m22, tz,
+ ],
+ worldToObject: [
+ im00, im01, im02, itx,
+ im10, im11, im12, ity,
+ im20, im21, im22, itz,
+ ],
+ negativeScale: determinant < 0,
+ };
+}
+
+function transformPoint3x4(rows, point) {
+ return [
+ rows[0] * point[0] + rows[1] * point[1] + rows[2] * point[2] + rows[3],
+ rows[4] * point[0] + rows[5] * point[1] + rows[6] * point[2] + rows[7],
+ rows[8] * point[0] + rows[9] * point[1] + rows[10] * point[2] + rows[11],
+ ];
+}
+
+function transformDirection3x4(rows, vector) {
+ return [
+ rows[0] * vector[0] + rows[1] * vector[1] + rows[2] * vector[2],
+ rows[4] * vector[0] + rows[5] * vector[1] + rows[6] * vector[2],
+ rows[8] * vector[0] + rows[9] * vector[1] + rows[10] * vector[2],
+ ];
+}
+
+function createTextureCollector() {
+ const indexByKey = new Map();
+ const dataIdMap = new WeakMap();
+ let nextDataId = 1;
+ const descriptors = [];
+ const wordChunks = [];
+ let totalWords = 0;
+
+ function objectIdentity(dataBuffer) {
+ if (!dataIdMap.has(dataBuffer)) {
+ dataIdMap.set(dataBuffer, nextDataId++);
+ }
+ return dataIdMap.get(dataBuffer);
+ }
+
+ function addTexture(rawDescriptor, defaultSrgb = false) {
+ if (!rawDescriptor) {
+ return { index: -1, meanLinearRgb: [1, 1, 1] };
+ }
+ const image = rawDescriptor.image ?? rawDescriptor;
+ const width = Number(image.width ?? 0);
+ const height = Number(image.height ?? 0);
+ const data = image.data;
+ if (!(width >= 1 && height >= 1) || !data) {
+ return { index: -1, meanLinearRgb: [1, 1, 1] };
+ }
+
+ let format = TEXTURE_FORMAT_RGBA8_UNORM;
+ if (typeof rawDescriptor.format === 'number') {
+ format = rawDescriptor.format & 0xff;
+ } else if (data instanceof Float32Array) {
+ format = TEXTURE_FORMAT_RGBA32_FLOAT;
+ } else if (data instanceof Uint16Array) {
+ format = TEXTURE_FORMAT_RG16_FLOAT;
+ } else {
+ const explicitLinear = rawDescriptor.colorSpace === 'linear' || rawDescriptor.colorLookup === null;
+ const explicitSrgb = rawDescriptor.colorSpace === 'srgb' || Boolean(rawDescriptor.colorLookup);
+ const isSrgb = explicitLinear ? false : (explicitSrgb || defaultSrgb);
+ format = isSrgb ? TEXTURE_FORMAT_RGBA8_SRGB : TEXTURE_FORMAT_RGBA8_UNORM;
+ }
+
+ const repeatU = rawDescriptor.wrapU ?? (rawDescriptor.repeat === false ? 1 : 0);
+ const repeatV = rawDescriptor.wrapV ?? (rawDescriptor.repeat === false ? 1 : 0);
+ const mipCount = Math.max(1, Math.min(255, Number(rawDescriptor.mipCount ?? 1)));
+ const nearest = rawDescriptor.nearest ? 1 : 0;
+ const useUv1 = rawDescriptor.uvSet === 1 ? 1 : 0;
+ const uvScale = rawDescriptor.uvScale ?? [1, 1];
+ const uvOffset = rawDescriptor.uvOffset ?? [0, 0];
+ const formatAndSampler = (
+ (format & 0xff) |
+ ((mipCount & 0xff) << 8) |
+ ((repeatU & 0x3) << 16) |
+ ((repeatV & 0x3) << 18) |
+ (nearest << 20) |
+ (useUv1 << 21)
+ ) >>> 0;
+
+ const dedupeKey = `${objectIdentity(data)}|${width}x${height}|${formatAndSampler}|${uvScale[0]},${uvScale[1]}|${uvOffset[0]},${uvOffset[1]}`;
+ if (indexByKey.has(dedupeKey)) {
+ return indexByKey.get(dedupeKey);
+ }
+
+ const pixelCount = width * height;
+ const dataOffset = totalWords;
+ let packedWords;
+ let sumR = 0;
+ let sumG = 0;
+ let sumB = 0;
+
+ if (format === TEXTURE_FORMAT_RGBA32_FLOAT) {
+ const floatPixels = data instanceof Float32Array ? data : new Float32Array(data);
+ const floatBuffer = new ArrayBuffer(pixelCount * 16);
+ const floatView = new Float32Array(floatBuffer);
+ const channels = Math.max(1, Math.floor(floatPixels.length / pixelCount));
+ for (let pixel = 0; pixel < pixelCount; pixel++) {
+ const r = floatPixels[pixel * channels] ?? 0;
+ const g = channels > 1 ? floatPixels[pixel * channels + 1] : r;
+ const b = channels > 2 ? floatPixels[pixel * channels + 2] : r;
+ const a = channels > 3 ? floatPixels[pixel * channels + 3] : 1;
+ floatView[pixel * 4] = r;
+ floatView[pixel * 4 + 1] = g;
+ floatView[pixel * 4 + 2] = b;
+ floatView[pixel * 4 + 3] = a;
+ sumR += r;
+ sumG += g;
+ sumB += b;
+ }
+ packedWords = new Uint32Array(floatBuffer);
+ } else if (format === TEXTURE_FORMAT_RG16_FLOAT) {
+ const halfData = data instanceof Uint16Array ? data : new Uint16Array(data);
+ const wordCount = Math.ceil(pixelCount / 1);
+ const alignedWords = Math.ceil(wordCount / 4) * 4;
+ packedWords = new Uint32Array(alignedWords);
+ for (let pixel = 0; pixel < pixelCount; pixel++) {
+ const lo = halfData[pixel * 2] ?? 0;
+ const hi = halfData[pixel * 2 + 1] ?? 0;
+ packedWords[pixel] = (lo | (hi << 16)) >>> 0;
+ }
+ sumR = pixelCount;
+ sumG = pixelCount;
+ sumB = pixelCount;
+ } else {
+ const alignedWords = Math.max(4, Math.ceil(pixelCount / 4) * 4);
+ packedWords = new Uint32Array(alignedWords);
+ const isSrgb = format === TEXTURE_FORMAT_RGBA8_SRGB;
+ for (let pixel = 0; pixel < pixelCount; pixel++) {
+ const rByte = data[pixel * 4] & 0xff;
+ const gByte = data[pixel * 4 + 1] & 0xff;
+ const bByte = data[pixel * 4 + 2] & 0xff;
+ const aByte = data[pixel * 4 + 3] & 0xff;
+ packedWords[pixel] = (rByte | (gByte << 8) | (bByte << 16) | (aByte << 24)) >>> 0;
+ sumR += isSrgb ? SRGB_BYTE_TO_LINEAR[rByte] : rByte / 255;
+ sumG += isSrgb ? SRGB_BYTE_TO_LINEAR[gByte] : gByte / 255;
+ sumB += isSrgb ? SRGB_BYTE_TO_LINEAR[bByte] : bByte / 255;
+ }
+ }
+
+ const descriptorBytes = new ArrayBuffer(STRUCT_STRIDES_V2.textureDescriptor);
+ const descriptorU32 = new Uint32Array(descriptorBytes);
+ const descriptorF32 = new Float32Array(descriptorBytes);
+ descriptorU32[0] = dataOffset >>> 0;
+ descriptorU32[1] = width >>> 0;
+ descriptorU32[2] = height >>> 0;
+ descriptorU32[3] = formatAndSampler;
+ descriptorF32[4] = Number(uvScale[0] ?? 1);
+ descriptorF32[5] = Number(uvScale[1] ?? 1);
+ descriptorF32[6] = Number(uvOffset[0] ?? 0);
+ descriptorF32[7] = Number(uvOffset[1] ?? 0);
+
+ const assignedIndex = descriptors.length;
+ descriptors.push(new Uint8Array(descriptorBytes));
+ wordChunks.push(packedWords);
+ totalWords += packedWords.length;
+
+ const record = {
+ index: assignedIndex,
+ meanLinearRgb: [sumR / pixelCount, sumG / pixelCount, sumB / pixelCount],
+ };
+ indexByKey.set(dedupeKey, record);
+ return record;
+ }
+
+ function addPackedRgba8Words(words, width, height, isSrgb, repeat) {
+ const pixelCount = width * height;
+ const alignedWords = Math.max(4, Math.ceil(pixelCount / 4) * 4);
+ const padded = new Uint32Array(alignedWords);
+ padded.set(words.subarray(0, pixelCount));
+ let sumR = 0;
+ let sumG = 0;
+ let sumB = 0;
+ for (let pixel = 0; pixel < pixelCount; pixel++) {
+ const word = padded[pixel];
+ const rByte = word & 0xff;
+ const gByte = (word >>> 8) & 0xff;
+ const bByte = (word >>> 16) & 0xff;
+ sumR += isSrgb ? SRGB_BYTE_TO_LINEAR[rByte] : rByte / 255;
+ sumG += isSrgb ? SRGB_BYTE_TO_LINEAR[gByte] : gByte / 255;
+ sumB += isSrgb ? SRGB_BYTE_TO_LINEAR[bByte] : bByte / 255;
+ }
+ const format = isSrgb ? TEXTURE_FORMAT_RGBA8_SRGB : TEXTURE_FORMAT_RGBA8_UNORM;
+ const wrap = repeat ? 0 : 1;
+ const formatAndSampler = (format | (1 << 8) | (wrap << 16) | (wrap << 18)) >>> 0;
+ const descriptorBytes = new ArrayBuffer(STRUCT_STRIDES_V2.textureDescriptor);
+ const descriptorU32 = new Uint32Array(descriptorBytes);
+ const descriptorF32 = new Float32Array(descriptorBytes);
+ descriptorU32[0] = totalWords >>> 0;
+ descriptorU32[1] = width >>> 0;
+ descriptorU32[2] = height >>> 0;
+ descriptorU32[3] = formatAndSampler;
+ descriptorF32[4] = 1;
+ descriptorF32[5] = 1;
+ descriptorF32[6] = 0;
+ descriptorF32[7] = 0;
+
+ const assignedIndex = descriptors.length;
+ descriptors.push(new Uint8Array(descriptorBytes));
+ wordChunks.push(padded);
+ totalWords += padded.length;
+ return {
+ index: assignedIndex,
+ meanLinearRgb: [sumR / pixelCount, sumG / pixelCount, sumB / pixelCount],
+ };
+ }
+
+ function finish() {
+ const textureCount = descriptors.length;
+ const descriptorBuffer = new Uint8Array(Math.max(1, textureCount) * STRUCT_STRIDES_V2.textureDescriptor);
+ for (let index = 0; index < textureCount; index++) {
+ descriptorBuffer.set(descriptors[index], index * STRUCT_STRIDES_V2.textureDescriptor);
+ }
+ const texelBuffer = new Uint32Array(Math.max(4, totalWords));
+ let cursor = 0;
+ for (const chunk of wordChunks) {
+ texelBuffer.set(chunk, cursor);
+ cursor += chunk.length;
+ }
+ return {
+ textureDescriptors: descriptorBuffer,
+ textureCount,
+ textureTexels: texelBuffer,
+ };
+ }
+
+ return { addTexture, addPackedRgba8Words, finish };
+}
+
+function resolveAlphaMode(material, alpha, alphaCutoff) {
+ if (typeof material.alphaMode === 'number') {
+ return material.alphaMode >>> 0;
+ }
+ if (material.alphaMode === 'mask') {
+ return ALPHA_MODE_MASK;
+ }
+ if (material.alphaMode === 'blend') {
+ return alphaCutoff > 0 ? ALPHA_MODE_MASK : ALPHA_MODE_BLEND;
+ }
+ if (alphaCutoff > 0) {
+ return ALPHA_MODE_MASK;
+ }
+ if (alpha < 1) {
+ return ALPHA_MODE_BLEND;
+ }
+ return ALPHA_MODE_OPAQUE;
+}
+
+function resolveEmissionFields(material) {
+ if (material.emissionStrength !== undefined) {
+ const strength = Math.max(0, Number(material.emissionStrength));
+ const color = material.emissionColor ?? material.emissiveColor ?? material.baseColor ?? material.color ?? [1, 1, 1];
+ return { emissionColor: [color[0], color[1], color[2]], emissionStrength: strength };
+ }
+ if (typeof material.emission === 'number') {
+ const strength = Math.max(0, material.emission);
+ const color = material.emissiveColor ?? material.emissionColor ?? material.baseColor ?? material.color ?? [1, 1, 1];
+ return { emissionColor: [color[0], color[1], color[2]], emissionStrength: strength };
+ }
+ if (Array.isArray(material.emission) || ArrayBuffer.isView(material.emission)) {
+ const r = Math.max(0, Number(material.emission[0] ?? 0));
+ const g = Math.max(0, Number(material.emission[1] ?? 0));
+ const b = Math.max(0, Number(material.emission[2] ?? 0));
+ const strength = Math.max(r, g, b);
+ if (strength > 0) {
+ return {
+ emissionColor: [r / strength, g / strength, b / strength],
+ emissionStrength: strength,
+ };
+ }
+ }
+ return { emissionColor: [0, 0, 0], emissionStrength: 0 };
+}
+
+function resolveSubsurfaceFields(material, baseColor) {
+ const block = material.subsurface;
+ const directWeight = Number(material.subsurfaceWeight ?? block?.weight ?? 0);
+ if (!(directWeight > 0)) {
+ return {
+ weight: 0,
+ radius: [0, 0, 0],
+ color: [baseColor[0], baseColor[1], baseColor[2]],
+ anisotropy: 0,
+ ior: Number(material.subsurfaceIor ?? 1.4),
+ };
+ }
+ const scale = Number(block?.scale ?? 1);
+ const rawRadius = material.subsurfaceRadius ?? block?.meanFreePath ?? (
+ block?.radius ? [block.radius[0] * scale, block.radius[1] * scale, block.radius[2] * scale] : [1, 0.2, 0.1]
+ );
+ const radius = [
+ Math.max(1e-6, Number(rawRadius[0] ?? 1e-6)),
+ Math.max(1e-6, Number(rawRadius[1] ?? 1e-6)),
+ Math.max(1e-6, Number(rawRadius[2] ?? 1e-6)),
+ ];
+ const rawColor = material.subsurfaceColor ?? block?.color ?? baseColor;
+ return {
+ weight: Math.min(1, Math.max(0, directWeight)),
+ radius,
+ color: [Number(rawColor[0]), Number(rawColor[1]), Number(rawColor[2])],
+ anisotropy: Math.max(-0.9, Math.min(0.9, Number(material.subsurfaceAnisotropy ?? block?.anisotropy ?? 0))),
+ ior: Number(material.subsurfaceIor ?? block?.ior ?? 1.4),
+ };
+}
+
+/**
+ * Packs one `MaterialRecord` (256 B) matching `FORMAT-v2.md` section 4 and `src/cycles/abi.wgsl`.
+ */
+export function packMaterialRecordV2(material = {}, textureCollector = null) {
+ const buffer = new ArrayBuffer(STRUCT_STRIDES_V2.material);
+ const f32 = new Float32Array(buffer);
+ const u32 = new Uint32Array(buffer);
+ const i32 = new Int32Array(buffer);
+
+ const baseColor = material.baseColor ?? material.color ?? [1, 1, 1];
+ const metallic = Math.min(1, Math.max(0, Number(material.metallic ?? 0)));
+ const roughness = Math.min(1, Math.max(0, Number(material.roughness ?? 0.5)));
+ const isLiquid = material.tag === 'liquid' && material.liquid;
+ const ior = Number(isLiquid ? (material.liquid.ior ?? material.ior ?? 1.33) : (material.ior ?? 1.5));
+ const specularIorLevel = material.specularIorLevel !== undefined
+ ? Number(material.specularIorLevel)
+ : 0.5 * Number(material.specular ?? 1);
+ const diffuseRoughness = Math.min(1, Math.max(0, Number(material.diffuseRoughness ?? 0)));
+
+ const hasExplicitF82 = Boolean(material.f82Tint || material.specularColor);
+ const f82Tint = material.f82Tint ?? material.specularColor ?? [1, 1, 1];
+ const anisotropy = Math.min(1, Math.max(0, Number(material.anisotropy ?? 0)));
+ const anisotropyRotation = Number(material.anisotropyRotation ?? 0);
+ const transmissionWeight = Math.min(
+ 1,
+ Math.max(0, Number(isLiquid ? 1 : (material.transmissionWeight ?? material.transmission ?? 0))),
+ );
+ const alpha = Math.min(1, Math.max(0, Number(material.alpha ?? material.opacity ?? 1)));
+ const rawCutoff = Number(
+ material.alphaCutoff !== undefined
+ ? material.alphaCutoff
+ : (material.alphaMode === 'mask' ? 0.5 : 0),
+ );
+ const alphaMode = resolveAlphaMode(material, alpha, rawCutoff);
+ const alphaCutoff = alphaMode === ALPHA_MODE_MASK ? (rawCutoff > 0 ? rawCutoff : 0.5) : 0;
+
+ const coatTint = material.coatTint ?? material.clearcoatTint ?? [1, 1, 1];
+ const coatWeight = Math.min(1, Math.max(0, Number(material.coatWeight ?? material.clearcoat ?? 0)));
+ const coatRoughness = Math.min(1, Math.max(0, Number(material.coatRoughness ?? material.clearcoatRoughness ?? 0)));
+ const coatIor = Number(material.coatIor ?? material.clearcoatIor ?? 1.5);
+
+ const iridescenceFactor = Number(material.iridescence ?? 1);
+ const thinFilmThickness = material.thinFilmThickness !== undefined
+ ? Math.max(0, Number(material.thinFilmThickness))
+ : (material.iridescenceThickness !== undefined && iridescenceFactor > 0
+ ? Math.max(0, Number(material.iridescenceThickness) * iridescenceFactor)
+ : 0);
+ const thinFilmIor = Number(material.thinFilmIor ?? material.iridescenceIor ?? 1.33);
+
+ const rawSheenColor = material.sheenTint ?? material.sheenColor ?? [1, 1, 1];
+ const sheenWeight = material.sheenWeight !== undefined
+ ? Math.min(1, Math.max(0, Number(material.sheenWeight)))
+ : (material.sheenColor ? 1 : 0);
+ const sheenRoughness = Math.min(1, Math.max(0, Number(material.sheenRoughness ?? 0.5)));
+
+ const rawAttenuationDistance = Number(material.absorptionDistance ?? material.attenuationDistance ?? 0);
+ const absorptionDistance = Number.isFinite(rawAttenuationDistance) && rawAttenuationDistance > 0
+ ? rawAttenuationDistance
+ : 0;
+ const absorptionColor = material.absorptionColor ?? material.attenuationColor ?? [1, 1, 1];
+
+ const { emissionColor, emissionStrength } = resolveEmissionFields(material);
+ const subsurface = resolveSubsurfaceFields(material, baseColor);
+ const normalScale = Array.isArray(material.normalScale) || ArrayBuffer.isView(material.normalScale)
+ ? 0.5 * (Math.abs(Number(material.normalScale[0] ?? 1)) + Math.abs(Number(material.normalScale[1] ?? 1)))
+ : Number(material.normalScale ?? 1);
+ const coatNormalScale = Number(material.coatNormalScale ?? 1);
+ const bumpDistance = Math.max(0, Number(material.bumpDistance ?? 0));
+
+ const collector = textureCollector;
+ const baseTex = collector
+ ? collector.addTexture(material.texture ?? material.map, true)
+ : { index: Number(material.baseColorTex ?? -1), meanLinearRgb: [1, 1, 1] };
+ const mrTex = collector
+ ? collector.addTexture(material.surfaceTexture ?? material.metallicRoughnessMap, false)
+ : { index: Number(material.metallicRoughnessTex ?? -1), meanLinearRgb: [1, 1, 1] };
+ const normalTex = collector
+ ? collector.addTexture(material.normalTexture ?? material.normalMap, false)
+ : { index: Number(material.normalTex ?? -1), meanLinearRgb: [1, 1, 1] };
+ const emissionTex = collector
+ ? collector.addTexture(material.emissiveTexture ?? (emissionStrength > 0 ? material.emissiveMap : null), true)
+ : { index: Number(material.emissionTex ?? -1), meanLinearRgb: [1, 1, 1] };
+ const transmissionTex = collector
+ ? collector.addTexture(material.transmissionTexture ?? material.transmissionMap, false)
+ : { index: Number(material.transmissionTex ?? -1), meanLinearRgb: [1, 1, 1] };
+ const coatTex = collector
+ ? collector.addTexture(material.clearcoatTexture ?? material.layerMaps?.clearcoatTexture, false)
+ : { index: Number(material.coatWeightRoughnessTex ?? -1), meanLinearRgb: [1, 1, 1] };
+ const coatTintTex = collector
+ ? collector.addTexture(material.coatTintTexture ?? material.coatTintMap, true)
+ : { index: Number(material.coatTintTex ?? -1), meanLinearRgb: [1, 1, 1] };
+ const coatNormalTex = collector
+ ? collector.addTexture(material.coatNormalTexture ?? material.coatNormalMap, false)
+ : { index: Number(material.coatNormalTex ?? -1), meanLinearRgb: [1, 1, 1] };
+ const sheenTex = collector
+ ? collector.addTexture(material.sheenTexture ?? material.sheenMap, true)
+ : { index: Number(material.sheenColorRoughnessTex ?? -1), meanLinearRgb: [1, 1, 1] };
+ const anisotropyTex = collector
+ ? collector.addTexture(material.anisotropyTexture ?? material.anisotropyMap, false)
+ : { index: Number(material.anisotropyTex ?? -1), meanLinearRgb: [1, 1, 1] };
+ const explicitAlphaTex = collector
+ ? collector.addTexture(material.alphaTexture ?? material.alphaMap, false)
+ : { index: Number(material.alphaTex ?? -1), meanLinearRgb: [1, 1, 1] };
+ const bumpTex = collector
+ ? collector.addTexture(material.bumpTexture ?? material.bumpMap, false)
+ : { index: Number(material.bumpTex ?? -1), meanLinearRgb: [1, 1, 1] };
+
+ const alphaTexIndex = explicitAlphaTex.index >= 0
+ ? explicitAlphaTex.index
+ : (alphaMode !== ALPHA_MODE_OPAQUE ? baseTex.index : -1);
+
+ let flags = 0;
+ if (material.multiscatterGgx !== false) {
+ flags |= MATERIAL_FLAG_MULTISCATTER_GGX;
+ }
+ if (material.thinWalled) {
+ flags |= MATERIAL_FLAG_THIN_WALLED;
+ }
+ if (material.transparentShadow !== false) {
+ flags |= MATERIAL_FLAG_TRANSPARENT_SHADOW;
+ }
+ if (material.doubleSided !== false) {
+ flags |= MATERIAL_FLAG_DOUBLE_SIDED;
+ }
+ if (emissionStrength > 0 && luminance(emissionColor) > 0 && material.emissiveMis !== false) {
+ flags |= MATERIAL_FLAG_EMISSIVE_MIS;
+ }
+ if ((hasExplicitF82 && metallic > 0) || material.f82Metallic) {
+ flags |= MATERIAL_FLAG_F82_METALLIC;
+ }
+ if (typeof material.flags === 'number') {
+ flags = material.flags >>> 0;
+ }
+
+ f32[0] = Number(baseColor[0]);
+ f32[1] = Number(baseColor[1]);
+ f32[2] = Number(baseColor[2]);
+ f32[3] = metallic;
+
+ f32[4] = roughness;
+ f32[5] = ior;
+ f32[6] = specularIorLevel;
+ f32[7] = diffuseRoughness;
+
+ f32[8] = Number(f82Tint[0]);
+ f32[9] = Number(f82Tint[1]);
+ f32[10] = Number(f82Tint[2]);
+ f32[11] = anisotropy;
+
+ f32[12] = anisotropyRotation;
+ f32[13] = transmissionWeight;
+ f32[14] = alpha;
+ f32[15] = alphaCutoff;
+
+ f32[16] = Number(coatTint[0]);
+ f32[17] = Number(coatTint[1]);
+ f32[18] = Number(coatTint[2]);
+ f32[19] = coatWeight;
+
+ f32[20] = coatRoughness;
+ f32[21] = coatIor;
+ f32[22] = thinFilmThickness;
+ f32[23] = thinFilmIor;
+
+ f32[24] = Number(rawSheenColor[0]);
+ f32[25] = Number(rawSheenColor[1]);
+ f32[26] = Number(rawSheenColor[2]);
+ f32[27] = sheenWeight;
+
+ f32[28] = Number(absorptionColor[0]);
+ f32[29] = Number(absorptionColor[1]);
+ f32[30] = Number(absorptionColor[2]);
+ f32[31] = absorptionDistance;
+
+ f32[32] = Number(emissionColor[0]);
+ f32[33] = Number(emissionColor[1]);
+ f32[34] = Number(emissionColor[2]);
+ f32[35] = emissionStrength;
+
+ f32[36] = subsurface.radius[0];
+ f32[37] = subsurface.radius[1];
+ f32[38] = subsurface.radius[2];
+ f32[39] = subsurface.weight;
+
+ f32[40] = subsurface.color[0];
+ f32[41] = subsurface.color[1];
+ f32[42] = subsurface.color[2];
+ f32[43] = subsurface.anisotropy;
+
+ f32[44] = sheenRoughness;
+ f32[45] = subsurface.ior;
+ f32[46] = normalScale;
+ f32[47] = coatNormalScale;
+
+ u32[48] = flags >>> 0;
+ u32[49] = alphaMode >>> 0;
+ f32[50] = bumpDistance;
+ u32[51] = INVALID_INDEX_V2;
+
+ i32[52] = baseTex.index;
+ i32[53] = mrTex.index;
+ i32[54] = normalTex.index;
+ i32[55] = emissionTex.index;
+ i32[56] = transmissionTex.index;
+ i32[57] = coatTex.index;
+ i32[58] = coatTintTex.index;
+ i32[59] = coatNormalTex.index;
+ i32[60] = sheenTex.index;
+ i32[61] = anisotropyTex.index;
+ i32[62] = alphaTexIndex;
+ i32[63] = bumpTex.index;
+
+ const meanEmissiveRadiance = [
+ emissionColor[0] * emissionStrength * emissionTex.meanLinearRgb[0],
+ emissionColor[1] * emissionStrength * emissionTex.meanLinearRgb[1],
+ emissionColor[2] * emissionStrength * emissionTex.meanLinearRgb[2],
+ ];
+
+ return {
+ bytes: new Uint8Array(buffer),
+ alphaMode,
+ usesSubsurface: subsurface.weight > 0,
+ isEmissive: (flags & MATERIAL_FLAG_EMISSIVE_MIS) !== 0 && luminance(meanEmissiveRadiance) > 0,
+ meanEmissiveRadiance,
+ };
+}
+
+function computeTriangleTangents(edge1, edge2, n0, n1, n2, uv0, uv1, uv2) {
+ const du1 = uv1[0] - uv0[0];
+ const dv1 = uv1[1] - uv0[1];
+ const du2 = uv2[0] - uv0[0];
+ const dv2 = uv2[1] - uv0[1];
+ const det = du1 * dv2 - du2 * dv1;
+ if (Math.abs(det) < 1e-12) {
+ const t0 = orthonormalBasis(n0).axisU;
+ const t1 = orthonormalBasis(n1).axisU;
+ const t2 = orthonormalBasis(n2).axisU;
+ return { t0, t1, t2, sign: 1.0, hasUvTangents: false };
+ }
+ const invDet = 1 / det;
+ const rawTangent = [
+ (edge1[0] * dv2 - edge2[0] * dv1) * invDet,
+ (edge1[1] * dv2 - edge2[1] * dv1) * invDet,
+ (edge1[2] * dv2 - edge2[2] * dv1) * invDet,
+ ];
+ const rawBitangent = [
+ (edge2[0] * du1 - edge1[0] * du2) * invDet,
+ (edge2[1] * du1 - edge1[1] * du2) * invDet,
+ (edge2[2] * du1 - edge1[2] * du2) * invDet,
+ ];
+
+ function projectTangent(normal) {
+ const proj = dotVec3(rawTangent, normal);
+ const ortho = [
+ rawTangent[0] - normal[0] * proj,
+ rawTangent[1] - normal[1] * proj,
+ rawTangent[2] - normal[2] * proj,
+ ];
+ const len = Math.hypot(ortho[0], ortho[1], ortho[2]);
+ if (!(len > 1e-12)) {
+ return orthonormalBasis(normal).axisU;
+ }
+ return [ortho[0] / len, ortho[1] / len, ortho[2] / len];
+ }
+
+ const t0 = projectTangent(n0);
+ const t1 = projectTangent(n1);
+ const t2 = projectTangent(n2);
+ const sign = dotVec3(crossVec3(n0, t0), rawBitangent) < 0 ? -1.0 : 1.0;
+ return { t0, t1, t2, sign, hasUvTangents: true };
+}
+
+function writeTriangleRecordBytes(targetBytes, byteOffset, tri) {
+ const viewBuffer = targetBytes.buffer;
+ const baseByte = targetBytes.byteOffset + byteOffset;
+ const f32 = new Float32Array(viewBuffer, baseByte, 56);
+ const u32 = new Uint32Array(viewBuffer, baseByte, 56);
+
+ f32[0] = tri.p0[0];
+ f32[1] = tri.p0[1];
+ f32[2] = tri.p0[2];
+ u32[3] = tri.materialIndex >>> 0;
+
+ f32[4] = tri.edge1[0];
+ f32[5] = tri.edge1[1];
+ f32[6] = tri.edge1[2];
+ u32[7] = tri.localEmissiveOffset >>> 0;
+
+ f32[8] = tri.edge2[0];
+ f32[9] = tri.edge2[1];
+ f32[10] = tri.edge2[2];
+ u32[11] = tri.flags >>> 0;
+
+ f32[12] = tri.n0[0];
+ f32[13] = tri.n0[1];
+ f32[14] = tri.n0[2];
+ f32[15] = tri.uv0[0];
+
+ f32[16] = tri.n1[0];
+ f32[17] = tri.n1[1];
+ f32[18] = tri.n1[2];
+ f32[19] = tri.uv0[1];
+
+ f32[20] = tri.n2[0];
+ f32[21] = tri.n2[1];
+ f32[22] = tri.n2[2];
+ f32[23] = tri.uv1[0];
+
+ f32[24] = tri.t0[0];
+ f32[25] = tri.t0[1];
+ f32[26] = tri.t0[2];
+ f32[27] = tri.uv1[1];
+
+ f32[28] = tri.t1[0];
+ f32[29] = tri.t1[1];
+ f32[30] = tri.t1[2];
+ f32[31] = tri.uv2[0];
+
+ f32[32] = tri.t2[0];
+ f32[33] = tri.t2[1];
+ f32[34] = tri.t2[2];
+ f32[35] = tri.uv2[1];
+
+ f32[36] = tri.c0[0];
+ f32[37] = tri.c0[1];
+ f32[38] = tri.c0[2];
+ f32[39] = tri.tangentSign;
+
+ f32[40] = tri.c1[0];
+ f32[41] = tri.c1[1];
+ f32[42] = tri.c1[2];
+ u32[43] = tri.meshId >>> 0;
+
+ f32[44] = tri.c2[0];
+ f32[45] = tri.c2[1];
+ f32[46] = tri.c2[2];
+ u32[47] = tri.primitiveId >>> 0;
+
+ f32[48] = tri.uvSet1_0[0];
+ f32[49] = tri.uvSet1_0[1];
+ f32[50] = tri.uvSet1_1[0];
+ f32[51] = tri.uvSet1_1[1];
+ f32[52] = tri.uvSet1_2[0];
+ f32[53] = tri.uvSet1_2[1];
+ u32[54] = INVALID_INDEX_V2;
+ u32[55] = 0;
+}
+
+function writeInstanceRecordBytes(targetBytes, byteOffset, inst) {
+ const baseByte = targetBytes.byteOffset + byteOffset;
+ const f32 = new Float32Array(targetBytes.buffer, baseByte, 40);
+ const u32 = new Uint32Array(targetBytes.buffer, baseByte, 40);
+
+ for (let index = 0; index < 12; index++) {
+ f32[index] = inst.objectToWorld[index];
+ f32[12 + index] = inst.worldToObject[index];
+ }
+ u32[24] = inst.blasIndex >>> 0;
+ u32[25] = inst.triangleOffset >>> 0;
+ u32[26] = inst.opaqueTriangleCount >>> 0;
+ u32[27] = inst.totalTriangleCount >>> 0;
+ u32[28] = inst.materialOverride >>> 0;
+ u32[29] = inst.visibilityFlags >>> 0;
+ u32[30] = inst.lightGroupMaskLo >>> 0;
+ u32[31] = inst.lightGroupMaskHi >>> 0;
+ u32[32] = inst.emissiveBaseOffset >>> 0;
+ u32[33] = inst.objectId >>> 0;
+ f32[34] = inst.objectRandom;
+ f32[35] = inst.shadowTerminatorOffset ?? 0;
+ f32[36] = inst.objectColor[0];
+ f32[37] = inst.objectColor[1];
+ f32[38] = inst.objectColor[2];
+ f32[39] = inst.objectColor[3];
+}
+
+function packEmissiveTriangleBuffer(emissiveList) {
+ const count = emissiveList.length;
+ const buffer = new Uint8Array(Math.max(1, count) * STRUCT_STRIDES_V2.emissiveTriangle);
+ if (count === 0) {
+ return { emissiveTriangles: buffer, emissiveTriangleCount: 0, emissiveTotalWeight: 0, boundsMin: null, boundsMax: null, maskOr: 0 };
+ }
+ let totalWeight = 0;
+ for (const item of emissiveList) {
+ totalWeight += item.selectionWeight;
+ }
+ if (!(totalWeight > 0)) {
+ totalWeight = count;
+ }
+ const boundsMin = [Infinity, Infinity, Infinity];
+ const boundsMax = [-Infinity, -Infinity, -Infinity];
+ let maskOr = 0;
+ let cumulative = 0;
+
+ for (let index = 0; index < count; index++) {
+ const item = emissiveList[index];
+ const pdf = item.selectionWeight > 0 ? item.selectionWeight / totalWeight : 1 / count;
+ cumulative += pdf;
+ const cdfUpper = index === count - 1 ? 1.0 : Math.min(1.0, cumulative);
+
+ const baseByte = index * STRUCT_STRIDES_V2.emissiveTriangle;
+ const f32 = new Float32Array(buffer.buffer, baseByte, 24);
+ const u32 = new Uint32Array(buffer.buffer, baseByte, 24);
+
+ f32[0] = item.p0[0];
+ f32[1] = item.p0[1];
+ f32[2] = item.p0[2];
+ f32[3] = item.area;
+
+ f32[4] = item.edge1[0];
+ f32[5] = item.edge1[1];
+ f32[6] = item.edge1[2];
+ u32[7] = item.instanceIndex >>> 0;
+
+ f32[8] = item.edge2[0];
+ f32[9] = item.edge2[1];
+ f32[10] = item.edge2[2];
+ u32[11] = item.triangleIndex >>> 0;
+
+ f32[12] = item.geometricNormal[0];
+ f32[13] = item.geometricNormal[1];
+ f32[14] = item.geometricNormal[2];
+ u32[15] = item.materialIndex >>> 0;
+
+ f32[16] = item.radiance[0];
+ f32[17] = item.radiance[1];
+ f32[18] = item.radiance[2];
+ f32[19] = item.selectionWeight;
+
+ f32[20] = pdf;
+ f32[21] = cdfUpper;
+ u32[22] = item.lightGroupMaskLo >>> 0;
+ u32[23] = item.lightGroupMaskHi >>> 0;
+
+ maskOr = (maskOr | item.lightGroupMaskLo) >>> 0;
+ const p1 = [item.p0[0] + item.edge1[0], item.p0[1] + item.edge1[1], item.p0[2] + item.edge1[2]];
+ const p2 = [item.p0[0] + item.edge2[0], item.p0[1] + item.edge2[1], item.p0[2] + item.edge2[2]];
+ for (let axis = 0; axis < 3; axis++) {
+ boundsMin[axis] = Math.min(boundsMin[axis], item.p0[axis], p1[axis], p2[axis]);
+ boundsMax[axis] = Math.max(boundsMax[axis], item.p0[axis], p1[axis], p2[axis]);
+ }
+ }
+
+ return {
+ emissiveTriangles: buffer,
+ emissiveTriangleCount: count,
+ emissiveTotalWeight: totalWeight,
+ boundsMin,
+ boundsMax,
+ maskOr,
+ };
+}
+
+function buildAnalyticLightEntries(lightsSection = {}) {
+ const records = [];
+
+ if (lightsSection.sun) {
+ const sun = lightsSection.sun;
+ const sunColor = sun.color ?? [0, 0, 0];
+ const maxChannel = Math.max(sunColor[0], sunColor[1], sunColor[2]);
+ if (maxChannel > 0) {
+ const towardSun = normalizeVec3(sun.direction, [0, 1, 0]);
+ const emissionDirection = [-towardSun[0], -towardSun[1], -towardSun[2]];
+ const { axisU, axisV } = orthonormalBasis(emissionDirection);
+ const halfAngle = Math.max(0, Number(sun.angularRadius ?? SUN_DEFAULT_HALF_ANGLE));
+ const cosHalfAngle = Math.cos(halfAngle);
+ const sinHalfAngle = Math.sin(halfAngle);
+ const discFactor = sinHalfAngle > 1e-7 ? Math.PI * sinHalfAngle * sinHalfAngle : 1;
+ const solidAngle = halfAngle > 0 ? 2 * Math.PI * (1 - cosHalfAngle) : 0;
+ const radiance = [
+ sunColor[0] / discFactor,
+ sunColor[1] / discFactor,
+ sunColor[2] / discFactor,
+ ];
+ let flags = LIGHT_FLAG_NORMALIZE;
+ if (sun.cyclesCastShadow !== false) {
+ flags |= LIGHT_FLAG_CAST_SHADOW;
+ }
+ if (halfAngle > 0 && sun.multipleImportance !== false) {
+ flags |= LIGHT_FLAG_MULTIPLE_IMPORTANCE;
+ }
+ if (sun.cameraVisible === true) {
+ flags |= LIGHT_FLAG_CAMERA_VISIBLE;
+ }
+ const masks = lightBitMaskWords(sun.bit, sun.lightGroupMaskLo, sun.lightGroupMaskHi);
+ const weight = Math.max(1e-6, Math.PI * luminance(sunColor));
+ records.push({
+ position: [0, 0, 0],
+ lightType: LIGHT_TYPE_SUN,
+ radiance,
+ flags,
+ direction: emissionDirection,
+ radius: 0,
+ axisU,
+ sizeU: 0,
+ axisV,
+ sizeV: 0,
+ cosHalfAngle,
+ spotBlend: 0,
+ tanHalfSpread: 0,
+ spreadNormalization: 0,
+ areaOrSolidAngle: solidAngle,
+ maxDistance: 1e30,
+ masks,
+ weight,
+ isDistant: true,
+ });
+ }
+ }
+
+ for (const point of lightsSection.points ?? []) {
+ const intensity = Math.max(0, Number(point.intensity ?? 0));
+ const color = point.color ?? [1, 1, 1];
+ if (!(intensity > 0) || !(luminance(color) > 0)) {
+ continue;
+ }
+ const radius = Math.max(0, Number(point.radius ?? 0));
+ const radianceScale = radius > 0 ? intensity / (Math.PI * radius * radius) : intensity;
+ const radiance = [color[0] * radianceScale, color[1] * radianceScale, color[2] * radianceScale];
+ let flags = LIGHT_FLAG_NORMALIZE;
+ if (point.cyclesCastShadow !== false) {
+ flags |= LIGHT_FLAG_CAST_SHADOW;
+ }
+ if (radius > 0 && point.multipleImportance !== false) {
+ flags |= LIGHT_FLAG_MULTIPLE_IMPORTANCE;
+ }
+ if (point.cameraVisible === true) {
+ flags |= LIGHT_FLAG_CAMERA_VISIBLE;
+ }
+ const masks = lightBitMaskWords(point.bit, point.lightGroupMaskLo, point.lightGroupMaskHi);
+ const maxDistance = point.range > 0 ? Number(point.range) : 1e30;
+ const weight = Math.max(1e-6, 4 * Math.PI * luminance(color) * intensity);
+ records.push({
+ position: [Number(point.position[0]), Number(point.position[1]), Number(point.position[2])],
+ lightType: LIGHT_TYPE_POINT,
+ radiance,
+ flags,
+ direction: [0, -1, 0],
+ radius,
+ axisU: [1, 0, 0],
+ sizeU: 0,
+ axisV: [0, 0, 1],
+ sizeV: 0,
+ cosHalfAngle: -1,
+ spotBlend: 0,
+ tanHalfSpread: 0,
+ spreadNormalization: 0,
+ areaOrSolidAngle: radius > 0 ? 4 * Math.PI * radius * radius : 0,
+ maxDistance,
+ masks,
+ weight,
+ isDistant: false,
+ });
+ }
+
+ for (const spot of lightsSection.spots ?? []) {
+ const intensity = Math.max(0, Number(spot.intensity ?? 0));
+ const color = spot.color ?? [1, 1, 1];
+ if (!(intensity > 0) || !(luminance(color) > 0)) {
+ continue;
+ }
+ const radius = Math.max(0, Number(spot.radius ?? 0));
+ const radianceScale = radius > 0 ? intensity / (Math.PI * radius * radius) : intensity;
+ const radiance = [color[0] * radianceScale, color[1] * radianceScale, color[2] * radianceScale];
+ const direction = normalizeVec3(spot.direction, [0, -1, 0]);
+ const { axisU, axisV } = orthonormalBasis(direction);
+ const cosHalfAngle = spot.cosineHalfAngle !== undefined
+ ? Number(spot.cosineHalfAngle)
+ : Math.cos(Number(spot.angle ?? Math.PI / 4));
+ let spotBlend = 0;
+ if (spot.spotBlend !== undefined) {
+ spotBlend = Number(spot.spotBlend);
+ } else if (spot.penumbra !== undefined) {
+ spotBlend = Number(spot.penumbra);
+ } else if (spot.blend !== undefined) {
+ const denom = 1 - cosHalfAngle;
+ spotBlend = denom > 1e-8 ? Number(spot.blend) / denom : 0;
+ }
+ spotBlend = Math.min(1, Math.max(0, spotBlend));
+
+ let flags = LIGHT_FLAG_NORMALIZE;
+ if (spot.cyclesCastShadow !== false) {
+ flags |= LIGHT_FLAG_CAST_SHADOW;
+ }
+ if (radius > 0 && spot.multipleImportance !== false) {
+ flags |= LIGHT_FLAG_MULTIPLE_IMPORTANCE;
+ }
+ if (spot.cameraVisible === true) {
+ flags |= LIGHT_FLAG_CAMERA_VISIBLE;
+ }
+ const masks = lightBitMaskWords(spot.bit, spot.lightGroupMaskLo, spot.lightGroupMaskHi);
+ const maxDistance = spot.range > 0 ? Number(spot.range) : 1e30;
+ const coneSolidAngle = Math.max(1e-4, 2 * Math.PI * Math.max(0, 1 - cosHalfAngle));
+ const weight = Math.max(1e-6, coneSolidAngle * luminance(color) * intensity);
+ records.push({
+ position: [Number(spot.position[0]), Number(spot.position[1]), Number(spot.position[2])],
+ lightType: LIGHT_TYPE_SPOT,
+ radiance,
+ flags,
+ direction,
+ radius,
+ axisU,
+ sizeU: 0,
+ axisV,
+ sizeV: 0,
+ cosHalfAngle,
+ spotBlend,
+ tanHalfSpread: 0,
+ spreadNormalization: 0,
+ areaOrSolidAngle: radius > 0 ? 4 * Math.PI * radius * radius : 0,
+ maxDistance,
+ masks,
+ weight,
+ isDistant: false,
+ });
+ }
+
+ for (const area of lightsSection.areas ?? []) {
+ const intensity = Math.max(0, Number(area.intensity ?? 0));
+ const color = area.color ?? [1, 1, 1];
+ const width = Math.max(1e-6, Number(area.width ?? area.sizeU ?? 1));
+ const height = Math.max(1e-6, Number(area.height ?? area.sizeV ?? width));
+ if (!(intensity > 0) || !(luminance(color) > 0)) {
+ continue;
+ }
+ const isDisk = area.shape === 'disk' || area.shape === 'ellipse' || area.lightType === LIGHT_TYPE_AREA_DISK;
+ const surfaceArea = isDisk ? Math.PI * 0.25 * width * height : width * height;
+ const radianceScale = intensity / surfaceArea;
+ const radiance = [color[0] * radianceScale, color[1] * radianceScale, color[2] * radianceScale];
+ const direction = normalizeVec3(area.normal ?? area.direction, [0, -1, 0]);
+ let axisU;
+ let axisV;
+ if (area.across && area.along) {
+ axisU = normalizeVec3(area.across, [1, 0, 0]);
+ axisV = normalizeVec3(area.along, [0, 0, 1]);
+ } else {
+ const guide = normalizeVec3(area.up ?? [0, 1, 0], [0, 1, 0]);
+ axisU = normalizeVec3(crossVec3(guide, direction), [1, 0, 0]);
+ axisV = normalizeVec3(crossVec3(direction, axisU), [0, 0, 1]);
+ }
+
+ const spread = area.spread === undefined ? Math.PI : Math.max(1e-4, Math.min(Math.PI, Number(area.spread)));
+ let tanHalfSpread = 0;
+ let spreadNormalization = 0;
+ if (spread < Math.PI - 1e-5) {
+ const halfSpread = 0.5 * spread;
+ tanHalfSpread = Math.tan(halfSpread);
+ spreadNormalization = 1 / Math.max(1e-8, tanHalfSpread - halfSpread);
+ }
+
+ let flags = LIGHT_FLAG_NORMALIZE;
+ if (area.cyclesCastShadow !== false) {
+ flags |= LIGHT_FLAG_CAST_SHADOW;
+ }
+ if (spread > 0 && area.multipleImportance !== false) {
+ flags |= LIGHT_FLAG_MULTIPLE_IMPORTANCE;
+ }
+ if (area.cameraVisible === true) {
+ flags |= LIGHT_FLAG_CAMERA_VISIBLE;
+ }
+ if (area.portal === true) {
+ flags |= LIGHT_FLAG_PORTAL;
+ }
+ const masks = lightBitMaskWords(area.bit, area.lightGroupMaskLo, area.lightGroupMaskHi);
+ const weight = Math.max(1e-6, Math.PI * luminance(color) * intensity);
+ records.push({
+ position: [Number(area.position[0]), Number(area.position[1]), Number(area.position[2])],
+ lightType: isDisk ? LIGHT_TYPE_AREA_DISK : LIGHT_TYPE_AREA_RECT,
+ radiance,
+ flags,
+ direction,
+ radius: 0,
+ axisU,
+ sizeU: width,
+ axisV,
+ sizeV: height,
+ cosHalfAngle: 0,
+ spotBlend: 0,
+ tanHalfSpread,
+ spreadNormalization,
+ areaOrSolidAngle: surfaceArea,
+ maxDistance: area.range > 0 ? Number(area.range) : 1e30,
+ masks,
+ weight,
+ isDistant: false,
+ });
+ }
+
+ return records;
+}
+
+function packAnalyticLightsBuffer(entries) {
+ const count = entries.length;
+ const buffer = new Uint8Array(Math.max(1, count) * STRUCT_STRIDES_V2.light);
+ if (count === 0) {
+ return { lights: buffer, lightCount: 0, analyticLightTotalWeight: 0, boundsMin: null, boundsMax: null, maskOr: 0, hasDistant: false };
+ }
+ let totalWeight = 0;
+ for (const entry of entries) {
+ totalWeight += entry.weight;
+ }
+ const boundsMin = [Infinity, Infinity, Infinity];
+ const boundsMax = [-Infinity, -Infinity, -Infinity];
+ let maskOr = 0;
+ let hasDistant = false;
+ let cumulative = 0;
+
+ for (let index = 0; index < count; index++) {
+ const entry = entries[index];
+ const pdf = entry.weight / totalWeight;
+ cumulative += pdf;
+ const cdfUpper = index === count - 1 ? 1.0 : Math.min(1.0, cumulative);
+
+ const baseByte = index * STRUCT_STRIDES_V2.light;
+ const f32 = new Float32Array(buffer.buffer, baseByte, 32);
+ const u32 = new Uint32Array(buffer.buffer, baseByte, 32);
+ const i32 = new Int32Array(buffer.buffer, baseByte, 32);
+
+ f32[0] = entry.position[0];
+ f32[1] = entry.position[1];
+ f32[2] = entry.position[2];
+ u32[3] = entry.lightType >>> 0;
+
+ f32[4] = entry.radiance[0];
+ f32[5] = entry.radiance[1];
+ f32[6] = entry.radiance[2];
+ u32[7] = entry.flags >>> 0;
+
+ f32[8] = entry.direction[0];
+ f32[9] = entry.direction[1];
+ f32[10] = entry.direction[2];
+ f32[11] = entry.radius;
+
+ f32[12] = entry.axisU[0];
+ f32[13] = entry.axisU[1];
+ f32[14] = entry.axisU[2];
+ f32[15] = entry.sizeU;
+
+ f32[16] = entry.axisV[0];
+ f32[17] = entry.axisV[1];
+ f32[18] = entry.axisV[2];
+ f32[19] = entry.sizeV;
+
+ f32[20] = entry.cosHalfAngle;
+ f32[21] = entry.spotBlend;
+ f32[22] = entry.tanHalfSpread;
+ f32[23] = entry.spreadNormalization;
+
+ f32[24] = entry.areaOrSolidAngle;
+ f32[25] = entry.maxDistance;
+ i32[26] = -1;
+ u32[27] = 0;
+
+ f32[28] = pdf;
+ f32[29] = cdfUpper;
+ u32[30] = entry.masks.lo >>> 0;
+ u32[31] = entry.masks.hi >>> 0;
+
+ maskOr = (maskOr | entry.masks.lo) >>> 0;
+ if (entry.isDistant) {
+ hasDistant = true;
+ } else {
+ const extent = Math.max(entry.radius, 0.5 * Math.hypot(entry.sizeU, entry.sizeV));
+ for (let axis = 0; axis < 3; axis++) {
+ boundsMin[axis] = Math.min(boundsMin[axis], entry.position[axis] - extent);
+ boundsMax[axis] = Math.max(boundsMax[axis], entry.position[axis] + extent);
+ }
+ }
+ }
+
+ return {
+ lights: buffer,
+ lightCount: count,
+ analyticLightTotalWeight: totalWeight,
+ boundsMin: boundsMin[0] <= boundsMax[0] ? boundsMin : null,
+ boundsMax: boundsMin[0] <= boundsMax[0] ? boundsMax : null,
+ maskOr,
+ hasDistant,
+ };
+}
+
+function packRootLightTreeNode(packedLights, packedEmissives) {
+ const totalEmitters = packedLights.lightCount + packedEmissives.emissiveTriangleCount;
+ const buffer = new Uint8Array(STRUCT_STRIDES_V2.lightTreeNode);
+ if (totalEmitters === 0) {
+ return { lightTreeNodes: buffer, lightTreeNodeCount: 0 };
+ }
+ const f32 = new Float32Array(buffer.buffer, 0, 16);
+ const u32 = new Uint32Array(buffer.buffer, 0, 16);
+ const i32 = new Int32Array(buffer.buffer, 0, 16);
+
+ const boundsMin = [Infinity, Infinity, Infinity];
+ const boundsMax = [-Infinity, -Infinity, -Infinity];
+ for (const candidate of [packedLights, packedEmissives]) {
+ if (!candidate.boundsMin) continue;
+ for (let axis = 0; axis < 3; axis++) {
+ boundsMin[axis] = Math.min(boundsMin[axis], candidate.boundsMin[axis]);
+ boundsMax[axis] = Math.max(boundsMax[axis], candidate.boundsMax[axis]);
+ }
+ }
+ if (!(boundsMin[0] <= boundsMax[0])) {
+ boundsMin.fill(-1);
+ boundsMax.fill(1);
+ }
+
+ const leafCount = Math.min(0xffff, totalEmitters);
+ const kindBit = packedLights.lightCount === 0 && packedEmissives.emissiveTriangleCount > 0 ? (1 << 16) : 0;
+ const distantBit = packedLights.hasDistant ? (1 << 17) : 0;
+
+ f32[0] = boundsMin[0];
+ f32[1] = boundsMin[1];
+ f32[2] = boundsMin[2];
+ f32[3] = packedLights.analyticLightTotalWeight + packedEmissives.emissiveTotalWeight;
+
+ f32[4] = boundsMax[0];
+ f32[5] = boundsMax[1];
+ f32[6] = boundsMax[2];
+ f32[7] = Math.PI;
+
+ f32[8] = 0;
+ f32[9] = 1;
+ f32[10] = 0;
+ f32[11] = Math.PI;
+
+ i32[12] = -1;
+ u32[13] = 0;
+ u32[14] = (leafCount | kindBit | distantBit) >>> 0;
+ u32[15] = (packedLights.maskOr | packedEmissives.maskOr) >>> 0;
+
+ return { lightTreeNodes: buffer, lightTreeNodeCount: 1 };
+}
+
+function packEnvironmentTexelsV2(environment, options = {}) {
+ if (!environment || !(environment.width > 0 && environment.height > 0)) {
+ const bg = options.backgroundColor ?? [0, 0, 0];
+ return {
+ environmentTexels: new Float32Array(4),
+ envWidth: 0,
+ envHeight: 0,
+ envCdfOffset: 0,
+ envRotation: 0,
+ envColor: [Number(bg[0]), Number(bg[1]), Number(bg[2])],
+ envTotalWeight: 0,
+ };
+ }
+
+ const width = Math.round(environment.width);
+ const height = Math.round(environment.height);
+ const channels = Math.max(3, Math.round(environment.channels ?? 3));
+ const source = environment.data;
+ const intensity = Number(environment.intensity ?? 1);
+ const radianceLimit = options.hdriRadianceLimit === undefined
+ ? DEFAULT_HDRI_RADIANCE_LIMIT
+ : Number(options.hdriRadianceLimit);
+ const envRotation = environment.rotation !== undefined
+ ? Number(environment.rotation)
+ : Math.atan2(Number(environment.sine ?? 0), Number(environment.cosine ?? 1));
+
+ const pixelCount = width * height;
+ const totalVec4 = 2 * pixelCount + height;
+ const texels = new Float32Array(totalVec4 * 4);
+ const rowTotals = new Float64Array(height);
+ const pixelWeights = new Float64Array(pixelCount);
+ const deltaPhi = (2 * Math.PI) / width;
+ const deltaTheta = Math.PI / height;
+ let totalWeight = 0;
+
+ for (let y = 0; y < height; y++) {
+ const sinTheta = Math.sin(Math.PI * (y + 0.5) / height);
+ let rowSum = 0;
+ for (let x = 0; x < width; x++) {
+ const pixelIndex = y * width + x;
+ const srcBase = pixelIndex * channels;
+ const r = Math.min(radianceLimit, Math.max(0, Number(source[srcBase])));
+ const g = Math.min(radianceLimit, Math.max(0, Number(source[srcBase + 1])));
+ const b = Math.min(radianceLimit, Math.max(0, Number(source[srcBase + 2])));
+ const dstBase = pixelIndex * 4;
+ texels[dstBase] = r;
+ texels[dstBase + 1] = g;
+ texels[dstBase + 2] = b;
+ texels[dstBase + 3] = 1.0;
+
+ const weight = (0.2126 * r + 0.7152 * g + 0.0722 * b) * intensity * sinTheta * deltaPhi * deltaTheta;
+ pixelWeights[pixelIndex] = weight;
+ rowSum += weight;
+ }
+ rowTotals[y] = rowSum;
+ totalWeight += rowSum;
+ }
+
+ const envCdfOffset = pixelCount;
+ let marginalRunning = 0;
+ for (let y = 0; y < height; y++) {
+ const marginalProb = totalWeight > 0 ? rowTotals[y] / totalWeight : 1 / height;
+ marginalRunning += marginalProb;
+ const marginalBase = (envCdfOffset + y) * 4;
+ texels[marginalBase] = y === height - 1 ? 1.0 : Math.min(1.0, marginalRunning);
+ texels[marginalBase + 1] = marginalProb;
+ texels[marginalBase + 2] = 0.0;
+ texels[marginalBase + 3] = 0.0;
+
+ const rowTotal = rowTotals[y];
+ let condRunning = 0;
+ for (let x = 0; x < width; x++) {
+ const pixelIndex = y * width + x;
+ const condProb = rowTotal > 0 ? pixelWeights[pixelIndex] / rowTotal : 1 / width;
+ condRunning += condProb;
+ const condBase = (envCdfOffset + height + pixelIndex) * 4;
+ texels[condBase] = x === width - 1 ? 1.0 : Math.min(1.0, condRunning);
+ texels[condBase + 1] = condProb;
+ texels[condBase + 2] = 0.0;
+ texels[condBase + 3] = 0.0;
+ }
+ }
+
+ const envColor = options.envColor ?? [intensity, intensity, intensity];
+ return {
+ environmentTexels: texels,
+ envWidth: width,
+ envHeight: height,
+ envCdfOffset,
+ envRotation,
+ envColor: [Number(envColor[0]), Number(envColor[1]), Number(envColor[2])],
+ envTotalWeight: totalWeight,
+ };
+}
+
+function effectiveCyclesClamp(value) {
+ if (value === undefined || value === null) {
+ return 0.0;
+ }
+ const numeric = Number(value);
+ if (!Number.isFinite(numeric) || numeric <= 0 || numeric >= 1e29) {
+ return 0.0;
+ }
+ return numeric * 3.0;
+}
+
+function resolveFilterParameters(options = {}) {
+ const filter = options.filterType ?? options.pixelFilter ?? 0;
+ let filterType = 0;
+ if (filter === 1 || filter === 'gaussian') {
+ filterType = 1;
+ } else if (filter === 2 || filter === 'blackman-harris' || filter === 'blackman_harris') {
+ filterType = 2;
+ }
+ const defaultWidth = filterType === 0 ? 1.0 : 1.5;
+ const filterWidth = options.filterWidth !== undefined ? Math.max(0.01, Number(options.filterWidth)) : defaultWidth;
+ return { filterType, filterWidth };
+}
+
+function packKernelParamsV2({
+ camera,
+ options,
+ counts,
+ packedEnvironment,
+ volume,
+ usesSubsurface,
+ emissiveTotalWeight,
+ analyticLightTotalWeight,
+ rayEpsilon,
+ farDistance,
+}) {
+ const buffer = new ArrayBuffer(STRUCT_STRIDES_V2.kernelParams);
+ const f32 = new Float32Array(buffer);
+ const u32 = new Uint32Array(buffer);
+
+ const width = Math.max(1, Math.round(Number(options.width ?? 1)));
+ const height = Math.max(1, Math.round(Number(options.height ?? 1)));
+ const totalSamples = Math.max(1, Math.round(Number(options.samples ?? 1)));
+ const samplesPerDispatch = Math.max(1, Math.round(Number(options.samplesPerDispatch ?? 1)));
+ const seed = (options.seed ?? 0) >>> 0;
+ const adaptiveThreshold = Math.max(0, Number(options.noiseThreshold ?? options.adaptiveThreshold ?? 0));
+ const volumeDensity = Math.max(0, Number(volume?.density ?? 0));
+
+ let kernelFlags = 0;
+ if (options.useLightTree === true && counts.lightTreeNodeCount > 0) {
+ kernelFlags |= KERNEL_FLAG_USE_LIGHT_TREE;
+ }
+ if (volumeDensity > 0) {
+ kernelFlags |= KERNEL_FLAG_HAS_VOLUME;
+ }
+ if (usesSubsurface) {
+ kernelFlags |= KERNEL_FLAG_HAS_SUBSURFACE;
+ }
+ if (camera?.orthographic === true || options.orthographic === true) {
+ kernelFlags |= KERNEL_FLAG_ORTHOGRAPHIC_CAMERA;
+ }
+ if (adaptiveThreshold > 0) {
+ kernelFlags |= KERNEL_FLAG_ADAPTIVE_SAMPLING;
+ }
+ if (options.transparentBackground === true) {
+ kernelFlags |= KERNEL_FLAG_TRANSPARENT_BACKGROUND;
+ }
+
+ const maxBounces = Math.max(0, Math.round(Number(options.bounces ?? options.maxBounces ?? 8)));
+ const maxDiffuseBounces = Math.max(0, Math.round(Number(options.diffuseBounces ?? maxBounces)));
+ const maxGlossyBounces = Math.max(0, Math.round(Number(options.glossyBounces ?? maxBounces)));
+ const maxTransmissionBounces = Math.max(0, Math.round(Number(options.transmissionBounces ?? maxBounces)));
+ const maxVolumeBounces = Math.max(0, Math.round(Number(options.volumeBounces ?? maxBounces)));
+ const maxTransparentBounces = Math.max(0, Math.round(Number(options.transparentBounces ?? Math.max(maxBounces, 8))));
+ const minBounceRr = Math.max(0, Math.round(Number(options.minBounceRr ?? 3)));
+ const { filterType, filterWidth } = resolveFilterParameters(options);
+
+ const eye = camera?.eye ?? camera?.position ?? [0, 0, 0];
+ const forward = normalizeVec3(camera?.forward ?? [0, 0, -1], [0, 0, -1]);
+ const halfWidth = Number(camera?.halfWidth ?? 1);
+ const halfHeight = Number(camera?.halfHeight ?? 1);
+ const rawRight = camera?.right ?? [1, 0, 0];
+ const rawUp = camera?.above ?? camera?.up ?? [0, 1, 0];
+ const scaledRight = camera?.scaledAxes
+ ? [Number(rawRight[0]), Number(rawRight[1]), Number(rawRight[2])]
+ : [Number(rawRight[0]) * halfWidth, Number(rawRight[1]) * halfWidth, Number(rawRight[2]) * halfWidth];
+ const scaledUp = camera?.scaledAxes
+ ? [Number(rawUp[0]), Number(rawUp[1]), Number(rawUp[2])]
+ : [Number(rawUp[0]) * halfHeight, Number(rawUp[1]) * halfHeight, Number(rawUp[2]) * halfHeight];
+
+ const cameraNear = Math.max(0, Number(options.near ?? camera?.near ?? 0));
+ const cameraFar = Math.max(cameraNear + 1e-3, Number(options.far ?? camera?.far ?? farDistance ?? 1e30));
+ const lensShift = camera?.lensShift ?? options.lensShift ?? [0, 0];
+
+ u32[0] = FORMAT_V2_MAGIC;
+ u32[1] = FORMAT_V2_VERSION;
+ u32[2] = width >>> 0;
+ u32[3] = height >>> 0;
+
+ u32[4] = (options.sampleOffset ?? 0) >>> 0;
+ u32[5] = samplesPerDispatch >>> 0;
+ u32[6] = totalSamples >>> 0;
+ u32[7] = seed;
+
+ u32[8] = kernelFlags >>> 0;
+ f32[9] = adaptiveThreshold;
+ f32[10] = effectiveCyclesClamp(options.clampDirect);
+ f32[11] = effectiveCyclesClamp(options.clampIndirect);
+
+ u32[12] = maxBounces >>> 0;
+ u32[13] = maxDiffuseBounces >>> 0;
+ u32[14] = maxGlossyBounces >>> 0;
+ u32[15] = maxTransmissionBounces >>> 0;
+
+ u32[16] = maxVolumeBounces >>> 0;
+ u32[17] = maxTransparentBounces >>> 0;
+ u32[18] = minBounceRr >>> 0;
+ u32[19] = filterType >>> 0;
+
+ f32[20] = filterWidth;
+ u32[21] = counts.instanceCount >>> 0;
+ u32[22] = counts.triangleCount >>> 0;
+ u32[23] = counts.materialCount >>> 0;
+
+ u32[24] = counts.emissiveTriangleCount >>> 0;
+ u32[25] = counts.lightCount >>> 0;
+ u32[26] = counts.lightTreeNodeCount >>> 0;
+ u32[27] = counts.textureCount >>> 0;
+
+ f32[28] = Number(eye[0]);
+ f32[29] = Number(eye[1]);
+ f32[30] = Number(eye[2]);
+ f32[31] = cameraNear;
+
+ f32[32] = forward[0];
+ f32[33] = forward[1];
+ f32[34] = forward[2];
+ f32[35] = cameraFar;
+
+ f32[36] = scaledRight[0];
+ f32[37] = scaledRight[1];
+ f32[38] = scaledRight[2];
+ f32[39] = Math.max(0, Number(camera?.apertureRadius ?? options.apertureRadius ?? 0));
+
+ f32[40] = scaledUp[0];
+ f32[41] = scaledUp[1];
+ f32[42] = scaledUp[2];
+ f32[43] = Math.max(1e-4, Number(camera?.focalDistance ?? options.focalDistance ?? 10));
+
+ f32[44] = Number(lensShift[0] ?? 0);
+ f32[45] = Number(lensShift[1] ?? 0);
+ u32[46] = Math.max(0, Math.round(Number(camera?.apertureBlades ?? options.apertureBlades ?? 0))) >>> 0;
+ f32[47] = Number(camera?.apertureRotation ?? options.apertureRotation ?? 0);
+
+ u32[48] = packedEnvironment.envWidth >>> 0;
+ u32[49] = packedEnvironment.envHeight >>> 0;
+ u32[50] = packedEnvironment.envCdfOffset >>> 0;
+ f32[51] = packedEnvironment.envRotation;
+
+ f32[52] = packedEnvironment.envColor[0];
+ f32[53] = packedEnvironment.envColor[1];
+ f32[54] = packedEnvironment.envColor[2];
+ f32[55] = packedEnvironment.envTotalWeight;
+
+ const volMin = volume?.minimum ?? [0, 0, 0];
+ const volMax = volume?.maximum ?? [0, 0, 0];
+ const volAlbedo = volume?.albedo ?? [1, 1, 1];
+ f32[56] = Number(volMin[0]);
+ f32[57] = Number(volMin[1]);
+ f32[58] = Number(volMin[2]);
+ f32[59] = volumeDensity;
+
+ f32[60] = Number(volMax[0]);
+ f32[61] = Number(volMax[1]);
+ f32[62] = Number(volMax[2]);
+ f32[63] = Math.max(-0.99, Math.min(0.99, Number(volume?.anisotropy ?? 0)));
+
+ f32[64] = Number(volAlbedo[0]);
+ f32[65] = Number(volAlbedo[1]);
+ f32[66] = Number(volAlbedo[2]);
+ f32[67] = emissiveTotalWeight;
+
+ f32[68] = analyticLightTotalWeight;
+ f32[69] = rayEpsilon > 0 ? rayEpsilon : 1e-4;
+ u32[70] = Math.max(1, Math.round(Number(options.adaptiveMinSamples ?? 16))) >>> 0;
+ u32[71] = 0;
+
+ f32[72] = Number(options.exposure ?? 1.0);
+ f32[73] = packedEnvironment.envWidth > 0 && packedEnvironment.envTotalWeight > 0 ? 1.0 : 0.0;
+ u32[74] = 0;
+ u32[75] = 0;
+
+ u32[76] = 0;
+ u32[77] = 0;
+ u32[78] = 0;
+ u32[79] = 0;
+
+ return new Uint8Array(buffer);
+}
+
+function buildGeometryTriangleItem(geometry, triIndex, defaultMaterialIndex, meshId, materialRecords) {
+ const { positions, normals, uvs, uv1s, colors, tangents, indices, triangleMaterial } = geometry;
+ const i0 = indices[triIndex * 3];
+ const i1 = indices[triIndex * 3 + 1];
+ const i2 = indices[triIndex * 3 + 2];
+
+ const p0 = [positions[i0 * 3], positions[i0 * 3 + 1], positions[i0 * 3 + 2]];
+ const p1 = [positions[i1 * 3], positions[i1 * 3 + 1], positions[i1 * 3 + 2]];
+ const p2 = [positions[i2 * 3], positions[i2 * 3 + 1], positions[i2 * 3 + 2]];
+ const edge1 = [p1[0] - p0[0], p1[1] - p0[1], p1[2] - p0[2]];
+ const edge2 = [p2[0] - p0[0], p2[1] - p0[1], p2[2] - p0[2]];
+ const geoNormal = normalizeVec3(crossVec3(edge1, edge2), [0, 1, 0]);
+
+ const n0 = normals ? normalizeVec3([normals[i0 * 3], normals[i0 * 3 + 1], normals[i0 * 3 + 2]], geoNormal) : geoNormal;
+ const n1 = normals ? normalizeVec3([normals[i1 * 3], normals[i1 * 3 + 1], normals[i1 * 3 + 2]], geoNormal) : geoNormal;
+ const n2 = normals ? normalizeVec3([normals[i2 * 3], normals[i2 * 3 + 1], normals[i2 * 3 + 2]], geoNormal) : geoNormal;
+
+ const uv0 = uvs ? [uvs[i0 * 2], uvs[i0 * 2 + 1]] : [0, 0];
+ const uv1 = uvs ? [uvs[i1 * 2], uvs[i1 * 2 + 1]] : [0, 0];
+ const uv2 = uvs ? [uvs[i2 * 2], uvs[i2 * 2 + 1]] : [0, 0];
+
+ const c0 = colors ? [colors[i0 * 3], colors[i0 * 3 + 1], colors[i0 * 3 + 2]] : [1, 1, 1];
+ const c1 = colors ? [colors[i1 * 3], colors[i1 * 3 + 1], colors[i1 * 3 + 2]] : [1, 1, 1];
+ const c2 = colors ? [colors[i2 * 3], colors[i2 * 3 + 1], colors[i2 * 3 + 2]] : [1, 1, 1];
+
+ const uvSet1_0 = uv1s ? [uv1s[i0 * 2], uv1s[i0 * 2 + 1]] : [0, 0];
+ const uvSet1_1 = uv1s ? [uv1s[i1 * 2], uv1s[i1 * 2 + 1]] : [0, 0];
+ const uvSet1_2 = uv1s ? [uv1s[i2 * 2], uv1s[i2 * 2 + 1]] : [0, 0];
+
+ let t0;
+ let t1;
+ let t2;
+ let tangentSign = 1.0;
+ if (tangents && tangents.length >= (positions.length / 3) * 4) {
+ t0 = normalizeVec3([tangents[i0 * 4], tangents[i0 * 4 + 1], tangents[i0 * 4 + 2]], [1, 0, 0]);
+ t1 = normalizeVec3([tangents[i1 * 4], tangents[i1 * 4 + 1], tangents[i1 * 4 + 2]], [1, 0, 0]);
+ t2 = normalizeVec3([tangents[i2 * 4], tangents[i2 * 4 + 1], tangents[i2 * 4 + 2]], [1, 0, 0]);
+ tangentSign = tangents[i0 * 4 + 3] < 0 ? -1.0 : 1.0;
+ } else {
+ const computed = computeTriangleTangents(edge1, edge2, n0, n1, n2, uv0, uv1, uv2);
+ t0 = computed.t0;
+ t1 = computed.t1;
+ t2 = computed.t2;
+ tangentSign = computed.sign;
+ }
+
+ let flags = TRIANGLE_FLAG_SMOOTH_NORMALS | TRIANGLE_FLAG_HAS_TANGENTS | TRIANGLE_FLAG_DOUBLE_SIDED;
+ if (colors) {
+ flags |= TRIANGLE_FLAG_HAS_VERTEX_COLORS;
+ }
+ if (uv1s) {
+ flags |= TRIANGLE_FLAG_HAS_UV1;
+ }
+
+ const materialIndex = triangleMaterial ? triangleMaterial[triIndex] : defaultMaterialIndex;
+ const matInfo = materialRecords[materialIndex];
+ const isOpaque = (matInfo?.alphaMode ?? ALPHA_MODE_OPAQUE) === ALPHA_MODE_OPAQUE;
+
+ return {
+ p0,
+ edge1,
+ edge2,
+ n0,
+ n1,
+ n2,
+ uv0,
+ uv1,
+ uv2,
+ t0,
+ t1,
+ t2,
+ tangentSign,
+ c0,
+ c1,
+ c2,
+ uvSet1_0,
+ uvSet1_1,
+ uvSet1_2,
+ flags,
+ materialIndex,
+ meshId,
+ primitiveId: triIndex,
+ localEmissiveOffset: INVALID_INDEX_V2,
+ isOpaque,
+ };
+}
+
+function appendWorldEmissiveIfActive({
+ emissiveList,
+ triItem,
+ globalTriangleIndex,
+ instanceIndex,
+ resolvedMaterialIndex,
+ materialRecords,
+ objectToWorld,
+ negativeScale,
+ lightGroupMaskLo,
+ lightGroupMaskHi,
+}) {
+ const matInfo = materialRecords[resolvedMaterialIndex];
+ if (!matInfo?.isEmissive) {
+ return INVALID_INDEX_V2;
+ }
+ const worldP0 = transformPoint3x4(objectToWorld, triItem.p0);
+ const worldEdge1 = transformDirection3x4(objectToWorld, triItem.edge1);
+ const worldEdge2 = transformDirection3x4(objectToWorld, triItem.edge2);
+ const cross = crossVec3(worldEdge1, worldEdge2);
+ const crossLength = Math.hypot(cross[0], cross[1], cross[2]);
+ const area = 0.5 * crossLength;
+ if (!(area > 1e-12)) {
+ return INVALID_INDEX_V2;
+ }
+ const normalSign = negativeScale ? -1 : 1;
+ const geometricNormal = [
+ (cross[0] / crossLength) * normalSign,
+ (cross[1] / crossLength) * normalSign,
+ (cross[2] / crossLength) * normalSign,
+ ];
+ const radiance = matInfo.meanEmissiveRadiance;
+ const selectionWeight = luminance(radiance) * area;
+ if (!(selectionWeight > 0)) {
+ return INVALID_INDEX_V2;
+ }
+ const emittedIndex = emissiveList.length;
+ emissiveList.push({
+ p0: worldP0,
+ area,
+ edge1: worldEdge1,
+ instanceIndex,
+ edge2: worldEdge2,
+ triangleIndex: globalTriangleIndex,
+ geometricNormal,
+ materialIndex: resolvedMaterialIndex,
+ radiance,
+ selectionWeight,
+ lightGroupMaskLo,
+ lightGroupMaskHi,
+ });
+ return emittedIndex;
+}
+
+function packInstancedGeometry(instancesInput, rawMaterials, textureCollector) {
+ const materialRecords = rawMaterials.map(mat => packMaterialRecordV2(mat, textureCollector));
+ const materialsBuffer = new Uint8Array(Math.max(1, materialRecords.length) * STRUCT_STRIDES_V2.material);
+ materialRecords.forEach((rec, index) => materialsBuffer.set(rec.bytes, index * STRUCT_STRIDES_V2.material));
+
+ const forceNonOpaqueGeometries = new Set();
+ const firstDefaultMatByGeo = new Map();
+ for (let instIdx = 0; instIdx < instancesInput.length; instIdx++) {
+ const inst = instancesInput[instIdx];
+ const geometry = inst?.geometry;
+ if (!geometry) continue;
+ const defaultMat = Number(inst.materialIndex ?? 0);
+ if (!firstDefaultMatByGeo.has(geometry)) {
+ firstDefaultMatByGeo.set(geometry, defaultMat);
+ }
+ const overrideMat = inst.materialOverride !== undefined
+ ? (inst.materialOverride >>> 0)
+ : (!geometry.triangleMaterial && defaultMat !== firstDefaultMatByGeo.get(geometry) ? (defaultMat >>> 0) : INVALID_INDEX_V2);
+ if (overrideMat !== INVALID_INDEX_V2) {
+ const matAlphaMode = materialRecords[overrideMat]?.alphaMode ?? ALPHA_MODE_OPAQUE;
+ if (matAlphaMode !== ALPHA_MODE_OPAQUE) {
+ forceNonOpaqueGeometries.add(geometry);
+ }
+ }
+ }
+
+ const meshCache = new Map();
+ const allTriangles = [];
+ const instanceItems = [];
+ const emissiveList = [];
+
+ for (let instIdx = 0; instIdx < instancesInput.length; instIdx++) {
+ const inst = instancesInput[instIdx];
+ const geometry = inst.geometry;
+ if (!geometry?.positions || !geometry?.indices) {
+ throw new TypeError(`Instance[${instIdx}] requires a geometry with positions and indices.`);
+ }
+ const defaultMaterialIndex = Number(inst.materialIndex ?? 0);
+ let materialOverride = inst.materialOverride !== undefined
+ ? (inst.materialOverride >>> 0)
+ : (inst.overrideMaterial === true ? (defaultMaterialIndex >>> 0) : INVALID_INDEX_V2);
+
+ let meshSlot = meshCache.get(geometry);
+ if (!meshSlot) {
+ const blasIndex = meshCache.size;
+ const triCount = Math.floor(geometry.indices.length / 3);
+ const forceNonOpaque = forceNonOpaqueGeometries.has(geometry);
+ const opaque = [];
+ const cutout = [];
+ for (let t = 0; t < triCount; t++) {
+ const item = buildGeometryTriangleItem(geometry, t, defaultMaterialIndex, blasIndex, materialRecords);
+ if (item.isOpaque && !forceNonOpaque) {
+ opaque.push(item);
+ } else {
+ cutout.push(item);
+ }
+ }
+ const ordered = [...opaque, ...cutout];
+ const triangleOffset = allTriangles.length;
+ const opaqueTriangleCount = opaque.length;
+ const totalTriangleCount = ordered.length;
+
+ let localEmissiveCounter = 0;
+ for (const item of ordered) {
+ if (materialRecords[item.materialIndex]?.isEmissive) {
+ item.localEmissiveOffset = localEmissiveCounter++;
+ }
+ allTriangles.push(item);
+ }
+ meshSlot = { blasIndex, defaultMaterialIndex, triangleOffset, opaqueTriangleCount, totalTriangleCount, ordered };
+ meshCache.set(geometry, meshSlot);
+ } else if (
+ materialOverride === INVALID_INDEX_V2 &&
+ !geometry.triangleMaterial &&
+ defaultMaterialIndex !== meshSlot.defaultMaterialIndex
+ ) {
+ materialOverride = defaultMaterialIndex >>> 0;
+ }
+
+ const decomposed = decomposeAffineMatrix(inst.matrix ?? IDENTITY_MATRIX_4X4);
+ const masks = resolveLightMaskWords(inst.lightMask, inst.lightMaskHi);
+ const baseVisibility = inst.visibilityFlags !== undefined
+ ? (inst.visibilityFlags & 0x3f)
+ : INSTANCE_DEFAULT_VISIBILITY;
+ const visibilityFlags = (baseVisibility | (decomposed.negativeScale ? INSTANCE_FLAG_NEGATIVE_SCALE : 0)) >>> 0;
+
+ let emissiveBaseOffset = INVALID_INDEX_V2;
+ let instanceEmissiveCount = 0;
+ for (let localIdx = 0; localIdx < meshSlot.ordered.length; localIdx++) {
+ const triItem = meshSlot.ordered[localIdx];
+ const globalTriIdx = meshSlot.triangleOffset + localIdx;
+ const resolvedMatIdx = materialOverride !== INVALID_INDEX_V2 ? materialOverride : triItem.materialIndex;
+ const emittedIdx = appendWorldEmissiveIfActive({
+ emissiveList,
+ triItem,
+ globalTriangleIndex: globalTriIdx,
+ instanceIndex: instIdx,
+ resolvedMaterialIndex: resolvedMatIdx,
+ materialRecords,
+ objectToWorld: decomposed.objectToWorld,
+ negativeScale: decomposed.negativeScale,
+ lightGroupMaskLo: masks.lo,
+ lightGroupMaskHi: masks.hi,
+ });
+ if (emittedIdx !== INVALID_INDEX_V2) {
+ if (emissiveBaseOffset === INVALID_INDEX_V2) {
+ emissiveBaseOffset = emittedIdx;
+ }
+ if (triItem.localEmissiveOffset === INVALID_INDEX_V2) {
+ triItem.localEmissiveOffset = instanceEmissiveCount;
+ }
+ instanceEmissiveCount++;
+ }
+ }
+
+ const objectId = (inst.objectId ?? instIdx) >>> 0;
+ instanceItems.push({
+ objectToWorld: decomposed.objectToWorld,
+ worldToObject: decomposed.worldToObject,
+ blasIndex: meshSlot.blasIndex,
+ triangleOffset: meshSlot.triangleOffset,
+ opaqueTriangleCount: meshSlot.opaqueTriangleCount,
+ totalTriangleCount: meshSlot.totalTriangleCount,
+ materialOverride,
+ visibilityFlags,
+ lightGroupMaskLo: masks.lo,
+ lightGroupMaskHi: masks.hi,
+ emissiveBaseOffset,
+ objectId,
+ objectRandom: inst.objectRandom !== undefined ? Number(inst.objectRandom) : deterministicUnitHash(objectId),
+ shadowTerminatorOffset: Number(inst.shadowTerminatorOffset ?? 0),
+ objectColor: inst.objectColor ?? [1, 1, 1, 1],
+ });
+ }
+
+ const trianglesBuffer = new Uint8Array(Math.max(1, allTriangles.length) * STRUCT_STRIDES_V2.triangle);
+ for (let index = 0; index < allTriangles.length; index++) {
+ writeTriangleRecordBytes(trianglesBuffer, index * STRUCT_STRIDES_V2.triangle, allTriangles[index]);
+ }
+ const instancesBuffer = new Uint8Array(Math.max(1, instanceItems.length) * STRUCT_STRIDES_V2.instance);
+ for (let index = 0; index < instanceItems.length; index++) {
+ writeInstanceRecordBytes(instancesBuffer, index * STRUCT_STRIDES_V2.instance, instanceItems[index]);
+ }
+
+ return {
+ instances: instancesBuffer,
+ instanceCount: instanceItems.length,
+ triangles: trianglesBuffer,
+ triangleCount: allTriangles.length,
+ materials: materialsBuffer,
+ materialCount: materialRecords.length,
+ usesSubsurface: materialRecords.some(rec => rec.usesSubsurface),
+ emissiveList,
+ };
+}
+
+function packFlattenedTraceScene(scene, rawParts, textureCollector) {
+ const mergedMaterials = (scene.materials ?? []).map((resolvedMat, index) => {
+ const rawMat = rawParts?.[index]?.material;
+ return rawMat ? { ...rawMat, ...resolvedMat } : resolvedMat;
+ });
+ const materialRecords = mergedMaterials.map(mat => packMaterialRecordV2(mat, textureCollector));
+ const materialsBuffer = new Uint8Array(Math.max(1, materialRecords.length) * STRUCT_STRIDES_V2.material);
+ materialRecords.forEach((rec, index) => materialsBuffer.set(rec.bytes, index * STRUCT_STRIDES_V2.material));
+
+ const totalSceneTriangles = Math.floor((scene.indices?.length ?? 0) / 3);
+ const trianglesByPart = new Map();
+ for (let triIndex = 0; triIndex < totalSceneTriangles; triIndex++) {
+ const partIndex = scene.triangleMaterial ? scene.triangleMaterial[triIndex] : 0;
+ let bucket = trianglesByPart.get(partIndex);
+ if (!bucket) {
+ bucket = [];
+ trianglesByPart.set(partIndex, bucket);
+ }
+ bucket.push(triIndex);
+ }
+
+ const identityTransform = decomposeAffineMatrix(IDENTITY_MATRIX_4X4);
+ const allTriangles = [];
+ const instanceItems = [];
+ const emissiveList = [];
+
+ const sortedPartIndices = [...trianglesByPart.keys()].sort((a, b) => a - b);
+ for (const partIndex of sortedPartIndices) {
+ const triIndices = trianglesByPart.get(partIndex);
+ const opaque = [];
+ const cutout = [];
+ for (const triIndex of triIndices) {
+ const item = buildGeometryTriangleItem(scene, triIndex, partIndex, partIndex, materialRecords);
+ if (item.isOpaque) {
+ opaque.push(item);
+ } else {
+ cutout.push(item);
+ }
+ }
+ const ordered = [...opaque, ...cutout];
+ const instanceIndex = instanceItems.length;
+ const triangleOffset = allTriangles.length;
+ const partMaterial = mergedMaterials[partIndex] ?? {};
+ const masks = resolveLightMaskWords(partMaterial.lightMask, partMaterial.lightMaskHi);
+
+ let emissiveBaseOffset = INVALID_INDEX_V2;
+ let localEmissiveCounter = 0;
+ for (let localIdx = 0; localIdx < ordered.length; localIdx++) {
+ const triItem = ordered[localIdx];
+ const globalTriIdx = triangleOffset + localIdx;
+ const emittedIdx = appendWorldEmissiveIfActive({
+ emissiveList,
+ triItem,
+ globalTriangleIndex: globalTriIdx,
+ instanceIndex,
+ resolvedMaterialIndex: triItem.materialIndex,
+ materialRecords,
+ objectToWorld: identityTransform.objectToWorld,
+ negativeScale: false,
+ lightGroupMaskLo: masks.lo,
+ lightGroupMaskHi: masks.hi,
+ });
+ if (emittedIdx !== INVALID_INDEX_V2) {
+ if (emissiveBaseOffset === INVALID_INDEX_V2) {
+ emissiveBaseOffset = emittedIdx;
+ }
+ triItem.localEmissiveOffset = localEmissiveCounter++;
+ }
+ allTriangles.push(triItem);
+ }
+
+ const objectId = partIndex >>> 0;
+ instanceItems.push({
+ objectToWorld: identityTransform.objectToWorld,
+ worldToObject: identityTransform.worldToObject,
+ blasIndex: instanceIndex,
+ triangleOffset,
+ opaqueTriangleCount: opaque.length,
+ totalTriangleCount: ordered.length,
+ materialOverride: INVALID_INDEX_V2,
+ visibilityFlags: INSTANCE_DEFAULT_VISIBILITY,
+ lightGroupMaskLo: masks.lo,
+ lightGroupMaskHi: masks.hi,
+ emissiveBaseOffset,
+ objectId,
+ objectRandom: deterministicUnitHash(objectId),
+ shadowTerminatorOffset: 0,
+ objectColor: [1, 1, 1, 1],
+ });
+ }
+
+ const trianglesBuffer = new Uint8Array(Math.max(1, allTriangles.length) * STRUCT_STRIDES_V2.triangle);
+ for (let index = 0; index < allTriangles.length; index++) {
+ writeTriangleRecordBytes(trianglesBuffer, index * STRUCT_STRIDES_V2.triangle, allTriangles[index]);
+ }
+ const instancesBuffer = new Uint8Array(Math.max(1, instanceItems.length) * STRUCT_STRIDES_V2.instance);
+ for (let index = 0; index < instanceItems.length; index++) {
+ writeInstanceRecordBytes(instancesBuffer, index * STRUCT_STRIDES_V2.instance, instanceItems[index]);
+ }
+
+ return {
+ instances: instancesBuffer,
+ instanceCount: instanceItems.length,
+ triangles: trianglesBuffer,
+ triangleCount: allTriangles.length,
+ materials: materialsBuffer,
+ materialCount: materialRecords.length,
+ usesSubsurface: materialRecords.some(rec => rec.usesSubsurface),
+ emissiveList,
+ };
+}
+
+/**
+ * Packs a 67js scene (from `buildTraceScene` or an explicit `{ instances, materials }` descriptor) and camera into
+ * `FORMAT-v2` typed-array buffers (`schemaVersion: 2`) matching `FORMAT-v2.md` and `src/cycles/abi.wgsl`.
+ */
+export function buildNativeInputV2(scene, camera, options = {}) {
+ if (!scene || typeof scene !== 'object') {
+ throw new TypeError('buildNativeInputV2 requires a scene object.');
+ }
+ if (scene.localVolumes) {
+ throw new RangeError(
+ 'environment.localVolumes is traced by the CPU path tracer only; render-native cannot draw them. Use backend "cpu" or remove the volumes.'
+ );
+ }
+ if (!camera || typeof camera !== 'object') {
+ throw new TypeError('buildNativeInputV2 requires a camera object.');
+ }
+
+ const textureCollector = createTextureCollector();
+ const explicitInstances = options.instances ?? scene.instances;
+ const packedGeometry = explicitInstances
+ ? packInstancedGeometry(explicitInstances, options.materials ?? scene.materials ?? [{}], textureCollector)
+ : packFlattenedTraceScene(scene, options.parts ?? scene.parts, textureCollector);
+
+ const packedTextures = textureCollector.finish();
+ const packedEmissives = packEmissiveTriangleBuffer(packedGeometry.emissiveList);
+ const analyticEntries = buildAnalyticLightEntries(scene.lights);
+ const packedLights = packAnalyticLightsBuffer(analyticEntries);
+ const packedLightTree = packRootLightTreeNode(packedLights, packedEmissives);
+ const packedEnvironment = packEnvironmentTexelsV2(scene.environment, options);
+
+ const counts = {
+ instanceCount: packedGeometry.instanceCount,
+ triangleCount: packedGeometry.triangleCount,
+ materialCount: packedGeometry.materialCount,
+ emissiveTriangleCount: packedEmissives.emissiveTriangleCount,
+ lightCount: packedLights.lightCount,
+ lightTreeNodeCount: packedLightTree.lightTreeNodeCount,
+ textureCount: packedTextures.textureCount,
+ };
+
+ const kernelParams = packKernelParamsV2({
+ camera,
+ options,
+ counts,
+ packedEnvironment,
+ volume: scene.volume,
+ usesSubsurface: packedGeometry.usesSubsurface,
+ emissiveTotalWeight: packedEmissives.emissiveTotalWeight,
+ analyticLightTotalWeight: packedLights.analyticLightTotalWeight,
+ rayEpsilon: Number(scene.surfaceOffset ?? options.rayEpsilon ?? 1e-4),
+ farDistance: Number(scene.farDistance ?? 1e30),
+ });
+
+ return {
+ schemaVersion: FORMAT_V2_VERSION,
+ kernelParams,
+ instances: packedGeometry.instances,
+ instanceCount: counts.instanceCount,
+ triangles: packedGeometry.triangles,
+ triangleCount: counts.triangleCount,
+ materials: packedGeometry.materials,
+ materialCount: counts.materialCount,
+ emissiveTriangles: packedEmissives.emissiveTriangles,
+ emissiveTriangleCount: counts.emissiveTriangleCount,
+ lights: packedLights.lights,
+ lightCount: counts.lightCount,
+ lightTreeNodes: packedLightTree.lightTreeNodes,
+ lightTreeNodeCount: counts.lightTreeNodeCount,
+ textureDescriptors: packedTextures.textureDescriptors,
+ textureCount: counts.textureCount,
+ textureTexels: packedTextures.textureTexels,
+ environmentTexels: packedEnvironment.environmentTexels,
+ };
+}
+
+function extractAtlasSubtexture(atlasWords, atlasWidth, rectX, rectY, width, height) {
+ const words = new Uint32Array(width * height);
+ for (let row = 0; row < height; row++) {
+ const srcStart = (rectY + row) * atlasWidth + rectX;
+ words.set(atlasWords.subarray(srcStart, srcStart + width), row * width);
+ }
+ return words;
+}
+
+/**
+ * Upgrades a legacy v1 `buildNativeInput` payload to `FORMAT-v2` (`schemaVersion: 2`) so existing callers passing v1
+ * inputs with `kernel: 'cycles'` or `JS67_NATIVE_KERNEL=cycles` run without changing call sites.
+ */
+export function upgradeNativeInputV1ToV2(v1Input, options = {}) {
+ if (v1Input?.schemaVersion === FORMAT_V2_VERSION) {
+ return v1Input;
+ }
+ if (!v1Input || !(v1Input.parameters instanceof Uint8Array) || v1Input.parameters.byteLength !== 256) {
+ throw new TypeError('upgradeNativeInputV1ToV2 requires a v1 NativeTraceInput with a 256-byte parameters block, or a FORMAT-v2 input.');
+ }
+
+ const paramBuffer = v1Input.parameters.buffer;
+ const paramByteOffset = v1Input.parameters.byteOffset;
+ const paramF32 = new Float32Array(paramBuffer, paramByteOffset, 64);
+ const paramI32 = new Int32Array(paramBuffer, paramByteOffset, 64);
+ const paramU32 = new Uint32Array(paramBuffer, paramByteOffset, 64);
+
+ const triangleCount = Number(v1Input.triangleCount ?? 0);
+ const triData = v1Input.triangles;
+ if (!(triangleCount >= 0) || !triData || triData.length < triangleCount * 36) {
+ throw new RangeError('v1 NativeTraceInput.triangles must hold at least triangleCount * 36 floats.');
+ }
+
+ const subsurfaceVec4Offset = paramU32[60];
+ const materialVec4Limit = subsurfaceVec4Offset > 0 ? subsurfaceVec4Offset : Math.floor((v1Input.materials?.length ?? 0) / 4);
+ const maxPossibleMaterials = Math.max(1, Math.floor(materialVec4Limit / 10));
+ let highestMaterialIndex = 0;
+ for (let slot = 0; slot < triangleCount; slot++) {
+ const matIdx = Math.max(0, Math.round(triData[slot * 36 + 3]));
+ if (matIdx > highestMaterialIndex) {
+ highestMaterialIndex = matIdx;
+ }
+ }
+ const materialCount = Math.min(maxPossibleMaterials, highestMaterialIndex + 1);
+
+ const textureCollector = createTextureCollector();
+ const atlasCache = new Map();
+ const atlasWidth = paramU32[45] || 1;
+ const atlasWords = v1Input.atlas;
+
+ function registerAtlasRect(rectX, rectY, width, height, flagsValue) {
+ if (!(width > 0 && height > 0) || !atlasWords) {
+ return { index: -1, meanLinearRgb: [1, 1, 1] };
+ }
+ const x = Math.round(rectX);
+ const y = Math.round(rectY);
+ const w = Math.round(width);
+ const h = Math.round(height);
+ const flags = Math.round(flagsValue);
+ const key = `${x},${y},${w},${h},${flags}`;
+ if (atlasCache.has(key)) {
+ return atlasCache.get(key);
+ }
+ const repeat = (flags & 1) !== 0;
+ const isSrgb = (flags & 2) !== 0;
+ const subWords = extractAtlasSubtexture(atlasWords, atlasWidth, x, y, w, h);
+ const added = textureCollector.addPackedRgba8Words(subWords, w, h, isSrgb, repeat);
+ atlasCache.set(key, added);
+ return added;
+ }
+
+ const matSource = v1Input.materials;
+ const materialRecords = [];
+ const materialLightMasks = [];
+ for (let m = 0; m < materialCount; m++) {
+ const base = m * 40;
+ const baseColor = [matSource[base], matSource[base + 1], matSource[base + 2]];
+ const metallic = matSource[base + 3];
+ const emission = [matSource[base + 4], matSource[base + 5], matSource[base + 6]];
+ const roughness = matSource[base + 7];
+ const clearcoat = matSource[base + 8];
+ const clearcoatRoughness = matSource[base + 9];
+ const transmission = matSource[base + 10];
+ const ior = matSource[base + 11] > 0 ? matSource[base + 11] : 1.5;
+ const normalScale = [matSource[base + 12] || 1, matSource[base + 13] || 1];
+ const alphaCutoff = matSource[base + 14];
+ const maskLo = ((Math.round(matSource[base + 15]) & 0xffff) | ((Math.round(matSource[base + 16]) & 0xffff) << 16)) >>> 0;
+ materialLightMasks.push(maskLo);
+
+ const baseTex = registerAtlasRect(matSource[base + 24], matSource[base + 25], matSource[base + 26], matSource[base + 27], matSource[base + 17]);
+ const normalTex = registerAtlasRect(matSource[base + 28], matSource[base + 29], matSource[base + 30], matSource[base + 31], matSource[base + 18]);
+ const mrTex = registerAtlasRect(matSource[base + 32], matSource[base + 33], matSource[base + 34], matSource[base + 35], matSource[base + 19]);
+ const emissionTex = registerAtlasRect(matSource[base + 36], matSource[base + 37], matSource[base + 38], matSource[base + 39], matSource[base + 20]);
+
+ let subsurface = null;
+ if (subsurfaceVec4Offset > 0) {
+ const subBase = subsurfaceVec4Offset * 4 + m * 8;
+ if (subBase + 7 < matSource.length && matSource[subBase] > 0) {
+ const hasCustomColor = matSource[subBase + 4] >= 0;
+ subsurface = {
+ weight: matSource[subBase],
+ meanFreePath: [matSource[subBase + 1], matSource[subBase + 2], matSource[subBase + 3]],
+ color: hasCustomColor ? [matSource[subBase + 4], matSource[subBase + 5], matSource[subBase + 6]] : baseColor,
+ };
+ }
+ }
+
+ const packedMat = packMaterialRecordV2({
+ baseColor,
+ metallic,
+ roughness,
+ ior,
+ clearcoat,
+ clearcoatRoughness,
+ transmission,
+ normalScale,
+ emission,
+ subsurface,
+ alphaMode: alphaCutoff > 0 && baseTex.index >= 0 ? 'mask' : 'opaque',
+ alphaCutoff: alphaCutoff > 0 && baseTex.index >= 0 ? alphaCutoff : 0,
+ baseColorTex: baseTex.index,
+ normalTex: normalTex.index,
+ metallicRoughnessTex: mrTex.index,
+ emissionTex: emissionTex.index,
+ alphaTex: alphaCutoff > 0 && baseTex.index >= 0 ? baseTex.index : -1,
+ }, null);
+ packedMat.meanEmissiveRadiance = [
+ packedMat.meanEmissiveRadiance[0] * emissionTex.meanLinearRgb[0],
+ packedMat.meanEmissiveRadiance[1] * emissionTex.meanLinearRgb[1],
+ packedMat.meanEmissiveRadiance[2] * emissionTex.meanLinearRgb[2],
+ ];
+ packedMat.isEmissive = luminance(packedMat.meanEmissiveRadiance) > 0;
+ materialRecords.push(packedMat);
+ }
+
+ const materialsBuffer = new Uint8Array(Math.max(1, materialRecords.length) * STRUCT_STRIDES_V2.material);
+ materialRecords.forEach((rec, idx) => materialsBuffer.set(rec.bytes, idx * STRUCT_STRIDES_V2.material));
+
+ const trianglesByMat = new Map();
+ for (let slot = 0; slot < triangleCount; slot++) {
+ const matIdx = Math.min(materialCount - 1, Math.max(0, Math.round(triData[slot * 36 + 3])));
+ let list = trianglesByMat.get(matIdx);
+ if (!list) {
+ list = [];
+ trianglesByMat.set(matIdx, list);
+ }
+ list.push(slot);
+ }
+
+ const identityTransform = decomposeAffineMatrix(IDENTITY_MATRIX_4X4);
+ const allTriangles = [];
+ const instanceItems = [];
+ const emissiveList = [];
+
+ for (const matIdx of [...trianglesByMat.keys()].sort((a, b) => a - b)) {
+ const slots = trianglesByMat.get(matIdx);
+ const opaque = [];
+ const cutout = [];
+ for (const slot of slots) {
+ const b = slot * 36;
+ const p0 = [triData[b], triData[b + 1], triData[b + 2]];
+ const edge1 = [triData[b + 4], triData[b + 5], triData[b + 6]];
+ const edge2 = [triData[b + 8], triData[b + 9], triData[b + 10]];
+ const geoNormal = normalizeVec3(crossVec3(edge1, edge2), [0, 1, 0]);
+ const n0 = normalizeVec3([triData[b + 12], triData[b + 13], triData[b + 14]], geoNormal);
+ const n1 = normalizeVec3([triData[b + 16], triData[b + 17], triData[b + 18]], geoNormal);
+ const n2 = normalizeVec3([triData[b + 20], triData[b + 21], triData[b + 22]], geoNormal);
+ const uv0 = [triData[b + 15], triData[b + 27]];
+ const uv1 = [triData[b + 19], triData[b + 31]];
+ const uv2 = [triData[b + 23], triData[b + 35]];
+ const c0 = [triData[b + 24], triData[b + 25], triData[b + 26]];
+ const c1 = [triData[b + 28], triData[b + 29], triData[b + 30]];
+ const c2 = [triData[b + 32], triData[b + 33], triData[b + 34]];
+ const tang = computeTriangleTangents(edge1, edge2, n0, n1, n2, uv0, uv1, uv2);
+ const isOpaque = (materialRecords[matIdx]?.alphaMode ?? ALPHA_MODE_OPAQUE) === ALPHA_MODE_OPAQUE;
+ const triItem = {
+ p0,
+ edge1,
+ edge2,
+ n0,
+ n1,
+ n2,
+ uv0,
+ uv1,
+ uv2,
+ t0: tang.t0,
+ t1: tang.t1,
+ t2: tang.t2,
+ tangentSign: tang.sign,
+ c0,
+ c1,
+ c2,
+ uvSet1_0: [0, 0],
+ uvSet1_1: [0, 0],
+ uvSet1_2: [0, 0],
+ flags: TRIANGLE_FLAG_SMOOTH_NORMALS | TRIANGLE_FLAG_HAS_VERTEX_COLORS | TRIANGLE_FLAG_HAS_TANGENTS | TRIANGLE_FLAG_DOUBLE_SIDED,
+ materialIndex: matIdx,
+ meshId: matIdx,
+ primitiveId: slot,
+ localEmissiveOffset: INVALID_INDEX_V2,
+ isOpaque,
+ };
+ if (isOpaque) {
+ opaque.push(triItem);
+ } else {
+ cutout.push(triItem);
+ }
+ }
+
+ const ordered = [...opaque, ...cutout];
+ const instanceIndex = instanceItems.length;
+ const triangleOffset = allTriangles.length;
+ const maskLo = materialLightMasks[matIdx] ?? 0xffffffff;
+ const maskHi = maskLo === 0xffffffff ? 0xffffffff : 0;
+
+ let emissiveBaseOffset = INVALID_INDEX_V2;
+ let localEmissiveCounter = 0;
+ for (let localIdx = 0; localIdx < ordered.length; localIdx++) {
+ const triItem = ordered[localIdx];
+ const globalTriIdx = triangleOffset + localIdx;
+ const emittedIdx = appendWorldEmissiveIfActive({
+ emissiveList,
+ triItem,
+ globalTriangleIndex: globalTriIdx,
+ instanceIndex,
+ resolvedMaterialIndex: matIdx,
+ materialRecords,
+ objectToWorld: identityTransform.objectToWorld,
+ negativeScale: false,
+ lightGroupMaskLo: maskLo,
+ lightGroupMaskHi: maskHi,
+ });
+ if (emittedIdx !== INVALID_INDEX_V2) {
+ if (emissiveBaseOffset === INVALID_INDEX_V2) {
+ emissiveBaseOffset = emittedIdx;
+ }
+ triItem.localEmissiveOffset = localEmissiveCounter++;
+ }
+ allTriangles.push(triItem);
+ }
+
+ const objectId = matIdx >>> 0;
+ instanceItems.push({
+ objectToWorld: identityTransform.objectToWorld,
+ worldToObject: identityTransform.worldToObject,
+ blasIndex: instanceIndex,
+ triangleOffset,
+ opaqueTriangleCount: opaque.length,
+ totalTriangleCount: ordered.length,
+ materialOverride: INVALID_INDEX_V2,
+ visibilityFlags: INSTANCE_DEFAULT_VISIBILITY,
+ lightGroupMaskLo: maskLo,
+ lightGroupMaskHi: maskHi,
+ emissiveBaseOffset,
+ objectId,
+ objectRandom: deterministicUnitHash(objectId),
+ shadowTerminatorOffset: 0,
+ objectColor: [1, 1, 1, 1],
+ });
+ }
+
+ const trianglesBuffer = new Uint8Array(Math.max(1, allTriangles.length) * STRUCT_STRIDES_V2.triangle);
+ for (let idx = 0; idx < allTriangles.length; idx++) {
+ writeTriangleRecordBytes(trianglesBuffer, idx * STRUCT_STRIDES_V2.triangle, allTriangles[idx]);
+ }
+ const instancesBuffer = new Uint8Array(Math.max(1, instanceItems.length) * STRUCT_STRIDES_V2.instance);
+ for (let idx = 0; idx < instanceItems.length; idx++) {
+ writeInstanceRecordBytes(instancesBuffer, idx * STRUCT_STRIDES_V2.instance, instanceItems[idx]);
+ }
+
+ const v1LightCount = Math.max(0, paramI32[39]);
+ const hasSun = paramI32[41] > 0;
+ const reconstructedLights = { sun: null, points: [], spots: [], areas: [] };
+ if (hasSun) {
+ const cosSun = Math.min(1, Math.max(-1, paramF32[23]));
+ reconstructedLights.sun = {
+ bit: 0,
+ direction: [paramF32[16], paramF32[17], paramF32[18]],
+ color: [paramF32[20], paramF32[21], paramF32[22]],
+ angularRadius: Math.acos(cosSun),
+ };
+ }
+ const lightFloats = v1Input.lights;
+ for (let i = 0; i < v1LightCount; i++) {
+ const b = i * 24;
+ const position = [lightFloats[b], lightFloats[b + 1], lightFloats[b + 2]];
+ const type = Math.round(lightFloats[b + 3]);
+ const color = [lightFloats[b + 4], lightFloats[b + 5], lightFloats[b + 6]];
+ const bit = Math.round(lightFloats[b + 7]);
+ if (type === 2) {
+ reconstructedLights.areas.push({
+ bit,
+ position,
+ color,
+ normal: [lightFloats[b + 8], lightFloats[b + 9], lightFloats[b + 10]],
+ width: lightFloats[b + 11],
+ across: [lightFloats[b + 12], lightFloats[b + 13], lightFloats[b + 14]],
+ height: lightFloats[b + 15],
+ along: [lightFloats[b + 16], lightFloats[b + 17], lightFloats[b + 18]],
+ intensity: lightFloats[b + 20],
+ });
+ } else if (type === 1) {
+ reconstructedLights.spots.push({
+ bit,
+ position,
+ color,
+ direction: [lightFloats[b + 8], lightFloats[b + 9], lightFloats[b + 10]],
+ radius: lightFloats[b + 11],
+ cosineHalfAngle: lightFloats[b + 15],
+ blend: lightFloats[b + 19],
+ intensity: lightFloats[b + 20],
+ range: lightFloats[b + 21],
+ });
+ } else {
+ reconstructedLights.points.push({
+ bit,
+ position,
+ color,
+ radius: lightFloats[b + 11],
+ intensity: lightFloats[b + 20],
+ range: lightFloats[b + 21],
+ });
+ }
+ }
+
+ const hasEnvironment = paramI32[42] > 0;
+ const reconstructedEnv = hasEnvironment && v1Input.environmentColors
+ ? {
+ width: Math.max(1, Math.round(paramF32[24])),
+ height: Math.max(1, Math.round(paramF32[25])),
+ channels: 4,
+ data: v1Input.environmentColors,
+ intensity: paramF32[26],
+ cosine: paramF32[28],
+ sine: paramF32[29],
+ }
+ : null;
+
+ const volume = paramF32[51] > 0
+ ? {
+ minimum: [paramF32[48], paramF32[49], paramF32[50]],
+ density: paramF32[51],
+ maximum: [paramF32[52], paramF32[53], paramF32[54]],
+ anisotropy: paramF32[55],
+ albedo: [paramF32[56], paramF32[57], paramF32[58]],
+ maxDistance: paramF32[59],
+ }
+ : null;
+
+ const camera = {
+ eye: [paramF32[0], paramF32[1], paramF32[2]],
+ forward: [paramF32[4], paramF32[5], paramF32[6]],
+ right: [paramF32[8], paramF32[9], paramF32[10]],
+ above: [paramF32[12], paramF32[13], paramF32[14]],
+ halfWidth: paramF32[32],
+ halfHeight: paramF32[33],
+ };
+
+ const packedTextures = textureCollector.finish();
+ const packedEmissives = packEmissiveTriangleBuffer(emissiveList);
+ const analyticEntries = buildAnalyticLightEntries(reconstructedLights);
+ const packedLights = packAnalyticLightsBuffer(analyticEntries);
+ const packedLightTree = packRootLightTreeNode(packedLights, packedEmissives);
+ const packedEnvironment = packEnvironmentTexelsV2(reconstructedEnv, options);
+
+ const mergedOptions = {
+ width: options.width ?? paramI32[36],
+ height: options.height ?? paramI32[37],
+ bounces: options.bounces ?? paramI32[38],
+ seed: options.seed ?? paramU32[44],
+ noiseThreshold: options.noiseThreshold ?? paramF32[35],
+ ...options,
+ };
+
+ const counts = {
+ instanceCount: instanceItems.length,
+ triangleCount: allTriangles.length,
+ materialCount: materialRecords.length,
+ emissiveTriangleCount: packedEmissives.emissiveTriangleCount,
+ lightCount: packedLights.lightCount,
+ lightTreeNodeCount: packedLightTree.lightTreeNodeCount,
+ textureCount: packedTextures.textureCount,
+ };
+
+ const kernelParams = packKernelParamsV2({
+ camera,
+ options: mergedOptions,
+ counts,
+ packedEnvironment,
+ volume,
+ usesSubsurface: materialRecords.some(rec => rec.usesSubsurface),
+ emissiveTotalWeight: packedEmissives.emissiveTotalWeight,
+ analyticLightTotalWeight: packedLights.analyticLightTotalWeight,
+ rayEpsilon: paramF32[30] > 0 ? paramF32[30] : 1e-4,
+ farDistance: paramF32[31] > 0 ? paramF32[31] : 1e30,
+ });
+
+ return {
+ schemaVersion: FORMAT_V2_VERSION,
+ kernelParams,
+ instances: instancesBuffer,
+ instanceCount: counts.instanceCount,
+ triangles: trianglesBuffer,
+ triangleCount: counts.triangleCount,
+ materials: materialsBuffer,
+ materialCount: counts.materialCount,
+ emissiveTriangles: packedEmissives.emissiveTriangles,
+ emissiveTriangleCount: counts.emissiveTriangleCount,
+ lights: packedLights.lights,
+ lightCount: counts.lightCount,
+ lightTreeNodes: packedLightTree.lightTreeNodes,
+ lightTreeNodeCount: counts.lightTreeNodeCount,
+ textureDescriptors: packedTextures.textureDescriptors,
+ textureCount: counts.textureCount,
+ textureTexels: packedTextures.textureTexels,
+ environmentTexels: packedEnvironment.environmentTexels,
+ };
+}
diff --git a/packages/render-native/src/cycles/bootstrap_main.wgsl b/packages/render-native/src/cycles/bootstrap_main.wgsl
new file mode 100644
index 00000000..1970c06b
--- /dev/null
+++ b/packages/render-native/src/cycles/bootstrap_main.wgsl
@@ -0,0 +1,111 @@
+// Bootstrap entry points used only when `bootstrapKernel: true` is requested while `kernel-manifest.txt` has no
+// compute entry point yet. Never listed in `kernel-manifest.txt`, so zero symbols collide with integrator or closure modules.
+
+@compute @workgroup_size(8, 8, 1)
+fn main(@builtin(global_invocation_id) global_id: vec3<u32>) {
+ if (global_id.x >= kernel_params.image_width || global_id.y >= kernel_params.image_height) {
+ return;
+ }
+ let pixel_index = global_id.y * kernel_params.image_width + global_id.x;
+ let pixel_count = kernel_params.image_width * kernel_params.image_height;
+
+ let uv_x = (2.0 * ((f32(global_id.x) + 0.5) / f32(max(kernel_params.image_width, 1u))) - 1.0) + kernel_params.lens_shift.x * 2.0;
+ let uv_y = (1.0 - 2.0 * ((f32(global_id.y) + 0.5) / f32(max(kernel_params.image_height, 1u)))) + kernel_params.lens_shift.y * 2.0;
+ let ray_direction = normalize(
+ kernel_params.camera_forward + uv_x * kernel_params.camera_right + uv_y * kernel_params.camera_up
+ );
+ let t_min = max(kernel_params.camera_near, kernel_params.ray_epsilon);
+ let t_max = max(kernel_params.camera_far, t_min + 1.0);
+
+ var rq: ray_query;
+ rayQueryInitialize(&rq, scene_tlas, RayDesc(0u, 0x3Fu, t_min, t_max, kernel_params.camera_position, ray_direction));
+ while (rayQueryProceed(&rq)) {
+ let candidate = rayQueryGetCandidateIntersection(&rq);
+ if (candidate.kind == RAY_QUERY_INTERSECTION_TRIANGLE) {
+ let cand_inst = instances[candidate.instance_custom_data];
+ let cand_local = select(0u, cand_inst.opaque_triangle_count, candidate.geometry_index > 0u) + candidate.primitive_index;
+ let cand_tri = triangles[cand_inst.triangle_offset + cand_local];
+ let cand_mat_idx = select(cand_inst.material_override, cand_tri.material_index, cand_inst.material_override == INVALID_INDEX);
+ let cand_mat = materials[cand_mat_idx];
+ var alpha = cand_mat.alpha;
+ if (cand_mat.base_color_tex >= 0 && u32(cand_mat.base_color_tex) < kernel_params.texture_count) {
+ let desc = texture_descriptors[u32(cand_mat.base_color_tex)];
+ let bary_w = 1.0 - candidate.barycentrics.x - candidate.barycentrics.y;
+ let hit_u = fract(bary_w * cand_tri.uv0_u + candidate.barycentrics.x * cand_tri.uv1_u + candidate.barycentrics.y * cand_tri.uv2_u);
+ let hit_v = fract(bary_w * cand_tri.uv0_v + candidate.barycentrics.x * cand_tri.uv1_v + candidate.barycentrics.y * cand_tri.uv2_v);
+ let tex_x = min(u32(max(hit_u, 0.0) * f32(desc.width)), max(desc.width, 1u) - 1u);
+ let tex_y = min(u32(max(hit_v, 0.0) * f32(desc.height)), max(desc.height, 1u) - 1u);
+ let packed_texel = unpack4x8unorm(texture_texels[desc.data_offset + tex_y * desc.width + tex_x]);
+ alpha = alpha * packed_texel.a;
+ }
+ if (cand_mat.alpha_mode != ALPHA_MODE_MASK || alpha >= cand_mat.alpha_cutoff) {
+ rayQueryConfirmIntersection(&rq);
+ }
+ }
+ }
+
+ var sample_radiance = kernel_params.env_color;
+ if (kernel_params.env_width > 0u && kernel_params.env_height > 0u) {
+ sample_radiance = environment_texels[0].rgb * kernel_params.env_color;
+ }
+ var hit_albedo = vec3<f32>(0.0);
+ var hit_normal = vec3<f32>(0.0);
+ var hit_depth = 0.0;
+
+ let committed = rayQueryGetCommittedIntersection(&rq);
+ if (committed.kind != RAY_QUERY_INTERSECTION_NONE) {
+ let inst = instances[committed.instance_custom_data];
+ let local_tri = select(0u, inst.opaque_triangle_count, committed.geometry_index > 0u) + committed.primitive_index;
+ let tri = triangles[inst.triangle_offset + local_tri];
+ let mat_idx = select(inst.material_override, tri.material_index, inst.material_override == INVALID_INDEX);
+ let mat = materials[mat_idx];
+ let bary_w = 1.0 - committed.barycentrics.x - committed.barycentrics.y;
+ let obj_n = normalize(bary_w * tri.n0 + committed.barycentrics.x * tri.n1 + committed.barycentrics.y * tri.n2);
+ var world_n = normalize(
+ obj_n.x * inst.world_to_object_row0.xyz +
+ obj_n.y * inst.world_to_object_row1.xyz +
+ obj_n.z * inst.world_to_object_row2.xyz
+ );
+ if (!committed.front_face && (tri.flags & TRIANGLE_FLAG_DOUBLE_SIDED) != 0u) {
+ world_n = -world_n;
+ }
+ hit_albedo = mat.base_color;
+ hit_normal = world_n;
+ hit_depth = committed.t;
+ sample_radiance = mat.base_color * 0.5 + mat.emission_color * mat.emission_strength;
+ if (kernel_params.light_count > 0u && (lights[0].light_group_mask_lo & inst.light_group_mask_lo) != 0u) {
+ sample_radiance += hit_albedo * lights[0].radiance * 0.01;
+ }
+ if (kernel_params.emissive_triangle_count > 0u) {
+ sample_radiance += emissive_triangles[0].radiance * 0.001;
+ }
+ if (kernel_params.light_tree_node_count > 0u && light_tree_nodes[0].energy < 0.0) {
+ sample_radiance = vec3<f32>(0.0);
+ }
+ }
+
+ let batch = max(kernel_params.samples_per_dispatch, 1u);
+ let batch_f = f32(batch);
+ let lum = dot(sample_radiance, vec3<f32>(0.2126, 0.7152, 0.0722));
+ film_accumulation[pixel_index] += vec4<f32>(sample_radiance * kernel_params.film_exposure * batch_f, hit_depth * batch_f);
+ film_accumulation[pixel_count + pixel_index] += vec4<f32>(hit_albedo * batch_f, 0.0);
+ film_accumulation[2u * pixel_count + pixel_index] += vec4<f32>(hit_normal * batch_f, 0.0);
+ film_accumulation[3u * pixel_count + pixel_index] += vec4<f32>(lum * batch_f, lum * lum * batch_f, 0.0, batch_f);
+}
+
+@compute @workgroup_size(64, 1, 1)
+fn test_lobe_samples(@builtin(global_invocation_id) global_id: vec3<u32>) {
+ let total = kernel_params.image_width * kernel_params.image_height;
+ let idx = global_id.x;
+ if (idx >= total) {
+ return;
+ }
+ let mat = materials[0];
+ let wo = normalize(kernel_params.camera_forward);
+ let front_face = select(0u, 1u, kernel_params.camera_near >= 0.0);
+ let mode = kernel_params.kernel_flags;
+ film_accumulation[idx] = vec4<f32>(mat.base_color, mat.roughness);
+ film_accumulation[total + idx] = vec4<f32>(wo, f32(front_face));
+ film_accumulation[2u * total + idx] = vec4<f32>(mat.f82_tint, f32(mode));
+ film_accumulation[3u * total + idx] = vec4<f32>(f32(kernel_params.seed), mat.ior, mat.metallic, 1.0);
+}
diff --git a/packages/render-native/src/cycles/mod.rs b/packages/render-native/src/cycles/mod.rs
index 50e6348d..287f81c9 100644
--- a/packages/render-native/src/cycles/mod.rs
+++ b/packages/render-native/src/cycles/mod.rs
@@ -3,14 +3,17 @@ use napi::Result;
use crate::host::device::failure;
const KERNEL_MANIFEST_SOURCE: &str = include_str!("kernel-manifest.txt");
+const BOOTSTRAP_MAIN_SOURCE: &str = include_str!("bootstrap_main.wgsl");
include!(concat!(env!("OUT_DIR"), "/cycles_manifest_files.rs"));
-/// Parses `kernel-manifest.txt`, ignoring blank lines and `#` comments, and returns relative WGSL paths in order.
+/// Parses `kernel-manifest.txt`, stripping any UTF-8 BOM and ignoring blank lines and `#` comments, and returns relative WGSL paths in order.
pub(crate) fn parse_kernel_manifest(manifest_text: &str) -> Vec<&str> {
let mut entries = Vec::new();
- for raw_line in manifest_text.lines() {
- let without_comment = raw_line.split('#').next().unwrap_or("");
+ let without_file_bom = manifest_text.trim_start_matches('\u{feff}');
+ for raw_line in without_file_bom.lines() {
+ let without_line_bom = raw_line.trim_start_matches('\u{feff}');
+ let without_comment = without_line_bom.split('#').next().unwrap_or("");
let trimmed = without_comment.trim();
if !trimmed.is_empty() {
entries.push(trimmed);
@@ -61,23 +64,56 @@ fn strip_wgsl_comments(source: &str) -> String {
cleaned
}
-fn has_compute_main_entry_point(shader_source: &str) -> bool {
+fn is_identifier_byte(byte: u8) -> bool {
+ byte.is_ascii_alphanumeric() || byte == b'_'
+}
+
+pub(crate) fn has_compute_entry_point(shader_source: &str, target_entry_point: &str) -> bool {
let uncommented = strip_wgsl_comments(shader_source);
- let mut saw_compute_attribute = false;
- for token in uncommented.split_whitespace() {
- if token.contains("@compute") {
- saw_compute_attribute = true;
+ let bytes = uncommented.as_bytes();
+ let mut index = 0usize;
+ let mut pending_compute = false;
+ let mut awaiting_function_name = false;
+ while index < bytes.len() {
+ if bytes[index] == b'@' {
+ let start = index + 1;
+ let mut end = start;
+ while end < bytes.len() && is_identifier_byte(bytes[end]) {
+ end += 1;
+ }
+ if &uncommented[start..end] == "compute" {
+ pending_compute = true;
+ }
+ index = end;
+ continue;
}
- if saw_compute_attribute && (token == "main" || token.starts_with("main(")) {
- return true;
+ if is_identifier_byte(bytes[index]) {
+ let start = index;
+ let mut end = start + 1;
+ while end < bytes.len() && is_identifier_byte(bytes[end]) {
+ end += 1;
+ }
+ let token = &uncommented[start..end];
+ if awaiting_function_name {
+ if pending_compute && token == target_entry_point {
+ return true;
+ }
+ awaiting_function_name = false;
+ pending_compute = false;
+ } else if token == "fn" {
+ awaiting_function_name = true;
+ }
+ index = end;
+ continue;
}
+ index += 1;
}
false
}
/// Concatenates the WGSL modules listed in `src/cycles/kernel-manifest.txt` in order and verifies a runnable `@compute`
-/// `main` entry point exists before opening a GPU pipeline.
-pub(crate) fn assemble_cycles_kernel() -> Result<String> {
+/// `target_entry_point` exists (appending `bootstrap_main.wgsl` only when `allow_bootstrap` is true and the manifest lacks it).
+pub(crate) fn assemble_cycles_kernel_entry(target_entry_point: &str, allow_bootstrap: bool) -> Result<String> {
let entries = parse_kernel_manifest(KERNEL_MANIFEST_SOURCE);
if entries.is_empty() {
return Err(failure(
@@ -91,17 +127,55 @@ pub(crate) fn assemble_cycles_kernel() -> Result<String> {
.find(|(name, _)| name == entry)
.ok_or_else(|| failure(format!("Cycles kernel manifest entry is not embedded: {entry}")))?;
let module_source = std::str::from_utf8(raw_bytes)
- .map_err(|error| failure(format!("Cycles kernel module {entry} is not valid UTF-8: {error}")))?;
+ .map_err(|error| failure(format!("Cycles kernel module {entry} is not valid UTF-8: {error}")))?
+ .trim_start_matches('\u{feff}');
if !assembled.is_empty() && !assembled.ends_with('\n') {
assembled.push('\n');
}
assembled.push_str(module_source);
}
- if !has_compute_main_entry_point(&assembled) {
- return Err(failure(format!(
- "The Cycles native kernel cannot run yet: src/cycles/kernel-manifest.txt defines no @compute main entry point (assembled modules: {}).",
- entries.join(", ")
- )));
+ if !has_compute_entry_point(&assembled, target_entry_point) {
+ if allow_bootstrap {
+ if !assembled.ends_with('\n') {
+ assembled.push('\n');
+ }
+ assembled.push_str(BOOTSTRAP_MAIN_SOURCE.trim_start_matches('\u{feff}'));
+ }
+ if !has_compute_entry_point(&assembled, target_entry_point) {
+ return Err(failure(format!(
+ "The Cycles native kernel cannot run yet: src/cycles/kernel-manifest.txt defines no @compute {target_entry_point} entry point (assembled modules: {}).",
+ entries.join(", ")
+ )));
+ }
}
Ok(assembled)
}
+
+pub(crate) fn assemble_cycles_kernel() -> Result<String> {
+ assemble_cycles_kernel_entry("main", false)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::{has_compute_entry_point, parse_kernel_manifest};
+
+ #[test]
+ fn parses_manifest_with_utf8_bom_and_comments() {
+ let text = "\u{feff}# header\r\n\u{feff}abi.wgsl # inline comment\r\n closure.wgsl \n\n";
+ assert_eq!(parse_kernel_manifest(text), vec!["abi.wgsl", "closure.wgsl"]);
+ }
+
+ #[test]
+ fn detects_named_compute_entry_points_independently() {
+ let source = r#"
+ // @compute fn main() {}
+ fn helper() {}
+ @compute @workgroup_size(64, 1, 1)
+ fn test_lobe_samples() {}
+ fn not_compute_main() {}
+ "#;
+ assert!(has_compute_entry_point(source, "test_lobe_samples"));
+ assert!(!has_compute_entry_point(source, "main"));
+ assert!(!has_compute_entry_point(source, "helper"));
+ }
+}
diff --git a/packages/render-native/src/host/accel.rs b/packages/render-native/src/host/accel.rs
index 55308571..34f05967 100644
--- a/packages/render-native/src/host/accel.rs
+++ b/packages/render-native/src/host/accel.rs
@@ -1,9 +1,18 @@
+use std::collections::BTreeMap;
+
+use napi::Result;
use wgpu::util::DeviceExt;
+use crate::host::device::failure;
use crate::host::textures::material_is_cutout;
pub(crate) const TRIANGLE_FLOATS: usize = 9 * 4;
+pub(crate) const INSTANCE_RECORD_BYTES: usize = 160;
+pub(crate) const TRIANGLE_RECORD_BYTES: usize = 224;
const VERTEX_STRIDE_BYTES: u64 = 12;
+const IDENTITY_TRANSFORM_3X4: [f32; 12] = [1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0];
+const MAX_TLAS_INSTANCES: usize = 1 << 24;
+const INSTANCE_RAY_VISIBILITY_MASK: u32 = 0x3F;
pub(crate) struct UnpackedTriangles {
pub(crate) vertices: Vec<f32>,
@@ -11,6 +20,41 @@ pub(crate) struct UnpackedTriangles {
pub(crate) opaque_count: usize,
}
+pub(crate) struct CyclesAcceleration {
+ pub(crate) tlas: wgpu::Tlas,
+ pub(crate) _blases: Vec<wgpu::Blas>,
+ pub(crate) _vertex_buffer: wgpu::Buffer,
+}
+
+#[derive(Clone, Copy, PartialEq, Eq)]
+struct BlasSliceSpec {
+ triangle_offset: u32,
+ opaque_triangle_count: u32,
+ total_triangle_count: u32,
+}
+
+struct BlasBuildPlan {
+ blas: wgpu::Blas,
+ geometry_sizes: Vec<wgpu::BlasTriangleGeometrySizeDescriptor>,
+ geometry_vertex_starts: Vec<u32>,
+}
+
+struct ParsedInstancePlacement {
+ transform_row_major_3x4: [f32; 12],
+ blas_plan_index: usize,
+ cull_mask: u8,
+}
+
+fn read_u32_le(bytes: &[u8], offset: usize) -> u32 {
+ let word: [u8; 4] = bytes[offset..offset + 4].try_into().unwrap();
+ u32::from_le_bytes(word)
+}
+
+fn read_f32_le(bytes: &[u8], offset: usize) -> f32 {
+ let word: [u8; 4] = bytes[offset..offset + 4].try_into().unwrap();
+ f32::from_le_bytes(word)
+}
+
/// Unpacks corner-plus-two-edges triangle rows into three 3D corners per triangle, placing opaque triangles before
/// alpha-cutout triangles so each hardware BLAS geometry has a uniform opacity flag.
pub(crate) fn unpack_triangles(triangle_data: &[f32], materials: &[f32], triangle_count: usize) -> UnpackedTriangles {
@@ -97,7 +141,7 @@ pub(crate) fn build_acceleration_structure(
});
tlas[0] = Some(wgpu::TlasInstance::new(
&blas,
- [1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0],
+ IDENTITY_TRANSFORM_3X4,
0,
0xFF,
));
@@ -129,3 +173,265 @@ pub(crate) fn build_acceleration_structure(
let _ = device.poll(wgpu::PollType::wait_indefinitely());
tlas
}
+
+fn unpack_v2_triangle_vertices(triangle_bytes: &[u8], triangle_count: usize) -> Vec<f32> {
+ if triangle_count == 0 {
+ return vec![0.0; 9];
+ }
+ let mut vertices = Vec::with_capacity(triangle_count * 9);
+ for index in 0..triangle_count {
+ let base = index * TRIANGLE_RECORD_BYTES;
+ let p0 = [
+ read_f32_le(triangle_bytes, base),
+ read_f32_le(triangle_bytes, base + 4),
+ read_f32_le(triangle_bytes, base + 8),
+ ];
+ let edge1 = [
+ read_f32_le(triangle_bytes, base + 16),
+ read_f32_le(triangle_bytes, base + 20),
+ read_f32_le(triangle_bytes, base + 24),
+ ];
+ let edge2 = [
+ read_f32_le(triangle_bytes, base + 32),
+ read_f32_le(triangle_bytes, base + 36),
+ read_f32_le(triangle_bytes, base + 40),
+ ];
+ vertices.extend_from_slice(&p0);
+ vertices.extend((0..3).map(|axis| p0[axis] + edge1[axis]));
+ vertices.extend((0..3).map(|axis| p0[axis] + edge2[axis]));
+ }
+ vertices
+}
+
+fn create_blas_plan_for_slice(device: &wgpu::Device, spec: BlasSliceSpec) -> BlasBuildPlan {
+ let opaque_count = spec.opaque_triangle_count as usize;
+ let total_count = spec.total_triangle_count as usize;
+ let cutout_count = total_count - opaque_count;
+ let base_triangle = spec.triangle_offset as usize;
+ let mut geometry_sizes = Vec::new();
+ let mut geometry_vertex_starts = Vec::new();
+ for (local_start, count_in_geometry, flags) in [
+ (0usize, opaque_count, wgpu::AccelerationStructureGeometryFlags::OPAQUE),
+ (opaque_count, cutout_count, wgpu::AccelerationStructureGeometryFlags::empty()),
+ ] {
+ if count_in_geometry == 0 {
+ continue;
+ }
+ geometry_vertex_starts.push(((base_triangle + local_start) * 3) as u32);
+ geometry_sizes.push(wgpu::BlasTriangleGeometrySizeDescriptor {
+ vertex_format: wgpu::VertexFormat::Float32x3,
+ vertex_count: (count_in_geometry * 3) as u32,
+ index_format: None,
+ index_count: None,
+ flags,
+ });
+ }
+ let blas = device.create_blas(
+ &wgpu::CreateBlasDescriptor {
+ label: Some("cycles mesh blas"),
+ flags: wgpu::AccelerationStructureFlags::PREFER_FAST_TRACE,
+ update_mode: wgpu::AccelerationStructureUpdateMode::Build,
+ },
+ wgpu::BlasGeometrySizeDescriptors::Triangles {
+ descriptors: geometry_sizes.clone(),
+ },
+ );
+ BlasBuildPlan {
+ blas,
+ geometry_sizes,
+ geometry_vertex_starts,
+ }
+}
+
+/// Builds an empty masked-out 1-triangle BLAS + TLAS when a scene has zero instances or runs a lobe-only probe.
+pub(crate) fn build_empty_cycles_acceleration(device: &wgpu::Device, queue: &wgpu::Queue) -> CyclesAcceleration {
+ let vertex_buffer = create_vertex_buffer(device, &[0.0f32; 9]);
+ let dummy_plan = create_blas_plan_for_slice(
+ device,
+ BlasSliceSpec {
+ triangle_offset: 0,
+ opaque_triangle_count: 1,
+ total_triangle_count: 1,
+ },
+ );
+ let mut tlas = device.create_tlas(&wgpu::CreateTlasDescriptor {
+ label: Some("cycles empty tlas"),
+ flags: wgpu::AccelerationStructureFlags::PREFER_FAST_TRACE,
+ update_mode: wgpu::AccelerationStructureUpdateMode::Build,
+ max_instances: 1,
+ });
+ tlas[0] = Some(wgpu::TlasInstance::new(&dummy_plan.blas, IDENTITY_TRANSFORM_3X4, 0, 0x00));
+ let triangle_geometries: Vec<wgpu::BlasTriangleGeometry> = dummy_plan
+ .geometry_sizes
+ .iter()
+ .zip(&dummy_plan.geometry_vertex_starts)
+ .map(|(size, first_vertex)| wgpu::BlasTriangleGeometry {
+ size,
+ vertex_buffer: &vertex_buffer,
+ first_vertex: *first_vertex,
+ vertex_stride: VERTEX_STRIDE_BYTES,
+ index_buffer: None,
+ first_index: None,
+ transform_buffer: None,
+ transform_buffer_offset: None,
+ })
+ .collect();
+ let mut build_encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
+ label: Some("cycles empty accel build"),
+ });
+ build_encoder.build_acceleration_structures(
+ std::iter::once(&wgpu::BlasBuildEntry {
+ blas: &dummy_plan.blas,
+ geometry: wgpu::BlasGeometries::TriangleGeometries(triangle_geometries),
+ }),
+ std::iter::once(&tlas),
+ );
+ queue.submit(Some(build_encoder.finish()));
+ let _ = device.poll(wgpu::PollType::wait_indefinitely());
+ CyclesAcceleration {
+ tlas,
+ _blases: vec![dummy_plan.blas],
+ _vertex_buffer: vertex_buffer,
+ }
+}
+
+/// Builds one hardware BLAS per unique `InstanceRecord.blas_index` and one hardware TLAS over all `instance_count` instances.
+pub(crate) fn build_cycles_acceleration_structure(
+ device: &wgpu::Device,
+ queue: &wgpu::Queue,
+ instance_bytes: &[u8],
+ instance_count: usize,
+ triangle_bytes: &[u8],
+ triangle_count: usize,
+) -> Result<CyclesAcceleration> {
+ if instance_count > MAX_TLAS_INSTANCES {
+ return Err(failure(format!(
+ "Instance count {instance_count} exceeds the hardware 24-bit custom index limit ({MAX_TLAS_INSTANCES})."
+ )));
+ }
+ if instance_count == 0 || triangle_count == 0 {
+ return Ok(build_empty_cycles_acceleration(device, queue));
+ }
+
+ let mut blas_lookup: BTreeMap<u32, (usize, BlasSliceSpec)> = BTreeMap::new();
+ let mut blas_specs: Vec<BlasSliceSpec> = Vec::new();
+ let mut placements: Vec<ParsedInstancePlacement> = Vec::with_capacity(instance_count);
+
+ for instance_index in 0..instance_count {
+ let base = instance_index * INSTANCE_RECORD_BYTES;
+ let blas_index = read_u32_le(instance_bytes, base + 96);
+ let triangle_offset = read_u32_le(instance_bytes, base + 100);
+ let opaque_triangle_count = read_u32_le(instance_bytes, base + 104);
+ let total_triangle_count = read_u32_le(instance_bytes, base + 108);
+ let visibility_flags = read_u32_le(instance_bytes, base + 116);
+
+ if total_triangle_count == 0 {
+ return Err(failure(format!(
+ "InstanceRecord[{instance_index}] has total_triangle_count == 0; pass at least 1 triangle per instance."
+ )));
+ }
+ if opaque_triangle_count > total_triangle_count {
+ return Err(failure(format!(
+ "InstanceRecord[{instance_index}] has opaque_triangle_count ({opaque_triangle_count}) > total_triangle_count ({total_triangle_count})."
+ )));
+ }
+ let end_triangle = (triangle_offset as u64) + (total_triangle_count as u64);
+ if end_triangle > triangle_count as u64 {
+ return Err(failure(format!(
+ "InstanceRecord[{instance_index}] triangle range {triangle_offset}..{end_triangle} exceeds triangle_count ({triangle_count})."
+ )));
+ }
+
+ let spec = BlasSliceSpec {
+ triangle_offset,
+ opaque_triangle_count,
+ total_triangle_count,
+ };
+ let blas_plan_index = if let Some(&(existing_index, existing_spec)) = blas_lookup.get(&blas_index) {
+ if existing_spec != spec {
+ return Err(failure(format!(
+ "InstanceRecord[{instance_index}] reuses blas_index {blas_index} with mismatched triangle slice bounds."
+ )));
+ }
+ existing_index
+ } else {
+ let next_index = blas_specs.len();
+ blas_specs.push(spec);
+ blas_lookup.insert(blas_index, (next_index, spec));
+ next_index
+ };
+
+ let mut transform_row_major_3x4 = [0.0f32; 12];
+ for float_index in 0..12 {
+ transform_row_major_3x4[float_index] = read_f32_le(instance_bytes, base + float_index * 4);
+ }
+ let cull_mask = (visibility_flags & INSTANCE_RAY_VISIBILITY_MASK) as u8;
+ placements.push(ParsedInstancePlacement {
+ transform_row_major_3x4,
+ blas_plan_index,
+ cull_mask,
+ });
+ }
+
+ let vertices = unpack_v2_triangle_vertices(triangle_bytes, triangle_count);
+ let vertex_buffer = create_vertex_buffer(device, &vertices);
+ let plans: Vec<BlasBuildPlan> = blas_specs
+ .iter()
+ .map(|spec| create_blas_plan_for_slice(device, *spec))
+ .collect();
+
+ let mut tlas = device.create_tlas(&wgpu::CreateTlasDescriptor {
+ label: Some("cycles scene tlas"),
+ flags: wgpu::AccelerationStructureFlags::PREFER_FAST_TRACE,
+ update_mode: wgpu::AccelerationStructureUpdateMode::Build,
+ max_instances: instance_count as u32,
+ });
+ for (instance_index, placement) in placements.iter().enumerate() {
+ tlas[instance_index] = Some(wgpu::TlasInstance::new(
+ &plans[placement.blas_plan_index].blas,
+ placement.transform_row_major_3x4,
+ instance_index as u32,
+ placement.cull_mask,
+ ));
+ }
+
+ let blas_entries: Vec<wgpu::BlasBuildEntry> = plans
+ .iter()
+ .map(|plan| {
+ let triangle_geometries: Vec<wgpu::BlasTriangleGeometry> = plan
+ .geometry_sizes
+ .iter()
+ .zip(&plan.geometry_vertex_starts)
+ .map(|(size, first_vertex)| wgpu::BlasTriangleGeometry {
+ size,
+ vertex_buffer: &vertex_buffer,
+ first_vertex: *first_vertex,
+ vertex_stride: VERTEX_STRIDE_BYTES,
+ index_buffer: None,
+ first_index: None,
+ transform_buffer: None,
+ transform_buffer_offset: None,
+ })
+ .collect();
+ wgpu::BlasBuildEntry {
+ blas: &plan.blas,
+ geometry: wgpu::BlasGeometries::TriangleGeometries(triangle_geometries),
+ }
+ })
+ .collect();
+
+ let mut build_encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
+ label: Some("cycles accel build"),
+ });
+ build_encoder.build_acceleration_structures(blas_entries.iter(), std::iter::once(&tlas));
+ queue.submit(Some(build_encoder.finish()));
+ let _ = device.poll(wgpu::PollType::wait_indefinitely());
+ drop(blas_entries);
+
+ let blases = plans.into_iter().map(|plan| plan.blas).collect();
+ Ok(CyclesAcceleration {
+ tlas,
+ _blases: blases,
+ _vertex_buffer: vertex_buffer,
+ })
+}
diff --git a/packages/render-native/src/host/session.rs b/packages/render-native/src/host/session.rs
index 2374c87d..cb88ec64 100644
--- a/packages/render-native/src/host/session.rs
+++ b/packages/render-native/src/host/session.rs
@@ -1,14 +1,17 @@
use std::time::Instant;
use napi::Result;
+use wgpu::util::DeviceExt;
use crate::host::accel::{
- build_acceleration_structure, create_vertex_buffer, unpack_triangles, TRIANGLE_FLOATS,
+ build_acceleration_structure, build_cycles_acceleration_structure, build_empty_cycles_acceleration,
+ create_vertex_buffer, unpack_triangles, CyclesAcceleration, INSTANCE_RECORD_BYTES, TRIANGLE_FLOATS,
+ TRIANGLE_RECORD_BYTES,
};
-use crate::host::device::{failure, layout_entry, open_device, storage_entry};
-use crate::host::film::read_accumulation;
-use crate::host::textures::upload_scene_buffers;
-use crate::NativeTraceInput;
+use crate::host::device::{failure, layout_entry, open_device, storage_buffer, storage_entry};
+use crate::host::film::{image_accumulation_bytes, read_accumulation};
+use crate::host::textures::{upload_cycles_scene_buffers, upload_scene_buffers};
+use crate::{NativeTraceInput, NativeTraceInputV2, ProbeCyclesLobeOptions};
const PARAMETER_BYTES: usize = 16 * 16;
const VOLUME_DENSITY_BYTE_OFFSET: usize = 51 * 4;
@@ -16,6 +19,18 @@ const SUBSURFACE_OFFSET_BYTE_OFFSET: usize = 60 * 4;
const SAMPLE_INDEX_BYTE_OFFSET: u64 = 43 * 4;
const SAMPLES_PER_WAIT: u32 = 4;
+const KERNEL_PARAMS_V2_BYTES: usize = 320;
+const FORMAT_V2_MAGIC: u32 = 0x36375054;
+const FORMAT_V2_VERSION: u32 = 2;
+const MATERIAL_RECORD_BYTES: usize = 256;
+const EMISSIVE_TRIANGLE_RECORD_BYTES: usize = 96;
+const LIGHT_RECORD_BYTES: usize = 128;
+const LIGHT_TREE_NODE_BYTES: usize = 64;
+const TEXTURE_DESCRIPTOR_BYTES: usize = 32;
+const CYCLES_SAMPLE_OFFSET_BYTE_OFFSET: u64 = 16;
+const LOBE_PROBE_WORKGROUP_SIZE: u32 = 64;
+const MAX_COMPUTE_WORKGROUPS_PER_DIMENSION: u64 = 65_535;
+
/// A device with the scene's acceleration structure built and one compute pipeline bound to it.
pub(crate) struct PreparedScene {
pub(crate) device: wgpu::Device,
@@ -36,6 +51,24 @@ pub(crate) struct PreparedScene {
pub(crate) _tlas: wgpu::Tlas,
}
+pub(crate) struct PreparedCyclesScene {
+ pub(crate) device: wgpu::Device,
+ pub(crate) queue: wgpu::Queue,
+ pub(crate) pipeline: wgpu::ComputePipeline,
+ pub(crate) bind_group: wgpu::BindGroup,
+ pub(crate) accumulation: wgpu::Buffer,
+ pub(crate) parameters: wgpu::Buffer,
+ pub(crate) adapter_name: String,
+ pub(crate) backend_name: String,
+ pub(crate) features: String,
+ pub(crate) setup_seconds: f64,
+ pub(crate) compile_seconds: f64,
+ pub(crate) upload_seconds: f64,
+ pub(crate) acceleration_build_seconds: f64,
+ pub(crate) _buffers: Vec<wgpu::Buffer>,
+ pub(crate) _acceleration: CyclesAcceleration,
+}
+
/// What one kind of job adds to the shared scene setup: the kernel text, its entry point, the accumulation size and the
/// extra read only buffers bound after the accumulation (bindings 9 and up).
pub(crate) struct JobShape<'a> {
@@ -82,6 +115,26 @@ fn create_bind_group_layout(device: &wgpu::Device, extra_buffer_count: usize) ->
})
}
+fn create_cycles_bind_group_layout(device: &wgpu::Device) -> wgpu::BindGroupLayout {
+ let mut layout_entries = vec![
+ layout_entry(
+ 0,
+ wgpu::BindingType::Buffer {
+ ty: wgpu::BufferBindingType::Uniform,
+ has_dynamic_offset: false,
+ min_binding_size: None,
+ },
+ ),
+ layout_entry(1, wgpu::BindingType::AccelerationStructure { vertex_return: false }),
+ ];
+ layout_entries.extend((2..=10).map(|binding| storage_entry(binding, true)));
+ layout_entries.push(storage_entry(11, false));
+ device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
+ label: Some("cycles path tracer"),
+ entries: &layout_entries,
+ })
+}
+
fn compile_compute_pipeline(
device: &wgpu::Device,
shader_source: String,
@@ -147,6 +200,35 @@ fn create_scene_bind_group(
})
}
+fn create_cycles_bind_group(
+ device: &wgpu::Device,
+ bind_group_layout: &wgpu::BindGroupLayout,
+ parameters: &wgpu::Buffer,
+ tlas: &wgpu::Tlas,
+ buffers: &[wgpu::Buffer],
+ accumulation: &wgpu::Buffer,
+) -> wgpu::BindGroup {
+ let mut entries = vec![
+ wgpu::BindGroupEntry { binding: 0, resource: parameters.as_entire_binding() },
+ wgpu::BindGroupEntry { binding: 1, resource: tlas.as_binding() },
+ ];
+ for (offset, buffer) in buffers.iter().enumerate() {
+ entries.push(wgpu::BindGroupEntry {
+ binding: 2 + offset as u32,
+ resource: buffer.as_entire_binding(),
+ });
+ }
+ entries.push(wgpu::BindGroupEntry {
+ binding: 11,
+ resource: accumulation.as_entire_binding(),
+ });
+ device.create_bind_group(&wgpu::BindGroupDescriptor {
+ label: Some("cycles path tracer"),
+ layout: bind_group_layout,
+ entries: &entries,
+ })
+}
+
pub(crate) fn prepare_scene(input: &NativeTraceInput, shape: JobShape) -> Result<PreparedScene> {
let setup_started = Instant::now();
let triangle_count = input.triangle_count as usize;
@@ -259,3 +341,290 @@ pub(crate) fn trace_samples(
let sums = read_accumulation(device, queue, &prepared.accumulation, accumulation_bytes)?;
Ok((sums, trace_started.elapsed().as_secs_f64()))
}
+
+fn validate_kernel_params_v2(parameter_bytes: &[u8]) -> Result<()> {
+ if parameter_bytes.len() != KERNEL_PARAMS_V2_BYTES {
+ return Err(failure(format!(
+ "KernelParamsV2 must be {KERNEL_PARAMS_V2_BYTES} bytes, got {}.",
+ parameter_bytes.len()
+ )));
+ }
+ let magic = u32::from_le_bytes(parameter_bytes[0..4].try_into().unwrap());
+ if magic != FORMAT_V2_MAGIC {
+ return Err(failure(format!(
+ "Invalid KernelParamsV2 magic 0x{magic:08x}: expected 0x{FORMAT_V2_MAGIC:08x}."
+ )));
+ }
+ let version = u32::from_le_bytes(parameter_bytes[4..8].try_into().unwrap());
+ if version != FORMAT_V2_VERSION {
+ return Err(failure(format!(
+ "Unsupported KernelParamsV2 format_version {version}: expected {FORMAT_V2_VERSION}."
+ )));
+ }
+ Ok(())
+}
+
+fn validate_record_buffer(label: &str, bytes: &[u8], count: u32, stride: usize) -> Result<()> {
+ let minimum_bytes = (count.max(1) as usize) * stride;
+ if bytes.len() < minimum_bytes || bytes.len() % stride != 0 {
+ return Err(failure(format!(
+ "FORMAT-v2 {label} buffer must be a multiple of {stride} bytes and at least {minimum_bytes} bytes for count {count}, got {} bytes.",
+ bytes.len()
+ )));
+ }
+ Ok(())
+}
+
+pub(crate) fn prepare_cycles_scene(
+ input: &NativeTraceInputV2,
+ shader_source: String,
+ width: u32,
+ height: u32,
+ total_samples: u32,
+ accumulation_bytes: u64,
+) -> Result<PreparedCyclesScene> {
+ let setup_started = Instant::now();
+ if width == 0 || height == 0 {
+ return Err(failure("Trace width and height must both be >= 1."));
+ }
+ if total_samples == 0 {
+ return Err(failure("Trace samples must be >= 1."));
+ }
+ if input.schema_version != FORMAT_V2_VERSION {
+ return Err(failure(format!(
+ "Invalid FORMAT-v2 input schemaVersion {}: expected {FORMAT_V2_VERSION}.",
+ input.schema_version
+ )));
+ }
+ validate_kernel_params_v2(&input.kernel_params)?;
+ validate_record_buffer("instances", &input.instances, input.instance_count, INSTANCE_RECORD_BYTES)?;
+ validate_record_buffer("triangles", &input.triangles, input.triangle_count, TRIANGLE_RECORD_BYTES)?;
+ validate_record_buffer("materials", &input.materials, input.material_count, MATERIAL_RECORD_BYTES)?;
+ validate_record_buffer(
+ "emissiveTriangles",
+ &input.emissive_triangles,
+ input.emissive_triangle_count,
+ EMISSIVE_TRIANGLE_RECORD_BYTES,
+ )?;
+ validate_record_buffer("lights", &input.lights, input.light_count, LIGHT_RECORD_BYTES)?;
+ validate_record_buffer(
+ "lightTreeNodes",
+ &input.light_tree_nodes,
+ input.light_tree_node_count,
+ LIGHT_TREE_NODE_BYTES,
+ )?;
+ validate_record_buffer(
+ "textureDescriptors",
+ &input.texture_descriptors,
+ input.texture_count,
+ TEXTURE_DESCRIPTOR_BYTES,
+ )?;
+
+ let (device, queue, adapter_info) = open_device()?;
+ let setup_seconds = setup_started.elapsed().as_secs_f64();
+
+ let compile_started = Instant::now();
+ let bind_group_layout = create_cycles_bind_group_layout(&device);
+ let pipeline = compile_compute_pipeline(&device, shader_source, "main", &bind_group_layout)?;
+ let compile_seconds = compile_started.elapsed().as_secs_f64();
+
+ let upload_started = Instant::now();
+ let uploaded = upload_cycles_scene_buffers(&device, input, width, height, total_samples, accumulation_bytes);
+ let upload_seconds = upload_started.elapsed().as_secs_f64();
+
+ let build_started = Instant::now();
+ let acceleration = build_cycles_acceleration_structure(
+ &device,
+ &queue,
+ &input.instances,
+ input.instance_count as usize,
+ &input.triangles,
+ input.triangle_count as usize,
+ )?;
+ let acceleration_build_seconds = build_started.elapsed().as_secs_f64();
+
+ let bind_group = create_cycles_bind_group(
+ &device,
+ &bind_group_layout,
+ &uploaded.parameters,
+ &acceleration.tlas,
+ &uploaded.buffers,
+ &uploaded.accumulation,
+ );
+ let has_ray_query = device.features().contains(wgpu::Features::EXPERIMENTAL_RAY_QUERY);
+ let features = if has_ray_query { "EXPERIMENTAL_RAY_QUERY" } else { "" };
+ Ok(PreparedCyclesScene {
+ device,
+ queue,
+ pipeline,
+ bind_group,
+ accumulation: uploaded.accumulation,
+ parameters: uploaded.parameters,
+ adapter_name: adapter_info.name,
+ backend_name: format!("{:?}", adapter_info.backend),
+ features: features.to_string(),
+ setup_seconds,
+ compile_seconds,
+ upload_seconds,
+ acceleration_build_seconds,
+ _buffers: uploaded.buffers,
+ _acceleration: acceleration,
+ })
+}
+
+pub(crate) fn trace_cycles_samples(
+ prepared: &PreparedCyclesScene,
+ samples: u32,
+ samples_per_dispatch: u32,
+ groups: (u32, u32),
+ accumulation_bytes: u64,
+ max_seconds: Option<f64>,
+) -> Result<(Vec<f32>, f64)> {
+ let trace_started = Instant::now();
+ let device = &prepared.device;
+ let queue = &prepared.queue;
+ let step = samples_per_dispatch.max(1);
+ let mut sample_offset = 0u32;
+ let mut dispatch_count = 0u32;
+
+ while sample_offset < samples {
+ let batch_samples = (samples - sample_offset).min(step);
+ let mut dispatch_words = [0u8; 8];
+ dispatch_words[0..4].copy_from_slice(&sample_offset.to_le_bytes());
+ dispatch_words[4..8].copy_from_slice(&batch_samples.to_le_bytes());
+ queue.write_buffer(&prepared.parameters, CYCLES_SAMPLE_OFFSET_BYTE_OFFSET, &dispatch_words);
+
+ let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
+ label: Some("cycles sample batch"),
+ });
+ {
+ let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
+ label: None,
+ timestamp_writes: None,
+ });
+ pass.set_pipeline(&prepared.pipeline);
+ pass.set_bind_group(0, &prepared.bind_group, &[]);
+ pass.dispatch_workgroups(groups.0, groups.1, 1);
+ }
+ queue.submit(Some(encoder.finish()));
+
+ sample_offset += batch_samples;
+ dispatch_count += 1;
+ if dispatch_count % SAMPLES_PER_WAIT == 0 || sample_offset >= samples {
+ let _ = device.poll(wgpu::PollType::wait_indefinitely());
+ if let Some(limit) = max_seconds {
+ if trace_started.elapsed().as_secs_f64() > limit {
+ return Err(failure(format!(
+ "The native trace passed its time limit of {limit} s after {sample_offset} of {samples} samples."
+ )));
+ }
+ }
+ }
+ }
+
+ let sums = read_accumulation(device, queue, &prepared.accumulation, accumulation_bytes)?;
+ Ok((sums, trace_started.elapsed().as_secs_f64()))
+}
+
+pub(crate) fn run_cycles_lobe_probe(options: &ProbeCyclesLobeOptions, shader_source: String) -> Result<Vec<f32>> {
+ if options.width == 0 || options.height == 0 {
+ return Err(failure("probeCyclesLobe width and height must both be >= 1."));
+ }
+ let total_invocations = (options.width as u64) * (options.height as u64);
+ let groups_x = total_invocations.div_ceil(LOBE_PROBE_WORKGROUP_SIZE as u64);
+ if groups_x > MAX_COMPUTE_WORKGROUPS_PER_DIMENSION {
+ return Err(failure(format!(
+ "probeCyclesLobe dispatch requires {groups_x} workgroups in X, exceeding WebGPU/Vulkan limit {MAX_COMPUTE_WORKGROUPS_PER_DIMENSION}."
+ )));
+ }
+ validate_kernel_params_v2(&options.kernel_params)?;
+ if options.materials.len() < MATERIAL_RECORD_BYTES || options.materials.len() % MATERIAL_RECORD_BYTES != 0 {
+ return Err(failure(format!(
+ "probeCyclesLobe materials buffer must be a positive multiple of {MATERIAL_RECORD_BYTES} bytes, got {} bytes.",
+ options.materials.len()
+ )));
+ }
+ if let Some(ref descriptors) = options.texture_descriptors {
+ if descriptors.is_empty() || descriptors.len() % TEXTURE_DESCRIPTOR_BYTES != 0 {
+ return Err(failure(format!(
+ "probeCyclesLobe textureDescriptors must be a positive multiple of {TEXTURE_DESCRIPTOR_BYTES} bytes, got {} bytes.",
+ descriptors.len()
+ )));
+ }
+ }
+
+ let (device, queue, _) = open_device()?;
+ let bind_group_layout = create_cycles_bind_group_layout(&device);
+ let pipeline = compile_compute_pipeline(&device, shader_source, "test_lobe_samples", &bind_group_layout)?;
+ let acceleration = build_empty_cycles_acceleration(&device, &queue);
+ let accumulation_bytes = image_accumulation_bytes(options.width, options.height);
+
+ let mut parameter_bytes = options.kernel_params.to_vec();
+ parameter_bytes[8..12].copy_from_slice(&options.width.to_le_bytes());
+ parameter_bytes[12..16].copy_from_slice(&options.height.to_le_bytes());
+
+ let parameters = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
+ label: Some("lobe probe params"),
+ contents: &parameter_bytes,
+ usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
+ });
+ let default_descriptors = [0u8; TEXTURE_DESCRIPTOR_BYTES];
+ let descriptor_slice: &[u8] = match options.texture_descriptors {
+ Some(ref bytes) => bytes,
+ None => &default_descriptors,
+ };
+ let default_texels = [0u32; 4];
+ let texel_slice: &[u32] = match options.texture_texels {
+ Some(ref words) if !words.is_empty() => words,
+ _ => &default_texels,
+ };
+ let buffers = vec![
+ storage_buffer(&device, "dummy instances", &[0u8; INSTANCE_RECORD_BYTES]),
+ storage_buffer(&device, "dummy triangles", &[0u8; TRIANGLE_RECORD_BYTES]),
+ storage_buffer(&device, "probe materials", &options.materials),
+ storage_buffer(&device, "dummy emissive triangles", &[0u8; EMISSIVE_TRIANGLE_RECORD_BYTES]),
+ storage_buffer(&device, "dummy lights", &[0u8; LIGHT_RECORD_BYTES]),
+ storage_buffer(&device, "dummy light tree", &[0u8; LIGHT_TREE_NODE_BYTES]),
+ storage_buffer(&device, "probe texture descriptors", descriptor_slice),
+ storage_buffer(&device, "probe texture texels", bytemuck::cast_slice(texel_slice)),
+ storage_buffer(&device, "dummy environment texels", &[0u8; 16]),
+ ];
+ let accumulation = device.create_buffer(&wgpu::BufferDescriptor {
+ label: Some("lobe probe accumulation"),
+ size: accumulation_bytes,
+ usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC,
+ mapped_at_creation: false,
+ });
+ let bind_group = create_cycles_bind_group(
+ &device,
+ &bind_group_layout,
+ &parameters,
+ &acceleration.tlas,
+ &buffers,
+ &accumulation,
+ );
+
+ let started = Instant::now();
+ let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
+ label: Some("lobe probe dispatch"),
+ });
+ {
+ let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
+ label: None,
+ timestamp_writes: None,
+ });
+ pass.set_pipeline(&pipeline);
+ pass.set_bind_group(0, &bind_group, &[]);
+ pass.dispatch_workgroups(groups_x as u32, 1, 1);
+ }
+ queue.submit(Some(encoder.finish()));
+ let _ = device.poll(wgpu::PollType::wait_indefinitely());
+ if let Some(limit) = options.max_seconds {
+ if started.elapsed().as_secs_f64() > limit {
+ return Err(failure(format!(
+ "probeCyclesLobe passed its time limit of {limit} s."
+ )));
+ }
+ }
+ read_accumulation(&device, &queue, &accumulation, accumulation_bytes)
+}
diff --git a/packages/render-native/src/host/textures.rs b/packages/render-native/src/host/textures.rs
index 98b67e83..6613aee7 100644
--- a/packages/render-native/src/host/textures.rs
+++ b/packages/render-native/src/host/textures.rs
@@ -1,7 +1,7 @@
use wgpu::util::DeviceExt;
use crate::host::device::storage_buffer;
-use crate::NativeTraceInput;
+use crate::{NativeTraceInput, NativeTraceInputV2};
const MATERIAL_TEXELS: usize = 10;
const CUTOUT_START_WORD_INDEX: usize = 47;
@@ -67,3 +67,46 @@ pub(crate) fn upload_scene_buffers(
parameters,
}
}
+
+pub(crate) fn upload_cycles_scene_buffers(
+ device: &wgpu::Device,
+ input: &NativeTraceInputV2,
+ width: u32,
+ height: u32,
+ total_samples: u32,
+ accumulation_bytes: u64,
+) -> UploadedSceneBuffers {
+ let mut parameter_bytes = input.kernel_params.to_vec();
+ parameter_bytes[8..12].copy_from_slice(&width.to_le_bytes());
+ parameter_bytes[12..16].copy_from_slice(&height.to_le_bytes());
+ parameter_bytes[24..28].copy_from_slice(&total_samples.to_le_bytes());
+
+ // Bindings 2..=10 in FORMAT-v2 order.
+ let buffers = vec![
+ storage_buffer(device, "cycles instances", &input.instances),
+ storage_buffer(device, "cycles triangles", &input.triangles),
+ storage_buffer(device, "cycles materials", &input.materials),
+ storage_buffer(device, "cycles emissive triangles", &input.emissive_triangles),
+ storage_buffer(device, "cycles lights", &input.lights),
+ storage_buffer(device, "cycles light tree nodes", &input.light_tree_nodes),
+ storage_buffer(device, "cycles texture descriptors", &input.texture_descriptors),
+ storage_buffer(device, "cycles texture texels", bytemuck::cast_slice(&input.texture_texels)),
+ storage_buffer(device, "cycles environment texels", bytemuck::cast_slice(&input.environment_texels)),
+ ];
+ let accumulation = device.create_buffer(&wgpu::BufferDescriptor {
+ label: Some("cycles film accumulation"),
+ size: accumulation_bytes,
+ usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC,
+ mapped_at_creation: false,
+ });
+ let parameters = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
+ label: Some("cycles kernel params"),
+ contents: &parameter_bytes,
+ usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
+ });
+ UploadedSceneBuffers {
+ buffers,
+ accumulation,
+ parameters,
+ }
+}
diff --git a/packages/render-native/src/lib.rs b/packages/render-native/src/lib.rs
index abbb05a5..ed3c6693 100644
--- a/packages/render-native/src/lib.rs
+++ b/packages/render-native/src/lib.rs
@@ -13,7 +13,9 @@ use crate::host::film::{
image_accumulation_bytes, image_workgroups, pad_texel_vectors, resolve_image, resolve_texels,
texel_accumulation_bytes, texel_workgroups,
};
-use crate::host::session::{prepare_scene, trace_samples, JobShape};
+use crate::host::session::{
+ prepare_cycles_scene, prepare_scene, run_cycles_lobe_probe, trace_cycles_samples, trace_samples, JobShape,
+};
const KERNEL_SOURCE: &str = include_str!("kernel.wgsl");
/// The texel entry point of the light bake, appended to the kernel for a bake only.
@@ -35,6 +37,28 @@ pub struct NativeTraceInput {
pub parameters: Uint8Array,
}
+#[napi(object)]
+pub struct NativeTraceInputV2 {
+ pub schema_version: u32,
+ pub kernel_params: Uint8Array,
+ pub instances: Uint8Array,
+ pub instance_count: u32,
+ pub triangles: Uint8Array,
+ pub triangle_count: u32,
+ pub materials: Uint8Array,
+ pub material_count: u32,
+ pub emissive_triangles: Uint8Array,
+ pub emissive_triangle_count: u32,
+ pub lights: Uint8Array,
+ pub light_count: u32,
+ pub light_tree_nodes: Uint8Array,
+ pub light_tree_node_count: u32,
+ pub texture_descriptors: Uint8Array,
+ pub texture_count: u32,
+ pub texture_texels: Uint32Array,
+ pub environment_texels: Float32Array,
+}
+
#[napi(object)]
pub struct NativeTraceOptions {
pub width: u32,
@@ -46,6 +70,28 @@ pub struct NativeTraceOptions {
pub kernel: Option<String>,
}
+#[napi(object)]
+pub struct NativeCyclesTraceOptions {
+ pub width: u32,
+ pub height: u32,
+ pub samples: u32,
+ pub samples_per_dispatch: Option<u32>,
+ pub max_seconds: Option<f64>,
+ pub bootstrap_kernel: Option<bool>,
+}
+
+#[napi(object)]
+pub struct ProbeCyclesLobeOptions {
+ pub width: u32,
+ pub height: u32,
+ pub kernel_params: Uint8Array,
+ pub materials: Uint8Array,
+ pub texture_descriptors: Option<Uint8Array>,
+ pub texture_texels: Option<Uint32Array>,
+ pub max_seconds: Option<f64>,
+ pub bootstrap_kernel: Option<bool>,
+}
+
#[napi(object)]
pub struct NativeTexels {
/// How many lightmap texels the two lists hold.
@@ -109,8 +155,10 @@ fn select_kernel_source(requested_kernel: Option<&str>) -> Result<(String, bool)
match kernel_name {
"legacy" => Ok((KERNEL_SOURCE.to_string(), true)),
"cycles" => {
- let source = cycles::assemble_cycles_kernel()?;
- Ok((source, false))
+ let _ = cycles::assemble_cycles_kernel()?;
+ Err(failure(
+ "traceScene requires FORMAT-v2 buffers when kernel is \"cycles\"; call traceNative or traceSceneCycles.",
+ ))
}
other => Err(failure(format!(
"Invalid native kernel {other:?}: pass \"legacy\" or \"cycles\" in options.kernel or JS67_NATIVE_KERNEL."
@@ -118,7 +166,7 @@ fn select_kernel_source(requested_kernel: Option<&str>) -> Result<(String, bool)
}
}
-/// Traces the packed scene on the GPU with hardware ray queries.
+/// Traces the packed legacy v1 scene on the GPU with hardware ray queries.
#[napi]
pub fn trace_scene(input: NativeTraceInput, options: NativeTraceOptions) -> Result<NativeTraceResult> {
let (source, rewrite_specialization_flags) = select_kernel_source(options.kernel.as_deref())?;
@@ -155,6 +203,60 @@ pub fn trace_scene(input: NativeTraceInput, options: NativeTraceOptions) -> Resu
})
}
+/// Traces a packed `FORMAT-v2` scene on the GPU using the assembled Cycles-parity WGSL kernel.
+#[napi]
+pub fn trace_scene_cycles(input: NativeTraceInputV2, options: NativeCyclesTraceOptions) -> Result<NativeTraceResult> {
+ let source = cycles::assemble_cycles_kernel_entry("main", options.bootstrap_kernel.unwrap_or(false))?;
+ let pixel_count = options.width as u64 * options.height as u64;
+ let accumulation_bytes = image_accumulation_bytes(options.width, options.height);
+ let prepared = prepare_cycles_scene(
+ &input,
+ source,
+ options.width,
+ options.height,
+ options.samples,
+ accumulation_bytes,
+ )?;
+ let groups = image_workgroups(options.width, options.height);
+ let samples_per_dispatch = options.samples_per_dispatch.unwrap_or(1).max(1);
+ let (sums, traced_seconds) = trace_cycles_samples(
+ &prepared,
+ options.samples,
+ samples_per_dispatch,
+ groups,
+ accumulation_bytes,
+ options.max_seconds,
+ )?;
+ let resolved = resolve_image(&sums, pixel_count);
+ Ok(NativeTraceResult {
+ rgba: Float32Array::new(resolved.rgba),
+ albedo: Float32Array::new(resolved.albedo),
+ normal: Float32Array::new(resolved.normal),
+ depth: Float32Array::new(resolved.depth),
+ variance: Float32Array::new(resolved.variance),
+ average_samples: resolved.average_samples,
+ adapter: prepared.adapter_name,
+ backend: prepared.backend_name,
+ features: prepared.features,
+ setup_seconds: prepared.setup_seconds,
+ compile_seconds: prepared.compile_seconds,
+ upload_seconds: prepared.upload_seconds,
+ acceleration_build_seconds: prepared.acceleration_build_seconds,
+ traced_seconds,
+ })
+}
+
+/// Dispatches `"test_lobe_samples"` on the assembled Cycles WGSL shader and returns all 4 raw `film_accumulation` planes.
+#[napi]
+pub fn probe_cycles_lobe(options: ProbeCyclesLobeOptions) -> Result<Float32Array> {
+ let source = cycles::assemble_cycles_kernel_entry(
+ "test_lobe_samples",
+ options.bootstrap_kernel.unwrap_or(false),
+ )?;
+ let raw_planes = run_cycles_lobe_probe(&options, source)?;
+ Ok(Float32Array::new(raw_planes))
+}
+
/// The light that reaches each lightmap texel: `options.samples` cosine weighted paths from every texel, traced with the
/// scene's ray queries. The parameter block of `input` carries the lights, the bounces and the seed; its texel count and
/// sample count words are the ones `buildNativeTexelInput` writes.
diff --git a/tests/native-pack-v2.test.js b/tests/native-pack-v2.test.js
new file mode 100644
index 00000000..8c729112
--- /dev/null
+++ b/tests/native-pack-v2.test.js
@@ -0,0 +1,555 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import {
+ FORMAT_V2_MAGIC,
+ FORMAT_V2_VERSION,
+ STRUCT_STRIDES_V2,
+ buildNativeInput,
+ buildNativeInputV2,
+ findNativeAddon,
+ packMaterialRecordV2,
+ probeCyclesLobe,
+ traceNative,
+ upgradeNativeInputV1ToV2,
+} from '../packages/render-native/index.mjs';
+import { createEnvironmentMap } from '../src/hdri.js';
+import { createCamera } from '../src/path-tracer.js';
+import * as pack from '../src/path-tracer-gpu-pack.js';
+import { buildTraceScene } from '../src/path-tracer-scene.js';
+
+function quadGeometry(z = 0) {
+ return {
+ positions: new Float32Array([
+ -1, -1, z,
+ 1, -1, z,
+ 1, 1, z,
+ -1, 1, z,
+ ]),
+ normals: new Float32Array([
+ 0, 0, 1,
+ 0, 0, 1,
+ 0, 0, 1,
+ 0, 0, 1,
+ ]),
+ uvs: new Float32Array([
+ 0, 1,
+ 1, 1,
+ 1, 0,
+ 0, 0,
+ ]),
+ colors: new Float32Array([
+ 1, 1, 1,
+ 1, 1, 1,
+ 1, 1, 1,
+ 1, 1, 1,
+ ]),
+ indices: new Uint32Array([0, 1, 2, 0, 2, 3]),
+ };
+}
+
+function makeCheckerRgba8(width = 4, height = 4, cutoutLeftHalf = false) {
+ const data = new Uint8Array(width * height * 4);
+ for (let y = 0; y < height; y++) {
+ for (let x = 0; x < width; x++) {
+ const idx = (y * width + x) * 4;
+ const bright = (x + y) % 2 === 0;
+ data[idx] = bright ? 240 : 60;
+ data[idx + 1] = bright ? 180 : 40;
+ data[idx + 2] = bright ? 100 : 20;
+ data[idx + 3] = cutoutLeftHalf && x < width / 2 ? 0 : 255;
+ }
+ }
+ return { width, height, data };
+}
+
+function viewRecord(bytes, stride, index = 0) {
+ const offset = bytes.byteOffset + index * stride;
+ return {
+ f32: new Float32Array(bytes.buffer, offset, stride / 4),
+ u32: new Uint32Array(bytes.buffer, offset, stride / 4),
+ i32: new Int32Array(bytes.buffer, offset, stride / 4),
+ };
+}
+
+test('buildNativeInputV2 packs empty-emitter scene with valid FORMAT-v2 headers and non-empty dummy tables', () => {
+ const parts = [{ name: 'card', geometry: quadGeometry(0), material: { color: [0.6, 0.5, 0.4], roughness: 0.7 } }];
+ const scene = buildTraceScene(parts, {});
+ const camera = createCamera({ eye: [0, 0, 4], target: [0, 0, 0], fov: 45 }, 32, 16);
+ const v2 = buildNativeInputV2(scene, camera, { width: 32, height: 16, samples: 8, bounces: 6, seed: 99 });
+
+ assert.equal(v2.schemaVersion, 2);
+ assert.equal(v2.kernelParams.byteLength, STRUCT_STRIDES_V2.kernelParams);
+ assert.equal(v2.instanceCount, 1);
+ assert.equal(v2.triangleCount, 2);
+ assert.equal(v2.materialCount, 1);
+ assert.equal(v2.emissiveTriangleCount, 0);
+ assert.equal(v2.lightCount, 0);
+ assert.equal(v2.lightTreeNodeCount, 0);
+ assert.equal(v2.textureCount, 0);
+
+ // Dummy buffers stay >= 16 B and exact stride multiples so storage bindings 2..10 always validate.
+ assert.equal(v2.emissiveTriangles.byteLength, STRUCT_STRIDES_V2.emissiveTriangle);
+ assert.equal(v2.lights.byteLength, STRUCT_STRIDES_V2.light);
+ assert.equal(v2.lightTreeNodes.byteLength, STRUCT_STRIDES_V2.lightTreeNode);
+ assert.equal(v2.textureDescriptors.byteLength, STRUCT_STRIDES_V2.textureDescriptor);
+ assert.ok(v2.textureTexels.byteLength >= 16);
+ assert.ok(v2.environmentTexels.byteLength >= 16);
+
+ const kp = viewRecord(v2.kernelParams, STRUCT_STRIDES_V2.kernelParams);
+ assert.equal(kp.u32[0], FORMAT_V2_MAGIC);
+ assert.equal(kp.u32[1], FORMAT_V2_VERSION);
+ assert.equal(kp.u32[2], 32);
+ assert.equal(kp.u32[3], 16);
+ assert.equal(kp.u32[6], 8);
+ assert.equal(kp.u32[7], 99);
+ assert.equal(kp.f32[10], 0);
+ assert.equal(kp.f32[11], 0);
+ assert.equal(kp.u32[12], 6);
+ assert.equal(kp.u32[21], 1);
+ assert.equal(kp.u32[22], 2);
+ assert.equal(kp.u32[23], 1);
+ assert.equal(kp.u32[24], 0);
+ assert.equal(kp.u32[25], 0);
+ assert.equal(kp.u32[26], 0);
+ assert.equal(kp.u32[27], 0);
+});
+
+test('buildNativeInputV2 deduplicates shared mesh BLASes, inverts 3x4 transforms, and handles negative-scale instances', () => {
+ const sharedMesh = quadGeometry(0);
+ const camera = createCamera({ eye: [0, 0, 6], target: [0, 0, 0], fov: 50 }, 16, 16);
+ const cosA = Math.cos(0.4);
+ const sinA = Math.sin(0.4);
+ // Column-major 4x4: rotation around Z + non-uniform scale (2, 0.5, 1.5) + translation (3, -2, 1).
+ const positiveTransform = [
+ 2 * cosA, 2 * sinA, 0, 0,
+ -0.5 * sinA, 0.5 * cosA, 0, 0,
+ 0, 0, 1.5, 0,
+ 3, -2, 1, 1,
+ ];
+ // Mirrored across X (det < 0) with translation (-2, 1, -0.5).
+ const mirroredTransform = [
+ -1, 0, 0, 0,
+ 0, 1, 0, 0,
+ 0, 0, 1, 0,
+ -2, 1, -0.5, 1,
+ ];
+
+ const v2 = buildNativeInputV2(
+ {
+ materials: [
+ { color: [0.8, 0.2, 0.2], roughness: 0.4 },
+ { color: [1, 0.9, 0.7], emission: 5, roughness: 0.8 },
+ ],
+ instances: [
+ { geometry: sharedMesh, matrix: positiveTransform, materialIndex: 0 },
+ { geometry: sharedMesh, matrix: mirroredTransform, materialOverride: 1, lightMask: 0b101 },
+ ],
+ lights: {},
+ },
+ camera,
+ { width: 16, height: 16, samples: 1 },
+ );
+
+ assert.equal(v2.instanceCount, 2);
+ assert.equal(v2.triangleCount, 2, 'shared geometry must pack once into triangles');
+ assert.equal(v2.emissiveTriangleCount, 2, 'emissive override instance emits 2 world-space emissive triangles');
+
+ const inst0 = viewRecord(v2.instances, STRUCT_STRIDES_V2.instance, 0);
+ const inst1 = viewRecord(v2.instances, STRUCT_STRIDES_V2.instance, 1);
+ assert.equal(inst0.u32[24], 0, 'inst0 blas_index');
+ assert.equal(inst1.u32[24], 0, 'inst1 shares blas_index 0');
+ assert.equal(inst0.u32[29] & 64, 0, 'positive-det instance clears NEGATIVE_SCALE');
+ assert.equal(inst1.u32[29] & 64, 64, 'negative-det instance sets INSTANCE_FLAG_NEGATIVE_SCALE (64)');
+ assert.equal(inst1.u32[28], 1, 'inst1 material_override');
+ assert.equal(inst1.u32[30], 0b101, 'inst1 light_group_mask_lo');
+ assert.equal(inst0.u32[32], 0xffffffff, 'non-emissive inst0 emissive_base_offset');
+ assert.equal(inst1.u32[32], 0, 'emissive inst1 emissive_base_offset');
+
+ // Verify world_to_object * object_to_world == identity on arbitrary point p = [0.7, -1.3, 2.1].
+ const p = [0.7, -1.3, 2.1];
+ const o2w = inst0.f32.subarray(0, 12);
+ const w2o = inst0.f32.subarray(12, 24);
+ const worldP = [
+ o2w[0] * p[0] + o2w[1] * p[1] + o2w[2] * p[2] + o2w[3],
+ o2w[4] * p[0] + o2w[5] * p[1] + o2w[6] * p[2] + o2w[7],
+ o2w[8] * p[0] + o2w[9] * p[1] + o2w[10] * p[2] + o2w[11],
+ ];
+ const roundTripP = [
+ w2o[0] * worldP[0] + w2o[1] * worldP[1] + w2o[2] * worldP[2] + w2o[3],
+ w2o[4] * worldP[0] + w2o[5] * worldP[1] + w2o[6] * worldP[2] + w2o[7],
+ w2o[8] * worldP[0] + w2o[9] * worldP[1] + w2o[10] * worldP[2] + w2o[11],
+ ];
+ for (let axis = 0; axis < 3; axis++) {
+ assert.ok(Math.abs(roundTripP[axis] - p[axis]) < 1e-5, `axis ${axis} round-trip mismatch`);
+ }
+
+ // Mirrored quad across X originally faced +Z; true outward normal after X-mirror still faces +Z!
+ const em0 = viewRecord(v2.emissiveTriangles, STRUCT_STRIDES_V2.emissiveTriangle, 0);
+ assert.ok(Math.abs(em0.f32[12]) < 1e-6);
+ assert.ok(Math.abs(em0.f32[13]) < 1e-6);
+ assert.ok(Math.abs(em0.f32[14] - 1.0) < 1e-6, 'mirrored emissive geometric_normal stays +Z');
+ const em1 = viewRecord(v2.emissiveTriangles, STRUCT_STRIDES_V2.emissiveTriangle, 1);
+ assert.equal(em1.f32[21], 1.0, 'emissive CDF ends at 1.0');
+
+ const tri0 = viewRecord(v2.triangles, STRUCT_STRIDES_V2.triangle, 0);
+ const tri1 = viewRecord(v2.triangles, STRUCT_STRIDES_V2.triangle, 1);
+ assert.equal(tri0.u32[7], 0, 'shared triangle 0 local_emissive_offset populated for emissive override MIS');
+ assert.equal(tri1.u32[7], 1, 'shared triangle 1 local_emissive_offset populated for emissive override MIS');
+});
+
+test('packMaterialRecordV2 and texture packing follow Principled v2 flags and deduplicate shared textures', () => {
+ const sharedImage = makeCheckerRgba8(4, 4, true);
+ const mixedGeo = {
+ positions: new Float32Array([
+ -1, 0, 0, 1, 0, 0, 0, 1, 0,
+ -1, 0, -1, 1, 0, -1, 0, 1, -1,
+ ]),
+ normals: new Float32Array([
+ 0, 0, 1, 0, 0, 1, 0, 0, 1,
+ 0, 0, 1, 0, 0, 1, 0, 0, 1,
+ ]),
+ uvs: new Float32Array([
+ 0, 0, 1, 0, 0.5, 1,
+ 0, 0, 1, 0, 0.5, 1,
+ ]),
+ indices: new Uint32Array([0, 1, 2, 3, 4, 5]),
+ triangleMaterial: new Uint32Array([1, 0]), // tri 0 is cutout (mat 1), tri 1 is opaque (mat 0)
+ };
+ const floatTex = { width: 2, height: 2, data: new Float32Array(2 * 2 * 4).fill(0.5) };
+ const camera = createCamera({ eye: [0, 0, 4], target: [0, 0, 0], fov: 45 }, 16, 16);
+
+ const v2 = buildNativeInputV2(
+ {
+ materials: [
+ {
+ color: [0.9, 0.8, 0.5],
+ metallic: 1.0,
+ roughness: 0.2,
+ specular: 0.8,
+ specularColor: [1.0, 0.9, 0.7],
+ anisotropy: 0.6,
+ clearcoat: 1.0,
+ clearcoatRoughness: 0.05,
+ coatTint: [0.9, 0.95, 1.0],
+ iridescence: 1.0,
+ iridescenceThickness: 380,
+ iridescenceIor: 1.35,
+ sheenColor: [0.8, 0.8, 0.9],
+ sheenRoughness: 0.4,
+ attenuationColor: [0.4, 0.8, 0.9],
+ attenuationDistance: 0.25,
+ map: { image: sharedImage, colorSpace: 'srgb' },
+ normalMap: { image: floatTex },
+ },
+ {
+ color: [1, 1, 1],
+ alphaMode: 'mask',
+ alphaCutoff: 0.5,
+ map: { image: sharedImage, colorSpace: 'srgb' },
+ },
+ ],
+ instances: [{ geometry: mixedGeo, materialIndex: 0 }],
+ lights: {},
+ },
+ camera,
+ { width: 16, height: 16, samples: 1, clampDirect: 2.0, clampIndirect: 4.0 },
+ );
+
+ // sharedImage used twice -> 1 RGBA8_SRGB descriptor + 1 RGBA32_FLOAT descriptor = 2 total descriptors.
+ assert.equal(v2.textureCount, 2);
+ const td0 = viewRecord(v2.textureDescriptors, STRUCT_STRIDES_V2.textureDescriptor, 0);
+ const td1 = viewRecord(v2.textureDescriptors, STRUCT_STRIDES_V2.textureDescriptor, 1);
+ assert.equal(td0.u32[0] % 4, 0, 'td0 16B word alignment');
+ assert.equal(td1.u32[0] % 4, 0, 'td1 16B word alignment');
+ assert.equal(td0.u32[3] & 0xff, 1, 'RGBA8_SRGB = 1');
+ assert.equal(td1.u32[3] & 0xff, 2, 'RGBA32_FLOAT = 2');
+
+ // Within the mesh BLAS, the opaque triangle (originally tri 1) must be ordered before the cutout triangle (tri 0).
+ const inst = viewRecord(v2.instances, STRUCT_STRIDES_V2.instance, 0);
+ assert.equal(inst.u32[26], 1, 'opaque_triangle_count === 1');
+ assert.equal(inst.u32[27], 2, 'total_triangle_count === 2');
+ const triOpaque = viewRecord(v2.triangles, STRUCT_STRIDES_V2.triangle, 0);
+ const triCutout = viewRecord(v2.triangles, STRUCT_STRIDES_V2.triangle, 1);
+ assert.equal(triOpaque.u32[3], 0, 'slot 0 is opaque material 0');
+ assert.equal(triCutout.u32[3], 1, 'slot 1 is mask material 1');
+
+ const mat0 = viewRecord(v2.materials, STRUCT_STRIDES_V2.material, 0);
+ assert.ok(Math.abs(mat0.f32[6] - 0.4) < 1e-6, 'specular_ior_level = 0.5 * specular');
+ assert.ok(Math.abs(mat0.f32[22] - 380) < 1e-6, 'thin_film_thickness');
+ assert.ok(Math.abs(mat0.f32[31] - 0.25) < 1e-6, 'absorption_distance');
+ assert.equal(mat0.u32[48] & 1, 1, 'MATERIAL_FLAG_MULTISCATTER_GGX = 1u');
+ assert.equal(mat0.u32[48] & 4, 4, 'MATERIAL_FLAG_TRANSPARENT_SHADOW = 4u');
+ assert.equal(mat0.u32[48] & 8, 8, 'MATERIAL_FLAG_DOUBLE_SIDED = 8u');
+ assert.equal(mat0.u32[48] & 32, 32, 'MATERIAL_FLAG_F82_METALLIC = 32u');
+ assert.equal(mat0.i32[52], 0, 'base_color_tex');
+ assert.equal(mat0.i32[54], 1, 'normal_tex');
+
+ const mat1 = viewRecord(v2.materials, STRUCT_STRIDES_V2.material, 1);
+ assert.equal(mat1.u32[49], 1, 'ALPHA_MODE_MASK = 1');
+ assert.equal(mat1.i32[52], 0, 'shared base_color_tex');
+ assert.equal(mat1.i32[62], 0, 'alpha_tex points to base_color_tex');
+
+ // Cycles clamp semantics: multiplied by 3.0.
+ const kp = viewRecord(v2.kernelParams, STRUCT_STRIDES_V2.kernelParams);
+ assert.ok(Math.abs(kp.f32[10] - 6.0) < 1e-6, 'clamp_direct = 2.0 * 3.0');
+ assert.ok(Math.abs(kp.f32[11] - 12.0) < 1e-6, 'clamp_indirect = 4.0 * 3.0');
+});
+
+test('buildNativeInputV2 normalizes all 5 Cycles light types, camera-visibility flags, and HDRI marginal/conditional CDFs', () => {
+ const hdriPixels = new Float32Array(8 * 4 * 3);
+ for (let i = 0; i < 8 * 4; i++) {
+ hdriPixels[i * 3] = i === 5 ? 50.0 : 0.5; // 50.0 must clamp to HDRI_RADIANCE_LIMIT = 16
+ hdriPixels[i * 3 + 1] = 0.25;
+ hdriPixels[i * 3 + 2] = 0.1;
+ }
+ const envMap = createEnvironmentMap({ width: 8, height: 4, data: hdriPixels, intensity: 1.5 });
+ const parts = [{ name: 'floor', geometry: quadGeometry(-2), material: { color: [0.5, 0.5, 0.5] } }];
+ const scene = buildTraceScene(parts, {
+ map: envMap,
+ keyColor: [4, 3, 2],
+ lightDirection: [0, 1, 0], // toward sun (+Y), so emission direction must be (0, -1, 0)
+ pointLights: [
+ { position: [1, 2, 3], color: [1, 0.5, 0.25], intensity: 10, radius: 0.2 },
+ { position: [-1, 2, 3], color: [1, 1, 1], intensity: 5, radius: 0 },
+ ],
+ spotLights: [
+ { position: [0, 3, 1], direction: [0, -1, 0], angle: 0.5, penumbra: 0.3, color: [1, 0.9, 0.8], intensity: 20, radius: 0.1 },
+ ],
+ areaLights: [
+ { position: [2, 3, 0], direction: [0, -1, 0], up: [0, 0, 1], width: 2.0, height: 0.5, color: [0.8, 0.9, 1], intensity: 6 },
+ ],
+ });
+ // Also append a disk area light with spread < pi to verify LIGHT_TYPE_AREA_DISK (3) and spread normalization.
+ scene.lights.areas.push({
+ bit: 26,
+ shape: 'disk',
+ spread: Math.PI / 3,
+ cameraVisible: true,
+ position: [-2, 3, 0],
+ normal: [0, -1, 0],
+ across: [1, 0, 0],
+ along: [0, 0, 1],
+ width: 1.2,
+ height: 1.2,
+ color: [1, 1, 1],
+ intensity: 4,
+ });
+
+ const camera = createCamera({ eye: [0, 0, 5], target: [0, 0, 0], fov: 50 }, 16, 16);
+ const v2 = buildNativeInputV2(scene, camera, { width: 16, height: 16, samples: 1 });
+ assert.equal(v2.lightCount, 6);
+
+ const sun = viewRecord(v2.lights, STRUCT_STRIDES_V2.light, 0);
+ const pointSphere = viewRecord(v2.lights, STRUCT_STRIDES_V2.light, 1);
+ const pointDelta = viewRecord(v2.lights, STRUCT_STRIDES_V2.light, 2);
+ const spot = viewRecord(v2.lights, STRUCT_STRIDES_V2.light, 3);
+ const areaRect = viewRecord(v2.lights, STRUCT_STRIDES_V2.light, 4);
+ const areaDisk = viewRecord(v2.lights, STRUCT_STRIDES_V2.light, 5);
+
+ assert.equal(sun.u32[3], 4, 'LIGHT_TYPE_SUN');
+ assert.ok(Math.abs(sun.f32[9] + 1.0) < 1e-6, 'sun direction points from emitter into scene (-Y)');
+ assert.equal(sun.u32[7] & 4, 0, 'sun CAMERA_VISIBLE off by default');
+
+ assert.equal(pointSphere.u32[3], 0, 'LIGHT_TYPE_POINT');
+ const expectedPointRad = 10 / (Math.PI * 0.2 * 0.2);
+ assert.ok(Math.abs(pointSphere.f32[4] - expectedPointRad) < 1e-3, 'sphere point radiance = intensity / (pi * r^2)');
+ assert.equal(pointSphere.u32[7] & 2, 2, 'finite-radius point enables MULTIPLE_IMPORTANCE');
+ assert.equal(pointSphere.u32[7] & 4, 0, 'point CAMERA_VISIBLE off by default');
+
+ assert.ok(Math.abs(pointDelta.f32[4] - 5.0) < 1e-6, 'delta point intensity = color * intensity');
+ assert.equal(pointDelta.u32[7] & 2, 0, 'delta point disables MULTIPLE_IMPORTANCE');
+
+ assert.equal(spot.u32[3], 1, 'LIGHT_TYPE_SPOT');
+ assert.ok(Math.abs(spot.f32[20] - Math.cos(0.5)) < 1e-6, 'spot cos_half_angle');
+ assert.ok(Math.abs(spot.f32[21] - 0.3) < 1e-6, 'spot_blend recovered as 0.3 in [0, 1]');
+
+ assert.equal(areaRect.u32[3], 2, 'LIGHT_TYPE_AREA_RECT');
+ assert.ok(Math.abs(areaRect.f32[4] - 0.8 * (6 / (2.0 * 0.5))) < 1e-5, 'area rect radiance = color * intensity / (W * H)');
+ assert.equal(areaRect.f32[22], 0, 'default spread=pi sets tan_half_spread = 0');
+ assert.equal(areaRect.f32[23], 0, 'default spread=pi sets spread_normalization = 0');
+
+ assert.equal(areaDisk.u32[3], 3, 'LIGHT_TYPE_AREA_DISK');
+ assert.equal(areaDisk.u32[7] & 4, 4, 'explicit cameraVisible sets LIGHT_FLAG_CAMERA_VISIBLE');
+ assert.ok(areaDisk.f32[22] > 0 && areaDisk.f32[23] > 0, 'spread < pi populates tan_half_spread and spread_normalization');
+ assert.equal(areaDisk.f32[29], 1.0, 'analytic light CDF ends at 1.0');
+
+ // HDRI texels + marginal + conditional CDF invariants.
+ assert.equal(v2.environmentTexels.length, (2 * 8 * 4 + 4) * 4);
+ assert.equal(v2.environmentTexels[5 * 4], 16.0, 'HDRI pixel clamped at 16.0');
+ const cdfStart = 8 * 4;
+ let marginalProbSum = 0;
+ for (let y = 0; y < 4; y++) {
+ marginalProbSum += v2.environmentTexels[(cdfStart + y) * 4 + 1];
+ let condProbSum = 0;
+ for (let x = 0; x < 8; x++) {
+ condProbSum += v2.environmentTexels[(cdfStart + 4 + y * 8 + x) * 4 + 1];
+ }
+ assert.ok(Math.abs(condProbSum - 1.0) < 1e-5, `row ${y} conditional probabilities sum to 1`);
+ assert.equal(v2.environmentTexels[(cdfStart + 4 + y * 8 + 7) * 4], 1.0, `row ${y} conditional CDF ends at 1.0`);
+ }
+ assert.ok(Math.abs(marginalProbSum - 1.0) < 1e-5, 'marginal probabilities sum to 1');
+ assert.equal(v2.environmentTexels[(cdfStart + 3) * 4], 1.0, 'marginal CDF ends at 1.0');
+});
+
+test('upgradeNativeInputV1ToV2 preserves textures, lights, subsurface, volume, and camera from legacy v1 input', () => {
+ const texImage = makeCheckerRgba8(4, 4, true);
+ const envMap = createEnvironmentMap({ width: 4, height: 2, data: new Float32Array(4 * 2 * 3).fill(0.4), intensity: 1.0 });
+ const parts = [
+ {
+ name: 'wax',
+ geometry: quadGeometry(0),
+ material: {
+ color: [0.8, 0.5, 0.4],
+ roughness: 0.4,
+ subsurface: { weight: 0.8, radius: [1, 0.3, 0.1], scale: 0.05 },
+ },
+ },
+ {
+ name: 'cutout-card',
+ geometry: quadGeometry(1),
+ material: {
+ color: [1, 1, 1],
+ alphaMode: 'mask',
+ alphaCutoff: 0.5,
+ map: { image: texImage, colorSpace: 'srgb' },
+ },
+ },
+ {
+ name: 'lamp',
+ geometry: quadGeometry(2),
+ material: { color: [1, 0.8, 0.5], emission: 4 },
+ },
+ ];
+ const scene = buildTraceScene(parts, {
+ map: envMap,
+ keyColor: [3, 3, 3],
+ lightDirection: [0, 1, 1],
+ spotLights: [{ position: [0, 3, 2], direction: [0, -1, -0.5], angle: 0.6, penumbra: 0.25, color: [1, 1, 1], intensity: 12, radius: 0.05 }],
+ volumeFog: { minimum: [-5, -5, -5], maximum: [5, 5, 5], density: 0.1, anisotropy: 0.3 },
+ });
+ const camera = createCamera({ eye: [0, 1, 6], target: [0, 0, 0], fov: 50 }, 24, 16);
+ const v1 = buildNativeInput(scene, camera, { width: 24, height: 16, samples: 4, bounces: 5, seed: 7 }, pack);
+ const upgraded = upgradeNativeInputV1ToV2(v1, { width: 24, height: 16, samples: 4 });
+
+ assert.equal(upgraded.schemaVersion, 2);
+ assert.equal(upgraded.instanceCount, 3);
+ assert.equal(upgraded.triangleCount, 6);
+ assert.equal(upgraded.materialCount, 3);
+ assert.equal(upgraded.emissiveTriangleCount, 2);
+ assert.equal(upgraded.lightCount, 2); // sun + spot
+ assert.equal(upgraded.textureCount, 1);
+
+ const kp = viewRecord(upgraded.kernelParams, STRUCT_STRIDES_V2.kernelParams);
+ assert.equal(kp.u32[8] & (2 | 4), 2 | 4, 'HAS_VOLUME | HAS_SUBSURFACE set in kernel_flags');
+ assert.equal(kp.f32[10], 0, 'unclamped direct by default');
+ assert.equal(kp.f32[11], 0, 'unclamped indirect by default');
+
+ const spot = viewRecord(upgraded.lights, STRUCT_STRIDES_V2.light, 1);
+ assert.ok(Math.abs(spot.f32[21] - 0.25) < 1e-5, 'spot_blend recovered cleanly from v1 blend');
+});
+
+test('Cycles v2 host executes multi-BLAS/TLAS ray queries, cutout alpha masking, v1 auto-upgrade, and probeCyclesLobe on GPU', { skip: !findNativeAddon() }, () => {
+ const cutoutImage = makeCheckerRgba8(4, 4, true); // left half alpha=0, right half alpha=255
+ const sharedQuad = quadGeometry(0);
+ const camera = createCamera({ eye: [0, 0, 2.4], target: [0, 0, 0], fov: 50 }, 16, 16);
+
+ // Instance 0: cutout quad at z = 0 (left half transparent x < 0, right half opaque green x > 0).
+ // Instance 1: mirrored solid red backdrop quad at z = -1 covering full view (shares same geometry!).
+ const v2Input = buildNativeInputV2(
+ {
+ materials: [
+ { color: [0.1, 0.9, 0.2], alphaMode: 'mask', alphaCutoff: 0.5, map: { image: cutoutImage, colorSpace: 'srgb' } },
+ { color: [0.9, 0.1, 0.1], roughness: 0.8 },
+ ],
+ instances: [
+ { geometry: sharedQuad, matrix: [2, 0, 0, 0, 0, 2, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1], materialIndex: 0 },
+ { geometry: sharedQuad, matrix: [-4, 0, 0, 0, 0, 4, 0, 0, 0, 0, 1, 0, 0, 0, -1, 1], materialOverride: 1 },
+ ],
+ lights: {
+ points: [{ position: [0, 0, 3], color: [1, 1, 1], intensity: 2, radius: 0.1 }],
+ },
+ },
+ camera,
+ { width: 16, height: 16, samples: 4 },
+ );
+
+ assert.throws(
+ () => traceNative(v2Input, { width: 16, height: 16, samples: 1, kernel: 'legacy' }),
+ /Cannot pass a FORMAT-v2 scene input to kernel "legacy"/,
+ );
+
+ const result = traceNative(v2Input, {
+ width: 16,
+ height: 16,
+ samples: 4,
+ samplesPerDispatch: 2,
+ kernel: 'cycles',
+ bootstrapKernel: true,
+ });
+
+ assert.equal(result.rgba.length, 16 * 16 * 4);
+ assert.equal(result.albedo.length, 16 * 16 * 3);
+ assert.equal(result.normal.length, 16 * 16 * 3);
+ assert.equal(result.depth.length, 16 * 16);
+ assert.equal(result.variance.length, 16 * 16);
+ assert.equal(result.averageSamples, 4);
+ assert.equal(result.features, 'EXPERIMENTAL_RAY_QUERY');
+ assert.ok(result.rgba.every(Number.isFinite));
+
+ // Left pixel (x=3, y=8) sees through the alpha=0 cutout to the backdrop at z=-1 (red albedo, depth ~ 3.4).
+ // Right pixel (x=12, y=8) hits the opaque half of the foreground card at z=0 (green albedo, depth ~ 2.4).
+ const leftPixel = 8 * 16 + 3;
+ const rightPixel = 8 * 16 + 12;
+ assert.ok(result.albedo[leftPixel * 3] > 0.8 && result.albedo[leftPixel * 3 + 1] < 0.2, 'cutout hole hits red backdrop');
+ assert.ok(result.albedo[rightPixel * 3 + 1] > 0.8 && result.albedo[rightPixel * 3] < 0.2, 'opaque texel hits green foreground');
+ assert.ok(result.depth[leftPixel] > result.depth[rightPixel] + 0.8, 'backdrop depth exceeds foreground depth');
+ // Both mirrored backdrop and foreground face +Z toward camera!
+ assert.ok(result.normal[leftPixel * 3 + 2] > 0.99, 'mirrored backdrop outward normal is +Z');
+ assert.ok(result.normal[rightPixel * 3 + 2] > 0.99, 'foreground outward normal is +Z');
+
+ // Verify v1 input auto-upgrades when kernel: 'cycles' is selected.
+ const v1Scene = buildTraceScene([{ name: 'quad', geometry: sharedQuad, material: { color: [0.3, 0.6, 0.9] } }], {});
+ const v1Input = buildNativeInput(v1Scene, camera, { width: 8, height: 8, samples: 2, bounces: 2, seed: 1 }, pack);
+ const autoUpgradedResult = traceNative(v1Input, {
+ width: 8,
+ height: 8,
+ samples: 2,
+ kernel: 'cycles',
+ bootstrapKernel: true,
+ });
+ assert.equal(autoUpgradedResult.rgba.length, 8 * 8 * 4);
+ assert.ok(autoUpgradedResult.rgba.every(Number.isFinite));
+
+ // Verify probeCyclesLobe dispatches "test_lobe_samples" and returns all 4 raw planes un-divided.
+ const probePlanes = probeCyclesLobe({
+ width: 16,
+ height: 8,
+ mode: 1,
+ seed: 42,
+ wo: [0, 0.6, 0.8],
+ frontFace: false,
+ material: {
+ color: [0.8, 0.4, 0.2],
+ roughness: 0.35,
+ metallic: 1.0,
+ ior: 1.45,
+ f82Tint: [0.95, 0.85, 0.75],
+ },
+ bootstrapKernel: true,
+ });
+ const count = 16 * 8;
+ assert.equal(probePlanes.length, 4 * count * 4);
+ assert.ok(probePlanes.every(Number.isFinite));
+
+ const customMaterialBytes = packMaterialRecordV2({ color: [0.25, 0.5, 0.75], roughness: 0.2 }).bytes;
+ const rawBytesProbe = probeCyclesLobe({
+ width: 8,
+ height: 4,
+ materialBytes: customMaterialBytes,
+ bootstrapKernel: true,
+ });
+ assert.equal(rawBytesProbe.length, 4 * 8 * 4 * 4);
+ assert.ok(rawBytesProbe.every(Number.isFinite));
+
+ assert.throws(() => probeCyclesLobe({ width: 8, height: 8, wo: [0, 0, 0], bootstrapKernel: true }), /non-zero finite 3D vector/);
+});