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(assets): Assets.preload — explicit-ref prefetch for streaming

yhh6e1f9170affd
diff --git a/docs/astro/src/content/docs/guides/assets.mdx b/docs/astro/src/content/docs/guides/assets.mdx
index 14ddb2bf5..713141b55 100644
--- a/docs/astro/src/content/docs/guides/assets.mdx
+++ b/docs/astro/src/content/docs/guides/assets.mdx
@@ -84,6 +84,22 @@ const bundle = await assets.loadGroup('level2', (loaded, total) => {
This grouping is what maps onto [WeChat subpackages](/docs/guides/wechat/) for
on-demand download.
+When the set of assets you want to warm isn't a group or label — say, the next
+area's textures while the player is still in this one — `preload` takes an
+explicit ref list, infers each asset's type (manifest, then file extension),
+and loads through the same typed channels with bounded concurrency:
+
+```typescript
+const { failed } = await assets.preload(
+ ['textures/boss.png', 'audio/boss-theme.mp3', 'maps/arena.estilemap'],
+ (loaded, total) => console.log(`${loaded}/${total}`),
+);
+```
+
+It never rejects — refs that can't be typed or fail to load are reported in
+`failed`. The eventual real loads then hit warm caches (or revive resident
+textures) instead of the network.
+
## Cooking, compression & content addressing
At build time the **cook** walks the dependency graph from your entry scene(s),
diff --git a/docs/astro/src/content/docs/zh-cn/guides/assets.mdx b/docs/astro/src/content/docs/zh-cn/guides/assets.mdx
index 4b320f2d1..d4e074d7b 100644
--- a/docs/astro/src/content/docs/zh-cn/guides/assets.mdx
+++ b/docs/astro/src/content/docs/zh-cn/guides/assets.mdx
@@ -77,6 +77,20 @@ const bundle = await assets.loadGroup('level2', (loaded, total) => {
`loadByLabel(...)` 按 label 标签加载资源,而不是按文件夹分组。正是这种分组映射到
[微信分包](/docs/zh-cn/guides/wechat/),实现按需下载。
+当你想预热的资源集合不是一个组或标签时——比如玩家还在当前区域,就先加载下一区域的
+纹理——`preload` 接受显式的引用列表,自动推断每个资源的类型(清单优先,其次文件扩展名),
+经同一套按类型通道以受限并发加载:
+
+```typescript
+const { failed } = await assets.preload(
+ ['textures/boss.png', 'audio/boss-theme.mp3', 'maps/arena.estilemap'],
+ (loaded, total) => console.log(`${loaded}/${total}`),
+);
+```
+
+它永远不会 reject——无法确定类型或加载失败的引用会记录在 `failed` 里。之后真正的
+加载会命中已预热的缓存(或复活驻留纹理),而不是走网络。
+
## 烘焙、压缩与内容寻址
构建时,**烘焙**从入口场景出发遍历依赖图,**剔除一切触达不到的资源**,暂存可达文件,
@@ -88,18 +102,28 @@ const bundle = await assets.loadGroup('level2', (loaded, total) => {
## 生命周期与引用计数
-加载的 GPU 资源是**引用计数**的。当使用某资源的实体被销毁(despawn)时,它的引用被释放;
-一个按字节预算的 LRU 会在常驻显存超过预算时逐出最旧的未引用纹理。你一般不用手动管理——
-正常引用和销毁实体即可。
+加载的 GPU 资源是**引用计数**的。当使用某资源的实体被销毁(despawn)时,它的引用被释放——
+但释放的纹理不会立即销毁:它以**可逐出缓存条目**的形式留驻,同一纹理再次被加载(重进场景、
+流式加载重新进入某区域)时会被**原地复活**,而不是重新下载和解码。一个按字节预算的 LRU
+在常驻显存超过预算时逐出最旧的未引用纹理。你一般不用手动管理——正常引用和销毁实体即可。
-用 `setTextureBudget` 限制常驻纹理内存——常驻显存越过它后,LRU 会逐出最旧的未引用纹理:
+预算默认 **64 MB**(`RuntimeConfig.textureCacheBudget`,也可在构建配置里用
+`textureCacheBudget` 设置)。用 `setTextureBudget` 按你的游戏调大小,用
+`getResourceStats` 观测驻留情况:
```typescript
-import { setTextureBudget } from 'esengine';
+import { setTextureBudget, getResourceStats } from 'esengine';
setTextureBudget(256 * 1024 * 1024); // 256 MB texture budget
+
+const stats = getResourceStats();
+// stats.textureBytes — 常驻纹理字节数(持有 + 可逐出)
+// stats.textureBudget — 当前预算
+// stats.textureEvictableCount — 等待复活或逐出的热缓存条目数
```
+把预算设为 `0` 会关闭热缓存——每个纹理在最后一个引用释放的瞬间就被销毁。
+
## 最佳实践
- **代码里按路径引用,让编辑器写 `@uuid:`**——绝不手写 UUID 引用。
diff --git a/sdk/src/asset/Assets.ts b/sdk/src/asset/Assets.ts
index d2c6f57de..d45e0c891 100644
--- a/sdk/src/asset/Assets.ts
+++ b/sdk/src/asset/Assets.ts
@@ -479,6 +479,91 @@ export class Assets {
}
}
+ /**
+ * Preload an explicit list of refs (`@uuid:` or paths) through the typed
+ * loaders, warming every cache with bounded concurrency and progress.
+ * This is the streaming prefetch primitive: point it at the next area's
+ * assets while gameplay continues, and the eventual real loads hit warm
+ * caches (or revive resident textures) instead of the network.
+ *
+ * Asset types come from the catalog / manifest when known, falling back
+ * to file-extension matching against the registered loaders. Refs whose
+ * type can't be determined — and refs that fail to load — are reported
+ * in `failed`; preload itself never rejects.
+ */
+ async preload(
+ refs: ReadonlyArray<string>,
+ onProgress?: (loaded: number, total: number) => void,
+ options?: { readonly maxConcurrent?: number },
+ ): Promise<{ failed: MissingAsset[] }> {
+ const failed: MissingAsset[] = [];
+ const tasks: Array<() => Promise<void>> = [];
+
+ for (const ref of refs) {
+ const path = this.resolveLoadPath_(ref);
+ const type = this.inferAssetType_(path);
+ if (!type) {
+ log.warn('asset', `preload: cannot determine asset type for ${ref}`);
+ failed.push({ ref, reason: 'unresolved' });
+ continue;
+ }
+ const load = this.typedLoadFor_(path, type);
+ if (!load) {
+ log.warn('asset', `preload: no loader for type '${type}' (${ref})`);
+ failed.push({ ref, type, reason: 'unresolved' });
+ continue;
+ }
+ tasks.push(() =>
+ load().then(() => {}).catch(e => {
+ log.warn('asset', `preload: failed to load ${ref}`, e);
+ failed.push({
+ ref, type, reason: 'load-failed',
+ error: e instanceof Error ? e.message : String(e),
+ });
+ }),
+ );
+ }
+
+ let loadedCount = 0;
+ const totalCount = tasks.length;
+ onProgress?.(0, totalCount);
+ const maxConcurrent = Math.max(1, options?.maxConcurrent ?? DEFAULT_PRELOAD_CONCURRENCY);
+ await runWithConcurrency(tasks, maxConcurrent, () => {
+ onProgress?.(++loadedCount, totalCount);
+ });
+ return { failed };
+ }
+
+ /** Asset type for a resolved path: catalog entry → manifest entry →
+ * extension match against the registered loaders → null. */
+ private inferAssetType_(path: string): string | null {
+ const catalogType = this.catalog.getEntry(path)?.type;
+ if (catalogType) return catalogType;
+ const manifestType = this.manifestModel_?.assetByPath(path)?.type;
+ if (manifestType) return manifestType;
+ const dot = path.lastIndexOf('.');
+ if (dot < 0) return null;
+ const ext = path.slice(dot).toLowerCase();
+ for (const loader of this.loaders_.values()) {
+ if (loader.extensions.includes(ext)) return loader.type;
+ }
+ return null;
+ }
+
+ /** Thunk that loads `path` through its type's canonical channel, or null
+ * when no loader handles the type. Textures/spine have dedicated entry
+ * points (refcount / two-file pairing); everything else is loadTyped. */
+ private typedLoadFor_(path: string, type: string): (() => Promise<unknown>) | null {
+ switch (type) {
+ case 'texture': return () => this.loadTexture(path);
+ case 'spine': return () => this.loadSpine(path);
+ case 'font':
+ case 'bitmap-font': return () => this.loadFont(path);
+ default:
+ return this.loaders_.has(type) ? () => this.loadTyped(type, path) : null;
+ }
+ }
+
// =========================================================================
// Raw Data (escape hatch)
// =========================================================================
diff --git a/sdk/tests/assets-preload.test.ts b/sdk/tests/assets-preload.test.ts
new file mode 100644
index 000000000..fe2500dcf
--- /dev/null
+++ b/sdk/tests/assets-preload.test.ts
@@ -0,0 +1,138 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file assets-preload.test.ts
+ * @brief Assets.preload contract: explicit ref lists warm the typed caches
+ * with progress, types resolve via catalog → extension fallback, and
+ * undeterminable/failing refs land in `failed` without rejecting.
+ */
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { Assets } from '../src/asset/Assets';
+import { Catalog, type CatalogData } from '../src/asset/Catalog';
+import type { Backend } from '../src/asset/Backend';
+import type { AssetLoader } from '../src/asset/AssetLoader';
+
+vi.mock('../src/resourceManager', () => ({
+ requireResourceManager: () => ({
+ createTexture: vi.fn(() => 42),
+ registerExternalTexture: vi.fn(() => 42),
+ releaseTexture: vi.fn(),
+ getTextureGLId: vi.fn(() => 1),
+ registerTextureWithPath: vi.fn(),
+ acquireTextureByPath: vi.fn(() => 0),
+ invalidateTexturePath: vi.fn(() => false),
+ getTextureDimensions: vi.fn(() => ({ width: 64, height: 64 })),
+ }),
+ getResourceManager: () => null,
+ evictTextureDimensions: vi.fn(),
+}));
+
+vi.mock('../src/platform', () => ({
+ platformCreateCanvas: () => ({
+ width: 256, height: 256,
+ getContext: () => ({
+ clearRect: vi.fn(),
+ drawImage: vi.fn(),
+ getImageData: () => ({ data: { buffer: new ArrayBuffer(256 * 256 * 4) } }),
+ }),
+ }),
+ platformCreateImage: () => {
+ const img: { width?: number; height?: number; onload?: () => void } = {};
+ setTimeout(() => { img.width = 64; img.height = 64; img.onload?.(); }, 0);
+ return img;
+ },
+ platformFetch: vi.fn(),
+ platformReadFile: vi.fn(),
+ platformReadTextFile: vi.fn(),
+ platformFileExists: vi.fn(),
+}));
+
+const mockModule = {
+ _malloc: vi.fn(() => 0),
+ _free: vi.fn(),
+ HEAPU8: new Uint8Array(1024 * 1024),
+ GL: null,
+ FS: null,
+} as never;
+
+const catalogData: CatalogData = {
+ version: 1,
+ entries: {
+ 'sprites/hero.png': { type: 'texture' },
+ 'data/level.custom': { type: 'custom' },
+ },
+ addresses: {},
+ labels: {},
+};
+
+describe('Assets.preload', () => {
+ let assets: Assets;
+ let backend: Backend;
+ let customLoads: string[];
+
+ beforeEach(() => {
+ customLoads = [];
+ backend = {
+ fetchBinary: vi.fn(async () => new ArrayBuffer(8)),
+ fetchText: vi.fn(async () => 'payload'),
+ resolveUrl: (path: string) => `http://test/${path}`,
+ } as unknown as Backend;
+ assets = Assets.create({
+ backend,
+ catalog: Catalog.fromJson(catalogData),
+ module: mockModule,
+ });
+ const customLoader: AssetLoader<{ value: string }> = {
+ type: 'custom',
+ extensions: ['.custom'],
+ load: async (path) => {
+ customLoads.push(path);
+ return { value: path };
+ },
+ unload: vi.fn(),
+ };
+ assets.register(customLoader);
+ });
+
+ it('warms caches for catalog-typed and extension-inferred refs, with progress', async () => {
+ const ticks: Array<[number, number]> = [];
+ const { failed } = await assets.preload(
+ ['sprites/hero.png', 'data/level.custom', 'data/other.custom'],
+ (loaded, total) => ticks.push([loaded, total]),
+ );
+
+ expect(failed).toEqual([]);
+ // 'data/other.custom' has no catalog entry — its type came from the
+ // .custom extension of the registered loader.
+ expect(customLoads.sort()).toEqual(['data/level.custom', 'data/other.custom']);
+ expect(assets.getTexture('sprites/hero.png')).toBeDefined();
+ expect(ticks[0]).toEqual([0, 3]);
+ expect(ticks[ticks.length - 1]).toEqual([3, 3]);
+
+ // The eventual real load is a pure cache hit — the loader doesn't re-run.
+ await assets.load('custom', 'data/level.custom');
+ expect(customLoads.filter(p => p === 'data/level.custom')).toHaveLength(1);
+ });
+
+ it('reports refs whose type cannot be determined without rejecting', async () => {
+ const { failed } = await assets.preload(['mystery/blob.xyz']);
+ expect(failed).toEqual([
+ { ref: 'mystery/blob.xyz', reason: 'unresolved' },
+ ]);
+ });
+
+ it('reports load failures per ref and still completes the rest', async () => {
+ const failing: AssetLoader<never> = {
+ type: 'broken',
+ extensions: ['.broken'],
+ load: async () => { throw new Error('boom'); },
+ unload: vi.fn(),
+ };
+ assets.register(failing);
+
+ const { failed } = await assets.preload(['a.broken', 'data/level.custom']);
+ expect(customLoads).toEqual(['data/level.custom']);
+ expect(failed).toHaveLength(1);
+ expect(failed[0]).toMatchObject({ ref: 'a.broken', type: 'broken', reason: 'load-failed', error: 'boom' });
+ });
+});