A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
feat: add command replication for multi-window floating panel architecture
esengineb9ef9ec831dc
diff --git a/editor/src/DockLayoutManager.ts b/editor/src/DockLayoutManager.tsindex f8054ad3d..5dab9cf70 100644--- a/editor/src/DockLayoutManager.ts+++ b/editor/src/DockLayoutManager.ts@@ -92,7 +92,7 @@ export class DockLayoutManager {this.panelManager_,);},- disableFloatingGroups: true,+ disableFloatingGroups: false,});this.setupTabContextMenu(container);@@ -226,11 +226,6 @@ export class DockLayoutManager {const desc = getPanel(id);if (!desc) return;- if (desc.detachOnly) {- this.handleDetachPanel(id, false);- return;- }-if (desc.position === 'center') {this.api_.addPanel({id: desc.id,diff --git a/editor/src/__tests__/commands/CommandSerialization.test.ts b/editor/src/__tests__/commands/CommandSerialization.test.tsnew file mode 100644index 000000000..c64e7ce21--- /dev/null+++ b/editor/src/__tests__/commands/CommandSerialization.test.ts@@ -0,0 +1,220 @@+import { describe, it, expect } from 'vitest';+import type { SceneData, EntityData } from '../../types/SceneTypes';+import { createEntityData } from '../../types/SceneTypes';+import { CommandRegistry } from '../../commands/Command';+import { PropertyCommand } from '../../commands/PropertyCommand';+import {+ CreateEntityCommand,+ DeleteEntityCommand,+ ReparentCommand,+ MoveEntityCommand,+ AddComponentCommand,+ RemoveComponentCommand,+ ReorderComponentCommand,+} from '../../commands/EntityCommands';+import { RenameEntityCommand } from '../../commands/RenameEntityCommand';+import { ToggleVisibilityCommand } from '../../commands/ToggleVisibilityCommand';+import { CompoundCommand } from '../../commands/CompoundCommand';++function makeScene(): { scene: SceneData; entityMap: Map<number, EntityData> } {+ const e1 = createEntityData(1, 'Player', null);+ e1.components.push({ type: 'Transform', data: { x: 0, y: 0 } });+ e1.children = [2];++ const e2 = createEntityData(2, 'Child', 1);+ e2.components.push({ type: 'Sprite', data: { color: 'red' } });+ e2.components.push({ type: 'Transform', data: { x: 10, y: 20 } });++ const scene: SceneData = { version: '1', name: 'Test', entities: [e1, e2] };+ const entityMap = new Map<number, EntityData>();+ entityMap.set(1, e1);+ entityMap.set(2, e2);+ return { scene, entityMap };+}++function roundTrip(+ cmd: import('../../commands/Command').Command,+ scene: SceneData,+ entityMap: Map<number, EntityData>,+) {+ const serialized = cmd.serialize();+ expect(serialized).not.toBeNull();+ const deserialized = CommandRegistry.deserialize(serialized!, scene, entityMap);+ expect(deserialized).not.toBeNull();+ return deserialized!;+}++describe('Command Serialization', () => {+ it('PropertyCommand round-trip', () => {+ const { scene, entityMap } = makeScene();+ const cmd = new PropertyCommand(scene, entityMap, 1, 'Transform', 'x', 0, 5);+ const restored = roundTrip(cmd, scene, entityMap);++ expect(restored.type).toBe('property');+ restored.execute();+ const comp = entityMap.get(1)!.components.find(c => c.type === 'Transform')!;+ expect(comp.data.x).toBe(5);++ restored.undo();+ expect(comp.data.x).toBe(0);+ });++ it('CreateEntityCommand round-trip', () => {+ const { scene, entityMap } = makeScene();+ const cmd = new CreateEntityCommand(scene, entityMap, 10, 'NewEntity', 1);+ const restored = roundTrip(cmd, scene, entityMap);++ restored.execute();+ expect(scene.entities.find(e => e.id === 10)).toBeTruthy();+ expect(entityMap.get(1)!.children).toContain(10);++ restored.undo();+ expect(scene.entities.find(e => e.id === 10)).toBeUndefined();+ });++ it('DeleteEntityCommand round-trip', () => {+ const { scene, entityMap } = makeScene();+ const cmd = new DeleteEntityCommand(scene, entityMap, 2);+ const restored = roundTrip(cmd, scene, entityMap);++ restored.execute();+ expect(scene.entities.find(e => e.id === 2)).toBeUndefined();++ restored.undo();+ expect(scene.entities.find(e => e.id === 2)).toBeTruthy();+ });++ it('ReparentCommand round-trip', () => {+ const { scene, entityMap } = makeScene();+ const cmd = new ReparentCommand(scene, entityMap, 2, null);+ const restored = roundTrip(cmd, scene, entityMap);++ restored.execute();+ expect(entityMap.get(2)!.parent).toBeNull();+ expect(entityMap.get(1)!.children).not.toContain(2);++ restored.undo();+ expect(entityMap.get(2)!.parent).toBe(1);+ });++ it('MoveEntityCommand round-trip', () => {+ const { scene, entityMap } = makeScene();+ const cmd = new MoveEntityCommand(scene, entityMap, 2, null, 0);+ const restored = roundTrip(cmd, scene, entityMap);++ restored.execute();+ expect(entityMap.get(2)!.parent).toBeNull();++ restored.undo();+ expect(entityMap.get(2)!.parent).toBe(1);+ });++ it('AddComponentCommand round-trip', () => {+ const { scene, entityMap } = makeScene();+ const cmd = new AddComponentCommand(scene, entityMap, 1, 'Health', { hp: 100 });+ const restored = roundTrip(cmd, scene, entityMap);++ restored.execute();+ const comp = entityMap.get(1)!.components.find(c => c.type === 'Health');+ expect(comp).toBeTruthy();+ expect(comp!.data.hp).toBe(100);++ restored.undo();+ expect(entityMap.get(1)!.components.find(c => c.type === 'Health')).toBeUndefined();+ });++ it('RemoveComponentCommand round-trip', () => {+ const { scene, entityMap } = makeScene();+ const cmd = new RemoveComponentCommand(scene, entityMap, 1, 'Transform');+ const restored = roundTrip(cmd, scene, entityMap);++ restored.execute();+ expect(entityMap.get(1)!.components.find(c => c.type === 'Transform')).toBeUndefined();++ restored.undo();+ expect(entityMap.get(1)!.components.find(c => c.type === 'Transform')).toBeTruthy();+ });++ it('ReorderComponentCommand round-trip', () => {+ const { scene, entityMap } = makeScene();+ const cmd = new ReorderComponentCommand(scene, entityMap, 2, 0, 1);+ const restored = roundTrip(cmd, scene, entityMap);++ const components = entityMap.get(2)!.components;+ expect(components[0].type).toBe('Sprite');++ restored.execute();+ expect(components[0].type).toBe('Transform');+ expect(components[1].type).toBe('Sprite');++ restored.undo();+ expect(components[0].type).toBe('Sprite');+ });++ it('RenameEntityCommand round-trip', () => {+ const { scene, entityMap } = makeScene();+ const cmd = new RenameEntityCommand(scene, entityMap, 1, 'Player', 'Hero');+ const restored = roundTrip(cmd, scene, entityMap);++ restored.execute();+ expect(entityMap.get(1)!.name).toBe('Hero');++ restored.undo();+ expect(entityMap.get(1)!.name).toBe('Player');+ });++ it('ToggleVisibilityCommand round-trip', () => {+ const { scene, entityMap } = makeScene();+ const cmd = new ToggleVisibilityCommand(scene, entityMap, 1);+ const restored = roundTrip(cmd, scene, entityMap);++ restored.execute();+ expect(entityMap.get(1)!.visible).toBe(false);++ restored.undo();+ expect(entityMap.get(1)!.visible).toBe(true);+ });++ it('CompoundCommand round-trip', () => {+ const { scene, entityMap } = makeScene();+ const cmds = [+ new PropertyCommand(scene, entityMap, 1, 'Transform', 'x', 0, 99),+ new RenameEntityCommand(scene, entityMap, 1, 'Player', 'Boss'),+ ];+ const compound = new CompoundCommand(cmds, 'Batch edit');+ const restored = roundTrip(compound, scene, entityMap);++ restored.execute();+ expect(entityMap.get(1)!.components.find(c => c.type === 'Transform')!.data.x).toBe(99);+ expect(entityMap.get(1)!.name).toBe('Boss');++ restored.undo();+ expect(entityMap.get(1)!.components.find(c => c.type === 'Transform')!.data.x).toBe(0);+ expect(entityMap.get(1)!.name).toBe('Player');+ });++ it('CompoundCommand returns null if child is non-serializable', () => {+ const { scene, entityMap } = makeScene();+ const mockNonSerializable = {+ id: 'x', type: 'fake', timestamp: 0, description: '', structural: false,+ execute() {}, undo() {},+ canMerge() { return false; }, merge() { return this; },+ updateEntityMap() {}, emitChangeEvents() {},+ serialize() { return null; },+ };+ const compound = new CompoundCommand(+ [mockNonSerializable, new PropertyCommand(scene, entityMap, 1, 'Transform', 'x', 0, 1)],+ 'Mixed',+ );+ expect(compound.serialize()).toBeNull();+ });++ it('CommandRegistry.deserialize returns null for unknown type', () => {+ const { scene, entityMap } = makeScene();+ const result = CommandRegistry.deserialize(+ { type: 'unknown_type', data: {} },+ scene, entityMap,+ );+ expect(result).toBeNull();+ });+});diff --git a/editor/src/commands/Command.ts b/editor/src/commands/Command.tsindex 9d5d15713..a0373f446 100644--- a/editor/src/commands/Command.ts+++ b/editor/src/commands/Command.ts@@ -3,7 +3,48 @@* @brief Command interface for undo/redo system*/-import type { EntityData } from '../types/SceneTypes';+import type { EntityData, SceneData } from '../types/SceneTypes';++// =============================================================================+// SerializedCommand+// =============================================================================++export interface SerializedCommand {+ type: string;+ data: Record<string, unknown>;+}++export type CommandDeserializer = (+ data: Record<string, unknown>,+ scene: SceneData,+ entityMap: Map<number, EntityData>,+) => Command;++// =============================================================================+// CommandRegistry+// =============================================================================++const deserializers_ = new Map<string, CommandDeserializer>();++export const CommandRegistry = {+ register(type: string, deserializer: CommandDeserializer): void {+ deserializers_.set(type, deserializer);+ },++ deserialize(+ serialized: SerializedCommand,+ scene: SceneData,+ entityMap: Map<number, EntityData>,+ ): Command | null {+ const deserializer = deserializers_.get(serialized.type);+ if (!deserializer) return null;+ return deserializer(serialized.data, scene, entityMap);+ },++ has(type: string): boolean {+ return deserializers_.has(type);+ },+};// =============================================================================// ChangeEmitter Interface@@ -43,6 +84,8 @@ export interface Command {updateEntityMap(map: Map<number, EntityData>, isUndo: boolean): void;emitChangeEvents(emitter: ChangeEmitter, isUndo: boolean): void;++ serialize(): SerializedCommand | null;}// =============================================================================@@ -76,4 +119,8 @@ export abstract class BaseCommand implements Command {updateEntityMap(_map: Map<number, EntityData>, _isUndo: boolean): void {}emitChangeEvents(_emitter: ChangeEmitter, _isUndo: boolean): void {}++ serialize(): SerializedCommand | null {+ return null;+ }}diff --git a/editor/src/commands/CompoundCommand.ts b/editor/src/commands/CompoundCommand.tsindex 149f76b6a..e71ffeaa8 100644--- a/editor/src/commands/CompoundCommand.ts+++ b/editor/src/commands/CompoundCommand.ts@@ -3,8 +3,8 @@* @brief Compound command for batching multiple commands as one undo unit*/-import type { EntityData } from '../types/SceneTypes';-import { BaseCommand, type ChangeEmitter, type Command } from './Command';+import type { EntityData, SceneData } from '../types/SceneTypes';+import { BaseCommand, CommandRegistry, type ChangeEmitter, type Command, type SerializedCommand } from './Command';export class CompoundCommand extends BaseCommand {readonly type = 'compound';@@ -45,6 +45,32 @@ export class CompoundCommand extends BaseCommand {}}+ serialize(): SerializedCommand | null {+ const serializedCmds: SerializedCommand[] = [];+ for (const cmd of this.commands_) {+ const s = cmd.serialize();+ if (!s) return null;+ serializedCmds.push(s);+ }+ return {+ type: this.type,+ data: { commands: serializedCmds, description: this.description },+ };+ }++ static {+ CommandRegistry.register('compound', (data, scene, entityMap) => {+ const serializedCmds = data.commands as SerializedCommand[];+ const commands: Command[] = [];+ for (const s of serializedCmds) {+ const cmd = CommandRegistry.deserialize(s, scene, entityMap);+ if (!cmd) return null as unknown as Command;+ commands.push(cmd);+ }+ return new CompoundCommand(commands, data.description as string);+ });+ }+emitChangeEvents(emitter: ChangeEmitter, isUndo: boolean): void {if (isUndo) {for (let i = this.commands_.length - 1; i >= 0; i--) {diff --git a/editor/src/commands/EntityCommands.ts b/editor/src/commands/EntityCommands.tsindex 2ac9c9aec..23ec2d401 100644--- a/editor/src/commands/EntityCommands.ts+++ b/editor/src/commands/EntityCommands.ts@@ -5,7 +5,7 @@import type { SceneData, EntityData } from '../types/SceneTypes';import { createEntityData } from '../types/SceneTypes';-import { BaseCommand, type ChangeEmitter } from './Command';+import { BaseCommand, CommandRegistry, type ChangeEmitter, type SerializedCommand } from './Command';// =============================================================================// CreateEntityCommand@@ -73,6 +73,24 @@ export class CreateEntityCommand extends BaseCommand {});}+ serialize(): SerializedCommand {+ return {+ type: this.type,+ data: { entityId: this.entityId_, name: this.name_, parent: this.parent_ },+ };+ }++ static {+ CommandRegistry.register('create_entity', (data, scene, entityMap) =>+ new CreateEntityCommand(+ scene, entityMap,+ data.entityId as number,+ data.name as string,+ (data.parent as number | null) ?? null,+ ),+ );+ }+get entityId(): number {return this.entityId_;}@@ -167,6 +185,19 @@ export class DeleteEntityCommand extends BaseCommand {}}+ serialize(): SerializedCommand {+ return {+ type: this.type,+ data: { entityId: this.entityId_ },+ };+ }++ static {+ CommandRegistry.register('delete_entity', (data, scene, entityMap) =>+ new DeleteEntityCommand(scene, entityMap, data.entityId as number),+ );+ }+private collectDescendants(entityId: number): EntityData[] {const result: EntityData[] = [];const entity = this.entityMap_.get(entityId);@@ -220,6 +251,23 @@ export class ReparentCommand extends BaseCommand {});}+ serialize(): SerializedCommand {+ return {+ type: this.type,+ data: { entityId: this.entityId_, newParent: this.newParent_ },+ };+ }++ static {+ CommandRegistry.register('reparent', (data, scene, entityMap) =>+ new ReparentCommand(+ scene, entityMap,+ data.entityId as number,+ (data.newParent as number | null) ?? null,+ ),+ );+ }+private setParent(newParent: number | null): void {const entity = this.entityMap_.get(this.entityId_);if (!entity) return;@@ -287,6 +335,28 @@ export class MoveEntityCommand extends BaseCommand {});}+ serialize(): SerializedCommand {+ return {+ type: this.type,+ data: {+ entityId: this.entityId_,+ newParent: this.newParent_,+ newIndex: this.newIndex_,+ },+ };+ }++ static {+ CommandRegistry.register('move_entity', (data, scene, entityMap) =>+ new MoveEntityCommand(+ scene, entityMap,+ data.entityId as number,+ (data.newParent as number | null) ?? null,+ data.newIndex as number,+ ),+ );+ }+private computeIndex(parent: number | null): number {if (parent !== null) {const parentData = this.entityMap_.get(parent);@@ -378,6 +448,28 @@ export class AddComponentCommand extends BaseCommand {action: isUndo ? 'removed' : 'added',});}++ serialize(): SerializedCommand {+ return {+ type: this.type,+ data: {+ entityId: this.entityId_,+ componentType: this.componentType_,+ componentData: this.componentData_,+ },+ };+ }++ static {+ CommandRegistry.register('add_component', (data, scene, entityMap) =>+ new AddComponentCommand(+ scene, entityMap,+ data.entityId as number,+ data.componentType as string,+ data.componentData as Record<string, unknown>,+ ),+ );+ }}// =============================================================================@@ -429,6 +521,23 @@ export class RemoveComponentCommand extends BaseCommand {action: isUndo ? 'added' : 'removed',});}++ serialize(): SerializedCommand {+ return {+ type: this.type,+ data: { entityId: this.entityId_, componentType: this.componentType_ },+ };+ }++ static {+ CommandRegistry.register('remove_component', (data, scene, entityMap) =>+ new RemoveComponentCommand(+ scene, entityMap,+ data.entityId as number,+ data.componentType as string,+ ),+ );+ }}// =============================================================================@@ -458,6 +567,28 @@ export class ReorderComponentCommand extends BaseCommand {this.swap(this.toIndex_, this.fromIndex_);}+ serialize(): SerializedCommand {+ return {+ type: this.type,+ data: {+ entityId: this.entityId_,+ fromIndex: this.fromIndex_,+ toIndex: this.toIndex_,+ },+ };+ }++ static {+ CommandRegistry.register('reorder_component', (data, scene, entityMap) =>+ new ReorderComponentCommand(+ scene, entityMap,+ data.entityId as number,+ data.fromIndex as number,+ data.toIndex as number,+ ),+ );+ }+private swap(from: number, to: number): void {const entity = this.entityMap_.get(this.entityId_);if (!entity) return;diff --git a/editor/src/commands/PropertyCommand.ts b/editor/src/commands/PropertyCommand.tsindex cf1c4229a..0ed213882 100644--- a/editor/src/commands/PropertyCommand.ts+++ b/editor/src/commands/PropertyCommand.ts@@ -5,7 +5,7 @@import type { Entity } from 'esengine';import type { SceneData, EntityData } from '../types/SceneTypes';-import { BaseCommand, type ChangeEmitter, type Command } from './Command';+import { BaseCommand, CommandRegistry, type ChangeEmitter, type Command, type SerializedCommand } from './Command';// =============================================================================// Constants@@ -73,6 +73,19 @@ export class PropertyCommand extends BaseCommand {});}+ serialize(): SerializedCommand {+ return {+ type: this.type,+ data: {+ entity: this.entity_ as number,+ componentType: this.componentType_,+ propertyName: this.propertyName_,+ oldValue: this.oldValue_,+ newValue: this.newValue_,+ },+ };+ }+get entity(): number {return this.entity_ as number;}@@ -85,6 +98,19 @@ export class PropertyCommand extends BaseCommand {return this.propertyName_;}+ static {+ CommandRegistry.register('property', (data, scene, entityMap) =>+ new PropertyCommand(+ scene, entityMap,+ data.entity as number,+ data.componentType as string,+ data.propertyName as string,+ data.oldValue,+ data.newValue,+ ),+ );+ }+private setPropertyValue(value: unknown): void {const entityData = this.entityMap_.get(this.entity_ as number);if (!entityData) return;diff --git a/editor/src/commands/RenameEntityCommand.ts b/editor/src/commands/RenameEntityCommand.tsindex c4d983bcf..af3298187 100644--- a/editor/src/commands/RenameEntityCommand.ts+++ b/editor/src/commands/RenameEntityCommand.ts@@ -1,6 +1,6 @@import type { Entity } from 'esengine';import type { EntityData, SceneData } from '../types/SceneTypes';-import { BaseCommand, type Command } from './Command';+import { BaseCommand, CommandRegistry, type Command, type SerializedCommand } from './Command';const MERGE_WINDOW_MS = 500;@@ -44,6 +44,28 @@ export class RenameEntityCommand extends BaseCommand {);}+ serialize(): SerializedCommand {+ return {+ type: this.type,+ data: {+ entity: this.entity_ as number,+ oldName: this.oldName_,+ newName: this.newName_,+ },+ };+ }++ static {+ CommandRegistry.register('rename_entity', (data, scene, entityMap) =>+ new RenameEntityCommand(+ scene, entityMap,+ data.entity as number,+ data.oldName as string,+ data.newName as string,+ ),+ );+ }+private setName(name: string): void {const entityData = this.entityMap_.get(this.entity_ as number);if (entityData) {diff --git a/editor/src/commands/ToggleVisibilityCommand.ts b/editor/src/commands/ToggleVisibilityCommand.tsindex 9cb5c7ade..5acfd4b77 100644--- a/editor/src/commands/ToggleVisibilityCommand.ts+++ b/editor/src/commands/ToggleVisibilityCommand.ts@@ -1,5 +1,5 @@import type { EntityData, SceneData } from '../types/SceneTypes';-import { BaseCommand, type ChangeEmitter } from './Command';+import { BaseCommand, CommandRegistry, type ChangeEmitter, type SerializedCommand } from './Command';export class ToggleVisibilityCommand extends BaseCommand {readonly type = 'toggle_visibility';@@ -54,6 +54,19 @@ export class ToggleVisibilityCommand extends BaseCommand {}}+ serialize(): SerializedCommand {+ return {+ type: this.type,+ data: { entityId: this.entityId_ },+ };+ }++ static {+ CommandRegistry.register('toggle_visibility', (data, scene, entityMap) =>+ new ToggleVisibilityCommand(scene, entityMap, data.entityId as number),+ );+ }+private captureVisibilityStates(entityId: number): void {const entityData = this.entityMap_.get(entityId);if (!entityData) return;diff --git a/editor/src/commands/index.ts b/editor/src/commands/index.tsindex e08b1dba7..9a6bb00cb 100644--- a/editor/src/commands/index.ts+++ b/editor/src/commands/index.ts@@ -3,7 +3,10 @@* @brief Command system exports*/-export { type Command, type ChangeEmitter, BaseCommand } from './Command';+export {+ type Command, type ChangeEmitter, type SerializedCommand,+ type CommandDeserializer, CommandRegistry, BaseCommand,+} from './Command';export { PropertyCommand } from './PropertyCommand';export {CreateEntityCommand,diff --git a/editor/src/multiwindow/CommandReplicator.ts b/editor/src/multiwindow/CommandReplicator.tsnew file mode 100644index 000000000..bf108d420--- /dev/null+++ b/editor/src/multiwindow/CommandReplicator.ts@@ -0,0 +1,94 @@+import type { EditorStore } from '../store/EditorStore';+import type { Command } from '../commands/Command';+import { emit, listen, type UnlistenFn } from '@tauri-apps/api/event';+import {+ CHANNEL_CMD_EXECUTED,+ CHANNEL_CMD_REQUEST,+ CHANNEL_CMD_SNAPSHOT,+ type CmdExecutedMessage,+ type CmdRequestMessage,+ type CmdSnapshotMessage,+} from './protocol';+import { CommandRegistry } from '../commands/Command';++export class CommandReplicator {+ private version_ = 0;+ private store_: EditorStore;+ private unlisteners_: UnlistenFn[] = [];+ private started_ = false;+ private originalExecuteCommand_: ((cmd: Command) => void) | null = null;++ constructor(store: EditorStore) {+ this.store_ = store;+ }++ async start(): Promise<void> {+ if (this.started_) return;+ this.started_ = true;++ this.originalExecuteCommand_ = this.store_.executeCommand.bind(this.store_);+ this.store_.executeCommand = (cmd: Command) => {+ this.originalExecuteCommand_!(cmd);+ this.broadcastCommand(cmd);+ };++ const unlistenRequest = await listen<CmdRequestMessage>(CHANNEL_CMD_REQUEST, (event) => {+ this.handleCommandRequest(event.payload);+ });++ const unlistenSnapshot = await listen<string>(CHANNEL_CMD_SNAPSHOT + ':request', () => {+ this.sendSnapshot();+ });++ this.unlisteners_.push(unlistenRequest, unlistenSnapshot);+ }++ private broadcastCommand(cmd: Command): void {+ const serialized = cmd.serialize();+ if (!serialized) {+ this.version_++;+ this.sendSnapshot();+ return;+ }++ this.version_++;+ const msg: CmdExecutedMessage = {+ version: this.version_,+ serialized,+ };+ emit(CHANNEL_CMD_EXECUTED, msg);+ }++ private handleCommandRequest(payload: CmdRequestMessage): void {+ const cmd = CommandRegistry.deserialize(+ payload.serialized,+ this.store_.scene,+ this.store_.entityMap_,+ );+ if (cmd) {+ this.originalExecuteCommand_!(cmd);+ this.broadcastCommand(cmd);+ }+ }++ private sendSnapshot(): void {+ const msg: CmdSnapshotMessage = {+ scene: JSON.parse(JSON.stringify(this.store_.scene)),+ selectedEntities: Array.from(this.store_.selectedEntities),+ version: this.version_,+ };+ emit(CHANNEL_CMD_SNAPSHOT, msg);+ }++ dispose(): void {+ if (this.originalExecuteCommand_) {+ this.store_.executeCommand = this.originalExecuteCommand_;+ this.originalExecuteCommand_ = null;+ }+ for (const unlisten of this.unlisteners_) {+ unlisten();+ }+ this.unlisteners_ = [];+ this.started_ = false;+ }+}diff --git a/editor/src/multiwindow/ReplicaStore.ts b/editor/src/multiwindow/ReplicaStore.tsnew file mode 100644index 000000000..38a8edc70--- /dev/null+++ b/editor/src/multiwindow/ReplicaStore.ts@@ -0,0 +1,141 @@+import type { EntityData, SceneData } from '../types/SceneTypes';+import type { EditorState, EditorListener, AssetSelection, DirtyFlag } from '../store/EditorStore';+import { CommandRegistry, type SerializedCommand } from '../commands/Command';+import { emit, listen, type UnlistenFn } from '@tauri-apps/api/event';+import {+ CHANNEL_CMD_EXECUTED,+ CHANNEL_CMD_REQUEST,+ CHANNEL_CMD_SNAPSHOT,+ type CmdExecutedMessage,+ type CmdSnapshotMessage,+} from './protocol';++export class ReplicaStore {+ private state_: EditorState;+ private entityMap_ = new Map<number, EntityData>();+ private version_ = 0;+ private listeners_ = new Set<EditorListener>();+ private unlisteners_: UnlistenFn[] = [];+ private pendingNotify_ = false;+ private dirtyFlags_ = new Set<DirtyFlag>();++ constructor() {+ this.state_ = {+ scene: { version: '1', name: 'Untitled', entities: [] },+ selectedEntities: new Set(),+ selectedAsset: null,+ isDirty: false,+ filePath: null,+ };+ }++ get scene(): SceneData {+ return this.state_.scene;+ }++ get selectedEntities(): ReadonlySet<number> {+ return this.state_.selectedEntities;+ }++ get selectedAsset(): AssetSelection | null {+ return this.state_.selectedAsset;+ }++ get entityMap(): ReadonlyMap<number, EntityData> {+ return this.entityMap_;+ }++ async connect(): Promise<void> {+ const unlistenCmd = await listen<CmdExecutedMessage>(CHANNEL_CMD_EXECUTED, (event) => {+ this.handleCommandExecuted(event.payload);+ });++ const unlistenSnapshot = await listen<CmdSnapshotMessage>(CHANNEL_CMD_SNAPSHOT, (event) => {+ this.handleSnapshot(event.payload);+ });++ this.unlisteners_.push(unlistenCmd, unlistenSnapshot);++ emit(CHANNEL_CMD_SNAPSHOT + ':request', {});+ }++ subscribe(listener: EditorListener): () => void {+ this.listeners_.add(listener);+ return () => this.listeners_.delete(listener);+ }++ sendCommand(serialized: SerializedCommand): void {+ emit(CHANNEL_CMD_REQUEST, { serialized });+ }++ getEntityData(entityId: number): EntityData | undefined {+ return this.entityMap_.get(entityId);+ }++ dispose(): void {+ for (const unlisten of this.unlisteners_) {+ unlisten();+ }+ this.unlisteners_ = [];+ this.listeners_.clear();+ }++ private handleCommandExecuted(msg: CmdExecutedMessage): void {+ if (msg.version !== this.version_ + 1) {+ emit(CHANNEL_CMD_SNAPSHOT + ':request', {});+ return;+ }++ this.version_ = msg.version;++ const cmd = CommandRegistry.deserialize(+ msg.serialized,+ this.state_.scene,+ this.entityMap_,+ );++ if (!cmd) {+ emit(CHANNEL_CMD_SNAPSHOT + ':request', {});+ return;+ }++ cmd.execute();+ cmd.updateEntityMap(this.entityMap_, false);++ if (cmd.structural) {+ this.rebuildEntityMap();+ this.notify('hierarchy');+ } else {+ this.notify('scene');+ }+ }++ private handleSnapshot(msg: CmdSnapshotMessage): void {+ this.state_.scene = msg.scene;+ this.state_.selectedEntities = new Set(msg.selectedEntities);+ this.version_ = msg.version;+ this.rebuildEntityMap();+ this.notify('hierarchy');+ }++ private rebuildEntityMap(): void {+ this.entityMap_.clear();+ for (const entity of this.state_.scene.entities) {+ this.entityMap_.set(entity.id, entity);+ }+ }++ private notify(flag: DirtyFlag): void {+ this.dirtyFlags_.add(flag);+ if (this.pendingNotify_) return;+ this.pendingNotify_ = true;+ requestAnimationFrame(() => {+ this.pendingNotify_ = false;+ const flags = new Set(this.dirtyFlags_);+ this.dirtyFlags_.clear();+ for (const listener of this.listeners_) {+ listener(this.state_, flags);+ }+ });+ }+}diff --git a/editor/src/multiwindow/index.ts b/editor/src/multiwindow/index.tsindex 16df332da..164ce0c5a 100644--- a/editor/src/multiwindow/index.ts+++ b/editor/src/multiwindow/index.ts@@ -1,6 +1,8 @@export { RemoteEditorStore } from './RemoteEditorStore';export { MainWindowBridge } from './MainWindowBridge';export { WindowManager } from './WindowManager';+export { CommandReplicator } from './CommandReplicator';+export { ReplicaStore } from './ReplicaStore';export {CHANNEL_STATE,@@ -19,6 +21,12 @@ export {type OutputType,type OutputMessage,type ProfilerStatsMessage,+ CHANNEL_CMD_EXECUTED,+ CHANNEL_CMD_REQUEST,+ CHANNEL_CMD_SNAPSHOT,+ type CmdExecutedMessage,+ type CmdRequestMessage,+ type CmdSnapshotMessage,} from './protocol';export { serializeEditorState } from './stateSerializer';diff --git a/editor/src/multiwindow/protocol.ts b/editor/src/multiwindow/protocol.tsindex 4278e508d..536234371 100644--- a/editor/src/multiwindow/protocol.ts+++ b/editor/src/multiwindow/protocol.ts@@ -19,6 +19,9 @@ export const CHANNEL_EXTENSIONS_DATA = 'editor:extensions-data';export const CHANNEL_EXTENSIONS_TOGGLE = 'editor:extensions-toggle';export const CHANNEL_EXTENSIONS_RELOAD = 'editor:extensions-reload';export const CHANNEL_EXTENSIONS_REQUEST = 'editor:extensions-request';+export const CHANNEL_CMD_EXECUTED = 'editor:cmd-executed';+export const CHANNEL_CMD_REQUEST = 'editor:cmd-request';+export const CHANNEL_CMD_SNAPSHOT = 'editor:cmd-snapshot';// =============================================================================// State Snapshot@@ -151,3 +154,22 @@ export interface ExtensionToggleMessage {}export interface ExtensionReloadMessage {}++// =============================================================================+// Command Replication Messages+// =============================================================================++export interface CmdExecutedMessage {+ version: number;+ serialized: import('../commands/Command').SerializedCommand;+}++export interface CmdRequestMessage {+ serialized: import('../commands/Command').SerializedCommand;+}++export interface CmdSnapshotMessage {+ scene: SceneData;+ selectedEntities: number[];+ version: number;+}diff --git a/editor/src/panels/PanelRegistry.ts b/editor/src/panels/PanelRegistry.tsindex 75cac626a..e6e3ce069 100644--- a/editor/src/panels/PanelRegistry.ts+++ b/editor/src/panels/PanelRegistry.ts@@ -9,7 +9,6 @@ export interface PanelDescriptor {icon?: string;position: PanelPosition;defaultVisible?: boolean;- detachOnly?: boolean;order?: number;factory: PanelFactory;}@@ -39,5 +38,5 @@ export function getAllPanels(): PanelDescriptor[] {}export function getPanelsByPosition(position: PanelPosition): PanelDescriptor[] {- return getAllPanels().filter(p => p.position === position && !p.detachOnly);+ return getAllPanels().filter(p => p.position === position);}diff --git a/editor/src/panels/builtinPanels.ts b/editor/src/panels/builtinPanels.tsindex c00f3869d..270641162 100644--- a/editor/src/panels/builtinPanels.ts+++ b/editor/src/panels/builtinPanels.ts@@ -92,7 +92,7 @@ export function registerBuiltinPanels(registrar: PluginRegistrar, options: Builttitle: 'Timeline',icon: icons.film(PANEL_ICON_SIZE),position: 'bottom',- detachOnly: true,+ defaultVisible: false,order: 2,factory: (c) => ({ instance: new TimelinePanel(c, getEditorStore()) }),});@@ -102,7 +102,7 @@ export function registerBuiltinPanels(registrar: PluginRegistrar, options: Builttitle: 'Profiler',icon: icons.gauge(PANEL_ICON_SIZE),position: 'bottom',- detachOnly: true,+ defaultVisible: false,order: 99,factory: (c) => ({ instance: new ProfilerPanel(c) }),});@@ -112,7 +112,7 @@ export function registerBuiltinPanels(registrar: PluginRegistrar, options: Builttitle: 'Frame Debugger',icon: icons.gauge(PANEL_ICON_SIZE),position: 'bottom',- detachOnly: true,+ defaultVisible: false,order: 3,factory: (c) => ({ instance: new FrameDebuggerPanel(c) }),});@@ -122,7 +122,7 @@ export function registerBuiltinPanels(registrar: PluginRegistrar, options: Builttitle: 'Extensions',icon: icons.package(PANEL_ICON_SIZE),position: 'bottom',- detachOnly: true,+ defaultVisible: false,order: 4,factory: (c) => ({ instance: new ExtensionsPanel(c) }),});