A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
refactor: simplify Assets resource to AssetServer directly
esenginea84bbf7f2a14
diff --git a/desktop/public/sdk/cjs/index.wechat.js b/desktop/public/sdk/cjs/index.wechat.jsindex c9b8b5227..ea7ee99fa 100644--- a/desktop/public/sdk/cjs/index.wechat.js+++ b/desktop/public/sdk/cjs/index.wechat.js@@ -2969,6 +2969,194 @@ class MaterialLoader {}}+/**+ * @file scene.ts+ * @brief Scene loading utilities+ */+// =============================================================================+// Scene Loader+// =============================================================================+function loadSceneData(world, sceneData) {+ const entityMap = new Map();+ for (const entityData of sceneData.entities) {+ const entity = world.spawn();+ entityMap.set(entityData.id, entity);+ for (const compData of entityData.components) {+ loadComponent(world, entity, compData);+ }+ }+ // Set parent-child relationships+ for (const entityData of sceneData.entities) {+ if (entityData.parent !== null) {+ const entity = entityMap.get(entityData.id);+ const parentEntity = entityMap.get(entityData.parent);+ if (entity !== undefined && parentEntity !== undefined) {+ world.setParent(entity, parentEntity);+ }+ }+ }+ return entityMap;+}+async function loadSceneWithAssets(world, sceneData, options) {+ const entityMap = new Map();+ const assetServer = options?.assetServer;+ const texturePathToUrl = new Map();+ for (const entityData of sceneData.entities) {+ const entity = world.spawn();+ entityMap.set(entityData.id, entity);+ for (const compData of entityData.components) {+ if (compData.type === 'Sprite' && assetServer) {+ const data = compData.data;+ if (typeof data.texture === 'string' && data.texture) {+ const texturePath = data.texture;+ const isDataUrl = texturePath.startsWith('data:');+ const url = isDataUrl+ ? texturePath+ : options?.assetBaseUrl+ ? `${options.assetBaseUrl}/${texturePath}`+ : `/${texturePath}`;+ try {+ const info = await assetServer.loadTexture(url);+ data.texture = info.handle;+ texturePathToUrl.set(texturePath, url);+ }+ catch (err) {+ console.warn(`Failed to load texture: ${url}`, err);+ data.texture = 0;+ }+ }+ if (typeof data.material === 'string' && data.material) {+ try {+ const loaded = await assetServer.loadMaterial(data.material, options?.assetBaseUrl);+ data.material = loaded.handle;+ }+ catch (err) {+ console.warn(`Failed to load material: ${data.material}`, err);+ data.material = 0;+ }+ }+ }+ if (compData.type === 'SpineAnimation' && assetServer) {+ const data = compData.data;+ const skeletonPath = data.skeletonPath;+ const atlasPath = data.atlasPath;+ if (skeletonPath && atlasPath) {+ const result = await assetServer.loadSpine(skeletonPath, atlasPath, options?.assetBaseUrl);+ if (!result.success) {+ console.warn(`Failed to load Spine: ${result.error}`);+ }+ }+ if (typeof data.material === 'string' && data.material) {+ try {+ const loaded = await assetServer.loadMaterial(data.material, options?.assetBaseUrl);+ data.material = loaded.handle;+ }+ catch (err) {+ console.warn(`Failed to load material: ${data.material}`, err);+ data.material = 0;+ }+ }+ }+ loadComponent(world, entity, compData);+ }+ }+ for (const entityData of sceneData.entities) {+ if (entityData.parent !== null) {+ const entity = entityMap.get(entityData.id);+ const parentEntity = entityMap.get(entityData.parent);+ if (entity !== undefined && parentEntity !== undefined) {+ world.setParent(entity, parentEntity);+ }+ }+ }+ 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;+}+function loadComponent(world, entity, compData) {+ const data = compData.data;+ switch (compData.type) {+ case 'LocalTransform':+ world.insert(entity, LocalTransform, data);+ break;+ case 'Sprite':+ world.insert(entity, Sprite, data);+ break;+ case 'Camera':+ world.insert(entity, Camera, data);+ break;+ case 'Canvas':+ world.insert(entity, Canvas, data);+ break;+ case 'Text':+ world.insert(entity, Text, data);+ break;+ case 'SpineAnimation':+ world.insert(entity, SpineAnimation, data);+ break;+ default:+ console.warn(`Unknown component type: ${compData.type}`);+ }+}+function updateCameraAspectRatio(world, aspectRatio) {+ const cameraEntities = world.getEntitiesWithComponents([Camera]);+ for (const entity of cameraEntities) {+ const camera = world.get(entity, Camera);+ if (camera) {+ camera.aspectRatio = aspectRatio;+ world.insert(entity, Camera, camera);+ }+ }+}++class AsyncCache {+ constructor() {+ this.cache_ = new Map();+ this.pending_ = new Map();+ }+ async getOrLoad(key, loader) {+ const cached = this.cache_.get(key);+ if (cached !== undefined) {+ return cached;+ }+ const pending = this.pending_.get(key);+ if (pending) {+ return pending;+ }+ const promise = loader();+ this.pending_.set(key, promise);+ try {+ const result = await promise;+ this.cache_.set(key, result);+ return result;+ }+ finally {+ this.pending_.delete(key);+ }+ }+ get(key) {+ return this.cache_.get(key);+ }+ has(key) {+ return this.cache_.has(key);+ }+ delete(key) {+ return this.cache_.delete(key);+ }+ clear() {+ this.cache_.clear();+ }+ values() {+ return this.cache_.values();+ }+}+/*** @file AssetServer.ts* @brief Asset loading and caching system@@ -2978,24 +3166,16 @@ class MaterialLoader {// =============================================================================class AssetServer {constructor(module) {- this.cache_ = new Map();- this.pending_ = new Map();- this.loadedSpines_ = new Map();+ this.textureCache_ = new AsyncCache();+ this.shaderCache_ = new AsyncCache();+ this.jsonCache_ = new AsyncCache();+ this.textCache_ = new AsyncCache();+ this.binaryCache_ = new AsyncCache();+ this.loadedSpines_ = new Set();this.virtualFSPaths_ = new Set();- this.materialLoader_ = null;- this.shaderCache_ = new Map();- this.shaderPending_ = new Map();this.module_ = module;- if (typeof OffscreenCanvas !== 'undefined') {- this.canvas_ = new OffscreenCanvas(512, 512);- this.ctx_ = this.canvas_.getContext('2d', { willReadFrequently: true });- }- else {- this.canvas_ = document.createElement('canvas');- this.canvas_.width = 512;- this.canvas_.height = 512;- this.ctx_ = this.canvas_.getContext('2d', { willReadFrequently: true });- }+ this.canvas_ = this.createCanvas(512, 512);+ this.ctx_ = this.canvas_.getContext('2d', { willReadFrequently: true });const shaderLoader = {load: (path) => this.loadShader(path),get: (path) => this.shaderCache_.get(path),@@ -3003,7 +3183,7 @@ class AssetServer {this.materialLoader_ = new MaterialLoader(shaderLoader);}// =========================================================================- // Public API+ // Texture// =========================================================================/*** Load texture with vertical flip (for Sprite/UI).@@ -3020,54 +3200,54 @@ class AssetServer {return this.loadTextureWithFlip(source, false);}getTexture(source) {- return this.cache_.get(this.getCacheKey(source, true));+ return this.textureCache_.get(this.textureCacheKey(source, true));}hasTexture(source) {- return this.cache_.has(this.getCacheKey(source, true));+ return this.textureCache_.has(this.textureCacheKey(source, true));}releaseTexture(source) {const rm = this.module_.getResourceManager();for (const flip of [true, false]) {- const key = this.getCacheKey(source, flip);- const info = this.cache_.get(key);+ const key = this.textureCacheKey(source, flip);+ const info = this.textureCache_.get(key);if (info) {rm.releaseTexture(info.handle);- this.cache_.delete(key);+ this.textureCache_.delete(key);}}}releaseAll() {const rm = this.module_.getResourceManager();- for (const info of this.cache_.values()) {+ for (const info of this.textureCache_.values()) {rm.releaseTexture(info.handle);}- this.cache_.clear();+ this.textureCache_.clear();+ this.jsonCache_.clear();+ this.textCache_.clear();+ this.binaryCache_.clear();}setTextureMetadata(handle, border) {const rm = this.module_.getResourceManager();rm.setTextureMetadata(handle, border.left, border.right, border.top, border.bottom);}setTextureMetadataByPath(source, border) {- const info = this.cache_.get(this.getCacheKey(source, true));+ const info = this.textureCache_.get(this.textureCacheKey(source, true));if (info) {this.setTextureMetadata(info.handle, border);return true;}return false;}+ // =========================================================================+ // Spine+ // =========================================================================async loadSpine(skeletonPath, atlasPath, baseUrl) {const cacheKey = `${skeletonPath}:${atlasPath}`;- if (this.loadedSpines_.get(cacheKey)) {+ if (this.loadedSpines_.has(cacheKey)) {return { success: true };}- const resolveUrl = (path) => {- if (path.startsWith('http://') || path.startsWith('https://') || path.startsWith('/')) {- return path;- }- return baseUrl ? `${baseUrl}/${path}` : `/${path}`;- };try {- const atlasUrl = resolveUrl(atlasPath);+ const atlasUrl = this.resolveUrl(atlasPath, baseUrl);const atlasResponse = await fetch(atlasUrl);if (!atlasResponse.ok) {return { success: false, error: `Failed to fetch atlas: ${atlasUrl}` };@@ -3080,7 +3260,7 @@ class AssetServer {const textureNames = this.parseAtlasTextures(atlasContent);for (const texName of textureNames) {const texPath = atlasDir ? `${atlasDir}/${texName}` : texName;- const texUrl = resolveUrl(texPath);+ const texUrl = this.resolveUrl(texPath, baseUrl);try {const info = await this.loadTextureRaw(texUrl);const rm = this.module_.getResourceManager();@@ -3090,7 +3270,7 @@ class AssetServer {console.warn(`[AssetServer] Failed to load Spine texture: ${texPath}`, err);}}- const skelUrl = resolveUrl(skeletonPath);+ const skelUrl = this.resolveUrl(skeletonPath, baseUrl);const skelResponse = await fetch(skelUrl);if (!skelResponse.ok) {return { success: false, error: `Failed to fetch skeleton: ${skelUrl}` };@@ -3102,7 +3282,7 @@ class AssetServer {if (!this.writeToVirtualFS(skeletonPath, skelData)) {return { success: false, error: `Failed to write skeleton to virtual FS: ${skeletonPath}` };}- this.loadedSpines_.set(cacheKey, true);+ this.loadedSpines_.add(cacheKey);return { success: true };}catch (err) {@@ -3110,105 +3290,108 @@ class AssetServer {}}isSpineLoaded(skeletonPath, atlasPath) {- return this.loadedSpines_.get(`${skeletonPath}:${atlasPath}`) ?? false;+ return this.loadedSpines_.has(`${skeletonPath}:${atlasPath}`);}+ // =========================================================================+ // Material & Shader+ // =========================================================================async loadMaterial(path, baseUrl) {- if (!this.materialLoader_) {- throw new Error('MaterialLoader not initialized');- }- const fullPath = this.resolveAssetPath(path, baseUrl);- return this.materialLoader_.load(fullPath);+ return this.materialLoader_.load(this.resolveUrl(path, baseUrl));}getMaterial(path, baseUrl) {- if (!this.materialLoader_)- return undefined;- const fullPath = this.resolveAssetPath(path, baseUrl);- return this.materialLoader_.get(fullPath);+ return this.materialLoader_.get(this.resolveUrl(path, baseUrl));}hasMaterial(path, baseUrl) {- if (!this.materialLoader_)- return false;- const fullPath = this.resolveAssetPath(path, baseUrl);- return this.materialLoader_.has(fullPath);+ return this.materialLoader_.has(this.resolveUrl(path, baseUrl));}async loadShader(path) {- const cached = this.shaderCache_.get(path);- if (cached)- return cached;- const pending = this.shaderPending_.get(path);- if (pending)- return pending;- const promise = this.loadShaderInternal(path);- this.shaderPending_.set(path, promise);- try {- const handle = await promise;- this.shaderCache_.set(path, handle);- return handle;+ return this.shaderCache_.getOrLoad(path, () => this.loadShaderInternal(path));+ }+ // =========================================================================+ // Generic File Loading+ // =========================================================================+ async loadJson(path, options) {+ const url = this.resolveUrl(path, options?.baseUrl);+ if (options?.noCache) {+ return this.fetchJson(url);}- finally {- this.shaderPending_.delete(path);+ return this.jsonCache_.getOrLoad(url, () => this.fetchJson(url));+ }+ async loadText(path, options) {+ const url = this.resolveUrl(path, options?.baseUrl);+ if (options?.noCache) {+ return this.fetchText(url);}+ return this.textCache_.getOrLoad(url, () => this.fetchText(url));}- async loadShaderInternal(path) {- const exists = await platformFileExists(path);- if (!exists) {- throw new Error(`Shader file not found: ${path}`);+ async loadBinary(path, options) {+ const url = this.resolveUrl(path, options?.baseUrl);+ if (options?.noCache) {+ return this.fetchBinary(url);}- const content = await platformReadTextFile(path);- if (!content) {- throw new Error(`Failed to read shader file: ${path}`);+ return this.binaryCache_.getOrLoad(url, () => this.fetchBinary(url));+ }+ // =========================================================================+ // Scene & Batch+ // =========================================================================+ async loadScene(world, sceneData) {+ return loadSceneWithAssets(world, sceneData, { assetServer: this });+ }+ async loadAll(manifest) {+ const bundle = {+ textures: new Map(),+ materials: new Map(),+ spine: new Map(),+ json: new Map(),+ text: new Map(),+ binary: new Map(),+ };+ const promises = [];+ if (manifest.textures) {+ for (const path of manifest.textures) {+ promises.push(this.loadTexture(path).then(info => { bundle.textures.set(path, info); }));+ }}- const { vertex, fragment } = this.parseEsShader(content);- if (!vertex || !fragment) {- throw new Error(`Invalid shader format: ${path}`);+ if (manifest.materials) {+ for (const path of manifest.materials) {+ promises.push(this.loadMaterial(path).then(mat => { bundle.materials.set(path, mat); }));+ }}- return Material.createShader(vertex, fragment);- }- parseEsShader(content) {- let vertex = null;- let fragment = 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/);- if (vertexMatch) {- vertex = vertexMatch[1].trim();+ if (manifest.spine) {+ for (const desc of manifest.spine) {+ const key = `${desc.skeleton}:${desc.atlas}`;+ promises.push(this.loadSpine(desc.skeleton, desc.atlas, desc.baseUrl).then(result => {+ bundle.spine.set(key, result);+ }));+ }+ }+ if (manifest.json) {+ for (const path of manifest.json) {+ promises.push(this.loadJson(path).then(data => { bundle.json.set(path, data); }));+ }}- if (fragmentMatch) {- fragment = fragmentMatch[1].trim();+ if (manifest.text) {+ for (const path of manifest.text) {+ promises.push(this.loadText(path).then(data => { bundle.text.set(path, data); }));+ }}- return { vertex, fragment };- }- resolveAssetPath(path, baseUrl) {- if (path.startsWith('/') || path.startsWith('http')) {- return path;+ if (manifest.binary) {+ for (const path of manifest.binary) {+ promises.push(this.loadBinary(path).then(data => { bundle.binary.set(path, data); }));+ }}- return baseUrl ? `${baseUrl}/${path}` : `/${path}`;+ await Promise.all(promises);+ return bundle;}// =========================================================================- // Private Methods+ // Private - Texture// =========================================================================- getCacheKey(source, flip) {+ textureCacheKey(source, flip) {return `${source}:${flip ? 'f' : 'n'}`;}async loadTextureWithFlip(source, flip) {- const cacheKey = this.getCacheKey(source, flip);- const cached = this.cache_.get(cacheKey);- if (cached) {- return cached;- }- const pending = this.pending_.get(cacheKey);- if (pending) {- return pending;- }- const promise = this.loadTextureInternal(source, flip);- this.pending_.set(cacheKey, promise);- try {- const result = await promise;- this.cache_.set(cacheKey, result);- return result;- }- finally {- this.pending_.delete(cacheKey);- }+ const cacheKey = this.textureCacheKey(source, flip);+ return this.textureCache_.getOrLoad(cacheKey, () => this.loadTextureInternal(source, flip));}async loadTextureInternal(source, flip) {const img = await this.loadImage(source);@@ -3273,12 +3456,59 @@ class AssetServer {}}}- nextPowerOf2(n) {- let p = 1;- while (p < n)- p *= 2;- return p;+ // =========================================================================+ // Private - Shader+ // =========================================================================+ async loadShaderInternal(path) {+ const exists = await platformFileExists(path);+ if (!exists) {+ throw new Error(`Shader file not found: ${path}`);+ }+ const content = await platformReadTextFile(path);+ 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);+ }+ parseEsShader(content) {+ 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+ // =========================================================================+ async fetchJson(url) {+ const response = await platformFetch(url);+ if (!response.ok) {+ throw new Error(`Failed to fetch JSON: ${url} (${response.status})`);+ }+ return response.json();+ }+ async fetchText(url) {+ const response = await platformFetch(url);+ if (!response.ok) {+ throw new Error(`Failed to fetch text: ${url} (${response.status})`);+ }+ return response.text();+ }+ async fetchBinary(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+ // =========================================================================writeToVirtualFS(virtualPath, data) {if (this.virtualFSPaths_.has(virtualPath)) {return true;@@ -3325,10 +3555,33 @@ class AssetServer {}}}+ // =========================================================================+ // Private - Utilities+ // =========================================================================+ resolveUrl(path, baseUrl) {+ if (path.startsWith('/') || path.startsWith('http://') || path.startsWith('https://')) {+ return path;+ }+ const base = baseUrl ?? this.baseUrl;+ return base ? `${base}/${path}` : `/${path}`;+ }+ createCanvas(width, height) {+ const canvas = typeof OffscreenCanvas !== 'undefined'+ ? new OffscreenCanvas(width, height)+ : document.createElement('canvas');+ canvas.width = width;+ canvas.height = height;+ return canvas;+ }+ nextPowerOf2(n) {+ let p = 1;+ while (p < n)+ p *= 2;+ return p;+ }parseAtlasTextures(atlasContent) {const textures = [];- const lines = atlasContent.split('\n');- for (const line of lines) {+ for (const line of atlasContent.split('\n')) {const trimmed = line.trim();if (trimmed && !trimmed.includes(':') &&(trimmed.endsWith('.png') || trimmed.endsWith('.jpg'))) {@@ -3343,7 +3596,7 @@ class AssetServer {* @file AssetPlugin.ts* @brief Plugin that provides asset loading capabilities*/-const Assets = defineResource({ server: null }, 'Assets');+const Assets = defineResource(null, 'Assets');// =============================================================================// Asset Plugin// =============================================================================@@ -3354,158 +3607,11 @@ class AssetPlugin {console.warn('AssetPlugin: No WASM module available');return;}- const server = new AssetServer(module);- app.insertResource(Assets, { server });+ app.insertResource(Assets, new AssetServer(module));}}const assetPlugin = new AssetPlugin();-/**- * @file scene.ts- * @brief Scene loading utilities- */-// =============================================================================-// Scene Loader-// =============================================================================-function loadSceneData(world, sceneData) {- const entityMap = new Map();- for (const entityData of sceneData.entities) {- const entity = world.spawn();- entityMap.set(entityData.id, entity);- for (const compData of entityData.components) {- loadComponent(world, entity, compData);- }- }- // Set parent-child relationships- for (const entityData of sceneData.entities) {- if (entityData.parent !== null) {- const entity = entityMap.get(entityData.id);- const parentEntity = entityMap.get(entityData.parent);- if (entity !== undefined && parentEntity !== undefined) {- world.setParent(entity, parentEntity);- }- }- }- return entityMap;-}-async function loadSceneWithAssets(world, sceneData, options) {- const entityMap = new Map();- const assetServer = options?.assetServer;- const texturePathToUrl = new Map();- for (const entityData of sceneData.entities) {- const entity = world.spawn();- entityMap.set(entityData.id, entity);- for (const compData of entityData.components) {- if (compData.type === 'Sprite' && assetServer) {- const data = compData.data;- if (typeof data.texture === 'string' && data.texture) {- const texturePath = data.texture;- const isDataUrl = texturePath.startsWith('data:');- const url = isDataUrl- ? texturePath- : options?.assetBaseUrl- ? `${options.assetBaseUrl}/${texturePath}`- : `/${texturePath}`;- try {- const info = await assetServer.loadTexture(url);- data.texture = info.handle;- texturePathToUrl.set(texturePath, url);- }- catch (err) {- console.warn(`Failed to load texture: ${url}`, err);- data.texture = 0;- }- }- if (typeof data.material === 'string' && data.material) {- try {- const loaded = await assetServer.loadMaterial(data.material, options?.assetBaseUrl);- data.material = loaded.handle;- }- catch (err) {- console.warn(`Failed to load material: ${data.material}`, err);- data.material = 0;- }- }- }- if (compData.type === 'SpineAnimation' && assetServer) {- const data = compData.data;- const skeletonPath = data.skeletonPath;- const atlasPath = data.atlasPath;- if (skeletonPath && atlasPath) {- const result = await assetServer.loadSpine(skeletonPath, atlasPath, options?.assetBaseUrl);- if (!result.success) {- console.warn(`Failed to load Spine: ${result.error}`);- }- }- if (typeof data.material === 'string' && data.material) {- try {- const loaded = await assetServer.loadMaterial(data.material, options?.assetBaseUrl);- data.material = loaded.handle;- }- catch (err) {- console.warn(`Failed to load material: ${data.material}`, err);- data.material = 0;- }- }- }- loadComponent(world, entity, compData);- }- }- for (const entityData of sceneData.entities) {- if (entityData.parent !== null) {- const entity = entityMap.get(entityData.id);- const parentEntity = entityMap.get(entityData.parent);- if (entity !== undefined && parentEntity !== undefined) {- world.setParent(entity, parentEntity);- }- }- }- 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;-}-function loadComponent(world, entity, compData) {- const data = compData.data;- switch (compData.type) {- case 'LocalTransform':- world.insert(entity, LocalTransform, data);- break;- case 'Sprite':- world.insert(entity, Sprite, data);- break;- case 'Camera':- world.insert(entity, Camera, data);- break;- case 'Canvas':- world.insert(entity, Canvas, data);- break;- case 'Text':- world.insert(entity, Text, data);- break;- case 'SpineAnimation':- world.insert(entity, SpineAnimation, data);- break;- default:- console.warn(`Unknown component type: ${compData.type}`);- }-}-function updateCameraAspectRatio(world, aspectRatio) {- const cameraEntities = world.getEntitiesWithComponents([Camera]);- for (const entity of cameraEntities) {- const camera = world.get(entity, Camera);- if (camera) {- camera.aspectRatio = aspectRatio;- world.insert(entity, Camera, camera);- }- }-}-/*** @file PreviewPlugin.ts* @brief Plugin for editor preview functionality@@ -3544,9 +3650,7 @@ class PreviewPlugin {}const sceneData = await response.json();const assets = this.app_.getResource(Assets);- await loadSceneWithAssets(this.app_.world, sceneData, {- assetServer: assets.server- });+ await assets.loadScene(this.app_.world, sceneData);this.ensureCamera();}catch (err) {@@ -3900,5 +4004,5 @@ function createSpineController(wasmModule) {initWeChatPlatform();setPlatform(wechatAdapter);-export { App, AssetPlugin, AssetServer, Assets, BlendMode, Camera, Canvas, Children, Commands, CommandsInstance, DataType, Draw, EntityCommands, Geometry, INVALID_ENTITY, INVALID_TEXTURE, Input, LocalTransform, Material, MaterialLoader, Mut, Parent, PostProcess, PreviewPlugin, Query, QueryInstance, RenderStage, Renderer, Res, ResMut, Schedule, ShaderSources, SpineAnimation, SpineController, Sprite, SystemRunner, Text, TextAlign, TextOverflow, TextPlugin, TextRenderer, TextVerticalAlign, Time, UIRect, Velocity, World, WorldTransform, assetPlugin, color, createSpineController, createWebApp, defineComponent, defineResource, defineSystem, defineTag, getComponentDefaults, getPlatform, getPlatformType, initDrawAPI, initGeometryAPI, initMaterialAPI, initPostProcessAPI, initRendererAPI, isBuiltinComponent, isPlatformInitialized, isWeChat, isWeb, loadComponent, loadSceneData, loadSceneWithAssets, platformFetch, platformFileExists, platformInstantiateWasm, platformReadFile, platformReadTextFile, quat, registerMaterialCallback, shutdownDrawAPI, shutdownGeometryAPI, shutdownMaterialAPI, shutdownPostProcessAPI, shutdownRendererAPI, textPlugin, updateCameraAspectRatio, vec2, vec3, vec4, wxFileExists, wxFileExistsSync, wxGetImagePixels, wxLoadImage, wxLoadImagePixels, wxReadFile, wxReadTextFile, wxWriteFile };+export { App, AssetPlugin, AssetServer, Assets, AsyncCache, BlendMode, Camera, Canvas, Children, Commands, CommandsInstance, DataType, Draw, EntityCommands, Geometry, INVALID_ENTITY, INVALID_TEXTURE, Input, LocalTransform, Material, MaterialLoader, Mut, Parent, PostProcess, PreviewPlugin, Query, QueryInstance, RenderStage, Renderer, Res, ResMut, Schedule, ShaderSources, SpineAnimation, SpineController, Sprite, SystemRunner, Text, TextAlign, TextOverflow, TextPlugin, TextRenderer, TextVerticalAlign, Time, UIRect, Velocity, World, WorldTransform, assetPlugin, color, createSpineController, createWebApp, defineComponent, defineResource, defineSystem, defineTag, getComponentDefaults, getPlatform, getPlatformType, initDrawAPI, initGeometryAPI, initMaterialAPI, initPostProcessAPI, initRendererAPI, isBuiltinComponent, isPlatformInitialized, isWeChat, isWeb, loadComponent, loadSceneData, loadSceneWithAssets, platformFetch, platformFileExists, platformInstantiateWasm, platformReadFile, platformReadTextFile, quat, registerMaterialCallback, shutdownDrawAPI, shutdownGeometryAPI, shutdownMaterialAPI, shutdownPostProcessAPI, shutdownRendererAPI, textPlugin, updateCameraAspectRatio, vec2, vec3, vec4, wxFileExists, wxFileExistsSync, wxGetImagePixels, wxLoadImage, wxLoadImagePixels, wxReadFile, wxReadTextFile, wxWriteFile };//# sourceMappingURL=index.wechat.js.mapdiff --git a/desktop/public/sdk/esm/esengine.d.ts b/desktop/public/sdk/esm/esengine.d.tsindex 0331366fa..02162a20a 100644--- a/desktop/public/sdk/esm/esengine.d.ts+++ b/desktop/public/sdk/esm/esengine.d.ts@@ -821,6 +821,48 @@ declare class MaterialLoader {private resolveShaderPath;}+/**+ * @file scene.ts+ * @brief Scene loading utilities+ */++interface SceneEntityData {+ id: number;+ name: string;+ parent: number | null;+ children: number[];+ components: SceneComponentData[];+}+interface SceneComponentData {+ type: string;+ data: Record<string, unknown>;+}+interface SliceBorder$1 {+ left: number;+ right: number;+ top: number;+ bottom: number;+}+interface TextureMetadata {+ version: string;+ type: 'texture';+ sliceBorder: SliceBorder$1;+}+interface SceneData {+ version: string;+ name: string;+ entities: SceneEntityData[];+ textureMetadata?: Record<string, TextureMetadata>;+}+interface SceneLoadOptions {+ assetServer?: AssetServer;+ assetBaseUrl?: string;+}+declare function loadSceneData(world: World, sceneData: SceneData): Map<number, Entity>;+declare function loadSceneWithAssets(world: World, sceneData: SceneData, options?: SceneLoadOptions): Promise<Map<number, Entity>>;+declare function loadComponent(world: World, entity: Entity, compData: SceneComponentData): void;+declare function updateCameraAspectRatio(world: World, aspectRatio: number): void;+/*** @file AssetServer.ts* @brief Asset loading and caching system@@ -831,7 +873,7 @@ interface TextureInfo {width: number;height: number;}-interface SliceBorder$1 {+interface SliceBorder {left: number;right: number;top: number;@@ -841,17 +883,44 @@ interface SpineLoadResult {success: boolean;error?: string;}+interface SpineDescriptor {+ skeleton: string;+ atlas: string;+ baseUrl?: string;+}+interface FileLoadOptions {+ baseUrl?: string;+ noCache?: boolean;+}+interface AssetManifest {+ textures?: string[];+ materials?: string[];+ spine?: SpineDescriptor[];+ json?: string[];+ text?: string[];+ binary?: string[];+}+interface AssetBundle {+ textures: Map<string, TextureInfo>;+ materials: Map<string, LoadedMaterial>;+ spine: Map<string, SpineLoadResult>;+ json: Map<string, unknown>;+ text: Map<string, string>;+ binary: Map<string, ArrayBuffer>;+}declare class AssetServer {+ baseUrl?: string;private module_;- private cache_;- private pending_;- private canvas_;- private ctx_;+ private textureCache_;+ private shaderCache_;+ private jsonCache_;+ private textCache_;+ private binaryCache_;private loadedSpines_;private virtualFSPaths_;private materialLoader_;- private shaderCache_;- private shaderPending_;+ private canvas_;+ private ctx_;constructor(module: ESEngineModule);/*** Load texture with vertical flip (for Sprite/UI).@@ -867,80 +936,56 @@ declare class AssetServer {hasTexture(source: string): boolean;releaseTexture(source: string): void;releaseAll(): void;- setTextureMetadata(handle: TextureHandle, border: SliceBorder$1): void;- setTextureMetadataByPath(source: string, border: SliceBorder$1): boolean;+ setTextureMetadata(handle: TextureHandle, border: SliceBorder): void;+ setTextureMetadataByPath(source: string, border: SliceBorder): boolean;loadSpine(skeletonPath: string, atlasPath: string, baseUrl?: string): Promise<SpineLoadResult>;isSpineLoaded(skeletonPath: string, atlasPath: string): boolean;loadMaterial(path: string, baseUrl?: string): Promise<LoadedMaterial>;getMaterial(path: string, baseUrl?: string): LoadedMaterial | undefined;hasMaterial(path: string, baseUrl?: string): boolean;loadShader(path: string): Promise<ShaderHandle>;- private loadShaderInternal;- private parseEsShader;- private resolveAssetPath;- private getCacheKey;+ loadJson<T = unknown>(path: string, options?: FileLoadOptions): Promise<T>;+ loadText(path: string, options?: FileLoadOptions): Promise<string>;+ loadBinary(path: string, options?: FileLoadOptions): Promise<ArrayBuffer>;+ loadScene(world: World, sceneData: SceneData): Promise<Map<number, Entity>>;+ loadAll(manifest: AssetManifest): Promise<AssetBundle>;+ private textureCacheKey;private loadTextureWithFlip;private loadTextureInternal;private loadImage;private createTextureFromImage;private unpremultiplyAlpha;- private nextPowerOf2;+ private loadShaderInternal;+ private parseEsShader;+ private fetchJson;+ private fetchText;+ private fetchBinary;private writeToVirtualFS;private ensureVirtualDir;+ private resolveUrl;+ private createCanvas;+ private nextPowerOf2;private parseAtlasTextures;}-interface AssetsData {- server: AssetServer;+declare class AsyncCache<T> {+ private cache_;+ private pending_;+ getOrLoad(key: string, loader: () => Promise<T>): Promise<T>;+ get(key: string): T | undefined;+ has(key: string): boolean;+ delete(key: string): boolean;+ clear(): void;+ values(): IterableIterator<T>;}-declare const Assets: ResourceDef<AssetsData>;++type AssetsData = AssetServer;+declare const Assets: ResourceDef<AssetServer>;declare class AssetPlugin implements Plugin {build(app: App): void;}declare const assetPlugin: AssetPlugin;-/**- * @file scene.ts- * @brief Scene loading utilities- */--interface SceneEntityData {- id: number;- name: string;- parent: number | null;- children: number[];- components: SceneComponentData[];-}-interface SceneComponentData {- type: string;- data: Record<string, unknown>;-}-interface SliceBorder {- left: number;- right: number;- top: number;- bottom: number;-}-interface TextureMetadata {- version: string;- type: 'texture';- sliceBorder: SliceBorder;-}-interface SceneData {- version: string;- name: string;- entities: SceneEntityData[];- textureMetadata?: Record<string, TextureMetadata>;-}-interface SceneLoadOptions {- assetServer?: AssetServer;- assetBaseUrl?: string;-}-declare function loadSceneData(world: World, sceneData: SceneData): Map<number, Entity>;-declare function loadSceneWithAssets(world: World, sceneData: SceneData, options?: SceneLoadOptions): Promise<Map<number, Entity>>;-declare function loadComponent(world: World, entity: Entity, compData: SceneComponentData): void;-declare function updateCameraAspectRatio(world: World, aspectRatio: number): void;-/*** @file PreviewPlugin.ts* @brief Plugin for editor preview functionality@@ -1597,5 +1642,5 @@ declare const Renderer: {getStats(): RenderStats;};-export { App, AssetPlugin, AssetServer, Assets, BlendMode, Camera, Canvas, Children, Commands, CommandsInstance, DataType, Draw, EntityCommands, Geometry, INVALID_ENTITY, INVALID_TEXTURE, Input, LocalTransform, Material, MaterialLoader, Mut, Parent, PostProcess, PreviewPlugin, Query, QueryInstance, RenderStage, Renderer, Res, ResMut, ResMutInstance, Schedule, ShaderSources, SpineAnimation, SpineController, Sprite, SystemRunner, Text, TextAlign, TextOverflow, TextPlugin, TextRenderer, TextVerticalAlign, Time, UIRect, Velocity, World, WorldTransform, assetPlugin, color, createSpineController, createWebApp, defineComponent, defineResource, defineSystem, defineTag, getComponentDefaults, getPlatform, getPlatformType, initDrawAPI, initGeometryAPI, initMaterialAPI, initPostProcessAPI, initRendererAPI, isBuiltinComponent, isPlatformInitialized, isWeChat, isWeb, loadComponent, loadSceneData, loadSceneWithAssets, platformFetch, platformFileExists, platformInstantiateWasm, platformReadFile, platformReadTextFile, quat, registerMaterialCallback, shutdownDrawAPI, shutdownGeometryAPI, shutdownMaterialAPI, shutdownPostProcessAPI, shutdownRendererAPI, textPlugin, updateCameraAspectRatio, vec2, vec3, vec4 };-export type { AnyComponentDef, AssetsData, BuiltinComponentDef, CameraData, CanvasData, ChildrenData, Color, CommandsDescriptor, ComponentData, ComponentDef, CppRegistry, CppResourceManager, DrawAPI, ESEngineModule, Entity, GeometryHandle, GeometryOptions, InferParam, InferParams, InputState, LoadedMaterial, LocalTransformData, MaterialAssetData, MaterialHandle, MaterialOptions, MutWrapper, ParentData, PlatformAdapter, PlatformRequestOptions, PlatformResponse, PlatformType, Plugin, Quat, QueryDescriptor, QueryResult, RenderStats, RenderTargetHandle, ResDescriptor, ResMutDescriptor, ResourceDef, SceneComponentData, SceneData, SceneEntityData, SceneLoadOptions, ShaderHandle, ShaderLoader, SliceBorder$1 as SliceBorder, SpineAnimationData, SpineEvent, SpineEventCallback, SpineEventType, SpineLoadResult, SpriteData, SystemDef, SystemParam, TextData, TextRenderResult, TextureHandle, TextureInfo, TimeData, TrackEntryInfo, UIRectData, UniformValue, Vec2, Vec3, Vec4, VelocityData, VertexAttributeDescriptor, WebAppOptions, WorldTransformData };+export { App, AssetPlugin, AssetServer, Assets, AsyncCache, BlendMode, Camera, Canvas, Children, Commands, CommandsInstance, DataType, Draw, EntityCommands, Geometry, INVALID_ENTITY, INVALID_TEXTURE, Input, LocalTransform, Material, MaterialLoader, Mut, Parent, PostProcess, PreviewPlugin, Query, QueryInstance, RenderStage, Renderer, Res, ResMut, ResMutInstance, Schedule, ShaderSources, SpineAnimation, SpineController, Sprite, SystemRunner, Text, TextAlign, TextOverflow, TextPlugin, TextRenderer, TextVerticalAlign, Time, UIRect, Velocity, World, WorldTransform, assetPlugin, color, createSpineController, createWebApp, defineComponent, defineResource, defineSystem, defineTag, getComponentDefaults, getPlatform, getPlatformType, initDrawAPI, initGeometryAPI, initMaterialAPI, initPostProcessAPI, initRendererAPI, isBuiltinComponent, isPlatformInitialized, isWeChat, isWeb, loadComponent, loadSceneData, loadSceneWithAssets, platformFetch, platformFileExists, platformInstantiateWasm, platformReadFile, platformReadTextFile, quat, registerMaterialCallback, shutdownDrawAPI, shutdownGeometryAPI, shutdownMaterialAPI, shutdownPostProcessAPI, shutdownRendererAPI, textPlugin, updateCameraAspectRatio, vec2, vec3, vec4 };+export type { AnyComponentDef, AssetBundle, AssetManifest, AssetsData, BuiltinComponentDef, CameraData, CanvasData, ChildrenData, Color, CommandsDescriptor, ComponentData, ComponentDef, CppRegistry, CppResourceManager, DrawAPI, ESEngineModule, Entity, FileLoadOptions, GeometryHandle, GeometryOptions, InferParam, InferParams, InputState, LoadedMaterial, LocalTransformData, MaterialAssetData, MaterialHandle, MaterialOptions, MutWrapper, ParentData, PlatformAdapter, PlatformRequestOptions, PlatformResponse, PlatformType, Plugin, Quat, QueryDescriptor, QueryResult, RenderStats, RenderTargetHandle, ResDescriptor, ResMutDescriptor, ResourceDef, SceneComponentData, SceneData, SceneEntityData, SceneLoadOptions, ShaderHandle, ShaderLoader, SliceBorder, SpineAnimationData, SpineDescriptor, SpineEvent, SpineEventCallback, SpineEventType, SpineLoadResult, SpriteData, SystemDef, SystemParam, TextData, TextRenderResult, TextureHandle, TextureInfo, TimeData, TrackEntryInfo, UIRectData, UniformValue, Vec2, Vec3, Vec4, VelocityData, VertexAttributeDescriptor, WebAppOptions, WorldTransformData };diff --git a/desktop/public/sdk/esm/esengine.js b/desktop/public/sdk/esm/esengine.jsindex 2d1b86540..b61034520 100644--- a/desktop/public/sdk/esm/esengine.js+++ b/desktop/public/sdk/esm/esengine.js@@ -2659,6 +2659,194 @@ class MaterialLoader {}}+/**+ * @file scene.ts+ * @brief Scene loading utilities+ */+// =============================================================================+// Scene Loader+// =============================================================================+function loadSceneData(world, sceneData) {+ const entityMap = new Map();+ for (const entityData of sceneData.entities) {+ const entity = world.spawn();+ entityMap.set(entityData.id, entity);+ for (const compData of entityData.components) {+ loadComponent(world, entity, compData);+ }+ }+ // Set parent-child relationships+ for (const entityData of sceneData.entities) {+ if (entityData.parent !== null) {+ const entity = entityMap.get(entityData.id);+ const parentEntity = entityMap.get(entityData.parent);+ if (entity !== undefined && parentEntity !== undefined) {+ world.setParent(entity, parentEntity);+ }+ }+ }+ return entityMap;+}+async function loadSceneWithAssets(world, sceneData, options) {+ const entityMap = new Map();+ const assetServer = options?.assetServer;+ const texturePathToUrl = new Map();+ for (const entityData of sceneData.entities) {+ const entity = world.spawn();+ entityMap.set(entityData.id, entity);+ for (const compData of entityData.components) {+ if (compData.type === 'Sprite' && assetServer) {+ const data = compData.data;+ if (typeof data.texture === 'string' && data.texture) {+ const texturePath = data.texture;+ const isDataUrl = texturePath.startsWith('data:');+ const url = isDataUrl+ ? texturePath+ : options?.assetBaseUrl+ ? `${options.assetBaseUrl}/${texturePath}`+ : `/${texturePath}`;+ try {+ const info = await assetServer.loadTexture(url);+ data.texture = info.handle;+ texturePathToUrl.set(texturePath, url);+ }+ catch (err) {+ console.warn(`Failed to load texture: ${url}`, err);+ data.texture = 0;+ }+ }+ if (typeof data.material === 'string' && data.material) {+ try {+ const loaded = await assetServer.loadMaterial(data.material, options?.assetBaseUrl);+ data.material = loaded.handle;+ }+ catch (err) {+ console.warn(`Failed to load material: ${data.material}`, err);+ data.material = 0;+ }+ }+ }+ if (compData.type === 'SpineAnimation' && assetServer) {+ const data = compData.data;+ const skeletonPath = data.skeletonPath;+ const atlasPath = data.atlasPath;+ if (skeletonPath && atlasPath) {+ const result = await assetServer.loadSpine(skeletonPath, atlasPath, options?.assetBaseUrl);+ if (!result.success) {+ console.warn(`Failed to load Spine: ${result.error}`);+ }+ }+ if (typeof data.material === 'string' && data.material) {+ try {+ const loaded = await assetServer.loadMaterial(data.material, options?.assetBaseUrl);+ data.material = loaded.handle;+ }+ catch (err) {+ console.warn(`Failed to load material: ${data.material}`, err);+ data.material = 0;+ }+ }+ }+ loadComponent(world, entity, compData);+ }+ }+ for (const entityData of sceneData.entities) {+ if (entityData.parent !== null) {+ const entity = entityMap.get(entityData.id);+ const parentEntity = entityMap.get(entityData.parent);+ if (entity !== undefined && parentEntity !== undefined) {+ world.setParent(entity, parentEntity);+ }+ }+ }+ 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;+}+function loadComponent(world, entity, compData) {+ const data = compData.data;+ switch (compData.type) {+ case 'LocalTransform':+ world.insert(entity, LocalTransform, data);+ break;+ case 'Sprite':+ world.insert(entity, Sprite, data);+ break;+ case 'Camera':+ world.insert(entity, Camera, data);+ break;+ case 'Canvas':+ world.insert(entity, Canvas, data);+ break;+ case 'Text':+ world.insert(entity, Text, data);+ break;+ case 'SpineAnimation':+ world.insert(entity, SpineAnimation, data);+ break;+ default:+ console.warn(`Unknown component type: ${compData.type}`);+ }+}+function updateCameraAspectRatio(world, aspectRatio) {+ const cameraEntities = world.getEntitiesWithComponents([Camera]);+ for (const entity of cameraEntities) {+ const camera = world.get(entity, Camera);+ if (camera) {+ camera.aspectRatio = aspectRatio;+ world.insert(entity, Camera, camera);+ }+ }+}++class AsyncCache {+ constructor() {+ this.cache_ = new Map();+ this.pending_ = new Map();+ }+ async getOrLoad(key, loader) {+ const cached = this.cache_.get(key);+ if (cached !== undefined) {+ return cached;+ }+ const pending = this.pending_.get(key);+ if (pending) {+ return pending;+ }+ const promise = loader();+ this.pending_.set(key, promise);+ try {+ const result = await promise;+ this.cache_.set(key, result);+ return result;+ }+ finally {+ this.pending_.delete(key);+ }+ }+ get(key) {+ return this.cache_.get(key);+ }+ has(key) {+ return this.cache_.has(key);+ }+ delete(key) {+ return this.cache_.delete(key);+ }+ clear() {+ this.cache_.clear();+ }+ values() {+ return this.cache_.values();+ }+}+/*** @file AssetServer.ts* @brief Asset loading and caching system@@ -2668,24 +2856,16 @@ class MaterialLoader {// =============================================================================class AssetServer {constructor(module) {- this.cache_ = new Map();- this.pending_ = new Map();- this.loadedSpines_ = new Map();+ this.textureCache_ = new AsyncCache();+ this.shaderCache_ = new AsyncCache();+ this.jsonCache_ = new AsyncCache();+ this.textCache_ = new AsyncCache();+ this.binaryCache_ = new AsyncCache();+ this.loadedSpines_ = new Set();this.virtualFSPaths_ = new Set();- this.materialLoader_ = null;- this.shaderCache_ = new Map();- this.shaderPending_ = new Map();this.module_ = module;- if (typeof OffscreenCanvas !== 'undefined') {- this.canvas_ = new OffscreenCanvas(512, 512);- this.ctx_ = this.canvas_.getContext('2d', { willReadFrequently: true });- }- else {- this.canvas_ = document.createElement('canvas');- this.canvas_.width = 512;- this.canvas_.height = 512;- this.ctx_ = this.canvas_.getContext('2d', { willReadFrequently: true });- }+ this.canvas_ = this.createCanvas(512, 512);+ this.ctx_ = this.canvas_.getContext('2d', { willReadFrequently: true });const shaderLoader = {load: (path) => this.loadShader(path),get: (path) => this.shaderCache_.get(path),@@ -2693,7 +2873,7 @@ class AssetServer {this.materialLoader_ = new MaterialLoader(shaderLoader);}// =========================================================================- // Public API+ // Texture// =========================================================================/*** Load texture with vertical flip (for Sprite/UI).@@ -2710,54 +2890,54 @@ class AssetServer {return this.loadTextureWithFlip(source, false);}getTexture(source) {- return this.cache_.get(this.getCacheKey(source, true));+ return this.textureCache_.get(this.textureCacheKey(source, true));}hasTexture(source) {- return this.cache_.has(this.getCacheKey(source, true));+ return this.textureCache_.has(this.textureCacheKey(source, true));}releaseTexture(source) {const rm = this.module_.getResourceManager();for (const flip of [true, false]) {- const key = this.getCacheKey(source, flip);- const info = this.cache_.get(key);+ const key = this.textureCacheKey(source, flip);+ const info = this.textureCache_.get(key);if (info) {rm.releaseTexture(info.handle);- this.cache_.delete(key);+ this.textureCache_.delete(key);}}}releaseAll() {const rm = this.module_.getResourceManager();- for (const info of this.cache_.values()) {+ for (const info of this.textureCache_.values()) {rm.releaseTexture(info.handle);}- this.cache_.clear();+ this.textureCache_.clear();+ this.jsonCache_.clear();+ this.textCache_.clear();+ this.binaryCache_.clear();}setTextureMetadata(handle, border) {const rm = this.module_.getResourceManager();rm.setTextureMetadata(handle, border.left, border.right, border.top, border.bottom);}setTextureMetadataByPath(source, border) {- const info = this.cache_.get(this.getCacheKey(source, true));+ const info = this.textureCache_.get(this.textureCacheKey(source, true));if (info) {this.setTextureMetadata(info.handle, border);return true;}return false;}+ // =========================================================================+ // Spine+ // =========================================================================async loadSpine(skeletonPath, atlasPath, baseUrl) {const cacheKey = `${skeletonPath}:${atlasPath}`;- if (this.loadedSpines_.get(cacheKey)) {+ if (this.loadedSpines_.has(cacheKey)) {return { success: true };}- const resolveUrl = (path) => {- if (path.startsWith('http://') || path.startsWith('https://') || path.startsWith('/')) {- return path;- }- return baseUrl ? `${baseUrl}/${path}` : `/${path}`;- };try {- const atlasUrl = resolveUrl(atlasPath);+ const atlasUrl = this.resolveUrl(atlasPath, baseUrl);const atlasResponse = await fetch(atlasUrl);if (!atlasResponse.ok) {return { success: false, error: `Failed to fetch atlas: ${atlasUrl}` };@@ -2770,7 +2950,7 @@ class AssetServer {const textureNames = this.parseAtlasTextures(atlasContent);for (const texName of textureNames) {const texPath = atlasDir ? `${atlasDir}/${texName}` : texName;- const texUrl = resolveUrl(texPath);+ const texUrl = this.resolveUrl(texPath, baseUrl);try {const info = await this.loadTextureRaw(texUrl);const rm = this.module_.getResourceManager();@@ -2780,7 +2960,7 @@ class AssetServer {console.warn(`[AssetServer] Failed to load Spine texture: ${texPath}`, err);}}- const skelUrl = resolveUrl(skeletonPath);+ const skelUrl = this.resolveUrl(skeletonPath, baseUrl);const skelResponse = await fetch(skelUrl);if (!skelResponse.ok) {return { success: false, error: `Failed to fetch skeleton: ${skelUrl}` };@@ -2792,7 +2972,7 @@ class AssetServer {if (!this.writeToVirtualFS(skeletonPath, skelData)) {return { success: false, error: `Failed to write skeleton to virtual FS: ${skeletonPath}` };}- this.loadedSpines_.set(cacheKey, true);+ this.loadedSpines_.add(cacheKey);return { success: true };}catch (err) {@@ -2800,105 +2980,108 @@ class AssetServer {}}isSpineLoaded(skeletonPath, atlasPath) {- return this.loadedSpines_.get(`${skeletonPath}:${atlasPath}`) ?? false;+ return this.loadedSpines_.has(`${skeletonPath}:${atlasPath}`);}+ // =========================================================================+ // Material & Shader+ // =========================================================================async loadMaterial(path, baseUrl) {- if (!this.materialLoader_) {- throw new Error('MaterialLoader not initialized');- }- const fullPath = this.resolveAssetPath(path, baseUrl);- return this.materialLoader_.load(fullPath);+ return this.materialLoader_.load(this.resolveUrl(path, baseUrl));}getMaterial(path, baseUrl) {- if (!this.materialLoader_)- return undefined;- const fullPath = this.resolveAssetPath(path, baseUrl);- return this.materialLoader_.get(fullPath);+ return this.materialLoader_.get(this.resolveUrl(path, baseUrl));}hasMaterial(path, baseUrl) {- if (!this.materialLoader_)- return false;- const fullPath = this.resolveAssetPath(path, baseUrl);- return this.materialLoader_.has(fullPath);+ return this.materialLoader_.has(this.resolveUrl(path, baseUrl));}async loadShader(path) {- const cached = this.shaderCache_.get(path);- if (cached)- return cached;- const pending = this.shaderPending_.get(path);- if (pending)- return pending;- const promise = this.loadShaderInternal(path);- this.shaderPending_.set(path, promise);- try {- const handle = await promise;- this.shaderCache_.set(path, handle);- return handle;+ return this.shaderCache_.getOrLoad(path, () => this.loadShaderInternal(path));+ }+ // =========================================================================+ // Generic File Loading+ // =========================================================================+ async loadJson(path, options) {+ const url = this.resolveUrl(path, options?.baseUrl);+ if (options?.noCache) {+ return this.fetchJson(url);}- finally {- this.shaderPending_.delete(path);+ return this.jsonCache_.getOrLoad(url, () => this.fetchJson(url));+ }+ async loadText(path, options) {+ const url = this.resolveUrl(path, options?.baseUrl);+ if (options?.noCache) {+ return this.fetchText(url);}+ return this.textCache_.getOrLoad(url, () => this.fetchText(url));}- async loadShaderInternal(path) {- const exists = await platformFileExists(path);- if (!exists) {- throw new Error(`Shader file not found: ${path}`);+ async loadBinary(path, options) {+ const url = this.resolveUrl(path, options?.baseUrl);+ if (options?.noCache) {+ return this.fetchBinary(url);}- const content = await platformReadTextFile(path);- if (!content) {- throw new Error(`Failed to read shader file: ${path}`);+ return this.binaryCache_.getOrLoad(url, () => this.fetchBinary(url));+ }+ // =========================================================================+ // Scene & Batch+ // =========================================================================+ async loadScene(world, sceneData) {+ return loadSceneWithAssets(world, sceneData, { assetServer: this });+ }+ async loadAll(manifest) {+ const bundle = {+ textures: new Map(),+ materials: new Map(),+ spine: new Map(),+ json: new Map(),+ text: new Map(),+ binary: new Map(),+ };+ const promises = [];+ if (manifest.textures) {+ for (const path of manifest.textures) {+ promises.push(this.loadTexture(path).then(info => { bundle.textures.set(path, info); }));+ }}- const { vertex, fragment } = this.parseEsShader(content);- if (!vertex || !fragment) {- throw new Error(`Invalid shader format: ${path}`);+ if (manifest.materials) {+ for (const path of manifest.materials) {+ promises.push(this.loadMaterial(path).then(mat => { bundle.materials.set(path, mat); }));+ }}- return Material.createShader(vertex, fragment);- }- parseEsShader(content) {- let vertex = null;- let fragment = 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/);- if (vertexMatch) {- vertex = vertexMatch[1].trim();+ if (manifest.spine) {+ for (const desc of manifest.spine) {+ const key = `${desc.skeleton}:${desc.atlas}`;+ promises.push(this.loadSpine(desc.skeleton, desc.atlas, desc.baseUrl).then(result => {+ bundle.spine.set(key, result);+ }));+ }}- if (fragmentMatch) {- fragment = fragmentMatch[1].trim();+ if (manifest.json) {+ for (const path of manifest.json) {+ promises.push(this.loadJson(path).then(data => { bundle.json.set(path, data); }));+ }}- return { vertex, fragment };- }- resolveAssetPath(path, baseUrl) {- if (path.startsWith('/') || path.startsWith('http')) {- return path;+ if (manifest.text) {+ for (const path of manifest.text) {+ promises.push(this.loadText(path).then(data => { bundle.text.set(path, data); }));+ }+ }+ if (manifest.binary) {+ for (const path of manifest.binary) {+ promises.push(this.loadBinary(path).then(data => { bundle.binary.set(path, data); }));+ }}- return baseUrl ? `${baseUrl}/${path}` : `/${path}`;+ await Promise.all(promises);+ return bundle;}// =========================================================================- // Private Methods+ // Private - Texture// =========================================================================- getCacheKey(source, flip) {+ textureCacheKey(source, flip) {return `${source}:${flip ? 'f' : 'n'}`;}async loadTextureWithFlip(source, flip) {- const cacheKey = this.getCacheKey(source, flip);- const cached = this.cache_.get(cacheKey);- if (cached) {- return cached;- }- const pending = this.pending_.get(cacheKey);- if (pending) {- return pending;- }- const promise = this.loadTextureInternal(source, flip);- this.pending_.set(cacheKey, promise);- try {- const result = await promise;- this.cache_.set(cacheKey, result);- return result;- }- finally {- this.pending_.delete(cacheKey);- }+ const cacheKey = this.textureCacheKey(source, flip);+ return this.textureCache_.getOrLoad(cacheKey, () => this.loadTextureInternal(source, flip));}async loadTextureInternal(source, flip) {const img = await this.loadImage(source);@@ -2963,12 +3146,59 @@ class AssetServer {}}}- nextPowerOf2(n) {- let p = 1;- while (p < n)- p *= 2;- return p;+ // =========================================================================+ // Private - Shader+ // =========================================================================+ async loadShaderInternal(path) {+ const exists = await platformFileExists(path);+ if (!exists) {+ throw new Error(`Shader file not found: ${path}`);+ }+ const content = await platformReadTextFile(path);+ 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);}+ parseEsShader(content) {+ 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+ // =========================================================================+ async fetchJson(url) {+ const response = await platformFetch(url);+ if (!response.ok) {+ throw new Error(`Failed to fetch JSON: ${url} (${response.status})`);+ }+ return response.json();+ }+ async fetchText(url) {+ const response = await platformFetch(url);+ if (!response.ok) {+ throw new Error(`Failed to fetch text: ${url} (${response.status})`);+ }+ return response.text();+ }+ async fetchBinary(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+ // =========================================================================writeToVirtualFS(virtualPath, data) {if (this.virtualFSPaths_.has(virtualPath)) {return true;@@ -3015,10 +3245,33 @@ class AssetServer {}}}+ // =========================================================================+ // Private - Utilities+ // =========================================================================+ resolveUrl(path, baseUrl) {+ if (path.startsWith('/') || path.startsWith('http://') || path.startsWith('https://')) {+ return path;+ }+ const base = baseUrl ?? this.baseUrl;+ return base ? `${base}/${path}` : `/${path}`;+ }+ createCanvas(width, height) {+ const canvas = typeof OffscreenCanvas !== 'undefined'+ ? new OffscreenCanvas(width, height)+ : document.createElement('canvas');+ canvas.width = width;+ canvas.height = height;+ return canvas;+ }+ nextPowerOf2(n) {+ let p = 1;+ while (p < n)+ p *= 2;+ return p;+ }parseAtlasTextures(atlasContent) {const textures = [];- const lines = atlasContent.split('\n');- for (const line of lines) {+ for (const line of atlasContent.split('\n')) {const trimmed = line.trim();if (trimmed && !trimmed.includes(':') &&(trimmed.endsWith('.png') || trimmed.endsWith('.jpg'))) {@@ -3033,7 +3286,7 @@ class AssetServer {* @file AssetPlugin.ts* @brief Plugin that provides asset loading capabilities*/-const Assets = defineResource({ server: null }, 'Assets');+const Assets = defineResource(null, 'Assets');// =============================================================================// Asset Plugin// =============================================================================@@ -3044,158 +3297,11 @@ class AssetPlugin {console.warn('AssetPlugin: No WASM module available');return;}- const server = new AssetServer(module);- app.insertResource(Assets, { server });+ app.insertResource(Assets, new AssetServer(module));}}const assetPlugin = new AssetPlugin();-/**- * @file scene.ts- * @brief Scene loading utilities- */-// =============================================================================-// Scene Loader-// =============================================================================-function loadSceneData(world, sceneData) {- const entityMap = new Map();- for (const entityData of sceneData.entities) {- const entity = world.spawn();- entityMap.set(entityData.id, entity);- for (const compData of entityData.components) {- loadComponent(world, entity, compData);- }- }- // Set parent-child relationships- for (const entityData of sceneData.entities) {- if (entityData.parent !== null) {- const entity = entityMap.get(entityData.id);- const parentEntity = entityMap.get(entityData.parent);- if (entity !== undefined && parentEntity !== undefined) {- world.setParent(entity, parentEntity);- }- }- }- return entityMap;-}-async function loadSceneWithAssets(world, sceneData, options) {- const entityMap = new Map();- const assetServer = options?.assetServer;- const texturePathToUrl = new Map();- for (const entityData of sceneData.entities) {- const entity = world.spawn();- entityMap.set(entityData.id, entity);- for (const compData of entityData.components) {- if (compData.type === 'Sprite' && assetServer) {- const data = compData.data;- if (typeof data.texture === 'string' && data.texture) {- const texturePath = data.texture;- const isDataUrl = texturePath.startsWith('data:');- const url = isDataUrl- ? texturePath- : options?.assetBaseUrl- ? `${options.assetBaseUrl}/${texturePath}`- : `/${texturePath}`;- try {- const info = await assetServer.loadTexture(url);- data.texture = info.handle;- texturePathToUrl.set(texturePath, url);- }- catch (err) {- console.warn(`Failed to load texture: ${url}`, err);- data.texture = 0;- }- }- if (typeof data.material === 'string' && data.material) {- try {- const loaded = await assetServer.loadMaterial(data.material, options?.assetBaseUrl);- data.material = loaded.handle;- }- catch (err) {- console.warn(`Failed to load material: ${data.material}`, err);- data.material = 0;- }- }- }- if (compData.type === 'SpineAnimation' && assetServer) {- const data = compData.data;- const skeletonPath = data.skeletonPath;- const atlasPath = data.atlasPath;- if (skeletonPath && atlasPath) {- const result = await assetServer.loadSpine(skeletonPath, atlasPath, options?.assetBaseUrl);- if (!result.success) {- console.warn(`Failed to load Spine: ${result.error}`);- }- }- if (typeof data.material === 'string' && data.material) {- try {- const loaded = await assetServer.loadMaterial(data.material, options?.assetBaseUrl);- data.material = loaded.handle;- }- catch (err) {- console.warn(`Failed to load material: ${data.material}`, err);- data.material = 0;- }- }- }- loadComponent(world, entity, compData);- }- }- for (const entityData of sceneData.entities) {- if (entityData.parent !== null) {- const entity = entityMap.get(entityData.id);- const parentEntity = entityMap.get(entityData.parent);- if (entity !== undefined && parentEntity !== undefined) {- world.setParent(entity, parentEntity);- }- }- }- 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;-}-function loadComponent(world, entity, compData) {- const data = compData.data;- switch (compData.type) {- case 'LocalTransform':- world.insert(entity, LocalTransform, data);- break;- case 'Sprite':- world.insert(entity, Sprite, data);- break;- case 'Camera':- world.insert(entity, Camera, data);- break;- case 'Canvas':- world.insert(entity, Canvas, data);- break;- case 'Text':- world.insert(entity, Text, data);- break;- case 'SpineAnimation':- world.insert(entity, SpineAnimation, data);- break;- default:- console.warn(`Unknown component type: ${compData.type}`);- }-}-function updateCameraAspectRatio(world, aspectRatio) {- const cameraEntities = world.getEntitiesWithComponents([Camera]);- for (const entity of cameraEntities) {- const camera = world.get(entity, Camera);- if (camera) {- camera.aspectRatio = aspectRatio;- world.insert(entity, Camera, camera);- }- }-}-/*** @file PreviewPlugin.ts* @brief Plugin for editor preview functionality@@ -3234,9 +3340,7 @@ class PreviewPlugin {}const sceneData = await response.json();const assets = this.app_.getResource(Assets);- await loadSceneWithAssets(this.app_.world, sceneData, {- assetServer: assets.server- });+ await assets.loadScene(this.app_.world, sceneData);this.ensureCamera();}catch (err) {@@ -3589,5 +3693,5 @@ function createSpineController(wasmModule) {// Initialize Web platformsetPlatform(webAdapter);-export { App, AssetPlugin, AssetServer, Assets, BlendMode, Camera, Canvas, Children, Commands, CommandsInstance, DataType, Draw, EntityCommands, Geometry, INVALID_ENTITY, INVALID_TEXTURE, Input, LocalTransform, Material, MaterialLoader, Mut, Parent, PostProcess, PreviewPlugin, Query, QueryInstance, RenderStage, Renderer, Res, ResMut, Schedule, ShaderSources, SpineAnimation, SpineController, Sprite, SystemRunner, Text, TextAlign, TextOverflow, TextPlugin, TextRenderer, TextVerticalAlign, Time, UIRect, Velocity, World, WorldTransform, assetPlugin, color, createSpineController, createWebApp, defineComponent, defineResource, defineSystem, defineTag, getComponentDefaults, getPlatform, getPlatformType, initDrawAPI, initGeometryAPI, initMaterialAPI, initPostProcessAPI, initRendererAPI, isBuiltinComponent, isPlatformInitialized, isWeChat, isWeb, loadComponent, loadSceneData, loadSceneWithAssets, platformFetch, platformFileExists, platformInstantiateWasm, platformReadFile, platformReadTextFile, quat, registerMaterialCallback, shutdownDrawAPI, shutdownGeometryAPI, shutdownMaterialAPI, shutdownPostProcessAPI, shutdownRendererAPI, textPlugin, updateCameraAspectRatio, vec2, vec3, vec4 };+export { App, AssetPlugin, AssetServer, Assets, AsyncCache, BlendMode, Camera, Canvas, Children, Commands, CommandsInstance, DataType, Draw, EntityCommands, Geometry, INVALID_ENTITY, INVALID_TEXTURE, Input, LocalTransform, Material, MaterialLoader, Mut, Parent, PostProcess, PreviewPlugin, Query, QueryInstance, RenderStage, Renderer, Res, ResMut, Schedule, ShaderSources, SpineAnimation, SpineController, Sprite, SystemRunner, Text, TextAlign, TextOverflow, TextPlugin, TextRenderer, TextVerticalAlign, Time, UIRect, Velocity, World, WorldTransform, assetPlugin, color, createSpineController, createWebApp, defineComponent, defineResource, defineSystem, defineTag, getComponentDefaults, getPlatform, getPlatformType, initDrawAPI, initGeometryAPI, initMaterialAPI, initPostProcessAPI, initRendererAPI, isBuiltinComponent, isPlatformInitialized, isWeChat, isWeb, loadComponent, loadSceneData, loadSceneWithAssets, platformFetch, platformFileExists, platformInstantiateWasm, platformReadFile, platformReadTextFile, quat, registerMaterialCallback, shutdownDrawAPI, shutdownGeometryAPI, shutdownMaterialAPI, shutdownPostProcessAPI, shutdownRendererAPI, textPlugin, updateCameraAspectRatio, vec2, vec3, vec4 };//# sourceMappingURL=index.js.mapdiff --git a/sdk/examples/playground/assets/beer.png b/sdk/examples/playground/assets/beer.pngdeleted file mode 100644index 2defeb3d8..000000000Binary files a/sdk/examples/playground/assets/beer.png and /dev/null differdiff --git a/sdk/examples/playground/package-lock.json b/sdk/examples/playground/package-lock.jsondeleted file mode 100644index a4307c6ac..000000000--- a/sdk/examples/playground/package-lock.json+++ /dev/null@@ -1,494 +0,0 @@-{- "name": "test-project",- "version": "1.0.0",- "lockfileVersion": 3,- "requires": true,- "packages": {- "": {- "name": "test-project",- "version": "1.0.0",- "dependencies": {- "esengine": "file:../.."- },- "devDependencies": {- "esbuild": "^0.20.0",- "typescript": "^5.0.0"- }- },- "../..": {- "name": "esengine",- "version": "0.2.0",- "license": "MIT",- "devDependencies": {- "@rollup/plugin-typescript": "^11.1.5",- "rimraf": "^5.0.5",- "rollup": "^4.9.0",- "rollup-plugin-dts": "^6.1.0",- "tslib": "^2.6.2",- "typescript": "^5.3.0"- }- },- "../sdk": {- "name": "esengine",- "version": "0.2.0",- "extraneous": true,- "license": "MIT",- "devDependencies": {- "@rollup/plugin-typescript": "^11.1.5",- "rimraf": "^5.0.5",- "rollup": "^4.9.0",- "rollup-plugin-dts": "^6.1.0",- "tslib": "^2.6.2",- "typescript": "^5.3.0"- }- },- "node_modules/@esbuild/aix-ppc64": {- "version": "0.20.2",- "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.20.2.tgz",- "integrity": "sha512-D+EBOJHXdNZcLJRBkhENNG8Wji2kgc9AZ9KiPr1JuZjsNtyHzrsfLRrY0tk2H2aoFu6RANO1y1iPPUCDYWkb5g==",- "cpu": [- "ppc64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "aix"- ],- "engines": {- "node": ">=12"- }- },- "node_modules/@esbuild/android-arm": {- "version": "0.20.2",- "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.20.2.tgz",- "integrity": "sha512-t98Ra6pw2VaDhqNWO2Oph2LXbz/EJcnLmKLGBJwEwXX/JAN83Fym1rU8l0JUWK6HkIbWONCSSatf4sf2NBRx/w==",- "cpu": [- "arm"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "android"- ],- "engines": {- "node": ">=12"- }- },- "node_modules/@esbuild/android-arm64": {- "version": "0.20.2",- "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.20.2.tgz",- "integrity": "sha512-mRzjLacRtl/tWU0SvD8lUEwb61yP9cqQo6noDZP/O8VkwafSYwZ4yWy24kan8jE/IMERpYncRt2dw438LP3Xmg==",- "cpu": [- "arm64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "android"- ],- "engines": {- "node": ">=12"- }- },- "node_modules/@esbuild/android-x64": {- "version": "0.20.2",- "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.20.2.tgz",- "integrity": "sha512-btzExgV+/lMGDDa194CcUQm53ncxzeBrWJcncOBxuC6ndBkKxnHdFJn86mCIgTELsooUmwUm9FkhSp5HYu00Rg==",- "cpu": [- "x64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "android"- ],- "engines": {- "node": ">=12"- }- },- "node_modules/@esbuild/darwin-arm64": {- "version": "0.20.2",- "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.20.2.tgz",- "integrity": "sha512-4J6IRT+10J3aJH3l1yzEg9y3wkTDgDk7TSDFX+wKFiWjqWp/iCfLIYzGyasx9l0SAFPT1HwSCR+0w/h1ES/MjA==",- "cpu": [- "arm64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "darwin"- ],- "engines": {- "node": ">=12"- }- },- "node_modules/@esbuild/darwin-x64": {- "version": "0.20.2",- "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.20.2.tgz",- "integrity": "sha512-tBcXp9KNphnNH0dfhv8KYkZhjc+H3XBkF5DKtswJblV7KlT9EI2+jeA8DgBjp908WEuYll6pF+UStUCfEpdysA==",- "cpu": [- "x64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "darwin"- ],- "engines": {- "node": ">=12"- }- },- "node_modules/@esbuild/freebsd-arm64": {- "version": "0.20.2",- "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.20.2.tgz",- "integrity": "sha512-d3qI41G4SuLiCGCFGUrKsSeTXyWG6yem1KcGZVS+3FYlYhtNoNgYrWcvkOoaqMhwXSMrZRl69ArHsGJ9mYdbbw==",- "cpu": [- "arm64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "freebsd"- ],- "engines": {- "node": ">=12"- }- },- "node_modules/@esbuild/freebsd-x64": {- "version": "0.20.2",- "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.20.2.tgz",- "integrity": "sha512-d+DipyvHRuqEeM5zDivKV1KuXn9WeRX6vqSqIDgwIfPQtwMP4jaDsQsDncjTDDsExT4lR/91OLjRo8bmC1e+Cw==",- "cpu": [- "x64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "freebsd"- ],- "engines": {- "node": ">=12"- }- },- "node_modules/@esbuild/linux-arm": {- "version": "0.20.2",- "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.20.2.tgz",- "integrity": "sha512-VhLPeR8HTMPccbuWWcEUD1Az68TqaTYyj6nfE4QByZIQEQVWBB8vup8PpR7y1QHL3CpcF6xd5WVBU/+SBEvGTg==",- "cpu": [- "arm"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "linux"- ],- "engines": {- "node": ">=12"- }- },- "node_modules/@esbuild/linux-arm64": {- "version": "0.20.2",- "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.20.2.tgz",- "integrity": "sha512-9pb6rBjGvTFNira2FLIWqDk/uaf42sSyLE8j1rnUpuzsODBq7FvpwHYZxQ/It/8b+QOS1RYfqgGFNLRI+qlq2A==",- "cpu": [- "arm64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "linux"- ],- "engines": {- "node": ">=12"- }- },- "node_modules/@esbuild/linux-ia32": {- "version": "0.20.2",- "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.20.2.tgz",- "integrity": "sha512-o10utieEkNPFDZFQm9CoP7Tvb33UutoJqg3qKf1PWVeeJhJw0Q347PxMvBgVVFgouYLGIhFYG0UGdBumROyiig==",- "cpu": [- "ia32"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "linux"- ],- "engines": {- "node": ">=12"- }- },- "node_modules/@esbuild/linux-loong64": {- "version": "0.20.2",- "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.20.2.tgz",- "integrity": "sha512-PR7sp6R/UC4CFVomVINKJ80pMFlfDfMQMYynX7t1tNTeivQ6XdX5r2XovMmha/VjR1YN/HgHWsVcTRIMkymrgQ==",- "cpu": [- "loong64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "linux"- ],- "engines": {- "node": ">=12"- }- },- "node_modules/@esbuild/linux-mips64el": {- "version": "0.20.2",- "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.20.2.tgz",- "integrity": "sha512-4BlTqeutE/KnOiTG5Y6Sb/Hw6hsBOZapOVF6njAESHInhlQAghVVZL1ZpIctBOoTFbQyGW+LsVYZ8lSSB3wkjA==",- "cpu": [- "mips64el"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "linux"- ],- "engines": {- "node": ">=12"- }- },- "node_modules/@esbuild/linux-ppc64": {- "version": "0.20.2",- "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.20.2.tgz",- "integrity": "sha512-rD3KsaDprDcfajSKdn25ooz5J5/fWBylaaXkuotBDGnMnDP1Uv5DLAN/45qfnf3JDYyJv/ytGHQaziHUdyzaAg==",- "cpu": [- "ppc64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "linux"- ],- "engines": {- "node": ">=12"- }- },- "node_modules/@esbuild/linux-riscv64": {- "version": "0.20.2",- "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.20.2.tgz",- "integrity": "sha512-snwmBKacKmwTMmhLlz/3aH1Q9T8v45bKYGE3j26TsaOVtjIag4wLfWSiZykXzXuE1kbCE+zJRmwp+ZbIHinnVg==",- "cpu": [- "riscv64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "linux"- ],- "engines": {- "node": ">=12"- }- },- "node_modules/@esbuild/linux-s390x": {- "version": "0.20.2",- "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.20.2.tgz",- "integrity": "sha512-wcWISOobRWNm3cezm5HOZcYz1sKoHLd8VL1dl309DiixxVFoFe/o8HnwuIwn6sXre88Nwj+VwZUvJf4AFxkyrQ==",- "cpu": [- "s390x"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "linux"- ],- "engines": {- "node": ">=12"- }- },- "node_modules/@esbuild/linux-x64": {- "version": "0.20.2",- "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.20.2.tgz",- "integrity": "sha512-1MdwI6OOTsfQfek8sLwgyjOXAu+wKhLEoaOLTjbijk6E2WONYpH9ZU2mNtR+lZ2B4uwr+usqGuVfFT9tMtGvGw==",- "cpu": [- "x64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "linux"- ],- "engines": {- "node": ">=12"- }- },- "node_modules/@esbuild/netbsd-x64": {- "version": "0.20.2",- "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.20.2.tgz",- "integrity": "sha512-K8/DhBxcVQkzYc43yJXDSyjlFeHQJBiowJ0uVL6Tor3jGQfSGHNNJcWxNbOI8v5k82prYqzPuwkzHt3J1T1iZQ==",- "cpu": [- "x64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "netbsd"- ],- "engines": {- "node": ">=12"- }- },- "node_modules/@esbuild/openbsd-x64": {- "version": "0.20.2",- "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.20.2.tgz",- "integrity": "sha512-eMpKlV0SThJmmJgiVyN9jTPJ2VBPquf6Kt/nAoo6DgHAoN57K15ZghiHaMvqjCye/uU4X5u3YSMgVBI1h3vKrQ==",- "cpu": [- "x64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "openbsd"- ],- "engines": {- "node": ">=12"- }- },- "node_modules/@esbuild/sunos-x64": {- "version": "0.20.2",- "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.20.2.tgz",- "integrity": "sha512-2UyFtRC6cXLyejf/YEld4Hajo7UHILetzE1vsRcGL3earZEW77JxrFjH4Ez2qaTiEfMgAXxfAZCm1fvM/G/o8w==",- "cpu": [- "x64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "sunos"- ],- "engines": {- "node": ">=12"- }- },- "node_modules/@esbuild/win32-arm64": {- "version": "0.20.2",- "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.20.2.tgz",- "integrity": "sha512-GRibxoawM9ZCnDxnP3usoUDO9vUkpAxIIZ6GQI+IlVmr5kP3zUq+l17xELTHMWTWzjxa2guPNyrpq1GWmPvcGQ==",- "cpu": [- "arm64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "win32"- ],- "engines": {- "node": ">=12"- }- },- "node_modules/@esbuild/win32-ia32": {- "version": "0.20.2",- "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.20.2.tgz",- "integrity": "sha512-HfLOfn9YWmkSKRQqovpnITazdtquEW8/SoHW7pWpuEeguaZI4QnCRW6b+oZTztdBnZOS2hqJ6im/D5cPzBTTlQ==",- "cpu": [- "ia32"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "win32"- ],- "engines": {- "node": ">=12"- }- },- "node_modules/@esbuild/win32-x64": {- "version": "0.20.2",- "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.20.2.tgz",- "integrity": "sha512-N49X4lJX27+l9jbLKSqZ6bKNjzQvHaT8IIFUy+YIqmXQdjYCToGWwOItDrfby14c78aDd5NHQl29xingXfCdLQ==",- "cpu": [- "x64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "win32"- ],- "engines": {- "node": ">=12"- }- },- "node_modules/esbuild": {- "version": "0.20.2",- "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.20.2.tgz",- "integrity": "sha512-WdOOppmUNU+IbZ0PaDiTst80zjnrOkyJNHoKupIcVyU8Lvla3Ugx94VzkQ32Ijqd7UhHJy75gNWDMUekcrSJ6g==",- "dev": true,- "hasInstallScript": true,- "license": "MIT",- "bin": {- "esbuild": "bin/esbuild"- },- "engines": {- "node": ">=12"- },- "optionalDependencies": {- "@esbuild/aix-ppc64": "0.20.2",- "@esbuild/android-arm": "0.20.2",- "@esbuild/android-arm64": "0.20.2",- "@esbuild/android-x64": "0.20.2",- "@esbuild/darwin-arm64": "0.20.2",- "@esbuild/darwin-x64": "0.20.2",- "@esbuild/freebsd-arm64": "0.20.2",- "@esbuild/freebsd-x64": "0.20.2",- "@esbuild/linux-arm": "0.20.2",- "@esbuild/linux-arm64": "0.20.2",- "@esbuild/linux-ia32": "0.20.2",- "@esbuild/linux-loong64": "0.20.2",- "@esbuild/linux-mips64el": "0.20.2",- "@esbuild/linux-ppc64": "0.20.2",- "@esbuild/linux-riscv64": "0.20.2",- "@esbuild/linux-s390x": "0.20.2",- "@esbuild/linux-x64": "0.20.2",- "@esbuild/netbsd-x64": "0.20.2",- "@esbuild/openbsd-x64": "0.20.2",- "@esbuild/sunos-x64": "0.20.2",- "@esbuild/win32-arm64": "0.20.2",- "@esbuild/win32-ia32": "0.20.2",- "@esbuild/win32-x64": "0.20.2"- }- },- "node_modules/esengine": {- "resolved": "../..",- "link": true- },- "node_modules/typescript": {- "version": "5.9.3",- "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz",- "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",- "dev": true,- "license": "Apache-2.0",- "bin": {- "tsc": "bin/tsc",- "tsserver": "bin/tsserver"- },- "engines": {- "node": ">=14.17"- }- }- }-}diff --git a/sdk/examples/playground/package.json b/sdk/examples/playground/package.jsondeleted file mode 100644index 3fe1ee4a6..000000000--- a/sdk/examples/playground/package.json+++ /dev/null@@ -1,17 +0,0 @@-{- "name": "test-project",- "version": "1.0.0",- "type": "module",- "scripts": {- "build": "npx esbuild src/main.ts --bundle --format=esm --outfile=build/scripts/main.js --sourcemap",- "dev": "npx esbuild src/main.ts --bundle --format=esm --outfile=build/scripts/main.js --sourcemap --watch",- "build:playable": "npx esbuild src/main.ts --bundle --format=iife --global-name=Game --outfile=build/playable/game.js --minify"- },- "dependencies": {- "esengine": "file:../.."- },- "devDependencies": {- "esbuild": "^0.20.0",- "typescript": "^5.0.0"- }-}diff --git a/sdk/examples/playground/src/main.ts b/sdk/examples/playground/src/main.tsdeleted file mode 100644index dbc734571..000000000--- a/sdk/examples/playground/src/main.ts+++ /dev/null@@ -1,147 +0,0 @@-/**- * ESEngine Project Entry Point- *- * This file is the main entry point for your game logic.- * Press F5 in the editor to run, or use Web Preview for browser testing.- */-import {- type ESEngineModule,- App,- createWebApp,- defineSystem,- defineTag,- Schedule,- Commands,- LocalTransform,- Sprite,- Camera,- Canvas,- Res,- Time,- Query,- Mut,- type Entity,- Text,- TextAlign,- textPlugin,- assetPlugin,- Assets,- INVALID_TEXTURE-} from 'esengine';--const Animated = defineTag('Animated');--// =============================================================================-// Main Entry Point-// =============================================================================--export async function main(Module: ESEngineModule): Promise<void> {- console.log('ESEngine starting...');-- // Create the app with WASM module (handles renderer init + render loop)- const app = createWebApp(Module);-- // Add plugins- app.addPlugin(textPlugin);- app.addPlugin(assetPlugin);-- // Get asset server and load texture- const assets = app.getResource(Assets).server;- const testIcon = await assets.loadTexture('assets/beer.png');- console.log(`Loaded texture: ${testIcon.width}x${testIcon.height}, handle=${testIcon.handle}`);-- // Add startup system - runs once at beginning- app.addSystemToSchedule(Schedule.Startup, defineSystem(- [Commands()],- (cmds) => {- console.log('Startup: Creating entities...');-- // Create camera- const camera = cmds.spawn()- .insert(Camera, {- projectionType: 1, // Orthographic- fov: 60,- orthoSize: 400,- nearPlane: 0.1,- farPlane: 1000,- aspectRatio: 1,- isActive: true,- priority: 0- })- .insert(LocalTransform, {- position: { x: 0, y: 0, z: 10 },- rotation: { w: 1, x: 0, y: 0, z: 0 },- scale: { x: 1, y: 1, z: 1 }- })- .id();-- // Create a sprite with loaded texture- const sprite = cmds.spawn()- .insert(Animated)- .insert(Sprite, {- texture: testIcon.handle,- color: { x: 1, y: 1, z: 1, w: 1 },- size: { x: testIcon.width, y: testIcon.height },- uvOffset: { x: 0, y: 0 },- uvScale: { x: 1, y: 1 },- layer: 0,- flipX: false,- flipY: false- })- .insert(LocalTransform, {- position: { x: 0, y: 0, z: 0 },- rotation: { w: 1, x: 0, y: 0, z: 0 },- scale: { x: 1, y: 1, z: 1 }- })- .id();-- const textEntity = cmds.spawn()- .insert(Text, {- content: 'Hello ESEngine!',- fontFamily: 'Arial',- fontSize: 32,- color: { x: 1, y: 1, z: 1, w: 1 },- align: TextAlign.Center,- baseline: 0,- maxWidth: 0,- lineHeight: 1.2,- dirty: true- })- .insert(Sprite, {- texture: 0,- color: { x: 1, y: 1, z: 1, w: 1 },- size: { x: 200, y: 50 },- uvOffset: { x: 0, y: 0 },- uvScale: { x: 1, y: 1 },- layer: 10,- flipX: false,- flipY: false- })- .insert(LocalTransform, {- position: { x: 0, y: 150, z: 0 },- rotation: { w: 1, x: 0, y: 0, z: 0 },- scale: { x: 1, y: 1, z: 1 }- })- .id();-- console.log(`Created camera: ${camera}, sprite: ${sprite}, text: ${textEntity}`);- }- ));-- app.addSystemToSchedule(Schedule.Update, defineSystem(- [Res(Time), Query(Animated, Mut(LocalTransform))],- (time, query) => {- for (const [entity, _, transform] of query) {- transform.position = {- x: Math.sin(time.elapsed) * 100,- y: Math.cos(time.elapsed) * 100,- z: 0- };- }- }- ));-- // Start the game loop- console.log('Starting game loop...');- app.run();-}diff --git a/sdk/examples/playground/tsconfig.json b/sdk/examples/playground/tsconfig.jsondeleted file mode 100644index 84d188ba9..000000000--- a/sdk/examples/playground/tsconfig.json+++ /dev/null@@ -1,15 +0,0 @@-{- "compilerOptions": {- "target": "ES2020",- "module": "ESNext",- "lib": ["ES2020", "DOM"],- "moduleResolution": "node",- "strict": true,- "esModuleInterop": true,- "skipLibCheck": true,- "forceConsistentCasingInFileNames": true,- "noEmit": true- },- "include": ["src/**/*.ts"],- "exclude": ["node_modules", "build"]-}diff --git a/sdk/src/asset/AssetPlugin.ts b/sdk/src/asset/AssetPlugin.tsindex 167c49414..5749f13df 100644--- a/sdk/src/asset/AssetPlugin.ts+++ b/sdk/src/asset/AssetPlugin.ts@@ -11,12 +11,10 @@ import { AssetServer } from './AssetServer';// Assets Resource// =============================================================================-export interface AssetsData {- server: AssetServer;-}+export type AssetsData = AssetServer;export const Assets = defineResource<AssetsData>(- { server: null! },+ null!,'Assets');@@ -32,8 +30,7 @@ export class AssetPlugin implements Plugin {return;}- const server = new AssetServer(module);- app.insertResource(Assets, { server });+ app.insertResource(Assets, new AssetServer(module));}}diff --git a/sdk/src/preview/PreviewPlugin.ts b/sdk/src/preview/PreviewPlugin.tsindex bb521b6f8..3c6526f5e 100644--- a/sdk/src/preview/PreviewPlugin.ts+++ b/sdk/src/preview/PreviewPlugin.ts@@ -5,7 +5,7 @@import type { App, Plugin } from '../app';import { Assets, assetPlugin } from '../asset';-import { loadSceneWithAssets, type SceneData } from '../scene';+import type { SceneData } from '../scene';import { LocalTransform, Camera, type LocalTransformData, type CameraData } from '../component';import { platformFetch } from '../platform';@@ -52,9 +52,7 @@ export class PreviewPlugin implements Plugin {const sceneData = await response.json<SceneData>();const assets = this.app_.getResource(Assets);- await loadSceneWithAssets(this.app_.world, sceneData, {- assetServer: assets.server- });+ await assets.loadScene(this.app_.world, sceneData);this.ensureCamera();} catch (err) {