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:
YHH
2025-11-25 22:23:19 +08:00
committed by GitHub
parent 551ca7805d
commit 3fb6f919f8
166 changed files with 54691 additions and 8674 deletions

View File

@@ -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();

View File

@@ -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 {

View File

@@ -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 {
}
}
}
}
}

View File

@@ -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);

View File

@@ -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;
}
}

View File

@@ -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';

View File

@@ -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);

View File

@@ -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 => ({

View File

@@ -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) => {

View File

@@ -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;

View File

@@ -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) => {

View File

@@ -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>
);
}

View File

@@ -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" />

View File

@@ -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);

View File

@@ -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;
}

View File

@@ -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();

View 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>
);
}

View File

@@ -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;

View File

@@ -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

View File

@@ -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>

View 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);
}

View File

@@ -0,0 +1,9 @@
/**
* Editor Gizmos
* 编辑器 Gizmos
*
* Gizmo implementations for built-in components.
* 内置组件的 Gizmo 实现。
*/
export { registerSpriteGizmo } from './SpriteGizmo';

View File

@@ -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}
/>
);
}

View 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();

View File

@@ -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', {});
}

View 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();

View File

@@ -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;
};
}
}

View File

@@ -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;
}

View File

@@ -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);
}
}

View File

@@ -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;