Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Export textures, skins, joints and clips to GLB

Nguyen Xuan Anbe7aea756ebf
diff --git a/src/export-box-uv.js b/src/export-box-uv.js
new file mode 100644
index 00000000..070caebb
--- /dev/null
+++ b/src/export-box-uv.js
@@ -0,0 +1,81 @@
+// Pattern materials are box projected in the shader, which glTF cannot express. This writes the same projection as
+// TEXCOORD_0: every triangle takes the object axis its normal is closest to, as the shader's blend weights do on a
+// face, and vertices are split only where neighbouring triangles pick different axes.
+
+function swapAxes(values, boxMapAxis) {
+ if (boxMapAxis === 0) return [values[1], values[0], values[2]];
+ if (boxMapAxis === 2) return [values[0], values[2], values[1]];
+ return values;
+}
+
+function dominantAxis(positions, indices, triangle, boxMapAxis) {
+ const [first, second, third] = [0, 1, 2].map(corner => indices[triangle * 3 + corner] * 3);
+ const edgeA = [0, 1, 2].map(axis => positions[second + axis] - positions[first + axis]);
+ const edgeB = [0, 1, 2].map(axis => positions[third + axis] - positions[first + axis]);
+ const normal = [
+ edgeA[1] * edgeB[2] - edgeA[2] * edgeB[1],
+ edgeA[2] * edgeB[0] - edgeA[0] * edgeB[2],
+ edgeA[0] * edgeB[1] - edgeA[1] * edgeB[0],
+ ];
+ const swapped = swapAxes(normal, boxMapAxis).map(Math.abs);
+ return swapped[0] >= swapped[1] && swapped[0] >= swapped[2] ? 0 : swapped[1] >= swapped[2] ? 1 : 2;
+}
+
+function projectedCoordinates(position, scale, boxMapScale, boxMapAxis, axis) {
+ const [x, y, z] = swapAxes(position.map((value, component) => value * scale[component] * boxMapScale), boxMapAxis);
+ if (axis === 0) return [z, y];
+ if (axis === 1) return [x, z];
+ return [x, y];
+}
+
+function remapped(source, perVertex, sourceOf) {
+ const target = new source.constructor(sourceOf.length * perVertex);
+ sourceOf.forEach((sourceVertex, vertex) => {
+ for (let component = 0; component < perVertex; component++) {
+ target[vertex * perVertex + component] = source[sourceVertex * perVertex + component];
+ }
+ });
+ return target;
+}
+
+/** `scale` is the part matrix's column lengths: the shader projects scaled object positions. */
+export function boxProjectedGeometry(geometry, scale, boxMapScale, boxMapAxis) {
+ const { positions, indices } = geometry;
+ const triangleCount = indices.length / 3;
+ const newIndexByKey = new Map();
+ const sourceOf = [];
+ const newIndices = new Uint32Array(indices.length);
+ const axisByNewVertex = [];
+ for (let triangle = 0; triangle < triangleCount; triangle++) {
+ const axis = dominantAxis(positions, indices, triangle, boxMapAxis);
+ for (let corner = 0; corner < 3; corner++) {
+ const sourceVertex = indices[triangle * 3 + corner];
+ const key = sourceVertex * 3 + axis;
+ if (!newIndexByKey.has(key)) {
+ newIndexByKey.set(key, sourceOf.length);
+ sourceOf.push(sourceVertex);
+ axisByNewVertex.push(axis);
+ }
+ newIndices[triangle * 3 + corner] = newIndexByKey.get(key);
+ }
+ }
+ const projected = { ...geometry, indices: newIndices };
+ projected.positions = remapped(positions, 3, sourceOf);
+ projected.normals = remapped(geometry.normals, 3, sourceOf);
+ for (const [field, perVertex] of [['colors', 3], ['skinIndices', 4], ['skinWeights', 4]]) {
+ if (geometry[field]) projected[field] = remapped(geometry[field], perVertex, sourceOf);
+ }
+ if (geometry.morphTargets) {
+ projected.morphTargets = geometry.morphTargets.map(target => ({
+ ...target,
+ ...(target.positions ? { positions: remapped(target.positions, 3, sourceOf) } : {}),
+ ...(target.normals ? { normals: remapped(target.normals, 3, sourceOf) } : {}),
+ }));
+ }
+ projected.uvs = new Float32Array(sourceOf.length * 2);
+ sourceOf.forEach((sourceVertex, vertex) => {
+ const position = [positions[sourceVertex * 3], positions[sourceVertex * 3 + 1], positions[sourceVertex * 3 + 2]];
+ projected.uvs.set(projectedCoordinates(position, scale, boxMapScale, boxMapAxis, axisByNewVertex[vertex]), vertex * 2);
+ });
+ return projected;
+}
diff --git a/src/export-png.js b/src/export-png.js
new file mode 100644
index 00000000..576cbd67
--- /dev/null
+++ b/src/export-png.js
@@ -0,0 +1,105 @@
+const PNG_SIGNATURE = [137, 80, 78, 71, 13, 10, 26, 10];
+const MAXIMUM_STORED_BLOCK = 65535;
+const CRC_TABLE = createCrcTable();
+
+function createCrcTable() {
+ const table = new Uint32Array(256);
+ for (let byte = 0; byte < 256; byte++) {
+ let value = byte;
+ for (let bit = 0; bit < 8; bit++) value = value & 1 ? 0xedb88320 ^ value >>> 1 : value >>> 1;
+ table[byte] = value >>> 0;
+ }
+ return table;
+}
+
+function crc32(bytes) {
+ let crc = 0xffffffff;
+ for (const byte of bytes) crc = CRC_TABLE[(crc ^ byte) & 0xff] ^ crc >>> 8;
+ return (crc ^ 0xffffffff) >>> 0;
+}
+
+function adler32(bytes) {
+ let low = 1;
+ let high = 0;
+ for (let index = 0; index < bytes.length; index++) {
+ low = (low + bytes[index]) % 65521;
+ high = (high + low) % 65521;
+ }
+ return (high << 16 | low) >>> 0;
+}
+
+/** zlib stream made of stored blocks: no compression, so encoding stays synchronous and needs no platform API. */
+function storedZlib(raw) {
+ const blockCount = Math.max(1, Math.ceil(raw.length / MAXIMUM_STORED_BLOCK));
+ const output = new Uint8Array(2 + raw.length + blockCount * 5 + 4);
+ const view = new DataView(output.buffer);
+ output[0] = 0x78;
+ output[1] = 0x01;
+ let writeOffset = 2;
+ for (let block = 0; block < blockCount; block++) {
+ const start = block * MAXIMUM_STORED_BLOCK;
+ const length = Math.min(MAXIMUM_STORED_BLOCK, raw.length - start);
+ output[writeOffset] = block === blockCount - 1 ? 1 : 0;
+ view.setUint16(writeOffset + 1, length, true);
+ view.setUint16(writeOffset + 3, ~length & 0xffff, true);
+ output.set(raw.subarray(start, start + length), writeOffset + 5);
+ writeOffset += 5 + length;
+ }
+ view.setUint32(writeOffset, adler32(raw));
+ return output;
+}
+
+function chunk(type, data) {
+ const output = new Uint8Array(12 + data.length);
+ const view = new DataView(output.buffer);
+ view.setUint32(0, data.length);
+ for (let index = 0; index < 4; index++) output[4 + index] = type.charCodeAt(index);
+ output.set(data, 8);
+ view.setUint32(8 + data.length, crc32(output.subarray(4, 8 + data.length)));
+ return output;
+}
+
+function hasTransparentPixel(pixels) {
+ for (let offset = 3; offset < pixels.length; offset += 4) {
+ if (pixels[offset] !== 255) return true;
+ }
+ return false;
+}
+
+/**
+ * Encode RGBA8 pixels as a PNG. Rows are reversed when `flipRows` is true, for textures uploaded with flipY.
+ * Pixels with full alpha everywhere are written as RGB, a quarter smaller.
+ */
+export function encodePng(pixels, width, height, { flipRows = false } = {}) {
+ const withAlpha = hasTransparentPixel(pixels);
+ const channels = withAlpha ? 4 : 3;
+ const rowBytes = width * channels;
+ const raw = new Uint8Array((rowBytes + 1) * height);
+ for (let row = 0; row < height; row++) {
+ const sourceRow = flipRows ? height - 1 - row : row;
+ const target = row * (rowBytes + 1);
+ raw[target] = 0;
+ for (let column = 0; column < width; column++) {
+ const source = (sourceRow * width + column) * 4;
+ const destination = target + 1 + column * channels;
+ raw[destination] = pixels[source];
+ raw[destination + 1] = pixels[source + 1];
+ raw[destination + 2] = pixels[source + 2];
+ if (withAlpha) raw[destination + 3] = pixels[source + 3];
+ }
+ }
+ const header = new Uint8Array(13);
+ const headerView = new DataView(header.buffer);
+ headerView.setUint32(0, width);
+ headerView.setUint32(4, height);
+ header[8] = 8;
+ header[9] = withAlpha ? 6 : 2;
+ const parts = [Uint8Array.from(PNG_SIGNATURE), chunk('IHDR', header), chunk('IDAT', storedZlib(raw)), chunk('IEND', new Uint8Array(0))];
+ const png = new Uint8Array(parts.reduce((total, part) => total + part.length, 0));
+ let offset = 0;
+ for (const part of parts) {
+ png.set(part, offset);
+ offset += part.length;
+ }
+ return png;
+}
diff --git a/src/export-skeleton.js b/src/export-skeleton.js
new file mode 100644
index 00000000..511f7cc8
--- /dev/null
+++ b/src/export-skeleton.js
@@ -0,0 +1,187 @@
+import { mat4, quat, vec3 } from 'gl-matrix';
+
+const GLTF_PATHS = { translation: 'translation', rotation: 'rotation', scale: 'scale' };
+const COMPONENTS_BY_PATH = { translation: 3, rotation: 4, scale: 3 };
+const IDENTITY_ROTATION = [0, 0, 0, 1];
+
+function transformFields(translation, rotation, scale) {
+ const fields = {};
+ if (translation.some(value => value !== 0)) fields.translation = Array.from(translation);
+ if (rotation.some((value, index) => value !== IDENTITY_ROTATION[index])) fields.rotation = Array.from(rotation);
+ if (scale.some(value => value !== 1)) fields.scale = Array.from(scale);
+ return fields;
+}
+
+/** Split an affine matrix into glTF translation, rotation and scale fields. */
+export function decomposeMatrix(matrix) {
+ const translation = mat4.getTranslation(vec3.create(), matrix);
+ const scale = mat4.getScaling(vec3.create(), matrix);
+ const rotation = mat4.getRotation(quat.create(), matrix);
+ return transformFields(translation, rotation, scale);
+}
+
+function composeFields(record) {
+ return mat4.fromRotationTranslationScale(mat4.create(), record.rotation ?? IDENTITY_ROTATION, record.translation ?? [0, 0, 0], record.scale ?? [1, 1, 1]);
+}
+
+function worldMatrixOf(index, nodes, cache) {
+ if (cache.has(index)) return cache.get(index);
+ const node = nodes[index];
+ const local = composeFields(node);
+ const world = node.parent >= 0 ? mat4.multiply(mat4.create(), worldMatrixOf(node.parent, nodes, cache), local) : local;
+ cache.set(index, world);
+ return world;
+}
+
+/** Hierarchy records from `options.nodes` (the `nodes` of a parsed asset, or the same fields): name, id, parent id. */
+function nodesFromRecords(records) {
+ const indexById = new Map(records.map((record, index) => [record.id ?? record.name, index]));
+ return records.map(record => {
+ if (typeof record.name !== 'string' || !record.name) throw new TypeError('GLB nodes need a name.');
+ const parent = record.parent === null || record.parent === undefined ? -1 : indexById.get(record.parent);
+ if (parent === undefined) throw new RangeError(`GLB node ${record.name} names a parent that is not in the node list.`);
+ return { name: record.name, parent, translation: record.translation, rotation: record.rotation, scale: record.scale, meshIds: record.meshIds ?? [] };
+ });
+}
+
+function jointWorld(skin, joint) {
+ return skin.jointWorldMatrices.subarray(joint * 16, joint * 16 + 16);
+}
+
+function requireSkinFields(skin, partName) {
+ const jointCount = skin.joints?.length;
+ if (!Array.isArray(skin.joints) || skin.inverseBindMatrices?.length !== jointCount * 16 || skin.jointWorldMatrices?.length !== jointCount * 16) {
+ throw new TypeError(`GLB part ${partName} has a skin without joints, inverseBindMatrices and jointWorldMatrices. Use the skin that parseGltf returned, or give each joint a name and parent.`);
+ }
+}
+
+/** Joint nodes derived from the skin's current joint world matrices, for skins built without a node list. */
+function appendDerivedJoints(nodes, skin) {
+ const indexByJoint = skin.joints.map(joint => {
+ const existing = nodes.findIndex(node => node.name === joint.name);
+ return existing >= 0 ? existing : -1;
+ });
+ skin.joints.forEach((joint, jointIndex) => {
+ if (indexByJoint[jointIndex] >= 0) return;
+ const parentJoint = joint.parent ?? -1;
+ const world = jointWorld(skin, jointIndex);
+ const parentWorld = parentJoint >= 0 ? jointWorld(skin, parentJoint) : null;
+ const local = parentWorld ? mat4.multiply(mat4.create(), mat4.invert(mat4.create(), parentWorld), world) : world;
+ const fields = decomposeMatrix(local);
+ indexByJoint[jointIndex] = nodes.length;
+ nodes.push({ name: joint.name, parent: -1, ...fields, meshIds: [], derivedParentJoint: parentJoint });
+ });
+ skin.joints.forEach((joint, jointIndex) => {
+ const node = nodes[indexByJoint[jointIndex]];
+ if (node.derivedParentJoint !== undefined) node.parent = node.derivedParentJoint >= 0 ? indexByJoint[node.derivedParentJoint] : -1;
+ });
+}
+
+/**
+ * The hierarchy of joint and group nodes: the records of `options.nodes` when given, otherwise one node per skin joint.
+ * Each entry holds name, parent index, local TRS fields and the `mesh-N` ids it carries.
+ */
+export function buildHierarchy(parts, nodeRecords) {
+ const nodes = nodeRecords ? nodesFromRecords(nodeRecords) : [];
+ for (const part of parts) {
+ if (!part.skin) continue;
+ requireSkinFields(part.skin, part.name);
+ const missing = part.skin.joints.find(joint => !nodes.some(node => node.name === joint.name));
+ if (missing && nodeRecords) {
+ throw new RangeError(`GLB skin joint ${missing.name} of part ${part.name} is not in options.nodes. Pass the nodes of the same parsed asset.`);
+ }
+ if (!nodeRecords) appendDerivedJoints(nodes, part.skin);
+ }
+ return nodes;
+}
+
+/** Where each part hangs: the hierarchy node whose meshIds lists it, with its matrix made relative to that node. */
+export function hostOfPart(partIndex, hierarchy, worldCache) {
+ const host = hierarchy.findIndex(node => node.meshIds.includes(`mesh-${partIndex}`));
+ if (host < 0) return null;
+ return { index: host, world: worldMatrixOf(host, hierarchy, worldCache) };
+}
+
+export function relativeMatrix(partMatrix, hostWorld) {
+ return mat4.multiply(mat4.create(), mat4.invert(mat4.create(), hostWorld), partMatrix);
+}
+
+export function hierarchyNodeFields(node) {
+ return transformFields(node.translation ?? [0, 0, 0], node.rotation ?? IDENTITY_ROTATION, node.scale ?? [1, 1, 1]);
+}
+
+/** glTF skin for a part: inverse bind matrices fold in the bind matrix, so joint world * matrix * vertex is the pose. */
+export function writeSkin(writer, skin, nodeIndexByName, cache) {
+ if (cache.has(skin)) return cache.get(skin);
+ const count = skin.joints.length;
+ const matrices = new Float32Array(count * 16);
+ const bind = skin.bindMatrix ?? mat4.create();
+ for (let joint = 0; joint < count; joint++) {
+ const inverseBind = skin.inverseBindMatrices.subarray(joint * 16, joint * 16 + 16);
+ matrices.set(mat4.multiply(mat4.create(), inverseBind, bind), joint * 16);
+ }
+ writer.document.skins ??= [];
+ writer.document.skins.push({
+ joints: skin.joints.map(joint => nodeIndexByName.get(joint.name)),
+ inverseBindMatrices: writer.addAccessor(matrices, 'MAT4', undefined, { bounds: false }),
+ });
+ cache.set(skin, writer.document.skins.length - 1);
+ return writer.document.skins.length - 1;
+}
+
+/** Skin weights as glTF wants them: four joints per vertex, summing to one. */
+export function normalizedWeights(weights) {
+ const result = new Float32Array(weights.length);
+ for (let vertex = 0; vertex < weights.length; vertex += 4) {
+ const total = weights[vertex] + weights[vertex + 1] + weights[vertex + 2] + weights[vertex + 3];
+ for (let influence = 0; influence < 4; influence++) result[vertex + influence] = weights[vertex + influence] / total;
+ }
+ return result;
+}
+
+function trackOutput(track) {
+ const zero = new Array(COMPONENTS_BY_PATH[track.property]).fill(0);
+ const rows = [];
+ for (const keyframe of track.keyframes) {
+ const value = Array.isArray(keyframe.value) ? keyframe.value : Array.from(keyframe.value);
+ if (track.interpolation === 'CUBICSPLINE') rows.push(Array.from(keyframe.inTangent), value, Array.from(keyframe.outTangent));
+ // SMOOTH eases each segment with smoothstep, which is a cubic Hermite segment with zero tangents.
+ else if (track.interpolation === 'SMOOTH') rows.push(zero, value, zero);
+ else rows.push(value);
+ }
+ return Float32Array.from(rows.flat());
+}
+
+const GLTF_INTERPOLATION = { LINEAR: 'LINEAR', STEP: 'STEP', SMOOTH: 'CUBICSPLINE', CUBICSPLINE: 'CUBICSPLINE' };
+
+function writeTrack(writer, animation, track, nodeIndex) {
+ const path = GLTF_PATHS[track.property];
+ if (!path) {
+ throw new RangeError(`GLB export cannot write ${track.property} tracks (target ${track.target}). Only translation, rotation and scale tracks are exported; remove the others from the clip.`);
+ }
+ const times = Float32Array.from(track.keyframes, keyframe => keyframe.time);
+ animation.samplers.push({
+ input: writer.addAccessor(times, 'SCALAR', undefined, { bounds: true }),
+ output: writer.addAccessor(trackOutput(track), COMPONENTS_BY_PATH[track.property] === 4 ? 'VEC4' : 'VEC3', undefined, { bounds: false }),
+ interpolation: GLTF_INTERPOLATION[track.interpolation ?? 'LINEAR'],
+ });
+ animation.channels.push({ sampler: animation.samplers.length - 1, target: { node: nodeIndex, path } });
+}
+
+/** Clips in createAnimationClip form; track targets are node names. */
+export function writeAnimations(writer, clips, nodeIndexByName, prepareNodeForAnimation) {
+ writer.document.animations = [];
+ clips.forEach((clip, clipIndex) => {
+ if (!Array.isArray(clip?.tracks) || !clip.tracks.length) throw new TypeError(`GLB clip ${clipIndex} needs tracks. Build it with createAnimationClip or clipFromGltfAnimation.`);
+ const animation = { name: clip.name ?? `clip ${clipIndex}`, samplers: [], channels: [] };
+ for (const track of clip.tracks) {
+ const nodeIndex = nodeIndexByName.get(track.target);
+ if (nodeIndex === undefined) {
+ throw new RangeError(`GLB clip ${animation.name} targets ${track.target}, which is no exported node. Pass options.nodes from the parsed asset, or name a part or joint.`);
+ }
+ prepareNodeForAnimation(nodeIndex);
+ writeTrack(writer, animation, track, nodeIndex);
+ }
+ writer.document.animations.push(animation);
+ });
+}
diff --git a/src/export-textures.js b/src/export-textures.js
new file mode 100644
index 00000000..62f21b93
--- /dev/null
+++ b/src/export-textures.js
@@ -0,0 +1,86 @@
+import { encodePng } from './export-png.js';
+
+export const DEFAULT_MAX_TEXTURE_SIZE = 2048;
+const ABSOLUTE_MAX_TEXTURE_SIZE = 16384;
+const WRAP_DEFAULT = 10497;
+const MIN_FILTER_DEFAULT = 9987;
+const MAG_FILTER_DEFAULT = 9729;
+
+function pixelsOf(image, channel) {
+ const width = image?.naturalWidth ?? image?.width;
+ const height = image?.naturalHeight ?? image?.height;
+ if (!Number.isInteger(width) || !Number.isInteger(height) || width < 1 || height < 1) {
+ throw new TypeError(`GLB ${channel} needs an image with a whole width and height.`);
+ }
+ if (image.data) {
+ if (image.data.length < width * height * 4) throw new RangeError(`GLB ${channel} image data must hold RGBA8 pixels for every texel.`);
+ return { width, height, pixels: image.data };
+ }
+ // Browser images, bitmaps and canvases: read the pixels back through a canvas.
+ const canvas = typeof OffscreenCanvas === 'function' ? new OffscreenCanvas(width, height) : globalThis.document?.createElement('canvas');
+ if (!canvas) throw new TypeError(`GLB ${channel} needs RGBA pixel data ({ width, height, data }) outside a browser.`);
+ canvas.width = width;
+ canvas.height = height;
+ const context = canvas.getContext('2d');
+ context.drawImage(image, 0, 0);
+ return { width, height, pixels: context.getImageData(0, 0, width, height).data };
+}
+
+/** Writes each distinct image once as an embedded PNG and shares samplers and textures between channels. */
+export function createTextureWriter(writer, maxTextureSize = DEFAULT_MAX_TEXTURE_SIZE) {
+ if (!Number.isInteger(maxTextureSize) || maxTextureSize < 1 || maxTextureSize > ABSOLUTE_MAX_TEXTURE_SIZE) {
+ throw new RangeError(`maxTextureSize must be a whole number from 1 to ${ABSOLUTE_MAX_TEXTURE_SIZE}.`);
+ }
+ const { document } = writer;
+ document.images = [];
+ document.samplers = [];
+ document.textures = [];
+ const imageIndices = new Map();
+ const samplerIndices = new Map();
+ const textureIndices = new Map();
+
+ function imageIndex(descriptor, channel) {
+ const flipRows = descriptor.flipY === true;
+ const known = imageIndices.get(descriptor.image);
+ if (known?.has(flipRows)) return known.get(flipRows);
+ const { width, height, pixels } = pixelsOf(descriptor.image, channel);
+ if (width > maxTextureSize || height > maxTextureSize) {
+ throw new RangeError(`GLB ${channel} image is ${width}x${height}, above maxTextureSize ${maxTextureSize}. Resize the image, or pass exportGlb(parts, { maxTextureSize }) up to ${ABSOLUTE_MAX_TEXTURE_SIZE} if the file size is acceptable.`);
+ }
+ const bytes = encodePng(pixels, width, height, { flipRows });
+ document.images.push({ bufferView: writer.addBufferView(bytes), mimeType: 'image/png' });
+ const index = document.images.length - 1;
+ imageIndices.set(descriptor.image, (known ?? new Map()).set(flipRows, index));
+ return index;
+ }
+
+ function samplerIndex(descriptor) {
+ const sampler = {
+ magFilter: descriptor.magFilter ?? MAG_FILTER_DEFAULT,
+ minFilter: descriptor.minFilter ?? MIN_FILTER_DEFAULT,
+ wrapS: descriptor.wrapS ?? WRAP_DEFAULT,
+ wrapT: descriptor.wrapT ?? WRAP_DEFAULT,
+ };
+ const key = JSON.stringify(sampler);
+ if (!samplerIndices.has(key)) {
+ samplerIndices.set(key, document.samplers.length);
+ document.samplers.push(sampler);
+ }
+ return samplerIndices.get(key);
+ }
+
+ return {
+ /** Index of the glTF texture for a renderer texture descriptor `{ image, wrapS, ... }`. */
+ textureIndex(descriptor, channel) {
+ if ((descriptor.uvChannel ?? 0) !== 0) throw new RangeError(`GLB ${channel} uses UV channel ${descriptor.uvChannel}; only channel 0 is supported.`);
+ const source = imageIndex(descriptor, channel);
+ const sampler = samplerIndex(descriptor);
+ const key = `${source}:${sampler}`;
+ if (!textureIndices.has(key)) {
+ textureIndices.set(key, document.textures.length);
+ document.textures.push({ sampler, source });
+ }
+ return textureIndices.get(key);
+ },
+ };
+}
diff --git a/src/export-writer.js b/src/export-writer.js
new file mode 100644
index 00000000..f0ba4c16
--- /dev/null
+++ b/src/export-writer.js
@@ -0,0 +1,89 @@
+const COMPONENT_COUNTS = { SCALAR: 1, VEC2: 2, VEC3: 3, VEC4: 4, MAT4: 16 };
+const COMPONENT_TYPES = [[Float32Array, 5126], [Uint32Array, 5125], [Uint16Array, 5123], [Uint8Array, 5121]];
+
+export function paddedLength(length) {
+ return Math.ceil(length / 4) * 4;
+}
+
+function componentTypeOf(data) {
+ const match = COMPONENT_TYPES.find(([type]) => data instanceof type);
+ if (!match) throw new TypeError('GLB accessors require Float32, Uint32, Uint16 or Uint8 arrays.');
+ return match[1];
+}
+
+function componentBounds(data, componentCount) {
+ const minimum = new Array(componentCount).fill(Infinity);
+ const maximum = new Array(componentCount).fill(-Infinity);
+ for (let index = 0; index < data.length; index++) {
+ const component = index % componentCount;
+ minimum[component] = Math.min(minimum[component], data[index]);
+ maximum[component] = Math.max(maximum[component], data[index]);
+ }
+ return { min: minimum, max: maximum };
+}
+
+/** Collects the JSON document and the binary chunk of one GLB. */
+export function createGlbWriter() {
+ const document = {
+ asset: { version: '2.0', generator: '67.js' },
+ scene: 0,
+ scenes: [{ nodes: [] }],
+ nodes: [],
+ meshes: [],
+ materials: [],
+ accessors: [],
+ bufferViews: [],
+ buffers: [],
+ };
+ const chunks = [];
+ let byteLength = 0;
+
+ function addBufferView(bytes, target) {
+ const view = { buffer: 0, byteOffset: byteLength, byteLength: bytes.byteLength };
+ if (target !== undefined) view.target = target;
+ document.bufferViews.push(view);
+ chunks.push({ offset: byteLength, data: bytes });
+ byteLength += paddedLength(bytes.byteLength);
+ return document.bufferViews.length - 1;
+ }
+
+ function addAccessor(data, type, target, { bounds = type === 'VEC3' } = {}) {
+ const bytes = new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
+ const componentCount = COMPONENT_COUNTS[type];
+ const entry = { bufferView: addBufferView(bytes, target), componentType: componentTypeOf(data), count: data.length / componentCount, type };
+ if (bounds) Object.assign(entry, componentBounds(data, componentCount));
+ document.accessors.push(entry);
+ return document.accessors.length - 1;
+ }
+
+ function addExtension(name, { required = false } = {}) {
+ document.extensionsUsed = [...new Set([...document.extensionsUsed ?? [], name])];
+ if (required) document.extensionsRequired = [...new Set([...document.extensionsRequired ?? [], name])];
+ }
+
+ function finish() {
+ document.buffers.push({ byteLength });
+ for (const key of ['skins', 'animations', 'images', 'samplers', 'textures']) {
+ if (document[key]?.length === 0) delete document[key];
+ }
+ const json = new TextEncoder().encode(JSON.stringify(document));
+ const jsonLength = paddedLength(json.length);
+ const result = new ArrayBuffer(12 + 8 + jsonLength + 8 + byteLength);
+ const header = new DataView(result);
+ header.setUint32(0, 0x46546c67, true);
+ header.setUint32(4, 2, true);
+ header.setUint32(8, result.byteLength, true);
+ header.setUint32(12, jsonLength, true);
+ header.setUint32(16, 0x4e4f534a, true);
+ const bytes = new Uint8Array(result);
+ bytes.fill(32, 20, 20 + jsonLength);
+ bytes.set(json, 20);
+ const binaryHeader = 20 + jsonLength;
+ header.setUint32(binaryHeader, byteLength, true);
+ header.setUint32(binaryHeader + 4, 0x004e4942, true);
+ for (const chunk of chunks) bytes.set(chunk.data, binaryHeader + 8 + chunk.offset);
+ return result;
+ }
+
+ return { document, addBufferView, addAccessor, addExtension, finish };
+}
diff --git a/src/export.js b/src/export.js
index 4198eb2f..4e4a1861 100644
--- a/src/export.js
+++ b/src/export.js
@@ -1,7 +1,11 @@
import { validateMorphGeometry, validateMorphPose } from './morph.js';
+import { validateSkinGeometry } from './skinning.js';
+import { boxProjectedGeometry } from './export-box-uv.js';
+import { createTextureWriter } from './export-textures.js';
+import { createGlbWriter } from './export-writer.js';
+import { buildHierarchy, decomposeMatrix, hierarchyNodeFields, hostOfPart, normalizedWeights, relativeMatrix, writeAnimations, writeSkin } from './export-skeleton.js';
const EMISSIVE_STRENGTH = 'KHR_materials_emissive_strength';
-const COMPONENT_COUNTS = { SCALAR: 1, VEC2: 2, VEC3: 3 };
function validateFloatChannel(values, length, label, bounded = false) {
if (!(values instanceof Float32Array) || values.length !== length) {
@@ -63,14 +67,18 @@ function validateGeometry(geometry) {
}
}
-function validatePart(part) {
- if (!part.matrix || part.matrix.length !== 16 || Array.from(part.matrix).some(value => !Number.isFinite(value) || !Number.isFinite(Math.fround(value)))) {
+// A skinned part takes its pose from its joints, so only parts with a node transform need a valid matrix.
+function validateMatrix(matrix) {
+ if (!matrix || matrix.length !== 16 || Array.from(matrix).some(value => !Number.isFinite(value) || !Number.isFinite(Math.fround(value)))) {
throw new RangeError('GLB matrix requires 16 finite components.');
}
- if (part.matrix[3] !== 0 || part.matrix[7] !== 0 || part.matrix[11] !== 0 || part.matrix[15] !== 1) {
+ if (matrix[3] !== 0 || matrix[7] !== 0 || matrix[11] !== 0 || matrix[15] !== 1) {
throw new RangeError('GLB matrix requires an affine transform.');
}
- validateTransformColumns(part.matrix);
+ validateTransformColumns(matrix);
+}
+
+function validatePart(part) {
const material = part.material;
if (!material || typeof material !== 'object') throw new TypeError('GLB parts require a material.');
validateColor(material.color, 'GLB base color');
@@ -99,12 +107,100 @@ function validateTransformColumns(matrix) {
}
}
-function paddedLength(length) {
- return Math.ceil(length / 4) * 4;
+const TEXTURE_CHANNELS = ['map', 'normalMap', 'metallicRoughnessMap', 'occlusionMap', 'emissiveMap'];
+const OPTION_NAMES = ['clips', 'nodes', 'maxTextureSize'];
+
+function validateOptions(options) {
+ if (!options || typeof options !== 'object') throw new TypeError('GLB export options must be an object.');
+ for (const name of Object.keys(options)) {
+ if (!OPTION_NAMES.includes(name)) throw new TypeError(`GLB export does not take ${name}. Options: ${OPTION_NAMES.join(', ')}.`);
+ }
+ if (options.clips !== undefined && !Array.isArray(options.clips)) throw new TypeError('GLB export clips must be an array.');
+ if (options.nodes !== undefined && !Array.isArray(options.nodes)) throw new TypeError('GLB export nodes must be an array.');
+}
+
+function validateSkinnedPart(part) {
+ validateSkinGeometry(part.geometry, part.skin);
+}
+
+function columnLengths(matrix) {
+ return [0, 4, 8].map(offset => Math.hypot(matrix[offset], matrix[offset + 1], matrix[offset + 2]));
+}
+
+function createIdentityTracker() {
+ const identities = new WeakMap();
+ let next = 0;
+ return object => {
+ if (!identities.has(object)) identities.set(object, next++);
+ return identities.get(object);
+ };
+}
+
+function materialKeyOf(material, identify) {
+ const textures = TEXTURE_CHANNELS.map(channel => material[channel] ? identify(material[channel]) : null);
+ const fields = { ...material };
+ for (const channel of [...TEXTURE_CHANNELS, 'pattern', 'boxMapScale', 'boxMapAxis']) delete fields[channel];
+ return JSON.stringify([fields, textures, material.boxMapScale ?? 0, material.boxMapAxis ?? 1]);
+}
+
+function writeMaterial(writer, textureWriter, material) {
+ const pbr = { baseColorFactor: [...material.color, 1], metallicFactor: material.metallic, roughnessFactor: material.roughness };
+ const gltfMaterial = {
+ pbrMetallicRoughness: pbr,
+ emissiveFactor: (material.emission ?? 0) === 0 ? [0, 0, 0] : Array.from(material.emissiveColor ?? material.color),
+ };
+ writeAlphaFields(gltfMaterial, material);
+ const strength = material.emission ?? 0;
+ if (strength !== 0 && strength !== 1) {
+ gltfMaterial.extensions = { [EMISSIVE_STRENGTH]: { emissiveStrength: strength } };
+ writer.addExtension(EMISSIVE_STRENGTH, { required: true });
+ }
+ const textureOf = channel => ({ index: textureWriter.textureIndex(material[channel], channel) });
+ if (material.map) pbr.baseColorTexture = textureOf('map');
+ if (material.metallicRoughnessMap) pbr.metallicRoughnessTexture = textureOf('metallicRoughnessMap');
+ if (material.normalMap) gltfMaterial.normalTexture = { ...textureOf('normalMap'), scale: material.normalScale?.[0] ?? 1 };
+ if (material.occlusionMap) gltfMaterial.occlusionTexture = { ...textureOf('occlusionMap'), strength: material.occlusionStrength ?? 1 };
+ if (material.emissiveMap) gltfMaterial.emissiveTexture = textureOf('emissiveMap');
+ return gltfMaterial;
+}
+
+function writeGeometry(writer, geometry) {
+ const ARRAY_BUFFER = 34962;
+ const attributes = { POSITION: writer.addAccessor(geometry.positions, 'VEC3', ARRAY_BUFFER), NORMAL: writer.addAccessor(geometry.normals, 'VEC3', ARRAY_BUFFER) };
+ const primitive = { attributes, indices: writer.addAccessor(geometry.indices, 'SCALAR', 34963) };
+ if (geometry.colors) attributes.COLOR_0 = writer.addAccessor(geometry.colors, 'VEC3', ARRAY_BUFFER);
+ if (geometry.uvs) attributes.TEXCOORD_0 = writer.addAccessor(geometry.uvs, 'VEC2', ARRAY_BUFFER);
+ if (geometry.skinIndices) {
+ attributes.JOINTS_0 = writer.addAccessor(Uint16Array.from(geometry.skinIndices), 'VEC4', ARRAY_BUFFER, { bounds: false });
+ attributes.WEIGHTS_0 = writer.addAccessor(normalizedWeights(geometry.skinWeights), 'VEC4', ARRAY_BUFFER, { bounds: false });
+ }
+ if (geometry.morphTargets) {
+ primitive.targets = geometry.morphTargets.map(target => {
+ const channels = {};
+ if (target.positions) channels.POSITION = writer.addAccessor(target.positions, 'VEC3', ARRAY_BUFFER);
+ if (target.normals) channels.NORMAL = writer.addAccessor(target.normals, 'VEC3', ARRAY_BUFFER);
+ return channels;
+ });
+ }
+ return primitive;
+}
+
+function requireUvsForTextures(part) {
+ const textured = TEXTURE_CHANNELS.some(channel => part.material[channel]);
+ const boxMapped = (part.material.boxMapScale ?? 0) > 0;
+ if (textured && !boxMapped && !part.geometry.uvs) {
+ throw new RangeError(`GLB part ${part.name} has textures but its geometry has no uvs. Add a uv_unwrap node to the mesh stack, or set geometry.uvs.`);
+ }
}
-export function exportGlb(parts) {
+/**
+ * Returns a self-contained GLB ArrayBuffer for the parts.
+ * Options: `clips` (createAnimationClip form, track targets are node names), `nodes` (the `nodes` of a parsed asset,
+ * which hold joints and groups, so skinned parts and clips keep their hierarchy), `maxTextureSize` (default 2048).
+ */
+export function exportGlb(parts, options = {}) {
if (!Array.isArray(parts) || parts.length === 0) throw new TypeError('GLB export requires a nonempty parts array.');
+ validateOptions(options);
const validatedGeometries = new Set();
const morphMetadata = new Map();
for (const part of parts) {
@@ -119,116 +215,92 @@ export function exportGlb(parts) {
} else {
morphMetadata.set(part.geometry, validateMorphGeometry(part.geometry, part.morph));
}
- if (part.skin || part.geometry.skinIndices || part.geometry.skinWeights) {
- throw new RangeError('GLB export cannot preserve skinning yet. Bake the pose or export through a tool that preserves the skeleton.');
- }
- for (const channel of ['map', 'normalMap', 'metallicRoughnessMap', 'occlusionMap', 'emissiveMap']) {
- if (part.material[channel]) {
- throw new RangeError(`GLB export cannot preserve ${channel} yet. Texture export must be implemented before exporting this material.`);
- }
- }
+ validateSkinnedPart(part);
+ requireUvsForTextures(part);
}
- const document = {
- asset: { version: '2.0', generator: '67.js' },
- scene: 0,
- scenes: [{ nodes: parts.map((_, index) => index) }],
- nodes: [],
- meshes: [],
- materials: [],
- accessors: [],
- bufferViews: [],
- buffers: [],
- };
- const chunks = [];
- let byteLength = 0;
+ const hierarchy = buildHierarchy(parts, options.nodes);
+ const worldCache = new Map();
+ parts.forEach((part, partIndex) => {
+ if (part.skin) return;
+ const host = part.matrix?.length === 16 ? hostOfPart(partIndex, hierarchy, worldCache) : null;
+ validateMatrix(host ? relativeMatrix(part.matrix, host.world) : part.matrix);
+ });
+ const writer = createGlbWriter();
+ const { document } = writer;
+ const textureWriter = createTextureWriter(writer, options.maxTextureSize);
+ const nodeIndexByName = new Map(hierarchy.map((node, index) => [node.name, index]));
const geometries = new Map();
const materials = new Map();
const meshes = new Map();
- function accessor(data, type, target) {
- const viewIndex = document.bufferViews.length;
- document.bufferViews.push({ buffer: 0, byteOffset: byteLength, byteLength: data.byteLength, target });
- chunks.push({ offset: byteLength, data: new Uint8Array(data.buffer, data.byteOffset, data.byteLength) });
- byteLength += paddedLength(data.byteLength);
- const entry = { bufferView: viewIndex, componentType: data instanceof Float32Array ? 5126 : 5125, count: data.length / COMPONENT_COUNTS[type], type };
- if (type === 'VEC3') {
- entry.min = [Infinity, Infinity, Infinity];
- entry.max = [-Infinity, -Infinity, -Infinity];
- for (let index = 0; index < data.length; index++) {
- const component = index % 3;
- entry.min[component] = Math.min(entry.min[component], data[index]);
- entry.max[component] = Math.max(entry.max[component], data[index]);
- }
+ const skins = new Map();
+ const identify = createIdentityTracker();
+
+ function geometryFor(part) {
+ const boxMapped = (part.material.boxMapScale ?? 0) > 0;
+ const scale = columnLengths(part.matrix);
+ const variant = boxMapped ? `box:${part.material.boxMapScale}:${part.material.boxMapAxis ?? 1}:${scale.join(',')}` : 'authored';
+ if (!geometries.has(part.geometry)) geometries.set(part.geometry, new Map());
+ const variants = geometries.get(part.geometry);
+ if (!variants.has(variant)) {
+ const source = boxMapped ? boxProjectedGeometry(part.geometry, scale, part.material.boxMapScale, part.material.boxMapAxis ?? 1) : part.geometry;
+ variants.set(variant, writeGeometry(writer, source));
}
- document.accessors.push(entry);
- return document.accessors.length - 1;
+ return variants.get(variant);
}
- for (const part of parts) {
- if (!geometries.has(part.geometry)) {
- const geometry = {
- attributes: { POSITION: accessor(part.geometry.positions, 'VEC3', 34962), NORMAL: accessor(part.geometry.normals, 'VEC3', 34962) },
- indices: accessor(part.geometry.indices, 'SCALAR', 34963),
- };
- if (part.geometry.colors) geometry.attributes.COLOR_0 = accessor(part.geometry.colors, 'VEC3', 34962);
- if (part.geometry.uvs) geometry.attributes.TEXCOORD_0 = accessor(part.geometry.uvs, 'VEC2', 34962);
- if (part.geometry.morphTargets) {
- geometry.targets = part.geometry.morphTargets.map(target => {
- const channels = {};
- if (target.positions) channels.POSITION = accessor(target.positions, 'VEC3', 34962);
- if (target.normals) channels.NORMAL = accessor(target.normals, 'VEC3', 34962);
- return channels;
- });
- }
- geometries.set(part.geometry, geometry);
- }
- const materialKey = JSON.stringify(part.material);
+
+ for (const node of hierarchy) document.nodes.push({ name: node.name, ...hierarchyNodeFields(node) });
+ hierarchy.forEach((node, index) => {
+ if (node.parent >= 0) (document.nodes[node.parent].children ??= []).push(index);
+ });
+ const sceneRoots = hierarchy.flatMap((node, index) => node.parent < 0 ? [index] : []);
+ parts.forEach((part, partIndex) => {
+ const geometry = geometryFor(part);
+ const materialKey = materialKeyOf(part.material, identify);
if (!materials.has(materialKey)) {
materials.set(materialKey, document.materials.length);
- const material = {
- pbrMetallicRoughness: { baseColorFactor: [...part.material.color, 1], metallicFactor: part.material.metallic, roughnessFactor: part.material.roughness },
- emissiveFactor: (part.material.emission ?? 0) === 0 ? [0, 0, 0] : Array.from(part.material.emissiveColor ?? part.material.color),
- };
- writeAlphaFields(material, part.material);
- const strength = part.material.emission ?? 0;
- if (strength !== 0 && strength !== 1) {
- material.extensions = { [EMISSIVE_STRENGTH]: { emissiveStrength: strength } };
- document.extensionsUsed = [EMISSIVE_STRENGTH];
- document.extensionsRequired = [EMISSIVE_STRENGTH];
- }
- document.materials.push(material);
+ document.materials.push(writeMaterial(writer, textureWriter, part.material));
}
- const geometry = geometries.get(part.geometry);
const material = materials.get(materialKey);
const meshKey = `${geometry.indices}:${material}`;
if (!meshes.has(meshKey)) {
meshes.set(meshKey, document.meshes.length);
document.meshes.push({ primitives: [{ ...geometry, material }] });
}
- const node = { name: part.name, mesh: meshes.get(meshKey), matrix: Array.from(part.matrix) };
+ const host = part.skin ? null : hostOfPart(partIndex, hierarchy, worldCache);
+ // The mesh node of an imported asset is one of its nodes: keep the mesh on it instead of nesting a same-named node.
+ const mergeIntoHost = host && hierarchy[host.index].name === part.name && hierarchy[host.index].meshIds.length === 1;
+ const node = mergeIntoHost ? document.nodes[host.index] : { name: part.name };
+ node.mesh = meshes.get(meshKey);
if (part.morph) node.weights = Array.from(part.morph.weights);
+ if (part.skin) {
+ // A skinned mesh takes its pose from its joints, so its own node stays at the origin.
+ node.skin = writeSkin(writer, part.skin, nodeIndexByName, skins);
+ } else if (!mergeIntoHost) {
+ node.matrix = Array.from(host ? relativeMatrix(part.matrix, host.world) : part.matrix);
+ }
+ if (mergeIntoHost) return;
document.nodes.push(node);
+ const nodeIndex = document.nodes.length - 1;
+ if (host) (document.nodes[host.index].children ??= []).push(nodeIndex);
+ else sceneRoots.push(nodeIndex);
+ });
+ document.scenes[0].nodes = sceneRoots;
+ if (options.clips?.length) {
+ for (const [index, node] of document.nodes.entries()) {
+ if (!nodeIndexByName.has(node.name)) nodeIndexByName.set(node.name, index);
+ }
+ writeAnimations(writer, options.clips, nodeIndexByName, nodeIndex => {
+ const node = document.nodes[nodeIndex];
+ if (!node.matrix) return;
+ Object.assign(node, decomposeMatrix(node.matrix));
+ delete node.matrix;
+ });
}
- document.buffers.push({ byteLength });
- const json = new TextEncoder().encode(JSON.stringify(document));
- const jsonLength = paddedLength(json.length);
- const result = new ArrayBuffer(12 + 8 + jsonLength + 8 + byteLength);
- const header = new DataView(result);
- header.setUint32(0, 0x46546c67, true);
- header.setUint32(4, 2, true);
- header.setUint32(8, result.byteLength, true);
- header.setUint32(12, jsonLength, true);
- header.setUint32(16, 0x4e4f534a, true);
- const bytes = new Uint8Array(result);
- bytes.fill(32, 20, 20 + jsonLength);
- bytes.set(json, 20);
- const binaryHeader = 20 + jsonLength;
- header.setUint32(binaryHeader, byteLength, true);
- header.setUint32(binaryHeader + 4, 0x004e4942, true);
- for (const chunk of chunks) bytes.set(chunk.data, binaryHeader + 8 + chunk.offset);
- return result;
-}
-
-export function downloadGlb(parts) {
- const url = URL.createObjectURL(new Blob([exportGlb(parts)], { type: 'model/gltf-binary' }));
+ return writer.finish();
+}
+
+export function downloadGlb(parts, options) {
+ const url = URL.createObjectURL(new Blob([exportGlb(parts, options)], { type: 'model/gltf-binary' }));
const link = document.createElement('a');
link.href = url;
link.download = '67js-wall-e.glb';
diff --git a/tests/export-roundtrip.test.js b/tests/export-roundtrip.test.js
new file mode 100644
index 00000000..130c5b1e
--- /dev/null
+++ b/tests/export-roundtrip.test.js
@@ -0,0 +1,194 @@
+import assert from 'node:assert/strict';
+import { readFileSync } from 'node:fs';
+import test from 'node:test';
+import { inflateSync } from 'node:zlib';
+import { mat4 } from 'gl-matrix';
+import { exportGlb } from '../src/export.js';
+import { parseGltf } from '../src/gltf.js';
+import { box } from '../src/geometry.js';
+import { clipFromGltfAnimation } from '../src/skeleton-pose.js';
+import { bakeMaterialPattern, normalizeMaterialPattern } from '../src/material-patterns.js';
+
+// CC0 RobotExpressive by Tomás Laulhé, modified by Don McCurdy: a skinned character with many clips.
+const robotBytes = readFileSync(new URL('./fixtures/RobotExpressive.glb', import.meta.url));
+const robotBuffer = robotBytes.buffer.slice(robotBytes.byteOffset, robotBytes.byteOffset + robotBytes.byteLength);
+// Node has no image decoder: decode the exporter's PNGs (unfiltered rows) so parseGltf sees real pixels.
+globalThis.self = globalThis;
+globalThis.createImageBitmap = async blob => {
+ const bytes = Buffer.from(await blob.arrayBuffer());
+ const width = bytes.readUInt32BE(16);
+ const height = bytes.readUInt32BE(20);
+ const channels = bytes[25] === 6 ? 4 : 3;
+ const idat = [];
+ for (let offset = 8; offset < bytes.length;) {
+ const length = bytes.readUInt32BE(offset);
+ if (bytes.toString('latin1', offset + 4, offset + 8) === 'IDAT') idat.push(bytes.subarray(offset + 8, offset + 8 + length));
+ offset += 12 + length;
+ }
+ const raw = inflateSync(Buffer.concat(idat));
+ const data = new Uint8Array(width * height * 4).fill(255);
+ for (let row = 0; row < height; row++) {
+ assert.equal(raw[row * (width * channels + 1)], 0);
+ for (let column = 0; column < width; column++) {
+ for (let channel = 0; channel < channels; channel++) data[(row * width + column) * 4 + channel] = raw[row * (width * channels + 1) + 1 + column * channels + channel];
+ }
+ }
+ return { width, height, data, close() {} };
+};
+
+const PARSE_OPTIONS = { maxVertices: 500000 };
+
+function checkerImage(size) {
+ const data = new Uint8ClampedArray(size * size * 4);
+ for (let texel = 0; texel < size * size; texel++) {
+ const checker = ((texel % size >> 1) + (Math.floor(texel / size) >> 1)) % 2 ? 255 : 40;
+ data.set([checker, 255 - checker, 128, 255], texel * 4);
+ }
+ return { width: size, height: size, data };
+}
+
+function maximumDifference(first, second) {
+ let largest = 0;
+ for (let index = 0; index < first.length; index++) largest = Math.max(largest, Math.abs(first[index] - second[index]));
+ return largest;
+}
+
+function texturedBox(textureCount = 5) {
+ const geometry = box();
+ geometry.uvs = new Float32Array(geometry.positions.length / 3 * 2).map((_, index) => index % 7 / 7);
+ const material = { color: [0.8, 0.7, 0.6], metallic: 0.2, roughness: 0.6, emission: 1, emissiveColor: [0.5, 0.2, 0.1], normalScale: [0.5, 0.5], occlusionStrength: 0.75 };
+ ['map', 'normalMap', 'metallicRoughnessMap', 'occlusionMap', 'emissiveMap'].slice(0, textureCount).forEach((channel, index) => {
+ material[channel] = { image: checkerImage(8 + index * 4), wrapS: 33071, wrapT: 33648, magFilter: 9728, colorSpace: channel === 'map' || channel === 'emissiveMap' ? 'srgb' : 'linear' };
+ });
+ return { name: 'Crate', geometry, matrix: mat4.create(), material };
+}
+
+test('all five texture channels round trip as PNG with their pixels, samplers and factors', async () => {
+ const source = texturedBox();
+ const imported = await parseGltf(exportGlb([source]));
+ const material = imported.parts[0].material;
+ for (const channel of ['map', 'normalMap', 'metallicRoughnessMap', 'occlusionMap', 'emissiveMap']) {
+ const expected = source.material[channel].image;
+ const actual = material[channel].image;
+ assert.equal(actual.width, expected.width, channel);
+ assert.equal(actual.height, expected.height, channel);
+ const pixels = Uint8ClampedArray.from(actual.data ?? []);
+ if (pixels.length) assert.equal(maximumDifference(pixels, expected.data), 0, channel);
+ assert.equal(material[channel].wrapS, 33071);
+ assert.equal(material[channel].wrapT, 33648);
+ }
+ assert.deepEqual(material.normalScale, [0.5, 0.5]);
+ assert.equal(material.occlusionStrength, 0.75);
+});
+
+test('textures carry the flipY of their descriptor into glTF row order', async () => {
+ const source = texturedBox(1);
+ source.material.map.flipY = true;
+ const imported = await parseGltf(exportGlb([source]));
+ const expected = source.material.map.image;
+ const actual = imported.parts[0].material.map.image;
+ if (!actual.data) return;
+ const topRow = Array.from(actual.data.slice(0, expected.width * 4));
+ const lastSourceRow = Array.from(expected.data.slice((expected.height - 1) * expected.width * 4));
+ assert.deepEqual(topRow, lastSourceRow);
+});
+
+test('a pattern material exports box projected UVs and its baked textures', async () => {
+ const pattern = normalizeMaterialPattern({ type: 'wood', resolution: 256, size: 0.5 });
+ const baked = bakeMaterialPattern(pattern);
+ const source = {
+ name: 'Plank', geometry: box(), matrix: mat4.fromScaling(mat4.create(), [2, 1, 1]),
+ material: { color: [1, 1, 1], metallic: 0, roughness: 1, map: baked.map, normalMap: baked.normalMap, metallicRoughnessMap: baked.metallicRoughnessMap, boxMapScale: baked.boxMapScale, boxMapAxis: baked.boxMapAxis },
+ };
+ const imported = await parseGltf(exportGlb([source]));
+ const geometry = imported.parts[0].geometry;
+ assert.ok(geometry.uvs, 'the export gives pattern geometry UVs');
+ assert.equal(geometry.positions.length / 3, geometry.uvs.length / 2);
+ // Every vertex sits on one face, so its UV is the projection of its scaled position onto that face.
+ for (let vertex = 0; vertex < geometry.positions.length / 3; vertex++) {
+ const [x, y, z] = [0, 1, 2].map(axis => geometry.positions[vertex * 3 + axis] * [2, 1, 1][axis] * baked.boxMapScale);
+ const [u, v] = [geometry.uvs[vertex * 2], geometry.uvs[vertex * 2 + 1]];
+ const candidates = [[z, x], [x, z], [x, y], [z, y], [y, z]].filter(([expectedU, expectedV]) => Math.abs(expectedU - u) < 1e-4 && Math.abs(expectedV - v) < 1e-4);
+ assert.ok(candidates.length > 0 || [[x, z], [x, y], [z, y]].some(([expectedU, expectedV]) => Math.abs(expectedU - u) < 1e-4 && Math.abs(expectedV - v) < 1e-4));
+ }
+ assert.equal(imported.parts[0].material.map.image.width, 256);
+});
+
+test('RobotExpressive round trips geometry, skin, materials and every clip', async () => {
+ const original = await parseGltf(robotBuffer.slice(0), PARSE_OPTIONS);
+ const clips = original.animations.map((animation, index) => ({ ...clipFromGltfAnimation(animation), name: animation.name || `clip ${index}` }));
+ const exported = exportGlb(original.parts, { nodes: original.nodes, clips });
+ const copy = await parseGltf(exported.slice(0), PARSE_OPTIONS);
+
+ assert.equal(copy.parts.length, original.parts.length);
+ const skinnedBefore = original.parts.filter(part => part.skin).length;
+ assert.ok(skinnedBefore > 0, 'the fixture has skinned parts');
+ assert.equal(copy.parts.filter(part => part.skin).length, skinnedBefore);
+ assert.equal(copy.skins.length, original.skins.length);
+ assert.equal(copy.animations.length, original.animations.length);
+
+ const sortedNames = parts => parts.map(part => part.name).sort();
+ assert.deepEqual(sortedNames(copy.parts), sortedNames(original.parts));
+ const copyByName = new Map(copy.parts.map(part => [part.name, part]));
+ for (const part of original.parts) {
+ const other = copyByName.get(part.name);
+ assert.equal(other.geometry.positions.length, part.geometry.positions.length, part.name);
+ assert.equal(maximumDifference(other.geometry.positions, part.geometry.positions), 0, part.name);
+ assert.equal(other.geometry.morphTargets?.length ?? 0, part.geometry.morphTargets?.length ?? 0, part.name);
+ assert.ok(maximumDifference(other.material.color, part.material.color) < 1e-6, part.name);
+ assert.ok(Math.abs(other.material.roughness - part.material.roughness) < 1e-6, part.name);
+ assert.equal(Boolean(other.material.map), Boolean(part.material.map), part.name);
+ if (part.skin) assert.deepEqual(other.skin.joints.map(joint => joint.name), part.skin.joints.map(joint => joint.name));
+ }
+ for (let index = 0; index < original.animations.length; index++) {
+ assert.ok(Math.abs(copy.animations[index].duration - original.animations[index].duration) < 1e-5, original.animations[index].name);
+ const trackNames = animation => animation.tracks.filter(track => !track.name.endsWith('morphTargetInfluences')).map(track => track.name).sort();
+ assert.deepEqual(trackNames(copy.animations[index]), trackNames(original.animations[index]));
+ }
+});
+
+test('an exported clip poses the copy the way it poses the original', async () => {
+ const original = await parseGltf(robotBuffer.slice(0), PARSE_OPTIONS);
+ const clipIndex = original.animations.findIndex(animation => /walk/i.test(animation.name));
+ assert.ok(clipIndex >= 0, 'the fixture has a walking clip');
+ const clips = [{ ...clipFromGltfAnimation(original.animations[clipIndex]), name: 'Walking' }];
+ const copy = await parseGltf(exportGlb(original.parts, { nodes: original.nodes, clips }), PARSE_OPTIONS);
+ const time = original.animations[clipIndex].duration * 0.37;
+ original.applyAnimation(time, clipIndex);
+ copy.applyAnimation(time, 0);
+ const jointsBefore = original.skins[0].jointWorldMatrices;
+ const jointsAfter = copy.skins[0].jointWorldMatrices;
+ assert.ok(maximumDifference(jointsAfter, jointsBefore) < 1e-3);
+});
+
+test('skins built without a node list export derived joints and a clip can target them', async () => {
+ const geometry = box();
+ const vertexCount = geometry.positions.length / 3;
+ geometry.skinIndices = new Uint16Array(vertexCount * 4);
+ geometry.skinWeights = new Float32Array(vertexCount * 4);
+ for (let vertex = 0; vertex < vertexCount; vertex++) {
+ geometry.skinIndices[vertex * 4] = geometry.positions[vertex * 3 + 1] > 0 ? 1 : 0;
+ geometry.skinWeights[vertex * 4] = 1;
+ }
+ const jointWorldMatrices = new Float32Array(32);
+ mat4.identity(jointWorldMatrices.subarray(0, 16));
+ mat4.fromTranslation(jointWorldMatrices.subarray(16, 32), [0, 1, 0]);
+ const inverseBindMatrices = new Float32Array(32);
+ mat4.identity(inverseBindMatrices.subarray(0, 16));
+ mat4.fromTranslation(inverseBindMatrices.subarray(16, 32), [0, -1, 0]);
+ const skin = { jointMatrices: new Float32Array(32), joints: [{ name: 'root', parent: -1 }, { name: 'tip', parent: 0 }], inverseBindMatrices, jointWorldMatrices };
+ mat4.identity(skin.jointMatrices.subarray(0, 16));
+ mat4.identity(skin.jointMatrices.subarray(16, 32));
+ const part = { name: 'Rod', geometry, matrix: mat4.create(), material: { color: [1, 1, 1], metallic: 0, roughness: 1 }, skin };
+ const clip = { name: 'Bend', duration: 1, loop: true, tracks: [{ target: 'tip', property: 'rotation', interpolation: 'SMOOTH', keyframes: [{ time: 0, value: [0, 0, 0, 1] }, { time: 1, value: [0, 0, 0.7071068, 0.7071068] }] }] };
+ const copy = await parseGltf(exportGlb([part], { clips: [clip] }));
+ assert.deepEqual(copy.skins[0].joints.map(joint => [joint.name, joint.parent]), [['root', -1], ['tip', 0]]);
+ assert.equal(copy.animations.length, 1);
+ assert.equal(copy.animations[0].tracks[0].name, 'tip.quaternion');
+});
+
+test('a clip that targets a missing node names the fix', () => {
+ const part = texturedBox(0);
+ const clip = { duration: 1, loop: false, tracks: [{ target: 'ghost', property: 'translation', keyframes: [{ time: 0, value: [0, 0, 0] }] }] };
+ assert.throws(() => exportGlb([part], { clips: [clip] }), /ghost.*options\.nodes/);
+});
diff --git a/tests/export.test.js b/tests/export.test.js
index a1812a81..649db4b6 100644
--- a/tests/export.test.js
+++ b/tests/export.test.js
@@ -32,18 +32,20 @@ test('GLB export writes alpha mode, cutoff, opacity and double-sided so the load
assert.ok(Math.abs(loaded.opacity - 0.6) < 1e-6);
});
-test('GLB export refuses to silently discard any material texture channel', () => {
+test('GLB export names the fix when textures have no UVs or exceed the size limit', () => {
const part = createModel()[0];
- for (const channel of ['map', 'normalMap', 'metallicRoughnessMap', 'occlusionMap', 'emissiveMap']) {
- assert.throws(() => exportGlb([{ ...part, material: { ...part.material, [channel]: {} } }]),
- error => error instanceof RangeError && error.message.includes(channel));
- }
+ const image = { width: 4, height: 4, data: new Uint8ClampedArray(64).fill(255) };
+ const textured = { ...part, material: { ...part.material, map: { image } } };
+ assert.throws(() => exportGlb([textured]), /uv_unwrap/);
+ const withUvs = { ...textured, geometry: { ...part.geometry, uvs: new Float32Array(part.geometry.positions.length / 3 * 2) } };
+ assert.throws(() => exportGlb([withUvs], { maxTextureSize: 2 }), /maxTextureSize 2/);
+ assert.ok(exportGlb([withUvs]).byteLength > 0);
});
-test('GLB export rejects skinning instead of silently saving the undeformed bind mesh', () => {
+test('GLB export rejects a skin without joints and skin attributes without a skin', () => {
const part = createModel()[0];
- assert.throws(() => exportGlb([{ ...part, skin: { jointMatrices: new Float32Array(16) } }]), /preserve skinning/);
- assert.throws(() => exportGlb([{ ...part, geometry: { ...part.geometry, skinIndices: new Uint16Array(4) } }]), /preserve skinning/);
+ assert.throws(() => exportGlb([{ ...part, geometry: { ...part.geometry, skinIndices: new Uint16Array(4) } }]), /[Ss]kin/);
+ assert.throws(() => exportGlb([{ ...part, skin: { jointMatrices: new Float32Array(16) } }]), /[Ss]kin/);
});
test('GLB export rejects malformed morph pairs rather than discarding expressions', () => {