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 project launcher and real file system integration
esenginec7074893f02a
diff --git a/desktop/src-tauri/capabilities/default.json b/desktop/src-tauri/capabilities/default.jsonnew file mode 100644index 000000000..efd998fc5--- /dev/null+++ b/desktop/src-tauri/capabilities/default.json@@ -0,0 +1,28 @@+{+ "$schema": "../gen/schemas/desktop-schema.json",+ "identifier": "default",+ "description": "Default capabilities for ESEngine Editor",+ "windows": ["main"],+ "permissions": [+ "core:default",+ "shell:allow-open",+ "dialog:default",+ "dialog:allow-open",+ "dialog:allow-save",+ "fs:default",+ "fs:allow-read-text-file",+ "fs:allow-write-text-file",+ "fs:allow-exists",+ "fs:allow-mkdir",+ "fs:allow-read-dir",+ {+ "identifier": "fs:scope",+ "allow": [+ "$HOME/**",+ "$DOCUMENT/**",+ "$DESKTOP/**",+ "**"+ ]+ }+ ]+}diff --git a/desktop/src-tauri/gen/schemas/capabilities.json b/desktop/src-tauri/gen/schemas/capabilities.jsonindex 9e26dfeeb..f78d1c28c 100644--- a/desktop/src-tauri/gen/schemas/capabilities.json+++ b/desktop/src-tauri/gen/schemas/capabilities.json@@ -1 +1 @@-{}\ No newline at end of file+{"default":{"identifier":"default","description":"Default capabilities for ESEngine Editor","local":true,"windows":["main"],"permissions":["core:default","shell:allow-open","dialog:default","dialog:allow-open","dialog:allow-save","fs:default","fs:allow-read-text-file","fs:allow-write-text-file","fs:allow-exists","fs:allow-mkdir","fs:allow-read-dir",{"identifier":"fs:scope","allow":["$HOME/**","$DOCUMENT/**","$DESKTOP/**","**"]}]}}\ No newline at end of filediff --git a/desktop/src/main.ts b/desktop/src/main.tsindex df9b8dc97..31906e889 100644--- a/desktop/src/main.ts+++ b/desktop/src/main.ts@@ -4,10 +4,27 @@*/import '@esengine/editor/styles';-import { createEditor } from '@esengine/editor';+import { createEditor, ProjectLauncher } from '@esengine/editor';import { injectNativeFS } from './native-fs';-async function init() {+let currentLauncher: ProjectLauncher | null = null;++async function showLauncher(container: HTMLElement): Promise<void> {+ currentLauncher = new ProjectLauncher(container, {+ onProjectOpen: (projectPath) => {+ currentLauncher?.dispose();+ currentLauncher = null;+ openEditor(container, projectPath);+ },+ });+}++function openEditor(container: HTMLElement, projectPath: string): void {+ const editor = createEditor(container, { projectPath });+ console.log('ESEngine Editor opened project:', projectPath, editor);+}++async function init(): Promise<void> {injectNativeFS();const container = document.getElementById('editor-root');@@ -16,8 +33,7 @@ async function init() {return;}- const editor = createEditor(container);- console.log('ESEngine Editor initialized', editor);+ showLauncher(container);}init().catch(console.error);diff --git a/desktop/src/native-fs.ts b/desktop/src/native-fs.tsindex d83dd5319..b1c7703ed 100644--- a/desktop/src/native-fs.ts+++ b/desktop/src/native-fs.ts@@ -4,11 +4,43 @@*/import { open, save } from '@tauri-apps/plugin-dialog';-import { readTextFile, writeTextFile } from '@tauri-apps/plugin-fs';+import {+ readTextFile,+ writeTextFile,+ mkdir,+ exists,+ readDir,+} from '@tauri-apps/plugin-fs';++export interface DirectoryEntry {+ name: string;+ isDirectory: boolean;+ isFile: boolean;+}++export interface FileChangeEvent {+ type: 'create' | 'modify' | 'remove' | 'rename' | 'any';+ paths: string[];+}++export type UnwatchFn = () => void;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>;+ readFile(path: string): Promise<string | null>;+ openProject(): Promise<string | null>;+ listDirectory(path: string): Promise<string[]>;+ listDirectoryDetailed(path: string): Promise<DirectoryEntry[]>;+ watchDirectory(+ path: string,+ callback: (event: FileChangeEvent) => void,+ options?: { recursive?: boolean }+ ): Promise<UnwatchFn>;}export function injectNativeFS(): void {@@ -48,6 +80,101 @@ export function injectNativeFS(): void {return null;}},++ async selectDirectory() {+ try {+ const path = await open({+ directory: true,+ multiple: false,+ });+ return typeof path === 'string' ? path : null;+ } catch (err) {+ console.error('Failed to select directory:', err);+ return null;+ }+ },++ async createDirectory(path: string) {+ try {+ await mkdir(path, { recursive: true });+ return true;+ } catch (err) {+ console.error('Failed to create directory:', err);+ return false;+ }+ },++ async exists(path: string) {+ try {+ return await exists(path);+ } catch {+ return false;+ }+ },++ async writeFile(path: string, content: string) {+ try {+ await writeTextFile(path, content);+ return true;+ } catch (err) {+ console.error('Failed to write file:', err);+ return false;+ }+ },++ async readFile(path: string) {+ try {+ return await readTextFile(path);+ } catch (err) {+ console.error('Failed to read file:', err);+ return null;+ }+ },++ async openProject() {+ try {+ const path = await open({+ multiple: false,+ filters: [{ name: 'ESEngine Project', extensions: ['esproject'] }],+ });+ return typeof path === 'string' ? path : null;+ } catch (err) {+ console.error('Failed to open project:', err);+ return null;+ }+ },++ async listDirectory(path: string) {+ try {+ const entries = await readDir(path);+ return entries.map(e => e.name);+ } catch {+ return [];+ }+ },++ async listDirectoryDetailed(path: string) {+ try {+ const entries = await readDir(path);+ return entries.map(e => ({+ name: e.name,+ isDirectory: e.isDirectory,+ isFile: e.isFile,+ }));+ } catch (err) {+ console.error('Failed to list directory:', err);+ return [];+ }+ },++ async watchDirectory(+ _path: string,+ _callback: (event: FileChangeEvent) => void,+ _options?: { recursive?: boolean }+ ) {+ // File watching not yet supported - use manual refresh+ return () => {};+ },};(window as any).__esengine_fs = nativeFS;diff --git a/editor/src/Editor.ts b/editor/src/Editor.tsindex b9c42af30..442fee182 100644--- a/editor/src/Editor.ts+++ b/editor/src/Editor.ts@@ -9,12 +9,20 @@ import { EditorBridge } from './bridge/EditorBridge';import { HierarchyPanel } from './panels/HierarchyPanel';import { InspectorPanel } from './panels/InspectorPanel';import { SceneViewPanel } from './panels/SceneViewPanel';-import { ContentBrowserPanel } from './panels/ContentBrowserPanel';+import { ContentBrowserPanel, type ContentBrowserOptions } from './panels/ContentBrowserPanel';import { registerBuiltinEditors } from './property/editors';import { registerBuiltinSchemas } from './schemas/ComponentSchemas';import { saveSceneToFile, loadSceneFromFile } from './io/SceneSerializer';import { icons } from './utils/icons';+// =============================================================================+// Types+// =============================================================================++export interface EditorOptions {+ projectPath?: string;+}+// =============================================================================// Editor// =============================================================================@@ -24,6 +32,7 @@ export class Editor {private app_: App | null = null;private store_: EditorStore;private bridge_: EditorBridge | null = null;+ private projectPath_: string | null = null;private hierarchyPanel_: HierarchyPanel | null = null;private inspectorPanel_: InspectorPanel | null = null;@@ -32,9 +41,10 @@ export class Editor {private assetsPanelVisible_: boolean = true;private outputPanelVisible_: boolean = false;- constructor(container: HTMLElement) {+ constructor(container: HTMLElement, options?: EditorOptions) {this.container_ = container;this.store_ = new EditorStore();+ this.projectPath_ = options?.projectPath ?? null;registerBuiltinEditors();registerBuiltinSchemas();@@ -43,6 +53,10 @@ export class Editor {this.setupKeyboardShortcuts();}+ get projectPath(): string | null {+ return this.projectPath_;+ }+setApp(app: App): void {this.app_ = app;this.bridge_ = new EditorBridge(app, this.store_);@@ -166,7 +180,9 @@ export class Editor {this.hierarchyPanel_ = new HierarchyPanel(hierarchyContainer, this.store_);this.inspectorPanel_ = new InspectorPanel(inspectorContainer, this.store_);this.sceneViewPanel_ = new SceneViewPanel(sceneViewContainer, this.store_);- this.contentBrowserPanel_ = new ContentBrowserPanel(contentBrowserContainer);+ this.contentBrowserPanel_ = new ContentBrowserPanel(contentBrowserContainer, {+ projectPath: this.projectPath_ ?? undefined,+ });this.setupToolbarEvents();this.setupStatusbarEvents();@@ -278,21 +294,21 @@ export class Editor {const bottomPanel = this.container_.querySelector('.es-editor-bottom') as HTMLElement;if (this.assetsPanelVisible_) {- // Already showing assets, hide itthis.assetsPanelVisible_ = false;assetsBtn?.classList.remove('es-active');if (contentBrowser) contentBrowser.style.display = 'none';- if (bottomPanel) bottomPanel.style.display = this.outputPanelVisible_ ? 'flex' : 'none';+ if (bottomPanel) bottomPanel.style.display = this.outputPanelVisible_ ? '' : 'none';} else {- // Show assets, hide outputthis.assetsPanelVisible_ = true;this.outputPanelVisible_ = false;assetsBtn?.classList.add('es-active');outputBtn?.classList.remove('es-active');- if (contentBrowser) contentBrowser.style.display = 'block';+ if (contentBrowser) contentBrowser.style.display = '';if (outputPanel) outputPanel.style.display = 'none';- if (bottomPanel) bottomPanel.style.display = 'flex';+ if (bottomPanel) bottomPanel.style.display = '';}++ requestAnimationFrame(() => this.sceneViewPanel_?.resize());}private toggleOutputPanel(): void {@@ -303,21 +319,21 @@ export class Editor {const bottomPanel = this.container_.querySelector('.es-editor-bottom') as HTMLElement;if (this.outputPanelVisible_) {- // Already showing output, hide itthis.outputPanelVisible_ = false;outputBtn?.classList.remove('es-active');if (outputPanel) outputPanel.style.display = 'none';- if (bottomPanel) bottomPanel.style.display = this.assetsPanelVisible_ ? 'flex' : 'none';+ if (bottomPanel) bottomPanel.style.display = this.assetsPanelVisible_ ? '' : 'none';} else {- // Show output, hide assetsthis.outputPanelVisible_ = true;this.assetsPanelVisible_ = false;outputBtn?.classList.add('es-active');assetsBtn?.classList.remove('es-active');- if (outputPanel) outputPanel.style.display = 'block';+ if (outputPanel) outputPanel.style.display = '';if (contentBrowser) contentBrowser.style.display = 'none';- if (bottomPanel) bottomPanel.style.display = 'flex';+ if (bottomPanel) bottomPanel.style.display = '';}++ requestAnimationFrame(() => this.sceneViewPanel_?.resize());}private updateStatusbar(): void {@@ -349,6 +365,6 @@ export class Editor {// Factory Function// =============================================================================-export function createEditor(container: HTMLElement): Editor {- return new Editor(container);+export function createEditor(container: HTMLElement, options?: EditorOptions): Editor {+ return new Editor(container, options);}diff --git a/editor/src/index.ts b/editor/src/index.tsindex 4b15aa2a0..be1fbdb5b 100644--- a/editor/src/index.ts+++ b/editor/src/index.ts@@ -108,6 +108,38 @@ export {loadSceneFromFile,} from './io';+// =============================================================================+// Launcher+// =============================================================================++export {+ ProjectLauncher,+ NewProjectDialog,+ createProject,+ openProject,+ openProjectDialog,+ selectProjectLocation,+ getRecentProjects,+ loadProjectConfig,+ type ProjectLauncherOptions,+ type CreateProjectOptions,+ type ProjectServiceResult,+} from './launcher';++// =============================================================================+// Project Types+// =============================================================================++export {+ type ProjectConfig,+ type RecentProject,+ type ProjectTemplate,+ PROJECT_TEMPLATES,+ PROJECT_FILE_EXTENSION,+ SCENE_FILE_EXTENSION,+ ENGINE_VERSION,+} from './types/ProjectTypes';+// =============================================================================// Styles// =============================================================================diff --git a/editor/src/launcher/NewProjectDialog.ts b/editor/src/launcher/NewProjectDialog.tsnew file mode 100644index 000000000..7281434a5--- /dev/null+++ b/editor/src/launcher/NewProjectDialog.ts@@ -0,0 +1,201 @@+/**+ * @file NewProjectDialog.ts+ * @brief New project creation dialog+ */++import type { ProjectTemplate } from '../types/ProjectTypes';+import { PROJECT_TEMPLATES } from '../types/ProjectTypes';+import { createProject, selectProjectLocation } from './ProjectService';++// =============================================================================+// Types+// =============================================================================++export interface NewProjectDialogOptions {+ onClose: () => void;+ onProjectCreated: (projectPath: string) => void;+}++// =============================================================================+// NewProjectDialog+// =============================================================================++export class NewProjectDialog {+ private overlay_: HTMLElement;+ private options_: NewProjectDialogOptions;+ private selectedTemplate_: ProjectTemplate = 'empty';+ private projectLocation_: string = '';++ constructor(options: NewProjectDialogOptions) {+ this.options_ = options;++ this.overlay_ = document.createElement('div');+ this.overlay_.className = 'es-dialog-overlay';+ document.body.appendChild(this.overlay_);++ this.render();+ this.setupEvents();+ }++ dispose(): void {+ this.overlay_.remove();+ }++ private render(): void {+ const templatesHtml = PROJECT_TEMPLATES.map(+ (t) => `+ <label class="es-dialog-template ${t.id === this.selectedTemplate_ ? 'selected' : ''} ${!t.enabled ? 'disabled' : ''}">+ <input type="radio" name="template" value="${t.id}"+ ${t.id === this.selectedTemplate_ ? 'checked' : ''}+ ${!t.enabled ? 'disabled' : ''}>+ <span class="es-dialog-template-name">${t.name}</span>+ <span class="es-dialog-template-desc">${t.description}${!t.enabled ? ' (coming soon)' : ''}</span>+ </label>+ `+ ).join('');++ this.overlay_.innerHTML = `+ <div class="es-dialog">+ <div class="es-dialog-header">+ <span class="es-dialog-title">New Project</span>+ <button class="es-dialog-close" data-action="close">×</button>+ </div>+ <div class="es-dialog-body">+ <div class="es-dialog-field">+ <label class="es-dialog-label">Project Name</label>+ <input type="text" class="es-dialog-input" id="project-name"+ placeholder="My Game" value="MyGame">+ </div>+ <div class="es-dialog-field">+ <label class="es-dialog-label">Location</label>+ <div class="es-dialog-path-row">+ <input type="text" class="es-dialog-input es-dialog-path"+ id="project-location" placeholder="Select a folder..." readonly>+ <button class="es-dialog-browse" data-action="browse">...</button>+ </div>+ </div>+ <div class="es-dialog-field">+ <label class="es-dialog-label">Template</label>+ <div class="es-dialog-templates">+ ${templatesHtml}+ </div>+ </div>+ </div>+ <div class="es-dialog-footer">+ <button class="es-dialog-btn" data-action="cancel">Cancel</button>+ <button class="es-dialog-btn es-dialog-btn-primary" data-action="create">Create Project</button>+ </div>+ </div>+ `;+ }++ private setupEvents(): void {+ // Close button+ this.overlay_.querySelector('[data-action="close"]')?.addEventListener('click', () => {+ this.options_.onClose();+ });++ // Cancel button+ this.overlay_.querySelector('[data-action="cancel"]')?.addEventListener('click', () => {+ this.options_.onClose();+ });++ // Browse button+ this.overlay_.querySelector('[data-action="browse"]')?.addEventListener('click', () => {+ this.handleBrowse();+ });++ // Create button+ this.overlay_.querySelector('[data-action="create"]')?.addEventListener('click', () => {+ this.handleCreate();+ });++ // Template selection+ this.overlay_.querySelectorAll('input[name="template"]').forEach((input) => {+ input.addEventListener('change', (e) => {+ const target = e.target as HTMLInputElement;+ this.selectedTemplate_ = target.value as ProjectTemplate;+ this.updateTemplateSelection();+ });+ });++ // Overlay click to close+ this.overlay_.addEventListener('click', (e) => {+ if (e.target === this.overlay_) {+ this.options_.onClose();+ }+ });++ // Escape key to close+ const keyHandler = (e: KeyboardEvent) => {+ if (e.key === 'Escape') {+ this.options_.onClose();+ document.removeEventListener('keydown', keyHandler);+ }+ };+ document.addEventListener('keydown', keyHandler);+ }++ private updateTemplateSelection(): void {+ this.overlay_.querySelectorAll('.es-dialog-template').forEach((el) => {+ const input = el.querySelector('input') as HTMLInputElement;+ el.classList.toggle('selected', input.checked);+ });+ }++ private async handleBrowse(): Promise<void> {+ const path = await selectProjectLocation();+ if (path) {+ this.projectLocation_ = path;+ const locationInput = this.overlay_.querySelector('#project-location') as HTMLInputElement;+ if (locationInput) {+ locationInput.value = path;+ }+ }+ }++ private async handleCreate(): Promise<void> {+ const nameInput = this.overlay_.querySelector('#project-name') as HTMLInputElement;+ const name = nameInput?.value.trim();++ if (!name) {+ alert('Please enter a project name');+ nameInput?.focus();+ return;+ }++ if (!this.projectLocation_) {+ alert('Please select a project location');+ return;+ }++ // Validate project name+ if (!/^[a-zA-Z0-9_-]+$/.test(name)) {+ alert('Project name can only contain letters, numbers, underscores, and hyphens');+ nameInput?.focus();+ return;+ }++ const createBtn = this.overlay_.querySelector('[data-action="create"]') as HTMLButtonElement;+ if (createBtn) {+ createBtn.disabled = true;+ createBtn.textContent = 'Creating...';+ }++ const result = await createProject({+ name,+ location: this.projectLocation_,+ template: this.selectedTemplate_,+ });++ if (result.success && result.data) {+ this.options_.onProjectCreated(result.data);+ } else {+ alert(result.error ?? 'Failed to create project');+ if (createBtn) {+ createBtn.disabled = false;+ createBtn.textContent = 'Create Project';+ }+ }+ }+}diff --git a/editor/src/launcher/ProjectLauncher.ts b/editor/src/launcher/ProjectLauncher.tsnew file mode 100644index 000000000..1bd8f6528--- /dev/null+++ b/editor/src/launcher/ProjectLauncher.ts@@ -0,0 +1,210 @@+/**+ * @file ProjectLauncher.ts+ * @brief Project launcher/welcome screen component+ */++import type { RecentProject } from '../types/ProjectTypes';+import {+ getRecentProjects,+ removeRecentProject,+ openProject,+ openProjectDialog,+} from './ProjectService';+import { NewProjectDialog } from './NewProjectDialog';++// =============================================================================+// Types+// =============================================================================++export interface ProjectLauncherOptions {+ onProjectOpen: (projectPath: string) => void;+}++// =============================================================================+// ProjectLauncher+// =============================================================================++export class ProjectLauncher {+ private container_: HTMLElement;+ private options_: ProjectLauncherOptions;+ private newProjectDialog_: NewProjectDialog | null = null;++ constructor(container: HTMLElement, options: ProjectLauncherOptions) {+ this.container_ = container;+ this.options_ = options;++ this.render();+ }++ dispose(): void {+ this.newProjectDialog_?.dispose();+ this.newProjectDialog_ = null;+ this.container_.innerHTML = '';+ }++ private render(): void {+ this.container_.className = 'es-launcher';+ this.container_.innerHTML = `+ <div class="es-launcher-content">+ <div class="es-launcher-header">+ <div class="es-launcher-logo">+ <div class="es-launcher-logo-icon">ES</div>+ <div class="es-launcher-logo-text">+ <span class="es-launcher-title">ESEngine</span>+ <span class="es-launcher-subtitle">Editor</span>+ </div>+ </div>+ </div>++ <div class="es-launcher-actions">+ <button class="es-launcher-btn es-launcher-btn-primary" data-action="new">+ <span class="es-launcher-btn-icon">+</span>+ <span>New Project</span>+ </button>+ <button class="es-launcher-btn" data-action="open">+ <span class="es-launcher-btn-icon">📂</span>+ <span>Open Project</span>+ </button>+ </div>++ <div class="es-launcher-recent">+ <div class="es-launcher-recent-header">+ <span>Recent Projects</span>+ </div>+ <div class="es-launcher-recent-list"></div>+ </div>++ <div class="es-launcher-footer">+ <span>v0.1.0</span>+ </div>+ </div>+ `;++ this.renderRecentProjects();+ this.setupEvents();+ }++ private renderRecentProjects(): void {+ const listContainer = this.container_.querySelector('.es-launcher-recent-list');+ if (!listContainer) return;++ const projects = getRecentProjects();++ if (projects.length === 0) {+ listContainer.innerHTML = `+ <div class="es-launcher-recent-empty">+ No recent projects+ </div>+ `;+ return;+ }++ listContainer.innerHTML = projects+ .map((project, index) => this.renderRecentProjectItem(project, index))+ .join('');++ // Bind click events for recent project items+ listContainer.querySelectorAll('.es-launcher-recent-item').forEach((item, index) => {+ item.addEventListener('click', () => this.handleOpenRecentProject(projects[index]));+ });++ listContainer.querySelectorAll('.es-launcher-recent-remove').forEach((btn, index) => {+ btn.addEventListener('click', (e) => {+ e.stopPropagation();+ this.handleRemoveRecentProject(projects[index].path);+ });+ });+ }++ private renderRecentProjectItem(project: RecentProject, _index: number): string {+ const timeAgo = this.formatTimeAgo(project.lastOpened);+ const shortPath = this.shortenPath(project.path);++ return `+ <div class="es-launcher-recent-item">+ <div class="es-launcher-recent-icon">📁</div>+ <div class="es-launcher-recent-info">+ <div class="es-launcher-recent-name">${this.escapeHtml(project.name)}</div>+ <div class="es-launcher-recent-path">${this.escapeHtml(shortPath)}</div>+ </div>+ <div class="es-launcher-recent-time">${timeAgo}</div>+ <button class="es-launcher-recent-remove" title="Remove from list">×</button>+ </div>+ `;+ }++ private setupEvents(): void {+ const newBtn = this.container_.querySelector('[data-action="new"]');+ const openBtn = this.container_.querySelector('[data-action="open"]');++ newBtn?.addEventListener('click', () => this.handleNewProject());+ openBtn?.addEventListener('click', () => this.handleOpenProject());+ }++ private handleNewProject(): void {+ if (this.newProjectDialog_) return;++ this.newProjectDialog_ = new NewProjectDialog({+ onClose: () => {+ this.newProjectDialog_?.dispose();+ this.newProjectDialog_ = null;+ },+ onProjectCreated: (projectPath) => {+ this.newProjectDialog_?.dispose();+ this.newProjectDialog_ = null;+ this.options_.onProjectOpen(projectPath);+ },+ });+ }++ private async handleOpenProject(): Promise<void> {+ const result = await openProjectDialog();+ if (result.success && result.data) {+ this.options_.onProjectOpen(result.data);+ } else if (result.error && result.error !== 'No project selected') {+ alert(result.error);+ }+ }++ private async handleOpenRecentProject(project: RecentProject): Promise<void> {+ const result = await openProject(project.path);+ if (result.success && result.data) {+ this.options_.onProjectOpen(result.data);+ } else if (result.error) {+ alert(result.error);+ this.renderRecentProjects();+ }+ }++ private handleRemoveRecentProject(path: string): void {+ removeRecentProject(path);+ this.renderRecentProjects();+ }++ private formatTimeAgo(isoString: string): string {+ const date = new Date(isoString);+ const now = new Date();+ const diffMs = now.getTime() - date.getTime();+ const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24));++ if (diffDays === 0) return 'Today';+ if (diffDays === 1) return 'Yesterday';+ if (diffDays < 7) return `${diffDays} days ago`;+ if (diffDays < 30) return `${Math.floor(diffDays / 7)} weeks ago`;+ if (diffDays < 365) return `${Math.floor(diffDays / 30)} months ago`;+ return `${Math.floor(diffDays / 365)} years ago`;+ }++ private shortenPath(path: string): string {+ const normalized = path.replace(/\\/g, '/');+ const parts = normalized.split('/');+ if (parts.length <= 4) return normalized;+ return `.../${parts.slice(-3).join('/')}`;+ }++ private escapeHtml(text: string): string {+ const div = document.createElement('div');+ div.textContent = text;+ return div.innerHTML;+ }+}diff --git a/editor/src/launcher/ProjectService.ts b/editor/src/launcher/ProjectService.tsnew file mode 100644index 000000000..3f5ac5d8a--- /dev/null+++ b/editor/src/launcher/ProjectService.ts@@ -0,0 +1,480 @@+/**+ * @file ProjectService.ts+ * @brief Project creation and management service+ */++import type {+ ProjectConfig,+ RecentProject,+ ProjectTemplate,+} from '../types/ProjectTypes';+import { ENGINE_VERSION } from '../types/ProjectTypes';++// =============================================================================+// 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>;+}++function getNativeFS(): NativeFS | null {+ return (window as any).__esengine_fs ?? null;+}++// =============================================================================+// Recent Projects Storage+// =============================================================================++const RECENT_PROJECTS_KEY = 'esengine_recent_projects';+const MAX_RECENT_PROJECTS = 10;++export function getRecentProjects(): RecentProject[] {+ try {+ const data = localStorage.getItem(RECENT_PROJECTS_KEY);+ if (!data) return [];+ return JSON.parse(data) as RecentProject[];+ } catch {+ return [];+ }+}++export function addRecentProject(project: RecentProject): void {+ const projects = getRecentProjects().filter(p => p.path !== project.path);+ projects.unshift(project);+ if (projects.length > MAX_RECENT_PROJECTS) {+ projects.pop();+ }+ localStorage.setItem(RECENT_PROJECTS_KEY, JSON.stringify(projects));+}++export function removeRecentProject(path: string): void {+ const projects = getRecentProjects().filter(p => p.path !== path);+ localStorage.setItem(RECENT_PROJECTS_KEY, JSON.stringify(projects));+}++export function clearRecentProjects(): void {+ localStorage.removeItem(RECENT_PROJECTS_KEY);+}++// =============================================================================+// Project Service+// =============================================================================++export interface CreateProjectOptions {+ name: string;+ location: string;+ template: ProjectTemplate;+}++export interface ProjectServiceResult<T = void> {+ success: boolean;+ data?: T;+ error?: string;+}++function joinPath(...parts: string[]): string {+ return parts.join('/').replace(/\\/g, '/').replace(/\/+/g, '/');+}++function getProjectDir(location: string, name: string): string {+ return joinPath(location, name);+}++export async function selectProjectLocation(): Promise<string | null> {+ const fs = getNativeFS();+ if (!fs) {+ console.warn('Native FS not available');+ return null;+ }+ return fs.selectDirectory();+}++export async function createProject(+ options: CreateProjectOptions+): Promise<ProjectServiceResult<string>> {+ const fs = getNativeFS();+ if (!fs) {+ return { success: false, error: 'Native file system not available' };+ }++ const { name, location, template } = options;+ const projectDir = getProjectDir(location, name);++ // Check if directory already exists+ if (await fs.exists(projectDir)) {+ return { success: false, error: 'Project directory already exists' };+ }++ // Create project structure+ const directories = [+ projectDir,+ joinPath(projectDir, 'src'),+ joinPath(projectDir, 'assets'),+ joinPath(projectDir, 'assets/scenes'),+ joinPath(projectDir, 'assets/textures'),+ joinPath(projectDir, 'assets/audio'),+ joinPath(projectDir, '.esengine'),+ ];++ for (const dir of directories) {+ const success = await fs.createDirectory(dir);+ if (!success) {+ return { success: false, error: `Failed to create directory: ${dir}` };+ }+ }++ // Create project config+ const now = new Date().toISOString();+ const config: ProjectConfig = {+ name,+ version: '0.1.0',+ engine: ENGINE_VERSION,+ defaultScene: 'assets/scenes/main.esscene',+ created: now,+ modified: now,+ };++ const projectFilePath = joinPath(projectDir, 'project.esproject');+ const configJson = JSON.stringify(config, null, 2);+ if (!(await fs.writeFile(projectFilePath, configJson))) {+ return { success: false, error: 'Failed to write project file' };+ }++ // Create default scene based on template+ const defaultScene = createDefaultScene(name, template);+ const sceneFilePath = joinPath(projectDir, 'assets/scenes/main.esscene');+ if (!(await fs.writeFile(sceneFilePath, JSON.stringify(defaultScene, null, 2)))) {+ return { success: false, error: 'Failed to write default scene' };+ }++ // Create editor settings+ const editorSettings = {+ lastOpenedScene: 'assets/scenes/main.esscene',+ };+ const settingsPath = joinPath(projectDir, '.esengine/settings.json');+ await fs.writeFile(settingsPath, JSON.stringify(editorSettings, null, 2));++ // Create script files+ const scriptFiles = createProjectScripts(name, template);+ for (const [filePath, content] of Object.entries(scriptFiles)) {+ const fullPath = joinPath(projectDir, filePath);+ if (!(await fs.writeFile(fullPath, content))) {+ console.warn(`Failed to write script file: ${filePath}`);+ }+ }++ // Add to recent projects+ addRecentProject({+ name,+ path: projectFilePath,+ lastOpened: now,+ });++ return { success: true, data: projectFilePath };+}++export async function openProjectDialog(): Promise<ProjectServiceResult<string>> {+ const fs = getNativeFS();+ if (!fs) {+ return { success: false, error: 'Native file system not available' };+ }++ const projectPath = await fs.openProject();+ if (!projectPath) {+ return { success: false, error: 'No project selected' };+ }++ return openProject(projectPath);+}++export async function openProject(+ projectPath: string+): Promise<ProjectServiceResult<string>> {+ const fs = getNativeFS();+ if (!fs) {+ return { success: false, error: 'Native file system not available' };+ }++ // Validate project file exists+ if (!(await fs.exists(projectPath))) {+ removeRecentProject(projectPath);+ return { success: false, error: 'Project file not found' };+ }++ // Read and validate project config+ const content = await fs.readFile(projectPath);+ if (!content) {+ return { success: false, error: 'Failed to read project file' };+ }++ try {+ const config = JSON.parse(content) as ProjectConfig;+ if (!config.name || !config.version) {+ return { success: false, error: 'Invalid project file format' };+ }++ // Update recent projects+ addRecentProject({+ name: config.name,+ path: projectPath,+ lastOpened: new Date().toISOString(),+ });++ return { success: true, data: projectPath };+ } catch {+ return { success: false, error: 'Failed to parse project file' };+ }+}++export async function loadProjectConfig(+ projectPath: string+): Promise<ProjectConfig | null> {+ const fs = getNativeFS();+ if (!fs) return null;++ const content = await fs.readFile(projectPath);+ if (!content) return null;++ try {+ return JSON.parse(content) as ProjectConfig;+ } catch {+ return null;+ }+}++// =============================================================================+// Script Templates+// =============================================================================++const MAIN_TS_TEMPLATE = `/**+ * ESEngine Project Entry Point+ *+ * This file is the main entry point for your game logic.+ * Press F5 in the editor to run, or use Web Preview for browser testing.+ */+import {+ type ESEngineModule,+ App,+ createWebApp,+ defineSystem,+ Schedule,+ Commands,+ LocalTransform,+ Sprite,+ Camera,+ Canvas,+ Res,+ Time,+ Query,+ Mut,+ type Entity+} from 'esengine';++// =============================================================================+// Main Entry Point+// =============================================================================++export async function main(Module: ESEngineModule): Promise<void> {+ console.log('ESEngine starting...');++ // Create the app with WASM module (handles renderer init + render loop)+ const app = createWebApp(Module);++ // Add startup system - runs once at beginning+ app.addSystemToSchedule(Schedule.Startup, defineSystem(+ [Commands()],+ (cmds) => {+ console.log('Startup: Creating entities...');++ // Create camera+ const camera = cmds.spawn()+ .insert(Camera, {+ projectionType: 1, // Orthographic+ fov: 60,+ orthoSize: 400,+ nearPlane: 0.1,+ farPlane: 1000,+ aspectRatio: 1,+ isActive: true,+ priority: 0+ })+ .insert(LocalTransform, {+ position: { x: 0, y: 0, z: 10 },+ rotation: { w: 1, x: 0, y: 0, z: 0 },+ scale: { x: 1, y: 1, z: 1 }+ })+ .id();++ // Create a test sprite+ const sprite = cmds.spawn()+ .insert(Sprite, {+ texture: 0,+ color: { x: 1, y: 0.5, z: 0.2, w: 1 },+ size: { x: 100, y: 100 },+ uvOffset: { x: 0, y: 0 },+ uvScale: { x: 1, y: 1 },+ layer: 0,+ flipX: false,+ flipY: false+ })+ .insert(LocalTransform, {+ position: { x: 0, y: 0, z: 0 },+ rotation: { w: 1, x: 0, y: 0, z: 0 },+ scale: { x: 1, y: 1, z: 1 }+ })+ .id();++ console.log(\`Created camera: \${camera}, sprite: \${sprite}\`);+ }+ ));++ // Add update system - runs every frame+ app.addSystemToSchedule(Schedule.Update, defineSystem(+ [Res(Time), Query(LocalTransform, Sprite)],+ (time, query) => {+ for (const [entity, transform, sprite] of query) {+ // Move the sprite in a circle+ transform.position.x = Math.sin(time.elapsed) * 100;+ transform.position.y = Math.cos(time.elapsed) * 100;+ }+ }+ ));++ // Start the game loop+ console.log('Starting game loop...');+ app.run();+}+`;++function createPackageJson(projectName: string): string {+ return JSON.stringify({+ name: projectName.toLowerCase().replace(/\s+/g, '-'),+ version: '0.1.0',+ type: 'module',+ scripts: {+ build: 'rollup -c',+ watch: 'rollup -c -w',+ },+ devDependencies: {+ '@rollup/plugin-node-resolve': '^15.2.3',+ '@rollup/plugin-typescript': '^11.1.6',+ rollup: '^4.18.0',+ typescript: '^5.4.5',+ },+ dependencies: {+ esengine: '^0.1.0',+ },+ }, null, 2);+}++const TSCONFIG_TEMPLATE = JSON.stringify({+ compilerOptions: {+ target: 'ES2020',+ module: 'ESNext',+ moduleResolution: 'bundler',+ strict: true,+ esModuleInterop: true,+ skipLibCheck: true,+ forceConsistentCasingInFileNames: true,+ declaration: false,+ outDir: './dist',+ rootDir: './src',+ },+ include: ['src/**/*'],+ exclude: ['node_modules'],+}, null, 2);++const ROLLUP_CONFIG_TEMPLATE = `import resolve from '@rollup/plugin-node-resolve';+import typescript from '@rollup/plugin-typescript';++export default {+ input: 'src/main.ts',+ output: {+ file: 'dist/bundle.js',+ format: 'es',+ sourcemap: true+ },+ plugins: [+ resolve(),+ typescript()+ ],+ external: ['esengine']+};+`;++const GITIGNORE_TEMPLATE = `# Dependencies+node_modules/++# Build outputs+dist/++# IDE+.vscode/+.idea/++# OS+.DS_Store+Thumbs.db++# Editor cache+.esengine/cache/+`;++function createProjectScripts(+ name: string,+ _template: ProjectTemplate+): Record<string, string> {+ return {+ 'src/main.ts': MAIN_TS_TEMPLATE,+ 'package.json': createPackageJson(name),+ 'tsconfig.json': TSCONFIG_TEMPLATE,+ 'rollup.config.js': ROLLUP_CONFIG_TEMPLATE,+ '.gitignore': GITIGNORE_TEMPLATE,+ };+}++// =============================================================================+// Default Scene Creation+// =============================================================================++function createDefaultScene(projectName: string, _template: ProjectTemplate) {+ return {+ version: '1.0',+ name: 'Main',+ entities: [+ {+ id: 1,+ name: 'Camera',+ parent: null,+ children: [],+ components: [+ {+ type: 'LocalTransform',+ data: {+ position: { x: 0, y: 0, z: 10 },+ rotation: { x: 0, y: 0, z: 0, w: 1 },+ scale: { x: 1, y: 1, z: 1 },+ },+ },+ {+ type: 'Camera',+ data: {+ isActive: true,+ projectionType: 1,+ fov: 60,+ orthoSize: 400,+ nearPlane: 0.1,+ farPlane: 1000,+ },+ },+ ],+ },+ ],+ };+}diff --git a/editor/src/launcher/index.ts b/editor/src/launcher/index.tsnew file mode 100644index 000000000..df09ced15--- /dev/null+++ b/editor/src/launcher/index.ts@@ -0,0 +1,23 @@+/**+ * @file index.ts+ * @brief Launcher module exports+ */++export { ProjectLauncher } from './ProjectLauncher';+export type { ProjectLauncherOptions } from './ProjectLauncher';++export { NewProjectDialog } from './NewProjectDialog';+export type { NewProjectDialogOptions } from './NewProjectDialog';++export {+ createProject,+ openProject,+ openProjectDialog,+ selectProjectLocation,+ getRecentProjects,+ addRecentProject,+ removeRecentProject,+ clearRecentProjects,+ loadProjectConfig,+} from './ProjectService';+export type { CreateProjectOptions, ProjectServiceResult } from './ProjectService';diff --git a/editor/src/panels/ContentBrowserPanel.ts b/editor/src/panels/ContentBrowserPanel.tsindex b3f18a808..b4093267b 100644--- a/editor/src/panels/ContentBrowserPanel.ts+++ b/editor/src/panels/ContentBrowserPanel.ts@@ -9,17 +9,113 @@ import { icons } from '../utils/icons';// 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>;+}+interface FolderNode {name: string;path: string;children: FolderNode[];expanded: boolean;+ loaded: boolean;}interface AssetItem {name: string;path: string;- type: 'folder' | 'file';+ type: 'folder' | 'scene' | 'script' | 'image' | 'audio' | 'json' | 'file';+}++export interface ContentBrowserOptions {+ projectPath?: string;+}++// =============================================================================+// Helpers+// =============================================================================++function getNativeFS(): NativeFS | null {+ return (window as any).__esengine_fs ?? 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() : '';+}++function getAssetType(entry: DirectoryEntry): AssetItem['type'] {+ if (entry.isDirectory) return 'folder';++ const ext = getFileExtension(entry.name);+ switch (ext) {+ case '.esscene':+ return 'scene';+ case '.ts':+ case '.js':+ return 'script';+ case '.png':+ case '.jpg':+ case '.jpeg':+ case '.gif':+ case '.webp':+ case '.bmp':+ return 'image';+ case '.mp3':+ case '.wav':+ case '.ogg':+ case '.flac':+ return 'audio';+ case '.json':+ return 'json';+ default:+ return 'file';+ }+}++function getAssetIcon(type: AssetItem['type'], size: number = 32): string {+ switch (type) {+ case 'folder':+ return icons.folder(size);+ case 'scene':+ return icons.layers(size);+ case 'script':+ return icons.code(size);+ case 'image':+ return icons.image(size);+ case 'audio':+ return icons.volume(size);+ case 'json':+ return icons.braces(size);+ default:+ return icons.file(size);+ }}// =============================================================================@@ -33,22 +129,27 @@ export class ContentBrowserPanel {private footerContainer_: HTMLElement | null = null;private searchInput_: HTMLInputElement | null = null;- private rootFolder_: FolderNode;- private currentPath_: string = 'assets';+ private projectPath_: string | null = null;+ private rootFolder_: FolderNode | null = null;+ private currentPath_: string = '';private searchFilter_: string = '';+ private unwatchFn_: (() => void) | null = null;+ private currentItems_: AssetItem[] = [];- constructor(container: HTMLElement) {+ constructor(container: HTMLElement, options?: ContentBrowserOptions) {this.container_ = container;+ this.projectPath_ = options?.projectPath ?? null;- this.rootFolder_ = this.createMockFolderStructure();+ if (this.projectPath_) {+ this.currentPath_ = getParentPath(this.projectPath_);+ }this.container_.classList.add('es-content-browser');this.container_.innerHTML = `<div class="es-content-browser-header"><span class="es-content-browser-title">${icons.folder(14)} Content Browser</span><div class="es-content-browser-actions">- <button class="es-btn es-btn-icon" title="Minimize">${icons.chevronDown(12)}</button>- <button class="es-btn es-btn-icon" title="Close">${icons.x(12)}</button>+ <button class="es-btn es-btn-icon es-refresh-btn" title="Refresh">${icons.refresh(12)}</button></div></div><div class="es-content-browser-body">@@ -69,27 +170,130 @@ export class ContentBrowserPanel {this.searchInput_ = this.container_.querySelector('.es-content-search');this.setupEvents();- this.render();+ this.initialize();}dispose(): void {- // Cleanup+ if (this.unwatchFn_) {+ this.unwatchFn_();+ this.unwatchFn_ = null;+ }+ }++ private async initialize(): Promise<void> {+ if (this.projectPath_) {+ await this.loadProjectDirectory();+ await this.setupFileWatcher();+ } else {+ this.rootFolder_ = this.createEmptyFolderStructure();+ this.render();+ }+ }++ private async loadProjectDirectory(): Promise<void> {+ const projectDir = getParentPath(this.projectPath_!);+ this.currentPath_ = projectDir;++ this.rootFolder_ = {+ name: this.getProjectName(),+ path: projectDir,+ children: [],+ expanded: true,+ loaded: false,+ };++ await this.loadFolderChildren(this.rootFolder_);+ this.render();}- private createMockFolderStructure(): FolderNode {+ private getProjectName(): string {+ if (!this.projectPath_) return 'Project';+ const normalized = this.projectPath_.replace(/\\/g, '/');+ const parts = normalized.split('/');+ return parts[parts.length - 2] || 'Project';+ }++ private async loadFolderChildren(folder: FolderNode): Promise<void> {+ const fs = getNativeFS();+ if (!fs) return;++ try {+ const entries = await fs.listDirectoryDetailed(folder.path);++ folder.children = entries+ .filter(e => e.isDirectory && !e.name.startsWith('.'))+ .sort((a, b) => a.name.localeCompare(b.name))+ .map(e => ({+ name: e.name,+ path: joinPath(folder.path, e.name),+ children: [],+ expanded: false,+ loaded: false,+ }));++ folder.loaded = true;+ } catch (err) {+ console.error('Failed to load folder:', folder.path, err);+ }+ }++ private async setupFileWatcher(): Promise<void> {+ const fs = getNativeFS();+ if (!fs || !this.projectPath_) return;++ const projectDir = getParentPath(this.projectPath_);++ try {+ this.unwatchFn_ = await fs.watchDirectory(+ projectDir,+ (event) => {+ console.log('File change:', event);+ this.refresh();+ },+ { recursive: true }+ );+ } catch (err) {+ console.error('Failed to setup file watcher:', err);+ }+ }++ async refresh(): Promise<void> {+ if (this.rootFolder_ && this.projectPath_) {+ this.rootFolder_.loaded = false;+ await this.loadFolderChildren(this.rootFolder_);++ const expandedPaths = this.collectExpandedPaths(this.rootFolder_);+ for (const path of expandedPaths) {+ const folder = this.findFolder(this.rootFolder_, path);+ if (folder && !folder.loaded) {+ await this.loadFolderChildren(folder);+ }+ }++ this.render();+ }+ }++ private collectExpandedPaths(node: FolderNode): string[] {+ const paths: string[] = [];+ if (node.expanded) {+ paths.push(node.path);+ for (const child of node.children) {+ paths.push(...this.collectExpandedPaths(child));+ }+ }+ return paths;+ }++ private createEmptyFolderStructure(): FolderNode {return {- name: 'assets',- path: 'assets',+ name: 'Project',+ path: '',expanded: true,+ loaded: true,children: [- { name: '.esengine', path: 'assets/.esengine', expanded: false, children: [] },- { name: 'audio', path: 'assets/audio', expanded: false, children: [] },- { name: 'fonts', path: 'assets/fonts', expanded: false, children: [] },- { name: 'prefabs', path: 'assets/prefabs', expanded: false, children: [] },- { name: 'scenes', path: 'assets/scenes', expanded: false, children: [] },- { name: 'scripts', path: 'assets/scripts', expanded: false, children: [] },- { name: 'shaders', path: 'assets/shaders', expanded: false, children: [] },- { name: 'textures', path: 'assets/textures', expanded: false, children: [] },+ { name: 'assets', path: 'assets', expanded: false, loaded: true, children: [] },+ { name: 'src', path: 'src', expanded: false, loaded: true, children: [] },],};}@@ -100,7 +304,7 @@ export class ContentBrowserPanel {this.renderGrid();});- this.treeContainer_?.addEventListener('click', (e) => {+ this.treeContainer_?.addEventListener('click', async (e) => {const target = e.target as HTMLElement;const item = target.closest('.es-folder-item') as HTMLElement;if (!item) return;@@ -109,13 +313,13 @@ export class ContentBrowserPanel {if (!path) return;if (target.closest('.es-folder-expand')) {- this.toggleFolder(path);+ await this.toggleFolder(path);} else {this.selectFolder(path);}});- this.gridContainer_?.addEventListener('dblclick', (e) => {+ this.gridContainer_?.addEventListener('dblclick', async (e) => {const target = e.target as HTMLElement;const item = target.closest('.es-asset-item') as HTMLElement;if (!item) return;@@ -125,23 +329,44 @@ export class ContentBrowserPanel {if (type === 'folder' && path) {this.selectFolder(path);- this.expandFolder(path);+ await this.expandFolder(path);+ } else if (path) {+ this.onAssetDoubleClick(path, type as AssetItem['type']);}});++ const refreshBtn = this.container_.querySelector('.es-refresh-btn');+ refreshBtn?.addEventListener('click', () => {+ this.refresh();+ });}- private toggleFolder(path: string): void {+ private onAssetDoubleClick(path: string, type: AssetItem['type']): void {+ console.log('Asset double-clicked:', path, type);+ }++ private async toggleFolder(path: string): Promise<void> {const folder = this.findFolder(this.rootFolder_, path);if (folder) {folder.expanded = !folder.expanded;++ if (folder.expanded && !folder.loaded) {+ await this.loadFolderChildren(folder);+ }+this.renderTree();}}- private expandFolder(path: string): void {+ private async expandFolder(path: string): Promise<void> {const folder = this.findFolder(this.rootFolder_, path);if (folder) {folder.expanded = true;++ if (!folder.loaded) {+ await this.loadFolderChildren(folder);+ }+this.renderTree();}}@@ -152,7 +377,8 @@ export class ContentBrowserPanel {this.renderGrid();}- private findFolder(node: FolderNode, path: string): FolderNode | null {+ private findFolder(node: FolderNode | null, path: string): FolderNode | null {+ if (!node) return null;if (node.path === path) return node;for (const child of node.children) {const found = this.findFolder(child, path);@@ -167,13 +393,13 @@ export class ContentBrowserPanel {}private renderTree(): void {- if (!this.treeContainer_) return;+ if (!this.treeContainer_ || !this.rootFolder_) return;this.treeContainer_.innerHTML = this.renderFolderNode(this.rootFolder_, 0);}private renderFolderNode(node: FolderNode, depth: number): string {const isSelected = node.path === this.currentPath_;- const hasChildren = node.children.length > 0;+ const hasChildren = node.children.length > 0 || !node.loaded;const indent = depth * 16;let html = `@@ -186,7 +412,7 @@ export class ContentBrowserPanel {</div>`;- if (node.expanded && hasChildren) {+ if (node.expanded) {for (const child of node.children) {html += this.renderFolderNode(child, depth + 1);}@@ -195,29 +421,24 @@ export class ContentBrowserPanel {return html;}- private renderGrid(): void {+ private async renderGrid(): Promise<void> {if (!this.gridContainer_) return;- const currentFolder = this.findFolder(this.rootFolder_, this.currentPath_);- if (!currentFolder) return;-- let items: AssetItem[] = currentFolder.children.map((child) => ({- name: child.name,- path: child.path,- type: 'folder' as const,- }));+ const items = await this.loadCurrentFolderItems();+ this.currentItems_ = items;+ let filteredItems = items;if (this.searchFilter_) {- items = items.filter((item) =>+ filteredItems = items.filter((item) =>item.name.toLowerCase().includes(this.searchFilter_));}- this.gridContainer_.innerHTML = items+ this.gridContainer_.innerHTML = filteredItems.map((item) => `<div class="es-asset-item" data-path="${item.path}" data-type="${item.type}">- <div class="es-asset-icon">${icons.folder(32)}</div>+ <div class="es-asset-icon">${getAssetIcon(item.type)}</div><div class="es-asset-name">${item.name}</div></div>`@@ -225,7 +446,46 @@ export class ContentBrowserPanel {.join('');if (this.footerContainer_) {- this.footerContainer_.textContent = `${items.length} items`;+ this.footerContainer_.textContent = `${filteredItems.length} items`;+ }+ }++ private async loadCurrentFolderItems(): Promise<AssetItem[]> {+ const fs = getNativeFS();+ if (!fs || !this.currentPath_) {+ return this.getFallbackItems();+ }++ try {+ const entries = await fs.listDirectoryDetailed(this.currentPath_);++ return entries+ .filter(e => !e.name.startsWith('.'))+ .sort((a, b) => {+ if (a.isDirectory !== b.isDirectory) {+ return a.isDirectory ? -1 : 1;+ }+ return a.name.localeCompare(b.name);+ })+ .map(e => ({+ name: e.name,+ path: joinPath(this.currentPath_, e.name),+ type: getAssetType(e),+ }));+ } catch (err) {+ console.error('Failed to load folder items:', err);+ return this.getFallbackItems();}}++ private getFallbackItems(): AssetItem[] {+ const currentFolder = this.findFolder(this.rootFolder_, this.currentPath_);+ if (!currentFolder) return [];++ return currentFolder.children.map((child) => ({+ name: child.name,+ path: child.path,+ type: 'folder' as const,+ }));+ }}diff --git a/editor/src/panels/SceneViewPanel.ts b/editor/src/panels/SceneViewPanel.tsindex edc1f7c3a..51141ef56 100644--- a/editor/src/panels/SceneViewPanel.ts+++ b/editor/src/panels/SceneViewPanel.ts@@ -18,6 +18,7 @@ export class SceneViewPanel {private canvas_: HTMLCanvasElement;private unsubscribe_: (() => void) | null = null;private animationId_: number | null = null;+ private resizeObserver_: ResizeObserver | null = null;private panX_ = 0;private panY_ = 0;@@ -60,6 +61,10 @@ export class SceneViewPanel {this.unsubscribe_();this.unsubscribe_ = null;}+ if (this.resizeObserver_) {+ this.resizeObserver_.disconnect();+ this.resizeObserver_ = null;+ }}setBridge(bridge: EditorBridge): void {@@ -103,7 +108,13 @@ export class SceneViewPanel {this.canvas_.addEventListener('wheel', this.onWheel.bind(this));this.canvas_.addEventListener('click', this.onClick.bind(this));- window.addEventListener('resize', () => this.resize());+ const viewport = this.container_.querySelector('.es-sceneview-viewport');+ if (viewport) {+ this.resizeObserver_ = new ResizeObserver(() => {+ this.resize();+ });+ this.resizeObserver_.observe(viewport);+ }}private onMouseDown(e: MouseEvent): void {diff --git a/editor/src/styles/editor.css b/editor/src/styles/editor.cssindex ec6b65578..44ccedb38 100644--- a/editor/src/styles/editor.css+++ b/editor/src/styles/editor.css@@ -1215,3 +1215,400 @@ svg {.es-btn-tab.es-active svg {stroke: #d19a66;}++/* =============================================================================+ * Project Launcher+ * ============================================================================= */++.es-launcher {+ width: 100%;+ height: 100%;+ background: var(--es-bg-primary);+ display: flex;+ align-items: center;+ justify-content: center;+}++.es-launcher-content {+ width: 100%;+ max-width: 600px;+ padding: 40px;+}++.es-launcher-header {+ text-align: center;+ margin-bottom: 40px;+}++.es-launcher-logo {+ display: inline-flex;+ align-items: center;+ gap: 16px;+}++.es-launcher-logo-icon {+ width: 64px;+ height: 64px;+ background: linear-gradient(135deg, #d19a66, #e5c07b);+ border-radius: 12px;+ display: flex;+ align-items: center;+ justify-content: center;+ font-size: 24px;+ font-weight: bold;+ color: #1e1e1e;+}++.es-launcher-logo-text {+ display: flex;+ flex-direction: column;+ align-items: flex-start;+}++.es-launcher-title {+ font-size: 28px;+ font-weight: 600;+ color: var(--es-text-primary);+}++.es-launcher-subtitle {+ font-size: 16px;+ color: var(--es-text-secondary);+}++.es-launcher-actions {+ display: flex;+ gap: 12px;+ margin-bottom: 32px;+}++.es-launcher-btn {+ flex: 1;+ display: flex;+ align-items: center;+ justify-content: center;+ gap: 8px;+ padding: 16px 24px;+ background: var(--es-bg-secondary);+ border: 1px solid var(--es-border);+ color: var(--es-text-primary);+ font-size: 14px;+ cursor: pointer;+ transition: all 0.15s;+}++.es-launcher-btn:hover {+ background: var(--es-bg-hover);+ border-color: var(--es-text-secondary);+}++.es-launcher-btn-primary {+ background: #d19a66;+ border-color: #d19a66;+ color: #1e1e1e;+ font-weight: 500;+}++.es-launcher-btn-primary:hover {+ background: #e5c07b;+ border-color: #e5c07b;+}++.es-launcher-btn-icon {+ font-size: 18px;+}++.es-launcher-recent {+ background: var(--es-bg-secondary);+ border: 1px solid var(--es-border);+}++.es-launcher-recent-header {+ padding: 12px 16px;+ border-bottom: 1px solid var(--es-border);+ color: var(--es-text-secondary);+ font-size: 12px;+ text-transform: uppercase;+ letter-spacing: 0.5px;+}++.es-launcher-recent-list {+ max-height: 300px;+ overflow-y: auto;+}++.es-launcher-recent-empty {+ padding: 40px 20px;+ text-align: center;+ color: var(--es-text-secondary);+}++.es-launcher-recent-item {+ display: flex;+ align-items: center;+ gap: 12px;+ padding: 12px 16px;+ cursor: pointer;+ transition: background 0.15s;+}++.es-launcher-recent-item:hover {+ background: var(--es-bg-hover);+}++.es-launcher-recent-icon {+ font-size: 20px;+ flex-shrink: 0;+}++.es-launcher-recent-info {+ flex: 1;+ min-width: 0;+}++.es-launcher-recent-name {+ color: var(--es-text-primary);+ font-size: 14px;+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+}++.es-launcher-recent-path {+ color: var(--es-text-secondary);+ font-size: 12px;+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+}++.es-launcher-recent-time {+ color: var(--es-text-secondary);+ font-size: 12px;+ flex-shrink: 0;+}++.es-launcher-recent-remove {+ width: 24px;+ height: 24px;+ background: transparent;+ border: none;+ color: var(--es-text-secondary);+ font-size: 16px;+ cursor: pointer;+ opacity: 0;+ transition: opacity 0.15s;+}++.es-launcher-recent-item:hover .es-launcher-recent-remove {+ opacity: 1;+}++.es-launcher-recent-remove:hover {+ color: var(--es-danger);+}++.es-launcher-footer {+ margin-top: 24px;+ text-align: center;+ color: var(--es-text-secondary);+ font-size: 12px;+}++/* =============================================================================+ * Dialog Overlay+ * ============================================================================= */++.es-dialog-overlay {+ position: fixed;+ top: 0;+ left: 0;+ right: 0;+ bottom: 0;+ background: rgba(0, 0, 0, 0.6);+ display: flex;+ align-items: center;+ justify-content: center;+ z-index: 1000;+}++.es-dialog {+ width: 100%;+ max-width: 480px;+ background: var(--es-bg-secondary);+ border: 1px solid var(--es-border);+ box-shadow: 0 8px 32px rgba(0, 0, 0, 0.4);+}++.es-dialog-header {+ display: flex;+ align-items: center;+ justify-content: space-between;+ padding: 16px 20px;+ border-bottom: 1px solid var(--es-border);+}++.es-dialog-title {+ font-size: 16px;+ font-weight: 500;+ color: var(--es-text-primary);+}++.es-dialog-close {+ width: 28px;+ height: 28px;+ background: transparent;+ border: none;+ color: var(--es-text-secondary);+ font-size: 20px;+ cursor: pointer;+ display: flex;+ align-items: center;+ justify-content: center;+}++.es-dialog-close:hover {+ color: var(--es-text-primary);+}++.es-dialog-body {+ padding: 20px;+}++.es-dialog-field {+ margin-bottom: 16px;+}++.es-dialog-field:last-child {+ margin-bottom: 0;+}++.es-dialog-label {+ display: block;+ margin-bottom: 6px;+ font-size: 13px;+ color: var(--es-text-secondary);+}++.es-dialog-input {+ width: 100%;+ padding: 8px 12px;+ background: var(--es-bg-primary);+ border: 1px solid var(--es-border);+ color: var(--es-text-primary);+ font-size: 14px;+}++.es-dialog-input:focus {+ outline: none;+ border-color: var(--es-accent);+}++.es-dialog-path-row {+ display: flex;+ gap: 8px;+}++.es-dialog-path {+ flex: 1;+}++.es-dialog-browse {+ padding: 8px 16px;+ background: var(--es-bg-tertiary);+ border: 1px solid var(--es-border);+ color: var(--es-text-primary);+ cursor: pointer;+}++.es-dialog-browse:hover {+ background: var(--es-bg-hover);+}++.es-dialog-templates {+ display: flex;+ flex-direction: column;+ gap: 8px;+}++.es-dialog-template {+ display: flex;+ align-items: flex-start;+ gap: 12px;+ padding: 12px;+ background: var(--es-bg-primary);+ border: 1px solid var(--es-border);+ cursor: pointer;+ transition: all 0.15s;+}++.es-dialog-template:hover:not(.disabled) {+ border-color: var(--es-text-secondary);+}++.es-dialog-template.selected {+ border-color: #d19a66;+ background: rgba(209, 154, 102, 0.1);+}++.es-dialog-template.disabled {+ opacity: 0.5;+ cursor: not-allowed;+}++.es-dialog-template input {+ margin-top: 2px;+}++.es-dialog-template-name {+ display: block;+ color: var(--es-text-primary);+ font-size: 14px;+ font-weight: 500;+}++.es-dialog-template-desc {+ display: block;+ color: var(--es-text-secondary);+ font-size: 12px;+ margin-top: 2px;+}++.es-dialog-footer {+ display: flex;+ justify-content: flex-end;+ gap: 8px;+ padding: 16px 20px;+ border-top: 1px solid var(--es-border);+}++.es-dialog-btn {+ padding: 8px 20px;+ background: var(--es-bg-tertiary);+ border: 1px solid var(--es-border);+ color: var(--es-text-primary);+ font-size: 14px;+ cursor: pointer;+ transition: all 0.15s;+}++.es-dialog-btn:hover {+ background: var(--es-bg-hover);+}++.es-dialog-btn:disabled {+ opacity: 0.5;+ cursor: not-allowed;+}++.es-dialog-btn-primary {+ background: #d19a66;+ border-color: #d19a66;+ color: #1e1e1e;+ font-weight: 500;+}++.es-dialog-btn-primary:hover:not(:disabled) {+ background: #e5c07b;+ border-color: #e5c07b;+}diff --git a/editor/src/types/ProjectTypes.ts b/editor/src/types/ProjectTypes.tsnew file mode 100644index 000000000..b76209406--- /dev/null+++ b/editor/src/types/ProjectTypes.ts@@ -0,0 +1,69 @@+/**+ * @file ProjectTypes.ts+ * @brief Project configuration and management types+ */++// =============================================================================+// Project Configuration+// =============================================================================++export interface ProjectConfig {+ name: string;+ version: string;+ engine: string;+ defaultScene: string;+ created: string;+ modified: string;+}++// =============================================================================+// Recent Projects+// =============================================================================++export interface RecentProject {+ name: string;+ path: string;+ lastOpened: string;+}++// =============================================================================+// Project Templates+// =============================================================================++export type ProjectTemplate = 'empty' | '2d' | '3d';++export interface ProjectTemplateInfo {+ id: ProjectTemplate;+ name: string;+ description: string;+ enabled: boolean;+}++export const PROJECT_TEMPLATES: ProjectTemplateInfo[] = [+ {+ id: 'empty',+ name: 'Empty Project',+ description: 'A blank project with basic folder structure',+ enabled: true,+ },+ {+ id: '2d',+ name: '2D Game',+ description: 'Template for 2D games with sprite rendering',+ enabled: false,+ },+ {+ id: '3d',+ name: '3D Game',+ description: 'Template for 3D games with camera and lighting',+ enabled: false,+ },+];++// =============================================================================+// Constants+// =============================================================================++export const PROJECT_FILE_EXTENSION = '.esproject';+export const SCENE_FILE_EXTENSION = '.esscene';+export const ENGINE_VERSION = '0.1.0';diff --git a/editor/src/utils/icons.ts b/editor/src/utils/icons.tsindex 1a90f31f2..4395d351d 100644--- a/editor/src/utils/icons.ts+++ b/editor/src/utils/icons.ts@@ -33,6 +33,11 @@ import {File,Search,Trash2,+ RefreshCw,+ Layers,+ Code,+ Volume2,+ Braces,} from 'lucide';// =============================================================================@@ -94,6 +99,11 @@ export const icons = {file: (size?: number) => renderIcon(File as IconNode, size),search: (size?: number) => renderIcon(Search as IconNode, size),trash: (size?: number) => renderIcon(Trash2 as IconNode, size),+ refresh: (size?: number) => renderIcon(RefreshCw as IconNode, size),+ layers: (size?: number) => renderIcon(Layers as IconNode, size),+ code: (size?: number) => renderIcon(Code as IconNode, size),+ volume: (size?: number) => renderIcon(Volume2 as IconNode, size),+ braces: (size?: number) => renderIcon(Braces as IconNode, size),};export type IconName = keyof typeof icons;diff --git a/templates/src/main.ts b/templates/src/main.tsindex c996c9159..19058f0b9 100644--- a/templates/src/main.ts+++ b/templates/src/main.ts@@ -4,8 +4,8 @@* This file is the main entry point for your game logic.* Press F5 in the editor to run, or use Web Preview for browser testing.*/-import type { ESEngineModule } from 'esengine/wasm';import {+ type ESEngineModule,App,createWebApp,defineSystem,@@ -18,8 +18,9 @@ import {Res,Time,Query,+ Mut,type Entity-} from 'esengine/ecs';+} from 'esengine';// =============================================================================// Main Entry Point