A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
feat: add Spine animation support with asset loading system
esenginee16f63859dda
diff --git a/.gitmodules b/.gitmodulesindex 0629d202b..fbc2d6d65 100644--- a/.gitmodules+++ b/.gitmodules@@ -13,3 +13,6 @@[submodule "third_party/msdfgen"]path = third_party/msdfgenurl = https://github.com/Chlumsky/msdfgen.git+[submodule "third_party/spine-runtimes"]+ path = third_party/spine-runtimes+ url = https://github.com/EsotericSoftware/spine-runtimes.gitdiff --git a/.vscode/c_cpp_properties.json b/.vscode/c_cpp_properties.jsonindex 6579b3692..9413df613 100644--- a/.vscode/c_cpp_properties.json+++ b/.vscode/c_cpp_properties.json@@ -1,5 +1,29 @@{"configurations": [+ {+ "name": "Mac",+ "includePath": [+ "${workspaceFolder}/src",+ "${workspaceFolder}/include",+ "${workspaceFolder}/third_party/glm",+ "${workspaceFolder}/third_party/glfw/include",+ "${workspaceFolder}/third_party/glad/include",+ "${workspaceFolder}/third_party/stb",+ "${workspaceFolder}/third_party/spine-runtimes/spine-cpp/spine-cpp/include",+ "${workspaceFolder}/third_party/json/single_include",+ "${workspaceFolder}/build/quickjs_headers"+ ],+ "defines": [+ "_DEBUG",+ "ES_PLATFORM_NATIVE",+ "ES_PLATFORM_MACOS",+ "ES_DEBUG"+ ],+ "cStandard": "c17",+ "cppStandard": "c++20",+ "intelliSenseMode": "macos-clang-arm64",+ "compileCommands": "${workspaceFolder}/build/compile_commands.json"+ },{"name": "Win32","includePath": [@@ -9,6 +33,8 @@"${workspaceFolder}/third_party/glfw/include","${workspaceFolder}/third_party/glad/include","${workspaceFolder}/third_party/stb",+ "${workspaceFolder}/third_party/spine-runtimes/spine-cpp/spine-cpp/include",+ "${workspaceFolder}/third_party/json/single_include","${workspaceFolder}/build/quickjs_headers"],"defines": [diff --git a/editor/src/asset/AssetLoader.ts b/editor/src/asset/AssetLoader.tsnew file mode 100644index 000000000..d3aee5f95--- /dev/null+++ b/editor/src/asset/AssetLoader.ts@@ -0,0 +1,281 @@+/**+ * @file AssetLoader.ts+ * @brief Asset loading for editor with Emscripten virtual filesystem support+ */++import type { ESEngineModule } from 'esengine';+import type { AssetPathResolver } from './AssetPathResolver';++interface DecodedImage {+ width: number;+ height: number;+ data: Uint8Array;+}++interface NativeFS {+ readFile(path: string): Promise<string | null>;+ readBinaryFile(path: string): Promise<Uint8Array | null>;+}++export interface LoadResult {+ success: boolean;+ error?: string;+}++interface SpineLoadState {+ skeleton: boolean;+ atlas: boolean;+ textures: Map<string, number>;+}++export class AssetLoader {+ private module_: ESEngineModule;+ private pathResolver_: AssetPathResolver;+ private loadedTextures_: Map<string, number> = new Map();+ private loadedSpines_: Map<string, SpineLoadState> = new Map();+ private virtualFSPaths_: Set<string> = new Set();++ constructor(module: ESEngineModule, pathResolver: AssetPathResolver) {+ this.module_ = module;+ this.pathResolver_ = pathResolver;+ }++ async loadTexture(relativePath: string): Promise<{ success: boolean; handle?: number; error?: string }> {+ const existing = this.loadedTextures_.get(relativePath);+ if (existing !== undefined) {+ return { success: true, handle: existing };+ }++ const fs = this.getNativeFS();+ if (!fs) {+ return { success: false, error: 'Native filesystem not available' };+ }++ const absolutePath = this.pathResolver_.toAbsolutePath(relativePath);+ const data = await fs.readBinaryFile(absolutePath);+ if (!data) {+ return { success: false, error: `Failed to read: ${absolutePath}` };+ }++ const decoded = await this.decodeImage(data);+ if (!decoded) {+ return { success: false, error: `Failed to decode: ${relativePath}` };+ }++ const rm = this.module_.getResourceManager();+ if (!rm) {+ return { success: false, error: 'ResourceManager not available' };+ }++ const pixelPtr = this.module_._malloc(decoded.data.length);+ this.module_.HEAPU8.set(decoded.data, pixelPtr);++ const handleId = rm.createTexture(decoded.width, decoded.height, pixelPtr, decoded.data.length, 1);+ this.module_._free(pixelPtr);++ const INVALID_HANDLE = 0xFFFFFFFF;+ if (handleId === INVALID_HANDLE) {+ return { success: false, error: `Failed to create GPU texture: ${relativePath}` };+ }++ rm.registerTextureWithPath(handleId, relativePath);+ this.loadedTextures_.set(relativePath, handleId);++ return { success: true, handle: handleId };+ }++ async loadSpine(skeletonPath: string, atlasPath: string): Promise<LoadResult> {+ const cacheKey = `${skeletonPath}:${atlasPath}`;+ const existing = this.loadedSpines_.get(cacheKey);+ if (existing?.skeleton && existing?.atlas && existing.textures.size > 0) {+ return { success: true };+ }++ const fs = this.getNativeFS();+ if (!fs) {+ return { success: false, error: 'Native filesystem not available' };+ }++ const state: SpineLoadState = existing ?? { skeleton: false, atlas: false, textures: new Map() };++ if (!state.atlas) {+ const atlasAbsPath = this.pathResolver_.toAbsolutePath(atlasPath);+ const atlasContent = await fs.readFile(atlasAbsPath);+ if (!atlasContent) {+ return { success: false, error: `Failed to read atlas: ${atlasAbsPath}` };+ }++ if (!this.writeToVirtualFS(atlasPath, atlasContent)) {+ return { success: false, error: `Failed to write atlas: ${atlasPath}` };+ }+ state.atlas = true;++ const atlasDir = atlasPath.substring(0, atlasPath.lastIndexOf('/'));+ const textureNames = this.parseAtlasTextures(atlasContent);++ for (const texName of textureNames) {+ const texPath = atlasDir ? `${atlasDir}/${texName}` : texName;++ if (state.textures.has(texPath)) continue;++ const result = await this.loadTexture(texPath);+ if (result.success && result.handle !== undefined) {+ state.textures.set(texPath, result.handle);+ } else {+ console.error(`[AssetLoader] Failed to load Spine texture: ${texPath} - ${result.error}`);+ }+ }+ }++ if (!state.skeleton) {+ const skelAbsPath = this.pathResolver_.toAbsolutePath(skeletonPath);+ const isBinary = skeletonPath.endsWith('.skel');+ const skelData = isBinary+ ? await fs.readBinaryFile(skelAbsPath)+ : await fs.readFile(skelAbsPath);++ if (!skelData) {+ return { success: false, error: `Failed to read skeleton: ${skelAbsPath}` };+ }++ if (!this.writeToVirtualFS(skeletonPath, skelData)) {+ return { success: false, error: `Failed to write skeleton: ${skeletonPath}` };+ }+ state.skeleton = true;+ }++ this.loadedSpines_.set(cacheKey, state);+ return { success: true };+ }++ isTextureLoaded(path: string): boolean {+ return this.loadedTextures_.has(path);+ }++ isSpineLoaded(skeletonPath: string, atlasPath: string): boolean {+ const cacheKey = `${skeletonPath}:${atlasPath}`;+ const state = this.loadedSpines_.get(cacheKey);+ return !!(state?.skeleton && state?.atlas);+ }++ getTextureHandle(path: string): number | undefined {+ return this.loadedTextures_.get(path);+ }++ releaseTexture(path: string): void {+ const handle = this.loadedTextures_.get(path);+ if (handle !== undefined) {+ const rm = this.module_.getResourceManager();+ rm?.releaseTexture(handle);+ this.loadedTextures_.delete(path);+ }+ }++ clearCache(): void {+ this.loadedTextures_.clear();+ this.loadedSpines_.clear();+ this.virtualFSPaths_.clear();+ }++ private writeToVirtualFS(virtualPath: string, data: string | Uint8Array): boolean {+ if (this.virtualFSPaths_.has(virtualPath)) {+ return true;+ }++ const emscriptenFs = this.getEmscriptenFS();+ if (!emscriptenFs) {+ return false;+ }++ try {+ this.ensureVirtualDir(virtualPath);+ emscriptenFs.writeFile(virtualPath, data);+ this.virtualFSPaths_.add(virtualPath);+ return true;+ } catch (e) {+ console.error(`[AssetLoader] Failed to write to virtual FS: ${virtualPath}`, e);+ return false;+ }+ }++ private ensureVirtualDir(virtualPath: string): void {+ const emscriptenFs = this.getEmscriptenFS();+ if (!emscriptenFs) 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 = currentPath ? `${currentPath}/${part}` : part;+ try {+ const analysis = emscriptenFs.analyzePath(currentPath);+ if (!analysis.exists) {+ emscriptenFs.mkdir(currentPath);+ }+ } catch {+ try {+ emscriptenFs.mkdir(currentPath);+ } catch {+ // Directory might already exist+ }+ }+ }+ }++ private parseAtlasTextures(atlasContent: string): string[] {+ const textures: string[] = [];+ const lines = atlasContent.split('\n');++ for (const line of lines) {+ const trimmed = line.trim();+ if (trimmed && !trimmed.includes(':') &&+ (trimmed.endsWith('.png') || trimmed.endsWith('.jpg'))) {+ textures.push(trimmed);+ }+ }++ return textures;+ }++ private getNativeFS(): NativeFS | null {+ return (window as any).__esengine_fs ?? null;+ }++ private getEmscriptenFS(): any {+ return this.module_.FS ?? null;+ }++ private async decodeImage(data: Uint8Array): Promise<DecodedImage | null> {+ try {+ const blob = new Blob([new Uint8Array(data)]);+ const bitmap = await createImageBitmap(blob);++ const canvas = document.createElement('canvas');+ canvas.width = bitmap.width;+ canvas.height = bitmap.height;++ const ctx = canvas.getContext('2d');+ if (!ctx) {+ bitmap.close();+ return null;+ }++ ctx.drawImage(bitmap, 0, 0);+ bitmap.close();++ const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);++ return {+ width: canvas.width,+ height: canvas.height,+ data: new Uint8Array(imageData.data.buffer)+ };+ } catch (e) {+ console.error('[AssetLoader] Failed to decode image:', e);+ return null;+ }+ }+}diff --git a/editor/src/asset/AssetPathResolver.ts b/editor/src/asset/AssetPathResolver.tsnew file mode 100644index 000000000..bf7a0d7a0--- /dev/null+++ b/editor/src/asset/AssetPathResolver.ts@@ -0,0 +1,89 @@+/**+ * @file AssetPathResolver.ts+ * @brief Unified path resolution for editor assets+ */++interface NativeFS {+ exists(path: string): Promise<boolean>;+ readFile(path: string): Promise<string | null>;+ readBinaryFile(path: string): Promise<Uint8Array | null>;+}++export interface PathValidationResult {+ exists: boolean;+ error?: string;+}++export class AssetPathResolver {+ private projectDir_ = '';++ setProjectDir(dir: string): void {+ this.projectDir_ = this.normalizePath(dir);+ }++ getProjectDir(): string {+ return this.projectDir_;+ }++ toRelativePath(absolutePath: string): string {+ const normalized = this.normalizePath(absolutePath);+ if (!this.projectDir_) {+ return normalized;+ }++ if (normalized.startsWith(this.projectDir_)) {+ const relative = normalized.substring(this.projectDir_.length);+ return relative.startsWith('/') ? relative.substring(1) : relative;+ }++ return normalized;+ }++ toAbsolutePath(relativePath: string): string {+ const normalized = this.normalizePath(relativePath);+ if (this.isAbsolute(normalized)) {+ return normalized;+ }++ if (!this.projectDir_) {+ return normalized;+ }++ return `${this.projectDir_}/${normalized}`;+ }++ async validatePath(path: string): Promise<PathValidationResult> {+ const fs = this.getNativeFS();+ if (!fs) {+ return { exists: false, error: 'Native filesystem not available' };+ }++ const absolutePath = this.toAbsolutePath(path);++ try {+ if (typeof fs.exists === 'function') {+ const exists = await fs.exists(absolutePath);+ return { exists };+ }++ const content = await fs.readBinaryFile(absolutePath);+ return { exists: content !== null };+ } catch (err) {+ const message = err instanceof Error ? err.message : String(err);+ return { exists: false, error: message };+ }+ }++ isAbsolute(path: string): boolean {+ const normalized = this.normalizePath(path);+ return normalized.startsWith('/') || /^[A-Za-z]:/.test(normalized);+ }++ private normalizePath(path: string): string {+ return path.replace(/\\/g, '/');+ }++ private getNativeFS(): NativeFS | null {+ return (window as any).__esengine_fs ?? null;+ }+}diff --git a/editor/src/asset/index.ts b/editor/src/asset/index.tsnew file mode 100644index 000000000..0d29723f8--- /dev/null+++ b/editor/src/asset/index.ts@@ -0,0 +1,21 @@+/**+ * @file index.ts+ * @brief Asset module exports+ */++export { AssetPathResolver } from './AssetPathResolver';+export type { PathValidationResult } from './AssetPathResolver';++export { AssetLoader } from './AssetLoader';+export type { LoadResult } from './AssetLoader';++import { AssetPathResolver } from './AssetPathResolver';++let globalPathResolver: AssetPathResolver | null = null;++export function getGlobalPathResolver(): AssetPathResolver {+ if (!globalPathResolver) {+ globalPathResolver = new AssetPathResolver();+ }+ return globalPathResolver;+}diff --git a/editor/src/bounds/SpineAnimationBoundsProvider.ts b/editor/src/bounds/SpineAnimationBoundsProvider.tsnew file mode 100644index 000000000..a87c6bbcc--- /dev/null+++ b/editor/src/bounds/SpineAnimationBoundsProvider.ts@@ -0,0 +1,20 @@+/**+ * @file SpineAnimationBoundsProvider.ts+ * @brief Bounds provider for SpineAnimation component+ */++import type { Bounds, BoundsProvider } from './BoundsProvider';++const DEFAULT_SPINE_SIZE = 200;++export const spineAnimationBoundsProvider: BoundsProvider = {+ getBounds(data: any): Bounds | null {+ if (data?.bounds?.width && data?.bounds?.height) {+ return { width: data.bounds.width, height: data.bounds.height };+ }++ const scale = data?.skeletonScale ?? 1;+ const size = DEFAULT_SPINE_SIZE * scale;+ return { width: size, height: size };+ }+};diff --git a/editor/src/bounds/index.ts b/editor/src/bounds/index.tsindex 5721159c4..03ff0d2fe 100644--- a/editor/src/bounds/index.ts+++ b/editor/src/bounds/index.ts@@ -10,9 +10,11 @@ import { registerBoundsProvider } from './BoundsRegistry';import { spriteBoundsProvider } from './SpriteBoundsProvider';import { textBoundsProvider } from './TextBoundsProvider';import { uiRectBoundsProvider } from './UIRectBoundsProvider';+import { spineAnimationBoundsProvider } from './SpineAnimationBoundsProvider';export function initBoundsProviders(): void {registerBoundsProvider('UIRect', uiRectBoundsProvider);registerBoundsProvider('Sprite', spriteBoundsProvider);registerBoundsProvider('Text', textBoundsProvider);+ registerBoundsProvider('SpineAnimation', spineAnimationBoundsProvider);}diff --git a/editor/src/panels/HierarchyPanel.ts b/editor/src/panels/HierarchyPanel.tsindex 1cadbd945..5477b8ad9 100644--- a/editor/src/panels/HierarchyPanel.ts+++ b/editor/src/panels/HierarchyPanel.ts@@ -7,6 +7,7 @@ import type { Entity } from 'esengine';import type { EntityData, SceneData } from '../types/SceneTypes';import type { EditorStore } from '../store/EditorStore';import { icons } from '../utils/icons';+import { getGlobalPathResolver } from '../asset';// =============================================================================// HierarchyPanel@@ -123,6 +124,192 @@ export class HierarchyPanel {this.showContextMenu(e.clientX, e.clientY, null);}});++ this.setupDragAndDrop();+ }++ private setupDragAndDrop(): void {+ this.treeContainer_.addEventListener('dragover', (e) => {+ const types = e.dataTransfer?.types ?? [];+ const hasAssetData = Array.from(types).includes('application/esengine-asset');+ if (!hasAssetData) return;++ e.preventDefault();+ e.dataTransfer!.dropEffect = 'copy';++ const target = e.target as HTMLElement;+ const item = target.closest('.es-hierarchy-item') as HTMLElement;++ this.treeContainer_.querySelectorAll('.es-drag-over').forEach(el => {+ el.classList.remove('es-drag-over');+ });++ if (item) {+ item.classList.add('es-drag-over');+ } else {+ this.treeContainer_.classList.add('es-drag-over');+ }+ });++ this.treeContainer_.addEventListener('dragleave', (e) => {+ const relatedTarget = e.relatedTarget as HTMLElement;+ if (this.treeContainer_.contains(relatedTarget)) return;++ this.treeContainer_.querySelectorAll('.es-drag-over').forEach(el => {+ el.classList.remove('es-drag-over');+ });+ this.treeContainer_.classList.remove('es-drag-over');+ });++ this.treeContainer_.addEventListener('drop', (e) => {+ e.preventDefault();++ this.treeContainer_.querySelectorAll('.es-drag-over').forEach(el => {+ el.classList.remove('es-drag-over');+ });+ this.treeContainer_.classList.remove('es-drag-over');++ const assetDataStr = e.dataTransfer?.getData('application/esengine-asset');+ if (!assetDataStr) return;++ let assetData: { type: string; path: string; name: string };+ try {+ assetData = JSON.parse(assetDataStr);+ } catch {+ return;+ }++ const target = e.target as HTMLElement;+ const item = target.closest('.es-hierarchy-item') as HTMLElement;+ const parentEntity = item+ ? parseInt(item.dataset.entityId ?? '', 10) as Entity+ : null;++ this.createEntityFromAsset(assetData, parentEntity);+ });+ }++ private async createEntityFromAsset(+ asset: { type: string; path: string; name: string },+ parent: Entity | null+ ): Promise<void> {+ const baseName = asset.name.replace(/\.[^.]+$/, '');++ if (asset.type === 'spine' || asset.type === 'json') {+ const ext = asset.name.substring(asset.name.lastIndexOf('.')).toLowerCase();+ if (ext === '.atlas') return;++ const skeletonPath = this.toRelativePath(asset.path);+ const atlasPath = await this.findAtlasFile(skeletonPath);++ if (!atlasPath) {+ console.error(`[HierarchyPanel] No atlas file found for: ${skeletonPath}`);+ alert(`无法找到 atlas 文件。\n请确保骨骼文件所在目录下有 .atlas 文件。`);+ return;+ }++ const newEntity = this.store_.createEntity(baseName, parent);++ this.store_.addComponent(newEntity, 'LocalTransform', {+ position: { x: 0, y: 0, z: 0 },+ rotation: { x: 0, y: 0, z: 0, w: 1 },+ scale: { x: 1, y: 1, z: 1 },+ });++ this.store_.addComponent(newEntity, 'SpineAnimation', {+ skeletonPath,+ atlasPath,+ skin: 'default',+ animation: '',+ timeScale: 1,+ loop: true,+ playing: true,+ flipX: false,+ flipY: false,+ color: { x: 1, y: 1, z: 1, w: 1 },+ layer: 0,+ skeletonScale: 1,+ });+ } else if (asset.type === 'image') {+ const newEntity = this.store_.createEntity(baseName, parent);++ this.store_.addComponent(newEntity, 'LocalTransform', {+ position: { x: 0, y: 0, z: 0 },+ rotation: { x: 0, y: 0, z: 0, w: 1 },+ scale: { x: 1, y: 1, z: 1 },+ });++ this.store_.addComponent(newEntity, 'UIRect', {+ size: { x: 100, y: 100 },+ anchor: { x: 0.5, y: 0.5 },+ pivot: { x: 0.5, y: 0.5 },+ });++ this.store_.addComponent(newEntity, 'Sprite', {+ texture: this.toRelativePath(asset.path),+ color: { x: 1, y: 1, z: 1, w: 1 },+ size: { x: 100, y: 100 },+ uvOffset: { x: 0, y: 0 },+ uvScale: { x: 1, y: 1 },+ layer: 0,+ flipX: false,+ flipY: false,+ });+ }+ }++ private toRelativePath(absolutePath: string): string {+ return getGlobalPathResolver().toRelativePath(absolutePath);+ }++ private async findAtlasFile(skeletonPath: string): Promise<string | null> {+ const pathResolver = getGlobalPathResolver();++ const sameNameAtlas = skeletonPath.replace(/\.(json|skel)$/i, '.atlas');+ const validation = await pathResolver.validatePath(sameNameAtlas);+ if (validation.exists) {+ return sameNameAtlas;+ }++ const dir = skeletonPath.substring(0, skeletonPath.lastIndexOf('/'));+ const absoluteDir = pathResolver.toAbsolutePath(dir);++ const fs = (window as any).__esengine_fs;+ if (!fs?.listDirectoryDetailed) {+ return null;+ }++ try {+ const entries = await fs.listDirectoryDetailed(absoluteDir);+ const atlasFiles = entries+ .filter((e: { name: string; isFile: boolean }) =>+ e.isFile && e.name.endsWith('.atlas'))+ .map((e: { name: string }) => e.name);++ if (atlasFiles.length === 1) {+ return dir ? `${dir}/${atlasFiles[0]}` : atlasFiles[0];+ }++ if (atlasFiles.length > 1) {+ const baseName = skeletonPath+ .substring(skeletonPath.lastIndexOf('/') + 1)+ .replace(/\.(json|skel)$/i, '');++ const matching = atlasFiles.find((name: string) =>+ name.replace('.atlas', '').toLowerCase().includes(baseName.toLowerCase().split('-')[0])+ );++ if (matching) {+ return dir ? `${dir}/${matching}` : matching;+ }++ return dir ? `${dir}/${atlasFiles[0]}` : atlasFiles[0];+ }+ } catch (err) {+ console.warn('[HierarchyPanel] Failed to scan directory for atlas files:', err);+ }++ return null;}private render(): void {@@ -173,8 +360,10 @@ export class HierarchyPanel {const hasCamera = entity.components.some(c => c.type === 'Camera');const hasSprite = entity.components.some(c => c.type === 'Sprite');const hasText = entity.components.some(c => c.type === 'Text');+ const hasSpine = entity.components.some(c => c.type === 'SpineAnimation');if (hasCamera) return icons.camera(12);+ if (hasSpine) return icons.bone(12);if (hasText) return icons.type(12);if (hasSprite) return icons.image(12);return icons.box(12);@@ -182,7 +371,9 @@ export class HierarchyPanel {private getEntityType(entity: EntityData): string {const hasCamera = entity.components.some(c => c.type === 'Camera');+ const hasSpine = entity.components.some(c => c.type === 'SpineAnimation');if (hasCamera) return 'Camera';+ if (hasSpine) return 'Spine';return 'Entity';}@@ -231,6 +422,7 @@ export class HierarchyPanel {{ label: 'Create Entity', action: () => this.store_.createEntity(undefined, entity) },{ label: 'Create Sprite', action: () => this.createEntityWithComponent('Sprite', entity) },{ label: 'Create Text', action: () => this.createEntityWithComponent('Text', entity) },+ { label: 'Create Spine', action: () => this.createEntityWithComponent('SpineAnimation', entity) },{ label: 'Create Camera', action: () => this.createEntityWithComponent('Camera', entity), separator: true },];@@ -321,6 +513,21 @@ export class HierarchyPanel {anchor: { x: 0.5, y: 0.5 },pivot: { x: 0.5, y: 0.5 },};+ case 'SpineAnimation':+ return {+ skeletonPath: '',+ atlasPath: '',+ skin: 'default',+ animation: '',+ timeScale: 1,+ loop: true,+ playing: true,+ flipX: false,+ flipY: false,+ color: { x: 1, y: 1, z: 1, w: 1 },+ layer: 0,+ skeletonScale: 1,+ };default:return {};}diff --git a/editor/src/panels/SceneViewPanel.ts b/editor/src/panels/SceneViewPanel.tsindex e9b2e0656..341717b97 100644--- a/editor/src/panels/SceneViewPanel.ts+++ b/editor/src/panels/SceneViewPanel.ts@@ -73,6 +73,7 @@ export class SceneViewPanel {private overlayCanvas_: HTMLCanvasElement | null = null;private unsubscribe_: (() => void) | null = null;private animationId_: number | null = null;+ private continuousRender_ = false;private resizeObserver_: ResizeObserver | null = null;private projectPath_: string | null = null;private app_: App | null = null;@@ -123,6 +124,22 @@ export class SceneViewPanel {return null;}+ private getEntityBoundsWithSpine(entityData: import('../types/SceneTypes').EntityData): { width: number; height: number; offsetX?: number; offsetY?: number } {+ const hasSpine = entityData.components.some(c => c.type === 'SpineAnimation');+ if (hasSpine && this.sceneRenderer_) {+ const spineBounds = this.sceneRenderer_.getSpineBounds(entityData.id);+ if (spineBounds) {+ return {+ width: Math.abs(spineBounds.width),+ height: Math.abs(spineBounds.height),+ offsetX: spineBounds.x + spineBounds.width / 2,+ offsetY: spineBounds.y + spineBounds.height / 2+ };+ }+ }+ return getEntityBounds(entityData.components);+ }+constructor(container: HTMLElement, store: EditorStore, options?: SceneViewPanelOptions) {this.container_ = container;this.store_ = store;@@ -199,6 +216,7 @@ export class SceneViewPanel {}dispose(): void {+ this.continuousRender_ = false;if (this.animationId_ !== null) {cancelAnimationFrame(this.animationId_);this.animationId_ = null;@@ -274,7 +292,7 @@ export class SceneViewPanel {}await this.syncSceneToRenderer();- this.requestRender();+ this.startContinuousRender();} else {console.warn('WebGL init failed, falling back to Canvas 2D');this.sceneRenderer_ = null;@@ -513,7 +531,7 @@ export class SceneViewPanel {this.rectDragStartSize_ = { x: size.x, y: size.y };this.rectDragOriginalSize_ = { x: size.x, y: size.y };} else {- const bounds = getEntityBounds(entityData.components);+ const bounds = this.getEntityBoundsWithSpine(entityData);this.rectDragStartSize_ = { x: bounds.width, y: bounds.height };this.rectDragOriginalSize_ = { x: bounds.width, y: bounds.height };}@@ -911,16 +929,18 @@ export class SceneViewPanel {if (!pos) return 'none';const worldTransform = this.store_.getWorldTransform(entityData.id);- const bounds = getEntityBounds(entityData.components);+ const bounds = this.getEntityBoundsWithSpine(entityData);const w = bounds.width * Math.abs(worldTransform.scale.x);const h = bounds.height * Math.abs(worldTransform.scale.y);+ const offsetX = (bounds.offsetX ?? 0) * worldTransform.scale.x;+ const offsetY = (bounds.offsetY ?? 0) * worldTransform.scale.y;const halfW = w / 2;const halfH = h / 2;const handleSize = GIZMO_HANDLE_SIZE / this.zoom_;- const dx = worldX - pos.x;- const dy = worldY - pos.y;+ const dx = worldX - pos.x - offsetX;+ const dy = worldY - pos.y - offsetY;const handles: { x: number; y: number; key: RectHandle }[] = [{ x: -halfW, y: halfH, key: 'tl' },@@ -1032,18 +1052,22 @@ export class SceneViewPanel {const pos = worldTransform.position;const scale = worldTransform.scale;- const bounds = getEntityBounds(entity.components);+ const bounds = this.getEntityBoundsWithSpine(entity);const w = bounds.width * Math.abs(scale.x);const h = bounds.height * Math.abs(scale.y);+ const offsetX = (bounds.offsetX ?? 0) * scale.x;+ const offsetY = (bounds.offsetY ?? 0) * scale.y;+ const centerX = pos.x + offsetX;+ const centerY = pos.y + offsetY;const halfW = w / 2;const halfH = h / 2;if (- worldX >= pos.x - halfW &&- worldX <= pos.x + halfW &&- worldY >= pos.y - halfH &&- worldY <= pos.y + halfH+ worldX >= centerX - halfW &&+ worldX <= centerX + halfW &&+ worldY >= centerY - halfH &&+ worldY <= centerY + halfH) {return entity.id as Entity;}@@ -1065,9 +1089,23 @@ export class SceneViewPanel {this.animationId_ = requestAnimationFrame(() => {this.animationId_ = null;this.render();+ if (this.continuousRender_) {+ this.requestRender();+ }});}+ startContinuousRender(): void {+ if (!this.continuousRender_) {+ this.continuousRender_ = true;+ this.requestRender();+ }+ }++ stopContinuousRender(): void {+ this.continuousRender_ = false;+ }+private render(): void {if (this.useWebGL_ && this.sceneRenderer_ && this.webglCanvas_) {this.sceneRenderer_.camera.panX = this.panX_;@@ -1128,12 +1166,14 @@ export class SceneViewPanel {const pos = worldTransform.position;const scale = worldTransform.scale;- const bounds = getEntityBounds(entityData.components);+ const bounds = this.getEntityBoundsWithSpine(entityData);const w = bounds.width * Math.abs(scale.x);const h = bounds.height * Math.abs(scale.y);+ const offsetX = (bounds.offsetX ?? 0) * scale.x;+ const offsetY = (bounds.offsetY ?? 0) * scale.y;ctx.save();- ctx.translate(pos.x, -pos.y);+ ctx.translate(pos.x + offsetX, -pos.y - offsetY);ctx.strokeStyle = '#00aaff';ctx.lineWidth = 2 / this.zoom_;@@ -1358,7 +1398,7 @@ export class SceneViewPanel {if (!entityData) return;const worldTransform = this.store_.getWorldTransform(entityData.id);- const bounds = getEntityBounds(entityData.components);+ const bounds = this.getEntityBoundsWithSpine(entityData);const w = bounds.width * Math.abs(worldTransform.scale.x);const h = bounds.height * Math.abs(worldTransform.scale.y);diff --git a/editor/src/renderer/EditorSceneRenderer.ts b/editor/src/renderer/EditorSceneRenderer.tsindex a44152eb7..7dcdbe8aa 100644--- a/editor/src/renderer/EditorSceneRenderer.ts+++ b/editor/src/renderer/EditorSceneRenderer.ts@@ -13,6 +13,7 @@ import {createIdentityTransform,} from '../math/Transform';import { EditorTextRenderer } from './EditorTextRenderer';+import { AssetPathResolver, AssetLoader } from '../asset';// =============================================================================// EditorSceneRenderer@@ -25,7 +26,8 @@ export class EditorSceneRenderer {private textRenderer_: EditorTextRenderer | null = null;private camera_: EditorCamera;private initialized_ = false;- private projectDir_ = '';+ private pathResolver_: AssetPathResolver;+ private assetLoader_: AssetLoader | null = null;/** Map scene entity IDs to runtime entities */private entityMap_: Map<number, Entity> = new Map();@@ -42,6 +44,7 @@ export class EditorSceneRenderer {constructor() {this.camera_ = new EditorCamera();+ this.pathResolver_ = new AssetPathResolver();}/**@@ -60,8 +63,9 @@ export class EditorSceneRenderer {}this.registry_ = new module.Registry();- this.textureManager_ = new EditorTextureManager(module);+ this.textureManager_ = new EditorTextureManager(module, this.pathResolver_);this.textRenderer_ = new EditorTextRenderer(module);+ this.assetLoader_ = new AssetLoader(module, this.pathResolver_);this.initialized_ = true;return true;@@ -71,7 +75,14 @@ export class EditorSceneRenderer {* @brief Set project directory for texture loading*/setProjectDir(projectDir: string): void {- this.projectDir_ = projectDir.replace(/\\/g, '/');+ this.pathResolver_.setProjectDir(projectDir);+ }++ /**+ * @brief Get path resolver for external use+ */+ get pathResolver(): AssetPathResolver {+ return this.pathResolver_;}/**@@ -183,6 +194,22 @@ export class EditorSceneRenderer {return this.textureManager_;}+ /**+ * @brief Get spine bounds for an entity+ * @returns bounds object with x, y, width, height, or null if not found+ */+ getSpineBounds(sceneEntityId: number): { x: number; y: number; width: number; height: number } | null {+ if (!this.module_ || !this.registry_) return null;++ const entity = this.entityMap_.get(sceneEntityId);+ if (entity === undefined) return null;++ const bounds = this.module_.getSpineBounds(this.registry_, entity);+ if (!bounds.valid) return null;++ return { x: bounds.x, y: bounds.y, width: bounds.width, height: bounds.height };+ }+/*** @brief Render a frame*/@@ -267,6 +294,10 @@ export class EditorSceneRenderer {case 'Text':this.syncText(entity, comp.data, entityId);break;++ case 'SpineAnimation':+ await this.syncSpineAnimation(entity, comp.data);+ break;}}@@ -394,11 +425,8 @@ export class EditorSceneRenderer {let textureHandle = 0;const texturePath = data.texture;- if (texturePath && this.projectDir_) {- textureHandle = await this.textureManager_.loadTexture(- this.projectDir_,- texturePath- );+ if (texturePath) {+ textureHandle = await this.textureManager_.loadTexture(texturePath);}if (this.registry_.hasSprite(entity)) {@@ -460,4 +488,41 @@ export class EditorSceneRenderer {flipY: false,});}++ private async syncSpineAnimation(entity: Entity, data: any): Promise<void> {+ if (!this.registry_ || !this.assetLoader_) return;++ const skeletonPath = data.skeletonPath ?? '';+ const atlasPath = data.atlasPath ?? '';++ if (!skeletonPath || !atlasPath) {+ console.warn('[EditorSceneRenderer] SpineAnimation missing skeleton or atlas path');+ return;+ }++ const result = await this.assetLoader_.loadSpine(skeletonPath, atlasPath);+ if (!result.success) {+ console.warn(`[EditorSceneRenderer] Failed to load Spine: ${result.error}`);+ return;+ }++ if (this.registry_.hasSpineAnimation(entity)) {+ this.registry_.removeSpineAnimation(entity);+ }++ this.registry_.addSpineAnimation(entity, {+ skeletonPath,+ atlasPath,+ skin: data.skin ?? 'default',+ animation: data.animation ?? '',+ timeScale: data.timeScale ?? 1,+ loop: data.loop ?? true,+ playing: data.playing ?? true,+ flipX: data.flipX ?? false,+ flipY: data.flipY ?? false,+ color: data.color ?? { x: 1, y: 1, z: 1, w: 1 },+ layer: data.layer ?? 0,+ skeletonScale: data.skeletonScale ?? 1,+ });+ }}diff --git a/editor/src/renderer/EditorTextureManager.ts b/editor/src/renderer/EditorTextureManager.tsindex 53e3d0814..4927f14ce 100644--- a/editor/src/renderer/EditorTextureManager.ts+++ b/editor/src/renderer/EditorTextureManager.ts@@ -5,6 +5,7 @@import type { ESEngineModule } from 'esengine';import { parseTextureMetadata, getMetaFilePath } from '../types/TextureMetadata';+import type { AssetPathResolver } from '../asset';// =============================================================================// Types@@ -27,21 +28,22 @@ interface TextureEntry {export class EditorTextureManager {private module_: ESEngineModule;+ private pathResolver_: AssetPathResolver;private pathToEntry_: Map<string, TextureEntry> = new Map();private pendingLoads_: Map<string, Promise<number>> = new Map();- constructor(module: ESEngineModule) {+ constructor(module: ESEngineModule, pathResolver: AssetPathResolver) {this.module_ = module;+ this.pathResolver_ = pathResolver;}/*** @brief Load texture from file and create GPU texture- * @param projectDir Project root directory- * @param texturePath Relative texture path (e.g., "assets/textures/bg.png")+ * @param texturePath Relative or absolute texture path* @returns Texture handle ID, or 0 if failed*/- async loadTexture(projectDir: string, texturePath: string): Promise<number> {- const fullPath = this.resolvePath(projectDir, texturePath);+ async loadTexture(texturePath: string): Promise<number> {+ const fullPath = this.pathResolver_.toAbsolutePath(texturePath);const existing = this.pathToEntry_.get(fullPath);if (existing) {@@ -53,7 +55,7 @@ export class EditorTextureManager {return pending;}- const loadPromise = this.loadTextureInternal(projectDir, fullPath);+ const loadPromise = this.loadTextureInternal(fullPath);this.pendingLoads_.set(fullPath, loadPromise);try {@@ -68,8 +70,8 @@ export class EditorTextureManager {* @brief Get cached texture handle* @returns Handle ID or null if not loaded*/- getHandle(projectDir: string, texturePath: string): number | null {- const fullPath = this.resolvePath(projectDir, texturePath);+ getHandle(texturePath: string): number | null {+ const fullPath = this.pathResolver_.toAbsolutePath(texturePath);const entry = this.pathToEntry_.get(fullPath);return entry?.handle ?? null;}@@ -77,8 +79,8 @@ export class EditorTextureManager {/*** @brief Get texture dimensions*/- getSize(projectDir: string, texturePath: string): { width: number; height: number } | null {- const fullPath = this.resolvePath(projectDir, texturePath);+ getSize(texturePath: string): { width: number; height: number } | null {+ const fullPath = this.pathResolver_.toAbsolutePath(texturePath);const entry = this.pathToEntry_.get(fullPath);if (!entry) return null;return { width: entry.width, height: entry.height };@@ -98,8 +100,8 @@ export class EditorTextureManager {/*** @brief Release a specific texture*/- release(projectDir: string, texturePath: string): void {- const fullPath = this.resolvePath(projectDir, texturePath);+ release(texturePath: string): void {+ const fullPath = this.pathResolver_.toAbsolutePath(texturePath);const entry = this.pathToEntry_.get(fullPath);if (entry) {const rm = this.module_.getResourceManager();@@ -112,15 +114,7 @@ export class EditorTextureManager {// Private Methods// =========================================================================- private resolvePath(projectDir: string, texturePath: string): string {- const normalized = texturePath.replace(/\\/g, '/');- if (normalized.startsWith('/') || normalized.includes(':')) {- return normalized;- }- return `${projectDir.replace(/\\/g, '/')}/${normalized}`;- }-- private async loadTextureInternal(projectDir: string, fullPath: string): Promise<number> {+ private async loadTextureInternal(fullPath: string): Promise<number> {const fs = this.getNativeFS();if (!fs) {console.warn('[EditorTextureManager] NativeFS not available');@@ -140,7 +134,7 @@ export class EditorTextureManager {this.pathToEntry_.set(fullPath, { handle, width, height });- await this.loadAndApplyMetadata(projectDir, fullPath, handle);+ await this.loadAndApplyMetadata(fullPath, handle);return handle;}@@ -191,7 +185,7 @@ export class EditorTextureManager {}}- private async loadAndApplyMetadata(_projectDir: string, texturePath: string, handle: number): Promise<void> {+ private async loadAndApplyMetadata(texturePath: string, handle: number): Promise<void> {const fs = this.getNativeFS();if (!fs) return;diff --git a/sdk/src/wasm.ts b/sdk/src/wasm.tsindex cdd238ab0..33637ead9 100644--- a/sdk/src/wasm.ts+++ b/sdk/src/wasm.ts@@ -55,9 +55,14 @@ export interface CppRegistry {hasChildren(entity: Entity): boolean;removeChildren(entity: Entity): void;+ addSpineAnimation(entity: Entity, data: unknown): void;+ getSpineAnimation(entity: Entity): unknown;+ hasSpineAnimation(entity: Entity): boolean;+ removeSpineAnimation(entity: Entity): void;+setParent(child: Entity, parent: Entity): void;- [key: string]: unknown;+ [key: string]: any;}// =============================================================================@@ -70,17 +75,40 @@ export interface CppResourceManager {releaseTexture(handle: number): void;releaseShader(handle: number): void;setTextureMetadata(handle: number, left: number, right: number, top: number, bottom: number): void;+ registerTextureWithPath(handle: number, path: string): void;}// =============================================================================// WASM Module Interface// =============================================================================+export interface EmscriptenFS {+ writeFile(path: string, data: string | Uint8Array): void;+ readFile(path: string, opts?: { encoding?: string }): string | Uint8Array;+ mkdir(path: string): void;+ mkdirTree(path: string): void;+ unlink(path: string): void;+ stat(path: string): { mode: number; size: number };+ isFile(mode: number): boolean;+ isDir(mode: number): boolean;+ analyzePath(path: string): { exists: boolean; parentExists: boolean };+}++export interface SpineBounds {+ x: number;+ y: number;+ width: number;+ height: number;+ valid: boolean;+}+export interface ESEngineModule {Registry: new () => CppRegistry;HEAPU8: Uint8Array;HEAPF32: Float32Array;+ FS: EmscriptenFS;+initRenderer(): void;initRendererWithCanvas(canvasSelector: string): boolean;initRendererWithContext(contextHandle: number): boolean;@@ -96,6 +124,7 @@ export interface ESEngineModule {renderFrame(registry: CppRegistry, width: number, height: number): void;renderFrameWithMatrix(registry: CppRegistry, width: number, height: number, matrixPtr: number): void;getResourceManager(): CppResourceManager;+ getSpineBounds(registry: CppRegistry, entity: number): SpineBounds;_malloc(size: number): number;_free(ptr: number): void;diff --git a/src/esengine/bindings/WebSDKEntry.cpp b/src/esengine/bindings/WebSDKEntry.cppindex 4be5080bf..1ae188852 100644--- a/src/esengine/bindings/WebSDKEntry.cpp+++ b/src/esengine/bindings/WebSDKEntry.cpp@@ -25,6 +25,9 @@#include "../ecs/TransformSystem.hpp"#include "../ecs/components/Camera.hpp"#include "../ecs/components/Transform.hpp"+#include "../spine/SpineResourceManager.hpp"+#include "../spine/SpineSystem.hpp"+#include "../spine/SpineRenderer.hpp"#include <glm/gtc/matrix_transform.hpp>#include <glm/gtc/type_ptr.hpp>@@ -35,6 +38,9 @@ static Unique<RenderContext> g_renderContext;static Unique<RenderPipeline> g_renderPipeline;static Unique<ecs::TransformSystem> g_transformSystem;static Unique<resource::ResourceManager> g_resourceManager;+static Unique<spine::SpineResourceManager> g_spineResourceManager;+static Unique<spine::SpineSystem> g_spineSystem;+static Unique<spine::SpineRenderer> g_spineRenderer;static EMSCRIPTEN_WEBGL_CONTEXT_HANDLE g_webglContext = 0;static bool g_initialized = false;@@ -77,6 +83,14 @@ bool initRendererInternal(const char* canvasSelector) {g_renderPipeline = makeUnique<RenderPipeline>(*g_renderContext, *g_resourceManager);g_transformSystem = makeUnique<ecs::TransformSystem>();+ g_spineResourceManager = makeUnique<spine::SpineResourceManager>(*g_resourceManager);+ g_spineResourceManager->init();++ g_spineSystem = makeUnique<spine::SpineSystem>(*g_spineResourceManager);++ g_spineRenderer = makeUnique<spine::SpineRenderer>(*g_renderContext, *g_resourceManager, *g_spineSystem);+ g_spineRenderer->init();+g_initialized = true;glClearColor(0.0f, 0.0f, 0.0f, 1.0f);@@ -120,6 +134,14 @@ bool initRendererWithContext(int contextHandle) {g_renderPipeline = makeUnique<RenderPipeline>(*g_renderContext, *g_resourceManager);g_transformSystem = makeUnique<ecs::TransformSystem>();+ g_spineResourceManager = makeUnique<spine::SpineResourceManager>(*g_resourceManager);+ g_spineResourceManager->init();++ g_spineSystem = makeUnique<spine::SpineSystem>(*g_spineResourceManager);++ g_spineRenderer = makeUnique<spine::SpineRenderer>(*g_renderContext, *g_resourceManager, *g_spineSystem);+ g_spineRenderer->init();+g_initialized = true;glClearColor(0.0f, 0.0f, 0.0f, 1.0f);@@ -131,6 +153,12 @@ bool initRendererWithContext(int contextHandle) {void shutdownRenderer() {if (!g_initialized) return;+ g_spineRenderer->shutdown();+ g_spineRenderer.reset();+ g_spineSystem.reset();+ g_spineResourceManager->shutdown();+ g_spineResourceManager.reset();+g_transformSystem.reset();g_renderPipeline.reset();g_renderContext->shutdown();@@ -173,6 +201,10 @@ void rm_releaseTexture(resource::ResourceManager& rm, u32 handleId) {rm.releaseTexture(resource::TextureHandle(handleId));}+void rm_registerTextureWithPath(resource::ResourceManager& rm, u32 handleId, const std::string& path) {+ rm.registerTextureWithPath(resource::TextureHandle(handleId), path);+}+void rm_releaseShader(resource::ResourceManager& rm, u32 handleId) {rm.releaseShader(resource::ShaderHandle(handleId));}@@ -194,6 +226,10 @@ void renderFrame(ecs::Registry& registry, i32 viewportWidth, i32 viewportHeight)g_transformSystem->update(registry, 0.0f);}+ if (g_spineSystem) {+ g_spineSystem->update(registry, 0.016f);+ }+glViewport(0, 0, viewportWidth, viewportHeight);glClearColor(0.0f, 0.0f, 0.0f, 1.0f);glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);@@ -232,6 +268,12 @@ void renderFrame(ecs::Registry& registry, i32 viewportWidth, i32 viewportHeight)g_renderPipeline->begin(viewProjection);g_renderPipeline->submit(registry);g_renderPipeline->end();++ if (g_spineRenderer) {+ g_spineRenderer->begin(viewProjection);+ g_spineRenderer->submit(registry);+ g_spineRenderer->end();+ }}void renderFrameWithMatrix(ecs::Registry& registry, i32 viewportWidth, i32 viewportHeight,@@ -242,6 +284,10 @@ void renderFrameWithMatrix(ecs::Registry& registry, i32 viewportWidth, i32 viewpg_transformSystem->update(registry, 0.0f);}+ if (g_spineSystem) {+ g_spineSystem->update(registry, 0.016f);+ }+glViewport(0, 0, viewportWidth, viewportHeight);glClearColor(0.1f, 0.1f, 0.1f, 1.0f);glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);@@ -252,6 +298,31 @@ void renderFrameWithMatrix(ecs::Registry& registry, i32 viewportWidth, i32 viewpg_renderPipeline->begin(viewProjection);g_renderPipeline->submit(registry);g_renderPipeline->end();++ if (g_spineRenderer) {+ g_spineRenderer->begin(viewProjection);+ g_spineRenderer->submit(registry);+ g_spineRenderer->end();+ }+}++struct SpineBounds {+ f32 x = 0;+ f32 y = 0;+ f32 width = 0;+ f32 height = 0;+ bool valid = false;+};++SpineBounds getSpineBounds(ecs::Registry& registry, Entity entity) {+ SpineBounds bounds;+ if (!g_spineSystem) return bounds;++ if (g_spineSystem->getSkeletonBounds(entity, bounds.x, bounds.y,+ bounds.width, bounds.height)) {+ bounds.valid = true;+ }+ return bounds;}} // namespace esengine@@ -270,7 +341,17 @@ EMSCRIPTEN_BINDINGS(esengine_renderer) {.function("createShader", &esengine::rm_createShader).function("releaseTexture", &esengine::rm_releaseTexture).function("releaseShader", &esengine::rm_releaseShader)- .function("setTextureMetadata", &esengine::rm_setTextureMetadata);+ .function("setTextureMetadata", &esengine::rm_setTextureMetadata)+ .function("registerTextureWithPath", &esengine::rm_registerTextureWithPath);++ emscripten::value_object<esengine::SpineBounds>("SpineBounds")+ .field("x", &esengine::SpineBounds::x)+ .field("y", &esengine::SpineBounds::y)+ .field("width", &esengine::SpineBounds::width)+ .field("height", &esengine::SpineBounds::height)+ .field("valid", &esengine::SpineBounds::valid);++ emscripten::function("getSpineBounds", &esengine::getSpineBounds);}int main() {diff --git a/src/esengine/resource/ResourceManager.cpp b/src/esengine/resource/ResourceManager.cppindex 23c6dd4b7..3bf524f35 100644--- a/src/esengine/resource/ResourceManager.cpp+++ b/src/esengine/resource/ResourceManager.cpp@@ -172,13 +172,18 @@ TextureHandle ResourceManager::createTexture(u32 width, u32 height, ConstSpan<u8}TextureHandle ResourceManager::loadTexture(const std::string& path) {+ ES_LOG_INFO("ResourceManager::loadTexture looking for: {}", path);+auto cached = textures_.findByPath(path);if (cached.isValid()) {textures_.addRef(cached);stats_.cacheHits++;+ ES_LOG_INFO("ResourceManager::loadTexture found in cache: handle={}", cached.id());return cached;}+ ES_LOG_WARN("ResourceManager::loadTexture NOT found in cache: {}", path);+#ifdef ES_PLATFORM_WEBES_LOG_ERROR("loadTexture from file not supported on Web, use createTexture with pixel data");stats_.cacheMisses++;@@ -232,6 +237,13 @@ void ResourceManager::releaseTexture(TextureHandle handle) {}}+void ResourceManager::registerTextureWithPath(TextureHandle handle, const std::string& path) {+ if (handle.isValid() && !path.empty()) {+ ES_LOG_INFO("ResourceManager::registerTextureWithPath handle={} path={}", handle.id(), path);+ textures_.setPath(handle, path);+ }+}+const std::string& ResourceManager::getTexturePath(TextureHandle handle) const {return textures_.getPath(handle);}diff --git a/src/esengine/resource/ResourceManager.hpp b/src/esengine/resource/ResourceManager.hppindex 9a29e4fc4..1afe9796a 100644--- a/src/esengine/resource/ResourceManager.hpp+++ b/src/esengine/resource/ResourceManager.hpp@@ -213,6 +213,13 @@ public:*/void releaseTexture(TextureHandle handle);+ /**+ * @brief Registers a texture with a path for cache lookup+ * @param handle The texture handle+ * @param path The path to associate (used by loadTexture cache)+ */+ void registerTextureWithPath(TextureHandle handle, const std::string& path);+/*** @brief Gets the cached path for a texture* @param handle The texture handlediff --git a/src/esengine/resource/ResourcePool.hpp b/src/esengine/resource/ResourcePool.hppindex 44d39c021..46654fd7d 100644--- a/src/esengine/resource/ResourcePool.hpp+++ b/src/esengine/resource/ResourcePool.hpp@@ -158,6 +158,23 @@ public:return it != pathToId_.end() ? Handle<T>(it->second) : Handle<T>();}+ /**+ * @brief Associates a path with an existing resource+ * @param handle The resource handle+ * @param path The path to associate+ */+ void setPath(Handle<T> handle, const std::string& path) {+ if (!handle.isValid() || handle.id() >= entries_.size()) return;+ auto& entry = entries_[handle.id()];+ if (entry.refCount > 0 && !path.empty()) {+ if (!entry.path.empty()) {+ pathToId_.erase(entry.path);+ }+ entry.path = path;+ pathToId_[path] = handle.id();+ }+ }+/*** @brief Increments the reference count for a resource* @param handle The resource handlediff --git a/src/esengine/spine/SpineExtension.cpp b/src/esengine/spine/SpineExtension.cppnew file mode 100644index 000000000..339a173ad--- /dev/null+++ b/src/esengine/spine/SpineExtension.cpp@@ -0,0 +1,67 @@+/**+ * @file SpineExtension.cpp+ * @brief ESEngine implementation of Spine's extension interface+ */++// =============================================================================+// Includes+// =============================================================================++#include "SpineExtension.hpp"+#include "../platform/FileSystem.hpp"+#include "../core/Log.hpp"++#include <spine/SpineString.h>++#include <cstring>++namespace esengine::spine {++// =============================================================================+// ESEngineSpineExtension Implementation+// =============================================================================++char* ESEngineSpineExtension::_readFile(const ::spine::String& path, int* length) {+ std::string pathStr(path.buffer(), path.length());++ auto data = FileSystem::readBinaryFile(pathStr);+ if (data.empty()) {+ ES_LOG_ERROR("Failed to read Spine file: {}", pathStr);+ *length = 0;+ return nullptr;+ }++ *length = static_cast<int>(data.size());+ char* buffer = ::spine::SpineExtension::alloc<char>(data.size() + 1, __FILE__, __LINE__);+ std::memcpy(buffer, data.data(), data.size());+ buffer[data.size()] = '\0';++ return buffer;+}++// =============================================================================+// Extension Initialization+// =============================================================================++static ESEngineSpineExtension* s_extension = nullptr;++void initSpineExtension() {+ if (s_extension == nullptr) {+ s_extension = new ESEngineSpineExtension();+ ::spine::SpineExtension::setInstance(s_extension);+ }+}++} // namespace esengine::spine++// =============================================================================+// Spine Default Extension Provider+// =============================================================================++namespace spine {++SpineExtension* getDefaultExtension() {+ return new esengine::spine::ESEngineSpineExtension();+}++} // namespace spinediff --git a/src/esengine/spine/SpineExtension.hpp b/src/esengine/spine/SpineExtension.hppnew file mode 100644index 000000000..fe0c0fa31--- /dev/null+++ b/src/esengine/spine/SpineExtension.hpp@@ -0,0 +1,55 @@+/**+ * @file SpineExtension.hpp+ * @brief ESEngine implementation of Spine's extension interface+ * @details Bridges Spine's file/memory operations with ESEngine's FileSystem.+ *+ * @author ESEngine Team+ * @date 2026+ *+ * @copyright Copyright (c) 2026 ESEngine Team+ * Licensed under the MIT License.+ */+#pragma once++// =============================================================================+// Includes+// =============================================================================++#include <spine/Extension.h>++namespace esengine::spine {++// =============================================================================+// ESEngineSpineExtension Class+// =============================================================================++/**+ * @brief ESEngine implementation of Spine's extension interface+ *+ * @details Provides file reading through ESEngine's FileSystem and+ * uses standard memory allocation. This extension is automatically+ * set when SpineResourceManager is initialized.+ */+class ESEngineSpineExtension : public ::spine::DefaultSpineExtension {+public:+ ESEngineSpineExtension() = default;+ ~ESEngineSpineExtension() override = default;++protected:+ /**+ * @brief Reads a file using ESEngine's FileSystem+ * @param path File path to read+ * @param length Output parameter for file length+ * @return Allocated buffer containing file data (caller must free)+ */+ char* _readFile(const ::spine::String& path, int* length) override;+};++/**+ * @brief Initializes the ESEngine Spine extension+ * @details Must be called before loading any Spine assets.+ * Called automatically by SpineResourceManager::init().+ */+void initSpineExtension();++} // namespace esengine::spinediff --git a/src/esengine/spine/SpineRenderer.cpp b/src/esengine/spine/SpineRenderer.cppnew file mode 100644index 000000000..5e8e86c88--- /dev/null+++ b/src/esengine/spine/SpineRenderer.cpp@@ -0,0 +1,386 @@+/**+ * @file SpineRenderer.cpp+ * @brief Spine skeleton renderer implementation+ */++// =============================================================================+// Includes+// =============================================================================++#include "SpineRenderer.hpp"+#include "../core/Log.hpp"+#include "../ecs/components/SpineAnimation.hpp"+#include "../ecs/components/Transform.hpp"+#include "../renderer/Renderer.hpp"+#include "../renderer/RenderCommand.hpp"++#include <spine/RegionAttachment.h>+#include <spine/MeshAttachment.h>+#include <spine/ClippingAttachment.h>++#ifdef ES_PLATFORM_WEB+ #include <GLES3/gl3.h>+#else+ #ifdef _WIN32+ #include <windows.h>+ #endif+ #include <glad/glad.h>+#endif++namespace esengine::spine {++// =============================================================================+// SpineRenderer Implementation+// =============================================================================++SpineRenderer::SpineRenderer(RenderContext& context,+ resource::ResourceManager& resourceManager,+ SpineSystem& spineSystem)+ : context_(context)+ , resource_manager_(resourceManager)+ , spine_system_(spineSystem) {+}++SpineRenderer::~SpineRenderer() {+ if (initialized_) {+ shutdown();+ }+}++void SpineRenderer::init() {+ if (initialized_) return;++ vertices_.reserve(1024);+ indices_.reserve(2048);+ world_vertices_.reserve(1024);++ initialized_ = true;+ ES_LOG_INFO("SpineRenderer initialized");+}++void SpineRenderer::shutdown() {+ if (!initialized_) return;++ vertices_.clear();+ indices_.clear();+ world_vertices_.clear();++ initialized_ = false;+ ES_LOG_INFO("SpineRenderer shutdown");+}++void SpineRenderer::begin(const glm::mat4& viewProjection) {+ view_projection_ = viewProjection;+ triangle_count_ = 0;+ draw_call_count_ = 0;++ glEnable(GL_BLEND);+ glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);+ glDisable(GL_DEPTH_TEST);+}++void SpineRenderer::submit(ecs::Registry& registry) {+ auto view = registry.view<ecs::SpineAnimation>();++ for (auto entity : view) {+ auto& comp = registry.get<ecs::SpineAnimation>(entity);+ auto* instance = spine_system_.getInstance(entity);++ if (!instance || !instance->skeleton) continue;++ glm::vec3 position{0.0f};+ glm::quat rotation{1.0f, 0.0f, 0.0f, 0.0f};+ glm::vec3 scale{1.0f};++ if (registry.has<ecs::WorldTransform>(entity)) {+ const auto& world = registry.get<ecs::WorldTransform>(entity);+ position = world.position;+ rotation = world.rotation;+ scale = world.scale;+ } else if (registry.has<ecs::LocalTransform>(entity)) {+ const auto& local = registry.get<ecs::LocalTransform>(entity);+ position = local.position;+ rotation = local.rotation;+ scale = local.scale;+ }++ renderSkeleton(instance->skeleton.get(), position, rotation, scale,+ comp.color, comp.layer);+ }+}++void SpineRenderer::renderSkeleton(::spine::Skeleton* skeleton,+ const glm::vec3& position,+ const glm::quat& rotation,+ const glm::vec3& scale,+ const glm::vec4& tintColor,+ i32 layer) {+ if (!skeleton) return;++ glm::mat4 transform = glm::mat4(1.0f);+ transform = glm::translate(transform, position);+ transform *= glm::mat4_cast(rotation);+ transform = glm::scale(transform, scale);++ auto& drawOrder = skeleton->getDrawOrder();+ for (size_t i = 0; i < drawOrder.size(); ++i) {+ ::spine::Slot* slot = drawOrder[i];+ if (!slot) continue;++ ::spine::Attachment* attachment = slot->getAttachment();+ if (!attachment) continue;++ if (!slot->getData().isVisible()) continue;++ if (attachment->getRTTI().isExactly(::spine::ClippingAttachment::rtti)) {+ auto* clip = static_cast<::spine::ClippingAttachment*>(attachment);+ clipper_.clipStart(*slot, clip);+ continue;+ }++ if (attachment->getRTTI().isExactly(::spine::RegionAttachment::rtti)) {+ auto* region = static_cast<::spine::RegionAttachment*>(attachment);+ renderRegionAttachment(region, *slot, transform, tintColor);+ } else if (attachment->getRTTI().isExactly(::spine::MeshAttachment::rtti)) {+ auto* mesh = static_cast<::spine::MeshAttachment*>(attachment);+ renderMeshAttachment(mesh, *slot, transform, tintColor);+ }++ clipper_.clipEnd(*slot);+ }++ clipper_.clipEnd();+ flushBatch();+}++void SpineRenderer::renderRegionAttachment(::spine::RegionAttachment* attachment,+ ::spine::Slot& slot,+ const glm::mat4& transform,+ const glm::vec4& tintColor) {+ auto* region = attachment->getRegion();+ if (!region) return;++ world_vertices_.resize(8);+ attachment->computeWorldVertices(slot, world_vertices_.data(), 0, 2);++ auto& uvs = attachment->getUVs();+ auto& attachColor = attachment->getColor();+ auto& slotColor = slot.getColor();+ auto& skelColor = slot.getSkeleton().getColor();++ f32 r = skelColor.r * slotColor.r * attachColor.r * tintColor.r;+ f32 g = skelColor.g * slotColor.g * attachColor.g * tintColor.g;+ f32 b = skelColor.b * slotColor.b * attachColor.b * tintColor.b;+ f32 a = skelColor.a * slotColor.a * attachColor.a * tintColor.a;++ u32 textureId = getTextureId(region->rendererObject);+ auto blendMode = slot.getData().getBlendMode();++ if (textureId != current_texture_id_ || blendMode != current_blend_mode_) {+ flushBatch();+ current_texture_id_ = textureId;+ current_blend_mode_ = blendMode;+ setBlendMode(blendMode);+ }++ u32 baseIndex = static_cast<u32>(vertices_.size());++ for (int j = 0; j < 4; ++j) {+ glm::vec4 pos(world_vertices_[j * 2], world_vertices_[j * 2 + 1], 0.0f, 1.0f);+ pos = transform * pos;++ SpineRenderVertex vertex;+ vertex.position = glm::vec2(pos.x, pos.y);+ vertex.uv = glm::vec2(uvs[j * 2], uvs[j * 2 + 1]);+ vertex.color = glm::vec4(r, g, b, a);+ vertices_.push_back(vertex);+ }++ indices_.push_back(baseIndex);+ indices_.push_back(baseIndex + 1);+ indices_.push_back(baseIndex + 2);+ indices_.push_back(baseIndex + 2);+ indices_.push_back(baseIndex + 3);+ indices_.push_back(baseIndex);+}++void SpineRenderer::renderMeshAttachment(::spine::MeshAttachment* attachment,+ ::spine::Slot& slot,+ const glm::mat4& transform,+ const glm::vec4& tintColor) {+ auto* region = attachment->getRegion();+ if (!region) return;++ size_t vertexCount = attachment->getWorldVerticesLength() / 2;+ world_vertices_.resize(attachment->getWorldVerticesLength());+ attachment->computeWorldVertices(slot, 0, attachment->getWorldVerticesLength(),+ world_vertices_.data(), 0, 2);++ auto& uvs = attachment->getUVs();+ auto& triangles = attachment->getTriangles();+ auto& attachColor = attachment->getColor();+ auto& slotColor = slot.getColor();+ auto& skelColor = slot.getSkeleton().getColor();++ f32 r = skelColor.r * slotColor.r * attachColor.r * tintColor.r;+ f32 g = skelColor.g * slotColor.g * attachColor.g * tintColor.g;+ f32 b = skelColor.b * slotColor.b * attachColor.b * tintColor.b;+ f32 a = skelColor.a * slotColor.a * attachColor.a * tintColor.a;++ u32 textureId = getTextureId(region->rendererObject);+ auto blendMode = slot.getData().getBlendMode();++ if (textureId != current_texture_id_ || blendMode != current_blend_mode_) {+ flushBatch();+ current_texture_id_ = textureId;+ current_blend_mode_ = blendMode;+ setBlendMode(blendMode);+ }++ u32 baseIndex = static_cast<u32>(vertices_.size());++ if (clipper_.isClipping()) {+ clipper_.clipTriangles(world_vertices_.data(),+ const_cast<unsigned short*>(triangles.buffer()),+ triangles.size(),+ uvs.buffer(), 2);++ auto& clippedVerts = clipper_.getClippedVertices();+ auto& clippedUVs = clipper_.getClippedUVs();+ auto& clippedTris = clipper_.getClippedTriangles();++ size_t clippedVertCount = clippedVerts.size() / 2;+ for (size_t j = 0; j < clippedVertCount; ++j) {+ glm::vec4 pos(clippedVerts[j * 2], clippedVerts[j * 2 + 1], 0.0f, 1.0f);+ pos = transform * pos;++ SpineRenderVertex vertex;+ vertex.position = glm::vec2(pos.x, pos.y);+ vertex.uv = glm::vec2(clippedUVs[j * 2], clippedUVs[j * 2 + 1]);+ vertex.color = glm::vec4(r, g, b, a);+ vertices_.push_back(vertex);+ }++ for (size_t j = 0; j < clippedTris.size(); ++j) {+ indices_.push_back(baseIndex + clippedTris[j]);+ }+ } else {+ for (size_t j = 0; j < vertexCount; ++j) {+ glm::vec4 pos(world_vertices_[j * 2], world_vertices_[j * 2 + 1], 0.0f, 1.0f);+ pos = transform * pos;++ SpineRenderVertex vertex;+ vertex.position = glm::vec2(pos.x, pos.y);+ vertex.uv = glm::vec2(uvs[j * 2], uvs[j * 2 + 1]);+ vertex.color = glm::vec4(r, g, b, a);+ vertices_.push_back(vertex);+ }++ for (size_t j = 0; j < triangles.size(); ++j) {+ indices_.push_back(baseIndex + triangles[j]);+ }+ }+}++u32 SpineRenderer::getTextureId(void* spineTexture) {+ if (!spineTexture) {+ return context_.getWhiteTextureId();+ }++ u32 handleId = static_cast<u32>(reinterpret_cast<uintptr_t>(spineTexture)) - 1;+ resource::TextureHandle handle(handleId);++ auto* texture = resource_manager_.getTexture(handle);+ if (texture) {+ return texture->getId();+ }++ return context_.getWhiteTextureId();+}++void SpineRenderer::setBlendMode(::spine::BlendMode mode) {+ switch (mode) {+ case ::spine::BlendMode_Normal:+ glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);+ break;+ case ::spine::BlendMode_Additive:+ glBlendFunc(GL_SRC_ALPHA, GL_ONE);+ break;+ case ::spine::BlendMode_Multiply:+ glBlendFunc(GL_DST_COLOR, GL_ONE_MINUS_SRC_ALPHA);+ break;+ case ::spine::BlendMode_Screen:+ glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_COLOR);+ break;+ }+}++void SpineRenderer::flushBatch() {+ if (vertices_.empty() || indices_.empty()) {+ return;+ }++ auto* shader = context_.getTextureShader();+ if (!shader) {+ vertices_.clear();+ indices_.clear();+ return;+ }++ shader->bind();+ shader->setUniform("u_projection", view_projection_);+ shader->setUniform("u_model", glm::mat4(1.0f));+ shader->setUniform("u_color", glm::vec4(1.0f));++ glActiveTexture(GL_TEXTURE0);+ glBindTexture(GL_TEXTURE_2D, current_texture_id_);+ shader->setUniform("u_texture", 0);++ u32 vao, vbo, ebo;+ glGenVertexArrays(1, &vao);+ glGenBuffers(1, &vbo);+ glGenBuffers(1, &ebo);++ glBindVertexArray(vao);++ glBindBuffer(GL_ARRAY_BUFFER, vbo);+ glBufferData(GL_ARRAY_BUFFER,+ static_cast<GLsizeiptr>(vertices_.size() * sizeof(SpineRenderVertex)),+ vertices_.data(), GL_STREAM_DRAW);++ glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo);+ glBufferData(GL_ELEMENT_ARRAY_BUFFER,+ static_cast<GLsizeiptr>(indices_.size() * sizeof(u32)),+ indices_.data(), GL_STREAM_DRAW);++ glEnableVertexAttribArray(0);+ glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, sizeof(SpineRenderVertex),+ reinterpret_cast<void*>(offsetof(SpineRenderVertex, position)));++ glEnableVertexAttribArray(1);+ glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(SpineRenderVertex),+ reinterpret_cast<void*>(offsetof(SpineRenderVertex, uv)));++ glEnableVertexAttribArray(2);+ glVertexAttribPointer(2, 4, GL_FLOAT, GL_FALSE, sizeof(SpineRenderVertex),+ reinterpret_cast<void*>(offsetof(SpineRenderVertex, color)));++ glDrawElements(GL_TRIANGLES, static_cast<GLsizei>(indices_.size()),+ GL_UNSIGNED_INT, nullptr);++ triangle_count_ += static_cast<u32>(indices_.size() / 3);+ draw_call_count_++;++ glDeleteBuffers(1, &ebo);+ glDeleteBuffers(1, &vbo);+ glDeleteVertexArrays(1, &vao);++ vertices_.clear();+ indices_.clear();+}++void SpineRenderer::end() {+ flushBatch();+}++} // namespace esengine::spinediff --git a/src/esengine/spine/SpineRenderer.hpp b/src/esengine/spine/SpineRenderer.hppnew file mode 100644index 000000000..b8823341a--- /dev/null+++ b/src/esengine/spine/SpineRenderer.hpp@@ -0,0 +1,159 @@+/**+ * @file SpineRenderer.hpp+ * @brief Spine skeleton renderer+ * @details Renders Spine skeletons using the batch renderer.+ *+ * @author ESEngine Team+ * @date 2026+ *+ * @copyright Copyright (c) 2026 ESEngine Team+ * Licensed under the MIT License.+ */+#pragma once++// =============================================================================+// Includes+// =============================================================================++#include "../core/Types.hpp"+#include "../math/Math.hpp"+#include "../ecs/Registry.hpp"+#include "../renderer/RenderContext.hpp"+#include "../resource/ResourceManager.hpp"+#include "SpineSystem.hpp"++#include <spine/spine.h>++#include <vector>++namespace esengine::spine {++// =============================================================================+// SpineRenderVertex+// =============================================================================++/**+ * @brief Vertex data for Spine rendering+ */+struct SpineRenderVertex {+ glm::vec2 position;+ glm::vec2 uv;+ glm::vec4 color;+};++// =============================================================================+// SpineRenderer+// =============================================================================++/**+ * @brief Renders Spine skeletons+ *+ * @details Extracts mesh data from Spine skeletons and submits triangles+ * to the BatchRenderer2D for efficient rendering.+ *+ * @code+ * SpineRenderer spineRenderer(context, resourceManager, spineSystem);+ * spineRenderer.init();+ *+ * // In render loop+ * spineRenderer.begin(viewProjection);+ * spineRenderer.submit(registry);+ * spineRenderer.end();+ *+ * spineRenderer.shutdown();+ * @endcode+ */+class SpineRenderer {+public:+ SpineRenderer(RenderContext& context,+ resource::ResourceManager& resourceManager,+ SpineSystem& spineSystem);+ ~SpineRenderer();++ SpineRenderer(const SpineRenderer&) = delete;+ SpineRenderer& operator=(const SpineRenderer&) = delete;++ // =========================================================================+ // Lifecycle+ // =========================================================================++ void init();+ void shutdown();++ // =========================================================================+ // Rendering+ // =========================================================================++ /**+ * @brief Begins a render frame+ * @param viewProjection Combined view-projection matrix+ */+ void begin(const glm::mat4& viewProjection);++ /**+ * @brief Submits all Spine entities for rendering+ * @param registry ECS registry containing SpineAnimation components+ */+ void submit(ecs::Registry& registry);++ /**+ * @brief Renders a single skeleton at a transform+ * @param skeleton The skeleton to render+ * @param position World position+ * @param rotation World rotation+ * @param scale World scale+ * @param tintColor Color multiplier+ * @param layer Render layer+ */+ void renderSkeleton(::spine::Skeleton* skeleton,+ const glm::vec3& position,+ const glm::quat& rotation,+ const glm::vec3& scale,+ const glm::vec4& tintColor,+ i32 layer);++ /**+ * @brief Ends the render frame and flushes batches+ */+ void end();++ // =========================================================================+ // Statistics+ // =========================================================================++ u32 getTriangleCount() const { return triangle_count_; }+ u32 getDrawCallCount() const { return draw_call_count_; }++private:+ void renderRegionAttachment(::spine::RegionAttachment* attachment,+ ::spine::Slot& slot,+ const glm::mat4& transform,+ const glm::vec4& tintColor);++ void renderMeshAttachment(::spine::MeshAttachment* attachment,+ ::spine::Slot& slot,+ const glm::mat4& transform,+ const glm::vec4& tintColor);++ u32 getTextureId(void* spineTexture);+ void setBlendMode(::spine::BlendMode mode);+ void flushBatch();++ RenderContext& context_;+ resource::ResourceManager& resource_manager_;+ SpineSystem& spine_system_;++ glm::mat4 view_projection_;+ std::vector<SpineRenderVertex> vertices_;+ std::vector<u32> indices_;+ ::spine::SkeletonClipping clipper_;+ std::vector<f32> world_vertices_;++ u32 current_texture_id_ = 0;+ ::spine::BlendMode current_blend_mode_ = ::spine::BlendMode_Normal;+ u32 triangle_count_ = 0;+ u32 draw_call_count_ = 0;+ bool initialized_ = false;+};++} // namespace esengine::spinediff --git a/src/esengine/spine/SpineResourceManager.cpp b/src/esengine/spine/SpineResourceManager.cppnew file mode 100644index 000000000..a0ab65abe--- /dev/null+++ b/src/esengine/spine/SpineResourceManager.cpp@@ -0,0 +1,207 @@+/**+ * @file SpineResourceManager.cpp+ * @brief Spine skeleton data resource management+ */++// =============================================================================+// Includes+// =============================================================================++#include "SpineResourceManager.hpp"+#include "SpineExtension.hpp"+#include "../core/Log.hpp"+#include "../platform/FileSystem.hpp"+#include "../renderer/Texture.hpp"++#include <spine/SkeletonBinary.h>+#include <spine/SkeletonJson.h>+#include <spine/AtlasAttachmentLoader.h>++namespace esengine::spine {++// =============================================================================+// ESEngineTextureLoader Implementation+// =============================================================================++ESEngineTextureLoader::ESEngineTextureLoader(resource::ResourceManager& resourceManager)+ : resource_manager_(resourceManager) {+}++void ESEngineTextureLoader::load(::spine::AtlasPage& page, const ::spine::String& path) {+ std::string pathStr(path.buffer(), path.length());++ ES_LOG_INFO("SpineTextureLoader: trying to load texture: {}", pathStr);++ auto handle = resource_manager_.loadTexture(pathStr);+ if (!handle.isValid()) {+ ES_LOG_ERROR("Failed to load Spine texture: {}", pathStr);+ return;+ }++ ES_LOG_INFO("SpineTextureLoader: loaded texture handle: {}", handle.id());++ auto* texture = resource_manager_.getTexture(handle);+ if (texture) {+ page.width = static_cast<int>(texture->getWidth());+ page.height = static_cast<int>(texture->getHeight());+ void* key = reinterpret_cast<void*>(static_cast<uintptr_t>(handle.id() + 1));+ page.texture = key;+ texture_handles_[key] = handle;+ }+}++void ESEngineTextureLoader::unload(void* texture) {+ auto it = texture_handles_.find(texture);+ if (it != texture_handles_.end()) {+ resource_manager_.releaseTexture(it->second);+ texture_handles_.erase(it);+ }+}++// =============================================================================+// SpineResourceManager Implementation+// =============================================================================++SpineResourceManager::SpineResourceManager(resource::ResourceManager& resourceManager)+ : resource_manager_(resourceManager) {+}++SpineResourceManager::~SpineResourceManager() {+ if (initialized_) {+ shutdown();+ }+}++void SpineResourceManager::init() {+ if (initialized_) return;++ initSpineExtension();+ texture_loader_ = makeUnique<ESEngineTextureLoader>(resource_manager_);+ initialized_ = true;++ ES_LOG_INFO("SpineResourceManager initialized");+}++void SpineResourceManager::shutdown() {+ if (!initialized_) return;++ cache_.clear();+ pool_.clear();+ texture_loader_.reset();+ initialized_ = false;++ ES_LOG_INFO("SpineResourceManager shutdown");+}++resource::SpineDataHandle SpineResourceManager::load(const std::string& skeletonPath,+ const std::string& atlasPath,+ f32 scale) {+ if (!initialized_) {+ ES_LOG_ERROR("SpineResourceManager not initialized");+ return resource::SpineDataHandle();+ }++ auto cacheIt = cache_.find(skeletonPath);+ if (cacheIt != cache_.end()) {+ return cacheIt->second;+ }++ auto atlas = makeUnique<::spine::Atlas>(atlasPath.c_str(), texture_loader_.get());+ if (atlas->getPages().size() == 0) {+ ES_LOG_ERROR("Failed to load Spine atlas: {}", atlasPath);+ return resource::SpineDataHandle();+ }++ bool isBinary = skeletonPath.ends_with(".skel");+ resource::SpineDataHandle handle;++ if (isBinary) {+ handle = loadBinary(skeletonPath, atlas.get(), scale);+ } else {+ handle = loadJson(skeletonPath, atlas.get(), scale);+ }++ if (handle.isValid()) {+ auto* data = pool_.get(handle);+ if (data) {+ data->atlas = std::move(atlas);+ }+ cache_[skeletonPath] = handle;+ ES_LOG_INFO("Loaded Spine skeleton: {}", skeletonPath);+ }++ return handle;+}++resource::SpineDataHandle SpineResourceManager::loadBinary(const std::string& skeletonPath,+ ::spine::Atlas* atlas, f32 scale) {+ ::spine::AtlasAttachmentLoader attachmentLoader(atlas);+ ::spine::SkeletonBinary binary(&attachmentLoader);+ binary.setScale(scale);++ auto* skeletonData = binary.readSkeletonDataFile(skeletonPath.c_str());+ if (!skeletonData) {+ ES_LOG_ERROR("Failed to load Spine skeleton binary: {} - {}",+ skeletonPath, binary.getError().buffer());+ return resource::SpineDataHandle();+ }++ auto data = makeUnique<SpineSkeletonData>();+ data->skeletonData.reset(skeletonData);+ data->stateData = makeUnique<::spine::AnimationStateData>(skeletonData);+ data->stateData->setDefaultMix(0.2f);++ return pool_.add(std::move(data));+}++resource::SpineDataHandle SpineResourceManager::loadJson(const std::string& skeletonPath,+ ::spine::Atlas* atlas, f32 scale) {+ ::spine::AtlasAttachmentLoader attachmentLoader(atlas);+ ::spine::SkeletonJson json(&attachmentLoader);+ json.setScale(scale);++ auto* skeletonData = json.readSkeletonDataFile(skeletonPath.c_str());+ if (!skeletonData) {+ ES_LOG_ERROR("Failed to load Spine skeleton JSON: {} - {}",+ skeletonPath, json.getError().buffer());+ return resource::SpineDataHandle();+ }++ auto data = makeUnique<SpineSkeletonData>();+ data->skeletonData.reset(skeletonData);+ data->stateData = makeUnique<::spine::AnimationStateData>(skeletonData);+ data->stateData->setDefaultMix(0.2f);++ return pool_.add(std::move(data));+}++SpineSkeletonData* SpineResourceManager::get(resource::SpineDataHandle handle) {+ return pool_.get(handle);+}++const SpineSkeletonData* SpineResourceManager::get(resource::SpineDataHandle handle) const {+ return pool_.get(handle);+}++void SpineResourceManager::release(resource::SpineDataHandle handle) {+ if (!handle.isValid()) return;++ for (auto it = cache_.begin(); it != cache_.end(); ++it) {+ if (it->second == handle) {+ cache_.erase(it);+ break;+ }+ }+ pool_.release(handle.id());+}++resource::SpineDataHandle SpineResourceManager::getByPath(const std::string& skeletonPath) const {+ auto it = cache_.find(skeletonPath);+ return it != cache_.end() ? it->second : resource::SpineDataHandle();+}++usize SpineResourceManager::getLoadedCount() const {+ return pool_.size();+}++} // namespace esengine::spinediff --git a/src/esengine/spine/SpineResourceManager.hpp b/src/esengine/spine/SpineResourceManager.hppnew file mode 100644index 000000000..02e32b891--- /dev/null+++ b/src/esengine/spine/SpineResourceManager.hpp@@ -0,0 +1,185 @@+/**+ * @file SpineResourceManager.hpp+ * @brief Spine skeleton data resource management+ * @details Provides caching and lifecycle management for Spine resources.+ *+ * @author ESEngine Team+ * @date 2026+ *+ * @copyright Copyright (c) 2026 ESEngine Team+ * Licensed under the MIT License.+ */+#pragma once++// =============================================================================+// Includes+// =============================================================================++#include "../core/Types.hpp"+#include "../resource/Handle.hpp"+#include "../resource/ResourcePool.hpp"+#include "../resource/ResourceManager.hpp"++#include <spine/spine.h>++#include <string>+#include <unordered_map>++namespace esengine::spine {++// =============================================================================+// Forward Declarations+// =============================================================================++struct SpineSkeletonData;++// =============================================================================+// ESEngineTextureLoader+// =============================================================================++/**+ * @brief Texture loader for Spine atlases+ *+ * @details Loads textures through ESEngine's ResourceManager and associates+ * them with Spine atlas pages.+ */+class ESEngineTextureLoader : public ::spine::TextureLoader {+public:+ explicit ESEngineTextureLoader(resource::ResourceManager& resourceManager);+ ~ESEngineTextureLoader() override = default;++ void load(::spine::AtlasPage& page, const ::spine::String& path) override;+ void unload(void* texture) override;++private:+ resource::ResourceManager& resource_manager_;+ std::unordered_map<void*, resource::TextureHandle> texture_handles_;+};++// =============================================================================+// SpineSkeletonData+// =============================================================================++/**+ * @brief Container for loaded Spine skeleton resources+ *+ * @details Holds all data needed to create Skeleton and AnimationState+ * instances. Resources are reference-counted by SpineResourceManager.+ */+struct SpineSkeletonData {+ Unique<::spine::Atlas> atlas;+ Unique<::spine::SkeletonData> skeletonData;+ Unique<::spine::AnimationStateData> stateData;++ SpineSkeletonData() = default;+ ~SpineSkeletonData() = default;++ SpineSkeletonData(const SpineSkeletonData&) = delete;+ SpineSkeletonData& operator=(const SpineSkeletonData&) = delete;+ SpineSkeletonData(SpineSkeletonData&&) = default;+ SpineSkeletonData& operator=(SpineSkeletonData&&) = default;+};++// =============================================================================+// SpineResourceManager+// =============================================================================++/**+ * @brief Manages Spine skeleton resources with caching+ *+ * @details Provides loading, caching, and lifecycle management for Spine+ * skeleton data. Resources are cached by path for deduplication.+ *+ * @code+ * SpineResourceManager spineMgr(resourceManager);+ * spineMgr.init();+ *+ * auto handle = spineMgr.load("skeleton.skel", "skeleton.atlas");+ * auto* data = spineMgr.get(handle);+ *+ * // Create skeleton instance+ * auto skeleton = makeUnique<spine::Skeleton>(data->skeletonData.get());+ * auto state = makeUnique<spine::AnimationState>(data->stateData.get());+ *+ * spineMgr.release(handle);+ * spineMgr.shutdown();+ * @endcode+ */+class SpineResourceManager {+public:+ explicit SpineResourceManager(resource::ResourceManager& resourceManager);+ ~SpineResourceManager();++ SpineResourceManager(const SpineResourceManager&) = delete;+ SpineResourceManager& operator=(const SpineResourceManager&) = delete;++ // =========================================================================+ // Lifecycle+ // =========================================================================++ void init();+ void shutdown();+ bool isInitialized() const { return initialized_; }++ // =========================================================================+ // Resource Loading+ // =========================================================================++ /**+ * @brief Loads Spine skeleton data from files+ * @param skeletonPath Path to .skel (binary) or .json skeleton file+ * @param atlasPath Path to .atlas file+ * @param scale Optional skeleton scale (default 1.0)+ * @return Handle to the loaded data, or invalid handle on failure+ */+ resource::SpineDataHandle load(const std::string& skeletonPath,+ const std::string& atlasPath,+ f32 scale = 1.0f);++ /**+ * @brief Gets skeleton data by handle+ * @param handle The data handle+ * @return Pointer to the data, or nullptr if invalid+ */+ SpineSkeletonData* get(resource::SpineDataHandle handle);++ /**+ * @brief Gets skeleton data by handle (const)+ * @param handle The data handle+ * @return Const pointer to the data, or nullptr if invalid+ */+ const SpineSkeletonData* get(resource::SpineDataHandle handle) const;++ /**+ * @brief Releases skeleton data+ * @param handle The data handle+ */+ void release(resource::SpineDataHandle handle);++ /**+ * @brief Gets handle by skeleton path (if cached)+ * @param skeletonPath Path used to load the skeleton+ * @return Handle if cached, invalid handle otherwise+ */+ resource::SpineDataHandle getByPath(const std::string& skeletonPath) const;++ // =========================================================================+ // Statistics+ // =========================================================================++ usize getLoadedCount() const;++private:+ resource::ResourceManager& resource_manager_;+ Unique<ESEngineTextureLoader> texture_loader_;+ resource::ResourcePool<SpineSkeletonData> pool_;+ std::unordered_map<std::string, resource::SpineDataHandle> cache_;+ bool initialized_ = false;++ resource::SpineDataHandle loadBinary(const std::string& skeletonPath,+ ::spine::Atlas* atlas, f32 scale);+ resource::SpineDataHandle loadJson(const std::string& skeletonPath,+ ::spine::Atlas* atlas, f32 scale);+};++} // namespace esengine::spinediff --git a/src/esengine/spine/SpineSystem.cpp b/src/esengine/spine/SpineSystem.cppnew file mode 100644index 000000000..9de54308b--- /dev/null+++ b/src/esengine/spine/SpineSystem.cpp@@ -0,0 +1,217 @@+/**+ * @file SpineSystem.cpp+ * @brief Spine animation update system+ */++// =============================================================================+// Includes+// =============================================================================++#include "SpineSystem.hpp"+#include "../core/Log.hpp"+#include "../ecs/components/SpineAnimation.hpp"+#include "../ecs/components/Transform.hpp"++namespace esengine::spine {++// =============================================================================+// SpineSystem Implementation+// =============================================================================++SpineSystem::SpineSystem(SpineResourceManager& resourceManager)+ : resource_manager_(resourceManager) {+}++SpineSystem::~SpineSystem() {+ instances_.clear();+}++void SpineSystem::update(ecs::Registry& registry, f32 deltaTime) {+ auto view = registry.view<ecs::SpineAnimation>();++ for (auto entity : view) {+ auto& comp = registry.get<ecs::SpineAnimation>(entity);++ if (comp.needsReload && !comp.skeletonPath.empty() && !comp.atlasPath.empty()) {+ loadSkeletonForEntity(entity, comp);+ }++ auto it = instances_.find(entity);+ if (it != instances_.end()) {+ syncComponentToInstance(entity, comp);+ updateAnimation(entity, comp, deltaTime);+ }+ }++ std::vector<Entity> toRemove;+ for (auto& [entity, instance] : instances_) {+ if (!registry.valid(entity) || !registry.has<ecs::SpineAnimation>(entity)) {+ toRemove.push_back(entity);+ }+ }+ for (Entity e : toRemove) {+ instances_.erase(e);+ }+}++void SpineSystem::loadSkeletonForEntity(Entity entity, ecs::SpineAnimation& comp) {+ auto handle = resource_manager_.load(comp.skeletonPath, comp.atlasPath, comp.skeletonScale);+ if (!handle.isValid()) {+ ES_LOG_ERROR("Failed to load spine skeleton for entity {}", entity);+ comp.needsReload = false;+ return;+ }++ auto* data = resource_manager_.get(handle);+ if (!data || !data->skeletonData || !data->stateData) {+ ES_LOG_ERROR("Invalid spine data for entity {}", entity);+ comp.needsReload = false;+ return;+ }++ auto instance = SpineInstance{};+ instance.skeleton = makeUnique<::spine::Skeleton>(data->skeletonData.get());+ instance.state = makeUnique<::spine::AnimationState>(data->stateData.get());++ if (!comp.skin.empty()) {+ instance.skeleton->setSkin(comp.skin.c_str());+ instance.skeleton->setSlotsToSetupPose();+ }++ if (!comp.animation.empty()) {+ instance.state->setAnimation(0, comp.animation.c_str(), comp.loop);+ }++ instance.skeleton->setScaleX(comp.flipX ? -1.0f : 1.0f);+ instance.skeleton->setScaleY(comp.flipY ? -1.0f : 1.0f);++ comp.skeletonData = handle;+ comp.needsReload = false;++ instances_[entity] = std::move(instance);+}++void SpineSystem::updateAnimation(Entity entity, ecs::SpineAnimation& comp, f32 deltaTime) {+ auto it = instances_.find(entity);+ if (it == instances_.end()) return;++ auto& instance = it->second;+ auto* skeleton = instance.skeleton.get();+ auto* state = instance.state.get();++ if (!skeleton || !state) return;++ if (comp.playing) {+ state->update(deltaTime * comp.timeScale);+ }++ state->apply(*skeleton);+ skeleton->update(deltaTime);+ skeleton->updateWorldTransform(::spine::Physics_Update);+}++void SpineSystem::syncComponentToInstance(Entity entity, ecs::SpineAnimation& comp) {+ auto it = instances_.find(entity);+ if (it == instances_.end()) return;++ auto& instance = it->second;+ auto* skeleton = instance.skeleton.get();++ if (!skeleton) return;++ skeleton->setScaleX(comp.flipX ? -1.0f : 1.0f);+ skeleton->setScaleY(comp.flipY ? -1.0f : 1.0f);++ auto& color = skeleton->getColor();+ color.r = comp.color.r;+ color.g = comp.color.g;+ color.b = comp.color.b;+ color.a = comp.color.a;+}++void SpineSystem::reloadAssets(ecs::Registry& registry) {+ instances_.clear();+ auto view = registry.view<ecs::SpineAnimation>();+ for (auto entity : view) {+ auto& comp = registry.get<ecs::SpineAnimation>(entity);+ comp.needsReload = true;+ }+}++SpineInstance* SpineSystem::getInstance(Entity entity) {+ auto it = instances_.find(entity);+ return it != instances_.end() ? &it->second : nullptr;+}++const SpineInstance* SpineSystem::getInstance(Entity entity) const {+ auto it = instances_.find(entity);+ return it != instances_.end() ? &it->second : nullptr;+}++bool SpineSystem::playAnimation(Entity entity, const std::string& animation,+ bool loop, i32 track) {+ auto it = instances_.find(entity);+ if (it == instances_.end() || !it->second.state) return false;++ auto* entry = it->second.state->setAnimation(+ static_cast<size_t>(track), animation.c_str(), loop);+ return entry != nullptr;+}++bool SpineSystem::addAnimation(Entity entity, const std::string& animation,+ bool loop, f32 delay, i32 track) {+ auto it = instances_.find(entity);+ if (it == instances_.end() || !it->second.state) return false;++ auto* entry = it->second.state->addAnimation(+ static_cast<size_t>(track), animation.c_str(), loop, delay);+ return entry != nullptr;+}++bool SpineSystem::setSkin(Entity entity, const std::string& skinName) {+ auto it = instances_.find(entity);+ if (it == instances_.end() || !it->second.skeleton) return false;++ it->second.skeleton->setSkin(skinName.c_str());+ it->second.skeleton->setSlotsToSetupPose();+ return true;+}++bool SpineSystem::getBonePosition(Entity entity, const std::string& boneName,+ f32& outX, f32& outY) const {+ auto it = instances_.find(entity);+ if (it == instances_.end() || !it->second.skeleton) return false;++ auto* bone = it->second.skeleton->findBone(boneName.c_str());+ if (!bone) return false;++ outX = bone->getWorldX();+ outY = bone->getWorldY();+ return true;+}++bool SpineSystem::getBoneRotation(Entity entity, const std::string& boneName,+ f32& outRotation) const {+ auto it = instances_.find(entity);+ if (it == instances_.end() || !it->second.skeleton) return false;++ auto* bone = it->second.skeleton->findBone(boneName.c_str());+ if (!bone) return false;++ outRotation = bone->getWorldRotationX();+ return true;+}++bool SpineSystem::getSkeletonBounds(Entity entity, f32& outX, f32& outY,+ f32& outWidth, f32& outHeight) const {+ auto it = instances_.find(entity);+ if (it == instances_.end() || !it->second.skeleton) {+ return false;+ }++ ::spine::Vector<f32> vertices;+ it->second.skeleton->getBounds(outX, outY, outWidth, outHeight, vertices);+ return true;+}++} // namespace esengine::spinediff --git a/src/esengine/spine/SpineSystem.hpp b/src/esengine/spine/SpineSystem.hppnew file mode 100644index 000000000..1c32b0c0f--- /dev/null+++ b/src/esengine/spine/SpineSystem.hpp@@ -0,0 +1,178 @@+/**+ * @file SpineSystem.hpp+ * @brief Spine animation update system+ * @details Updates Spine skeletons and animation states for all entities.+ *+ * @author ESEngine Team+ * @date 2026+ *+ * @copyright Copyright (c) 2026 ESEngine Team+ * Licensed under the MIT License.+ */+#pragma once++// =============================================================================+// Includes+// =============================================================================++#include "../core/Types.hpp"+#include "../ecs/Registry.hpp"+#include "../ecs/components/SpineAnimation.hpp"+#include "SpineResourceManager.hpp"++#include <spine/spine.h>++#include <unordered_map>++namespace esengine::spine {++// =============================================================================+// SpineInstance+// =============================================================================++/**+ * @brief Per-entity Spine runtime instance+ *+ * @details Contains the Skeleton and AnimationState objects for a single+ * entity. These are created from the shared SpineSkeletonData.+ */+struct SpineInstance {+ Unique<::spine::Skeleton> skeleton;+ Unique<::spine::AnimationState> state;++ SpineInstance() = default;+ ~SpineInstance() = default;++ SpineInstance(const SpineInstance&) = delete;+ SpineInstance& operator=(const SpineInstance&) = delete;+ SpineInstance(SpineInstance&&) = default;+ SpineInstance& operator=(SpineInstance&&) = default;+};++// =============================================================================+// SpineSystem+// =============================================================================++/**+ * @brief System for updating Spine animations+ *+ * @details Manages the lifecycle of Spine instances per entity and updates+ * animation states each frame. Creates/destroys instances as needed+ * when SpineAnimation components are added/removed.+ *+ * @code+ * SpineSystem spineSystem(spineResourceManager);+ *+ * // In update loop+ * spineSystem.update(registry, deltaTime);+ * @endcode+ */+class SpineSystem {+public:+ explicit SpineSystem(SpineResourceManager& resourceManager);+ ~SpineSystem();++ SpineSystem(const SpineSystem&) = delete;+ SpineSystem& operator=(const SpineSystem&) = delete;++ /**+ * @brief Updates all Spine animations+ * @param registry ECS registry containing SpineAnimation components+ * @param deltaTime Time elapsed since last update (seconds)+ */+ void update(ecs::Registry& registry, f32 deltaTime);++ /**+ * @brief Forces reload of all skeleton assets+ * @param registry ECS registry to update+ */+ void reloadAssets(ecs::Registry& registry);++ /**+ * @brief Gets the Spine instance for an entity+ * @param entity Entity to query+ * @return Pointer to SpineInstance, or nullptr if not found+ */+ SpineInstance* getInstance(Entity entity);++ /**+ * @brief Gets the Spine instance for an entity (const)+ * @param entity Entity to query+ * @return Const pointer to SpineInstance, or nullptr if not found+ */+ const SpineInstance* getInstance(Entity entity) const;++ /**+ * @brief Plays an animation on an entity+ * @param entity Target entity+ * @param animation Animation name+ * @param loop Whether to loop+ * @param track Animation track (default 0)+ * @return True if animation was set+ */+ bool playAnimation(Entity entity, const std::string& animation,+ bool loop = true, i32 track = 0);++ /**+ * @brief Adds an animation to the queue+ * @param entity Target entity+ * @param animation Animation name+ * @param loop Whether to loop+ * @param delay Delay before starting+ * @param track Animation track (default 0)+ * @return True if animation was queued+ */+ bool addAnimation(Entity entity, const std::string& animation,+ bool loop = true, f32 delay = 0.0f, i32 track = 0);++ /**+ * @brief Sets skin on an entity+ * @param entity Target entity+ * @param skinName Skin name+ * @return True if skin was set+ */+ bool setSkin(Entity entity, const std::string& skinName);++ /**+ * @brief Gets bone world position+ * @param entity Target entity+ * @param boneName Bone name+ * @param outX Output X position+ * @param outY Output Y position+ * @return True if bone was found+ */+ bool getBonePosition(Entity entity, const std::string& boneName,+ f32& outX, f32& outY) const;++ /**+ * @brief Gets bone world rotation+ * @param entity Target entity+ * @param boneName Bone name+ * @param outRotation Output rotation in degrees+ * @return True if bone was found+ */+ bool getBoneRotation(Entity entity, const std::string& boneName,+ f32& outRotation) const;++ /**+ * @brief Gets skeleton bounds+ * @param entity Target entity+ * @param outX Output X offset+ * @param outY Output Y offset+ * @param outWidth Output width+ * @param outHeight Output height+ * @return True if bounds were retrieved+ */+ bool getSkeletonBounds(Entity entity, f32& outX, f32& outY,+ f32& outWidth, f32& outHeight) const;++private:+ void loadSkeletonForEntity(Entity entity, ecs::SpineAnimation& comp);+ void updateAnimation(Entity entity, ecs::SpineAnimation& comp, f32 deltaTime);+ void syncComponentToInstance(Entity entity, ecs::SpineAnimation& comp);++ SpineResourceManager& resource_manager_;+ std::unordered_map<Entity, SpineInstance> instances_;+};++} // namespace esengine::spinediff --git a/third_party/spine-runtimes b/third_party/spine-runtimesnew file mode 160000index 000000000..54d700974--- /dev/null+++ b/third_party/spine-runtimes@@ -0,0 +1 @@+Subproject commit 54d7009745a7f6a62db5352c09abc11a42b99a36