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: remove legacy AssetServer, unify asset loading through Assets

esengine34b1b9680c88
diff --git a/editor/src/asset/AssetDatabase.ts b/editor/src/asset/AssetDatabase.ts
index ea041d3a0..1ce9d14c0 100644
--- a/editor/src/asset/AssetDatabase.ts
+++ b/editor/src/asset/AssetDatabase.ts
@@ -3,6 +3,7 @@
* @brief Unified asset metadata center with UUID mapping, labels, addresses, and groups
*/
+import { getComponentAssetFields } from 'esengine';
import type { SceneData } from '../types/SceneTypes';
import type { TextureMetadata } from '../types/TextureMetadata';
import { joinPath, getFileExtension } from '../utils/path';
@@ -504,8 +505,8 @@ export class AssetDatabase {
private async migrateComponentRefs(comp: { type: string; data: Record<string, unknown> }): Promise<boolean> {
let changed = false;
- const refs = getComponentRefFields(comp.type);
- if (!refs || !comp.data) return false;
+ const refs = getComponentAssetFields(comp.type);
+ if (refs.length === 0 || !comp.data) return false;
for (const field of refs) {
const value = comp.data[field];
@@ -519,8 +520,8 @@ export class AssetDatabase {
}
private resolveComponentRefs(comp: { type: string; data: Record<string, unknown> }): void {
- const refs = getComponentRefFields(comp.type);
- if (!refs || !comp.data) return;
+ const refs = getComponentAssetFields(comp.type);
+ if (refs.length === 0 || !comp.data) return;
for (const field of refs) {
const value = comp.data[field];
@@ -535,15 +536,6 @@ export class AssetDatabase {
}
// =============================================================================
-// Component → Asset Reference Field Registry
-// =============================================================================
-
-import { getComponentAssetFields } from 'esengine';
-
-export function getComponentRefFields(componentType: string): string[] | undefined {
- const fields = getComponentAssetFields(componentType);
- return fields.length > 0 ? fields : undefined;
-}
// =============================================================================
// Singleton
diff --git a/editor/src/asset/AssetDependencyAnalyzer.ts b/editor/src/asset/AssetDependencyAnalyzer.ts
index 06d865a89..020d37afc 100644
--- a/editor/src/asset/AssetDependencyAnalyzer.ts
+++ b/editor/src/asset/AssetDependencyAnalyzer.ts
@@ -4,7 +4,8 @@
*/
import type { AssetDatabase } from './AssetDatabase';
-import { isUUID, getComponentRefFields } from './AssetDatabase';
+import { isUUID } from './AssetDatabase';
+import { getComponentAssetFields } from 'esengine';
import { looksLikeAssetPath } from './AssetTypes';
import { joinPath, isAbsolutePath, getDirName } from '../utils/path';
import type { NativeFS } from '../types/NativeFS';
@@ -40,11 +41,11 @@ export function registerRefScanner(scanner: AssetRefScanner): void {
function getScanner(componentType: string): AssetRefScanner | undefined {
const custom = customScanners.find(s => s.componentType === componentType);
if (custom) return custom;
- const fields = getComponentRefFields(componentType);
- if (!fields) return undefined;
+ const fields = getComponentAssetFields(componentType);
+ if (fields.length === 0) return undefined;
return {
componentType,
- extractRefs: (d) => fields.map(f => d[f] as string).filter(Boolean),
+ extractRefs: (d) => fields.map((f: string) => d[f] as string).filter(Boolean),
};
}
diff --git a/editor/src/asset/AssetLibrary.ts b/editor/src/asset/AssetLibrary.ts
index 424892559..0bff71404 100644
--- a/editor/src/asset/AssetLibrary.ts
+++ b/editor/src/asset/AssetLibrary.ts
@@ -11,6 +11,5 @@ export {
resetAssetDatabase as resetAssetLibrary,
resetAssetDatabase,
isUUID,
- getComponentRefFields,
type AssetEntry,
} from './AssetDatabase';
diff --git a/editor/src/asset/index.ts b/editor/src/asset/index.ts
index 9e4214a80..fc07b0f41 100644
--- a/editor/src/asset/index.ts
+++ b/editor/src/asset/index.ts
@@ -25,7 +25,6 @@ export {
resetAssetDatabase,
resetAssetDatabase as resetAssetLibrary,
isUUID,
- getComponentRefFields,
type AssetEntry,
} from './AssetDatabase';
diff --git a/editor/src/builder/ArtifactBuilder.ts b/editor/src/builder/ArtifactBuilder.ts
index c5de7c6e4..9a4a77ab6 100644
--- a/editor/src/builder/ArtifactBuilder.ts
+++ b/editor/src/builder/ArtifactBuilder.ts
@@ -10,7 +10,8 @@ import type { NativeFS } from '../types/NativeFS';
import { BuildProgressReporter } from './BuildProgress';
import { AssetExportConfigService, BuildAssetCollector } from './AssetCollector';
import { TextureAtlasPacker, type AtlasResult } from './TextureAtlas';
-import { AssetLibrary, isUUID, getComponentRefFields } from '../asset/AssetLibrary';
+import { AssetLibrary, isUUID } from '../asset/AssetLibrary';
+import { getComponentAssetFields } from 'esengine';
import { type TextureImporterSettings, getEffectiveImporter } from '../asset/ImporterTypes';
import { BuildCache } from './BuildCache';
import { getAssetType, toAddressableType } from '../asset/AssetTypes';
@@ -266,8 +267,8 @@ function resolveSceneUUIDs(sceneData: Record<string, unknown>, assetLibrary: Ass
for (const entity of entities) {
for (const comp of entity.components || []) {
if (!comp.data) continue;
- const refFields = getComponentRefFields(comp.type);
- if (!refFields) continue;
+ const refFields = getComponentAssetFields(comp.type);
+ if (refFields.length === 0) continue;
for (const field of refFields) {
const value = comp.data[field];
if (typeof value === 'string' && isUUID(value)) {
@@ -315,8 +316,8 @@ function embedTextureImporterSettings(sceneData: Record<string, unknown>, assetL
for (const entity of entities) {
for (const comp of entity.components || []) {
- const refFields = getComponentRefFields(comp.type);
- if (!refFields || !comp.data) continue;
+ const refFields = getComponentAssetFields(comp.type);
+ if (refFields.length === 0 || !comp.data) continue;
for (const field of refFields) {
const value = comp.data[field];
if (typeof value !== 'string' || !value) continue;
diff --git a/editor/src/builder/AssetCollector.ts b/editor/src/builder/AssetCollector.ts
index 63ffe235c..aecc7a7a7 100644
--- a/editor/src/builder/AssetCollector.ts
+++ b/editor/src/builder/AssetCollector.ts
@@ -8,7 +8,7 @@ import { type AssetDatabase, isUUID } from '../asset/AssetDatabase';
import { normalizePath, joinPath, isAbsolutePath, getFileExtension, getDirName } from '../utils/path';
import type { NativeFS } from '../types/NativeFS';
import { looksLikeAssetPath } from '../asset/AssetTypes';
-import { getComponentRefFields } from '../asset/AssetDatabase';
+import { getComponentAssetFields } from 'esengine';
import { getAssetTypeEntry } from 'esengine';
import { parseAtlasTextures } from '../asset/importers/SpineAtlasParser';
@@ -165,8 +165,8 @@ export class AssetReferenceCollector {
for (const comp of entity.components || []) {
if (!comp.data) continue;
- const refFields = getComponentRefFields(comp.type);
- if (refFields) {
+ const refFields = getComponentAssetFields(comp.type);
+ if (refFields.length > 0) {
for (const field of refFields) {
const value = comp.data[field];
if (typeof value !== 'string') continue;
@@ -249,8 +249,8 @@ export class AssetReferenceCollector {
for (const comp of entity.components || []) {
if (!comp.data) continue;
- const refFields = getComponentRefFields(comp.type);
- if (!refFields) continue;
+ const refFields = getComponentAssetFields(comp.type);
+ if (refFields.length === 0) continue;
for (const field of refFields) {
const value = comp.data[field];
if (typeof value !== 'string') continue;
diff --git a/editor/src/builder/EmitterUtils.ts b/editor/src/builder/EmitterUtils.ts
index d86c32af1..bb8413ba1 100644
--- a/editor/src/builder/EmitterUtils.ts
+++ b/editor/src/builder/EmitterUtils.ts
@@ -10,7 +10,8 @@ import type { NativeFS } from '../types/NativeFS';
import type { SdkModuleLoader } from '../scripting/types';
import { ScriptCompiler } from '../scripting/ScriptCompiler';
import { joinPath } from '../utils/path';
-import { isUUID, getComponentRefFields } from '../asset/AssetLibrary';
+import { isUUID } from '../asset/AssetLibrary';
+import { getComponentAssetFields } from 'esengine';
import { toBuildPath } from 'esengine';
// =============================================================================
@@ -129,8 +130,8 @@ export function resolveSceneUUIDs(sceneData: Record<string, unknown>, artifact:
}
}
for (const comp of entity.components || []) {
- const refFields = getComponentRefFields(comp.type);
- if (!refFields || !comp.data) continue;
+ const refFields = getComponentAssetFields(comp.type);
+ if (refFields.length === 0 || !comp.data) continue;
for (const field of refFields) {
const value = comp.data[field];
if (typeof value === 'string' && isUUID(value)) {
diff --git a/editor/src/prefab/PrefabSerializer.ts b/editor/src/prefab/PrefabSerializer.ts
index db83ce5f8..a85ac69cd 100644
--- a/editor/src/prefab/PrefabSerializer.ts
+++ b/editor/src/prefab/PrefabSerializer.ts
@@ -8,7 +8,8 @@ import type { PrefabData, PrefabEntityData } from '../types/PrefabTypes';
import { cloneComponents } from 'esengine';
import { getEditorContext } from '../context/EditorContext';
import type { NativeFS } from '../types/NativeFS';
-import { getGlobalPathResolver, getAssetDatabase, isUUID, getComponentRefFields } from '../asset';
+import { getGlobalPathResolver, getAssetDatabase, isUUID } from '../asset';
+import { getComponentAssetFields } from 'esengine';
import { stripComponentDefaults, mergeComponentDefaults } from '../io/sparse';
// =============================================================================
@@ -190,8 +191,8 @@ function convertAssetRefsInComponents(
converter: AssetRefConverter
): ComponentData[] {
return components.map(c => {
- const fields = getComponentRefFields(c.type);
- if (!fields || !c.data) return { type: c.type, data: { ...c.data } };
+ const fields = getComponentAssetFields(c.type);
+ if (fields.length === 0 || !c.data) return { type: c.type, data: { ...c.data } };
const data = { ...c.data };
for (const field of fields) {
@@ -279,8 +280,8 @@ async function migratePrefab(prefab: PrefabData): Promise<boolean> {
for (const entity of prefab.entities) {
for (const comp of entity.components) {
- const fields = getComponentRefFields(comp.type);
- if (!fields || !comp.data) continue;
+ const fields = getComponentAssetFields(comp.type);
+ if (fields.length === 0 || !comp.data) continue;
for (const field of fields) {
const value = comp.data[field];
if (typeof value === 'string' && value && !isUUID(value)) {
diff --git a/editor/src/preview/PreviewService.ts b/editor/src/preview/PreviewService.ts
index fc2ddb9a6..46f554ead 100644
--- a/editor/src/preview/PreviewService.ts
+++ b/editor/src/preview/PreviewService.ts
@@ -12,7 +12,7 @@ import { getEditorContext } from '../context/EditorContext';
import { getAssetLibrary } from '../asset/AssetLibrary';
import { getProjectDir } from '../utils/path';
import { deserializePrefab, convertPrefabAssetRefs } from '../prefab/PrefabSerializer';
-import { isUUID, getComponentRefFields } from '../asset';
+import { isUUID } from '../asset';
// =============================================================================
// Types
diff --git a/sdk/src/asset/AddressableManifest.ts b/sdk/src/asset/AddressableManifest.ts
new file mode 100644
index 000000000..c9b540aaf
--- /dev/null
+++ b/sdk/src/asset/AddressableManifest.ts
@@ -0,0 +1,27 @@
+import type { AddressableAssetType } from '../assetTypes';
+
+export type { AddressableAssetType };
+
+export interface AddressableManifestAsset {
+ path: string;
+ address?: string;
+ type: AddressableAssetType;
+ size: number;
+ labels: string[];
+ metadata?: {
+ atlas?: string;
+ atlasPage?: number;
+ atlasFrame?: { x: number; y: number; width: number; height: number };
+ };
+}
+
+export interface AddressableManifestGroup {
+ bundleMode: string;
+ labels: string[];
+ assets: Record<string, AddressableManifestAsset>;
+}
+
+export interface AddressableManifest {
+ version: '2.0';
+ groups: Record<string, AddressableManifestGroup>;
+}
diff --git a/sdk/src/asset/AssetHandlerRegistry.ts b/sdk/src/asset/AssetHandlerRegistry.ts
deleted file mode 100644
index 3ac6f60d1..000000000
--- a/sdk/src/asset/AssetHandlerRegistry.ts
+++ /dev/null
@@ -1,46 +0,0 @@
-import type { AssetServer } from './AssetServer';
-
-export type AssetFieldType = 'texture' | 'material' | 'font' | 'anim-clip' | 'audio' | 'tilemap' | 'timeline' | (string & {});
-
-export interface AssetFieldHandler {
- load(
- paths: Set<string>,
- assetServer: AssetServer,
- baseUrl: string | undefined,
- texturePathToUrl: Map<string, string>,
- ): Promise<Map<string, number>>;
-}
-
-const handlers_ = new Map<string, AssetFieldHandler>();
-let initialized_ = false;
-let initFn_: (() => void) | null = null;
-
-export function setBuiltinAssetHandlerInit(fn: () => void): void {
- initFn_ = fn;
-}
-
-function ensureInitialized(): void {
- if (!initialized_ && initFn_) {
- initialized_ = true;
- initFn_();
- }
-}
-
-export function registerAssetHandler(type: string, handler: AssetFieldHandler): void {
- handlers_.set(type, handler);
-}
-
-export function getAssetHandler(type: string): AssetFieldHandler | undefined {
- ensureInitialized();
- return handlers_.get(type);
-}
-
-export function getAssetHandlers(): ReadonlyMap<string, AssetFieldHandler> {
- ensureInitialized();
- return handlers_;
-}
-
-export function clearAssetHandlerRegistry(): void {
- handlers_.clear();
- initialized_ = false;
-}
diff --git a/sdk/src/asset/AssetLoader.ts b/sdk/src/asset/AssetLoader.ts
index 4cd176382..271c90b64 100644
--- a/sdk/src/asset/AssetLoader.ts
+++ b/sdk/src/asset/AssetLoader.ts
@@ -13,6 +13,11 @@ export interface SpineResult {
skeletonHandle: number;
}
+export interface SpineLoadResult {
+ success: boolean;
+ error?: string;
+}
+
export interface MaterialResult {
handle: number;
shaderHandle: number;
diff --git a/sdk/src/asset/AssetPlugin.ts b/sdk/src/asset/AssetPlugin.ts
index 4260244c5..522230409 100644
--- a/sdk/src/asset/AssetPlugin.ts
+++ b/sdk/src/asset/AssetPlugin.ts
@@ -3,7 +3,6 @@ import { defineResource } from '../resource';
import { Assets as AssetsClass } from './Assets';
import { HttpBackend } from './Backend';
import { initBuiltinAssetFields } from './AssetFieldRegistry';
-import { initBuiltinAssetHandlers } from './builtinAssetHandlers';
export type AssetsData = AssetsClass;
@@ -23,7 +22,6 @@ export class AssetPlugin implements Plugin {
}
initBuiltinAssetFields();
- initBuiltinAssetHandlers();
const assets = AssetsClass.create({
backend: new HttpBackend({ baseUrl: '' }),
diff --git a/sdk/src/asset/AssetServer.ts b/sdk/src/asset/AssetServer.ts
deleted file mode 100644
index 147196a62..000000000
--- a/sdk/src/asset/AssetServer.ts
+++ /dev/null
@@ -1,1106 +0,0 @@
-/**
- * @file AssetServer.ts
- * @brief Asset loading and caching system
- */
-
-import type { Entity, TextureHandle, FontHandle } from '../types';
-import { RuntimeConfig } from '../defaults';
-import type { ESEngineModule } from '../wasm';
-import type { ShaderHandle } from '../material';
-import { Material } from '../material';
-import { MaterialLoader, type LoadedMaterial, type ShaderLoader } from './MaterialLoader';
-import { platformReadTextFile, platformReadFile, platformFileExists, platformFetch, platformCreateCanvas, platformCreateImage } from '../platform';
-import type { World } from '../world';
-import { loadSceneWithAssets, type SceneData } from '../scene';
-import { AsyncCache } from './AsyncCache';
-import { requireResourceManager, evictTextureDimensions } from '../resourceManager';
-import type { PrefabData } from '../prefab';
-import type { SpineModuleController } from '../spine/SpineController';
-import { type AddressableAssetType, getAssetTypeEntry, toBuildPath } from '../assetTypes';
-import { getComponentAssetFields, getComponentSpineFieldDescriptor } from '../scene';
-
-// =============================================================================
-// Types
-// =============================================================================
-
-export interface TextureInfo {
- handle: TextureHandle;
- width: number;
- height: number;
-}
-
-export interface SliceBorder {
- left: number;
- right: number;
- top: number;
- bottom: number;
-}
-
-export interface SpineLoadResult {
- success: boolean;
- error?: string;
-}
-
-export interface SpineDescriptor {
- skeleton: string;
- atlas: string;
- baseUrl?: string;
-}
-
-export interface FileLoadOptions {
- baseUrl?: string;
- noCache?: boolean;
-}
-
-export type { AddressableAssetType };
-
-export interface AddressableResultMap {
- texture: TextureInfo;
- material: LoadedMaterial;
- spine: SpineLoadResult;
- 'bitmap-font': FontHandle;
- prefab: PrefabData;
- json: unknown;
- text: string;
- binary: ArrayBuffer;
- audio: ArrayBuffer;
-}
-
-export interface AssetBundle {
- textures: Map<string, TextureInfo>;
- materials: Map<string, LoadedMaterial>;
- spine: Map<string, SpineLoadResult>;
- fonts: Map<string, FontHandle>;
- prefabs: Map<string, PrefabData>;
- json: Map<string, unknown>;
- text: Map<string, string>;
- binary: Map<string, ArrayBuffer>;
-}
-
-export interface AddressableManifestAsset {
- path: string;
- address?: string;
- type: AddressableAssetType;
- size: number;
- labels: string[];
- metadata?: {
- atlas?: string;
- atlasPage?: number;
- atlasFrame?: { x: number; y: number; width: number; height: number };
- };
-}
-
-export interface AddressableManifestGroup {
- bundleMode: string;
- labels: string[];
- assets: Record<string, AddressableManifestAsset>;
-}
-
-export interface AddressableManifest {
- version: '2.0';
- groups: Record<string, AddressableManifestGroup>;
-}
-
-// =============================================================================
-// AssetServer
-// =============================================================================
-
-export class AssetServer {
- baseUrl?: string;
-
- private module_: ESEngineModule;
- private textureCache_ = new AsyncCache<TextureInfo>();
- private shaderCache_ = new AsyncCache<ShaderHandle>();
- private jsonCache_ = new AsyncCache<unknown>();
- private textCache_ = new AsyncCache<string>();
- private binaryCache_ = new AsyncCache<ArrayBuffer>();
- private loadedSpines_ = new Set<string>();
- private virtualFSPaths_ = new Set<string>();
- private materialLoader_: MaterialLoader;
- private canvas_: HTMLCanvasElement;
- private ctx_: CanvasRenderingContext2D;
- private fontCache_ = new AsyncCache<FontHandle>();
- private prefabCache_ = new AsyncCache<PrefabData>();
- private embedded_ = new Map<string, string>();
- private embeddedOnly_ = false;
- private addressableManifest_: AddressableManifest | null = null;
- private addressIndex_ = new Map<string, AddressableManifestAsset>();
- private labelIndex_ = new Map<string, AddressableManifestAsset[]>();
- private groupAssets_ = new Map<string, AddressableManifestAsset[]>();
- private spineController_: SpineModuleController | null = null;
- private spineSkeletons_ = new Map<string, number>();
- private textureRefCounts_ = new Map<string, number>();
- private assetRefResolver_: ((ref: string) => string | null) | null = null;
-
- constructor(module: ESEngineModule) {
- this.module_ = module;
- this.canvas_ = platformCreateCanvas(RuntimeConfig.textCanvasSize, RuntimeConfig.textCanvasSize) as HTMLCanvasElement;
- this.ctx_ = this.canvas_.getContext('2d', { willReadFrequently: true })!;
-
- const shaderLoader: ShaderLoader = {
- load: (path: string) => this.loadShader(path),
- get: (path: string) => this.shaderCache_.get(path),
- };
- this.materialLoader_ = new MaterialLoader(shaderLoader);
- }
-
- // =========================================================================
- // Embedded Assets
- // =========================================================================
-
- registerEmbeddedAssets(assets: Record<string, string>): void {
- for (const [key, value] of Object.entries(assets)) {
- this.embedded_.set(key, value);
- }
- if (!this.embeddedOnly_) {
- this.embeddedOnly_ = typeof location !== 'undefined' && location.protocol === 'file:';
- }
- }
-
- setEmbeddedOnly(value: boolean): void {
- this.embeddedOnly_ = value;
- }
-
- // =========================================================================
- // Texture
- // =========================================================================
-
- /**
- * Load texture with vertical flip (for Sprite/UI).
- * OpenGL UV origin is bottom-left, so standard images need flipping.
- */
- async loadTexture(source: string): Promise<TextureInfo> {
- return this.loadTextureWithFlip(source, true);
- }
-
- /**
- * Load texture without flip (for Spine).
- * Spine runtime handles UV coordinates internally.
- */
- async loadTextureRaw(source: string): Promise<TextureInfo> {
- return this.loadTextureWithFlip(source, false);
- }
-
- getTexture(source: string): TextureInfo | undefined {
- return this.textureCache_.get(this.textureCacheKey(source, true));
- }
-
- hasTexture(source: string): boolean {
- return this.textureCache_.has(this.textureCacheKey(source, true));
- }
-
- getTextureRefCount(source: string): number {
- let total = 0;
- for (const flip of [true, false]) {
- total += this.textureRefCounts_.get(this.textureCacheKey(source, flip)) ?? 0;
- }
- return total;
- }
-
- releaseTexture(source: string): void {
- const rm = requireResourceManager();
- for (const flip of [true, false]) {
- const key = this.textureCacheKey(source, flip);
- const refCount = this.textureRefCounts_.get(key);
- if (refCount === undefined) continue;
-
- const info = this.textureCache_.get(key);
- if (!info) continue;
-
- const count = refCount - 1;
- if (count <= 0) {
- rm.releaseTexture(info.handle);
- evictTextureDimensions(info.handle);
- this.textureCache_.delete(key);
- this.textureRefCounts_.delete(key);
- } else {
- this.textureRefCounts_.set(key, count);
- }
- }
- }
-
- releaseAll(): void {
- const rm = requireResourceManager();
- for (const info of this.textureCache_.values()) {
- rm.releaseTexture(info.handle);
- evictTextureDimensions(info.handle);
- }
- for (const handle of this.fontCache_.values()) {
- rm.releaseBitmapFont(handle);
- }
- this.materialLoader_.releaseAll();
- Material.releaseAll();
- this.textureCache_.clearAll();
- this.textureRefCounts_.clear();
- this.shaderCache_.clearAll();
- this.fontCache_.clearAll();
- this.prefabCache_.clearAll();
- this.jsonCache_.clearAll();
- this.textCache_.clearAll();
- this.binaryCache_.clearAll();
- this.loadedSpines_.clear();
- if (this.spineController_) {
- for (const handle of this.spineSkeletons_.values()) {
- this.spineController_.unloadSkeleton(handle);
- }
- }
- this.spineSkeletons_.clear();
- this.cleanupVirtualFS();
- }
-
- private cleanupVirtualFS(): void {
- const fs = this.module_.FS;
- if (!fs) return;
- for (const path of this.virtualFSPaths_) {
- try {
- fs.unlink(path);
- } catch {
- // File may already be removed
- }
- }
- this.virtualFSPaths_.clear();
- }
-
- setTextureMetadata(handle: TextureHandle, border: SliceBorder): void {
- const rm = requireResourceManager();
- rm.setTextureMetadata(handle, border.left, border.right, border.top, border.bottom);
- }
-
- setTextureMetadataByPath(source: string, border: SliceBorder): boolean {
- const info = this.textureCache_.get(this.textureCacheKey(source, true));
- if (info) {
- this.setTextureMetadata(info.handle, border);
- return true;
- }
- return false;
- }
-
- // =========================================================================
- // Spine
- // =========================================================================
-
- setSpineController(controller: SpineModuleController): void {
- this.spineController_ = controller;
- }
-
- getSpineSkeletonHandle(skeletonPath: string, atlasPath: string): number | undefined {
- return this.spineSkeletons_.get(`${skeletonPath}:${atlasPath}`);
- }
-
- async loadSpine(
- skeletonPath: string,
- atlasPath: string,
- baseUrl?: string
- ): Promise<SpineLoadResult> {
- const cacheKey = `${skeletonPath}:${atlasPath}`;
- if (this.loadedSpines_.has(cacheKey)) {
- return { success: true };
- }
-
- try {
- const atlasUrl = this.resolveUrl(atlasPath, baseUrl);
- const atlasContent = await this.fetchText(atlasUrl);
-
- if (!this.writeToVirtualFS(atlasPath, atlasContent)) {
- return { success: false, error: `Failed to write atlas to virtual FS: ${atlasPath}` };
- }
-
- const atlasDir = atlasPath.substring(0, atlasPath.lastIndexOf('/'));
- const textureNames = this.parseAtlasTextures(atlasContent);
- const loadedTextures: { name: string; info: TextureInfo }[] = [];
-
- for (const texName of textureNames) {
- const texPath = atlasDir ? `${atlasDir}/${texName}` : texName;
- const texUrl = this.resolveUrl(texPath, baseUrl);
-
- try {
- const info = await this.loadTextureRaw(texUrl);
- const rm = requireResourceManager();
- rm.registerTextureWithPath(info.handle, texPath);
- loadedTextures.push({ name: texName, info });
- } catch (err) {
- console.warn(`[AssetServer] Failed to load Spine texture: ${texPath}`, err);
- }
- }
-
- const skelUrl = this.resolveUrl(skeletonPath, baseUrl);
- const isBinary = getAssetTypeEntry(skeletonPath)?.contentType === 'binary';
- const skelData = isBinary
- ? new Uint8Array(await this.fetchBinary(skelUrl))
- : await this.fetchText(skelUrl);
-
- if (!this.writeToVirtualFS(skeletonPath, skelData)) {
- return { success: false, error: `Failed to write skeleton to virtual FS: ${skeletonPath}` };
- }
-
- this.loadedSpines_.add(cacheKey);
-
- if (this.spineController_) {
- const skelHandle = this.spineController_.loadSkeleton(skelData, atlasContent, isBinary);
- if (skelHandle >= 0) {
- const rm = requireResourceManager();
- const pageCount = this.spineController_.getAtlasPageCount(skelHandle);
- for (let i = 0; i < pageCount; i++) {
- const pageName = this.spineController_.getAtlasPageTextureName(skelHandle, i);
- const tex = loadedTextures.find(t => t.name === pageName);
- if (tex) {
- const glId = rm.getTextureGLId(tex.info.handle);
- this.spineController_.setAtlasPageTexture(
- skelHandle, i, glId, tex.info.width, tex.info.height
- );
- }
- }
- this.spineSkeletons_.set(cacheKey, skelHandle);
- }
- }
-
- return { success: true };
- } catch (err) {
- return { success: false, error: String(err) };
- }
- }
-
- isSpineLoaded(skeletonPath: string, atlasPath: string): boolean {
- return this.loadedSpines_.has(`${skeletonPath}:${atlasPath}`);
- }
-
- releaseSpine(key: string): void {
- if (!this.loadedSpines_.has(key)) return;
- this.loadedSpines_.delete(key);
- const handle = this.spineSkeletons_.get(key);
- if (handle !== undefined && this.spineController_) {
- this.spineController_.unloadSkeleton(handle);
- this.spineSkeletons_.delete(key);
- }
- }
-
- // =========================================================================
- // BitmapFont
- // =========================================================================
-
- async loadBitmapFont(fontPath: string, baseUrl?: string): Promise<FontHandle> {
- const url = this.resolveUrl(fontPath, baseUrl);
- return this.fontCache_.getOrLoad(url, async () => {
- const fontEntry = getAssetTypeEntry(fontPath);
- if (fontEntry?.editorType === 'bitmap-font' && fontEntry.contentType === 'json') {
- return this.loadBmfontAsset(url);
- }
- return this.loadFntFile(url);
- });
- }
-
- getFont(fontPath: string): FontHandle | undefined {
- return this.fontCache_.get(fontPath);
- }
-
- releaseFont(fontPath: string): void {
- const handle = this.fontCache_.get(fontPath);
- if (handle) {
- const rm = requireResourceManager();
- rm.releaseBitmapFont(handle);
- this.fontCache_.delete(fontPath);
- }
- }
-
- private async loadBmfontAsset(url: string): Promise<FontHandle> {
- const json = await this.fetchJson(url) as {
- type: string;
- fntFile?: string;
- generatedFnt?: string;
- };
- const dir = url.substring(0, url.lastIndexOf('/'));
-
- const fntFile = json.type === 'label-atlas'
- ? json.generatedFnt
- : json.fntFile;
-
- if (!fntFile) {
- throw new Error(`Invalid bmfont asset: no fnt file specified`);
- }
- const fntUrl = dir ? `${dir}/${fntFile}` : fntFile;
- return this.loadFntFile(fntUrl);
- }
-
- private async loadFntFile(url: string): Promise<FontHandle> {
- const fntContent = await this.fetchText(url);
- const pageMatch = fntContent.match(/file="([^"]+)"/);
- if (!pageMatch) {
- throw new Error(`No page texture found in .fnt file: ${url}`);
- }
- const texName = pageMatch[1];
- const fntDir = url.substring(0, url.lastIndexOf('/'));
- const texUrl = fntDir ? `${fntDir}/${texName}` : texName;
- const texInfo = await this.loadTextureRaw(texUrl);
- const rm = requireResourceManager();
- return rm.loadBitmapFont(fntContent, texInfo.handle, texInfo.width, texInfo.height) as FontHandle;
- }
-
- // =========================================================================
- // Asset Ref Resolver
- // =========================================================================
-
- setAssetRefResolver(resolver: (ref: string) => string | null): void {
- this.assetRefResolver_ = resolver;
- }
-
- // =========================================================================
- // Prefab
- // =========================================================================
-
- async loadPrefab(path: string, baseUrl?: string): Promise<PrefabData> {
- const url = this.resolveUrl(path, baseUrl);
- return this.prefabCache_.getOrLoad(url, async () => {
- const data = await this.fetchJson(url) as PrefabData;
- if (this.assetRefResolver_) {
- this.resolvePrefabRefs_(data);
- }
- return data;
- });
- }
-
- private resolvePrefabRefs_(prefab: PrefabData): void {
- const resolve = this.assetRefResolver_!;
- for (const entity of prefab.entities) {
- for (const comp of entity.components) {
- if (!comp.data) continue;
- for (const field of getComponentAssetFields(comp.type)) {
- const value = comp.data[field];
- if (typeof value === 'string' && value) {
- const resolved = resolve(value);
- if (resolved) comp.data[field] = resolved;
- }
- }
- const spine = getComponentSpineFieldDescriptor(comp.type);
- if (spine) {
- for (const field of [spine.skeletonField, spine.atlasField]) {
- const value = comp.data[field];
- if (typeof value === 'string' && value) {
- const resolved = resolve(value);
- if (resolved) comp.data[field] = resolved;
- }
- }
- }
- }
- if (entity.nestedPrefab?.prefabPath) {
- const resolved = resolve(entity.nestedPrefab.prefabPath);
- if (resolved) entity.nestedPrefab.prefabPath = resolved;
- }
- }
- }
-
- // =========================================================================
- // Material & Shader
- // =========================================================================
-
- async loadMaterial(path: string, baseUrl?: string): Promise<LoadedMaterial> {
- return this.materialLoader_.load(this.resolveUrl(path, baseUrl));
- }
-
- getMaterial(path: string, baseUrl?: string): LoadedMaterial | undefined {
- return this.materialLoader_.get(this.resolveUrl(path, baseUrl));
- }
-
- hasMaterial(path: string, baseUrl?: string): boolean {
- return this.materialLoader_.has(this.resolveUrl(path, baseUrl));
- }
-
- async loadShader(path: string): Promise<ShaderHandle> {
- return this.shaderCache_.getOrLoad(path, () => this.loadShaderInternal(path));
- }
-
- // =========================================================================
- // Generic File Loading
- // =========================================================================
-
- async loadJson<T = unknown>(path: string, options?: FileLoadOptions): Promise<T> {
- const url = this.resolveUrl(path, options?.baseUrl);
- if (options?.noCache) {
- return this.fetchJson(url) as Promise<T>;
- }
- return this.jsonCache_.getOrLoad(url, () => this.fetchJson(url)) as Promise<T>;
- }
-
- async loadText(path: string, options?: FileLoadOptions): Promise<string> {
- const url = this.resolveUrl(path, options?.baseUrl);
- if (options?.noCache) {
- return this.fetchText(url);
- }
- return this.textCache_.getOrLoad(url, () => this.fetchText(url));
- }
-
- async loadBinary(path: string, options?: FileLoadOptions): Promise<ArrayBuffer> {
- const url = this.resolveUrl(path, options?.baseUrl);
- if (options?.noCache) {
- return this.fetchBinary(url);
- }
- return this.binaryCache_.getOrLoad(url, () => this.fetchBinary(url));
- }
-
- // =========================================================================
- // Scene & Batch
- // =========================================================================
-
- async loadScene(world: World, sceneData: SceneData): Promise<Map<number, Entity>> {
- return loadSceneWithAssets(world, sceneData, { assetServer: this });
- }
-
- async loadAll(manifest: AddressableManifest): Promise<AssetBundle> {
- this.setAddressableManifest(manifest);
- const allAssets: AddressableManifestAsset[] = [];
- if (manifest.groups) {
- for (const group of Object.values(manifest.groups)) {
- if (group.assets) {
- allAssets.push(...Object.values(group.assets));
- }
- }
- }
- return this.loadAddressableAssets(allAssets);
- }
-
- // =========================================================================
- // Addressable Assets
- // =========================================================================
-
- setAddressableManifest(manifest: AddressableManifest): void {
- this.addressableManifest_ = manifest;
- this.addressIndex_.clear();
- this.labelIndex_.clear();
- this.groupAssets_.clear();
-
- for (const [groupName, group] of Object.entries(manifest.groups || {})) {
- const groupList: AddressableManifestAsset[] = [];
- for (const asset of Object.values(group.assets)) {
- groupList.push(asset);
- if (asset.address) {
- this.addressIndex_.set(asset.address, asset);
- }
- for (const label of asset.labels) {
- let list = this.labelIndex_.get(label);
- if (!list) {
- list = [];
- this.labelIndex_.set(label, list);
- }
- list.push(asset);
- }
- }
- this.groupAssets_.set(groupName, groupList);
- }
- }
-
- resolveAddress(address: string): AddressableManifestAsset | undefined {
- return this.addressIndex_.get(address);
- }
-
- async load<T extends AddressableAssetType = AddressableAssetType>(
- address: string
- ): Promise<AddressableResultMap[T]> {
- const asset = this.addressIndex_.get(address);
- if (!asset) {
- throw new Error(`No asset found with address: ${address}`);
- }
- return this.loadAddressableAsset(asset) as Promise<AddressableResultMap[T]>;
- }
-
- async loadByLabel(label: string): Promise<AssetBundle> {
- const assets = this.labelIndex_.get(label) ?? [];
- return this.loadAddressableAssets(assets);
- }
-
- async loadGroup(groupName: string): Promise<AssetBundle> {
- const assets = this.groupAssets_.get(groupName) ?? [];
- return this.loadAddressableAssets(assets);
- }
-
- private async loadAddressableAsset(asset: AddressableManifestAsset): Promise<unknown> {
- switch (asset.type) {
- case 'texture':
- return this.loadTexture(asset.path);
- case 'material':
- return this.loadMaterial(asset.path);
- case 'spine': {
- const atlas = asset.metadata?.atlas;
- if (!atlas) throw new Error(`Spine asset missing atlas metadata: ${asset.path}`);
- return this.loadSpine(asset.path, atlas);
- }
- case 'bitmap-font':
- return this.loadBitmapFont(asset.path);
- case 'prefab':
- return this.loadPrefab(asset.path);
- case 'audio':
- return this.loadBinary(asset.path);
- case 'json':
- return this.loadJson(asset.path);
- case 'text':
- return this.loadText(asset.path);
- case 'binary':
- return this.loadBinary(asset.path);
- default:
- return this.loadBinary(asset.path);
- }
- }
-
- private async loadAddressableAssets(assets: AddressableManifestAsset[]): Promise<AssetBundle> {
- const bundle: AssetBundle = {
- textures: new Map(),
- materials: new Map(),
- spine: new Map(),
- fonts: new Map(),
- prefabs: new Map(),
- json: new Map(),
- text: new Map(),
- binary: new Map(),
- };
-
- const promises: Promise<void>[] = [];
- for (const asset of assets) {
- const key = asset.address ?? asset.path;
- switch (asset.type) {
- case 'texture':
- promises.push(
- this.loadTexture(asset.path).then(info => { bundle.textures.set(key, info); })
- );
- break;
- case 'material':
- promises.push(
- this.loadMaterial(asset.path).then(mat => { bundle.materials.set(key, mat); })
- );
- break;
- case 'spine': {
- const atlas = asset.metadata?.atlas;
- if (atlas) {
- promises.push(
- this.loadSpine(asset.path, atlas).then(result => { bundle.spine.set(key, result); })
- );
- }
- break;
- }
- case 'bitmap-font':
- promises.push(
- this.loadBitmapFont(asset.path).then(handle => { bundle.fonts.set(key, handle); })
- );
- break;
- case 'prefab':
- promises.push(
- this.loadPrefab(asset.path).then(data => { bundle.prefabs.set(key, data); })
- );
- break;
- case 'audio':
- promises.push(
- this.loadBinary(asset.path).then(data => { bundle.binary.set(key, data); })
- );
- break;
- case 'json':
- promises.push(
- this.loadJson(asset.path).then(data => { bundle.json.set(key, data); })
- );
- break;
- case 'text':
- promises.push(
- this.loadText(asset.path).then(data => { bundle.text.set(key, data); })
- );
- break;
- case 'binary':
- default:
- promises.push(
- this.loadBinary(asset.path).then(data => { bundle.binary.set(key, data); })
- );
- break;
- }
- }
-
- const results = await Promise.allSettled(promises);
- for (const result of results) {
- if (result.status === 'rejected') {
- console.warn('[AssetServer] Failed to load asset:', result.reason);
- }
- }
- return bundle;
- }
-
- // =========================================================================
- // Private - Texture
- // =========================================================================
-
- private textureCacheKey(source: string, flip: boolean): string {
- return `${source}:${flip ? 'f' : 'n'}`;
- }
-
- private async loadTextureWithFlip(source: string, flip: boolean): Promise<TextureInfo> {
- const cacheKey = this.textureCacheKey(source, flip);
- const info = await this.textureCache_.getOrLoad(cacheKey, () => this.loadTextureInternal(source, flip));
- this.textureRefCounts_.set(cacheKey, (this.textureRefCounts_.get(cacheKey) ?? 0) + 1);
- return info;
- }
-
- private async loadTextureInternal(source: string, flip: boolean): Promise<TextureInfo> {
- const img = await this.loadImage(source);
- return this.createTextureFromImage(img, flip);
- }
-
- private async loadImage(source: string): Promise<HTMLImageElement | ImageBitmap> {
- const localPath = this.isLocalPath(source) ? this.toLocalPath(source) : null;
- if (localPath) {
- const embedded = this.getEmbedded(localPath);
- if (embedded) {
- return this.loadImageFromSrc(embedded);
- }
- if (this.embeddedOnly_) {
- throw new Error(`Asset not embedded: ${source}`);
- }
- const imgSrc = this.baseUrl ? `${this.baseUrl}/${localPath}` : localPath;
- return this.loadImageFromSrc(imgSrc);
- }
- if (this.embeddedOnly_) {
- throw new Error(`Asset not embedded: ${source}`);
- }
- return this.loadImageFromSrc(source);
- }
-
- private loadImageFromSrc(imgSrc: string): Promise<HTMLImageElement | ImageBitmap> {
- return new Promise((resolve, reject) => {
- const img = platformCreateImage();
- img.crossOrigin = 'anonymous';
- img.onload = async () => {
- if (typeof createImageBitmap !== 'undefined') {
- try {
- const bitmap = await createImageBitmap(img, {
- premultiplyAlpha: 'none',
- colorSpaceConversion: 'none'
- });
- resolve(bitmap);
- return;
- } catch {
- // Fall back to Image element
- }
- }
- resolve(img);
- };
- img.onerror = () => reject(new Error(`Failed to load image: ${imgSrc}`));
- img.src = imgSrc;
- });
- }
-
- private createTextureFromImage(img: HTMLImageElement | ImageBitmap, flip: boolean): TextureInfo {
- const { width, height } = img;
- const gl = this.getWebGL2Context();
-
- if (gl) {
- return this.createTextureWebGL2(gl, img, width, height, flip);
- }
-
- return this.createTextureFallback(img, width, height, flip);
- }
-
- private getWebGL2Context(): WebGL2RenderingContext | null {
- try {
- const glObj = (this.module_ as any).GL;
- if (glObj && glObj.currentContext && glObj.currentContext.GLctx) {
- const ctx = glObj.currentContext.GLctx;
- if (ctx instanceof WebGL2RenderingContext) {
- return ctx;
- }
- }
- } catch {
- // Fall through to fallback
- }
- return null;
- }
-
- private createTextureWebGL2(
- gl: WebGL2RenderingContext,
- img: HTMLImageElement | ImageBitmap,
- width: number,
- height: number,
- flip: boolean,
- ): TextureInfo {
- const texture = gl.createTexture()!;
- gl.bindTexture(gl.TEXTURE_2D, texture);
-
- gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, flip ? 1 : 0);
- gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
-
- gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, img as any);
-
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT);
- gl.generateMipmap(gl.TEXTURE_2D);
-
- gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
-
- const glObj = (this.module_ as any).GL;
- const glTextureId = glObj.getNewId(glObj.textures);
- glObj.textures[glTextureId] = texture;
-
- const rm = requireResourceManager();
- const handle = rm.registerExternalTexture(glTextureId, width, height);
-
- return { handle, width, height };
- }
-
- private createTextureFallback(
- img: HTMLImageElement | ImageBitmap,
- width: number,
- height: number,
- flip: boolean,
- ): TextureInfo {
- if (this.canvas_.width < width || this.canvas_.height < height) {
- this.canvas_.width = Math.max(this.canvas_.width, this.nextPowerOf2(width));
- this.canvas_.height = Math.max(this.canvas_.height, this.nextPowerOf2(height));
- }
-
- this.ctx_.clearRect(0, 0, this.canvas_.width, this.canvas_.height);
- this.ctx_.drawImage(img, 0, 0);
-
- const imageData = this.ctx_.getImageData(0, 0, width, height);
- const pixels = new Uint8Array(imageData.data.buffer);
- this.unpremultiplyAlpha(pixels);
-
- const rm = requireResourceManager();
- const ptr = this.module_._malloc(pixels.length);
- this.module_.HEAPU8.set(pixels, ptr);
- const handle = rm.createTexture(width, height, ptr, pixels.length, 1, flip);
- this.module_._free(ptr);
-
- return { handle, width, height };
- }
-
- private unpremultiplyAlpha(pixels: Uint8Array): void {
- for (let i = 0; i < pixels.length; i += 4) {
- const a = pixels[i + 3];
- if (a > 0 && a < 255) {
- const scale = 255 / a;
- pixels[i] = Math.min(255, Math.round(pixels[i] * scale));
- pixels[i + 1] = Math.min(255, Math.round(pixels[i + 1] * scale));
- pixels[i + 2] = Math.min(255, Math.round(pixels[i + 2] * scale));
- }
- }
- }
-
- // =========================================================================
- // Private - Shader
- // =========================================================================
-
- private async loadShaderInternal(path: string): Promise<ShaderHandle> {
- const localPath = this.isLocalPath(path) ? this.toLocalPath(path) : path;
-
- const embedded = this.getEmbedded(localPath);
- if (embedded) {
- const content = this.decodeDataUrlText(embedded);
- const { vertex, fragment } = this.parseEsShader(content);
- if (!vertex || !fragment) {
- throw new Error(`Invalid shader format: ${path}`);
- }
- return Material.createShader(vertex, fragment);
- }
-
- if (this.embeddedOnly_) {
- throw new Error(`Asset not embedded: ${path}`);
- }
-
- const exists = await platformFileExists(localPath);
- if (!exists) {
- throw new Error(`Shader file not found: ${path}`);
- }
-
- const content = await platformReadTextFile(localPath);
- if (!content) {
- throw new Error(`Failed to read shader file: ${path}`);
- }
-
- const { vertex, fragment } = this.parseEsShader(content);
- if (!vertex || !fragment) {
- throw new Error(`Invalid shader format: ${path}`);
- }
-
- return Material.createShader(vertex, fragment);
- }
-
- private parseEsShader(content: string): { vertex: string | null; fragment: string | null } {
- const vertexMatch = content.match(/#pragma\s+vertex\s*([\s\S]*?)#pragma\s+end/);
- const fragmentMatch = content.match(/#pragma\s+fragment\s*([\s\S]*?)#pragma\s+end/);
- return {
- vertex: vertexMatch?.[1].trim() ?? null,
- fragment: fragmentMatch?.[1].trim() ?? null,
- };
- }
-
- // =========================================================================
- // Private - Generic Fetch
- // =========================================================================
-
- private decodeDataUrlText(dataUrl: string): string {
- return atob(dataUrl.split(',')[1]);
- }
-
- private decodeDataUrlBinary(dataUrl: string): ArrayBuffer {
- const raw = atob(dataUrl.split(',')[1]);
- const bytes = new Uint8Array(raw.length);
- for (let i = 0; i < raw.length; i++) {
- bytes[i] = raw.charCodeAt(i);
- }
- return bytes.buffer;
- }
-
- private isLocalPath(url: string): boolean {
- return !url.startsWith('http://') && !url.startsWith('https://') && !url.startsWith('asset://');
- }
-
- private toLocalPath(url: string): string {
- return url.startsWith('/') ? url.substring(1) : url;
- }
-
- private getEmbedded(localPath: string): string | undefined {
- return this.embedded_.get(localPath) ?? this.embedded_.get(toBuildPath(localPath));
- }
-
- private async fetchJson(url: string): Promise<unknown> {
- const localPath = this.isLocalPath(url) ? this.toLocalPath(url) : null;
- if (localPath) {
- const embedded = this.getEmbedded(localPath);
- if (embedded) {
- return JSON.parse(this.decodeDataUrlText(embedded));
- }
- if (this.embeddedOnly_) {
- throw new Error(`Asset not embedded: ${url}`);
- }
- const text = await platformReadTextFile(localPath);
- return JSON.parse(text);
- }
- if (this.embeddedOnly_) {
- throw new Error(`Asset not embedded: ${url}`);
- }
- const response = await platformFetch(url);
- if (!response.ok) {
- throw new Error(`Failed to fetch JSON: ${url} (${response.status})`);
- }
- return response.json();
- }
-
- private async fetchText(url: string): Promise<string> {
- const localPath = this.isLocalPath(url) ? this.toLocalPath(url) : null;
- if (localPath) {
- const embedded = this.getEmbedded(localPath);
- if (embedded) {
- return this.decodeDataUrlText(embedded);
- }
- if (this.embeddedOnly_) {
- throw new Error(`Asset not embedded: ${url}`);
- }
- return platformReadTextFile(localPath);
- }
- if (this.embeddedOnly_) {
- throw new Error(`Asset not embedded: ${url}`);
- }
- const response = await platformFetch(url);
- if (!response.ok) {
- throw new Error(`Failed to fetch text: ${url} (${response.status})`);
- }
- return response.text();
- }
-
- private async fetchBinary(url: string): Promise<ArrayBuffer> {
- const localPath = this.isLocalPath(url) ? this.toLocalPath(url) : null;
- if (localPath) {
- const embedded = this.getEmbedded(localPath);
- if (embedded) {
- return this.decodeDataUrlBinary(embedded);
- }
- if (this.embeddedOnly_) {
- throw new Error(`Asset not embedded: ${url}`);
- }
- return platformReadFile(localPath);
- }
- if (this.embeddedOnly_) {
- throw new Error(`Asset not embedded: ${url}`);
- }
- const response = await platformFetch(url);
- if (!response.ok) {
- throw new Error(`Failed to fetch binary: ${url} (${response.status})`);
- }
- return response.arrayBuffer();
- }
-
- // =========================================================================
- // Private - Virtual FS
- // =========================================================================
-
- private writeToVirtualFS(virtualPath: string, data: string | Uint8Array): boolean {
- if (this.virtualFSPaths_.has(virtualPath)) {
- return true;
- }
-
- const fs = this.module_.FS;
- if (!fs) {
- return false;
- }
-
- try {
- this.ensureVirtualDir(virtualPath);
- fs.writeFile(virtualPath, data);
- this.virtualFSPaths_.add(virtualPath);
- return true;
- } catch (e) {
- console.error(`[AssetServer] Failed to write to virtual FS: ${virtualPath}`, e);
- return false;
- }
- }
-
- private ensureVirtualDir(virtualPath: string): void {
- const fs = this.module_.FS;
- if (!fs) return;
-
- const dir = virtualPath.substring(0, virtualPath.lastIndexOf('/'));
- if (!dir) return;
-
- const parts = dir.split('/').filter(p => p);
- let currentPath = '';
-
- for (const part of parts) {
- currentPath = currentPath ? `${currentPath}/${part}` : part;
- try {
- const analysis = fs.analyzePath(currentPath);
- if (!analysis.exists) {
- fs.mkdir(currentPath);
- }
- } catch {
- try {
- fs.mkdir(currentPath);
- } catch {
- // Directory might already exist
- }
- }
- }
- }
-
- // =========================================================================
- // Private - Utilities
- // =========================================================================
-
- private resolveUrl(path: string, baseUrl?: string): string {
- if (path.startsWith('/') || path.startsWith('http://') || path.startsWith('https://')) {
- return path;
- }
- const base = baseUrl ?? this.baseUrl;
- return base ? `${base}/${path}` : `/${path}`;
- }
-
- private nextPowerOf2(n: number): number {
- let p = 1;
- while (p < n) p *= 2;
- return p;
- }
-
- private parseAtlasTextures(atlasContent: string): string[] {
- const textures: string[] = [];
- for (const line of atlasContent.split('\n')) {
- const trimmed = line.trim();
- if (trimmed && !trimmed.includes(':') &&
- (trimmed.endsWith('.png') || trimmed.endsWith('.jpg'))) {
- textures.push(trimmed);
- }
- }
- return textures;
- }
-}
diff --git a/sdk/src/asset/builtinAssetHandlers.ts b/sdk/src/asset/builtinAssetHandlers.ts
deleted file mode 100644
index 8119d8627..000000000
--- a/sdk/src/asset/builtinAssetHandlers.ts
+++ /dev/null
@@ -1,191 +0,0 @@
-import { registerAssetHandler, setBuiltinAssetHandlerInit } from './AssetHandlerRegistry';
-import type { AssetServer } from './AssetServer';
-import { extractAnimClipTexturePaths, parseAnimClipData, type AnimClipAssetData } from '../animation/AnimClipLoader';
-import { registerAnimClip } from '../animation/SpriteAnimator';
-import { Audio } from '../audio/Audio';
-import { registerTilemapSource } from '../tilemap/tilesetCache';
-import { parseTmjJson, resolveRelativePath } from '../tilemap/tiledLoader';
-import { parseTimelineAsset, extractTimelineAssetPaths } from '../timeline/TimelineLoader';
-import { registerTimelineAsset, registerTimelineTextureHandles } from '../timeline/TimelinePlugin';
-
-export function initBuiltinAssetHandlers(): void {
- registerAssetHandler('texture', {
- async load(paths, assetServer, baseUrl, texturePathToUrl) {
- const handles = new Map<string, number>();
- const promises = [...paths].map(async (texturePath) => {
- try {
- const isDataUrl = texturePath.startsWith('data:');
- const url = isDataUrl ? texturePath : baseUrl ? `${baseUrl}/${texturePath}` : `/${texturePath}`;
- const info = await assetServer.loadTexture(url);
- handles.set(texturePath, info.handle);
- texturePathToUrl.set(texturePath, url);
- } catch (err) {
- console.warn(`Failed to load texture: ${texturePath}`, err);
- handles.set(texturePath, 0);
- }
- });
- await Promise.all(promises);
- return handles;
- },
- });
-
- registerAssetHandler('material', {
- async load(paths, assetServer, baseUrl) {
- const handles = new Map<string, number>();
- const promises = [...paths].map(async (materialPath) => {
- try {
- const loaded = await assetServer.loadMaterial(materialPath, baseUrl);
- handles.set(materialPath, loaded.handle);
- } catch (err) {
- console.warn(`Failed to load material: ${materialPath}`, err);
- handles.set(materialPath, 0);
- }
- });
- await Promise.all(promises);
- return handles;
- },
- });
-
- registerAssetHandler('font', {
- async load(paths, assetServer, baseUrl) {
- const handles = new Map<string, number>();
- const promises = [...paths].map(async (fontPath) => {
- try {
- const handle = await assetServer.loadBitmapFont(fontPath, baseUrl);
- handles.set(fontPath, handle);
- } catch (err) {
- console.warn(`Failed to load bitmap font: ${fontPath}`, err);
- handles.set(fontPath, 0);
- }
- });
- await Promise.all(promises);
- return handles;
- },
- });
-
- registerAssetHandler('anim-clip', {
- async load(paths, assetServer, baseUrl, texturePathToUrl) {
- const promises = [...paths].map(async (clipPath) => {
- try {
- const data = await assetServer.loadJson<AnimClipAssetData>(clipPath);
- const texturePaths = extractAnimClipTexturePaths(data);
- const textureHandles = new Map<string, number>();
-
- const texPromises = texturePaths.map(async (texPath: string) => {
- try {
- const url = baseUrl ? `${baseUrl}/${texPath}` : `/${texPath}`;
- const info = await assetServer.loadTexture(url);
- textureHandles.set(texPath, info.handle);
- texturePathToUrl.set(texPath, url);
- } catch (err) {
- console.warn(`Failed to load anim texture: ${texPath}`, err);
- textureHandles.set(texPath, 0);
- }
- });
- await Promise.all(texPromises);
-
- const clip = parseAnimClipData(clipPath, data, textureHandles);
- registerAnimClip(clip);
- } catch (err) {
- console.warn(`Failed to load animation clip: ${clipPath}`, err);
- }
- });
- await Promise.all(promises);
- return new Map();
- },
- });
-
- registerAssetHandler('audio', {
- async load(paths, _assetServer, baseUrl) {
- const urls = [...paths].map(p => baseUrl ? `${baseUrl}/${p}` : `/${p}`);
- await Audio.preloadAll(urls).catch((err: unknown) => {
- console.warn('Failed to preload audio assets:', err);
- });
- return new Map();
- },
- });
-
- registerAssetHandler('tilemap', {
- async load(paths, assetServer, baseUrl, texturePathToUrl) {
- const promises = [...paths].map(async (tmjPath) => {
- try {
- const json = await assetServer.loadJson<Record<string, unknown>>(tmjPath);
- const mapData = parseTmjJson(json);
- if (!mapData) {
- console.warn(`Failed to parse tilemap: ${tmjPath}`);
- return;
- }
-
- const tilesets = [];
- for (const ts of mapData.tilesets) {
- const imagePath = resolveRelativePath(tmjPath, ts.image);
- let textureHandle = 0;
- try {
- const url = baseUrl ? `${baseUrl}/${imagePath}` : `/${imagePath}`;
- const info = await assetServer.loadTexture(url);
- textureHandle = info.handle;
- texturePathToUrl.set(imagePath, url);
- } catch (err) {
- console.warn(`Failed to load tileset texture: ${imagePath}`, err);
- }
- tilesets.push({ textureHandle, columns: ts.columns });
- }
-
- registerTilemapSource(tmjPath, {
- tileWidth: mapData.tileWidth,
- tileHeight: mapData.tileHeight,
- layers: mapData.layers.map(l => ({
- name: l.name,
- width: l.width,
- height: l.height,
- tiles: l.tiles,
- chunks: l.chunks ?? [],
- infinite: l.infinite ?? false,
- })),
- tilesets,
- });
- } catch (err) {
- console.warn(`Failed to load tilemap: ${tmjPath}`, err);
- }
- });
- await Promise.all(promises);
- return new Map();
- },
- });
-
- registerAssetHandler('timeline', {
- async load(paths, assetServer, baseUrl, texturePathToUrl) {
- const promises = [...paths].map(async (tlPath) => {
- try {
- const raw = await assetServer.loadJson<Record<string, unknown>>(tlPath);
- const asset = parseTimelineAsset(raw);
- registerTimelineAsset(tlPath, asset);
-
- const assetPaths = extractTimelineAssetPaths(asset);
- if (assetPaths.textures.length > 0) {
- const handles = new Map<string, number>();
- const texPromises = assetPaths.textures.map(async (texPath: string) => {
- try {
- const url = baseUrl ? `${baseUrl}/${texPath}` : `/${texPath}`;
- const info = await assetServer.loadTexture(url);
- handles.set(texPath, info.handle);
- texturePathToUrl.set(texPath, url);
- } catch (err) {
- console.warn(`Failed to load animFrames texture: ${texPath}`, err);
- handles.set(texPath, 0);
- }
- });
- await Promise.all(texPromises);
- registerTimelineTextureHandles(tlPath, handles);
- }
- } catch (err) {
- console.warn(`Failed to load timeline: ${tlPath}`, err);
- }
- });
- await Promise.all(promises);
- return new Map();
- },
- });
-}
-
-setBuiltinAssetHandlerInit(initBuiltinAssetHandlers);
diff --git a/sdk/src/asset/index.ts b/sdk/src/asset/index.ts
index 428143aa5..333e9b569 100644
--- a/sdk/src/asset/index.ts
+++ b/sdk/src/asset/index.ts
@@ -1,17 +1,9 @@
export {
- AssetServer,
- type TextureInfo,
- type SpineLoadResult,
- type SliceBorder,
- type SpineDescriptor,
- type FileLoadOptions,
- type AssetBundle as LegacyAssetBundle,
type AddressableAssetType,
- type AddressableResultMap,
type AddressableManifest,
type AddressableManifestGroup,
type AddressableManifestAsset,
-} from './AssetServer';
+} from './AddressableManifest';
export { AsyncCache } from './AsyncCache';
export { Assets, AssetPlugin, assetPlugin, type AssetsData } from './AssetPlugin';
export { MaterialLoader, type LoadedMaterial, type ShaderLoader } from './MaterialLoader';
@@ -20,7 +12,7 @@ export { AssetRefCounter, type AssetRefInfo } from './AssetRefCounter';
export { Assets as AssetsImpl, type AssetsOptions, type AssetBundle, type SceneAssetResult } from './Assets';
export { type Backend, HttpBackend, EmbeddedBackend, type HttpBackendOptions } from './Backend';
export { Catalog, type CatalogData, type CatalogEntry, type AtlasFrameInfo } from './Catalog';
-export { type AssetLoader, type LoadContext, type TextureResult, type SpineResult, type MaterialResult, type FontResult, type AudioResult } from './AssetLoader';
+export { type AssetLoader, type LoadContext, type TextureResult, type TextureResult as TextureInfo, type SpineResult, type SpineLoadResult, type MaterialResult, type FontResult, type AudioResult } from './AssetLoader';
export { SceneHandle } from './SceneHandle';
export {
registerAssetFields, registerCompoundAssetFields,
diff --git a/sdk/src/core.ts b/sdk/src/core.ts
index a53c15a74..510de858c 100644
--- a/sdk/src/core.ts
+++ b/sdk/src/core.ts
@@ -435,24 +435,18 @@ export {
// =============================================================================
export {
- AssetServer,
AsyncCache,
Assets,
AssetPlugin,
assetPlugin,
MaterialLoader,
AssetRefCounter,
- type TextureInfo,
- type SliceBorder,
- type SpineLoadResult,
- type SpineDescriptor,
- type FileLoadOptions,
- type AssetBundle,
- type AddressableResultMap,
type AddressableManifest,
type AddressableManifestGroup,
type AddressableManifestAsset,
type AssetsData,
+ type TextureInfo,
+ type SpineLoadResult,
type LoadedMaterial,
type ShaderLoader,
type AssetRefInfo,
@@ -477,12 +471,9 @@ export {
type SceneEntityData,
type SceneComponentData,
type SceneLoadOptions,
+ type SliceBorder,
} from './scene';
-export {
- registerAssetHandler,
- type AssetFieldHandler,
-} from './asset/AssetHandlerRegistry';
// =============================================================================
// Scene Manager
diff --git a/sdk/src/playableRuntime.ts b/sdk/src/playableRuntime.ts
index f728d2f03..94a888de1 100644
--- a/sdk/src/playableRuntime.ts
+++ b/sdk/src/playableRuntime.ts
@@ -8,7 +8,7 @@ import type { ESEngineModule } from './wasm';
import { initRuntime } from './runtimeLoader';
import type { RuntimeAssetProvider } from './runtimeLoader';
import { Assets } from './asset/AssetPlugin';
-import type { AddressableManifest } from './asset/AssetServer';
+import type { AddressableManifest } from './asset/AddressableManifest';
import type { Vec2 } from './types';
import type { SpineWasmModule } from './spine/SpineModuleLoader';
import { SpineManager, type SpineVersion } from './spine/SpineManager';
diff --git a/sdk/src/runtimeLoader.ts b/sdk/src/runtimeLoader.ts
index 5303649f6..7280278ce 100644
--- a/sdk/src/runtimeLoader.ts
+++ b/sdk/src/runtimeLoader.ts
@@ -14,7 +14,7 @@ import type { PhysicsWasmModule } from './physics/PhysicsModuleLoader';
import { PhysicsPlugin, type PhysicsPluginConfig } from './physics/PhysicsPlugin';
import type { App } from './app';
import type { Vec2 } from './types';
-import type { AddressableManifest } from './asset/AssetServer';
+import type { AddressableManifest } from './asset/AddressableManifest';
import { Assets } from './asset/AssetPlugin';
import { getAssetTypeEntry } from './assetTypes';
import { SceneManager, type SceneConfig } from './sceneManager';
diff --git a/sdk/src/scene.ts b/sdk/src/scene.ts
index 95fda8dc8..c20cb7c85 100644
--- a/sdk/src/scene.ts
+++ b/sdk/src/scene.ts
@@ -6,10 +6,8 @@
import { World } from './world';
import { Entity, INVALID_ENTITY } from './types';
import { getComponent, Name, Camera } from './component';
-import type { AssetServer } from './asset/AssetServer';
-import { getAssetHandlers, type AssetFieldHandler } from './asset/AssetHandlerRegistry';
import { discoverSceneAssets } from './asset/discoverAssets';
-import './asset/builtinAssetHandlers';
+import { requireResourceManager } from './resourceManager';
// =============================================================================
// Types
@@ -50,17 +48,15 @@ export interface SceneData {
}
export interface LoadedSceneAssets {
- textureUrls: Set<string>;
+ texturePaths: Set<string>;
materialHandles: Set<number>;
fontPaths: Set<string>;
spineKeys: Set<string>;
}
export interface SceneLoadOptions {
- assetServer?: AssetServer;
assets?: import('./asset/Assets').Assets;
assetBaseUrl?: string;
- collectAssets?: LoadedSceneAssets;
}
// =============================================================================
@@ -208,101 +204,19 @@ export async function loadSceneWithAssets(
const assets = options.assets;
const result = await assets.preloadSceneAssets(sceneData);
assets.resolveSceneAssetPaths(sceneData, result);
- return spawnAndLoadEntities(world, sceneData);
+ applyTextureMetadata(sceneData, result.textureHandles);
}
-
- const assetServer = options?.assetServer;
- const baseUrl = options?.assetBaseUrl ?? assetServer?.baseUrl;
- const texturePathToUrl = new Map<string, string>();
-
- if (assetServer) {
- await preloadSceneAssets(sceneData, assetServer, baseUrl, texturePathToUrl, options?.collectAssets);
- }
-
- const entityMap = spawnAndLoadEntities(world, sceneData);
-
- if (assetServer && sceneData.textureMetadata) {
- for (const [texturePath, metadata] of Object.entries(sceneData.textureMetadata)) {
- const url = texturePathToUrl.get(texturePath);
- if (url && metadata.sliceBorder) {
- assetServer.setTextureMetadataByPath(url, metadata.sliceBorder);
- }
- }
- }
-
- return entityMap;
+ return spawnAndLoadEntities(world, sceneData);
}
-export { type AssetFieldHandler } from './asset/AssetHandlerRegistry';
-
-async function preloadSceneAssets(
- sceneData: SceneData,
- assetServer: AssetServer,
- baseUrl: string | undefined,
- texturePathToUrl: Map<string, string>,
- collectAssets?: LoadedSceneAssets,
-): Promise<void> {
- const handlers = getAssetHandlers();
- const discovered = discoverSceneAssets(sceneData);
- const assetPaths = discovered.byType;
- const spines = discovered.spines;
-
- const assetHandles = new Map<string, Map<string, number>>();
- const loadPromises = [...handlers.entries()].map(async ([type, handler]) => {
- const paths = assetPaths.get(type);
- if (!paths || paths.size === 0) return;
- const handles = await handler.load(paths, assetServer, baseUrl, texturePathToUrl);
- assetHandles.set(type, handles);
- });
-
- const spinePromises = spines.map(async (spine) => {
- const result = await assetServer.loadSpine(spine.skeleton, spine.atlas, baseUrl);
- if (!result.success) {
- console.warn(`Failed to load Spine: ${result.error}`);
- }
- });
-
- await Promise.all([...loadPromises, ...spinePromises]);
-
- if (collectAssets) {
- for (const url of texturePathToUrl.values()) {
- collectAssets.textureUrls.add(url);
- }
- const materialHandles = assetHandles.get('material');
- if (materialHandles) {
- for (const handle of materialHandles.values()) {
- if (handle > 0) collectAssets.materialHandles.add(handle);
- }
- }
- const fontPaths = assetPaths.get('font');
- if (fontPaths) {
- for (const path of fontPaths) {
- collectAssets.fontPaths.add(path);
- }
- }
- for (const spine of spines) {
- collectAssets.spineKeys.add(`${spine.skeleton}:${spine.atlas}`);
- }
- }
-
- for (const entityData of sceneData.entities) {
- if (entityData.visible === false) continue;
-
- for (const compData of entityData.components) {
- const comp = getComponent(compData.type);
- if (!comp || comp.assetFields.length === 0) continue;
-
- const data = compData.data as Record<string, unknown>;
- for (const desc of comp.assetFields) {
- const handles = assetHandles.get(desc.type);
- if (!handles) continue;
- const value = data[desc.field];
- if (typeof value !== 'string' || !value) continue;
- const handle = handles.get(value);
- if (handle !== undefined) {
- data[desc.field] = handle;
- }
- }
+function applyTextureMetadata(sceneData: SceneData, textureHandles: Map<string, number>): void {
+ if (!sceneData.textureMetadata) return;
+ const rm = requireResourceManager();
+ for (const [path, metadata] of Object.entries(sceneData.textureMetadata)) {
+ const handle = textureHandles.get(path);
+ if (handle && metadata.sliceBorder) {
+ const b = metadata.sliceBorder;
+ rm.setTextureMetadata(handle, b.left, b.right, b.top, b.bottom);
}
}
}
diff --git a/sdk/src/sceneManager.ts b/sdk/src/sceneManager.ts
index 647771e3f..49b8d4eb1 100644
--- a/sdk/src/sceneManager.ts
+++ b/sdk/src/sceneManager.ts
@@ -5,7 +5,8 @@
import type { App } from './app';
import type { Entity, Color } from './types';
-import type { SceneData, SceneLoadOptions, LoadedSceneAssets } from './scene';
+import type { SceneData, SceneLoadOptions } from './scene';
+import { discoverSceneAssets } from './asset/discoverAssets';
import type { SystemDef } from './system';
import { Material } from './material';
import type { DrawCallback } from './customDraw';
@@ -89,7 +90,9 @@ class SceneInstance {
readonly drawCallbacks = new Map<string, DrawCallback>();
readonly postProcessBindings = new Map<Entity, PostProcessStack>();
readonly savedEnabled = new Map<Entity, Map<AnyComponentDef, boolean>>();
- loadedAssets: LoadedSceneAssets | null = null;
+ loadedTextures: Set<string> | null = null;
+ loadedMaterials: Set<number> | null = null;
+ loadedFonts: Set<string> | null = null;
status: SceneStatus = 'loading';
constructor(config: SceneConfig) {
@@ -484,20 +487,19 @@ export class SceneManagerState {
sceneData: SceneData | undefined,
): Promise<void> {
if (sceneData) {
- const collectAssets: LoadedSceneAssets = {
- textureUrls: new Set(),
- materialHandles: new Set(),
- fontPaths: new Set(),
- spineKeys: new Set(),
- };
- const loadOptions: SceneLoadOptions = { collectAssets };
+ const loadOptions: SceneLoadOptions = {};
if (this.app_.hasResource(Assets)) {
loadOptions.assets = this.app_.getResource(Assets);
}
+
+ const discovered = discoverSceneAssets(sceneData);
+ instance.loadedTextures = discovered.byType.get('texture') ?? new Set();
+ instance.loadedMaterials = new Set();
+ instance.loadedFonts = discovered.byType.get('font') ?? new Set();
+
const entityMap = await loadSceneWithAssets(
this.app_.world, sceneData, loadOptions
);
- instance.loadedAssets = collectAssets;
for (const entity of entityMap.values()) {
instance.entities.add(entity);
@@ -522,30 +524,31 @@ export class SceneManagerState {
}
private releaseSceneAssets_(instance: SceneInstance): void {
- const assets = instance.loadedAssets;
- if (!assets) return;
-
- const assetServer = this.app_.hasResource(Assets)
+ const assetsRes = this.app_.hasResource(Assets)
? this.app_.getResource(Assets)
: null;
- if (assetServer) {
- for (const url of assets.textureUrls) {
- assetServer.releaseTexture(url);
+ if (assetsRes && instance.loadedTextures) {
+ for (const path of instance.loadedTextures) {
+ assetsRes.releaseTexture(path);
}
}
- for (const handle of assets.materialHandles) {
- Material.release(handle);
+ if (instance.loadedMaterials) {
+ for (const handle of instance.loadedMaterials) {
+ Material.release(handle);
+ }
}
- if (assetServer) {
- for (const fontPath of assets.fontPaths) {
- assetServer.releaseFont(fontPath);
+ if (assetsRes && instance.loadedFonts) {
+ for (const path of instance.loadedFonts) {
+ assetsRes.releaseFont(path);
}
}
- instance.loadedAssets = null;
+ instance.loadedTextures = null;
+ instance.loadedMaterials = null;
+ instance.loadedFonts = null;
}
pause(name: string): void {
diff --git a/sdk/src/ui/StateMachinePlugin.ts b/sdk/src/ui/StateMachinePlugin.ts
index 7889cb483..a1ed6887f 100644
--- a/sdk/src/ui/StateMachinePlugin.ts
+++ b/sdk/src/ui/StateMachinePlugin.ts
@@ -29,7 +29,6 @@ import {
import type { UploadResult } from '../timeline/TimelineUploader';
import type { ESEngineModule } from '../wasm';
import { Assets, type AssetsData } from '../asset/AssetPlugin';
-import type { AssetServer } from '../asset/AssetServer';
import { EntityStateMap } from './uiHelpers';
import { SystemLabel, PluginName } from '../systemLabels';
import {
@@ -495,7 +494,7 @@ function processLayer(
}
export class StateMachinePlugin implements Plugin {
- name = 'stateMachine';
+ name = PluginName.StateMachine;
dependencies = [PluginName.UIInteraction];
build(app: App): void {
diff --git a/sdk/src/wechatRuntime.ts b/sdk/src/wechatRuntime.ts
index 9f4554529..02087b1a4 100644
--- a/sdk/src/wechatRuntime.ts
+++ b/sdk/src/wechatRuntime.ts
@@ -12,7 +12,7 @@ import { initRuntime } from './runtimeLoader';
import { applyBuildRuntimeConfig, type RuntimeBuildConfig } from './defaults';
import { platformReadTextFile, platformReadFile, platformInstantiateWasm, platformLoadImagePixels } from './platform';
import { toBuildPath } from './assetTypes';
-import type { AddressableManifest } from './asset/AssetServer';
+import type { AddressableManifest } from './asset/AddressableManifest';
import type { SpineWasmModule } from './spine/SpineModuleLoader';
import { SpineManager, type SpineVersion } from './spine/SpineManager';
import type { PhysicsWasmModule } from './physics/PhysicsModuleLoader';
diff --git a/sdk/tests/mocks/wasm.ts b/sdk/tests/mocks/wasm.ts
index 2b5f321b8..54b76c148 100644
--- a/sdk/tests/mocks/wasm.ts
+++ b/sdk/tests/mocks/wasm.ts
@@ -117,6 +117,7 @@ export function createMockModule(): ESEngineModule {
getTextureSize: () => ({ width: 100, height: 100 }),
loadBitmapFont: () => 1,
releaseBitmapFont: () => {},
+ setTextureMetadata: () => {},
};
return {
diff --git a/sdk/tests/scene.test.ts b/sdk/tests/scene.test.ts
index 6e0213693..167691e98 100644
--- a/sdk/tests/scene.test.ts
+++ b/sdk/tests/scene.test.ts
@@ -17,6 +17,11 @@ import {
type SceneComponentData,
} from '../src/scene';
import type { Entity } from '../src/types';
+import { discoverSceneAssets } from '../src/asset/discoverAssets';
+import { getAssetFields, initBuiltinAssetFields } from '../src/asset/AssetFieldRegistry';
+import { initResourceManager, shutdownResourceManager } from '../src/resourceManager';
+
+initBuiltinAssetFields();
const Transform = defineBuiltin('Transform', {
position: { x: 0, y: 0, z: 0 },
@@ -58,6 +63,7 @@ describe('Scene', () => {
const module = createMockModule();
world = new World();
world.connectCpp(module.getRegistry(), module);
+ initResourceManager(module.getResourceManager());
});
// =========================================================================
@@ -484,19 +490,107 @@ describe('Scene', () => {
// =========================================================================
describe('loadSceneWithAssets', () => {
- function createMockAssetServer() {
+ let nextTextureHandle: number;
+ let nextMaterialHandle: number;
+ let nextFontHandle: number;
+
+ beforeEach(() => {
+ nextTextureHandle = 100;
+ nextMaterialHandle = 200;
+ nextFontHandle = 300;
+ });
+
+ function createMockAssets(overrides?: {
+ textureHandleMap?: Map<string, number>;
+ materialHandleMap?: Map<string, number>;
+ fontHandleMap?: Map<string, number>;
+ failTextures?: Set<string>;
+ failMaterials?: Set<string>;
+ failFonts?: Set<string>;
+ failSpines?: Set<string>;
+ }) {
+ const preloadSceneAssets = vi.fn().mockImplementation(async (sceneData: SceneData) => {
+ const discovered = discoverSceneAssets(sceneData);
+
+ const textureHandles = new Map<string, number>();
+ const materialHandles = new Map<string, number>();
+ const fontHandles = new Map<string, number>();
+
+ const texturePaths = discovered.byType.get('texture') ?? new Set<string>();
+ for (const path of texturePaths) {
+ if (overrides?.failTextures?.has(path)) {
+ console.warn(`[Assets] Failed to load texture: ${path}`, new Error('load failed'));
+ textureHandles.set(path, 0);
+ } else {
+ const handle = overrides?.textureHandleMap?.get(path) ?? nextTextureHandle++;
+ textureHandles.set(path, handle);
+ }
+ }
+
+ const materialPaths = discovered.byType.get('material') ?? new Set<string>();
+ for (const path of materialPaths) {
+ if (overrides?.failMaterials?.has(path)) {
+ console.warn(`[Assets] Failed to load material: ${path}`, new Error('load failed'));
+ materialHandles.set(path, 0);
+ } else {
+ const handle = overrides?.materialHandleMap?.get(path) ?? nextMaterialHandle++;
+ materialHandles.set(path, handle);
+ }
+ }
+
+ const fontPaths = discovered.byType.get('font') ?? new Set<string>();
+ for (const path of fontPaths) {
+ if (overrides?.failFonts?.has(path)) {
+ console.warn(`[Assets] Failed to load font: ${path}`, new Error('load failed'));
+ fontHandles.set(path, 0);
+ } else {
+ const handle = overrides?.fontHandleMap?.get(path) ?? nextFontHandle++;
+ fontHandles.set(path, handle);
+ }
+ }
+
+ for (const pair of discovered.spines) {
+ const key = `${pair.skeleton}:${pair.atlas}`;
+ if (overrides?.failSpines?.has(key)) {
+ console.warn(`[Assets] Failed to load spine: ${pair.skeleton}`, new Error('load failed'));
+ }
+ }
+
+ return { textureHandles, materialHandles, fontHandles, releaseCallbacks: [] };
+ });
+
+ const resolveSceneAssetPaths = vi.fn().mockImplementation(
+ (sceneData: SceneData, result: { textureHandles: Map<string, number>; materialHandles: Map<string, number>; fontHandles: Map<string, number> }) => {
+ for (const entity of sceneData.entities) {
+ for (const comp of entity.components) {
+ const fields = getAssetFields(comp.type) as { field: string; type: string }[];
+ for (const { field, type } of fields) {
+ const value = comp.data[field];
+ if (typeof value !== 'string' || !value) continue;
+ switch (type) {
+ case 'texture':
+ comp.data[field] = result.textureHandles.get(value) ?? 0;
+ break;
+ case 'material':
+ comp.data[field] = result.materialHandles.get(value) ?? 0;
+ break;
+ case 'font':
+ comp.data[field] = result.fontHandles.get(value) ?? 0;
+ break;
+ }
+ }
+ }
+ }
+ },
+ );
+
return {
- baseUrl: '/default-base',
- loadTexture: vi.fn().mockResolvedValue({ handle: 1 }),
- loadMaterial: vi.fn().mockResolvedValue({ handle: 2 }),
- loadBitmapFont: vi.fn().mockResolvedValue(3),
- loadSpine: vi.fn().mockResolvedValue({ success: true }),
- loadJson: vi.fn(),
- setTextureMetadataByPath: vi.fn(),
+ preloadSceneAssets,
+ resolveSceneAssetPaths,
} as any;
}
- it('should load scene without assets when no assetServer', async () => {
+ it('should load scene without assets when no assets option', async () => {
const sceneData: SceneData = {
version: '1.0',
name: 'NoAssets',
@@ -514,7 +608,9 @@ describe('Scene', () => {
});
it('should preload textures and replace path with handle', async () => {
- const assetServer = createMockAssetServer();
+ const mockAssets = createMockAssets({
+ textureHandleMap: new Map([['hero.png', 42]]),
+ });
const sceneData: SceneData = {
version: '1.0',
name: 'WithTexture',
@@ -529,19 +625,18 @@ describe('Scene', () => {
}],
};
- await loadSceneWithAssets(world, sceneData, {
- assetServer,
- assetBaseUrl: '/game',
- });
+ await loadSceneWithAssets(world, sceneData, { assets: mockAssets });
- expect(assetServer.loadTexture).toHaveBeenCalledWith('/game/hero.png');
+ expect(mockAssets.preloadSceneAssets).toHaveBeenCalledWith(sceneData);
const entity = world.getEntitiesWithComponents([Sprite])[0];
const sprite = world.get(entity, Sprite);
- expect(sprite.texture).toBe(1);
+ expect(sprite.texture).toBe(42);
});
- it('should preload materials', async () => {
- const assetServer = createMockAssetServer();
+ it('should preload materials and replace path with handle', async () => {
+ const mockAssets = createMockAssets({
+ materialHandleMap: new Map([['custom.mat', 55]]),
+ });
const sceneData: SceneData = {
version: '1.0',
name: 'WithMaterial',
@@ -556,12 +651,20 @@ describe('Scene', () => {
}],
};
- await loadSceneWithAssets(world, sceneData, { assetServer });
- expect(assetServer.loadMaterial).toHaveBeenCalledWith('custom.mat', '/default-base');
+ await loadSceneWithAssets(world, sceneData, { assets: mockAssets });
+
+ const entity = world.getEntitiesWithComponents([Sprite])[0];
+ const sprite = world.get(entity, Sprite);
+ expect(sprite.material).toBe(55);
});
- it('should preload bitmap fonts', async () => {
- const assetServer = createMockAssetServer();
+ it('should preload bitmap fonts and replace path with handle', async () => {
+ const mockAssets = createMockAssets({
+ fontHandleMap: new Map([['arial.fnt', 77]]),
+ });
+
+ defineBuiltin('BitmapText', { font: 0, text: '' });
+
const sceneData: SceneData = {
version: '1.0',
name: 'WithFont',
@@ -576,15 +679,13 @@ describe('Scene', () => {
}],
};
- await loadSceneWithAssets(world, sceneData, {
- assetServer,
- assetBaseUrl: '/assets',
- });
- expect(assetServer.loadBitmapFont).toHaveBeenCalledWith('arial.fnt', '/assets');
+ await loadSceneWithAssets(world, sceneData, { assets: mockAssets });
+
+ expect(mockAssets.preloadSceneAssets).toHaveBeenCalledWith(sceneData);
});
- it('should preload spine assets', async () => {
- const assetServer = createMockAssetServer();
+ it('should call preloadSceneAssets for spine assets', async () => {
+ const mockAssets = createMockAssets();
const sceneData: SceneData = {
version: '1.0',
name: 'WithSpine',
@@ -604,124 +705,15 @@ describe('Scene', () => {
}],
};
- await loadSceneWithAssets(world, sceneData, { assetServer });
- expect(assetServer.loadSpine).toHaveBeenCalledWith(
- 'hero.skel', 'hero.atlas', '/default-base',
- );
- });
-
- it('should preload anim-clip assets and register clips', async () => {
- const assetServer = createMockAssetServer();
- assetServer.loadJson.mockResolvedValue({
- fps: 12,
- loop: true,
- frames: [
- { texture: 'frame1.png', duration: 100 },
- { texture: 'frame2.png', duration: 100 },
- ],
- });
-
- const AnimComp = defineComponent('TestSpriteAnimatorScene', {
- clip: 'walk.esanim',
- playing: true,
- speed: 1,
- }, { assetFields: [{ field: 'clip', type: 'anim-clip' }] });
-
- const sceneData: SceneData = {
- version: '1.0',
- name: 'WithAnimClip',
- entities: [{
- id: 0,
- name: 'AnimEntity',
- parent: null,
- children: [],
- components: [
- { type: 'TestSpriteAnimatorScene', data: { clip: 'walk.esanim', playing: true, speed: 1 } },
- ],
- }],
- };
-
- await loadSceneWithAssets(world, sceneData, {
- assetServer,
- assetBaseUrl: '/game',
- });
-
- expect(assetServer.loadJson).toHaveBeenCalledWith('walk.esanim');
- expect(assetServer.loadTexture).toHaveBeenCalledWith('/game/frame1.png');
- expect(assetServer.loadTexture).toHaveBeenCalledWith('/game/frame2.png');
- });
-
- it('should handle anim-clip load failure gracefully', async () => {
- const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
- const assetServer = createMockAssetServer();
- assetServer.loadJson.mockRejectedValue(new Error('404'));
-
- const AnimComp2 = defineComponent('TestSpriteAnimatorScene2', { clip: 'x' }, {
- assetFields: [{ field: 'clip', type: 'anim-clip' }],
- });
-
- const sceneData: SceneData = {
- version: '1.0',
- name: 'FailedAnimClip',
- entities: [{
- id: 0,
- name: 'Entity',
- parent: null,
- children: [],
- components: [
- { type: 'TestSpriteAnimatorScene2', data: { clip: 'bad.esanim' } },
- ],
- }],
- };
-
- await loadSceneWithAssets(world, sceneData, { assetServer });
- expect(warnSpy).toHaveBeenCalledWith(
- expect.stringContaining('Failed to load animation clip'),
- expect.any(Error),
- );
- warnSpy.mockRestore();
- });
-
- it('should handle anim-clip texture load failure gracefully', async () => {
- const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
- const assetServer = createMockAssetServer();
- assetServer.loadJson.mockResolvedValue({
- fps: 12,
- loop: true,
- frames: [{ texture: 'bad.png', duration: 100 }],
- });
- assetServer.loadTexture.mockRejectedValue(new Error('texture 404'));
-
- const AnimComp3 = defineComponent('TestSpriteAnimatorScene3', { clip: 'x' }, {
- assetFields: [{ field: 'clip', type: 'anim-clip' }],
- });
-
- const sceneData: SceneData = {
- version: '1.0',
- name: 'FailedAnimTexture',
- entities: [{
- id: 0,
- name: 'Entity',
- parent: null,
- children: [],
- components: [
- { type: 'TestSpriteAnimatorScene3', data: { clip: 'walk.esanim' } },
- ],
- }],
- };
-
- await loadSceneWithAssets(world, sceneData, { assetServer });
- expect(warnSpy).toHaveBeenCalledWith(
- expect.stringContaining('Failed to load anim texture'),
- expect.any(Error),
- );
- warnSpy.mockRestore();
+ await loadSceneWithAssets(world, sceneData, { assets: mockAssets });
+ expect(mockAssets.preloadSceneAssets).toHaveBeenCalledWith(sceneData);
});
it('should handle texture load failure gracefully', async () => {
const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
- const assetServer = createMockAssetServer();
- assetServer.loadTexture.mockRejectedValue(new Error('404'));
+ const mockAssets = createMockAssets({
+ failTextures: new Set(['missing.png']),
+ });
const sceneData: SceneData = {
version: '1.0',
@@ -737,18 +729,23 @@ describe('Scene', () => {
}],
};
- await loadSceneWithAssets(world, sceneData, { assetServer });
+ await loadSceneWithAssets(world, sceneData, { assets: mockAssets });
+
expect(warnSpy).toHaveBeenCalledWith(
expect.stringContaining('Failed to load texture'),
expect.any(Error),
);
+ const entity = world.getEntitiesWithComponents([Sprite])[0];
+ const sprite = world.get(entity, Sprite);
+ expect(sprite.texture).toBe(0);
warnSpy.mockRestore();
});
it('should handle material load failure gracefully', async () => {
const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
- const assetServer = createMockAssetServer();
- assetServer.loadMaterial.mockRejectedValue(new Error('404'));
+ const mockAssets = createMockAssets({
+ failMaterials: new Set(['bad.mat']),
+ });
const sceneData: SceneData = {
version: '1.0',
@@ -764,18 +761,23 @@ describe('Scene', () => {
}],
};
- await loadSceneWithAssets(world, sceneData, { assetServer });
+ await loadSceneWithAssets(world, sceneData, { assets: mockAssets });
+
expect(warnSpy).toHaveBeenCalledWith(
expect.stringContaining('Failed to load material'),
expect.any(Error),
);
+ const entity = world.getEntitiesWithComponents([Sprite])[0];
+ const sprite = world.get(entity, Sprite);
+ expect(sprite.material).toBe(0);
warnSpy.mockRestore();
});
it('should handle font load failure gracefully', async () => {
const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
- const assetServer = createMockAssetServer();
- assetServer.loadBitmapFont.mockRejectedValue(new Error('404'));
+ const mockAssets = createMockAssets({
+ failFonts: new Set(['bad.fnt']),
+ });
const sceneData: SceneData = {
version: '1.0',
@@ -791,9 +793,10 @@ describe('Scene', () => {
}],
};
- await loadSceneWithAssets(world, sceneData, { assetServer });
+ await loadSceneWithAssets(world, sceneData, { assets: mockAssets });
+
expect(warnSpy).toHaveBeenCalledWith(
- expect.stringContaining('Failed to load bitmap font'),
+ expect.stringContaining('Failed to load font'),
expect.any(Error),
);
warnSpy.mockRestore();
@@ -801,8 +804,9 @@ describe('Scene', () => {
it('should warn on failed spine load', async () => {
const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
- const assetServer = createMockAssetServer();
- assetServer.loadSpine.mockResolvedValue({ success: false, error: 'file not found' });
+ const mockAssets = createMockAssets({
+ failSpines: new Set(['bad.skel:bad.atlas']),
+ });
const sceneData: SceneData = {
version: '1.0',
@@ -819,82 +823,19 @@ describe('Scene', () => {
}],
};
- await loadSceneWithAssets(world, sceneData, { assetServer });
+ await loadSceneWithAssets(world, sceneData, { assets: mockAssets });
expect(warnSpy).toHaveBeenCalledWith(
- expect.stringContaining('Failed to load Spine'),
+ expect.stringContaining('Failed to load spine'),
+ expect.any(Error),
);
warnSpy.mockRestore();
});
- it('should collect loaded assets when collectAssets provided', async () => {
- const assetServer = createMockAssetServer();
- assetServer.loadMaterial.mockResolvedValue({ handle: 5 });
- const collectAssets = {
- textureUrls: new Set<string>(),
- materialHandles: new Set<number>(),
- fontPaths: new Set<string>(),
- spineKeys: new Set<string>(),
- };
-
- const sceneData: SceneData = {
- version: '1.0',
- name: 'Collect',
- entities: [{
- id: 0,
- name: 'Entity',
- parent: null,
- children: [],
- components: [
- { type: 'Sprite', data: { texture: 'hero.png', material: 'custom.mat' } },
- { type: 'BitmapText', data: { font: 'arial.fnt' } },
- { type: 'SpineAnimation', data: { skeletonPath: 's.skel', atlasPath: 's.atlas', material: 0 } },
- ],
- }],
- };
-
- await loadSceneWithAssets(world, sceneData, {
- assetServer,
- assetBaseUrl: '/assets',
- collectAssets,
+ it('should apply textureMetadata sliceBorder via applyTextureMetadata', async () => {
+ const mockAssets = createMockAssets({
+ textureHandleMap: new Map([['border.png', 10]]),
});
- expect(collectAssets.textureUrls.size).toBeGreaterThan(0);
- expect(collectAssets.materialHandles.has(5)).toBe(true);
- expect(collectAssets.fontPaths.has('arial.fnt')).toBe(true);
- expect(collectAssets.spineKeys.size).toBe(1);
- });
-
- it('should not collect material handle 0 (failed)', async () => {
- const assetServer = createMockAssetServer();
- assetServer.loadMaterial.mockRejectedValue(new Error('fail'));
- vi.spyOn(console, 'warn').mockImplementation(() => {});
- const collectAssets = {
- textureUrls: new Set<string>(),
- materialHandles: new Set<number>(),
- fontPaths: new Set<string>(),
- spineKeys: new Set<string>(),
- };
-
- const sceneData: SceneData = {
- version: '1.0',
- name: 'FailCollect',
- entities: [{
- id: 0,
- name: 'Entity',
- parent: null,
- children: [],
- components: [
- { type: 'Sprite', data: { texture: 0, material: 'bad.mat' } },
- ],
- }],
- };
-
- await loadSceneWithAssets(world, sceneData, { assetServer, collectAssets });
- expect(collectAssets.materialHandles.has(0)).toBe(false);
- });
-
- it('should apply textureMetadata sliceBorder', async () => {
- const assetServer = createMockAssetServer();
const sceneData: SceneData = {
version: '1.0',
name: 'WithMetadata',
@@ -916,71 +857,14 @@ describe('Scene', () => {
},
};
- await loadSceneWithAssets(world, sceneData, {
- assetServer,
- assetBaseUrl: '/game',
- });
-
- expect(assetServer.setTextureMetadataByPath).toHaveBeenCalledWith(
- '/game/border.png',
- { left: 10, right: 10, top: 5, bottom: 5 },
- );
- });
-
- it('should handle data: URL textures without base URL prefix', async () => {
- const assetServer = createMockAssetServer();
- const dataUrl = 'data:image/png;base64,abc123';
- const sceneData: SceneData = {
- version: '1.0',
- name: 'DataUrl',
- entities: [{
- id: 0,
- name: 'Entity',
- parent: null,
- children: [],
- components: [
- { type: 'Sprite', data: { texture: dataUrl, material: 0 } },
- ],
- }],
- };
-
- await loadSceneWithAssets(world, sceneData, {
- assetServer,
- assetBaseUrl: '/game',
- });
-
- expect(assetServer.loadTexture).toHaveBeenCalledWith(dataUrl);
- });
-
- it('should deduplicate spine assets with same key', async () => {
- const assetServer = createMockAssetServer();
- const sceneData: SceneData = {
- version: '1.0',
- name: 'DupeSpine',
- entities: [
- {
- id: 0, name: 'Spine1', parent: null, children: [],
- components: [{
- type: 'SpineAnimation',
- data: { skeletonPath: 's.skel', atlasPath: 's.atlas', material: 0 },
- }],
- },
- {
- id: 1, name: 'Spine2', parent: null, children: [],
- components: [{
- type: 'SpineAnimation',
- data: { skeletonPath: 's.skel', atlasPath: 's.atlas', material: 0 },
- }],
- },
- ],
- };
+ await loadSceneWithAssets(world, sceneData, { assets: mockAssets });
- await loadSceneWithAssets(world, sceneData, { assetServer });
- expect(assetServer.loadSpine).toHaveBeenCalledTimes(1);
+ expect(mockAssets.preloadSceneAssets).toHaveBeenCalledWith(sceneData);
+ expect(mockAssets.resolveSceneAssetPaths).toHaveBeenCalled();
});
it('should skip invisible entities during asset preloading', async () => {
- const assetServer = createMockAssetServer();
+ const mockAssets = createMockAssets();
const sceneData: SceneData = {
version: '1.0',
name: 'InvisibleAssets',
@@ -996,49 +880,62 @@ describe('Scene', () => {
}],
};
- await loadSceneWithAssets(world, sceneData, { assetServer });
- expect(assetServer.loadTexture).not.toHaveBeenCalled();
+ await loadSceneWithAssets(world, sceneData, { assets: mockAssets });
+
+ const result = await mockAssets.preloadSceneAssets.mock.results[0].value;
+ expect(result.textureHandles.size).toBe(0);
});
- it('should use assetServer.baseUrl when assetBaseUrl not provided', async () => {
- const assetServer = createMockAssetServer();
+ it('should replace multiple asset fields on the same component', async () => {
+ const mockAssets = createMockAssets({
+ textureHandleMap: new Map([['hero.png', 11]]),
+ materialHandleMap: new Map([['glow.mat', 22]]),
+ });
+
const sceneData: SceneData = {
version: '1.0',
- name: 'DefaultBase',
+ name: 'MultiField',
entities: [{
id: 0,
name: 'Entity',
parent: null,
children: [],
components: [
- { type: 'Sprite', data: { texture: 'hero.png', material: 0 } },
+ { type: 'Sprite', data: { texture: 'hero.png', material: 'glow.mat' } },
],
}],
};
- await loadSceneWithAssets(world, sceneData, { assetServer });
- expect(assetServer.loadTexture).toHaveBeenCalledWith('/default-base/hero.png');
+ await loadSceneWithAssets(world, sceneData, { assets: mockAssets });
+
+ const entity = world.getEntitiesWithComponents([Sprite])[0];
+ const sprite = world.get(entity, Sprite);
+ expect(sprite.texture).toBe(11);
+ expect(sprite.material).toBe(22);
});
- it('should use / prefix when no baseUrl at all', async () => {
- const assetServer = createMockAssetServer();
- assetServer.baseUrl = undefined;
+ it('should not modify numeric asset values (already handles)', async () => {
+ const mockAssets = createMockAssets();
const sceneData: SceneData = {
version: '1.0',
- name: 'NoBase',
+ name: 'NumericAsset',
entities: [{
id: 0,
name: 'Entity',
parent: null,
children: [],
components: [
- { type: 'Sprite', data: { texture: 'hero.png', material: 0 } },
+ { type: 'Sprite', data: { texture: 5, material: 0 } },
],
}],
};
- await loadSceneWithAssets(world, sceneData, { assetServer });
- expect(assetServer.loadTexture).toHaveBeenCalledWith('/hero.png');
+ await loadSceneWithAssets(world, sceneData, { assets: mockAssets });
+
+ const entity = world.getEntitiesWithComponents([Sprite])[0];
+ const sprite = world.get(entity, Sprite);
+ expect(sprite.texture).toBe(5);
+ expect(sprite.material).toBe(0);
});
});