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
docs(guides): add Hot Update guide with editor config screenshots
yhhe2508a13441d
diff --git a/docs/astro/astro.config.mjs b/docs/astro/astro.config.mjsindex 2305fcfb0..d521a7f73 100644--- a/docs/astro/astro.config.mjs+++ b/docs/astro/astro.config.mjs@@ -125,6 +125,7 @@ export default defineConfig({{ label: 'Saving & Loading', translations: { 'zh-CN': '存档与读档' }, slug: 'guides/save' },{ label: 'Localization', translations: { 'zh-CN': '本地化' }, slug: 'guides/localization' },{ label: 'Building & Exporting', translations: { 'zh-CN': '构建与导出' }, slug: 'guides/build-export' },+ { label: 'Hot Update', translations: { 'zh-CN': '热更新' }, slug: 'guides/hot-update' },{ label: 'WeChat MiniGame', translations: { 'zh-CN': '微信小游戏' }, slug: 'guides/wechat' },{ label: 'Networking', translations: { 'zh-CN': '联网' }, slug: 'guides/networking' },{ label: 'AI Agents (MCP)', translations: { 'zh-CN': 'AI 代理 (MCP)' }, slug: 'guides/mcp' },diff --git a/docs/astro/src/assets/guides/en/hot-update-build-cdn.png b/docs/astro/src/assets/guides/en/hot-update-build-cdn.pngnew file mode 100644index 000000000..f22d389b8Binary files /dev/null and b/docs/astro/src/assets/guides/en/hot-update-build-cdn.png differdiff --git a/docs/astro/src/assets/guides/en/hot-update-cdn-badge.png b/docs/astro/src/assets/guides/en/hot-update-cdn-badge.pngnew file mode 100644index 000000000..c98bb7bfdBinary files /dev/null and b/docs/astro/src/assets/guides/en/hot-update-cdn-badge.png differdiff --git a/docs/astro/src/assets/guides/en/hot-update-delivery-menu.png b/docs/astro/src/assets/guides/en/hot-update-delivery-menu.pngnew file mode 100644index 000000000..c81c811b3Binary files /dev/null and b/docs/astro/src/assets/guides/en/hot-update-delivery-menu.png differdiff --git a/docs/astro/src/assets/guides/zh/hot-update-build-cdn.png b/docs/astro/src/assets/guides/zh/hot-update-build-cdn.pngnew file mode 100644index 000000000..5d484e973Binary files /dev/null and b/docs/astro/src/assets/guides/zh/hot-update-build-cdn.png differdiff --git a/docs/astro/src/assets/guides/zh/hot-update-cdn-badge.png b/docs/astro/src/assets/guides/zh/hot-update-cdn-badge.pngnew file mode 100644index 000000000..c98bb7bfdBinary files /dev/null and b/docs/astro/src/assets/guides/zh/hot-update-cdn-badge.png differdiff --git a/docs/astro/src/assets/guides/zh/hot-update-delivery-menu.png b/docs/astro/src/assets/guides/zh/hot-update-delivery-menu.pngnew file mode 100644index 000000000..a25be558eBinary files /dev/null and b/docs/astro/src/assets/guides/zh/hot-update-delivery-menu.png differdiff --git a/docs/astro/src/content/docs/guides/hot-update.mdx b/docs/astro/src/content/docs/guides/hot-update.mdxnew file mode 100644index 000000000..da7df3d8e--- /dev/null+++ b/docs/astro/src/content/docs/guides/hot-update.mdx@@ -0,0 +1,342 @@+---+title: Hot Update+description: Ship a game, then change its art or data on a CDN and have running clients pick up the new bytes — no re-download of the package, no store re-submission. Content-addressed, atomic, integrity-checked, and transparent to game code.+---++import { Aside, Steps } from '@astrojs/starlight/components';++A **hot update** ships a game once, then swaps out its assets — a texture, a+sound, a prefab — from a **CDN**, so running clients pick up the new bytes without+re-downloading the package or resubmitting to a store. It's how a shipped mobile+or mini-game title changes content after review.++Estella's hot update is **content-addressed**, **atomic** (all-or-nothing, with a+rollback), **integrity-checked** (tampered bytes are rejected), and **transparent+to game code** (a built-in rebinder swaps the new asset into live sprites for you).+The same mechanism runs on Web, Desktop, WeChat MiniGame, and native.++<Aside type="tip">+ The runnable [`hot-update-demo`](https://github.com/esengine/estella/tree/master/examples/hot-update-demo)+ example shows the whole loop on a single sprite — with **no game code at all**.+</Aside>++## How it works++Every cooked asset ships as `<contentHash>.<ext>` — an **immutable, permanently+cacheable URL**. Change one byte and the hash changes, so the asset becomes a+*new* URL; the old one is simply never referenced again. Nothing is ever+overwritten, so a cache can never go stale.++A hot update is therefore just four steps:++<Steps>++1. **Fetch** the remote **manifest** (`asset-manifest.json`) from the CDN.+2. **Diff** it against the manifest the game is running, by content hash.+3. **Download** only the assets whose hash changed (and verify each one).+4. **Swap** the active manifest — refs now resolve to the new URLs.++</Steps>++Because assets are content-addressed, the diff is a pure per-asset hash+comparison and applying it can never corrupt a cached file. The whole flow is+platform-uniform: the same `asset-manifest.json` drives every target.++## Delivery groups++Which assets ship *inside the package* and which are served *from a CDN* is a+per-folder decision called the asset's **delivery group**. Every folder resolves+to one of three modes:++| Mode | Bundle | Badge | Ships… | Use for |+| --- | --- | --- | --- | --- |+| **Local** | eager | — | inside the package, loaded at boot | the game's core assets |+| **Subpackage** | lazy | `PKG` (purple) | inside the package, loaded on demand | large optional content, [WeChat subpackages](/docs/guides/wechat/) |+| **Remote** | remote | `CDN` (blue) | from a CDN, **hot-updatable** | anything you want to change after shipping |++Only **Remote** groups are hot-updated — they're the assets fetched from your CDN+against a per-environment root. Local and Subpackage assets are baked into the+build. (Subpackages are on-demand *within* the package; see+[Assets → Addressable groups](/docs/guides/assets/#addressable-groups-lazy-loading).)++### Mark a folder for CDN delivery++In the **Content Browser**, right-click any folder and pick **Delivery → Remote+(CDN / hot-update)**. That's the whole authoring step — the folder's every asset+(recursively) now ships from the CDN instead of the package.++++*Content Browser → right-click a folder → **Delivery** → **Local / Subpackage / Remote (CDN / hot-update)**. The choice is written to `.esengine/asset-groups.json`.*++A folder assigned to a Subpackage or Remote group carries a corner **badge** so+you can see the delivery layout at a glance — `CDN` (blue) for remote, `PKG`+(purple) for subpackage.++++*The `cdn` folder wears a blue **CDN** badge — its assets are delivered remotely and can be hot-updated.*++The delivery decision is **decoupled from the folder name** — any ordinary folder+can be a remote group. (The legacy convention where a `remote/<name>/` or+`subpackages/<name>/` folder name implied delivery still works as a zero-config+fallback when a project has no `asset-groups.json`.)++### Set the CDN root++Remote-group assets need a **root URL** to fetch from — your CDN. It's a **build+profile** setting, so `dev` and `prod` can point at different CDNs, and the+export bakes the active profile's root into the shipped game. Set it in the+**Build** dialog (**File → Build…**):++++*The **CDN root (hot-update)** field in the Build dialog writes the active profile's `remoteRoot` to `asset-groups.json`. Leave it empty to load remote assets same-origin (e.g. for local testing).*++### `.esengine/asset-groups.json`++Both settings above are stored in one authored file, the single source of truth+the cook **and** the editor's Play realm read through one resolver (so they can+never disagree about where an asset ships):++```json+{+ "version": "1.0",+ "groups": {+ "cdn": { "folder": "assets/cdn", "mode": "remote" }+ },+ "activeProfile": "dev",+ "profiles": {+ "dev": { "remoteRoot": "" },+ "prod": { "remoteRoot": "https://cdn.example.com/my-game" }+ }+}+```++| Field | Type | Description |+| --- | --- | --- |+| `version` | `string` | Config version (`"1.0"`). |+| `groups` | `Record<name, {folder, mode}>` | Folder → delivery assignments. |+| `groups.<name>.folder` | `string` | Project-relative folder; every asset under it (recursively) joins the group. The **longest** matching prefix wins when folders nest. |+| `groups.<name>.mode` | `'local' \| 'subpackage' \| 'remote'` | Delivery mode. |+| `activeProfile` | `string` | Which profile the build uses (key into `profiles`). |+| `profiles.<name>.remoteRoot` | `string` | CDN root that this profile's remote-group assets are served from. Empty ⇒ same-origin. |++## What the build ships++Every Web / Desktop export always writes an **`asset-manifest.json`** (the+addressable manifest) next to the game — that's what a client diffs against for a+hot update. When the active profile has a CDN root, the export also bakes a+`hotUpdate` block into `game.config.json`:++```json+{+ "hotUpdate": {+ "remoteRoot": "https://cdn.example.com/my-game",+ "persistUpdateKey": "esengine:hotupdate"+ }+}+```++The shipped runtime reads this and wires itself up automatically at boot:++- `remoteRoot` is applied, so remote-group `@uuid` refs resolve to the CDN.+- `persistUpdateKey` (defaults to `esengine:hotupdate` whenever a root is set)+ makes the runtime **restore any previously-applied update at boot** — a+ returning player starts on the already-updated content, even offline.+- The **built-in rebinder** is installed, so an applied update swaps into live+ sprites with no game code.++You publish an update by uploading the newly-cooked assets **and** the fresh+`asset-manifest.json` to your CDN. Because URLs are content-addressed, uploading+is purely additive — the old files stay valid for clients that haven't updated.++## Triggering an update at runtime++The runtime is auto-configured, but *something* has to ask "is there an update?".+That's a single call the game makes — at boot, behind a **Check for updates**+button, or on a timer.++### Quick start++```ts+import { defineSystem, Res, Schedule, Assets } from 'esengine';++async function pullUpdate(assets: Assets): Promise<void> {+ // 1. Fetch the CDN manifest and diff it against the running one (downloads nothing).+ const plan = await assets.checkForUpdate({+ manifestUrl: 'https://cdn.example.com/my-game/asset-manifest.json',+ remoteRoot: 'https://cdn.example.com/my-game',+ });+ if (!plan.hasUpdate) return;+ console.log(`Update available: ${plan.changedAssets.length} files, ${(plan.totalBytes / 1024) | 0} KB`);++ // 2. Download + verify every changed asset, then swap the manifest — atomically.+ const result = await assets.applyUpdate((loaded, total) => {+ console.log(`Downloading ${loaded}/${total}`);+ });+ if (result.ok) console.log(`Applied — ${result.updated} assets updated`);+ else console.warn('Update failed, rolled back:', result.failed);+}++// Run it once at startup (guarded so the async check fires a single time).+let checked = false;+const checkForUpdates = defineSystem([Res(Assets)], (assets) => {+ if (checked) return;+ checked = true;+ void pullUpdate(assets);+});+// app.addSystems(Schedule.Update, checkForUpdates)+```++`checkForUpdate` is the "is there an update, and how big?" query — it fetches the+candidate manifest and returns a [plan](#updateplan) but downloads no assets, so+you can show a prompt (`N files, K KB`) before committing. `applyUpdate` then does+the download and swap.++### Zero-code rebinding++When a scene references an asset by `@uuid` and that asset lives in a remote+group, `applyUpdate` does **everything** — it downloads the new bytes, swaps the+manifest, and the built-in rebinder replaces the old texture in every live+`Sprite` and `Mesh2D` on screen. The picture changes on its own; the scene author+writes nothing. (The `hot-update-demo` example's game code is literally empty.)++For anything the built-in rebinder doesn't cover — a texture you bound manually, a+sound, a custom system — subscribe to `onInvalidate` and rebind yourself:++```ts+const unsub = assets.onInvalidate((ref) => {+ // `ref` was just invalidated by an update — reload it and rebind wherever you use it.+ void assets.loadTexture(ref).then((tex) => { /* assign tex.handle */ });+});+```++### API reference++The hot-update surface lives on the `Assets` resource (`Res(Assets)`):++| Method | Returns | Description |+| --- | --- | --- |+| `checkForUpdate(options)` | `Promise<UpdatePlan>` | Fetch a candidate manifest, diff it against the active one, and stage it. Downloads no assets. |+| `applyUpdate(onProgress?)` | `Promise<ApplyUpdateResult>` | Apply the staged update **atomically**: download + verify every changed asset, then swap the manifest, rebind live handles, and persist. `onProgress(loaded, total)` reports download progress. |+| `restorePersistedUpdate(key)` | `boolean` | At boot, restore the manifest a prior `applyUpdate` persisted under `key`. The runtime calls this for you when `persistUpdateKey` is set. |+| `setRemoteRoot(url?)` | `void` | Point remote-group resolution at a CDN root (`undefined` clears it → same-origin). The runtime sets this from the build's `remoteRoot`. |+| `remoteRoot` | `string \| undefined` | The active CDN root (getter). |+| `onInvalidate(listener)` | `() => void` | Subscribe to per-ref invalidations (for custom rebinding). Returns an unsubscribe function. |+| `loadGroup(name, onProgress?)` | `Promise<AssetBundle>` | Load a whole group on demand (the DLC pattern — see below). |+| `releaseGroup(name)` | `void` | Release everything `loadGroup(name)` acquired. |++**`CheckForUpdateOptions`**++| Field | Type | Description |+| --- | --- | --- |+| `manifestUrl` | `string` | URL of the candidate (remote) manifest JSON. |+| `remoteRoot` | `string` *(optional)* | CDN root the candidate's remote-group assets are served from. Defaults to the current root. |++**`UpdatePlan`** (returned by `checkForUpdate`)++| Field | Type | Description |+| --- | --- | --- |+| `hasUpdate` | `boolean` | True iff any asset is new or content-changed. |+| `changedAssets` | `AssetChange[]` | New / content-changed assets to download. |+| `removedAssets` | `AssetChange[]` | Assets present before but gone now (informational; never downloaded). |+| `changedGroups` | `string[]` | Distinct groups owning ≥1 changed asset. |+| `totalBytes` | `number` | Sum of `changedAssets` sizes — the download estimate for a progress UI. |+| `fromRevision` / `toRevision` | `string \| null` | The old / new manifest revisions. |++**`ApplyUpdateResult`** (returned by `applyUpdate`)++| Field | Type | Description |+| --- | --- | --- |+| `ok` | `boolean` | True only when every changed asset downloaded + verified and the manifest was swapped. |+| `updated` | `number` | How many assets were applied (`0` on failure). |+| `failed` | `AssetDownloadFailure[]` | Why it rolled back — each `{ path, reason: 'fetch' \| 'integrity' }`. |++## On-demand groups (DLC)++Beyond hot updates, a remote group is also a **downloadable content** channel: a+game can pull a whole group when the player reaches the content it backs, and+release it when they leave.++```ts+// Player enters "world 2" — pull its remote group from the CDN.+const bundle = await assets.loadGroup('world2', (loaded, total) => {+ showProgress(loaded / total);+});+// ...later, player leaves:+assets.releaseGroup('world2');+```++`loadGroup` warms the cache through the same typed loaders as everything else, and+`releaseGroup` reference-counts the release — an asset another scene still holds+survives. See [Assets → Addressable groups](/docs/guides/assets/#addressable-groups-lazy-loading)+for the group model in full.++## Integrity, atomicity & rollback++`applyUpdate` is **two-phase and all-or-nothing**:++<Steps>++1. **Download + verify.** Every changed asset is fetched and its bytes are hashed+ and compared to the manifest's `contentHash`. A download that fails, or bytes+ that don't match (a corrupted or tampered CDN response), is recorded as a+ failure. The active manifest is **not touched** during this phase.+2. **Commit.** Only if *every* asset succeeded does the update commit — the+ manifest and root swap, live handles rebind, and the new manifest persists.++</Steps>++If phase 1 turns up any failure, **nothing** is applied: the old manifest stays+active (a clean rollback) and `applyUpdate` returns `{ ok: false, failed }`. A+half-applied update is impossible.++<Aside type="caution">+ A cooked web build enforces a **same-origin CSP** by default — fetching a+ manifest or assets from a different origin (a different host or port) is blocked+ unless your CDN sends the right CORS headers. Serve the manifest and the assets+ from an origin the game is allowed to reach.+</Aside>++## Persistence & offline++When `persistUpdateKey` is set (the export does this automatically), `applyUpdate`+saves the applied manifest to platform storage. At the next boot the runtime calls+`restorePersistedUpdate(key)` and the player starts **directly on the updated+content — even with no network**. On native and mini-game targets the verified+bytes are also written to a content-addressed **disk cache**, so updated assets+load offline without re-hitting the CDN.++## Platform support++| Target | Manifest + diff | CDN fetch | Persist | Disk cache |+| --- | --- | --- | --- | --- |+| **Web** | ✅ | ✅ (CORS/CSP apply) | `localStorage` | browser HTTP cache |+| **Desktop** | ✅ | ✅ | ✅ | ✅ (content-addressed) |+| **WeChat MiniGame** | ✅ | ✅ | ✅ | ✅ |+| **Native (iOS / Android)** | ✅ | ✅ | ✅ | ✅ |++The manifest diff is pure and platform-agnostic; only the fetch, storage, and+disk-cache primitives differ per platform, and the runtime picks the right one.++## Best practices++- **Put hot-updatable content in its own folder** and mark it Remote — keep the+ core game local so the package boots without a network.+- **Gate the check** behind a boot-time run-once guard or a "Check for updates"+ button; don't call `checkForUpdate` every frame.+- **Show the size.** `checkForUpdate` gives you `totalBytes` and the file count+ before you commit — prompt the player before a large download on mobile data.+- **Handle `ok: false`.** A failed update rolls back cleanly; retry later rather+ than assuming success.+- **Use profiles.** Point `dev` at a test bucket (or empty for same-origin) and+ `prod` at your real CDN, so a build ships the right root automatically.+- **Version by manifest URL.** A staged rollout / A-B channel is just a different+ `manifestUrl` — hand different clients different manifests off the same CDN.++## See also++- [Assets](/docs/guides/assets/) — references, the manifest, typed loaders, and the group model.+- [Building & Exporting](/docs/guides/build-export/) — where the CDN root and `asset-manifest.json` come from.+- [WeChat MiniGame](/docs/guides/wechat/) — how subpackages map to the delivery groups here.diff --git a/docs/astro/src/content/docs/zh-cn/guides/hot-update.mdx b/docs/astro/src/content/docs/zh-cn/guides/hot-update.mdxnew file mode 100644index 000000000..414e810ec--- /dev/null+++ b/docs/astro/src/content/docs/zh-cn/guides/hot-update.mdx@@ -0,0 +1,270 @@+---+title: 热更新+description: 游戏发布后,把美术或数据放到 CDN 上更新,运行中的客户端即可拉取新字节——无需重新下载安装包,无需重新过审。内容寻址、原子应用、完整性校验,且对游戏代码透明。+---++import { Aside, Steps } from '@astrojs/starlight/components';++**热更新**让游戏只发布一次,之后从 **CDN** 换掉它的资产——一张贴图、一段音效、一个预制体——运行中的客户端便能拉取新字节,无需重新下载安装包,也无需重新提交到商店。这正是已上架的手游或小游戏在过审后继续更新内容的方式。++Estella 的热更新是**内容寻址**、**原子**(要么全成、要么回滚)、**完整性校验**(被篡改的字节会被拒绝)且**对游戏代码透明**(内建重绑器会替你把新资产换进运行中的精灵)。同一套机制在 Web、桌面、微信小游戏与原生上一致运行。++<Aside type="tip">+ 可运行的 [`hot-update-demo`](https://github.com/esengine/estella/tree/master/examples/hot-update-demo)+ 示例在一张精灵上演示了完整闭环——**且不含一行游戏代码**。+</Aside>++## 工作原理++每个 cook 后的资产都以 `<contentHash>.<ext>` 的形式发布——这是一个**不可变、可永久缓存的 URL**。改动一个字节,哈希就变,资产便成为一个*新* URL;旧的 URL 从此不再被引用。任何文件都不会被覆盖,因此缓存永远不会失效。++于是一次热更新就是四步:++<Steps>++1. 从 CDN **拉取**远端**清单**(`asset-manifest.json`)。+2. 按内容哈希把它与游戏正在运行的清单**做 diff**。+3. 只**下载**哈希变化的那些资产(并逐一校验)。+4. **切换**活动清单——引用随即解析到新 URL。++</Steps>++因为资产是内容寻址的,diff 就是一次纯粹的逐资产哈希比较,应用它绝不会破坏已缓存的文件。整条链路平台无关:同一份 `asset-manifest.json` 驱动所有目标平台。++## 交付组++哪些资产打进*包内*、哪些从 *CDN* 提供,是一个按文件夹的决策,称为资产的**交付组**。每个文件夹都归结为三种模式之一:++| 模式 | Bundle | 徽标 | 交付方式 | 适用于 |+| --- | --- | --- | --- | --- |+| **本地** | eager | — | 打进包内,启动时加载 | 游戏的核心资产 |+| **分包** | lazy | `分包`(紫) | 打进包内,按需加载 | 大体量可选内容、[微信分包](/docs/zh-cn/guides/wechat/) |+| **远端** | remote | `CDN`(蓝) | 从 CDN 提供,**可热更新** | 任何你想在发布后改动的内容 |++只有**远端**组会被热更新——它们是按环境根地址从你的 CDN 拉取的资产。本地与分包资产都被烘进构建里。(分包是包*内*的按需加载,见 [资源 → 寻址组](/docs/zh-cn/guides/assets/#寻址组懒加载)。)++### 把文件夹标为 CDN 交付++在**内容浏览器**中右键任意文件夹,选择 **交付方式 → 远端(CDN / 热更)**。这就是全部的配置动作——该文件夹下的每个资产(递归)从此改由 CDN 交付,而不再打进包内。++++*内容浏览器 → 右键文件夹 → **交付方式** → **本地 / 分包 / 远端(CDN / 热更)**。选择会写入 `.esengine/asset-groups.json`。*++被指派到分包或远端组的文件夹会带一个角标**徽标**,让你一眼看清交付布局——`CDN`(蓝)表示远端,`分包`(紫)表示分包。++++*`cdn` 文件夹带着蓝色 **CDN** 徽标——它的资产以远端方式交付,可被热更新。*++交付决策**与文件夹名解耦**——任意普通文件夹都能成为远端组。(旧约定中以 `remote/<name>/` 或 `subpackages/<name>/` 文件夹名隐含交付方式的做法仍然有效,作为项目没有 `asset-groups.json` 时的零配置回退。)++### 设置 CDN 根地址++远端组资产需要一个**根 URL** 来拉取——你的 CDN。它是一个**构建 profile** 设置,因此 `dev` 与 `prod` 可以指向不同的 CDN,导出时会把活动 profile 的根地址烘进发布的游戏里。在**构建**对话框(**文件 → 构建…**)中设置:++++*构建对话框中的 **CDN 地址(热更)** 字段会把活动 profile 的 `remoteRoot` 写入 `asset-groups.json`。留空则远端资产从游戏同源加载(例如本地测试时)。*++### `.esengine/asset-groups.json`++以上两项设置都存在同一个授权文件里,它是 cook **与**编辑器 Play 域通过同一个 resolver 读取的单一事实来源(因此两者绝不会对资产的交付去向产生分歧):++```json+{+ "version": "1.0",+ "groups": {+ "cdn": { "folder": "assets/cdn", "mode": "remote" }+ },+ "activeProfile": "dev",+ "profiles": {+ "dev": { "remoteRoot": "" },+ "prod": { "remoteRoot": "https://cdn.example.com/my-game" }+ }+}+```++| 字段 | 类型 | 说明 |+| --- | --- | --- |+| `version` | `string` | 配置版本(`"1.0"`)。 |+| `groups` | `Record<name, {folder, mode}>` | 文件夹 → 交付方式的指派。 |+| `groups.<name>.folder` | `string` | 项目相对文件夹;其下(递归)每个资产都归入该组。文件夹嵌套时,**最长**匹配前缀胜出。 |+| `groups.<name>.mode` | `'local' \| 'subpackage' \| 'remote'` | 交付模式。 |+| `activeProfile` | `string` | 构建使用哪个 profile(`profiles` 的键)。 |+| `profiles.<name>.remoteRoot` | `string` | 该 profile 的远端组资产的 CDN 根地址。留空 ⇒ 同源。 |++## 构建产出了什么++每次 Web / 桌面导出都会在游戏旁写出一份 **`asset-manifest.json`**(可寻址清单)——那正是客户端做热更新 diff 的依据。当活动 profile 设有 CDN 根地址时,导出还会把一段 `hotUpdate` 烘进 `game.config.json`:++```json+{+ "hotUpdate": {+ "remoteRoot": "https://cdn.example.com/my-game",+ "persistUpdateKey": "esengine:hotupdate"+ }+}+```++发布的运行时会读取它,并在启动时自动接线:++- 应用 `remoteRoot`,于是远端组的 `@uuid` 引用解析到 CDN。+- `persistUpdateKey`(只要设了根地址就默认为 `esengine:hotupdate`)让运行时在**启动时恢复此前已应用的更新**——回访玩家直接从已更新的内容开始,即使离线。+- 安装**内建重绑器**,于是一次已应用的更新会自动换进运行中的精灵,无需游戏代码。++你发布一次更新的方式,是把新 cook 出的资产**连同**新的 `asset-manifest.json` 上传到 CDN。因为 URL 是内容寻址的,上传纯粹是增量的——旧文件对尚未更新的客户端依然有效。++## 在运行时触发更新++运行时已自动配置好,但总得有*什么*来发问「有没有更新?」。那是游戏发起的一次调用——在启动时、藏在**检查更新**按钮后,或用定时器。++### 快速上手++```ts+import { defineSystem, Res, Schedule, Assets } from 'esengine';++async function pullUpdate(assets: Assets): Promise<void> {+ // 1. 拉取 CDN 清单并与运行中的清单做 diff(不下载任何东西)。+ const plan = await assets.checkForUpdate({+ manifestUrl: 'https://cdn.example.com/my-game/asset-manifest.json',+ remoteRoot: 'https://cdn.example.com/my-game',+ });+ if (!plan.hasUpdate) return;+ console.log(`有可用更新:${plan.changedAssets.length} 个文件,${(plan.totalBytes / 1024) | 0} KB`);++ // 2. 下载并校验每个变更资产,然后切换清单——原子完成。+ const result = await assets.applyUpdate((loaded, total) => {+ console.log(`下载中 ${loaded}/${total}`);+ });+ if (result.ok) console.log(`已应用——更新了 ${result.updated} 个资产`);+ else console.warn('更新失败,已回滚:', result.failed);+}++// 在启动时运行一次(加锁,让这次异步检查只触发一次)。+let checked = false;+const checkForUpdates = defineSystem([Res(Assets)], (assets) => {+ if (checked) return;+ checked = true;+ void pullUpdate(assets);+});+// app.addSystems(Schedule.Update, checkForUpdates)+```++`checkForUpdate` 是「有没有更新、有多大?」的查询——它拉取候选清单并返回一份[计划](#updateplan),但不下载任何资产,因此你可以在提交前弹出提示(`N 个文件,K KB`)。`applyUpdate` 才真正下载并切换。++### 零代码重绑++当场景以 `@uuid` 引用某个资产、而该资产位于远端组时,`applyUpdate` 会**全部搞定**——它下载新字节、切换清单,内建重绑器随即把旧贴图换进屏幕上每一个运行中的 `Sprite` 与 `Mesh2D`。画面自行改变,场景作者什么都不用写。(`hot-update-demo` 示例的游戏代码字面上是空的。)++对于内建重绑器覆盖不到的东西——你手动绑定的贴图、一段音效、一个自定义系统——订阅 `onInvalidate` 自行重绑:++```ts+const unsub = assets.onInvalidate((ref) => {+ // `ref` 刚被一次更新失效——重新加载它,并在你用到它的地方重绑。+ void assets.loadTexture(ref).then((tex) => { /* 赋值 tex.handle */ });+});+```++### API 参考++热更新接口位于 `Assets` 资源上(`Res(Assets)`):++| 方法 | 返回 | 说明 |+| --- | --- | --- |+| `checkForUpdate(options)` | `Promise<UpdatePlan>` | 拉取候选清单,与活动清单 diff,并暂存。不下载任何资产。 |+| `applyUpdate(onProgress?)` | `Promise<ApplyUpdateResult>` | **原子地**应用暂存的更新:下载并校验每个变更资产,然后切换清单、重绑运行中的句柄、持久化。`onProgress(loaded, total)` 回报下载进度。 |+| `restorePersistedUpdate(key)` | `boolean` | 在启动时,恢复上一次 `applyUpdate` 以 `key` 持久化的清单。设了 `persistUpdateKey` 时运行时会替你调用。 |+| `setRemoteRoot(url?)` | `void` | 把远端组解析指向某个 CDN 根地址(`undefined` 清除 → 同源)。运行时会从构建的 `remoteRoot` 设置它。 |+| `remoteRoot` | `string \| undefined` | 当前 CDN 根地址(getter)。 |+| `onInvalidate(listener)` | `() => void` | 订阅逐引用的失效(用于自定义重绑)。返回一个取消订阅的函数。 |+| `loadGroup(name, onProgress?)` | `Promise<AssetBundle>` | 按需加载整个组(DLC 模式——见下文)。 |+| `releaseGroup(name)` | `void` | 释放 `loadGroup(name)` 获取的一切。 |++**`CheckForUpdateOptions`**++| 字段 | 类型 | 说明 |+| --- | --- | --- |+| `manifestUrl` | `string` | 候选(远端)清单 JSON 的 URL。 |+| `remoteRoot` | `string`(可选) | 候选清单的远端组资产从哪个 CDN 根地址提供。默认沿用当前根地址。 |++**`UpdatePlan`**(`checkForUpdate` 返回)++| 字段 | 类型 | 说明 |+| --- | --- | --- |+| `hasUpdate` | `boolean` | 当且仅当有任何资产新增或内容变化时为真。 |+| `changedAssets` | `AssetChange[]` | 需要下载的新增 / 内容变化资产。 |+| `removedAssets` | `AssetChange[]` | 此前存在、现已消失的资产(仅供参考;从不下载)。 |+| `changedGroups` | `string[]` | 拥有 ≥1 个变更资产的不同组。 |+| `totalBytes` | `number` | `changedAssets` 大小之和——进度 UI 的下载量估计。 |+| `fromRevision` / `toRevision` | `string \| null` | 旧 / 新清单修订号。 |++**`ApplyUpdateResult`**(`applyUpdate` 返回)++| 字段 | 类型 | 说明 |+| --- | --- | --- |+| `ok` | `boolean` | 仅当每个变更资产都下载 + 校验通过且清单已切换时为真。 |+| `updated` | `number` | 应用了多少个资产(失败时为 `0`)。 |+| `failed` | `AssetDownloadFailure[]` | 为何回滚——每项 `{ path, reason: 'fetch' \| 'integrity' }`。 |++## 按需组(DLC)++除了热更新,远端组也是一条**可下载内容**通道:游戏可以在玩家到达某内容支撑的区域时拉取整个组,离开时释放。++```ts+// 玩家进入「第二世界」——从 CDN 拉取它的远端组。+const bundle = await assets.loadGroup('world2', (loaded, total) => {+ showProgress(loaded / total);+});+// ……稍后玩家离开:+assets.releaseGroup('world2');+```++`loadGroup` 通过与其它一切相同的类型化加载器暖起缓存,`releaseGroup` 按引用计数释放——被另一个场景仍持有的资产会存活。完整的组模型见 [资源 → 寻址组](/docs/zh-cn/guides/assets/#寻址组懒加载)。++## 完整性、原子性与回滚++`applyUpdate` 是**两相、要么全成要么全不**的:++<Steps>++1. **下载 + 校验。** 每个变更资产都被拉取,其字节被哈希并与清单的 `contentHash` 比对。下载失败、或字节不匹配(被破坏或篡改的 CDN 响应),都记为一次失败。此阶段**不触碰**活动清单。+2. **提交。** 只有当*每个*资产都成功时,更新才提交——切换清单与根地址、重绑运行中的句柄、持久化新清单。++</Steps>++若第 1 相出现任何失败,则**什么都不应用**:旧清单保持活动(干净回滚),`applyUpdate` 返回 `{ ok: false, failed }`。半应用的更新不可能出现。++<Aside type="caution">+ cook 出的 Web 构建默认强制**同源 CSP**——从不同源(不同主机或端口)拉取清单或资产会被拦截,除非你的 CDN 送出正确的 CORS 头。请把清单与资产放在游戏被允许访问的源上。+</Aside>++## 持久化与离线++当设了 `persistUpdateKey` 时(导出会自动设置),`applyUpdate` 会把已应用的清单存入平台存储。下次启动时运行时调用 `restorePersistedUpdate(key)`,玩家便**直接从已更新的内容开始——哪怕没有网络**。在原生与小游戏目标上,校验过的字节还会写入一个内容寻址的**落盘缓存**,于是已更新的资产离线加载而无需再次访问 CDN。++## 平台支持++| 目标 | 清单 + diff | CDN 拉取 | 持久化 | 落盘缓存 |+| --- | --- | --- | --- | --- |+| **Web** | ✅ | ✅(受 CORS/CSP 约束) | `localStorage` | 浏览器 HTTP 缓存 |+| **桌面** | ✅ | ✅ | ✅ | ✅(内容寻址) |+| **微信小游戏** | ✅ | ✅ | ✅ | ✅ |+| **原生(iOS / Android)** | ✅ | ✅ | ✅ | ✅ |++清单 diff 是纯粹且平台无关的;只有拉取、存储与落盘缓存原语按平台不同,运行时会挑选正确的那一个。++## 最佳实践++- **把可热更的内容放进独立文件夹**并标为远端——核心游戏保持本地,让安装包无网也能启动。+- **给检查加锁**,藏在启动时的一次性开关或「检查更新」按钮后;不要每帧调用 `checkForUpdate`。+- **展示体积。** `checkForUpdate` 在你提交前就给出 `totalBytes` 与文件数——在移动数据网络下大下载前提示玩家。+- **处理 `ok: false`。** 失败的更新会干净回滚;稍后重试,而不是假定成功。+- **善用 profile。** 让 `dev` 指向测试桶(或留空走同源)、`prod` 指向真正的 CDN,这样构建就会自动发布正确的根地址。+- **用清单 URL 做版本。** 灰度发布 / A-B 通道无非是不同的 `manifestUrl`——给不同客户端发同一 CDN 上不同的清单。++## 参见++- [资源](/docs/zh-cn/guides/assets/)——引用、清单、类型化加载器与组模型。+- [构建与导出](/docs/zh-cn/guides/build-export/)——CDN 根地址与 `asset-manifest.json` 从哪里来。+- [微信小游戏](/docs/zh-cn/guides/wechat/)——分包如何映射到这里的交付组。