Files
OpenFrontIO/tests/pathfinding/playground/api/maps.ts
T
Arkadiusz Sygulski 0e3ced3bfa Pathfinding Refactor pt. 2 (#2866)
## Playtest

https://pf-pt-2.openfront.dev/

## Pathfinding Refactor pt. 2

<img width="1536" height="1024" alt="image"
src="https://github.com/user-attachments/assets/9477958e-54b7-4c83-b317-ba789e809e9e"
/>


This is a follow-up to a previous PR introducing pathfinding changes.
This time, it introduces a complete refactor of `pathfinding` directory
and breakdown into composable pieces.

### Unified PathFinder interface

`PathFinder<T>` and `SteppingPathFinder<T>` are introduced to unify
**all** pathfinding across the application. First one exposes complete
path, while stepping variant allows the callee to iterate over the path
by calling `.next`. All pathfinders share this one common interface,
which makes them easy to use in any scenario -
`PathFinding.Water(game).search(from, to)`.

`SteppingPathFinder<T>` extends `PathFinder<T>` with an ability to
iterate over the path. It handles caching, storing current index and
invalidation. This allows the units to not care about the inner workings
of the pathfinder and just call `pf.next(current, target)` and receive
instructions on what to do next.

### Common entry point

All pathfinders are now exposed from common `PathFinding` entrypoint:

- `PathFinding.Water`
- `PathFinding.Rail`
- `PathFinding.Stations`
- `PathFinding.Rail`

Additional entry point is introduced for pathfinders which need to work
both in the worker, but also on the frontend, which lacks `Game`
interface. Currently only `UniversalPathFinding.Parabola` is available.

### Spatial Query

New module has been introduced close to `pathfinding` - `SpatialQuery`.
It aims to resolve any questions game may have about finding tiles
meeting criteria. Currently `SpatialQuery.closestShore(player, target)`
and `SpatialQuery.closestShoreByWater(player, target)` are available -
they help answering questions about naval invasion: "What is the best
landing location from user's click?" and "Which our tile should be used
to launch the transport ship?". Under the hood they use very similar
mechanics to pathfinding, so it felt right to put them close by.

### Modular architecture

Pathfinders now support transformers: `MiniMapTransformer`,
`ShoreCoercingTransformer`, `ComponentCheckTransformer`,
`SmoothingTransformer`. Transformers functions like a middleware in the
pathfinding chain. They wrap around the pathfinder and provide
additional functionality. This allows the pathfinder to focus on
actually finding the path instead of doing unrelated things.

Example chain for simple (A*) water pathfinding:
```ts
static WaterSimple(game: Game): SteppingPathFinder<TileRef> {
  const miniMap = game.miniMap();
  const pf = new AStarWater(miniMap);

  return PathFinderBuilder.create(pf)
    .wrap((pf) => new ShoreCoercingTransformer(pf, miniMap))
    .wrap((pf) => new MiniMapTransformer(pf, game.map(), miniMap))
    .buildWithStepper(tileStepperConfig(game));
}
```

The Pathfinder - here `AStarWater` - does not care about the conversion
between minimap and main map tiles. It also does not care if the source
or destination is a land tile. The transformers take care of that. The
pathfinder gets a set of valid coordinates and produces the path -
that's it.

Modular approach makes working on a particular set of utilities much
easier - for example map upscaling is handled consistently across all
pathfinders. Additionally, the pathfinders are not tied to the
particular map resolution used. Pass them a different map and they will
work the same.

### Algorithms

Algorithms used are neatly organized inside
`src/core/pathfinding/algorithms`. They are prefixed with the algorithm
name and suffixed with the use case. File without suffix exposes generic
version ready to traverse any graph with adapters. Specialized versions
either use an adapter or inline logic when performance is critical -
using adapters leads to 20-30% performance loss.

The directory includes `A*` and `BFS` but also other useful utils, such
as `AbstractGraph` used to generate... an abstract graph on top of the
tile map and `ConnectedComponents` helping to identify whether two tiles
are connected by a path without actually computing the path.

### Playground

The playground have been updated with new algorithms, including tweaked
very greedy `A*`.

<img width="2175" height="1424" alt="image"
src="https://github.com/user-attachments/assets/1f833651-0024-4299-bf86-882f5368358c"
/>

### Tests

Yeah, there are some, a little too many if I say so myself. But there
are no useless tests. I had to ensure refactored code works somehow
reliably. This PR comes with trust me bro guarantee, but I would
appreciate someone confirming **naval invasions, nukes (esp. MIRV) and
warships**.

### Discord
`moleole`

GL & HF
2026-01-11 20:11:14 -08:00

219 lines
5.5 KiB
TypeScript

import { readdirSync, readFileSync } from "fs";
import { dirname, join } from "path";
import { fileURLToPath } from "url";
import { Game } from "../../../../src/core/game/Game.js";
import { AStarWaterHierarchical } from "../../../../src/core/pathfinding/algorithms/AStar.WaterHierarchical.js";
import { setupFromPath } from "../../utils.js";
// Available comparison adapters
// Note: "hpa" runs same algorithm without debug overhead for fair timing comparison
export const COMPARISON_ADAPTERS = ["hpa", "a.baseline", "a.generic", "a.full"];
export interface MapInfo {
name: string;
displayName: string;
}
export interface MapCache {
game: Game;
hpaStar: AStarWaterHierarchical;
}
const cache = new Map<string, MapCache>();
/**
* Global configuration for map loading
*/
let config = {
cachePaths: true,
};
/**
* Set configuration options
*/
export function setConfig(options: { cachePaths?: boolean }) {
config = { ...config, ...options };
}
/**
* Get the resources/maps directory path
*/
function getMapsDirectory(): string {
return join(
dirname(fileURLToPath(import.meta.url)),
"../../../../resources/maps",
);
}
/**
* Format map name to title case with proper spacing
* Handles: underscores, camelCase, existing spaces, and parentheses
*/
function formatMapName(name: string): string {
return (
name
// Replace underscores with spaces
.replace(/_/g, " ")
// Add space before capital letters (for camelCase)
.replace(/([a-z])([A-Z])/g, "$1 $2")
// Convert to lowercase first
.toLowerCase()
// Capitalize first letter of string
.replace(/^\w/, (char) => char.toUpperCase())
// Capitalize after spaces and opening parentheses
.replace(/(\s+|[(])\w/g, (match) => match.toUpperCase())
);
}
/**
* Get list of available maps by reading the resources/maps directory
*/
export function listMaps(): MapInfo[] {
const mapsDir = getMapsDirectory();
const maps: MapInfo[] = [];
try {
const entries = readdirSync(mapsDir, { withFileTypes: true });
for (const entry of entries) {
if (entry.isDirectory()) {
const name = entry.name;
let displayName = formatMapName(name);
// Try to read displayName from manifest.json
try {
const manifestPath = join(mapsDir, name, "manifest.json");
const manifestData = JSON.parse(readFileSync(manifestPath, "utf-8"));
if (manifestData.name) {
displayName = formatMapName(manifestData.name);
}
} catch (e) {
// If manifest doesn't exist or doesn't have name, use formatted folder name
console.warn(
`Could not read manifest for ${name}:`,
e instanceof Error ? e.message : e,
);
}
maps.push({ name, displayName });
}
}
} catch (e) {
console.error("Failed to read maps directory:", e);
}
return maps.sort((a, b) => a.displayName.localeCompare(b.displayName));
}
/**
* Load a map from cache or disk
*/
export async function loadMap(mapName: string): Promise<MapCache> {
// Check cache first
if (cache.has(mapName)) {
return cache.get(mapName)!;
}
const mapsDir = getMapsDirectory();
// Use the existing setupFromPath utility to load the map
const game = await setupFromPath(mapsDir, mapName, { disableNavMesh: false });
// Get pre-built graph from game
const graph = game.miniWaterGraph();
if (!graph) {
throw new Error(`No water graph available for map: ${mapName}`);
}
// Initialize AStarWaterHierarchical with minimap and graph
const hpaStar = new AStarWaterHierarchical(game.miniMap(), graph, {
cachePaths: config.cachePaths,
});
const cacheEntry: MapCache = { game, hpaStar };
// Store in cache
cache.set(mapName, cacheEntry);
return cacheEntry;
}
/**
* Get map metadata for client
*/
export async function getMapMetadata(mapName: string) {
const { game, hpaStar } = await loadMap(mapName);
// Extract map data
const mapData: number[] = [];
for (let y = 0; y < game.height(); y++) {
for (let x = 0; x < game.width(); x++) {
const tile = game.ref(x, y);
mapData.push(game.isWater(tile) ? 1 : 0);
}
}
// Extract static graph data from GameMapHPAStar
// Access internal graph via type casting (test code only)
const graph = (hpaStar as any).graph;
const miniMap = game.miniMap();
// Convert nodes to client format
const allNodes = graph.getAllNodes().map((node: any) => ({
id: node.id,
x: miniMap.x(node.tile),
y: miniMap.y(node.tile),
}));
// Convert edges to client format
const edges: Array<{
fromId: number;
toId: number;
from: number[];
to: number[];
cost: number;
}> = [];
for (let i = 0; i < graph.edgeCount; i++) {
const edge = graph.getEdge(i);
if (!edge) continue;
const nodeA = graph.getNode(edge.nodeA);
const nodeB = graph.getNode(edge.nodeB);
if (!nodeA || !nodeB) continue;
edges.push({
fromId: edge.nodeA,
toId: edge.nodeB,
from: [miniMap.x(nodeA.tile) * 2, miniMap.y(nodeA.tile) * 2],
to: [miniMap.x(nodeB.tile) * 2, miniMap.y(nodeB.tile) * 2],
cost: edge.cost,
});
}
console.log(
`Map ${mapName}: ${allNodes.length} nodes, ${edges.length} edges`,
);
const clusterSize = graph.clusterSize;
return {
name: mapName,
width: game.width(),
height: game.height(),
mapData,
graphDebug: {
allNodes,
edges,
clusterSize,
},
adapters: COMPARISON_ADAPTERS,
};
}
/**
* Clear map cache
*/
export function clearCache() {
cache.clear();
}