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
fix(native): a CDN texture loads on a native build, and from the cache when offline
esengine4fe8cd941a3f
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex fb0c3b203..efc8634c9 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -22,6 +22,7 @@ published separately; it ships inside the editor.### Fixed+- A native build loads a remote group's textures from the CDN — they never loaded before — and after a hot update, from its disk cache when offline.- A WeChat development build connects to the editor from WeChat DevTools (the domain check is turned off for that build only), and frame replays come back from a mini-game.- Hot update works on mini-games: the update is fetched from the CDN, verified, applied and cached, and after a restart without a network the game starts on it with its updated art.- A frame-rate cap now holds: `setTargetFrameRate(30)` on a 60 Hz display runs at 30, not 24.diff --git a/native/host/bindings/AssetBindings.cpp b/native/host/bindings/AssetBindings.cppindex 773b1bd14..1a909d863 100644--- a/native/host/bindings/AssetBindings.cpp+++ b/native/host/bindings/AssetBindings.cpp@@ -41,13 +41,21 @@ JSValue js_readAsset(JSContext* ctx, JSValueConst, int, JSValueConst* argv) {return JS_NewArrayBufferCopy(ctx, bytes.data(), bytes.size());}-// es_loadImagePixels(path) -> { width, height, pixels: ArrayBuffer(RGBA) } | null.-// Decodes a packaged image asset to top-first RGBA via stb_image.+// es_loadImagePixels(path | ArrayBuffer) -> { width, height, pixels: ArrayBuffer(RGBA) } | null.+// Decodes a packaged image asset — or bytes the script fetched or read from the+// cache, which is how a CDN image arrives — to top-first RGBA via stb_image.JSValue js_loadImagePixels(JSContext* ctx, JSValueConst, int, JSValueConst* argv) {- const char* path = JS_ToCString(ctx, argv[0]);- if (!path) return JS_NULL;- std::vector<u8> file = readAsset(host(), path);- JS_FreeCString(ctx, path);+ std::vector<u8> file;+ size_t size = 0;+ if (uint8_t* raw = JS_GetArrayBuffer(ctx, &size, argv[0])) {+ file.assign(raw, raw + size);+ } else {+ JS_FreeValue(ctx, JS_GetException(ctx)); // not an ArrayBuffer: a path+ const char* path = JS_ToCString(ctx, argv[0]);+ if (!path) return JS_NULL;+ file = readAsset(host(), path);+ JS_FreeCString(ctx, path);+ }if (file.empty()) return JS_NULL;int w = 0, h = 0, ch = 0;stbi_uc* px = stbi_load_from_memory(file.data(), (int)file.size(), &w, &h, &ch, 4);diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.mdindex b31cce202..8a107952c 100644--- a/sdk/etc/index.native.api.md+++ b/sdk/etc/index.native.api.md@@ -5290,7 +5290,7 @@ es_audioVoiceState: ((voiceId: number) => { playing: boolean; currentTime: numbees_devicePixelRatio: (() => number) | undefinedes_fetch: ((request: { url: string; method?: string; headers?: Record<string, string>; body?: string | ArrayBuffer; responseType?: string; }, callback: (result: { ok: boolean; status: number; statusText: string; headers: Record<string, string>; arrayBuffer?: ArrayBuffer; text?: string; error?: string; }) => void) => void) | undefinedes_getStorageItem: ((key: string) => string | null) | undefined-es_loadImagePixels: (path: string) => { width: number; height: number; pixels: ArrayBuffer; } | null+es_loadImagePixels: (pathOrBytes: string | ArrayBuffer) => { width: number; height: number; pixels: ArrayBuffer; } | nulles_pollGamepads: (() => { index: number; connected: boolean; buttons: number[]; axes: number[]; }[]) | undefinedes_rasterizeGlyph: ((request: PlatformGlyphRequest) => { pixels: ArrayBuffer; width: number; height: number; advance: number; bearingX: number; bearingY: number; } | null) | undefinedes_readAsset: (path: string) => ArrayBuffer | nulldiff --git a/sdk/src/platform/native/hostBridge.ts b/sdk/src/platform/native/hostBridge.tsindex bfc1d9973..f8fcaed18 100644--- a/sdk/src/platform/native/hostBridge.ts+++ b/sdk/src/platform/native/hostBridge.ts@@ -36,7 +36,8 @@ export interface NativeHostBindings {/** A packaged file's bytes, or null when it is not in the package. */es_readAsset(path: string): ArrayBuffer | null;/** Decode a packaged image to top-first RGBA, or null on failure. */- es_loadImagePixels(path: string): { width: number; height: number; pixels: ArrayBuffer } | null;+ /** A packaged path, or bytes already fetched (a CDN image, a cached one). */+ es_loadImagePixels(pathOrBytes: string | ArrayBuffer): { width: number; height: number; pixels: ArrayBuffer } | null;/** Rasterize one glyph through the OS font stack — what a 2D canvas does on* the web. Optional, all-or-nothing with the rest of {@link TEXT_BINDINGS}:* a host that has not bound its font stack draws no text. */@@ -189,15 +190,22 @@ export function createHostBridge(},fileExists: (path) => Promise.resolve(bindings.es_readAsset(path) != null),fetch: (url, options) => hostFetch(bindings, url, options),- loadImagePixels: (path) => {- const decoded = bindings.es_loadImagePixels(path);- return decoded- ? Promise.resolve({- width: decoded.width,- height: decoded.height,- pixels: new Uint8Array(decoded.pixels),- })- : Promise.reject(new Error(`image decode failed: ${path}`));+ loadImagePixels: async (path) => {+ // The host decodes packaged paths; a CDN image is bytes the script brings,+ // from the hot-update cache when it is there, else from the network.+ let source: string | ArrayBuffer = path;+ if (/^https?:\/\//i.test(path)) {+ const cached = bindings.es_readCacheFile ? bindings.es_readCacheFile(cacheEntryName(path)) : null;+ if (cached) source = cached;+ else {+ const got = await hostFetch(bindings, path, { responseType: 'arraybuffer' });+ if (!got.ok || !got.arrayBuffer) throw new Error(`image fetch failed: ${path} (${got.status})`);+ source = got.arrayBuffer;+ }+ }+ const decoded = bindings.es_loadImagePixels(source);+ if (!decoded) throw new Error(`image decode failed: ${path}`);+ return { width: decoded.width, height: decoded.height, pixels: new Uint8Array(decoded.pixels) };},...(bindings.es_rasterizeGlyph ? { rasterizeGlyph: (request) => hostGlyph(bindings, request) } : {}),...storage,diff --git a/sdk/tests/native-host-bridge.test.ts b/sdk/tests/native-host-bridge.test.tsindex 4aea13578..56df6dfc1 100644--- a/sdk/tests/native-host-bridge.test.ts+++ b/sdk/tests/native-host-bridge.test.ts@@ -8,6 +8,7 @@*/import { describe, it, expect, vi } from 'vitest';import { createHostBridge, assertHostEnvironment, assertNativeHost } from '../src/platform/native';+import { cacheEntryName } from '../src/platform/cacheEntryName';import { REGISTRY_BINDINGS, RESOURCE_BINDINGS, PLATFORM_BINDINGS } from '../src/ecs/bridge/nativeBindings';/** The globals a real host installs (console, timers, clock, decoder). */@@ -285,3 +286,42 @@ describe('assertNativeHost', () => {expect(() => assertNativeHost(scope)).toThrow(/TextDecoder/);});});++describe('a CDN image on a native build', () => {+ // The host decodes packaged paths only: a remote group's texture never loaded,+ // online or off, until the script brought the host the bytes.+ const decoded = { width: 1, height: 1, pixels: new ArrayBuffer(4) };+ const url = 'https://cdn.example/remote/art.png';++ it('is decoded from the hot-update cache when it is there', async () => {+ const cached = new Uint8Array([9]).buffer;+ const load = vi.fn(() => decoded);+ const fetch = vi.fn();+ const bridge = createHostBridge(hostScope({+ es_loadImagePixels: load, es_fetch: fetch,+ es_readCacheFile: (key: string) => (key === cacheEntryName(url) ? cached : null),+ es_writeCacheFile: () => true,+ }));+ await bridge.loadImagePixels(url);+ expect(load).toHaveBeenCalledWith(cached);+ expect(fetch).not.toHaveBeenCalled();+ });++ it('is fetched as bytes and decoded when it is not', async () => {+ const bytes = new Uint8Array([1, 2]).buffer;+ const load = vi.fn(() => decoded);+ const fetch = vi.fn((req: { responseType?: string }, done: (r: unknown) => void) =>+ done({ ok: true, status: 200, statusText: 'OK', headers: {}, arrayBuffer: bytes, responseType: req.responseType }));+ const bridge = createHostBridge(hostScope({ es_loadImagePixels: load, es_fetch: fetch, es_readCacheFile: () => null }));+ await bridge.loadImagePixels(url);+ expect(fetch.mock.calls[0][0]).toMatchObject({ url, responseType: 'arraybuffer' });+ expect(load).toHaveBeenCalledWith(bytes);+ });++ it('a packaged path still goes to the host as a path', async () => {+ const load = vi.fn(() => decoded);+ const bridge = createHostBridge(hostScope({ es_loadImagePixels: load }));+ await bridge.loadImagePixels('assets/hero.png');+ expect(load).toHaveBeenCalledWith('assets/hero.png');+ });+});diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjsindex fad94527b..3b08b04e9 100644--- a/tools/releaseNotes.mjs+++ b/tools/releaseNotes.mjs@@ -1080,4 +1080,6 @@ export const NOTED = {{ note: 'A WeChat development build connects to the editor from WeChat DevTools (the domain check is turned off for that build only), and frame replays come back from a mini-game.' },'fix(hot-update): a mini-game fetches its update from the CDN, and shows it offline':{ note: 'Hot update works on mini-games: the update is fetched from the CDN, verified, applied and cached, and after a restart without a network the game starts on it with its updated art.' },+ 'fix(native): a CDN texture loads on a native build, and from the cache when offline':+ { note: 'A native build loads a remote group\'s textures from the CDN — they never loaded before — and after a hot update, from its disk cache when offline.' },};