Skip to content

armgit / kiln

Public Imported from GitHub
0

Build and revise procedural 3D assets with your coding agent. Local MCP server, CLI and TypeScript engine with rendered review, editable source and GLB export.

Record batch membership and protect review-clip targets in --draws minimal (#347)

Matthew Kissinger61be20e4b040
diff --git a/CHANGELOG.md b/CHANGELOG.md
index f8335143..a95c8dc2 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,14 @@ does not publish a package.
## Unreleased
+- `--draws minimal` names each batch node after its first copy, `<copy>_Instances`, and
+ `drawReduction.instancing` records which node names went into each batch, in instance order. A
+ batched copy loses its mesh, and a mesh-less copy with no children or extensions is removed. Clips
+ kept only as the review copy (`scenes[].extras.kilnReviewClipsV1`) now protect the nodes their tracks
+ name, as native animations do. Such a file is not batched (`batchingSkipped: 'review clips'`), and a node a
+ track names is never merged, which also holds for `optimize: 'full'`. The `KILN_BAKE_INSTANCE` pass
+ skips these files too, so an instanced build of one now has its copies as separate nodes. Tests now
+ show the draw reduction keeping animated, LOD, hidden, semantic and relationship-target parts.
- A review shot no longer exports the same derivative GLB, or decodes the same frame, more than once.
Measured on the 2,635,224-triangle cathedral against a warm GPU service (two runs each):
- Shots that draw the same scene state share one derivative export, within a call and across calls on
diff --git a/docs/export-profiles.md b/docs/export-profiles.md
index 695050de..89a60188 100644
--- a/docs/export-profiles.md
+++ b/docs/export-profiles.md
@@ -211,17 +211,32 @@ saved revision does not change.
1. Every mesh used by two or more nodes becomes an `EXT_mesh_gpu_instancing` batch, within the
limits in [the runtime notes](runtime.md): one handedness per batch, no shear, and tangent-bearing
- copies batched by the rotation they share.
+ copies batched by the rotation they share. A batched copy loses its mesh. A mesh-less copy with
+ no children or extensions is removed, name and all; one with either stays as a named node with
+ no mesh. The batch node is named after its first copy, `<copy>_Instances`, with `_1`, `_2` and
+ so on when that name is taken.
+ - **Nothing is batched** when the file has animations, skins or review clips
+ (`scenes[].extras.kilnReviewClipsV1`), or when any node has extras (semantic metadata
+ included), `KHR_node_visibility`, an `MSFT_lod` chain or a `Joint_*` name.
+ - In that case `drawReduction.batchingSkipped` gives the reason, and only step 2 runs.
2. Parts whose mesh has a single user merge per material, vertex layout and tangent handedness,
within cubes `--draw-cell` metres wide (default 15), so a viewer can still cull a large asset by
- region. Blended and transmissive parts, and nodes a consumer reads by name (`Joint_*` pivots,
- semantic roles, extras, visibility, LOD), are never merged. A part keeps its node name; its
- geometry can move to another node of its cell.
+ region.
+ - **Never merged:** blended and transmissive parts, and the nodes a consumer reads by name.
+ Those are animation and review-clip targets, `Joint_*` pivots, nodes with extras, nodes a
+ semantic relationship names, and visibility and LOD nodes.
+ - A merged part keeps its node name, but its geometry can move to another node of its cell.
Unlike `optimize: 'full'`, it runs no `palette()`, which rewrites materials, and no `weld()`,
-which splits accessors that parts share. On a 16 MB cathedral, `weld()` alone added 10 MB. The
-sidecar's `drawReduction` reports draws before and after, batches, merges, and what stayed
-separate and why.
+which splits accessors that parts share. On a 16 MB cathedral, `weld()` alone added 10 MB.
+
+The sidecar's `drawReduction` reports:
+
+- draws before and after, batches and merges;
+- what stayed separate, and why;
+- `instancing`, one entry per batch: `{ node, mesh, count, instances }`. Here `instances[i]` is
+ the name of the node that instance `i` replaced, as in `--target three`'s
+ `delivery.instancing`. A consumer that found a copy by name finds it there.
Measured on copies of the 1,834-draw cathedral revision:
@@ -234,6 +249,32 @@ Measured on copies of the 1,834-draw cathedral revision:
Batches cost a renderer more per draw than plain meshes do, so measure frame time in the target
scene, not only the draw count.
+In three r186, every batch costs load time, about 17 ms per render pass, for two reasons:
+
+- **A shader per batch.** Below 1,024 copies, `nodes/accessors/Instance.js` stores a batch's
+ matrices in a uniform array whose shader name and length are its own.
+- **A node graph per batch.** `RenderObject` adds each `InstancedMesh`'s uuid to its cache key,
+ so three builds each batch's node graph separately.
+
+The cathedral above has 176 batches. In an unmodified r186 viewer:
+
+- WebGL2 compiled 203 programs and first drew at 33 s; the saved revision first drew at 4 s.
+- WebGPU built 399 shader modules and held the page for 3.9 s after its first frame.
+
+Two viewer changes remove most of that cost:
+
+- **Share shaders.** Report a uniform-buffer limit of zero:
+ `renderer.backend.capabilities.getUniformBufferLimit = () => 0` after `init()`. Every batch
+ then reads its matrices as instanced attributes, which are named by slot, so batches with the
+ same material share a shader. That gave 29 programs on WebGL2 and 55 modules on WebGPU. Only
+ skinning and `RangeNode` read the same limit, and a skeleton then reads its bones from a
+ texture.
+- **Build ahead.** Call `renderer.compileAsync(model, camera, scene)` before the model is first
+ drawn, on WebGPU too when it has many batches. `compileAsync` yields between objects.
+
+With both, WebGL2 first drew at 7.9 s. WebGPU had no task over 150 ms and first drew at 6.1 s,
+where the saved revision draws at 1.1 s.
+
## three.js runtime target
`--target three` (runtime profile only) derives a GLB for a three.js application:
diff --git a/docs/runtime.md b/docs/runtime.md
index a2d2105e..e70dcc6c 100644
--- a/docs/runtime.md
+++ b/docs/runtime.md
@@ -165,7 +165,7 @@ see the [migration notes](migration.md#changes-in-10).
| Environment variable | Supported values |
| --- | --- |
| `KILN_BAKE_OPTIMIZE` | `off` (default), `auto`, `palette` or `full`; any other value means `off`. `palette` merges flat-colour materials into one palette material and texture; `auto` does so only for an asset with at least four distinct materials. `full` also merges compatible primitives within rigid groups, preserving animation, joint, semantic, visibility and LOD boundaries |
-| `KILN_BAKE_INSTANCE` | `auto` (default), `off` or `on`; any other value means `auto`. `on` batches a mesh shared by five or more nodes with `EXT_mesh_gpu_instancing` and `auto` does so only for `role: 'fill'` assets; neither batches an animated or skinned asset, or one with `Joint_` pivots, LOD chains, or nodes that carry extras or visibility |
+| `KILN_BAKE_INSTANCE` | `auto` (default), `off` or `on`; any other value means `auto`. `on` batches a mesh shared by five or more nodes with `EXT_mesh_gpu_instancing` and `auto` does so only for `role: 'fill'` assets; neither batches an animated or skinned asset, one whose scene carries review clips (`kilnReviewClipsV1`), or one with `Joint_` pivots, LOD chains, or nodes that carry extras or visibility |
The MCP and CLI tools pin `optimize: 'off'` for every render, inspection and save, so `KILN_BAKE_OPTIMIZE` does not change a tool's GLB; they leave `instance` to the host, so `KILN_BAKE_INSTANCE` does. Library calls that omit `optimize` take the variable: `renderGLB` in process, `renderSceneToGLB` (including the review copies some tool views are rendered from), `renderCodeViewGrid` and `rasterizeComposedScene`. The library's own subprocess mode does not pass either variable to its worker. `node kiln.mjs asset ASSET_ID REVISION --rebuild --out rebuilt.glb` replays the `optimize` and `instance` the saved manifest recorded, whatever the variables say. Both variables are part of the local build-cache key.
diff --git a/src/__tests__/draw-reduction.test.ts b/src/__tests__/draw-reduction.test.ts
index de40d44f..dc4d9ea5 100644
--- a/src/__tests__/draw-reduction.test.ts
+++ b/src/__tests__/draw-reduction.test.ts
@@ -4,11 +4,13 @@
*/
import { describe, expect, it } from 'bun:test';
import { createHash } from 'node:crypto';
+import type { Document, Node } from '@gltf-transform/core';
+import { type InstancedMesh, KHRNodeVisibility, type Visibility } from '@gltf-transform/extensions';
import * as THREE from 'three';
import { exportAssetGlb } from '../asset-export';
import type { AssetRecord } from '../assets';
import { reduceDrawCalls } from '../draw-reduction';
-import { createGltfIO } from '../gltf-io';
+import { createGltfIO, type Lod, MSFT_LOD, MSFTLod } from '../gltf-io';
import { collectGlbMetrics } from '../metrics';
import {
boxGeo,
@@ -163,6 +165,235 @@ describe('reduceDrawCalls', () => {
.find((node) => node.getName() === 'Mesh_Door');
expect(door?.getMesh()).not.toBeNull();
});
+
+ it('names each batch and records which copies went into it, in instance order', async () => {
+ const { bytes } = await renderSceneToGLB(buildingScene(), { instance: 'off' });
+ const before = await createGltfIO().readBinary(bytes);
+ const at = new Map(
+ before
+ .getRoot()
+ .listNodes()
+ .map((node) => [node.getName(), node.getWorldTranslation()]),
+ );
+ // The legacy exporter names meshes and the community one does not; batch names hold either way.
+ const mesh =
+ before
+ .getRoot()
+ .listNodes()
+ .find((node) => node.getName() === 'Mesh_Pane0')
+ ?.getMesh()
+ ?.getName() ?? '';
+ const doc = await createGltfIO().readBinary(bytes);
+ const summary = await reduceDrawCalls(doc);
+
+ expect(summary.instancing).toEqual([
+ {
+ node: 'Mesh_Pane0_Instances',
+ mesh,
+ count: 2,
+ instances: ['Mesh_Pane0', 'Mesh_Pane1'],
+ },
+ {
+ node: 'Mesh_MirrorPane0_Instances',
+ mesh,
+ count: 2,
+ instances: ['Mesh_MirrorPane0', 'Mesh_MirrorPane1'],
+ },
+ ]);
+ for (const { node: name, instances } of summary.instancing) {
+ const node = doc
+ .getRoot()
+ .listNodes()
+ .find((candidate) => candidate.getName() === name);
+ const batch = node?.getExtension<InstancedMesh>('EXT_mesh_gpu_instancing');
+ if (!node || !batch) throw new Error(`no batch named ${name}`);
+ const world = new THREE.Matrix4().fromArray(node.getWorldMatrix());
+ const translations = batch.getAttribute('TRANSLATION')!;
+ instances.forEach((copy, i) => {
+ const placed = new THREE.Vector3(...translations.getElement(i, [])).applyMatrix4(world);
+ const expected = at.get(copy)!;
+ for (let k = 0; k < 3; k++) expect(placed.getComponent(k)).toBeCloseTo(expected[k]!, 5);
+ });
+ }
+ });
+});
+
+/**
+ * Four one-off stone parts that merge into one draw, and a repeated pane. `mark` makes the door a
+ * part something addresses; the door must then keep its own geometry where it was authored.
+ */
+async function reduceWithMarkedDoor(mark: (doc: Document, door: Node) => void) {
+ const root = createRoot('Probe');
+ const stone = gameMaterial(0x999999);
+ createPart('Wall', boxGeo(4, 3, 0.4), stone, { parent: root });
+ createPart('Pier', boxGeo(0.5, 3, 0.5), stone, { position: [3, 0, 0], parent: root });
+ createPart('Door', boxGeo(1, 2, 0.1), stone, { position: [1, 0, 1], parent: root });
+ createPart('Plinth', boxGeo(1, 0.5, 1), stone, { position: [5, 0, 1], parent: root });
+ const pane = createPart('Pane0', planeGeo(1, 2), gameMaterial(0x803030), {
+ position: [0, 1, 4],
+ parent: root,
+ });
+ createInstance('Pane1', pane, { position: [3, 1, 4], parent: root });
+ const { bytes } = await renderSceneToGLB(root, { instance: 'off' });
+ const doc = await createGltfIO().readBinary(bytes);
+ const find = (name: string) =>
+ doc
+ .getRoot()
+ .listNodes()
+ .find((node) => node.getName() === name);
+ const door = find('Mesh_Door')!;
+ const authored = Array.from(
+ door.getMesh()!.listPrimitives()[0]!.getAttribute('POSITION')!.getArray()!,
+ );
+ mark(doc, door);
+ const summary = await reduceDrawCalls(doc);
+ const kept = find('Mesh_Door');
+ const positions = kept?.getMesh()?.listPrimitives()[0]?.getAttribute('POSITION')?.getArray();
+ return {
+ doc,
+ summary,
+ find,
+ door: kept,
+ doorPositions: positions ? Array.from(positions) : undefined,
+ authored,
+ };
+}
+
+describe('--draws minimal keeps what a consumer addresses', () => {
+ it('merges an unmarked door with the other stone', async () => {
+ const { summary, door, find } = await reduceWithMarkedDoor(() => {});
+ expect(summary.merges).toBeGreaterThan(0);
+ expect(summary.batches).toBe(1);
+ expect(find('Mesh_Pane1')).toBeUndefined();
+ expect(door?.getMesh() ?? null).toBeNull();
+ });
+
+ it('keeps an animated part and its channel', async () => {
+ const { doc, summary, door, doorPositions, authored } = await reduceWithMarkedDoor(
+ (doc, door) => {
+ const buffer = doc.getRoot().listBuffers()[0]!;
+ const accessor = (type: 'SCALAR' | 'VEC3', values: number[]) =>
+ doc.createAccessor().setType(type).setArray(new Float32Array(values)).setBuffer(buffer);
+ const sampler = doc
+ .createAnimationSampler()
+ .setInput(accessor('SCALAR', [0, 1]))
+ .setOutput(accessor('VEC3', [1, 0, 1, 2, 0, 1]));
+ const channel = doc
+ .createAnimationChannel()
+ .setTargetNode(door)
+ .setTargetPath('translation')
+ .setSampler(sampler);
+ doc.createAnimation('Open').addSampler(sampler).addChannel(channel);
+ },
+ );
+ expect(summary.merges).toBeGreaterThan(0);
+ expect(summary.batchingSkipped).toBe('animations');
+ expect(doorPositions).toEqual(authored);
+ expect(doc.getRoot().listAnimations()[0]!.listChannels()[0]!.getTargetNode()).toBe(door!);
+ });
+
+ it('keeps a level-of-detail chain', async () => {
+ const { doc, summary, door, doorPositions, authored } = await reduceWithMarkedDoor(
+ (doc, door) => {
+ const level = doc.createNode('Mesh_Door_Lod1').setMesh(door.getMesh());
+ door.setExtension(MSFT_LOD, doc.createExtension(MSFTLod).createLod().addLevel(level));
+ },
+ );
+ expect(summary.merges).toBeGreaterThan(0);
+ expect(summary.batchingSkipped).toBe('levels of detail');
+ expect(doorPositions).toEqual(authored);
+ const levels = door!.getExtension<Lod>(MSFT_LOD)!.listLevels();
+ expect(levels.map((level) => level.getName())).toEqual(['Mesh_Door_Lod1']);
+ expect(doc.getRoot().listNodes()).toContain(levels[0] as Node);
+ });
+
+ it('keeps a hidden part', async () => {
+ const { summary, door, doorPositions, authored } = await reduceWithMarkedDoor((doc, door) => {
+ door.setExtension(
+ 'KHR_node_visibility',
+ doc.createExtension(KHRNodeVisibility).createVisibility().setVisible(false),
+ );
+ });
+ expect(summary.merges).toBeGreaterThan(0);
+ expect(summary.batchingSkipped).toBe('node extras or visibility');
+ expect(doorPositions).toEqual(authored);
+ expect(door!.getExtension<Visibility>('KHR_node_visibility')!.getVisible()).toBe(false);
+ });
+
+ it('keeps a part with semantic metadata, and a part a relationship names', async () => {
+ const semantic = { kilnSemantic: { version: 1, roles: ['interaction.door'] } };
+ const marked = await reduceWithMarkedDoor((_, door) => door.setExtras(semantic));
+ expect(marked.summary.merges).toBeGreaterThan(0);
+ expect(marked.summary.batchingSkipped).toBe('node extras or visibility');
+ expect(marked.doorPositions).toEqual(marked.authored);
+ expect(marked.door!.getExtras()).toEqual(semantic);
+
+ const named = await reduceWithMarkedDoor((doc) => {
+ const wall = doc
+ .getRoot()
+ .listNodes()
+ .find((node) => node.getName() === 'Mesh_Wall')!;
+ wall.setExtras({
+ kilnSemantic: {
+ version: 1,
+ relationships: [{ type: 'opens', targetType: 'node', target: 'Mesh_Door' }],
+ },
+ });
+ });
+ expect(named.summary.merges).toBeGreaterThan(0);
+ expect(named.doorPositions).toEqual(named.authored);
+ });
+
+ it('keeps every part a review clip animates', async () => {
+ const { doc, summary, find, doorPositions, authored } = await reduceWithMarkedDoor((doc) => {
+ const track = (name: string) => ({ name, times: [0, 1], values: [1, 0] });
+ doc
+ .getRoot()
+ .listScenes()[0]!
+ .setExtras({
+ kilnReviewClipsV1: {
+ version: 1,
+ clips: [
+ {
+ name: 'Fade',
+ duration: 1,
+ tracks: [track('Mesh_Door.material.opacity'), track('Mesh_Pane1.material.opacity')],
+ },
+ ],
+ },
+ });
+ });
+ expect(summary.merges).toBeGreaterThan(0);
+ expect(summary.batchingSkipped).toBe('review clips');
+ expect(doorPositions).toEqual(authored);
+ const pane = find('Mesh_Pane0')?.getMesh();
+ expect(pane).toBeDefined();
+ expect(find('Mesh_Pane1')?.getMesh()).toBe(pane!);
+ expect(Object.keys(doc.getRoot().listScenes()[0]!.getExtras())).toContain('kilnReviewClipsV1');
+ });
+
+ it('reads a review track name three cannot parse as the node it names', async () => {
+ const { summary, doorPositions, authored } = await reduceWithMarkedDoor((doc) => {
+ doc
+ .getRoot()
+ .listScenes()[0]!
+ .setExtras({
+ kilnReviewClipsV1: {
+ version: 1,
+ clips: [
+ {
+ name: 'Odd',
+ duration: 1,
+ tracks: [{ name: 'Mesh_Door', times: [0], values: [1] }],
+ },
+ ],
+ },
+ });
+ });
+ expect(summary.merges).toBeGreaterThan(0);
+ expect(summary.batchingSkipped).toBe('review clips');
+ expect(doorPositions).toEqual(authored);
+ });
});
describe('--draws minimal runtime export', () => {
diff --git a/src/draw-reduction.ts b/src/draw-reduction.ts
index b5901de0..90b1179e 100644
--- a/src/draw-reduction.ts
+++ b/src/draw-reduction.ts
@@ -43,6 +43,12 @@ export interface DrawReductionV1 {
instances: number;
/** Why no copy was batched, when something in the asset rules batching out. */
batchingSkipped?: string;
+ /**
+ * Each batch node, its mesh and the names of the nodes it replaced, in instance order: copy `i`
+ * is the batch's instance `i`. A batched copy loses its mesh, and one with no children or
+ * extensions is removed with its name; this is where its geometry went.
+ */
+ instancing: { node: string; mesh: string; count: number; instances: string[] }[];
merges: number;
cellSize: number;
/** Primitives the merge left alone, by reason. */
@@ -68,8 +74,25 @@ export async function reduceDrawCalls(
const drawsBefore = collectGlbMetrics(doc).drawCalls;
const batchingSkipped = instancingBlocker(doc);
- if (!batchingSkipped) await instanceByHandedness(doc, REPEAT_MIN);
+ const created = batchingSkipped ? [] : await instanceByHandedness(doc, REPEAT_MIN);
const { batches, instances } = countInstanceBatches(doc);
+ // `instance()` leaves batch nodes unnamed. Naming each after its first copy, uniquely, makes it
+ // addressable whether or not the exporter named the mesh.
+ const names = new Set(
+ doc
+ .getRoot()
+ .listNodes()
+ .map((node) => node.getName()),
+ );
+ const instancing = created.map(({ node, instances: copies }) => {
+ const mesh = node.getMesh()?.getName() ?? '';
+ const base = `${copies[0] || mesh || 'Mesh'}_Instances`;
+ let name = base;
+ for (let k = 1; names.has(name); k++) name = `${base}_${k}`;
+ names.add(name);
+ node.setName(name);
+ return { node: name, mesh, count: copies.length, instances: copies };
+ });
// Repeats are batches now. A copy left over shares its mesh with a batch, and baking it would
// duplicate geometry; mixed into a bucket it can also push the join past the vertex limit,
@@ -90,6 +113,7 @@ export async function reduceDrawCalls(
batches,
instances,
...(batchingSkipped ? { batchingSkipped } : {}),
+ instancing,
merges: merge.merges,
cellSize,
locked,
diff --git a/src/instance-handedness.ts b/src/instance-handedness.ts
index 4a58c42f..41f28703 100644
--- a/src/instance-handedness.ts
+++ b/src/instance-handedness.ts
@@ -17,7 +17,7 @@
* stretch they share, carried on the batch node, leaving only translation and uniform scale on the
* instances.
*/
-import type { Accessor, Document, Mesh, Node, mat4, vec3, vec4 } from '@gltf-transform/core';
+import type { Accessor, Document, Mesh, Node, Scene, mat4, vec3, vec4 } from '@gltf-transform/core';
import { instance } from '@gltf-transform/functions';
import type { InstancedMesh } from '@gltf-transform/extensions';
import * as THREE from 'three';
@@ -149,9 +149,13 @@ function carrySharedLinear(doc: Document, node: Node, batch: InstancedMesh, shar
* hands, straightens shear and rotates tangent-bearing copies. Stand-in meshes steer that grouping:
* mirrored nodes share one per mesh and become their own batch, tangent-bearing nodes share one per
* mesh and shared rotation, and a node no batch can draw faithfully gets its own and stays below
- * `min`. Every node and batch gets its real mesh back.
+ * `min`. Every node and batch gets its real mesh back. Returns each new batch node with the names
+ * of the nodes it replaced, in instance order.
*/
-export async function instanceByHandedness(doc: Document, min: number): Promise<void> {
+export async function instanceByHandedness(
+ doc: Document,
+ min: number,
+): Promise<{ node: Node; instances: string[] }[]> {
const root = doc.getRoot();
const originals = new Map<Mesh, Mesh>();
const standIn = (mesh: Mesh) => {
@@ -192,8 +196,34 @@ export async function instanceByHandedness(doc: Document, min: number): Promise<
}
}
+ // `instance()` orders a batch's copies as its scene traversal meets them and adds the batch to
+ // that scene, so the same traversal names them.
+ const users = new Map<Scene, Map<Mesh, string[]>>();
+ const existing = new Set<Node>();
+ for (const scene of root.listScenes()) {
+ const byMesh = new Map<Mesh, string[]>();
+ users.set(scene, byMesh);
+ scene.traverse((node) => {
+ const mesh = node.getMesh();
+ if (node.getExtension('EXT_mesh_gpu_instancing')) existing.add(node);
+ else if (mesh) {
+ const names = byMesh.get(mesh) ?? [];
+ names.push(node.getName());
+ byMesh.set(mesh, names);
+ }
+ });
+ }
+
await doc.transform(instance({ min }));
+ const created: { node: Node; instances: string[] }[] = [];
+ for (const [scene, byMesh] of users)
+ for (const node of scene.listChildren()) {
+ const mesh = node.getMesh();
+ if (!mesh || existing.has(node) || !node.getExtension('EXT_mesh_gpu_instancing')) continue;
+ created.push({ node, instances: byMesh.get(mesh) ?? [] });
+ }
+
const mirroredStandIns = new Set(mirrored.values());
for (const node of root.listNodes()) {
const mesh = node.getMesh();
@@ -209,6 +239,30 @@ export async function instanceByHandedness(doc: Document, min: number): Promise<
// A viewer without the extension would silently draw one copy per batch: make it refuse instead.
for (const extension of root.listExtensionsUsed())
if (extension.extensionName === 'EXT_mesh_gpu_instancing') extension.setRequired(true);
+ return created;
+}
+
+/** A three track's node name; a name three cannot parse protects itself whole. */
+function trackNodeName(name: string): string {
+ try {
+ return THREE.PropertyBinding.parseTrackName(name).nodeName || name;
+ } catch {
+ return name;
+ }
+}
+
+/** The node names a scene's `kilnReviewClipsV1` tracks animate, as three's track names state them. */
+export function reviewClipTargets(doc: Document): Set<string> {
+ const targets = new Set<string>();
+ for (const scene of doc.getRoot().listScenes()) {
+ const review = scene.getExtras().kilnReviewClipsV1 as { clips?: unknown } | undefined;
+ if (!Array.isArray(review?.clips)) continue;
+ for (const clip of review.clips as { tracks?: unknown }[])
+ if (Array.isArray(clip?.tracks))
+ for (const track of clip.tracks as { name?: unknown }[])
+ if (typeof track?.name === 'string') targets.add(trackNodeName(track.name));
+ }
+ return targets;
}
/** Why this document cannot be batched at all, or undefined when it can. */
@@ -216,6 +270,8 @@ export function instancingBlocker(doc: Document): string | undefined {
const root = doc.getRoot();
if (root.listAnimations().length > 0) return 'animations';
if (root.listSkins().length > 0) return 'skins';
+ // The review copy of clips glTF cannot state targets nodes by name, as animations do.
+ if (reviewClipTargets(doc).size > 0) return 'review clips';
const nodes = root.listNodes();
// Kiln City runtimes target pivots by name, and a batch drops per-node names.
if (nodes.some((node) => /^joint[_-]/i.test(node.getName()))) return 'joint pivots';
diff --git a/src/rigid-merge.ts b/src/rigid-merge.ts
index 3d7267e6..6819d912 100644
--- a/src/rigid-merge.ts
+++ b/src/rigid-merge.ts
@@ -7,7 +7,7 @@
* and joined into fewer draws. No node is removed, renamed or reparented; a node whose
* primitives all moved keeps its name with no mesh.
*
- * Boundaries: animation targets, skin joints, `Joint_*` pivots (`hasJointPivots`' rule), nodes
+ * Boundaries: animation targets (including nodes a scene's `kilnReviewClipsV1` tracks name), skin joints, `Joint_*` pivots (`hasJointPivots`' rule), nodes
* with any extras (a superset of Kiln semantic metadata), nodes a semantic relationship names
* (`targetType: 'node'`, resolved by name in `assembly.ts`), `KHR_node_visibility`, `MSFT_lod`,
* shared scene entry points, and names the caller keeps. A boundary's own primitives never move.
@@ -55,6 +55,7 @@ import { createTransform, dequantizePrimitive, joinPrimitives } from '@gltf-tran
import * as THREE from 'three';
import { KILN_SEMANTIC_EXTRAS_KEY, type SemanticRelationshipV1 } from './contracts/semantic';
import { type Lod, MSFT_LOD } from './gltf-io';
+import { reviewClipTargets } from './instance-handedness';
export type RigidBoundaryReason =
| 'animated'
@@ -163,6 +164,7 @@ export function findRigidBoundaries(
const target = channel.getTargetNode();
if (target) add(target, 'animated');
}
+ const reviewed = reviewClipTargets(doc);
for (const skin of root.listSkins())
for (const joint of skin.listJoints()) add(joint, 'skin-joint');
const targets = new Set<string>();
@@ -183,6 +185,7 @@ export function findRigidBoundaries(
// Scene roots can be shared; nodes otherwise have a single parent. Only
// merges wholly inside a shared subtree are safe in every scene using it.
if (sceneParents > 1) add(node, 'shared-scene');
+ if (reviewed.has(name)) add(node, 'animated');
if (JOINT_PIVOT.test(name)) add(node, 'joint-pivot');
if (hasKeys(node.getExtras())) add(node, 'extras');
if (targets.has(name)) add(node, 'relationship-target');