3D engine that AI agents drive
Open glTF materials whose maps use different KHR_texture_transform (closes #457)
Nguyen Xuan An15d0c1a6c807
diff --git a/changes/457.md b/changes/457.mdnew file mode 100644index 00000000..5364362d--- /dev/null+++ b/changes/457.md@@ -0,0 +1 @@+- `loadGltf` and `parseGltf` now open a glTF whose material has maps with different `KHR_texture_transform` (issue #457), for example a tiled base color map beside an emissive map with no transform, instead of throwing. The loader keeps the transform that is cheapest to tile to and resamples the other maps into that UV space at load, with a `warnings` entry naming the material and map. A resampled map grows to at most 4 times its source pixels and never past `maxTextureImagePixels`. Maps that cannot be resampled (a ratio that is not a whole number, a clamped or mirrored sampler, a compressed texture) still fail, now with the material named. Scenes that load files without mixed transforms draw the same pixels.diff --git a/changes/457.size.md b/changes/457.size.mdnew file mode 100644index 00000000..f809f7ce--- /dev/null+++ b/changes/457.size.md@@ -0,0 +1,2 @@+- entry:gltf+lazy: 2445 bytes gzip (56643 to 59088) for the resampling module, which only a file with mixed texture transforms loads+- scene:gltf-box+lazy: 2426 bytes gzip (85257 to 87683), the same modulediff --git a/docs/gltf.md b/docs/gltf.mdindex 297ef50c..2af3dc06 100644--- a/docs/gltf.md+++ b/docs/gltf.md@@ -137,7 +137,7 @@ POINTS, LINES, LINE_LOOP and LINE_STRIP primitives are skipped with a warning th| Extension | Behavior || --- | --- || `KHR_mesh_quantization`, `KHR_materials_emissive_strength` | Supported. |-| `KHR_texture_transform` | Offset, rotation and scale are baked into `geometry.uvs`. All maps of one material must share one transform, except the normal map: it may differ by an offset and a positive scale (same rotation), which the shader applies on top of the baked UVs (`normalMapTransform` in `material-layer-shaders`). Any other difference fails the import. `texCoord` overrides are rejected. |+| `KHR_texture_transform` | Offset, rotation and scale are baked into `geometry.uvs`. The maps of one material share one baked transform. A normal map may differ by an offset and a positive scale (same rotation), which the shader applies on top of the baked UVs (`normalMapTransform` in `material-layer-shaders`). Any other map that differs is resampled at load into the shared UV space and named in `warnings`: the loader keeps the transform most maps have and tiles the rest, so it must differ by whole-number tilings (a tiled base color beside an untransformed emissive map). A resampled map grows to at most 4 times the pixels of its source and never past `maxTextureImagePixels`. A map that cannot be resampled (a clamped or mirrored sampler, a compressed texture, a non-integer ratio such as scale 2 against scale 3) fails the import with the material named. `texCoord` overrides are rejected. || `EXT_mesh_gpu_instancing` | The node expands into one part per instance and primitive. Parts of one primitive share one geometry object, so the renderer batches them. Skinned or morphed instancing is rejected. || `KHR_materials_unlit` | The material gets the renderer's `unlit` tag and shows its base color and base color map alone. Emissive, normal, occlusion and metallic-roughness maps and layers are dropped. || `KHR_lights_punctual` | Point and spot lights (up to the renderer limits of 16 point and 8 spot lights, in candela like the renderer) and the first directional light become `asset.lights`, a partial `environment`: `pointLights`, `spotLights`, and `keyColor` (color times lux), `lightDirection` and `keyIntensity` for the key light. Pass it as `Renderer67`'s `environment` option or a `frame.environment`. A spot's `penumbra` is `(outer - inner) / outer`. A light over the limits, a second directional light and an invalid light are skipped with a warning. The renderer has no calibrated photometric units, so judge the level by eye. |diff --git a/src/gltf-map-resample.js b/src/gltf-map-resample.jsnew file mode 100644index 00000000..e333199b--- /dev/null+++ b/src/gltf-map-resample.js@@ -0,0 +1,221 @@+// Opens a glTF material whose maps carry different KHR_texture_transform values. The first UV set holds one transform, so+// the maps that differ are resampled into that shared UV space once, at load time. parseGltf imports this module only for a+// file that has such a material, so it adds nothing to a scene that loads a clean file.++const IDENTITY_KEY = JSON.stringify([[0, 0], 0, [1, 1]]);+const REPEAT_WRAP = 10497;+const WHOLE_NUMBER_TOLERANCE = 1e-6;+// A resampled map may grow to this many times the pixels of its source: a 2 by 2 tiling at full density.+const MAX_GROWTH = 4;+// The decoded material field that holds each glTF material texture. Layer textures keep their glTF property name.+const SOURCE_FIELD = {+ baseColorTexture: 'map',+ metallicRoughnessTexture: 'metalnessMap',+ occlusionTexture: 'aoMap',+ emissiveTexture: 'emissiveMap',+};++const uvChannelOf = reference => reference.texCoord ?? 0;++// Compares transforms; the identity maps to the empty key, like the loader's own.+function uvTransformKey(transform) {+ const key = JSON.stringify([transform.offset, transform.rotation, transform.scale]);+ return key === IDENTITY_KEY ? '' : key;+}++function materialLabel(material, index) {+ return material?.name ? `"${material.name}" (material ${index})` : `material ${index}`;+}++/** The 2 by 2 matrix [a, b, c, d] of the UV transform, row-major: uv' = matrix * uv + offset. */+function linearPart({ rotation, scale }) {+ const cosine = Math.cos(rotation);+ const sine = Math.sin(rotation);+ return [cosine * scale[0], sine * scale[1], -sine * scale[0], cosine * scale[1]];+}++function multiply([a, b, c, d], [e, f, g, h]) {+ return [a * e + b * g, a * f + b * h, c * e + d * g, c * f + d * h];+}++function invert([a, b, c, d]) {+ const determinant = a * d - b * c;+ if (!Number.isFinite(determinant) || Math.abs(determinant) < 1e-12) return null;+ return [d / determinant, -b / determinant, -c / determinant, a / determinant];+}++/**+ * Where a map reads its own texture for a UV already baked with `shared`: ownUv = linear * sharedUv + offset. The result+ * is null when `linear` is not made of whole numbers, because the baked image is one tile that repeats once per UV unit+ * and only whole-number steps land on the same texel again after each repeat.+ */+function sharedToOwn(shared, own) {+ const inverse = invert(linearPart(shared));+ if (!inverse) return null;+ const linear = multiply(linearPart(own), inverse);+ const rounded = linear.map(Math.round);+ if (linear.some((value, index) => Math.abs(value - rounded[index]) > WHOLE_NUMBER_TOLERANCE)) return null;+ const [a, b, c, d] = rounded;+ const offset = [own.offset[0] - (a * shared.offset[0] + b * shared.offset[1]), own.offset[1] - (c * shared.offset[0] + d * shared.offset[1])];+ return { linear: rounded, offset };+}++function textureWrapsByRepeat(document, reference) {+ const sampler = document.samplers?.[document.textures?.[reference.index]?.sampler] ?? {};+ return (sampler.wrapS ?? REPEAT_WRAP) === REPEAT_WRAP && (sampler.wrapT ?? REPEAT_WRAP) === REPEAT_WRAP;+}++/** The maps of one material that read the first UV set and can be resampled: [property, reference, transform]. */+function resamplableMaps(material, { materialTextureReferences, textureUvTransform }) {+ return materialTextureReferences(material)+ .filter(([property, reference]) => property !== 'normalTexture' && uvChannelOf(reference) === 0)+ .map(([property, reference]) => [property, reference, textureUvTransform(reference)]);+}++/** The transform to share, and the resample of every map that differs from it. The cheapest tiling wins; null if none works. */+function cheapestSharing(document, maps) {+ const candidates = new Map();+ for (const [, , transform] of maps) {+ const key = uvTransformKey(transform);+ candidates.set(key, { transform, count: (candidates.get(key)?.count ?? 0) + 1 });+ }+ const ranked = [...candidates.entries()].sort((first, second) => second[1].count - first[1].count);+ let best = null;+ for (const [sharedKey, { transform: shared }] of ranked) {+ const resamples = [];+ let growth = 0;+ for (const [property, reference, transform] of maps) {+ if (uvTransformKey(transform) === sharedKey) continue;+ const placement = textureWrapsByRepeat(document, reference) ? sharedToOwn(shared, transform) : null;+ if (!placement) {+ growth = Infinity;+ break;+ }+ growth += Math.abs(placement.linear[0] * placement.linear[3] - placement.linear[1] * placement.linear[2]);+ resamples.push({ property, ...placement });+ }+ if (growth < (best?.growth ?? Infinity)) best = { shared, resamples, growth };+ }+ return best;+}++function writeSharedTransform(reference, shared) {+ const { KHR_texture_transform: previous, ...otherExtensions } = reference.extensions ?? {};+ const extensions = uvTransformKey(shared) === '' ? otherExtensions : { ...otherExtensions, KHR_texture_transform: { ...previous, offset: shared.offset, rotation: shared.rotation, scale: shared.scale } };+ if (Object.keys(extensions).length) reference.extensions = extensions;+ else delete reference.extensions;+}++/**+ * For every material whose maps differ, rewrites the document so that all its maps share one KHR_texture_transform and+ * returns { apply(decoded, limits) }, which resamples the planned maps of the decoded materials and returns one warning per map.+ * Returns null when no material differs. Throws, naming the material, when the maps cannot be brought into one UV space.+ */+export function planMapResampling(document, loaderHelpers) {+ const plans = new Map();+ (document.materials ?? []).forEach((material, index) => {+ const maps = resamplableMaps(material ?? {}, loaderHelpers);+ if (new Set(maps.map(([, , transform]) => uvTransformKey(transform))).size < 2) return;+ const sharing = cheapestSharing(document, maps);+ if (!sharing) {+ const names = maps.map(([property]) => property).join(', ');+ throw new Error(`Maps of ${materialLabel(material, index)} have KHR_texture_transform values that cannot share one UV space (${names}). They must repeat, read TEXCOORD_0, and differ by whole-number tilings of one of them.`);+ }+ for (const [, reference, transform] of maps) {+ if (uvTransformKey(transform) !== uvTransformKey(sharing.shared)) writeSharedTransform(reference, sharing.shared);+ }+ plans.set(index, sharing.resamples);+ });+ if (!plans.size) return null;+ return { apply: (decoded, limits) => applyMapResampling(decoded, plans, document, limits) };+}++function pixelsOf(image, name) {+ if (image.data) return image.data;+ if (typeof OffscreenCanvas !== 'function' && typeof document === 'undefined') throw new Error(`${name} cannot be read back to resample it: this runtime has no canvas.`);+ const canvas = typeof OffscreenCanvas === 'function' ? new OffscreenCanvas(image.width, image.height) : Object.assign(document.createElement('canvas'), { width: image.width, height: image.height });+ const context = canvas.getContext('2d', { willReadFrequently: true });+ if (!context) throw new Error(`${name} cannot be read back to resample it.`);+ context.drawImage(image, 0, 0);+ return context.getImageData(0, 0, image.width, image.height).data;+}++function wrapped(index, size) {+ return ((index % size) + size) % size;+}++function sampleBilinear(source, width, height, u, v, output, outputOffset) {+ const x = u * width - 0.5;+ const y = v * height - 0.5;+ const left = Math.floor(x);+ const top = Math.floor(y);+ const weightX = x - left;+ const weightY = y - top;+ for (let channel = 0; channel < 4; channel++) {+ const at = (column, row) => source[(wrapped(row, height) * width + wrapped(column, width)) * 4 + channel];+ const upper = at(left, top) * (1 - weightX) + at(left + 1, top) * weightX;+ const lower = at(left, top + 1) * (1 - weightX) + at(left + 1, top + 1) * weightX;+ output[outputOffset + channel] = Math.round(upper * (1 - weightY) + lower * weightY);+ }+}++/** Size of the resampled image: the source texel density kept, so tiling grows it, within the growth cap and the pixel limit. */+function resampledSize(image, { linear }, maxPixels) {+ const [a, b, c, d] = linear;+ let width = Math.max(1, Math.round(Math.hypot(a * image.width, c * image.height)));+ let height = Math.max(1, Math.round(Math.hypot(b * image.width, d * image.height)));+ const allowed = Math.min(MAX_GROWTH * image.width * image.height, maxPixels);+ const capped = width * height > allowed;+ if (capped) {+ const shrink = Math.sqrt(allowed / (width * height));+ width = Math.max(1, Math.floor(width * shrink));+ height = Math.max(1, Math.floor(height * shrink));+ }+ return { width, height, capped };+}++function resample(texture, placement, name, maxPixels) {+ if (texture.isCompressedTexture || !texture.image) throw new Error(`${name} is a compressed texture and cannot be resampled to a shared KHR_texture_transform.`);+ const { image } = texture;+ const source = pixelsOf(image, name);+ const { width, height, capped } = resampledSize(image, placement, maxPixels);+ const [a, b, c, d] = placement.linear;+ const data = new Uint8Array(width * height * 4);+ for (let row = 0; row < height; row++) {+ const sharedV = (row + 0.5) / height;+ for (let column = 0; column < width; column++) {+ const sharedU = (column + 0.5) / width;+ sampleBilinear(source, image.width, image.height, a * sharedU + b * sharedV + placement.offset[0], c * sharedU + d * sharedV + placement.offset[1], data, (row * width + column) * 4);+ }+ }+ return { texture: { ...texture, image: { width, height, data } }, from: [image.width, image.height], to: [width, height], capped };+}++/** Replaces each planned map of the decoded materials with its resampled copy, and returns one warning per map. */+function applyMapResampling(decoded, plans, document, limits) {+ const warnings = [];+ const copies = new Map();+ const handled = new Set();+ decoded.scene.traverse(node => {+ const material = node.isMesh ? node.material : null;+ if (!material || handled.has(material) || !plans.has(material.materialIndex)) return;+ handled.add(material);+ const label = materialLabel(document.materials[material.materialIndex], material.materialIndex);+ for (const placement of plans.get(material.materialIndex)) {+ const holder = SOURCE_FIELD[placement.property] ? material : material.layerTextures;+ const field = SOURCE_FIELD[placement.property] ?? placement.property;+ const texture = holder?.[field];+ if (!texture) continue;+ const key = `${placement.linear}|${placement.offset}`;+ if (!copies.has(texture)) copies.set(texture, new Map());+ const name = `${placement.property} of ${label}`;+ if (!copies.get(texture).has(key)) {+ const result = resample(texture, placement, name, limits.maxTextureImagePixels);+ copies.get(texture).set(key, result.texture);+ warnings.push(`Resampled ${name} from ${result.from.join('x')} to ${result.to.join('x')} to share the UV transform of the other maps${result.capped ? ' (capped at 4 times the source pixels or maxTextureImagePixels)' : ''}.`);+ }+ holder[field] = copies.get(texture).get(key);+ }+ });+ return warnings;+}diff --git a/src/gltf.js b/src/gltf.jsindex ecf04b3f..b6c0d827 100644--- a/src/gltf.js+++ b/src/gltf.js@@ -985,7 +985,17 @@ export async function parseGltf(data, options = {}) {const document = documentFrom(data, limits.maxBytes);const fallbackWarnings = await applyFallbacksTo(document);const decoders = options.decoders ?? {};- const { ignoredExtensions } = validateDocument(document, limits, allowedExtensionsFor(decoders));+ let resampler = null;+ let validated;+ try {+ validated = validateDocument(document, limits, allowedExtensionsFor(decoders));+ } catch (error) {+ // Maps with different transforms are resampled by a module that only a file with such a material loads.+ resampler = (await import('./gltf-map-resample.js')).planMapResampling(document, { materialTextureReferences, textureUvTransform });+ if (!resampler) throw error;+ validated = validateDocument(document, limits, allowedExtensionsFor(decoders));+ }+ const { ignoredExtensions } = validated;await loadLayerShadersFor(document);const warnings = [...fallbackWarnings, ...ignoredExtensions.map(extension => `${extension} is accepted but not rendered.`), ...skippedPrimitiveWarnings(document)];const dataBytes = typeof data === 'string' ? new TextEncoder().encode(data).byteLength : data.byteLength;@@ -997,6 +1007,7 @@ export async function parseGltf(data, options = {}) {let gltf;try {gltf = await decodeGltf({ document, glbBinary: binaryChunk(data), resourceBytes, decoders, limits, imageTargets: textureScaling.targetByImageIndex });+ if (resampler) warnings.push(...resampler.apply(gltf, limits));const parts = [];const bindings = [];const skinBindings = [];diff --git a/tests/gltf-extensions.test.js b/tests/gltf-extensions.test.jsindex c8e88c5b..d9a157d0 100644--- a/tests/gltf-extensions.test.js+++ b/tests/gltf-extensions.test.js@@ -115,12 +115,12 @@ test('KHR_texture_transform bakes one shared offset, rotation and scale into thetest('KHR_texture_transform rejects different transforms and texCoord overrides on one material', async context => {mockImageBitmap(context);- const moved = { offset: [0.5, 0] };- const metallicRoughnessMoved = document => {- addTexturedMaterial(document, [moved, moved]);- document.materials[0].pbrMetallicRoughness.metallicRoughnessTexture = { index: 0, extensions: { KHR_texture_transform: { offset: [0, 0.5] } } };+ const tiled = { scale: [2, 2] };+ const metallicRoughnessTiledThrice = document => {+ addTexturedMaterial(document, [tiled, tiled]);+ document.materials[0].pbrMetallicRoughness.metallicRoughnessTexture = { index: 0, extensions: { KHR_texture_transform: { scale: [3, 3] } } };};- await assert.rejects(parseGltf(triangleDocument({ edit: metallicRoughnessMoved })), /same KHR_texture_transform/);+ await assert.rejects(parseGltf(triangleDocument({ edit: metallicRoughnessTiledThrice })), /cannot share one UV space/);await assert.rejects(parseGltf(triangleDocument({ edit: document => addTexturedMaterial(document, [{ texCoord: 1 }, { texCoord: 1 }]) })), /texCoord/);});@@ -457,3 +457,81 @@ test('a compressed KTX2 format 67js does not upload fails with a clear message',const loader = ktx2LoaderReturning(compressedKtx2Texture(8, ETC1_RGB), { bptcSupported: true });await assert.rejects(parseGltf(ktx2BaseColorDocument(8), { decoders: { ktx2: loader } }), /does not upload/);});++// A 2 by 2 image whose four texels differ, with its pixels attached the way a decoded image carries them.+function patternBitmap() {+ const data = new Uint8Array([10, 0, 0, 255, 20, 0, 0, 255, 30, 0, 0, 255, 40, 0, 0, 255]);+ return { width: 2, height: 2, data, close() {} };+}++function mockPatternBitmap(context) {+ const previousBitmap = globalThis.createImageBitmap;+ const previousSelf = globalThis.self;+ globalThis.self = globalThis;+ globalThis.createImageBitmap = async () => patternBitmap();+ context.after(() => {+ if (previousBitmap) globalThis.createImageBitmap = previousBitmap;+ else delete globalThis.createImageBitmap;+ if (previousSelf) globalThis.self = previousSelf;+ else delete globalThis.self;+ });+}++function redAt(image, u, v) {+ const fraction = value => value - Math.floor(value);+ const column = Math.floor(fraction(u) * image.width);+ const row = Math.floor(fraction(v) * image.height);+ return image.data[(row * image.width + column) * 4];+}++function tiledBaseWithPlainEmissive(document, emissiveExtra = {}) {+ document.images = [{ uri: PNG_IMAGE }];+ document.textures = [{ source: 0 }];+ document.materials[0].name = 'Crate';+ document.materials[0].pbrMetallicRoughness.baseColorTexture = { index: 0, extensions: { KHR_texture_transform: { scale: [2, 2] } } };+ document.materials[0].emissiveTexture = { index: 0, ...emissiveExtra };+ document.extensionsUsed = ['KHR_texture_transform'];+}++test('a tiled base color map beside an untransformed emissive map loads, with the tiled map resampled and a warning', async context => {+ mockPatternBitmap(context);+ const asset = await parseGltf(triangleDocument({ edit: document => tiledBaseWithPlainEmissive(document) }));+ assertClose(asset.parts[0].geometry.uvs, TRIANGLE_UVS);+ assert.equal(asset.warnings.filter(warning => /Resampled baseColorTexture of "Crate" \(material 0\) from 2x2 to 4x4/.test(warning)).length, 1);+ const { map, emissiveMap } = asset.parts[0].material;+ assert.equal(emissiveMap.image.width, 2);+ assert.equal(map.image.width, 4);+ const original = patternBitmap();+ for (const [u, v] of [[0.1, 0.1], [0.3, 0.8], [0.6, 0.2], [0.9, 0.9], [0.45, 0.55]]) {+ const originalTexel = redAt(original, 2 * u, 2 * v);+ assert.equal(redAt(map.image, u, v), originalTexel, `base color at ${u}, ${v}`);+ }+ assert.equal(redAt(emissiveMap.image, 0.1, 0.1), 10);+ assert.equal(redAt(emissiveMap.image, 0.9, 0.9), 40);+});++test('resampled maps stay within four times their source pixels and name the cap', async context => {+ mockPatternBitmap(context);+ const edit = document => {+ tiledBaseWithPlainEmissive(document);+ document.materials[0].pbrMetallicRoughness.baseColorTexture.extensions.KHR_texture_transform.scale = [4, 4];+ };+ const asset = await parseGltf(triangleDocument({ edit }));+ assert.equal(asset.parts[0].material.map.image.width, 4);+ assert.equal(asset.parts[0].material.map.image.height, 4);+ assert.ok(asset.warnings.some(warning => /from 2x2 to 4x4.*capped/.test(warning)));+});++test('maps that cannot be resampled still fail the import, naming the material', async context => {+ mockPatternBitmap(context);+ const clamped = document => {+ tiledBaseWithPlainEmissive(document);+ document.samplers = [{ wrapS: 33071, wrapT: 33071 }];+ document.textures[0].sampler = 0;+ };+ await assert.rejects(parseGltf(triangleDocument({ edit: clamped })), /Crate.*cannot share one UV space/);+ const tiledTwiceAndThrice = document => {+ tiledBaseWithPlainEmissive(document, { extensions: { KHR_texture_transform: { scale: [3, 3] } } });+ };+ await assert.rejects(parseGltf(triangleDocument({ edit: tiledTwiceAndThrice })), /Crate.*cannot share one UV space/);+});