A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
feat(editor): live particle preview in edit mode
yhh53f3e3c0cceb
diff --git a/desktop/src/commands/editorCommands.ts b/desktop/src/commands/editorCommands.tsindex 9111f5ca3..c64f6aea8 100644--- a/desktop/src/commands/editorCommands.ts+++ b/desktop/src/commands/editorCommands.ts@@ -16,6 +16,7 @@ import { SceneCommands } from '@/engine/SceneCommands';import { SceneModel } from '@/engine/SceneModel';import { hasEntityClipboard } from '@/engine/entityClipboard';import { ViewportController } from '@/engine/ViewportController';+import { applyFxPreview } from '@/engine/fxPreview';import { createTilemapFromTileset } from '@/tilemap/createTilemap';import { dockApi } from '@/layout/dockApi';import { EDITOR_MODES } from '@/mode/editorModes';@@ -305,6 +306,16 @@ commands.register({isChecked: () => editor().showGizmos,run: () => editor().toggleGizmos(),});+commands.register({+ id: 'view.togglePreviewFx',+ label: 'Preview FX',+ category: 'View',+ isChecked: () => editor().previewFx,+ run: () => {+ editor().togglePreviewFx();+ applyFxPreview(editor().previewFx);+ },+});commands.register({id: 'view.toggleColliders',label: 'Show Colliders',diff --git a/desktop/src/engine/fxPreview.ts b/desktop/src/engine/fxPreview.tsnew file mode 100644index 000000000..ffe17ba31--- /dev/null+++ b/desktop/src/engine/fxPreview.ts@@ -0,0 +1,27 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file fxPreview.ts+ * @brief Applies the editor's FX-preview toggle to the live engine: flips the+ * SDK's edit-preview flag (which unfreezes the particle sim in edit+ * mode) and restarts every emitter so both edges are clean — enabling+ * replays from t=0, disabling clears residue instead of freezing+ * particles mid-air.+ */+import { setParticleEditPreview, Particle, ParticleEmitter } from 'esengine';+import { EngineHost } from './EngineHost';++export function applyFxPreview(enabled: boolean): void {+ setParticleEditPreview(enabled);+ const world = EngineHost.world;+ const particle = EngineHost.getResource(Particle);+ if (!world || !particle) return;+ for (const e of world.getEntitiesWithComponents([ParticleEmitter])) {+ particle.reset(e);+ // reset() lowers the playing flag and the lazy first-update auto-play+ // was already consumed, so a playOnStart emitter is re-kicked by hand.+ if (enabled && (world.get(e, ParticleEmitter) as { playOnStart?: boolean }).playOnStart) {+ particle.play(e);+ }+ }+}diff --git a/desktop/src/engine/schema.ts b/desktop/src/engine/schema.tsindex 3dc8b4c3d..2081df323 100644--- a/desktop/src/engine/schema.ts+++ b/desktop/src/engine/schema.ts@@ -26,7 +26,7 @@ export type WorldT = App['world'];*/export type ReadonlyWorldT = Pick<WorldT,- 'valid' | 'has' | 'get' | 'getAllEntities' | 'entityCount' | 'getWorldVersion'+ 'valid' | 'has' | 'get' | 'getAllEntities' | 'getEntitiesWithComponents' | 'entityCount' | 'getWorldVersion'>;export type AnyComp = Parameters<WorldT['has']>[1];diff --git a/desktop/src/layout/MenuBar.tsx b/desktop/src/layout/MenuBar.tsxindex a6954d878..3c7e163a4 100644--- a/desktop/src/layout/MenuBar.tsx+++ b/desktop/src/layout/MenuBar.tsx@@ -130,6 +130,7 @@ export function MenuBar() {cmdItem('view.toggleGrid'),cmdItem('view.toggleGizmos'),cmdItem('view.toggleColliders'),+ cmdItem('view.togglePreviewFx'),{ sep: true },cmdItem('view.toggleCoordSpace'),cmdItem('view.togglePivotMode'),diff --git a/desktop/src/layout/Toolbar.tsx b/desktop/src/layout/Toolbar.tsxindex ab02372b5..78487defd 100644--- a/desktop/src/layout/Toolbar.tsx+++ b/desktop/src/layout/Toolbar.tsx@@ -11,6 +11,7 @@ import {Scale3d,Magnet,Grid3x3,+ Sparkles,Play,Pause,Square as Stop,@@ -69,7 +70,7 @@ export function Toolbar() {const playPlayers = useEditorStore((s) => s.playPlayers);const setPlayPlayers = useEditorStore((s) => s.setPlayPlayers);const [modeMenu, setModeMenu] = useState<{ x: number; y: number } | null>(null);- const { tool, snapping, showGrid, showGizmos, isPlaying, isPaused, togglePause, stop } =+ const { tool, snapping, showGrid, showGizmos, previewFx, isPlaying, isPaused, togglePause, stop } =useEditorStore();// Re-render on history changes to refresh undo/redo enabled state + labels.@@ -123,6 +124,7 @@ export function Toolbar() {<div className="tgroup"><TBtn icon={Magnet} label="Snapping" active={snapping} onClick={() => commands.run('view.toggleSnapping')} /><TBtn icon={Grid3x3} label="Show Grid" active={showGrid} onClick={() => commands.run('view.toggleGrid')} />+ <TBtn icon={Sparkles} label="Preview FX" active={previewFx} onClick={() => commands.run('view.togglePreviewFx')} /></div><span className="tspacer" />diff --git a/desktop/src/main.tsx b/desktop/src/main.tsxindex 42954a3b5..7e1718e54 100644--- a/desktop/src/main.tsx+++ b/desktop/src/main.tsx@@ -42,7 +42,9 @@ import { dockApi } from './layout/dockApi';import { EditorControlSurface } from './engine/EditorSession';import { SceneModel } from './engine/SceneModel';import { EngineHost } from './engine/EngineHost';-import { UINode, UIVisual } from 'esengine';+import { UINode, UIVisual, Particle } from 'esengine';+import { applyFxPreview } from './engine/fxPreview';+import { commands } from './commands/registry';import { ViewportController } from './engine/ViewportController';import { PerfMonitor } from './engine/PerfMonitor';import { LogStore } from './store/LogStore';@@ -62,6 +64,10 @@ initFsWatch();initBackgroundThrottle();+// Sync the FX-preview default into the engine flag before anything boots (the+// flag is module-scoped; emitters auto-play lazily once a scene loads).+applyFxPreview(useEditorStore.getState().previewFx);+// Automation hook (screenshots / visual-regression): with `?automation=1`, expose the// minimum to drive the launcher→editor flow from a headless driver. Gated so the normal// editor never carries it; mirrors the headless render host's `window.__estellaHeadless`.@@ -75,6 +81,18 @@ if (new URLSearchParams(location.search).has('automation')) {playState: () => PlayRealm.getSnapshot(),/** Player count for the next Play (1 = single, 2-4 = listen server + clients). */setPlayPlayers: (n: number) => useEditorStore.getState().setPlayPlayers(n),+ /** Advance the EDIT-realm engine n frames (headless drivers: rAF may stall). */+ tickEngine: async (n: number, dt = 1 / 60) => {+ for (let i = 0; i < n; i++) await EngineHost.tick(dt);+ },+ /** Live particle count of a SOURCE entity's emitter (edit-preview probes). */+ particleAlive: (id: number) => {+ const rt = SceneModel.runtimeFor(id);+ const particle = EngineHost.getResource(Particle);+ return rt != null && particle ? particle.getAliveCount(rt) : -1;+ },+ /** Dispatch any registered editor command by id (the UI's own channel). */+ runCommand: (id: string) => commands.run(id),reveal: (id: string) => dockApi.revealAndExpand(id),togglePerfOverlay: () => PerfMonitor.toggleOverlay(),captureThumbnail: () => ProjectStore.captureThumbnail(),diff --git a/desktop/src/panels/Viewport.tsx b/desktop/src/panels/Viewport.tsxindex 3b56e9316..be8a96a7e 100644--- a/desktop/src/panels/Viewport.tsx+++ b/desktop/src/panels/Viewport.tsx@@ -504,6 +504,7 @@ export function Viewport() {const showGrid = useEditorStore((s) => s.showGrid);const showGizmos = useEditorStore((s) => s.showGizmos);const showColliders = useEditorStore((s) => s.showColliders);+ const previewFx = useEditorStore((s) => s.previewFx);const activeGizmoAxis = useEditorStore((s) => s.activeGizmoAxis);const coordSpace = useEditorStore((s) => s.coordSpace);const pivotMode = useEditorStore((s) => s.pivotMode);@@ -1300,6 +1301,7 @@ export function Viewport() {<DdCheck on={showGrid} label="Grid" onClick={() => commands.run('view.toggleGrid')} /><DdCheck on={showGizmos} label="Gizmos" onClick={() => commands.run('view.toggleGizmos')} /><DdCheck on={showColliders} label="Colliders" onClick={() => commands.run('view.toggleColliders')} />+ <DdCheck on={previewFx} label="Preview FX" onClick={() => commands.run('view.togglePreviewFx')} /><DdCheck on={perfVisible} label="Perf" onClick={() => PerfMonitor.toggleOverlay()} /></OvDropdown><span className="ov-divider" />diff --git a/desktop/src/store/editorStore.ts b/desktop/src/store/editorStore.tsindex 2bfafcd14..95d9c68aa 100644--- a/desktop/src/store/editorStore.ts+++ b/desktop/src/store/editorStore.ts@@ -41,6 +41,8 @@ interface EditorState {showGizmos: boolean;/** Draw collider outlines in the viewport (off declutters a physics-heavy scene). */showColliders: boolean;+ /** Simulate particle emitters live in edit mode (authoring preview). */+ previewFx: boolean;snapping: boolean;// Grid-snap increment (world units) applied to Move while `snapping` is on. The// viewport snap dropdown picks from a fixed set (16 / 32 / 64); "off" flips@@ -64,6 +66,7 @@ interface EditorState {toggleGrid: () => void;toggleGizmos: () => void;toggleColliders: () => void;+ togglePreviewFx: () => void;toggleSnapping: () => void;setSnapStep: (step: number) => void;setSnapAngle: (deg: number) => void;@@ -125,6 +128,7 @@ export const useEditorStore = create<EditorState>((set) => ({showGrid: true,showGizmos: true,showColliders: true,+ previewFx: true,snapping: false,snapStep: 32,snapAngle: 15,@@ -138,6 +142,7 @@ export const useEditorStore = create<EditorState>((set) => ({toggleGrid: () => set((s) => ({ showGrid: !s.showGrid })),toggleGizmos: () => set((s) => ({ showGizmos: !s.showGizmos })),toggleColliders: () => set((s) => ({ showColliders: !s.showColliders })),+ togglePreviewFx: () => set((s) => ({ previewFx: !s.previewFx })),toggleSnapping: () => set((s) => ({ snapping: !s.snapping })),setSnapStep: (snapStep) => set({ snapStep, snapping: true }),setSnapAngle: (snapAngle) => set({ snapAngle }),diff --git a/docs/astro/src/content/docs/guides/particle.mdx b/docs/astro/src/content/docs/guides/particle.mdxindex ca0e292ac..770a52bdf 100644--- a/docs/astro/src/content/docs/guides/particle.mdx+++ b/docs/astro/src/content/docs/guides/particle.mdx@@ -32,7 +32,9 @@ curve by default, or a full **gradient/curve** for precise control (see below).<Aside type="note">Particle simulation is **gameplay**: it advances in play mode and in thestandalone runtime, and is frozen in the editor's edit mode (like physics,- animation, and timelines). Enter Play to preview an effect.+ animation, and timelines) — with one authoring exception: the editor's+ **Preview FX** toggle (toolbar ✨, on by default) simulates emitters live+ while you tune them, no Play needed. Re-toggling it replays from t=0.</Aside>## Setup@@ -295,7 +297,8 @@ const control = defineSystem([Res(Particle)], (particles) => {- **Atlas particle textures** and share one `material` so emitters batch.- **Spread min/max** for natural variety; equal min/max reads as mechanical.- **Reuse emitters** via `reset` + `play` instead of spawning/despawning.-- Remember particles only advance in **play mode** — preview in Play.+- In game code particles advance in **play mode**; in the editor the **Preview+ FX** toggle keeps them live while you author.## See alsodiff --git a/docs/astro/src/content/docs/zh-cn/guides/particle.mdx b/docs/astro/src/content/docs/zh-cn/guides/particle.mdxindex 229838947..9787298aa 100644--- a/docs/astro/src/content/docs/zh-cn/guides/particle.mdx+++ b/docs/astro/src/content/docs/zh-cn/guides/particle.mdx@@ -27,7 +27,8 @@ CPU 模拟粒子,并按发射器**GPU 实例化**为单次 draw call 渲染,所<Aside type="note">粒子模拟属于**玩法**:它在播放模式和独立运行时里推进,在编辑器编辑模式下冻结(与物理、- 动画、时间轴一致)。进入 Play 预览特效。+ 动画、时间轴一致)——唯一的创作例外是编辑器的 **Preview FX** 开关(工具栏 ✨,默认开):+ 调参的同时发射器实时模拟,不用进 Play。重新切换 = 从 t=0 重播。</Aside>## 安装@@ -281,7 +282,7 @@ const control = defineSystem([Res(Particle)], (particles) => {- **把粒子贴图打成图集**并共享一个 `material`,让发射器合批。- **拉开 min/max** 得到自然的变化;min/max 相等看起来很机械。- **复用发射器**:用 `reset` + `play` 而不是生成/销毁。-- 记住粒子只在**播放模式**推进——在 Play 里预览。+- 游戏代码里粒子在**播放模式**推进;编辑器里 **Preview FX** 开关让它们在创作时保持鲜活。## 参见diff --git a/examples/particle-demo/assets/scenes/static-emitters.esscene b/examples/particle-demo/assets/scenes/static-emitters.essceneindex f400a5207..d64c934c6 100644--- a/examples/particle-demo/assets/scenes/static-emitters.esscene+++ b/examples/particle-demo/assets/scenes/static-emitters.esscene@@ -9,7 +9,7 @@"children": [],"components": [{ "type": "Transform", "data": { "position": { "x": 0, "y": 0, "z": 10 } } },- { "type": "Camera", "data": { "projectionType": 1, "orthoSize": 300, "isActive": true, "priority": 0, "backgroundColor": { "r": 0.06, "g": 0.07, "b": 0.10, "a": 1 } } }+ { "type": "Camera", "data": { "projectionType": 1, "orthoSize": 300, "isActive": true, "priority": 0 } }],"visible": true},diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.mdindex 8d0b9bb39..cf786288c 100644--- a/sdk/etc/index.api.md+++ b/sdk/etc/index.api.md@@ -1,7 +1,7 @@# API surface — esengine/index<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 1117 stable · 17 beta · 1 deprecated+Symbols: 1119 stable · 17 beta · 1 deprecated## ABI_LAYOUT_HASH — const```@@ -7880,6 +7880,11 @@ InputRouter(ext: string): boolean```+## isParticleEditPreview — function+```+(): boolean+```+## isPlatformInitialized — function```(): boolean@@ -8485,6 +8490,11 @@ Plugin(world: World, entity: Entity, target: Vec2): void```+## setParticleEditPreview — function+```+(enabled: boolean): void+```+## setPlayMode — function```(active: boolean): voiddiff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.mdindex 9a3f23b49..0ce80266a 100644--- a/sdk/etc/index.node.api.md+++ b/sdk/etc/index.node.api.md@@ -1,7 +1,7 @@# API surface — esengine/index.node<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 1116 stable · 19 beta · 1 deprecated+Symbols: 1118 stable · 19 beta · 1 deprecated## ANCHOR_AXES — const```@@ -7875,6 +7875,11 @@ InputRouter(ext: string): boolean```+## isParticleEditPreview — function+```+(): boolean+```+## isPlatformInitialized — function```(): boolean@@ -8490,6 +8495,11 @@ Plugin(world: World, entity: Entity, target: Vec2): void```+## setParticleEditPreview — function+```+(enabled: boolean): void+```+## setPlayMode — function```(active: boolean): voiddiff --git a/sdk/src/core-content.ts b/sdk/src/core-content.tsindex ccf493bd4..805f5ce80 100644--- a/sdk/src/core-content.ts+++ b/sdk/src/core-content.ts@@ -308,6 +308,8 @@ export {ParticleAPI,ParticlePlugin,particlePlugin,+ setParticleEditPreview,+ isParticleEditPreview,} from './particle';// =============================================================================diff --git a/sdk/src/particle/ParticlePlugin.ts b/sdk/src/particle/ParticlePlugin.tsindex cb02fc2aa..3ef5cc747 100644--- a/sdk/src/particle/ParticlePlugin.ts+++ b/sdk/src/particle/ParticlePlugin.ts@@ -11,6 +11,23 @@ import { Particle, ParticleAPI } from './ParticleAPI';import { bakeGradient, type Gradient } from './gradient';import { bakeCurve, type Curve } from './curve';+// Editor authoring preview: lets the particle simulation advance in EDIT mode+// too, so emitters are live while they are being tuned. Module-scoped rather+// than per-App: only an editor's edit realm ever flips it — the play realm and+// shipped runtimes are separate module instances where it stays false and+// playModeOnly rules alone.+let editPreview_ = false;++/** Editor-only: advance the particle simulation in edit mode (live authoring+ * preview). No effect outside an editor (playModeOnly already passes there). */+export function setParticleEditPreview(enabled: boolean): void {+ editPreview_ = enabled;+}++export function isParticleEditPreview(): boolean {+ return editPreview_;+}+export class ParticlePlugin implements Plugin {name = 'particle';@@ -52,13 +69,14 @@ export class ParticlePlugin implements Plugin {// Particle advance is gameplay — frozen in editor edit mode, runs in// play mode / standalone runtime (matches animation/physics/timeline).+ // The edit-preview flag is the one authoring exception (see above).app.addSystemToSchedule(Schedule.Update, defineSystem([Res(Time), Res(Particle)],(time: TimeData, particle: ParticleAPI) => {particle.update(time.delta);},{ name: 'ParticleSystem' }- ), { runIf: playModeOnly });+ ), { runIf: () => editPreview_ || playModeOnly() });}}diff --git a/sdk/src/particle/index.ts b/sdk/src/particle/index.tsindex 42a919d26..a7117ade9 100644--- a/sdk/src/particle/index.ts+++ b/sdk/src/particle/index.ts@@ -1,6 +1,11 @@// SPDX-License-Identifier: Apache-2.0// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Teamexport { Particle, ParticleAPI } from './ParticleAPI';-export { ParticlePlugin, particlePlugin } from './ParticlePlugin';+export {+ ParticlePlugin,+ particlePlugin,+ setParticleEditPreview,+ isParticleEditPreview,+} from './ParticlePlugin';export { bakeGradient, GRADIENT_LUT_SIZE, type Gradient, type GradientStop } from './gradient';export { bakeCurve, type Curve, type CurveKey } from './curve';diff --git a/sdk/tests/particle-edit-preview.test.ts b/sdk/tests/particle-edit-preview.test.tsnew file mode 100644index 000000000..763e57dbf--- /dev/null+++ b/sdk/tests/particle-edit-preview.test.ts@@ -0,0 +1,62 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * Edit-mode particle preview: the simulation stays frozen in editor edit mode+ * by default (the playModeOnly contract), and the editor-only preview flag is+ * the one authoring exception — flipping it advances the sim live while+ * emitters are being tuned. Outside an editor the flag is irrelevant.+ */+import { describe, it, expect, afterEach } from 'vitest';+import { App } from '../src/app';+import { setEditorMode, setPlayMode } from '../src/env';+import {+ particlePlugin, Particle,+ setParticleEditPreview, isParticleEditPreview,+} from '../src/particle';++const STEP = 1 / 60;++afterEach(() => {+ setEditorMode(false);+ setPlayMode(false);+ setParticleEditPreview(false);+});++function makeApp(): { app: App; updates: () => number } {+ const app = App.new();+ app.addPlugin(particlePlugin);+ let count = 0;+ const api = app.getResource(Particle);+ api.update = () => { count++; };+ return { app, updates: () => count };+}++describe('particle edit preview', () => {+ it('edit mode: frozen by default, live while the preview flag is on', async () => {+ setEditorMode(true);+ const { app, updates } = makeApp();++ await app.tick(STEP);+ expect(updates()).toBe(0); // edit mode → gameplay frozen (unchanged)++ setParticleEditPreview(true);+ expect(isParticleEditPreview()).toBe(true);+ await app.tick(STEP);+ expect(updates()).toBe(1); // preview unfreezes the sim only++ setParticleEditPreview(false);+ await app.tick(STEP);+ expect(updates()).toBe(1); // re-freezes+ });++ it('play mode and standalone runtime are untouched by the flag', async () => {+ const { app, updates } = makeApp();+ await app.tick(STEP);+ expect(updates()).toBe(1); // standalone: playModeOnly already passes++ setEditorMode(true);+ setPlayMode(true);+ await app.tick(STEP);+ expect(updates()).toBe(2); // editor play mode: runs regardless of the flag+ });+});