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: simplify SDK runtime loader and add renderer frame lifecycle
esengine3caa843c0d7e
diff --git a/sdk/src/app.ts b/sdk/src/app.tsindex 84139df11..b3678b4da 100644--- a/sdk/src/app.ts+++ b/sdk/src/app.ts@@ -23,7 +23,7 @@ import { setWasmErrorHandler } from './wasmError';import { platformNow, platformDevicePixelRatio } from './platform';import { ProjectionType, ScaleMode, SceneOwner } from './component';import type { Entity } from './types';-import { RenderPipeline, type SpineRendererFn } from './renderPipeline';+import { RenderPipeline } from './renderPipeline';import { Renderer } from './renderer';import { PostProcess } from './postprocess';import type { SceneConfig } from './sceneManager';@@ -110,6 +110,10 @@ export class App {// Plugins// =========================================================================+ getPlugin<T extends Plugin>(ctor: new (...args: any[]) => T): T | undefined {+ return this.installed_plugins_.find((p): p is T => p instanceof ctor);+ }+addPlugin(plugin: Plugin): this {if (this.installedPluginSet_.has(plugin)) return this;if (plugin.dependencies) {@@ -208,10 +212,6 @@ export class App {this.pipeline_ = pipeline;}- setSpineRenderer(fn: SpineRendererFn | null): void {- this.pipeline_?.setSpineRenderer(fn);- }-get spineInitPromise(): Promise<unknown> | undefined {return this.spineInitPromise_;}@@ -781,6 +781,7 @@ export function createWebApp(module: ESEngineModule, options?: WebAppOptions): Awidth, height, elapsed,});} else {+ pipeline.beginFrame();pipeline.beginScreenCapture();for (const cam of cameras) {const vp = cam.viewportRect;diff --git a/sdk/src/core.ts b/sdk/src/core.tsindex c89fed151..c650fe03c 100644--- a/sdk/src/core.ts+++ b/sdk/src/core.ts@@ -633,7 +633,6 @@ export {type Viewport,type RenderParams,type CameraRenderParams,- type SpineRendererFn,} from './renderPipeline';// =============================================================================diff --git a/sdk/src/playableRuntime.ts b/sdk/src/playableRuntime.tsindex 6178b5d0a..270584840 100644--- a/sdk/src/playableRuntime.ts+++ b/sdk/src/playableRuntime.ts@@ -11,13 +11,18 @@ import { Assets } from './asset/AssetPlugin';import type { AddressableManifest } from './asset/AssetServer';import type { Vec2 } from './types';import type { SpineWasmModule } from './spine/SpineModuleLoader';+import { SpineManager, type SpineVersion } from './spine/SpineManager';import type { PhysicsWasmModule } from './physics/PhysicsModuleLoader';import type { SceneData } from './scene';import { Audio } from './audio/Audio';-declare const ESSpineModule: ((opts: unknown) => Promise<SpineWasmModule>) | undefined;declare const ESPhysicsModule: ((opts: unknown) => Promise<PhysicsWasmModule>) | undefined;+export interface SpineModuleEntry {+ factory: (opts: unknown) => Promise<SpineWasmModule>;+ wasmBase64: string;+}+export interface PlayableRuntimeConfig {app: App;module: ESEngineModule;@@ -25,7 +30,7 @@ export interface PlayableRuntimeConfig {assets: Record<string, string>;scenes: Array<{ name: string; data: SceneData }>;firstScene: string;- spineWasmBase64?: string;+ spineModules?: Record<string, SpineModuleEntry>;physicsWasmBase64?: string;physicsConfig?: { gravity?: Vec2; fixedTimestep?: number; subStepCount?: number };manifest?: AddressableManifest | null;@@ -132,13 +137,6 @@ async function instantiateWasmModule(}}-async function initSpineModule(wasmBase64: string): Promise<SpineWasmModule | null> {- if (typeof ESSpineModule === 'undefined') return null;- const mod = await instantiateWasmModule(ESSpineModule, wasmBase64);- if (!mod) console.warn('Spine module not available');- return mod as SpineWasmModule | null;-}-async function initPhysicsModule(wasmBase64: string): Promise<PhysicsWasmModule | null> {if (typeof ESPhysicsModule === 'undefined') return null;const mod = await instantiateWasmModule(ESPhysicsModule, wasmBase64);@@ -146,6 +144,37 @@ async function initPhysicsModule(wasmBase64: string): Promise<PhysicsWasmModulereturn mod as PhysicsWasmModule | null;}+function buildSpineManager(+ module: ESEngineModule,+ spineModules: Record<string, SpineModuleEntry>,+): SpineManager {+ const factories = new Map<SpineVersion, () => Promise<SpineWasmModule>>();+ for (const [version, entry] of Object.entries(spineModules)) {+ const ver = version as SpineVersion;+ factories.set(ver, async () => {+ const wasmBytes = decodeBase64ToWasm(entry.wasmBase64);+ return entry.factory({+ instantiateWasm(imports: WebAssembly.Imports, cb: Function) {+ const response = new Response(wasmBytes.buffer as ArrayBuffer, {+ headers: { 'Content-Type': 'application/wasm' },+ });+ WebAssembly.instantiateStreaming(response, imports).then(+ r => cb(r.instance, r.module),+ () => {+ WebAssembly.instantiate(wasmBytes.buffer as ArrayBuffer, imports).then(+ r => cb((r as WebAssembly.WebAssemblyInstantiatedSource).instance,+ (r as WebAssembly.WebAssemblyInstantiatedSource).module),+ );+ },+ );+ return {};+ },+ }) as Promise<SpineWasmModule>;+ });+ }+ return new SpineManager(module, factories);+}+export async function initPlayableRuntime(config: PlayableRuntimeConfig): Promise<void> {const { app, module, assets, scenes, firstScene } = config;@@ -155,9 +184,10 @@ export async function initPlayableRuntime(config: PlayableRuntimeConfig): PromisassetServer.setEmbeddedOnly(true);}- const spineModule = config.spineWasmBase64- ? await initSpineModule(config.spineWasmBase64)- : null;+ let spineManager: SpineManager | null = null;+ if (config.spineModules && Object.keys(config.spineModules).length > 0) {+ spineManager = buildSpineManager(module, config.spineModules);+ }const physicsModule = config.physicsWasmBase64? await initPhysicsModule(config.physicsWasmBase64)@@ -177,7 +207,7 @@ export async function initPlayableRuntime(config: PlayableRuntimeConfig): Promisprovider,scenes,firstScene,- spineModule,+ spineManager,physicsModule,physicsConfig: config.physicsConfig,manifest: config.manifest,diff --git a/sdk/src/preview/PreviewPlugin.ts b/sdk/src/preview/PreviewPlugin.tsindex 1668f59f9..85298589f 100644--- a/sdk/src/preview/PreviewPlugin.ts+++ b/sdk/src/preview/PreviewPlugin.ts@@ -11,6 +11,7 @@ import { DEFAULT_DESIGN_WIDTH, DEFAULT_DESIGN_HEIGHT, DEFAULT_PIXELS_PER_UNIT }import { platformFetch } from '../platform';import { SceneManager } from '../sceneManager';import { WebAssetProvider } from './WebAssetProvider';+import { SpinePlugin } from '../spine/SpinePlugin';const PREVIEW_SCENE = '__preview__';@@ -70,19 +71,15 @@ export class PreviewPlugin implements Plugin {const provider = new WebAssetProvider(this.baseUrl_);await provider.prefetch(sceneData);- let spineModule = null;- const spinePromise = this.app_.spineInitPromise;- if (spinePromise) {- const result = await spinePromise as { controller: { raw: any }; coreModule: unknown };- spineModule = result.controller.raw;- }+ const spinePlugin = this.app_.getPlugin(SpinePlugin);+ const spineManager = spinePlugin?.spineManager ?? null;await loadRuntimeScene({app: this.app_,module: this.app_.wasmModule!,sceneData,provider,- spineModule,+ spineManager,sceneName: PREVIEW_SCENE,});}diff --git a/sdk/src/renderPipeline.ts b/sdk/src/renderPipeline.tsindex 3f0809fc5..ab8b634c7 100644--- a/sdk/src/renderPipeline.ts+++ b/sdk/src/renderPipeline.ts@@ -5,7 +5,7 @@import type { CppRegistry } from './wasm';import type { Entity } from './types';-import { Renderer, SubmitSkipFlags } from './renderer';+import { Renderer } from './renderer';import { PostProcess } from './postprocess';import { Draw } from './draw';import { getDrawCallbacks, unregisterDrawCallback } from './customDraw';@@ -34,31 +34,22 @@ export interface CameraRenderParams {cameraEntity?: Entity;}-export type SpineRendererFn = (registry: { _cpp: CppRegistry }, elapsed: number) => void;--export type TilemapRendererFn = () => void;-export class RenderPipeline {- private spineRenderer_: SpineRendererFn | null = null;- private tilemapRenderer_: TilemapRendererFn | null = null;private lastWidth_ = 0;private lastHeight_ = 0;private activeScenes_: Set<string> | null = null;+ private preFlushCallbacks_: ((registry: { _cpp: CppRegistry }) => void)[] = [];- get spineRenderer(): SpineRendererFn | null {- return this.spineRenderer_;- }-- setSpineRenderer(fn: SpineRendererFn | null): void {- this.spineRenderer_ = fn;+ setActiveScenes(scenes: Set<string> | null): void {+ this.activeScenes_ = scenes;}- setTilemapRenderer(fn: TilemapRendererFn | null): void {- this.tilemapRenderer_ = fn;+ addPreFlushCallback(cb: (registry: { _cpp: CppRegistry }) => void): void {+ this.preFlushCallbacks_.push(cb);}- setActiveScenes(scenes: Set<string> | null): void {- this.activeScenes_ = scenes;+ beginFrame(): void {+ Renderer.beginFrame();}beginScreenCapture(): void {@@ -82,21 +73,14 @@ export class RenderPipeline {registry: { _cpp: CppRegistry },viewProjection: Float32Array,viewport: Viewport,- elapsed: number,+ _elapsed: number,): void {- const skipFlags = this.spineRenderer_ ? SubmitSkipFlags.Spine : SubmitSkipFlags.None;- Renderer.submitAll(registry, skipFlags, viewport.x, viewport.y, viewport.w, viewport.h);-- if (this.tilemapRenderer_) {- this.tilemapRenderer_();- }-- if (this.spineRenderer_) {- this.spineRenderer_(registry, elapsed);- }+ Renderer.updateTransforms(registry);+ Renderer.submitAll(registry, 0, viewport.x, viewport.y, viewport.w, viewport.h);+ for (const cb of this.preFlushCallbacks_) cb(registry);Renderer.flush();- this.executeDrawCallbacks(viewProjection, elapsed);+ this.executeDrawCallbacks(viewProjection, _elapsed);}render(params: RenderParams): void {@@ -108,6 +92,7 @@ export class RenderPipeline {this.lastHeight_ = height;}+ Renderer.beginFrame();Renderer.setViewport(0, 0, width, height);Renderer.clearBuffers(3);Renderer.begin(viewProjection);diff --git a/sdk/src/renderer.ts b/sdk/src/renderer.tsindex 52b36b8d9..803d6cb82 100644--- a/sdk/src/renderer.ts+++ b/sdk/src/renderer.ts@@ -52,6 +52,19 @@ export const Renderer = {module?.renderer_resize(width, height);},+ beginFrame(): void {+ module?.renderer_beginFrame();+ },++ updateTransforms(registry: { _cpp: CppRegistry }): void {+ if (!module) return;+ try {+ module.renderer_updateTransforms(registry._cpp);+ } catch (e) {+ handleWasmError(e, 'Renderer.updateTransforms');+ }+ },+begin(viewProjection: Float32Array, target?: RenderTargetHandle): void {if (!module || !viewProjectionPtr) return;try {diff --git a/sdk/src/runtimeLoader.ts b/sdk/src/runtimeLoader.tsindex 4ac63adf7..b1464bec6 100644--- a/sdk/src/runtimeLoader.ts+++ b/sdk/src/runtimeLoader.ts@@ -3,20 +3,21 @@* @brief Runtime scene loader for builder targets (WeChat, Playable, etc.)*/-import { SpineAnimation, Transform, SceneOwner, type SpineAnimationData, type TransformData } from './component';+import { SceneOwner } from './component';import { Material } from './material';import { loadSceneData, getComponentAssetFieldDescriptors, getComponentSpineFieldDescriptor, type AssetFieldType, type SceneData } from './scene';import type { ESEngineModule } from './wasm';-import { wrapSpineModule, type SpineWasmModule, type SpineWrappedAPI } from './spine/SpineModuleLoader';+import type { SpineWasmModule } from './spine/SpineModuleLoader';+import { SpineManager, type SpineVersion } from './spine/SpineManager';import type { PhysicsWasmModule } from './physics/PhysicsModuleLoader';import { PhysicsPlugin, type PhysicsPluginConfig } from './physics/PhysicsPlugin';import type { App } from './app';-import type { Entity, Vec2 } from './types';+import type { Vec2 } from './types';import type { AddressableManifest } from './asset/AssetServer';import { Assets } from './asset/AssetPlugin';import { getAssetTypeEntry } from './assetTypes';import { SceneManager, type SceneConfig } from './sceneManager';-import { DEFAULT_MAX_DELTA_TIME, DEFAULT_FALLBACK_DT, DEFAULT_GRAVITY, DEFAULT_FIXED_TIMESTEP } from './defaults';+import { DEFAULT_GRAVITY, DEFAULT_FIXED_TIMESTEP } from './defaults';import { type AnimClipAssetData, extractAnimClipTexturePaths, parseAnimClipData } from './animation/AnimClipLoader';import { registerAnimClip } from './animation/SpriteAnimator';import { Audio } from './audio/Audio';@@ -162,14 +163,47 @@ function parseAtlasTextures(content: string): string[] {return textures;}-async function loadSpineAssets(+function ensureVirtualDir(module: ESEngineModule, virtualPath: string): void {+ const fs = module.FS;+ if (!fs) return;+ const dir = virtualPath.substring(0, virtualPath.lastIndexOf('/'));+ if (!dir) return;+ const parts = dir.split('/').filter(p => p);+ let currentPath = '';+ for (const part of parts) {+ currentPath += '/' + part;+ try { fs.mkdir(currentPath); } catch { /* already exists */ }+ }+}++function writeToVirtualFS(module: ESEngineModule, virtualPath: string, data: string | Uint8Array): boolean {+ const fs = module.FS;+ if (!fs) return false;+ try {+ ensureVirtualDir(module, virtualPath);+ fs.writeFile(virtualPath, data);+ return true;+ } catch {+ return false;+ }+}++interface SpineAssetInfo {+ version: SpineVersion | null;+ skelData: Uint8Array | string;+ atlasText: string;+ textures: Map<string, { glId: number; w: number; h: number }>;+}++async function loadSpineAssetsToVirtualFS(module: ESEngineModule,- spineModule: SpineWasmModule,- spineAPI: SpineWrappedAPI,sceneData: SceneData,provider: RuntimeAssetProvider,-): Promise<Record<string, number>> {- const skeletons: Record<string, number> = {};+ spineManager?: SpineManager | null,+): Promise<Map<string, SpineAssetInfo>> {+ const loaded = new Set<string>();+ const assetInfoMap = new Map<string, SpineAssetInfo>();+for (const entity of sceneData.entities) {for (const comp of entity.components) {const spineDesc = getComponentSpineFieldDescriptor(comp.type);@@ -178,193 +212,59 @@ async function loadSpineAssets(const atlasRef = comp.data[spineDesc.atlasField] as string;if (!skelRef || !atlasRef) continue;- const skelPath = provider.resolvePath(skelRef);+ const cacheKey = `${skelRef}:${atlasRef}`;+ if (loaded.has(cacheKey)) continue;+ loaded.add(cacheKey);+const atlasPath = provider.resolvePath(atlasRef);try {const atlasContent = await provider.readText(atlasRef);- const isBinary = getAssetTypeEntry(skelPath)?.contentType === 'binary';-- let skelDataPtr: number;- let skelDataLen: number;- if (isBinary) {- const bytes = await provider.readBinary(skelRef);- skelDataLen = bytes.length;- skelDataPtr = spineModule._malloc(skelDataLen);- spineModule.HEAPU8.set(bytes, skelDataPtr);- } else {- const text = await provider.readText(skelRef);- const encoder = new TextEncoder();- const bytes = encoder.encode(text);- skelDataLen = bytes.length;- skelDataPtr = spineModule._malloc(skelDataLen + 1);- spineModule.HEAPU8.set(bytes, skelDataPtr);- spineModule.HEAPU8[skelDataPtr + skelDataLen] = 0;- }- const skelHandle = spineAPI.loadSkeleton(- skelDataPtr, skelDataLen, atlasContent, atlasContent.length, isBinary);- spineModule._free(skelDataPtr);- if (skelHandle < 0) continue;+ const skelPath = provider.resolvePath(skelRef);+ const isBinary = getAssetTypeEntry(skelPath)?.contentType === 'binary';+ const skelData = isBinary+ ? await provider.readBinary(skelRef)+ : await provider.readText(skelRef);- skeletons[skelRef] = skelHandle;+ const version = spineManager+ ? (typeof skelData === 'string'+ ? SpineManager.detectVersionJson(skelData)+ : SpineManager.detectVersion(skelData))+ : null;const texNames = parseAtlasTextures(atlasContent);const atlasDir = atlasPath.substring(0, atlasPath.lastIndexOf('/'));- for (let k = 0; k < texNames.length; k++) {- const texPath = atlasDir + '/' + texNames[k];+ const rm = module.getResourceManager();+ const textures = new Map<string, { glId: number; w: number; h: number }>();++ for (const texName of texNames) {+ const texPath = atlasDir + '/' + texName;try {const result = provider.loadPixelsRaw? await provider.loadPixelsRaw(texPath): await provider.loadPixels(texPath);const handle = createTextureFromPixels(module, result, false);- const rm = module.getResourceManager();- const glId = rm.getTextureGLId(handle);- spineAPI.setAtlasPageTexture(skelHandle, k, glId, result.width, result.height);+ rm.registerTextureWithPath(handle, texPath);+ textures.set(texName, {+ glId: rm.getTextureGLId(handle),+ w: result.width,+ h: result.height,+ });} catch { /* skip missing texture */ }}- } catch { /* skip failed spine asset */ }- }- }- return skeletons;-}--function createSpineInstances(- spineAPI: SpineWrappedAPI,- sceneData: SceneData,- skeletons: Record<string, number>,- entityMap: Map<number, number>,-): Record<number, number> {- const instances: Record<number, number> = {};- for (const entityData of sceneData.entities) {- if (entityData.visible === false) continue;- for (const comp of entityData.components) {- const spineDesc = getComponentSpineFieldDescriptor(comp.type);- if (!spineDesc || !comp.data) continue;- const skelRef = comp.data[spineDesc.skeletonField] as string;- const skelHandle = skeletons[skelRef];- if (skelHandle === undefined) continue;-- const instanceId = spineAPI.createInstance(skelHandle);- if (instanceId < 0) continue;- const entity = entityMap.get(entityData.id);- if (entity !== undefined) instances[entity] = instanceId;+ const isNative = !version || version === '4.2';+ if (isNative) {+ writeToVirtualFS(module, atlasPath, atlasContent);+ writeToVirtualFS(module, skelPath, skelData);+ }- if (comp.data.animation) {- spineAPI.playAnimation(- instanceId, comp.data.animation as string,- comp.data.loop !== false, 0);- }- if (comp.data.skin) {- spineAPI.setSkin(instanceId, comp.data.skin as string);- }+ assetInfoMap.set(cacheKey, { version, skelData, atlasText: atlasContent, textures });+ } catch { /* skip failed spine asset */ }}}- return instances;-}--function buildTransformMatrix(- wt: TransformData,- skeletonScale: number,- flipX: boolean,- flipY: boolean,-): Float32Array {- const sx = wt.worldScale.x * skeletonScale * (flipX ? -1 : 1);- const sy = wt.worldScale.y * skeletonScale * (flipY ? -1 : 1);- const sz = wt.worldScale.z;- const qx = wt.worldRotation.x, qy = wt.worldRotation.y, qz = wt.worldRotation.z, qw = wt.worldRotation.w;- const x2 = qx + qx, y2 = qy + qy, z2 = qz + qz;- const xx = qx * x2, xy = qx * y2, xz = qx * z2;- const yy = qy * y2, yz = qy * z2, zz = qz * z2;- const wx = qw * x2, wy = qw * y2, wz = qw * z2;- return new Float32Array([- (1 - (yy + zz)) * sx, (xy + wz) * sx, (xz - wy) * sx, 0,- (xy - wz) * sy, (1 - (xx + zz)) * sy, (yz + wx) * sy, 0,- (xz + wy) * sz, (yz - wx) * sz, (1 - (xx + yy)) * sz, 0,- wt.worldPosition.x, wt.worldPosition.y, wt.worldPosition.z, 1,- ]);-}--function setupSpineRenderer(- app: App,- module: ESEngineModule,- spineModule: SpineWasmModule,- spineAPI: SpineWrappedAPI,- instances: Record<number, number>,-): void {- let lastElapsed = 0;- app.setSpineRenderer((_registry: unknown, elapsed: number) => {- let dt = elapsed - lastElapsed;- lastElapsed = elapsed;- if (dt <= 0 || dt > DEFAULT_MAX_DELTA_TIME) dt = DEFAULT_FALLBACK_DT;-- const world = app.world;-- for (const entity in instances) {- const entityId = Number(entity) as Entity;- const instanceId = instances[entity];-- const spineData = world.has(entityId, SpineAnimation)- ? world.get(entityId, SpineAnimation) as SpineAnimationData- : null;-- const playing = spineData?.playing !== false;- const timeScale = spineData?.timeScale ?? 1;- if (playing) {- spineAPI.update(instanceId, dt * timeScale);- }-- let transformPtr = 0;- if (world.has(entityId, Transform)) {- const wt = world.get(entityId, Transform) as TransformData;- const skeletonScale = spineData?.skeletonScale ?? 1;- const flipX = spineData?.flipX ?? false;- const flipY = spineData?.flipY ?? false;- const mat = buildTransformMatrix(wt, skeletonScale, flipX, flipY);- transformPtr = module._malloc(64);- module.HEAPF32.set(mat, transformPtr >> 2);- }-- const batchCount = spineAPI.getMeshBatchCount(instanceId);- for (let b = 0; b < batchCount; b++) {- const vertCount = spineAPI.getMeshBatchVertexCount(instanceId, b);- const idxCount = spineAPI.getMeshBatchIndexCount(instanceId, b);- if (!vertCount || !idxCount) continue;-- const vertBytes = vertCount * 8 * 4;- const idxBytes = idxCount * 2;- const vertPtr = spineModule._malloc(vertBytes);- const idxPtr = spineModule._malloc(idxBytes);- const texIdPtr = spineModule._malloc(4);- const blendPtr = spineModule._malloc(4);-- spineAPI.getMeshBatchData(instanceId, b, vertPtr, idxPtr, texIdPtr, blendPtr);- const texId = spineModule.HEAPU32[texIdPtr >> 2];- const blendMode = spineModule.HEAPU32[blendPtr >> 2];- const srcVerts = new Float32Array(spineModule.HEAPF32.buffer, vertPtr, vertCount * 8);- const srcIdx = new Uint16Array(spineModule.HEAPU8.buffer, idxPtr, idxCount);-- const coreVertPtr = module._malloc(vertBytes);- const coreIdxPtr = module._malloc(idxBytes);- module.HEAPF32.set(srcVerts, coreVertPtr >> 2);- new Uint16Array(module.HEAPU8.buffer, coreIdxPtr, idxCount).set(srcIdx);-- module.renderer_submitTriangles(- coreVertPtr, vertCount, coreIdxPtr, idxCount,- texId, blendMode, transformPtr);-- module._free(coreVertPtr);- module._free(coreIdxPtr);- spineModule._free(vertPtr);- spineModule._free(idxPtr);- spineModule._free(texIdPtr);- spineModule._free(blendPtr);- }-- if (transformPtr) module._free(transformPtr);- }- });+ return assetInfoMap;}// =============================================================================@@ -614,6 +514,7 @@ export interface LoadRuntimeSceneOptions {sceneData: SceneData;provider: RuntimeAssetProvider;spineModule?: SpineWasmModule | null;+ spineManager?: SpineManager | null;physicsModule?: PhysicsWasmModule | null;physicsConfig?: { gravity?: Vec2; fixedTimestep?: number; subStepCount?: number; contactHertz?: number; contactDampingRatio?: number; contactSpeed?: number };manifest?: AddressableManifest | null;@@ -621,17 +522,12 @@ export interface LoadRuntimeSceneOptions {}export async function loadRuntimeScene(options: LoadRuntimeSceneOptions): Promise<void> {- const { app, module, sceneData, provider, spineModule, physicsModule, physicsConfig, manifest, sceneName } = options;+ const { app, module, sceneData, provider, spineManager, physicsModule, physicsConfig, manifest, sceneName } = options;const textureCache = await loadTextures(module, sceneData, provider);applyTextureMetadata(module, sceneData, textureCache);- let spineSkeletons: Record<string, number> = {};- let spineAPI: SpineWrappedAPI | null = null;- if (spineModule) {- spineAPI = wrapSpineModule(spineModule);- spineSkeletons = await loadSpineAssets(module, spineModule, spineAPI, sceneData, provider);- }+ const spineAssetInfo = await loadSpineAssetsToVirtualFS(module, sceneData, provider, spineManager);if (physicsModule) {const config: PhysicsPluginConfig = {@@ -660,16 +556,47 @@ export async function loadRuntimeScene(options: LoadRuntimeSceneOptions): Promis(module as ESEngineModule).transform_update(cppRegistry);}+ if (spineManager && cppRegistry && spineAssetInfo.size > 0) {+ for (const sceneEntity of sceneData.entities) {+ for (const comp of sceneEntity.components) {+ const spineDesc = getComponentSpineFieldDescriptor(comp.type);+ if (!spineDesc || !comp.data) continue;+ const skelRef = comp.data[spineDesc.skeletonField] as string;+ const atlasRef = comp.data[spineDesc.atlasField] as string;+ if (!skelRef || !atlasRef) continue;++ const cacheKey = `${skelRef}:${atlasRef}`;+ const info = spineAssetInfo.get(cacheKey);+ if (!info || !info.version || info.version === '4.2') continue;++ const entity = entityMap.get(sceneEntity.id);+ if (entity === undefined) continue;++ await spineManager.loadEntity(+ entity, info.skelData, info.atlasText, info.textures, cppRegistry);++ spineManager.setEntityProps(entity, {+ skeletonScale: (comp.data.skeletonScale as number) ?? 1,+ flipX: (comp.data.flipX as boolean) ?? false,+ flipY: (comp.data.flipY as boolean) ?? false,+ layer: (comp.data.layer as number) ?? 0,+ });+ const skin = comp.data.skin as string;+ if (skin) spineManager.setSkin(entity, skin);+ const animation = comp.data.animation as string;+ if (animation) {+ spineManager.setAnimation(entity, animation, comp.data.loop !== false);+ }+ }+ }+ }+if (sceneName && app.hasResource(SceneManager)) {for (const entity of entityMap.values()) {app.world.insert(entity, SceneOwner, { scene: sceneName, persistent: false });}}- if (spineModule && spineAPI) {- const instances = createSpineInstances(spineAPI, sceneData, spineSkeletons, entityMap);- setupSpineRenderer(app, module, spineModule, spineAPI, instances);- }if (manifest) {const assetServer = app.getResource(Assets);@@ -699,6 +626,7 @@ export interface RuntimeInitConfig {scenes: Array<{ name: string; data: SceneData }>;firstScene: string;spineModule?: SpineWasmModule | null;+ spineManager?: SpineManager | null;physicsModule?: PhysicsWasmModule | null;physicsConfig?: { gravity?: Vec2; fixedTimestep?: number; subStepCount?: number; contactHertz?: number; contactDampingRatio?: number; contactSpeed?: number };manifest?: AddressableManifest | null;@@ -715,6 +643,7 @@ export async function initRuntime(config: RuntimeInitConfig): Promise<void> {module: config.module,provider: config.provider,spineModule: config.spineModule,+ spineManager: config.spineManager,physicsModule: config.physicsModule,physicsConfig: config.physicsConfig,manifest: config.manifest,diff --git a/sdk/src/wasm.ts b/sdk/src/wasm.tsindex 841f039e1..1a84f3c3e 100644--- a/sdk/src/wasm.ts+++ b/sdk/src/wasm.ts@@ -88,6 +88,24 @@ export interface ESEngineModule {getResourceManager(): CppResourceManager;getSpineBounds?(registry: CppRegistry, entity: number): SpineBounds;+ spine_update?(registry: CppRegistry, dt: number): void;+ spine_play?(entity: number, animation: string, loop: boolean, track: number): boolean;+ spine_addAnimation?(entity: number, animation: string, loop: boolean, delay: number, track: number): boolean;+ spine_setSkin?(entity: number, skinName: string): boolean;+ spine_getBonePosition?(entity: number, boneName: string): { x: number; y: number } | null;+ spine_hasInstance?(entity: number): boolean;+ spine_reloadAssets?(registry: CppRegistry): void;+ spine_getAnimations?(entity: number): string[];+ spine_getSkins?(entity: number): string[];+ spine_setNeedsReload?(registry: CppRegistry, entity: number, value: boolean): void;+ renderer_submitSpineBatch?(+ verticesPtr: number, vertexCount: number,+ indicesPtr: number, indexCount: number,+ textureId: number, blendMode: number,+ transformPtr: number,+ entity: number, layer: number, depth: number+ ): void;+// Material cacheinvalidateMaterialCache(materialId: number): void;clearMaterialCache(): void;@@ -159,6 +177,8 @@ export interface ESEngineModule {// Renderer API (RenderFrame)renderer_init(width: number, height: number): void;renderer_resize(width: number, height: number): void;+ renderer_beginFrame(): void;+ renderer_updateTransforms(registry: CppRegistry): void;renderer_begin(matrixPtr: number, targetHandle: number): void;renderer_flush(): void;renderer_end(): void;@@ -169,11 +189,6 @@ export interface ESEngineModule {renderer_submitSpine?(registry: CppRegistry): void;renderer_submitParticles?(registry: CppRegistry): void;renderer_submitAll(registry: CppRegistry, skipFlags: number, vpX: number, vpY: number, vpW: number, vpH: number): void;- renderer_submitTriangles(- verticesPtr: number, vertexCount: number,- indicesPtr: number, indexCount: number,- textureId: number, blendMode: number,- transformPtr: number): void;particle_update?(registry: CppRegistry, dt: number): void;particle_play?(registry: CppRegistry, entity: number): void;particle_stop?(registry: CppRegistry, entity: number): void;diff --git a/sdk/src/webAppFactory.ts b/sdk/src/webAppFactory.tsindex 157fb0a2b..916c1a561 100644--- a/sdk/src/webAppFactory.ts+++ b/sdk/src/webAppFactory.ts@@ -8,6 +8,8 @@ import { particlePlugin } from './particle';import { tilemapPlugin } from './tilemap';import { postProcessPlugin } from './postprocess';import { timelinePlugin } from './timeline';+import { SpinePlugin } from './spine';+import type { SpineWasmProvider } from './spine';export { uiPlugins };export { textPlugin, TextPlugin } from './ui/TextPlugin';@@ -36,8 +38,14 @@ export { ParticlePlugin, particlePlugin } from './particle';export { PostProcessPlugin, postProcessPlugin } from './postprocess';export { TimelinePlugin, timelinePlugin, registerTimelineAsset, parseTimelineAsset, clearTimelineHandles } from './timeline';-const defaultPlugins = [...uiPlugins, animationPlugin, audioPlugin, particlePlugin, tilemapPlugin, postProcessPlugin, timelinePlugin];+export interface CreateWebAppOptions extends WebAppOptions {+ spineProvider?: SpineWasmProvider;+}++const basePlugins = [animationPlugin, audioPlugin, particlePlugin, tilemapPlugin, postProcessPlugin, timelinePlugin];-export function createWebApp(module: ESEngineModule, options?: WebAppOptions): App {- return _createWebApp(module, { plugins: defaultPlugins, ...options });+export function createWebApp(module: ESEngineModule, options?: CreateWebAppOptions): App {+ const spinePlugin = new SpinePlugin(options?.spineProvider);+ const plugins = [...uiPlugins, ...basePlugins, spinePlugin, ...(options?.plugins ?? [])];+ return _createWebApp(module, { ...options, plugins });}diff --git a/sdk/src/wechatRuntime.ts b/sdk/src/wechatRuntime.tsindex 5ee918524..15d0b43a0 100644--- a/sdk/src/wechatRuntime.ts+++ b/sdk/src/wechatRuntime.ts@@ -14,6 +14,7 @@ import { platformReadTextFile, platformReadFile, platformInstantiateWasm, platfoimport { toBuildPath } from './assetTypes';import type { AddressableManifest } from './asset/AssetServer';import type { SpineWasmModule } from './spine/SpineModuleLoader';+import { SpineManager, type SpineVersion } from './spine/SpineManager';import type { PhysicsWasmModule } from './physics/PhysicsModuleLoader';import type { Vec2 } from './types';import type { SceneData } from './scene';@@ -117,7 +118,7 @@ export interface WeChatRuntimeConfig {firstScene: string;runtimeConfig?: RuntimeBuildConfig;physicsConfig?: { gravity?: Vec2; fixedTimestep?: number; subStepCount?: number };- spineFactory?: (opts: unknown) => Promise<SpineWasmModule>;+ spineFactories?: Record<string, (opts: unknown) => Promise<SpineWasmModule>>;physicsFactory?: (opts: unknown) => Promise<PhysicsWasmModule>;}@@ -161,9 +162,16 @@ export async function initWeChatRuntime(config: WeChatRuntimeConfig): Promise<voapplyBuildRuntimeConfig(app, config.runtimeConfig);}- let spineModule: SpineWasmModule | null = null;- if (config.spineFactory) {- spineModule = await initWasmModule(config.spineFactory, 'spine.wasm');+ let spineManager: SpineManager | null = null;+ if (config.spineFactories && Object.keys(config.spineFactories).length > 0) {+ const factories = new Map<SpineVersion, () => Promise<SpineWasmModule>>();+ for (const [version, factory] of Object.entries(config.spineFactories)) {+ const ver = version as SpineVersion;+ const tag = version.replace('.', '');+ const wasmPath = `spine_${tag}.wasm`;+ factories.set(ver, () => initWasmModule(factory, wasmPath) as Promise<SpineWasmModule>);+ }+ spineManager = new SpineManager(module, factories);}let physicsModule: PhysicsWasmModule | null = null;@@ -185,7 +193,7 @@ export async function initWeChatRuntime(config: WeChatRuntimeConfig): Promise<voprovider,scenes,firstScene: config.firstScene,- spineModule,+ spineManager,physicsModule,physicsConfig: config.physicsConfig,manifest,diff --git a/sdk/tests/renderPipeline.test.ts b/sdk/tests/renderPipeline.test.tsindex 8fcb58c5e..65152f8d2 100644--- a/sdk/tests/renderPipeline.test.ts+++ b/sdk/tests/renderPipeline.test.ts@@ -18,11 +18,8 @@ vi.mock('../src/renderer', () => ({setViewport: vi.fn(),setScissor: vi.fn(),clearBuffers: vi.fn(),- },- SubmitSkipFlags: {- None: 0,- Spine: 1,- Particles: 2,+ updateTransforms: vi.fn(),+ beginFrame: vi.fn(),},}));@@ -63,7 +60,7 @@ import { RenderPipeline } from '../src/renderPipeline';import { Renderer } from '../src/renderer';import { PostProcess } from '../src/postprocess';import { Draw } from '../src/draw';-import { getDrawCallbacks, unregisterDrawCallback } from '../src/customDraw';+import { unregisterDrawCallback } from '../src/customDraw';describe('RenderPipeline', () => {let pipeline: RenderPipeline;@@ -78,30 +75,6 @@ describe('RenderPipeline', () => {viewProjection = new Float32Array(16);});- describe('property setters', () => {- it('stores spineRenderer via setSpineRenderer', () => {- const fn = vi.fn();- pipeline.setSpineRenderer(fn);- expect(pipeline.spineRenderer).toBe(fn);- });-- it('returns null for spineRenderer by default', () => {- expect(pipeline.spineRenderer).toBeNull();- });-- it('allows clearing spineRenderer with null', () => {- pipeline.setSpineRenderer(vi.fn());- pipeline.setSpineRenderer(null);- expect(pipeline.spineRenderer).toBeNull();- });-- it('stores active scenes via setActiveScenes', () => {- const scenes = new Set(['scene1', 'scene2']);- pipeline.setActiveScenes(scenes);- pipeline.render({ registry, viewProjection, width: 100, height: 100, elapsed: 0 });- });- });-describe('render() call sequence', () => {it('calls rendering methods in correct order', () => {const callOrder: string[] = [];@@ -152,21 +125,7 @@ describe('RenderPipeline', () => {expect(Renderer.resize).toHaveBeenCalledWith(1024, 768);});- it('triggers resize when only width changes', () => {- pipeline.render({ registry, viewProjection, width: 800, height: 600, elapsed: 0 });- vi.clearAllMocks();- pipeline.render({ registry, viewProjection, width: 1024, height: 600, elapsed: 0 });- expect(Renderer.resize).toHaveBeenCalledWith(1024, 600);- });-- it('triggers resize when only height changes', () => {- pipeline.render({ registry, viewProjection, width: 800, height: 600, elapsed: 0 });- vi.clearAllMocks();- pipeline.render({ registry, viewProjection, width: 800, height: 768, elapsed: 0 });- expect(Renderer.resize).toHaveBeenCalledWith(800, 768);- });-- it('does not call PostProcess.resize on render() (only renderCamera does)', () => {+ it('does not call PostProcess.resize on render()', () => {pipeline.render({ registry, viewProjection, width: 800, height: 600, elapsed: 0 });expect(PostProcess.resize).not.toHaveBeenCalled();});@@ -185,52 +144,11 @@ describe('RenderPipeline', () => {expect(PostProcess.resize).toHaveBeenCalledWith(800, 600);});-- it('does not call PostProcess.resize in renderCamera when no postprocess stack', () => {- (PostProcess.getStack as ReturnType<typeof vi.fn>).mockReturnValue(null);-- pipeline.renderCamera({- registry,- viewProjection,- viewportPixels: { x: 0, y: 0, w: 800, h: 600 },- clearFlags: 3,- elapsed: 0,- cameraEntity: 1 as any,- });-- expect(PostProcess.resize).not.toHaveBeenCalled();- });});- describe('spine rendering', () => {- it('calls submitAll without skip flags by default', () => {- pipeline.render({ registry, viewProjection, width: 800, height: 600, elapsed: 16 });- expect(Renderer.submitAll).toHaveBeenCalledWith(registry, 0, 0, 0, 800, 600);- });-- it('skips spine in submitAll and calls custom spineRenderer when set', () => {- const customSpine = vi.fn();- pipeline.setSpineRenderer(customSpine);- pipeline.render({ registry, viewProjection, width: 800, height: 600, elapsed: 16 });-- expect(Renderer.submitAll).toHaveBeenCalledWith(registry, 1, 0, 0, 800, 600);- expect(customSpine).toHaveBeenCalledWith(registry, 16);- });-- it('reverts to no skip flags when spineRenderer cleared', () => {- const customSpine = vi.fn();- pipeline.setSpineRenderer(customSpine);- pipeline.setSpineRenderer(null);+ describe('submitScene', () => {+ it('calls submitAll with skipFlags=0 (all plugins participate)', () => {pipeline.render({ registry, viewProjection, width: 800, height: 600, elapsed: 16 });-- expect(Renderer.submitAll).toHaveBeenCalledWith(registry, 0, 0, 0, 800, 600);- expect(customSpine).not.toHaveBeenCalled();- });- });-- describe('mask processing (handled in C++)', () => {- it('submitAll receives viewport params for C++ mask processing', () => {- pipeline.render({ registry, viewProjection, width: 800, height: 600, elapsed: 0 });expect(Renderer.submitAll).toHaveBeenCalledWith(registry, 0, 0, 0, 800, 600);});});@@ -278,29 +196,6 @@ describe('RenderPipeline', () => {expect(cb2).not.toHaveBeenCalled();});- it('runs callbacks with no scene filter when activeScenes is set', () => {- const cb = vi.fn();- mockCallbacks.set('cb-no-scene', { fn: cb, scene: '' });-- pipeline.setActiveScenes(new Set(['scene-a']));- pipeline.render({ registry, viewProjection, width: 800, height: 600, elapsed: 0 });-- expect(cb).toHaveBeenCalled();- });-- it('runs all callbacks when activeScenes is null', () => {- const cb1 = vi.fn();- const cb2 = vi.fn();- mockCallbacks.set('cb1', { fn: cb1, scene: 'scene-a' });- mockCallbacks.set('cb2', { fn: cb2, scene: 'scene-b' });-- pipeline.setActiveScenes(null);- pipeline.render({ registry, viewProjection, width: 800, height: 600, elapsed: 0 });-- expect(cb1).toHaveBeenCalled();- expect(cb2).toHaveBeenCalled();- });-it('logs error and unregisters throwing callback', () => {const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});const error = new Error('test error');@@ -313,19 +208,6 @@ describe('RenderPipeline', () => {errorSpy.mockRestore();});- it('continues executing other callbacks after one throws', () => {- const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});- const goodCb = vi.fn();- mockCallbacks.set('bad-cb', { fn: () => { throw new Error('fail'); }, scene: '' });- mockCallbacks.set('good-cb', { fn: goodCb, scene: '' });-- pipeline.render({ registry, viewProjection, width: 800, height: 600, elapsed: 0 });-- expect(goodCb).toHaveBeenCalled();- expect(unregisterDrawCallback).toHaveBeenCalledWith('bad-cb');- errorSpy.mockRestore();- });-it('still calls Draw.end even when callback throws', () => {vi.spyOn(console, 'error').mockImplementation(() => {});mockCallbacks.set('bad-cb', { fn: () => { throw new Error('fail'); }, scene: '' });@@ -359,44 +241,7 @@ describe('RenderPipeline', () => {]);});- it('uses clearFlags parameter for clearBuffers', () => {- pipeline.renderCamera({ registry, viewProjection, viewportPixels, clearFlags: 1, elapsed: 0 });- expect(Renderer.clearBuffers).toHaveBeenCalledWith(1);- });-- it('does not trigger resize', () => {- pipeline.renderCamera({ registry, viewProjection, viewportPixels, clearFlags: 3, elapsed: 0 });- expect(Renderer.resize).not.toHaveBeenCalled();- });-- it('follows correct rendering sequence', () => {- const callOrder: string[] = [];- (Renderer.setViewport as ReturnType<typeof vi.fn>).mockImplementation(() => callOrder.push('setViewport'));- (Renderer.setScissor as ReturnType<typeof vi.fn>).mockImplementation(() => callOrder.push('setScissor'));- (Renderer.clearBuffers as ReturnType<typeof vi.fn>).mockImplementation(() => callOrder.push('clearBuffers'));- (Renderer.begin as ReturnType<typeof vi.fn>).mockImplementation(() => callOrder.push('begin'));- (Renderer.submitAll as ReturnType<typeof vi.fn>).mockImplementation(() => callOrder.push('submitAll'));- (Renderer.flush as ReturnType<typeof vi.fn>).mockImplementation(() => callOrder.push('flush'));- (Renderer.end as ReturnType<typeof vi.fn>).mockImplementation(() => callOrder.push('end'));-- pipeline.renderCamera({ registry, viewProjection, viewportPixels, clearFlags: 3, elapsed: 0 });-- expect(callOrder).toEqual([- 'setViewport', 'setScissor', 'clearBuffers', 'setScissor',- 'begin', 'submitAll', 'flush', 'end',- ]);- });-- it('skips spine in submitAll and calls custom spineRenderer in renderCamera', () => {- const customSpine = vi.fn();- pipeline.setSpineRenderer(customSpine);- pipeline.renderCamera({ registry, viewProjection, viewportPixels, clearFlags: 3, elapsed: 16 });-- expect(Renderer.submitAll).toHaveBeenCalledWith(registry, 1, 10, 20, 400, 300);- expect(customSpine).toHaveBeenCalledWith(registry, 16);- });-- it('passes viewport params to submitAll in renderCamera for C++ mask processing', () => {+ it('passes viewport params to submitAll', () => {pipeline.renderCamera({ registry, viewProjection, viewportPixels, clearFlags: 3, elapsed: 0 });expect(Renderer.submitAll).toHaveBeenCalledWith(registry, 0, 10, 20, 400, 300);});@@ -436,16 +281,6 @@ describe('RenderPipeline', () => {expect(PostProcess._executeScreenPasses).toHaveBeenCalled();});- it('does not call screen capture when screenStack has 0 enabled passes', () => {- const mockStack = { enabledPassCount: 0, passes: [] };- (PostProcess as any).screenStack = mockStack;-- pipeline.beginScreenCapture();- pipeline.endScreenCapture();- expect(PostProcess._beginScreenCapture).not.toHaveBeenCalled();- expect(PostProcess._executeScreenPasses).not.toHaveBeenCalled();- });-it('initializes postprocess if not yet initialized', () => {const mockStack = { enabledPassCount: 1, passes: [] };(PostProcess as any).screenStack = mockStack;