Skip to content

3D engine that AI agents drive

Name the field when a glTF list or node name has the wrong type (#2452)

Nguyen Xuan An8e68e3fedfa0
diff --git a/changes/2452.md b/changes/2452.md
new file mode 100644
index 00000000..4442e4f8
--- /dev/null
+++ b/changes/2452.md
@@ -0,0 +1 @@
+- A glTF whose `children`, animation `channels` or `samplers`, `extensionsUsed` or `extensionsRequired` is not an array, or whose node or mesh `name` is not a string, now fails with an error that names the field instead of a raw `TypeError` (#2452, #2453)
diff --git a/docs/gltf.md b/docs/gltf.md
index e1e8dc07..ac4b4b48 100644
--- a/docs/gltf.md
+++ b/docs/gltf.md
@@ -55,7 +55,7 @@ The importer rejects cyclic hierarchies, multiple parents, and hierarchies deepe
It checks PNG, JPEG and WebP dimensions before browser image decoding.
Decoded accessor data has its own budget, `maxDecodedBytes`, and a file over it fails before any accessor is read: `decoded accessor bytes 1200000000, over maxDecodedBytes 1073741824. Fix: pass { maxDecodedBytes: 1200000000 }`.
-A file also fails when its meshopt-compressed buffer views would decode to more than `maxDecodedBytes` in total, even a view no accessor uses; the views and the accessors then share that one budget. A meshopt view whose `byteLength`, extension `byteLength`, `count` or `byteStride` is not a non-negative safe integer fails by field name. The check names the total, for example `decoded meshopt view bytes 4800000000, over maxDecodedBytes 1073741824`, and is raised before the decoder runs; when the accessors then push the shared total over, the error reads `decoded accessor and meshopt view bytes`. A scene `nodes` that is not an array fails by field name too. So does any of `nodes`, `meshes`, `accessors`, `bufferViews`, `buffers`, `materials`, `textures`, `images`, `skins` or `animations` that is neither absent, `null` nor an array (`Invalid glTF meshes: expected an array of objects.`), or that holds a `null` or non-object entry (the error names the array and the index of the bad entry); a `null` array is treated as absent. A dangling index (`primitive.material`, a scene node, an accessor `bufferView`, a mesh without `primitives`) fails with the field and the valid range. A buffer view `byteStride` below the element size or not a multiple of 4, an accessor or sparse `byteOffset` that is negative or fractional, and a sparse index type other than 5121, 5123 or 5125, fail by name. A `normalized` flag on a float or 32-bit integer accessor is ignored.
+A file also fails when its meshopt-compressed buffer views would decode to more than `maxDecodedBytes` in total, even a view no accessor uses; the views and the accessors then share that one budget. A meshopt view whose `byteLength`, extension `byteLength`, `count` or `byteStride` is not a non-negative safe integer fails by field name. The check names the total, for example `decoded meshopt view bytes 4800000000, over maxDecodedBytes 1073741824`, and is raised before the decoder runs; when the accessors then push the shared total over, the error reads `decoded accessor and meshopt view bytes`. A scene `nodes` that is not an array fails by field name too. So does any of `nodes`, `meshes`, `accessors`, `bufferViews`, `buffers`, `materials`, `textures`, `images`, `skins` or `animations` that is neither absent, `null` nor an array (`Invalid glTF meshes: expected an array of objects.`), or that holds a `null` or non-object entry (the error names the array and the index of the bad entry); a `null` array is treated as absent. So does any of `nodes[i].children`, `animations[i].channels`, `animations[i].samplers`, `extensionsUsed` or `extensionsRequired` that is not an array (a `null` one is treated as absent), a `null` animation channel, and a node or mesh `name` that is not a string. A dangling index (`primitive.material`, a scene node, an accessor `bufferView`, a mesh without `primitives`) fails with the field and the valid range. A buffer view `byteStride` below the element size or not a multiple of 4, an accessor or sparse `byteOffset` that is negative or fractional, and a sparse index type other than 5121, 5123 or 5125, fail by name. A `normalized` flag on a float or 32-bit integer accessor is ignored.
Accessors are decoded one primitive at a time while the scene is converted, and each is released after the last node that uses it, so decoding holds the file bytes plus the converted geometry plus one primitive, not every accessor at once. The file bytes stay until the last primitive is read; drop your own reference to them after the call returns.
These limits bound asset inputs and geometry, rather than the renderer's total GPU allocation.
The renderer retains its separate memory budget.
diff --git a/src/gltf-references.js b/src/gltf-references.js
index 145db534..c2dd1fcd 100644
--- a/src/gltf-references.js
+++ b/src/gltf-references.js
@@ -47,6 +47,32 @@ function validateEntryObjects(document) {
}
}
+// A null or absent list loads as empty; any other non-array would reach a for...of and fail with a raw TypeError.
+function requireList(value, fieldPath) {
+ if (value === undefined || value === null || Array.isArray(value)) return;
+ throw new Error(`Invalid glTF ${fieldPath}: expected an array. Fix: pass an array or remove the field.`);
+}
+
+const ENTRY_LIST_FIELDS = [['nodes', 'children'], ['animations', 'channels'], ['animations', 'samplers']];
+
+function validateListAndNameFields(document) {
+ requireList(document.extensionsUsed, 'extensionsUsed');
+ requireList(document.extensionsRequired, 'extensionsRequired');
+ for (const [arrayName, fieldName] of ENTRY_LIST_FIELDS) {
+ (document[arrayName] ?? []).forEach((entry, entryIndex) => requireList(entry[fieldName], `${arrayName}[${entryIndex}].${fieldName}`));
+ }
+ for (const arrayName of ['nodes', 'meshes']) {
+ (document[arrayName] ?? []).forEach((entry, entryIndex) => {
+ if (entry.name !== undefined && entry.name !== null && typeof entry.name !== 'string') {
+ throw new Error(`Invalid glTF ${arrayName}[${entryIndex}].name ${JSON.stringify(entry.name)}: expected a string. Fix: pass a string or remove the field.`);
+ }
+ });
+ }
+ (document.animations ?? []).forEach((animation, animationIndex) => {
+ (animation.channels ?? []).forEach((channel, channelIndex) => requireObject(channel, `animations[${animationIndex}].channels[${channelIndex}]`));
+ });
+}
+
const NODE_TRANSFORM_LENGTHS = { matrix: 16, translation: 3, rotation: 4, scale: 3 };
function validateNodeTransforms(document) {
@@ -68,6 +94,7 @@ function validateNodeTransforms(document) {
export function validateDocumentReferences(document) {
if (!document || typeof document !== 'object' || Array.isArray(document)) throw new Error('glTF JSON must be an object. Fix: pass a glTF 2.0 document.');
validateEntryObjects(document);
+ validateListAndNameFields(document);
validateMeshReferences(document);
validateAccessorReferences(document);
validateSceneReferences(document);
diff --git a/tests/gltf-list-field-validation.test.js b/tests/gltf-list-field-validation.test.js
new file mode 100644
index 00000000..575d2ea3
--- /dev/null
+++ b/tests/gltf-list-field-validation.test.js
@@ -0,0 +1,61 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { parseGltf } from '../src/gltf.js';
+
+const triangleBytes = new Uint8Array(new Float32Array([0, 0, 0, 1, 0, 0, 0, 1, 0]).buffer);
+
+/** A one-triangle glTF; `change(document)` edits the JSON before it is serialized. */
+function triangleJson(change) {
+ const document = {
+ asset: { version: '2.0' },
+ scene: 0,
+ scenes: [{ nodes: [0] }],
+ nodes: [{ mesh: 0 }],
+ meshes: [{ primitives: [{ attributes: { POSITION: 0 } }] }],
+ accessors: [{ bufferView: 0, componentType: 5126, count: 3, type: 'VEC3' }],
+ bufferViews: [{ buffer: 0, byteLength: 36 }],
+ buffers: [{ byteLength: 36, uri: `data:application/octet-stream;base64,${Buffer.from(triangleBytes).toString('base64')}` }],
+ };
+ change(document);
+ return JSON.stringify(document);
+}
+
+const animateNode = document => {
+ document.animations = [{ channels: [{ sampler: 0, target: { node: 0, path: 'translation' } }], samplers: [{ input: 1, output: 2 }] }];
+};
+
+test('a null or absent list still loads', async () => {
+ await parseGltf(triangleJson(document => {
+ document.nodes[0].children = null;
+ document.extensionsUsed = null;
+ document.extensionsRequired = null;
+ }));
+});
+
+test('a list field that is not an array fails by its glTF path, not with a TypeError', async () => {
+ const cases = [
+ ['nodes[0].children', document => { document.nodes[0].children = 0; }],
+ ['animations[0].channels', document => { animateNode(document); document.animations[0].channels = {}; }],
+ ['animations[0].samplers', document => { animateNode(document); document.animations[0].samplers = true; }],
+ ['extensionsUsed', document => { document.extensionsUsed = 'KHR_lights_punctual'; }],
+ ['extensionsRequired', document => { document.extensionsRequired = 5; }],
+ ];
+ for (const [path, change] of cases) {
+ await assert.rejects(() => parseGltf(triangleJson(change)), error => error.constructor === Error && error.message.includes(`Invalid glTF ${path}: expected an array`), path);
+ }
+});
+
+test('a null animation channel fails by its glTF path', async () => {
+ const text = triangleJson(document => {
+ animateNode(document);
+ document.animations[0].channels.push(null);
+ });
+ await assert.rejects(() => parseGltf(text), error => error.constructor === Error && error.message.includes('animations[0].channels[1]'));
+});
+
+test('a node or mesh name that is not a string fails by its glTF path, not with a TypeError', async () => {
+ const nodeName = triangleJson(document => { document.nodes[0].name = 7; });
+ await assert.rejects(() => parseGltf(nodeName), error => error.constructor === Error && error.message.includes('nodes[0].name 7'));
+ const meshName = triangleJson(document => { document.meshes[0].name = ['a']; });
+ await assert.rejects(() => parseGltf(meshName), error => error.constructor === Error && error.message.includes('meshes[0].name'));
+});