Files
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

146 lines
4.6 KiB
TypeScript

import { describe, expect, it } from "vitest";
import {
ConnectedComponents,
LAND_MARKER,
} from "../../../src/core/pathfinding/algorithms/ConnectedComponents";
import { createGameMap, createIslandMap, L, W } from "./_fixtures";
// prettier-ignore
const twoComponentsMapData = {
width: 7, height: 5, grid: [
W, W, L, L, L, W, W,
W, W, L, L, L, W, W,
W, W, L, L, L, W, W,
W, W, L, L, L, W, W,
W, W, L, L, L, W, W,
],
};
describe("ConnectedComponents", () => {
describe("getComponentId", () => {
it("returns 0 before initialization", () => {
const map = createGameMap(createIslandMap());
const wc = new ConnectedComponents(map);
// Water tile at (0,0) - should return 0 (not initialized)
const waterTile = map.ref(0, 0);
expect(wc.getComponentId(waterTile)).toBe(0);
});
it("returns same component ID for all water tiles in single connected area", () => {
const map = createGameMap(createIslandMap());
const wc = new ConnectedComponents(map);
wc.initialize();
const water1 = map.ref(0, 0);
const water2 = map.ref(4, 0);
const water3 = map.ref(0, 4);
const water4 = map.ref(4, 4);
expect(map.isWater(water1)).toBe(true);
expect(map.isWater(water2)).toBe(true);
expect(map.isWater(water3)).toBe(true);
expect(map.isWater(water4)).toBe(true);
const id1 = wc.getComponentId(water1);
const id2 = wc.getComponentId(water2);
const id3 = wc.getComponentId(water3);
const id4 = wc.getComponentId(water4);
expect(id1).toBe(1);
expect(id2).toBe(id1);
expect(id3).toBe(id1);
expect(id4).toBe(id1);
});
it("returns different component IDs for disconnected water areas", () => {
const map = createGameMap(twoComponentsMapData);
const wc = new ConnectedComponents(map);
wc.initialize();
const leftWater1 = map.ref(0, 0);
const leftWater2 = map.ref(1, 2);
const rightWater1 = map.ref(5, 0);
const rightWater2 = map.ref(6, 4);
expect(map.isWater(leftWater1)).toBe(true);
expect(map.isWater(leftWater2)).toBe(true);
expect(map.isWater(rightWater1)).toBe(true);
expect(map.isWater(rightWater2)).toBe(true);
const leftId1 = wc.getComponentId(leftWater1);
const leftId2 = wc.getComponentId(leftWater2);
const rightId1 = wc.getComponentId(rightWater1);
const rightId2 = wc.getComponentId(rightWater2);
expect(leftId1).not.toBe(rightId1);
expect(leftId1).toBe(leftId2);
expect(leftId1).toBeGreaterThan(0);
expect(leftId1).not.toBe(LAND_MARKER);
expect(rightId1).toBe(rightId2);
expect(rightId1).toBeGreaterThan(0);
expect(rightId1).not.toBe(LAND_MARKER);
});
it("returns LAND_MARKER for land tiles", () => {
const map = createGameMap(twoComponentsMapData);
const wc = new ConnectedComponents(map);
wc.initialize();
const landTile1 = map.ref(2, 0);
const landTile2 = map.ref(3, 2);
const landTile3 = map.ref(4, 4);
expect(map.isLand(landTile1)).toBe(true);
expect(map.isLand(landTile2)).toBe(true);
expect(map.isLand(landTile3)).toBe(true);
expect(wc.getComponentId(landTile1)).toBe(LAND_MARKER);
expect(wc.getComponentId(landTile2)).toBe(LAND_MARKER);
expect(wc.getComponentId(landTile3)).toBe(LAND_MARKER);
});
});
describe("determinism", () => {
it("produces same component IDs on repeated initialization", () => {
const map = createGameMap(twoComponentsMapData);
const wc1 = new ConnectedComponents(map);
const wc2 = new ConnectedComponents(map);
wc1.initialize();
wc2.initialize();
// Check all tiles have same component ID
for (let y = 0; y < 5; y++) {
for (let x = 0; x < 7; x++) {
const tile = map.ref(x, y);
expect(wc1.getComponentId(tile)).toBe(wc2.getComponentId(tile));
}
}
});
});
describe("direct terrain access optimization", () => {
it("produces same results with accessTerrainDirectly=false", () => {
const map = createGameMap(twoComponentsMapData);
const wcDirect = new ConnectedComponents(map, true);
const wcIndirect = new ConnectedComponents(map, false);
wcDirect.initialize();
wcIndirect.initialize();
// Check all tiles have same component ID
for (let y = 0; y < 5; y++) {
for (let x = 0; x < 7; x++) {
const tile = map.ref(x, y);
expect(wcDirect.getComponentId(tile)).toBe(
wcIndirect.getComponentId(tile),
);
}
}
});
});
});