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 asset loading system and fix transparency rendering

esengine0b3ade2d73a8
diff --git a/scripts/build-playable.bat b/scripts/build-playable.bat
index 9e3fac4c7..6722850ce 100644
--- a/scripts/build-playable.bat
+++ b/scripts/build-playable.bat
@@ -37,6 +37,7 @@ echo [4/4] Bundling into single HTML...
node tools\bundle-playable.js ^
--wasm build-web-single\sdk\esengine.single.js ^
--game sdk\examples\playground\build\playable\game.js ^
+ --assets sdk\examples\playground\assets ^
--output playable.html
if errorlevel 1 goto :error
diff --git a/sdk/examples/playground/assets/beer.png b/sdk/examples/playground/assets/beer.png
new file mode 100644
index 000000000..2defeb3d8
Binary files /dev/null and b/sdk/examples/playground/assets/beer.png differ
diff --git a/sdk/examples/playground/src/main.ts b/sdk/examples/playground/src/main.ts
index dd321bd26..dbc734571 100644
--- a/sdk/examples/playground/src/main.ts
+++ b/sdk/examples/playground/src/main.ts
@@ -24,6 +24,8 @@ import {
Text,
TextAlign,
textPlugin,
+ assetPlugin,
+ Assets,
INVALID_TEXTURE
} from 'esengine';
@@ -39,8 +41,14 @@ export async function main(Module: ESEngineModule): Promise<void> {
// Create the app with WASM module (handles renderer init + render loop)
const app = createWebApp(Module);
- // Add the text plugin for automatic Text -> Sprite texture sync
+ // Add plugins
app.addPlugin(textPlugin);
+ app.addPlugin(assetPlugin);
+
+ // Get asset server and load texture
+ const assets = app.getResource(Assets).server;
+ const testIcon = await assets.loadTexture('assets/beer.png');
+ console.log(`Loaded texture: ${testIcon.width}x${testIcon.height}, handle=${testIcon.handle}`);
// Add startup system - runs once at beginning
app.addSystemToSchedule(Schedule.Startup, defineSystem(
@@ -67,13 +75,13 @@ export async function main(Module: ESEngineModule): Promise<void> {
})
.id();
- // Create a test sprite
+ // Create a sprite with loaded texture
const sprite = cmds.spawn()
.insert(Animated)
.insert(Sprite, {
- texture: INVALID_TEXTURE,
- color: { x: 1, y: 0.5, z: 0.2, w: 1 },
- size: { x: 100, y: 100 },
+ texture: testIcon.handle,
+ color: { x: 1, y: 1, z: 1, w: 1 },
+ size: { x: testIcon.width, y: testIcon.height },
uvOffset: { x: 0, y: 0 },
uvScale: { x: 1, y: 1 },
layer: 0,
diff --git a/sdk/src/app.ts b/sdk/src/app.ts
index aaf1b3572..7849d5cb0 100644
--- a/sdk/src/app.ts
+++ b/sdk/src/app.ts
@@ -5,7 +5,7 @@
import { World } from './world';
import { Schedule, SystemDef, SystemRunner } from './system';
-import { ResourceStorage, Time, TimeData } from './resource';
+import { ResourceStorage, Time, TimeData, type ResourceDef } from './resource';
import type { ESEngineModule, CppRegistry } from './wasm';
// =============================================================================
@@ -106,6 +106,23 @@ export class App {
return this.world_;
}
+ // =========================================================================
+ // Resource Access
+ // =========================================================================
+
+ insertResource<T>(resource: ResourceDef<T>, value: T): this {
+ this.resources_.insert(resource, value);
+ return this;
+ }
+
+ getResource<T>(resource: ResourceDef<T>): T {
+ return this.resources_.get(resource);
+ }
+
+ hasResource<T>(resource: ResourceDef<T>): boolean {
+ return this.resources_.has(resource);
+ }
+
// =========================================================================
// Run
// =========================================================================
diff --git a/sdk/src/asset/AssetPlugin.ts b/sdk/src/asset/AssetPlugin.ts
new file mode 100644
index 000000000..167c49414
--- /dev/null
+++ b/sdk/src/asset/AssetPlugin.ts
@@ -0,0 +1,40 @@
+/**
+ * @file AssetPlugin.ts
+ * @brief Plugin that provides asset loading capabilities
+ */
+
+import type { App, Plugin } from '../app';
+import { defineResource } from '../resource';
+import { AssetServer } from './AssetServer';
+
+// =============================================================================
+// Assets Resource
+// =============================================================================
+
+export interface AssetsData {
+ server: AssetServer;
+}
+
+export const Assets = defineResource<AssetsData>(
+ { server: null! },
+ 'Assets'
+);
+
+// =============================================================================
+// Asset Plugin
+// =============================================================================
+
+export class AssetPlugin implements Plugin {
+ build(app: App): void {
+ const module = app.wasmModule;
+ if (!module) {
+ console.warn('AssetPlugin: No WASM module available');
+ return;
+ }
+
+ const server = new AssetServer(module);
+ app.insertResource(Assets, { server });
+ }
+}
+
+export const assetPlugin = new AssetPlugin();
diff --git a/sdk/src/asset/AssetServer.ts b/sdk/src/asset/AssetServer.ts
new file mode 100644
index 000000000..0613b0ad1
--- /dev/null
+++ b/sdk/src/asset/AssetServer.ts
@@ -0,0 +1,186 @@
+/**
+ * @file AssetServer.ts
+ * @brief Asset loading and caching system
+ */
+
+import type { TextureHandle } from '../types';
+import type { ESEngineModule } from '../wasm';
+
+// =============================================================================
+// Types
+// =============================================================================
+
+export interface TextureInfo {
+ handle: TextureHandle;
+ width: number;
+ height: number;
+}
+
+// =============================================================================
+// AssetServer
+// =============================================================================
+
+export class AssetServer {
+ private module_: ESEngineModule;
+ private cache_ = new Map<string, TextureInfo>();
+ private pending_ = new Map<string, Promise<TextureInfo>>();
+ private canvas_: OffscreenCanvas | HTMLCanvasElement;
+ private ctx_: CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D;
+
+ 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 })!;
+ }
+ }
+
+ // =========================================================================
+ // Public API
+ // =========================================================================
+
+ async loadTexture(source: string): Promise<TextureInfo> {
+ const cached = this.cache_.get(source);
+ if (cached) {
+ return cached;
+ }
+
+ const pending = this.pending_.get(source);
+ if (pending) {
+ return pending;
+ }
+
+ const promise = this.loadTextureInternal(source);
+ this.pending_.set(source, promise);
+
+ try {
+ const result = await promise;
+ this.cache_.set(source, result);
+ return result;
+ } finally {
+ this.pending_.delete(source);
+ }
+ }
+
+ getTexture(source: string): TextureInfo | undefined {
+ return this.cache_.get(source);
+ }
+
+ hasTexture(source: string): boolean {
+ return this.cache_.has(source);
+ }
+
+ releaseTexture(source: string): void {
+ const info = this.cache_.get(source);
+ if (info) {
+ const rm = this.module_.getResourceManager();
+ rm.releaseTexture(info.handle);
+ this.cache_.delete(source);
+ }
+ }
+
+ releaseAll(): void {
+ const rm = this.module_.getResourceManager();
+ for (const info of this.cache_.values()) {
+ rm.releaseTexture(info.handle);
+ }
+ this.cache_.clear();
+ }
+
+ // =========================================================================
+ // Private Methods
+ // =========================================================================
+
+ private async loadTextureInternal(source: string): Promise<TextureInfo> {
+ const img = await this.loadImage(source);
+ return this.createTextureFromImage(img);
+ }
+
+ private async loadImage(source: string): Promise<HTMLImageElement | ImageBitmap> {
+ return new Promise((resolve, reject) => {
+ const img = new Image();
+ img.crossOrigin = 'anonymous';
+ img.onload = async () => {
+ if (typeof createImageBitmap !== 'undefined') {
+ try {
+ const bitmap = await createImageBitmap(img, {
+ premultiplyAlpha: 'none',
+ colorSpaceConversion: 'none'
+ });
+ resolve(bitmap);
+ return;
+ } catch {
+ // Fall back to Image element
+ }
+ }
+ resolve(img);
+ };
+ img.onerror = () => reject(new Error(`Failed to load image: ${source}`));
+ img.src = source;
+ });
+ }
+
+ private createTextureFromImage(img: HTMLImageElement | ImageBitmap): TextureInfo {
+ const { width, height } = img;
+
+ if (this.canvas_.width < width || this.canvas_.height < height) {
+ this.canvas_.width = Math.max(this.canvas_.width, this.nextPowerOf2(width));
+ this.canvas_.height = Math.max(this.canvas_.height, this.nextPowerOf2(height));
+ }
+
+ this.ctx_.clearRect(0, 0, this.canvas_.width, this.canvas_.height);
+ this.ctx_.globalCompositeOperation = 'copy';
+ this.ctx_.drawImage(img, 0, 0);
+ this.ctx_.globalCompositeOperation = 'source-over';
+
+ const imageData = this.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 handle = rm.createTexture(width, height, ptr, flipped.length, 1);
+ this.module_._free(ptr);
+
+ return { handle, width, height };
+ }
+
+ 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;
+ }
+
+ private nextPowerOf2(n: number): number {
+ let p = 1;
+ while (p < n) p *= 2;
+ return p;
+ }
+}
diff --git a/sdk/src/asset/index.ts b/sdk/src/asset/index.ts
new file mode 100644
index 000000000..87420e295
--- /dev/null
+++ b/sdk/src/asset/index.ts
@@ -0,0 +1,7 @@
+/**
+ * @file index.ts
+ * @brief Asset module exports
+ */
+
+export { AssetServer, type TextureInfo } from './AssetServer';
+export { Assets, AssetPlugin, assetPlugin, type AssetsData } from './AssetPlugin';
diff --git a/sdk/src/index.ts b/sdk/src/index.ts
index 715ea5f62..6e7138c65 100644
--- a/sdk/src/index.ts
+++ b/sdk/src/index.ts
@@ -151,3 +151,16 @@ export {
type TextData,
type TextRenderResult,
} from './ui';
+
+// =============================================================================
+// Asset
+// =============================================================================
+
+export {
+ AssetServer,
+ Assets,
+ AssetPlugin,
+ assetPlugin,
+ type TextureInfo,
+ type AssetsData,
+} from './asset';
diff --git a/sdk/src/ui/TextPlugin.ts b/sdk/src/ui/TextPlugin.ts
index 194347c67..f9ed56474 100644
--- a/sdk/src/ui/TextPlugin.ts
+++ b/sdk/src/ui/TextPlugin.ts
@@ -55,6 +55,7 @@ export class TextPlugin implements Plugin {
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 };
diff --git a/sdk/src/ui/TextRenderer.ts b/sdk/src/ui/TextRenderer.ts
index 67b3c302a..e43ef4350 100644
--- a/sdk/src/ui/TextRenderer.ts
+++ b/sdk/src/ui/TextRenderer.ts
@@ -63,16 +63,17 @@ export class TextRenderer {
canvas.height = newHeight;
}
- ctx.clearRect(0, 0, width, height);
-
- ctx.font = `${text.fontSize}px ${text.fontFamily}`;
- ctx.textAlign = this.mapAlign(text.align);
- ctx.textBaseline = 'top';
-
const r = Math.round(text.color.x * 255);
const g = Math.round(text.color.y * 255);
const b = Math.round(text.color.z * 255);
const a = text.color.w;
+
+ // Clear with text color but alpha=0 to avoid black fringing
+ ctx.clearRect(0, 0, canvas.width, canvas.height);
+
+ ctx.font = `${text.fontSize}px ${text.fontFamily}`;
+ ctx.textAlign = this.mapAlign(text.align);
+ ctx.textBaseline = 'top';
ctx.fillStyle = `rgba(${r}, ${g}, ${b}, ${a})`;
let y = padding;
@@ -95,6 +96,7 @@ 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();
@@ -214,8 +216,20 @@ 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; // RGBA
+ const rowSize = width * 4;
const flipped = new Uint8Array(pixels.length);
for (let y = 0; y < height; y++) {
diff --git a/src/esengine/bindings/WebSDKEntry.cpp b/src/esengine/bindings/WebSDKEntry.cpp
index 903223404..9fef87d9b 100644
--- a/src/esengine/bindings/WebSDKEntry.cpp
+++ b/src/esengine/bindings/WebSDKEntry.cpp
@@ -74,6 +74,10 @@ void initRenderer() {
g_renderPipeline = makeUnique<RenderPipeline>(*g_renderContext, *g_resourceManager);
g_initialized = true;
+
+ // Initial clear to prevent black flash before first render
+ glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
+ glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
}
void shutdownRenderer() {
@@ -128,7 +132,7 @@ void renderFrame(ecs::Registry& registry, i32 viewportWidth, i32 viewportHeight)
if (!g_initialized || !g_renderContext) return;
glViewport(0, 0, viewportWidth, viewportHeight);
- glClearColor(0.1f, 0.1f, 0.1f, 1.0f);
+ glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glm::mat4 viewProjection = glm::mat4(1.0f);
diff --git a/src/esengine/renderer/RenderPipeline.cpp b/src/esengine/renderer/RenderPipeline.cpp
index a0958825a..20fe06a8d 100644
--- a/src/esengine/renderer/RenderPipeline.cpp
+++ b/src/esengine/renderer/RenderPipeline.cpp
@@ -229,6 +229,7 @@ void RenderPipeline::buildBatches() {
void RenderPipeline::executeBatches() {
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
+ glDisable(GL_DEPTH_TEST);
batcher_->setProjection(view_projection_);
batcher_->beginBatch();
@@ -274,6 +275,7 @@ void RenderPipeline::executeNonBatched() {
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
+ glDisable(GL_DEPTH_TEST);
for (const auto& item : items_) {
glm::mat4 model = glm::mat4(1.0f);
diff --git a/tools/bundle-playable.js b/tools/bundle-playable.js
index 86a441244..f666828af 100644
--- a/tools/bundle-playable.js
+++ b/tools/bundle-playable.js
@@ -5,12 +5,22 @@
* Usage:
* node tools/bundle-playable.js --wasm build-web-single/sdk/esengine.single.js \
* --game sdk/examples/playground/build/playable/game.js \
+ * --assets sdk/examples/playground/assets \
* --output playable.html
*/
const fs = require('fs');
const path = require('path');
+const MIME_TYPES = {
+ '.png': 'image/png',
+ '.jpg': 'image/jpeg',
+ '.jpeg': 'image/jpeg',
+ '.gif': 'image/gif',
+ '.webp': 'image/webp',
+ '.svg': 'image/svg+xml',
+};
+
const HTML_TEMPLATE = `<!DOCTYPE html>
<html lang="en">
<head>
@@ -64,12 +74,14 @@ html,body{width:100%;height:100%;overflow:hidden;background:#000}
</html>`;
function parseArgs(args) {
- const result = { wasm: null, game: null, output: 'playable.html' };
+ const result = { wasm: null, game: null, assets: null, output: 'playable.html' };
for (let i = 0; i < args.length; i++) {
if (args[i] === '--wasm' && args[i + 1]) {
result.wasm = args[++i];
} else if (args[i] === '--game' && args[i + 1]) {
result.game = args[++i];
+ } else if (args[i] === '--assets' && args[i + 1]) {
+ result.assets = args[++i];
} else if (args[i] === '--output' && args[i + 1]) {
result.output = args[++i];
} else if (args[i] === '--help' || args[i] === '-h') {
@@ -77,17 +89,19 @@ function parseArgs(args) {
Bundle ESEngine game into single HTML for playable ads.
Usage:
- node bundle-playable.js --wasm <sdk.js> --game <game.js> [--output <out.html>]
+ node bundle-playable.js --wasm <sdk.js> --game <game.js> [--assets <dir>] [--output <out.html>]
Options:
--wasm Path to esengine.single.js (WASM SDK with inlined binary)
--game Path to game.js (IIFE bundle with SDK runtime)
+ --assets Path to assets directory (images will be inlined as base64)
--output Output HTML file (default: playable.html)
Example:
node tools/bundle-playable.js \\
--wasm build-web-single/sdk/esengine.single.js \\
--game sdk/examples/playground/build/playable/game.js \\
+ --assets sdk/examples/playground/assets \\
--output playable.html
`);
process.exit(0);
@@ -96,6 +110,46 @@ Example:
return result;
}
+function scanAssets(assetsDir) {
+ const assets = new Map();
+ if (!fs.existsSync(assetsDir)) {
+ return assets;
+ }
+
+ function scan(dir, prefix = '') {
+ const entries = fs.readdirSync(dir, { withFileTypes: true });
+ for (const entry of entries) {
+ const fullPath = path.join(dir, entry.name);
+ const relativePath = prefix ? `${prefix}/${entry.name}` : entry.name;
+
+ if (entry.isDirectory()) {
+ scan(fullPath, relativePath);
+ } else {
+ const ext = path.extname(entry.name).toLowerCase();
+ if (MIME_TYPES[ext]) {
+ const data = fs.readFileSync(fullPath);
+ const base64 = data.toString('base64');
+ const dataUrl = `data:${MIME_TYPES[ext]};base64,${base64}`;
+ assets.set(relativePath, dataUrl);
+ }
+ }
+ }
+ }
+
+ scan(assetsDir);
+ return assets;
+}
+
+function inlineAssets(code, assets, assetsPrefix) {
+ let result = code;
+ for (const [relativePath, dataUrl] of assets) {
+ const assetPath = assetsPrefix ? `${assetsPrefix}/${relativePath}` : relativePath;
+ result = result.split(`'${assetPath}'`).join(`'${dataUrl}'`);
+ result = result.split(`"${assetPath}"`).join(`"${dataUrl}"`);
+ }
+ return result;
+}
+
function main() {
const args = parseArgs(process.argv.slice(2));
@@ -118,7 +172,19 @@ function main() {
}
const wasmSdk = fs.readFileSync(args.wasm, 'utf-8');
- const gameCode = fs.readFileSync(args.game, 'utf-8');
+ let gameCode = fs.readFileSync(args.game, 'utf-8');
+
+ // Inline assets if provided
+ if (args.assets) {
+ const assets = scanAssets(args.assets);
+ if (assets.size > 0) {
+ console.log(`Inlining ${assets.size} asset(s)...`);
+ for (const [name] of assets) {
+ console.log(` - ${name}`);
+ }
+ gameCode = inlineAssets(gameCode, assets, 'assets');
+ }
+ }
const html = HTML_TEMPLATE
.replace('{{WASM_SDK}}', wasmSdk)