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.

refactor(runtime): convert Particle/Tween/Audio singletons to per-app resources

esengine5c769720fbfd
diff --git a/examples/audio-demo/src/systems/sfx.ts b/examples/audio-demo/src/systems/sfx.ts
index 7316002f1..2890cf15c 100644
--- a/examples/audio-demo/src/systems/sfx.ts
+++ b/examples/audio-demo/src/systems/sfx.ts
@@ -1,5 +1,5 @@
import {
- defineSystem, Query, Mut, Res, Time, Input, Audio,
+ defineSystem, Query, Mut, Res, Time, Input, Audio, AudioAPI,
UIEvents,
} from 'esengine';
import type { UIEventQueue } from 'esengine';
@@ -15,8 +15,8 @@ const SFX_URLS = [
let triggerIndex = 0;
export const sfxTriggerSystem = defineSystem(
- [Query(Mut(SFXTrigger)), Res(Time), Res(Input), Res(UIEvents)],
- (query, time, input, events: UIEventQueue) => {
+ [Query(Mut(SFXTrigger)), Res(Time), Res(Input), Res(UIEvents), Res(Audio)],
+ (query, time, input, events: UIEventQueue, audio: AudioAPI) => {
triggerIndex = 0;
for (const [entity, trigger] of query) {
trigger.cooldown = Math.max(0, trigger.cooldown - time.delta);
@@ -26,7 +26,7 @@ export const sfxTriggerSystem = defineSystem(
if ((input.isKeyPressed(key) || clicked) && trigger.cooldown <= 0) {
const url = SFX_URLS[triggerIndex];
if (url) {
- Audio.playSFX(url);
+ audio.playSFX(url);
}
trigger.cooldown = 0.1;
}
diff --git a/examples/tween-animation/src/systems/setup.ts b/examples/tween-animation/src/systems/setup.ts
index 9a194886b..1882f2fed 100644
--- a/examples/tween-animation/src/systems/setup.ts
+++ b/examples/tween-animation/src/systems/setup.ts
@@ -1,6 +1,6 @@
import {
- defineSystem, Query,
- Transform, Sprite, Tween, TweenTarget, EasingType, LoopMode,
+ defineSystem, Query, Res,
+ Transform, Sprite, Tween, TweenAPI, TweenTarget, EasingType, LoopMode,
} from 'esengine';
import { EasingDemo, ScaleDemo, RotationDemo, ColorDemo } from '../components';
@@ -18,39 +18,39 @@ const X_TO = 250;
const DURATION = 2;
export const setupSystem = defineSystem(
- [Query(Transform, EasingDemo), Query(Transform, ScaleDemo), Query(Transform, RotationDemo), Query(Transform, ColorDemo)],
- (easings, scales, rotations, colors) => {
+ [Res(Tween), Query(Transform, EasingDemo), Query(Transform, ScaleDemo), Query(Transform, RotationDemo), Query(Transform, ColorDemo)],
+ (tween: TweenAPI, easings, scales, rotations, colors) => {
for (const [entity, _t, demo] of easings) {
- Tween.to(entity, TweenTarget.PositionX, X_FROM, X_TO, DURATION, {
+ tween.to(entity, TweenTarget.PositionX, X_FROM, X_TO, DURATION, {
easing: EASING_TYPES[demo.easingIndex] ?? EasingType.Linear,
loop: LoopMode.PingPong,
});
}
for (const [entity] of scales) {
- Tween.to(entity, TweenTarget.ScaleX, 0.5, 2.0, 1.0, {
+ tween.to(entity, TweenTarget.ScaleX, 0.5, 2.0, 1.0, {
easing: EasingType.EaseInOutQuad,
loop: LoopMode.PingPong,
});
- Tween.to(entity, TweenTarget.ScaleY, 0.5, 2.0, 1.0, {
+ tween.to(entity, TweenTarget.ScaleY, 0.5, 2.0, 1.0, {
easing: EasingType.EaseInOutQuad,
loop: LoopMode.PingPong,
});
}
for (const [entity] of rotations) {
- Tween.to(entity, TweenTarget.RotationZ, 0, 360, 3.0, {
+ tween.to(entity, TweenTarget.RotationZ, 0, 360, 3.0, {
easing: EasingType.Linear,
loop: LoopMode.Restart,
});
}
for (const [entity] of colors) {
- Tween.to(entity, TweenTarget.ColorR, 1, 0, 2, {
+ tween.to(entity, TweenTarget.ColorR, 1, 0, 2, {
loop: LoopMode.PingPong,
easing: EasingType.EaseInOutQuad,
});
- Tween.to(entity, TweenTarget.ColorG, 0, 1, 2, {
+ tween.to(entity, TweenTarget.ColorG, 0, 1, 2, {
loop: LoopMode.PingPong,
easing: EasingType.EaseInOutQuad,
});
diff --git a/sdk/src/animation/AnimationPlugin.ts b/sdk/src/animation/AnimationPlugin.ts
index 5681d201f..30e89412c 100644
--- a/sdk/src/animation/AnimationPlugin.ts
+++ b/sdk/src/animation/AnimationPlugin.ts
@@ -9,9 +9,8 @@ import { Res } from '../resource';
import { Time, type TimeData } from '../resource';
import type { Entity } from '../types';
import type { ESEngineModule, CppRegistry } from '../wasm';
-import { initTweenAPI, shutdownTweenAPI, Tween } from './Tween';
+import { Tween, TweenAPI } from './Tween';
import { spriteAnimatorSystemUpdate, removeAnimEventListeners } from './SpriteAnimator';
-import { tweenCompositionManager } from './TweenGroup';
import { playModeOnly } from '../env';
import { SystemLabel } from '../systemLabels';
@@ -21,19 +20,19 @@ export class AnimationPlugin implements Plugin {
build(app: App): void {
const module = app.wasmModule as ESEngineModule;
const registry = app.world.getCppRegistry() as CppRegistry;
- initTweenAPI(module, registry);
+ const tween = new TweenAPI(module, registry);
+ app.insertResource(Tween, tween);
const world = app.world;
world.onDespawn((entity: Entity) => {
- Tween.cancelAll(entity);
+ tween.cancelAll(entity);
removeAnimEventListeners(entity);
});
app.addSystemToSchedule(Schedule.Update, defineSystem(
- [Res(Time)],
- (time: TimeData) => {
- Tween.update(time.delta);
- tweenCompositionManager.update();
+ [Res(Time), Res(Tween)],
+ (time: TimeData, tweenAPI: TweenAPI) => {
+ tweenAPI.update(time.delta);
},
{ name: 'TweenSystem' }
), { runIf: playModeOnly });
@@ -46,11 +45,6 @@ export class AnimationPlugin implements Plugin {
{ name: 'SpriteAnimatorSystem' }
), { runAfter: [SystemLabel.Tween], runIf: playModeOnly });
}
-
- cleanup(): void {
- shutdownTweenAPI();
- tweenCompositionManager.clear();
- }
}
export const animationPlugin = new AnimationPlugin();
diff --git a/sdk/src/animation/Tween.ts b/sdk/src/animation/Tween.ts
index 453c67d70..99ed34ed1 100644
--- a/sdk/src/animation/Tween.ts
+++ b/sdk/src/animation/Tween.ts
@@ -1,13 +1,25 @@
/**
* @file Tween.ts
* @brief Property tween API wrapping C++ TweenSystem
+ *
+ * `TweenAPI` is per-app — each `App` owns an instance via the `Tween`
+ * resource. Consume as `Res(Tween)` in a system or
+ * `app.getResource(Tween)` outside ECS code.
*/
import type { Entity } from '../types';
import type { ESEngineModule, CppRegistry } from '../wasm';
+import { defineResource } from '../resource';
import { EasingType } from './Easing';
import { LoopMode, TweenState, type TweenOptions } from './TweenTypes';
-import { valueTweenManager, ValueTweenHandle } from './ValueTween';
+import { ValueTweenManager, ValueTweenHandle } from './ValueTween';
+import {
+ TweenGroup,
+ TweenSequence,
+ TweenCompositionManager,
+ type Completable,
+ type TweenFactory,
+} from './TweenGroup';
// Re-export so consumers can reach shared types via the Tween entry point
export { EasingType, type BezierPoints } from './Easing';
@@ -34,7 +46,7 @@ export { ValueTweenHandle } from './ValueTween';
* separately; for now TweenTarget is the stable subset.
*
* If you need to tween a field not in this list (e.g. UIRect.anchorMin.x),
- * use `Tween.value(...)` with a callback that writes the field yourself,
+ * use `tween.value(...)` with a callback that writes the field yourself,
* or drive it via Timeline.
*/
export const TweenTarget = {
@@ -62,11 +74,18 @@ export type TweenTarget = (typeof TweenTarget)[keyof typeof TweenTarget];
export class TweenHandle {
private readonly module_: ESEngineModule;
private readonly registry_: CppRegistry;
+ private readonly valueManager_: ValueTweenManager;
readonly entity: Entity;
- constructor(module: ESEngineModule, registry: CppRegistry, entity: Entity) {
+ constructor(
+ module: ESEngineModule,
+ registry: CppRegistry,
+ valueManager: ValueTweenManager,
+ entity: Entity,
+ ) {
this.module_ = module;
this.registry_ = registry;
+ this.valueManager_ = valueManager;
this.entity = entity;
}
@@ -81,7 +100,7 @@ export class TweenHandle {
then(next: TweenHandle | ValueTweenHandle): this {
if (next instanceof ValueTweenHandle) {
- valueTweenManager.registerCppSequence(this.entity, next.id);
+ this.valueManager_.registerCppSequence(this.entity, next.id);
return this;
}
this.module_._anim_setSequenceNext(this.registry_, this.entity, next.entity);
@@ -102,69 +121,97 @@ export class TweenHandle {
}
// =============================================================================
-// Tween Static API
+// Per-app Tween API
// =============================================================================
-let _module: ESEngineModule | null = null;
-let _registry: CppRegistry | null = null;
-
-export function initTweenAPI(module: ESEngineModule, registry: CppRegistry): void {
- _module = module;
- _registry = registry;
- valueTweenManager.init(module, registry);
-}
-
-export function shutdownTweenAPI(): void {
- valueTweenManager.shutdown();
- _module = null;
- _registry = null;
-}
-
-function getModule(): ESEngineModule {
- if (!_module) throw new Error('Tween API not initialized');
- return _module;
-}
+export class TweenAPI {
+ private readonly module_: ESEngineModule;
+ private readonly registry_: CppRegistry;
+ private readonly valueManager_: ValueTweenManager;
+ private readonly compositionManager_: TweenCompositionManager;
-function getRegistry(): CppRegistry {
- if (!_registry) throw new Error('Tween API not initialized');
- return _registry;
-}
+ constructor(module: ESEngineModule, registry: CppRegistry) {
+ this.module_ = module;
+ this.registry_ = registry;
+ this.valueManager_ = new ValueTweenManager(module, registry);
+ this.compositionManager_ = new TweenCompositionManager();
+ }
-export const Tween = {
- to(entity: Entity, target: TweenTarget, from: number, to: number,
- duration: number, options?: TweenOptions): TweenHandle {
- const m = getModule();
- const r = getRegistry();
+ to(
+ entity: Entity,
+ target: TweenTarget,
+ from: number,
+ to: number,
+ duration: number,
+ options?: TweenOptions,
+ ): TweenHandle {
const easing = options?.easing ?? EasingType.Linear;
const delay = options?.delay ?? 0;
const loop = options?.loop ?? LoopMode.None;
const loopCount = options?.loopCount ?? 0;
- const tweenEntity = m._anim_createTween(
- r, entity, target, from, to, duration,
+ const tweenEntity = this.module_._anim_createTween(
+ this.registry_, entity, target, from, to, duration,
easing, delay, loop, loopCount,
) as Entity;
- return new TweenHandle(m, r, tweenEntity);
- },
+ return new TweenHandle(this.module_, this.registry_, this.valueManager_, tweenEntity);
+ }
- value(from: number, to: number, duration: number,
- callback: (value: number) => void,
- options?: TweenOptions): ValueTweenHandle {
- const id = valueTweenManager.create(from, to, duration, callback, options);
- return new ValueTweenHandle(id);
- },
+ value(
+ from: number,
+ to: number,
+ duration: number,
+ callback: (value: number) => void,
+ options?: TweenOptions,
+ ): ValueTweenHandle {
+ const id = this.valueManager_.create(from, to, duration, callback, options);
+ return new ValueTweenHandle(this.valueManager_, id);
+ }
cancel(tweenHandle: TweenHandle): void {
- getModule()._anim_cancelTween(getRegistry(), tweenHandle.entity);
- },
+ this.module_._anim_cancelTween(this.registry_, tweenHandle.entity);
+ }
cancelAll(entity: Entity): void {
- getModule()._anim_cancelAllTweens(getRegistry(), entity);
- },
+ this.module_._anim_cancelAllTweens(this.registry_, entity);
+ }
update(deltaTime: number): void {
- getModule()._anim_updateTweens(getRegistry(), deltaTime);
- valueTweenManager.update(deltaTime);
- },
-};
+ this.module_._anim_updateTweens(this.registry_, deltaTime);
+ this.valueManager_.update(deltaTime);
+ this.compositionManager_.update();
+ }
+
+ // ---- Composition builders -------------------------------------------------
+
+ parallel(tweens: Completable[]): TweenGroup {
+ const group = new TweenGroup(tweens);
+ this.compositionManager_.add(group);
+ return group;
+ }
+
+ sequence(factories: TweenFactory[]): TweenSequence {
+ const seq = new TweenSequence(factories);
+ this.compositionManager_.add(seq);
+ return seq;
+ }
+
+ delay(seconds: number): ValueTweenHandle {
+ const id = this.valueManager_.create(0, 0, seconds, () => {});
+ return new ValueTweenHandle(this.valueManager_, id);
+ }
+
+ /** @internal test hook — how many groups/sequences are still being polled */
+ get activeCompositionCount(): number {
+ return this.compositionManager_.activeCount;
+ }
+
+ /** @internal shutdown hook for plugin cleanup */
+ clear(): void {
+ this.compositionManager_.clear();
+ }
+}
+
+/** Resource handle for the per-app Tween API. */
+export const Tween = defineResource<TweenAPI>(null!, 'Tween');
diff --git a/sdk/src/animation/TweenGroup.ts b/sdk/src/animation/TweenGroup.ts
index dcacdd019..04a30ed55 100644
--- a/sdk/src/animation/TweenGroup.ts
+++ b/sdk/src/animation/TweenGroup.ts
@@ -1,16 +1,27 @@
/**
* @file TweenGroup.ts
- * @brief Parallel and sequential tween composition utilities
+ * @brief Parallel and sequential tween composition utilities.
+ *
+ * `TweenGroup` / `TweenSequence` are pure logic — they wrap any set of
+ * `Completable` items and expose parent-level state/pause/resume/cancel.
+ * `TweenCompositionManager` owns auto-polling: call `add(group)` once and
+ * `update()` each frame; it removes groups as they finish.
+ *
+ * There is no module-level composition singleton anymore — the manager is
+ * owned by each `TweenAPI` instance so multiple apps don't share state.
*/
import { TweenState } from './TweenTypes';
-import { valueTweenManager, ValueTweenHandle } from './ValueTween';
+
+// Keep the handle type re-exported from this module for downstream
+// convenience (TweenAPI's composition helpers return ValueTweenHandle).
+export type { ValueTweenHandle } from './ValueTween';
// =============================================================================
// Completable - common interface for things that finish
// =============================================================================
-interface Completable {
+export interface Completable {
get state(): TweenState;
pause(): void;
resume(): void;
@@ -75,7 +86,7 @@ export class TweenGroup implements Completable {
// TweenSequence - sequential execution
// =============================================================================
-type TweenFactory = () => Completable;
+export type TweenFactory = () => Completable;
export class TweenSequence implements Completable {
private readonly factories_: TweenFactory[];
@@ -141,10 +152,10 @@ export class TweenSequence implements Completable {
}
// =============================================================================
-// Composition Manager - polls groups/sequences for completion
+// Composition Manager (per-app) - polls groups/sequences for completion
// =============================================================================
-class TweenCompositionManager {
+export class TweenCompositionManager {
private readonly active_ = new Set<TweenGroup | TweenSequence>();
add(item: TweenGroup | TweenSequence): void {
@@ -168,27 +179,6 @@ class TweenCompositionManager {
}
}
-export const tweenCompositionManager = new TweenCompositionManager();
-
-// =============================================================================
-// Builder API
-// =============================================================================
-
-export const TweenCompose = {
- parallel(tweens: Completable[]): TweenGroup {
- const group = new TweenGroup(tweens);
- tweenCompositionManager.add(group);
- return group;
- },
-
- sequence(factories: TweenFactory[]): TweenSequence {
- const seq = new TweenSequence(factories);
- tweenCompositionManager.add(seq);
- return seq;
- },
-
- delay(seconds: number): ValueTweenHandle {
- const id = valueTweenManager.create(0, 0, seconds, () => {});
- return new ValueTweenHandle(id);
- },
-};
+// The builder API (parallel / sequence / delay) now lives on `TweenAPI`
+// since it needs access to per-app state (value tween manager, composition
+// manager). See `TweenAPI.parallel()` / `.sequence()` / `.delay()`.
diff --git a/sdk/src/animation/ValueTween.ts b/sdk/src/animation/ValueTween.ts
index a90d0905b..9a79f5c2e 100644
--- a/sdk/src/animation/ValueTween.ts
+++ b/sdk/src/animation/ValueTween.ts
@@ -1,6 +1,10 @@
/**
* @file ValueTween.ts
* @brief JS-side value tweening (fallback for fields not covered by C++ TweenTarget)
+ *
+ * Each App owns its own `ValueTweenManager` instance (held inside
+ * `TweenAPI`). Handles carry a reference back to their manager so
+ * `handle.state` / `handle.cancel()` etc. route to the right app.
*/
import type { ESEngineModule, CppRegistry } from '../wasm';
@@ -31,17 +35,17 @@ interface ValueTweenEntry {
}
// =============================================================================
-// Value Tween Manager
+// Value Tween Manager (per-app)
// =============================================================================
-class ValueTweenManager {
+export class ValueTweenManager {
private entries_ = new Map<number, ValueTweenEntry>();
private nextId_ = 1;
private cppSequences_ = new Map<number, number>();
- private module_: ESEngineModule | null = null;
- private registry_: CppRegistry | null = null;
+ private readonly module_: ESEngineModule;
+ private readonly registry_: CppRegistry;
- init(module: ESEngineModule, registry: CppRegistry): void {
+ constructor(module: ESEngineModule, registry: CppRegistry) {
this.module_ = module;
this.registry_ = registry;
}
@@ -75,15 +79,13 @@ class ValueTweenManager {
}
update(dt: number): void {
- if (this.module_ && this.registry_) {
- for (const [cppEntity, jsTweenId] of this.cppSequences_) {
- const cppState = this.module_._anim_getTweenState(
- this.registry_, cppEntity as Entity,
- );
- if (cppState === TweenState.Completed) {
- this.resume(jsTweenId);
- this.cppSequences_.delete(cppEntity);
- }
+ for (const [cppEntity, jsTweenId] of this.cppSequences_) {
+ const cppState = this.module_._anim_getTweenState(
+ this.registry_, cppEntity as Entity,
+ );
+ if (cppState === TweenState.Completed) {
+ this.resume(jsTweenId);
+ this.cppSequences_.delete(cppEntity);
}
}
@@ -189,35 +191,33 @@ class ValueTweenManager {
this.cppSequences_.set(cppEntity as number, jsTweenId);
this.pause(jsTweenId);
}
-
- shutdown(): void {
- this.entries_.clear();
- this.cppSequences_.clear();
- this.module_ = null;
- this.registry_ = null;
- this.nextId_ = 1;
- }
}
-export const valueTweenManager = new ValueTweenManager();
-
// =============================================================================
-// Value Tween Handle
+// Value Tween Handle — carries a back-ref to its manager so handle-side
+// calls route to the right app's state.
// =============================================================================
export class ValueTweenHandle {
+ private readonly manager_: ValueTweenManager;
readonly id: number;
- constructor(id: number) {
+ constructor(manager: ValueTweenManager, id: number) {
+ this.manager_ = manager;
this.id = id;
}
+ /** @internal used by TweenAPI.then() to chain the C++ tween side */
+ get manager(): ValueTweenManager {
+ return this.manager_;
+ }
+
get state(): TweenState {
- return valueTweenManager.getState(this.id);
+ return this.manager_.getState(this.id);
}
bezier(p1x: number, p1y: number, p2x: number, p2y: number): this {
- valueTweenManager.setBezier(this.id, p1x, p1y, p2x, p2y);
+ this.manager_.setBezier(this.id, p1x, p1y, p2x, p2y);
return this;
}
@@ -225,22 +225,22 @@ export class ValueTweenHandle {
then(next: { pause(): void; resume(): void }): this;
then(next: ValueTweenHandle | { pause(): void; resume(): void }): this {
if (next instanceof ValueTweenHandle) {
- valueTweenManager.setSequenceNext(this.id, next.id);
+ this.manager_.setSequenceNext(this.id, next.id);
} else {
- valueTweenManager.setSequenceNextExternal(this.id, next);
+ this.manager_.setSequenceNextExternal(this.id, next);
}
return this;
}
pause(): void {
- valueTweenManager.pause(this.id);
+ this.manager_.pause(this.id);
}
resume(): void {
- valueTweenManager.resume(this.id);
+ this.manager_.resume(this.id);
}
cancel(): void {
- valueTweenManager.cancel(this.id);
+ this.manager_.cancel(this.id);
}
}
diff --git a/sdk/src/animation/index.ts b/sdk/src/animation/index.ts
index 70bc07985..718c086d4 100644
--- a/sdk/src/animation/index.ts
+++ b/sdk/src/animation/index.ts
@@ -17,14 +17,14 @@ export {
export {
Tween,
+ TweenAPI,
TweenHandle,
TweenTarget,
- initTweenAPI,
- shutdownTweenAPI,
} from './Tween';
export {
ValueTweenHandle,
+ ValueTweenManager,
} from './ValueTween';
export {
@@ -54,8 +54,9 @@ export {
export {
TweenGroup,
TweenSequence,
- TweenCompose,
- tweenCompositionManager,
+ TweenCompositionManager,
+ type Completable,
+ type TweenFactory,
} from './TweenGroup';
export {
diff --git a/sdk/src/asset/AssetLoader.ts b/sdk/src/asset/AssetLoader.ts
index 271c90b64..1197f97b3 100644
--- a/sdk/src/asset/AssetLoader.ts
+++ b/sdk/src/asset/AssetLoader.ts
@@ -54,6 +54,13 @@ export interface LoadContext {
loadTexture(path: string, flipY?: boolean): Promise<TextureResult>;
loadText(path: string): Promise<string>;
loadBinary(path: string): Promise<ArrayBuffer>;
+ /**
+ * Audio API for the owning app, resolved lazily so that
+ * AudioPlugin / AssetPlugin can be installed in either order.
+ * Returns null when no AudioPlugin is installed — audio-typed
+ * assets will fail to preload.
+ */
+ getAudio(): import('../audio/Audio').AudioAPI | null;
}
export interface AssetLoader<T> {
diff --git a/sdk/src/asset/AssetPlugin.ts b/sdk/src/asset/AssetPlugin.ts
index ca4cb99c4..78ff4df68 100644
--- a/sdk/src/asset/AssetPlugin.ts
+++ b/sdk/src/asset/AssetPlugin.ts
@@ -4,6 +4,7 @@ import { Assets as AssetsClass } from './Assets';
import { HttpBackend } from './Backend';
import { initBuiltinAssetFields } from './AssetFieldRegistry';
import { AssetRefCounter } from './AssetRefCounter';
+import { Audio, type AudioAPI } from '../audio/Audio';
import { log } from '../logger';
export type AssetsData = AssetsClass;
@@ -28,6 +29,8 @@ export class AssetPlugin implements Plugin {
const assets = AssetsClass.create({
backend: new HttpBackend({ baseUrl: '' }),
module,
+ getAudio: (): AudioAPI | null =>
+ app.hasResource(Audio) ? app.getResource(Audio) : null,
});
// Install the ref counter so resolveSceneAssetPaths records who
diff --git a/sdk/src/asset/Assets.ts b/sdk/src/asset/Assets.ts
index b3a557a98..cdd37a0bd 100644
--- a/sdk/src/asset/Assets.ts
+++ b/sdk/src/asset/Assets.ts
@@ -31,6 +31,12 @@ export interface AssetsOptions {
backend: Backend;
catalog?: Catalog;
module: ESEngineModule;
+ /**
+ * Lazy accessor for the owning app's Audio API. AudioAssetLoader
+ * calls it at load time so AssetPlugin and AudioPlugin can be built
+ * in any order. Pass null (or omit) if no audio support is needed.
+ */
+ getAudio?: () => import('../audio/Audio').AudioAPI | null;
}
export interface AssetBundle {
@@ -82,6 +88,7 @@ export class Assets {
private baseUrl_?: string;
private module_: ESEngineModule;
+ private getAudio_: () => import('../audio/Audio').AudioAPI | null;
private loaders_ = new Map<string, AssetLoader<unknown>>();
private textureLoader_: TextureLoader;
private spineLoader_: SpineAssetLoader;
@@ -98,6 +105,7 @@ export class Assets {
this.backend = options.backend;
this.catalog = options.catalog ?? Catalog.empty();
this.module_ = options.module;
+ this.getAudio_ = options.getAudio ?? (() => null);
this.textureLoader_ = new TextureLoader(options.module);
this.spineLoader_ = new SpineAssetLoader(options.module);
@@ -663,6 +671,9 @@ export class Assets {
async loadBinary(path: string): Promise<ArrayBuffer> {
return self.backend.fetchBinary(self.backend.resolveUrl(path));
},
+ getAudio() {
+ return self.getAudio_();
+ },
};
return this.loadContext_;
}
diff --git a/sdk/src/asset/loaders/AudioAssetLoader.ts b/sdk/src/asset/loaders/AudioAssetLoader.ts
index e24ffdb26..84d537132 100644
--- a/sdk/src/asset/loaders/AudioAssetLoader.ts
+++ b/sdk/src/asset/loaders/AudioAssetLoader.ts
@@ -1,18 +1,24 @@
import type { AssetLoader, LoadContext, AudioResult } from '../AssetLoader';
-import { Audio } from '../../audio/Audio';
+import { log } from '../../logger';
export class AudioAssetLoader implements AssetLoader<AudioResult> {
readonly type = 'audio';
readonly extensions = ['.mp3', '.wav', '.ogg', '.m4a', '.aac'];
async load(path: string, ctx: LoadContext): Promise<AudioResult> {
+ const audio = ctx.getAudio();
+ if (!audio) {
+ log.warn('asset', `AudioAssetLoader: no Audio resource for "${path}" (AudioPlugin not installed?)`);
+ return { bufferId: path };
+ }
const buildPath = ctx.catalog.getBuildPath(path);
const buffer = await ctx.loadBinary(buildPath);
- await Audio.preloadFromData(path, buffer);
+ await audio.preloadFromData(path, buffer);
return { bufferId: path };
}
unload(_asset: AudioResult): void {
- // Audio buffers are managed globally by Audio system
+ // Audio buffers are owned by the app's AudioAPI and freed on
+ // plugin teardown via `audio.dispose()`.
}
}
diff --git a/sdk/src/audio/Audio.ts b/sdk/src/audio/Audio.ts
index 18ada68c7..722001f69 100644
--- a/sdk/src/audio/Audio.ts
+++ b/sdk/src/audio/Audio.ts
@@ -1,43 +1,43 @@
import type { PlatformAudioBackend, AudioBufferHandle, AudioHandle } from './PlatformAudioBackend';
import type { AudioMixer } from './AudioMixer';
+import { defineResource } from '../resource';
import { log } from '../logger';
-export class Audio {
- private static backend_: PlatformAudioBackend;
- private static mixer_: AudioMixer | null = null;
- private static bufferCache_ = new Map<string, AudioBufferHandle>();
- private static bgmHandle_: AudioHandle | null = null;
- private static bgmVolume_ = 1.0;
- private static fadeAnimIds_ = new Set<number>();
- private static disposed_ = false;
- private static assetResolver_: ((url: string) => ArrayBuffer | null) | null = null;
- static baseUrl = '';
+/**
+ * Per-app audio API. Each `App` owns an `AudioAPI` instance (created by
+ * `AudioPlugin.build()`), exposed via the `Audio` resource.
+ *
+ * Consumed as a resource: declare `Res(Audio)` as a system param or
+ * grab it with `app.getResource(Audio)` outside ECS code.
+ */
+export class AudioAPI {
+ private readonly backend_: PlatformAudioBackend;
+ private readonly mixer_: AudioMixer | null;
+ private readonly bufferCache_ = new Map<string, AudioBufferHandle>();
+ private bgmHandle_: AudioHandle | null = null;
+ private bgmVolume_ = 1.0;
+ private readonly fadeAnimIds_ = new Set<number>();
+ private disposed_ = false;
+ private assetResolver_: ((url: string) => ArrayBuffer | null) | null = null;
+ baseUrl = '';
- static init(backend: PlatformAudioBackend, mixer: AudioMixer | null = null): void {
+ constructor(backend: PlatformAudioBackend, mixer: AudioMixer | null = null) {
this.backend_ = backend;
this.mixer_ = mixer;
- this.bufferCache_.clear();
- this.bgmHandle_ = null;
- this.bgmVolume_ = 1.0;
- this.disposed_ = false;
- for (const id of this.fadeAnimIds_) {
- cancelAnimationFrame(id);
- }
- this.fadeAnimIds_.clear();
}
- static setAssetResolver(resolver: (url: string) => ArrayBuffer | null): void {
+ setAssetResolver(resolver: (url: string) => ArrayBuffer | null): void {
this.assetResolver_ = resolver;
}
- private static resolveUrl_(url: string): string {
+ private resolveUrl_(url: string): string {
if (!this.baseUrl || url.startsWith('/') || url.startsWith('http://') || url.startsWith('https://')) {
return url;
}
return `${this.baseUrl}/${url}`;
}
- static async preload(url: string): Promise<void> {
+ async preload(url: string): Promise<void> {
if (this.bufferCache_.has(url)) return;
if (this.assetResolver_) {
const data = this.assetResolver_(url);
@@ -49,17 +49,17 @@ export class Audio {
this.bufferCache_.set(url, buffer);
}
- static async preloadAll(urls: string[]): Promise<void> {
+ async preloadAll(urls: string[]): Promise<void> {
await Promise.all(urls.map(url => this.preload(url)));
}
- static async preloadFromData(url: string, data: ArrayBuffer): Promise<void> {
+ async preloadFromData(url: string, data: ArrayBuffer): Promise<void> {
if (this.bufferCache_.has(url)) return;
const buffer = await this.backend_.loadBufferFromData(url, data);
this.bufferCache_.set(url, buffer);
}
- static playSFX(url: string, config?: {
+ playSFX(url: string, config?: {
volume?: number;
pitch?: number;
pan?: number;
@@ -74,7 +74,7 @@ export class Audio {
};
const buffer = this.bufferCache_.get(url);
if (!buffer) {
- const pending = this.createDeferredHandle();
+ const pending = this.createDeferredHandle_();
this.preload(url).then(() => {
if (this.disposed_) return;
const buf = this.bufferCache_.get(url);
@@ -89,7 +89,7 @@ export class Audio {
return this.backend_.play(buffer, playConfig);
}
- static playBGM(url: string, config?: {
+ playBGM(url: string, config?: {
volume?: number;
fadeIn?: number;
crossFade?: number;
@@ -105,7 +105,7 @@ export class Audio {
this.bgmVolume_ = targetVolume;
if (this.bgmHandle_ && config?.crossFade) {
- this.fadeOut(this.bgmHandle_, config.crossFade, oldVolume);
+ this.fadeOut_(this.bgmHandle_, config.crossFade, oldVolume);
} else if (this.bgmHandle_) {
this.bgmHandle_.stop();
}
@@ -118,7 +118,7 @@ export class Audio {
});
if (fadeInDuration) {
- this.fadeIn(this.bgmHandle_, fadeInDuration, targetVolume);
+ this.fadeIn_(this.bgmHandle_, fadeInDuration, targetVolume);
}
};
@@ -138,7 +138,7 @@ export class Audio {
}
}
- static stopAll(): void {
+ stopAll(): void {
for (const id of this.fadeAnimIds_) {
cancelAnimationFrame(id);
}
@@ -149,7 +149,7 @@ export class Audio {
}
}
- static stopBGM(fadeOut?: number): void {
+ stopBGM(fadeOut?: number): void {
if (!this.bgmHandle_) return;
for (const id of this.fadeAnimIds_) {
cancelAnimationFrame(id);
@@ -158,49 +158,49 @@ export class Audio {
if (fadeOut && fadeOut > 0) {
const handle = this.bgmHandle_;
this.bgmHandle_ = null;
- this.fadeOut(handle, fadeOut, this.bgmVolume_);
+ this.fadeOut_(handle, fadeOut, this.bgmVolume_);
} else {
this.bgmHandle_.stop();
this.bgmHandle_ = null;
}
}
- static setMasterVolume(volume: number): void {
+ setMasterVolume(volume: number): void {
if (this.mixer_) {
this.mixer_.master.volume = volume;
}
}
- static setMusicVolume(volume: number): void {
+ setMusicVolume(volume: number): void {
if (this.mixer_) {
this.mixer_.music.volume = volume;
}
}
- static setSFXVolume(volume: number): void {
+ setSFXVolume(volume: number): void {
if (this.mixer_) {
this.mixer_.sfx.volume = volume;
}
}
- static setUIVolume(volume: number): void {
+ setUIVolume(volume: number): void {
if (this.mixer_) {
this.mixer_.ui.volume = volume;
}
}
- static muteBus(busName: string, muted: boolean): void {
+ muteBus(busName: string, muted: boolean): void {
const bus = this.mixer_?.getBus(busName);
if (bus) {
bus.muted = muted;
}
}
- static getBufferHandle(url: string): AudioBufferHandle | undefined {
+ getBufferHandle(url: string): AudioBufferHandle | undefined {
return this.bufferCache_.get(url);
}
- static dispose(): void {
+ dispose(): void {
this.disposed_ = true;
for (const id of this.fadeAnimIds_) {
cancelAnimationFrame(id);
@@ -215,10 +215,9 @@ export class Audio {
}
this.bufferCache_.clear();
this.backend_?.dispose();
- this.mixer_ = null;
}
- private static fadeIn(handle: AudioHandle, duration: number, targetVolume: number): void {
+ private fadeIn_(handle: AudioHandle, duration: number, targetVolume: number): void {
handle.setVolume(0);
const startTime = performance.now();
let animId = 0;
@@ -237,7 +236,7 @@ export class Audio {
this.fadeAnimIds_.add(animId);
}
- private static fadeOut(handle: AudioHandle, duration: number, startVolume: number): void {
+ private fadeOut_(handle: AudioHandle, duration: number, startVolume: number): void {
const startTime = performance.now();
let animId = 0;
const tick = () => {
@@ -256,7 +255,7 @@ export class Audio {
this.fadeAnimIds_.add(animId);
}
- private static createDeferredHandle(): AudioHandle & { resolve(real: AudioHandle): void } {
+ private createDeferredHandle_(): AudioHandle & { resolve(real: AudioHandle): void } {
let real: AudioHandle | null = null;
const handle: AudioHandle & { resolve(r: AudioHandle): void } = {
id: -1,
@@ -275,3 +274,6 @@ export class Audio {
return handle;
}
}
+
+/** Resource handle for the per-app audio API. */
+export const Audio = defineResource<AudioAPI>(null!, 'Audio');
diff --git a/sdk/src/audio/AudioPlugin.ts b/sdk/src/audio/AudioPlugin.ts
index 1f7eedcce..3f690d16c 100644
--- a/sdk/src/audio/AudioPlugin.ts
+++ b/sdk/src/audio/AudioPlugin.ts
@@ -2,7 +2,7 @@ import type { App, Plugin } from '../app';
import type { Entity } from '../types';
import { defineSystem, Schedule } from '../system';
import { Res, Time, type TimeData } from '../resource';
-import { Audio } from './Audio';
+import { Audio, AudioAPI } from './Audio';
import { AudioSource, AudioListener, type AudioSourceData, type AudioListenerData } from './AudioComponents';
import { WorldTransform, type WorldTransformData } from '../component';
import { getPlatform } from '../platform/base';
@@ -23,6 +23,7 @@ export class AudioPlugin implements Plugin {
private config_: AudioPluginConfig;
private activeSourceHandles_: Map<number, AudioHandle> | null = null;
private playedEntities_: Set<number> | null = null;
+ private audio_: AudioAPI | null = null;
constructor(config: AudioPluginConfig = {}) {
this.config_ = config;
@@ -37,7 +38,9 @@ export class AudioPlugin implements Plugin {
});
const mixer = backend.mixer;
- Audio.init(backend, mixer);
+ const audio = new AudioAPI(backend, mixer);
+ this.audio_ = audio;
+ app.insertResource(Audio, audio);
if (mixer) {
if (config.masterVolume !== undefined) mixer.master.volume = config.masterVolume;
@@ -65,8 +68,8 @@ export class AudioPlugin implements Plugin {
app.addSystemToSchedule(
Schedule.PreUpdate,
defineSystem(
- [Res(Time)],
- (_time: TimeData) => {
+ [Res(Time), Res(Audio)],
+ (_time: TimeData, audioAPI: AudioAPI) => {
const playMode = !isEditor() || isPlayMode();
if (!playMode) {
@@ -105,7 +108,7 @@ export class AudioPlugin implements Plugin {
liveEntities.add(id);
if (source.playOnAwake && !playedEntities.has(id) && !activeSourceHandles.has(id) && backend.isReady) {
- const buffer = Audio.getBufferHandle(source.clip);
+ const buffer = audioAPI.getBufferHandle(source.clip);
if (buffer) {
const handle = backend.play(buffer, {
bus: source.bus,
@@ -184,7 +187,8 @@ export class AudioPlugin implements Plugin {
cleanup(): void {
this.stopAllSources();
- Audio.dispose();
+ this.audio_?.dispose();
+ this.audio_ = null;
}
}
diff --git a/sdk/src/audio/index.ts b/sdk/src/audio/index.ts
index 9e4fccb59..61fdbc855 100644
--- a/sdk/src/audio/index.ts
+++ b/sdk/src/audio/index.ts
@@ -1,4 +1,4 @@
-export { Audio } from './Audio';
+export { Audio, AudioAPI } from './Audio';
export { AudioBus, type AudioBusConfig } from './AudioBus';
export { AudioMixer, type AudioMixerConfig } from './AudioMixer';
export { AudioPool, type PooledAudioNode } from './AudioPool';
diff --git a/sdk/src/core-content.ts b/sdk/src/core-content.ts
index 3cc7b4a90..3903d5566 100644
--- a/sdk/src/core-content.ts
+++ b/sdk/src/core-content.ts
@@ -160,13 +160,13 @@ export { PreviewPlugin, WebAssetProvider } from './preview';
export {
Tween,
+ TweenAPI,
TweenHandle,
EasingType,
TweenTarget,
TweenState,
LoopMode,
- initTweenAPI,
- shutdownTweenAPI,
+ ValueTweenHandle,
SpriteAnimator,
spriteAnimatorSystemUpdate,
registerAnimClip,
@@ -190,7 +190,8 @@ export {
removeAnimEventListeners,
TweenGroup,
TweenSequence,
- TweenCompose,
+ type Completable,
+ type TweenFactory,
} from './animation';
// =============================================================================
@@ -199,6 +200,7 @@ export {
export {
Audio,
+ AudioAPI,
AudioPlugin,
audioPlugin,
AudioSource,
@@ -229,8 +231,7 @@ export {
export {
Particle,
- initParticleAPI,
- shutdownParticleAPI,
+ ParticleAPI,
ParticlePlugin,
particlePlugin,
} from './particle';
diff --git a/sdk/src/particle/ParticleAPI.ts b/sdk/src/particle/ParticleAPI.ts
index d5bd749bd..d536e369f 100644
--- a/sdk/src/particle/ParticleAPI.ts
+++ b/sdk/src/particle/ParticleAPI.ts
@@ -1,42 +1,44 @@
import type { ESEngineModule, CppRegistry } from '../wasm';
import type { Entity } from '../types';
+import { defineResource } from '../resource';
+
+/**
+ * Per-app particle API. Wraps the C++ registry-scoped particle system
+ * so two App instances (e.g. editor tabs previewing different scenes)
+ * can drive independent simulations without cross-talk.
+ *
+ * Consumed as a resource: declare `Res(Particle)` as a system param, or
+ * grab it with `app.getResource(Particle)` outside ECS code.
+ */
+export class ParticleAPI {
+ private readonly module_: ESEngineModule;
+ private readonly registry_: CppRegistry;
+
+ constructor(module: ESEngineModule, registry: CppRegistry) {
+ this.module_ = module;
+ this.registry_ = registry;
+ }
-let module: ESEngineModule | null = null;
-let registry: CppRegistry | null = null;
-
-export function initParticleAPI(m: ESEngineModule, r: CppRegistry): void {
- module = m;
- registry = r;
-}
-
-export function shutdownParticleAPI(): void {
- module = null;
- registry = null;
-}
-
-export const Particle = {
update(dt: number): void {
- if (!module || !registry) return;
- module.particle_update?.(registry, dt);
- },
+ this.module_.particle_update?.(this.registry_, dt);
+ }
play(entity: Entity): void {
- if (!module || !registry) return;
- module.particle_play?.(registry, entity as number);
- },
+ this.module_.particle_play?.(this.registry_, entity as number);
+ }
stop(entity: Entity): void {
- if (!module || !registry) return;
- module.particle_stop?.(registry, entity as number);
- },
+ this.module_.particle_stop?.(this.registry_, entity as number);
+ }
reset(entity: Entity): void {
- if (!module || !registry) return;
- module.particle_reset?.(registry, entity as number);
- },
+ this.module_.particle_reset?.(this.registry_, entity as number);
+ }
getAliveCount(entity: Entity): number {
- if (!module) return 0;
- return module.particle_getAliveCount?.(entity as number) ?? 0;
- },
-};
+ return this.module_.particle_getAliveCount?.(entity as number) ?? 0;
+ }
+}
+
+/** Resource handle for the per-app particle API. */
+export const Particle = defineResource<ParticleAPI>(null!, 'Particle');
diff --git a/sdk/src/particle/ParticlePlugin.ts b/sdk/src/particle/ParticlePlugin.ts
index bd78fd3bf..a21a26f68 100644
--- a/sdk/src/particle/ParticlePlugin.ts
+++ b/sdk/src/particle/ParticlePlugin.ts
@@ -3,7 +3,7 @@ import { defineSystem, Schedule } from '../system';
import { Res } from '../resource';
import { Time, type TimeData } from '../resource';
import type { ESEngineModule, CppRegistry } from '../wasm';
-import { initParticleAPI, shutdownParticleAPI, Particle } from './ParticleAPI';
+import { Particle, ParticleAPI } from './ParticleAPI';
export class ParticlePlugin implements Plugin {
name = 'particle';
@@ -11,20 +11,16 @@ export class ParticlePlugin implements Plugin {
build(app: App): void {
const module = app.wasmModule as ESEngineModule;
const registry = app.world.getCppRegistry() as CppRegistry;
- initParticleAPI(module, registry);
+ app.insertResource(Particle, new ParticleAPI(module, registry));
app.addSystemToSchedule(Schedule.Update, defineSystem(
- [Res(Time)],
- (time: TimeData) => {
- Particle.update(time.delta);
+ [Res(Time), Res(Particle)],
+ (time: TimeData, particle: ParticleAPI) => {
+ particle.update(time.delta);
},
{ name: 'ParticleSystem' }
));
}
-
- cleanup(): void {
- shutdownParticleAPI();
- }
}
export const particlePlugin = new ParticlePlugin();
diff --git a/sdk/src/particle/index.ts b/sdk/src/particle/index.ts
index f20007edb..2b51cf1cc 100644
--- a/sdk/src/particle/index.ts
+++ b/sdk/src/particle/index.ts
@@ -1,2 +1,2 @@
-export { Particle, initParticleAPI, shutdownParticleAPI } from './ParticleAPI';
+export { Particle, ParticleAPI } from './ParticleAPI';
export { ParticlePlugin, particlePlugin } from './ParticlePlugin';
diff --git a/sdk/src/playableRuntime.ts b/sdk/src/playableRuntime.ts
index 4a03173ef..4c1aac39b 100644
--- a/sdk/src/playableRuntime.ts
+++ b/sdk/src/playableRuntime.ts
@@ -203,11 +203,13 @@ export async function initPlayableRuntime(config: PlayableRuntimeConfig): Promis
const provider = new EmbeddedAssetProvider(assets);
- Audio.setAssetResolver((url: string) => {
- const dataUrl = assets[url];
- if (!dataUrl) return null;
- return decodeDataUrlBinary(dataUrl).buffer as ArrayBuffer;
- });
+ if (app.hasResource(Audio)) {
+ app.getResource(Audio).setAssetResolver((url: string) => {
+ const dataUrl = assets[url];
+ if (!dataUrl) return null;
+ return decodeDataUrlBinary(dataUrl).buffer as ArrayBuffer;
+ });
+ }
await initRuntime({
app,
diff --git a/sdk/src/runtimeLoader.ts b/sdk/src/runtimeLoader.ts
index 873ccbab7..41147436a 100644
--- a/sdk/src/runtimeLoader.ts
+++ b/sdk/src/runtimeLoader.ts
@@ -343,8 +343,13 @@ async function loadMaterials(
// Audio Helpers
// =============================================================================
-async function preloadAudioClips(provider: RuntimeAssetProvider, audioPaths: Set<string>): Promise<void> {
+async function preloadAudioClips(app: App, provider: RuntimeAssetProvider, audioPaths: Set<string>): Promise<void> {
if (audioPaths.size === 0) return;
+ if (!app.hasResource(Audio)) {
+ log.warn('runtime', 'No Audio resource; skipping audio preload (AudioPlugin not installed?)');
+ return;
+ }
+ const audio = app.getResource(Audio);
const paths = [...audioPaths];
@@ -352,13 +357,13 @@ async function preloadAudioClips(provider: RuntimeAssetProvider, audioPaths: Set
await Promise.all(paths.map(async (path) => {
try {
const binary = await provider.readBinary(path);
- await Audio.preloadFromData(path, binary.buffer as ArrayBuffer);
+ await audio.preloadFromData(path, binary.buffer as ArrayBuffer);
} catch (err) {
log.warn('runtime', `Failed to preload audio: ${path}`, err);
}
}));
} else {
- await Audio.preloadAll(paths).catch(err => {
+ await audio.preloadAll(paths).catch(err => {
log.warn('runtime', 'Failed to preload audio assets', err);
});
}
@@ -489,7 +494,7 @@ export async function loadRuntimeScene(options: LoadRuntimeSceneOptions): Promis
const materialCache = await loadMaterials(provider, getAssetPathsByType(discovered, 'material'));
await loadAnimClips(module, provider, getAssetPathsByType(discovered, 'anim-clip'));
await loadTilemaps(module, provider, getAssetPathsByType(discovered, 'tilemap'));
- await preloadAudioClips(provider, getAssetPathsByType(discovered, 'audio'));
+ await preloadAudioClips(app, provider, getAssetPathsByType(discovered, 'audio'));
resolveSceneAssetPaths(sceneData, textureCache, fontCache, materialCache);
const entityMap = loadSceneData(app.world, sceneData);
diff --git a/sdk/src/timeline/TimelinePlugin.ts b/sdk/src/timeline/TimelinePlugin.ts
index a33bde153..451557358 100644
--- a/sdk/src/timeline/TimelinePlugin.ts
+++ b/sdk/src/timeline/TimelinePlugin.ts
@@ -4,6 +4,7 @@ import { Res } from '../resource';
import { Time, type TimeData } from '../resource';
import { defineComponent, getComponent } from '../component';
import { playModeOnly } from '../env';
+import { Audio, type AudioAPI } from '../audio/Audio';
import { WrapMode, TrackType, type TimelineAsset, type AnimFramesTrack } from './TimelineTypes';
import { parseTimelineAsset } from './TimelineLoader';
import { uploadTimelineToWasm, type UploadResult } from './TimelineUploader';
@@ -104,6 +105,7 @@ export class TimelinePlugin implements Plugin {
setTimelineModule(module);
const registry = world.getCppRegistry() as any;
+ const audio: AudioAPI | null = app.hasResource(Audio) ? app.getResource(Audio) : null;
const entities = world.getEntitiesWithComponents([TimelinePlayer]);
for (const entity of entities) {
@@ -148,7 +150,7 @@ export class TimelinePlugin implements Plugin {
const wrapModeNum = WRAP_MODE_MAP[playerData.wrapMode] ?? WrapMode.Once;
module._tl_setWrapMode(handle, wrapModeNum);
- advanceAndProcess(world, module, handle, entity, time.delta, playerData.speed, uploadResult);
+ advanceAndProcess(world, module, handle, entity, time.delta, playerData.speed, uploadResult, audio);
this.processAnimFrames(world, module, entity, handle, playerData.timeline);
if (!module._tl_isPlaying(handle) && playerData.playing) {
diff --git a/sdk/src/timeline/TimelineRuntime.ts b/sdk/src/timeline/TimelineRuntime.ts
index 52c6d326d..d05151595 100644
--- a/sdk/src/timeline/TimelineRuntime.ts
+++ b/sdk/src/timeline/TimelineRuntime.ts
@@ -1,6 +1,6 @@
import { getComponent, SpineAnimation } from '../component';
import { SpriteAnimator } from '../animation/SpriteAnimator';
-import { Audio } from '../audio';
+import type { AudioAPI } from '../audio/Audio';
import { uploadTimelineToWasm, type UploadResult } from './TimelineUploader';
import type { TimelineAsset } from './TimelineTypes';
import type { ESEngineModule } from '../wasm';
@@ -101,7 +101,7 @@ function decodeEventString(module: ESEngineModule, index: number): string {
return new TextDecoder().decode(bytes);
}
-export function processTimelineEvents(world: any, module: ESEngineModule): void {
+export function processTimelineEvents(world: any, module: ESEngineModule, audio: AudioAPI | null = null): void {
const count = module._tl_getEventCount();
for (let i = 0; i < count; i++) {
const type = module._tl_getEventType(i);
@@ -143,8 +143,8 @@ export function processTimelineEvents(world: any, module: ESEngineModule): void
case TimelineEventType.AudioPlay: {
const clipPath = decodeEventString(module, i);
const volume = module._tl_getEventFloatParam(i);
- if (clipPath) {
- Audio.playSFX(clipPath, { volume });
+ if (clipPath && audio) {
+ audio.playSFX(clipPath, { volume });
}
break;
}
@@ -201,12 +201,13 @@ export function advanceAndProcess(
handle: number, entity: Entity,
dt: number, speed: number,
uploadResult: UploadResult,
+ audio: AudioAPI | null = null,
): void {
module._tl_advance(
world.getCppRegistry() as any,
handle, entity, dt, speed,
);
- processTimelineEvents(world, module);
+ processTimelineEvents(world, module, audio);
processCustomProperties(world, module, uploadResult);
module._tl_clearResults();
}
diff --git a/sdk/tests/audio-api.test.ts b/sdk/tests/audio-api.test.ts
index c25d14a71..76206bcb2 100644
--- a/sdk/tests/audio-api.test.ts
+++ b/sdk/tests/audio-api.test.ts
@@ -1,5 +1,5 @@
import { describe, it, expect, beforeEach, vi } from 'vitest';
-import { Audio } from '../src/audio/Audio';
+import { AudioAPI } from '../src/audio/Audio';
import type { PlatformAudioBackend, AudioHandle, AudioBufferHandle, PlayConfig } from '../src/audio/PlatformAudioBackend';
import type { AudioMixer } from '../src/audio/AudioMixer';
import type { AudioBus } from '../src/audio/AudioBus';
@@ -67,40 +67,41 @@ function createMockMixer(): AudioMixer {
} as unknown as AudioMixer;
}
-describe('Audio', () => {
+describe('AudioAPI', () => {
let backend: PlatformAudioBackend;
let mixer: AudioMixer;
+ let audio: AudioAPI;
beforeEach(() => {
backend = createMockBackend();
mixer = createMockMixer();
- Audio.init(backend, mixer);
+ audio = new AudioAPI(backend, mixer);
});
describe('preload', () => {
it('should load buffer via backend', async () => {
- await Audio.preload('sfx.mp3');
+ await audio.preload('sfx.mp3');
expect(backend.loadBuffer).toHaveBeenCalledWith('sfx.mp3');
});
it('should not reload already cached buffer', async () => {
- await Audio.preload('sfx.mp3');
- await Audio.preload('sfx.mp3');
+ await audio.preload('sfx.mp3');
+ await audio.preload('sfx.mp3');
expect(backend.loadBuffer).toHaveBeenCalledTimes(1);
});
});
describe('preloadAll', () => {
it('should load multiple buffers in parallel', async () => {
- await Audio.preloadAll(['a.mp3', 'b.mp3', 'c.mp3']);
+ await audio.preloadAll(['a.mp3', 'b.mp3', 'c.mp3']);
expect(backend.loadBuffer).toHaveBeenCalledTimes(3);
});
});
describe('playSFX', () => {
it('should play from cached buffer', async () => {
- await Audio.preload('click.mp3');
- const handle = Audio.playSFX('click.mp3', { volume: 0.5 });
+ await audio.preload('click.mp3');
+ const handle = audio.playSFX('click.mp3', { volume: 0.5 });
expect(backend.play).toHaveBeenCalledWith(
{ id: 1, duration: 2.0 },
expect.objectContaining({ bus: 'sfx', volume: 0.5 })
@@ -108,17 +109,17 @@ describe('Audio', () => {
});
it('should return deferred handle for uncached buffer', () => {
- const handle = Audio.playSFX('uncached.mp3');
+ const handle = audio.playSFX('uncached.mp3');
expect(handle.id).toBe(-1);
expect(handle.isPlaying).toBe(false);
});
it('should delegate deferred handle methods after resolve', async () => {
- await Audio.preload('deferred.mp3');
+ await audio.preload('deferred.mp3');
const mockHandle = createMockHandle({ id: 42 });
(backend.play as ReturnType<typeof vi.fn>).mockReturnValue(mockHandle);
- const handle = Audio.playSFX('deferred.mp3');
+ const handle = audio.playSFX('deferred.mp3');
handle.stop();
expect(mockHandle.stop).toHaveBeenCalled();
});
@@ -126,8 +127,8 @@ describe('Audio', () => {
describe('playBGM', () => {
it('should play as looping music', async () => {
- await Audio.preload('bgm.mp3');
- Audio.playBGM('bgm.mp3');
+ await audio.preload('bgm.mp3');
+ audio.playBGM('bgm.mp3');
expect(backend.play).toHaveBeenCalledWith(
{ id: 1, duration: 2.0 },
expect.objectContaining({ bus: 'music', loop: true })
@@ -135,14 +136,14 @@ describe('Audio', () => {
});
it('should stop previous BGM', async () => {
- await Audio.preload('bgm1.mp3');
+ await audio.preload('bgm1.mp3');
const firstHandle = createMockHandle();
(backend.play as ReturnType<typeof vi.fn>).mockReturnValue(firstHandle);
- Audio.playBGM('bgm1.mp3');
+ audio.playBGM('bgm1.mp3');
const secondHandle = createMockHandle();
(backend.play as ReturnType<typeof vi.fn>).mockReturnValue(secondHandle);
- Audio.playBGM('bgm1.mp3');
+ audio.playBGM('bgm1.mp3');
expect(firstHandle.stop).toHaveBeenCalled();
});
@@ -150,56 +151,56 @@ describe('Audio', () => {
describe('stopBGM', () => {
it('should stop current BGM', async () => {
- await Audio.preload('bgm.mp3');
+ await audio.preload('bgm.mp3');
const mockHandle = createMockHandle();
(backend.play as ReturnType<typeof vi.fn>).mockReturnValue(mockHandle);
- Audio.playBGM('bgm.mp3');
- Audio.stopBGM();
+ audio.playBGM('bgm.mp3');
+ audio.stopBGM();
expect(mockHandle.stop).toHaveBeenCalled();
});
it('should do nothing if no BGM playing', () => {
- expect(() => Audio.stopBGM()).not.toThrow();
+ expect(() => audio.stopBGM()).not.toThrow();
});
});
describe('volume controls', () => {
it('should set master volume', () => {
- Audio.setMasterVolume(0.5);
+ audio.setMasterVolume(0.5);
expect(mixer.master.volume).toBe(0.5);
});
it('should set music volume', () => {
- Audio.setMusicVolume(0.3);
+ audio.setMusicVolume(0.3);
expect(mixer.music.volume).toBe(0.3);
});
it('should set sfx volume', () => {
- Audio.setSFXVolume(0.7);
+ audio.setSFXVolume(0.7);
expect(mixer.sfx.volume).toBe(0.7);
});
it('should set ui volume', () => {
- Audio.setUIVolume(0.6);
+ audio.setUIVolume(0.6);
expect(mixer.ui.volume).toBe(0.6);
});
});
describe('muteBus', () => {
it('should mute specified bus', () => {
- Audio.muteBus('sfx', true);
+ audio.muteBus('sfx', true);
expect(mixer.getBus).toHaveBeenCalledWith('sfx');
});
});
describe('dispose', () => {
it('should stop BGM and dispose backend', async () => {
- await Audio.preload('bgm.mp3');
+ await audio.preload('bgm.mp3');
const mockHandle = createMockHandle();
(backend.play as ReturnType<typeof vi.fn>).mockReturnValue(mockHandle);
- Audio.playBGM('bgm.mp3');
+ audio.playBGM('bgm.mp3');
- Audio.dispose();
+ audio.dispose();
expect(mockHandle.stop).toHaveBeenCalled();
expect(backend.unloadBuffer).toHaveBeenCalled();
@@ -207,9 +208,9 @@ describe('Audio', () => {
});
it('should clear buffer cache', async () => {
- await Audio.preload('sfx.mp3');
- Audio.dispose();
- expect(Audio.getBufferHandle('sfx.mp3')).toBeUndefined();
+ await audio.preload('sfx.mp3');
+ audio.dispose();
+ expect(audio.getBufferHandle('sfx.mp3')).toBeUndefined();
});
it('should prevent in-flight preloads from playing after dispose', async () => {
@@ -218,8 +219,8 @@ describe('Audio', () => {
new Promise(r => { resolveLoad = r; })
);
- Audio.playSFX('slow.mp3');
- Audio.dispose();
+ audio.playSFX('slow.mp3');
+ audio.dispose();
resolveLoad({ id: 99, duration: 1.0 });
await new Promise(r => setTimeout(r, 0));
@@ -230,4 +231,18 @@ describe('Audio', () => {
);
});
});
+
+ describe('isolation', () => {
+ it('two AudioAPI instances keep independent buffer caches', async () => {
+ const backend2 = createMockBackend();
+ const audio2 = new AudioAPI(backend2, createMockMixer());
+
+ await audio.preload('a.mp3');
+ expect(backend.loadBuffer).toHaveBeenCalledTimes(1);
+ expect(backend2.loadBuffer).not.toHaveBeenCalled();
+
+ await audio2.preload('a.mp3');
+ expect(backend2.loadBuffer).toHaveBeenCalledTimes(1);
+ });
+ });
});
diff --git a/sdk/tests/audio-plugin.test.ts b/sdk/tests/audio-plugin.test.ts
index 60545b74d..13eae1b7b 100644
--- a/sdk/tests/audio-plugin.test.ts
+++ b/sdk/tests/audio-plugin.test.ts
@@ -1,6 +1,6 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { AudioPlugin, audioPlugin } from '../src/audio/AudioPlugin';
-import { Audio } from '../src/audio/Audio';
+import { AudioAPI } from '../src/audio/Audio';
import type { AudioHandle, AudioBufferHandle, PlatformAudioBackend } from '../src/audio/PlatformAudioBackend';
import type { AudioMixer } from '../src/audio/AudioMixer';
import type { AudioBus } from '../src/audio/AudioBus';
@@ -70,7 +70,7 @@ describe('AudioPlugin', () => {
expect(audioPlugin).toBeInstanceOf(AudioPlugin);
});
- it('should have name "AudioPlugin"', () => {
+ it('should have name "audio"', () => {
expect(audioPlugin.name).toBe('audio');
});
@@ -88,14 +88,6 @@ describe('AudioPlugin', () => {
expect(plugin.name).toBe('audio');
});
- it('should call Audio.dispose on cleanup', () => {
- const disposeSpy = vi.spyOn(Audio, 'dispose').mockImplementation(() => {});
- const plugin = new AudioPlugin();
- plugin.cleanup();
- expect(disposeSpy).toHaveBeenCalled();
- disposeSpy.mockRestore();
- });
-
describe('stopAllSources', () => {
it('should stop all active handles and clear the map', () => {
const plugin = new AudioPlugin();
@@ -132,10 +124,16 @@ describe('AudioPlugin', () => {
});
describe('cleanup', () => {
- it('should call stopAllSources then Audio.dispose', () => {
+ it('should call stopAllSources then dispose the owned AudioAPI instance', () => {
const plugin = new AudioPlugin();
+ const backend = createMockBackend();
+ const audio = new AudioAPI(backend, backend.mixer);
+ (plugin as any).audio_ = audio;
+ (plugin as any).activeSourceHandles_ = new Map();
+ (plugin as any).playedEntities_ = new Set();
+
const stopSpy = vi.spyOn(plugin, 'stopAllSources');
- const disposeSpy = vi.spyOn(Audio, 'dispose').mockImplementation(() => {});
+ const disposeSpy = vi.spyOn(audio, 'dispose');
plugin.cleanup();
@@ -144,49 +142,59 @@ describe('AudioPlugin', () => {
const stopOrder = stopSpy.mock.invocationCallOrder[0];
const disposeOrder = disposeSpy.mock.invocationCallOrder[0];
expect(stopOrder).toBeLessThan(disposeOrder);
+ });
+
+ it('should clear the audio_ reference after dispose', () => {
+ const plugin = new AudioPlugin();
+ const backend = createMockBackend();
+ (plugin as any).audio_ = new AudioAPI(backend, backend.mixer);
+ (plugin as any).activeSourceHandles_ = new Map();
+ (plugin as any).playedEntities_ = new Set();
+
+ plugin.cleanup();
- stopSpy.mockRestore();
- disposeSpy.mockRestore();
+ expect((plugin as any).audio_).toBeNull();
});
});
});
-describe('Audio.stopAll', () => {
+describe('AudioAPI.stopAll', () => {
let backend: PlatformAudioBackend;
+ let audio: AudioAPI;
beforeEach(() => {
backend = createMockBackend();
- Audio.init(backend, backend.mixer);
+ audio = new AudioAPI(backend, backend.mixer);
});
it('should stop BGM without disposing backend', async () => {
- await Audio.preload('bgm.mp3');
+ await audio.preload('bgm.mp3');
const bgmHandle = createMockHandle();
(backend.play as ReturnType<typeof vi.fn>).mockReturnValue(bgmHandle);
- Audio.playBGM('bgm.mp3');
+ audio.playBGM('bgm.mp3');
- Audio.stopAll();
+ audio.stopAll();
expect(bgmHandle.stop).toHaveBeenCalled();
expect(backend.dispose).not.toHaveBeenCalled();
- expect(Audio.getBufferHandle('bgm.mp3')).toBeDefined();
+ expect(audio.getBufferHandle('bgm.mp3')).toBeDefined();
});
it('should allow playing new BGM after stopAll', async () => {
- await Audio.preload('bgm.mp3');
+ await audio.preload('bgm.mp3');
const firstHandle = createMockHandle();
(backend.play as ReturnType<typeof vi.fn>).mockReturnValue(firstHandle);
- Audio.playBGM('bgm.mp3');
- Audio.stopAll();
+ audio.playBGM('bgm.mp3');
+ audio.stopAll();
const secondHandle = createMockHandle();
(backend.play as ReturnType<typeof vi.fn>).mockReturnValue(secondHandle);
- Audio.playBGM('bgm.mp3');
+ audio.playBGM('bgm.mp3');
expect(backend.play).toHaveBeenCalledTimes(2);
});
it('should be safe to call when no audio is playing', () => {
- expect(() => Audio.stopAll()).not.toThrow();
+ expect(() => audio.stopAll()).not.toThrow();
});
});
diff --git a/sdk/tests/playableRuntime.test.ts b/sdk/tests/playableRuntime.test.ts
index e51edf535..031503633 100644
--- a/sdk/tests/playableRuntime.test.ts
+++ b/sdk/tests/playableRuntime.test.ts
@@ -19,6 +19,7 @@ function createMockConfig(overrides?: Partial<PlayableRuntimeConfig>): PlayableR
getResource: vi.fn().mockReturnValue({
registerEmbeddedAssets: vi.fn(),
setEmbeddedOnly: vi.fn(),
+ setAssetResolver: vi.fn(),
}),
hasResource: vi.fn().mockReturnValue(true),
run: vi.fn(),
diff --git a/sdk/tests/tween-group.test.ts b/sdk/tests/tween-group.test.ts
index 5e1458ac5..86ce45bb8 100644
--- a/sdk/tests/tween-group.test.ts
+++ b/sdk/tests/tween-group.test.ts
@@ -1,5 +1,5 @@
import { describe, it, expect, vi } from 'vitest';
-import { TweenGroup, TweenSequence, TweenCompose, tweenCompositionManager } from '../src/animation/TweenGroup';
+import { TweenGroup, TweenSequence, TweenCompositionManager } from '../src/animation/TweenGroup';
import { TweenState } from '../src/animation/TweenTypes';
function mockTween(doneAfter: number) {
@@ -133,18 +133,35 @@ describe('TweenSequence', () => {
});
});
-describe('TweenCompose', () => {
- it('parallel() registers with composition manager', () => {
- const initial = tweenCompositionManager.activeCount;
- TweenCompose.parallel([mockTween(1)]);
- expect(tweenCompositionManager.activeCount).toBe(initial + 1);
- tweenCompositionManager.clear();
+describe('TweenCompositionManager', () => {
+ it('add() tracks a group', () => {
+ const mgr = new TweenCompositionManager();
+ mgr.add(new TweenGroup([mockTween(1)]));
+ expect(mgr.activeCount).toBe(1);
});
- it('sequence() registers with composition manager', () => {
- const initial = tweenCompositionManager.activeCount;
- TweenCompose.sequence([() => mockTween(1)]);
- expect(tweenCompositionManager.activeCount).toBe(initial + 1);
- tweenCompositionManager.clear();
+ it('add() tracks a sequence', () => {
+ const mgr = new TweenCompositionManager();
+ mgr.add(new TweenSequence([() => mockTween(1)]));
+ expect(mgr.activeCount).toBe(1);
+ });
+
+ it('update() drops completed items', () => {
+ const mgr = new TweenCompositionManager();
+ const a = mockTween(0);
+ a.tick(1);
+ const group = new TweenGroup([a]);
+ mgr.add(group);
+ expect(mgr.activeCount).toBe(1);
+ mgr.update();
+ expect(mgr.activeCount).toBe(0);
+ });
+
+ it('clear() empties the set', () => {
+ const mgr = new TweenCompositionManager();
+ mgr.add(new TweenGroup([mockTween(1)]));
+ mgr.add(new TweenSequence([() => mockTween(1)]));
+ mgr.clear();
+ expect(mgr.activeCount).toBe(0);
});
});
diff --git a/sdk/tests/tween.test.ts b/sdk/tests/tween.test.ts
index ba6f5fc69..d16551c17 100644
--- a/sdk/tests/tween.test.ts
+++ b/sdk/tests/tween.test.ts
@@ -1,15 +1,13 @@
-import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+import { describe, it, expect, beforeEach, vi } from 'vitest';
import type { ESEngineModule, CppRegistry } from '../src/wasm';
import type { Entity } from '../src/types';
import {
- Tween,
+ TweenAPI,
TweenHandle,
EasingType,
TweenTarget,
TweenState,
LoopMode,
- initTweenAPI,
- shutdownTweenAPI,
} from '../src/animation/Tween';
function createMockAnimModule() {
@@ -44,16 +42,13 @@ function createMockAnimModule() {
describe('Tween API', () => {
let module: ESEngineModule;
let registry: CppRegistry;
+ let tween: TweenAPI;
beforeEach(() => {
const mock = createMockAnimModule();
module = mock.module;
registry = mock.registry;
- initTweenAPI(module, registry);
- });
-
- afterEach(() => {
- shutdownTweenAPI();
+ tween = new TweenAPI(module, registry);
});
// =========================================================================
@@ -92,13 +87,13 @@ describe('Tween API', () => {
});
// =========================================================================
- // Tween.to()
+ // tween.to()
// =========================================================================
- describe('Tween.to()', () => {
+ describe('tween.to()', () => {
it('should call WASM createTween with correct params', () => {
const entity = 42 as Entity;
- Tween.to(entity, TweenTarget.PositionX, 0, 100, 1.5);
+ tween.to(entity, TweenTarget.PositionX, 0, 100, 1.5);
expect(module._anim_createTween).toHaveBeenCalledWith(
registry, 42, TweenTarget.PositionX,
@@ -108,7 +103,7 @@ describe('Tween API', () => {
});
it('should pass easing option', () => {
- Tween.to(1 as Entity, TweenTarget.ColorA, 1, 0, 0.5, {
+ tween.to(1 as Entity, TweenTarget.ColorA, 1, 0, 0.5, {
easing: EasingType.EaseOutQuad,
});
@@ -120,7 +115,7 @@ describe('Tween API', () => {
});
it('should pass delay option', () => {
- Tween.to(1 as Entity, TweenTarget.ScaleX, 1, 2, 1, {
+ tween.to(1 as Entity, TweenTarget.ScaleX, 1, 2, 1, {
delay: 0.5,
});
@@ -132,7 +127,7 @@ describe('Tween API', () => {
});
it('should pass loop options', () => {
- Tween.to(1 as Entity, TweenTarget.PositionY, 0, 50, 2, {
+ tween.to(1 as Entity, TweenTarget.PositionY, 0, 50, 2, {
loop: LoopMode.PingPong,
loopCount: 3,
});
@@ -145,7 +140,7 @@ describe('Tween API', () => {
});
it('should return a TweenHandle', () => {
- const handle = Tween.to(1 as Entity, TweenTarget.PositionX, 0, 10, 1);
+ const handle = tween.to(1 as Entity, TweenTarget.PositionX, 0, 10, 1);
expect(handle).toBeInstanceOf(TweenHandle);
});
});
@@ -159,12 +154,12 @@ describe('Tween API', () => {
(module._anim_getTweenState as ReturnType<typeof vi.fn>)
.mockReturnValueOnce(TweenState.Paused);
- const handle = Tween.to(1 as Entity, TweenTarget.PositionX, 0, 10, 1);
+ const handle = tween.to(1 as Entity, TweenTarget.PositionX, 0, 10, 1);
expect(handle.state).toBe(TweenState.Paused);
});
it('should call WASM setBezier', () => {
- const handle = Tween.to(1 as Entity, TweenTarget.PositionX, 0, 10, 1);
+ const handle = tween.to(1 as Entity, TweenTarget.PositionX, 0, 10, 1);
handle.bezier(0.25, 0.1, 0.25, 1.0);
expect(module._anim_setTweenBezier).toHaveBeenCalledWith(
@@ -173,14 +168,14 @@ describe('Tween API', () => {
});
it('bezier() should return this for chaining', () => {
- const handle = Tween.to(1 as Entity, TweenTarget.PositionX, 0, 10, 1);
+ const handle = tween.to(1 as Entity, TweenTarget.PositionX, 0, 10, 1);
const result = handle.bezier(0, 0, 1, 1);
expect(result).toBe(handle);
});
it('should chain tweens with then()', () => {
- const h1 = Tween.to(1 as Entity, TweenTarget.PositionX, 0, 10, 1);
- const h2 = Tween.to(1 as Entity, TweenTarget.PositionY, 0, 20, 1);
+ const h1 = tween.to(1 as Entity, TweenTarget.PositionX, 0, 10, 1);
+ const h2 = tween.to(1 as Entity, TweenTarget.PositionY, 0, 20, 1);
h1.then(h2);
expect(module._anim_setSequenceNext).toHaveBeenCalledWith(
@@ -189,28 +184,28 @@ describe('Tween API', () => {
});
it('then() should return this for chaining', () => {
- const h1 = Tween.to(1 as Entity, TweenTarget.PositionX, 0, 10, 1);
- const h2 = Tween.to(1 as Entity, TweenTarget.PositionY, 0, 20, 1);
+ const h1 = tween.to(1 as Entity, TweenTarget.PositionX, 0, 10, 1);
+ const h2 = tween.to(1 as Entity, TweenTarget.PositionY, 0, 20, 1);
const result = h1.then(h2);
expect(result).toBe(h1);
});
it('should pause a tween', () => {
- const handle = Tween.to(1 as Entity, TweenTarget.PositionX, 0, 10, 1);
+ const handle = tween.to(1 as Entity, TweenTarget.PositionX, 0, 10, 1);
handle.pause();
expect(module._anim_pauseTween).toHaveBeenCalledWith(registry, handle.entity);
});
it('should resume a tween', () => {
- const handle = Tween.to(1 as Entity, TweenTarget.PositionX, 0, 10, 1);
+ const handle = tween.to(1 as Entity, TweenTarget.PositionX, 0, 10, 1);
handle.resume();
expect(module._anim_resumeTween).toHaveBeenCalledWith(registry, handle.entity);
});
it('should cancel a tween via handle', () => {
- const handle = Tween.to(1 as Entity, TweenTarget.PositionX, 0, 10, 1);
+ const handle = tween.to(1 as Entity, TweenTarget.PositionX, 0, 10, 1);
handle.cancel();
expect(module._anim_cancelTween).toHaveBeenCalledWith(registry, handle.entity);
@@ -218,48 +213,55 @@ describe('Tween API', () => {
});
// =========================================================================
- // Tween static methods
+ // Instance methods
// =========================================================================
- describe('static methods', () => {
- it('Tween.cancel() should delegate to WASM', () => {
- const handle = Tween.to(1 as Entity, TweenTarget.PositionX, 0, 10, 1);
- Tween.cancel(handle);
+ describe('instance methods', () => {
+ it('tween.cancel() should delegate to WASM', () => {
+ const handle = tween.to(1 as Entity, TweenTarget.PositionX, 0, 10, 1);
+ tween.cancel(handle);
expect(module._anim_cancelTween).toHaveBeenCalledWith(registry, handle.entity);
});
- it('Tween.cancelAll() should delegate to WASM', () => {
+ it('tween.cancelAll() should delegate to WASM', () => {
const entity = 5 as Entity;
- Tween.cancelAll(entity);
+ tween.cancelAll(entity);
expect(module._anim_cancelAllTweens).toHaveBeenCalledWith(registry, 5);
});
- it('Tween.update() should delegate to WASM', () => {
- Tween.update(0.016);
+ it('tween.update() should delegate to WASM', () => {
+ tween.update(0.016);
expect(module._anim_updateTweens).toHaveBeenCalledWith(registry, 0.016);
});
});
// =========================================================================
- // Lifecycle
+ // Per-app isolation
// =========================================================================
- describe('lifecycle', () => {
- it('should throw if used before init', () => {
- shutdownTweenAPI();
- expect(() => Tween.to(1 as Entity, TweenTarget.PositionX, 0, 10, 1))
- .toThrow('Tween API not initialized');
- });
+ describe('isolation', () => {
+ it('two TweenAPI instances drive independent WASM calls', () => {
+ const { module: module2, registry: registry2 } = createMockAnimModule();
+ const tween2 = new TweenAPI(module2, registry2);
- it('should work after re-init', () => {
- shutdownTweenAPI();
- initTweenAPI(module, registry);
+ tween.to(1 as Entity, TweenTarget.PositionX, 0, 10, 1);
+ tween2.to(2 as Entity, TweenTarget.PositionY, 0, 20, 1);
- expect(() => Tween.to(1 as Entity, TweenTarget.PositionX, 0, 10, 1))
- .not.toThrow();
+ expect(module._anim_createTween).toHaveBeenCalledTimes(1);
+ expect(module2._anim_createTween).toHaveBeenCalledTimes(1);
+ expect(module._anim_createTween).toHaveBeenCalledWith(
+ registry, 1, TweenTarget.PositionX,
+ 0, 10, 1,
+ EasingType.Linear, 0, LoopMode.None, 0,
+ );
+ expect(module2._anim_createTween).toHaveBeenCalledWith(
+ registry2, 2, TweenTarget.PositionY,
+ 0, 20, 1,
+ EasingType.Linear, 0, LoopMode.None, 0,
+ );
});
});
});