Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

feat([issue-3017]): let sprite atlases hold a track with no facing, and gate animation on the registry

[._.]/ Adam Eivy72579065d6a1
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 1a5e2d4b94..a8cee7917a 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -44,6 +44,7 @@
## Sprite Manager
+- **[issue-3017] Sprite sheets can now describe an animation that has no facing — the groundwork for animating places and objects** — every animation in a sprite sheet was assumed to be a character walk: eight rows, one per direction. That is wrong for most of what would come next. A tree moving in the wind, water, a flickering lamp — none of them face anywhere, and a sheet that insisted on eight facings for them would be seven-eighths empty with no way to say so. An animation now states whether it is directional, and one with no facing occupies a single row that the published layout file marks as such (`"rows": 1`), so a game reads that one row no matter which way anything is pointing instead of sampling seven blank ones. Everything still ships as **one** sheet per record — a second image would double what a game has to load and bind, and the unused cells compress to almost nothing. The rule that all of a walk's directions must agree on frame count and speed now applies *within* each animation rather than across the whole sheet, so a three-frame ambient loop can sit beside a twelve-frame walk. The other half is the gate: animation was refused outright for anything that wasn't a character, which is why **Places** and **Objects** had no animation path at all — that check now asks which animations a record kind can actually carry, so admitting those kinds becomes a matter of adding the animation rather than unpicking the refusal. To be clear about what this does and doesn't do: it is the sheet-and-publishing groundwork, not a feature you can use yet. No animation that places or objects can carry exists so far, and rendering and approving one is still walk-shaped — that work is tracked separately. Nothing changes for an existing character: walks compile to byte-identical sheets, already-published sheets are untouched until you republish, and the layout file gains the new row field additively.
- **[issue-3021] Walk cycles no longer jitter — the character stays put while only the limbs move** — every frame of a walk was being positioned independently of its neighbours, so the character slid sideways as the arms swung and bobbed up and down when a stray speck of leftover background sat below the feet. Two separate things caused it. First, each frame was horizontally anchored on wherever *its own* hips happened to measure, which drifts as the legs scissor and could flip by a pixel on alternating frames — a walk rendered in place has a fixed hip position by definition, so all frames of a direction now share one. Second, the compiler that builds the final sprite sheet was re-positioning every cell from scratch on a *different* rule than the packer had used (the silhouette's centre rather than the hips), which threw away the alignment and let a swinging arm drag the whole body with it — it now carries the packer's anchor through instead. The feet also now land on the ground line based on the actual sole rather than the single lowest visible pixel, so one leftover speck of background can't lift the body — at both stages, since fixing only the first was silently undone by the second. The standing (idle) pose is anchored the same way as the walk frames now too, so a character no longer pops sideways the moment it starts or stops walking. Feet still sit exactly on the ground line in every frame, so nothing changes for a game using these sheets. Existing walks keep their packed frames until you reprocess them — but simply recompiling one picks up the corrected alignment and saves it as a new atlas version, so you can fix a character's jitter without re-rendering anything.
- **[issue-3020] Reprocessing a walk at a new frame count now updates every preview immediately, instead of showing the old art** — re-deriving a direction from 8 frames to 12 left the loop preview playing a violently jumpy, mis-centered animation: it had already picked up the new 12-frame timing, but your browser was still painting the *previous* 8-frame image, so it stepped 12 times across a picture that only had 8 poses in it. It looked like the sprite had been packed off-center — the packed art was fine all along, and reloading the page fixed it. Every sprite asset's address now carries a fingerprint of its contents, so the moment a reprocess changes the art the loop preview, the Loop Trimmer, and the asset browser and inspector all repaint on their own. That last part matters because the same reprocess also rewrites the individual pose frames and the contrast review sheet — the very things you'd open to check whether the strip really was repacked, which until now kept showing you the pre-reprocess art. This also covers a reprocess that changes the art *without* changing the frame count (a different cycle window, different background-removal settings), which previously went unnoticed entirely — and because the fingerprint only changes when the art does, unchanged assets are still served from cache rather than re-downloaded over Tailscale.
- **[issue-3022] Walk cards now show the clip length grok actually delivered** — the Clip picker offers 6s and 10s, and it turns out those really are the only two lengths available: asking for a shorter clip to save render time doesn't work, because grok renders 6 seconds regardless and charges the same for it. Rather than leave that buried in a code comment (where it had already drifted into two comments claiming opposite things), each walk direction now reports the length of the clip it actually got, measured from the file — and says so in amber if that differs from what was requested. So if grok's options ever change, you'll see it on the card instead of having to guess.
diff --git a/docs/features/sprite-export-contract.md b/docs/features/sprite-export-contract.md
index bf095fb47d..5b64e379f9 100644
--- a/docs/features/sprite-export-contract.md
+++ b/docs/features/sprite-export-contract.md
@@ -18,7 +18,9 @@ The compiler (`server/services/sprites/atlas.js`) produces one PNG: a fixed-cell
`N` is read from the approved run manifests — every direction of a track must share it — so the atlas width tracks the authored count. **That makes the column layout a moving target for anything that hardcodes it.**
-Frame-count and fps uniformity is a **within-track** rule, never a between-track one: all 8 facings of a given track share a column span because the atlas is a rectangular grid, but two different tracks may legally differ in both length and speed (a four-frame action beside a twelve-frame walk). Each track's authoring range comes from its own row in `server/services/sprites/animationTracks.js`, and its column span is recorded in `geometry.tracks` and republished in the sidecar. Only `walk` is registered today.
+Frame-count and fps uniformity is a **within-track** rule, never a between-track one: every facing of a given track shares a column span because the atlas is a rectangular grid, but two different tracks may legally differ in both length and speed (a four-frame action beside a twelve-frame walk). Each track's authoring range comes from its own row in `server/services/sprites/animationTracks.js`, and its column span is recorded in `geometry.tracks` and republished in the sidecar. Only `walk` is registered today.
+
+**Not every track has eight rows.** A track is *directional* (one row per facing — a character walk) or *non-directional* (one row, period — a tree moving in the wind, water, a flickering lamp, which have no facing at all). A non-directional track occupies **row 0** across its whole column span and leaves the remaining rows transparent. Its span says so: `rows: 1`. There is still exactly **one atlas per record** — a second image would double the publish and binding surface for no gain, and the transparent cells cost only file size, which PNG compresses to near nothing.
Non-walk tracks namespace their column labels with the track id (`scanner-00`, `scanner-01`, …). Walk keeps its historical labels — the named gait phases at 8 frames, positional `frame-NN` at any other length — so existing and imported atlases round-trip unchanged.
@@ -51,8 +53,8 @@ Nothing else crosses. The compile manifest, the run provenance, the trims, and t
"columns": ["idle", "left-contact", "…", "right-up"],
"columnCount": 9,
"tracks": {
- "idle": { "start": 0, "count": 1 },
- "walk": { "start": 1, "count": 8 }
+ "idle": { "start": 0, "count": 1, "rows": 8 },
+ "walk": { "start": 1, "count": 8, "rows": 8 }
},
"walkFrameCount": 8,
"previewFps": 12,
@@ -64,6 +66,7 @@ Consumer guidance:
- **Resolve columns by name, not by constant.** `tracks` gives each animation track a column span, so a walk of any length — and any additional track (a four-frame scanner action, a three-frame ambient loop) — is additive rather than a breaking re-read. A track that isn't in the grid simply isn't in `tracks`; don't assume one is present. `columns` is the flat list for anything that wants raw names.
- **`tracks` tiles `columns` exactly.** The spans are contiguous, non-overlapping, and sum to `columnCount` — so `cellSize × columnCount` is the PNG width and a span always addresses real pixels. A sidecar whose spans disagreed with its own column list is refused at publish rather than shipped.
+- **Read `rows` before you index by facing.** A span's `rows` is how many of the atlas's rows that track actually occupies. `rows === rowCount` is the familiar case (one row per facing, indexed through `rowOrder`); **`rows: 1` means the track lives on row 0 only** and you should sample row 0 no matter which way anything is facing — the other rows of those columns are transparent. Every span carries the field; a sidecar written before it existed describes only directional tracks, so treating a missing `rows` as full height is correct.
- **Verify before you trust.** `sourceAtlasSha256` identifies the atlas the layout describes. The sidecar is written *before* the PNG on each publish, so a partially-completed publish is detectable (hash mismatch) rather than silent.
- **The sidecar carries no timestamp** — identical geometry produces byte-identical content, so an unchanged republish rewrites nothing.
- The sidecar shares the PNG's per-repo write serialization and its occupied-destination guard: an atlas whose sidecar was deleted gets it back on the next publish, and a file at that path PortOS didn't write (no `kind: portos-sprite-atlas-layout`, or not valid JSON at all) is never replaced without an explicit overwrite acknowledgment. It has no *divergence* guard — unlike the PNG, a PortOS-written sidecar someone hand-edited is simply regenerated, since it is derived data.
@@ -94,8 +97,9 @@ Two mechanisms guard that:
| Path | Role |
|---|---|
| `server/services/sprites/atlas.js` | Compiles the atlas; owns the geometry block and the pre-pixel up-to-date check |
-| `server/services/sprites/atlasGrid.js` | The grid itself: column spans per track, within-track uniformity, reading a persisted (or legacy) grid back |
-| `server/services/sprites/animationTracks.js` | One row per animation track — its bounds, defaults, and directionality |
+| `server/services/sprites/atlasGrid.js` | The grid itself: column spans and row spans per track, within-track uniformity, reading a persisted (or legacy) grid back |
+| `server/services/sprites/animationTracks.js` | One row per animation track — its bounds, defaults, directionality, and which record kinds may carry it |
+| `server/services/sprites/reference.js` | The two animation gates: `requireCharacter` (walk workflow) and `requireAnimatable` (compile/publish) |
| `server/services/sprites/atlasLayout.js` | Builds the sidecar payload; compares geometry against a runtime contract |
| `server/services/sprites/publish.js` | Binding validation, the publish-time guard, the atomic PNG + sidecar write |
| `server/services/sprites/walkBounds.js` | The authorable frame-count / fps ranges |
diff --git a/server/routes/sprites.js b/server/routes/sprites.js
index a6e44e4f23..a40919bf8b 100644
--- a/server/routes/sprites.js
+++ b/server/routes/sprites.js
@@ -44,6 +44,7 @@ import {
listReferenceSources, listSpriteThumbnails, forkSprite,
} from '../services/sprites/reference.js';
import { resolveSpriteAssetPrompt } from '../services/sprites/assetPrompt.js';
+import { WALK_TRACK, kindSupportsTrack, tracksForKind } from '../services/sprites/animationTracks.js';
import {
getWalkState, startWalkGeneration, approveWalkDirection, rerunWalkPostprocess, unlockWalkSet,
reopenWalkDirection, setWalkTarget, getWalkSourceFrames, unlockDirectionalAnchor,
@@ -100,14 +101,20 @@ router.post('/import', asyncHandler(async (req, res) => {
router.get('/:id', asyncHandler(async (req, res) => {
const detail = await getRecordWithAssets(req.params.id);
if (!detail) throw new ServerError('Sprite record not found', { status: 404, code: 'NOT_FOUND' });
- const isCharacter = detail.record.kind === 'character';
- const [reference, walk, atlas] = isCharacter
- ? await Promise.all([
- getReferenceSet(req.params.id),
- getWalkState(req.params.id),
- getAtlasState(req.params.id),
- ])
- : [null, null, null];
+ // Two questions, not one (#3017). `reference`/`walk` are the gait-shaped
+ // workflow, so they follow the WALK track's record kinds — the same thing
+ // requireCharacter asks. `atlas` follows the track-presence gate that
+ // compileAtlas/publishAtlas use, so a record kind unlocked by a future
+ // non-directional track gets its compiled atlas back here too; spelling this
+ // as `kind === 'character'` would have left the UI blank for exactly the
+ // records the registry had just admitted.
+ const { kind } = detail.record;
+ const runsWalk = kindSupportsTrack(kind, WALK_TRACK);
+ const [reference, walk, atlas] = await Promise.all([
+ runsWalk ? getReferenceSet(req.params.id) : null,
+ runsWalk ? getWalkState(req.params.id) : null,
+ tracksForKind(kind).length ? getAtlasState(req.params.id) : null,
+ ]);
res.json({ ...detail, reference, walk, atlas });
}));
diff --git a/server/services/sprites/animationTracks.js b/server/services/sprites/animationTracks.js
index c65f9d679c..d4a714686c 100644
--- a/server/services/sprites/animationTracks.js
+++ b/server/services/sprites/animationTracks.js
@@ -27,6 +27,16 @@
* for reasons no message explains. Absent (`undefined`/`null`) means "the
* default track" and resolves to `walk`, which is what preserves every existing
* call site; an empty string is *present and invalid*, so it throws.
+ *
+ * **Which records may carry a track is registry data too (#3017).** The whole
+ * sprite animation surface used to be gated on a literal `kind !== 'character'`
+ * check, which is why `place` and `object` records had no animation path at all
+ * — a tree in the wind or a flickering lamp was unrepresentable not because the
+ * atlas couldn't hold it but because the gate refused the record. Each row now
+ * declares the record `kinds` that may carry it, and the gates ask the registry
+ * (`tracksForKind` / `kindSupportsTrack`) instead of naming a kind. Walk stays
+ * character-only, so behavior is unchanged today; a row that lists `place` is
+ * all it takes to unlock those records, with no gate edit anywhere.
*/
/** The default track — the only one that exists today. */
@@ -41,6 +51,11 @@ export const WALK_TRACK = 'walk';
* precedence chain (see `animationTargets.js`).
* - `directional` — true when the track occupies one atlas ROW per facing
* (walk: 8 directions); a future ambient loop would be false (one row).
+ * Load-bearing since #3017: `trackRowCount` turns it into the number of rows
+ * the track's cells may occupy, and the compiler refuses a cell outside them.
+ * - `kinds` — the sprite record kinds that may carry this track. The animation
+ * gates read this instead of testing for `'character'`, so unlocking a record
+ * kind is a data change here rather than a hunt through the service layer.
* - `contractFrameCountField` / `contractFpsField` — the field names this track
* occupies in an app's `publishBinding.runtimeContract` (#2982). Named here so
* the app rung of the precedence chain is track-driven rather than hard-coded
@@ -52,6 +67,10 @@ export const ANIMATION_TRACKS = Object.freeze({
id: WALK_TRACK,
label: 'Walk cycle',
directional: true,
+ // A walk cycle is a character gait — a place or an object has no gait to
+ // author, so walk stays character-only and every existing gate keeps its
+ // exact behavior. What changed in #3017 is only WHERE that fact lives.
+ kinds: Object.freeze(['character']),
minFrameCount: 6,
maxFrameCount: 16,
defaultFrameCount: 12,
@@ -93,6 +112,14 @@ export function assertAnimationTrackRows(tracks) {
if (row.id !== id) throw new Error(`animationTracks: row '${id}' declares mismatched id '${row.id}'`);
if (typeof row.label !== 'string' || !row.label) throw new Error(`animationTracks: track '${id}' needs a label`);
if (typeof row.directional !== 'boolean') throw new Error(`animationTracks: track '${id}' needs a boolean 'directional'`);
+ // A row with no kinds is unreachable work: nothing could ever carry it, and
+ // the gate would refuse every record with a message blaming the record.
+ if (!Array.isArray(row.kinds) || !row.kinds.length) {
+ throw new Error(`animationTracks: track '${id}' needs a non-empty 'kinds' array`);
+ }
+ if (row.kinds.some((kind) => typeof kind !== 'string' || !kind)) {
+ throw new Error(`animationTracks: track '${id}' has a non-string entry in 'kinds'`);
+ }
for (const field of ['minFrameCount', 'maxFrameCount', 'defaultFrameCount', 'minFps', 'maxFps', 'defaultFps']) {
if (!Number.isInteger(row[field])) throw new Error(`animationTracks: track '${id}' needs an integer '${field}'`);
}
@@ -160,6 +187,49 @@ export function getAnimationTrack(id, tracks = ANIMATION_TRACKS) {
return tracks[key];
}
+/**
+ * The atlas rows one track's cells may occupy, given how many facings the grid
+ * has: every row for a directional track, exactly one (row 0) for a
+ * non-directional one.
+ *
+ * `directionCount` is a PARAMETER rather than an import because this module is
+ * a true leaf — `animationTracks.test.js` asserts it imports nothing at all —
+ * and the canonical direction list lives in `prompts.js`. Callers that already
+ * know the grid pass its real height; `atlasGrid.js` supplies the default.
+ */
+export function trackRowCount(id, directionCount, tracks = ANIMATION_TRACKS) {
+ const row = getAnimationTrack(id, tracks);
+ if (!Number.isInteger(directionCount) || directionCount < 1) {
+ throw new Error(`animationTracks: trackRowCount needs a positive direction count, got ${directionCount}`);
+ }
+ return row.directional ? directionCount : 1;
+}
+
+/**
+ * Every track a record of this `kind` may carry, in registration order.
+ *
+ * This is the whole of the "track-presence gate" (#3017): a record kind with no
+ * rows has no animation path, and a kind with at least one does — replacing the
+ * literal `kind !== 'character'` test the sprite services used to make. An
+ * absent/blank kind matches nothing rather than defaulting to a kind, so a
+ * malformed record can't inherit character's permissions.
+ */
+export function tracksForKind(kind, tracks = ANIMATION_TRACKS) {
+ if (typeof kind !== 'string' || !kind) return [];
+ return Object.values(tracks).filter((row) => row.kinds.includes(kind));
+}
+
+/**
+ * True when a record of `kind` may carry the named track. A predicate, not a
+ * boundary: an unrecognized track id answers `false` rather than throwing,
+ * because the gates call this to DECIDE. The row is an O(1) lookup, so this
+ * asks it directly instead of rebuilding `tracksForKind`'s array to re-find it.
+ */
+export function kindSupportsTrack(kind, id, tracks = ANIMATION_TRACKS) {
+ if (!isAnimationTrack(id, tracks)) return false;
+ return typeof kind === 'string' && !!kind && tracks[id].kinds.includes(kind);
+}
+
// Round-then-clamp, with unusable input (NaN, non-numeric) falling back to the
// knob's default rather than to a bound — the two knobs differ only in which
// three row fields they read.
diff --git a/server/services/sprites/animationTracks.test.js b/server/services/sprites/animationTracks.test.js
index 2c75123e71..ad5b1f5928 100644
--- a/server/services/sprites/animationTracks.test.js
+++ b/server/services/sprites/animationTracks.test.js
@@ -15,8 +15,10 @@ import { dirname, join } from 'path';
import {
WALK_TRACK, ANIMATION_TRACKS, ANIMATION_TRACK_IDS,
isAnimationTrack, getAnimationTrack, clampTrackFrameCount, clampTrackFps,
- assertAnimationTrackRows,
+ assertAnimationTrackRows, trackRowCount, tracksForKind, kindSupportsTrack,
} from './animationTracks.js';
+import { SPRITE_RECORD_KINDS } from './recordsLogic.js';
+import { AMBIENT_TRACK_ROW } from './spriteTestFixtures.js';
import {
staticImportSpecifiers, staticImportClosure, specifierMatchesPackage,
} from '../../lib/staticImportGraph.js';
@@ -36,6 +38,9 @@ describe('the registry rows', () => {
expect(getAnimationTrack(WALK_TRACK)).toMatchObject({
id: 'walk',
directional: true,
+ // #3017 moved the gate into the registry without loosening it: a walk
+ // cycle is a character gait, so `place`/`object` are still refused.
+ kinds: ['character'],
minFrameCount: 6,
maxFrameCount: 16,
defaultFrameCount: 12,
@@ -56,6 +61,7 @@ describe('the registry rows', () => {
expect(row.id, `${id}.id must match its registry key`).toBe(id);
expect(typeof row.label).toBe('string');
expect(typeof row.directional).toBe('boolean');
+ expect(Array.isArray(row.kinds) && row.kinds.length > 0, `${id}.kinds must be non-empty`).toBe(true);
expect(typeof row.contractFrameCountField).toBe('string');
// `null` is legal here — a track whose speed an app has no say in — so
// this must stay as permissive as the module-load guard, or the first row
@@ -110,6 +116,14 @@ describe('the module-load row guard', () => {
.toThrow(/'scanner\.contractFrameCountField' and 'scanner\.contractFpsField'/);
});
+ it('rejects a row no record kind can carry (#3017)', () => {
+ // A row with no kinds is unreachable work — nothing could ever carry it,
+ // and the gate would refuse every record with a message blaming the record.
+ expect(() => assertAnimationTrackRows(twoRows({ kinds: [] }))).toThrow(/needs a non-empty 'kinds' array/);
+ expect(() => assertAnimationTrackRows(twoRows({ kinds: 'character' }))).toThrow(/needs a non-empty 'kinds' array/);
+ expect(() => assertAnimationTrackRows(twoRows({ kinds: ['character', ''] }))).toThrow(/non-string entry in 'kinds'/);
+ });
+
it('lets a row opt out of an fps contract field with null', () => {
expect(() => assertAnimationTrackRows(twoRows({ contractFpsField: null }))).not.toThrow();
// …and two such rows don't collide on "null".
@@ -158,6 +172,78 @@ describe('getAnimationTrack — absent vs unrecognized', () => {
});
});
+describe('directionality and record-kind support (#3017)', () => {
+ // `AMBIENT_TRACK_ROW` is a synthetic NON-directional row admitting the two
+ // kinds that had no animation path at all. The shipped registry's only track
+ // is directional and character-only, so a test written against it alone could
+ // not tell "reads the row" from "hardcodes 8 / hardcodes 'character'" — the
+ // same injected-table idiom the guard tests above use.
+ const walk = getAnimationTrack(WALK_TRACK);
+ const MIXED = { walk, ambient: AMBIENT_TRACK_ROW };
+
+ it('accepts a well-formed non-directional row', () => {
+ expect(() => assertAnimationTrackRows(MIXED)).not.toThrow();
+ });
+
+ it('turns directionality into a row count, scaled to the grid it is asked about', () => {
+ expect(trackRowCount('walk', 8, MIXED)).toBe(8);
+ expect(trackRowCount('walk', 4, MIXED)).toBe(4);
+ // A track with no facing is ONE row whatever the grid height — that single
+ // row is row 0, and the rest of its column span stays transparent.
+ expect(trackRowCount('ambient', 8, MIXED)).toBe(1);
+ expect(trackRowCount('ambient', 4, MIXED)).toBe(1);
+ });
+
+ it('refuses an unusable direction count rather than returning NaN rows', () => {
+ expect(() => trackRowCount('walk', 0, MIXED)).toThrow(/positive direction count/);
+ expect(() => trackRowCount('walk', 2.5, MIXED)).toThrow(/positive direction count/);
+ // Unknown ids stay getAnimationTrack's boundary.
+ expect(() => trackRowCount('nope', 8, MIXED)).toThrow(/Unknown animation track 'nope'/);
+ });
+
+ it('answers which tracks a record kind may carry — the whole track-presence gate', () => {
+ expect(tracksForKind('character', MIXED).map((r) => r.id)).toEqual(['walk']);
+ expect(tracksForKind('place', MIXED).map((r) => r.id)).toEqual(['ambient']);
+ expect(tracksForKind('object', MIXED).map((r) => r.id)).toEqual(['ambient']);
+ // The gate's negative case: a kind no row lists has no animation path.
+ expect(tracksForKind('props', MIXED)).toEqual([]);
+ // A malformed record must not inherit character's permissions by default.
+ expect(tracksForKind('', MIXED)).toEqual([]);
+ expect(tracksForKind(undefined, MIXED)).toEqual([]);
+ expect(tracksForKind(null, MIXED)).toEqual([]);
+ });
+
+ it('reports per-track support, refusing an unknown track rather than throwing', () => {
+ expect(kindSupportsTrack('character', 'walk', MIXED)).toBe(true);
+ expect(kindSupportsTrack('place', 'walk', MIXED)).toBe(false);
+ expect(kindSupportsTrack('place', 'ambient', MIXED)).toBe(true);
+ // A predicate is the wrong place to throw — the gates use it to DECIDE.
+ expect(kindSupportsTrack('character', 'nope', MIXED)).toBe(false);
+ });
+
+ it('keeps the shipped registry character-only, so no gate loosened today', () => {
+ expect(tracksForKind('character').map((r) => r.id)).toEqual([WALK_TRACK]);
+ for (const kind of ['place', 'object', 'props']) {
+ expect(tracksForKind(kind), `${kind} has no track yet`).toEqual([]);
+ }
+ });
+
+ it('spells every `kinds` entry from the real record vocabulary', () => {
+ // The module-load guard can only check that `kinds` holds non-empty
+ // strings, because animationTracks.js imports nothing (asserted below) and
+ // the vocabulary lives in recordsLogic.js. So `kinds: ['charcter']` passes
+ // every guard, makes the track uncarryable by anything, and surfaces only
+ // as the baffling "No animation track applies to character records".
+ // Cross-checked here, where reaching another module is fine — the same
+ // place the client-mirror parity check lives.
+ for (const id of ANIMATION_TRACK_IDS) {
+ for (const kind of ANIMATION_TRACKS[id].kinds) {
+ expect(SPRITE_RECORD_KINDS, `${id}.kinds names an unknown record kind '${kind}'`).toContain(kind);
+ }
+ }
+ });
+});
+
describe('per-track clamps', () => {
it('clamps into the named track\'s range and rounds', () => {
expect(clampTrackFrameCount(2, WALK_TRACK)).toBe(6);
diff --git a/server/services/sprites/atlas.js b/server/services/sprites/atlas.js
index 9aa78c67e2..ce70220aba 100644
--- a/server/services/sprites/atlas.js
+++ b/server/services/sprites/atlas.js
@@ -40,7 +40,7 @@ import {
spriteDir, resolveSpriteAssetPath, RUNTIME_POINTER_REL, RUNTIME_PUBLICATIONS_REL,
isSourcePipelinePath,
} from './paths.js';
-import { requireCharacter, loadManifest } from './reference.js';
+import { requireAnimatable, loadManifest } from './reference.js';
import { SPRITE_DIRECTIONS } from './prompts.js';
import { keyChannelSplit } from './chromaKey.js';
import {
@@ -51,7 +51,9 @@ import {
} from './walkPostprocess.js';
import { ATLAS_IDLE_COLUMN } from './walkBounds.js';
import { WALK_TRACK, ANIMATION_TRACK_IDS } from './animationTracks.js';
-import { buildAtlasGrid, resolveTrackUniformity, compiledGridUpToDate } from './atlasGrid.js';
+import {
+ buildAtlasGrid, resolveTrackUniformity, compiledGridUpToDate, trackDirections,
+} from './atlasGrid.js';
import {
withWalkWriteTail, walkSetRelPath, importedWalkDirections,
} from './walk.js';
@@ -343,13 +345,17 @@ export async function validateForCompile(recordId) {
// already agreed across directions when it runs.
//
// Rows are keyed by TRACK because uniformity is a within-track rule (#3016):
- // all 8 facings of one track must share a frame count and speed since the
- // atlas is a rectangular grid, but a second track is free to differ. Only
- // `walk` is registered today; a second track adds a sibling row list here and
- // is resolved by the same loop, with no change to the shape.
+ // every facing of one track must share a frame count and speed since the
+ // atlas is a rectangular grid, but a second track is free to differ. HOW MANY
+ // facings a track has is per-track too (#3017) — `trackDirections` answers it
+ // from the registry, so a non-directional track is authored and approved as
+ // one row rather than being held to eight. Only `walk` is registered today
+ // (directional, so this is exactly SPRITE_DIRECTIONS); a second track adds a
+ // sibling row list here and is resolved by the same loop.
+ const walkDirections = trackDirections(WALK_TRACK, SPRITE_DIRECTIONS);
const manifests = {};
const trackRows = { [WALK_TRACK]: [] };
- for (const direction of SPRITE_DIRECTIONS) {
+ for (const direction of walkDirections) {
const entry = walkSet.directions?.[direction];
if (!entry || entry.status !== 'approved') throw compileError(`Direction ${direction} is not approved`);
const manifestBytes = await readVerified(entry.runManifest, entry.runManifestSha256, `Run manifest for ${direction}`);
@@ -378,11 +384,13 @@ export async function validateForCompile(recordId) {
.map((id) => resolveTrackUniformity(id, trackRows[id], {
error: compileError,
defaultFps: LEGACY_MANIFEST_FPS[id],
+ // The count this loop actually collected against, not a re-derivation.
+ expectedRows: trackDirections(id, SPRITE_DIRECTIONS).length,
}));
const walk = tracks.find((t) => t.id === WALK_TRACK);
const runs = {};
- for (const direction of SPRITE_DIRECTIONS) {
+ for (const direction of walkDirections) {
const { entry, manifest } = manifests[direction];
// Same frame-validity definition the approve gate uses (verifyPackagedFrames),
// here in its byte-verifying mode: existence + per-frame sha256 + gait-phase/
@@ -449,6 +457,12 @@ async function compileDirectionRow(recordId, direction, validated, geometry) {
}
cells.push({
column: ATLAS_IDLE_COLUMN,
+ // `track` + `frameIndex` are what place this cell in the grid: the compiler
+ // looks the pair up in the track spans rather than trusting the order cells
+ // happen to be pushed in (#3017). The idle anchor is a one-column track of
+ // its own, exactly as the sidecar has always described it.
+ track: ATLAS_IDLE_COLUMN,
+ frameIndex: 0,
...idle,
sourcePath: anchor.path,
sourceSha256: anchor.sha256,
@@ -481,7 +495,14 @@ async function compileDirectionRow(recordId, direction, validated, geometry) {
const frame = manifest.frames[i];
const { scaled, bounds, baseline } = walkScaled[i];
const normalized = placeCell(scaled, bounds, baseline, walkPasteX, `${direction}-${frame.phase}`, geometry, directionScale);
- cells.push({ column: frame.phase, ...normalized, sourcePath: frame.path, sourceSha256: frame.sha256 });
+ cells.push({
+ column: frame.phase,
+ track: WALK_TRACK,
+ frameIndex: i,
+ ...normalized,
+ sourcePath: frame.path,
+ sourceSha256: frame.sha256,
+ });
}
return {
@@ -547,7 +568,12 @@ export function compileAtlas(recordId, options = {}) {
}
export async function compileAtlasInTail(recordId, { geometry: geometryOverride } = {}) {
- await requireCharacter(recordId);
+ // The track-presence gate (#3017), not a literal kind check: a record may
+ // compile an atlas when its kind carries at least one registered animation
+ // track. Walk is character-only, so this refuses exactly what it always did —
+ // but registering a non-directional ambient track that lists `place`/`object`
+ // unlocks those records here with no edit to this line.
+ await requireAnimatable(recordId);
const geometry = mergeGeometry(geometryOverride);
const validated = await validateForCompile(recordId);
const dir = spriteDir(recordId);
@@ -587,20 +613,52 @@ export async function compileAtlasInTail(recordId, { geometry: geometryOverride
// compileDirectionRow still emits `idle` + this direction's walk frames, and
// verifyPackagedFrames has already asserted each frame's phase against the
- // walk labels — so row/column agreement remains structural for the one track
- // that exists. Making the row compiler span-driven (so it stays structural for
- // a second track) belongs with the track that needs it, #3018.
+ // walk labels. What #3017 changes is that placement no longer *assumes* that:
+ // every cell states its `track` and `frameIndex` and is placed through the
+ // grid's spans, so a track that occupies fewer columns or fewer rows lands
+ // where the sidecar says it does or the compile fails loudly. Producing the
+ // frames for a second track is still #3018's job; this is the grid contract
+ // that track will slot into.
const rows = [];
for (const direction of SPRITE_DIRECTIONS) {
rows.push(await compileDirectionRow(recordId, direction, validated, geometry));
}
+ // Resolve one cell's place in the grid from its track's span, once, and stamp
+ // the answer on the cell so the manifest below reports where the pixels
+ // actually went instead of re-deriving it. Deriving the index positionally
+ // (its order within the row) was correct only while every track was
+ // full-width and full-height; it would silently misplace a shorter or
+ // single-row track rather than reporting the mismatch.
+ const placeInGrid = (cell, r) => {
+ const span = tracks[cell.track];
+ if (!span) throw compileError(`Compiled cell references unknown atlas track '${cell.track}'`);
+ // A non-directional track owns row 0 only; the rest of its span stays as
+ // the zero-filled canvas left it — transparent, which PNG compresses to
+ // near nothing. A cell compiled outside its track's rows would overwrite
+ // pixels the sidecar promises are empty, so refuse rather than composite.
+ if (r >= span.rows) {
+ throw compileError(`Track '${cell.track}' occupies ${span.rows} atlas row(s) but a cell was compiled for ${SPRITE_DIRECTIONS[r]} (row ${r})`);
+ }
+ if (!Number.isInteger(cell.frameIndex) || cell.frameIndex < 0 || cell.frameIndex >= span.count) {
+ throw compileError(`Track '${cell.track}' frame ${cell.frameIndex} is outside its ${span.count}-column span`);
+ }
+ const index = span.start + cell.frameIndex;
+ if (columns[index] !== cell.column) {
+ throw compileError(`Track '${cell.track}' frame ${cell.frameIndex} is column "${columns[index]}" in the grid but the cell is labeled "${cell.column}"`);
+ }
+ cell.columnIndex = index;
+ return index;
+ };
+
const { cellSize } = geometry;
const atlasWidth = cellSize * columns.length;
const atlasHeight = cellSize * SPRITE_DIRECTIONS.length;
const atlas = { data: Buffer.alloc(atlasWidth * atlasHeight * 4), width: atlasWidth, height: atlasHeight };
for (let r = 0; r < rows.length; r++) {
- rows[r].cells.forEach((cell, c) => compositeOnto(atlas, cell.cell, c * cellSize, r * cellSize));
+ for (const cell of rows[r].cells) {
+ compositeOnto(atlas, cell.cell, placeInGrid(cell, r) * cellSize, r * cellSize);
+ }
}
const atlasBuffer = await sharp(atlas.data, { raw: { width: atlasWidth, height: atlasHeight, channels: 4 } })
.png()
@@ -695,9 +753,11 @@ export async function compileAtlasInTail(recordId, { geometry: geometryOverride
walkDirectionScale: row.walkDirectionScale,
idleScale: row.idleScale,
idlePolicy: row.idlePolicy,
- cells: row.cells.map((cell, c) => ({
+ // The index the compositor stamped on, so the manifest cannot claim a
+ // cell sits somewhere other than where its pixels actually landed.
+ cells: row.cells.map((cell) => ({
column: cell.column,
- columnIndex: c,
+ columnIndex: cell.columnIndex,
translation: cell.meta.translation,
scale: cell.meta.scale,
occupiedBounds: cell.meta.occupiedBounds,
diff --git a/server/services/sprites/atlas.test.js b/server/services/sprites/atlas.test.js
index 9dbf5b50e0..b9de576111 100644
--- a/server/services/sprites/atlas.test.js
+++ b/server/services/sprites/atlas.test.js
@@ -14,7 +14,7 @@ import { join } from 'path';
import sharp from 'sharp';
import { mkdir, writeFile, readFile } from 'fs/promises';
import { createHash } from 'crypto';
-import { lockAllAnchors as lockAllAnchorsFixture } from './spriteTestFixtures.js';
+import { lockAllAnchors as lockAllAnchorsFixture, trackSpan as fullSpan } from './spriteTestFixtures.js';
const TEST_ROOT = mkdtempSync(join(tmpdir(), 'sprite-atlas-test-'));
@@ -314,8 +314,8 @@ describe('compileAtlas', () => {
const manifest = JSON.parse(await readFile(join(TEST_ROOT, 'sprites', id, result.manifestPath), 'utf8'));
expect(manifest.geometry.tracks).toEqual({
- idle: { start: 0, count: 1 },
- walk: { start: 1, count: 12 },
+ idle: fullSpan(0, 1),
+ walk: fullSpan(1, 12),
});
// The descriptor, the column list and the emitted PNG width all describe
// the same grid — a consumer resolving a track by span lands on the pixels
@@ -327,6 +327,52 @@ describe('compileAtlas', () => {
expect(result.geometry.tracks).toEqual(manifest.geometry.tracks);
});
+ it('records how many atlas rows each track occupies (#3017)', async () => {
+ const id = await finalizedCharacter();
+ const result = await compileAtlas(id);
+
+ // Both shipped tracks are directional, so both are full-height — that is
+ // the point: nothing about an existing character's atlas changes. What the
+ // field buys is that a NON-directional track (a tree in the wind) can say
+ // it owns row 0 only, and a consumer knows to read row 0 regardless of
+ // facing instead of sampling seven transparent rows.
+ expect(result.geometry.tracks.idle.rows).toBe(SPRITE_DIRECTIONS.length);
+ expect(result.geometry.tracks.walk.rows).toBe(SPRITE_DIRECTIONS.length);
+ expect(result.geometry.rows).toBe(SPRITE_DIRECTIONS.length);
+
+ // Cells are placed through the spans, so every manifest columnIndex lands
+ // inside its own track's span and names the column the grid has there.
+ const manifest = JSON.parse(await readFile(join(TEST_ROOT, 'sprites', id, result.manifestPath), 'utf8'));
+ for (const row of manifest.directions) {
+ for (const cell of row.cells) {
+ expect(manifest.geometry.columns[cell.columnIndex]).toBe(cell.column);
+ }
+ }
+ });
+
+ it('stays byte-identical to a pointer that predates the rows field', async () => {
+ // The idempotency regression #3017 could have caused: `rows` is new on every
+ // span, so a pointer written before it would compare unequal and re-run the
+ // entire pixel pipeline on every compile, forever, for every existing
+ // install. Absent must normalize to full height on the way in.
+ const id = await finalizedCharacter();
+ const first = await compileAtlas(id);
+
+ const pointerAbs = join(TEST_ROOT, 'sprites', id, 'runtime/current.json');
+ const pointer = JSON.parse(await readFile(pointerAbs, 'utf8'));
+ pointer.geometry = {
+ ...pointer.geometry,
+ tracks: Object.fromEntries(
+ Object.entries(pointer.geometry.tracks).map(([t, s]) => [t, { start: s.start, count: s.count }]),
+ ),
+ };
+ await writeFile(pointerAbs, JSON.stringify(pointer));
+
+ const again = await compileAtlas(id);
+ expect(again.created).toBe(false);
+ expect(again.version).toBe(first.version);
+ });
+
it('recompiles a set whose pointer describes a DIFFERENT track set over the same columns', async () => {
const id = await finalizedCharacter();
const first = await compileAtlas(id);
@@ -340,7 +386,7 @@ describe('compileAtlas', () => {
// untouched instead of writing a new version.
const pointerAbs = join(TEST_ROOT, 'sprites', id, 'runtime/current.json');
const pointer = JSON.parse(await readFile(pointerAbs, 'utf8'));
- expect(pointer.geometry.tracks).toEqual({ idle: { start: 0, count: 1 }, walk: { start: 1, count: 8 } });
+ expect(pointer.geometry.tracks).toEqual({ idle: fullSpan(0, 1), walk: fullSpan(1, 8) });
pointer.atlasSha256 = 'f'.repeat(64);
pointer.geometry = {
...pointer.geometry,
@@ -356,7 +402,7 @@ describe('compileAtlas', () => {
expect(again.created).toBe(true);
expect(again.version).toBe(first.version + 1);
expect(again.geometry.columns).toEqual(['idle', ...WALK_PHASES]);
- expect(again.geometry.tracks).toEqual({ idle: { start: 0, count: 1 }, walk: { start: 1, count: 8 } });
+ expect(again.geometry.tracks).toEqual({ idle: fullSpan(0, 1), walk: fullSpan(1, 8) });
});
it('stays idempotent for a legacy pointer written before the tracks descriptor existed', async () => {
diff --git a/server/services/sprites/atlasGrid.js b/server/services/sprites/atlasGrid.js
index a73dceb679..fc60b08233 100644
--- a/server/services/sprites/atlasGrid.js
+++ b/server/services/sprites/atlasGrid.js
@@ -15,7 +15,7 @@
*
* - **`buildAtlasGrid`** — the span builder. `idle` is column 0, then each
* track's columns in stable registry-registration order, yielding both the
- * flat `columns` list and the `{ start, count }` `tracks` descriptor the
+ * flat `columns` list and the `{ start, count, rows }` `tracks` descriptor the
* published `layout.json` sidecar carries (#2982).
* - **`resolveTrackUniformity`** — one track's frame count / fps resolved from
* its per-direction rows, asserting the 8 facings agree. It NEVER compares one
@@ -31,6 +31,26 @@
* definition of a column span has to live below both. Nothing here touches fs,
* state, or the image graph.
*
+ * **Rows are per-track too, since #3017.** A directional track occupies one row
+ * per facing; a NON-directional one (a tree in the wind, water, a flickering
+ * lamp — animations with no facing at all) occupies row 0 and leaves the rest of
+ * its column span transparent. That is why every span carries `rows` alongside
+ * `{ start, count }`, and why `trackDirections` exists: the compiler asks which
+ * facings a track actually has instead of assuming eight. Still ONE rectangular
+ * atlas per record — transparent cells cost only file size, which PNG compresses
+ * to near nothing, and a second atlas would double the publish/binding surface.
+ *
+ * That generalization is the GRID and COMPILE layer only. The authoring side is
+ * still eight-shaped by design and by name — `walk.js`'s `allApproved` and its
+ * `finalized-eight-direction-walk-set`, and `reference.js`'s eight anchors — so
+ * a non-directional track is expressible and compilable here before it is
+ * authorable there. #3045 is the track that closes that half.
+ *
+ * A persisted span with NO `rows` is read as full-height rather than rejected:
+ * every grid compiled before #3017 is walk + idle, both directional, so
+ * defaulting to the grid's row count is what keeps existing atlases idempotent
+ * instead of condemning them to recompile their pixels forever.
+ *
* **Only ONE track is registered today** (`walk`). The multi-track paths below
* are proven in `atlasGrid.test.js` against a synthetic REGISTRY TABLE rather
* than by shipping a second track's artwork. The registry table is the
@@ -41,10 +61,46 @@
* change here.
*/
-import { ANIMATION_TRACKS, WALK_TRACK, getAnimationTrack } from './animationTracks.js';
+import {
+ ANIMATION_TRACKS, WALK_TRACK, getAnimationTrack, trackRowCount,
+} from './animationTracks.js';
import { ATLAS_IDLE_COLUMN, ATLAS_SCANNER_COLUMN, walkPhaseLabels } from './walkBounds.js';
+import { SPRITE_DIRECTIONS } from './prompts.js';
import { canonicalStringify } from '../../lib/objects.js';
+/**
+ * The height of every atlas this compiler emits: one row per canonical facing.
+ *
+ * Deliberately NOT a threaded parameter. Grid height is fixed by
+ * `SPRITE_DIRECTIONS`, and the only place a *different* number can legitimately
+ * appear is a PERSISTED geometry — a pointer or an imported manifest carrying
+ * its own `geometry.rows`. So the readers of persisted geometry (`deriveTracks`
+ * and, through it, `compiledGridUpToDate`) take a row count; the producers
+ * (`buildAtlasGrid`, `resolveTrackUniformity`) do not, because inventing a knob
+ * for them would only create a second, disagreeing source for one number.
+ */
+export const ATLAS_DEFAULT_ROWS = SPRITE_DIRECTIONS.length;
+
+/**
+ * The facings one track occupies, out of the grid's full direction list: all of
+ * them for a directional track, just the first (row 0) for a non-directional
+ * one.
+ *
+ * Scoped to the GRID and COMPILE layer, which is all #3017 generalized: it is
+ * what stops `validateForCompile` and the uniformity check from assuming eight
+ * facings per track. The *authoring* side is still eight-shaped on purpose —
+ * `walk.js`'s `allApproved` and its `finalized-eight-direction-walk-set`
+ * manifest, and `reference.js`'s eight anchors, all still hardcode the facing
+ * list, and generalizing them is the job of the track that needs it (#3045).
+ */
+export function trackDirections(trackId, directions = SPRITE_DIRECTIONS, tracks = ANIMATION_TRACKS) {
+ if (!Array.isArray(directions) || !directions.length) {
+ throw new Error(`Atlas track '${trackId}' needs a non-empty direction list`);
+ }
+ const rows = trackRowCount(trackId, directions.length, tracks);
+ return rows === directions.length ? [...directions] : directions.slice(0, rows);
+}
+
/**
* Column labels for one track's span.
*
@@ -75,12 +131,16 @@ export function trackColumnLabels(trackId, frameCount) {
* Build the atlas grid from a set of track specs (`{ id, frameCount }`).
*
* Returns `{ columns, tracks }` where `tracks` maps each track id to its
- * contiguous `{ start, count }` column span — mutually consistent by
+ * contiguous `{ start, count, rows }` column span — mutually consistent by
* construction, so the emitted PNG width (`cellSize × columns.length`) and the
- * sidecar's spans can never drift apart.
+ * sidecar's spans can never drift apart. `rows` is how many of the grid's
+ * facings that track occupies (#3017): every one for a directional track, just
+ * row 0 for a non-directional one, whose remaining cells stay transparent.
*
* `idle` is always column 0 and is described as a track of its own, matching
- * what the sidecar has always emitted. Specs are sorted into the registry's
+ * what the sidecar has always emitted. It is full-height by definition — the
+ * per-facing resting pose is the one cell every direction row is guaranteed to
+ * have. Specs are sorted into the registry's
* registration order rather than trusted in call order, so two call sites that
* list tracks differently still produce the same grid, and an id the registry
* doesn't know is refused through `getAnimationTrack`'s own unknown-track
@@ -107,16 +167,26 @@ export function buildAtlasGrid(specs, tracks = ANIMATION_TRACKS) {
}
const ordered = [...specs].sort((a, b) => order.indexOf(a.id) - order.indexOf(b.id));
+ const trackRows = ordered.map((spec) => trackRowCount(spec.id, ATLAS_DEFAULT_ROWS, tracks));
+
+ // The idle anchor is the per-facing resting pose, so it spans as many rows as
+ // the tallest track present — NOT an unconditional full height. A record whose
+ // only track is non-directional has exactly one facing worth of pose, and
+ // stamping eight here would promise a consumer seven rows of pixels nothing
+ // ever writes. With any directional track present this is the full height,
+ // which is every grid that exists today. Inserted FIRST so the descriptor's
+ // key order still matches the column order a published sidecar carries.
const columns = [ATLAS_IDLE_COLUMN];
- const spans = { [ATLAS_IDLE_COLUMN]: { start: 0, count: 1 } };
- for (const spec of ordered) {
+ const spans = { [ATLAS_IDLE_COLUMN]: { start: 0, count: 1, rows: Math.max(...trackRows) } };
+ ordered.forEach((spec, i) => {
// Labels are DERIVED, never supplied: trackColumnLabels is total and
// deterministic, so accepting them from the caller would only create a
- // mismatch the builder then has to reconcile against itself.
+ // mismatch the builder then has to reconcile against itself. Row height is
+ // derived the same way, from the registry's `directional` flag.
const labels = trackColumnLabels(spec.id, spec.frameCount);
- spans[spec.id] = { start: columns.length, count: labels.length };
+ spans[spec.id] = { start: columns.length, count: labels.length, rows: trackRows[i] };
columns.push(...labels);
- }
+ });
return { columns, tracks: spans };
}
@@ -169,8 +239,13 @@ export function resolveWalkFrameCount(geometry) {
* non-overlapping, covering every column. A sidecar whose spans disagree with
* its own `columns` would silently point a consumer at the wrong pixels, which
* is the entire failure mode #2982 exists to prevent.
+ *
+ * `rows` is normalized, not merely copied: absent means full-height (every grid
+ * written before #3017 carries only directional tracks), and a present value is
+ * range-checked against the grid's real height so a descriptor can't promise
+ * rows the PNG doesn't have.
*/
-function validateCompiledTracks(compiled, columns) {
+function validateCompiledTracks(compiled, columns, directionCount) {
const entries = Object.entries(compiled);
if (!entries.length) {
return { error: `Atlas track descriptor is empty but the grid has ${columns.length} columns` };
@@ -183,6 +258,11 @@ function validateCompiledTracks(compiled, columns) {
if (span.start < 0 || span.start + span.count > columns.length) {
return { error: `Atlas track "${id}" spans columns ${span.start}–${span.start + span.count - 1}, outside the ${columns.length}-column grid` };
}
+ // Absent is legal (legacy = full height); present must be a real row count.
+ if (span.rows !== undefined && span.rows !== null
+ && (!Number.isInteger(span.rows) || span.rows < 1 || span.rows > directionCount)) {
+ return { error: `Atlas track "${id}" claims ${span.rows} rows, outside the ${directionCount}-row grid` };
+ }
}
const sorted = [...entries].sort((a, b) => a[1].start - b[1].start);
let cursor = 0;
@@ -192,7 +272,11 @@ function validateCompiledTracks(compiled, columns) {
return { error: `Atlas track "${id}" starts at column ${span.start} but the previous track ends at ${cursor} — the grid is not tiled by its tracks` };
}
cursor += span.count;
- tracks[id] = { start: span.start, count: span.count };
+ tracks[id] = {
+ start: span.start,
+ count: span.count,
+ rows: Number.isInteger(span.rows) ? span.rows : directionCount,
+ };
}
if (cursor !== columns.length) {
return { error: `Atlas tracks describe ${cursor} of ${columns.length} columns` };
@@ -202,7 +286,7 @@ function validateCompiledTracks(compiled, columns) {
/**
* Group a compiled grid into named tracks of contiguous column spans:
- * `{ idle: { start: 0, count: 1 }, walk: { start: 1, count: 8 } }`.
+ * `{ idle: { start: 0, count: 1, rows: 8 }, walk: { start: 1, count: 8, rows: 8 } }`.
*
* `compiledTracks` — the descriptor the compiler persisted into the manifest
* geometry — is authoritative when **present**, which is what lets a grid carry
@@ -217,22 +301,25 @@ function validateCompiledTracks(compiled, columns) {
* descriptor that fails to describe the grid, and it is rejected rather than
* silently re-derived.
*/
-export function deriveTracks(columns, walkFrameCount, compiledTracks = null) {
- const described = describeTracks(columns, walkFrameCount, compiledTracks);
+export function deriveTracks(columns, walkFrameCount, compiledTracks = null, directionCount = ATLAS_DEFAULT_ROWS) {
+ const described = describeTracks(columns, walkFrameCount, compiledTracks, directionCount);
if (described.error) throw new Error(described.error);
return described.tracks;
}
/** Non-throwing `deriveTracks` — `{ tracks }` or `{ error }`. */
-function describeTracks(columns, walkFrameCount, compiledTracks = null) {
+function describeTracks(columns, walkFrameCount, compiledTracks = null, directionCount = ATLAS_DEFAULT_ROWS) {
if (!Array.isArray(columns) || !columns.length) {
return { error: 'Compiled atlas geometry has no column list' };
}
+ if (!Number.isInteger(directionCount) || directionCount < 1) {
+ return { error: `Compiled atlas geometry has no usable row count (got ${directionCount})` };
+ }
if (compiledTracks !== null && compiledTracks !== undefined) {
if (typeof compiledTracks !== 'object' || Array.isArray(compiledTracks)) {
return { error: 'Atlas track descriptor must be an object of column spans' };
}
- return validateCompiledTracks(compiledTracks, columns);
+ return validateCompiledTracks(compiledTracks, columns, directionCount);
}
const walkStart = columns[0] === ATLAS_IDLE_COLUMN ? 1 : 0;
@@ -243,7 +330,10 @@ function describeTracks(columns, walkFrameCount, compiledTracks = null) {
const name = index >= walkStart && index < walkEnd ? WALK_TRACK : column;
const existing = tracks[name];
if (!existing) {
- tracks[name] = { start: index, count: 1 };
+ // Legacy grids predate non-directional tracks entirely — walk, idle, and
+ // the pre-#2986 scanner placeholder are all full-height — so every span
+ // derived this way is the grid's full height.
+ tracks[name] = { start: index, count: 1, rows: directionCount };
continue;
}
if (existing.start + existing.count !== index) {
@@ -282,7 +372,20 @@ export function compiledGridUpToDate(current, expected) {
if (current.targetMaxHeight !== expected.targetMaxHeight) return false;
if (current.targetMaxWidth !== expected.targetMaxWidth) return false;
if (JSON.stringify(current.columns) !== JSON.stringify(expected.columns)) return false;
- const described = describeTracks(current.columns, resolveWalkFrameCount(current), current.tracks ?? null);
+ // Described, not compared raw, so a pointer predating `rows` (#3017) is
+ // normalized on the way in and stays idempotent — the same reason a pointer
+ // predating `tracks` (#3016) is described the legacy way.
+ //
+ // The height comes from the POINTER's own `geometry.rows`, which is what
+ // atlasLayout.js reads when it builds the sidecar from that same geometry.
+ // Normalizing to a constant here instead would let the two consumers of one
+ // persisted grid disagree about how tall it is.
+ const described = describeTracks(
+ current.columns,
+ resolveWalkFrameCount(current),
+ current.tracks ?? null,
+ Number.isInteger(current.rows) ? current.rows : ATLAS_DEFAULT_ROWS,
+ );
if (described.error) return false;
// canonicalStringify, NOT JSON.stringify: the two sides are built by three
// different producers with three different key-insertion orders
@@ -305,6 +408,14 @@ export function compiledGridUpToDate(current, expected) {
* check reads the named track's own registry row (#3015) instead of the global
* walk-shaped 6–16 / 4–24 constants.
*
+ * **How MANY directions is per-track too (#3017).** A directional track needs
+ * every facing; a non-directional one has exactly one row and must not be held
+ * to eight — so a row list that doesn't match the track's height is refused
+ * here rather than surfacing as a half-empty atlas. `expectedRows` is that
+ * height; callers that built `rows` from `trackDirections` already have it, so
+ * it is passed rather than re-derived (deriving it here from a grid height would
+ * be the third computation of one fact inside a single caller).
+ *
* `rows` are `{ direction, frameCount, declaredFrameCount, fps }`. The registry
* `tracks` table is the injection seam (as in `buildAtlasGrid`), and `error` is
* injectable so this leaf stays free of the error-handler import — callers pass
@@ -318,10 +429,17 @@ export function resolveTrackUniformity(trackId, rows, {
trackRow = getAnimationTrack(trackId, tracks),
error = (message) => new Error(message),
defaultFps = trackRow.defaultFps,
+ expectedRows = trackRowCount(trackId, ATLAS_DEFAULT_ROWS, tracks),
} = {}) {
if (!Array.isArray(rows) || !rows.length) {
throw error(`Track ${trackId} has no directions to compile`);
}
+ if (rows.length !== expectedRows) {
+ throw error(
+ `Track ${trackId} occupies ${expectedRows} atlas ${expectedRows === 1 ? 'row' : 'rows'} `
+ + `but ${rows.length} ${rows.length === 1 ? 'was' : 'were'} supplied`,
+ );
+ }
let frameCount = null;
let fps = null;
for (const row of rows) {
diff --git a/server/services/sprites/atlasGrid.test.js b/server/services/sprites/atlasGrid.test.js
index ea2ab90cf3..f596ebc4cd 100644
--- a/server/services/sprites/atlasGrid.test.js
+++ b/server/services/sprites/atlasGrid.test.js
@@ -12,15 +12,24 @@
* builder could collapse back to `['idle', ...walkLabels]` and such a test would
* stay green, which is exactly the regression it exists to prevent. Shipping a
* real second track is #3018's job.
+ *
+ * #3017 adds the NON-directional case on the same terms: `AMBIENT_TRACK_ROW`
+ * (shared from spriteTestFixtures.js, since animationTracks.test.js needs the
+ * same row) is a synthetic three-frame, single-row, place/object track. Every
+ * row-span assertion below runs against it, because the shipped registry's only
+ * track is directional and a full-height-only registry cannot distinguish
+ * "reads the registry's `directional` flag" from "hardcodes eight rows".
*/
import { describe, it, expect } from 'vitest';
import {
trackColumnLabels, buildAtlasGrid, deriveTracks,
resolveWalkFrameCount, compiledGridUpToDate, resolveTrackUniformity,
+ trackDirections, ATLAS_DEFAULT_ROWS,
} from './atlasGrid.js';
import { walkPhaseLabels } from './walkBounds.js';
import { getAnimationTrack, ANIMATION_TRACKS } from './animationTracks.js';
+import { trackSpan as span, AMBIENT_TRACK_ROW } from './spriteTestFixtures.js';
// A second track that does NOT exist in the registry, shaped like a short
// action animation: four frames, which sits BELOW walk's floor of 6 — the exact
@@ -29,6 +38,7 @@ const SCANNER_ROW = Object.freeze({
id: 'scanner',
label: 'Scanner sweep',
directional: true,
+ kinds: Object.freeze(['character']),
minFrameCount: 2,
maxFrameCount: 8,
defaultFrameCount: 4,
@@ -39,8 +49,12 @@ const SCANNER_ROW = Object.freeze({
contractFpsField: null,
});
const TWO_TRACK_REGISTRY = Object.freeze({ walk: ANIMATION_TRACKS.walk, scanner: SCANNER_ROW });
+
+const MIXED_REGISTRY = Object.freeze({ walk: ANIMATION_TRACKS.walk, ambient: AMBIENT_TRACK_ROW });
+
const DIRECTIONS = ['S', 'SE', 'E', 'NE', 'N', 'NW', 'W', 'SW'];
+
const rowsFor = (frameCount, fps, overrides = {}) =>
DIRECTIONS.map((direction) => ({
direction, frameCount, declaredFrameCount: frameCount, fps, ...overrides,
@@ -76,7 +90,7 @@ describe('buildAtlasGrid', () => {
it('emits idle first, then one contiguous span per track', () => {
const grid = buildAtlasGrid([{ id: 'walk', frameCount: 8 }]);
expect(grid.columns).toEqual(['idle', ...walkPhaseLabels(8)]);
- expect(grid.tracks).toEqual({ idle: { start: 0, count: 1 }, walk: { start: 1, count: 8 } });
+ expect(grid.tracks).toEqual({ idle: span(0, 1), walk: span(1, 8) });
});
it('packs two tracks of DIFFERENT lengths into one grid', () => {
@@ -90,9 +104,9 @@ describe('buildAtlasGrid', () => {
'scanner-00', 'scanner-01', 'scanner-02', 'scanner-03',
]);
expect(grid.tracks).toEqual({
- idle: { start: 0, count: 1 },
- walk: { start: 1, count: 12 },
- scanner: { start: 13, count: 4 },
+ idle: span(0, 1),
+ walk: span(1, 12),
+ scanner: span(13, 4),
});
// columns and tracks stay mutually consistent — the spans tile the grid,
// so the emitted PNG width (cellSize × columns.length) matches what the
@@ -102,6 +116,42 @@ describe('buildAtlasGrid', () => {
expect(grid.columns.length).toBe(17);
});
+ it('gives a non-directional track a single row and its neighbours the full height (#3017)', () => {
+ const grid = buildAtlasGrid(
+ [{ id: 'walk', frameCount: 8 }, { id: 'ambient', frameCount: 3 }],
+ MIXED_REGISTRY,
+ );
+ // One rectangular atlas, not one per track: the ambient span is as WIDE as
+ // its frame count but only one row TALL, and the remaining rows of those
+ // columns are simply never written (transparent, which PNG compresses to
+ // near nothing).
+ expect(grid.tracks).toEqual({
+ idle: span(0, 1),
+ walk: span(1, 8),
+ ambient: span(9, 3, 1),
+ });
+ expect(grid.columns).toEqual(['idle', ...walkPhaseLabels(8), 'ambient-00', 'ambient-01', 'ambient-02']);
+ // Still tiled — a single-row track occupies real columns, so the width math
+ // and the sidecar's spans stay mutually consistent.
+ expect(Object.values(grid.tracks).reduce((n, s) => n + s.count, 0)).toBe(grid.columns.length);
+ });
+
+ it('sizes the idle anchor to the tallest track, not to an unconditional full height', () => {
+ // idle is the per-facing resting pose. A record whose ONLY track is
+ // non-directional has one facing worth of pose, so promising eight rows
+ // would advertise seven rows of pixels nothing ever writes.
+ const ambientOnly = buildAtlasGrid([{ id: 'ambient', frameCount: 3 }], MIXED_REGISTRY);
+ expect(ambientOnly.tracks).toEqual({ idle: span(0, 1, 1), ambient: span(1, 3, 1) });
+
+ // …and any directional track present pulls it back to the full height,
+ // which is every grid that exists today.
+ const withWalk = buildAtlasGrid(
+ [{ id: 'walk', frameCount: 8 }, { id: 'ambient', frameCount: 3 }],
+ MIXED_REGISTRY,
+ );
+ expect(withWalk.tracks.idle.rows).toBe(DIRECTIONS.length);
+ });
+
it('sorts specs into registration order rather than call order', () => {
const asGiven = buildAtlasGrid(
[{ id: 'scanner', frameCount: 4 }, { id: 'walk', frameCount: 6 }],
@@ -145,21 +195,50 @@ describe('deriveTracks', () => {
// four one-column singletons.
const legacy = deriveTracks(grid.columns, 6, null);
expect(legacy.scanner).toBeUndefined();
- expect(legacy['scanner-00']).toEqual({ start: 7, count: 1 });
+ expect(legacy['scanner-00']).toEqual(span(7, 1));
});
it('treats an absent descriptor as legacy and a present-but-empty one as invalid', () => {
// Absent ≠ present-but-empty: `{}` is a descriptor that fails to describe
// the grid and must be refused, never silently re-derived.
expect(deriveTracks(['idle', 'a', 'b'], 2, null)).toEqual({
- idle: { start: 0, count: 1 }, walk: { start: 1, count: 2 },
+ idle: span(0, 1), walk: span(1, 2),
});
expect(deriveTracks(['idle', 'a', 'b'], 2, undefined)).toEqual({
- idle: { start: 0, count: 1 }, walk: { start: 1, count: 2 },
+ idle: span(0, 1), walk: span(1, 2),
});
expect(() => deriveTracks(['idle', 'a', 'b'], 2, {})).toThrow(/descriptor is empty/);
});
+ it('round-trips a single-row span and defaults an absent one to full height (#3017)', () => {
+ const grid = buildAtlasGrid(
+ [{ id: 'walk', frameCount: 8 }, { id: 'ambient', frameCount: 3 }],
+ MIXED_REGISTRY,
+ );
+ expect(deriveTracks(grid.columns, 8, grid.tracks)).toEqual(grid.tracks);
+
+ // A descriptor persisted before #3017 has no `rows` at all. Every track in
+ // such a grid is directional, so normalizing to the grid's full height is
+ // what keeps those atlases describable AND idempotent — dropping the field
+ // through unchanged would instead emit a sidecar span with no row info.
+ const legacy = Object.fromEntries(
+ Object.entries(grid.tracks).map(([id, s]) => [id, { start: s.start, count: s.count }]),
+ );
+ expect(deriveTracks(grid.columns, 8, legacy).ambient).toEqual(span(9, 3));
+ expect(deriveTracks(grid.columns, 8, legacy).walk).toEqual(span(1, 8));
+ });
+
+ it('refuses a span claiming more rows than the grid has', () => {
+ const columns = ['idle', 'a', 'b'];
+ expect(() => deriveTracks(columns, 2, { idle: { start: 0, count: 1 }, walk: { start: 1, count: 2, rows: 9 } }))
+ .toThrow(/claims 9 rows, outside the 8-row grid/);
+ expect(() => deriveTracks(columns, 2, { idle: { start: 0, count: 1 }, walk: { start: 1, count: 2, rows: 0 } }))
+ .toThrow(/claims 0 rows, outside the 8-row grid/);
+ // …measured against the grid's REAL height, not the canonical eight.
+ expect(() => deriveTracks(columns, 2, { idle: { start: 0, count: 1 }, walk: { start: 1, count: 2, rows: 4 } }, 3))
+ .toThrow(/claims 4 rows, outside the 3-row grid/);
+ });
+
it('refuses a descriptor that does not tile its own column list', () => {
const columns = ['idle', 'a', 'b', 'c'];
expect(() => deriveTracks(columns, 3, { idle: { start: 0, count: 1 }, walk: { start: 1, count: 2 } }))
@@ -182,19 +261,19 @@ describe('deriveTracks', () => {
it('spans the walk by position, so positional frame-NN labels group too', () => {
// A grid whose columns are `frame-00…` rather than the named gait phases
// must still describe ONE walk track, not ten singletons.
- expect(deriveTracks(['idle', ...walkPhaseLabels(10)], 10).walk).toEqual({ start: 1, count: 10 });
+ expect(deriveTracks(['idle', ...walkPhaseLabels(10)], 10).walk).toEqual(span(1, 10));
// …and a pre-#2986 grid still describes its scanner placeholder honestly
// rather than folding it into the walk span.
expect(deriveTracks(['idle', ...walkPhaseLabels(6), 'scanner'], 6)).toEqual({
- idle: { start: 0, count: 1 },
- walk: { start: 1, count: 6 },
- scanner: { start: 7, count: 1 },
+ idle: span(0, 1),
+ walk: span(1, 6),
+ scanner: span(7, 1),
});
// Any repeated non-walk column groups into its own span too.
expect(deriveTracks(['idle', 'w0', 'w1', 'scan-a', 'scan-a', 'scan-a'], 2)).toEqual({
- idle: { start: 0, count: 1 },
- walk: { start: 1, count: 2 },
- 'scan-a': { start: 3, count: 3 },
+ idle: span(0, 1),
+ walk: span(1, 2),
+ 'scan-a': span(3, 3),
});
});
@@ -241,9 +320,9 @@ describe('compiledGridUpToDate', () => {
// the column names identical. That is a different grid and must recompile.
const repartitioned = persisted({
tracks: {
- idle: { start: 0, count: 1 },
- walk: { start: 1, count: 4 },
- scanner: { start: 5, count: 4 },
+ idle: span(0, 1),
+ walk: span(1, 4),
+ scanner: span(5, 4),
},
});
expect(repartitioned.columns).toEqual(expected.columns);
@@ -270,12 +349,47 @@ describe('compiledGridUpToDate', () => {
});
});
+describe('trackDirections', () => {
+ it('gives a directional track every facing and a non-directional one just row 0', () => {
+ expect(trackDirections('walk', DIRECTIONS, MIXED_REGISTRY)).toEqual(DIRECTIONS);
+ // A tree in the wind has no facing — one row to author, one to approve, one
+ // to compile. This is what lets the approval and compile flows stop
+ // demanding eight directions per track.
+ expect(trackDirections('ambient', DIRECTIONS, MIXED_REGISTRY)).toEqual(['S']);
+ });
+
+ it('defaults to the canonical eight facings and refuses an empty list', () => {
+ expect(trackDirections('walk')).toHaveLength(ATLAS_DEFAULT_ROWS);
+ expect(ATLAS_DEFAULT_ROWS).toBe(8);
+ expect(() => trackDirections('walk', [])).toThrow(/non-empty direction list/);
+ // Unknown ids stay the registry's boundary rather than this helper's.
+ expect(() => trackDirections('nope', DIRECTIONS)).toThrow(/Unknown animation track 'nope'/);
+ });
+});
+
describe('resolveTrackUniformity', () => {
it('resolves a track from its per-direction rows', () => {
// Labels are NOT returned — buildAtlasGrid derives them, so the two can't disagree.
expect(resolveTrackUniformity('walk', rowsFor(12, 10))).toEqual({ id: 'walk', frameCount: 12, fps: 10 });
});
+ it('holds a non-directional track to ONE row, not to eight (#3017)', () => {
+ const oneRow = [{ direction: 'S', frameCount: 3, declaredFrameCount: 3, fps: 4 }];
+ expect(resolveTrackUniformity('ambient', oneRow, { tracks: MIXED_REGISTRY }))
+ .toEqual({ id: 'ambient', frameCount: 3, fps: 4 });
+
+ // The failure this prevents: an approval flow that demanded eight facings
+ // for a tree in the wind — there is only one to author, and seven of the
+ // eight rows are transparent by design.
+ expect(() => resolveTrackUniformity('ambient', rowsFor(3, 4), { tracks: MIXED_REGISTRY }))
+ .toThrow(/Track ambient occupies 1 atlas row but 8 were supplied/);
+
+ // …and the reverse is still enforced: a directional track that lost a
+ // facing would otherwise compile a half-empty atlas rather than failing.
+ expect(() => resolveTrackUniformity('walk', rowsFor(12, 10).slice(0, 7)))
+ .toThrow(/Track walk occupies 8 atlas rows but 7 were supplied/);
+ });
+
it('enforces uniformity WITHIN a track', () => {
const ragged = rowsFor(12, 10);
ragged[3] = { ...ragged[3], frameCount: 10, declaredFrameCount: 10 };
diff --git a/server/services/sprites/atlasLayout.js b/server/services/sprites/atlasLayout.js
index 72e59f62d7..7c70a2a495 100644
--- a/server/services/sprites/atlasLayout.js
+++ b/server/services/sprites/atlasLayout.js
@@ -16,7 +16,10 @@
* verify the atlas it loaded is the one the layout describes
* (`sourceAtlasSha256`). Alongside the flat `columns` list it carries a
* per-track column span (`tracks`), so a future multi-frame scanner action or
- * an ambient loop is an additive track rather than a v2 rewrite.
+ * an ambient loop is an additive track rather than a v2 rewrite. Each span
+ * also states how many `rows` its track occupies (#3017): a non-directional
+ * track — a tree in the wind, water, a lamp — is single-row, and a consumer
+ * reads row 0 for it regardless of which way the camera or the player faces.
* - `runtimeContractMismatch` compares compiled geometry against the optional
* `publishBinding.runtimeContract` the app declared, so a publish the app
* cannot consume is refused with both numbers named instead of shipping.
@@ -42,7 +45,7 @@
*/
import { basename } from 'path';
-import { deriveTracks, resolveWalkFrameCount } from './atlasGrid.js';
+import { deriveTracks, resolveWalkFrameCount, ATLAS_DEFAULT_ROWS } from './atlasGrid.js';
// Bump only on a breaking shape change. Adding a field (or a new track) is
// additive — consumers read `tracks`/`columns` by name, not by position.
@@ -81,6 +84,9 @@ export function buildAtlasLayout({
throw new Error('Compiled atlas geometry has no column list');
}
const walkFrameCount = resolveWalkFrameCount(geometry);
+ // The grid's real height, so a span's `rows` is checked against (and defaulted
+ // to) the atlas actually being described rather than the canonical eight.
+ const rows = geometry.rows ?? (Array.isArray(geometry.directionOrder) ? geometry.directionOrder.length : null);
return {
schemaVersion: ATLAS_LAYOUT_SCHEMA_VERSION,
kind: ATLAS_LAYOUT_KIND,
@@ -91,14 +97,19 @@ export function buildAtlasLayout({
atlasVersion: version ?? null,
sourceAtlasSha256: atlasSha256,
cellSize: geometry.cellSize ?? null,
- rows: geometry.rows ?? (Array.isArray(geometry.directionOrder) ? geometry.directionOrder.length : null),
+ rows,
rowOrder: Array.isArray(geometry.directionOrder) ? [...geometry.directionOrder] : null,
columns: [...columns],
columnCount: columns.length,
// Prefer the descriptor the compiler persisted (#3016) — the only thing
// that can describe two tracks of differing length — and fall back to the
// legacy column-name derivation for a grid compiled before it existed.
- tracks: deriveTracks(columns, walkFrameCount, geometry.tracks ?? null),
+ // Each span carries `rows` (#3017), so a consumer knows a non-directional
+ // track lives on row 0 regardless of facing without inspecting pixels.
+ // A geometry with no usable row count falls back to the canonical eight —
+ // the shape every such atlas really has. Stated rather than laundered
+ // through `undefined` to re-trigger a default.
+ tracks: deriveTracks(columns, walkFrameCount, geometry.tracks ?? null, rows ?? ATLAS_DEFAULT_ROWS),
walkFrameCount,
previewFps: Number.isFinite(geometry.walkFps) ? geometry.walkFps : null,
previewFpsNote: PREVIEW_FPS_NOTE,
diff --git a/server/services/sprites/atlasLayout.test.js b/server/services/sprites/atlasLayout.test.js
index c55c690a7e..a788e43888 100644
--- a/server/services/sprites/atlasLayout.test.js
+++ b/server/services/sprites/atlasLayout.test.js
@@ -13,8 +13,10 @@ import { walkPhaseLabels } from './walkBounds.js';
// consumer actually reads.
import { buildAtlasGrid } from './atlasGrid.js';
import { ANIMATION_TRACKS } from './animationTracks.js';
+import { trackSpan as span } from './spriteTestFixtures.js';
const DIRECTIONS = ['S', 'SE', 'E', 'NE', 'N', 'NW', 'W', 'SW'];
+
// The grid the compiler emits today: idle + N walk phases (#2986 dropped the
// trailing scanner placeholder).
const geometryFor = (walkFrameCount, overrides = {}) => ({
@@ -68,7 +70,7 @@ describe('buildAtlasLayout', () => {
expect(layout.columns).toEqual(['idle', ...walkPhaseLabels(8)]);
// The compiled grid has exactly two tracks — the scanner span is gone with
// the column it described (#2986).
- expect(layout.tracks).toEqual({ idle: { start: 0, count: 1 }, walk: { start: 1, count: 8 } });
+ expect(layout.tracks).toEqual({ idle: span(0, 1), walk: span(1, 8) });
expect(layout.previewFpsNote).toMatch(/do not use this as a runtime frame rate/);
// No timestamp: identical geometry must produce byte-identical content so
// an unchanged republish stays a no-op.
@@ -85,7 +87,7 @@ describe('buildAtlasLayout', () => {
});
expect(layout.columnCount).toBe(10);
expect(layout.walkFrameCount).toBe(8);
- expect(layout.tracks.scanner).toEqual({ start: 9, count: 1 });
+ expect(layout.tracks.scanner).toEqual(span(9, 1));
});
it('describes a two-track grid whose tracks differ in length (#3016)', () => {
@@ -105,9 +107,9 @@ describe('buildAtlasLayout', () => {
atlasDestPath: 'assets/sprites/hero/hero-atlas.png',
});
expect(layout.tracks).toEqual({
- idle: { start: 0, count: 1 },
- walk: { start: 1, count: 12 },
- scanner: { start: 13, count: 4 },
+ idle: span(0, 1),
+ walk: span(1, 12),
+ scanner: span(13, 4),
});
// columns, tracks and the atlas width stay mutually consistent: the spans
// tile the column list exactly, so a consumer sampling by span lands on the
diff --git a/server/services/sprites/publish.js b/server/services/sprites/publish.js
index c3b3eb8b91..c8f8adee73 100644
--- a/server/services/sprites/publish.js
+++ b/server/services/sprites/publish.js
@@ -40,7 +40,7 @@ import { createKeyCachedQueue } from '../../lib/createKeyCachedQueue.js';
import { getAppById } from '../apps.js';
import { isDeploying } from '../appDeployer.js';
import { spriteDir, RUNTIME_POINTER_REL, RUNTIME_PUBLICATIONS_REL } from './paths.js';
-import { requireCharacter } from './reference.js';
+import { requireAnimatable } from './reference.js';
import { listRecords, updateRecord } from './records.js';
import { withWalkWriteTail } from './walk.js';
import { compileAtlasInTail } from './atlas.js';
@@ -156,9 +156,15 @@ export async function validatePublishBinding(binding) {
* particular app was built against, so carrying it across a re-point would make
* every publish to the new app 409 against an expectation that app never
* declared (and, with no UI for the field, leave no way out).
+ *
+ * Gated on the record carrying an animation track (#3017), not on it being a
+ * character — publishing an atlas is about the atlas, and a record kind that
+ * gains a non-directional ambient track should be bindable and publishable
+ * without this gate being revisited. Walk is character-only today, so nothing
+ * that used to be accepted or refused here changes.
*/
export async function setPublishBinding(recordId, binding) {
- const record = await requireCharacter(recordId);
+ const record = await requireAnimatable(recordId);
const validated = await validatePublishBinding(binding);
const stored = record.publishBinding;
if (validated && binding.runtimeContract === undefined && validated.appId === stored?.appId) {
@@ -235,7 +241,7 @@ export function publishAtlas(recordId, options = {}) {
}
async function publishAtlasImpl(recordId, { acknowledgeOverwrite = false } = {}) {
- const record = await requireCharacter(recordId);
+ const record = await requireAnimatable(recordId);
const binding = record.publishBinding;
if (!binding?.appId || !binding?.atlasDestPath) {
throw new ServerError('No publish binding configured — set the target app and atlas path first', { status: 409, code: 'PUBLISH_BINDING_REQUIRED' });
diff --git a/server/services/sprites/publish.test.js b/server/services/sprites/publish.test.js
index 152c170050..a9de9e11e1 100644
--- a/server/services/sprites/publish.test.js
+++ b/server/services/sprites/publish.test.js
@@ -16,6 +16,7 @@ import { tmpdir } from 'os';
import { join } from 'path';
import { mkdir, writeFile, readFile } from 'fs/promises';
import { createHash } from 'crypto';
+import { trackSpan as fullSpan } from './spriteTestFixtures.js';
const TEST_ROOT = mkdtempSync(join(tmpdir(), 'sprite-publish-test-'));
const APP_REPO = join(TEST_ROOT, 'game-repo');
@@ -54,6 +55,7 @@ const sha256 = (buf) => createHash('sha256').update(buf).digest('hex');
const { SPRITE_DIRECTIONS: DIRECTIONS } = await import('./prompts.js');
+
// The geometry block a real compile writes into the runtime pointer — the
// publish path reads it for the contract guard and the layout sidecar.
const atlasGeometry = (walkFrameCount = 8, overrides = {}) => ({
@@ -513,8 +515,8 @@ describe('layout sidecar (#2982)', () => {
expect(layout.columns).toHaveLength(13);
// Per-track spans so a future multi-frame track is additive, not a rewrite.
expect(layout.tracks).toEqual({
- idle: { start: 0, count: 1 },
- walk: { start: 1, count: 12 },
+ idle: fullSpan(0, 1),
+ walk: fullSpan(1, 12),
});
// previewFps travels labeled as authoring-only — the app must not animate from it.
expect(layout.previewFpsNote).toMatch(/Authoring metadata only/);
@@ -533,7 +535,7 @@ describe('layout sidecar (#2982)', () => {
const layout = await readSidecar(BINDING.atlasDestPath);
expect(layout.columnCount).toBe(10);
expect(layout.walkFrameCount).toBe(8);
- expect(layout.tracks.scanner).toEqual({ start: 9, count: 1 });
+ expect(layout.tracks.scanner).toEqual(fullSpan(9, 1));
});
it('is a no-op on an unchanged republish but self-heals a deleted sidecar', async () => {
diff --git a/server/services/sprites/reference.js b/server/services/sprites/reference.js
index 8390511cf6..b5fc7b59f7 100644
--- a/server/services/sprites/reference.js
+++ b/server/services/sprites/reference.js
@@ -42,6 +42,9 @@ import {
buildMainReferencePrompt, buildAnchorPrompt, buildTurnaroundPrompt,
} from './prompts.js';
import { pickChromaKey, keyProximityWarning, CHROMA_KEY_HEXES, DEFAULT_CHROMA_KEY } from './chromaKey.js';
+import {
+ WALK_TRACK, ANIMATION_TRACK_IDS, kindSupportsTrack, tracksForKind,
+} from './animationTracks.js';
import {
analyzeForeground, paletteFromAnalysis, normalizeFromAnalysis, recompositeOnKey,
} from './normalize.js';
@@ -158,15 +161,61 @@ function seedManifest(recordId) {
};
}
-export async function requireCharacter(recordId) {
+/**
+ * THE animation gate (#3017) — one mechanism, two questions.
+ *
+ * Every sprite service used to ask the same literal question, `kind !==
+ * 'character'`, whether it cared about the walk cycle specifically or about
+ * animation in general. Those are different questions, and conflating them is
+ * why `place` and `object` records had no animation path at all: not because
+ * the atlas couldn't hold a tree moving in the wind, but because the gate
+ * refused the record before anything else ran.
+ *
+ * `trackId` names which question to ask — a specific track, or `null` for "any
+ * registered track at all". Both answers are registry DATA, so a row that
+ * admits another record kind unlocks it here with nothing to edit. Deliberately
+ * ONE function rather than a `requireX` per track: N tracks growing N gates is
+ * the special-case-on-shared-infrastructure shape the registry exists to end.
+ *
+ * The message names the kind and the tracks that DO exist, because "this record
+ * kind has no animation track" is a fact about the registry the user can act on,
+ * unlike the old blanket "character records only".
+ */
+export async function requireTrack(recordId, trackId = null) {
const record = await getRecord(recordId);
if (!record) throw new ServerError('Sprite record not found', { status: 404, code: 'NOT_FOUND' });
- if (record.kind !== 'character') {
- throw new ServerError('Reference workflow applies to character records only', { status: 400, code: 'NOT_A_CHARACTER' });
+ const supported = trackId
+ ? kindSupportsTrack(record.kind, trackId)
+ : tracksForKind(record.kind).length > 0;
+ if (!supported) {
+ // The walk gate keeps its historical message and code — callers (and
+ // reference.test.js) match on NOT_A_CHARACTER, and walk is character-only,
+ // so nothing that used to be refused is now admitted or vice versa.
+ if (trackId === WALK_TRACK) {
+ throw new ServerError('Reference workflow applies to character records only', { status: 400, code: 'NOT_A_CHARACTER' });
+ }
+ throw new ServerError(
+ `No animation track applies to ${record.kind} records — the registered tracks are: ${ANIMATION_TRACK_IDS.join(', ')}`,
+ { status: 400, code: 'NOT_ANIMATABLE' },
+ );
}
return record;
}
+/**
+ * The walk/reference-workflow gate. Turnarounds, the eight directional anchors,
+ * walk runs and trims are all gait-shaped, so this stays exactly as strict as it
+ * ever was — it is `requireTrack(id, WALK_TRACK)` under a name its 13 call sites
+ * already use.
+ */
+export const requireCharacter = (recordId) => requireTrack(recordId, WALK_TRACK);
+
+/**
+ * The track-presence gate, for the paths that are about animation as such —
+ * compiling the runtime atlas, and the publish binding / publish that ship it.
+ */
+export const requireAnimatable = (recordId) => requireTrack(recordId);
+
// First free `-vN` filename — locked artifacts are never overwritten; a
// correction after a crash or an anchor unlock lands on the next version
// instead of replacing evidence.
@@ -548,7 +597,10 @@ export async function listReferenceSources() {
const records = await listRecords();
const out = [];
for (const r of records) {
- if (r.kind !== 'character' || r.deleted) continue;
+ // Same question requireCharacter asks — a reference set exists only for a
+ // kind that carries the walk track — so a row admitting another kind is
+ // picked up here too instead of this list silently staying character-only.
+ if (r.deleted || !kindSupportsTrack(r.kind, WALK_TRACK)) continue;
const manifest = await loadManifest(r.id);
// Same picker resolveSourceReference uses, so the advertised image is
// exactly the one a seed will attach.
@@ -582,7 +634,10 @@ export async function listSpriteThumbnails() {
const records = await listRecords();
const results = await Promise.all(records.map(async (r) => {
if (r.deleted) return null;
- if (r.kind === 'character') {
+ // Registry-driven for the same reason as listReferenceSources: a locked
+ // main reference is a property of carrying the walk track, not of the
+ // literal kind name.
+ if (kindSupportsTrack(r.kind, WALK_TRACK)) {
const manifest = await loadManifest(r.id);
const main = manifest?.mainReference;
if (main?.locked && main.path) return { id: r.id, path: main.path };
diff --git a/server/services/sprites/reference.test.js b/server/services/sprites/reference.test.js
index d4dae5ea81..8ae779a5c8 100644
--- a/server/services/sprites/reference.test.js
+++ b/server/services/sprites/reference.test.js
@@ -54,6 +54,7 @@ const records = await import('./records.js');
const {
getReferenceSet, startReferenceGeneration, attachReferenceCandidate, lockReference, patchSpriteRecord,
unlockReferenceAnchor, listReferenceSources, listSpriteThumbnails, forkSprite,
+ requireCharacter, requireAnimatable,
} = await import('./reference.js');
let seq = 0;
@@ -127,6 +128,39 @@ beforeEach(() => {
});
afterAll(() => rmSync(TEST_ROOT, { recursive: true, force: true }));
+describe('the animation gates (#3017)', () => {
+ // The gates used to be one literal `kind !== 'character'` test. They are now
+ // two registry reads with different questions: "may this record carry the
+ // WALK track" (the gait-shaped reference/walk workflow) and "may it carry ANY
+ // track" (compiling and publishing an atlas). Walk is character-only, so both
+ // refuse exactly what they always did — what changed is that adding a row
+ // listing `place` unlocks the second gate with no edit to this file's target.
+ it('404s an unknown record from either gate', async () => {
+ await expect(requireCharacter('nope-1')).rejects.toMatchObject({ code: 'NOT_FOUND' });
+ await expect(requireAnimatable('nope-2')).rejects.toMatchObject({ code: 'NOT_FOUND' });
+ });
+
+ it('admits a character through both gates', async () => {
+ const id = newId();
+ await createCharacter(id);
+ await expect(requireCharacter(id)).resolves.toMatchObject({ id, kind: 'character' });
+ await expect(requireAnimatable(id)).resolves.toMatchObject({ id, kind: 'character' });
+ });
+
+ it('refuses a place/object record, naming the tracks that DO exist', async () => {
+ await records.createRecord({ kind: 'place', name: 'Grove' }, 'grove');
+ // The walk gate keeps its historical code, so existing callers matching on
+ // NOT_A_CHARACTER are unaffected.
+ await expect(requireCharacter('grove')).rejects.toMatchObject({ code: 'NOT_A_CHARACTER' });
+ // The track-presence gate explains itself in terms of the registry, which
+ // is the thing a user (or a future track) can actually change.
+ await expect(requireAnimatable('grove')).rejects.toMatchObject({
+ code: 'NOT_ANIMATABLE',
+ message: /No animation track applies to place records.*walk/,
+ });
+ });
+});
+
describe('startReferenceGeneration', () => {
it('404s an unknown record and 400s a props record', async () => {
await expect(startReferenceGeneration('nope', { target: 'main', designPrompt: 'x' }))
diff --git a/server/services/sprites/spriteTestFixtures.js b/server/services/sprites/spriteTestFixtures.js
index 6a5930eaf9..65983e84e7 100644
--- a/server/services/sprites/spriteTestFixtures.js
+++ b/server/services/sprites/spriteTestFixtures.js
@@ -1,12 +1,20 @@
/**
- * Shared reference-candidate fixture helpers for the sprite test suites
- * (reference.test.js, walk.test.js, atlas.test.js). Each export is
- * parameterized on the calling suite's TEST_ROOT rather than closing over a
- * module-level constant, so every suite keeps its own tmpdir and isolation.
+ * Shared fixture helpers for the sprite test suites (reference.test.js,
+ * walk.test.js, atlas.test.js, atlasGrid.test.js, atlasLayout.test.js,
+ * publish.test.js). The candidate-writing helpers are parameterized on the
+ * calling suite's TEST_ROOT rather than closing over a module-level constant,
+ * so every suite keeps its own tmpdir and isolation.
+ *
+ * The grid fixtures at the bottom are here because four suites were each
+ * spelling out the same track-span shape and two were spelling out the same
+ * synthetic registry row: a new span field (or a new required registry field)
+ * would otherwise be a six-file edit, and any file that missed it would go
+ * green on a stale shape.
*/
import { join } from 'path';
import sharp from 'sharp';
import { mkdir, writeFile } from 'fs/promises';
+import { SPRITE_DIRECTIONS } from './prompts.js';
// A green/teal character rectangle on a magenta background — the legacy
// Pioneer shape, so auto chroma-key selection keeps magenta.
@@ -59,3 +67,39 @@ export async function lockAllAnchors(testRoot, recordId, { lockReference, direct
});
}
}
+
+/**
+ * A track's column span as `buildAtlasGrid` and the layout sidecar emit it.
+ * `rows` defaults to the full grid height, which is what every shipped track
+ * (walk, idle) and every grid compiled before #3017 has — spelled out rather
+ * than omitted so a span that quietly lost its row count reads as a failure.
+ */
+export const trackSpan = (start, count, rows = SPRITE_DIRECTIONS.length) => ({ start, count, rows });
+
+/**
+ * A synthetic NON-directional registry row (#3017), shaped like an ambient
+ * loop: a tree moving in the wind, water, a flickering lamp. Three frames —
+ * below walk's floor of 6 — and no facing at all, so it occupies row 0 and
+ * leaves the other seven transparent. It lists `place`/`object`, the record
+ * kinds that had no animation path whatsoever before the gate became registry
+ * data.
+ *
+ * Synthetic on purpose: the shipped registry's only track is directional and
+ * character-only, so a test written against it alone could not tell "reads the
+ * row" from "hardcodes 8 / hardcodes 'character'". Same injected-table idiom
+ * `assertAnimationTrackRows(tracks)` uses. Shipping the real row is #3045.
+ */
+export const AMBIENT_TRACK_ROW = Object.freeze({
+ id: 'ambient',
+ label: 'Ambient loop',
+ directional: false,
+ kinds: Object.freeze(['place', 'object']),
+ minFrameCount: 2,
+ maxFrameCount: 6,
+ defaultFrameCount: 3,
+ minFps: 2,
+ maxFps: 12,
+ defaultFps: 4,
+ contractFrameCountField: 'ambientFrameCount',
+ contractFpsField: null,
+});