A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
feat(anim): a clip anchors each frame, so shifting artwork keeps its feet planted
yhhc34d2c67b2fc
diff --git a/desktop/src/components/GridField.tsx b/desktop/src/components/GridField.tsxindex e6b300d0d..883a92e7e 100644--- a/desktop/src/components/GridField.tsx+++ b/desktop/src/components/GridField.tsx@@ -11,6 +11,10 @@ export function GridField(props: {label: string;value: number;min?: number;+ /** Upper clamp; grid geometry has none, a normalized anchor has 1. */+ max?: number;+ /** Decimals to keep. Omitted = the integer pixel grid this field started as. */+ decimals?: number;className?: string;onCommit: (n: number) => void;}) {@@ -18,14 +22,19 @@ export function GridField(props: {useEffect(() => setText(String(props.value)), [props.value]);const commit = () => {const n = Number(text);- if (Number.isFinite(n) && n !== props.value) props.onCommit(Math.max(props.min ?? 0, Math.floor(n)));- else setText(String(props.value));+ if (!Number.isFinite(n) || n === props.value) {+ setText(String(props.value));+ return;+ }+ const q = props.decimals === undefined ? Math.floor(n) : Number(n.toFixed(props.decimals));+ props.onCommit(Math.min(props.max ?? Infinity, Math.max(props.min ?? 0, q)));};return (<label className={props.className ?? 'ts-field'}><span>{props.label}</span><input- type="number" value={text} min={props.min ?? 0}+ type="number" value={text} min={props.min ?? 0} max={props.max}+ step={props.decimals === undefined ? 1 : 10 ** -props.decimals}onChange={(e) => setText(e.target.value)}onBlur={commit}onKeyDown={(e) => { if (e.key === 'Enter') (e.target as HTMLInputElement).blur(); }}diff --git a/desktop/src/engine/FlipbookViewportPreview.ts b/desktop/src/engine/FlipbookViewportPreview.tsindex 0f0872d31..85cc939e3 100644--- a/desktop/src/engine/FlipbookViewportPreview.ts+++ b/desktop/src/engine/FlipbookViewportPreview.ts@@ -12,16 +12,17 @@* clip is open in the Flipbook editor, the document's live asset is sampled* instead of the file, so frame edits animate as you make them.*- * Only sheet-cell frames preview (writing uvOffset/uvScale on the existing- * sheet texture); legacy per-texture clips would need live handle resolution- * and keep their panel-only preview. Restores the captured Sprite on deselect,+ * Only sheet-cell frames preview (writing uvOffset/uvScale — and the frame's+ * anchor, when the clip authors one — on the existing sheet texture); legacy+ * per-texture clips would need live handle resolution and keep their panel-only+ * preview. Restores the captured Sprite on deselect,* play-mode entry, or the Preview FX flag going off. The scene saves from the* MODEL, never the World, so these transient writes cannot leak into the file.*/import {- getComponent, parseAnimClipAsset, animClipCellUv,- type AnimClipAssetData, type AnimClipFrameData,+ getComponent, parseAnimClipAsset, animClipCellUv, animClipFramePivot,+ type AnimClipAssetData, type AnimClipFrameData, type AnimClipPivotData,} from 'esengine';import { AnimClipDocument } from '@/flipbook/AnimClipDocument';import { useSelection } from '@/store/selectionStore';@@ -174,8 +175,18 @@ export class FlipbookViewportPreviewImpl {if (!sheet || !frame || frame.cell === undefined) return;if (!world.valid(this.bound.entity) || !world.has(this.bound.entity, Sprite)) return;const uv = animClipCellUv(sheet, frame.cell);+ // The frame's anchor, resolved through the same seam the runtime bakes with. A+ // clip that authors none falls back to the CAPTURED base pivot, not to whatever+ // an earlier frame left behind — so unticking Anchor snaps back immediately.+ const pivot = animClipFramePivot(this.asset, frame)+ ?? (this.baseSprite as { pivot?: AnimClipPivotData } | null)?.pivot;const sprite = world.get(this.bound.entity, Sprite) as { uvOffset: unknown; uvScale: unknown };- world.set(this.bound.entity, Sprite, { ...sprite, uvOffset: uv.uvOffset, uvScale: uv.uvScale });+ world.set(this.bound.entity, Sprite, {+ ...sprite,+ uvOffset: uv.uvOffset,+ uvScale: uv.uvScale,+ ...(pivot ? { pivot: { x: pivot.x, y: pivot.y } } : {}),+ });}}diff --git a/desktop/src/engine/entitySources.ts b/desktop/src/engine/entitySources.tsindex a27de98dd..03bda8d6d 100644--- a/desktop/src/engine/entitySources.ts+++ b/desktop/src/engine/entitySources.ts@@ -115,6 +115,8 @@ export function animatedSpritePrefab(texture?: string;size?: { x: number; y: number };uv?: { uvOffset: { x: number; y: number }; uvScale: { x: number; y: number } };+ /** Frame 0's anchor, when the clip authors anchors (else the Sprite default). */+ pivot?: { x: number; y: number };loop?: boolean;},): PrefabData {@@ -125,6 +127,7 @@ export function animatedSpritePrefab(sprite.uvOffset = { ...seed.uv.uvOffset };sprite.uvScale = { ...seed.uv.uvScale };}+ if (seed.pivot) sprite.pivot = { x: seed.pivot.x, y: seed.pivot.y };return preset(name, [['Transform', {}],['Sprite', sprite],diff --git a/desktop/src/flipbook/AnimClipCommands.ts b/desktop/src/flipbook/AnimClipCommands.tsindex be09d65c5..c24c6fc22 100644--- a/desktop/src/flipbook/AnimClipCommands.ts+++ b/desktop/src/flipbook/AnimClipCommands.ts@@ -7,13 +7,18 @@* step; the panel never mutates the asset directly.*/-import { serializeAnimClip, type AnimClipSheetData } from 'esengine';+import {+ serializeAnimClip, animClipDrivesPivot, DEFAULT_ANIM_CLIP_PIVOT,+ type AnimClipSheetData, type AnimClipPivotData,+} from 'esengine';import { AnimClipDocument } from './AnimClipDocument';import { Toasts } from '@/store/Toasts';import { t } from '@/i18n';type GridPatch = Partial<Pick<AnimClipSheetData, 'cellWidth' | 'cellHeight' | 'margin' | 'spacing'>>;+const finitePivot = (p: AnimClipPivotData): boolean => Number.isFinite(p.x) && Number.isFinite(p.y);+export const AnimClipCommands = {/** Edit the sheet grid geometry; every cell frame follows the new slicing. */setGrid(patch: GridPatch): void {@@ -78,6 +83,44 @@ export const AnimClipCommands = {});},+ /**+ * Turn frame anchors on or off for the whole clip. On seeds the clip-wide anchor+ * (centered, i.e. what `Sprite.pivot` already defaults to); off drops the clip+ * anchor AND every frame override, which is the only way back to "playback never+ * touches the entity's pivot".+ */+ setAnchorsEnabled(on: boolean): void {+ const asset = AnimClipDocument.asset;+ if (!asset || animClipDrivesPivot(asset) === on) return;+ AnimClipDocument.edit(on ? 'Enable Frame Anchors' : 'Disable Frame Anchors', (a) => {+ if (on) {+ a.pivot = { ...DEFAULT_ANIM_CLIP_PIVOT };+ return;+ }+ delete a.pivot;+ for (const f of a.frames) delete f.pivot;+ });+ },++ /** The clip-wide anchor every frame without an override inherits. */+ setClipPivot(pivot: AnimClipPivotData): void {+ if (!finitePivot(pivot)) return;+ AnimClipDocument.edit('Edit Clip Anchor', (a) => {+ a.pivot = { x: pivot.x, y: pivot.y };+ });+ },++ /** Per-frame anchor override; `undefined` falls the frame back to the clip anchor. */+ setFramePivot(index: number, pivot: AnimClipPivotData | undefined): void {+ if (pivot && !finitePivot(pivot)) return;+ AnimClipDocument.edit(pivot ? 'Edit Frame Anchor' : 'Clear Frame Anchor', (a) => {+ const f = a.frames[index];+ if (!f) return;+ if (pivot) f.pivot = { x: pivot.x, y: pivot.y };+ else delete f.pivot;+ });+ },+setFps(fps: number): void {if (!Number.isFinite(fps) || fps < 1) return;AnimClipDocument.edit('Edit FPS', (a) => {diff --git a/desktop/src/flipbook/animClipInspectorModel.ts b/desktop/src/flipbook/animClipInspectorModel.tsindex e8b75d942..77b667651 100644--- a/desktop/src/flipbook/animClipInspectorModel.ts+++ b/desktop/src/flipbook/animClipInspectorModel.ts@@ -9,7 +9,7 @@* route through AnimClipCommands (one undo step each). The point is one* inspector, no bespoke property panel.*/-import type { AnimClipAssetData } from 'esengine';+import { animClipDrivesPivot, DEFAULT_ANIM_CLIP_PIVOT, type AnimClipAssetData } from 'esengine';import type { InspectorComponent, InspectorFieldType, GradientValue, CurveValue, DimensionValue, MapValue } from '@/types';import { AnimClipCommands } from './AnimClipCommands';import { t } from '@/i18n';@@ -37,6 +37,19 @@ export function buildAnimClipComponents(asset: AnimClipAssetData): InspectorComp],},];+ // Only once the clip drives anchors — the Flipbook editor's Anchor toggle owns+ // that switch, so the inspector never conjures pivot data into a clip.+ if (animClipDrivesPivot(asset)) {+ const p = asset.pivot ?? DEFAULT_ANIM_CLIP_PIVOT;+ out[0].fields.push({+ key: 'pivot',+ label: t('fb.field.pivot'),+ type: 'vec2',+ value: [p.x, p.y],+ defaultValue: [DEFAULT_ANIM_CLIP_PIVOT.x, DEFAULT_ANIM_CLIP_PIVOT.y],+ tooltip: t('fb.field.pivotTip'),+ });+ }const s = asset.sheet;if (s) {out.push({@@ -63,6 +76,11 @@ export function makeAnimClipWrite() {case 'loop':AnimClipCommands.setLoop(value === 1 || value === true);break;+ case 'pivot': {+ const v = value as number[];+ AnimClipCommands.setClipPivot({ x: v[0], y: v[1] });+ break;+ }case 'cellWidth':case 'cellHeight':case 'margin':diff --git a/desktop/src/flipbook/createAnimatedSprite.ts b/desktop/src/flipbook/createAnimatedSprite.tsindex d0834ea8e..3f780fcd6 100644--- a/desktop/src/flipbook/createAnimatedSprite.ts+++ b/desktop/src/flipbook/createAnimatedSprite.ts@@ -8,7 +8,9 @@* static pose IS frame 0 (sheet texture + first cell's UV window), and* Play animates with zero code.*/-import { parseAnimClipAsset, animClipCellUv, type AnimClipAssetData } from 'esengine';+import {+ parseAnimClipAsset, animClipCellUv, animClipFramePivot, type AnimClipAssetData,+} from 'esengine';import { Images } from 'lucide-react';import { createFromSource, animatedSpritePrefab, type EntitySource } from '@/engine/entitySources';import { useSelection } from '@/store/selectionStore';@@ -20,6 +22,7 @@ function animClipSource(clipPath: string, clipRef: string, asset: AnimClipAssetDconst name = (clipPath.split('/').pop() ?? 'Sprite').replace(/\.[^.]+$/, '') || 'Sprite';const sheet = asset.sheet;const firstCell = asset.frames.find((f) => f.cell !== undefined)?.cell;+ const first = asset.frames[0];return {id: `animclip:${clipPath}`,label: name,@@ -30,6 +33,7 @@ function animClipSource(clipPath: string, clipRef: string, asset: AnimClipAssetDtexture: sheet?.texture ?? asset.frames[0]?.texture,size: sheet ? { x: sheet.cellWidth, y: sheet.cellHeight } : undefined,uv: sheet && firstCell !== undefined ? animClipCellUv(sheet, firstCell) : undefined,+ pivot: first ? animClipFramePivot(asset, first) ?? undefined : undefined,loop: asset.loop ?? true,}),afterCreate: (_ctx, rootId) => {diff --git a/desktop/src/i18n/messages/flipbook.ts b/desktop/src/i18n/messages/flipbook.tsindex a87460bc1..e162d531d 100644--- a/desktop/src/i18n/messages/flipbook.ts+++ b/desktop/src/i18n/messages/flipbook.ts@@ -38,6 +38,25 @@ export const flipbookMessages = defineMessages({'fb.event.onFrame': { en: 'Fires on this frame', zh: '在此帧触发' },'fb.event.remove': { en: 'Remove event', zh: '移除事件' },'fb.events.empty': { en: 'No events — add one at the current frame', zh: '暂无事件——在当前帧添加一个' },+ 'fb.anchor': { en: 'Anchor', zh: '锚点' },+ 'fb.anchor.tip': {+ en: "Per-frame anchor: drive the sprite's pivot from the clip so the artwork can shift inside the cell without the character sliding. Off = playback leaves the entity's own pivot alone.",+ zh: '逐帧锚点:由剪辑驱动精灵的中心点,画面在格子里位移时角色也不会跟着滑动。关闭 = 播放不触碰实体自身的中心点。',+ },+ 'fb.anchor.x': { en: 'Anchor X', zh: '锚点 X' },+ 'fb.anchor.y': { en: 'Anchor Y', zh: '锚点 Y' },+ 'fb.anchor.frameTip': {+ en: 'Anchor of the current frame (0–1 of the frame, 0,0 = bottom-left). Editing it overrides the clip anchor for this frame only.',+ zh: '当前帧的锚点(0–1,相对该帧,0,0 = 左下角)。修改后仅覆盖此帧,其余帧仍用剪辑锚点。',+ },+ 'fb.anchor.dragTip': { en: 'Drag to anchor this frame', zh: '拖动以设置此帧锚点' },+ 'fb.anchor.clearFrame': { en: 'Clear this frame’s anchor override', zh: '清除此帧的锚点覆盖' },+ 'fb.anchor.overridden': { en: 'Anchored separately from the clip', zh: '锚点已单独覆盖' },+ 'fb.field.pivot': { en: 'Default Anchor', zh: '默认锚点' },+ 'fb.field.pivotTip': {+ en: 'Clip-wide anchor (0–1 of the frame, 0,0 = bottom-left) — frames without their own anchor inherit it. Written onto Sprite.pivot during playback.',+ zh: '整段剪辑的锚点(0–1,相对帧,0,0 = 左下角)——没有自己锚点的帧继承它。播放时写入 Sprite.pivot。',+ },'fb.onion': { en: 'Onion skin', zh: '洋葱皮' },'fb.onionFrames': { en: 'Frames', zh: '帧数' },'fb.onionTip': { en: 'Ghost the nearest frames behind the current one (while paused)', zh: '暂停时在当前帧后叠印相邻帧,便于对位' },diff --git a/desktop/src/panels/FlipbookEditor.tsx b/desktop/src/panels/FlipbookEditor.tsxindex 88db932ed..d9a0c6cf3 100644--- a/desktop/src/panels/FlipbookEditor.tsx+++ b/desktop/src/panels/FlipbookEditor.tsx@@ -4,9 +4,9 @@* @file FlipbookEditor.tsx* @brief The .esanim sprite-flipbook editor panel — the sheet texture with a* slicing-grid overlay (click or drag cells to append frames) over a- * frame strip with per-frame durations, fps/loop, and a live looping- * preview. Subscribes to the reactive AnimClipDocument; mutations go- * through AnimClipCommands (one undo step each).+ * frame strip with per-frame durations, fps/loop, a draggable frame anchor,+ * and a live looping preview. Subscribes to the reactive AnimClipDocument;+ * mutations go through AnimClipCommands (one undo step each).*/import {@@ -15,8 +15,8 @@ import {} from 'react';import { Plus, Trash2, X, Film } from 'lucide-react';import {- animClipSheetCols, animClipSheetRows,- type AnimClipFrameData, type AnimClipSheetData,+ animClipSheetCols, animClipSheetRows, animClipDrivesPivot, animClipFramePivot,+ type AnimClipFrameData, type AnimClipPivotData, type AnimClipSheetData,} from 'esengine';import { EmptyState } from '@/components/EmptyState';import { GridField } from '@/components/GridField';@@ -79,6 +79,9 @@ export function FlipbookEditor() {frameIdxRef.current = frameIdx;const [onion, setOnion] = useState(true);const [onionFrames, setOnionFrames] = useState(1);+ // Live anchor drag: shown while the pointer is down, committed once on release+ // (one undo step, same shape as the cell-append stroke above).+ const [anchorDrag, setAnchorDrag] = useState<AnimClipPivotData | null>(null);const playFrames = asset?.frames;const playFps = asset?.fps ?? 12;@@ -126,6 +129,22 @@ export function FlipbookEditor() {const curFrame = Math.min(frameIdx, Math.max(0, asset.frames.length - 1));+ // Anchors: the clip drives Sprite.pivot only once it authors one. The stage+ // handle edits the CURRENT frame; the clip-wide default lives in the inspector.+ const anchors = animClipDrivesPivot(asset);+ const curPivot: AnimClipPivotData =+ anchorDrag ?? (asset.frames[curFrame] ? animClipFramePivot(asset, asset.frames[curFrame]) : null) ?? { x: 0.5, y: 0.5 };+ const pivotFromPointer = (e: { clientX: number; clientY: number; currentTarget: HTMLElement }): AnimClipPivotData => {+ const r = e.currentTarget.getBoundingClientRect();+ const clamp01 = (n: number) => Math.min(1, Math.max(0, n));+ const round = (n: number) => Math.round(n * 1000) / 1000;+ return {+ x: round(clamp01((e.clientX - r.left) / (r.width || 1))),+ // Bottom-up, because that is the space Sprite.pivot is in.+ y: round(clamp01(1 - (e.clientY - r.top) / (r.height || 1))),+ };+ };+// Onion skin: ghost the nearest frames behind the current one, fading with// distance. Only while paused — during playback the trail is just noise.const STAGE = 152;@@ -220,6 +239,40 @@ export function FlipbookEditor() {/>))}<span className="fb-thumb fb-pv__cur" style={thumbFor(asset.frames[curFrame], STAGE)} title={t('fb.preview')} />+ {anchors && (() => {+ const box = thumbFor(asset.frames[curFrame], STAGE);+ return (+ <span+ className="fb-pv__anchor"+ style={{ width: box.width, height: box.height }}+ title={t('fb.anchor.dragTip')}+ onPointerDown={(e) => {+ e.preventDefault();+ // Capture keeps the drag alive past the box edge; a pointer the+ // browser no longer considers active throws instead, and losing+ // capture must not lose the drag.+ try { e.currentTarget.setPointerCapture(e.pointerId); } catch { /* drag without capture */ }+ setPlaying(false);+ setAnchorDrag(pivotFromPointer(e));+ }}+ onPointerMove={(e) => { if (anchorDrag) setAnchorDrag(pivotFromPointer(e)); }}+ onPointerUp={(e) => {+ if (!anchorDrag) return;+ const p = pivotFromPointer(e);+ setAnchorDrag(null);+ AnimClipCommands.setFramePivot(curFrame, p);+ }}+ // A cancelled pointer (released off-window, touch interrupted) must+ // drop the preview rather than leave the crosshair parked mid-drag.+ onPointerCancel={() => setAnchorDrag(null)}+ >+ <span+ className="fb-pv__anchor-dot"+ style={{ left: `${curPivot.x * 100}%`, bottom: `${curPivot.y * 100}%` }}+ />+ </span>+ );+ })()}</div><div className="fb-pv__bar"><Transport@@ -242,6 +295,33 @@ export function FlipbookEditor() {<input type="checkbox" checked={asset.loop ?? true} onChange={(e) => AnimClipCommands.setLoop(e.target.checked)} /><span>{t('fb.loop')}</span></label>+ <label className="fb-field" title={t('fb.anchor.tip')}>+ <input+ type="checkbox" checked={anchors}+ onChange={(e) => AnimClipCommands.setAnchorsEnabled(e.target.checked)}+ />+ <span>{t('fb.anchor')}</span>+ </label>+ {anchors && (+ <span className="fb-anchor" title={t('fb.anchor.frameTip')}>+ <GridField+ label={t('fb.anchor.x')} value={curPivot.x} min={-1} max={2} decimals={3}+ onCommit={(n) => AnimClipCommands.setFramePivot(curFrame, { x: n, y: curPivot.y })}+ />+ <GridField+ label={t('fb.anchor.y')} value={curPivot.y} min={-1} max={2} decimals={3}+ onCommit={(n) => AnimClipCommands.setFramePivot(curFrame, { x: curPivot.x, y: n })}+ />+ {asset.frames[curFrame]?.pivot && (+ <button+ type="button" className="fb-fx" title={t('fb.anchor.clearFrame')}+ onClick={() => AnimClipCommands.setFramePivot(curFrame, undefined)}+ >+ <X size={11} strokeWidth={2.2} />+ </button>+ )}+ </span>+ )}<label className="fb-field fb-onion" title={t('fb.onionTip')}><input type="checkbox" checked={onion} onChange={(e) => setOnion(e.target.checked)} /><span>{t('fb.onion')}</span>@@ -278,6 +358,7 @@ export function FlipbookEditor() {title={invalid ? t('fb.frame.invalidTip', { cell: f.cell ?? 0 }) : undefined}>{asset.events?.some((e) => e.frame === i) && <span className="fb-frame__evt" title={t('fb.event.onFrame')} />}+ {f.pivot && <span className="fb-frame__pin" title={t('fb.anchor.overridden')} />}<spanclassName="fb-thumb fb-frame__thumb" style={thumbFor(f)}title={t('fb.frame.scrubTip')}diff --git a/desktop/src/theme/flipbook.css b/desktop/src/theme/flipbook.cssindex 7e425f689..9c394d9d3 100644--- a/desktop/src/theme/flipbook.css+++ b/desktop/src/theme/flipbook.css@@ -103,6 +103,18 @@box-shadow: 0 0 0 1px var(--srf-2);z-index: 1;}+/* This frame anchors itself instead of inheriting the clip anchor. */+.fb-frame__pin {+ position: absolute;+ top: 2px;+ left: 2px;+ width: 6px;+ height: 6px;+ border-radius: 50%;+ background: var(--warn);+ box-shadow: 0 0 0 1px var(--srf-2);+ z-index: 1;+}/* Animation events bar: chips of {frame → name}, one per frame event. */.fb-events {@@ -210,7 +222,47 @@transform: translate(-50%, -50%);}.fb-pv__ghost { pointer-events: none; }-.fb-pv__bar { display: flex; align-items: center; gap: 8px; }++/* Frame anchor handle: a drag surface covering the current frame's box, with the+ crosshair placed in the frame's own 0–1 space — `bottom` (not `top`) because that+ is the bottom-up space Sprite.pivot lives in. Hairlines run past the box and get+ clipped by the stage, giving a full-width guide to line feet up against the+ onion-skin ghosts. */+.fb-pv__anchor {+ position: absolute;+ left: 50%;+ top: 50%;+ transform: translate(-50%, -50%);+ z-index: 2;+ cursor: crosshair;+ touch-action: none;+}+.fb-pv__anchor-dot {+ position: absolute;+ width: 9px;+ height: 9px;+ margin: 0 0 -4.5px -4.5px; /* centers the dot on (left, bottom) */+ border-radius: 50%;+ background: var(--acc-hi);+ box-shadow: 0 0 0 1.5px #fff, 0 0 4px rgb(0 0 0 / 0.55);+ pointer-events: none;+}+.fb-pv__anchor-dot::before,+.fb-pv__anchor-dot::after {+ content: '';+ position: absolute;+ background: var(--acc-hi);+ opacity: 0.5;+}+.fb-pv__anchor-dot::before { left: 4px; top: -400px; width: 1px; height: 800px; }+.fb-pv__anchor-dot::after { top: 4px; left: -400px; height: 1px; width: 800px; }++/* Wraps once the transport, fps/loop, anchor and onion controls outgrow one row. */+.fb-pv__bar { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; row-gap: 6px; }+/* Wider than the integer grid fields it borrows its styling from: an anchor reads+ 0.276, not 64. */+.fb-anchor { display: inline-flex; align-items: center; gap: 6px; }+.fb-anchor .ts-field input[type='number'] { width: 58px; }.fb-onion { display: inline-flex; align-items: center; gap: 4px; cursor: pointer; }.fb-dur {width: 40px;diff --git a/desktop/tests/flipbook-commands.test.ts b/desktop/tests/flipbook-commands.test.tsindex d40e886cb..470c39a8e 100644--- a/desktop/tests/flipbook-commands.test.ts+++ b/desktop/tests/flipbook-commands.test.ts@@ -72,4 +72,56 @@ describe('AnimClipCommands', () => {AnimClipCommands.setLoop(false);expect(asset().loop).toBe(false);});++ // — Frame anchors —++ it('setAnchorsEnabled seeds a centered clip anchor and is idempotent', () => {+ expect(asset().pivot).toBeUndefined();+ AnimClipCommands.setAnchorsEnabled(true);+ expect(asset().pivot).toEqual({ x: 0.5, y: 0.5 });++ AnimClipCommands.setAnchorsEnabled(true); // already on — no second undo step+ EditorHistory.undo();+ expect(asset().pivot).toBeUndefined();+ });++ it('setAnchorsEnabled(false) clears the clip anchor AND every frame override', () => {+ AnimClipCommands.appendFrames([0, 1]);+ AnimClipCommands.setAnchorsEnabled(true);+ AnimClipCommands.setFramePivot(1, { x: 0.25, y: 0 });+ expect(asset().frames[1].pivot).toEqual({ x: 0.25, y: 0 });++ AnimClipCommands.setAnchorsEnabled(false);+ expect(asset().pivot).toBeUndefined();+ expect(asset().frames.every((f) => f.pivot === undefined)).toBe(true);++ EditorHistory.undo(); // one step back = anchors as they were+ expect(asset().pivot).toEqual({ x: 0.5, y: 0.5 });+ expect(asset().frames[1].pivot).toEqual({ x: 0.25, y: 0 });+ });++ it('setFramePivot writes an override and clears back to the clip anchor', () => {+ AnimClipCommands.appendFrames([0]);+ AnimClipCommands.setFramePivot(0, { x: 0.4, y: 0.1 });+ expect(asset().frames[0].pivot).toEqual({ x: 0.4, y: 0.1 });+ AnimClipCommands.setFramePivot(0, undefined);+ expect(asset().frames[0].pivot).toBeUndefined();+ });++ it('rejects non-finite anchors instead of writing NaN into the clip', () => {+ AnimClipCommands.appendFrames([0]);+ AnimClipCommands.setClipPivot({ x: Number.NaN, y: 0 });+ AnimClipCommands.setFramePivot(0, { x: 0, y: Number.POSITIVE_INFINITY });+ expect(asset().pivot).toBeUndefined();+ expect(asset().frames[0].pivot).toBeUndefined();+ expect(AnimClipDocument.dirty).toBe(true); // appendFrames only+ });++ it('setClipPivot moves the clip-wide anchor without touching overrides', () => {+ AnimClipCommands.appendFrames([0, 1]);+ AnimClipCommands.setFramePivot(1, { x: 0.25, y: 0 });+ AnimClipCommands.setClipPivot({ x: 0.5, y: 0 });+ expect(asset().pivot).toEqual({ x: 0.5, y: 0 });+ expect(asset().frames[1].pivot).toEqual({ x: 0.25, y: 0 });+ });});diff --git a/docs/astro/src/content/docs/guides/animation.mdx b/docs/astro/src/content/docs/guides/animation.mdxindex 0fda56714..e84d35ab6 100644--- a/docs/astro/src/content/docs/guides/animation.mdx+++ b/docs/astro/src/content/docs/guides/animation.mdx@@ -113,6 +113,42 @@ Re-slicing the grid moves every frame consistently — frames reference gridcells, not pixel rectangles. Frames that fall outside the current grid areflagged red in the strip.+### Per-frame anchors++An anchor is the point a sprite sits, rotates and scales about — `Sprite.pivot`,+normalized inside the frame, `(0,0)` bottom-left and `(0.5,0.5)` centered. When the+artwork shifts inside its cell from frame to frame, one entity-wide anchor makes the+character slide around; anchoring **per frame** pins whatever has to hold still —+feet on the ground, a hand on a weapon.++Tick **Anchor** in the Flipbook editor's preview bar and a crosshair appears over the+current frame. Drag it (or type the X / Y beside it) to anchor that frame. The+hairlines run the width of the stage, so with onion skin on you can line each frame's+feet up against its neighbours. A frame anchored on its own gets an amber dot in the+strip, and **×** clears that override so the frame falls back to the clip's anchor —+which lives in the Details inspector as **Default Anchor**.++Resolution order: the frame's own anchor, else the clip's, else centered. A clip that+authors no anchor at all leaves `Sprite.pivot` **exactly** as the entity set it, so+existing projects are untouched until you tick the box; unticking clears the clip+anchor and every frame override and returns to that hands-off behaviour.++```jsonc+// walk.esanim — the clip stands on its feet, one frame leans back+{+ "version": "1.4",+ "fps": 10,+ "pivot": { "x": 0.5, "y": 0 },+ "frames": [+ { "cell": 0 },+ { "cell": 1, "pivot": { "x": 0.47, "y": 0 } }+ ]+}+```++Anchors are the clip's business only while it plays a frame: nothing stops a+`Transform` or a tween from moving the entity as usual.+### Clips from codeThe `.esanim` document is plain data, so a clip can also be built at runtime:@@ -146,6 +182,8 @@ const registerRun = defineSystem([Res(Assets), Res(SpriteAnimation)], async (ass| `parseAnimClipData(name, data, textureHandles)` | Resolve asset data into a runtime `SpriteAnimClip` — each cell frame gets its texture handle and UV window. || `parseAnimClipAsset(json)` / `serializeAnimClip(data)` | Parse / write the `.esanim` JSON document (the pair round-trips). || `animClipCellRect(sheet, cell)` / `animClipCellUv(sheet, cell)` | Pixel rect / UV window of a grid cell — what a `Sprite` shows for that frame. |+| `animClipFramePivot(data, frame)` | The anchor a frame renders with — its own, else the clip's, else centered. `null` when the clip authors none (leave `Sprite.pivot` alone). |+| `animClipDrivesPivot(data)` | Whether the clip authors anchors at all. |### Driving clips from a state machine — no codediff --git a/docs/astro/src/content/docs/zh-cn/guides/animation.mdx b/docs/astro/src/content/docs/zh-cn/guides/animation.mdxindex a59b6fdb4..8d6253e59 100644--- a/docs/astro/src/content/docs/zh-cn/guides/animation.mdx+++ b/docs/astro/src/content/docs/zh-cn/guides/animation.mdx@@ -103,6 +103,39 @@ const listen = defineSystem([Res(SpriteAnimation)], (anim) => {重新切片时所有帧一致跟随——帧引用的是网格格子,不是像素矩形。超出当前网格的帧会在帧条中标红。+### 逐帧锚点++锚点就是精灵的落点、旋转与缩放中心——也就是 `Sprite.pivot`,在帧内归一化,+`(0,0)` 为左下角、`(0.5,0.5)` 为居中。当画面在格子里逐帧位移时,只有一个+实体级锚点会让角色跟着滑来滑去;**逐帧**设锚点则能把必须钉住的部位钉住——+脚踩在地面上、手握在武器上。++在 Flipbook 编辑器预览条勾上**锚点**,当前帧上会出现一个十字准星:拖动它+(或在旁边直接输入 X / Y)即可为该帧设锚点。准星的辅助线横贯整个预览台,+配合洋葱皮就能把每一帧的脚与相邻帧对齐。单独设过锚点的帧在帧条上带一个+琥珀色圆点,**×** 清除该覆盖、让此帧回落到剪辑锚点——剪辑锚点在检视器里+就是**默认锚点**。++解析顺序:帧自己的锚点 → 剪辑锚点 → 居中。**完全没有**声明锚点的剪辑会+原封不动地保留实体自己设的 `Sprite.pivot`,所以在你勾上这个开关之前,+老项目一律不受影响;取消勾选会清除剪辑锚点和所有逐帧覆盖,回到这种+「不插手」的行为。++```jsonc+// walk.esanim —— 整段剪辑站在脚上,其中一帧向后仰+{+ "version": "1.4",+ "fps": 10,+ "pivot": { "x": 0.5, "y": 0 },+ "frames": [+ { "cell": 0 },+ { "cell": 1, "pivot": { "x": 0.47, "y": 0 } }+ ]+}+```++锚点只在剪辑播放某一帧时归剪辑管:`Transform` 或补间照常移动实体,互不干扰。+### 用代码创建剪辑`.esanim` 文档就是普通数据,所以剪辑也可以在运行时构建:`createAnimClip` 建一个@@ -135,6 +168,8 @@ const registerRun = defineSystem([Res(Assets), Res(SpriteAnimation)], async (ass| `parseAnimClipData(name, data, textureHandles)` | 把资产数据解析成运行时 `SpriteAnimClip`——每个格子帧得到纹理句柄与 UV 窗口。 || `parseAnimClipAsset(json)` / `serializeAnimClip(data)` | 解析 / 写出 `.esanim` JSON 文档(两者可往返)。 || `animClipCellRect(sheet, cell)` / `animClipCellUv(sheet, cell)` | 网格格子的像素矩形 / UV 窗口——即该帧 `Sprite` 显示的内容。 |+| `animClipFramePivot(data, frame)` | 该帧实际渲染用的锚点——帧自己的 → 剪辑的 → 居中。剪辑没有声明锚点时返回 `null`(表示不要动 `Sprite.pivot`)。 |+| `animClipDrivesPivot(data)` | 该剪辑是否声明了锚点。 |### 用状态机驱动剪辑——零代码diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.mdindex fbb93aa3c..6b038c1ca 100644--- a/sdk/etc/index.api.md+++ b/sdk/etc/index.api.md@@ -1,7 +1,7 @@# API surface — esengine/index<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 1372 stable · 17 beta · 1 deprecated+Symbols: 1376 stable · 17 beta · 1 deprecated## ABI_LAYOUT_HASH — const```@@ -15,7 +15,7 @@ readonly AnchorAxis[]## ANIM_CLIP_FORMAT_VERSION — const```-"1.3"+"1.4"```## ASSET_GROUP_MODES — const@@ -244,6 +244,7 @@ events: AnimClipEventData[] | undefinedfps: number | undefinedframes: AnimClipFrameData[]loop: boolean | undefined+pivot: AnimClipPivotData | undefinedsheet: AnimClipSheetData | undefinedtype: "animation-clip"version: string@@ -261,9 +262,16 @@ name: stringatlasFrame: { x: number; y: number; width: number; height: number; pageWidth: number; pageHeight: number; } | undefinedcell: number | undefinedduration: number | undefined+pivot: AnimClipPivotData | undefinedtexture: string | undefined```+## AnimClipPivotData — interface+```+x: number+y: number+```+## AnimClipSheetData — interface```cellHeight: number@@ -1902,6 +1910,11 @@ None = 0ThemeTokens```+## DEFAULT_ANIM_CLIP_PIVOT — const+```+AnimClipPivotData+```+## DEFAULT_DESIGN_HEIGHT — const```number@@ -6287,6 +6300,7 @@ name: string## SpriteAnimFrame — interface```duration: number | undefined+pivot: { x: number; y: number; } | undefinedtexture: numberuvOffset: { x: number; y: number; } | undefineduvScale: { x: number; y: number; } | undefined@@ -8272,6 +8286,16 @@ AiRegistry<AiContext>(sheet: AnimClipSheetData, cell: number): { uvOffset: { x: number; y: number; }; uvScale: { x: number; y: number; }; }```+## animClipDrivesPivot — function+```+(data: AnimClipAssetData): boolean+```++## animClipFramePivot — function+```+(data: AnimClipAssetData, frame: AnimClipFrameData): AnimClipPivotData | null+```+## animClipSheetCols — function```(sheet: AnimClipSheetData): numberdiff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.mdindex a03ef42e2..f7530e289 100644--- a/sdk/etc/index.native.api.md+++ b/sdk/etc/index.native.api.md@@ -1,7 +1,7 @@# API surface — esengine/index.native<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 1391 stable · 22 beta · 1 deprecated+Symbols: 1395 stable · 22 beta · 1 deprecated## ABI_LAYOUT_HASH — const```@@ -15,7 +15,7 @@ readonly AnchorAxis[]## ANIM_CLIP_FORMAT_VERSION — const```-"1.3"+"1.4"```## ASSET_GROUP_MODES — const@@ -244,6 +244,7 @@ events: AnimClipEventData[] | undefinedfps: number | undefinedframes: AnimClipFrameData[]loop: boolean | undefined+pivot: AnimClipPivotData | undefinedsheet: AnimClipSheetData | undefinedtype: "animation-clip"version: string@@ -261,9 +262,16 @@ name: stringatlasFrame: { x: number; y: number; width: number; height: number; pageWidth: number; pageHeight: number; } | undefinedcell: number | undefinedduration: number | undefined+pivot: AnimClipPivotData | undefinedtexture: string | undefined```+## AnimClipPivotData — interface+```+x: number+y: number+```+## AnimClipSheetData — interface```cellHeight: number@@ -1910,6 +1918,11 @@ None = 0ThemeTokens```+## DEFAULT_ANIM_CLIP_PIVOT — const+```+AnimClipPivotData+```+## DEFAULT_DESIGN_HEIGHT — const```number@@ -6451,6 +6464,7 @@ name: string## SpriteAnimFrame — interface```duration: number | undefined+pivot: { x: number; y: number; } | undefinedtexture: numberuvOffset: { x: number; y: number; } | undefineduvScale: { x: number; y: number; } | undefined@@ -8436,6 +8450,16 @@ AiRegistry<AiContext>(sheet: AnimClipSheetData, cell: number): { uvOffset: { x: number; y: number; }; uvScale: { x: number; y: number; }; }```+## animClipDrivesPivot — function+```+(data: AnimClipAssetData): boolean+```++## animClipFramePivot — function+```+(data: AnimClipAssetData, frame: AnimClipFrameData): AnimClipPivotData | null+```+## animClipSheetCols — function```(sheet: AnimClipSheetData): numberdiff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.mdindex 965f2b12a..be8852499 100644--- a/sdk/etc/index.node.api.md+++ b/sdk/etc/index.node.api.md@@ -1,7 +1,7 @@# API surface — esengine/index.node<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 1371 stable · 19 beta · 1 deprecated+Symbols: 1375 stable · 19 beta · 1 deprecated## ANCHOR_AXES — const```@@ -10,7 +10,7 @@ readonly AnchorAxis[]## ANIM_CLIP_FORMAT_VERSION — const```-"1.3"+"1.4"```## ASSET_GROUP_MODES — const@@ -239,6 +239,7 @@ events: AnimClipEventData[] | undefinedfps: number | undefinedframes: AnimClipFrameData[]loop: boolean | undefined+pivot: AnimClipPivotData | undefinedsheet: AnimClipSheetData | undefinedtype: "animation-clip"version: string@@ -256,9 +257,16 @@ name: stringatlasFrame: { x: number; y: number; width: number; height: number; pageWidth: number; pageHeight: number; } | undefinedcell: number | undefinedduration: number | undefined+pivot: AnimClipPivotData | undefinedtexture: string | undefined```+## AnimClipPivotData — interface+```+x: number+y: number+```+## AnimClipSheetData — interface```cellHeight: number@@ -1897,6 +1905,11 @@ None = 0ThemeTokens```+## DEFAULT_ANIM_CLIP_PIVOT — const+```+AnimClipPivotData+```+## DEFAULT_DESIGN_HEIGHT — const```number@@ -6282,6 +6295,7 @@ name: string## SpriteAnimFrame — interface```duration: number | undefined+pivot: { x: number; y: number; } | undefinedtexture: numberuvOffset: { x: number; y: number; } | undefineduvScale: { x: number; y: number; } | undefined@@ -8267,6 +8281,16 @@ AiRegistry<AiContext>(sheet: AnimClipSheetData, cell: number): { uvOffset: { x: number; y: number; }; uvScale: { x: number; y: number; }; }```+## animClipDrivesPivot — function+```+(data: AnimClipAssetData): boolean+```++## animClipFramePivot — function+```+(data: AnimClipAssetData, frame: AnimClipFrameData): AnimClipPivotData | null+```+## animClipSheetCols — function```(sheet: AnimClipSheetData): numberdiff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.mdindex 04cd57d45..81fca79f1 100644--- a/sdk/etc/minigame.api.md+++ b/sdk/etc/minigame.api.md@@ -1,7 +1,7 @@# API surface — esengine/minigame<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 1392 stable · 17 beta · 1 deprecated+Symbols: 1396 stable · 17 beta · 1 deprecated## ANCHOR_AXES — const```@@ -10,7 +10,7 @@ readonly AnchorAxis[]## ANIM_CLIP_FORMAT_VERSION — const```-"1.3"+"1.4"```## ASSET_GROUP_MODES — const@@ -239,6 +239,7 @@ events: AnimClipEventData[] | undefinedfps: number | undefinedframes: AnimClipFrameData[]loop: boolean | undefined+pivot: AnimClipPivotData | undefinedsheet: AnimClipSheetData | undefinedtype: "animation-clip"version: string@@ -256,9 +257,16 @@ name: stringatlasFrame: { x: number; y: number; width: number; height: number; pageWidth: number; pageHeight: number; } | undefinedcell: number | undefinedduration: number | undefined+pivot: AnimClipPivotData | undefinedtexture: string | undefined```+## AnimClipPivotData — interface+```+x: number+y: number+```+## AnimClipSheetData — interface```cellHeight: number@@ -1897,6 +1905,11 @@ None = 0ThemeTokens```+## DEFAULT_ANIM_CLIP_PIVOT — const+```+AnimClipPivotData+```+## DEFAULT_DESIGN_HEIGHT — const```number@@ -6497,6 +6510,7 @@ name: string## SpriteAnimFrame — interface```duration: number | undefined+pivot: { x: number; y: number; } | undefinedtexture: numberuvOffset: { x: number; y: number; } | undefineduvScale: { x: number; y: number; } | undefined@@ -8482,6 +8496,16 @@ AiRegistry<AiContext>(sheet: AnimClipSheetData, cell: number): { uvOffset: { x: number; y: number; }; uvScale: { x: number; y: number; }; }```+## animClipDrivesPivot — function+```+(data: AnimClipAssetData): boolean+```++## animClipFramePivot — function+```+(data: AnimClipAssetData, frame: AnimClipFrameData): AnimClipPivotData | null+```+## animClipSheetCols — function```(sheet: AnimClipSheetData): numberdiff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.mdindex 52e1ced45..ae9d077da 100644--- a/sdk/etc/wechat.api.md+++ b/sdk/etc/wechat.api.md@@ -1,7 +1,7 @@# API surface — esengine/wechat<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 1382 stable · 17 beta · 1 deprecated+Symbols: 1386 stable · 17 beta · 1 deprecated## ANCHOR_AXES — const```@@ -10,7 +10,7 @@ readonly AnchorAxis[]## ANIM_CLIP_FORMAT_VERSION — const```-"1.3"+"1.4"```## ASSET_GROUP_MODES — const@@ -239,6 +239,7 @@ events: AnimClipEventData[] | undefinedfps: number | undefinedframes: AnimClipFrameData[]loop: boolean | undefined+pivot: AnimClipPivotData | undefinedsheet: AnimClipSheetData | undefinedtype: "animation-clip"version: string@@ -256,9 +257,16 @@ name: stringatlasFrame: { x: number; y: number; width: number; height: number; pageWidth: number; pageHeight: number; } | undefinedcell: number | undefinedduration: number | undefined+pivot: AnimClipPivotData | undefinedtexture: string | undefined```+## AnimClipPivotData — interface+```+x: number+y: number+```+## AnimClipSheetData — interface```cellHeight: number@@ -1897,6 +1905,11 @@ None = 0ThemeTokens```+## DEFAULT_ANIM_CLIP_PIVOT — const+```+AnimClipPivotData+```+## DEFAULT_DESIGN_HEIGHT — const```number@@ -6289,6 +6302,7 @@ name: string## SpriteAnimFrame — interface```duration: number | undefined+pivot: { x: number; y: number; } | undefinedtexture: numberuvOffset: { x: number; y: number; } | undefineduvScale: { x: number; y: number; } | undefined@@ -8291,6 +8305,16 @@ AiRegistry<AiContext>(sheet: AnimClipSheetData, cell: number): { uvOffset: { x: number; y: number; }; uvScale: { x: number; y: number; }; }```+## animClipDrivesPivot — function+```+(data: AnimClipAssetData): boolean+```++## animClipFramePivot — function+```+(data: AnimClipAssetData, frame: AnimClipFrameData): AnimClipPivotData | null+```+## animClipSheetCols — function```(sheet: AnimClipSheetData): numberdiff --git a/sdk/src/animation/AnimClipLoader.ts b/sdk/src/animation/AnimClipLoader.tsindex 076929026..7adc491c7 100644--- a/sdk/src/animation/AnimClipLoader.ts+++ b/sdk/src/animation/AnimClipLoader.ts@@ -2,7 +2,8 @@// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team/*** @file AnimClipLoader.ts- * @brief .esanim asset format: parsing, serialization, and sheet-grid math+ * @brief .esanim asset format: parsing, serialization, sheet-grid math, and+ * per-frame anchor resolution*/import type { SpriteAnimClip, SpriteAnimFrame } from './SpriteAnimator';@@ -12,7 +13,22 @@ import { log } from '../util/logger';// .esanim File Format// =============================================================================-export const ANIM_CLIP_FORMAT_VERSION = '1.3';+export const ANIM_CLIP_FORMAT_VERSION = '1.4';++/**+ * A frame's anchor, normalized inside the frame's own rect — EXACTLY the space+ * `Sprite.pivot` uses: (0,0) = bottom-left, (0.5,0.5) = center, (1,1) = top-right.+ * The same numbers travel from the file to the component with no conversion, so+ * "feet on the ground" is `{ x: 0.5, y: 0 }` in both places. Values outside 0–1+ * are allowed (they anchor outside the frame), matching `Sprite.pivot`.+ */+export interface AnimClipPivotData {+ x: number;+ y: number;+}++/** The anchor a clip that authors pivots falls back to — the `Sprite.pivot` default. */+export const DEFAULT_ANIM_CLIP_PIVOT: AnimClipPivotData = { x: 0.5, y: 0.5 };/*** Sprite-sheet slicing grid. When present, frames may reference grid cells@@ -36,6 +52,12 @@ export interface AnimClipFrameData {/** Sheet cell index (row-major, 0-based); requires a `sheet` section. */cell?: number;duration?: number;+ /**+ * Anchor override for this frame; absent = the clip's `pivot`. Added in format+ * 1.4 — this is what keeps a character's feet planted when the artwork shifts+ * inside the cell from frame to frame.+ */+ pivot?: AnimClipPivotData;atlasFrame?: {x: number;y: number;@@ -62,6 +84,13 @@ export interface AnimClipAssetData {type: 'animation-clip';fps?: number;loop?: boolean;+ /**+ * Clip-wide anchor every frame inherits (frames override it per frame) — the+ * same fallback relationship `fps` has with per-frame `duration`. Absent means+ * the clip does not author anchors at all and playback leaves `Sprite.pivot`+ * exactly as the entity authored it.+ */+ pivot?: AnimClipPivotData;sheet?: AnimClipSheetData;frames: AnimClipFrameData[];events?: AnimClipEventData[];@@ -119,6 +148,38 @@ export function animClipCellUv(};}+// =============================================================================+// Frame anchors+// =============================================================================++/**+ * Does this clip author anchors at all? True as soon as the clip OR any single+ * frame declares one. All-or-nothing on purpose: a clip that anchored only some+ * frames would leave the last override standing on the plain ones — the same+ * staleness the UV window has to reset away.+ */+export function animClipDrivesPivot(data: AnimClipAssetData): boolean {+ return data.pivot !== undefined || data.frames.some(f => f.pivot !== undefined);+}++/**+ * The anchor a frame actually renders with: its own override, else the clip+ * default, else centered — or `null` when the clip authors no anchors, which is+ * the signal to leave `Sprite.pivot` exactly as the entity set it.+ *+ * The one place this resolution lives: the runtime bake, the edit-mode viewport+ * projection, and the editor's drag handle all read it here.+ */+export function animClipFramePivot(+ data: AnimClipAssetData,+ frame: AnimClipFrameData,+): AnimClipPivotData | null {+ if (frame.pivot) return { x: frame.pivot.x, y: frame.pivot.y };+ if (!animClipDrivesPivot(data)) return null;+ const p = data.pivot ?? DEFAULT_ANIM_CLIP_PIVOT;+ return { x: p.x, y: p.y };+}+// =============================================================================// Parsing / serialization// =============================================================================@@ -133,6 +194,15 @@ function nonNeg(v: unknown, fallback: number): number {return typeof v === 'number' && Number.isFinite(v) && v >= 0 ? v : fallback;}+/** A `{x,y}` anchor, or undefined when the field is missing or not a finite pair.+ * Deliberately unclamped: an anchor outside 0–1 is legal on `Sprite.pivot` too. */+function pivotOf(v: unknown): AnimClipPivotData | undefined {+ const p = v as { x?: unknown; y?: unknown } | null | undefined;+ if (!p || typeof p.x !== 'number' || typeof p.y !== 'number') return undefined;+ if (!Number.isFinite(p.x) || !Number.isFinite(p.y)) return undefined;+ return { x: p.x, y: p.y };+}+/** Parse arbitrary JSON into a normalized {@link AnimClipAssetData} (tolerant of missing fields). */export function parseAnimClipAsset(rawJson: unknown): AnimClipAssetData {const raw = rawJson as Record<string, any> | null | undefined;@@ -153,11 +223,17 @@ export function parseAnimClipAsset(rawJson: unknown): AnimClipAssetData {for (const f of Array.isArray(raw?.frames) ? raw.frames : []) {if (!f) continue;const duration = typeof f.duration === 'number' && f.duration > 0 ? f.duration : undefined;+ const framePivot = pivotOf(f.pivot);if (sheet && typeof f.cell === 'number' && Number.isInteger(f.cell) && f.cell >= 0) {- frames.push({ cell: f.cell, ...(duration !== undefined ? { duration } : {}) });+ frames.push({+ cell: f.cell,+ ...(duration !== undefined ? { duration } : {}),+ ...(framePivot ? { pivot: framePivot } : {}),+ });} else if (typeof f.texture === 'string' && f.texture) {const frame: AnimClipFrameData = { texture: f.texture };if (duration !== undefined) frame.duration = duration;+ if (framePivot) frame.pivot = framePivot;const af = f.atlasFrame;if (af && [af.x, af.y, af.width, af.height, af.pageWidth, af.pageHeight].every((n: unknown) => typeof n === 'number' && Number.isFinite(n))) {@@ -176,26 +252,34 @@ export function parseAnimClipAsset(rawJson: unknown): AnimClipAssetData {events.push({ frame: e.frame, name: e.name, ...(e.data !== undefined ? { data: e.data } : {}) });}}+ const clipPivot = pivotOf(raw?.pivot);return {version: typeof raw?.version === 'string' ? raw.version : ANIM_CLIP_FORMAT_VERSION,type: 'animation-clip',fps: posInt(raw?.fps, DEFAULT_FPS),loop: typeof raw?.loop === 'boolean' ? raw.loop : true,+ ...(clipPivot ? { pivot: clipPivot } : {}),...(sheet ? { sheet } : {}),frames,...(events.length ? { events } : {}),};}-/** Serialize an {@link AnimClipAssetData} to a plain JSON-ready object (drops empty/undefined). */+/**+ * Serialize an {@link AnimClipAssetData} to a plain JSON-ready object (drops+ * empty/undefined). Stamps the CURRENT format version: whatever the file said when+ * it was read, this writer produced what is on disk now — a clip that gained 1.4+ * anchors must not keep claiming 1.3.+ */export function serializeAnimClip(asset: AnimClipAssetData): Record<string, unknown> {return {- version: asset.version || ANIM_CLIP_FORMAT_VERSION,+ version: ANIM_CLIP_FORMAT_VERSION,type: 'animation-clip',fps: asset.fps ?? DEFAULT_FPS,loop: asset.loop ?? true,+ ...(asset.pivot ? { pivot: { ...asset.pivot } } : {}),...(asset.sheet ? { sheet: { ...asset.sheet } } : {}),- frames: asset.frames.map(f => ({ ...f })),+ frames: asset.frames.map(f => ({ ...f, ...(f.pivot ? { pivot: { ...f.pivot } } : {}) })),...(asset.events && asset.events.length ? { events: asset.events.map(e => ({ ...e })) } : {}),};}@@ -265,6 +349,9 @@ export function parseAnimClipData(loop: data.loop ?? true,...(data.events?.length ? { events: data.events.map(e => ({ frame: e.frame, name: e.name, data: e.data })) } : {}),frames: data.frames.map(f => {+ // Resolved once at load: at runtime a frame either carries the anchor it+ // renders with, or the clip authors none and playback leaves pivot alone.+ const pivot = animClipFramePivot(data, f);if (sheet && f.cell !== undefined) {if (f.cell >= cellCount) {log.warn('asset', `${clipPath}: frame cell ${f.cell} outside the ${cellCount}-cell sheet grid; clamped`);@@ -272,6 +359,7 @@ export function parseAnimClipData(const frame: SpriteAnimFrame = {texture: textureHandles.get(sheet.texture) ?? 0,duration: f.duration,+ ...(pivot ? { pivot } : {}),...animClipCellUv(sheet, f.cell),};return frame;@@ -279,6 +367,7 @@ export function parseAnimClipData(const frame: SpriteAnimFrame = {texture: textureHandles.get(f.texture ?? '') ?? 0,duration: f.duration,+ ...(pivot ? { pivot } : {}),};if (f.atlasFrame) {const af = f.atlasFrame;diff --git a/sdk/src/animation/SpriteAnimator.ts b/sdk/src/animation/SpriteAnimator.tsindex 6c8879d6b..e67b5eee5 100644--- a/sdk/src/animation/SpriteAnimator.ts+++ b/sdk/src/animation/SpriteAnimator.ts@@ -20,6 +20,13 @@ export interface SpriteAnimFrame {duration?: number;uvOffset?: { x: number; y: number };uvScale?: { x: number; y: number };+ /**+ * The anchor this frame renders with, in `Sprite.pivot`'s own space — resolved+ * at load time from the clip's per-frame/clip-wide anchors. Absent on EVERY+ * frame of a clip that authors no anchors, which is what keeps playback from+ * touching a pivot the entity owns.+ */+ pivot?: { x: number; y: number };}export interface SpriteAnimEvent {@@ -219,6 +226,12 @@ export class SpriteAnimationAPI {sprite.uvOffset = { x: 0, y: 0 };sprite.uvScale = { x: 1, y: 1 };}+ // No reset branch: the loader gives EVERY frame of an anchor-authoring+ // clip a pivot, so absent here means the clip authors none at all and+ // the entity's own pivot stands.+ if (frame.pivot) {+ sprite.pivot = { x: frame.pivot.x, y: frame.pivot.y };+ }world.insert(entity, Sprite, sprite);}diff --git a/sdk/src/animation/index.ts b/sdk/src/animation/index.tsindex f6cb4aa66..0e1ce9f1b 100644--- a/sdk/src/animation/index.ts+++ b/sdk/src/animation/index.ts@@ -115,9 +115,13 @@ export {animClipSheetRows,animClipCellRect,animClipCellUv,+ animClipDrivesPivot,+ animClipFramePivot,ANIM_CLIP_FORMAT_VERSION,+ DEFAULT_ANIM_CLIP_PIVOT,type AnimClipAssetData,type AnimClipFrameData,type AnimClipSheetData,type AnimClipEventData,+ type AnimClipPivotData,} from './AnimClipLoader';diff --git a/sdk/src/core-content.ts b/sdk/src/core-content.tsindex 3e2e09d99..29fd48fae 100644--- a/sdk/src/core-content.ts+++ b/sdk/src/core-content.ts@@ -340,11 +340,15 @@ export {animClipSheetRows,animClipCellRect,animClipCellUv,+ animClipDrivesPivot,+ animClipFramePivot,ANIM_CLIP_FORMAT_VERSION,+ DEFAULT_ANIM_CLIP_PIVOT,type AnimClipAssetData,type AnimClipFrameData,type AnimClipSheetData,type AnimClipEventData,+ type AnimClipPivotData,TweenGroup,TweenSequence,type Completable,diff --git a/sdk/tests/anim-clip-asset.test.ts b/sdk/tests/anim-clip-asset.test.tsindex 7ad196d20..fa6e47dfd 100644--- a/sdk/tests/anim-clip-asset.test.ts+++ b/sdk/tests/anim-clip-asset.test.ts@@ -15,6 +15,10 @@ import {animClipSheetCols,animClipSheetRows,animClipCellRect,+ animClipDrivesPivot,+ animClipFramePivot,+ ANIM_CLIP_FORMAT_VERSION,+ DEFAULT_ANIM_CLIP_PIVOT,type AnimClipAssetData,type AnimClipSheetData,} from '../src/animation/AnimClipLoader';@@ -251,6 +255,103 @@ describe('parseAnimClipData with sheet cells', () => {});});+// =============================================================================+// Frame anchors (format 1.4)+// =============================================================================++describe('frame anchor resolution', () => {+ const base: AnimClipAssetData = {+ version: ANIM_CLIP_FORMAT_VERSION,+ type: 'animation-clip',+ fps: 10,+ loop: true,+ sheet: SHEET,+ frames: [{ cell: 0 }, { cell: 1 }],+ };++ it('reports a clip with no anchors anywhere as not driving pivot', () => {+ expect(animClipDrivesPivot(base)).toBe(false);+ expect(animClipFramePivot(base, base.frames[0])).toBeNull();+ });++ it('drives pivot from a clip-wide anchor, inherited by every frame', () => {+ const data = { ...base, pivot: { x: 0.5, y: 0 } };+ expect(animClipDrivesPivot(data)).toBe(true);+ expect(animClipFramePivot(data, data.frames[0])).toEqual({ x: 0.5, y: 0 });+ expect(animClipFramePivot(data, data.frames[1])).toEqual({ x: 0.5, y: 0 });+ });++ it('prefers a frame override over the clip-wide anchor', () => {+ const data = {+ ...base,+ pivot: { x: 0.5, y: 0 },+ frames: [{ cell: 0 }, { cell: 1, pivot: { x: 0.3, y: 0.2 } }],+ };+ expect(animClipFramePivot(data, data.frames[0])).toEqual({ x: 0.5, y: 0 });+ expect(animClipFramePivot(data, data.frames[1])).toEqual({ x: 0.3, y: 0.2 });+ });++ it('centers the frames a partially-anchored clip left unset (no stale override)', () => {+ // One frame anchored, no clip default: the plain frames must resolve to the+ // Sprite default rather than keeping the anchored frame's value.+ const data = { ...base, frames: [{ cell: 0 }, { cell: 1, pivot: { x: 0.3, y: 0.2 } }] };+ expect(animClipDrivesPivot(data)).toBe(true);+ expect(animClipFramePivot(data, data.frames[0])).toEqual(DEFAULT_ANIM_CLIP_PIVOT);+ });++ it('never hands back the authored anchor object', () => {+ const data = { ...base, pivot: { x: 0.5, y: 0 } };+ const resolved = animClipFramePivot(data, data.frames[0])!;+ resolved.x = 0.9;+ expect(data.pivot.x).toBe(0.5);+ });+});++describe('parseAnimClipData anchor bake', () => {+ const handles = new Map([['@uuid:sheet', 7]]);++ it('bakes a resolved anchor onto every frame of an anchoring clip', () => {+ const clip = parseAnimClipData('run.esanim', {+ version: ANIM_CLIP_FORMAT_VERSION,+ type: 'animation-clip',+ fps: 10,+ loop: true,+ pivot: { x: 0.5, y: 0 },+ sheet: SHEET,+ frames: [{ cell: 0 }, { cell: 1, pivot: { x: 0.4, y: 0.1 } }],+ }, handles);++ expect(clip.frames[0].pivot).toEqual({ x: 0.5, y: 0 });+ expect(clip.frames[1].pivot).toEqual({ x: 0.4, y: 0.1 });+ });++ it('bakes anchors on per-texture frames as well', () => {+ const clip = parseAnimClipData('mix.esanim', {+ version: ANIM_CLIP_FORMAT_VERSION,+ type: 'animation-clip',+ fps: 10,+ loop: true,+ frames: [{ texture: 'a.png', pivot: { x: 0.5, y: 0 } }],+ }, new Map([['a.png', 3]]));++ expect(clip.frames[0].texture).toBe(3);+ expect(clip.frames[0].pivot).toEqual({ x: 0.5, y: 0 });+ });++ it('leaves every frame anchor-free when the clip authors none', () => {+ const clip = parseAnimClipData('run.esanim', {+ version: ANIM_CLIP_FORMAT_VERSION,+ type: 'animation-clip',+ fps: 10,+ loop: true,+ sheet: SHEET,+ frames: [{ cell: 0 }, { cell: 1 }],+ }, handles);++ expect(clip.frames.every(f => f.pivot === undefined)).toBe(true);+ });+});+describe('parseAnimClipAsset (tolerant parse)', () => {it('normalizes a well-formed sheet clip round-trip through serializeAnimClip', () => {const clip = createAnimClip('@uuid:sheet', 32, 48, 134, 100);@@ -275,6 +376,45 @@ describe('parseAnimClipAsset (tolerant parse)', () => {expect(parsed.frames[0].atlasFrame).toEqual(af);});+ it('round-trips clip-wide and per-frame anchors', () => {+ const clip = createAnimClip('@uuid:sheet', 32, 48, 134, 100);+ clip.pivot = { x: 0.5, y: 0 };+ clip.frames.push({ cell: 0 }, { cell: 1, pivot: { x: 0.4, y: 0.05 } });+ const parsed = parseAnimClipAsset(JSON.parse(JSON.stringify(serializeAnimClip(clip))));+ expect(parsed).toEqual(clip);+ });++ it('keeps anchors on per-texture frames too', () => {+ const parsed = parseAnimClipAsset({+ frames: [{ texture: 'a.png', pivot: { x: 0.5, y: 0 } }],+ });+ expect(parsed.frames[0].pivot).toEqual({ x: 0.5, y: 0 });+ });++ it('drops malformed anchors instead of half-applying them', () => {+ const parsed = parseAnimClipAsset({+ pivot: { x: 0.5 },+ frames: [+ { texture: 'a.png', pivot: { x: 'low', y: 0 } },+ { texture: 'b.png', pivot: { x: NaN, y: 0 } },+ { texture: 'c.png', pivot: null },+ ],+ });+ expect(parsed.pivot).toBeUndefined();+ expect(parsed.frames.every(f => f.pivot === undefined)).toBe(true);+ });++ it('keeps anchors outside 0–1 (Sprite.pivot allows them)', () => {+ const parsed = parseAnimClipAsset({ pivot: { x: -0.25, y: 1.5 }, frames: [] });+ expect(parsed.pivot).toEqual({ x: -0.25, y: 1.5 });+ });++ it('stamps the current format version on save', () => {+ const parsed = parseAnimClipAsset({ version: '1.2', frames: [{ texture: 'a.png' }] });+ expect(parsed.version).toBe('1.2'); // read back as authored+ expect(serializeAnimClip(parsed).version).toBe(ANIM_CLIP_FORMAT_VERSION);+ });+it('defaults fps/loop and fills sheet defaults', () => {const parsed = parseAnimClipAsset({ sheet: { texture: 't.png' }, frames: [] });expect(parsed.fps).toBe(12);diff --git a/sdk/tests/sprite-animator.test.ts b/sdk/tests/sprite-animator.test.tsindex 214eae643..39ceec0db 100644--- a/sdk/tests/sprite-animator.test.ts+++ b/sdk/tests/sprite-animator.test.ts@@ -11,6 +11,7 @@ import {type SpriteAnimatorData,type SpriteAnimClip,} from '../src/animation/SpriteAnimator';+import { parseAnimClipAsset, parseAnimClipData } from '../src/animation/AnimClipLoader';function createAnimTestWorld(): { world: World; registry: CppRegistry } {const spriteStore = new Map<Entity, Record<string, unknown>>();@@ -316,4 +317,93 @@ describe('SpriteAnimator', () => {expect(s2.texture).toBe(20); // advanced});});++ // =========================================================================+ // Per-frame anchors+ // =========================================================================++ describe('per-frame anchors', () => {+ it('applies the frame anchor to Sprite.pivot as frames advance', () => {+ anim.registerClip({+ name: 'anchored', fps: 10, loop: true,+ frames: [+ { texture: 1, pivot: { x: 0.5, y: 0 } },+ { texture: 2, pivot: { x: 0.25, y: 0.1 } },+ ],+ });+ const entity = world.spawn();+ world.insert(entity, Sprite, { texture: 0 });+ world.insert(entity, SpriteAnimator, { clip: 'anchored' });++ anim.update(world, 0.001);+ expect((world.get(entity, Sprite) as SpriteData).pivot).toEqual({ x: 0.5, y: 0 });++ anim.update(world, 0.1);+ expect((world.get(entity, Sprite) as SpriteData).pivot).toEqual({ x: 0.25, y: 0.1 });+ });++ it('leaves the entity pivot alone for a clip that authors no anchors', () => {+ anim.registerClip({+ name: 'plain', fps: 10, loop: true,+ frames: [{ texture: 10 }, { texture: 20 }],+ });+ const entity = world.spawn();+ world.insert(entity, Sprite, { texture: 0, pivot: { x: 0.5, y: 0 } });+ world.insert(entity, SpriteAnimator, { clip: 'plain' });++ anim.update(world, 0.001);+ anim.update(world, 0.1);++ // No frame carries a pivot: the entity's own anchor stands.+ expect((world.get(entity, Sprite) as SpriteData).pivot).toEqual({ x: 0.5, y: 0 });+ });++ it('copies the anchor instead of aliasing the clip frame', () => {+ const frame = { texture: 1, pivot: { x: 0.5, y: 0 } };+ anim.registerClip({ name: 'shared', fps: 10, loop: true, frames: [frame] });+ const entity = world.spawn();+ world.insert(entity, Sprite, { texture: 0 });+ world.insert(entity, SpriteAnimator, { clip: 'shared' });++ anim.update(world, 0.001);+ const sprite = world.get(entity, Sprite) as SpriteData;+ sprite.pivot.x = 0.9;++ expect(frame.pivot.x).toBe(0.5);+ });++ it('carries an anchor from .esanim TEXT all the way onto the Sprite', () => {+ // The whole production path in one go: file text → tolerant parse → runtime+ // bake → animator apply, which is what a shipped clip actually travels.+ const text = JSON.stringify({+ version: '1.4',+ type: 'animation-clip',+ fps: 10,+ loop: true,+ pivot: { x: 0.5, y: 0 },+ frames: [+ { texture: 'walk_0.png' },+ { texture: 'walk_1.png', pivot: { x: 0.25, y: 0.75 } },+ ],+ });+ const data = parseAnimClipAsset(JSON.parse(text));+ anim.registerClip(parseAnimClipData('walk.esanim', data, new Map([+ ['walk_0.png', 11], ['walk_1.png', 22],+ ])));++ const entity = world.spawn();+ world.insert(entity, Sprite, { texture: 0, pivot: { x: 0.5, y: 0.5 } });+ world.insert(entity, SpriteAnimator, { clip: 'walk.esanim' });++ anim.update(world, 0.001);+ let sprite = world.get(entity, Sprite) as SpriteData;+ expect(sprite.texture).toBe(11);+ expect(sprite.pivot).toEqual({ x: 0.5, y: 0 }); // clip-wide anchor++ anim.update(world, 0.1);+ sprite = world.get(entity, Sprite) as SpriteData;+ expect(sprite.texture).toBe(22);+ expect(sprite.pivot).toEqual({ x: 0.25, y: 0.75 }); // frame override+ });+ });});