Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

refactor: extract shared modules to eliminate code duplication

esengine2df92b9c6fcd
diff --git a/editor/src/asset/AssetLibrary.ts b/editor/src/asset/AssetLibrary.ts
index d3a15a011..367c44433 100644
--- a/editor/src/asset/AssetLibrary.ts
+++ b/editor/src/asset/AssetLibrary.ts
@@ -5,6 +5,9 @@
import type { SceneData } from '../types/SceneTypes';
import type { TextureMetadata } from '../types/TextureMetadata';
+import { joinPath, getFileExtension } from '../utils/path';
+import type { NativeFS } from '../types/NativeFS';
+import { ASSET_EXTENSIONS, getAssetType } from './AssetTypes';
// =============================================================================
// Types
@@ -17,59 +20,6 @@ interface AssetMeta {
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 {
diff --git a/editor/src/asset/AssetLoader.ts b/editor/src/asset/AssetLoader.ts
index ab5ad9880..090717063 100644
--- a/editor/src/asset/AssetLoader.ts
+++ b/editor/src/asset/AssetLoader.ts
@@ -6,6 +6,7 @@
import type { ESEngineModule } from 'esengine';
import type { AssetPathResolver } from './AssetPathResolver';
import { getEditorContext } from '../context/EditorContext';
+import type { NativeFS } from '../types/NativeFS';
interface DecodedImage {
width: number;
@@ -13,11 +14,6 @@ interface DecodedImage {
data: Uint8Array;
}
-interface NativeFS {
- readFile(path: string): Promise<string | null>;
- readBinaryFile(path: string): Promise<Uint8Array | null>;
-}
-
export interface LoadResult {
success: boolean;
error?: string;
diff --git a/editor/src/asset/AssetPathResolver.ts b/editor/src/asset/AssetPathResolver.ts
index cca636dee..44181b94f 100644
--- a/editor/src/asset/AssetPathResolver.ts
+++ b/editor/src/asset/AssetPathResolver.ts
@@ -4,12 +4,7 @@
*/
import { getEditorContext } from '../context/EditorContext';
-
-interface NativeFS {
- exists(path: string): Promise<boolean>;
- readFile(path: string): Promise<string | null>;
- readBinaryFile(path: string): Promise<Uint8Array | null>;
-}
+import type { NativeFS } from '../types/NativeFS';
export interface PathValidationResult {
exists: boolean;
diff --git a/editor/src/asset/AssetTypes.ts b/editor/src/asset/AssetTypes.ts
new file mode 100644
index 000000000..61d3f98c6
--- /dev/null
+++ b/editor/src/asset/AssetTypes.ts
@@ -0,0 +1,37 @@
+import { getFileExtension } from '../utils/path';
+
+export const ASSET_EXTENSIONS = new Set([
+ 'png', 'jpg', 'jpeg', 'gif', 'webp', 'svg',
+ 'mp3', 'wav', 'ogg',
+ 'atlas', 'skel', 'json',
+ 'esmaterial', 'esshader',
+]);
+
+export 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';
+ }
+}
+
+export 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);
+}
diff --git a/editor/src/asset/EditorAssetServer.ts b/editor/src/asset/EditorAssetServer.ts
index 4b93f1ef0..45df07546 100644
--- a/editor/src/asset/EditorAssetServer.ts
+++ b/editor/src/asset/EditorAssetServer.ts
@@ -12,11 +12,8 @@ import type { AssetPathResolver } from './AssetPathResolver';
import { parseShaderProperties, getShaderDefaultProperties } from '../shader/ShaderPropertyParser';
import { getAssetEventBus } from '../events/AssetEventBus';
import { getEditorContext } from '../context/EditorContext';
-
-interface NativeFS {
- readFile(path: string): Promise<string | null>;
- exists(path: string): Promise<boolean>;
-}
+import type { NativeFS } from '../types/NativeFS';
+import { parseEsShader, resolveShaderPath } from '../utils/shader';
interface LoadedMaterial {
handle: MaterialHandle;
@@ -177,7 +174,7 @@ export class EditorAssetServer {
throw new Error(`Invalid material file type: ${data.type}`);
}
- const shaderPath = this.resolveShaderPath(path, data.shader);
+ const shaderPath = resolveShaderPath(path, data.shader);
const shaderDefaults = await this.getShaderDefaultProperties(shaderPath);
const mergedProperties = { ...shaderDefaults, ...data.properties };
@@ -230,7 +227,7 @@ export class EditorAssetServer {
throw new Error(`Failed to read shader file: ${fullPath}`);
}
- const { vertex, fragment } = this.parseEsShader(content);
+ const { vertex, fragment } = parseEsShader(content);
if (!vertex || !fragment) {
throw new Error(`Invalid shader format: ${path}`);
}
@@ -240,30 +237,6 @@ export class EditorAssetServer {
return handle;
}
- private parseEsShader(content: string): { vertex: string | null; fragment: string | null } {
- let vertex: string | null = null;
- let fragment: string | null = null;
-
- const vertexMatch = content.match(/#pragma\s+vertex\s*([\s\S]*?)#pragma\s+end/);
- const fragmentMatch = content.match(/#pragma\s+fragment\s*([\s\S]*?)#pragma\s+end/);
-
- if (vertexMatch) {
- vertex = vertexMatch[1].trim();
- }
- if (fragmentMatch) {
- fragment = fragmentMatch[1].trim();
- }
-
- return { vertex, fragment };
- }
-
- private resolveShaderPath(materialPath: string, shaderPath: string): string {
- if (shaderPath.startsWith('/') || shaderPath.startsWith('assets/')) {
- return shaderPath;
- }
- const dir = materialPath.substring(0, materialPath.lastIndexOf('/'));
- return dir ? `${dir}/${shaderPath}` : shaderPath;
- }
private getNativeFS(): NativeFS | null {
return getEditorContext().fs ?? null;
diff --git a/editor/src/builder/AssetCollector.ts b/editor/src/builder/AssetCollector.ts
index d659787d1..e96fcc1a1 100644
--- a/editor/src/builder/AssetCollector.ts
+++ b/editor/src/builder/AssetCollector.ts
@@ -5,6 +5,9 @@
import type { BuildConfig } from '../types/BuildTypes';
import { type AssetLibrary, isUUID } from '../asset/AssetLibrary';
+import { normalizePath, joinPath, isAbsolutePath, getFileExtension, getDirName } from '../utils/path';
+import type { NativeFS } from '../types/NativeFS';
+import { ASSET_EXTENSIONS, looksLikeAssetPath } from '../asset/AssetTypes';
// =============================================================================
// Types
@@ -17,54 +20,6 @@ export interface AssetExportConfig {
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
// =============================================================================
diff --git a/editor/src/builder/MaterialCompiler.ts b/editor/src/builder/MaterialCompiler.ts
new file mode 100644
index 000000000..4ea1bac21
--- /dev/null
+++ b/editor/src/builder/MaterialCompiler.ts
@@ -0,0 +1,68 @@
+import type { NativeFS } from '../types/NativeFS';
+import type { AssetLibrary } from '../asset/AssetLibrary';
+import type { BuildConfig } from '../types/BuildTypes';
+import type { AssetExportConfig } from './AssetCollector';
+import { BuildAssetCollector, AssetExportConfigService } from './AssetCollector';
+import { joinPath } from '../utils/path';
+import { parseEsShader, resolveShaderPath } from '../utils/shader';
+
+export interface CompiledMaterial {
+ relativePath: string;
+ uuid: string;
+ json: string;
+}
+
+export async function compileMaterials(
+ fs: NativeFS,
+ projectDir: string,
+ assetLibrary: AssetLibrary,
+ config: BuildConfig,
+ exportConfig: AssetExportConfig
+): Promise<CompiledMaterial[]> {
+ const results: CompiledMaterial[] = [];
+ const collector = new BuildAssetCollector(fs, projectDir, assetLibrary);
+ const assetPaths = await collector.collect(config, exportConfig);
+
+ for (const relativePath of assetPaths) {
+ if (!relativePath.endsWith('.esmaterial')) continue;
+
+ const uuid = assetLibrary.getUuid(relativePath);
+ if (!uuid) continue;
+
+ const fullPath = joinPath(projectDir, relativePath);
+ const content = await fs.readFile(fullPath);
+ if (!content) continue;
+
+ try {
+ const matData = JSON.parse(content);
+ if (matData.type !== 'material' || !matData.shader) continue;
+
+ const shaderRelPath = resolveShaderPath(relativePath, matData.shader);
+ const shaderFullPath = joinPath(projectDir, shaderRelPath);
+ const shaderContent = await fs.readFile(shaderFullPath);
+ if (!shaderContent) continue;
+
+ const parsed = 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 ?? {},
+ };
+
+ results.push({
+ relativePath,
+ uuid,
+ json: JSON.stringify(compiled),
+ });
+ } catch {
+ console.warn(`[MaterialCompiler] Failed to compile material: ${relativePath}`);
+ }
+ }
+
+ return results;
+}
diff --git a/editor/src/builder/PlayableBuilder.ts b/editor/src/builder/PlayableBuilder.ts
index 9125fbbfe..af7c0344c 100644
--- a/editor/src/builder/PlayableBuilder.ts
+++ b/editor/src/builder/PlayableBuilder.ts
@@ -20,57 +20,9 @@ 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
-// =============================================================================
-
-interface NativeFS {
- exists(path: string): Promise<boolean>;
- readFile(path: string): Promise<string | null>;
- readBinaryFile(path: string): Promise<Uint8Array | null>;
- writeFile(path: string, content: string): Promise<boolean>;
- listDirectoryDetailed(path: string): Promise<Array<{ name: string; isDirectory: boolean }>>;
- createDirectory(path: string): Promise<boolean>;
-}
-
-// =============================================================================
-// Path Utilities
-// =============================================================================
-
-function normalizePath(path: string): string {
- return path.replace(/\\/g, '/');
-}
-
-function joinPath(...parts: string[]): string {
- return normalizePath(parts.join('/').replace(/\/+/g, '/'));
-}
-
-function getProjectDir(projectPath: string): string {
- const normalized = normalizePath(projectPath);
- const lastSlash = normalized.lastIndexOf('/');
- return lastSlash > 0 ? normalized.substring(0, lastSlash) : normalized;
-}
-
-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 getDir(filePath: string): string {
- const normalized = normalizePath(filePath);
- const lastSlash = normalized.lastIndexOf('/');
- return lastSlash > 0 ? normalized.substring(0, lastSlash) : normalized;
-}
-
-function getDirName(path: string): string {
- const lastSlash = path.lastIndexOf('/');
- return lastSlash > 0 ? path.substring(0, lastSlash) : '';
-}
+import { normalizePath, joinPath, getProjectDir, getFileExtension, isAbsolutePath, getParentDir } from '../utils/path';
+import { compileMaterials } from './MaterialCompiler';
+import type { NativeFS } from '../types/NativeFS';
// =============================================================================
// MIME Types
@@ -446,7 +398,7 @@ export class PlayableBuilder {
// 6. Compile materials
this.progress_.setCurrentTask('Compiling materials...', 20);
- const compiledMaterials = await this.compileMaterials();
+ 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)
@@ -468,7 +420,7 @@ export class PlayableBuilder {
this.progress_.setPhase('writing');
this.progress_.setCurrentTask('Writing output...', 0);
const outputPath = this.resolveOutputPath(settings.outputPath);
- const outputDir = getDir(outputPath);
+ const outputDir = getParentDir(outputPath);
await this.fs_.createDirectory(outputDir);
const success = await this.fs_.writeFile(outputPath, html);
@@ -622,7 +574,7 @@ ${imports}
if (isAbsolutePath(args.path)) {
resolvedPath = normalizePath(args.path);
} else if (args.path.startsWith('.')) {
- const baseDir = args.importer ? getDir(args.importer) : args.resolveDir;
+ const baseDir = args.importer ? getParentDir(args.importer) : args.resolveDir;
resolvedPath = joinPath(baseDir, args.path);
} else {
if (args.path === 'esengine') {
@@ -685,66 +637,19 @@ ${imports}
};
}
- 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 }>();
+ private async compileMaterials_(): Promise<Map<string, { uuid: string; compiledJson: string }>> {
const configService = new AssetExportConfigService(this.projectDir_, this.fs_!);
const exportConfig = await configService.load();
+ const compiled = await compileMaterials(this.fs_!, this.projectDir_, this.assetLibrary_, this.context_.config, exportConfig);
- 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 ?? {},
- };
-
- result.set(relativePath, {
- uuid,
- compiledJson: JSON.stringify(compiled),
- });
- } catch {
- console.warn(`[PlayableBuilder] Failed to compile material: ${relativePath}`);
- }
+ const result = new Map<string, { uuid: string; compiledJson: string }>();
+ for (const mat of compiled) {
+ result.set(mat.relativePath, {
+ uuid: mat.uuid,
+ compiledJson: mat.json,
+ });
}
-
return result;
}
diff --git a/editor/src/builder/TextureAtlas.ts b/editor/src/builder/TextureAtlas.ts
index 7c0f48b80..1cee79847 100644
--- a/editor/src/builder/TextureAtlas.ts
+++ b/editor/src/builder/TextureAtlas.ts
@@ -4,6 +4,8 @@
*/
import { type AssetLibrary, isUUID } from '../asset/AssetLibrary';
+import { joinPath } from '../utils/path';
+import type { NativeFS } from '../types/NativeFS';
// =============================================================================
// Types
@@ -40,11 +42,6 @@ interface RectWithId extends Rect {
id: string;
}
-interface NativeFS {
- readFile(path: string): Promise<string | null>;
- readBinaryFile(path: string): Promise<Uint8Array | null>;
-}
-
// =============================================================================
// MaxRects Bin Packing
// =============================================================================
@@ -213,7 +210,7 @@ export class TextureAtlasPacker {
for (const relPath of eligiblePaths) {
if (spineTextures.has(relPath) || nineSliceTextures.has(relPath)) continue;
- const fullPath = this.joinPath(this.projectDir_, relPath);
+ const fullPath = joinPath(this.projectDir_, relPath);
const data = await this.fs_.readBinaryFile(fullPath);
if (!data) continue;
@@ -372,7 +369,7 @@ export class TextureAtlasPacker {
const result = new Set<string>();
for (const atlasRelPath of atlasPaths) {
- const fullPath = this.joinPath(this.projectDir_, atlasRelPath);
+ const fullPath = joinPath(this.projectDir_, atlasRelPath);
const content = await this.fs_.readFile(fullPath);
if (!content) continue;
@@ -452,7 +449,4 @@ export class TextureAtlasPacker {
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.ts
index 28d93f812..0fe71fe0a 100644
--- a/editor/src/builder/WeChatBuilder.ts
+++ b/editor/src/builder/WeChatBuilder.ts
@@ -12,62 +12,21 @@ import { findTsFiles, EDITOR_ONLY_DIRS } from '../scripting/ScriptLoader';
import { BuildAssetCollector, AssetExportConfigService } from './AssetCollector';
import { TextureAtlasPacker, type AtlasResult } from './TextureAtlas';
import { AssetLibrary } from '../asset/AssetLibrary';
+import { normalizePath, joinPath, getProjectDir, isAbsolutePath, getParentDir } from '../utils/path';
+import { resolveShaderPath } from '../utils/shader';
+import { getAssetType } from '../asset/AssetTypes';
+import { compileMaterials } from './MaterialCompiler';
+import type { NativeFS } from '../types/NativeFS';
// =============================================================================
// Types
// =============================================================================
-interface NativeFS {
- exists(path: string): Promise<boolean>;
- readFile(path: string): Promise<string | null>;
- readBinaryFile(path: string): Promise<Uint8Array | null>;
- writeFile(path: string, content: string): Promise<boolean>;
- writeBinaryFile(path: string, data: Uint8Array): Promise<boolean>;
- copyFile(src: string, dest: string): Promise<boolean>;
- listDirectoryDetailed(path: string): Promise<Array<{ name: string; isDirectory: boolean }>>;
- createDirectory(path: string): Promise<boolean>;
- getEngineWxgameJs(): Promise<string>;
- getEngineWxgameWasm(): Promise<Uint8Array>;
- getSdkWechatJs(): Promise<string>;
-}
-
interface AssetManifestEntry {
path: string;
type: string;
}
-// =============================================================================
-// Path Utilities
-// =============================================================================
-
-function normalizePath(path: string): string {
- return path.replace(/\\/g, '/');
-}
-
-function joinPath(...parts: string[]): string {
- return normalizePath(parts.join('/').replace(/\/+/g, '/'));
-}
-
-function getProjectDir(projectPath: string): string {
- const normalized = normalizePath(projectPath);
- const lastSlash = normalized.lastIndexOf('/');
- 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 getDirName(path: string): string {
- const lastSlash = path.lastIndexOf('/');
- return lastSlash > 0 ? path.substring(0, lastSlash) : '';
-}
-
// =============================================================================
// WeChatBuilder
// =============================================================================
@@ -135,7 +94,7 @@ export class WeChatBuilder {
// 5. Compile materials
this.progress_.setCurrentTask('Compiling materials...', 20);
- const compiledMaterials = await this.compileMaterials();
+ const compiledMaterials = await this.compileMaterials_();
this.progress_.log('info', `Compiled ${compiledMaterials.size} material(s)`);
// 6. Copy scenes (with atlas rewriting, UUID preserved)
@@ -590,11 +549,6 @@ function updateMaterials(world, sceneData, materialCache, entityMap) {
const fs = this.fs_!;
const projectDir = this.projectDir_;
- const getDir = (filePath: string): string => {
- const normalized = normalizePath(filePath);
- const lastSlash = normalized.lastIndexOf('/');
- return lastSlash > 0 ? normalized.substring(0, lastSlash) : normalized;
- };
const resolvePackageEntry = async (pkgName: string): Promise<string | null> => {
const pkgJsonPath = joinPath(projectDir, 'node_modules', pkgName, 'package.json');
@@ -643,7 +597,7 @@ function updateMaterials(world, sceneData, materialCache, entityMap) {
if (isAbsolutePath(args.path)) {
resolvedPath = normalizePath(args.path);
} else if (args.path.startsWith('.')) {
- const baseDir = args.importer ? getDir(args.importer) : args.resolveDir;
+ const baseDir = args.importer ? getParentDir(args.importer) : args.resolveDir;
resolvedPath = joinPath(baseDir, args.path);
} else {
const pkgEntry = await resolvePackageEntry(args.path);
@@ -681,70 +635,22 @@ function updateMaterials(world, sceneData, materialCache, entityMap) {
};
}
- private async compileMaterials(): Promise<Map<string, { uuid: string; outputPath: string; json: string }>> {
- const result = new Map<string, { uuid: string; outputPath: string; json: string }>();
+ private async compileMaterials_(): Promise<Map<string, { uuid: string; outputPath: string; json: string }>> {
const configService = new AssetExportConfigService(this.projectDir_, this.fs_!);
const exportConfig = await configService.load();
+ const compiled = await compileMaterials(this.fs_!, this.projectDir_, this.assetLibrary_, this.context_.config, exportConfig);
- 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}`);
- }
+ const result = new Map<string, { uuid: string; outputPath: string; json: string }>();
+ for (const mat of compiled) {
+ result.set(mat.relativePath, {
+ uuid: mat.uuid,
+ outputPath: mat.relativePath.replace(/\.esmaterial$/, '.json'),
+ json: JSON.stringify(JSON.parse(mat.json), null, 2),
+ });
}
-
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
@@ -826,7 +732,7 @@ function updateMaterials(world, sceneData, materialCache, entityMap) {
try {
const matData = JSON.parse(content);
if (matData.shader) {
- compiledShaderPaths.add(this.resolveShaderPath(matPath, matData.shader));
+ compiledShaderPaths.add(resolveShaderPath(matPath, matData.shader));
}
} catch {
// ignore
@@ -899,20 +805,9 @@ function updateMaterials(world, sceneData, materialCache, entityMap) {
continue;
}
- 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;
- }
-
manifest[uuid] = {
path: relativePath,
- type,
+ type: getAssetType(relativePath),
};
}
diff --git a/editor/src/extension/EditorExportService.ts b/editor/src/extension/EditorExportService.ts
index 8bd6383ac..0c1f4429a 100644
--- a/editor/src/extension/EditorExportService.ts
+++ b/editor/src/extension/EditorExportService.ts
@@ -5,18 +5,7 @@
import { SDK_VERSION } from '../types/ProjectTypes';
import { getEditorContext } from '../context/EditorContext';
-
-// =============================================================================
-// Native FS Interface
-// =============================================================================
-
-interface NativeFS {
- createDirectory(path: string): Promise<boolean>;
- exists(path: string): Promise<boolean>;
- writeFile(path: string, content: string): Promise<boolean>;
- readFile(path: string): Promise<string | null>;
- getEditorDts(): Promise<string>;
-}
+import type { NativeFS } from '../types/NativeFS';
function getNativeFS(): NativeFS | null {
return getEditorContext().fs ?? null;
diff --git a/editor/src/extension/ExtensionLoader.ts b/editor/src/extension/ExtensionLoader.ts
index 0d36577a9..4716670c4 100644
--- a/editor/src/extension/ExtensionLoader.ts
+++ b/editor/src/extension/ExtensionLoader.ts
@@ -10,24 +10,7 @@ import type { NativeFS, CompileError } from '../scripting/types';
import { getEditorContext } from '../context/EditorContext';
import { ExtensionContext } from './ExtensionContext';
import { setEditorAPI } from './editorAPI';
-
-// =============================================================================
-// Path Utilities
-// =============================================================================
-
-function normalizePath(path: string): string {
- return path.replace(/\\/g, '/');
-}
-
-function joinPath(...parts: string[]): string {
- return normalizePath(parts.join('/').replace(/\/+/g, '/'));
-}
-
-function getProjectDir(projectPath: string): string {
- const normalized = normalizePath(projectPath);
- const lastSlash = normalized.lastIndexOf('/');
- return lastSlash > 0 ? normalized.substring(0, lastSlash) : normalized;
-}
+import { normalizePath, joinPath, getProjectDir } from '../utils/path';
// =============================================================================
// Native FS Access
diff --git a/editor/src/io/SceneSerializer.ts b/editor/src/io/SceneSerializer.ts
index 18a7dfb1f..0e7228a43 100644
--- a/editor/src/io/SceneSerializer.ts
+++ b/editor/src/io/SceneSerializer.ts
@@ -6,6 +6,7 @@
import type { SceneData, EntityData, ComponentData } from '../types/SceneTypes';
import { getEditorContext } from '../context/EditorContext';
import { getDefaultComponentData } from '../schemas/ComponentSchemas';
+import type { NativeFS } from '../types/NativeFS';
// =============================================================================
// SceneSerializer
@@ -81,13 +82,6 @@ export class SceneSerializer {
// Native File System Interface (for Tauri)
// =============================================================================
-interface NativeFS {
- saveFile(content: string, defaultPath?: string): Promise<string | null>;
- loadFile(): Promise<{ path: string; content: string } | null>;
- readFile(path: string): Promise<string | null>;
- writeFile?(path: string, content: string): Promise<boolean>;
-}
-
function getNativeFS(): NativeFS | null {
return getEditorContext().fs ?? null;
}
diff --git a/editor/src/launcher/ProjectService.ts b/editor/src/launcher/ProjectService.ts
index db373a1b9..9c0deca8a 100644
--- a/editor/src/launcher/ProjectService.ts
+++ b/editor/src/launcher/ProjectService.ts
@@ -12,19 +12,7 @@ import { ENGINE_VERSION } from '../types/ProjectTypes';
import { SdkExportService } from '../sdk';
import { EditorExportService } from '../extension';
import { getEditorContext } from '../context/EditorContext';
-
-// =============================================================================
-// Native FS Interface
-// =============================================================================
-
-interface NativeFS {
- selectDirectory(): Promise<string | null>;
- createDirectory(path: string): Promise<boolean>;
- exists(path: string): Promise<boolean>;
- writeFile(path: string, content: string): Promise<boolean>;
- readFile(path: string): Promise<string | null>;
- openProject(): Promise<string | null>;
-}
+import type { NativeFS } from '../types/NativeFS';
function getNativeFS(): NativeFS | null {
return getEditorContext().fs ?? null;
@@ -81,9 +69,7 @@ export interface ProjectServiceResult<T = void> {
error?: string;
}
-function joinPath(...parts: string[]): string {
- return parts.join('/').replace(/\\/g, '/').replace(/\/+/g, '/');
-}
+import { joinPath } from '../utils/path';
function getProjectDir(location: string, name: string): string {
return joinPath(location, name);
diff --git a/editor/src/panels/ContentBrowserPanel.ts b/editor/src/panels/ContentBrowserPanel.ts
index 2812f3476..fd29cca05 100644
--- a/editor/src/panels/ContentBrowserPanel.ts
+++ b/editor/src/panels/ContentBrowserPanel.ts
@@ -9,32 +9,13 @@ import { showContextMenu } from '../ui/ContextMenu';
import { getPlatformAdapter } from '../platform/PlatformAdapter';
import { showInputDialog, showConfirmDialog } from '../ui/dialog';
import { getEditorContext } from '../context/EditorContext';
+import { joinPath, getParentDir } from '../utils/path';
+import type { NativeFS, DirectoryEntry } from '../types/NativeFS';
// =============================================================================
// Types
// =============================================================================
-interface DirectoryEntry {
- name: string;
- isDirectory: boolean;
- isFile: boolean;
-}
-
-interface FileChangeEvent {
- type: 'create' | 'modify' | 'remove' | 'rename' | 'any';
- paths: string[];
-}
-
-interface NativeFS {
- listDirectoryDetailed(path: string): Promise<DirectoryEntry[]>;
- watchDirectory(
- path: string,
- callback: (event: FileChangeEvent) => void,
- options?: { recursive?: boolean }
- ): Promise<() => void>;
- openFolder(path: string): Promise<boolean>;
-}
-
interface NativeShell {
openFile(path: string): Promise<void>;
openInEditor(projectPath: string, filePath: string): Promise<void>;
@@ -71,16 +52,6 @@ function getNativeShell(): NativeShell | null {
return getEditorContext().shell ?? null;
}
-function joinPath(...parts: string[]): string {
- return parts.join('/').replace(/\\/g, '/').replace(/\/+/g, '/');
-}
-
-function getParentPath(path: string): string {
- const normalized = path.replace(/\\/g, '/');
- const lastSlash = normalized.lastIndexOf('/');
- return lastSlash > 0 ? normalized.substring(0, lastSlash) : normalized;
-}
-
function getFileExtension(filename: string): string {
const dotIndex = filename.lastIndexOf('.');
return dotIndex > 0 ? filename.substring(dotIndex).toLowerCase() : '';
@@ -176,7 +147,7 @@ export class ContentBrowserPanel {
this.onOpenScene_ = options?.onOpenScene ?? null;
if (this.projectPath_) {
- this.currentPath_ = getParentPath(this.projectPath_);
+ this.currentPath_ = getParentDir(this.projectPath_);
}
this.container_.classList.add('es-content-browser');
@@ -276,7 +247,7 @@ export class ContentBrowserPanel {
}
private async loadProjectDirectory(): Promise<void> {
- const projectDir = getParentPath(this.projectPath_!);
+ const projectDir = getParentDir(this.projectPath_!);
this.currentPath_ = projectDir;
this.rootFolder_ = {
@@ -326,7 +297,7 @@ export class ContentBrowserPanel {
const fs = getNativeFS();
if (!fs || !this.projectPath_) return;
- const projectDir = getParentPath(this.projectPath_);
+ const projectDir = getParentDir(this.projectPath_);
try {
this.unwatchFn_ = await fs.watchDirectory(
@@ -504,7 +475,7 @@ export class ContentBrowserPanel {
private showAssetContextMenu(e: MouseEvent, path: string, type: AssetItem['type']): void {
const fs = getNativeFS();
- const parentPath = getParentPath(path);
+ const parentPath = getParentDir(path);
const fileName = path.split('/').pop() ?? path;
showContextMenu({
diff --git a/editor/src/panels/InspectorPanel.ts b/editor/src/panels/InspectorPanel.ts
index fdf7a213a..a65538893 100644
--- a/editor/src/panels/InspectorPanel.ts
+++ b/editor/src/panels/InspectorPanel.ts
@@ -36,6 +36,8 @@ import {
type ShaderProperty,
} from '../shader/ShaderPropertyParser';
import { getEditorContext, getEditorInstance } from '../context/EditorContext';
+import { AssetExportConfigService, type FolderExportMode } from '../builder/AssetCollector';
+import type { NativeFS } from '../types/NativeFS';
// =============================================================================
// Types
@@ -47,18 +49,6 @@ interface EditorInfo {
propertyName: string;
}
-interface FileStats {
- size: number;
- modified: Date | null;
- created: Date | null;
-}
-
-interface NativeFS {
- readFile(path: string): Promise<string | null>;
- readBinaryFile(path: string): Promise<Uint8Array | null>;
- getFileStats(path: string): Promise<FileStats | null>;
-}
-
// =============================================================================
// Helpers
// =============================================================================
@@ -894,6 +884,9 @@ export class InspectorPanel {
case 'material':
await this.renderMaterialInspector(asset.path);
break;
+ case 'folder':
+ await this.renderFolderInspector(asset.path);
+ break;
default:
await this.renderFileInspector(asset.path, asset.type);
}
@@ -2131,6 +2124,104 @@ export class InspectorPanel {
container.appendChild(wrapper);
}
+ private async renderFolderInspector(path: string): Promise<void> {
+ const fs = getNativeFS();
+ const projectDir = this.getProjectDir();
+ if (!projectDir) return;
+
+ const relativePath = path.startsWith(projectDir)
+ ? path.substring(projectDir.length + 1)
+ : path;
+
+ const configService = new AssetExportConfigService(projectDir, fs as any);
+ const exportConfig = await configService.load();
+ const currentMode: FolderExportMode = exportConfig.folders[relativePath] || 'auto';
+
+ const descriptions: Record<FolderExportMode, string> = {
+ auto: 'Included only if referenced by build scenes',
+ always: 'Always included in all builds',
+ exclude: 'Never included in builds',
+ };
+
+ const exportSection = document.createElement('div');
+ exportSection.className = 'es-component-section es-collapsible es-expanded';
+ exportSection.innerHTML = `
+ <div class="es-component-header es-collapsible-header">
+ <span class="es-collapse-icon">${icons.chevronDown(12)}</span>
+ <span class="es-component-icon">${icons.settings(14)}</span>
+ <span class="es-component-title">Export Settings</span>
+ </div>
+ <div class="es-component-properties es-collapsible-content">
+ <div class="es-property-row">
+ <label class="es-property-label">Export Mode</label>
+ <div class="es-property-editor">
+ <select class="es-input es-folder-export-mode">
+ <option value="auto"${currentMode === 'auto' ? ' selected' : ''}>Auto</option>
+ <option value="always"${currentMode === 'always' ? ' selected' : ''}>Always Include</option>
+ <option value="exclude"${currentMode === 'exclude' ? ' selected' : ''}>Exclude</option>
+ </select>
+ </div>
+ </div>
+ <div class="es-property-row">
+ <label class="es-property-label"></label>
+ <div class="es-property-value es-folder-export-desc" style="color: var(--text-muted); font-size: 11px;">${descriptions[currentMode]}</div>
+ </div>
+ </div>
+ `;
+
+ const header = exportSection.querySelector('.es-collapsible-header');
+ header?.addEventListener('click', () => {
+ exportSection.classList.toggle('es-expanded');
+ });
+
+ const select = exportSection.querySelector('.es-folder-export-mode') as HTMLSelectElement;
+ const descEl = exportSection.querySelector('.es-folder-export-desc') as HTMLElement;
+ select?.addEventListener('change', async () => {
+ const mode = select.value as FolderExportMode;
+ descEl.textContent = descriptions[mode];
+ await configService.setMode(relativePath, mode);
+ });
+
+ this.contentContainer_.appendChild(exportSection);
+
+ let itemCount = 0;
+ if (fs) {
+ try {
+ const entries = await (fs as any).listDirectoryDetailed(path);
+ itemCount = entries?.length ?? 0;
+ } catch {
+ // Ignore
+ }
+ }
+
+ const propsSection = document.createElement('div');
+ propsSection.className = 'es-component-section es-collapsible es-expanded';
+ propsSection.innerHTML = `
+ <div class="es-component-header es-collapsible-header">
+ <span class="es-collapse-icon">${icons.chevronDown(12)}</span>
+ <span class="es-component-icon">${icons.settings(14)}</span>
+ <span class="es-component-title">Properties</span>
+ </div>
+ <div class="es-component-properties es-collapsible-content">
+ <div class="es-property-row">
+ <label class="es-property-label">Items</label>
+ <div class="es-property-value">${itemCount}</div>
+ </div>
+ <div class="es-property-row">
+ <label class="es-property-label">Path</label>
+ <div class="es-property-value">${this.escapeHtml(relativePath)}</div>
+ </div>
+ </div>
+ `;
+
+ const propsHeader = propsSection.querySelector('.es-collapsible-header');
+ propsHeader?.addEventListener('click', () => {
+ propsSection.classList.toggle('es-expanded');
+ });
+
+ this.contentContainer_.appendChild(propsSection);
+ }
+
private async renderFileInspector(path: string, type: AssetType): Promise<void> {
const fs = getNativeFS();
const stats = fs ? await fs.getFileStats(path) : null;
diff --git a/editor/src/preview/PreviewService.ts b/editor/src/preview/PreviewService.ts
index 3f4c60a0c..f1b009c98 100644
--- a/editor/src/preview/PreviewService.ts
+++ b/editor/src/preview/PreviewService.ts
@@ -9,6 +9,7 @@ import type { TextureMetadata } from '../types/TextureMetadata';
import { getMetaFilePath, parseTextureMetadata } from '../types/TextureMetadata';
import { getEditorContext } from '../context/EditorContext';
import { getAssetLibrary } from '../asset/AssetLibrary';
+import { getProjectDir } from '../utils/path';
// =============================================================================
// Types
@@ -23,20 +24,6 @@ interface PreviewConfig {
port?: number;
}
-// =============================================================================
-// Path Utilities
-// =============================================================================
-
-function normalizePath(path: string): string {
- return path.replace(/\\/g, '/');
-}
-
-function getProjectDir(projectPath: string): string {
- const normalized = normalizePath(projectPath);
- const lastSlash = normalized.lastIndexOf('/');
- return lastSlash > 0 ? normalized.substring(0, lastSlash) : normalized;
-}
-
// =============================================================================
// Preview Service
// =============================================================================
diff --git a/editor/src/property/editors.ts b/editor/src/property/editors.ts
index 1c861bda5..a7d40d4e8 100644
--- a/editor/src/property/editors.ts
+++ b/editor/src/property/editors.ts
@@ -11,6 +11,7 @@ import {
import { getEditorContext, getEditorInstance } from '../context/EditorContext';
import { getPlatformAdapter } from '../platform/PlatformAdapter';
import { getAssetLibrary, isUUID } from '../asset/AssetLibrary';
+import type { NativeFS } from '../types/NativeFS';
// =============================================================================
// Drag Helper
@@ -654,11 +655,6 @@ function createEnumEditor(
// Texture Editor
// =============================================================================
-interface NativeFS {
- readFile(path: string): Promise<string | null>;
- readBinaryFile(path: string): Promise<Uint8Array | null>;
-}
-
function getNativeFS(): NativeFS | null {
return getEditorContext().fs ?? null;
}
diff --git a/editor/src/property/materialEditors.ts b/editor/src/property/materialEditors.ts
index 9548d72b4..96f4ea8e2 100644
--- a/editor/src/property/materialEditors.ts
+++ b/editor/src/property/materialEditors.ts
@@ -11,6 +11,7 @@ import {
import { BLEND_MODE_OPTIONS } from '../types/MaterialMetadata';
import { getPlatformAdapter } from '../platform/PlatformAdapter';
import { getEditorContext, getEditorInstance } from '../context/EditorContext';
+import type { NativeFS } from '../types/NativeFS';
// =============================================================================
// Helpers
@@ -182,11 +183,6 @@ function createShaderFileEditor(
// Material Texture Editor
// =============================================================================
-interface NativeFS {
- readFile(path: string): Promise<string | null>;
- readBinaryFile(path: string): Promise<Uint8Array | null>;
-}
-
function getNativeFS(): NativeFS | null {
return getEditorContext().fs ?? null;
}
diff --git a/editor/src/renderer/EditorTextureManager.ts b/editor/src/renderer/EditorTextureManager.ts
index 88b2599a0..57e951770 100644
--- a/editor/src/renderer/EditorTextureManager.ts
+++ b/editor/src/renderer/EditorTextureManager.ts
@@ -7,17 +7,12 @@ import type { ESEngineModule } from 'esengine';
import { parseTextureMetadata, getMetaFilePath } from '../types/TextureMetadata';
import type { AssetPathResolver } from '../asset';
import { getEditorContext } from '../context/EditorContext';
+import type { NativeFS } from '../types/NativeFS';
// =============================================================================
// Types
// =============================================================================
-interface NativeFS {
- readBinaryFile(path: string): Promise<Uint8Array | null>;
- readFile(path: string): Promise<string | null>;
- exists(path: string): Promise<boolean>;
-}
-
interface TextureEntry {
handle: number;
width: number;
diff --git a/editor/src/scripting/ScriptLoader.ts b/editor/src/scripting/ScriptLoader.ts
index ed296ac85..32e5b31c6 100644
--- a/editor/src/scripting/ScriptLoader.ts
+++ b/editor/src/scripting/ScriptLoader.ts
@@ -9,24 +9,7 @@ import { virtualFsPlugin } from './esbuildPlugins';
import type { NativeFS, ScriptLoaderOptions, CompileError } from './types';
import { clearScriptComponents } from '../schemas/ComponentSchemas';
import { getEditorContext } from '../context/EditorContext';
-
-// =============================================================================
-// Path Utilities
-// =============================================================================
-
-function normalizePath(path: string): string {
- return path.replace(/\\/g, '/');
-}
-
-function joinPath(...parts: string[]): string {
- return normalizePath(parts.join('/').replace(/\/+/g, '/'));
-}
-
-function getProjectDir(projectPath: string): string {
- const normalized = normalizePath(projectPath);
- const lastSlash = normalized.lastIndexOf('/');
- return lastSlash > 0 ? normalized.substring(0, lastSlash) : normalized;
-}
+import { normalizePath, joinPath, getProjectDir } from '../utils/path';
// =============================================================================
// Native FS Access
diff --git a/editor/src/scripting/esbuildPlugins.ts b/editor/src/scripting/esbuildPlugins.ts
index 506165125..90ebaac31 100644
--- a/editor/src/scripting/esbuildPlugins.ts
+++ b/editor/src/scripting/esbuildPlugins.ts
@@ -5,31 +5,18 @@
import type * as esbuild from 'esbuild-wasm';
import type { NativeFS } from './types';
+import { normalizePath, joinPath, getParentDir } from '../utils/path';
// =============================================================================
// Path Utilities
// =============================================================================
-function normalizePath(path: string): string {
- return path.replace(/\\/g, '/');
-}
-
-function joinPath(...parts: string[]): string {
- return normalizePath(parts.join('/').replace(/\/+/g, '/'));
-}
-
-function dirname(path: string): string {
- const normalized = normalizePath(path);
- const lastSlash = normalized.lastIndexOf('/');
- return lastSlash > 0 ? normalized.substring(0, lastSlash) : normalized;
-}
-
function resolvePath(from: string, to: string): string {
if (!to.startsWith('.')) {
return to;
}
- const fromDir = dirname(from);
+ const fromDir = getParentDir(from);
const parts = fromDir.split('/');
const toParts = to.split('/');
@@ -208,7 +195,7 @@ export function virtualFsPlugin(options: VirtualFsPluginOptions): esbuild.Plugin
return {
contents: content,
loader,
- resolveDir: dirname(args.path),
+ resolveDir: getParentDir(args.path),
};
});
},
diff --git a/editor/src/scripting/types.ts b/editor/src/scripting/types.ts
index 371390a49..fc47eb7f8 100644
--- a/editor/src/scripting/types.ts
+++ b/editor/src/scripting/types.ts
@@ -3,59 +3,7 @@
* @brief Script loader type definitions
*/
-// =============================================================================
-// Native FS Interface
-// =============================================================================
-
-export interface DirectoryEntry {
- name: string;
- isDirectory: boolean;
- isFile: boolean;
-}
-
-export interface FileStats {
- size: number;
- modified: Date | null;
- created: Date | null;
-}
-
-export interface NativeFS {
- saveFile(content: string, defaultPath?: string): Promise<string | null>;
- loadFile(): Promise<{ path: string; content: string } | null>;
- selectDirectory(): Promise<string | null>;
- createDirectory(path: string): Promise<boolean>;
- exists(path: string): Promise<boolean>;
- writeFile(path: string, content: string): Promise<boolean>;
- writeBinaryFile(path: string, data: Uint8Array): Promise<boolean>;
- readFile(path: string): Promise<string | null>;
- readBinaryFile(path: string): Promise<Uint8Array | null>;
- copyFile(src: string, dest: string): Promise<boolean>;
- getFileStats(path: string): Promise<FileStats | null>;
- openProject(): Promise<string | null>;
- listDirectory(path: string): Promise<string[]>;
- listDirectoryDetailed(path: string): Promise<DirectoryEntry[]>;
- watchDirectory(
- path: string,
- callback: (event: { type: 'create' | 'modify' | 'remove' | 'rename' | 'any'; paths: string[] }) => void,
- options?: { recursive?: boolean }
- ): Promise<() => void>;
- openFolder(path: string): Promise<boolean>;
- openFile?(path: string): Promise<void>;
- showOpenDialog?(options: { title?: string; filters?: Array<{ name: string; extensions: string[] }> }): Promise<string[] | null>;
- getResourcePath(): Promise<string>;
- getEngineJs(): Promise<string>;
- getEngineWasm(): Promise<Uint8Array>;
- getEngineSingleJs(): Promise<string>;
- getEngineWxgameJs(): Promise<string>;
- getEngineWxgameWasm(): Promise<Uint8Array>;
- getSdkWechatJs(): Promise<string>;
- getSdkEsmJs(): Promise<string>;
- getSdkEsmDts(): Promise<string>;
- getSdkWasmJs(): Promise<string>;
- getSdkWasmDts(): Promise<string>;
- getEditorDts(): Promise<string>;
- toAssetUrl?(path: string): string;
-}
+export type { NativeFS, DirectoryEntry, FileStats } from '../types/NativeFS';
// =============================================================================
// Script Loader Types
diff --git a/editor/src/sdk/SdkExportService.ts b/editor/src/sdk/SdkExportService.ts
index 7aa594704..38c62d74f 100644
--- a/editor/src/sdk/SdkExportService.ts
+++ b/editor/src/sdk/SdkExportService.ts
@@ -5,21 +5,7 @@
import { SDK_VERSION } from '../types/ProjectTypes';
import { getEditorContext } from '../context/EditorContext';
-
-// =============================================================================
-// Native FS Interface
-// =============================================================================
-
-interface NativeFS {
- createDirectory(path: string): Promise<boolean>;
- writeFile(path: string, content: string): Promise<boolean>;
- readFile(path: string): Promise<string | null>;
- getSdkEsmJs(): Promise<string>;
- getSdkEsmDts(): Promise<string>;
- getSdkWasmJs(): Promise<string>;
- getSdkWasmDts(): Promise<string>;
- getSdkWechatJs(): Promise<string>;
-}
+import type { NativeFS } from '../types/NativeFS';
function getNativeFS(): NativeFS | null {
return getEditorContext().fs ?? null;
diff --git a/editor/src/types/NativeFS.ts b/editor/src/types/NativeFS.ts
new file mode 100644
index 000000000..34a4b1228
--- /dev/null
+++ b/editor/src/types/NativeFS.ts
@@ -0,0 +1,49 @@
+export interface DirectoryEntry {
+ name: string;
+ isDirectory: boolean;
+ isFile: boolean;
+}
+
+export interface FileStats {
+ size: number;
+ modified: Date | null;
+ created: Date | null;
+}
+
+export interface NativeFS {
+ saveFile(content: string, defaultPath?: string): Promise<string | null>;
+ loadFile(): Promise<{ path: string; content: string } | null>;
+ selectDirectory(): Promise<string | null>;
+ createDirectory(path: string): Promise<boolean>;
+ exists(path: string): Promise<boolean>;
+ writeFile(path: string, content: string): Promise<boolean>;
+ writeBinaryFile(path: string, data: Uint8Array): Promise<boolean>;
+ readFile(path: string): Promise<string | null>;
+ readBinaryFile(path: string): Promise<Uint8Array | null>;
+ copyFile(src: string, dest: string): Promise<boolean>;
+ getFileStats(path: string): Promise<FileStats | null>;
+ openProject(): Promise<string | null>;
+ listDirectory(path: string): Promise<string[]>;
+ listDirectoryDetailed(path: string): Promise<DirectoryEntry[]>;
+ watchDirectory(
+ path: string,
+ callback: (event: { type: 'create' | 'modify' | 'remove' | 'rename' | 'any'; paths: string[] }) => void,
+ options?: { recursive?: boolean }
+ ): Promise<() => void>;
+ openFolder(path: string): Promise<boolean>;
+ openFile?(path: string): Promise<void>;
+ showOpenDialog?(options: { title?: string; filters?: Array<{ name: string; extensions: string[] }> }): Promise<string[] | null>;
+ getResourcePath(): Promise<string>;
+ getEngineJs(): Promise<string>;
+ getEngineWasm(): Promise<Uint8Array>;
+ getEngineSingleJs(): Promise<string>;
+ getEngineWxgameJs(): Promise<string>;
+ getEngineWxgameWasm(): Promise<Uint8Array>;
+ getSdkWechatJs(): Promise<string>;
+ getSdkEsmJs(): Promise<string>;
+ getSdkEsmDts(): Promise<string>;
+ getSdkWasmJs(): Promise<string>;
+ getSdkWasmDts(): Promise<string>;
+ getEditorDts(): Promise<string>;
+ toAssetUrl?(path: string): string;
+}
diff --git a/editor/src/utils/path.ts b/editor/src/utils/path.ts
new file mode 100644
index 000000000..811188403
--- /dev/null
+++ b/editor/src/utils/path.ts
@@ -0,0 +1,33 @@
+export function normalizePath(path: string): string {
+ return path.replace(/\\/g, '/');
+}
+
+export function joinPath(...parts: string[]): string {
+ return normalizePath(parts.join('/').replace(/\/+/g, '/'));
+}
+
+export function getFileExtension(path: string): string {
+ const lastDot = path.lastIndexOf('.');
+ return lastDot > 0 ? path.substring(lastDot + 1).toLowerCase() : '';
+}
+
+export function getDirName(path: string): string {
+ const lastSlash = path.lastIndexOf('/');
+ return lastSlash > 0 ? path.substring(0, lastSlash) : '';
+}
+
+export function getParentDir(path: string): string {
+ const normalized = normalizePath(path);
+ const lastSlash = normalized.lastIndexOf('/');
+ return lastSlash > 0 ? normalized.substring(0, lastSlash) : normalized;
+}
+
+export function getProjectDir(projectPath: string): string {
+ const normalized = normalizePath(projectPath);
+ const lastSlash = normalized.lastIndexOf('/');
+ return lastSlash > 0 ? normalized.substring(0, lastSlash) : normalized;
+}
+
+export function isAbsolutePath(path: string): boolean {
+ return path.startsWith('/') || /^[a-zA-Z]:/.test(path);
+}
diff --git a/editor/src/utils/shader.ts b/editor/src/utils/shader.ts
new file mode 100644
index 000000000..4ef8fe853
--- /dev/null
+++ b/editor/src/utils/shader.ts
@@ -0,0 +1,13 @@
+import { getDirName } from './path';
+
+export function 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 };
+}
+
+export function resolveShaderPath(materialPath: string, shaderPath: string): string {
+ if (shaderPath.startsWith('/') || shaderPath.startsWith('assets/')) return shaderPath;
+ const dir = getDirName(materialPath);
+ return dir ? `${dir}/${shaderPath}` : shaderPath;
+}