Files
OpenFrontIO/tests/pathfinding/utils.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

274 lines
8.0 KiB
TypeScript

import fs from "fs";
import path, { dirname } from "path";
import { fileURLToPath } from "url";
import {
Difficulty,
Game,
GameMapSize,
GameMapType,
GameMode,
GameType,
PlayerInfo,
} from "../../src/core/game/Game";
import { createGame } from "../../src/core/game/GameImpl";
import { TileRef } from "../../src/core/game/GameMap";
import {
genTerrainFromBin,
MapManifest,
} from "../../src/core/game/TerrainMapLoader";
import { UserSettings } from "../../src/core/game/UserSettings";
import { AStarWater } from "../../src/core/pathfinding/algorithms/AStar.Water";
import { AStarWaterHierarchical } from "../../src/core/pathfinding/algorithms/AStar.WaterHierarchical";
import { PathFinding } from "../../src/core/pathfinding/PathFinder";
import { PathFinderBuilder } from "../../src/core/pathfinding/PathFinderBuilder";
import { StepperConfig } from "../../src/core/pathfinding/PathFinderStepper";
import { MiniMapTransformer } from "../../src/core/pathfinding/transformers/MiniMapTransformer";
import {
PathStatus,
SteppingPathFinder,
} from "../../src/core/pathfinding/types";
import { GameConfig } from "../../src/core/Schemas";
import { TestConfig } from "../util/TestConfig";
export type BenchmarkRoute = {
name: string;
from: TileRef;
to: TileRef;
};
export type BenchmarkResult = {
route: string;
executionTime: number | null;
pathLength: number | null;
};
export type BenchmarkSummary = {
totalRoutes: number;
successfulRoutes: number;
timedRoutes: number;
totalDistance: number;
totalTime: number;
avgTime: number;
};
function tileStepperConfig(game: Game): StepperConfig<TileRef> {
return {
equals: (a, b) => a === b,
distance: (a, b) => game.manhattanDist(a, b),
preCheck: (from, to) =>
typeof from !== "number" ||
typeof to !== "number" ||
!game.isValidRef(from) ||
!game.isValidRef(to)
? { status: PathStatus.NOT_FOUND }
: null,
};
}
export function getAdapter(
game: Game,
name: string,
): SteppingPathFinder<TileRef> {
switch (name) {
case "a.baseline": {
return PathFinderBuilder.create(new AStarWater(game.miniMap()))
.wrap((pf) => new MiniMapTransformer(pf, game, game.miniMap()))
.buildWithStepper(tileStepperConfig(game));
}
case "a.generic": {
// Same as baseline - uses AStarWater on minimap
return PathFinderBuilder.create(new AStarWater(game.miniMap()))
.wrap((pf) => new MiniMapTransformer(pf, game, game.miniMap()))
.buildWithStepper(tileStepperConfig(game));
}
case "a.full": {
return PathFinderBuilder.create(
new AStarWater(game.map()),
).buildWithStepper(tileStepperConfig(game));
}
case "hpa": {
// Recreate AStarWaterHierarchical without cache, this approach was chosen
// over adding cache toggles to the existing game instance
// to avoid adding side effect from benchmark to the game
const graph = game.miniWaterGraph();
if (!graph) {
throw new Error("miniWaterGraph not available");
}
const hpa = new AStarWaterHierarchical(game.miniMap(), graph, {
cachePaths: false,
});
(game as any)._miniWaterHPA = hpa;
return PathFinding.Water(game);
}
case "hpa.cached":
return PathFinding.Water(game);
default:
throw new Error(`Unknown pathfinding adapter: ${name}`);
}
}
export async function getScenario(
scenarioName: string,
adapterName: string = "hpa",
) {
const scenario = await import(`./benchmark/scenarios/${scenarioName}.js`);
const enableNavMesh = adapterName.startsWith("hpa");
// Time game creation (includes NavMesh initialization for default adapter)
const start = performance.now();
const currentDir = dirname(fileURLToPath(import.meta.url));
const projectRoot = path.join(currentDir, "../..");
const mapsDirectory = path.join(projectRoot, "resources/maps");
const game = await setupFromPath(mapsDirectory, scenario.MAP_NAME, {
disableNavMesh: !enableNavMesh,
});
const initTime = performance.now() - start;
const routes = scenario.ROUTES.map(([fromName, toName]: [string, string]) => {
const fromCoord: [number, number] = scenario.PORTS[fromName];
const toCoord: [number, number] = scenario.PORTS[toName];
return {
name: `${fromName}${toName}`,
from: game.ref(fromCoord[0], fromCoord[1]),
to: game.ref(toCoord[0], toCoord[1]),
};
});
return {
game,
routes,
initTime,
};
}
export function measurePathLength(
adapter: SteppingPathFinder<TileRef>,
route: BenchmarkRoute,
): number | null {
const path = adapter.findPath(route.from, route.to);
return path ? path.length : null;
}
export function measureTime<T>(fn: () => T): { result: T; time: number } {
const start = performance.now();
const result = fn();
const end = performance.now();
return { result, time: end - start };
}
export function measureExecutionTime(
adapter: SteppingPathFinder<TileRef>,
route: BenchmarkRoute,
executions: number = 1,
): number | null {
const { time } = measureTime(() => {
for (let i = 0; i < executions; i++) {
adapter.findPath(route.from, route.to);
}
});
return time / executions;
}
export function calculateStats(results: BenchmarkResult[]): BenchmarkSummary {
const successful = results.filter((r) => r.pathLength !== null);
const timed = results.filter((r) => r.executionTime !== null);
const totalDistance = successful.reduce((sum, r) => sum + r.pathLength!, 0);
const totalTime = timed.reduce((sum, r) => sum + r.executionTime!, 0);
const avgTime = timed.length > 0 ? totalTime / timed.length : 0;
return {
totalRoutes: results.length,
successfulRoutes: successful.length,
timedRoutes: timed.length,
totalDistance,
totalTime,
avgTime,
};
}
export function printRow(columns: (string | number)[], widths: number[]): void {
const formatted = columns.map((col, i) => {
const str = typeof col === "number" ? col.toString() : col;
return str.padEnd(widths[i]);
});
console.log(formatted.join(" "));
}
export function printSeparator(width: number = 80): void {
console.log("-".repeat(width));
}
export function printHeader(title: string, width: number = 80): void {
printSeparator(width);
console.log(title);
printSeparator(width);
console.log("");
}
export async function setupFromPath(
mapDirectory: string,
mapName: string,
gameConfig: Partial<GameConfig> = {},
humans: PlayerInfo[] = [],
): Promise<Game> {
// Suppress console.debug for tests
console.debug = () => {};
// Load map files from specified directory
const mapBinPath = path.join(mapDirectory, mapName, "map.bin");
const miniMapBinPath = path.join(mapDirectory, mapName, "map4x.bin");
const manifestPath = path.join(mapDirectory, mapName, "manifest.json");
// Check if files exist
if (!fs.existsSync(mapBinPath)) {
throw new Error(`Map not found: ${mapBinPath}`);
}
if (!fs.existsSync(miniMapBinPath)) {
throw new Error(`Mini map not found: ${miniMapBinPath}`);
}
if (!fs.existsSync(manifestPath)) {
throw new Error(`Manifest not found: ${manifestPath}`);
}
const mapBinBuffer = fs.readFileSync(mapBinPath);
const miniMapBinBuffer = fs.readFileSync(miniMapBinPath);
const manifest = JSON.parse(
fs.readFileSync(manifestPath, "utf8"),
) satisfies MapManifest;
const gameMap = await genTerrainFromBin(manifest.map, mapBinBuffer);
const miniGameMap = await genTerrainFromBin(manifest.map4x, miniMapBinBuffer);
// Configure the game
const config = new TestConfig(
new (await import("../util/TestServerConfig")).TestServerConfig(),
{
gameMap: GameMapType.Asia,
gameMapSize: GameMapSize.Normal,
gameMode: GameMode.FFA,
gameType: GameType.Singleplayer,
difficulty: Difficulty.Medium,
disableNations: false,
donateGold: false,
donateTroops: false,
bots: 0,
infiniteGold: false,
infiniteTroops: false,
instantBuild: false,
randomSpawn: false,
...gameConfig,
},
new UserSettings(),
false,
);
return createGame(humans, [], gameMap, miniGameMap, config);
}