diff --git a/Dockerfile b/Dockerfile index 76514d2a9..e94d7c655 100644 --- a/Dockerfile +++ b/Dockerfile @@ -56,6 +56,7 @@ ENV CC=zigcc CGO_ENABLED=1 # Build server WORKDIR /build/server COPY cmd/server/go.mod cmd/server/go.sum ./ +COPY internal/areamap/ ../../internal/areamap/ COPY internal/geofilter/ ../../internal/geofilter/ COPY internal/sigvalidate/ ../../internal/sigvalidate/ COPY internal/packetpath/ ../../internal/packetpath/ diff --git a/cmd/server/areas.go b/cmd/server/areas.go new file mode 100644 index 000000000..d102d7796 --- /dev/null +++ b/cmd/server/areas.go @@ -0,0 +1,76 @@ +package main + +import ( + "fmt" + "os" + "path/filepath" + "sort" + + "github.com/meshcore-analyzer/areamap" +) + +// LoadAreaMap builds the map of every area: config.json's areas (layer +// "region") and the features of AreasFile. It stores the map on cfg, where +// the store and the handlers find it. A code defined twice, a missing file +// or a file that is not GeoJSON is an error: the caller refuses to start +// rather than run with areas silently missing. +func LoadAreaMap(cfg *Config, configDir string) (*areamap.Map, error) { + var areas []areamap.Area + keys := make([]string, 0, len(cfg.Areas)) + for k := range cfg.Areas { + keys = append(keys, k) + } + sort.Strings(keys) + for _, k := range keys { + e := cfg.Areas[k] + if e.Label == "" { + continue // "_comment" and other non-areas + } + var ring [][2]float64 + switch { + case len(e.Polygon) >= 3: + // config.json polygons are [lat, lon]; GeoJSON rings are [lon, lat]. + for _, p := range e.Polygon { + ring = append(ring, [2]float64{p[1], p[0]}) + } + case e.LatMin != nil && e.LatMax != nil && e.LonMin != nil && e.LonMax != nil: + ring = [][2]float64{{*e.LonMin, *e.LatMin}, {*e.LonMax, *e.LatMin}, {*e.LonMax, *e.LatMax}, {*e.LonMin, *e.LatMax}} + default: + continue // listed by name only, with nothing to locate against + } + areas = append(areas, areamap.Area{Code: k, Label: e.Label, Layer: areamap.DefaultLayer, Polygons: [][][][2]float64{{ring}}}) + } + if cfg.AreasFile != "" { + path := cfg.AreasFile + if !filepath.IsAbs(path) { + path = filepath.Join(configDir, path) + } + data, err := os.ReadFile(path) + if err != nil { + return nil, fmt.Errorf("areasFile: %w", err) + } + fromFile, err := areamap.ParseGeoJSON(data) + if err != nil { + return nil, fmt.Errorf("areasFile %s: %w", path, err) + } + areas = append(areas, fromFile...) + } + m, err := areamap.New(areas) + if err != nil { + return nil, err + } + cfg.areaMap = m + return m, nil +} + +// fileArea reports whether code names an area that only the areas file +// defines, so area= resolves it by position instead of config.json's entry. +func (c *Config) fileArea(code string) bool { + if c == nil || c.areaMap == nil { + return false + } + if _, inConfig := c.Areas[code]; inConfig { + return false + } + return c.areaMap.Has(code) +} diff --git a/cmd/server/areas_test.go b/cmd/server/areas_test.go new file mode 100644 index 000000000..cd62d6f8d --- /dev/null +++ b/cmd/server/areas_test.go @@ -0,0 +1,137 @@ +package main + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "testing" + + "github.com/gorilla/mux" + "github.com/meshcore-analyzer/areamap" +) + +// A rough Scotland on the "country" layer, in GeoJSON's [lon, lat] order. +const scotlandGeoJSON = `{"type":"FeatureCollection","features":[ + {"type":"Feature","properties":{"code":"SCO","label":"Scotland","layer":"country","iata":["EDI"]}, + "geometry":{"type":"Polygon","coordinates":[[[-7.5,55.0],[-1.5,55.0],[-1.5,60.9],[-7.5,60.9],[-7.5,55.0]]]}}]}` + +func writeAreasFile(t *testing.T, body string) string { + t.Helper() + dir := t.TempDir() + if err := os.WriteFile(filepath.Join(dir, "areas.geojson"), []byte(body), 0o644); err != nil { + t.Fatal(err) + } + return dir +} + +func belgium() map[string]AreaEntry { + return map[string]AreaEntry{ + "BEL": {Label: "Belgium", Polygon: [][2]float64{{50.0, 2.5}, {51.5, 2.5}, {51.5, 6.4}, {50.0, 6.4}}}, + "_comment": {}, + } +} + +func TestLoadAreaMapReadsConfigAreasAndTheFile(t *testing.T) { + dir := writeAreasFile(t, scotlandGeoJSON) + cfg := &Config{Areas: belgium(), AreasFile: "areas.geojson"} + m, err := LoadAreaMap(cfg, dir) + if err != nil { + t.Fatal(err) + } + if cfg.areaMap != m { + t.Error("the map must be kept on the config for the store and handlers") + } + // config.json polygons are [lat, lon]; they must land the right way round. + if got, _ := m.Locate(areamap.DefaultLayer, 50.85, 4.35); got != "BEL" { + t.Errorf("Brussels = %q, want BEL from config.json", got) + } + if got, _ := m.Locate("country", 55.95, -3.19); got != "SCO" { + t.Errorf("Edinburgh = %q, want SCO from the file", got) + } + if got, _ := m.LocateIATA("country", "edi"); got != "SCO" { + t.Errorf("EDI = %q, want SCO", got) + } +} + +func TestLoadAreaMapRefusesBadFiles(t *testing.T) { + dup := `{"type":"FeatureCollection","features":[{"type":"Feature","properties":{"code":"BEL","label":"Again"},"geometry":{"type":"Polygon","coordinates":[[[0,0],[1,0],[1,1],[0,0]]]}}]}` + cases := map[string]struct { + body, file string + }{ + "a code also in config.json": {dup, "areas.geojson"}, + "a missing file": {scotlandGeoJSON, "nope.geojson"}, + "not GeoJSON": {`{`, "areas.geojson"}, + } + for name, c := range cases { + dir := writeAreasFile(t, c.body) + if _, err := LoadAreaMap(&Config{Areas: belgium(), AreasFile: c.file}, dir); err == nil { + t.Errorf("%s: accepted, want an error", name) + } + } + if m, err := LoadAreaMap(&Config{}, t.TempDir()); err != nil || len(m.Areas("")) != 0 { + t.Errorf("no areas at all = %v, %v; want an empty map and no error", m, err) + } +} + +func TestHandleConfigAreasListsFileAreasWithTheirLayer(t *testing.T) { + dir := writeAreasFile(t, scotlandGeoJSON) + cfg := &Config{Areas: belgium(), AreasFile: "areas.geojson"} + if _, err := LoadAreaMap(cfg, dir); err != nil { + t.Fatal(err) + } + r := mux.NewRouter() + srv := &Server{db: setupTestDBv2(t), cfg: cfg} + r.HandleFunc("/api/config/areas", srv.handleConfigAreas).Methods("GET") + w := httptest.NewRecorder() + r.ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/api/config/areas", nil)) + var got []map[string]string + if err := json.NewDecoder(w.Body).Decode(&got); err != nil { + t.Fatal(err) + } + layers := map[string]string{} + for _, a := range got { + layers[a["key"]] = a["layer"] + } + if len(got) != 2 || layers["BEL"] != areamap.DefaultLayer || layers["SCO"] != "country" { + t.Errorf("areas = %v, want BEL (region) and SCO (country)", got) + } +} + +func TestAreaFilterWorksForFileAreas(t *testing.T) { + db := setupTestDBv2(t) + mustExecDB(t, db, `INSERT INTO nodes (public_key, lat, lon) VALUES ('edinburgh', 55.95, -3.19)`) + mustExecDB(t, db, `INSERT INTO nodes (public_key, lat, lon) VALUES ('newcastle', 54.97, -1.61)`) + mustExecDB(t, db, `INSERT INTO nodes (public_key, lat, lon) VALUES ('dublin', 53.35, -6.26)`) + dir := writeAreasFile(t, scotlandGeoJSON) + cfg := &Config{AreasFile: "areas.geojson"} + if _, err := LoadAreaMap(cfg, dir); err != nil { + t.Fatal(err) + } + s := newTestStoreWithDB(t, db, cfg) + got := s.resolveAreaNodes("SCO") + if len(got) != 1 || !got["edinburgh"] { + t.Errorf("nodes in SCO = %v, want only edinburgh", got) + } + // config.json areas keep their own path, unchanged. + cfg.Areas = belgium() + if got := s.resolveAreaNodes("BEL"); got != nil { + t.Errorf("no Belgian nodes, got %v", got) + } +} + +// The example in docs/ must load as documented. +func TestTheDocumentedExampleAreasFileLoads(t *testing.T) { + cfg := &Config{AreasFile: "../../docs/examples/areas.example.geojson"} + m, err := LoadAreaMap(cfg, ".") + if err != nil { + t.Fatal(err) + } + if got, _ := m.Locate(areamap.DefaultLayer, 37.34, -121.89); got != "BAY" { + t.Errorf("San Jose = %q, want BAY", got) + } + if got, _ := m.LocateIATA(areamap.DefaultLayer, "MRY"); got != "MRY" { + t.Errorf("observer MRY = %q, want MRY", got) + } +} diff --git a/cmd/server/config.go b/cmd/server/config.go index efa6ed279..775ab4123 100644 --- a/cmd/server/config.go +++ b/cmd/server/config.go @@ -11,6 +11,7 @@ import ( "sync/atomic" "time" + "github.com/meshcore-analyzer/areamap" "github.com/meshcore-analyzer/dbconfig" "github.com/meshcore-analyzer/geofilter" "github.com/meshcore-analyzer/packetpath" @@ -24,6 +25,9 @@ type AreaEntry struct { LatMax *float64 `json:"latMax,omitempty"` LonMin *float64 `json:"lonMin,omitempty"` LonMax *float64 `json:"lonMax,omitempty"` + // match, when set, decides membership instead of the polygon or box: an + // area from areasFile, tested against its GeoJSON geometry. + match func(lat, lon float64) bool } // ListLimitsConfig defines maximum row limits for list endpoints to prevent DoS. @@ -139,6 +143,14 @@ type Config struct { GeoFilter *GeoFilterConfig `json:"geo_filter,omitempty"` Areas map[string]AreaEntry `json:"areas,omitempty"` + // AreasFile names a GeoJSON FeatureCollection of further areas, relative + // to the config directory: real boundaries (coastlines, islands, holes) + // in layers, which config.json's polygons cannot hold. See + // internal/areamap for the feature properties it reads. + AreasFile string `json:"areasFile,omitempty"` + // areaMap holds every area, from Areas and AreasFile, once LoadAreaMap + // has run. Nil until then. + areaMap *areamap.Map Timestamps *TimestampConfig `json:"timestamps,omitempty"` diff --git a/cmd/server/db.go b/cmd/server/db.go index b396a266d..9c2c6fc15 100644 --- a/cmd/server/db.go +++ b/cmd/server/db.go @@ -3190,6 +3190,10 @@ func (db *DB) GetNodePubkeysInArea(entry AreaEntry) ([]string, error) { LonMin: entry.LonMin, LonMax: entry.LonMax, } + inside := func(lat, lon float64) bool { return geofilter.PassesFilter(lat, lon, gf) } + if entry.match != nil { + inside = entry.match + } var result []string for rows.Next() { @@ -3205,7 +3209,7 @@ func (db *DB) GetNodePubkeysInArea(entry AreaEntry) ([]string, error) { if lat.Float64 == 0 && lon.Float64 == 0 { continue } - if geofilter.PassesFilter(lat.Float64, lon.Float64, gf) { + if inside(lat.Float64, lon.Float64) { result = append(result, pk) } } diff --git a/cmd/server/go.mod b/cmd/server/go.mod index badbe96db..c2fb40d7a 100644 --- a/cmd/server/go.mod +++ b/cmd/server/go.mod @@ -5,10 +5,13 @@ go 1.22 require ( github.com/gorilla/mux v1.8.1 github.com/gorilla/websocket v1.5.3 + github.com/meshcore-analyzer/areamap v0.0.0 github.com/meshcore-analyzer/geofilter v0.0.0 github.com/meshcore-analyzer/sigvalidate v0.0.0 ) +replace github.com/meshcore-analyzer/areamap => ../../internal/areamap + replace github.com/meshcore-analyzer/geofilter => ../../internal/geofilter replace github.com/meshcore-analyzer/sigvalidate => ../../internal/sigvalidate diff --git a/cmd/server/main.go b/cmd/server/main.go index 58a679825..b281e0f49 100644 --- a/cmd/server/main.go +++ b/cmd/server/main.go @@ -105,6 +105,14 @@ func main() { if err != nil { log.Printf("[config] warning: %v (using defaults)", err) } + // Areas from config.json and areasFile. A bad areas file stops startup: + // running with areas silently missing would put packets in the wrong + // place without anyone noticing. + if am, err := LoadAreaMap(cfg, configDir); err != nil { + log.Fatalf("[areas] %v", err) + } else if n := len(am.Areas("")); n > 0 { + log.Printf("[areas] %d areas in layers %v", n, am.Layers()) + } // CLI flags override config if port > 0 { diff --git a/cmd/server/routes.go b/cmd/server/routes.go index 066404d6c..8726e8f34 100644 --- a/cmd/server/routes.go +++ b/cmd/server/routes.go @@ -6,6 +6,7 @@ import ( "encoding/json" "errors" "fmt" + "github.com/meshcore-analyzer/areamap" "log" "math" "net/http" @@ -541,13 +542,22 @@ func (s *Server) handleConfigAreas(w http.ResponseWriter, r *http.Request) { type areaListEntry struct { Key string `json:"key"` Label string `json:"label"` + Layer string `json:"layer"` } result := make([]areaListEntry, 0, len(s.cfg.Areas)) for k, v := range s.cfg.Areas { if v.Label == "" { continue // skip comment/invalid entries (e.g. "_comment" keys in config) } - result = append(result, areaListEntry{Key: k, Label: v.Label}) + result = append(result, areaListEntry{Key: k, Label: v.Label, Layer: areamap.DefaultLayer}) + } + // Areas from areasFile, in the file's order, with their layer. + if s.cfg.areaMap != nil { + for _, a := range s.cfg.areaMap.Areas("") { + if s.cfg.fileArea(a.Code) { + result = append(result, areaListEntry{Key: a.Code, Label: a.Label, Layer: a.Layer}) + } + } } writeJSON(w, result) } @@ -1594,8 +1604,13 @@ func (s *Server) handleNodes(w http.ResponseWriter, r *http.Request) { var areaNodes map[string]bool if s.store != nil { areaNodes = s.store.resolveAreaNodes(area) - } else if s.cfg != nil && s.cfg.Areas != nil { - if entry, ok := s.cfg.Areas[area]; ok { + } else if s.cfg != nil { + entry, ok := s.cfg.Areas[area] + if !ok && s.cfg.fileArea(area) { + m := s.cfg.areaMap + entry, ok = AreaEntry{match: func(lat, lon float64) bool { return m.Contains(area, lat, lon) }}, true + } + if ok { pks, err := s.db.GetNodePubkeysInArea(entry) if err == nil { areaNodes = make(map[string]bool, len(pks)) diff --git a/cmd/server/store.go b/cmd/server/store.go index 2d9552850..4e0e71125 100644 --- a/cmd/server/store.go +++ b/cmd/server/store.go @@ -3860,12 +3860,18 @@ const areaNodeTTL = 30 * time.Second // TTL is served as-is while one background refresh re-queries it (#2146). // Uses its own RWMutex so callers holding s.mu won't deadlock. func (s *PacketStore) resolveAreaNodes(areaKey string) map[string]bool { - if s.config == nil || s.config.Areas == nil { + if s.config == nil { return nil } entry, ok := s.config.Areas[areaKey] if !ok { - return nil + if !s.config.fileArea(areaKey) { + return nil + } + // An area from areasFile: matched by position against its GeoJSON + // geometry, through the same cache as config.json's areas. + m := s.config.areaMap + entry = AreaEntry{match: func(lat, lon float64) bool { return m.Contains(areaKey, lat, lon) }} } s.areaNodeMu.RLock() diff --git a/config.example.json b/config.example.json index 012a35ec6..e57bb948c 100644 --- a/config.example.json +++ b/config.example.json @@ -272,6 +272,8 @@ "mode": "flag", "_comment": "Controls how the ingestor handles ADVERTs whose GPS is OUTSIDE the geo_filter polygon (#730). 'flag' (default): store the advert/node and tag it foreign_advert=1 so operators can see bridged/leaked nodes via the API ('foreign': true on /api/nodes). 'drop': legacy behavior — silently discard the advert (no log, no node row). Only applies when geo_filter is configured; otherwise has no effect." }, + "_comment_areasFile": "Optional. A GeoJSON FeatureCollection of further areas, path relative to this file (or absolute). Use it for real boundaries that the polygons below cannot hold: coastlines, islands (MultiPolygon) and holes. Each feature is one area; its properties are code (required, unique across every area including those below), label, layer (default \"region\"; one file can hold several sets, such as countries and counties) and iata (airport codes of observers that report no position, so they still belong to an area). Coordinates are GeoJSON's [lon, lat]. Its areas join the area filter beside the ones below. A missing or invalid file stops the server at startup. Example: docs/examples/areas.example.geojson.", + "areasFile": "", "areas": { "_comment": "Optional. GPS-based display filter. Each entry defines a geographic area by polygon ([lat, lon] pairs) or bounding box (latMin/latMax/lonMin/lonMax). Packets and nodes are attributed to an area based on the transmitting node's own GPS coordinates — not the observer's location. Areas appear as a filter pill bar in the dashboard. Remove this section to disable the area filter UI.", "BAY": { diff --git a/docs/api-spec.md b/docs/api-spec.md index 9875009e8..6aca3370e 100644 --- a/docs/api-spec.md +++ b/docs/api-spec.md @@ -2252,22 +2252,23 @@ Returns a flat key-value object. ## GET /api/config/areas -Available area filters defined in `config.json` under `areas`. Used by the frontend to populate the area pill bar. Entries with an empty `label` (e.g. comment keys) are excluded. +Available area filters: those defined in `config.json` under `areas`, then those in the GeoJSON file named by `areasFile`, in the file's order. Used by the frontend to populate the area pill bar. Entries with an empty `label` (e.g. comment keys) are excluded. ### Response `200` ```jsonc [ { - "key": string, // area key as defined in config (e.g. "bayarea") - "label": string // display name (e.g. "Bay Area") + "key": string, // area key as defined in config (e.g. "bayarea"), or a feature's code in areasFile + "label": string, // display name (e.g. "Bay Area") + "layer": string // "region" for config.json areas; the feature's layer for areasFile areas } ] ``` Returns `[]` when no areas are configured. -**Note:** Polygon coordinates are **not** included. Use `/api/config/areas/polygons` for the full geometry. +**Note:** Polygon coordinates are **not** included. Use `/api/config/areas/polygons` for the full geometry of `config.json` areas; areas from `areasFile` are not repeated there (their geometry is the file itself). --- diff --git a/docs/examples/areas.example.geojson b/docs/examples/areas.example.geojson new file mode 100644 index 000000000..2512e0aaf --- /dev/null +++ b/docs/examples/areas.example.geojson @@ -0,0 +1,23 @@ +{ + "type": "FeatureCollection", + "features": [ + { + "type": "Feature", + "properties": { "code": "BAY", "label": "Bay Area", "layer": "region", "iata": ["SJC", "SFO", "OAK"] }, + "geometry": { + "type": "Polygon", + "coordinates": [[[-122.55, 37.90], [-121.75, 37.90], [-121.75, 37.25], [-122.55, 37.25], [-122.55, 37.90]]] + } + }, + { + "type": "Feature", + "properties": { "code": "MRY", "label": "Monterey Bay", "layer": "region", "iata": ["MRY"] }, + "geometry": { + "type": "MultiPolygon", + "coordinates": [ + [[[-122.05, 37.05], [-121.60, 37.05], [-121.60, 36.45], [-122.05, 36.45], [-122.05, 37.05]]] + ] + } + } + ] +} diff --git a/internal/areamap/areamap.go b/internal/areamap/areamap.go new file mode 100644 index 000000000..ca90363b9 --- /dev/null +++ b/internal/areamap/areamap.go @@ -0,0 +1,295 @@ +// Package areamap places a position in a named area: the regions a deployment +// draws for itself in a GeoJSON file, so packets and nodes can be attributed +// to where they are, not to the observer that heard them. +// +// Each feature of the FeatureCollection is one area. Its properties name it +// (code, label), put it in a layer (several sets of areas can share a file: +// countries, counties), and may list the airport codes of observers that +// report no position. Geometry is a Polygon or MultiPolygon, holes respected, +// in GeoJSON's [lon, lat] order. +package areamap + +import ( + "encoding/json" + "errors" + "fmt" + "math" + "strings" +) + +// DefaultLayer is the layer of an area that names none. +const DefaultLayer = "region" + +// Area is one named area. +type Area struct { + Code string + Label string + Layer string + // IATA lists airport codes of observers without a position that belong + // to this area. + IATA []string + // Polygons are the area's parts; each is an outer ring and its holes, in + // [lon, lat] order. + Polygons [][][][2]float64 +} + +// Info is an area without its geometry, for listings. +type Info struct { + Code string `json:"code"` + Label string `json:"label"` + Layer string `json:"layer"` +} + +// part is one polygon prepared for lookups: its rings and bounding box. +type part struct { + rings [][][2]float64 + minLon, minLat, maxLon, maxLat float64 +} + +type prepared struct { + Area + parts []part + size float64 // area in roughly square kilometres, to pick the smallest + iata map[string]bool +} + +// Map answers which area of a layer holds a position. +type Map struct { + areas []prepared + layers []string + byCode map[string]int +} + +// ErrDuplicate is returned when two areas share a code. +var ErrDuplicate = errors.New("areamap: duplicate area code") + +type geoJSON struct { + Type string `json:"type"` + Features []struct { + Type string `json:"type"` + Properties struct { + Code string `json:"code"` + Label string `json:"label"` + Layer string `json:"layer"` + IATA []string `json:"iata"` + } `json:"properties"` + Geometry struct { + Type string `json:"type"` + Coordinates json.RawMessage `json:"coordinates"` + } `json:"geometry"` + } `json:"features"` +} + +// ParseGeoJSON reads a FeatureCollection into areas. +func ParseGeoJSON(data []byte) ([]Area, error) { + var g geoJSON + if err := json.Unmarshal(data, &g); err != nil { + return nil, fmt.Errorf("areamap: %w", err) + } + if g.Type != "FeatureCollection" { + return nil, fmt.Errorf("areamap: want a FeatureCollection, got %q", g.Type) + } + out := make([]Area, 0, len(g.Features)) + for i, f := range g.Features { + p := f.Properties + code := strings.TrimSpace(p.Code) + if code == "" { + return nil, fmt.Errorf("areamap: feature %d has no code", i) + } + a := Area{Code: code, Label: strings.TrimSpace(p.Label), Layer: strings.TrimSpace(p.Layer), IATA: p.IATA} + if a.Label == "" { + a.Label = code + } + if a.Layer == "" { + a.Layer = DefaultLayer + } + switch f.Geometry.Type { + case "Polygon": + var poly [][][2]float64 + if err := json.Unmarshal(f.Geometry.Coordinates, &poly); err != nil { + return nil, fmt.Errorf("areamap: %s: %w", code, err) + } + a.Polygons = [][][][2]float64{poly} + case "MultiPolygon": + if err := json.Unmarshal(f.Geometry.Coordinates, &a.Polygons); err != nil { + return nil, fmt.Errorf("areamap: %s: %w", code, err) + } + default: + return nil, fmt.Errorf("areamap: %s: geometry %q is not a Polygon or MultiPolygon", code, f.Geometry.Type) + } + for _, poly := range a.Polygons { + if len(poly) == 0 { + return nil, fmt.Errorf("areamap: %s: a polygon with no rings", code) + } + for _, ring := range poly { + if len(ring) < 3 { + return nil, fmt.Errorf("areamap: %s: a ring needs at least three points", code) + } + } + } + out = append(out, a) + } + return out, nil +} + +// New builds a map. Codes must be unique across every layer. +func New(areas []Area) (*Map, error) { + m := &Map{byCode: make(map[string]int, len(areas))} + seenLayer := map[string]bool{} + for _, a := range areas { + if _, dup := m.byCode[a.Code]; dup { + return nil, fmt.Errorf("%w: %s", ErrDuplicate, a.Code) + } + if a.Layer == "" { + a.Layer = DefaultLayer + } + p := prepared{Area: a, iata: map[string]bool{}} + for _, c := range a.IATA { + p.iata[strings.ToUpper(strings.TrimSpace(c))] = true + } + for _, poly := range a.Polygons { + pt := part{rings: poly, minLon: math.Inf(1), minLat: math.Inf(1), maxLon: math.Inf(-1), maxLat: math.Inf(-1)} + for _, c := range poly[0] { + pt.minLon, pt.maxLon = math.Min(pt.minLon, c[0]), math.Max(pt.maxLon, c[0]) + pt.minLat, pt.maxLat = math.Min(pt.minLat, c[1]), math.Max(pt.maxLat, c[1]) + } + p.parts = append(p.parts, pt) + for i, ring := range poly { + s := ringSize(ring) + if i > 0 { + s = -s + } + p.size += s + } + } + m.byCode[a.Code] = len(m.areas) + m.areas = append(m.areas, p) + if !seenLayer[a.Layer] { + seenLayer[a.Layer] = true + m.layers = append(m.layers, a.Layer) + } + } + return m, nil +} + +// ringSize is a ring's area in roughly square kilometres: the shoelace sum +// with longitude scaled by the cosine of the ring's mean latitude. It only +// has to order overlapping areas by size. +func ringSize(ring [][2]float64) float64 { + var lat float64 + for _, c := range ring { + lat += c[1] + } + k := math.Cos(lat / float64(len(ring)) * math.Pi / 180) + var s float64 + for i, j := 0, len(ring)-1; i < len(ring); j, i = i, i+1 { + s += (ring[j][0]*k)*ring[i][1] - (ring[i][0]*k)*ring[j][1] + } + return math.Abs(s) / 2 * 111.32 * 111.32 +} + +// inRing is the even-odd test on one ring, x = lon, y = lat. +func inRing(ring [][2]float64, lat, lon float64) bool { + in := false + for i, j := 0, len(ring)-1; i < len(ring); j, i = i, i+1 { + xi, yi := ring[i][0], ring[i][1] + xj, yj := ring[j][0], ring[j][1] + if (yi > lat) != (yj > lat) && lon < (xj-xi)*(lat-yi)/(yj-yi)+xi { + in = !in + } + } + return in +} + +func (p *prepared) contains(lat, lon float64) bool { + for i := range p.parts { + pt := &p.parts[i] + if lon < pt.minLon || lon > pt.maxLon || lat < pt.minLat || lat > pt.maxLat { + continue + } + if !inRing(pt.rings[0], lat, lon) { + continue + } + hole := false + for _, h := range pt.rings[1:] { + if inRing(h, lat, lon) { + hole = true + break + } + } + if !hole { + return true + } + } + return false +} + +// Layers lists the layers, in the order their first area appeared. +func (m *Map) Layers() []string { return append([]string(nil), m.layers...) } + +// Areas lists one layer's areas, or every area when layer is "". +func (m *Map) Areas(layer string) []Info { + out := []Info{} + for i := range m.areas { + a := &m.areas[i] + if layer == "" || a.Layer == layer { + out = append(out, Info{Code: a.Code, Label: a.Label, Layer: a.Layer}) + } + } + return out +} + +// Locate returns the code of the smallest area of layer containing the +// position. 0,0 is an unset GPS, never a place. +func (m *Map) Locate(layer string, lat, lon float64) (string, bool) { + if m == nil || (lat == 0 && lon == 0) { + return "", false + } + best, bestSize := -1, math.Inf(1) + for i := range m.areas { + a := &m.areas[i] + if a.Layer != layer || a.size >= bestSize { + continue + } + if a.contains(lat, lon) { + best, bestSize = i, a.size + } + } + if best < 0 { + return "", false + } + return m.areas[best].Code, true +} + +// LocateIATA returns the area of layer whose IATA list holds code. +func (m *Map) LocateIATA(layer, code string) (string, bool) { + if m == nil { + return "", false + } + code = strings.ToUpper(strings.TrimSpace(code)) + for i := range m.areas { + a := &m.areas[i] + if a.Layer == layer && a.iata[code] { + return a.Code, true + } + } + return "", false +} + +// Has reports whether an area with code exists. +func (m *Map) Has(code string) bool { + if m == nil { + return false + } + _, ok := m.byCode[code] + return ok +} + +// Contains reports whether the area with code holds the position. +func (m *Map) Contains(code string, lat, lon float64) bool { + if m == nil || (lat == 0 && lon == 0) { + return false + } + i, ok := m.byCode[code] + return ok && m.areas[i].contains(lat, lon) +} diff --git a/internal/areamap/areamap_test.go b/internal/areamap/areamap_test.go new file mode 100644 index 000000000..6ea3f7238 --- /dev/null +++ b/internal/areamap/areamap_test.go @@ -0,0 +1,188 @@ +package areamap + +import ( + "errors" + "testing" +) + +// Two countries and a city: "Mainland" has a lake (a hole) and an island (a +// second polygon); "City" sits inside Mainland on another layer; "Neighbour" +// borders Mainland to the east. +const fixture = `{ + "type": "FeatureCollection", + "features": [ + {"type": "Feature", "properties": {"code": "MLD", "label": "Mainland", "layer": "country", "iata": ["MLA", "mlb"]}, + "geometry": {"type": "MultiPolygon", "coordinates": [ + [[[0,0],[10,0],[10,10],[0,10],[0,0]], [[4,4],[6,4],[6,6],[4,6],[4,4]]], + [[[-5,2],[-3,2],[-3,4],[-5,4],[-5,2]]] + ]}}, + {"type": "Feature", "properties": {"code": "NBR", "label": "Neighbour", "layer": "country"}, + "geometry": {"type": "Polygon", "coordinates": [[[10,0],[20,0],[20,10],[10,10],[10,0]]]}}, + {"type": "Feature", "properties": {"code": "CTY", "label": "City"}, + "geometry": {"type": "Polygon", "coordinates": [[[1,1],[3,1],[3,3],[1,3],[1,1]]]}} + ] +}` + +func load(t *testing.T) *Map { + t.Helper() + areas, err := ParseGeoJSON([]byte(fixture)) + if err != nil { + t.Fatal(err) + } + m, err := New(areas) + if err != nil { + t.Fatal(err) + } + return m +} + +func TestParseGeoJSONReadsEveryFeature(t *testing.T) { + areas, err := ParseGeoJSON([]byte(fixture)) + if err != nil { + t.Fatal(err) + } + if len(areas) != 3 { + t.Fatalf("areas = %d, want 3", len(areas)) + } + if a := areas[0]; a.Code != "MLD" || a.Label != "Mainland" || a.Layer != "country" || len(a.Polygons) != 2 || len(a.Polygons[0]) != 2 { + t.Errorf("Mainland = %+v, want two parts, the first with a hole", a) + } + if a := areas[2]; a.Layer != DefaultLayer { + t.Errorf("an area naming no layer is in %q, want %q", a.Layer, DefaultLayer) + } +} + +func TestLocateUsesLonLatOrderHolesAndIslands(t *testing.T) { + m := load(t) + cases := []struct { + name string + lat, lon float64 + want string + }{ + {"inside the mainland", 8, 2, "MLD"}, + {"on the island", 3, -4, "MLD"}, + {"in the lake", 5, 5, ""}, + {"in the neighbour", 5, 15, "NBR"}, + {"at sea", 50, 50, ""}, + {"lat and lon swapped would land in the neighbour", 2, 15, "NBR"}, + {"unset GPS", 0, 0, ""}, + } + for _, c := range cases { + got, ok := m.Locate("country", c.lat, c.lon) + if got != c.want || ok != (c.want != "") { + t.Errorf("%s (%v, %v) = %q %v, want %q", c.name, c.lat, c.lon, got, ok, c.want) + } + } +} + +func TestLocateStaysInsideItsLayer(t *testing.T) { + m := load(t) + if got, _ := m.Locate("country", 2, 2); got != "MLD" { + t.Errorf("country layer at the city = %q, want MLD", got) + } + if got, _ := m.Locate(DefaultLayer, 2, 2); got != "CTY" { + t.Errorf("region layer at the city = %q, want CTY", got) + } + if got, ok := m.Locate("no-such-layer", 2, 2); ok { + t.Errorf("an unknown layer placed a point in %q", got) + } +} + +func TestSmallestAreaWinsWhereALayerOverlaps(t *testing.T) { + big := Area{Code: "BIG", Label: "Big", Layer: "x", Polygons: [][][][2]float64{{{{0, 0}, {10, 0}, {10, 10}, {0, 10}}}}} + small := Area{Code: "SML", Label: "Small", Layer: "x", Polygons: [][][][2]float64{{{{2, 2}, {4, 2}, {4, 4}, {2, 4}}}}} + m, err := New([]Area{big, small}) + if err != nil { + t.Fatal(err) + } + if got, _ := m.Locate("x", 3, 3); got != "SML" { + t.Errorf("overlap = %q, want the smaller area SML", got) + } + if got, _ := m.Locate("x", 8, 8); got != "BIG" { + t.Errorf("outside the small area = %q, want BIG", got) + } +} + +func TestLayersAreasAndIATA(t *testing.T) { + m := load(t) + if l := m.Layers(); len(l) != 2 || l[0] != "country" || l[1] != DefaultLayer { + t.Errorf("layers = %v, want [country region]", l) + } + if a := m.Areas("country"); len(a) != 2 || a[0].Code != "MLD" || a[1].Label != "Neighbour" { + t.Errorf("country areas = %+v", a) + } + if a := m.Areas(""); len(a) != 3 { + t.Errorf("all areas = %d, want 3", len(a)) + } + if got, ok := m.LocateIATA("country", "MLB"); !ok || got != "MLD" { + t.Errorf("IATA MLB = %q %v, want MLD (case-insensitive)", got, ok) + } + if _, ok := m.LocateIATA(DefaultLayer, "MLA"); ok { + t.Error("an IATA code belongs to its own layer only") + } + if !m.Has("CTY") || m.Has("NOPE") { + t.Error("Has must know every code and only those") + } + if !m.Contains("MLD", 3, -4) || m.Contains("MLD", 5, 5) || m.Contains("NOPE", 1, 1) { + t.Error("Contains disagrees with Locate") + } +} + +func TestBadInputIsRefused(t *testing.T) { + cases := map[string]string{ + "not json": `{`, + "not a collection": `{"type":"Feature"}`, + "no code": `{"type":"FeatureCollection","features":[{"type":"Feature","properties":{"label":"x"},"geometry":{"type":"Polygon","coordinates":[[[0,0],[1,0],[1,1],[0,0]]]}}]}`, + "a point": `{"type":"FeatureCollection","features":[{"type":"Feature","properties":{"code":"P","label":"x"},"geometry":{"type":"Point","coordinates":[0,0]}}]}`, + "a two-point ring": `{"type":"FeatureCollection","features":[{"type":"Feature","properties":{"code":"P","label":"x"},"geometry":{"type":"Polygon","coordinates":[[[0,0],[1,0]]]}}]}`, + } + for name, in := range cases { + if _, err := ParseGeoJSON([]byte(in)); err == nil { + t.Errorf("%s: accepted, want an error", name) + } + } + dup := []Area{ + {Code: "A", Label: "One", Layer: "x", Polygons: [][][][2]float64{{{{0, 0}, {1, 0}, {1, 1}}}}}, + {Code: "A", Label: "Two", Layer: "y", Polygons: [][][][2]float64{{{{0, 0}, {1, 0}, {1, 1}}}}}, + } + if _, err := New(dup); !errors.Is(err, ErrDuplicate) { + t.Errorf("duplicate code across layers: err = %v, want ErrDuplicate", err) + } +} + +// A realistic boundary: six areas of 2,000 vertices each. +func BenchmarkLocate(b *testing.B) { + var areas []Area + for a := 0; a < 6; a++ { + ring := make([][2]float64, 0, 2000) + for i := 0; i < 2000; i++ { + // a jagged square, each area offset east of the last + t := float64(i) / 2000 + var x, y float64 + switch { + case t < .25: + x, y = t*4, 0 + case t < .5: + x, y = 1, (t-.25)*4 + case t < .75: + x, y = 1-(t-.5)*4, 1 + default: + x, y = 0, 1-(t-.75)*4 + } + if i%2 == 1 { + x, y = x*0.999+0.0005, y*0.999+0.0005 + } + ring = append(ring, [2]float64{float64(a) + x, y}) + } + areas = append(areas, Area{Code: string(rune('A' + a)), Label: "x", Layer: "x", Polygons: [][][][2]float64{{ring}}}) + } + m, err := New(areas) + if err != nil { + b.Fatal(err) + } + b.ReportAllocs() + b.ResetTimer() + for i := 0; i < b.N; i++ { + m.Locate("x", 0.5, float64(i%6)+0.5) + } +} diff --git a/internal/areamap/go.mod b/internal/areamap/go.mod new file mode 100644 index 000000000..09e3d8f88 --- /dev/null +++ b/internal/areamap/go.mod @@ -0,0 +1,3 @@ +module github.com/meshcore-analyzer/areamap + +go 1.22