3D engine that AI agents drive
Pack native job textures into the v2 pool without the v1 atlas (#1053)
Nguyen Xuan An8f3a9c444daf
diff --git a/changes/1053.md b/changes/1053.mdnew file mode 100644index 00000000..a5fe1fd4--- /dev/null+++ b/changes/1053.md@@ -0,0 +1 @@+- A native render job packs its maps straight into the FORMAT-v2 texture pool, so a scene with more than the 4096 by 16384 texels of the old atlas renders instead of failing with "The material textures do not fit the GPU atlas" (#1053)diff --git a/docs/path-tracer.md b/docs/path-tracer.mdindex ad644665..66f6c737 100644--- a/docs/path-tracer.md+++ b/docs/path-tracer.md@@ -65,7 +65,7 @@ Also checked before any ray is traced: samples times pixels times bounces at mos- A part's material is its own entry in `materials`, so copies may differ in material; a multi-material mesh stays one geometry with the materials the part names.- `buildNativeInput` (the `legacy` kernel) refuses an instanced scene with an error; build the scene without `instancing` for that kernel. `traceNative` with `kernel: "legacy"` refuses a FORMAT-v2 input the same way.- Render jobs with `renderer.backend: "native"` keep repeated geometry as instances when the job traces with the `cycles` kernel (the default): the job page exports FORMAT-v2 tables of the unique triangles and one record per part, the job runner rebuilds the input for `traceNative`, and the report names the `instances` and counts `triangles` once per shared geometry. With `JS67_NATIVE_KERNEL=legacy`, `JS67_NATIVE_INSTANCING=off` (flattened triangles on the `cycles` kernel, to compare the two), or a scene where no geometry is shared, the job exports flattened geometry as before; on the `cycles` kernel the materials are still sent whole (next point), and only the legacy kernel reads the v1 tables.-- A job sends the materials of an instanced scene and of a flattened one the same way (`buildJobNativeInput` and `buildFlattenedJobNativeInput` in `packages/render-native/job-input.mjs`): what the v1 material tables carry is read from them, and `carriedMaterialFields` lays blend opacity, sheen, specular, anisotropy, iridescence, attenuation and the layer textures over it. A part looks the same whether or not other geometry in the scene is shared, and a material that sets none of those fields packs to the record the v1 tables gave. Every job on the `cycles` kernel is exported as FORMAT-v2; the legacy kernel and light bakes keep the v1 tables.+- A job sends the materials of an instanced scene and of a flattened one the same way (`buildJobNativeInput` and `buildFlattenedJobNativeInput` in `packages/render-native/job-input.mjs`): what the v1 material tables carry is read from them, and `carriedMaterialFields` lays blend opacity, sheen, specular, anisotropy, iridescence, attenuation and the layer textures over it. A part looks the same whether or not other geometry in the scene is shared, and a material that sets none of those fields packs to the record the v1 tables gave. Every job on the `cycles` kernel is exported as FORMAT-v2; the legacy kernel and light bakes keep the v1 tables. A job's maps go from the materials into the FORMAT-v2 texture pool without the v1 atlas (`withVirtualAtlas` in `packages/render-native/pack-input.mjs`), so the pool (`TEXTURE_POOL_MAX_BYTES`, 1 GiB, mip levels counted) limits them and not the 4096 by 16384 texels of the atlas; a scene that fitted the atlas packs to the same bytes (`tests/native-job-texture-pool.test.js` holds the SHA-256 of every table). Over the pool the job throws "The texture pool is full" and says to pass smaller textures.- Texture mip levels are opt in on the `cycles` kernel: pass `textureMips: true` to the packer (or `mips: true` on one texture) and every linearly filtered texture, RGBA8, sRGB and float, stores a mip chain after level 0 (level 1 integrates the level 0 reconstruction, the rest are 2 x 2 boxes); the kernel then keeps a ray cone per path and reads the level a hit asks for, blended between two levels. Blender Cycles reads level 0 only, so the default stays level 0 and an existing scene packs and renders byte for byte as before. The pool check counts the levels (a third more texels). The estimate, its limits and the measured error of a minified checker are in `docs/cycles-parity.md` ("Texture mip levels").- When the instanced packer refuses a scene (copies of an emissive mesh that emit different triangles, a singular matrix), the job exports it flattened as before and the report says `instancing: "flattened"` and `instancingReason`. A scene that fails to export no longer marks the native tracer unusable for the process; only a tracer or adapter failure does.- A part with `shadowOnly: true` becomes an instance that camera rays skip (visibility bits for every other ray kind stay set). An instance whose material differs from the first copy's emits light by its own material: a copy made emissive by its material is sampled as a light, and a copy made non-emissive is not. Triangles of a shared mesh that are emissive keep one `local_emissive_offset` for all copies, so a copy scaled to a size that drops an emissive triangle the other copies keep is refused with its index.diff --git a/packages/render-native/job-input.mjs b/packages/render-native/job-input.mjsindex f332bf7c..7ec31d61 100644--- a/packages/render-native/job-input.mjs+++ b/packages/render-native/job-input.mjs@@ -2,8 +2,9 @@// FORMAT-v2 material record holds, so the job takes what the tables carry from the tables (a scene that uses nothing else packs// to the bytes it always did) and lays the rest of the material over it: blend opacity, sheen, specular, anisotropy,// iridescence, attenuation and the layer textures. A flattened scene and an instanced one go through the same records, so a-// part looks the same whether or not other geometry in the scene is shared.-import { buildNativeInput, packNativeMaterialTables } from './pack-input.mjs';+// part looks the same whether or not other geometry in the scene is shared. The maps go from the materials into the FORMAT-v2+// texture pool without the v1 atlas, so the pool (1 GiB) is the limit on them, not the atlas (4096 x 16384 texels).+import { buildNativeInput, packNativeMaterialTables, withVirtualAtlas } from './pack-input.mjs';import { buildNativeInputV2, reduceV1MaterialTable, upgradeNativeInputV1ToV2 } from './pack-input-v2.mjs';const ALL_LIGHT_GROUPS = 0xffffffff;@@ -156,11 +157,12 @@ export function buildJobNativeInput(scene, camera, options, pack, resolveTextureif (!scene?.instances || !scene.traceMaterials) {throw new TypeError('buildJobNativeInput packs an instanced scene: build it with buildTraceScene(parts, environment, { instancing: true }) and share a geometry between two parts.');}- const tables = packNativeMaterialTables(scene.traceMaterials, null, pack);+ const tables = packNativeMaterialTables(scene.traceMaterials, null, withVirtualAtlas(pack));const reducedMaterials = reduceV1MaterialTable({materials: tables.materials,atlas: tables.atlas,atlasWidth: tables.atlasWidth,+ virtualTextures: tables.virtualTextures,subsurfaceVec4Offset: tables.subsurfaceVec4Offset,materialCount: scene.traceMaterials.length,carriedFields: carriedMaterialFieldsOfScene(scene, resolveTexture),@@ -186,5 +188,5 @@ export function buildFlattenedJobNativeInput(scene, camera, options, pack, resol...(options.samples === undefined ? {} : { samples: options.samples }),...(options.textureMips === undefined ? {} : { textureMips: options.textureMips }),};- return upgradeNativeInputV1ToV2(buildNativeInput(scene, camera, options, pack), upgradeOptions, carriedFields);+ return upgradeNativeInputV1ToV2(buildNativeInput(scene, camera, options, withVirtualAtlas(pack)), upgradeOptions, carriedFields);}diff --git a/packages/render-native/pack-input-v2.mjs b/packages/render-native/pack-input-v2.mjsindex b06b943b..0be7b382 100644--- a/packages/render-native/pack-input-v2.mjs+++ b/packages/render-native/pack-input-v2.mjs@@ -2607,6 +2607,14 @@ export function buildNativeInputV2(scene, camera, options = {}) {};}+// The words of a texture that was never copied into an atlas (`packVirtualAtlas` in pack-input.mjs): its RGBA8 bytes as+// little-endian words, the layout the atlas rows hold.+function virtualTextureWords(texture, width, height) {+ const words = new Uint32Array(width * height);+ new Uint8Array(words.buffer).set(texture.data.subarray(0, width * height * 4));+ return words;+}+function extractAtlasSubtexture(atlasWords, atlasWidth, rectX, rectY, width, height) {const words = new Uint32Array(width * height);for (let row = 0; row < height; row++) {@@ -2652,8 +2660,10 @@ function withCarriedFields(descriptor, carried, textureCollector) {* `carriedFields`, when given, holds one `carriedMaterialFields` result per material for everything the tables cannot hold* (blend opacity, sheen, specular, anisotropy, iridescence, attenuation, the layer textures and the rest of the record).* `materials` holds the table with the subsurface table after it, `atlas` the atlas words and `atlasWidth` their row width.+ * `virtualTextures`, when given, replaces the atlas: the rectangle of a map is `{ x: its index in that list, y: 0 }` and the+ * map is read from the list, so the texture pool is the only limit on the maps.*/-export function reduceV1MaterialTable({ materials: matSource, atlas: atlasWords, atlasWidth, subsurfaceVec4Offset, materialCount, carriedFields, textureMips }) {+export function reduceV1MaterialTable({ materials: matSource, atlas: atlasWords, atlasWidth, subsurfaceVec4Offset, materialCount, carriedFields, textureMips, virtualTextures }) {const textureCollector = createTextureCollector({ textureMips });const atlasCache = new Map();@@ -2672,7 +2682,9 @@ export function reduceV1MaterialTable({ materials: matSource, atlas: atlasWords,}const repeat = (flags & 1) !== 0;const isSrgb = (flags & 2) !== 0;- const subWords = extractAtlasSubtexture(atlasWords, atlasWidth, x, y, w, h);+ const subWords = virtualTextures+ ? virtualTextureWords(virtualTextures[x], w, h)+ : extractAtlasSubtexture(atlasWords, atlasWidth, x, y, w, h);const added = textureCollector.addPackedRgba8Words(subWords, w, h, isSrgb, repeat);atlasCache.set(key, added);return added;@@ -2793,6 +2805,7 @@ export function upgradeNativeInputV1ToV2(v1Input, options = {}, carriedFields =materialCount,carriedFields,textureMips: options.textureMips,+ virtualTextures: v1Input.virtualTextures,});const materialsBuffer = new Uint8Array(Math.max(1, materialRecords.length) * STRUCT_STRIDES_V2.material);diff --git a/packages/render-native/pack-input.mjs b/packages/render-native/pack-input.mjsindex be77ece4..9ed86169 100644--- a/packages/render-native/pack-input.mjs+++ b/packages/render-native/pack-input.mjs@@ -68,6 +68,7 @@ export function buildNativeInput(scene, camera, options, pack) {materials: materialTables.materials,lights: lights.table.data,atlas: materialTables.atlas,+ ...(materialTables.virtualTextures ? { virtualTextures: materialTables.virtualTextures } : {}),environmentColors: environment?.colors ?? new Float32Array(4),environmentTables,parameters: writeParameters(scene, camera, options, lights.count, materialTables.atlasWidth, materialTables.subsurfaceVec4Offset),@@ -80,6 +81,7 @@ export function buildNativeInput(scene, camera, options, pack) {*/export function packNativeMaterialTables(materials, shadowOnlyParts, pack) {const atlas = pack.packAtlas(materials);+ const virtualTextures = atlas.virtualTextures ? { virtualTextures: atlas.virtualTextures } : {};const materialData = pack.packMaterials(materials, atlas, shadowOnlyParts).data;const usesSubsurface = pack.sceneUsesSubsurface(materials);const subsurfaceData = usesSubsurface ? pack.packSubsurface(materials).data : new Float32Array(0);@@ -91,9 +93,37 @@ export function packNativeMaterialTables(materials, shadowOnlyParts, pack) {atlas: new Uint32Array(atlas.data.buffer, atlas.data.byteOffset, Math.floor(atlas.data.byteLength / 4)),atlasWidth: atlas.width,subsurfaceVec4Offset: usesSubsurface ? materialData.length / 4 : 0,+ ...virtualTextures,};}+const MATERIAL_TEXTURE_FIELDS = Object.freeze(['texture', 'normalTexture', 'surfaceTexture', 'emissiveTexture']);++/**+ * A stand-in for `packAtlas` that copies no pixel. Each distinct texture gets the rectangle `{ x: its number, y: 0 }` in the+ * material table, and `virtualTextures[number]` holds the texture itself. The FORMAT-v2 job packs read the maps from there+ * straight into the texture pool, so the maps are limited by the pool (`TEXTURE_POOL_MAX_BYTES`) and not by the 4096 x 16384+ * texels of the v1 atlas.+ */+export function packVirtualAtlas(materials) {+ const placements = new Map();+ const virtualTextures = [];+ for (const material of materials) {+ for (const field of MATERIAL_TEXTURE_FIELDS) {+ const texture = material[field];+ if (!texture || placements.has(texture.data)) continue;+ placements.set(texture.data, { x: virtualTextures.length, y: 0 });+ virtualTextures.push(texture);+ }+ }+ return { placements, width: 1, height: 1, data: new Uint8Array(4), virtualTextures };+}++/** `pack` with the atlas step replaced by `packVirtualAtlas`; the tables it packs carry `virtualTextures`. */+export function withVirtualAtlas(pack) {+ return { ...pack, packAtlas: packVirtualAtlas };+}+// The words of the parameter block the texel entry reads: the texel count where an image holds its width, and the sample// count in the third word after the seed and the atlas width.const TEXEL_SAMPLES_WORD = 46;diff --git a/tests/native-job-texture-pool.test.js b/tests/native-job-texture-pool.test.jsnew file mode 100644index 00000000..2d250582--- /dev/null+++ b/tests/native-job-texture-pool.test.js@@ -0,0 +1,153 @@+import assert from 'node:assert/strict';+import { createHash } from 'node:crypto';+import test from 'node:test';+import { STRUCT_STRIDES_V2 } from '../packages/render-native/index.mjs';+import { buildFlattenedJobNativeInput, buildJobNativeInput } from '../packages/render-native/job-input.mjs';+import { TEXTURE_POOL_MAX_BYTES } from '../packages/render-native/pack-input-v2.mjs';+import { createCamera } from '../src/path-tracer.js';+import * as pack from '../src/path-tracer-gpu-pack.js';+import { buildTraceScene, resolveTexture } from '../src/path-tracer-scene.js';++const WIDTH = 24;+const HEIGHT = 16;+const camera = createCamera({ eye: [0, 0, 8], target: [0, 0, 0], fov: 50 }, WIDTH, HEIGHT);+const packOptions = { width: WIDTH, height: HEIGHT, samples: 16, bounces: 4, seed: 7, fireflyClamp: 20, noiseThreshold: 0 };+const environment = { keyColor: [3, 3, 3], lightDirection: [0.4, 0.8, 0.5] };++function quad(scale) {+ return {+ positions: Float32Array.from([-scale, -scale, 0, scale, -scale, 0, scale, scale, 0, -scale, scale, 0]),+ normals: Float32Array.from([0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1]),+ uvs: Float32Array.from([0, 0, 1, 0, 1, 1, 0, 1]),+ indices: Uint32Array.from([0, 1, 2, 0, 2, 3]),+ };+}++const translate = x => [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, x, 0, 0, 1];++function pattern(width, height, seedByte) {+ const data = new Uint8ClampedArray(width * height * 4);+ for (let texel = 0; texel < width * height; texel++) {+ data.set([(texel * 37 + seedByte) % 256, (texel * 91) % 256, (texel * 13 + seedByte * 3) % 256, 255 - (texel % 4) * 40], texel * 4);+ }+ return { image: { width, height, data }, colorSpace: 'srgb' };+}++function texturedParts() {+ const shared = quad(1);+ return [+ { name: 'copy-a', geometry: shared, matrix: translate(-2), material: { color: [0.8, 0.2, 0.2], roughness: 0.5, map: pattern(8, 8, 9), normalMap: pattern(4, 4, 2) } },+ { name: 'copy-b', geometry: shared, matrix: translate(2), material: { color: [0.2, 0.2, 0.8], metallicRoughnessMap: pattern(6, 2, 3), emission: 2, emissiveMap: pattern(2, 2, 4) } },+ { name: 'leaf', geometry: quad(0.8), matrix: translate(0), material: { color: [1, 1, 1], map: pattern(4, 4, 5), alphaMode: 'mask', alphaCutoff: 0.4 } },+ ];+}++function hashOfTable(table) {+ return createHash('sha256').update(Buffer.from(table.buffer, table.byteOffset, table.byteLength)).digest('hex');+}++// Every packed table of the input, by name.+function hashesOfPackedTables(input) {+ const tableNames = Object.keys(input).filter(name => ArrayBuffer.isView(input[name])).sort();+ assert.ok(tableNames.length >= 10);+ return Object.fromEntries(tableNames.map(name => [name, hashOfTable(input[name])]));+}++// SHA-256 of every packed table of the two scenes, taken with the v1 atlas step in place (before issue 1053).+const GOLDEN_INSTANCED_HASHES = {+ emissiveTriangles: '2e38284e3690d5a05476c1c3068ea5e3b87e9667c3417183f287d60b1c5834b9',+ environmentTexels: '374708fff7719dd5979ec875d56cd2286f6d3cf7ec317a3b25632aab28ec37bb',+ instances: 'a196ea995083d3efc659bedb4a91ecffb87a008462be5532196dbb3cc20d94ac',+ kernelParams: '0a786f473a472a962889ba8cc747f2bdf43d73eecef1d8c1e31df0ba9a716d85',+ lightToTree: '363f012b74b9c88d828c809a568dc50627214866415aeb36ef6effbc3061741f',+ lightTreeEmitters: '6d3621e3ca86542383ba5f3f8990f1b21aa214e30cef3bca52693d1a0e05a3a8',+ lightTreeNodes: 'df3874b6cd51492d661ee5e9b3821d45275729a0cc583f1b51362158bb6f7156',+ lights: '5b7b79a262b416ac80244a7134d249c40df90df2a296cf9e17f4a5639a5c8ee8',+ materials: 'b27b23b445b1a0ba1dcbc84d8d5c14a42a67aa5025d43428abe77cb889709f83',+ textureDescriptors: 'e755bedfb56672eae156d9456473ab7fda65a6988cb270710a348c3a11dfc11a',+ textureTexels: 'd9b9eb4847af896ad84f6c2135359c7c4d037bf4a7e062e53a782710414a7a16',+ triangles: '2d22067f2b24404afca1bbaf2b9bc093876194114bdb568c9d10afa40de9be4f',+};+const GOLDEN_FLATTENED_HASHES = {+ emissiveTriangles: '2f834ad7899f3eaf0e5dcd2879c8477e1536cfed5ef945aa2b44c6ce61079001',+ environmentTexels: '374708fff7719dd5979ec875d56cd2286f6d3cf7ec317a3b25632aab28ec37bb',+ instances: '3df2d7e9401c8d2496e079d72c063298e79bf509bf3d0a6dd48e349d6ee58186',+ kernelParams: '40b03e08a41099a7cd7c75f3abb16163de889cd6f1ef747337ee2bd1c2f9ca1b',+ lightToTree: '363f012b74b9c88d828c809a568dc50627214866415aeb36ef6effbc3061741f',+ lightTreeEmitters: '07b5da35edf058375e8651d377e64187d81c65b885f2f587f455c9b19ceb128f',+ lightTreeNodes: 'ed8ee54927b117ebebb291c33752b0f94ee091db758c14049ebf05cea17f8ad5',+ lights: 'cacd8feeb79d5493f0f783d3f68baa5df766800397331160b0bc6c371384d5d6',+ materials: 'b27b23b445b1a0ba1dcbc84d8d5c14a42a67aa5025d43428abe77cb889709f83',+ textureDescriptors: 'e755bedfb56672eae156d9456473ab7fda65a6988cb270710a348c3a11dfc11a',+ textureTexels: 'd9b9eb4847af896ad84f6c2135359c7c4d037bf4a7e062e53a782710414a7a16',+ triangles: '96c8ea48ddace72c91112c5b773822350ad6e97fc59755853db57362e7f3fc59',+};++test('a textured instanced job packs the tables it packed through the v1 atlas', () => {+ const scene = buildTraceScene(texturedParts(), environment, { instancing: true });+ assert.ok(scene.instances);+ const hashes = hashesOfPackedTables(buildJobNativeInput(scene, camera, packOptions, pack, resolveTexture));+ if (process.env.PRINT_POOL_HASHES) console.log('INSTANCED', JSON.stringify(hashes));+ assert.deepEqual(hashes, GOLDEN_INSTANCED_HASHES);+});++test('a textured flattened job packs the tables it packed through the v1 atlas', () => {+ const scene = buildTraceScene(texturedParts(), environment);+ const hashes = hashesOfPackedTables(buildFlattenedJobNativeInput(scene, camera, packOptions, pack, resolveTexture));+ if (process.env.PRINT_POOL_HASHES) console.log('FLATTENED', JSON.stringify(hashes));+ assert.deepEqual(hashes, GOLDEN_FLATTENED_HASHES);+});++// The maps are distinct arrays (the packers tell maps apart by their array) over one buffer, so a test holds one copy of the pixels.+function manyMapParts(mapCount, mapSize) {+ const shared = quad(1);+ const pixels = pattern(mapSize, mapSize, 1).image.data;+ return Array.from({ length: mapCount }, (_, index) => ({+ name: `part-${index}`,+ geometry: index < 2 ? shared : quad(1 + index / 100),+ matrix: translate(index),+ material: { color: [1, 1, 1], map: { image: { width: mapSize, height: mapSize, data: new Uint8ClampedArray(pixels.buffer, 0, pixels.length) }, colorSpace: 'srgb' } },+ }));+}++const OVER_ATLAS_MAP_COUNT = 70;+const OVER_ATLAS_MAP_SIZE = 1024;++test('v1 atlas alone rejects the maps the v2 pool takes', () => {+ const parts = manyMapParts(OVER_ATLAS_MAP_COUNT, OVER_ATLAS_MAP_SIZE);+ const scene = buildTraceScene(parts, environment, { instancing: true });+ assert.throws(() => pack.packAtlas(scene.traceMaterials), /do not fit the GPU atlas/);+});++test('an instanced job with maps beyond the v1 atlas packs them into the texture pool', () => {+ const parts = manyMapParts(OVER_ATLAS_MAP_COUNT, OVER_ATLAS_MAP_SIZE);+ const scene = buildTraceScene(parts, environment, { instancing: true });+ const input = buildJobNativeInput(scene, camera, packOptions, pack, resolveTexture);+ const mapBytes = OVER_ATLAS_MAP_COUNT * OVER_ATLAS_MAP_SIZE * OVER_ATLAS_MAP_SIZE * 4;+ assert.ok(input.textureTexels.byteLength >= mapBytes);+ assert.ok(input.textureTexels.byteLength <= TEXTURE_POOL_MAX_BYTES);+ assert.equal(input.textureDescriptors.byteLength / STRUCT_STRIDES_V2.textureDescriptor, OVER_ATLAS_MAP_COUNT);+});++test('a flattened job with maps beyond the v1 atlas packs them into the texture pool', () => {+ const parts = manyMapParts(OVER_ATLAS_MAP_COUNT, OVER_ATLAS_MAP_SIZE);+ const scene = buildTraceScene(parts, environment);+ const input = buildFlattenedJobNativeInput(scene, camera, packOptions, pack, resolveTexture);+ assert.ok(input.textureTexels.byteLength >= OVER_ATLAS_MAP_COUNT * OVER_ATLAS_MAP_SIZE * OVER_ATLAS_MAP_SIZE * 4);+});++test('a job whose map exceeds the texture pool says what to pass instead', () => {+ // One map a row taller than the 1 GiB pool: the pool check runs before any pixel is read, so a short array stands in for the pixels.+ const side = 16384;+ const oversize = { image: { width: side, height: side + 1, data: new Uint8ClampedArray(4) }, colorSpace: 'srgb' };+ const shared = quad(1);+ const parts = [+ { name: 'copy-a', geometry: shared, matrix: translate(0), material: { color: [1, 1, 1], map: oversize } },+ { name: 'copy-b', geometry: shared, matrix: translate(2), material: { color: [1, 1, 1] } },+ ];+ const scene = buildTraceScene(parts, environment, { instancing: true });+ assert.throws(+ () => buildJobNativeInput(scene, camera, packOptions, pack, resolveTexture),+ error => error instanceof RangeError && /texture pool is full/.test(error.message) && /Pass smaller textures/.test(error.message),+ );+});