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.

fix(editor): a timeline previews the thing that plays it, instead of nothing

yhh585ee4bec31a
diff --git a/desktop/src/i18n/messages/sequencer.ts b/desktop/src/i18n/messages/sequencer.ts
index 96084fd39..201df1433 100644
--- a/desktop/src/i18n/messages/sequencer.ts
+++ b/desktop/src/i18n/messages/sequencer.ts
@@ -29,8 +29,12 @@ export const sequencerMessages = defineMessages({
// — transport bar —
'seq.unnamed': { en: 'Unnamed', zh: '未命名' },
'seq.metaSummary': { en: '· {frames} frames · {fps}fps · {wrap}', zh: '· {frames} 帧 · {fps}fps · {wrap}' },
- 'seq.bindTitle': { en: 'Bind preview to the selected entity', zh: '将预览绑定到所选实体' },
+ 'seq.bindTitle': {
+ en: 'Preview against the entity that plays this timeline (or the selected one)',
+ zh: '预览绑定到播放这条时间轴的实体(否则用所选实体)',
+ },
'seq.unbound': { en: 'Unbound', zh: '未绑定' },
+ 'seq.instances': { en: '{count} entities play this — previewing one', zh: '有 {count} 个实体在播它——预览其中一个' },
'seq.recordTitle': { en: 'Record: property edits auto-key', zh: '录制:编辑属性时自动打关键帧' },
'seq.jumpStart': { en: 'Jump to start', zh: '跳到开头' },
'seq.prevKeyframe': { en: 'Previous keyframe', zh: '上一个关键帧' },
@@ -99,6 +103,10 @@ export const sequencerMessages = defineMessages({
en: 'Animation has no file (sample clips cannot be saved)',
zh: '动画没有对应的文件(示例剪辑无法保存)',
},
+ 'seq.toast.unbound': {
+ en: '{name} has nothing to preview against: no entity in this document plays it, and nothing is selected. Select the entity to animate, then press the link button.',
+ zh: '{name} 没有可预览的对象:这个文档里没有实体在播它,也没有选中任何实体。选中要动的实体,再点链接按钮。',
+ },
'seq.toast.saved': { en: 'Animation saved', zh: '动画已保存' },
'seq.toast.saveFailed': { en: 'Failed to save: {error}', zh: '保存失败:{error}' },
});
diff --git a/desktop/src/panels/Sequencer.tsx b/desktop/src/panels/Sequencer.tsx
index 99cb09a71..328ca26e5 100644
--- a/desktop/src/panels/Sequencer.tsx
+++ b/desktop/src/panels/Sequencer.tsx
@@ -20,6 +20,7 @@ import { evaluateChannel, InterpType, WrapMode } from 'esengine';
import { t } from '@/i18n';
import { animatableFieldsFor } from '@/engine/schema';
import { TimelineDocument } from '@/timeline/TimelineDocument';
+import { previewRootFor, playerCountFor } from '@/timeline/previewRoot';
import { createAnimationClip } from '@/timeline/openClip';
import { TimelineCommands } from '@/timeline/TimelineCommands';
import { buildTimelineComponents, makeTimelineWrite } from '@/timeline/timelineInspectorModel';
@@ -163,6 +164,9 @@ function SequencerBody() {
const root = TimelineDocument.rootEntity;
const rootName = root != null ? (SceneModel.entityBySource(root)?.name || `#${root}`) : null;
+ // A scene can hold several instances of one effect (the pack's twinkle is in four
+ // panels); the preview animates ONE, so say which count it picked from.
+ const players = playerCountFor(TimelineDocument.filePath);
const tlRef = useRef<HTMLDivElement>(null);
@@ -390,10 +394,11 @@ function SequencerBody() {
type="button"
className={`seq-btn seq-btn--text${rootName ? ' on' : ''}`}
title={t('seq.bindTitle')}
- onClick={() => TimelineDocument.setRootEntity(useSelection.getState().selectedId)}
+ onClick={() => TimelineDocument.setRootEntity(previewRootFor(TimelineDocument.filePath))}
>
<Link2 size={13} /><span>{rootName ?? t('seq.unbound')}</span>
</button>
+ {players > 1 && <span className="seq-meta__dim">{t('seq.instances', { count: players })}</span>}
<span className="seq-div" />
<button
type="button"
diff --git a/desktop/src/timeline/openClip.ts b/desktop/src/timeline/openClip.ts
index 24bff683b..d61010ab7 100644
--- a/desktop/src/timeline/openClip.ts
+++ b/desktop/src/timeline/openClip.ts
@@ -13,8 +13,8 @@
import { parseAnimationClip } from 'esengine';
import { t } from '@/i18n';
import { TimelineDocument } from './TimelineDocument';
+import { previewRootFor } from './previewRoot';
import { useSequencerStore } from '@/store/sequencerStore';
-import { useSelection } from '@/store/selectionStore';
import { dockApi } from '@/layout/dockApi';
import { Toasts } from '@/store/Toasts';
import { ProjectStore } from '@/project/ProjectStore';
@@ -25,7 +25,7 @@ export async function openAnimationClip(path: string): Promise<void> {
// Already-open file: front the Sequencer and rebind the preview root — a
// reload would clobber unsaved edits.
if (TimelineDocument.isOpen && TimelineDocument.filePath === path) {
- TimelineDocument.setRootEntity(useSelection.getState().selectedId);
+ TimelineDocument.setRootEntity(previewRootFor(path));
dockApi.revealAndExpand('sequencer');
return;
}
@@ -33,11 +33,16 @@ 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;
+ // Bind the preview to the entity that PLAYS this clip (else the selection) so
+ // scrubbing animates something: opened from the Content Browser the selection is
+ // an asset, and binding to that bound to nothing at all.
+ const rootEntity = previewRootFor(path);
TimelineDocument.open({ asset, filePath: path, rootEntity });
useSequencerStore.getState().resetForClip();
dockApi.revealAndExpand('sequencer');
+ if (rootEntity == null) {
+ Toasts.push(t('seq.toast.unbound', { name: baseName(path) }), 'info', 5000);
+ }
} catch (e) {
Toasts.push(t('seq.toast.openFailed', { error: String(e) }), 'error');
}
diff --git a/desktop/src/timeline/previewRoot.ts b/desktop/src/timeline/previewRoot.ts
new file mode 100644
index 000000000..d9927c394
--- /dev/null
+++ b/desktop/src/timeline/previewRoot.ts
@@ -0,0 +1,39 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file previewRoot.ts
+ * @brief The one door for "which entity should the Sequencer preview against" —
+ * the open document + selection, resolved through {@link resolveTimelineRoot}.
+ *
+ * Kept apart from the pure resolver so the rule stays unit-testable while this side
+ * owns the wiring: the model, the selection store, and the asset registry that turns
+ * the open file path into the `@uuid:` ref a `TimelinePlayer` actually stores.
+ */
+
+import { SceneModel } from '@/engine/SceneModel';
+import { useSelection } from '@/store/selectionStore';
+import { ProjectStore } from '@/project/ProjectStore';
+import { resolveTimelineRoot, timelinePlayersFor, type TimelineRootEntity } from './timelineRoot';
+
+/** Matches the refs that name this project-relative asset path: a `TimelinePlayer`
+ * may hold the `@uuid:` form (what the editor writes) or the path itself. */
+function refMatcher(filePath: string | null): (ref: string) => boolean {
+ if (!filePath) return () => false;
+ const uuidRef = ProjectStore.assetRef(filePath);
+ return (ref) => ref === filePath || (!!uuidRef && ref === uuidRef);
+}
+
+function modelEntities(): TimelineRootEntity[] {
+ return (SceneModel.current?.entities ?? []) as unknown as TimelineRootEntity[];
+}
+
+/** The preview root for the timeline at `filePath`, given the current selection. */
+export function previewRootFor(filePath: string | null): number | null {
+ return resolveTimelineRoot(modelEntities(), useSelection.getState().selectedId ?? null, refMatcher(filePath));
+}
+
+/** How many entities in the open document play this timeline (the Sequencer says so
+ * when there is more than one, since the preview shows exactly one of them). */
+export function playerCountFor(filePath: string | null): number {
+ return timelinePlayersFor(modelEntities(), refMatcher(filePath)).length;
+}
diff --git a/desktop/src/timeline/timelineRoot.ts b/desktop/src/timeline/timelineRoot.ts
new file mode 100644
index 000000000..76b7f45d4
--- /dev/null
+++ b/desktop/src/timeline/timelineRoot.ts
@@ -0,0 +1,75 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file timelineRoot.ts
+ * @brief Which entity a timeline previews against — derived from the document
+ * rather than asked for.
+ *
+ * A timeline's tracks address their targets by child path, so the preview needs the
+ * ROOT of the subtree the clip animates. That root is not a mystery: it is the entity
+ * whose `TimelinePlayer` plays this very asset. Binding to "whatever was selected when
+ * you opened the file" instead meant that opening a clip from the Content Browser —
+ * where the selection is an asset, not an entity — bound to nothing, and playing the
+ * Sequencer then animated nothing at all, silently.
+ *
+ * The selection still wins when it is a player for this asset (or sits inside one), so
+ * picking one of several instances previews that one; and an unbound selection is still
+ * the answer when authoring a fresh clip onto a chosen entity, which is what the
+ * recorder needs.
+ *
+ * Pure over the model's entity list — no store, no World.
+ */
+
+/** The entity shape this reads: identity, parent link, and component data. */
+export interface TimelineRootEntity {
+ id: number;
+ parent?: number | null;
+ components: readonly { type: string; data?: Record<string, unknown> }[];
+}
+
+const PLAYER = 'TimelinePlayer';
+
+/** Whether this entity plays the asset `matches` accepts. */
+function playsAsset(e: TimelineRootEntity, matches: (ref: string) => boolean): boolean {
+ const player = e.components.find((c) => c.type === PLAYER);
+ const ref = player?.data?.timeline;
+ return typeof ref === 'string' && ref !== '' && matches(ref);
+}
+
+/**
+ * The preview root for the open timeline, in order of preference:
+ * 1. the selection, or its nearest ancestor, that plays this asset — so selecting a
+ * node inside an effect previews the effect, not the node;
+ * 2. the only entity in the document that plays it (any of them, in document order,
+ * when a scene holds several instances);
+ * 3. the raw selection — authoring a new clip onto the entity you picked;
+ * 4. null, when there is nothing to preview against.
+ */
+export function resolveTimelineRoot(
+ entities: readonly TimelineRootEntity[],
+ selectedId: number | null,
+ matches: (ref: string) => boolean,
+): number | null {
+ const byId = new Map(entities.map((e) => [e.id, e]));
+
+ for (let cur = selectedId; cur != null; ) {
+ const e = byId.get(cur);
+ if (!e) break;
+ if (playsAsset(e, matches)) return e.id;
+ cur = e.parent ?? null;
+ }
+
+ const player = entities.find((e) => playsAsset(e, matches));
+ if (player) return player.id;
+
+ return selectedId ?? null;
+}
+
+/** Every entity that plays the asset — for telling the user a scene holds more than
+ * one instance of the effect they are editing. */
+export function timelinePlayersFor(
+ entities: readonly TimelineRootEntity[],
+ matches: (ref: string) => boolean,
+): number[] {
+ return entities.filter((e) => playsAsset(e, matches)).map((e) => e.id);
+}
diff --git a/desktop/tests/timeline-root.test.ts b/desktop/tests/timeline-root.test.ts
new file mode 100644
index 000000000..f519b8d5e
--- /dev/null
+++ b/desktop/tests/timeline-root.test.ts
@@ -0,0 +1,70 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file Which entity a timeline previews against (timeline/timelineRoot.ts).
+ * The Sequencer used to bind to "whatever was selected when you opened the
+ * file", so opening a clip from the Content Browser — where the selection is an
+ * asset — bound to nothing and playing animated nothing, silently. The root is
+ * derivable: it is the entity whose TimelinePlayer plays this asset.
+ */
+import { describe, it, expect } from 'vitest';
+import { resolveTimelineRoot, timelinePlayersFor, type TimelineRootEntity } from '@/timeline/timelineRoot';
+
+const REF = '@uuid:11111111-2222-3333-4444-555555555555';
+const PATH = 'assets/timelines/fx-twinkle.estimeline';
+const matches = (ref: string): boolean => ref === REF || ref === PATH;
+
+/** An effect instance: a player root with two children, plus an unrelated entity. */
+function scene(): TimelineRootEntity[] {
+ return [
+ { id: 1, parent: null, components: [{ type: 'Transform', data: {} }] },
+ { id: 2, parent: 1, components: [{ type: 'UINode', data: {} }, { type: 'TimelinePlayer', data: { timeline: REF } }] },
+ { id: 3, parent: 2, components: [{ type: 'UIVisual', data: {} }] },
+ { id: 4, parent: 2, components: [{ type: 'UIVisual', data: {} }] },
+ { id: 5, parent: 1, components: [{ type: 'Text', data: {} }] },
+ ];
+}
+
+describe('resolveTimelineRoot', () => {
+ it('finds the player when nothing is selected — the Content Browser case', () => {
+ expect(resolveTimelineRoot(scene(), null, matches)).toBe(2);
+ });
+
+ it('climbs from a node INSIDE the effect to the player, not the node', () => {
+ expect(resolveTimelineRoot(scene(), 3, matches)).toBe(2);
+ });
+
+ it('keeps the selected player when several instances exist', () => {
+ const two = [
+ ...scene(),
+ { id: 6, parent: 1, components: [{ type: 'TimelinePlayer', data: { timeline: REF } }] },
+ { id: 7, parent: 6, components: [{ type: 'UIVisual', data: {} }] },
+ ];
+ expect(resolveTimelineRoot(two, 7, matches)).toBe(6);
+ expect(resolveTimelineRoot(two, null, matches)).toBe(2); // document order
+ expect(timelinePlayersFor(two, matches)).toEqual([2, 6]);
+ });
+
+ it('matches the path form as well as the uuid ref', () => {
+ const byPath = scene().map((e) =>
+ e.id === 2 ? { ...e, components: [{ type: 'TimelinePlayer', data: { timeline: PATH } }] } : e);
+ expect(resolveTimelineRoot(byPath, null, matches)).toBe(2);
+ });
+
+ it('falls back to the raw selection — authoring a fresh clip onto a chosen entity', () => {
+ const noPlayers = scene().filter((e) => e.id !== 2);
+ expect(resolveTimelineRoot(noPlayers, 5, matches)).toBe(5);
+ });
+
+ it('answers null when there is nothing to preview against', () => {
+ const noPlayers = scene().filter((e) => e.id !== 2);
+ expect(resolveTimelineRoot(noPlayers, null, matches)).toBeNull();
+ expect(timelinePlayersFor(noPlayers, matches)).toEqual([]);
+ });
+
+ it('ignores a player bound to a different timeline', () => {
+ const other = scene().map((e) =>
+ e.id === 2 ? { ...e, components: [{ type: 'TimelinePlayer', data: { timeline: '@uuid:other' } }] } : e);
+ expect(resolveTimelineRoot(other, null, matches)).toBeNull();
+ });
+});
diff --git a/docs/astro/src/content/docs/guides/timeline.mdx b/docs/astro/src/content/docs/guides/timeline.mdx
index 7731c16ea..7e0fc1ccd 100644
--- a/docs/astro/src/content/docs/guides/timeline.mdx
+++ b/docs/astro/src/content/docs/guides/timeline.mdx
@@ -113,6 +113,22 @@ curves and their tangent handles for eases the dope sheet can't express:
*The curve editor: each keyframed channel becomes an editable curve (here `position.x` easing in, `position.y` bobbing), with per-key tangent handles.*
+### What the preview animates
+
+Scrubbing or playing in the Sequencer animates the **live viewport**, not a separate
+preview window — the sampled pose is written to the open document and restored the
+moment you unbind, close, or enter Play, so it can never leak into the saved scene.
+
+It animates one entity: the **preview root**, named on the link button in the
+Sequencer's header. That root is derived, not asked for — it is the entity whose
+`TimelinePlayer` plays this timeline, so double-clicking a clip in the Content Browser
+binds to the thing that plays it. Selecting a node *inside* an effect still previews
+the whole effect (the root is found by walking up), and when several entities play the
+same timeline the header says so and previews the selected one. With no player anywhere
+and nothing selected there is nothing to animate: the button reads **Unbound**, and the
+link button binds it to your selection — which is how you author a new clip onto an
+entity that does not play it yet.
+
## Timelines from code
An `.estimeline` document is plain data — the `TimelineAsset` type plus the
diff --git a/docs/astro/src/content/docs/zh-cn/guides/timeline.mdx b/docs/astro/src/content/docs/zh-cn/guides/timeline.mdx
index 9affbde65..1d18709e8 100644
--- a/docs/astro/src/content/docs/zh-cn/guides/timeline.mdx
+++ b/docs/astro/src/content/docs/zh-cn/guides/timeline.mdx
@@ -107,6 +107,17 @@ const control = defineSystem([Query(TimelinePlayer), Res(Timeline)], (q, timelin
*曲线编辑器:每个关键帧通道变成一条可编辑曲线(这里 `position.x` 缓入、`position.y` 起伏),每个关键帧带切线手柄。*
+### 预览动的是什么
+
+在 Sequencer 里拖播放头或按播放,动的是**活的视口**,不是另开一个预览窗——采样出的姿态写进当前
+打开的文档,一旦解绑、关闭或进入 Play 就立刻还原,所以它永远不会漏进存下来的场景。
+
+它只动一个实体:**预览根**,名字就写在 Sequencer 头部那个链接按钮上。这个根是**推导出来的、不用你
+指定**——谁的 `TimelinePlayer` 在播这条时间轴,它就是根,所以从内容浏览器双击一个 clip 就会绑到真正
+播它的那个东西上。选中特效**内部**的某个节点也照样预览整个特效(会往上找根);同一条时间轴被多个实体
+播时,头部会写明有几个、预览的是所选那个。要是哪儿都没有播它的实体、又没选中任何东西,那就没什么可动
+的:按钮显示 **未绑定**,点它会绑到你当前的选择——这正是给一个还没播它的实体新建 clip 的做法。
+
## 用代码构建时间轴
`.estimeline` 文档就是普通数据——用 `TimelineAsset` 类型加上 `TrackType` /