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.
JavaScript 3d3d-assets3d-modelingagent-skillsagent-toolsai-agentsasset-pipelinecligame-assetsglbgltfmcpmcp-servermodel-context-protocolprocedural-generationprocedural-modelingtext-to-3dthreejstypescript
feat(export): choose position quantization bits and report the grid step (#197)
Matt Kissingerd96724cafdd4
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex cc26d688..9d728c3f 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -46,6 +46,13 @@ does not publish a package.thresholds, leaves budget tiers above N out of the shipped declaration and records allof it in the sidecar's `delivery.lod`. The default keeps every level([#196](https://github.com/instruktlabs/kiln/issues/196)).+- The three runtime target takes `positionBits` (CLI `--position-bits 8..16|float`) for+ position quantization; other attribute classes are unchanged and the default stays 14+ bits. The sidecar's `delivery.quantization` adds `positionSteps` (the grid step in metres+ per mesh node) and `maxPositionStep`, and `bits.position` is `'float32'` for float+ positions. With float positions, `KHR_mesh_quantization` is still declared for the+ quantized normals and texture coordinates+ ([#197](https://github.com/instruktlabs/kiln/issues/197)).## 1.4.0 (2026-10-23)diff --git a/docs/export-profiles.md b/docs/export-profiles.mdindex ce75e831..0a22a435 100644--- a/docs/export-profiles.md+++ b/docs/export-profiles.md@@ -227,6 +227,13 @@ What it does, in order:keeps its authored transform (its scale is the collider size).3. Vertices are reordered for compression, then quantized with `KHR_mesh_quantization`per mesh: position 14 bits, normal 10, texcoord 12, colour 8, weights 8.+ Position bits divide each mesh's largest half-extent into `2^(bits-1) - 1` steps, so+ 14 bits on a 10 m mesh is a grid of about 0.61 mm: enough to close a modelled seam or+ move a measured clearance. `positionBits` (CLI `--position-bits`) takes 8 to 16, or+ `float` to keep positions as 32-bit floats while the other classes stay quantized.+ The sidecar reports the step in metres for each mesh node (`positionSteps`) and the+ largest (`maxPositionStep`); a vertex moves by at most half its step. Check it against+ the smallest gap or clearance that matters before shipping.Underscore attributes such as `_EDGE` and `_CAVITY` are **not** quantized and stayFLOAT. Buffers are written with `EXT_meshopt_compression` (required) unless thecaller passes `compression: 'none'` (CLI `--compression none`): then buffers stay plain,@@ -254,7 +261,7 @@ The sidecar `delivery` block states what a consumer needs:| --- | --- || `extensionsUsed`, `extensionsRequired` | The derived GLB's extension sets || `compression` | `{ extension: 'EXT_meshopt_compression', method: 'quantize' }`, or `{ extension: 'none' }` |-| `quantization` | Bits per attribute class; `customAttributes: 'float32'` |+| `quantization` | Bits per attribute class (`position` is `'float32'` when unquantized); `customAttributes: 'float32'`; `positionSteps: [{ node, mesh, step }]` in metres (skinned meshes in mesh units) and `maxPositionStep` || `nodeScale` | Every node whose matrix now carries a dequantization `{ scale, offset }`, its `localScale`, and whether the mesh moved to a child (`meshMovedToChild`, `authoredNode`) || `colliderProxies` | Collider node and proxy child paths || `customAttributes` | Each underscore attribute, its mesh count, `FLOAT`, not normalized |diff --git a/skills/kiln-author-asset/references/export-profiles.md b/skills/kiln-author-asset/references/export-profiles.mdindex d99d8fbb..770634d0 100644--- a/skills/kiln-author-asset/references/export-profiles.md+++ b/skills/kiln-author-asset/references/export-profiles.md@@ -59,7 +59,10 @@ Use this target with Meshopt decoding configured in the consumer, or add`--compression none` for a loader without a Meshopt decoder: buffers stay plain whilequantization 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+sidecar's `delivery.lod` lists what was dropped. Positions are quantized to 14 bits per+mesh by default; read `delivery.quantization.maxPositionStep` (metres) and, when it+approaches a seam or clearance that matters, re-export with `--position-bits 16` or+`--position-bits float` instead of reshaping the asset. Preserveloaded node transforms, skeletons and inverse bind matrices: they restore quantizedpositions to the intended dimensions. A loader does not automatically implementKiln's LOD selection, collider behavior, anchors or kit snapping. Test those in thediff --git a/src/__tests__/runtime-three-position-bits.test.ts b/src/__tests__/runtime-three-position-bits.test.tsnew file mode 100644index 00000000..eed5c90f--- /dev/null+++ b/src/__tests__/runtime-three-position-bits.test.ts@@ -0,0 +1,131 @@+/**+ * #197: the three runtime target quantizes positions to 14 bits per mesh by default, which on+ * a 10 m mesh is a grid of about 0.61 mm. `positionBits` chooses 8 to 16 bits or `float`, and+ * the sidecar reports the resulting grid step in metres for every quantized mesh node and the+ * largest one, so the effect is visible before shipping. The default bytes are unchanged.+ */+import { beforeAll, describe, expect, test } from 'bun:test';+import { createHash } from 'node:crypto';+import type { Document as GltfDocument, Node } from '@gltf-transform/core';+import { deliverThreeRuntimeGlb, exportAssetGlb } from '../asset-export';+import type { AssetRecord } from '../assets';+import { createGltfIO } from '../gltf-io';+import { validateFinalGlbBytes } from '../qa/gltf';+import { renderGLBInProcess } from '../render';+import * as THREE from 'three';++const PROGRAM = `const meta={name:'Long Hull'};+function build(){+ const root=createRoot('Root');+ const m=gameMaterial('#777777');+ createPart('Hull',boxGeo(10,1,1),m,{parent:root,position:[0,0.5,0]});+ const nested=new THREE.Group(); nested.name='Doubled'; nested.scale.set(2,2,2); root.add(nested);+ createPart('Fin',boxGeo(1,1,0.1),m,{parent:nested,position:[0,2,0]});+ return root;+}`;++let source: Uint8Array;+beforeAll(async () => {+ source = new Uint8Array((await renderGLBInProcess(PROGRAM)).glb);+});++const sha = (bytes: Uint8Array) => `sha256:${createHash('sha256').update(bytes).digest('hex')}`;+const derive = (options: Record<string, unknown> = {}) =>+ deliverThreeRuntimeGlb(source, { compression: 'none', ...options });+const read = async (glb: Uint8Array) => createGltfIO().readBinary(glb);++/** The part node by name: both exporters name it, while only one names its mesh. */+const partNode = (doc: GltfDocument, name: string): Node =>+ doc+ .getRoot()+ .listNodes()+ .find((candidate: Node) => candidate.getName() === name && candidate.getMesh())!;+/** World-space positions of a part, decoded the way a loader decodes them. */+function worldPositions(doc: GltfDocument, part: string): THREE.Vector3[] {+ const node = partNode(doc, part);+ const matrix = new THREE.Matrix4().fromArray(node.getWorldMatrix());+ const position = node.getMesh()!.listPrimitives()[0]!.getAttribute('POSITION')!;+ return Array.from({ length: position.getCount() }, (_, i) =>+ new THREE.Vector3().fromArray(position.getElement(i, [])).applyMatrix4(matrix),+ );+}+/** The export reorders vertices, so each one is matched to its nearest authored vertex. */+const largestError = (actual: THREE.Vector3[], expected: THREE.Vector3[]) =>+ Math.max(...actual.map((point) => Math.min(...expected.map((other) => point.distanceTo(other)))));++describe('three runtime positionBits', () => {+ test('the default reports a 14-bit grid step per node and the largest one', async () => {+ const { delivery } = await derive();+ expect(delivery.quantization.bits.position).toBe(14);+ const steps = Object.fromEntries(+ delivery.quantization.positionSteps.map(({ node, step }) => [+ node+ .split('/')+ .pop()!+ .replace(/\[\d+\]$/, ''),+ step,+ ]),+ );+ // Half-extent over 2^13 - 1 levels, times the node's world scale.+ expect(steps['Mesh_Hull']).toBeCloseTo(5 / 8191, 12);+ expect(steps['Mesh_Fin']).toBeCloseTo((0.5 * 2) / 8191, 12);+ expect(delivery.quantization.maxPositionStep).toBeCloseTo(5 / 8191, 12);+ });++ test('16 bits shrinks the step and the measured error stays within half of it', async () => {+ const authored = worldPositions(await read(source), 'Mesh_Hull');+ const fine = await derive({ positionBits: 16 });+ expect(fine.delivery.quantization.bits.position).toBe(16);+ expect(fine.delivery.quantization.maxPositionStep).toBeCloseTo(5 / 32767, 12);+ const fineError = largestError(worldPositions(await read(fine.glb), 'Mesh_Hull'), authored);+ expect(fineError).toBeLessThanOrEqual(fine.delivery.quantization.maxPositionStep / 2 + 1e-9);+ const coarse = await derive();+ const coarseError = largestError(worldPositions(await read(coarse.glb), 'Mesh_Hull'), authored);+ expect(fineError).toBeLessThan(coarseError);+ });++ test('float leaves positions unquantized and moves no node scale', async () => {+ const authored = worldPositions(await read(source), 'Mesh_Hull');+ const exact = await derive({ positionBits: 'float' });+ const { quantization, nodeScale } = exact.delivery;+ expect(quantization.bits.position).toBe('float32');+ expect(quantization.positionSteps).toEqual([]);+ expect(quantization.maxPositionStep).toBe(0);+ expect(nodeScale).toEqual([]);+ const doc = await read(exact.glb);+ const accessor = partNode(doc, 'Mesh_Hull')+ .getMesh()!+ .listPrimitives()[0]!+ .getAttribute('POSITION')!;+ expect(accessor.getComponentType()).toBe(5126);+ expect(largestError(worldPositions(doc, 'Mesh_Hull'), authored)).toBe(0);+ // Normals and texture coordinates are still quantized, so the extension stays required+ // and the file is valid glTF.+ expect(exact.delivery.extensionsRequired).toContain('KHR_mesh_quantization');+ expect((await validateFinalGlbBytes(exact.glb)).issues.numErrors).toBe(0);+ });++ test('the default bytes do not change, and positionBits is validated', async () => {+ expect(sha((await derive({ positionBits: 14 })).glb)).toBe(sha((await derive()).glb));+ for (const bad of [7, 17, 12.5, 'half', Number.NaN])+ await expect(derive({ positionBits: bad })).rejects.toThrow('positionBits');+ const record: AssetRecord = {+ manifest: {+ version: 'kiln.asset.v1',+ assetId: 'a_bits',+ revisionId: 'r_bits',+ name: 'Long Hull',+ 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', positionBits: 'float' }),+ ).rejects.toThrow('requires the three runtime target');+ });+});diff --git a/src/asset-cli.test.ts b/src/asset-cli.test.tsindex 9d55f35f..25158833 100644--- a/src/asset-cli.test.ts+++ b/src/asset-cli.test.ts@@ -241,7 +241,32 @@ test('CLI saves, exports, imports, and restores a revision across independent stexpect(JSON.parse(await readFile(join(root, 'lod0.kiln-metadata.json'), 'utf8')).delivery.lod,).toMatchObject({ maxLod: 0, budgetTiersOmitted: [] });+ // #197: --position-bits reaches the sidecar, which reports the grid step it produced.+ const floatRun = run('first', [+ 'export',+ asset.assetId,+ asset.revisionId,+ '--out',+ join(root, 'float.glb'),+ '--profile',+ 'runtime',+ '--target',+ 'three',+ '--position-bits',+ 'float',+ '--json',+ ]);+ expect(floatRun.status, floatRun.stderr).toBe(0);+ expect(JSON.parse(floatRun.stdout)).toMatchObject({ target: 'three', positionBits: 'float' });+ expect(+ JSON.parse(await readFile(join(root, 'float.kiln-metadata.json'), 'utf8')).delivery+ .quantization,+ ).toMatchObject({ bits: { position: 'float32' }, maxPositionStep: 0 });for (const flags of [+ ['--profile', 'runtime', '--position-bits', '16'],+ ['--profile', 'runtime', '--target', 'three', '--position-bits', '7'],+ ['--profile', 'runtime', '--target', 'three', '--position-bits', '17'],+ ['--profile', 'runtime', '--target', 'three', '--position-bits', 'half'],['--profile', 'runtime', '--max-lod', '0'],['--profile', 'runtime', '--target', 'three', '--max-lod', '-1'],['--profile', 'runtime', '--target', 'three', '--max-lod', '1.5'],diff --git a/src/asset-cli.ts b/src/asset-cli.tsindex f6eeb07a..10a6fa1a 100644--- a/src/asset-cli.ts+++ b/src/asset-cli.ts@@ -57,6 +57,8 @@ ${SAVE_LINES}for loaders without a Meshopt decoder (default meshopt)[--max-lod N] with --target three: keep LOD0..LODN of each MSFT_lod chain anddrop the rest (0 keeps LOD0 only); the sidecar lists what was dropped+ [--position-bits 8..16|float] with --target three: position quantization bits+ (default 14) or float positions; the sidecar reports the grid step[--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@@ -102,6 +104,7 @@ export async function assetMain(argv: readonly string[]): Promise<number> {'target','compression','max-lod',+ 'position-bits','textures','port','render',@@ -406,6 +409,17 @@ export async function assetMain(argv: readonly string[]): Promise<number> {if (maxLodFlag !== undefined && target !== 'three')throw new Error('--max-lod requires --target three');const maxLod = maxLodFlag === undefined ? undefined : Number(maxLodFlag);+ const bitsFlag = flags['position-bits'];+ if (+ bitsFlag !== undefined &&+ bitsFlag !== 'float' &&+ !(/^\d+$/.test(bitsFlag) && Number(bitsFlag) >= 8 && Number(bitsFlag) <= 16)+ )+ throw new Error('--position-bits must be an integer from 8 to 16, or float');+ if (bitsFlag !== undefined && target !== 'three')+ throw new Error('--position-bits requires --target three');+ const positionBits =+ bitsFlag === undefined || bitsFlag === 'float' ? bitsFlag : Number(bitsFlag);const textures = flags.textures;if (textures !== undefined && textures !== 'manifest' && textures !== 'external')throw new Error('Unknown --textures value; use manifest or external');@@ -444,6 +458,7 @@ export async function assetMain(argv: readonly string[]): Promise<number> {...(target ? { target } : {}),...(compression ? { compression } : {}),...(maxLod !== undefined ? { maxLod } : {}),+ ...(positionBits !== undefined ? { positionBits } : {}),...(textures ? { textures } : {}),...(gltfLayout ? { gltfFileName: basename(destination) } : {}),...(flags.ktx2 ? { ktx2Encoder: await createKtx2Encoder() } : {}),@@ -515,6 +530,7 @@ export async function assetMain(argv: readonly string[]): Promise<number> {...(target ? { target } : {}),...(compression ? { compression } : {}),...(maxLod !== undefined ? { maxLod } : {}),+ ...(positionBits !== undefined ? { positionBits } : {}),format,...(ktx2Receipt ? { ktx2: ktx2Receipt } : {}),...(format !== 'source'diff --git a/src/asset-export-textures.test.ts b/src/asset-export-textures.test.tsindex 00ed06b1..414064fc 100644--- a/src/asset-export-textures.test.ts+++ b/src/asset-export-textures.test.ts@@ -78,6 +78,9 @@ test('without a texture option, runtime and three exports keep their pre-manifesconst three = await exportAssetGlb(record, { profile: 'runtime', target: 'three' });if (plain.profile !== 'runtime' || three.profile !== 'runtime') throw new Error('runtime');// Recorded on main before the manifest existed (2026-10-22): the default stays byte-identical.+ // The three pair was re-recorded for #197 (2026-10-23): its sidecar gained the position grid+ // steps, and the GLB carries the sidecar's hash. The derived geometry bytes were compared+ // before and after and are unchanged.expect({plainGlb: sha(plain.glb),plainMetadata: sha(plain.metadata.bytes),@@ -86,8 +89,8 @@ test('without a texture option, runtime and three exports keep their pre-manifes}).toEqual({plainGlb: 'sha256:975e9ee4580d90ea61948ee28da42494c78b89e61ced4c79c6ebc4f4fea961e3',plainMetadata: 'sha256:cb34dde89a001478c04fa165c2eb64197b9cd490de2f50266425b9dc8cd1a44b',- threeGlb: 'sha256:159cf047413a6501ed0e4dd75e418bc78c961b6022ef38ccb8ac2e8381fde09f',- threeMetadata: 'sha256:9f8a384e00f85511c3a7f7ce70951943722cf35aa96e2b9c9854a32975233385',+ threeGlb: 'sha256:90ecf54d5ae512d8f37624e7f9d4794995b551f5d402c3071bc183ae352339e9',+ threeMetadata: 'sha256:1cfd246cb94b4257acb8a404cdf21de622fcf3258a9a75e37c00bda142187213',});});diff --git a/src/asset-export.ts b/src/asset-export.tsindex d97b4619..0dfcfbca 100644--- a/src/asset-export.ts+++ b/src/asset-export.ts@@ -249,6 +249,8 @@ export async function exportAssetGlb(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');+ if (options.positionBits !== undefined && options.target !== 'three')+ throw new Error('Runtime positionBits requires the three runtime target');const textures = options.textures;if (textures !== undefined && textures !== 'manifest' && textures !== 'external')throw new Error('Unknown runtime texture option');@@ -319,6 +321,7 @@ export async function exportAssetGlb(...(options.ktx2Encoder ? { ktx2Encoder: options.ktx2Encoder } : {}),...(options.compression ? { compression: options.compression } : {}),...(options.maxLod !== undefined ? { maxLod: options.maxLod } : {}),+ ...(options.positionBits !== undefined ? { positionBits: options.positionBits } : {}),},textures === 'external' ? { gltfBasename: gltfName.slice(0, -'.gltf'.length) } : {},);diff --git a/src/runtime-three.ts b/src/runtime-three.tsindex 9488a9ba..0923212e 100644--- a/src/runtime-three.ts+++ b/src/runtime-three.ts@@ -17,6 +17,7 @@* rather than re-parenting bare geometry.*/import {+ Accessor,type Document,Format,Logger,@@ -27,14 +28,16 @@ import {} from '@gltf-transform/core';import {EXTMeshGPUInstancing,+ type InstancedMesh,EXTMeshoptCompression,+ KHRMeshQuantization,KHRTextureBasisu,} from '@gltf-transform/extensions';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';-import { createGltfIO, MSFT_LOD } from './gltf-io';+import { createGltfIO, type Lod, MSFT_LOD } from './gltf-io';import { deliveryNodePaths } from './delivery-inspect';import { KILN_REPEAT_INSTANCES_KEY } from './delivery';import { collectGlbMetrics, isHiddenGltfNode } from './metrics';@@ -53,6 +56,9 @@ export const RUNTIME_THREE_QUANTIZATION = Object.freeze({});const QUANTIZED_SEMANTICS =/^(POSITION|NORMAL|TANGENT|TEXCOORD_\d+|COLOR_\d+|JOINTS_\d+|WEIGHTS_\d+)$/;+/** The same set without POSITION, for `positionBits: 'float'`. */+const QUANTIZED_SEMANTICS_EXCEPT_POSITION =+ /^(NORMAL|TANGENT|TEXCOORD_\d+|COLOR_\d+|JOINTS_\d+|WEIGHTS_\d+)$/;/** The material slot an image serves; `other` covers extension textures. */export type RuntimeThreeKtx2SlotV1 =@@ -110,6 +116,11 @@ export interface RuntimeThreeOptionsV1 {* the shipped declaration. Omitted keeps every level.*/maxLod?: number;+ /**+ * Position quantization: 8 to 16 bits per mesh (default 14), or `float` to keep positions+ * as 32-bit floats. Other attribute classes are unchanged.+ */+ positionBits?: number | 'float';}export type RuntimeThreeCompression = 'meshopt' | 'none';export interface RuntimeThreeNodeScaleV1 {@@ -133,9 +144,25 @@ export interface RuntimeThreeDeliveryV1 {quantization: {extension: 'KHR_mesh_quantization';volume: 'mesh';- bits: { position: number; normal: number; texcoord: number; color: number; weight: number };+ /** `position` is `float32` when `positionBits: 'float'` left positions unquantized. */+ bits: {+ position: number | 'float32';+ normal: number;+ texcoord: number;+ color: number;+ weight: number;+ };/** Underscore attributes are never quantized and stay FLOAT, unnormalized. */customAttributes: 'float32';+ /**+ * The quantized position grid step in metres for each mesh node: the mesh's half-extent+ * over `2^(bits-1) - 1` levels, times the node's world scale and largest instance scale.+ * The rounding error of a vertex is at most half its step. Skinned meshes report mesh+ * units. Empty when positions stay float.+ */+ positionSteps: { node: string; mesh: string; step: number }[];+ /** The largest of `positionSteps`, or 0. */+ maxPositionStep: number;};/*** Every node whose local matrix carries a quantization transform. Positions in its mesh are@@ -407,6 +434,104 @@ function decomposeDelta(before: number[], after: number[]) {};}+/** Whether any primitive or morph target stores data only `KHR_mesh_quantization` permits. */+function hasQuantizedVertexData(doc: Document): boolean {+ const quantized = (semantic: string, accessor: Accessor): boolean => {+ if (accessor.getComponentSize() >= 4) return false;+ if (semantic === 'POSITION' || semantic === 'NORMAL' || semantic === 'TANGENT') return true;+ if (!semantic.startsWith('TEXCOORD_')) return false;+ // Normalized unsigned bytes and shorts are core glTF texture coordinates.+ const type = accessor.getComponentType();+ return !(+ accessor.getNormalized() &&+ (type === Accessor.ComponentType.UNSIGNED_BYTE ||+ type === Accessor.ComponentType.UNSIGNED_SHORT)+ );+ };+ return doc+ .getRoot()+ .listMeshes()+ .flatMap((mesh) => mesh.listPrimitives())+ .flatMap((primitive) => [primitive, ...primitive.listTargets()])+ .some((target) =>+ target+ .listSemantics()+ .some((semantic) => quantized(semantic, target.getAttribute(semantic)!)),+ );+}++/**+ * The position grid step of every mesh node at `bits` (#197), before quantization. The+ * quantizer scales each mesh by the largest half-extent of its position volume (morph+ * deltas included, as the pinned `quantize` computes it) and stores `bits - 1` magnitude+ * bits, so one step is that half-extent over `2^(bits-1) - 1`. World scale comes from the+ * node's ancestors; an off-scene LOD level takes its LOD0's parent, where a loader puts it.+ */+function positionGridSteps(+ doc: Document,+ bits: number,+): { node: Node; mesh: string; step: number }[] {+ const levels = 2 ** (bits - 1) - 1;+ const lodBase = new Map<Node, Node>();+ for (const node of doc.getRoot().listNodes())+ for (const level of node.getExtension<Lod>(MSFT_LOD)?.listLevels() ?? [])+ if (level.propertyType === PropertyType.NODE) lodBase.set(level as Node, node);+ const world = (node: Node): THREE.Matrix4 => {+ const matrix = new THREE.Matrix4().fromArray(node.getWorldMatrix());+ let top = node;+ while (top.getParentNode()) top = top.getParentNode()!;+ const placed = lodBase.get(top)?.getParentNode();+ return placed+ ? new THREE.Matrix4().fromArray(placed.getWorldMatrix()).multiply(matrix)+ : matrix;+ };+ const halfExtent = (mesh: Mesh): number => {+ const min = [Infinity, Infinity, Infinity];+ const max = [-Infinity, -Infinity, -Infinity];+ const widen = (values: number[], doubleFromZero: boolean) => {+ for (let axis = 0; axis < 3; axis++) {+ const value = values[axis]!;+ const candidates = doubleFromZero ? [value, value * 2, 0] : [value];+ min[axis] = Math.min(min[axis]!, ...candidates);+ max[axis] = Math.max(max[axis]!, ...candidates);+ }+ };+ for (const primitive of mesh.listPrimitives()) {+ const position = primitive.getAttribute('POSITION');+ if (position) {+ widen(position.getMin([]), false);+ widen(position.getMax([]), false);+ }+ for (const target of primitive.listTargets()) {+ const delta = target.getAttribute('POSITION');+ if (delta) {+ widen(delta.getMin([]), true);+ widen(delta.getMax([]), true);+ }+ }+ }+ return Math.max(...[0, 1, 2].map((axis) => (max[axis]! - min[axis]!) / 2));+ };+ const instanceScale = (node: Node): number => {+ const scale = node+ .getExtension<InstancedMesh>('EXT_mesh_gpu_instancing')+ ?.getAttribute('SCALE');+ if (!scale) return 1;+ let largest = 0;+ for (let i = 0; i < scale.getCount(); i++)+ largest = Math.max(largest, ...scale.getElement(i, []).map(Math.abs));+ return largest;+ };+ const steps: { node: Node; mesh: string; step: number }[] = [];+ for (const node of doc.getRoot().listNodes()) {+ const mesh = node.getMesh();+ if (!mesh?.listPrimitives().some((primitive) => primitive.getAttribute('POSITION'))) continue;+ const scale = node.getSkin() ? 1 : world(node).getMaxScaleOnAxis() * instanceScale(node);+ steps.push({ node, mesh: mesh.getName(), step: (halfExtent(mesh) * scale) / levels });+ }+ return steps;+}+/*** 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@@ -481,6 +606,12 @@ export async function deliverRuntimeThreeGlb(const { maxLod } = options;if (maxLod !== undefined && !(Number.isSafeInteger(maxLod) && maxLod >= 0))throw new Error('Runtime three maxLod must be a non-negative integer');+ const positionBits = options.positionBits ?? RUNTIME_THREE_QUANTIZATION.position;+ if (+ positionBits !== 'float' &&+ !(Number.isSafeInteger(positionBits) && positionBits >= 8 && positionBits <= 16)+ )+ throw new Error('Runtime three positionBits must be an integer from 8 to 16, or float');const io = createGltfIO().registerDependencies({'meshopt.encoder': meshoptEncoder,});@@ -496,19 +627,29 @@ export async function deliverRuntimeThreeGlb(const matrices = new Map<Node, number[]>();for (const node of doc.getRoot().listNodes())if (node.getMesh()) matrices.set(node, [...node.getMatrix()]);+ // Measured before the quantizer folds each mesh's scale into its node.+ const steps = positionBits === 'float' ? [] : positionGridSteps(doc, positionBits);+ const semantics =+ positionBits === 'float' ? QUANTIZED_SEMANTICS_EXCEPT_POSITION : QUANTIZED_SEMANTICS;await doc.transform(reorder({ encoder: meshoptEncoder as never, target: 'size' }),quantize({- pattern: QUANTIZED_SEMANTICS,- patternTargets: QUANTIZED_SEMANTICS,+ pattern: semantics,+ patternTargets: semantics,quantizationVolume: 'mesh',- quantizePosition: RUNTIME_THREE_QUANTIZATION.position,+ quantizePosition:+ positionBits === 'float' ? RUNTIME_THREE_QUANTIZATION.position : positionBits,quantizeNormal: RUNTIME_THREE_QUANTIZATION.normal,quantizeTexcoord: RUNTIME_THREE_QUANTIZATION.texcoord,quantizeColor: RUNTIME_THREE_QUANTIZATION.color,quantizeWeight: RUNTIME_THREE_QUANTIZATION.weight,}),);+ // The pinned quantizer decides whether to declare KHR_mesh_quantization by testing the+ // POSITION accessor for every semantic, so float positions hide quantized normals and+ // texture coordinates and the file would be invalid. Declare it from the accessors.+ if (positionBits === 'float' && hasQuantizedVertexData(doc))+ doc.createExtension(KHRMeshQuantization).setRequired(true);if (compression === 'meshopt')doc.createExtension(EXTMeshoptCompression)@@ -599,13 +740,19 @@ export async function deliverRuntimeThreeGlb(extension: 'KHR_mesh_quantization',volume: 'mesh',bits: {- position: RUNTIME_THREE_QUANTIZATION.position,+ position: positionBits === 'float' ? 'float32' : positionBits,normal: RUNTIME_THREE_QUANTIZATION.normal,texcoord: RUNTIME_THREE_QUANTIZATION.texcoord,color: RUNTIME_THREE_QUANTIZATION.color,weight: RUNTIME_THREE_QUANTIZATION.weight,},customAttributes: 'float32',+ positionSteps: steps.map(({ node, mesh, step }) => ({+ node: after.get(node) ?? `#lod/${encodeURIComponent(node.getName())}`,+ mesh,+ step,+ })),+ maxPositionStep: Math.max(0, ...steps.map(({ step }) => step)),},nodeScale,colliderProxies: proxies.map(({ collider, proxy }) => ({