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(rc6): compressed textures end-to-end — both texture paths via compressed.ts (C2)

yhh5568f719468a
diff --git a/desktop/package.json b/desktop/package.json
index dea753979..d1c92019f 100644
--- a/desktop/package.json
+++ b/desktop/package.json
@@ -25,6 +25,7 @@
"verify:render:tilemap": "vite build && ESTELLA_VERIFY_SCENE=/scenes/tilemap-flip.esscene ESTELLA_VERIFY_MANIFEST=/scenes/tilemap-flip.textures.json ESTELLA_VERIFY_W=256 ESTELLA_VERIFY_H=256 ESTELLA_VERIFY_STEPS=2 ESTELLA_VERIFY_EXPECT=\"[{\\\"x\\\":0.40,\\\"y\\\":0.36,\\\"rgb\\\":[255,0,0]},{\\\"x\\\":0.60,\\\"y\\\":0.36,\\\"rgb\\\":[0,255,0]},{\\\"x\\\":0.40,\\\"y\\\":0.58,\\\"rgb\\\":[0,0,255]},{\\\"x\\\":0.60,\\\"y\\\":0.58,\\\"rgb\\\":[255,255,0]}]\" electron scripts/headless-verify.mjs",
"verify:render:tilemap:transform": "vite build && ESTELLA_VERIFY_SCENE=/scenes/tilemap-transform.esscene ESTELLA_VERIFY_MANIFEST=/scenes/tilemap-transform.textures.json ESTELLA_VERIFY_W=256 ESTELLA_VERIFY_H=256 ESTELLA_VERIFY_STEPS=2 ESTELLA_VERIFY_EXPECT=\"[{\\\"x\\\":0.40,\\\"y\\\":0.36,\\\"rgb\\\":[255,255,0]},{\\\"x\\\":0.60,\\\"y\\\":0.36,\\\"rgb\\\":[0,255,0]},{\\\"x\\\":0.40,\\\"y\\\":0.58,\\\"rgb\\\":[0,0,255]},{\\\"x\\\":0.60,\\\"y\\\":0.58,\\\"rgb\\\":[255,0,0]}]\" electron scripts/headless-verify.mjs",
"verify:render:material": "vite build && ESTELLA_VERIFY_SCENE=/scenes/mat-tint.esscene ESTELLA_VERIFY_MANIFEST=/scenes/mat-tint.textures.json ESTELLA_VERIFY_W=256 ESTELLA_VERIFY_H=256 ESTELLA_VERIFY_STEPS=2 ESTELLA_VERIFY_EXPECT=\"[{\\\"x\\\":0.5,\\\"y\\\":0.5,\\\"rgb\\\":[255,0,0],\\\"tol\\\":40}]\" electron scripts/headless-verify.mjs",
+ "verify:render:ktx2": "vite build && ESTELLA_VERIFY_SCENE=/scenes/ktx2-sprite.esscene ESTELLA_VERIFY_MANIFEST=/scenes/ktx2-sprite.textures.json ESTELLA_VERIFY_W=256 ESTELLA_VERIFY_H=256 ESTELLA_VERIFY_STEPS=2 ESTELLA_VERIFY_EXPECT=\"[{\\\"x\\\":0.5,\\\"y\\\":0.5,\\\"rgb\\\":[0,180,0],\\\"tol\\\":50}]\" electron scripts/headless-verify.mjs",
"verify:render:material:instance": "vite build && ESTELLA_VERIFY_SCENE=/scenes/mat-instance.esscene ESTELLA_VERIFY_MANIFEST=/scenes/mat-instance.textures.json ESTELLA_VERIFY_W=256 ESTELLA_VERIFY_H=256 ESTELLA_VERIFY_STEPS=2 ESTELLA_VERIFY_EXPECT=\"[{\\\"x\\\":0.5,\\\"y\\\":0.5,\\\"rgb\\\":[0,255,0],\\\"tol\\\":40}]\" electron scripts/headless-verify.mjs",
"verify:render:material:texture": "vite build && ESTELLA_VERIFY_SCENE=/scenes/mat-tex.esscene ESTELLA_VERIFY_MANIFEST=/scenes/mat-tex.textures.json ESTELLA_VERIFY_W=256 ESTELLA_VERIFY_H=256 ESTELLA_VERIFY_STEPS=2 ESTELLA_VERIFY_EXPECT=\"[{\\\"x\\\":0.5,\\\"y\\\":0.5,\\\"rgb\\\":[0,255,0],\\\"tol\\\":50}]\" electron scripts/headless-verify.mjs",
"verify:render:material:switch": "vite build && ESTELLA_VERIFY_SCENE=/scenes/mat-sw.esscene ESTELLA_VERIFY_MANIFEST=/scenes/mat-sw.textures.json ESTELLA_VERIFY_W=256 ESTELLA_VERIFY_H=256 ESTELLA_VERIFY_STEPS=2 ESTELLA_VERIFY_EXPECT=\"[{\\\"x\\\":0.25,\\\"y\\\":0.5,\\\"rgb\\\":[255,0,0],\\\"tol\\\":50},{\\\"x\\\":0.75,\\\"y\\\":0.5,\\\"rgb\\\":[0,255,0],\\\"tol\\\":50}]\" electron scripts/headless-verify.mjs",
diff --git a/desktop/public/scenes/ktx2-sprite.esscene b/desktop/public/scenes/ktx2-sprite.esscene
new file mode 100644
index 000000000..cbca423c2
--- /dev/null
+++ b/desktop/public/scenes/ktx2-sprite.esscene
@@ -0,0 +1,28 @@
+{
+ "version": "1.0",
+ "name": "KTX2 Sprite",
+ "entities": [
+ {
+ "id": 0,
+ "name": "Camera",
+ "parent": null,
+ "children": [],
+ "components": [
+ { "type": "Transform", "data": { "position": { "x": 0, "y": 0, "z": 10 } } },
+ { "type": "Camera", "data": { "projectionType": 1, "orthoSize": 300, "isActive": true, "priority": 0 } }
+ ],
+ "visible": true
+ },
+ {
+ "id": 1,
+ "name": "Quad",
+ "parent": null,
+ "children": [],
+ "components": [
+ { "type": "Transform", "data": { "position": { "x": 0, "y": 0, "z": 0 } } },
+ { "type": "Sprite", "data": { "size": { "x": 200, "y": 200 }, "color": { "r": 1, "g": 1, "b": 1, "a": 1 }, "texture": "@uuid:abcdef01-2345-4678-89ab-cdef01234567" } }
+ ],
+ "visible": true
+ }
+ ]
+}
diff --git a/desktop/public/scenes/ktx2-sprite.textures.json b/desktop/public/scenes/ktx2-sprite.textures.json
new file mode 100644
index 000000000..5d46d80d4
--- /dev/null
+++ b/desktop/public/scenes/ktx2-sprite.textures.json
@@ -0,0 +1,3 @@
+{
+ "abcdef01-2345-4678-89ab-cdef01234567": "/scenes/ktx2-test/green.ktx2"
+}
diff --git a/desktop/public/scenes/ktx2-test/green.ktx2 b/desktop/public/scenes/ktx2-test/green.ktx2
new file mode 100644
index 000000000..a4727d8ea
Binary files /dev/null and b/desktop/public/scenes/ktx2-test/green.ktx2 differ
diff --git a/sdk/src/asset/AssetPlugin.ts b/sdk/src/asset/AssetPlugin.ts
index 63b2a06b7..d157bf7fc 100644
--- a/sdk/src/asset/AssetPlugin.ts
+++ b/sdk/src/asset/AssetPlugin.ts
@@ -4,6 +4,7 @@ import type { App, Plugin } from '../app';
import { defineResource } from '../resource';
import { Assets as AssetsClass } from './Assets';
import { HttpBackend } from './Backend';
+import { transcoderFromModule, type BasisWasmModule } from './basisTranscoder';
import { initBuiltinAssetFields } from './AssetFieldRegistry';
import { AssetRefCounter } from './AssetRefCounter';
import { Audio, type AudioAPI } from '../audio/Audio';
@@ -38,6 +39,17 @@ export class AssetPlugin implements Plugin {
app.hasResource(SpriteAnimation) ? app.getResource(SpriteAnimation) : null,
});
+ // Lazily acquire the Basis transcoder for KTX2 textures the same way
+ // physics/spine acquire their modules — only when a compressed texture is
+ // actually loaded (RC6 Batch C). The closure defers to app.sideModules,
+ // which the realm sets before any asset load.
+ assets.getTextureLoader().setTranscoderProvider(async () => {
+ const host = app.sideModules;
+ if (!host) return null;
+ const mod = await host.acquire('basis');
+ return mod ? transcoderFromModule(mod as unknown as BasisWasmModule) : null;
+ });
+
// Install the ref counter so resolveSceneAssetPaths records who
// uses what, and wire it to world despawns so entries don't
// outlive their entities. Tools / debug UI read it via
diff --git a/sdk/src/asset/loaders/TextureLoader.ts b/sdk/src/asset/loaders/TextureLoader.ts
index 348347441..ee87c1ad3 100644
--- a/sdk/src/asset/loaders/TextureLoader.ts
+++ b/sdk/src/asset/loaders/TextureLoader.ts
@@ -28,12 +28,30 @@ export class TextureLoader implements AssetLoader<TextureResult> {
private module_: ESEngineModule;
/**
- * Basis transcoder for KTX2 assets, injected by the basis plugin (Batch C3).
- * Null until registered — KTX2 loads then error with a clear message rather
- * than silently falling back.
+ * Basis transcoder for KTX2 assets. Either injected directly via
+ * {@link setTranscoder} (tests / embedded realms) or acquired lazily on the
+ * first KTX2 load via {@link setTranscoderProvider} — AssetPlugin wires the
+ * provider to `app.sideModules.acquire('basis')`, so the basis wasm is only
+ * fetched when a project actually uses compressed textures (self-gating, like
+ * physics / spine).
*/
private transcoder_: BasisTranscoder | null = null;
+ private transcoderProvider_: (() => Promise<BasisTranscoder | null>) | null = null;
+ private transcoderPending_: Promise<BasisTranscoder | null> | null = null;
setTranscoder(t: BasisTranscoder | null): void { this.transcoder_ = t; }
+ setTranscoderProvider(p: (() => Promise<BasisTranscoder | null>) | null): void {
+ this.transcoderProvider_ = p;
+ }
+
+ /** The transcoder, acquiring it once on demand. Concurrent KTX2 loads share
+ * the in-flight acquisition so the basis module loads exactly once. */
+ private async ensureTranscoder_(): Promise<BasisTranscoder | null> {
+ if (this.transcoder_) return this.transcoder_;
+ if (!this.transcoderProvider_) return null;
+ if (!this.transcoderPending_) this.transcoderPending_ = this.transcoderProvider_();
+ this.transcoder_ = await this.transcoderPending_;
+ return this.transcoder_;
+ }
private canvas_: HTMLCanvasElement | OffscreenCanvas | null = null;
private ctx_: CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D | null = null;
/**
@@ -115,10 +133,11 @@ export class TextureLoader implements AssetLoader<TextureResult> {
if (!isKtx2(bytes)) throw new Error(`TextureLoader: ${path} is not a KTX2 file`);
const gl = this.getWebGL2Context();
if (!gl) throw new Error('TextureLoader: KTX2 textures require a WebGL2 context');
- if (!this.transcoder_) {
- throw new Error('TextureLoader: no Basis transcoder registered (load the basis module before KTX2 assets)');
+ const transcoder = await this.ensureTranscoder_();
+ if (!transcoder) {
+ throw new Error('TextureLoader: no Basis transcoder available (basis side module missing — KTX2 assets need it)');
}
- const r = loadCompressedTexture(gl, this.module_, this.transcoder_, bytes, settings);
+ const r = loadCompressedTexture(gl, this.module_, transcoder, bytes, settings);
return { handle: r.handle, width: r.width, height: r.height };
}
diff --git a/sdk/src/runtimeLoader.ts b/sdk/src/runtimeLoader.ts
index 8c43b31dd..7e1d19e51 100644
--- a/sdk/src/runtimeLoader.ts
+++ b/sdk/src/runtimeLoader.ts
@@ -32,6 +32,8 @@ import { registerTilemapSource } from './tilemap/tilesetCache';
import { log } from './logger';
import { createTextureFromPixels, type RuntimeAssetProvider, type TextureParams } from './runtimeAssets';
import { loadSpineAssets, applySpineEntities } from './spine/loadSpineScene';
+import { loadCompressedTexture, type CompressedUploadOptions, type BasisTranscoder } from './asset/compressed';
+import { transcoderFromModule, type BasisWasmModule } from './asset/basisTranscoder';
// =============================================================================
// Public Interface
@@ -50,15 +52,25 @@ async function loadTextures(
sceneData: SceneData,
provider: RuntimeAssetProvider,
texturePaths: Set<string>,
+ transcoder: BasisTranscoder | null,
): Promise<Record<string, number>> {
const cache: Record<string, number> = {};
const texSettings = (sceneData as any).textureImporterSettings as Record<string, TextureParams> | undefined;
+ const gl = transcoder ? getWebGL2(module) : null;
for (const ref of texturePaths) {
try {
const params = texSettings?.[ref];
- const pixelData = await provider.loadPixels(ref);
- const handle = createTextureFromPixels(module, pixelData, true, params);
- cache[ref] = handle;
+ // KTX2 stays GPU-compressed in VRAM (RC6): decode to a device format
+ // through the SAME compressed.ts core the editor TextureLoader uses, so
+ // both paths agree by construction. Non-KTX2 keeps the RGBA upload.
+ if (transcoder && gl && provider.resolvePath(ref).toLowerCase().endsWith('.ktx2')) {
+ const bytes = await provider.readBinary(ref);
+ const r = loadCompressedTexture(gl, module, transcoder, new Uint8Array(bytes), compressedOpts(params));
+ cache[ref] = r.handle;
+ } else {
+ const pixelData = await provider.loadPixels(ref);
+ cache[ref] = createTextureFromPixels(module, pixelData, true, params);
+ }
} catch (e) {
log.warn('runtime', `Failed to load texture: ${ref}`, e);
cache[ref] = 0;
@@ -67,6 +79,37 @@ async function loadTextures(
return cache;
}
+/** WebGL2 context the emscripten module renders into (for JS-side compressed
+ * uploads via gl.compressedTexImage2D), or null. */
+function getWebGL2(module: ESEngineModule): WebGL2RenderingContext | null {
+ try {
+ const ctx = (module.GL as any)?.currentContext?.GLctx;
+ return (typeof WebGL2RenderingContext !== 'undefined' && ctx instanceof WebGL2RenderingContext) ? ctx : null;
+ } catch { return null; }
+}
+
+/** Map runtime TextureParams (filterMode/wrapMode) → compressed upload options. */
+function compressedOpts(params?: TextureParams): CompressedUploadOptions {
+ const filter = params?.filterMode === 'nearest' ? 'nearest' : 'linear';
+ const wrap = params?.wrapMode === 'repeat' ? 'repeat' : params?.wrapMode === 'mirror' ? 'mirror' : 'clamp';
+ return { filter, wrap };
+}
+
+/** Acquire the Basis transcoder iff the scene uses any KTX2 texture — self-gating
+ * off app.sideModules, the same way physics/spine acquire their modules. */
+async function acquireBasisIfNeeded(
+ app: App, provider: RuntimeAssetProvider, texturePaths: Set<string>,
+): Promise<BasisTranscoder | null> {
+ if (!app.sideModules) return null;
+ let needs = false;
+ for (const ref of texturePaths) {
+ if (provider.resolvePath(ref).toLowerCase().endsWith('.ktx2')) { needs = true; break; }
+ }
+ if (!needs) return null;
+ const mod = await app.sideModules.acquire('basis');
+ return mod ? transcoderFromModule(mod as unknown as BasisWasmModule) : null;
+}
+
function applyTextureMetadata(
sceneData: SceneData,
textureCache: Record<string, number>,
@@ -362,7 +405,9 @@ export async function loadRuntimeScene(options: LoadRuntimeSceneOptions): Promis
const discovered = discoverSceneAssets(sceneData);
- const textureCache = await loadTextures(module, sceneData, provider, getAssetPathsByType(discovered, 'texture'));
+ const texturePaths = getAssetPathsByType(discovered, 'texture');
+ const transcoder = await acquireBasisIfNeeded(app, provider, texturePaths);
+ const textureCache = await loadTextures(module, sceneData, provider, texturePaths, transcoder);
applyTextureMetadata(sceneData, textureCache);
const spineAssetInfo = await loadSpineAssets(module, provider, spineManager, discovered.spines);