Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Decode EXT_meshopt_compression inside loadGltf (closes #461)

Nguyen Xuan Ana8f9b6b2432b
diff --git a/changes/461.md b/changes/461.md
new file mode 100644
index 00000000..3735dcd9
--- /dev/null
+++ b/changes/461.md
@@ -0,0 +1 @@
+- Decode EXT_meshopt_compression inside `loadGltf` and `parseGltf` (closes #461). Attribute, triangle and index modes with the NONE, OCTAHEDRAL, QUATERNION and EXPONENTIAL filters decode with no `options.decoders.meshopt`, so gltfpack and Sketchfab files, `public/wall-e.glb` and the three showcase worlds (both parts each) open, and so do they in the MCP asset catalog and `scene_create_asset`. The decoder is meshoptimizer's WebAssembly build that three.js already ships, in a chunk (`src/gltf-meshopt.js`) that only a file with a compressed buffer view loads: entry:core, lit-box, gltf-box and agent-scene do not grow (gltf-box -31 B gzip). The fallback buffer is never read and does not count against `maxBytes`, so it may be absent or an unreachable `uri`. A view that fails to decode throws `EXT_meshopt_compression could not decode a buffer view` with its mode and filter. `options.decoders.meshopt` still replaces the built-in decoder. The showcase page no longer imports a decoder itself.
diff --git a/changes/461.size.md b/changes/461.size.md
new file mode 100644
index 00000000..5809dc79
--- /dev/null
+++ b/changes/461.size.md
@@ -0,0 +1,2 @@
+- entry:gltf+lazy: the meshopt decoder chunk (7,669 bytes gzip) is the price of opening compressed GLBs, which the MCP catalog, `public/wall-e.glb`, gltfpack and Sketchfab files need; it loads only when a file has a meshopt buffer view. The showcase already shipped the same decoder, now through this one path.
+- scene:gltf-box+lazy: the same chunk (7,682 bytes gzip), fetched only by a compressed file; scene:gltf-box itself shrinks by 31 bytes.
diff --git a/docs/gltf.md b/docs/gltf.md
index 2af3dc06..14713598 100644
--- a/docs/gltf.md
+++ b/docs/gltf.md
@@ -143,7 +143,7 @@ POINTS, LINES, LINE_LOOP and LINE_STRIP primitives are skipped with a warning th
| `KHR_lights_punctual` | Point and spot lights (up to the renderer limits of 16 point and 8 spot lights, in candela like the renderer) and the first directional light become `asset.lights`, a partial `environment`: `pointLights`, `spotLights`, and `keyColor` (color times lux), `lightDirection` and `keyIntensity` for the key light. Pass it as `Renderer67`'s `environment` option or a `frame.environment`. A spot's `penumbra` is `(outer - inner) / outer`. A light over the limits, a second directional light and an invalid light are skipped with a warning. The renderer has no calibrated photometric units, so judge the level by eye. |
| `KHR_materials_variants`, `KHR_materials_dispersion`, `KHR_materials_diffuse_roughness`, `EXT_materials_bump`, `EXT_texture_avif` and any other optional extension | Ignored, named in `warnings`. |
| `KHR_draco_mesh_compression` | Needs `options.decoders.draco`. |
-| `EXT_meshopt_compression` | Needs `options.decoders.meshopt`. |
+| `EXT_meshopt_compression` | Decoded by 67js: attribute, triangle and index modes with the NONE, OCTAHEDRAL, QUATERNION and EXPONENTIAL filters. The decoder is a separate chunk that loads only when `extensionsUsed` or `extensionsRequired` lists the extension. The fallback buffer is never read, so it may be absent, zero-filled or an unreachable `uri`, and it does not count against `maxBytes`. A buffer view that fails to decode throws a named error. `options.decoders.meshopt` still replaces the built-in decoder. |
| `KHR_texture_basisu` | Needs `options.decoders.ktx2`. |
| `EXT_texture_webp` | The WebP source is decoded by the browser like PNG and JPEG. When the texture also has a PNG or JPEG `source` and the browser cannot decode WebP, that source is used instead. |
| `KHR_materials_clearcoat`, `_transmission`, `_ior`, `_specular`, `_sheen`, `_volume`, `_anisotropy`, `_iridescence` | Read as factors and rendered as material layers, see `docs/material-maps.md`. The textures `clearcoatTexture`, `clearcoatRoughnessTexture`, `clearcoatNormalTexture`, `anisotropyTexture`, `sheenColorTexture` and `sheenRoughnessTexture` are read too, into `material.layerMaps` (their GLSL loads with `material-layer-shaders`); a renderer draws at most three different ones, and none beside splat layers. The transmission, iridescence and specular textures are not read: their factors are used. `occlusionTexture`, `emissiveTexture` and `metallicRoughnessTexture` may use TEXCOORD_1 (the mesh's `lightUvs`, which a light bake also uses); base color and normal textures must use TEXCOORD_0, and a texture on TEXCOORD_1 cannot carry `KHR_texture_transform`. Their textures are ignored, and an iridescent film takes the thickness maximum. Export writes them back. |
@@ -151,25 +151,24 @@ POINTS, LINES, LINE_LOOP and LINE_STRIP primitives are skipped with a warning th
`KHR_materials_transmission` with a factor above zero sets `material.transmission` to that factor.
It is a hint only: the renderer does not draw transmission yet.
-Without the matching decoder, a file that uses a compression extension fails with `Unsupported glTF extension` and the option name.
+Without the matching decoder, a file that uses Draco or KTX2 fails with `Unsupported glTF extension` and the option name. Meshopt needs no option.
### Decoders
-The decoders are the Three.js loaders, and they stay yours: only an application that passes one imports Three.js. 67js 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)`.
+The Draco and KTX2 decoders are the Three.js loaders, and they stay yours: only an application that passes one imports Three.js. 67js 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)`, and a KTX2 loader needs `load(url, onLoad, onProgress, onError)`.
```js
import { DRACOLoader } from 'three/addons/loaders/DRACOLoader.js';
import { KTX2Loader } from 'three/addons/loaders/KTX2Loader.js';
import { loadGltf, ktx2WorkerConfigFor } from '67js/addons/gltf';
-import { MeshoptDecoder } from 'three/addons/libs/meshopt_decoder.module.js';
const draco = new DRACOLoader().setDecoderPath('/vendor/draco/'); // copy three/examples/jsm/libs/draco/
const ktx2 = new KTX2Loader().setTranscoderPath('/vendor/basis/'); // copy three/examples/jsm/libs/basis/
// Transcode to a GPU-compressed format the renderer's context takes, or to RGBA8 where it takes none.
ktx2.workerConfig = ktx2WorkerConfigFor(renderer.context);
-const asset = await loadGltf('/models/car.glb', { decoders: { draco, ktx2, meshopt: MeshoptDecoder } });
+const asset = await loadGltf('/models/car.glb', { decoders: { draco, ktx2 } });
```
Any subset works. Draco and KTX2 decode in browser workers. Dispose the loaders yourself when done (`draco.dispose()`, `ktx2.dispose()`).
@@ -219,7 +218,7 @@ The tests cover parent transforms, missing normals, UVs, shared geometry, PBR fa
The tests also cover input limits, unsupported features, compressed image dimensions, and oversized fetch cancellation.
`node --test tests/gltf-extensions.test.js` covers texture transform baking, instancing, ignored material extensions and the decoder options.
-The meshopt test decodes a real encoded buffer with the Three.js decoder.
+The meshopt tests decode real encoded buffers (all modes and filters, a fixture encoded in the test) without any option.
The Draco and KTX2 tests use stand-in loaders, because no encoder is installed: they prove the wiring, not the wasm decoders.
`tests/fixtures/textured-triangle.gltf` contains an original triangle and a generated two-pixel-square PNG.
diff --git a/src/gltf-accessors.js b/src/gltf-accessors.js
index 69b6ddcc..df856088 100644
--- a/src/gltf-accessors.js
+++ b/src/gltf-accessors.js
@@ -39,7 +39,7 @@ function copyElements(source, offset, stride, count, elementBytes) {
/**
* 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.
+ * `bufferBytes(index)` returns the bytes of a glTF buffer. `meshoptDecoder` replaces the built-in decoder of compressed views.
*/
export function createAccessorReader(document, bufferBytes, meshoptDecoder) {
const viewCache = new Map();
@@ -54,23 +54,12 @@ export function createAccessorReader(document, bufferBytes, meshoptDecoder) {
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. */
+ /** Decode every meshopt view before any accessor is read, so reading stays synchronous. The decoder loads only for a file that has one. */
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]));
- }
+ if (!views.some(view => view.extensions?.EXT_meshopt_compression)) return;
+ const { decodeMeshoptViews } = await import('./gltf-meshopt.js');
+ for (const [index, bytes] of await decodeMeshoptViews(views, bufferBytes, meshoptDecoder)) viewCache.set(index, bytes);
}
function viewBytes(index) {
diff --git a/src/gltf-meshopt.js b/src/gltf-meshopt.js
new file mode 100644
index 00000000..09386c32
--- /dev/null
+++ b/src/gltf-meshopt.js
@@ -0,0 +1,37 @@
+import { MeshoptDecoder } from 'three/addons/libs/meshopt_decoder.module.js';
+
+// Decodes EXT_meshopt_compression buffer views with the meshoptimizer WebAssembly decoder (MIT, the build that ships with three.js).
+// Only a file that has such a view loads this module, so the decoder costs every other file nothing.
+const MODES = new Set(['ATTRIBUTES', 'TRIANGLES', 'INDICES']);
+const FILTERS = new Set(['NONE', 'OCTAHEDRAL', 'QUATERNION', 'EXPONENTIAL']);
+
+function decodeView(view, bufferBytes, decoder) {
+ const extension = view.extensions.EXT_meshopt_compression;
+ const filter = extension.filter ?? 'NONE';
+ 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.');
+ const decodedLength = extension.count * extension.byteStride;
+ if (!Number.isSafeInteger(decodedLength) || decodedLength !== view.byteLength) {
+ throw new Error('EXT_meshopt_compression count and byteStride do not match the buffer view length.');
+ }
+ if (!MODES.has(extension.mode) || !FILTERS.has(filter)) throw new Error('EXT_meshopt_compression has an unknown mode or filter.');
+ const decoded = new Uint8Array(decodedLength);
+ try {
+ decoder.decodeGltfBuffer(decoded, extension.count, extension.byteStride, source.subarray(offset, offset + extension.byteLength), extension.mode, filter);
+ } catch (error) {
+ throw new Error(`EXT_meshopt_compression could not decode a buffer view (${extension.mode}, ${filter}): ${error.message}`);
+ }
+ return decoded;
+}
+
+/** Returns a Map from buffer view index to its decoded bytes. The fallback buffer is never read. */
+export async function decodeMeshoptViews(bufferViews, bufferBytes, suppliedDecoder) {
+ const decoder = suppliedDecoder ?? MeshoptDecoder;
+ await decoder.ready;
+ const decodedViews = new Map();
+ bufferViews.forEach((view, index) => {
+ if (view.extensions?.EXT_meshopt_compression) decodedViews.set(index, decodeView(view, bufferBytes, decoder));
+ });
+ return decodedViews;
+}
diff --git a/src/gltf.js b/src/gltf.js
index b6c0d827..5eb6325c 100644
--- a/src/gltf.js
+++ b/src/gltf.js
@@ -12,7 +12,7 @@ import { MAX_MORPH_TARGETS, createMorphPose, validateMorphGeometry, validateMorp
export const GLTF_CAPABILITIES = Object.freeze({
formats: ['glb', 'gltf'],
- supported: ['triangle meshes', 'world transforms', 'rigid node animations', 'four-influence skeletal skinning', 'joint node animations', 'relative POSITION/NORMAL morph targets', 'morph weight animations', 'PNG/JPEG/WebP base color textures', 'normal/occlusion/emissive/metallic-roughness textures', 'TEXCOORD_0', 'TEXCOORD_1 for occlusion, emissive and metallic-roughness textures', 'clearcoat, clearcoat roughness, clearcoat normal, anisotropy, sheen color and sheen roughness textures', 'linear RGB vertex colors, with the alpha of RGBA colors ignored and reported in warnings','metallic roughness factors', 'emissive factors', 'alpha mask and blend modes', 'double-sided materials', 'KHR_mesh_quantization', 'KHR_materials_emissive_strength', 'KHR_materials_clearcoat, transmission, volume, ior, specular, sheen, anisotropy and iridescence factors', 'KHR_texture_transform baked into UVs, with a normal map that differs by scale and offset applied in the shader', 'EXT_mesh_gpu_instancing expanded into parts', 'KHR_draco_mesh_compression with options.decoders.draco', 'EXT_meshopt_compression with options.decoders.meshopt', 'KHR_texture_basisu with options.decoders.ktx2', 'EXT_texture_webp, with the PNG or JPEG fallback source when the browser cannot decode WebP', 'KHR_materials_unlit as the unlit material tag, with a base color map only', 'KHR_lights_punctual point and spot lights (up to eight each) and the first directional light, returned in lights as environment options'],
+ supported: ['triangle meshes', 'world transforms', 'rigid node animations', 'four-influence skeletal skinning', 'joint node animations', 'relative POSITION/NORMAL morph targets', 'morph weight animations', 'PNG/JPEG/WebP base color textures', 'normal/occlusion/emissive/metallic-roughness textures', 'TEXCOORD_0', 'TEXCOORD_1 for occlusion, emissive and metallic-roughness textures', 'clearcoat, clearcoat roughness, clearcoat normal, anisotropy, sheen color and sheen roughness textures', 'linear RGB vertex colors, with the alpha of RGBA colors ignored and reported in warnings','metallic roughness factors', 'emissive factors', 'alpha mask and blend modes', 'double-sided materials', 'KHR_mesh_quantization', 'KHR_materials_emissive_strength', 'KHR_materials_clearcoat, transmission, volume, ior, specular, sheen, anisotropy and iridescence factors', 'KHR_texture_transform baked into UVs, with a normal map that differs by scale and offset applied in the shader', 'EXT_mesh_gpu_instancing expanded into parts', 'KHR_draco_mesh_compression with options.decoders.draco', 'EXT_meshopt_compression', 'KHR_texture_basisu with options.decoders.ktx2', 'EXT_texture_webp, with the PNG or JPEG fallback source when the browser cannot decode WebP', 'KHR_materials_unlit as the unlit material tag, with a base color map only', 'KHR_lights_punctual point and spot lights (up to eight each) and the first directional light, returned in lights as environment options'],
// The primitive's own material is drawn; the other variants are not selectable.
ignoredExtensions: ['KHR_materials_variants', 'KHR_materials_dispersion', 'KHR_materials_diffuse_roughness', 'EXT_materials_bump', 'EXT_texture_avif'],
optionalExtensions: 'Any other optional extension is ignored and named in warnings. One listed in extensionsRequired that 67js does not read is refused.',
@@ -52,8 +52,8 @@ const DEFAULT_MAX_INSTANCES = 4096;
// KHR_xmp_json_ld and its earlier name KHR_xmp only carry metadata (authors, licences) and change nothing drawn: the
// Khronos sample assets list them, and a file must not be refused for them.
const METADATA_EXTENSIONS = ['KHR_xmp_json_ld', 'KHR_xmp'];
-const ALLOWED_EXTENSIONS = new Set(['KHR_mesh_quantization', 'KHR_materials_emissive_strength', 'KHR_texture_transform', 'EXT_mesh_gpu_instancing', 'EXT_texture_webp', 'KHR_materials_unlit', 'KHR_lights_punctual', ...METADATA_EXTENSIONS, ...GLTF_LAYER_EXTENSIONS]);
-const DECODER_BY_EXTENSION = { KHR_draco_mesh_compression: 'draco', EXT_meshopt_compression: 'meshopt', KHR_texture_basisu: 'ktx2' };
+const ALLOWED_EXTENSIONS = new Set(['KHR_mesh_quantization', 'KHR_materials_emissive_strength', 'KHR_texture_transform', 'EXT_mesh_gpu_instancing', 'EXT_meshopt_compression', 'EXT_texture_webp', 'KHR_materials_unlit', 'KHR_lights_punctual', ...METADATA_EXTENSIONS, ...GLTF_LAYER_EXTENSIONS]);
+const DECODER_BY_EXTENSION = { KHR_draco_mesh_compression: 'draco', KHR_texture_basisu: 'ktx2' };
const IDENTITY_UV_TRANSFORM = Object.freeze({ offset: [0, 0], rotation: 0, scale: [1, 1] });
const IDENTITY_UV_TRANSFORM_KEY = JSON.stringify([IDENTITY_UV_TRANSFORM.offset, IDENTITY_UV_TRANSFORM.rotation, IDENTITY_UV_TRANSFORM.scale]);
const MATERIAL_TEXTURES = [
@@ -331,7 +331,8 @@ function validateDocument(document, limits, allowedExtensions) {
let declaredBytes = 0;
for (const buffer of document.buffers ?? []) {
if (!Number.isSafeInteger(buffer.byteLength) || buffer.byteLength < 0) throw new Error('Invalid glTF buffer length.');
- declaredBytes += buffer.byteLength;
+ // A meshopt fallback buffer holds the uncompressed copy of data that is decoded from the compressed buffer; it is never read.
+ if (!buffer.extensions?.EXT_meshopt_compression?.fallback) declaredBytes += buffer.byteLength;
}
if (declaredBytes > limits.maxBytes) throw new Error('glTF buffers exceed maxBytes.');
let vertices = 0;
@@ -669,7 +670,7 @@ async function boundedFetch(url, maxBytes, signal) {
async function prepareResources(document, data, dataBytes, options, limits) {
const resourceBytes = new Map();
- const definitions = [...(document.buffers ?? []), ...(document.images ?? [])];
+ const definitions = [...(document.buffers ?? []).filter(buffer => !buffer.extensions?.EXT_meshopt_compression?.fallback), ...(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;
@@ -979,7 +980,7 @@ function convertMaterial(source, limits, maps, definition = {}) {
return material;
}
-/** Parse a bounded glTF 2.0 asset into Renderer67 parts. Draco, meshopt and KTX2 decoders come from options.decoders. */
+/** Parse a bounded glTF 2.0 asset into Renderer67 parts. Draco and KTX2 decoders come from options.decoders; meshopt decodes in a chunk that loads on demand, unless options.decoders.meshopt replaces it. */
export async function parseGltf(data, options = {}) {
const limits = limitsFor(options);
const document = documentFrom(data, limits.maxBytes);
diff --git a/src/showcase.js b/src/showcase.js
index 1f9eb246..1f5107a8 100644
--- a/src/showcase.js
+++ b/src/showcase.js
@@ -217,12 +217,6 @@ async function readDescription(id) {
return response.json();
}
-// Showcase GLBs may use EXT_meshopt_compression; the decoder is a small chunk fetched beside the model download.
-async function loadDecoders() {
- const { MeshoptDecoder } = await import('three/addons/libs/meshopt_decoder.module.js');
- return { meshopt: MeshoptDecoder };
-}
-
function showCredits(credits = []) {
creditList.replaceChildren(...credits.map(credit => {
const item = document.createElement('li');
@@ -256,7 +250,7 @@ async function finishWorld(world) {
const files = [{ parts: asset.parts, ranks: world.ranks }];
for (const [index, model] of remainingModels.entries()) {
const baseUrl = new URL('.', new URL(description.glbRest[index], location.href)).href;
- const remaining = await loadGltf(model, { baseUrl, decoders: world.decoders, ...(description.gltfOptions ?? {}) });
+ const remaining = await loadGltf(model, { baseUrl, ...(description.gltfOptions ?? {}) });
files.push({ parts: remaining.parts, ranks: await readPartRanks(model) });
}
if (!isCurrent()) return;
@@ -311,10 +305,9 @@ async function selectScene(id) {
meter.register(url);
readByteLength(url, abort.signal).then(total => meter.setTotal(url, total), () => {});
}
- const [model, map, decoders] = await Promise.all([
+ const [model, map] = await Promise.all([
download(glbUrl.href, 'model/gltf-binary'),
loadSky(previewUrl ?? skyUrl),
- loadDecoders(),
]);
// The rest starts the moment the first part is in, so the link stays busy while the page decodes and draws it.
const remainingDownloads = Promise.all([
@@ -322,7 +315,7 @@ async function selectScene(id) {
previewUrl ? loadSky(skyUrl) : null,
]);
remainingDownloads.catch(() => {});
- const asset = await loadGltf(model, { baseUrl: new URL('.', glbUrl).href, decoders, ...(description.gltfOptions ?? {}) });
+ const asset = await loadGltf(model, { baseUrl: new URL('.', glbUrl).href, ...(description.gltfOptions ?? {}) });
if (request !== loadingRequest) return;
renderer?.dispose();
const rendererOptions = description.renderer ?? {};
@@ -356,7 +349,7 @@ async function selectScene(id) {
}
progressLabel = `Loading the rest of ${SCENE_LABELS[id]}`;
showProgress(progressLabel, meter);
- finishWorld({ id, request, description, asset, ranks: await readPartRanks(model), detachReflection, remainingDownloads, decoders, abort });
+ finishWorld({ id, request, description, asset, ranks: await readPartRanks(model), detachReflection, remainingDownloads, abort });
} catch (error) {
if (request !== loadingRequest) return;
markPressedTab(currentId);
diff --git a/tests/gltf-extensions.test.js b/tests/gltf-extensions.test.js
index d9a157d0..c4ed9f58 100644
--- a/tests/gltf-extensions.test.js
+++ b/tests/gltf-extensions.test.js
@@ -276,7 +276,7 @@ test('required material extensions, bad layer values and missing decoders are re
await assert.rejects(parseGltf(badTransmission), /transmission must be between 0 and 1.*Use a number inside that range/);
const badIor = triangleDocument({ edit: document => { document.materials[0].extensions = { KHR_materials_ior: { ior: 0.5 } }; } });
await assert.rejects(parseGltf(badIor), /ior must be between 1 and 2.5/);
- for (const [extension, decoder] of [['KHR_draco_mesh_compression', 'draco'], ['EXT_meshopt_compression', 'meshopt'], ['KHR_texture_basisu', 'ktx2']]) {
+ for (const [extension, decoder] of [['KHR_draco_mesh_compression', 'draco'], ['KHR_texture_basisu', 'ktx2']]) {
const data = triangleDocument({ edit: document => { document.extensionsRequired = [extension]; } });
await assert.rejects(parseGltf(data), new RegExp(`options\\.decoders\\.${decoder}`));
}
diff --git a/tests/gltf-meshopt.test.js b/tests/gltf-meshopt.test.js
new file mode 100644
index 00000000..1fb8ec0b
--- /dev/null
+++ b/tests/gltf-meshopt.test.js
@@ -0,0 +1,239 @@
+import assert from 'node:assert/strict';
+import { readFile } from 'node:fs/promises';
+import test from 'node:test';
+import { MeshoptEncoder } from 'meshoptimizer';
+import { createAccessorReader } from '../src/gltf-accessors.js';
+import { parseGltf } from '../src/gltf.js';
+
+const MESHOPT = 'EXT_meshopt_compression';
+const FLOAT = 5126;
+const BYTE = 5120;
+const SHORT = 5122;
+const UNSIGNED_SHORT = 5123;
+
+await MeshoptEncoder.ready;
+
+function padToFour(length) {
+ return Math.ceil(length / 4) * 4;
+}
+
+function bytesOf(typedArray) {
+ return new Uint8Array(typedArray.buffer, typedArray.byteOffset, typedArray.byteLength);
+}
+
+function buildGlb(document, binary) {
+ const json = new TextEncoder().encode(JSON.stringify(document));
+ const jsonLength = padToFour(json.length);
+ const binaryLength = padToFour(binary.length);
+ const glb = new Uint8Array(28 + jsonLength + binaryLength);
+ const header = new DataView(glb.buffer);
+ header.setUint32(0, 0x46546c67, true);
+ header.setUint32(4, 2, true);
+ header.setUint32(8, glb.length, true);
+ header.setUint32(12, jsonLength, true);
+ header.setUint32(16, 0x4e4f534a, true);
+ glb.fill(32, 20, 20 + jsonLength);
+ glb.set(json, 20);
+ header.setUint32(20 + jsonLength, binaryLength, true);
+ header.setUint32(24 + jsonLength, 0x004e4942, true);
+ glb.set(binary, 28 + jsonLength);
+ return glb.buffer;
+}
+
+function joinChunks(chunks) {
+ const offsets = [];
+ let length = 0;
+ for (const chunk of chunks) {
+ offsets.push(length);
+ length += padToFour(chunk.length);
+ }
+ const binary = new Uint8Array(length);
+ chunks.forEach((chunk, index) => binary.set(chunk, offsets[index]));
+ return { binary, offsets };
+}
+
+/** A latitude and longitude sphere with unit normals. */
+function sphere(rings = 12, segments = 16) {
+ const positions = [];
+ const normals = [];
+ for (let ring = 0; ring <= rings; ring++) {
+ const polar = (ring / rings) * Math.PI;
+ for (let segment = 0; segment <= segments; segment++) {
+ const azimuth = (segment / segments) * Math.PI * 2;
+ const normal = [Math.sin(polar) * Math.cos(azimuth), Math.cos(polar), Math.sin(polar) * Math.sin(azimuth)];
+ normals.push(...normal);
+ positions.push(...normal.map(value => value * 1.5));
+ }
+ }
+ const indices = [];
+ for (let ring = 0; ring < rings; ring++) {
+ for (let segment = 0; segment < segments; segment++) {
+ const first = ring * (segments + 1) + segment;
+ const second = first + segments + 1;
+ indices.push(first, second, first + 1, second, second + 1, first + 1);
+ }
+ }
+ return { positions: new Float32Array(positions), normals: new Float32Array(normals), indices: new Uint16Array(indices) };
+}
+
+/** Octahedral-encodes unit normals into four signed bytes each, through the encoder's filter. */
+function octahedralNormals(normals) {
+ const count = normals.length / 3;
+ const withWidth = new Float32Array(count * 4);
+ for (let index = 0; index < count; index++) withWidth.set(normals.subarray(index * 3, index * 3 + 3), index * 4);
+ return MeshoptEncoder.encodeFilterOct(withWidth, count, 4, 8);
+}
+
+function compressedView({ buffer = 1, data, count, byteStride, mode, filter, target }) {
+ const encoded = MeshoptEncoder.encodeGltfBuffer(data, count, byteStride, mode);
+ return { encoded, view: (offset) => ({ buffer, byteLength: count * byteStride, byteStride: mode === 'ATTRIBUTES' ? byteStride : undefined, target, extensions: { [MESHOPT]: { buffer: 0, byteOffset: offset, byteLength: encoded.length, byteStride, mode, count, ...(filter ? { filter } : {}) } } }) };
+}
+
+/** The same sphere, either as plain buffer views or as one meshopt-compressed GLB (positions, octahedral normals, triangle indices). */
+function sphereGlb({ compressed, fallback = 'zero' }) {
+ const mesh = sphere();
+ const vertexCount = mesh.positions.length / 3;
+ const normalBytes = compressed ? octahedralNormals(mesh.normals) : bytesOf(mesh.normals);
+ const base = { asset: { version: '2.0' }, scenes: [{ nodes: [0] }], nodes: [{ mesh: 0 }], meshes: [{ primitives: [{ attributes: { POSITION: 0, NORMAL: 1 }, indices: 2 }] }] };
+ const normalAccessor = compressed
+ ? { bufferView: 1, componentType: BYTE, normalized: true, count: vertexCount, type: 'VEC3' }
+ : { bufferView: 1, componentType: FLOAT, count: vertexCount, type: 'VEC3' };
+ const accessors = [
+ { bufferView: 0, componentType: FLOAT, count: vertexCount, type: 'VEC3', min: [-1.5, -1.5, -1.5], max: [1.5, 1.5, 1.5] },
+ normalAccessor,
+ { bufferView: 2, componentType: UNSIGNED_SHORT, count: mesh.indices.length, type: 'SCALAR' },
+ ];
+ if (!compressed) {
+ const { binary, offsets } = joinChunks([bytesOf(mesh.positions), normalBytes, bytesOf(mesh.indices)]);
+ const bufferViews = [
+ { buffer: 0, byteOffset: offsets[0], byteLength: mesh.positions.byteLength, byteStride: 12 },
+ { buffer: 0, byteOffset: offsets[1], byteLength: normalBytes.length, byteStride: 12 },
+ { buffer: 0, byteOffset: offsets[2], byteLength: mesh.indices.byteLength },
+ ];
+ return buildGlb({ ...base, accessors, bufferViews, buffers: [{ byteLength: binary.length }] }, binary);
+ }
+ const position = compressedView({ data: bytesOf(mesh.positions), count: vertexCount, byteStride: 12, mode: 'ATTRIBUTES' });
+ const normal = compressedView({ data: normalBytes, count: vertexCount, byteStride: 4, mode: 'ATTRIBUTES', filter: 'OCTAHEDRAL' });
+ const index = compressedView({ data: bytesOf(mesh.indices), count: mesh.indices.length, byteStride: 2, mode: 'TRIANGLES' });
+ const { binary, offsets } = joinChunks([position.encoded, normal.encoded, index.encoded]);
+ const fallbackBuffer = { byteLength: 1 << 20, extensions: { [MESHOPT]: { fallback: true } } };
+ if (fallback === 'unreachable') fallbackBuffer.uri = 'fallback.bin';
+ const document = {
+ ...base,
+ accessors,
+ bufferViews: [position.view(offsets[0]), normal.view(offsets[1]), index.view(offsets[2])],
+ buffers: [{ byteLength: binary.length }, fallbackBuffer],
+ extensionsUsed: [MESHOPT, 'KHR_mesh_quantization'],
+ extensionsRequired: [MESHOPT, 'KHR_mesh_quantization'],
+ };
+ return buildGlb(document, binary);
+}
+
+/** The triangle codec may rotate the corners of a triangle, so triangles compare by their corners starting from the lowest index. */
+function triangleKeys(indices) {
+ const keys = [];
+ for (let start = 0; start < indices.length; start += 3) {
+ const corners = [indices[start], indices[start + 1], indices[start + 2]];
+ const lowest = corners.indexOf(Math.min(...corners));
+ keys.push([0, 1, 2].map(offset => corners[(lowest + offset) % 3]).join(','));
+ }
+ return keys.sort();
+}
+
+test('a meshopt-compressed GLB decodes without any decoder option and matches the uncompressed geometry', async () => {
+ const plain = await parseGltf(sphereGlb({ compressed: false }));
+ const compressed = await parseGltf(sphereGlb({ compressed: true }));
+ const expected = plain.parts[0].geometry;
+ const actual = compressed.parts[0].geometry;
+ assert.deepEqual(Array.from(actual.positions), Array.from(expected.positions));
+ assert.deepEqual(triangleKeys(actual.indices), triangleKeys(expected.indices));
+ assert.equal(actual.normals.length, expected.normals.length);
+ for (let index = 0; index < expected.normals.length; index += 3) {
+ const alignment = actual.normals[index] * expected.normals[index] + actual.normals[index + 1] * expected.normals[index + 1] + actual.normals[index + 2] * expected.normals[index + 2];
+ assert.ok(alignment > 0.995, `normal ${index / 3} is within about 5 degrees of the source`);
+ }
+});
+
+test('a fallback buffer that is absent, zero-filled in the file or an unreachable uri is never read', async () => {
+ for (const fallback of ['zero', 'unreachable']) {
+ const asset = await parseGltf(sphereGlb({ compressed: true, fallback }));
+ assert.ok(asset.parts[0].geometry.positions.length > 0, fallback);
+ }
+});
+
+test('a compressed buffer view that cannot be decoded names the extension', async () => {
+ const glb = new Uint8Array(sphereGlb({ compressed: true }));
+ const binaryStart = 28 + new DataView(glb.buffer).getUint32(12, true);
+ glb.fill(0xff, binaryStart, binaryStart + 64);
+ await assert.rejects(parseGltf(glb.buffer), /EXT_meshopt_compression could not decode a buffer view/);
+});
+
+test('a caller supplied decoder still takes the place of the built-in one', async () => {
+ let calls = 0;
+ const supplied = {
+ ready: Promise.resolve(),
+ decodeGltfBuffer() {
+ calls++;
+ throw new Error('stand-in');
+ },
+ };
+ await assert.rejects(parseGltf(sphereGlb({ compressed: true }), { decoders: { meshopt: supplied } }), /stand-in/);
+ assert.equal(calls, 1);
+});
+
+/** Reads one accessor through a compressed view of the given mode and filter. */
+async function readThroughMeshopt({ data, count, byteStride, mode, filter, accessor }) {
+ const { MeshoptDecoder } = await import('three/addons/libs/meshopt_decoder.module.js');
+ const { encoded, view } = compressedView({ data, count, byteStride, mode, filter });
+ const document = { accessors: [{ bufferView: 0, count, ...accessor }], bufferViews: [view(0)], buffers: [{ byteLength: encoded.length }, { byteLength: count * byteStride }] };
+ const reader = createAccessorReader(document, index => (index === 0 ? encoded : null), MeshoptDecoder);
+ await reader.prepare();
+ return reader.readAccessor(0).array;
+}
+
+test('the OCTAHEDRAL filter returns unit normals', async () => {
+ const normals = sphere(6, 8).normals;
+ const count = normals.length / 3;
+ const decoded = await readThroughMeshopt({ data: octahedralNormals(normals), count, byteStride: 4, mode: 'ATTRIBUTES', filter: 'OCTAHEDRAL', accessor: { componentType: BYTE, normalized: true, type: 'VEC3' } });
+ assert.equal(decoded.length, count * 3);
+ for (let index = 0; index < count; index++) {
+ const x = decoded[index * 3] / 127;
+ const y = decoded[index * 3 + 1] / 127;
+ const z = decoded[index * 3 + 2] / 127;
+ const length = Math.hypot(x, y, z);
+ const alignment = (x * normals[index * 3] + y * normals[index * 3 + 1] + z * normals[index * 3 + 2]) / length;
+ assert.ok(alignment > 0.995, `normal ${index}`);
+ }
+});
+
+test('the QUATERNION filter returns a rotation equal to the source', async () => {
+ const half = Math.PI / 5;
+ const source = new Float32Array([Math.sin(half) * 0.6, Math.sin(half) * 0.8, 0, Math.cos(half), 0, 0, 0, 1]);
+ const filtered = MeshoptEncoder.encodeFilterQuat(source, 2, 8, 16);
+ const decoded = await readThroughMeshopt({ data: filtered, count: 2, byteStride: 8, mode: 'ATTRIBUTES', filter: 'QUATERNION', accessor: { componentType: SHORT, normalized: true, type: 'VEC4' } });
+ for (let element = 0; element < 2; element++) {
+ let alignment = 0;
+ for (let lane = 0; lane < 4; lane++) alignment += (decoded[element * 4 + lane] / 32767) * source[element * 4 + lane];
+ assert.ok(Math.abs(alignment) > 0.9999, `quaternion ${element}`);
+ }
+});
+
+test('the EXPONENTIAL filter returns floats close to the source', async () => {
+ const source = new Float32Array([0.5, -12.25, 300.125, 1e-3, 7, -0.75]);
+ const filtered = MeshoptEncoder.encodeFilterExp(source, 2, 12, 16);
+ const decoded = await readThroughMeshopt({ data: filtered, count: 2, byteStride: 12, mode: 'ATTRIBUTES', filter: 'EXPONENTIAL', accessor: { componentType: FLOAT, type: 'VEC3' } });
+ source.forEach((value, index) => assert.ok(Math.abs(decoded[index] - value) <= Math.abs(value) * 1e-3 + 1e-3, `value ${index}`));
+});
+
+test('the INDICES mode returns the same index sequence', async () => {
+ const indices = Uint16Array.from({ length: 300 }, (_, index) => (index * 7) % 91);
+ const decoded = await readThroughMeshopt({ data: bytesOf(indices), count: indices.length, byteStride: 2, mode: 'INDICES', accessor: { componentType: UNSIGNED_SHORT, type: 'SCALAR' } });
+ assert.deepEqual(Array.from(decoded), Array.from(indices));
+});
+
+test('the public showcase and sample GLBs load without a decoder option', async () => {
+ globalThis.createImageBitmap ??= async () => ({ width: 4, height: 4, close() {} });
+ const bytes = await readFile(new URL('../public/wall-e.glb', import.meta.url));
+ const asset = await parseGltf(bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength), { maxVertices: 500000 });
+ assert.ok(asset.parts.length > 0);
+});
diff --git a/tests/showcase-port-weight.test.js b/tests/showcase-port-weight.test.js
index 6748f405..2b0145ef 100644
--- a/tests/showcase-port-weight.test.js
+++ b/tests/showcase-port-weight.test.js
@@ -1,6 +1,7 @@
import assert from 'node:assert/strict';
import { readFile } from 'node:fs/promises';
import test from 'node:test';
+import { parseGltf } from '../src/gltf.js';
import { parseRadianceHdr } from '../src/hdri.js';
const SHOWCASE_SOURCE = new URL('../src/showcase.js', import.meta.url);
@@ -9,6 +10,8 @@ const WORLDS = ['port', 'airport', 'datacenter'];
// The first part is what a visitor waits for: at 5 Mbps every megabyte is about 1.7 s, and the first frame is due within 5 s.
const FIRST_PART_BYTE_BUDGET = 3.1 * MEGABYTE;
const REST_PART_BYTE_BUDGET = 16 * MEGABYTE;
+// Node has no image decoder, so the test stubs createImageBitmap and only the geometry is real.
+const SHOWCASE_LIMITS = { maxBytes: 64 * MEGABYTE, maxVertices: 4_000_000, maxParts: 20_000, maxTexturePixels: 512 * MEGABYTE, maxTextureImagePixels: 100_000_000 };
function readGltfJson(buffer) {
const jsonLength = buffer.readUInt32LE(12);
@@ -55,12 +58,23 @@ for (const world of WORLDS) {
});
}
-test('the showcase page supplies the meshopt decoder to the glTF loader', async () => {
+test('the showcase page leaves meshopt decoding to the glTF loader', async () => {
const source = await readFile(SHOWCASE_SOURCE, 'utf8');
- assert.match(source, /meshopt_decoder\.module\.js/);
- assert.match(source, /decoders/);
+ assert.doesNotMatch(source, /meshopt_decoder/);
+ assert.doesNotMatch(source, /decoders/);
});
+for (const world of WORLDS) {
+ test(`the ${world} showcase files load through loadGltf without a decoder option`, async () => {
+ const { first, rest } = await readWorld(world);
+ globalThis.createImageBitmap ??= async () => ({ width: 4, height: 4, close() {} });
+ for (const buffer of [first, rest]) {
+ const asset = await parseGltf(buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength), SHOWCASE_LIMITS);
+ assert.ok(asset.parts.length > 0);
+ }
+ });
+}
+
test('the showcase page draws the first part before it streams the rest', async () => {
const source = await readFile(SHOWCASE_SOURCE, 'utf8');
assert.match(source, /glbRest/);