From 4bbe3a863899dcac4ae2d215827555980442f7b0 Mon Sep 17 00:00:00 2001 From: Dirk Wahrheit Date: Fri, 20 Nov 2026 10:44:05 +1200 Subject: [PATCH 1/3] feat: judge a passage only up to the land that stops it MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A boat behind a headland or an island heading our way raised alarms although it would have to go round the land first. With S-57 charts served by a chart provider that offers its tiles through the chartTiles PropertyValue (signalk-charts-provider-simple), a passage now ends where a boat, or own ship, would reach charted land: at least 150 m of it along the course, with charted water right before and after, on the course and on the courses 3° to either side. The boat raises only if it comes close enough before that, as one that first crosses our bow does, and ranks by when it gets there. Land never raises a level. A course once stopped by land is stopped at the same place again by 50 m of it, kept through gaps of up to a minute. Land next to waters no chart covers, land where any chart shows water or could not be read, land at either end of a course and overview charts without zoom 14 tiles do not count. While the tiles of a course load, no level rises, for at most 10 s; a tile read gives up after 5 s, and a course that cannot be checked shows no land. Nothing to set up: without such charts everything stays as before. The plugin now recommends signalk-charts-provider-simple. --- AGENTS.md | 10 +- README.md | 4 +- package-lock.json | 43 ++++ package.json | 5 +- src/cpa.ts | 11 + src/evaluator.ts | 259 ++++++++++++++++++---- src/index.ts | 23 +- src/land.ts | 472 +++++++++++++++++++++++++++++++++++++++++ test/evaluator.test.ts | 424 +++++++++++++++++++++++++++++++++++- test/land.test.ts | 413 ++++++++++++++++++++++++++++++++++++ test/plugin.test.ts | 2 + test/tiles.ts | 120 +++++++++++ 12 files changed, 1741 insertions(+), 45 deletions(-) create mode 100644 src/land.ts create mode 100644 test/land.test.ts create mode 100644 test/tiles.ts diff --git a/AGENTS.md b/AGENTS.md index ae1b626..5dce929 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -15,6 +15,13 @@ sensors raises one alarm. - `zones.ts` — sensitivity presets and `assess()`, the level decision with hysteresis. - `evaluator.ts` — reads the data model, keeps per-target levels, drives a sink. +- `land.ts` — the land on S-57 charts (`LNDARE`; any chart's `DEPARE` or + `DRGARE` water wins), read from the tiles a chart provider plugin offers + through the `chartTiles` PropertyValue (signalk-charts-provider-simple), in + process, so it works on secured servers. `landRuns` gives the stretches of + land along a course with charted water on either side, from cached tiles, + loading missing ones in the background. The evaluator judges a passage only + up to where land stops either course; land never raises a level. - `targets.ts` — folds `targets.*` contexts (radar, camera; the server's sensor-targets convention) into the evaluator's input: a target with `sameAs` joins the context it names, the rest become objects of their own, @@ -43,7 +50,8 @@ sensors raises one alarm. - **Schema defaults are not applied at runtime.** `start()` receives `{}` for a plugin that was never configured; always merge `DEFAULTS` under the config. - **No install scripts.** The app store installs with `--ignore-scripts`; keep - runtime dependencies pure JS (today: `typebox` only). + runtime dependencies pure JS (today: `typebox`, and `@mapbox/vector-tile` + with `pbf` to read chart tiles). - **ESM.** Relative imports carry the `.js` extension (nodenext module resolution); the entry is `export default function (app)`. - **Clear what you raise.** Every path that stops tracking a target (lost, diff --git a/README.md b/README.md index b3a8522..caf8ff4 100644 --- a/README.md +++ b/README.md @@ -11,6 +11,7 @@ Install **Collision Alerts** from the App Store. It starts by itself with the Co - **Using SK Derived Data for CPA?** Turn its CPA calculation off, or every alarm comes twice. - **Had the older `signalk-collision-alerts` plugin?** Uninstall it, or every alarm comes twice. Its settings don't carry over. - **Have radar or a camera?** Also install **Target Fusion** from the App Store. A boat seen on both AIS and radar then raises one alarm, not two. +- **Have S-57 (ENC) charts?** Serve them with **Charts Provider Simple** 2.22 or later from the App Store. A boat that could reach you only across charted land, such as one behind a headland or an island, then raises nothing, within the limits under **Behind land** below. There is nothing to set up. ## Settings @@ -53,6 +54,7 @@ The plugin tries to alarm only when it matters: - **Between AIS reports.** Small boats report only every 30 s. In between, each boat is judged where it is by now, carried on along its course for up to a minute. A boat moving slower than 3 kn, judged by the Harbour limits, alarms only once a report puts it inside the alarm limits, or once its last report is 40 s old: it may be turning into its berth. A faster boat, judged by them at your berth with _Only for boats coming straight at you_, alarms on dead reckoning at once. - **Busy waters.** At most 3 boats warn or alarm at once, the most urgent first. A warning that had to make room for a more urgent boat stays quiet for 2 minutes, unless it turns into an alarm or clears the limits and comes back. - **No flicker.** An alarm stays on until the boat is clearly outside the limits again. +- **Behind land.** With S-57 (ENC) charts served by Charts Provider Simple 2.22 or later, a passage ends where a boat, or you, would reach charted land: at least 150 m of it along the course, with charted water right before and after, on the course and on the courses 3° to either side. The boat would have to go round. It raises only if it comes close enough before that, as one that first crosses your bow does, and is judged anew as soon as its course runs clear. A course once stopped by land is stopped at the same place again by 50 m of it, so one swinging across the tip of a headland does not switch the alarm on and off. This is kept through gaps of up to a minute in judging the boat. A course that only clips a point, land where any chart shows water or a chart could not be read, land next to waters no chart covers (such as unsurveyed areas) and land right where a boat or its closest approach is charted never count. Overview charts, which have no tiles at zoom 14, are not read. While the charts for a course load, no warning or alarm rises, for at most 10 s. Charts can be wrong or out of date: land only ever lowers a warning or alarm, never raises one. The 3 kn is the advanced setting **Use the harbour distances when both boats are slower than X knots**. Set it to 0 to turn off the harbour, berth, stopped-boat and overtaking rules above, so every boat gets your chosen limits. Boats crossing your wake still stay quiet. The 3 boats are **No more than X boats raising alarms at the same time**. @@ -62,4 +64,4 @@ A current mayara plugin leaves radar collision alarms to this plugin, so a boat ## For app developers -Each alarm is a notification at `notifications.navigation.closestApproach.` on your own vessel, raised through the server's Notifications API, or as a plain notification delta on servers that don't manage notifications. Its `data` holds `targetRef` (the target's context, such as `vessels.urn:mrn:imo:mmsi:244123456` or `targets.radar:…`), `source`, `sources` (when radar or a camera sees the target), `cpa` (m), `tcpa` (s), `range` (m), `targetCog` (rad, `null` when stopped), `targetSog` (m/s) and `cpaPositions`. Each target in range also gets `navigation.closestApproach` `{ distance, timeTo }`, which can be turned off. It is published when the target reports, when your course or speed changes, and otherwise at the first evaluation at least 10 s after the last, so a display that shows `timeTo` as received runs up to that long behind: 10 s at the default 2 s interval. Radar and camera targets are read from `targets.:` contexts. One whose `sameAs` names an AIS vessel joins it, and the alarm goes under the vessel's id. While the plugin runs, it emits the `collisionAlerts` PropertyValue `{ evaluatesTargets: true }`, and `{ evaluatesTargets: false }` when it stops, so sensor plugins can leave their alarms to it. +Each alarm is a notification at `notifications.navigation.closestApproach.` on your own vessel, raised through the server's Notifications API, or as a plain notification delta on servers that don't manage notifications. Its `data` holds `targetRef` (the target's context, such as `vessels.urn:mrn:imo:mmsi:244123456` or `targets.radar:…`), `source`, `sources` (when radar or a camera sees the target), `cpa` (m), `tcpa` (s), `range` (m), `targetCog` (rad, `null` when stopped), `targetSog` (m/s) and `cpaPositions`. Each target in range also gets `navigation.closestApproach` `{ distance, timeTo }`, which can be turned off. It is published when the target reports, when your course or speed changes, and otherwise at the first evaluation at least 10 s after the last, so a display that shows `timeTo` as received runs up to that long behind: 10 s at the default 2 s interval. Radar and camera targets are read from `targets.:` contexts. One whose `sameAs` names an AIS vessel joins it, and the alarm goes under the vessel's id. Land is read from the `chartTiles` PropertyValue, which a chart provider plugin such as Charts Provider Simple offers: `getTile(chartId, z, x, y)` for its charts' tiles, in-process, so it needs no token on a secured server. The S-57 charts are those the resources API lists with type `S-57`, and their land is their `LNDARE` layer. While the plugin runs, it emits the `collisionAlerts` PropertyValue `{ evaluatesTargets: true }`, and `{ evaluatesTargets: false }` when it stops, so sensor plugins can leave their alarms to it. diff --git a/package-lock.json b/package-lock.json index f983e19..aa82da0 100644 --- a/package-lock.json +++ b/package-lock.json @@ -9,6 +9,8 @@ "version": "0.9.0", "license": "Apache-2.0", "dependencies": { + "@mapbox/vector-tile": "^3.0.0", + "pbf": "^5.1.2", "typebox": "^1.3.34" }, "devDependencies": { @@ -323,6 +325,23 @@ "dev": true, "license": "MIT" }, + "node_modules/@mapbox/point-geometry": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@mapbox/point-geometry/-/point-geometry-1.1.0.tgz", + "integrity": "sha512-YGcBz1cg4ATXDCM/71L9xveh4dynfGmcLDqufR+nQQy3fKwsAZsWd/x4621/6uJaeB9mwOHE6hPeDgXz9uViUQ==", + "license": "ISC" + }, + "node_modules/@mapbox/vector-tile": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/@mapbox/vector-tile/-/vector-tile-3.0.0.tgz", + "integrity": "sha512-Qf10S1uIHMk20ri/IVBnpS+esUEkVaR5Hftmz88jTInrpmWgPGJfPe3LVjjlE77trLx8tH6qjTG7uWH9hIq/0Q==", + "license": "BSD-3-Clause", + "dependencies": { + "@mapbox/point-geometry": "~1.1.0", + "@types/geojson": "^7946.0.16", + "pbf": "^5.0.0" + } + }, "node_modules/@oxc-project/types": { "version": "0.156.0", "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.156.0.tgz", @@ -702,6 +721,12 @@ "dev": true, "license": "MIT" }, + "node_modules/@types/geojson": { + "version": "7946.0.16", + "resolved": "https://registry.npmjs.org/@types/geojson/-/geojson-7946.0.16.tgz", + "integrity": "sha512-6C8nqWur3j98U6+lXDfTUWIfgvZU+EumvpHKcYjujKH7woYyLj2sUmff0tRhrqM7BohUw7Pz3ZB1jj2gW9Fvmg==", + "license": "MIT" + }, "node_modules/@types/json-schema": { "version": "7.0.15", "resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.15.tgz", @@ -2075,6 +2100,18 @@ "node": ">=8" } }, + "node_modules/pbf": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/pbf/-/pbf-5.2.0.tgz", + "integrity": "sha512-R6YptaRZl0t9SVO6MllszYq1IkaOQawzprndmvQxEoFrtvX7fT+oNIPoVD152NOllmLWEC3ThxzUTqBX12q5FQ==", + "license": "BSD-3-Clause", + "dependencies": { + "protocol-buffers-schema": "^3.6.1" + }, + "bin": { + "pbf": "bin/pbf" + } + }, "node_modules/picocolors": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", @@ -2165,6 +2202,12 @@ "node": ">=6.0.0" } }, + "node_modules/protocol-buffers-schema": { + "version": "3.6.1", + "resolved": "https://registry.npmjs.org/protocol-buffers-schema/-/protocol-buffers-schema-3.6.1.tgz", + "integrity": "sha512-VG2K63Igkiv9p76tk1lilczEK1cT+kCjKtkdhw1dQZV3k3IXJbd3o6Ho8b9zJZaHSnT2hKe4I+ObmX9w6m5SmQ==", + "license": "MIT" + }, "node_modules/punycode": { "version": "2.3.1", "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", diff --git a/package.json b/package.json index 1562761..fd7d68c 100644 --- a/package.json +++ b/package.json @@ -31,7 +31,8 @@ "./docs/screenshots/cpa-alarm.png" ], "recommends": [ - "signalk-target-fusion" + "signalk-target-fusion", + "signalk-charts-provider-simple" ] }, "files": [ @@ -44,6 +45,8 @@ "signalk": ">=2.31.0" }, "dependencies": { + "@mapbox/vector-tile": "^3.0.0", + "pbf": "^5.1.2", "typebox": "^1.3.34" }, "devDependencies": { diff --git a/src/cpa.ts b/src/cpa.ts index 9ea57d2..1855f07 100644 --- a/src/cpa.ts +++ b/src/cpa.ts @@ -86,6 +86,17 @@ export function computeCpa(own: Track, target: Track): CpaResult { } } +/** The distance (m) between two tracks `seconds` from now. */ +export function separationAt(own: Track, target: Track, seconds: number): number { + const cosLat = Math.cos(own.position.latitude * DEG) + const dLon = wrapDegrees(target.position.longitude - own.position.longitude) + const rx = dLon * DEG * cosLat * EARTH_RADIUS + const ry = (target.position.latitude - own.position.latitude) * DEG * EARTH_RADIUS + const vx = target.sog * Math.sin(target.cog) - own.sog * Math.sin(own.cog) + const vy = target.sog * Math.cos(target.cog) - own.sog * Math.cos(own.cog) + return Math.hypot(rx + vx * seconds, ry + vy * seconds) +} + /** `rx`, `ry`: target relative to own ship (m); `vx`, `vy`: its relative velocity (m/s). */ function bowCrossing( own: Track, diff --git a/src/evaluator.ts b/src/evaluator.ts index 78964f9..e9d8bb8 100644 --- a/src/evaluator.ts +++ b/src/evaluator.ts @@ -1,4 +1,11 @@ -import { advance, computeCpa, type CpaResult, type Track } from './cpa.js' +import { + advance, + computeCpa, + separationAt, + type CpaResult, + type LatLon, + type Track +} from './cpa.js' import type { AlarmSink, CollisionAlert } from './alarms.js' import { DriftDetector } from './drift.js' import { MotionCheck } from './motion.js' @@ -30,6 +37,16 @@ export interface TargetNode extends VesselNode { sources?: string[] } +/** What the charts show along a course. */ +export interface LandCheck { + /** + * The stretches of land a straight course from `from` to `to` crosses with + * charted water on either side, in order: where each begins and its + * length, metres. Undefined while the charts for it are still loading. + */ + landRuns(from: LatLon, to: LatLon): { start: number; length: number }[] | undefined +} + export interface EvaluatorOptions { zones: Zone[] /** @@ -52,6 +69,8 @@ export interface EvaluatorOptions { maxRange: number /** Data older than this (seconds) is ignored. */ maxAge: number + /** Charts to tell a course to closest approach that runs across land. */ + land?: LandCheck } export type Evaluation = { @@ -137,6 +156,83 @@ const DISPLACED_HOLD = 120_000 // below 2 kn reports only every 3 min. const REPORT_CONFIRM_WAIT = 40_000 +// A boat cannot keep a course across this much land (m), with water on +// either side: its passage ends where its course, or ours, reaches it, and +// it is judged anew once its course runs clear. A smaller islet, spit or +// pier does not count, since a boat rounds it in moments. +const LAND_BLOCKS = 150 + +// Land within this distance (m) of where a course was last stopped, or +// this share of the way there if more, is the same land, and stops it from +// this length (m) on: a course swings a few degrees with every report, and +// near a headland the land it crosses swings with it. +const SAME_LAND = 300 +const SAME_LAND_SHARE = Math.sin((6 * Math.PI) / 180) +const LAND_CLEARS = 50 + +// Land stops a boat only if it also stops the courses this angle to either +// side of its own (3°, the course error a fast boat is judged with): one +// whose course just clips a headland may as well pass it. +const LAND_COURSE_ERROR = Math.asin(COURSE_ERROR) + +// While the charts of a target's courses load, its level does not rise, for +// no longer than this (ms). +const LAND_WAIT = 10_000 + +// Where land stopped a target's courses is remembered through gaps in its +// level or data this long (ms). +const LAND_MEMORY = 60_000 + +/** + * Where land stops a track's courses: when it reaches it, s from now, and + * where on each course. + */ +export interface LandStop { + time: number + at: LatLon[] +} + +function metresBetween(a: LatLon, b: LatLon): number { + return separationAt({ position: a, cog: 0, sog: 0 }, { position: b, cog: 0, sog: 0 }, 0) +} + +const LAND_COURSES = [0, -LAND_COURSE_ERROR, LAND_COURSE_ERROR] + +/** + * Where land stops a track in the next `seconds`: land at least + * LAND_BLOCKS long, or LAND_CLEARS where `before` says it stopped that + * course last, on its course and on the courses LAND_COURSE_ERROR to + * either side, at the latest of their times. Null when one of them runs + * clear, undefined while the charts for them load. + */ +export function landStop( + land: LandCheck, + track: Track, + seconds: number, + before: LatLon[] | undefined +): LandStop | null | undefined { + if (track.sog === 0 || seconds <= 0) return null + // All three are asked at once, so their charts load together. + const stops = LAND_COURSES.map((turn, i) => { + const course = { ...track, cog: track.cog + turn } + const runs = land.landRuns(track.position, advance(course, seconds)) + if (!runs) return undefined + const last = before?.[i] + const run = runs.find((r) => { + const same = + last !== undefined && + metresBetween(advance(course, r.start / track.sog), last) <= + Math.max(SAME_LAND, r.start * SAME_LAND_SHARE) + return r.length >= (same ? LAND_CLEARS : LAND_BLOCKS) + }) + return run ? { time: run.start / track.sog, at: advance(course, run.start / track.sog) } : null + }) + if (stops.includes(null)) return null + if (stops.includes(undefined)) return undefined + const found = stops as { time: number; at: LatLon }[] + return { time: Math.max(...found.map((s) => s.time)), at: found.map((s) => s.at) } +} + // A target already alarmed ranks as if its closest approach came this many // seconds sooner, so two targets of similar urgency don't take turns at the // last alarm slot, which would re-sound the alarm every few seconds. @@ -147,7 +243,10 @@ interface Candidate { node: TargetNode level: AlertLevel result: CpaResult - /** Seconds to closest approach as judged: past for boats keeping their distance. */ + /** + * Seconds to closest approach as judged, or to where land stops a course + * if sooner: past for boats keeping their distance. + */ tcpa: number target: Track } @@ -273,6 +372,15 @@ export class Evaluator { private readonly drift = new DriftDetector() /** When `evaluate` last ran, ms since the epoch. */ private lastEvaluation: number | undefined + /** + * Per target, where land last stopped its course and ours, when the charts + * of the courses began loading, and when it was last judged by them, ms + * since the epoch. + */ + private readonly landStates = new Map< + string, + { theirs?: LatLon[]; ours?: LatLon[]; loadingSince?: number; at: number } + >() /** The normal zones with the slow zones' distances. */ private readonly cutZones: Zone[] @@ -341,7 +449,8 @@ export class Evaluator { const reported = raw && this.motion.apply(targetId, raw, time) const target = reported && this.drift.apply(targetId, reported, time) const carried = reportAge(time, nowMs) - const result = own && target ? computeCpa(own, deadReckon(target, carried)) : null + const targetNow = target && deadReckon(target, carried) + const result = own && targetNow ? computeCpa(own, targetNow) : null const context = contextOf(targetId, node) if (!target || !result || result.range > this.options.maxRange) { if (!result) { @@ -434,18 +543,6 @@ export class Evaluator { // approaching. const judgedTime = (t: number) => !result.keepingDistance && target.sog > 0 && t < 0 && t > -carried ? 0 : t - const judgedTcpa = judgedTime(tcpa) - const crossing = result.bowCrossing - const courseErrorReach = (error: number) => - ownStopped && target.sog >= FAST_TARGET_SPEED - ? Math.max(0, result.cpa - target.sog * Math.max(0, tcpa) * error) - : result.cpa - const cpa = courseErrorReach(COURSE_ERROR) - const judged: Passage = { - cpa, - tcpa: judgedTcpa, - bowCrossing: crossing && { ...crossing, time: judgedTime(crossing.time) } - } // A raised level is judged by every zone set it has been judged by since // it was raised, until it clears: speed noise near a threshold would // otherwise swap the zones every few updates, clearing the alarm and @@ -470,32 +567,108 @@ export class Evaluator { } return level } - let level = judge(judged) - if (current !== undefined) { - const held = judge({ ...judged, cpa: courseErrorReach(HELD_COURSE_ERROR) }) - const kept = severity(held) > severity(current) ? current : held - if (severity(kept) > severity(level)) { - level = kept + // The level of a passage whose closest approach is `closest` metres, + // `time` seconds from now, with this bow crossing. + const levelOf = ( + closest: number, + time: number, + crossing: CpaResult['bowCrossing'] + ): { level: AlertLevel | undefined; judged: Passage } => { + const courseErrorReach = (error: number) => + ownStopped && target.sog >= FAST_TARGET_SPEED + ? Math.max(0, closest - target.sog * Math.max(0, time) * error) + : closest + const cpa = courseErrorReach(COURSE_ERROR) + const judged: Passage = { + cpa, + tcpa: judgedTime(time), + bowCrossing: crossing && { ...crossing, time: judgedTime(crossing.time) } } + let level = judge(judged) + if (current !== undefined) { + const held = judge({ ...judged, cpa: courseErrorReach(HELD_COURSE_ERROR) }) + const kept = severity(held) > severity(current) ? current : held + if (severity(kept) > severity(level)) { + level = kept + } + } + if ( + judgedBy === SLOW_SET && + targetSlow && + target.sog > 0 && + carried * 1000 < REPORT_CONFIRM_WAIT && + severity(level) >= SEVERITY.alarm + ) { + // At its last report, its closest approach was as close, only + // further ahead. + const asReported = judge({ + cpa, + tcpa: time + carried, + bowCrossing: crossing && { ...crossing, time: crossing.time + carried } + }) + if (severity(asReported) < severity(level)) { + // Never below a level it has and keeps carried on. + const kept = severity(current) < severity(level) ? current : level + level = severity(asReported) > severity(kept) ? asReported : kept + } + } + return { level, judged } } - if ( - judgedBy === SLOW_SET && - targetSlow && - target.sog > 0 && - carried * 1000 < REPORT_CONFIRM_WAIT && - severity(level) >= SEVERITY.alarm - ) { - // At its last report, its closest approach was as close, only further - // ahead. - const asReported = judge({ - cpa, - tcpa: tcpa + carried, - bowCrossing: crossing && { ...crossing, time: crossing.time + carried } - }) - if (severity(asReported) < severity(level)) { - // Never below a level it has and keeps carried on. - const kept = severity(current) < severity(level) ? current : level - level = severity(asReported) > severity(kept) ? asReported : kept + const passage = levelOf(result.cpa, tcpa, result.bowCrossing) + let judged = passage.judged + let level = passage.level + // When the closest approach comes, as far as the boats can get to it. + let reachedTcpa = tcpa + const land = this.options.land + if (level && land && own && targetNow && !result.keepingDistance && result.tcpa > 0) { + // The boats come no closer than where land stops one of them, so the + // passage is judged only up to there: a boat that crosses our bow or + // comes close before it reaches the land still raises. Land only ever + // lowers a level. + const kept = this.landStates.get(targetId) + const state = + kept && nowMs >= kept.at && nowMs - kept.at <= LAND_MEMORY ? kept : { at: nowMs } + state.at = nowMs + this.landStates.set(targetId, state) + const theirs = landStop(land, targetNow, result.tcpa, state.theirs) + const ours = landStop(land, own, result.tcpa, state.ours) + // Each course keeps where land stopped it until its charts say + // otherwise. + if (theirs !== undefined) state.theirs = theirs?.at + if (ours !== undefined) state.ours = ours?.at + // A stop already found holds while the other course loads: the + // boats come no closer than there, if not stopped sooner. + const stops = [theirs, ours].flatMap((stop) => (stop ? [stop.time] : [])) + const end = + stops.length > 0 + ? Math.min(...stops) + : theirs === undefined || ours === undefined + ? undefined + : Infinity + if (end === undefined) { + state.loadingSince ??= nowMs + if ( + nowMs >= state.loadingSince && + nowMs - state.loadingSince < LAND_WAIT && + severity(level) > severity(current) + ) { + level = current + } + } else { + state.loadingSince = undefined + if (end !== Infinity) { + const crossing = result.bowCrossing + const beforeLand = levelOf( + separationAt(own, targetNow, end), + end, + crossing && crossing.time <= end ? crossing : null + ) + if (severity(beforeLand.level) < severity(level)) { + level = beforeLand.level + } + judged = beforeLand.judged + reachedTcpa = Math.min(tcpa, end) + } } } if (current === undefined && overtaken && judgedBy === CUT_SET) { @@ -518,7 +691,7 @@ export class Evaluator { } } if (level && !quiet) { - candidates.push({ targetId, node, level, result, tcpa, target }) + candidates.push({ targetId, node, level, result, tcpa: reachedTcpa, target }) } } @@ -527,6 +700,11 @@ export class Evaluator { this.overtakenTargets = overtakenTargets this.zoneSets = zoneSets this.overtakenInZone = overtakenInZone + for (const [targetId, state] of this.landStates) { + if (!seen.has(targetId) || nowMs - state.at > LAND_MEMORY || nowMs < state.at) { + this.landStates.delete(targetId) + } + } this.motion.retain(seen) this.drift.retain(seen) this.levels.clear() @@ -592,6 +770,7 @@ export class Evaluator { this.lastEvaluation = undefined this.overtakenInZone.clear() this.keepingDistanceSince.clear() + this.landStates.clear() this.raised.clear() this.displaced.clear() this.motion.clear() diff --git a/src/index.ts b/src/index.ts index f5f1d27..9d7cefc 100644 --- a/src/index.ts +++ b/src/index.ts @@ -7,12 +7,16 @@ import { Evaluator, positionTime, toTrack, type VesselNode } from './evaluator.j import { DEFAULTS, formSchema, formUiSchema, limitsFor, migrate, type Config } from './config.js' import { targetNodes, type SensorTargetNode } from './targets.js' import { regionChoices, SilentRegions } from './regions.js' +import { ChartLand } from './land.js' const PLUGIN_ID = 'collision-alerts' // 1 while alarms are paused, 0 otherwise; a PUT of 1 pauses, 0 resumes. const PAUSED_PATH = 'navigation.collisionAlerts.paused' // Regions change only when someone edits them in a chart plotter. const REGION_REFRESH_MS = 60_000 +// Charts come and go when someone installs or removes them, and when the +// chart provider starts, which may be after us. +const CHART_REFRESH_MS = 60_000 const NM = 1852 const KNOT = 1852 / 3600 @@ -40,6 +44,8 @@ const WATCHING = 'Watching AIS, radar and other targets' export default function (app: ServerAPI): Plugin { let timer: ReturnType | undefined let regionTimer: ReturnType | undefined + let chartTimer: ReturnType | undefined + let chartLand: ChartLand | undefined // Epoch ms; kept across a restart of the plugin, not of the server. let pausedUntil = 0 // The latest start()'s evaluation; a PUT runs it at once. @@ -104,6 +110,16 @@ export default function (app: ServerAPI): Plugin { const maxAge = config.maxAgeMinutes * 60 const limits = limitsFor(config) const harbour = limitsFor(config, 'harbour') + // Courses across land are told on the S-57 charts a chart provider + // hands out, such as signalk-charts-provider-simple; without one, none. + // Tiles stay at least until every course has been checked again. + const land = new ChartLand(app, Math.max(5000, 3 * config.interval * 1000)) + chartLand = land + const refreshCharts = () => { + void land.refresh() + } + refreshCharts() + chartTimer = setInterval(refreshCharts, CHART_REFRESH_MS) const activeEvaluator = new Evaluator( { zones: limits.zones, @@ -113,7 +129,8 @@ export default function (app: ServerAPI): Plugin { slowSpeed: config.slowSpeed * KNOT, maxAlarms: config.maxAlarms, maxRange: config.maxRange * NM, - maxAge + maxAge, + land }, createSink(app) ) @@ -232,6 +249,10 @@ export default function (app: ServerAPI): Plugin { timer = undefined clearInterval(regionTimer) regionTimer = undefined + clearInterval(chartTimer) + chartTimer = undefined + chartLand?.stop() + chartLand = undefined tick = undefined evaluator?.stop() evaluator = undefined diff --git a/src/land.ts b/src/land.ts new file mode 100644 index 0000000..4ed7dd1 --- /dev/null +++ b/src/land.ts @@ -0,0 +1,472 @@ +import { gunzipSync } from 'node:zlib' +import { VectorTile, type VectorTileLayer } from '@mapbox/vector-tile' +import { PbfReader } from 'pbf' +import type { ServerAPI } from '@signalk/server-api' +import type { LatLon } from './cpa.js' + +/** + * The PropertyValue through which a chart provider plugin hands its tiles to + * other plugins in-process, whatever the server's security settings. + */ +export const CHART_TILES_PROPERTY = 'chartTiles' + +export interface ChartTiles { + /** + * The tile body as served over HTTP (a vector tile may be gzipped). Null + * where the chart has no tile, undefined for a chart this provider does + * not have. + */ + getTile(chartId: string, z: number, x: number, y: number): Promise +} + +/** A stretch of land along a course: where it begins and its length, metres. */ +export interface LandRun { + start: number + length: number +} + +// S-57 object classes, which S-57 vector charts carry as layer names. On one +// chart the land and the water areas never overlap. +const LAND = 'LNDARE' +const WATER = ['DEPARE', 'DRGARE'] + +// Tiles about 2 km across in the tropics. A chart that has no tiles this +// fine is an overview, whose generalised coastline can close a narrow +// passage, and is not read. +const ZOOM = 14 +// Metres between the points tested along a course. +const STEP = 10 +const MAX_POINTS = 2000 +// Tiles kept; more while the courses being checked need them. +const MAX_TILES = 256 +// By default, a tile used this recently (ms) is not evicted. +const IN_USE_MS = 5000 +const PARALLEL_READS = 4 +const READ_TIMEOUT_MS = 5000 +const RETRY_MS = 60_000 +// Charts can be rebuilt in place under the same id; tiles are read afresh +// this often (ms). +const TILE_TTL_MS = 600_000 +const MAX_TILE_BYTES = 16 * 1024 * 1024 +// Horizontal bands per tile into which a layer's edges are sorted, so a +// point is tested against the edges near it only. +const BANDS = 64 +const EARTH_RADIUS = 6371008.8 +const DEG = Math.PI / 180 + +/** A layer's polygon edges, sorted into horizontal bands of the tile. */ +export interface Layer { + extent: number + /** Per band, the edges reaching into it, flat as x1, y1, x2, y2, feature. */ + bands: Int32Array[] + features: number +} + +interface Chart { + id: string + zoom: number + /** West, south, east, north; west > east across the antimeridian. */ + bounds?: [number, number, number, number] +} + +interface ChartResource { + type?: unknown + minzoom?: unknown + maxzoom?: unknown + bounds?: unknown +} + +type Tile = + | { state: 'loaded'; land: Layer[]; water: Layer[] } + | { state: 'none' } + | { state: 'failed'; retryAt: number } + | { state: 'loading' } + +interface Entry { + tile: Tile + usedAt: number +} + +/** What the charts show at a point. */ +type Ground = 'water' | 'land' | 'unknown' | 'loading' + +function chartOf(id: string, chart: ChartResource): Chart | undefined { + if (typeof chart.type !== 'string' || chart.type.toUpperCase() !== 'S-57') return undefined + const min = typeof chart.minzoom === 'number' ? chart.minzoom : 0 + const max = typeof chart.maxzoom === 'number' ? chart.maxzoom : ZOOM + if (max < ZOOM) return undefined + const bounds = + Array.isArray(chart.bounds) && + chart.bounds.length === 4 && + chart.bounds.every((b) => typeof b === 'number' && Number.isFinite(b)) + ? (chart.bounds as [number, number, number, number]) + : undefined + return { id, zoom: Math.max(min, ZOOM), bounds } +} + +function covers(chart: Chart, { latitude, longitude }: LatLon): boolean { + if (!chart.bounds) return true + const [west, south, east, north] = chart.bounds + if (latitude < south || latitude > north) return false + return west <= east + ? longitude >= west && longitude <= east + : longitude >= west || longitude <= east +} + +function wrap(longitude: number): number { + return ((((longitude + 180) % 360) + 360) % 360) - 180 +} + +/** Web Mercator tile coordinates of a point, fractional. */ +export function tileXY({ latitude, longitude }: LatLon, zoom: number): [number, number] { + const n = 2 ** zoom + const lat = Math.max(-85.0511, Math.min(85.0511, latitude)) * DEG + return [ + ((wrap(longitude) + 180) / 360) * n, + ((1 - Math.log(Math.tan(lat) + 1 / Math.cos(lat)) / Math.PI) / 2) * n + ] +} + +function bandOf(y: number, extent: number): number { + return Math.max(0, Math.min(BANDS - 1, Math.floor((y / extent) * BANDS))) +} + +function layerOf(layer: VectorTileLayer): Layer { + const bands: number[][] = Array.from({ length: BANDS }, () => []) + let features = 0 + for (let i = 0; i < layer.length; i++) { + const feature = layer.feature(i) + if (feature.type !== 3) continue + for (const ring of feature.loadGeometry()) { + for (let j = 0, k = ring.length - 1; j < ring.length; k = j++) { + const a = ring[k] + const b = ring[j] + if (a.y === b.y) continue + const last = bandOf(Math.max(a.y, b.y), layer.extent) + for (let band = bandOf(Math.min(a.y, b.y), layer.extent); band <= last; band++) { + bands[band].push(a.x, a.y, b.x, b.y, features) + } + } + } + features++ + } + return { extent: layer.extent, bands: bands.map((edges) => Int32Array.from(edges)), features } +} + +/** The polygons of the named layers of a vector tile, by name. */ +export function tileLayers(body: Uint8Array, names: string[]): Map { + const bytes = + body[0] === 0x1f && body[1] === 0x8b + ? gunzipSync(body, { maxOutputLength: MAX_TILE_BYTES }) + : body + const tile = new VectorTile(new PbfReader(bytes)) + const layers = new Map() + for (const name of names) { + const layer = tile.layers[name] as VectorTileLayer | undefined + if (!layer) continue + // Its positions cannot be read: skipped, a water layer would turn water + // into land. + if (!(layer.extent > 0)) throw new Error(`layer ${name} has no extent`) + layers.set(name, layerOf(layer)) + } + return layers +} + +/** + * Whether a point in tile units lies inside any polygon of a layer, by the + * even-odd rule over each feature's rings: inside an outer ring, outside its + * holes. + */ +export function inLayer({ extent, bands, features }: Layer, x: number, y: number): boolean { + const edges = bands[bandOf(y, extent)] + const odd = new Uint8Array(features) + for (let i = 0; i < edges.length; i += 5) { + const x1 = edges[i] + const y1 = edges[i + 1] + const x2 = edges[i + 2] + const y2 = edges[i + 3] + if (y1 > y !== y2 > y && x < ((x2 - x1) * (y - y1)) / (y2 - y1) + x1) odd[edges[i + 4]] ^= 1 + } + return odd.includes(1) +} + +function isChartTiles(value: unknown): value is ChartTiles { + return ( + typeof value === 'object' && + value !== null && + typeof (value as { getTile?: unknown }).getTile === 'function' + ) +} + +function withTimeout(promise: Promise, ms: number): Promise { + return new Promise((resolve, reject) => { + const timer = setTimeout(() => { + reject(new Error(`no tile within ${ms / 1000} s`)) + }, ms) + promise.then( + (value) => { + clearTimeout(timer) + resolve(value) + }, + (err: unknown) => { + clearTimeout(timer) + reject(err instanceof Error ? err : new Error(String(err))) + } + ) + }) +} + +/** + * The land on the S-57 charts that chart provider plugins hand out, for + * telling where a course runs across it. Tiles are read as courses need + * them, so a question about a new stretch of water is answered once its + * tiles have loaded. + */ +export class ChartLand { + private charts: Chart[] = [] + /** In order of last use, the oldest first. */ + private tiles = new Map() + private queue: { entry: Entry; chart: Chart; x: number; y: number }[] = [] + private reading = 0 + private clearedAt = Date.now() + private stopped = false + /** The latest `chartTiles` of each provider plugin. */ + private providers = new Map() + private readonly unsubscribe: () => void + /** Per chart, the failures already logged since it last read. */ + private readonly reported = new Map>() + + /** + * @param inUseMs a tile used this recently (ms) is not evicted: at least + * the time between two checks of all courses. + */ + constructor( + private readonly app: ServerAPI, + private readonly inUseMs = IN_USE_MS + ) { + this.unsubscribe = app.onPropertyValues(CHART_TILES_PROPERTY, (history) => { + const latest = new Map() + for (const entry of history) { + if (entry) latest.set(entry.setter, entry.value) + } + this.providers = new Map( + [...latest].filter((pair): pair is [string, ChartTiles] => isChartTiles(pair[1])) + ) + // A provider that came or went may change what a tile reads as, and + // one that came may bring charts the list did not have. + this.clear() + void this.refresh() + }) + } + + async refresh(now = Date.now()): Promise { + let charts: Chart[] + // The list comes from other plugins: anything in it that is not a chart + // is skipped, and nothing it holds may make this reject. + try { + const resources: unknown = await this.app.resourcesApi.listResources('charts', {}) + charts = + typeof resources === 'object' && resources !== null + ? Object.entries(resources).flatMap(([id, chart]) => + typeof chart === 'object' && chart !== null + ? (chartOf(id, chart as ChartResource) ?? []) + : [] + ) + : [] + } catch (err) { + this.app.debug(`Could not list charts: ${String(err)}`) + return + } + // A refresh still running at stop() brings no charts back. + if (this.stopped) return + if ( + JSON.stringify(charts) !== JSON.stringify(this.charts) || + now - this.clearedAt > TILE_TTL_MS + ) { + this.charts = charts + this.clear(now) + } + } + + stop(): void { + this.unsubscribe() + this.stopped = true + this.charts = [] + this.clear() + } + + /** + * The stretches of land a straight course from `from` to `to` crosses with + * charted water on either side, in order, or undefined while the charts + * for it are still loading. Land at either end, or next to waters no chart + * covers, does not count: a boat or a closest approach charted on land is + * where a chart is wrong or too coarse, not behind land. + */ + landRuns(from: LatLon, to: LatLon, now = Date.now()): LandRun[] | undefined { + // A tile that cannot be read must not stop the alarms: it shows no land. + try { + return this.scan(from, to, now) + } catch (err) { + this.report('', err instanceof Error ? err.message : String(err)) + return [] + } + } + + private scan(from: LatLon, to: LatLon, now: number): LandRun[] | undefined { + const lat0 = from.latitude * DEG + const dLon = wrap(to.longitude - from.longitude) + const dx = dLon * DEG * Math.cos(lat0) * EARTH_RADIUS + const dy = (to.latitude - from.latitude) * DEG * EARTH_RADIUS + const length = Math.hypot(dx, dy) + const points = Math.min(MAX_POINTS, Math.ceil(length / STEP)) + if (points < 2) return [] + const step = length / points + const memo = new Map() + const grounds: Ground[] = [] + for (let i = 0; i <= points; i++) { + const f = i / points + const point = { + latitude: from.latitude + f * (to.latitude - from.latitude), + longitude: wrap(from.longitude + f * dLon) + } + grounds.push(this.groundAt(point, now, memo)) + } + if (grounds.includes('loading')) return undefined + // A run is measured from its first land point to its last, so it is + // never longer than the land between them. + const runs: LandRun[] = [] + let before: Ground | undefined + let run: LandRun | undefined + grounds.forEach((ground, i) => { + if (ground === 'land') { + if (before === 'water') run = { start: i * step, length: 0 } + if (run) run.length = i * step - run.start + } else if (ground === 'water' && run) { + runs.push(run) + } + if (ground !== 'land') run = undefined + before = ground + }) + return runs + } + + private groundAt(point: LatLon, now: number, memo: Map): Ground { + let land = false + let loading = false + // A chart that could not be read may show water here. + let unread = false + for (const chart of this.charts) { + if (!covers(chart, point)) continue + const [fx, fy] = tileXY(point, chart.zoom) + const x = Math.floor(fx) + const y = Math.floor(fy) + const tile = this.tile(chart, x, y, now, memo) + if (tile.state === 'loading') { + loading = true + continue + } + if (tile.state === 'failed') unread = true + if (tile.state !== 'loaded') continue + const inside = (layer: Layer) => + inLayer(layer, (fx - x) * layer.extent, (fy - y) * layer.extent) + // Charts can disagree on a coastline; where any shows water, a boat + // may well be able to pass. + if (tile.water.some(inside)) return 'water' + if (tile.land.some(inside)) land = true + } + return loading ? 'loading' : land && !unread ? 'land' : 'unknown' + } + + private tile(chart: Chart, x: number, y: number, now: number, memo: Map): Tile { + const key = `${chart.id}/${chart.zoom}/${x}/${y}` + const memoised = memo.get(key) + if (memoised) return memoised + let entry = this.tiles.get(key) + if (entry?.tile.state === 'failed' && now >= entry.tile.retryAt) entry = undefined + if (entry) { + entry.usedAt = now + this.tiles.delete(key) + this.tiles.set(key, entry) + } else { + entry = { tile: { state: 'loading' }, usedAt: now } + this.tiles.set(key, entry) + if (!this.stopped) this.queue.push({ entry, chart, x, y }) + this.evict(now) + this.pump() + } + memo.set(key, entry.tile) + return entry.tile + } + + private evict(now: number): void { + for (const [key, entry] of this.tiles) { + if (this.tiles.size <= MAX_TILES) return + if (entry.tile.state !== 'loading' && now - entry.usedAt >= this.inUseMs) { + this.tiles.delete(key) + } + } + } + + private clear(now = Date.now()): void { + this.tiles = new Map() + this.queue = [] + this.clearedAt = now + } + + private pump(): void { + while (this.reading < PARALLEL_READS && this.queue.length > 0) { + const next = this.queue.shift() + if (next) void this.load(next) + } + } + + /** Reads a tile into its entry; one cleared meanwhile is read into nothing. */ + private async load({ entry, chart, x, y }: { entry: Entry; chart: Chart; x: number; y: number }) { + this.reading++ + try { + const body = await withTimeout(this.read(chart, x, y), READ_TIMEOUT_MS) + if (body === undefined) { + // No provider has the chart, perhaps not yet: one is starting. + entry.tile = { state: 'failed', retryAt: Date.now() + RETRY_MS } + } else { + const layers = body && tileLayers(body, [LAND, ...WATER]) + const land = layers?.get(LAND) + entry.tile = layers + ? { + state: 'loaded', + land: land ? [land] : [], + water: WATER.flatMap((name) => layers.get(name) ?? []) + } + : { state: 'none' } + this.reported.delete(chart.id) + } + } catch (err) { + this.report(chart.id, err instanceof Error ? err.message : String(err)) + entry.tile = { state: 'failed', retryAt: Date.now() + RETRY_MS } + } finally { + this.reading-- + } + this.pump() + } + + /** The tile body, null where its provider has none, undefined when no provider has the chart. */ + private async read(chart: Chart, x: number, y: number): Promise { + for (const provider of this.providers.values()) { + const body = await provider.getTile(chart.id, chart.zoom, x, y) + if (body !== undefined) return body + } + return undefined + } + + private report(chart: string, reason: string): void { + const reported = this.reported.get(chart) ?? new Set() + this.reported.set(chart, reported) + if (reported.has(reason)) return + reported.add(reason) + this.app.error( + chart + ? `Could not read chart ${chart} to check courses across land: ${reason}` + : `Could not check a course across land: ${reason}` + ) + } +} diff --git a/test/evaluator.test.ts b/test/evaluator.test.ts index bc6c3e0..70b8878 100644 --- a/test/evaluator.test.ts +++ b/test/evaluator.test.ts @@ -1,9 +1,10 @@ import { describe, expect, it } from 'vitest' import type { AlarmSink, CollisionAlert } from '../src/alarms.js' -import type { Track } from '../src/cpa.js' +import type { LatLon, Track } from '../src/cpa.js' import { deadReckon, Evaluator, + landStop, reportAge, toTrack, type EvaluatorOptions, @@ -1812,3 +1813,424 @@ describe('judging boats by where they cross our course', () => { expect(passing.sink.calls).toEqual([]) }) }) + +describe('a passage that land ends', () => { + const METRES = (6371008.8 * Math.PI) / 180 + // 1 NM ahead, coming straight at us: an alarm in open water. + const headOn = vessel(50 + 1 / 60, 1, 180, 5) + const passing = { + passingDistance: PASSING_DISTANCE.coastal, + slowPassingDistance: PASSING_DISTANCE.harbour + } + + /** South, north, west, east. */ + type Box = [number, number, number, number] + + /** + * Charts with rectangles of land, water all round them: the stretches of + * each that a straight course crosses from water to water. + */ + function charts(...boxes: Box[]) { + const check = { + boxes, + loading: false, + /** Courses from here are still loading. */ + loadingFrom: undefined as LatLon | undefined, + calls: [] as [LatLon, LatLon][], + landRuns(from: LatLon, to: LatLon) { + check.calls.push([from, to]) + if (check.loading || from === check.loadingFrom) return undefined + const length = Math.hypot( + (to.latitude - from.latitude) * METRES, + (to.longitude - from.longitude) * METRES * Math.cos((from.latitude * Math.PI) / 180) + ) + const runs: { start: number; length: number }[] = [] + for (const [south, north, west, east] of check.boxes) { + // Where the course is inside the box, as fractions of it. + let enter = 0 + let leave = 1 + for (const [p, d, low, high] of [ + [from.latitude, to.latitude - from.latitude, south, north], + [from.longitude, to.longitude - from.longitude, west, east] + ]) { + if (d === 0) { + if (p < low || p > high) leave = -1 + continue + } + const t1 = (low - p) / d + const t2 = (high - p) / d + enter = Math.max(enter, Math.min(t1, t2)) + leave = Math.min(leave, Math.max(t1, t2)) + } + if (enter > 0 && leave < 1 && leave > enter) { + runs.push({ start: enter * length, length: (leave - enter) * length }) + } + } + return runs.sort((x, y) => x.start - y.start) + } + } + return check + } + + /** Land between two parallels, right across the chart. */ + const band = (south: number, north: number) => charts([south, north, -180, 180]) + + /** Land between two meridians, right across the chart. */ + const wall = (west: number, east: number): Box => [-90, 90, west, east] + + /** The longitude `metres` east of ours. */ + const east = (metres: number) => 1 + metres / METRES / Math.cos((50 * Math.PI) / 180) + + /** Land `metres` wide from 0.3 NM north of us. */ + const between = (metres: number) => band(50 + 0.3 / 60, 50 + 0.3 / 60 + metres / METRES) + + it('raises nothing for a boat that land stops short of us', () => { + const open = setup(passing) + open.ev.evaluate(own, { [OTHER]: headOn }, SELF, NOW) + expect(open.sink.calls).toEqual([[OTHER, expect.objectContaining({ level: 'alarm' })]]) + const { sink, ev } = setup({ ...passing, land: between(300) }) + ev.evaluate(own, { [OTHER]: headOn }, SELF, NOW) + expect(sink.calls).toHaveLength(0) + }) + + it('reads the courses from where the boats are to where each would be at closest approach', () => { + // From 300 m west and 700 m north, heading east at our speed: closest + // approach in 100 s, with us 500 m north and it 200 m east of our course. + const land = band(0, 0) + const { ev } = setup({ ...passing, land }) + ev.evaluate(own, { [OTHER]: vessel(50 + 700 / METRES, east(-300), 90, 5) }, SELF, NOW) + // Each course and those 3° to either side of it. + const [theirs, , , ours] = land.calls + expect(theirs[0].longitude).toBeCloseTo(east(-300), 5) + expect(theirs[1].latitude).toBeCloseTo(50 + 700 / METRES, 5) + expect(theirs[1].longitude).toBeCloseTo(east(200), 5) + expect(ours[0]).toBe(own.position) + expect(ours[1].latitude).toBeCloseTo(50 + 500 / METRES, 5) + expect(ours[1].longitude).toBeCloseTo(1, 5) + }) + + it('counts no land narrower than 150 m', () => { + const { sink, ev } = setup({ ...passing, land: between(140) }) + ev.evaluate(own, { [OTHER]: headOn }, SELF, NOW) + expect(sink.calls).toEqual([[OTHER, expect.objectContaining({ level: 'alarm' })]]) + }) + + it('still alarms for a boat that crosses our bow before it reaches land', () => { + // From 300 m west and 700 m north, heading east at our speed: it crosses + // 400 m ahead of us in 60 s, and reaches land 20 m east of our course + // line, before its closest approach 200 m east of it. + const crossing = vessel(50 + 700 / METRES, east(-300), 90, 5) + const { sink, ev } = setup({ ...passing, land: charts(wall(east(20), east(190))) }) + ev.evaluate(own, { [OTHER]: crossing }, SELF, NOW) + expect(sink.calls).toEqual([[OTHER, expect.objectContaining({ level: 'alarm' })]]) + }) + + it('never raises a level by ending a passage at land', () => { + // Closing at 10 m/s from 3800 m: dead ahead in 380 s, just too late for + // the alarm. We reach 160 m of land at 2800 m in 350 s, 300 m apart. + const fast = defined(toTrack(vessel(50, 1, 0, 8), NOW, 360)) + const slow = vessel(50 + 3800 / METRES, 1, 180, 2) + const land = band(50 + 2800 / METRES, 50 + 2960 / METRES) + const { sink, ev } = setup({ land }) + ev.evaluate(fast, { [OTHER]: slow }, SELF, NOW) + expect(sink.calls).toEqual([[OTHER, expect.objectContaining({ level: 'warn' })]]) + }) + + it('lets a boat pass land its course only clips, which it may as well miss', () => { + // 300 m of land from 0.3 NM north of us, reaching `half` metres to either + // side of our course. + const point = (half: number): Box => [ + 50 + 0.3 / 60, + 50 + 0.3 / 60 + 300 / METRES, + east(-half), + east(half) + ] + const clipped = setup({ ...passing, land: charts(point(20)) }) + clipped.ev.evaluate(own, { [OTHER]: headOn }, SELF, NOW) + expect(clipped.sink.calls).toEqual([[OTHER, expect.objectContaining({ level: 'alarm' })]]) + // Wide enough for the courses 3° to either side, if not 6°. + for (const half of [40, 200]) { + const blocked = setup({ ...passing, land: charts(point(half)) }) + blocked.ev.evaluate(own, { [OTHER]: headOn }, SELF, NOW) + expect(blocked.sink.calls).toHaveLength(0) + } + }) + + it('counts 50 m only of the land that stopped a course, not of other land', () => { + const land = between(300) + const { sink, ev } = setup({ ...passing, land }) + ev.evaluate(own, { [OTHER]: headOn }, SELF, NOW) + // 55 m of land on our course, 300 m on from where land stopped it: it + // does not stop it. + land.boxes = band(50 + 860 / METRES, 50 + 915 / METRES).boxes + ev.evaluate(own, { [OTHER]: headOn }, SELF, NOW + 2000) + expect(sink.calls).toEqual([[OTHER, expect.objectContaining({ level: 'alarm' })]]) + // Nor 100 m on the boat's course, where land never stopped it. + land.boxes = band(50 + 1111 / METRES, 50 + 1211 / METRES).boxes + ev.evaluate(own, { [OTHER]: headOn }, SELF, NOW + 4000) + expect(sink.calls).toEqual([ + [OTHER, expect.objectContaining({ level: 'alarm' })], + [OTHER, expect.objectContaining({ level: 'alarm' })] + ]) + }) + + it('forgets after a minute where land stopped a course', () => { + const land = between(300) + const { sink, ev } = setup({ ...passing, land }) + ev.evaluate(own, { [OTHER]: headOn }, SELF, NOW) + land.boxes = between(100).boxes + ev.evaluate(own, { [OTHER]: headOn }, SELF, NOW + 61_000) + expect(sink.calls).toEqual([[OTHER, expect.objectContaining({ level: 'alarm' })]]) + }) + + it('drops a bow crossing the boat would come to only past the land', () => { + // From 300 m west and 700 m north, heading east: it would cross 400 m + // ahead of us in 60 s, but reaches 170 m of land 250 m west of our + // course in 10 s. + const crossing = vessel(50 + 700 / METRES, east(-300), 90, 5) + const open = setup(passing) + open.ev.evaluate(own, { [OTHER]: crossing }, SELF, NOW) + expect(open.sink.calls).toHaveLength(1) + const { sink, ev } = setup({ ...passing, land: charts(wall(east(-250), east(-80))) }) + ev.evaluate(own, { [OTHER]: crossing }, SELF, NOW) + expect(sink.calls).toHaveLength(0) + }) + + it('ends the passage where the first of the two courses reaches land', () => { + // It reaches land in 20 s, 1652 m off; we would in 100 s, 852 m off, + // inside the warning distance. + const land = charts( + [50 + 1592 / METRES, 50 + 1752 / METRES, -180, 180], + [50 + 500 / METRES, 50 + 660 / METRES, -180, 180] + ) + const { sink, ev } = setup({ land }) + ev.evaluate(own, { [OTHER]: headOn }, SELF, NOW) + expect(sink.calls).toHaveLength(0) + }) + + it('stops a course at 50 m only where land stopped that course, for any course', () => { + // The boat's course stopped by 300 m of land 0.4 NM north of its + // closest approach, then by 100 m there. + const north = (metres: number) => 50 + metres / METRES + const land = band(north(1100), north(1400)) + const { sink, ev } = setup({ ...passing, land }) + ev.evaluate(own, { [OTHER]: headOn }, SELF, NOW) + land.boxes = band(north(1300), north(1400)).boxes + ev.evaluate(own, { [OTHER]: headOn }, SELF, NOW + 2000) + // Ours stopped 200 m on from where it was, by 55 m. + const ours = between(300) + const second = setup({ ...passing, land: ours }) + second.ev.evaluate(own, { [OTHER]: headOn }, SELF, NOW) + ours.boxes = band(north(756), north(811)).boxes + second.ev.evaluate(own, { [OTHER]: headOn }, SELF, NOW + 2000) + expect([...sink.calls, ...second.sink.calls]).toHaveLength(0) + }) + + it('forgets where land stopped a course once it runs clear', () => { + // Ours, then the boat's, 0.4 NM north of its closest approach. + const north = (metres: number) => 50 + metres / METRES + for (const [wide, narrow] of [ + [between(300), between(100)], + [band(north(1100), north(1400)), band(north(1300), north(1400))] + ]) { + const land = charts(...wide.boxes) + const { sink, ev } = setup({ ...passing, land }) + ev.evaluate(own, { [OTHER]: headOn }, SELF, NOW) + land.boxes = [] + ev.evaluate(own, { [OTHER]: headOn }, SELF, NOW + 2000) + land.boxes = narrow.boxes + ev.evaluate(own, { [OTHER]: headOn }, SELF, NOW + 4000) + expect(sink.calls.map(([, alert]) => alert?.level)).toEqual(['alarm', 'alarm']) + } + }) + + it('forgets where land stopped the boat once its course runs clear, while ours loads', () => { + const north = (metres: number) => 50 + metres / METRES + const land = band(north(1100), north(1400)) + const { sink, ev } = setup({ ...passing, land }) + ev.evaluate(own, { [OTHER]: headOn }, SELF, NOW) + land.boxes = [] + land.loadingFrom = own.position + ev.evaluate(own, { [OTHER]: headOn }, SELF, NOW + 2000) + land.boxes = band(north(1300), north(1400)).boxes + land.loadingFrom = undefined + ev.evaluate(own, { [OTHER]: headOn }, SELF, NOW + 4000) + expect(sink.calls).toEqual([[OTHER, expect.objectContaining({ level: 'alarm' })]]) + }) + + it('keeps a stop found on one course while the other loads, past the wait', () => { + const north = (metres: number) => 50 + metres / METRES + const land = band(north(1100), north(1400)) + land.loadingFrom = own.position + const { sink, ev } = setup({ ...passing, land }) + ev.evaluate(own, { [OTHER]: headOn }, SELF, NOW) + ev.evaluate(own, { [OTHER]: headOn }, SELF, NOW + 12_000) + expect(sink.calls).toHaveLength(0) + }) + + describe('far off', () => { + // We lie still; the boat comes from 11 km north at 10 m/s, a warning by + // the Offshore limits. Land from 4000 m to 4300 m north of us. + const still = defined(toTrack(vessel(50, 1, 0, 0), NOW, 360)) + const north = (metres: number) => 50 + metres / METRES + const coming = (cogDeg: number) => vessel(north(11000), 1, cogDeg, 10) + const offshore = { zones: PRESETS.offshore } + + it('stops each of the three courses where that one was stopped before', () => { + // The land's east edge is where the course 3° east of the boat's + // leaves it, after 169 m, then after 112 m as the edge seen swings. + const island = (edge: number): Box => [north(4000), north(4300), east(-1000), east(edge)] + const land = charts(island(360)) + const { sink, ev } = setup({ ...offshore, land }) + for (let i = 0; i < 6; i++) { + land.boxes = [island(i % 2 === 0 ? 360 : 357)] + ev.evaluate(still, { [OTHER]: coming(180) }, SELF, NOW + i * 2000) + } + expect(sink.calls).toHaveLength(0) + }) + + it('takes land as the same where a course 6.7 km long swings 3° across it', () => { + const land = band(north(4000), north(4300)) + const { sink, ev } = setup({ ...offshore, land }) + ev.evaluate(still, { [OTHER]: coming(180) }, SELF, NOW) + // 100 m of it now, met 350 m further east. + land.boxes = band(north(4200), north(4300)).boxes + ev.evaluate(still, { [OTHER]: coming(177) }, SELF, NOW + 2000) + expect(sink.calls).toHaveLength(0) + }) + }) + + it('raises nothing for a boat we overtake that land stops short of us', () => { + // We come up on a boat 100 m ahead at 1 m/s more than its 4 m/s. Without + // land it alarms at once; land from 250 m ahead stops it 62 m off. + const ahead = vessel(50 + 100 / METRES, 1, 0, 4) + const overtaking = { ...passing, slowSpeed: (3 * 1852) / 3600 } + const open = setup(overtaking) + open.ev.evaluate(own, { [OTHER]: ahead }, SELF, NOW) + expect(open.sink.calls).toEqual([[OTHER, expect.objectContaining({ level: 'alarm' })]]) + const land = band(50 + 250 / METRES, 50 + 410 / METRES) + const { sink, ev } = setup({ ...overtaking, land }) + ev.evaluate(own, { [OTHER]: ahead }, SELF, NOW) + expect(sink.calls).toHaveLength(0) + }) + + it('forgets a stop dated later than now, as after the clock was set back', () => { + const land = between(300) + const { sink, ev } = setup({ ...passing, land }) + ev.evaluate(own, { [OTHER]: headOn }, SELF, NOW + 10_000) + land.boxes = between(100).boxes + ev.evaluate(own, { [OTHER]: headOn }, SELF, NOW) + expect(sink.calls).toEqual([[OTHER, expect.objectContaining({ level: 'alarm' })]]) + }) + + it('ranks a boat by when land stops it', () => { + // Both would pass 700 m off, a warning. The one to the east would in + // 200 s, but land stops it in 167 s; the one to the west passes in 185 s. + const eastern = vessel(50 + 2000 / METRES, east(700), 180, 5) + const western = vessel(50 + 1850 / METRES, east(-700), 180, 5) + const land = charts([50 + 1005 / METRES, 50 + 1165 / METRES, east(500), east(900)]) + const { sink, ev } = setup({ land, maxAlarms: 1 }) + ev.evaluate(own, { [OTHER]: eastern, [THIRD]: western }, SELF, NOW) + expect(sink.calls).toEqual([[OTHER, expect.objectContaining({ level: 'warn' })]]) + }) + + it('raises nothing when our own course reaches land first', () => { + const anchored = vessel(50 + 1 / 60, 1, 0, 0) + const open = setup(passing) + open.ev.evaluate(own, { [OTHER]: anchored }, SELF, NOW) + expect(open.sink.calls).toHaveLength(1) + const { sink, ev } = setup({ ...passing, land: between(300) }) + ev.evaluate(own, { [OTHER]: anchored }, SELF, NOW) + expect(sink.calls).toHaveLength(0) + }) + + it('clears an alarm once the passage ends at land', () => { + const land = band(0, 0) + const { sink, ev } = setup({ ...passing, land }) + ev.evaluate(own, { [OTHER]: headOn }, SELF, NOW) + land.boxes = between(300).boxes + ev.evaluate(own, { [OTHER]: headOn }, SELF, NOW + 2000) + expect(sink.calls).toEqual([ + [OTHER, expect.objectContaining({ level: 'alarm' })], + [OTHER, undefined] + ]) + }) + + it('lets a passage that ended at land run on only past less than 50 m, through gaps', () => { + const land = between(300) + const { sink, ev } = setup({ ...passing, land }) + ev.evaluate(own, { [OTHER]: headOn }, SELF, NOW) + land.boxes = between(100).boxes + ev.evaluate(own, { [OTHER]: headOn }, SELF, NOW + 2000) + // Out of range for a moment: no level, nothing judged. + ev.evaluate(own, { [OTHER]: vessel(50 + 20 / 60, 1, 180, 5) }, SELF, NOW + 4000) + ev.evaluate(own, { [OTHER]: headOn }, SELF, NOW + 6000) + expect(sink.calls).toHaveLength(0) + land.boxes = between(40).boxes + ev.evaluate(own, { [OTHER]: headOn }, SELF, NOW + 8000) + expect(sink.calls).toEqual([[OTHER, expect.objectContaining({ level: 'alarm' })]]) + }) + + it('raises no level while the charts load, for up to 10 s', () => { + const land = between(300) + land.loading = true + const { sink, ev } = setup({ ...passing, land }) + ev.evaluate(own, { [OTHER]: headOn }, SELF, NOW) + ev.evaluate(own, { [OTHER]: headOn }, SELF, NOW + 8000) + expect(sink.calls).toHaveLength(0) + ev.evaluate(own, { [OTHER]: headOn }, SELF, NOW + 10_000) + expect(sink.calls).toEqual([[OTHER, expect.objectContaining({ level: 'alarm' })]]) + }) + + it('keeps a passage that ended at land quiet while the charts load, for up to 10 s', () => { + const land = between(300) + const { sink, ev } = setup({ ...passing, land }) + ev.evaluate(own, { [OTHER]: headOn }, SELF, NOW) + land.loading = true + ev.evaluate(own, { [OTHER]: headOn }, SELF, NOW + 2000) + ev.evaluate(own, { [OTHER]: headOn }, SELF, NOW + 10_000) + expect(sink.calls).toHaveLength(0) + ev.evaluate(own, { [OTHER]: headOn }, SELF, NOW + 12_000) + expect(sink.calls).toEqual([[OTHER, expect.objectContaining({ level: 'alarm' })]]) + }) + + it('keeps a raised alarm while the charts load', () => { + const land = band(0, 0) + const { sink, ev } = setup({ ...passing, land }) + ev.evaluate(own, { [OTHER]: headOn }, SELF, NOW) + land.loading = true + ev.evaluate(own, { [OTHER]: headOn }, SELF, NOW + 2000) + expect(sink.calls).toEqual([ + [OTHER, expect.objectContaining({ level: 'alarm' })], + [OTHER, expect.objectContaining({ level: 'alarm' })] + ]) + }) + + describe('landStop', () => { + // Heading north at 10 m/s for 200 s. + const track: Track = { position: { latitude: 50, longitude: 1 }, cog: 0, sog: 10 } + + it('takes the latest time any of the three courses reaches land', () => { + // Land from 1000 m north west of our course, from 1100 m east of it. + const land = charts( + [50 + 1000 / METRES, 50 + 1300 / METRES, east(-200), east(1)], + [50 + 1100 / METRES, 50 + 1300 / METRES, east(1), east(200)] + ) + expect(landStop(land, track, 200, undefined)?.time).toBeCloseTo(110.15, 1) + }) + + it('asks all three courses at once, and none stops it if one runs clear', () => { + const land = between(300) + land.loading = true + expect(landStop(land, track, 200, undefined)).toBeUndefined() + expect(land.calls).toHaveLength(3) + const partly = charts() + let calls = 0 + const clearFirst = { + landRuns: (from: LatLon, to: LatLon) => + calls++ === 0 ? partly.landRuns(from, to) : undefined + } + expect(landStop(clearFirst, track, 200, undefined)).toBeNull() + }) + }) +}) diff --git a/test/land.test.ts b/test/land.test.ts new file mode 100644 index 0000000..215ed2a --- /dev/null +++ b/test/land.test.ts @@ -0,0 +1,413 @@ +import { gzipSync } from 'node:zlib' +import { afterEach, describe, expect, it, vi } from 'vitest' +import type { PropertyValue, ServerAPI } from '@signalk/server-api' +import { + CHART_TILES_PROPERTY, + ChartLand, + inLayer, + tileLayers, + tileXY, + type ChartTiles, + type LandRun +} from '../src/land.js' +import { bandTile, encodeTile, stripsTile } from './tiles.js' + +// A band of land 0.004° (445 m) wide from 10° N, right across the chart, in +// tile row 7734 at zoom 14. +const SOUTH = 10 +const NORTH = 10.004 +const ROW = 7734 +const METRES = (6371008.8 * Math.PI) / 180 +const BAND = 0.004 * METRES + +const enc = { type: 'S-57', minzoom: 8, maxzoom: 16, bounds: [19, 9, 21, 11] } + +const at = (latitude: number, longitude = 20) => ({ latitude, longitude }) + +type Requests = [string, number, number, number][] + +function band( + options: Parameters[4] = {}, + zip = false, + chart = 'enc', + requests: Requests = [] +): ChartTiles { + return { + getTile: (chartId, z, x, y) => { + requests.push([chartId, z, x, y]) + if (chartId !== chart) return Promise.resolve(undefined) + const tile = bandTile(z, y, SOUTH, NORTH, options) + return Promise.resolve(zip ? gzipSync(tile) : tile) + } + } +} + +function fakeApp(charts: Record) { + const history: (PropertyValue | undefined)[] = [undefined] + let listener: ((values: (PropertyValue | undefined)[]) => void) | undefined + const app = { + debug: vi.fn(), + error: vi.fn(), + resourcesApi: { listResources: vi.fn(() => Promise.resolve(charts)) }, + onPropertyValues: vi.fn((name: string, cb: (values: (PropertyValue | undefined)[]) => void) => { + if (name !== CHART_TILES_PROPERTY) return () => undefined + listener = cb + cb([...history]) + return () => { + listener = undefined + } + }) + } + const emit = (setter: string, value: unknown) => { + history.push({ timestamp: Date.now(), setter, name: CHART_TILES_PROPERTY, value }) + listener?.([...history]) + } + return { app: app as unknown as ServerAPI, error: app.error, emit } +} + +async function chartLand(charts: Record, ...providers: ChartTiles[]) { + const fake = fakeApp(charts) + providers.forEach((provider, i) => { + fake.emit(`provider${i}`, provider) + }) + const land = new ChartLand(fake.app) + await land.refresh() + return { land, ...fake } +} + +const settle = () => new Promise((resolve) => setTimeout(resolve, 0)) + +/** The land along a course once its tiles have loaded. */ +async function runs( + land: ChartLand, + from: { latitude: number; longitude: number }, + to = from, + now = Date.now() +): Promise { + land.landRuns(from, to, now) + await settle() + return land.landRuns(from, to, now) +} + +/** The single run across the band on a course from 9.995° N to 10.009° N. */ +function expectBand(found: LandRun[] | undefined) { + expect(found).toHaveLength(1) + const [run] = found ?? [] + expect(run.start).toBeGreaterThan(0.005 * METRES - 20) + expect(run.start).toBeLessThan(0.005 * METRES + 20) + expect(run.length).toBeGreaterThan(BAND - 20) + expect(run.length).toBeLessThan(BAND + 20) +} + +afterEach(() => { + vi.useRealTimers() +}) + +describe('tileLayers', () => { + it('reads the polygons of the named layers, gzipped or not', () => { + const square: [number, number][] = [ + [0, 0], + [100, 0], + [100, 100], + [0, 100] + ] + const hole: [number, number][] = [ + [40, 40], + [40, 60], + [60, 60], + [60, 40] + ] + const tile = encodeTile({ LNDARE: [[square, hole]], SOUNDG: [[square]] }) + for (const body of [tile, gzipSync(tile)]) { + const layers = tileLayers(body, ['LNDARE', 'DEPARE']) + expect([...layers.keys()]).toEqual(['LNDARE']) + const layer = layers.get('LNDARE') + expect(layer).toBeDefined() + if (!layer) return + expect(inLayer(layer, 20, 20)).toBe(true) + expect(inLayer(layer, 50, 50)).toBe(false) + expect(inLayer(layer, 150, 20)).toBe(false) + } + }) +}) + +describe('tileXY', () => { + it('finds the tiles a chart plotter shows', () => { + // Nouméa, in the tile Freeboard requests at zoom 14. + const [x, y] = tileXY(at(-22.2877, 166.4356), 14) + expect([Math.floor(x), Math.floor(y)]).toEqual([15766, 9232]) + }) +}) + +describe('ChartLand', () => { + it('finds where a course crosses land with water on either side', async () => { + const { land } = await chartLand({ enc }, band()) + // Undecided until the tiles have loaded. + expect(land.landRuns(at(9.995), at(10.009))).toBeUndefined() + expectBand(await runs(land, at(9.995), at(10.009))) + }) + + it('counts no land at either end of a course', async () => { + const { land } = await chartLand({ enc }, band()) + expect(await runs(land, at(10.002), at(10.009))).toEqual([]) + expect(await runs(land, at(9.995), at(10.002))).toEqual([]) + }) + + it('measures land from its first point to its last, never longer than it is', async () => { + const narrow: ChartTiles = { + getTile: (_chart, z, _x, y) => + Promise.resolve( + stripsTile(z, y, { + LNDARE: [[SOUTH, SOUTH + 142 / METRES]], + DEPARE: [ + [9, SOUTH], + [SOUTH + 142 / METRES, 11] + ] + }) + ) + } + const { land } = await chartLand({ enc }, narrow) + // However the points along the course fall on it. + for (let shift = 0; shift < 10; shift++) { + const from = at(9.995 + shift / METRES) + const found = await runs(land, from, { ...from, latitude: from.latitude + 0.014 }) + expect(found).toHaveLength(1) + expect(found?.[0].length).toBeLessThanOrEqual(142) + expect(found?.[0].length).toBeGreaterThan(120) + } + }) + + it('breaks land at waters no chart covers', async () => { + // Water, 80 m of land, 500 m nothing charted, 80 m of land, water. + const m = (metres: number) => SOUTH + metres / METRES + const islets: ChartTiles = { + getTile: (_chart, z, _x, y) => + Promise.resolve( + stripsTile(z, y, { + LNDARE: [ + [m(0), m(80)], + [m(580), m(660)] + ], + DEPARE: [ + [9, m(0)], + [m(660), 11] + ] + }) + ) + } + const { land } = await chartLand({ enc }, islets) + expect(await runs(land, at(9.995), at(10.009))).toEqual([]) + }) + + it('counts no land where a chart that covers it could not be read', async () => { + const charts = { enc, other: enc } + const unread: ChartTiles = { + getTile: (chartId) => + chartId === 'other' ? Promise.reject(new Error('busy')) : Promise.resolve(undefined) + } + const { land } = await chartLand(charts, band(), unread) + expect(await runs(land, at(9.995), at(10.009))).toEqual([]) + }) + + it('takes a tile whose layer has no extent for one it could not read', async () => { + const square: [number, number][] = [ + [0, 0], + [100, 0], + [100, 100], + [0, 100] + ] + expect(() => tileLayers(encodeTile({ DEPARE: [[square]] }, 0), ['DEPARE'])).toThrow('no extent') + // So the water it may hold vetoes another chart's land. + const charts = { enc, other: enc } + const broken: ChartTiles = { + getTile: (chartId) => + Promise.resolve(chartId === 'other' ? encodeTile({ DEPARE: [[square]] }, 0) : undefined) + } + const { land } = await chartLand(charts, band(), broken) + expect(await runs(land, at(9.995), at(10.009))).toEqual([]) + }) + + it('shows no land, and says so, where a course cannot be checked', async () => { + const { land, error } = await chartLand({ enc }, band()) + vi.spyOn(land as unknown as { scan: () => never }, 'scan').mockImplementation(() => { + throw new Error('bad geometry') + }) + expect(land.landRuns(at(9.995), at(10.009))).toEqual([]) + expect(error).toHaveBeenCalledWith(expect.stringContaining('bad geometry')) + }) + + it('counts no land without charted water on either side', async () => { + const { land } = await chartLand({ enc }, band({ water: false })) + expect(await runs(land, at(9.995), at(10.009))).toEqual([]) + }) + + it('counts no land where another chart shows water', async () => { + const charts = { enc, other: enc } + const { land } = await chartLand( + charts, + band(), + band({ layer: 'DEPARE', water: false }, false, 'other') + ) + expect(await runs(land, at(9.995), at(10.009))).toEqual([]) + }) + + it('reads gzipped tiles', async () => { + const { land } = await chartLand({ enc }, band({}, true)) + expectBand(await runs(land, at(9.995), at(10.009))) + }) + + it('reads the tiles of zoom 14, and no chart that has none', async () => { + const requests: Requests = [] + const { land } = await chartLand({ enc }, band({}, false, 'enc', requests)) + await runs(land, at(9.995), at(10.009)) + expect(requests).toEqual([['enc', 14, 9102, ROW]]) + const overview = await chartLand({ enc: { ...enc, maxzoom: 12 } }, band()) + expect(overview.land.landRuns(at(9.995), at(10.009))).toEqual([]) + // A chart that starts finer is read at its first zoom. + const fine: Requests = [] + const harbour = await chartLand({ enc: { ...enc, minzoom: 15 } }, band({}, false, 'enc', fine)) + await runs(harbour.land, at(9.995), at(10.009)) + expect(new Set(fine.map(([, z]) => z))).toEqual(new Set([15])) + }) + + it('keeps tiles as long as it is told they are in use', async () => { + const requests: Requests = [] + const fake = fakeApp({ enc: { ...enc, bounds: [19, 9, 30, 11] } }) + fake.emit('provider', band({}, false, 'enc', requests)) + const land = new ChartLand(fake.app, 60_000) + await land.refresh() + const now = Date.now() + const course = async (i: number, time: number) => { + const from = at(9.995, 19.001 + i * 0.022) + await runs(land, from, { ...from, latitude: from.latitude + 0.001 }, time) + } + for (let i = 0; i < 300; i++) await course(i, now) + await course(300, now + 20_000) + await course(1, now + 20_000) + expect(requests).toHaveLength(301) + }) + + it('keeps tiles in use, and evicts the longest unused beyond 256', async () => { + const requests: Requests = [] + const wide = { ...enc, bounds: [19, 9, 30, 11] } + const { land } = await chartLand({ enc: wide }, band({}, false, 'enc', requests)) + const now = Date.now() + // A short course in each of 300 tiles along the parallel. + const tile = (i: number) => at(9.995, 19.001 + i * 0.022) + const course = async (i: number, time: number) => { + const from = tile(i) + await runs(land, from, { ...from, latitude: from.latitude + 0.001 }, time) + } + for (let i = 0; i < 300; i++) await course(i, now) + expect(requests).toHaveLength(300) + // All used within 5 s: none evicted. + await course(0, now + 3000) + expect(requests).toHaveLength(300) + // A new tile later evicts the oldest unused ones, down to 256. + await course(300, now + 20_000) + await course(299, now + 20_000) + expect(requests).toHaveLength(301) + await course(1, now + 20_000) + expect(requests).toHaveLength(302) + }) + + it('skips anything in the chart list that is not a chart', async () => { + const { land } = await chartLand({ broken: null, odd: 'x', enc }, band()) + expectBand(await runs(land, at(9.995), at(10.009))) + const fake = fakeApp({}) + fake.app.resourcesApi.listResources = vi.fn(() => + Promise.resolve(null as unknown as Record) + ) + await expect(new ChartLand(fake.app).refresh()).resolves.toBeUndefined() + }) + + it('reads only S-57 charts, and only where they have data', async () => { + const raster = await chartLand({ enc: { ...enc, type: 'tilelayer' } }, band()) + expect(raster.land.landRuns(at(9.995), at(10.009))).toEqual([]) + const elsewhere = await chartLand({ enc: { ...enc, bounds: [21, 9, 22, 11] } }, band()) + expect(elsewhere.land.landRuns(at(9.995), at(10.009))).toEqual([]) + }) + + it('reads a chart that spans the antimeridian, on a course across it', async () => { + const { land } = await chartLand({ enc: { ...enc, bounds: [170, 9, -170, 11] } }, band()) + expectBand(await runs(land, at(9.995, 179.99), at(10.009, 179.99))) + // Diagonally across 180°: the land is the same share of a longer course. + const length = Math.hypot(0.014 * METRES, 0.01 * METRES * Math.cos((9.995 * Math.PI) / 180)) + const found = await runs(land, at(9.995, 179.995), at(10.009, -179.995)) + expect(found).toHaveLength(1) + expect(found?.[0].length).toBeGreaterThan((length * 0.004) / 0.014 - 20) + expect(found?.[0].length).toBeLessThan((length * 0.004) / 0.014 + 20) + }) + + it('knows no land without a chart provider, and reads the tiles once one comes', async () => { + const { land, emit } = await chartLand({ enc }) + expect(await runs(land, at(9.995), at(10.009))).toEqual([]) + emit('provider', band()) + expectBand(await runs(land, at(9.995), at(10.009))) + // Withdrawn, as a provider does when it stops. + emit('provider', null) + expect(await runs(land, at(9.995), at(10.009))).toEqual([]) + }) + + it('reads a tile again when its provider changes under a read', async () => { + let release: (tile: Uint8Array) => void = () => undefined + const slow: ChartTiles = { + getTile: () => + new Promise((resolve) => { + release = resolve + }) + } + const { land, emit } = await chartLand({ enc }, slow) + land.landRuns(at(9.995), at(10.009)) + emit('provider0', band({ layer: 'DEPARE' })) + release(bandTile(14, ROW, SOUTH, NORTH)) + await settle() + expect(await runs(land, at(9.995), at(10.009))).toEqual([]) + }) + + it('gives up a read after 5 s, and tries again a minute later', async () => { + vi.useFakeTimers() + const getTile = vi.fn(() => new Promise(() => undefined)) + const { land, error } = await chartLand({ enc }, { getTile }) + const now = Date.now() + expect(land.landRuns(at(9.995), at(10.009), now)).toBeUndefined() + await vi.advanceTimersByTimeAsync(5000) + expect(land.landRuns(at(9.995), at(10.009), now + 5000)).toEqual([]) + expect(error).toHaveBeenCalledWith(expect.stringContaining('no tile within 5 s')) + const reads = getTile.mock.calls.length + land.landRuns(at(9.995), at(10.009), now + 5000 + 60_000) + expect(getTile.mock.calls.length).toBeGreaterThan(reads) + }) + + it('reports a chart it cannot read once, and knows no land there', async () => { + const broken: ChartTiles = { getTile: () => Promise.reject(new Error('disk gone')) } + const { land, error } = await chartLand({ enc }, broken) + expect(await runs(land, at(9.995), at(10.009))).toEqual([]) + expect(await runs(land, at(9.995), at(10.009))).toEqual([]) + expect(error).toHaveBeenCalledOnce() + expect(error).toHaveBeenCalledWith(expect.stringContaining('disk gone')) + }) + + it('reads the tiles afresh every 10 minutes, as a chart may be rebuilt', async () => { + const requests: Requests = [] + const { land } = await chartLand({ enc }, band({}, false, 'enc', requests)) + const now = Date.now() + await runs(land, at(9.995), at(10.009), now) + const read = requests.length + await land.refresh(now + 60_000) + await runs(land, at(9.995), at(10.009), now + 60_000) + expect(requests).toHaveLength(read) + await land.refresh(now + 601_000) + await runs(land, at(9.995), at(10.009), now + 601_000) + expect(requests.length).toBeGreaterThan(read) + }) + + it('stops reading and listening for providers when stopped', async () => { + const requests: Requests = [] + const { land, emit } = await chartLand({ enc }) + land.stop() + emit('provider', band({}, false, 'enc', requests)) + expect(await runs(land, at(9.995), at(10.009))).toEqual([]) + expect(requests).toHaveLength(0) + }) +}) diff --git a/test/plugin.test.ts b/test/plugin.test.ts index e258917..b082d68 100644 --- a/test/plugin.test.ts +++ b/test/plugin.test.ts @@ -34,6 +34,8 @@ function fakeApp(managed: boolean) { registerPutHandler: vi.fn(), savePluginOptions: vi.fn(), emitPropertyValue: vi.fn(), + onPropertyValues: vi.fn(() => () => undefined), + resourcesApi: { listResources: vi.fn(() => Promise.resolve({})) }, handleMessage: vi.fn(), getSelfPath: vi.fn(() => nav(50, 0, 5)), getPath: vi.fn((path: string): unknown => diff --git a/test/tiles.ts b/test/tiles.ts new file mode 100644 index 0000000..2fb82c8 --- /dev/null +++ b/test/tiles.ts @@ -0,0 +1,120 @@ +import { PbfWriter } from 'pbf' + +const EXTENT = 4096 +const BUFFER = 64 +const DEG = Math.PI / 180 + +/** [x, y] in tile units. */ +type Ring = [number, number][] + +function zigzag(n: number): number { + return n < 0 ? -2 * n - 1 : 2 * n +} + +/** MVT geometry commands for polygon rings, each given without its closing vertex. */ +function geometry(rings: Ring[]): number[] { + const commands: number[] = [] + let x = 0 + let y = 0 + for (const ring of rings) { + ring.forEach(([px, py], i) => { + if (i === 0) commands.push((1 << 3) | 1) + else if (i === 1) commands.push(((ring.length - 1) << 3) | 2) + commands.push(zigzag(px - x), zigzag(py - y)) + x = px + y = py + }) + commands.push((1 << 3) | 7) + } + return commands +} + +/** A vector tile with polygon features, each a list of rings, by layer name. */ +export function encodeTile(layers: Record, extent = EXTENT): Uint8Array { + const tile = new PbfWriter() + for (const [name, polygons] of Object.entries(layers)) { + tile.writeMessage( + 3, + (_: undefined, layer: PbfWriter) => { + layer.writeVarintField(15, 2) + layer.writeStringField(1, name) + for (const rings of polygons) { + layer.writeMessage( + 2, + (__: undefined, feature: PbfWriter) => { + feature.writeVarintField(3, 3) + feature.writePackedVarint(4, geometry(rings)) + }, + undefined + ) + } + layer.writeVarintField(5, extent) + }, + undefined + ) + } + return tile.finish() +} + +/** The y in tile units, within tile row `y` at `z`, of a latitude. */ +function tileUnitY(latitude: number, z: number, y: number): number { + const lat = latitude * DEG + const row = ((1 - Math.log(Math.tan(lat) + 1 / Math.cos(lat)) / Math.PI) / 2) * 2 ** z + return Math.round((row - y) * EXTENT) +} + +/** A rectangle across the tile and its buffer, from tile unit `top` down to `bottom`. */ +function strip(top: number, bottom: number): Ring[][] { + const north = Math.max(-BUFFER, top) + const south = Math.min(EXTENT + BUFFER, bottom) + if (north >= south) return [] + return [ + [ + [ + [-BUFFER, north], + [EXTENT + BUFFER, north], + [EXTENT + BUFFER, south], + [-BUFFER, south] + ] + ] + ] +} + +/** + * Tile z/x/y of a chart with land (`LNDARE`) from `south` to `north` right + * across it, and, with `water`, a depth area (`DEPARE`) everywhere else. + */ +export function bandTile( + z: number, + y: number, + south: number, + north: number, + { water = true, layer = 'LNDARE' } = {} +): Uint8Array { + const top = tileUnitY(north, z, y) + const bottom = tileUnitY(south, z, y) + const layers: Record = { [layer]: strip(top, bottom) } + if (water) { + layers.DEPARE = [...strip(-BUFFER, top), ...strip(bottom, EXTENT + BUFFER)] + } + return encodeTile(layers) +} + +/** + * Tile z/x/y of a chart with strips right across it, each from a south to a + * north latitude, by layer name. + */ +export function stripsTile( + z: number, + y: number, + layers: Record +): Uint8Array { + return encodeTile( + Object.fromEntries( + Object.entries(layers).map(([name, strips]) => [ + name, + strips.flatMap(([south, north]) => strip(tileUnitY(north, z, y), tileUnitY(south, z, y))) + ]) + ) + ) +} From 9438dbb672f21a15834e62454cc83a20b47d113a Mon Sep 17 00:00:00 2001 From: Dirk Wahrheit Date: Fri, 20 Nov 2026 12:41:11 +1200 Subject: [PATCH 2/3] fix: look for land up to a later bow crossing, and wait for both courses Land was looked for only up to the closest approach, so a bow crossing after it counted even past land in between. Land is now looked for up to whichever comes later, and a boat past its closest approach by the time it reaches land keeps that closest approach. A stop found on one course lowered the level at once while the other course was loading, but could also let it rise. It still lowers it; a rise waits for both courses, for at most 10 s. Without a chart provider there is no tile to wait for, so a course shows no land at once. --- src/evaluator.ts | 52 ++++++++++++++++++++----------------- src/land.ts | 2 ++ test/evaluator.test.ts | 58 +++++++++++++++++++++++++++++++++++++----- test/land.test.ts | 3 ++- 4 files changed, 84 insertions(+), 31 deletions(-) diff --git a/src/evaluator.ts b/src/evaluator.ts index e9d8bb8..ecf8e46 100644 --- a/src/evaluator.ts +++ b/src/evaluator.ts @@ -630,22 +630,39 @@ export class Evaluator { kept && nowMs >= kept.at && nowMs - kept.at <= LAND_MEMORY ? kept : { at: nowMs } state.at = nowMs this.landStates.set(targetId, state) - const theirs = landStop(land, targetNow, result.tcpa, state.theirs) - const ours = landStop(land, own, result.tcpa, state.ours) + // A bow crossing after the closest approach still counts, so land + // is looked for up to whichever comes later. + const horizon = Math.max(result.tcpa, result.bowCrossing?.time ?? 0) + const theirs = landStop(land, targetNow, horizon, state.theirs) + const ours = landStop(land, own, horizon, state.ours) // Each course keeps where land stopped it until its charts say // otherwise. if (theirs !== undefined) state.theirs = theirs?.at if (ours !== undefined) state.ours = ours?.at - // A stop already found holds while the other course loads: the - // boats come no closer than there, if not stopped sooner. + // A stop already found lowers the level while the other course + // loads: the boats come no closer than there, if not stopped sooner. const stops = [theirs, ours].flatMap((stop) => (stop ? [stop.time] : [])) - const end = - stops.length > 0 - ? Math.min(...stops) - : theirs === undefined || ours === undefined - ? undefined - : Infinity - if (end === undefined) { + if (stops.length > 0) { + const end = Math.min(...stops) + const crossing = result.bowCrossing + // Past its closest approach by then, a boat came closest there. + const beforeLand = + end >= result.tcpa + ? levelOf(result.cpa, tcpa, crossing && crossing.time <= end ? crossing : null) + : levelOf( + separationAt(own, targetNow, end), + end, + crossing && crossing.time <= end ? crossing : null + ) + if (severity(beforeLand.level) < severity(level)) { + level = beforeLand.level + } + judged = beforeLand.judged + reachedTcpa = Math.min(tcpa, end) + } + // While a course loads, its land may stop the boat sooner: the level + // does not rise meanwhile, for a moment. + if (theirs === undefined || ours === undefined) { state.loadingSince ??= nowMs if ( nowMs >= state.loadingSince && @@ -656,19 +673,6 @@ export class Evaluator { } } else { state.loadingSince = undefined - if (end !== Infinity) { - const crossing = result.bowCrossing - const beforeLand = levelOf( - separationAt(own, targetNow, end), - end, - crossing && crossing.time <= end ? crossing : null - ) - if (severity(beforeLand.level) < severity(level)) { - level = beforeLand.level - } - judged = beforeLand.judged - reachedTcpa = Math.min(tcpa, end) - } } } if (current === undefined && overtaken && judgedBy === CUT_SET) { diff --git a/src/land.ts b/src/land.ts index 4ed7dd1..6a89a1b 100644 --- a/src/land.ts +++ b/src/land.ts @@ -303,6 +303,8 @@ export class ChartLand { * where a chart is wrong or too coarse, not behind land. */ landRuns(from: LatLon, to: LatLon, now = Date.now()): LandRun[] | undefined { + // Without a provider no tile can come, so there is nothing to wait for. + if (this.providers.size === 0) return [] // A tile that cannot be read must not stop the alarms: it shows no land. try { return this.scan(from, to, now) diff --git a/test/evaluator.test.ts b/test/evaluator.test.ts index 70b8878..3a21c5a 100644 --- a/test/evaluator.test.ts +++ b/test/evaluator.test.ts @@ -1834,12 +1834,12 @@ describe('a passage that land ends', () => { const check = { boxes, loading: false, - /** Courses from here are still loading. */ - loadingFrom: undefined as LatLon | undefined, + /** Courses from where this holds are still loading. */ + loadingWhen: (() => false) as (from: LatLon) => boolean, calls: [] as [LatLon, LatLon][], landRuns(from: LatLon, to: LatLon) { check.calls.push([from, to]) - if (check.loading || from === check.loadingFrom) return undefined + if (check.loading || check.loadingWhen(from)) return undefined const length = Math.hypot( (to.latitude - from.latitude) * METRES, (to.longitude - from.longitude) * METRES * Math.cos((from.latitude * Math.PI) / 180) @@ -2050,10 +2050,10 @@ describe('a passage that land ends', () => { const { sink, ev } = setup({ ...passing, land }) ev.evaluate(own, { [OTHER]: headOn }, SELF, NOW) land.boxes = [] - land.loadingFrom = own.position + land.loadingWhen = (from) => from === own.position ev.evaluate(own, { [OTHER]: headOn }, SELF, NOW + 2000) land.boxes = band(north(1300), north(1400)).boxes - land.loadingFrom = undefined + land.loadingWhen = () => false ev.evaluate(own, { [OTHER]: headOn }, SELF, NOW + 4000) expect(sink.calls).toEqual([[OTHER, expect.objectContaining({ level: 'alarm' })]]) }) @@ -2061,13 +2061,59 @@ describe('a passage that land ends', () => { it('keeps a stop found on one course while the other loads, past the wait', () => { const north = (metres: number) => 50 + metres / METRES const land = band(north(1100), north(1400)) - land.loadingFrom = own.position + land.loadingWhen = (from) => from === own.position const { sink, ev } = setup({ ...passing, land }) ev.evaluate(own, { [OTHER]: headOn }, SELF, NOW) ev.evaluate(own, { [OTHER]: headOn }, SELF, NOW + 12_000) expect(sink.calls).toHaveLength(0) }) + describe('a bow crossing after the closest approach', () => { + // A boat abeam to starboard, heading 350.5° at 6.1 m/s, closes to its + // closest approach and then crosses ahead of us. `abeam` metres off, it + // crosses 160 m ahead in 160 s. + const crossingLate = (abeam: number) => { + const vx = -abeam / 160 + const cog = (Math.atan2(vx, 6) * 180) / Math.PI + return vessel(50, east(abeam), (cog + 360) % 360, Math.hypot(vx, 6)) + } + const north = (metres: number) => 50 + metres / METRES + + it('looks for land up to the crossing', () => { + // Closest 113 m off in 80 s, then across our bow; 200 m of land + // between the two, which it reaches in 93 s. + const late = crossingLate(160) + const open = setup(passing) + open.ev.evaluate(own, { [OTHER]: late }, SELF, NOW) + expect(open.sink.calls).toEqual([[OTHER, expect.objectContaining({ level: 'alarm' })]]) + const land = band(north(560), north(760)) + const { sink, ev } = setup({ ...passing, land }) + ev.evaluate(own, { [OTHER]: late }, SELF, NOW) + expect(sink.calls).toHaveLength(0) + }) + + it('keeps the closest approach that comes before the land', () => { + // Closest 39 m off in 9 s; land stops it in 42 s, 51 m off. + const land = band(north(250), north(450)) + const { sink, ev } = setup({ ...passing, land }) + ev.evaluate(own, { [OTHER]: crossingLate(40) }, SELF, NOW) + expect(sink.calls).toEqual([[OTHER, expect.objectContaining({ level: 'alarm' })]]) + }) + }) + + it('raises no level while one course loads, though land stops the other', () => { + // It crosses 400 m ahead of us in 60 s; land stops us in 64 s, and its + // own course is still loading. + const crossing = vessel(50 + 700 / METRES, east(-300), 90, 5) + const land = band(50 + 320 / METRES, 50 + 480 / METRES) + land.loadingWhen = (from) => from !== own.position + const { sink, ev } = setup({ ...passing, land }) + ev.evaluate(own, { [OTHER]: crossing }, SELF, NOW) + expect(sink.calls).toHaveLength(0) + ev.evaluate(own, { [OTHER]: crossing }, SELF, NOW + 10_000) + expect(sink.calls).toEqual([[OTHER, expect.objectContaining({ level: 'alarm' })]]) + }) + describe('far off', () => { // We lie still; the boat comes from 11 km north at 10 m/s, a warning by // the Offshore limits. Land from 4000 m to 4300 m north of us. diff --git a/test/land.test.ts b/test/land.test.ts index 215ed2a..9d5d599 100644 --- a/test/land.test.ts +++ b/test/land.test.ts @@ -341,7 +341,8 @@ describe('ChartLand', () => { it('knows no land without a chart provider, and reads the tiles once one comes', async () => { const { land, emit } = await chartLand({ enc }) - expect(await runs(land, at(9.995), at(10.009))).toEqual([]) + // At once: there is nothing to load. + expect(land.landRuns(at(9.995), at(10.009))).toEqual([]) emit('provider', band()) expectBand(await runs(land, at(9.995), at(10.009))) // Withdrawn, as a provider does when it stops. From 103b7d349603dab96c53f47f094e5d112262deab Mon Sep 17 00:00:00 2001 From: dirkwa <86628605+dirkwa@users.noreply.github.com> Date: Fri, 20 Nov 2026 07:34:58 +0000 Subject: [PATCH 3/3] fix: read a long course at full resolution, for its first 20 km A course longer than 20 km was sampled more coarsely than every 10 m, so land a little over 150 m wide could measure under 150 m and not stop a passage. A course with a bow crossing hours ahead asks for one that long. A course is now read at 10 m spacing for its first 20 km, as far as a 27 kn ship runs in the longest Offshore warning time. Land beyond is not looked for; land only ever lowers a level, so that errs on the side of the alarm. --- src/land.ts | 12 ++++++++---- test/land.test.ts | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 40 insertions(+), 4 deletions(-) diff --git a/src/land.ts b/src/land.ts index 6a89a1b..67f7813 100644 --- a/src/land.ts +++ b/src/land.ts @@ -36,6 +36,8 @@ const WATER = ['DEPARE', 'DRGARE'] const ZOOM = 14 // Metres between the points tested along a course. const STEP = 10 +// Points tested on one course at most: a course is read only this far +// (20 km), as a wider spacing would measure land too short to count. const MAX_POINTS = 2000 // Tiles kept; more while the courses being checked need them. const MAX_TILES = 256 @@ -300,7 +302,8 @@ export class ChartLand { * charted water on either side, in order, or undefined while the charts * for it are still loading. Land at either end, or next to waters no chart * covers, does not count: a boat or a closest approach charted on land is - * where a chart is wrong or too coarse, not behind land. + * where a chart is wrong or too coarse, not behind land. Only the first + * 20 km of the course are read. */ landRuns(from: LatLon, to: LatLon, now = Date.now()): LandRun[] | undefined { // Without a provider no tile can come, so there is nothing to wait for. @@ -320,13 +323,14 @@ export class ChartLand { const dx = dLon * DEG * Math.cos(lat0) * EARTH_RADIUS const dy = (to.latitude - from.latitude) * DEG * EARTH_RADIUS const length = Math.hypot(dx, dy) - const points = Math.min(MAX_POINTS, Math.ceil(length / STEP)) + const read = Math.min(length, MAX_POINTS * STEP) + const points = Math.ceil(read / STEP) if (points < 2) return [] - const step = length / points + const step = read / points const memo = new Map() const grounds: Ground[] = [] for (let i = 0; i <= points; i++) { - const f = i / points + const f = (i * step) / length const point = { latitude: from.latitude + f * (to.latitude - from.latitude), longitude: wrap(from.longitude + f * dLon) diff --git a/test/land.test.ts b/test/land.test.ts index 9d5d599..d0819c0 100644 --- a/test/land.test.ts +++ b/test/land.test.ts @@ -177,6 +177,38 @@ describe('ChartLand', () => { } }) + it('keeps its 10 m spacing on a long course, read for its first 20 km', async () => { + // 190 m of land 5 km out, and more 25 km out, on a course of 136 km. + const m = (metres: number) => SOUTH + metres / METRES + const lands: ChartTiles = { + getTile: (_chart, z, _x, y) => + Promise.resolve( + stripsTile(z, y, { + LNDARE: [ + [m(5000), m(5190)], + [m(25000), m(25500)] + ], + DEPARE: [ + [9, m(5000)], + [m(5190), m(25000)], + [m(25500), 11] + ] + }) + ) + } + const { land } = await chartLand({ enc }, lands) + const from = at(SOUTH) + const to = at(m(136_000)) + let found = land.landRuns(from, to) + for (let i = 0; i < 20 && !found; i++) { + await settle() + found = land.landRuns(from, to) + } + expect(found).toHaveLength(1) + expect(found?.[0].start).toBeCloseTo(5000, -1) + expect(found?.[0].length).toBeGreaterThan(180) + }) + it('breaks land at waters no chart covers', async () => { // Water, 80 m of land, 500 m nothing charted, 80 m of land, water. const m = (metres: number) => SOUTH + metres / METRES