mirror of
https://github.com/openfrontio/OpenFrontIO.git
synced 2026-07-14 17:46:45 +00:00
create async path finder, trade ships use async when captured
This commit is contained in:
+27
-136
@@ -1,138 +1,29 @@
|
||||
import { PriorityQueue } from "@datastructures-js/priority-queue";
|
||||
import { SearchNode } from "../game/Game";
|
||||
import { PathFindResultType } from "./PathFinding";
|
||||
import { Cell, Tile } from "../game/Game";
|
||||
|
||||
|
||||
export class AStar {
|
||||
private fwdOpenSet: PriorityQueue<{ tile: SearchNode; fScore: number; }>;
|
||||
private bwdOpenSet: PriorityQueue<{ tile: SearchNode; fScore: number; }>;
|
||||
private fwdCameFrom: Map<SearchNode, SearchNode>;
|
||||
private bwdCameFrom: Map<SearchNode, SearchNode>;
|
||||
private fwdGScore: Map<SearchNode, number>;
|
||||
private bwdGScore: Map<SearchNode, number>;
|
||||
private meetingPoint: SearchNode | null;
|
||||
public completed: boolean;
|
||||
|
||||
constructor(
|
||||
private src: SearchNode,
|
||||
private dst: SearchNode,
|
||||
private canMove: (t: SearchNode) => boolean,
|
||||
private neighbors: (sn: SearchNode) => SearchNode[],
|
||||
private iterations: number,
|
||||
private maxTries: number
|
||||
) {
|
||||
this.fwdOpenSet = new PriorityQueue<{ tile: SearchNode; fScore: number; }>(
|
||||
(a, b) => a.fScore - b.fScore
|
||||
);
|
||||
this.bwdOpenSet = new PriorityQueue<{ tile: SearchNode; fScore: number; }>(
|
||||
(a, b) => a.fScore - b.fScore
|
||||
);
|
||||
this.fwdCameFrom = new Map<SearchNode, SearchNode>();
|
||||
this.bwdCameFrom = new Map<SearchNode, SearchNode>();
|
||||
this.fwdGScore = new Map<SearchNode, number>();
|
||||
this.bwdGScore = new Map<SearchNode, number>();
|
||||
this.meetingPoint = null;
|
||||
this.completed = false;
|
||||
|
||||
// Initialize forward search
|
||||
this.fwdGScore.set(src, 0);
|
||||
this.fwdOpenSet.enqueue({ tile: src, fScore: this.heuristic(src, dst) });
|
||||
|
||||
// Initialize backward search
|
||||
this.bwdGScore.set(dst, 0);
|
||||
this.bwdOpenSet.enqueue({ tile: dst, fScore: this.heuristic(dst, src) });
|
||||
}
|
||||
|
||||
compute(): PathFindResultType {
|
||||
if (this.completed) return PathFindResultType.Completed;
|
||||
|
||||
this.maxTries -= 1;
|
||||
let iterations = this.iterations;
|
||||
|
||||
while (!this.fwdOpenSet.isEmpty() && !this.bwdOpenSet.isEmpty()) {
|
||||
iterations--;
|
||||
if (iterations <= 0) {
|
||||
if (this.maxTries <= 0) {
|
||||
return PathFindResultType.PathNotFound;
|
||||
}
|
||||
return PathFindResultType.Pending;
|
||||
}
|
||||
|
||||
// Process forward search
|
||||
const fwdCurrent = this.fwdOpenSet.dequeue()!.tile;
|
||||
if (this.bwdGScore.has(fwdCurrent)) {
|
||||
// We found a meeting point!
|
||||
this.meetingPoint = fwdCurrent;
|
||||
this.completed = true;
|
||||
return PathFindResultType.Completed;
|
||||
}
|
||||
|
||||
this.expandSearchNode(fwdCurrent, true);
|
||||
|
||||
// Process backward search
|
||||
const bwdCurrent = this.bwdOpenSet.dequeue()!.tile;
|
||||
if (this.fwdGScore.has(bwdCurrent)) {
|
||||
// We found a meeting point!
|
||||
this.meetingPoint = bwdCurrent;
|
||||
this.completed = true;
|
||||
return PathFindResultType.Completed;
|
||||
}
|
||||
|
||||
this.expandSearchNode(bwdCurrent, false);
|
||||
}
|
||||
|
||||
return this.completed ? PathFindResultType.Completed : PathFindResultType.PathNotFound;
|
||||
}
|
||||
|
||||
private expandSearchNode(current: SearchNode, isForward: boolean) {
|
||||
for (const neighbor of this.neighbors(current)) {
|
||||
if (neighbor !== (isForward ? this.dst : this.src) && !this.canMove(neighbor)) continue;
|
||||
|
||||
const gScore = isForward ? this.fwdGScore : this.bwdGScore;
|
||||
const openSet = isForward ? this.fwdOpenSet : this.bwdOpenSet;
|
||||
const cameFrom = isForward ? this.fwdCameFrom : this.bwdCameFrom;
|
||||
|
||||
let tentativeGScore = gScore.get(current)! + neighbor.cost();
|
||||
|
||||
if (!gScore.has(neighbor) || tentativeGScore < gScore.get(neighbor)!) {
|
||||
cameFrom.set(neighbor, current);
|
||||
gScore.set(neighbor, tentativeGScore);
|
||||
const fScore = tentativeGScore + this.heuristic(
|
||||
neighbor,
|
||||
isForward ? this.dst : this.src
|
||||
);
|
||||
openSet.enqueue({ tile: neighbor, fScore: fScore });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private heuristic(a: SearchNode, b: SearchNode): number {
|
||||
// TODO use wrapped
|
||||
try {
|
||||
return 1.1 * Math.abs(a.cell().x - b.cell().x) + Math.abs(a.cell().y - b.cell().y);
|
||||
} catch {
|
||||
console.log('uh oh')
|
||||
}
|
||||
}
|
||||
|
||||
public reconstructPath(): SearchNode[] {
|
||||
if (!this.meetingPoint) return [];
|
||||
|
||||
// Reconstruct path from start to meeting point
|
||||
const fwdPath: SearchNode[] = [this.meetingPoint];
|
||||
let current = this.meetingPoint;
|
||||
while (this.fwdCameFrom.has(current)) {
|
||||
current = this.fwdCameFrom.get(current)!;
|
||||
fwdPath.unshift(current);
|
||||
}
|
||||
|
||||
// Reconstruct path from meeting point to goal
|
||||
current = this.meetingPoint;
|
||||
while (this.bwdCameFrom.has(current)) {
|
||||
current = this.bwdCameFrom.get(current)!;
|
||||
fwdPath.push(current);
|
||||
}
|
||||
|
||||
return fwdPath;
|
||||
}
|
||||
export interface AStar {
|
||||
compute(): PathFindResultType
|
||||
reconstructPath(): SearchNode[]
|
||||
}
|
||||
|
||||
export enum PathFindResultType {
|
||||
NextTile,
|
||||
Pending,
|
||||
Completed,
|
||||
PathNotFound
|
||||
} export type TileResult = {
|
||||
type: PathFindResultType.NextTile;
|
||||
tile: Tile;
|
||||
} | {
|
||||
type: PathFindResultType.Pending;
|
||||
} | {
|
||||
type: PathFindResultType.Completed;
|
||||
tile: Tile;
|
||||
} | {
|
||||
type: PathFindResultType.PathNotFound;
|
||||
};
|
||||
|
||||
export interface SearchNode {
|
||||
cost(): number
|
||||
cell(): Cell
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { TerrainTile, Tile, Game, GameMap, Cell } from "../game/Game";
|
||||
import { PathFindResultType } from "./PathFinding";
|
||||
import { AStar, PathFindResultType } from "./AStar";
|
||||
|
||||
export class AsyncPathFinderCreator {
|
||||
private worker: Worker;
|
||||
@@ -33,11 +33,11 @@ export class AsyncPathFinderCreator {
|
||||
});
|
||||
}
|
||||
|
||||
createPathFinder(src: Tile, dst: Tile, numTicks: number): AsyncPathFinder {
|
||||
createParallelAStar(src: Tile, dst: Tile, numTicks: number): ParallelAStar {
|
||||
if (!this.isInitialized) {
|
||||
throw new Error('PathFinder not initialized');
|
||||
}
|
||||
return new AsyncPathFinder(this.game, this.worker, src, dst, numTicks);
|
||||
return new ParallelAStar(this.game, this.worker, src, dst, numTicks);
|
||||
}
|
||||
|
||||
cleanup() {
|
||||
@@ -45,8 +45,7 @@ export class AsyncPathFinderCreator {
|
||||
}
|
||||
}
|
||||
|
||||
// AsyncPathFinder.ts
|
||||
export class AsyncPathFinder {
|
||||
export class ParallelAStar implements AStar {
|
||||
private path: Tile[] | 'NOT_FOUND' | null = null;
|
||||
private promise: Promise<void>;
|
||||
|
||||
@@ -59,18 +58,24 @@ export class AsyncPathFinder {
|
||||
) { }
|
||||
|
||||
findPath(): Promise<void> {
|
||||
const requestId = crypto.randomUUID()
|
||||
this.promise = new Promise((resolve, reject) => {
|
||||
const timeout = setTimeout(() => {
|
||||
reject("Path timeout");
|
||||
}, 100_000);
|
||||
|
||||
const handler = (e: MessageEvent) => {
|
||||
if (e.data.requestId != requestId) {
|
||||
return
|
||||
}
|
||||
clearTimeout(timeout);
|
||||
this.worker.removeEventListener('message', handler);
|
||||
|
||||
if (e.data.type === 'pathFound') {
|
||||
this.path = e.data.path.map(pos => this.game.tile(new Cell(pos.x, pos.y)));
|
||||
resolve();
|
||||
} else if (e.data.type === 'pathNotFound') {
|
||||
this.path = 'NOT_FOUND'
|
||||
} else {
|
||||
reject(e.data.reason || "Path not found");
|
||||
}
|
||||
@@ -79,7 +84,7 @@ export class AsyncPathFinder {
|
||||
this.worker.addEventListener('message', handler);
|
||||
this.worker.postMessage({
|
||||
type: 'findPath',
|
||||
requestId: crypto.randomUUID(),
|
||||
requestId: requestId,
|
||||
currentTick: this.game.ticks(),
|
||||
duration: this.numTicks,
|
||||
start: { x: this.src.cell().x, y: this.src.cell().y },
|
||||
@@ -97,14 +102,11 @@ export class AsyncPathFinder {
|
||||
}
|
||||
this.numTicks--;
|
||||
if (this.numTicks <= 0) {
|
||||
for (let i = 0; i < 1_000_000; i++) {
|
||||
if (this.path == 'NOT_FOUND') {
|
||||
return PathFindResultType.PathNotFound
|
||||
}
|
||||
if (this.path != null) {
|
||||
console.log('in Asyncclient: found a path!!')
|
||||
return PathFindResultType.Completed;
|
||||
}
|
||||
if (this.path == 'NOT_FOUND') {
|
||||
return PathFindResultType.PathNotFound
|
||||
}
|
||||
if (this.path != null) {
|
||||
return PathFindResultType.Completed;
|
||||
}
|
||||
throw new Error(`path not completed in time`)
|
||||
}
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
// pathfinding.ts
|
||||
import { Cell, GameMap, SearchNode, TerrainMap, TerrainTile, TerrainType } from "../game/Game";
|
||||
import { PathFindResultType } from "./PathFinding";
|
||||
import { AStar } from "./AStar";
|
||||
import { Cell, GameMap, TerrainMap, TerrainTile, TerrainType } from "../game/Game";
|
||||
import { SearchNode } from "./AStar";
|
||||
import { PathFindResultType } from "./AStar";
|
||||
import { SerialAStar } from "./SerialAStar";
|
||||
import { loadTerrainMap } from "../game/TerrainMapLoader";
|
||||
import { PriorityQueue } from "@datastructures-js/priority-queue";
|
||||
|
||||
@@ -12,7 +13,7 @@ let isProcessingSearch = false
|
||||
|
||||
|
||||
interface Search {
|
||||
aStar: AStar,
|
||||
aStar: SerialAStar,
|
||||
deadline: number
|
||||
requestId: string
|
||||
}
|
||||
@@ -40,17 +41,17 @@ self.onmessage = (e) => {
|
||||
function initializeMap(data: { gameMap: GameMap }) {
|
||||
terrainMapPromise = loadTerrainMap(data.gameMap)
|
||||
self.postMessage({ type: 'initialized' });
|
||||
processingInterval = setInterval(computeSearches, .5) as unknown as number;
|
||||
processingInterval = setInterval(computeSearches, .1) as unknown as number;
|
||||
}
|
||||
|
||||
function findPath(terrainMap: TerrainMap, req: SearchRequest) {
|
||||
const aStar = new AStar(
|
||||
const aStar = new SerialAStar(
|
||||
terrainMap.terrain(new Cell(req.start.x, req.start.y)),
|
||||
terrainMap.terrain(new Cell(req.end.x, req.end.y)),
|
||||
(sn: SearchNode) => (sn as TerrainTile).terrainType() == TerrainType.Ocean,
|
||||
(sn: SearchNode): SearchNode[] => terrainMap.neighbors((sn as TerrainTile)),
|
||||
100_000,
|
||||
1000
|
||||
10_000,
|
||||
req.duration,
|
||||
);
|
||||
|
||||
searches.enqueue({
|
||||
@@ -88,7 +89,7 @@ function computeSearches() {
|
||||
case PathFindResultType.PathNotFound:
|
||||
console.warn(`worker: path not found to port`);
|
||||
self.postMessage({
|
||||
type: 'error',
|
||||
type: 'pathNotFound',
|
||||
requestId: search.requestId,
|
||||
});
|
||||
break
|
||||
|
||||
@@ -1,26 +1,8 @@
|
||||
import { Tile } from "../game/Game";
|
||||
import { Game, Tile } from "../game/Game";
|
||||
import { manhattanDist } from "../Util";
|
||||
import { AStar } from "./AStar";
|
||||
|
||||
export enum PathFindResultType {
|
||||
NextTile,
|
||||
Pending,
|
||||
Completed,
|
||||
PathNotFound
|
||||
}
|
||||
|
||||
export type TileResult = {
|
||||
type: PathFindResultType.NextTile;
|
||||
tile: Tile
|
||||
} | {
|
||||
type: PathFindResultType.Pending;
|
||||
} | {
|
||||
type: PathFindResultType.Completed;
|
||||
tile: Tile
|
||||
} | {
|
||||
type: PathFindResultType.PathNotFound;
|
||||
}
|
||||
|
||||
import { AStar, PathFindResultType, TileResult } from "./AStar";
|
||||
import { AsyncPathFinderCreator, ParallelAStar } from "./AsyncPathFinding";
|
||||
import { SerialAStar } from "./SerialAStar";
|
||||
|
||||
export class PathFinder {
|
||||
|
||||
@@ -30,12 +12,31 @@ export class PathFinder {
|
||||
private aStar: AStar
|
||||
private computeFinished = true
|
||||
|
||||
constructor(
|
||||
private iterations: number,
|
||||
private canMove: (t: Tile) => boolean,
|
||||
private maxTries: number = 20
|
||||
private constructor(
|
||||
private newAStar: (curr: Tile, dst: Tile) => AStar
|
||||
) { }
|
||||
|
||||
public static Serial(iterations: number, canMove: (t: Tile) => boolean, maxTries: number = 20): PathFinder {
|
||||
return new PathFinder(
|
||||
(curr: Tile, dst: Tile) => {
|
||||
return new SerialAStar(
|
||||
curr,
|
||||
dst,
|
||||
canMove,
|
||||
sn => ((sn as Tile).neighbors()), iterations, maxTries
|
||||
)
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
public static Parallel(creator: AsyncPathFinderCreator, numTicks: number): PathFinder {
|
||||
return new PathFinder(
|
||||
(curr: Tile, dst: Tile) => {
|
||||
return creator.createParallelAStar(curr, dst, numTicks)
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
nextTile(curr: Tile, dst: Tile, dist: number = 1): TileResult {
|
||||
if (curr == null) {
|
||||
console.error('curr is null')
|
||||
@@ -53,7 +54,7 @@ export class PathFinder {
|
||||
this.curr = curr
|
||||
this.dst = dst
|
||||
this.path = null
|
||||
this.aStar = new AStar(curr, dst, this.canMove, sn => ((sn as Tile).neighbors()), this.iterations, this.maxTries)
|
||||
this.aStar = this.newAStar(curr, dst)
|
||||
this.computeFinished = false
|
||||
return this.nextTile(curr, dst)
|
||||
} else {
|
||||
|
||||
@@ -0,0 +1,138 @@
|
||||
import { PriorityQueue } from "@datastructures-js/priority-queue";
|
||||
import { AStar, SearchNode } from "./AStar";
|
||||
import { PathFindResultType } from "./AStar";
|
||||
|
||||
|
||||
export class SerialAStar implements AStar{
|
||||
private fwdOpenSet: PriorityQueue<{ tile: SearchNode; fScore: number; }>;
|
||||
private bwdOpenSet: PriorityQueue<{ tile: SearchNode; fScore: number; }>;
|
||||
private fwdCameFrom: Map<SearchNode, SearchNode>;
|
||||
private bwdCameFrom: Map<SearchNode, SearchNode>;
|
||||
private fwdGScore: Map<SearchNode, number>;
|
||||
private bwdGScore: Map<SearchNode, number>;
|
||||
private meetingPoint: SearchNode | null;
|
||||
public completed: boolean;
|
||||
|
||||
constructor(
|
||||
private src: SearchNode,
|
||||
private dst: SearchNode,
|
||||
private canMove: (t: SearchNode) => boolean,
|
||||
private neighbors: (sn: SearchNode) => SearchNode[],
|
||||
private iterations: number,
|
||||
private maxTries: number
|
||||
) {
|
||||
this.fwdOpenSet = new PriorityQueue<{ tile: SearchNode; fScore: number; }>(
|
||||
(a, b) => a.fScore - b.fScore
|
||||
);
|
||||
this.bwdOpenSet = new PriorityQueue<{ tile: SearchNode; fScore: number; }>(
|
||||
(a, b) => a.fScore - b.fScore
|
||||
);
|
||||
this.fwdCameFrom = new Map<SearchNode, SearchNode>();
|
||||
this.bwdCameFrom = new Map<SearchNode, SearchNode>();
|
||||
this.fwdGScore = new Map<SearchNode, number>();
|
||||
this.bwdGScore = new Map<SearchNode, number>();
|
||||
this.meetingPoint = null;
|
||||
this.completed = false;
|
||||
|
||||
// Initialize forward search
|
||||
this.fwdGScore.set(src, 0);
|
||||
this.fwdOpenSet.enqueue({ tile: src, fScore: this.heuristic(src, dst) });
|
||||
|
||||
// Initialize backward search
|
||||
this.bwdGScore.set(dst, 0);
|
||||
this.bwdOpenSet.enqueue({ tile: dst, fScore: this.heuristic(dst, src) });
|
||||
}
|
||||
|
||||
compute(): PathFindResultType {
|
||||
if (this.completed) return PathFindResultType.Completed;
|
||||
|
||||
this.maxTries -= 1;
|
||||
let iterations = this.iterations;
|
||||
|
||||
while (!this.fwdOpenSet.isEmpty() && !this.bwdOpenSet.isEmpty()) {
|
||||
iterations--;
|
||||
if (iterations <= 0) {
|
||||
if (this.maxTries <= 0) {
|
||||
return PathFindResultType.PathNotFound;
|
||||
}
|
||||
return PathFindResultType.Pending;
|
||||
}
|
||||
|
||||
// Process forward search
|
||||
const fwdCurrent = this.fwdOpenSet.dequeue()!.tile;
|
||||
if (this.bwdGScore.has(fwdCurrent)) {
|
||||
// We found a meeting point!
|
||||
this.meetingPoint = fwdCurrent;
|
||||
this.completed = true;
|
||||
return PathFindResultType.Completed;
|
||||
}
|
||||
|
||||
this.expandSearchNode(fwdCurrent, true);
|
||||
|
||||
// Process backward search
|
||||
const bwdCurrent = this.bwdOpenSet.dequeue()!.tile;
|
||||
if (this.fwdGScore.has(bwdCurrent)) {
|
||||
// We found a meeting point!
|
||||
this.meetingPoint = bwdCurrent;
|
||||
this.completed = true;
|
||||
return PathFindResultType.Completed;
|
||||
}
|
||||
|
||||
this.expandSearchNode(bwdCurrent, false);
|
||||
}
|
||||
|
||||
return this.completed ? PathFindResultType.Completed : PathFindResultType.PathNotFound;
|
||||
}
|
||||
|
||||
private expandSearchNode(current: SearchNode, isForward: boolean) {
|
||||
for (const neighbor of this.neighbors(current)) {
|
||||
if (neighbor !== (isForward ? this.dst : this.src) && !this.canMove(neighbor)) continue;
|
||||
|
||||
const gScore = isForward ? this.fwdGScore : this.bwdGScore;
|
||||
const openSet = isForward ? this.fwdOpenSet : this.bwdOpenSet;
|
||||
const cameFrom = isForward ? this.fwdCameFrom : this.bwdCameFrom;
|
||||
|
||||
let tentativeGScore = gScore.get(current)! + neighbor.cost();
|
||||
|
||||
if (!gScore.has(neighbor) || tentativeGScore < gScore.get(neighbor)!) {
|
||||
cameFrom.set(neighbor, current);
|
||||
gScore.set(neighbor, tentativeGScore);
|
||||
const fScore = tentativeGScore + this.heuristic(
|
||||
neighbor,
|
||||
isForward ? this.dst : this.src
|
||||
);
|
||||
openSet.enqueue({ tile: neighbor, fScore: fScore });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private heuristic(a: SearchNode, b: SearchNode): number {
|
||||
// TODO use wrapped
|
||||
try {
|
||||
return 1.1 * Math.abs(a.cell().x - b.cell().x) + Math.abs(a.cell().y - b.cell().y);
|
||||
} catch {
|
||||
console.log('uh oh')
|
||||
}
|
||||
}
|
||||
|
||||
public reconstructPath(): SearchNode[] {
|
||||
if (!this.meetingPoint) return [];
|
||||
|
||||
// Reconstruct path from start to meeting point
|
||||
const fwdPath: SearchNode[] = [this.meetingPoint];
|
||||
let current = this.meetingPoint;
|
||||
while (this.fwdCameFrom.has(current)) {
|
||||
current = this.fwdCameFrom.get(current)!;
|
||||
fwdPath.unshift(current);
|
||||
}
|
||||
|
||||
// Reconstruct path from meeting point to goal
|
||||
current = this.meetingPoint;
|
||||
while (this.bwdCameFrom.has(current)) {
|
||||
current = this.bwdCameFrom.get(current)!;
|
||||
fwdPath.push(current);
|
||||
}
|
||||
|
||||
return fwdPath;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user