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
perf(nav): reuse grid search workspaces across queries
yhhee0fb5fda018
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex dee8cfec4..757db40fc 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -16,6 +16,8 @@ published separately; it ships inside the editor.### Fixed+- **Grid path searches reuse their working memory.** Repeated queries reuse per-grid score, parent, visitation and heap storage instead of allocating map-sized buffers each time. Search stamps isolate queries, nested searches receive separate storage, exceptions release leases, and returned routes remain caller-owned. Weighted paths, snapping and best-effort endpoints retain their behavior.+- **Native text measurement wraps without rescanning growing prefixes.** The public measurement path appends ordered glyph advances through the shared greedy wrapper, avoiding quadratic cache queries and repeated host rasterization when long text exceeds the bounded working set. Whitespace, supplementary characters and signed spacing keep existing line breaks and metrics; Canvas retains whole-string measurement for non-additive typography.- **Public native text measurement retains a bounded advance cache.** Historical font revisions, sizes and missing-glyph estimates retire from a 4096-entry working set. A second-chance clock keeps recently queried advances reusable without reinserting Map entries on every character; failed host measurements leave retained entries intact. Widths, wrapping and the Canvas measurement path retain their existing behavior.diff --git a/docs/astro/src/content/docs/gameplay/ai/navigation.mdx b/docs/astro/src/content/docs/gameplay/ai/navigation.mdxindex 76e18d7f0..afb650157 100644--- a/docs/astro/src/content/docs/gameplay/ai/navigation.mdx+++ b/docs/astro/src/content/docs/gameplay/ai/navigation.mdx@@ -260,6 +260,10 @@ grid walkability through `setWalkable`, `setObstructed` and `clearObstructions`clearance and cached connectivity are invalidated together. Dynamic blockerscontribute to body clearance. Area prices remain live without rebuilding connectivity.+Repeated grid queries reuse working memory. Returned routes remain independent,+so callers may retain or edit them without changing a later search. Route costs,+endpoint snapping and best-effort partial paths retain their existing behavior.+The reproducible CPU corpus runs in headless Chromium with door and buildingchanges on 32/64/128-cell maps and 64 simultaneous replans:diff --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 c59c7b26c..38f41c931 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@@ -222,6 +222,9 @@ if (result.status !== 'complete') console.info(result.reason);格子通行状态通过 `setWalkable`、`setObstructed` 和 `clearObstructions` 修改,确保净空和连通性缓存一起失效。动态障碍也计入角色宽度所需净空;区域价格变化无需重建连通性。+重复格子查询会复用工作内存;返回的路线仍各自独立,可保留或修改,不会影响后续查询。+路线代价、端点吸附和尽量靠近的部分路径行为保持一致。+可复现的 CPU 语料使用无头 Chromium,在 32/64/128 格地图中开关门、放置建筑并同时重算64 个代理的路径:diff --git a/sdk/src/ai/nav/gridSearchScratch.ts b/sdk/src/ai/nav/gridSearchScratch.tsnew file mode 100644index 000000000..9a9895671--- /dev/null+++ b/sdk/src/ai/nav/gridSearchScratch.ts@@ -0,0 +1,45 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+import type { NavGrid } from './NavGrid';+import { MinHeap } from './minHeap';++export interface GridSearchScratch {+ gScore: Float64Array;+ cameFrom: Int32Array;+ seen: Uint32Array;+ closed: Uint32Array;+ heap: MinHeap;+ epoch: number;+ leased: boolean;+}++const buffers = new WeakMap<NavGrid, GridSearchScratch>();+const create = (count: number): GridSearchScratch => ({+ gScore: new Float64Array(count), cameFrom: new Int32Array(count),+ seen: new Uint32Array(count), closed: new Uint32Array(count),+ heap: new MinHeap(count), epoch: 0, leased: false,+});++/** Reentrant queries get private temporary storage while the grid's buffer is leased. */+export function leaseGridSearch(grid: NavGrid): GridSearchScratch {+ let state = buffers.get(grid);+ if (!state) {+ state = create(grid.width * grid.height);+ buffers.set(grid, state);+ } else if (state.leased) {+ state = create(grid.width * grid.height);+ }+ state.leased = true;+ state.epoch = (state.epoch + 1) >>> 0;+ if (state.epoch === 0) {+ state.seen.fill(0); state.closed.fill(0);+ state.epoch = 1;+ }+ state.heap.size = 0;+ return state;+}++/** Returned routes contain cell objects, so no caller retains these working arrays. */+export function releaseGridSearch(state: GridSearchScratch): void {+ state.leased = false;+}diff --git a/sdk/src/ai/nav/pathfind.ts b/sdk/src/ai/nav/pathfind.tsindex 488ad37a3..29521053e 100644--- a/sdk/src/ai/nav/pathfind.ts+++ b/sdk/src/ai/nav/pathfind.ts@@ -11,7 +11,7 @@*/import type { NavGrid, Cell } from './NavGrid';-import { MinHeap } from './minHeap';+import { leaseGridSearch, releaseGridSearch, type GridSearchScratch } from './gridSearchScratch';import { cachedGridGoal, rememberGridComponents } from './gridConnectivity';import type { Vec3 } from '../../types';@@ -64,29 +64,38 @@ export function findPath(const requestedGoal = g;g = cachedGridGoal(grid, s, g, clearance, (x, y) => heuristic(x, y, requestedGoal.x, requestedGoal.y, diagonal)) ?? g;- const { width, height } = grid;- const n = width * height;+ if (s.x === g.x && s.y === g.y) return [{ x: s.x, y: s.y }];++ const state = leaseGridSearch(grid);+ try {+ return searchGridPath(grid, s, g, clearance, diagonal, state);+ } finally {+ releaseGridSearch(state);+ }+}++function searchGridPath(+ grid: NavGrid, s: Cell, g: Cell, clearance: number, diagonal: boolean, state: GridSearchScratch,+): Cell[] {+ const { width } = grid;const startIdx = s.y * width + s.x;const goalIdx = g.y * width + g.x;- if (startIdx === goalIdx) return [{ x: s.x, y: s.y }];-- const gScore = new Float64Array(n).fill(Infinity);- const cameFrom = new Int32Array(n).fill(-1);- const closed = new Uint8Array(n);+ const { gScore, cameFrom, closed, seen, heap, epoch } = state;gScore[startIdx] = 0;+ cameFrom[startIdx] = -1;+ seen[startIdx] = epoch;// The nearest the search ever got, in case it never gets there.let nearestIdx = startIdx;let nearestScore = heuristic(s.x, s.y, g.x, g.y, diagonal);- const heap = new MinHeap(n);heap.push(startIdx, nearestScore);while (heap.size > 0) {const current = heap.pop();if (current === goalIdx) return reconstruct(cameFrom, current, width);- if (closed[current]) continue;- closed[current] = 1;+ if (closed[current] === epoch) continue;+ closed[current] = epoch;const cx = current % width;const cy = (current - cx) / width;@@ -101,11 +110,12 @@ export function findPath(if (i >= 4 && (!fits(grid, cx + dx, cy, clearance) || !fits(grid, cx, cy + dy, clearance))) continue;const nIdx = ny * width + nx;- if (closed[nIdx]) continue;+ if (closed[nIdx] === epoch) continue;const step = (i < 4 ? 1 : SQRT2) * grid.costAt(nx, ny);const tentative = baseG + step;- if (tentative < gScore[nIdx]) {+ if (tentative < (seen[nIdx] === epoch ? gScore[nIdx]! : Infinity)) {+ seen[nIdx] = epoch;gScore[nIdx] = tentative;cameFrom[nIdx] = current;const toGoal = heuristic(nx, ny, g.x, g.y, diagonal);diff --git a/sdk/tests/nav-search-scratch.test.ts b/sdk/tests/nav-search-scratch.test.tsnew file mode 100644index 000000000..af106f50d--- /dev/null+++ b/sdk/tests/nav-search-scratch.test.ts@@ -0,0 +1,117 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+import { describe, it, expect } from 'vitest';+import { NavGrid } from '../src/ai/nav/NavGrid';+import { findPath } from '../src/ai/nav/pathfind';+import { leaseGridSearch, releaseGridSearch } from '../src/ai/nav/gridSearchScratch';++function referenceCosts(grid: NavGrid, start: { x: number; y: number }, diagonal: boolean): number[] {+ const costs = Array<number>(grid.width * grid.height).fill(Infinity);+ const closed = new Set<number>();+ costs[grid.index(start.x, start.y)] = 0;+ for (;;) {+ let at = -1, nearest = Infinity;+ for (let i = 0; i < costs.length; i++) if (!closed.has(i) && costs[i]! < nearest) {+ at = i; nearest = costs[i]!;+ }+ if (at < 0) return costs;+ closed.add(at);+ const x = at % grid.width, y = Math.floor(at / grid.width);+ for (let dy = -1; dy <= 1; dy++) for (let dx = -1; dx <= 1; dx++) {+ if ((!dx && !dy) || (!diagonal && dx && dy)) continue;+ if (!grid.isWalkable(x + dx, y + dy)) continue;+ if (dx && dy && (!grid.isWalkable(x + dx, y) || !grid.isWalkable(x, y + dy))) continue;+ const next = grid.index(x + dx, y + dy);+ costs[next] = Math.min(costs[next]!, nearest + Math.hypot(dx, dy) * grid.costAt(x + dx, y + dy));+ }+ }+}++describe('grid search working storage', () => {+ it('retains weighted shortest paths and closest partial endpoints across repeated queries', () => {+ let seed = 23;+ const random = () => ((seed = (Math.imul(seed, 1664525) + 1013904223) >>> 0) / 0x100000000);+ const corners = [{ x: 0, y: 0 }, { x: 8, y: 8 }, { x: 8, y: 0 }, { x: 0, y: 8 }];+ for (let sample = 0; sample < 40; sample++) {+ const mask = Uint8Array.from({ length: 81 }, () => random() > 0.25 ? 1 : 0);+ for (const p of corners) mask[p.y * 9 + p.x] = 1;+ if (sample % 3 === 0) for (let y = 0; y < 9; y++) mask[y * 9 + 4] = 0;+ const grid = new NavGrid({ width: 9, height: 9, cellSize: 1, walkable: mask });+ for (let y = 0; y < 9; y++) for (let x = 0; x < 9; x++) grid.setCost(x, y, 1 + Math.floor(random() * 4));+ for (const [ai, bi] of [[0,1],[1,0],[0,2],[3,1]]) {+ const a = corners[ai!]!, b = corners[bi!]!, diagonal = sample % 2 === 0;+ const oracle = referenceCosts(grid, a, diagonal);+ const path = findPath(grid, a, b, { diagonal, snapRadius: 0 })!;+ expect(path[0]).toEqual(a);+ const end = path.at(-1)!;+ if (Number.isFinite(oracle[grid.index(b.x, b.y)])) expect(end).toEqual(b);+ else {+ const distance = (x: number, y: number) => {+ const dx = Math.abs(x - b.x), dy = Math.abs(y - b.y);+ return dx + dy + (diagonal ? (Math.SQRT2 - 2) * Math.min(dx, dy) : 0);+ };+ const closest = Math.min(...oracle.map((v, i) => Number.isFinite(v) ? distance(i % 9, Math.floor(i / 9)) : Infinity));+ expect(distance(end.x, end.y)).toBeCloseTo(closest);+ }+ let cost = 0;+ for (let i = 1; i < path.length; i++) {+ const p = path[i - 1]!, q = path[i]!;+ expect(grid.isWalkable(q.x, q.y)).toBe(true);+ expect(Math.max(Math.abs(q.x - p.x), Math.abs(q.y - p.y))).toBe(1);+ if (p.x !== q.x && p.y !== q.y) {+ expect(diagonal && grid.isWalkable(p.x, q.y) && grid.isWalkable(q.x, p.y)).toBe(true);+ }+ cost += Math.hypot(q.x - p.x, q.y - p.y) * grid.costAt(q.x, q.y);+ }+ expect(cost).toBeCloseTo(oracle[grid.index(end.x, end.y)]!);+ }+ }+ });++ it('supports a nested query on the same grid without replacing the outer path state', () => {+ const grid = new NavGrid({ width: 16, height: 16, cellSize: 1 });+ for (let y = 0; y < 16; y++) if (y !== 8) grid.setWalkable(8, y, false);+ let nested = false;+ grid.costAt = () => {+ if (!nested) {+ nested = true;+ const route = findPath(grid, { x: 15, y: 0 }, { x: 0, y: 15 })!;+ expect(route[0]).toEqual({ x: 15, y: 0 }); expect(route.at(-1)).toEqual({ x: 0, y: 15 });+ }+ return 1;+ };+ const outer = findPath(grid, { x: 0, y: 0 }, { x: 15, y: 15 })!;+ expect(nested).toBe(true);+ expect(outer[0]).toEqual({ x: 0, y: 0 }); expect(outer.at(-1)).toEqual({ x: 15, y: 15 });+ expect(outer.some(p => p.x === 8 && p.y === 8)).toBe(true);+ });++ it('releases leased storage after a query throws', () => {+ const grid = new NavGrid({ width: 5, height: 5, cellSize: 1 });+ const first = leaseGridSearch(grid); releaseGridSearch(first);+ grid.costAt = () => { throw new Error('cost failed'); };+ expect(() => findPath(grid, { x: 0, y: 0 }, { x: 4, y: 4 })).toThrow('cost failed');+ const again = leaseGridSearch(grid);+ expect(again).toBe(first); releaseGridSearch(again);+ grid.costAt = () => 1;+ expect(findPath(grid, { x: 0, y: 0 }, { x: 4, y: 4 })?.at(-1)).toEqual({ x: 4, y: 4 });+ });++ it('clears stamps when their counter wraps', () => {+ const grid = new NavGrid({ width: 5, height: 5, cellSize: 1 });+ const state = leaseGridSearch(grid);+ state.epoch = 0xffffffff;+ state.seen.fill(1); state.closed.fill(1); state.gScore.fill(-100); state.cameFrom.fill(0);+ releaseGridSearch(state);+ const route = findPath(grid, { x: 0, y: 0 }, { x: 4, y: 4 })!;+ expect(route[0]).toEqual({ x: 0, y: 0 }); expect(route.at(-1)).toEqual({ x: 4, y: 4 });+ });++ it('leaves returned routes owned by their caller', () => {+ const grid = new NavGrid({ width: 20, height: 20, cellSize: 1 });+ const first = findPath(grid, { x: 0, y: 0 }, { x: 19, y: 19 })!;+ const snapshot = structuredClone(first);+ for (let i = 0; i < 20; i++) findPath(grid, { x: 19, y: i }, { x: 0, y: 19 - i });+ expect(first).toEqual(snapshot);+ });+});diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjsindex aadaf6a77..03bc41249 100644--- a/tools/releaseNotes.mjs+++ b/tools/releaseNotes.mjs@@ -28,6 +28,8 @@ export const NOTES_FLOOR = 'v0.65.0';* the reader recognises anyway.*/export const NOTED = {+ 'perf(nav): reuse grid search workspaces across queries':+ { note: 'Grid path searches reuse their working memory.' },'feat(nav): diagnose partial routes and reuse disconnected grid topology':{ note: 'Navigation queries distinguish complete routes from best-effort paths.' },'perf(text): wrap native measurements with ordered advances':