import type { Position } from '../../../sdk/types.js'; import { loadWalkableGrid, type WalkableGrid } from './walkable-grid.js'; interface NormalizedEndpoint { readonly cell: number; readonly point: Readonly; } export interface LocalPathDistanceQuery { readonly from: Readonly; readonly to: Readonly; } class MinHeap { private readonly cells: number[] = []; private readonly priorities: number[] = []; clear(): void { this.cells.length = 0; this.priorities.length = 0; } push(cell: number, priority: number): void { let index = this.cells.length; this.cells.push(cell); this.priorities.push(priority); while (index > 0) { const parent = (index - 1) >> 1; if (this.priorities[parent] <= priority) break; this.cells[index] = this.cells[parent]; this.priorities[index] = this.priorities[parent]; index = parent; } this.cells[index] = cell; this.priorities[index] = priority; } pop(): { cell: number; priority: number } | null { if (this.cells.length === 0) return null; const cell = this.cells[0]; const priority = this.priorities[0]; const lastCell = this.cells.pop()!; const lastPriority = this.priorities.pop()!; if (this.cells.length > 0) { let index = 0; while (true) { const left = index * 2 + 1; if (left >= this.cells.length) break; const right = left + 1; const child = right < this.cells.length && this.priorities[right] < this.priorities[left] ? right : left; if (this.priorities[child] >= lastPriority) break; this.cells[index] = this.cells[child]; this.priorities[index] = this.priorities[child]; index = child; } this.cells[index] = lastCell; this.priorities[index] = lastPriority; } return { cell, priority }; } } const NEIGHBORS = [ [1, 0], [-1, 0], [0, 1], [0, -1], [1, 1], [1, -1], [-1, 1], [-1, -1], ] as const; /** Local A* over the packaged collision-inflated ClawClaw walkability grid. */ export class AStarPathfinder { private readonly score: Float64Array; private readonly seen: Uint32Array; private readonly closed: Uint32Array; private readonly heap = new MinHeap(); private generation = 0; constructor(private readonly grid: WalkableGrid) { const cells = grid.width * grid.height; this.score = new Float64Array(cells); this.seen = new Uint32Array(cells); this.closed = new Uint32Array(cells); } distance(from: Position, to: Position): number | null { if ( !Number.isFinite(from?.x) || !Number.isFinite(from?.y) || !Number.isFinite(to?.x) || !Number.isFinite(to?.y) ) { throw new TypeError('Path distance points must contain finite x/y coordinates.'); } const start = this.normalize(from); const goal = this.normalize(to); if (!start || !goal) return null; if (start.cell === goal.cell) { return Math.hypot(goal.point.x - start.point.x, goal.point.y - start.point.y); } const cellDistance = this.findCellDistance(start.cell, goal.cell); return cellDistance == null ? null : this.measureCellDistance(start, goal, cellDistance); } /** * Resolve arbitrary route pairs in input order. Repeated endpoints are * grouped by their snapped grid cell on the smaller side of the batch so * one graph scan serves every route in that group. */ distances(queries: readonly LocalPathDistanceQuery[]): Array { for (const { from, to } of queries) { this.assertFinitePoint(from); this.assertFinitePoint(to); } if (queries.length === 0) return []; const results = new Array(queries.length).fill(null); const pending: Array<{ readonly index: number; readonly from: NormalizedEndpoint; readonly to: NormalizedEndpoint; }> = []; for (const [index, query] of queries.entries()) { const from = this.normalize(query.from); const to = this.normalize(query.to); if (!from || !to) continue; if (from.cell !== to.cell) { pending.push({ index, from, to }); continue; } results[index] = Math.hypot( to.point.x - from.point.x, to.point.y - from.point.y, ); } if (pending.length === 0) return results; const fromCells = new Set(pending.map(({ from }) => from.cell)); const toCells = new Set(pending.map(({ to }) => to.cell)); const reverse = toCells.size < fromCells.size; const groups = new Map(); for (const query of pending) { const anchorCell = (reverse ? query.to : query.from).cell; const group = groups.get(anchorCell) ?? []; group.push(query); groups.set(anchorCell, group); } for (const [anchorCell, entries] of groups) { const targetCells = new Set(entries.map(query => ( reverse ? query.from.cell : query.to.cell ))); let cellDistances: ReadonlyMap; if (targetCells.size === 1) { const targetCell = targetCells.values().next().value as number; const distance = this.findCellDistance(anchorCell, targetCell); cellDistances = distance === null ? new Map() : new Map([[targetCell, distance]]); } else { cellDistances = this.findCellDistancesToGoals(anchorCell, targetCells); } for (const query of entries) { const targetCell = (reverse ? query.from : query.to).cell; const cellDistance = cellDistances.get(targetCell); results[query.index] = cellDistance === undefined ? null : this.measureCellDistance(query.from, query.to, cellDistance); } } return results; } private assertFinitePoint(point: Readonly): void { if (!Number.isFinite(point?.x) || !Number.isFinite(point?.y)) { throw new TypeError('Path distance points must contain finite x/y coordinates.'); } } private measureCellDistance( start: NormalizedEndpoint, goal: NormalizedEndpoint, cellDistance: number, ): number { // Route through both endpoint cell centers. This is independent of A*/ // Dijkstra parent tie-breaking and is a conservative upper bound for the // backend's smoothed path over the same walkable-cell route. const startCenter = this.grid.cellToWorld(start.cell); const goalCenter = this.grid.cellToWorld(goal.cell); const distance = cellDistance + Math.hypot(start.point.x - startCenter.x, start.point.y - startCenter.y) + Math.hypot(goal.point.x - goalCenter.x, goal.point.y - goalCenter.y); return Math.round(distance * 10) / 10; } private normalize(point: Readonly): NormalizedEndpoint | null { const rawCell = this.grid.worldToCell(point.x, point.y); const inside = point.x >= 0 && point.y >= 0 && point.x < this.grid.width * this.grid.tileSize && point.y < this.grid.height * this.grid.tileSize; if (inside && this.grid.isWalkableCell(rawCell)) return { cell: rawCell, point }; const cell = this.grid.snapToWalkable(rawCell); return cell < 0 ? null : { cell, point: this.grid.cellToWorld(cell) }; } private findCellDistance(start: number, goal: number): number | null { const generation = this.nextGeneration(); this.heap.clear(); this.seen[start] = generation; this.score[start] = 0; this.heap.push(start, this.heuristic(start, goal)); while (true) { const next = this.heap.pop(); if (!next) return null; const { cell } = next; if (this.closed[cell] === generation) continue; if (next.priority > this.score[cell] + this.heuristic(cell, goal) + Number.EPSILON) continue; if (cell === goal) return this.score[cell]; this.closed[cell] = generation; this.visitNeighbors(cell, goal, generation); } } private findCellDistancesToGoals( start: number, goals: ReadonlySet, ): Map { if (goals.size === 0) return new Map(); const generation = this.nextGeneration(); const remaining = new Set(goals); const reached = new Map(); this.heap.clear(); this.seen[start] = generation; this.score[start] = 0; this.heap.push(start, 0); while (remaining.size > 0) { const next = this.heap.pop(); if (!next) break; const { cell } = next; if (this.closed[cell] === generation) continue; if (next.priority > this.score[cell] + Number.EPSILON) continue; this.closed[cell] = generation; if (remaining.delete(cell)) reached.set(cell, this.score[cell]); if (remaining.size === 0) break; this.visitNeighbors(cell, null, generation); } return reached; } private visitNeighbors(cell: number, goal: number | null, generation: number): void { const x = cell % this.grid.width; const y = Math.floor(cell / this.grid.width); for (const [dx, dy] of NEIGHBORS) { const nx = x + dx; const ny = y + dy; if (!this.grid.isWalkable(nx, ny)) continue; if (dx !== 0 && dy !== 0) { if (!this.grid.isWalkable(x + dx, y) || !this.grid.isWalkable(x, y + dy)) continue; } const neighbor = ny * this.grid.width + nx; if (this.closed[neighbor] === generation) continue; const tentative = this.score[cell] + (dx === 0 || dy === 0 ? this.grid.tileSize : this.grid.tileSize * Math.SQRT2); if (this.seen[neighbor] === generation && this.score[neighbor] <= tentative) continue; this.seen[neighbor] = generation; this.score[neighbor] = tentative; this.heap.push(neighbor, tentative + (goal == null ? 0 : this.heuristic(neighbor, goal))); } } private heuristic(from: number, to: number): number { const dx = Math.abs((from % this.grid.width) - (to % this.grid.width)); const dy = Math.abs(Math.floor(from / this.grid.width) - Math.floor(to / this.grid.width)); const diagonal = Math.min(dx, dy); return this.grid.tileSize * (Math.max(dx, dy) + (Math.SQRT2 - 1) * diagonal); } private nextGeneration(): number { this.generation = (this.generation + 1) >>> 0; if (this.generation === 0) { this.seen.fill(0); this.closed.fill(0); this.generation = 1; } return this.generation; } } let defaultPathfinder: AStarPathfinder | null = null; export function getLocalPathDistance(from: Position, to: Position): number | null { defaultPathfinder ??= new AStarPathfinder(loadWalkableGrid()); return defaultPathfinder.distance(from, to); } export function getLocalPathDistances( queries: readonly LocalPathDistanceQuery[], ): Array { defaultPathfinder ??= new AStarPathfinder(loadWalkableGrid()); return defaultPathfinder.distances(queries); }