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.

feat(export): keep only LOD0..N in the three runtime target (#196)

Matt Kissingerf1a4c364a958
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 90ae212d..cc26d688 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -41,6 +41,11 @@ does not publish a package.
three runtime target leaves after batching each `repeatInstances` group. It is
informational and never changes the tier's status
([#200](https://github.com/instruktlabs/kiln/issues/200)).
+- The three runtime target takes `maxLod` (CLI `--max-lod N`): it keeps LOD0..LODN of each
+ `MSFT_lod` chain and removes the lower levels with what only they used, trims their
+ thresholds, leaves budget tiers above N out of the shipped declaration and records all
+ of it in the sidecar's `delivery.lod`. The default keeps every level
+ ([#196](https://github.com/instruktlabs/kiln/issues/196)).
## 1.4.0 (2026-10-23)
diff --git a/docs/delivery-contract.md b/docs/delivery-contract.md
index de75edb8..1dd72ce9 100644
--- a/docs/delivery-contract.md
+++ b/docs/delivery-contract.md
@@ -175,7 +175,8 @@ Consumer rules that follow from it:
under the appropriate authored parent. Your application chooses one active tier
using the retained `MSFT_screencoverage` policy or its own documented policy.
Do not show all levels together. A final impostor marker does not implement
- billboarding or distance-based switching.
+ billboarding or distance-based switching. A consumer that draws LOD0 only can export
+ with `--max-lod 0` so the lower levels are not shipped at all.
`src/__tests__/runtime-three-export.test.ts` qualifies static geometry, role data,
instancing, explicit lower-tier selection and a quantized skin through Three's
diff --git a/docs/export-profiles.md b/docs/export-profiles.md
index 46113b28..ce75e831 100644
--- a/docs/export-profiles.md
+++ b/docs/export-profiles.md
@@ -237,7 +237,18 @@ What it does, in order:
[KTX2 textures](#ktx2-textures).
Roles and kit extras, hidden collider nodes (`KHR_node_visibility`), anchors, ports and
-`MSFT_lod` chains are kept. The sidecar `delivery` block states what a consumer needs:
+`MSFT_lod` chains are kept.
+
+A loader that never selects a level still downloads every lower one. `maxLod: n` (CLI
+`--max-lod n`) keeps LOD0 to LODn of each chain in the default scene and removes the
+rest, with the meshes, materials and textures only they used; `0` keeps LOD0 alone and
+removes `MSFT_lod`. Thresholds in `MSFT_screencoverage` are cut to the kept levels. When a
+chain loses levels, budget tiers above `n` leave the shipped `kilnBudgetV1` declaration,
+since they would otherwise be measured against fewer levels; the sidecar lists them as
+`budgetTiersOmitted`. A dropped level that an animation targets is refused. Kiln still
+does not select a level at runtime.
+
+The sidecar `delivery` block states what a consumer needs:
| Field | Meaning |
| --- | --- |
@@ -249,6 +260,7 @@ Roles and kit extras, hidden collider nodes (`KHR_node_visibility`), anchors, po
| `customAttributes` | Each underscore attribute, its mesh count, `FLOAT`, not normalized |
| `instancing` | Each batch node, its mesh, count and instance names in order |
| `ktx2` | `encoded` or `skipped` with the texture count and reason; `encoder` (name, version, Basis WebAssembly hash and every setting) when the encoder declared it |
+| `lod` | With `maxLod` only: `{ maxLod, chains: [{ path, levels, dropped }], budgetTiersOmitted }`, where `levels` counts the kept levels and `dropped` names the removed ones |
| `preserved` | Counts of LOD chains, hidden nodes, colliders, anchors, ports and kit modules |
Quantization stores positions as normalized integers and moves the metre scale onto
diff --git a/skills/kiln-author-asset/references/export-profiles.md b/skills/kiln-author-asset/references/export-profiles.md
index cc7b67e6..d99d8fbb 100644
--- a/skills/kiln-author-asset/references/export-profiles.md
+++ b/skills/kiln-author-asset/references/export-profiles.md
@@ -57,7 +57,9 @@ the additional target changes geometry encoding and can change hierarchy.
Use this target with Meshopt decoding configured in the consumer, or add
`--compression none` for a loader without a Meshopt decoder: buffers stay plain while
-quantization and instancing remain. Preserve
+quantization and instancing remain. For a loader that never switches levels, add
+`--max-lod 0` (or a higher level) so lower `MSFT_lod` levels are not shipped; the
+sidecar's `delivery.lod` lists what was dropped. Preserve
loaded node transforms, skeletons and inverse bind matrices: they restore quantized
positions to the intended dimensions. A loader does not automatically implement
Kiln's LOD selection, collider behavior, anchors or kit snapping. Test those in the
diff --git a/src/__tests__/runtime-three-max-lod.test.ts b/src/__tests__/runtime-three-max-lod.test.ts
new file mode 100644
index 00000000..0d6cb426
--- /dev/null
+++ b/src/__tests__/runtime-three-max-lod.test.ts
@@ -0,0 +1,170 @@
+/**
+ * #196: `maxLod` on the three runtime target keeps LOD0..LODn of every `MSFT_lod` chain and
+ * drops the rest, so a loader that never selects a level does not download it. Thresholds are
+ * trimmed with the levels, budget tiers that no longer describe the file are left out of the
+ * shipped declaration, and the sidecar names what was dropped. The default is unchanged.
+ */
+import { beforeAll, describe, expect, test } from 'bun:test';
+import { createHash } from 'node:crypto';
+import { deliverThreeRuntimeGlb, exportAssetGlb } from '../asset-export';
+import type { AssetRecord } from '../assets';
+import { Document } from '@gltf-transform/core';
+import { createGltfIO, MSFT_LOD, MSFTLod } from '../gltf-io';
+import { renderGLBInProcess, inspectGlbIntegration } from '../render';
+
+const PROGRAM = `const meta={name:'Tiered Lamp'};
+function build(){
+ const root=createRoot('Root');
+ const m=gameMaterial('#777777');
+ const glow=gameMaterial('#ffcc66');
+ createPart('Base',boxGeo(1,0.2,1),m,{parent:root});
+ const tiers=['Lamp_LOD0','Lamp_LOD1','Lamp_LOD2'].map((name)=>{const g=new THREE.Group();g.name=name;root.add(g);return g;});
+ createPart('Hi',sphereGeo(0.5,24,16),m,{parent:tiers[0],position:[0,1,0]});
+ createPart('Mid',sphereGeo(0.5,10,8),m,{parent:tiers[1],position:[0,1,0]});
+ createPart('Card',planeGeo(1,1),glow,{parent:tiers[2],position:[0,1,0]});
+ defineLod(tiers,{screenCoverage:[0.4,0.1,0],impostor:true});
+ defineBudget({ triangles: { LOD0: 2000, LOD1: 400, LOD2: 40 }, draws: 3 });
+ return root;
+}`;
+
+let source: Uint8Array;
+beforeAll(async () => {
+ source = new Uint8Array((await renderGLBInProcess(PROGRAM)).glb);
+});
+
+const json = async (glb: Uint8Array) => (await createGltfIO().binaryToJSON(glb)).json;
+const sha = (bytes: Uint8Array) => `sha256:${createHash('sha256').update(bytes).digest('hex')}`;
+const plain = (options: Record<string, unknown> = {}) =>
+ deliverThreeRuntimeGlb(source, { compression: 'none', ...options });
+
+describe('three runtime maxLod', () => {
+ test('maxLod 1 keeps LOD0 and LOD1, trims thresholds and omits the LOD2 budget tier', async () => {
+ const full = await plain();
+ const trimmed = await plain({ maxLod: 1 });
+ expect(trimmed.glb.byteLength).toBeLessThan(full.glb.byteLength);
+ const names = (await json(trimmed.glb)).nodes!.map((node) => node.name);
+ expect(names).toContain('Lamp_LOD1');
+ expect(names).not.toContain('Lamp_LOD2');
+ expect(names).not.toContain('Card');
+ expect((await json(trimmed.glb)).materials!.map((m) => m.name)).toHaveLength(
+ (await json(full.glb)).materials!.length - 1,
+ );
+ const manifest = (await inspectGlbIntegration(trimmed.glb))!;
+ expect(manifest.levelsOfDetail).toHaveLength(1);
+ const chain = manifest.levelsOfDetail![0]!;
+ expect(chain.screenCoverage).toEqual([0.4, 0.1]);
+ expect(chain.levels.map((level) => level.name)).toEqual(['Lamp_LOD0', 'Lamp_LOD1']);
+ expect(manifest.budget!.tiers.map((tier) => tier.tier)).toEqual(['LOD0', 'LOD1']);
+ expect(trimmed.delivery.lod).toEqual({
+ maxLod: 1,
+ chains: [{ path: chain.path, levels: 2, dropped: ['Lamp_LOD2'] }],
+ budgetTiersOmitted: ['LOD2'],
+ });
+ });
+
+ test('maxLod 0 removes the chain and every lower level', async () => {
+ const trimmed = await plain({ maxLod: 0 });
+ const document = await json(trimmed.glb);
+ expect(document.extensionsUsed ?? []).not.toContain('MSFT_lod');
+ const names = document.nodes!.map((node) => node.name);
+ expect(names).not.toContain('Lamp_LOD1');
+ expect(names).not.toContain('Lamp_LOD2');
+ const lod0 = document.nodes!.find((node) => node.name === 'Lamp_LOD0')!;
+ expect(lod0.extensions?.['MSFT_lod']).toBeUndefined();
+ expect((lod0.extras as Record<string, unknown> | undefined)?.['MSFT_screencoverage']).toBe(
+ undefined,
+ );
+ const manifest = (await inspectGlbIntegration(trimmed.glb))!;
+ expect(manifest.levelsOfDetail ?? []).toEqual([]);
+ expect(manifest.budget!.tiers.map((tier) => tier.tier)).toEqual(['LOD0']);
+ expect(manifest.budget!.tiers[0]!.measured.triangles).toBe(
+ (await inspectGlbIntegration(source))!.budget!.tiers[0]!.measured.triangles,
+ );
+ expect(trimmed.delivery.lod).toMatchObject({
+ maxLod: 0,
+ chains: [{ levels: 1, dropped: ['Lamp_LOD1', 'Lamp_LOD2'] }],
+ budgetTiersOmitted: ['LOD1', 'LOD2'],
+ });
+ });
+
+ test('a maxLod at or above every chain changes nothing but the record', async () => {
+ const full = await plain();
+ const kept = await plain({ maxLod: 2 });
+ expect(sha(kept.glb)).toBe(sha(full.glb));
+ expect(kept.delivery.lod).toMatchObject({ maxLod: 2, budgetTiersOmitted: [] });
+ expect(kept.delivery.lod!.chains[0]).toMatchObject({ levels: 3, dropped: [] });
+ expect(full.delivery.lod).toBeUndefined();
+ });
+
+ test('a dropped level that an animation targets is refused', async () => {
+ const doc = new Document();
+ const buffer = doc.createBuffer();
+ const accessor = (array: Float32Array<ArrayBuffer>, type: 'SCALAR' | 'VEC3') =>
+ doc.createAccessor().setType(type).setArray(array).setBuffer(buffer);
+ const mesh = doc
+ .createMesh('Tri')
+ .addPrimitive(
+ doc
+ .createPrimitive()
+ .setAttribute(
+ 'POSITION',
+ accessor(new Float32Array([0, 0, 0, 1, 0, 0, 0, 1, 0]), 'VEC3'),
+ ),
+ );
+ const lod0 = doc.createNode('Prop_LOD0').setMesh(mesh);
+ const lod1 = doc.createNode('Prop_LOD1').setMesh(mesh);
+ lod0.setExtension(MSFT_LOD, doc.createExtension(MSFTLod).createLod().addLevel(lod1));
+ doc.createScene('Scene').addChild(lod0);
+ const sampler = doc
+ .createAnimationSampler()
+ .setInput(accessor(new Float32Array([0, 1]), 'SCALAR'))
+ .setOutput(accessor(new Float32Array([0, 0, 0, 0, 1, 0]), 'VEC3'));
+ doc
+ .createAnimation('Bob')
+ .addSampler(sampler)
+ .addChannel(
+ doc
+ .createAnimationChannel()
+ .setTargetNode(lod1)
+ .setTargetPath('translation')
+ .setSampler(sampler),
+ );
+ const bytes = await createGltfIO().writeBinary(doc);
+ await expect(deliverThreeRuntimeGlb(bytes, { maxLod: 0 })).rejects.toThrow(
+ 'which animation "Bob" targets',
+ );
+ expect((await deliverThreeRuntimeGlb(bytes, { maxLod: 1 })).delivery.lod!.chains).toEqual([
+ { path: '/Scene[0]/Prop_LOD0[0]', levels: 2, dropped: [] },
+ ]);
+ });
+
+ test('maxLod is a non-negative integer and needs the three target', async () => {
+ for (const bad of [-1, 1.5, Number.NaN, '1'])
+ await expect(plain({ maxLod: bad })).rejects.toThrow('maxLod');
+ const record: AssetRecord = {
+ manifest: {
+ version: 'kiln.asset.v1',
+ assetId: 'a_lod',
+ revisionId: 'r_lod',
+ name: 'Tiered Lamp',
+ tags: [],
+ createdAt: '2026-10-23T00:00:00.000Z',
+ editable: false,
+ files: {
+ 'asset.glb': { bytes: source.length, sha256: sha(source) as `sha256:${string}` },
+ },
+ },
+ files: { 'asset.glb': source },
+ };
+ await expect(exportAssetGlb(record, { profile: 'runtime', maxLod: 0 })).rejects.toThrow(
+ 'requires the three runtime target',
+ );
+ const output = await exportAssetGlb(record, {
+ profile: 'runtime',
+ target: 'three',
+ compression: 'none',
+ maxLod: 0,
+ });
+ expect(output.profile).toBe('runtime');
+ });
+});
diff --git a/src/asset-cli.test.ts b/src/asset-cli.test.ts
index d2d54ab2..9d55f35f 100644
--- a/src/asset-cli.test.ts
+++ b/src/asset-cli.test.ts
@@ -221,7 +221,31 @@ test('CLI saves, exports, imports, and restores a revision across independent st
).delivery;
expect(plainDelivery.compression).toEqual({ extension: 'none' });
expect(plainDelivery.extensionsRequired).not.toContain('EXT_meshopt_compression');
+ // #196: --max-lod passes through to the sidecar, which records the choice.
+ const lod0Run = run('first', [
+ 'export',
+ asset.assetId,
+ asset.revisionId,
+ '--out',
+ join(root, 'lod0.glb'),
+ '--profile',
+ 'runtime',
+ '--target',
+ 'three',
+ '--max-lod',
+ '0',
+ '--json',
+ ]);
+ expect(lod0Run.status, lod0Run.stderr).toBe(0);
+ expect(JSON.parse(lod0Run.stdout)).toMatchObject({ target: 'three', maxLod: 0 });
+ expect(
+ JSON.parse(await readFile(join(root, 'lod0.kiln-metadata.json'), 'utf8')).delivery.lod,
+ ).toMatchObject({ maxLod: 0, budgetTiersOmitted: [] });
for (const flags of [
+ ['--profile', 'runtime', '--max-lod', '0'],
+ ['--profile', 'runtime', '--target', 'three', '--max-lod', '-1'],
+ ['--profile', 'runtime', '--target', 'three', '--max-lod', '1.5'],
+ ['--profile', 'runtime', '--target', 'three', '--max-lod', 'all'],
['--profile', 'editable', '--target', 'three'],
['--profile', 'runtime', '--target', 'unity'],
['--profile', 'runtime', '--compression', 'none'],
diff --git a/src/asset-cli.ts b/src/asset-cli.ts
index a89f910d..f6eeb07a 100644
--- a/src/asset-cli.ts
+++ b/src/asset-cli.ts
@@ -55,6 +55,8 @@ ${SAVE_LINES}
instancing; sidecar states node scales; KTX2 skipped unless --ktx2
[--compression meshopt|none] with --target three: none writes plain buffers
for loaders without a Meshopt decoder (default meshopt)
+ [--max-lod N] with --target three: keep LOD0..LODN of each MSFT_lod chain and
+ drop the rest (0 keeps LOD0 only); the sidecar lists what was dropped
[--ktx2] with --target three: KTX2 through the optional [email protected] peer
(npm install [email protected]), ETC1S colour, UASTC data maps
[--textures manifest] runtime only: the sidecar names each image's exact bytes
@@ -99,6 +101,7 @@ export async function assetMain(argv: readonly string[]): Promise<number> {
'profile',
'target',
'compression',
+ 'max-lod',
'textures',
'port',
'render',
@@ -397,6 +400,12 @@ export async function assetMain(argv: readonly string[]): Promise<number> {
throw new Error('--compression must be meshopt or none');
if (compression !== undefined && target !== 'three')
throw new Error('--compression requires --target three');
+ const maxLodFlag = flags['max-lod'];
+ if (maxLodFlag !== undefined && !/^\d+$/.test(maxLodFlag))
+ throw new Error('--max-lod must be a non-negative integer, such as 0 for LOD0 only');
+ if (maxLodFlag !== undefined && target !== 'three')
+ throw new Error('--max-lod requires --target three');
+ const maxLod = maxLodFlag === undefined ? undefined : Number(maxLodFlag);
const textures = flags.textures;
if (textures !== undefined && textures !== 'manifest' && textures !== 'external')
throw new Error('Unknown --textures value; use manifest or external');
@@ -434,6 +443,7 @@ export async function assetMain(argv: readonly string[]): Promise<number> {
metadataFileName,
...(target ? { target } : {}),
...(compression ? { compression } : {}),
+ ...(maxLod !== undefined ? { maxLod } : {}),
...(textures ? { textures } : {}),
...(gltfLayout ? { gltfFileName: basename(destination) } : {}),
...(flags.ktx2 ? { ktx2Encoder: await createKtx2Encoder() } : {}),
@@ -504,6 +514,7 @@ export async function assetMain(argv: readonly string[]): Promise<number> {
profile,
...(target ? { target } : {}),
...(compression ? { compression } : {}),
+ ...(maxLod !== undefined ? { maxLod } : {}),
format,
...(ktx2Receipt ? { ktx2: ktx2Receipt } : {}),
...(format !== 'source'
diff --git a/src/asset-export.ts b/src/asset-export.ts
index 0b02ee13..d97b4619 100644
--- a/src/asset-export.ts
+++ b/src/asset-export.ts
@@ -247,6 +247,8 @@ export async function exportAssetGlb(
throw new Error('A runtime export target requires the runtime profile');
if (options.compression !== undefined && options.target !== 'three')
throw new Error('Runtime compression requires the three runtime target');
+ if (options.maxLod !== undefined && options.target !== 'three')
+ throw new Error('Runtime maxLod requires the three runtime target');
const textures = options.textures;
if (textures !== undefined && textures !== 'manifest' && textures !== 'external')
throw new Error('Unknown runtime texture option');
@@ -316,6 +318,7 @@ export async function exportAssetGlb(
{
...(options.ktx2Encoder ? { ktx2Encoder: options.ktx2Encoder } : {}),
...(options.compression ? { compression: options.compression } : {}),
+ ...(options.maxLod !== undefined ? { maxLod: options.maxLod } : {}),
},
textures === 'external' ? { gltfBasename: gltfName.slice(0, -'.gltf'.length) } : {},
);
diff --git a/src/gltf-io.ts b/src/gltf-io.ts
index a3d1f013..7390c5b9 100644
--- a/src/gltf-io.ts
+++ b/src/gltf-io.ts
@@ -53,6 +53,10 @@ export class Lod extends ExtensionProperty<ILod> {
public listLevels(): (Node | Material)[] {
return this.listRefs('levels');
}
+
+ public removeLevel(level: Node | Material): this {
+ return this.removeRef('levels', level);
+ }
}
/**
diff --git a/src/lod-export.ts b/src/lod-export.ts
index c130193c..96124f5d 100644
--- a/src/lod-export.ts
+++ b/src/lod-export.ts
@@ -126,3 +126,73 @@ export function summarizeLodChains(doc: Document): LevelOfDetailChainV1[] {
};
});
}
+
+/** What {@link trimLodChains} kept and dropped in one chain. */
+export interface TrimmedLodChain {
+ /** The chain's LOD0 path. */
+ path: string;
+ /** Levels left, LOD0 included. */
+ levels: number;
+ /** Names of the dropped levels, highest detail first. */
+ dropped: string[];
+}
+
+/**
+ * Keep LOD0..LOD`maxLod` of every chain in {@link listLodChainNodes} and delete the rest (#196).
+ * Thresholds are cut to the kept levels; a chain left with LOD0 alone loses `MSFT_lod` and its
+ * thresholds. Dropped subtrees are disposed; the caller prunes what they alone used. A dropped
+ * level that an animation targets is refused rather than leaving the clip a dangling channel.
+ */
+export function trimLodChains(doc: Document, maxLod: number): TrimmedLodChain[] {
+ const chains = listLodChainNodes(doc);
+ const doomed = new Set<GltfNode>();
+ for (const { levels } of chains)
+ for (const level of levels.slice(maxLod + 1))
+ level.traverse((node) => {
+ doomed.add(node);
+ });
+ for (const animation of doc.getRoot().listAnimations())
+ for (const channel of animation.listChannels()) {
+ const target = channel.getTargetNode();
+ if (target && doomed.has(target))
+ throw new Error(
+ `maxLod ${maxLod} would drop ${target.getName() || 'a node'}, which animation ${JSON.stringify(animation.getName())} targets; keep that level.`,
+ );
+ }
+ const trimmed = chains.map(({ levels, paths }) => {
+ const [base, ...lower] = levels as [GltfNode, ...GltfNode[]];
+ const dropped = lower.slice(maxLod);
+ if (dropped.length > 0) {
+ const lod = base.getExtension<Lod>(MSFT_LOD)!;
+ for (const level of dropped) lod.removeLevel(level);
+ const extras = { ...(base.getExtras() as Record<string, unknown>) };
+ const coverage = screenCoverageOf(base);
+ if (maxLod === 0) {
+ base.setExtension(MSFT_LOD, null);
+ lod.dispose();
+ delete extras[MSFT_SCREENCOVERAGE];
+ } else if (coverage) extras[MSFT_SCREENCOVERAGE] = coverage.slice(0, maxLod + 1);
+ base.setExtras(extras);
+ for (const level of dropped) {
+ const subtree: GltfNode[] = [];
+ level.traverse((node) => {
+ subtree.push(node);
+ });
+ for (const node of subtree.reverse()) node.dispose();
+ }
+ }
+ return {
+ path: paths[0]!,
+ levels: levels.length - dropped.length,
+ dropped: dropped.map((level) => level.getName()),
+ };
+ });
+ // With no chain left, the extension would still be declared as used.
+ const root = doc.getRoot();
+ if (!root.listNodes().some((node) => node.getExtension(MSFT_LOD)))
+ root
+ .listExtensionsUsed()
+ .find((extension) => extension.extensionName === MSFT_LOD)
+ ?.dispose();
+ return trimmed;
+}
diff --git a/src/runtime-three.ts b/src/runtime-three.ts
index 24217690..9488a9ba 100644
--- a/src/runtime-three.ts
+++ b/src/runtime-three.ts
@@ -30,7 +30,7 @@ import {
EXTMeshoptCompression,
KHRTextureBasisu,
} from '@gltf-transform/extensions';
-import { cloneDocument, dedup, quantize, reorder } from '@gltf-transform/functions';
+import { cloneDocument, dedup, prune, quantize, reorder } from '@gltf-transform/functions';
import type { Property } from '@gltf-transform/core';
import * as THREE from 'three';
import { KILN_SEMANTIC_ROLES, readSemanticMetadataV1FromExtras } from './contracts/semantic';
@@ -39,6 +39,8 @@ import { deliveryNodePaths } from './delivery-inspect';
import { KILN_REPEAT_INSTANCES_KEY } from './delivery';
import { collectGlbMetrics, isHiddenGltfNode } from './metrics';
import { isKtx2, sha256Hex } from './runtime-textures';
+import { trimLodChains, type TrimmedLodChain } from './lod-export';
+import { KILN_BUDGET_KEY } from './budget';
/** Bits per quantized attribute class; custom underscore attributes stay float32. */
export const RUNTIME_THREE_QUANTIZATION = Object.freeze({
@@ -102,6 +104,12 @@ export interface RuntimeThreeOptionsV1 {
* quantization, instancing and every preserved feature stay.
*/
compression?: RuntimeThreeCompression;
+ /**
+ * Keep LOD0..LOD`maxLod` of every `MSFT_lod` chain and drop the lower levels, for loaders
+ * that never select a level (`0` keeps LOD0 alone). Budget tiers above it are left out of
+ * the shipped declaration. Omitted keeps every level.
+ */
+ maxLod?: number;
}
export type RuntimeThreeCompression = 'meshopt' | 'none';
export interface RuntimeThreeNodeScaleV1 {
@@ -146,6 +154,13 @@ export interface RuntimeThreeDeliveryV1 {
/** The encoder's own identity, when it declared one. */
encoder?: RuntimeThreeKtx2EncoderIdentityV1;
};
+ /** Present when `maxLod` was given: what each chain kept and dropped. */
+ lod?: {
+ maxLod: number;
+ chains: TrimmedLodChain[];
+ /** Budget tiers above `maxLod`, removed from the shipped declaration, not judged. */
+ budgetTiersOmitted: string[];
+ };
preserved: {
lodChains: number;
hiddenNodes: number;
@@ -392,6 +407,51 @@ function decomposeDelta(before: number[], after: number[]) {
};
}
+/**
+ * Drop levels above `maxLod` (#196), then the meshes, materials and textures only they used.
+ * Budget tiers above `maxLod` no longer describe the file once a chain lost levels, so they
+ * leave the shipped declaration and are listed instead of being judged against fewer levels.
+ */
+async function trimLevels(doc: Document, maxLod: number) {
+ const chains = trimLodChains(doc, maxLod);
+ const budgetTiersOmitted: string[] = [];
+ if (chains.some((chain) => chain.dropped.length > 0)) {
+ await doc.transform(
+ prune({
+ // A pruned mesh leaves its primitives holding their accessors and material.
+ propertyTypes: [
+ PropertyType.MESH,
+ PropertyType.PRIMITIVE,
+ PropertyType.PRIMITIVE_TARGET,
+ PropertyType.ACCESSOR,
+ PropertyType.MATERIAL,
+ PropertyType.TEXTURE,
+ ],
+ keepAttributes: true,
+ keepIndices: true,
+ keepLeaves: true,
+ keepExtras: true,
+ keepSolidTextures: true,
+ }),
+ );
+ const scene = doc.getRoot().getDefaultScene() ?? doc.getRoot().listScenes()[0];
+ const extras = { ...((scene?.getExtras() ?? {}) as Record<string, unknown>) };
+ const budget = extras[KILN_BUDGET_KEY] as { triangles?: Record<string, number> } | undefined;
+ if (scene && budget?.triangles) {
+ const triangles = { ...budget.triangles };
+ for (const tier of Object.keys(triangles))
+ if (Number(tier.slice(3)) > maxLod) {
+ budgetTiersOmitted.push(tier);
+ delete triangles[tier];
+ }
+ if (Object.keys(triangles).length > 0) extras[KILN_BUDGET_KEY] = { ...budget, triangles };
+ else delete extras[KILN_BUDGET_KEY];
+ scene.setExtras(extras);
+ }
+ }
+ return { maxLod, chains, budgetTiersOmitted };
+}
+
/** What the derivation returns beside the GLB: facts and, on request, the `.gltf` layout. */
export interface RuntimeThreeResult {
glb: Uint8Array;
@@ -418,11 +478,15 @@ export async function deliverRuntimeThreeGlb(
const compression = options.compression ?? 'meshopt';
if (compression !== 'meshopt' && compression !== 'none')
throw new Error('Runtime three compression must be meshopt or none');
+ const { maxLod } = options;
+ if (maxLod !== undefined && !(Number.isSafeInteger(maxLod) && maxLod >= 0))
+ throw new Error('Runtime three maxLod must be a non-negative integer');
const io = createGltfIO().registerDependencies({
'meshopt.encoder': meshoptEncoder,
});
const doc = await io.readBinary(bytes);
doc.setLogger(new Logger(Logger.Verbosity.SILENT));
+ const lod = maxLod === undefined ? undefined : await trimLevels(doc, maxLod);
// Merge identical accessors so equal children are recognisable by content; names stay.
await doc.transform(dedup({ propertyTypes: [PropertyType.ACCESSOR], keepUniqueNames: true }));
const instanced = applyScopedInstancing(doc);
@@ -559,6 +623,7 @@ export async function deliverRuntimeThreeGlb(
})),
instancing: instanced.map(({ node, ...rest }) => ({ node: pathOf(node), ...rest })),
ktx2,
+ ...(lod ? { lod } : {}),
preserved: {
lodChains: all.filter((node) => node.getExtension(MSFT_LOD)).length,
hiddenNodes: all.filter((node) => isHiddenGltfNode(node)).length,