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(nav): stage cancellable surface replacements and explain pending routes
yhha5f05744498d
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 8abeec69b..7cb29fd7a 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -14,6 +14,10 @@ published separately; it ships inside the editor.## [Unreleased]+### Added++- **Navigation replacements commit only from the latest request.** Versioned surface-update handles reject cancelled and superseded results, retain destinations while the navigation driver waits, and resume after commit or cancellation. Route inspection explains pending updates; the courtyard workshop adds asset-backed terrain reload/cancel controls. Producers still own background computation and I/O cancellation.+### Fixed- **2D navigation doors close without the mesh bake delay.** Grid obstacle marking runs on the next navigation tick even when the previous obstacle update was less than 200 ms ago. Closing and reopening a passage immediately invalidates cached connectivity; polygon mesh baking keeps its existing throttle.diff --git a/desktop b/desktopindex a418f5931..6f19c1423 160000--- a/desktop+++ b/desktop@@ -1 +1 @@-Subproject commit a418f593164c2422aaa80433d75cea2535bc69eb+Subproject commit 6f19c14234226c13ed6b2e7ad5bf7146bb63c5afdiff --git a/docs/astro/src/content/docs/gameplay/ai/navigation.mdx b/docs/astro/src/content/docs/gameplay/ai/navigation.mdxindex a86b83135..614da8f1c 100644--- a/docs/astro/src/content/docs/gameplay/ai/navigation.mdx+++ b/docs/astro/src/content/docs/gameplay/ai/navigation.mdx@@ -53,6 +53,41 @@ cell it touches fits the body, and a diagonal needs both of its shared orthogona— so a smoothed route is exactly as legal as the staircase it replaced, and thesame shape of route a mesh gives.+### Replacing a surface after asynchronous work++`nav.beginSurfaceUpdate()` returns a versioned `NavSurfaceUpdate`. Build a+replacement separately, then call `update.commit(surface)`. Only the latest+pending request can commit; a superseded, cancelled or completed handle returns+`false`. `nav.setSurface(...)` and assigning `nav.surface` also cancel a pending+request. `update.cancel()` keeps the previous surface and resumes its routes.++While `nav.surfaceUpdatePending` is true, the navigation driver retains agent+destinations and stops its steering. Character gravity remains active. Resource+queries return no route, and `queryWorldPath` reports `unavailable / building`;+the editor's route inspector displays the pending update. Planning counters+include agents waiting for this replacement.++```typescript+import { Navigation, NavGrid, type NavGridOptions } from 'esengine/ai';++async function replaceTerrain(nav: Navigation, load: () => Promise<NavGridOptions>) {+ const update = nav.beginSurfaceUpdate();+ try {+ const data = await load();+ if (update.pending) update.commit(new NavGrid(data));+ } finally {+ update.cancel(); // Also releases a failed request; harmless after commit.+ }+}+```++Cancel on owner teardown as well. Cancellation revokes the right to commit; the+producer owns aborting its I/O or worker. This protocol schedules no background+worker and does not make synchronous mesh baking asynchronous. Do not mutate the+live surface while staging a replacement: cancellation cannot roll back those+mutations. The courtyard workshop provides terrain reload/cancel controls using+an actual JSON asset and releases its asset lease on every outcome.+### A mesh for a 3D sceneA 3D scene has geometry rather than a tile mask, so its surface is **baked** fromdiff --git a/docs/astro/src/content/docs/zh-cn/gameplay/ai/navigation.mdx b/docs/astro/src/content/docs/zh-cn/gameplay/ai/navigation.mdxindex b5528ca15..cee7e4ad5 100644--- a/docs/astro/src/content/docs/zh-cn/gameplay/ai/navigation.mdx+++ b/docs/astro/src/content/docs/zh-cn/gameplay/ai/navigation.mdx@@ -49,6 +49,36 @@ export const setupNav = defineSystem([Res(Nav)], (nav) => {两侧的正交格都通——所以拉直后的路线和它替换掉的那条阶梯一样合法,并且和网格给出的是同一种形状的路线。+### 异步工作完成后替换导航表面++`nav.beginSurfaceUpdate()` 返回带版本号的 `NavSurfaceUpdate`。单独构建替换表面后调用+`update.commit(surface)`;只有最新且仍待提交的请求能成功。过期、已取消或已完成的句柄+返回 `false`。`nav.setSurface(...)` 和赋值 `nav.surface` 也会取消待提交请求。+`update.cancel()` 保留旧表面并恢复原有路线。++`nav.surfaceUpdatePending` 为真时,导航驱动保留代理目标并停止自己的转向;角色重力仍生效。+资源查询暂不返回路线,`queryWorldPath` 报告 `unavailable / building`,编辑器路线诊断显示+导航正在更新。规划计数也包含等待替换表面的代理。++```typescript+import { Navigation, NavGrid, type NavGridOptions } from 'esengine/ai';++async function replaceTerrain(nav: Navigation, load: () => Promise<NavGridOptions>) {+ const update = nav.beginSurfaceUpdate();+ try {+ const data = await load();+ if (update.pending) update.commit(new NavGrid(data));+ } finally {+ update.cancel(); // 失败时释放请求;已提交后再取消不会改变结果。+ }+}+```++请求所属对象销毁时也应取消。取消撤销提交资格,底层 I/O 或 worker 由构建器负责停止。+这套协议不启动后台线程,也不会把同步 mesh 烘焙变成异步。准备替换结果时不要修改正在+使用的表面;取消无法回滚这些修改。庭院工坊使用实际 JSON 资产演示重载/取消,并在成功、+失败、过期或取消后释放对应的资产引用。+### 3D 场景的网格3D 场景有的是几何而不是瓦片掩码,所以它的 surface 是从**它本来就在碰撞的那些刚体**上diff --git a/docs/astro/src/data/apiStability.generated.json b/docs/astro/src/data/apiStability.generated.jsonindex 9a5d7d87c..cf95af42e 100644--- a/docs/astro/src/data/apiStability.generated.json+++ b/docs/astro/src/data/apiStability.generated.json@@ -3,10 +3,10 @@"counts": {"public": 115,"beta": 103,- "experimental": 2198,+ "experimental": 2199,"deprecated": 3},- "total": 2416,+ "total": 2417,"subsystems": [{"id": "mobile-controls",diff --git a/examples/navigation-workshop/README.md b/examples/navigation-workshop/README.mdindex f41eaa37d..0dce6084a 100644--- a/examples/navigation-workshop/README.md+++ b/examples/navigation-workshop/README.md@@ -10,10 +10,18 @@ art, an editable gate and storehouse, and eight authored couriers.occupied by a courier is refused. Existing destinations take a detour.- **C / Crowd:** switch between eight and 24 couriers, then dispatch them again.- **R / Reset:** reset deliveries while preserving the gate/building settings.+- **U / Reload terrain:** load `assets/navigation/courtyard.json` through the+ asset system and atomically replace the grid. Couriers keep their targets and+ wait while loading; live gate/storehouse obstacles are applied to the new grid.+- **Esc / Cancel reload:** retain the current grid and resume its routes. A late+ asset result cannot commit after cancellation or a newer reload request.The buttons support pointer/touch input; the keys are desktop shortcuts. Thestatus shows completed deliveries and plans waiting in the engine's fair queue.In the editor, select a courier during Play and use **Inspect current route**.+Pending terrain requests report **Navigation is updating**. Terrain data loads+asynchronously; this example does not move mesh baking to a worker. The request+owner releases the JSON lease even when its result is cancelled or superseded.`Gate` and `Warehouse` are scene-authored `NavObstacle` entities. Theirvisuals follow their authored `enabled` fields, including edits duringdiff --git a/examples/navigation-workshop/assets/navigation/courtyard.json b/examples/navigation-workshop/assets/navigation/courtyard.jsonnew file mode 100644index 000000000..3e296b020--- /dev/null+++ b/examples/navigation-workshop/assets/navigation/courtyard.json@@ -0,0 +1,310 @@+{+ "width": 23,+ "height": 13,+ "cellSize": 32,+ "origin": {+ "x": -352,+ "y": -192+ },+ "walkable": [+ 0,+ 0,+ 0,+ 0,+ 0,+ 0,+ 0,+ 0,+ 0,+ 0,+ 0,+ 0,+ 0,+ 0,+ 0,+ 0,+ 0,+ 0,+ 0,+ 0,+ 0,+ 0,+ 0,+ 0,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 0,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 0,+ 0,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 0,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 0,+ 0,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 0,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 0,+ 0,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 0,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 0,+ 0,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 0,+ 0,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 0,+ 0,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 0,+ 0,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 0,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 0,+ 0,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 0,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 0,+ 0,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 0,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 0,+ 0,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 0,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 0,+ 0,+ 0,+ 0,+ 0,+ 0,+ 0,+ 0,+ 0,+ 0,+ 0,+ 0,+ 0,+ 0,+ 0,+ 0,+ 0,+ 0,+ 0,+ 0,+ 0,+ 0,+ 0,+ 0+ ]+}diff --git a/examples/navigation-workshop/assets/navigation/courtyard.json.meta b/examples/navigation-workshop/assets/navigation/courtyard.json.metanew file mode 100644index 000000000..d05234b3f--- /dev/null+++ b/examples/navigation-workshop/assets/navigation/courtyard.json.meta@@ -0,0 +1,6 @@+{+ "uuid": "25e7e0fe-e665-4af2-ac71-777177b4c006",+ "version": "2.0",+ "type": "json",+ "importer": {}+}diff --git a/examples/navigation-workshop/src/main.ts b/examples/navigation-workshop/src/main.tsindex 7e2921efb..7fa890f72 100644--- a/examples/navigation-workshop/src/main.ts+++ b/examples/navigation-workshop/src/main.ts@@ -1,15 +1,46 @@import {addPlugin, defineSystem, Schedule, Res, GetWorld, Input, UIEvents, Playthrough,- Transform, Sprite, Text, Name, spawnUIEntity, createButton, UIPositionType, px, quaternionToAngle2D,+ Transform, Sprite, Text, Name, Assets, spawnUIEntity, createButton, UIPositionType, px, quaternionToAngle2D,type World, type Entity,} from 'esengine';-import { Nav, NavAgent, NavObstacle, NavGrid, setNavDestination } from 'esengine/ai';+import { Nav, NavAgent, NavObstacle, NavGrid, setNavDestination, type NavSurfaceUpdate, type NavGridOptions } from 'esengine/ai';+const cleanupReloads=new WeakMap<object,()=>void>();addPlugin({ name: 'navigation-workshop', build(app) {const facts = { gateClosed: false, warehousePlaced: false, couriers: 8, arrived: 0, waiting: 0,- completedPlans: 0, queuedPlans: 0, planMs: 0, leftOfGate: 8, rightOfGate: 0 };+ completedPlans: 0, queuedPlans: 0, planMs: 0, leftOfGate: 8, rightOfGate: 0,+ reloadPending:false, reloadVersion:0, reloadCommitted:0, reloadCancelled:0, reloadSettled:0, reloadFailed:0 };app.insertResource(Playthrough, { facts });let agents: Entity[] = [], status: Entity | null = null, notice = 'A delivery is on its way. Try closing the gate.';+ let terrainUpdate:NavSurfaceUpdate|null=null;+ cleanupReloads.set(app,()=>{terrainUpdate?.cancel();terrainUpdate=null;});+ const reloadTerrain=async()=>{+ const nav=app.getResource(Nav),update=nav.beginSurfaceUpdate();terrainUpdate=update;+ facts.reloadPending=true;facts.reloadVersion=update.version;+ notice='Terrain loading. Couriers keep their destinations and wait. Esc cancels.';+ let release:(()=>void)|undefined;+ try{+ const lease=await app.getResource(Assets).acquireTyped<{data:NavGridOptions}>('json','@uuid:25e7e0fe-e665-4af2-ac71-777177b4c006');+ release=()=>lease.release();+ if(!update.pending)return;+ const data=lease.value.data;+ if(data.width!==23||data.height!==13||data.cellSize!==32||data.origin?.x!==-352||data.origin?.y!==-192+ ||!Array.isArray(data.walkable)||data.walkable.length!==299||!data.walkable.every(v=>v===0||v===1))throw new Error('Invalid terrain layout');+ if(update.commit(new NavGrid(data))){facts.reloadCommitted=update.version;notice='Terrain reloaded. Existing destinations and obstacles are kept.';}+ }catch{+ if(update.pending){facts.reloadFailed=update.version;notice='Terrain could not load. The previous layout is kept.';}+ }finally{+ release?.();update.cancel();+ facts.reloadSettled=Math.max(facts.reloadSettled,update.version);+ if(terrainUpdate===update){terrainUpdate=null;facts.reloadPending=false;}+ }+ };+ const cancelTerrain=()=>{+ if(terrainUpdate?.cancel()){+ facts.reloadCancelled=terrainUpdate.version;terrainUpdate=null;facts.reloadPending=false;+ notice='Terrain reload cancelled. Couriers resume on the previous layout.';+ }+ };const start = (i: number) => ({ x: -288+(i%3)*32, y: -96+Math.floor(i/3)*32, z: 0 });const goal = (i: number) => ({ x: 64+(i%5)*64, y: -128+Math.floor(i/5)*64, z: 0 });const obstacle = (world: World, name: string, enabled: boolean) => {@@ -88,14 +119,15 @@ addPlugin({ name: 'navigation-workshop', build(app) {label('WorkshopSubtitle','Open the gate. Change the courtyard. Keep the delivery moving.',48,70,920,15);label('DispatchLabel','DISPATCH',172,116,150,12,{r:.48,g:.8,b:.79,a:1});label('DepotLabel','DELIVERY DEPOT',730,116,180,12,{r:.94,g:.79,b:.48,a:1});- status=label('WorkshopStatus','',144,582,736,13);- const buttons:[string,string,()=>void][]=[['GateButton','G / TOGGLE GATE',()=>gate(world)],['BuildButton','B / STOREHOUSE',()=>build(world)],['CrowdButton','C / 8 OR 24 COURIERS',()=>crowd(world)],['ResetButton','R / RESET DELIVERY',()=>{dispatch(world);notice='Delivery reset. Existing gate and storehouse settings are kept.';}]];+ status=label('WorkshopStatus','',144,578,736,13);+ const buttons:[string,string,()=>void][]=[['GateButton','G / TOGGLE GATE',()=>gate(world)],['BuildButton','B / STOREHOUSE',()=>build(world)],['CrowdButton','C / 8 OR 24 COURIERS',()=>crowd(world)],['ResetButton','R / RESET DELIVERY',()=>{dispatch(world);notice='Delivery reset. Existing gate and storehouse settings are kept.';}],+ ['ReloadButton','U / RELOAD TERRAIN',()=>void reloadTerrain()],['CancelReloadButton','ESC / CANCEL RELOAD',cancelTerrain]];buttons.forEach(([name,text,onClick],i)=>{- const button=createButton({world,events,parent:canvas,node:{position:UIPositionType.Absolute,insetLeft:px(120+i*200),insetTop:px(630),width:px(184),height:px(40)},+ const button=createButton({world,events,parent:canvas,node:{position:UIPositionType.Absolute,insetLeft:px(120+(i%3)*264),insetTop:px(622+Math.floor(i/3)*42),width:px(248),height:px(36)},text:{content:text,fontSize:12,color:{r:.94,g:.88,b:.7,a:1}},background:{color:{r:.14,g:.2,b:.25,a:1}},onClick});world.insert(button.entity,Name,{value:name});});- label('WorkshopHelp','Gate and storehouse are editable NavObstacle entities. Select a courier during Play to inspect its route.',120,682,800,11);+ label('WorkshopHelp','Gate and storehouse are editable NavObstacle entities. Select a courier during Play to inspect its route.',48,94,920,10);},{name:'WorkshopSetup'}));app.addSystem(defineSystem([Res(Nav),Res(Input),GetWorld()],(nav,input,world)=>{facts.gateClosed=syncObstacle(world,'Gate');facts.warehousePlaced=syncObstacle(world,'Warehouse');@@ -103,6 +135,8 @@ addPlugin({ name: 'navigation-workshop', build(app) {if(input.isKeyPressed('KeyB'))build(world);if(input.isKeyPressed('KeyC'))crowd(world);if(input.isKeyPressed('KeyR')){dispatch(world);notice='Delivery reset. Existing gate and storehouse settings are kept.';}+ if(input.isKeyPressed('KeyU'))void reloadTerrain();+ if(input.isKeyPressed('Escape'))cancelTerrain();facts.arrived=0;facts.waiting=0;facts.leftOfGate=0;facts.rightOfGate=0;for(const e of agents){const agent=world.get(e,NavAgent),p=world.get(e,Transform).position;if(agent.arrived)facts.arrived++;else facts.waiting++;@@ -112,4 +146,4 @@ addPlugin({ name: 'navigation-workshop', build(app) {if(status!==null){const content=`${facts.couriers} COURIERS / ${facts.arrived} DELIVERED / ${facts.queuedPlans} PLANS QUEUED\n${notice}`;if(world.get(status,Text).content!==content)world.insert(status,Text,{...world.get(status,Text),content});}},{name:'WorkshopControls',runAfter:['NavAgentSystem']}));-}});+},cleanup(app){if(app){cleanupReloads.get(app)?.();cleanupReloads.delete(app);}}});diff --git a/sdk/etc/ai.api.md b/sdk/etc/ai.api.mdindex 78a32c0fb..1e4dfd714 100644--- a/sdk/etc/ai.api.md+++ b/sdk/etc/ai.api.md@@ -1,7 +1,7 @@# API surface — esengine/ai<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 0 public · 0 beta · 160 experimental · 0 deprecated+Symbols: 0 public · 0 beta · 161 experimental · 0 deprecated## AiAction — type @experimental```@@ -542,7 +542,7 @@ halfExtents: Vec3## NavPathResult — interface @experimental```path: Vec3[] | null-reason: "none" | "no-surface" | "start-unavailable" | "target-unavailable" | "disconnected" | "insufficient-clearance" | "radius-mismatch" | "diagnostics-unavailable"+reason: "none" | "no-surface" | "building" | "start-unavailable" | "target-unavailable" | "disconnected" | "insufficient-clearance" | "radius-mismatch" | "diagnostics-unavailable"status: "unknown" | "unavailable" | "complete" | "partial"```@@ -582,6 +582,15 @@ face: (corners: readonly Vec3[]) => voidlink: (a: Vec3, b: Vec3) => void```+## NavSurfaceUpdate — interface @experimental+```+cancel: () => boolean+cancelled: boolean+commit: (surface: NavSurface | null) => boolean+pending: boolean+version: number+```+## NavVolume — const @experimental```ComponentDef<NavVolumeData>@@ -601,6 +610,7 @@ stepHeight: number## Navigation — class @experimental```+beginSurfaceUpdate: () => NavSurfaceUpdatefindWorldPath: (from: NavPoint, to: NavPoint, opts?: NavQueryOptions) => Vec3[] | nullhasSurface: () => booleaninvalidatePaths: () => void@@ -611,6 +621,7 @@ planningStats: { completed: number; pending: number; elapsedMs: number; }queryWorldPath: (from: NavPoint, to: NavPoint, opts?: NavQueryOptions) => NavPathResultsetSurface: (surface: NavSurface | null) => voidsurface: NavSurface | null+surfaceUpdatePending: booleanstatic new (): Navigationstatic prototype: Navigation```diff --git a/sdk/src/ai/nav/NavPlugin.ts b/sdk/src/ai/nav/NavPlugin.tsindex 266a57eb7..cc7e1cfa2 100644--- a/sdk/src/ai/nav/NavPlugin.ts+++ b/sdk/src/ai/nav/NavPlugin.ts@@ -256,21 +256,22 @@ export function stepNavigation(// A flat scene is walked in x/y; ground with height in it, in x/z.const flat = Math.abs(nav.surface?.up.z ?? 0) > Math.abs(nav.surface?.up.y ?? 1);const entities = world.getEntitiesWithComponents([NavAgent, Transform]);+ if (nav.surfaceUpdatePending) {+ nav.planningStats.completed = 0; nav.planningStats.elapsedMs = 0; nav.planningStats.pending = 0;+ for (const entity of entities) {+ if (!world.get(entity, NavAgent).hasTarget) continue;+ nav.planningStats.pending++;+ clearNavigationVelocity(world, entity, runtimes);+ }+ return;+ }const blocked = planNavigation(world, nav, dt, runtimes, entities);// Agents awaiting a valid route must not retain old steering velocity. Keep// vertical velocity: gravity and the character solver still own that axis.for (const entity of entities) {const active = world.get(entity, NavAgent).hasTarget;if (!blocked.has(entity) && (!active || runtimes.get(entity)?.reachable)) continue;- const rt = runtimes.get(entity);- if (rt) { rt.velocityA = 0; rt.velocityB = 0; }- if (world.has(entity, CharacterController3D)) {- const character = world.get(entity, CharacterController3D);- if (character.enabled !== false) {- character.velocity.x = 0; character.velocity.z = 0;- world.set(entity, CharacterController3D, character);- }- }+ clearNavigationVelocity(world, entity, runtimes);}const crowd = gatherCrowd(world, entities, runtimes, flat);@@ -312,6 +313,17 @@ export function stepNavigation(}}+/** Stop only navigation's steering axes; gravity and inactive bodies keep theirs. */+function clearNavigationVelocity(world: NavWorldView, entity: Entity, runtimes: Map<Entity, AgentRuntime>): void {+ const rt = runtimes.get(entity);+ if (rt) { rt.velocityA = 0; rt.velocityB = 0; }+ if (!world.has(entity, CharacterController3D)) return;+ const character = world.get(entity, CharacterController3D);+ if (character.enabled === false) return;+ character.velocity.x = 0; character.velocity.z = 0;+ world.set(entity, CharacterController3D, character);+}+/*** Everyone on the surface who is a BODY, in the two axes they steer on. An agent* routed as a point declares no body and neither gives way nor is given way to.diff --git a/sdk/src/ai/nav/NavSurface.ts b/sdk/src/ai/nav/NavSurface.tsindex 30d381d70..e3de744cb 100644--- a/sdk/src/ai/nav/NavSurface.ts+++ b/sdk/src/ai/nav/NavSurface.ts@@ -39,7 +39,7 @@ export interface NavQueryOptions {export interface NavPathResult {path: Vec3[] | null;status: 'complete' | 'partial' | 'unavailable' | 'unknown';- reason: 'none' | 'no-surface' | 'start-unavailable' | 'target-unavailable'+ reason: 'none' | 'no-surface' | 'building' | 'start-unavailable' | 'target-unavailable'| 'disconnected' | 'insufficient-clearance' | 'radius-mismatch' | 'diagnostics-unavailable';}diff --git a/sdk/src/ai/nav/Navigation.ts b/sdk/src/ai/nav/Navigation.tsindex a09ccefe3..c07ef19f1 100644--- a/sdk/src/ai/nav/Navigation.ts+++ b/sdk/src/ai/nav/Navigation.ts@@ -14,22 +14,75 @@ import { defineResource } from '../../ecs/resource';import type { Vec3 } from '../../types';import type { NavPoint, NavQueryOptions, NavSurface, NavPathResult } from './NavSurface';+/** Ownership of one replacement surface; build it separately from the live one. */+export interface NavSurfaceUpdate {+ readonly version: number;+ readonly pending: boolean;+ readonly cancelled: boolean;+ /** Install only if this is still the current request. */+ commit(surface: NavSurface | null): boolean;+ /** Retain the previous surface and reject future commits from this request.+ * The producer owns stopping its underlying work. */+ cancel(): boolean;+}+export class Navigation {+ private surface_: NavSurface | null = null;+ private surfaceUpdate_: NavSurfaceUpdate | null = null;+ private surfaceUpdateVersion_ = 0;+/** Where agents may walk, or null until something builds and installs it. */- surface: NavSurface | null = null;+ get surface(): NavSurface | null { return this.surface_; }+ set surface(surface: NavSurface | null) {+ this.surfaceUpdate_?.cancel();+ this.surface_ = surface;+ }/** Soft planning time budget per NavAgentSystem tick, in ms. At least one* query may run; a synchronous query cannot be interrupted. <=0 disables it. */planningBudgetMs = 2;/** Maximum agent plans per tick; <=0 disables the count limit. */maxPlansPerFrame = 16;- /** Last agent-planning tick only; excludes movement, avoidance and baking. */+ /** Last agent tick; pending includes agents held for a surface update.+ * Time excludes movement, avoidance and baking. */readonly planningStats = { completed: 0, pending: 0, elapsedMs: 0 };private pathRevision_ = 0;/** Revision used by agents to retire cached plans after an explicit update. */get pathRevision(): number { return this.pathRevision_; }+ /** Agents retain destinations and wait while a replacement is pending. */+ get surfaceUpdatePending(): boolean { return this.surfaceUpdate_ !== null; }++ /** Stage an async producer's result without exposing a half-built surface.+ * Starting another request cancels the previous one's right to commit.+ * This schedules no worker; the producer owns computation and yielding. */+ beginSurfaceUpdate(): NavSurfaceUpdate {+ this.surfaceUpdate_?.cancel();+ let cancelled = false;+ const update: NavSurfaceUpdate = {+ version: ++this.surfaceUpdateVersion_,+ get pending() { return current(); },+ get cancelled() { return cancelled; },+ commit: surface => {+ if (!current()) return false;+ this.surfaceUpdate_ = null;+ this.surface_ = surface;+ this.invalidatePaths();+ return true;+ },+ cancel: () => {+ if (!current()) return false;+ cancelled = true;+ this.surfaceUpdate_ = null;+ return true;+ },+ };+ const current = () => this.surfaceUpdate_ === update;+ this.surfaceUpdate_ = update;+ return Object.freeze(update);+ }+/** Replan agents after editing a custom surface or its links/costs in place.* Built-in grid topology and replacing the surface are detected automatically. */invalidatePaths(): void { this.pathRevision_++; }@@ -47,11 +100,13 @@ export class Navigation {* {@link NavSurface.findWorldPath} for what the waypoints carry.*/findWorldPath(from: NavPoint, to: NavPoint, opts?: NavQueryOptions): Vec3[] | null {+ if (this.surfaceUpdatePending) return null;return this.surface ? this.surface.findWorldPath(from, to, opts) : null;}/** Explain a built-in route; custom surfaces without diagnostics report unknown. */queryWorldPath(from: NavPoint, to: NavPoint, opts?: NavQueryOptions): NavPathResult {+ if (this.surfaceUpdatePending) return { path: null, status: 'unavailable', reason: 'building' };if (!this.surface) return { path: null, status: 'unavailable', reason: 'no-surface' };if (this.surface.queryWorldPath) return this.surface.queryWorldPath(from, to, opts);return { path: this.surface.findWorldPath(from, to, opts), status: 'unknown', reason: 'diagnostics-unavailable' };diff --git a/sdk/src/ai/nav/index.ts b/sdk/src/ai/nav/index.tsindex 47ac4029a..42e002eb7 100644--- a/sdk/src/ai/nav/index.ts+++ b/sdk/src/ai/nav/index.ts@@ -16,7 +16,7 @@ export {collectNavGeometry, navGeometryReady,type NavGeometry, type CollectNavGeometryOptions,} from './navGeometry';-export { Navigation, Nav } from './Navigation';+export { Navigation, Nav, type NavSurfaceUpdate } from './Navigation';export { NavAgent, type NavAgentData, setNavDestination, stopNavAgent } from './NavAgent';export { NavVolume, type NavVolumeData } from './NavVolume';export { NavObstacle, type NavObstacleData } from './NavObstacle';diff --git a/sdk/tests/nav-step.test.ts b/sdk/tests/nav-step.test.tsindex b97714c6b..d10d62f97 100644--- a/sdk/tests/nav-step.test.ts+++ b/sdk/tests/nav-step.test.ts@@ -77,6 +77,31 @@ function openNav(width = 10, height = 3, cellSize = 10): Navigation {}describe('stepNavigation', () => {+ it.each(['cancel','commit'])('holds destinations during a surface update and resumes after %s', finish => {+ const world=new FakeWorld(),nav=openNav(40,9,10),runtimes=new Map<Entity,AgentRuntime>();+ const e=world.spawnAgent(20,40,{speed:60,radius:3,arriveRadius:2,repathInterval:0,+ hasTarget:true,targetX:300,targetY:40});+ stepNavigation(world,nav,1/60,runtimes);+ const before=world.pos(e),update=nav.beginSurfaceUpdate();+ for(let i=0;i<120;i++)stepNavigation(world,nav,1/60,runtimes);+ expect(world.pos(e)).toEqual(before);expect(world.agent(e)).toMatchObject({hasTarget:true,arrived:false});+ expect(nav.planningStats).toEqual({completed:0,pending:1,elapsedMs:0});+ if(finish==='commit')update.commit(new NavGrid({width:40,height:9,cellSize:10}));else update.cancel();+ for(let i=0;i<360;i++)stepNavigation(world,nav,1/60,runtimes);+ expect(world.agent(e).arrived).toBe(true);+ });++ it('clears pending-update character steering while preserving gravity and inactive bodies',()=>{+ const world=new FakeWorld(),nav=openNav(),runtimes=new Map<Entity,AgentRuntime>();+ const e=world.spawnAgent(20,0,{hasTarget:true,targetX:70});+ world.giveCharacter(e,{velocity:{x:100,y:-320,z:50}});+ const idle=world.spawnAgent(30,0,{hasTarget:false});+ world.giveCharacter(idle,{velocity:{x:20,y:-30,z:40}});+ nav.beginSurfaceUpdate();stepNavigation(world,nav,1/60,runtimes);+ expect(world.character(e).velocity).toEqual({x:0,y:-320,z:0});+ expect(world.character(idle).velocity).toEqual({x:20,y:-30,z:40});+ });+it.each([0, .5, 3, 5])('crowd followers honor a final arrival radius of %s', arriveRadius => {const world = new FakeWorld();const e = world.spawnAgent(20, 150, {speed:78, radius:8, arriveRadius,diff --git a/sdk/tests/nav-surface-update.test.ts b/sdk/tests/nav-surface-update.test.tsnew file mode 100644index 000000000..421994e80--- /dev/null+++ b/sdk/tests/nav-surface-update.test.ts@@ -0,0 +1,72 @@+// SPDX-License-Identifier: Apache-2.0+import {it,expect,vi} from 'vitest';+import {Navigation} from '../src/ai/nav/Navigation';+import {NavGrid} from '../src/ai/nav/NavGrid';++const grid=()=>new NavGrid({width:9,height:9,cellSize:10});+const from={x:20,y:40},to={x:60,y:40};++it('keeps the live surface but refuses routes while a replacement is pending',()=>{+ const nav=new Navigation(),old=grid();nav.setSurface(old);+ const query=vi.spyOn(old,'queryWorldPath');+ const update=nav.beginSurfaceUpdate();+ expect(nav.surface).toBe(old);expect(update.pending).toBe(true);+ expect(nav.queryWorldPath(from,to)).toEqual({path:null,status:'unavailable',reason:'building'});+ expect(nav.findWorldPath(from,to)).toBeNull();expect(query).not.toHaveBeenCalled();+ const replacement=grid(),before=nav.pathRevision;+ expect(update.commit(replacement)).toBe(true);+ expect(nav.surface).toBe(replacement);expect(nav.pathRevision).toBe(before+1);+ expect(nav.surfaceUpdatePending).toBe(false);expect(update.pending).toBe(false);+ expect(update.cancelled).toBe(false);expect(update.commit(old)).toBe(false);+ expect(update.cancel()).toBe(false);expect(nav.queryWorldPath(from,to).status).toBe('complete');+});++it('rejects a late async result after a newer request has committed',async()=>{+ const nav=new Navigation(),old=grid(),replacement=grid();nav.setSurface(old);+ const first=nav.beginSurfaceUpdate();+ let finish!:()=>void;+ const work=new Promise<void>(resolve=>{finish=resolve;}).then(()=>first.commit(old));+ const second=nav.beginSurfaceUpdate();+ expect(second.version).toBeGreaterThan(first.version);+ expect(first.cancelled).toBe(true);expect(first.pending).toBe(false);+ expect(second.commit(replacement)).toBe(true);+ finish();expect(await work).toBe(false);expect(nav.surface).toBe(replacement);+});++it('cancels idempotently and restores queries against the unchanged live surface',()=>{+ const nav=new Navigation(),old=grid();nav.setSurface(old);+ const update=nav.beginSurfaceUpdate(),revision=nav.pathRevision;+ expect(update.cancel()).toBe(true);expect(update.cancel()).toBe(false);+ expect(update.cancelled).toBe(true);expect(update.commit(grid())).toBe(false);+ expect(nav.pathRevision).toBe(revision);expect(nav.surface).toBe(old);+ expect(nav.queryWorldPath(from,to).status).toBe('complete');+});++it.each(['surface','setSurface'])('explicit %s replacement cancels an older producer',method=>{+ const nav=new Navigation(),update=nav.beginSurfaceUpdate(),replacement=grid();+ if(method==='surface')nav.surface=replacement;else nav.setSurface(replacement);+ expect(update.cancelled).toBe(true);expect(update.commit(grid())).toBe(false);+ expect(nav.surface).toBe(replacement);expect(nav.surfaceUpdatePending).toBe(false);+});++it('reports initial construction and supports an explicit empty result',()=>{+ const nav=new Navigation(),update=nav.beginSurfaceUpdate();+ expect(nav.hasSurface()).toBe(false);expect(nav.queryWorldPath(from,to).reason).toBe('building');+ expect(update.commit(null)).toBe(true);+ expect(nav.queryWorldPath(from,to).reason).toBe('no-surface');+});++it('invalidates cached plans even when a producer commits the same surface identity',()=>{+ const nav=new Navigation(),old=grid();nav.setSurface(old);+ const revision=nav.pathRevision,update=nav.beginSurfaceUpdate();+ expect(update.commit(old)).toBe(true);expect(nav.pathRevision).toBe(revision+1);+});++it('lets a failed producer cancel in finally without replacing the live surface',async()=>{+ const nav=new Navigation(),old=grid();nav.setSurface(old);+ const update=nav.beginSurfaceUpdate();+ await expect((async()=>{try{await Promise.reject(new Error('decode failed'));}+ finally{update.cancel();}})()).rejects.toThrow('decode failed');+ expect(nav.surfaceUpdatePending).toBe(false);expect(nav.surface).toBe(old);+ expect(nav.queryWorldPath(from,to).status).toBe('complete');+});diff --git a/tools/generate-navigation-workshop.mjs b/tools/generate-navigation-workshop.mjsindex 3f0dc920a..9ff25d024 100644--- a/tools/generate-navigation-workshop.mjs+++ b/tools/generate-navigation-workshop.mjs@@ -13,6 +13,17 @@ const uuid = name => {const h = createHash('sha256').update('estella.navigation-workshop.' + name).digest('hex');return `${h.slice(0,8)}-${h.slice(8,12)}-4${h.slice(13,16)}-a${h.slice(17,20)}-${h.slice(20,32)}`;};+fs.mkdirSync(path.join(project,'assets/navigation'),{recursive:true});+const walkable=Array.from({length:23*13},(_,i)=>{+ const x=i%23,y=Math.floor(i/23);+ return x===0||x===22||y===0||y===12||(x===11&&(y<5||y>7))?0:1;+});+fs.writeFileSync(path.join(project,'assets/navigation/courtyard.json'),JSON.stringify({+ width:23,height:13,cellSize:32,origin:{x:-352,y:-192},walkable,+},null,2)+'\n');+fs.writeFileSync(path.join(project,'assets/navigation/courtyard.json.meta'),JSON.stringify({+ uuid:uuid('terrain-layout'),version:'2.0',type:'json',importer:{},+},null,2)+'\n');const meta = name => fs.writeFileSync(path.join(textures, name + '.png.meta'), JSON.stringify({uuid: uuid(name), version: '2.0', type: 'texture', importer: {maxSize: 2048, filterMode: 'nearest', wrapMode: 'clamp', premultiplyAlpha: false,diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjsindex 0739f0716..b7905749f 100644--- a/tools/releaseNotes.mjs+++ b/tools/releaseNotes.mjs@@ -28,6 +28,10 @@ export const NOTES_FLOOR = 'v0.65.0';* the reader recognises anyway.*/export const NOTED = {+ 'feat(nav): explain pending navigation surface replacements':+ { note: 'Navigation replacements commit only from the latest request.' },+ 'feat(nav): stage cancellable surface replacements and explain pending routes':+ { note: 'Navigation replacements commit only from the latest request.' },'test(nav): yield fixed-step capture work to the compositor':{ internal: 'Headless workshop acceptance yields between fixed simulation batches so software rendering can drain before screenshots, and persists sampled facts before capture failures.' },'fix(nav): apply grid obstacle changes without bake throttling':diff --git a/tools/verify-navigation-inspector.mjs b/tools/verify-navigation-inspector.mjsindex c03227eb0..ef8fff2d0 100644--- a/tools/verify-navigation-inspector.mjs+++ b/tools/verify-navigation-inspector.mjs@@ -9,7 +9,7 @@ const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');const out = path.join(root, 'output/navigation-inspector-ci');fs.mkdirSync(out, { recursive: true });const records = [];-for (const state of ['complete', 'disconnected', 'insufficient-clearance', 'no-target']) {+for (const state of ['complete', 'disconnected', 'insufficient-clearance', 'no-target', 'building']) {const project = fs.mkdtempSync(path.join(out, 'project-'));fs.mkdirSync(path.join(project, 'assets/scenes'), { recursive: true });fs.mkdirSync(path.join(project, 'src'));@@ -27,7 +27,7 @@ import { Nav, Navigation, NavGrid } from 'esengine/ai';addPlugin({name:'navigation-inspection-fixture',build(app){const nav=new Navigation(),grid=new NavGrid({width:11,height:9,cellSize:1});${state === 'disconnected' || state === 'insufficient-clearance' ? `for(let y=0;y<9;y++) if(${state === 'insufficient-clearance' ? 'y!==4' : 'true'}) grid.setWalkable(5,y,false);` : ''}- nav.setSurface(grid);app.insertResource(Nav,nav);+ nav.setSurface(grid);${state === 'building' ? 'nav.beginSurfaceUpdate();' : ''}app.insertResource(Nav,nav);}});`);const script = `(async()=>{const e=window.__estellaEditor;@@ -53,11 +53,11 @@ addPlugin({name:'navigation-inspection-fixture',build(app){const line = run.stdout.split('\n').find(line => line.startsWith('[eval] '));assert(line, 'Missing inspector observation');const result = JSON.parse(line.slice('[eval] '.length));- const expected = { complete: 'Route reaches the resolved destination', disconnected: 'Start and target are disconnected', 'insufficient-clearance': 'this agent cannot fit', 'no-target': 'No active destination' }[state];+ const expected = { complete: 'Route reaches the resolved destination', disconnected: 'Start and target are disconnected', 'insufficient-clearance': 'this agent cannot fit', 'no-target': 'No active destination', building: 'Navigation is updating' }[state];assert(result.status.includes(expected), JSON.stringify(result));if (state !== 'no-target') assert(result.status.includes('Last planning tick:'), 'Missing live planning queue counters');assert(fs.existsSync(path.join(out, state + '.png')), 'Missing editor screenshot');records.push(result);fs.writeFileSync(path.join(out, 'observations.json'), JSON.stringify({ records }, null, 2));}-console.log('Navigation inspector: 4 live Play scenarios passed.');+console.log('Navigation inspector: 5 live Play scenarios passed.');diff --git a/tools/verify-navigation-workshop.mjs b/tools/verify-navigation-workshop.mjsindex 053d920ae..5cd9240d0 100644--- a/tools/verify-navigation-workshop.mjs+++ b/tools/verify-navigation-workshop.mjs@@ -125,6 +125,58 @@ try {assert.equal(crowdTrace.overlaps.length,0,'Crowded courier body entered the warehouse beyond contact skin');const crowd = await snapshot('crowd-delivered');assert.equal(crowd.arrived,24,'Crowded delivery did not complete');+ const manifest=JSON.parse(fs.readFileSync(path.join(dir,'asset-manifest.json'),'utf8'));+ const terrain=Object.values(manifest.groups).map(g=>g.assets['25e7e0fe-e665-4af2-ac71-777177b4c006']).find(Boolean);+ assert(terrain,'Missing packaged terrain JSON');+ const terrainUrl=origin+'/'+terrain.path,heldRequests=[];+ await page.route(terrainUrl,route=>{heldRequests.push(route);});+ await click('ResetButton');+ const firstRequest=page.waitForRequest(terrainUrl);+ await click('ReloadButton');await firstRequest;+ const cancelledVersion=(await facts()).reloadVersion;+ const positions=()=>page.evaluate(()=>window.__estellaCooked.probe(Array.from({length:24},(_,i)=>`Courier ${String(i+1).padStart(2,'0')}`)).at);+ const beforeHold=await positions();await step(180);+ const afterHold=await positions();+ records.push({name:'reload-hold-positions',frames:180,dt:1/60,before:beforeHold,after:afterHold});+ fs.writeFileSync(path.join(out,'observations.json'),JSON.stringify({...identity,records,errors},null,2));+ assert.deepEqual(afterHold,beforeHold,'A pending terrain update moved couriers on the old route');+ assert.equal((await snapshot('reload-held')).reloadPending,true);+ await click('CancelReloadButton');+ assert.equal((await facts()).reloadCancelled,cancelledVersion);+ await heldRequests.shift().continue();+ await page.waitForFunction(v=>window.__estellaCooked.facts().reloadSettled>=v,cancelledVersion);+ assert.equal((await facts()).reloadCommitted,0,'A cancelled terrain result was installed');+ await step(1800);+ assert.equal((await snapshot('reload-cancelled')).arrived,24,'Cancellation did not resume old routes');+ await click('ResetButton');+ const secondRequest=page.waitForRequest(terrainUrl);+ await click('ReloadButton');await secondRequest;+ const supersededVersion=(await facts()).reloadVersion;+ await click('ReloadButton');+ const latestVersion=(await facts()).reloadVersion;+ assert(latestVersion>supersededVersion,'A replacement request did not advance its version');+ await heldRequests.shift().continue();+ await page.waitForFunction(v=>{const f=window.__estellaCooked.facts();return !f.reloadPending&&f.reloadCommitted===v&&f.reloadSettled>=v;},latestVersion);+ const replacementTrace=await simulate(1800,24);+ records.push({name:'reload-committed-trace',...replacementTrace});+ fs.writeFileSync(path.join(out,'observations.json'),JSON.stringify({...identity,records,errors},null,2));+ assert.equal(replacementTrace.overlaps.length,0,'Reloaded terrain lost its live warehouse obstacle');+ assert.equal(replacementTrace.facts.arrived,24,'Replacement terrain did not resume retained destinations');+ await snapshot('reload-committed');+ await click('ResetButton');+ const failedRequest=page.waitForRequest(terrainUrl);+ await click('ReloadButton');await failedRequest;+ const failedVersion=(await facts()).reloadVersion;+ await heldRequests.shift().fulfill({contentType:'application/json',body:JSON.stringify({width:0})});+ await page.waitForFunction(v=>{const f=window.__estellaCooked.facts();return !f.reloadPending&&f.reloadFailed===v&&f.reloadSettled>=v;},failedVersion);+ assert.equal((await facts()).reloadCommitted,latestVersion,'Invalid terrain replaced the live grid');+ const failedTrace=await simulate(1800,24);+ records.push({name:'reload-failed-trace',responseOverride:{width:0},...failedTrace});+ fs.writeFileSync(path.join(out,'observations.json'),JSON.stringify({...identity,records,errors},null,2));+ assert.equal(failedTrace.overlaps.length,0,'Failed reload changed the active warehouse footprint');+ assert.equal(failedTrace.facts.arrived,24,'Failed terrain reload did not resume the retained grid');+ await snapshot('reload-failed');+ await page.unroute(terrainUrl);const touch=await browser.newPage({viewport:{width:768,height:540},hasTouch:true,isMobile:true});touch.on('pageerror',error=>errors.push(String(error)));await touch.goto(origin+'/?headless');@@ -168,5 +220,5 @@ try {sceneOverride:{path:'assets/scenes/main.esscene',enabled:['Gate','Warehouse'],sha256:createHash('sha256').update(authoredBody).digest('hex')}});assert.equal(errors.length,0,errors.join('\n'));fs.writeFileSync(path.join(out,'observations.json'),JSON.stringify({...identity,status:'passed',records,errors},null,2));- console.log('Workshop Web export: gate retention/resume, warehouse detour, 24-courier delivery and authored obstacles passed.');+ console.log('Workshop Web export: gate retention, crowd delivery, authored obstacles and terrain reload/cancel/supersede/failure passed.');} finally { await browser.close(); await new Promise(resolve=>server.close(resolve)); }