diff --git a/docs/character-pack.md b/docs/character-pack.md index a4778aa..238c80a 100644 --- a/docs/character-pack.md +++ b/docs/character-pack.md @@ -10,13 +10,13 @@ On top of the common fields (`schemaVersion`, `kind`, `id`, `version`, `source`, | --- | --- | | `model` | One package path ending in `.glb`: the rigged, skinned character. | | `skeleton` | `"meshy-28"` (see below). | -| `animations` | Object keyed by state. Required: `idle`, `walk`, `run`, `shoot`, `death`, `crouch`, `crouchwalk`, `jump`. Optional: `idle1h`, `walk1h`, `walkfire`. No other keys. Each value is a distinct `.glb` path. | +| `animations` | Object keyed by state. Required: `idle`, `walk`, `run`, `shoot`, `death`, `crouch`, `crouchwalk`, `jump`. Optional: `idle1h`, `walk1h`, `walkfire`, plus one optional `extra` map of named clips (see below). No other keys. Each state value is a `.glb` path; states may each have their own file (the clip inside named exactly as the state) or all share one `states.glb` whose clip names are the state names. | | `previews` | At least one portrait image path (`.png`, `.jpg`, `.jpeg` or `.webp`). | | `rights` | `{ "status": "original" \| "public-domain" \| "political-satire", "basis": "", "references": ["", ...] }`; `references` is optional. | | `budgets` | `{ "triangles": , "bytes": }`. `triangles` bounds the model; `bytes` bounds the sum of every `files[].bytes`. | | `evidence` | Optional extra paths (for example a provenance sidecar). | -Every file in `files` must be declared by exactly one role (`model`, `animations.`, `previews`, `evidence`) and every declared path must appear in `files`. +Every file in `files` must be declared by at least one role (`model`, `animations.`, `animations.extra.`, `previews`, `evidence`) and every declared path must appear in `files`. One role *kind* per file: several `animations.` roles may share one states-pack file, several `animations.extra.` roles may share one family-pack file, but a file can never be both a state file and an extra file, nor carry a non-animation role besides. Extra-clip files count toward `budgets.bytes` like any other file. ```json { @@ -28,7 +28,12 @@ Every file in `files` must be declared by exactly one role (`model`, `animations "files": [{ "path": "model/capitao-caveira.glb", "sha256": "…", "bytes": 1 }], "model": "model/capitao-caveira.glb", "skeleton": "meshy-28", - "animations": { "idle": "animations/idle.glb", "walk": "animations/walk.glb", "…": "…" }, + "animations": { "idle": "animations/states.glb", "walk": "animations/states.glb", "…": "…", + "extra": { + "strafe_left": { "file": "animations/extra/loco.glb", "duration": 0.9, "loop": true, "rootMotion": false, "source": "Mixamo Strafe Left retargeted to meshy-28", "family": "loco" }, + "walk_back": { "file": "animations/extra/loco.glb", "duration": 1.2, "loop": true, "rootMotion": false, "source": "Mixamo Walk Back retargeted to meshy-28" }, + "emote_salute": { "file": "animations/extra/emote-salute.glb", "duration": 2.0, "loop": false, "rootMotion": false, "source": "Mixamo Salute retargeted to meshy-28", "family": "emote" } + } }, "previews": ["previews/portrait.jpg"], "rights": { "status": "original", "basis": "Invented character; concept prompt forbids likeness of real people and existing characters." }, "budgets": { "triangles": 6000, "bytes": 8388608 } @@ -39,12 +44,43 @@ Every file in `files` must be declared by exactly one role (`model`, `animations `node tools/validate-pack.mjs [package-root]` runs the schema, safe-path, role, size and SHA-256 checks shared by every pack. Before any payload is hashed, the sum of `files[].bytes` must not exceed `budgets.bytes`. It then reads the character bytes as data only (no renderer, no code execution): +- Animation GLBs may use the converter's `EXT_meshopt_compression` layout: buffer 0 is the compressed stream inside the BIN chunk and a virtual fallback buffer carries the uncompressed view sizes. Every compressed stream range is bounds-checked against the BIN chunk. The model keeps the strict single-buffer container, because the validator reads its skin bytes raw. - The model is a GLB 2 container with in-bounds buffer views and accessors, finite positions and in-range indices. Every primitive is a triangle list (mode 4), and the triangle count must not exceed `budgets.triangles`. - The model has exactly one skin, and `inverseBindMatrices` holds one float `MAT4` per joint. Every skinned primitive has a `JOINTS_0` unsigned byte/short `VEC4` and a float or normalized `WEIGHTS_0` `VEC4` per vertex, and every joint index stays inside the skin. - The skin is exactly meshy-28: 28 joints whose (name, nearest joint ancestor) pairs match the list below as a multiset. -- Each animation GLB contains an animation named exactly as its state that drives at least one meshy-28 bone through a `translation`, `rotation` or `scale` channel. A `weights` channel must target a mesh with morph targets. Every sampler has at least one float keyframe time and the output type and count that match its interpolation (and, for `weights`, the number of morph targets). +- Each animation GLB contains an animation named exactly as its state (or extra key) that drives at least one meshy-28 bone through a `translation`, `rotation` or `scale` channel. A `weights` channel must target a mesh with morph targets. Every sampler has at least one float keyframe time and the output type and count that match its interpolation (and, for `weights`, the number of morph targets). When several states share one `states.glb`, or several extras share one family-pack file, each declared name must exist as an animation inside that shared GLB, and the GLB is read once per file, not once per clip. - Each preview starts with the PNG, JPEG or WebP signature for its extension. + +## Optional clips (`animations.extra`) + +`animations.extra` is an optional map of named clips beyond the states, for movement set, weapon handling, damage reactions, melee, round outcomes and emotes. Keys match `^[a-z][a-z0-9_]{1,40}$` and must be either a name from the fixed vocabulary below or an `emote_` prefix followed by at least one character. Anything else — including state names and the bare `emote_` prefix — is rejected. The vocabulary is `extraClipNames`/`extraClipPrefixes` in `tools/lib/character-pack.mjs` (68 names: `coreExtraClipNames` plus `converterExtraClipNames`); the client mirrors it in `public/js/data/content-releases.js`. + +- Locomotion (cardinals and diagonals; diagonals follow `__`): `strafe_left`, `strafe_right`, `walk_back`, `walk_fwd_left`, `walk_fwd_right`, `walk_back_left`, `walk_back_right`, `run_back`, `run_left`, `run_right`, `run_fwd_left`, `run_fwd_right`, `run_back_left`, `run_back_right` +- Sprint: `sprint`, `sprint_back`, `sprint_left`, `sprint_right`, `sprint_fwd_left`, `sprint_fwd_right`, `sprint_back_left`, `sprint_back_right` +- Crouched locomotion and aim: `crouchwalk_left`, `crouchwalk_right`, `crouchwalk_back`, `crouchwalk_fwd_left`, `crouchwalk_fwd_right`, `crouchwalk_back_left`, `crouchwalk_back_right`, `crouch_aim`, `crouch_pistol`, `crouch_turn_left`, `crouch_turn_right` +- Turns (standing): `turn_left`, `turn_right` +- Jump phases: `jump_start`, `jump_loop`, `jump_land`, `jump_pistol` +- Aim, pistol and crouch fire: `idle_aim`, `shoot_pistol`, `shoot_crouch`, `run_pistol`, `run_back_pistol`, `strafe_left_pistol`, `strafe_right_pistol`, `walk_back_pistol` +- Weapon handling: `reload_rifle`, `reload_pistol`, `draw_rifle`, `holster_rifle`, `draw_pistol`, `holster_pistol` +- Damage reactions: `hit_front`, `hit_back`, `hit_left`, `hit_right`, `hit_head` +- Death variants: `death_front`, `death_right`, `death_headshot_front`, `death_headshot_back`, `death_crouch` +- Melee and utility: `grenade_throw`, `knife_idle`, `knife_stab` +- Round outcomes: `victory`, `defeat` +- Emotes: any key starting with `emote_` (for example `emote_danca`) + +The converter group (`converterExtraClipNames`) is a snapshot of the names proposed by the animation conversion library (branch `feat/animation-conversion-20261109`, `tools/lib/animation-library.mjs`, 2026-11-09; every name is used by at least one key of its `library/index.json`). `assertExtraClipVocabulary` in `tools/lib/character-pack.mjs` enforces the single source: the vocabulary must equal the core names plus the converter set, with no duplicates, no state collisions and no pattern breaks; `tools/checks/character-pack-check.mjs` proves it against the real exports and synthetic mutants. The conversion tooling must import `extraClipNames` from `tools/lib/character-pack.mjs` instead of maintaining its own name list. + +Each entry is an object with exactly six fields: `file` (a `.glb` package path, declared in `files`), `duration` (seconds, positive), `loop` (boolean), `rootMotion` (boolean), `source` (provenance string, for example the source animation and rig pipeline) and the optional `family` (`"loco"`, `"combat"`, `"ceremony"` or `"emote"`). `duration`, `loop` and `rootMotion` are declared metadata for the runtime; the GLB itself still carries the authoritative keyframes. A missing `extra` map is valid — optional means absent, not empty promises. + +### Family packs + +Extras arrive the way the animation converter packs them (`tools/lib/clip-pack.mjs`, `character-clips@2`): one GLB per family — `states.glb` (the 11 runtime states), `loco.glb`, `combat.glb`, `ceremony.glb` — plus one GLB per emote. The contract accepts both this layout and the older one-file-per-clip layout: + +- Several non-emote keys may point at the same `file`; every key must then exist as an animation name inside that GLB, and all keys sharing a file must belong to one single family (`clipFamily` in `tools/lib/character-pack.mjs`, which mirrors the converter's `packFamily`; the check suite proves the mirror against a snapshot of the converter's own answers). A declared `family` must match the name's family. +- Emote keys always keep one file per key: an `emote_*` entry may never share its file with any other key. +- States may all point at one `states.glb` whose clip names are the state names; the per-state layout remains valid, and the two cannot mix files (`animations.` and `animations.extra.` are different role kinds). + ## meshy-28 The shared Meshy humanoid skeleton the runtime clips are baked against, taken from the client donor `public/models/characters/mst.glb` and identical in all 37 offline-rigged Creepypasta Season characters. Skin joint order, with the nearest joint ancestor in parentheses: @@ -63,7 +99,7 @@ Photos of real people never enter either repository. ## Checks -`npm run check` builds a synthetic character pack (a programmatic 12-triangle skinned GLB and eleven one-channel clips, no real asset bytes), validates it, and requires each contract mutant to be rejected for its stated reason: missing states, unknown state, misnamed clip, clip driving no meshy-28 bone, clip channel without a path, clip without keyframes or with mismatched output, wrong skeleton id, renamed, reparented or missing bone, missing skin or weights, missing, mistyped or out-of-skin `JOINTS_0`, triangle strips, bad GLB magic or version, triangle and byte budgets (including the byte budget before hashing), bad rights, missing or invalid previews, undeclared files, and hash or size mutations. +`npm run check` builds a synthetic character pack (a programmatic 12-triangle skinned GLB, one-channel state clips, a loco family pack shared by two extras and a per-file extra, no real asset bytes), validates it — once per layout, including all states in one `states.glb` — and requires each contract mutant to be rejected for its stated reason: missing states, unknown state, misnamed clip, clip driving no meshy-28 bone, clip channel without a path, clip without keyframes or with mismatched output, wrong skeleton id, renamed, reparented or missing bone, missing skin or weights, missing, mistyped or out-of-skin `JOINTS_0`, triangle strips, bad GLB magic or version, triangle and byte budgets (including the byte budget before hashing), bad rights, missing or invalid previews, undeclared files, hash or size mutations, and the extra-clip rules: unknown, pattern-violating, state-colliding or bare-prefix names, entries with missing or mistyped fields, non-GLB files, missing, duplicate or misnamed clip files, extras pushing the pack over its byte budget, a key missing inside the family pack, an emote sharing any file, a declared family mismatching the clip name, a family outside the enum, one file mixing families, and a states pack missing a state clip. It also proves the `clipFamily` mirror against a snapshot of the converter's `packFamily` answers, including a poisoned-mirror mutant. ## Concept generation diff --git a/schemas/asset-pack.schema.json b/schemas/asset-pack.schema.json index 725e51d..e3ecaa3 100644 --- a/schemas/asset-pack.schema.json +++ b/schemas/asset-pack.schema.json @@ -109,7 +109,24 @@ "jump": { "$ref": "#/$defs/glbPath" }, "idle1h": { "$ref": "#/$defs/glbPath" }, "walk1h": { "$ref": "#/$defs/glbPath" }, - "walkfire": { "$ref": "#/$defs/glbPath" } + "walkfire": { "$ref": "#/$defs/glbPath" }, + "extra": { + "type": "object", + "propertyNames": { "pattern": "^[a-z][a-z0-9_]{1,40}$" }, + "additionalProperties": { + "type": "object", + "required": ["file", "duration", "loop", "rootMotion", "source"], + "properties": { + "file": { "$ref": "#/$defs/glbPath" }, + "duration": { "type": "number", "exclusiveMinimum": 0 }, + "loop": { "type": "boolean" }, + "rootMotion": { "type": "boolean" }, + "source": { "type": "string", "minLength": 1 }, + "family": { "enum": ["loco", "combat", "ceremony", "emote"] } + }, + "additionalProperties": false + } + } }, "additionalProperties": false }, diff --git a/tools/checks/character-pack-check.mjs b/tools/checks/character-pack-check.mjs index 15524c9..7b0aae8 100755 --- a/tools/checks/character-pack-check.mjs +++ b/tools/checks/character-pack-check.mjs @@ -5,7 +5,8 @@ import { createHash } from 'node:crypto'; import fs from 'node:fs'; import os from 'node:os'; import path from 'node:path'; -import { meshy28Joints, optionalCharacterStates, requiredCharacterStates } from '../lib/character-pack.mjs'; +import { assertExtraClipVocabulary, clipFamily, converterExtraClipNames, coreExtraClipNames, extraClipNames, meshy28Joints, optionalCharacterStates, requiredCharacterStates } from '../lib/character-pack.mjs'; +import { readGlb } from '../lib/glb-inspect.mjs'; import { validatePack } from '../lib/pack.mjs'; const png = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=', 'base64'); @@ -13,7 +14,7 @@ const sha256 = bytes => createHash('sha256').update(bytes).digest('hex'); const clone = value => JSON.parse(JSON.stringify(value)); const pad4 = bytes => Buffer.concat([bytes, Buffer.alloc((4 - (bytes.length % 4)) % 4)]); -function glb(document, chunks) { +function glb(document, chunks, extraBuffers = []) { const views = []; const parts = []; let offset = 0; @@ -24,7 +25,7 @@ function glb(document, chunks) { offset += padded.length; } const bin = Buffer.concat(parts); - const json = Buffer.from(JSON.stringify({ asset: { version: '2.0', generator: 'coro-solto-studio character-pack-check' }, ...document, buffers: [{ byteLength: bin.length }], bufferViews: views })); + const json = Buffer.from(JSON.stringify({ asset: { version: '2.0', generator: 'coro-solto-studio character-pack-check' }, ...document, buffers: [{ byteLength: bin.length }, ...extraBuffers], bufferViews: [...document.bufferViews ?? [], ...views] })); const paddedJson = Buffer.concat([json, Buffer.alloc((4 - (json.length % 4)) % 4, 0x20)]); const header = Buffer.alloc(20); header.writeUInt32LE(0x46546c67, 0); @@ -123,10 +124,68 @@ function clipGlb(name, { target = 'Hips', path: channelPath = 'rotation', keyfra }, chunks); } +// A family pack (or a states pack): several named clips sharing one GLB, all driving the Hips +// rotation channel, exactly how the converter merges per-clip GLBs into states/loco/combat/ +// ceremony files. +function clipsGlb(names) { + const nodes = skeletonNodes(meshy28Joints); + const targetNode = nodes.findIndex(node => node.name === 'Hips'); + return glb({ + scene: 0, + scenes: [{ nodes: [0] }], + nodes, + animations: names.map(name => ({ + name, + channels: [{ sampler: 0, target: { node: targetNode, path: 'rotation' } }], + samplers: [{ input: 0, output: 1, interpolation: 'LINEAR' }], + })), + accessors: [ + { bufferView: 0, componentType: 5126, count: 2, type: 'SCALAR', min: [0], max: [1] }, + { bufferView: 1, componentType: 5126, count: 2, type: 'VEC4' }, + ], + }, [ + { bytes: floats([0, 1]) }, + { bytes: floats([0, 0, 0, 1, 0, 0, 0, 1]) }, + ]); +} + +// The converter's EXT_meshopt_compression shape: buffer 0 holds the compressed stream (the +// BIN chunk), buffer 1 is the virtual fallback buffer, and every bufferView lives in the +// fallback with a compressed range pointing into buffer 0. +function meshoptClipsGlb(names, { markFallback = true, overshootStream = false } = {}) { + const nodes = skeletonNodes(meshy28Joints); + const targetNode = nodes.findIndex(node => node.name === 'Hips'); + const stream = Buffer.alloc(16, 7); + const secondHalf = overshootStream ? 16 : 8; + return glb({ + scene: 0, + scenes: [{ nodes: [0] }], + nodes, + animations: names.map(name => ({ + name, + channels: [{ sampler: 0, target: { node: targetNode, path: 'rotation' } }], + samplers: [{ input: 0, output: 1, interpolation: 'LINEAR' }], + })), + accessors: [ + { bufferView: 0, componentType: 5126, count: 2, type: 'SCALAR', min: [0], max: [1] }, + { bufferView: 1, componentType: 5126, count: 2, type: 'VEC4' }, + ], + bufferViews: [ + { buffer: 1, byteOffset: 0, byteLength: 8, extensions: { EXT_meshopt_compression: { buffer: 0, byteOffset: 0, byteLength: 8 } } }, + { buffer: 1, byteOffset: 8, byteLength: 32, extensions: { EXT_meshopt_compression: { buffer: 0, byteOffset: secondHalf, byteLength: secondHalf === 16 ? 16 : 8 } } }, + ], + }, [{ bytes: stream }], [{ byteLength: 40, ...(markFallback ? { extensions: { EXT_meshopt_compression: { fallback: true } } } : {}) }]); +} + const allStates = [...requiredCharacterStates, ...optionalCharacterStates]; function validFiles() { const files = { 'model/fixture-character.glb': modelGlb(), 'previews/portrait.png': png }; for (const state of allStates) files[`animations/${state}.glb`] = clipGlb(state); + // strafe_left and walk_back share the loco family pack; sprint_fwd_left keeps the old + // one-file-per-clip layout; the emote keeps its own file. Family declared on some keys only. + files['animations/extra/loco.glb'] = clipsGlb(['strafe_left', 'walk_back']); + files['animations/extra/sprint-fwd-left.glb'] = clipGlb('sprint_fwd_left'); + files['animations/extra/emote-danca.glb'] = clipGlb('emote_danca'); return files; } @@ -140,7 +199,15 @@ function manifestFor(files) { files: Object.entries(files).map(([file, bytes]) => ({ path: file, sha256: sha256(bytes), bytes: bytes.length })), model: 'model/fixture-character.glb', skeleton: 'meshy-28', - animations: Object.fromEntries(allStates.map(state => [state, `animations/${state}.glb`])), + animations: { + ...Object.fromEntries(allStates.map(state => [state, `animations/${state}.glb`])), + extra: { + strafe_left: { file: 'animations/extra/loco.glb', duration: 0.8, loop: true, rootMotion: false, source: 'Synthetic strafe-left fixture clip', family: 'loco' }, + walk_back: { file: 'animations/extra/loco.glb', duration: 1.1, loop: true, rootMotion: false, source: 'Synthetic walk-back fixture clip' }, + emote_danca: { file: 'animations/extra/emote-danca.glb', duration: 2.5, loop: false, rootMotion: false, source: 'Synthetic emote fixture clip', family: 'emote' }, + sprint_fwd_left: { file: 'animations/extra/sprint-fwd-left.glb', duration: 0.7, loop: true, rootMotion: false, source: 'Synthetic converter-vocabulary fixture clip' }, + }, + }, previews: ['previews/portrait.png'], rights: { status: 'original', basis: 'Invented synthetic test character with no likeness or third-party design.' }, budgets: { triangles: 100, bytes: 1048576 }, @@ -164,6 +231,18 @@ async function validateCase({ files = validFiles(), replace = {}, mutate = () => return validatePack({ manifestPath, packageRoot }); } +// Synchronous form of expectRejection for the pure vocabulary invariant (no pack fixture). +function expectVocabularyFailure(label, pattern, options) { + try { + assertExtraClipVocabulary(options); + } catch (caught) { + if (!pattern.test(caught.message)) throw new Error(`${label} was rejected for the wrong reason: ${caught.message}`); + console.log(`PASS ${label} rejected`); + return; + } + throw new Error(`${label} was not rejected`); +} + async function expectRejection(label, pattern, options) { let error; try { await validateCase(options); } catch (caught) { error = caught; } @@ -177,14 +256,111 @@ const dropState = state => manifest => { manifest.files = manifest.files.filter(file => file.path !== `animations/${state}.glb`); }; +const dropExtras = manifest => { + for (const entry of Object.values(manifest.animations.extra || {})) { + manifest.files = manifest.files.filter(file => file.path !== entry.file); + } + delete manifest.animations.extra; +}; + try { const valid = await validateCase(); - console.log(`PASS Valid synthetic character pack (${valid.character.triangles} triangles, ${valid.character.joints} meshy-28 joints, ${valid.character.animations} state clips)`); - const requiredOnly = await validateCase({ mutate: manifest => optionalCharacterStates.forEach(state => dropState(state)(manifest)) }); - console.log(`PASS Valid character pack with only the ${requiredOnly.character.animations} required states`); + console.log(`PASS Valid synthetic character pack (${valid.character.triangles} triangles, ${valid.character.joints} meshy-28 joints, ${valid.character.animations} state clips, ${valid.character.extraClips} extra clips)`); + const requiredOnly = await validateCase({ mutate: manifest => { optionalCharacterStates.forEach(state => dropState(state)(manifest)); dropExtras(manifest); } }); + console.log(`PASS Valid character pack with only the ${requiredOnly.character.animations} required states and ${requiredOnly.character.extraClips} extra clips`); await validateCase({ replace: { 'animations/idle.glb': clipGlb('idle', { morph: 'valid' }) } }); console.log('PASS Valid clip with a bone channel plus a morph-weights channel'); + // Every state may also come from one shared states pack whose clip names are the state names. + const statesPack = await validateCase({ + files: { + 'model/fixture-character.glb': modelGlb(), + 'previews/portrait.png': png, + 'animations/states.glb': clipsGlb(allStates), + 'animations/extra/loco.glb': clipsGlb(['strafe_left', 'walk_back']), + 'animations/extra/sprint-fwd-left.glb': clipGlb('sprint_fwd_left'), + 'animations/extra/emote-danca.glb': clipGlb('emote_danca'), + }, + mutate: manifest => { + for (const state of allStates) manifest.animations[state] = 'animations/states.glb'; + }, + }); + console.log(`PASS Valid character pack with all ${statesPack.character.animations} states in one states.glb`); + + // The converter's meshopt family packs (fallback buffer + compressed streams) validate as + // animation files, while the raw model read keeps the strict single-buffer container. + await validateCase({ replace: { 'animations/extra/loco.glb': meshoptClipsGlb(['strafe_left', 'walk_back']) } }); + console.log('PASS Valid meshopt-compressed family pack accepted'); + const meshoptShape = path.join(directory, 'meshopt-shape.glb'); + fs.writeFileSync(meshoptShape, meshoptClipsGlb(['strafe_left'])); + await readGlb(meshoptShape, 'meshopt-shape.glb', { allowMeshoptFallback: true }); + try { + await readGlb(meshoptShape, 'meshopt-shape.glb'); + throw new Error('Strict readGlb accepted the meshopt fallback layout'); + } catch (caught) { + if (!/one self-contained buffer/.test(caught.message)) throw new Error(`Strict readGlb rejected for the wrong reason: ${caught.message}`); + } + console.log('PASS Strict readGlb still rejects the meshopt fallback layout (model path)'); + + // Single-source vocabulary invariant: the contract vocabulary must equal the core names plus + // the animation conversion library's proposed names (snapshot in character-pack.mjs). + assertExtraClipVocabulary(); + console.log(`PASS Extra clip vocabulary covers the conversion library (${extraClipNames.length} names = ${coreExtraClipNames.length} core + ${converterExtraClipNames.length} converter)`); + expectVocabularyFailure('Converter key missing from the vocabulary', /converter clip names missing from the vocabulary: vault_low/, { + converter: [...converterExtraClipNames, 'vault_low'], + }); + expectVocabularyFailure('Vocabulary name outside the core and converter sets', /extra clip names outside the core and converter sets: moonwalk/, { + vocabulary: [...extraClipNames, 'moonwalk'], + }); + expectVocabularyFailure('Core name dropped from the vocabulary', /core extra clip names missing from the vocabulary: victory/, { + vocabulary: extraClipNames.filter(name => name !== 'victory'), + }); + expectVocabularyFailure('Duplicate vocabulary entry', /duplicate extra clip name in the vocabulary: sprint/, { + vocabulary: [...extraClipNames, 'sprint'], + }); + + + // Family parity: the contract mirror must classify every name exactly like the converter's + // packFamily. Snapshot generated 2026-11-09 by importing packFamily from + // feat/animation-conversion-20261109 tools/lib/clip-pack.mjs over every state, vocabulary and + // sample emote name; the converter's pack id `emotes` is the contract family `emote`. + const converterPackFamilies = Object.freeze({ + idle: 'states', walk: 'states', run: 'states', shoot: 'states', death: 'states', crouch: 'states', + crouchwalk: 'states', jump: 'states', idle1h: 'states', walk1h: 'states', walkfire: 'states', + strafe_left: 'loco', strafe_right: 'loco', walk_back: 'loco', run_back: 'loco', strafe_left_pistol: 'loco', + strafe_right_pistol: 'loco', walk_back_pistol: 'loco', reload_rifle: 'combat', reload_pistol: 'combat', + draw_rifle: 'combat', holster_rifle: 'combat', draw_pistol: 'combat', holster_pistol: 'combat', + hit_front: 'combat', hit_back: 'combat', hit_left: 'combat', hit_right: 'combat', hit_head: 'combat', + grenade_throw: 'combat', knife_idle: 'combat', knife_stab: 'combat', victory: 'ceremony', defeat: 'ceremony', + crouch_aim: 'loco', crouch_pistol: 'loco', crouch_turn_left: 'loco', crouch_turn_right: 'loco', + crouchwalk_back: 'loco', crouchwalk_back_left: 'loco', crouchwalk_back_right: 'loco', crouchwalk_fwd_left: 'loco', + crouchwalk_fwd_right: 'loco', crouchwalk_left: 'loco', crouchwalk_right: 'loco', death_crouch: 'ceremony', + death_front: 'ceremony', death_headshot_back: 'ceremony', death_headshot_front: 'ceremony', death_right: 'ceremony', + idle_aim: 'loco', jump_land: 'loco', jump_loop: 'loco', jump_pistol: 'loco', jump_start: 'loco', + run_back_left: 'loco', run_back_pistol: 'loco', run_back_right: 'loco', run_fwd_left: 'loco', run_fwd_right: 'loco', + run_left: 'loco', run_pistol: 'loco', run_right: 'loco', shoot_crouch: 'combat', shoot_pistol: 'combat', + sprint: 'loco', sprint_back: 'loco', sprint_back_left: 'loco', sprint_back_right: 'loco', sprint_fwd_left: 'loco', + sprint_fwd_right: 'loco', sprint_left: 'loco', sprint_right: 'loco', turn_left: 'loco', turn_right: 'loco', + walk_back_left: 'loco', walk_back_right: 'loco', walk_fwd_left: 'loco', walk_fwd_right: 'loco', + emote_salute: 'emotes', emote_danca: 'emotes', emote_breakdance_uprock: 'emotes', emote_capoeira_bencao: 'emotes', + }); + const assertFamilyParity = (classifier, label) => { + for (const [name, converter] of Object.entries(converterPackFamilies)) { + const expected = converter === 'emotes' ? 'emote' : converter; + if (classifier(name) !== expected) throw new Error(`${label}: family of ${name} is ${classifier(name)}, converter says ${expected}`); + } + }; + assertFamilyParity(clipFamily, 'Clip family mirror'); + console.log(`PASS Clip family mirror matches the converter's packFamily for ${Object.keys(converterPackFamilies).length} names`); + try { + assertFamilyParity(name => (name === 'hit_head' ? 'loco' : clipFamily(name)), 'Poisoned family mirror'); + throw new Error('Poisoned family mirror was not rejected'); + } catch (caught) { + if (!/Poisoned family mirror: family of hit_head is loco, converter says combat/.test(caught.message)) { + throw new Error(`Poisoned family mirror rejected for the wrong reason: ${caught.message}`); + } + console.log('PASS Poisoned family mirror rejected'); + } for (const state of requiredCharacterStates) { await expectRejection(`Missing required state ${state}`, new RegExp(`must have required property '${state}'`), { mutate: dropState(state) }); } @@ -200,7 +376,91 @@ try { await expectRejection('Morph weights channel on a mesh without morph targets', /animation "idle" has an invalid channel/, { replace: { 'animations/idle.glb': clipGlb('idle', { morph: 'no-targets' }) } }); await expectRejection('Clip without keyframes', /animation "death" has no keyframes/, { replace: { 'animations/death.glb': clipGlb('death', { keyframes: 0 }) } }); await expectRejection('Clip output count differs from keyframes', /output values that do not match its rotation keyframes/, { replace: { 'animations/crouch.glb': clipGlb('crouch', { keyframes: 2, outputValues: 1 }) } }); - await expectRejection('Same clip declared for two states', /Duplicate declared path/, { mutate: manifest => { manifest.animations.walk = manifest.animations.idle; } }); + await expectRejection('State pointed at another state per-state file', /animations\/idle\.glb: no animation named "walk"/, { + mutate: manifest => { + manifest.animations.walk = manifest.animations.idle; + manifest.files = manifest.files.filter(file => file.path !== 'animations/walk.glb'); + }, + }); + await expectRejection('Unknown extra clip name', /animations\.extra has an unknown clip name: moonwalk/, { + replace: { 'animations/extra/moonwalk.glb': clipGlb('moonwalk') }, + mutate: manifest => { manifest.animations.extra.moonwalk = { file: 'animations/extra/moonwalk.glb', duration: 1, loop: false, rootMotion: false, source: 'Not in the vocabulary' }; }, + }); + await expectRejection('Extra clip name equal to a state', /unknown clip name: idle/, { + mutate: manifest => { manifest.animations.extra.idle = manifest.animations.extra.strafe_left; }, + }); + await expectRejection('Bare emote prefix as an extra clip name', /unknown clip name: emote_/, { + replace: { 'animations/extra/emote-puro.glb': clipGlb('emote_') }, + mutate: manifest => { manifest.animations.extra.emote_ = { file: 'animations/extra/emote-puro.glb', duration: 1, loop: false, rootMotion: false, source: 'Bare prefix' }; }, + }); + await expectRejection('Extra clip name outside the key pattern', /\/animations\/extra must match pattern "\^\[a-z\]\[a-z0-9_\]\{1,40\}\$"/, { + replace: { 'animations/extra/Strafe-left.glb': clipGlb('strafe_left') }, + mutate: manifest => { manifest.animations.extra.Strafe_left = { file: 'animations/extra/Strafe-left.glb', duration: 1, loop: true, rootMotion: false, source: 'Uppercase key' }; }, + }); + await expectRejection('Family pack file missing from files', /Declared path is missing from files: animations\/extra\/loco\.glb/, { + mutate: manifest => { manifest.files = manifest.files.filter(file => file.path !== 'animations/extra/loco.glb'); }, + }); + await expectRejection('Extra clip file shared with a state', /Duplicate declared path: animations\/idle\.glb \(animations\.idle and animations\.extra\.strafe_left\)/, { + mutate: manifest => { manifest.animations.extra.strafe_left.file = manifest.animations.idle; }, + }); + await expectRejection('Extras counted in the byte budget', /over its \d+-byte budget/, { + mutate: manifest => { + const extraBytes = manifest.files.filter(file => file.path.startsWith('animations/extra/')).reduce((sum, file) => sum + file.bytes, 0); + manifest.budgets.bytes = manifest.files.reduce((sum, file) => sum + file.bytes, 0) - extraBytes; + }, + }); + await expectRejection('Extra clip misnamed inside its one-clip file', /animations\/extra\/sprint-fwd-left\.glb: no animation named "sprint_fwd_left"/, { + replace: { 'animations/extra/sprint-fwd-left.glb': clipGlb('SprintFwdLeft') }, + }); + await expectRejection('Key missing inside the family pack', /animations\/extra\/loco\.glb: no animation named "walk_back"/, { + replace: { 'animations/extra/loco.glb': clipsGlb(['strafe_left']) }, + }); + await expectRejection('Emote clip sharing a family-pack file', /emote clips keep one file per clip, but animations\/extra\/loco\.glb is shared by /, { + mutate: manifest => { manifest.animations.extra.emote_danca.file = 'animations/extra/loco.glb'; }, + }); + await expectRejection('Emote clips sharing one file', /emote clips keep one file per clip/, { + mutate: manifest => { manifest.animations.extra.emote_salute = { ...manifest.animations.extra.emote_danca, file: manifest.animations.extra.emote_danca.file }; }, + }); + await expectRejection('Declared family mismatching the clip name', /animations\.extra\.strafe_left declares family "combat" but its name belongs to "loco"/, { + mutate: manifest => { manifest.animations.extra.strafe_left.family = 'combat'; }, + }); + await expectRejection('Family outside the contract enum', /animations\/extra\/strafe_left\/family must be equal to one of the allowed values/, { + mutate: manifest => { manifest.animations.extra.strafe_left.family = 'states'; }, + }); + await expectRejection('Family pack mixing clip families', /animations\/extra\/loco\.glb mixes clip families \(loco and combat\)/, { + mutate: manifest => { manifest.animations.extra.reload_rifle = { file: 'animations/extra/loco.glb', duration: 2, loop: false, rootMotion: false, source: 'Combat clip in a loco pack' }; }, + }); + await expectRejection('States pack missing one state clip', /animations\/states\.glb: no animation named "walkfire"/, { + files: { + 'model/fixture-character.glb': modelGlb(), + 'previews/portrait.png': png, + 'animations/states.glb': clipsGlb(allStates.filter(state => state !== 'walkfire')), + 'animations/extra/loco.glb': clipsGlb(['strafe_left', 'walk_back']), + 'animations/extra/sprint-fwd-left.glb': clipGlb('sprint_fwd_left'), + 'animations/extra/emote-danca.glb': clipGlb('emote_danca'), + }, + mutate: manifest => { + for (const state of allStates) manifest.animations[state] = 'animations/states.glb'; + }, + }); + await expectRejection('Second buffer without the meshopt fallback marker', /GLB validation failed for animations\/extra\/loco\.glb: GLB must contain one self-contained buffer/, { + replace: { 'animations/extra/loco.glb': meshoptClipsGlb(['strafe_left', 'walk_back'], { markFallback: false }) }, + }); + await expectRejection('Meshopt stream past the BIN chunk', /bufferView 1 has an out-of-bounds meshopt stream/, { + replace: { 'animations/extra/loco.glb': meshoptClipsGlb(['strafe_left', 'walk_back'], { overshootStream: true }) }, + }); + await expectRejection('Extra clip file is not a GLB', /animations\/extra\/strafe_left\/file must match pattern/, { + mutate: manifest => { manifest.animations.extra.strafe_left.file = 'animations/extra/strafe-left.gltf'; }, + }); + await expectRejection('Extra entry missing a required field', /animations\/extra\/strafe_left must have required property 'duration'/, { + mutate: manifest => { delete manifest.animations.extra.strafe_left.duration; }, + }); + await expectRejection('Extra entry with a mistyped loop', /animations\/extra\/strafe_left\/loop must be boolean/, { + mutate: manifest => { manifest.animations.extra.strafe_left.loop = 'yes'; }, + }); + await expectRejection('Extra entry with a non-numeric duration', /animations\/extra\/strafe_left\/duration must be number/, { + mutate: manifest => { manifest.animations.extra.strafe_left.duration = '0.8'; }, + }); await expectRejection('Wrong skeleton id', /\/skeleton must be equal to constant/, { mutate: manifest => { manifest.skeleton = 'mixamo-65'; } }); const renamed = meshy28Joints.map(([name, parent]) => [name === 'LeftForeArm' ? 'LeftElbow' : name, parent === 'LeftForeArm' ? 'LeftElbow' : parent]); diff --git a/tools/lib/character-pack.mjs b/tools/lib/character-pack.mjs index 2bef959..982f076 100644 --- a/tools/lib/character-pack.mjs +++ b/tools/lib/character-pack.mjs @@ -4,6 +4,87 @@ import { inspectGlb, readAccessorComponent, readGlb } from './glb-inspect.mjs'; export const requiredCharacterStates = Object.freeze(['idle', 'walk', 'run', 'shoot', 'death', 'crouch', 'crouchwalk', 'jump']); export const optionalCharacterStates = Object.freeze(['idle1h', 'walk1h', 'walkfire']); +// Optional named clips a pack may carry beyond the states, as `animations.extra` entries. +// Fixed names for locomotion, weapon handling, damage reactions, melee and round outcomes, +// plus free-form emotes under the `emote_` prefix (at least one character after the prefix). +// State names are never valid extra names, so the two key spaces stay disjoint. +export const coreExtraClipNames = Object.freeze([ + 'strafe_left', 'strafe_right', 'walk_back', 'run_back', + 'strafe_left_pistol', 'strafe_right_pistol', 'walk_back_pistol', + 'reload_rifle', 'reload_pistol', 'draw_rifle', 'holster_rifle', 'draw_pistol', 'holster_pistol', + 'hit_front', 'hit_back', 'hit_left', 'hit_right', 'hit_head', + 'grenade_throw', 'knife_idle', 'knife_stab', 'victory', 'defeat', +]); +// Every name the animation conversion library proposes (branch feat/animation-conversion-20261109, +// tools/lib/animation-library.mjs PROPOSED_EXTRA_NAMES; snapshot 2026-11-09 — each name is used +// by at least one key of library/index.json). 8-way diagonals follow `__`; +// cardinal walk keeps strafe_left/strafe_right/walk_back and run backwards keeps run_back. Kept +// sorted to diff against the converter's own sorted export. The converter must import +// `extraClipNames` from this module as the single source instead of maintaining its own copy. +export const converterExtraClipNames = Object.freeze([ + 'crouch_aim', 'crouch_pistol', 'crouch_turn_left', 'crouch_turn_right', + 'crouchwalk_back', 'crouchwalk_back_left', 'crouchwalk_back_right', + 'crouchwalk_fwd_left', 'crouchwalk_fwd_right', 'crouchwalk_left', 'crouchwalk_right', + 'death_crouch', 'death_front', 'death_headshot_back', 'death_headshot_front', 'death_right', + 'idle_aim', 'jump_land', 'jump_loop', 'jump_pistol', 'jump_start', + 'run_back_left', 'run_back_pistol', 'run_back_right', 'run_fwd_left', 'run_fwd_right', + 'run_left', 'run_pistol', 'run_right', + 'shoot_crouch', 'shoot_pistol', 'sprint', 'sprint_back', 'sprint_back_left', 'sprint_back_right', + 'sprint_fwd_left', 'sprint_fwd_right', 'sprint_left', 'sprint_right', + 'turn_left', 'turn_right', + 'walk_back_left', 'walk_back_right', 'walk_fwd_left', 'walk_fwd_right', +]); +export const extraClipNames = Object.freeze([...coreExtraClipNames, ...converterExtraClipNames]); +export const extraClipPrefixes = Object.freeze(['emote_']); + +const extraClipKeyPattern = /^[a-z][a-z0-9_]{1,40}$/; +const stateNameSet = new Set([...requiredCharacterStates, ...optionalCharacterStates]); + +// Clip family of a name, mirroring the converter's `packFamily` (branch +// feat/animation-conversion-20261109, tools/lib/clip-pack.mjs). That branch is stacked on this +// one, so it cannot be imported here without a circular dependency; the mirror is kept honest by +// a snapshot parity check in tools/checks/character-pack-check.mjs, and the converter must import +// `clipFamily` from this module once it rebases. Two deliberate vocabulary differences: the +// contract says `emote` where the converter's pack id is `emotes` (emotes are never packed as a +// family file), and `states` is a valid answer here even though only the converter emits it. +export const extraClipFamilies = Object.freeze(['loco', 'combat', 'ceremony', 'emote']); +export function clipFamily(name) { + if (stateNameSet.has(name)) return 'states'; + if (name.startsWith('emote_')) return 'emote'; + if (/^(victory|defeat|death_)/.test(name)) return 'ceremony'; + if (/^(reload_|draw_|holster_|hit_|grenade_|knife_|shoot_)/.test(name)) return 'combat'; + return 'loco'; +} + + +// Single-source invariant: the published vocabulary must equal the core contract names plus the +// converter set above. A name the converter proposes but the contract lacks, a dropped core name, +// a name outside both sets, a duplicate, a state collision or a pattern break all fail here. +// `tools/checks/character-pack-check.mjs` runs this against the real exports and against +// synthetic mutants; the converter branch runs it with its own proposed names once it adopts +// the import. +export function assertExtraClipVocabulary({ vocabulary = extraClipNames, converter = converterExtraClipNames } = {}) { + const seen = new Set(); + for (const name of vocabulary) { + if (seen.has(name)) throw new Error(`duplicate extra clip name in the vocabulary: ${name}`); + seen.add(name); + if (stateNameSet.has(name)) throw new Error(`extra clip name collides with a state name: ${name}`); + if (!extraClipKeyPattern.test(name)) throw new Error(`extra clip name breaks the key pattern: ${name}`); + } + const missing = converter.filter(name => !seen.has(name)); + if (missing.length) throw new Error(`converter clip names missing from the vocabulary: ${missing.join(', ')}`); + const lostCore = coreExtraClipNames.filter(name => !seen.has(name)); + if (lostCore.length) throw new Error(`core extra clip names missing from the vocabulary: ${lostCore.join(', ')}`); + const expected = new Set([...coreExtraClipNames, ...converter]); + const orphans = vocabulary.filter(name => !expected.has(name)); + if (orphans.length) throw new Error(`extra clip names outside the core and converter sets: ${orphans.join(', ')}`); +} + +export function isExtraClipName(name) { + return extraClipNames.includes(name) + || extraClipPrefixes.some(prefix => name.length > prefix.length && name.startsWith(prefix)); +} + // The shared Meshy humanoid skeleton every runtime clip is baked against: skin joint order // and the nearest joint ancestor of each joint (null for the root). Derived from the client // donor `public/models/characters/mst.glb` and the 37 offline-rigged lote30 characters; the @@ -29,13 +110,47 @@ const imageMagic = [ export function characterRoleEntries(manifest) { if (manifest.kind !== 'character') return []; const entries = [{ role: 'model', path: manifest.model }]; - for (const [state, file] of Object.entries(manifest.animations || {})) entries.push({ role: `animations.${state}`, path: file }); + for (const [state, file] of Object.entries(manifest.animations || {})) { + if (state === 'extra') continue; + entries.push({ role: `animations.${state}`, path: file }); + } + entries.push(...characterExtraEntries(manifest)); for (const role of ['previews', 'evidence']) { for (const file of manifest[role] || []) entries.push({ role, path: file }); } return entries; } +// Extra-clip role entries. This is also the structural gate that rejects names outside the +// vocabulary (bare prefixes, state names, anything else), wrong `family` declarations and illegal +// file sharing during validateManifestStructure, before any payload is hashed. Non-emote keys may +// share one family-pack file (all of them must belong to a single family, exactly like the +// converter packs them); emote keys always keep one file per key. +export function characterExtraEntries(manifest) { + const extras = manifest.animations?.extra; + if (extras === undefined) return []; + if (typeof extras !== 'object' || Array.isArray(extras)) throw new Error('animations.extra must be an object keyed by extra clip name'); + const entries = []; + const namesByFile = new Map(); + for (const [name, entry] of Object.entries(extras)) { + if (!isExtraClipName(name)) throw new Error(`animations.extra has an unknown clip name: ${name}`); + if (entry?.family !== undefined && entry.family !== clipFamily(name)) { + throw new Error(`animations.extra.${name} declares family "${entry.family}" but its name belongs to "${clipFamily(name)}"`); + } + entries.push({ role: `animations.extra.${name}`, path: entry?.file }); + namesByFile.set(entry?.file, [...(namesByFile.get(entry?.file) || []), name]); + } + for (const [file, names] of namesByFile) { + if (names.length < 2) continue; + if (names.some(name => name.startsWith('emote_'))) { + throw new Error(`animations.extra: emote clips keep one file per clip, but ${file} is shared by ${names.join(', ')}`); + } + const families = [...new Set(names.map(clipFamily))]; + if (families.length > 1) throw new Error(`animations.extra: ${file} mixes clip families (${families.join(' and ')})`); + } + return entries; +} + const pairKey = ([name, parent]) => `${name}<${parent ?? ''}`; function multiset(pairs) { @@ -178,10 +293,29 @@ export async function validateCharacterPack(manifest, absolutes) { throw new Error(`${manifest.model}: ${model.triangles} triangles, over the ${manifest.budgets.triangles}-triangle budget`); } + // States may share one states.glb and extras may share one family-pack file, so every + // animation GLB is read once per file, not once per clip that points at it. Animation packs + // accept the converter's EXT_meshopt_compression fallback-buffer layout; the model does not + // (its skin bytes are read raw, so it keeps the strict single-buffer container). + const documents = new Map(); + const animationDocument = async file => { + if (!documents.has(file)) documents.set(file, (await readGlb(absolutes.get(file), file, { allowMeshoptFallback: true })).document); + return documents.get(file); + }; for (const [state, file] of Object.entries(manifest.animations)) { - const { document } = await readGlb(absolutes.get(file), file); - assertStateAnimation(document, state, file); + if (state === 'extra') continue; + assertStateAnimation(await animationDocument(file), state, file); + } + for (const [name, entry] of Object.entries(manifest.animations.extra || {})) { + assertStateAnimation(await animationDocument(entry.file), name, entry.file); } for (const file of manifest.previews) await assertImage(file, absolutes.get(file)); - return { triangles: model.triangles, bytes: characterDeclaredBytes(manifest), joints: meshy28Joints.length, animations: Object.keys(manifest.animations).length }; + const states = Object.keys(manifest.animations).filter(key => key !== 'extra').length; + return { + triangles: model.triangles, + bytes: characterDeclaredBytes(manifest), + joints: meshy28Joints.length, + animations: states, + extraClips: Object.keys(manifest.animations.extra || {}).length, + }; } diff --git a/tools/lib/glb-inspect.mjs b/tools/lib/glb-inspect.mjs index e60e7de..5593282 100644 --- a/tools/lib/glb-inspect.mjs +++ b/tools/lib/glb-inspect.mjs @@ -18,7 +18,11 @@ function integer(value) { // Parses and bounds-checks the GLB 2 container, buffer views and accessors without // interpreting any scene content. Returns the JSON document and the BIN chunk bytes. -export async function readGlb(absolute, label = absolute) { +// `allowMeshoptFallback` also accepts the EXT_meshopt_compression layout the animation +// converter emits (buffer 0 = compressed stream in the BIN chunk, further buffers marked +// `EXT_meshopt_compression.fallback` = virtual uncompressed views that exist only logically); +// callers that read raw component bytes (the character model) keep the strict single buffer. +export async function readGlb(absolute, label = absolute, { allowMeshoptFallback = false } = {}) { const handle = await open(absolute, 'r'); try { const { size } = await handle.stat(); @@ -45,14 +49,32 @@ export async function readGlb(absolute, label = absolute) { if (!Array.isArray(document.accessors) || !Array.isArray(document.bufferViews) || !Array.isArray(document.buffers)) { fail(label, 'missing accessor, bufferView or buffer inventories'); } - if (document.buffers.length !== 1 || document.buffers[0].uri !== undefined || !integer(document.buffers[0].byteLength) || document.buffers[0].byteLength > binBytes) { + const meshoptFallback = allowMeshoptFallback && document.buffers.slice(1).every( + buffer => buffer.uri === undefined && integer(buffer.byteLength) + && buffer.extensions?.EXT_meshopt_compression?.fallback === true, + ); + if (document.buffers[0].uri !== undefined || !integer(document.buffers[0].byteLength) || document.buffers[0].byteLength > binBytes + || (document.buffers.length > 1 && !meshoptFallback)) { fail(label, 'GLB must contain one self-contained buffer within the BIN chunk'); } for (const [index, view] of document.bufferViews.entries()) { - if (view.buffer !== 0 || !integer(view.byteOffset ?? 0) || !integer(view.byteLength) || view.byteLength < 1) fail(label, `invalid bufferView ${index}`); + if (!integer(view.byteOffset ?? 0) || !integer(view.byteLength) || view.byteLength < 1) fail(label, `invalid bufferView ${index}`); const offset = view.byteOffset ?? 0; - if (offset + view.byteLength > document.buffers[0].byteLength || offset + view.byteLength > binBytes) fail(label, `bufferView ${index} exceeds its buffer`); + const compression = view.extensions?.EXT_meshopt_compression; + if (view.buffer === 0) { + if (offset + view.byteLength > document.buffers[0].byteLength || offset + view.byteLength > binBytes) fail(label, `bufferView ${index} exceeds its buffer`); + } else if (meshoptFallback && compression !== undefined + && document.buffers[view.buffer]?.extensions?.EXT_meshopt_compression?.fallback === true) { + // The bytes live in the compressed stream: bounds-check the stream range instead. + const streamOffset = compression.byteOffset ?? 0; + if (compression.buffer !== 0 || !integer(streamOffset) || !integer(compression.byteLength) || compression.byteLength < 1 + || streamOffset + compression.byteLength > document.buffers[0].byteLength) { + fail(label, `bufferView ${index} has an out-of-bounds meshopt stream`); + } + } else { + fail(label, `bufferView ${index} exceeds its buffer`); + } if (view.byteStride !== undefined && (!integer(view.byteStride) || view.byteStride < 4 || view.byteStride > 256 || view.byteStride % 4 !== 0)) { fail(label, `invalid byteStride on bufferView ${index}`); } diff --git a/tools/lib/pack.mjs b/tools/lib/pack.mjs index 6bc9139..d81f934 100644 --- a/tools/lib/pack.mjs +++ b/tools/lib/pack.mjs @@ -59,12 +59,18 @@ export function validateManifestStructure(manifest) { fileIndexes.set(file.path, index); } + // One role kind per file. Many `animations.` roles may share one state-pack file and + // many `animations.extra.` roles may share one family-pack file, but a file can never mix + // state and extra clips, nor take a non-animation role on the side. + const roleKind = role => (role.startsWith('animations.extra.') ? 'animations.extra' : role.startsWith('animations.') ? 'animations.state' : role); const roleOwners = new Map(); for (const entry of [...mapRoleEntries(manifest), ...characterRoleEntries(manifest)]) { assertPackageRelativePath(entry.path, `${entry.role} path`); assertNotExecutableJavaScript(entry.path); - if (roleOwners.has(entry.path)) { - throw new Error(`Duplicate declared path: ${entry.path} (${roleOwners.get(entry.path)} and ${entry.role})`); + const kind = roleKind(entry.role); + const owner = roleOwners.get(entry.path); + if (owner !== undefined && roleKind(owner) !== kind) { + throw new Error(`Duplicate declared path: ${entry.path} (${owner} and ${entry.role})`); } if (!fileIndexes.has(entry.path)) throw new Error(`Declared path is missing from files: ${entry.path}`); roleOwners.set(entry.path, entry.role);