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: update editor scene manager and Spine integration for multi-version support

esengine950387a88261
diff --git a/editor/src/asset/AssetLoader.ts b/editor/src/asset/AssetLoader.ts
index e31b319b1..78c4913dd 100644
--- a/editor/src/asset/AssetLoader.ts
+++ b/editor/src/asset/AssetLoader.ts
@@ -4,7 +4,6 @@
*/
import { type ESEngineModule, getAssetTypeEntry } from 'esengine';
-import type { SpineModuleController } from 'esengine/spine';
import type { AssetPathResolver } from './AssetPathResolver';
import { getEditorContext } from '../context/EditorContext';
import type { NativeFS } from '../types/NativeFS';
@@ -21,6 +20,12 @@ export interface LoadResult {
error?: string;
}
+export interface SpineRawLoadResult extends LoadResult {
+ skelData?: Uint8Array | string;
+ atlasText?: string;
+ textures?: Map<string, { glId: number; w: number; h: number }>;
+}
+
interface SpineLoadState {
skeleton: boolean;
atlas: boolean;
@@ -153,38 +158,33 @@ export class AssetLoader {
return { success: true };
}
- async loadSpineToModule(
- controller: SpineModuleController,
- skeletonPath: string,
- atlasPath: string
- ): Promise<{ success: boolean; skeletonHandle?: number; error?: string }> {
+ async loadSpineWithRawData(skeletonPath: string, atlasPath: string): Promise<SpineRawLoadResult> {
const fs = this.getNativeFS();
if (!fs) {
return { success: false, error: 'Native filesystem not available' };
}
const atlasAbsPath = this.pathResolver_.toAbsolutePath(atlasPath);
- const atlasContent = await fs.readFile(atlasAbsPath);
- if (!atlasContent) {
+ const atlasText = await fs.readFile(atlasAbsPath);
+ if (!atlasText) {
return { success: false, error: `Failed to read atlas: ${atlasAbsPath}` };
}
const atlasDir = atlasPath.substring(0, atlasPath.lastIndexOf('/'));
- const textureNames = parseAtlasTextures(atlasContent);
- const textureResults: { path: string; handle: number; width: number; height: number }[] = [];
+ const textureNames = parseAtlasTextures(atlasText);
+ const textures = new Map<string, { glId: number; w: number; h: number }>();
for (const texName of textureNames) {
const texPath = atlasDir ? `${atlasDir}/${texName}` : texName;
const result = await this.loadTexture(texPath);
if (result.success && result.handle !== undefined) {
- textureResults.push({
- path: texPath,
- handle: result.handle,
- width: result.width!,
- height: result.height!,
+ const rm = this.module_.getResourceManager();
+ const glId = rm.getTextureGLId(result.handle);
+ textures.set(texName, {
+ glId,
+ w: result.width ?? 0,
+ h: result.height ?? 0,
});
- } else {
- console.error(`[AssetLoader] Failed to load Spine texture: ${texPath} - ${result.error}`);
}
}
@@ -198,29 +198,7 @@ export class AssetLoader {
return { success: false, error: `Failed to read skeleton: ${skelAbsPath}` };
}
- const skeletonHandle = controller.loadSkeleton(
- skelData instanceof Uint8Array ? skelData : skelData as string,
- atlasContent, isBinary);
- if (skeletonHandle < 0) {
- let detail = '';
- try { detail = controller.getLastError(); } catch { /* not available before WASM rebuild */ }
- return { success: false, error: `Failed to load skeleton in spine module: ${skeletonPath}${detail ? ' (' + detail + ')' : ''}` };
- }
-
- const rm = this.module_.getResourceManager();
- const pageCount = controller.getAtlasPageCount(skeletonHandle);
- for (let i = 0; i < pageCount; i++) {
- const pageName = controller.getAtlasPageTextureName(skeletonHandle, i);
- const tex = textureResults.find(t => t.path.endsWith(pageName));
- if (tex) {
- const glTexId = rm.getTextureGLId(tex.handle);
- controller.setAtlasPageTexture(skeletonHandle, i, glTexId, tex.width, tex.height);
- } else {
- console.warn(`[AssetLoader] Atlas page ${i} texture not found: "${pageName}". Available: ${textureResults.map(t => t.path).join(', ')}`);
- }
- }
-
- return { success: true, skeletonHandle };
+ return { success: true, skelData, atlasText, textures };
}
isTextureLoaded(path: string): boolean {
diff --git a/editor/src/asset/EditorAssetServer.ts b/editor/src/asset/EditorAssetServer.ts
index 4fe3a11c8..71317f7c8 100644
--- a/editor/src/asset/EditorAssetServer.ts
+++ b/editor/src/asset/EditorAssetServer.ts
@@ -7,7 +7,7 @@ import type { ESEngineModule } from 'esengine';
import type { TextureInfo, SliceBorder, SpineLoadResult, MaterialHandle, ShaderHandle, MaterialAssetData } from 'esengine';
import { Material, getAssetTypeEntry } from 'esengine';
import { EditorTextureManager } from '../renderer/EditorTextureManager';
-import { AssetLoader } from './AssetLoader';
+import { AssetLoader, type SpineRawLoadResult } from './AssetLoader';
import type { AssetPathResolver } from './AssetPathResolver';
import { parseShaderProperties, getShaderDefaultProperties } from '../shader/ShaderPropertyParser';
import { getAssetEventBus } from '../events/AssetEventBus';
@@ -191,6 +191,10 @@ export class EditorAssetServer {
return false;
}
+ async loadSpineWithRawData(skeletonPath: string, atlasPath: string): Promise<SpineRawLoadResult> {
+ return this.assetLoader_.loadSpineWithRawData(skeletonPath, atlasPath);
+ }
+
isSpineLoaded(skeletonPath: string, atlasPath: string): boolean {
return this.assetLoader_.isSpineLoaded(skeletonPath, atlasPath);
}
diff --git a/editor/src/property/editors/spineEditors.ts b/editor/src/property/editors/spineEditors.ts
index 0c9836265..faf417d49 100644
--- a/editor/src/property/editors/spineEditors.ts
+++ b/editor/src/property/editors/spineEditors.ts
@@ -140,7 +140,7 @@ export function createSpineAnimationEditor(
container: HTMLElement,
ctx: PropertyEditorContext
): PropertyEditorInstance {
- const { value, onChange, getComponentValue } = ctx;
+ const { value, onChange, getComponentValue, getCurrentValue } = ctx;
const wrapper = document.createElement('div');
wrapper.className = 'es-spine-animation-editor';
@@ -155,6 +155,8 @@ export function createSpineAnimationEditor(
let currentAnimations: string[] = [];
+ const liveValue = () => String(getCurrentValue?.() ?? value ?? '');
+
const updateOptions = (animations: string[], currentValue: string) => {
select.innerHTML = '';
@@ -180,7 +182,7 @@ export function createSpineAnimationEditor(
const skeletonRef = getComponentValue?.('skeletonPath') as string;
const skeletonPath = skeletonRef ? resolveToPath(skeletonRef) : '';
if (!skeletonPath) {
- updateOptions([], String(value ?? ''));
+ updateOptions([], liveValue());
return;
}
@@ -189,9 +191,9 @@ export function createSpineAnimationEditor(
const data = await loadSpineSkeletonData(skeletonPath, atlasPath);
if (data) {
const animations = getAnimationNames(data);
- updateOptions(animations, String(value ?? ''));
+ updateOptions(animations, liveValue());
} else {
- updateOptions([], String(value ?? ''));
+ updateOptions([], liveValue());
}
};
@@ -236,7 +238,7 @@ export function createSpineSkinEditor(
container: HTMLElement,
ctx: PropertyEditorContext
): PropertyEditorInstance {
- const { value, onChange, getComponentValue } = ctx;
+ const { value, onChange, getComponentValue, getCurrentValue } = ctx;
const wrapper = document.createElement('div');
wrapper.className = 'es-spine-skin-editor';
@@ -251,6 +253,8 @@ export function createSpineSkinEditor(
let currentSkins: string[] = [];
+ const liveValue = () => String(getCurrentValue?.() ?? value ?? 'default');
+
const updateOptions = (skins: string[], currentValue: string) => {
select.innerHTML = '';
@@ -278,7 +282,7 @@ export function createSpineSkinEditor(
const skeletonRef = getComponentValue?.('skeletonPath') as string;
const skeletonPath = skeletonRef ? resolveToPath(skeletonRef) : '';
if (!skeletonPath) {
- updateOptions(['default'], String(value ?? 'default'));
+ updateOptions(['default'], liveValue());
return;
}
@@ -287,9 +291,9 @@ export function createSpineSkinEditor(
const data = await loadSpineSkeletonData(skeletonPath, atlasPath);
if (data) {
const skins = getSkinNames(data);
- updateOptions(skins.length > 0 ? skins : ['default'], String(value ?? 'default'));
+ updateOptions(skins.length > 0 ? skins : ['default'], liveValue());
} else {
- updateOptions(['default'], String(value ?? 'default'));
+ updateOptions(['default'], liveValue());
}
};
diff --git a/editor/src/renderer/EditorSceneRenderer.ts b/editor/src/renderer/EditorSceneRenderer.ts
index 7ae1bcd2e..a1d9d91c0 100644
--- a/editor/src/renderer/EditorSceneRenderer.ts
+++ b/editor/src/renderer/EditorSceneRenderer.ts
@@ -10,7 +10,6 @@ import {
type PostProcessEffectData,
type PostProcessVolumeData,
} from 'esengine';
-import type { SpineModuleController } from 'esengine/spine';
import type { SceneData, ComponentData } from '../types/SceneTypes';
import type { EditorStore } from '../store/EditorStore';
import { EditorCamera } from './EditorCamera';
@@ -186,10 +185,6 @@ export class EditorSceneRenderer {
this.context_.setProjectDir(projectDir);
}
- setSpineController(controller: SpineModuleController | null): void {
- this.context_.setSpineController(controller);
- }
-
get pathResolver(): AssetPathResolver {
return this.context_.pathResolver_;
}
@@ -215,19 +210,19 @@ export class EditorSceneRenderer {
return this.sceneManager_?.assetServer ?? null;
}
- get spineInstanceCount(): number {
- return this.sceneManager_?.spineInstanceCount ?? 0;
- }
-
getSpineBounds(sceneEntityId: number): { x: number; y: number; width: number; height: number } | null {
- if (!this.module_ || !this.sceneManager_) return null;
-
- const moduleBounds = this.sceneManager_.getSpineBoundsFromModule(sceneEntityId);
- if (moduleBounds) return moduleBounds;
+ if (!this.sceneManager_) return null;
const entity = this.sceneManager_.getEntityMap().get(sceneEntityId);
if (entity === undefined) return null;
+ const spineManager = this.context_.spineManager;
+ if (spineManager) {
+ const moduleBounds = spineManager.getBounds(entity);
+ if (moduleBounds) return moduleBounds;
+ }
+
+ if (!this.module_) return null;
const bounds = this.module_.getSpineBounds?.(this.sceneManager_.registry, entity);
if (!bounds?.valid) return null;
@@ -392,6 +387,7 @@ export class EditorSceneRenderer {
Renderer.setClearColor(bg.r, bg.g, bg.b, bg.a);
Renderer.resize(width, height);
+ Renderer.beginFrame();
Renderer.setViewport(0, 0, width, height);
Renderer.clearBuffers(3);
Renderer.begin(matrix);
@@ -420,6 +416,7 @@ export class EditorSceneRenderer {
const registry = { _cpp: cppReg };
try {
+ Renderer.beginFrame();
Renderer.setViewport(0, 0, width, height);
Renderer.clearBuffers(3);
Renderer.begin(vpMatrix);
diff --git a/editor/src/renderer/GameViewRenderer.ts b/editor/src/renderer/GameViewRenderer.ts
index a176d2645..1842c424a 100644
--- a/editor/src/renderer/GameViewRenderer.ts
+++ b/editor/src/renderer/GameViewRenderer.ts
@@ -236,7 +236,7 @@ export class GameViewRenderer {
try {
Renderer.resize(renderW, renderH);
-
+ Renderer.beginFrame();
if (pipeline) {
pipeline.renderCamera({
registry,
diff --git a/editor/src/renderer/SharedRenderContext.ts b/editor/src/renderer/SharedRenderContext.ts
index 691329035..a2fe908ad 100644
--- a/editor/src/renderer/SharedRenderContext.ts
+++ b/editor/src/renderer/SharedRenderContext.ts
@@ -35,10 +35,11 @@ import {
clearTimelineHandles,
} from 'esengine';
import { PhysicsPlugin, type PhysicsPluginConfig } from 'esengine/physics';
-import type { SpineModuleController } from 'esengine/spine';
+import { SpinePlugin, SpineManager, createSpineFactories, type SpineWasmProvider } from 'esengine/spine';
import { EditorSceneManager } from '../scene/EditorSceneManager';
import { AssetPathResolver } from '../asset';
import type { GameViewRenderer } from './GameViewRenderer';
+import { getEditorContext } from '../context/EditorContext';
export class SharedRenderContext {
module_: ESEngineModule | null = null;
@@ -53,8 +54,6 @@ export class SharedRenderContext {
private gameViewRenderer_: GameViewRenderer | null = null;
private inputState_: InputState | null = null;
private startTime_ = 0;
- private lastElapsed_ = 0;
-
private playMode_ = false;
private paused_ = false;
private playSpeed_ = 1;
@@ -64,6 +63,7 @@ export class SharedRenderContext {
private continuousRender_ = false;
private isDirty_ = true;
private physicsFactory_: unknown = null;
+ private spineManager_: SpineManager | null = null;
private sceneViewportW_ = 0;
private sceneViewportH_ = 0;
private gameViewportW_ = 0;
@@ -168,6 +168,8 @@ export class SharedRenderContext {
app.addPlugin(audioPlugin);
app.addPlugin(particlePlugin);
app.addPlugin(tilemapPlugin);
+ this.spineManager_ = this.createSpineManager_(module);
+ app.addPlugin(new SpinePlugin(this.spineManager_ ?? undefined));
app.addPlugin(sceneManagerPlugin);
app.addPlugin(postProcessPlugin);
app.addPlugin(timelinePlugin);
@@ -177,6 +179,7 @@ export class SharedRenderContext {
this.app_ = app;
this.sceneManager_ = new EditorSceneManager(module, this.pathResolver_, app.world);
+ this.sceneManager_.setSpineManager(this.spineManager_);
this.sceneManager_.registerSystems(app);
this.initialized_ = true;
@@ -234,21 +237,6 @@ export class SharedRenderContext {
this.sceneManager_?.setProjectDir(projectDir);
}
- setSpineController(controller: SpineModuleController | null): void {
- this.sceneManager_?.setSpineController(controller);
-
- if (controller && this.pipeline_ && this.module_) {
- const module = this.module_;
- this.pipeline_.setSpineRenderer((_registry, elapsed) => {
- const dt = elapsed - this.lastElapsed_;
- this.lastElapsed_ = elapsed;
- this.sceneManager_?.updateAndSubmitSpine(module, dt);
- });
- } else {
- this.pipeline_?.setSpineRenderer(null);
- }
- }
-
get elapsed(): number {
return (performance.now() - this.startTime_) / 1000;
}
@@ -311,10 +299,32 @@ export class SharedRenderContext {
this.postTickCallback_?.();
}
+ get spineManager(): SpineManager | null {
+ return this.spineManager_;
+ }
+
setPhysicsFactory(factory: unknown): void {
this.physicsFactory_ = factory;
}
+ private createSpineManager_(module: ESEngineModule): SpineManager {
+ const provider: SpineWasmProvider = {
+ async loadJs(version: string): Promise<string> {
+ const fs = getEditorContext().fs;
+ if (!fs) throw new Error('NativeFS not available');
+ return fs.getSpineJs(version);
+ },
+ async loadWasm(version: string): Promise<ArrayBuffer> {
+ const fs = getEditorContext().fs;
+ if (!fs) throw new Error('NativeFS not available');
+ const bytes = await fs.getSpineWasm(version);
+ return bytes.buffer as ArrayBuffer;
+ },
+ };
+ const factories = createSpineFactories(provider);
+ return new SpineManager(module, factories);
+ }
+
async enterPlayMode(physicsConfig?: PhysicsPluginConfig): Promise<void> {
if (physicsConfig && this.app_) {
const plugin = new PhysicsPlugin(
@@ -375,6 +385,11 @@ export class SharedRenderContext {
this.animationId_ = null;
}
+ if (this.spineManager_) {
+ this.spineManager_.shutdown();
+ this.spineManager_ = null;
+ }
+
if (this.sceneManager_) {
this.sceneManager_.dispose();
this.sceneManager_ = null;
diff --git a/editor/src/scene/EditorSceneManager.ts b/editor/src/scene/EditorSceneManager.ts
index e8688e992..bcc8f945b 100644
--- a/editor/src/scene/EditorSceneManager.ts
+++ b/editor/src/scene/EditorSceneManager.ts
@@ -21,7 +21,6 @@ import {
Audio,
INVALID_FONT,
INVALID_MATERIAL,
- DEFAULT_SPINE_SKIN,
UIRect,
UIMask,
defineSystem,
@@ -32,7 +31,6 @@ import {
getAnimClip,
type AnimClipAssetData,
type SceneComponentData,
- type TransformData,
type TextInputData,
type LayoutRect,
ScaleMode,
@@ -43,8 +41,7 @@ import {
registerTimelineAsset,
parseTimelineAsset,
} from 'esengine';
-import type { SpineModuleController } from 'esengine/spine';
-import { submitSpineMeshesToCore } from 'esengine/spine';
+import { SpineCpp, SpineManager } from 'esengine/spine';
import type { SceneData, EntityData, ComponentData } from '../types/SceneTypes';
import { EditorAssetServer } from '../asset/EditorAssetServer';
import { AssetPathResolver } from '../asset/AssetPathResolver';
@@ -54,9 +51,6 @@ import { getEditorContext } from '../context/EditorContext';
import { getEditorContainer } from '../container/EditorContainer';
import { COMPONENT_LIFECYCLE, type ComponentLifecycle } from '../container/tokens';
import { getPlatformAdapter } from '../platform/PlatformAdapter';
-import {
- transformToMatrix4x4,
-} from '../math/Transform';
const BitmapTextAlign = {
Left: 0,
@@ -85,17 +79,18 @@ export class EditorSceneManager {
private syncing_ = false;
private pendingScene_: SceneData | null = null;
private syncCompleteResolvers_: (() => void)[] = [];
- private spineController_: SpineModuleController | null = null;
- private spineInstances_ = new Map<number, number>();
- private spineSkeletons_ = new Map<string, number>();
- private spineInstanceKeys_ = new Map<number, string>();
- private spineCurrentState_ = new Map<number, { animation: string; skin: string; loop: boolean }>();
private spineReadyListeners_ = new Set<(entityId: number) => void>();
private updatingEntities_ = new Map<number, Promise<void>>();
private viewportAspect_ = 0;
private postLoadHooks_ = new Map<string, (entityId: number, data: Record<string, any>) => Promise<void>>();
private ownsWorld_: boolean;
+ private spineManager_: SpineManager | null = null;
+ private pendingSpineData_ = new Map<number, {
+ skelData: Uint8Array | string;
+ atlasText: string;
+ textures: Map<string, { glId: number; w: number; h: number }>;
+ }>();
constructor(module: ESEngineModule, pathResolver: AssetPathResolver, world?: World) {
this.module_ = module;
@@ -134,12 +129,16 @@ export class EditorSceneManager {
},
});
container.provide(COMPONENT_LIFECYCLE, 'SpineAnimation', {
- remove: (_world, _entity, entityId) => {
- this.destroySpineInstance(entityId);
+ remove: (_world, entity, _entityId) => {
+ this.spineManager_?.removeEntity(entity);
},
});
}
+ setSpineManager(manager: SpineManager | null): void {
+ this.spineManager_ = manager;
+ }
+
setProjectDir(projectDir: string): void {
this.pathResolver_.setProjectDir(projectDir);
}
@@ -208,34 +207,6 @@ export class EditorSceneManager {
};
}
- setSpineController(controller: SpineModuleController | null): void {
- this.clearSpineInstances();
- this.spineController_ = controller;
- if (controller) {
- this.resyncSpineEntities();
- }
- }
-
- private async resyncSpineEntities(): Promise<void> {
- for (const [entityId, entityData] of this.entityDataMap_) {
- const spineComp = entityData.components.find(c => c.type === 'SpineAnimation');
- if (!spineComp) continue;
- const data = spineComp.data as Record<string, any>;
- const skelRef = data.skeletonPath ?? '';
- const atlasRef = data.atlasPath ?? '';
- if (!skelRef || !atlasRef) continue;
- await this.syncSpineInstance(entityId, {
- ...data,
- skeletonPath: this.resolveAssetRef(skelRef),
- atlasPath: this.resolveAssetRef(atlasRef),
- });
- }
- }
-
- get spineController(): SpineModuleController | null {
- return this.spineController_;
- }
-
// =========================================================================
// Scene Loading
// =========================================================================
@@ -403,7 +374,6 @@ export class EditorSceneManager {
removeEntity(entityId: number): void {
const entity = this.entityMap_.get(entityId);
if (entity !== undefined) {
- this.destroySpineInstance(entityId);
getDependencyGraph().clearEntity(entityId);
try {
this.world_.despawn(entity);
@@ -515,60 +485,9 @@ export class EditorSceneManager {
}
// =========================================================================
- // Spine Module Rendering
+ // Spine (C++ path)
// =========================================================================
- updateAndSubmitSpine(coreModule: ESEngineModule, dt: number): void {
- if (!this.spineController_ || this.spineInstances_.size === 0) return;
-
- for (const [entityId, instanceId] of this.spineInstances_) {
- const entityData = this.entityDataMap_.get(entityId);
- if (!entityData || entityData.visible === false) continue;
-
- const spineComp = entityData.components.find(c => c.type === 'SpineAnimation');
- const spineData = spineComp?.data as Record<string, unknown> | undefined;
- if (spineData?.enabled === false) continue;
-
- const skeletonScale = (spineData?.skeletonScale as number) ?? 1;
- const flipX = (spineData?.flipX as boolean) ?? false;
- const flipY = (spineData?.flipY as boolean) ?? false;
- const playing = spineData?.playing !== false;
- const timeScale = (spineData?.timeScale as number) ?? 1;
- const color = spineData?.color as { r: number; g: number; b: number; a: number } | undefined;
-
- if (playing) {
- this.spineController_.update(instanceId, dt * timeScale);
- }
-
- const entity = this.entityMap_.get(entityId);
- if (entity === undefined) continue;
-
- const scaleX = skeletonScale * (flipX ? -1 : 1);
- const scaleY = skeletonScale * (flipY ? -1 : 1);
-
- const registry = this.registry;
- let transform: Float32Array | undefined;
-
- if (registry.hasTransform(entity)) {
- const wt = registry.getTransform(entity) as TransformData;
- transform = transformToMatrix4x4({
- position: wt.worldPosition,
- rotation: wt.worldRotation,
- scale: { x: wt.worldScale.x * scaleX, y: wt.worldScale.y * scaleY, z: wt.worldScale.z },
- });
- }
-
- submitSpineMeshesToCore(coreModule, this.spineController_, instanceId, transform, color);
- }
- }
-
- getSpineBoundsFromModule(sceneEntityId: number): { x: number; y: number; width: number; height: number } | null {
- if (!this.spineController_) return null;
- const instanceId = this.spineInstances_.get(sceneEntityId);
- if (instanceId === undefined) return null;
- return this.spineController_.getBounds(instanceId);
- }
-
getBitmapTextBounds(entityId: number): { width: number; height: number; offsetX: number; offsetY: number } | null {
const entity = this.entityMap_.get(entityId);
if (entity === undefined) return null;
@@ -592,16 +511,10 @@ export class EditorSceneManager {
}
hasSpineInstance(entityId: number): boolean {
- return this.spineInstances_.has(entityId);
- }
-
- get spineInstanceCount(): number {
- let count = 0;
- for (const entityId of this.spineInstances_.keys()) {
- const entityData = this.entityDataMap_.get(entityId);
- if (entityData && entityData.visible !== false) count++;
- }
- return count;
+ const entity = this.entityMap_.get(entityId);
+ if (entity === undefined) return false;
+ if (this.spineManager_?.hasInstance(entity)) return true;
+ return SpineCpp.hasInstance(entity);
}
onSpineInstanceReady(listener: (entityId: number) => void): () => void {
@@ -610,50 +523,35 @@ export class EditorSceneManager {
}
getSpineSkeletonInfo(entityId: number): { animations: string[]; skins: string[] } | null {
- if (!this.spineController_) return null;
- const instanceId = this.spineInstances_.get(entityId);
- if (instanceId === undefined) return null;
+ const entity = this.entityMap_.get(entityId);
+ if (entity === undefined) return null;
+ if (this.spineManager_?.hasInstance(entity)) {
+ return {
+ animations: this.spineManager_.getAnimations(entity),
+ skins: this.spineManager_.getSkins(entity),
+ };
+ }
+ if (!SpineCpp.hasInstance(entity)) return null;
return {
- animations: this.spineController_.getAnimations(instanceId),
- skins: this.spineController_.getSkins(instanceId),
+ animations: SpineCpp.getAnimations(entity),
+ skins: SpineCpp.getSkins(entity),
};
}
- // =========================================================================
- // Spine Instance Lifecycle
- // =========================================================================
-
- private destroySpineInstance(entityId: number): void {
- const instanceId = this.spineInstances_.get(entityId);
- if (instanceId !== undefined && this.spineController_) {
- this.spineController_.destroyInstance(instanceId);
- }
- this.spineInstances_.delete(entityId);
- this.spineInstanceKeys_.delete(entityId);
- this.spineCurrentState_.delete(entityId);
- }
-
- private clearSpineInstances(): void {
- if (this.spineController_) {
- for (const instanceId of this.spineInstances_.values()) {
- this.spineController_.destroyInstance(instanceId);
- }
- }
- this.spineInstances_.clear();
- this.spineSkeletons_.clear();
- this.spineInstanceKeys_.clear();
- this.spineCurrentState_.clear();
- }
-
// =========================================================================
// Cleanup
// =========================================================================
clear(): void {
- this.clearSpineInstances();
for (const entityId of this.entityMap_.keys()) {
getDependencyGraph().clearEntity(entityId);
}
+ if (this.spineManager_) {
+ for (const entity of this.entityMap_.values()) {
+ this.spineManager_.removeEntity(entity);
+ }
+ }
+ this.pendingSpineData_.clear();
for (const entity of this.world_.getAllEntities()) {
this.world_.despawn(entity);
}
@@ -826,7 +724,18 @@ export class EditorSceneManager {
data[spineDesc.skeletonField] = skelPath;
data[spineDesc.atlasField] = atlasPath;
- if (!this.spineController_) {
+ if (this.spineManager_) {
+ const rawResult = await this.assetServer_.loadSpineWithRawData(skelPath, atlasPath);
+ if (rawResult.success && rawResult.skelData) {
+ this.pendingSpineData_.set(entityId, {
+ skelData: rawResult.skelData,
+ atlasText: rawResult.atlasText!,
+ textures: rawResult.textures!,
+ });
+ } else {
+ console.warn(`[EditorSceneManager] Failed to load Spine raw data: ${rawResult.error}`);
+ }
+ } else {
const result = await this.assetServer_.loadSpine(skelPath, atlasPath);
if (!result.success) {
console.warn(`[EditorSceneManager] Failed to load Spine: ${result.error}`);
@@ -918,7 +827,7 @@ export class EditorSceneManager {
}
// =========================================================================
- // Spine Instance Sync (post-load hook)
+ // Post-load hooks
// =========================================================================
private async applyAnimFirstFrame(entityId: number, data: Record<string, any>): Promise<void> {
@@ -944,67 +853,35 @@ export class EditorSceneManager {
}
private async syncSpineInstance(entityId: number, data: Record<string, any>): Promise<void> {
- if (!this.spineController_) return;
-
- const controller = this.spineController_;
- const skeletonPath = data.skeletonPath ?? '';
- const atlasPath = data.atlasPath ?? '';
- if (!skeletonPath || !atlasPath) return;
-
- const cacheKey = `${skeletonPath}:${atlasPath}`;
- const existingKey = this.spineInstanceKeys_.get(entityId);
- let instanceId = this.spineInstances_.get(entityId);
-
- if (instanceId === undefined || existingKey !== cacheKey) {
- this.destroySpineInstance(entityId);
-
- let skeletonHandle = this.spineSkeletons_.get(cacheKey);
- if (skeletonHandle === undefined) {
- const result = await this.assetServer_.assetLoader.loadSpineToModule(
- controller, skeletonPath, atlasPath,
- );
- if (!result.success || result.skeletonHandle === undefined) {
- console.warn(`[EditorSceneManager] Failed to load Spine to module: ${result.error}`);
- return;
+ const pending = this.pendingSpineData_.get(entityId);
+ if (pending && this.spineManager_) {
+ this.pendingSpineData_.delete(entityId);
+ const entity = this.entityMap_.get(entityId);
+ if (entity !== undefined) {
+ const cppRegistry = this.world_.getCppRegistry();
+ if (cppRegistry) {
+ const version = await this.spineManager_.loadEntity(
+ entity, pending.skelData, pending.atlasText,
+ pending.textures, cppRegistry);
+ if (version) {
+ this.spineManager_.setEntityProps(entity, {
+ skeletonScale: (data.skeletonScale as number) ?? 1,
+ flipX: (data.flipX as boolean) ?? false,
+ flipY: (data.flipY as boolean) ?? false,
+ layer: (data.layer as number) ?? 0,
+ });
+ const skin = data.skin as string;
+ if (skin) this.spineManager_.setSkin(entity, skin);
+ const animation = data.animation as string;
+ if (animation) {
+ this.spineManager_.setAnimation(entity, animation, data.loop !== false);
+ }
+ }
}
- if (this.spineController_ !== controller) return;
- skeletonHandle = result.skeletonHandle;
- this.spineSkeletons_.set(cacheKey, skeletonHandle);
- }
-
- try {
- instanceId = controller.createInstance(skeletonHandle);
- } catch (e) {
- console.warn(`[EditorSceneManager] Spine createInstance failed for entity ${entityId}:`, e);
- return;
- }
- this.spineInstances_.set(entityId, instanceId);
- this.spineInstanceKeys_.set(entityId, cacheKey);
- this.spineCurrentState_.delete(entityId);
-
- for (const cb of this.spineReadyListeners_) {
- cb(entityId);
}
}
-
- const skin = data.skin ?? DEFAULT_SPINE_SKIN;
- const animation = data.animation ?? '';
- const loop = data.loop ?? true;
- const prev = this.spineCurrentState_.get(entityId);
-
- try {
- if (!prev || prev.skin !== skin) {
- controller.setSkin(instanceId, skin);
- }
- if (!prev || prev.animation !== animation || prev.loop !== loop) {
- if (animation) {
- controller.play(instanceId, animation, loop);
- }
- }
- } catch (e) {
- console.warn(`[EditorSceneManager] Spine state update failed for entity ${entityId}:`, e);
+ for (const cb of this.spineReadyListeners_) {
+ cb(entityId);
}
-
- this.spineCurrentState_.set(entityId, { animation, skin, loop });
}
}
diff --git a/editor/src/services/SpineService.ts b/editor/src/services/SpineService.ts
index 3a4e0ba02..c1339adde 100644
--- a/editor/src/services/SpineService.ts
+++ b/editor/src/services/SpineService.ts
@@ -1,15 +1,12 @@
-import type { SpineWasmModule } from 'esengine/spine';
-import { SpineModuleController, wrapSpineModule } from 'esengine/spine';
import type { EditorStore } from '../store/EditorStore';
export interface SpinePanelDelegate {
- setSpineController(ctrl: SpineModuleController | null): void;
+ setSpineController(ctrl: unknown): void;
getSpineSkeletonInfo(entityId: number): { animations: string[]; skins: string[] } | null;
onSpineInstanceReady(listener: (entityId: number) => void): () => void;
}
export class SpineService {
- private spineModule_: unknown = null;
private spineVersion_: string = 'none';
private spineVersionChangeHandler_: ((version: string) => void) | null = null;
private store_: EditorStore;
@@ -21,22 +18,11 @@ export class SpineService {
registerSpinePanel(delegate: SpinePanelDelegate): () => void {
this.delegate_ = delegate;
- if (this.spineModule_) {
- const raw = this.spineModule_ as SpineWasmModule;
- const controller = new SpineModuleController(raw, wrapSpineModule(raw));
- delegate.setSpineController(controller);
- }
return () => { this.delegate_ = null; };
}
- setSpineModule(module: unknown, version: string): void {
- this.spineModule_ = module;
+ setSpineModule(_module: unknown, version: string): void {
this.spineVersion_ = version;
- if (this.delegate_ && module) {
- const raw = module as SpineWasmModule;
- const controller = new SpineModuleController(raw, wrapSpineModule(raw));
- this.delegate_.setSpineController(controller);
- }
this.store_.notifyChange();
}
@@ -48,10 +34,6 @@ export class SpineService {
this.spineVersionChangeHandler_?.(version);
}
- get spineModule(): unknown {
- return this.spineModule_;
- }
-
get spineVersion(): string {
return this.spineVersion_;
}