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 world transform cache, gizmo undo/redo, and nine-slice rotation
esenginec3ed792c3ff3
diff --git a/editor/src/math/Transform.ts b/editor/src/math/Transform.tsnew file mode 100644index 000000000..14bf2f327--- /dev/null+++ b/editor/src/math/Transform.ts@@ -0,0 +1,171 @@+/**+ * @file Transform.ts+ * @brief Math utilities for transform calculations+ */++// =============================================================================+// Types+// =============================================================================++export interface Vec3 {+ x: number;+ y: number;+ z: number;+}++export interface Quat {+ x: number;+ y: number;+ z: number;+ w: number;+}++export interface Transform {+ position: Vec3;+ rotation: Quat;+ scale: Vec3;+}++// =============================================================================+// Constants+// =============================================================================++export const IDENTITY_TRANSFORM: Readonly<Transform> = Object.freeze({+ position: Object.freeze({ x: 0, y: 0, z: 0 }),+ rotation: Object.freeze({ x: 0, y: 0, z: 0, w: 1 }),+ scale: Object.freeze({ x: 1, y: 1, z: 1 }),+});++export const DEG_TO_RAD = Math.PI / 180;+export const RAD_TO_DEG = 180 / Math.PI;++// =============================================================================+// Quaternion Operations+// =============================================================================++/**+ * @brief Multiply two quaternions: result = a * b+ */+export function multiplyQuat(a: Quat, b: Quat): Quat {+ return {+ x: a.w * b.x + a.x * b.w + a.y * b.z - a.z * b.y,+ y: a.w * b.y - a.x * b.z + a.y * b.w + a.z * b.x,+ z: a.w * b.z + a.x * b.y - a.y * b.x + a.z * b.w,+ w: a.w * b.w - a.x * b.x - a.y * b.y - a.z * b.z,+ };+}++/**+ * @brief Rotate a vector by a quaternion+ */+export function rotateVector(v: Vec3, q: Quat): Vec3 {+ const { x: qx, y: qy, z: qz, w: qw } = q;+ const { x: vx, y: vy, z: vz } = v;++ const ix = qw * vx + qy * vz - qz * vy;+ const iy = qw * vy + qz * vx - qx * vz;+ const iz = qw * vz + qx * vy - qy * vx;+ const iw = -qx * vx - qy * vy - qz * vz;++ return {+ x: ix * qw + iw * -qx + iy * -qz - iz * -qy,+ y: iy * qw + iw * -qy + iz * -qx - ix * -qz,+ z: iz * qw + iw * -qz + ix * -qy - iy * -qx,+ };+}++/**+ * @brief Convert quaternion to Euler angles (degrees)+ */+export function quatToEuler(q: Quat): Vec3 {+ const { x, y, z, w } = q;++ const sinrCosp = 2 * (w * x + y * z);+ const cosrCosp = 1 - 2 * (x * x + y * y);+ const roll = Math.atan2(sinrCosp, cosrCosp);++ const sinp = 2 * (w * y - z * x);+ const pitch = Math.abs(sinp) >= 1+ ? Math.sign(sinp) * Math.PI / 2+ : Math.asin(sinp);++ const sinyCosp = 2 * (w * z + x * y);+ const cosyCosp = 1 - 2 * (y * y + z * z);+ const yaw = Math.atan2(sinyCosp, cosyCosp);++ return {+ x: roll * RAD_TO_DEG,+ y: pitch * RAD_TO_DEG,+ z: yaw * RAD_TO_DEG,+ };+}++/**+ * @brief Convert Euler angles (degrees) to quaternion+ */+export function eulerToQuat(euler: Vec3): Quat {+ const roll = euler.x * DEG_TO_RAD;+ const pitch = euler.y * DEG_TO_RAD;+ const yaw = euler.z * DEG_TO_RAD;++ const cr = Math.cos(roll * 0.5);+ const sr = Math.sin(roll * 0.5);+ const cp = Math.cos(pitch * 0.5);+ const sp = Math.sin(pitch * 0.5);+ const cy = Math.cos(yaw * 0.5);+ const sy = Math.sin(yaw * 0.5);++ return {+ w: cr * cp * cy + sr * sp * sy,+ x: sr * cp * cy - cr * sp * sy,+ y: cr * sp * cy + sr * cp * sy,+ z: cr * cp * sy - sr * sp * cy,+ };+}++// =============================================================================+// Transform Operations+// =============================================================================++/**+ * @brief Compose parent and child transforms: worldChild = worldParent * localChild+ */+export function composeTransforms(parent: Transform, child: Transform): Transform {+ const rotatedPos = rotateVector(child.position, parent.rotation);++ return {+ position: {+ x: parent.position.x + rotatedPos.x * parent.scale.x,+ y: parent.position.y + rotatedPos.y * parent.scale.y,+ z: parent.position.z + rotatedPos.z * parent.scale.z,+ },+ rotation: multiplyQuat(parent.rotation, child.rotation),+ scale: {+ x: parent.scale.x * child.scale.x,+ y: parent.scale.y * child.scale.y,+ z: parent.scale.z * child.scale.z,+ },+ };+}++/**+ * @brief Create a copy of an identity transform+ */+export function createIdentityTransform(): Transform {+ return {+ position: { x: 0, y: 0, z: 0 },+ rotation: { x: 0, y: 0, z: 0, w: 1 },+ scale: { x: 1, y: 1, z: 1 },+ };+}++/**+ * @brief Clone a transform+ */+export function cloneTransform(t: Transform): Transform {+ return {+ position: { ...t.position },+ rotation: { ...t.rotation },+ scale: { ...t.scale },+ };+}diff --git a/editor/src/math/index.ts b/editor/src/math/index.tsnew file mode 100644index 000000000..026d7ffff--- /dev/null+++ b/editor/src/math/index.ts@@ -0,0 +1,6 @@+/**+ * @file index.ts+ * @brief Math utilities exports+ */++export * from './Transform';diff --git a/editor/src/panels/SceneViewPanel.ts b/editor/src/panels/SceneViewPanel.tsindex cfe6759ac..c76173522 100644--- a/editor/src/panels/SceneViewPanel.ts+++ b/editor/src/panels/SceneViewPanel.ts@@ -1,13 +1,17 @@/*** @file SceneViewPanel.ts- * @brief Scene viewport panel with canvas rendering and gizmo tools+ * @brief Scene viewport panel with WebGL rendering and gizmo overlay*/-import type { Entity } from 'esengine';+import type { Entity, App } from 'esengine';import type { EditorStore } from '../store/EditorStore';import type { EditorBridge } from '../bridge/EditorBridge';+import type { SliceBorder } from '../types/TextureMetadata';import { getPlatformAdapter } from '../platform/PlatformAdapter';+import { hasSlicing, parseTextureMetadata } from '../types/TextureMetadata';import { icons } from '../utils/icons';+import { EditorSceneRenderer } from '../renderer/EditorSceneRenderer';+import { quatToEuler, eulerToQuat } from '../math/Transform';// =============================================================================// Types@@ -23,6 +27,14 @@ interface GizmoColors {hover: string;}+interface GizmoSettings {+ showGrid: boolean;+ gridColor: string;+ gridOpacity: number;+ showGizmos: boolean;+ showSelectionBox: boolean;+}+const GIZMO_COLORS: GizmoColors = {x: '#e74c3c',y: '#2ecc71',@@ -33,12 +45,21 @@ const GIZMO_COLORS: GizmoColors = {const GIZMO_SIZE = 80;const GIZMO_HANDLE_SIZE = 10;+const DEFAULT_GIZMO_SETTINGS: GizmoSettings = {+ showGrid: true,+ gridColor: '#333333',+ gridOpacity: 1.0,+ showGizmos: true,+ showSelectionBox: true,+};+// =============================================================================// SceneViewPanel// =============================================================================export interface SceneViewPanelOptions {projectPath?: string;+ app?: App;}export class SceneViewPanel {@@ -46,10 +67,18 @@ export class SceneViewPanel {private store_: EditorStore;private bridge_: EditorBridge | null = null;private canvas_: HTMLCanvasElement;+ private webglCanvas_: HTMLCanvasElement | null = null;+ private overlayCanvas_: HTMLCanvasElement | null = null;private unsubscribe_: (() => void) | null = null;private animationId_: number | null = null;private resizeObserver_: ResizeObserver | null = null;private projectPath_: string | null = null;+ private app_: App | null = null;++ private sceneRenderer_: EditorSceneRenderer | null = null;+ private useWebGL_ = false;+ private webglInitialized_ = false;+ private webglInitPending_ = false;private panX_ = 0;private panY_ = 0;@@ -65,18 +94,26 @@ export class SceneViewPanel {private gizmoDragStartX_ = 0;private gizmoDragStartY_ = 0;private gizmoDragStartValue_: { x: number; y: number; z: number } = { x: 0, y: 0, z: 0 };+ private gizmoDragOriginalValue_: unknown = null;+ private gizmoDragPropertyName_: string = '';private keydownHandler_: ((e: KeyboardEvent) => void) | null = null;private skipNextClick_ = false;private boundOnDocumentMouseMove_: ((e: MouseEvent) => void) | null = null;private boundOnDocumentMouseUp_: ((e: MouseEvent) => void) | null = null;private textureCache_: Map<string, HTMLImageElement | null> = new Map();+ private metadataCache_: Map<string, SliceBorder | null> = new Map();private loadingTextures_: Set<string> = new Set();+ private gizmoSettings_: GizmoSettings = { ...DEFAULT_GIZMO_SETTINGS };+ private settingsDropdown_: HTMLElement | null = null;+ private settingsDropdownClickHandler_: ((e: MouseEvent) => void) | null = null;+constructor(container: HTMLElement, store: EditorStore, options?: SceneViewPanelOptions) {this.container_ = container;this.store_ = store;this.projectPath_ = options?.projectPath ?? null;+ this.app_ = options?.app ?? null;this.container_.className = 'es-sceneview-panel';this.container_.innerHTML = `@@ -92,18 +129,58 @@ export class SceneViewPanel {<div class="es-toolbar-divider"></div><button class="es-btn es-btn-icon" data-action="reset-view" title="Reset View">${icons.refresh(14)}</button><span class="es-zoom-display">100%</span>+ <div class="es-toolbar-divider"></div>+ <div class="es-gizmo-settings-wrapper">+ <button class="es-btn es-btn-icon" data-action="gizmo-settings" title="Gizmo Settings">${icons.settings(14)}</button>+ <div class="es-gizmo-settings-dropdown" style="display: none;">+ <div class="es-settings-row">+ <label class="es-settings-checkbox">+ <input type="checkbox" data-setting="showGrid" checked>+ <span>Show Grid</span>+ </label>+ </div>+ <div class="es-settings-row">+ <label class="es-settings-label">Grid Color</label>+ <input type="color" data-setting="gridColor" value="#333333" class="es-color-input">+ </div>+ <div class="es-settings-row">+ <label class="es-settings-label">Grid Opacity</label>+ <input type="range" data-setting="gridOpacity" min="0" max="1" step="0.1" value="1" class="es-slider-input">+ </div>+ <div class="es-settings-divider"></div>+ <div class="es-settings-row">+ <label class="es-settings-checkbox">+ <input type="checkbox" data-setting="showGizmos" checked>+ <span>Show Gizmos</span>+ </label>+ </div>+ <div class="es-settings-row">+ <label class="es-settings-checkbox">+ <input type="checkbox" data-setting="showSelectionBox" checked>+ <span>Show Selection Box</span>+ </label>+ </div>+ </div>+ </div></div></div><div class="es-sceneview-viewport">- <canvas class="es-sceneview-canvas"></canvas>+ <canvas class="es-sceneview-webgl"></canvas>+ <canvas class="es-sceneview-overlay"></canvas></div>`;- this.canvas_ = this.container_.querySelector('.es-sceneview-canvas')!;+ this.webglCanvas_ = this.container_.querySelector('.es-sceneview-webgl')!;+ this.overlayCanvas_ = this.container_.querySelector('.es-sceneview-overlay')!;+ this.canvas_ = this.overlayCanvas_;this.setupEvents();- this.unsubscribe_ = store.subscribe(() => this.requestRender());+ this.unsubscribe_ = store.subscribe(() => this.onSceneChanged());this.resize();++ if (this.app_?.wasmModule) {+ this.initWebGLRenderer();+ }}dispose(): void {@@ -123,6 +200,14 @@ export class SceneViewPanel {document.removeEventListener('keydown', this.keydownHandler_);this.keydownHandler_ = null;}+ if (this.settingsDropdownClickHandler_) {+ document.removeEventListener('click', this.settingsDropdownClickHandler_);+ this.settingsDropdownClickHandler_ = null;+ }+ if (this.sceneRenderer_) {+ this.sceneRenderer_.dispose();+ this.sceneRenderer_ = null;+ }this.stopDocumentDrag();}@@ -135,6 +220,63 @@ export class SceneViewPanel {this.projectPath_ = path;this.textureCache_.clear();this.loadingTextures_.clear();++ if (this.sceneRenderer_) {+ const projectDir = path.replace(/\\/g, '/').replace(/\/[^/]+$/, '');+ this.sceneRenderer_.setProjectDir(projectDir);+ this.syncSceneToRenderer();+ }++ this.requestRender();+ }++ setApp(app: App): void {+ this.app_ = app;+ if (app.wasmModule && !this.webglInitialized_ && !this.webglInitPending_) {+ this.initWebGLRenderer();+ }+ }++ private async initWebGLRenderer(): Promise<void> {+ if (this.webglInitPending_ || this.webglInitialized_) return;+ if (!this.app_?.wasmModule || !this.webglCanvas_) return;++ this.webglInitPending_ = true;++ const canvasId = `es-sceneview-webgl-${Date.now()}`;+ this.webglCanvas_.id = canvasId;++ this.sceneRenderer_ = new EditorSceneRenderer();+ const success = await this.sceneRenderer_.init(this.app_.wasmModule, `#${canvasId}`);++ if (success) {+ this.webglInitialized_ = true;+ this.useWebGL_ = true;++ if (this.projectPath_) {+ const projectDir = this.projectPath_.replace(/\\/g, '/').replace(/\/[^/]+$/, '');+ this.sceneRenderer_.setProjectDir(projectDir);+ }++ await this.syncSceneToRenderer();+ this.requestRender();+ } else {+ console.warn('WebGL init failed, falling back to Canvas 2D');+ this.sceneRenderer_ = null;+ }++ this.webglInitPending_ = false;+ }++ private async syncSceneToRenderer(): Promise<void> {+ if (!this.sceneRenderer_) return;+ await this.sceneRenderer_.syncScene(this.store_.scene);+ }++ private async onSceneChanged(): Promise<void> {+ if (this.sceneRenderer_ && this.useWebGL_) {+ await this.syncSceneToRenderer();+ }this.requestRender();}@@ -183,6 +325,20 @@ export class SceneViewPanel {const rect = viewport.getBoundingClientRect();const dpr = window.devicePixelRatio || 1;+ if (this.webglCanvas_) {+ this.webglCanvas_.width = rect.width * dpr;+ this.webglCanvas_.height = rect.height * dpr;+ this.webglCanvas_.style.width = `${rect.width}px`;+ this.webglCanvas_.style.height = `${rect.height}px`;+ }++ if (this.overlayCanvas_) {+ this.overlayCanvas_.width = rect.width * dpr;+ this.overlayCanvas_.height = rect.height * dpr;+ this.overlayCanvas_.style.width = `${rect.width}px`;+ this.overlayCanvas_.style.height = `${rect.height}px`;+ }+this.canvas_.width = rect.width * dpr;this.canvas_.height = rect.height * dpr;this.canvas_.style.width = `${rect.width}px`;@@ -201,6 +357,8 @@ export class SceneViewPanel {this.requestRender();});+ this.setupGizmoSettingsDropdown();+const gizmoButtons = this.container_.querySelectorAll('.es-gizmo-btn');gizmoButtons.forEach(btn => {btn.addEventListener('click', () => {@@ -256,6 +414,50 @@ export class SceneViewPanel {this.requestRender();}+ private setupGizmoSettingsDropdown(): void {+ const settingsBtn = this.container_.querySelector('[data-action="gizmo-settings"]');+ this.settingsDropdown_ = this.container_.querySelector('.es-gizmo-settings-dropdown');++ if (!settingsBtn || !this.settingsDropdown_) return;++ settingsBtn.addEventListener('click', (e) => {+ e.stopPropagation();+ const isVisible = this.settingsDropdown_!.style.display !== 'none';+ this.settingsDropdown_!.style.display = isVisible ? 'none' : 'block';+ });++ this.settingsDropdownClickHandler_ = (e: MouseEvent) => {+ if (this.settingsDropdown_ && !this.settingsDropdown_.contains(e.target as Node) &&+ !settingsBtn.contains(e.target as Node)) {+ this.settingsDropdown_.style.display = 'none';+ }+ };+ document.addEventListener('click', this.settingsDropdownClickHandler_);++ this.settingsDropdown_.querySelectorAll('input').forEach(input => {+ const setting = input.dataset.setting as keyof GizmoSettings;+ if (!setting) return;++ input.addEventListener('change', () => {+ if (input.type === 'checkbox') {+ (this.gizmoSettings_ as any)[setting] = input.checked;+ } else if (input.type === 'range') {+ (this.gizmoSettings_ as any)[setting] = parseFloat(input.value);+ } else if (input.type === 'color') {+ (this.gizmoSettings_ as any)[setting] = input.value;+ }+ this.requestRender();+ });++ if (input.type === 'range') {+ input.addEventListener('input', () => {+ (this.gizmoSettings_ as any)[setting] = parseFloat(input.value);+ this.requestRender();+ });+ }+ });+ }+private onMouseDown(e: MouseEvent): void {if (e.button === 1 || (e.button === 0 && e.altKey)) {this.isDragging_ = true;@@ -283,11 +485,15 @@ export class SceneViewPanel {if (transform) {if (this.gizmoMode_ === 'rotate') {const quat = transform.data.rotation as { x: number; y: number; z: number; w: number };- this.gizmoDragStartValue_ = this.quatToEuler(quat ?? { x: 0, y: 0, z: 0, w: 1 });+ this.gizmoDragStartValue_ = quatToEuler(quat ?? { x: 0, y: 0, z: 0, w: 1 });+ this.gizmoDragPropertyName_ = 'rotation';+ this.gizmoDragOriginalValue_ = quat ? { ...quat } : { x: 0, y: 0, z: 0, w: 1 };} else {const prop = this.gizmoMode_ === 'scale' ? 'scale' : 'position';const value = transform.data[prop] as { x: number; y: number; z: number };this.gizmoDragStartValue_ = { ...value };+ this.gizmoDragPropertyName_ = prop;+ this.gizmoDragOriginalValue_ = { ...value };}}this.startDocumentDrag();@@ -365,12 +571,54 @@ export class SceneViewPanel {}if (this.isGizmoDragging_) {+ this.commitGizmoDrag();this.isGizmoDragging_ = false;this.dragAxis_ = 'none';this.skipNextClick_ = true;}}+ private commitGizmoDrag(): void {+ const entity = this.store_.selectedEntity;+ if (entity === null || !this.gizmoDragPropertyName_ || this.gizmoDragOriginalValue_ === null) {+ return;+ }++ const entityData = this.store_.getSelectedEntityData();+ const transform = entityData?.components.find(c => c.type === 'LocalTransform');+ if (!transform) return;++ const currentValue = transform.data[this.gizmoDragPropertyName_];+ if (!currentValue) return;++ const oldValue = this.gizmoDragOriginalValue_;+ const newValue = this.deepClone(currentValue);++ if (this.valuesEqual(oldValue, newValue)) {+ return;+ }++ this.store_.updateProperty(+ entity,+ 'LocalTransform',+ this.gizmoDragPropertyName_,+ oldValue,+ newValue+ );++ this.gizmoDragOriginalValue_ = null;+ this.gizmoDragPropertyName_ = '';+ }++ private deepClone<T>(obj: T): T {+ if (obj === null || typeof obj !== 'object') return obj;+ return JSON.parse(JSON.stringify(obj));+ }++ private valuesEqual(a: unknown, b: unknown): boolean {+ return JSON.stringify(a) === JSON.stringify(b);+ }+private onMouseLeave(_e: MouseEvent): void {if (this.isDragging_ || this.isGizmoDragging_) {return;@@ -416,10 +664,7 @@ export class SceneViewPanel {const entityData = this.store_.getSelectedEntityData();if (!entityData) return null;- const transform = entityData.components.find(c => c.type === 'LocalTransform');- if (!transform) return null;-- return transform.data.position as { x: number; y: number; z: number } ?? { x: 0, y: 0, z: 0 };+ return this.store_.getWorldTransform(entityData.id).position;}private hitTestGizmo(worldX: number, worldY: number): DragAxis {@@ -499,52 +744,13 @@ export class SceneViewPanel {const newRotZ = this.gizmoDragStartValue_.z + deltaAngle;const euler = { x: 0, y: 0, z: newRotZ };- const quat = this.eulerToQuat(euler);+ const quat = eulerToQuat(euler);this.store_.updatePropertyDirect(entity, 'LocalTransform', 'rotation', quat);}this.requestRender();}- private quatToEuler(q: { x: number; y: number; z: number; w: number }): { x: number; y: number; z: number } {- const { x, y, z, w } = q;-- const sinrCosp = 2 * (w * x + y * z);- const cosrCosp = 1 - 2 * (x * x + y * y);- const roll = Math.atan2(sinrCosp, cosrCosp);-- const sinp = 2 * (w * y - z * x);- const pitch = Math.abs(sinp) >= 1 ? Math.sign(sinp) * Math.PI / 2 : Math.asin(sinp);-- const sinyCosp = 2 * (w * z + x * y);- const cosyCosp = 1 - 2 * (y * y + z * z);- const yaw = Math.atan2(sinyCosp, cosyCosp);-- const toDeg = 180 / Math.PI;- return { x: roll * toDeg, y: pitch * toDeg, z: yaw * toDeg };- }-- private eulerToQuat(euler: { x: number; y: number; z: number }): { x: number; y: number; z: number; w: number } {- const toRad = Math.PI / 180;- const roll = euler.x * toRad;- const pitch = euler.y * toRad;- const yaw = euler.z * toRad;-- const cr = Math.cos(roll * 0.5);- const sr = Math.sin(roll * 0.5);- const cp = Math.cos(pitch * 0.5);- const sp = Math.sin(pitch * 0.5);- const cy = Math.cos(yaw * 0.5);- const sy = Math.sin(yaw * 0.5);-- return {- w: cr * cp * cy + sr * sp * sy,- x: sr * cp * cy - cr * sp * sy,- y: cr * sp * cy + sr * cp * sy,- z: cr * cp * sy - sr * sp * cy,- };- }-private onWheel(e: WheelEvent): void {e.preventDefault();@@ -577,8 +783,9 @@ export class SceneViewPanel {if (!transform) continue;- const pos = transform.data.position as { x: number; y: number; z: number };- const scale = transform.data.scale as { x: number; y: number; z: number } ?? { x: 1, y: 1, z: 1 };+ const worldTransform = this.store_.getWorldTransform(entity.id);+ const pos = worldTransform.position;+ const scale = worldTransform.scale;const sprite = entity.components.find(c => c.type === 'Sprite');let w = defaultSize;@@ -594,10 +801,10 @@ export class SceneViewPanel {const halfH = h / 2;if (- worldX >= (pos?.x ?? 0) - halfW &&- worldX <= (pos?.x ?? 0) + halfW &&- worldY >= (pos?.y ?? 0) - halfH &&- worldY <= (pos?.y ?? 0) + halfH+ worldX >= pos.x - halfW &&+ worldX <= pos.x + halfW &&+ worldY >= pos.y - halfH &&+ worldY <= pos.y + halfH) {return entity.id as Entity;}@@ -623,13 +830,99 @@ export class SceneViewPanel {}private render(): void {- if (this.bridge_) {+ if (this.useWebGL_ && this.sceneRenderer_ && this.webglCanvas_) {+ this.sceneRenderer_.camera.panX = this.panX_;+ this.sceneRenderer_.camera.panY = this.panY_;+ this.sceneRenderer_.camera.zoom = this.zoom_;++ this.sceneRenderer_.render(this.webglCanvas_.width, this.webglCanvas_.height);+ this.renderOverlay();+ } else if (this.bridge_) {this.bridge_.render(this.canvas_.width, this.canvas_.height);} else {this.renderPreview();}}+ private renderOverlay(): void {+ if (!this.overlayCanvas_) return;++ const ctx = this.overlayCanvas_.getContext('2d');+ if (!ctx) return;++ const w = this.overlayCanvas_.width;+ const h = this.overlayCanvas_.height;++ ctx.clearRect(0, 0, w, h);++ ctx.save();+ ctx.translate(w / 2 + this.panX_ * this.zoom_, h / 2 + this.panY_ * this.zoom_);+ ctx.scale(this.zoom_, this.zoom_);++ this.drawGrid(ctx, w, h);++ const selectedEntity = this.store_.selectedEntity;++ if (selectedEntity !== null) {+ if (this.gizmoSettings_.showSelectionBox) {+ this.drawSelectionBox(ctx);+ }++ if (this.gizmoMode_ !== 'select' && this.gizmoSettings_.showGizmos) {+ this.drawGizmo(ctx);+ }+ }++ ctx.restore();+ }++ private drawSelectionBox(ctx: CanvasRenderingContext2D): void {+ const entityData = this.store_.getSelectedEntityData();+ if (!entityData) return;++ const transform = entityData.components.find(c => c.type === 'LocalTransform');+ const sprite = entityData.components.find(c => c.type === 'Sprite');++ if (!transform) return;++ const worldTransform = this.store_.getWorldTransform(entityData.id);+ const pos = worldTransform.position;+ const scale = worldTransform.scale;++ let w = 50;+ let h = 50;++ if (sprite) {+ const size = sprite.data.size as { x: number; y: number };+ if (size) {+ w = size.x * Math.abs(scale.x);+ h = size.y * Math.abs(scale.y);+ }+ }++ ctx.save();+ ctx.translate(pos.x, -pos.y);++ ctx.strokeStyle = '#00aaff';+ ctx.lineWidth = 2 / this.zoom_;+ ctx.setLineDash([]);+ ctx.strokeRect(-w / 2, -h / 2, w, h);++ ctx.fillStyle = '#00aaff';+ const handleSize = 6 / this.zoom_;+ const corners = [+ [-w / 2, -h / 2],+ [w / 2, -h / 2],+ [-w / 2, h / 2],+ [w / 2, h / 2],+ ];+ for (const [cx, cy] of corners) {+ ctx.fillRect(cx - handleSize / 2, cy - handleSize / 2, handleSize, handleSize);+ }++ ctx.restore();+ }+private renderPreview(): void {const ctx = this.canvas_.getContext('2d');if (!ctx) return;@@ -653,7 +946,7 @@ export class SceneViewPanel {this.drawEntity(ctx, entity, entity.id === selectedEntity);}- if (selectedEntity !== null && this.gizmoMode_ !== 'select') {+ if (selectedEntity !== null && this.gizmoMode_ !== 'select' && this.gizmoSettings_.showGizmos) {this.drawGizmo(ctx);}@@ -710,7 +1003,7 @@ export class SceneViewPanel {const entityData = this.store_.getSelectedEntityData();const transform = entityData?.components.find(c => c.type === 'LocalTransform');const quat = transform?.data.rotation as { x: number; y: number; z: number; w: number } ?? { x: 0, y: 0, z: 0, w: 1 };- const euler = this.quatToEuler(quat);+ const euler = quatToEuler(quat);const angleRad = -euler.z * Math.PI / 180;ctx.strokeStyle = 'rgba(100, 100, 100, 0.5)';@@ -765,6 +1058,8 @@ export class SceneViewPanel {}private drawGrid(ctx: CanvasRenderingContext2D, w: number, h: number): void {+ if (!this.gizmoSettings_.showGrid) return;+const gridSize = 50;const halfW = w / 2 / this.zoom_;const halfH = h / 2 / this.zoom_;@@ -774,7 +1069,8 @@ export class SceneViewPanel {const startY = Math.floor((-halfH - this.panY_) / gridSize) * gridSize;const endY = Math.ceil((halfH - this.panY_) / gridSize) * gridSize;- ctx.strokeStyle = '#333';+ ctx.globalAlpha = this.gizmoSettings_.gridOpacity;+ ctx.strokeStyle = this.gizmoSettings_.gridColor;ctx.lineWidth = 1 / this.zoom_;for (let x = startX; x <= endX; x += gridSize) {@@ -793,7 +1089,7 @@ export class SceneViewPanel {ctx.stroke();}- ctx.strokeStyle = '#555';+ ctx.strokeStyle = this.lightenColor(this.gizmoSettings_.gridColor, 30);ctx.lineWidth = 2 / this.zoom_;ctx.beginPath();ctx.moveTo(startX, 0);@@ -803,6 +1099,16 @@ export class SceneViewPanel {ctx.moveTo(0, startY);ctx.lineTo(0, endY);ctx.stroke();++ ctx.globalAlpha = 1;+ }++ private lightenColor(hex: string, percent: number): string {+ const num = parseInt(hex.replace('#', ''), 16);+ const r = Math.min(255, ((num >> 16) & 0xff) + Math.round(255 * percent / 100));+ const g = Math.min(255, ((num >> 8) & 0xff) + Math.round(255 * percent / 100));+ const b = Math.min(255, (num & 0xff) + Math.round(255 * percent / 100));+ return `#${((r << 16) | (g << 8) | b).toString(16).padStart(6, '0')}`;}private drawEntity(@@ -815,8 +1121,9 @@ export class SceneViewPanel {if (!transform) return;- const pos = transform.data.position as { x: number; y: number; z: number } ?? { x: 0, y: 0, z: 0 };- const scale = transform.data.scale as { x: number; y: number; z: number } ?? { x: 1, y: 1, z: 1 };+ const worldTransform = this.store_.getWorldTransform(entity.id);+ const pos = worldTransform.position;+ const scale = worldTransform.scale;let w = 50;let h = 50;diff --git a/editor/src/store/EditorStore.ts b/editor/src/store/EditorStore.tsindex efa356e33..de92df481 100644--- a/editor/src/store/EditorStore.ts+++ b/editor/src/store/EditorStore.ts@@ -15,6 +15,8 @@ import {AddComponentCommand,RemoveComponentCommand,} from '../commands';+import { WorldTransformCache } from '../transform/WorldTransformCache';+import type { Transform } from '../math/Transform';// =============================================================================// Types@@ -47,6 +49,7 @@ export class EditorStore {private history_: CommandHistory;private listeners_: Set<EditorListener> = new Set();private nextEntityId_ = 1;+ private worldTransforms_ = new WorldTransformCache();constructor() {this.state_ = {@@ -103,6 +106,7 @@ export class EditorStore {this.state_.filePath = null;this.history_.clear();this.nextEntityId_ = 1;+ this.worldTransforms_.setScene(this.state_.scene);this.notify();}@@ -117,6 +121,7 @@ export class EditorStore {const maxId = scene.entities.reduce((max, e) => Math.max(max, e.id), 0);this.nextEntityId_ = maxId + 1;+ this.worldTransforms_.setScene(scene);this.notify();}@@ -247,9 +252,33 @@ export class EditorStore {component.data[propertyName] = newValue;this.state_.isDirty = true;++ if (componentType === 'LocalTransform') {+ this.worldTransforms_.updateEntity(entityData);+ this.worldTransforms_.markDirty(entity as number);+ }+this.notify();}+ // =========================================================================+ // World Transform+ // =========================================================================++ /**+ * @brief Get cached world transform for an entity+ */+ getWorldTransform(entityId: number): Transform {+ return this.worldTransforms_.getWorldTransform(entityId);+ }++ /**+ * @brief Invalidate all cached transforms (force recalculation)+ */+ invalidateAllTransforms(): void {+ this.worldTransforms_.invalidateAll();+ }+// =========================================================================// Undo/Redo// =========================================================================@@ -257,6 +286,7 @@ export class EditorStore {undo(): void {if (this.history_.undo()) {this.state_.isDirty = true;+ this.worldTransforms_.invalidateAll();this.notify();}}@@ -264,6 +294,7 @@ export class EditorStore {redo(): void {if (this.history_.redo()) {this.state_.isDirty = true;+ this.worldTransforms_.invalidateAll();this.notify();}}@@ -284,6 +315,7 @@ export class EditorStore {private executeCommand(cmd: import('../commands').Command): void {this.history_.execute(cmd);this.state_.isDirty = true;+ this.worldTransforms_.invalidateAll();this.notify();}diff --git a/editor/src/transform/WorldTransformCache.ts b/editor/src/transform/WorldTransformCache.tsnew file mode 100644index 000000000..5f0dd5ec3--- /dev/null+++ b/editor/src/transform/WorldTransformCache.ts@@ -0,0 +1,150 @@+/**+ * @file WorldTransformCache.ts+ * @brief Caches world transforms with dirty flag optimization+ */++import type { SceneData, EntityData } from '../types/SceneTypes';+import {+ Transform,+ composeTransforms,+ createIdentityTransform,+} from '../math/Transform';++// =============================================================================+// WorldTransformCache+// =============================================================================++export class WorldTransformCache {+ private cache_ = new Map<number, Transform>();+ private dirty_ = new Set<number>();+ private entityMap_ = new Map<number, EntityData>();++ /**+ * @brief Set scene data and rebuild entity index+ */+ setScene(scene: SceneData): void {+ this.entityMap_.clear();+ this.cache_.clear();+ this.dirty_.clear();++ for (const entity of scene.entities) {+ this.entityMap_.set(entity.id, entity);+ this.dirty_.add(entity.id);+ }+ }++ /**+ * @brief Update entity data (call when entity components change)+ */+ updateEntity(entity: EntityData): void {+ this.entityMap_.set(entity.id, entity);+ }++ /**+ * @brief Add new entity to cache+ */+ addEntity(entity: EntityData): void {+ this.entityMap_.set(entity.id, entity);+ this.dirty_.add(entity.id);+ }++ /**+ * @brief Remove entity from cache+ */+ removeEntity(entityId: number): void {+ this.entityMap_.delete(entityId);+ this.cache_.delete(entityId);+ this.dirty_.delete(entityId);+ }++ /**+ * @brief Get world transform for an entity (uses cache)+ */+ getWorldTransform(entityId: number): Transform {+ if (!this.dirty_.has(entityId) && this.cache_.has(entityId)) {+ return this.cache_.get(entityId)!;+ }++ const transform = this.computeWorldTransform(entityId);+ this.cache_.set(entityId, transform);+ this.dirty_.delete(entityId);+ return transform;+ }++ /**+ * @brief Mark entity and all descendants as dirty+ */+ markDirty(entityId: number): void {+ this.invalidateSubtree(entityId);+ }++ /**+ * @brief Called when entity hierarchy changes (reparenting)+ */+ onHierarchyChanged(entityId: number): void {+ this.invalidateSubtree(entityId);+ }++ /**+ * @brief Clear all cached transforms+ */+ clear(): void {+ this.cache_.clear();+ this.dirty_.clear();+ }++ /**+ * @brief Mark all entities as dirty (force recalculation)+ */+ invalidateAll(): void {+ this.cache_.clear();+ for (const entityId of this.entityMap_.keys()) {+ this.dirty_.add(entityId);+ }+ }++ // =========================================================================+ // Private Methods+ // =========================================================================++ private invalidateSubtree(entityId: number): void {+ this.dirty_.add(entityId);+ this.cache_.delete(entityId);++ const entity = this.entityMap_.get(entityId);+ if (entity) {+ for (const childId of entity.children) {+ this.invalidateSubtree(childId);+ }+ }+ }++ private computeWorldTransform(entityId: number): Transform {+ const entity = this.entityMap_.get(entityId);+ if (!entity) {+ return createIdentityTransform();+ }++ const localTransform = this.getLocalTransform(entity);++ if (entity.parent === null) {+ return localTransform;+ }++ const parentWorld = this.getWorldTransform(entity.parent);+ return composeTransforms(parentWorld, localTransform);+ }++ private getLocalTransform(entity: EntityData): Transform {+ const comp = entity.components.find(c => c.type === 'LocalTransform');+ if (!comp) {+ return createIdentityTransform();+ }++ return {+ position: (comp.data.position as any) ?? { x: 0, y: 0, z: 0 },+ rotation: (comp.data.rotation as any) ?? { x: 0, y: 0, z: 0, w: 1 },+ scale: (comp.data.scale as any) ?? { x: 1, y: 1, z: 1 },+ };+ }+}diff --git a/editor/src/transform/index.ts b/editor/src/transform/index.tsnew file mode 100644index 000000000..84c78d050--- /dev/null+++ b/editor/src/transform/index.ts@@ -0,0 +1,6 @@+/**+ * @file index.ts+ * @brief Transform utilities exports+ */++export { WorldTransformCache } from './WorldTransformCache';diff --git a/src/esengine/renderer/RenderPipeline.cpp b/src/esengine/renderer/RenderPipeline.cppindex 20fe06a8d..4d1ab69b0 100644--- a/src/esengine/renderer/RenderPipeline.cpp+++ b/src/esengine/renderer/RenderPipeline.cpp@@ -142,12 +142,26 @@ void RenderPipeline::collectFromRegistry(ecs::Registry& registry) {item.depth = transform.position.z;item.flip_x = sprite.flipX;item.flip_y = sprite.flipY;+ item.use_nine_slice = false;+ item.slice_border = {};+ item.texture_size = {1.0f, 1.0f};item.texture_id = context_.getWhiteTextureId();if (sprite.texture.isValid()) {Texture* tex = resource_manager_.getTexture(sprite.texture);if (tex) {item.texture_id = tex->getId();+ item.texture_size = glm::vec2(+ static_cast<f32>(tex->getWidth()),+ static_cast<f32>(tex->getHeight())+ );++ // Auto-detect nine-slice from texture metadata+ const auto* metadata = resource_manager_.getTextureMetadata(sprite.texture);+ if (metadata && metadata->sliceBorder.hasSlicing()) {+ item.use_nine_slice = true;+ item.slice_border = metadata->sliceBorder;+ }}}@@ -237,27 +251,46 @@ void RenderPipeline::executeBatches() {for (const auto& item : items_) {glm::vec2 finalSize = item.size * glm::vec2(item.scale);- f32 angle = glm::angle(item.rotation);- glm::vec3 axis = glm::axis(item.rotation);- if (axis.z < 0) {- angle = -angle;- }+ // Use nine-slice rendering if enabled and has valid borders+ if (item.use_nine_slice) {+ f32 angle = glm::angle(item.rotation);+ glm::vec3 axis = glm::axis(item.rotation);+ if (axis.z < 0) {+ angle = -angle;+ }- if (std::abs(angle) > 0.001f) {- batcher_->drawRotatedQuad(+ batcher_->drawNineSlice(glm::vec2(item.position),finalSize,- angle,item.texture_id,- item.color+ item.texture_size,+ item.slice_border,+ item.color,+ angle);} else {- batcher_->drawQuad(- glm::vec3(item.position.x, item.position.y, item.depth),- finalSize,- item.texture_id,- item.color- );+ f32 angle = glm::angle(item.rotation);+ glm::vec3 axis = glm::axis(item.rotation);+ if (axis.z < 0) {+ angle = -angle;+ }++ if (std::abs(angle) > 0.001f) {+ batcher_->drawRotatedQuad(+ glm::vec2(item.position),+ finalSize,+ angle,+ item.texture_id,+ item.color+ );+ } else {+ batcher_->drawQuad(+ glm::vec3(item.position.x, item.position.y, item.depth),+ finalSize,+ item.texture_id,+ item.color+ );+ }}}diff --git a/src/esengine/renderer/Renderer.cpp b/src/esengine/renderer/Renderer.cppindex 6e527a886..a843196db 100644--- a/src/esengine/renderer/Renderer.cpp+++ b/src/esengine/renderer/Renderer.cpp@@ -25,6 +25,7 @@#endif#include <array>+#include <cmath>#include <vector>namespace esengine {@@ -514,6 +515,146 @@ void BatchRenderer2D::setProjection(const glm::mat4& projection) {data_->projection = projection;}+void BatchRenderer2D::drawNineSlice(const glm::vec2& position, const glm::vec2& size,+ u32 textureId, const glm::vec2& texSize,+ const resource::SliceBorder& border,+ const glm::vec4& color,+ f32 rotation) {+ // Extract border values+ f32 L = border.left;+ f32 R = border.right;+ f32 T = border.top;+ f32 B = border.bottom;++ // Calculate position splits (from left edge of sprite)+ // Sprite is centered at position, so left edge is at position.x - size.x/2+ f32 baseX = position.x - size.x * 0.5f;+ f32 baseY = position.y - size.y * 0.5f;++ f32 x0 = baseX;+ f32 x1 = baseX + L;+ f32 x2 = baseX + size.x - R;+ f32 x3 = baseX + size.x;++ f32 y0 = baseY;+ f32 y1 = baseY + B;+ f32 y2 = baseY + size.y - T;+ f32 y3 = baseY + size.y;++ // Calculate UV splits+ f32 u0 = 0.0f;+ f32 u1 = L / texSize.x;+ f32 u2 = 1.0f - R / texSize.x;+ f32 u3 = 1.0f;++ f32 v0 = 0.0f;+ f32 v1 = B / texSize.y;+ f32 v2 = 1.0f - T / texSize.y;+ f32 v3 = 1.0f;++ // Precompute rotation sin/cos+ f32 cosR = std::cos(rotation);+ f32 sinR = std::sin(rotation);++ // Helper to rotate a point around center (position)+ auto rotatePoint = [&position, cosR, sinR](f32 x, f32 y) -> glm::vec2 {+ f32 dx = x - position.x;+ f32 dy = y - position.y;+ return glm::vec2(+ position.x + dx * cosR - dy * sinR,+ position.y + dx * sinR + dy * cosR+ );+ };++ // Helper to draw a single slice quad with rotation+ auto drawSlice = [this, textureId, &color, &rotatePoint, rotation](+ f32 px, f32 py, f32 pw, f32 ph,+ f32 uvX, f32 uvY, f32 uvW, f32 uvH) {++ if (pw <= 0 || ph <= 0) return;++ // Check if batch is full+ if (data_->vertices.size() >= MAX_VERTICES) {+ flush();+ }++ // Find or add texture slot+ f32 texIndex = 0.0f;+ if (textureId != 0) {+ bool found = false;+ for (u32 i = 0; i < data_->textureSlotIndex; ++i) {+ if (data_->textureSlots[i] == textureId) {+ texIndex = static_cast<f32>(i);+ found = true;+ break;+ }+ }+ if (!found) {+ if (data_->textureSlotIndex >= MAX_TEXTURE_SLOTS) {+ flush();+ }+ data_->textureSlots[data_->textureSlotIndex] = textureId;+ texIndex = static_cast<f32>(data_->textureSlotIndex);+ data_->textureSlotIndex++;+ }+ }++ // Vertices for this slice (bottom-left origin)+ // 0: bottom-left, 1: bottom-right, 2: top-right, 3: top-left+ BatchVertex v0, v1, v2, v3;++ // Apply rotation to each vertex position+ glm::vec2 p0 = rotatePoint(px, py);+ glm::vec2 p1 = rotatePoint(px + pw, py);+ glm::vec2 p2 = rotatePoint(px + pw, py + ph);+ glm::vec2 p3 = rotatePoint(px, py + ph);++ v0.position = glm::vec3(p0.x, p0.y, 0.0f);+ v0.color = color;+ v0.texCoord = glm::vec2(uvX, uvY);+ v0.texIndex = texIndex;++ v1.position = glm::vec3(p1.x, p1.y, 0.0f);+ v1.color = color;+ v1.texCoord = glm::vec2(uvX + uvW, uvY);+ v1.texIndex = texIndex;++ v2.position = glm::vec3(p2.x, p2.y, 0.0f);+ v2.color = color;+ v2.texCoord = glm::vec2(uvX + uvW, uvY + uvH);+ v2.texIndex = texIndex;++ v3.position = glm::vec3(p3.x, p3.y, 0.0f);+ v3.color = color;+ v3.texCoord = glm::vec2(uvX, uvY + uvH);+ v3.texIndex = texIndex;++ data_->vertices.push_back(v0);+ data_->vertices.push_back(v1);+ data_->vertices.push_back(v2);+ data_->vertices.push_back(v3);++ data_->indexCount += 6;+ data_->quadCount++;+ };++ // Draw 9 slices (3x3 grid)+ // Row 1 (bottom): y0 to y1+ drawSlice(x0, y0, x1 - x0, y1 - y0, u0, v0, u1 - u0, v1 - v0); // Bottom-left+ drawSlice(x1, y0, x2 - x1, y1 - y0, u1, v0, u2 - u1, v1 - v0); // Bottom-center+ drawSlice(x2, y0, x3 - x2, y1 - y0, u2, v0, u3 - u2, v1 - v0); // Bottom-right++ // Row 2 (middle): y1 to y2+ drawSlice(x0, y1, x1 - x0, y2 - y1, u0, v1, u1 - u0, v2 - v1); // Middle-left+ drawSlice(x1, y1, x2 - x1, y2 - y1, u1, v1, u2 - u1, v2 - v1); // Center+ drawSlice(x2, y1, x3 - x2, y2 - y1, u2, v1, u3 - u2, v2 - v1); // Middle-right++ // Row 3 (top): y2 to y3+ drawSlice(x0, y2, x1 - x0, y3 - y2, u0, v2, u1 - u0, v3 - v2); // Top-left+ drawSlice(x1, y2, x2 - x1, y3 - y2, u1, v2, u2 - u1, v3 - v2); // Top-center+ drawSlice(x2, y2, x3 - x2, y3 - y2, u2, v2, u3 - u2, v3 - v2); // Top-right+}+u32 BatchRenderer2D::getDrawCallCount() const {return data_ ? data_->drawCallCount : 0;}diff --git a/src/esengine/renderer/Renderer.hpp b/src/esengine/renderer/Renderer.hppindex db5e9f2ee..eeb0c33c8 100644--- a/src/esengine/renderer/Renderer.hpp+++ b/src/esengine/renderer/Renderer.hpp@@ -24,6 +24,7 @@#include "Texture.hpp"#include "RenderContext.hpp"#include "../resource/Handle.hpp"+#include "../resource/TextureMetadata.hpp"// Forward declarationnamespace esengine::resource {@@ -343,6 +344,26 @@ public:f32 rotation, u32 textureId,const glm::vec4& tintColor = glm::vec4(1.0f));+ // =========================================================================+ // Nine-Slice Rendering+ // =========================================================================++ /**+ * @brief Draws a nine-slice sprite+ * @param position Center position (x, y)+ * @param size Total width and height+ * @param textureId GPU texture handle+ * @param texSize Texture dimensions in pixels+ * @param border Nine-slice border configuration+ * @param color Color tint (defaults to white)+ * @param rotation Rotation angle in radians (defaults to 0)+ */+ void drawNineSlice(const glm::vec2& position, const glm::vec2& size,+ u32 textureId, const glm::vec2& texSize,+ const resource::SliceBorder& border,+ const glm::vec4& color = glm::vec4(1.0f),+ f32 rotation = 0.0f);+// =========================================================================// Configuration// =========================================================================