BlueGit

timfa questward

Scale A* heuristic by minStepCost so cheap paths win.

Manhattan assumed cost 1 per tile, so path step costs below 1 made the heuristic inadmissible and A* returned short grass routes instead of roads. Prefer-paths pathfinding now passes PATH_GROUND_STEP_COST as the floor.

timfa Tim Falken · pushed by timfa

Authored 2026-09-01 · 2 months ago

Hash
b8a5a26cd81d5eb84a514806802ddfea3d00d5a6
Parent
b4e0ef6a
4 files changed +49 −6
server/src/navigation/astar.js +9 −4
@@ -131,11 +131,14 @@ export function orderedCardinals (fromX, fromY, goalX, goalY, axisTiePreferVerti
131 131 * @param {object} [options]
132 132 * @param {boolean} [options.preferVertical] axis-tie break only: players vertical, mobs horizontal
133 133 * @param {(x: number, y: number) => number} [options.stepCost] movement cost into a tile (default 1)
134 * @param {number} [options.minStepCost] lowest possible stepCost (default 1). Required for
135 * admissible heuristics when some tiles cost less than 1 (e.g. path preference).
134 136 */
135 137 export function findPath (startX, startY, goalX, goalY, isWalkable, minX, minY, maxX, maxY, options = {})
136 138 {
137 139 const axisTiePreferVertical = !!options.preferVertical;
138 140 const stepCost = typeof options.stepCost === "function" ? options.stepCost : null;
141 const minStepCost = Math.max(0.001, Number(options.minStepCost) || 1);
139 142 if (!isWalkable(goalX, goalY) || !isWalkable(startX, startY))
140 143 { return []; }
141 144
@@ -152,6 +155,8 @@ export function findPath (startX, startY, goalX, goalY, isWalkable, minX, minY,
152 155 return (y - minY) * width + (x - minX);
153 156 }
154 157
158 const heuristic = (x, y) => (Math.abs(goalX - x) + Math.abs(goalY - y)) * minStepCost;
159
155 160 const inBounds = (x, y) => x >= minX && y >= minY && x <= maxX && y <= maxY;
156 161 const cameFrom = new Int32Array(width * height).fill(-1);
157 162 const gScore = new Float64Array(width * height).fill(Infinity);
@@ -160,7 +165,7 @@ export function findPath (startX, startY, goalX, goalY, isWalkable, minX, minY,
160 165 gScore[startIndex] = 0;
161 166
162 167 const open = new MinHeap();
163 open.push({ x: startX, y: startY, f: Math.abs(goalX - startX) + Math.abs(goalY - startY) });
168 open.push({ x: startX, y: startY, f: heuristic(startX, startY) });
164 169
165 170 while (open.size > 0)
166 171 {
@@ -194,17 +199,17 @@ export function findPath (startX, startY, goalX, goalY, isWalkable, minX, minY,
194 199 if (closed[neighborIndex])
195 200 { continue; }
196 201
197 const cost = stepCost ? Math.max(0.001, Number(stepCost(nx, ny)) || 1) : 1;
202 const cost = stepCost ? Math.max(minStepCost, Number(stepCost(nx, ny)) || 1) : 1;
198 203 const tentative = gScore[currentIndex] + cost;
199 204 if (tentative >= gScore[neighborIndex])
200 205 { continue; }
201 206
202 207 cameFrom[neighborIndex] = currentIndex;
203 208 gScore[neighborIndex] = tentative;
204 const h = Math.abs(goalX - nx) + Math.abs(goalY - ny);
209 const h = heuristic(nx, ny);
205 210 const stepIsVertical = dir.y !== 0;
206 211 const preferredStep = preferVertical ? stepIsVertical : !stepIsVertical;
207 const bias = preferredStep ? 0 : AXIS_TIE_BIAS;
212 const bias = preferredStep ? 0 : AXIS_TIE_BIAS * minStepCost;
208 213 open.push({ x: nx, y: ny, f: tentative + h + bias });
209 214 }
210 215 }
@@ -131,11 +131,14 @@ export function orderedCardinals (fromX, fromY, goalX, goalY, axisTiePreferVerti
131 * @param {object} [options]
131 * @param {object} [options]
132 * @param {boolean} [options.preferVertical] axis-tie break only: players vertical, mobs horizontal
132 * @param {boolean} [options.preferVertical] axis-tie break only: players vertical, mobs horizontal
133 * @param {(x: number, y: number) => number} [options.stepCost] movement cost into a tile (default 1)
133 * @param {(x: number, y: number) => number} [options.stepCost] movement cost into a tile (default 1)
134 * @param {number} [options.minStepCost] lowest possible stepCost (default 1). Required for
135 * admissible heuristics when some tiles cost less than 1 (e.g. path preference).
134 */
136 */
135export function findPath (startX, startY, goalX, goalY, isWalkable, minX, minY, maxX, maxY, options = {})
137export function findPath (startX, startY, goalX, goalY, isWalkable, minX, minY, maxX, maxY, options = {})
136{
138{
137 const axisTiePreferVertical = !!options.preferVertical;
139 const axisTiePreferVertical = !!options.preferVertical;
138 const stepCost = typeof options.stepCost === "function" ? options.stepCost : null;
140 const stepCost = typeof options.stepCost === "function" ? options.stepCost : null;
141 const minStepCost = Math.max(0.001, Number(options.minStepCost) || 1);
139 if (!isWalkable(goalX, goalY) || !isWalkable(startX, startY))
142 if (!isWalkable(goalX, goalY) || !isWalkable(startX, startY))
140 { return []; }
143 { return []; }
141
144
@@ -152,6 +155,8 @@ export function findPath (startX, startY, goalX, goalY, isWalkable, minX, minY,
152 return (y - minY) * width + (x - minX);
155 return (y - minY) * width + (x - minX);
153 }
156 }
154
157
158 const heuristic = (x, y) => (Math.abs(goalX - x) + Math.abs(goalY - y)) * minStepCost;
159
155 const inBounds = (x, y) => x >= minX && y >= minY && x <= maxX && y <= maxY;
160 const inBounds = (x, y) => x >= minX && y >= minY && x <= maxX && y <= maxY;
156 const cameFrom = new Int32Array(width * height).fill(-1);
161 const cameFrom = new Int32Array(width * height).fill(-1);
157 const gScore = new Float64Array(width * height).fill(Infinity);
162 const gScore = new Float64Array(width * height).fill(Infinity);
@@ -160,7 +165,7 @@ export function findPath (startX, startY, goalX, goalY, isWalkable, minX, minY,
160 gScore[startIndex] = 0;
165 gScore[startIndex] = 0;
161
166
162 const open = new MinHeap();
167 const open = new MinHeap();
163 open.push({ x: startX, y: startY, f: Math.abs(goalX - startX) + Math.abs(goalY - startY) });
168 open.push({ x: startX, y: startY, f: heuristic(startX, startY) });
164
169
165 while (open.size > 0)
170 while (open.size > 0)
166 {
171 {
@@ -194,17 +199,17 @@ export function findPath (startX, startY, goalX, goalY, isWalkable, minX, minY,
194 if (closed[neighborIndex])
199 if (closed[neighborIndex])
195 { continue; }
200 { continue; }
196
201
197 const cost = stepCost ? Math.max(0.001, Number(stepCost(nx, ny)) || 1) : 1;
202 const cost = stepCost ? Math.max(minStepCost, Number(stepCost(nx, ny)) || 1) : 1;
198 const tentative = gScore[currentIndex] + cost;
203 const tentative = gScore[currentIndex] + cost;
199 if (tentative >= gScore[neighborIndex])
204 if (tentative >= gScore[neighborIndex])
200 { continue; }
205 { continue; }
201
206
202 cameFrom[neighborIndex] = currentIndex;
207 cameFrom[neighborIndex] = currentIndex;
203 gScore[neighborIndex] = tentative;
208 gScore[neighborIndex] = tentative;
204 const h = Math.abs(goalX - nx) + Math.abs(goalY - ny);
209 const h = heuristic(nx, ny);
205 const stepIsVertical = dir.y !== 0;
210 const stepIsVertical = dir.y !== 0;
206 const preferredStep = preferVertical ? stepIsVertical : !stepIsVertical;
211 const preferredStep = preferVertical ? stepIsVertical : !stepIsVertical;
207 const bias = preferredStep ? 0 : AXIS_TIE_BIAS;
212 const bias = preferredStep ? 0 : AXIS_TIE_BIAS * minStepCost;
208 open.push({ x: nx, y: ny, f: tentative + h + bias });
213 open.push({ x: nx, y: ny, f: tentative + h + bias });
209 }
214 }
210 }
215 }
server/src/simulation/workerWorld.js +2 −1
@@ -75,7 +75,7 @@ import {
75 75 staminaCostPerRunStep,
76 76 publicStaminaView
77 77 } from "../../../shared/stamina/rules.js";
78 import { stepCostForGround } from "../../../shared/navigation/pathGround.js";
78 import { stepCostForGround, PATH_GROUND_STEP_COST } from "../../../shared/navigation/pathGround.js";
79 79 import { GroundType, normalizeGround } from "../../../shared/definitions/tiles.js";
80 80 import { clearFollow, setFollow, stepFollow, recordFollowTrail, consumeFollowTrail } from "./follow.js";
81 81 import { ensureFlightComponent, stepFreeFlight } from "./freeFlight.js";
@@ -2110,6 +2110,7 @@ export class WorkerWorld
2110 2110 if (preferPaths)
2111 2111 {
2112 2112 options.stepCost = (x, y) => stepCostForGround(this.groundTypeAt(x, y), { preferPaths: true });
2113 options.minStepCost = PATH_GROUND_STEP_COST;
2113 2114 }
2114 2115 return options;
2115 2116 }
@@ -75,7 +75,7 @@ import {
75 staminaCostPerRunStep,
75 staminaCostPerRunStep,
76 publicStaminaView
76 publicStaminaView
77} from "../../../shared/stamina/rules.js";
77} from "../../../shared/stamina/rules.js";
78import { stepCostForGround } from "../../../shared/navigation/pathGround.js";
78import { stepCostForGround, PATH_GROUND_STEP_COST } from "../../../shared/navigation/pathGround.js";
79import { GroundType, normalizeGround } from "../../../shared/definitions/tiles.js";
79import { GroundType, normalizeGround } from "../../../shared/definitions/tiles.js";
80import { clearFollow, setFollow, stepFollow, recordFollowTrail, consumeFollowTrail } from "./follow.js";
80import { clearFollow, setFollow, stepFollow, recordFollowTrail, consumeFollowTrail } from "./follow.js";
81import { ensureFlightComponent, stepFreeFlight } from "./freeFlight.js";
81import { ensureFlightComponent, stepFreeFlight } from "./freeFlight.js";
@@ -2110,6 +2110,7 @@ export class WorkerWorld
2110 if (preferPaths)
2110 if (preferPaths)
2111 {
2111 {
2112 options.stepCost = (x, y) => stepCostForGround(this.groundTypeAt(x, y), { preferPaths: true });
2112 options.stepCost = (x, y) => stepCostForGround(this.groundTypeAt(x, y), { preferPaths: true });
2113 options.minStepCost = PATH_GROUND_STEP_COST;
2113 }
2114 }
2114 return options;
2115 return options;
2115 }
2116 }
server/tests/astar.test.js +37 −0
@@ -91,6 +91,7 @@ test("A* path-ground stepCost prefers a road of equal Manhattan length", () =>
91 91 4,
92 92 {
93 93 preferVertical: false,
94 minStepCost: PATH_GROUND_STEP_COST,
94 95 stepCost: (x, y) => stepCostForGround(
95 96 pathTiles.has(`${x},${y}`) ? GroundType.path : GroundType.grass,
96 97 { preferPaths: true }
@@ -100,3 +101,39 @@ test("A* path-ground stepCost prefers a road of equal Manhattan length", () =>
100 101 assert.ok(route.some((step) => step.x === 1 && step.y === 0), JSON.stringify(route));
101 102 assert.ok(PATH_GROUND_STEP_COST < 1);
102 103 });
104
105 test("A* with cheap paths takes a short detour onto the road", () =>
106 {
107 // Player above middle of top bar; vertical road on the right; goal middle of bottom.
108 // Straight down is 12 grass steps; via road is +2 tiles but much cheaper at 0.1/step.
109 const pathTiles = new Set();
110 for (let x = 0; x <= 2; x++)
111 { pathTiles.add(`${x},1`); }
112 for (let y = 2; y <= 11; y++)
113 { pathTiles.add(`2,${y}`); }
114 for (let x = 0; x <= 2; x++)
115 { pathTiles.add(`${x},12`); }
116
117 const route = findPath(
118 1,
119 0,
120 1,
121 12,
122 () => true,
123 -2,
124 -2,
125 20,
126 20,
127 {
128 preferVertical: true,
129 minStepCost: PATH_GROUND_STEP_COST,
130 stepCost: (x, y) => stepCostForGround(
131 pathTiles.has(`${x},${y}`) ? GroundType.path : GroundType.grass,
132 { preferPaths: true }
133 )
134 }
135 );
136 const onRoad = route.filter((step) => pathTiles.has(`${step.x},${step.y}`));
137 assert.ok(onRoad.length >= 10, `expected mostly road, got ${JSON.stringify(route)}`);
138 assert.ok(route.some((step) => step.x === 2), "should use the vertical road column");
139 });
@@ -91,6 +91,7 @@ test("A* path-ground stepCost prefers a road of equal Manhattan length", () =>
91 4,
91 4,
92 {
92 {
93 preferVertical: false,
93 preferVertical: false,
94 minStepCost: PATH_GROUND_STEP_COST,
94 stepCost: (x, y) => stepCostForGround(
95 stepCost: (x, y) => stepCostForGround(
95 pathTiles.has(`${x},${y}`) ? GroundType.path : GroundType.grass,
96 pathTiles.has(`${x},${y}`) ? GroundType.path : GroundType.grass,
96 { preferPaths: true }
97 { preferPaths: true }
@@ -100,3 +101,39 @@ test("A* path-ground stepCost prefers a road of equal Manhattan length", () =>
100 assert.ok(route.some((step) => step.x === 1 && step.y === 0), JSON.stringify(route));
101 assert.ok(route.some((step) => step.x === 1 && step.y === 0), JSON.stringify(route));
101 assert.ok(PATH_GROUND_STEP_COST < 1);
102 assert.ok(PATH_GROUND_STEP_COST < 1);
102});
103});
104
105test("A* with cheap paths takes a short detour onto the road", () =>
106{
107 // Player above middle of top bar; vertical road on the right; goal middle of bottom.
108 // Straight down is 12 grass steps; via road is +2 tiles but much cheaper at 0.1/step.
109 const pathTiles = new Set();
110 for (let x = 0; x <= 2; x++)
111 { pathTiles.add(`${x},1`); }
112 for (let y = 2; y <= 11; y++)
113 { pathTiles.add(`2,${y}`); }
114 for (let x = 0; x <= 2; x++)
115 { pathTiles.add(`${x},12`); }
116
117 const route = findPath(
118 1,
119 0,
120 1,
121 12,
122 () => true,
123 -2,
124 -2,
125 20,
126 20,
127 {
128 preferVertical: true,
129 minStepCost: PATH_GROUND_STEP_COST,
130 stepCost: (x, y) => stepCostForGround(
131 pathTiles.has(`${x},${y}`) ? GroundType.path : GroundType.grass,
132 { preferPaths: true }
133 )
134 }
135 );
136 const onRoad = route.filter((step) => pathTiles.has(`${step.x},${step.y}`));
137 assert.ok(onRoad.length >= 10, `expected mostly road, got ${JSON.stringify(route)}`);
138 assert.ok(route.some((step) => step.x === 2), "should use the vertical road column");
139});
shared/navigation/pathGround.js +1 −1
@@ -5,7 +5,7 @@ import { GroundType, groundDefinition } from "../definitions/tiles.js";
5 5 * Slightly cheaper than grass so equal-ish routes favour the path without
6 6 * accepting long detours.
7 7 */
8 export const PATH_GROUND_STEP_COST = 0.10;
8 export const PATH_GROUND_STEP_COST = 0.70;
9 9
10 10 export function isPathGround (typeId)
11 11 {
@@ -5,7 +5,7 @@ import { GroundType, groundDefinition } from "../definitions/tiles.js";
5 * Slightly cheaper than grass so equal-ish routes favour the path without
5 * Slightly cheaper than grass so equal-ish routes favour the path without
6 * accepting long detours.
6 * accepting long detours.
7 */
7 */
8export const PATH_GROUND_STEP_COST = 0.10;
8export const PATH_GROUND_STEP_COST = 0.70;
9
9
10export function isPathGround (typeId)
10export function isPathGround (typeId)
11{
11{