A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
feat: add UUID-based asset library with build-time material compilation
esengine8a7c82e2d5b3
diff --git a/editor/src/Editor.ts b/editor/src/Editor.tsindex ece27d091..2c87f077c 100644--- a/editor/src/Editor.ts+++ b/editor/src/Editor.ts@@ -40,6 +40,7 @@ import { PreviewService } from './preview';import { showBuildSettingsDialog, BuildService } from './builder';import { getGlobalPathResolver } from './asset';import type { EditorAssetServer } from './asset/EditorAssetServer';+import { getAssetLibrary } from './asset/AssetLibrary';import { setEditorInstance, getEditorContext, getEditorInstance } from './context/EditorContext';import { getAllMenus, getMenuItems, getAllStatusbarItems, registerBuiltinMenus } from './menus';import { ShortcutManager } from './menus/ShortcutManager';@@ -116,6 +117,7 @@ export class Editor {if (this.projectPath_) {this.setupEditorGlobals();+ this.initializeAssetLibrary();this.initializeAllScripts();this.previewService_ = new PreviewService({ projectPath: this.projectPath_ });}@@ -218,6 +220,7 @@ export class Editor {async loadScene(): Promise<void> {const scene = await loadSceneFromFile();if (scene) {+ await getAssetLibrary().migrateScene(scene);this.store_.loadScene(scene);}}@@ -225,6 +228,10 @@ export class Editor {async openSceneFromPath(scenePath: string): Promise<void> {const scene = await loadSceneFromPath(scenePath);if (scene) {+ const migrated = await getAssetLibrary().migrateScene(scene);+ if (migrated) {+ await saveSceneToPath(scene, scenePath);+ }this.store_.loadScene(scene, scenePath);console.log('Scene loaded:', scenePath);}@@ -300,6 +307,20 @@ export class Editor {// Script Operations// =========================================================================+ private async initializeAssetLibrary(): Promise<void> {+ if (!this.projectPath_) return;++ const fs = getEditorContext().fs;+ if (!fs) return;++ const projectDir = this.projectPath_.replace(/[/\\][^/\\]+$/, '');+ try {+ await getAssetLibrary().initialize(projectDir, fs);+ } catch (err) {+ console.error('Failed to initialize AssetLibrary:', err);+ }+ }+private async initializeAllScripts(): Promise<void> {await this.initializeExtensions();await this.initializeScripts();diff --git a/editor/src/asset/AssetLibrary.ts b/editor/src/asset/AssetLibrary.tsnew file mode 100644index 000000000..d3a15a011--- /dev/null+++ b/editor/src/asset/AssetLibrary.ts@@ -0,0 +1,333 @@+/**+ * @file AssetLibrary.ts+ * @brief UUID-based asset library with bidirectional path/UUID mapping+ */++import type { SceneData } from '../types/SceneTypes';+import type { TextureMetadata } from '../types/TextureMetadata';++// =============================================================================+// Types+// =============================================================================++interface AssetMeta {+ uuid: string;+ version: string;+ type: string;+ sliceBorder?: { left: number; right: number; top: number; bottom: number };+}++interface NativeFS {+ exists(path: string): Promise<boolean>;+ readFile(path: string): Promise<string | null>;+ writeFile(path: string, content: string): Promise<boolean>;+ listDirectoryDetailed(path: string): Promise<Array<{ name: string; isDirectory: boolean }>>;+}++// =============================================================================+// Path Utilities+// =============================================================================++function normalizePath(path: string): string {+ return path.replace(/\\/g, '/');+}++function joinPath(...parts: string[]): string {+ return normalizePath(parts.join('/').replace(/\/+/g, '/'));+}++function getFileExtension(path: string): string {+ const lastDot = path.lastIndexOf('.');+ return lastDot > 0 ? path.substring(lastDot + 1).toLowerCase() : '';+}++const ASSET_EXTENSIONS = new Set([+ 'png', 'jpg', 'jpeg', 'gif', 'webp', 'svg',+ 'mp3', 'wav', 'ogg',+ 'atlas', 'skel', 'json',+ 'esmaterial', 'esshader',+]);++function getAssetType(path: string): string {+ const ext = getFileExtension(path);+ switch (ext) {+ case 'png': case 'jpg': case 'jpeg': case 'gif': case 'webp': case 'svg':+ return 'texture';+ case 'esmaterial':+ return 'material';+ case 'esshader':+ return 'shader';+ case 'atlas':+ return 'spine-atlas';+ case 'skel':+ return 'spine-skeleton';+ case 'json':+ return 'json';+ case 'mp3': case 'wav': case 'ogg':+ return 'audio';+ default:+ return 'unknown';+ }+}++const UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;++export function isUUID(value: string): boolean {+ return UUID_REGEX.test(value);+}++// =============================================================================+// AssetLibrary+// =============================================================================++export class AssetLibrary {+ private uuidToPath_ = new Map<string, string>();+ private pathToUuid_ = new Map<string, string>();+ private fs_: NativeFS | null = null;+ private projectDir_ = '';++ async initialize(projectDir: string, fs: NativeFS): Promise<void> {+ this.fs_ = fs;+ this.projectDir_ = projectDir;+ this.uuidToPath_.clear();+ this.pathToUuid_.clear();++ const assetsDir = joinPath(projectDir, 'assets');+ if (await fs.exists(assetsDir)) {+ await this.scanDirectory(assetsDir, 'assets');+ }+ }++ getPath(uuid: string): string | undefined {+ return this.uuidToPath_.get(uuid);+ }++ getUuid(path: string): string | undefined {+ return this.pathToUuid_.get(path);+ }++ async ensureMeta(relativePath: string): Promise<string> {+ const existing = this.pathToUuid_.get(relativePath);+ if (existing) return existing;++ if (!this.fs_) {+ throw new Error('AssetLibrary not initialized');+ }++ const fullPath = joinPath(this.projectDir_, relativePath);+ const metaPath = `${fullPath}.meta`;++ if (await this.fs_.exists(metaPath)) {+ const content = await this.fs_.readFile(metaPath);+ if (content) {+ try {+ const meta = JSON.parse(content) as AssetMeta;+ if (meta.uuid) {+ this.register(meta.uuid, relativePath);+ return meta.uuid;+ }+ } catch {+ // Fall through to create new meta+ }+ }+ }++ const uuid = crypto.randomUUID();+ const assetType = getAssetType(relativePath);+ const meta: AssetMeta = {+ uuid,+ version: '1.0',+ type: assetType,+ };++ if (assetType === 'texture') {+ const existingContent = await this.fs_.readFile(metaPath);+ if (existingContent) {+ try {+ const existing = JSON.parse(existingContent);+ if (existing.sliceBorder) {+ meta.sliceBorder = existing.sliceBorder;+ }+ } catch {+ // ignore+ }+ }+ if (!meta.sliceBorder) {+ meta.sliceBorder = { left: 0, right: 0, top: 0, bottom: 0 };+ }+ }++ await this.fs_.writeFile(metaPath, JSON.stringify(meta, null, 2));+ this.register(uuid, relativePath);+ return uuid;+ }++ async migrateScene(scene: SceneData): Promise<boolean> {+ if (scene.version === '2.0') return false;+ if (!this.fs_) return false;++ let changed = false;++ for (const entity of scene.entities) {+ for (const comp of entity.components || []) {+ if (comp.type === 'Sprite' && comp.data) {+ if (typeof comp.data.texture === 'string' && !isUUID(comp.data.texture as string)) {+ const uuid = await this.ensureMeta(comp.data.texture as string);+ comp.data.texture = uuid;+ changed = true;+ }+ if (typeof comp.data.material === 'string' && !isUUID(comp.data.material as string)) {+ const uuid = await this.ensureMeta(comp.data.material as string);+ comp.data.material = uuid;+ changed = true;+ }+ }++ if (comp.type === 'SpineAnimation' && comp.data) {+ if (typeof comp.data.skeletonPath === 'string' && !isUUID(comp.data.skeletonPath as string)) {+ const uuid = await this.ensureMeta(comp.data.skeletonPath as string);+ comp.data.skeletonPath = uuid;+ changed = true;+ }+ if (typeof comp.data.atlasPath === 'string' && !isUUID(comp.data.atlasPath as string)) {+ const uuid = await this.ensureMeta(comp.data.atlasPath as string);+ comp.data.atlasPath = uuid;+ changed = true;+ }+ if (typeof comp.data.material === 'string' && !isUUID(comp.data.material as string)) {+ const uuid = await this.ensureMeta(comp.data.material as string);+ comp.data.material = uuid;+ changed = true;+ }+ }+ }+ }++ if (scene.textureMetadata) {+ const newMetadata: Record<string, TextureMetadata> = {};+ for (const [key, value] of Object.entries(scene.textureMetadata)) {+ if (isUUID(key)) {+ newMetadata[key] = value;+ } else {+ const uuid = await this.ensureMeta(key);+ newMetadata[uuid] = value;+ changed = true;+ }+ }+ scene.textureMetadata = newMetadata;+ }++ if (changed) {+ scene.version = '2.0';+ }++ return changed;+ }++ resolveSceneAssetPaths(scene: SceneData): void {+ for (const entity of scene.entities) {+ for (const comp of entity.components || []) {+ if (comp.type === 'Sprite' && comp.data) {+ if (typeof comp.data.texture === 'string' && isUUID(comp.data.texture as string)) {+ const path = this.getPath(comp.data.texture as string);+ if (path) comp.data.texture = path;+ }+ if (typeof comp.data.material === 'string' && isUUID(comp.data.material as string)) {+ const path = this.getPath(comp.data.material as string);+ if (path) comp.data.material = path;+ }+ }++ if (comp.type === 'SpineAnimation' && comp.data) {+ if (typeof comp.data.skeletonPath === 'string' && isUUID(comp.data.skeletonPath as string)) {+ const path = this.getPath(comp.data.skeletonPath as string);+ if (path) comp.data.skeletonPath = path;+ }+ if (typeof comp.data.atlasPath === 'string' && isUUID(comp.data.atlasPath as string)) {+ const path = this.getPath(comp.data.atlasPath as string);+ if (path) comp.data.atlasPath = path;+ }+ if (typeof comp.data.material === 'string' && isUUID(comp.data.material as string)) {+ const path = this.getPath(comp.data.material as string);+ if (path) comp.data.material = path;+ }+ }+ }+ }++ if (scene.textureMetadata) {+ const resolved: Record<string, TextureMetadata> = {};+ for (const [key, value] of Object.entries(scene.textureMetadata)) {+ if (isUUID(key)) {+ const path = this.getPath(key);+ if (path) {+ resolved[path] = value;+ } else {+ resolved[key] = value;+ }+ } else {+ resolved[key] = value;+ }+ }+ scene.textureMetadata = resolved;+ }+ }++ private register(uuid: string, relativePath: string): void {+ this.uuidToPath_.set(uuid, relativePath);+ this.pathToUuid_.set(relativePath, uuid);+ }++ private async scanDirectory(absolutePath: string, relativePath: string): Promise<void> {+ if (!this.fs_) return;++ const entries = await this.fs_.listDirectoryDetailed(absolutePath);++ for (const entry of entries) {+ const childAbsolute = joinPath(absolutePath, entry.name);+ const childRelative = `${relativePath}/${entry.name}`;++ if (entry.isDirectory) {+ await this.scanDirectory(childAbsolute, childRelative);+ } else if (entry.name.endsWith('.meta')) {+ const content = await this.fs_.readFile(childAbsolute);+ if (content) {+ try {+ const meta = JSON.parse(content) as AssetMeta;+ if (meta.uuid) {+ const assetRelPath = childRelative.replace(/\.meta$/, '');+ this.register(meta.uuid, assetRelPath);+ }+ } catch {+ // Skip invalid meta files+ }+ }+ } else {+ const ext = getFileExtension(entry.name);+ if (ASSET_EXTENSIONS.has(ext)) {+ const metaAbsolute = `${childAbsolute}.meta`;+ if (!await this.fs_.exists(metaAbsolute)) {+ await this.ensureMeta(childRelative);+ }+ }+ }+ }+ }+}++// =============================================================================+// Singleton+// =============================================================================++let instance: AssetLibrary | null = null;++export function getAssetLibrary(): AssetLibrary {+ if (!instance) {+ instance = new AssetLibrary();+ }+ return instance;+}++export function resetAssetLibrary(): void {+ instance = null;+}diff --git a/editor/src/asset/index.ts b/editor/src/asset/index.tsindex c8a7ec9d3..65554e5ad 100644--- a/editor/src/asset/index.ts+++ b/editor/src/asset/index.ts@@ -17,6 +17,13 @@ export {resetDependencyGraph,} from './AssetDependencyGraph';+export {+ AssetLibrary,+ getAssetLibrary,+ resetAssetLibrary,+ isUUID,+} from './AssetLibrary';+import { AssetPathResolver } from './AssetPathResolver';let globalPathResolver: AssetPathResolver | null = null;diff --git a/editor/src/builder/AssetCollector.ts b/editor/src/builder/AssetCollector.tsnew file mode 100644index 000000000..d659787d1--- /dev/null+++ b/editor/src/builder/AssetCollector.ts@@ -0,0 +1,346 @@+/**+ * @file AssetCollector.ts+ * @brief Asset export pipeline: config, reference collection, and build-time asset gathering+ */++import type { BuildConfig } from '../types/BuildTypes';+import { type AssetLibrary, isUUID } from '../asset/AssetLibrary';++// =============================================================================+// Types+// =============================================================================++export type FolderExportMode = 'auto' | 'always' | 'exclude';++export interface AssetExportConfig {+ version: '1.0';+ folders: Record<string, FolderExportMode>;+}++interface NativeFS {+ exists(path: string): Promise<boolean>;+ readFile(path: string): Promise<string | null>;+ writeFile(path: string, content: string): Promise<boolean>;+ createDirectory(path: string): Promise<boolean>;+ listDirectoryDetailed(path: string): Promise<Array<{ name: string; isDirectory: boolean }>>;+}++// =============================================================================+// Path Utilities+// =============================================================================++function normalizePath(path: string): string {+ return path.replace(/\\/g, '/');+}++function joinPath(...parts: string[]): string {+ return normalizePath(parts.join('/').replace(/\/+/g, '/'));+}++function isAbsolutePath(path: string): boolean {+ return path.startsWith('/') || /^[a-zA-Z]:/.test(path);+}++function getFileExtension(path: string): string {+ const lastDot = path.lastIndexOf('.');+ return lastDot > 0 ? path.substring(lastDot + 1).toLowerCase() : '';+}++function getDirName(path: string): string {+ const lastSlash = path.lastIndexOf('/');+ return lastSlash > 0 ? path.substring(0, lastSlash) : '';+}++const ASSET_EXTENSIONS = new Set([+ 'png', 'jpg', 'jpeg', 'gif', 'webp', 'svg',+ 'mp3', 'wav', 'ogg',+ 'atlas', 'skel', 'json',+ 'esmaterial', 'esshader',+]);++function looksLikeAssetPath(value: unknown): value is string {+ if (typeof value !== 'string') return false;+ if (!value.includes('/')) return false;+ const ext = getFileExtension(value);+ return ASSET_EXTENSIONS.has(ext);+}++// =============================================================================+// AssetExportConfigService+// =============================================================================++const CONFIG_PATH = '.esengine/asset-export.json';++function createDefaultConfig(): AssetExportConfig {+ return { version: '1.0', folders: {} };+}++export class AssetExportConfigService {+ private fs_: NativeFS;+ private projectDir_: string;++ constructor(projectDir: string, fs: NativeFS) {+ this.projectDir_ = projectDir;+ this.fs_ = fs;+ }++ async load(): Promise<AssetExportConfig> {+ const fullPath = joinPath(this.projectDir_, CONFIG_PATH);+ const content = await this.fs_.readFile(fullPath);+ if (!content) return createDefaultConfig();++ try {+ const data = JSON.parse(content);+ return {+ version: '1.0',+ folders: data.folders ?? {},+ };+ } catch {+ return createDefaultConfig();+ }+ }++ async save(config: AssetExportConfig): Promise<void> {+ const dirPath = joinPath(this.projectDir_, '.esengine');+ await this.fs_.createDirectory(dirPath);+ const fullPath = joinPath(this.projectDir_, CONFIG_PATH);+ await this.fs_.writeFile(fullPath, JSON.stringify(config, null, 4));+ }++ async setMode(folderPath: string, mode: FolderExportMode): Promise<void> {+ const config = await this.load();+ if (mode === 'auto') {+ delete config.folders[folderPath];+ } else {+ config.folders[folderPath] = mode;+ }+ await this.save(config);+ }+}++// =============================================================================+// AssetReferenceCollector+// =============================================================================++export class AssetReferenceCollector {+ private fs_: NativeFS;+ private projectDir_: string;+ private assetLibrary_: AssetLibrary | null;++ constructor(fs: NativeFS, projectDir: string, assetLibrary?: AssetLibrary) {+ this.fs_ = fs;+ this.projectDir_ = projectDir;+ this.assetLibrary_ = assetLibrary ?? null;+ }++ private resolveRef(ref: string): string {+ if (this.assetLibrary_ && isUUID(ref)) {+ return this.assetLibrary_.getPath(ref) ?? ref;+ }+ return ref;+ }++ async collectFromScenes(scenePaths: string[]): Promise<Set<string>> {+ const refs = new Set<string>();+ const visited = new Set<string>();++ for (const scenePath of scenePaths) {+ const fullPath = isAbsolutePath(scenePath)+ ? normalizePath(scenePath)+ : joinPath(this.projectDir_, scenePath);++ const content = await this.fs_.readFile(fullPath);+ if (!content) continue;++ try {+ const scene = JSON.parse(content);+ await this.collectSceneRefs(scene, refs, visited);+ } catch {+ continue;+ }+ }++ return refs;+ }++ private async collectSceneRefs(+ scene: Record<string, unknown>,+ refs: Set<string>,+ visited: Set<string>+ ): Promise<void> {+ const entities = scene.entities as Array<{+ components: Array<{ type: string; data: Record<string, unknown> }>;+ }> | undefined;++ if (!entities) return;++ for (const entity of entities) {+ for (const comp of entity.components || []) {+ if (comp.type === 'Sprite' && comp.data) {+ if (typeof comp.data.texture === 'string') {+ refs.add(this.resolveRef(comp.data.texture));+ }+ if (typeof comp.data.material === 'string') {+ await this.collectMaterialRefs(this.resolveRef(comp.data.material), refs, visited);+ }+ }++ if (comp.type === 'SpineAnimation' && comp.data) {+ const skelPath = comp.data.skeletonPath;+ const atlasPath = comp.data.atlasPath;++ if (typeof skelPath === 'string') {+ refs.add(this.resolveRef(skelPath));+ }+ if (typeof atlasPath === 'string') {+ const resolvedAtlas = this.resolveRef(atlasPath);+ refs.add(resolvedAtlas);+ await this.collectAtlasTextures(resolvedAtlas, refs);+ }+ if (typeof comp.data.material === 'string') {+ await this.collectMaterialRefs(this.resolveRef(comp.data.material), refs, visited);+ }+ }+ }+ }++ const textureMetadata = scene.textureMetadata as Record<string, unknown> | undefined;+ if (textureMetadata) {+ for (const key of Object.keys(textureMetadata)) {+ refs.add(this.resolveRef(key));+ }+ }+ }++ private async collectMaterialRefs(+ materialPath: string,+ refs: Set<string>,+ visited: Set<string>+ ): Promise<void> {+ if (visited.has(materialPath)) return;+ visited.add(materialPath);+ refs.add(materialPath);++ const fullPath = isAbsolutePath(materialPath)+ ? materialPath+ : joinPath(this.projectDir_, materialPath);++ const content = await this.fs_.readFile(fullPath);+ if (!content) return;++ try {+ const material = JSON.parse(content);++ if (typeof material.shader === 'string' && material.shader) {+ refs.add(material.shader);+ }++ if (material.properties && typeof material.properties === 'object') {+ for (const value of Object.values(material.properties)) {+ if (looksLikeAssetPath(value)) {+ refs.add(value);+ }+ }+ }+ } catch {+ // Ignore parse errors+ }+ }++ private async collectAtlasTextures(atlasPath: string, refs: Set<string>): Promise<void> {+ const fullPath = isAbsolutePath(atlasPath)+ ? atlasPath+ : joinPath(this.projectDir_, atlasPath);++ const content = await this.fs_.readFile(fullPath);+ if (!content) return;++ const atlasDir = getDirName(atlasPath);+ const lines = content.split('\n');+ for (const rawLine of lines) {+ const line = rawLine.trim();+ if (line && line.indexOf(':') === -1 && (/\.png$/i.test(line) || /\.jpg$/i.test(line))) {+ const texturePath = atlasDir ? `${atlasDir}/${line}` : line;+ refs.add(texturePath);+ }+ }+ }+}++// =============================================================================+// BuildAssetCollector+// =============================================================================++export class BuildAssetCollector {+ private fs_: NativeFS;+ private projectDir_: string;+ private assetLibrary_: AssetLibrary | null;++ constructor(fs: NativeFS, projectDir: string, assetLibrary?: AssetLibrary) {+ this.fs_ = fs;+ this.projectDir_ = projectDir;+ this.assetLibrary_ = assetLibrary ?? null;+ }++ async collect(config: BuildConfig, exportConfig: AssetExportConfig): Promise<Set<string>> {+ const refCollector = new AssetReferenceCollector(this.fs_, this.projectDir_, this.assetLibrary_ ?? undefined);+ const referencedPaths = await refCollector.collectFromScenes(config.scenes);++ const result = new Set<string>();+ const assetsDir = joinPath(this.projectDir_, 'assets');+ if (!await this.fs_.exists(assetsDir)) {+ return result;+ }++ await this.walkDirectory(assetsDir, 'assets', exportConfig, referencedPaths, result);+ return result;+ }++ private getEffectiveMode(+ relativePath: string,+ settings: Record<string, FolderExportMode>+ ): FolderExportMode {+ if (settings[relativePath]) {+ return settings[relativePath];+ }++ let current = relativePath;+ while (current.includes('/')) {+ current = current.substring(0, current.lastIndexOf('/'));+ if (settings[current]) {+ return settings[current];+ }+ }++ return 'auto';+ }++ private async walkDirectory(+ absolutePath: string,+ relativePath: string,+ exportConfig: AssetExportConfig,+ referencedPaths: Set<string>,+ result: Set<string>+ ): Promise<void> {+ const mode = this.getEffectiveMode(relativePath, exportConfig.folders);++ if (mode === 'exclude') return;++ const entries = await this.fs_.listDirectoryDetailed(absolutePath);++ for (const entry of entries) {+ const childAbsolute = joinPath(absolutePath, entry.name);+ const childRelative = `${relativePath}/${entry.name}`;++ if (entry.isDirectory) {+ await this.walkDirectory(childAbsolute, childRelative, exportConfig, referencedPaths, result);+ } else {+ if (mode === 'always') {+ result.add(childRelative);+ } else if (referencedPaths.has(childRelative)) {+ result.add(childRelative);+ }+ }+ }+ }+}diff --git a/editor/src/builder/PlayableBuilder.ts b/editor/src/builder/PlayableBuilder.tsindex cb5e3133f..9125fbbfe 100644--- a/editor/src/builder/PlayableBuilder.ts+++ b/editor/src/builder/PlayableBuilder.ts@@ -6,8 +6,9 @@* 1. Load pre-built esengine.single.js (WASM module loader)* 2. Compile user scripts to IIFE format (with esengine bundled)* 3. Read startup scene JSON- * 4. Collect and inline assets as base64 data URLs- * 5. Assemble final HTML using scene-driven template+ * 4. Compile materials (.esmaterial + .esshader → single JSON)+ * 5. Collect and inline assets as base64 data URLs (keyed by UUID)+ * 6. Assemble final HTML using scene-driven template*/import * as esbuild from 'esbuild-wasm/esm/browser';@@ -16,6 +17,9 @@ import { BuildProgressReporter } from './BuildProgress';import { BuildCache, type BuildCacheData } from './BuildCache';import { getEditorContext } from '../context/EditorContext';import { findTsFiles, EDITOR_ONLY_DIRS } from '../scripting/ScriptLoader';+import { BuildAssetCollector, AssetExportConfigService } from './AssetCollector';+import { TextureAtlasPacker, type AtlasResult } from './TextureAtlas';+import { AssetLibrary, isUUID } from '../asset/AssetLibrary';// =============================================================================// Types@@ -63,6 +67,11 @@ function getDir(filePath: string): string {return lastSlash > 0 ? normalized.substring(0, lastSlash) : normalized;}+function getDirName(path: string): string {+ const lastSlash = path.lastIndexOf('/');+ return lastSlash > 0 ? path.substring(0, lastSlash) : '';+}+// =============================================================================// MIME Types// =============================================================================@@ -167,13 +176,13 @@ async function loadSceneTextures(mod,scene){for(var j=0;j<ent.components.length;j++){var comp=ent.components[j];if(comp.type==='Sprite'&&comp.data.texture&&typeof comp.data.texture==='string'){- var tp=comp.data.texture;- if(!cache[tp]){- var d=__PA__[tp];+ var ref=comp.data.texture;+ if(!cache[ref]){+ var d=__PA__[ref];if(d){- try{cache[tp]=createTextureFromPixels(mod,await loadImagePixels(d))}- catch(e){console.warn('Failed to load texture:',tp,e);cache[tp]=0}- }else{cache[tp]=0}+ try{cache[ref]=createTextureFromPixels(mod,await loadImagePixels(d))}+ catch(e){console.warn('Failed to load texture:',ref,e);cache[ref]=0}+ }else{cache[ref]=0}}}}@@ -188,11 +197,12 @@ async function loadSpineAssets(mod,scene){for(var j=0;j<ent.components.length;j++){var comp=ent.components[j];if(comp.type!=='SpineAnimation'||!comp.data)continue;- var skelPath=comp.data.skeletonPath,atlasPath=comp.data.atlasPath;- if(!skelPath||!atlasPath)continue;- var atlasData=__PA__[atlasPath];+ var skelRef=comp.data.skeletonPath,atlasRef=comp.data.atlasPath;+ if(!skelRef||!atlasRef)continue;+ var atlasData=__PA__[atlasRef];if(atlasData){var atlasContent=decodeText(atlasData);+ var atlasPath=atlasRef;ensureFSDir(mod,atlasPath);mod.FS.writeFile(atlasPath,atlasContent);var texNames=parseAtlasTextures(atlasContent);@@ -208,8 +218,9 @@ async function loadSpineAssets(mod,scene){}}}- var skelData=__PA__[skelPath];+ var skelData=__PA__[skelRef];if(skelData){+ var skelPath=skelRef;ensureFSDir(mod,skelPath);if(skelPath.endsWith('.skel'))mod.FS.writeFile(skelPath,decodeBinary(skelData));else mod.FS.writeFile(skelPath,decodeText(skelData));@@ -218,6 +229,58 @@ async function loadSpineAssets(mod,scene){}}+function loadMaterials(scene){+ var es=window.esengine;+ var materialCache={};+ var shaderCache={};+ for(var i=0;i<scene.entities.length;i++){+ var ent=scene.entities[i];+ for(var j=0;j<ent.components.length;j++){+ var comp=ent.components[j];+ if(!comp.data||typeof comp.data.material!=='string'||!comp.data.material)continue;+ if(comp.type!=='Sprite'&&comp.type!=='SpineAnimation')continue;+ var matRef=comp.data.material;+ if(materialCache[matRef]!==undefined)continue;+ try{+ var matDataUrl=__PA__[matRef];+ if(!matDataUrl){materialCache[matRef]=0;continue}+ var matData=JSON.parse(decodeText(matDataUrl));+ if(!matData.vertexSource||!matData.fragmentSource){materialCache[matRef]=0;continue}+ var shaderKey=matData.vertexSource+matData.fragmentSource;+ var shaderHandle=shaderCache[shaderKey];+ if(!shaderHandle){+ shaderHandle=es.Material.createShader(matData.vertexSource,matData.fragmentSource);+ shaderCache[shaderKey]=shaderHandle;+ }+ materialCache[matRef]=es.Material.createFromAsset(matData,shaderHandle);+ }catch(e){console.warn('Failed to load material:',matRef,e);materialCache[matRef]=0}+ }+ }+ return materialCache;+}++function updateMaterials(world,scene,materialCache,entityMap){+ var es=window.esengine;+ for(var i=0;i<scene.entities.length;i++){+ var ed=scene.entities[i];+ var entity=entityMap.get(ed.id);+ if(entity===undefined)continue;+ for(var j=0;j<ed.components.length;j++){+ var comp=ed.components[j];+ if(!comp.data||typeof comp.data.material!=='string'||!comp.data.material)continue;+ var h=materialCache[comp.data.material]||0;+ if(!h)continue;+ if(comp.type==='Sprite'){+ var sprite=world.get(entity,es.Sprite);+ if(sprite){sprite.material=h;world.insert(entity,es.Sprite,sprite)}+ }else if(comp.type==='SpineAnimation'){+ var spine=world.get(entity,es.SpineAnimation);+ if(spine){spine.material=h;world.insert(entity,es.SpineAnimation,spine)}+ }+ }+ }+}+function updateSpriteTextures(world,scene,cache,entityMap){var es=window.esengine;for(var i=0;i<scene.entities.length;i++){@@ -237,10 +300,10 @@ function updateSpriteTextures(world,scene,cache,entityMap){function applyTextureMetadata(mod,scene,cache){if(!scene.textureMetadata)return;var rm=mod.getResourceManager();- for(var tp in scene.textureMetadata){- var h=cache[tp];+ for(var ref in scene.textureMetadata){+ var h=cache[ref];if(h&&h>0){- var m=scene.textureMetadata[tp];+ var m=scene.textureMetadata[ref];if(m&&m.sliceBorder){var b=m.sliceBorder;rm.setTextureMetadata(h,b.left,b.right,b.top,b.bottom);@@ -265,8 +328,10 @@ function applyTextureMetadata(mod,scene,cache){var textureCache=await loadSceneTextures(Module,__SCENE__);applyTextureMetadata(Module,__SCENE__,textureCache);await loadSpineAssets(Module,__SCENE__);+ var materialCache=loadMaterials(__SCENE__);var entityMap=es.loadSceneData(app.world,__SCENE__);updateSpriteTextures(app.world,__SCENE__,textureCache,entityMap);+ updateMaterials(app.world,__SCENE__,materialCache,entityMap);var screenAspect=c.width/c.height;es.updateCameraAspectRatio(app.world,screenAspect);@@ -288,6 +353,7 @@ export class PlayableBuilder {this.projectDir_ = getProjectDir(context.projectPath);this.progress_ = context.progress || new BuildProgressReporter();this.cache_ = context.cache || null;+ this.assetLibrary_ = new AssetLibrary();}// =========================================================================@@ -313,7 +379,9 @@ export class PlayableBuilder {this.progress_.log('info', 'Starting Playable build...');try {- // Check cache for compiled scripts+ 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);@@ -361,19 +429,42 @@ export class PlayableBuilder {}this.progress_.log('info', `Scene loaded: ${scenePath}`);- // 4. Collect assets+ // 4. Pack texture atlasthis.progress_.setPhase('processing_assets');- this.progress_.setCurrentTask('Collecting assets...', 0);- const assets = await this.collectAssets();+ this.progress_.setCurrentTask('Packing texture atlas...', 0);+ const { atlasResult, packedPaths } = await this.packTextureAtlas();+ if (atlasResult.pages.length > 0) {+ this.progress_.log('info', `Packed ${atlasResult.frameMap.size} textures into ${atlasResult.pages.length} atlas page(s)`);+ }++ // 5. Rewrite scene data with atlas UVs, then resolve all UUID refs to paths+ const sceneData = JSON.parse(sceneContent);+ const packer = new TextureAtlasPacker(this.fs_!, this.projectDir_, this.assetLibrary_);+ packer.rewriteSceneData(sceneData, atlasResult, '');+ this.resolveSceneUUIDs(sceneData);+ const rewrittenScene = JSON.stringify(sceneData);++ // 6. Compile materials+ this.progress_.setCurrentTask('Compiling materials...', 20);+ const compiledMaterials = await this.compileMaterials();+ this.progress_.log('info', `Compiled ${compiledMaterials.size} material(s)`);++ // 7. Collect assets (keyed by UUID, excluding packed textures, adding atlas pages)+ this.progress_.setCurrentTask('Collecting assets...', 30);+ const assets = await this.collectAssets(packedPaths, compiledMaterials);+ for (let i = 0; i < atlasResult.pages.length; i++) {+ const base64 = this.arrayBufferToBase64(atlasResult.pages[i].imageData);+ assets.set(`atlas_${i}.png`, `data:image/png;base64,${base64}`);+ }this.progress_.log('info', `Collected ${assets.size} assets`);- // 5. Assemble HTML+ // 8. Assemble HTMLthis.progress_.setPhase('assembling');this.progress_.setCurrentTask('Assembling HTML...', 0);- const html = this.assembleHTML(wasmSdk, gameCode, sceneContent, assets);+ const html = this.assembleHTML(wasmSdk, gameCode, rewrittenScene, assets);this.progress_.log('info', `HTML assembled: ${html.length} bytes`);- // 6. Write output+ // 9. Write outputthis.progress_.setPhase('writing');this.progress_.setCurrentTask('Writing output...', 0);const outputPath = this.resolveOutputPath(settings.outputPath);@@ -383,7 +474,6 @@ export class PlayableBuilder {const success = await this.fs_.writeFile(outputPath, html);if (success) {- // Save cacheif (this.cache_) {const cacheData = await this.cache_.createCacheData(this.context_.config.id,@@ -457,9 +547,6 @@ export class PlayableBuilder {return this.createMinimalGameCode();}- // Generate entry content that:- // 1. Imports esengine and exposes it globally- // 2. Imports all user scripts (to register components)const imports = scripts.map(p => `import "${p}";`).join('\n');const entryContent = `import * as esengine from 'esengine';@@ -502,7 +589,6 @@ ${imports}return `(function(){var esengine = window.esengine || {};- // Minimal esengine stub if no user scripts})();`;}@@ -539,7 +625,6 @@ ${imports}const baseDir = args.importer ? getDir(args.importer) : args.resolveDir;resolvedPath = joinPath(baseDir, args.path);} else {- // Bare module specifierif (args.path === 'esengine') {resolvedPath = joinPath(projectDir, '.esengine/sdk/index.js');} else if (args.path === 'esengine/wasm') {@@ -600,43 +685,185 @@ ${imports}};}- private async collectAssets(): Promise<Map<string, string>> {- const assets = new Map<string, string>();- const assetsPath = joinPath(this.projectDir_, 'assets');+ private parseEsShader(content: string): { vertex: string | null; fragment: string | null } {+ const vm = content.match(/#pragma\s+vertex\s*([\s\S]*?)#pragma\s+end/);+ const fm = content.match(/#pragma\s+fragment\s*([\s\S]*?)#pragma\s+end/);+ return { vertex: vm ? vm[1].trim() : null, fragment: fm ? fm[1].trim() : null };+ }++ private resolveShaderPath(materialPath: string, shaderPath: string): string {+ if (shaderPath.startsWith('/') || shaderPath.startsWith('assets/')) return shaderPath;+ const dir = getDirName(materialPath);+ return dir ? `${dir}/${shaderPath}` : shaderPath;+ }++ private async compileMaterials(): Promise<Map<string, { uuid: string; compiledJson: string }>> {+ const result = new Map<string, { uuid: string; compiledJson: string }>();+ const configService = new AssetExportConfigService(this.projectDir_, this.fs_!);+ const exportConfig = await configService.load();++ const collector = new BuildAssetCollector(this.fs_!, this.projectDir_, this.assetLibrary_);+ const assetPaths = await collector.collect(this.context_.config, exportConfig);++ for (const relativePath of assetPaths) {+ if (!relativePath.endsWith('.esmaterial')) continue;++ const uuid = this.assetLibrary_.getUuid(relativePath);+ if (!uuid) continue;++ const fullPath = joinPath(this.projectDir_, relativePath);+ const content = await this.fs_!.readFile(fullPath);+ if (!content) continue;++ try {+ const matData = JSON.parse(content);+ if (matData.type !== 'material' || !matData.shader) continue;++ const shaderRelPath = this.resolveShaderPath(relativePath, matData.shader);+ const shaderFullPath = joinPath(this.projectDir_, shaderRelPath);+ const shaderContent = await this.fs_!.readFile(shaderFullPath);+ if (!shaderContent) continue;- if (await this.fs_!.exists(assetsPath)) {- await this.collectAssetsRecursive(assetsPath, 'assets', assets);+ const parsed = this.parseEsShader(shaderContent);+ if (!parsed.vertex || !parsed.fragment) continue;++ const compiled = {+ type: 'material',+ vertexSource: parsed.vertex,+ fragmentSource: parsed.fragment,+ blendMode: matData.blendMode ?? 0,+ depthTest: matData.depthTest ?? false,+ properties: matData.properties ?? {},+ };++ result.set(relativePath, {+ uuid,+ compiledJson: JSON.stringify(compiled),+ });+ } catch {+ console.warn(`[PlayableBuilder] Failed to compile material: ${relativePath}`);+ }}- return assets;+ return result;}- private async collectAssetsRecursive(- dirPath: string,- relativePath: string,- assets: Map<string, string>- ): Promise<void> {- const entries = await this.fs_!.listDirectoryDetailed(dirPath);+ private async packTextureAtlas(): Promise<{ atlasResult: AtlasResult; packedPaths: Set<string> }> {+ const configService = new AssetExportConfigService(this.projectDir_, this.fs_!);+ const exportConfig = await configService.load();- for (const entry of entries) {- const fullPath = joinPath(dirPath, entry.name);- const entryRelativePath = relativePath ? `${relativePath}/${entry.name}` : entry.name;+ const collector = new BuildAssetCollector(this.fs_!, this.projectDir_, this.assetLibrary_);+ const assetPaths = await collector.collect(this.context_.config, exportConfig);- if (entry.isDirectory) {- await this.collectAssetsRecursive(fullPath, entryRelativePath, assets);- } else {- const ext = getFileExtension(entry.name);- const mimeType = MIME_TYPES[ext];-- if (mimeType) {- const binary = await this.fs_!.readBinaryFile(fullPath);- if (binary) {- const base64 = this.arrayBufferToBase64(binary);- const dataUrl = `data:${mimeType};base64,${base64}`;- assets.set(entryRelativePath, dataUrl);+ const imagePaths = [...assetPaths].filter(p => {+ const ext = p.split('.').pop()?.toLowerCase() ?? '';+ return ext === 'png' || ext === 'jpg' || ext === 'jpeg';+ });++ const sceneDataList: Array<{ name: string; data: Record<string, unknown> }> = [];+ for (const scenePath of this.context_.config.scenes) {+ const fullPath = this.resolveScenePath(scenePath);+ const content = await this.fs_!.readFile(fullPath);+ if (content) {+ const name = scenePath.replace(/.*\//, '').replace('.esscene', '');+ sceneDataList.push({ name, data: JSON.parse(content) });+ }+ }++ const packer = new TextureAtlasPacker(this.fs_!, this.projectDir_, this.assetLibrary_);+ const atlasResult = await packer.pack(imagePaths, sceneDataList);++ const packedPaths = new Set<string>(atlasResult.frameMap.keys());+ return { atlasResult, packedPaths };+ }++ private async collectAssets(+ packedPaths: Set<string>,+ compiledMaterials: Map<string, { uuid: string; compiledJson: string }>+ ): Promise<Map<string, string>> {+ const assets = new Map<string, string>();++ const configService = new AssetExportConfigService(this.projectDir_, this.fs_!);+ const exportConfig = await configService.load();++ const collector = new BuildAssetCollector(this.fs_!, this.projectDir_, this.assetLibrary_);+ const assetPaths = await collector.collect(this.context_.config, exportConfig);++ const compiledMaterialPaths = new Set<string>(compiledMaterials.keys());++ for (const relativePath of assetPaths) {+ if (packedPaths.has(relativePath)) continue;+ if (relativePath.endsWith('.esshader')) continue;++ if (compiledMaterialPaths.has(relativePath)) {+ const compiled = compiledMaterials.get(relativePath)!;+ const base64 = btoa(compiled.compiledJson);+ assets.set(relativePath, `data:application/json;base64,${base64}`);+ continue;+ }++ const ext = getFileExtension(relativePath);+ const mimeType = MIME_TYPES[ext];+ if (!mimeType) continue;++ const fullPath = joinPath(this.projectDir_, relativePath);+ const binary = await this.fs_!.readBinaryFile(fullPath);+ if (binary) {+ const base64 = this.arrayBufferToBase64(binary);+ assets.set(relativePath, `data:${mimeType};base64,${base64}`);+ }+ }++ return assets;+ }++ private resolveSceneUUIDs(sceneData: Record<string, unknown>): void {+ const entities = sceneData.entities as Array<{+ components: Array<{ type: string; data: Record<string, unknown> }>;+ }> | undefined;+ if (!entities) return;++ for (const entity of entities) {+ for (const comp of entity.components || []) {+ if (comp.type === 'Sprite' && comp.data) {+ if (typeof comp.data.texture === 'string' && isUUID(comp.data.texture)) {+ const path = this.assetLibrary_.getPath(comp.data.texture);+ if (path) comp.data.texture = path;}+ if (typeof comp.data.material === 'string' && isUUID(comp.data.material)) {+ const path = this.assetLibrary_.getPath(comp.data.material);+ if (path) comp.data.material = path;+ }+ }+ if (comp.type === 'SpineAnimation' && comp.data) {+ if (typeof comp.data.skeletonPath === 'string' && isUUID(comp.data.skeletonPath)) {+ const path = this.assetLibrary_.getPath(comp.data.skeletonPath);+ if (path) comp.data.skeletonPath = path;+ }+ if (typeof comp.data.atlasPath === 'string' && isUUID(comp.data.atlasPath)) {+ const path = this.assetLibrary_.getPath(comp.data.atlasPath);+ if (path) comp.data.atlasPath = path;+ }+ if (typeof comp.data.material === 'string' && isUUID(comp.data.material)) {+ const path = this.assetLibrary_.getPath(comp.data.material);+ if (path) comp.data.material = path;+ }+ }+ }+ }++ const textureMetadata = sceneData.textureMetadata as Record<string, unknown> | undefined;+ if (textureMetadata) {+ const resolved: Record<string, unknown> = {};+ for (const [key, value] of Object.entries(textureMetadata)) {+ if (isUUID(key)) {+ const path = this.assetLibrary_.getPath(key);+ resolved[path ?? key] = value;+ } else {+ resolved[key] = value;}}+ sceneData.textureMetadata = resolved;}}@@ -670,4 +897,5 @@ ${imports}private projectDir_: string;private progress_: BuildProgressReporter;private cache_: BuildCache | null;+ private assetLibrary_: AssetLibrary;}diff --git a/editor/src/builder/TextureAtlas.ts b/editor/src/builder/TextureAtlas.tsnew file mode 100644index 000000000..7c0f48b80--- /dev/null+++ b/editor/src/builder/TextureAtlas.ts@@ -0,0 +1,458 @@+/**+ * @file TextureAtlas.ts+ * @brief Build-time texture atlas packer using MaxRects algorithm+ */++import { type AssetLibrary, isUUID } from '../asset/AssetLibrary';++// =============================================================================+// Types+// =============================================================================++export interface AtlasFrame {+ path: string;+ x: number;+ y: number;+ width: number;+ height: number;+}++export interface AtlasPage {+ width: number;+ height: number;+ frames: AtlasFrame[];+ imageData: Uint8Array;+}++export interface AtlasResult {+ pages: AtlasPage[];+ frameMap: Map<string, { page: number; frame: AtlasFrame }>;+}++interface Rect {+ x: number;+ y: number;+ width: number;+ height: number;+}++interface RectWithId extends Rect {+ id: string;+}++interface NativeFS {+ readFile(path: string): Promise<string | null>;+ readBinaryFile(path: string): Promise<Uint8Array | null>;+}++// =============================================================================+// MaxRects Bin Packing+// =============================================================================++const PADDING = 2;++class MaxRectsBin {+ private width_: number;+ private height_: number;+ private freeRects_: Rect[];+ readonly placed: RectWithId[] = [];++ constructor(width: number, height: number) {+ this.width_ = width;+ this.height_ = height;+ this.freeRects_ = [{ x: 0, y: 0, width, height }];+ }++ insert(width: number, height: number, id: string): RectWithId | null {+ const paddedW = width + PADDING;+ const paddedH = height + PADDING;++ let bestRect: Rect | null = null;+ let bestShortSide = Infinity;+ let bestLongSide = Infinity;+ let bestIndex = -1;++ for (let i = 0; i < this.freeRects_.length; i++) {+ const free = this.freeRects_[i];+ if (paddedW <= free.width && paddedH <= free.height) {+ const leftoverH = free.height - paddedH;+ const leftoverW = free.width - paddedW;+ const shortSide = Math.min(leftoverH, leftoverW);+ const longSide = Math.max(leftoverH, leftoverW);++ if (shortSide < bestShortSide ||+ (shortSide === bestShortSide && longSide < bestLongSide)) {+ bestRect = { x: free.x, y: free.y, width: paddedW, height: paddedH };+ bestShortSide = shortSide;+ bestLongSide = longSide;+ bestIndex = i;+ }+ }+ }++ if (!bestRect || bestIndex < 0) return null;++ const result: RectWithId = {+ x: bestRect.x,+ y: bestRect.y,+ width,+ height,+ id,+ };++ this.splitFreeRects(bestRect);+ this.pruneFreeRects();+ this.placed.push(result);++ return result;+ }++ private splitFreeRects(used: Rect): void {+ const newFree: Rect[] = [];++ for (let i = this.freeRects_.length - 1; i >= 0; i--) {+ const free = this.freeRects_[i];++ if (used.x >= free.x + free.width || used.x + used.width <= free.x ||+ used.y >= free.y + free.height || used.y + used.height <= free.y) {+ continue;+ }++ this.freeRects_.splice(i, 1);++ if (used.x > free.x) {+ newFree.push({ x: free.x, y: free.y, width: used.x - free.x, height: free.height });+ }+ if (used.x + used.width < free.x + free.width) {+ newFree.push({+ x: used.x + used.width, y: free.y,+ width: free.x + free.width - used.x - used.width, height: free.height,+ });+ }+ if (used.y > free.y) {+ newFree.push({ x: free.x, y: free.y, width: free.width, height: used.y - free.y });+ }+ if (used.y + used.height < free.y + free.height) {+ newFree.push({+ x: free.x, y: used.y + used.height,+ width: free.width, height: free.y + free.height - used.y - used.height,+ });+ }+ }++ this.freeRects_.push(...newFree);+ }++ private pruneFreeRects(): void {+ for (let i = 0; i < this.freeRects_.length; i++) {+ for (let j = i + 1; j < this.freeRects_.length; j++) {+ const a = this.freeRects_[i];+ const b = this.freeRects_[j];+ if (this.contains(b, a)) {+ this.freeRects_.splice(i, 1);+ i--;+ break;+ }+ if (this.contains(a, b)) {+ this.freeRects_.splice(j, 1);+ j--;+ }+ }+ }+ }++ private contains(outer: Rect, inner: Rect): boolean {+ return inner.x >= outer.x && inner.y >= outer.y &&+ inner.x + inner.width <= outer.x + outer.width &&+ inner.y + inner.height <= outer.y + outer.height;+ }+}++// =============================================================================+// TextureAtlasPacker+// =============================================================================++function isPackableImage(path: string): boolean {+ const ext = path.split('.').pop()?.toLowerCase() ?? '';+ return ext === 'png' || ext === 'jpg' || ext === 'jpeg';+}++export class TextureAtlasPacker {+ private fs_: NativeFS;+ private projectDir_: string;+ private assetLibrary_: AssetLibrary | null;++ constructor(fs: NativeFS, projectDir: string, assetLibrary?: AssetLibrary) {+ this.fs_ = fs;+ this.projectDir_ = projectDir;+ this.assetLibrary_ = assetLibrary ?? null;+ }++ private resolveRef(ref: string): string {+ if (this.assetLibrary_ && isUUID(ref)) {+ return this.assetLibrary_.getPath(ref) ?? ref;+ }+ return ref;+ }++ async pack(+ imagePaths: string[],+ sceneDataList: Array<{ name: string; data: Record<string, unknown> }>,+ maxSize: number = 2048+ ): Promise<AtlasResult> {+ const result: AtlasResult = { pages: [], frameMap: new Map() };++ const eligiblePaths = imagePaths.filter(p => isPackableImage(p));+ if (eligiblePaths.length === 0) return result;++ const spineTextures = await this.collectSpineTextures(sceneDataList);+ const nineSliceTextures = this.collectNineSliceTextures(sceneDataList);++ const images: Array<{ path: string; width: number; height: number; data: Uint8Array }> = [];++ for (const relPath of eligiblePaths) {+ if (spineTextures.has(relPath) || nineSliceTextures.has(relPath)) continue;++ const fullPath = this.joinPath(this.projectDir_, relPath);+ const data = await this.fs_.readBinaryFile(fullPath);+ if (!data) continue;++ const size = this.getImageSize(data, relPath);+ if (!size) continue;++ if (size.width > maxSize / 2 || size.height > maxSize / 2) continue;++ images.push({ path: relPath, width: size.width, height: size.height, data });+ }++ if (images.length === 0) return result;++ images.sort((a, b) => Math.max(b.width, b.height) - Math.max(a.width, a.height));++ const bins: MaxRectsBin[] = [];++ for (const img of images) {+ let placed = false;+ for (let i = 0; i < bins.length; i++) {+ const rect = bins[i].insert(img.width, img.height, img.path);+ if (rect) {+ placed = true;+ break;+ }+ }+ if (!placed) {+ const bin = new MaxRectsBin(maxSize, maxSize);+ const rect = bin.insert(img.width, img.height, img.path);+ if (rect) {+ bins.push(bin);+ }+ }+ }++ const imageDataMap = new Map<string, { data: Uint8Array; width: number; height: number }>();+ for (const img of images) {+ imageDataMap.set(img.path, { data: img.data, width: img.width, height: img.height });+ }++ for (let pageIdx = 0; pageIdx < bins.length; pageIdx++) {+ const bin = bins[pageIdx];+ const frames: AtlasFrame[] = [];++ const canvas = new OffscreenCanvas(maxSize, maxSize);+ const ctx = canvas.getContext('2d')!;++ for (const rect of bin.placed) {+ const imgInfo = imageDataMap.get(rect.id);+ if (!imgInfo) continue;++ const blob = new Blob([imgInfo.data.buffer as ArrayBuffer]);+ const bitmap = await createImageBitmap(blob);+ ctx.drawImage(bitmap, rect.x, rect.y);+ bitmap.close();++ const frame: AtlasFrame = {+ path: rect.id,+ x: rect.x,+ y: rect.y,+ width: rect.width,+ height: rect.height,+ };+ frames.push(frame);++ result.frameMap.set(rect.id, { page: pageIdx, frame });+ }++ const pngBlob = await canvas.convertToBlob({ type: 'image/png' });+ const pngData = new Uint8Array(await pngBlob.arrayBuffer());++ result.pages.push({+ width: maxSize,+ height: maxSize,+ frames,+ imageData: pngData,+ });+ }++ return result;+ }++ rewriteSceneData(+ sceneData: Record<string, unknown>,+ atlasResult: AtlasResult,+ atlasPathPrefix: string+ ): void {+ const entities = sceneData.entities as Array<{+ components: Array<{ type: string; data: Record<string, unknown> }>;+ }> | undefined;++ if (!entities) return;++ const metadataUpdates: Array<{ oldKey: string; newPath: string }> = [];++ for (const entity of entities) {+ for (const comp of entity.components || []) {+ if (comp.type !== 'Sprite' || !comp.data) continue;++ const textureRef = comp.data.texture;+ if (typeof textureRef !== 'string') continue;++ const texturePath = this.resolveRef(textureRef);+ const entry = atlasResult.frameMap.get(texturePath);+ if (!entry) continue;++ const page = atlasResult.pages[entry.page];+ const frame = entry.frame;+ const atlasTexturePath = `${atlasPathPrefix}atlas_${entry.page}.png`;++ metadataUpdates.push({ oldKey: textureRef as string, newPath: atlasTexturePath });++ comp.data.texture = atlasTexturePath;+ comp.data.uvOffset = {+ x: frame.x / page.width,+ y: frame.y / page.height,+ };+ comp.data.uvScale = {+ x: frame.width / page.width,+ y: frame.height / page.height,+ };+ }+ }++ const textureMetadata = sceneData.textureMetadata as Record<string, unknown> | undefined;+ if (textureMetadata) {+ for (const { oldKey, newPath } of metadataUpdates) {+ if (textureMetadata[oldKey] && !textureMetadata[newPath]) {+ textureMetadata[newPath] = textureMetadata[oldKey];+ delete textureMetadata[oldKey];+ }+ }+ }+ }++ private async collectSpineTextures(+ sceneDataList: Array<{ name: string; data: Record<string, unknown> }>+ ): Promise<Set<string>> {+ const atlasPaths = new Set<string>();+ for (const { data } of sceneDataList) {+ const entities = data.entities as Array<{+ components: Array<{ type: string; data: Record<string, unknown> }>;+ }> | undefined;+ if (!entities) continue;++ for (const entity of entities) {+ for (const comp of entity.components || []) {+ if (comp.type !== 'SpineAnimation' || !comp.data) continue;+ const atlasPath = comp.data.atlasPath;+ if (typeof atlasPath === 'string') {+ atlasPaths.add(this.resolveRef(atlasPath));+ }+ }+ }+ }++ const result = new Set<string>();+ for (const atlasRelPath of atlasPaths) {+ const fullPath = this.joinPath(this.projectDir_, atlasRelPath);+ const content = await this.fs_.readFile(fullPath);+ if (!content) continue;++ const atlasDir = atlasRelPath.substring(0, atlasRelPath.lastIndexOf('/'));+ const lines = content.split('\n');+ for (const line of lines) {+ const trimmed = line.trim();+ if (trimmed && !trimmed.includes(':') && (/\.png$/i.test(trimmed) || /\.jpg$/i.test(trimmed))) {+ const texPath = atlasDir ? `${atlasDir}/${trimmed}` : trimmed;+ result.add(texPath);+ }+ }+ }+ return result;+ }++ private collectNineSliceTextures(+ sceneDataList: Array<{ name: string; data: Record<string, unknown> }>+ ): Set<string> {+ const result = new Set<string>();+ for (const { data } of sceneDataList) {+ const textureMetadata = data.textureMetadata as Record<string, { sliceBorder?: { left: number; right: number; top: number; bottom: number } }> | undefined;+ if (!textureMetadata) continue;++ for (const [key, metadata] of Object.entries(textureMetadata)) {+ if (metadata?.sliceBorder) {+ const b = metadata.sliceBorder;+ if (b.left > 0 || b.right > 0 || b.top > 0 || b.bottom > 0) {+ result.add(this.resolveRef(key));+ }+ }+ }+ }+ return result;+ }++ private getImageSize(data: Uint8Array, path: string): { width: number; height: number } | null {+ const ext = path.split('.').pop()?.toLowerCase() ?? '';+ if (ext === 'png') return this.getPngSize(data);+ if (ext === 'jpg' || ext === 'jpeg') return this.getJpegSize(data);+ return null;+ }++ private getPngSize(data: Uint8Array): { width: number; height: number } | null {+ if (data.length < 24) return null;+ if (data[0] !== 0x89 || data[1] !== 0x50 || data[2] !== 0x4E || data[3] !== 0x47) return null;++ const width = (data[16] << 24) | (data[17] << 16) | (data[18] << 8) | data[19];+ const height = (data[20] << 24) | (data[21] << 16) | (data[22] << 8) | data[23];+ return { width, height };+ }++ private getJpegSize(data: Uint8Array): { width: number; height: number } | null {+ if (data.length < 2 || data[0] !== 0xFF || data[1] !== 0xD8) return null;++ let offset = 2;+ while (offset < data.length - 1) {+ if (data[offset] !== 0xFF) return null;+ const marker = data[offset + 1];++ if (marker === 0xC0 || marker === 0xC2) {+ if (offset + 9 > data.length) return null;+ const height = (data[offset + 5] << 8) | data[offset + 6];+ const width = (data[offset + 7] << 8) | data[offset + 8];+ return { width, height };+ }++ if (marker === 0xD9) return null;+ if (marker === 0xD0 || (marker >= 0xD0 && marker <= 0xD7) || marker === 0x01) {+ offset += 2;+ continue;+ }++ const segLen = (data[offset + 2] << 8) | data[offset + 3];+ offset += 2 + segLen;+ }+ return null;+ }++ private joinPath(...parts: string[]): string {+ return parts.join('/').replace(/\/+/g, '/').replace(/\\/g, '/');+ }+}diff --git a/editor/src/builder/WeChatBuilder.ts b/editor/src/builder/WeChatBuilder.tsindex cd0d67a2e..28d93f812 100644--- a/editor/src/builder/WeChatBuilder.ts+++ b/editor/src/builder/WeChatBuilder.ts@@ -9,6 +9,9 @@ import { BuildProgressReporter } from './BuildProgress';import { BuildCache } from './BuildCache';import { getEditorContext } from '../context/EditorContext';import { findTsFiles, EDITOR_ONLY_DIRS } from '../scripting/ScriptLoader';+import { BuildAssetCollector, AssetExportConfigService } from './AssetCollector';+import { TextureAtlasPacker, type AtlasResult } from './TextureAtlas';+import { AssetLibrary } from '../asset/AssetLibrary';// =============================================================================// Types@@ -28,6 +31,11 @@ interface NativeFS {getSdkWechatJs(): Promise<string>;}+interface AssetManifestEntry {+ path: string;+ type: string;+}+// =============================================================================// Path Utilities// =============================================================================@@ -46,13 +54,18 @@ function getProjectDir(projectPath: string): string {return lastSlash > 0 ? normalized.substring(0, lastSlash) : normalized;}+function isAbsolutePath(path: string): boolean {+ return path.startsWith('/') || /^[a-zA-Z]:/.test(path);+}+function getFileExtension(path: string): string {const lastDot = path.lastIndexOf('.');return lastDot > 0 ? path.substring(lastDot + 1).toLowerCase() : '';}-function isAbsolutePath(path: string): boolean {- return path.startsWith('/') || /^[a-zA-Z]:/.test(path);+function getDirName(path: string): string {+ const lastSlash = path.lastIndexOf('/');+ return lastSlash > 0 ? path.substring(0, lastSlash) : '';}// =============================================================================@@ -65,6 +78,7 @@ export class WeChatBuilder {private projectDir_: string;private progress_: BuildProgressReporter;private cache_: BuildCache | null;+ private assetLibrary_: AssetLibrary;constructor(context: BuildContext) {this.context_ = context;@@ -72,6 +86,7 @@ export class WeChatBuilder {this.projectDir_ = getProjectDir(context.projectPath);this.progress_ = context.progress || new BuildProgressReporter();this.cache_ = context.cache || null;+ this.assetLibrary_ = new AssetLibrary();}async build(): Promise<BuildResult> {@@ -88,9 +103,10 @@ export class WeChatBuilder {this.progress_.log('info', 'Starting WeChat MiniGame build...');try {- const outputDir = joinPath(this.projectDir_, settings.outputDir);+ await this.assetLibrary_.initialize(this.projectDir_, this.fs_);+ this.progress_.log('info', 'Asset library initialized');- // Create output directory+ const outputDir = joinPath(this.projectDir_, settings.outputDir);await this.fs_.createDirectory(outputDir);// 1. Generate project.config.json@@ -109,18 +125,35 @@ export class WeChatBuilder {await this.generateGameJs(outputDir);this.progress_.log('info', 'Generated game.js');- // 4. Copy scenes+ // 4. Collect assets and pack atlasthis.progress_.setPhase('processing_assets');- this.progress_.setCurrentTask('Copying scenes...', 0);- await this.copyScenes(outputDir);+ this.progress_.setCurrentTask('Packing texture atlas...', 0);+ const { atlasResult, packedPaths } = await this.packTextureAtlas(outputDir);+ if (atlasResult.pages.length > 0) {+ this.progress_.log('info', `Packed ${atlasResult.frameMap.size} textures into ${atlasResult.pages.length} atlas page(s)`);+ }++ // 5. Compile materials+ this.progress_.setCurrentTask('Compiling materials...', 20);+ const compiledMaterials = await this.compileMaterials();+ this.progress_.log('info', `Compiled ${compiledMaterials.size} material(s)`);++ // 6. Copy scenes (with atlas rewriting, UUID preserved)+ this.progress_.setCurrentTask('Copying scenes...', 30);+ await this.copyScenes(outputDir, atlasResult);this.progress_.log('info', 'Copied scenes');- // 5. Copy assets+ // 7. Copy assets (excluding packed textures, .esmaterial, .esshader)this.progress_.setCurrentTask('Copying assets...', 50);- await this.copyAssets(outputDir);+ await this.copyAssets(outputDir, packedPaths, compiledMaterials);this.progress_.log('info', 'Copied assets');- // 6. Write output+ // 8. Generate asset-manifest.json+ this.progress_.setCurrentTask('Generating asset manifest...', 70);+ await this.generateAssetManifest(outputDir, packedPaths, compiledMaterials, atlasResult);+ this.progress_.log('info', 'Generated asset-manifest.json');++ // 9. Write outputthis.progress_.setPhase('writing');this.progress_.setCurrentTask('Finalizing...', 0);@@ -236,6 +269,12 @@ var ESEngineModule = require('./esengine.js');var SDK = require('./sdk.js');globalThis.__esengine_sdk = SDK;+var manifest = JSON.parse(wx.getFileSystemManager().readFileSync('asset-manifest.json', 'utf-8'));++function resolveAsset(uuid) {+ return manifest[uuid] || null;+}+function createTextureFromPixels(module, result) {var rm = module.getResourceManager();var ptr = module._malloc(result.pixels.length);@@ -252,14 +291,16 @@ async function loadSceneTextures(module, sceneData) {for (var j = 0; j < entity.components.length; j++) {var comp = entity.components[j];if (comp.type === 'Sprite' && comp.data.texture && typeof comp.data.texture === 'string') {- var texturePath = comp.data.texture;- if (!textureCache[texturePath]) {+ var textureRef = comp.data.texture;+ if (!textureCache[textureRef]) {+ var entry = resolveAsset(textureRef);+ var texturePath = entry ? entry.path : textureRef;try {var result = await SDK.wxLoadImagePixels(texturePath);- textureCache[texturePath] = createTextureFromPixels(module, result);+ textureCache[textureRef] = createTextureFromPixels(module, result);} catch (err) {console.warn('Failed to load texture:', texturePath, err);- textureCache[texturePath] = 0;+ textureCache[textureRef] = 0;}}}@@ -290,10 +331,10 @@ function updateSpriteTextures(world, sceneData, textureCache, entityMap) {function applyTextureMetadata(module, sceneData, textureCache) {if (!sceneData.textureMetadata) return;var rm = module.getResourceManager();- for (var texturePath in sceneData.textureMetadata) {- var handle = textureCache[texturePath];+ for (var textureRef in sceneData.textureMetadata) {+ var handle = textureCache[textureRef];if (handle && handle > 0) {- var metadata = sceneData.textureMetadata[texturePath];+ var metadata = sceneData.textureMetadata[textureRef];if (metadata && metadata.sliceBorder) {var border = metadata.sliceBorder;rm.setTextureMetadata(handle, border.left, border.right, border.top, border.bottom);@@ -302,6 +343,123 @@ function applyTextureMetadata(module, sceneData, textureCache) {}}+function ensureFSDir(module, path) {+ var parts = path.split('/');+ var cur = '';+ for (var i = 0; i < parts.length - 1; i++) {+ cur += (cur ? '/' : '') + parts[i];+ try { module.FS.mkdir(cur); } catch(e) {}+ }+}++function parseAtlasTextures(content) {+ var textures = [];+ var lines = content.split('\\n');+ for (var i = 0; i < lines.length; i++) {+ var line = lines[i].trim();+ if (line && line.indexOf(':') === -1 && (/\\.png$/i.test(line) || /\\.jpg$/i.test(line)))+ textures.push(line);+ }+ return textures;+}++async function loadSpineAssets(module, sceneData) {+ var rm = module.getResourceManager();+ var wxfs = wx.getFileSystemManager();+ for (var i = 0; i < sceneData.entities.length; i++) {+ var entity = sceneData.entities[i];+ for (var j = 0; j < entity.components.length; j++) {+ var comp = entity.components[j];+ if (comp.type !== 'SpineAnimation' || !comp.data) continue;+ var skelRef = comp.data.skeletonPath;+ var atlasRef = comp.data.atlasPath;+ if (!skelRef || !atlasRef) continue;+ var skelEntry = resolveAsset(skelRef);+ var atlasEntry = resolveAsset(atlasRef);+ var skelPath = skelEntry ? skelEntry.path : skelRef;+ var atlasPath = atlasEntry ? atlasEntry.path : atlasRef;+ comp.data.skeletonPath = skelPath;+ comp.data.atlasPath = atlasPath;+ try {+ var atlasContent = wxfs.readFileSync(atlasPath, 'utf-8');+ ensureFSDir(module, atlasPath);+ module.FS.writeFile(atlasPath, atlasContent);+ var texNames = parseAtlasTextures(atlasContent);+ var atlasDir = atlasPath.substring(0, atlasPath.lastIndexOf('/'));+ for (var k = 0; k < texNames.length; k++) {+ var texPath = atlasDir + '/' + texNames[k];+ try {+ var result = await SDK.wxLoadImagePixels(texPath, false);+ var handle = createTextureFromPixels(module, result);+ rm.registerTextureWithPath(handle, texPath);+ } catch(e) { console.warn('Failed to load spine texture:', texPath, e); }+ }+ ensureFSDir(module, skelPath);+ if (skelPath.endsWith('.skel')) {+ module.FS.writeFile(skelPath, new Uint8Array(wxfs.readFileSync(skelPath)));+ } else {+ module.FS.writeFile(skelPath, wxfs.readFileSync(skelPath, 'utf-8'));+ }+ } catch(e) { console.warn('Failed to load spine:', skelPath, e); }+ }+ }+}++function loadMaterials(sceneData) {+ var wxfs = wx.getFileSystemManager();+ var materialCache = {};+ var shaderCache = {};+ for (var i = 0; i < sceneData.entities.length; i++) {+ var entity = sceneData.entities[i];+ for (var j = 0; j < entity.components.length; j++) {+ var comp = entity.components[j];+ if (!comp.data || typeof comp.data.material !== 'string' || !comp.data.material) continue;+ if (comp.type !== 'Sprite' && comp.type !== 'SpineAnimation') continue;+ var matRef = comp.data.material;+ if (materialCache[matRef] !== undefined) continue;+ try {+ var entry = resolveAsset(matRef);+ if (!entry) { materialCache[matRef] = 0; continue; }+ var matJson = wxfs.readFileSync(entry.path, 'utf-8');+ var matData = JSON.parse(matJson);+ if (!matData.vertexSource || !matData.fragmentSource) { materialCache[matRef] = 0; continue; }+ var shaderKey = matData.vertexSource + matData.fragmentSource;+ var shaderHandle = shaderCache[shaderKey];+ if (!shaderHandle) {+ shaderHandle = SDK.Material.createShader(matData.vertexSource, matData.fragmentSource);+ shaderCache[shaderKey] = shaderHandle;+ }+ materialCache[matRef] = SDK.Material.createFromAsset(matData, shaderHandle);+ } catch (e) {+ console.warn('Failed to load material:', matRef, e);+ materialCache[matRef] = 0;+ }+ }+ }+ return materialCache;+}++function updateMaterials(world, sceneData, materialCache, entityMap) {+ for (var i = 0; i < sceneData.entities.length; i++) {+ var entityData = sceneData.entities[i];+ var entity = entityMap.get(entityData.id);+ if (entity === undefined) continue;+ for (var j = 0; j < entityData.components.length; j++) {+ var comp = entityData.components[j];+ if (!comp.data || typeof comp.data.material !== 'string' || !comp.data.material) continue;+ var handle = materialCache[comp.data.material] || 0;+ if (!handle) continue;+ if (comp.type === 'Sprite') {+ var sprite = world.get(entity, SDK.Sprite);+ if (sprite) { sprite.material = handle; world.insert(entity, SDK.Sprite, sprite); }+ } else if (comp.type === 'SpineAnimation') {+ var spine = world.get(entity, SDK.SpineAnimation);+ if (spine) { spine.material = handle; world.insert(entity, SDK.SpineAnimation, spine); }+ }+ }+ }+}+(async function() {var canvas = wx.createCanvas();var info = wx.getSystemInfoSync();@@ -347,8 +505,11 @@ function applyTextureMetadata(module, sceneData, textureCache) {var textureCache = await loadSceneTextures(module, sceneData);applyTextureMetadata(module, sceneData, textureCache);+ await loadSpineAssets(module, sceneData);+ var materialCache = loadMaterials(sceneData);var entityMap = SDK.loadSceneData(app.world, sceneData);updateSpriteTextures(app.world, sceneData, textureCache, entityMap);+ updateMaterials(app.world, sceneData, materialCache, entityMap);var screenAspect = canvas.width / canvas.height;SDK.updateCameraAspectRatio(app.world, screenAspect);@@ -493,7 +654,6 @@ function applyTextureMetadata(module, sceneData, textureCache) {}}- // Add extension if missingif (!resolvedPath.endsWith('.ts') && !resolvedPath.endsWith('.js')) {if (await fs.exists(resolvedPath + '.ts')) {resolvedPath += '.ts';@@ -521,10 +681,115 @@ function applyTextureMetadata(module, sceneData, textureCache) {};}- private async copyScenes(outputDir: string): Promise<void> {+ private async compileMaterials(): Promise<Map<string, { uuid: string; outputPath: string; json: string }>> {+ const result = new Map<string, { uuid: string; outputPath: string; json: string }>();+ const configService = new AssetExportConfigService(this.projectDir_, this.fs_!);+ const exportConfig = await configService.load();++ const collector = new BuildAssetCollector(this.fs_!, this.projectDir_, this.assetLibrary_);+ const assetPaths = await collector.collect(this.context_.config, exportConfig);++ for (const relativePath of assetPaths) {+ if (!relativePath.endsWith('.esmaterial')) continue;++ const uuid = this.assetLibrary_.getUuid(relativePath);+ if (!uuid) continue;++ const fullPath = joinPath(this.projectDir_, relativePath);+ const content = await this.fs_!.readFile(fullPath);+ if (!content) continue;++ try {+ const matData = JSON.parse(content);+ if (matData.type !== 'material' || !matData.shader) continue;++ const shaderRelPath = this.resolveShaderPath(relativePath, matData.shader);+ const shaderFullPath = joinPath(this.projectDir_, shaderRelPath);+ const shaderContent = await this.fs_!.readFile(shaderFullPath);+ if (!shaderContent) continue;++ const parsed = this.parseEsShader(shaderContent);+ if (!parsed.vertex || !parsed.fragment) continue;++ const compiled = {+ type: 'material',+ vertexSource: parsed.vertex,+ fragmentSource: parsed.fragment,+ blendMode: matData.blendMode ?? 0,+ depthTest: matData.depthTest ?? false,+ properties: matData.properties ?? {},+ };++ const outputRelPath = relativePath.replace(/\.esmaterial$/, '.json');+ result.set(relativePath, {+ uuid,+ outputPath: outputRelPath,+ json: JSON.stringify(compiled, null, 2),+ });+ } catch {+ console.warn(`[WeChatBuilder] Failed to compile material: ${relativePath}`);+ }+ }++ return result;+ }++ private parseEsShader(content: string): { vertex: string | null; fragment: string | null } {+ const vm = content.match(/#pragma\s+vertex\s*([\s\S]*?)#pragma\s+end/);+ const fm = content.match(/#pragma\s+fragment\s*([\s\S]*?)#pragma\s+end/);+ return { vertex: vm ? vm[1].trim() : null, fragment: fm ? fm[1].trim() : null };+ }++ private resolveShaderPath(materialPath: string, shaderPath: string): string {+ if (shaderPath.startsWith('/') || shaderPath.startsWith('assets/')) return shaderPath;+ const dir = getDirName(materialPath);+ return dir ? `${dir}/${shaderPath}` : shaderPath;+ }++ private async packTextureAtlas(+ outputDir: string+ ): Promise<{ atlasResult: AtlasResult; packedPaths: Set<string> }> {+ const configService = new AssetExportConfigService(this.projectDir_, this.fs_!);+ const exportConfig = await configService.load();++ const collector = new BuildAssetCollector(this.fs_!, this.projectDir_, this.assetLibrary_);+ const assetPaths = await collector.collect(this.context_.config, exportConfig);++ const imagePaths = [...assetPaths].filter(p => {+ const ext = p.split('.').pop()?.toLowerCase() ?? '';+ return ext === 'png' || ext === 'jpg' || ext === 'jpeg';+ });++ const sceneDataList: Array<{ name: string; data: Record<string, unknown> }> = [];+ for (const scenePath of this.context_.config.scenes) {+ const fullPath = isAbsolutePath(scenePath)+ ? normalizePath(scenePath)+ : joinPath(this.projectDir_, scenePath);+ const content = await this.fs_!.readFile(fullPath);+ if (content) {+ const name = scenePath.replace(/.*\//, '').replace('.esscene', '');+ sceneDataList.push({ name, data: JSON.parse(content) });+ }+ }++ const packer = new TextureAtlasPacker(this.fs_!, this.projectDir_, this.assetLibrary_);+ const atlasResult = await packer.pack(imagePaths, sceneDataList);++ for (let i = 0; i < atlasResult.pages.length; i++) {+ const atlasPath = joinPath(outputDir, `atlas_${i}.png`);+ await this.fs_!.writeBinaryFile(atlasPath, atlasResult.pages[i].imageData);+ }++ const packedPaths = new Set<string>(atlasResult.frameMap.keys());+ return { atlasResult, packedPaths };+ }++ private async copyScenes(outputDir: string, atlasResult: AtlasResult): Promise<void> {const scenesDir = joinPath(outputDir, 'scenes');await this.fs_!.createDirectory(scenesDir);+ const packer = new TextureAtlasPacker(this.fs_!, this.projectDir_, this.assetLibrary_);+for (const scenePath of this.context_.config.scenes) {const fullPath = isAbsolutePath(scenePath)? normalizePath(scenePath)@@ -533,97 +798,128 @@ function applyTextureMetadata(module, sceneData, textureCache) {const content = await this.fs_!.readFile(fullPath);if (content) {const name = scenePath.replace(/.*\//, '').replace('.esscene', '');- const encodedContent = this.encodeTexturePathsInScene(content);- await this.fs_!.writeFile(joinPath(scenesDir, `${name}.json`), encodedContent);+ const sceneData = JSON.parse(content);+ packer.rewriteSceneData(sceneData, atlasResult, '');+ await this.fs_!.writeFile(joinPath(scenesDir, `${name}.json`), JSON.stringify(sceneData, null, 2));}}}- private encodeTexturePathsInScene(sceneJson: string): string {- try {- const scene = JSON.parse(sceneJson);- for (const entity of scene.entities || []) {- for (const comp of entity.components || []) {- if (comp.type === 'Sprite' && comp.data?.texture) {- comp.data.texture = this.encodeAssetPath(comp.data.texture);+ private async copyAssets(+ outputDir: string,+ packedPaths: Set<string>,+ compiledMaterials: Map<string, { uuid: string; outputPath: string; json: string }>+ ): Promise<void> {+ const configService = new AssetExportConfigService(this.projectDir_, this.fs_!);+ const exportConfig = await configService.load();++ const collector = new BuildAssetCollector(this.fs_!, this.projectDir_, this.assetLibrary_);+ const assetPaths = await collector.collect(this.context_.config, exportConfig);++ const compiledMaterialPaths = new Set<string>();+ const compiledShaderPaths = new Set<string>();+ for (const [matPath, compiled] of compiledMaterials) {+ compiledMaterialPaths.add(matPath);+ const fullPath = joinPath(this.projectDir_, matPath);+ const content = await this.fs_!.readFile(fullPath);+ if (content) {+ try {+ const matData = JSON.parse(content);+ if (matData.shader) {+ compiledShaderPaths.add(this.resolveShaderPath(matPath, matData.shader));}+ } catch {+ // ignore}}- if (scene.textureMetadata) {- const encodedMetadata: Record<string, unknown> = {};- for (const [path, metadata] of Object.entries(scene.textureMetadata)) {- encodedMetadata[this.encodeAssetPath(path)] = metadata;- }- scene.textureMetadata = encodedMetadata;- }- return JSON.stringify(scene, null, 2);- } catch {- return sceneJson;}- }- private encodeAssetPath(path: string): string {- if (!path || typeof path !== 'string') return path;- const parts = path.split('/');- const encodedParts = parts.map(part => {- const dotIndex = part.lastIndexOf('.');- if (dotIndex > 0) {- const name = part.substring(0, dotIndex);- const ext = part.substring(dotIndex);- return encodeURIComponent(name) + ext;- }- return encodeURIComponent(part);- });- return encodedParts.join('/');- }+ for (const relativePath of assetPaths) {+ if (packedPaths.has(relativePath)) continue;+ if (compiledMaterialPaths.has(relativePath)) continue;+ if (compiledShaderPaths.has(relativePath)) continue;+ if (relativePath.endsWith('.esshader')) continue;- private async copyAssets(outputDir: string): Promise<void> {- const srcTexturesPath = joinPath(this.projectDir_, 'assets/textures');- const destTexturesPath = joinPath(outputDir, 'assets/textures');+ const srcPath = joinPath(this.projectDir_, relativePath);+ const destPath = joinPath(outputDir, relativePath);- if (await this.fs_!.exists(srcTexturesPath)) {- await this.copyDirectoryRecursive(srcTexturesPath, destTexturesPath);- }+ const destDir = destPath.substring(0, destPath.lastIndexOf('/'));+ await this.fs_!.createDirectory(destDir);- const srcAudioPath = joinPath(this.projectDir_, 'assets/audio');- const destAudioPath = joinPath(outputDir, 'assets/audio');+ const data = await this.fs_!.readBinaryFile(srcPath);+ if (data) {+ await this.fs_!.writeBinaryFile(destPath, data);+ }+ }- if (await this.fs_!.exists(srcAudioPath)) {- await this.copyDirectoryRecursive(srcAudioPath, destAudioPath);+ for (const [, compiled] of compiledMaterials) {+ const destPath = joinPath(outputDir, compiled.outputPath);+ const destDir = destPath.substring(0, destPath.lastIndexOf('/'));+ await this.fs_!.createDirectory(destDir);+ await this.fs_!.writeFile(destPath, compiled.json);}}- private async copyDirectoryRecursive(srcDir: string, destDir: string): Promise<void> {- await this.fs_!.createDirectory(destDir);-- const entries = await this.fs_!.listDirectoryDetailed(srcDir);+ private async generateAssetManifest(+ outputDir: string,+ packedPaths: Set<string>,+ compiledMaterials: Map<string, { uuid: string; outputPath: string; json: string }>,+ atlasResult: AtlasResult+ ): Promise<void> {+ const manifest: Record<string, AssetManifestEntry> = {};++ const configService = new AssetExportConfigService(this.projectDir_, this.fs_!);+ const exportConfig = await configService.load();+ const collector = new BuildAssetCollector(this.fs_!, this.projectDir_, this.assetLibrary_);+ const assetPaths = await collector.collect(this.context_.config, exportConfig);++ for (const relativePath of assetPaths) {+ if (relativePath.endsWith('.esshader')) continue;++ const uuid = this.assetLibrary_.getUuid(relativePath);+ if (!uuid) continue;++ if (packedPaths.has(relativePath)) {+ const entry = atlasResult.frameMap.get(relativePath);+ if (entry) {+ manifest[uuid] = {+ path: `atlas_${entry.page}.png`,+ type: 'texture',+ };+ }+ continue;+ }- for (const entry of entries) {- const srcPath = joinPath(srcDir, entry.name);- const encodedName = this.encodeFileName(entry.name);- const destPath = joinPath(destDir, encodedName);+ const compiled = compiledMaterials.get(relativePath);+ if (compiled) {+ manifest[uuid] = {+ path: compiled.outputPath,+ type: 'material',+ };+ continue;+ }- if (entry.isDirectory) {- await this.copyDirectoryRecursive(srcPath, destPath);- } else {- const ext = getFileExtension(entry.name);- if (['png', 'jpg', 'jpeg', 'gif', 'webp', 'mp3', 'wav', 'ogg'].includes(ext)) {- const data = await this.fs_!.readBinaryFile(srcPath);- if (data) {- await this.fs_!.writeBinaryFile(destPath, data);- }- }+ const ext = getFileExtension(relativePath);+ let type = 'unknown';+ switch (ext) {+ case 'png': case 'jpg': case 'jpeg': case 'gif': case 'webp': case 'svg':+ type = 'texture'; break;+ case 'atlas': type = 'spine-atlas'; break;+ case 'skel': type = 'spine-skeleton'; break;+ case 'json': type = 'json'; break;+ case 'mp3': case 'wav': case 'ogg': type = 'audio'; break;}- }- }- private encodeFileName(name: string): string {- const dotIndex = name.lastIndexOf('.');- if (dotIndex > 0) {- const baseName = name.substring(0, dotIndex);- const ext = name.substring(dotIndex);- return encodeURIComponent(baseName) + ext;+ manifest[uuid] = {+ path: relativePath,+ type,+ };}- return encodeURIComponent(name);++ await this.fs_!.writeFile(+ joinPath(outputDir, 'asset-manifest.json'),+ JSON.stringify(manifest, null, 2)+ );}+}diff --git a/editor/src/builder/index.ts b/editor/src/builder/index.tsindex a83e82757..fc8cfd0d1 100644--- a/editor/src/builder/index.ts+++ b/editor/src/builder/index.ts@@ -17,3 +17,6 @@ export { BuildConfigIO, downloadConfigsAsFile, uploadConfigsFromFile, type Exporexport { BuildHistory, formatBuildTime, formatBuildDuration, getBuildStatusIcon, getBuildStatusClass, type BuildHistoryEntry, type BuildStatus } from './BuildHistory';export { BUILD_TEMPLATES, getTemplates, getTemplatesByPlatform, getTemplate, createConfigFromTemplate, applyTemplateToConfig, getTemplateIconSvg, type BuildTemplate } from './BuildTemplates';export { BatchBuilder, ParallelBatchBuilder, type BatchBuildResult, type ConfigBuildResult, type BatchBuildProgress } from './BatchBuilder';+export { AssetExportConfigService, AssetReferenceCollector, BuildAssetCollector, type FolderExportMode, type AssetExportConfig } from './AssetCollector';+export { TextureAtlasPacker, type AtlasFrame, type AtlasPage, type AtlasResult } from './TextureAtlas';+export { AssetLibrary, getAssetLibrary, resetAssetLibrary, isUUID } from '../asset/AssetLibrary';diff --git a/editor/src/io/SceneSerializer.ts b/editor/src/io/SceneSerializer.tsindex bd580d222..18a7dfb1f 100644--- a/editor/src/io/SceneSerializer.ts+++ b/editor/src/io/SceneSerializer.ts@@ -26,6 +26,9 @@ export class SceneSerializer {if (!scene.version) {scene.version = '1.0';}+ if (scene.version !== '1.0' && scene.version !== '2.0') {+ scene.version = '1.0';+ }if (!scene.name) {scene.name = 'Untitled';}diff --git a/editor/src/panels/ContentBrowserPanel.ts b/editor/src/panels/ContentBrowserPanel.tsindex 0a61e66a5..2812f3476 100644--- a/editor/src/panels/ContentBrowserPanel.ts+++ b/editor/src/panels/ContentBrowserPanel.ts@@ -972,7 +972,7 @@ void main() {const entries = await fs.listDirectoryDetailed(this.currentPath_);return entries- .filter(e => !e.name.startsWith('.'))+ .filter(e => !e.name.startsWith('.') && !e.name.endsWith('.meta')).sort((a, b) => {if (a.isDirectory !== b.isDirectory) {return a.isDirectory ? -1 : 1;diff --git a/editor/src/preview/PreviewService.ts b/editor/src/preview/PreviewService.tsindex d73affc7b..3f4c60a0c 100644--- a/editor/src/preview/PreviewService.ts+++ b/editor/src/preview/PreviewService.ts@@ -8,6 +8,7 @@ import type { NativeFS } from '../scripting/types';import type { TextureMetadata } from '../types/TextureMetadata';import { getMetaFilePath, parseTextureMetadata } from '../types/TextureMetadata';import { getEditorContext } from '../context/EditorContext';+import { getAssetLibrary } from '../asset/AssetLibrary';// =============================================================================// Types@@ -86,10 +87,12 @@ export class PreviewService {): Promise<void> {await this.ensureDirectory(fs, this.previewDir_);- // Collect texture metadata- const textureMetadata = await this.collectTextureMetadata(fs, scene);+ const resolvedScene = JSON.parse(JSON.stringify(scene));+ getAssetLibrary().resolveSceneAssetPaths(resolvedScene);++ const textureMetadata = await this.collectTextureMetadata(fs, resolvedScene);const sceneWithMetadata: SceneData = {- ...scene,+ ...resolvedScene,textureMetadata: Object.keys(textureMetadata).length > 0 ? textureMetadata : undefined,};diff --git a/editor/src/property/editors.ts b/editor/src/property/editors.tsindex 1e6587995..1c861bda5 100644--- a/editor/src/property/editors.ts+++ b/editor/src/property/editors.ts@@ -10,6 +10,7 @@ import {} from './PropertyEditor';import { getEditorContext, getEditorInstance } from '../context/EditorContext';import { getPlatformAdapter } from '../platform/PlatformAdapter';+import { getAssetLibrary, isUUID } from '../asset/AssetLibrary';// =============================================================================// Drag Helper@@ -682,6 +683,23 @@ function getMimeType(path: string): string {}}+function resolveDisplayName(ref: string): string {+ if (!ref) return '';+ if (isUUID(ref)) {+ const path = getAssetLibrary().getPath(ref);+ return path ?? ref;+ }+ return ref;+}++function resolveToPath(ref: string): string {+ if (!ref) return '';+ if (isUUID(ref)) {+ return getAssetLibrary().getPath(ref) ?? ref;+ }+ return ref;+}+function createTextureEditor(container: HTMLElement,ctx: PropertyEditorContext@@ -706,7 +724,7 @@ function createTextureEditor(const input = document.createElement('input');input.type = 'text';input.className = 'es-input es-input-texture es-asset-link';- input.value = (value && typeof value === 'string') ? value : '';+ input.value = (value && typeof value === 'string') ? resolveDisplayName(value) : '';input.placeholder = 'None';input.readOnly = true;@@ -720,7 +738,7 @@ function createTextureEditor(clearBtn.title = 'Clear';clearBtn.innerHTML = `<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line></svg>`;- const updatePreview = async (texturePath: string) => {+ const updatePreview = async (textureRef: string) => {if (currentBlobUrl) {URL.revokeObjectURL(currentBlobUrl);currentBlobUrl = null;@@ -728,6 +746,7 @@ function createTextureEditor(const projectDir = getProjectDir();const fs = getNativeFS();+ const texturePath = resolveToPath(textureRef);if (texturePath && projectDir && fs) {const fullPath = `${projectDir}/${texturePath}`;@@ -753,12 +772,12 @@ function createTextureEditor(const navigateToAssetPath = async (e: Event) => {e.stopPropagation();- const texturePath = input.value;- if (!texturePath) return;+ const displayPath = input.value;+ if (!displayPath) return;const editor = getEditorInstance();if (editor?.navigateToAsset) {- await editor.navigateToAsset(texturePath);+ await editor.navigateToAsset(displayPath);}};@@ -795,9 +814,11 @@ function createTextureEditor(const projectDir = getProjectDir();if (projectDir && assetData.path.startsWith(projectDir)) {const relativePath = assetData.path.substring(projectDir.length + 1);+ const uuid = getAssetLibrary().getUuid(relativePath);+ const ref = uuid ?? relativePath;input.value = relativePath;- onChange(relativePath);- updatePreview(relativePath);+ onChange(ref);+ updatePreview(ref);}}} catch (err) {@@ -823,9 +844,11 @@ function createTextureEditor(const assetsIndex = normalizedPath.indexOf('/assets/');if (assetsIndex !== -1) {const relativePath = normalizedPath.substring(assetsIndex + 1);+ const uuid = getAssetLibrary().getUuid(relativePath);+ const ref = uuid ?? relativePath;input.value = relativePath;- onChange(relativePath);- updatePreview(relativePath);+ onChange(ref);+ updatePreview(ref);}}} catch (err) {@@ -849,7 +872,7 @@ function createTextureEditor(return {update(v: unknown) {const newValue = String(v ?? '');- input.value = newValue;+ input.value = resolveDisplayName(newValue);updatePreview(newValue);},dispose() {@@ -970,7 +993,7 @@ function createSpineFileEditor(const input = document.createElement('input');input.type = 'text';input.className = 'es-input es-input-file';- input.value = String(value ?? '');+ input.value = resolveDisplayName(String(value ?? ''));input.placeholder = 'None';const browseBtn = document.createElement('button');@@ -1006,8 +1029,10 @@ function createSpineFileEditor(const assetsIndex = normalizedPath.indexOf('/assets/');if (assetsIndex !== -1) {const relativePath = normalizedPath.substring(assetsIndex + 1);+ const uuid = getAssetLibrary().getUuid(relativePath);+ const ref = uuid ?? relativePath;input.value = relativePath;- onChange(relativePath);+ onChange(ref);}}} catch (err) {@@ -1027,7 +1052,7 @@ function createSpineFileEditor(return {update(v: unknown) {- input.value = String(v ?? '');+ input.value = resolveDisplayName(String(v ?? ''));},dispose() {wrapper.remove();@@ -1117,7 +1142,8 @@ function createSpineAnimationEditor(};const loadAnimations = async () => {- const skeletonPath = getComponentValue?.('skeletonPath') as string;+ const skeletonRef = getComponentValue?.('skeletonPath') as string;+ const skeletonPath = skeletonRef ? resolveToPath(skeletonRef) : '';if (!skeletonPath) {updateOptions([], String(value ?? ''));return;@@ -1208,7 +1234,8 @@ function createSpineSkinEditor(};const loadSkins = async () => {- const skeletonPath = getComponentValue?.('skeletonPath') as string;+ const skeletonRef = getComponentValue?.('skeletonPath') as string;+ const skeletonPath = skeletonRef ? resolveToPath(skeletonRef) : '';if (!skeletonPath) {updateOptions(['default'], String(value ?? 'default'));return;@@ -1275,7 +1302,7 @@ function createMaterialFileEditor(const input = document.createElement('input');input.type = 'text';input.className = 'es-input es-input-file es-asset-link';- input.value = String(value ?? '');+ input.value = resolveDisplayName(String(value ?? ''));input.placeholder = 'None';input.readOnly = true;@@ -1323,8 +1350,10 @@ function createMaterialFileEditor(const projectDir = getProjectDir();if (projectDir && assetData.path.startsWith(projectDir)) {const relativePath = assetData.path.substring(projectDir.length + 1);+ const uuid = getAssetLibrary().getUuid(relativePath);+ const ref = uuid ?? relativePath;input.value = relativePath;- onChange(relativePath);+ onChange(ref);}}} catch (err) {@@ -1350,8 +1379,10 @@ function createMaterialFileEditor(const assetsIndex = normalizedPath.indexOf('/assets/');if (assetsIndex !== -1) {const relativePath = normalizedPath.substring(assetsIndex + 1);+ const uuid = getAssetLibrary().getUuid(relativePath);+ const ref = uuid ?? relativePath;input.value = relativePath;- onChange(relativePath);+ onChange(ref);}}} catch (err) {@@ -1371,7 +1402,7 @@ function createMaterialFileEditor(return {update(v: unknown) {- input.value = String(v ?? '');+ input.value = resolveDisplayName(String(v ?? ''));},dispose() {wrapper.remove();diff --git a/editor/src/scene/EditorSceneManager.ts b/editor/src/scene/EditorSceneManager.tsindex 7289d6b2e..0d3ebd37d 100644--- a/editor/src/scene/EditorSceneManager.ts+++ b/editor/src/scene/EditorSceneManager.ts@@ -21,6 +21,7 @@ import type { SceneData, EntityData, ComponentData } from '../types/SceneTypes';import { EditorAssetServer } from '../asset/EditorAssetServer';import { AssetPathResolver } from '../asset/AssetPathResolver';import { getDependencyGraph } from '../asset/AssetDependencyGraph';+import { getAssetLibrary, isUUID } from '../asset/AssetLibrary';import {Transform,createIdentityTransform,@@ -343,6 +344,13 @@ export class EditorSceneManager {return { x: 1920, y: 1080 };}+ private resolveAssetRef(ref: string): string {+ if (isUUID(ref)) {+ return getAssetLibrary().getPath(ref) ?? ref;+ }+ return ref;+ }+private async syncSprite(entity: Entity, data: any, entityId: number): Promise<void> {let textureHandle = INVALID_TEXTURE as number;let materialHandle = 0;@@ -350,15 +358,17 @@ export class EditorSceneManager {getDependencyGraph().clearEntity(entityId);this.assetServer_.releaseMaterialInstance(entityId);- const texturePath = data.texture;- if (texturePath && typeof texturePath === 'string') {+ const textureRef = data.texture;+ if (textureRef && typeof textureRef === 'string') {+ const texturePath = this.resolveAssetRef(textureRef);const info = await this.assetServer_.loadTexture(texturePath);textureHandle = info.handle;- getDependencyGraph().registerUsage(texturePath, entityId);+ getDependencyGraph().registerUsage(textureRef, entityId);}- const materialPath = data.material;- if (materialPath && typeof materialPath === 'string') {+ const materialRef = data.material;+ if (materialRef && typeof materialRef === 'string') {+ const materialPath = this.resolveAssetRef(materialRef);try {const loaded = await this.assetServer_.loadMaterial(materialPath);const overrides = data.materialOverrides;@@ -370,7 +380,7 @@ export class EditorSceneManager {} else {materialHandle = loaded.handle;}- getDependencyGraph().registerUsage(materialPath, entityId);+ getDependencyGraph().registerUsage(materialRef, entityId);} catch (err) {console.warn(`[EditorSceneManager] Failed to load material: ${materialPath}`, err);}@@ -431,14 +441,17 @@ export class EditorSceneManager {}private async syncSpineAnimation(entity: Entity, data: any, entityId: number): Promise<void> {- const skeletonPath = data.skeletonPath ?? '';- const atlasPath = data.atlasPath ?? '';+ const skeletonRef = data.skeletonPath ?? '';+ const atlasRef = data.atlasPath ?? '';- if (!skeletonPath || !atlasPath) {+ if (!skeletonRef || !atlasRef) {console.warn('[EditorSceneManager] SpineAnimation missing skeleton or atlas path');return;}+ const skeletonPath = this.resolveAssetRef(skeletonRef);+ const atlasPath = this.resolveAssetRef(atlasRef);+getDependencyGraph().clearEntity(entityId);const result = await this.assetServer_.loadSpine(skeletonPath, atlasPath);@@ -447,16 +460,17 @@ export class EditorSceneManager {return;}- getDependencyGraph().registerUsage(skeletonPath, entityId);- getDependencyGraph().registerUsage(atlasPath, entityId);+ getDependencyGraph().registerUsage(skeletonRef, entityId);+ getDependencyGraph().registerUsage(atlasRef, entityId);let materialHandle = 0;- const materialPath = data.material;- if (materialPath && typeof materialPath === 'string') {+ const materialRef = data.material;+ if (materialRef && typeof materialRef === 'string') {+ const materialPath = this.resolveAssetRef(materialRef);try {const loaded = await this.assetServer_.loadMaterial(materialPath);materialHandle = loaded.handle;- getDependencyGraph().registerUsage(materialPath, entityId);+ getDependencyGraph().registerUsage(materialRef, entityId);} catch (err) {console.warn(`[EditorSceneManager] Failed to load material: ${materialPath}`, err);}diff --git a/editor/src/types/SceneTypes.ts b/editor/src/types/SceneTypes.tsindex 4e0620105..65fa6fe03 100644--- a/editor/src/types/SceneTypes.ts+++ b/editor/src/types/SceneTypes.ts@@ -54,7 +54,7 @@ export interface ViewportState {export function createEmptyScene(name: string = 'Untitled'): SceneData {return {- version: '1.0',+ version: '2.0',name,entities: [],};diff --git a/editor/src/types/TextureMetadata.ts b/editor/src/types/TextureMetadata.tsindex 4e699e03b..934b1cccf 100644--- a/editor/src/types/TextureMetadata.ts+++ b/editor/src/types/TextureMetadata.ts@@ -27,6 +27,7 @@ export function hasSlicing(border: SliceBorder): boolean {// =============================================================================export interface TextureMetadata {+ uuid?: string;version: string;type: 'texture';sliceBorder: SliceBorder;@@ -52,7 +53,7 @@ export function parseTextureMetadata(json: string): TextureMetadata | null {try {const data = JSON.parse(json);if (data.type !== 'texture') return null;- return {+ const result: TextureMetadata = {version: data.version ?? '1.0',type: 'texture',sliceBorder: {@@ -62,6 +63,10 @@ export function parseTextureMetadata(json: string): TextureMetadata | null {bottom: data.sliceBorder?.bottom ?? 0}};+ if (data.uuid) {+ result.uuid = data.uuid;+ }+ return result;} catch {return null;}