mirror of
https://github.com/Kpa-clawbot/meshcore-analyzer.git
synced 2026-11-22 04:57:07 +00:00
The repeater planner (#2391) gets a fourth tab, **Coverage**: put a marker where you are thinking of placing a repeater, set its antenna height, and see on the map who would hear it. It answers the siting question "what does a repeater reach if we put it here", with two layers: handheld users and other repeaters. ## What it shows - **Users layer:** the chance that a handheld at 1.5 m hears the site, in 4 bands (10-25%, 25-50%, 50-75%, 75% and up; below 10% is not painted). The chance comes from a distance curve `P(d) = 1 / (1 + exp((ln d - ln d50) / slope))`, fitted on drive-test receptions of 41 Belgian repeaters (d50 2.7 km, slope 0.30). Terrain only lowers a cell by 2 bands where a 1.5 m receiver sits deeper than 1 first-Fresnel radius under the terrain (`cmd/server/planner_viewshed.go:19-21`). Antenna height does not change the curve: in the drive tests, handheld reach barely changed between 1, 7 and 15 m. The panel says so in one line. - **Repeaters layer:** first-Fresnel clearance from the site to every cell, for a receiver at "Repeaters at" height (default `planner.existingAntennaM`). 3 classes: line of sight (clearance 0% or more), slightly blocked (-20% to 0%), blocked (not painted). Every known repeater within range gets its link computed with the existing planner link code, a dot in its class colour, a line for line of sight and slightly blocked, and an entry in a list. - **Compute button:** changing site, height or range moves the marker and updates the URL hash right away, and dims an existing result with an "Outdated" note. Only "Compute coverage" starts a job. A shared link that carries a site computes once on open. The planner has 1 heavy-job slot shared with Area and allows 6 jobs per minute per IP, so recomputing on every change would burn both. State is in the hash: `#/tools/planner?mode=coverage&site=51.06,4.41&h=10&rx=5&range=30&layer=repeaters`. This builds on the repeater planner @zfouts wrote in #2391: the terrain tiles, the first-Fresnel analysis, the link code, the job protocol and the Area module pattern are all reused here. Thanks for that work, it made this tab a small addition instead of a new subsystem. ## Why the Repeaters classes are not the route LOS verdicts The route verdicts (clear 100%+, clear60 60%+, marginal 0%+, blocked) almost never show on Shuttle Radar Topography Mission (SRTM) terrain at mast heights. At 10 m / 5 m, 30 km around Mechelen, 109 of 70,980 cells reach clear60 or clear. SRTM includes trees and roofs, so the line between 2 masts rarely clears 60% of the Fresnel zone. I checked the clearance against one Belgian repeater (28 m, receivers at 5 m) and the repeaters live data shows it actually hears: | Distance | Heard, clearance >= 0 | Heard, clearance < 0 | |---|---|---| | 0-10 km | 9 of 11 | none in range | | 10-20 km | 3 of 4 | 1 of 8 | | 20-30 km | 0 of 6 | 3 of 35 | | 30-60 km | 1 of 2 | 0 of 84 | Every link heard within 16 km had a clearance between 2% and 54%, so "marginal" is where working links live. The map classes follow that (`repeaterClass`, `cmd/server/planner_viewshed.go:75-89`). Chain, Relay and Area keep the shared verdicts; `losVerdict` is unchanged. This rests on 17 heard links from 1 repeater, which is why the -20% band is narrow and the panel says line of sight stops being enough beyond about 20 km. ## Server - `GET /api/planner/viewshed?site=&h=&rx=&range=` (`cmd/server/planner_api.go:603`, route `cmd/server/routes.go:393`). Same job protocol, result cache, rate limits and opt-in as the other planner endpoints: 404 while `planner.enabled` is false. - One byte per cell: low nibble Users class 1-5, high nibble Repeaters class 1-3, 0 for no data. The grid is about 300 x 300 at every range: 0.2 km cells up to 30 km, `range/150` above (`planner_viewshed.go:47`). - Links skip rooms, stale repeaters and a repeater within 100 m of the site (that is the site itself). They carry no `elev_m` profile. - `truncated` is true only when the 300-node cap may have dropped a repeater within range (`viewshedTruncated`, `planner_api.go:694`). - Tile cap: `Viewshed` in the planner tile limits, sized from the largest offered range (60 km). - New config: `planner.userReach.{d50Km,slope}` with a `_comment` in `config.example.json`. Bounds 0.2-50 km and 0.05-2. - No writes, no new `map[string]interface{}`; response types `PlannerViewshedResponse/Params/Link` in `planner_types.go`. ## Frontend - `public/planner-coverage.js` + `.css`, mounted like `planner-area.js`. `planner.js` gets a `MODULES` table (`public/planner.js:31`) so Area and Coverage share one enter/leave path. - Canvas raster in an `L.imageOverlay`; the layer switch repaints locally without a new request. Requests go through `fetchJob` / `CSApi`. - Colours are CSS variables `--pl-cov-user-2..5` and `--pl-cov-rep-1..3` in `:root` and both dark blocks of `style.css`; the Repeaters ones point at `--status-*`, so a theme that changes those changes the map. ## Performance The job is opt-in and runs in the existing planner job slot, never in a hot path. Measured on real SRTM tiles, local build, 304 Belgian repeaters: | Site | Range | Mast | Job time | |---|---|---|---| | Maasvallei (hilly) | 30 km | 10 m | 2.07 s | | Maasvallei | 30 km | 30 m | 2.57 s | | Maasvallei | 60 km | 10 m | 3.98 s | | Mechelen (flat) | 30 km | 10 m | 2.61 s | On a staging instance (ARM64, cold tile cache) a 30 km job took 6.8 s including the tile downloads. Response size at 60 km with 115 links: 239,942 bytes with link elevation profiles, 149,984 without (what this PR ships). `BenchmarkViewshedMaxLeg` covers the 60 km worst case on a synthetic terrain view. ## Verification - Go: 26 viewshed tests and benchmarks in `planner_viewshed_test.go`, `planner_api_test.go`, `planner_config_test.go` and `planner_tiles_test.go`, among them: flat terrain equals the plain curve and `analyzeLOS`, a ridge shadows only its far side, missing terrain is "no data", the `truncated` rule (proven to fail on the old rule), links without `elev_m`, the repeater at the site left out. `go test ./...` in `cmd/server` passes. - Frontend: `tests/unit/test-planner-coverage.js` (23 tests, in `test-all.sh`): grid decode, class-to-colour mapping, unpainted classes, hash round trip, no fetch on parameter change, 1 fetch per click, deep-link autorun once, stale responses ignored, link classes at the boundaries, escaped repeater names. - E2E: 5 Coverage cases in `tests/e2e/test-planner-e2e.js` (stubbed viewshed): click and compute, layer switch without a request, outdated then recompute, deep link, leaving the tab removes the overlay. Planner E2E 25/25 locally. - eslint 0 errors. Browser: light and dark theme, Users and Repeaters on flat, hilly and coastal sites, deep links, no console errors; also on a staging instance with live data. ## Not in this PR - The `--pl-cov-*` colours are not in the customizer's `THEME_CSS_MAP` yet. They follow `--status-*` for the Repeaters layer; the Users colours need their own entries (AGENTS.md rule 8, later milestone). - In Flanders the Users layer is close to a circle: 0.3% of cells differ from the plain curve around Mechelen, 42% in the Maasvallei, 64% in the Ardennes. The terrain correction is untested in hilly areas, the drive tests had no repeater there. - The Repeaters calibration uses 1 repeater. Other operators with drive tests or neighbour data can tighten it. - A link's class comes from `clearance_pct`, rounded to 0.1%, while the grid uses the raw clearance: within 0.05% of a bound a link can land 1 class off the cell under it. List, line and dot always agree with each other. - An OS dark-mode switch without the theme toggle does not repaint the overlay until the next compute, the same as the planner's tile layer. --------- Co-authored-by: zfouts <zachary.fouts@gmail.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
240 lines
7.7 KiB
Go
240 lines
7.7 KiB
Go
package main
|
||
|
||
// Viewshed raster for the planner's Coverage tab: for one candidate site,
|
||
// each cell of a grid around it gets a Users class (handheld reach curve,
|
||
// lowered in deep terrain shadow) and a Repeaters class (the same LOS
|
||
// verdict a Chain leg site→cell would get).
|
||
|
||
import (
|
||
"context"
|
||
"math"
|
||
"runtime"
|
||
"sync"
|
||
"sync/atomic"
|
||
)
|
||
|
||
const (
|
||
// viewshedUserRxM: handheld height above ground for the shadow test.
|
||
viewshedUserRxM = 1.5
|
||
// viewshedShadowClearance: a ground path whose worst first-Fresnel
|
||
// clearance is below this (the LOS this many F1 radii under terrain)
|
||
// counts as deep shadow.
|
||
viewshedShadowClearance = -1.0
|
||
// viewshedShadowDrop: Users classes dropped in deep shadow (floor 1).
|
||
viewshedShadowDrop = 2
|
||
)
|
||
|
||
type viewshedParams struct {
|
||
Site geoPoint
|
||
SiteM, RxM, RangeKm, FreqMHz, KFactor float64
|
||
Reach PlannerUserReach
|
||
}
|
||
|
||
// viewshedGrid: Rows×Cols cells over BBox, row 0 north, row-major; cell
|
||
// (r, c) is centred at the middle of the r-th of Rows equal latitude bands
|
||
// (from N) and the c-th of Cols equal longitude bands (from W). Each byte
|
||
// is users | repeaters<<4; a nibble of 0 means no data (outside RangeKm, or
|
||
// no terrain at the cell, the site or on the path between).
|
||
type viewshedGrid struct {
|
||
BBox geoBBox
|
||
Rows, Cols int
|
||
CellKm float64
|
||
Cells []byte
|
||
}
|
||
|
||
func viewshedBBox(site geoPoint, rangeKm float64) geoBBox {
|
||
return plannerExpandBBox(geoBBox{S: site.Lat, W: site.Lon, N: site.Lat, E: site.Lon}, rangeKm)
|
||
}
|
||
|
||
// viewshedCellKm: 200 m, coarser above 30 km so a grid stays near 300×300.
|
||
func viewshedCellKm(rangeKm float64) float64 { return math.Max(0.2, rangeKm/150) }
|
||
|
||
// userReachP is the handheld reach curve P = 1/(1+exp((ln d − ln d50)/s)).
|
||
func userReachP(dKm float64, r PlannerUserReach) float64 {
|
||
return 1 / (1 + math.Exp((math.Log(dKm)-math.Log(r.D50Km))/r.Slope))
|
||
}
|
||
|
||
func userReachClass(p float64) byte {
|
||
switch {
|
||
case p < 0.10:
|
||
return 1
|
||
case p < 0.25:
|
||
return 2
|
||
case p < 0.50:
|
||
return 3
|
||
case p < 0.75:
|
||
return 4
|
||
}
|
||
return 5
|
||
}
|
||
|
||
// viewshedNearClearance is the lower bound of the Repeaters "slightly
|
||
// blocked" class: the line of sight at most this fraction of the first
|
||
// Fresnel radius under terrain. Calibrated loosely on one repeater
|
||
// (2026-11-16, 17 heard links): every link heard within 16 km had a clearance
|
||
// of 2% to 54%, so the textbook 60%/100% classes never mark working links on
|
||
// SRTM; within 20 km, 12 of 15 links with clearance >= 0 were heard against 1
|
||
// of 8 below 0; one link was heard at -20%.
|
||
const viewshedNearClearance = -0.2
|
||
|
||
// repeaterClass maps a first-Fresnel clearance (1 = fully clear) to the
|
||
// Repeaters class: 3 line of sight (>= 0), 2 slightly blocked (down to
|
||
// viewshedNearClearance), 1 blocked.
|
||
func repeaterClass(c float64) byte {
|
||
switch {
|
||
case c >= 0:
|
||
return 3
|
||
case c >= viewshedNearClearance:
|
||
return 2
|
||
}
|
||
return 1
|
||
}
|
||
|
||
// viewshedWorkers is how many goroutines computeViewshed spreads rows over.
|
||
// The planner runs one Coverage/Viewshed job at a time (plannerCovSlots), so
|
||
// this is also the most CPUs a viewshed takes from the live app.
|
||
func viewshedWorkers() int { return max(1, min(4, runtime.GOMAXPROCS(0)/2)) }
|
||
|
||
// clearancePair is two e.clearance walks of the same path a→b in one pass:
|
||
// the worst first-Fresnel clearance with the receiver hbR above ground
|
||
// (floor −Inf, every sample: crOK=false means no terrain on the path, or ctx
|
||
// cancelled with e.err set), and whether the worst clearance with the
|
||
// receiver hbU is below shadowFloor. Each result equals that of its own
|
||
// e.clearance call.
|
||
func (e *planLinkEval) clearancePair(a, b geoPoint, distKm, ha, hbR, hbU, shadowFloor float64) (cr float64, crOK, shadow bool) {
|
||
cr, cu, ok := e.clearanceWalk(a, b, distKm, ha, hbR, math.Inf(-1), hbU, true)
|
||
if !ok {
|
||
return 0, false, false
|
||
}
|
||
return cr, true, cu < shadowFloor
|
||
}
|
||
|
||
// computeViewshed profiles site→cell for every cell in range: two
|
||
// clearance walks per cell (receiver at RxM for Repeaters, at
|
||
// viewshedUserRxM for the Users shadow test). progress gets the fraction of
|
||
// rows done. Errors: ctx.Err() only.
|
||
func computeViewshed(ctx context.Context, v terrainView, p viewshedParams, progress func(float64)) (viewshedGrid, error) {
|
||
return computeViewshedN(ctx, v, p, viewshedWorkers(), progress)
|
||
}
|
||
|
||
// computeViewshedN is computeViewshed over up to workers goroutines. Cells are
|
||
// independent and each row's bytes are written by one worker only, so the
|
||
// grid is identical for any workers. progress is called serially with a
|
||
// non-decreasing fraction that ends at exactly 1.
|
||
func computeViewshedN(ctx context.Context, v terrainView, p viewshedParams, workers int, progress func(float64)) (viewshedGrid, error) {
|
||
cellKm := viewshedCellKm(p.RangeKm)
|
||
bb := viewshedBBox(p.Site, p.RangeKm)
|
||
cosLat := math.Cos(p.Site.Lat * math.Pi / 180)
|
||
rows := max(1, int(math.Ceil((bb.N-bb.S)*plannerKmPerDeg/cellKm)))
|
||
cols := max(1, int(math.Ceil((bb.E-bb.W)*plannerKmPerDeg*cosLat/cellKm)))
|
||
g := viewshedGrid{BBox: bb, Rows: rows, Cols: cols, CellKm: cellKm, Cells: make([]byte, rows*cols)}
|
||
if err := ctx.Err(); err != nil {
|
||
return viewshedGrid{}, err
|
||
}
|
||
if _, ok := v.ElevationAt(p.Site.Lat, p.Site.Lon); !ok {
|
||
return g, nil // no terrain at the site: every cell is no data
|
||
}
|
||
dLat := (bb.N - bb.S) / float64(rows)
|
||
dLon := (bb.E - bb.W) / float64(cols)
|
||
// row fills row r with e; it reports e.err (ctx cancelled).
|
||
row := func(e *planLinkEval, r int) error {
|
||
lat := bb.N - (float64(r)+0.5)*dLat
|
||
for c := 0; c < cols; c++ {
|
||
cell := geoPoint{Lat: lat, Lon: bb.W + (float64(c)+0.5)*dLon}
|
||
d := geoDistKm(p.Site, cell)
|
||
if d > p.RangeKm {
|
||
continue
|
||
}
|
||
cr, ok, shadow := e.clearancePair(p.Site, cell, d, p.SiteM, p.RxM, viewshedUserRxM, viewshedShadowClearance)
|
||
if !ok {
|
||
continue // no terrain on the path (or ctx cancelled: checked below)
|
||
}
|
||
users := userReachClass(userReachP(d, p.Reach))
|
||
if shadow {
|
||
if users > viewshedShadowDrop {
|
||
users -= viewshedShadowDrop
|
||
} else {
|
||
users = 1
|
||
}
|
||
}
|
||
g.Cells[r*cols+c] = users | repeaterClass(cr)<<4
|
||
}
|
||
return e.err
|
||
}
|
||
workers = max(1, min(workers, rows))
|
||
if workers == 1 {
|
||
e := newPlanLinkEval(ctx, v, p.FreqMHz, p.KFactor)
|
||
for r := 0; r < rows; r++ {
|
||
if err := row(e, r); err != nil {
|
||
return viewshedGrid{}, err
|
||
}
|
||
if progress != nil {
|
||
progress(float64(r+1) / float64(rows))
|
||
}
|
||
}
|
||
} else {
|
||
// Rows are handed out one at a time (they differ in length), each
|
||
// worker with its own planLinkEval, which is not safe to share.
|
||
var (
|
||
next, stop atomic.Int64
|
||
mu sync.Mutex // serialises progress and the first error
|
||
done int
|
||
firstErr error
|
||
panicked any
|
||
wg sync.WaitGroup
|
||
)
|
||
for w := 0; w < workers; w++ {
|
||
wg.Add(1)
|
||
go func() {
|
||
defer wg.Done()
|
||
defer func() {
|
||
// Re-raised below on the caller's goroutine, where the
|
||
// job runner recovers it; here it would kill the process.
|
||
if r := recover(); r != nil {
|
||
mu.Lock()
|
||
if panicked == nil {
|
||
panicked = r
|
||
}
|
||
mu.Unlock()
|
||
stop.Store(1)
|
||
}
|
||
}()
|
||
e := newPlanLinkEval(ctx, v, p.FreqMHz, p.KFactor)
|
||
for stop.Load() == 0 {
|
||
r := int(next.Add(1) - 1)
|
||
if r >= rows {
|
||
return
|
||
}
|
||
err := row(e, r)
|
||
mu.Lock()
|
||
if err != nil && firstErr == nil {
|
||
firstErr = err
|
||
}
|
||
if err == nil {
|
||
done++
|
||
if progress != nil {
|
||
progress(float64(done) / float64(rows))
|
||
}
|
||
}
|
||
mu.Unlock()
|
||
if err != nil {
|
||
stop.Store(1)
|
||
return
|
||
}
|
||
}
|
||
}()
|
||
}
|
||
wg.Wait()
|
||
if panicked != nil {
|
||
panic(panicked)
|
||
}
|
||
if firstErr != nil {
|
||
return viewshedGrid{}, firstErr
|
||
}
|
||
}
|
||
if err := ctx.Err(); err != nil {
|
||
return viewshedGrid{}, err
|
||
}
|
||
return g, nil
|
||
}
|