feat: 集成Rust WASM渲染引擎与TypeScript ECS框架 (#228)
* feat: 集成Rust WASM渲染引擎与TypeScript ECS框架 * feat: 增强编辑器UI功能与跨平台支持 * fix: 修复CI测试和类型检查问题 * fix: 修复CI问题并提高测试覆盖率 * fix: 修复CI问题并提高测试覆盖率
This commit is contained in:
@@ -14,16 +14,18 @@ import {
|
||||
ProjectService,
|
||||
CompilerRegistry,
|
||||
InspectorRegistry,
|
||||
INotification
|
||||
INotification,
|
||||
CommandManager
|
||||
} from '@esengine/editor-core';
|
||||
import type { IDialogExtended } from './services/TauriDialogService';
|
||||
import { GlobalBlackboardService } from '@esengine/behavior-tree';
|
||||
import { ServiceRegistry, PluginInstaller, useDialogStore } from './app/managers';
|
||||
import { StartupPage } from './components/StartupPage';
|
||||
import { SceneHierarchy } from './components/SceneHierarchy';
|
||||
import { Inspector } from './components/Inspector';
|
||||
import { Inspector } from './components/inspectors/Inspector';
|
||||
import { AssetBrowser } from './components/AssetBrowser';
|
||||
import { ConsolePanel } from './components/ConsolePanel';
|
||||
import { Viewport } from './components/Viewport';
|
||||
import { PluginManagerWindow } from './components/PluginManagerWindow';
|
||||
import { ProfilerWindow } from './components/ProfilerWindow';
|
||||
import { PortManager } from './components/PortManager';
|
||||
@@ -82,6 +84,7 @@ function App() {
|
||||
const [sceneManager, setSceneManager] = useState<SceneManagerService | null>(null);
|
||||
const [notification, setNotification] = useState<INotification | null>(null);
|
||||
const [dialog, setDialog] = useState<IDialogExtended | null>(null);
|
||||
const [commandManager] = useState(() => new CommandManager());
|
||||
const { t, locale, changeLocale } = useLocale();
|
||||
|
||||
// 同步 locale 到 TauriDialogService
|
||||
@@ -660,13 +663,13 @@ function App() {
|
||||
{
|
||||
id: 'scene-hierarchy',
|
||||
title: locale === 'zh' ? '场景层级' : 'Scene Hierarchy',
|
||||
content: <SceneHierarchy entityStore={entityStore} messageHub={messageHub} />,
|
||||
content: <SceneHierarchy entityStore={entityStore} messageHub={messageHub} commandManager={commandManager} />,
|
||||
closable: false
|
||||
},
|
||||
{
|
||||
id: 'inspector',
|
||||
title: locale === 'zh' ? '检视器' : 'Inspector',
|
||||
content: <Inspector entityStore={entityStore} messageHub={messageHub} inspectorRegistry={inspectorRegistry!} projectPath={currentProjectPath} />,
|
||||
content: <Inspector entityStore={entityStore} messageHub={messageHub} inspectorRegistry={inspectorRegistry!} projectPath={currentProjectPath} commandManager={commandManager} />,
|
||||
closable: false
|
||||
},
|
||||
{
|
||||
@@ -681,13 +684,19 @@ function App() {
|
||||
{
|
||||
id: 'scene-hierarchy',
|
||||
title: locale === 'zh' ? '场景层级' : 'Scene Hierarchy',
|
||||
content: <SceneHierarchy entityStore={entityStore} messageHub={messageHub} />,
|
||||
content: <SceneHierarchy entityStore={entityStore} messageHub={messageHub} commandManager={commandManager} />,
|
||||
closable: false
|
||||
},
|
||||
{
|
||||
id: 'viewport',
|
||||
title: locale === 'zh' ? '视口' : 'Viewport',
|
||||
content: <Viewport locale={locale} />,
|
||||
closable: false
|
||||
},
|
||||
{
|
||||
id: 'inspector',
|
||||
title: locale === 'zh' ? '检视器' : 'Inspector',
|
||||
content: <Inspector entityStore={entityStore} messageHub={messageHub} inspectorRegistry={inspectorRegistry!} projectPath={currentProjectPath} />,
|
||||
content: <Inspector entityStore={entityStore} messageHub={messageHub} inspectorRegistry={inspectorRegistry!} projectPath={currentProjectPath} commandManager={commandManager} />,
|
||||
closable: false
|
||||
},
|
||||
{
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
import { Entity, Component } from '@esengine/ecs-framework';
|
||||
import { MessageHub } from '@esengine/editor-core';
|
||||
import { BaseCommand } from '../BaseCommand';
|
||||
|
||||
/**
|
||||
* 添加组件命令
|
||||
*/
|
||||
export class AddComponentCommand extends BaseCommand {
|
||||
private component: Component | null = null;
|
||||
|
||||
constructor(
|
||||
private messageHub: MessageHub,
|
||||
private entity: Entity,
|
||||
private ComponentClass: new () => Component,
|
||||
private initialData?: Record<string, unknown>
|
||||
) {
|
||||
super();
|
||||
}
|
||||
|
||||
execute(): void {
|
||||
this.component = new this.ComponentClass();
|
||||
|
||||
// 应用初始数据
|
||||
if (this.initialData) {
|
||||
for (const [key, value] of Object.entries(this.initialData)) {
|
||||
(this.component as any)[key] = value;
|
||||
}
|
||||
}
|
||||
|
||||
this.entity.addComponent(this.component);
|
||||
|
||||
this.messageHub.publish('component:added', {
|
||||
entity: this.entity,
|
||||
component: this.component
|
||||
});
|
||||
}
|
||||
|
||||
undo(): void {
|
||||
if (!this.component) return;
|
||||
|
||||
this.entity.removeComponent(this.component);
|
||||
|
||||
this.messageHub.publish('component:removed', {
|
||||
entity: this.entity,
|
||||
componentType: this.ComponentClass.name
|
||||
});
|
||||
|
||||
this.component = null;
|
||||
}
|
||||
|
||||
getDescription(): string {
|
||||
return `添加组件: ${this.ComponentClass.name}`;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
import { Entity, Component } from '@esengine/ecs-framework';
|
||||
import { MessageHub } from '@esengine/editor-core';
|
||||
import { BaseCommand } from '../BaseCommand';
|
||||
|
||||
/**
|
||||
* 移除组件命令
|
||||
*/
|
||||
export class RemoveComponentCommand extends BaseCommand {
|
||||
private componentData: Record<string, unknown> = {};
|
||||
private ComponentClass: new () => Component;
|
||||
|
||||
constructor(
|
||||
private messageHub: MessageHub,
|
||||
private entity: Entity,
|
||||
private component: Component
|
||||
) {
|
||||
super();
|
||||
this.ComponentClass = component.constructor as new () => Component;
|
||||
|
||||
// 保存组件数据用于撤销
|
||||
for (const key of Object.keys(component)) {
|
||||
if (key !== 'entity' && key !== 'id') {
|
||||
this.componentData[key] = (component as any)[key];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
execute(): void {
|
||||
this.entity.removeComponent(this.component);
|
||||
|
||||
this.messageHub.publish('component:removed', {
|
||||
entity: this.entity,
|
||||
componentType: this.ComponentClass.name
|
||||
});
|
||||
}
|
||||
|
||||
undo(): void {
|
||||
const newComponent = new this.ComponentClass();
|
||||
|
||||
// 恢复数据
|
||||
for (const [key, value] of Object.entries(this.componentData)) {
|
||||
(newComponent as any)[key] = value;
|
||||
}
|
||||
|
||||
this.entity.addComponent(newComponent);
|
||||
this.component = newComponent;
|
||||
|
||||
this.messageHub.publish('component:added', {
|
||||
entity: this.entity,
|
||||
component: newComponent
|
||||
});
|
||||
}
|
||||
|
||||
getDescription(): string {
|
||||
return `移除组件: ${this.ComponentClass.name}`;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
import { Entity, Component } from '@esengine/ecs-framework';
|
||||
import { MessageHub } from '@esengine/editor-core';
|
||||
import { BaseCommand } from '../BaseCommand';
|
||||
import { ICommand } from '../ICommand';
|
||||
|
||||
/**
|
||||
* 更新组件属性命令
|
||||
*/
|
||||
export class UpdateComponentCommand extends BaseCommand {
|
||||
private oldValue: unknown;
|
||||
|
||||
constructor(
|
||||
private messageHub: MessageHub,
|
||||
private entity: Entity,
|
||||
private component: Component,
|
||||
private propertyName: string,
|
||||
private newValue: unknown
|
||||
) {
|
||||
super();
|
||||
this.oldValue = (component as any)[propertyName];
|
||||
}
|
||||
|
||||
execute(): void {
|
||||
(this.component as any)[this.propertyName] = this.newValue;
|
||||
|
||||
this.messageHub.publish('component:updated', {
|
||||
entity: this.entity,
|
||||
component: this.component,
|
||||
propertyName: this.propertyName,
|
||||
value: this.newValue
|
||||
});
|
||||
}
|
||||
|
||||
undo(): void {
|
||||
(this.component as any)[this.propertyName] = this.oldValue;
|
||||
|
||||
this.messageHub.publish('component:updated', {
|
||||
entity: this.entity,
|
||||
component: this.component,
|
||||
propertyName: this.propertyName,
|
||||
value: this.oldValue
|
||||
});
|
||||
}
|
||||
|
||||
getDescription(): string {
|
||||
return `更新 ${this.component.constructor.name}.${this.propertyName}`;
|
||||
}
|
||||
|
||||
canMergeWith(other: ICommand): boolean {
|
||||
if (!(other instanceof UpdateComponentCommand)) return false;
|
||||
|
||||
return (
|
||||
this.entity === other.entity &&
|
||||
this.component === other.component &&
|
||||
this.propertyName === other.propertyName
|
||||
);
|
||||
}
|
||||
|
||||
mergeWith(other: ICommand): ICommand {
|
||||
if (!(other instanceof UpdateComponentCommand)) {
|
||||
throw new Error('无法合并不同类型的命令');
|
||||
}
|
||||
|
||||
// 保留原始值,使用新命令的新值
|
||||
const merged = new UpdateComponentCommand(
|
||||
this.messageHub,
|
||||
this.entity,
|
||||
this.component,
|
||||
this.propertyName,
|
||||
other.newValue
|
||||
);
|
||||
merged.oldValue = this.oldValue;
|
||||
|
||||
return merged;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
export { AddComponentCommand } from './AddComponentCommand';
|
||||
export { RemoveComponentCommand } from './RemoveComponentCommand';
|
||||
export { UpdateComponentCommand } from './UpdateComponentCommand';
|
||||
@@ -0,0 +1,58 @@
|
||||
import { Core, Entity } from '@esengine/ecs-framework';
|
||||
import { EntityStoreService, MessageHub } from '@esengine/editor-core';
|
||||
import { BaseCommand } from '../BaseCommand';
|
||||
|
||||
/**
|
||||
* 创建实体命令
|
||||
*/
|
||||
export class CreateEntityCommand 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
|
||||
) {
|
||||
super();
|
||||
}
|
||||
|
||||
execute(): void {
|
||||
const scene = Core.scene;
|
||||
if (!scene) {
|
||||
throw new Error('场景未初始化');
|
||||
}
|
||||
|
||||
this.entity = scene.createEntity(this.entityName);
|
||||
this.entityId = this.entity.id;
|
||||
|
||||
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 });
|
||||
}
|
||||
|
||||
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 `创建实体: ${this.entityName}`;
|
||||
}
|
||||
|
||||
getCreatedEntity(): Entity | null {
|
||||
return this.entity;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
import { Core, Entity, Component } from '@esengine/ecs-framework';
|
||||
import { EntityStoreService, MessageHub } from '@esengine/editor-core';
|
||||
import { BaseCommand } from '../BaseCommand';
|
||||
|
||||
/**
|
||||
* 删除实体命令
|
||||
*/
|
||||
export class DeleteEntityCommand extends BaseCommand {
|
||||
private entityId: number;
|
||||
private entityName: string;
|
||||
private parentEntity: Entity | null;
|
||||
private components: Component[] = [];
|
||||
private childEntities: Entity[] = [];
|
||||
|
||||
constructor(
|
||||
private entityStore: EntityStoreService,
|
||||
private messageHub: MessageHub,
|
||||
private entity: Entity
|
||||
) {
|
||||
super();
|
||||
this.entityId = entity.id;
|
||||
this.entityName = entity.name;
|
||||
this.parentEntity = entity.parent;
|
||||
|
||||
// 保存组件状态用于撤销
|
||||
this.components = [...entity.components];
|
||||
// 保存子实体
|
||||
this.childEntities = [...entity.children];
|
||||
}
|
||||
|
||||
execute(): void {
|
||||
// 先移除子实体
|
||||
for (const child of this.childEntities) {
|
||||
this.entityStore.removeEntity(child);
|
||||
}
|
||||
|
||||
this.entityStore.removeEntity(this.entity);
|
||||
this.entity.destroy();
|
||||
|
||||
this.messageHub.publish('entity:removed', { entityId: this.entityId });
|
||||
}
|
||||
|
||||
undo(): void {
|
||||
const scene = Core.scene;
|
||||
if (!scene) {
|
||||
throw new Error('场景未初始化');
|
||||
}
|
||||
|
||||
// 重新创建实体
|
||||
const newEntity = scene.createEntity(this.entityName);
|
||||
|
||||
// 设置父实体
|
||||
if (this.parentEntity) {
|
||||
this.parentEntity.addChild(newEntity);
|
||||
}
|
||||
|
||||
// 恢复组件
|
||||
for (const component of this.components) {
|
||||
// 创建组件副本
|
||||
const ComponentClass = component.constructor as new () => Component;
|
||||
const newComponent = new ComponentClass();
|
||||
|
||||
// 复制属性
|
||||
for (const key of Object.keys(component)) {
|
||||
if (key !== 'entity' && key !== 'id') {
|
||||
(newComponent as any)[key] = (component as any)[key];
|
||||
}
|
||||
}
|
||||
|
||||
newEntity.addComponent(newComponent);
|
||||
}
|
||||
|
||||
// 恢复子实体
|
||||
for (const child of this.childEntities) {
|
||||
newEntity.addChild(child);
|
||||
this.entityStore.addEntity(child, newEntity);
|
||||
}
|
||||
|
||||
this.entityStore.addEntity(newEntity, this.parentEntity ?? undefined);
|
||||
this.entityStore.selectEntity(newEntity);
|
||||
|
||||
// 更新引用
|
||||
this.entity = newEntity;
|
||||
|
||||
this.messageHub.publish('entity:added', { entity: newEntity });
|
||||
}
|
||||
|
||||
getDescription(): string {
|
||||
return `删除实体: ${this.entityName}`;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
export { CreateEntityCommand } from './CreateEntityCommand';
|
||||
export { DeleteEntityCommand } from './DeleteEntityCommand';
|
||||
@@ -1,29 +1,37 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { Entity, Core } from '@esengine/ecs-framework';
|
||||
import { EntityStoreService, MessageHub, SceneManagerService } from '@esengine/editor-core';
|
||||
import { EntityStoreService, MessageHub, SceneManagerService, CommandManager } from '@esengine/editor-core';
|
||||
import { useLocale } from '../hooks/useLocale';
|
||||
import { Box, Layers, Wifi, Search, Plus, Trash2 } from 'lucide-react';
|
||||
import { Box, Layers, Wifi, Search, Plus, Trash2, Monitor, Globe } from 'lucide-react';
|
||||
import { ProfilerService, RemoteEntity } from '../services/ProfilerService';
|
||||
import { confirm } from '@tauri-apps/plugin-dialog';
|
||||
import { CreateEntityCommand, DeleteEntityCommand } from '../application/commands/entity';
|
||||
import '../styles/SceneHierarchy.css';
|
||||
|
||||
type ViewMode = 'local' | 'remote';
|
||||
|
||||
interface SceneHierarchyProps {
|
||||
entityStore: EntityStoreService;
|
||||
messageHub: MessageHub;
|
||||
commandManager: CommandManager;
|
||||
}
|
||||
|
||||
export function SceneHierarchy({ entityStore, messageHub }: SceneHierarchyProps) {
|
||||
export function SceneHierarchy({ entityStore, messageHub, commandManager }: SceneHierarchyProps) {
|
||||
const [entities, setEntities] = useState<Entity[]>([]);
|
||||
const [remoteEntities, setRemoteEntities] = useState<RemoteEntity[]>([]);
|
||||
const [isRemoteConnected, setIsRemoteConnected] = useState(false);
|
||||
const [viewMode, setViewMode] = useState<ViewMode>('local');
|
||||
const [selectedId, setSelectedId] = useState<number | null>(null);
|
||||
const [searchQuery, setSearchQuery] = useState('');
|
||||
const [sceneName, setSceneName] = useState<string>('Untitled');
|
||||
const [remoteSceneName, setRemoteSceneName] = useState<string | null>(null);
|
||||
const [sceneFilePath, setSceneFilePath] = useState<string | null>(null);
|
||||
const [isSceneModified, setIsSceneModified] = useState<boolean>(false);
|
||||
const [contextMenu, setContextMenu] = useState<{ x: number; y: number; entityId: number | null } | null>(null);
|
||||
const { t, locale } = useLocale();
|
||||
|
||||
const isShowingRemote = viewMode === 'remote' && isRemoteConnected;
|
||||
|
||||
// Subscribe to scene changes
|
||||
useEffect(() => {
|
||||
const sceneManager = Core.services.resolve(SceneManagerService);
|
||||
@@ -182,14 +190,15 @@ export function SceneHierarchy({ entityStore, messageHub }: SceneHierarchyProps)
|
||||
};
|
||||
|
||||
const handleCreateEntity = () => {
|
||||
const scene = Core.scene;
|
||||
if (!scene) return;
|
||||
|
||||
const entityCount = entityStore.getAllEntities().length;
|
||||
const entityName = `Entity ${entityCount + 1}`;
|
||||
const entity = scene.createEntity(entityName);
|
||||
entityStore.addEntity(entity);
|
||||
entityStore.selectEntity(entity);
|
||||
|
||||
const command = new CreateEntityCommand(
|
||||
entityStore,
|
||||
messageHub,
|
||||
entityName
|
||||
);
|
||||
commandManager.execute(command);
|
||||
};
|
||||
|
||||
const handleDeleteEntity = async () => {
|
||||
@@ -200,8 +209,8 @@ export function SceneHierarchy({ entityStore, messageHub }: SceneHierarchyProps)
|
||||
|
||||
const confirmed = await confirm(
|
||||
locale === 'zh'
|
||||
? `确定要删除实体 "${entity.name}" 吗?此操作无法撤销。`
|
||||
: `Are you sure you want to delete entity "${entity.name}"? This action cannot be undone.`,
|
||||
? `确定要删除实体 "${entity.name}" 吗?`
|
||||
: `Are you sure you want to delete entity "${entity.name}"?`,
|
||||
{
|
||||
title: locale === 'zh' ? '删除实体' : 'Delete Entity',
|
||||
kind: 'warning'
|
||||
@@ -209,22 +218,44 @@ export function SceneHierarchy({ entityStore, messageHub }: SceneHierarchyProps)
|
||||
);
|
||||
|
||||
if (confirmed) {
|
||||
entity.destroy();
|
||||
entityStore.removeEntity(entity);
|
||||
const command = new DeleteEntityCommand(
|
||||
entityStore,
|
||||
messageHub,
|
||||
entity
|
||||
);
|
||||
commandManager.execute(command);
|
||||
}
|
||||
};
|
||||
|
||||
const handleContextMenu = (e: React.MouseEvent, entityId: number | null) => {
|
||||
e.preventDefault();
|
||||
setContextMenu({ x: e.clientX, y: e.clientY, entityId });
|
||||
};
|
||||
|
||||
const closeContextMenu = () => {
|
||||
setContextMenu(null);
|
||||
};
|
||||
|
||||
// Close context menu on click outside
|
||||
useEffect(() => {
|
||||
const handleClick = () => closeContextMenu();
|
||||
if (contextMenu) {
|
||||
window.addEventListener('click', handleClick);
|
||||
return () => window.removeEventListener('click', handleClick);
|
||||
}
|
||||
}, [contextMenu]);
|
||||
|
||||
// Listen for Delete key
|
||||
useEffect(() => {
|
||||
const handleKeyDown = (e: KeyboardEvent) => {
|
||||
if (e.key === 'Delete' && selectedId && !isRemoteConnected) {
|
||||
if (e.key === 'Delete' && selectedId && !isShowingRemote) {
|
||||
handleDeleteEntity();
|
||||
}
|
||||
};
|
||||
|
||||
window.addEventListener('keydown', handleKeyDown);
|
||||
return () => window.removeEventListener('keydown', handleKeyDown);
|
||||
}, [selectedId, isRemoteConnected]);
|
||||
}, [selectedId, isShowingRemote]);
|
||||
|
||||
// Filter entities based on search query
|
||||
const filterRemoteEntities = (entityList: RemoteEntity[]): RemoteEntity[] => {
|
||||
@@ -262,11 +293,11 @@ export function SceneHierarchy({ entityStore, messageHub }: SceneHierarchyProps)
|
||||
};
|
||||
|
||||
// Determine which entities to display
|
||||
const displayEntities = isRemoteConnected
|
||||
const displayEntities = isShowingRemote
|
||||
? filterRemoteEntities(remoteEntities)
|
||||
: filterLocalEntities(entities);
|
||||
const showRemoteIndicator = isRemoteConnected && remoteEntities.length > 0;
|
||||
const displaySceneName = isRemoteConnected && remoteSceneName ? remoteSceneName : sceneName;
|
||||
const showRemoteIndicator = isShowingRemote && remoteEntities.length > 0;
|
||||
const displaySceneName = isShowingRemote && remoteSceneName ? remoteSceneName : sceneName;
|
||||
|
||||
return (
|
||||
<div className="scene-hierarchy">
|
||||
@@ -282,6 +313,24 @@ export function SceneHierarchy({ entityStore, messageHub }: SceneHierarchyProps)
|
||||
{displaySceneName}{!isRemoteConnected && isSceneModified ? '*' : ''}
|
||||
</span>
|
||||
</div>
|
||||
{isRemoteConnected && (
|
||||
<div className="view-mode-toggle">
|
||||
<button
|
||||
className={`mode-btn ${viewMode === 'local' ? 'active' : ''}`}
|
||||
onClick={() => setViewMode('local')}
|
||||
title={locale === 'zh' ? '本地场景' : 'Local Scene'}
|
||||
>
|
||||
<Monitor size={14} />
|
||||
</button>
|
||||
<button
|
||||
className={`mode-btn ${viewMode === 'remote' ? 'active' : ''}`}
|
||||
onClick={() => setViewMode('remote')}
|
||||
title={locale === 'zh' ? '远程实体' : 'Remote Entities'}
|
||||
>
|
||||
<Globe size={14} />
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
{showRemoteIndicator && (
|
||||
<div className="remote-indicator" title="Showing remote entities">
|
||||
<Wifi size={12} />
|
||||
@@ -297,18 +346,17 @@ export function SceneHierarchy({ entityStore, messageHub }: SceneHierarchyProps)
|
||||
onChange={(e) => setSearchQuery(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
{!isRemoteConnected && (
|
||||
{!isShowingRemote && (
|
||||
<div className="hierarchy-toolbar">
|
||||
<button
|
||||
className="toolbar-btn"
|
||||
className="toolbar-btn icon-only"
|
||||
onClick={handleCreateEntity}
|
||||
title={locale === 'zh' ? '创建实体' : 'Create Entity'}
|
||||
>
|
||||
<Plus size={14} />
|
||||
<span>{locale === 'zh' ? '创建实体' : 'Create Entity'}</span>
|
||||
</button>
|
||||
<button
|
||||
className="toolbar-btn"
|
||||
className="toolbar-btn icon-only"
|
||||
onClick={handleDeleteEntity}
|
||||
disabled={!selectedId}
|
||||
title={locale === 'zh' ? '删除实体' : 'Delete Entity'}
|
||||
@@ -317,18 +365,18 @@ export function SceneHierarchy({ entityStore, messageHub }: SceneHierarchyProps)
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
<div className="hierarchy-content scrollable">
|
||||
<div className="hierarchy-content scrollable" onContextMenu={(e) => !isShowingRemote && handleContextMenu(e, null)}>
|
||||
{displayEntities.length === 0 ? (
|
||||
<div className="empty-state">
|
||||
<Box size={48} strokeWidth={1.5} className="empty-icon" />
|
||||
<div className="empty-title">{t('hierarchy.empty')}</div>
|
||||
<div className="empty-hint">
|
||||
{isRemoteConnected
|
||||
{isShowingRemote
|
||||
? 'No entities in remote game'
|
||||
: 'Create an entity to get started'}
|
||||
</div>
|
||||
</div>
|
||||
) : isRemoteConnected ? (
|
||||
) : isShowingRemote ? (
|
||||
<ul className="entity-list">
|
||||
{(displayEntities as RemoteEntity[]).map((entity) => (
|
||||
<li
|
||||
@@ -357,14 +405,45 @@ export function SceneHierarchy({ entityStore, messageHub }: SceneHierarchyProps)
|
||||
key={entity.id}
|
||||
className={`entity-item ${selectedId === entity.id ? 'selected' : ''}`}
|
||||
onClick={() => handleEntityClick(entity)}
|
||||
onContextMenu={(e) => {
|
||||
e.stopPropagation();
|
||||
handleEntityClick(entity);
|
||||
handleContextMenu(e, entity.id);
|
||||
}}
|
||||
>
|
||||
<Box size={14} className="entity-icon" />
|
||||
<span className="entity-name">Entity {entity.id}</span>
|
||||
<span className="entity-name">{entity.name || `Entity ${entity.id}`}</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{contextMenu && !isShowingRemote && (
|
||||
<div
|
||||
className="context-menu"
|
||||
style={{
|
||||
position: 'fixed',
|
||||
left: contextMenu.x,
|
||||
top: contextMenu.y,
|
||||
zIndex: 1000
|
||||
}}
|
||||
>
|
||||
<button onClick={() => { handleCreateEntity(); closeContextMenu(); }}>
|
||||
<Plus size={12} />
|
||||
<span>{locale === 'zh' ? '创建实体' : 'Create Entity'}</span>
|
||||
</button>
|
||||
{contextMenu.entityId && (
|
||||
<>
|
||||
<div className="context-menu-divider" />
|
||||
<button onClick={() => { handleDeleteEntity(); closeContextMenu(); }}>
|
||||
<Trash2 size={12} />
|
||||
<span>{locale === 'zh' ? '删除实体' : 'Delete Entity'}</span>
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { Play, Pause, RotateCcw, Maximize2, Grid3x3, Eye, EyeOff, Activity, Box, Square } from 'lucide-react';
|
||||
import { Play, Pause, RotateCcw, Maximize2, Grid3x3, Eye, EyeOff, Activity, Box, Square, Zap } from 'lucide-react';
|
||||
import '../styles/Viewport.css';
|
||||
import { useEngine } from '../hooks/useEngine';
|
||||
|
||||
interface ViewportProps {
|
||||
locale?: string;
|
||||
@@ -14,6 +15,11 @@ export function Viewport({ locale = 'en' }: ViewportProps) {
|
||||
const [showGizmos, setShowGizmos] = useState(true);
|
||||
const [showStats, setShowStats] = useState(false);
|
||||
const [is3D, setIs3D] = useState(true);
|
||||
const [useRustEngine, setUseRustEngine] = useState(false);
|
||||
|
||||
// Rust engine hook (only active in 2D mode with engine enabled)
|
||||
// Rust引擎钩子(仅在2D模式且启用引擎时激活)
|
||||
const engine = useEngine('viewport-canvas', useRustEngine && !is3D);
|
||||
const animationFrameRef = useRef<number>();
|
||||
const glRef = useRef<WebGLRenderingContext | null>(null);
|
||||
const gridProgramRef = useRef<WebGLProgram | null>(null);
|
||||
@@ -573,7 +579,17 @@ export function Viewport({ locale = 'en' }: ViewportProps) {
|
||||
};
|
||||
|
||||
const handlePlayPause = () => {
|
||||
setIsPlaying(!isPlaying);
|
||||
const newPlaying = !isPlaying;
|
||||
setIsPlaying(newPlaying);
|
||||
|
||||
// Control Rust engine if active | 控制Rust引擎(如果激活)
|
||||
if (useRustEngine && !is3D && engine.state.initialized) {
|
||||
if (newPlaying) {
|
||||
engine.start();
|
||||
} else {
|
||||
engine.stop();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const handleReset = () => {
|
||||
@@ -634,6 +650,15 @@ export function Viewport({ locale = 'en' }: ViewportProps) {
|
||||
>
|
||||
{is3D ? <Box size={16} /> : <Square size={16} />}
|
||||
</button>
|
||||
{!is3D && (
|
||||
<button
|
||||
className={`viewport-btn ${useRustEngine ? 'active' : ''}`}
|
||||
onClick={() => setUseRustEngine(!useRustEngine)}
|
||||
title={locale === 'zh' ? 'Rust引擎' : 'Rust Engine'}
|
||||
>
|
||||
<Zap size={16} />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
<div className="viewport-toolbar-right">
|
||||
<button
|
||||
@@ -652,17 +677,33 @@ export function Viewport({ locale = 'en' }: ViewportProps) {
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<canvas ref={canvasRef} className="viewport-canvas" />
|
||||
<canvas ref={canvasRef} id="viewport-canvas" className="viewport-canvas" />
|
||||
{showStats && (
|
||||
<div className="viewport-stats">
|
||||
<div className="viewport-stat">
|
||||
<span className="viewport-stat-label">FPS:</span>
|
||||
<span className="viewport-stat-value">{fps}</span>
|
||||
<span className="viewport-stat-value">
|
||||
{useRustEngine && !is3D ? engine.state.fps : fps}
|
||||
</span>
|
||||
</div>
|
||||
<div className="viewport-stat">
|
||||
<span className="viewport-stat-label">Draw Calls:</span>
|
||||
<span className="viewport-stat-value">{drawCalls}</span>
|
||||
<span className="viewport-stat-value">
|
||||
{useRustEngine && !is3D ? engine.state.drawCalls : drawCalls}
|
||||
</span>
|
||||
</div>
|
||||
{useRustEngine && !is3D && (
|
||||
<div className="viewport-stat">
|
||||
<span className="viewport-stat-label">Sprites:</span>
|
||||
<span className="viewport-stat-value">{engine.state.spriteCount}</span>
|
||||
</div>
|
||||
)}
|
||||
{useRustEngine && !is3D && engine.state.error && (
|
||||
<div className="viewport-stat viewport-stat-error">
|
||||
<span className="viewport-stat-label">Error:</span>
|
||||
<span className="viewport-stat-value">{engine.state.error}</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -12,7 +12,7 @@ import {
|
||||
EntityInspector
|
||||
} from './views';
|
||||
|
||||
export function Inspector({ entityStore: _entityStore, messageHub, inspectorRegistry, projectPath }: InspectorProps) {
|
||||
export function Inspector({ entityStore: _entityStore, messageHub, inspectorRegistry, projectPath, commandManager }: InspectorProps) {
|
||||
const [target, setTarget] = useState<InspectorTarget>(null);
|
||||
const [componentVersion, setComponentVersion] = useState(0);
|
||||
const [autoRefresh, setAutoRefresh] = useState(true);
|
||||
@@ -196,7 +196,7 @@ export function Inspector({ entityStore: _entityStore, messageHub, inspectorRegi
|
||||
}
|
||||
|
||||
if (target.type === 'entity') {
|
||||
return <EntityInspector entity={target.data} messageHub={messageHub} componentVersion={componentVersion} />;
|
||||
return <EntityInspector entity={target.data} messageHub={messageHub} commandManager={commandManager} componentVersion={componentVersion} />;
|
||||
}
|
||||
|
||||
return null;
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
import { Entity } from '@esengine/ecs-framework';
|
||||
import { EntityStoreService, MessageHub, InspectorRegistry } from '@esengine/editor-core';
|
||||
import { EntityStoreService, MessageHub, InspectorRegistry, CommandManager } from '@esengine/editor-core';
|
||||
|
||||
export interface InspectorProps {
|
||||
entityStore: EntityStoreService;
|
||||
messageHub: MessageHub;
|
||||
inspectorRegistry: InspectorRegistry;
|
||||
projectPath?: string | null;
|
||||
commandManager: CommandManager;
|
||||
}
|
||||
|
||||
export interface AssetFileInfo {
|
||||
|
||||
@@ -1,18 +1,24 @@
|
||||
import { useState } from 'react';
|
||||
import { Settings, ChevronDown, ChevronRight, X } from 'lucide-react';
|
||||
import { Entity, Component } from '@esengine/ecs-framework';
|
||||
import { MessageHub } from '@esengine/editor-core';
|
||||
import { Settings, ChevronDown, ChevronRight, X, Plus } from 'lucide-react';
|
||||
import { Entity, Component, Core } from '@esengine/ecs-framework';
|
||||
import { MessageHub, CommandManager, ComponentRegistry } from '@esengine/editor-core';
|
||||
import { PropertyInspector } from '../../PropertyInspector';
|
||||
import { RemoveComponentCommand, UpdateComponentCommand, AddComponentCommand } from '../../../application/commands/component';
|
||||
import '../../../styles/EntityInspector.css';
|
||||
|
||||
interface EntityInspectorProps {
|
||||
entity: Entity;
|
||||
messageHub: MessageHub;
|
||||
commandManager: CommandManager;
|
||||
componentVersion: number;
|
||||
}
|
||||
|
||||
export function EntityInspector({ entity, messageHub, componentVersion }: EntityInspectorProps) {
|
||||
export function EntityInspector({ entity, messageHub, commandManager, componentVersion }: EntityInspectorProps) {
|
||||
const [expandedComponents, setExpandedComponents] = useState<Set<number>>(new Set());
|
||||
const [showComponentMenu, setShowComponentMenu] = useState(false);
|
||||
|
||||
const componentRegistry = Core.services.resolve(ComponentRegistry);
|
||||
const availableComponents = componentRegistry?.getAllComponents() || [];
|
||||
|
||||
const toggleComponentExpanded = (index: number) => {
|
||||
setExpandedComponents((prev) => {
|
||||
@@ -26,21 +32,33 @@ export function EntityInspector({ entity, messageHub, componentVersion }: Entity
|
||||
});
|
||||
};
|
||||
|
||||
const handleAddComponent = (ComponentClass: new () => Component) => {
|
||||
const command = new AddComponentCommand(messageHub, entity, ComponentClass);
|
||||
commandManager.execute(command);
|
||||
setShowComponentMenu(false);
|
||||
};
|
||||
|
||||
const handleRemoveComponent = (index: number) => {
|
||||
const component = entity.components[index];
|
||||
if (component) {
|
||||
entity.removeComponent(component);
|
||||
messageHub.publish('component:removed', { entity, component });
|
||||
const command = new RemoveComponentCommand(
|
||||
messageHub,
|
||||
entity,
|
||||
component
|
||||
);
|
||||
commandManager.execute(command);
|
||||
}
|
||||
};
|
||||
|
||||
const handlePropertyChange = (component: Component, propertyName: string, value: unknown) => {
|
||||
messageHub.publish('component:property:changed', {
|
||||
const command = new UpdateComponentCommand(
|
||||
messageHub,
|
||||
entity,
|
||||
component,
|
||||
propertyName,
|
||||
value
|
||||
});
|
||||
);
|
||||
commandManager.execute(command);
|
||||
};
|
||||
|
||||
return (
|
||||
@@ -63,10 +81,77 @@ export function EntityInspector({ entity, messageHub, componentVersion }: Entity
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{entity.components.length > 0 && (
|
||||
<div className="inspector-section">
|
||||
<div className="section-title">组件</div>
|
||||
{entity.components.map((component: Component, index: number) => {
|
||||
<div className="inspector-section">
|
||||
<div className="section-title" style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
|
||||
<span>组件</span>
|
||||
<div style={{ position: 'relative' }}>
|
||||
<button
|
||||
onClick={() => setShowComponentMenu(!showComponentMenu)}
|
||||
style={{
|
||||
background: 'transparent',
|
||||
border: '1px solid #4a4a4a',
|
||||
borderRadius: '4px',
|
||||
color: '#e0e0e0',
|
||||
cursor: 'pointer',
|
||||
padding: '2px 6px',
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
gap: '4px',
|
||||
fontSize: '11px'
|
||||
}}
|
||||
>
|
||||
<Plus size={12} />
|
||||
添加
|
||||
</button>
|
||||
{showComponentMenu && (
|
||||
<div
|
||||
style={{
|
||||
position: 'absolute',
|
||||
top: '100%',
|
||||
right: 0,
|
||||
marginTop: '4px',
|
||||
backgroundColor: '#2a2a2a',
|
||||
border: '1px solid #4a4a4a',
|
||||
borderRadius: '4px',
|
||||
boxShadow: '0 4px 12px rgba(0,0,0,0.3)',
|
||||
zIndex: 1000,
|
||||
minWidth: '150px',
|
||||
maxHeight: '200px',
|
||||
overflowY: 'auto'
|
||||
}}
|
||||
>
|
||||
{availableComponents.length === 0 ? (
|
||||
<div style={{ padding: '8px 12px', color: '#888', fontSize: '11px' }}>
|
||||
没有可用组件
|
||||
</div>
|
||||
) : (
|
||||
availableComponents.map((info) => (
|
||||
<button
|
||||
key={info.name}
|
||||
onClick={() => info.type && handleAddComponent(info.type)}
|
||||
style={{
|
||||
display: 'block',
|
||||
width: '100%',
|
||||
padding: '6px 12px',
|
||||
background: 'transparent',
|
||||
border: 'none',
|
||||
color: '#e0e0e0',
|
||||
fontSize: '12px',
|
||||
textAlign: 'left',
|
||||
cursor: 'pointer'
|
||||
}}
|
||||
onMouseEnter={(e) => (e.currentTarget.style.backgroundColor = '#3a3a3a')}
|
||||
onMouseLeave={(e) => (e.currentTarget.style.backgroundColor = 'transparent')}
|
||||
>
|
||||
{info.name}
|
||||
</button>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
{entity.components.map((component: Component, index: number) => {
|
||||
const isExpanded = expandedComponents.has(index);
|
||||
const componentName = component.constructor?.name || 'Component';
|
||||
|
||||
@@ -140,8 +225,7 @@ export function EntityInspector({ entity, messageHub, componentVersion }: Entity
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import type { Entity, Component } from '@esengine/ecs-framework';
|
||||
import type { Node } from '@esengine/behavior-tree-editor';
|
||||
|
||||
export interface PluginEvent {
|
||||
name: string;
|
||||
|
||||
127
packages/editor-app/src/hooks/useEngine.ts
Normal file
127
packages/editor-app/src/hooks/useEngine.ts
Normal file
@@ -0,0 +1,127 @@
|
||||
/**
|
||||
* React hook for using the Rust game engine.
|
||||
* 使用Rust游戏引擎的React钩子。
|
||||
*/
|
||||
|
||||
import { useEffect, useRef, useState, useCallback } from 'react';
|
||||
import { EngineService } from '../services/EngineService';
|
||||
|
||||
export interface EngineState {
|
||||
initialized: boolean;
|
||||
running: boolean;
|
||||
fps: number;
|
||||
drawCalls: number;
|
||||
spriteCount: number;
|
||||
error: string | null;
|
||||
}
|
||||
|
||||
export interface UseEngineReturn {
|
||||
state: EngineState;
|
||||
start: () => void;
|
||||
stop: () => void;
|
||||
createSprite: (name: string, options?: {
|
||||
x?: number;
|
||||
y?: number;
|
||||
textureId?: number;
|
||||
width?: number;
|
||||
height?: number;
|
||||
}) => void;
|
||||
loadTexture: (id: number, url: string) => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Hook for managing engine lifecycle in React components.
|
||||
* 用于在React组件中管理引擎生命周期的钩子。
|
||||
*
|
||||
* @param canvasId - Canvas element ID | Canvas元素ID
|
||||
* @param autoInit - Whether to auto-initialize | 是否自动初始化
|
||||
*/
|
||||
export function useEngine(canvasId: string, autoInit = true): UseEngineReturn {
|
||||
const engineRef = useRef<EngineService>(EngineService.getInstance());
|
||||
const statsIntervalRef = useRef<number | null>(null);
|
||||
|
||||
const [state, setState] = useState<EngineState>({
|
||||
initialized: false,
|
||||
running: false,
|
||||
fps: 0,
|
||||
drawCalls: 0,
|
||||
spriteCount: 0,
|
||||
error: null
|
||||
});
|
||||
|
||||
// Initialize engine | 初始化引擎
|
||||
useEffect(() => {
|
||||
if (!autoInit) return;
|
||||
|
||||
const init = async () => {
|
||||
try {
|
||||
await engineRef.current.initialize(canvasId);
|
||||
setState(prev => ({ ...prev, initialized: true, error: null }));
|
||||
|
||||
// Start stats update interval | 启动统计更新间隔
|
||||
statsIntervalRef.current = window.setInterval(() => {
|
||||
const stats = engineRef.current.getStats();
|
||||
setState(prev => ({
|
||||
...prev,
|
||||
fps: stats.fps,
|
||||
drawCalls: stats.drawCalls,
|
||||
spriteCount: stats.spriteCount
|
||||
}));
|
||||
}, 100);
|
||||
} catch (error) {
|
||||
console.error('Failed to initialize engine | 引擎初始化失败:', error);
|
||||
setState(prev => ({
|
||||
...prev,
|
||||
error: error instanceof Error ? error.message : String(error)
|
||||
}));
|
||||
}
|
||||
};
|
||||
|
||||
init();
|
||||
|
||||
return () => {
|
||||
if (statsIntervalRef.current) {
|
||||
clearInterval(statsIntervalRef.current);
|
||||
}
|
||||
engineRef.current.dispose();
|
||||
};
|
||||
}, [canvasId, autoInit]);
|
||||
|
||||
// Start engine | 启动引擎
|
||||
const start = useCallback(() => {
|
||||
engineRef.current.start();
|
||||
setState(prev => ({ ...prev, running: true }));
|
||||
}, []);
|
||||
|
||||
// Stop engine | 停止引擎
|
||||
const stop = useCallback(() => {
|
||||
engineRef.current.stop();
|
||||
setState(prev => ({ ...prev, running: false }));
|
||||
}, []);
|
||||
|
||||
// Create sprite entity | 创建精灵实体
|
||||
const createSprite = useCallback((name: string, options?: {
|
||||
x?: number;
|
||||
y?: number;
|
||||
textureId?: number;
|
||||
width?: number;
|
||||
height?: number;
|
||||
}) => {
|
||||
engineRef.current.createSpriteEntity(name, options);
|
||||
}, []);
|
||||
|
||||
// Load texture | 加载纹理
|
||||
const loadTexture = useCallback((id: number, url: string) => {
|
||||
engineRef.current.loadTexture(id, url);
|
||||
}, []);
|
||||
|
||||
return {
|
||||
state,
|
||||
start,
|
||||
stop,
|
||||
createSprite,
|
||||
loadTexture
|
||||
};
|
||||
}
|
||||
|
||||
export default useEngine;
|
||||
254
packages/editor-app/src/services/EngineService.ts
Normal file
254
packages/editor-app/src/services/EngineService.ts
Normal file
@@ -0,0 +1,254 @@
|
||||
/**
|
||||
* Engine service for managing Rust engine lifecycle.
|
||||
* 管理Rust引擎生命周期的服务。
|
||||
*/
|
||||
|
||||
import { EngineBridge, SpriteComponent, EngineRenderSystem, ITransformComponent } from '@esengine/ecs-engine-bindgen';
|
||||
import { Core, Scene, Entity, Component, ECSComponent } from '@esengine/ecs-framework';
|
||||
import * as esEngine from '@esengine/engine';
|
||||
|
||||
/**
|
||||
* Transform component for editor entities.
|
||||
* 编辑器实体的变换组件。
|
||||
*/
|
||||
@ECSComponent('Transform')
|
||||
export class TransformComponent extends Component implements ITransformComponent {
|
||||
position = { x: 0, y: 0 };
|
||||
rotation = 0;
|
||||
scale = { x: 1, y: 1 };
|
||||
}
|
||||
|
||||
/**
|
||||
* Engine service singleton for editor integration.
|
||||
* 用于编辑器集成的引擎服务单例。
|
||||
*/
|
||||
export class EngineService {
|
||||
private static instance: EngineService | null = null;
|
||||
|
||||
private bridge: EngineBridge | null = null;
|
||||
private scene: Scene | null = null;
|
||||
private renderSystem: EngineRenderSystem | null = null;
|
||||
private initialized = false;
|
||||
private running = false;
|
||||
private animationFrameId: number | null = null;
|
||||
private lastTime = 0;
|
||||
|
||||
private constructor() {}
|
||||
|
||||
/**
|
||||
* Get singleton instance.
|
||||
* 获取单例实例。
|
||||
*/
|
||||
static getInstance(): EngineService {
|
||||
if (!EngineService.instance) {
|
||||
EngineService.instance = new EngineService();
|
||||
}
|
||||
return EngineService.instance;
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize the engine with canvas.
|
||||
* 使用canvas初始化引擎。
|
||||
*/
|
||||
async initialize(canvasId: string): Promise<void> {
|
||||
if (this.initialized) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
// Create engine bridge | 创建引擎桥接
|
||||
this.bridge = new EngineBridge({
|
||||
canvasId
|
||||
});
|
||||
|
||||
// Initialize WASM with pre-imported module | 使用预导入模块初始化WASM
|
||||
await this.bridge.initializeWithModule(esEngine);
|
||||
|
||||
// Initialize Core if not already | 初始化Core(如果尚未初始化)
|
||||
if (!Core.scene) {
|
||||
Core.create({ debug: false });
|
||||
}
|
||||
|
||||
// Create ECS scene and set it via Core | 通过Core创建并设置ECS场景
|
||||
this.scene = new Scene({ name: 'EditorScene' });
|
||||
|
||||
// Add render system | 添加渲染系统
|
||||
this.renderSystem = new EngineRenderSystem(this.bridge, TransformComponent);
|
||||
this.scene.addSystem(this.renderSystem);
|
||||
|
||||
// Set scene via Core | 通过Core设置场景
|
||||
Core.setScene(this.scene);
|
||||
|
||||
this.initialized = true;
|
||||
console.log('EngineService initialized | 引擎服务初始化完成');
|
||||
} catch (error) {
|
||||
console.error('Failed to initialize engine | 引擎初始化失败:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if engine is initialized.
|
||||
* 检查引擎是否已初始化。
|
||||
*/
|
||||
isInitialized(): boolean {
|
||||
return this.initialized;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if engine is running.
|
||||
* 检查引擎是否正在运行。
|
||||
*/
|
||||
isRunning(): boolean {
|
||||
return this.running;
|
||||
}
|
||||
|
||||
/**
|
||||
* Start the game loop.
|
||||
* 启动游戏循环。
|
||||
*/
|
||||
start(): void {
|
||||
if (!this.initialized || this.running) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.running = true;
|
||||
this.lastTime = performance.now();
|
||||
this.gameLoop();
|
||||
}
|
||||
|
||||
/**
|
||||
* Stop the game loop.
|
||||
* 停止游戏循环。
|
||||
*/
|
||||
stop(): void {
|
||||
this.running = false;
|
||||
if (this.animationFrameId !== null) {
|
||||
cancelAnimationFrame(this.animationFrameId);
|
||||
this.animationFrameId = null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Main game loop.
|
||||
* 主游戏循环。
|
||||
*/
|
||||
private gameLoop = (): void => {
|
||||
if (!this.running) {
|
||||
return;
|
||||
}
|
||||
|
||||
const currentTime = performance.now();
|
||||
const deltaTime = (currentTime - this.lastTime) / 1000;
|
||||
this.lastTime = currentTime;
|
||||
|
||||
// Update via Core | 通过Core更新
|
||||
Core.update(deltaTime);
|
||||
|
||||
this.animationFrameId = requestAnimationFrame(this.gameLoop);
|
||||
};
|
||||
|
||||
/**
|
||||
* Create entity with sprite and transform.
|
||||
* 创建带精灵和变换的实体。
|
||||
*/
|
||||
createSpriteEntity(name: string, options?: {
|
||||
x?: number;
|
||||
y?: number;
|
||||
textureId?: number;
|
||||
width?: number;
|
||||
height?: number;
|
||||
}): Entity | null {
|
||||
if (!this.scene) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const entity = this.scene.createEntity(name);
|
||||
|
||||
// Add transform | 添加变换组件
|
||||
const transform = new TransformComponent();
|
||||
if (options) {
|
||||
transform.position.x = options.x ?? 0;
|
||||
transform.position.y = options.y ?? 0;
|
||||
}
|
||||
entity.addComponent(transform);
|
||||
|
||||
// Add sprite | 添加精灵组件
|
||||
const sprite = new SpriteComponent();
|
||||
if (options) {
|
||||
sprite.textureId = options.textureId ?? 0;
|
||||
sprite.width = options.width ?? 64;
|
||||
sprite.height = options.height ?? 64;
|
||||
}
|
||||
entity.addComponent(sprite);
|
||||
|
||||
return entity;
|
||||
}
|
||||
|
||||
/**
|
||||
* Load texture.
|
||||
* 加载纹理。
|
||||
*/
|
||||
loadTexture(id: number, url: string): void {
|
||||
if (this.renderSystem) {
|
||||
this.renderSystem.loadTexture(id, url);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get engine statistics.
|
||||
* 获取引擎统计信息。
|
||||
*/
|
||||
getStats(): { fps: number; drawCalls: number; spriteCount: number } {
|
||||
if (!this.renderSystem) {
|
||||
return { fps: 0, drawCalls: 0, spriteCount: 0 };
|
||||
}
|
||||
|
||||
const engineStats = this.renderSystem.getStats();
|
||||
return {
|
||||
fps: engineStats?.fps ?? 0,
|
||||
drawCalls: engineStats?.drawCalls ?? 0,
|
||||
spriteCount: this.renderSystem.spriteCount
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the ECS scene.
|
||||
* 获取ECS场景。
|
||||
*/
|
||||
getScene(): Scene | null {
|
||||
return this.scene;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resize the engine viewport.
|
||||
* 调整引擎视口大小。
|
||||
*/
|
||||
resize(width: number, height: number): void {
|
||||
if (this.bridge) {
|
||||
this.bridge.resize(width, height);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Dispose engine resources.
|
||||
* 释放引擎资源。
|
||||
*/
|
||||
dispose(): void {
|
||||
this.stop();
|
||||
|
||||
// Scene doesn't have a destroy method, just clear reference
|
||||
// 场景没有destroy方法,只需清除引用
|
||||
this.scene = null;
|
||||
|
||||
if (this.bridge) {
|
||||
this.bridge.dispose();
|
||||
this.bridge = null;
|
||||
}
|
||||
|
||||
this.renderSystem = null;
|
||||
this.initialized = false;
|
||||
}
|
||||
}
|
||||
|
||||
export default EngineService;
|
||||
@@ -67,6 +67,51 @@
|
||||
transition: color var(--transition-fast);
|
||||
}
|
||||
|
||||
.view-mode-toggle {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 2px;
|
||||
padding: 2px;
|
||||
background-color: var(--color-bg-base);
|
||||
border: 1px solid var(--color-border-default);
|
||||
border-radius: var(--radius-sm);
|
||||
}
|
||||
|
||||
.mode-btn {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 24px;
|
||||
min-width: 24px;
|
||||
height: 20px;
|
||||
padding: 0;
|
||||
background: transparent;
|
||||
border: none;
|
||||
border-radius: var(--radius-xs);
|
||||
color: #cccccc;
|
||||
cursor: pointer;
|
||||
transition: all var(--transition-fast);
|
||||
}
|
||||
|
||||
.mode-btn svg {
|
||||
width: 14px;
|
||||
height: 14px;
|
||||
min-width: 14px;
|
||||
min-height: 14px;
|
||||
color: inherit;
|
||||
stroke: currentColor;
|
||||
}
|
||||
|
||||
.mode-btn:hover {
|
||||
background-color: var(--color-bg-hover);
|
||||
color: var(--color-text-primary);
|
||||
}
|
||||
|
||||
.mode-btn.active {
|
||||
background-color: var(--color-primary);
|
||||
color: white;
|
||||
}
|
||||
|
||||
.remote-indicator {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
@@ -144,8 +189,14 @@
|
||||
}
|
||||
|
||||
.toolbar-btn:disabled {
|
||||
opacity: 0.5;
|
||||
cursor: not-allowed;
|
||||
color: #666;
|
||||
}
|
||||
|
||||
.toolbar-btn.icon-only {
|
||||
padding: var(--spacing-xs);
|
||||
min-width: 28px;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.hierarchy-content {
|
||||
@@ -340,3 +391,38 @@
|
||||
transform: scale(1.05);
|
||||
}
|
||||
}
|
||||
|
||||
/* Context menu styles */
|
||||
.context-menu {
|
||||
background-color: var(--color-bg-elevated);
|
||||
border: 1px solid var(--color-border-default);
|
||||
border-radius: var(--radius-md);
|
||||
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
|
||||
padding: var(--spacing-xs);
|
||||
min-width: 150px;
|
||||
}
|
||||
|
||||
.context-menu button {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--spacing-sm);
|
||||
width: 100%;
|
||||
padding: var(--spacing-sm) var(--spacing-md);
|
||||
background: transparent;
|
||||
border: none;
|
||||
border-radius: var(--radius-sm);
|
||||
color: var(--color-text-primary);
|
||||
font-size: var(--font-size-sm);
|
||||
cursor: pointer;
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
.context-menu button:hover {
|
||||
background-color: var(--color-bg-hover);
|
||||
}
|
||||
|
||||
.context-menu-divider {
|
||||
height: 1px;
|
||||
background-color: var(--color-border-default);
|
||||
margin: var(--spacing-xs) 0;
|
||||
}
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
--color-text-primary: #cccccc;
|
||||
--color-text-secondary: #9d9d9d;
|
||||
--color-text-tertiary: #6a6a6a;
|
||||
--color-text-disabled: #4d4d4d;
|
||||
--color-text-disabled: #aaaaaa;
|
||||
--color-text-inverse: #ffffff;
|
||||
|
||||
/* 颜色系统 - 边框 */
|
||||
|
||||
Reference in New Issue
Block a user