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
refactor(scene): extract SceneTransitionController from sceneManager
esengine1f79fe401743
diff --git a/sdk/src/scene/SceneTransitionController.ts b/sdk/src/scene/SceneTransitionController.tsnew file mode 100644index 000000000..c99463585--- /dev/null+++ b/sdk/src/scene/SceneTransitionController.ts@@ -0,0 +1,199 @@+/**+ * @file SceneTransitionController.ts+ * @brief Fade transition state machine for scene switches.+ *+ * Extracted from the monolithic SceneManagerState so the sequencing+ * (fade-out → loading → fade-in) and its overlay-drawing side effect+ * live in one self-contained unit. SceneManagerState owns an instance+ * of this controller and drives it from `updateTransition()`.+ */+import type { Color } from '../types';+import { registerDrawCallback, unregisterDrawCallback } from '../customDraw';+import { Draw } from '../draw';+import { log } from '../logger';++export interface FadeTransitionOptions {+ readonly duration: number;+ readonly color: Color;+ readonly onStart?: () => void;+ readonly onComplete?: () => void;+}++/**+ * Fade transition runs in three phases:+ * - fade-out: overlay alpha ramps 0 → 1 over duration/2+ * - loading: overlay stays fully opaque while the old scene unloads and the+ * new one loads. Visual hold absorbs any load latency and prevents a+ * black-screen flash if the swap takes longer than the timer.+ * - fade-in: overlay alpha ramps 1 → 0 over duration/2+ *+ * Only a completed fade-in resolves the caller's promise. Any failure during+ * the `loading` phase rejects it with the original error.+ */+type TransitionPhase = 'fade-out' | 'loading' | 'fade-in';++type SwitchOutcome =+ | { readonly status: 'pending' }+ | { readonly status: 'success' }+ | { readonly status: 'error'; readonly error: unknown };++interface TransitionState {+ phase: TransitionPhase;+ elapsed: number;+ duration: number;+ color: Color;+ resolve: () => void;+ reject: (reason?: unknown) => void;+ onComplete: (() => void) | undefined;+ outcome: SwitchOutcome;+}++const TRANSITION_CALLBACK_ID = '__scene_transition_overlay__';+const OVERLAY_SIZE = 20000;++export class SceneTransitionController {+ private state_: TransitionState | null = null;++ isTransitioning(): boolean {+ return this.state_ !== null;+ }++ /**+ * Begin a fade transition. The returned promise resolves after fade-in+ * completes following a successful `performSwap`, or rejects with+ * `performSwap`'s error. The controller drives the visual overlay via+ * `Draw.rect` on every frame until the state machine clears itself.+ */+ start(options: FadeTransitionOptions, performSwap: () => Promise<void>): Promise<void> {+ return new Promise((resolve, reject) => {+ const { duration, color, onComplete } = options;++ options.onStart?.();++ this.state_ = {+ phase: 'fade-out',+ elapsed: 0,+ duration,+ color,+ resolve,+ reject,+ onComplete,+ outcome: { status: 'pending' },+ };++ registerDrawCallback(TRANSITION_CALLBACK_ID, () => this.drawOverlay_());++ // Fire the swap when we enter the 'loading' phase, not now — the+ // fade-out needs to finish first. We kick it off from update().+ this.performSwap_ = performSwap;+ });+ }++ /** Advance the state machine by `dt` seconds. */+ update(dt: number): void {+ if (!this.state_) return;++ this.state_.elapsed += dt;+ const halfDuration = this.state_.duration / 2;++ // Phase 1 → 2: fade-out reached full opacity. Start the swap; hold+ // the overlay fully opaque while it runs.+ if (this.state_.phase === 'fade-out' && this.state_.elapsed >= halfDuration) {+ this.state_.phase = 'loading';+ this.state_.elapsed = 0;+ this.kickSwap_();+ }++ // Phase 2 → 3 or reject: loading polls the outcome each frame. Elapsed+ // is clamped to 0 so the overlay never fades back in prematurely —+ // visual hold until the outcome is known.+ if (this.state_.phase === 'loading') {+ const outcome = this.state_.outcome;+ if (outcome.status === 'pending') {+ this.state_.elapsed = 0;+ return;+ }+ if (outcome.status === 'error') {+ const { reject } = this.state_;+ this.teardown_();+ reject(outcome.error);+ return;+ }+ // success → start fade-in+ this.state_.phase = 'fade-in';+ this.state_.elapsed = 0;+ return;+ }++ // Phase 3: fade-in done → resolve caller's promise.+ if (this.state_.phase === 'fade-in' && this.state_.elapsed >= halfDuration) {+ const { resolve, onComplete } = this.state_;+ this.teardown_();+ onComplete?.();+ resolve();+ }+ }++ /** Forcibly drop any in-flight transition without resolving or rejecting. */+ reset(): void {+ if (this.state_) {+ this.teardown_();+ }+ }++ private performSwap_: (() => Promise<void>) | null = null;++ private kickSwap_(): void {+ const state = this.state_;+ const swap = this.performSwap_;+ this.performSwap_ = null;+ if (!state || !swap) return;++ void (async () => {+ try {+ await swap();+ // Only record success if this transition is still the in-flight+ // one (reset/replace could have cleared state_ meanwhile).+ if (this.state_ === state) {+ state.outcome = { status: 'success' };+ }+ } catch (err) {+ log.error('scene', 'Scene transition failed', err);+ if (this.state_ === state) {+ state.outcome = { status: 'error', error: err };+ }+ }+ })();+ }++ private teardown_(): void {+ this.state_ = null;+ this.performSwap_ = null;+ unregisterDrawCallback(TRANSITION_CALLBACK_ID);+ }++ private drawOverlay_(): void {+ const state = this.state_;+ if (!state) return;+ const halfDuration = state.duration / 2;+ let alpha: number;+ switch (state.phase) {+ case 'fade-out':+ alpha = Math.min(state.elapsed / halfDuration, 1);+ break;+ case 'loading':+ alpha = 1;+ break;+ case 'fade-in':+ alpha = Math.max(1 - state.elapsed / halfDuration, 0);+ break;+ }+ Draw.setLayer(9999);+ Draw.setDepth(9999);+ Draw.rect(+ { x: 0, y: 0 },+ { x: OVERLAY_SIZE, y: OVERLAY_SIZE },+ { r: state.color.r, g: state.color.g, b: state.color.b, a: alpha },+ );+ }+}diff --git a/sdk/src/sceneManager.ts b/sdk/src/sceneManager.tsindex 2054115f0..7fe839c75 100644--- a/sdk/src/sceneManager.ts+++ b/sdk/src/sceneManager.ts@@ -14,8 +14,8 @@ import { Schedule } from './system';import { loadSceneWithAssets } from './scene';import { registerDrawCallback, unregisterDrawCallback } from './customDraw';import { PostProcess, PostProcessStack } from './postprocess';-import { Draw } from './draw';import { defineResource } from './resource';+import { SceneTransitionController } from './scene/SceneTransitionController';import {SceneOwner, Disabled, Sprite, SpineAnimation, BitmapText,ShapeRenderer, ParticleEmitter,@@ -65,39 +65,7 @@ export interface TransitionOptions {onComplete?: () => void;}-/**- * Fade transition runs in three phases:- * - fade-out: overlay alpha ramps 0 → 1 over duration/2- * - loading: overlay stays fully opaque while the old scene unloads and the- * new one loads. Visual hold absorbs any load latency and prevents a- * black-screen flash if the swap takes longer than the timer.- * - fade-in: overlay alpha ramps 1 → 0 over duration/2- *- * Only a completed fade-in resolves the caller's promise. Any failure during- * the `loading` phase rejects it with the original error.- */-type TransitionPhase = 'fade-out' | 'loading' | 'fade-in';--type SwitchOutcome =- | { readonly status: 'pending' }- | { readonly status: 'success' }- | { readonly status: 'error'; readonly error: unknown };--interface TransitionState {- phase: TransitionPhase;- elapsed: number;- duration: number;- color: Color;- targetScene: string;- options: TransitionOptions;- resolve: () => void;- reject: (reason?: unknown) => void;- /** Outcome of the in-flight doSwitch() during the `loading` phase. */- outcome: SwitchOutcome;-}--const TRANSITION_CALLBACK_ID = '__scene_transition_overlay__';-const OVERLAY_SIZE = 20000;+// Fade transition state machine lives in SceneTransitionController.// =============================================================================// Scene Instance (internal)@@ -198,7 +166,7 @@ export class SceneManagerState {private readonly loadOrder_: string[] = [];private activeScene_: string | null = null;private initialScene_: string | null = null;- private transition_: TransitionState | null = null;+ private readonly transitionController_ = new SceneTransitionController();private switching_ = false;private loadPromises_ = new Map<string, Promise<SceneContext>>();@@ -216,10 +184,7 @@ export class SceneManagerState {}}- if (this.transition_) {- unregisterDrawCallback(TRANSITION_CALLBACK_ID);- this.transition_ = null;- }+ this.transitionController_.reset();this.configs_.clear();this.scenes_.clear();@@ -247,11 +212,11 @@ export class SceneManagerState {}isTransitioning(): boolean {- return this.transition_ !== null;+ return this.transitionController_.isTransitioning();}async switchTo(name: string, options?: TransitionOptions): Promise<void> {- if (this.transition_ || this.switching_) {+ if (this.transitionController_.isTransitioning() || this.switching_) {log.warn('scene', `Scene switch already in progress, ignoring switchTo("${name}")`);return;}@@ -259,7 +224,23 @@ export class SceneManagerState {const transition = options?.transition ?? 'none';if (transition === 'fade') {- await this.startFadeTransition(name, options ?? {});+ const duration = options?.duration ?? RuntimeConfig.sceneTransitionDuration;+ const color = options?.color ?? { ...RuntimeConfig.sceneTransitionColor };+ const oldScene = this.activeScene_;+ await this.transitionController_.start(+ {+ duration,+ color,+ onStart: options?.onStart,+ onComplete: options?.onComplete,+ },+ async () => {+ if (oldScene && oldScene !== name) {+ await this.unload(oldScene, options);+ }+ await this.load(name);+ },+ );return;}@@ -274,126 +255,8 @@ export class SceneManagerState {}}- private startFadeTransition(targetScene: string, options: TransitionOptions): Promise<void> {- return new Promise((resolve, reject) => {- const duration = options.duration ?? RuntimeConfig.sceneTransitionDuration;- const color = options.color ?? { ...RuntimeConfig.sceneTransitionColor };-- options.onStart?.();-- this.transition_ = {- phase: 'fade-out',- elapsed: 0,- duration,- color,- targetScene,- options,- resolve,- reject,- outcome: { status: 'pending' },- };-- registerDrawCallback(TRANSITION_CALLBACK_ID, () => {- if (!this.transition_) return;- const halfDuration = this.transition_.duration / 2;- let alpha: number;- switch (this.transition_.phase) {- case 'fade-out':- alpha = Math.min(this.transition_.elapsed / halfDuration, 1);- break;- case 'loading':- alpha = 1;- break;- case 'fade-in':- alpha = Math.max(1 - this.transition_.elapsed / halfDuration, 0);- break;- }- Draw.setLayer(9999);- Draw.setDepth(9999);- Draw.rect(- { x: 0, y: 0 },- { x: OVERLAY_SIZE, y: OVERLAY_SIZE },- { r: color.r, g: color.g, b: color.b, a: alpha },- );- });- });- }-updateTransition(dt: number): void {- if (!this.transition_) return;-- this.transition_.elapsed += dt;- const halfDuration = this.transition_.duration / 2;-- // Phase 1 → 2: fade-out reached full opacity. Start the swap, hold- // the overlay fully opaque while it runs.- if (this.transition_.phase === 'fade-out' && this.transition_.elapsed >= halfDuration) {- this.transition_.phase = 'loading';- this.transition_.elapsed = 0;-- const transition = this.transition_;- const { targetScene, options } = transition;- const oldScene = this.activeScene_;-- // Fire-and-forget; we observe completion via `transition.outcome`.- // Errors are recorded there rather than rejecting the transition- // promise directly so the outcome check below owns the cleanup path- // (avoids racing with a transition_ that may have been cleared).- void (async () => {- try {- if (oldScene && oldScene !== targetScene) {- await this.unload(oldScene, options);- }- await this.load(targetScene);- // Only record success if this transition is still the- // in-flight one (cancel/replace could have reassigned).- if (this.transition_ === transition) {- transition.outcome = { status: 'success' };- }- } catch (err) {- log.error('scene', 'Scene transition failed', err);- if (this.transition_ === transition) {- transition.outcome = { status: 'error', error: err };- } else {- // Transition was replaced mid-flight; nothing to reject.- }- }- })();- }-- // Phase 2 → 3 or reject: loading phase checks whether the swap has- // finished this frame. Elapsed is clamped to 0 so the overlay never- // fades back in prematurely — visual hold until the outcome is known.- if (this.transition_.phase === 'loading') {- const outcome = this.transition_.outcome;- if (outcome.status === 'pending') {- this.transition_.elapsed = 0;- return;- }- if (outcome.status === 'error') {- const { reject, options } = this.transition_;- this.transition_ = null;- unregisterDrawCallback(TRANSITION_CALLBACK_ID);- // Still call onComplete? No — onComplete signals success. Keep- // it scoped to the successful path.- void options;- reject(outcome.error);- return;- }- // success → start fade-in- this.transition_.phase = 'fade-in';- this.transition_.elapsed = 0;- return;- }-- // Phase 3: fade-in done → resolve caller's promise.- if (this.transition_.phase === 'fade-in' && this.transition_.elapsed >= halfDuration) {- const { resolve, options } = this.transition_;- this.transition_ = null;- unregisterDrawCallback(TRANSITION_CALLBACK_ID);- options.onComplete?.();- resolve();- }+ this.transitionController_.update(dt);}async load(name: string): Promise<SceneContext> {diff --git a/sdk/tests/scene-transition-controller.test.ts b/sdk/tests/scene-transition-controller.test.tsnew file mode 100644index 000000000..531219290--- /dev/null+++ b/sdk/tests/scene-transition-controller.test.ts@@ -0,0 +1,137 @@+/**+ * @file scene-transition-controller.test.ts+ * @brief SceneTransitionController — three-phase fade state machine in+ * isolation from the SceneManager.+ */+import { describe, expect, it, vi } from 'vitest';++const drawCalls = {+ register: vi.fn(),+ unregister: vi.fn(),+};++vi.mock('../src/customDraw', () => ({+ registerDrawCallback: (id: string, fn: () => void) => drawCalls.register(id, fn),+ unregisterDrawCallback: (id: string) => drawCalls.unregister(id),+}));++vi.mock('../src/draw', () => ({+ Draw: {+ setLayer: vi.fn(),+ setDepth: vi.fn(),+ rect: vi.fn(),+ },+}));++import { SceneTransitionController } from '../src/scene/SceneTransitionController';++describe('SceneTransitionController', () => {+ it('resolves after fade-out → loading → fade-in on a successful swap', async () => {+ drawCalls.register.mockClear();+ drawCalls.unregister.mockClear();+ const ctrl = new SceneTransitionController();+ let swapped = false;+ const p = ctrl.start(+ { duration: 1.0, color: { r: 0, g: 0, b: 0, a: 1 } },+ async () => { swapped = true; },+ );+ let resolved = false;+ p.then(() => { resolved = true; });++ expect(ctrl.isTransitioning()).toBe(true);+ expect(drawCalls.register).toHaveBeenCalledTimes(1);++ ctrl.update(0.6); // fade-out done → loading; kicks swap+ await new Promise(r => setTimeout(r, 5)); // let swap microtask settle+ expect(swapped).toBe(true);++ ctrl.update(0.0); // loading sees success → fade-in+ ctrl.update(0.6); // fade-in done → resolve+ await p;++ expect(resolved).toBe(true);+ expect(ctrl.isTransitioning()).toBe(false);+ expect(drawCalls.unregister).toHaveBeenCalledTimes(1);+ });++ it('rejects with the swap error and cleans up', async () => {+ drawCalls.register.mockClear();+ drawCalls.unregister.mockClear();+ const ctrl = new SceneTransitionController();+ const boom = new Error('swap failed');+ const p = ctrl.start(+ { duration: 1.0, color: { r: 0, g: 0, b: 0, a: 1 } },+ async () => { throw boom; },+ );+ const errs: unknown[] = [];+ p.catch(e => errs.push(e));++ ctrl.update(0.6); // fade-out done → loading+ await new Promise(r => setTimeout(r, 5));+ ctrl.update(0.0); // loading sees error → reject+ await new Promise(r => setTimeout(r, 0));+ await new Promise(r => setTimeout(r, 0));++ expect(errs).toEqual([boom]);+ expect(ctrl.isTransitioning()).toBe(false);+ expect(drawCalls.unregister).toHaveBeenCalledTimes(1);+ });++ it('holds the overlay fully opaque while the swap is pending', async () => {+ drawCalls.register.mockClear();+ drawCalls.unregister.mockClear();+ const ctrl = new SceneTransitionController();+ let release: (() => void) | null = null;+ void ctrl.start(+ { duration: 1.0, color: { r: 0, g: 0, b: 0, a: 1 } },+ () => new Promise<void>(resolve => { release = resolve; }),+ );++ ctrl.update(0.6); // fade-out → loading+ // Call update many more times while the swap has not resolved;+ // the controller must stay in 'loading' and not advance.+ for (let i = 0; i < 10; i++) ctrl.update(0.2);+ expect(ctrl.isTransitioning()).toBe(true);++ release!();+ await new Promise(r => setTimeout(r, 5));+ ctrl.update(0.0); // loading → fade-in+ ctrl.update(0.6); // fade-in → resolve+ expect(ctrl.isTransitioning()).toBe(false);+ });++ it('reset() clears in-flight transitions without resolve/reject', () => {+ drawCalls.register.mockClear();+ drawCalls.unregister.mockClear();+ const ctrl = new SceneTransitionController();+ void ctrl.start(+ { duration: 1.0, color: { r: 0, g: 0, b: 0, a: 1 } },+ async () => { /* noop */ },+ );+ expect(ctrl.isTransitioning()).toBe(true);++ ctrl.reset();+ expect(ctrl.isTransitioning()).toBe(false);+ expect(drawCalls.unregister).toHaveBeenCalledTimes(1);+ });++ it('invokes onStart at start and onComplete only on success', async () => {+ const onStart = vi.fn();+ const onComplete = vi.fn();+ const ctrl = new SceneTransitionController();+ const p = ctrl.start(+ { duration: 1.0, color: { r: 0, g: 0, b: 0, a: 1 }, onStart, onComplete },+ async () => { /* noop */ },+ );+ expect(onStart).toHaveBeenCalledTimes(1);+ expect(onComplete).not.toHaveBeenCalled();++ ctrl.update(0.6);+ await new Promise(r => setTimeout(r, 5));+ ctrl.update(0.0);+ ctrl.update(0.6);+ await p;++ expect(onComplete).toHaveBeenCalledTimes(1);+ });+});