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
feat(asset): the runtime reads an asset out of the pack its export put it in
esengine8893de92cfc4
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.mdindex f3f9f5035..70460c7d6 100644--- a/sdk/etc/index.api.md+++ b/sdk/etc/index.api.md@@ -134,6 +134,7 @@ compressedFormats: string[] | undefinedcontentHash: string | undefinedlabels: string[]metadata: { atlas?: string; atlasPage?: number; atlasFrame?: { x: number; y: number; width: number; height: number; }; atlasPageWidth?: number; atlasPageHeight?: number; } | undefined+pack: AssetPackRef | undefinedpath: stringsize: numberspineImport: SpineManifestContract | undefined@@ -4827,6 +4828,8 @@ findAsset: (pathOrAddress: string) => AddressableManifestAsset | nullgroup: (name: string) => AddressableManifestGroup | nullgroupNames: () => string[]groupsByMode: (mode: BundleMode) => string[]+packMembers: () => Map<string, Set<string>>+packOf: (path: string) => AssetPackRef | nullremoteAssetIdentity: (ref: string) => string | nullremoteAssetPath: (ref: string) => string | nullresolvePath: (ref: string) => stringdiff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.mdindex 5a76e6816..ef2b2fb4d 100644--- a/sdk/etc/index.native.api.md+++ b/sdk/etc/index.native.api.md@@ -134,6 +134,7 @@ compressedFormats: string[] | undefinedcontentHash: string | undefinedlabels: string[]metadata: { atlas?: string; atlasPage?: number; atlasFrame?: { x: number; y: number; width: number; height: number; }; atlasPageWidth?: number; atlasPageHeight?: number; } | undefined+pack: AssetPackRef | undefinedpath: stringsize: numberspineImport: SpineManifestContract | undefined@@ -4835,6 +4836,8 @@ findAsset: (pathOrAddress: string) => AddressableManifestAsset | nullgroup: (name: string) => AddressableManifestGroup | nullgroupNames: () => string[]groupsByMode: (mode: BundleMode) => string[]+packMembers: () => Map<string, Set<string>>+packOf: (path: string) => AssetPackRef | nullremoteAssetIdentity: (ref: string) => string | nullremoteAssetPath: (ref: string) => string | nullresolvePath: (ref: string) => stringdiff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.mdindex 9f4261638..fa78ad5b0 100644--- a/sdk/etc/index.node.api.md+++ b/sdk/etc/index.node.api.md@@ -129,6 +129,7 @@ compressedFormats: string[] | undefinedcontentHash: string | undefinedlabels: string[]metadata: { atlas?: string; atlasPage?: number; atlasFrame?: { x: number; y: number; width: number; height: number; }; atlasPageWidth?: number; atlasPageHeight?: number; } | undefined+pack: AssetPackRef | undefinedpath: stringsize: numberspineImport: SpineManifestContract | undefined@@ -4822,6 +4823,8 @@ findAsset: (pathOrAddress: string) => AddressableManifestAsset | nullgroup: (name: string) => AddressableManifestGroup | nullgroupNames: () => string[]groupsByMode: (mode: BundleMode) => string[]+packMembers: () => Map<string, Set<string>>+packOf: (path: string) => AssetPackRef | nullremoteAssetIdentity: (ref: string) => string | nullremoteAssetPath: (ref: string) => string | nullresolvePath: (ref: string) => stringdiff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.mdindex 1f72e67b8..b882a97b8 100644--- a/sdk/etc/minigame.api.md+++ b/sdk/etc/minigame.api.md@@ -129,6 +129,7 @@ compressedFormats: string[] | undefinedcontentHash: string | undefinedlabels: string[]metadata: { atlas?: string; atlasPage?: number; atlasFrame?: { x: number; y: number; width: number; height: number; }; atlasPageWidth?: number; atlasPageHeight?: number; } | undefined+pack: AssetPackRef | undefinedpath: stringsize: numberspineImport: SpineManifestContract | undefined@@ -4822,6 +4823,8 @@ findAsset: (pathOrAddress: string) => AddressableManifestAsset | nullgroup: (name: string) => AddressableManifestGroup | nullgroupNames: () => string[]groupsByMode: (mode: BundleMode) => string[]+packMembers: () => Map<string, Set<string>>+packOf: (path: string) => AssetPackRef | nullremoteAssetIdentity: (ref: string) => string | nullremoteAssetPath: (ref: string) => string | nullresolvePath: (ref: string) => stringdiff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.mdindex 8475c8d49..88966b157 100644--- a/sdk/etc/wechat.api.md+++ b/sdk/etc/wechat.api.md@@ -129,6 +129,7 @@ compressedFormats: string[] | undefinedcontentHash: string | undefinedlabels: string[]metadata: { atlas?: string; atlasPage?: number; atlasFrame?: { x: number; y: number; width: number; height: number; }; atlasPageWidth?: number; atlasPageHeight?: number; } | undefined+pack: AssetPackRef | undefinedpath: stringsize: numberspineImport: SpineManifestContract | undefined@@ -4829,6 +4830,8 @@ findAsset: (pathOrAddress: string) => AddressableManifestAsset | nullgroup: (name: string) => AddressableManifestGroup | nullgroupNames: () => string[]groupsByMode: (mode: BundleMode) => string[]+packMembers: () => Map<string, Set<string>>+packOf: (path: string) => AssetPackRef | nullremoteAssetIdentity: (ref: string) => string | nullremoteAssetPath: (ref: string) => string | nullresolvePath: (ref: string) => stringdiff --git a/sdk/src/asset/AddressableManifest.ts b/sdk/src/asset/AddressableManifest.tsindex adfff901f..64fc3265e 100644--- a/sdk/src/asset/AddressableManifest.ts+++ b/sdk/src/asset/AddressableManifest.ts@@ -39,6 +39,12 @@ export interface AddressableManifestAsset {* after a skeleton was re-pointed at another atlas.*/spineImport?: SpineManifestContract;+ /**+ * Present when the export packed this asset with others into one file, which+ * a network build fetches once instead of one request per asset: `path` then+ * names no file of its own, and its bytes are `size` at `offset` in `file`.+ */+ pack?: AssetPackRef;metadata?: {atlas?: string;atlasPage?: number;@@ -49,6 +55,14 @@ export interface AddressableManifestAsset {};}+/** Where a packed asset's bytes sit (see {@link AddressableManifestAsset.pack}). */+export interface AssetPackRef {+ /** The pack, as a path beside the manifest. */+ file: string;+ offset: number;+ size: number;+}+export interface AddressableManifestGroup {bundleMode: string;labels: string[];@@ -137,6 +151,33 @@ export class ManifestModel {return new ManifestModel(manifest);}+ private packs_: Map<string, AssetPackRef> | null = null;++ /** The pack holding the asset at build `path`, or null when it has a file of its own. */+ packOf(path: string): AssetPackRef | null {+ if (!this.packs_) {+ this.packs_ = new Map();+ for (const g of Object.values(this.manifest.groups)) {+ for (const a of Object.values(g.assets)) if (a.pack) this.packs_.set(a.path, a.pack);+ }+ }+ return this.packs_.get(path) ?? null;+ }++ /** The build paths each pack holds, by pack file. */+ packMembers(): Map<string, Set<string>> {+ const members = new Map<string, Set<string>>();+ for (const g of Object.values(this.manifest.groups)) {+ for (const a of Object.values(g.assets)) {+ if (!a.pack) continue;+ let set = members.get(a.pack.file);+ if (!set) members.set(a.pack.file, set = new Set());+ set.add(a.path);+ }+ }+ return members;+ }+static empty(): ManifestModel {return new ManifestModel({ version: '2.0', groups: {} });}diff --git a/sdk/src/asset/Assets.ts b/sdk/src/asset/Assets.tsindex d6b843817..e878bcf18 100644--- a/sdk/src/asset/Assets.ts+++ b/sdk/src/asset/Assets.ts@@ -1,6 +1,7 @@// SPDX-License-Identifier: Apache-2.0// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Teamimport type { Backend } from './Backend';+import { packedBackend } from './packedBackend';import { Catalog, type AtlasFrameInfo } from './Catalog';import { ManifestModel, normalizeBundleMode, type AddressableManifest, type AddressableAssetType } from './AddressableManifest';import { diffManifests, type UpdatePlan, type AssetChange } from './hotUpdate';@@ -90,7 +91,8 @@ export interface CheckForUpdateOptions {* failed) or `integrity` (bytes' content hash ≠ the manifest's). */export interface AssetDownloadFailure {path: string;- reason: 'fetch' | 'integrity';+ /** `packed`: the update's manifest packs the asset, and an update downloads assets one by one. */+ reason: 'fetch' | 'integrity' | 'packed';}/**@@ -456,7 +458,7 @@ export class Assets {private handleToPath_ = new Map<string, string>();private constructor(options: AssetsOptions) {- this.backend = options.backend;+ this.backend = options.backend && packedBackend(options.backend, () => this.manifestModel_);this.catalog = options.catalog ?? Catalog.empty();this.module_ = options.module;this.getAudio_ = options.getAudio ?? (() => null);@@ -1197,6 +1199,10 @@ export class Assets {): Promise<{ url: string; failure?: AssetDownloadFailure['reason']; cache?: 'stored' | 'failed' | 'unsupported' }> {const group = model.group(c.group);const remote = group != null && normalizeBundleMode(group.bundleMode) === 'remote';+ // An export with hot update configured does not pack; a manifest that does+ // was built for a package that is not updated, and is refused rather than+ // fetched as files that do not exist.+ if (model.packOf(c.path)) return { url: c.path, failure: 'packed' };const path = this.manifestAssetUrl_(c.path, remote, root);const url = this.backend.resolveUrl(path);try {diff --git a/sdk/src/asset/packedBackend.ts b/sdk/src/asset/packedBackend.tsnew file mode 100644index 000000000..f0e53f4a3--- /dev/null+++ b/sdk/src/asset/packedBackend.ts@@ -0,0 +1,86 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file packedBackend.ts — reading an asset out of the pack an export put it in.+ *+ * A network build with thousands of small assets spends its load on requests,+ * not bytes: a browser holds six connections to an origin, and Bistro's 1505+ * meshes queued behind them. The export packs local assets into a few files;+ * this reads one member by fetching its pack once and slicing it. Which pack+ * holds what is asked of the manifest in force at the time, not fixed at boot.+ */+import type { Backend } from './Backend';+import type { AssetPackRef, ManifestModel } from './AddressableManifest';++/**+ * `inner`, reading packed assets out of their packs. A pack's bytes are held+ * until every asset in it has been read once, then let go: a later read (a+ * device-loss rebuild) fetches the pack again.+ */+export function packedBackend(inner: Backend, manifest: () => ManifestModel | null): Backend {+ const fetched = new Map<string, Promise<ArrayBuffer>>();+ const unread = new Map<string, Set<string>>();+ let urlToPath: Map<string, string> | null = null;+ let indexedFor: ManifestModel | null = null;++ // Loaders ask by build path or by the url it resolves to; both must find the pack.+ const lookup = (asked: string): { path: string; pack: AssetPackRef } | null => {+ const model = manifest();+ if (!model) return null;+ if (indexedFor !== model) {+ indexedFor = model;+ urlToPath = new Map();+ unread.clear();+ for (const [file, paths] of model.packMembers()) {+ unread.set(file, new Set(paths));+ for (const p of paths) urlToPath.set(inner.resolveUrl(p), p);+ }+ }+ const direct = model.packOf(asked);+ if (direct) return { path: asked, pack: direct };+ const path = urlToPath!.get(asked);+ const pack = path ? model.packOf(path) : null;+ return path && pack ? { path, pack } : null;+ };++ const read = async (asked: string): Promise<ArrayBuffer | null> => {+ const hit = lookup(asked);+ if (!hit) return null;+ const { path, pack } = hit;+ let bytes = fetched.get(pack.file);+ if (!bytes) {+ bytes = inner.fetchBinary(pack.file);+ fetched.set(pack.file, bytes);+ // A failed fetch is not kept: the next read asks again.+ bytes.catch(() => fetched.delete(pack.file));+ }+ const buffer = await bytes;+ if (pack.offset + pack.size > buffer.byteLength) {+ throw new Error(`${path}: ${pack.file} holds ${buffer.byteLength} bytes, the manifest puts it at ${pack.offset}+${pack.size}`);+ }+ const left = unread.get(pack.file);+ left?.delete(path);+ if (left && left.size === 0) {+ fetched.delete(pack.file);+ unread.set(pack.file, new Set(manifest()?.packMembers().get(pack.file) ?? []));+ }+ return buffer.slice(pack.offset, pack.offset + pack.size);+ };++ return {+ async fetchBinary(path: string): Promise<ArrayBuffer> {+ return (await read(path)) ?? inner.fetchBinary(path);+ },+ async fetchText(path: string): Promise<string> {+ const bytes = await read(path);+ return bytes ? new TextDecoder().decode(bytes) : inner.fetchText(path);+ },+ resolveUrl: (path: string) => inner.resolveUrl(path),+ ...(inner.setBaseUrl ? {+ setBaseUrl: (url: string) => {+ inner.setBaseUrl!(url);+ indexedFor = null;+ },+ } : {}),+ };+}diff --git a/sdk/tests/assets.test.ts b/sdk/tests/assets.test.tsindex 752cddcc1..17d2f5392 100644--- a/sdk/tests/assets.test.ts+++ b/sdk/tests/assets.test.ts@@ -95,7 +95,8 @@ describe('Assets', () => {it('creates instance with catalog', () => {expect(assets.catalog).toBeDefined();- expect(assets.backend).toBe(backend);+ // Wrapped to read packed assets; everything else goes to the given backend.+ expect(assets.backend.resolveUrl('a/b.png')).toBe(backend.resolveUrl('a/b.png'));});it('creates instance with empty catalog', () => {diff --git a/sdk/tests/packed-backend.test.ts b/sdk/tests/packed-backend.test.tsnew file mode 100644index 000000000..4b468d46c--- /dev/null+++ b/sdk/tests/packed-backend.test.ts@@ -0,0 +1,63 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file A packed asset reads out of its pack, which is fetched once per round of reads.+ */+import { describe, it, expect } from 'vitest';+import { packedBackend } from '../src/asset/packedBackend';+import { ManifestModel, type AddressableManifest } from '../src/asset/AddressableManifest';+import type { Backend } from '../src/asset/Backend';++const PACK = new Uint8Array([...new TextEncoder().encode('{"a":1}'), 9, 8, 7]);++function inner(): Backend & { fetched: string[] } {+ const fetched: string[] = [];+ return {+ fetched,+ resolveUrl: (p: string) => `https://cdn.example/game/${p}`,+ async fetchBinary(p: string) {+ fetched.push(p);+ if (p === 'packs/p1.pack') return PACK.slice().buffer;+ return new Uint8Array([42]).buffer;+ },+ async fetchText(p: string) { fetched.push(p); return 'loose'; },+ };+}++function model(withPack = true): ManifestModel {+ const m: AddressableManifest = { version: '2.0', groups: { main: { bundleMode: 'local', labels: [], assets: {+ a: { path: 'assets/a.esmaterial', type: 'material', size: 7, labels: [], ...(withPack ? { pack: { file: 'packs/p1.pack', offset: 0, size: 7 } } : {}) },+ b: { path: 'assets/b.esmesh', type: 'binary', size: 3, labels: [], ...(withPack ? { pack: { file: 'packs/p1.pack', offset: 7, size: 3 } } : {}) },+ c: { path: 'assets/c.png', type: 'texture', size: 1, labels: [] },+ } } } };+ return ManifestModel.fromJson(m);+}++describe('reading a packed asset', () => {+ it('slices it out of its pack, by path or by the url it resolves to', async () => {+ const net = inner();+ const backend = packedBackend(net, () => model());+ expect(await backend.fetchText('assets/a.esmaterial')).toBe('{"a":1}');+ expect([...new Uint8Array(await backend.fetchBinary('https://cdn.example/game/assets/b.esmesh'))]).toEqual([9, 8, 7]);+ expect([...new Uint8Array(await backend.fetchBinary('assets/c.png'))]).toEqual([42]);+ expect(net.fetched).toEqual(['packs/p1.pack', 'assets/c.png']);+ });++ it('lets go of a pack once every member was read, and fetches it again for a later read', async () => {+ const net = inner();+ const backend = packedBackend(net, () => model());+ await Promise.all([backend.fetchBinary('assets/a.esmaterial'), backend.fetchBinary('assets/b.esmesh')]);+ await backend.fetchBinary('assets/a.esmaterial');+ expect(net.fetched).toEqual(['packs/p1.pack', 'packs/p1.pack']);+ });++ it('asks the manifest in force: once a manifest stops packing an asset, its own file is read', async () => {+ const net = inner();+ let current = model();+ const backend = packedBackend(net, () => current);+ await backend.fetchBinary('assets/b.esmesh');+ current = model(false);+ await backend.fetchBinary('assets/b.esmesh');+ expect(net.fetched).toEqual(['packs/p1.pack', 'assets/b.esmesh']);+ });+});