mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-21 19:40:34 +00:00
feat(tours): round hikes, other ways of a leg and wanderer trails through the assistant
The assistant can now search a round hike of about a wished length from one point and the router's other ways for one leg of a hike, with the planner's own search, and propose each one as a hike card to compare and take. It can also search the user's wanderer trails, preview one as a card, import it and check a wanderer tour against its source. The round search, its loop geometry, the test whether two lines are one way, the other ways among a router's offers and the pins that hold a chosen way move to @trek/shared; the planner and the road trip use them from there.
This commit is contained in:
@@ -134,6 +134,9 @@ const TOUR_PLANNING_TOOLS: ReadonlySet<string> = new Set([
|
||||
'plan_ski_route',
|
||||
'prepare_tour_change',
|
||||
'save_tour_change',
|
||||
'propose_round_hike',
|
||||
'propose_hike_leg_way',
|
||||
'import_wanderer_trail',
|
||||
]);
|
||||
|
||||
/** The tool that keeps a note in the trip notes; kept at once, without a card. */
|
||||
|
||||
@@ -106,6 +106,11 @@ export const TOUR_LOOK = {
|
||||
find_tours_for_day: { stepKey: 'assistant.step.readingTours' },
|
||||
search_tour_pois: { stepKey: 'assistant.step.tourPois' },
|
||||
get_city_walk_progress: { stepKey: 'assistant.step.readingTour' },
|
||||
propose_round_hike: { stepKey: 'assistant.step.findingRounds' },
|
||||
propose_hike_leg_way: { stepKey: 'assistant.step.findingWays' },
|
||||
search_wanderer_trails: { stepKey: 'assistant.step.searchingWanderer' },
|
||||
preview_wanderer_trail: { stepKey: 'assistant.step.readingTrail' },
|
||||
check_tour_source: { stepKey: 'assistant.step.checkingSource' },
|
||||
},
|
||||
entities: {
|
||||
tour: {
|
||||
|
||||
@@ -143,6 +143,8 @@ describe('tourRouteModel', () => {
|
||||
expect(canTake(SAVED)).toBe(false);
|
||||
expect(canTake({ ...HIKE, activity: 'kayak', source: 'plan' })).toBe(false);
|
||||
expect(canTake({ ...HIKE, source: 'pending' })).toBe(false);
|
||||
// Another way for a leg of a saved hike changes that hike; it is not created anew.
|
||||
expect(canTake({ ...HIKE, placeId: 12 })).toBe(false);
|
||||
});
|
||||
|
||||
it('FE-AI-TOUR-010: proposals of one answer form ways of three at most; anything else stands alone', () => {
|
||||
|
||||
@@ -227,10 +227,12 @@ export function routePoints(card: TourRouteCard): [number, number][] {
|
||||
|
||||
/**
|
||||
* Whether "Plan this" can take the proposal: a hike whose way was planned,
|
||||
* or a city walk. A paddle or ski plan, a saved tour and a held change cannot.
|
||||
* or a city walk. A paddle or ski plan, a saved tour, a held change and the
|
||||
* other way of a saved hike's leg (named by its place, changed with
|
||||
* update_tour rather than created anew) cannot.
|
||||
*/
|
||||
export function canTake(card: TourRouteCard): boolean {
|
||||
if (card.source !== 'proposal') return false;
|
||||
if (card.source !== 'proposal' || card.placeId !== null) return false;
|
||||
return card.activity === 'walk' || (card.activity === 'hike' && card.routed);
|
||||
}
|
||||
|
||||
|
||||
@@ -15,8 +15,6 @@ import {
|
||||
calculateAlternatives,
|
||||
avoidedClasses,
|
||||
routeEngineFor,
|
||||
sameRoad,
|
||||
furthestFrom,
|
||||
osrmLegSegment,
|
||||
} from './RouteCalculator'
|
||||
|
||||
@@ -1204,37 +1202,6 @@ describe('a trip that avoids something', () => {
|
||||
expect(plain.avoidance).toBeUndefined()
|
||||
})
|
||||
|
||||
it('FE-COMP-ROUTECALCULATOR-064: a road that runs the whole of another and turns off to a point and back is not that road', () => {
|
||||
// The shape of a leg bent by a via: every point of the plain road lies on it, so
|
||||
// asked only one way round the two read as one.
|
||||
const plainRoad = { coordinates: [[61, 10], [61, 11], [61, 12]] as [number, number][], distance: 100_000, duration: 3600 }
|
||||
const spur = { coordinates: [[61, 10], [61, 11], [61.3, 11], [61, 11], [61, 12]] as [number, number][], distance: 166_000, duration: 5400 }
|
||||
|
||||
expect(sameRoad(plainRoad, spur)).toBe(false)
|
||||
expect(sameRoad(spur, plainRoad)).toBe(false)
|
||||
expect(sameRoad(plainRoad, { ...plainRoad, distance: 104_000, duration: 3900 })).toBe(true)
|
||||
})
|
||||
|
||||
it('FE-COMP-ROUTECALCULATOR-065: one road drawn with a different spacing of points is still one road', () => {
|
||||
// Two engines' lines of one long road share almost no vertex. Measured to the nearest
|
||||
// sampled vertex, a point on the same road sat half a sample off it: kilometres here.
|
||||
// The dense line is sampled every tenth vertex, 0.05 degrees apart; the sparse one sits
|
||||
// exactly between those samples, 1.8 km from the nearest, on the very same road.
|
||||
const dense = Array.from({ length: 2001 }, (_, i) => [50, i * 0.005] as [number, number])
|
||||
const sparse: [number, number][] = [
|
||||
[50, 0],
|
||||
...Array.from({ length: 200 }, (_, i) => [50, 0.025 + i * 0.05] as [number, number]),
|
||||
[50, 10],
|
||||
]
|
||||
const a = { coordinates: dense, distance: 700_000, duration: 25_000 }
|
||||
const b = { coordinates: sparse, distance: 712_000, duration: 27_000 }
|
||||
|
||||
expect(sameRoad(a, b)).toBe(true)
|
||||
const off = furthestFrom([[50.02, 5]], dense)
|
||||
expect(off?.index).toBe(0)
|
||||
expect(off?.km).toBeCloseTo(2.22, 1)
|
||||
})
|
||||
|
||||
it('FE-COMP-ROUTECALCULATOR-066: the avoidance offer beside an OSRM leg says when it crosses by ferry', async () => {
|
||||
server.use(
|
||||
http.get(`${FOSSGIS.driving}/:coords`, () => HttpResponse.json({ code: 'Ok', routes: [{ geometry: { coordinates: [[10, 63], [11, 63], [12, 63]] }, distance: 100000, duration: 3600 }] })),
|
||||
|
||||
@@ -5,7 +5,7 @@ import { haversineKm } from '../../utils/geo'
|
||||
import { formatDistance } from '../../utils/units'
|
||||
import { countRoute } from './routeUsageCounter'
|
||||
import { valhallaRouteAvoiding, valhallaRun, valhallaAvailable, valhallaAlternates, valhallaSpacing, legAvoids, type AvoidClass, type ValhallaLeg } from './valhallaRoute'
|
||||
import type { RouteUsageSurface } from '@trek/shared'
|
||||
import { furthestFrom, sameRoad, type RouteUsageSurface } from '@trek/shared'
|
||||
|
||||
// FOSSGIS hosts OSRM with real per-profile routing (car/foot/bike) — the
|
||||
// project-osrm.org demo is car-only (it ignores the profile in the URL). Use
|
||||
@@ -803,41 +803,6 @@ export type RoadLine = Pick<RouteAlternative, 'coordinates' | 'distance' | 'dura
|
||||
*/
|
||||
const EXCLUDABLE_CLASSES = ['motorway', 'toll', 'ferry'] as const
|
||||
|
||||
/**
|
||||
* How far two lines may stray from each other and still be the same road, in kilometres.
|
||||
*
|
||||
* Parallel carriageways, a different slip road onto the same motorway and the noise
|
||||
* between two engines' idea of where a road is all sit well under this. A way somebody
|
||||
* would call an alternative leaves it by kilometres: the ferry-free run from Hamburg to
|
||||
* Copenhagen, which is a genuinely different road, peaks 2.3 km off the default.
|
||||
*/
|
||||
const SAME_ROAD_KM = 0.5
|
||||
|
||||
/**
|
||||
* Two lines are the same road.
|
||||
*
|
||||
* Length and duration used to decide this, and stopped being enough when a second engine
|
||||
* started answering. Valhalla prices roads differently: measured over twelve European
|
||||
* legs its distances ran 1.8 % above OSRM's, so on a 470 km leg the same road comes back
|
||||
* thirteen kilometres apart and a 200 m tolerance calls it a discovery. Two identical
|
||||
* blue lines on the map is exactly what that looks like. Duration is the worse of the
|
||||
* two to lean on: over the same twelve legs it ranged from 14.7 % under OSRM's to 13.2 %
|
||||
* over, with the sign set by the region rather than by the road.
|
||||
*
|
||||
* The geometry does not care which engine drew it, so it decides whenever there is one.
|
||||
* The numbers stay as the fallback for a line with no shape to compare.
|
||||
*
|
||||
* Measured both ways round. Asked only whether `b` stays near `a`, a road that runs the
|
||||
* whole of `b` and then turns off to a point and back passed as `b`, because every point
|
||||
* of `b` is on it; that is exactly the shape of a leg bent by a via, and the picker and
|
||||
* the check behind a choice both have to tell it from the plain road.
|
||||
*/
|
||||
export function sameRoad(a: RoadLine, b: RoadLine): boolean {
|
||||
const there = furthestFrom(b.coordinates, a.coordinates)
|
||||
const back = furthestFrom(a.coordinates, b.coordinates)
|
||||
if (there && back) return Math.max(there.km, back.km) < SAME_ROAD_KM
|
||||
return Math.abs(a.distance - b.distance) < 200 && Math.abs(a.duration - b.duration) < 60
|
||||
}
|
||||
|
||||
/**
|
||||
* Hosts that have already answered "I do not do exclude", by base URL.
|
||||
@@ -1103,87 +1068,3 @@ function furthestPointFrom(line: [number, number][], reference: [number, number]
|
||||
const furthest = furthestFrom(line, reference)
|
||||
return furthest ? { lat: furthest.lat, lng: furthest.lng } : null
|
||||
}
|
||||
|
||||
/**
|
||||
* The same point, plus how far off it actually is.
|
||||
*
|
||||
* The search itself stays in squared degrees with a cosine on the longitude: it only has
|
||||
* to ORDER the candidates, and a haversine per pair of a 200-by-200 comparison buys
|
||||
* nothing for it. The winner is converted once at the end, because `sameRoad` needs a
|
||||
* real distance rather than a rank, and half a degree is a different number of metres in
|
||||
* Andalusia than in Lapland.
|
||||
*
|
||||
* `index` is where on `line` the point sits, so points taken off one line can be put back
|
||||
* in the order that line drives through them.
|
||||
*/
|
||||
export function furthestFrom(
|
||||
line: [number, number][],
|
||||
reference: [number, number][],
|
||||
): { index: number; lat: number; lng: number; km: number } | null {
|
||||
if (!line.length || !reference.length) return null
|
||||
// Every tenth vertex is plenty: alternatives differ over kilometres, not metres, and a
|
||||
// full cross product of two thousand-point lines is not worth the milliseconds.
|
||||
const step = Math.max(1, Math.floor(reference.length / 200))
|
||||
let bestIndex = -1
|
||||
let bestNeighbour: [number, number] | null = null
|
||||
let bestDist = -1
|
||||
for (let i = 0; i < line.length; i += Math.max(1, Math.floor(line.length / 200))) {
|
||||
const near = nearestOn(line[i], reference, step)
|
||||
if (near.d > bestDist) { bestDist = near.d; bestIndex = i; bestNeighbour = near.at }
|
||||
}
|
||||
if (bestIndex < 0) return null
|
||||
const [lat, lng] = line[bestIndex]
|
||||
const km = bestNeighbour ? haversineKm({ lat, lng }, { lat: bestNeighbour[0], lng: bestNeighbour[1] }) : 0
|
||||
return { index: bestIndex, lat, lng, km }
|
||||
}
|
||||
|
||||
/**
|
||||
* Where `reference` passes closest to `point`, as a squared distance in the same scaled
|
||||
* degrees and the spot on the line it was measured to.
|
||||
*
|
||||
* Coarse, then fine. The sampled vertices find the stretch, and the segments either side
|
||||
* of the nearest one find the road itself. Measured to the sampled vertex alone, a point
|
||||
* on the very same road sat up to half a sample apart from it, which on a thousand
|
||||
* kilometre leg is kilometres: two engines' lines of one motorway then read as two roads.
|
||||
*/
|
||||
function nearestOn(
|
||||
point: [number, number],
|
||||
reference: [number, number][],
|
||||
step: number,
|
||||
): { d: number; at: [number, number] } {
|
||||
const cos = Math.cos((point[0] * Math.PI) / 180)
|
||||
const squared = (p: [number, number]): number => {
|
||||
const dLat = point[0] - p[0]
|
||||
const dLng = (point[1] - p[1]) * cos
|
||||
return dLat * dLat + dLng * dLng
|
||||
}
|
||||
let nearestIndex = 0
|
||||
let nearest = Infinity
|
||||
for (let j = 0; j < reference.length; j += step) {
|
||||
const d = squared(reference[j])
|
||||
if (d < nearest) { nearest = d; nearestIndex = j }
|
||||
}
|
||||
let at = reference[nearestIndex]
|
||||
const last = Math.min(reference.length - 1, nearestIndex + step)
|
||||
for (let k = Math.max(0, nearestIndex - step); k < last; k++) {
|
||||
const on = closestOnSegment(point, reference[k], reference[k + 1], cos)
|
||||
const d = squared(on)
|
||||
if (d < nearest) { nearest = d; at = on }
|
||||
}
|
||||
return { d: nearest, at }
|
||||
}
|
||||
|
||||
/** The point of segment a-b closest to `p`, with longitude scaled by `cos` so the plane is fair. */
|
||||
function closestOnSegment(
|
||||
p: [number, number],
|
||||
a: [number, number],
|
||||
b: [number, number],
|
||||
cos: number,
|
||||
): [number, number] {
|
||||
const dx = (b[1] - a[1]) * cos
|
||||
const dy = b[0] - a[0]
|
||||
const length = dx * dx + dy * dy
|
||||
if (length === 0) return a
|
||||
const t = Math.max(0, Math.min(1, (((p[1] - a[1]) * cos) * dx + (p[0] - a[0]) * dy) / length))
|
||||
return [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t]
|
||||
}
|
||||
|
||||
@@ -1,35 +1,17 @@
|
||||
import { furthestFrom, sameRoad, type RoadLine } from '../Map/RouteCalculator'
|
||||
import { MAX_WAY_PINS, pinWay, type PinnedWay, type WayPin } from '@trek/shared'
|
||||
import type { RoadLine } from '../Map/RouteCalculator'
|
||||
import { isStoredStop, type RouteSegment } from '@trek/shared/roadtrip'
|
||||
import type { RailLegRoute, RailLegRouter, RoadtripDay, RoadtripStop } from './useRoadtripRoutes'
|
||||
import type { OfferedRoute, RailDrive, ViaAnchor } from './useRouteAlternatives'
|
||||
|
||||
/**
|
||||
* The most points one choice may pin to the road.
|
||||
*
|
||||
* Every pin is one more request to a host that allows one a second, and one more handle on
|
||||
* the map somebody has to understand later. A way that three points cannot hold is not
|
||||
* held by the router at all: a ferry OSRM will not board, or a class the day is not
|
||||
* weighed against.
|
||||
*/
|
||||
export const MAX_PINS = 3
|
||||
/** The most points one choice may pin to the road (see `MAX_WAY_PINS`). */
|
||||
export const MAX_PINS = MAX_WAY_PINS
|
||||
|
||||
/** A point a choice is held by, in the order the chosen road drives through them. */
|
||||
export interface Pin {
|
||||
lat: number
|
||||
lng: number
|
||||
}
|
||||
export type Pin = WayPin
|
||||
|
||||
/** Whether the rail's router drives an offer, and the pins that make it do so. */
|
||||
export interface PinProof {
|
||||
/** True when the router drove the offer with `pins` in place. */
|
||||
held: boolean
|
||||
/** The pins that held it, in the order the offer drives through them. Empty otherwise. */
|
||||
pins: Pin[]
|
||||
/** True when the last answer came from a stand-in engine, which proves nothing either way. */
|
||||
fellBack: boolean
|
||||
/** The router's answer to the last attempt. */
|
||||
last: RailLegRoute
|
||||
}
|
||||
export type PinProof = PinnedWay<RailLegRoute>
|
||||
|
||||
/**
|
||||
* The fewest points that make the rail's own router drive `offer`, found by asking it.
|
||||
@@ -37,19 +19,10 @@ export interface PinProof {
|
||||
* A choice used to be stored as one via at the point where the offer strayed furthest,
|
||||
* and nobody asked whether the router then drove the offer. Often it did not. A point on
|
||||
* a ferry is pulled to the nearest pier by OSRM, which never boards one, so Amsterdam to
|
||||
* Newcastle "without the motorway" came back as a thousand kilometres through Calais. An
|
||||
* offer weighed away from motorways by the second engine is held by one point for a few
|
||||
* kilometres, and the motorway takes the rest. Either way the choice looked saved and the
|
||||
* drive did something else.
|
||||
*
|
||||
* So the check is the router itself. The router's own preference starts with no pin; any
|
||||
* other offer with the point furthest from the road being driven. After each answer that
|
||||
* is not the offer, the point of the offer furthest from that answer joins in, placed in
|
||||
* the order the offer drives through them, until the answer is the offer or `maxPins` is
|
||||
* reached. The spacing between the requests is the router's own (`RailLegRouter.route`).
|
||||
*
|
||||
* An answer from a stand-in engine proves nothing about the one that will draw the leg,
|
||||
* so it ends the check without a verdict on the road.
|
||||
* Newcastle "without the motorway" came back as a thousand kilometres through Calais. So
|
||||
* the check is the router itself, the way `pinWay` asks it; the spacing between the
|
||||
* requests is the router's own (`RailLegRouter.route`). The server asks the same way for
|
||||
* the ways of a hike's leg.
|
||||
*/
|
||||
export async function pinAlternative({
|
||||
offer,
|
||||
@@ -65,23 +38,9 @@ export async function pinAlternative({
|
||||
signal: AbortSignal
|
||||
maxPins?: number
|
||||
}): Promise<PinProof> {
|
||||
const placed: { index: number; lat: number; lng: number }[] = []
|
||||
if (!offer.direct) {
|
||||
const far = furthestFrom(offer.coordinates, current?.coordinates ?? [])
|
||||
if (far) placed.push(far)
|
||||
}
|
||||
for (;;) {
|
||||
if (signal.aborted) throw new DOMException('The check was abandoned', 'AbortError')
|
||||
const last = await route(placed.map(({ lat, lng }) => ({ lat, lng })), signal)
|
||||
if (last.fellBack) return { held: false, pins: [], fellBack: true, last }
|
||||
if (sameRoad(last, offer)) return { held: true, pins: placed.map(({ lat, lng }) => ({ lat, lng })), fellBack: false, last }
|
||||
if (placed.length >= maxPins) return { held: false, pins: [], fellBack: false, last }
|
||||
const far = furthestFrom(offer.coordinates, last.coordinates)
|
||||
// The same point again would ask the same question and earn the same answer.
|
||||
if (!far || placed.some(p => p.index === far.index)) return { held: false, pins: [], fellBack: false, last }
|
||||
placed.push(far)
|
||||
placed.sort((a, b) => a.index - b.index)
|
||||
}
|
||||
const proof = await pinWay({ offer, current, route: (pins) => route(pins, signal), signal, maxPins })
|
||||
if (!proof) throw new DOMException('The check was abandoned', 'AbortError')
|
||||
return proof
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { useCallback, useMemo, useRef, useState } from 'react'
|
||||
import { calculateAlternatives, sameRoad, type RouteAlternative, type RouteEngine } from '../Map/RouteCalculator'
|
||||
import { sameRoad } from '@trek/shared'
|
||||
import { calculateAlternatives, type RouteAlternative, type RouteEngine } from '../Map/RouteCalculator'
|
||||
import type { RailLegRoute, RailLegRouter } from './useRoadtripRoutes'
|
||||
|
||||
/** One offered way of driving a leg, with what it means for this trip. */
|
||||
|
||||
@@ -1,3 +1,12 @@
|
||||
import {
|
||||
deviationOf,
|
||||
distanceWindow,
|
||||
isRoundTarget,
|
||||
MAX_ROUND_ASKS,
|
||||
ROUND_MAX_M,
|
||||
ROUND_MIN_M,
|
||||
ROUND_TOLERANCE,
|
||||
} from '@trek/shared';
|
||||
import { AlertTriangle, Check, Loader2, Mountain, RefreshCcwDot, Search, Target } from 'lucide-react';
|
||||
import { useState } from 'react';
|
||||
import { useTranslation } from '../../../i18n';
|
||||
@@ -11,19 +20,7 @@ import { fs } from '../../shared/DialogShell';
|
||||
import { Tooltip } from '../../shared/Tooltip';
|
||||
import { TourNotice } from '../tourParts';
|
||||
import { MapCard, MapCardActions, MapCornerOverlay, StopDisc, VariantFigures, WayChoice } from './mapCardParts';
|
||||
import { MAX_ROUND_ASKS } from './roundHikeRouting';
|
||||
import {
|
||||
deviationOf,
|
||||
distanceWindow,
|
||||
isRoundTarget,
|
||||
metersTyped,
|
||||
ROUND_MAX_M,
|
||||
ROUND_MIN_M,
|
||||
ROUND_TOLERANCE,
|
||||
roundStarts,
|
||||
typedLength,
|
||||
type RoundCandidate,
|
||||
} from './roundHikes';
|
||||
import { metersTyped, roundStarts, typedLength, type RoundCandidate } from './roundHikes';
|
||||
import { stopNumbersOf } from './tourPlannerWaypoints';
|
||||
import type { RoundHikeView } from './useRoundHikes';
|
||||
import type { TourPlannerController } from './useTourPlanner';
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import { hikingTimeMinutes, type PlannableTourType } from '@trek/shared';
|
||||
import { hikingTimeMinutes, otherWaysOf, type PlannableTourType } from '@trek/shared';
|
||||
import { analyzeRouteGeometry } from '../../../utils/routeGeometry';
|
||||
import { sameRoad } from '../../Map/RouteCalculator';
|
||||
import type { CostingOptions, ValhallaLeg } from '../../Map/valhallaRoute';
|
||||
import { legSpanOf } from './routeLegAt';
|
||||
import type { TourPlannerWaypoint } from './tourPlannerWaypoints';
|
||||
@@ -137,32 +136,27 @@ export function currentVariantOf(
|
||||
};
|
||||
}
|
||||
|
||||
const roadOf = (coordinates: [number, number][]) => ({ coordinates, distance: 0, duration: 0 });
|
||||
|
||||
/**
|
||||
* The way the section takes now first, then each other way the router
|
||||
* offered that is not the same way again, lettered in the order the router
|
||||
* gave them and at most three. The router's first answer is never one of
|
||||
* them: it is its own way between the two points under the same rules, the
|
||||
* one the tour already routes the section by, so choosing it could change
|
||||
* nothing even where it is drawn a little apart from the route. Their heights
|
||||
* are still to be asked for.
|
||||
* offered that is not the same way again (`otherWaysOf`), lettered in the
|
||||
* order the router gave them and at most three. The router's first answer is
|
||||
* never one of them: it is its own way between the two points under the same
|
||||
* rules, the one the tour already routes the section by, so choosing it could
|
||||
* change nothing even where it is drawn a little apart from the route. Their
|
||||
* heights are still to be asked for.
|
||||
*/
|
||||
export function offeredVariants(current: LegVariant, offers: readonly ValhallaLeg[]): LegVariant[] {
|
||||
const variants: LegVariant[] = [current];
|
||||
for (const offer of offers.slice(1)) {
|
||||
const key = OTHER_WAY_KEYS[variants.length - 1];
|
||||
if (!key) break;
|
||||
if (variants.some((known) => sameRoad(roadOf(known.coordinates), roadOf(offer.coordinates)))) continue;
|
||||
variants.push({
|
||||
key,
|
||||
const others = otherWaysOf(current, offers, OTHER_WAY_KEYS.length);
|
||||
return [
|
||||
current,
|
||||
...others.map((offer, index): LegVariant => ({
|
||||
key: OTHER_WAY_KEYS[index] ?? 'c',
|
||||
current: false,
|
||||
coordinates: offer.coordinates,
|
||||
...figuresOf(offer.coordinates),
|
||||
heights: 'pending',
|
||||
});
|
||||
}
|
||||
return variants;
|
||||
})),
|
||||
];
|
||||
}
|
||||
|
||||
/** A way with the heights the router answered, or with its heights unknown when there were none. */
|
||||
|
||||
@@ -1,75 +0,0 @@
|
||||
// FE-TOUR-ROUND-GEOMETRY-001 to FE-TOUR-ROUND-GEOMETRY-005: where a round hike's loop is steered
|
||||
// through, and how much of a line covers ground twice or the ground of another (RTE-03).
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { haversineKm } from '../../../utils/geo';
|
||||
import { loopSpots, retracedShare, sharedShare, spotToward, STRAIGHT_PER_RADIUS_M } from './roundHikeGeometry';
|
||||
|
||||
const START = { lat: 47.5, lng: 11.1 };
|
||||
const meters = (a: { lat: number; lng: number }, b: { lat: number; lng: number }) => haversineKm(a, b) * 1000;
|
||||
const line = (...spots: { lat: number; lng: number }[]): [number, number][] => spots.map(({ lat, lng }) => [lat, lng]);
|
||||
|
||||
describe('spotToward', () => {
|
||||
it('FE-TOUR-ROUND-GEOMETRY-001: lies the asked distance away in the asked direction', () => {
|
||||
const north = spotToward(START, 0, 1000);
|
||||
expect(meters(START, north)).toBeCloseTo(1000, 0);
|
||||
expect(north.lat).toBeGreaterThan(START.lat);
|
||||
expect(north.lng).toBeCloseTo(START.lng, 9);
|
||||
const east = spotToward(START, 90, 2500);
|
||||
expect(meters(START, east)).toBeCloseTo(2500, 0);
|
||||
expect(east.lng).toBeGreaterThan(START.lng);
|
||||
// Across the date line the longitude comes back into range.
|
||||
expect(spotToward({ lat: 0, lng: 179.999 }, 90, 1000).lng).toBeLessThan(-179.99);
|
||||
});
|
||||
});
|
||||
|
||||
describe('loopSpots', () => {
|
||||
it('FE-TOUR-ROUND-GEOMETRY-002: three corners of a square in a circle touching the start, its centre toward the bearing', () => {
|
||||
const radius = 1000;
|
||||
const spots = loopSpots(START, 90, radius);
|
||||
expect(spots).toHaveLength(3);
|
||||
const centre = spotToward(START, 90, radius);
|
||||
for (const spot of spots) expect(meters(centre, spot)).toBeCloseTo(radius, 0);
|
||||
// The far corner lies opposite the start, a diameter away.
|
||||
expect(meters(START, spots[1])).toBeCloseTo(2 * radius, 0);
|
||||
const corners = [START, ...spots, START];
|
||||
let straight = 0;
|
||||
for (let i = 1; i < corners.length; i += 1) straight += meters(corners[i - 1], corners[i]);
|
||||
expect(straight).toBeCloseTo(STRAIGHT_PER_RADIUS_M * radius, -1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('retracedShare', () => {
|
||||
it('FE-TOUR-ROUND-GEOMETRY-003: a loop covers little ground twice, a way there and back all of it', () => {
|
||||
const loop = line(START, ...loopSpots(START, 0, 800), START);
|
||||
expect(retracedShare(loop)).toBeLessThan(0.1);
|
||||
const far = spotToward(START, 45, 3000);
|
||||
expect(retracedShare(line(START, far, START))).toBeGreaterThan(0.9);
|
||||
// A loop with a long way in and out shares that way.
|
||||
const gate = spotToward(START, 0, 1500);
|
||||
const lollipop = line(START, gate, ...loopSpots(gate, 0, 300), gate, START);
|
||||
expect(retracedShare(lollipop)).toBeGreaterThan(0.4);
|
||||
});
|
||||
|
||||
it('FE-TOUR-ROUND-GEOMETRY-004: a line too short to sample shares nothing', () => {
|
||||
expect(retracedShare([])).toBe(0);
|
||||
expect(retracedShare(line(START))).toBe(0);
|
||||
expect(retracedShare(line(START, START))).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('sharedShare', () => {
|
||||
it('FE-TOUR-ROUND-GEOMETRY-005: the share of one line on the ground of another', () => {
|
||||
const loop = line(START, ...loopSpots(START, 0, 800), START);
|
||||
expect(sharedShare(loop, loop)).toBe(1);
|
||||
const other = line(START, ...loopSpots(START, 180, 800), START);
|
||||
expect(sharedShare(loop, other)).toBeLessThan(0.1);
|
||||
// Half of a line lies on the other: the share says so, one way round.
|
||||
const half = line(START, spotToward(START, 0, 1000));
|
||||
const whole = line(START, spotToward(START, 0, 2000));
|
||||
expect(sharedShare(half, whole)).toBe(1);
|
||||
expect(sharedShare(whole, half)).toBeCloseTo(0.5, 1);
|
||||
expect(sharedShare([], loop)).toBe(0);
|
||||
expect(sharedShare(loop, line(START))).toBe(0);
|
||||
expect(sharedShare(line(START, START), loop)).toBe(1);
|
||||
});
|
||||
});
|
||||
@@ -1,139 +0,0 @@
|
||||
/**
|
||||
* RTE-03: the plain geometry a round hike is searched with. Where the loop is
|
||||
* steered through, and how much of a routed line covers the same ground twice
|
||||
* or the ground of another line. Nothing here asks a router.
|
||||
*/
|
||||
|
||||
type Spot = { lat: number; lng: number };
|
||||
type Line = readonly (readonly [number, number])[];
|
||||
|
||||
const EARTH_M = 6_371_000;
|
||||
const toRad = (deg: number) => (deg * Math.PI) / 180;
|
||||
const toDeg = (rad: number) => (rad * 180) / Math.PI;
|
||||
|
||||
/** The spot `meters` away from `from` toward `bearingDeg` (clockwise from north), on the sphere. */
|
||||
export function spotToward(from: Spot, bearingDeg: number, meters: number): Spot {
|
||||
const angle = meters / EARTH_M;
|
||||
const bearing = toRad(bearingDeg);
|
||||
const lat1 = toRad(from.lat);
|
||||
const lng1 = toRad(from.lng);
|
||||
const lat2 = Math.asin(Math.sin(lat1) * Math.cos(angle) + Math.cos(lat1) * Math.sin(angle) * Math.cos(bearing));
|
||||
const lng2 =
|
||||
lng1 +
|
||||
Math.atan2(Math.sin(bearing) * Math.sin(angle) * Math.cos(lat1), Math.cos(angle) - Math.sin(lat1) * Math.sin(lat2));
|
||||
return { lat: toDeg(lat2), lng: ((toDeg(lng2) + 540) % 360) - 180 };
|
||||
}
|
||||
|
||||
/** The loop's length in straight lines from corner to corner, per metre of its circle's radius: a square's. */
|
||||
export const STRAIGHT_PER_RADIUS_M = 4 * Math.SQRT2;
|
||||
|
||||
/**
|
||||
* The three spots a loop out of `start` is steered through: the other corners
|
||||
* of a square in a circle of `radiusM` that touches the start, its centre
|
||||
* toward `bearingDeg`. Walked in order, the loop goes round the circle once
|
||||
* and comes back to the start from the other side.
|
||||
*/
|
||||
export function loopSpots(start: Spot, bearingDeg: number, radiusM: number): Spot[] {
|
||||
const centre = spotToward(start, bearingDeg, radiusM);
|
||||
// Seen from the centre the start lies the other way; the corners follow it a quarter turn apart.
|
||||
const towardStart = bearingDeg + 180;
|
||||
return [90, 180, 270].map((turn) => spotToward(centre, towardStart + turn, radiusM));
|
||||
}
|
||||
|
||||
/** Samples are taken along a line this far apart. */
|
||||
const SAMPLE_M = 20;
|
||||
/** Two samples this close lie on the same ground: about the width of a path and the router's drawing of it. */
|
||||
const SAME_GROUND_M = 25;
|
||||
/**
|
||||
* Ground passed twice only counts when the two passes lie this far apart
|
||||
* along the line: the samples next to one another on a bend are one pass.
|
||||
*/
|
||||
const SECOND_PASS_M = 300;
|
||||
|
||||
interface Sample {
|
||||
x: number;
|
||||
y: number;
|
||||
along: number;
|
||||
}
|
||||
|
||||
/** A flat projection in metres around one latitude, good for the few kilometres a hike spans. */
|
||||
function projector(refLat: number) {
|
||||
const perDegLat = (Math.PI * EARTH_M) / 180;
|
||||
const perDegLng = perDegLat * Math.cos(toRad(refLat));
|
||||
return ([lat, lng]: readonly [number, number]) => ({ x: lng * perDegLng, y: lat * perDegLat });
|
||||
}
|
||||
|
||||
/** The line as samples every few metres, each with how far along the line it lies. */
|
||||
function samplesOf(line: Line, project: ReturnType<typeof projector>): Sample[] {
|
||||
const samples: Sample[] = [];
|
||||
let along = 0;
|
||||
let next = 0;
|
||||
for (let i = 1; i < line.length; i += 1) {
|
||||
const a = project(line[i - 1]);
|
||||
const b = project(line[i]);
|
||||
const length = Math.hypot(b.x - a.x, b.y - a.y);
|
||||
while (next <= along + length) {
|
||||
const share = length > 0 ? (next - along) / length : 0;
|
||||
samples.push({ x: a.x + (b.x - a.x) * share, y: a.y + (b.y - a.y) * share, along: next });
|
||||
next += SAMPLE_M;
|
||||
}
|
||||
along += length;
|
||||
}
|
||||
return samples;
|
||||
}
|
||||
|
||||
const cellOf = (value: number) => Math.floor(value / SAME_GROUND_M);
|
||||
|
||||
/** The samples by the grid cell they lie in, so a neighbour is looked for among a few, not all. */
|
||||
function gridOf(samples: readonly Sample[]): Map<string, Sample[]> {
|
||||
const grid = new Map<string, Sample[]>();
|
||||
for (const sample of samples) {
|
||||
const key = `${cellOf(sample.x)}:${cellOf(sample.y)}`;
|
||||
const cell = grid.get(key);
|
||||
if (cell) cell.push(sample);
|
||||
else grid.set(key, [sample]);
|
||||
}
|
||||
return grid;
|
||||
}
|
||||
|
||||
/** Whether a sample of `grid` that `counts` lies on the same ground as `sample`. */
|
||||
function hasNeighbour(grid: Map<string, Sample[]>, sample: Sample, counts: (other: Sample) => boolean): boolean {
|
||||
const cx = cellOf(sample.x);
|
||||
const cy = cellOf(sample.y);
|
||||
for (let dx = -1; dx <= 1; dx += 1) {
|
||||
for (let dy = -1; dy <= 1; dy += 1) {
|
||||
const near = grid
|
||||
.get(`${cx + dx}:${cy + dy}`)
|
||||
?.some((other) => Math.hypot(other.x - sample.x, other.y - sample.y) <= SAME_GROUND_M && counts(other));
|
||||
if (near) return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* The share of a line that covers ground it passes a second time, from 0 to
|
||||
* 1. A loop with a short way in and out shares little; the same way there and
|
||||
* back shares all of it.
|
||||
*/
|
||||
export function retracedShare(line: Line): number {
|
||||
if (line.length < 2) return 0;
|
||||
const samples = samplesOf(line, projector(line[0][0]));
|
||||
if (samples.length < 2) return 0;
|
||||
const grid = gridOf(samples);
|
||||
const twice = samples.filter((sample) =>
|
||||
hasNeighbour(grid, sample, (other) => Math.abs(other.along - sample.along) > SECOND_PASS_M)
|
||||
).length;
|
||||
return twice / samples.length;
|
||||
}
|
||||
|
||||
/** The share of line `a` that lies on the ground of line `b`, from 0 to 1. */
|
||||
export function sharedShare(a: Line, b: Line): number {
|
||||
if (a.length < 2 || b.length < 2) return 0;
|
||||
const project = projector(a[0][0]);
|
||||
const samples = samplesOf(a, project);
|
||||
if (samples.length === 0) return 0;
|
||||
const grid = gridOf(samplesOf(b, project));
|
||||
const shared = samples.filter((sample) => hasNeighbour(grid, sample, () => true)).length;
|
||||
return shared / samples.length;
|
||||
}
|
||||
@@ -10,9 +10,9 @@ const { valhallaRun, enrichTourElevations } = vi.hoisted(() => ({
|
||||
vi.mock('../../Map/valhallaRoute', () => ({ valhallaRun }));
|
||||
vi.mock('./tourRouting', () => ({ enrichTourElevations }));
|
||||
|
||||
import { spotToward } from './roundHikeGeometry';
|
||||
import { findRoundHikes, MAX_ROUND_ASKS, type RoundSearchReport } from './roundHikeRouting';
|
||||
import { fitsWish, type RoundRequest } from './roundHikes';
|
||||
import { fitsWish, MAX_ROUND_ASKS, spotToward } from '@trek/shared';
|
||||
import { findRoundHikes, type RoundSearchReport } from './roundHikeRouting';
|
||||
import type { RoundRequest } from './roundHikes';
|
||||
|
||||
type Spot = { lat: number; lng: number };
|
||||
|
||||
|
||||
@@ -1,34 +1,12 @@
|
||||
import { haversineKm } from '../../../utils/geo';
|
||||
import { searchRoundLoops, type RoundLoop } from '@trek/shared';
|
||||
import { valhallaRun } from '../../Map/valhallaRoute';
|
||||
import { figuresOf } from './legVariants';
|
||||
import { loopSpots, retracedShare, sharedShare, STRAIGHT_PER_RADIUS_M } from './roundHikeGeometry';
|
||||
import { fitsWish, ROUND_KEYS, type RoundCandidate, type RoundRequest } from './roundHikes';
|
||||
import { ROUND_KEYS, type RoundCandidate, type RoundRequest } from './roundHikes';
|
||||
import { MAX_TOUR_SNAP_M } from './tourRouteOutcome';
|
||||
import { enrichTourElevations } from './tourRouting';
|
||||
|
||||
type Spot = { lat: number; lng: number };
|
||||
|
||||
/**
|
||||
* The directions a search sends its loops in, in turn: three a third of a
|
||||
* turn apart first, so the first rounds found lie on different sides of the
|
||||
* start, then the three between them.
|
||||
*/
|
||||
const BEARINGS = [0, 120, 240, 60, 180, 300] as const;
|
||||
/**
|
||||
* The most questions one search puts to the router. The public instance
|
||||
* answers one a second, so a search ends within about a quarter of a minute,
|
||||
* with the heights of what it found.
|
||||
*/
|
||||
export const MAX_ROUND_ASKS = 12;
|
||||
/** How much longer the paths are than the straight lines between the corners, until the router said. */
|
||||
const FIRST_DETOUR = 1.3;
|
||||
/** A loop walking more than this share of its ground twice is an out and back, not a round. */
|
||||
const MAX_RETRACED_SHARE = 0.4;
|
||||
/** Two rounds sharing more than this share of their ground are one round, walked a little apart. */
|
||||
const MAX_SHARED_SHARE = 0.6;
|
||||
/** A loop that missed the length is asked again once, its circle scaled within these bounds. */
|
||||
const RESCALE = { min: 0.5, max: 2 } as const;
|
||||
|
||||
/** Where a search stands: still asking, done with what it found, or without one answer from the router. */
|
||||
export interface RoundSearchReport {
|
||||
phase: 'searching' | 'done' | 'failed';
|
||||
@@ -37,33 +15,17 @@ export interface RoundSearchReport {
|
||||
asked: number;
|
||||
}
|
||||
|
||||
/** A loop the router planned: its line, where it met the steering spots, and how far it is. */
|
||||
interface Loop {
|
||||
coordinates: [number, number][];
|
||||
via: Spot[];
|
||||
distanceM: number;
|
||||
/** The same loop in straight lines from corner to corner. */
|
||||
straightM: number;
|
||||
}
|
||||
|
||||
const clamp = (value: number, { min, max }: { min: number; max: number }) => Math.min(max, Math.max(min, value));
|
||||
|
||||
/** The circle a loop of `targetM` is steered round, for paths `detour` times longer than straight lines. */
|
||||
const radiusFor = (targetM: number, detour: number) => targetM / (detour * STRAIGHT_PER_RADIUS_M);
|
||||
|
||||
function straightLength(spots: readonly Spot[]): number {
|
||||
let km = 0;
|
||||
for (let i = 1; i < spots.length; i += 1) km += haversineKm(spots[i - 1], spots[i]);
|
||||
return km * 1000;
|
||||
}
|
||||
|
||||
/**
|
||||
* One loop out of the start and back, asked on foot under the hike's rules:
|
||||
* the same question the planner asks for a hike through these points, so the
|
||||
* round taken is the round shown. `undefined` when the router gave no answer,
|
||||
* null when a spot lies too far from any path to steer through.
|
||||
*/
|
||||
async function askLoop(request: RoundRequest, spots: Spot[], signal: AbortSignal): Promise<Loop | null | undefined> {
|
||||
async function askLoop(
|
||||
request: RoundRequest,
|
||||
spots: Spot[],
|
||||
signal: AbortSignal
|
||||
): Promise<RoundLoop | null | undefined> {
|
||||
const points = [request.start, ...spots, request.start];
|
||||
const run = await valhallaRun(points, 'walking', [], signal, request.costing);
|
||||
if (!run) return undefined;
|
||||
@@ -73,28 +35,12 @@ async function askLoop(request: RoundRequest, spots: Spot[], signal: AbortSignal
|
||||
coordinates,
|
||||
via: run.snapped.slice(1, -1).map(({ at }) => ({ lat: at[0], lng: at[1] })),
|
||||
distanceM: figuresOf(coordinates).distanceM,
|
||||
straightM: straightLength(points),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* What a planned loop is worth: a round to offer, a loop to ask again larger
|
||||
* or smaller, or nothing (an out and back, or a round already found).
|
||||
*/
|
||||
function judge(loop: Loop, request: RoundRequest, found: readonly RoundCandidate[]): 'round' | 'rescale' | 'drop' {
|
||||
if (!fitsWish(loop.distanceM, request.targetM)) return 'rescale';
|
||||
if (retracedShare(loop.coordinates) > MAX_RETRACED_SHARE) return 'drop';
|
||||
const known = found.some(
|
||||
(round) =>
|
||||
Math.max(sharedShare(loop.coordinates, round.coordinates), sharedShare(round.coordinates, loop.coordinates)) >
|
||||
MAX_SHARED_SHARE
|
||||
);
|
||||
return known ? 'drop' : 'round';
|
||||
}
|
||||
|
||||
function candidateOf(loop: Loop, index: number): RoundCandidate {
|
||||
function candidateOf(loop: RoundLoop, index: number): RoundCandidate {
|
||||
return {
|
||||
key: ROUND_KEYS[index],
|
||||
key: ROUND_KEYS[index] ?? 'c',
|
||||
current: false,
|
||||
coordinates: loop.coordinates,
|
||||
...figuresOf(loop.coordinates),
|
||||
@@ -103,63 +49,32 @@ function candidateOf(loop: Loop, index: number): RoundCandidate {
|
||||
};
|
||||
}
|
||||
|
||||
/** What one search has learned so far, carried from one question to the next. */
|
||||
interface SearchState {
|
||||
found: RoundCandidate[];
|
||||
asked: number;
|
||||
answered: number;
|
||||
detour: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* The loops in one direction: asked once at the size the detour so far
|
||||
* suggests, and once more scaled by how far the first missed the length.
|
||||
*/
|
||||
async function searchBearing(request: RoundRequest, bearing: number, state: SearchState, signal: AbortSignal) {
|
||||
let radius = radiusFor(request.targetM, state.detour);
|
||||
for (let attempt = 0; attempt < 2 && state.asked < MAX_ROUND_ASKS; attempt += 1) {
|
||||
const loop = await askLoop(request, loopSpots(request.start, bearing, radius), signal);
|
||||
state.asked += 1;
|
||||
if (signal.aborted || loop === undefined) return;
|
||||
state.answered += 1;
|
||||
if (!loop) return;
|
||||
// The paths here are this much longer than the straight lines: the next circle is drawn for them.
|
||||
if (loop.straightM > 0) state.detour = clamp(loop.distanceM / loop.straightM, { min: 1, max: 3 });
|
||||
const verdict = judge(loop, request, state.found);
|
||||
if (verdict === 'round') state.found.push(candidateOf(loop, state.found.length));
|
||||
if (verdict !== 'rescale') return;
|
||||
radius *= clamp(request.targetM / loop.distanceM, RESCALE);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* RTE-03: up to three different round hikes out of the start, each within a
|
||||
* fifth of the wished length. The router plans loops steered round circles
|
||||
* in several directions; a loop that misses the length is asked once more at
|
||||
* a corrected size, one that walks its ground twice or repeats a round found
|
||||
* is left out. Then the heights of each round, one after the other. `report`
|
||||
* hears every step, so the rounds and their figures fill in as they come;
|
||||
* nothing is reported once `signal` aborts.
|
||||
* fifth of the wished length, searched by the rules both the planner and the
|
||||
* assistant search by (`searchRoundLoops`), the loops asked of the browser's
|
||||
* router. Then the heights of each round, one after the other. `report` hears
|
||||
* every step, so the rounds and their figures fill in as they come; nothing
|
||||
* is reported once `signal` aborts.
|
||||
*/
|
||||
export async function findRoundHikes(
|
||||
request: RoundRequest,
|
||||
signal: AbortSignal,
|
||||
report: (answer: RoundSearchReport) => void
|
||||
): Promise<void> {
|
||||
const state: SearchState = { found: [], asked: 0, answered: 0, detour: FIRST_DETOUR };
|
||||
for (const bearing of BEARINGS) {
|
||||
if (state.found.length >= ROUND_KEYS.length || state.asked >= MAX_ROUND_ASKS) break;
|
||||
await searchBearing(request, bearing, state, signal);
|
||||
if (signal.aborted) return;
|
||||
report({ phase: 'searching', candidates: [...state.found], asked: state.asked });
|
||||
}
|
||||
const state = await searchRoundLoops(request.start, request.targetM, (spots) => askLoop(request, spots, signal), {
|
||||
signal,
|
||||
onStep: ({ found, asked }) => report({ phase: 'searching', candidates: found.map(candidateOf), asked }),
|
||||
});
|
||||
if (signal.aborted) return;
|
||||
if (state.answered === 0) {
|
||||
report({ phase: 'failed', candidates: [], asked: state.asked });
|
||||
return;
|
||||
}
|
||||
let candidates = [...state.found];
|
||||
const found = state.found.map(candidateOf);
|
||||
let candidates = [...found];
|
||||
report({ phase: 'done', candidates, asked: state.asked });
|
||||
for (const round of state.found) {
|
||||
for (const round of found) {
|
||||
const heights = await enrichTourElevations(round.coordinates, signal);
|
||||
if (signal.aborted) return;
|
||||
// A round without heights keeps its length; its climb, descent and time stay unknown.
|
||||
|
||||
@@ -1,17 +1,11 @@
|
||||
// FE-TOUR-ROUND-HIKES-001 to FE-TOUR-ROUND-HIKES-007: the model of round hikes out of a stop,
|
||||
// FE-TOUR-ROUND-HIKES-002 to FE-TOUR-ROUND-HIKES-007: the model of round hikes out of a stop,
|
||||
// when a round fits the wish, what a search asks and the plan a chosen round becomes (RTE-03).
|
||||
import { isClosedLoop } from '@trek/shared';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { haversineKm } from '../../../utils/geo';
|
||||
import {
|
||||
canStartRound,
|
||||
deviationOf,
|
||||
distanceWindow,
|
||||
fitsWish,
|
||||
isRoundTarget,
|
||||
metersTyped,
|
||||
ROUND_MAX_M,
|
||||
ROUND_MIN_M,
|
||||
roundPlanOf,
|
||||
roundRequestOf,
|
||||
roundStarts,
|
||||
@@ -27,25 +21,7 @@ const BACK: TourPlannerWaypoint = { id: 'back', lat: 47.5, lng: 11.1, role: 'end
|
||||
const COSTING = { max_hiking_difficulty: 2 };
|
||||
|
||||
describe('the wished length', () => {
|
||||
it('FE-TOUR-ROUND-HIKES-001: a round fits within a fifth either way, and its deviation is signed', () => {
|
||||
const { minM, maxM } = distanceWindow(10_000);
|
||||
expect(minM).toBeCloseTo(8_000);
|
||||
expect(maxM).toBeCloseTo(12_000);
|
||||
expect(fitsWish(8_001, 10_000)).toBe(true);
|
||||
expect(fitsWish(11_999, 10_000)).toBe(true);
|
||||
expect(fitsWish(7_999, 10_000)).toBe(false);
|
||||
expect(fitsWish(12_001, 10_000)).toBe(false);
|
||||
expect(deviationOf(10_800, 10_000)).toBeCloseTo(0.08);
|
||||
expect(deviationOf(9_500, 10_000)).toBeCloseTo(-0.05);
|
||||
});
|
||||
|
||||
it('FE-TOUR-ROUND-HIKES-002: only a number in range can be asked for, typed in either unit', () => {
|
||||
expect(isRoundTarget(null)).toBe(false);
|
||||
expect(isRoundTarget(Number.NaN)).toBe(false);
|
||||
expect(isRoundTarget(ROUND_MIN_M - 1)).toBe(false);
|
||||
expect(isRoundTarget(ROUND_MIN_M)).toBe(true);
|
||||
expect(isRoundTarget(ROUND_MAX_M)).toBe(true);
|
||||
expect(isRoundTarget(ROUND_MAX_M + 1)).toBe(false);
|
||||
it('FE-TOUR-ROUND-HIKES-002: a length is typed in either unit', () => {
|
||||
expect(metersTyped('12,5', 'metric')).toBe(12_500);
|
||||
expect(metersTyped(' 10 ', 'metric')).toBe(10_000);
|
||||
expect(metersTyped('', 'metric')).toBeNull();
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
import { isClosedLoop, type PlannableTourType } from '@trek/shared';
|
||||
import { distanceWindow, isClosedLoop, isRoundTarget, spotToward, type PlannableTourType } from '@trek/shared';
|
||||
import type { DistanceUnit } from '../../../types';
|
||||
import { convertDistance } from '../../../utils/units';
|
||||
import type { CostingOptions } from '../../Map/valhallaRoute';
|
||||
import { OTHER_WAY_KEYS, type LegVariant } from './legVariants';
|
||||
import { spotToward } from './roundHikeGeometry';
|
||||
import type { TourPlannerWaypoint } from './tourPlannerWaypoints';
|
||||
import { closeLoop } from './tourRouteActions';
|
||||
|
||||
@@ -16,15 +15,6 @@ import { closeLoop } from './tourRouteActions';
|
||||
|
||||
type Spot = { lat: number; lng: number };
|
||||
|
||||
/** How far a round may lie off the wished length and still be offered: a fifth either way. */
|
||||
export const ROUND_TOLERANCE = 0.2;
|
||||
/** The shortest round asked for, in metres: below it there is hardly a loop to walk. */
|
||||
export const ROUND_MIN_M = 1_000;
|
||||
/** The longest round asked for, in metres: a long day on foot, and as far as the router is asked to plan in one go. */
|
||||
export const ROUND_MAX_M = 60_000;
|
||||
/** The length a search starts with, in metres, until one was asked for. */
|
||||
export const ROUND_DEFAULT_M = 10_000;
|
||||
|
||||
/** The rounds one search offers at most, lettered and coloured like the other ways of a section. */
|
||||
export const ROUND_KEYS = OTHER_WAY_KEYS;
|
||||
export type RoundKey = (typeof ROUND_KEYS)[number];
|
||||
@@ -46,22 +36,6 @@ export interface RoundRequest {
|
||||
key: string;
|
||||
}
|
||||
|
||||
/** The shortest and longest round that fits a wish of `targetM`. */
|
||||
export function distanceWindow(targetM: number): { minM: number; maxM: number } {
|
||||
return { minM: targetM * (1 - ROUND_TOLERANCE), maxM: targetM * (1 + ROUND_TOLERANCE) };
|
||||
}
|
||||
|
||||
/** Whether a round of `distanceM` fits a wish of `targetM`. */
|
||||
export function fitsWish(distanceM: number, targetM: number): boolean {
|
||||
const { minM, maxM } = distanceWindow(targetM);
|
||||
return distanceM >= minM && distanceM <= maxM;
|
||||
}
|
||||
|
||||
/** How far a round lies off the wish, as a signed share: 0.08 is 8 % longer, -0.05 is 5 % shorter. */
|
||||
export function deviationOf(distanceM: number, targetM: number): number {
|
||||
return (distanceM - targetM) / targetM;
|
||||
}
|
||||
|
||||
/**
|
||||
* A length as typed in the traveller's unit, in metres; a comma reads as a
|
||||
* decimal point. Null while the text is no number.
|
||||
@@ -78,11 +52,6 @@ export function typedLength(meters: number, unit: DistanceUnit): string {
|
||||
return String(Math.round(convertDistance(meters / 1000, unit) * 10) / 10);
|
||||
}
|
||||
|
||||
/** Whether a wished length can be asked for at all. */
|
||||
export function isRoundTarget(targetM: number | null): targetM is number {
|
||||
return targetM !== null && Number.isFinite(targetM) && targetM >= ROUND_MIN_M && targetM <= ROUND_MAX_M;
|
||||
}
|
||||
|
||||
/**
|
||||
* The points a round can start from: the stops of the tour. A shaping point
|
||||
* is no place to start from, and the way back of a loop is its start again.
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import {
|
||||
hikingCosting,
|
||||
ROUND_DEFAULT_M,
|
||||
type HikingPreferences,
|
||||
type PlannableTourType,
|
||||
type TourMaxHikingDifficulty,
|
||||
@@ -10,7 +11,6 @@ import type { CostingOptions } from '../../Map/valhallaRoute';
|
||||
import { findRoundHikes, type RoundSearchReport } from './roundHikeRouting';
|
||||
import {
|
||||
canStartRound,
|
||||
ROUND_DEFAULT_M,
|
||||
roundPlanOf,
|
||||
roundRequestOf,
|
||||
searchAreaOf,
|
||||
|
||||
Reference in New Issue
Block a user