Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Preserve relative morph targets in GLB snapshots

Nguyen Xuan An3260a13b275f
diff --git a/docs/morph-targets.md b/docs/morph-targets.md
index 951f5215..e1a6a183 100644
--- a/docs/morph-targets.md
+++ b/docs/morph-targets.md
@@ -123,3 +123,14 @@ It checks independent signed poses, the 64th target, retained buffers, atomic re
`scripts/smoke-morph-composition.mjs` compares combined skinning, normal deltas, normal cancellation and shadow receivers with CPU-baked geometry.
The film scientist uses shared eyelid geometry with one retained blink pose per actor.
Visual quality and frame performance require separate scene measurements.
+
+## GLB snapshots
+
+`exportGlb(parts)` preserves relative position and normal target accessors and each node's current weights.
+Repeated instances retain shared meshes while their signed weights remain independent.
+The export contains editable targets and a static pose, rather than baked vertex positions.
+It does not serialize animation clips. Skinning and material textures still fail explicitly at export.
+The importer must support morph targets before opening the snapshot in 67.js.
+
+The output follows [glTF morph target and node weight semantics](https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#morph-targets).
+Export tests inspect the serialized accessors and load the GLB with the independent Three.js loader.
diff --git a/scripts/smoke-package.mjs b/scripts/smoke-package.mjs
index 886b994e..b6a1a32a 100644
--- a/scripts/smoke-package.mjs
+++ b/scripts/smoke-package.mjs
@@ -30,7 +30,7 @@ const sourceArchive = resolve(consumer, packedSource.filename);
const installed = spawnSync(process.execPath, [npmCli, 'install', `67js@file:${sourceArchive.replaceAll('\\', '/')}`, '@dimforge/[email protected]', '--ignore-scripts', '--no-audit', '--no-fund'], { cwd: consumer, windowsHide: true, encoding: 'utf8' });
assert.equal(installed.status, 0, installed.stderr);
const example = `import assert from 'node:assert/strict';
-import { VERSION, Renderer67, box, assemblyOffset, cameraView, fitPerspectiveDistance, createAnimationClip, sampleAnimationClip, EFFECT_PRESETS, createMorphPose, MAX_MORPH_TARGETS } from '67js';
+import { VERSION, Renderer67, box, assemblyOffset, cameraView, fitPerspectiveDistance, createAnimationClip, sampleAnimationClip, EFFECT_PRESETS, createMorphPose, MAX_MORPH_TARGETS, exportGlb } from '67js';
import { createModel } from '67js/addons/model';
import * as nature from '67js/addons/nature';
import * as film from '67js/addons/film';
@@ -42,6 +42,15 @@ assert.equal(VERSION, '${metadata.version}');
assert.equal(typeof Renderer67, 'function');
assert.equal(MAX_MORPH_TARGETS, 64);
assert.ok(createMorphPose(64).weights instanceof Float32Array);
+const morphGeometry = box();
+morphGeometry.morphTargets = [{ positions: new Float32Array(morphGeometry.positions.length).fill(0.125) }];
+const morphPose = createMorphPose(1);
+morphPose.weights[0] = -0.5;
+const morphSnapshot = exportGlb([{ name: 'packed morph', geometry: morphGeometry, morph: morphPose, matrix: new Float32Array([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]), material: { color: [0.5, 0.5, 0.5], metallic: 0, roughness: 0.7, emission: 0 } }]);
+const morphHeader = new DataView(morphSnapshot);
+const morphDocument = JSON.parse(new TextDecoder().decode(new Uint8Array(morphSnapshot, 20, morphHeader.getUint32(12, true))));
+assert.deepEqual(morphDocument.nodes[0].weights, [-0.5]);
+assert.ok(Number.isInteger(morphDocument.meshes[0].primitives[0].targets[0].POSITION));
assert.throws(() => new Renderer67({}, [], { environment: { pointLights: Array(9).fill({ position: [0, 1, 0] }) } }), /at most/, 'Packed renderer must validate light limits before requesting a GPU context.');
assert.ok(box().positions.length > 0);
const parts = createModel();
diff --git a/skills/build-67js-scene/references/scene-contract.md b/skills/build-67js-scene/references/scene-contract.md
index 258314bc..6dd82e36 100644
--- a/skills/build-67js-scene/references/scene-contract.md
+++ b/skills/build-67js-scene/references/scene-contract.md
@@ -97,7 +97,8 @@ Targets contain static relative Float32 XYZ deltas, not absolute vertices. At le
Change retained `part.morph.weights`, then call `renderer.updateParts()` to commit the pose.
Separate pose identities split batches; repeated parts can share static target geometry.
Morphs run before skinning and use standard materials. Read `docs/morph-targets.md` for numeric limits and memory costs.
-Do not silently export morphs through `exportGlb`; it currently rejects them. Check the decoder's capabilities before importing shape keys.
+Source `exportGlb(parts)` preserves morph target deltas and current node weights as a static GLB snapshot; it does not serialize animation clips.
+Skinning and textured materials still reject at export. Check the decoder's capabilities before importing shape keys.
The optional `{ shadows: false }` update option suits flat scenes without moving shadow casters.
`cameraView('front' | 'right' | 'top')` returns an orthographic camera with the correct up vector.
diff --git a/src/export.js b/src/export.js
index e659ec93..e7b3e849 100644
--- a/src/export.js
+++ b/src/export.js
@@ -1,12 +1,12 @@
+import { validateMorphGeometry } from './morph.js';
+
function paddedLength(length) {
return Math.ceil(length / 4) * 4;
}
export function exportGlb(parts) {
for (const part of parts) {
- if (part.morph || part.geometry.morphTargets !== undefined) {
- throw new RangeError('GLB export cannot preserve morph targets yet. Bake the pose or export through a tool that preserves the targets.');
- }
+ 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.');
}
@@ -52,10 +52,19 @@ export function exportGlb(parts) {
}
for (const part of parts) {
if (!geometries.has(part.geometry)) {
- geometries.set(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.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);
if (!materials.has(materialKey)) {
@@ -72,7 +81,9 @@ export function exportGlb(parts) {
meshes.set(meshKey, document.meshes.length);
document.meshes.push({ primitives: [{ ...geometry, material }] });
}
- document.nodes.push({ name: part.name, mesh: meshes.get(meshKey), matrix: Array.from(part.matrix) });
+ const node = { name: part.name, mesh: meshes.get(meshKey), matrix: Array.from(part.matrix) };
+ if (part.morph) node.weights = Array.from(part.morph.weights);
+ document.nodes.push(node);
}
document.buffers.push({ byteLength });
const json = new TextEncoder().encode(JSON.stringify(document));
diff --git a/tests/export.test.js b/tests/export.test.js
index fce008d8..fbbff8e8 100644
--- a/tests/export.test.js
+++ b/tests/export.test.js
@@ -3,6 +3,10 @@ import assert from 'node:assert/strict';
import { createModel } from '../src/model.js';
import { exportGlb } from '../src/export.js';
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
+import { box } from '../src/geometry.js';
+import { createMorphPose } from '../src/morph.js';
+import { mat4 } from 'gl-matrix';
+import { Vector3 } from 'three';
test('exported GLB loads with an independent glTF loader and preserves every part', async () => {
const parts = createModel();
@@ -31,8 +35,51 @@ test('GLB export rejects skinning instead of silently saving the undeformed bind
assert.throws(() => exportGlb([{ ...part, geometry: { ...part.geometry, skinIndices: new Uint16Array(4) } }]), /preserve skinning/);
});
-test('GLB export rejects morph targets rather than discarding expressions', () => {
+test('GLB export rejects malformed morph pairs rather than discarding expressions', () => {
const part = createModel()[0];
- assert.throws(() => exportGlb([{ ...part, morph: { weights: new Float32Array(1) } }]), /preserve morph targets/);
- assert.throws(() => exportGlb([{ ...part, geometry: { ...part.geometry, morphTargets: [] } }]), /preserve morph targets/);
+ assert.throws(() => exportGlb([{ ...part, morph: { weights: new Float32Array(1) } }]), /target array/);
+ assert.throws(() => exportGlb([{ ...part, geometry: { ...part.geometry, morphTargets: [] } }]), /require a morph pose/);
+});
+
+test('GLB morph snapshots retain relative channels, shared meshes and independent signed node weights', async () => {
+ const geometry = box();
+ const positions = new Float32Array(geometry.positions.length);
+ const normals = new Float32Array(geometry.normals.length);
+ for (let offset = 0; offset < positions.length; offset += 3) {
+ positions[offset] = 0.25;
+ positions[offset + 1] = 0.125;
+ normals[offset + 2] = 0.1;
+ }
+ geometry.morphTargets = [{ positions }, { normals }];
+ const first = createMorphPose(2);
+ const second = createMorphPose(2);
+ first.weights.set([1.5, -0.5]);
+ second.weights.set([-0.25, 0.75]);
+ const material = { color: [0.4, 0.5, 0.6], metallic: 0, roughness: 0.7, emission: 0 };
+ const parts = [first, second].map((morph, index) => ({ name: `instance ${index}`, geometry, material, morph, matrix: mat4.create() }));
+ const binary = exportGlb(parts);
+ const view = new DataView(binary);
+ const document = JSON.parse(new TextDecoder().decode(new Uint8Array(binary, 20, view.getUint32(12, true))));
+ assert.equal(document.meshes.length, 1);
+ assert.deepEqual(document.nodes.map(node => node.weights), [[1.5, -0.5], [-0.25, 0.75]]);
+ const targets = document.meshes[0].primitives[0].targets;
+ assert.deepEqual(Object.keys(targets[0]), ['POSITION']);
+ assert.deepEqual(Object.keys(targets[1]), ['NORMAL']);
+ assert.deepEqual(document.accessors[targets[0].POSITION].min, [0.25, 0.125, 0]);
+ const loaded = await new GLTFLoader().parseAsync(binary, '');
+ const meshes = [];
+ loaded.scene.traverse(node => { if (node.isMesh) meshes.push(node); });
+ assert.equal(meshes.length, 2);
+ assert.equal(meshes[0].geometry, meshes[1].geometry);
+ assert.deepEqual(meshes.map(mesh => mesh.morphTargetInfluences), [[1.5, -0.5], [-0.25, 0.75]]);
+ for (let instance = 0; instance < meshes.length; instance++) {
+ // GLTFLoader fills an omitted position channel with the base attribute.
+ // Isolate the declared position target when using its CPU vertex helper.
+ meshes[instance].morphTargetInfluences[1] = 0;
+ const point = meshes[instance].getVertexPosition(0, new Vector3());
+ assert.equal(point.x, geometry.positions[0] + parts[instance].morph.weights[0] * positions[0]);
+ assert.equal(point.y, geometry.positions[1] + parts[instance].morph.weights[0] * positions[1]);
+ }
+ first.weights[0] = NaN;
+ assert.throws(() => exportGlb(parts), /finite Float32/);
});