3D engine that AI agents drive
Add PBR texture channels and retain instance update buffers
Nguyen Xuan Anb9c9abb7d4fa
diff --git a/docs/material-maps.md b/docs/material-maps.mdnew file mode 100644index 00000000..833199d9--- /dev/null+++ b/docs/material-maps.md@@ -0,0 +1,92 @@+# Material maps++`Renderer67` supports five texture channels on standard metallic/roughness materials.+Each channel uses an image descriptor. All channels sample `geometry.uvs`, which contains two finite values per vertex.++```js+const colorTexture = { image: colorImage, colorSpace: 'srgb' };+const surfaceTexture = { image: packedImage, colorSpace: 'linear' };+const material = {+ color: [1, 1, 1],+ metallic: 0.8,+ roughness: 0.6,+ emission: 1,+ emissiveColor: [0.1, 0.2, 0.3],+ map: colorTexture,+ normalMap: { image: normalImage, colorSpace: 'linear' },+ normalScale: [1, 1],+ metallicRoughnessMap: surfaceTexture,+ occlusionMap: surfaceTexture,+ occlusionStrength: 0.7,+ emissiveMap: { image: emissionImage, colorSpace: 'srgb' },+};+```++The packed image can contain occlusion in R, roughness in G, and metallic in B.+The renderer applies the following channel rules from the [glTF 2.0 specification](https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#materials).++| Field | Input | Effect |+| --- | --- | --- |+| `map` | sRGB by default, or explicit linear RGB | Multiplies the linear base color and vertex tint. |+| `normalMap` | Explicit linear RGB | Decodes tangent-space XYZ from `[0, 1]` to `[-1, 1]`. |+| `metallicRoughnessMap` | Explicit linear RGB | Multiplies roughness by G and metallic by B. |+| `occlusionMap` | Explicit linear RGB | Uses R to attenuate indirect lighting. |+| `emissiveMap` | sRGB | Multiplies linear `emissiveColor * emission`. |++WebGL sRGB texture storage decodes color maps before shading. Data maps use linear texture storage.+Occlusion uses `mix(1, R, occlusionStrength)`. It does not attenuate direct lights or emission.+Roughness retains the renderer's minimum of `0.075` and derivative-based specular filtering.++`normalScale` contains two finite floats for X and Y. Negative values can invert either tangent axis.+The renderer derives an orthogonal tangent basis from position and UV screen derivatives, including mirrored UV handedness.+Degenerate UVs retain the geometric normal because they have no tangent basis.++Explicit vertex tangents are not consumed. Derivative tangents can differ from authored tangent bases on curved meshes.++## Descriptors and batching++A descriptor contains `image`, `uvChannel`, `colorSpace`, `flipY`, `wrapS`, `wrapT`, `minFilter`, and `magFilter`.+`uvChannel` defaults to zero. `flipY` defaults to false.++Sampler fields use WebGL enum values. Wrapping supports repeat, clamp-to-edge, and mirrored repeat.+Magnification supports nearest and linear. Minification also supports all four mipmap filters.++Descriptor identity determines GPU texture reuse. Repeated parts can share descriptors without duplicating GPU textures or texture-budget charges.+Different descriptors allocate separately even when they reference the same decoded image.+Every channel and its mipmaps contributes to `textureBytes` and the render memory plan.++A batch groups geometry identity, all five map identities, `normalScale` values, and `occlusionStrength`.+The renderer uses batch uniforms for scale and strength because its instance attributes already occupy 16 vertex locations.+Changing any of these batch fields requires a new renderer. `updateParts()` rejects changes before uploading instance data.+Color, metallic, roughness, emission, emissive color, and transforms retain their existing update behavior.+Descriptors and decoded image contents must remain unchanged while a renderer uses them.++Two API shapes were considered. A nested channel registry could carry arbitrary channel packing and transforms.+Named per-channel descriptors reuse the existing `material.map` contract and make channel semantics explicit.+The current API uses named descriptors. Arbitrary channel routing and texture transforms remain unsupported.++## glTF import and lifetime++`parseGltf()` and `loadGltf()` import base color, normal, metallic/roughness, occlusion, and emissive textures.+The importer preserves `normalTexture.scale`, `occlusionTexture.strength`, color spaces, samplers, and shared descriptor identities.+A texture reused for color and data receives separate descriptors with the appropriate color spaces.+Existing byte, resource, vertex, and combined image-pixel limits apply before decoding.+Invalid sampler values, texture indices, scales, or missing UVs fail before resources load.++1. Dispose the renderer before disposing its imported asset.+2. Call `asset.dispose()` to release decoded textures and images.++Renderer disposal deletes every cached GPU texture. Asset disposal closes each shared decoded image once.++## Limits++Texture transforms, UV channels beyond zero, transparency, alpha masking, and double-sided glTF materials remain unsupported.+Skinning, morph targets, compressed texture formats, and unsupported glTF extensions fail explicitly.+The new PBR maps require a standard material tag, including `gltf` or `armor`.+Procedural tags such as water, terrain, foliage, floor, fire, and smoke reject the new channels.+Unlit materials accept base and emissive maps only.+Texture alpha is ignored for opaque materials, as required by glTF's opaque mode.++This feature does not complete the full material system.+Extensions such as clearcoat, transmission, anisotropy, and sheen, material layers, node graphs, and authored tangent support remain missing.+GLB export of these material maps is outside this feature.diff --git a/scripts/benchmark-instance-updates.mjs b/scripts/benchmark-instance-updates.mjsnew file mode 100644index 00000000..c2764a87--- /dev/null+++ b/scripts/benchmark-instance-updates.mjs@@ -0,0 +1,43 @@+import { mat3 } from 'gl-matrix';+import { performance } from 'node:perf_hooks';+import { mkdir, writeFile } from 'node:fs/promises';+import { constants, setPriority } from 'node:os';+import { Renderer67, groupParts } from '../src/renderer.js';+import { createWallEPreviewScene } from '../src/wall-e-preview-scene.js';+setPriority(constants.priority.PRIORITY_BELOW_NORMAL);+const { parts } = createWallEPreviewScene();+const renderer = Object.create(Renderer67.prototype);+renderer.context = { ARRAY_BUFFER: 34962, bindBuffer() {}, bufferSubData() {} };+renderer.partLocations = new Map();+renderer.updateBatches = new Set();+renderer.batches = groupParts(parts).map(group => {+ const batch = { instanceData: new Float32Array(group.length * 41) };+ group.forEach((part, index) => renderer.partLocations.set(part, {+ batch, index, geometry: part.geometry, map: part.material.map ?? null, normalMatrix: mat3.create(),+ mapState: ['map', 'normalMap', 'metallicRoughnessMap', 'occlusionMap', 'emissiveMap']+ .map(field => part.material[field] ?? null).concat(part.material.normalScale ?? [1, 1], part.material.occlusionStrength ?? 1),+ }));+ return batch;+});+for (let index = 0; index < 100; index++) renderer.updateParts(parts);+let normalAllocations = 0;+const create = mat3.create;+mat3.create = () => { normalAllocations++; return create(); };+const samples = [];+try {+ for (let trial = 0; trial < 5; trial++) {+ const start = performance.now();+ for (let frame = 0; frame < 500; frame++) renderer.updateParts(parts);+ samples.push((performance.now() - start) / 500);+ }+} finally {+ mat3.create = create;+}+samples.sort((a, b) => a - b);+const result = {+ parts: parts.length, frames: 2500, medianUpdateMs: samples[2], samplesMs: samples, normalAllocations,+ scope: 'CPU validation and instance packing; mock GPU upload, not GPU frame time',+};+await mkdir('artifacts', { recursive: true });+await writeFile('artifacts/instance-update-benchmark.json', JSON.stringify(result, null, 2));+console.log(JSON.stringify(result));diff --git a/scripts/smoke-material-maps.mjs b/scripts/smoke-material-maps.mjsnew file mode 100644index 00000000..45b5f8f2--- /dev/null+++ b/scripts/smoke-material-maps.mjs@@ -0,0 +1,90 @@+import assert from 'node:assert/strict';+import { mkdir, writeFile } from 'node:fs/promises';+import { constants, setPriority } from 'node:os';+import { chromium } from 'playwright';++setPriority(constants.priority.PRIORITY_BELOW_NORMAL);+await mkdir('artifacts', { recursive: true });+const browser = await chromium.launch({+ executablePath: 'C:/Program Files/Google/Chrome/Application/chrome.exe',+ headless: true, args: ['--enable-webgl', '--ignore-gpu-blocklist'],+});+try {+ const page = await browser.newPage({ viewport: { width: 1700, height: 900 } });+ const errors = [];+ page.on('pageerror', error => errors.push(error.message));+ await page.goto(`${process.argv[2] ?? 'http://127.0.0.1:5173'}/motion.html`);+ await page.waitForFunction(() => window.__scene?.renderer);+ const report = await page.evaluate(async () => {+ window.__scene.renderer.dispose();+ const { Renderer67, sphere } = await import('/src/index.js');+ document.body.replaceChildren();+ document.body.style.cssText = 'margin:0;padding:24px;background:#141a1c;color:white;display:flex;flex-wrap:wrap;font:16px sans-serif;gap:20px';+ const geometry = sphere(64, 32);+ const channels = {+ baseline: null, normalMap: [235, 128, 200], normalMapSmallUV: [235, 128, 200],+ metallicRoughnessMap: [255, 32, 0], occlusionMap: [0, 255, 255], emissiveMap: [255, 0, 0],+ };+ const results = {};+ let normalPixels;+ for (const [channel, color] of Object.entries(channels)) {+ const container = document.createElement('div');+ const label = document.createElement('p');+ label.textContent = channel;+ const canvas = document.createElement('canvas');+ canvas.style.cssText = 'width:250px;height:300px;display:block';+ container.append(label, canvas);+ document.body.append(container);+ const material = { tag: 'gltf', color: [0.3, 0.5, 0.65], metallic: 0.8, roughness: 0.55, emission: 0.3, emissiveColor: [0.2, 0.3, 0.4] };+ if (color) {+ const image = document.createElement('canvas');+ image.width = image.height = 16;+ const context = image.getContext('2d');+ context.fillStyle = `rgb(${color.join(',')})`;+ context.fillRect(0, 0, 16, 16);+ material[channel === 'normalMapSmallUV' ? 'normalMap' : channel] = { image, colorSpace: channel === 'emissiveMap' ? 'srgb' : 'linear' };+ }+ const mesh = channel === 'normalMapSmallUV' ? { ...geometry, uvs: geometry.uvs.map(value => value * 0.001) } : geometry;+ const part = { name: channel, geometry: mesh, material, matrix: new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]) };+ const renderer = new Renderer67(canvas, [part], { ground: false, shadows: false, samples: 4, pixelRatio: 1, memoryBudgetMiB: 32 });+ renderer.render({ eye: [0, 0, 5], target: [0, 0, 0] });+ const gl = renderer.context;+ const pixels = new Uint8Array(canvas.width * canvas.height * 4);+ gl.readPixels(0, 0, canvas.width, canvas.height, gl.RGBA, gl.UNSIGNED_BYTE, pixels);+ let checksum = 2166136261;+ for (const value of pixels) checksum = Math.imul(checksum ^ value, 16777619) >>> 0;+ results[channel] = { checksum, error: gl.getError(), textureBytes: renderer.textureBytes };+ if (channel === 'normalMap') normalPixels = pixels;+ if (channel === 'normalMapSmallUV') {+ let difference = 0;+ for (let index = 0; index < pixels.length; index++) difference += Math.abs(pixels[index] - normalPixels[index]);+ results[channel].meanDifferenceFromNormal = difference / pixels.length;+ }+ // Keep a bitmap for the screenshot, then release the GPU context and cached maps.+ const bitmap = await createImageBitmap(canvas);+ renderer.dispose();+ const saved = document.createElement('canvas');+ saved.width = canvas.width;+ saved.height = canvas.height;+ saved.style.cssText = canvas.style.cssText;+ saved.getContext('2d').drawImage(bitmap, 0, 0);+ bitmap.close();+ canvas.replaceWith(saved);+ }+ return results;+ });+ for (const [channel, result] of Object.entries(report)) {+ assert.equal(result.error, 0, `${channel} produced a WebGL error`);+ if (channel !== 'baseline') {+ assert.notEqual(result.checksum, report.baseline.checksum, `${channel} did not change the rendered image`);+ assert.ok(result.textureBytes > report.baseline.textureBytes);+ }+ }+ assert.deepEqual(errors, []);+ assert.ok(report.normalMapSmallUV.meanDifferenceFromNormal < 0.1, 'UV scale changed tangent-space normal lighting');+ await page.screenshot({ path: 'artifacts/material-maps-reference.png' });+ await writeFile('artifacts/material-maps-reference.json', JSON.stringify(report, null, 2));+ console.log(JSON.stringify(report));+} finally {+ await browser.close();+}diff --git a/src/geometry.js b/src/geometry.jsindex 3fd437ee..241fc182 100644--- a/src/geometry.js+++ b/src/geometry.js@@ -40,12 +40,21 @@ function surface(columns, rows, sample) {}export function sphere(segments = 64, rings = 40) {- return surface(segments, rings, (longitude, latitude) => {+ const result = surface(segments, rings, (longitude, latitude) => {const angle = longitude * FULL_TURN;const elevation = latitude * Math.PI;const position = [Math.sin(elevation) * Math.cos(angle), Math.cos(elevation), Math.sin(elevation) * Math.sin(angle)];return { position, normal: position };});+ result.uvs = new Float32Array((segments + 1) * (rings + 1) * 2);+ for (let row = 0; row <= rings; row++) {+ for (let column = 0; column <= segments; column++) {+ const offset = (row * (segments + 1) + column) * 2;+ result.uvs[offset] = column / segments;+ result.uvs[offset + 1] = row / rings;+ }+ }+ return result;}// The torus lies in XY, facing +Z. Partial arcs are useful for interrupted armor rings.diff --git a/src/gltf.js b/src/gltf.jsindex a1b4813a..53ffeb73 100644--- a/src/gltf.js+++ b/src/gltf.js@@ -1,10 +1,11 @@import { AnimationMixer, LoadingManager, LoopOnce } from 'three';import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';+import { textureDescriptorInfo } from './renderer.js';export const GLTF_CAPABILITIES = Object.freeze({formats: ['glb', 'gltf'],- supported: ['triangle meshes', 'world transforms', 'rigid node animations', 'PNG/JPEG base color textures', 'TEXCOORD_0', 'linear RGB vertex colors', 'metallic roughness factors', 'emissive factors', 'KHR_mesh_quantization', 'KHR_materials_emissive_strength'],- unsupported: ['skinning', 'morph targets', 'vertex alpha below one', 'alpha blending or masking', 'double-sided materials', 'normal/occlusion/emissive/metallic-roughness textures', 'texture transforms', 'DRACO', 'KTX2', 'GPU instancing'],+ supported: ['triangle meshes', 'world transforms', 'rigid node animations', 'PNG/JPEG base color textures', 'normal/occlusion/emissive/metallic-roughness textures', 'TEXCOORD_0', 'linear RGB vertex colors', 'metallic roughness factors', 'emissive factors', 'KHR_mesh_quantization', 'KHR_materials_emissive_strength'],+ unsupported: ['skinning', 'morph targets', 'vertex alpha below one', 'alpha blending or masking', 'double-sided materials', 'texture transforms', 'DRACO', 'KTX2', 'GPU instancing'],});const DEFAULT_MAX_BYTES = 32 * 1024 * 1024;@@ -12,6 +13,17 @@ const DEFAULT_MAX_VERTICES = 2_000_000;const ALLOWED_EXTENSIONS = new Set(['KHR_mesh_quantization', 'KHR_materials_emissive_strength']);const WRAPPING = { 1000: 10497, 1001: 33071, 1002: 33648 };const FILTERING = { 1003: 9728, 1004: 9984, 1005: 9986, 1006: 9729, 1007: 9985, 1008: 9987 };+const MATERIAL_TEXTURES = [+ ['map', 'baseColorTexture', 'srgb'],+ ['normalMap', 'normalTexture', 'linear'],+ ['metallicRoughnessMap', 'metallicRoughnessTexture', 'linear'],+ ['occlusionMap', 'occlusionTexture', 'linear'],+ ['emissiveMap', 'emissiveTexture', 'srgb'],+];++function materialTexture(material, field) {+ return ['baseColorTexture', 'metallicRoughnessTexture'].includes(field) ? material.pbrMetallicRoughness?.[field] : material[field];+}function limitsFor(options) {const limits = {@@ -136,12 +148,25 @@ function validateDocument(document, limits) {}if ((material.alphaMode ?? 'OPAQUE') !== 'OPAQUE') throw new Error(`Unsupported alpha mode: ${material.alphaMode}.`);if (material.doubleSided) throw new Error('Double-sided materials are unsupported.');- if (material.normalTexture || material.occlusionTexture || material.emissiveTexture || material.pbrMetallicRoughness?.metallicRoughnessTexture) {- throw new Error('Only base color textures are supported. Other material texture channels are unsupported.');+ for (const [, field] of MATERIAL_TEXTURES) {+ const texture = materialTexture(material, field);+ if (!texture) continue;+ if ((texture.texCoord ?? 0) !== 0 || texture.extensions && Object.keys(texture.extensions).length) throw new Error(`${field} requires TEXCOORD_0 without texture transforms.`);+ if (!Number.isInteger(texture.index) || !document.textures?.[texture.index]) throw new Error(`Invalid ${field} texture index.`);+ if (field === 'normalTexture' && (!Number.isFinite(texture.scale ?? 1) || !Number.isFinite(Math.fround(texture.scale ?? 1)))) throw new Error('Normal texture scale must be a finite float.');+ if (field === 'occlusionTexture' && (!Number.isFinite(texture.strength ?? 1) || (texture.strength ?? 1) < 0 || (texture.strength ?? 1) > 1)) throw new Error('Occlusion texture strength must be within zero and one.');}- const texture = material.pbrMetallicRoughness?.baseColorTexture;- if (texture && ((texture.texCoord ?? 0) !== 0 || texture.extensions && Object.keys(texture.extensions).length)) {- throw new Error('Base color textures require TEXCOORD_0 without texture transforms.');+ }+ for (const texture of document.textures ?? []) {+ if (!Number.isInteger(texture.source) || !document.images?.[texture.source]) throw new Error('Invalid texture image index.');+ if (texture.sampler !== undefined && (!Number.isInteger(texture.sampler) || !document.samplers?.[texture.sampler])) throw new Error('Invalid texture sampler index.');+ const sampler = document.samplers?.[texture.sampler] ?? {};+ textureDescriptorInfo({ image: { width: 1, height: 1 }, ...sampler });+ }+ for (const mesh of document.meshes ?? []) {+ for (const primitive of mesh.primitives ?? []) {+ const material = document.materials?.[primitive.material];+ if (material && MATERIAL_TEXTURES.some(([, field]) => materialTexture(material, field)) && primitive.attributes?.TEXCOORD_0 === undefined) throw new Error('Material textures require TEXCOORD_0.');}}let decodedBytes = 0;@@ -387,7 +412,7 @@ function convertVertexColors(attribute, vertexCount) {return colors;}-function convertMaterial(source, limits, maps) {+function convertMaterial(source, limits, maps, definition = {}) {const material = {tag: 'gltf',color: source.color.toArray(),@@ -395,25 +420,33 @@ function convertMaterial(source, limits, maps) {roughness: source.roughness,emission: source.emissiveIntensity ?? 1,emissiveColor: source.emissive.toArray(),+ normalScale: [definition.normalTexture?.scale ?? 1, definition.normalTexture?.scale ?? 1],+ occlusionStrength: source.aoMapIntensity,};if (!material.emissiveColor.some(value => value > 0)) material.emission = 0;if (!Number.isFinite(Math.fround(material.emission)) || material.emission < 0) throw new Error('Emissive intensity must be a finite nonnegative float.');- if (source.map) {- if (!maps.has(source.map)) {- const image = source.map.image;- if (!image || image.width * image.height > limits.maxTexturePixels) throw new Error('Base color image is missing or exceeds maxTexturePixels.');- maps.set(source.map, {+ for (const [field, , colorSpace] of MATERIAL_TEXTURES) {+ const texture = source[field === 'metallicRoughnessMap' ? 'metalnessMap' : field === 'occlusionMap' ? 'aoMap' : field];+ if (!texture) continue;+ if (!maps.has(texture)) maps.set(texture, new Map());+ const descriptors = maps.get(texture);+ if (!descriptors.has(colorSpace)) {+ const image = texture.image;+ if (!image || image.width * image.height > limits.maxTexturePixels) throw new Error(`${field} image is missing or exceeds maxTexturePixels.`);+ const descriptor = {image,uvChannel: 0,- wrapS: WRAPPING[source.map.wrapS],- wrapT: WRAPPING[source.map.wrapT],- minFilter: FILTERING[source.map.minFilter],- magFilter: FILTERING[source.map.magFilter],+ wrapS: WRAPPING[texture.wrapS],+ wrapT: WRAPPING[texture.wrapT],+ minFilter: FILTERING[texture.minFilter],+ magFilter: FILTERING[texture.magFilter],flipY: false,- colorSpace: 'srgb',- });+ colorSpace,+ };+ textureDescriptorInfo(descriptor);+ descriptors.set(colorSpace, descriptor);}- material.map = maps.get(source.map);+ material[field] = descriptors.get(colorSpace);}return material;}@@ -422,6 +455,7 @@ function releaseParsed(gltf) {const geometries = new Set();const materials = new Set();const textures = new Set();+ const images = new Set();for (const scene of gltf.scenes) {scene.traverse(node => {if (node.geometry) geometries.add(node.geometry);@@ -434,9 +468,10 @@ function releaseParsed(gltf) {geometries.forEach(geometry => geometry.dispose());materials.forEach(material => material.dispose());textures.forEach(texture => {- texture.image?.close?.();+ if (texture.image) images.add(texture.image);texture.dispose();});+ images.forEach(image => image.close?.());}/** Parse a bounded glTF 2.0 asset into Renderer67 parts. Three.js only decodes the asset. */@@ -469,8 +504,9 @@ export async function parseGltf(data, options = {}) {if (node.isSkinnedMesh || node.morphTargetInfluences?.length) throw new Error('Skinning and morph targets are unsupported.');if (Array.isArray(node.material)) throw new Error('Multiple materials on one decoded primitive are unsupported.');const materialIndex = gltf.parser.associations.get(node.material)?.materials;- if (document.materials?.[materialIndex]?.pbrMetallicRoughness?.baseColorTexture && !node.material.map) {- throw new Error('Base color texture failed to decode. Use a valid PNG or JPEG image.');+ for (const [field, sourceField] of MATERIAL_TEXTURES) {+ const decodedField = field === 'metallicRoughnessMap' ? 'metalnessMap' : field === 'occlusionMap' ? 'aoMap' : field;+ if (materialTexture(document.materials?.[materialIndex] ?? {}, sourceField) && !node.material[decodedField]) throw new Error(`${sourceField} failed to decode. Use a valid PNG or JPEG image.`);}const determinant = node.matrixWorld.determinant();if (!Number.isFinite(determinant) || Math.abs(determinant) < 1e-12) throw new Error('Mesh world transform is singular or non-finite.');@@ -481,10 +517,10 @@ export async function parseGltf(data, options = {}) {if (actualVertices > limits.maxVertices) throw new Error('Decoded geometry exceeds maxVertices.');geometries.set(geometryKey, convertGeometry(node.geometry, mirrored));}- if (!materials.has(node.material)) materials.set(node.material, convertMaterial(node.material, limits, maps));+ if (!materials.has(node.material)) materials.set(node.material, convertMaterial(node.material, limits, maps, document.materials?.[materialIndex]));const geometry = geometries.get(geometryKey);const material = materials.get(node.material);- if (material.map && !geometry.uvs) throw new Error('A base color texture requires TEXCOORD_0.');+ if (MATERIAL_TEXTURES.some(([field]) => material[field]) && !geometry.uvs) throw new Error('Material textures require TEXCOORD_0.');const part = { name: node.name || `glTF mesh ${parts.length + 1}`, geometry, matrix: new Float32Array(node.matrixWorld.elements), material };if (!Array.from(part.matrix).every(Number.isFinite)) throw new Error('Mesh world matrix must be finite.');parts.push(part);diff --git a/src/renderer.js b/src/renderer.jsindex f39322a6..1ef89e49 100644--- a/src/renderer.js+++ b/src/renderer.js@@ -7,16 +7,57 @@ import { resolveEffects } from './effects.js';const MATERIAL_TAGS = { armor: 1, floor: 2, water: 3, foliage: 4, terrain: 5, grass: 7, fire: 8, smoke: 9, unlit: 10 };const INSTANCE_STRIDE = 41;+const ZERO_VECTOR = Object.freeze([0, 0, 0]);+const MATERIAL_MAPS = ['map', 'normalMap', 'metallicRoughnessMap', 'occlusionMap', 'emissiveMap'];+const MAP_UNIFORMS = ['baseMap', 'normalMap', 'metallicRoughnessMap', 'occlusionMap', 'emissiveMap'];+const MAP_FLAGS = ['hasBaseMap', 'hasNormalMap', 'hasMetallicRoughnessMap', 'hasOcclusionMap', 'hasEmissiveMap'];+const DEFAULT_NORMAL_SCALE = [1, 1];+const PROCEDURAL_MATERIAL_TAGS = new Set(['water', 'foliage', 'grass', 'terrain', 'floor', 'fire', 'smoke']);-function validateTransform(part) {- const finiteFloat = value => Number.isFinite(value) && Number.isFinite(Math.fround(value));- if (part.matrix?.length !== 16 || !Array.from(part.matrix).every(finiteFloat)) throw new Error(`Invalid transform: ${part.name}`);- const normalMatrix = mat3.normalFromMat4(mat3.create(), part.matrix);- if (!normalMatrix || !Array.from(normalMatrix).every(Number.isFinite)) throw new Error(`Singular transform: ${part.name}`);- for (const value of [part.material.color, part.material.emissiveColor ?? part.material.color, part.assembly?.offset ?? [0, 0, 0], part.assembly?.detailOffset ?? [0, 0, 0]]) {- if (value.length !== 3 || !Array.from(value).every(finiteFloat)) throw new Error(`Invalid instance vector: ${part.name}`);+function validateMaterialMaps(material) {+ if (PROCEDURAL_MATERIAL_TAGS.has(material.tag)) {+ for (let index = 1; index < MATERIAL_MAPS.length; index++) {+ if (material[MATERIAL_MAPS[index]]) throw new Error('Material maps require a standard PBR material tag. Procedural tags are unsupported.');+ }+ }+ if (material.tag === 'unlit' && (material.normalMap || material.metallicRoughnessMap || material.occlusionMap)) {+ throw new Error('Unlit materials support only base and emissive maps.');+ }+ const normalScale = material.normalScale ?? DEFAULT_NORMAL_SCALE;+ if (normalScale.length !== 2 || !Number.isFinite(normalScale[0]) || !Number.isFinite(normalScale[1]) || !Number.isFinite(Math.fround(normalScale[0])) || !Number.isFinite(Math.fround(normalScale[1]))) throw new Error('normalScale must contain two finite floats.');+ const occlusionStrength = material.occlusionStrength ?? 1;+ if (!Number.isFinite(occlusionStrength) || occlusionStrength < 0 || occlusionStrength > 1) throw new Error('occlusionStrength must be within zero and one.');+}++function materialMapState(material) {+ validateMaterialMaps(material);+ const normalScale = material.normalScale ?? DEFAULT_NORMAL_SCALE;+ const occlusionStrength = material.occlusionStrength ?? 1;+ return [...MATERIAL_MAPS.map(field => material[field] ?? null), normalScale[0], normalScale[1], occlusionStrength];+}++function hasMaterialMap(material) {+ return MATERIAL_MAPS.some(field => material[field]);+}++function finiteFloat(value) {+ return Number.isFinite(value) && Number.isFinite(Math.fround(value));+}++function finiteVector(value, size) {+ if (value?.length !== size) return false;+ for (let index = 0; index < size; index++) if (!finiteFloat(value[index])) return false;+ return true;+}++function validateTransform(part, normalMatrix = mat3.create()) {+ if (!finiteVector(part.matrix, 16)) throw new Error(`Invalid transform: ${part.name}`);+ if (!mat3.normalFromMat4(normalMatrix, part.matrix) || !finiteVector(normalMatrix, 9)) throw new Error(`Singular transform: ${part.name}`);+ if (!finiteVector(part.material.color, 3) || !finiteVector(part.material.emissiveColor ?? part.material.color, 3) ||+ !finiteVector(part.assembly?.offset ?? ZERO_VECTOR, 3) || !finiteVector(part.assembly?.detailOffset ?? ZERO_VECTOR, 3)) {+ throw new Error(`Invalid instance vector: ${part.name}`);}- if (![part.material.metallic, part.material.roughness, part.material.emission ?? 0].every(finiteFloat)) throw new Error(`Invalid material: ${part.name}`);+ if (!finiteFloat(part.material.metallic) || !finiteFloat(part.material.roughness) || !finiteFloat(part.material.emission ?? 0)) throw new Error(`Invalid material: ${part.name}`);return normalMatrix;}@@ -25,9 +66,12 @@ function packInstance(data, index, part, normalMatrix) {data.set(part.matrix, offset);data.set(normalMatrix, offset + 16);data.set(part.material.color, offset + 25);- data.set([part.material.metallic, part.material.roughness, part.material.emission ?? 0, MATERIAL_TAGS[part.material.tag] ?? 0], offset + 28);- data.set(part.assembly?.offset ?? [0, 0, 0], offset + 32);- data.set(part.assembly?.detailOffset ?? [0, 0, 0], offset + 35);+ data[offset + 28] = part.material.metallic;+ data[offset + 29] = part.material.roughness;+ data[offset + 30] = part.material.emission ?? 0;+ data[offset + 31] = MATERIAL_TAGS[part.material.tag] ?? 0;+ data.set(part.assembly?.offset ?? ZERO_VECTOR, offset + 32);+ data.set(part.assembly?.detailOffset ?? ZERO_VECTOR, offset + 35);data.set(part.material.emissiveColor ?? part.material.color, offset + 38);}@@ -73,16 +117,24 @@ function groundPart() {export function groupParts(parts, batching = true) {const groups = new Map();+ const batches = [];for (const part of parts) {validateTransform(part);const key = batching ? part.geometry : part;if (!groups.has(key)) groups.set(key, new Map());- const maps = groups.get(key);- const map = part.material.map ?? null;- if (!maps.has(map)) maps.set(map, []);- maps.get(map).push(part);+ let maps = groups.get(key);+ for (const value of materialMapState(part.material)) {+ if (!maps.has(value)) maps.set(value, new Map());+ maps = maps.get(value);+ }+ if (!maps.has('parts')) {+ const batch = [];+ maps.set('parts', batch);+ batches.push(batch);+ }+ maps.get('parts').push(part);}- return [...groups.values()].flatMap(maps => [...maps.values()]);+ return batches;}export function textureDescriptorInfo(map, maximumSize = Infinity) {@@ -90,6 +142,7 @@ export function textureDescriptorInfo(map, maximumSize = Infinity) {const height = map.image?.naturalHeight ?? map.image?.height;if (!Number.isInteger(width) || !Number.isInteger(height) || width <= 0 || height <= 0 || width > maximumSize || height > maximumSize) throw new Error('Texture image dimensions are invalid or exceed MAX_TEXTURE_SIZE.');if ((map.uvChannel ?? 0) !== 0) throw new Error('Only texture UV channel 0 is supported.');+ if (map.transform || map.offset || map.repeat || map.rotation !== undefined || map.extensions && Object.keys(map.extensions).length) throw new Error('Texture transforms and extensions are unsupported. Bake them into UV channel 0.');if (map.colorSpace && !['srgb', 'linear'].includes(map.colorSpace)) throw new Error('Texture color space must be srgb or linear.');const wrapS = map.wrapS ?? 10497;const wrapT = map.wrapT ?? 10497;@@ -128,18 +181,32 @@ export class Renderer67 {this.buffers = [];this.batches = [];this.partLocations = new Map();+ this.updateBatches = new Set();this.textures = new Map();this.textureBytes = 4;this.shadowsDirty = true;const groups = groupParts(ground ? [...parts, groundPart()] : parts, batching);const textureLimit = this.context.getParameter(this.context.MAX_TEXTURE_SIZE);- const maps = new Set(groups.map(group => group[0].material.map).filter(Boolean));- for (const map of maps) this.textureBytes += textureDescriptorInfo(map, textureLimit).bytes;+ const maps = new Set();+ for (const group of groups) {+ for (const field of MATERIAL_MAPS) {+ const map = group[0].material[field];+ if (!map) continue;+ const info = textureDescriptorInfo(map, textureLimit);+ if (['normalMap', 'metallicRoughnessMap', 'occlusionMap'].includes(field) && map.colorSpace !== 'linear') throw new Error(`${field} requires a linear texture descriptor.`);+ if (field === 'emissiveMap' && (map.colorSpace ?? 'srgb') !== 'srgb') throw new Error('emissiveMap requires an srgb texture descriptor.');+ if (!maps.has(map)) this.textureBytes += info.bytes;+ maps.add(map);+ }+ }this.capabilities.maximumTextureSize = textureLimit;for (const group of groups) {const geometry = group[0].geometry;if (geometry.uvs && geometry.uvs.length !== geometry.positions.length / 3 * 2) throw new Error('Geometry UV count must match the vertex count.');- if (group[0].material.map && !geometry.uvs) throw new Error('Textured geometry requires UV channel 0.');+ if (hasMaterialMap(group[0].material) && !geometry.uvs) throw new Error('Textured geometry requires UV channel 0.');+ for (const coordinate of geometry.uvs ?? []) {+ if (!Number.isFinite(coordinate)) throw new Error('Geometry UVs must be finite.');+ }if (geometry.colors && geometry.colors.length !== geometry.positions.length) throw new Error('Geometry colors must contain RGB for every vertex.');}const expectedGeometryBytes = groups.reduce((total, group) => total + ['positions', 'normals', 'indices', 'uvs', 'colors'].reduce((bytes, field) => bytes + (group[0].geometry[field]?.byteLength ?? 0), 0) + group.length * INSTANCE_STRIDE * 4, 0);@@ -151,7 +218,7 @@ export class Renderer67 {this.inverseViewProjection = mat4.create();this.program = compileProgram(this.context, benchmark ? benchmarkVertexShader : vertexShader, benchmark ? benchmarkFragmentShader : fragmentShader);this.depthProgram = compileProgram(this.context, depthVertexShader, depthFragmentShader);- this.uniforms = Object.fromEntries(['viewProjection', 'lightProjection', 'eye', 'armorColor', 'armorSurface', 'exposure', 'inspection', 'shadowMap', 'baseMap', 'hasBaseMap', 'hdrEnabled', 'time', 'wind', 'worldMode', 'daylight', 'lightDirection', 'fogColor', 'fogDensity', 'waterRipple', 'rippleTime', 'explosionProgress', 'explosionCenter', 'assemblyAmount'].map((name) => [name, this.context.getUniformLocation(this.program, name)]));+ this.uniforms = Object.fromEntries(['viewProjection', 'lightProjection', 'eye', 'armorColor', 'armorSurface', 'exposure', 'inspection', 'shadowMap', ...MAP_UNIFORMS, ...MAP_FLAGS, 'normalScale', 'occlusionStrength', 'hdrEnabled', 'time', 'wind', 'worldMode', 'daylight', 'lightDirection', 'fogColor', 'fogDensity', 'waterRipple', 'rippleTime', 'explosionProgress', 'explosionCenter', 'assemblyAmount'].map((name) => [name, this.context.getUniformLocation(this.program, name)]));if (!benchmark) {this.postProgram = compileProgram(this.context, fullscreenVertex, postFragment);this.skyProgram = compileProgram(this.context, fullscreenVertex, skyFragment);@@ -234,7 +301,7 @@ export class Renderer67 {context.enableVertexAttribArray(13);context.vertexAttribPointer(13, 2, context.FLOAT, false, 0, 0);} else {- if (parts[0].material.map) throw new Error('Textured geometry requires UV channel 0.');+ if (hasMaterialMap(parts[0].material)) throw new Error('Textured geometry requires UV channel 0.');context.disableVertexAttribArray(13);context.vertexAttrib2f(13, 0, 0);}@@ -265,30 +332,41 @@ export class Renderer67 {this.attribute(15, 3, stride * 4, 152);context.bindVertexArray(null);const map = parts[0].material.map ?? null;- const batch = { vertexArray, instanceBuffer, instanceData, texture: this.createTexture(map), map, indexCount: geometry.indices.length, instanceCount: parts.length, floor: parts[0].material.tag === 'floor' };- parts.forEach((part, index) => this.partLocations.set(part, { batch, index, geometry: part.geometry, map }));+ const mapState = materialMapState(parts[0].material);+ const textures = mapState.slice(0, 5).map(descriptor => this.createTexture(descriptor));+ const batch = { vertexArray, instanceBuffer, instanceData, textures, mapState, texture: textures[0], map, indexCount: geometry.indices.length, instanceCount: parts.length, floor: parts[0].material.tag === 'floor' };+ parts.forEach((part, index) => this.partLocations.set(part, { batch, index, geometry: part.geometry, map, mapState, normalMatrix: mat3.create() }));return batch;}updateParts(parts, { shadows = true } = {}) {- const prepared = parts.map(part => {+ // Preflight every part before touching packed data or submitting GPU writes.+ for (const part of parts) {const location = this.partLocations.get(part);if (!location) throw new Error(`Unknown part identity: ${part.name}`);if (part.geometry !== location.geometry) throw new Error(`Geometry changes require a new renderer: ${part.name}`);if ((part.material.map ?? null) !== location.map) throw new Error(`Texture map changes require a new renderer: ${part.name}`);- return { part, location, normalMatrix: validateTransform(part) };- });- const batches = new Set();- for (const { part, location, normalMatrix } of prepared) {- packInstance(location.batch.instanceData, location.index, part, normalMatrix);- batches.add(location.batch);+ validateMaterialMaps(part.material);+ const normalScale = part.material.normalScale ?? DEFAULT_NORMAL_SCALE;+ const mapState = location.mapState;+ for (let index = 0; index < MATERIAL_MAPS.length; index++) {+ if ((part.material[MATERIAL_MAPS[index]] ?? null) !== mapState[index]) throw new Error(`Material map or scale changes require a new renderer: ${part.name}`);+ }+ if (normalScale[0] !== mapState[5] || normalScale[1] !== mapState[6] || (part.material.occlusionStrength ?? 1) !== mapState[7]) throw new Error(`Material map or scale changes require a new renderer: ${part.name}`);+ validateTransform(part, location.normalMatrix);}- for (const batch of batches) {+ this.updateBatches.clear();+ for (const part of parts) {+ const location = this.partLocations.get(part);+ packInstance(location.batch.instanceData, location.index, part, location.normalMatrix);+ this.updateBatches.add(location.batch);+ }+ for (const batch of this.updateBatches) {this.context.bindBuffer(this.context.ARRAY_BUFFER, batch.instanceBuffer);this.context.bufferSubData(this.context.ARRAY_BUFFER, 0, batch.instanceData);}- if (shadows && prepared.length > 0) this.shadowsDirty = true;- return prepared.length;+ if (shadows && parts.length > 0) this.shadowsDirty = true;+ return parts.length;}attribute(location, size, stride, offset) {@@ -484,10 +562,14 @@ export class Renderer67 {drawBatch(batch, textured = false) {if (textured && !this.benchmark) {- this.context.activeTexture(this.context.TEXTURE1);- this.context.bindTexture(this.context.TEXTURE_2D, batch.texture);- this.context.uniform1i(this.uniforms.baseMap, 1);- this.context.uniform1f(this.uniforms.hasBaseMap, batch.map ? 1 : 0);+ for (let index = 0; index < MATERIAL_MAPS.length; index++) {+ this.context.activeTexture(this.context.TEXTURE0 + index + 1);+ this.context.bindTexture(this.context.TEXTURE_2D, batch.textures[index]);+ this.context.uniform1i(this.uniforms[MAP_UNIFORMS[index]], index + 1);+ this.context.uniform1f(this.uniforms[MAP_FLAGS[index]], batch.mapState[index] ? 1 : 0);+ }+ this.context.uniform2f(this.uniforms.normalScale, batch.mapState[5], batch.mapState[6]);+ this.context.uniform1f(this.uniforms.occlusionStrength, batch.mapState[7]);}this.context.bindVertexArray(batch.vertexArray);this.context.drawElementsInstanced(this.context.TRIANGLES, batch.indexCount, this.context.UNSIGNED_INT, 0, batch.instanceCount);diff --git a/src/shaders.js b/src/shaders.jsindex 454322b2..56ca986c 100644--- a/src/shaders.js+++ b/src/shaders.js@@ -114,6 +114,16 @@ uniform float explosionProgress;uniform sampler2D shadowMap;uniform sampler2D baseMap;uniform float hasBaseMap;+uniform sampler2D normalMap;+uniform sampler2D metallicRoughnessMap;+uniform sampler2D occlusionMap;+uniform sampler2D emissiveMap;+uniform float hasNormalMap;+uniform float hasMetallicRoughnessMap;+uniform float hasOcclusionMap;+uniform float hasEmissiveMap;+uniform vec2 normalScale;+uniform float occlusionStrength;uniform float hdrEnabled;out vec4 outputColor;const float PI = 3.14159265359;@@ -190,14 +200,44 @@ vec3 toneMap(vec3 color) {return clamp((color * (2.51 * color + 0.03)) / (color * (2.43 * color + 0.59) + 0.14), 0.0, 1.0);}+vec3 mappedNormal(vec3 normal) {+ vec3 positionX = dFdx(worldPosition);+ vec3 positionY = dFdy(worldPosition);+ vec2 uvX = dFdx(textureUV);+ vec2 uvY = dFdy(textureUV);+ float uvScale = max(max(abs(uvX.x), abs(uvX.y)), max(abs(uvY.x), abs(uvY.y)));+ if (uvScale == 0.0) return normal;+ uvX /= uvScale;+ uvY /= uvScale;+ float determinant = uvX.x * uvY.y - uvX.y * uvY.x;+ // Degenerate UVs have no tangent basis and retain the geometric normal.+ if (abs(determinant) < 1e-7) return normal;+ vec3 tangent = (positionX * uvY.y - positionY * uvX.y) / determinant;+ vec3 bitangent = (positionY * uvX.x - positionX * uvY.x) / determinant;+ tangent -= normal * dot(normal, tangent);+ float tangentScale = max(max(abs(tangent.x), abs(tangent.y)), abs(tangent.z));+ if (tangentScale == 0.0) return normal;+ tangent /= tangentScale;+ tangent = normalize(tangent);+ float handedness = dot(cross(normal, tangent), bitangent) < 0.0 ? -1.0 : 1.0;+ bitangent = normalize(cross(normal, tangent)) * handedness;+ vec3 sampled = texture(normalMap, textureUV).xyz * 2.0 - 1.0;+ sampled.xy *= normalScale;+ vec3 mapped = mat3(tangent, bitangent, normal) * sampled;+ return dot(mapped, mapped) > 1e-12 ? normalize(mapped) : normal;+}+void main() {vec3 normal = normalize(worldNormal);+ if (hasNormalMap > 0.5) normal = mappedNormal(normal);vec3 viewDirection = normalize(eye - worldPosition);vec3 color = mix(baseColor, armorColor, step(0.5, surface.w) * (1.0 - step(1.5, surface.w)));color *= vertexTint;if (hasBaseMap > 0.5) color *= texture(baseMap, textureUV).rgb;+ vec3 emission = emissionColor * surface.z;+ if (hasEmissiveMap > 0.5) emission *= texture(emissiveMap, textureUV).rgb;if (surface.w == 10.0) {- vec3 radiance = color * exposure + emissionColor * surface.z;+ vec3 radiance = color * exposure + emission;outputColor = vec4(hdrEnabled > 0.5 ? radiance : pow(max(radiance, vec3(0)), vec3(1.0 / 2.2)), 1.0);return;}@@ -207,6 +247,12 @@ void main() {metallic = armorSurface.x;roughness = armorSurface.y;}+ if (hasMetallicRoughnessMap > 0.5) {+ vec4 sampled = texture(metallicRoughnessMap, textureUV);+ metallic *= sampled.b;+ roughness *= sampled.g;+ }+ roughness = clamp(roughness, 0.075, 1.0);vec3 normalChange = max(abs(dFdx(normal)), abs(dFdy(normal)));roughness = clamp(sqrt(roughness * roughness + dot(normalChange, normalChange) * 0.3), 0.075, 1.0);if (surface.w == 3.0) {@@ -245,10 +291,12 @@ void main() {radiance += illuminate(normal, viewDirection, normalize(vec3(4.0, 2.0, -3.0)), mix(vec3(0.8, 2.0, 1.8), vec3(0.12, 0.17, 0.20) * daylight, worldMode), color, metallic, roughness);radiance += illuminate(normal, viewDirection, normalize(vec3(1.0, 2.0, 5.0)), vec3(0.6, 0.7, 0.8) * mix(1.0, 0.25 * daylight, worldMode), color, metallic, roughness);vec3 reflectance = fresnel(max(dot(normal, viewDirection), 0.0), mix(vec3(0.04), color, metallic));- radiance += studio(reflect(-viewDirection, normal), roughness) * reflectance * (1.0 - roughness * 0.55) * mix(1.0, 0.5 * daylight, worldMode);- radiance += color * (1.0 - metallic) * mix(vec3(0.16, 0.20, 0.22), vec3(0.19, 0.25, 0.30) * max(daylight, 0.08), worldMode) * (0.45 + 0.55 * max(normal.y, 0.0));+ float occlusion = 1.0;+ if (hasOcclusionMap > 0.5) occlusion = mix(1.0, texture(occlusionMap, textureUV).r, occlusionStrength);+ radiance += studio(reflect(-viewDirection, normal), roughness) * reflectance * (1.0 - roughness * 0.55) * mix(1.0, 0.5 * daylight, worldMode) * occlusion;+ radiance += color * (1.0 - metallic) * mix(vec3(0.16, 0.20, 0.22), vec3(0.19, 0.25, 0.30) * max(daylight, 0.08), worldMode) * (0.45 + 0.55 * max(normal.y, 0.0)) * occlusion;if (surface.w == 4.0 || surface.w == 7.0) radiance += color * max(dot(-normal, normalize(lightDirection)), 0.0) * 0.3 * daylight;- radiance += emissionColor * surface.z;+ radiance += emission;if (surface.w == 3.0) {float reflectivity = 0.20 + 0.65 * pow(1.0 - max(dot(normal, viewDirection), 0.0), 3.0);vec3 reflection = mix(vec3(0.12, 0.24, 0.28), vec3(0.40, 0.63, 0.78), clamp(reflect(-viewDirection, normal).y, 0.0, 1.0));diff --git a/tests/gltf.test.js b/tests/gltf.test.jsindex c1a486c5..7a5987b5 100644--- a/tests/gltf.test.js+++ b/tests/gltf.test.js@@ -1,5 +1,6 @@import assert from 'node:assert/strict';import test from 'node:test';+import { Texture } from 'three';import { mat4 } from 'gl-matrix';import { exportGlb } from '../src/export.js';import { GLTF_CAPABILITIES, loadGltf, parseGltf } from '../src/gltf.js';@@ -142,7 +143,7 @@ test('unsupported features fail explicitly before loading resources', async () =[document => { document.meshes[0].primitives[0].mode = 1; }, /TRIANGLES/],[document => { document.materials[0].alphaMode = 'BLEND'; }, /alpha mode/],[document => { document.materials[0].doubleSided = true; }, /Double-sided/],- [document => { document.materials[0].normalTexture = { index: 0 }; }, /texture channels/],+ [document => { document.materials[0].normalTexture = { index: 0 }; }, /normalTexture texture index/],[document => { document.extensionsRequired = ['KHR_draco_mesh_compression']; }, /KHR_draco/],[document => { document.materials[0].extensions = { KHR_materials_clearcoat: {} }; }, /KHR_materials_clearcoat/],[document => { document.buffers[0].uri = 'external.bin'; }, /baseUrl/],@@ -278,3 +279,89 @@ test('vertex colors reject nonopaque alpha and invalid RGB factors explicitly',})), expected);}});++const PNG_IMAGE = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAIAAAACCAYAAABytg0kAAAAEklEQVR4AWI6k2b8H4SZGKAAAAAA//8VS4tGAAAABklEQVQDAEBuBM3uhq5wAAAAAElFTkSuQmCC';++function addMaterialMaps(document) {+ document.images = [{ uri: PNG_IMAGE }];+ document.samplers = [{ wrapS: 33071, wrapT: 33648, minFilter: 9728, magFilter: 9729 }];+ document.textures = [{ source: 0, sampler: 0 }];+ const material = document.materials[0];+ material.pbrMetallicRoughness.baseColorTexture = { index: 0 };+ material.pbrMetallicRoughness.metallicRoughnessTexture = { index: 0 };+ material.normalTexture = { index: 0, scale: 0.35 };+ material.occlusionTexture = { index: 0, strength: 0.4 };+ material.emissiveTexture = { index: 0 };+}++test('all glTF map channels preserve sampler, linear data, sRGB color, scales, sharing and image disposal', async context => {+ const previousBitmap = globalThis.createImageBitmap;+ const previousSelf = globalThis.self;+ globalThis.self = globalThis;+ let decoded = 0;+ let closed = 0;+ globalThis.createImageBitmap = async () => {+ decoded++;+ return { width: 2, height: 2, close() { closed++; } };+ };+ context.after(() => {+ if (previousBitmap) globalThis.createImageBitmap = previousBitmap;+ else delete globalThis.createImageBitmap;+ if (previousSelf) globalThis.self = previousSelf;+ else delete globalThis.self;+ });+ const disposedTextures = new Set();+ const originalDispose = Texture.prototype.dispose;+ context.mock.method(Texture.prototype, 'dispose', function () {+ disposedTextures.add(this);+ return originalDispose.call(this);+ });+ const asset = await parseGltf(triangleAsset(addMaterialMaps), { maxTexturePixels: 4 });+ const material = asset.parts[0].material;+ assert.equal(material, asset.parts[1].material);+ assert.deepEqual(material.normalScale, [0.35, 0.35]);+ assert.equal(material.occlusionStrength, 0.4);+ assert.equal(material.map, material.emissiveMap);+ assert.equal(material.normalMap, material.metallicRoughnessMap);+ assert.equal(material.normalMap, material.occlusionMap);+ assert.notEqual(material.map, material.normalMap);+ assert.equal(material.map.image, material.normalMap.image);+ for (const field of ['map', 'normalMap', 'metallicRoughnessMap', 'occlusionMap', 'emissiveMap']) {+ const descriptor = material[field];+ assert.equal(descriptor.colorSpace, ['map', 'emissiveMap'].includes(field) ? 'srgb' : 'linear');+ assert.equal(descriptor.uvChannel, 0);+ assert.equal(descriptor.flipY, false);+ assert.equal(descriptor.wrapS, 33071);+ assert.equal(descriptor.wrapT, 33648);+ assert.equal(descriptor.minFilter, 9728);+ assert.equal(descriptor.magFilter, 9729);+ }+ assert.equal(decoded, 1);+ asset.dispose();+ asset.dispose();+ assert.equal(closed, 1);+ assert.equal(disposedTextures.size, 1);+ assert.ok(GLTF_CAPABILITIES.supported.includes('normal/occlusion/emissive/metallic-roughness textures'));+});++test('map preflight rejects unsupported UVs, sampler states, invalid scales and missing geometry UVs', async () => {+ const changes = [+ [document => { document.materials[0].normalTexture.texCoord = 1; }, /TEXCOORD_0/],+ [document => { document.materials[0].normalTexture.scale = 'invalid'; }, /finite float/],+ [document => { document.materials[0].normalTexture.scale = '1'; }, /finite float/],+ [document => { document.materials[0].occlusionTexture.strength = 2; }, /strength/],+ [document => { document.samplers[0].wrapS = 4; }, /wrap mode/],+ [document => { document.samplers[0].minFilter = 4; }, /filtering/],+ [document => { document.textures[0].source = 4; }, /image index/],+ [document => { document.textures[0].sampler = 4; }, /sampler index/],+ [document => { delete document.meshes[0].primitives[0].attributes.TEXCOORD_0; }, /TEXCOORD_0/],+ [document => { document.materials[0].emissiveTexture.extensions = { KHR_texture_transform: { offset: [0.2, 0] } }; }, /KHR_texture_transform/],+ ];+ for (const [change, expected] of changes) {+ await assert.rejects(parseGltf(triangleAsset(document => {+ addMaterialMaps(document);+ change(document);+ })), expected);+ }+ await assert.rejects(parseGltf(triangleAsset(addMaterialMaps), { maxTexturePixels: 3 }), /maxTexturePixels/);+});diff --git a/tests/model.test.js b/tests/model.test.jsindex 2b1dae83..817d24c6 100644--- a/tests/model.test.js+++ b/tests/model.test.js@@ -4,6 +4,21 @@ import { createHash } from 'node:crypto';import { box, cylinder, sphere, torus } from '../src/geometry.js';import { createModel } from '../src/model.js';+test('sphere UVs preserve separate seam coordinates and cover every vertex', () => {+ const segments = 12;+ const rings = 8;+ const mesh = sphere(segments, rings);+ assert.equal(mesh.uvs.length, mesh.positions.length / 3 * 2);+ for (const value of mesh.uvs) assert.ok(Number.isFinite(value) && value >= 0 && value <= 1);+ for (let row = 0; row <= rings; row++) {+ const first = row * (segments + 1);+ const last = first + segments;+ assert.equal(mesh.uvs[first * 2], 0);+ assert.equal(mesh.uvs[last * 2], 1);+ for (let axis = 0; axis < 3; axis++) assert.ok(Math.abs(mesh.positions[first * 3 + axis] - mesh.positions[last * 3 + axis]) < 1e-6);+ }+});+function validateGeometry(mesh) {assert.ok(mesh.positions instanceof Float32Array);assert.ok(mesh.normals instanceof Float32Array);diff --git a/tests/renderer.test.js b/tests/renderer.test.jsindex 5e6c522f..6123c7bb 100644--- a/tests/renderer.test.js+++ b/tests/renderer.test.js@@ -1,6 +1,6 @@import test from 'node:test';import assert from 'node:assert/strict';-import { mat4 } from 'gl-matrix';+import { mat4, mat3 } from 'gl-matrix';import { Renderer67, groupParts, textureDescriptorInfo } from '../src/renderer.js';function part(name, geometry = {}, map) {@@ -12,7 +12,11 @@ function retainedRenderer(parts) {const renderer = Object.create(Renderer67.prototype);const batch = { instanceBuffer: {}, instanceData: new Float32Array(parts.length * 41).fill(7) };renderer.context = { ARRAY_BUFFER: 34962, bindBuffer() {}, bufferSubData(target, offset, data) { writes.push({ target, offset, data: Array.from(data) }); } };- renderer.partLocations = new Map(parts.map((item, index) => [item, { batch, index, geometry: item.geometry, map: item.material.map ?? null }]));+ renderer.partLocations = new Map(parts.map((item, index) => [item, {+ batch, index, geometry: item.geometry, map: item.material.map ?? null, normalMatrix: mat3.create(),+ mapState: ['map', 'normalMap', 'metallicRoughnessMap', 'occlusionMap', 'emissiveMap'].map(field => item.material[field] ?? null).concat(item.material.normalScale ?? [1, 1], item.material.occlusionStrength ?? 1),+ }]));+ renderer.updateBatches = new Set();renderer.shadowsDirty = false;return { renderer, batch, writes };}@@ -79,6 +83,26 @@ test('mixed invalid updates fail atomically before CPU or GPU instance data chanassert.equal(writes.length, 0);});+test('repeated instance updates retain normal buffers without allocating matrices per frame', () => {+ const parts = [part('first'), part('second')];+ const { renderer, batch } = retainedRenderer(parts);+ const normals = parts.map(item => renderer.partLocations.get(item).normalMatrix);+ const dirtyBatches = renderer.updateBatches;+ const originalCreate = mat3.create;+ mat3.create = () => { throw new Error('Unexpected per-frame matrix allocation'); };+ try {+ for (let frame = 0; frame < 20; frame++) {+ parts[0].matrix[12] = frame;+ renderer.updateParts(parts);+ }+ } finally {+ mat3.create = originalCreate;+ }+ assert.equal(batch.instanceData[12], 19);+ assert.equal(renderer.updateBatches, dirtyBatches);+ parts.forEach((item, index) => assert.equal(renderer.partLocations.get(item).normalMatrix, normals[index]));+});+test('texture descriptor preflight validates dimensions, channel, samplers and mipmap bytes', () => {const info = textureDescriptorInfo({ image: { width: 4, height: 4 }, colorSpace: 'srgb', uvChannel: 0 }, 16);assert.equal(info.bytes, 84);@@ -88,3 +112,119 @@ test('texture descriptor preflight validates dimensions, channel, samplers and massert.throws(() => textureDescriptorInfo({ image: { width: 4, height: 4 }, uvChannel: 1 }), /channel 0/);assert.throws(() => textureDescriptorInfo({ image: { width: 4, height: 4 }, minFilter: 4 }), /filtering/);});++test('all material map identities and fixed scale values partition instance batches', () => {+ for (const field of ['normalMap', 'metallicRoughnessMap', 'occlusionMap', 'emissiveMap']) {+ const geometry = {};+ const first = part('first', geometry);+ first.material[field] = {};+ const second = part('second', geometry);+ second.material[field] = first.material[field];+ assert.equal(groupParts([first, second]).length, 1);+ second.material[field] = {};+ assert.equal(groupParts([first, second]).length, 2);+ second.material[field] = first.material[field];+ second.material.normalScale = [0.5, -1];+ assert.equal(groupParts([first, second]).length, 2);+ second.material.normalScale = [1, 1];+ second.material.occlusionStrength = 0.3;+ assert.equal(groupParts([first, second]).length, 2);+ }+});++test('map and scale changes reject atomically before retained data uploads', () => {+ for (const field of ['normalMap', 'metallicRoughnessMap', 'occlusionMap', 'emissiveMap', 'normalScale', 'occlusionStrength']) {+ const parts = [part('moving'), part('changed')];+ const { renderer, batch, writes } = retainedRenderer(parts);+ parts[0].matrix[12] = 4;+ parts[1].material[field] = field === 'normalScale' ? [0.5, 1] : field === 'occlusionStrength' ? 0.2 : {};+ assert.throws(() => renderer.updateParts(parts), /map or scale changes/);+ assert.ok(batch.instanceData.every(value => value === 7));+ assert.equal(writes.length, 0);+ }+ assert.throws(() => groupParts([{ ...part('invalid'), material: { ...part('invalid').material, normalScale: [Infinity, 1] } }]), /normalScale/);+ assert.throws(() => groupParts([{ ...part('invalid'), material: { ...part('invalid').material, occlusionStrength: 2 } }]), /occlusionStrength/);+ const procedural = part('procedural');+ procedural.material.tag = 'water';+ procedural.material.metallicRoughnessMap = {};+ assert.throws(() => groupParts([procedural]), /Procedural tags/);+ procedural.material.tag = 'unlit';+ assert.throws(() => groupParts([procedural]), /Unlit materials/);+});++function preflightCanvas() {+ const context = {+ MAX_TEXTURE_SIZE: 3379, MAX_SAMPLES: 36183,+ getInternalformatParameter() { return []; },+ getParameter(parameter) { return parameter === this.MAX_TEXTURE_SIZE ? 8192 : 4; },+ createProgram() { throw new Error('Reached GPU allocation'); },+ };+ return { clientWidth: 64, clientHeight: 64, getContext() { return context; } };+}++test('texture budgets count every channel and charge shared descriptors once before GPU allocation', () => {+ const geometry = { positions: new Float32Array(9), normals: new Float32Array(9), indices: new Uint32Array([0, 1, 2]), uvs: new Float32Array(6) };+ for (const field of ['map', 'normalMap', 'metallicRoughnessMap', 'occlusionMap', 'emissiveMap']) {+ const item = part('large map', geometry);+ item.material[field] = { image: { width: 4096, height: 4096 }, colorSpace: field === 'map' || field === 'emissiveMap' ? 'srgb' : 'linear' };+ assert.throws(() => new Renderer67(preflightCanvas(), [item], { ground: false, memoryBudgetMiB: 32 }), /Memory budget/);+ }+ const shared = { image: { width: 1024, height: 1024 }, colorSpace: 'linear' };+ const item = part('shared map', geometry);+ item.material.normalMap = shared;+ item.material.metallicRoughnessMap = shared;+ item.material.occlusionMap = shared;+ assert.throws(() => new Renderer67(preflightCanvas(), [item], { ground: false, memoryBudgetMiB: 24 }), /Reached GPU allocation/);+ item.material.occlusionMap = { ...shared };+ assert.throws(() => new Renderer67(preflightCanvas(), [item], { ground: false, memoryBudgetMiB: 24 }), /Memory budget/);+ item.material.normalMap = { ...shared, colorSpace: 'srgb' };+ assert.throws(() => new Renderer67(preflightCanvas(), [item], { ground: false }), /requires a linear/);+ assert.throws(() => textureDescriptorInfo({ ...shared, rotation: 1 }), /transforms/);+});++test('GPU uploads use descriptor color spaces, cache shared maps, and dispose every cached texture', () => {+ const renderer = Object.create(Renderer67.prototype);+ const uploaded = [];+ const deleted = [];+ renderer.textures = new Map();+ renderer.buffers = [];+ renderer.batches = [];+ renderer.partLocations = new Map();+ renderer.releaseFrameTargets = () => {};+ renderer.context = {+ RGBA8: 32856, SRGB8_ALPHA8: 35907, MAX_TEXTURE_SIZE: 3379,+ getParameter(parameter) { return parameter === this.MAX_TEXTURE_SIZE ? 8192 : 0; },+ createTexture() { return {}; }, bindTexture() {}, pixelStorei() {}, texParameteri() {}, generateMipmap() {},+ texImage2D(...arguments_) { uploaded.push(arguments_[2]); },+ deleteTexture(texture) { if (texture) deleted.push(texture); }, deleteFramebuffer() {}, deleteProgram() {},+ };+ const color = { image: { width: 4, height: 4 }, colorSpace: 'srgb' };+ const data = { ...color, colorSpace: 'linear' };+ const first = renderer.createTexture(color);+ const second = renderer.createTexture(data);+ assert.equal(renderer.createTexture(data), second);+ assert.deepEqual(uploaded, [35907, 32856]);+ renderer.dispose();+ assert.deepEqual(deleted, [first, second]);+ assert.equal(renderer.textures.size, 0);+});++test('draw batches bind all channels with their flags and scalar uniforms', () => {+ const renderer = Object.create(Renderer67.prototype);+ const bindings = [];+ const uniforms = [];+ renderer.uniforms = Object.fromEntries(['baseMap', 'normalMap', 'metallicRoughnessMap', 'occlusionMap', 'emissiveMap', 'hasBaseMap', 'hasNormalMap', 'hasMetallicRoughnessMap', 'hasOcclusionMap', 'hasEmissiveMap', 'normalScale', 'occlusionStrength'].map(name => [name, name]));+ renderer.context = {+ TEXTURE0: 33984,+ activeTexture(unit) { bindings.push(unit); }, bindTexture() {}, bindVertexArray() {}, drawElementsInstanced() {},+ uniform1i(name, value) { uniforms.push([name, value]); },+ uniform1f(name, value) { uniforms.push([name, value]); },+ uniform2f(name, first, second) { uniforms.push([name, first, second]); },+ };+ renderer.drawBatch({ textures: [{}, {}, {}, {}, {}], mapState: [{}, {}, {}, null, {}, 0.5, -1, 0.4] }, true);+ assert.deepEqual(bindings, [33985, 33986, 33987, 33988, 33989]);+ assert.ok(uniforms.some(values => values[0] === 'hasOcclusionMap' && values[1] === 0));+ assert.ok(uniforms.some(values => values[0] === 'metallicRoughnessMap' && values[1] === 3));+ assert.ok(uniforms.some(values => values[0] === 'normalScale' && values[1] === 0.5 && values[2] === -1));+ assert.ok(uniforms.some(values => values[0] === 'occlusionStrength' && values[1] === 0.4));+});