mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-26 06:37:33 +00:00
feat(ski-routing): plan ski tours on the piste graphs of TREK Places
A new Nest domain plans the legs of a ski and winter tour on the runs, lifts, cross-country trails, ski touring and winter paths the Places host builds from OpenStreetMap, one SGR1 graph per ski area. TREK fetches the index once, downloads an area by its id when a planner first plans in it, checks it against the index's SHA-256 and keeps it in data/ski; no clicked point ever leaves the server. A leg whose area is slower than two seconds answers loading, and an older copy stands in while the host is down. The reader decodes the writer's golden file byte for byte, including the two edge flags it added (area_has_run, type_unknown). The search is A* in a worker thread over a profile per discipline (alpine, snowboard, cross-country by technique, touring, snowshoe, winter hike) with the times and penalties of the cost model, up to five snap candidates per point, lift stations as entry points, legs that go on from each other, pieces of a split network stitched by their boundary nodes, other ways by the penalty method, and a failed leg explained by relaxing one rule at a time (difficulty, lift class, technique, riding down, uphill) without ever handing out the relaxed line. POST /api/trips/:tripId/ski/route, GET .../ski/area-near and GET .../ski/network/:areaId sit behind Tours and the trip, with plan_ski_route as their MCP twin. A daily job looks for a new build and sweeps areas unused for 90 days. The admin switch ski_routing_enabled is on wherever TREK Places is.
This commit is contained in:
@@ -101,6 +101,19 @@ export class AddonsService {
|
||||
return this.writeFlag('tours_cycle_map_enabled', enabled);
|
||||
}
|
||||
|
||||
/**
|
||||
* The admin's switch for the piste router under Tours, as stored; fail-open, so it works
|
||||
* wherever TREK Places is enabled until an admin switches it off.
|
||||
*/
|
||||
async getToursSkiRouting() {
|
||||
const value = await readAppSetting(this.appSettings, 'ski_routing_enabled');
|
||||
return { enabled: value !== 'false' };
|
||||
}
|
||||
|
||||
async updateToursSkiRouting(enabled: boolean) {
|
||||
return this.writeFlag('ski_routing_enabled', enabled);
|
||||
}
|
||||
|
||||
/** wanderer may be used: Tours is on and the admin allowed it under Tours. */
|
||||
async isWandererAvailable(): Promise<boolean> {
|
||||
return (await this.isAddonEnabled(ADDON_IDS.TOURS)) && (await this.getToursWanderer()).enabled;
|
||||
|
||||
@@ -342,6 +342,25 @@ export class AdminController {
|
||||
return result;
|
||||
}
|
||||
|
||||
@Get('tours-ski-routing')
|
||||
@ResponseContract(adminFeatureToggleResponseSchema)
|
||||
getToursSkiRouting() {
|
||||
return this.addons.getToursSkiRouting();
|
||||
}
|
||||
|
||||
@Put('tours-ski-routing')
|
||||
@ResponseContract(adminFeatureToggleResponseSchema)
|
||||
async updateToursSkiRouting(@CurrentUser() user: User, @Body() body: AdminFeatureToggleDto, @Req() req: Request) {
|
||||
const result = await this.addons.updateToursSkiRouting(body.enabled);
|
||||
await this.audit.writeAudit({
|
||||
userId: user.id,
|
||||
action: 'admin.tours_ski_routing',
|
||||
ip: getClientIp(req),
|
||||
details: { enabled: result.enabled },
|
||||
});
|
||||
return result;
|
||||
}
|
||||
|
||||
@Get('places-photos')
|
||||
getPlacesPhotos() {
|
||||
return this.addons.getPlacesPhotos();
|
||||
|
||||
@@ -86,6 +86,7 @@ import { SchoolHolidaysModule } from './school-holidays/school-holidays.module';
|
||||
import { SessionsModule } from './sessions/sessions.module';
|
||||
import { SettingsModule } from './settings/settings.module';
|
||||
import { ShareModule } from './share/share.module';
|
||||
import { SkiRoutingModule } from './ski-routing/ski-routing.module';
|
||||
import { StorageModule } from './storage/storage.module';
|
||||
import { SystemNoticesModule } from './system-notices/system-notices.module';
|
||||
import { TagsModule } from './tags/tags.module';
|
||||
@@ -160,6 +161,7 @@ import { APP_FILTER, APP_GUARD, APP_INTERCEPTOR, APP_PIPE } from '@nestjs/core';
|
||||
FerratasModule,
|
||||
PaddleObstaclesModule,
|
||||
PaddleRoutingModule,
|
||||
SkiRoutingModule,
|
||||
TripsModule,
|
||||
CollabModule,
|
||||
FilesModule,
|
||||
|
||||
@@ -116,6 +116,9 @@ export const APP_SETTINGS = {
|
||||
// tiles are OpenStreetMap France's, free for moderate use with a Referer; a heavy or commercial
|
||||
// install switches it off (or reaches an agreement) under the operator's usage policy.
|
||||
tours_cycle_map_enabled: { schema: flag, default: 'true' },
|
||||
// The piste router for ski tours, on wherever TREK Places is: it only downloads the ski areas a
|
||||
// planner plans in, and no clicked point leaves the server. The switch is the operator's way out.
|
||||
ski_routing_enabled: { schema: flag, default: 'true' },
|
||||
route_usage_enabled: { schema: flag, default: 'false' },
|
||||
// PAD-11C: how TREK gets the water data of a place a paddler plans in (auto, ask, off) and the largest extract it loads by itself.
|
||||
paddle_auto_load: { schema: z.enum(['auto', 'ask', 'off']), default: 'auto' },
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
import { readEnv } from '../../app-config';
|
||||
import {
|
||||
trekPlacesWinterArea,
|
||||
trekPlacesWinterIndex,
|
||||
trekPlacesWinterMeta,
|
||||
type TrekPlacesWinterBody,
|
||||
type TrekPlacesWinterIndex,
|
||||
} from './trek-places.client';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import type { WinterMeta } from '@trek/shared';
|
||||
|
||||
/**
|
||||
* The winter layer of the TREK Places host (`/v1/winter/*`) as a provider:
|
||||
* which build it serves, its index of ski areas, and one area's graph. Every
|
||||
* request goes through the same client as the place search, so the operator's
|
||||
* opt-out, the size caps, the timeouts and the circuit breaker hold for it
|
||||
* too. No request carries a coordinate. It holds no state of its own, so
|
||||
* the piste router's module provides it without importing the maps module.
|
||||
*/
|
||||
@Injectable()
|
||||
export class TrekPlacesWinterService {
|
||||
/** Whether the operator lets anything go to TREK Places at all. */
|
||||
enabled(): boolean {
|
||||
return readEnv().maps.trekPlacesEnabled;
|
||||
}
|
||||
|
||||
meta(): Promise<WinterMeta> {
|
||||
return trekPlacesWinterMeta();
|
||||
}
|
||||
|
||||
index(etag: string | null): Promise<TrekPlacesWinterIndex> {
|
||||
return trekPlacesWinterIndex(etag);
|
||||
}
|
||||
|
||||
area(id: string, etag: string | null): Promise<TrekPlacesWinterBody> {
|
||||
return trekPlacesWinterArea(id, etag);
|
||||
}
|
||||
}
|
||||
@@ -13,8 +13,16 @@
|
||||
*/
|
||||
import { readEnv, getAppUrl } from '../../app-config';
|
||||
import { toApiLang } from './maps.helpers';
|
||||
import { normalizePlaceWebsite } from '@trek/shared';
|
||||
import {
|
||||
normalizePlaceWebsite,
|
||||
winterIndexRowSchema,
|
||||
winterMetaSchema,
|
||||
type WinterIndex,
|
||||
type WinterIndexRow,
|
||||
type WinterMeta,
|
||||
} from '@trek/shared';
|
||||
|
||||
import { createHash } from 'node:crypto';
|
||||
import { z } from 'zod';
|
||||
|
||||
/** The public instance. An operator may point at their own copy instead. */
|
||||
@@ -200,28 +208,68 @@ export function trekPlacesBaseUrl(): string {
|
||||
return (configured || DEFAULT_TREK_PLACES_URL).replace(/\/+$/, '');
|
||||
}
|
||||
|
||||
/**
|
||||
* TREK_PLACES_ENABLED=false is the operator's word that nothing leaves for
|
||||
* the index. Every caller checks it before asking, and this is the one place
|
||||
* every request passes, so a caller that did not is still stopped here. Ahead
|
||||
* of the breaker: a refusal says nothing about reachability.
|
||||
*/
|
||||
function assertEnabled(): void {
|
||||
if (!readEnv().maps.trekPlacesEnabled) {
|
||||
throw new Error(SWITCHED_OFF_MESSAGE);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a breaker holds requests back right now, for a caller with a batch
|
||||
* to stop early. The winter downloads are layer reads, so they ask the layers'.
|
||||
*/
|
||||
export function trekPlacesHeldBack(breaker: Breaker = layersBreaker): boolean {
|
||||
return Date.now() < breaker.openUntil;
|
||||
}
|
||||
|
||||
/** Refuses a request while its breaker holds them back. */
|
||||
function assertBreakerClosed(breaker: Breaker): void {
|
||||
if (Date.now() < breaker.openUntil) {
|
||||
throw new Error('TREK Places API unreachable, not retrying yet');
|
||||
}
|
||||
}
|
||||
|
||||
/** A failed request, counted against its breaker when it says something about reachability. */
|
||||
function noteFailure(err: unknown, breaker: Breaker): void {
|
||||
if (countsAgainstReachability(err)) {
|
||||
breaker.failures += 1;
|
||||
if (breaker.failures >= BREAKER_FAILURES_BEFORE_OPEN) {
|
||||
breaker.openUntil = Date.now() + BREAKER_COOLDOWN_MS;
|
||||
// Back to the threshold rather than to zero: when the cooldown ends,
|
||||
// one more failure re-opens the breaker instead of buying another four
|
||||
// full timeouts.
|
||||
breaker.failures = BREAKER_FAILURES_BEFORE_OPEN - 1;
|
||||
}
|
||||
} else {
|
||||
// The service answered. A 404 is an answer.
|
||||
breaker.failures = 0;
|
||||
}
|
||||
}
|
||||
|
||||
function statusError(status: number): Error & { status: number } {
|
||||
const err = new Error(`TREK Places API ${status}`) as Error & { status: number };
|
||||
err.status = status;
|
||||
return err;
|
||||
}
|
||||
|
||||
async function getJson<T>(
|
||||
path: string,
|
||||
params: Record<string, string | number | undefined>,
|
||||
opts: { maxBytes?: number; timeoutMs?: number; breaker?: Breaker } = {},
|
||||
): Promise<T> {
|
||||
const breaker = opts.breaker ?? searchBreaker;
|
||||
// TREK_PLACES_ENABLED=false is the operator's word that nothing leaves for
|
||||
// the index. Every caller checks it before asking, and this is the one place
|
||||
// every request passes, so a caller that did not is still stopped here. Ahead
|
||||
// of the breaker: a refusal says nothing about reachability.
|
||||
if (!readEnv().maps.trekPlacesEnabled) {
|
||||
throw new Error(SWITCHED_OFF_MESSAGE);
|
||||
}
|
||||
|
||||
assertEnabled();
|
||||
const url = new URL(trekPlacesBaseUrl() + path);
|
||||
for (const [k, v] of Object.entries(params)) {
|
||||
if (v !== undefined && v !== null && v !== '') url.searchParams.set(k, String(v));
|
||||
}
|
||||
|
||||
if (Date.now() < breaker.openUntil) {
|
||||
throw new Error('TREK Places API unreachable, not retrying yet');
|
||||
}
|
||||
assertBreakerClosed(breaker);
|
||||
|
||||
const controller = new AbortController();
|
||||
const timer = setTimeout(() => controller.abort(), opts.timeoutMs ?? TIMEOUT_MS);
|
||||
@@ -233,11 +281,7 @@ async function getJson<T>(
|
||||
'X-TREK-Instance': instanceToken(),
|
||||
},
|
||||
});
|
||||
if (!res.ok) {
|
||||
const err = new Error(`TREK Places API ${res.status}`) as Error & { status: number };
|
||||
err.status = res.status;
|
||||
throw err;
|
||||
}
|
||||
if (!res.ok) throw statusError(res.status);
|
||||
// Read with a cap rather than res.json(): a hostile or broken upstream
|
||||
// should not be able to hand us an unbounded body to buffer.
|
||||
const text = await readCapped(res, opts.maxBytes ?? MAX_BYTES);
|
||||
@@ -246,19 +290,7 @@ async function getJson<T>(
|
||||
breaker.failures = 0;
|
||||
return parsed;
|
||||
} catch (err: unknown) {
|
||||
if (countsAgainstReachability(err)) {
|
||||
breaker.failures += 1;
|
||||
if (breaker.failures >= BREAKER_FAILURES_BEFORE_OPEN) {
|
||||
breaker.openUntil = Date.now() + BREAKER_COOLDOWN_MS;
|
||||
// Back to the threshold rather than to zero: when the cooldown ends,
|
||||
// one more failure re-opens the breaker instead of buying another four
|
||||
// full timeouts.
|
||||
breaker.failures = BREAKER_FAILURES_BEFORE_OPEN - 1;
|
||||
}
|
||||
} else {
|
||||
// The service answered. A 404 is an answer.
|
||||
breaker.failures = 0;
|
||||
}
|
||||
noteFailure(err, breaker);
|
||||
throw err;
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
@@ -286,8 +318,17 @@ export function serviceLang(lang: string | undefined): string | undefined {
|
||||
}
|
||||
|
||||
async function readCapped(res: Response, max: number): Promise<string> {
|
||||
if (!res.body) return res.text();
|
||||
return (await readCappedBytes(res, max)).toString('utf8');
|
||||
}
|
||||
|
||||
async function readCappedBytes(res: Response, max: number): Promise<Buffer> {
|
||||
const reader = res.body?.getReader();
|
||||
if (!reader) return res.text();
|
||||
if (!reader) {
|
||||
const whole = Buffer.from(await res.arrayBuffer());
|
||||
if (whole.length > max) throw new Error('TREK Places API response too large');
|
||||
return whole;
|
||||
}
|
||||
const chunks: Uint8Array[] = [];
|
||||
let size = 0;
|
||||
for (;;) {
|
||||
@@ -300,7 +341,7 @@ async function readCapped(res: Response, max: number): Promise<string> {
|
||||
}
|
||||
chunks.push(value);
|
||||
}
|
||||
return Buffer.concat(chunks).toString('utf8');
|
||||
return Buffer.concat(chunks);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -834,3 +875,109 @@ export async function trekPlacesRoutes(
|
||||
truncated: answer.data.truncated === true,
|
||||
};
|
||||
}
|
||||
|
||||
// ── Winter layer ─────────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* What the winter layer answers a conditional request: nothing new since the
|
||||
* tag the caller holds, or the body as sent with its tag. None of its three
|
||||
* endpoints takes a coordinate, so the service learns only which area a
|
||||
* planner loaded, never where anyone clicked.
|
||||
*/
|
||||
export type TrekPlacesWinterBody = { status: 'not_modified' } | { status: 'ok'; bytes: Buffer; etag: string | null };
|
||||
|
||||
const WINTER_META = { timeoutMs: 5_000, maxBytes: 64 * 1024 };
|
||||
const WINTER_INDEX = { timeoutMs: 15_000, maxBytes: 8 * 1024 * 1024 };
|
||||
const WINTER_AREA = { timeoutMs: 30_000, maxBytes: 32 * 1024 * 1024 };
|
||||
const WINTER_AREA_ID = /^[a-z]:[0-9]+(-[0-9a-z]+)?$/;
|
||||
|
||||
/** An ETag without its quotes and weak mark. */
|
||||
function bareTag(value: string | null): string | null {
|
||||
let tag = value?.trim() ?? '';
|
||||
if (tag.startsWith('W/')) tag = tag.slice(2);
|
||||
if (tag.length >= 2 && tag.startsWith('"') && tag.endsWith('"')) tag = tag.slice(1, -1);
|
||||
return tag || null;
|
||||
}
|
||||
|
||||
/** The head of the index; its rows are read one by one. */
|
||||
const winterIndexHeadSchema = z.object({
|
||||
build: z.string().min(1).max(40),
|
||||
format: z.number().int(),
|
||||
areas: z.array(z.unknown()),
|
||||
});
|
||||
|
||||
async function getWinter(
|
||||
path: string,
|
||||
accept: string,
|
||||
etag: string | null,
|
||||
limits: { timeoutMs: number; maxBytes: number },
|
||||
): Promise<TrekPlacesWinterBody> {
|
||||
assertEnabled();
|
||||
const url = new URL(trekPlacesBaseUrl() + path);
|
||||
assertBreakerClosed(layersBreaker);
|
||||
const controller = new AbortController();
|
||||
const timer = setTimeout(() => controller.abort(), limits.timeoutMs);
|
||||
try {
|
||||
const headers: Record<string, string> = { Accept: accept, 'X-TREK-Instance': instanceToken() };
|
||||
if (etag) headers['If-None-Match'] = `"${etag}"`;
|
||||
const res = await fetch(url, { signal: controller.signal, headers });
|
||||
if (res.status === 304 && etag) {
|
||||
layersBreaker.failures = 0;
|
||||
return { status: 'not_modified' };
|
||||
}
|
||||
if (!res.ok) throw statusError(res.status);
|
||||
const bytes = await readCappedBytes(res, limits.maxBytes);
|
||||
layersBreaker.failures = 0;
|
||||
return { status: 'ok', bytes, etag: bareTag(res.headers.get('etag')) };
|
||||
} catch (err: unknown) {
|
||||
noteFailure(err, layersBreaker);
|
||||
throw err;
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
}
|
||||
|
||||
/** Which build the winter layer serves, and the SHA-256 that tells a new index from the one kept. */
|
||||
export async function trekPlacesWinterMeta(): Promise<WinterMeta> {
|
||||
const answer = await getWinter('/v1/winter/meta', 'application/json', null, WINTER_META);
|
||||
if (answer.status !== 'ok') throw new Error('TREK Places winter meta came back empty');
|
||||
return winterMetaSchema.parse(JSON.parse(answer.bytes.toString('utf8')));
|
||||
}
|
||||
|
||||
export type TrekPlacesWinterIndex =
|
||||
| { status: 'not_modified' }
|
||||
| { status: 'ok'; index: WinterIndex; sha256: string; dropped: number };
|
||||
|
||||
/**
|
||||
* Every ski area with its box, size and checksum, unless the index the caller
|
||||
* holds (`etag`, its SHA-256) is still the current one. The checksum returned
|
||||
* is that of the JSON as read, for the caller to hold against the meta's
|
||||
* `indexSha`. A row that does not read as an area is dropped on its own and
|
||||
* counted; the head of the index must read, or nothing does.
|
||||
*/
|
||||
export async function trekPlacesWinterIndex(etag: string | null): Promise<TrekPlacesWinterIndex> {
|
||||
const answer = await getWinter('/v1/winter/index', 'application/json', etag, WINTER_INDEX);
|
||||
if (answer.status !== 'ok') return answer;
|
||||
const head = winterIndexHeadSchema.parse(JSON.parse(answer.bytes.toString('utf8')));
|
||||
const areas: WinterIndexRow[] = [];
|
||||
for (const row of head.areas) {
|
||||
const parsed = winterIndexRowSchema.safeParse(row);
|
||||
if (parsed.success) areas.push(parsed.data);
|
||||
}
|
||||
return {
|
||||
status: 'ok',
|
||||
index: { build: head.build, format: head.format, areas },
|
||||
sha256: createHash('sha256').update(answer.bytes).digest('hex'),
|
||||
dropped: head.areas.length - areas.length,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* One area's graph, gzip-packed SGR1 exactly as the service stores it, unless
|
||||
* the copy the caller holds (`etag`, its SHA-256) is still current. The caller
|
||||
* checks the bytes against the index's checksum before keeping them.
|
||||
*/
|
||||
export async function trekPlacesWinterArea(id: string, etag: string | null): Promise<TrekPlacesWinterBody> {
|
||||
if (!WINTER_AREA_ID.test(id) || id.length > 64) throw new Error(`Not a ski area id: ${id}`);
|
||||
return getWinter(`/v1/winter/area/${encodeURIComponent(id)}`, 'application/vnd.trek.sgraph', etag, WINTER_AREA);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
import type { EdgeCosts } from './profile';
|
||||
import type { FoundPath, SearchOutcome } from './router';
|
||||
import { buildLeg, legSeconds } from './segments';
|
||||
import type { SkiNet } from './stitch';
|
||||
import type { SkiRouteAlternative } from '@trek/shared';
|
||||
|
||||
/**
|
||||
* Other ways for a leg (spec 7.5), by the penalty method: every edge a way
|
||||
* already uses costs 1.4 times as much in the next search. A way found that
|
||||
* way is offered only when it shares less than 70 % of its length with the
|
||||
* ways before it and takes at most half as long again as the best one.
|
||||
*/
|
||||
|
||||
const PENALTY = 1.4;
|
||||
const MAX_SHARED = 0.7;
|
||||
const MAX_SLOWER = 1.5;
|
||||
|
||||
/** How much of a way's length runs on edges an earlier way used. */
|
||||
function sharedShare(net: SkiNet, path: FoundPath, used: ReadonlySet<number>): number {
|
||||
let total = 0;
|
||||
let shared = 0;
|
||||
for (const step of path.steps) {
|
||||
const length = (net.edgeLen[step.edge] as number) * Math.abs(step.to - step.from);
|
||||
total += length;
|
||||
if (used.has(step.edge)) shared += length;
|
||||
}
|
||||
return total > 0 ? shared / total : 1;
|
||||
}
|
||||
|
||||
export function findAlternatives(
|
||||
net: SkiNet,
|
||||
costs: EdgeCosts,
|
||||
best: FoundPath,
|
||||
count: number,
|
||||
search: (penalty: Float64Array) => SearchOutcome,
|
||||
): SkiRouteAlternative[] {
|
||||
if (count <= 0) return [];
|
||||
const bestSeconds = legSeconds(buildLeg(net, costs, best.steps, [best.start.lat, best.start.lng, best.start.ele]));
|
||||
const penalty = new Float64Array(net.edgeCount).fill(1);
|
||||
const used = new Set<number>();
|
||||
const punish = (path: FoundPath) => {
|
||||
for (const edge of new Set(path.steps.map((step) => step.edge))) {
|
||||
penalty[edge] = (penalty[edge] as number) * PENALTY;
|
||||
used.add(edge);
|
||||
}
|
||||
};
|
||||
punish(best);
|
||||
const found: SkiRouteAlternative[] = [];
|
||||
// A rejected way is penalised too, so the next try looks elsewhere; two spare tries at most.
|
||||
for (let tries = 0; tries < count + 2 && found.length < count; tries++) {
|
||||
const outcome = search(penalty);
|
||||
if (outcome.status !== 'ok') break;
|
||||
const path = outcome.path;
|
||||
const leg = buildLeg(net, costs, path.steps, [path.start.lat, path.start.lng, path.start.ele]);
|
||||
const seconds = legSeconds(leg);
|
||||
if (sharedShare(net, path, used) < MAX_SHARED && seconds <= bestSeconds * MAX_SLOWER) {
|
||||
found.push({ geometry: leg.geometry, segments: leg.segments, seconds_total: seconds });
|
||||
}
|
||||
punish(path);
|
||||
}
|
||||
return found;
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
import { DIFF_UNKNOWN, DIFFICULTY_NAMES, Kind } from '../ski-graph.contract';
|
||||
import { difficultyAllowed, liftClassOf, Mode, type EdgeCosts, type SkiProfile } from './profile';
|
||||
import type { FoundPath, Step } from './router';
|
||||
import type { SkiNet } from './stitch';
|
||||
import type { SkiFailCode, SkiFailHint, SkiRouteFailedLeg, SkiRunDifficulty } from '@trek/shared';
|
||||
|
||||
/**
|
||||
* Why a leg found no way (spec 7.6): the rules are relaxed one at a time and
|
||||
* the leg searched again; the first relaxation that finds a way names the
|
||||
* reason and the one change that would plan the leg. The way a relaxed search
|
||||
* found is only read for its reason, never returned as the leg's line.
|
||||
*/
|
||||
|
||||
/** One try at a leg with a profile: a way, no place to start or end, no way, or a search out of budget. */
|
||||
export type LegAttempt =
|
||||
| { status: 'ok'; path: FoundPath; settled: number; costs: EdgeCosts }
|
||||
| { status: 'no_snap'; which: 'from' | 'to' }
|
||||
| { status: 'none'; nearest: { lat: number; lng: number } | null }
|
||||
| { status: 'timeout' };
|
||||
|
||||
type Attempt = (profile: SkiProfile) => LegAttempt;
|
||||
|
||||
type Found = Extract<LegAttempt, { status: 'ok' }>;
|
||||
|
||||
interface Relaxation {
|
||||
code: SkiFailCode;
|
||||
applies: (profile: SkiProfile) => boolean;
|
||||
relax: (profile: SkiProfile) => SkiProfile;
|
||||
/** The hint and the run or lift the reason is about, read off the relaxed way. */
|
||||
read: (net: SkiNet, base: SkiProfile, found: Found) => { hint: SkiFailHint; name: string | null };
|
||||
}
|
||||
|
||||
const DOWNHILL_DISCIPLINES: ReadonlySet<string> = new Set(['alpine', 'snowboard', 'touring']);
|
||||
const DESCENT_MODES: ReadonlySet<number> = new Set([Mode.DOWNHILL, Mode.SKITOUR_DOWN]);
|
||||
const PISTE_KINDS: ReadonlySet<number> = new Set([Kind.RUN, Kind.AREA, Kind.CONNECTION]);
|
||||
const LIFT_EDGE_KINDS: ReadonlySet<number> = new Set([Kind.LIFT, Kind.RAIL, Kind.BOARD]);
|
||||
|
||||
const modeOf = (costs: EdgeCosts, step: Step): number =>
|
||||
(step.dir === 0 ? costs.modeFwd[step.edge] : costs.modeBack[step.edge]) as number;
|
||||
|
||||
const nameOf = (net: SkiNet, edge: number): string | null => net.edgeName[edge] ?? net.edgeRef[edge] ?? null;
|
||||
|
||||
/** The hardest run of a way above what a profile allows, if it has one. */
|
||||
export function hardestAbove(
|
||||
net: SkiNet,
|
||||
base: SkiProfile,
|
||||
path: FoundPath,
|
||||
costs: EdgeCosts,
|
||||
): { level: SkiRunDifficulty; name: string | null } | null {
|
||||
let hardest = -1;
|
||||
let edge = -1;
|
||||
for (const step of path.steps) {
|
||||
const diff = net.edgeDiff[step.edge] as number;
|
||||
if (!DESCENT_MODES.has(modeOf(costs, step)) || !PISTE_KINDS.has(net.edgeKind[step.edge] as number)) continue;
|
||||
if (diff === DIFF_UNKNOWN || difficultyAllowed(base.options, diff) || diff <= hardest) continue;
|
||||
hardest = diff;
|
||||
edge = step.edge;
|
||||
}
|
||||
const level = DIFFICULTY_NAMES[hardest];
|
||||
return level ? { level, name: nameOf(net, edge) } : null;
|
||||
}
|
||||
|
||||
const RELAXATIONS: readonly Relaxation[] = [
|
||||
{
|
||||
code: 'blocked_by_difficulty',
|
||||
applies: (p) =>
|
||||
DOWNHILL_DISCIPLINES.has(p.discipline) && (p.options.max_difficulty !== 'expert' || !p.options.allow_freeride),
|
||||
relax: (p) => ({ ...p, options: { ...p.options, max_difficulty: 'expert', allow_freeride: true } }),
|
||||
read: (net, base, found) => {
|
||||
const hardest = hardestAbove(net, base, found.path, found.costs);
|
||||
return { hint: hardest ? { raise_difficulty: hardest.level } : {}, name: hardest?.name ?? null };
|
||||
},
|
||||
},
|
||||
{
|
||||
code: 'blocked_by_lift_avoid',
|
||||
applies: (p) => p.useLifts && p.options.avoid_lifts.length > 0,
|
||||
relax: (p) => ({ ...p, options: { ...p.options, avoid_lifts: [] } }),
|
||||
read: (net, base, found) => {
|
||||
for (const step of found.path.steps) {
|
||||
if (!LIFT_EDGE_KINDS.has(net.edgeKind[step.edge] as number)) continue;
|
||||
const cls = liftClassOf(net.edgeLift[step.edge] as number);
|
||||
if (cls && base.options.avoid_lifts.includes(cls)) {
|
||||
return { hint: { allow_lift: cls }, name: nameOf(net, step.edge) };
|
||||
}
|
||||
}
|
||||
return { hint: {}, name: null };
|
||||
},
|
||||
},
|
||||
{
|
||||
code: 'blocked_by_technique',
|
||||
applies: (p) => p.discipline === 'cross_country' && p.technique !== 'unknown',
|
||||
relax: (p) => ({ ...p, technique: 'unknown' }),
|
||||
read: () => ({ hint: { technique: 'unknown' }, name: null }),
|
||||
},
|
||||
{
|
||||
code: 'needs_ride_down',
|
||||
applies: (p) => p.useLifts && !p.options.allow_lift_down,
|
||||
relax: (p) => ({ ...p, options: { ...p.options, allow_lift_down: true } }),
|
||||
read: (net, _base, found) => {
|
||||
const ride = found.path.steps.find((step) => modeOf(found.costs, step) === Mode.LIFT_DOWN);
|
||||
return { hint: { allow_lift_down: true }, name: ride ? nameOf(net, ride.edge) : null };
|
||||
},
|
||||
},
|
||||
{
|
||||
code: 'uphill_only',
|
||||
applies: (p) => p.discipline === 'alpine' || p.discipline === 'snowboard',
|
||||
relax: (p) => ({ ...p, walkUphill: true }),
|
||||
read: () => ({ hint: { discipline: 'touring' }, name: null }),
|
||||
},
|
||||
];
|
||||
|
||||
/**
|
||||
* The reason a leg failed, from relaxing the rules one at a time, or null when
|
||||
* no single relaxation finds a way (the caller then says where it stopped).
|
||||
*/
|
||||
export function explainFailure(net: SkiNet, base: SkiProfile, attempt: Attempt): SkiRouteFailedLeg | null {
|
||||
for (const relaxation of RELAXATIONS) {
|
||||
if (!relaxation.applies(base)) continue;
|
||||
const found = attempt(relaxation.relax(base));
|
||||
if (found.status !== 'ok') continue;
|
||||
const { hint, name } = relaxation.read(net, base, found);
|
||||
return { status: 'failed', code: relaxation.code, at: null, hint, detail: { name } };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
import { LocalFrame } from '../../../lib/geo/geo';
|
||||
import { encodePolyline } from '../../../utils/polyline';
|
||||
import { Kind, LIFT_NAMES, Use } from '../ski-graph.contract';
|
||||
import { difficultyName } from './segments';
|
||||
import type { SkiNet } from './stitch';
|
||||
import type { SkiNetworkFeature, SkiSegmentKind } from '@trek/shared';
|
||||
|
||||
/**
|
||||
* An area's runs, lifts and trails as lines for the planner's map (spec 10.4):
|
||||
* each drawn edge simplified (Douglas-Peucker, 5 m) and encoded as a
|
||||
* Google polyline with what the map labels it by. Links, crossings, station
|
||||
* edges and the open-slope edges between an area's portals are not drawn;
|
||||
* the raster overlay shows the slopes themselves.
|
||||
*/
|
||||
|
||||
/** Drawn edge kinds and the kind each is drawn as. */
|
||||
const DRAWN: ReadonlyMap<number, SkiSegmentKind> = new Map<number, SkiSegmentKind>([
|
||||
[Kind.RUN, 'run'],
|
||||
[Kind.LIFT, 'lift'],
|
||||
[Kind.RAIL, 'rail'],
|
||||
[Kind.NORDIC, 'nordic'],
|
||||
[Kind.SKITOUR, 'skitour'],
|
||||
[Kind.HIKE, 'hike'],
|
||||
[Kind.SLED_WALKUP, 'hike'],
|
||||
[Kind.CONNECTION, 'connection'],
|
||||
]);
|
||||
|
||||
/** Above this the lines are simplified harder. */
|
||||
const NETWORK_MAX_BYTES = 3 * 1024 * 1024;
|
||||
|
||||
/** The points of a line that stay within `tolerance` metres of it, its ends always kept. */
|
||||
export function simplifyLine(points: ReadonlyArray<[number, number]>, tolerance: number): Array<[number, number]> {
|
||||
if (points.length <= 2) return [...points];
|
||||
const first = points[0] as [number, number];
|
||||
const frame = new LocalFrame(first[0], first[1]);
|
||||
const xy = points.map(([lat, lng]) => [frame.x(lng), frame.y(lat)] as const);
|
||||
const keep = new Uint8Array(points.length);
|
||||
keep[0] = 1;
|
||||
keep[points.length - 1] = 1;
|
||||
const stack: Array<[number, number]> = [[0, points.length - 1]];
|
||||
while (stack.length > 0) {
|
||||
const [from, to] = stack.pop() as [number, number];
|
||||
const [ax, ay] = xy[from] as readonly [number, number];
|
||||
const [bx, by] = xy[to] as readonly [number, number];
|
||||
const dx = bx - ax;
|
||||
const dy = by - ay;
|
||||
const length2 = dx * dx + dy * dy;
|
||||
let worst = -1;
|
||||
let worstDistance = tolerance;
|
||||
for (let i = from + 1; i < to; i++) {
|
||||
const [px, py] = xy[i] as readonly [number, number];
|
||||
const t = length2 === 0 ? 0 : Math.max(0, Math.min(1, ((px - ax) * dx + (py - ay) * dy) / length2));
|
||||
const distance = Math.hypot(px - (ax + t * dx), py - (ay + t * dy));
|
||||
if (distance > worstDistance) {
|
||||
worstDistance = distance;
|
||||
worst = i;
|
||||
}
|
||||
}
|
||||
if (worst < 0) continue;
|
||||
keep[worst] = 1;
|
||||
stack.push([from, worst], [worst, to]);
|
||||
}
|
||||
return points.filter((_, i) => keep[i] === 1);
|
||||
}
|
||||
|
||||
function featureOf(net: SkiNet, e: number, kind: SkiSegmentKind, tolerance: number): SkiNetworkFeature {
|
||||
const line: Array<[number, number]> = [];
|
||||
for (let i = net.geomStart[e] as number; i < (net.geomStart[e + 1] as number); i++) {
|
||||
line.push([net.geomLat[i] as number, net.geomLng[i] as number]);
|
||||
}
|
||||
const fwd = net.edgeFwd[e] as number;
|
||||
const back = net.edgeBack[e] as number;
|
||||
const lift = net.edgeLift[e] as number;
|
||||
const riddenOneWay = (fwd & Use.LIFT_UP) !== 0 && (back & (Use.LIFT_UP | Use.LIFT_DOWN)) === 0;
|
||||
const skiedOneWay = (fwd & Use.DOWNHILL) !== 0 && (back & Use.DOWNHILL) === 0;
|
||||
return {
|
||||
kind,
|
||||
difficulty: kind === 'run' || kind === 'connection' ? difficultyName(net.edgeDiff[e] as number) : null,
|
||||
name: net.edgeName[e] ?? net.edgeRef[e] ?? null,
|
||||
lift_type: lift > 0 ? (LIFT_NAMES[lift] ?? null) : null,
|
||||
oneway: kind === 'lift' || kind === 'rail' ? riddenOneWay : skiedOneWay,
|
||||
line: encodePolyline(simplifyLine(line, tolerance), 5),
|
||||
};
|
||||
}
|
||||
|
||||
/** The drawn lines of a network, simplified at 5 m, or at 15 m when that comes to more than 3 MB. */
|
||||
export function networkFeatures(net: SkiNet): { features: SkiNetworkFeature[]; simplified_m: number } {
|
||||
let result: { features: SkiNetworkFeature[]; simplified_m: number } = { features: [], simplified_m: 5 };
|
||||
for (const tolerance of [5, 15]) {
|
||||
const features: SkiNetworkFeature[] = [];
|
||||
let bytes = 0;
|
||||
for (let e = 0; e < net.edgeCount; e++) {
|
||||
const kind = DRAWN.get(net.edgeKind[e] as number);
|
||||
if (!kind) continue;
|
||||
const feature = featureOf(net, e, kind, tolerance);
|
||||
bytes += feature.line.length + (feature.name?.length ?? 0) + 80;
|
||||
features.push(feature);
|
||||
}
|
||||
result = { features, simplified_m: tolerance };
|
||||
if (bytes <= NETWORK_MAX_BYTES) break;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
import { findAlternatives } from './alternatives';
|
||||
import { explainFailure, hardestAbove, type LegAttempt } from './explain';
|
||||
import { compileProfile, type EdgeCosts, type SkiProfile } from './profile';
|
||||
import { LEG_TIME_MS, MAX_SETTLED, searchPath, type SearchBudget } from './router';
|
||||
import { buildLeg, flagNotes, legSeconds } from './segments';
|
||||
import { nearestUsable, SNAP_RADIUS_M, snapPoint, type Snap } from './snap';
|
||||
import type { SkiNet } from './stitch';
|
||||
import type { SkiRouteLeg, SkiRoutePoint, SkiWhy } from '@trek/shared';
|
||||
|
||||
/**
|
||||
* The legs of one request on one network: each leg snapped, searched and,
|
||||
* planned, built into its line and stretches with its notes and other ways;
|
||||
* failed, explained. A leg that goes on from the one before starts exactly
|
||||
* where that one ended, so a tour does not jump between two parallel runs at
|
||||
* a point the skier set.
|
||||
*/
|
||||
|
||||
export interface LegInput {
|
||||
from: SkiRoutePoint;
|
||||
to: SkiRoutePoint;
|
||||
/** The leg starts at the point the previous leg of this job ended at. */
|
||||
continues: boolean;
|
||||
}
|
||||
|
||||
interface PlanInput {
|
||||
legs: readonly LegInput[];
|
||||
profile: SkiProfile;
|
||||
alternatives: number;
|
||||
}
|
||||
|
||||
/** A relaxed search while explaining gets a quarter of the nodes and well under a second. */
|
||||
const RELAXED_SETTLED = MAX_SETTLED / 4;
|
||||
const RELAXED_MS = 600;
|
||||
/** Only a leg found cheaply is searched again for the harder runs it kept clear of. */
|
||||
const WHY_SETTLED = 50_000;
|
||||
/** How much quicker the harder way must be before the note says so. */
|
||||
const WHY_FASTER = 0.8;
|
||||
/** How far a point off the network is measured, at most. */
|
||||
const MEASURE_OFF_M = 2000;
|
||||
const COMPILED_PROFILES = 8;
|
||||
|
||||
const round1 = (value: number): number => Math.round(value * 10) / 10;
|
||||
const startOf = (snap: Snap): [number, number, number] => [snap.lat, snap.lng, snap.ele];
|
||||
|
||||
export class SkiRouter {
|
||||
private readonly compiled = new Map<string, EdgeCosts>();
|
||||
|
||||
constructor(readonly net: SkiNet) {}
|
||||
|
||||
/** The network's costs for a profile, kept for the last few profiles asked. */
|
||||
costsFor(profile: SkiProfile): EdgeCosts {
|
||||
const key = JSON.stringify(profile);
|
||||
let costs = this.compiled.get(key);
|
||||
if (costs) {
|
||||
this.compiled.delete(key);
|
||||
} else {
|
||||
costs = compileProfile(profile, this.net);
|
||||
}
|
||||
this.compiled.set(key, costs);
|
||||
while (this.compiled.size > COMPILED_PROFILES) this.compiled.delete(this.compiled.keys().next().value as string);
|
||||
return costs;
|
||||
}
|
||||
|
||||
plan(input: PlanInput, areaIds: string[]): SkiRouteLeg[] {
|
||||
let previous: Snap | null = null;
|
||||
return input.legs.map((leg) => {
|
||||
const { answer, end } = this.planLeg(leg, input, leg.continues ? previous : null, areaIds);
|
||||
previous = end;
|
||||
return answer;
|
||||
});
|
||||
}
|
||||
|
||||
/** One try at a leg with a profile, starting at `start` when the leg goes on from the one before. */
|
||||
private attempt(profile: SkiProfile, leg: LegInput, start: Snap | null, budget: SearchBudget): LegAttempt {
|
||||
const costs = this.costsFor(profile);
|
||||
const radius = SNAP_RADIUS_M[profile.discipline];
|
||||
const starts = start ? [start] : snapPoint(this.net, costs, leg.from.lat, leg.from.lng, radius, 'from');
|
||||
if (starts.length === 0) return { status: 'no_snap', which: 'from' };
|
||||
const ends = snapPoint(this.net, costs, leg.to.lat, leg.to.lng, radius, 'to');
|
||||
if (ends.length === 0) return { status: 'no_snap', which: 'to' };
|
||||
const outcome = searchPath(this.net, costs, starts, ends, leg.to, budget);
|
||||
if (outcome.status === 'ok') return { status: 'ok', path: outcome.path, settled: outcome.settled, costs };
|
||||
return outcome.status === 'none' ? { status: 'none', nearest: outcome.nearest } : { status: 'timeout' };
|
||||
}
|
||||
|
||||
private relaxedBudget(): SearchBudget {
|
||||
return { maxSettled: RELAXED_SETTLED, deadline: Date.now() + RELAXED_MS };
|
||||
}
|
||||
|
||||
private planLeg(
|
||||
leg: LegInput,
|
||||
input: PlanInput,
|
||||
start: Snap | null,
|
||||
areaIds: string[],
|
||||
): { answer: SkiRouteLeg; end: Snap | null } {
|
||||
const base = input.profile;
|
||||
const found = this.attempt(base, leg, start, { maxSettled: MAX_SETTLED, deadline: Date.now() + LEG_TIME_MS });
|
||||
if (found.status === 'timeout') {
|
||||
return { answer: { status: 'failed', code: 'timeout', at: null, hint: null, detail: null }, end: null };
|
||||
}
|
||||
if (found.status !== 'ok') return { answer: this.failed(base, leg, start, found), end: null };
|
||||
const { path, costs } = found;
|
||||
const built = buildLeg(this.net, costs, path.steps, startOf(path.start));
|
||||
const avoided = this.avoidedDifficulty(base, leg, start, found, legSeconds(built));
|
||||
const why: SkiWhy[] = [...avoided, ...flagNotes(built.flagCounts)];
|
||||
const alternatives = findAlternatives(this.net, costs, path, input.alternatives, (penalty) =>
|
||||
searchPath(this.net, costs, [path.start], [path.end], leg.to, this.relaxedBudget(), penalty),
|
||||
);
|
||||
const { flagCounts: _flags, ...line } = built;
|
||||
return {
|
||||
answer: {
|
||||
status: 'ok',
|
||||
...line,
|
||||
snapped_m: { from: round1(path.start.distance), to: round1(path.end.distance) },
|
||||
area_ids: areaIds,
|
||||
why,
|
||||
alternatives,
|
||||
},
|
||||
end: path.end,
|
||||
};
|
||||
}
|
||||
|
||||
/** Why a leg found no way, or where it stopped. */
|
||||
private failed(base: SkiProfile, leg: LegInput, start: Snap | null, found: LegAttempt): SkiRouteLeg {
|
||||
const explained = explainFailure(this.net, base, (profile) =>
|
||||
this.attempt(profile, leg, start, this.relaxedBudget()),
|
||||
);
|
||||
if (explained) return explained;
|
||||
if (found.status === 'no_snap') {
|
||||
const point = found.which === 'from' ? leg.from : leg.to;
|
||||
const near = nearestUsable(this.net, this.costsFor(base), point.lat, point.lng, MEASURE_OFF_M);
|
||||
const name = near ? (this.net.edgeName[near.edge] ?? this.net.edgeRef[near.edge] ?? null) : null;
|
||||
const detail = near ? { name, distance_m: Math.round(near.distance) } : null;
|
||||
return { status: 'failed', code: 'not_on_piste', at: point, hint: null, detail };
|
||||
}
|
||||
const nearest = found.status === 'none' ? found.nearest : null;
|
||||
return { status: 'failed', code: 'disconnected', at: nearest, hint: null, detail: null };
|
||||
}
|
||||
|
||||
/** A note when a way over harder runs would have been clearly quicker; nothing for a leg costly to search. */
|
||||
private avoidedDifficulty(
|
||||
base: SkiProfile,
|
||||
leg: LegInput,
|
||||
start: Snap | null,
|
||||
found: Extract<LegAttempt, { status: 'ok' }>,
|
||||
seconds: number,
|
||||
): SkiWhy[] {
|
||||
const limited = base.options.max_difficulty !== 'expert' || !base.options.allow_freeride;
|
||||
const downhill = base.discipline === 'alpine' || base.discipline === 'snowboard' || base.discipline === 'touring';
|
||||
if (!limited || !downhill || found.settled > WHY_SETTLED) return [];
|
||||
const options = { ...base.options, max_difficulty: 'expert' as const, allow_freeride: true };
|
||||
const relaxed: SkiProfile = { ...base, options };
|
||||
const other = this.attempt(relaxed, leg, start, this.relaxedBudget());
|
||||
if (other.status !== 'ok') return [];
|
||||
const hardest = hardestAbove(this.net, base, other.path, other.costs);
|
||||
const faster = legSeconds(buildLeg(this.net, other.costs, other.path.steps, startOf(other.path.start)));
|
||||
if (!hardest || faster > seconds * WHY_FASTER) return [];
|
||||
const saved = Math.round(seconds - faster);
|
||||
return [{ kind: 'avoided_difficulty', level: hardest.level, name: hardest.name, saved_seconds: saved }];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,399 @@
|
||||
import { DIFF_EXPERT, DIFF_UNKNOWN, EdgeFlag, Groom, Kind, Lift, NodeFlag, Use } from '../ski-graph.contract';
|
||||
import type { SkiNet } from './stitch';
|
||||
import type { SkiDiscipline, SkiLiftClass, SkiRouteOptions, SkiTechnique } from '@trek/shared';
|
||||
|
||||
/**
|
||||
* Who travels the network, and what each edge costs them (spec 8). Two numbers
|
||||
* per edge and direction: the time it takes (what the traveller is shown) and
|
||||
* the cost the search weighs, which is the time with penalties and the
|
||||
* skier's preferences on top. An edge a profile may not use costs Infinity.
|
||||
*/
|
||||
export interface SkiProfile {
|
||||
discipline: SkiDiscipline;
|
||||
/** Cross-country only; `unknown` takes either technique. Null for every other discipline. */
|
||||
technique: SkiTechnique | null;
|
||||
options: SkiRouteOptions;
|
||||
/** Whether lifts may be ridden at all, the discipline's default resolved. */
|
||||
useLifts: boolean;
|
||||
/** Only while explaining a failure: a downhill skier may walk up a run, to tell "no way up" from "no way". */
|
||||
walkUphill?: boolean;
|
||||
}
|
||||
|
||||
/** How an edge is travelled in one direction, or 0 when it is not. */
|
||||
export const Mode = {
|
||||
NONE: 0,
|
||||
DOWNHILL: 1,
|
||||
LIFT: 2,
|
||||
LIFT_DOWN: 3,
|
||||
BOARD: 4,
|
||||
BOARD_DOWN: 5,
|
||||
ALIGHT: 6,
|
||||
ALIGHT_DOWN: 7,
|
||||
NORDIC: 8,
|
||||
SKITOUR_UP: 9,
|
||||
SKITOUR_DOWN: 10,
|
||||
SNOWSHOE: 11,
|
||||
HIKE: 12,
|
||||
WALK: 13,
|
||||
UPHILL_PISTE: 14,
|
||||
} as const;
|
||||
|
||||
/** The time and cost of every edge in both directions for one profile, and how each is travelled. */
|
||||
export interface EdgeCosts {
|
||||
timeFwd: Float64Array;
|
||||
timeBack: Float64Array;
|
||||
costFwd: Float64Array;
|
||||
costBack: Float64Array;
|
||||
modeFwd: Uint8Array;
|
||||
modeBack: Uint8Array;
|
||||
/** The fastest the search can go, metres of straight line per second of cost: the A* heuristic's speed. */
|
||||
maxSpeed: number;
|
||||
}
|
||||
|
||||
/** Edges walked or skied as a link between pieces of the network. */
|
||||
const WALK_KINDS: ReadonlySet<number> = new Set([Kind.LINK, Kind.CROSSING, Kind.CONNECTION, Kind.WALK]);
|
||||
/** Edges a run's difficulty applies to. */
|
||||
const PISTE_KINDS: ReadonlySet<number> = new Set([Kind.RUN, Kind.AREA, Kind.CONNECTION]);
|
||||
|
||||
/** The lift class the skier may leave out, by `edgeLift`. */
|
||||
export function liftClassOf(lift: number): SkiLiftClass | null {
|
||||
if (lift === Lift.CABLE_CAR) return 'cable_car';
|
||||
if (lift === Lift.GONDOLA || lift === Lift.MIXED) return 'gondola';
|
||||
if (lift === Lift.CHAIR_DETACHABLE || lift === Lift.CHAIR_FIXED) return 'open_chair';
|
||||
if (lift >= Lift.DRAG && lift <= Lift.MAGIC_CARPET) return 'drag';
|
||||
if (lift === Lift.FUNICULAR || lift === Lift.RACK) return 'rail';
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Whether a lift of this class may be ridden up. Cross-country skiers ride only enclosed transport. */
|
||||
export function liftAllowed(profile: SkiProfile, cls: SkiLiftClass | null): boolean {
|
||||
if (!profile.useLifts || cls === null || profile.options.avoid_lifts.includes(cls)) return false;
|
||||
if (profile.discipline === 'cross_country') return cls === 'gondola' || cls === 'cable_car' || cls === 'rail';
|
||||
// Nobody on snowshoes or boots is towed up a slope.
|
||||
if (profile.discipline === 'snowshoe' || profile.discipline === 'winter_hike') return cls !== 'drag';
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Whether a lift of this class may be ridden down: a gondola, a cable car or a train, never a tow. */
|
||||
export function liftDownAllowed(profile: SkiProfile, cls: SkiLiftClass | null): boolean {
|
||||
return profile.options.allow_lift_down && cls !== 'drag' && liftAllowed(profile, cls);
|
||||
}
|
||||
|
||||
/** Whether a run of this difficulty is within the skier's limit; one the data does not grade always is. */
|
||||
export function difficultyAllowed(options: SkiRouteOptions, diff: number): boolean {
|
||||
if (diff === DIFF_UNKNOWN) return true;
|
||||
if (diff > DIFF_EXPERT) return options.allow_freeride;
|
||||
return diff <= DIFF_LEVEL[options.max_difficulty];
|
||||
}
|
||||
|
||||
const DIFF_LEVEL: Record<SkiRouteOptions['max_difficulty'], number> = {
|
||||
novice: 0,
|
||||
easy: 1,
|
||||
intermediate: 2,
|
||||
advanced: 3,
|
||||
expert: 4,
|
||||
};
|
||||
|
||||
function lifted(profile: SkiProfile, net: SkiNet, e: number, uses: number, board: number, down: number): number {
|
||||
const cls = liftClassOf(net.edgeLift[e] as number);
|
||||
if (uses & Use.LIFT_UP && liftAllowed(profile, cls)) return board;
|
||||
if (uses & Use.LIFT_DOWN && liftDownAllowed(profile, cls)) return down;
|
||||
return Mode.NONE;
|
||||
}
|
||||
|
||||
function nordicWanted(profile: SkiProfile): number {
|
||||
if (profile.technique === 'classic') return Use.NORDIC_CLASSIC;
|
||||
if (profile.technique === 'skating') return Use.NORDIC_SKATING;
|
||||
return Use.NORDIC_CLASSIC | Use.NORDIC_SKATING;
|
||||
}
|
||||
|
||||
function groomAllowed(profile: SkiProfile, net: SkiNet, e: number): boolean {
|
||||
const groom = net.edgeGroom[e] as number;
|
||||
if (profile.options.groomed_only && (groom === 0 || groom & Groom.BACKCOUNTRY)) return false;
|
||||
return !profile.options.lit_only || ((net.edgeFlags[e] as number) & EdgeFlag.LIT) !== 0;
|
||||
}
|
||||
|
||||
/** A downhill use of a piste, as long as its difficulty is within the limit. */
|
||||
function descent(profile: SkiProfile, net: SkiNet, e: number, mode: number): number {
|
||||
if (!PISTE_KINDS.has(net.edgeKind[e] as number)) return mode;
|
||||
return difficultyAllowed(profile.options, net.edgeDiff[e] as number) ? mode : Mode.NONE;
|
||||
}
|
||||
|
||||
/** A run short enough to be crossed on foot by someone who does not ski it. */
|
||||
function crossable(net: SkiNet, e: number): boolean {
|
||||
const kind = net.edgeKind[e] as number;
|
||||
return (kind === Kind.RUN || kind === Kind.AREA) && (net.edgeLen[e] as number) <= 80;
|
||||
}
|
||||
|
||||
function downhillMode(profile: SkiProfile, net: SkiNet, e: number, uses: number, other: number): number {
|
||||
const kind = net.edgeKind[e] as number;
|
||||
if (uses & Use.DOWNHILL) {
|
||||
const mode = descent(profile, net, e, Mode.DOWNHILL);
|
||||
if (mode !== Mode.NONE) return mode;
|
||||
}
|
||||
if (uses & Use.WALK && WALK_KINDS.has(kind)) return Mode.WALK;
|
||||
if (profile.walkUphill && (kind === Kind.RUN || kind === Kind.AREA) && other & Use.DOWNHILL) return Mode.WALK;
|
||||
return Mode.NONE;
|
||||
}
|
||||
|
||||
function touringMode(profile: SkiProfile, net: SkiNet, e: number, uses: number, other: number, dir: 0 | 1): number {
|
||||
const kind = net.edgeKind[e] as number;
|
||||
const up = dir === 0 ? (net.edgeUp[e] as number) : (net.edgeDown[e] as number);
|
||||
const down = dir === 0 ? (net.edgeDown[e] as number) : (net.edgeUp[e] as number);
|
||||
const canDescend = (uses & (Use.DOWNHILL | Use.SKITOUR_DOWN)) !== 0;
|
||||
const canClimb = (uses & (Use.SKITOUR_UP | Use.SNOWSHOE)) !== 0;
|
||||
if (canDescend && (!canClimb || down >= up)) {
|
||||
const mode = descent(profile, net, e, Mode.SKITOUR_DOWN);
|
||||
if (mode !== Mode.NONE) return mode;
|
||||
}
|
||||
if (canClimb) return Mode.SKITOUR_UP;
|
||||
if (profile.options.touring_uphill_on_pistes && (kind === Kind.RUN || kind === Kind.AREA) && other & Use.DOWNHILL) {
|
||||
return Mode.UPHILL_PISTE;
|
||||
}
|
||||
return uses & Use.WALK && WALK_KINDS.has(kind) ? Mode.WALK : Mode.NONE;
|
||||
}
|
||||
|
||||
/** How a profile travels an edge's snow (not its lifts) in one direction. */
|
||||
function snowMode(profile: SkiProfile, net: SkiNet, e: number, dir: 0 | 1): number {
|
||||
const uses = (dir === 0 ? net.edgeFwd[e] : net.edgeBack[e]) as number;
|
||||
const other = (dir === 0 ? net.edgeBack[e] : net.edgeFwd[e]) as number;
|
||||
const kind = net.edgeKind[e] as number;
|
||||
const walk = uses & Use.WALK && WALK_KINDS.has(kind) ? Mode.WALK : Mode.NONE;
|
||||
switch (profile.discipline) {
|
||||
case 'alpine':
|
||||
case 'snowboard':
|
||||
return downhillMode(profile, net, e, uses, other);
|
||||
case 'cross_country':
|
||||
if (uses & nordicWanted(profile) && groomAllowed(profile, net, e)) return Mode.NORDIC;
|
||||
return walk;
|
||||
case 'touring':
|
||||
return touringMode(profile, net, e, uses, other, dir);
|
||||
case 'snowshoe':
|
||||
// A run's ski touring bits are a tourer's way down it, not a snowshoe trail.
|
||||
if (!PISTE_KINDS.has(kind) && uses & (Use.SNOWSHOE | Use.WINTER_HIKE | Use.SKITOUR_UP | Use.SKITOUR_DOWN)) {
|
||||
return Mode.SNOWSHOE;
|
||||
}
|
||||
if (crossable(net, e) && (uses | other) !== 0) return Mode.WALK;
|
||||
return walk;
|
||||
case 'winter_hike':
|
||||
if (uses & Use.WINTER_HIKE) return Mode.HIKE;
|
||||
if (crossable(net, e) && (uses | other) !== 0) return Mode.WALK;
|
||||
return walk;
|
||||
}
|
||||
}
|
||||
|
||||
/** How a profile travels an edge in one direction, or {@link Mode.NONE}. */
|
||||
export function travelMode(profile: SkiProfile, net: SkiNet, e: number, dir: 0 | 1): number {
|
||||
const uses = (dir === 0 ? net.edgeFwd[e] : net.edgeBack[e]) as number;
|
||||
const kind = net.edgeKind[e] as number;
|
||||
if (kind === Kind.LIFT || kind === Kind.RAIL) return lifted(profile, net, e, uses, Mode.LIFT, Mode.LIFT_DOWN);
|
||||
if (kind === Kind.BOARD) return lifted(profile, net, e, uses, Mode.BOARD, Mode.BOARD_DOWN);
|
||||
if (kind === Kind.ALIGHT) return lifted(profile, net, e, uses, Mode.ALIGHT, Mode.ALIGHT_DOWN);
|
||||
return snowMode(profile, net, e, dir);
|
||||
}
|
||||
|
||||
// ── Times (spec 8.1) ─────────────────────────────────────────────────────────
|
||||
|
||||
/** Downhill speed by difficulty, m/s: novice, easy, intermediate, advanced, expert, freeride, extreme. */
|
||||
const RUN_SPEED = [4, 7, 8.5, 7, 6, 5, 5];
|
||||
const UNKNOWN_RUN_SPEED = 7;
|
||||
const PACE_FACTOR: Record<SkiRouteOptions['pace'], number> = { relaxed: 0.7, normal: 1, sporty: 1.3 };
|
||||
|
||||
/** Ride speed by lift type when the data gives no ride time, m/s. */
|
||||
const LIFT_SPEED: Record<number, number> = {
|
||||
[Lift.CABLE_CAR]: 10,
|
||||
[Lift.GONDOLA]: 5,
|
||||
[Lift.MIXED]: 5,
|
||||
[Lift.CHAIR_DETACHABLE]: 5,
|
||||
[Lift.CHAIR_FIXED]: 2.3,
|
||||
[Lift.DRAG]: 3,
|
||||
[Lift.TBAR]: 3,
|
||||
[Lift.JBAR]: 3,
|
||||
[Lift.PLATTER]: 3,
|
||||
[Lift.ROPE_TOW]: 2,
|
||||
[Lift.MAGIC_CARPET]: 0.8,
|
||||
[Lift.FUNICULAR]: 8,
|
||||
[Lift.RACK]: 8,
|
||||
};
|
||||
|
||||
/** The wait at a lift's bottom station, a guess from its type and capacity, seconds. */
|
||||
export function boardWaitSeconds(lift: number, capacity: number): number {
|
||||
const cls = liftClassOf(lift);
|
||||
if (lift === Lift.MAGIC_CARPET) return 30;
|
||||
if (cls === 'drag') return 60;
|
||||
if (cls === 'cable_car' || cls === 'rail') return 240;
|
||||
return capacity >= 2400 ? 90 : 120;
|
||||
}
|
||||
|
||||
const ALIGHT_SECONDS = 15;
|
||||
const WALK_SPEED = 0.7;
|
||||
|
||||
/** DIN 33466: the longer of the two times plus half the shorter, both in seconds. */
|
||||
const din = (horizontal: number, vertical: number): number =>
|
||||
Math.max(horizontal, vertical) + Math.min(horizontal, vertical) / 2;
|
||||
|
||||
function runSeconds(profile: SkiProfile, net: SkiNet, e: number, length: number): number {
|
||||
const diff = net.edgeDiff[e] as number;
|
||||
let speed = (diff === DIFF_UNKNOWN ? UNKNOWN_RUN_SPEED : RUN_SPEED[diff]) ?? UNKNOWN_RUN_SPEED;
|
||||
if ((net.edgeGroom[e] as number) & Groom.MOGUL) speed *= 0.8;
|
||||
if ((net.edgeKind[e] as number) === Kind.AREA) speed *= 0.8;
|
||||
speed *= PACE_FACTOR[profile.options.pace];
|
||||
if (profile.discipline === 'snowboard') {
|
||||
if ((net.edgeFlags[e] as number) & EdgeFlag.FLAT_FOR_BOARD) return length / 1.5;
|
||||
speed *= 0.95;
|
||||
}
|
||||
return length / speed;
|
||||
}
|
||||
|
||||
/** Tobler's hiking function, normalised to the flat, for a nordic skier: slower up, a little faster down. */
|
||||
function toblerFactor(grade: number): number {
|
||||
const factor = Math.exp(-3.5 * Math.abs(grade + 0.05)) / Math.exp(-0.175);
|
||||
return Math.min(2.5, Math.max(0.25, factor));
|
||||
}
|
||||
|
||||
function nordicSeconds(profile: SkiProfile, net: SkiNet, e: number, length: number, climb: number, drop: number) {
|
||||
const flat = profile.technique === 'skating' ? 3.3 : 2.5;
|
||||
const grade = length > 0 ? (climb - drop) / length : 0;
|
||||
let speed = flat * toblerFactor(grade);
|
||||
if ((net.edgeGroom[e] as number) & Groom.BACKCOUNTRY) speed *= 0.6;
|
||||
return length / speed;
|
||||
}
|
||||
|
||||
/** What it takes to travel an edge in one direction in a mode, seconds; the wait at a lift included. */
|
||||
export function edgeSeconds(profile: SkiProfile, net: SkiNet, e: number, dir: 0 | 1, mode: number): number {
|
||||
const length = net.edgeLen[e] as number;
|
||||
const climb = dir === 0 ? (net.edgeUp[e] as number) : (net.edgeDown[e] as number);
|
||||
const drop = dir === 0 ? (net.edgeDown[e] as number) : (net.edgeUp[e] as number);
|
||||
const kind = net.edgeKind[e] as number;
|
||||
// A link, a crossing or a mapped walk is walked, whatever it lets through.
|
||||
if (mode === Mode.WALK || kind === Kind.LINK || kind === Kind.CROSSING || kind === Kind.WALK) {
|
||||
return length / WALK_SPEED + (climb / 300) * 3600;
|
||||
}
|
||||
switch (mode) {
|
||||
case Mode.DOWNHILL:
|
||||
return runSeconds(profile, net, e, length);
|
||||
case Mode.LIFT:
|
||||
case Mode.LIFT_DOWN: {
|
||||
const ride = net.edgeLiftSec[e] as number;
|
||||
return ride > 0 ? ride : length / (LIFT_SPEED[net.edgeLift[e] as number] ?? 5);
|
||||
}
|
||||
case Mode.BOARD:
|
||||
case Mode.BOARD_DOWN:
|
||||
return boardWaitSeconds(net.edgeLift[e] as number, net.edgeLiftCap[e] as number);
|
||||
case Mode.ALIGHT:
|
||||
case Mode.ALIGHT_DOWN:
|
||||
return ALIGHT_SECONDS;
|
||||
case Mode.NORDIC:
|
||||
return nordicSeconds(profile, net, e, length, climb, drop);
|
||||
case Mode.SKITOUR_UP:
|
||||
case Mode.UPHILL_PISTE:
|
||||
return din(length / (4000 / 3600), (climb / 350) * 3600);
|
||||
case Mode.SKITOUR_DOWN:
|
||||
return length / (kind === Kind.RUN || kind === Kind.AREA || kind === Kind.CONNECTION ? 7 : 3);
|
||||
case Mode.SNOWSHOE:
|
||||
return din(length / (3000 / 3600), (climb / 250) * 3600 + (drop / 500) * 3600);
|
||||
case Mode.HIKE:
|
||||
return din(length / (4000 / 3600), (climb / 300) * 3600 + (drop / 500) * 3600) / 0.85;
|
||||
default:
|
||||
return Number.POSITIVE_INFINITY;
|
||||
}
|
||||
}
|
||||
|
||||
/** The extra seconds of the node an edge arrives at: getting out of the bindings where the map says to. */
|
||||
export function dismountSeconds(net: SkiNet, node: number): number {
|
||||
const flags = net.nodeFlags[node] as number;
|
||||
if (flags & NodeFlag.DISMOUNT_YES) return 30;
|
||||
return flags & NodeFlag.DISMOUNT_SOMETIMES ? 10 : 0;
|
||||
}
|
||||
|
||||
// ── Costs (spec 8.2) ─────────────────────────────────────────────────────────
|
||||
|
||||
const SKIING_MODES: ReadonlySet<number> = new Set([Mode.DOWNHILL, Mode.NORDIC, Mode.SKITOUR_DOWN]);
|
||||
const LIFT_MODES: ReadonlySet<number> = new Set([Mode.LIFT, Mode.LIFT_DOWN, Mode.BOARD, Mode.BOARD_DOWN]);
|
||||
|
||||
/** OsmAnd's weighting for the easiest way: the harder a run against the limit, the dearer. */
|
||||
function easiestFactor(options: SkiRouteOptions, diff: number): number {
|
||||
if (diff === DIFF_UNKNOWN) return 1.5;
|
||||
const below = DIFF_LEVEL[options.max_difficulty] - Math.min(diff, DIFF_EXPERT);
|
||||
if (below <= 0) return 1.8;
|
||||
if (below === 1) return 1.5;
|
||||
return below === 2 ? 1.2 : 1;
|
||||
}
|
||||
|
||||
function nordicPenalty(profile: SkiProfile, net: SkiNet, e: number): number {
|
||||
const groom = net.edgeGroom[e] as number;
|
||||
let factor = 1;
|
||||
if (groom & Groom.BACKCOUNTRY) factor *= profile.technique === 'skating' ? 3 : 2;
|
||||
if ((net.edgeFlags[e] as number) & EdgeFlag.TECHNIQUE_ASSUMED) factor *= 1.1;
|
||||
return factor;
|
||||
}
|
||||
|
||||
/** The cost the search weighs for an edge travelled in one direction: its time, penalised and weighted. */
|
||||
export function edgeCost(profile: SkiProfile, net: SkiNet, e: number, dir: 0 | 1, mode: number, time: number): number {
|
||||
const flags = net.edgeFlags[e] as number;
|
||||
const kind = net.edgeKind[e] as number;
|
||||
let cost = time;
|
||||
if (mode === Mode.LIFT_DOWN) cost *= 3;
|
||||
if (mode === Mode.UPHILL_PISTE) cost *= 1.5;
|
||||
const uses = (dir === 0 ? net.edgeFwd[e] : net.edgeBack[e]) as number;
|
||||
if (mode === Mode.SNOWSHOE && uses & Use.SNOWSHOE) cost *= 0.8;
|
||||
if (mode === Mode.NORDIC) cost *= nordicPenalty(profile, net, e);
|
||||
if (dir === 1 && flags & EdgeFlag.DIR_CONFLICT && SKIING_MODES.has(mode)) cost *= 1.5;
|
||||
if (dir === 1 && flags & EdgeFlag.NORDIC_SOFT_ONEWAY && mode === Mode.NORDIC) cost *= 1.1;
|
||||
if (kind === Kind.AREA && flags & EdgeFlag.AREA_HAS_RUN) cost *= 1.3;
|
||||
if (flags & EdgeFlag.TYPE_UNKNOWN) cost *= 1.5;
|
||||
if (profile.discipline === 'snowboard') {
|
||||
if (mode === Mode.DOWNHILL && flags & EdgeFlag.FLAT_FOR_BOARD) cost *= 3;
|
||||
if (mode === Mode.BOARD && liftClassOf(net.edgeLift[e] as number) === 'drag') cost += 600;
|
||||
}
|
||||
if (profile.options.priority === 'most_skiing') {
|
||||
if (SKIING_MODES.has(mode)) cost /= 1.8;
|
||||
else if (LIFT_MODES.has(mode)) cost *= 1.2;
|
||||
}
|
||||
if (profile.options.priority === 'easiest' && mode === Mode.DOWNHILL && PISTE_KINDS.has(kind)) {
|
||||
cost *= easiestFactor(profile.options, net.edgeDiff[e] as number);
|
||||
}
|
||||
if (flags & EdgeFlag.INFERRED_LINK) {
|
||||
cost = (cost + 30) * ((net.edgeLen[e] as number) > 50 ? 2 : 1);
|
||||
if (profile.options.avoid_inferred_links) cost *= 5;
|
||||
}
|
||||
return cost;
|
||||
}
|
||||
|
||||
/** Every edge's time, cost and mode in both directions for one profile. */
|
||||
export function compileProfile(profile: SkiProfile, net: SkiNet): EdgeCosts {
|
||||
const m = net.edgeCount;
|
||||
const costs: EdgeCosts = {
|
||||
timeFwd: new Float64Array(m),
|
||||
timeBack: new Float64Array(m),
|
||||
costFwd: new Float64Array(m),
|
||||
costBack: new Float64Array(m),
|
||||
modeFwd: new Uint8Array(m),
|
||||
modeBack: new Uint8Array(m),
|
||||
maxSpeed: 1,
|
||||
};
|
||||
for (let e = 0; e < m; e++) {
|
||||
for (const dir of [0, 1] as const) {
|
||||
const mode = travelMode(profile, net, e, dir);
|
||||
const arrive = dir === 0 ? (net.edgeB[e] as number) : (net.edgeA[e] as number);
|
||||
const time =
|
||||
mode === Mode.NONE ? Infinity : edgeSeconds(profile, net, e, dir, mode) + dismountSeconds(net, arrive);
|
||||
const cost = mode === Mode.NONE ? Infinity : edgeCost(profile, net, e, dir, mode, time);
|
||||
if (dir === 0) {
|
||||
costs.timeFwd[e] = time;
|
||||
costs.costFwd[e] = cost;
|
||||
costs.modeFwd[e] = mode;
|
||||
} else {
|
||||
costs.timeBack[e] = time;
|
||||
costs.costBack[e] = cost;
|
||||
costs.modeBack[e] = mode;
|
||||
}
|
||||
// A little over the fastest edge, so the heuristic stays below any cost the lengths' rounding could give.
|
||||
const length = net.edgeLen[e] as number;
|
||||
if (Number.isFinite(cost) && cost > 0 && length > 0) {
|
||||
costs.maxSpeed = Math.max(costs.maxSpeed, (length / cost) * 1.02);
|
||||
}
|
||||
}
|
||||
}
|
||||
return costs;
|
||||
}
|
||||
@@ -0,0 +1,266 @@
|
||||
import { metresBetween } from '../../../lib/geo/geo';
|
||||
import { MinHeap } from '../../../lib/geo/min-heap';
|
||||
import type { EdgeCosts } from './profile';
|
||||
import type { Snap } from './snap';
|
||||
import type { SkiNet } from './stitch';
|
||||
|
||||
/**
|
||||
* The search (spec 7.5): A* over the network on cost, from any of a leg's
|
||||
* start places to any of its end places, with the straight line at the
|
||||
* fastest edge's speed as the heuristic, so the first way found is the
|
||||
* cheapest. A search has a budget of settled nodes and of time; spent, it
|
||||
* answers `timeout` rather than a guess.
|
||||
*/
|
||||
|
||||
/** A stretch of one edge, travelled from share `from` to share `to` of its length (both 0 to 1, a to b). */
|
||||
export interface Step {
|
||||
edge: number;
|
||||
dir: 0 | 1;
|
||||
from: number;
|
||||
to: number;
|
||||
}
|
||||
|
||||
export interface FoundPath {
|
||||
steps: Step[];
|
||||
cost: number;
|
||||
start: Snap;
|
||||
end: Snap;
|
||||
}
|
||||
|
||||
export type SearchOutcome =
|
||||
| { status: 'ok'; path: FoundPath; settled: number }
|
||||
| { status: 'none'; settled: number; nearest: { lat: number; lng: number } | null }
|
||||
| { status: 'timeout'; settled: number };
|
||||
|
||||
export interface SearchBudget {
|
||||
maxSettled: number;
|
||||
deadline: number;
|
||||
}
|
||||
|
||||
/** The most nodes one search settles before it gives up, and how long it may take. */
|
||||
export const MAX_SETTLED = 400_000;
|
||||
export const LEG_TIME_MS = 3000;
|
||||
|
||||
/** Per-node state of a search, reused between searches on the same network and told apart by a stamp. */
|
||||
class SearchState {
|
||||
readonly g: Float64Array;
|
||||
readonly prevEdge: Int32Array;
|
||||
readonly prevDir: Uint8Array;
|
||||
readonly startOf: Int32Array;
|
||||
readonly stamp: Uint32Array;
|
||||
readonly settled: Uint32Array;
|
||||
current = 0;
|
||||
readonly heap = new MinHeap(4096);
|
||||
|
||||
constructor(nodes: number) {
|
||||
this.g = new Float64Array(nodes);
|
||||
this.prevEdge = new Int32Array(nodes);
|
||||
this.prevDir = new Uint8Array(nodes);
|
||||
this.startOf = new Int32Array(nodes);
|
||||
this.stamp = new Uint32Array(nodes);
|
||||
this.settled = new Uint32Array(nodes);
|
||||
}
|
||||
|
||||
begin(): void {
|
||||
this.current++;
|
||||
this.heap.clear();
|
||||
}
|
||||
|
||||
cost(node: number): number {
|
||||
return this.stamp[node] === this.current ? (this.g[node] as number) : Infinity;
|
||||
}
|
||||
|
||||
set(node: number, cost: number, edge: number, dir: 0 | 1, start: number): void {
|
||||
this.stamp[node] = this.current;
|
||||
this.g[node] = cost;
|
||||
this.prevEdge[node] = edge;
|
||||
this.prevDir[node] = dir;
|
||||
this.startOf[node] = start;
|
||||
}
|
||||
}
|
||||
|
||||
const states = new WeakMap<SkiNet, SearchState>();
|
||||
|
||||
function stateOf(net: SkiNet): SearchState {
|
||||
let state = states.get(net);
|
||||
if (!state) {
|
||||
state = new SearchState(net.nodeCount);
|
||||
states.set(net, state);
|
||||
}
|
||||
state.begin();
|
||||
return state;
|
||||
}
|
||||
|
||||
/** How a search may begin: at a node (a lift station, or an edge's end reached from a start place on it). */
|
||||
interface Entry {
|
||||
snap: Snap;
|
||||
/** The partial stretch from the start place to the node, or null where the place is the node. */
|
||||
step: Step | null;
|
||||
}
|
||||
|
||||
/** How a search may end: from a node, along part of an edge to an end place, at an extra cost. */
|
||||
interface Exit {
|
||||
snap: Snap;
|
||||
step: Step | null;
|
||||
extra: number;
|
||||
}
|
||||
|
||||
/** What a stretch of an edge costs; none at all where it has no length (a place right at a node). */
|
||||
function stepCost(costs: EdgeCosts, step: Step, penalty: Float64Array | null): number {
|
||||
const share = Math.abs(step.to - step.from);
|
||||
if (share === 0) return 0;
|
||||
const cost = step.dir === 0 ? (costs.costFwd[step.edge] as number) : (costs.costBack[step.edge] as number);
|
||||
return cost * share * (penalty ? (penalty[step.edge] as number) : 1);
|
||||
}
|
||||
|
||||
function entriesOf(net: SkiNet, snap: Snap): Array<{ node: number; entry: Entry }> {
|
||||
if (snap.edge < 0) return [{ node: snap.node, entry: { snap, step: null } }];
|
||||
return [
|
||||
{ node: net.edgeB[snap.edge] as number, entry: { snap, step: { edge: snap.edge, dir: 0, from: snap.t, to: 1 } } },
|
||||
{ node: net.edgeA[snap.edge] as number, entry: { snap, step: { edge: snap.edge, dir: 1, from: snap.t, to: 0 } } },
|
||||
];
|
||||
}
|
||||
|
||||
function exitsOf(net: SkiNet, snap: Snap): Array<{ node: number; exit: Omit<Exit, 'extra'> }> {
|
||||
if (snap.edge < 0) return [{ node: snap.node, exit: { snap, step: null } }];
|
||||
return [
|
||||
{ node: net.edgeA[snap.edge] as number, exit: { snap, step: { edge: snap.edge, dir: 0, from: 0, to: snap.t } } },
|
||||
{ node: net.edgeB[snap.edge] as number, exit: { snap, step: { edge: snap.edge, dir: 1, from: 1, to: snap.t } } },
|
||||
];
|
||||
}
|
||||
|
||||
/** Both places on one edge (or at one station): the stretch between them, where the profile may go that way. */
|
||||
function directPath(costs: EdgeCosts, from: Snap, to: Snap, penalty: Float64Array | null): FoundPath | null {
|
||||
const sameSpot = from.edge < 0 ? to.edge < 0 && from.node === to.node : from.edge === to.edge && from.t === to.t;
|
||||
if (sameSpot) return { steps: [], cost: from.startCost + to.startCost, start: from, end: to };
|
||||
if (from.edge < 0 || from.edge !== to.edge) return null;
|
||||
const step: Step = { edge: from.edge, dir: to.t > from.t ? 0 : 1, from: from.t, to: to.t };
|
||||
const cost = stepCost(costs, step, penalty);
|
||||
if (!Number.isFinite(cost)) return null;
|
||||
return { steps: [step], cost: from.startCost + cost + to.startCost, start: from, end: to };
|
||||
}
|
||||
|
||||
interface Best {
|
||||
cost: number;
|
||||
node: number;
|
||||
exit: Exit | null;
|
||||
direct: FoundPath | null;
|
||||
}
|
||||
|
||||
/** The path back from the node an exit was taken at, to the entry it began with. */
|
||||
function unwind(net: SkiNet, state: SearchState, entries: Entry[], node: number, exit: Exit, cost: number): FoundPath {
|
||||
const steps: Step[] = [];
|
||||
if (exit.step) steps.push(exit.step);
|
||||
let at = node;
|
||||
while ((state.prevEdge[at] as number) >= 0) {
|
||||
const edge = state.prevEdge[at] as number;
|
||||
const dir = state.prevDir[at] as 0 | 1;
|
||||
steps.push(dir === 0 ? { edge, dir, from: 0, to: 1 } : { edge, dir, from: 1, to: 0 });
|
||||
at = dir === 0 ? (net.edgeA[edge] as number) : (net.edgeB[edge] as number);
|
||||
}
|
||||
const entry = entries[state.startOf[at] as number] as Entry;
|
||||
if (entry.step) steps.push(entry.step);
|
||||
steps.reverse();
|
||||
return { steps, cost, start: entry.snap, end: exit.snap };
|
||||
}
|
||||
|
||||
/**
|
||||
* The cheapest way from any start place to any end place, or why there is
|
||||
* none. `penalty` multiplies the cost of an edge (the alternatives' search);
|
||||
* `target` is the clicked end point, which the heuristic measures to.
|
||||
*/
|
||||
export function searchPath(
|
||||
net: SkiNet,
|
||||
costs: EdgeCosts,
|
||||
starts: readonly Snap[],
|
||||
ends: readonly Snap[],
|
||||
target: { lat: number; lng: number },
|
||||
budget: SearchBudget,
|
||||
penalty: Float64Array | null = null,
|
||||
): SearchOutcome {
|
||||
const state = stateOf(net);
|
||||
const h = (node: number) =>
|
||||
metresBetween(net.nodeLat[node] as number, net.nodeLng[node] as number, target.lat, target.lng) / costs.maxSpeed;
|
||||
const entries: Entry[] = [];
|
||||
const best: Best = { cost: Infinity, node: -1, exit: null, direct: null };
|
||||
|
||||
for (const start of starts) {
|
||||
for (const end of ends) {
|
||||
const direct = directPath(costs, start, end, penalty);
|
||||
if (direct && direct.cost < best.cost) Object.assign(best, { cost: direct.cost, direct });
|
||||
}
|
||||
for (const { node, entry } of entriesOf(net, start)) {
|
||||
const cost = start.startCost + (entry.step ? stepCost(costs, entry.step, penalty) : 0);
|
||||
if (!Number.isFinite(cost) || cost >= state.cost(node)) continue;
|
||||
entries.push(entry);
|
||||
state.set(node, cost, -1, 0, entries.length - 1);
|
||||
state.heap.push(node, cost + h(node));
|
||||
}
|
||||
}
|
||||
|
||||
const exits = new Map<number, Exit[]>();
|
||||
for (const end of ends) {
|
||||
for (const { node, exit } of exitsOf(net, end)) {
|
||||
const extra = end.startCost + (exit.step ? stepCost(costs, exit.step, penalty) : 0);
|
||||
if (!Number.isFinite(extra)) continue;
|
||||
exits.set(node, [...(exits.get(node) ?? []), { ...exit, extra }]);
|
||||
}
|
||||
}
|
||||
|
||||
let settledCount = 0;
|
||||
let nearest = -1;
|
||||
let nearestDistance = Infinity;
|
||||
while (state.heap.size > 0) {
|
||||
if (state.heap.peekKey() >= best.cost) break;
|
||||
const u = state.heap.pop();
|
||||
if (state.settled[u] === state.current) continue;
|
||||
state.settled[u] = state.current;
|
||||
settledCount++;
|
||||
if (settledCount > budget.maxSettled || ((settledCount & 1023) === 0 && Date.now() > budget.deadline)) {
|
||||
return { status: 'timeout', settled: settledCount };
|
||||
}
|
||||
const gu = state.cost(u);
|
||||
const remaining = h(u);
|
||||
if (remaining < nearestDistance) {
|
||||
nearestDistance = remaining;
|
||||
nearest = u;
|
||||
}
|
||||
for (const exit of exits.get(u) ?? []) {
|
||||
if (gu + exit.extra < best.cost) Object.assign(best, { cost: gu + exit.extra, node: u, exit, direct: null });
|
||||
}
|
||||
relax(net, costs, state, u, gu, h, penalty);
|
||||
}
|
||||
|
||||
if (best.direct) return { status: 'ok', path: best.direct, settled: settledCount };
|
||||
if (best.exit) {
|
||||
return { status: 'ok', path: unwind(net, state, entries, best.node, best.exit, best.cost), settled: settledCount };
|
||||
}
|
||||
const point = nearest >= 0 ? { lat: net.nodeLat[nearest] as number, lng: net.nodeLng[nearest] as number } : null;
|
||||
return { status: 'none', settled: settledCount, nearest: point };
|
||||
}
|
||||
|
||||
/** Every edge out of a settled node, in each direction the profile may travel it. */
|
||||
function relax(
|
||||
net: SkiNet,
|
||||
costs: EdgeCosts,
|
||||
state: SearchState,
|
||||
u: number,
|
||||
gu: number,
|
||||
h: (node: number) => number,
|
||||
penalty: Float64Array | null,
|
||||
): void {
|
||||
for (let i = net.adjStart[u] as number; i < (net.adjStart[u + 1] as number); i++) {
|
||||
const e = net.adjEdge[i] as number;
|
||||
const a = net.edgeA[e] as number;
|
||||
const b = net.edgeB[e] as number;
|
||||
if (a === b) continue;
|
||||
const dir: 0 | 1 = a === u ? 0 : 1;
|
||||
const v = dir === 0 ? b : a;
|
||||
const edgeCost = dir === 0 ? (costs.costFwd[e] as number) : (costs.costBack[e] as number);
|
||||
if (!Number.isFinite(edgeCost) || state.settled[v] === state.current) continue;
|
||||
const next = gu + edgeCost * (penalty ? (penalty[e] as number) : 1);
|
||||
if (next >= state.cost(v)) continue;
|
||||
state.set(v, next, e, dir, -1);
|
||||
state.heap.push(v, next + h(v));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,306 @@
|
||||
import { metresBetween } from '../../../lib/geo/geo';
|
||||
import { DIFF_UNKNOWN, DIFFICULTY_NAMES, EdgeFlag, Groom, Kind, LIFT_NAMES } from '../ski-graph.contract';
|
||||
import { dismountSeconds, liftClassOf, Mode, type EdgeCosts } from './profile';
|
||||
import type { Step } from './router';
|
||||
import type { SkiNet } from './stitch';
|
||||
import type { SkiFlag, SkiGeometryPoint, SkiLegSeconds, SkiRouteSegment, SkiSegmentKind, SkiWhy } from '@trek/shared';
|
||||
|
||||
/**
|
||||
* A found path as the planner reads it (spec 9.2): one line of points with
|
||||
* their heights, cut into stretches of one kind and one name (a run, a lift
|
||||
* with its wait, a link the data does not hold), with the time of each and
|
||||
* the totals, which are the stretches added up and nothing else.
|
||||
*/
|
||||
|
||||
interface BuiltLeg {
|
||||
geometry: SkiGeometryPoint[];
|
||||
segments: SkiRouteSegment[];
|
||||
distance_m: number;
|
||||
climb_m: number;
|
||||
descent_m: number;
|
||||
seconds: SkiLegSeconds;
|
||||
/** Every flag on the way and how many stretches of edge carry it, for the notes. */
|
||||
flagCounts: Map<SkiFlag, number>;
|
||||
}
|
||||
|
||||
/** The segment kind of an edge kind, before the mode it is travelled in says otherwise. */
|
||||
const KIND_SEGMENT: readonly SkiSegmentKind[] = [
|
||||
'run',
|
||||
'lift',
|
||||
'rail',
|
||||
'lift',
|
||||
'lift',
|
||||
'nordic',
|
||||
'skitour',
|
||||
'hike',
|
||||
'hike',
|
||||
'connection',
|
||||
'area',
|
||||
'link',
|
||||
'crossing',
|
||||
'walk',
|
||||
];
|
||||
|
||||
const DOWN_MODES: ReadonlySet<number> = new Set([Mode.LIFT_DOWN, Mode.BOARD_DOWN, Mode.ALIGHT_DOWN]);
|
||||
const UP_MODES: ReadonlySet<number> = new Set([Mode.LIFT, Mode.BOARD, Mode.ALIGHT]);
|
||||
const ON_FOOT_KINDS: ReadonlySet<number> = new Set([Kind.LINK, Kind.CROSSING, Kind.WALK]);
|
||||
|
||||
const GROOMING: ReadonlyArray<readonly [number, string]> = [
|
||||
[Groom.CLASSIC, 'classic'],
|
||||
[Groom.SKATING, 'skating'],
|
||||
[Groom.SCOOTER, 'scooter'],
|
||||
[Groom.BACKCOUNTRY, 'backcountry'],
|
||||
[Groom.MOGUL, 'mogul'],
|
||||
];
|
||||
|
||||
const EDGE_FLAGS: ReadonlyArray<readonly [number, SkiFlag]> = [
|
||||
[EdgeFlag.INFERRED_LINK, 'inferred_link'],
|
||||
[EdgeFlag.INFERRED_CROSSING, 'inferred_crossing'],
|
||||
[EdgeFlag.DIR_FROM_DEM, 'dir_from_dem'],
|
||||
[EdgeFlag.DIR_CONFLICT, 'dir_conflict'],
|
||||
[EdgeFlag.RELATION_INHERITED, 'relation_inherited'],
|
||||
[EdgeFlag.AREA_DERIVED, 'area_derived'],
|
||||
[EdgeFlag.TUNNEL, 'tunnel'],
|
||||
];
|
||||
|
||||
/** The flags the notes of a planned leg are built from (spec 7.6). */
|
||||
const WHY_FLAGS: readonly SkiFlag[] = [
|
||||
'ride_down',
|
||||
'dir_from_dem',
|
||||
'technique_assumed',
|
||||
'inferred_link',
|
||||
'relation_inherited',
|
||||
'area_derived',
|
||||
'difficulty_unknown',
|
||||
];
|
||||
|
||||
function segmentKind(net: SkiNet, e: number, mode: number): SkiSegmentKind {
|
||||
const kind = net.edgeKind[e] as number;
|
||||
if (DOWN_MODES.has(mode)) return 'lift_down';
|
||||
if (UP_MODES.has(mode)) return liftClassOf(net.edgeLift[e] as number) === 'rail' ? 'rail' : 'lift';
|
||||
if (mode === Mode.WALK && (kind === Kind.RUN || kind === Kind.AREA)) return 'crossing';
|
||||
return KIND_SEGMENT[kind] ?? 'walk';
|
||||
}
|
||||
|
||||
export function difficultyName(diff: number): SkiRouteSegment['difficulty'] {
|
||||
return diff === DIFF_UNKNOWN ? null : (DIFFICULTY_NAMES[diff] ?? null);
|
||||
}
|
||||
|
||||
const modeOf = (costs: EdgeCosts, step: Step): number =>
|
||||
(step.dir === 0 ? costs.modeFwd[step.edge] : costs.modeBack[step.edge]) as number;
|
||||
|
||||
/** The flags one stretch of edge carries, as travelled. */
|
||||
function stepFlags(net: SkiNet, costs: EdgeCosts, step: Step): SkiFlag[] {
|
||||
const flags = net.edgeFlags[step.edge] as number;
|
||||
const kind = net.edgeKind[step.edge] as number;
|
||||
const mode = modeOf(costs, step);
|
||||
const out = EDGE_FLAGS.filter(([bit]) => flags & bit).map(([, flag]) => flag);
|
||||
if (flags & EdgeFlag.TECHNIQUE_ASSUMED && mode === Mode.NORDIC) out.push('technique_assumed');
|
||||
if (DOWN_MODES.has(mode)) out.push('ride_down');
|
||||
if (mode === Mode.UPHILL_PISTE) out.push('uphill_on_piste');
|
||||
const descending = mode === Mode.DOWNHILL || mode === Mode.SKITOUR_DOWN;
|
||||
if (descending && (kind === Kind.RUN || kind === Kind.AREA) && net.edgeDiff[step.edge] === DIFF_UNKNOWN) {
|
||||
out.push('difficulty_unknown');
|
||||
}
|
||||
const arrives = step.to === 1 || step.to === 0;
|
||||
const node = step.dir === 0 ? (net.edgeB[step.edge] as number) : (net.edgeA[step.edge] as number);
|
||||
if (arrives && dismountSeconds(net, node) > 0) out.push('dismount');
|
||||
return out;
|
||||
}
|
||||
|
||||
/** The points of an edge between two shares of its length, in the direction travelled. */
|
||||
function stepPoints(net: SkiNet, step: Step): SkiGeometryPoint[] {
|
||||
const first = net.geomStart[step.edge] as number;
|
||||
const last = (net.geomStart[step.edge + 1] as number) - 1;
|
||||
const at: number[] = [0];
|
||||
for (let i = first; i < last; i++) {
|
||||
const piece = metresBetween(
|
||||
net.geomLat[i] as number,
|
||||
net.geomLng[i] as number,
|
||||
net.geomLat[i + 1] as number,
|
||||
net.geomLng[i + 1] as number,
|
||||
);
|
||||
at.push((at[at.length - 1] as number) + piece);
|
||||
}
|
||||
const total = at[at.length - 1] as number;
|
||||
const share = (k: number) => (total > 0 ? (at[k] as number) / total : k / Math.max(1, last - first));
|
||||
const pointAt = (f: number): SkiGeometryPoint => {
|
||||
let k = 0;
|
||||
while (k < last - first - 1 && share(k + 1) < f) k++;
|
||||
const span = share(k + 1) - share(k);
|
||||
const r = span > 0 ? Math.min(1, Math.max(0, (f - share(k)) / span)) : 0;
|
||||
const a = first + k;
|
||||
const ele = (net.geomEle[a] as number) + ((net.geomEle[a + 1] as number) - (net.geomEle[a] as number)) * r;
|
||||
return [
|
||||
(net.geomLat[a] as number) + ((net.geomLat[a + 1] as number) - (net.geomLat[a] as number)) * r,
|
||||
(net.geomLng[a] as number) + ((net.geomLng[a + 1] as number) - (net.geomLng[a] as number)) * r,
|
||||
Number.isFinite(ele) ? Math.round(ele) : null,
|
||||
];
|
||||
};
|
||||
const low = Math.min(step.from, step.to);
|
||||
const high = Math.max(step.from, step.to);
|
||||
const points: SkiGeometryPoint[] = [pointAt(low)];
|
||||
for (let k = 1; k < last - first; k++) {
|
||||
const f = share(k);
|
||||
if (f > low && f < high) {
|
||||
const ele = net.geomEle[first + k] as number;
|
||||
points.push([
|
||||
net.geomLat[first + k] as number,
|
||||
net.geomLng[first + k] as number,
|
||||
Number.isFinite(ele) ? ele : null,
|
||||
]);
|
||||
}
|
||||
}
|
||||
points.push(pointAt(high));
|
||||
return step.from <= step.to ? points : points.reverse();
|
||||
}
|
||||
|
||||
const samePoint = (a: SkiGeometryPoint, b: SkiGeometryPoint) =>
|
||||
Math.abs(a[0] - b[0]) < 1e-9 && Math.abs(a[1] - b[1]) < 1e-9;
|
||||
|
||||
interface Piece {
|
||||
key: string;
|
||||
segment: SkiRouteSegment;
|
||||
}
|
||||
|
||||
/** One stretch of edge as a segment of its own, before neighbours of the same kind and name are joined. */
|
||||
function stepSegment(net: SkiNet, costs: EdgeCosts, step: Step, from: number, to: number): Piece {
|
||||
const e = step.edge;
|
||||
const mode = modeOf(costs, step);
|
||||
const share = Math.abs(step.to - step.from);
|
||||
const time = ((step.dir === 0 ? costs.timeFwd[e] : costs.timeBack[e]) as number) * share;
|
||||
const kind = segmentKind(net, e, mode);
|
||||
const waits = mode === Mode.BOARD || mode === Mode.BOARD_DOWN;
|
||||
const lift = net.edgeLift[e] as number;
|
||||
const liftType = lift > 0 ? (LIFT_NAMES[lift] ?? null) : null;
|
||||
const pisteKind = kind === 'run' || kind === 'area' || kind === 'connection';
|
||||
const difficulty = pisteKind ? difficultyName(net.edgeDiff[e] as number) : null;
|
||||
const name = net.edgeName[e] ?? null;
|
||||
const ref = net.edgeRef[e] ?? null;
|
||||
const way = net.edgeWay[e] as number;
|
||||
return {
|
||||
key: [kind, name, ref, difficulty, liftType].join('|'),
|
||||
segment: {
|
||||
kind,
|
||||
from,
|
||||
to,
|
||||
name,
|
||||
ref,
|
||||
difficulty,
|
||||
lift_type: liftType,
|
||||
grooming: GROOMING.filter(([bit]) => (net.edgeGroom[e] as number) & bit).map(([, label]) => label),
|
||||
seconds: waits ? 0 : time,
|
||||
wait_seconds: waits ? time : 0,
|
||||
length_m: (net.edgeLen[e] as number) * share,
|
||||
flags: stepFlags(net, costs, step),
|
||||
osm_way: way > 0 ? way : null,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** Which of the four totals a stretch of edge counts towards. */
|
||||
function bucketOf(net: SkiNet, costs: EdgeCosts, step: Step): keyof SkiLegSeconds {
|
||||
const mode = modeOf(costs, step);
|
||||
if (mode === Mode.BOARD || mode === Mode.BOARD_DOWN) return 'wait';
|
||||
if (UP_MODES.has(mode) || DOWN_MODES.has(mode)) return 'lift';
|
||||
if (mode === Mode.WALK || ON_FOOT_KINDS.has(net.edgeKind[step.edge] as number)) return 'walk';
|
||||
return 'ski';
|
||||
}
|
||||
|
||||
/** A found path as a leg: its line, its stretches and its totals. */
|
||||
export function buildLeg(net: SkiNet, costs: EdgeCosts, steps: readonly Step[], start: [number, number, number]) {
|
||||
const geometry: SkiGeometryPoint[] = [];
|
||||
const pieces: Piece[] = [];
|
||||
const seconds: SkiLegSeconds = { ski: 0, lift: 0, wait: 0, walk: 0 };
|
||||
const flagCounts = new Map<SkiFlag, number>();
|
||||
let climb = 0;
|
||||
let descent = 0;
|
||||
let distance = 0;
|
||||
for (const step of steps) {
|
||||
if (Math.abs(step.to - step.from) < 1e-9) continue;
|
||||
const points = stepPoints(net, step);
|
||||
const last = geometry[geometry.length - 1];
|
||||
const joins = last !== undefined && samePoint(last, points[0] as SkiGeometryPoint);
|
||||
const from = joins ? geometry.length - 1 : geometry.length;
|
||||
geometry.push(...(joins ? points.slice(1) : points));
|
||||
const piece = stepSegment(net, costs, step, from, geometry.length - 1);
|
||||
pieces.push(piece);
|
||||
const share = Math.abs(step.to - step.from);
|
||||
const up = step.dir === 0 ? net.edgeUp[step.edge] : net.edgeDown[step.edge];
|
||||
const down = step.dir === 0 ? net.edgeDown[step.edge] : net.edgeUp[step.edge];
|
||||
climb += (up as number) * share;
|
||||
descent += (down as number) * share;
|
||||
distance += piece.segment.length_m;
|
||||
const bucket = bucketOf(net, costs, step);
|
||||
seconds[bucket] += piece.segment.seconds + piece.segment.wait_seconds;
|
||||
for (const flag of piece.segment.flags) flagCounts.set(flag, (flagCounts.get(flag) ?? 0) + 1);
|
||||
}
|
||||
if (geometry.length < 2) {
|
||||
// Both ends on one spot: a leg of no length, still a line of two points.
|
||||
const spot: SkiGeometryPoint = [start[0], start[1], Number.isFinite(start[2]) ? start[2] : null];
|
||||
geometry.splice(0, geometry.length, spot, [...spot]);
|
||||
pieces.splice(0, pieces.length, {
|
||||
key: 'walk',
|
||||
segment: {
|
||||
kind: 'walk',
|
||||
from: 0,
|
||||
to: 1,
|
||||
name: null,
|
||||
ref: null,
|
||||
difficulty: null,
|
||||
lift_type: null,
|
||||
grooming: [],
|
||||
seconds: 0,
|
||||
wait_seconds: 0,
|
||||
length_m: 0,
|
||||
flags: [],
|
||||
osm_way: null,
|
||||
},
|
||||
});
|
||||
}
|
||||
return {
|
||||
geometry,
|
||||
segments: joinPieces(pieces),
|
||||
distance_m: round1(distance),
|
||||
climb_m: Math.round(climb),
|
||||
descent_m: Math.round(descent),
|
||||
// Not rounded, here or in the segments: the totals are the segments added up, to the second.
|
||||
seconds,
|
||||
flagCounts,
|
||||
} satisfies BuiltLeg;
|
||||
}
|
||||
|
||||
const round1 = (value: number): number => Math.round(value * 10) / 10;
|
||||
|
||||
/** Neighbouring stretches of one kind and name as one segment; a lift's wait, ride and exit become one. */
|
||||
function joinPieces(pieces: readonly Piece[]): SkiRouteSegment[] {
|
||||
const out: Array<{ key: string; segment: SkiRouteSegment }> = [];
|
||||
for (const piece of pieces) {
|
||||
const previous = out[out.length - 1];
|
||||
if (previous && previous.key === piece.key) {
|
||||
const joined = previous.segment;
|
||||
joined.to = piece.segment.to;
|
||||
joined.seconds += piece.segment.seconds;
|
||||
joined.wait_seconds += piece.segment.wait_seconds;
|
||||
joined.length_m += piece.segment.length_m;
|
||||
joined.flags = [...new Set([...joined.flags, ...piece.segment.flags])];
|
||||
joined.grooming = [...new Set([...joined.grooming, ...piece.segment.grooming])];
|
||||
joined.osm_way ??= piece.segment.osm_way;
|
||||
continue;
|
||||
}
|
||||
out.push({ key: piece.key, segment: { ...piece.segment } });
|
||||
}
|
||||
return out.map(({ segment }) => ({ ...segment, length_m: round1(segment.length_m) }));
|
||||
}
|
||||
|
||||
/** The flag notes of a planned leg, from the flags its stretches carry. */
|
||||
export function flagNotes(flagCounts: ReadonlyMap<SkiFlag, number>): SkiWhy[] {
|
||||
return WHY_FLAGS.flatMap((flag) => {
|
||||
const count = flagCounts.get(flag) ?? 0;
|
||||
return count > 0 ? [{ kind: 'flag' as const, flag, count }] : [];
|
||||
});
|
||||
}
|
||||
|
||||
/** The total time of a built leg, waits included. */
|
||||
export const legSeconds = (leg: Pick<BuiltLeg, 'seconds'>): number =>
|
||||
leg.seconds.ski + leg.seconds.lift + leg.seconds.wait + leg.seconds.walk;
|
||||
@@ -0,0 +1,295 @@
|
||||
import { metresBetween, projectOnSegment } from '../../../lib/geo/geo';
|
||||
import { Kind, NodeFlag } from '../ski-graph.contract';
|
||||
import type { EdgeCosts } from './profile';
|
||||
import type { SkiNet } from './stitch';
|
||||
import type { SkiDiscipline } from '@trek/shared';
|
||||
|
||||
/**
|
||||
* Where a clicked point joins the network (spec 7.4). Up to five places on
|
||||
* the runs and trails the profile may use, the best one per edge, each a
|
||||
* virtual point at a share of its edge's length; the search may start from
|
||||
* any of them, so a click between two parallel runs finds the one that goes
|
||||
* somewhere. A click right beside a lift means the lift: its bottom station
|
||||
* for the start of a leg, its top station for the end.
|
||||
*/
|
||||
|
||||
/** How far a click may lie off the network and still join it, metres. */
|
||||
export const SNAP_RADIUS_M: Record<SkiDiscipline, number> = {
|
||||
alpine: 150,
|
||||
snowboard: 150,
|
||||
cross_country: 100,
|
||||
touring: 300,
|
||||
snowshoe: 300,
|
||||
winter_hike: 300,
|
||||
};
|
||||
|
||||
/** A click this close to a lift's line is taken for the lift. */
|
||||
export const LIFT_SNAP_M = 40;
|
||||
/** The most places a click joins the network at. */
|
||||
export const MAX_SNAPS = 5;
|
||||
/** Walking pace from the click to where it joins the network, m/s: what each place costs to reach. */
|
||||
const SNAP_WALK_SPEED = 1;
|
||||
|
||||
export interface Snap {
|
||||
/** The edge the point lies on, or -1 where the click took a lift station (`node`). */
|
||||
edge: number;
|
||||
node: number;
|
||||
/** The share of the edge's length from its first node to the point. */
|
||||
t: number;
|
||||
lat: number;
|
||||
lng: number;
|
||||
ele: number;
|
||||
/** Metres from the click. */
|
||||
distance: number;
|
||||
/** Seconds the search starts (or ends) the point with. */
|
||||
startCost: number;
|
||||
}
|
||||
|
||||
/** A coarse grid of the network's line pieces, for finding what lies near a click. */
|
||||
interface SegmentGrid {
|
||||
cells: Map<number, number[]>;
|
||||
}
|
||||
|
||||
const CELL_DEG = 0.002;
|
||||
const cellKey = (y: number, x: number): number => (y + 50_000) * 200_000 + (x + 100_000);
|
||||
|
||||
const grids = new WeakMap<SkiNet, SegmentGrid>();
|
||||
|
||||
/** Each line piece of the network under every grid cell its box touches, stored as `point index`. */
|
||||
function gridOf(net: SkiNet): SegmentGrid {
|
||||
const known = grids.get(net);
|
||||
if (known) return known;
|
||||
const cells = new Map<number, number[]>();
|
||||
for (let e = 0; e < net.edgeCount; e++) {
|
||||
for (let i = net.geomStart[e] as number; i < (net.geomStart[e + 1] as number) - 1; i++) {
|
||||
const y0 = Math.floor(Math.min(net.geomLat[i] as number, net.geomLat[i + 1] as number) / CELL_DEG);
|
||||
const y1 = Math.floor(Math.max(net.geomLat[i] as number, net.geomLat[i + 1] as number) / CELL_DEG);
|
||||
const x0 = Math.floor(Math.min(net.geomLng[i] as number, net.geomLng[i + 1] as number) / CELL_DEG);
|
||||
const x1 = Math.floor(Math.max(net.geomLng[i] as number, net.geomLng[i + 1] as number) / CELL_DEG);
|
||||
for (let y = y0; y <= y1; y++) {
|
||||
for (let x = x0; x <= x1; x++) {
|
||||
const key = cellKey(y, x);
|
||||
const list = cells.get(key);
|
||||
if (list) list.push(i);
|
||||
else cells.set(key, [i]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
const grid = { cells };
|
||||
grids.set(net, grid);
|
||||
return grid;
|
||||
}
|
||||
|
||||
/** The edge a point of the pool belongs to, by binary search over the edges' starts. */
|
||||
function edgeOfPoint(net: SkiNet, point: number): number {
|
||||
let lo = 0;
|
||||
let hi = net.edgeCount - 1;
|
||||
while (lo < hi) {
|
||||
const mid = (lo + hi + 1) >> 1;
|
||||
if ((net.geomStart[mid] as number) <= point) lo = mid;
|
||||
else hi = mid - 1;
|
||||
}
|
||||
return lo;
|
||||
}
|
||||
|
||||
interface Near {
|
||||
edge: number;
|
||||
/** The first point of the nearest line piece, and the share along that piece. */
|
||||
point: number;
|
||||
share: number;
|
||||
distance: number;
|
||||
}
|
||||
|
||||
/** The nearest spot of every edge with a line piece within `radius` of a point. */
|
||||
function nearEdges(net: SkiNet, lat: number, lng: number, radius: number): Map<number, Near> {
|
||||
const grid = gridOf(net);
|
||||
const dLat = radius / 111_195;
|
||||
const dLng = radius / (111_195 * Math.max(0.05, Math.cos((lat * Math.PI) / 180)));
|
||||
const best = new Map<number, Near>();
|
||||
const seen = new Set<number>();
|
||||
for (let y = Math.floor((lat - dLat) / CELL_DEG); y <= Math.floor((lat + dLat) / CELL_DEG); y++) {
|
||||
for (let x = Math.floor((lng - dLng) / CELL_DEG); x <= Math.floor((lng + dLng) / CELL_DEG); x++) {
|
||||
for (const point of grid.cells.get(cellKey(y, x)) ?? []) {
|
||||
if (seen.has(point)) continue;
|
||||
seen.add(point);
|
||||
const { t, distance } = projectOnSegment(
|
||||
lat,
|
||||
lng,
|
||||
net.geomLat[point] as number,
|
||||
net.geomLng[point] as number,
|
||||
net.geomLat[point + 1] as number,
|
||||
net.geomLng[point + 1] as number,
|
||||
);
|
||||
if (distance > radius) continue;
|
||||
const edge = edgeOfPoint(net, point);
|
||||
const known = best.get(edge);
|
||||
if (!known || distance < known.distance) best.set(edge, { edge, point, share: t, distance });
|
||||
}
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
/** The share of an edge's length at a spot on one of its line pieces, with the spot's height. */
|
||||
function spotOn(net: SkiNet, near: Near): { t: number; lat: number; lng: number; ele: number } {
|
||||
const first = net.geomStart[near.edge] as number;
|
||||
const last = (net.geomStart[near.edge + 1] as number) - 1;
|
||||
let total = 0;
|
||||
let before = 0;
|
||||
for (let i = first; i < last; i++) {
|
||||
const piece = metresBetween(
|
||||
net.geomLat[i] as number,
|
||||
net.geomLng[i] as number,
|
||||
net.geomLat[i + 1] as number,
|
||||
net.geomLng[i + 1] as number,
|
||||
);
|
||||
if (i < near.point) before += piece;
|
||||
if (i === near.point) before += piece * near.share;
|
||||
total += piece;
|
||||
}
|
||||
const a = near.point;
|
||||
const lerp = (values: Float64Array) =>
|
||||
(values[a] as number) + ((values[a + 1] as number) - (values[a] as number)) * near.share;
|
||||
return { t: total > 0 ? before / total : 0, lat: lerp(net.geomLat), lng: lerp(net.geomLng), ele: lerp(net.geomEle) };
|
||||
}
|
||||
|
||||
const LIFT_KINDS: ReadonlySet<number> = new Set([Kind.LIFT, Kind.RAIL]);
|
||||
const RIDE_KINDS: ReadonlySet<number> = new Set([Kind.LIFT, Kind.RAIL, Kind.BOARD, Kind.ALIGHT]);
|
||||
|
||||
/**
|
||||
* The ground nodes of a lift's stations: every one (`grounds`), and those the
|
||||
* profile may board at (`boards`) and leave at (`alights`).
|
||||
*/
|
||||
function stationsOf(net: SkiNet, costs: EdgeCosts, liftEdge: number) {
|
||||
const chain = new Set<number>([net.edgeA[liftEdge] as number, net.edgeB[liftEdge] as number]);
|
||||
const queue = [...chain];
|
||||
const grounds = new Set<number>();
|
||||
const boards: number[] = [];
|
||||
const alights: number[] = [];
|
||||
while (queue.length > 0) {
|
||||
const node = queue.pop() as number;
|
||||
for (let i = net.adjStart[node] as number; i < (net.adjStart[node + 1] as number); i++) {
|
||||
const e = net.adjEdge[i] as number;
|
||||
const kind = net.edgeKind[e] as number;
|
||||
const usable = Number.isFinite(costs.costFwd[e]);
|
||||
if (kind === Kind.BOARD && net.edgeB[e] === node) {
|
||||
grounds.add(net.edgeA[e] as number);
|
||||
if (usable) boards.push(net.edgeA[e] as number);
|
||||
}
|
||||
if (kind === Kind.ALIGHT && net.edgeA[e] === node) {
|
||||
grounds.add(net.edgeB[e] as number);
|
||||
if (usable) alights.push(net.edgeB[e] as number);
|
||||
}
|
||||
if (!LIFT_KINDS.has(kind)) continue;
|
||||
for (const next of [net.edgeA[e] as number, net.edgeB[e] as number]) {
|
||||
if (!chain.has(next) && (net.nodeFlags[next] as number) & NodeFlag.LIFT_INTERNAL) {
|
||||
chain.add(next);
|
||||
queue.push(next);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return { grounds: [...grounds], boards, alights };
|
||||
}
|
||||
|
||||
function nodeSnap(net: SkiNet, node: number, lat: number, lng: number): Snap {
|
||||
return {
|
||||
edge: -1,
|
||||
node,
|
||||
t: 0,
|
||||
lat: net.nodeLat[node] as number,
|
||||
lng: net.nodeLng[node] as number,
|
||||
ele: net.nodeEle[node] as number,
|
||||
distance: metresBetween(lat, lng, net.nodeLat[node] as number, net.nodeLng[node] as number),
|
||||
startCost: 0,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The station a click beside a lift means: the station it lies at, when it
|
||||
* lies at one; else the lift's lowest boarding for the start of a leg and its
|
||||
* highest exit for the end. Null when the profile may neither board nor leave.
|
||||
*/
|
||||
function stationSnap(
|
||||
net: SkiNet,
|
||||
costs: EdgeCosts,
|
||||
liftEdge: number,
|
||||
role: 'from' | 'to',
|
||||
lat: number,
|
||||
lng: number,
|
||||
): Snap | null {
|
||||
const { grounds: all, boards, alights } = stationsOf(net, costs, liftEdge);
|
||||
const atStation = all
|
||||
.map((ground) => nodeSnap(net, ground, lat, lng))
|
||||
.filter((snap) => snap.distance <= LIFT_SNAP_M)
|
||||
.sort((a, b) => a.distance - b.distance)[0];
|
||||
if (atStation) return atStation;
|
||||
const grounds = role === 'from' ? boards : alights;
|
||||
if (grounds.length === 0) return null;
|
||||
// A station without a height counts as neither the lowest nor the highest.
|
||||
const height = (ground: number) => {
|
||||
const ele = net.nodeEle[ground] as number;
|
||||
if (!Number.isNaN(ele)) return ele;
|
||||
return role === 'from' ? Infinity : -Infinity;
|
||||
};
|
||||
let node = grounds[0] as number;
|
||||
for (const ground of grounds) {
|
||||
const better = role === 'from' ? height(ground) < height(node) : height(ground) > height(node);
|
||||
if (better) node = ground;
|
||||
}
|
||||
return nodeSnap(net, node, lat, lng);
|
||||
}
|
||||
|
||||
/**
|
||||
* Where a clicked point joins the network for a profile: a lift station when
|
||||
* the click lies beside a lift and nearer to it than to anything skiable,
|
||||
* else up to five places on edges the profile may use, nearest first.
|
||||
*/
|
||||
export function snapPoint(
|
||||
net: SkiNet,
|
||||
costs: EdgeCosts,
|
||||
lat: number,
|
||||
lng: number,
|
||||
radius: number,
|
||||
role: 'from' | 'to',
|
||||
): Snap[] {
|
||||
const near = nearEdges(net, lat, lng, Math.max(radius, LIFT_SNAP_M));
|
||||
const usable: Near[] = [];
|
||||
let lift: Near | null = null;
|
||||
for (const spot of near.values()) {
|
||||
const kind = net.edgeKind[spot.edge] as number;
|
||||
if (LIFT_KINDS.has(kind)) {
|
||||
if (spot.distance <= LIFT_SNAP_M && (!lift || spot.distance < lift.distance)) lift = spot;
|
||||
continue;
|
||||
}
|
||||
if (RIDE_KINDS.has(kind) || spot.distance > radius) continue;
|
||||
if (Number.isFinite(costs.costFwd[spot.edge]) || Number.isFinite(costs.costBack[spot.edge])) usable.push(spot);
|
||||
}
|
||||
usable.sort((a, b) => a.distance - b.distance);
|
||||
if (lift && (usable.length === 0 || lift.distance < (usable[0] as Near).distance)) {
|
||||
const station = stationSnap(net, costs, lift.edge, role, lat, lng);
|
||||
if (station) return [station];
|
||||
}
|
||||
return usable.slice(0, MAX_SNAPS).map((spot) => {
|
||||
const at = spotOn(net, spot);
|
||||
return { edge: spot.edge, node: -1, ...at, distance: spot.distance, startCost: spot.distance / SNAP_WALK_SPEED };
|
||||
});
|
||||
}
|
||||
|
||||
/** The nearest edge a profile may use within `radius`, for telling how far off the network a point lies. */
|
||||
export function nearestUsable(
|
||||
net: SkiNet,
|
||||
costs: EdgeCosts,
|
||||
lat: number,
|
||||
lng: number,
|
||||
radius: number,
|
||||
): { edge: number; distance: number } | null {
|
||||
let best: { edge: number; distance: number } | null = null;
|
||||
for (const spot of nearEdges(net, lat, lng, radius).values()) {
|
||||
if (RIDE_KINDS.has(net.edgeKind[spot.edge] as number)) continue;
|
||||
if (!Number.isFinite(costs.costFwd[spot.edge]) && !Number.isFinite(costs.costBack[spot.edge])) continue;
|
||||
if (!best || spot.distance < best.distance) best = { edge: spot.edge, distance: spot.distance };
|
||||
}
|
||||
return best;
|
||||
}
|
||||
@@ -0,0 +1,215 @@
|
||||
import { poolString } from '../ski-graph';
|
||||
import { ELE_MISSING, EdgeFlag, NodeFlag, type SkiGraphData } from '../ski-graph.contract';
|
||||
|
||||
/**
|
||||
* The network the router searches: one area's graph, or up to four pieces of
|
||||
* a large network stitched together. Coordinates are degrees, heights metres
|
||||
* (NaN where the terrain data has none), names read out of the string pools,
|
||||
* and every node knows its edges.
|
||||
*
|
||||
* Stitching follows the writer's own check (`stitch` in `winter/qa.py`): a
|
||||
* node flagged `boundary` with a positive OSM id is one node in every piece
|
||||
* that holds it, and an edge two pieces both carry (the halo one piece keeps
|
||||
* of its neighbour) is kept once, the copy without `halo` winning. A synthetic
|
||||
* node (negative id) is never joined to anything.
|
||||
*/
|
||||
export interface SkiNet {
|
||||
areaIds: string[];
|
||||
colourScheme: 'europe' | 'north_america';
|
||||
nodeCount: number;
|
||||
edgeCount: number;
|
||||
nodeLat: Float64Array;
|
||||
nodeLng: Float64Array;
|
||||
nodeEle: Float64Array;
|
||||
nodeFlags: Uint16Array;
|
||||
nodeOsm: Float64Array;
|
||||
edgeA: Uint32Array;
|
||||
edgeB: Uint32Array;
|
||||
edgeLen: Float64Array;
|
||||
edgeUp: Float64Array;
|
||||
edgeDown: Float64Array;
|
||||
edgeKind: Uint8Array;
|
||||
edgeFwd: Uint16Array;
|
||||
edgeBack: Uint16Array;
|
||||
edgeDiff: Uint8Array;
|
||||
edgeGroom: Uint8Array;
|
||||
edgeLift: Uint8Array;
|
||||
edgeLiftSec: Uint16Array;
|
||||
edgeLiftCap: Uint16Array;
|
||||
edgeFlags: Uint32Array;
|
||||
edgeName: Array<string | null>;
|
||||
edgeRef: Array<string | null>;
|
||||
edgeWay: Float64Array;
|
||||
/** Where each edge's points start in the point pool; `geomStart[e + 1]` is where they end. */
|
||||
geomStart: Uint32Array;
|
||||
geomLat: Float64Array;
|
||||
geomLng: Float64Array;
|
||||
geomEle: Float64Array;
|
||||
/** The edges at each node: `adjEdge[adjStart[n] .. adjStart[n + 1]]`. */
|
||||
adjStart: Uint32Array;
|
||||
adjEdge: Uint32Array;
|
||||
/** Roughly what the arrays take, for the cache's budget. */
|
||||
bytes: number;
|
||||
}
|
||||
|
||||
interface EdgeRef {
|
||||
graph: SkiGraphData;
|
||||
index: number;
|
||||
remap: Int32Array;
|
||||
halo: boolean;
|
||||
}
|
||||
|
||||
/** An edge's identity across pieces: its way and its exact line. */
|
||||
function edgeKey(graph: SkiGraphData, e: number): string {
|
||||
const start = graph.edgeGeomOff[e] as number;
|
||||
const end = graph.edgeGeomOff[e + 1] as number;
|
||||
const parts: number[] = [graph.edgeWay[e] as number];
|
||||
for (let i = start; i < end; i++) parts.push(graph.geomLatE7[i] as number, graph.geomLngE7[i] as number);
|
||||
return parts.join(',');
|
||||
}
|
||||
|
||||
const metres = (value: number): number => (value === ELE_MISSING ? Number.NaN : value);
|
||||
|
||||
/** The edges to keep of all pieces, in the order they were first met, and each piece's node numbering. */
|
||||
function collect(graphs: readonly SkiGraphData[]) {
|
||||
const byOsm = new Map<number, number>();
|
||||
const nodes: Array<{ graph: SkiGraphData; index: number }> = [];
|
||||
const edges = new Map<string, EdgeRef>();
|
||||
let anonymous = 0;
|
||||
for (const graph of graphs) {
|
||||
const remap = new Int32Array(graph.header.nodeCount);
|
||||
for (let i = 0; i < graph.header.nodeCount; i++) {
|
||||
const osm = graph.nodeOsm[i] as number;
|
||||
const stitchable = graphs.length > 1 && osm > 0 && ((graph.nodeFlags[i] as number) & NodeFlag.BOUNDARY) !== 0;
|
||||
const known = stitchable ? byOsm.get(osm) : undefined;
|
||||
if (known !== undefined) {
|
||||
remap[i] = known;
|
||||
continue;
|
||||
}
|
||||
remap[i] = nodes.length;
|
||||
if (stitchable) byOsm.set(osm, nodes.length);
|
||||
nodes.push({ graph, index: i });
|
||||
}
|
||||
for (let e = 0; e < graph.header.edgeCount; e++) {
|
||||
const halo = ((graph.edgeFlags[e] as number) & EdgeFlag.HALO) !== 0;
|
||||
// One piece alone has nothing to deduplicate.
|
||||
const key = graphs.length > 1 ? edgeKey(graph, e) : String(anonymous++);
|
||||
const kept = edges.get(key);
|
||||
if (kept && (halo || !kept.halo)) continue;
|
||||
edges.set(key, { graph, index: e, remap, halo });
|
||||
}
|
||||
}
|
||||
return { nodes, edges: [...edges.values()] };
|
||||
}
|
||||
|
||||
/** The network of one area (or of the pieces of one) as the router searches it. */
|
||||
export function stitchGraphs(graphs: readonly SkiGraphData[]): SkiNet {
|
||||
if (graphs.length === 0) throw new Error('No graph to stitch');
|
||||
const { nodes, edges } = collect(graphs);
|
||||
const n = nodes.length;
|
||||
const m = edges.length;
|
||||
let points = 0;
|
||||
for (const { graph, index } of edges) {
|
||||
points += (graph.edgeGeomOff[index + 1] as number) - (graph.edgeGeomOff[index] as number);
|
||||
}
|
||||
|
||||
const net: SkiNet = {
|
||||
areaIds: graphs.map((graph) => graph.header.areaId ?? ''),
|
||||
colourScheme: graphs[0]?.header.colourScheme === 'north_america' ? 'north_america' : 'europe',
|
||||
nodeCount: n,
|
||||
edgeCount: m,
|
||||
nodeLat: new Float64Array(n),
|
||||
nodeLng: new Float64Array(n),
|
||||
nodeEle: new Float64Array(n),
|
||||
nodeFlags: new Uint16Array(n),
|
||||
nodeOsm: new Float64Array(n),
|
||||
edgeA: new Uint32Array(m),
|
||||
edgeB: new Uint32Array(m),
|
||||
edgeLen: new Float64Array(m),
|
||||
edgeUp: new Float64Array(m),
|
||||
edgeDown: new Float64Array(m),
|
||||
edgeKind: new Uint8Array(m),
|
||||
edgeFwd: new Uint16Array(m),
|
||||
edgeBack: new Uint16Array(m),
|
||||
edgeDiff: new Uint8Array(m),
|
||||
edgeGroom: new Uint8Array(m),
|
||||
edgeLift: new Uint8Array(m),
|
||||
edgeLiftSec: new Uint16Array(m),
|
||||
edgeLiftCap: new Uint16Array(m),
|
||||
edgeFlags: new Uint32Array(m),
|
||||
edgeName: new Array<string | null>(m),
|
||||
edgeRef: new Array<string | null>(m),
|
||||
edgeWay: new Float64Array(m),
|
||||
geomStart: new Uint32Array(m + 1),
|
||||
geomLat: new Float64Array(points),
|
||||
geomLng: new Float64Array(points),
|
||||
geomEle: new Float64Array(points),
|
||||
adjStart: new Uint32Array(n + 1),
|
||||
adjEdge: new Uint32Array(2 * m),
|
||||
bytes: 0,
|
||||
};
|
||||
|
||||
nodes.forEach(({ graph, index }, i) => {
|
||||
net.nodeLat[i] = (graph.nodeLatE7[index] as number) / 1e7;
|
||||
net.nodeLng[i] = (graph.nodeLngE7[index] as number) / 1e7;
|
||||
net.nodeEle[i] = metres(graph.nodeEle[index] as number);
|
||||
net.nodeFlags[i] = graph.nodeFlags[index] as number;
|
||||
net.nodeOsm[i] = graph.nodeOsm[index] as number;
|
||||
});
|
||||
|
||||
let at = 0;
|
||||
edges.forEach(({ graph, index, remap }, e) => {
|
||||
net.edgeA[e] = remap[graph.edgeA[index] as number] as number;
|
||||
net.edgeB[e] = remap[graph.edgeB[index] as number] as number;
|
||||
net.edgeLen[e] = graph.edgeLen[index] as number;
|
||||
net.edgeUp[e] = graph.edgeUp[index] as number;
|
||||
net.edgeDown[e] = graph.edgeDown[index] as number;
|
||||
net.edgeKind[e] = graph.edgeKind[index] as number;
|
||||
net.edgeFwd[e] = graph.edgeFwdUses[index] as number;
|
||||
net.edgeBack[e] = graph.edgeBackUses[index] as number;
|
||||
net.edgeDiff[e] = graph.edgeDiff[index] as number;
|
||||
net.edgeGroom[e] = graph.edgeGroom[index] as number;
|
||||
net.edgeLift[e] = graph.edgeLift[index] as number;
|
||||
net.edgeLiftSec[e] = graph.edgeLiftSec[index] as number;
|
||||
net.edgeLiftCap[e] = graph.edgeLiftCap[index] as number;
|
||||
net.edgeFlags[e] = graph.edgeFlags[index] as number;
|
||||
net.edgeName[e] = poolString(graph.strings, graph.edgeName[index] as number);
|
||||
net.edgeRef[e] = poolString(graph.strings, graph.edgeRef[index] as number);
|
||||
net.edgeWay[e] = graph.edgeWay[index] as number;
|
||||
net.geomStart[e] = at;
|
||||
for (let i = graph.edgeGeomOff[index] as number; i < (graph.edgeGeomOff[index + 1] as number); i++) {
|
||||
net.geomLat[at] = (graph.geomLatE7[i] as number) / 1e7;
|
||||
net.geomLng[at] = (graph.geomLngE7[i] as number) / 1e7;
|
||||
net.geomEle[at] = metres(graph.geomEle[i] as number);
|
||||
at++;
|
||||
}
|
||||
});
|
||||
net.geomStart[m] = at;
|
||||
buildAdjacency(net);
|
||||
net.bytes = n * 34 + m * 80 + points * 24;
|
||||
return net;
|
||||
}
|
||||
|
||||
/** Every node's edges, a self-loop listed once. */
|
||||
function buildAdjacency(net: SkiNet): void {
|
||||
const degree = new Uint32Array(net.nodeCount + 1);
|
||||
for (let e = 0; e < net.edgeCount; e++) {
|
||||
const a = net.edgeA[e] as number;
|
||||
const b = net.edgeB[e] as number;
|
||||
degree[a + 1] = (degree[a + 1] as number) + 1;
|
||||
if (b !== a) degree[b + 1] = (degree[b + 1] as number) + 1;
|
||||
}
|
||||
for (let i = 1; i <= net.nodeCount; i++) degree[i] = (degree[i] as number) + (degree[i - 1] as number);
|
||||
net.adjStart.set(degree);
|
||||
const fill = degree.slice(0, net.nodeCount);
|
||||
for (let e = 0; e < net.edgeCount; e++) {
|
||||
const a = net.edgeA[e] as number;
|
||||
const b = net.edgeB[e] as number;
|
||||
net.adjEdge[fill[a] as number] = e;
|
||||
fill[a] = (fill[a] as number) + 1;
|
||||
if (b !== a) {
|
||||
net.adjEdge[fill[b] as number] = e;
|
||||
fill[b] = (fill[b] as number) + 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
import { logError, logInfo } from '../audit/audit-log.logger';
|
||||
import { CronRegistrarService } from '../scheduling/cron-registrar.service';
|
||||
import { SkiAreasService } from './ski-areas.service';
|
||||
import { Injectable, type OnApplicationBootstrap } from '@nestjs/common';
|
||||
|
||||
/**
|
||||
* The daily look at the Places host's winter layer (spec 7.2): when it serves
|
||||
* a new build, the index is fetched, and every area kept here whose graph
|
||||
* changed is fetched again, so a planner opening a tour tomorrow does not
|
||||
* wait for it. Area files unused for 90 days go. Nothing runs while TREK
|
||||
* Places is switched off.
|
||||
*/
|
||||
@Injectable()
|
||||
export class SkiAreasJob implements OnApplicationBootstrap {
|
||||
constructor(
|
||||
private readonly areas: SkiAreasService,
|
||||
private readonly registrar: CronRegistrarService,
|
||||
) {}
|
||||
|
||||
onApplicationBootstrap(): void {
|
||||
if (!this.registrar.isEnabled()) return;
|
||||
this.registrar.register('ski-areas', '40 4 * * *', () => this.tick());
|
||||
}
|
||||
|
||||
async tick(): Promise<void> {
|
||||
try {
|
||||
const swept = await this.areas.sweep(Date.now());
|
||||
if (swept > 0) logInfo(`[Ski] ${swept} ski area files unused for 90 days removed`);
|
||||
if (!this.areas.enabled()) return;
|
||||
if ((await this.areas.refresh()) !== 'updated') return;
|
||||
await this.refreshKept();
|
||||
} catch (err: unknown) {
|
||||
logError(`[Ski] daily ski area check: ${err instanceof Error ? err.message : String(err)}`);
|
||||
}
|
||||
}
|
||||
|
||||
/** The areas kept here whose graph the new build changed, fetched again. */
|
||||
private async refreshKept(): Promise<void> {
|
||||
const index = await this.areas.index();
|
||||
if (!index) return;
|
||||
const kept = await this.areas.keptAreas();
|
||||
const changed = index.areas.filter((area) =>
|
||||
kept.some((copy) => copy.id === area.row.id && copy.sha8 !== area.row.sha256.slice(0, 8)),
|
||||
);
|
||||
const outcomes = await Promise.allSettled(changed.map((area) => this.areas.ensureArea(area.row)));
|
||||
const failed = outcomes.filter((outcome) => outcome.status === 'rejected').length;
|
||||
if (changed.length === 0) return;
|
||||
logInfo(`[Ski] ${changed.length - failed} of ${changed.length} kept ski areas fetched anew`);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,406 @@
|
||||
import { DataPathsService } from '../app-config/data-paths.service';
|
||||
import { logError, logInfo, logWarn } from '../audit/audit-log.logger';
|
||||
import { TrekPlacesWinterService } from '../maps/trek-places-winter.service';
|
||||
import { SGR_FORMAT } from './ski-graph.contract';
|
||||
import { Injectable, type OnApplicationBootstrap } from '@nestjs/common';
|
||||
import {
|
||||
winterAttributionSchema,
|
||||
winterIndexSchema,
|
||||
type WinterIndex,
|
||||
type WinterIndexRow,
|
||||
type WinterMeta,
|
||||
} from '@trek/shared';
|
||||
|
||||
import { createHash } from 'node:crypto';
|
||||
import { existsSync } from 'node:fs';
|
||||
import { mkdir, readFile, readdir, rename, rm, stat, utimes, writeFile } from 'node:fs/promises';
|
||||
import { join } from 'node:path';
|
||||
import { z } from 'zod';
|
||||
|
||||
/**
|
||||
* The ski areas the piste router plans on (spec 7.2, 7.3): the Places host's
|
||||
* index of every area, and each area's graph as it was downloaded. No table:
|
||||
* the index is a file `data/ski/index-<sha8>.json`, each area a file
|
||||
* `data/ski/areas/<id>@<sha8>.sgr.gz`, written beside its name and renamed
|
||||
* into place. An area is downloaded once, when a planner first plans in it,
|
||||
* and checked against the index's checksum before it is kept; a copy of an
|
||||
* older build stays as the fallback while the Places host cannot be reached.
|
||||
*/
|
||||
|
||||
/** One area of the index with where its padded box lies. */
|
||||
export interface IndexedArea {
|
||||
row: WinterIndexRow;
|
||||
minLat: number;
|
||||
minLng: number;
|
||||
maxLat: number;
|
||||
maxLng: number;
|
||||
}
|
||||
|
||||
export interface SkiIndex {
|
||||
build: string;
|
||||
indexSha: string;
|
||||
attribution: string;
|
||||
areas: IndexedArea[];
|
||||
/** Area positions by 0.1 degree cell of their padded box. */
|
||||
grid: Map<number, number[]>;
|
||||
}
|
||||
|
||||
/** An area's graph file, and whether it is an older build kept for when the Places host is down. */
|
||||
export interface AreaFile {
|
||||
file: string;
|
||||
stale: boolean;
|
||||
}
|
||||
|
||||
/** Why a leg has no area to be planned on. */
|
||||
type AreaPick =
|
||||
| { status: 'ok'; areas: IndexedArea[] }
|
||||
| { status: 'no_area'; at: { lat: number; lng: number } }
|
||||
| { status: 'cross_area'; at: { lat: number; lng: number } };
|
||||
|
||||
/** An area's box is widened by this much, so a click just past its outermost run still finds it. */
|
||||
const PAD_M = 300;
|
||||
/** At most this many areas are stitched for one leg. */
|
||||
const MAX_AREAS = 4;
|
||||
const CELL_DEG = 0.1;
|
||||
/** An area a download failed for counts as unavailable this long. */
|
||||
const FAILED_FOR_MS = 5 * 60 * 1000;
|
||||
/** Area files not used for this long are swept. */
|
||||
export const UNUSED_FOR_MS = 90 * 24 * 60 * 60 * 1000;
|
||||
export const DEFAULT_ATTRIBUTION = '© OpenStreetMap contributors, ODbL. Terrain: Mapzen Terrarium';
|
||||
|
||||
const storedIndexSchema = z.object({
|
||||
meta: z.object({ build: z.string(), indexSha: z.string(), attribution: winterAttributionSchema }),
|
||||
index: winterIndexSchema,
|
||||
});
|
||||
|
||||
const cellKey = (y: number, x: number): number => (y + 1000) * 10_000 + (x + 2000);
|
||||
const safeId = (id: string): string => id.replace(':', '_');
|
||||
const sha256 = (bytes: Buffer): string => createHash('sha256').update(bytes).digest('hex');
|
||||
|
||||
function indexed(row: WinterIndexRow): IndexedArea {
|
||||
const [minLng, minLat, maxLng, maxLat] = row.bbox;
|
||||
const padLat = PAD_M / 111_195;
|
||||
const padLng = PAD_M / (111_195 * Math.max(0.05, Math.cos((((minLat + maxLat) / 2) * Math.PI) / 180)));
|
||||
return { row, minLat: minLat - padLat, minLng: minLng - padLng, maxLat: maxLat + padLat, maxLng: maxLng + padLng };
|
||||
}
|
||||
|
||||
function contains(area: IndexedArea, point: { lat: number; lng: number }): boolean {
|
||||
return point.lat >= area.minLat && point.lat <= area.maxLat && point.lng >= area.minLng && point.lng <= area.maxLng;
|
||||
}
|
||||
|
||||
function touches(a: IndexedArea, b: IndexedArea): boolean {
|
||||
return a.minLat <= b.maxLat && b.minLat <= a.maxLat && a.minLng <= b.maxLng && b.minLng <= a.maxLng;
|
||||
}
|
||||
|
||||
/** The id an area's pieces share: `w:12` for `w:12-1a`. */
|
||||
const baseId = (id: string): string => id.split('-')[0] as string;
|
||||
|
||||
function distanceTo(area: IndexedArea, point: { lat: number; lng: number }): number {
|
||||
const lat = (area.minLat + area.maxLat) / 2;
|
||||
const lng = (area.minLng + area.maxLng) / 2;
|
||||
return Math.hypot(lat - point.lat, (lng - point.lng) * Math.cos((point.lat * Math.PI) / 180));
|
||||
}
|
||||
|
||||
export function buildIndex(meta: Pick<WinterMeta, 'build' | 'indexSha' | 'attribution'>, index: WinterIndex): SkiIndex {
|
||||
const areas = index.areas.map(indexed);
|
||||
const grid = new Map<number, number[]>();
|
||||
areas.forEach((area, position) => {
|
||||
for (let y = Math.floor(area.minLat / CELL_DEG); y <= Math.floor(area.maxLat / CELL_DEG); y++) {
|
||||
for (let x = Math.floor(area.minLng / CELL_DEG); x <= Math.floor(area.maxLng / CELL_DEG); x++) {
|
||||
const key = cellKey(y, x);
|
||||
grid.set(key, [...(grid.get(key) ?? []), position]);
|
||||
}
|
||||
}
|
||||
});
|
||||
const attribution = `${meta.attribution.data}. ${meta.attribution.terrain}`;
|
||||
return { build: meta.build, indexSha: meta.indexSha, attribution, areas, grid };
|
||||
}
|
||||
|
||||
/** The areas whose padded box holds a point, nearest first. */
|
||||
export function areasAt(index: SkiIndex, point: { lat: number; lng: number }): IndexedArea[] {
|
||||
const key = cellKey(Math.floor(point.lat / CELL_DEG), Math.floor(point.lng / CELL_DEG));
|
||||
return (index.grid.get(key) ?? ([] as number[]))
|
||||
.map((position) => index.areas[position] as IndexedArea)
|
||||
.filter((area) => contains(area, point))
|
||||
.sort((a, b) => distanceTo(a, point) - distanceTo(b, point));
|
||||
}
|
||||
|
||||
/**
|
||||
* The areas a leg is planned on: those holding its ends, with the pieces of
|
||||
* the same network that touch them, at most four, nearest first. Ends in two
|
||||
* areas that do not touch are two ski areas, not one leg.
|
||||
*/
|
||||
export function pickAreas(
|
||||
index: SkiIndex,
|
||||
leg: { from: { lat: number; lng: number }; to: { lat: number; lng: number } },
|
||||
): AreaPick {
|
||||
const atFrom = areasAt(index, leg.from);
|
||||
if (atFrom.length === 0) return { status: 'no_area', at: leg.from };
|
||||
const atTo = areasAt(index, leg.to);
|
||||
if (atTo.length === 0) return { status: 'no_area', at: leg.to };
|
||||
const picked = new Map<string, IndexedArea>();
|
||||
for (const area of [...atFrom, ...atTo]) picked.set(area.row.id, area);
|
||||
const shared = atFrom.some((a) => atTo.some((b) => a.row.id === b.row.id));
|
||||
if (!shared && !atFrom.some((a) => atTo.some((b) => touches(a, b)))) return { status: 'cross_area', at: leg.to };
|
||||
// Pieces of a split network between the two ends, so the stitch has its halo.
|
||||
const bases = new Set([...picked.values()].map((area) => baseId(area.row.id)));
|
||||
const middle = { lat: (leg.from.lat + leg.to.lat) / 2, lng: (leg.from.lng + leg.to.lng) / 2 };
|
||||
for (const area of areasAt(index, middle)) {
|
||||
if (bases.has(baseId(area.row.id))) picked.set(area.row.id, area);
|
||||
}
|
||||
const areas = [...picked.values()].sort((a, b) => distanceTo(a, leg.from) - distanceTo(b, leg.from));
|
||||
return { status: 'ok', areas: areas.slice(0, MAX_AREAS) };
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class SkiAreasService implements OnApplicationBootstrap {
|
||||
private current: SkiIndex | null = null;
|
||||
private loading: Promise<SkiIndex | null> | null = null;
|
||||
private readonly downloads = new Map<string, Promise<void>>();
|
||||
private readonly failedAt = new Map<string, number>();
|
||||
|
||||
constructor(
|
||||
private readonly paths: DataPathsService,
|
||||
private readonly winter: TrekPlacesWinterService,
|
||||
) {}
|
||||
|
||||
private dir(): string {
|
||||
return join(this.paths.dataDir, 'ski');
|
||||
}
|
||||
|
||||
private areasDir(): string {
|
||||
return join(this.dir(), 'areas');
|
||||
}
|
||||
|
||||
fileOf(row: WinterIndexRow): string {
|
||||
return join(this.areasDir(), `${safeId(row.id)}@${row.sha256.slice(0, 8)}.sgr.gz`);
|
||||
}
|
||||
|
||||
/** Halves of a write a crash left are cleared at boot. */
|
||||
async onApplicationBootstrap(): Promise<void> {
|
||||
try {
|
||||
await this.sweep(Date.now(), { tempOnly: true });
|
||||
} catch (err) {
|
||||
logError(`[Ski] clearing half-written files: ${err instanceof Error ? err.message : String(err)}`);
|
||||
}
|
||||
}
|
||||
|
||||
/** Whether the operator lets anything go to the Places host. */
|
||||
enabled(): boolean {
|
||||
return this.winter.enabled();
|
||||
}
|
||||
|
||||
/** The index of ski areas: in memory, else as kept on disk, else fetched. Null when none can be had. */
|
||||
index(): Promise<SkiIndex | null> {
|
||||
if (this.current) return Promise.resolve(this.current);
|
||||
if (!this.loading) {
|
||||
this.loading = this.loadIndex().finally(() => {
|
||||
this.loading = null;
|
||||
});
|
||||
}
|
||||
return this.loading;
|
||||
}
|
||||
|
||||
private async loadIndex(): Promise<SkiIndex | null> {
|
||||
const kept = await this.readKeptIndex();
|
||||
if (kept) {
|
||||
this.current = kept;
|
||||
return kept;
|
||||
}
|
||||
if (!this.winter.enabled()) return null;
|
||||
try {
|
||||
await this.refresh();
|
||||
} catch (err) {
|
||||
logWarn(`[Ski] fetching the ski area index: ${err instanceof Error ? err.message : String(err)}`);
|
||||
}
|
||||
return this.current;
|
||||
}
|
||||
|
||||
private async readKeptIndex(): Promise<SkiIndex | null> {
|
||||
let names: string[];
|
||||
try {
|
||||
names = (await readdir(this.dir())).filter((name) => name.startsWith('index-') && name.endsWith('.json'));
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
const read = await Promise.all(names.map((name) => this.readIndexFile(name)));
|
||||
const newest = read
|
||||
.filter((kept): kept is { at: number; index: SkiIndex } => kept !== null)
|
||||
.sort((a, b) => b.at - a.at)[0];
|
||||
return newest?.index ?? null;
|
||||
}
|
||||
|
||||
private async readIndexFile(name: string): Promise<{ at: number; index: SkiIndex } | null> {
|
||||
const file = join(this.dir(), name);
|
||||
try {
|
||||
const stored = storedIndexSchema.parse(JSON.parse(await readFile(file, 'utf8')));
|
||||
return { at: (await stat(file)).mtimeMs, index: buildIndex(stored.meta, stored.index) };
|
||||
} catch {
|
||||
logWarn(`[Ski] the kept index ${name} does not read; it is skipped`);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Asks the Places host which build it serves and fetches the index when it
|
||||
* is not the one held. An index whose checksum is not the one the host
|
||||
* announced, or of a format this build cannot read, is not taken: the one
|
||||
* held stays. Throws when the host cannot be reached.
|
||||
*/
|
||||
async refresh(): Promise<'unchanged' | 'updated' | 'refused'> {
|
||||
const meta = await this.winter.meta();
|
||||
if (this.current?.indexSha === meta.indexSha) return 'unchanged';
|
||||
if (meta.format !== SGR_FORMAT) {
|
||||
logWarn(`[Ski] the Places host serves winter format ${meta.format}; this TREK reads ${SGR_FORMAT}`);
|
||||
return 'refused';
|
||||
}
|
||||
const answer = await this.winter.index(this.current?.indexSha ?? null);
|
||||
if (answer.status === 'not_modified') return 'unchanged';
|
||||
if (answer.sha256 !== meta.indexSha) {
|
||||
logWarn(`[Ski] the ski area index does not match its checksum; the one held stays`);
|
||||
return 'refused';
|
||||
}
|
||||
if (answer.dropped > 0) logWarn(`[Ski] ${answer.dropped} rows of the ski area index did not read`);
|
||||
const kept = { build: meta.build, indexSha: meta.indexSha, attribution: meta.attribution };
|
||||
const stored = { meta: kept, index: answer.index };
|
||||
await this.writeAtomically(join(this.dir(), `index-${meta.indexSha.slice(0, 8)}.json`), JSON.stringify(stored));
|
||||
this.current = buildIndex(stored.meta, stored.index);
|
||||
logInfo(`[Ski] ski area index of build ${meta.build}: ${answer.index.areas.length} areas`);
|
||||
await this.dropOtherIndexes(meta.indexSha);
|
||||
return 'updated';
|
||||
}
|
||||
|
||||
private async dropOtherIndexes(keep: string): Promise<void> {
|
||||
const names = await readdir(this.dir());
|
||||
const stale = names.filter((name) => name.startsWith('index-') && name !== `index-${keep.slice(0, 8)}.json`);
|
||||
await Promise.all(stale.map((name) => rm(join(this.dir(), name), { force: true })));
|
||||
}
|
||||
|
||||
private async writeAtomically(file: string, content: string | Buffer): Promise<void> {
|
||||
await mkdir(join(file, '..'), { recursive: true });
|
||||
const temp = `${file}.tmp`;
|
||||
await writeFile(temp, content);
|
||||
await rename(temp, file);
|
||||
}
|
||||
|
||||
/** Whether an area's graph is here, on its way, or cannot be had right now. */
|
||||
stateOf(row: WinterIndexRow): 'ready' | 'loading' | 'unavailable' {
|
||||
if (existsSync(this.fileOf(row))) return 'ready';
|
||||
if (this.downloads.has(row.id)) return 'loading';
|
||||
const failed = this.failedAt.get(row.id);
|
||||
if (!this.winter.enabled() || (failed !== undefined && Date.now() - failed < FAILED_FOR_MS)) return 'unavailable';
|
||||
return 'loading';
|
||||
}
|
||||
|
||||
/**
|
||||
* An area's graph file: the current build's, downloaded if it is not here
|
||||
* yet (one download however many ask at once), or the newest older copy
|
||||
* while the download fails. Throws when there is neither.
|
||||
*/
|
||||
async ensureArea(row: WinterIndexRow): Promise<AreaFile> {
|
||||
const file = this.fileOf(row);
|
||||
if (existsSync(file)) {
|
||||
await this.touch(file);
|
||||
return { file, stale: false };
|
||||
}
|
||||
let download = this.downloads.get(row.id);
|
||||
if (!download) {
|
||||
download = this.download(row, file).finally(() => this.downloads.delete(row.id));
|
||||
this.downloads.set(row.id, download);
|
||||
}
|
||||
try {
|
||||
await download;
|
||||
this.failedAt.delete(row.id);
|
||||
return { file, stale: false };
|
||||
} catch (err) {
|
||||
this.failedAt.set(row.id, Date.now());
|
||||
const older = await this.keptCopy(row.id);
|
||||
if (older) return { file: older, stale: true };
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
private async download(row: WinterIndexRow, file: string): Promise<void> {
|
||||
let answer: Awaited<ReturnType<TrekPlacesWinterService['area']>>;
|
||||
try {
|
||||
answer = await this.winter.area(row.id, null);
|
||||
} catch (err) {
|
||||
// An id the host does not know means the index is out of date.
|
||||
if ((err as { status?: number }).status === 404) void this.refresh().catch(() => undefined);
|
||||
throw err;
|
||||
}
|
||||
if (answer.status !== 'ok') throw new Error(`The Places host sent no graph for ${row.id}`);
|
||||
if (sha256(answer.bytes) !== row.sha256) {
|
||||
throw new Error(`The graph of ${row.id} does not match the index's checksum; it was not kept`);
|
||||
}
|
||||
await this.writeAtomically(file, answer.bytes);
|
||||
}
|
||||
|
||||
/** The newest file of an area kept from an earlier build, if any. */
|
||||
private async keptCopy(id: string): Promise<string | null> {
|
||||
let names: string[];
|
||||
try {
|
||||
names = await readdir(this.areasDir());
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
const prefix = `${safeId(id)}@`;
|
||||
const copies = names.filter((name) => name.startsWith(prefix) && name.endsWith('.sgr.gz'));
|
||||
const dated = await Promise.all(
|
||||
copies.map(async (name) => ({ name, at: (await stat(join(this.areasDir(), name))).mtimeMs })),
|
||||
);
|
||||
const newest = dated.sort((a, b) => b.at - a.at)[0];
|
||||
return newest ? join(this.areasDir(), newest.name) : null;
|
||||
}
|
||||
|
||||
/** Marks a file used, so the sweep keeps it. */
|
||||
private async touch(file: string): Promise<void> {
|
||||
const now = new Date();
|
||||
await utimes(file, now, now).catch(() => undefined);
|
||||
}
|
||||
|
||||
/** The ids of the areas with a graph kept here, with the checksum prefix each file carries. */
|
||||
async keptAreas(): Promise<Array<{ id: string; sha8: string }>> {
|
||||
let names: string[];
|
||||
try {
|
||||
names = await readdir(this.areasDir());
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
return names
|
||||
.filter((name) => name.endsWith('.sgr.gz') && name.includes('@'))
|
||||
.map((name) => {
|
||||
const [id, rest] = name.split('@') as [string, string];
|
||||
return { id: id.replace('_', ':'), sha8: rest.slice(0, 8) };
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Clears what is left of interrupted writes and, unless `tempOnly`, every
|
||||
* area file unused for 90 days. An area kept is never older than its last use.
|
||||
*/
|
||||
async sweep(now: number, { tempOnly = false }: { tempOnly?: boolean } = {}): Promise<number> {
|
||||
const removed = await Promise.all([this.dir(), this.areasDir()].map((dir) => this.sweepDir(dir, now, tempOnly)));
|
||||
return removed.reduce((sum, count) => sum + count, 0);
|
||||
}
|
||||
|
||||
private async sweepDir(dir: string, now: number, tempOnly: boolean): Promise<number> {
|
||||
let names: string[];
|
||||
try {
|
||||
names = await readdir(dir);
|
||||
} catch {
|
||||
return 0;
|
||||
}
|
||||
const verdicts = await Promise.all(
|
||||
names.map(async (name) => {
|
||||
if (name.endsWith('.tmp')) return name;
|
||||
if (tempOnly || !name.endsWith('.sgr.gz')) return null;
|
||||
const at = (await stat(join(dir, name))).mtimeMs;
|
||||
return now - at > UNUSED_FOR_MS ? name : null;
|
||||
}),
|
||||
);
|
||||
const doomed = verdicts.filter((name): name is string => name !== null);
|
||||
await Promise.all(doomed.map((name) => rm(join(dir, name), { force: true })));
|
||||
return doomed.length;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,195 @@
|
||||
/**
|
||||
* SGR1, the graph of one ski area as the Places host writes it
|
||||
* (trek-places-api `winter/sgr.py`, codes in `winter/model.py`). Every number
|
||||
* here is part of that contract: a change to an existing value is a new
|
||||
* format, never a fix. The golden file `tests/fixtures/ski/golden-v1.sgr` is
|
||||
* the same bytes the writer's own test pins.
|
||||
*/
|
||||
|
||||
export const SGR_MAGIC = 'SGR1';
|
||||
export const SGR_FORMAT = 1;
|
||||
|
||||
/** What an edge may be used for, per direction (`edgeFwdUses` a to b, `edgeBackUses` b to a). */
|
||||
export const Use = {
|
||||
DOWNHILL: 1 << 0,
|
||||
LIFT_UP: 1 << 1,
|
||||
LIFT_DOWN: 1 << 2,
|
||||
NORDIC_CLASSIC: 1 << 3,
|
||||
NORDIC_SKATING: 1 << 4,
|
||||
SKITOUR_UP: 1 << 5,
|
||||
SKITOUR_DOWN: 1 << 6,
|
||||
SNOWSHOE: 1 << 7,
|
||||
WINTER_HIKE: 1 << 8,
|
||||
WALK: 1 << 9,
|
||||
} as const;
|
||||
|
||||
export const Kind = {
|
||||
RUN: 0,
|
||||
LIFT: 1,
|
||||
RAIL: 2,
|
||||
BOARD: 3,
|
||||
ALIGHT: 4,
|
||||
NORDIC: 5,
|
||||
SKITOUR: 6,
|
||||
HIKE: 7,
|
||||
SLED_WALKUP: 8,
|
||||
CONNECTION: 9,
|
||||
AREA: 10,
|
||||
LINK: 11,
|
||||
CROSSING: 12,
|
||||
WALK: 13,
|
||||
} as const;
|
||||
|
||||
/** `edgeDiff`: novice to extreme, 255 where the data gives none. */
|
||||
export const DIFFICULTY_NAMES = [
|
||||
'novice',
|
||||
'easy',
|
||||
'intermediate',
|
||||
'advanced',
|
||||
'expert',
|
||||
'freeride',
|
||||
'extreme',
|
||||
] as const;
|
||||
export const DIFF_UNKNOWN = 255;
|
||||
export const DIFF_EXPERT = 4;
|
||||
|
||||
/** `edgeGroom` bits. */
|
||||
export const Groom = {
|
||||
CLASSIC: 1 << 0,
|
||||
SKATING: 1 << 1,
|
||||
SCOOTER: 1 << 2,
|
||||
BACKCOUNTRY: 1 << 3,
|
||||
MOGUL: 1 << 4,
|
||||
ASSUMED: 1 << 7,
|
||||
} as const;
|
||||
|
||||
/** `edgeLift`, as OpenStreetMap names each type. */
|
||||
export const LIFT_NAMES = [
|
||||
'none',
|
||||
'cable_car',
|
||||
'gondola',
|
||||
'mixed_lift',
|
||||
'chair_detachable',
|
||||
'chair_fixed',
|
||||
'drag_lift',
|
||||
't-bar',
|
||||
'j-bar',
|
||||
'platter',
|
||||
'rope_tow',
|
||||
'magic_carpet',
|
||||
'funicular',
|
||||
'rack_railway',
|
||||
] as const;
|
||||
|
||||
export const Lift = {
|
||||
NONE: 0,
|
||||
CABLE_CAR: 1,
|
||||
GONDOLA: 2,
|
||||
MIXED: 3,
|
||||
CHAIR_DETACHABLE: 4,
|
||||
CHAIR_FIXED: 5,
|
||||
DRAG: 6,
|
||||
TBAR: 7,
|
||||
JBAR: 8,
|
||||
PLATTER: 9,
|
||||
ROPE_TOW: 10,
|
||||
MAGIC_CARPET: 11,
|
||||
FUNICULAR: 12,
|
||||
RACK: 13,
|
||||
} as const;
|
||||
|
||||
/** `nodeFlags` bits. */
|
||||
export const NodeFlag = {
|
||||
STATION: 1 << 0,
|
||||
PORTAL: 1 << 1,
|
||||
DISMOUNT_YES: 1 << 2,
|
||||
DISMOUNT_SOMETIMES: 1 << 3,
|
||||
LIFT_INTERNAL: 1 << 4,
|
||||
BOUNDARY: 1 << 5,
|
||||
ELE_MISSING: 1 << 6,
|
||||
AREA_INTERIOR: 1 << 7,
|
||||
} as const;
|
||||
|
||||
/**
|
||||
* `edgeFlags` bits. Bits 17 and 18 are the writer's beyond the first draft of
|
||||
* the format: an area edge whose polygon holds a mapped run (cost x1.3), and a
|
||||
* way tagged `piste:type=yes`, usable as a connection only (cost x1.5).
|
||||
*/
|
||||
export const EdgeFlag = {
|
||||
DIR_FROM_DEM: 1 << 0,
|
||||
DIR_CONFLICT: 1 << 1,
|
||||
RELATION_INHERITED: 1 << 2,
|
||||
TECHNIQUE_ASSUMED: 1 << 3,
|
||||
INFERRED_LINK: 1 << 4,
|
||||
INFERRED_CROSSING: 1 << 5,
|
||||
AREA_DERIVED: 1 << 6,
|
||||
TUNNEL: 1 << 7,
|
||||
LIT: 1 << 8,
|
||||
SKITOUR_UPHILL_OK: 1 << 9,
|
||||
HIGHWAY_SHARED: 1 << 10,
|
||||
FLAT_FOR_BOARD: 1 << 11,
|
||||
RIDE_DOWN: 1 << 12,
|
||||
HEATED: 1 << 13,
|
||||
BUBBLE: 1 << 14,
|
||||
NORDIC_SOFT_ONEWAY: 1 << 15,
|
||||
HALO: 1 << 16,
|
||||
AREA_HAS_RUN: 1 << 17,
|
||||
TYPE_UNKNOWN: 1 << 18,
|
||||
} as const;
|
||||
|
||||
/** A height the terrain data does not have. */
|
||||
export const ELE_MISSING = -32768;
|
||||
/** A string offset that names no string. */
|
||||
export const NO_STRING = 0xffffffff;
|
||||
|
||||
/** The head of an SGR1 file, as JSON. */
|
||||
export interface SkiGraphHeader {
|
||||
format: number;
|
||||
build: string | null;
|
||||
areaId: string | null;
|
||||
name: string | null;
|
||||
kind: string | null;
|
||||
country: string | null;
|
||||
colourScheme: string | null;
|
||||
/** [minLng, minLat, maxLng, maxLat] */
|
||||
bbox: [number, number, number, number] | null;
|
||||
counts: Record<string, number> | null;
|
||||
nodeCount: number;
|
||||
edgeCount: number;
|
||||
geomCount: number;
|
||||
stringBytes: number;
|
||||
crc32: number;
|
||||
}
|
||||
|
||||
/** One area's graph as decoded: the file's arrays, as typed arrays, and its string pool. */
|
||||
export interface SkiGraphData {
|
||||
header: SkiGraphHeader;
|
||||
nodeLatE7: Int32Array;
|
||||
nodeLngE7: Int32Array;
|
||||
nodeEle: Int16Array;
|
||||
nodeFlags: Uint16Array;
|
||||
nodeOsm: Float64Array;
|
||||
edgeA: Uint32Array;
|
||||
edgeB: Uint32Array;
|
||||
edgeLen: Float32Array;
|
||||
edgeUp: Uint16Array;
|
||||
edgeDown: Uint16Array;
|
||||
edgeKind: Uint8Array;
|
||||
edgeFwdUses: Uint16Array;
|
||||
edgeBackUses: Uint16Array;
|
||||
edgeDiff: Uint8Array;
|
||||
edgeGroom: Uint8Array;
|
||||
edgeLift: Uint8Array;
|
||||
edgeLiftSec: Uint16Array;
|
||||
edgeLiftCap: Uint16Array;
|
||||
edgeFlags: Uint32Array;
|
||||
edgeName: Uint32Array;
|
||||
edgeRef: Uint32Array;
|
||||
edgeWay: Float64Array;
|
||||
edgeGeomOff: Uint32Array;
|
||||
geomLatE7: Int32Array;
|
||||
geomLngE7: Int32Array;
|
||||
geomEle: Int16Array;
|
||||
/** The string pool: UTF-8, each string ended by a NUL, addressed by its byte offset. */
|
||||
strings: Uint8Array;
|
||||
}
|
||||
@@ -0,0 +1,209 @@
|
||||
import { NO_STRING, SGR_FORMAT, SGR_MAGIC, type SkiGraphData, type SkiGraphHeader } from './ski-graph.contract';
|
||||
|
||||
import { crc32, gunzipSync } from 'node:zlib';
|
||||
|
||||
/**
|
||||
* The reader of SGR1 (`ski-graph.contract.ts`). Little-endian throughout: the
|
||||
* magic, the length of a JSON head, the head, zero bytes up to the next
|
||||
* multiple of 8 from the start of the file, then every section in a fixed
|
||||
* order, each padded to 8 bytes, and last the string pool. The head's `crc32`
|
||||
* covers every byte after the head's padding, so a damaged or cut file is
|
||||
* refused before any of it is used.
|
||||
*/
|
||||
|
||||
type SectionArray = keyof Omit<SkiGraphData, 'header' | 'strings'>;
|
||||
type Count = 'n' | 'e' | 'e1' | 'g';
|
||||
|
||||
const VIEWS = {
|
||||
i32: Int32Array,
|
||||
i16: Int16Array,
|
||||
u16: Uint16Array,
|
||||
u32: Uint32Array,
|
||||
u8: Uint8Array,
|
||||
f32: Float32Array,
|
||||
f64: Float64Array,
|
||||
} as const;
|
||||
|
||||
/** The sections in the writer's order (`SECTIONS` in `winter/sgr.py`), with their element type and length. */
|
||||
const SECTIONS: ReadonlyArray<readonly [SectionArray, keyof typeof VIEWS, Count]> = [
|
||||
['nodeLatE7', 'i32', 'n'],
|
||||
['nodeLngE7', 'i32', 'n'],
|
||||
['nodeEle', 'i16', 'n'],
|
||||
['nodeFlags', 'u16', 'n'],
|
||||
['nodeOsm', 'f64', 'n'],
|
||||
['edgeA', 'u32', 'e'],
|
||||
['edgeB', 'u32', 'e'],
|
||||
['edgeLen', 'f32', 'e'],
|
||||
['edgeUp', 'u16', 'e'],
|
||||
['edgeDown', 'u16', 'e'],
|
||||
['edgeKind', 'u8', 'e'],
|
||||
['edgeFwdUses', 'u16', 'e'],
|
||||
['edgeBackUses', 'u16', 'e'],
|
||||
['edgeDiff', 'u8', 'e'],
|
||||
['edgeGroom', 'u8', 'e'],
|
||||
['edgeLift', 'u8', 'e'],
|
||||
['edgeLiftSec', 'u16', 'e'],
|
||||
['edgeLiftCap', 'u16', 'e'],
|
||||
['edgeFlags', 'u32', 'e'],
|
||||
['edgeName', 'u32', 'e'],
|
||||
['edgeRef', 'u32', 'e'],
|
||||
['edgeWay', 'f64', 'e'],
|
||||
['edgeGeomOff', 'u32', 'e1'],
|
||||
['geomLatE7', 'i32', 'g'],
|
||||
['geomLngE7', 'i32', 'g'],
|
||||
['geomEle', 'i16', 'g'],
|
||||
];
|
||||
|
||||
/** Why a file was refused; `format` marks a file of a format this build does not read, which keeps the old one. */
|
||||
export class SkiGraphFormatError extends Error {
|
||||
constructor(
|
||||
message: string,
|
||||
readonly unknownFormat = false,
|
||||
) {
|
||||
super(message);
|
||||
this.name = 'SkiGraphFormatError';
|
||||
}
|
||||
}
|
||||
|
||||
const padTo8 = (offset: number): number => (offset + 7) & ~7;
|
||||
|
||||
function count(value: unknown, what: string): number {
|
||||
if (typeof value !== 'number' || !Number.isInteger(value) || value < 0) {
|
||||
throw new SkiGraphFormatError(`SGR1 head has no valid ${what}`);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
function readHeader(bytes: Buffer): { header: SkiGraphHeader; bodyStart: number } {
|
||||
if (bytes.length < 8 || bytes.toString('latin1', 0, 4) !== SGR_MAGIC) {
|
||||
throw new SkiGraphFormatError('Not an SGR1 file');
|
||||
}
|
||||
const headLength = bytes.readUInt32LE(4);
|
||||
if (8 + headLength > bytes.length) throw new SkiGraphFormatError('SGR1 head runs past the end of the file');
|
||||
let head: unknown;
|
||||
try {
|
||||
head = JSON.parse(bytes.toString('utf8', 8, 8 + headLength));
|
||||
} catch {
|
||||
throw new SkiGraphFormatError('SGR1 head is not JSON');
|
||||
}
|
||||
if (typeof head !== 'object' || head === null) throw new SkiGraphFormatError('SGR1 head is not an object');
|
||||
const header = head as SkiGraphHeader;
|
||||
if (header.format !== SGR_FORMAT) {
|
||||
throw new SkiGraphFormatError(`SGR1 format ${String(header.format)} is not ${SGR_FORMAT}`, true);
|
||||
}
|
||||
count(header.nodeCount, 'node count');
|
||||
count(header.edgeCount, 'edge count');
|
||||
count(header.geomCount, 'point count');
|
||||
count(header.stringBytes, 'string pool size');
|
||||
count(header.crc32, 'checksum');
|
||||
return { header, bodyStart: padTo8(8 + headLength) };
|
||||
}
|
||||
|
||||
/** An area's graph from the bytes of its SGR1 file. Throws {@link SkiGraphFormatError} on anything amiss. */
|
||||
export function decodeSkiGraph(bytes: Buffer): SkiGraphData {
|
||||
const { header, bodyStart } = readHeader(bytes);
|
||||
if (bodyStart > bytes.length) throw new SkiGraphFormatError('SGR1 file ends inside its head');
|
||||
if (crc32(bytes.subarray(bodyStart)) >>> 0 !== header.crc32) {
|
||||
throw new SkiGraphFormatError('SGR1 checksum differs');
|
||||
}
|
||||
const sizes: Record<Count, number> = {
|
||||
n: header.nodeCount,
|
||||
e: header.edgeCount,
|
||||
e1: header.edgeCount + 1,
|
||||
g: header.geomCount,
|
||||
};
|
||||
const arrays = new Map<SectionArray, ArrayBufferView>();
|
||||
let offset = bodyStart;
|
||||
for (const [name, type, length] of SECTIONS) {
|
||||
const View = VIEWS[type];
|
||||
const byteLength = sizes[length] * View.BYTES_PER_ELEMENT;
|
||||
if (offset + byteLength > bytes.length) {
|
||||
throw new SkiGraphFormatError(`SGR1 section ${name} runs past the end`);
|
||||
}
|
||||
// Copied out of the file's buffer, so every view starts aligned whatever Node's pool did with it.
|
||||
const copy = new Uint8Array(byteLength);
|
||||
copy.set(bytes.subarray(offset, offset + byteLength));
|
||||
arrays.set(name, new View(copy.buffer, 0, sizes[length]));
|
||||
offset = padTo8(offset + byteLength);
|
||||
}
|
||||
if (offset + header.stringBytes > bytes.length) {
|
||||
throw new SkiGraphFormatError('SGR1 string pool runs past the end');
|
||||
}
|
||||
const strings = Uint8Array.from(bytes.subarray(offset, offset + header.stringBytes));
|
||||
const take = <T extends ArrayBufferView>(name: SectionArray): T => {
|
||||
const view = arrays.get(name);
|
||||
if (!view) throw new SkiGraphFormatError(`SGR1 lacks ${name}`);
|
||||
return view as T;
|
||||
};
|
||||
const graph: SkiGraphData = {
|
||||
header,
|
||||
nodeLatE7: take('nodeLatE7'),
|
||||
nodeLngE7: take('nodeLngE7'),
|
||||
nodeEle: take('nodeEle'),
|
||||
nodeFlags: take('nodeFlags'),
|
||||
nodeOsm: take('nodeOsm'),
|
||||
edgeA: take('edgeA'),
|
||||
edgeB: take('edgeB'),
|
||||
edgeLen: take('edgeLen'),
|
||||
edgeUp: take('edgeUp'),
|
||||
edgeDown: take('edgeDown'),
|
||||
edgeKind: take('edgeKind'),
|
||||
edgeFwdUses: take('edgeFwdUses'),
|
||||
edgeBackUses: take('edgeBackUses'),
|
||||
edgeDiff: take('edgeDiff'),
|
||||
edgeGroom: take('edgeGroom'),
|
||||
edgeLift: take('edgeLift'),
|
||||
edgeLiftSec: take('edgeLiftSec'),
|
||||
edgeLiftCap: take('edgeLiftCap'),
|
||||
edgeFlags: take('edgeFlags'),
|
||||
edgeName: take('edgeName'),
|
||||
edgeRef: take('edgeRef'),
|
||||
edgeWay: take('edgeWay'),
|
||||
edgeGeomOff: take('edgeGeomOff'),
|
||||
geomLatE7: take('geomLatE7'),
|
||||
geomLngE7: take('geomLngE7'),
|
||||
geomEle: take('geomEle'),
|
||||
strings,
|
||||
};
|
||||
checkReferences(graph);
|
||||
return graph;
|
||||
}
|
||||
|
||||
/** Every edge names nodes that exist and points that exist, so the router never reads past an array. */
|
||||
function checkReferences(graph: SkiGraphData): void {
|
||||
const nodes = graph.header.nodeCount;
|
||||
const points = graph.header.geomCount;
|
||||
for (let e = 0; e < graph.header.edgeCount; e++) {
|
||||
if ((graph.edgeA[e] as number) >= nodes || (graph.edgeB[e] as number) >= nodes) {
|
||||
throw new SkiGraphFormatError(`SGR1 edge ${e} names a node that does not exist`);
|
||||
}
|
||||
const start = graph.edgeGeomOff[e] as number;
|
||||
const end = graph.edgeGeomOff[e + 1] as number;
|
||||
if (end < start + 2 || end > points) {
|
||||
throw new SkiGraphFormatError(`SGR1 edge ${e} has no line of its own`);
|
||||
}
|
||||
}
|
||||
if (graph.header.edgeCount > 0 && graph.edgeGeomOff[graph.header.edgeCount] !== points) {
|
||||
throw new SkiGraphFormatError('SGR1 points do not add up');
|
||||
}
|
||||
}
|
||||
|
||||
/** An area's graph from its file as the Places host sends it: SGR1, gzip-packed. */
|
||||
export function decodeSkiGraphGz(packed: Buffer): SkiGraphData {
|
||||
let bytes: Buffer;
|
||||
try {
|
||||
bytes = gunzipSync(packed);
|
||||
} catch {
|
||||
throw new SkiGraphFormatError('SGR1 file is not gzip');
|
||||
}
|
||||
return decodeSkiGraph(bytes);
|
||||
}
|
||||
|
||||
const UTF8 = new TextDecoder('utf-8');
|
||||
|
||||
/** The string at a pool offset, null for none (or an offset the pool does not hold). */
|
||||
export function poolString(strings: Uint8Array, offset: number): string | null {
|
||||
if (offset === NO_STRING || offset >= strings.length) return null;
|
||||
const end = strings.indexOf(0, offset);
|
||||
return UTF8.decode(strings.subarray(offset, end < 0 ? strings.length : end));
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
import { networkFeatures } from './engine/network';
|
||||
import { SkiRouter, type LegInput } from './engine/plan';
|
||||
import type { SkiProfile } from './engine/profile';
|
||||
import { stitchGraphs } from './engine/stitch';
|
||||
import { decodeSkiGraphGz } from './ski-graph';
|
||||
import type { SkiNetworkFeature, SkiRouteLeg } from '@trek/shared';
|
||||
|
||||
import { readFile } from 'node:fs/promises';
|
||||
|
||||
/** The legs of one area (or of the pieces of one) to plan, on the graph files at `files`. */
|
||||
export interface SkiRouteJob {
|
||||
kind: 'route';
|
||||
files: string[];
|
||||
areaIds: string[];
|
||||
legs: LegInput[];
|
||||
profile: SkiProfile;
|
||||
alternatives: number;
|
||||
}
|
||||
|
||||
/** The drawn lines of one area, for the map. */
|
||||
interface SkiNetworkJob {
|
||||
kind: 'network';
|
||||
files: string[];
|
||||
}
|
||||
|
||||
export type SkiJob = SkiRouteJob | SkiNetworkJob;
|
||||
|
||||
interface SkiNetworkLines {
|
||||
features: SkiNetworkFeature[];
|
||||
simplified_m: number;
|
||||
}
|
||||
|
||||
export type SkiJobResult<J extends SkiJob> = J extends SkiRouteJob ? SkiRouteLeg[] : SkiNetworkLines;
|
||||
|
||||
/** Plans on area graphs: in a worker thread in production, on the calling thread in tests. */
|
||||
export interface SkiRouterRunner {
|
||||
run<J extends SkiJob>(job: J): Promise<SkiJobResult<J>>;
|
||||
/** Drops every network built from a file, after the area was fetched again or removed. */
|
||||
forget(file: string): void;
|
||||
close(): Promise<void>;
|
||||
}
|
||||
|
||||
export const SKI_ROUTER_RUNNER = Symbol('SKI_ROUTER_RUNNER');
|
||||
|
||||
/** What the decoded and stitched networks of a thread may take together (spec 7.3). */
|
||||
export const NETWORK_BUDGET_BYTES = 256 * 1024 * 1024;
|
||||
|
||||
/**
|
||||
* The networks a thread keeps decoded, the least recently used dropped first
|
||||
* once they take more than the budget together. Keyed by the files a network
|
||||
* was built from, so a network stitched of two areas is one entry.
|
||||
*/
|
||||
export class NetCache {
|
||||
private readonly routers = new Map<string, { router: Promise<SkiRouter>; bytes: number }>();
|
||||
|
||||
constructor(private readonly budget = NETWORK_BUDGET_BYTES) {}
|
||||
|
||||
get(files: readonly string[]): Promise<SkiRouter> {
|
||||
const key = [...files].sort().join('|');
|
||||
const known = this.routers.get(key);
|
||||
if (known) {
|
||||
this.routers.delete(key);
|
||||
this.routers.set(key, known);
|
||||
return known.router;
|
||||
}
|
||||
const entry = { router: this.load(files), bytes: 0 };
|
||||
this.routers.set(key, entry);
|
||||
void entry.router.then(
|
||||
(router) => {
|
||||
entry.bytes = router.net.bytes;
|
||||
this.trim(key);
|
||||
},
|
||||
() => this.routers.delete(key),
|
||||
);
|
||||
return entry.router;
|
||||
}
|
||||
|
||||
private async load(files: readonly string[]): Promise<SkiRouter> {
|
||||
const graphs = await Promise.all(files.map(async (file) => decodeSkiGraphGz(await readFile(file))));
|
||||
return new SkiRouter(stitchGraphs(graphs));
|
||||
}
|
||||
|
||||
/** Drops the oldest networks until the rest fit, never the one just loaded. */
|
||||
private trim(keep: string): void {
|
||||
let total = [...this.routers.values()].reduce((sum, entry) => sum + entry.bytes, 0);
|
||||
for (const [key, entry] of this.routers) {
|
||||
if (total <= this.budget) break;
|
||||
if (key === keep) continue;
|
||||
this.routers.delete(key);
|
||||
total -= entry.bytes;
|
||||
}
|
||||
}
|
||||
|
||||
forget(file: string): void {
|
||||
for (const key of [...this.routers.keys()]) {
|
||||
if (key.split('|').includes(file)) this.routers.delete(key);
|
||||
}
|
||||
}
|
||||
|
||||
clear(): void {
|
||||
this.routers.clear();
|
||||
}
|
||||
}
|
||||
|
||||
export async function runSkiJob(cache: NetCache, job: SkiJob): Promise<SkiRouteLeg[] | SkiNetworkLines> {
|
||||
const router = await cache.get(job.files);
|
||||
if (job.kind === 'network') return networkFeatures(router.net);
|
||||
return router.plan({ legs: job.legs, profile: job.profile, alternatives: job.alternatives }, job.areaIds);
|
||||
}
|
||||
|
||||
/** The test runner: the same work on the calling thread. */
|
||||
export class InlineSkiRouterRunner implements SkiRouterRunner {
|
||||
private readonly cache = new NetCache();
|
||||
|
||||
run<J extends SkiJob>(job: J): Promise<SkiJobResult<J>> {
|
||||
return runSkiJob(this.cache, job) as Promise<SkiJobResult<J>>;
|
||||
}
|
||||
|
||||
forget(file: string): void {
|
||||
this.cache.forget(file);
|
||||
}
|
||||
|
||||
close(): Promise<void> {
|
||||
this.cache.clear();
|
||||
return Promise.resolve();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import { NetCache, runSkiJob, type SkiJob } from './ski-router-runner';
|
||||
|
||||
import { parentPort } from 'node:worker_threads';
|
||||
|
||||
/** The piste router's thread: answers the jobs it is sent on networks it keeps decoded. */
|
||||
const cache = new NetCache();
|
||||
|
||||
parentPort?.on('message', (message: { id: number; job?: SkiJob; forget?: string }) => {
|
||||
if (message.forget) {
|
||||
cache.forget(message.forget);
|
||||
return;
|
||||
}
|
||||
if (!message.job) return;
|
||||
runSkiJob(cache, message.job).then(
|
||||
(result) => parentPort?.postMessage({ id: message.id, result }),
|
||||
(err: unknown) =>
|
||||
parentPort?.postMessage({ id: message.id, error: err instanceof Error ? err.message : String(err) }),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,50 @@
|
||||
import { ADDON_IDS } from '../../addons';
|
||||
import { AddonGuard } from '../addons/addon.guard';
|
||||
import { RequireAddon } from '../addons/require-addon.decorator';
|
||||
import { JwtAuthGuard } from '../auth-core/jwt-auth.guard';
|
||||
import { ResponseContract } from '../common/response-contract';
|
||||
import { TripAccessGuard } from '../permissions/trip-access.guard';
|
||||
import { SkiAreaNearQueryDto, SkiRouteRequestDto } from './ski-routing.dto';
|
||||
import { SkiRoutingService } from './ski-routing.service';
|
||||
import { Body, Controller, Get, HttpCode, Param, Post, Query, Res, UseGuards } from '@nestjs/common';
|
||||
import { skiAreaNearResponseSchema, skiNetworkResponseSchema, skiRouteResponseSchema } from '@trek/shared';
|
||||
|
||||
import type { Response } from 'express';
|
||||
|
||||
/**
|
||||
* The piste router for a ski and winter tour (spec 7.2). It reads and writes
|
||||
* nothing of the trip; the trip in the path only says whose planner asks, so
|
||||
* anyone who can see the trip may. No route takes a point to the Places host:
|
||||
* the areas are downloaded by id and searched here.
|
||||
*/
|
||||
@Controller('api/trips/:tripId/ski')
|
||||
@UseGuards(AddonGuard, JwtAuthGuard, TripAccessGuard)
|
||||
@RequireAddon(ADDON_IDS.TOURS, 'Tours')
|
||||
export class SkiRoutingController {
|
||||
constructor(private readonly routing: SkiRoutingService) {}
|
||||
|
||||
/** POST /api/trips/:tripId/ski/route: every leg planned on the pistes, or failed with its reason. */
|
||||
@Post('route')
|
||||
@HttpCode(200)
|
||||
@ResponseContract(skiRouteResponseSchema)
|
||||
async route(@Body() body: SkiRouteRequestDto) {
|
||||
return await this.routing.route(body);
|
||||
}
|
||||
|
||||
/** GET /api/trips/:tripId/ski/area-near: the ski area at a point; asking starts its download. */
|
||||
@Get('area-near')
|
||||
@ResponseContract(skiAreaNearResponseSchema)
|
||||
async areaNear(@Query() query: SkiAreaNearQueryDto) {
|
||||
return await this.routing.areaNear(query.lat, query.lng);
|
||||
}
|
||||
|
||||
/** GET /api/trips/:tripId/ski/network/:areaId: an area's runs, lifts and trails for the map, tagged by its checksum. */
|
||||
@Get('network/:areaId')
|
||||
@ResponseContract(skiNetworkResponseSchema)
|
||||
async network(@Param('areaId') areaId: string, @Res({ passthrough: true }) res: Response) {
|
||||
const { sha256, ...network } = await this.routing.network(areaId);
|
||||
res.setHeader('ETag', `"${sha256}"`);
|
||||
res.setHeader('Cache-Control', 'private, max-age=3600');
|
||||
return network;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
import { skiAreaNearQuerySchema, skiRouteRequestSchema } from '@trek/shared';
|
||||
|
||||
import { createZodDto } from 'nestjs-zod';
|
||||
|
||||
export class SkiRouteRequestDto extends createZodDto(skiRouteRequestSchema) {}
|
||||
|
||||
export class SkiAreaNearQueryDto extends createZodDto(skiAreaNearQuerySchema) {}
|
||||
@@ -0,0 +1,63 @@
|
||||
import { ADDON_IDS } from '../../addons';
|
||||
import { noAccess } from '../../mcp/tools/_shared';
|
||||
import { McpController, Tool, TOOL_ANNOTATIONS_READONLY, ok, type McpContext } from '../../nest-mcp';
|
||||
import { addonGate } from '../addons/addon-gate';
|
||||
import { AddonsService } from '../addons/addons.service';
|
||||
import { TripAccessService } from '../trip-membership/trip-access.service';
|
||||
import { SkiRoutingService } from './ski-routing.service';
|
||||
import { idSchema, skiRouteRequestSchema, type SkiRouteInput, type SkiRouteLeg } from '@trek/shared';
|
||||
|
||||
/** A planned leg as a client reads it: its measures and its stretches, not its thousands of points. */
|
||||
function summary(leg: SkiRouteLeg) {
|
||||
if (leg.status === 'failed') return leg;
|
||||
return {
|
||||
status: leg.status,
|
||||
distance_m: leg.distance_m,
|
||||
climb_m: leg.climb_m,
|
||||
descent_m: leg.descent_m,
|
||||
seconds: leg.seconds,
|
||||
snapped_m: leg.snapped_m,
|
||||
points: leg.geometry.length,
|
||||
segments: leg.segments.map(({ from: _from, to: _to, grooming: _grooming, osm_way: _way, ...segment }) => segment),
|
||||
why: leg.why,
|
||||
alternatives: leg.alternatives.length,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The piste router for a client, read only and with the REST route's rules:
|
||||
* the caller must see the trip, Tours must be on, and the request is the same
|
||||
* contract, planned by the same service. It plans and answers; nothing is
|
||||
* saved, and no clicked point leaves the server.
|
||||
*/
|
||||
@McpController()
|
||||
export class SkiRoutingMcp {
|
||||
constructor(
|
||||
private readonly routing: SkiRoutingService,
|
||||
private readonly access: TripAccessService,
|
||||
// Read by the addon gate.
|
||||
readonly addons: AddonsService,
|
||||
) {}
|
||||
|
||||
@Tool({
|
||||
name: 'plan_ski_route',
|
||||
description:
|
||||
'Plan the legs of a ski and winter tour on the runs, lifts, cross-country trails, ski touring and winter paths of OpenStreetMap, for a discipline (alpine, snowboard, cross_country with a technique of classic, skating or unknown, touring, snowshoe, winter_hike) and its options (max_difficulty from novice to expert, allow_freeride, avoid_lifts by class, allow_lift_down, priority fastest, most_skiing or easiest, pace, groomed_only and lit_only for cross-country, touring_uphill_on_pistes, use_lifts, avoid_inferred_links). Each leg (from, to) answers its length, climb and descent, its time split into skiing, lifts, waiting at lifts and walking, how far its ends were moved onto the network, its stretches (run with difficulty, lift with type, link the map data does not hold, and so on) and notes on what it rests on; a leg that cannot be planned says why (not_on_piste, no_area, cross_area, disconnected, blocked_by_difficulty with the level it needs, blocked_by_lift_avoid, blocked_by_technique, needs_ride_down, uphill_only, loading while an area downloads, places_unavailable, disabled). Times are estimates from the run difficulties and lift types, waits are guesses, and nothing says what is open, groomed or safe today; nothing is saved.',
|
||||
inputSchema: { tripId: idSchema, ...skiRouteRequestSchema.shape },
|
||||
annotations: TOOL_ANNOTATIONS_READONLY,
|
||||
when: addonGate(ADDON_IDS.TOURS),
|
||||
access: { group: 'trips', mode: 'read' },
|
||||
})
|
||||
async planSkiRoute({ tripId, ...request }: SkiRouteInput & { tripId: number }, ctx: McpContext) {
|
||||
if (!(await this.access.findAccessible(tripId, ctx.userId))) return noAccess();
|
||||
const planned = await this.routing.route(skiRouteRequestSchema.parse(request));
|
||||
return ok({
|
||||
legs: planned.legs.map(summary),
|
||||
build: planned.build,
|
||||
stale: planned.stale,
|
||||
area_names: planned.area_names,
|
||||
colour_scheme: planned.colour_scheme,
|
||||
attribution: planned.attribution,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
import { AddonsModule } from '../addons/addons.module';
|
||||
import { TrekPlacesWinterService } from '../maps/trek-places-winter.service';
|
||||
import { PermissionsModule } from '../permissions/permissions.module';
|
||||
import { SchedulingModule } from '../scheduling/scheduling.module';
|
||||
import { TripMembershipModule } from '../trip-membership/trip-membership.module';
|
||||
import { SkiAreasJob } from './ski-areas.job';
|
||||
import { SkiAreasService } from './ski-areas.service';
|
||||
import { InlineSkiRouterRunner, SKI_ROUTER_RUNNER } from './ski-router-runner';
|
||||
import { SkiRoutingController } from './ski-routing.controller';
|
||||
import { SkiRoutingMcp } from './ski-routing.mcp';
|
||||
import { SkiRoutingService } from './ski-routing.service';
|
||||
import { WorkerSkiRouterRunner } from './worker-router-runner';
|
||||
import { Module } from '@nestjs/common';
|
||||
|
||||
import { existsSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
|
||||
/** The router's own thread where the build ships its script; on the calling thread under the TypeScript sources (the tests). */
|
||||
function routerRunner() {
|
||||
const entry = join(__dirname, 'ski-router.worker.js');
|
||||
return existsSync(entry) ? new WorkerSkiRouterRunner(entry) : new InlineSkiRouterRunner();
|
||||
}
|
||||
|
||||
/**
|
||||
* The piste router (spec 7): ski and winter tours planned on the ski areas
|
||||
* the TREK Places host builds from OpenStreetMap. The areas are downloaded by
|
||||
* id and kept in the data folder (SkiAreasService), searched in a worker
|
||||
* thread, and checked against the host's new builds once a day (SkiAreasJob).
|
||||
*/
|
||||
@Module({
|
||||
imports: [AddonsModule, PermissionsModule, TripMembershipModule, SchedulingModule],
|
||||
controllers: [SkiRoutingController],
|
||||
providers: [
|
||||
SkiRoutingService,
|
||||
SkiRoutingMcp,
|
||||
SkiAreasService,
|
||||
SkiAreasJob,
|
||||
TrekPlacesWinterService,
|
||||
{ provide: SKI_ROUTER_RUNNER, useFactory: routerRunner },
|
||||
],
|
||||
})
|
||||
export class SkiRoutingModule {}
|
||||
@@ -0,0 +1,245 @@
|
||||
import { AddonsService } from '../addons/addons.service';
|
||||
import { logInfo, logWarn } from '../audit/audit-log.logger';
|
||||
import { DomainError, notFound } from '../common/domain-error';
|
||||
import type { LegInput } from './engine/plan';
|
||||
import type { SkiProfile } from './engine/profile';
|
||||
import {
|
||||
DEFAULT_ATTRIBUTION,
|
||||
pickAreas,
|
||||
SkiAreasService,
|
||||
type AreaFile,
|
||||
type IndexedArea,
|
||||
type SkiIndex,
|
||||
} from './ski-areas.service';
|
||||
import { SKI_ROUTER_RUNNER, type SkiRouterRunner } from './ski-router-runner';
|
||||
import { Inject, Injectable, type OnApplicationShutdown } from '@nestjs/common';
|
||||
import {
|
||||
skiOptionsForDiscipline,
|
||||
skiUsesLifts,
|
||||
type SkiAreaNearResponse,
|
||||
type SkiAreaState,
|
||||
type SkiFailCode,
|
||||
type SkiNetworkResponse,
|
||||
type SkiRouteFailedLeg,
|
||||
type SkiRouteLeg,
|
||||
type SkiRouteRequest,
|
||||
type SkiRouteResponse,
|
||||
} from '@trek/shared';
|
||||
|
||||
/** A leg whose area is not here within this long is answered `loading`; the download goes on. */
|
||||
export const LOADING_MS = 2000;
|
||||
|
||||
type Settled<T> = { status: 'done'; value: T } | { status: 'failed'; error: unknown } | { status: 'pending' };
|
||||
|
||||
/**
|
||||
* A promise's outcome if it settles within `ms`, else `pending`. The promise
|
||||
* is always handled, so one that fails after the wait never goes unhandled.
|
||||
*/
|
||||
export function settleWithin<T>(promise: Promise<T>, ms: number): Promise<Settled<T>> {
|
||||
const settled = promise.then(
|
||||
(value): Settled<T> => ({ status: 'done', value }),
|
||||
(error: unknown): Settled<T> => ({ status: 'failed', error }),
|
||||
);
|
||||
let timer: NodeJS.Timeout | undefined;
|
||||
const waited = new Promise<Settled<T>>((resolve) => {
|
||||
timer = setTimeout(() => resolve({ status: 'pending' }), ms);
|
||||
});
|
||||
return Promise.race([settled, waited]).finally(() => clearTimeout(timer));
|
||||
}
|
||||
|
||||
function failed(code: SkiFailCode, at: { lat: number; lng: number } | null = null): SkiRouteFailedLeg {
|
||||
return { status: 'failed', code, at, hint: null, detail: null };
|
||||
}
|
||||
|
||||
/** A leg that cannot be planned here at all: the planner draws it freely. */
|
||||
function freeDraw(code: SkiFailCode): SkiRouteFailedLeg {
|
||||
return { status: 'failed', code, at: null, hint: { free_draw: true }, detail: null };
|
||||
}
|
||||
|
||||
const samePoint = (a: { lat: number; lng: number }, b: { lat: number; lng: number }) =>
|
||||
Math.abs(a.lat - b.lat) < 1e-7 && Math.abs(a.lng - b.lng) < 1e-7;
|
||||
|
||||
/** What the router is asked: the request's discipline with its own options and technique, the defaults resolved. */
|
||||
export function profileOf(request: SkiRouteRequest): SkiProfile {
|
||||
const options = skiOptionsForDiscipline(request.discipline, request.options);
|
||||
return {
|
||||
discipline: request.discipline,
|
||||
technique: request.discipline === 'cross_country' ? (request.technique ?? 'unknown') : null,
|
||||
options,
|
||||
useLifts: skiUsesLifts(request.discipline, options),
|
||||
};
|
||||
}
|
||||
|
||||
interface Group {
|
||||
areas: IndexedArea[];
|
||||
indices: number[];
|
||||
}
|
||||
|
||||
/**
|
||||
* The piste router (spec 7): plans the legs of a ski and winter tour on the
|
||||
* ski areas the Places host serves, for the REST route and the MCP tool
|
||||
* alike. A leg is planned on the areas holding its ends; the legs of the same
|
||||
* areas go to the router's thread as one job, in order, so each goes on from
|
||||
* where the one before ended. Nothing is written; nothing of the trip is read.
|
||||
*/
|
||||
@Injectable()
|
||||
export class SkiRoutingService implements OnApplicationShutdown {
|
||||
constructor(
|
||||
private readonly areas: SkiAreasService,
|
||||
private readonly addons: AddonsService,
|
||||
@Inject(SKI_ROUTER_RUNNER) private readonly runner: SkiRouterRunner,
|
||||
) {}
|
||||
|
||||
async onApplicationShutdown(): Promise<void> {
|
||||
await this.runner.close();
|
||||
}
|
||||
|
||||
/** Why nothing can be planned here at all, or null: TREK Places off, or the admin's switch off. */
|
||||
private async refusal(): Promise<SkiFailCode | null> {
|
||||
if (!this.areas.enabled()) return 'places_unavailable';
|
||||
return (await this.addons.getToursSkiRouting()).enabled ? null : 'disabled';
|
||||
}
|
||||
|
||||
async route(request: SkiRouteRequest): Promise<SkiRouteResponse> {
|
||||
const all = (leg: SkiRouteLeg): SkiRouteResponse => ({
|
||||
legs: request.legs.map(() => leg),
|
||||
build: null,
|
||||
stale: false,
|
||||
area_names: [],
|
||||
colour_scheme: 'europe',
|
||||
attribution: DEFAULT_ATTRIBUTION,
|
||||
});
|
||||
const refused = await this.refusal();
|
||||
if (refused) return all(freeDraw(refused));
|
||||
const index = await settleWithin(this.areas.index(), LOADING_MS);
|
||||
if (index.status === 'pending') return all(failed('loading'));
|
||||
if (index.status === 'failed' || !index.value) return all(freeDraw('places_unavailable'));
|
||||
return this.routeOn(index.value, request);
|
||||
}
|
||||
|
||||
private async routeOn(index: SkiIndex, request: SkiRouteRequest): Promise<SkiRouteResponse> {
|
||||
const legs: SkiRouteLeg[] = new Array<SkiRouteLeg>(request.legs.length);
|
||||
const groups = new Map<string, Group>();
|
||||
request.legs.forEach((leg, position) => {
|
||||
const pick = pickAreas(index, leg);
|
||||
if (pick.status !== 'ok') {
|
||||
legs[position] = failed(pick.status, pick.at);
|
||||
return;
|
||||
}
|
||||
const key = pick.areas.map((area) => area.row.id).join('+');
|
||||
const group: Group = groups.get(key) ?? { areas: pick.areas, indices: [] };
|
||||
group.indices.push(position);
|
||||
groups.set(key, group);
|
||||
});
|
||||
const profile = profileOf(request);
|
||||
const used = new Set<IndexedArea>();
|
||||
let stale = false;
|
||||
await Promise.all(
|
||||
[...groups.values()].map(async (group) => {
|
||||
const planned = await this.planGroup(group, request, profile);
|
||||
group.indices.forEach((position, at) => {
|
||||
legs[position] = planned.legs[at] as SkiRouteLeg;
|
||||
});
|
||||
if (planned.used) group.areas.forEach((area) => used.add(area));
|
||||
stale ||= planned.stale;
|
||||
}),
|
||||
);
|
||||
const names = [...new Set([...used].flatMap((area) => (area.row.name ? [area.row.name] : [])))];
|
||||
return {
|
||||
legs,
|
||||
build: used.size > 0 ? index.build : null,
|
||||
stale,
|
||||
area_names: names,
|
||||
colour_scheme: [...used][0]?.row.colourScheme ?? 'europe',
|
||||
attribution: index.attribution,
|
||||
};
|
||||
}
|
||||
|
||||
/** One group's legs on its areas: downloaded within the wait, then planned in the router's thread. */
|
||||
private async planGroup(
|
||||
group: Group,
|
||||
request: SkiRouteRequest,
|
||||
profile: SkiProfile,
|
||||
): Promise<{ legs: SkiRouteLeg[]; used: boolean; stale: boolean }> {
|
||||
const answer = (leg: SkiRouteLeg) => ({ legs: group.indices.map(() => leg), used: false, stale: false });
|
||||
const downloads = Promise.all(group.areas.map((area) => this.areas.ensureArea(area.row)));
|
||||
const files = await settleWithin(downloads, LOADING_MS);
|
||||
if (files.status === 'pending') {
|
||||
return answer({ ...failed('loading'), detail: { name: group.areas[0]?.row.name ?? null } });
|
||||
}
|
||||
if (files.status === 'failed') {
|
||||
logInfo(`[Ski] no graph for ${group.areas.map((area) => area.row.id).join(', ')}: ${String(files.error)}`);
|
||||
return answer(freeDraw('places_unavailable'));
|
||||
}
|
||||
const legs: LegInput[] = group.indices.map((position, at) => {
|
||||
const leg = request.legs[position] as SkiRouteRequest['legs'][number];
|
||||
// A leg goes on from the one before only where that one is the tour's leg right before it.
|
||||
const previous = at > 0 && group.indices[at - 1] === position - 1 ? request.legs[position - 1] : undefined;
|
||||
return { from: leg.from, to: leg.to, continues: !!previous && samePoint(previous.to, leg.from) };
|
||||
});
|
||||
try {
|
||||
const planned = await this.runner.run({
|
||||
kind: 'route',
|
||||
files: files.value.map((file: AreaFile) => file.file),
|
||||
areaIds: group.areas.map((area) => area.row.id),
|
||||
legs,
|
||||
profile,
|
||||
alternatives: request.alternatives,
|
||||
});
|
||||
return { legs: planned, used: true, stale: files.value.some((file) => file.stale) };
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : String(err);
|
||||
logWarn(`[Ski] routing on ${group.areas.map((area) => area.row.id).join(', ')}: ${message}`);
|
||||
if (message === 'timeout' || message === 'busy') return answer(failed(message));
|
||||
return answer(freeDraw('places_unavailable'));
|
||||
}
|
||||
}
|
||||
|
||||
/** The ski area at a point and whether its graph is here; asking starts its download (spec 7.3, prefetch). */
|
||||
async areaNear(lat: number, lng: number): Promise<SkiAreaNearResponse> {
|
||||
const index = await settleWithin(this.areas.index(), LOADING_MS);
|
||||
if (index.status !== 'done' || !index.value) return { area: null };
|
||||
const row = index.value.areas.find(
|
||||
(area) => lat >= area.minLat && lat <= area.maxLat && lng >= area.minLng && lng <= area.maxLng,
|
||||
)?.row;
|
||||
if (!row) return { area: null };
|
||||
const refused = await this.refusal();
|
||||
let state: SkiAreaState = refused ? 'unavailable' : this.areas.stateOf(row);
|
||||
if (state === 'loading') {
|
||||
const fetched = await settleWithin(this.areas.ensureArea(row), 0);
|
||||
if (fetched.status === 'done') state = 'ready';
|
||||
}
|
||||
return {
|
||||
area: {
|
||||
id: row.id,
|
||||
name: row.name,
|
||||
kind: row.kind,
|
||||
colour_scheme: row.colourScheme,
|
||||
build: index.value.build,
|
||||
state,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** An area's runs, lifts and trails as lines for the map; the area is downloaded first if it has to be. */
|
||||
async network(areaId: string): Promise<SkiNetworkResponse & { sha256: string }> {
|
||||
if (await this.refusal()) throw new DomainError(503, 'Piste data is not available');
|
||||
const index = await this.areas.index();
|
||||
const area = index?.areas.find((candidate) => candidate.row.id === areaId);
|
||||
if (!index || !area) throw notFound('Ski area not found');
|
||||
let file: AreaFile;
|
||||
try {
|
||||
file = await this.areas.ensureArea(area.row);
|
||||
} catch {
|
||||
throw new DomainError(503, 'Piste data is not available');
|
||||
}
|
||||
const lines = await this.runner.run({ kind: 'network', files: [file.file] });
|
||||
return {
|
||||
area_id: area.row.id,
|
||||
build: index.build,
|
||||
colour_scheme: area.row.colourScheme,
|
||||
...lines,
|
||||
sha256: area.row.sha256,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
import type { SkiJob, SkiJobResult, SkiRouterRunner } from './ski-router-runner';
|
||||
|
||||
import { join } from 'node:path';
|
||||
import { Worker } from 'node:worker_threads';
|
||||
|
||||
/** A job waits this long for its answer, and four seconds more for every leg it plans. */
|
||||
const BASE_ANSWER_MS = 8000;
|
||||
const ANSWER_MS_PER_LEG = 4000;
|
||||
const MAX_ANSWER_MS = 60_000;
|
||||
/** With this many jobs already waiting, a new one is turned away as busy rather than queued. */
|
||||
export const MAX_WAITING_JOBS = 8;
|
||||
/** A thread with nothing to do ends after half an hour; the next job starts one again. */
|
||||
const IDLE_MS = 30 * 60 * 1000;
|
||||
|
||||
interface Waiting {
|
||||
settle: (outcome: { result: unknown } | { error: Error }) => void;
|
||||
timer: NodeJS.Timeout;
|
||||
}
|
||||
|
||||
type Reply = { id: number; result?: unknown; error?: string };
|
||||
|
||||
export function answerTimeoutMs(job: SkiJob): number {
|
||||
const legs = job.kind === 'route' ? job.legs.length : 1;
|
||||
return Math.min(MAX_ANSWER_MS, BASE_ANSWER_MS + ANSWER_MS_PER_LEG * Math.max(0, legs - 1));
|
||||
}
|
||||
|
||||
/**
|
||||
* The piste router's own thread, so a search never holds up the server's
|
||||
* requests. Started on the first job and ended when idle; a job not answered
|
||||
* in time fails as `timeout` and the thread is replaced, a thread that dies
|
||||
* fails what it held, and the next job finds a fresh one.
|
||||
*/
|
||||
export class WorkerSkiRouterRunner implements SkiRouterRunner {
|
||||
private thread: Worker | null = null;
|
||||
private lastId = 0;
|
||||
private readonly waiting = new Map<number, Waiting>();
|
||||
private idleTimer: NodeJS.Timeout | null = null;
|
||||
|
||||
constructor(private readonly entry = join(__dirname, 'ski-router.worker.js')) {}
|
||||
|
||||
run<J extends SkiJob>(job: J): Promise<SkiJobResult<J>> {
|
||||
if (this.waiting.size >= MAX_WAITING_JOBS) return Promise.reject(new Error('busy'));
|
||||
const worker = this.ensureThread();
|
||||
const id = ++this.lastId;
|
||||
return new Promise<SkiJobResult<J>>((resolve, reject) => {
|
||||
const timer = setTimeout(() => {
|
||||
this.waiting.delete(id);
|
||||
reject(new Error('timeout'));
|
||||
this.replaceThread();
|
||||
}, answerTimeoutMs(job));
|
||||
this.waiting.set(id, {
|
||||
timer,
|
||||
settle: (outcome) => ('error' in outcome ? reject(outcome.error) : resolve(outcome.result as SkiJobResult<J>)),
|
||||
});
|
||||
worker.postMessage({ id, job });
|
||||
});
|
||||
}
|
||||
|
||||
forget(file: string): void {
|
||||
this.thread?.postMessage({ id: 0, forget: file });
|
||||
}
|
||||
|
||||
async close(): Promise<void> {
|
||||
if (this.idleTimer) clearTimeout(this.idleTimer);
|
||||
this.failWaiting(new Error('closed'));
|
||||
const worker = this.thread;
|
||||
this.thread = null;
|
||||
await worker?.terminate();
|
||||
}
|
||||
|
||||
private ensureThread(): Worker {
|
||||
if (this.idleTimer) clearTimeout(this.idleTimer);
|
||||
this.idleTimer = setTimeout(() => void this.close(), IDLE_MS);
|
||||
this.idleTimer.unref();
|
||||
if (this.thread) return this.thread;
|
||||
// The thread runs the compiled code with the path aliases the server's own start registers.
|
||||
const execArgv = process.execArgv.filter(
|
||||
(arg, index, all) =>
|
||||
arg === '--require' || arg === '-r' || all[index - 1] === '--require' || all[index - 1] === '-r',
|
||||
);
|
||||
const worker = new Worker(this.entry, { execArgv });
|
||||
worker.on('message', (reply: Reply) => this.receive(reply));
|
||||
worker.on('error', (err: Error) => this.lost(worker, err));
|
||||
worker.on('exit', () => this.lost(worker, new Error('router thread ended')));
|
||||
worker.unref();
|
||||
this.thread = worker;
|
||||
return worker;
|
||||
}
|
||||
|
||||
private receive(reply: Reply): void {
|
||||
const waiting = this.waiting.get(reply.id);
|
||||
if (!waiting) return;
|
||||
this.waiting.delete(reply.id);
|
||||
clearTimeout(waiting.timer);
|
||||
if (reply.result !== undefined) waiting.settle({ result: reply.result });
|
||||
else waiting.settle({ error: new Error(reply.error ?? 'router failed') });
|
||||
}
|
||||
|
||||
/** A thread that ended or failed takes its jobs with it; one already replaced leaves the new thread's alone. */
|
||||
private lost(worker: Worker, err: Error): void {
|
||||
if (this.thread !== worker) return;
|
||||
this.thread = null;
|
||||
this.failWaiting(err);
|
||||
}
|
||||
|
||||
private replaceThread(): void {
|
||||
const worker = this.thread;
|
||||
this.thread = null;
|
||||
void worker?.terminate();
|
||||
}
|
||||
|
||||
private failWaiting(err: Error): void {
|
||||
for (const [id, waiting] of this.waiting) {
|
||||
clearTimeout(waiting.timer);
|
||||
this.waiting.delete(id);
|
||||
waiting.settle({ error: err });
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user