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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix([issue-3021]): register walk frames on one shared hip anchor, through compile
[._.]/ Adam Eivy4801477b159a
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex e75cc7a411..bce32b0f3b 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -35,6 +35,7 @@## Sprite Manager+- **[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-2980] See every frame a walk's video produced — and rebuild the loop at a new frame count without re-rendering** — the Loop Trimmer could only *drop* columns from a strip that was already packed, so an 8-frame walk could never become a 12-frame one there: the extra source frames were thrown away at pack time and nothing in the workspace showed they had ever existed. The trimmer now has a **Source frames** section listing every frame extracted from that run's clip (typically ~70 at 12fps), with the gait cycle the packer picked marked in amber and the frames that became the strip's columns highlighted — so the headroom above the current count is visible at a glance. A **Re-derive from clip** control beside it repacks the loop from that same on-disk video at a new frame count / speed, with no AI call and no new render; the frame count and speed are the walk set's shared cycle target rather than a free per-run range, since every direction of one walk has to agree for the atlas to compile, and changing them says so before it retargets the set. A run whose extracted frames were cleaned up (which is every imported run — the importer doesn't copy them) says so and offers a one-click "Extract frames from clip" rather than quietly running ffmpeg for every direction you happen to click through; an approved direction or a frozen set offers the matching inline Reopen / Unlock instead of failing on click; a run with no clip at all explains that in one line rather than showing an empty grid, and names the right remedy for how it got there; and if the frames on disk turn out not to be the ones the strip was packed from, the cycle markers are withheld rather than pointing at the wrong frames. Re-deriving an *imported* run also works now — its run id was rejected by the reprocess endpoint before it ever reached the service that #2993 taught to handle it.- **[issue-3004] Turnaround sheets stop mirroring the front view, so a front-worn bag no longer ends up on the character's back** — the back panel of a generated turnaround sheet was often just the front figure flipped left-to-right, which meant anything mounted on the *front* of the body (a hip bag worn at the front, a chest pack, a belt buckle) reappeared on the character's back in the rear view, and the same mistake carried into any single rotated view derived from the sheet. The old instruction only pinned accessories to the same anatomical *side* — a rule a mirrored figure satisfies perfectly, because the bug is on the front/back axis, not left/right. The sheet prompt now states that the panels are one character physically *rotated* about a vertical axis and that no panel may be a flip or copy of another, each derived view is told it is a rotation rather than a mirrored copy, and every facing carries its own rule for what that angle hides: a rear view hides front-mounted gear (keeping only what genuinely wraps around, like a strap crossing the back) and shows no face or front closures; a front view hides backpacks and back-slung weapons; each profile hides whatever sits on the far side of the torso — hedged for the diagonal views, where a 45-degree turn only partly hides things, so gear doesn't pop in and out as the sprite rotates. The diagonal views are also now told to interpolate between the two sheet panels they sit between, instead of being pointed at a panel the four-panel sheet doesn't have. The front/back panels also now say where a right-hip item lands on screen once the character turns, so "same side" can't be satisfied by leaving it in the same pixels. The walk-video step is told not to invent gear the anchor hides mid-loop.- **[issue-2993] Imported characters can finally be re-derived — smoother walks, and an atlas you can compile here** — a character brought over from a source art pipeline was frozen the moment it arrived: Unlock, Reopen and Compile all refused it outright, so an imported 8-frame walk could never be brought up to 12 and its atlas could only ever be re-published, never rebuilt. That refusal was written when the import genuinely left nothing behind to work from — but the importer now copies each direction's source clip, so it had become a lie. Those actions are now gated on whether the clip is actually there: a direction with its clip on disk reopens and reprocesses at any frame count and speed, with no new render and no new spend, and the buttons appear instead of being hidden. A direction with no clip is still refused, but now says so plainly and tells you to re-import the character. Compiling is likewise per-direction: the atlas names the directions still packaged by the source pipeline instead of refusing the whole set, so an imported character becomes compilable one direction at a time as you re-derive them — and approving a direction whose packaged frames were never imported is now caught up front, rather than surfacing much later as an unexplained compile error.diff --git a/server/services/sprites/atlas.js b/server/services/sprites/atlas.jsindex 8d7f0ccad1..ee3981cdb2 100644--- a/server/services/sprites/atlas.js+++ b/server/services/sprites/atlas.js@@ -4,8 +4,12 @@* Compiles the immutable runtime sprite-sheet from a finalized eight-direction* walk set: an (idle + N walk phases)-column × 8-row grid (× S/SE/E/* NE/N/NW/W/SW) of fixed-size cells, each frame scaled once per direction and- * translated so its silhouette centers on the pivot x and its feet land exactly- * on the pivot ground line. N (the walk frame count) is read from the approved+ * translated so it anchors on the pivot x and its sole lands exactly on the+ * pivot ground line. Placement is anchored on the HIP, not the silhouette+ * centre, and shared across a direction's cells — a walk frame carries the+ * packer's pivot through the scale, the idle anchor measures its own (#3021) —+ * so a swinging limb cannot slide the character and idle→walk does not pop.+ * N (the walk frame count) is read from the approved* run manifests — every direction must share it — so the atlas width tracks the* authored count (historically 8; variable per #sprite-walk-variable-frames).* Ports the source pipeline's@@ -44,7 +48,7 @@ import {WALK_MIN_FPS, WALK_MAX_FPS, WALK_FPS,pyRound, pyRoundTo, median, decodeRgbaFrame, premultipliedResize,sampleBorderKey, validateMeasuredKey, recoverAlphaFrame, despillKeyFrame,- alphaBbox, compositeOnto, sha256Buffer,+ alphaBbox, robustBottomRow, rootX, ROBUST_BASELINE_MIN_PIXELS, compositeOnto, sha256Buffer,} from './walkPostprocess.js';import { ATLAS_IDLE_COLUMN } from './walkBounds.js';import {@@ -94,10 +98,27 @@ const atlasStem = (recordId) => `${recordId}-animation-atlas`;const compileError = (message, code = 'ATLAS_COMPILE_INVALID') =>new ServerError(message, { status: 422, code });-function occupiedDimensions(frame, threshold, label) {+/**+ * The minimum opaque-pixel count a row needs to read as the sole rather than a+ * stray speck, at a given resize factor. A cell is typically upscaled from the+ * packer's frame, and the resize smears one source pixel across ~`scale` of+ * them — so a fixed count would let an upscaled speck masquerade as a sole.+ */+const cellMinRun = (scale) => Math.max(ROBUST_BASELINE_MIN_PIXELS, Math.ceil(ROBUST_BASELINE_MIN_PIXELS * scale));++/**+ * `robust` measures height to the SOLE rather than to the lowest lit pixel+ * (#3021). It matters here and not only at placement time: these dimensions set+ * the direction's scale, so a single speck below the feet made one frame read+ * taller, shrank the scale for the whole direction, and pushed the compiled idle+ * height off the walk median it is asserted against. Off for the idle anchor,+ * which is measured at the silhouette threshold on a raw reference.+ */+function occupiedDimensions(frame, threshold, label, robust = false) {const bounds = alphaBbox(frame, threshold);if (!bounds) throw compileError(`${label} has no visible pixels`);- return { width: bounds.right - bounds.left, height: bounds.bottom - bounds.top };+ const bottom = robust ? robustBottomRow(frame, threshold) : bounds.bottom;+ return { width: bounds.right - bounds.left, height: bottom - bounds.top };}/**@@ -124,12 +145,12 @@ async function transparentSource(bytes, split, keyHex) {}/**- * Scale a source frame once and translate it into a cell so the silhouette- * centers on pivot x with its feet exactly on the pivot ground line —- * translation-only placement, refusing any content that touches a cell edge.+ * Scale a source frame once and measure what placement needs from it: the bbox+ * the cell-edge guards test, and the sole the ground line is pinned to.+ * Placement itself is `placeCell` — the two are split because a direction's x is+ * SHARED, so every frame has to be measured before any of them can be placed.*/-async function normalizeCellFrame(source, scale, label, geometry) {- const { cellSize, pivot } = geometry;+async function scaleForCell(source, scale, label) {const width = Math.max(1, pyRound(source.width * scale));const height = Math.max(1, pyRound(source.height * scale));const scaled = await premultipliedResize(source, width, height);@@ -141,9 +162,30 @@ async function normalizeCellFrame(source, scale, label, geometry) {}const bounds = alphaBbox(scaled, ALPHA_THRESHOLD);if (!bounds) throw compileError(`${label} has no visible pixels after scaling`);- const centerX = (bounds.left + bounds.right - 1) / 2;- const pasteX = pyRound(pivot[0] - centerX);- const pasteY = pivot[1] - (bounds.bottom - 1);+ // The SOLE, not the lowest lit pixel — vertical placement keys on this.+ // Pinning the raw bbox bottom is what let a sub-sole speck set the ground line+ // and bob the body (#3021), and fixing it only in the packer would have been+ // undone right here: the packer would place the sole at its baseline, leaving+ // the speck lower, and this stage would pin the SPECK to the ground line,+ // landing the body exactly where it started.+ //+ // Measured on `scaled`, in the same space the ground-line assertion re-measures+ // — but with the pixel threshold scaled to match. These cells are upscaled+ // ~2.5x, and a lanczos upscale smears a single stray pixel into a blob several+ // pixels wide, wide enough to clear a fixed threshold and be mistaken for a+ // sole. Scaling the threshold keeps "a speck is a speck" true at any cell size.+ const baseline = robustBottomRow(scaled, ALPHA_THRESHOLD, cellMinRun(scale));+ return { scaled, bounds, baseline };+}++/**+ * Translate an already-scaled frame into a cell at the given x, with its sole on+ * the pivot ground line — translation-only placement, refusing any content that+ * touches a cell edge.+ */+function placeCell(scaled, bounds, baseline, pasteX, label, geometry, scale) {+ const { cellSize, pivot } = geometry;+ const pasteY = pivot[1] - (baseline - 1);if (pasteX + bounds.left <= 0 || pasteY + bounds.top <= 0) {throw compileError(`${label} touches the top or left runtime cell edge`);}@@ -152,11 +194,14 @@ async function normalizeCellFrame(source, scale, label, geometry) {}const cell = { data: Buffer.alloc(cellSize * cellSize * 4), width: cellSize, height: cellSize };compositeOnto(cell, scaled, pasteX, pasteY);- // Port-faithful belt-and-braces: re-measure the composed cell and verify- // the feet really sit on the ground line (runtime_publish.py does the same- // final _bounds check rather than trusting the placement math).+ // Port-faithful belt-and-braces: re-measure the composed cell and verify the+ // feet really sit on the ground line (runtime_publish.py does the same final+ // _bounds check rather than trusting the placement math). Measured by the same+ // robust rule that positioned it — asserting on the raw bbox would fail for+ // any frame carrying a speck below the sole, which is precisely the case this+ // is meant to tolerate.const final = alphaBbox(cell, ALPHA_THRESHOLD);- if (!final || final.bottom - 1 !== pivot[1]) {+ if (!final || robustBottomRow(cell, ALPHA_THRESHOLD, cellMinRun(scale)) - 1 !== pivot[1]) {throw compileError(`${label} misses the runtime ground line y=${pivot[1]}`);}return {@@ -174,6 +219,28 @@ async function normalizeCellFrame(source, scale, label, geometry) {};}+/**+ * The shared x every cell of one direction is placed at, and the correction (if+ * any) needed to keep the whole row inside its cells.+ *+ * Anchoring on the packer's hip pivot rather than each cell's own silhouette+ * centre is what preserves registration through compile (#3021) — but it also+ * moves content off-centre by however far the hip sits from the silhouette+ * middle, which for a wide sprite can be enough to touch a cell edge and turn a+ * previously-successful compile into a hard 422. So the row is shifted back as a+ * WHOLE when that happens: relative registration between frames is preserved+ * exactly (the point of the fix), and only the row's absolute offset gives way.+ * Per-frame correction would reintroduce the very drift being removed.+ */+function sharedRowPasteX(anchoredX, boundsList, geometry) {+ const { cellSize } = geometry;+ const minLeft = Math.min(...boundsList.map((b) => anchoredX + b.left));+ const maxRight = Math.max(...boundsList.map((b) => anchoredX + b.right));+ if (minLeft <= 0) return anchoredX + (1 - minLeft);+ if (maxRight >= cellSize) return anchoredX - (maxRight - cellSize + 1);+ return anchoredX;+}+/*** Revalidate the full evidence chain: finalized walk set → selection →* per-direction run manifests → packaged frame bytes, plus the locked@@ -336,7 +403,7 @@ async function compileDirectionRow(recordId, direction, validated, geometry) {for (const bytes of frameBytes) {walkSources.push(await transparentSource(bytes, split, validated.chromaKey));}- const dims = walkSources.map((f, i) => occupiedDimensions(f, ALPHA_THRESHOLD, `${direction}-${manifest.frames[i].phase}`));+ const dims = walkSources.map((f, i) => occupiedDimensions(f, ALPHA_THRESHOLD, `${direction}-${manifest.frames[i].phase}`, true));const directionScale = Math.min(geometry.targetMaxHeight / Math.max(...dims.map((d) => d.height)),geometry.targetMaxWidth / Math.max(...dims.map((d) => d.width)),@@ -348,7 +415,21 @@ async function compileDirectionRow(recordId, direction, validated, geometry) {const idleDims = occupiedDimensions(idleSource, SILHOUETTE_ALPHA_THRESHOLD, `${direction}-idle`);const desiredIdleHeight = median(dims.map((d) => d.height)) * directionScale;const idleScale = Math.min(desiredIdleHeight / idleDims.height, geometry.targetMaxWidth / idleDims.width);- const idle = await normalizeCellFrame(idleSource, idleScale, `${direction}-idle`, geometry);+ const idleLabel = `${direction}-idle`;+ const idleScaled = await scaleForCell(idleSource, idleScale, idleLabel);+ // The idle anchor is a raw reference with no packer alignment behind it, so+ // its hip is measured directly — the same `rootX` band the packer uses. It+ // must be hip-anchored like the walk cells rather than silhouette-centred: the+ // two rules differ by however far the hip sits off centre, and with idle on one+ // rule and walk on the other the character visibly pops sideways the instant+ // the game starts or stops the gait (#3021). Measured at the silhouette+ // threshold, matching how this cell's scale was derived.+ const idleHipX = rootX(idleScaled.scaled, alphaBbox(idleScaled.scaled, SILHOUETTE_ALPHA_THRESHOLD) || idleScaled.bounds);+ const idle = placeCell(+ idleScaled.scaled, idleScaled.bounds, idleScaled.baseline,+ sharedRowPasteX(pyRound(geometry.pivot[0] - idleHipX), [idleScaled.bounds], geometry),+ idleLabel, geometry, idleScale,+ );if (Math.abs(idle.meta.occupiedBounds.height - desiredIdleHeight) > IDLE_HEIGHT_TOLERANCE) {throw compileError(`${direction} idle height ${idle.meta.occupiedBounds.height} misses the walk median ${pyRoundTo(desiredIdleHeight, 2)}`);}@@ -360,9 +441,32 @@ async function compileDirectionRow(recordId, direction, validated, geometry) {policy: 'locked-directional-reference-anchor',});+ // The packer's pivot x, in the walk frame's own coordinates — the anchor every+ // frame of this direction already shares (#3021). Read from the manifest so a+ // future packer geometry change flows through instead of being duplicated+ // here; a manifest predating `alignment.targetPivot` falls back to the cell+ // centre, which is what WALK_PIVOT has always been.+ const packerPivotX = Number(manifest.alignment?.targetPivot?.[0]);+ const walkPivotX = Number.isFinite(packerPivotX)+ ? packerPivotX+ : (Number(manifest.alignment?.cellSize) || walkSources[0].width) / 2;++ // Scale every walk frame BEFORE placing any of them: the row's x is shared, so+ // it can only be corrected for cell-edge overflow once all the bounds are known.+ const walkScaled = [];for (let i = 0; i < walkSources.length; i++) {+ walkScaled.push(await scaleForCell(walkSources[i], directionScale, `${direction}-${manifest.frames[i].phase}`));+ }+ const walkPasteX = sharedRowPasteX(+ pyRound(geometry.pivot[0] - walkPivotX * directionScale),+ walkScaled.map((w) => w.bounds),+ geometry,+ );++ for (let i = 0; i < walkScaled.length; i++) {const frame = manifest.frames[i];- const normalized = await normalizeCellFrame(walkSources[i], directionScale, `${direction}-${frame.phase}`, geometry);+ 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 });}diff --git a/server/services/sprites/atlas.test.js b/server/services/sprites/atlas.test.jsindex 1f2ca37a72..ac91ad5cb5 100644--- a/server/services/sprites/atlas.test.js+++ b/server/services/sprites/atlas.test.js@@ -55,7 +55,14 @@ async function lockAllAnchors(id) {}/** Transparent 40×40 RGBA frame with an opaque 20×30 figure. */-async function walkFramePng(path, tint) {+/**+ * `armX` (optional) adds a protruding block at that column — a stand-in for a+ * swinging limb, so a direction's frames differ in SILHOUETTE and not just in+ * tint. Registration bugs (#3021) only show up across differing silhouettes:+ * with the identical-shape default, every placement rule agrees and an+ * inter-cell assertion would pass vacuously.+ */+async function walkFramePng(path, tint, armX = null, speck = false) {const w = 40; const h = 40;const buf = Buffer.alloc(w * h * 4);for (let y = 5; y < 35; y++) {@@ -63,11 +70,21 @@ async function walkFramePng(path, tint) {buf.set([tint, 107, 101, 255], (y * w + x) * 4);}}+ if (armX !== null) {+ for (let y = 12; y < 20; y++) {+ for (let x = armX; x < armX + 6; x++) buf.set([tint, 107, 101, 255], (y * w + x) * 4);+ }+ }+ // A lone opaque pixel below the sole — the despill survivor / dropped shadow+ // that used to drag the whole frame's grounding down with it.+ if (speck) buf.set([tint, 107, 101, 255], (35 * w + 20) * 4);await mkdir(join(path, '..'), { recursive: true });await sharp(buf, { raw: { width: w, height: h, channels: 4 } }).png().toFile(path);}-async function buildFinalizedWalkSet(recordId, { frameCount = WALK_PHASES.length, fps } = {}) {+async function buildFinalizedWalkSet(recordId, {+ frameCount = WALK_PHASES.length, fps, varyArm = false, alignment = null, speckFrames = [],+} = {}) {const manifest = await loadManifest(recordId);const chromaKey = manifest.chromaKey;const dir = join(TEST_ROOT, 'sprites', recordId);@@ -86,7 +103,7 @@ async function buildFinalizedWalkSet(recordId, { frameCount = WALK_PHASES.lengthfor (let i = 0; i < labels.length; i++) {const name = `${String(i).padStart(2, '0')}-${labels[i]}.png`;const rel = `${generatedRel}/frames/${name}`;- await walkFramePng(join(dir, rel), 20 + i * 8);+ await walkFramePng(join(dir, rel), 20 + i * 8, varyArm ? 2 + (i % 4) * 2 : null, speckFrames.includes(i));frames.push({outputIndex: i,phase: labels[i],@@ -102,6 +119,7 @@ async function buildFinalizedWalkSet(recordId, { frameCount = WALK_PHASES.lengthchromaKey,frameCount,...(fps != null ? { frameRate: fps } : {}),+ ...(alignment ? { alignment } : {}),frames,};const manifestRel = `${generatedRel}/${recordId}-walk-${direction}-manifest.json`;@@ -190,6 +208,57 @@ describe('compileAtlas', () => {expect(state.publications).toEqual([]);});+ // #3021: the compiler used to re-derive each cell's x from its own silhouette+ // centre, discarding the shared hip anchor the packer had already established+ // — so a swinging limb slid the whole character even when the strip was+ // perfectly registered. The frames here differ in silhouette (varyArm), which+ // is the only condition under which the two rules disagree.+ it('preserves the packer hip anchor across a direction, so a swinging limb cannot slide the character', async () => {+ const id = newId();+ await lockAllAnchors(id);+ await buildFinalizedWalkSet(id, {+ varyArm: true,+ alignment: { cellSize: 40, targetPivot: [20, 35] },+ });+ const result = await compileAtlas(id);+ const manifest = JSON.parse(await readFile(join(TEST_ROOT, 'sprites', id, result.manifestPath), 'utf8'));++ for (const row of manifest.directions) {+ const walkCells = row.cells.filter((c) => c.column !== 'idle');+ // Every walk cell of a direction lands on ONE x — that IS the preserved+ // registration. (The idle cell is a raw anchor with no packer alignment+ // behind it, so it keeps silhouette-centre placement and is excluded.)+ expect(new Set(walkCells.map((c) => c.translation[0])).size).toBe(1);+ // Guard against passing because the silhouettes came out identical after+ // all: the varying limb must still be visible in the measured bounds.+ expect(new Set(walkCells.map((c) => c.occupiedBounds.width)).size).toBeGreaterThan(1);+ // The runtime ground-line contract is per-cell and still holds.+ for (const cell of row.cells) {+ expect(cell.occupiedBounds.top + cell.occupiedBounds.height - 1).toBe(DEFAULT_ATLAS_GEOMETRY.pivot[1]);+ }+ }+ });++ // The packer's robust baseline is only worth having if it survives compile.+ // It nearly didn't: this stage pinned the raw bbox bottom at a FOUR TIMES more+ // sensitive alpha threshold, so it re-pinned the speck to the ground line and+ // landed the body exactly where the old code did — fixing the strip preview+ // and nothing the game actually loads.+ it('ignores a speck below the sole when grounding a compiled cell', async () => {+ const id = newId();+ await lockAllAnchors(id);+ await buildFinalizedWalkSet(id, { speckFrames: [2], alignment: { cellSize: 40, targetPivot: [20, 35] } });+ const result = await compileAtlas(id);+ const manifest = JSON.parse(await readFile(join(TEST_ROOT, 'sprites', id, result.manifestPath), 'utf8'));++ for (const row of manifest.directions) {+ const walkCells = row.cells.filter((c) => c.column !== 'idle');+ // The specked frame must sit at the same height as its neighbours: one+ // stray pixel below the feet must not lift the body.+ expect(new Set(walkCells.map((c) => c.translation[1])).size).toBe(1);+ }+ });+it('compiles a variable-frame (12-frame) walk set into a wider atlas + geometry', async () => {const id = newId();await lockAllAnchors(id);diff --git a/server/services/sprites/walkPostprocess.js b/server/services/sprites/walkPostprocess.jsindex 5d1979f5a5..18a656a096 100644--- a/server/services/sprites/walkPostprocess.js+++ b/server/services/sprites/walkPostprocess.js@@ -76,6 +76,10 @@ const KEY_REPAIR_RADIUS = 8; // despill neighbor-search chebyshev radiusconst OPAQUE_EDGE_ALPHA = 245; // alpha at/above this counts as clean/opaqueconst BBOX_ALPHA_THRESHOLD = 24; // alpha_bbox visibility thresholdconst ROOT_ALPHA_THRESHOLD = 48; // root_x band pixel threshold+// How many opaque pixels a row needs to count as the character's sole rather+// than a stray speck (#3021). A real sole is tens of pixels wide at these+// scales; a despill survivor or shadow remnant is one or two.+export const ROBUST_BASELINE_MIN_PIXELS = 3;const SIGNATURE_SIZE = 48;const SIGNATURE_BACKGROUND = { r: 48, g: 52, b: 54 };const MIN_CYCLE_MOTION = 0.75;@@ -375,6 +379,31 @@ export function selectCycleIndices(signatures, frameCount = WALK_FRAME_COUNT) {};}+/**+ * The frame's baseline: the lowest row carrying at least `minRun` opaque pixels,+ * returned as a height (exclusive bottom) so it drops into the same arithmetic+ * as `resized.height`.+ *+ * Using the raw bbox bottom made vertical registration hostage to a single+ * pixel (#3021) — one surviving despill speck or a soft shadow below the feet+ * extended the bbox, and pinning that to the baseline lifted the entire body by+ * that much. Requiring a short RUN of opaque pixels ignores stragglers while+ * still finding the real sole, which is many pixels wide. Falls back to the+ * bbox bottom when no row qualifies (a very small or very sparse frame), so a+ * legitimate thin sprite still registers rather than throwing.+ */+export function robustBottomRow(frame, threshold = BBOX_ALPHA_THRESHOLD, minRun = ROBUST_BASELINE_MIN_PIXELS) {+ const { data, width, height } = frame;+ for (let y = height - 1; y >= 0; y--) {+ let count = 0;+ for (let x = 0; x < width; x++) {+ if (data[(y * width + x) * 4 + 3] > threshold && ++count >= minRun) return y + 1;+ }+ }+ const bbox = alphaBbox(frame, threshold);+ return bbox ? bbox.bottom : height;+}+/** Tight bbox of visible (alpha > threshold) pixels; exclusive right/bottom. */export function alphaBbox(frame, threshold = BBOX_ALPHA_THRESHOLD) {const { data, width, height } = frame;@@ -471,6 +500,19 @@ export async function alignFrames(frames) {const maxWidth = Math.max(...bboxes.map((b) => b.right - b.left));const maxHeight = Math.max(...bboxes.map((b) => b.bottom - b.top));const scale = Math.min(1, (WALK_CELL_SIZE * 0.78) / maxWidth, (WALK_CELL_SIZE * 0.82) / maxHeight);++ // ONE hip anchor for the whole direction (#3021). Anchoring x per frame made+ // the body slide: `rootX` is the median of the hip/leg band, so it migrates as+ // the legs scissor, and being a float median of an even-sized set it lands on+ // .5 often enough that banker's rounding alternates the result by 1px on+ // consecutive frames — a toggle locked to frame parity. A walk cycle rendered+ // in place has a constant hip x by definition, so the median ACROSS frames is+ // both the physically correct model and immune to per-frame silhouette noise.+ // Per-frame values stay in the manifest (`hipOffsets`) for diagnostics.+ const sourceRootXs = frames.map((f, i) => (rootX(f, bboxes[i]) - bboxes[i].left) * scale);+ const sharedRootX = median(sourceRootXs);+ const dx = pyRound(WALK_PIVOT[0] - sharedRootX);+const aligned = [];const translations = [];for (let i = 0; i < frames.length; i++) {@@ -478,9 +520,11 @@ export async function alignFrames(frames) {const cropped = cropFrame(frames[i], bbox);const size = [Math.max(1, pyRound(cropped.width * scale)), Math.max(1, pyRound(cropped.height * scale))];const resized = await premultipliedResize(cropped, size[0], size[1]);- const sourceRootX = (rootX(frames[i], bbox) - bbox.left) * scale;- const dx = pyRound(WALK_PIVOT[0] - sourceRootX);- const dy = pyRound(WALK_PIVOT[1] - resized.height);+ // Feet land on the baseline by the frame's ROBUST bottom, not its bbox+ // bottom. `alphaBbox` extends to a single surviving despill speck or a+ // dropped shadow, and pinning that to y=352 lifted the whole body by+ // however far the speck sat below the feet.+ const dy = pyRound(WALK_PIVOT[1] - robustBottomRow(resized));const canvas = blankFrame(WALK_CELL_SIZE, WALK_CELL_SIZE);compositeOnto(canvas, resized, dx, dy);aligned.push(canvas);@@ -492,7 +536,14 @@ export async function alignFrames(frames) {cellSize: WALK_CELL_SIZE,fixedScale: pyRoundTo(scale, 8),targetPivot: WALK_PIVOT,- operation: 'one-fixed-scale-plus-per-frame-translation',+ // Renamed from 'one-fixed-scale-plus-per-frame-translation': x is now+ // shared across the direction, so only y varies per frame. The shared x+ // itself is not stored separately — it IS every entry of `translations`.+ operation: 'one-fixed-scale-shared-hip-x-plus-per-frame-baseline-y',+ // The per-frame hip measurements the shared anchor was taken from. Kept+ // for diagnostics: their spread is the drift this alignment cancels, so a+ // regression shows up as translations moving with them again.+ hipOffsets: sourceRootXs.map((v) => pyRoundTo(v, 4)),translations,},};diff --git a/server/services/sprites/walkPostprocess.test.js b/server/services/sprites/walkPostprocess.test.jsindex 163db17c5c..71f3dae832 100644--- a/server/services/sprites/walkPostprocess.test.js+++ b/server/services/sprites/walkPostprocess.test.js@@ -14,7 +14,7 @@ import {pyRound, pyRoundTo, median, sampleBorderKey, validateMeasuredKey,isUsableMeasuredKey, longestUsableSpan,recoverAlphaFrame, despillKeyFrame, imageDistance, selectCycleIndices,- alphaBbox, rootX, alignFrames, packStrip, validateFrames, buildContrastSheet,+ alphaBbox, rootX, robustBottomRow, alignFrames, packStrip, validateFrames, buildContrastSheet,prepareWalkAnchorChromaInput, WALK_PHASES, WALK_CELL_SIZE, WALK_FRAME_COUNT,} from './walkPostprocess.js';import { keyChannelSplit } from './chromaKey.js';@@ -216,7 +216,7 @@ describe('alignFrames / packStrip', () => {const { frames, alignment } = await alignFrames([frame]);expect(frames[0].width).toBe(WALK_CELL_SIZE);expect(alignment.fixedScale).toBe(1); // fits inside 299×314 unscaled- expect(alignment.operation).toBe('one-fixed-scale-plus-per-frame-translation');+ expect(alignment.operation).toBe('one-fixed-scale-shared-hip-x-plus-per-frame-baseline-y');const [dx, dy] = alignment.translations[0];expect(dy).toBe(352 - 200); // feet on the baselineexpect(dx).toBe(192 - 50); // hip median (col 99.5 abs → 49.5 rel) → pyRound(192-49.5)=142@@ -235,6 +235,63 @@ describe('alignFrames / packStrip', () => {expect(alignment.fixedScale).toBeLessThan(1);});+ // Registration is a relationship BETWEEN frames, so a single-frame call can't+ // observe it — which is why the per-frame drift in #3021 went untested for so+ // long. These build a synthetic direction whose frames differ only in ways a+ // real gait differs, and assert the character doesn't move because of it.+ describe('inter-frame registration (#3021)', () => {+ // Torso/hips identical in every frame; only an arm swings. A viewer should+ // see the arm move and the body stay put.+ const swingingArm = (armX) => {+ const frame = makeFrame(200, 300);+ fillRect(frame, 80, 40, 120, 240, [80, 60, 40, 255]); // torso+legs, fixed+ fillRect(frame, armX, 90, armX + 20, 130, [80, 60, 40, 255]); // arm, moves+ return frame;+ };++ it('gives every frame the same x, so a swinging arm cannot slide the body', async () => {+ const { alignment } = await alignFrames([swingingArm(50), swingingArm(80), swingingArm(120)]);+ const xs = alignment.translations.map(([dx]) => dx);+ expect(new Set(xs).size).toBe(1);+ // The per-frame measurements are kept for diagnostics and DO still vary —+ // pin that, so this test can't pass by the anchor becoming constant.+ expect(new Set(alignment.hipOffsets).size).toBeGreaterThan(1);+ });++ it('keeps the baseline stable across frames of equal height', async () => {+ const { alignment } = await alignFrames([swingingArm(50), swingingArm(80), swingingArm(120)]);+ const ys = alignment.translations.map(([, dy]) => dy);+ expect(Math.max(...ys) - Math.min(...ys)).toBeLessThanOrEqual(1);+ });++ // The single-pixel sensitivity that made the body bob: one speck below the+ // feet used to extend the bbox and lift the whole frame by that distance.+ it('ignores a stray speck below the feet when setting the baseline', async () => {+ const clean = swingingArm(80);+ const specked = swingingArm(80);+ setPx(specked, 100, 260, [80, 60, 40, 255]); // 20px below the sole+ const { alignment } = await alignFrames([clean, specked]);+ const [, dyClean] = alignment.translations[0];+ const [, dySpecked] = alignment.translations[1];+ expect(dySpecked).toBe(dyClean);+ });++ it('still finds the sole when the character is genuinely thin', async () => {+ // 4px wide — above the 3px run threshold, so it registers on its own sole+ // rather than falling back.+ const thin = makeFrame(60, 120);+ fillRect(thin, 20, 10, 24, 100, [80, 60, 40, 255]);+ expect(robustBottomRow(thin)).toBe(100);+ });++ it('falls back to the bbox bottom rather than throwing on a sub-threshold frame', async () => {+ // 2px wide — never satisfies the run threshold on any row.+ const sliver = makeFrame(40, 60);+ fillRect(sliver, 10, 5, 12, 50, [80, 60, 40, 255]);+ expect(robustBottomRow(sliver)).toBe(50);+ });+ });+it('packs 8 cells into one 3072×384 row', () => {const frames = Array.from({ length: 8 }, () => makeFrame(WALK_CELL_SIZE, WALK_CELL_SIZE));const strip = packStrip(frames);