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 BoundsProvider system and improve Text component
esengine173154edf892
diff --git a/desktop/public/esengine-sdk.js b/desktop/public/esengine-sdk.jsindex fb704c1a9..145db276a 100644--- a/desktop/public/esengine-sdk.js+++ b/desktop/public/esengine-sdk.js@@ -936,7 +936,6 @@ class TextRenderer {}const imageData = ctx.getImageData(0, 0, width, height);const pixels = new Uint8Array(imageData.data.buffer);- this.unpremultiplyAlpha(pixels);const flipped = this.flipVertically(pixels, width, height);const rm = this.module.getResourceManager();const ptr = this.module._malloc(flipped.length);@@ -1040,17 +1039,6 @@ class TextRenderer {p *= 2;return p;}- unpremultiplyAlpha(pixels) {- for (let i = 0; i < pixels.length; i += 4) {- const a = pixels[i + 3];- if (a > 0 && a < 255) {- const scale = 255 / a;- pixels[i] = Math.min(255, Math.round(pixels[i] * scale));- pixels[i + 1] = Math.min(255, Math.round(pixels[i + 1] * scale));- pixels[i + 2] = Math.min(255, Math.round(pixels[i + 2] * scale));- }- }- }flipVertically(pixels, width, height) {const rowSize = width * 4;const flipped = new Uint8Array(pixels.length);@@ -1067,7 +1055,6 @@ class TextRenderer {* @file TextPlugin.ts* @brief Plugin that automatically syncs Text components to Sprite textures*/-defineResource({ renderer: null }, 'TextRenderer');// =============================================================================// Text Plugin// =============================================================================@@ -1079,23 +1066,30 @@ class TextPlugin {return;}const renderer = new TextRenderer(module);- app.addSystemToSchedule(Schedule.Startup, defineSystem([], () => {- // Initialization if needed- }));- app.addSystemToSchedule(Schedule.PreUpdate, defineSystem([Query(Text, Mut(Sprite))], (query) => {- for (const [entity, text, sprite] of query) {- const textData = text;- const spriteData = sprite;- if (!textData.dirty)+ const world = app.world;+ app.addSystemToSchedule(Schedule.PreUpdate, defineSystem([], () => {+ const entities = world.getEntitiesWithComponents([Text]);+ for (const entity of entities) {+ const text = world.get(entity, Text);+ if (!text.dirty)continue;- const result = renderer.renderForEntity(entity, textData);- console.log(`Text texture size: ${result.width}x${result.height}`);- spriteData.texture = result.textureHandle;- spriteData.size = { x: result.width, y: result.height };- spriteData.color = { x: 1, y: 1, z: 1, w: 1 };- spriteData.uvOffset = { x: 0, y: 0 };- spriteData.uvScale = { x: 1, y: 1 };- textData.dirty = false;+ if (!world.has(entity, Sprite)) {+ world.insert(entity, Sprite, {+ texture: 0,+ size: { x: 0, y: 0 },+ color: { x: 1, y: 1, z: 1, w: 1 },+ anchor: { x: 0.5, y: 0.5 },+ flip: { x: false, y: false }+ });+ }+ const result = renderer.renderForEntity(entity, text);+ const sprite = world.get(entity, Sprite);+ sprite.texture = result.textureHandle;+ sprite.size = { x: result.width, y: result.height };+ sprite.uvOffset = { x: 0, y: 0 };+ sprite.uvScale = { x: 1, y: 1 };+ world.insert(entity, Sprite, sprite);+ text.dirty = false;}}));}diff --git a/editor/src/Editor.ts b/editor/src/Editor.tsindex 55909eb37..d1ea3d584 100644--- a/editor/src/Editor.ts+++ b/editor/src/Editor.ts@@ -12,6 +12,7 @@ import { SceneViewPanel } from './panels/SceneViewPanel';import { ContentBrowserPanel, type ContentBrowserOptions } from './panels/ContentBrowserPanel';import { registerBuiltinEditors } from './property/editors';import { registerBuiltinSchemas } from './schemas/ComponentSchemas';+import { initBoundsProviders } from './bounds';import { saveSceneToFile, loadSceneFromFile, loadSceneFromPath } from './io/SceneSerializer';import { icons } from './utils/icons';import { ScriptLoader } from './scripting';@@ -52,6 +53,7 @@ export class Editor {registerBuiltinEditors();registerBuiltinSchemas();+ initBoundsProviders();this.setupLayout();this.setupKeyboardShortcuts();diff --git a/editor/src/bounds/BoundsProvider.ts b/editor/src/bounds/BoundsProvider.tsnew file mode 100644index 000000000..77cd80048--- /dev/null+++ b/editor/src/bounds/BoundsProvider.ts@@ -0,0 +1,13 @@+/**+ * @file BoundsProvider.ts+ * @brief Interface for component bounds providers+ */++export interface Bounds {+ width: number;+ height: number;+}++export interface BoundsProvider {+ getBounds(data: any): Bounds | null;+}diff --git a/editor/src/bounds/BoundsRegistry.ts b/editor/src/bounds/BoundsRegistry.tsnew file mode 100644index 000000000..08270aa92--- /dev/null+++ b/editor/src/bounds/BoundsRegistry.ts@@ -0,0 +1,23 @@+/**+ * @file BoundsRegistry.ts+ * @brief Registry for component bounds providers+ */++import type { Bounds, BoundsProvider } from './BoundsProvider';++const providers = new Map<string, BoundsProvider>();++export function registerBoundsProvider(componentType: string, provider: BoundsProvider): void {+ providers.set(componentType, provider);+}++export function getEntityBounds(components: { type: string; data: any }[]): Bounds {+ for (const comp of components) {+ const provider = providers.get(comp.type);+ if (provider) {+ const bounds = provider.getBounds(comp.data);+ if (bounds) return bounds;+ }+ }+ return { width: 50, height: 50 };+}diff --git a/editor/src/bounds/SpriteBoundsProvider.ts b/editor/src/bounds/SpriteBoundsProvider.tsnew file mode 100644index 000000000..d9c9f34cd--- /dev/null+++ b/editor/src/bounds/SpriteBoundsProvider.ts@@ -0,0 +1,15 @@+/**+ * @file SpriteBoundsProvider.ts+ * @brief Bounds provider for Sprite component+ */++import type { Bounds, BoundsProvider } from './BoundsProvider';++export const spriteBoundsProvider: BoundsProvider = {+ getBounds(data: any): Bounds | null {+ if (data?.size?.x && data?.size?.y) {+ return { width: data.size.x, height: data.size.y };+ }+ return null;+ }+};diff --git a/editor/src/bounds/TextBoundsProvider.ts b/editor/src/bounds/TextBoundsProvider.tsnew file mode 100644index 000000000..d862b5a22--- /dev/null+++ b/editor/src/bounds/TextBoundsProvider.ts@@ -0,0 +1,41 @@+/**+ * @file TextBoundsProvider.ts+ * @brief Bounds provider for Text component+ */++import type { Bounds, BoundsProvider } from './BoundsProvider';++let measureCtx: CanvasRenderingContext2D | null = null;++function getContext(): CanvasRenderingContext2D {+ if (!measureCtx) {+ measureCtx = document.createElement('canvas').getContext('2d')!;+ }+ return measureCtx;+}++export const textBoundsProvider: BoundsProvider = {+ getBounds(data: any): Bounds | null {+ 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 ctx = getContext();+ ctx.font = `${fontSize}px ${fontFamily}`;++ const lines = content.split('\n');+ let maxWidth = 0;+ for (const line of lines) {+ maxWidth = Math.max(maxWidth, ctx.measureText(line).width);+ }++ const padding = fontSize * 0.2;+ return {+ width: Math.ceil(maxWidth) + padding * 2,+ height: Math.ceil(lines.length * fontSize * lineHeight) + padding * 2+ };+ }+};diff --git a/editor/src/bounds/index.ts b/editor/src/bounds/index.tsnew file mode 100644index 000000000..b6c8f1d25--- /dev/null+++ b/editor/src/bounds/index.ts@@ -0,0 +1,16 @@+/**+ * @file bounds/index.ts+ * @brief Bounds module exports and initialization+ */++export * from './BoundsProvider';+export * from './BoundsRegistry';++import { registerBoundsProvider } from './BoundsRegistry';+import { spriteBoundsProvider } from './SpriteBoundsProvider';+import { textBoundsProvider } from './TextBoundsProvider';++export function initBoundsProviders(): void {+ registerBoundsProvider('Sprite', spriteBoundsProvider);+ registerBoundsProvider('Text', textBoundsProvider);+}diff --git a/editor/src/panels/SceneViewPanel.ts b/editor/src/panels/SceneViewPanel.tsindex 6fbeb6482..be0cb6282 100644--- a/editor/src/panels/SceneViewPanel.ts+++ b/editor/src/panels/SceneViewPanel.ts@@ -12,6 +12,7 @@ import { hasSlicing, parseTextureMetadata } from '../types/TextureMetadata';import { icons } from '../utils/icons';import { EditorSceneRenderer } from '../renderer/EditorSceneRenderer';import { quatToEuler, eulerToQuat } from '../math/Transform';+import { getEntityBounds } from '../bounds';// =============================================================================// Types@@ -775,7 +776,6 @@ export class SceneViewPanel {private findEntityAtPosition(worldX: number, worldY: number): Entity | null {const scene = this.store_.scene;- const defaultSize = 50;for (let i = scene.entities.length - 1; i >= 0; i--) {const entity = scene.entities[i];@@ -786,16 +786,10 @@ export class SceneViewPanel {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;- let h = defaultSize;-- if (sprite) {- const size = sprite.data.size as { x: number; y: number };- w = (size?.x ?? defaultSize) * Math.abs(scale.x);- h = (size?.y ?? defaultSize) * Math.abs(scale.y);- }+ const bounds = getEntityBounds(entity.components);+ const w = bounds.width * Math.abs(scale.x);+ const h = bounds.height * Math.abs(scale.y);const halfW = w / 2;const halfH = h / 2;@@ -883,24 +877,15 @@ export class SceneViewPanel {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);- }- }+ const bounds = getEntityBounds(entityData.components);+ const w = bounds.width * Math.abs(scale.x);+ const h = bounds.height * Math.abs(scale.y);ctx.save();ctx.translate(pos.x, -pos.y);diff --git a/editor/src/renderer/EditorTextRenderer.ts b/editor/src/renderer/EditorTextRenderer.tsindex 18ef66a49..3dbf6036f 100644--- a/editor/src/renderer/EditorTextRenderer.ts+++ b/editor/src/renderer/EditorTextRenderer.ts@@ -120,7 +120,6 @@ export class EditorTextRenderer {const imageData = ctx.getImageData(0, 0, width, height);const pixels = new Uint8Array(imageData.data.buffer);- this.unpremultiplyAlpha(pixels);const flipped = this.flipVertically(pixels, width, height);const rm = this.module_.getResourceManager();@@ -189,18 +188,6 @@ export class EditorTextRenderer {return p;}- private unpremultiplyAlpha(pixels: Uint8Array): void {- for (let i = 0; i < pixels.length; i += 4) {- const a = pixels[i + 3];- if (a > 0 && a < 255) {- const scale = 255 / a;- pixels[i] = Math.min(255, Math.round(pixels[i] * scale));- pixels[i + 1] = Math.min(255, Math.round(pixels[i + 1] * scale));- pixels[i + 2] = Math.min(255, Math.round(pixels[i + 2] * scale));- }- }- }-private flipVertically(pixels: Uint8Array, width: number, height: number): Uint8Array {const rowSize = width * 4;const flipped = new Uint8Array(pixels.length);diff --git a/sdk/src/ui/TextPlugin.ts b/sdk/src/ui/TextPlugin.tsindex f9ed56474..d53165fc0 100644--- a/sdk/src/ui/TextPlugin.ts+++ b/sdk/src/ui/TextPlugin.ts@@ -5,24 +5,9 @@import type { App, Plugin } from '../app';import { defineSystem, Schedule } from '../system';-import { Query, Mut } from '../query';import { Sprite, type SpriteData } from '../component';import { Text, type TextData } from './text';import { TextRenderer } from './TextRenderer';-import { defineResource, Res } from '../resource';--// =============================================================================-// TextRenderer Resource-// =============================================================================--export interface TextRendererData {- renderer: TextRenderer | null;-}--export const TextRendererRes = defineResource<TextRendererData>(- { renderer: null },- 'TextRenderer'-);// =============================================================================// Text Plugin@@ -37,33 +22,37 @@ export class TextPlugin implements Plugin {}const renderer = new TextRenderer(module);+ const world = app.world;- app.addSystemToSchedule(Schedule.Startup, defineSystem(+ app.addSystemToSchedule(Schedule.PreUpdate, defineSystem([],() => {- // Initialization if needed- }- ));-- app.addSystemToSchedule(Schedule.PreUpdate, defineSystem(- [Query(Text, Mut(Sprite))],- (query) => {- for (const [entity, text, sprite] of query) {- const textData = text as TextData;- const spriteData = sprite as SpriteData;-- if (!textData.dirty) continue;-- const result = renderer.renderForEntity(entity, textData);- console.log(`Text texture size: ${result.width}x${result.height}`);-- spriteData.texture = result.textureHandle;- spriteData.size = { x: result.width, y: result.height };- spriteData.color = { x: 1, y: 1, z: 1, w: 1 };- spriteData.uvOffset = { x: 0, y: 0 };- spriteData.uvScale = { x: 1, y: 1 };-- textData.dirty = false;+ const entities = world.getEntitiesWithComponents([Text]);++ for (const entity of entities) {+ const text = world.get(entity, Text) as TextData;+ if (!text.dirty) continue;++ if (!world.has(entity, Sprite)) {+ world.insert(entity, Sprite, {+ texture: 0,+ size: { x: 0, y: 0 },+ color: { x: 1, y: 1, z: 1, w: 1 },+ anchor: { x: 0.5, y: 0.5 },+ flip: { x: false, y: false }+ });+ }++ const result = renderer.renderForEntity(entity, text);++ const sprite = world.get(entity, Sprite) as SpriteData;+ sprite.texture = result.textureHandle;+ sprite.size = { x: result.width, y: result.height };+ sprite.uvOffset = { x: 0, y: 0 };+ sprite.uvScale = { x: 1, y: 1 };+ world.insert(entity, Sprite, sprite);++ text.dirty = false;}}));diff --git a/sdk/src/ui/TextRenderer.ts b/sdk/src/ui/TextRenderer.tsindex 1b9041242..dd60a2e00 100644--- a/sdk/src/ui/TextRenderer.ts+++ b/sdk/src/ui/TextRenderer.ts@@ -96,7 +96,6 @@ export class TextRenderer {const imageData = ctx.getImageData(0, 0, width, height);const pixels = new Uint8Array(imageData.data.buffer);- this.unpremultiplyAlpha(pixels);const flipped = this.flipVertically(pixels, width, height);const rm = this.module.getResourceManager();@@ -216,18 +215,6 @@ export class TextRenderer {return p;}- private unpremultiplyAlpha(pixels: Uint8Array): void {- for (let i = 0; i < pixels.length; i += 4) {- const a = pixels[i + 3];- if (a > 0 && a < 255) {- const scale = 255 / a;- pixels[i] = Math.min(255, Math.round(pixels[i] * scale));- pixels[i + 1] = Math.min(255, Math.round(pixels[i + 1] * scale));- pixels[i + 2] = Math.min(255, Math.round(pixels[i + 2] * scale));- }- }- }-private flipVertically(pixels: Uint8Array, width: number, height: number): Uint8Array {const rowSize = width * 4;const flipped = new Uint8Array(pixels.length);diff --git a/sdk/src/ui/index.ts b/sdk/src/ui/index.tsindex 53959cefd..40a295223 100644--- a/sdk/src/ui/index.ts+++ b/sdk/src/ui/index.ts@@ -21,6 +21,4 @@ export {export {TextPlugin,textPlugin,- TextRendererRes,- type TextRendererData,} from './TextPlugin';