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.

feat: Add Text component rendering support

esengine56ff4318ade5
diff --git a/desktop/public/esengine-sdk.js b/desktop/public/esengine-sdk.js
index 8126ad60c..fb704c1a9 100644
--- a/desktop/public/esengine-sdk.js
+++ b/desktop/public/esengine-sdk.js
@@ -556,12 +556,8 @@ class World {
}
setParent(child, parent) {
if (this.cppRegistry_) {
- console.log(`[World] Calling cppRegistry_.setParent(${child}, ${parent})`);
this.cppRegistry_.setParent(child, parent);
}
- else {
- console.warn('[World] setParent called but cppRegistry_ is null!');
- }
}
// =========================================================================
// Component Management
@@ -884,13 +880,13 @@ class TextRenderer {
this.module = module;
if (typeof OffscreenCanvas !== 'undefined') {
this.canvas = new OffscreenCanvas(512, 512);
- this.ctx = this.canvas.getContext('2d');
+ this.ctx = this.canvas.getContext('2d', { willReadFrequently: true });
}
else {
this.canvas = document.createElement('canvas');
this.canvas.width = 512;
this.canvas.height = 512;
- this.ctx = this.canvas.getContext('2d');
+ this.ctx = this.canvas.getContext('2d', { willReadFrequently: true });
}
}
/**
@@ -1339,7 +1335,6 @@ async function loadSceneWithAssets(world, sceneData, options) {
const entity = entityMap.get(entityData.id);
const parentEntity = entityMap.get(entityData.parent);
if (entity !== undefined && parentEntity !== undefined) {
- console.log(`[SceneLoader] setParent: entity ${entity} -> parent ${parentEntity}`);
world.setParent(entity, parentEntity);
}
}
@@ -1419,12 +1414,6 @@ class PreviewPlugin {
assetServer: assets.server
});
this.ensureCamera();
- this.debugCamera();
- // 延迟检查,等渲染循环开始后
- setTimeout(() => {
- console.log('[PreviewPlugin] === Delayed Check (after render loop) ===');
- this.debugCamera();
- }, 1000);
}
catch (err) {
console.error('[PreviewPlugin] Failed to load scene:', err);
@@ -1465,44 +1454,6 @@ class PreviewPlugin {
world.insert(cameraEntity, Camera, cameraData);
}
}
- debugCamera() {
- if (!this.app_)
- return;
- const world = this.app_.world;
- const cameraEntities = world.getEntitiesWithComponents([Camera]);
- console.log('[PreviewPlugin] === Camera Debug ===');
- console.log(`[PreviewPlugin] Found ${cameraEntities.length} camera entities`);
- for (const entity of cameraEntities) {
- const camera = world.get(entity, Camera);
- const hasTransform = world.has(entity, LocalTransform);
- console.log(`[PreviewPlugin] Camera Entity ${entity}:`);
- console.log(` - isActive: ${camera.isActive}`);
- console.log(` - projectionType: ${camera.projectionType} (0=Ortho, 1=Persp)`);
- console.log(` - orthoSize: ${camera.orthoSize}`);
- console.log(` - hasLocalTransform: ${hasTransform}`);
- if (hasTransform) {
- const transform = world.get(entity, LocalTransform);
- console.log(` - position: (${transform.position.x}, ${transform.position.y}, ${transform.position.z})`);
- }
- }
- console.log('[PreviewPlugin] === Sprite Debug ===');
- const spriteEntities = world.getEntitiesWithComponents([Sprite, LocalTransform]);
- console.log(`[PreviewPlugin] Found ${spriteEntities.length} sprite entities with transform`);
- for (const entity of spriteEntities.slice(0, 5)) {
- const sprite = world.get(entity, Sprite);
- const localTransform = world.get(entity, LocalTransform);
- const hasWorld = world.has(entity, WorldTransform);
- console.log(`[PreviewPlugin] Sprite Entity ${entity}:`);
- console.log(` - texture: ${sprite.texture}`);
- console.log(` - size: (${sprite.size.x}, ${sprite.size.y})`);
- console.log(` - localPosition: (${localTransform.position.x}, ${localTransform.position.y}, ${localTransform.position.z})`);
- console.log(` - hasWorldTransform: ${hasWorld}`);
- if (hasWorld) {
- const worldTransform = world.get(entity, WorldTransform);
- console.log(` - worldPosition: (${worldTransform.position.x}, ${worldTransform.position.y}, ${worldTransform.position.z})`);
- }
- }
- }
}
export { App, AssetPlugin, AssetServer, Assets, Camera, Canvas, Children, Commands, CommandsInstance, EntityCommands, INVALID_ENTITY, INVALID_TEXTURE, Input, LocalTransform, Mut, Parent, PreviewPlugin, Query, QueryInstance, Res, ResMut, Schedule, Sprite, SystemRunner, Text, TextAlign, TextBaseline, TextPlugin, TextRenderer, Time, Velocity, World, WorldTransform, assetPlugin, color, createWebApp, defineComponent, defineResource, defineSystem, defineTag, isBuiltinComponent, loadSceneData, loadSceneWithAssets, quat, textPlugin, vec2, vec3, vec4 };
diff --git a/desktop/src-tauri/src/preview_template.html b/desktop/src-tauri/src/preview_template.html
index 6c6d564ce..3d293760a 100644
--- a/desktop/src-tauri/src/preview_template.html
+++ b/desktop/src-tauri/src/preview_template.html
@@ -40,6 +40,7 @@
import {
createWebApp,
assetPlugin,
+ textPlugin,
PreviewPlugin
} from '/esengine-sdk.js';
@@ -147,6 +148,7 @@
getViewportSize: getCanvasViewportSize
});
app.addPlugin(assetPlugin);
+ app.addPlugin(textPlugin);
app.addPlugin(previewPlugin);
// Setup resize handler AFTER app is created
diff --git a/editor/src/renderer/EditorSceneRenderer.ts b/editor/src/renderer/EditorSceneRenderer.ts
index 75b3680a5..eb3fc7649 100644
--- a/editor/src/renderer/EditorSceneRenderer.ts
+++ b/editor/src/renderer/EditorSceneRenderer.ts
@@ -12,6 +12,7 @@ import {
composeTransforms,
createIdentityTransform,
} from '../math/Transform';
+import { EditorTextRenderer } from './EditorTextRenderer';
// =============================================================================
// EditorSceneRenderer
@@ -21,6 +22,7 @@ export class EditorSceneRenderer {
private module_: ESEngineModule | null = null;
private registry_: CppRegistry | null = null;
private textureManager_: EditorTextureManager | null = null;
+ private textRenderer_: EditorTextRenderer | null = null;
private camera_: EditorCamera;
private initialized_ = false;
private projectDir_ = '';
@@ -55,6 +57,7 @@ export class EditorSceneRenderer {
this.registry_ = new module.Registry();
this.textureManager_ = new EditorTextureManager(module);
+ this.textRenderer_ = new EditorTextRenderer(module);
this.initialized_ = true;
return true;
@@ -168,6 +171,11 @@ export class EditorSceneRenderer {
this.textureManager_ = null;
}
+ if (this.textRenderer_) {
+ this.textRenderer_.releaseAll();
+ this.textRenderer_ = null;
+ }
+
if (this.registry_) {
this.registry_.delete();
this.registry_ = null;
@@ -210,6 +218,10 @@ export class EditorSceneRenderer {
case 'Camera':
this.syncCamera(entity, comp.data);
break;
+
+ case 'Text':
+ this.syncText(entity, comp.data, entityId);
+ break;
}
}
@@ -305,4 +317,26 @@ export class EditorSceneRenderer {
priority: data.priority ?? 0,
});
}
+
+ private syncText(entity: Entity, data: any, entityId: number): void {
+ if (!this.registry_ || !this.textRenderer_) return;
+
+ const result = this.textRenderer_.renderText(entityId, data);
+ if (!result) return;
+
+ if (this.registry_.hasSprite(entity)) {
+ this.registry_.removeSprite(entity);
+ }
+
+ this.registry_.addSprite(entity, {
+ texture: result.textureHandle,
+ color: { x: 1, y: 1, z: 1, w: 1 },
+ size: { x: result.width, y: result.height },
+ uvOffset: { x: 0, y: 0 },
+ uvScale: { x: 1, y: 1 },
+ layer: 25,
+ flipX: false,
+ flipY: false,
+ });
+ }
}
diff --git a/editor/src/renderer/EditorTextRenderer.ts b/editor/src/renderer/EditorTextRenderer.ts
new file mode 100644
index 000000000..18ef66a49
--- /dev/null
+++ b/editor/src/renderer/EditorTextRenderer.ts
@@ -0,0 +1,216 @@
+/**
+ * @file EditorTextRenderer.ts
+ * @brief Renders text to GPU textures for editor scene view
+ */
+
+import type { ESEngineModule } from 'esengine';
+
+// =============================================================================
+// Text Render Result
+// =============================================================================
+
+export interface TextRenderResult {
+ textureHandle: number;
+ width: number;
+ height: number;
+}
+
+// =============================================================================
+// EditorTextRenderer
+// =============================================================================
+
+export class EditorTextRenderer {
+ private canvas_: OffscreenCanvas | HTMLCanvasElement;
+ private ctx_: CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D;
+ private module_: ESEngineModule;
+ private cache_ = new Map<number, TextRenderResult>();
+
+ constructor(module: ESEngineModule) {
+ this.module_ = module;
+
+ if (typeof OffscreenCanvas !== 'undefined') {
+ this.canvas_ = new OffscreenCanvas(512, 512);
+ this.ctx_ = this.canvas_.getContext('2d', { willReadFrequently: true })!;
+ } else {
+ this.canvas_ = document.createElement('canvas');
+ this.canvas_.width = 512;
+ this.canvas_.height = 512;
+ this.ctx_ = this.canvas_.getContext('2d', { willReadFrequently: true })!;
+ }
+ }
+
+ renderText(entityId: number, data: any): TextRenderResult | null {
+ const existing = this.cache_.get(entityId);
+ if (existing) {
+ const rm = this.module_.getResourceManager();
+ rm.releaseTexture(existing.textureHandle);
+ }
+
+ const result = this.renderTextInternal(data);
+ if (result) {
+ this.cache_.set(entityId, result);
+ }
+ return result;
+ }
+
+ releaseAll(): void {
+ const rm = this.module_.getResourceManager();
+ for (const result of this.cache_.values()) {
+ rm.releaseTexture(result.textureHandle);
+ }
+ this.cache_.clear();
+ }
+
+ // =========================================================================
+ // Private Methods
+ // =========================================================================
+
+ private renderTextInternal(data: any): TextRenderResult | null {
+ const content = data.content ?? '';
+ if (!content) return null;
+
+ const fontFamily = data.fontFamily ?? 'Arial';
+ const fontSize = data.fontSize ?? 24;
+ const color = data.color ?? { x: 1, y: 1, z: 1, w: 1 };
+ const align = data.align ?? 0;
+ const maxWidth = data.maxWidth ?? 0;
+ const lineHeight = data.lineHeight ?? 1.2;
+
+ const ctx = this.ctx_;
+ const canvas = this.canvas_;
+
+ ctx.font = `${fontSize}px ${fontFamily}`;
+
+ const lines = this.wrapText(content, maxWidth);
+ const lineHeightPx = Math.ceil(fontSize * lineHeight);
+ const padding = Math.ceil(fontSize * 0.2);
+ const width = Math.ceil(this.measureWidth(lines)) + padding * 2;
+ const height = Math.ceil(lines.length * lineHeightPx) + padding * 2;
+
+ if (canvas.width < width || canvas.height < height) {
+ const newWidth = Math.max(canvas.width, this.nextPowerOf2(width));
+ const newHeight = Math.max(canvas.height, this.nextPowerOf2(height));
+ canvas.width = newWidth;
+ canvas.height = newHeight;
+ }
+
+ const r = Math.round(color.x * 255);
+ const g = Math.round(color.y * 255);
+ const b = Math.round(color.z * 255);
+ const a = color.w;
+
+ ctx.clearRect(0, 0, canvas.width, canvas.height);
+ ctx.font = `${fontSize}px ${fontFamily}`;
+ ctx.textAlign = this.mapAlign(align);
+ ctx.textBaseline = 'top';
+ ctx.fillStyle = `rgba(${r}, ${g}, ${b}, ${a})`;
+
+ let y = padding;
+ for (const line of lines) {
+ let x: number;
+ switch (align) {
+ case 0: x = padding; break;
+ case 1: x = width / 2; break;
+ case 2: x = width - padding; break;
+ default: x = padding;
+ }
+ ctx.fillText(line, x, y);
+ y += lineHeightPx;
+ }
+
+ 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);
+ this.module_.HEAPU8.set(flipped, ptr);
+
+ const textureHandle = rm.createTexture(width, height, ptr, flipped.length, 1);
+
+ this.module_._free(ptr);
+
+ return { textureHandle, width, height };
+ }
+
+ private wrapText(text: string, maxWidth: number): string[] {
+ if (!text) return [''];
+ if (maxWidth <= 0) return text.split('\n');
+
+ const paragraphs = text.split('\n');
+ const lines: string[] = [];
+
+ for (const paragraph of paragraphs) {
+ const words = paragraph.split(' ');
+ let currentLine = '';
+
+ for (const word of words) {
+ const testLine = currentLine ? `${currentLine} ${word}` : word;
+ const metrics = this.ctx_.measureText(testLine);
+
+ if (metrics.width > maxWidth && currentLine) {
+ lines.push(currentLine);
+ currentLine = word;
+ } else {
+ currentLine = testLine;
+ }
+ }
+ lines.push(currentLine);
+ }
+
+ return lines;
+ }
+
+ private measureWidth(lines: string[]): number {
+ let maxWidth = 0;
+ for (const line of lines) {
+ const metrics = this.ctx_.measureText(line);
+ const width = metrics.actualBoundingBoxLeft !== undefined
+ ? metrics.actualBoundingBoxLeft + metrics.actualBoundingBoxRight
+ : metrics.width;
+ maxWidth = Math.max(maxWidth, width);
+ }
+ return maxWidth;
+ }
+
+ private mapAlign(align: number): CanvasTextAlign {
+ switch (align) {
+ case 0: return 'left';
+ case 1: return 'center';
+ case 2: return 'right';
+ default: return 'left';
+ }
+ }
+
+ private nextPowerOf2(n: number): number {
+ let p = 1;
+ while (p < n) p *= 2;
+ 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);
+
+ for (let y = 0; y < height; y++) {
+ const srcOffset = y * rowSize;
+ const dstOffset = (height - 1 - y) * rowSize;
+ flipped.set(pixels.subarray(srcOffset, srcOffset + rowSize), dstOffset);
+ }
+
+ return flipped;
+ }
+}
diff --git a/editor/src/renderer/index.ts b/editor/src/renderer/index.ts
index 2387e06cc..733e79554 100644
--- a/editor/src/renderer/index.ts
+++ b/editor/src/renderer/index.ts
@@ -5,4 +5,5 @@
export { EditorSceneRenderer } from './EditorSceneRenderer';
export { EditorTextureManager } from './EditorTextureManager';
+export { EditorTextRenderer } from './EditorTextRenderer';
export { EditorCamera } from './EditorCamera';
diff --git a/sdk/src/scene.ts b/sdk/src/scene.ts
index 4706e07b0..27e93ec8e 100644
--- a/sdk/src/scene.ts
+++ b/sdk/src/scene.ts
@@ -120,7 +120,6 @@ export async function loadSceneWithAssets(
const entity = entityMap.get(entityData.id);
const parentEntity = entityMap.get(entityData.parent);
if (entity !== undefined && parentEntity !== undefined) {
- console.log(`[SceneLoader] setParent: entity ${entity} -> parent ${parentEntity}`);
world.setParent(entity, parentEntity);
}
}
diff --git a/sdk/src/ui/TextRenderer.ts b/sdk/src/ui/TextRenderer.ts
index e43ef4350..1b9041242 100644
--- a/sdk/src/ui/TextRenderer.ts
+++ b/sdk/src/ui/TextRenderer.ts
@@ -32,12 +32,12 @@ export class TextRenderer {
if (typeof OffscreenCanvas !== 'undefined') {
this.canvas = new OffscreenCanvas(512, 512);
- this.ctx = this.canvas.getContext('2d')!;
+ this.ctx = this.canvas.getContext('2d', { willReadFrequently: true })!;
} else {
this.canvas = document.createElement('canvas');
this.canvas.width = 512;
this.canvas.height = 512;
- this.ctx = this.canvas.getContext('2d')!;
+ this.ctx = this.canvas.getContext('2d', { willReadFrequently: true })!;
}
}
diff --git a/sdk/src/world.ts b/sdk/src/world.ts
index 780c4b664..587a323c1 100644
--- a/sdk/src/world.ts
+++ b/sdk/src/world.ts
@@ -69,10 +69,7 @@ export class World {
setParent(child: Entity, parent: Entity): void {
if (this.cppRegistry_) {
- console.log(`[World] Calling cppRegistry_.setParent(${child}, ${parent})`);
this.cppRegistry_.setParent(child, parent);
- } else {
- console.warn('[World] setParent called but cppRegistry_ is null!');
}
}