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(kiln): add animated impostor review spike

Matt Kissinger713ee6f29d77
diff --git a/imposter/__tests__/animated-bake.test.ts b/imposter/__tests__/animated-bake.test.ts
new file mode 100644
index 00000000..af39ee51
--- /dev/null
+++ b/imposter/__tests__/animated-bake.test.ts
@@ -0,0 +1,32 @@
+/**
+ * Animated bake math tests. Live Playwright bake is covered by the review script.
+ */
+
+import { describe, expect, test } from 'bun:test';
+
+import { enumerateOctahedralGrid } from '../animated-bake';
+
+describe('enumerateOctahedralGrid', () => {
+ test('returns one unit direction per view tile', () => {
+ const tiles = enumerateOctahedralGrid(6, 6);
+ expect(tiles).toHaveLength(36);
+ for (const tile of tiles) {
+ expect(Math.hypot(...tile.dir)).toBeCloseTo(1, 6);
+ }
+ });
+
+ test('uses row-major tile order', () => {
+ const tiles = enumerateOctahedralGrid(2, 2);
+ expect(tiles.map((tile) => [tile.i, tile.j])).toEqual([
+ [0, 0],
+ [1, 0],
+ [0, 1],
+ [1, 1],
+ ]);
+ });
+
+ test('rejects invalid dimensions', () => {
+ expect(() => enumerateOctahedralGrid(0, 6)).toThrow();
+ expect(() => enumerateOctahedralGrid(6.5, 6)).toThrow();
+ });
+});
diff --git a/imposter/__tests__/animated-schema.test.ts b/imposter/__tests__/animated-schema.test.ts
new file mode 100644
index 00000000..91c08846
--- /dev/null
+++ b/imposter/__tests__/animated-schema.test.ts
@@ -0,0 +1,206 @@
+/**
+ * Animated imposter sidecar schema tests.
+ */
+
+import { describe, expect, test } from 'bun:test';
+
+import {
+ ANIMATED_IMPOSTER_KIND,
+ ANIMATED_IMPOSTER_SCHEMA_VERSION,
+ AnimatedImposterMetaSchema,
+ type AnimatedImposterMeta,
+} from '../animated-schema';
+
+const VALID: AnimatedImposterMeta = {
+ version: ANIMATED_IMPOSTER_SCHEMA_VERSION,
+ kind: ANIMATED_IMPOSTER_KIND,
+ source: {
+ path: 'characters/nva.glb',
+ bytes: 4_200_000,
+ tris: 12_000,
+ skinned: true,
+ animationClips: ['CharacterArmature|Idle', 'CharacterArmature|Walk'],
+ },
+ bbox: {
+ min: [-0.5, 0, -0.4],
+ max: [0.5, 1.8, 0.4],
+ worldSize: 1.8,
+ yOffset: 0.9,
+ },
+ projection: 'orthographic',
+ view: {
+ layout: 'octahedral',
+ directionEncoding: 'octahedral',
+ grid: { x: 6, y: 6, count: 36 },
+ tileSize: 96,
+ framesPerClip: 8,
+ },
+ clips: [
+ {
+ target: 'idle',
+ resolved: 'Idle',
+ rawName: 'CharacterArmature|Idle',
+ matchedBy: 'exact',
+ frameCount: 8,
+ durationSec: 1,
+ },
+ {
+ target: 'walking',
+ resolved: 'Walk',
+ rawName: 'CharacterArmature|Walk',
+ matchedBy: 'alias',
+ frameCount: 8,
+ durationSec: 1,
+ },
+ ],
+ textures: {
+ layout: 'array',
+ color: {
+ uri: 'nva-albedo.ktx2',
+ format: 'r8-palette-index',
+ width: 576,
+ height: 576,
+ layers: 16,
+ bytes: 5_308_416,
+ colorSpace: 'srgb',
+ },
+ palette: {
+ uri: 'nva-palette.png',
+ width: 128,
+ rows: 1,
+ bytes: 512,
+ },
+ },
+ runtime: {
+ renderer: 'webgl2',
+ primitive: 'instanced-quad',
+ material: 'ShaderMaterial',
+ textureMode: 'data-array-texture',
+ attributes: ['frameOffset', 'clip', 'variant', 'yaw', 'paletteRow'],
+ },
+ storage: {
+ colorBytes: 5_308_416,
+ paletteBytes: 512,
+ totalRawBytes: 5_308_928,
+ envelopeBytes: 31_457_280,
+ fitsEnvelope: true,
+ },
+ validation: {
+ warnings: [
+ {
+ code: 'ANIMATED_IMPOSTER_CLIP_FALLBACK',
+ severity: 'warning',
+ message: 'shoot used idle fallback in this debug bake',
+ },
+ ],
+ },
+};
+
+describe('AnimatedImposterMetaSchema', () => {
+ test('accepts the animated octahedral sidecar contract', () => {
+ expect(AnimatedImposterMetaSchema.parse(VALID)).toEqual(VALID);
+ });
+
+ test('round-trips through JSON', () => {
+ const decoded = AnimatedImposterMetaSchema.parse(JSON.parse(JSON.stringify(VALID)));
+ expect(decoded).toEqual(VALID);
+ });
+
+ test('rejects the static imposter kind', () => {
+ const bad = { ...VALID, kind: 'imposter' };
+ expect(() => AnimatedImposterMetaSchema.parse(bad)).toThrow();
+ });
+
+ test('rejects mismatched grid counts', () => {
+ const bad = {
+ ...VALID,
+ view: {
+ ...VALID.view,
+ grid: { ...VALID.view.grid, count: 35 },
+ },
+ };
+ expect(() => AnimatedImposterMetaSchema.parse(bad)).toThrow();
+ });
+
+ test('rejects color dimensions that do not match grid and tile size', () => {
+ const bad = {
+ ...VALID,
+ textures: {
+ ...VALID.textures,
+ color: { ...VALID.textures.color, width: 512 },
+ },
+ };
+ expect(() => AnimatedImposterMetaSchema.parse(bad)).toThrow();
+ });
+
+ test('rejects layer counts that do not match clip frames', () => {
+ const bad = {
+ ...VALID,
+ textures: {
+ ...VALID.textures,
+ color: { ...VALID.textures.color, layers: 15 },
+ },
+ };
+ expect(() => AnimatedImposterMetaSchema.parse(bad)).toThrow();
+ });
+
+ test('requires the WebGL runtime attributes needed by the first slice', () => {
+ const bad = {
+ ...VALID,
+ runtime: {
+ ...VALID.runtime,
+ attributes: ['frameOffset', 'clip', 'variant', 'yaw'],
+ },
+ };
+ expect(() => AnimatedImposterMetaSchema.parse(bad)).toThrow();
+ });
+
+ test('keeps texture array and packed atlas runtime modes explicit', () => {
+ const bad = {
+ ...VALID,
+ runtime: {
+ ...VALID.runtime,
+ textureMode: 'packed-2d-atlas',
+ },
+ };
+ expect(() => AnimatedImposterMetaSchema.parse(bad)).toThrow();
+ });
+
+ test('accepts packed 2D atlas fallback dimensions', () => {
+ const packed = {
+ ...VALID,
+ textures: {
+ ...VALID.textures,
+ layout: 'atlas',
+ color: {
+ ...VALID.textures.color,
+ uri: 'nva-albedo-packed.png',
+ width: 576 * 4,
+ height: 576 * 4,
+ framesX: 4,
+ framesY: 4,
+ },
+ },
+ runtime: {
+ ...VALID.runtime,
+ textureMode: 'packed-2d-atlas',
+ },
+ };
+ expect(() => AnimatedImposterMetaSchema.parse(packed)).not.toThrow();
+ });
+
+ test('packed 2D atlas fallback requires frame grid metadata', () => {
+ const bad = {
+ ...VALID,
+ textures: {
+ ...VALID.textures,
+ layout: 'atlas',
+ },
+ runtime: {
+ ...VALID.runtime,
+ textureMode: 'packed-2d-atlas',
+ },
+ };
+ expect(() => AnimatedImposterMetaSchema.parse(bad)).toThrow();
+ });
+});
diff --git a/imposter/__tests__/animated-validate.test.ts b/imposter/__tests__/animated-validate.test.ts
new file mode 100644
index 00000000..342e4d77
--- /dev/null
+++ b/imposter/__tests__/animated-validate.test.ts
@@ -0,0 +1,176 @@
+/**
+ * Animated imposter pre-bake validator tests.
+ */
+
+import { describe, expect, test } from 'bun:test';
+
+import {
+ estimateAnimatedImposterStorage,
+ validateAnimatedImposterPreBake,
+} from '../animated-validate';
+import type { AnimatedImposterPreBakeInput } from '../animated-schema';
+
+const VALID = {
+ source: {
+ path: 'characters/nva.glb',
+ bytes: 4_200_000,
+ tris: 12_000,
+ skinned: true,
+ clipNames: [
+ 'CharacterArmature|Idle',
+ 'CharacterArmature|Walk',
+ 'CharacterArmature|Run',
+ 'CharacterArmature|Slash',
+ ],
+ },
+ clipTargets: ['idle', 'walking'],
+ viewGrid: { x: 6, y: 6 },
+ tileSize: 96,
+ framesPerClip: 8,
+ textureFormat: 'r8-palette-index',
+ textureLayout: 'array',
+ includeNormal: false,
+ includeDepth: false,
+ paletteWidth: 128,
+ paletteRows: 1,
+ envelopeBytes: 30 * 1024 * 1024,
+ clipFallbacks: [],
+} satisfies AnimatedImposterPreBakeInput;
+
+describe('estimateAnimatedImposterStorage', () => {
+ test('estimates one array layer per animation frame', () => {
+ const storage = estimateAnimatedImposterStorage(VALID);
+ expect(storage.atlasWidth).toBe(576);
+ expect(storage.atlasHeight).toBe(576);
+ expect(storage.layers).toBe(16);
+ expect(storage.bytesPerColorPixel).toBe(1);
+ expect(storage.colorBytes).toBe(576 * 576 * 16);
+ expect(storage.paletteBytes).toBe(512);
+ expect(storage.totalRawBytes).toBe(storage.colorBytes + storage.paletteBytes);
+ expect(storage.fitsEnvelope).toBe(true);
+ });
+
+ test('accounts for rgba debug output and aux layers', () => {
+ const storage = estimateAnimatedImposterStorage({
+ ...VALID,
+ textureFormat: 'rgba8',
+ includeNormal: true,
+ includeDepth: true,
+ });
+ const pixels = 576 * 576 * 16;
+ expect(storage.colorBytes).toBe(pixels * 4);
+ expect(storage.normalBytes).toBe(pixels * 4);
+ expect(storage.depthBytes).toBe(pixels * 4);
+ expect(storage.paletteBytes).toBe(0);
+ });
+});
+
+describe('validateAnimatedImposterPreBake', () => {
+ test('accepts the first-slice contract without warnings', () => {
+ const report = validateAnimatedImposterPreBake(VALID);
+ expect(report.ok).toBe(true);
+ expect(report.blockers).toEqual([]);
+ expect(report.warnings).toEqual([]);
+ expect(report.clipResolution.clips.idle?.resolved).toBe('Idle');
+ expect(report.clipResolution.clips.walking?.resolved).toBe('Walk');
+ });
+
+ test('blocks non-skinned sources', () => {
+ const report = validateAnimatedImposterPreBake({
+ ...VALID,
+ source: { ...VALID.source, skinned: false },
+ });
+ expect(report.ok).toBe(false);
+ expect(report.blockers.map((issue) => issue.code)).toContain('ANIMATED_IMPOSTER_SOURCE_NOT_SKINNED');
+ });
+
+ test('surfaces missing clip coverage without hiding the rest of the contract', () => {
+ const report = validateAnimatedImposterPreBake({
+ ...VALID,
+ clipTargets: ['idle', 'death'],
+ });
+ expect(report.ok).toBe(true);
+ expect(report.warnings.map((issue) => issue.code)).toContain('ANIMATED_IMPOSTER_CLIP_MISSING');
+ expect(report.clipResolution.clips.death?.resolved).toBeNull();
+ });
+
+ test('reports explicit fallback clips', () => {
+ const report = validateAnimatedImposterPreBake({
+ ...VALID,
+ source: {
+ ...VALID.source,
+ clipNames: ['CharacterArmature|Idle', 'CharacterArmature|Run'],
+ },
+ clipTargets: ['idle', 'walking', 'running'],
+ clipFallbacks: [{ target: 'walking', donor: 'running' }],
+ });
+ expect(report.ok).toBe(true);
+ expect(report.clipResolution.clips.walking?.resolved).toBe('Run');
+ expect(report.clipResolution.clips.walking?.matchedBy).toBe('fallback');
+ expect(report.warnings.map((issue) => issue.code)).toContain('ANIMATED_IMPOSTER_CLIP_FALLBACK');
+ });
+
+ test('blocks if no requested clips resolve', () => {
+ const report = validateAnimatedImposterPreBake({
+ ...VALID,
+ source: { ...VALID.source, clipNames: ['Jump'] },
+ clipTargets: ['idle', 'walking'],
+ });
+ expect(report.ok).toBe(false);
+ expect(report.blockers.map((issue) => issue.code)).toContain('ANIMATED_IMPOSTER_NO_RESOLVED_CLIPS');
+ });
+
+ test('warns when the view grid or frame count leaves the initial validation lane', () => {
+ const report = validateAnimatedImposterPreBake({
+ ...VALID,
+ viewGrid: { x: 4, y: 4 },
+ tileSize: 128,
+ framesPerClip: 24,
+ });
+ expect(report.ok).toBe(true);
+ expect(report.warnings.map((issue) => issue.code)).toContain('ANIMATED_IMPOSTER_VIEW_GRID_UNPROVEN');
+ expect(report.warnings.map((issue) => issue.code)).toContain('ANIMATED_IMPOSTER_TILE_SIZE_UNPROVEN');
+ expect(report.warnings.map((issue) => issue.code)).toContain('ANIMATED_IMPOSTER_FRAME_COUNT_UNPROVEN');
+ });
+
+ test('blocks invalid octahedral grids and tile sizes', () => {
+ const report = validateAnimatedImposterPreBake({
+ ...VALID,
+ viewGrid: { x: 6, y: 8 },
+ tileSize: 95,
+ });
+ expect(report.ok).toBe(false);
+ expect(report.blockers.map((issue) => issue.code)).toContain('ANIMATED_IMPOSTER_VIEW_GRID_NOT_SQUARE');
+ expect(report.blockers.map((issue) => issue.code)).toContain('ANIMATED_IMPOSTER_TILE_SIZE_OUT_OF_RANGE');
+ });
+
+ test('reports source manifest drift', () => {
+ const report = validateAnimatedImposterPreBake({
+ ...VALID,
+ source: {
+ ...VALID.source,
+ manifest: {
+ expectedBytes: 1,
+ actualBytes: 2,
+ expectedHash: 'old',
+ actualHash: 'new',
+ },
+ },
+ });
+ expect(report.ok).toBe(true);
+ expect(report.warnings.map((issue) => issue.code)).toContain('ANIMATED_IMPOSTER_SOURCE_MANIFEST_BYTES_DRIFT');
+ expect(report.warnings.map((issue) => issue.code)).toContain('ANIMATED_IMPOSTER_SOURCE_MANIFEST_HASH_DRIFT');
+ });
+
+ test('blocks storage estimates that exceed the per-character envelope', () => {
+ const report = validateAnimatedImposterPreBake({
+ ...VALID,
+ clipTargets: ['idle', 'walking', 'running', 'shoot'],
+ viewGrid: { x: 8, y: 8 },
+ framesPerClip: 16,
+ });
+ expect(report.ok).toBe(false);
+ expect(report.storage.fitsEnvelope).toBe(false);
+ expect(report.blockers.map((issue) => issue.code)).toContain('ANIMATED_IMPOSTER_STORAGE_ENVELOPE_EXCEEDED');
+ });
+});
diff --git a/imposter/animated-bake.ts b/imposter/animated-bake.ts
new file mode 100644
index 00000000..81bf25d4
--- /dev/null
+++ b/imposter/animated-bake.ts
@@ -0,0 +1,485 @@
+/**
+ * Animated octahedral imposter baker.
+ *
+ * W2 emits a packed RGBA8 debug atlas for review. Production R8 palette and
+ * KTX2/DataArrayTexture packaging stay behind the review gate.
+ */
+
+import { Buffer } from 'node:buffer';
+import { createHash } from 'node:crypto';
+import { readFileSync } from 'node:fs';
+import sharp from 'sharp';
+import { chromium, type Page } from 'playwright';
+
+import {
+ ANIMATED_IMPOSTER_DEFAULT_ENVELOPE_BYTES,
+ ANIMATED_IMPOSTER_KIND,
+ ANIMATED_IMPOSTER_SCHEMA_VERSION,
+ AnimatedImposterMetaSchema,
+ type AnimatedClipTarget,
+ type AnimatedImposterMeta,
+ type AnimatedImposterPreBakeInput,
+ type AnimatedImposterTextureLayout,
+} from './animated-schema';
+import {
+ validateAnimatedImposterPreBake,
+ type AnimatedImposterPreBakeReport,
+} from './animated-validate';
+import type { ResolvedClip } from './clip-resolver';
+
+export interface AnimatedTileCamera {
+ i: number;
+ j: number;
+ u: number;
+ v: number;
+ dir: [number, number, number];
+}
+
+export interface BakeAnimatedImposterOptions {
+ clipTargets?: AnimatedClipTarget[];
+ clipFallbacks?: AnimatedImposterPreBakeInput['clipFallbacks'];
+ viewGrid?: { x: number; y: number };
+ tileSize?: number;
+ framesPerClip?: number;
+ textureLayout?: AnimatedImposterTextureLayout;
+ sourcePath?: string;
+ colorUri?: string;
+ envelopeBytes?: number;
+}
+
+export interface BakeAnimatedImposterResult {
+ atlas: Buffer;
+ frameAtlases: Buffer[];
+ meta: AnimatedImposterMeta;
+ preBake: AnimatedImposterPreBakeReport;
+ frameAtlas: {
+ width: number;
+ height: number;
+ framesX: number;
+ framesY: number;
+ };
+}
+
+export interface AnimatedImposterSession {
+ bake(glb: Buffer | string, opts?: BakeAnimatedImposterOptions): Promise<BakeAnimatedImposterResult>;
+ close(): Promise<void>;
+}
+
+interface LoadedAnimatedGlbInfo {
+ bbox: { min: [number, number, number]; max: [number, number, number] };
+ tris: number;
+ skinned: boolean;
+ clipNames: string[];
+ clipDurations: Record<string, number>;
+}
+
+export function enumerateOctahedralGrid(x: number, y: number): AnimatedTileCamera[] {
+ if (!Number.isInteger(x) || !Number.isInteger(y) || x <= 0 || y <= 0) {
+ throw new Error('octahedral grid dimensions must be positive integers');
+ }
+ const out: AnimatedTileCamera[] = [];
+ for (let j = 0; j < y; j++) {
+ for (let i = 0; i < x; i++) {
+ const u = ((i + 0.5) / x) * 2 - 1;
+ const v = 1 - ((j + 0.5) / y) * 2;
+ out.push({ i, j, u, v, dir: octaDecode(u, v) });
+ }
+ }
+ return out;
+}
+
+export async function openAnimatedImposterSession(): Promise<AnimatedImposterSession> {
+ const browser = await chromium.launch();
+ const ctx = await browser.newContext({ viewport: { width: 1024, height: 1024 }, deviceScaleFactor: 1 });
+ const page = await ctx.newPage();
+ await page.setContent(buildAnimatedHarnessHtml());
+ await page.waitForFunction(
+ () => (globalThis as unknown as { __animatedImposterReady?: boolean }).__animatedImposterReady === true,
+ { timeout: 30_000 },
+ );
+
+ return {
+ bake: (glb, opts) => bakeAnimatedOnPage(page, glb, opts ?? {}),
+ close: async () => {
+ await ctx.close();
+ await browser.close();
+ },
+ };
+}
+
+export async function bakeAnimatedImposter(
+ glb: Buffer | string,
+ opts: BakeAnimatedImposterOptions = {},
+): Promise<BakeAnimatedImposterResult> {
+ const session = await openAnimatedImposterSession();
+ try {
+ return await session.bake(glb, opts);
+ } finally {
+ await session.close();
+ }
+}
+
+async function bakeAnimatedOnPage(
+ page: Page,
+ glb: Buffer | string,
+ opts: BakeAnimatedImposterOptions,
+): Promise<BakeAnimatedImposterResult> {
+ const buf = typeof glb === 'string' ? readFileSync(glb) : glb;
+ const sourcePath = opts.sourcePath ?? (typeof glb === 'string' ? glb : undefined);
+ const clipTargets = opts.clipTargets ?? ['walking'];
+ const viewGrid = opts.viewGrid ?? { x: 6, y: 6 };
+ const tileSize = opts.tileSize ?? 96;
+ const framesPerClip = opts.framesPerClip ?? 8;
+ const textureLayout = opts.textureLayout ?? 'atlas';
+ const colorUri = opts.colorUri ?? 'animated-albedo-packed.png';
+ const envelopeBytes = opts.envelopeBytes ?? ANIMATED_IMPOSTER_DEFAULT_ENVELOPE_BYTES;
+
+ if (textureLayout !== 'atlas') {
+ throw new Error('W2 animated imposter bake currently writes packed 2D atlas output only');
+ }
+
+ const loadInfo = (await page.evaluate(
+ async ([dataUrl, tileSz]) => {
+ const w = globalThis as unknown as {
+ __animatedImposterLoadGlb: (dataUrl: string, tileSize: number) => Promise<LoadedAnimatedGlbInfo>;
+ };
+ return w.__animatedImposterLoadGlb(dataUrl, tileSz);
+ },
+ [`data:model/gltf-binary;base64,${buf.toString('base64')}`, tileSize] as const,
+ )) as LoadedAnimatedGlbInfo;
+
+ const preBake = validateAnimatedImposterPreBake({
+ source: {
+ ...(sourcePath ? { path: sourcePath } : {}),
+ bytes: buf.byteLength,
+ tris: loadInfo.tris,
+ skinned: loadInfo.skinned,
+ clipNames: loadInfo.clipNames,
+ },
+ clipTargets,
+ clipFallbacks: opts.clipFallbacks ?? [],
+ viewGrid,
+ tileSize,
+ framesPerClip,
+ textureFormat: 'rgba8',
+ textureLayout,
+ includeNormal: false,
+ includeDepth: false,
+ envelopeBytes,
+ });
+
+ if (!preBake.ok) {
+ throw new Error(`animated imposter pre-bake failed: ${preBake.blockers.map((i) => i.message).join('; ')}`);
+ }
+
+ const tiles = enumerateOctahedralGrid(viewGrid.x, viewGrid.y);
+ const frameAtlases: Buffer[] = [];
+ const clips = clipTargets
+ .map((target) => preBake.clipResolution.clips[target])
+ .filter(isRenderableClip);
+
+ for (const clip of clips) {
+ const durationSec = durationForClip(loadInfo.clipDurations, clip.rawName!, clip.resolved!);
+ for (let frame = 0; frame < framesPerClip; frame++) {
+ const timeSec = durationSec * (frame / framesPerClip);
+ const tilePngs: Buffer[] = [];
+ for (const tile of tiles) {
+ const dataUrl = (await page.evaluate(
+ (args) => {
+ const w = globalThis as unknown as {
+ __animatedImposterRenderTile: (args: {
+ dir: [number, number, number];
+ clipRawName: string;
+ timeSec: number;
+ tileSize: number;
+ }) => string;
+ };
+ return w.__animatedImposterRenderTile(args);
+ },
+ {
+ dir: tile.dir,
+ clipRawName: clip.rawName!,
+ timeSec,
+ tileSize,
+ },
+ )) as string;
+ tilePngs.push(Buffer.from(dataUrl.split(',')[1]!, 'base64'));
+ }
+ frameAtlases.push(await composeAtlas(tilePngs, tileSize, viewGrid.x, viewGrid.y));
+ }
+ }
+
+ const layerWidth = viewGrid.x * tileSize;
+ const layerHeight = viewGrid.y * tileSize;
+ const { framesX, framesY } = chooseFrameGrid(frameAtlases.length);
+ const atlas = await composeAtlas(frameAtlases, layerWidth, framesX, framesY, layerHeight);
+ const min = loadInfo.bbox.min;
+ const max = loadInfo.bbox.max;
+ const worldSize = Math.max(max[0] - min[0], max[1] - min[1], max[2] - min[2]);
+ const yOffset = (min[1] + max[1]) * 0.5;
+
+ const meta: AnimatedImposterMeta = {
+ version: ANIMATED_IMPOSTER_SCHEMA_VERSION,
+ kind: ANIMATED_IMPOSTER_KIND,
+ source: {
+ ...(sourcePath ? { path: sourcePath } : {}),
+ bytes: buf.byteLength,
+ tris: loadInfo.tris,
+ skinned: loadInfo.skinned,
+ hash: createHash('sha256').update(buf).digest('hex'),
+ animationClips: loadInfo.clipNames,
+ },
+ bbox: { min, max, worldSize, yOffset },
+ projection: 'orthographic',
+ view: {
+ layout: 'octahedral',
+ directionEncoding: 'octahedral',
+ grid: { x: viewGrid.x, y: viewGrid.y, count: viewGrid.x * viewGrid.y },
+ tileSize,
+ framesPerClip,
+ },
+ clips: clips.map((clip) => ({
+ target: clip.target,
+ resolved: clip.resolved,
+ rawName: clip.rawName,
+ matchedBy: clip.matchedBy,
+ ...(clip.fallbackFor ? { fallbackFor: clip.fallbackFor } : {}),
+ frameCount: framesPerClip,
+ durationSec: durationForClip(loadInfo.clipDurations, clip.rawName!, clip.resolved!),
+ })),
+ textures: {
+ layout: textureLayout,
+ color: {
+ uri: colorUri,
+ format: 'rgba8',
+ width: layerWidth * framesX,
+ height: layerHeight * framesY,
+ layers: frameAtlases.length,
+ framesX,
+ framesY,
+ bytes: atlas.byteLength,
+ colorSpace: 'srgb',
+ },
+ },
+ runtime: {
+ renderer: 'webgl2',
+ primitive: 'instanced-quad',
+ material: 'ShaderMaterial',
+ textureMode: 'packed-2d-atlas',
+ attributes: ['frameOffset', 'clip', 'variant', 'yaw', 'paletteRow'],
+ },
+ storage: {
+ colorBytes: preBake.storage.colorBytes,
+ totalRawBytes: preBake.storage.totalRawBytes,
+ envelopeBytes: preBake.storage.envelopeBytes,
+ fitsEnvelope: preBake.storage.fitsEnvelope,
+ },
+ validation: {
+ warnings: preBake.warnings,
+ },
+ };
+
+ return {
+ atlas,
+ frameAtlases,
+ meta: AnimatedImposterMetaSchema.parse(meta),
+ preBake,
+ frameAtlas: { width: layerWidth, height: layerHeight, framesX, framesY },
+ };
+}
+
+async function composeAtlas(
+ tilePngs: Buffer[],
+ tileWidth: number,
+ tilesX: number,
+ tilesY: number,
+ tileHeight = tileWidth,
+): Promise<Buffer> {
+ const composites: sharp.OverlayOptions[] = [];
+ for (let idx = 0; idx < tilePngs.length; idx++) {
+ const i = idx % tilesX;
+ const j = Math.floor(idx / tilesX);
+ composites.push({ input: tilePngs[idx]!, left: i * tileWidth, top: j * tileHeight });
+ }
+
+ return sharp({
+ create: { width: tilesX * tileWidth, height: tilesY * tileHeight, channels: 4, background: { r: 0, g: 0, b: 0, alpha: 0 } },
+ })
+ .composite(composites)
+ .png()
+ .toBuffer();
+}
+
+function durationForClip(durations: Record<string, number>, rawName: string, resolved: string): number {
+ return durations[rawName] ?? durations[resolved] ?? durations[resolved.toLowerCase()] ?? 1;
+}
+
+function isRenderableClip(clip: ResolvedClip | undefined): clip is ResolvedClip & { rawName: string; resolved: string } {
+ return Boolean(clip?.rawName && clip.resolved);
+}
+
+function chooseFrameGrid(layerCount: number): { framesX: number; framesY: number } {
+ let best = { framesX: layerCount, framesY: 1, waste: 0, aspectPenalty: Number.POSITIVE_INFINITY };
+ for (let y = 1; y <= layerCount; y++) {
+ const x = Math.ceil(layerCount / y);
+ const waste = x * y - layerCount;
+ const aspectPenalty = Math.abs(x / y - 2);
+ if (waste < best.waste || (waste === best.waste && aspectPenalty < best.aspectPenalty)) {
+ best = { framesX: x, framesY: y, waste, aspectPenalty };
+ }
+ }
+ return { framesX: best.framesX, framesY: best.framesY };
+}
+
+function octaDecode(u: number, v: number): [number, number, number] {
+ let x = u;
+ const y = 1 - Math.abs(u) - Math.abs(v);
+ let z = v;
+
+ if (y < 0) {
+ const oldX = x;
+ x = (1 - Math.abs(z)) * Math.sign(oldX || 1);
+ z = (1 - Math.abs(oldX)) * Math.sign(z || 1);
+ }
+
+ const len = Math.hypot(x, y, z) || 1;
+ return [x / len, y / len, z / len];
+}
+
+function buildAnimatedHarnessHtml(): string {
+ return `<!DOCTYPE html>
+<html><head>
+<meta charset="utf-8">
+<style>html,body{margin:0;padding:0;background:#000}#app{width:1024px;height:1024px}</style>
+<script type="importmap">
+{
+ "imports": {
+ "three": "https://unpkg.com/[email protected]/build/three.module.js",
+ "three/addons/": "https://unpkg.com/[email protected]/examples/jsm/"
+ }
+}
+</script>
+</head>
+<body>
+<div id="app"></div>
+<script type="module">
+import * as THREE from 'three';
+import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
+
+const app = document.getElementById('app');
+const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true, preserveDrawingBuffer: true });
+renderer.setPixelRatio(1);
+renderer.setSize(1024, 1024);
+renderer.outputColorSpace = THREE.SRGBColorSpace;
+app.appendChild(renderer.domElement);
+
+const scene = new THREE.Scene();
+scene.add(new THREE.AmbientLight(0xffffff, 0.55));
+const key = new THREE.DirectionalLight(0xffffff, 1.1);
+key.position.set(1.5, 2, 1);
+scene.add(key);
+const fill = new THREE.DirectionalLight(0xffffff, 0.35);
+fill.position.set(-1, 0.5, -1);
+scene.add(fill);
+
+let root = null;
+let mixer = null;
+let clips = [];
+let boundsRadius = 1;
+let boundsCenter = new THREE.Vector3();
+let originalMaterials = new Map();
+
+function normalizeClipName(raw) {
+ let s = raw;
+ while (s.includes('|')) s = s.slice(s.indexOf('|') + 1);
+ return s;
+}
+
+function findClip(rawName) {
+ return clips.find((c) => c.name === rawName)
+ || clips.find((c) => normalizeClipName(c.name) === normalizeClipName(rawName));
+}
+
+window.__animatedImposterLoadGlb = async (dataUrl, tileSize) => {
+ if (root) scene.remove(root);
+ originalMaterials.clear();
+ if (renderer.domElement.width !== tileSize) renderer.setSize(tileSize, tileSize);
+ const loader = new GLTFLoader();
+ return new Promise((resolve, reject) => {
+ loader.load(dataUrl, (gltf) => {
+ root = gltf.scene;
+ clips = gltf.animations || [];
+ mixer = new THREE.AnimationMixer(root);
+ scene.add(root);
+ const box = new THREE.Box3().setFromObject(root);
+ boundsCenter = box.getCenter(new THREE.Vector3());
+ const size = box.getSize(new THREE.Vector3());
+ boundsRadius = Math.sqrt(size.x * size.x + size.y * size.y + size.z * size.z) * 0.5 || 1;
+ let tris = 0;
+ let skinned = false;
+ root.traverse((obj) => {
+ if (obj.isSkinnedMesh) skinned = true;
+ if (obj.isMesh && obj.material) {
+ originalMaterials.set(obj, obj.material);
+ const mats = Array.isArray(obj.material) ? obj.material : [obj.material];
+ for (const m of mats) {
+ m.side = THREE.FrontSide;
+ m.needsUpdate = true;
+ }
+ if (obj.geometry && obj.geometry.index) tris += obj.geometry.index.count / 3;
+ else if (obj.geometry && obj.geometry.attributes.position) tris += obj.geometry.attributes.position.count / 3;
+ }
+ });
+ const clipDurations = {};
+ for (const clip of clips) {
+ clipDurations[clip.name] = clip.duration || 1;
+ clipDurations[normalizeClipName(clip.name)] = clip.duration || 1;
+ clipDurations[normalizeClipName(clip.name).toLowerCase()] = clip.duration || 1;
+ }
+ resolve({
+ bbox: { min: [box.min.x, box.min.y, box.min.z], max: [box.max.x, box.max.y, box.max.z] },
+ tris: Math.round(tris),
+ skinned,
+ clipNames: clips.map((c) => c.name),
+ clipDurations,
+ });
+ }, undefined, (err) => reject(err));
+ });
+};
+
+window.__animatedImposterRenderTile = ({ dir, clipRawName, timeSec, tileSize }) => {
+ if (!root || !mixer) throw new Error('no animated GLB loaded');
+ if (renderer.domElement.width !== tileSize) renderer.setSize(tileSize, tileSize);
+
+ const clip = findClip(clipRawName);
+ if (!clip) throw new Error('clip not found: ' + clipRawName);
+ mixer.stopAllAction();
+ const action = mixer.clipAction(clip);
+ action.reset();
+ action.setLoop(THREE.LoopRepeat, Infinity);
+ action.play();
+ mixer.setTime((timeSec || 0) % (clip.duration || 1));
+ root.updateMatrixWorld(true);
+
+ root.traverse((o) => {
+ if (o.isMesh && originalMaterials.has(o)) o.material = originalMaterials.get(o);
+ });
+
+ const half = boundsRadius * 1.05;
+ const camera = new THREE.OrthographicCamera(-half, half, half, -half, 0.01, 200);
+ const d = new THREE.Vector3(dir[0], dir[1], dir[2]).normalize();
+ camera.position.copy(boundsCenter).addScaledVector(d, boundsRadius * 4);
+ camera.up.set(0, 1, 0);
+ if (Math.abs(d.dot(camera.up)) > 0.97) camera.up.set(0, 0, 1);
+ camera.lookAt(boundsCenter);
+
+ scene.background = null;
+ renderer.setClearColor(0x000000, 0);
+ renderer.render(scene, camera);
+ return renderer.domElement.toDataURL('image/png');
+};
+
+window.__animatedImposterReady = true;
+</script>
+</body></html>`;
+}
diff --git a/imposter/animated-schema.ts b/imposter/animated-schema.ts
new file mode 100644
index 00000000..4b458071
--- /dev/null
+++ b/imposter/animated-schema.ts
@@ -0,0 +1,330 @@
+/**
+ * Animated octahedral imposter sidecar and pre-bake contract.
+ *
+ * Version 2 is intentionally separate from the static imposter v1 schema:
+ * one array layer is one animation frame containing the full octahedral view grid.
+ */
+
+import { z } from 'zod';
+
+export const ANIMATED_IMPOSTER_SCHEMA_VERSION = 2 as const;
+export const ANIMATED_IMPOSTER_KIND = 'animated-octahedral-imposter' as const;
+export const ANIMATED_IMPOSTER_DEFAULT_ENVELOPE_BYTES = 30 * 1024 * 1024;
+
+export const AnimatedClipTargetSchema = z.enum(['idle', 'walking', 'running', 'shoot', 'death']);
+export const AnimatedImposterTextureFormatSchema = z.enum(['r8-palette-index', 'rgba8']);
+export const AnimatedImposterTextureLayoutSchema = z.enum(['array', 'atlas']);
+export const AnimatedImposterTextureModeSchema = z.enum(['data-array-texture', 'packed-2d-atlas']);
+export const AnimatedImposterRuntimeAttributeSchema = z.enum([
+ 'frameOffset',
+ 'clip',
+ 'variant',
+ 'yaw',
+ 'paletteRow',
+ 'lodAlpha',
+]);
+
+export const AnimatedImposterWarningSchema = z
+ .object({
+ code: z.string().min(1),
+ severity: z.enum(['info', 'warning', 'error']),
+ message: z.string().min(1),
+ fixHint: z.string().min(1).optional(),
+ })
+ .strict();
+
+const Vec3Schema = z.tuple([z.number(), z.number(), z.number()]);
+
+const AnimatedClipMetaSchema = z
+ .object({
+ target: AnimatedClipTargetSchema,
+ resolved: z.string().nullable(),
+ rawName: z.string().nullable(),
+ matchedBy: z.enum(['exact', 'alias', 'fallback', 'missing']),
+ fallbackFor: AnimatedClipTargetSchema.optional(),
+ frameCount: z.number().int().nonnegative(),
+ durationSec: z.number().positive().optional(),
+ })
+ .strict();
+
+const AnimatedTextureLayerSchema = z
+ .object({
+ uri: z.string().min(1),
+ format: AnimatedImposterTextureFormatSchema,
+ width: z.number().int().positive(),
+ height: z.number().int().positive(),
+ layers: z.number().int().positive(),
+ framesX: z.number().int().positive().optional(),
+ framesY: z.number().int().positive().optional(),
+ bytes: z.number().int().nonnegative(),
+ colorSpace: z.enum(['srgb', 'linear']),
+ })
+ .strict();
+
+export const AnimatedImposterMetaSchema = z
+ .object({
+ version: z.literal(ANIMATED_IMPOSTER_SCHEMA_VERSION),
+ kind: z.literal(ANIMATED_IMPOSTER_KIND),
+ source: z
+ .object({
+ path: z.string().optional(),
+ bytes: z.number().int().nonnegative(),
+ tris: z.number().int().nonnegative(),
+ skinned: z.boolean(),
+ hash: z.string().optional(),
+ animationClips: z.array(z.string()),
+ })
+ .strict(),
+ bbox: z
+ .object({
+ min: Vec3Schema,
+ max: Vec3Schema,
+ worldSize: z.number().positive(),
+ yOffset: z.number(),
+ })
+ .strict(),
+ projection: z.literal('orthographic'),
+ view: z
+ .object({
+ layout: z.literal('octahedral'),
+ directionEncoding: z.literal('octahedral'),
+ grid: z
+ .object({
+ x: z.number().int().positive(),
+ y: z.number().int().positive(),
+ count: z.number().int().positive(),
+ })
+ .strict(),
+ tileSize: z.number().int().positive(),
+ framesPerClip: z.number().int().positive(),
+ })
+ .strict(),
+ clips: z.array(AnimatedClipMetaSchema).min(1),
+ textures: z
+ .object({
+ layout: AnimatedImposterTextureLayoutSchema,
+ color: AnimatedTextureLayerSchema,
+ palette: z
+ .object({
+ uri: z.string().min(1),
+ width: z.number().int().positive(),
+ rows: z.number().int().positive(),
+ bytes: z.number().int().nonnegative(),
+ })
+ .strict()
+ .optional(),
+ normal: AnimatedTextureLayerSchema.optional(),
+ depth: AnimatedTextureLayerSchema.optional(),
+ })
+ .strict(),
+ runtime: z
+ .object({
+ renderer: z.literal('webgl2'),
+ primitive: z.literal('instanced-quad'),
+ material: z.literal('ShaderMaterial'),
+ textureMode: AnimatedImposterTextureModeSchema,
+ attributes: z.array(AnimatedImposterRuntimeAttributeSchema).min(1),
+ })
+ .strict(),
+ storage: z
+ .object({
+ colorBytes: z.number().int().nonnegative(),
+ normalBytes: z.number().int().nonnegative().optional(),
+ depthBytes: z.number().int().nonnegative().optional(),
+ paletteBytes: z.number().int().nonnegative().optional(),
+ totalRawBytes: z.number().int().nonnegative(),
+ envelopeBytes: z.number().int().positive(),
+ fitsEnvelope: z.boolean(),
+ })
+ .strict(),
+ validation: z
+ .object({
+ warnings: z.array(AnimatedImposterWarningSchema),
+ })
+ .strict(),
+ })
+ .strict()
+ .superRefine((meta, ctx) => {
+ const grid = meta.view.grid;
+ if (grid.count !== grid.x * grid.y) {
+ ctx.addIssue({
+ code: 'custom',
+ path: ['view', 'grid', 'count'],
+ message: 'grid.count must equal grid.x * grid.y',
+ });
+ }
+
+ const expectedLayerWidth = grid.x * meta.view.tileSize;
+ const expectedLayerHeight = grid.y * meta.view.tileSize;
+
+ const expectedLayers = meta.clips.reduce((sum, clip) => sum + clip.frameCount, 0);
+ if (meta.textures.color.layers !== expectedLayers) {
+ ctx.addIssue({
+ code: 'custom',
+ path: ['textures', 'color', 'layers'],
+ message: 'color texture layers must equal the sum of clip frame counts',
+ });
+ }
+
+ if (meta.textures.layout === 'array') {
+ if (meta.textures.color.width !== expectedLayerWidth) {
+ ctx.addIssue({
+ code: 'custom',
+ path: ['textures', 'color', 'width'],
+ message: 'array color texture width must equal grid.x * tileSize',
+ });
+ }
+ if (meta.textures.color.height !== expectedLayerHeight) {
+ ctx.addIssue({
+ code: 'custom',
+ path: ['textures', 'color', 'height'],
+ message: 'array color texture height must equal grid.y * tileSize',
+ });
+ }
+ if (meta.textures.color.framesX !== undefined || meta.textures.color.framesY !== undefined) {
+ ctx.addIssue({
+ code: 'custom',
+ path: ['textures', 'color'],
+ message: 'array color textures must not set framesX or framesY',
+ });
+ }
+ } else {
+ const framesX = meta.textures.color.framesX;
+ const framesY = meta.textures.color.framesY;
+ if (framesX === undefined || framesY === undefined) {
+ ctx.addIssue({
+ code: 'custom',
+ path: ['textures', 'color'],
+ message: 'packed atlas color texture requires framesX and framesY',
+ });
+ } else {
+ if (meta.textures.color.width !== expectedLayerWidth * framesX) {
+ ctx.addIssue({
+ code: 'custom',
+ path: ['textures', 'color', 'width'],
+ message: 'packed atlas color texture width must equal frameAtlasWidth * framesX',
+ });
+ }
+ if (meta.textures.color.height !== expectedLayerHeight * framesY) {
+ ctx.addIssue({
+ code: 'custom',
+ path: ['textures', 'color', 'height'],
+ message: 'packed atlas color texture height must equal frameAtlasHeight * framesY',
+ });
+ }
+ if (framesX * framesY < expectedLayers) {
+ ctx.addIssue({
+ code: 'custom',
+ path: ['textures', 'color'],
+ message: 'packed atlas frame grid must have capacity for every layer',
+ });
+ }
+ }
+ }
+
+ const requiredAttributes = ['frameOffset', 'clip', 'variant', 'yaw', 'paletteRow'] as const;
+ for (const attr of requiredAttributes) {
+ if (!meta.runtime.attributes.includes(attr)) {
+ ctx.addIssue({
+ code: 'custom',
+ path: ['runtime', 'attributes'],
+ message: `runtime.attributes must include ${attr}`,
+ });
+ }
+ }
+
+ if (meta.runtime.textureMode === 'data-array-texture' && meta.textures.layout !== 'array') {
+ ctx.addIssue({
+ code: 'custom',
+ path: ['runtime', 'textureMode'],
+ message: 'data-array-texture runtime mode requires textures.layout=array',
+ });
+ }
+ if (meta.runtime.textureMode === 'packed-2d-atlas' && meta.textures.layout !== 'atlas') {
+ ctx.addIssue({
+ code: 'custom',
+ path: ['runtime', 'textureMode'],
+ message: 'packed-2d-atlas runtime mode requires textures.layout=atlas',
+ });
+ }
+
+ const expectedTotal =
+ meta.storage.colorBytes +
+ (meta.storage.normalBytes ?? 0) +
+ (meta.storage.depthBytes ?? 0) +
+ (meta.storage.paletteBytes ?? 0);
+ if (meta.storage.totalRawBytes !== expectedTotal) {
+ ctx.addIssue({
+ code: 'custom',
+ path: ['storage', 'totalRawBytes'],
+ message: 'storage.totalRawBytes must equal the sum of texture and palette bytes',
+ });
+ }
+ if (meta.storage.fitsEnvelope !== meta.storage.totalRawBytes <= meta.storage.envelopeBytes) {
+ ctx.addIssue({
+ code: 'custom',
+ path: ['storage', 'fitsEnvelope'],
+ message: 'storage.fitsEnvelope must match totalRawBytes <= envelopeBytes',
+ });
+ }
+ });
+
+export const AnimatedImposterPreBakeInputSchema = z
+ .object({
+ source: z
+ .object({
+ path: z.string().optional(),
+ bytes: z.number().int().nonnegative(),
+ tris: z.number().int().nonnegative(),
+ skinned: z.boolean(),
+ clipNames: z.array(z.string()),
+ manifest: z
+ .object({
+ path: z.string().optional(),
+ expectedBytes: z.number().int().nonnegative().optional(),
+ actualBytes: z.number().int().nonnegative().optional(),
+ expectedHash: z.string().optional(),
+ actualHash: z.string().optional(),
+ })
+ .strict()
+ .optional(),
+ })
+ .strict(),
+ clipTargets: z.array(AnimatedClipTargetSchema).min(1),
+ clipFallbacks: z
+ .array(
+ z
+ .object({
+ target: AnimatedClipTargetSchema,
+ donor: AnimatedClipTargetSchema,
+ })
+ .strict(),
+ )
+ .default([]),
+ viewGrid: z
+ .object({
+ x: z.number().int().positive(),
+ y: z.number().int().positive(),
+ })
+ .strict(),
+ tileSize: z.number().int().positive(),
+ framesPerClip: z.number().int().positive(),
+ textureFormat: AnimatedImposterTextureFormatSchema.default('r8-palette-index'),
+ textureLayout: AnimatedImposterTextureLayoutSchema.default('array'),
+ includeNormal: z.boolean().default(false),
+ includeDepth: z.boolean().default(false),
+ paletteWidth: z.number().int().positive().default(128),
+ paletteRows: z.number().int().positive().default(1),
+ envelopeBytes: z.number().int().positive().default(ANIMATED_IMPOSTER_DEFAULT_ENVELOPE_BYTES),
+ })
+ .strict();
+
+export type AnimatedClipTarget = z.infer<typeof AnimatedClipTargetSchema>;
+export type AnimatedImposterTextureFormat = z.infer<typeof AnimatedImposterTextureFormatSchema>;
+export type AnimatedImposterTextureLayout = z.infer<typeof AnimatedImposterTextureLayoutSchema>;
+export type AnimatedImposterTextureMode = z.infer<typeof AnimatedImposterTextureModeSchema>;
+export type AnimatedImposterRuntimeAttribute = z.infer<typeof AnimatedImposterRuntimeAttributeSchema>;
+export type AnimatedImposterWarning = z.infer<typeof AnimatedImposterWarningSchema>;
+export type AnimatedImposterMeta = z.infer<typeof AnimatedImposterMetaSchema>;
+export type AnimatedImposterPreBakeInput = z.input<typeof AnimatedImposterPreBakeInputSchema>;
+export type AnimatedImposterPreBakeConfig = z.output<typeof AnimatedImposterPreBakeInputSchema>;
diff --git a/imposter/animated-validate.ts b/imposter/animated-validate.ts
new file mode 100644
index 00000000..dd1ccd1e
--- /dev/null
+++ b/imposter/animated-validate.ts
@@ -0,0 +1,293 @@
+/**
+ * Pure pre-bake validation for animated octahedral impostors.
+ *
+ * This stage does not load GLBs or write artifacts. Callers pass discovered
+ * source facts, and the validator makes the first bake contract explicit.
+ */
+
+import {
+ ANIMATED_IMPOSTER_DEFAULT_ENVELOPE_BYTES,
+ AnimatedImposterPreBakeInputSchema,
+ type AnimatedClipTarget,
+ type AnimatedImposterPreBakeConfig,
+ type AnimatedImposterPreBakeInput,
+ type AnimatedImposterTextureFormat,
+ type AnimatedImposterWarning,
+} from './animated-schema';
+import {
+ applyClipFallbacks,
+ resolveClips,
+ type ClipResolutionReport,
+ type ClipTarget,
+} from './clip-resolver';
+
+export interface AnimatedImposterStorageEstimate {
+ atlasWidth: number;
+ atlasHeight: number;
+ layers: number;
+ bytesPerColorPixel: number;
+ colorBytes: number;
+ normalBytes: number;
+ depthBytes: number;
+ paletteBytes: number;
+ totalRawBytes: number;
+ envelopeBytes: number;
+ fitsEnvelope: boolean;
+}
+
+export interface AnimatedImposterPreBakeReport {
+ ok: boolean;
+ blockers: AnimatedImposterWarning[];
+ warnings: AnimatedImposterWarning[];
+ clipResolution: ClipResolutionReport;
+ storage: AnimatedImposterStorageEstimate;
+ normalized: AnimatedImposterPreBakeConfig;
+}
+
+export function estimateAnimatedImposterStorage(
+ input: Pick<
+ AnimatedImposterPreBakeConfig,
+ | 'viewGrid'
+ | 'tileSize'
+ | 'framesPerClip'
+ | 'clipTargets'
+ | 'textureFormat'
+ | 'includeNormal'
+ | 'includeDepth'
+ | 'paletteWidth'
+ | 'paletteRows'
+ | 'envelopeBytes'
+ >,
+): AnimatedImposterStorageEstimate {
+ const atlasWidth = input.viewGrid.x * input.tileSize;
+ const atlasHeight = input.viewGrid.y * input.tileSize;
+ const layers = input.framesPerClip * input.clipTargets.length;
+ const pixels = atlasWidth * atlasHeight * layers;
+ const bytesPerColorPixel = bytesPerPixel(input.textureFormat);
+ const colorBytes = pixels * bytesPerColorPixel;
+ const normalBytes = input.includeNormal ? pixels * 4 : 0;
+ const depthBytes = input.includeDepth ? pixels * 4 : 0;
+ const paletteBytes = input.textureFormat === 'r8-palette-index'
+ ? input.paletteWidth * input.paletteRows * 4
+ : 0;
+ const totalRawBytes = colorBytes + normalBytes + depthBytes + paletteBytes;
+ const envelopeBytes = input.envelopeBytes ?? ANIMATED_IMPOSTER_DEFAULT_ENVELOPE_BYTES;
+
+ return {
+ atlasWidth,
+ atlasHeight,
+ layers,
+ bytesPerColorPixel,
+ colorBytes,
+ normalBytes,
+ depthBytes,
+ paletteBytes,
+ totalRawBytes,
+ envelopeBytes,
+ fitsEnvelope: totalRawBytes <= envelopeBytes,
+ };
+}
+
+export function validateAnimatedImposterPreBake(
+ raw: AnimatedImposterPreBakeInput,
+): AnimatedImposterPreBakeReport {
+ const input = AnimatedImposterPreBakeInputSchema.parse(raw);
+ const blockers: AnimatedImposterWarning[] = [];
+ const warnings: AnimatedImposterWarning[] = [];
+
+ const add = (issue: AnimatedImposterWarning) => {
+ if (issue.severity === 'error') blockers.push(issue);
+ else warnings.push(issue);
+ };
+
+ if (input.source.bytes <= 0) {
+ add({
+ code: 'ANIMATED_IMPOSTER_SOURCE_EMPTY',
+ severity: 'error',
+ message: 'Source GLB has no bytes.',
+ fixHint: 'Pass a non-empty GLB buffer or file path before baking.',
+ });
+ }
+
+ if (input.source.tris <= 0) {
+ add({
+ code: 'ANIMATED_IMPOSTER_SOURCE_NO_TRIS',
+ severity: 'error',
+ message: 'Source GLB has no triangles.',
+ fixHint: 'Inspect the source GLB and select a mesh-backed character asset.',
+ });
+ }
+
+ if (!input.source.skinned) {
+ add({
+ code: 'ANIMATED_IMPOSTER_SOURCE_NOT_SKINNED',
+ severity: 'error',
+ message: 'Animated octahedral impostors need a skinned source character.',
+ fixHint: 'Use a skinned GLB or pivot to the static imposter path for rigid props.',
+ });
+ }
+
+ if (input.source.clipNames.length === 0) {
+ add({
+ code: 'ANIMATED_IMPOSTER_SOURCE_NO_CLIPS',
+ severity: 'error',
+ message: 'Source GLB has no animation clips.',
+ fixHint: 'Choose an animated character GLB before starting the bake.',
+ });
+ }
+
+ let clipResolution = resolveClips(input.source.clipNames, toClipTargets(input.clipTargets));
+ if (input.clipFallbacks.length > 0) {
+ clipResolution = applyClipFallbacks(clipResolution, fallbackMap(input.clipFallbacks));
+ }
+
+ for (const target of input.clipTargets) {
+ const clip = clipResolution.clips[target];
+ if (!clip || !clip.resolved) {
+ add({
+ code: 'ANIMATED_IMPOSTER_CLIP_MISSING',
+ severity: 'warning',
+ message: `No source clip resolved for ${target}.`,
+ fixHint: 'Add a clip fallback or remove the target from this bake slice.',
+ });
+ } else if (clip.matchedBy === 'fallback') {
+ add({
+ code: 'ANIMATED_IMPOSTER_CLIP_FALLBACK',
+ severity: 'warning',
+ message: `${target} will use ${clip.fallbackFor} as a fallback clip.`,
+ fixHint: 'Treat the output as visually provisional until a dedicated clip exists.',
+ });
+ }
+ }
+
+ const resolvedCount = input.clipTargets.filter((target) => clipResolution.clips[target]?.resolved).length;
+ if (resolvedCount === 0) {
+ add({
+ code: 'ANIMATED_IMPOSTER_NO_RESOLVED_CLIPS',
+ severity: 'error',
+ message: 'None of the requested clip targets resolved to source animation clips.',
+ fixHint: 'Check the clip list from the GLB and update aliases or fallback rules.',
+ });
+ }
+
+ if (input.viewGrid.x !== input.viewGrid.y) {
+ add({
+ code: 'ANIMATED_IMPOSTER_VIEW_GRID_NOT_SQUARE',
+ severity: 'error',
+ message: 'The first octahedral view grid must be square.',
+ fixHint: 'Use 6x6 or 8x8 for the first implementation slice.',
+ });
+ }
+
+ if (input.viewGrid.x < 4 || input.viewGrid.x > 16 || input.viewGrid.y < 4 || input.viewGrid.y > 16) {
+ add({
+ code: 'ANIMATED_IMPOSTER_VIEW_GRID_OUT_OF_RANGE',
+ severity: 'error',
+ message: 'View grid dimensions must stay between 4 and 16.',
+ fixHint: 'Use 6x6 for the storage-safe spike or 8x8 for the quality spike.',
+ });
+ } else if (input.viewGrid.x !== 6 && input.viewGrid.x !== 8) {
+ add({
+ code: 'ANIMATED_IMPOSTER_VIEW_GRID_UNPROVEN',
+ severity: 'warning',
+ message: 'Only 6x6 and 8x8 view grids are part of the initial validation plan.',
+ fixHint: 'Prefer 6x6 or 8x8 until yaw-sweep validation proves another grid.',
+ });
+ }
+
+ if (input.tileSize < 32 || input.tileSize > 512 || input.tileSize % 8 !== 0) {
+ add({
+ code: 'ANIMATED_IMPOSTER_TILE_SIZE_OUT_OF_RANGE',
+ severity: 'error',
+ message: 'Tile size must be 32-512 pixels and divisible by 8.',
+ fixHint: 'Use 96 for the first slice unless a validation gallery proves otherwise.',
+ });
+ } else if (input.tileSize !== 96) {
+ add({
+ code: 'ANIMATED_IMPOSTER_TILE_SIZE_UNPROVEN',
+ severity: 'warning',
+ message: 'The first implementation slice is budgeted around 96px tiles.',
+ fixHint: 'Use 96px until storage and yaw-sweep validation produce a better target.',
+ });
+ }
+
+ if (input.framesPerClip < 1 || input.framesPerClip > 64) {
+ add({
+ code: 'ANIMATED_IMPOSTER_FRAME_COUNT_OUT_OF_RANGE',
+ severity: 'error',
+ message: 'Frames per clip must be between 1 and 64.',
+ fixHint: 'Use 8-16 frames per clip for the first slice.',
+ });
+ } else if (input.framesPerClip < 8 || input.framesPerClip > 16) {
+ add({
+ code: 'ANIMATED_IMPOSTER_FRAME_COUNT_UNPROVEN',
+ severity: 'warning',
+ message: 'The first implementation slice expects 8-16 frames per clip.',
+ fixHint: 'Keep early bakes inside 8-16 frames before tuning cadence.',
+ });
+ }
+
+ const manifest = input.source.manifest;
+ if (
+ manifest?.expectedBytes !== undefined &&
+ manifest.actualBytes !== undefined &&
+ manifest.expectedBytes !== manifest.actualBytes
+ ) {
+ add({
+ code: 'ANIMATED_IMPOSTER_SOURCE_MANIFEST_BYTES_DRIFT',
+ severity: 'warning',
+ message: 'Source manifest byte count does not match the discovered GLB bytes.',
+ fixHint: 'Refresh the source manifest before trusting cache or resumability decisions.',
+ });
+ }
+
+ if (
+ manifest?.expectedHash !== undefined &&
+ manifest.actualHash !== undefined &&
+ manifest.expectedHash !== manifest.actualHash
+ ) {
+ add({
+ code: 'ANIMATED_IMPOSTER_SOURCE_MANIFEST_HASH_DRIFT',
+ severity: 'warning',
+ message: 'Source manifest hash does not match the discovered GLB hash.',
+ fixHint: 'Refresh the source manifest or select the exact GLB revision intended for bake.',
+ });
+ }
+
+ const storage = estimateAnimatedImposterStorage(input);
+ if (!storage.fitsEnvelope) {
+ add({
+ code: 'ANIMATED_IMPOSTER_STORAGE_ENVELOPE_EXCEEDED',
+ severity: 'error',
+ message: `Raw animated imposter storage estimate is ${storage.totalRawBytes} bytes, above the ${storage.envelopeBytes} byte envelope.`,
+ fixHint: 'Reduce view grid, tile size, frames per clip, clip count, or aux layers before baking.',
+ });
+ }
+
+ return {
+ ok: blockers.length === 0,
+ blockers,
+ warnings,
+ clipResolution,
+ storage,
+ normalized: input,
+ };
+}
+
+function bytesPerPixel(format: AnimatedImposterTextureFormat): number {
+ return format === 'r8-palette-index' ? 1 : 4;
+}
+
+function toClipTargets(targets: AnimatedClipTarget[]): ClipTarget[] {
+ return targets.map((target) => target as ClipTarget);
+}
+
+function fallbackMap(
+ fallbacks: AnimatedImposterPreBakeConfig['clipFallbacks'],
+): Partial<Record<ClipTarget, ClipTarget>> {
+ const out: Partial<Record<ClipTarget, ClipTarget>> = {};
+ for (const fallback of fallbacks) {
+ out[fallback.target as ClipTarget] = fallback.donor as ClipTarget;
+ }
+ return out;
+}
diff --git a/imposter/bake.ts b/imposter/bake.ts
index 4723fe92..6f135a6e 100644
--- a/imposter/bake.ts
+++ b/imposter/bake.ts
@@ -21,7 +21,7 @@
import { Buffer } from 'node:buffer';
import { readFileSync } from 'node:fs';
import sharp from 'sharp';
-import { chromium, type Browser, type BrowserContext, type Page } from 'playwright';
+import { chromium, type Page } from 'playwright';
import type {
ImposterAngleCount,
diff --git a/imposter/index.ts b/imposter/index.ts
index 5e5c372f..d884e951 100644
--- a/imposter/index.ts
+++ b/imposter/index.ts
@@ -16,6 +16,19 @@ export {
IMPOSTER_SCHEMA_VERSION,
ImposterMetaSchema,
} from './schema';
+export {
+ ANIMATED_IMPOSTER_DEFAULT_ENVELOPE_BYTES,
+ ANIMATED_IMPOSTER_KIND,
+ ANIMATED_IMPOSTER_SCHEMA_VERSION,
+ AnimatedClipTargetSchema,
+ AnimatedImposterMetaSchema,
+ AnimatedImposterPreBakeInputSchema,
+ AnimatedImposterRuntimeAttributeSchema,
+ AnimatedImposterTextureFormatSchema,
+ AnimatedImposterTextureLayoutSchema,
+ AnimatedImposterTextureModeSchema,
+ AnimatedImposterWarningSchema,
+} from './animated-schema';
export type {
ImposterMeta,
ImposterAngleCount,
@@ -24,6 +37,17 @@ export type {
ImposterAuxLayer,
ImposterBgColor,
} from './schema';
+export type {
+ AnimatedClipTarget,
+ AnimatedImposterMeta,
+ AnimatedImposterPreBakeConfig,
+ AnimatedImposterPreBakeInput,
+ AnimatedImposterRuntimeAttribute,
+ AnimatedImposterTextureFormat,
+ AnimatedImposterTextureLayout,
+ AnimatedImposterTextureMode,
+ AnimatedImposterWarning,
+} from './animated-schema';
export { resolveLayout, enumerateTiles, dirFromAzEl } from './projection';
export type { TileCamera, TileLayout } from './projection';
@@ -39,3 +63,24 @@ export type {
ResolvedClip,
ClipResolutionReport,
} from './clip-resolver';
+
+export {
+ estimateAnimatedImposterStorage,
+ validateAnimatedImposterPreBake,
+} from './animated-validate';
+export type {
+ AnimatedImposterPreBakeReport,
+ AnimatedImposterStorageEstimate,
+} from './animated-validate';
+
+export {
+ bakeAnimatedImposter,
+ enumerateOctahedralGrid,
+ openAnimatedImposterSession,
+} from './animated-bake';
+export type {
+ AnimatedImposterSession,
+ AnimatedTileCamera,
+ BakeAnimatedImposterOptions,
+ BakeAnimatedImposterResult,
+} from './animated-bake';
diff --git a/index.ts b/index.ts
index dbf6f45b..bc461600 100644
--- a/index.ts
+++ b/index.ts
@@ -190,8 +190,42 @@ export type {
ImposterLayout,
ImposterAuxLayer,
ImposterBgColor,
+ AnimatedClipTarget,
+ AnimatedImposterMeta,
+ AnimatedImposterPreBakeConfig,
+ AnimatedImposterPreBakeInput,
+ AnimatedImposterPreBakeReport,
+ AnimatedImposterRuntimeAttribute,
+ AnimatedImposterStorageEstimate,
+ AnimatedImposterTextureFormat,
+ AnimatedImposterTextureLayout,
+ AnimatedImposterTextureMode,
+ AnimatedImposterWarning,
+ AnimatedImposterSession,
+ AnimatedTileCamera,
+ BakeAnimatedImposterOptions,
+ BakeAnimatedImposterResult,
+} from './imposter';
+export {
+ ANIMATED_IMPOSTER_DEFAULT_ENVELOPE_BYTES,
+ ANIMATED_IMPOSTER_KIND,
+ ANIMATED_IMPOSTER_SCHEMA_VERSION,
+ AnimatedClipTargetSchema,
+ AnimatedImposterMetaSchema,
+ AnimatedImposterPreBakeInputSchema,
+ AnimatedImposterRuntimeAttributeSchema,
+ AnimatedImposterTextureFormatSchema,
+ AnimatedImposterTextureLayoutSchema,
+ AnimatedImposterTextureModeSchema,
+ AnimatedImposterWarningSchema,
+ ImposterMetaSchema,
+ IMPOSTER_SCHEMA_VERSION,
+ estimateAnimatedImposterStorage,
+ validateAnimatedImposterPreBake,
+ bakeAnimatedImposter,
+ enumerateOctahedralGrid,
+ openAnimatedImposterSession,
} from './imposter';
-export { ImposterMetaSchema, IMPOSTER_SCHEMA_VERSION } from './imposter';
// =============================================================================
// Top-level `generate()` - the full pipeline: prompt -> code -> GLB
diff --git a/primitives.ts b/primitives.ts
index 15a93db2..5d9bc07e 100644
--- a/primitives.ts
+++ b/primitives.ts
@@ -327,7 +327,6 @@ export function crossedQuadsGeo(opts: CrossedQuadsOptions = {}): THREE.BufferGeo
const uvs = new Float32Array(posCount * 2);
const indices: number[] = [];
let vOffset = 0;
- let iOffset = 0;
for (const g of geometries) {
const p = g.attributes.position!;
const n = g.attributes.normal!;
@@ -347,7 +346,6 @@ export function crossedQuadsGeo(opts: CrossedQuadsOptions = {}): THREE.BufferGeo
indices.push(idx.getX(i) + vOffset);
}
vOffset += p.count;
- iOffset += idx.count;
}
out.setAttribute('position', new THREE.BufferAttribute(positions, 3));
out.setAttribute('normal', new THREE.BufferAttribute(normals, 3));