Skip to content

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.

feat(editor): UE Sequencer animation editor + modern timeline foundation (P1–P3)

esengine27cb136e205b
diff --git a/desktop/src/App.tsx b/desktop/src/App.tsx
index 92487e05c..e6ba7d8e1 100644
--- a/desktop/src/App.tsx
+++ b/desktop/src/App.tsx
@@ -14,6 +14,8 @@ import { useEditorStore } from '@/store/editorStore';
import { commands } from '@/commands';
import { PlayRealm } from '@/engine/PlayRealm';
import { PlayInspect } from '@/engine/PlayInspect';
+import { TimelinePreview } from '@/engine/TimelinePreview';
+import { TimelineRecorder } from '@/timeline/TimelineRecorder';
import { ProjectStore } from '@/project/ProjectStore';
import { dockApi } from '@/layout/dockApi';
import { Toasts } from '@/store/Toasts';
@@ -46,6 +48,13 @@ export function App() {
return () => window.removeEventListener('keydown', onKey);
}, []);
+ // Wire the Sequencer's edit-mode live preview (timeline document → World) and
+ // record-mode auto-key once.
+ useEffect(() => {
+ TimelinePreview.attach();
+ TimelineRecorder.attach();
+ }, []);
+
// Play runs in an ISOLATED realm (the Game panel's iframe = the shipping
// runtime), NOT by flipping the main edit World — so gameplay can never dirty
// the scene and the Viewport stays a live Scene view (REARCH_EDITOR_REALM R2).
diff --git a/desktop/src/components/icons.tsx b/desktop/src/components/icons.tsx
index d00f42d93..5a31c9711 100644
--- a/desktop/src/components/icons.tsx
+++ b/desktop/src/components/icons.tsx
@@ -10,6 +10,7 @@ import {
CircleDot,
Folder,
Film,
+ Clapperboard,
FileImage,
Music,
Component,
@@ -56,6 +57,7 @@ const ASSET_ICON: Record<AssetType, { icon: LucideIcon; tint: string }> = {
prefab: { icon: Component, tint: '#c2a274' },
material: { icon: Blend, tint: '#c0917a' },
script: { icon: FileCode2, tint: '#93a3bf' },
+ animation: { icon: Clapperboard, tint: '#9bb39a' },
file: { icon: File, tint: 'var(--text-dim)' },
};
diff --git a/desktop/src/engine/SceneCommands.ts b/desktop/src/engine/SceneCommands.ts
index e56de1e10..d6a557d21 100644
--- a/desktop/src/engine/SceneCommands.ts
+++ b/desktop/src/engine/SceneCommands.ts
@@ -85,6 +85,15 @@ interface FieldEdit {
before: unknown; // model (SceneData-format) value before the gesture
}
+/** A hook on the field-edit door; returns true to suppress the scene write. */
+export type EditHook = (
+ sourceId: EntityId,
+ compName: string,
+ key: string,
+ type: InspectorFieldType,
+ value: InspectorFieldValue,
+) => boolean;
+
export class SceneCommandsImpl {
// — Field-edit gesture: coalesce a focus→blur / drag into a single undo step. —
// Undo recording is INTERNAL: the only public write door is `setField` (and
@@ -94,11 +103,23 @@ export class SceneCommandsImpl {
// value read at `endGesture`, and the pair recorded as one model-op step.
private gesture: { label: string; touched: Map<string, FieldEdit> } | null = null;
+ // Optional observer/interceptor on the field-edit door — the Sequencer's record
+ // mode registers it to auto-key edits (REARCH_ANIMATION). Returning true
+ // SUPPRESSES the scene write (reserved for future non-destructive record);
+ // the recorder returns false (observe-only) so the edit still lands normally.
+ // Kept generic: SceneCommands knows nothing about timelines.
+ private editHook: EditHook | null = null;
+
constructor(
private readonly model: SceneModelImpl,
private readonly history: EditorHistoryImpl,
) {}
+ /** Register (or clear) the field-edit hook. One slot; last writer wins. */
+ setEditHook(fn: EditHook | null): void {
+ this.editHook = fn;
+ }
+
/** The current model value of one field, or undefined. */
private modelFieldValue(sourceId: number, comp: string, key: string): unknown {
const c = this.model.entityBySource(sourceId)?.components.find((c) => c.type === comp);
@@ -156,6 +177,8 @@ export class SceneCommandsImpl {
type: InspectorFieldType,
value: InspectorFieldValue,
): void {
+ // The edit hook (Sequencer record) may observe — or, returning true, suppress.
+ if (this.editHook && this.editHook(sourceId, compName, key, type, value)) return;
const e = this.model.entityBySource(sourceId);
if (!e) return;
const cur = (e.components.find((c) => c.type === compName)?.data as Record<string, unknown>) ?? {};
diff --git a/desktop/src/engine/TimelinePreview.ts b/desktop/src/engine/TimelinePreview.ts
new file mode 100644
index 000000000..124634c3b
--- /dev/null
+++ b/desktop/src/engine/TimelinePreview.ts
@@ -0,0 +1,150 @@
+/**
+ * @file TimelinePreview.ts
+ * @brief Edit-mode live preview of the open timeline document — the document→
+ * World projection that mirrors the scene's Reconciler (model→World),
+ * for animation (docs/REARCH_ANIMATION.md L4, the P1 payoff).
+ *
+ * Subscribes to {@link TimelineDocument} (asset + preview-root binding) and the
+ * sequencer playhead, and on every change samples the timeline at the playhead and
+ * writes the result to the bound entity's subtree in the live edit World — so
+ * scrubbing/playing the Sequencer animates the viewport. ONE path drives both
+ * scrub and the edit-mode play loop (sample-at-T), with no engine round-trip.
+ *
+ * It owns base-pose capture/restore: on bind it snapshots every component the
+ * timeline touches, and on unbind (close / rebind / entering play mode) it writes
+ * the snapshot back — so the entity returns to its authored pose. Safe by
+ * construction: the scene is saved from the MODEL, never the World, so these
+ * transient World writes can never leak into the saved scene.
+ *
+ * Active only in edit mode; when global Play (PIE) starts, it restores and stands
+ * down (the isolated play realm owns playback). Bound to the engine's process-level
+ * World via EngineHost, like the Reconciler.
+ */
+
+import { getComponent, resolveChildEntity, sampleTimelineInWorld, TrackType, type TimelineAsset } from 'esengine';
+import { TimelineDocument } from '@/timeline/TimelineDocument';
+import { useSequencerStore } from '@/store/sequencerStore';
+import { useEditorStore } from '@/store/editorStore';
+import { EngineHost } from './EngineHost';
+import { SceneModel } from './SceneModel';
+
+interface Snapshot {
+ entity: number;
+ // The SDK component definition (opaque here; passed straight back to world.get/set).
+ def: any;
+ data: unknown;
+}
+
+const clone = <T>(v: T): T =>
+ typeof structuredClone === 'function' ? structuredClone(v) : (JSON.parse(JSON.stringify(v)) as T);
+
+/** The distinct (entity, component) pairs a timeline's property tracks write to. */
+function affectedTargets(world: any, root: number, asset: TimelineAsset): Snapshot[] {
+ const seen = new Set<string>();
+ const out: Snapshot[] = [];
+ for (const track of asset.tracks) {
+ if (track.type !== TrackType.Property) continue;
+ const def = getComponent(track.component);
+ if (!def) continue;
+ const entity = resolveChildEntity(world, root, track.childPath);
+ if (entity == null || !world.has(entity, def)) continue;
+ const key = `${entity}:${track.component}`;
+ if (seen.has(key)) continue;
+ seen.add(key);
+ out.push({ entity: entity as number, def, data: undefined });
+ }
+ return out;
+}
+
+export class TimelinePreviewImpl {
+ private attached = false;
+ private boundRoot: number | null = null; // runtime entity id
+ private boundAsset: TimelineAsset | null = null;
+ private snapshot: Snapshot[] = [];
+ private rafPending = false;
+
+ /** Begin reacting to the document + playhead. Idempotent. */
+ attach(): void {
+ if (this.attached) return;
+ this.attached = true;
+ TimelineDocument.subscribe(() => this.sync());
+ useEditorStore.subscribe(() => this.sync()); // play-mode toggles bind/unbind
+ useSequencerStore.subscribe(() => this.scheduleApply()); // playhead scrubs/plays
+ this.sync();
+ }
+
+ /** The runtime root the preview should be bound to right now (or null). */
+ private desiredRoot(): number | null {
+ const sourceId = TimelineDocument.rootEntity;
+ if (!TimelineDocument.isOpen || sourceId == null) return null;
+ if (useEditorStore.getState().isPlaying) return null; // PIE owns the world
+ const world = EngineHost.mutableWorld();
+ if (!world) return null;
+ const rt = SceneModel.runtimeFor(sourceId);
+ return rt != null && world.valid(rt) ? rt : null;
+ }
+
+ /** Reconcile the binding (restore old / capture new base pose), then apply. */
+ private sync(): void {
+ const want = this.desiredRoot();
+ const asset = want != null ? TimelineDocument.asset : null;
+ if (want !== this.boundRoot || asset !== this.boundAsset) {
+ this.restore();
+ this.boundRoot = want;
+ this.boundAsset = asset;
+ this.capture();
+ }
+ this.apply();
+ }
+
+ private capture(): void {
+ this.snapshot = [];
+ const world = EngineHost.mutableWorld();
+ if (!world || this.boundRoot == null || this.boundAsset == null) return;
+ for (const t of affectedTargets(world, this.boundRoot, this.boundAsset)) {
+ this.snapshot.push({ entity: t.entity, def: t.def, data: clone(world.get(t.entity, t.def)) });
+ }
+ }
+
+ /** Write the captured base pose back to the affected components (no clear). */
+ private writeBase(): void {
+ const world = EngineHost.mutableWorld();
+ if (!world) return;
+ for (const s of this.snapshot) {
+ if (world.valid(s.entity) && world.has(s.entity, s.def)) {
+ world.set(s.entity, s.def, clone(s.data));
+ }
+ }
+ }
+
+ private restore(): void {
+ this.writeBase();
+ this.snapshot = [];
+ }
+
+ private apply(): void {
+ if (this.boundRoot == null || this.boundAsset == null) return;
+ const world = EngineHost.mutableWorld();
+ if (!world) return;
+ // Reset affected components to base, then layer the animation on top — so a
+ // muted (skipped) channel reverts to its scene value instead of freezing.
+ this.writeBase();
+ const muted = useSequencerStore.getState().mutedTracks;
+ sampleTimelineInWorld(this.boundAsset, useSequencerStore.getState().time, world, this.boundRoot, {
+ skipChannel: muted.size > 0 ? (cp, comp, prop) => muted.has(`${cp}|${comp}|${prop}`) : undefined,
+ });
+ }
+
+ /** Coalesce rapid playhead changes into one apply per frame. */
+ private scheduleApply(): void {
+ if (this.rafPending) return;
+ this.rafPending = true;
+ requestAnimationFrame(() => {
+ this.rafPending = false;
+ this.apply();
+ });
+ }
+}
+
+/** The app's default-session timeline preview. */
+export const TimelinePreview = new TimelinePreviewImpl();
diff --git a/desktop/src/layout/ActivityBar.tsx b/desktop/src/layout/ActivityBar.tsx
index 27bb65a8d..6870dd679 100644
--- a/desktop/src/layout/ActivityBar.tsx
+++ b/desktop/src/layout/ActivityBar.tsx
@@ -1,6 +1,6 @@
// Far-left icon rail (activity bar). Reveals docked panels and toggles the
// Content Drawer — the summoned quick-access surface.
-import { ListTree, SlidersHorizontal, FolderOpen, Terminal, Settings } from 'lucide-react';
+import { ListTree, SlidersHorizontal, FolderOpen, Terminal, Clapperboard, Settings } from 'lucide-react';
import { useEditorStore } from '@/store/editorStore';
import { dockApi } from '@/layout/dockApi';
import { commands } from '@/commands';
@@ -43,6 +43,14 @@ export function ActivityBar() {
>
<Terminal size={19} strokeWidth={1.7} />
</button>
+ <button
+ type="button"
+ className="act"
+ title="Sequencer"
+ onClick={() => dockApi.revealAndExpand('sequencer')}
+ >
+ <Clapperboard size={19} strokeWidth={1.7} />
+ </button>
<span className="act-spacer" />
diff --git a/desktop/src/layout/DockLayout.tsx b/desktop/src/layout/DockLayout.tsx
index 170f58c2f..7d8ae59a6 100644
--- a/desktop/src/layout/DockLayout.tsx
+++ b/desktop/src/layout/DockLayout.tsx
@@ -12,6 +12,7 @@ import { Details } from '@/panels/Details';
import { ContentBrowser } from '@/panels/ContentBrowser';
import { OutputLog } from '@/panels/OutputLog';
import { GamePanel } from '@/panels/GamePanel';
+import { Sequencer } from '@/panels/Sequencer';
import { dockApi } from '@/layout/dockApi';
// Each dock panel is a thin wrapper so dockview owns mount/unmount.
@@ -21,6 +22,7 @@ const components: Record<string, FC<IDockviewPanelProps>> = {
details: () => <Details />,
content: () => <ContentBrowser />,
log: () => <OutputLog />,
+ sequencer: () => <Sequencer />,
// The "Game" view (isolated play realm) — added on Play, removed on Stop.
game: () => <GamePanel />,
};
@@ -67,6 +69,20 @@ function buildDefaultLayout(api: DockviewReadyEvent['api']) {
});
}
+// Add the Sequencer as a bottom-dock tab if it isn't present yet. Run on both the
+// fresh-build and the restored-layout paths so existing saved layouts (pre-v5
+// Sequencer) gain the tab without resetting the user's whole arrangement.
+function ensureSequencer(api: DockviewReadyEvent['api']) {
+ if (api.getPanel('sequencer')) return;
+ const ref = api.getPanel('content') ? 'content' : api.getPanel('log') ? 'log' : undefined;
+ api.addPanel({
+ id: 'sequencer',
+ component: 'sequencer',
+ title: 'Sequencer',
+ position: ref ? { referencePanel: ref, direction: 'within' } : undefined,
+ });
+}
+
// A collapse/expand chevron in every dock group's header (the design's `.pcol`).
// Collapses the group to its tab bar by height; hidden on the Viewport/Game group
// (the center stage isn't an accordion). State follows the live group height, so
@@ -110,6 +126,11 @@ export function DockLayout() {
buildDefaultLayout(api);
}
+ // Ensure the Sequencer tab exists, then keep the Content Browser fronted so
+ // adding it doesn't steal the bottom dock's active tab on load.
+ ensureSequencer(api);
+ api.getPanel('content')?.api.setActive();
+
// Persist the dock arrangement so it survives reloads — a real editor habit.
api.onDidLayoutChange(() => {
localStorage.setItem(LAYOUT_KEY, JSON.stringify(api.toJSON()));
diff --git a/desktop/src/main.tsx b/desktop/src/main.tsx
index 59f101909..6eeb39f46 100644
--- a/desktop/src/main.tsx
+++ b/desktop/src/main.tsx
@@ -19,6 +19,7 @@ import './theme/outliner.css';
import './theme/log.css';
import './theme/viewport.css';
import './theme/content.css';
+import './theme/sequencer.css';
import './theme/chrome.css';
import './theme/menus.css';
import './theme/settings.css';
diff --git a/desktop/src/panels/ContentBrowser.tsx b/desktop/src/panels/ContentBrowser.tsx
index 983e9688e..da9b9a1bd 100644
--- a/desktop/src/panels/ContentBrowser.tsx
+++ b/desktop/src/panels/ContentBrowser.tsx
@@ -8,6 +8,7 @@ import { EditorHistory } from '@/engine/EditorHistory';
import { Toasts } from '@/store/Toasts';
import { useSelection } from '@/store/selectionStore';
import { IMAGE_RE, assetTypeOf as assetType, TYPE_CODE } from '@/project/assetMeta';
+import { openAnimationClip } from '@/timeline/openClip';
import { fsRefresh } from '@/project/fsWatch';
import type { DirEntry } from '@/project/format';
import type { AssetType } from '@/types';
@@ -186,6 +187,7 @@ const CHIP_GROUPS: { label: string; types: AssetType[]; color: string }[] = [
{ label: 'Image', types: ['texture', 'sprite'], color: assetTint('texture') },
{ label: 'Prefab', types: ['prefab'], color: assetTint('prefab') },
{ label: 'Scene', types: ['scene'], color: assetTint('scene') },
+ { label: 'Animation', types: ['animation'], color: assetTint('animation') },
{ label: 'Script', types: ['script'], color: assetTint('script') },
{ label: 'Audio', types: ['audio'], color: assetTint('audio') },
{ label: 'Material', types: ['material'], color: assetTint('material') },
@@ -298,6 +300,8 @@ export function ContentBrowser() {
if (assetType(name) === 'scene') {
if (EditorHistory.canUndo() && !window.confirm(`Open ${name}? Unsaved changes will be lost.`)) return;
void ProjectStore.openScene(path);
+ } else if (assetType(name) === 'animation') {
+ void openAnimationClip(path);
}
};
diff --git a/desktop/src/panels/Sequencer.tsx b/desktop/src/panels/Sequencer.tsx
new file mode 100644
index 000000000..62fd51d7e
--- /dev/null
+++ b/desktop/src/panels/Sequencer.tsx
@@ -0,0 +1,637 @@
+/**
+ * @file Sequencer.tsx
+ * @brief The UE-Sequencer-style animation editor panel (docs/REARCH_ANIMATION.md
+ * L4) — bottom-dock tab. P1 skeleton: open a clip, render the
+ * entity→component→channel track tree + a scrubbable frame timeline.
+ *
+ * Data flow mirrors the scene panels: subscribe to the TimelineDocument revision
+ * (the asset is the source of truth) and the sequencerStore (playhead / transport
+ * UI). Keyframe editing (P2), the add-track picker + curve view (P3), and live
+ * viewport preview on scrub (the next P1 step) plug into the marked seams.
+ */
+
+import { useEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react';
+import {
+ Circle, ChevronFirst, ChevronLast, ChevronLeft, ChevronRight,
+ Play, Pause, Repeat, Magnet, Plus, ChevronDown, Eye, EyeOff, Diamond, Film, Link2, Save, Trash2, Settings2,
+} from 'lucide-react';
+import { evaluateChannel, getComponent, InterpType, WrapMode } from 'esengine';
+import { TimelineDocument } from '@/timeline/TimelineDocument';
+import { TimelineCommands } from '@/timeline/TimelineCommands';
+import { useSequencerStore } from '@/store/sequencerStore';
+import { useSelection } from '@/store/selectionStore';
+import { SceneModel } from '@/engine/SceneModel';
+import { ContextMenu, type MenuItem } from '@/components/Menu';
+import { SequencerCurve } from '@/panels/SequencerCurve';
+import { sampleTimelineAsset } from '@/timeline/sampleTimeline';
+import {
+ buildTimelineRows, visibleRows, frameCount, timeToPct, pctToTime, findChannel, muteKey,
+ type SeqRow, type ChannelRef,
+} from '@/timeline/timelineView';
+
+// Interpolation choices shown in the keyframe popover (subset of InterpType).
+const INTERP_OPTIONS: [InterpType, string][] = [
+ [InterpType.Hermite, '自动(平滑)'],
+ [InterpType.Linear, '线性'],
+ [InterpType.Step, '阶梯(常量)'],
+ [InterpType.EaseInOut, '缓入缓出'],
+];
+
+const WRAP_OPTIONS: [WrapMode, string][] = [
+ [WrapMode.Once, '单次'],
+ [WrapMode.Loop, '循环'],
+ [WrapMode.PingPong, '往复'],
+];
+
+function getNested(obj: unknown, path: string): number {
+ let cur: unknown = obj;
+ for (const part of path.split('.')) {
+ if (cur == null || typeof cur !== 'object') return 0;
+ cur = (cur as Record<string, unknown>)[part];
+ }
+ return typeof cur === 'number' ? cur : 0;
+}
+
+interface AddTrackItem {
+ ref: ChannelRef;
+ component: string;
+ property: string;
+ value: number;
+}
+
+// The "add track" choices — engine-authoritative: each component the bound entity
+// carries × that component's `animatableFields` (from the engine registry, the
+// same source the inspector/serializer use), minus channels already tracked.
+function buildAddTrackItems(asset: { tracks: unknown } | null, rootSourceId: number | null): AddTrackItem[] {
+ if (!asset || rootSourceId == null) return [];
+ const entity = SceneModel.entityBySource(rootSourceId);
+ if (!entity) return [];
+ const items: AddTrackItem[] = [];
+ for (const comp of entity.components) {
+ const fields = getComponent(comp.type)?.animatableFields ?? [];
+ for (const property of fields) {
+ const ref: ChannelRef = { childPath: '', component: comp.type, property };
+ if (findChannel(asset as never, ref)) continue;
+ items.push({ ref, component: comp.type, property, value: getNested(comp.data, property) });
+ }
+ }
+ return items;
+}
+
+function EmptyState() {
+ return (
+ <div className="seq-empty">
+ <Film size={30} strokeWidth={1.3} />
+ <div className="seq-empty__title">没有打开的动画</div>
+ <div className="seq-empty__hint">在内容浏览器双击 .estimeline,或下方加载示例</div>
+ <button
+ type="button"
+ className="seq-empty__btn"
+ onClick={() => {
+ // Bind the preview to the current selection so scrubbing animates it.
+ const rootEntity = useSelection.getState().selectedId;
+ TimelineDocument.open({ asset: sampleTimelineAsset(), filePath: null, fps: 12, rootEntity });
+ useSequencerStore.getState().resetForClip();
+ }}
+ >
+ 加载示例(开发)
+ </button>
+ </div>
+ );
+}
+
+export function Sequencer() {
+ // Re-read the document on every revision bump (open / edit / close).
+ useSyncExternalStore(TimelineDocument.subscribe, TimelineDocument.getRevision);
+ const asset = TimelineDocument.asset;
+
+ if (!asset) return <div className="seq"><EmptyState /></div>;
+
+ return <SequencerBody />;
+}
+
+function SequencerBody() {
+ const asset = TimelineDocument.asset!;
+ const { fps } = TimelineDocument.meta;
+ const duration = asset.duration;
+
+ const time = useSequencerStore((s) => s.time);
+ const playing = useSequencerStore((s) => s.playing);
+ const loop = useSequencerStore((s) => s.loop);
+ const snap = useSequencerStore((s) => s.snap);
+ const view = useSequencerStore((s) => s.view);
+ const recording = useSequencerStore((s) => s.recording);
+ const collapsed = useSequencerStore((s) => s.collapsedGroups);
+ const mutedTracks = useSequencerStore((s) => s.mutedTracks);
+
+ const root = TimelineDocument.rootEntity;
+ const rootName = root != null ? (SceneModel.entityBySource(root)?.name || `#${root}`) : null;
+
+ const tlRef = useRef<HTMLDivElement>(null);
+
+ const totalFrames = frameCount(asset, fps);
+ const frame = Math.round(time * fps);
+
+ const rows = useMemo(() => buildTimelineRows(asset), [asset]);
+ const shown = useMemo(() => visibleRows(rows, collapsed), [rows, collapsed]);
+ const allKeyTimes = useMemo(() => {
+ const set = new Set<number>();
+ for (const r of rows) for (const t of r.keyframes) set.add(t);
+ return [...set].sort((a, b) => a - b);
+ }, [rows]);
+
+ // ── time helpers ──
+ const snapTime = (t: number) => {
+ const clamped = Math.max(0, Math.min(duration, t));
+ return snap && fps > 0 ? Math.round(clamped * fps) / fps : clamped;
+ };
+ const setTime = (t: number) => useSequencerStore.getState().setTime(snapTime(t));
+ const timeFromClientX = (clientX: number): number => {
+ const el = tlRef.current;
+ if (!el) return 0;
+ const r = el.getBoundingClientRect();
+ const pct = ((clientX - r.left) / r.width) * 100;
+ return pctToTime(pct, duration);
+ };
+
+ // ── keyframe editing (P2) ──
+ const selectedKey = useSequencerStore((s) => s.selectedKey);
+ const [dragKey, setDragKey] = useState<{ rowId: string; ref: ChannelRef; fromTime: number; time: number } | null>(null);
+ const [interp, setInterpPopover] = useState<{ ref: ChannelRef; time: number; x: number; y: number } | null>(null);
+
+ // Click a key → select + interp popover; drag past a threshold → move in time.
+ const onKeyPointerDown = (e: React.PointerEvent, ref: ChannelRef, rowId: string, time: number) => {
+ e.stopPropagation();
+ useSequencerStore.getState().setPlaying(false);
+ const startX = e.clientX;
+ const anchor = (e.currentTarget as HTMLElement).getBoundingClientRect();
+ let moved = false;
+ let liveTime = time;
+ const move = (ev: PointerEvent) => {
+ if (!moved && Math.abs(ev.clientX - startX) < 3) return;
+ moved = true;
+ liveTime = snapTime(timeFromClientX(ev.clientX));
+ setDragKey({ rowId, ref, fromTime: time, time: liveTime });
+ };
+ const up = () => {
+ window.removeEventListener('pointermove', move);
+ window.removeEventListener('pointerup', up);
+ setDragKey(null);
+ if (moved) {
+ TimelineCommands.moveKey(ref, time, liveTime);
+ useSequencerStore.getState().selectKey(`${rowId}@${liveTime}`);
+ setInterpPopover(null);
+ } else {
+ useSequencerStore.getState().selectKey(`${rowId}@${time}`);
+ setInterpPopover({ ref, time, x: anchor.left, y: anchor.bottom + 6 });
+ }
+ };
+ window.addEventListener('pointermove', move);
+ window.addEventListener('pointerup', up);
+ };
+
+ // Channel "key" button: insert a key at the playhead holding the curve's
+ // current value (a real curve split; in record mode auto-key uses the edit value).
+ const addKeyAtPlayhead = (ref: ChannelRef) => {
+ const ch = findChannel(asset, ref);
+ TimelineCommands.addKey(ref, snapTime(time), ch ? evaluateChannel(ch, time) : 0);
+ };
+
+ const curInterp: InterpType | null = interp
+ ? (findChannel(asset, interp.ref)?.keyframes.find((k) => Math.abs(k.time - interp.time) < 1e-4)?.interpolation
+ ?? InterpType.Hermite)
+ : null;
+
+ // ── track authoring + clip settings (P3) ──
+ const [pickerOpen, setPickerOpen] = useState<{ x: number; y: number } | null>(null);
+ const [settingsOpen, setSettingsOpen] = useState<{ x: number; y: number } | null>(null);
+ const [rowCtx, setRowCtx] = useState<{ x: number; y: number; ref: ChannelRef } | null>(null);
+ const addTrackItems = pickerOpen ? buildAddTrackItems(asset, root) : [];
+
+ const popoverAt = (e: React.MouseEvent) => {
+ const r = (e.currentTarget as HTMLElement).getBoundingClientRect();
+ return { x: Math.min(r.left, window.innerWidth - 240), y: r.bottom + 6 };
+ };
+
+ // ── playback (visual playhead; viewport preview is the next P1 step) ──
+ useEffect(() => {
+ if (!playing) return;
+ let raf = 0;
+ let last = performance.now();
+ const tick = (now: number) => {
+ const dt = (now - last) / 1000;
+ last = now;
+ const cur = useSequencerStore.getState().time + dt;
+ if (cur >= duration) {
+ if (loop) useSequencerStore.getState().setTime(cur % duration || 0);
+ else { useSequencerStore.getState().setTime(duration); useSequencerStore.getState().setPlaying(false); return; }
+ } else {
+ useSequencerStore.getState().setTime(cur);
+ }
+ raf = requestAnimationFrame(tick);
+ };
+ raf = requestAnimationFrame(tick);
+ return () => cancelAnimationFrame(raf);
+ }, [playing, loop, duration]);
+
+ const jumpKey = (dir: 1 | -1) => {
+ useSequencerStore.getState().setPlaying(false);
+ if (dir < 0) {
+ const prev = [...allKeyTimes].reverse().find((t) => t < time - 1e-4);
+ useSequencerStore.getState().setTime(prev ?? 0);
+ } else {
+ const next = allKeyTimes.find((t) => t > time + 1e-4);
+ useSequencerStore.getState().setTime(next ?? duration);
+ }
+ };
+
+ const onScrubDown = (e: React.PointerEvent) => {
+ if ((e.target as HTMLElement).closest('.seq-key')) return;
+ useSequencerStore.getState().setPlaying(false);
+ setTime(timeFromClientX(e.clientX));
+ const move = (ev: PointerEvent) => setTime(timeFromClientX(ev.clientX));
+ const up = () => {
+ window.removeEventListener('pointermove', move);
+ window.removeEventListener('pointerup', up);
+ };
+ window.addEventListener('pointermove', move);
+ window.addEventListener('pointerup', up);
+ };
+
+ // ── ruler ticks ──
+ const majorStep = Math.max(1, Math.round(fps / 2));
+ const showMinor = totalFrames <= 120;
+ const ticks: { f: number; major: boolean }[] = [];
+ for (let f = 0; f <= totalFrames; f++) {
+ const major = f % majorStep === 0;
+ if (major || showMinor) ticks.push({ f, major });
+ }
+
+ const keyCount = rows.reduce((n, r) => n + r.keyframes.length, 0);
+ const trackCount = rows.filter((r) => r.kind === 'channel' || r.kind === 'track').length;
+
+ return (
+ <div className={`seq${recording ? ' is-rec' : ''}${view === 'curve' ? ' is-curve' : ''}`}>
+ {/* transport */}
+ <div className="seq-bar">
+ <span className="seq-meta">
+ <Film size={13} className="seq-meta__icon" />
+ <b>{TimelineDocument.meta.filePath?.split('/').pop() ?? '未命名'}</b>
+ <span className="seq-meta__dim">· {totalFrames}帧 · {fps}fps · {loop ? '循环' : '单次'}</span>
+ </span>
+ <button
+ type="button"
+ className={`seq-btn seq-btn--text${rootName ? ' on' : ''}`}
+ title="把预览绑定到当前选中实体"
+ onClick={() => TimelineDocument.setRootEntity(useSelection.getState().selectedId)}
+ >
+ <Link2 size={13} /><span>{rootName ?? '未绑定'}</span>
+ </button>
+ <span className="seq-div" />
+ <button
+ type="button"
+ className={`seq-btn seq-btn--rec${recording ? ' on' : ''}`}
+ title="录制:编辑属性自动打帧"
+ onClick={() => useSequencerStore.getState().toggleRecording()}
+ >
+ <Circle size={12} fill="currentColor" />
+ </button>
+ <span className="seq-div" />
+ <button type="button" className="seq-btn" title="跳到开头" onClick={() => setTime(0)}><ChevronFirst size={15} /></button>
+ <button type="button" className="seq-btn" title="上一关键帧" onClick={() => jumpKey(-1)}><ChevronLeft size={15} /></button>
+ <button
+ type="button"
+ className="seq-btn seq-btn--play"
+ title="播放 / 暂停(空格)"
+ onClick={() => useSequencerStore.getState().togglePlay()}
+ >
+ {playing ? <Pause size={14} fill="currentColor" /> : <Play size={14} fill="currentColor" />}
+ </button>
+ <button type="button" className="seq-btn" title="下一关键帧" onClick={() => jumpKey(1)}><ChevronRight size={15} /></button>
+ <button type="button" className="seq-btn" title="跳到结尾" onClick={() => setTime(duration)}><ChevronLast size={15} /></button>
+ <button
+ type="button"
+ className={`seq-btn${loop ? ' on' : ''}`}
+ title="循环"
+ onClick={() => useSequencerStore.getState().toggleLoop()}
+ >
+ <Repeat size={14} />
+ </button>
+ <span className="seq-div" />
+ <span className="seq-frame">帧 <strong>{frame}</strong> / {totalFrames}</span>
+ <span className="seq-spacer" />
+ <div className="seq-tabs">
+ <button type="button" className={`seq-tab${view === 'sheet' ? ' active' : ''}`} onClick={() => useSequencerStore.getState().setView('sheet')}>摄影表</button>
+ <button type="button" className={`seq-tab${view === 'curve' ? ' active' : ''}`} onClick={() => useSequencerStore.getState().setView('curve')}>曲线</button>
+ </div>
+ <button
+ type="button"
+ className={`seq-btn${snap ? ' on' : ''}`}
+ title="吸附到帧"
+ onClick={() => useSequencerStore.getState().toggleSnap()}
+ >
+ <Magnet size={14} />
+ </button>
+ <button
+ type="button"
+ className="seq-btn"
+ title="片段设置(时长 / 帧率 / 循环)"
+ onClick={(e) => setSettingsOpen(popoverAt(e))}
+ >
+ <Settings2 size={14} />
+ </button>
+ <button
+ type="button"
+ className="seq-btn seq-btn--text"
+ title="添加轨道"
+ disabled={root == null}
+ onClick={(e) => setPickerOpen(popoverAt(e))}
+ >
+ <Plus size={14} /><span>轨道</span>
+ </button>
+ <button
+ type="button"
+ className={`seq-btn seq-btn--text${TimelineDocument.meta.dirty ? ' on' : ''}`}
+ title="保存动画"
+ onClick={() => void TimelineCommands.save()}
+ >
+ <Save size={14} /><span>{TimelineDocument.meta.dirty ? '保存*' : '保存'}</span>
+ </button>
+ </div>
+
+ {/* body: track list + timeline */}
+ <div className="seq-body">
+ <div className="seq-tracks">
+ <div className="seq-track-head">轨道</div>
+ <div className="seq-rows">
+ {shown.map((row) => (
+ <TrackRow
+ key={row.id}
+ row={row}
+ collapsed={collapsed.has(row.groupKey ?? '')}
+ muted={!!row.ref && mutedTracks.has(muteKey(row.ref))}
+ onAddKey={addKeyAtPlayhead}
+ onContext={(e, ref) => setRowCtx({ x: e.clientX, y: e.clientY, ref })}
+ />
+ ))}
+ </div>
+ </div>
+
+ <div className="seq-tl" ref={tlRef}>
+ <div className="seq-ruler" onPointerDown={onScrubDown}>
+ {ticks.map(({ f, major }) => (
+ <div
+ key={f}
+ className={`seq-tick${major ? ' major' : ''}`}
+ style={{ left: `${timeToPct(f / fps, duration)}%` }}
+ >
+ {major && <span className="seq-tick__label">{f}</span>}
+ </div>
+ ))}
+ </div>
+ <div className="seq-scroll" onPointerDown={onScrubDown}>
+ <div className="seq-grid">
+ {ticks.filter((t) => t.major).map(({ f }) => (
+ <div key={f} className="seq-gl" style={{ left: `${timeToPct(f / fps, duration)}%` }} />
+ ))}
+ </div>
+ {view === 'sheet' ? (
+ <div className="seq-lanes">
+ {shown.map((row) => (
+ <div
+ key={row.id}
+ className={`seq-lane seq-lane--${row.kind}${row.ref && mutedTracks.has(muteKey(row.ref)) ? ' muted' : ''}`}
+ >
+ {row.keyframes.map((t) => {
+ const isDrag = dragKey?.rowId === row.id && Math.abs(dragKey.fromTime - t) < 1e-4;
+ const at = isDrag ? dragKey!.time : t;
+ const sel = selectedKey === `${row.id}@${t}`;
+ return (
+ <div
+ key={t}
+ className={`seq-key${sel ? ' sel' : ''}${isDrag ? ' drag' : ''}`}
+ style={{ left: `${timeToPct(at, duration)}%` }}
+ title={`帧 ${Math.round(at * fps)}`}
+ onPointerDown={row.ref ? (e) => onKeyPointerDown(e, row.ref!, row.id, t) : undefined}
+ />
+ );
+ })}
+ </div>
+ ))}
+ </div>
+ ) : (
+ <SequencerCurve
+ asset={asset}
+ rows={shown}
+ duration={duration}
+ selectedKey={selectedKey}
+ timeFromClientX={timeFromClientX}
+ snapTime={snapTime}
+ />
+ )}
+ </div>
+ <div className="seq-playhead" style={{ left: `${timeToPct(time, duration)}%` }}>
+ <div className="seq-playhead__head" />
+ <span className="seq-playhead__time">{frame}</span>
+ </div>
+ </div>
+ </div>
+
+ {/* add-track picker — engine-authoritative animatable fields */}
+ {pickerOpen && (
+ <>
+ <div className="seq-pop-scrim" onPointerDown={() => setPickerOpen(null)} />
+ <div className="seq-picker" style={{ left: pickerOpen.x, top: pickerOpen.y }}>
+ <div className="seq-interp__title">添加轨道</div>
+ {addTrackItems.length === 0 ? (
+ <div className="seq-picker__empty">无可添加的可动画属性</div>
+ ) : (
+ addTrackItems.map((it) => (
+ <button
+ key={`${it.component}.${it.property}`}
+ type="button"
+ className="seq-interp__item"
+ onClick={() => {
+ TimelineCommands.addTrack(it.ref, it.value, snapTime(time));
+ setPickerOpen(null);
+ }}
+ >
+ <span className="seq-picker__comp">{it.component}</span>
+ <span className="seq-picker__prop">{it.property}</span>
+ </button>
+ ))
+ )}
+ </div>
+ </>
+ )}
+
+ {/* clip settings: duration / fps / wrap */}
+ {settingsOpen && (
+ <>
+ <div className="seq-pop-scrim" onPointerDown={() => setSettingsOpen(null)} />
+ <div className="seq-settings" style={{ left: settingsOpen.x, top: settingsOpen.y }}>
+ <div className="seq-interp__title">片段设置</div>
+ <label className="seq-settings__row">
+ <span>时长 (秒)</span>
+ <input
+ type="number" min={0} step={0.1} defaultValue={duration}
+ onChange={(e) => TimelineCommands.setDuration(parseFloat(e.target.value) || 0)}
+ />
+ </label>
+ <label className="seq-settings__row">
+ <span>帧率 (fps)</span>
+ <input
+ type="number" min={1} step={1} defaultValue={fps}
+ onChange={(e) => TimelineDocument.setFps(parseInt(e.target.value, 10) || 1)}
+ />
+ </label>
+ <div className="seq-settings__row">
+ <span>循环</span>
+ <div className="seq-settings__wrap">
+ {WRAP_OPTIONS.map(([mode, label]) => (
+ <button
+ key={mode}
+ type="button"
+ className={`seq-settings__wrapbtn${asset.wrapMode === mode ? ' on' : ''}`}
+ onClick={() => TimelineCommands.setWrapMode(mode)}
+ >
+ {label}
+ </button>
+ ))}
+ </div>
+ </div>
+ </div>
+ </>
+ )}
+
+ {/* channel row context menu */}
+ {rowCtx && (
+ <ContextMenu
+ x={rowCtx.x}
+ y={rowCtx.y}
+ items={
+ [
+ {
+ label: '删除轨道',
+ onClick: () => {
+ TimelineCommands.removeChannel(rowCtx.ref);
+ useSequencerStore.getState().selectKey(null);
+ },
+ },
+ ] as MenuItem[]
+ }
+ onClose={() => setRowCtx(null)}
+ />
+ )}
+
+ {/* keyframe interpolation popover */}
+ {interp && (
+ <>
+ <div className="seq-pop-scrim" onPointerDown={() => setInterpPopover(null)} />
+ <div className="seq-interp" style={{ left: interp.x, top: interp.y }}>
+ <div className="seq-interp__title">插值</div>
+ {INTERP_OPTIONS.map(([mode, label]) => (
+ <button
+ key={mode}
+ type="button"
+ className={`seq-interp__item${curInterp === mode ? ' on' : ''}`}
+ onClick={() => {
+ TimelineCommands.setKeyInterp(interp.ref, interp.time, mode);
+ setInterpPopover(null);
+ }}
+ >
+ {label}
+ </button>
+ ))}
+ <div className="seq-interp__sep" />
+ <button
+ type="button"
+ className="seq-interp__item seq-interp__del"
+ onClick={() => {
+ TimelineCommands.deleteKey(interp.ref, interp.time);
+ useSequencerStore.getState().selectKey(null);
+ setInterpPopover(null);
+ }}
+ >
+ <Trash2 size={12} /> 删除关键帧
+ </button>
+ </div>
+ </>
+ )}
+
+ {/* status strip */}
+ <div className="seq-foot">
+ <span className="seq-foot__dot" />
+ <span>{recording ? '● 录制中' : '动画编辑'}</span>
+ <span className="seq-spacer" />
+ <span><strong>{keyCount}</strong> 关键帧 · {trackCount} 轨道</span>
+ </div>
+ </div>
+ );
+}
+
+function TrackRow({
+ row,
+ collapsed,
+ muted,
+ onAddKey,
+ onContext,
+}: {
+ row: SeqRow;
+ collapsed: boolean;
+ muted: boolean;
+ onAddKey: (ref: ChannelRef) => void;
+ onContext: (e: React.MouseEvent, ref: ChannelRef) => void;
+}) {
+ const isGroup = row.kind === 'entity' || row.kind === 'component';
+ return (
+ <div
+ className={`seq-row seq-row--${row.kind}${muted ? ' muted' : ''}`}
+ style={{ paddingLeft: 8 + row.depth * 14 }}
+ onClick={() => {
+ if (isGroup && row.groupKey) useSequencerStore.getState().toggleGroup(row.groupKey);
+ }}
+ onContextMenu={
+ row.kind === 'channel' && row.ref
+ ? (e) => {
+ e.preventDefault();
+ onContext(e, row.ref!);
+ }
+ : undefined
+ }
+ >
+ {isGroup ? (
+ <ChevronDown size={12} className={`seq-row__chev${collapsed ? ' is-collapsed' : ''}`} />
+ ) : (
+ <span className="seq-row__chev seq-row__chev--leaf" />
+ )}
+ <span className="seq-row__label">{row.label}</span>
+ {row.kind === 'channel' && row.ref && (
+ <span className="seq-row__act">
+ <button
+ type="button"
+ className="seq-row__btn"
+ title="在播放头打关键帧"
+ onClick={(e) => {
+ e.stopPropagation();
+ onAddKey(row.ref!);
+ }}
+ >
+ <Diamond size={11} fill="currentColor" />
+ </button>
+ <button
+ type="button"
+ className={`seq-row__btn${muted ? ' on' : ''}`}
+ title={muted ? '取消静音' : '静音轨道'}
+ onClick={(e) => {
+ e.stopPropagation();
+ useSequencerStore.getState().toggleMute(muteKey(row.ref!));
+ }}
+ >
+ {muted ? <EyeOff size={11} /> : <Eye size={11} />}
+ </button>
+ </span>
+ )}
+ </div>
+ );
+}
diff --git a/desktop/src/panels/SequencerCurve.tsx b/desktop/src/panels/SequencerCurve.tsx
new file mode 100644
index 000000000..a8a4703d4
--- /dev/null
+++ b/desktop/src/panels/SequencerCurve.tsx
@@ -0,0 +1,186 @@
+/**
+ * @file SequencerCurve.tsx
+ * @brief Curve editor view for the Sequencer (docs/REARCH_ANIMATION.md P3).
+ *
+ * Best-architecture point: the curves are drawn by sampling the SAME runtime
+ * evaluator (`evaluateChannel`) the playback/preview uses — so the displayed curve
+ * is exactly what plays (WYSIWYG), with no parallel curve math. Editing a key's
+ * value/time or its in/out tangent handles writes the very keyframe fields the
+ * hermite evaluator reads, so the curve and the animation can never diverge.
+ *
+ * Lines render in one stretched SVG (non-scaling stroke); interactive points and
+ * tangent handles are DOM elements (crisp, easy hit-testing) — mirroring how the
+ * dope sheet renders keys as DOM.
+ */
+
+import { useRef, useState } from 'react';
+import { evaluateChannel, type TimelineAsset, type Keyframe } from 'esengine';
+import { TimelineCommands } from '@/timeline/TimelineCommands';
+import { useSequencerStore } from '@/store/sequencerStore';
+import { findChannel, timeToPct, type SeqRow } from '@/timeline/timelineView';
+
+const PAD_T = 8;
+const PAD_B = 8;
+const SAMPLES = 100;
+const PALETTE = ['var(--ax-x)', 'var(--ax-y)', 'var(--acc-hi)', '#c9a14e', '#9b8fc0', '#7faf9c'];
+
+interface CurveChannel {
+ row: SeqRow;
+ keyframes: Keyframe[];
+ color: string;
+}
+
+export function SequencerCurve({
+ asset,
+ rows,
+ duration,
+ selectedKey,
+ timeFromClientX,
+ snapTime,
+}: {
+ asset: TimelineAsset;
+ rows: SeqRow[];
+ duration: number;
+ selectedKey: string | null;
+ timeFromClientX: (clientX: number) => number;
+ snapTime: (t: number) => number;
+}) {
+ const areaRef = useRef<HTMLDivElement>(null);
+ const [drag, setDrag] = useState<{ rowId: string; fromTime: number; time: number; value: number } | null>(null);
+
+ const channels: CurveChannel[] = [];
+ rows.forEach((row) => {
+ if (row.kind !== 'channel' || !row.ref) return;
+ const ch = findChannel(asset, row.ref);
+ if (ch && ch.keyframes.length) channels.push({ row, keyframes: ch.keyframes, color: PALETTE[channels.length % PALETTE.length] });
+ });
+
+ // Shared value space (auto-fit to all visible keyframes, padded).
+ let min = Infinity;
+ let max = -Infinity;
+ for (const c of channels) for (const k of c.keyframes) {
+ if (k.value < min) min = k.value;
+ if (k.value > max) max = k.value;
+ }
+ if (!isFinite(min)) { min = 0; max = 1; }
+ if (max - min < 1e-6) { min -= 1; max += 1; }
+ const pad = (max - min) * 0.12;
+ min -= pad;
+ max += pad;
+ const range = max - min;
+
+ const valueToYPct = (v: number) => PAD_T + (1 - (v - min) / range) * (100 - PAD_T - PAD_B);
+ const valueFromClientY = (clientY: number): number => {
+ const r = areaRef.current?.getBoundingClientRect();
+ if (!r) return 0;
+ const pct = ((clientY - r.top) / r.height) * 100;
+ const norm = 1 - (pct - PAD_T) / (100 - PAD_T - PAD_B);
+ return min + norm * range;
+ };
+
+ const onPointDown = (e: React.PointerEvent, row: SeqRow, kf: Keyframe) => {
+ e.stopPropagation();
+ useSequencerStore.getState().setPlaying(false);
+ useSequencerStore.getState().selectKey(`${row.id}@${kf.time}`);
+ const sx = e.clientX, sy = e.clientY;
+ let moved = false, curT = kf.time, curV = kf.value;
+ const move = (ev: PointerEvent) => {
+ if (!moved && Math.abs(ev.clientX - sx) < 3 && Math.abs(ev.clientY - sy) < 3) return;
+ moved = true;
+ curT = snapTime(timeFromClientX(ev.clientX));
+ curV = valueFromClientY(ev.clientY);
+ setDrag({ rowId: row.id, fromTime: kf.time, time: curT, value: curV });
+ };
+ const up = () => {
+ window.removeEventListener('pointermove', move);
+ window.removeEventListener('pointerup', up);
+ setDrag(null);
+ if (moved && row.ref) {
+ TimelineCommands.editKey(row.ref, kf.time, curT, curV);
+ useSequencerStore.getState().selectKey(`${row.id}@${curT}`);
+ }
+ };
+ window.addEventListener('pointermove', move);
+ window.addEventListener('pointerup', up);
+ };
+
+ // Drag a tangent handle of the selected key → set in/out slope.
+ const onHandleDown = (e: React.PointerEvent, row: SeqRow, kf: Keyframe, side: 'in' | 'out') => {
+ e.stopPropagation();
+ const move = (ev: PointerEvent) => {
+ const t = timeFromClientX(ev.clientX);
+ const v = valueFromClientY(ev.clientY);
+ const dt = side === 'out' ? t - kf.time : kf.time - t;
+ if (Math.abs(dt) < 1e-4 || !row.ref) return;
+ const slope = side === 'out' ? (v - kf.value) / dt : (kf.value - v) / dt;
+ TimelineCommands.setKeyTangents(
+ row.ref,
+ kf.time,
+ side === 'in' ? slope : kf.inTangent,
+ side === 'out' ? slope : kf.outTangent,
+ );
+ };
+ const up = () => {
+ window.removeEventListener('pointermove', move);
+ window.removeEventListener('pointerup', up);
+ };
+ window.addEventListener('pointermove', move);
+ window.addEventListener('pointerup', up);
+ };
+
+ const HL = duration * 0.08; // tangent-handle length, in seconds
+
+ return (
+ <div className="seq-curve" ref={areaRef}>
+ <div className="seq-curve__axis">
+ <span style={{ top: `${valueToYPct(max - pad)}%` }}>{(max - pad).toFixed(1)}</span>
+ <span style={{ top: `${valueToYPct((min + max) / 2)}%` }}>{((min + max) / 2).toFixed(1)}</span>
+ <span style={{ top: `${valueToYPct(min + pad)}%` }}>{(min + pad).toFixed(1)}</span>
+ </div>
+
+ <svg className="seq-curve__svg" viewBox="0 0 100 100" preserveAspectRatio="none">
+ {channels.map((c) => {
+ let d = '';
+ for (let i = 0; i <= SAMPLES; i++) {
+ const t = (i / SAMPLES) * duration;
+ const x = timeToPct(t, duration);
+ const y = valueToYPct(evaluateChannel({ property: '', keyframes: c.keyframes }, t));
+ d += `${i === 0 ? 'M' : 'L'}${x.toFixed(2)} ${y.toFixed(2)} `;
+ }
+ return <path key={c.row.id} d={d} fill="none" style={{ stroke: c.color }} strokeWidth={1.5} vectorEffect="non-scaling-stroke" />;
+ })}
+ </svg>
+
+ {channels.map((c) =>
+ c.keyframes.map((kf) => {
+ const isDrag = drag?.rowId === c.row.id && Math.abs(drag.fromTime - kf.time) < 1e-4;
+ const t = isDrag ? drag!.time : kf.time;
+ const v = isDrag ? drag!.value : kf.value;
+ const selected = selectedKey === `${c.row.id}@${kf.time}`;
+ return (
+ <div key={`${c.row.id}/${kf.time}`}>
+ {selected && !isDrag && (
+ <>
+ <Handle x={timeToPct(kf.time - HL, duration)} y={valueToYPct(kf.value - kf.inTangent * HL)} color={c.color} onDown={(e) => onHandleDown(e, c.row, kf, 'in')} />
+ <Handle x={timeToPct(kf.time + HL, duration)} y={valueToYPct(kf.value + kf.outTangent * HL)} color={c.color} onDown={(e) => onHandleDown(e, c.row, kf, 'out')} />
+ </>
+ )}
+ <div
+ className={`seq-cpt${selected ? ' sel' : ''}`}
+ style={{ left: `${timeToPct(t, duration)}%`, top: `${valueToYPct(v)}%`, borderColor: c.color }}
+ title={`${c.row.label} = ${v.toFixed(2)}`}
+ onPointerDown={(e) => onPointDown(e, c.row, kf)}
+ />
+ </div>
+ );
+ }),
+ )}
+ </div>
+ );
+}
+
+function Handle({ x, y, color, onDown }: { x: number; y: number; color: string; onDown: (e: React.PointerEvent) => void }) {
+ return (
+ <div className="seq-chandle" style={{ left: `${x}%`, top: `${y}%`, background: color }} onPointerDown={onDown} />
+ );
+}
diff --git a/desktop/src/project/assetMeta.ts b/desktop/src/project/assetMeta.ts
index 917782768..7cb122207 100644
--- a/desktop/src/project/assetMeta.ts
+++ b/desktop/src/project/assetMeta.ts
@@ -18,6 +18,8 @@ export function assetTypeOf(name: string): AssetType {
if (ext === 'atlas' || ext === 'skel') return 'spine';
if (ext === 'esprefab') return 'prefab';
if (ext === 'esmat') return 'material';
+ // Unified animation clip (.esanim) + legacy multi-track timeline (.estimeline).
+ if (ext === 'esanim' || ext === 'estimeline') return 'animation';
return 'file';
}
@@ -33,6 +35,7 @@ export const TYPE_CODE: Record<AssetType, string> = {
spine: 'SPN',
audio: 'AUD',
script: 'TS',
+ animation: 'ANM',
};
export const baseName = (p: string) => (p.includes('/') ? p.slice(p.lastIndexOf('/') + 1) : p);
diff --git a/desktop/src/store/sequencerStore.ts b/desktop/src/store/sequencerStore.ts
new file mode 100644
index 000000000..f52e875b7
--- /dev/null
+++ b/desktop/src/store/sequencerStore.ts
@@ -0,0 +1,92 @@
+import { create } from 'zustand';
+
+// Sequencer UI + playback state (docs/REARCH_ANIMATION.md L4). Kept separate from
+// editorStore (scene-level UI) and the TimelineDocument (the asset data) — this is
+// the transient view state: playhead, transport flags, track-tree collapse,
+// keyframe selection. The playhead `time` is in SECONDS (the asset's unit); the
+// panel renders it as a frame via the document's fps.
+interface SequencerState {
+ // Playhead position, in seconds.
+ time: number;
+ setTime: (t: number) => void;
+
+ // Transport.
+ playing: boolean;
+ loop: boolean;
+ setPlaying: (p: boolean) => void;
+ togglePlay: () => void;
+ toggleLoop: () => void;
+
+ // Snap the playhead / keyframes to whole frames.
+ snap: boolean;
+ toggleSnap: () => void;
+
+ // Dope-sheet vs curve editor.
+ view: 'sheet' | 'curve';
+ setView: (v: 'sheet' | 'curve') => void;
+
+ // Record mode — editing a tracked property auto-keys at the playhead (P2).
+ recording: boolean;
+ toggleRecording: () => void;
+
+ // Collapsed track-tree groups (entity / component rows), keyed by groupKey.
+ collapsedGroups: Set<string>;
+ toggleGroup: (key: string) => void;
+
+ // Muted channels (editor-only; not saved to the asset), keyed by muteKey(ref).
+ // The preview skips these so the viewport reflects the mute.
+ mutedTracks: Set<string>;
+ toggleMute: (key: string) => void;
+
+ // Selected keyframe id (P2 editing), `${rowId}@${time}`.
+ selectedKey: string | null;
+ selectKey: (id: string | null) => void;
+
+ // Reset transient state when a different clip is opened.
+ resetForClip: () => void;
+}
+
+export const useSequencerStore = create<SequencerState>((set) => ({
+ time: 0,
+ setTime: (time) => set({ time: Math.max(0, time) }),
+
+ playing: false,
+ loop: true,
+ setPlaying: (playing) => set({ playing }),
+ togglePlay: () => set((s) => ({ playing: !s.playing })),
+ toggleLoop: () => set((s) => ({ loop: !s.loop })),
+
+ snap: true,
+ toggleSnap: () => set((s) => ({ snap: !s.snap })),
+
+ view: 'sheet',
+ setView: (view) => set({ view }),
+
+ recording: false,
+ toggleRecording: () => set((s) => ({ recording: !s.recording })),
+
+ collapsedGroups: new Set<string>(),
+ toggleGroup: (key) =>
+ set((s) => {
+ const next = new Set(s.collapsedGroups);
+ next.has(key) ? next.delete(key) : next.add(key);
+ return { collapsedGroups: next };
+ }),
+
+ mutedTracks: new Set<string>(),
+ toggleMute: (key) =>
+ set((s) => {
+ const next = new Set(s.mutedTracks);
+ next.has(key) ? next.delete(key) : next.add(key);
+ return { mutedTracks: next };
+ }),
+
+ selectedKey: null,
+ selectKey: (selectedKey) => set({ selectedKey }),
+
+ resetForClip: () =>
+ set({
+ time: 0, playing: false, selectedKey: null, recording: false,
+ mutedTracks: new Set<string>(), collapsedGroups: new Set<string>(),
+ }),
+}));
diff --git a/desktop/src/theme/sequencer.css b/desktop/src/theme/sequencer.css
new file mode 100644
index 000000000..4bb0dde1f
--- /dev/null
+++ b/desktop/src/theme/sequencer.css
@@ -0,0 +1,238 @@
+/* @file sequencer.css
+ Sequencer (animation timeline) panel — adapted from the design's
+ ue5-animation / botDock Sequencer onto the editor's tokens. Bottom-dock tab.
+ Structure: transport bar · (track list | frame timeline) · status strip. */
+
+.seq {
+ display: flex;
+ flex-direction: column;
+ height: 100%;
+ min-height: 0;
+ background: var(--panel);
+ color: var(--text);
+ font-size: 12px;
+ --seq-row-h: 22px;
+ --seq-tracks-w: 224px;
+}
+
+/* ── transport bar ── */
+.seq-bar {
+ display: flex;
+ align-items: center;
+ gap: 3px;
+ height: 34px;
+ flex: none;
+ padding: 0 8px;
+ background: var(--elevated);
+ border-bottom: 1px solid var(--border);
+}
+.seq-meta { display: inline-flex; align-items: center; gap: 4px; white-space: nowrap; }
+.seq-meta__icon { color: var(--acc-hi); }
+.seq-meta__dim { color: var(--text-mute); font-size: var(--fs-xs); }
+.seq-div { width: 1px; height: 16px; background: var(--border); margin: 0 4px; }
+.seq-spacer { flex: 1; }
+.seq-frame { color: var(--text-dim); font-family: var(--mono); font-size: var(--fs-xs); white-space: nowrap; }
+.seq-frame strong { color: var(--text); }
+
+.seq-btn {
+ display: inline-flex; align-items: center; justify-content: center; gap: 4px;
+ height: 24px; min-width: 24px; padding: 0 5px;
+ border: 0; border-radius: var(--r-md);
+ background: transparent; color: var(--text-dim); cursor: pointer;
+ transition: background 120ms var(--e-out), color 120ms var(--e-out);
+}
+.seq-btn:hover:not(:disabled) { background: var(--raised); color: var(--text); }
+.seq-btn:disabled { opacity: 0.4; cursor: default; }
+.seq-btn.on { color: var(--acc-hi); }
+.seq-btn--text span { font-size: var(--fs-xs); }
+.seq-btn--play {
+ background: var(--raised); color: var(--text);
+ min-width: 34px; border-radius: var(--r-md);
+}
+.seq-btn--play:hover { background: var(--srf-5); }
+.seq-btn--rec.on { color: var(--ax-x); }
+.seq.is-rec .seq-bar { box-shadow: inset 0 0 0 1px color-mix(in srgb, var(--ax-x) 40%, transparent); }
+
+.seq-tabs { display: inline-flex; background: var(--srf-2); border-radius: var(--r-md); padding: 2px; }
+.seq-tab {
+ border: 0; background: transparent; color: var(--text-mute); cursor: pointer;
+ font-size: var(--fs-xs); padding: 3px 9px; border-radius: var(--r-sm);
+}
+.seq-tab.active { background: var(--raised); color: var(--text); }
+
+/* ── body: track list | timeline ── */
+.seq-body { flex: 1; display: flex; min-height: 0; overflow: hidden; }
+
+.seq-tracks {
+ width: var(--seq-tracks-w); flex: none;
+ display: flex; flex-direction: column;
+ border-right: 1px solid var(--border);
+ overflow-y: auto;
+}
+.seq-track-head {
+ height: var(--seq-row-h); flex: none; display: flex; align-items: center;
+ padding: 0 10px; font-size: var(--fs-xs); color: var(--text-mute);
+ text-transform: uppercase; letter-spacing: 0.04em;
+ border-bottom: 1px solid var(--border); background: var(--elevated);
+}
+.seq-rows { display: flex; flex-direction: column; }
+
+.seq-row {
+ height: var(--seq-row-h); flex: none;
+ display: flex; align-items: center; gap: 4px;
+ padding-right: 6px; cursor: default; user-select: none;
+ border-bottom: 1px solid color-mix(in srgb, var(--border) 50%, transparent);
+}
+.seq-row--entity { background: var(--srf-3); cursor: pointer; }
+.seq-row--component { background: color-mix(in srgb, var(--srf-3) 50%, transparent); cursor: pointer; font-size: var(--fs-xs); }
+.seq-row--entity .seq-row__label { font-weight: 600; }
+.seq-row__label { flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+.seq-row--channel .seq-row__label { color: var(--text-dim); font-family: var(--mono); font-size: var(--fs-xs); }
+.seq-row--track .seq-row__label { color: var(--text-dim); }
+.seq-row__chev { color: var(--text-mute); transition: transform 150ms var(--e-out); flex: none; }
+.seq-row__chev.is-collapsed { transform: rotate(-90deg); }
+.seq-row__chev--leaf { width: 12px; height: 12px; }
+.seq-row__act { display: inline-flex; gap: 1px; opacity: 0; transition: opacity 120ms; }
+.seq-row:hover .seq-row__act { opacity: 1; }
+.seq-row__btn { border: 0; background: transparent; color: var(--text-mute); cursor: pointer; padding: 2px; border-radius: var(--r-xs); }
+.seq-row__btn:hover:not(:disabled) { color: var(--text); background: var(--raised); }
+.seq-row__btn:disabled { opacity: 0.5; cursor: default; }
+.seq-row__btn.on { color: var(--ax-x); }
+.seq-row.muted .seq-row__label { opacity: 0.45; text-decoration: line-through; }
+.seq-lane.muted .seq-key { opacity: 0.3; }
+
+/* ── timeline ── */
+.seq-tl { flex: 1; position: relative; display: flex; flex-direction: column; min-width: 0; overflow: hidden; }
+.seq-ruler {
+ height: var(--seq-row-h); flex: none; position: relative;
+ border-bottom: 1px solid var(--border); background: var(--elevated);
+ cursor: ew-resize;
+}
+.seq-tick { position: absolute; top: 0; bottom: 0; width: 1px; background: color-mix(in srgb, var(--border) 60%, transparent); }
+.seq-tick.major { background: var(--border); }
+.seq-tick__label {
+ position: absolute; top: 3px; left: 3px; font-size: 9px;
+ color: var(--text-mute); font-family: var(--mono);
+}
+.seq-scroll { flex: 1; position: relative; overflow-y: auto; cursor: ew-resize; }
+.seq-grid { position: absolute; inset: 0; pointer-events: none; }
+.seq-gl { position: absolute; top: 0; bottom: 0; width: 1px; background: color-mix(in srgb, var(--border) 40%, transparent); }
+.seq-lanes { position: relative; }
+.seq-lane {
+ height: var(--seq-row-h); position: relative;
+ border-bottom: 1px solid color-mix(in srgb, var(--border) 40%, transparent);
+}
+.seq-lane--entity { background: color-mix(in srgb, var(--srf-3) 40%, transparent); }
+.seq-lane--component { background: color-mix(in srgb, var(--srf-3) 20%, transparent); }
+
+.seq-key {
+ position: absolute; top: 50%; width: 9px; height: 9px;
+ transform: translate(-50%, -50%) rotate(45deg);
+ background: var(--acc); border: 1px solid var(--acc-hi); border-radius: 1px;
+ cursor: pointer;
+}
+.seq-key:hover { background: var(--acc-hi); }
+.seq-key.sel { background: var(--acc-hi); border-color: var(--text); box-shadow: 0 0 0 2px color-mix(in srgb, var(--acc-hi) 45%, transparent); z-index: 2; }
+.seq-key.drag { background: var(--acc-hi); cursor: ew-resize; z-index: 3; }
+
+/* keyframe interpolation popover */
+.seq-pop-scrim { position: fixed; inset: 0; z-index: 40; }
+.seq-interp {
+ position: fixed; z-index: 41; min-width: 150px;
+ background: var(--raised); border: 1px solid var(--border);
+ border-radius: var(--r-lg); padding: 4px; box-shadow: 0 8px 24px rgba(0,0,0,0.4);
+}
+.seq-interp__title { font-size: var(--fs-xs); color: var(--text-mute); padding: 4px 8px 6px; }
+.seq-interp__item {
+ display: flex; align-items: center; gap: 6px; width: 100%;
+ border: 0; background: transparent; color: var(--text-dim); cursor: pointer;
+ text-align: left; padding: 6px 8px; border-radius: var(--r-sm); font-size: 12px;
+}
+.seq-interp__item:hover { background: var(--srf-5); color: var(--text); }
+.seq-interp__item.on { color: var(--acc-hi); }
+.seq-interp__sep { height: 1px; background: var(--border); margin: 4px 2px; }
+.seq-interp__del { color: var(--ax-x); }
+.seq-interp__del:hover { background: color-mix(in srgb, var(--ax-x) 18%, transparent); color: var(--ax-x); }
+
+/* add-track picker + clip-settings popovers (share the interp popover shell) */
+.seq-picker, .seq-settings {
+ position: fixed; z-index: 41; min-width: 200px; max-height: 320px; overflow-y: auto;
+ background: var(--raised); border: 1px solid var(--border);
+ border-radius: var(--r-lg); padding: 4px; box-shadow: 0 8px 24px rgba(0,0,0,0.4);
+}
+.seq-picker__empty { padding: 8px; color: var(--text-mute); font-size: var(--fs-xs); }
+.seq-picker .seq-interp__item { justify-content: space-between; }
+.seq-picker__comp { color: var(--text-mute); font-size: var(--fs-xs); }
+.seq-picker__prop { color: var(--text); font-family: var(--mono); font-size: var(--fs-xs); }
+
+.seq-settings { min-width: 220px; padding: 8px; }
+.seq-settings__row {
+ display: flex; align-items: center; justify-content: space-between; gap: 10px;
+ padding: 5px 4px; font-size: 12px; color: var(--text-dim);
+}
+.seq-settings__row input {
+ width: 84px; background: var(--srf-2); border: 1px solid var(--border);
+ color: var(--text); border-radius: var(--r-sm); padding: 3px 6px;
+ font-family: var(--mono); font-size: var(--fs-xs);
+}
+.seq-settings__row input:focus { outline: none; border-color: var(--acc); }
+.seq-settings__wrap { display: inline-flex; background: var(--srf-2); border-radius: var(--r-md); padding: 2px; }
+.seq-settings__wrapbtn {
+ border: 0; background: transparent; color: var(--text-mute); cursor: pointer;
+ font-size: var(--fs-xs); padding: 3px 8px; border-radius: var(--r-sm);
+}
+.seq-settings__wrapbtn.on { background: var(--raised); color: var(--acc-hi); }
+
+.seq-playhead { position: absolute; top: 0; bottom: 0; width: 0; pointer-events: none; z-index: 5; }
+.seq-playhead::before { content: ''; position: absolute; top: 0; bottom: 0; left: -1px; width: 1px; background: var(--acc-hi); }
+.seq-playhead__head {
+ position: absolute; top: 0; left: -5px; width: 10px; height: 8px;
+ background: var(--acc-hi); border-radius: 0 0 2px 2px; pointer-events: auto; cursor: ew-resize;
+}
+.seq-playhead__time {
+ position: absolute; top: 1px; left: 7px; font-size: 9px; font-family: var(--mono);
+ color: var(--acc-hi); white-space: nowrap;
+}
+
+/* curve editor — fills the timeline scroll area in curve view */
+.seq-curve { position: absolute; inset: 0; }
+.seq-curve__svg { position: absolute; inset: 0; width: 100%; height: 100%; overflow: visible; }
+.seq-curve__axis { position: absolute; left: 0; top: 0; bottom: 0; width: 0; pointer-events: none; }
+.seq-curve__axis span {
+ position: absolute; left: 3px; transform: translateY(-50%);
+ font-size: 9px; font-family: var(--mono); color: var(--text-mute);
+}
+.seq-cpt {
+ position: absolute; width: 9px; height: 9px; transform: translate(-50%, -50%);
+ background: var(--panel); border: 1.5px solid var(--acc); border-radius: 50%;
+ cursor: pointer; z-index: 2;
+}
+.seq-cpt.sel { background: var(--acc-hi); border-color: var(--text); box-shadow: 0 0 0 2px color-mix(in srgb, var(--acc-hi) 40%, transparent); z-index: 3; }
+.seq-chandle {
+ position: absolute; width: 7px; height: 7px; transform: translate(-50%, -50%) rotate(45deg);
+ border-radius: 1px; cursor: move; opacity: 0.85; z-index: 3;
+}
+
+/* ── status strip ── */
+.seq-foot {
+ height: 22px; flex: none; display: flex; align-items: center; gap: 8px;
+ padding: 0 10px; font-size: var(--fs-xs); color: var(--text-mute);
+ border-top: 1px solid var(--border); background: var(--elevated);
+}
+.seq-foot strong { color: var(--text-dim); }
+.seq-foot__dot { width: 6px; height: 6px; border-radius: 50%; background: var(--acc); }
+.seq.is-rec .seq-foot__dot { background: var(--ax-x); }
+
+/* ── empty state ── */
+.seq-empty {
+ flex: 1; display: flex; flex-direction: column; align-items: center; justify-content: center;
+ gap: 8px; color: var(--text-mute); text-align: center; padding: 24px;
+}
+.seq-empty__title { color: var(--text-dim); font-size: 13px; }
+.seq-empty__hint { font-size: var(--fs-xs); }
+.seq-empty__btn {
+ margin-top: 6px; border: 1px solid var(--border); background: var(--raised);
+ color: var(--text-dim); border-radius: var(--r-md); padding: 5px 12px;
+ font-size: var(--fs-xs); cursor: pointer;
+}
+.seq-empty__btn:hover { color: var(--text); border-color: var(--acc); }
diff --git a/desktop/src/timeline/TimelineCommands.ts b/desktop/src/timeline/TimelineCommands.ts
new file mode 100644
index 000000000..a2e5ea917
--- /dev/null
+++ b/desktop/src/timeline/TimelineCommands.ts
@@ -0,0 +1,195 @@
+/**
+ * @file TimelineCommands.ts
+ * @brief Undoable edits to the open timeline document (docs/REARCH_ANIMATION.md P2).
+ *
+ * Mirrors the scene's SceneCommands: a command mutates the document's asset and
+ * registers one undo step on the shared {@link EditorHistory} (so timeline edits
+ * sit on the same undo stack as scene edits). Each command snapshots the whole
+ * asset before/after — timelines are small JSON, so whole-asset snapshots are the
+ * simplest correct undo unit (no per-keyframe inverse bookkeeping), and they make
+ * the preview self-consistent through undo/redo (TimelinePreview re-syncs on the
+ * document bump).
+ */
+
+import {
+ serializeTimelineToJson,
+ TrackType,
+ type TimelineAsset,
+ type InterpType,
+ type WrapMode,
+ type PropertyChannel,
+ type PropertyTrack,
+} from 'esengine';
+import { TimelineDocument } from './TimelineDocument';
+import { findChannel, upsertKeyframe, type ChannelRef } from './timelineView';
+import { EditorHistory } from '@/engine/EditorHistory';
+import { Toasts } from '@/store/Toasts';
+
+export type { ChannelRef };
+
+const clone = <T>(v: T): T =>
+ typeof structuredClone === 'function' ? structuredClone(v) : (JSON.parse(JSON.stringify(v)) as T);
+
+// Keyframes equal within this many seconds are treated as the same key.
+const EPS = 1e-4;
+
+function sortKeys(ch: PropertyChannel): void {
+ ch.keyframes.sort((a, b) => a.time - b.time);
+}
+
+class TimelineCommandsImpl {
+ /** Apply an already-decided mutation as one undo step (whole-asset snapshot). */
+ private apply(label: string, mutate: (draft: TimelineAsset) => void): void {
+ const before = TimelineDocument.asset;
+ if (!before) return;
+ const after = clone(before);
+ mutate(after);
+ TimelineDocument.replaceAsset(after);
+ EditorHistory.record(
+ label,
+ () => TimelineDocument.replaceAsset(after),
+ () => TimelineDocument.replaceAsset(before),
+ );
+ }
+
+ addKey(ref: ChannelRef, time: number, value: number, interp?: InterpType): void {
+ this.apply('Add Keyframe', (a) => {
+ const ch = findChannel(a, ref);
+ if (ch) upsertKeyframe(ch, time, value, interp);
+ });
+ }
+
+ /**
+ * Add an animatable channel (creating its property track if needed) and seed it
+ * with one keyframe at `time` holding `valueAtTime` — so a new track is animated,
+ * not empty. No-op if the channel already exists.
+ */
+ addTrack(ref: ChannelRef, valueAtTime: number, time: number): void {
+ if (findChannel(TimelineDocument.asset ?? ({} as TimelineAsset), ref)) return;
+ this.apply('Add Track', (a) => {
+ let track = a.tracks.find(
+ (t): t is PropertyTrack =>
+ t.type === TrackType.Property && t.childPath === ref.childPath && t.component === ref.component,
+ );
+ if (!track) {
+ track = { type: TrackType.Property, name: ref.component, childPath: ref.childPath, component: ref.component, channels: [] };
+ a.tracks.push(track);
+ }
+ let ch = track.channels.find((c) => c.property === ref.property);
+ if (!ch) {
+ ch = { property: ref.property, keyframes: [] };
+ track.channels.push(ch);
+ }
+ upsertKeyframe(ch, time, valueAtTime);
+ });
+ }
+
+ /** Remove an animatable channel; drop its property track when it goes empty. */
+ removeChannel(ref: ChannelRef): void {
+ this.apply('Remove Track', (a) => {
+ for (let ti = a.tracks.length - 1; ti >= 0; ti--) {
+ const t = a.tracks[ti];
+ if (t.type !== TrackType.Property || t.childPath !== ref.childPath || t.component !== ref.component) continue;
+ t.channels = t.channels.filter((c) => c.property !== ref.property);
+ if (t.channels.length === 0) a.tracks.splice(ti, 1);
+ }
+ });
+ }
+
+ deleteKey(ref: ChannelRef, time: number): void {
+ this.apply('Delete Keyframe', (a) => {
+ const ch = findChannel(a, ref);
+ if (!ch) return;
+ const i = ch.keyframes.findIndex((k) => Math.abs(k.time - time) < EPS);
+ if (i >= 0) ch.keyframes.splice(i, 1);
+ });
+ }
+
+ setKeyValue(ref: ChannelRef, time: number, value: number): void {
+ this.apply('Edit Keyframe', (a) => {
+ const k = findChannel(a, ref)?.keyframes.find((x) => Math.abs(x.time - time) < EPS);
+ if (k) k.value = value;
+ });
+ }
+
+ setKeyInterp(ref: ChannelRef, time: number, interp: InterpType): void {
+ this.apply('Set Interpolation', (a) => {
+ const k = findChannel(a, ref)?.keyframes.find((x) => Math.abs(x.time - time) < EPS);
+ if (k) k.interpolation = interp;
+ });
+ }
+
+ /** Move a key in time AND set its value in one step (curve-view 2D drag). */
+ editKey(ref: ChannelRef, fromTime: number, toTime: number, value: number): void {
+ this.apply('Edit Keyframe', (a) => {
+ const ch = findChannel(a, ref);
+ const k = ch?.keyframes.find((x) => Math.abs(x.time - fromTime) < EPS);
+ if (!ch || !k) return;
+ if (Math.abs(toTime - fromTime) >= EPS) {
+ const dup = ch.keyframes.findIndex((x) => x !== k && Math.abs(x.time - toTime) < EPS);
+ if (dup >= 0) ch.keyframes.splice(dup, 1);
+ k.time = toTime;
+ }
+ k.value = value;
+ sortKeys(ch);
+ });
+ }
+
+ /** Set a key's in/out tangents (and switch it to Hermite) — curve handle drag. */
+ setKeyTangents(ref: ChannelRef, time: number, inTangent: number, outTangent: number): void {
+ this.apply('Edit Tangents', (a) => {
+ const k = findChannel(a, ref)?.keyframes.find((x) => Math.abs(x.time - time) < EPS);
+ if (!k) return;
+ k.inTangent = inTangent;
+ k.outTangent = outTangent;
+ k.interpolation = undefined; // Hermite is the default (uses tangents)
+ });
+ }
+
+ /** Move a keyframe in time (drag). A key already at `toTime` is overwritten. */
+ moveKey(ref: ChannelRef, fromTime: number, toTime: number): void {
+ if (Math.abs(fromTime - toTime) < EPS) return;
+ this.apply('Move Keyframe', (a) => {
+ const ch = findChannel(a, ref);
+ if (!ch) return;
+ const k = ch.keyframes.find((x) => Math.abs(x.time - fromTime) < EPS);
+ if (!k) return;
+ const dup = ch.keyframes.findIndex((x) => x !== k && Math.abs(x.time - toTime) < EPS);
+ if (dup >= 0) ch.keyframes.splice(dup, 1);
+ k.time = toTime;
+ sortKeys(ch);
+ });
+ }
+
+ setDuration(seconds: number): void {
+ this.apply('Set Duration', (a) => {
+ a.duration = Math.max(0, seconds);
+ });
+ }
+
+ setWrapMode(mode: WrapMode): void {
+ this.apply('Set Wrap Mode', (a) => {
+ a.wrapMode = mode;
+ });
+ }
+
+ /** Write the document back to its .esanim file. */
+ async save(): Promise<void> {
+ const asset = TimelineDocument.asset;
+ const { filePath } = TimelineDocument.meta;
+ if (!asset) return;
+ if (!filePath) {
+ Toasts.push('动画未关联文件(示例片段无法保存)', 'error');
+ return;
+ }
+ try {
+ await window.estella.fs.write(filePath, serializeTimelineToJson(asset) + '\n');
+ TimelineDocument.markSaved();
+ Toasts.push('动画已保存', 'success', 1500);
+ } catch (e) {
+ Toasts.push(`保存失败:${String(e)}`, 'error');
+ }
+ }
+}
+
+export const TimelineCommands = new TimelineCommandsImpl();
diff --git a/desktop/src/timeline/TimelineDocument.ts b/desktop/src/timeline/TimelineDocument.ts
new file mode 100644
index 000000000..1b4556492
--- /dev/null
+++ b/desktop/src/timeline/TimelineDocument.ts
@@ -0,0 +1,122 @@
+/**
+ * @file TimelineDocument.ts
+ * @brief The open .estimeline as a reactive editor document — the first asset
+ * document session (docs/REARCH_ANIMATION.md L4).
+ *
+ * Mirrors the scene's model-authoritative reactivity (SceneStore): the in-memory
+ * TimelineAsset is the source of truth, panels subscribe via useSyncExternalStore
+ * and re-read on each revision bump. Editing commands (P2) mutate the asset and
+ * bump; for P1 the document just holds an opened clip + its preview binding.
+ *
+ * `fps` is editor display metadata (the asset stores time in seconds); the design
+ * shows a frame ruler, so the panel converts seconds ↔ frames via this fps.
+ */
+
+import { createStore } from 'zustand/vanilla';
+import { parseTimelineAsset, type TimelineAsset } from 'esengine';
+import type { EntityId } from '@/types';
+
+export interface TimelineDocMeta {
+ filePath: string | null;
+ fps: number;
+ dirty: boolean;
+}
+
+// The design's default authoring rate (12 fps). Editor-side only — not persisted
+// in the asset, which is frame-rate-independent (keyframe times are seconds).
+const DEFAULT_FPS = 12;
+
+function emptyMeta(): TimelineDocMeta {
+ return { filePath: null, fps: DEFAULT_FPS, dirty: false };
+}
+
+export interface OpenParams {
+ asset: TimelineAsset;
+ filePath?: string | null;
+ fps?: number;
+ rootEntity?: EntityId | null;
+}
+
+export class TimelineDocumentImpl {
+ private _asset: TimelineAsset | null = null;
+ private _meta: TimelineDocMeta = emptyMeta();
+ private _root: EntityId | null = null;
+ private readonly store = createStore<{ revision: number }>(() => ({ revision: 0 }));
+
+ subscribe = (fn: () => void): (() => void) => this.store.subscribe(fn);
+ getRevision = (): number => this.store.getState().revision;
+ private bump() {
+ this.store.setState((s) => ({ revision: s.revision + 1 }));
+ }
+
+ get asset(): TimelineAsset | null {
+ return this._asset;
+ }
+ get meta(): TimelineDocMeta {
+ return this._meta;
+ }
+ get rootEntity(): EntityId | null {
+ return this._root;
+ }
+ get isOpen(): boolean {
+ return this._asset !== null;
+ }
+
+ /** Open an already-parsed timeline asset, optionally bound to a preview entity. */
+ open(params: OpenParams): void {
+ this._asset = params.asset;
+ this._meta = {
+ filePath: params.filePath ?? null,
+ fps: params.fps ?? DEFAULT_FPS,
+ dirty: false,
+ };
+ this._root = params.rootEntity ?? null;
+ this.bump();
+ }
+
+ /** Open from raw .estimeline JSON (parsed + migrated by the SDK loader). */
+ openJson(raw: unknown, params: Omit<OpenParams, 'asset'> = {}): void {
+ this.open({ asset: parseTimelineAsset(raw), ...params });
+ }
+
+ /** Rebind which scene entity the timeline previews against (its root). */
+ setRootEntity(id: EntityId | null): void {
+ this._root = id;
+ this.bump();
+ }
+
+ /** Set the editor display frame rate (view metadata; not persisted in the asset). */
+ setFps(fps: number): void {
+ const next = Math.max(1, Math.round(fps));
+ if (next === this._meta.fps) return;
+ this._meta = { ...this._meta, fps: next };
+ this.bump();
+ }
+
+ /** Clear the dirty flag after a successful save. */
+ markSaved(): void {
+ if (!this._meta.dirty) return;
+ this._meta = { ...this._meta, dirty: false };
+ this.bump();
+ }
+
+ /**
+ * Replace the asset after a command mutation (P2). Kept distinct from open() so
+ * the file binding / fps survive an edit; marks the document dirty by default.
+ */
+ replaceAsset(next: TimelineAsset, opts: { dirty?: boolean } = {}): void {
+ this._asset = next;
+ this._meta = { ...this._meta, dirty: opts.dirty ?? true };
+ this.bump();
+ }
+
+ close(): void {
+ this._asset = null;
+ this._meta = emptyMeta();
+ this._root = null;
+ this.bump();
+ }
+}
+
+/** The app's default timeline document (the one the Sequencer panel drives). */
+export const TimelineDocument = new TimelineDocumentImpl();
diff --git a/desktop/src/timeline/TimelineRecorder.ts b/desktop/src/timeline/TimelineRecorder.ts
new file mode 100644
index 000000000..4bc79f234
--- /dev/null
+++ b/desktop/src/timeline/TimelineRecorder.ts
@@ -0,0 +1,131 @@
+/**
+ * @file TimelineRecorder.ts
+ * @brief Record mode — auto-key inspector/gizmo edits into the open clip
+ * (docs/REARCH_ANIMATION.md P2).
+ *
+ * Registers a generic edit hook on SceneCommands (the single field-edit door): when
+ * recording is on and the edited entity is the clip's bound preview root, it drops
+ * a keyframe at the playhead on every EXISTING channel the edited field maps to
+ * (vec fields fan out to their scalar channels, e.g. position → position.x/y/z).
+ *
+ * Observe-only: the hook returns false, so the edit still lands on the scene as
+ * usual and the viewport stays consistent (TimelinePreview re-samples the timeline,
+ * which now holds the keyed value). Rapid edits (a drag) are coalesced into ONE
+ * undo step via a short settle timer, so dragging doesn't flood the undo stack.
+ *
+ * Known P2 limitation: it keys only channels whose track already exists, and the
+ * edit also moves the entity's scene base value (true non-destructive record —
+ * suppress the scene write + read the inspector live — is a P3 upgrade the hook's
+ * boolean return already supports).
+ */
+
+import { TrackType, type TimelineAsset } from 'esengine';
+import { TimelineDocument } from './TimelineDocument';
+import { upsertKeyframe } from './timelineView';
+import { useSequencerStore } from '@/store/sequencerStore';
+import { SceneCommands } from '@/engine/SceneCommands';
+import { EditorHistory } from '@/engine/EditorHistory';
+import type { EntityId, InspectorFieldType, InspectorFieldValue } from '@/types';
+
+const clone = <T>(v: T): T =>
+ typeof structuredClone === 'function' ? structuredClone(v) : (JSON.parse(JSON.stringify(v)) as T);
+
+// Vector/color sub-field suffix → component index (value arrays are [x,y,z,w] /
+// [r,g,b,a]; the channel property is e.g. "position.x").
+const SUB_INDEX: Record<string, number> = { x: 0, y: 1, z: 2, w: 3, r: 0, g: 1, b: 2, a: 3 };
+
+/** Extract the scalar a channel `property` wants from an edited field's value. */
+function scalarFor(value: InspectorFieldValue, property: string, key: string): number | null {
+ if (property === key) return typeof value === 'number' ? value : null;
+ const suffix = property.slice(key.length + 1);
+ const i = SUB_INDEX[suffix];
+ if (i == null) return null;
+ if (Array.isArray(value)) return typeof value[i] === 'number' ? (value[i] as number) : null;
+ if (value && typeof value === 'object') {
+ const v = (value as Record<string, unknown>)[suffix];
+ return typeof v === 'number' ? v : null;
+ }
+ return null;
+}
+
+class TimelineRecorderImpl {
+ private attached = false;
+ private burstBefore: TimelineAsset | null = null;
+ private timer: ReturnType<typeof setTimeout> | null = null;
+
+ attach(): void {
+ if (this.attached) return;
+ this.attached = true;
+ SceneCommands.setEditHook((sourceId, compName, key, type, value) =>
+ this.onEdit(sourceId, compName, key, type, value),
+ );
+ // Flush the pending burst the moment recording is switched off.
+ useSequencerStore.subscribe(() => {
+ if (!useSequencerStore.getState().recording && this.timer != null) this.flush();
+ });
+ }
+
+ private onEdit(
+ sourceId: EntityId,
+ compName: string,
+ key: string,
+ _type: InspectorFieldType,
+ value: InspectorFieldValue,
+ ): boolean {
+ const seq = useSequencerStore.getState();
+ const asset = TimelineDocument.asset;
+ const root = TimelineDocument.rootEntity;
+ if (!seq.recording || !asset || root == null || sourceId !== root) return false;
+
+ const fps = TimelineDocument.meta.fps;
+ const time = seq.snap && fps > 0 ? Math.round(seq.time * fps) / fps : seq.time;
+
+ const draft = clone(asset);
+ let keyed = 0;
+ for (const track of draft.tracks) {
+ if (track.type !== TrackType.Property || track.childPath !== '' || track.component !== compName) continue;
+ for (const ch of track.channels) {
+ if (ch.property !== key && !ch.property.startsWith(`${key}.`)) continue;
+ const scalar = scalarFor(value, ch.property, key);
+ if (scalar == null) continue;
+ upsertKeyframe(ch, time, scalar);
+ keyed++;
+ }
+ }
+ if (keyed === 0) return false;
+
+ if (!this.burstBefore) this.burstBefore = clone(asset); // pre-burst state for one undo
+ TimelineDocument.replaceAsset(draft); // live (preview re-samples); undo recorded on settle
+ this.scheduleCommit();
+ return false; // observe-only — the scene edit still applies
+ }
+
+ private scheduleCommit(): void {
+ if (this.timer != null) clearTimeout(this.timer);
+ this.timer = setTimeout(() => this.commit(), 200);
+ }
+
+ private flush(): void {
+ if (this.timer != null) {
+ clearTimeout(this.timer);
+ this.timer = null;
+ }
+ this.commit();
+ }
+
+ /** Record the whole burst (pre-burst → now) as one undo step. */
+ private commit(): void {
+ this.timer = null;
+ const before = this.burstBefore;
+ this.burstBefore = null;
+ const after = TimelineDocument.asset;
+ if (!before || !after) return;
+ EditorHistory.record(
+ 'Record Keyframes',
+ () => TimelineDocument.replaceAsset(after),
+ () => TimelineDocument.replaceAsset(before),
+ );
+ }
+}
+
+export const TimelineRecorder = new TimelineRecorderImpl();
diff --git a/desktop/src/timeline/openClip.ts b/desktop/src/timeline/openClip.ts
new file mode 100644
index 000000000..ab60e08a6
--- /dev/null
+++ b/desktop/src/timeline/openClip.ts
@@ -0,0 +1,30 @@
+/**
+ * @file openClip.ts
+ * @brief Open an animation clip (.esanim / legacy .estimeline) from disk into
+ * the Sequencer (docs/REARCH_ANIMATION.md P2).
+ *
+ * Reads the project file, parses it through the unified clip loader (rich
+ * multi-track or legacy flipbook), opens it as the editor TimelineDocument bound
+ * to the current selection as its preview root, and reveals the Sequencer.
+ */
+
+import { parseAnimationClip } from 'esengine';
+import { TimelineDocument } from './TimelineDocument';
+import { useSequencerStore } from '@/store/sequencerStore';
+import { useSelection } from '@/store/selectionStore';
+import { dockApi } from '@/layout/dockApi';
+import { Toasts } from '@/store/Toasts';
+
+export async function openAnimationClip(path: string): Promise<void> {
+ try {
+ const text = await window.estella.fs.read(path);
+ const asset = parseAnimationClip(JSON.parse(text));
+ // Bind the preview to the current selection (if any) so scrubbing animates it.
+ const rootEntity = useSelection.getState().selectedId;
+ TimelineDocument.open({ asset, filePath: path, rootEntity });
+ useSequencerStore.getState().resetForClip();
+ dockApi.revealAndExpand('sequencer');
+ } catch (e) {
+ Toasts.push(`无法打开动画:${String(e)}`, 'error');
+ }
+}
diff --git a/desktop/src/timeline/sampleTimeline.ts b/desktop/src/timeline/sampleTimeline.ts
new file mode 100644
index 000000000..104430506
--- /dev/null
+++ b/desktop/src/timeline/sampleTimeline.ts
@@ -0,0 +1,76 @@
+/**
+ * @file sampleTimeline.ts
+ * @brief A built-in sample .estimeline for skeleton verification (DEV ONLY).
+ *
+ * Lets the Sequencer render a real track tree before the Content Browser "open
+ * .estimeline" flow lands (P2). Remove once opening real clips is wired.
+ */
+
+import { parseTimelineAsset, type TimelineAsset } from 'esengine';
+
+const RAW = {
+ version: '1.1',
+ type: 'timeline',
+ duration: 2.0,
+ wrapMode: 'loop',
+ tracks: [
+ {
+ type: 'property',
+ name: 'Move',
+ childPath: '',
+ component: 'Transform',
+ channels: [
+ {
+ property: 'position.x',
+ keyframes: [
+ { time: 0, value: 0, inTangent: 0, outTangent: 0, interpolation: 'linear' },
+ { time: 1, value: 120, inTangent: 0, outTangent: 0, interpolation: 'easeInOut' },
+ { time: 2, value: 0, inTangent: 0, outTangent: 0, interpolation: 'linear' },
+ ],
+ },
+ {
+ property: 'position.y',
+ keyframes: [
+ { time: 0, value: 0, inTangent: 0, outTangent: 0 },
+ { time: 1, value: 60, inTangent: 0, outTangent: 0 },
+ { time: 2, value: 0, inTangent: 0, outTangent: 0 },
+ ],
+ },
+ {
+ property: 'rotation.z',
+ keyframes: [
+ { time: 0, value: 0, inTangent: 0, outTangent: 0, interpolation: 'linear' },
+ { time: 2, value: Math.PI * 2, inTangent: 0, outTangent: 0, interpolation: 'linear' },
+ ],
+ },
+ ],
+ },
+ {
+ type: 'property',
+ name: 'Fade',
+ childPath: '',
+ component: 'Sprite',
+ channels: [
+ {
+ property: 'color.a',
+ keyframes: [
+ { time: 0, value: 1, inTangent: 0, outTangent: 0 },
+ { time: 1, value: 0.2, inTangent: 0, outTangent: 0 },
+ { time: 2, value: 1, inTangent: 0, outTangent: 0 },
+ ],
+ },
+ ],
+ },
+ {
+ type: 'audio',
+ name: 'Step',
+ childPath: '',
+ events: [{ time: 0.5, clip: 'sfx/step.mp3', volume: 0.8 }],
+ },
+ ],
+};
+
+export function sampleTimelineAsset(): TimelineAsset {
+ // Parse a fresh copy each call so edits don't mutate the shared literal.
+ return parseTimelineAsset(JSON.parse(JSON.stringify(RAW)));
+}
diff --git a/desktop/src/timeline/timelineView.ts b/desktop/src/timeline/timelineView.ts
new file mode 100644
index 000000000..f64e8757f
--- /dev/null
+++ b/desktop/src/timeline/timelineView.ts
@@ -0,0 +1,207 @@
+/**
+ * @file timelineView.ts
+ * @brief Read projection for the Sequencer panel — derive a renderable
+ * entity→component→channel row tree (and keyframe times) from the flat
+ * TimelineAsset. The seed of TimelineQuery (docs/REARCH_ANIMATION.md L4).
+ *
+ * The asset stores tracks flat (each carries childPath + component + channels);
+ * the UI shows them as the design's nested tree (Player → Transform → 位置/…),
+ * grouped by entity (childPath) then component, with each property channel a leaf
+ * lane. Non-property tracks (spine/audio/activation/…) render as single rows.
+ */
+
+import {
+ TrackType,
+ type TimelineAsset,
+ type Track,
+ type PropertyTrack,
+ type PropertyChannel,
+ type InterpType,
+} from 'esengine';
+
+/** Addresses one animatable channel: entity (childPath) + component + property. */
+export interface ChannelRef {
+ childPath: string;
+ component: string;
+ property: string;
+}
+
+/** Stable string key for a channel (mute set / lookups). */
+export function muteKey(ref: ChannelRef): string {
+ return `${ref.childPath}|${ref.component}|${ref.property}`;
+}
+
+/** Resolve the property channel a {@link ChannelRef} points at (or null). */
+export function findChannel(asset: TimelineAsset, ref: ChannelRef): PropertyChannel | null {
+ for (const t of asset.tracks) {
+ if (t.type === TrackType.Property && t.childPath === ref.childPath && t.component === ref.component) {
+ const ch = t.channels.find((c) => c.property === ref.property);
+ if (ch) return ch;
+ }
+ }
+ return null;
+}
+
+const KEY_EPS = 1e-4;
+
+/** Insert or replace a keyframe at `time` in a channel (keeps the array sorted). */
+export function upsertKeyframe(ch: PropertyChannel, time: number, value: number, interp?: InterpType): void {
+ const i = ch.keyframes.findIndex((k) => Math.abs(k.time - time) < KEY_EPS);
+ const kf = { time, value, inTangent: 0, outTangent: 0, ...(interp ? { interpolation: interp } : {}) };
+ if (i >= 0) ch.keyframes[i] = kf;
+ else {
+ ch.keyframes.push(kf);
+ ch.keyframes.sort((a, b) => a.time - b.time);
+ }
+}
+
+export type SeqRowKind = 'entity' | 'component' | 'channel' | 'track';
+
+export interface SeqRow {
+ /** Stable, unique row id (also the collapse/selection key). */
+ id: string;
+ kind: SeqRowKind;
+ label: string;
+ depth: number;
+ /** Set on collapsible group rows (entity / component). */
+ groupKey?: string;
+ /** Ancestor groupKeys — the row hides when any ancestor is collapsed. */
+ parentGroups: string[];
+ /** Keyframe times (seconds) for lane rendering; empty for group rows. */
+ keyframes: number[];
+ trackType: string;
+ /** Set on channel rows — the animatable target for keyframe edits. */
+ ref?: ChannelRef;
+}
+
+// Inset the lane edges so frame 0 / the last frame aren't flush against the
+// border (matches the design's PAD/SPAN mapping).
+export const LANE_PAD = 1;
+export const LANE_SPAN = 98;
+
+/** Frames in the clip given the editor display rate (asset time is seconds). */
+export function frameCount(asset: TimelineAsset, fps: number): number {
+ return Math.max(1, Math.round(asset.duration * fps));
+}
+
+/** Map a time (seconds) to a left-offset percentage within the timeline. */
+export function timeToPct(time: number, duration: number): number {
+ if (duration <= 0) return LANE_PAD;
+ return LANE_PAD + (time / duration) * LANE_SPAN;
+}
+
+/** Inverse of {@link timeToPct} — a left-offset percentage back to seconds. */
+export function pctToTime(pct: number, duration: number): number {
+ if (duration <= 0) return 0;
+ return ((pct - LANE_PAD) / LANE_SPAN) * duration;
+}
+
+/** Representative keyframe/event times for a non-property track (for its lane). */
+function trackEventTimes(track: Track): number[] {
+ switch (track.type) {
+ case TrackType.Spine:
+ return track.clips.map((c) => c.start);
+ case TrackType.Audio:
+ return track.events.map((e) => e.time);
+ case TrackType.Activation:
+ return track.ranges.flatMap((r) => [r.start, r.end]);
+ case TrackType.SpriteAnim:
+ return [track.startTime];
+ case TrackType.AnimFrames: {
+ const times: number[] = [];
+ let t = 0;
+ for (const f of track.frames) {
+ times.push(t);
+ t += f.duration ?? 1 / 12;
+ }
+ return times;
+ }
+ default:
+ return [];
+ }
+}
+
+export function buildTimelineRows(asset: TimelineAsset | null): SeqRow[] {
+ if (!asset) return [];
+
+ const byEntity = new Map<string, Track[]>();
+ for (const t of asset.tracks) {
+ const key = t.childPath ?? '';
+ const list = byEntity.get(key);
+ if (list) list.push(t);
+ else byEntity.set(key, [t]);
+ }
+
+ const rows: SeqRow[] = [];
+ for (const [childPath, tracks] of byEntity) {
+ const entityKey = `e:${childPath}`;
+ rows.push({
+ id: entityKey,
+ kind: 'entity',
+ label: childPath || '根实体',
+ depth: 0,
+ groupKey: entityKey,
+ parentGroups: [],
+ keyframes: [],
+ trackType: 'entity',
+ });
+
+ // Property tracks: group by component, then a leaf per channel.
+ const propTracks = tracks.filter((t): t is PropertyTrack => t.type === TrackType.Property);
+ const byComponent = new Map<string, PropertyTrack[]>();
+ for (const t of propTracks) {
+ const list = byComponent.get(t.component);
+ if (list) list.push(t);
+ else byComponent.set(t.component, [t]);
+ }
+ for (const [component, compTracks] of byComponent) {
+ const compKey = `${entityKey}/c:${component}`;
+ rows.push({
+ id: compKey,
+ kind: 'component',
+ label: component,
+ depth: 1,
+ groupKey: compKey,
+ parentGroups: [entityKey],
+ keyframes: [],
+ trackType: 'component',
+ });
+ for (const track of compTracks) {
+ for (const ch of track.channels) {
+ rows.push({
+ id: `${compKey}/${ch.property}`,
+ kind: 'channel',
+ label: ch.property,
+ depth: 2,
+ parentGroups: [entityKey, compKey],
+ keyframes: ch.keyframes.map((k) => k.time),
+ trackType: 'property',
+ ref: { childPath, component, property: ch.property },
+ });
+ }
+ }
+ }
+
+ // Non-property tracks (spine/audio/activation/spriteAnim/animFrames) → one row.
+ for (const t of tracks) {
+ if (t.type === TrackType.Property) continue;
+ rows.push({
+ id: `${entityKey}/t:${t.name}:${t.type}`,
+ kind: 'track',
+ label: t.name || t.type,
+ depth: 1,
+ parentGroups: [entityKey],
+ keyframes: trackEventTimes(t),
+ trackType: t.type,
+ });
+ }
+ }
+
+ return rows;
+}
+
+/** Filter out rows whose ancestor group is collapsed. */
+export function visibleRows(rows: SeqRow[], collapsed: Set<string>): SeqRow[] {
+ if (collapsed.size === 0) return rows;
+ return rows.filter((r) => !r.parentGroups.some((g) => collapsed.has(g)));
+}
diff --git a/desktop/src/types.ts b/desktop/src/types.ts
index cef45a7ca..112d1ab68 100644
--- a/desktop/src/types.ts
+++ b/desktop/src/types.ts
@@ -69,6 +69,7 @@ export type AssetType =
| 'prefab'
| 'material'
| 'script'
+ | 'animation'
| 'file';
export interface AssetItem {
diff --git a/desktop/tests/timeline-commands.test.ts b/desktop/tests/timeline-commands.test.ts
new file mode 100644
index 000000000..095bb9c08
--- /dev/null
+++ b/desktop/tests/timeline-commands.test.ts
@@ -0,0 +1,118 @@
+import { describe, it, expect, beforeEach } from 'vitest';
+import { WrapMode, TrackType, InterpType, type TimelineAsset } from 'esengine';
+import { TimelineDocument } from '@/timeline/TimelineDocument';
+import { TimelineCommands } from '@/timeline/TimelineCommands';
+import { findChannel } from '@/timeline/timelineView';
+import { EditorHistory } from '@/engine/EditorHistory';
+
+const REF = { childPath: '', component: 'Transform', property: 'position.x' };
+
+function freshAsset(): TimelineAsset {
+ return {
+ version: '1.1',
+ type: 'timeline',
+ duration: 2,
+ wrapMode: WrapMode.Once,
+ tracks: [
+ {
+ type: TrackType.Property,
+ name: 'Move',
+ childPath: '',
+ component: 'Transform',
+ channels: [
+ {
+ property: 'position.x',
+ keyframes: [{ time: 0, value: 0, inTangent: 0, outTangent: 0 }],
+ },
+ ],
+ },
+ ],
+ };
+}
+
+const keys = () => findChannel(TimelineDocument.asset!, REF)!.keyframes;
+
+describe('TimelineCommands', () => {
+ beforeEach(() => {
+ EditorHistory.clear();
+ TimelineDocument.open({ asset: freshAsset(), filePath: 'a.esanim', fps: 12 });
+ });
+
+ it('addKey inserts (sorted) and is undoable/redoable', () => {
+ TimelineCommands.addKey(REF, 1, 50);
+ expect(keys().map((k) => k.time)).toEqual([0, 1]);
+ expect(keys()[1].value).toBe(50);
+
+ EditorHistory.undo();
+ expect(keys().map((k) => k.time)).toEqual([0]);
+
+ EditorHistory.redo();
+ expect(keys().map((k) => k.time)).toEqual([0, 1]);
+ });
+
+ it('moveKey changes time and re-sorts', () => {
+ TimelineCommands.addKey(REF, 1.5, 10);
+ TimelineCommands.moveKey(REF, 1.5, 0.5);
+ expect(keys().map((k) => k.time)).toEqual([0, 0.5]);
+ });
+
+ it('setKeyInterp sets the interpolation mode', () => {
+ TimelineCommands.addKey(REF, 1, 10);
+ TimelineCommands.setKeyInterp(REF, 1, InterpType.Step);
+ expect(keys().find((k) => k.time === 1)?.interpolation).toBe(InterpType.Step);
+ });
+
+ it('deleteKey removes the keyframe', () => {
+ TimelineCommands.addKey(REF, 1, 10);
+ TimelineCommands.deleteKey(REF, 1);
+ expect(keys().map((k) => k.time)).toEqual([0]);
+ });
+
+ it('marks the document dirty on edit', () => {
+ expect(TimelineDocument.meta.dirty).toBe(false);
+ TimelineCommands.addKey(REF, 1, 10);
+ expect(TimelineDocument.meta.dirty).toBe(true);
+ });
+
+ it('addTrack creates a new channel+track seeded with a key, and is undoable', () => {
+ const NEW = { childPath: '', component: 'Sprite', property: 'color.a' };
+ expect(findChannel(TimelineDocument.asset!, NEW)).toBeNull();
+
+ TimelineCommands.addTrack(NEW, 0.5, 1);
+ const ch = findChannel(TimelineDocument.asset!, NEW);
+ expect(ch).not.toBeNull();
+ expect(ch!.keyframes).toEqual([{ time: 1, value: 0.5, inTangent: 0, outTangent: 0 }]);
+
+ EditorHistory.undo();
+ expect(findChannel(TimelineDocument.asset!, NEW)).toBeNull();
+ });
+
+ it('addTrack is a no-op when the channel already exists', () => {
+ const before = keys().length;
+ TimelineCommands.addTrack(REF, 9, 1); // REF.position.x already tracked
+ expect(keys().length).toBe(before);
+ });
+
+ it('removeChannel drops the channel and its now-empty track', () => {
+ TimelineCommands.removeChannel(REF);
+ expect(findChannel(TimelineDocument.asset!, REF)).toBeNull();
+ expect(TimelineDocument.asset!.tracks.length).toBe(0); // the only channel was removed
+ });
+
+ it('editKey sets time and value together (curve 2D drag)', () => {
+ TimelineCommands.addKey(REF, 1, 10);
+ TimelineCommands.editKey(REF, 1, 1.5, 88);
+ const k = keys().find((x) => Math.abs(x.time - 1.5) < 1e-4);
+ expect(k?.value).toBe(88);
+ expect(keys().some((x) => Math.abs(x.time - 1) < 1e-4)).toBe(false); // moved off 1
+ });
+
+ it('setKeyTangents writes in/out and reverts to Hermite', () => {
+ TimelineCommands.addKey(REF, 1, 10);
+ TimelineCommands.setKeyTangents(REF, 1, 2, -3);
+ const k = keys().find((x) => x.time === 1)!;
+ expect(k.inTangent).toBe(2);
+ expect(k.outTangent).toBe(-3);
+ expect(k.interpolation).toBeUndefined(); // Hermite default
+ });
+});
diff --git a/desktop/tests/timeline-recorder.test.ts b/desktop/tests/timeline-recorder.test.ts
new file mode 100644
index 000000000..eb99e7355
--- /dev/null
+++ b/desktop/tests/timeline-recorder.test.ts
@@ -0,0 +1,83 @@
+import { describe, it, expect, beforeEach } from 'vitest';
+import { WrapMode, TrackType, type TimelineAsset } from 'esengine';
+import { TimelineDocument } from '@/timeline/TimelineDocument';
+import { TimelineRecorder } from '@/timeline/TimelineRecorder';
+import { findChannel } from '@/timeline/timelineView';
+import { useSequencerStore } from '@/store/sequencerStore';
+import { SceneCommands } from '@/engine/SceneCommands';
+import { EditorHistory } from '@/engine/EditorHistory';
+
+TimelineRecorder.attach(); // registers the SceneCommands edit hook once
+
+const ROOT = 7 as const;
+
+function assetWith(props: string[]): TimelineAsset {
+ return {
+ version: '1.1',
+ type: 'timeline',
+ duration: 2,
+ wrapMode: WrapMode.Once,
+ tracks: [
+ {
+ type: TrackType.Property,
+ name: 'Move',
+ childPath: '',
+ component: 'Transform',
+ channels: props.map((property) => ({
+ property,
+ keyframes: [{ time: 0, value: 0, inTangent: 0, outTangent: 0 }],
+ })),
+ },
+ ],
+ };
+}
+
+const keysAt = (property: string) =>
+ findChannel(TimelineDocument.asset!, { childPath: '', component: 'Transform', property })!.keyframes;
+
+describe('TimelineRecorder (record auto-key)', () => {
+ beforeEach(() => {
+ EditorHistory.clear();
+ useSequencerStore.getState().setPlaying(false);
+ useSequencerStore.setState({ recording: false, snap: true });
+ TimelineDocument.open({ asset: assetWith(['position.x', 'position.y']), filePath: 'a.esanim', fps: 12, rootEntity: ROOT });
+ useSequencerStore.getState().setTime(1);
+ });
+
+ it('does nothing when not recording', () => {
+ SceneCommands.setField(ROOT, 'Transform', 'position', 'vec3', [9, 9, 0]);
+ expect(keysAt('position.x').map((k) => k.time)).toEqual([0]); // unchanged
+ });
+
+ it('keys mapped scalar channels at the playhead while recording', () => {
+ useSequencerStore.setState({ recording: true });
+ SceneCommands.setField(ROOT, 'Transform', 'position', 'vec3', [42, 24, 0]);
+ // Flush the coalesced burst by toggling recording off.
+ useSequencerStore.setState({ recording: false });
+
+ const x = keysAt('position.x');
+ const y = keysAt('position.y');
+ expect(x.map((k) => k.time)).toEqual([0, 1]);
+ expect(x.find((k) => k.time === 1)?.value).toBe(42);
+ expect(y.find((k) => k.time === 1)?.value).toBe(24);
+ });
+
+ it('ignores edits to a non-bound entity', () => {
+ useSequencerStore.setState({ recording: true });
+ SceneCommands.setField(999 as typeof ROOT, 'Transform', 'position', 'vec3', [1, 2, 0]);
+ useSequencerStore.setState({ recording: false });
+ expect(keysAt('position.x').map((k) => k.time)).toEqual([0]); // unchanged
+ });
+
+ it('coalesces a burst into one undo step', () => {
+ useSequencerStore.setState({ recording: true });
+ SceneCommands.setField(ROOT, 'Transform', 'position', 'vec3', [10, 0, 0]);
+ SceneCommands.setField(ROOT, 'Transform', 'position', 'vec3', [20, 0, 0]);
+ SceneCommands.setField(ROOT, 'Transform', 'position', 'vec3', [30, 0, 0]);
+ useSequencerStore.setState({ recording: false }); // flush → one commit
+
+ expect(keysAt('position.x').find((k) => k.time === 1)?.value).toBe(30);
+ EditorHistory.undo();
+ expect(keysAt('position.x').map((k) => k.time)).toEqual([0]); // single undo reverts the whole burst
+ });
+});
diff --git a/docs/REARCH_ANIMATION.md b/docs/REARCH_ANIMATION.md
new file mode 100644
index 000000000..f6b888e5f
--- /dev/null
+++ b/docs/REARCH_ANIMATION.md
@@ -0,0 +1,159 @@
+# Estella 动画 / Sequencer 重构 —— 反射写入 · 纯 TS 运行时 · 文档即真源(REARCH_ANIMATION)
+
+> 目标读者:引擎维护者 / AI 协作代理。
+> 体例同 `REARCH_SPINE.md` / `REARCH_EDITOR_MODEL.md`:描述**目标架构**与根治路径,而非现状;
+> 现状审计见各小节"病灶"引用的 `file:line`(2026-06 三路并行只读审计 + 交叉印证)。
+> **立项缘由**:设计稿(`design/ue5-animation.html` + `ue5-overview.html#botDock`)里的 **UE Sequencer**
+> 从未被搬进编辑器;而引擎那套 timeline runtime 当年是**临时实现**,用户明确"不够最佳现代就连引擎一起重构"。
+> 本文把"补一个编辑器面板"升级成"把整条动画求值链收口成一套现代化架构"。
+> **决策(用户已定)**:① Timeline 运行时改为**纯 TS**(文档即运行时);② **编辑器优先**交付。
+> **执行纪律**:终态删掉 C++ 临时实现与重复,不为兼容保留旧路径;分阶段只为每步可验证。
+
+---
+
+## 0. 核心诊断
+
+**真正的分界线不是"动画该不该有编辑器",而是"动画求值该不该和引擎已有的权威反射层合流"。**
+
+引擎**已经有**一套引擎权威的"按字段路径读写任意组件"的反射层(序列化 + Inspector 都在用):
+TS 侧 `PTR_LAYOUTS`(组件→字段偏移描述)+ `BuiltinBridge.writePtrField/readPtrField`(按偏移读写 WASM 堆)+
+`COMPONENT_META.animatableFields`(引擎权威的可动画字段表,与下文枚举**同源于** `ES_PROPERTY(animatable)`)。
+
+而 timeline 却**另起炉灶**:把可动画目标硬编码成 `AnimTargetField` 枚举 + 一个 ~40 路 `switch`,并且把运行时切成
+**C++ 求值 / TS 持文档**两半、靠每帧轮询结果缓冲同步。`AnimTargetField::CustomField` 这条"反射兜底"分支本身
+就证明了枚举是多余的——既然兜底能反射,全部都能反射。
+
+**三条事实定调:**
+1. **side-effect 本就大多必须过 JS**:音频=WebAudio 纯 JS(`sdk/src/audio/Audio.ts`)、spine=side-module 经 JS 桥
+ (`sdk/src/spine/ModuleBackend.ts`)、SpriteAnimator=纯 TS(`sdk/src/animation/SpriteAnimator.ts`)。
+ 也就是说 C++ timeline 里**唯一**非 JS 的工作只剩"属性曲线求值"。
+2. **属性求值搬到 TS 几乎零成本**:写入直接走 `writePtrField` 戳 WASM 堆(不经 embind 拷整结构),
+ authored 序列实例数很少,逐帧求值在 JS 完全可忽略;现有自定义属性分支早就在 TS 求值
+ (`TimelineRuntime.ts` `setNestedProperty` + `world.set`)证明可行。
+3. **批量程序化补间另有归宿**:Tween(`src/esengine/animation/TweenSystem.cpp`)是 C++ 批量快路径,
+ 服务"成千上万个简单补间";authored Sequencer 序列是"少量、富功能"——两者尺度不同,不必同核。
+
+**结论:属性求值统一到反射写入层;Timeline 运行时纯 TS 化(文档即运行时);Tween 留 C++ 批量快路径,
+与 Timeline 共用 easing/keyframe/反射写入。** 这样可消掉一整个 codegen 子系统、一套 C++ 系统、poll 缓冲、
+脑裂同步,同时为编辑器换来 **scrub == evaluate-at-T 免费** 的实时预览。
+
+---
+
+## 1. 现状病灶(file:line)
+
+### G1:可动画目标硬编码成枚举 + 大 switch(根因)
+- `src/esengine/animation/animTargets.generated.hpp` —— `enum AnimTargetField`(`TransformPositionX`…)+
+ `applyAnimatedValue()` 一个 ~40 路 `switch`,逐字段直接写结构体成员;末路 `CustomField` 空 case(TS 兜底)。
+- `src/esengine/animation/animTargets.generated.ts` —— `FIELD_MAP: Record<component, Record<path, enum>>` 镜像。
+- 生成器 `tools/eht/generators/anim_target.py` —— **与** `metadata.py`(`COMPONENT_META.animatableFields`)/
+ `ptr_layout.py`(`PTR_LAYOUTS`)**同源**于 `ES_PROPERTY(animatable)`。即:可动画字段已有引擎权威表,枚举是第二套真源。
+- **逐字段语义不可省**:`rotation.z` 欧拉角→四元数 `glm::quat(cos h,0,0,sin h)`、UIRect `anim_override_` 标志等——
+ 重构不是"删 switch",是"把 switch 改成数据驱动的 `path → writer` 反射表",逐字段语义保留为表项。
+
+### G2:每种轨道一个 binding(刚性)
+- `src/esengine/bindings/TimelineBindings.cpp` —— `tl_addPropertyTrack` / `tl_addSpineTrack` / `tl_addAudioTrack` /
+ `tl_addActivationTrack` / `tl_addSpriteAnimTrack` / `tl_addCustomPropertyTrack`,各自手工 float 打包。
+ 每加一种轨道都要动 C++ binding + `TimelineUploader.ts` 分支。
+
+### G3:脑裂 + 每帧轮询结果缓冲
+- C++ 持运行时 timeline(`TimelineSystem.cpp` / `TimelineData.hpp`),TS 持文档(`TimelineTypes.ts`),
+ 靠 `TimelineUploader.ts` re-upload 同步——两份真源。
+- side-effect 走"结果缓冲轮询":`TimelineBindings.cpp` `tl_getEventCount/getEventType/...` +
+ `tl_getCustomPropertyCount/...`,TS 端 `TimelineRuntime.ts` `processTimelineEvents()` / `processCustomProperties()`
+ 每帧循环跨 WASM 边界拉取再 `tl_clearResults()`。(同款 poll 模式 spine 也有,是 WASM 边界产物,非通用范式。)
+
+### G4:没有 scrub 原语、没有创作/序列化
+- `TimelineSystem.cpp:388` `evaluateAt()` 只回**裸通道值不应用**;`advance()`(:362)应用但只能按 dt **前进**——
+ 编辑器拖播放头没有"在任意 T 采样并应用"的干净入口。
+- 全栈**没有任何创作 API**(add/remove track、add/move/setInterp keyframe),**没有序列化器**
+ (`TimelineLoader.ts` 只解析 `.estimeline`,无逆向写盘);`Marker`/`CustomEvent` 是只声明不实现的空桩。
+
+### G5:4 份重复 easing + 两套 keyframe 类型
+- `src/esengine/animation/EasingFunctions.hpp`(全集,仅 Tween 用)、`TimelineSystem.cpp:114-124`(内联重复 3 个)、
+ `src/esengine/particle/ParticleEasing.hpp`(子集)、`sdk/src/camera/CameraDirector.ts` `applyCurve()`(第三套)。
+- TS 侧 `sdk/src/animation/Easing.ts` 已是 C++ 全集的 1:1 端口(可直接当统一 TS 源)。
+- Timeline 有带切线的 `TimelineKeyframe`(最富),Tween 只有隐式 from/to+easing——无统一 `Keyframe`。
+
+### G6:编辑器完全没有动画面板
+- `desktop/src/panels/` 只有 Outliner/Viewport/Details/ContentBrowser/OutputLog/GamePanel;
+ `DockLayout.tsx` 组件表无 sequencer;设计稿底部停靠 tab「动画 Sequencer」缺席。
+
+---
+
+## 2. 目标架构(四层)
+
+每层都**复用**引擎/编辑器已有的权威机制,而非再造。
+
+### L1 —— 统一反射写入层(codegen,C++ + TS 双镜像)
+- 由 `ES_PROPERTY(animatable)` 生成一张**数据驱动写入表** `path → writer`,取代 `AnimTargetField` 枚举 + switch + `FIELD_MAP`。
+ - C++:`ComponentFieldRegistry`(typeId → {name, offset, type, applyFn}),`applyFn` 承载逐字段语义(quat 转换、override 标志)。
+ - TS:复用既有 `PTR_LAYOUTS` + `writePtrField`,特例字段配套 writer(mirror C++ applyFn)。
+- **唯一写入路径**:Tween(C++)、Timeline(TS)、编辑器预览全部经此,与 Inspector/序列化同源。
+- 产出:删 `animTargets.generated.{hpp,ts}` 的枚举/switch/FIELD_MAP,改为生成 registry/表。
+
+### L2 —— 统一 easing / keyframe 数学
+- C++ `SharedEasing.hpp`(由 `EasingFunctions.hpp` 提升)+ TS `Easing.ts`(已存在端口);删 Timeline 内联、Particle 子集、Camera 第三套(改为委托/共享)。
+- 单一 `Keyframe { time, value, interp, inTangent, outTangent }` + `evaluateChannel(channel, t)`;Hermite/Linear/Step/Ease* 各模式集中一处。
+
+### L3 —— Timeline 运行时:纯 TS(文档即运行时)
+- `TimelineEvaluator.sample(doc, t, ctx)`:求值属性通道→走 L1 写入;side-effect(audio/spine/spriteAnim/activation/event)
+ 在 TS 内**边沿检测**(prevT→t)直接调对应 JS 子系统(`audio.playSFX` / `SpineManager.setAnimation` / SpriteAnimator / world.set)。
+- forward play 与 scrub **同一入口**(play = 累加 t 后 sample;scrub = 任意 T 直接 sample)→ scrub 免费。
+- 删 C++ `TimelineSystem`/`TimelineData`、`tl_add*Track`、poll 缓冲;`TimelinePlugin` 改为驱动 TS evaluator。
+- **Tween 留 C++** 批量快路径,apply 改走 L1 的 C++ registry。
+
+### L4 —— 创作层 + Sequencer 面板(编辑器,全新)
+- **资产文档会话**(首个,镜像 `EditorSession`/`SceneModel`/`Reconciler`/`SceneCommands`/`SceneStore`/`SceneQuery`/`EditorHistory`):
+ - `TimelineDocument`(= `.estimeline` JSON,**也就是 L3 的运行时对象**,无独立 upload)。
+ - `TimelineCommands`(addTrack/removeTrack/mute/addKey/moveKey/deleteKey/setValue/setInterp/setDuration/setFps/setWrap),
+ 每步经**同一** `EditorHistory`/`TransactionManager` 可撤销。
+ - 响应式 `TimelineStore` + `TimelineQuery` + `TimelineSerializer`(`TimelineLoader` 的逆)。
+ - 抽成 `AssetDocumentSession<T>` 基类——瓦片集/瓦片地图编辑器后续复用。
+- **`Sequencer.tsx`**:底部停靠 tab(与 Content/Log 并排,`referencePanel:'content', direction:'within'`)+ ActivityBar 入口 +
+ `editorStore` sequencer 态(当前 clip、播放头 time/frame、选中关键帧、录制)。
+ 传输条 / 轨道树(实体→组件→属性)/ 时间轴(标尺·帧网格·可拖播放头·关键帧道)/ 摄影表⇄曲线 / 精灵帧条 / 插值弹窗 / 吸附帧 / 录制(自动打帧)。
+ 复用 Details 的 scrub 手势 + 色板 token;"添加轨道"选择器由 `COMPONENT_META.animatableFields` + 选中实体层级(childPath)驱动。
+- **实时预览**:拖播放头/改关键帧 → 在播放头处 `evaluator.sample` 应用到绑定实体 → 视口即刷(scrub 免费的兑现点)。
+
+### 资产格式说明
+- **`.estimeline`** = 多轨 Sequencer 文档(property/spine/audio/activation/spriteAnim 轨 + Hermite/Linear/Step/Ease*)——本次 Sequencer 的编辑对象。
+- **`.esanim`**(AnimClip 精灵翻页,`AnimClipLoader.ts`)保持独立,作为 Sequencer 底部「精灵帧条」/ SpriteAnim 轨的来源。
+- 设计稿把 clip 写成 `Walk.esanim` 是 mockup 笔误;落地以 `.estimeline` 为 Sequencer 文档格式(沿用 loader version "1.1")。
+
+---
+
+## 3. 分阶段计划(编辑器优先)
+
+> 每阶段可独立验证、可单独提交。P1–P3 让编辑器先跑起来(建在最小新 TS runtime 上),P4 回收 C++ 临时实现,P5 收尾通用化。
+
+- **P1 —— 端到端可见闭环(证明 seam)**
+ L3 最小核(仅属性轨)`TimelineEvaluator.sample` + L4 文档会话骨架 + `TimelineSerializer`(读已有 + 写)。
+ `Sequencer.tsx` 注册进底部停靠 + ActivityBar + store;开 `.estimeline`(Content Browser 双击 / 选中实体的 TimelinePlayer)→ 渲染轨道树 + 关键帧道 + 播放头;
+ 拖播放头 → `sample` 应用到绑定实体 → 视口实时动。**验收:开真实 `.estimeline` → 见轨道 → 拖播放头角色动起来。**
+
+- **P2 —— 编辑 + 撤销 + 存盘**
+ `TimelineCommands`(add/move/delete key、setValue、setInterp)经 `EditorHistory` 手势;关键帧拖拽(时间+值)、插值弹窗、吸附帧;
+ 存盘走 Electron fs(`ProjectStore`);录制态(auto-key:录制中改 Inspector 受跟踪属性 → 在播放头插帧)。**验收:打帧/拖帧/改插值/撤销重做/存盘往返。**
+
+- **P3 —— 轨道创作 + 传输 + 曲线视图**
+ 添加轨道选择器(`COMPONENT_META.animatableFields` + 实体层级 childPath);静音/独奏、duration/fps/wrap 编辑、分组折叠;
+ 曲线视图(hermite/bezier 手柄)+ 摄影表⇄曲线切换;编辑态播放循环(rAF 驱动 sample)+ 上/下关键帧 + loop;精灵帧条(AnimFrames / SpriteAnimator)。
+
+- **P4 —— 回收 C++ 临时实现(引擎重构落地)**
+ side-effect 派发全部并入 TS evaluator(边沿检测)→ 删 C++ `TimelineSystem`/`TimelineData`/`TimelineBindings`(`tl_*`)+ poll 缓冲;
+ 生成 L1 反射写入表(C+++TS)→ 删 `animTargets` 枚举/switch/FIELD_MAP,Tween 的 C++ apply 改走新 registry;合并 easing(4→1)。
+ **预期 `esengine.wasm` 体积下降**(同 spine 重构 -503KB 的量级方向)。**验收:全测试绿 + wasm 重建 + 体积对比。**
+
+- **P5 —— 通用化收尾(可选)**
+ 抽 `AssetDocumentSession<T>` 基类;为 Animator/状态机层(设计稿 `Animator` 组件)预留组合点;瓦片集/瓦片地图编辑器复用同基类。
+
+---
+
+## 4. 风险 / 注记
+- **堆布局特例**:`writePtrField` 写的是 C++ 堆布局,少数字段 JS 形状与堆布局背离(如 Camera `viewport` vec4 vs JS viewportX/Y/W/H)。
+ L1 生成器同时知道偏移与打包,特例配套 writer;不可对所有字段裸 poke。
+- **rotation.z 语义**:JS Transform 用四元数;动画"rotation.z"按欧拉角需转换——L1 writer 表项承担,TS/C++ 两侧对齐。
+- **确定性**:play-realm 本就跑 SDK(TS);TS 定步求值与原 C++ 数值一致即可,无新确定性风险。
+- **P4 之前**:P1–P3 期间 C++ 旧 timeline 与新 TS evaluator **并存**(编辑器走新核,运行时旧核暂留),P4 才删旧核,避免中途破坏现有运行时播放。
+</content>
+</invoke>
diff --git a/sdk/src/timeline/AnimationClip.ts b/sdk/src/timeline/AnimationClip.ts
new file mode 100644
index 000000000..41ea48e4a
--- /dev/null
+++ b/sdk/src/timeline/AnimationClip.ts
@@ -0,0 +1,50 @@
+/**
+ * @file AnimationClip.ts
+ * @brief The unified animation-clip loader — one .esanim document the Sequencer
+ * authors and the Animator state-machine references (docs/REARCH_ANIMATION.md).
+ *
+ * The editor unified two formats into `.esanim`: the rich multi-track model
+ * (property curves + sprite frames + events + …) and the legacy sprite-flipbook
+ * AnimClip (frames + fps). `parseAnimationClip` accepts either — discriminating by
+ * structure, not the `type` string — and returns the one in-memory model
+ * ({@link TimelineAsset}). A flipbook becomes a clip with a single sprite-frame
+ * track, so old `.esanim` files keep working while everything converges on one
+ * format. (The engine's two RUNTIMES merge in P4; this is the format seam.)
+ */
+
+import { parseTimelineAsset } from './TimelineLoader';
+import { WrapMode, TrackType, type TimelineAsset, type AnimFramesTrack } from './TimelineTypes';
+
+/** Convert a legacy flipbook AnimClip (frames + fps) to a single sprite-frame track. */
+function flipbookToClip(raw: any): TimelineAsset {
+ const fps = typeof raw.fps === 'number' && raw.fps > 0 ? raw.fps : 12;
+ const frames = (raw.frames ?? []).map((f: any) => ({
+ texture: f.texture ?? '',
+ duration: f.duration ?? 1 / fps,
+ }));
+ const duration = frames.reduce((sum: number, f: any) => sum + (f.duration ?? 1 / fps), 0);
+ const track: AnimFramesTrack = {
+ type: TrackType.AnimFrames,
+ name: 'Sprite',
+ childPath: '',
+ frames,
+ };
+ return {
+ version: '1.1',
+ type: 'timeline',
+ duration,
+ wrapMode: raw.loop === false ? WrapMode.Once : WrapMode.Loop,
+ tracks: [track],
+ };
+}
+
+/**
+ * Parse any `.esanim` / legacy `.estimeline` document into the unified clip model.
+ * Discriminates by shape: a `tracks` array is the rich multi-track clip; a `frames`
+ * array is the legacy flipbook.
+ */
+export function parseAnimationClip(raw: any): TimelineAsset {
+ if (raw && Array.isArray(raw.tracks)) return parseTimelineAsset(raw);
+ if (raw && Array.isArray(raw.frames)) return flipbookToClip(raw);
+ return parseTimelineAsset(raw ?? {});
+}
diff --git a/sdk/src/timeline/TimelineEvaluator.ts b/sdk/src/timeline/TimelineEvaluator.ts
new file mode 100644
index 000000000..9b5f834f8
--- /dev/null
+++ b/sdk/src/timeline/TimelineEvaluator.ts
@@ -0,0 +1,205 @@
+/**
+ * @file TimelineEvaluator.ts
+ * @brief Pure-TS timeline sampler — evaluate a TimelineAsset at an absolute
+ * time and apply its property tracks to the world.
+ *
+ * The engine's C++ TimelineSystem is a temporary implementation (see
+ * docs/REARCH_ANIMATION.md). This is the modern replacement's kernel: ONE
+ * sample(time) call drives both forward playback (advance the clock, then sample)
+ * and editor scrubbing (sample at any T) — so the editor gets "scrub ==
+ * evaluate-at-T" for free, with no separate evaluate/apply paths.
+ *
+ * The interpolation math is a 1:1 port of TimelineSystem.cpp::evaluateChannel
+ * (hermite/linear/step/ease) so playback and editor preview match the C++ path
+ * numerically, and P4 can delete the C++ runtime with no regression.
+ *
+ * The sampler is dependency-injected (world / component lookup / child resolution)
+ * so it is a pure function: unit-testable without WASM and reusable by both the
+ * runtime and the editor preview bridge.
+ */
+
+import { TrackType, InterpType, WrapMode, type TimelineAsset, type PropertyChannel } from './TimelineTypes';
+import { setNestedProperty, resolveChildEntity } from './TimelineRuntime';
+import { getComponent } from '../component';
+import type { Entity } from '../types';
+
+// ---------------------------------------------------------------------------
+// Core math — 1:1 port of TimelineSystem.cpp (keep in lock-step)
+// ---------------------------------------------------------------------------
+
+function hermite(p0: number, p1: number, m0: number, m1: number, t: number): number {
+ const t2 = t * t;
+ const t3 = t2 * t;
+ const h00 = 2 * t3 - 3 * t2 + 1;
+ const h10 = t3 - 2 * t2 + t;
+ const h01 = -2 * t3 + 3 * t2;
+ const h11 = t3 - t2;
+ return h00 * p0 + h10 * m0 + h01 * p1 + h11 * m1;
+}
+
+function easeIn(t: number): number {
+ return t * t;
+}
+
+function easeOut(t: number): number {
+ return 1 - (1 - t) * (1 - t);
+}
+
+function easeInOut(t: number): number {
+ return t < 0.5 ? 2 * t * t : 1 - 2 * (1 - t) * (1 - t);
+}
+
+/** Evaluate a single property channel at `time` (seconds). Endpoints clamp. */
+export function evaluateChannel(channel: PropertyChannel, time: number): number {
+ const kfs = channel.keyframes;
+ if (!kfs || kfs.length === 0) return 0;
+ if (kfs.length === 1) return kfs[0].value;
+
+ if (time <= kfs[0].time) return kfs[0].value;
+ if (time >= kfs[kfs.length - 1].time) return kfs[kfs.length - 1].value;
+
+ let i = 0;
+ while (i < kfs.length - 1 && kfs[i + 1].time <= time) i++;
+
+ const k0 = kfs[i];
+ const k1 = kfs[i + 1];
+ const dt = k1.time - k0.time;
+ if (dt <= 0) return k0.value;
+
+ const t = (time - k0.time) / dt;
+
+ switch (k0.interpolation) {
+ case InterpType.Linear:
+ return k0.value + (k1.value - k0.value) * t;
+ case InterpType.Step:
+ return k0.value;
+ case InterpType.EaseIn:
+ return k0.value + (k1.value - k0.value) * easeIn(t);
+ case InterpType.EaseOut:
+ return k0.value + (k1.value - k0.value) * easeOut(t);
+ case InterpType.EaseInOut:
+ return k0.value + (k1.value - k0.value) * easeInOut(t);
+ case InterpType.Hermite:
+ default:
+ return hermite(k0.value, k1.value, k0.outTangent * dt, k1.inTangent * dt, t);
+ }
+}
+
+/** Map an absolute time through the clip's wrap mode (for forward playback). */
+export function applyWrapMode(
+ time: number, duration: number, mode: WrapMode,
+): { time: number; stopped: boolean } {
+ if (duration <= 0) return { time: 0, stopped: true };
+ if (time < 0) return { time: 0, stopped: false };
+ if (time < duration) return { time, stopped: false };
+
+ switch (mode) {
+ case WrapMode.Loop:
+ return { time: time % duration, stopped: false };
+ case WrapMode.PingPong: {
+ const cycle = duration * 2;
+ const t = time % cycle;
+ return { time: t <= duration ? t : cycle - t, stopped: false };
+ }
+ case WrapMode.Once:
+ default:
+ return { time: duration, stopped: true };
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Field application — seed of the REARCH_ANIMATION L1 reflection writer table
+// ---------------------------------------------------------------------------
+
+type FieldWriter = (data: any, value: number) => void;
+
+/**
+ * Per-field writers for animatable paths whose JS shape differs from the raw
+ * dot-path (so a generic `setNestedProperty` would corrupt them). This is the
+ * TS seed of L1's generated reflection writer table; for now the only such case
+ * is Transform rotation. Mirrors animTargets.generated.hpp exactly (value is the
+ * full Z angle in radians; the quaternion uses the half-angle) so editor preview
+ * matches the C++ runtime bit-for-bit.
+ */
+const WRITER_OVERRIDES: Record<string, FieldWriter> = {
+ 'Transform.rotation.z': (data, v) => {
+ const h = v * 0.5;
+ data.rotation = { w: Math.cos(h), x: 0, y: 0, z: Math.sin(h) };
+ },
+};
+
+function applyField(data: any, component: string, property: string, value: number): boolean {
+ const override = WRITER_OVERRIDES[`${component}.${property}`];
+ if (override) {
+ override(data, value);
+ return true;
+ }
+ return setNestedProperty(data, property, value);
+}
+
+// ---------------------------------------------------------------------------
+// Sampler
+// ---------------------------------------------------------------------------
+
+/** Minimal world surface the sampler needs (component get/set by definition). */
+export interface SampleWorld {
+ has(entity: Entity, def: any): boolean;
+ get(entity: Entity, def: any): any;
+ set(entity: Entity, def: any, data: any): void;
+}
+
+export interface SampleDeps {
+ world: SampleWorld;
+ getComponent: (name: string) => any;
+ resolveChild: (root: Entity, childPath: string) => Entity | null;
+}
+
+export interface SampleOptions {
+ /** Return true to skip a channel — the editor uses this for muted tracks. */
+ skipChannel?: (childPath: string, component: string, property: string) => boolean;
+}
+
+/**
+ * Evaluate every property track at `time` and write the results to the world.
+ * P1 covers property tracks only; spine/audio/spriteAnim/activation side-effects
+ * land in P3/P4. Each track touches one component on one resolved entity, so it
+ * reads/writes that component once (all channels folded into a single set).
+ */
+export function sampleTimeline(
+ asset: TimelineAsset, time: number, rootEntity: Entity, deps: SampleDeps, opts?: SampleOptions,
+): void {
+ for (const track of asset.tracks) {
+ if (track.type !== TrackType.Property) continue;
+
+ const def = deps.getComponent(track.component);
+ if (!def) continue;
+
+ const entity = deps.resolveChild(rootEntity, track.childPath);
+ if (entity == null || !deps.world.has(entity, def)) continue;
+
+ const data = deps.world.get(entity, def);
+ let changed = false;
+ for (const ch of track.channels) {
+ if (!ch.keyframes || ch.keyframes.length === 0) continue;
+ if (opts?.skipChannel?.(track.childPath, track.component, ch.property)) continue;
+ const v = evaluateChannel(ch, time);
+ if (applyField(data, track.component, ch.property, v)) changed = true;
+ }
+ if (changed) deps.world.set(entity, def, data);
+ }
+}
+
+/**
+ * Convenience wrapper binding the real SDK component registry + child resolver.
+ * The editor preview bridge and the runtime both call this; tests inject mocks
+ * into {@link sampleTimeline} directly.
+ */
+export function sampleTimelineInWorld(
+ asset: TimelineAsset, time: number, world: SampleWorld & any, rootEntity: Entity, opts?: SampleOptions,
+): void {
+ sampleTimeline(asset, time, rootEntity, {
+ world,
+ getComponent,
+ resolveChild: (root, childPath) => resolveChildEntity(world, root, childPath),
+ }, opts);
+}
diff --git a/sdk/src/timeline/TimelineSerializer.ts b/sdk/src/timeline/TimelineSerializer.ts
new file mode 100644
index 000000000..440d35f1d
--- /dev/null
+++ b/sdk/src/timeline/TimelineSerializer.ts
@@ -0,0 +1,76 @@
+/**
+ * @file TimelineSerializer.ts
+ * @brief Serialize an in-memory TimelineAsset back to .estimeline JSON — the
+ * inverse of TimelineLoader.parseTimelineAsset.
+ *
+ * The runtime previously only LOADED timelines; authoring (the Sequencer editor,
+ * docs/REARCH_ANIMATION.md) needs to write them back. Field names and the wrapMode
+ * string encoding mirror the loader exactly so parse(serialize(x)) round-trips —
+ * notably AnimFrames tracks persist under the on-disk key `animFrames` (the loader
+ * reads `raw.animFrames` into the in-memory `frames`).
+ */
+
+import { WrapMode, TrackType, type TimelineAsset, type Track } from './TimelineTypes';
+
+const CURRENT_VERSION = '1.1';
+
+const WRAP_MODE_NAMES: Record<WrapMode, string> = {
+ [WrapMode.Once]: 'once',
+ [WrapMode.Loop]: 'loop',
+ [WrapMode.PingPong]: 'pingPong',
+};
+
+function serializeTrack(track: Track): Record<string, unknown> {
+ const base = { type: track.type, name: track.name, childPath: track.childPath };
+
+ switch (track.type) {
+ case TrackType.Property:
+ return {
+ ...base,
+ component: track.component,
+ channels: track.channels.map(ch => ({
+ property: ch.property,
+ keyframes: ch.keyframes.map(kf => ({
+ time: kf.time,
+ value: kf.value,
+ inTangent: kf.inTangent,
+ outTangent: kf.outTangent,
+ ...(kf.interpolation ? { interpolation: kf.interpolation } : {}),
+ })),
+ })),
+ };
+ case TrackType.Spine:
+ return { ...base, clips: track.clips, blendIn: track.blendIn };
+ case TrackType.SpriteAnim:
+ return { ...base, clip: track.clip, startTime: track.startTime };
+ case TrackType.Audio:
+ return { ...base, events: track.events };
+ case TrackType.Activation:
+ return { ...base, ranges: track.ranges };
+ case TrackType.Marker:
+ return { ...base, markers: track.markers };
+ case TrackType.CustomEvent:
+ return { ...base, events: track.events };
+ case TrackType.AnimFrames:
+ // On-disk key is `animFrames` (matches the loader's read path).
+ return { ...base, animFrames: track.frames };
+ default:
+ return base;
+ }
+}
+
+/** Serialize to a plain JSON-ready object (the `.estimeline` document shape). */
+export function serializeTimelineAsset(asset: TimelineAsset): Record<string, unknown> {
+ return {
+ version: CURRENT_VERSION,
+ type: 'timeline',
+ duration: asset.duration,
+ wrapMode: WRAP_MODE_NAMES[asset.wrapMode] ?? 'once',
+ tracks: asset.tracks.map(serializeTrack),
+ };
+}
+
+/** Serialize to a pretty-printed JSON string for writing to disk. */
+export function serializeTimelineToJson(asset: TimelineAsset, indent = 2): string {
+ return JSON.stringify(serializeTimelineAsset(asset), null, indent);
+}
diff --git a/sdk/src/timeline/index.ts b/sdk/src/timeline/index.ts
index bdeea00b2..b9fad4abc 100644
--- a/sdk/src/timeline/index.ts
+++ b/sdk/src/timeline/index.ts
@@ -51,6 +51,25 @@ export {
setNestedProperty,
} from './TimelineRuntime';
+export {
+ sampleTimeline,
+ sampleTimelineInWorld,
+ evaluateChannel,
+ applyWrapMode,
+ type SampleWorld,
+ type SampleDeps,
+ type SampleOptions,
+} from './TimelineEvaluator';
+
+export {
+ serializeTimelineAsset,
+ serializeTimelineToJson,
+} from './TimelineSerializer';
+
+export {
+ parseAnimationClip,
+} from './AnimationClip';
+
export {
TimelinePlugin,
timelinePlugin,
diff --git a/sdk/src/webAppFactory.ts b/sdk/src/webAppFactory.ts
index c3b972f31..d332ee22f 100644
--- a/sdk/src/webAppFactory.ts
+++ b/sdk/src/webAppFactory.ts
@@ -33,6 +33,15 @@ export { AudioPlugin, audioPlugin } from './audio';
export { ParticlePlugin, particlePlugin } from './particle';
export { PostProcessPlugin, postProcessPlugin } from './postprocess';
export { TimelinePlugin, timelinePlugin, registerTimelineAsset, parseTimelineAsset, Timeline, TimelineApi, TimelinePlayer, type TimelinePlayerData } from './timeline';
+// Authoring + pure-TS evaluation surface for the editor Sequencer (REARCH_ANIMATION).
+export {
+ sampleTimeline, sampleTimelineInWorld, evaluateChannel, applyWrapMode,
+ serializeTimelineAsset, serializeTimelineToJson, resolveChildEntity, parseAnimationClip,
+ TrackType, InterpType, WrapMode,
+ type SampleWorld, type SampleDeps, type SampleOptions,
+ type TimelineAsset, type Track, type PropertyTrack, type PropertyChannel, type Keyframe,
+ type SpriteAnimTrack, type AudioTrack, type ActivationTrack, type SpineTrack, type AnimFramesTrack,
+} from './timeline';
export interface CreateWebAppOptions extends WebAppOptions {
spineProvider?: SpineWasmProvider;
diff --git a/sdk/tests/animation-clip.test.ts b/sdk/tests/animation-clip.test.ts
new file mode 100644
index 000000000..5e4cf2868
--- /dev/null
+++ b/sdk/tests/animation-clip.test.ts
@@ -0,0 +1,36 @@
+import { describe, it, expect } from 'vitest';
+import { parseAnimationClip } from '../src/timeline/AnimationClip';
+import { WrapMode, TrackType } from '../src/timeline/TimelineTypes';
+
+describe('parseAnimationClip (unified .esanim loader)', () => {
+ it('passes a rich multi-track clip straight through', () => {
+ const clip = parseAnimationClip({
+ version: '1.1', type: 'timeline', duration: 3, wrapMode: 'loop',
+ tracks: [{ type: 'property', name: 'M', childPath: '', component: 'Transform', channels: [] }],
+ });
+ expect(clip.duration).toBe(3);
+ expect(clip.wrapMode).toBe(WrapMode.Loop);
+ expect(clip.tracks).toHaveLength(1);
+ expect(clip.tracks[0].type).toBe(TrackType.Property);
+ });
+
+ it('converts a legacy flipbook AnimClip into one sprite-frame track', () => {
+ const clip = parseAnimationClip({
+ version: '1', type: 'animation-clip', fps: 10, loop: true,
+ frames: [{ texture: 'a' }, { texture: 'b' }, { texture: 'c' }],
+ });
+ expect(clip.tracks).toHaveLength(1);
+ const t = clip.tracks[0];
+ expect(t.type).toBe(TrackType.AnimFrames);
+ if (t.type === TrackType.AnimFrames) {
+ expect(t.frames.map((f) => f.texture)).toEqual(['a', 'b', 'c']);
+ }
+ expect(clip.duration).toBeCloseTo(0.3, 5); // 3 frames @ 10fps
+ expect(clip.wrapMode).toBe(WrapMode.Loop);
+ });
+
+ it('honors loop:false as Once', () => {
+ const clip = parseAnimationClip({ type: 'animation-clip', fps: 12, loop: false, frames: [{ texture: 'a' }] });
+ expect(clip.wrapMode).toBe(WrapMode.Once);
+ });
+});
diff --git a/sdk/tests/timeline-evaluator.test.ts b/sdk/tests/timeline-evaluator.test.ts
new file mode 100644
index 000000000..f9b498aef
--- /dev/null
+++ b/sdk/tests/timeline-evaluator.test.ts
@@ -0,0 +1,172 @@
+import { describe, it, expect } from 'vitest';
+import {
+ evaluateChannel,
+ applyWrapMode,
+ sampleTimeline,
+ type SampleDeps,
+} from '../src/timeline/TimelineEvaluator';
+import {
+ WrapMode,
+ TrackType,
+ InterpType,
+ type PropertyChannel,
+ type TimelineAsset,
+} from '../src/timeline/TimelineTypes';
+
+function ch(keyframes: PropertyChannel['keyframes'], property = 'value'): PropertyChannel {
+ return { property, keyframes };
+}
+
+describe('evaluateChannel', () => {
+ it('returns 0 for an empty channel and the lone value for one keyframe', () => {
+ expect(evaluateChannel(ch([]), 1)).toBe(0);
+ expect(evaluateChannel(ch([{ time: 0, value: 7, inTangent: 0, outTangent: 0 }]), 5)).toBe(7);
+ });
+
+ it('clamps to the endpoints outside the keyframe range', () => {
+ const c = ch([
+ { time: 1, value: 10, inTangent: 0, outTangent: 0 },
+ { time: 3, value: 30, inTangent: 0, outTangent: 0 },
+ ]);
+ expect(evaluateChannel(c, 0)).toBe(10);
+ expect(evaluateChannel(c, 5)).toBe(30);
+ });
+
+ it('interpolates linearly', () => {
+ const c = ch([
+ { time: 0, value: 0, inTangent: 0, outTangent: 0, interpolation: InterpType.Linear },
+ { time: 2, value: 100, inTangent: 0, outTangent: 0, interpolation: InterpType.Linear },
+ ]);
+ expect(evaluateChannel(c, 1)).toBeCloseTo(50, 5);
+ });
+
+ it('holds the previous value with Step interpolation', () => {
+ const c = ch([
+ { time: 0, value: 5, inTangent: 0, outTangent: 0, interpolation: InterpType.Step },
+ { time: 2, value: 99, inTangent: 0, outTangent: 0, interpolation: InterpType.Step },
+ ]);
+ expect(evaluateChannel(c, 1.9)).toBe(5);
+ expect(evaluateChannel(c, 2)).toBe(99);
+ });
+
+ it('eases (easeIn = t^2 at the midpoint)', () => {
+ const c = ch([
+ { time: 0, value: 0, inTangent: 0, outTangent: 0, interpolation: InterpType.EaseIn },
+ { time: 1, value: 1, inTangent: 0, outTangent: 0, interpolation: InterpType.EaseIn },
+ ]);
+ expect(evaluateChannel(c, 0.5)).toBeCloseTo(0.25, 5);
+ });
+
+ it('hermite passes through both keyframes', () => {
+ const c = ch([
+ { time: 0, value: 0, inTangent: 1, outTangent: 1, interpolation: InterpType.Hermite },
+ { time: 1, value: 10, inTangent: 1, outTangent: 1, interpolation: InterpType.Hermite },
+ ]);
+ expect(evaluateChannel(c, 0)).toBeCloseTo(0, 5);
+ expect(evaluateChannel(c, 1)).toBeCloseTo(10, 5);
+ });
+});
+
+describe('applyWrapMode', () => {
+ it('Once clamps and stops past the end', () => {
+ expect(applyWrapMode(5, 2, WrapMode.Once)).toEqual({ time: 2, stopped: true });
+ expect(applyWrapMode(1, 2, WrapMode.Once)).toEqual({ time: 1, stopped: false });
+ });
+ it('Loop wraps with fmod', () => {
+ expect(applyWrapMode(5, 2, WrapMode.Loop)).toEqual({ time: 1, stopped: false });
+ });
+ it('PingPong reflects in the second half', () => {
+ expect(applyWrapMode(3, 2, WrapMode.PingPong).time).toBeCloseTo(1, 5);
+ });
+});
+
+// A minimal mock world keyed by a sentinel component "definition" object.
+function mockDeps(store: Map<string, any>, defs: Record<string, object>): SampleDeps {
+ return {
+ world: {
+ has: (_e, def) => store.has((def as any).__name),
+ get: (_e, def) => store.get((def as any).__name),
+ set: (_e, def, data) => store.set((def as any).__name, data),
+ },
+ getComponent: (name) => defs[name],
+ resolveChild: (root, childPath) => (childPath ? null : root),
+ };
+}
+
+describe('sampleTimeline', () => {
+ it('applies a property track to the resolved component', () => {
+ const defs = { Transform: { __name: 'Transform' } };
+ const store = new Map<string, any>([
+ ['Transform', { position: { x: 0, y: 0, z: 0 }, rotation: { w: 1, x: 0, y: 0, z: 0 } }],
+ ]);
+ const asset: TimelineAsset = {
+ version: '1.1',
+ type: 'timeline',
+ duration: 2,
+ wrapMode: WrapMode.Once,
+ tracks: [{
+ type: TrackType.Property,
+ name: 'Move',
+ childPath: '',
+ component: 'Transform',
+ channels: [ch([
+ { time: 0, value: 0, inTangent: 0, outTangent: 0, interpolation: InterpType.Linear },
+ { time: 2, value: 100, inTangent: 0, outTangent: 0, interpolation: InterpType.Linear },
+ ], 'position.x')],
+ }],
+ };
+
+ sampleTimeline(asset, 1, 1 as Entity, mockDeps(store, defs));
+ expect(store.get('Transform').position.x).toBeCloseTo(50, 5);
+ });
+
+ it('skipChannel omits muted channels', () => {
+ const defs = { Transform: { __name: 'Transform' } };
+ const store = new Map<string, any>([
+ ['Transform', { position: { x: 0, y: 0, z: 0 }, rotation: { w: 1, x: 0, y: 0, z: 0 } }],
+ ]);
+ const asset: TimelineAsset = {
+ version: '1.1', type: 'timeline', duration: 2, wrapMode: WrapMode.Once,
+ tracks: [{
+ type: TrackType.Property, name: 'Move', childPath: '', component: 'Transform',
+ channels: [
+ ch([{ time: 0, value: 11, inTangent: 0, outTangent: 0 }], 'position.x'),
+ ch([{ time: 0, value: 22, inTangent: 0, outTangent: 0 }], 'position.y'),
+ ],
+ }],
+ };
+ sampleTimeline(asset, 0, 1 as Entity, mockDeps(store, defs), {
+ skipChannel: (_cp, _comp, prop) => prop === 'position.y',
+ });
+ expect(store.get('Transform').position.x).toBe(11);
+ expect(store.get('Transform').position.y).toBe(0); // muted → untouched
+ });
+
+ it('rotation.z writes a half-angle quaternion (matches the C++ runtime)', () => {
+ const defs = { Transform: { __name: 'Transform' } };
+ const store = new Map<string, any>([
+ ['Transform', { position: { x: 0, y: 0, z: 0 }, rotation: { w: 1, x: 0, y: 0, z: 0 } }],
+ ]);
+ const angle = Math.PI / 2; // 90°
+ const asset: TimelineAsset = {
+ version: '1.1',
+ type: 'timeline',
+ duration: 1,
+ wrapMode: WrapMode.Once,
+ tracks: [{
+ type: TrackType.Property,
+ name: 'Spin',
+ childPath: '',
+ component: 'Transform',
+ channels: [ch([{ time: 0, value: angle, inTangent: 0, outTangent: 0 }], 'rotation.z')],
+ }],
+ };
+
+ sampleTimeline(asset, 0, 1 as Entity, mockDeps(store, defs));
+ const q = store.get('Transform').rotation;
+ expect(q.w).toBeCloseTo(Math.cos(angle / 2), 5);
+ expect(q.z).toBeCloseTo(Math.sin(angle / 2), 5);
+ expect(q.x).toBe(0);
+ expect(q.y).toBe(0);
+ });
+});
diff --git a/sdk/tests/timeline-serializer.test.ts b/sdk/tests/timeline-serializer.test.ts
new file mode 100644
index 000000000..d0537e88f
--- /dev/null
+++ b/sdk/tests/timeline-serializer.test.ts
@@ -0,0 +1,54 @@
+import { describe, it, expect } from 'vitest';
+import { serializeTimelineAsset, serializeTimelineToJson } from '../src/timeline/TimelineSerializer';
+import { parseTimelineAsset } from '../src/timeline/TimelineLoader';
+import { WrapMode, TrackType, InterpType, type TimelineAsset } from '../src/timeline/TimelineTypes';
+
+const ASSET: TimelineAsset = {
+ version: '1.1',
+ type: 'timeline',
+ duration: 5,
+ wrapMode: WrapMode.Loop,
+ tracks: [
+ {
+ type: TrackType.Property,
+ name: 'Move',
+ childPath: 'child1',
+ component: 'Transform',
+ channels: [{
+ property: 'position.x',
+ keyframes: [
+ { time: 0, value: 0, inTangent: 0, outTangent: 0, interpolation: InterpType.Linear },
+ { time: 5, value: 100, inTangent: 0, outTangent: 0 },
+ ],
+ }],
+ },
+ {
+ type: TrackType.Audio,
+ name: 'SFX',
+ childPath: '',
+ events: [{ time: 1, clip: 'a.mp3', volume: 0.8 }],
+ },
+ {
+ type: TrackType.AnimFrames,
+ name: 'Frames',
+ childPath: 'fx',
+ frames: [{ texture: 't0' }, { texture: 't1', duration: 0.1 }],
+ },
+ ],
+};
+
+describe('TimelineSerializer', () => {
+ it('encodes wrapMode as a string and AnimFrames under the on-disk key', () => {
+ const doc = serializeTimelineAsset(ASSET) as any;
+ expect(doc.version).toBe('1.1');
+ expect(doc.wrapMode).toBe('loop');
+ const frames = doc.tracks.find((t: any) => t.type === 'animFrames');
+ expect(frames.animFrames).toHaveLength(2);
+ expect(frames.frames).toBeUndefined();
+ });
+
+ it('round-trips through the loader (parse ∘ serialize == identity)', () => {
+ const roundTripped = parseTimelineAsset(JSON.parse(serializeTimelineToJson(ASSET)));
+ expect(roundTripped).toEqual(ASSET);
+ });
+});