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.

feat: support embedded asset loading in Playable builds

esengine9559b2673f9a
diff --git a/editor/src/builder/PlayableBuilder.ts b/editor/src/builder/PlayableBuilder.ts
index 722b5a1ba..9c5cb6650 100644
--- a/editor/src/builder/PlayableBuilder.ts
+++ b/editor/src/builder/PlayableBuilder.ts
@@ -14,7 +14,6 @@
import * as esbuild from 'esbuild-wasm/esm/browser';
import type { BuildResult, BuildContext } from './BuildService';
import { BuildProgressReporter } from './BuildProgress';
-import { BuildCache, type BuildCacheData } from './BuildCache';
import { getEditorContext, getEsbuildWasmURL } from '../context/EditorContext';
import { findTsFiles, EDITOR_ONLY_DIRS } from '../scripting/ScriptLoader';
import { BuildAssetCollector, AssetExportConfigService } from './AssetCollector';
@@ -106,6 +105,7 @@ function decodeBinary(dataUrl){
if(!es||!es.createWebApp){console.error('esengine not found');return}
var app=es.createWebApp(Module);
+ if(typeof __PA__!=='undefined')es.registerEmbeddedAssets(app,__PA__);
es.flushPendingSystems(app);
var spineModule=null;
@@ -151,7 +151,6 @@ export class PlayableBuilder {
this.fs_ = getEditorContext().fs ?? null;
this.projectDir_ = getProjectDir(context.projectPath);
this.progress_ = context.progress || new BuildProgressReporter();
- this.cache_ = context.cache || null;
this.assetLibrary_ = new AssetLibrary();
}
@@ -181,11 +180,6 @@ export class PlayableBuilder {
await this.assetLibrary_.initialize(this.projectDir_, this.fs_);
this.progress_.log('info', 'Asset library initialized');
- let cachedData: BuildCacheData | null = null;
- if (this.cache_) {
- cachedData = await this.cache_.loadCache(this.context_.config.id);
- }
-
// 1. Load SDK
this.progress_.setCurrentTask('Loading SDK...', 0);
const wasmSdk = await this.loadSdk();
@@ -201,23 +195,8 @@ export class PlayableBuilder {
this.progress_.setPhase('compiling');
this.progress_.setCurrentTask('Compiling scripts...', 0);
- let gameCode: string;
- const scriptsPath = joinPath(this.projectDir_, 'src');
- const scriptFiles = await this.getScriptFiles(scriptsPath);
-
- if (cachedData?.compiledScripts && this.cache_) {
- const changes = await this.cache_.getChangedFiles(scriptFiles, cachedData);
- if (!this.cache_.hasChanges(changes)) {
- gameCode = cachedData.compiledScripts;
- this.progress_.log('info', 'Using cached compiled scripts');
- } else {
- gameCode = await this.compileUserScripts();
- this.progress_.log('info', `Scripts compiled: ${gameCode.length} bytes`);
- }
- } else {
- gameCode = await this.compileUserScripts();
- this.progress_.log('info', `Scripts compiled: ${gameCode.length} bytes`);
- }
+ const gameCode = await this.compileUserScripts();
+ this.progress_.log('info', `Scripts compiled: ${gameCode.length} bytes`);
// 3. Read startup scene
this.progress_.setCurrentTask('Loading scene...', 50);
@@ -288,15 +267,6 @@ export class PlayableBuilder {
const success = await this.fs_.writeFile(outputPath, html);
if (success) {
- if (this.cache_) {
- const cacheData = await this.cache_.createCacheData(
- this.context_.config.id,
- scriptFiles,
- gameCode
- );
- await this.cache_.saveCache(cacheData);
- }
-
this.progress_.log('info', `Build successful: ${outputPath}`);
return {
success: true,
@@ -313,13 +283,6 @@ export class PlayableBuilder {
}
}
- private async getScriptFiles(srcPath: string): Promise<string[]> {
- if (!await this.fs_!.exists(srcPath)) {
- return [];
- }
- return findTsFiles(this.fs_!, srcPath, EDITOR_ONLY_DIRS);
- }
-
// =========================================================================
// Private Methods
// =========================================================================
@@ -545,7 +508,7 @@ ${imports}
}
const packer = new TextureAtlasPacker(this.fs_!, this.projectDir_, this.assetLibrary_);
- const atlasResult = await packer.pack(imagePaths, sceneDataList);
+ const atlasResult = await packer.pack(imagePaths, sceneDataList, 2048, [...assetPaths]);
const packedPaths = new Set<string>(atlasResult.frameMap.keys());
return { atlasResult, packedPaths };
@@ -683,6 +646,5 @@ ${imports}
private fs_: NativeFS | null;
private projectDir_: string;
private progress_: BuildProgressReporter;
- private cache_: BuildCache | null;
private assetLibrary_: AssetLibrary;
}
diff --git a/sdk/src/asset/AssetServer.ts b/sdk/src/asset/AssetServer.ts
index 6522106aa..5609c8947 100644
--- a/sdk/src/asset/AssetServer.ts
+++ b/sdk/src/asset/AssetServer.ts
@@ -8,7 +8,7 @@ import type { ESEngineModule } from '../wasm';
import type { ShaderHandle } from '../material';
import { Material } from '../material';
import { MaterialLoader, type LoadedMaterial, type ShaderLoader } from './MaterialLoader';
-import { platformReadTextFile, platformFileExists, platformFetch, platformCreateCanvas } from '../platform';
+import { platformReadTextFile, platformReadFile, platformFileExists, platformFetch, platformCreateCanvas, platformCreateImage } from '../platform';
import type { World } from '../world';
import { loadSceneWithAssets, type SceneData } from '../scene';
import { AsyncCache } from './AsyncCache';
@@ -82,6 +82,7 @@ export class AssetServer {
private materialLoader_: MaterialLoader;
private canvas_: HTMLCanvasElement;
private ctx_: CanvasRenderingContext2D;
+ private embedded_ = new Map<string, string>();
constructor(module: ESEngineModule) {
this.module_ = module;
@@ -95,6 +96,16 @@ export class AssetServer {
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);
+ }
+ }
+
// =========================================================================
// Texture
// =========================================================================
@@ -176,11 +187,7 @@ export class AssetServer {
try {
const atlasUrl = this.resolveUrl(atlasPath, baseUrl);
- const atlasResponse = await fetch(atlasUrl);
- if (!atlasResponse.ok) {
- return { success: false, error: `Failed to fetch atlas: ${atlasUrl}` };
- }
- const atlasContent = await atlasResponse.text();
+ const atlasContent = await this.fetchText(atlasUrl);
if (!this.writeToVirtualFS(atlasPath, atlasContent)) {
return { success: false, error: `Failed to write atlas to virtual FS: ${atlasPath}` };
@@ -203,15 +210,10 @@ export class AssetServer {
}
const skelUrl = this.resolveUrl(skeletonPath, baseUrl);
- const skelResponse = await fetch(skelUrl);
- if (!skelResponse.ok) {
- return { success: false, error: `Failed to fetch skeleton: ${skelUrl}` };
- }
-
const isBinary = skeletonPath.endsWith('.skel');
const skelData = isBinary
- ? new Uint8Array(await skelResponse.arrayBuffer())
- : await skelResponse.text();
+ ? 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}` };
@@ -370,8 +372,11 @@ export class AssetServer {
}
private async loadImage(source: string): Promise<HTMLImageElement | ImageBitmap> {
+ const localPath = this.isLocalPath(source) ? this.toLocalPath(source) : source;
+ const embedded = this.embedded_.get(localPath);
+ const imgSrc = embedded ?? localPath;
return new Promise((resolve, reject) => {
- const img = new Image();
+ const img = platformCreateImage();
img.crossOrigin = 'anonymous';
img.onload = async () => {
if (typeof createImageBitmap !== 'undefined') {
@@ -389,7 +394,7 @@ export class AssetServer {
resolve(img);
};
img.onerror = () => reject(new Error(`Failed to load image: ${source}`));
- img.src = source;
+ img.src = imgSrc;
});
}
@@ -502,12 +507,13 @@ export class AssetServer {
// =========================================================================
private async loadShaderInternal(path: string): Promise<ShaderHandle> {
- const exists = await platformFileExists(path);
+ const localPath = this.isLocalPath(path) ? this.toLocalPath(path) : path;
+ const exists = await platformFileExists(localPath);
if (!exists) {
throw new Error(`Shader file not found: ${path}`);
}
- const content = await platformReadTextFile(path);
+ const content = await platformReadTextFile(localPath);
if (!content) {
throw new Error(`Failed to read shader file: ${path}`);
}
@@ -533,7 +539,37 @@ export class AssetServer {
// 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://');
+ }
+
+ private toLocalPath(url: string): string {
+ return url.startsWith('/') ? url.substring(1) : url;
+ }
+
private async fetchJson(url: string): Promise<unknown> {
+ const localPath = this.isLocalPath(url) ? this.toLocalPath(url) : null;
+ if (localPath) {
+ const embedded = this.embedded_.get(localPath);
+ if (embedded) {
+ return JSON.parse(this.decodeDataUrlText(embedded));
+ }
+ const text = await platformReadTextFile(localPath);
+ return JSON.parse(text);
+ }
const response = await platformFetch(url);
if (!response.ok) {
throw new Error(`Failed to fetch JSON: ${url} (${response.status})`);
@@ -542,6 +578,14 @@ export class AssetServer {
}
private async fetchText(url: string): Promise<string> {
+ const localPath = this.isLocalPath(url) ? this.toLocalPath(url) : null;
+ if (localPath) {
+ const embedded = this.embedded_.get(localPath);
+ if (embedded) {
+ return this.decodeDataUrlText(embedded);
+ }
+ return platformReadTextFile(localPath);
+ }
const response = await platformFetch(url);
if (!response.ok) {
throw new Error(`Failed to fetch text: ${url} (${response.status})`);
@@ -550,6 +594,14 @@ export class AssetServer {
}
private async fetchBinary(url: string): Promise<ArrayBuffer> {
+ const localPath = this.isLocalPath(url) ? this.toLocalPath(url) : null;
+ if (localPath) {
+ const embedded = this.embedded_.get(localPath);
+ if (embedded) {
+ return this.decodeDataUrlBinary(embedded);
+ }
+ return platformReadFile(localPath);
+ }
const response = await platformFetch(url);
if (!response.ok) {
throw new Error(`Failed to fetch binary: ${url} (${response.status})`);
diff --git a/sdk/src/asset/index.ts b/sdk/src/asset/index.ts
index 8f71717be..1b4ed93bb 100644
--- a/sdk/src/asset/index.ts
+++ b/sdk/src/asset/index.ts
@@ -16,3 +16,13 @@ export {
export { AsyncCache } from './AsyncCache';
export { Assets, AssetPlugin, assetPlugin, type AssetsData } from './AssetPlugin';
export { MaterialLoader, type LoadedMaterial, type ShaderLoader } from './MaterialLoader';
+
+import type { App } from '../app';
+import { Assets } from './AssetPlugin';
+
+export function registerEmbeddedAssets(app: App, assets: Record<string, string>): void {
+ const assetServer = app.getResource(Assets);
+ if (assetServer) {
+ assetServer.registerEmbeddedAssets(assets);
+ }
+}
diff --git a/sdk/src/core.ts b/sdk/src/core.ts
index df1e734c2..497f3ccac 100644
--- a/sdk/src/core.ts
+++ b/sdk/src/core.ts
@@ -180,6 +180,7 @@ export {
AssetPlugin,
assetPlugin,
MaterialLoader,
+ registerEmbeddedAssets,
type TextureInfo,
type SliceBorder,
type SpineLoadResult,