mirror of
https://github.com/openfrontio/OpenFrontIO.git
synced 2026-06-21 21:34:14 +00:00
85def73bd9
# Pathfinding pt. 3 ## Description: This PR introduces final change to the pathfinding - path refinement. It optimizes Line of Sight refinement by searching with for the best tile with a binary search instead of linearly. And then spends the recovered budget on better refinement of the first and last 50 tiles of the journey - the place where user is most likely to look at. Additionally this PR re-introduces magnitude check and makes the ships prefer sailing close to the coast, but not too close. ## Please complete the following: - [x] I have added screenshots for all UI updates - [x] I process any text displayed to the user through translateText() and I've added it to the en.json file - [x] I have added relevant tests to the test directory - [x] I confirm I have thoroughly tested these changes and take full responsibility for any bugs introduced ## What? | Before | After | | :--- | :--- | | <img width="1097" height="1117" alt="image" src="https://github.com/user-attachments/assets/4a0b300d-10ef-4151-b6dc-33acfb49f992" /> | <img width="1093" height="1119" alt="image" src="https://github.com/user-attachments/assets/cf81c515-c145-40f4-91e5-a4353986907b" /> | | <img width="1096" height="1129" alt="image" src="https://github.com/user-attachments/assets/21b46bce-f961-4259-88f6-fe4a66180270" /> | <img width="1098" height="1126" alt="image" src="https://github.com/user-attachments/assets/d92587d1-e6b6-4353-b4a4-1efe71bca43d" /> | ## Performance There is actually a severe performance impact of these changes. The path initial path takes almost 2x as long to generate - this is because pre processing can only do so much if the initial path is ugly. Luckily in real gameplay we only need to do this calculation once per edge, so the actual observed performance impact should be much smaller. Cache FTW. | | No Cache | Cache | | :--- | :--- | :--- | | Before | 277.04ms | 208.58ms | | After | 498.34ms | 264.27ms | ## DebugSpan Small utility, it allows any code to be easily instrumented for performance. The idea is the same as with [OTEL Spans](https://opentelemetry.io/docs/concepts/signals/traces/). Produce a span, create sub-spans, measure whatever you need. Works only when `globalThis.__DEBUG_SPAN_ENABLED__ === true`, otherwise no-op. Cool stuff, try it out: ```ts // Convenient wrapper, small performance impact return DebugSpan.wrap('add', () => a + b) // Synchronous API, basically free DebugSpan.start('work') work() DebugSpan.end() // Create sub spans DebugSpan.wrap('complex', () => { const aPlusB = DebugSpan.wrap('add', () => a + b) DebugSpan.set('additionResult', () => aPlusB) // Store data return aPlusB * c }) // Access spans, data and timing const span = DebugSpan.getLast() const compelxSpan = DebugSpan.getLast('complex') console.log(complexSpan.duration, complexSpan.data['additionResult']) ``` These are virtually free and can be enabled on-demand **in production** and available in the devtools. Under the hood devtools integration is just a wrapper around [Performance API](https://developer.mozilla.org/en-US/docs/Web/API/Performance_API). For clarity data keys not prefixed by `$` are omitted from the integration. Every key prefixed with `$` must be fully JSON serializable. <img width="977" height="799" alt="image" src="https://github.com/user-attachments/assets/b4d43506-1639-4f78-a611-30e61de12a07" />
198 lines
5.2 KiB
TypeScript
198 lines
5.2 KiB
TypeScript
import compression from "compression";
|
|
import express, { Request, Response } from "express";
|
|
import { dirname, join } from "path";
|
|
import { fileURLToPath } from "url";
|
|
import {
|
|
clearCache as clearMapCache,
|
|
getMapMetadata,
|
|
listMaps,
|
|
} from "./api/maps.js";
|
|
import { clearAdapterCaches, computePath } from "./api/pathfinding.js";
|
|
|
|
const app = express();
|
|
const PORT = process.env.PORT ?? 5555;
|
|
|
|
// Middleware
|
|
app.use(compression()); // gzip compression for large responses
|
|
app.use(express.json({ limit: "50mb" })); // JSON body parser with larger limit
|
|
|
|
// Serve static files from public directory
|
|
const publicDir = join(dirname(fileURLToPath(import.meta.url)), "public");
|
|
app.use(express.static(publicDir));
|
|
|
|
// API Routes
|
|
|
|
/**
|
|
* GET /api/maps
|
|
* List all available maps
|
|
*/
|
|
app.get("/api/maps", (req: Request, res: Response) => {
|
|
try {
|
|
const maps = listMaps();
|
|
res.json({ maps });
|
|
} catch (error) {
|
|
console.error("Error listing maps:", error);
|
|
res.status(500).json({
|
|
error: "Failed to list maps",
|
|
message: error instanceof Error ? error.message : String(error),
|
|
});
|
|
}
|
|
});
|
|
|
|
/**
|
|
* GET /api/maps/:name
|
|
* Get map metadata (map data, dimensions)
|
|
*/
|
|
app.get("/api/maps/:name", async (req: Request, res: Response) => {
|
|
try {
|
|
const { name } = req.params;
|
|
const metadata = await getMapMetadata(name);
|
|
res.json(metadata);
|
|
} catch (error) {
|
|
console.error(`Error loading map ${req.params.name}:`, error);
|
|
|
|
if (error instanceof Error && error.message.includes("ENOENT")) {
|
|
res.status(404).json({
|
|
error: "Map not found",
|
|
message: `Map "${req.params.name}" does not exist`,
|
|
});
|
|
} else {
|
|
res.status(500).json({
|
|
error: "Failed to load map",
|
|
message: error instanceof Error ? error.message : String(error),
|
|
});
|
|
}
|
|
}
|
|
});
|
|
|
|
/**
|
|
* GET /api/maps/:name/thumbnail
|
|
* Get map thumbnail image
|
|
*/
|
|
app.get("/api/maps/:name/thumbnail", (req: Request, res: Response) => {
|
|
try {
|
|
const { name } = req.params;
|
|
const thumbnailPath = join(
|
|
dirname(fileURLToPath(import.meta.url)),
|
|
"../../../resources/maps",
|
|
name,
|
|
"thumbnail.webp",
|
|
);
|
|
res.sendFile(thumbnailPath);
|
|
} catch (error) {
|
|
console.error(`Error loading thumbnail for ${req.params.name}:`, error);
|
|
res.status(404).json({
|
|
error: "Thumbnail not found",
|
|
message: error instanceof Error ? error.message : String(error),
|
|
});
|
|
}
|
|
});
|
|
|
|
/**
|
|
* POST /api/pathfind
|
|
* Compute pathfinding between two points
|
|
*
|
|
* Request body:
|
|
* {
|
|
* map: string,
|
|
* from: [x, y],
|
|
* to: [x, y],
|
|
* adapters?: string[] // Optional: which comparison adapters to run
|
|
* }
|
|
*
|
|
* Response:
|
|
* {
|
|
* primary: { path, length, time, debug: { nodePath, initialPath, timings } },
|
|
* comparisons: [{ adapter, path, length, time }, ...]
|
|
* }
|
|
*/
|
|
app.post("/api/pathfind", async (req: Request, res: Response) => {
|
|
try {
|
|
const { map, from, to, adapters } = req.body;
|
|
|
|
// Validate request
|
|
if (!map || !from || !to) {
|
|
return res.status(400).json({
|
|
error: "Invalid request",
|
|
message: "Missing required fields: map, from, to",
|
|
});
|
|
}
|
|
|
|
if (
|
|
!Array.isArray(from) ||
|
|
from.length !== 2 ||
|
|
!Array.isArray(to) ||
|
|
to.length !== 2
|
|
) {
|
|
return res.status(400).json({
|
|
error: "Invalid coordinates",
|
|
message: "from and to must be [x, y] coordinate arrays",
|
|
});
|
|
}
|
|
|
|
// Compute paths
|
|
const result = await computePath(
|
|
map,
|
|
from as [number, number],
|
|
to as [number, number],
|
|
{ adapters },
|
|
);
|
|
|
|
res.json(result);
|
|
} catch (error) {
|
|
console.error("Error computing path:", error);
|
|
|
|
if (error instanceof Error && error.message.includes("is not water")) {
|
|
res.status(400).json({
|
|
error: "Invalid coordinates",
|
|
message: error.message,
|
|
});
|
|
} else {
|
|
res.status(500).json({
|
|
error: "Failed to compute path",
|
|
message: error instanceof Error ? error.message : String(error),
|
|
});
|
|
}
|
|
}
|
|
});
|
|
|
|
/**
|
|
* POST /api/cache/clear
|
|
* Clear all caches (useful for development)
|
|
*/
|
|
app.post("/api/cache/clear", (req: Request, res: Response) => {
|
|
try {
|
|
clearMapCache();
|
|
clearAdapterCaches();
|
|
res.json({ message: "Caches cleared successfully" });
|
|
} catch (error) {
|
|
console.error("Error clearing caches:", error);
|
|
res.status(500).json({
|
|
error: "Failed to clear caches",
|
|
message: error instanceof Error ? error.message : String(error),
|
|
});
|
|
}
|
|
});
|
|
|
|
// Error handling middleware
|
|
app.use((err: Error, req: Request, res: Response, next: any) => {
|
|
console.error("Unhandled error:", err);
|
|
res.status(500).json({
|
|
error: "Internal server error",
|
|
message: err.message,
|
|
});
|
|
});
|
|
|
|
// Start server
|
|
app.listen(PORT, () => {
|
|
console.log(`
|
|
╔════════════════════════════════════════════════════════════╗
|
|
║ Pathfinding Playground Server ║
|
|
╚════════════════════════════════════════════════════════════╝
|
|
|
|
Server running at: http://localhost:${PORT}
|
|
|
|
Press Ctrl+C to stop
|
|
`);
|
|
});
|