Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Scale large glTF texture sets down at load instead of throwing

Nguyen Xuan An956c23121758
diff --git a/changes/260.md b/changes/260.md
new file mode 100644
index 00000000..1b78f9cb
--- /dev/null
+++ b/changes/260.md
@@ -0,0 +1 @@
+- Scale large glTF texture sets down at load instead of throwing (closes #260). When the images together pass `maxTexturePixels`, the largest are halved together until they fit, so 40 maps of 1024 px load with default options as 512 px. `asset.scaledTextures` lists each scaled image as `{ name, from, to }` and `asset.warnings` summarises it. The new `maxTextureImagePixels` option (default 16,777,216) is the hard ceiling for one image, which is still rejected before decoding. KTX2 images are never scaled.
diff --git a/docs/gltf.md b/docs/gltf.md
index c3c72f39..54a1b68e 100644
--- a/docs/gltf.md
+++ b/docs/gltf.md
@@ -39,7 +39,8 @@ The optional `signal` aborts those fetches.
| `maxVertices` | 2,000,000 | Declared and decoded geometry vertices. Indices have a separate ceiling of twelve times this value. |
| `maxParts` | 20,000 | Declared nodes and decoded mesh parts. |
| `maxResources` | 64 | Unique resource URIs. |
-| `maxTexturePixels` | 16,777,216 | Combined texture image pixels, checked before decoding. |
+| `maxTexturePixels` | 16,777,216 | Combined texture image pixels, checked from the file headers before decoding. Over the budget, the largest images are halved together until they fit, and `asset.scaledTextures` lists each one as `{ name, from, to }` (also summarised in `asset.warnings`). |
+| `maxTextureImagePixels` | 16,777,216 | Hard ceiling for one image, checked before decoding. Larger images are rejected, never scaled. |
| `maxJoints` | 4,096 | Combined declared joints and joint palettes for instantiated meshes. |
| `maxInstances` | 4,096 | Instances of one `EXT_mesh_gpu_instancing` node. |
@@ -167,7 +168,7 @@ const asset = await loadGltf('/models/car.glb', { decoders: { draco, ktx2, mesho
Any subset works. Draco and KTX2 decode in browser workers. Dispose the loaders yourself when done (`draco.dispose()`, `ktx2.dispose()`).
A KTX2 texture that decodes to a GPU-compressed format fails with a message that points back to this setting.
-KTX2 dimensions count toward `maxTexturePixels` before decoding.
+KTX2 dimensions count toward `maxTexturePixels` before decoding. KTX2 images are never scaled, so a KTX2-heavy file over the budget fails.
### Instancing limits
diff --git a/src/gltf-decode.js b/src/gltf-decode.js
index deeca35b..f73251a2 100644
--- a/src/gltf-decode.js
+++ b/src/gltf-decode.js
@@ -38,11 +38,14 @@ function mimeTypeOf(imageDefinition, bytes) {
return PNG_SIGNATURE.every((value, index) => bytes[index] === value) ? 'image/png' : 'image/jpeg';
}
-async function decodeImage(bytes, mimeType) {
+async function decodeImage(bytes, mimeType, target) {
const blob = new Blob([bytes], { type: mimeType });
if (typeof createImageBitmap === 'function') {
- return createImageBitmap(blob, { premultiplyAlpha: 'none', colorSpaceConversion: 'none', imageOrientation: 'none' });
+ const options = { premultiplyAlpha: 'none', colorSpaceConversion: 'none', imageOrientation: 'none' };
+ if (target) Object.assign(options, { resizeWidth: target.width, resizeHeight: target.height, resizeQuality: 'high' });
+ return createImageBitmap(blob, options);
}
+ if (target) throw new Error('Scaling textures to fit maxTexturePixels requires createImageBitmap.');
const url = URL.createObjectURL(blob);
try {
const image = new Image();
@@ -83,7 +86,7 @@ function normalizedWeights(weights) {
* The result has the shape the Renderer67 conversion in gltf.js reads. Nothing here imports three.js: Draco, meshopt
* and KTX2 decoders arrive as `decoders` objects that the caller supplies.
*/
-export async function decodeGltf({ document, glbBinary, resourceBytes, decoders, limits }) {
+export async function decodeGltf({ document, glbBinary, resourceBytes, decoders, limits, imageTargets = new Map() }) {
const releasers = [];
const usedNames = new Map();
const nodeCache = new Map();
@@ -138,7 +141,7 @@ export async function decodeGltf({ document, glbBinary, resourceBytes, decoders,
loaded = { image: texture.image, isCompressedTexture: texture.isCompressedTexture === true };
releasers.push(() => texture.dispose?.());
} else {
- const image = await decodeImage(bytes, mimeTypeOf(document.images[sourceIndex], bytes));
+ const image = await decodeImage(bytes, mimeTypeOf(document.images[sourceIndex], bytes), imageTargets.get(sourceIndex));
loaded = { image, isCompressedTexture: false };
releasers.push(() => image.close?.());
}
diff --git a/src/gltf.js b/src/gltf.js
index 79599cb5..1fe7039e 100644
--- a/src/gltf.js
+++ b/src/gltf.js
@@ -78,6 +78,7 @@ function limitsFor(options) {
maxParts: options.maxParts ?? 20_000,
maxResources: options.maxResources ?? 64,
maxTexturePixels: options.maxTexturePixels ?? 16_777_216,
+ maxTextureImagePixels: options.maxTextureImagePixels ?? 16_777_216,
maxJoints: options.maxJoints ?? 4096,
maxInstances: options.maxInstances ?? DEFAULT_MAX_INSTANCES,
};
@@ -488,10 +489,11 @@ function dataUriBytes(uri) {
return Uint8Array.from(binary, character => character.charCodeAt(0));
}
-function validateImage(bytes, maxPixels) {
+function validateImage(bytes, maxImagePixels) {
const header = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
let width;
let height;
+ let scalable = true;
if (bytes.length >= 24 && header.getUint32(0) === 0x89504e47 && header.getUint32(4) === 0x0d0a1a0a && header.getUint32(12) === 0x49484452) {
width = header.getUint32(16);
height = header.getUint32(20);
@@ -517,10 +519,11 @@ function validateImage(bytes, maxPixels) {
if (!width && bytes.length >= 28 && ktx2Identifier.every((value, index) => bytes[index] === value)) {
width = header.getUint32(20, true);
height = header.getUint32(24, true);
+ scalable = false;
}
if (!width || !height) throw new Error('Only valid PNG, JPEG and KTX2 texture images are supported.');
- if (width * height > maxPixels) throw new Error('Texture image exceeds maxTexturePixels before decoding.');
- return width * height;
+ if (width * height > maxImagePixels) throw new Error('Texture image exceeds maxTextureImagePixels before decoding.');
+ return { width, height, scalable };
}
function binaryChunk(data) {
@@ -590,7 +593,7 @@ async function prepareResources(document, data, dataBytes, options, limits) {
usedBytes += resource.bytes.byteLength;
resourceBytes.set(uri, resource.bytes);
}
- let texturePixels = 0;
+ const imageSizes = [];
for (const image of document.images ?? []) {
let bytes = resourceBytes.get(image.uri);
if (!bytes && image.bufferView !== undefined) {
@@ -604,11 +607,37 @@ async function prepareResources(document, data, dataBytes, options, limits) {
bytes = source.subarray(offset, offset + view.byteLength);
}
if (!bytes) throw new Error('glTF image has no supported source.');
- texturePixels += validateImage(bytes, limits.maxTexturePixels);
- if (texturePixels > limits.maxTexturePixels) throw new Error('Combined texture images exceed maxTexturePixels before decoding.');
+ imageSizes.push(validateImage(bytes, limits.maxTextureImagePixels));
}
- return resourceBytes;
- return resourceBytes;
+ return { resourceBytes, textureScaling: planTextureScaling(document.images ?? [], imageSizes, limits.maxTexturePixels) };
+}
+
+/**
+ * Fit the combined texture pixels into the budget by halving the largest images together, so equal maps stay equal.
+ * KTX2 images cannot be resized before transcoding; they count toward the budget and are never scaled.
+ */
+function planTextureScaling(imageDefinitions, imageSizes, maxTexturePixels) {
+ const targets = imageSizes.map(({ width, height }) => ({ width, height }));
+ const totalPixels = () => targets.reduce((sum, { width, height }) => sum + width * height, 0);
+ while (totalPixels() > maxTexturePixels) {
+ const scalable = targets.filter((target, index) => imageSizes[index].scalable && target.width * target.height > 1);
+ if (!scalable.length) throw new Error('Texture images exceed maxTexturePixels and cannot be scaled down further.');
+ const largestPixels = Math.max(...scalable.map(target => target.width * target.height));
+ for (const target of scalable) {
+ if (target.width * target.height !== largestPixels) continue;
+ target.width = Math.max(1, target.width >> 1);
+ target.height = Math.max(1, target.height >> 1);
+ }
+ }
+ const scaledTextures = [];
+ const targetByImageIndex = new Map();
+ targets.forEach((target, index) => {
+ const source = imageSizes[index];
+ if (target.width === source.width && target.height === source.height) return;
+ targetByImageIndex.set(index, target);
+ scaledTextures.push({ name: imageDefinitions[index].name ?? `image ${index}`, from: [source.width, source.height], to: [target.width, target.height] });
+ });
+ return { targetByImageIndex, scaledTextures };
}
function copyAttribute(attribute, size) {
@@ -786,7 +815,7 @@ function textureDescriptorFor(texture, field, { colorSpace, uvChannel, uvTransfo
const key = `${colorSpace}:${uvChannel}:${uvTransform ?? ''}`;
if (!descriptors.has(key)) {
const image = decodedTextureImage(texture, field);
- if (!image || image.width * image.height > limits.maxTexturePixels) throw new Error(`${field} image is missing or exceeds maxTexturePixels.`);
+ if (!image || image.width * image.height > limits.maxTextureImagePixels) throw new Error(`${field} image is missing or exceeds maxTextureImagePixels.`);
const descriptor = {
image,
uvChannel,
@@ -847,10 +876,14 @@ export async function parseGltf(data, options = {}) {
await loadLayerShadersFor(document);
const warnings = ignoredExtensions.map(extension => `${extension} is accepted but not rendered.`);
const dataBytes = typeof data === 'string' ? new TextEncoder().encode(data).byteLength : data.byteLength;
- const resourceBytes = await prepareResources(document, data, dataBytes, options, limits);
+ const { resourceBytes, textureScaling } = await prepareResources(document, data, dataBytes, options, limits);
+ if (textureScaling.scaledTextures.length) {
+ const names = textureScaling.scaledTextures.map(({ name, from, to }) => `${name} ${from.join('x')} to ${to.join('x')}`);
+ warnings.push(`Scaled ${names.length} texture image(s) to fit maxTexturePixels: ${names.join(', ')}.`);
+ }
let gltf;
try {
- gltf = await decodeGltf({ document, glbBinary: binaryChunk(data), resourceBytes, decoders, limits });
+ gltf = await decodeGltf({ document, glbBinary: binaryChunk(data), resourceBytes, decoders, limits, imageTargets: textureScaling.targetByImageIndex });
const parts = [];
const bindings = [];
const skinBindings = [];
@@ -1259,7 +1292,7 @@ export async function parseGltf(data, options = {}) {
}
return stagePose({ animation: { clip: clipIndex, time: Math.max(0, Math.min(time, clip.duration)) } }).commit();
}
- return { parts, warnings, skins: skinBindings.map(binding => binding.skin), animations: gltf.animations,
+ return { parts, warnings, scaledTextures: textureScaling.scaledTextures, skins: skinBindings.map(binding => binding.skin), animations: gltf.animations,
get nodes() { return structuredClone(nodeMetadata); }, stagePose, applyAnimation, dispose, capabilities: GLTF_CAPABILITIES };
} catch (error) {
gltf?.release();
diff --git a/tests/gltf.test.js b/tests/gltf.test.js
index 67996a15..5ea0da3e 100644
--- a/tests/gltf.test.js
+++ b/tests/gltf.test.js
@@ -215,7 +215,74 @@ test('texture pixel budgets reject compressed images before browser decoding', a
const oversized = triangleAsset(document => {
document.images = [{ uri: `data:image/png;base64,${Buffer.from(header).toString('base64')}` }];
});
- await assert.rejects(parseGltf(oversized), /maxTexturePixels before decoding/);
+ await assert.rejects(parseGltf(oversized), /maxTextureImagePixels before decoding/);
+});
+
+function pngHeaderUri(width, height) {
+ const header = new Uint8Array(24);
+ const view = new DataView(header.buffer);
+ view.setUint32(0, 0x89504e47);
+ view.setUint32(4, 0x0d0a1a0a);
+ view.setUint32(12, 0x49484452);
+ view.setUint32(16, width);
+ view.setUint32(20, height);
+ return `data:image/png;base64,${Buffer.from(header).toString('base64')}`;
+}
+
+function mockImageBitmapWithResize(context) {
+ const previousBitmap = globalThis.createImageBitmap;
+ const previousSelf = globalThis.self;
+ globalThis.self = globalThis;
+ const requests = [];
+ globalThis.createImageBitmap = async (blob, options) => {
+ requests.push(options);
+ return { width: options.resizeWidth ?? 1024, height: options.resizeHeight ?? 1024, close() {} };
+ };
+ context.after(() => {
+ if (previousBitmap) globalThis.createImageBitmap = previousBitmap;
+ else delete globalThis.createImageBitmap;
+ if (previousSelf) globalThis.self = previousSelf;
+ else delete globalThis.self;
+ });
+ return requests;
+}
+
+test('forty 1024 px maps load with default options by scaling them down and naming each one', async context => {
+ const requests = mockImageBitmapWithResize(context);
+ const asset = await parseGltf(triangleAsset(document => {
+ document.images = Array.from({ length: 40 }, (unused, index) => ({ name: `map ${index}`, uri: pngHeaderUri(1024, 1024) }));
+ }));
+ assert.equal(asset.scaledTextures.length, 40);
+ assert.deepEqual(asset.scaledTextures[3], { name: 'map 3', from: [1024, 1024], to: [512, 512] });
+ assert.match(asset.warnings.join(' '), /Scaled 40 texture image\(s\)/);
+ assert.equal(requests.length, 0, 'unreferenced images are not decoded');
+ asset.dispose();
+});
+
+test('only the largest maps are scaled, and decoding requests the scaled size', async context => {
+ const requests = mockImageBitmapWithResize(context);
+ const asset = await parseGltf(triangleAsset(document => {
+ addMaterialMaps(document);
+ document.images = [{ name: 'big', uri: pngHeaderUri(4, 4) }];
+ }), { maxTexturePixels: 8 });
+ assert.deepEqual(asset.scaledTextures, [{ name: 'big', from: [4, 4], to: [2, 2] }]);
+ assert.equal(requests[0].resizeWidth, 2);
+ assert.equal(requests[0].resizeHeight, 2);
+ const unscaled = await parseGltf(triangleAsset(addMaterialMaps));
+ assert.deepEqual(unscaled.scaledTextures, []);
+ asset.dispose();
+ unscaled.dispose();
+});
+
+test('the single image ceiling still rejects a hostile image whatever the combined budget', async () => {
+ const hostile = triangleAsset(document => {
+ document.images = [{ uri: pngHeaderUri(100000, 100000) }];
+ });
+ await assert.rejects(parseGltf(hostile, { maxTexturePixels: 1_000_000_000_000 }), /maxTextureImagePixels before decoding/);
+ const large = triangleAsset(document => {
+ document.images = [{ uri: pngHeaderUri(2048, 2048) }];
+ });
+ await assert.rejects(parseGltf(large, { maxTextureImagePixels: 1024 * 1024 }), /maxTextureImagePixels before decoding/);
});
test('hierarchy depth guards reject long chains regardless of node ordering', async () => {
@@ -387,7 +454,6 @@ test('map preflight rejects unsupported UVs, sampler states, invalid scales and
change(document);
})), expected);
}
- await assert.rejects(parseGltf(triangleAsset(addMaterialMaps), { maxTexturePixels: 3 }), /maxTexturePixels/);
});
function skinPosition(part, vertex) {