Skip to content

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.

refactor: update editor scene management and UI integration

esengine5ae0e2cdb07c
diff --git a/editor/src/bounds/TextBoundsProvider.ts b/editor/src/bounds/TextBoundsProvider.ts
index e298fc5b3..eec7bd2d3 100644
--- a/editor/src/bounds/TextBoundsProvider.ts
+++ b/editor/src/bounds/TextBoundsProvider.ts
@@ -3,6 +3,7 @@
* @brief Bounds provider for Text component
*/
+import { DEFAULT_FONT_SIZE, DEFAULT_FONT_FAMILY, DEFAULT_LINE_HEIGHT } from 'esengine';
import type { Bounds, BoundsProvider } from './BoundsProvider';
let measureCtx: CanvasRenderingContext2D | null = null;
@@ -19,9 +20,9 @@ export const textBoundsProvider: BoundsProvider = {
const content = data?.content;
if (!content) return null;
- const fontSize = data.fontSize ?? 24;
- const fontFamily = data.fontFamily ?? 'Arial';
- const lineHeight = data.lineHeight ?? 1.2;
+ const fontSize = data.fontSize ?? DEFAULT_FONT_SIZE;
+ const fontFamily = data.fontFamily ?? DEFAULT_FONT_FAMILY;
+ const lineHeight = data.lineHeight ?? DEFAULT_LINE_HEIGHT;
const maxWidthLimit = data.maxWidth ?? 0;
const ctx = getContext();
diff --git a/editor/src/gizmos/builtinGizmos.ts b/editor/src/gizmos/builtinGizmos.ts
index 137b170de..8f3b5397e 100644
--- a/editor/src/gizmos/builtinGizmos.ts
+++ b/editor/src/gizmos/builtinGizmos.ts
@@ -8,6 +8,9 @@ const GIZMO_COLORS = {
y: '#2ecc71',
xy: '#f1c40f',
hover: '#ffffff',
+ selection: '#00aaff',
+ handleStroke: '#000',
+ refLine: 'rgba(100, 100, 100, 0.5)',
};
const GIZMO_SIZE = 80;
@@ -292,7 +295,7 @@ export function createRotateGizmo(): GizmoDescriptor {
const euler = quatToEuler(quat);
const angleRad = -euler.z * Math.PI / 180;
- ctx.strokeStyle = 'rgba(100, 100, 100, 0.5)';
+ ctx.strokeStyle = GIZMO_COLORS.refLine;
ctx.lineWidth = lineWidth;
ctx.beginPath();
ctx.moveTo(0, 0);
@@ -305,14 +308,14 @@ export function createRotateGizmo(): GizmoDescriptor {
ctx.arc(0, 0, radius, 0, Math.PI * 2);
ctx.stroke();
- ctx.strokeStyle = '#00aaff';
+ ctx.strokeStyle = GIZMO_COLORS.selection;
ctx.lineWidth = lineWidth * 2;
ctx.beginPath();
ctx.moveTo(0, 0);
ctx.lineTo(Math.cos(angleRad) * radius, Math.sin(angleRad) * radius);
ctx.stroke();
- ctx.fillStyle = '#00aaff';
+ ctx.fillStyle = GIZMO_COLORS.selection;
ctx.beginPath();
ctx.arc(Math.cos(angleRad) * radius, Math.sin(angleRad) * radius, handleSize, 0, Math.PI * 2);
ctx.fill();
@@ -658,7 +661,7 @@ export function createRectGizmo(): GizmoDescriptor {
ctx.fillStyle = isHovered ? GIZMO_COLORS.hover : (isCorner ? GIZMO_COLORS.xy : GIZMO_COLORS.x);
ctx.fillRect(handle.x - handleSize, handle.y - handleSize, handleSize * 2, handleSize * 2);
- ctx.strokeStyle = '#000';
+ ctx.strokeStyle = GIZMO_COLORS.handleStroke;
ctx.lineWidth = 1 / zoom;
ctx.strokeRect(handle.x - handleSize, handle.y - handleSize, handleSize * 2, handleSize * 2);
}
diff --git a/editor/src/math/Transform.ts b/editor/src/math/Transform.ts
index 3afcd691f..ae2992879 100644
--- a/editor/src/math/Transform.ts
+++ b/editor/src/math/Transform.ts
@@ -3,7 +3,7 @@
* @brief Math utilities for transform calculations
*/
-import { computeUIRectLayout, type LayoutRect } from 'esengine';
+import { computeUIRectLayout, DEFAULT_SPRITE_SIZE, type LayoutRect } from 'esengine';
// =============================================================================
// Types
@@ -209,7 +209,7 @@ const DEFAULT_UIRECT: UIRectLike = {
anchorMax: { x: 0.5, y: 0.5 },
offsetMin: { x: 0, y: 0 },
offsetMax: { x: 0, y: 0 },
- size: { x: 100, y: 100 },
+ size: { ...DEFAULT_SPRITE_SIZE },
pivot: { x: 0.5, y: 0.5 },
};
@@ -252,7 +252,7 @@ export function getEntitySize(entity: EntityDataLike): { x: number; y: number }
return sprite.data.size as { x: number; y: number };
}
- return { x: 100, y: 100 };
+ return { ...DEFAULT_SPRITE_SIZE };
}
// =============================================================================
@@ -346,16 +346,16 @@ function computeScreenSpaceTransform(
const isRoot = i === 0;
if (isRoot) {
- resultX = layout.centerX;
- resultY = layout.centerY;
+ resultX = layout.originX;
+ resultY = layout.originY;
} else {
- resultX = layout.centerX - parentCenterX;
- resultY = layout.centerY - parentCenterY;
+ resultX = layout.originX - parentCenterX;
+ resultY = layout.originY - parentCenterY;
}
parentRect = layout.rect;
- parentCenterX = layout.centerX;
- parentCenterY = layout.centerY;
+ parentCenterX = layout.originX;
+ parentCenterY = layout.originY;
}
return {
@@ -398,9 +398,11 @@ export function computeAdjustedLocalTransform(
entity: EntityDataLike,
getParentEntity: (id: number) => EntityDataLike | undefined,
allEntities?: EntityDataLike[],
+ cachedCanvasRect?: LayoutRect | null,
): Transform {
- if (allEntities && isInScreenSpaceHierarchy(entity, getParentEntity)) {
- const canvasRect = findCanvasWorldRect(allEntities);
+ if (isInScreenSpaceHierarchy(entity, getParentEntity)) {
+ const canvasRect = cachedCanvasRect
+ ?? (allEntities ? findCanvasWorldRect(allEntities) : null);
if (canvasRect) {
return computeScreenSpaceTransform(entity, getParentEntity, canvasRect);
}
diff --git a/editor/src/panels/hierarchy/HierarchyTree.ts b/editor/src/panels/hierarchy/HierarchyTree.ts
index e3b8f9c8b..d890941bc 100644
--- a/editor/src/panels/hierarchy/HierarchyTree.ts
+++ b/editor/src/panels/hierarchy/HierarchyTree.ts
@@ -55,28 +55,41 @@ export function expandAncestors(state: HierarchyState, entityId: Entity): void {
}
}
+const ENTITY_ICON_PRIORITY: Array<[string, (size: number) => string]> = [
+ ['Camera', icons.camera],
+ ['SpineAnimation', icons.bone],
+ ['Text', icons.type],
+ ['BitmapText', icons.type],
+ ['TextInput', icons.type],
+ ['Sprite', icons.image],
+];
+
export function getEntityIcon(entity: EntityData): string {
if (entity.prefab?.isRoot) return icons.package(12);
- const hasCamera = entity.components.some(c => c.type === 'Camera');
- const hasSprite = entity.components.some(c => c.type === 'Sprite');
- const hasText = entity.components.some(c => c.type === 'Text');
- const hasBitmapText = entity.components.some(c => c.type === 'BitmapText');
- const hasTextInput = entity.components.some(c => c.type === 'TextInput');
- const hasSpine = entity.components.some(c => c.type === 'SpineAnimation');
-
- if (hasCamera) return icons.camera(12);
- if (hasSpine) return icons.bone(12);
- if (hasText || hasBitmapText || hasTextInput) return icons.type(12);
- if (hasSprite) return icons.image(12);
- return icons.box(12);
+ let bestIdx = ENTITY_ICON_PRIORITY.length;
+ for (const comp of entity.components) {
+ const idx = ENTITY_ICON_PRIORITY.findIndex(([type]) => type === comp.type);
+ if (idx !== -1 && idx < bestIdx) {
+ bestIdx = idx;
+ if (bestIdx === 0) break;
+ }
+ }
+
+ return bestIdx < ENTITY_ICON_PRIORITY.length
+ ? ENTITY_ICON_PRIORITY[bestIdx][1](12)
+ : icons.box(12);
}
+const ENTITY_TYPE_PRIORITY: Array<[string, string]> = [
+ ['Camera', 'Camera'],
+ ['SpineAnimation', 'Spine'],
+];
+
export function getEntityType(entity: EntityData): string {
- const hasCamera = entity.components.some(c => c.type === 'Camera');
- const hasSpine = entity.components.some(c => c.type === 'SpineAnimation');
- if (hasCamera) return 'Camera';
- if (hasSpine) return 'Spine';
+ for (const [compType, label] of ENTITY_TYPE_PRIORITY) {
+ if (entity.components.some(c => c.type === compType)) return label;
+ }
return 'Entity';
}
diff --git a/editor/src/panels/inspector/InspectorHelpers.ts b/editor/src/panels/inspector/InspectorHelpers.ts
index 3b2a59cf0..87b51e599 100644
--- a/editor/src/panels/inspector/InspectorHelpers.ts
+++ b/editor/src/panels/inspector/InspectorHelpers.ts
@@ -122,37 +122,29 @@ export function getAssetServer(): EditorAssetServer | null {
return editor?.assetServer ?? null;
}
+const COMPONENT_ICON_MAP = new Map<string, (size: number) => string>([
+ ['LocalTransform', icons.move],
+ ['WorldTransform', icons.move],
+ ['Sprite', icons.image],
+ ['NinePatch', icons.image],
+ ['Camera', icons.camera],
+ ['Text', icons.type],
+ ['TextInput', icons.type],
+ ['RigidBody', icons.zap],
+ ['BoxCollider', icons.zap],
+ ['CircleCollider', icons.zap],
+ ['CapsuleCollider', icons.zap],
+ ['SpineAnimation', icons.film],
+ ['Button', icons.scan],
+ ['Canvas', icons.scan],
+ ['UIRect', icons.scan],
+ ['LayoutGroup', icons.layoutGrid],
+ ['UIMask', icons.shield],
+]);
+
export function getComponentIcon(type: string): string {
- switch (type) {
- case 'LocalTransform':
- case 'WorldTransform':
- return icons.move(14);
- case 'Sprite':
- case 'NinePatch':
- return icons.image(14);
- case 'Camera':
- return icons.camera(14);
- case 'Text':
- case 'TextInput':
- return icons.type(14);
- case 'RigidBody':
- case 'BoxCollider':
- case 'CircleCollider':
- case 'CapsuleCollider':
- return icons.zap(14);
- case 'SpineAnimation':
- return icons.film(14);
- case 'Button':
- case 'Canvas':
- case 'UIRect':
- return icons.scan(14);
- case 'LayoutGroup':
- return icons.layoutGrid(14);
- case 'UIMask':
- return icons.shield(14);
- default:
- return icons.settings(14);
- }
+ const iconFn = COMPONENT_ICON_MAP.get(type);
+ return iconFn ? iconFn(14) : icons.settings(14);
}
export function renderError(container: HTMLElement, message: string): void {
diff --git a/editor/src/panels/scene-view/SceneViewPanel.ts b/editor/src/panels/scene-view/SceneViewPanel.ts
index 115d1a7aa..9d4840131 100644
--- a/editor/src/panels/scene-view/SceneViewPanel.ts
+++ b/editor/src/panels/scene-view/SceneViewPanel.ts
@@ -1,5 +1,5 @@
import type { Entity, App } from 'esengine';
-import { Renderer, computeUIRectLayout } from 'esengine';
+import { Renderer, computeUIRectLayout, DEFAULT_SPRITE_SIZE } from 'esengine';
import type { SpineModuleController } from 'esengine/spine';
import type { EditorStore } from '../../store/EditorStore';
import type { EditorBridge } from '../../bridge/EditorBridge';
@@ -227,7 +227,7 @@ export class SceneViewPanel {
anchorMin, anchorMax,
data.offsetMin ?? { x: 0, y: 0 },
data.offsetMax ?? { x: 0, y: 0 },
- data.size ?? { x: 100, y: 100 },
+ data.size ?? DEFAULT_SPRITE_SIZE,
parentRect,
);
return { width: Math.abs(layout.width), height: Math.abs(layout.height) };
@@ -1120,8 +1120,8 @@ export class SceneViewPanel {
const pos = worldTransform.position;
const scale = worldTransform.scale;
- let w = 50;
- let h = 50;
+ let w = DEFAULT_SPRITE_SIZE.x / 2;
+ let h = DEFAULT_SPRITE_SIZE.y / 2;
let color: { r: number; g: number; b: number; a: number } | null = null;
const hasSprite = !!sprite;
let textureImg: HTMLImageElement | null = null;
diff --git a/editor/src/preview/PreviewService.ts b/editor/src/preview/PreviewService.ts
index 198ae72c2..ed98e36db 100644
--- a/editor/src/preview/PreviewService.ts
+++ b/editor/src/preview/PreviewService.ts
@@ -7,6 +7,7 @@ import type { SceneData } from '../types/SceneTypes';
import type { NativeFS } from '../scripting/types';
import type { TextureMetadata } from '../types/TextureMetadata';
import { getMetaFilePath, parseTextureMetadata } from '../types/TextureMetadata';
+import { getComponentAssetFields } from 'esengine';
import { getEditorContext } from '../context/EditorContext';
import { getAssetLibrary } from '../asset/AssetLibrary';
import { getProjectDir } from '../utils/path';
@@ -161,7 +162,8 @@ export class PreviewService {
for (const entity of scene.entities) {
for (const component of entity.components) {
- if (component.type !== 'Sprite' && component.type !== 'UIMask') continue;
+ const assetFields = getComponentAssetFields(component.type);
+ if (!assetFields.includes('texture')) continue;
const texturePath = component.data.texture as string | undefined;
if (!texturePath || processedPaths.has(texturePath)) continue;
processedPaths.add(texturePath);
diff --git a/editor/src/scene/EditorSceneManager.ts b/editor/src/scene/EditorSceneManager.ts
index b39082267..e549f155d 100644
--- a/editor/src/scene/EditorSceneManager.ts
+++ b/editor/src/scene/EditorSceneManager.ts
@@ -13,12 +13,23 @@ import {
Renderer,
INVALID_TEXTURE,
INVALID_FONT,
+ INVALID_MATERIAL,
TextRenderer,
TextAlign,
TextVerticalAlign,
TextOverflow,
UIRect,
UIMask,
+ FillDirection,
+ applyDirectionalFill,
+ syncFillSpriteSize,
+ computeFillAnchors,
+ computeHandleAnchors,
+ DEFAULT_SPRITE_SIZE,
+ DEFAULT_FONT_FAMILY,
+ DEFAULT_FONT_SIZE,
+ DEFAULT_LINE_HEIGHT,
+ DEFAULT_SPINE_SKIN,
type SceneComponentData,
type TextData,
type BitmapTextData,
@@ -38,9 +49,40 @@ import {
type Transform,
getUIRectFromEntity,
computeAdjustedLocalTransform,
+ findCanvasWorldRect,
transformToMatrix4x4,
} from '../math/Transform';
+
+const TEXT_RENDER_LAYER = 25;
+
+const BitmapTextAlign = {
+ Left: 0,
+ Center: 1,
+ Right: 2,
+} as const;
+
+const SPRITE_SUPPRESSING_COMPONENTS = new Set(['Text', 'SpineAnimation']);
+
+const EDITOR_IGNORED_COMPONENTS = new Set([
+ 'Interactable',
+ 'Button',
+ 'ScreenSpace',
+ 'Slider',
+ 'ProgressBar',
+ 'Toggle',
+ 'ScrollView',
+ 'Dropdown',
+ 'LayoutGroup',
+ 'Image',
+ 'Draggable',
+ 'Focusable',
+ 'SafeArea',
+ 'ListView',
+ 'Canvas',
+ 'Camera',
+]);
+
// =============================================================================
// EditorSceneManager
// =============================================================================
@@ -64,6 +106,7 @@ export class EditorSceneManager {
private spineCurrentState_ = new Map<number, { animation: string; skin: string; loop: boolean }>();
private spineReadyListeners_ = new Set<(entityId: number) => void>();
private updatingEntities_ = new Map<number, Promise<void>>();
+ private cachedCanvasRect_: import('esengine').LayoutRect | null | undefined;
constructor(module: ESEngineModule, pathResolver: AssetPathResolver) {
this.module_ = module;
@@ -135,41 +178,134 @@ export class EditorSceneManager {
this.clear();
this.sceneData_ = scene;
+
for (const entityData of scene.entities) {
this.entityDataMap_.set(entityData.id, entityData);
+ this.entityMap_.set(entityData.id, this.world_.spawn());
}
- for (const entityData of scene.entities) {
- await this.loadEntity(entityData);
- }
+ this.cachedCanvasRect_ = findCanvasWorldRect(
+ Array.from(this.entityDataMap_.values()),
+ );
+ const loadPromises: Promise<void>[] = [];
for (const entityData of scene.entities) {
if (entityData.parent !== null) {
- const entity = this.entityMap_.get(entityData.id);
+ const entity = this.entityMap_.get(entityData.id)!;
const parentEntity = this.entityMap_.get(entityData.parent);
- if (entity !== undefined && parentEntity !== undefined) {
+ if (parentEntity !== undefined) {
this.world_.setParent(entity, parentEntity);
}
}
+ if (entityData.visible !== false) {
+ loadPromises.push(this.loadEntityComponents(entityData));
+ }
}
+ await Promise.all(loadPromises);
+
+ this.applyFillStates();
+
+ this.cachedCanvasRect_ = undefined;
}
- private async loadEntity(entityData: EntityData): Promise<void> {
- let entity = this.entityMap_.get(entityData.id);
- if (entity !== undefined) {
- if (this.world_.has(entity, Sprite)) {
- this.world_.remove(entity, Sprite);
+ private applyFillStates(): void {
+ for (const [_, entityData] of this.entityDataMap_) {
+ for (const comp of entityData.components) {
+ if (comp.type === 'Slider') {
+ this.applySliderFillState(entityData, comp.data);
+ break;
+ }
+ if (comp.type === 'ProgressBar') {
+ this.applyProgressBarFillState(entityData, comp.data);
+ break;
+ }
}
- if (this.world_.has(entity, BitmapText)) {
- this.world_.remove(entity, BitmapText);
+ }
+ }
+
+ private applySliderFillState(entityData: EntityData, data: Record<string, any>): void {
+ const value = data.value as number ?? 0;
+ const minValue = data.minValue as number ?? 0;
+ const maxValue = data.maxValue as number ?? 1;
+ const direction = data.direction as number ?? FillDirection.LeftToRight;
+ const fillEntityId = data.fillEntity as number ?? 0;
+ const handleEntityId = data.handleEntity as number ?? 0;
+
+ const range = maxValue - minValue;
+ const normalizedValue = range > 0 ? (value - minValue) / range : 0;
+
+ const parentSize = this.getEntityUIRectSize(entityData);
+ this.applyFillToWorld(fillEntityId, direction, normalizedValue, parentSize.x, parentSize.y);
+ this.applyHandleToWorld(handleEntityId, direction, normalizedValue);
+ }
+
+ private applyProgressBarFillState(entityData: EntityData, data: Record<string, any>): void {
+ const value = Math.max(0, Math.min(1, data.value as number ?? 0));
+ const direction = data.direction as number ?? FillDirection.LeftToRight;
+ const fillEntityId = data.fillEntity as number ?? 0;
+
+ const parentSize = this.getEntityUIRectSize(entityData);
+ this.applyFillToWorld(fillEntityId, direction, value, parentSize.x, parentSize.y);
+ }
+
+ private getEntityUIRectSize(entityData: EntityData): { x: number; y: number } {
+ const uiRectComp = entityData.components.find(c => c.type === 'UIRect');
+ const size = uiRectComp?.data?.size as { x: number; y: number } | undefined;
+ return { x: size?.x ?? 0, y: size?.y ?? 0 };
+ }
+
+ private applyFillToWorld(
+ fillEntityId: number, direction: number, normalizedValue: number,
+ parentW: number, parentH: number,
+ ): void {
+ if (fillEntityId === 0) return;
+ const fillEntity = this.entityMap_.get(fillEntityId);
+ if (fillEntity === undefined) return;
+ applyDirectionalFill(this.world_, fillEntity, direction, normalizedValue);
+ syncFillSpriteSize(this.world_, fillEntity, direction, normalizedValue, parentW, parentH);
+
+ const fillEntityData = this.entityDataMap_.get(fillEntityId);
+ if (fillEntityData) {
+ const uiRectComp = fillEntityData.components.find(c => c.type === 'UIRect');
+ if (uiRectComp) {
+ const anchors = computeFillAnchors(direction, normalizedValue);
+ uiRectComp.data.anchorMin = anchors.anchorMin;
+ uiRectComp.data.anchorMax = anchors.anchorMax;
+ uiRectComp.data.offsetMin = anchors.offsetMin;
+ uiRectComp.data.offsetMax = anchors.offsetMax;
}
- } else {
- entity = this.world_.spawn();
- this.entityMap_.set(entityData.id, entity);
}
+ this.syncEntityTransform(fillEntityId);
+ }
- if (entityData.visible === false) return;
+ private applyHandleToWorld(handleEntityId: number, direction: number, normalizedValue: number): void {
+ if (handleEntityId === 0) return;
+ const handleEntity = this.entityMap_.get(handleEntityId);
+ if (handleEntity === undefined) return;
+ if (!this.world_.has(handleEntity, UIRect)) return;
+ const handleRect = this.world_.get(handleEntity, UIRect) as UIRectData;
+ const anchors = computeHandleAnchors(direction, normalizedValue);
+ handleRect.anchorMin = anchors.anchorMin;
+ handleRect.anchorMax = anchors.anchorMax;
+ handleRect.offsetMin = { x: 0, y: 0 };
+ handleRect.offsetMax = { x: 0, y: 0 };
+ this.world_.insert(handleEntity, UIRect, handleRect);
+
+ const handleEntityData = this.entityDataMap_.get(handleEntityId);
+ if (handleEntityData) {
+ const uiRectComp = handleEntityData.components.find(c => c.type === 'UIRect');
+ if (uiRectComp) {
+ uiRectComp.data.anchorMin = anchors.anchorMin;
+ uiRectComp.data.anchorMax = anchors.anchorMax;
+ uiRectComp.data.offsetMin = { x: 0, y: 0 };
+ uiRectComp.data.offsetMax = { x: 0, y: 0 };
+ }
+ }
+ this.syncEntityTransform(handleEntityId);
+ }
+ private async loadEntityComponents(entityData: EntityData): Promise<void> {
+ const entity = this.entityMap_.get(entityData.id)!;
for (const comp of entityData.components) {
await this.loadComponentWithEditorLogic(entity, comp, entityData.id);
}
@@ -187,9 +323,10 @@ export class EditorSceneManager {
case 'Sprite': {
const entityData = this.entityDataMap_.get(entityId);
- const hasText = entityData?.components.some(c => c.type === 'Text');
- const hasSpine = entityData?.components.some(c => c.type === 'SpineAnimation');
- if (!hasText && !hasSpine) {
+ const suppressed = entityData?.components.some(
+ c => SPRITE_SUPPRESSING_COMPONENTS.has(c.type)
+ );
+ if (!suppressed) {
await this.syncSprite(entity, comp.data, entityId);
}
break;
@@ -216,13 +353,12 @@ export class EditorSceneManager {
case 'TextInput':
this.syncTextInput(entity, comp.data, entityId);
break;
- case 'Interactable':
- case 'Button':
- case 'ScreenSpace':
- break;
default:
- loadComponent(this.world_, entity, comp as SceneComponentData);
+ if (!EDITOR_IGNORED_COMPONENTS.has(comp.type)) {
+ loadComponent(this.world_, entity, comp as SceneComponentData);
+ }
+ break;
}
}
@@ -356,6 +492,17 @@ export class EditorSceneManager {
case 'BitmapText':
if (this.world_.has(entity, BitmapText)) this.world_.remove(entity, BitmapText);
break;
+ case 'UIRect':
+ if (this.world_.has(entity, UIRect)) this.world_.remove(entity, UIRect);
+ break;
+ case 'UIMask':
+ if (this.world_.has(entity, UIMask)) this.world_.remove(entity, UIMask);
+ break;
+ case 'Text':
+ case 'TextInput':
+ this.textRenderer_.release(entity);
+ if (this.world_.has(entity, Sprite)) this.world_.remove(entity, Sprite);
+ break;
case 'SpineAnimation':
this.destroySpineInstance(entityId);
break;
@@ -397,11 +544,9 @@ export class EditorSceneManager {
}
get registry(): CppRegistry {
- const registry = (this.world_ as any).cppRegistry_;
- if (!registry) {
- throw new Error('CppRegistry not connected');
- }
- return registry;
+ const reg = this.world_.getCppRegistry();
+ if (!reg) throw new Error('CppRegistry not connected');
+ return reg;
}
get isBusy(): boolean {
@@ -491,9 +636,9 @@ export class EditorSceneManager {
const metrics = Renderer.measureBitmapText(bt.font, bt.text, bt.fontSize, bt.spacing);
let offsetX = metrics.width / 2;
- if (bt.align === 1) {
+ if (bt.align === BitmapTextAlign.Center) {
offsetX = 0;
- } else if (bt.align === 2) {
+ } else if (bt.align === BitmapTextAlign.Right) {
offsetX = -metrics.width / 2;
}
@@ -593,17 +738,16 @@ export class EditorSceneManager {
}
}
- private syncTransform(entity: Entity, data: any, entityId: number): void {
- if (this.world_.has(entity, LocalTransform)) {
- this.world_.remove(entity, LocalTransform);
- }
-
+ private syncTransform(entity: Entity, _data: Record<string, unknown> | null, entityId: number): void {
const entityData = this.entityDataMap_.get(entityId);
if (!entityData) return;
- const allEntities = Array.from(this.entityDataMap_.values());
+ const canvasRect = this.cachedCanvasRect_ !== undefined
+ ? this.cachedCanvasRect_
+ : findCanvasWorldRect(Array.from(this.entityDataMap_.values()));
+
const adjustedLocal = computeAdjustedLocalTransform(
- entityData, (id) => this.entityDataMap_.get(id), allEntities,
+ entityData, (id) => this.entityDataMap_.get(id), undefined, canvasRect,
);
this.world_.insert(entity, LocalTransform, {
@@ -620,9 +764,9 @@ export class EditorSceneManager {
return ref;
}
- private async syncSprite(entity: Entity, data: any, entityId: number): Promise<void> {
+ private async syncSprite(entity: Entity, data: Record<string, any>, entityId: number): Promise<void> {
let textureHandle = INVALID_TEXTURE as number;
- let materialHandle = 0;
+ let materialHandle = INVALID_MATERIAL as number;
getDependencyGraph().clearEntity(entityId);
this.assetServer_.releaseMaterialInstance(entityId);
@@ -661,7 +805,7 @@ export class EditorSceneManager {
this.world_.remove(entity, Sprite);
}
- let spriteSize = data.size ?? { x: 100, y: 100 };
+ let spriteSize = data.size ?? DEFAULT_SPRITE_SIZE;
const entityData = this.entityDataMap_.get(entityId);
const uiRect = entityData?.components.find(c => c.type === 'UIRect');
if (uiRect?.data?.size) {
@@ -682,20 +826,20 @@ export class EditorSceneManager {
});
}
- private syncText(entity: Entity, data: any, entityId: number): void {
+ private syncText(entity: Entity, data: Record<string, any>, entityId: number): void {
const entityData = this.entityDataMap_.get(entityId);
const uiRectData = entityData ? getUIRectFromEntity(entityData) : null;
const textData: TextData = {
content: data.content ?? '',
- fontFamily: data.fontFamily ?? 'Arial',
- fontSize: data.fontSize ?? 24,
+ fontFamily: data.fontFamily ?? DEFAULT_FONT_FAMILY,
+ fontSize: data.fontSize ?? DEFAULT_FONT_SIZE,
color: data.color ?? { r: 1, g: 1, b: 1, a: 1 },
align: data.align ?? TextAlign.Left,
verticalAlign: data.verticalAlign ?? TextVerticalAlign.Top,
wordWrap: data.wordWrap ?? true,
overflow: data.overflow ?? TextOverflow.Visible,
- lineHeight: data.lineHeight ?? 1.2,
+ lineHeight: data.lineHeight ?? DEFAULT_LINE_HEIGHT,
};
if (!textData.content) {
@@ -706,29 +850,10 @@ export class EditorSceneManager {
return;
}
- const result = this.textRenderer_.renderForEntity(entity, textData, uiRectData);
-
- if (result.textureHandle === (INVALID_TEXTURE as number)) {
- return;
- }
-
- if (this.world_.has(entity, Sprite)) {
- this.world_.remove(entity, Sprite);
- }
-
- this.world_.insert(entity, Sprite, {
- texture: result.textureHandle,
- color: { r: 1, g: 1, b: 1, a: 1 },
- size: { x: result.width, y: result.height },
- uvOffset: { x: 0, y: 0 },
- uvScale: { x: 1, y: 1 },
- layer: 25,
- flipX: false,
- flipY: false,
- });
+ this.renderAndInsertTextSprite(entity, textData, uiRectData);
}
- private syncTextInput(entity: Entity, data: any, entityId: number): void {
+ private syncTextInput(entity: Entity, data: Record<string, any>, entityId: number): void {
const entityData = this.entityDataMap_.get(entityId);
const uiRectData = entityData ? getUIRectFromEntity(entityData) : null;
@@ -740,8 +865,8 @@ export class EditorSceneManager {
const textData: TextData = {
content: displayText,
- fontFamily: data.fontFamily ?? 'Arial',
- fontSize: data.fontSize ?? 24,
+ fontFamily: data.fontFamily ?? DEFAULT_FONT_FAMILY,
+ fontSize: data.fontSize ?? DEFAULT_FONT_SIZE,
color: isEmpty
? (data.placeholderColor ?? { r: 0.6, g: 0.6, b: 0.6, a: 1 })
: (data.color ?? { r: 1, g: 1, b: 1, a: 1 }),
@@ -749,18 +874,19 @@ export class EditorSceneManager {
verticalAlign: TextVerticalAlign.Middle,
wordWrap: false,
overflow: TextOverflow.Clip,
- lineHeight: 1.2,
+ lineHeight: data.lineHeight ?? DEFAULT_LINE_HEIGHT,
};
- const result = this.textRenderer_.renderForEntity(entity, textData, uiRectData);
-
- if (result.textureHandle === (INVALID_TEXTURE as number)) {
- return;
- }
+ this.renderAndInsertTextSprite(entity, textData, uiRectData);
+ }
- if (this.world_.has(entity, Sprite)) {
- this.world_.remove(entity, Sprite);
- }
+ private renderAndInsertTextSprite(
+ entity: Entity,
+ textData: TextData,
+ uiRectData: { size: { x: number; y: number } } | null,
+ ): void {
+ const result = this.textRenderer_.renderForEntity(entity, textData, uiRectData);
+ if (result.textureHandle === (INVALID_TEXTURE as number)) return;
this.world_.insert(entity, Sprite, {
texture: result.textureHandle,
@@ -768,13 +894,13 @@ export class EditorSceneManager {
size: { x: result.width, y: result.height },
uvOffset: { x: 0, y: 0 },
uvScale: { x: 1, y: 1 },
- layer: 25,
+ layer: TEXT_RENDER_LAYER,
flipX: false,
flipY: false,
});
}
- private async syncBitmapText(entity: Entity, data: any, _entityId: number): Promise<void> {
+ private async syncBitmapText(entity: Entity, data: Record<string, any>, _entityId: number): Promise<void> {
let fontHandle = INVALID_FONT as number;
const fontRef = data.font;
@@ -807,7 +933,7 @@ export class EditorSceneManager {
});
}
- private async syncSpineAnimation(entity: Entity, data: any, entityId: number): Promise<void> {
+ private async syncSpineAnimation(entity: Entity, data: Record<string, any>, entityId: number): Promise<void> {
const skeletonRef = data.skeletonPath ?? '';
const atlasRef = data.atlasPath ?? '';
@@ -831,7 +957,7 @@ export class EditorSceneManager {
entityId: number,
skeletonPath: string,
atlasPath: string,
- data: any,
+ data: Record<string, any>,
): Promise<void> {
const controller = this.spineController_!;
const cacheKey = `${skeletonPath}:${atlasPath}`;
@@ -871,7 +997,7 @@ export class EditorSceneManager {
}
}
- const skin = data.skin ?? 'default';
+ const skin = data.skin ?? DEFAULT_SPINE_SKIN;
const animation = data.animation ?? '';
const loop = data.loop ?? true;
const prev = this.spineCurrentState_.get(entityId);
@@ -897,7 +1023,7 @@ export class EditorSceneManager {
entityId: number,
skeletonPath: string,
atlasPath: string,
- data: any,
+ data: Record<string, any>,
): Promise<void> {
const result = await this.assetServer_.loadSpine(skeletonPath, atlasPath);
if (!result.success) {
@@ -905,7 +1031,7 @@ export class EditorSceneManager {
return;
}
- let materialHandle = 0;
+ let materialHandle = INVALID_MATERIAL as number;
const materialRef = data.material;
if (materialRef && typeof materialRef === 'string') {
const materialPath = this.resolveAssetRef(materialRef);
@@ -923,7 +1049,7 @@ export class EditorSceneManager {
data: {
skeletonPath,
atlasPath,
- skin: data.skin ?? 'default',
+ skin: data.skin ?? DEFAULT_SPINE_SKIN,
animation: data.animation ?? '',
timeScale: data.timeScale ?? 1,
loop: data.loop ?? true,
diff --git a/editor/src/scene/uiLayoutUtils.ts b/editor/src/scene/uiLayoutUtils.ts
new file mode 100644
index 000000000..48300b1c3
--- /dev/null
+++ b/editor/src/scene/uiLayoutUtils.ts
@@ -0,0 +1 @@
+export { computeFillAnchors, computeHandleAnchors, computeFillSize } from 'esengine';
diff --git a/editor/src/store/EditorStore.ts b/editor/src/store/EditorStore.ts
index 871a3fcc4..693230d6e 100644
--- a/editor/src/store/EditorStore.ts
+++ b/editor/src/store/EditorStore.ts
@@ -72,6 +72,11 @@ export interface ComponentChangeEvent {
export type ComponentChangeListener = (event: ComponentChangeEvent) => void;
+const DERIVED_PROPERTY_MAP: Array<{ source: [string, string]; target: [string, string] }> = [
+ { source: ['UIRect', 'size'], target: ['Sprite', 'size'] },
+ { source: ['TextInput', 'backgroundColor'], target: ['Sprite', 'color'] },
+];
+
// =============================================================================
// EditorStore
// =============================================================================
@@ -578,19 +583,13 @@ export class EditorStore {
}
notifyPropertyChange(event: PropertyChangeEvent): void {
- if (event.componentType === 'TextInput' && event.propertyName === 'backgroundColor') {
- const entityData = this.entityMap_.get(event.entity);
- const spriteComp = entityData?.components.find(c => c.type === 'Sprite');
- if (spriteComp) {
- spriteComp.data.color = event.newValue;
- }
- }
-
- if (event.componentType === 'UIRect' && event.propertyName === 'size') {
- const entityData = this.entityMap_.get(event.entity);
- const spriteComp = entityData?.components.find(c => c.type === 'Sprite');
- if (spriteComp) {
- spriteComp.data.size = event.newValue;
+ for (const rule of DERIVED_PROPERTY_MAP) {
+ if (event.componentType === rule.source[0] && event.propertyName === rule.source[1]) {
+ const entityData = this.entityMap_.get(event.entity);
+ const targetComp = entityData?.components.find(c => c.type === rule.target[0]);
+ if (targetComp) {
+ targetComp.data[rule.target[1]] = event.newValue;
+ }
}
}
@@ -601,14 +600,12 @@ export class EditorStore {
private syncDerivedProperties(): void {
for (const entityData of this.entityMap_.values()) {
- const uiRect = entityData.components.find(c => c.type === 'UIRect');
- const sprite = entityData.components.find(c => c.type === 'Sprite');
- if (uiRect && sprite) {
- sprite.data.size = uiRect.data.size;
- }
- const textInput = entityData.components.find(c => c.type === 'TextInput');
- if (textInput && sprite) {
- sprite.data.color = textInput.data.backgroundColor;
+ for (const rule of DERIVED_PROPERTY_MAP) {
+ const sourceComp = entityData.components.find(c => c.type === rule.source[0]);
+ const targetComp = entityData.components.find(c => c.type === rule.target[0]);
+ if (sourceComp && targetComp) {
+ targetComp.data[rule.target[1]] = sourceComp.data[rule.source[1]];
+ }
}
}
}
diff --git a/editor/src/sync/RuntimeSyncService.ts b/editor/src/sync/RuntimeSyncService.ts
index d6970655d..6d73ad794 100644
--- a/editor/src/sync/RuntimeSyncService.ts
+++ b/editor/src/sync/RuntimeSyncService.ts
@@ -7,6 +7,8 @@ import type { EditorStore, PropertyChangeEvent, HierarchyChangeEvent, Visibility
import type { EditorSceneManager } from '../scene/EditorSceneManager';
import { getAssetEventBus, type AssetEvent } from '../events/AssetEventBus';
import { getDependencyGraph } from '../asset/AssetDependencyGraph';
+import { ButtonState, FillDirection } from 'esengine';
+import { computeFillAnchors, computeHandleAnchors, computeFillSize } from '../scene/uiLayoutUtils';
export class RuntimeSyncService {
private unsubscribes_: (() => void)[] = [];
@@ -117,6 +119,14 @@ export class RuntimeSyncService {
if (event.componentType === 'Button') {
this.syncButtonTransitionColor(event.entity);
}
+
+ if (event.componentType === 'Slider') {
+ this.syncSliderChildren(event.entity);
+ }
+
+ if (event.componentType === 'ProgressBar') {
+ this.syncProgressBarChildren(event.entity);
+ }
}
private syncCanvasToCamera(canvasEntityId: number): void {
@@ -157,19 +167,88 @@ export class RuntimeSyncService {
const spriteComp = entityData.components.find(c => c.type === 'Sprite');
if (!spriteComp) return;
- const state = (buttonComp.data.state as number) ?? 0;
- const colorMap = [
- transition.normalColor,
- transition.hoveredColor,
- transition.pressedColor,
- transition.disabledColor,
- ];
+ const state = (buttonComp.data.state as number) ?? ButtonState.Normal;
+ const colorMap: Record<number, { r: number; g: number; b: number; a: number }> = {
+ [ButtonState.Normal]: transition.normalColor,
+ [ButtonState.Hovered]: transition.hoveredColor,
+ [ButtonState.Pressed]: transition.pressedColor,
+ [ButtonState.Disabled]: transition.disabledColor,
+ };
const color = colorMap[state] ?? transition.normalColor;
this.store_.updatePropertyDirect(entityId, 'Sprite', 'color', { ...color });
this.scheduleEntityUpdate(entityId);
}
+ private syncSliderChildren(entityId: number): void {
+ const entityData = this.store_.getEntityData(entityId);
+ if (!entityData) return;
+
+ const sliderComp = entityData.components.find(c => c.type === 'Slider');
+ if (!sliderComp) return;
+
+ const value = sliderComp.data.value as number ?? 0;
+ const minValue = sliderComp.data.minValue as number ?? 0;
+ const maxValue = sliderComp.data.maxValue as number ?? 1;
+ const direction = sliderComp.data.direction as number ?? FillDirection.LeftToRight;
+ const fillEntity = sliderComp.data.fillEntity as number ?? 0;
+ const handleEntity = sliderComp.data.handleEntity as number ?? 0;
+
+ const range = maxValue - minValue;
+ const normalizedValue = range > 0 ? (value - minValue) / range : 0;
+
+ const uiRectComp = entityData.components.find(c => c.type === 'UIRect');
+ const sliderW = (uiRectComp?.data?.size as { x: number; y: number })?.x ?? 0;
+ const sliderH = (uiRectComp?.data?.size as { x: number; y: number })?.y ?? 0;
+
+ if (fillEntity !== 0) {
+ const fillAnchors = computeFillAnchors(direction, normalizedValue);
+ this.store_.updatePropertyDirect(fillEntity, 'UIRect', 'anchorMin', fillAnchors.anchorMin);
+ this.store_.updatePropertyDirect(fillEntity, 'UIRect', 'anchorMax', fillAnchors.anchorMax);
+ this.store_.updatePropertyDirect(fillEntity, 'UIRect', 'offsetMin', fillAnchors.offsetMin);
+ this.store_.updatePropertyDirect(fillEntity, 'UIRect', 'offsetMax', fillAnchors.offsetMax);
+ this.store_.updatePropertyDirect(fillEntity, 'UIRect', 'size',
+ computeFillSize(direction, normalizedValue, sliderW, sliderH));
+ this.scheduleEntityUpdate(fillEntity);
+ }
+
+ if (handleEntity !== 0) {
+ const handleAnchors = computeHandleAnchors(direction, normalizedValue);
+ this.store_.updatePropertyDirect(handleEntity, 'UIRect', 'anchorMin', handleAnchors.anchorMin);
+ this.store_.updatePropertyDirect(handleEntity, 'UIRect', 'anchorMax', handleAnchors.anchorMax);
+ this.store_.updatePropertyDirect(handleEntity, 'UIRect', 'offsetMin', { x: 0, y: 0 });
+ this.store_.updatePropertyDirect(handleEntity, 'UIRect', 'offsetMax', { x: 0, y: 0 });
+ this.scheduleEntityUpdate(handleEntity);
+ }
+ }
+
+ private syncProgressBarChildren(entityId: number): void {
+ const entityData = this.store_.getEntityData(entityId);
+ if (!entityData) return;
+
+ const barComp = entityData.components.find(c => c.type === 'ProgressBar');
+ if (!barComp) return;
+
+ const value = Math.max(0, Math.min(1, barComp.data.value as number ?? 0));
+ const direction = barComp.data.direction as number ?? FillDirection.LeftToRight;
+ const fillEntity = barComp.data.fillEntity as number ?? 0;
+
+ const uiRectComp = entityData.components.find(c => c.type === 'UIRect');
+ const barW = (uiRectComp?.data?.size as { x: number; y: number })?.x ?? 0;
+ const barH = (uiRectComp?.data?.size as { x: number; y: number })?.y ?? 0;
+
+ if (fillEntity !== 0) {
+ const fillAnchors = computeFillAnchors(direction, value);
+ this.store_.updatePropertyDirect(fillEntity, 'UIRect', 'anchorMin', fillAnchors.anchorMin);
+ this.store_.updatePropertyDirect(fillEntity, 'UIRect', 'anchorMax', fillAnchors.anchorMax);
+ this.store_.updatePropertyDirect(fillEntity, 'UIRect', 'offsetMin', fillAnchors.offsetMin);
+ this.store_.updatePropertyDirect(fillEntity, 'UIRect', 'offsetMax', fillAnchors.offsetMax);
+ this.store_.updatePropertyDirect(fillEntity, 'UIRect', 'size',
+ computeFillSize(direction, value, barW, barH));
+ this.scheduleEntityUpdate(fillEntity);
+ }
+ }
+
private onHierarchyChange(event: HierarchyChangeEvent): void {
this.sceneManager_.reparentEntity(event.entity, event.newParent);
}