Feature/tilemap editor (#237)
* feat: 添加 Tilemap 编辑器插件和组件生命周期支持 * feat(editor-core): 添加声明式插件注册 API * feat(editor-core): 改进tiledmap结构合并tileset进tiledmapeditor * feat: 添加 editor-runtime SDK 和插件系统改进 * fix(ci): 修复SceneResourceManager里变量未使用问题
This commit is contained in:
@@ -4,9 +4,12 @@
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>ECS Framework Editor</title>
|
||||
<!-- ES Module Shims: 为不支持 Import Maps 的浏览器提供 polyfill -->
|
||||
<script async src="https://ga.jspm.io/npm:es-module-shims@1.10.0/dist/es-module-shims.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<!-- Import Map 将由 PluginLoader 在运行时动态注入 -->
|
||||
<script type="module" src="/src/main.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -5,20 +5,21 @@
|
||||
"type": "module",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "tsc && vite build",
|
||||
"preview": "vite preview",
|
||||
"build:sdk": "cd ../editor-runtime && pnpm build",
|
||||
"build": "npm run build:sdk && tsc && vite build",
|
||||
"build:watch": "vite build --watch",
|
||||
"tauri": "tauri",
|
||||
"kill-dev": "node scripts/kill-dev-server.js",
|
||||
"tauri:dev": "npm run kill-dev && tauri dev",
|
||||
"tauri:dev": "npm run build:sdk && tauri dev",
|
||||
"bundle:runtime": "node scripts/bundle-runtime.mjs",
|
||||
"tauri:build": "npm run bundle:runtime && tauri build",
|
||||
"tauri:build": "npm run build:sdk && npm run bundle:runtime && tauri build",
|
||||
"version": "node scripts/sync-version.js && git add src-tauri/tauri.conf.json"
|
||||
},
|
||||
"dependencies": {
|
||||
"@esengine/asset-system": "workspace:*",
|
||||
"@esengine/behavior-tree": "workspace:*",
|
||||
"@esengine/ecs-components": "workspace:*",
|
||||
"@esengine/tilemap": "workspace:*",
|
||||
"@esengine/tilemap-editor": "workspace:*",
|
||||
"@esengine/ecs-engine-bindgen": "workspace:*",
|
||||
"@esengine/ecs-framework": "workspace:*",
|
||||
"@esengine/editor-core": "workspace:*",
|
||||
|
||||
3127
packages/editor-app/pnpm-lock.yaml
generated
Normal file
3127
packages/editor-app/pnpm-lock.yaml
generated
Normal file
File diff suppressed because it is too large
Load Diff
15
packages/editor-app/public/assets/react-dom-shim.js
vendored
Normal file
15
packages/editor-app/public/assets/react-dom-shim.js
vendored
Normal file
@@ -0,0 +1,15 @@
|
||||
// React DOM shim - 从全局变量导出 ReactDOM
|
||||
const ReactDOM = window.ReactDOM;
|
||||
export default ReactDOM;
|
||||
export const {
|
||||
createPortal,
|
||||
flushSync,
|
||||
hydrate,
|
||||
render,
|
||||
unmountComponentAtNode,
|
||||
unstable_batchedUpdates,
|
||||
unstable_renderSubtreeIntoContainer,
|
||||
version,
|
||||
createRoot,
|
||||
hydrateRoot
|
||||
} = ReactDOM;
|
||||
4
packages/editor-app/public/assets/react-jsx-runtime-shim.js
vendored
Normal file
4
packages/editor-app/public/assets/react-jsx-runtime-shim.js
vendored
Normal file
@@ -0,0 +1,4 @@
|
||||
// React JSX Runtime shim - 从全局变量导出
|
||||
const ReactJSXRuntime = window.ReactJSXRuntime;
|
||||
export const { jsx, jsxs, Fragment } = ReactJSXRuntime;
|
||||
export default ReactJSXRuntime;
|
||||
40
packages/editor-app/public/assets/react-shim.js
vendored
Normal file
40
packages/editor-app/public/assets/react-shim.js
vendored
Normal file
@@ -0,0 +1,40 @@
|
||||
// React shim - 从全局变量导出 React
|
||||
// 这个文件用于 Import Map,让插件的 import 'react' 能正确解析到主应用的 React
|
||||
const React = window.React;
|
||||
export default React;
|
||||
export const {
|
||||
Children,
|
||||
Component,
|
||||
Fragment,
|
||||
Profiler,
|
||||
PureComponent,
|
||||
StrictMode,
|
||||
Suspense,
|
||||
cloneElement,
|
||||
createContext,
|
||||
createElement,
|
||||
createFactory,
|
||||
createRef,
|
||||
forwardRef,
|
||||
isValidElement,
|
||||
lazy,
|
||||
memo,
|
||||
startTransition,
|
||||
unstable_act,
|
||||
useCallback,
|
||||
useContext,
|
||||
useDebugValue,
|
||||
useDeferredValue,
|
||||
useEffect,
|
||||
useId,
|
||||
useImperativeHandle,
|
||||
useInsertionEffect,
|
||||
useLayoutEffect,
|
||||
useMemo,
|
||||
useReducer,
|
||||
useRef,
|
||||
useState,
|
||||
useSyncExternalStore,
|
||||
useTransition,
|
||||
version
|
||||
} = React;
|
||||
@@ -36,10 +36,10 @@ pub async fn build_plugin(plugin_folder: String, app: AppHandle) -> Result<Strin
|
||||
.map_err(|e| format!("Failed to create .build-cache directory: {}", e))?;
|
||||
}
|
||||
|
||||
let npm_command = if cfg!(target_os = "windows") {
|
||||
"npm.cmd"
|
||||
let pnpm_command = if cfg!(target_os = "windows") {
|
||||
"pnpm.cmd"
|
||||
} else {
|
||||
"npm"
|
||||
"pnpm"
|
||||
};
|
||||
|
||||
// Step 1: Install dependencies
|
||||
@@ -52,15 +52,15 @@ pub async fn build_plugin(plugin_folder: String, app: AppHandle) -> Result<Strin
|
||||
)
|
||||
.ok();
|
||||
|
||||
let install_output = Command::new(npm_command)
|
||||
let install_output = Command::new(&pnpm_command)
|
||||
.args(["install"])
|
||||
.current_dir(&plugin_folder)
|
||||
.output()
|
||||
.map_err(|e| format!("Failed to run npm install: {}", e))?;
|
||||
.map_err(|e| format!("Failed to run pnpm install: {}", e))?;
|
||||
|
||||
if !install_output.status.success() {
|
||||
return Err(format!(
|
||||
"npm install failed: {}",
|
||||
"pnpm install failed: {}",
|
||||
String::from_utf8_lossy(&install_output.stderr)
|
||||
));
|
||||
}
|
||||
@@ -75,15 +75,15 @@ pub async fn build_plugin(plugin_folder: String, app: AppHandle) -> Result<Strin
|
||||
)
|
||||
.ok();
|
||||
|
||||
let build_output = Command::new(npm_command)
|
||||
let build_output = Command::new(&pnpm_command)
|
||||
.args(["run", "build"])
|
||||
.current_dir(&plugin_folder)
|
||||
.output()
|
||||
.map_err(|e| format!("Failed to run npm run build: {}", e))?;
|
||||
.map_err(|e| format!("Failed to run pnpm run build: {}", e))?;
|
||||
|
||||
if !build_output.status.success() {
|
||||
return Err(format!(
|
||||
"npm run build failed: {}",
|
||||
"pnpm run build failed: {}",
|
||||
String::from_utf8_lossy(&build_output.stderr)
|
||||
));
|
||||
}
|
||||
|
||||
@@ -101,6 +101,10 @@ fn handle_project_protocol(
|
||||
let uri = request.uri();
|
||||
let path = uri.path();
|
||||
|
||||
// Debug logging
|
||||
println!("[project://] Full URI: {}", uri);
|
||||
println!("[project://] Path: {}", path);
|
||||
|
||||
let file_path = {
|
||||
let paths = match project_paths.lock() {
|
||||
Ok(p) => p,
|
||||
|
||||
@@ -3,8 +3,7 @@
|
||||
"version": "1.0.8",
|
||||
"identifier": "com.esengine.editor",
|
||||
"build": {
|
||||
"beforeDevCommand": "npm run dev",
|
||||
"devUrl": "http://localhost:5173",
|
||||
"beforeDevCommand": "npm run build:watch",
|
||||
"beforeBuildCommand": "npm run build",
|
||||
"frontendDist": "../dist"
|
||||
},
|
||||
@@ -67,7 +66,7 @@
|
||||
}
|
||||
],
|
||||
"security": {
|
||||
"csp": null,
|
||||
"csp": "default-src 'self' 'unsafe-inline' 'unsafe-eval' tauri: project: asset: https: http: data: blob:; script-src 'self' 'unsafe-inline' 'unsafe-eval' tauri: project: asset: https: http: blob:; style-src 'self' 'unsafe-inline' tauri: https: http:; img-src 'self' tauri: project: asset: https: http: data: blob:; connect-src 'self' tauri: project: asset: https: http: ws: wss:",
|
||||
"assetProtocol": {
|
||||
"enable": true,
|
||||
"scope": {
|
||||
|
||||
@@ -1,6 +1,14 @@
|
||||
import { useState, useEffect, useRef, useCallback } from 'react';
|
||||
import React, { useState, useEffect, useRef, useCallback } from 'react';
|
||||
import * as ReactDOM from 'react-dom';
|
||||
import * as ReactJSXRuntime from 'react/jsx-runtime';
|
||||
import { Core, createLogger, Scene } from '@esengine/ecs-framework';
|
||||
import * as ECSFramework from '@esengine/ecs-framework';
|
||||
|
||||
// 将 React 暴露到全局,供动态加载的插件使用
|
||||
// editor-runtime.js 将 React 设为 external,需要从全局获取
|
||||
(window as any).React = React;
|
||||
(window as any).ReactDOM = ReactDOM;
|
||||
(window as any).ReactJSXRuntime = ReactJSXRuntime;
|
||||
import {
|
||||
EditorPluginManager,
|
||||
UIRegistry,
|
||||
@@ -13,6 +21,7 @@ import {
|
||||
SceneManagerService,
|
||||
ProjectService,
|
||||
CompilerRegistry,
|
||||
ICompilerRegistry,
|
||||
InspectorRegistry,
|
||||
INotification,
|
||||
CommandManager
|
||||
@@ -64,6 +73,11 @@ Core.services.registerInstance(LocaleService, localeService);
|
||||
Core.services.registerSingleton(GlobalBlackboardService);
|
||||
Core.services.registerSingleton(CompilerRegistry);
|
||||
|
||||
// 在 CompilerRegistry 实例化后,也用 Symbol 注册,用于跨包插件访问
|
||||
// 注意:registerSingleton 会延迟实例化,所以需要在第一次使用后再注册 Symbol
|
||||
const compilerRegistryInstance = Core.services.resolve(CompilerRegistry);
|
||||
Core.services.registerInstance(ICompilerRegistry, compilerRegistryInstance);
|
||||
|
||||
const logger = createLogger('App');
|
||||
|
||||
function App() {
|
||||
@@ -368,33 +382,16 @@ function App() {
|
||||
|
||||
await projectService.openProject(projectPath);
|
||||
|
||||
await fetch('/@user-project-set-path', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ path: projectPath })
|
||||
});
|
||||
// 设置 Tauri project:// 协议的基础路径(用于加载插件等项目文件)
|
||||
await TauriAPI.setProjectBasePath(projectPath);
|
||||
|
||||
setStatus(t('header.status.projectOpened'));
|
||||
|
||||
setLoadingMessage(locale === 'zh' ? '步骤 2/2: 加载场景...' : 'Step 2/2: Loading scene...');
|
||||
setLoadingMessage(locale === 'zh' ? '步骤 2/2: 初始化场景...' : 'Step 2/2: Initializing scene...');
|
||||
|
||||
const sceneManagerService = Core.services.resolve(SceneManagerService);
|
||||
const scenesPath = projectService.getScenesPath();
|
||||
if (scenesPath && sceneManagerService) {
|
||||
try {
|
||||
const sceneFiles = await TauriAPI.scanDirectory(scenesPath, '*.ecs');
|
||||
|
||||
if (sceneFiles.length > 0) {
|
||||
const defaultScenePath = projectService.getDefaultScenePath();
|
||||
const sceneToLoad = sceneFiles.find((f) => f === defaultScenePath) || sceneFiles[0];
|
||||
|
||||
await sceneManagerService.openScene(sceneToLoad);
|
||||
} else {
|
||||
await sceneManagerService.newScene();
|
||||
}
|
||||
} catch {
|
||||
await sceneManagerService.newScene();
|
||||
}
|
||||
if (sceneManagerService) {
|
||||
await sceneManagerService.newScene();
|
||||
}
|
||||
|
||||
const settings = SettingsService.getInstance();
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { invoke } from '@tauri-apps/api/core';
|
||||
import { invoke, convertFileSrc } from '@tauri-apps/api/core';
|
||||
|
||||
/**
|
||||
* 文件过滤器定义
|
||||
@@ -298,6 +298,19 @@ export class TauriAPI {
|
||||
static async generateQRCode(text: string): Promise<string> {
|
||||
return await invoke<string>('generate_qrcode', { text });
|
||||
}
|
||||
|
||||
/**
|
||||
* 将本地文件路径转换为 Tauri 可访问的 asset URL
|
||||
* @param filePath 本地文件路径
|
||||
* @param protocol 协议类型 (默认: 'asset')
|
||||
* @returns 转换后的 URL,可用于 img src、audio src 等
|
||||
* @example
|
||||
* const url = TauriAPI.convertFileSrc('C:\\Users\\...\\image.png');
|
||||
* // 返回: 'https://asset.localhost/C:/Users/.../image.png'
|
||||
*/
|
||||
static convertFileSrc(filePath: string, protocol?: string): string {
|
||||
return convertFileSrc(filePath, protocol);
|
||||
}
|
||||
}
|
||||
|
||||
export interface DirectoryEntry {
|
||||
|
||||
@@ -2,13 +2,17 @@ import type { EditorPluginManager } from '@esengine/editor-core';
|
||||
import { SceneInspectorPlugin } from '../../plugins/SceneInspectorPlugin';
|
||||
import { ProfilerPlugin } from '../../plugins/ProfilerPlugin';
|
||||
import { EditorAppearancePlugin } from '../../plugins/EditorAppearancePlugin';
|
||||
import { GizmoPlugin } from '../../plugins/GizmoPlugin';
|
||||
import { TilemapEditorPlugin } from '@esengine/tilemap-editor';
|
||||
|
||||
export class PluginInstaller {
|
||||
async installBuiltinPlugins(pluginManager: EditorPluginManager): Promise<void> {
|
||||
const plugins = [
|
||||
new GizmoPlugin(),
|
||||
new SceneInspectorPlugin(),
|
||||
new ProfilerPlugin(),
|
||||
new EditorAppearancePlugin()
|
||||
new EditorAppearancePlugin(),
|
||||
new TilemapEditorPlugin()
|
||||
];
|
||||
|
||||
for (const plugin of plugins) {
|
||||
@@ -19,4 +23,4 @@ export class PluginInstaller {
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@ import { Core, ComponentRegistry as CoreComponentRegistry } from '@esengine/ecs-
|
||||
import {
|
||||
UIRegistry,
|
||||
MessageHub,
|
||||
IMessageHub,
|
||||
SerializerRegistry,
|
||||
EntityStoreService,
|
||||
ComponentRegistry,
|
||||
@@ -12,10 +13,17 @@ import {
|
||||
SettingsRegistry,
|
||||
SceneManagerService,
|
||||
FileActionRegistry,
|
||||
EntityCreationRegistry,
|
||||
EditorPluginManager,
|
||||
InspectorRegistry,
|
||||
IInspectorRegistry,
|
||||
PropertyRendererRegistry,
|
||||
FieldEditorRegistry
|
||||
FieldEditorRegistry,
|
||||
ComponentActionRegistry,
|
||||
IDialogService,
|
||||
IFileSystemService,
|
||||
CompilerRegistry,
|
||||
ICompilerRegistry
|
||||
} from '@esengine/editor-core';
|
||||
import {
|
||||
TransformComponent,
|
||||
@@ -128,9 +136,12 @@ export class ServiceRegistry {
|
||||
const settingsRegistry = new SettingsRegistry();
|
||||
const sceneManager = new SceneManagerService(messageHub, fileAPI, projectService, entityStore);
|
||||
const fileActionRegistry = new FileActionRegistry();
|
||||
const entityCreationRegistry = new EntityCreationRegistry();
|
||||
const componentActionRegistry = new ComponentActionRegistry();
|
||||
|
||||
Core.services.registerInstance(UIRegistry, uiRegistry);
|
||||
Core.services.registerInstance(MessageHub, messageHub);
|
||||
Core.services.registerInstance(IMessageHub, messageHub); // Symbol 注册用于跨包插件访问
|
||||
Core.services.registerInstance(SerializerRegistry, serializerRegistry);
|
||||
Core.services.registerInstance(EntityStoreService, entityStore);
|
||||
Core.services.registerInstance(ComponentRegistry, componentRegistry);
|
||||
@@ -141,6 +152,8 @@ export class ServiceRegistry {
|
||||
Core.services.registerInstance(SettingsRegistry, settingsRegistry);
|
||||
Core.services.registerInstance(SceneManagerService, sceneManager);
|
||||
Core.services.registerInstance(FileActionRegistry, fileActionRegistry);
|
||||
Core.services.registerInstance(EntityCreationRegistry, entityCreationRegistry);
|
||||
Core.services.registerInstance(ComponentActionRegistry, componentActionRegistry);
|
||||
|
||||
const pluginManager = new EditorPluginManager();
|
||||
pluginManager.initialize(coreInstance, Core.services);
|
||||
@@ -155,10 +168,12 @@ export class ServiceRegistry {
|
||||
const dialog = new TauriDialogService();
|
||||
const notification = new NotificationService();
|
||||
Core.services.registerInstance(NotificationService, notification);
|
||||
Core.services.registerInstance(IDialogService, dialog);
|
||||
Core.services.registerInstance(IFileSystemService, fileSystem);
|
||||
|
||||
const inspectorRegistry = new InspectorRegistry();
|
||||
|
||||
Core.services.registerInstance(InspectorRegistry, inspectorRegistry);
|
||||
Core.services.registerInstance(IInspectorRegistry, inspectorRegistry); // Symbol 注册用于跨包插件访问
|
||||
|
||||
const propertyRendererRegistry = new PropertyRendererRegistry();
|
||||
Core.services.registerInstance(PropertyRendererRegistry, propertyRendererRegistry);
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
import { Core, Entity } from '@esengine/ecs-framework';
|
||||
import { EntityStoreService, MessageHub } from '@esengine/editor-core';
|
||||
import { TransformComponent } from '@esengine/ecs-components';
|
||||
import { TilemapComponent } from '@esengine/tilemap';
|
||||
import { BaseCommand } from '../BaseCommand';
|
||||
|
||||
/**
|
||||
* Tilemap创建选项
|
||||
*/
|
||||
export interface TilemapCreationOptions {
|
||||
/** 地图宽度(瓦片数),默认10 */
|
||||
width?: number;
|
||||
/** 地图高度(瓦片数),默认10 */
|
||||
height?: number;
|
||||
/** 瓦片宽度(像素),默认32 */
|
||||
tileWidth?: number;
|
||||
/** 瓦片高度(像素),默认32 */
|
||||
tileHeight?: number;
|
||||
/** 渲染层级,默认0 */
|
||||
sortingOrder?: number;
|
||||
/** 初始Tileset源路径 */
|
||||
tilesetSource?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建带Tilemap组件的实体命令
|
||||
*/
|
||||
export class CreateTilemapEntityCommand extends BaseCommand {
|
||||
private entity: Entity | null = null;
|
||||
private entityId: number | null = null;
|
||||
|
||||
constructor(
|
||||
private entityStore: EntityStoreService,
|
||||
private messageHub: MessageHub,
|
||||
private entityName: string,
|
||||
private parentEntity?: Entity,
|
||||
private options: TilemapCreationOptions = {}
|
||||
) {
|
||||
super();
|
||||
}
|
||||
|
||||
execute(): void {
|
||||
const scene = Core.scene;
|
||||
if (!scene) {
|
||||
throw new Error('场景未初始化');
|
||||
}
|
||||
|
||||
this.entity = scene.createEntity(this.entityName);
|
||||
this.entityId = this.entity.id;
|
||||
|
||||
// 添加Transform组件
|
||||
this.entity.addComponent(new TransformComponent());
|
||||
|
||||
// 创建并配置Tilemap组件
|
||||
const tilemapComponent = new TilemapComponent();
|
||||
|
||||
// 应用配置选项
|
||||
const {
|
||||
width = 10,
|
||||
height = 10,
|
||||
tileWidth = 32,
|
||||
tileHeight = 32,
|
||||
sortingOrder = 0,
|
||||
tilesetSource
|
||||
} = this.options;
|
||||
|
||||
tilemapComponent.tileWidth = tileWidth;
|
||||
tilemapComponent.tileHeight = tileHeight;
|
||||
tilemapComponent.sortingOrder = sortingOrder;
|
||||
|
||||
// 初始化空白地图
|
||||
tilemapComponent.initializeEmpty(width, height);
|
||||
|
||||
// 添加初始 Tileset
|
||||
if (tilesetSource) {
|
||||
tilemapComponent.addTileset(tilesetSource);
|
||||
}
|
||||
|
||||
this.entity.addComponent(tilemapComponent);
|
||||
|
||||
if (this.parentEntity) {
|
||||
this.parentEntity.addChild(this.entity);
|
||||
}
|
||||
|
||||
this.entityStore.addEntity(this.entity, this.parentEntity);
|
||||
this.entityStore.selectEntity(this.entity);
|
||||
|
||||
this.messageHub.publish('entity:added', { entity: this.entity });
|
||||
this.messageHub.publish('tilemap:created', {
|
||||
entity: this.entity,
|
||||
component: tilemapComponent
|
||||
});
|
||||
}
|
||||
|
||||
undo(): void {
|
||||
if (!this.entity) return;
|
||||
|
||||
this.entityStore.removeEntity(this.entity);
|
||||
this.entity.destroy();
|
||||
|
||||
this.messageHub.publish('entity:removed', { entityId: this.entityId });
|
||||
|
||||
this.entity = null;
|
||||
}
|
||||
|
||||
getDescription(): string {
|
||||
return `创建Tilemap实体: ${this.entityName}`;
|
||||
}
|
||||
|
||||
getCreatedEntity(): Entity | null {
|
||||
return this.entity;
|
||||
}
|
||||
}
|
||||
@@ -2,5 +2,6 @@ export { CreateEntityCommand } from './CreateEntityCommand';
|
||||
export { CreateSpriteEntityCommand } from './CreateSpriteEntityCommand';
|
||||
export { CreateAnimatedSpriteEntityCommand } from './CreateAnimatedSpriteEntityCommand';
|
||||
export { CreateCameraEntityCommand } from './CreateCameraEntityCommand';
|
||||
export { CreateTilemapEntityCommand } from './CreateTilemapEntityCommand';
|
||||
export { DeleteEntityCommand } from './DeleteEntityCommand';
|
||||
|
||||
|
||||
@@ -95,27 +95,40 @@ export function AssetBrowser({ projectPath, locale, onOpenScene }: AssetBrowserP
|
||||
|
||||
const unsubscribe = messageHub.subscribe('asset:reveal', async (data: any) => {
|
||||
const filePath = data.path;
|
||||
if (filePath) {
|
||||
const lastSlashIndex = Math.max(filePath.lastIndexOf('/'), filePath.lastIndexOf('\\'));
|
||||
const dirPath = lastSlashIndex > 0 ? filePath.substring(0, lastSlashIndex) : null;
|
||||
if (dirPath) {
|
||||
if (!filePath || !projectPath) return;
|
||||
|
||||
// Convert relative path to absolute path if needed
|
||||
let absoluteFilePath = filePath;
|
||||
if (!filePath.includes(':') && !filePath.startsWith('/')) {
|
||||
absoluteFilePath = `${projectPath}/${filePath}`.replace(/\\/g, '/');
|
||||
}
|
||||
|
||||
const lastSlashIndex = Math.max(absoluteFilePath.lastIndexOf('/'), absoluteFilePath.lastIndexOf('\\'));
|
||||
const dirPath = lastSlashIndex > 0 ? absoluteFilePath.substring(0, lastSlashIndex) : null;
|
||||
|
||||
if (dirPath) {
|
||||
try {
|
||||
const dirExists = await TauriAPI.pathExists(dirPath);
|
||||
if (!dirExists) return;
|
||||
|
||||
setCurrentPath(dirPath);
|
||||
// Load assets first, then set selection after list is populated
|
||||
await loadAssets(dirPath);
|
||||
setSelectedPaths(new Set([filePath]));
|
||||
setSelectedPaths(new Set([absoluteFilePath]));
|
||||
|
||||
// Expand tree to reveal the file
|
||||
if (showDetailView) {
|
||||
detailViewFileTreeRef.current?.revealPath(filePath);
|
||||
detailViewFileTreeRef.current?.revealPath(absoluteFilePath);
|
||||
} else {
|
||||
treeOnlyViewFileTreeRef.current?.revealPath(filePath);
|
||||
treeOnlyViewFileTreeRef.current?.revealPath(absoluteFilePath);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(`[AssetBrowser] Failed to reveal asset: ${absoluteFilePath}`, error);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return () => unsubscribe();
|
||||
}, [showDetailView]);
|
||||
}, [showDetailView, projectPath]);
|
||||
|
||||
const loadAssets = async (path: string) => {
|
||||
setLoading(true);
|
||||
|
||||
@@ -3,7 +3,7 @@ import { Core, IService, ServiceType } from '@esengine/ecs-framework';
|
||||
import { CompilerRegistry, ICompiler, CompilerContext, CompileResult, IFileSystem, IDialog, FileEntry } from '@esengine/editor-core';
|
||||
import { X, Play, Loader2 } from 'lucide-react';
|
||||
import { open as tauriOpen, save as tauriSave, message as tauriMessage, confirm as tauriConfirm } from '@tauri-apps/plugin-dialog';
|
||||
import { invoke } from '@tauri-apps/api/core';
|
||||
import { invoke, convertFileSrc } from '@tauri-apps/api/core';
|
||||
import '../styles/CompilerConfigDialog.css';
|
||||
|
||||
interface DirectoryEntry {
|
||||
@@ -98,7 +98,11 @@ export const CompilerConfigDialog: React.FC<CompilerConfigDialogProps> = ({
|
||||
return entries
|
||||
.filter((e) => !e.is_dir && e.name.endsWith(ext))
|
||||
.map((e) => e.name.replace(ext, ''));
|
||||
}
|
||||
},
|
||||
convertToAssetUrl: (filePath: string) => {
|
||||
return convertFileSrc(filePath);
|
||||
},
|
||||
dispose: () => {}
|
||||
});
|
||||
|
||||
const createDialog = (): IDialog => ({
|
||||
@@ -124,7 +128,8 @@ export const CompilerConfigDialog: React.FC<CompilerConfigDialogProps> = ({
|
||||
},
|
||||
showConfirm: async (title: string, message: string) => {
|
||||
return await tauriConfirm(message, { title });
|
||||
}
|
||||
},
|
||||
dispose: () => {}
|
||||
});
|
||||
|
||||
const createContext = (): CompilerContext => ({
|
||||
|
||||
@@ -91,7 +91,11 @@ export function EntityInspector({ entityStore: _entityStore, messageHub }: Entit
|
||||
};
|
||||
|
||||
const handlePropertyChange = (component: any, propertyName: string, value: any) => {
|
||||
if (!selectedEntity) return;
|
||||
console.log('[EntityInspector] handlePropertyChange called:', propertyName, value);
|
||||
if (!selectedEntity) {
|
||||
console.log('[EntityInspector] No selectedEntity, returning');
|
||||
return;
|
||||
}
|
||||
|
||||
// Actually update the component property
|
||||
// 实际更新组件属性
|
||||
@@ -103,6 +107,10 @@ export function EntityInspector({ entityStore: _entityStore, messageHub }: Entit
|
||||
propertyName,
|
||||
value
|
||||
});
|
||||
|
||||
// Also publish scene:modified so other panels can react
|
||||
console.log('[EntityInspector] Publishing scene:modified');
|
||||
messageHub.publish('scene:modified', {});
|
||||
};
|
||||
|
||||
const renderRemoteProperty = (key: string, value: any) => {
|
||||
|
||||
@@ -92,10 +92,16 @@ export const FileTree = forwardRef<FileTreeHandle, FileTreeProps>(({ rootPath, o
|
||||
|
||||
// Expand tree to reveal a specific file path
|
||||
const revealPath = async (targetPath: string) => {
|
||||
if (!rootPath || !targetPath.startsWith(rootPath)) return;
|
||||
if (!rootPath) return;
|
||||
|
||||
// Normalize paths to use forward slashes for comparison
|
||||
const normalizedTargetPath = targetPath.replace(/\\/g, '/');
|
||||
const normalizedRootPath = rootPath.replace(/\\/g, '/');
|
||||
|
||||
if (!normalizedTargetPath.startsWith(normalizedRootPath)) return;
|
||||
|
||||
// Get path segments between root and target
|
||||
const relativePath = targetPath.substring(rootPath.length).replace(/^[/\\]/, '');
|
||||
const relativePath = normalizedTargetPath.substring(normalizedRootPath.length).replace(/^[/\\]/, '');
|
||||
const segments = relativePath.split(/[/\\]/);
|
||||
|
||||
// Build list of folder paths to expand
|
||||
@@ -748,9 +754,20 @@ export const FileTree = forwardRef<FileTreeHandle, FileTreeProps>(({ rootPath, o
|
||||
};
|
||||
|
||||
const renderNode = (node: TreeNode, level: number = 0) => {
|
||||
const isSelected = selectedPaths
|
||||
? selectedPaths.has(node.path)
|
||||
: (internalSelectedPath || selectedPath) === node.path;
|
||||
// Normalize paths for comparison (handle forward/backward slashes)
|
||||
const normalizedNodePath = node.path.replace(/\\/g, '/');
|
||||
const normalizedInternalPath = internalSelectedPath?.replace(/\\/g, '/');
|
||||
const normalizedSelectedPath = selectedPath?.replace(/\\/g, '/');
|
||||
|
||||
// Check if this node is selected, normalizing paths for comparison
|
||||
let isSelected = false;
|
||||
if (selectedPaths) {
|
||||
// Check both original path and normalized path in selectedPaths set
|
||||
isSelected = selectedPaths.has(node.path) || selectedPaths.has(normalizedNodePath);
|
||||
} else {
|
||||
isSelected = (normalizedInternalPath || normalizedSelectedPath) === normalizedNodePath;
|
||||
}
|
||||
|
||||
const isRenaming = renamingNode === node.path;
|
||||
const indent = level * 16;
|
||||
|
||||
|
||||
@@ -215,6 +215,8 @@ export function Inspector({ entityStore: _entityStore, messageHub, inspectorRegi
|
||||
propertyName,
|
||||
value
|
||||
});
|
||||
// Also publish scene:modified so other panels can react to changes
|
||||
messageHub.publish('scene:modified', {});
|
||||
};
|
||||
|
||||
const renderRemoteProperty = (key: string, value: any) => {
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
import { useState, useEffect, useRef } from 'react';
|
||||
import { Component, Core } from '@esengine/ecs-framework';
|
||||
import { PropertyMetadataService, PropertyMetadata, PropertyAction, MessageHub } from '@esengine/editor-core';
|
||||
import { PropertyMetadataService, PropertyMetadata, PropertyAction, MessageHub, IFileSystemService } from '@esengine/editor-core';
|
||||
import type { IFileSystem } from '@esengine/editor-core';
|
||||
import { ChevronRight, ChevronDown, ArrowRight, Lock } from 'lucide-react';
|
||||
import * as LucideIcons from 'lucide-react';
|
||||
import { AnimationClipsFieldEditor } from '../infrastructure/field-editors/AnimationClipsFieldEditor';
|
||||
import { AssetSaveDialog } from './dialogs/AssetSaveDialog';
|
||||
import '../styles/PropertyInspector.css';
|
||||
|
||||
const animationClipsEditor = new AnimationClipsFieldEditor();
|
||||
@@ -80,6 +82,12 @@ export function PropertyInspector({ component, entity, version, onChange, onActi
|
||||
if (onChange) {
|
||||
onChange(propertyName, value);
|
||||
}
|
||||
|
||||
// Always publish scene:modified so other panels can react to changes
|
||||
const messageHub = Core.services.resolve(MessageHub);
|
||||
if (messageHub) {
|
||||
messageHub.publish('scene:modified', {});
|
||||
}
|
||||
};
|
||||
|
||||
// Read value directly from component to avoid state sync issues
|
||||
@@ -187,6 +195,7 @@ export function PropertyInspector({ component, entity, version, onChange, onActi
|
||||
fileExtension={metadata.fileExtension}
|
||||
readOnly={metadata.readOnly || !!controlledBy}
|
||||
controlledBy={controlledBy}
|
||||
entityId={entity?.id?.toString()}
|
||||
onChange={(newValue) => handleChange(propertyName, newValue)}
|
||||
/>
|
||||
);
|
||||
@@ -469,6 +478,7 @@ function ColorField({ label, value, readOnly, onChange }: ColorFieldProps) {
|
||||
const v = Math.max(0, Math.min(100, 100 - ((e.clientY - rect.top) / rect.height) * 100));
|
||||
const newColor = hsvToHex(hsv.h, s, v);
|
||||
setTempColor(newColor);
|
||||
onChange(newColor); // Real-time update
|
||||
};
|
||||
|
||||
const handleHueChange = (e: React.MouseEvent<HTMLDivElement>) => {
|
||||
@@ -476,6 +486,7 @@ function ColorField({ label, value, readOnly, onChange }: ColorFieldProps) {
|
||||
const h = Math.max(0, Math.min(360, ((e.clientX - rect.left) / rect.width) * 360));
|
||||
const newColor = hsvToHex(h, hsv.s, hsv.v);
|
||||
setTempColor(newColor);
|
||||
onChange(newColor); // Real-time update
|
||||
};
|
||||
|
||||
return (
|
||||
@@ -857,11 +868,90 @@ interface AssetDropFieldProps {
|
||||
fileExtension?: string;
|
||||
readOnly?: boolean;
|
||||
controlledBy?: string;
|
||||
entityId?: string;
|
||||
onChange: (value: string) => void;
|
||||
}
|
||||
|
||||
function AssetDropField({ label, value, fileExtension, readOnly, controlledBy, onChange }: AssetDropFieldProps) {
|
||||
function AssetDropField({ label, value, fileExtension, readOnly, controlledBy, entityId, onChange }: AssetDropFieldProps) {
|
||||
const [isDragging, setIsDragging] = useState(false);
|
||||
const [showSaveDialog, setShowSaveDialog] = useState(false);
|
||||
|
||||
const canCreate = fileExtension && ['.tilemap.json', '.btree'].includes(fileExtension);
|
||||
|
||||
const handleCreate = () => {
|
||||
setShowSaveDialog(true);
|
||||
};
|
||||
|
||||
const handleSaveAsset = async (relativePath: string) => {
|
||||
const fileSystem = Core.services.tryResolve<IFileSystem>(IFileSystemService);
|
||||
const messageHub = Core.services.tryResolve(MessageHub);
|
||||
|
||||
if (!fileSystem) {
|
||||
console.error('[AssetDropField] FileSystem service not available');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
// Get absolute path from project
|
||||
const projectService = Core.services.tryResolve(
|
||||
(await import('@esengine/editor-core')).ProjectService
|
||||
);
|
||||
const currentProject = projectService?.getCurrentProject();
|
||||
if (!currentProject) {
|
||||
console.error('[AssetDropField] No project loaded');
|
||||
return;
|
||||
}
|
||||
|
||||
const absolutePath = `${currentProject.path}/${relativePath}`.replace(/\\/g, '/');
|
||||
|
||||
// Create default content based on file type
|
||||
let defaultContent = '';
|
||||
if (fileExtension === '.tilemap.json') {
|
||||
defaultContent = JSON.stringify({
|
||||
name: 'New Tilemap',
|
||||
version: 2,
|
||||
width: 20,
|
||||
height: 15,
|
||||
tileWidth: 16,
|
||||
tileHeight: 16,
|
||||
layers: [
|
||||
{
|
||||
id: 'default',
|
||||
name: 'Layer 0',
|
||||
visible: true,
|
||||
opacity: 1,
|
||||
data: new Array(20 * 15).fill(0)
|
||||
}
|
||||
],
|
||||
tilesets: []
|
||||
}, null, 2);
|
||||
} else if (fileExtension === '.btree') {
|
||||
defaultContent = JSON.stringify({
|
||||
name: 'New Behavior Tree',
|
||||
version: 1,
|
||||
nodes: [],
|
||||
connections: []
|
||||
}, null, 2);
|
||||
}
|
||||
|
||||
// Write file
|
||||
await fileSystem.writeFile(absolutePath, defaultContent);
|
||||
|
||||
// Update component with relative path
|
||||
onChange(relativePath);
|
||||
|
||||
// Open editor panel if tilemap
|
||||
if (messageHub && fileExtension === '.tilemap.json' && entityId) {
|
||||
const { useTilemapEditorStore } = await import('@esengine/tilemap-editor');
|
||||
useTilemapEditorStore.getState().setEntityId(entityId);
|
||||
messageHub.publish('dynamic-panel:open', { panelId: 'tilemap-editor', title: 'Tilemap Editor' });
|
||||
}
|
||||
|
||||
console.log('[AssetDropField] Created asset:', relativePath);
|
||||
} catch (error) {
|
||||
console.error('[AssetDropField] Failed to create asset:', error);
|
||||
}
|
||||
};
|
||||
|
||||
const handleDragEnter = (e: React.DragEvent) => {
|
||||
e.preventDefault();
|
||||
@@ -890,8 +980,14 @@ function AssetDropField({ label, value, fileExtension, readOnly, controlledBy, o
|
||||
if (assetPath) {
|
||||
if (fileExtension) {
|
||||
const extensions = fileExtension.split(',').map((ext) => ext.trim().toLowerCase());
|
||||
const fileExt = assetPath.toLowerCase().split('.').pop();
|
||||
if (fileExt && extensions.some((ext) => ext === `.${fileExt}` || ext === fileExt)) {
|
||||
const lowerPath = assetPath.toLowerCase();
|
||||
// Check if the path ends with any of the specified extensions
|
||||
// This handles both simple extensions (.json) and compound extensions (.tilemap.json)
|
||||
const isValidExtension = extensions.some((ext) => {
|
||||
const normalizedExt = ext.startsWith('.') ? ext : `.${ext}`;
|
||||
return lowerPath.endsWith(normalizedExt);
|
||||
});
|
||||
if (isValidExtension) {
|
||||
onChange(assetPath);
|
||||
}
|
||||
} else {
|
||||
@@ -943,6 +1039,18 @@ function AssetDropField({ label, value, fileExtension, readOnly, controlledBy, o
|
||||
{value ? getFileName(value) : 'None'}
|
||||
</span>
|
||||
<div className="property-asset-actions">
|
||||
{canCreate && !readOnly && !value && (
|
||||
<button
|
||||
className="property-asset-btn property-asset-btn-create"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
handleCreate();
|
||||
}}
|
||||
title="创建新资产"
|
||||
>
|
||||
+
|
||||
</button>
|
||||
)}
|
||||
{value && (
|
||||
<button
|
||||
className="property-asset-btn"
|
||||
@@ -957,6 +1065,16 @@ function AssetDropField({ label, value, fileExtension, readOnly, controlledBy, o
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Save Dialog */}
|
||||
<AssetSaveDialog
|
||||
isOpen={showSaveDialog}
|
||||
onClose={() => setShowSaveDialog(false)}
|
||||
onSave={handleSaveAsset}
|
||||
title={fileExtension === '.tilemap.json' ? '创建 Tilemap 资产' : '创建资产'}
|
||||
defaultFileName={fileExtension === '.tilemap.json' ? 'new-tilemap' : 'new-asset'}
|
||||
fileExtension={fileExtension}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { Entity, Core } from '@esengine/ecs-framework';
|
||||
import { EntityStoreService, MessageHub, SceneManagerService, CommandManager } from '@esengine/editor-core';
|
||||
import { EntityStoreService, MessageHub, SceneManagerService, CommandManager, EntityCreationRegistry, EntityCreationTemplate } from '@esengine/editor-core';
|
||||
import { useLocale } from '../hooks/useLocale';
|
||||
import { Box, Layers, Wifi, Search, Plus, Trash2, Monitor, Globe, Image, Camera, Film } from 'lucide-react';
|
||||
import { ProfilerService, RemoteEntity } from '../services/ProfilerService';
|
||||
@@ -31,10 +31,32 @@ export function SceneHierarchy({ entityStore, messageHub, commandManager, isProf
|
||||
const [contextMenu, setContextMenu] = useState<{ x: number; y: number; entityId: number | null } | null>(null);
|
||||
const [draggedEntityId, setDraggedEntityId] = useState<number | null>(null);
|
||||
const [dropTargetIndex, setDropTargetIndex] = useState<number | null>(null);
|
||||
const [pluginTemplates, setPluginTemplates] = useState<EntityCreationTemplate[]>([]);
|
||||
const { t, locale } = useLocale();
|
||||
|
||||
const isShowingRemote = viewMode === 'remote' && isRemoteConnected;
|
||||
|
||||
// Get entity creation templates from plugins
|
||||
useEffect(() => {
|
||||
const updateTemplates = () => {
|
||||
const registry = Core.services.resolve(EntityCreationRegistry);
|
||||
if (registry) {
|
||||
setPluginTemplates(registry.getAll());
|
||||
}
|
||||
};
|
||||
|
||||
updateTemplates();
|
||||
|
||||
// Update when plugins are installed
|
||||
const unsubInstalled = messageHub.subscribe('plugin:installed', updateTemplates);
|
||||
const unsubUninstalled = messageHub.subscribe('plugin:uninstalled', updateTemplates);
|
||||
|
||||
return () => {
|
||||
unsubInstalled();
|
||||
unsubUninstalled();
|
||||
};
|
||||
}, [messageHub]);
|
||||
|
||||
// Subscribe to scene changes
|
||||
useEffect(() => {
|
||||
const sceneManager = Core.services.resolve(SceneManagerService);
|
||||
@@ -535,6 +557,23 @@ export function SceneHierarchy({ entityStore, messageHub, commandManager, isProf
|
||||
<Camera size={12} />
|
||||
<span>{locale === 'zh' ? '创建相机' : 'Create Camera'}</span>
|
||||
</button>
|
||||
{pluginTemplates.length > 0 && (
|
||||
<>
|
||||
<div className="context-menu-divider" />
|
||||
{pluginTemplates.map((template) => (
|
||||
<button
|
||||
key={template.id}
|
||||
onClick={async () => {
|
||||
await template.create(contextMenu.entityId ?? undefined);
|
||||
closeContextMenu();
|
||||
}}
|
||||
>
|
||||
{template.icon || <Plus size={12} />}
|
||||
<span>{template.label}</span>
|
||||
</button>
|
||||
))}
|
||||
</>
|
||||
)}
|
||||
{contextMenu.entityId && (
|
||||
<>
|
||||
<div className="context-menu-divider" />
|
||||
|
||||
@@ -43,7 +43,7 @@ function generateRuntimeHtml(): string {
|
||||
<canvas id="runtime-canvas"></canvas>
|
||||
<script src="/runtime.browser.js"></script>
|
||||
<script type="module">
|
||||
import * as esEngine from '/engine.js';
|
||||
import * as esEngine from '/es_engine.js';
|
||||
(async function() {
|
||||
try {
|
||||
// Set canvas size before creating runtime
|
||||
@@ -361,7 +361,8 @@ export function Viewport({ locale = 'en', messageHub }: ViewportProps) {
|
||||
};
|
||||
}, []);
|
||||
|
||||
// Sync camera state to engine
|
||||
// Sync camera state to engine and publish camera:updated event
|
||||
// 同步相机状态到引擎并发布 camera:updated 事件
|
||||
useEffect(() => {
|
||||
if (engine.state.initialized) {
|
||||
EngineService.getInstance().setCamera({
|
||||
@@ -370,6 +371,17 @@ export function Viewport({ locale = 'en', messageHub }: ViewportProps) {
|
||||
zoom: camera2DZoom,
|
||||
rotation: 0
|
||||
});
|
||||
|
||||
// Publish camera update event for other systems
|
||||
// 发布相机更新事件供其他系统使用
|
||||
const hub = messageHubRef.current;
|
||||
if (hub) {
|
||||
hub.publish('camera:updated', {
|
||||
x: camera2DOffset.x,
|
||||
y: camera2DOffset.y,
|
||||
zoom: camera2DZoom
|
||||
});
|
||||
}
|
||||
}
|
||||
}, [camera2DOffset, camera2DZoom, engine.state.initialized]);
|
||||
|
||||
@@ -473,11 +485,11 @@ export function Viewport({ locale = 'en', messageHub }: ViewportProps) {
|
||||
}
|
||||
};
|
||||
|
||||
const handleStop = () => {
|
||||
const handleStop = async () => {
|
||||
setPlayState('stopped');
|
||||
engine.stop();
|
||||
// Restore scene snapshot
|
||||
EngineService.getInstance().restoreSceneSnapshot();
|
||||
await EngineService.getInstance().restoreSceneSnapshot();
|
||||
// Restore editor camera state
|
||||
setCamera2DOffset({ x: editorCameraRef.current.x, y: editorCameraRef.current.y });
|
||||
setCamera2DZoom(editorCameraRef.current.zoom);
|
||||
|
||||
@@ -197,3 +197,119 @@
|
||||
color: #666;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
/* Asset Save Dialog specific styles */
|
||||
.asset-save-filename {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 12px 16px;
|
||||
border-top: 1px solid #333;
|
||||
background: #252525;
|
||||
}
|
||||
|
||||
.asset-save-filename label {
|
||||
font-size: 12px;
|
||||
color: #888;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.asset-save-filename input {
|
||||
flex: 1;
|
||||
background: #1a1a1a;
|
||||
border: 1px solid #333;
|
||||
border-radius: 4px;
|
||||
padding: 6px 8px;
|
||||
color: #e0e0e0;
|
||||
font-size: 12px;
|
||||
outline: none;
|
||||
}
|
||||
|
||||
.asset-save-filename input:focus {
|
||||
border-color: #1976d2;
|
||||
}
|
||||
|
||||
.asset-save-extension {
|
||||
font-size: 11px;
|
||||
color: #666;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
/* New folder styles */
|
||||
.asset-save-new-folder-btn {
|
||||
padding: 8px 16px;
|
||||
border-top: 1px solid #333;
|
||||
}
|
||||
|
||||
.asset-save-new-folder-btn button {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
padding: 6px 12px;
|
||||
background: #333;
|
||||
border: none;
|
||||
border-radius: 4px;
|
||||
color: #e0e0e0;
|
||||
font-size: 12px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.asset-save-new-folder-btn button:hover {
|
||||
background: #444;
|
||||
}
|
||||
|
||||
.asset-save-new-folder {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 8px 16px;
|
||||
border-top: 1px solid #333;
|
||||
background: #252525;
|
||||
}
|
||||
|
||||
.asset-save-new-folder input {
|
||||
flex: 1;
|
||||
background: #1a1a1a;
|
||||
border: 1px solid #333;
|
||||
border-radius: 4px;
|
||||
padding: 6px 8px;
|
||||
color: #e0e0e0;
|
||||
font-size: 12px;
|
||||
outline: none;
|
||||
}
|
||||
|
||||
.asset-save-new-folder input:focus {
|
||||
border-color: #1976d2;
|
||||
}
|
||||
|
||||
.asset-save-new-folder button {
|
||||
padding: 6px 12px;
|
||||
border-radius: 4px;
|
||||
font-size: 12px;
|
||||
cursor: pointer;
|
||||
border: none;
|
||||
}
|
||||
|
||||
.asset-save-new-folder button:first-of-type {
|
||||
background: #1976d2;
|
||||
color: white;
|
||||
}
|
||||
|
||||
.asset-save-new-folder button:first-of-type:hover {
|
||||
background: #1565c0;
|
||||
}
|
||||
|
||||
.asset-save-new-folder button:first-of-type:disabled {
|
||||
background: #333;
|
||||
color: #666;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
.asset-save-new-folder button:last-child {
|
||||
background: #333;
|
||||
color: #e0e0e0;
|
||||
}
|
||||
|
||||
.asset-save-new-folder button:last-child:hover {
|
||||
background: #444;
|
||||
}
|
||||
|
||||
@@ -149,19 +149,34 @@ export function AssetPickerDialog({
|
||||
}
|
||||
}, [toggleFolder]);
|
||||
|
||||
// Convert absolute path to relative path based on project root
|
||||
const toRelativePath = useCallback((absolutePath: string): string => {
|
||||
const projectService = Core.services.tryResolve(ProjectService);
|
||||
const currentProject = projectService?.getCurrentProject();
|
||||
if (currentProject) {
|
||||
const projectPath = currentProject.path.replace(/\\/g, '/');
|
||||
const normalizedAbsolute = absolutePath.replace(/\\/g, '/');
|
||||
if (normalizedAbsolute.startsWith(projectPath)) {
|
||||
// Return relative path from project root
|
||||
return normalizedAbsolute.substring(projectPath.length + 1);
|
||||
}
|
||||
}
|
||||
return absolutePath;
|
||||
}, []);
|
||||
|
||||
const handleConfirm = useCallback(() => {
|
||||
if (selectedPath) {
|
||||
onSelect(selectedPath);
|
||||
onSelect(toRelativePath(selectedPath));
|
||||
onClose();
|
||||
}
|
||||
}, [selectedPath, onSelect, onClose]);
|
||||
}, [selectedPath, onSelect, onClose, toRelativePath]);
|
||||
|
||||
const handleDoubleClick = useCallback((node: FileNode) => {
|
||||
if (!node.isDirectory) {
|
||||
onSelect(node.path);
|
||||
onSelect(toRelativePath(node.path));
|
||||
onClose();
|
||||
}
|
||||
}, [onSelect, onClose]);
|
||||
}, [onSelect, onClose, toRelativePath]);
|
||||
|
||||
const getFileIcon = (name: string) => {
|
||||
const ext = name.split('.').pop()?.toLowerCase();
|
||||
|
||||
374
packages/editor-app/src/components/dialogs/AssetSaveDialog.tsx
Normal file
374
packages/editor-app/src/components/dialogs/AssetSaveDialog.tsx
Normal file
@@ -0,0 +1,374 @@
|
||||
import React, { useState, useEffect, useMemo, useCallback } from 'react';
|
||||
import { X, Search, Folder, FolderOpen, FolderPlus } from 'lucide-react';
|
||||
import { Core } from '@esengine/ecs-framework';
|
||||
import { ProjectService, IFileSystemService } from '@esengine/editor-core';
|
||||
import type { IFileSystem } from '@esengine/editor-core';
|
||||
import './AssetPickerDialog.css';
|
||||
|
||||
interface AssetSaveDialogProps {
|
||||
isOpen: boolean;
|
||||
onClose: () => void;
|
||||
onSave: (path: string) => void;
|
||||
title?: string;
|
||||
defaultFileName?: string;
|
||||
fileExtension?: string; // e.g., '.tilemap.json'
|
||||
placeholder?: string;
|
||||
}
|
||||
|
||||
interface FileNode {
|
||||
name: string;
|
||||
path: string;
|
||||
isDirectory: boolean;
|
||||
children?: FileNode[];
|
||||
}
|
||||
|
||||
export function AssetSaveDialog({
|
||||
isOpen,
|
||||
onClose,
|
||||
onSave,
|
||||
title = 'Save Asset',
|
||||
defaultFileName = 'new-asset',
|
||||
fileExtension = '',
|
||||
placeholder = 'Search folders...'
|
||||
}: AssetSaveDialogProps) {
|
||||
const [searchTerm, setSearchTerm] = useState('');
|
||||
const [expandedFolders, setExpandedFolders] = useState<Set<string>>(new Set());
|
||||
const [selectedFolder, setSelectedFolder] = useState<string | null>(null);
|
||||
const [fileName, setFileName] = useState(defaultFileName);
|
||||
const [folders, setFolders] = useState<FileNode[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [projectPath, setProjectPath] = useState('');
|
||||
const [showNewFolderInput, setShowNewFolderInput] = useState(false);
|
||||
const [newFolderName, setNewFolderName] = useState('');
|
||||
|
||||
// Load project folders
|
||||
useEffect(() => {
|
||||
if (!isOpen) return;
|
||||
|
||||
const loadFolders = async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const projectService = Core.services.tryResolve(ProjectService);
|
||||
const fileSystem = Core.services.tryResolve<IFileSystem>(IFileSystemService);
|
||||
|
||||
const currentProject = projectService?.getCurrentProject();
|
||||
if (projectService && currentProject && fileSystem) {
|
||||
const projPath = currentProject.path;
|
||||
setProjectPath(projPath);
|
||||
const assetsPath = `${projPath}/assets`;
|
||||
|
||||
// Set default selected folder to assets
|
||||
setSelectedFolder(assetsPath);
|
||||
|
||||
const buildTree = async (dirPath: string): Promise<FileNode[]> => {
|
||||
const entries = await fileSystem.listDirectory(dirPath);
|
||||
const nodes: FileNode[] = [];
|
||||
|
||||
for (const entry of entries) {
|
||||
// Only include directories
|
||||
if (entry.isDirectory) {
|
||||
const node: FileNode = {
|
||||
name: entry.name,
|
||||
path: entry.path,
|
||||
isDirectory: true
|
||||
};
|
||||
|
||||
try {
|
||||
node.children = await buildTree(entry.path);
|
||||
} catch {
|
||||
node.children = [];
|
||||
}
|
||||
|
||||
nodes.push(node);
|
||||
}
|
||||
}
|
||||
|
||||
// Sort alphabetically
|
||||
return nodes.sort((a, b) => a.name.localeCompare(b.name));
|
||||
};
|
||||
|
||||
const tree = await buildTree(assetsPath);
|
||||
// Add root assets folder
|
||||
const rootNode: FileNode = {
|
||||
name: 'assets',
|
||||
path: assetsPath,
|
||||
isDirectory: true,
|
||||
children: tree
|
||||
};
|
||||
setFolders([rootNode]);
|
||||
setExpandedFolders(new Set([assetsPath]));
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to load folders:', error);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
loadFolders();
|
||||
setFileName(defaultFileName);
|
||||
setSearchTerm('');
|
||||
}, [isOpen, defaultFileName]);
|
||||
|
||||
// Filter folders based on search
|
||||
const filteredFolders = useMemo(() => {
|
||||
if (!searchTerm) return folders;
|
||||
|
||||
const filterNode = (node: FileNode): FileNode | null => {
|
||||
const matchesSearch = node.name.toLowerCase().includes(searchTerm.toLowerCase());
|
||||
|
||||
if (node.children) {
|
||||
const filteredChildren = node.children
|
||||
.map(filterNode)
|
||||
.filter((n): n is FileNode => n !== null);
|
||||
|
||||
if (filteredChildren.length > 0 || matchesSearch) {
|
||||
return { ...node, children: filteredChildren };
|
||||
}
|
||||
}
|
||||
|
||||
return matchesSearch ? node : null;
|
||||
};
|
||||
|
||||
return folders
|
||||
.map(filterNode)
|
||||
.filter((n): n is FileNode => n !== null);
|
||||
}, [folders, searchTerm]);
|
||||
|
||||
const toggleFolder = useCallback((path: string) => {
|
||||
setExpandedFolders((prev) => {
|
||||
const next = new Set(prev);
|
||||
if (next.has(path)) {
|
||||
next.delete(path);
|
||||
} else {
|
||||
next.add(path);
|
||||
}
|
||||
return next;
|
||||
});
|
||||
}, []);
|
||||
|
||||
const handleSelectFolder = useCallback((node: FileNode) => {
|
||||
setSelectedFolder(node.path);
|
||||
if (!expandedFolders.has(node.path)) {
|
||||
toggleFolder(node.path);
|
||||
}
|
||||
}, [expandedFolders, toggleFolder]);
|
||||
|
||||
// Convert absolute path to relative path based on project root
|
||||
const toRelativePath = useCallback((absolutePath: string): string => {
|
||||
if (projectPath) {
|
||||
const normalizedProject = projectPath.replace(/\\/g, '/');
|
||||
const normalizedAbsolute = absolutePath.replace(/\\/g, '/');
|
||||
if (normalizedAbsolute.startsWith(normalizedProject)) {
|
||||
return normalizedAbsolute.substring(normalizedProject.length + 1);
|
||||
}
|
||||
}
|
||||
return absolutePath;
|
||||
}, [projectPath]);
|
||||
|
||||
const handleSave = useCallback(() => {
|
||||
if (selectedFolder && fileName) {
|
||||
// Ensure file has correct extension
|
||||
let finalFileName = fileName;
|
||||
if (fileExtension && !finalFileName.endsWith(fileExtension)) {
|
||||
finalFileName += fileExtension;
|
||||
}
|
||||
|
||||
const fullPath = `${selectedFolder}/${finalFileName}`.replace(/\\/g, '/');
|
||||
onSave(toRelativePath(fullPath));
|
||||
onClose();
|
||||
}
|
||||
}, [selectedFolder, fileName, fileExtension, onSave, onClose, toRelativePath]);
|
||||
|
||||
const handleCreateFolder = useCallback(async () => {
|
||||
if (!selectedFolder || !newFolderName.trim()) return;
|
||||
|
||||
const fileSystem = Core.services.tryResolve<IFileSystem>(IFileSystemService);
|
||||
if (!fileSystem) return;
|
||||
|
||||
try {
|
||||
const newFolderPath = `${selectedFolder}/${newFolderName.trim()}`.replace(/\\/g, '/');
|
||||
await fileSystem.createDirectory(newFolderPath);
|
||||
|
||||
// Add new folder to tree
|
||||
const addFolderToTree = (nodes: FileNode[]): FileNode[] => {
|
||||
return nodes.map(node => {
|
||||
if (node.path === selectedFolder) {
|
||||
const newNode: FileNode = {
|
||||
name: newFolderName.trim(),
|
||||
path: newFolderPath,
|
||||
isDirectory: true,
|
||||
children: []
|
||||
};
|
||||
return {
|
||||
...node,
|
||||
children: [...(node.children || []), newNode].sort((a, b) => a.name.localeCompare(b.name))
|
||||
};
|
||||
}
|
||||
if (node.children) {
|
||||
return { ...node, children: addFolderToTree(node.children) };
|
||||
}
|
||||
return node;
|
||||
});
|
||||
};
|
||||
|
||||
setFolders(addFolderToTree(folders));
|
||||
setSelectedFolder(newFolderPath);
|
||||
setExpandedFolders(prev => new Set([...prev, selectedFolder]));
|
||||
setShowNewFolderInput(false);
|
||||
setNewFolderName('');
|
||||
} catch (error) {
|
||||
console.error('Failed to create folder:', error);
|
||||
}
|
||||
}, [selectedFolder, newFolderName, folders]);
|
||||
|
||||
const renderNode = (node: FileNode, depth: number = 0) => {
|
||||
const isExpanded = expandedFolders.has(node.path);
|
||||
const isSelected = selectedFolder === node.path;
|
||||
|
||||
return (
|
||||
<div key={node.path}>
|
||||
<div
|
||||
className={`asset-picker-item ${isSelected ? 'selected' : ''}`}
|
||||
style={{ paddingLeft: `${depth * 16 + 8}px` }}
|
||||
onClick={() => handleSelectFolder(node)}
|
||||
onDoubleClick={() => toggleFolder(node.path)}
|
||||
>
|
||||
<span className="asset-picker-item__icon">
|
||||
{isExpanded ? <FolderOpen size={14} /> : <Folder size={14} />}
|
||||
</span>
|
||||
<span className="asset-picker-item__name">{node.name}</span>
|
||||
</div>
|
||||
{isExpanded && node.children && (
|
||||
<div className="asset-picker-children">
|
||||
{node.children.map((child) => renderNode(child, depth + 1))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
const getDisplayPath = () => {
|
||||
if (!selectedFolder) return '';
|
||||
const relativePath = toRelativePath(selectedFolder);
|
||||
let finalFileName = fileName;
|
||||
if (fileExtension && !finalFileName.endsWith(fileExtension)) {
|
||||
finalFileName += fileExtension;
|
||||
}
|
||||
return `${relativePath}/${finalFileName}`;
|
||||
};
|
||||
|
||||
if (!isOpen) return null;
|
||||
|
||||
return (
|
||||
<div className="asset-picker-overlay" onClick={onClose}>
|
||||
<div className="asset-picker-dialog" onClick={(e) => e.stopPropagation()}>
|
||||
<div className="asset-picker-header">
|
||||
<h3>{title}</h3>
|
||||
<button className="asset-picker-close" onClick={onClose}>
|
||||
<X size={16} />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="asset-picker-search">
|
||||
<Search size={14} />
|
||||
<input
|
||||
type="text"
|
||||
placeholder={placeholder}
|
||||
value={searchTerm}
|
||||
onChange={(e) => setSearchTerm(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="asset-picker-content">
|
||||
{loading ? (
|
||||
<div className="asset-picker-loading">Loading folders...</div>
|
||||
) : filteredFolders.length === 0 ? (
|
||||
<div className="asset-picker-empty">No folders found</div>
|
||||
) : (
|
||||
<div className="asset-picker-tree">
|
||||
{filteredFolders.map((node) => renderNode(node))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* New folder input */}
|
||||
{showNewFolderInput && (
|
||||
<div className="asset-save-new-folder">
|
||||
<input
|
||||
type="text"
|
||||
value={newFolderName}
|
||||
onChange={(e) => setNewFolderName(e.target.value)}
|
||||
placeholder="New folder name"
|
||||
autoFocus
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter') handleCreateFolder();
|
||||
if (e.key === 'Escape') {
|
||||
setShowNewFolderInput(false);
|
||||
setNewFolderName('');
|
||||
}
|
||||
}}
|
||||
/>
|
||||
<button onClick={handleCreateFolder} disabled={!newFolderName.trim()}>
|
||||
Create
|
||||
</button>
|
||||
<button onClick={() => {
|
||||
setShowNewFolderInput(false);
|
||||
setNewFolderName('');
|
||||
}}>
|
||||
Cancel
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* New folder button */}
|
||||
{!showNewFolderInput && selectedFolder && (
|
||||
<div className="asset-save-new-folder-btn">
|
||||
<button onClick={() => setShowNewFolderInput(true)}>
|
||||
<FolderPlus size={14} />
|
||||
New Folder
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="asset-save-filename">
|
||||
<label>File name:</label>
|
||||
<input
|
||||
type="text"
|
||||
value={fileName}
|
||||
onChange={(e) => setFileName(e.target.value)}
|
||||
placeholder="Enter file name"
|
||||
autoFocus
|
||||
/>
|
||||
{fileExtension && (
|
||||
<span className="asset-save-extension">{fileExtension}</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="asset-picker-footer">
|
||||
<div className="asset-picker-selected">
|
||||
{selectedFolder ? (
|
||||
<span title={getDisplayPath()}>
|
||||
{getDisplayPath()}
|
||||
</span>
|
||||
) : (
|
||||
<span className="placeholder">Select a folder</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="asset-picker-actions">
|
||||
<button className="btn-cancel" onClick={onClose}>
|
||||
Cancel
|
||||
</button>
|
||||
<button
|
||||
className="btn-confirm"
|
||||
onClick={handleSave}
|
||||
disabled={!selectedFolder || !fileName}
|
||||
>
|
||||
Save
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -113,6 +113,16 @@
|
||||
color: #f87171;
|
||||
}
|
||||
|
||||
/* 创建按钮特殊样式 */
|
||||
.asset-field__button--create {
|
||||
color: #4ade80;
|
||||
}
|
||||
|
||||
.asset-field__button--create:hover {
|
||||
background: #1a3a1a;
|
||||
color: #4ade80;
|
||||
}
|
||||
|
||||
/* 禁用状态 */
|
||||
.asset-field__container[disabled] {
|
||||
opacity: 0.6;
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import React, { useState, useRef, useCallback } from 'react';
|
||||
import { FileText, Search, X, FolderOpen, ArrowRight, Package } from 'lucide-react';
|
||||
import { FileText, Search, X, FolderOpen, ArrowRight, Package, Plus } from 'lucide-react';
|
||||
import { AssetPickerDialog } from '../../../components/dialogs/AssetPickerDialog';
|
||||
import './AssetField.css';
|
||||
|
||||
@@ -11,6 +11,7 @@ interface AssetFieldProps {
|
||||
placeholder?: string;
|
||||
readonly?: boolean;
|
||||
onNavigate?: (path: string) => void; // 导航到资产
|
||||
onCreate?: () => void; // 创建新资产
|
||||
}
|
||||
|
||||
export function AssetField({
|
||||
@@ -20,7 +21,8 @@ export function AssetField({
|
||||
fileExtension = '',
|
||||
placeholder = 'None',
|
||||
readonly = false,
|
||||
onNavigate
|
||||
onNavigate,
|
||||
onCreate
|
||||
}: AssetFieldProps) {
|
||||
const [isDragging, setIsDragging] = useState(false);
|
||||
const [isHovered, setIsHovered] = useState(false);
|
||||
@@ -137,6 +139,20 @@ export function AssetField({
|
||||
|
||||
{/* 操作按钮组 */}
|
||||
<div className="asset-field__actions">
|
||||
{/* 创建按钮 */}
|
||||
{onCreate && !readonly && !value && (
|
||||
<button
|
||||
className="asset-field__button asset-field__button--create"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
onCreate();
|
||||
}}
|
||||
title="创建新资产"
|
||||
>
|
||||
<Plus size={12} />
|
||||
</button>
|
||||
)}
|
||||
|
||||
{/* 浏览按钮 */}
|
||||
{!readonly && (
|
||||
<button
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { useState } from 'react';
|
||||
import { Settings, ChevronDown, ChevronRight, X, Plus, Box } from 'lucide-react';
|
||||
import { Entity, Component, Core, getComponentDependencies, getComponentTypeName, getComponentInstanceTypeName } from '@esengine/ecs-framework';
|
||||
import { MessageHub, CommandManager, ComponentRegistry } from '@esengine/editor-core';
|
||||
import { MessageHub, CommandManager, ComponentRegistry, ComponentActionRegistry } from '@esengine/editor-core';
|
||||
import { PropertyInspector } from '../../PropertyInspector';
|
||||
import { NotificationService } from '../../../services/NotificationService';
|
||||
import { RemoveComponentCommand, UpdateComponentCommand, AddComponentCommand } from '../../../application/commands/component';
|
||||
@@ -21,6 +21,7 @@ export function EntityInspector({ entity, messageHub, commandManager, componentV
|
||||
const [localVersion, setLocalVersion] = useState(0);
|
||||
|
||||
const componentRegistry = Core.services.resolve(ComponentRegistry);
|
||||
const componentActionRegistry = Core.services.resolve(ComponentActionRegistry);
|
||||
const availableComponents = componentRegistry?.getAllComponents() || [];
|
||||
|
||||
const toggleComponentExpanded = (index: number) => {
|
||||
@@ -252,6 +253,32 @@ export function EntityInspector({ entity, messageHub, commandManager, componentV
|
||||
}
|
||||
onAction={handlePropertyAction}
|
||||
/>
|
||||
{/* Dynamic component actions from plugins */}
|
||||
{componentActionRegistry?.getActionsForComponent(componentName).map((action) => (
|
||||
<button
|
||||
key={action.id}
|
||||
className="component-action-btn"
|
||||
onClick={() => action.execute(component, entity)}
|
||||
style={{
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
gap: '6px',
|
||||
padding: '8px 12px',
|
||||
width: '100%',
|
||||
marginTop: '8px',
|
||||
border: 'none',
|
||||
borderRadius: '4px',
|
||||
background: 'var(--accent-color, #0078d4)',
|
||||
color: 'white',
|
||||
cursor: 'pointer',
|
||||
fontSize: '12px',
|
||||
fontWeight: 500,
|
||||
}}
|
||||
>
|
||||
{action.icon}
|
||||
{action.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
81
packages/editor-app/src/gizmos/SpriteGizmo.ts
Normal file
81
packages/editor-app/src/gizmos/SpriteGizmo.ts
Normal file
@@ -0,0 +1,81 @@
|
||||
/**
|
||||
* Sprite Gizmo Implementation
|
||||
* 精灵 Gizmo 实现
|
||||
*
|
||||
* Registers gizmo provider for SpriteComponent using the GizmoRegistry.
|
||||
* Rendered via Rust WebGL engine for optimal performance.
|
||||
* 使用 GizmoRegistry 为 SpriteComponent 注册 gizmo 提供者。
|
||||
* 通过 Rust WebGL 引擎渲染以获得最佳性能。
|
||||
*/
|
||||
|
||||
import type { Entity } from '@esengine/ecs-framework';
|
||||
import type { IGizmoRenderData, IRectGizmoData, GizmoColor } from '@esengine/editor-core';
|
||||
import { GizmoColors, GizmoRegistry } from '@esengine/editor-core';
|
||||
import { SpriteComponent, TransformComponent } from '@esengine/ecs-components';
|
||||
|
||||
/**
|
||||
* Gizmo provider function for SpriteComponent.
|
||||
* SpriteComponent 的 gizmo 提供者函数。
|
||||
*/
|
||||
function spriteGizmoProvider(
|
||||
sprite: SpriteComponent,
|
||||
entity: Entity,
|
||||
isSelected: boolean
|
||||
): IGizmoRenderData[] {
|
||||
const transform = entity.getComponent(TransformComponent);
|
||||
if (!transform) {
|
||||
return [];
|
||||
}
|
||||
|
||||
// Calculate world-space dimensions
|
||||
// 计算世界空间尺寸
|
||||
const width = sprite.width * transform.scale.x;
|
||||
const height = sprite.height * transform.scale.y;
|
||||
|
||||
// Get rotation (handle both number and Vector3)
|
||||
// 获取旋转(处理数字和 Vector3 两种情况)
|
||||
const rotation = typeof transform.rotation === 'number'
|
||||
? transform.rotation
|
||||
: transform.rotation.z;
|
||||
|
||||
// Use predefined colors based on selection state
|
||||
// 根据选择状态使用预定义颜色
|
||||
const color: GizmoColor = isSelected
|
||||
? GizmoColors.selected
|
||||
: GizmoColors.unselected;
|
||||
|
||||
const gizmo: IRectGizmoData = {
|
||||
type: 'rect',
|
||||
x: transform.position.x,
|
||||
y: transform.position.y,
|
||||
width,
|
||||
height,
|
||||
rotation,
|
||||
originX: sprite.anchorX,
|
||||
originY: sprite.anchorY,
|
||||
color,
|
||||
showHandles: false // Selection handles are drawn separately by EngineRenderSystem
|
||||
};
|
||||
|
||||
return [gizmo];
|
||||
}
|
||||
|
||||
/**
|
||||
* Register gizmo provider for SpriteComponent.
|
||||
* 为 SpriteComponent 注册 gizmo 提供者。
|
||||
*
|
||||
* Uses the GizmoRegistry pattern for clean separation between
|
||||
* game components and editor functionality.
|
||||
* 使用 GizmoRegistry 模式实现游戏组件和编辑器功能的清晰分离。
|
||||
*/
|
||||
export function registerSpriteGizmo(): void {
|
||||
GizmoRegistry.register(SpriteComponent, spriteGizmoProvider);
|
||||
}
|
||||
|
||||
/**
|
||||
* Unregister gizmo provider for SpriteComponent.
|
||||
* 取消注册 SpriteComponent 的 gizmo 提供者。
|
||||
*/
|
||||
export function unregisterSpriteGizmo(): void {
|
||||
GizmoRegistry.unregister(SpriteComponent);
|
||||
}
|
||||
9
packages/editor-app/src/gizmos/index.ts
Normal file
9
packages/editor-app/src/gizmos/index.ts
Normal file
@@ -0,0 +1,9 @@
|
||||
/**
|
||||
* Editor Gizmos
|
||||
* 编辑器 Gizmos
|
||||
*
|
||||
* Gizmo implementations for built-in components.
|
||||
* 内置组件的 Gizmo 实现。
|
||||
*/
|
||||
|
||||
export { registerSpriteGizmo } from './SpriteGizmo';
|
||||
@@ -23,6 +23,25 @@ export class AssetFieldEditor implements IFieldEditor<string | null> {
|
||||
}
|
||||
};
|
||||
|
||||
const handleCreate = () => {
|
||||
const messageHub = Core.services.tryResolve(MessageHub);
|
||||
if (messageHub) {
|
||||
if (fileExtension === '.tilemap.json') {
|
||||
messageHub.publish('tilemap:create-asset', {
|
||||
entityId: context.metadata?.entityId,
|
||||
onChange
|
||||
});
|
||||
} else if (fileExtension === '.btree') {
|
||||
messageHub.publish('behavior-tree:create-asset', {
|
||||
entityId: context.metadata?.entityId,
|
||||
onChange
|
||||
});
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const canCreate = ['.tilemap.json', '.btree'].includes(fileExtension);
|
||||
|
||||
return (
|
||||
<AssetField
|
||||
label={label}
|
||||
@@ -32,6 +51,7 @@ export class AssetFieldEditor implements IFieldEditor<string | null> {
|
||||
placeholder={placeholder}
|
||||
readonly={context.readonly}
|
||||
onNavigate={handleNavigate}
|
||||
onCreate={canCreate ? handleCreate : undefined}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
40
packages/editor-app/src/plugins/GizmoPlugin.ts
Normal file
40
packages/editor-app/src/plugins/GizmoPlugin.ts
Normal file
@@ -0,0 +1,40 @@
|
||||
/**
|
||||
* Gizmo Plugin
|
||||
* Gizmo 插件
|
||||
*
|
||||
* Registers gizmo support for built-in components
|
||||
* 为内置组件注册 gizmo 支持
|
||||
*/
|
||||
|
||||
import type { Core, ServiceContainer } from '@esengine/ecs-framework';
|
||||
import type { IEditorPlugin } from '@esengine/editor-core';
|
||||
import { EditorPluginCategory } from '@esengine/editor-core';
|
||||
import { registerSpriteGizmo } from '../gizmos';
|
||||
|
||||
export class GizmoPlugin implements IEditorPlugin {
|
||||
readonly name = '@esengine/gizmo-plugin';
|
||||
readonly version = '1.0.0';
|
||||
readonly category = EditorPluginCategory.Tool;
|
||||
|
||||
get displayName(): string {
|
||||
return 'Gizmo System';
|
||||
}
|
||||
|
||||
get description(): string {
|
||||
return 'Provides gizmo support for editor components';
|
||||
}
|
||||
|
||||
async install(_core: Core, _services: ServiceContainer): Promise<void> {
|
||||
// Register gizmo support for SpriteComponent
|
||||
// 为 SpriteComponent 注册 gizmo 支持
|
||||
registerSpriteGizmo();
|
||||
|
||||
console.log('[GizmoPlugin] Installed - registered gizmo support for built-in components');
|
||||
}
|
||||
|
||||
async uninstall(): Promise<void> {
|
||||
console.log('[GizmoPlugin] Uninstalled');
|
||||
}
|
||||
}
|
||||
|
||||
export const gizmoPlugin = new GizmoPlugin();
|
||||
@@ -3,12 +3,21 @@
|
||||
* 管理Rust引擎生命周期的服务。
|
||||
*/
|
||||
|
||||
import { EngineBridge, EngineRenderSystem, CameraConfig } from '@esengine/ecs-engine-bindgen';
|
||||
import { EngineBridge, EngineRenderSystem, CameraConfig, GizmoDataProviderFn, HasGizmoProviderFn } from '@esengine/ecs-engine-bindgen';
|
||||
import { GizmoRegistry } from '@esengine/editor-core';
|
||||
import { Core, Scene, Entity, SceneSerializer } from '@esengine/ecs-framework';
|
||||
import { TransformComponent, SpriteComponent, SpriteAnimatorSystem, SpriteAnimatorComponent } from '@esengine/ecs-components';
|
||||
import { EntityStoreService, MessageHub } from '@esengine/editor-core';
|
||||
import { TilemapComponent, TilemapRenderingSystem } from '@esengine/tilemap';
|
||||
import { EntityStoreService, MessageHub, SceneManagerService, ProjectService } from '@esengine/editor-core';
|
||||
import * as esEngine from '@esengine/engine';
|
||||
import { AssetManager, EngineIntegration, AssetPathResolver, AssetPlatform } from '@esengine/asset-system';
|
||||
import {
|
||||
AssetManager,
|
||||
EngineIntegration,
|
||||
AssetPathResolver,
|
||||
AssetPlatform,
|
||||
globalPathResolver,
|
||||
SceneResourceManager
|
||||
} from '@esengine/asset-system';
|
||||
import { convertFileSrc } from '@tauri-apps/api/core';
|
||||
import { IdGenerator } from '../utils/idGenerator';
|
||||
|
||||
@@ -23,6 +32,7 @@ export class EngineService {
|
||||
private scene: Scene | null = null;
|
||||
private renderSystem: EngineRenderSystem | null = null;
|
||||
private animatorSystem: SpriteAnimatorSystem | null = null;
|
||||
private tilemapSystem: TilemapRenderingSystem | null = null;
|
||||
private initialized = false;
|
||||
private running = false;
|
||||
private animationFrameId: number | null = null;
|
||||
@@ -30,6 +40,7 @@ export class EngineService {
|
||||
private sceneSnapshot: string | null = null;
|
||||
private assetManager: AssetManager | null = null;
|
||||
private engineIntegration: EngineIntegration | null = null;
|
||||
private sceneResourceManager: SceneResourceManager | null = null;
|
||||
private assetPathResolver: AssetPathResolver | null = null;
|
||||
private assetSystemInitialized = false;
|
||||
private initializationError: Error | null = null;
|
||||
@@ -97,10 +108,28 @@ export class EngineService {
|
||||
this.animatorSystem.enabled = false;
|
||||
this.scene!.addSystem(this.animatorSystem);
|
||||
|
||||
// Add tilemap rendering system
|
||||
// 添加瓦片地图渲染系统
|
||||
this.tilemapSystem = new TilemapRenderingSystem();
|
||||
this.scene!.addSystem(this.tilemapSystem);
|
||||
|
||||
// Add render system to the scene | 将渲染系统添加到场景
|
||||
this.renderSystem = new EngineRenderSystem(this.bridge, TransformComponent);
|
||||
this.scene!.addSystem(this.renderSystem);
|
||||
|
||||
// Register tilemap system as render data provider
|
||||
// 将瓦片地图系统注册为渲染数据提供者
|
||||
this.renderSystem.addRenderDataProvider(this.tilemapSystem);
|
||||
|
||||
// Inject GizmoRegistry into render system
|
||||
// 将 GizmoRegistry 注入渲染系统
|
||||
this.renderSystem.setGizmoRegistry(
|
||||
((component, entity, isSelected) =>
|
||||
GizmoRegistry.getGizmoData(component, entity, isSelected)) as GizmoDataProviderFn,
|
||||
((component) =>
|
||||
GizmoRegistry.hasProvider(component.constructor as any)) as HasGizmoProviderFn
|
||||
);
|
||||
|
||||
// Initialize asset system | 初始化资产系统
|
||||
await this.initializeAssetSystem();
|
||||
|
||||
@@ -349,21 +378,55 @@ export class EngineService {
|
||||
this.assetManager = new AssetManager();
|
||||
|
||||
// 创建路径解析器 / Create path resolver
|
||||
const pathTransformerFn = (path: string) => {
|
||||
// 编辑器平台使用Tauri的convertFileSrc
|
||||
// Use Tauri's convertFileSrc for editor platform
|
||||
if (!path.startsWith('http://') && !path.startsWith('https://') && !path.startsWith('data:') && !path.startsWith('asset://')) {
|
||||
// 如果是相对路径,需要先转换为绝对路径
|
||||
// If it's a relative path, convert to absolute path first
|
||||
if (!path.startsWith('/') && !path.match(/^[a-zA-Z]:/)) {
|
||||
const projectService = Core.services.tryResolve<ProjectService>(ProjectService);
|
||||
if (projectService && projectService.isProjectOpen()) {
|
||||
const projectInfo = projectService.getCurrentProject();
|
||||
if (projectInfo) {
|
||||
const projectPath = projectInfo.path;
|
||||
// 规范化路径分隔符 / Normalize path separators
|
||||
const separator = projectPath.includes('\\') ? '\\' : '/';
|
||||
path = `${projectPath}${separator}${path.replace(/\//g, separator)}`;
|
||||
}
|
||||
}
|
||||
}
|
||||
return convertFileSrc(path);
|
||||
}
|
||||
return path;
|
||||
};
|
||||
|
||||
this.assetPathResolver = new AssetPathResolver({
|
||||
platform: AssetPlatform.Editor,
|
||||
pathTransformer: (path: string) => {
|
||||
// 编辑器平台使用Tauri的convertFileSrc
|
||||
// Use Tauri's convertFileSrc for editor platform
|
||||
if (!path.startsWith('http://') && !path.startsWith('https://') && !path.startsWith('data:')) {
|
||||
return convertFileSrc(path);
|
||||
}
|
||||
return path;
|
||||
}
|
||||
pathTransformer: pathTransformerFn
|
||||
});
|
||||
|
||||
// 配置全局路径解析器,供组件使用
|
||||
// Configure global path resolver for components to use
|
||||
globalPathResolver.updateConfig({
|
||||
platform: AssetPlatform.Editor,
|
||||
pathTransformer: pathTransformerFn
|
||||
});
|
||||
|
||||
// 创建引擎集成 / Create engine integration
|
||||
if (this.bridge) {
|
||||
this.engineIntegration = new EngineIntegration(this.assetManager, this.bridge);
|
||||
|
||||
// 创建场景资源管理器 / Create scene resource manager
|
||||
this.sceneResourceManager = new SceneResourceManager();
|
||||
this.sceneResourceManager.setResourceLoader(this.engineIntegration);
|
||||
|
||||
// 将 SceneResourceManager 设置到 SceneManagerService
|
||||
// Set SceneResourceManager to SceneManagerService
|
||||
const sceneManagerService = Core.services.tryResolve<SceneManagerService>(SceneManagerService);
|
||||
if (sceneManagerService) {
|
||||
sceneManagerService.setSceneResourceManager(this.sceneResourceManager);
|
||||
}
|
||||
}
|
||||
|
||||
this.assetSystemInitialized = true;
|
||||
@@ -625,18 +688,34 @@ export class EngineService {
|
||||
* Restore scene state from saved snapshot.
|
||||
* 从保存的快照恢复场景状态。
|
||||
*/
|
||||
restoreSceneSnapshot(): boolean {
|
||||
async restoreSceneSnapshot(): Promise<boolean> {
|
||||
if (!this.scene || !this.sceneSnapshot) {
|
||||
console.warn('Cannot restore snapshot: no scene or snapshot available');
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
// Clear tilemap rendering cache before restoring
|
||||
// 恢复前清除瓦片地图渲染缓存
|
||||
if (this.tilemapSystem) {
|
||||
console.log('[EngineService] Clearing tilemap cache before restore');
|
||||
this.tilemapSystem.clearCache();
|
||||
}
|
||||
|
||||
// Use SceneSerializer from core library
|
||||
console.log('[EngineService] Deserializing scene snapshot');
|
||||
SceneSerializer.deserialize(this.scene, this.sceneSnapshot, {
|
||||
strategy: 'replace',
|
||||
preserveIds: true
|
||||
});
|
||||
console.log('[EngineService] Scene deserialized, entities:', this.scene.entities.buffer.length);
|
||||
|
||||
// 加载场景资源 / Load scene resources
|
||||
if (this.sceneResourceManager) {
|
||||
await this.sceneResourceManager.loadSceneResources(this.scene);
|
||||
} else {
|
||||
console.warn('[EngineService] SceneResourceManager not available, skipping resource loading');
|
||||
}
|
||||
|
||||
// Sync EntityStore with restored scene entities
|
||||
const entityStore = Core.services.tryResolve(EntityStoreService);
|
||||
@@ -663,6 +742,7 @@ export class EngineService {
|
||||
}
|
||||
|
||||
// Notify UI to refresh
|
||||
console.log('[EngineService] Publishing scene:restored event');
|
||||
messageHub.publish('scene:restored', {});
|
||||
}
|
||||
|
||||
|
||||
73
packages/editor-app/src/services/ImportMapManager.ts
Normal file
73
packages/editor-app/src/services/ImportMapManager.ts
Normal file
@@ -0,0 +1,73 @@
|
||||
interface ImportMap {
|
||||
imports: Record<string, string>;
|
||||
scopes?: Record<string, Record<string, string>>;
|
||||
}
|
||||
|
||||
const SDK_MODULES: Record<string, string> = {
|
||||
'@esengine/editor-runtime': 'editor-runtime.js',
|
||||
'@esengine/behavior-tree': 'behavior-tree.js',
|
||||
};
|
||||
|
||||
class ImportMapManager {
|
||||
private initialized = false;
|
||||
private importMap: ImportMap = { imports: {} };
|
||||
|
||||
async initialize(): Promise<void> {
|
||||
if (this.initialized) {
|
||||
return;
|
||||
}
|
||||
|
||||
await this.buildImportMap();
|
||||
this.injectImportMap();
|
||||
|
||||
this.initialized = true;
|
||||
console.log('[ImportMapManager] Import Map initialized:', this.importMap);
|
||||
}
|
||||
|
||||
private async buildImportMap(): Promise<void> {
|
||||
const baseUrl = this.getBaseUrl();
|
||||
|
||||
for (const [moduleName, fileName] of Object.entries(SDK_MODULES)) {
|
||||
this.importMap.imports[moduleName] = `${baseUrl}assets/${fileName}`;
|
||||
}
|
||||
}
|
||||
|
||||
private getBaseUrl(): string {
|
||||
return window.location.origin + '/';
|
||||
}
|
||||
|
||||
private injectImportMap(): void {
|
||||
const existingMap = document.querySelector('script[type="importmap"]');
|
||||
if (existingMap) {
|
||||
try {
|
||||
const existing = JSON.parse(existingMap.textContent || '{}');
|
||||
this.importMap.imports = { ...existing.imports, ...this.importMap.imports };
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
existingMap.remove();
|
||||
}
|
||||
|
||||
const script = document.createElement('script');
|
||||
script.type = 'importmap';
|
||||
script.textContent = JSON.stringify(this.importMap, null, 2);
|
||||
|
||||
const head = document.head;
|
||||
const firstScript = head.querySelector('script');
|
||||
if (firstScript) {
|
||||
head.insertBefore(script, firstScript);
|
||||
} else {
|
||||
head.appendChild(script);
|
||||
}
|
||||
}
|
||||
|
||||
getImportMap(): ImportMap {
|
||||
return { ...this.importMap };
|
||||
}
|
||||
|
||||
isInitialized(): boolean {
|
||||
return this.initialized;
|
||||
}
|
||||
}
|
||||
|
||||
export const importMapManager = new ImportMapManager();
|
||||
@@ -2,6 +2,7 @@ import { EditorPluginManager, LocaleService, MessageHub } from '@esengine/editor
|
||||
import type { IEditorPlugin } from '@esengine/editor-core';
|
||||
import { Core } from '@esengine/ecs-framework';
|
||||
import { TauriAPI } from '../api/tauri';
|
||||
import { importMapManager } from './ImportMapManager';
|
||||
|
||||
interface PluginPackageJson {
|
||||
name: string;
|
||||
@@ -12,31 +13,41 @@ interface PluginPackageJson {
|
||||
'.': {
|
||||
import?: string;
|
||||
require?: string;
|
||||
development?: {
|
||||
types?: string;
|
||||
import?: string;
|
||||
};
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 插件加载器
|
||||
*
|
||||
* 负责从项目的 plugins 目录加载用户插件。
|
||||
* 统一使用 project:// 协议加载预编译的 JS 文件。
|
||||
*/
|
||||
export class PluginLoader {
|
||||
private loadedPluginNames: Set<string> = new Set();
|
||||
private moduleVersions: Map<string, number> = new Map();
|
||||
private loadedModuleUrls: Set<string> = new Set();
|
||||
|
||||
/**
|
||||
* 加载项目中的所有插件
|
||||
*/
|
||||
async loadProjectPlugins(projectPath: string, pluginManager: EditorPluginManager): Promise<void> {
|
||||
// 确保 Import Map 已初始化
|
||||
await importMapManager.initialize();
|
||||
|
||||
const pluginsPath = `${projectPath}/plugins`;
|
||||
|
||||
try {
|
||||
const exists = await TauriAPI.pathExists(pluginsPath);
|
||||
if (!exists) {
|
||||
console.log('[PluginLoader] No plugins directory found');
|
||||
return;
|
||||
}
|
||||
|
||||
const entries = await TauriAPI.listDirectory(pluginsPath);
|
||||
const pluginDirs = entries.filter((entry) => entry.is_dir && !entry.name.startsWith('.'));
|
||||
|
||||
console.log(`[PluginLoader] Found ${pluginDirs.length} plugin(s)`);
|
||||
|
||||
for (const entry of pluginDirs) {
|
||||
const pluginPath = `${pluginsPath}/${entry.name}`;
|
||||
await this.loadPlugin(pluginPath, entry.name, pluginManager);
|
||||
@@ -46,114 +57,130 @@ export class PluginLoader {
|
||||
}
|
||||
}
|
||||
|
||||
private async loadPlugin(pluginPath: string, pluginDirName: string, pluginManager: EditorPluginManager): Promise<void> {
|
||||
/**
|
||||
* 加载单个插件
|
||||
*/
|
||||
private async loadPlugin(
|
||||
pluginPath: string,
|
||||
pluginDirName: string,
|
||||
pluginManager: EditorPluginManager
|
||||
): Promise<void> {
|
||||
try {
|
||||
const packageJsonPath = `${pluginPath}/package.json`;
|
||||
const packageJsonExists = await TauriAPI.pathExists(packageJsonPath);
|
||||
|
||||
if (!packageJsonExists) {
|
||||
console.warn(`[PluginLoader] No package.json found in ${pluginPath}`);
|
||||
// 1. 读取 package.json
|
||||
const packageJson = await this.readPackageJson(pluginPath);
|
||||
if (!packageJson) {
|
||||
return;
|
||||
}
|
||||
|
||||
const packageJsonContent = await TauriAPI.readFileContent(packageJsonPath);
|
||||
const packageJson: PluginPackageJson = JSON.parse(packageJsonContent);
|
||||
|
||||
// 2. 如果插件已加载,先卸载
|
||||
if (this.loadedPluginNames.has(packageJson.name)) {
|
||||
try {
|
||||
await pluginManager.uninstallEditor(packageJson.name);
|
||||
this.loadedPluginNames.delete(packageJson.name);
|
||||
} catch (error) {
|
||||
console.error(`[PluginLoader] Failed to uninstall existing plugin ${packageJson.name}:`, error);
|
||||
}
|
||||
await this.unloadPlugin(packageJson.name, pluginManager);
|
||||
}
|
||||
|
||||
let entryPoint = 'src/index.ts';
|
||||
// 3. 确定入口文件(必须是编译后的 JS)
|
||||
const entryPoint = this.resolveEntryPoint(packageJson);
|
||||
|
||||
if (packageJson.exports?.['.']?.development?.import) {
|
||||
entryPoint = packageJson.exports['.'].development.import;
|
||||
} else if (packageJson.exports?.['.']?.import) {
|
||||
const importPath = packageJson.exports['.'].import;
|
||||
if (importPath.startsWith('src/')) {
|
||||
entryPoint = importPath;
|
||||
} else {
|
||||
const srcPath = importPath.replace('dist/', 'src/').replace('.js', '.ts');
|
||||
const srcExists = await TauriAPI.pathExists(`${pluginPath}/${srcPath}`);
|
||||
entryPoint = srcExists ? srcPath : importPath;
|
||||
}
|
||||
} else if (packageJson.module) {
|
||||
const srcPath = packageJson.module.replace('dist/', 'src/').replace('.js', '.ts');
|
||||
const srcExists = await TauriAPI.pathExists(`${pluginPath}/${srcPath}`);
|
||||
entryPoint = srcExists ? srcPath : packageJson.module;
|
||||
} else if (packageJson.main) {
|
||||
const srcPath = packageJson.main.replace('dist/', 'src/').replace('.js', '.ts');
|
||||
const srcExists = await TauriAPI.pathExists(`${pluginPath}/${srcPath}`);
|
||||
entryPoint = srcExists ? srcPath : packageJson.main;
|
||||
// 4. 验证文件存在
|
||||
const fullPath = `${pluginPath}/${entryPoint}`;
|
||||
const exists = await TauriAPI.pathExists(fullPath);
|
||||
if (!exists) {
|
||||
console.error(`[PluginLoader] Plugin not built: ${fullPath}`);
|
||||
console.error(`[PluginLoader] Run: cd ${pluginPath} && npm run build`);
|
||||
return;
|
||||
}
|
||||
|
||||
// 移除开头的 ./
|
||||
entryPoint = entryPoint.replace(/^\.\//, '');
|
||||
|
||||
// 使用版本号+时间戳确保每次加载都是唯一URL
|
||||
const currentVersion = (this.moduleVersions.get(packageJson.name) || 0) + 1;
|
||||
this.moduleVersions.set(packageJson.name, currentVersion);
|
||||
const timestamp = Date.now();
|
||||
const moduleUrl = `/@user-project/plugins/${pluginDirName}/${entryPoint}?v=${currentVersion}&t=${timestamp}`;
|
||||
|
||||
// 清除可能存在的旧模块缓存
|
||||
this.loadedModuleUrls.add(moduleUrl);
|
||||
// 5. 构建模块 URL(使用 project:// 协议)
|
||||
const moduleUrl = this.buildModuleUrl(pluginDirName, entryPoint, packageJson.name);
|
||||
console.log(`[PluginLoader] Loading: ${packageJson.name} from ${moduleUrl}`);
|
||||
|
||||
// 6. 动态导入模块
|
||||
const module = await import(/* @vite-ignore */ moduleUrl);
|
||||
|
||||
let pluginInstance: IEditorPlugin | null = null;
|
||||
try {
|
||||
pluginInstance = this.findPluginInstance(module);
|
||||
} catch (findError) {
|
||||
console.error('[PluginLoader] Error finding plugin instance:', findError);
|
||||
console.error('[PluginLoader] Module object:', module);
|
||||
return;
|
||||
}
|
||||
|
||||
// 7. 查找并验证插件实例
|
||||
const pluginInstance = this.findPluginInstance(module);
|
||||
if (!pluginInstance) {
|
||||
console.error(`[PluginLoader] No plugin instance found in ${packageJson.name}`);
|
||||
console.error(`[PluginLoader] No valid plugin instance found in ${packageJson.name}`);
|
||||
return;
|
||||
}
|
||||
|
||||
// 8. 安装插件
|
||||
await pluginManager.installEditor(pluginInstance);
|
||||
this.loadedPluginNames.add(packageJson.name);
|
||||
console.log(`[PluginLoader] Successfully loaded: ${packageJson.name}`);
|
||||
|
||||
// 同步插件的语言设置
|
||||
try {
|
||||
const localeService = Core.services.resolve(LocaleService);
|
||||
const currentLocale = localeService.getCurrentLocale();
|
||||
if (pluginInstance.setLocale) {
|
||||
pluginInstance.setLocale(currentLocale);
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn(`[PluginLoader] Failed to set locale for plugin ${packageJson.name}:`, error);
|
||||
}
|
||||
// 9. 同步语言设置
|
||||
this.syncPluginLocale(pluginInstance, packageJson.name);
|
||||
|
||||
// 通知节点面板重新加载模板
|
||||
try {
|
||||
const messageHub = Core.services.resolve(MessageHub);
|
||||
const localeService = Core.services.resolve(LocaleService);
|
||||
messageHub.publish('locale:changed', { locale: localeService.getCurrentLocale() });
|
||||
} catch (error) {
|
||||
console.warn('[PluginLoader] Failed to publish locale:changed event:', error);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(`[PluginLoader] Failed to load plugin from ${pluginPath}:`, error);
|
||||
if (error instanceof Error) {
|
||||
console.error('[PluginLoader] Error stack:', error.stack);
|
||||
console.error('[PluginLoader] Stack:', error.stack);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取插件的 package.json
|
||||
*/
|
||||
private async readPackageJson(pluginPath: string): Promise<PluginPackageJson | null> {
|
||||
const packageJsonPath = `${pluginPath}/package.json`;
|
||||
const exists = await TauriAPI.pathExists(packageJsonPath);
|
||||
|
||||
if (!exists) {
|
||||
console.warn(`[PluginLoader] No package.json found in ${pluginPath}`);
|
||||
return null;
|
||||
}
|
||||
|
||||
const content = await TauriAPI.readFileContent(packageJsonPath);
|
||||
return JSON.parse(content);
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析插件入口文件路径(始终使用编译后的 JS)
|
||||
*/
|
||||
private resolveEntryPoint(packageJson: PluginPackageJson): string {
|
||||
const entry = (
|
||||
packageJson.exports?.['.']?.import ||
|
||||
packageJson.module ||
|
||||
packageJson.main ||
|
||||
'dist/index.js'
|
||||
);
|
||||
return entry.replace(/^\.\//, '');
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建模块 URL(使用 project:// 协议)
|
||||
*
|
||||
* Windows 上需要用 http://project.localhost/ 格式
|
||||
* macOS/Linux 上用 project://localhost/ 格式
|
||||
*/
|
||||
private buildModuleUrl(pluginDirName: string, entryPoint: string, pluginName: string): string {
|
||||
// 版本号 + 时间戳确保每次加载都是新模块(绕过浏览器缓存)
|
||||
const version = (this.moduleVersions.get(pluginName) || 0) + 1;
|
||||
this.moduleVersions.set(pluginName, version);
|
||||
const timestamp = Date.now();
|
||||
|
||||
const path = `/plugins/${pluginDirName}/${entryPoint}?v=${version}&t=${timestamp}`;
|
||||
|
||||
// Windows 使用 http://scheme.localhost 格式
|
||||
// macOS/Linux 使用 scheme://localhost 格式
|
||||
const isWindows = navigator.userAgent.includes('Windows');
|
||||
if (isWindows) {
|
||||
return `http://project.localhost${path}`;
|
||||
}
|
||||
return `project://localhost${path}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 查找模块中的插件实例
|
||||
*/
|
||||
private findPluginInstance(module: any): IEditorPlugin | null {
|
||||
// 优先检查 default 导出
|
||||
if (module.default && this.isPluginInstance(module.default)) {
|
||||
return module.default;
|
||||
}
|
||||
|
||||
// 检查命名导出
|
||||
for (const key of Object.keys(module)) {
|
||||
const value = module[key];
|
||||
if (value && this.isPluginInstance(value)) {
|
||||
@@ -161,69 +188,74 @@ export class PluginLoader {
|
||||
}
|
||||
}
|
||||
|
||||
console.error('[PluginLoader] No valid plugin instance found. Exports:', module);
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证对象是否为有效的插件实例
|
||||
*/
|
||||
private isPluginInstance(obj: any): obj is IEditorPlugin {
|
||||
try {
|
||||
if (!obj || typeof obj !== 'object') {
|
||||
return false;
|
||||
}
|
||||
|
||||
const hasRequiredProperties =
|
||||
typeof obj.name === 'string' &&
|
||||
typeof obj.version === 'string' &&
|
||||
typeof obj.displayName === 'string' &&
|
||||
typeof obj.category === 'string' &&
|
||||
typeof obj.install === 'function' &&
|
||||
typeof obj.uninstall === 'function';
|
||||
|
||||
return hasRequiredProperties;
|
||||
} catch (error) {
|
||||
console.error('[PluginLoader] Error in isPluginInstance:', error);
|
||||
if (!obj || typeof obj !== 'object') {
|
||||
return false;
|
||||
}
|
||||
|
||||
return (
|
||||
typeof obj.name === 'string' &&
|
||||
typeof obj.version === 'string' &&
|
||||
typeof obj.displayName === 'string' &&
|
||||
typeof obj.category === 'string' &&
|
||||
typeof obj.install === 'function' &&
|
||||
typeof obj.uninstall === 'function'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 同步插件语言设置
|
||||
*/
|
||||
private syncPluginLocale(plugin: IEditorPlugin, pluginName: string): void {
|
||||
try {
|
||||
const localeService = Core.services.resolve(LocaleService);
|
||||
const currentLocale = localeService.getCurrentLocale();
|
||||
|
||||
if (plugin.setLocale) {
|
||||
plugin.setLocale(currentLocale);
|
||||
}
|
||||
|
||||
// 通知 UI 刷新
|
||||
const messageHub = Core.services.resolve(MessageHub);
|
||||
messageHub.publish('locale:changed', { locale: currentLocale });
|
||||
} catch (error) {
|
||||
console.warn(`[PluginLoader] Failed to sync locale for ${pluginName}:`, error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 卸载单个插件
|
||||
*/
|
||||
private async unloadPlugin(pluginName: string, pluginManager: EditorPluginManager): Promise<void> {
|
||||
try {
|
||||
await pluginManager.uninstallEditor(pluginName);
|
||||
this.loadedPluginNames.delete(pluginName);
|
||||
console.log(`[PluginLoader] Unloaded: ${pluginName}`);
|
||||
} catch (error) {
|
||||
console.error(`[PluginLoader] Failed to unload ${pluginName}:`, error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 卸载所有已加载的插件
|
||||
*/
|
||||
async unloadProjectPlugins(pluginManager: EditorPluginManager): Promise<void> {
|
||||
for (const pluginName of this.loadedPluginNames) {
|
||||
try {
|
||||
await pluginManager.uninstallEditor(pluginName);
|
||||
} catch (error) {
|
||||
console.error(`[PluginLoader] Failed to unload plugin ${pluginName}:`, error);
|
||||
}
|
||||
await this.unloadPlugin(pluginName, pluginManager);
|
||||
}
|
||||
|
||||
// 清除Vite模块缓存(如果HMR可用)
|
||||
this.invalidateModuleCache();
|
||||
|
||||
this.loadedPluginNames.clear();
|
||||
this.loadedModuleUrls.clear();
|
||||
}
|
||||
|
||||
private invalidateModuleCache(): void {
|
||||
try {
|
||||
// 尝试使用Vite HMR API无效化模块
|
||||
if (import.meta.hot) {
|
||||
import.meta.hot.invalidate();
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn('[PluginLoader] Failed to invalidate module cache:', error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取已加载的插件名称列表
|
||||
*/
|
||||
getLoadedPluginNames(): string[] {
|
||||
return Array.from(this.loadedPluginNames);
|
||||
}
|
||||
}
|
||||
|
||||
declare global {
|
||||
interface ImportMeta {
|
||||
hot?: {
|
||||
invalidate(): void;
|
||||
accept(callback?: () => void): void;
|
||||
dispose(callback: () => void): void;
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -21,6 +21,10 @@ export class TauriDialogService implements IDialogExtended {
|
||||
private showConfirmCallback?: (data: ConfirmDialogData) => void;
|
||||
private locale: string = 'zh';
|
||||
|
||||
dispose(): void {
|
||||
this.showConfirmCallback = undefined;
|
||||
}
|
||||
|
||||
setConfirmCallback(callback: (data: ConfirmDialogData) => void): void {
|
||||
this.showConfirmCallback = callback;
|
||||
}
|
||||
|
||||
@@ -1,9 +1,13 @@
|
||||
import { singleton } from 'tsyringe';
|
||||
import { invoke } from '@tauri-apps/api/core';
|
||||
import { invoke, convertFileSrc } from '@tauri-apps/api/core';
|
||||
import type { IFileSystem, FileEntry } from '@esengine/editor-core';
|
||||
|
||||
@singleton()
|
||||
export class TauriFileSystemService implements IFileSystem {
|
||||
dispose(): void {
|
||||
// No cleanup needed
|
||||
}
|
||||
|
||||
async readFile(path: string): Promise<string> {
|
||||
return await invoke<string>('read_file_content', { path });
|
||||
}
|
||||
@@ -49,4 +53,8 @@ export class TauriFileSystemService implements IFileSystem {
|
||||
async scanFiles(basePath: string, pattern: string): Promise<string[]> {
|
||||
return await invoke<string[]>('scan_files', { basePath, pattern });
|
||||
}
|
||||
|
||||
convertToAssetUrl(filePath: string): string {
|
||||
return convertFileSrc(filePath);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -517,6 +517,17 @@
|
||||
color: var(--color-accent);
|
||||
}
|
||||
|
||||
.property-asset-btn-create {
|
||||
color: #4ade80;
|
||||
font-weight: bold;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.property-asset-btn-create:hover {
|
||||
background: rgba(74, 222, 128, 0.15);
|
||||
color: #4ade80;
|
||||
}
|
||||
|
||||
.property-label-row {
|
||||
flex: 0 0 40%;
|
||||
display: flex;
|
||||
|
||||
@@ -1,36 +1,60 @@
|
||||
import { defineConfig } from 'vite';
|
||||
import { defineConfig, Plugin } from 'vite';
|
||||
import react from '@vitejs/plugin-react-swc';
|
||||
import wasm from 'vite-plugin-wasm';
|
||||
import topLevelAwait from 'vite-plugin-top-level-await';
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
|
||||
const host = process.env.TAURI_DEV_HOST;
|
||||
function copyPluginModulesPlugin(): Plugin {
|
||||
const modulePaths = [
|
||||
{ name: 'editor-runtime', path: path.resolve(__dirname, '../editor-runtime/dist') },
|
||||
{ name: 'behavior-tree', path: path.resolve(__dirname, '../behavior-tree/dist') },
|
||||
];
|
||||
|
||||
const userProjectPathMap = new Map<string, string>();
|
||||
const editorPackageMapping = new Map<string, string>();
|
||||
const editorPackageVersions = new Map<string, string>();
|
||||
const wasmPackages: string[] = []; // Auto-detected WASM packages
|
||||
return {
|
||||
name: 'copy-plugin-modules',
|
||||
writeBundle(options) {
|
||||
const outDir = options.dir || 'dist';
|
||||
const assetsDir = path.join(outDir, 'assets');
|
||||
|
||||
if (!fs.existsSync(assetsDir)) {
|
||||
fs.mkdirSync(assetsDir, { recursive: true });
|
||||
}
|
||||
|
||||
for (const mod of modulePaths) {
|
||||
if (!fs.existsSync(mod.path)) {
|
||||
console.warn(`[copy-plugin-modules] ${mod.name} dist not found: ${mod.path}`);
|
||||
continue;
|
||||
}
|
||||
const files = fs.readdirSync(mod.path);
|
||||
for (const file of files) {
|
||||
if (file.endsWith('.js')) {
|
||||
const src = path.join(mod.path, file);
|
||||
const dest = path.join(assetsDir, file);
|
||||
fs.copyFileSync(src, dest);
|
||||
console.log(`[copy-plugin-modules] Copied ${file}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
const host = process.env.TAURI_DEV_HOST;
|
||||
const wasmPackages: string[] = [];
|
||||
|
||||
/**
|
||||
* Check if a package directory contains WASM files (non-recursive, only check root and pkg folder).
|
||||
* 检查包目录是否包含WASM文件(非递归,只检查根目录和pkg文件夹)。
|
||||
* 检查包目录是否包含 WASM 文件
|
||||
*/
|
||||
function hasWasmFiles(dirPath: string): boolean {
|
||||
try {
|
||||
const files = fs.readdirSync(dirPath);
|
||||
for (const file of files) {
|
||||
// Only check .wasm files in root or pkg folder
|
||||
if (file.endsWith('.wasm')) {
|
||||
return true;
|
||||
}
|
||||
// Only check pkg folder (common wasm-pack output)
|
||||
if (file.endsWith('.wasm')) return true;
|
||||
if (file === 'pkg') {
|
||||
const pkgPath = path.join(dirPath, file);
|
||||
const pkgFiles = fs.readdirSync(pkgPath);
|
||||
if (pkgFiles.some(f => f.endsWith('.wasm'))) {
|
||||
return true;
|
||||
}
|
||||
if (pkgFiles.some(f => f.endsWith('.wasm'))) return true;
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
@@ -39,11 +63,12 @@ function hasWasmFiles(dirPath: string): boolean {
|
||||
return false;
|
||||
}
|
||||
|
||||
function loadEditorPackages() {
|
||||
/**
|
||||
* 扫描 packages 目录检测 WASM 包
|
||||
*/
|
||||
function detectWasmPackages() {
|
||||
const packagesDir = path.resolve(__dirname, '..');
|
||||
if (!fs.existsSync(packagesDir)) {
|
||||
return;
|
||||
}
|
||||
if (!fs.existsSync(packagesDir)) return;
|
||||
|
||||
const packageDirs = fs.readdirSync(packagesDir).filter(dir => {
|
||||
const stat = fs.statSync(path.join(packagesDir, dir));
|
||||
@@ -56,69 +81,51 @@ function loadEditorPackages() {
|
||||
try {
|
||||
const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf-8'));
|
||||
const packageName = packageJson.name;
|
||||
|
||||
if (packageName && packageName.startsWith('@esengine/')) {
|
||||
const mainFile = packageJson.module || packageJson.main;
|
||||
if (mainFile) {
|
||||
const entryPath = path.join(packagesDir, dir, mainFile);
|
||||
if (fs.existsSync(entryPath)) {
|
||||
editorPackageMapping.set(packageName, entryPath);
|
||||
}
|
||||
}
|
||||
if (packageJson.version) {
|
||||
editorPackageVersions.set(packageName, packageJson.version);
|
||||
}
|
||||
}
|
||||
|
||||
// Check for WASM files and add to wasmPackages
|
||||
// 检查WASM文件并添加到wasmPackages
|
||||
const packageDir = path.join(packagesDir, dir);
|
||||
|
||||
if (packageName && hasWasmFiles(packageDir)) {
|
||||
wasmPackages.push(packageName);
|
||||
console.log(`[Vite] Detected WASM package: ${packageName}`);
|
||||
}
|
||||
} catch (e) {
|
||||
console.error(`[Vite] Failed to read package.json for ${dir}:`, e);
|
||||
} catch {
|
||||
// Ignore errors
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Also scan node_modules for WASM packages
|
||||
// 也扫描node_modules中的WASM包
|
||||
// 扫描 node_modules
|
||||
const nodeModulesDir = path.resolve(__dirname, 'node_modules');
|
||||
if (fs.existsSync(nodeModulesDir)) {
|
||||
scanNodeModulesForWasm(nodeModulesDir);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Scan node_modules for WASM packages.
|
||||
* 扫描node_modules中的WASM包。
|
||||
*/
|
||||
function scanNodeModulesForWasm(nodeModulesDir: string) {
|
||||
try {
|
||||
const entries = fs.readdirSync(nodeModulesDir);
|
||||
for (const entry of entries) {
|
||||
// Skip .pnpm and other hidden/internal directories
|
||||
if (entry.startsWith('.')) continue;
|
||||
|
||||
const entryPath = path.join(nodeModulesDir, entry);
|
||||
const stat = fs.statSync(entryPath);
|
||||
|
||||
if (!stat.isDirectory()) continue;
|
||||
|
||||
// Handle scoped packages (@scope/package)
|
||||
if (entry.startsWith('@')) {
|
||||
const scopedPackages = fs.readdirSync(entryPath);
|
||||
for (const scopedPkg of scopedPackages) {
|
||||
const scopedPath = path.join(entryPath, scopedPkg);
|
||||
const scopedStat = fs.statSync(scopedPath);
|
||||
if (scopedStat.isDirectory()) {
|
||||
checkAndAddWasmPackage(scopedPath, `${entry}/${scopedPkg}`);
|
||||
if (fs.statSync(scopedPath).isDirectory()) {
|
||||
if (!wasmPackages.includes(`${entry}/${scopedPkg}`) && hasWasmFiles(scopedPath)) {
|
||||
wasmPackages.push(`${entry}/${scopedPkg}`);
|
||||
console.log(`[Vite] Detected WASM package in node_modules: ${entry}/${scopedPkg}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
checkAndAddWasmPackage(entryPath, entry);
|
||||
if (!wasmPackages.includes(entry) && hasWasmFiles(entryPath)) {
|
||||
wasmPackages.push(entry);
|
||||
console.log(`[Vite] Detected WASM package in node_modules: ${entry}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
@@ -126,615 +133,7 @@ function scanNodeModulesForWasm(nodeModulesDir: string) {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a package has WASM files and add to wasmPackages.
|
||||
* 检查包是否有WASM文件并添加到wasmPackages。
|
||||
*/
|
||||
function checkAndAddWasmPackage(packagePath: string, packageName: string) {
|
||||
// Skip if already added
|
||||
if (wasmPackages.includes(packageName)) return;
|
||||
|
||||
if (hasWasmFiles(packagePath)) {
|
||||
wasmPackages.push(packageName);
|
||||
console.log(`[Vite] Detected WASM package in node_modules: ${packageName}`);
|
||||
}
|
||||
}
|
||||
|
||||
loadEditorPackages();
|
||||
|
||||
const userProjectPlugin = () => ({
|
||||
name: 'user-project-middleware',
|
||||
resolveId(id: string, importer?: string) {
|
||||
if (id.startsWith('/@user-project/')) {
|
||||
return id;
|
||||
}
|
||||
|
||||
// 处理从 /@user-project/ 模块导入的相对路径
|
||||
if (importer && importer.startsWith('/@user-project/')) {
|
||||
if (id.startsWith('./') || id.startsWith('../')) {
|
||||
// 移除importer中的查询参数
|
||||
let cleanImporter = importer;
|
||||
const queryIndex = importer.indexOf('?');
|
||||
if (queryIndex !== -1) {
|
||||
cleanImporter = importer.substring(0, queryIndex);
|
||||
}
|
||||
const importerDir = path.dirname(cleanImporter.substring('/@user-project'.length));
|
||||
let resolvedPath = path.join(importerDir, id);
|
||||
resolvedPath = resolvedPath.replace(/\\/g, '/');
|
||||
|
||||
// 尝试添加扩展名
|
||||
let projectPath: string | null = null;
|
||||
for (const [, p] of userProjectPathMap) {
|
||||
projectPath = p;
|
||||
break;
|
||||
}
|
||||
|
||||
if (projectPath) {
|
||||
const possibleExtensions = ['', '.ts', '.tsx', '.js', '.jsx', '/index.ts', '/index.js'];
|
||||
for (const ext of possibleExtensions) {
|
||||
const testPath = path.join(projectPath, resolvedPath + ext);
|
||||
if (fs.existsSync(testPath) && !fs.statSync(testPath).isDirectory()) {
|
||||
return '/@user-project' + (resolvedPath + ext).replace(/\\/g, '/');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return '/@user-project' + resolvedPath;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
},
|
||||
load(id: string) {
|
||||
if (id.startsWith('/@user-project/')) {
|
||||
// 移除查询参数(用于缓存失效)
|
||||
let cleanId = id;
|
||||
const queryIndex = id.indexOf('?');
|
||||
if (queryIndex !== -1) {
|
||||
cleanId = id.substring(0, queryIndex);
|
||||
}
|
||||
|
||||
const relativePath = decodeURIComponent(cleanId.substring('/@user-project'.length));
|
||||
|
||||
let projectPath: string | null = null;
|
||||
for (const [, p] of userProjectPathMap) {
|
||||
projectPath = p;
|
||||
break;
|
||||
}
|
||||
|
||||
if (!projectPath) {
|
||||
throw new Error('Project path not set. Please open a project first.');
|
||||
}
|
||||
|
||||
const filePath = path.join(projectPath, relativePath);
|
||||
|
||||
if (!fs.existsSync(filePath)) {
|
||||
throw new Error(`File not found: ${filePath}`);
|
||||
}
|
||||
|
||||
if (fs.statSync(filePath).isDirectory()) {
|
||||
throw new Error(`Path is a directory: ${filePath}`);
|
||||
}
|
||||
|
||||
let content = fs.readFileSync(filePath, 'utf-8');
|
||||
|
||||
editorPackageMapping.forEach((srcPath, packageName) => {
|
||||
const escapedPackageName = packageName.replace(/\//g, '\\/');
|
||||
const regex = new RegExp(`from\\s+['"]${escapedPackageName}['"]`, 'g');
|
||||
content = content.replace(
|
||||
regex,
|
||||
`from "/@fs/${srcPath.replace(/\\/g, '/')}"`
|
||||
);
|
||||
});
|
||||
|
||||
// 直接返回源码,让 Vite 的转换管道处理
|
||||
// Vite 已经正确配置了 TypeScript 和装饰器的转换
|
||||
return content;
|
||||
}
|
||||
return null;
|
||||
},
|
||||
configureServer(server: any) {
|
||||
server.middlewares.use(async (req: any, res: any, next: any) => {
|
||||
|
||||
if (req.url === '/@ecs-framework-shim') {
|
||||
res.setHeader('Content-Type', 'application/javascript; charset=utf-8');
|
||||
res.setHeader('Access-Control-Allow-Origin', '*');
|
||||
res.end('export * from "/@fs/' + path.resolve(__dirname, '../core/src/index.ts').replace(/\\/g, '/') + '";');
|
||||
return;
|
||||
}
|
||||
|
||||
if (req.url === '/@user-project-set-path') {
|
||||
let body = '';
|
||||
req.on('data', (chunk: any) => {
|
||||
body += chunk.toString();
|
||||
});
|
||||
req.on('end', () => {
|
||||
try {
|
||||
const { path: projectPath } = JSON.parse(body);
|
||||
userProjectPathMap.set('current', projectPath);
|
||||
res.statusCode = 200;
|
||||
res.end('OK');
|
||||
} catch (err) {
|
||||
res.statusCode = 400;
|
||||
res.end('Invalid request');
|
||||
}
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (req.url === '/@plugin-generator') {
|
||||
let body = '';
|
||||
req.on('data', (chunk: any) => {
|
||||
body += chunk.toString();
|
||||
});
|
||||
req.on('end', async () => {
|
||||
try {
|
||||
const { pluginName, pluginVersion, outputPath, includeExample } = JSON.parse(body);
|
||||
|
||||
const pluginPath = path.join(outputPath, pluginName);
|
||||
|
||||
if (fs.existsSync(pluginPath)) {
|
||||
res.statusCode = 400;
|
||||
res.end(JSON.stringify({ error: 'Plugin directory already exists' }));
|
||||
return;
|
||||
}
|
||||
|
||||
fs.mkdirSync(pluginPath, { recursive: true });
|
||||
fs.mkdirSync(path.join(pluginPath, 'src'), { recursive: true });
|
||||
if (includeExample) {
|
||||
fs.mkdirSync(path.join(pluginPath, 'src', 'nodes'), { recursive: true });
|
||||
}
|
||||
|
||||
const coreVersion = editorPackageVersions.get('@esengine/ecs-framework') || '2.2.8';
|
||||
const editorCoreVersion = editorPackageVersions.get('@esengine/editor-core') || '1.0.0';
|
||||
const behaviorTreeVersion = editorPackageVersions.get('@esengine/behavior-tree') || '1.0.0';
|
||||
|
||||
const packageJson = {
|
||||
name: pluginName,
|
||||
version: pluginVersion,
|
||||
description: `Behavior tree plugin for ${pluginName}`,
|
||||
main: 'dist/index.js',
|
||||
module: 'dist/index.js',
|
||||
types: 'dist/index.d.ts',
|
||||
exports: {
|
||||
'.': {
|
||||
types: './dist/index.d.ts',
|
||||
import: './dist/index.js',
|
||||
development: {
|
||||
types: './src/index.ts',
|
||||
import: './src/index.ts'
|
||||
}
|
||||
}
|
||||
},
|
||||
scripts: {
|
||||
clean: 'rimraf bin dist tsconfig.tsbuildinfo',
|
||||
prebuild: 'npm run clean',
|
||||
build: 'npm run build:tsc && npm run copy:css && npm run build:rollup',
|
||||
'build:tsc': 'tsc',
|
||||
'copy:css': 'node scripts/copy-css.js',
|
||||
'build:rollup': 'rollup -c',
|
||||
dev: 'rollup -c -w',
|
||||
watch: 'tsc --watch'
|
||||
},
|
||||
peerDependencies: {
|
||||
'@esengine/ecs-framework': `^${coreVersion}`,
|
||||
'@esengine/editor-core': `^${editorCoreVersion}`
|
||||
},
|
||||
dependencies: {
|
||||
'@esengine/behavior-tree': `^${behaviorTreeVersion}`
|
||||
},
|
||||
devDependencies: {
|
||||
'typescript': '^5.8.3',
|
||||
'@rollup/plugin-commonjs': '^28.0.1',
|
||||
'@rollup/plugin-node-resolve': '^15.3.0',
|
||||
'rollup': '^4.28.1',
|
||||
'rollup-plugin-copy': '^3.5.0',
|
||||
'rollup-plugin-dts': '^6.1.1',
|
||||
'rollup-plugin-postcss': '^4.0.2',
|
||||
'rimraf': '^6.0.1'
|
||||
}
|
||||
};
|
||||
fs.writeFileSync(
|
||||
path.join(pluginPath, 'package.json'),
|
||||
JSON.stringify(packageJson, null, 2)
|
||||
);
|
||||
|
||||
const tsconfig = {
|
||||
compilerOptions: {
|
||||
target: 'ES2020',
|
||||
module: 'ESNext',
|
||||
moduleResolution: 'node',
|
||||
declaration: true,
|
||||
outDir: './dist',
|
||||
strict: true,
|
||||
esModuleInterop: true,
|
||||
skipLibCheck: true,
|
||||
forceConsistentCasingInFileNames: true,
|
||||
experimentalDecorators: true,
|
||||
emitDecoratorMetadata: true
|
||||
},
|
||||
include: ['src/**/*'],
|
||||
exclude: ['node_modules', 'dist']
|
||||
};
|
||||
fs.writeFileSync(
|
||||
path.join(pluginPath, 'tsconfig.json'),
|
||||
JSON.stringify(tsconfig, null, 2)
|
||||
);
|
||||
|
||||
const pluginInstanceName = `${pluginName.replace(/-/g, '')}Plugin`;
|
||||
|
||||
const indexTs = includeExample
|
||||
? `import './nodes/ExampleAction';
|
||||
|
||||
export { ${pluginInstanceName} } from './plugin';
|
||||
export * from './nodes/ExampleAction';
|
||||
|
||||
// 默认导出插件实例
|
||||
import { ${pluginInstanceName} as pluginInstance } from './plugin';
|
||||
export default pluginInstance;
|
||||
`
|
||||
: `export { ${pluginInstanceName} } from './plugin';
|
||||
|
||||
// 默认导出插件实例
|
||||
import { ${pluginInstanceName} as pluginInstance } from './plugin';
|
||||
export default pluginInstance;
|
||||
`;
|
||||
fs.writeFileSync(path.join(pluginPath, 'src', 'index.ts'), indexTs);
|
||||
|
||||
const pluginTs = `import type { IEditorPlugin } from '@esengine/editor-core';
|
||||
import { EditorPluginCategory } from '@esengine/editor-core';
|
||||
import type { Core, ServiceContainer } from '@esengine/ecs-framework';
|
||||
import { NodeTemplates } from '@esengine/behavior-tree';
|
||||
import type { NodeTemplate } from '@esengine/behavior-tree';
|
||||
import { t, setLocale } from './locales';
|
||||
|
||||
export class ${pluginName.split('-').map(s => s.charAt(0).toUpperCase() + s.slice(1)).join('')}Plugin implements IEditorPlugin {
|
||||
readonly name = '${pluginName}';
|
||||
readonly version = '${pluginVersion}';
|
||||
readonly category = EditorPluginCategory.Tool;
|
||||
|
||||
get displayName(): string {
|
||||
return t('plugin.name');
|
||||
}
|
||||
|
||||
get description(): string {
|
||||
return t('plugin.description');
|
||||
}
|
||||
|
||||
setLocale(locale: string): void {
|
||||
setLocale(locale);
|
||||
}
|
||||
|
||||
async install(core: Core, services: ServiceContainer): Promise<void> {
|
||||
console.log('[${pluginName}] Plugin installed');
|
||||
}
|
||||
|
||||
async uninstall(): Promise<void> {
|
||||
console.log('[${pluginName}] Plugin uninstalled');
|
||||
}
|
||||
|
||||
getNodeTemplates(): NodeTemplate[] {
|
||||
const templates = NodeTemplates.getAllTemplates();
|
||||
return templates.map(template => ({
|
||||
...template,
|
||||
displayName: t(template.displayName),
|
||||
description: t(template.description),
|
||||
properties: template.properties?.map(prop => ({
|
||||
...prop,
|
||||
label: t(prop.label),
|
||||
description: prop.description ? t(prop.description) : undefined
|
||||
}))
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
export const ${pluginName.replace(/-/g, '')}Plugin = new ${pluginName.split('-').map(s => s.charAt(0).toUpperCase() + s.slice(1)).join('')}Plugin();
|
||||
`;
|
||||
fs.writeFileSync(path.join(pluginPath, 'src', 'plugin.ts'), pluginTs);
|
||||
|
||||
const localesDir = path.join(pluginPath, 'src', 'locales');
|
||||
if (!fs.existsSync(localesDir)) {
|
||||
fs.mkdirSync(localesDir, { recursive: true });
|
||||
}
|
||||
|
||||
const localesIndexTs = `export type LocaleKey = 'zh' | 'en';
|
||||
|
||||
export const translations: Record<LocaleKey, Record<string, string>> = {
|
||||
zh: {
|
||||
'plugin.name': '${pluginName}',
|
||||
'plugin.description': '${pluginName} 行为树插件',
|
||||
'ExampleAction.name': '示例动作',
|
||||
'ExampleAction.description': '这是一个示例动作节点',
|
||||
'ExampleAction.message.label': '消息内容',
|
||||
'ExampleAction.message.description': '要打印的消息'
|
||||
},
|
||||
en: {
|
||||
'plugin.name': '${pluginName}',
|
||||
'plugin.description': 'Behavior tree plugin for ${pluginName}',
|
||||
'ExampleAction.name': 'Example Action',
|
||||
'ExampleAction.description': 'This is an example action node',
|
||||
'ExampleAction.message.label': 'Message',
|
||||
'ExampleAction.message.description': 'The message to print'
|
||||
}
|
||||
};
|
||||
|
||||
let currentLocale: LocaleKey = 'zh';
|
||||
|
||||
export function setLocale(locale: string) {
|
||||
currentLocale = (locale === 'en' ? 'en' : 'zh') as LocaleKey;
|
||||
}
|
||||
|
||||
export function t(key: string): string {
|
||||
return translations[currentLocale]?.[key] || translations['en']?.[key] || key;
|
||||
}
|
||||
`;
|
||||
fs.writeFileSync(path.join(localesDir, 'index.ts'), localesIndexTs);
|
||||
|
||||
if (includeExample) {
|
||||
const exampleActionTs = `import { TaskStatus, NodeType } from '@esengine/behavior-tree';
|
||||
import { INodeExecutor, NodeExecutionContext, BindingHelper, NodeExecutorMetadata } from '@esengine/behavior-tree';
|
||||
|
||||
/**
|
||||
* 示例动作执行器
|
||||
*/
|
||||
@NodeExecutorMetadata({
|
||||
implementationType: 'ExampleAction',
|
||||
nodeType: NodeType.Action,
|
||||
displayName: 'ExampleAction.name',
|
||||
description: 'ExampleAction.description',
|
||||
category: '自定义',
|
||||
configSchema: {
|
||||
message: {
|
||||
type: 'string',
|
||||
default: 'Hello from example action!',
|
||||
description: 'ExampleAction.message.description',
|
||||
supportBinding: true
|
||||
}
|
||||
}
|
||||
})
|
||||
export class ExampleAction implements INodeExecutor {
|
||||
execute(context: NodeExecutionContext): TaskStatus {
|
||||
const message = BindingHelper.getValue<string>(context, 'message', '');
|
||||
console.log('[ExampleAction]', message);
|
||||
return TaskStatus.Success;
|
||||
}
|
||||
}
|
||||
`;
|
||||
fs.writeFileSync(
|
||||
path.join(pluginPath, 'src', 'nodes', 'ExampleAction.ts'),
|
||||
exampleActionTs
|
||||
);
|
||||
}
|
||||
|
||||
const readme = `# ${pluginName}
|
||||
|
||||
Behavior tree plugin for ${pluginName}
|
||||
|
||||
## Installation
|
||||
|
||||
\`\`\`bash
|
||||
npm install
|
||||
npm run build
|
||||
\`\`\`
|
||||
|
||||
## Usage
|
||||
|
||||
在编辑器中加载此插件:
|
||||
|
||||
\`\`\`typescript
|
||||
import { ${pluginName.replace(/-/g, '')}Plugin } from '${pluginName}';
|
||||
import { EditorPluginManager } from '@esengine/editor-core';
|
||||
|
||||
// 在编辑器启动时注册插件
|
||||
const pluginManager = Core.services.resolve(EditorPluginManager);
|
||||
await pluginManager.installEditor(${pluginName.replace(/-/g, '')}Plugin);
|
||||
\`\`\`
|
||||
|
||||
## 多语言支持
|
||||
|
||||
本插件内置中英文多语言支持,使用简单的 i18n key 方式。
|
||||
|
||||
### 设置语言
|
||||
|
||||
\`\`\`typescript
|
||||
// 设置为中文
|
||||
${pluginName.replace(/-/g, '')}Plugin.setLocale('zh');
|
||||
|
||||
// 设置为英文
|
||||
${pluginName.replace(/-/g, '')}Plugin.setLocale('en');
|
||||
\`\`\`
|
||||
|
||||
### 翻译文件结构
|
||||
|
||||
在 \`src/locales/index.ts\` 中,使用扁平化的 key-value 结构:
|
||||
|
||||
\`\`\`typescript
|
||||
export const translations = {
|
||||
zh: {
|
||||
'plugin.name': '插件名称',
|
||||
'plugin.description': '插件描述',
|
||||
'NodeName.name': '节点显示名',
|
||||
'NodeName.description': '节点描述',
|
||||
'NodeName.property.label': '属性标签',
|
||||
'NodeName.property.description': '属性描述'
|
||||
},
|
||||
en: {
|
||||
'plugin.name': 'Plugin Name',
|
||||
// ...
|
||||
}
|
||||
};
|
||||
\`\`\`
|
||||
|
||||
### 在代码中使用
|
||||
|
||||
\`\`\`typescript
|
||||
import { TaskStatus, NodeType } from '@esengine/behavior-tree';
|
||||
import { INodeExecutor, NodeExecutionContext, BindingHelper, NodeExecutorMetadata } from '@esengine/behavior-tree';
|
||||
|
||||
@NodeExecutorMetadata({
|
||||
implementationType: 'YourNode',
|
||||
nodeType: NodeType.Action,
|
||||
displayName: 'YourNode.name',
|
||||
description: 'YourNode.description',
|
||||
category: '自定义',
|
||||
configSchema: {
|
||||
propertyName: {
|
||||
type: 'string',
|
||||
default: '',
|
||||
description: 'YourNode.propertyName.description',
|
||||
supportBinding: true
|
||||
}
|
||||
}
|
||||
})
|
||||
export class YourNode implements INodeExecutor {
|
||||
execute(context: NodeExecutionContext): TaskStatus {
|
||||
const propertyName = BindingHelper.getValue<string>(context, 'propertyName', '');
|
||||
// 执行逻辑
|
||||
return TaskStatus.Success;
|
||||
}
|
||||
}
|
||||
\`\`\`
|
||||
|
||||
## 目录结构
|
||||
|
||||
\`\`\`
|
||||
${pluginName}/
|
||||
├── src/
|
||||
│ ├── locales/ # 多语言文件
|
||||
│ │ └── index.ts
|
||||
│ ├── nodes/ # 行为树节点
|
||||
│ │ └── ExampleAction.ts
|
||||
│ ├── plugin.ts # 插件主类
|
||||
│ └── index.ts # 导出入口
|
||||
├── package.json
|
||||
├── tsconfig.json
|
||||
└── README.md
|
||||
\`\`\`
|
||||
`;
|
||||
fs.writeFileSync(path.join(pluginPath, 'README.md'), readme);
|
||||
|
||||
// 创建 scripts 目录并生成 copy-css.js
|
||||
const scriptsDir = path.join(pluginPath, 'scripts');
|
||||
fs.mkdirSync(scriptsDir, { recursive: true });
|
||||
|
||||
const copyCssJs = `import { readdirSync, statSync, copyFileSync, mkdirSync } from 'fs';
|
||||
import { join, dirname, relative } from 'path';
|
||||
|
||||
function copyCSS(srcDir, destDir) {
|
||||
const files = readdirSync(srcDir);
|
||||
|
||||
for (const file of files) {
|
||||
const srcPath = join(srcDir, file);
|
||||
const stat = statSync(srcPath);
|
||||
|
||||
if (stat.isDirectory()) {
|
||||
copyCSS(srcPath, destDir);
|
||||
} else if (file.endsWith('.css')) {
|
||||
const relativePath = relative('src', srcPath);
|
||||
const destPath = join(destDir, relativePath);
|
||||
|
||||
mkdirSync(dirname(destPath), { recursive: true });
|
||||
copyFileSync(srcPath, destPath);
|
||||
console.log(\`Copied: \${relativePath}\`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
copyCSS('src', 'bin');
|
||||
console.log('CSS files copied successfully!');
|
||||
`;
|
||||
fs.writeFileSync(path.join(scriptsDir, 'copy-css.js'), copyCssJs);
|
||||
|
||||
// 生成 rollup.config.cjs
|
||||
const rollupConfig = `const resolve = require('@rollup/plugin-node-resolve');
|
||||
const commonjs = require('@rollup/plugin-commonjs');
|
||||
const dts = require('rollup-plugin-dts').default;
|
||||
const postcss = require('rollup-plugin-postcss');
|
||||
|
||||
const external = [
|
||||
'react',
|
||||
'react/jsx-runtime',
|
||||
'zustand',
|
||||
'zustand/middleware',
|
||||
'lucide-react',
|
||||
'@esengine/ecs-framework',
|
||||
'@esengine/editor-core',
|
||||
'@esengine/behavior-tree',
|
||||
'tsyringe',
|
||||
'@tauri-apps/api/core',
|
||||
'@tauri-apps/plugin-dialog'
|
||||
];
|
||||
|
||||
module.exports = [
|
||||
// ES模块构建
|
||||
{
|
||||
input: 'bin/index.js',
|
||||
output: {
|
||||
file: 'dist/index.js',
|
||||
format: 'es',
|
||||
sourcemap: true,
|
||||
exports: 'named',
|
||||
inlineDynamicImports: true
|
||||
},
|
||||
plugins: [
|
||||
wasm(),
|
||||
topLevelAwait(),
|
||||
resolve({
|
||||
extensions: ['.js', '.jsx']
|
||||
}),
|
||||
postcss({
|
||||
inject: true,
|
||||
minimize: false
|
||||
}),
|
||||
commonjs()
|
||||
],
|
||||
external,
|
||||
onwarn(warning, warn) {
|
||||
if (warning.code === 'CIRCULAR_DEPENDENCY' || warning.code === 'THIS_IS_UNDEFINED') {
|
||||
return;
|
||||
}
|
||||
warn(warning);
|
||||
}
|
||||
},
|
||||
|
||||
// 类型定义构建
|
||||
{
|
||||
input: 'bin/index.d.ts',
|
||||
output: {
|
||||
file: 'dist/index.d.ts',
|
||||
format: 'es'
|
||||
},
|
||||
plugins: [
|
||||
wasm(),
|
||||
topLevelAwait(),
|
||||
dts({
|
||||
respectExternal: true
|
||||
})
|
||||
],
|
||||
external: [
|
||||
...external,
|
||||
/\\.css$/
|
||||
]
|
||||
}
|
||||
];
|
||||
`;
|
||||
fs.writeFileSync(path.join(pluginPath, 'rollup.config.cjs'), rollupConfig);
|
||||
|
||||
res.statusCode = 200;
|
||||
res.end(JSON.stringify({ success: true, path: pluginPath }));
|
||||
} catch (err: any) {
|
||||
console.error('[Vite] Failed to generate plugin:', err);
|
||||
res.statusCode = 500;
|
||||
res.end(JSON.stringify({ error: err.message }));
|
||||
}
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
next();
|
||||
});
|
||||
}
|
||||
});
|
||||
detectWasmPackages();
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [
|
||||
@@ -743,7 +142,7 @@ export default defineConfig({
|
||||
...react({
|
||||
tsDecorators: true,
|
||||
}),
|
||||
userProjectPlugin() as any
|
||||
copyPluginModulesPlugin(),
|
||||
],
|
||||
clearScreen: false,
|
||||
server: {
|
||||
@@ -767,11 +166,12 @@ export default defineConfig({
|
||||
minify: !process.env.TAURI_DEBUG ? 'esbuild' : false,
|
||||
sourcemap: !!process.env.TAURI_DEBUG,
|
||||
},
|
||||
esbuild: {
|
||||
// 保留类名和函数名,用于跨包插件服务匹配
|
||||
keepNames: true,
|
||||
},
|
||||
optimizeDeps: {
|
||||
// Pre-bundle common dependencies to avoid runtime re-optimization | 预打包常用依赖以避免运行时重新优化
|
||||
include: ['tslib', 'react', 'react-dom', 'zustand', 'lucide-react'],
|
||||
// Exclude WASM packages from pre-bundling | 排除 WASM 包不进行预打包
|
||||
// Add user WASM plugins to wasmPackages array at top of file | 将用户 WASM 插件添加到文件顶部的 wasmPackages 数组
|
||||
exclude: wasmPackages,
|
||||
},
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user