3D engine that AI agents drive
Load glTF without three.js
Nguyen Xuan An6857394184af
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 0ac5fdef..977a5121 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -2,6 +2,7 @@## Unreleased+- Load glTF without Three.js: the addon has its own GLB and glTF parser, node sampler and animation clips, so a box with the addon drops from 159,422 to 67,467 bytes gzip. Draco, meshopt and KTX2 still come from the decoders you pass in `options.decoders`. Only the default scene is decoded, and a node outside it is decoded only when a skin or an animation names it- Update the bundled `zod` to 4.6.7, which fixes a memory exhaustion advisory in the validation of oversized collections- Make the MCP preview server reject requests with another Host header, which closes DNS rebinding- Check the size of a mesh `array` before it allocates. Before this, the check ran after the copies existeddiff --git a/README.md b/README.mdindex aac4e122..5526f72a 100644--- a/README.md+++ b/README.md@@ -189,7 +189,7 @@ Read [CONTRIBUTING.md](CONTRIBUTING.md) before you open a pull request. It cover## Credits- [gl-matrix](https://github.com/toji/gl-matrix) supplies the matrix math.-- The glTF addon bundles the [Three.js](https://threejs.org/) glTF decoder under its MIT license. The core renderer does not depend on Three.js.+- The glTF addon has its own parser and does not depend on [Three.js](https://threejs.org/). The Draco, meshopt and KTX2 decoders are Three.js loaders that you pass in.- Textures, leaf atlases and the HDRI on the site are CC0 scans from [Poly Haven](https://polyhaven.com) and [ambientCG](https://ambientcg.com). See [the texture credits](public/textures/CREDITS.md).- WALL·E is a Disney/Pixar character. The study is procedural geometry with no external model assets.- The trailer study follows the shot order of [a Universal Pictures trailer](https://www.youtube.com/watch?v=uYPbbksJxIg) with procedural sets and an original score. It contains no film footage or soundtrack samples.diff --git a/bench/size/baseline.json b/bench/size/baseline.jsonindex e87b9e8d..1de5d156 100644--- a/bench/size/baseline.json+++ b/bench/size/baseline.json@@ -14,9 +14,9 @@},"bundles": {"entry:core": {- "min": 232517,- "gzip": 65730,- "brotli": 56178+ "min": 232566,+ "gzip": 65748,+ "brotli": 56102},"entry:model": {"min": 40093,@@ -44,9 +44,9 @@"brotli": 7331},"entry:gltf": {- "min": 533687,- "gzip": 134659,- "brotli": 111762+ "min": 139564,+ "gzip": 43172,+ "brotli": 37021},"entry:modeling": {"min": 309436,@@ -69,9 +69,9 @@"brotli": 71174},"entry:mesh": {- "min": 95451,- "gzip": 32718,- "brotli": 28879+ "min": 95797,+ "gzip": 32819,+ "brotli": 29011},"entry:shrinkwrap": {"min": 348855,@@ -134,14 +134,14 @@"brotli": 762},"entry:agent-scene": {- "min": 586176,- "gzip": 161435,- "brotli": 135409+ "min": 586522,+ "gzip": 161526,+ "brotli": 135640},"entry:agent-asset": {- "min": 612778,- "gzip": 168878,- "brotli": 141774+ "min": 613124,+ "gzip": 168953,+ "brotli": 141724},"entry:hdri": {"min": 8075,@@ -154,14 +154,14 @@"brotli": 41832},"scene:gltf-box": {- "min": 629811,- "gzip": 159422,- "brotli": 132670+ "min": 235553,+ "gzip": 67467,+ "brotli": 58083},"scene:agent-scene": {- "min": 678447,- "gzip": 185592,- "brotli": 155797+ "min": 678793,+ "gzip": 185681,+ "brotli": 155804}}}diff --git a/bench/size/budgets.json b/bench/size/budgets.jsonindex 564e41e1..2165567c 100644--- a/bench/size/budgets.json+++ b/bench/size/budgets.json@@ -11,12 +11,12 @@"entry:film": 156800,"entry:motion": 13600,"entry:canvas2d": 9400,- "entry:gltf": 137400,+ "entry:gltf": 44100,"entry:modeling": 75900,"entry:sculpt": 2500,"entry:surface": 74500,"entry:mesh-query": 87300,- "entry:mesh": 33400,+ "entry:mesh": 33500,"entry:shrinkwrap": 88600,"entry:surface-attachment": 11800,"entry:physics": 16500,@@ -29,11 +29,11 @@"entry:grass": 4400,"entry:clutter": 5300,"entry:texture-set": 900,- "entry:agent-scene": 164700,- "entry:agent-asset": 172300,+ "entry:agent-scene": 164800,+ "entry:agent-asset": 172400,"entry:hdri": 3300,"scene:lit-box": 49800,- "scene:gltf-box": 162700,+ "scene:gltf-box": 68900,"scene:agent-scene": 189400}}diff --git a/docs/gltf.md b/docs/gltf.mdindex 5a297fa4..e7abd692 100644--- a/docs/gltf.md+++ b/docs/gltf.md@@ -1,7 +1,8 @@# glTF asset bridge`src/gltf.js` converts glTF 2.0 assets into Renderer67 parts.-It uses the optional Three.js `GLTFLoader` for decoding, without creating a Three.js renderer.+It decodes GLB and glTF files with its own parser (`src/gltf-decode.js`), so the addon does not import Three.js.+A box with the addon is 67,467 bytes gzip, against 159,422 when it used `GLTFLoader`.The core renderer does not import this addon.```js@@ -91,7 +92,7 @@ The importer rejects a requested texture that fails to decode, rather than retur## Animation and ownership-`animations` contains the decoded Three.js animation clips, including their names, durations, and tracks.+`animations` contains the decoded animation clips, including their names, durations, and tracks. Each track has `name` (`Node.position`, `Node.quaternion`, `Node.scale` or `Node.morphTargetInfluences`), `times`, `values`, `getInterpolation()` and `createInterpolant(result)`, the same fields the Three.js clips had.`applyAnimation(time, clipIndex = 0)` evaluates node and joint animation at an absolute time in seconds.Time clamps to the selected clip's duration.The hook updates the existing part matrices and returns the same `parts` array.@@ -148,7 +149,8 @@ Without the matching decoder, a file that uses a compression extension fails wit### Decoders-The decoders are the Three.js loaders. 67.js does not bundle or fetch their wasm files, so you choose where they are served.+The decoders are the Three.js loaders, and they stay yours: only an application that passes one imports Three.js. 67.js does not bundle or fetch their wasm files, so you choose where they are served.+A Draco loader needs `decodeDracoFile(buffer, onLoad, attributeIds, attributeTypes, colorSpace, onError)`, a meshopt decoder needs `ready` and `decodeGltfBuffer`, and a KTX2 loader needs `load(url, onLoad, onProgress, onError)`.```jsimport { DRACOLoader } from 'three/addons/loaders/DRACOLoader.js';diff --git a/docs/parity.md b/docs/parity.mdindex 9b706797..55669266 100644--- a/docs/parity.md+++ b/docs/parity.md@@ -237,7 +237,7 @@ The goal also needs this work, and no page in the Blender manual covers it.| Work | Status | Why | Issues || --- | --- | --- | --- || Parity evidence | partial | This ledger exists. The Blender comparisons do not. | #24, #25, #26 |-| Bundle size | partial | `npm run size` checks a budget for each entry, and the package has a 1 MiB limit. three.js is still in the glTF and modeling paths. | #27, #33, #34, #35, #36 |+| Bundle size | partial | `npm run size` checks a budget for each entry, and the package has a 1 MiB limit. three.js is gone from the glTF path and still in the modeling paths. | #27, #33, #34, #35, #36 || Runtime speed | partial | `bench/runtime` compares 7 scenes, and three.js wins most of them. There is no culling, LOD selection or adaptive quality, and bakes run on the main thread. | #28, #37, #38, #74 || Agent measurement | partial | A task suite runs on one model and reads recipes only. | #29, #30, #31, #69 || Pull request checks | partial | The `Test` workflow reports a status and does not block a merge. | #32 |diff --git a/src/gltf-accessors.js b/src/gltf-accessors.jsnew file mode 100644index 00000000..69b6ddcc--- /dev/null+++ b/src/gltf-accessors.js@@ -0,0 +1,118 @@+export const COMPONENT_TYPES = {+ 5120: Int8Array,+ 5121: Uint8Array,+ 5122: Int16Array,+ 5123: Uint16Array,+ 5125: Uint32Array,+ 5126: Float32Array,+};+const COMPONENT_COUNTS = { SCALAR: 1, VEC2: 2, VEC3: 3, VEC4: 4, MAT2: 4, MAT3: 9, MAT4: 16 };+const NORMALIZATION_DIVISORS = { 5120: 127, 5121: 255, 5122: 32767, 5123: 65535 };++/** Float values of an attribute, with normalized integers scaled into zero to one or minus one to one. */+export function attributeFloats(attribute) {+ const length = attribute.count * attribute.itemSize;+ const values = new Float32Array(length);+ const divisor = attribute.normalized ? NORMALIZATION_DIVISORS[attribute.componentType] : 1;+ for (let index = 0; index < length; index++) {+ const value = attribute.array[index];+ values[index] = divisor === 1 ? value : Math.max(value / divisor, -1);+ }+ return values;+}++function elementBytesOf(accessor) {+ return COMPONENT_TYPES[accessor.componentType].BYTES_PER_ELEMENT * COMPONENT_COUNTS[accessor.type];+}++function copyElements(source, offset, stride, count, elementBytes) {+ if (count > 0 && offset + (count - 1) * stride + elementBytes > source.length) {+ throw new Error('glTF accessor exceeds its buffer view.');+ }+ const packed = new Uint8Array(count * elementBytes);+ for (let element = 0; element < count; element++) {+ const start = offset + element * stride;+ packed.set(source.subarray(start, start + elementBytes), element * elementBytes);+ }+ return packed;+}++/**+ * Reads accessors as tightly packed typed arrays, with sparse substitution and meshopt buffer views.+ * `bufferBytes(index)` returns the bytes of a glTF buffer. `meshoptDecoder` is only needed for compressed views.+ */+export function createAccessorReader(document, bufferBytes, meshoptDecoder) {+ const viewCache = new Map();++ function plainViewBytes(view) {+ const source = bufferBytes(view.buffer);+ const offset = view.byteOffset ?? 0;+ const length = view.byteLength;+ if (!source || !Number.isSafeInteger(length) || length < 0 || offset < 0 || offset + length > source.length) {+ throw new Error('glTF buffer view exceeds its buffer.');+ }+ return source.subarray(offset, offset + length);+ }++ async function decodeMeshoptView(view) {+ const extension = view.extensions.EXT_meshopt_compression;+ const source = bufferBytes(extension.buffer);+ const offset = extension.byteOffset ?? 0;+ if (!source || offset + extension.byteLength > source.length) throw new Error('Meshopt buffer view exceeds its buffer.');+ await meshoptDecoder.ready;+ const decoded = new Uint8Array(extension.count * extension.byteStride);+ meshoptDecoder.decodeGltfBuffer(decoded, extension.count, extension.byteStride, source.subarray(offset, offset + extension.byteLength), extension.mode, extension.filter ?? 'NONE');+ return decoded;+ }++ /** Decode every meshopt view before any accessor is read, so reading stays synchronous. */+ async function prepare() {+ const views = document.bufferViews ?? [];+ for (let index = 0; index < views.length; index++) {+ if (views[index].extensions?.EXT_meshopt_compression) viewCache.set(index, await decodeMeshoptView(views[index]));+ }+ }++ function viewBytes(index) {+ const view = document.bufferViews?.[index];+ if (!view) throw new Error('Invalid glTF buffer view index.');+ if (!viewCache.has(index)) viewCache.set(index, plainViewBytes(view));+ return viewCache.get(index);+ }++ function readAccessor(index) {+ const accessor = document.accessors?.[index];+ if (!accessor) throw new Error('Invalid glTF accessor index.');+ const ArrayType = COMPONENT_TYPES[accessor.componentType];+ if (!ArrayType) throw new Error('Unsupported glTF accessor component type.');+ const itemSize = COMPONENT_COUNTS[accessor.type];+ const elementBytes = elementBytesOf(accessor);+ let packed;+ if (accessor.bufferView === undefined) {+ packed = new Uint8Array(accessor.count * elementBytes);+ } else {+ const stride = document.bufferViews[accessor.bufferView].byteStride || elementBytes;+ packed = copyElements(viewBytes(accessor.bufferView), accessor.byteOffset ?? 0, stride, accessor.count, elementBytes);+ }+ const array = new ArrayType(packed.buffer);+ if (accessor.sparse) applySparse(accessor, array, itemSize);+ return { array, itemSize, count: accessor.count, normalized: accessor.normalized === true, componentType: accessor.componentType };+ }++ function applySparse(accessor, array, itemSize) {+ const { count, indices, values } = accessor.sparse;+ const IndexType = COMPONENT_TYPES[indices.componentType];+ if (!IndexType) throw new Error('Unsupported sparse index component type.');+ const indexBytes = copyElements(viewBytes(indices.bufferView), indices.byteOffset ?? 0, IndexType.BYTES_PER_ELEMENT, count, IndexType.BYTES_PER_ELEMENT);+ const sparseIndices = new IndexType(indexBytes.buffer);+ const itemBytes = array.BYTES_PER_ELEMENT * itemSize;+ const valueBytes = copyElements(viewBytes(values.bufferView), values.byteOffset ?? 0, itemBytes, count, itemBytes);+ const sparseValues = new array.constructor(valueBytes.buffer);+ for (let item = 0; item < count; item++) {+ if (sparseIndices[item] >= accessor.count) throw new Error('Sparse accessor index is out of range.');+ array.set(sparseValues.subarray(item * itemSize, (item + 1) * itemSize), sparseIndices[item] * itemSize);+ }+ }++ return { prepare, readAccessor, viewBytes };+}diff --git a/src/gltf-animation.js b/src/gltf-animation.jsnew file mode 100644index 00000000..799fa0b5--- /dev/null+++ b/src/gltf-animation.js@@ -0,0 +1,208 @@+import { attributeFloats } from './gltf-accessors.js';++export const INTERPOLATE_DISCRETE = 2300;+export const INTERPOLATE_LINEAR = 2301;+export const INTERPOLATE_SMOOTH = 2302;++const INTERPOLATION_BY_NAME = { STEP: INTERPOLATE_DISCRETE, LINEAR: INTERPOLATE_LINEAR, CUBICSPLINE: INTERPOLATE_SMOOTH };+const PROPERTY_BY_PATH = { translation: 'position', rotation: 'quaternion', scale: 'scale', weights: 'morphTargetInfluences' };++/** The decoded node a track writes to. Kept outside the track so the public track stays plain data. */+const targetByTrack = new WeakMap();++function lastIndexBelow(times, time) {+ let low = 0;+ let high = times.length - 1;+ while (high - low > 1) {+ const middle = (low + high) >> 1;+ if (times[middle] <= time) low = middle;+ else high = middle;+ }+ return low;+}++function slerpInto(result, values, offset0, offset1, weight) {+ let [x0, y0, z0, w0] = [values[offset0], values[offset0 + 1], values[offset0 + 2], values[offset0 + 3]];+ const [x1, y1, z1, w1] = [values[offset1], values[offset1 + 1], values[offset1 + 2], values[offset1 + 3]];+ let from = 1 - weight;+ let to = weight;+ const cosine = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1;+ const direction = cosine >= 0 ? 1 : -1;+ const squaredSine = 1 - cosine * cosine;+ if (squaredSine > Number.EPSILON) {+ const sine = Math.sqrt(squaredSine);+ const angle = Math.atan2(sine, cosine * direction);+ from = Math.sin(from * angle) / sine;+ to = Math.sin(to * angle) / sine;+ }+ const signedTo = to * direction;+ x0 = x0 * from + x1 * signedTo;+ y0 = y0 * from + y1 * signedTo;+ z0 = z0 * from + z1 * signedTo;+ w0 = w0 * from + w1 * signedTo;+ if (from === 1 - weight) {+ const scale = 1 / Math.hypot(x0, y0, z0, w0);+ x0 *= scale;+ y0 *= scale;+ z0 *= scale;+ w0 *= scale;+ }+ result[0] = x0;+ result[1] = y0;+ result[2] = z0;+ result[3] = w0;+}++function sampleStep(track, interval, result, size) {+ for (let component = 0; component < size; component++) result[component] = track.values[interval * size + component];+}++function sampleLinear(track, interval, time, result, size, isRotation) {+ const t0 = track.times[interval];+ const t1 = track.times[interval + 1];+ const weight = (time - t0) / (t1 - t0);+ if (isRotation) {+ slerpInto(result, track.values, interval * 4, (interval + 1) * 4, weight);+ return;+ }+ for (let component = 0; component < size; component++) {+ const from = track.values[interval * size + component];+ const to = track.values[(interval + 1) * size + component];+ result[component] = from * (1 - weight) + to * weight;+ }+}++function sampleCubic(track, interval, time, result, size, isRotation) {+ const t0 = track.times[interval];+ const delta = track.times[interval + 1] - t0;+ const p = (time - t0) / delta;+ const pp = p * p;+ const ppp = pp * p;+ const blendEnd = -2 * ppp + 3 * pp;+ const blendEndTangent = ppp - pp;+ const blendStart = 1 - blendEnd;+ const blendStartTangent = blendEndTangent - pp + p;+ const stride = size * 3;+ const first = interval * stride;+ const second = (interval + 1) * stride;+ for (let component = 0; component < size; component++) {+ const startPoint = track.values[first + size + component];+ const startTangent = track.values[first + 2 * size + component] * delta;+ const endPoint = track.values[second + size + component];+ const endTangent = track.values[second + component] * delta;+ result[component] = blendStart * startPoint + blendStartTangent * startTangent + blendEnd * endPoint + blendEndTangent * endTangent;+ }+ if (isRotation) {+ const scale = 1 / Math.hypot(result[0], result[1], result[2], result[3]);+ for (let component = 0; component < 4; component++) result[component] *= scale;+ }+}++/** Value of a track at a time. Times outside the keys clamp to the first or last key. */+function sampleTrack(track, time, result) {+ const cubic = track.interpolation === INTERPOLATE_SMOOTH;+ const size = track.values.length / track.times.length / (cubic ? 3 : 1);+ const last = track.times.length - 1;+ const clamped = time <= track.times[0] ? 0 : time >= track.times[last] ? last : -1;+ if (clamped >= 0) {+ const offset = (cubic ? clamped * 3 + 1 : clamped) * size;+ for (let component = 0; component < size; component++) result[component] = track.values[offset + component];+ return result;+ }+ const interval = lastIndexBelow(track.times, time);+ const isRotation = track.name.endsWith('.quaternion');+ if (track.interpolation === INTERPOLATE_DISCRETE) sampleStep(track, interval, result, size);+ else if (cubic) sampleCubic(track, interval, time, result, size, isRotation);+ else sampleLinear(track, interval, time, result, size, isRotation);+ return result;+}++function createTrack(name, times, values, interpolation) {+ const track = {+ name,+ times,+ values,+ interpolation,+ getInterpolation() {+ return interpolation;+ },+ getValueSize() {+ return values.length / times.length;+ },+ createInterpolant(result) {+ const size = track.getValueSize() / (interpolation === INTERPOLATE_SMOOTH ? 3 : 1);+ return { evaluate: time => sampleTrack(track, time, result.subarray(0, size)) };+ },+ };+ return track;+}++function validateTimes(times) {+ for (let index = 0; index < times.length; index++) {+ if (times[index] < 0 || index && times[index] <= times[index - 1]) throw new Error('Animation times must be nonnegative and strictly increasing.');+ }+}++function validateRotations(values, interpolation) {+ const cubic = interpolation === INTERPOLATE_SMOOTH;+ for (let offset = cubic ? 4 : 0; offset < values.length; offset += cubic ? 12 : 4) {+ const length = Math.hypot(values[offset], values[offset + 1], values[offset + 2], values[offset + 3]);+ if (Math.abs(length - 1) > 0.01) throw new Error('Animation rotation values require unit quaternions.');+ }+}++function nodeTrackName(node) {+ return node.name ? node.name : node.uuid;+}++function tracksForChannel(channel, sampler, node, readAccessor) {+ const interpolation = INTERPOLATION_BY_NAME[sampler.interpolation ?? 'LINEAR'];+ const times = attributeFloats(readAccessor(sampler.input));+ validateTimes(times);+ const values = attributeFloats(readAccessor(sampler.output));+ if (!times.every(Number.isFinite) || !values.every(Number.isFinite)) throw new Error('Animation times and values must be finite.');+ const path = channel.target.path;+ if (path === 'rotation') validateRotations(values, interpolation);+ const property = PROPERTY_BY_PATH[path];+ if (path !== 'weights') {+ const track = createTrack(`${nodeTrackName(node)}.${property}`, times, values, interpolation);+ targetByTrack.set(track, node);+ return [track];+ }+ const meshes = [node, ...node.children].filter(candidate => candidate.morphTargetInfluences);+ return meshes.map(mesh => {+ const track = createTrack(`${nodeTrackName(mesh)}.${property}`, times, values, interpolation);+ targetByTrack.set(track, mesh);+ return track;+ });+}++/** Build one clip per glTF animation. `nodeAt(index)` returns the decoded node for a glTF node index. */+export function createClips(document, nodeAt, readAccessor) {+ return (document.animations ?? []).map((definition, animationIndex) => {+ const tracks = [];+ for (const channel of definition.channels ?? []) {+ if (channel.target.node === undefined) continue;+ const sampler = definition.samplers[channel.sampler];+ tracks.push(...tracksForChannel(channel, sampler, nodeAt(channel.target.node), readAccessor));+ }+ const duration = Math.max(0, ...tracks.map(track => track.times[track.times.length - 1]));+ return { name: definition.name ? definition.name : `animation_${animationIndex}`, duration, tracks };+ });+}++/** Write the clip's value at `time` into the decoded nodes. Properties without a track keep their current value. */+export function applyClip(clip, time) {+ const clamped = Math.max(0, Math.min(time, clip.duration));+ for (const track of clip.tracks) {+ const target = targetByTrack.get(track);+ const result = new Float64Array(track.getValueSize() / (track.interpolation === INTERPOLATE_SMOOTH ? 3 : 1));+ const value = sampleTrack(track, clamped, result);+ const property = track.name.slice(track.name.lastIndexOf('.') + 1);+ if (property === 'morphTargetInfluences') {+ for (let index = 0; index < value.length; index++) target.morphTargetInfluences[index] = value[index];+ } else {+ target[property].fromArray(value);+ }+ }+}diff --git a/src/gltf-decode.js b/src/gltf-decode.jsnew file mode 100644index 00000000..9e174f43--- /dev/null+++ b/src/gltf-decode.js@@ -0,0 +1,372 @@+import { mat4 } from 'gl-matrix';+import { COMPONENT_TYPES, attributeFloats, createAccessorReader } from './gltf-accessors.js';+import { createClips } from './gltf-animation.js';+import { Matrix4, SceneNode } from './gltf-nodes.js';+import { createSkinPose, validateSkinGeometry } from './skinning.js';++const GEOMETRY_ATTRIBUTE_NAMES = {+ POSITION: 'position',+ NORMAL: 'normal',+ COLOR_0: 'color',+ TEXCOORD_0: 'uv',+ JOINTS_0: 'skinIndex',+ WEIGHTS_0: 'skinWeight',+};+const TEXTURE_SLOTS = [+ ['map', 'baseColorTexture', true],+ ['normalMap', 'normalTexture', false],+ ['metalnessMap', 'metallicRoughnessTexture', true],+ ['aoMap', 'occlusionTexture', false],+ ['emissiveMap', 'emissiveTexture', false],+];+const PNG_SIGNATURE = [0x89, 0x50, 0x4e, 0x47];+const LINEAR_SRGB = 'srgb-linear';+const COMPONENT_CODES = new Map(Object.entries(COMPONENT_TYPES).map(([code, ArrayType]) => [ArrayType, Number(code)]));++export function textureSourceIndex(texture) {+ return texture.extensions?.KHR_texture_basisu?.source ?? texture.source;+}++function sanitizeNodeName(name) {+ return name.replace(/\s/g, '_').replace(/[[\].:/]/g, '');+}++function mimeTypeOf(imageDefinition, bytes) {+ if (imageDefinition.mimeType) return imageDefinition.mimeType;+ return PNG_SIGNATURE.every((value, index) => bytes[index] === value) ? 'image/png' : 'image/jpeg';+}++async function decodeImage(bytes, mimeType) {+ const blob = new Blob([bytes], { type: mimeType });+ if (typeof createImageBitmap === 'function') {+ return createImageBitmap(blob, { premultiplyAlpha: 'none', colorSpaceConversion: 'none', imageOrientation: 'none' });+ }+ const url = URL.createObjectURL(blob);+ try {+ const image = new Image();+ image.src = url;+ await image.decode();+ return image;+ } finally {+ URL.revokeObjectURL(url);+ }+}++function decodedAttribute(attribute, normalized) {+ return {+ array: attribute.array,+ itemSize: attribute.itemSize,+ count: attribute.count,+ normalized: normalized ?? attribute.normalized === true,+ componentType: COMPONENT_CODES.get(attribute.array.constructor),+ };+}++/** Scale each vertex's four weights to sum to one, as three.js does for skinned meshes. */+function normalizedWeights(weights) {+ const values = attributeFloats(weights);+ for (let offset = 0; offset < values.length; offset += 4) {+ const total = values[offset] + values[offset + 1] + values[offset + 2] + values[offset + 3];+ if (total === 0) {+ values[offset] = 1;+ continue;+ }+ for (let influence = 0; influence < 4; influence++) values[offset + influence] /= total;+ }+ return { array: values, itemSize: 4, count: weights.count, normalized: false, componentType: 5126 };+}++/**+ * Decode the selected glTF scene into plain scene nodes, geometry sources, materials, textures and animation clips.+ * 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 }) {+ const releasers = [];+ const usedNames = new Map();+ const nodeCache = new Map();+ const meshNames = new Map();+ const sources = new Map();+ const materials = new Map();+ const textures = new Map();+ const images = new Map();+ const skeletons = new Map();+ const instanceMatrices = new Map();++ function bufferBytes(index) {+ const buffer = document.buffers?.[index];+ if (!buffer) return null;+ if (buffer.uri !== undefined) return resourceBytes.get(buffer.uri) ?? null;+ return index === 0 ? glbBinary : null;+ }++ const reader = createAccessorReader(document, bufferBytes, decoders.meshopt);+ await reader.prepare();++ function uniqueName(originalName) {+ const sanitized = sanitizeNodeName(originalName);+ if (usedNames.has(sanitized)) {+ const count = usedNames.get(sanitized) + 1;+ usedNames.set(sanitized, count);+ return `${sanitized}_${count}`;+ }+ usedNames.set(sanitized, 0);+ return sanitized;+ }++ function imageBytes(index) {+ const definition = document.images[index];+ if (definition.uri !== undefined) return resourceBytes.get(definition.uri);+ return reader.viewBytes(definition.bufferView);+ }++ function loadKtx2Image(bytes) {+ const loader = decoders.ktx2;+ const url = URL.createObjectURL(new Blob([bytes], { type: 'image/ktx2' }));+ return new Promise((resolve, reject) => loader.load(url, resolve, undefined, reject)).finally(() => URL.revokeObjectURL(url));+ }++ async function loadImage(sourceIndex, isKtx2) {+ const key = `${sourceIndex}:${isKtx2}`;+ if (images.has(key)) return images.get(key);+ const bytes = imageBytes(sourceIndex);+ let loaded;+ if (isKtx2) {+ const texture = await loadKtx2Image(bytes);+ loaded = { image: texture.image, isCompressedTexture: texture.isCompressedTexture === true };+ releasers.push(() => texture.dispose?.());+ } else {+ const image = await decodeImage(bytes, mimeTypeOf(document.images[sourceIndex], bytes));+ loaded = { image, isCompressedTexture: false };+ releasers.push(() => image.close?.());+ }+ images.set(key, loaded);+ return loaded;+ }++ async function loadTexture(textureIndex) {+ if (textures.has(textureIndex)) return textures.get(textureIndex);+ const definition = document.textures[textureIndex];+ const sampler = document.samplers?.[definition.sampler] ?? {};+ const { image, isCompressedTexture } = await loadImage(textureSourceIndex(definition), Boolean(definition.extensions?.KHR_texture_basisu));+ const texture = {+ image,+ isCompressedTexture,+ wrapS: sampler.wrapS ?? 10497,+ wrapT: sampler.wrapT ?? 10497,+ minFilter: sampler.minFilter ?? 9987,+ magFilter: sampler.magFilter ?? 9729,+ };+ textures.set(textureIndex, texture);+ return texture;+ }++ async function loadMaterial(materialIndex) {+ if (materials.has(materialIndex)) return materials.get(materialIndex);+ const definition = materialIndex === undefined ? {} : document.materials[materialIndex];+ const pbr = definition.pbrMetallicRoughness ?? {};+ const material = {+ materialIndex,+ color: (pbr.baseColorFactor ?? [1, 1, 1]).slice(0, 3),+ metalness: pbr.metallicFactor ?? 1,+ roughness: pbr.roughnessFactor ?? 1,+ emissive: [...(definition.emissiveFactor ?? [0, 0, 0])],+ emissiveIntensity: definition.extensions?.KHR_materials_emissive_strength?.emissiveStrength ?? 1,+ aoMapIntensity: definition.occlusionTexture?.strength ?? 1,+ };+ for (const [field, sourceField, inPbrBlock] of TEXTURE_SLOTS) {+ const reference = inPbrBlock ? pbr[sourceField] : definition[sourceField];+ if (!reference) continue;+ try {+ material[field] = await loadTexture(reference.index);+ } catch (error) {+ throw new Error(`${sourceField} failed to decode. Use a valid PNG or JPEG image. ${error.message}`);+ }+ }+ materials.set(materialIndex, material);+ return material;+ }++ function decodeDracoGeometry(primitive, extension) {+ const loader = decoders.draco;+ loader.preload?.();+ const attributeIds = {};+ const attributeTypes = {};+ for (const [semantic, id] of Object.entries(extension.attributes)) {+ const name = GEOMETRY_ATTRIBUTE_NAMES[semantic];+ if (!name) continue;+ attributeIds[name] = id;+ const accessor = document.accessors[primitive.attributes[semantic]];+ if (accessor) attributeTypes[name] = COMPONENT_TYPES[accessor.componentType].name;+ }+ const compressed = reader.viewBytes(extension.bufferView).slice().buffer;+ return new Promise((resolve, reject) => loader.decodeDracoFile(compressed, resolve, attributeIds, attributeTypes, LINEAR_SRGB, reject));+ }++ async function loadPrimitiveSource(meshIndex, primitiveIndex) {+ const key = `${meshIndex}:${primitiveIndex}`;+ if (sources.has(key)) return sources.get(key);+ const primitive = document.meshes[meshIndex].primitives[primitiveIndex];+ const dracoExtension = primitive.extensions?.KHR_draco_mesh_compression;+ const dracoGeometry = dracoExtension ? await decodeDracoGeometry(primitive, dracoExtension) : null;+ const attributes = {};+ for (const [semantic, accessorIndex] of Object.entries(primitive.attributes)) {+ const name = GEOMETRY_ATTRIBUTE_NAMES[semantic];+ if (!name) continue;+ if (dracoGeometry && dracoExtension.attributes[semantic] !== undefined) {+ const decoded = dracoGeometry.getAttribute(name);+ if (!decoded) throw new Error(`Draco geometry is missing ${semantic}.`);+ attributes[name] = decodedAttribute(decoded, document.accessors[accessorIndex]?.normalized === true);+ } else {+ attributes[name] = reader.readAccessor(accessorIndex);+ }+ }+ let index = null;+ if (primitive.indices !== undefined) index = dracoGeometry ? decodedAttribute(dracoGeometry.getIndex()) : reader.readAccessor(primitive.indices);+ const targets = primitive.targets ?? [];+ const source = {+ uuid: key,+ attributes,+ index,+ morphPositions: targets.map(target => target.POSITION === undefined ? undefined : reader.readAccessor(target.POSITION)),+ morphNormals: targets.map(target => target.NORMAL === undefined ? undefined : reader.readAccessor(target.NORMAL)),+ };+ sources.set(key, source);+ return source;+ }++ /** Raw joints and weights are checked before normalizing, so zero-weight vertices are reported. */+ function prepareSkinnedSource(source, jointCount) {+ if (source.skinPrepared) return;+ const { skinIndex, skinWeight, position } = source.attributes;+ validateSkinGeometry({ positions: { length: position.count * 3 }, skinIndices: attributeFloats(skinIndex), skinWeights: attributeFloats(skinWeight) }, createSkinPose(jointCount));+ source.attributes.skinWeight = normalizedWeights(skinWeight);+ source.skinPrepared = true;+ }++ function instanceMatricesFor(nodeIndex, extension) {+ if (instanceMatrices.has(nodeIndex)) return instanceMatrices.get(nodeIndex);+ const { TRANSLATION, ROTATION, SCALE } = extension.attributes;+ const translations = TRANSLATION === undefined ? null : attributeFloats(reader.readAccessor(TRANSLATION));+ const rotations = ROTATION === undefined ? null : attributeFloats(reader.readAccessor(ROTATION));+ const scales = SCALE === undefined ? null : attributeFloats(reader.readAccessor(SCALE));+ const count = [TRANSLATION, ROTATION, SCALE].filter(index => index !== undefined).map(index => document.accessors[index].count)[0];+ if (count > limits.maxInstances) throw new Error(`Decoded instance count ${count} exceeds maxInstances (${limits.maxInstances}).`);+ const matrices = new Float64Array(count * 16);+ for (let instance = 0; instance < count; instance++) {+ mat4.fromRotationTranslationScale(+ matrices.subarray(instance * 16, instance * 16 + 16),+ rotations ? rotations.subarray(instance * 4, instance * 4 + 4) : [0, 0, 0, 1],+ translations ? translations.subarray(instance * 3, instance * 3 + 3) : [0, 0, 0],+ scales ? scales.subarray(instance * 3, instance * 3 + 3) : [1, 1, 1],+ );+ }+ const result = { count, matrices };+ instanceMatrices.set(nodeIndex, result);+ return result;+ }++ function reserveMeshNames(meshIndex) {+ if (!meshNames.has(meshIndex)) {+ const mesh = document.meshes[meshIndex];+ const baseName = mesh.name || `mesh_${meshIndex}`;+ meshNames.set(meshIndex, mesh.primitives.map(() => uniqueName(baseName)));+ }+ return meshNames.get(meshIndex);+ }++ async function createPrimitiveObject(definition, nodeIndex, meshIndex, primitiveIndex) {+ const mesh = document.meshes[meshIndex];+ const primitive = mesh.primitives[primitiveIndex];+ const object = new SceneNode();+ object.isMesh = true;+ object.geometry = await loadPrimitiveSource(meshIndex, primitiveIndex);+ object.material = await loadMaterial(primitive.material);+ object.name = reserveMeshNames(meshIndex)[primitiveIndex];+ object.association = { meshes: meshIndex, primitives: primitiveIndex };+ if (definition.skin !== undefined) {+ object.isSkinnedMesh = true;+ prepareSkinnedSource(object.geometry, document.skins[definition.skin].joints.length);+ }+ const targetCount = primitive.targets?.length ?? 0;+ if (targetCount) {+ object.morphTargetInfluences = Array.from({ length: targetCount }, (unused, target) => definition.weights?.[target] ?? mesh.weights?.[target] ?? 0);+ }+ const instancing = definition.extensions?.EXT_mesh_gpu_instancing;+ if (instancing) {+ const { count, matrices } = instanceMatricesFor(nodeIndex, instancing);+ object.isInstancedMesh = true;+ object.count = count;+ object.instanceMatrices = matrices;+ }+ return object;+ }++ async function loadSkeleton(skinIndex) {+ if (skeletons.has(skinIndex)) return skeletons.get(skinIndex);+ const skin = document.skins[skinIndex];+ const bones = [];+ for (const joint of skin.joints) bones.push(await buildNode(joint));+ const inverseValues = skin.inverseBindMatrices === undefined ? null : attributeFloats(reader.readAccessor(skin.inverseBindMatrices));+ const boneInverses = bones.map((bone, index) => inverseValues ? new Matrix4().fromArray(inverseValues, index * 16) : new Matrix4());+ const skeleton = { bones, boneInverses, dispose() {} };+ skeletons.set(skinIndex, skeleton);+ return skeleton;+ }++ async function buildNode(nodeIndex) {+ if (nodeCache.has(nodeIndex)) return nodeCache.get(nodeIndex);+ const definition = document.nodes[nodeIndex];+ const nodeName = definition.name ? uniqueName(definition.name) : '';+ const objects = [];+ if (definition.mesh !== undefined) {+ for (let primitiveIndex = 0; primitiveIndex < document.meshes[definition.mesh].primitives.length; primitiveIndex++) {+ objects.push(await createPrimitiveObject(definition, nodeIndex, definition.mesh, primitiveIndex));+ }+ }+ let node;+ if (objects.length === 1) {+ node = objects[0];+ } else {+ node = new SceneNode();+ if (objects.length) node.association = { meshes: definition.mesh };+ for (const object of objects) node.add(object);+ }+ if (definition.name) node.name = nodeName;+ node.association = { ...node.association, nodes: nodeIndex };+ if (definition.matrix !== undefined) new Matrix4().fromArray(definition.matrix).decompose(node.position, node.quaternion, node.scale);+ if (definition.translation !== undefined) node.position.fromArray(definition.translation);+ if (definition.rotation !== undefined) node.quaternion.fromArray(definition.rotation);+ if (definition.scale !== undefined) node.scale.fromArray(definition.scale);+ nodeCache.set(nodeIndex, node);+ if (definition.skin !== undefined) {+ const skeleton = await loadSkeleton(definition.skin);+ node.traverse(candidate => {+ if (!candidate.isSkinnedMesh) return;+ candidate.skeleton = skeleton;+ candidate.bindMatrix = new Matrix4();+ });+ }+ for (const childIndex of definition.children ?? []) node.add(await buildNode(childIndex));+ return node;+ }++ const release = () => releasers.forEach(releaseOne => releaseOne());+ try {+ const sceneDefinition = document.scenes?.[document.scene ?? 0];+ if (!sceneDefinition) throw new Error('glTF has no default scene.');+ const scene = new SceneNode();+ for (const rootIndex of sceneDefinition.nodes ?? []) scene.add(await buildNode(rootIndex));+ for (const animation of document.animations ?? []) {+ for (const channel of animation.channels ?? []) {+ if (channel.target.node !== undefined) await buildNode(channel.target.node);+ }+ }+ const animations = createClips(document, index => nodeCache.get(index), reader.readAccessor);+ scene.updateMatrixWorld();+ return { scene, animations, release };+ } catch (error) {+ release();+ throw error;+ }+}diff --git a/src/gltf-nodes.js b/src/gltf-nodes.jsnew file mode 100644index 00000000..0cfb55b7--- /dev/null+++ b/src/gltf-nodes.js@@ -0,0 +1,115 @@+import { mat4, quat } from 'gl-matrix';++/** A fixed-size vector of doubles that reads and writes plain arrays. */+export class TransformVector {+ constructor(values) {+ this.values = values;+ }++ toArray() {+ return [...this.values];+ }++ fromArray(array, offset = 0) {+ for (let index = 0; index < this.values.length; index++) this.values[index] = array[offset + index];+ return this;+ }+}++/** A column-major 4x4 matrix with double precision, the shape the glTF import reads. */+export class Matrix4 {+ constructor() {+ this.elements = mat4.identity(new Float64Array(16));+ }++ fromArray(array, offset = 0) {+ for (let index = 0; index < 16; index++) this.elements[index] = array[offset + index];+ return this;+ }++ copy(other) {+ this.elements.set(other.elements);+ return this;+ }++ multiplyMatrices(left, right) {+ mat4.multiply(this.elements, left.elements, right.elements);+ return this;+ }++ determinant() {+ return mat4.determinant(this.elements);+ }++ compose(position, rotation, scale) {+ mat4.fromRotationTranslationScale(this.elements, rotation.values, position.values, scale.values);+ return this;+ }++ /** Split into translation, rotation and scale. A reflection goes into the X scale, as three.js does. */+ decompose(position, rotation, scale) {+ const e = this.elements;+ let scaleX = Math.hypot(e[0], e[1], e[2]);+ const scaleY = Math.hypot(e[4], e[5], e[6]);+ const scaleZ = Math.hypot(e[8], e[9], e[10]);+ if (this.determinant() < 0) scaleX = -scaleX;+ position.fromArray([e[12], e[13], e[14]]);+ const rotationMatrix = new Float64Array(16);+ rotationMatrix[15] = 1;+ for (let row = 0; row < 3; row++) {+ rotationMatrix[row] = e[row] / scaleX;+ rotationMatrix[4 + row] = e[4 + row] / scaleY;+ rotationMatrix[8 + row] = e[8 + row] / scaleZ;+ }+ rotation.fromArray(quat.normalize(new Float64Array(4), mat4.getRotation(new Float64Array(4), rotationMatrix)));+ scale.fromArray([scaleX, scaleY, scaleZ]);+ return this;+ }+}++let nextNodeId = 1;++/** One decoded glTF node or mesh primitive, with just the transform and mesh fields the import reads. */+export class SceneNode {+ constructor() {+ this.uuid = `node-uuid-${nextNodeId++}`;+ this.name = '';+ this.parent = null;+ this.children = [];+ this.position = new TransformVector([0, 0, 0]);+ this.quaternion = new TransformVector([0, 0, 0, 1]);+ this.scale = new TransformVector([1, 1, 1]);+ this.matrix = new Matrix4();+ this.matrixWorld = new Matrix4();+ this.matrixAutoUpdate = true;+ this.matrixWorldNeedsUpdate = false;+ this.association = {};+ }++ add(child) {+ child.parent = this;+ this.children.push(child);+ }++ traverse(visit) {+ visit(this);+ for (const child of this.children) child.traverse(visit);+ }++ updateMatrix() {+ this.matrix.compose(this.position, this.quaternion, this.scale);+ this.matrixWorldNeedsUpdate = true;+ }++ updateMatrixWorld() {+ if (this.matrixAutoUpdate) this.updateMatrix();+ if (this.parent) this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix);+ else this.matrixWorld.copy(this.matrix);+ this.matrixWorldNeedsUpdate = false;+ for (const child of this.children) child.updateMatrixWorld();+ }++ getMatrixAt(index, target) {+ return target.fromArray(this.instanceMatrices, index * 16);+ }+}diff --git a/src/gltf.js b/src/gltf.jsindex 982d86d2..4b8b9eda 100644--- a/src/gltf.js+++ b/src/gltf.js@@ -1,5 +1,7 @@-import { AnimationMixer, LoadingManager, LoopOnce, Matrix4 } from 'three';-import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';+import { applyClip } from './gltf-animation.js';+import { attributeFloats } from './gltf-accessors.js';+import { decodeGltf, textureSourceIndex } from './gltf-decode.js';+import { Matrix4 } from './gltf-nodes.js';import { textureDescriptorInfo } from './renderer.js';import { createSkinPose, updateSkinPose, validateSkinGeometry, validateSkinPose } from './skinning.js';import { MAX_MORPH_TARGETS, createMorphPose, validateMorphGeometry, validateMorphPose, validateMorphTransform } from './morph.js';@@ -20,8 +22,6 @@ const DECODER_BY_EXTENSION = { KHR_draco_mesh_compression: 'draco', EXT_meshopt_// Accepted when optional, because 67.js does not render them. Rejected when listed in extensionsRequired.const IGNORED_EXTENSIONS = new Set(GLTF_CAPABILITIES.ignoredExtensions);const IDENTITY_UV_TRANSFORM = Object.freeze({ offset: [0, 0], rotation: 0, scale: [1, 1] });-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'],@@ -385,10 +385,6 @@ function validateDocument(document, limits, allowedExtensions) {return { vertices, ignoredExtensions };}-function textureSourceIndex(texture) {- return texture.extensions?.KHR_texture_basisu?.source ?? texture.source;-}-function validateHierarchy(nodes) {const parents = new Set();for (const node of nodes) {@@ -509,108 +505,100 @@ async function boundedFetch(url, maxBytes, signal) {}async function prepareResources(document, data, dataBytes, options, limits) {- const resources = new Map();const resourceBytes = new Map();- const objectUrls = [];const definitions = [...(document.buffers ?? []), ...(document.images ?? [])];const uris = new Set(definitions.map(resource => resource.uri).filter(uri => uri !== undefined));if (uris.size > limits.maxResources) throw new Error('glTF resources exceed maxResources.');let usedBytes = dataBytes;- try {- for (const uri of uris) {- if (typeof uri !== 'string') throw new Error('Invalid glTF resource URI.');- if (uri.startsWith('data:')) {- resourceBytes.set(uri, dataUriBytes(uri));- resources.set(uri, uri);- continue;- }- if (!options.baseUrl && !/^(https?:|blob:)/.test(uri)) throw new Error('External glTF resources require baseUrl. Use GLB for a self-contained local file.');- const resolved = new URL(uri, options.baseUrl || undefined).href;- if (!/^(https?:|blob:)/.test(resolved)) throw new Error('Only HTTP, HTTPS, blob and embedded data resources are supported.');- const resource = await boundedFetch(resolved, limits.maxBytes - usedBytes, options.signal);- usedBytes += resource.bytes.byteLength;- resourceBytes.set(uri, resource.bytes);- const objectUrl = URL.createObjectURL(new Blob([resource.bytes], { type: resource.mimeType }));- objectUrls.push(objectUrl);- resources.set(resolved, objectUrl);+ for (const uri of uris) {+ if (typeof uri !== 'string') throw new Error('Invalid glTF resource URI.');+ if (uri.startsWith('data:')) {+ resourceBytes.set(uri, dataUriBytes(uri));+ continue;}- let texturePixels = 0;- for (const image of document.images ?? []) {- let bytes = resourceBytes.get(image.uri);- if (!bytes && image.bufferView !== undefined) {- const view = document.bufferViews?.[image.bufferView];- const buffer = view && document.buffers?.[view.buffer];- const source = buffer?.uri ? resourceBytes.get(buffer.uri) : view?.buffer === 0 ? binaryChunk(data) : null;- const offset = view?.byteOffset ?? 0;- if (!source || !Number.isSafeInteger(view.byteLength) || view.byteLength < 0 || offset < 0 || offset + view.byteLength > source.length) {- throw new Error('Invalid embedded glTF image buffer view.');- }- bytes = source.subarray(offset, offset + view.byteLength);+ if (!options.baseUrl && !/^(https?:|blob:)/.test(uri)) throw new Error('External glTF resources require baseUrl. Use GLB for a self-contained local file.');+ const resolved = new URL(uri, options.baseUrl || undefined).href;+ if (!/^(https?:|blob:)/.test(resolved)) throw new Error('Only HTTP, HTTPS, blob and embedded data resources are supported.');+ const resource = await boundedFetch(resolved, limits.maxBytes - usedBytes, options.signal);+ usedBytes += resource.bytes.byteLength;+ resourceBytes.set(uri, resource.bytes);+ }+ let texturePixels = 0;+ for (const image of document.images ?? []) {+ let bytes = resourceBytes.get(image.uri);+ if (!bytes && image.bufferView !== undefined) {+ const view = document.bufferViews?.[image.bufferView];+ const buffer = view && document.buffers?.[view.buffer];+ const source = buffer?.uri ? resourceBytes.get(buffer.uri) : view?.buffer === 0 ? binaryChunk(data) : null;+ const offset = view?.byteOffset ?? 0;+ if (!source || !Number.isSafeInteger(view.byteLength) || view.byteLength < 0 || offset < 0 || offset + view.byteLength > source.length) {+ throw new Error('Invalid embedded glTF image buffer view.');}- 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.');+ bytes = source.subarray(offset, offset + view.byteLength);}- return { resources, objectUrls };- } catch (error) {- objectUrls.forEach(url => URL.revokeObjectURL(url));- throw error;+ 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.');}+ return resourceBytes;+ return resourceBytes;}function copyAttribute(attribute, size) {if (attribute.itemSize !== size) throw new Error(`Expected a ${size}-component mesh attribute.`);- const result = new Float32Array(attribute.count * size);- const getters = ['getX', 'getY', 'getZ', 'getW'];- for (let vertex = 0; vertex < attribute.count; vertex++) {- for (let component = 0; component < size; component++) {- const value = attribute[getters[component]](vertex);- if (!Number.isFinite(value)) throw new Error('Mesh attributes must contain finite values.');- result[vertex * size + component] = value;+ const values = attributeFloats(attribute);+ if (!values.every(Number.isFinite)) throw new Error('Mesh attributes must contain finite values.');+ return values;+}++function computeVertexNormals(positions, indices) {+ const normals = new Float32Array(positions.length);+ for (let corner = 0; corner < indices.length; corner += 3) {+ const [first, second, third] = [indices[corner] * 3, indices[corner + 1] * 3, indices[corner + 2] * 3];+ const edgeAB = [positions[second] - positions[first], positions[second + 1] - positions[first + 1], positions[second + 2] - positions[first + 2]];+ const edgeAC = [positions[third] - positions[first], positions[third + 1] - positions[first + 1], positions[third + 2] - positions[first + 2]];+ const cross = [edgeAB[1] * edgeAC[2] - edgeAB[2] * edgeAC[1], edgeAB[2] * edgeAC[0] - edgeAB[0] * edgeAC[2], edgeAB[0] * edgeAC[1] - edgeAB[1] * edgeAC[0]];+ for (const vertexOffset of [first, second, third]) {+ for (let axis = 0; axis < 3; axis++) normals[vertexOffset + axis] += cross[axis];}}- return result;+ return normals;}function convertGeometry(source, mirrored, primitive) {- const position = source.getAttribute('position');- if (!source.getAttribute('normal')) source.computeVertexNormals();- if (source.getAttribute('normal').count !== position.count) throw new Error('NORMAL and POSITION counts must match.');- const geometry = { positions: copyAttribute(position, 3), normals: copyAttribute(source.getAttribute('normal'), 3) };- for (let offset = 0; offset < geometry.normals.length; offset += 3) {- const length = Math.hypot(...geometry.normals.subarray(offset, offset + 3));- if (length < 1e-8) throw new Error('Degenerate geometry has no usable vertex normal.');- for (let axis = 0; axis < 3; axis++) geometry.normals[offset + axis] /= length;- }- const sourceIndex = source.getIndex();- geometry.indices = new Uint32Array(sourceIndex?.count ?? position.count);- for (let index = 0; index < geometry.indices.length; index++) {- const value = sourceIndex ? sourceIndex.getX(index) : index;+ const { position, normal, uv, color, skinIndex, skinWeight } = source.attributes;+ const positions = copyAttribute(position, 3);+ const indices = new Uint32Array(source.index?.count ?? position.count);+ for (let index = 0; index < indices.length; index++) {+ const value = source.index ? source.index.array[index] : index;if (!Number.isInteger(value) || value < 0 || value >= position.count) throw new Error('Mesh index is out of range.');- geometry.indices[index] = value;+ indices[index] = value;+ }+ if (normal && normal.count !== position.count) throw new Error('NORMAL and POSITION counts must match.');+ const normals = normal ? copyAttribute(normal, 3) : computeVertexNormals(positions, indices);+ const geometry = { positions, normals, indices };+ for (let offset = 0; offset < normals.length; offset += 3) {+ const length = Math.hypot(...normals.subarray(offset, offset + 3));+ if (length < 1e-8) throw new Error('Degenerate geometry has no usable vertex normal.');+ for (let axis = 0; axis < 3; axis++) normals[offset + axis] /= length;}if (mirrored) {- for (let index = 0; index < geometry.indices.length; index += 3) {- const second = geometry.indices[index + 1];- geometry.indices[index + 1] = geometry.indices[index + 2];- geometry.indices[index + 2] = second;+ for (let index = 0; index < indices.length; index += 3) {+ const second = indices[index + 1];+ indices[index + 1] = indices[index + 2];+ indices[index + 2] = second;}}- const uv = source.getAttribute('uv');if (uv && uv.count !== position.count) throw new Error('TEXCOORD_0 and POSITION counts must match.');if (uv) geometry.uvs = copyAttribute(uv, 2);- const color = source.getAttribute('color');if (color) geometry.colors = convertVertexColors(color, position.count);- const skinIndices = source.getAttribute('skinIndex');- const skinWeights = source.getAttribute('skinWeight');- if (skinIndices) geometry.skinIndices = new Uint16Array(copyAttribute(skinIndices, 4));- if (skinWeights) geometry.skinWeights = copyAttribute(skinWeights, 4);+ if (skinIndex) geometry.skinIndices = new Uint16Array(copyAttribute(skinIndex, 4));+ if (skinWeight) geometry.skinWeights = copyAttribute(skinWeight, 4);if (primitive.targets?.length) {- if (!source.morphTargetsRelative) throw new Error('Decoded morph targets must contain relative deltas.');geometry.morphTargets = primitive.targets.map((target, index) => {const channels = {};- if (target.POSITION !== undefined) channels.positions = copyAttribute(source.morphAttributes.position[index], 3);- if (target.NORMAL !== undefined) channels.normals = copyAttribute(source.morphAttributes.normal[index], 3);+ if (target.POSITION !== undefined) channels.positions = copyAttribute(source.morphPositions[index], 3);+ if (target.NORMAL !== undefined) channels.normals = copyAttribute(source.morphNormals[index], 3);return channels;});}@@ -675,28 +663,6 @@ function validateNodeTransforms(nodes, pending, transform) {}}-function copyPrimitiveAssociations(original, decoded, associations) {- const association = associations.get(original);- if (original.isMesh && !association) throw new Error('Decoded mesh lost its original primitive association.');- if (association) associations.set(decoded, association);- if (original.children.length !== decoded.children.length) throw new Error('Decoded scene clone changed the node hierarchy.');- for (let index = 0; index < original.children.length; index++) {- copyPrimitiveAssociations(original.children[index], decoded.children[index], associations);- }-}--/** Three.js builds instanced meshes after it records associations, so restore the mesh and primitive indices here. */-function completeInstancedAssociations(object, associations, document, inheritedNodeIndex) {- const association = associations.get(object);- const ownsNode = Number.isInteger(association?.nodes);- const nodeIndex = ownsNode ? association.nodes : inheritedNodeIndex;- if (object.isInstancedMesh && association?.primitives === undefined) {- const siblingPrimitives = ownsNode || !object.parent ? [object] : object.parent.children.filter(child => child.isInstancedMesh && !Number.isInteger(associations.get(child)?.nodes));- associations.set(object, { ...association, meshes: document.nodes?.[nodeIndex]?.mesh, primitives: siblingPrimitives.indexOf(object) });- }- for (const child of object.children) completeInstancedAssociations(child, associations, document, nodeIndex);-}-function instanceMatricesOf(node, maximumInstances) {if (!node.isInstancedMesh) return [null];if (node.count > maximumInstances) throw new Error(`Decoded instance count ${node.count} exceeds maxInstances (${maximumInstances}).`);@@ -711,75 +677,6 @@ function worldMatrixOf(node, instanceMatrix, target) {return instanceMatrix ? target.multiplyMatrices(node.matrixWorld, instanceMatrix) : target.copy(node.matrixWorld);}-function skinPreflightPlugin(parser, document, primitiveAssociations) {- let originalRoots;- return {- name: '67SkinPreflight',- async beforeRoot() {- for (const mesh of document.meshes ?? []) {- for (const primitive of mesh.primitives ?? []) {- for (const target of primitive.targets ?? []) {- for (const accessor of Object.values(target)) copyAttribute(await parser.getDependency('accessor', accessor), 3);- }- }- }- for (const animation of document.animations ?? []) {- for (const channel of animation.channels ?? []) {- if (channel.target.node === undefined) continue;- const sampler = animation.samplers[channel.sampler];- const input = copyAttribute(await parser.getDependency('accessor', sampler.input), 1);- for (let index = 0; index < input.length; index++) {- if (input[index] < 0 || index && input[index] <= input[index - 1]) throw new Error('Animation times must be nonnegative and strictly increasing.');- }- const size = channel.target.path === 'rotation' ? 4 : channel.target.path === 'weights' ? 1 : 3;- const output = copyAttribute(await parser.getDependency('accessor', sampler.output), size);- if (channel.target.path === 'rotation') {- const cubic = sampler.interpolation === 'CUBICSPLINE';- for (let offset = cubic ? 4 : 0; offset < output.length; offset += cubic ? 12 : 4) {- const length = Math.hypot(output[offset], output[offset + 1], output[offset + 2], output[offset + 3]);- if (Math.abs(length - 1) > 0.01) throw new Error('Animation rotation values require unit quaternions.');- }- }- }- }- for (const node of document.nodes ?? []) {- if (node.skin === undefined) continue;- const pose = createSkinPose(document.skins[node.skin].joints.length);- for (const primitive of document.meshes[node.mesh].primitives) {- const [joints, weights] = await Promise.all([- parser.getDependency('accessor', primitive.attributes.JOINTS_0),- parser.getDependency('accessor', primitive.attributes.WEIGHTS_0),- ]);- validateSkinGeometry({ positions: { length: weights.count * 3 }, skinIndices: copyAttribute(joints, 4), skinWeights: copyAttribute(weights, 4) }, pose);- }- }- // loadScene reduces parser.associations globally, so capture before any scene loads.- const rootIndices = new Set();- for (const scene of document.scenes ?? []) {- for (const root of scene.nodes ?? []) rootIndices.add(root);- }- const roots = await Promise.all(Array.from(rootIndices, async index => [index, await parser.getDependency('node', index)]));- originalRoots = new Map(roots);- for (const [, root] of roots) completeInstancedAssociations(root, parser.associations, document, undefined);- for (const [node, association] of parser.associations) {- if (node.isMesh || Number.isInteger(association?.nodes)) {- primitiveAssociations.set(node, Object.freeze({ ...association }));- }- }- },- afterRoot(result) {- for (let index = 0; index < result.scenes.length; index++) {- const roots = document.scenes[index].nodes ?? [];- const scene = result.scenes[index];- if (roots.length !== scene.children.length) throw new Error('Decoded scene root count changed.');- for (let root = 0; root < roots.length; root++) {- copyPrimitiveAssociations(originalRoots.get(roots[root]), scene.children[root], primitiveAssociations);- }- }- },- };-}-function convertVertexColors(attribute, vertexCount) {if (attribute.count !== vertexCount || ![3, 4].includes(attribute.itemSize)) {throw new Error('COLOR_0 requires matching RGB or RGBA vertex values.');@@ -814,11 +711,11 @@ function decodedTextureImage(texture, field) {function convertMaterial(source, limits, maps, definition = {}) {const material = {tag: 'gltf',- color: source.color.toArray(),+ color: [...source.color],metallic: source.metalness,roughness: source.roughness,emission: source.emissiveIntensity ?? 1,- emissiveColor: source.emissive.toArray(),+ emissiveColor: [...source.emissive],normalScale: [definition.normalTexture?.scale ?? 1, definition.normalTexture?.scale ?? 1],occlusionStrength: source.aoMapIntensity,};@@ -842,10 +739,10 @@ function convertMaterial(source, limits, maps, definition = {}) {const descriptor = {image,uvChannel: 0,- wrapS: WRAPPING[texture.wrapS],- wrapT: WRAPPING[texture.wrapT],- minFilter: FILTERING[texture.minFilter],- magFilter: FILTERING[texture.magFilter],+ wrapS: texture.wrapS,+ wrapT: texture.wrapT,+ minFilter: texture.minFilter,+ magFilter: texture.magFilter,flipY: false,colorSpace,};@@ -857,33 +754,7 @@ function convertMaterial(source, limits, maps, definition = {}) {return material;}-function releaseParsed(gltf) {- const geometries = new Set();- const materials = new Set();- const textures = new Set();- const images = new Set();- const skeletons = new Set();- for (const scene of gltf.scenes) {- scene.traverse(node => {- if (node.geometry) geometries.add(node.geometry);- if (node.skeleton) skeletons.add(node.skeleton);- for (const material of Array.isArray(node.material) ? node.material : node.material ? [node.material] : []) {- materials.add(material);- for (const value of Object.values(material)) if (value?.isTexture) textures.add(value);- }- });- }- geometries.forEach(geometry => geometry.dispose());- materials.forEach(material => material.dispose());- textures.forEach(texture => {- if (texture.image) images.add(texture.image);- texture.dispose();- });- images.forEach(image => image.close?.());- skeletons.forEach(skeleton => skeleton.dispose());-}--/** Parse a bounded glTF 2.0 asset into Renderer67 parts. Three.js only decodes the asset. */+/** Parse a bounded glTF 2.0 asset into Renderer67 parts. Draco, meshopt and KTX2 decoders come from options.decoders. */export async function parseGltf(data, options = {}) {const limits = limitsFor(options);const document = documentFrom(data, limits.maxBytes);@@ -891,25 +762,10 @@ export async function parseGltf(data, options = {}) {const { ignoredExtensions } = validateDocument(document, limits, allowedExtensionsFor(decoders));const warnings = ignoredExtensions.map(extension => `${extension} is accepted but not rendered.`);const dataBytes = typeof data === 'string' ? new TextEncoder().encode(data).byteLength : data.byteLength;- const { resources, objectUrls } = await prepareResources(document, data, dataBytes, options, limits);- const manager = new LoadingManager();- manager.setURLModifier(url => {- if (resources.has(url)) return resources.get(url);- const normalized = new URL(url, options.baseUrl || undefined).href;- if (resources.has(normalized)) return resources.get(normalized);- if (url.startsWith('blob:')) return url;- throw new Error(`Unregistered glTF resource: ${url}.`);- });+ const resourceBytes = await prepareResources(document, data, dataBytes, options, limits);let gltf;- const primitiveAssociations = new WeakMap();try {- const loader = new GLTFLoader(manager);- if (decoders.draco) loader.setDRACOLoader(decoders.draco);- if (decoders.meshopt) loader.setMeshoptDecoder(decoders.meshopt);- if (decoders.ktx2) loader.setKTX2Loader(decoders.ktx2);- loader.register(parser => skinPreflightPlugin(parser, document, primitiveAssociations));- gltf = await loader.parseAsync(data, options.baseUrl ?? '');- gltf.scene.updateMatrixWorld(true);+ gltf = await decodeGltf({ document, glbBinary: binaryChunk(data), resourceBytes, decoders, limits });const parts = [];const bindings = [];const skinBindings = [];@@ -925,15 +781,11 @@ export async function parseGltf(data, options = {}) {gltf.scene.traverse(node => {nodes.push(node);if (!node.isMesh) return;- const association = primitiveAssociations.get(node);+ const association = node.association;const primitive = document.meshes?.[association?.meshes]?.primitives?.[association?.primitives];if (!primitive) throw new Error('Decoded mesh requires a valid original primitive association.');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;- 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 materialIndex = node.material.materialIndex;const uvTransform = materialUvTransform(document.materials?.[materialIndex] ?? {});const uvKey = uvTransformKey(uvTransform);if (!materials.has(node.material)) materials.set(node.material, convertMaterial(node.material, limits, maps, document.materials?.[materialIndex]));@@ -945,7 +797,7 @@ export async function parseGltf(data, options = {}) {const geometryMirrored = node.isSkinnedMesh ? false : mirrored;const geometryKey = `${node.geometry.uuid}:${geometryMirrored}:${uvKey}`;if (!geometries.has(geometryKey)) {- actualVertices += node.geometry.getAttribute('position').count * (1 + (primitive.targets?.length ?? 0));+ actualVertices += node.geometry.attributes.position.count * (1 + (primitive.targets?.length ?? 0));if (actualVertices > limits.maxVertices) throw new Error('Decoded geometry exceeds maxVertices.');const converted = convertGeometry(node.geometry, geometryMirrored, primitive);if (converted.uvs) bakeUvTransform(converted.uvs, uvTransform);@@ -982,7 +834,7 @@ export async function parseGltf(data, options = {}) {if (!parts.length) throw new Error('glTF scene contains no supported triangle meshes.');const sourceNodes = new Map();for (const node of nodes) {- const index = primitiveAssociations.get(node)?.nodes;+ const index = node.association.nodes;if (index === undefined) continue;const id = `node-${index}`;if (sourceNodes.has(id)) {@@ -1028,7 +880,6 @@ export async function parseGltf(data, options = {}) {for (const binding of morphBindings) {candidateParts[bindings.findIndex(transform => transform.node === binding.node)].morph = binding.pendingPose;}- const mixer = new AnimationMixer(gltf.scene);let disposed = false;let pendingTransaction;let currentAnimation = null;@@ -1060,19 +911,11 @@ export async function parseGltf(data, options = {}) {const basePose = capturePrivatePose();function playAnimation(animation) {- mixer.stopAllAction();restorePrivatePose(basePose);- mixer.setTime(0);if (animation === null) {return;}- const clip = gltf.animations[animation.clip];- const action = mixer.clipAction(clip);- action.reset();- action.setLoop(LoopOnce, 1);- action.clampWhenFinished = true;- action.play();- mixer.setTime(animation.time);+ applyClip(gltf.animations[animation.clip], animation.time);}function preparePose() {@@ -1286,10 +1129,7 @@ export async function parseGltf(data, options = {}) {}pendingTransaction?.discard();disposed = true;- mixer.stopAllAction();- mixer.uncacheRoot(gltf.scene);- releaseParsed(gltf);- objectUrls.forEach(url => URL.revokeObjectURL(url));+ gltf.release();}function applyAnimation(time, clipIndex = 0) {@@ -1308,8 +1148,7 @@ export async function parseGltf(data, options = {}) {return { parts, warnings, skins: skinBindings.map(binding => binding.skin), animations: gltf.animations,get nodes() { return structuredClone(nodeMetadata); }, stagePose, applyAnimation, dispose, capabilities: GLTF_CAPABILITIES };} catch (error) {- if (gltf) releaseParsed(gltf);- objectUrls.forEach(url => URL.revokeObjectURL(url));+ gltf?.release();throw error;}}diff --git a/tests/gltf-morph.test.js b/tests/gltf-morph.test.jsindex 0ee0f4b5..cf0125a0 100644--- a/tests/gltf-morph.test.js+++ b/tests/gltf-morph.test.js@@ -1,6 +1,5 @@import test from 'node:test';import assert from 'node:assert/strict';-import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';import { parseGltf } from '../src/gltf.js';import { skinnedStripAsset } from './fixtures/skinned-strip.js';@@ -135,28 +134,7 @@ test('multi-scene multi-primitive mappings retain each distinct morph channel de}});-test('association capture does not decode orphan meshes and disposes all decoded geometry', async context => {- const decodedMeshes = [];- const decodedGeometries = new Set();- const disposedGeometries = new Set();- const originalParse = GLTFLoader.prototype.parseAsync;- context.mock.method(GLTFLoader.prototype, 'parseAsync', function (...argumentsList) {- this.register(parser => ({- name: 'MorphLifecycleProbe',- loadMesh(index) {- decodedMeshes.push(index);- return parser.loadMesh(index).then(mesh => {- mesh.traverse(node => {- if (!node.geometry || decodedGeometries.has(node.geometry)) return;- decodedGeometries.add(node.geometry);- node.geometry.addEventListener('dispose', () => disposedGeometries.add(node.geometry));- });- return mesh;- });- },- }));- return originalParse.apply(this, argumentsList);- });+test('only the selected scene is decoded', async () => {const asset = await parseGltf(morphAsset((document, append) => {document.scenes = [{ nodes: [0] }, { nodes: [1] }];const positions = append(new Float32Array([0, 0, 0, 2, 0, 0, 0, 2, 0]), 'VEC3');@@ -164,10 +142,9 @@ test('association capture does not decode orphan meshes and disposes all decodeddocument.meshes.push({ primitives: [{ attributes: { POSITION: positions, NORMAL: 1 } }] });document.nodes.push({ name: 'Orphan', mesh: 1 });}));- assert.deepEqual(decodedMeshes, [0]);- assert.equal(decodedGeometries.size, 1);+ assert.equal(asset.parts.length, 1);+ assert.equal(asset.nodes.length, 1);asset.dispose();- assert.equal(disposedGeometries.size, decodedGeometries.size);});test('embedded glTF JSON defaults omitted node and mesh weights to retained zeros', async () => {@@ -239,9 +216,7 @@ test('morphs compose with skin palettes and invalid samples publish no matrix, passet.dispose();});-test('target expansion and primitive instance budgets reject before loader decoding', async context => {- let calls = 0;- context.mock.method(GLTFLoader.prototype, 'parseAsync', () => { calls++; throw new Error('Unexpected decode'); });+test('target expansion and primitive instance budgets reject before decoding', async () => {await assert.rejects(parseGltf(morphAsset(), { maxVertices: 8 }), /maxVertices/);await assert.rejects(parseGltf(morphAsset(document => {document.meshes[0].primitives = Array.from({ length: 3 }, () => document.meshes[0].primitives[0]);@@ -256,7 +231,6 @@ test('target expansion and primitive instance budgets reject before loader decodprimitive.targets = Array.from({ length: 64 }, () => ({ POSITION: positions }));});await assert.rejects(parseGltf(repeated, { maxBytes: repeated.byteLength }), /Decoded glTF accessors/);- assert.equal(calls, 0);});test('composed world bounds and changed public identities fail before any part publishes', async () => {diff --git a/tests/gltf.test.js b/tests/gltf.test.jsindex e23b1e3d..b5dc93e6 100644--- a/tests/gltf.test.js+++ b/tests/gltf.test.js@@ -1,6 +1,5 @@import assert from 'node:assert/strict';import test from 'node:test';-import { Texture } from 'three';import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';import { Matrix4, Vector3 } from 'three';import { skinnedStripAsset } from './fixtures/skinned-strip.js';@@ -342,12 +341,6 @@ test('all glTF map channels preserve sampler, linear data, sRGB color, scales, sif (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);@@ -372,7 +365,6 @@ test('all glTF map channels preserve sampler, linear data, sRGB color, scales, sasset.dispose();asset.dispose();assert.equal(closed, 1);- assert.equal(disposedTextures.size, 1);assert.ok(GLTF_CAPABILITIES.supported.includes('normal/occlusion/emissive/metallic-roughness textures'));});