Skip to content

armgit / Aleph

Public Imported from GitHub
0

Give satellite imagery, terrain data, buildings, streetview photos to your LLM

Initial new dashboard

Belluxxd7fdd59ec63a
diff --git a/README.md b/README.md
index ebd4f55..0dc9321 100644
--- a/README.md
+++ b/README.md
@@ -39,6 +39,16 @@ Then test with
alephgeo --help
```
+## Open the dashboard
+
+```sh
+alephgeo dashboard -o captures
+```
+
+The dashboard opens in your browser at `http://127.0.0.1:8100`. Draw a rectangle on the map, choose the sources and their settings, check the preview and time estimate, then start the capture. Open any capture to show or hide each layer. Captures are saved in `captures`.
+
+The basemap comes from [OpenFreeMap](https://openfreemap.org) and needs an internet connection.
+
## Use the CLI
Download a Street View photo or satellite image by place name:
diff --git a/aleph.py b/aleph.py
index c851f30..8e2629f 100644
--- a/aleph.py
+++ b/aleph.py
@@ -1,7 +1,6 @@
"""Find places, request imagery, and manage area captures."""
import json
-import math
import os
import shutil
import sys
@@ -11,7 +10,7 @@ from pathlib import Path
from src import capture, places, quick
from src.cli import parser
from src.common import CachedClient, Client, Progress, RequestError, now
-from src.geo import MERCATOR_RADIUS, bounds
+from src.geo import bounds
def style(text, code="1"):
@@ -32,8 +31,7 @@ def describe(run):
elif mode == "satellite":
label = "Satellite"
g = stage["grid"]
- latitude = math.radians((run["bounds"][0] + run["bounds"][2]) / 2)
- scale = 2 * math.pi * MERCATOR_RADIUS * math.cos(latitude) / (256 * 2 ** g["zoom"])
+ scale = capture.resolution(run["bounds"], g["zoom"])
message = f"{estimate['satellite_tiles']:,} tiles, {g['width']:,} × {g['height']:,} px at about {scale:.2f} m/px"
elif mode == "osm":
label = "OSM map"
@@ -190,8 +188,10 @@ def main(argv=None):
return 0
args = command.parse_args(argv)
if args.command == "dashboard":
- print("The dashboard is not available yet.", file=sys.stderr)
- return 1
+ from src import dashboard
+
+ return dashboard.serve(args.output, args.port, cache_dir=args.cache_dir, refresh=args.refresh,
+ open_browser=not args.no_browser)
if args.command != "capture":
with Progress() as progress:
result = query(args, progress)
diff --git a/docs/cli.md b/docs/cli.md
index b549917..e58342d 100644
--- a/docs/cli.md
+++ b/docs/cli.md
@@ -103,6 +103,14 @@ Rebuild outputs from downloaded files, offline:
alephgeo capture export captures/RUN_FOLDER
```
+## Open the dashboard
+
+```sh
+alephgeo dashboard -o captures
+```
+
+It lists the captures in `captures`, including ones made with `capture create`, and can resume stopped ones. `--port` changes the local port (default: `8100`) and `--no-browser` skips opening a tab. Quitting while a capture runs stops it so it can be resumed later.
+
## Use in scripts
Add `--json` for one JSON result on stdout; progress stays on stderr.
diff --git a/pyproject.toml b/pyproject.toml
index bfd5e98..313e0be 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -16,3 +16,6 @@ alephgeo = "aleph:main"
[tool.setuptools]
py-modules = ["aleph"]
packages = ["src"]
+
+[tool.setuptools.package-data]
+src = ["web/*"]
diff --git a/src/capture.py b/src/capture.py
index a9c49a9..2eddd4d 100644
--- a/src/capture.py
+++ b/src/capture.py
@@ -12,7 +12,7 @@ from PIL import Image
from . import mesh, satellite, streetview, terrain
from .common import WORKERS, MissingImagery, contained, fetch, now, number, open_image, positive, write_bytes, write_json
-from .geo import bounds, collection, coordinate, feature, grid, pixel, tile_ring, tiles
+from .geo import MERCATOR_RADIUS, bounds, collection, coordinate, feature, grid, pixel, tile_ring, tiles
SOURCES = ("streetview", "satellite", "osm", "mesh")
FORMAT_VERSION = 4
@@ -176,6 +176,12 @@ def estimate(run):
return dict(counts, seconds=math.ceil(seconds))
+def resolution(area, zoom, tile_size=256):
+ """Approximate ground meters per pixel at the middle of the area."""
+ latitude = math.radians((area[0] + area[2]) / 2)
+ return 2 * math.pi * MERCATOR_RADIUS * math.cos(latitude) / (tile_size * 2**zoom)
+
+
def photos(run, after=0):
return collection(
feature("Point", [photo["lon"], photo["lat"]], photo)
diff --git a/src/cli.py b/src/cli.py
index 120ca44..16d61be 100644
--- a/src/cli.py
+++ b/src/cli.py
@@ -192,4 +192,8 @@ def _capture_command(commands):
def _dashboard_command(commands):
- commands.add_parser("dashboard", help="Open the local capture dashboard (not available yet)")
+ dashboard = commands.add_parser("dashboard", help="Draw, capture, and explore areas in the browser")
+ dashboard.add_argument("-o", "--output", type=Path, default=Path("."), help="folder holding captures (default: current directory)")
+ dashboard.add_argument("--port", type=int, default=8100, help="local port (default: %(default)s)")
+ dashboard.add_argument("--no-browser", action="store_true", help="do not open a browser tab")
+ _cache_options(dashboard)
diff --git a/src/dashboard.py b/src/dashboard.py
new file mode 100644
index 0000000..9e8fb07
--- /dev/null
+++ b/src/dashboard.py
@@ -0,0 +1,430 @@
+"""Local dashboard: draw an area, preview its plan, capture it, and explore the results."""
+
+import json
+import mimetypes
+import sys
+import threading
+import webbrowser
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+from pathlib import Path
+from urllib.parse import parse_qs, unquote, urlsplit
+
+from . import capture, layers, places
+from .common import CachedClient, Client, RequestError, contained, now
+from .geo import bounds, collection, coordinate, feature, grid
+
+WEB = Path(__file__).resolve().parent / "web"
+PHOTO_KEYS = ("sequence", "filename", "heading", "side", "imagery_date", "pano_id", "path_name", "streetview_url")
+OUTPUTS = ("satellite.tif", "satellite.png", "terrain.tif", "map.osm", "mesh.glb")
+
+
+class Stopped(KeyboardInterrupt):
+ """Raised from a job's requests; capture.download then saves the run as stopped."""
+
+
+class Busy(Exception):
+ pass
+
+
+class Job:
+ """One planning or capture task at a time, polled by the browser."""
+
+ count = 0
+
+ def __init__(self, kind, work, folder=None, run=None):
+ Job.count += 1
+ self.id, self.kind, self.folder, self.run = Job.count, kind, folder, run
+ self.state, self.error, self.preview = "running", None, None
+ self.phase, self.done, self.total, self.unit = "Starting", 0, None, None
+ self.stop = threading.Event()
+ self.thread = threading.Thread(target=self.work, args=(work,), daemon=True)
+ self.thread.start()
+
+ def check(self):
+ if self.stop.is_set():
+ raise Stopped
+
+ def progress(self, phase, done=0, total=None, unit=None):
+ # Captures only stop between requests, so their partial exports can still finish.
+ if self.kind == "plan":
+ self.check()
+ self.phase, self.done, self.total, self.unit = phase, done, total, unit
+
+ def work(self, work):
+ try:
+ work(self)
+ self.state = "done"
+ except KeyboardInterrupt:
+ self.state = "stopped"
+ except Exception as error:
+ self.state, self.error = "failed", str(error) or type(error).__name__
+ print(f"alephgeo dashboard: {self.error}", file=sys.stderr)
+
+
+def imagery(area, stage, tile_size):
+ g = stage["grid"]
+ return dict(tiles=g["rows"] * g["columns"], zoom=g["zoom"], width=g["width"], height=g["height"],
+ meters_per_pixel=capture.resolution(area, g["zoom"], tile_size))
+
+
+def grid_lines(g, kind):
+ """Tile boundaries, or just the outline of large grids."""
+ x0, y0, x1, y1 = g["x0"], g["y0"], g["x0"] + g["columns"], g["y0"] + g["rows"]
+
+ def point(x, y):
+ lat, lon = coordinate(x * 256, y * 256, g["zoom"])
+ return [lon, lat]
+
+ xs = range(x0, x1 + 1) if g["columns"] <= 64 else (x0, x1)
+ ys = range(y0, y1 + 1) if g["rows"] <= 64 else (y0, y1)
+ lines = [[point(x, y0), point(x, y1)] for x in xs] + [[point(x0, y), point(x1, y)] for y in ys]
+ return feature("MultiLineString", lines, dict(kind=kind))
+
+
+def plan_layers(run):
+ """Planned street paths, stops, and spacing gaps, and the imagery tile grids."""
+ features = []
+ for stage in run["stages"]:
+ if stage["mode"] == "streetview":
+ features += [feature("LineString", [[p[1], p[0]] for p in part["points"]], dict(kind="path"))
+ for part in stage["paths"]]
+ features += [feature("LineString", [[gap["start"][1], gap["start"][0]], [gap["end"][1], gap["end"][0]]],
+ dict(kind="gap")) for gap in stage["coverage"]["gaps"]]
+ features += [feature("Point", [stop["lon"], stop["lat"]], dict(kind="stop")) for stop in stage["samples"]]
+ elif "grid" in stage:
+ features.append(grid_lines(stage["grid"], stage["mode"]))
+ return collection(features)
+
+
+def preview(run):
+ area, stages = run["bounds"], {}
+ for stage in run["stages"]:
+ mode = stage["mode"]
+ if mode == "streetview":
+ stages[mode] = dict(stops=len(stage["samples"]), photos=capture.total(stage), sphere=stage["full_sphere"],
+ panoramas=stage["coverage"]["available"], gaps=len(stage["coverage"]["gaps"]),
+ meters=stage["length"])
+ elif mode in ("satellite", "terrain"):
+ stages[mode] = imagery(area, stage, 512 if mode == "terrain" else 256)
+ elif mode == "mesh":
+ stages[mode] = dict(nodes=len(stage["nodes"]), level=stage["level"])
+ else:
+ stages[mode] = {}
+ return dict(bounds=area, options=run["options"], seconds=capture.estimate(run)["seconds"], stages=stages,
+ layers=plan_layers(run))
+
+
+def summary(identity, run, live):
+ stages = {}
+ for stage in run["stages"]:
+ results = stage["results"]
+ count = len(results)
+ stages[stage["mode"]] = info = dict(done=count, total=capture.total(stage))
+ if stage["mode"] in ("streetview", "mesh"):
+ info["skipped"] = sum(result.get("status") == "skipped" for result in results[:count])
+ if "grid" in stage:
+ info["zoom"] = stage["grid"]["zoom"]
+ state = "interrupted" if run["state"] == "running" and not live else run["state"]
+ return dict(id=identity, bounds=run["bounds"], started_at=run["started_at"], finished_at=run.get("finished_at"),
+ state=state, error=run.get("error"), options=run["options"], stages=stages)
+
+
+def area_and_options(body):
+ try:
+ area = bounds([float(value) for value in body["bounds"]])
+ except (KeyError, TypeError, ValueError) as error:
+ raise ValueError(f"Draw a valid rectangle first. {error}".strip()) from error
+ return area, capture.settings(body.get("options"))
+
+
+class Dashboard:
+ def __init__(self, root, cache_dir, refresh):
+ self.root = Path(root).expanduser().resolve()
+ self.cache_dir, self.refresh = cache_dir, refresh
+ self.lock = threading.RLock()
+ self.job = None
+ self.runs = {}
+ self.osm = {}
+ self.tiles = layers.Tiles()
+
+ # Jobs
+
+ def start(self, kind, work, folder=None, run=None):
+ with self.lock:
+ if self.job and self.job.state == "running":
+ raise Busy("Another task is running. Stop it first.")
+ self.job = Job(kind, work, folder, run)
+ return self.job_state()
+
+ def client(self, job, delay):
+ return Client(delay, cancel=job.check, cache_dir=self.cache_dir, refresh=self.refresh)
+
+ def plan(self, body):
+ area, options = area_and_options(body)
+
+ def work(job):
+ job.run = capture.plan(self.client(job, options["delay"]), area, options, job.progress)
+ job.preview = preview(job.run)
+
+ return self.start("plan", work)
+
+ def capture(self, body):
+ with self.lock:
+ job = self.job
+ if not job or job.kind != "plan" or job.state != "done" or job.id != body.get("plan"):
+ raise ValueError("This preview is out of date. Preview the capture again.")
+ run = job.run
+ run["started_at"] = now()
+ folder = capture.create_folder(run, self.root)
+ capture.save_preview(run, folder)
+ return self.download(folder, run)
+
+ def resume(self, identity):
+ folder = self.folder(identity)
+ with self.lock:
+ if self.job and self.job.state == "running":
+ raise Busy("Another task is running. Stop it first.")
+ return self.download(folder, capture.load(folder))
+
+ def download(self, folder, run):
+ def work(job):
+ capture.download(run, folder, self.client(job, run["options"]["delay"]), job.progress)
+
+ return self.start("capture", work, folder, run)
+
+ def stop(self):
+ if self.job and self.job.state == "running":
+ self.job.stop.set()
+ return self.job_state()
+
+ def job_state(self):
+ job = self.job
+ if job is None:
+ return None
+ state = dict(id=job.id, kind=job.kind, state=job.state, phase=job.phase, done=job.done, total=job.total,
+ unit=job.unit, error=job.error, stopping=job.stop.is_set())
+ if job.kind == "capture":
+ state["capture"] = job.folder.name
+ state["seconds"] = capture.estimate(job.run)["seconds"]
+ state["stages"] = {stage["mode"]: dict(done=len(stage["results"]), total=capture.total(stage))
+ for stage in job.run["stages"]}
+ return state
+
+ # Captures
+
+ def folder(self, identity):
+ if "/" in identity or identity.startswith("."):
+ raise FileNotFoundError("Capture not found.")
+ folder = contained(self.root, identity)
+ if not (folder / "manifest.json").is_file():
+ raise FileNotFoundError("Capture not found.")
+ return folder
+
+ def load(self, identity):
+ """The live run while it downloads, otherwise its manifest, reloaded when it changes."""
+ folder = self.folder(identity)
+ job = self.job
+ if job and job.kind == "capture" and job.folder == folder and job.state == "running":
+ return folder, job.run, True
+ stat = (folder / "manifest.json").stat()
+ signature = stat.st_mtime_ns, stat.st_size
+ cached = self.runs.get(identity)
+ if not cached or cached[0] != signature:
+ cached = self.runs[identity] = signature, capture.load(folder, check_files=False)
+ return folder, cached[1], False
+
+ def stage(self, identity, mode):
+ folder, run, live = self.load(identity)
+ stage = next((stage for stage in run["stages"] if stage["mode"] == mode), None)
+ if stage is None:
+ raise FileNotFoundError(f"This capture has no {mode} data.")
+ return folder, stage, live
+
+ def captures(self):
+ items = []
+ for folder in self.root.iterdir() if self.root.is_dir() else ():
+ if folder.is_dir() and (folder / "manifest.json").is_file():
+ try:
+ _, run, live = self.load(folder.name)
+ items.append(summary(folder.name, run, live))
+ except (OSError, ValueError, KeyError, TypeError) as error:
+ items.append(dict(id=folder.name, state="unreadable", error=str(error)))
+ return sorted(items, key=lambda item: item.get("started_at", ""), reverse=True)
+
+ def detail(self, identity):
+ folder, run, live = self.load(identity)
+ files = {name: (folder / name).stat().st_size for name in OUTPUTS if (folder / name).is_file()}
+ return dict(summary(identity, run, live), folder=str(folder), files=files)
+
+ def photos(self, identity, after):
+ try:
+ _, stage, _ = self.stage(identity, "streetview")
+ except FileNotFoundError:
+ return dict(count=0, features=[])
+ results = stage["results"]
+ count = len(results)
+ return dict(count=count, features=[
+ feature("Point", [photo["lon"], photo["lat"]], {key: photo.get(key) for key in PHOTO_KEYS})
+ for photo in results[max(0, after):count] if photo["status"] == "saved"])
+
+ def osm_layer(self, identity):
+ folder = self.folder(identity)
+ path = folder / "map.osm"
+ if not path.is_file():
+ raise FileNotFoundError("This capture has no saved OSM map yet.")
+ stat = path.stat()
+ signature = stat.st_mtime_ns, stat.st_size
+ cached = self.osm.get(identity)
+ if not cached or cached[0] != signature:
+ data = json.dumps(layers.osm(path), separators=(",", ":")).encode()
+ cached = self.osm[identity] = signature, data
+ return cached[1], "application/geo+json", 0
+
+ def tile(self, identity, mode, z, x, y):
+ folder, stage, _ = self.stage(identity, mode)
+ tile = self.tiles.get(folder, stage, int(z), int(x), int(y.split(".")[0]))
+ if tile is None:
+ raise FileNotFoundError("No saved tile here.")
+ # Tile URLs carry the saved count, so a response never changes.
+ return *tile, 86400
+
+ def file(self, identity, path):
+ target = contained(self.folder(identity), "/".join(path))
+ if not target.is_file():
+ raise FileNotFoundError("File not found.")
+ return target.read_bytes(), mimetypes.guess_type(target.name)[0] or "application/octet-stream", 86400
+
+ # Routes
+
+ def handle(self, method, parts, query, body):
+ match method, parts:
+ case "GET", []:
+ return (WEB / "index.html").read_bytes(), "text/html; charset=utf-8", 0
+ case "GET", [("app.js" | "style.css") as name]:
+ return (WEB / name).read_bytes(), mimetypes.guess_type(name)[0], 0
+ case "GET", ["api", "config"]:
+ return dict(root=str(self.root), defaults=capture.DEFAULT_OPTIONS, overviews=layers.OVERVIEWS)
+ case "GET", ["api", "job"]:
+ return self.job_state()
+ case "GET", ["api", "preview"]:
+ job = self.job
+ if not job or job.kind != "plan" or job.preview is None:
+ raise FileNotFoundError("No preview is ready.")
+ return dict(job.preview, plan=job.id)
+ case "GET", ["api", "search"]:
+ client = CachedClient(cache_dir=self.cache_dir, refresh=self.refresh)
+ return places.geocode(client, query=query.get("q", [""])[0], limit=6)
+ case "GET", ["api", "captures"]:
+ return self.captures()
+ case "GET", ["api", "captures", identity]:
+ return self.detail(identity)
+ case "GET", ["api", "captures", identity, "plan"]:
+ _, run, _ = self.load(identity)
+ return plan_layers(run)
+ case "GET", ["api", "captures", identity, "photos"]:
+ return self.photos(identity, int(query.get("after", ["0"])[0]))
+ case "GET", ["api", "captures", identity, "osm"]:
+ return self.osm_layer(identity)
+ case "GET", ["api", "captures", identity, ("satellite" | "terrain") as mode, z, x, y]:
+ return self.tile(identity, mode, z, x, y)
+ case "GET", ["api", "captures", identity, "files", *path] if path:
+ return self.file(identity, path)
+ case "POST", ["api", "estimate"]:
+ area, options = area_and_options(body)
+ result = {}
+ for mode, source in (("satellite", "satellite"), ("terrain", "osm")):
+ if source in options["include"]:
+ stage = dict(mode=mode, grid=grid(area, options[f"{mode}_zoom"]), results=[])
+ result[mode] = dict(imagery(area, stage, 512 if mode == "terrain" else 256),
+ seconds=capture.estimate(dict(stages=[stage], options=options))["seconds"])
+ return result
+ case "POST", ["api", "plan"]:
+ return self.plan(body)
+ case "POST", ["api", "capture"]:
+ return self.capture(body)
+ case "POST", ["api", "stop"]:
+ return self.stop()
+ case "POST", ["api", "captures", identity, "resume"]:
+ return self.resume(identity)
+ raise FileNotFoundError("Not found.")
+
+
+class Handler(BaseHTTPRequestHandler):
+ server_version = "Aleph"
+
+ def log_message(self, *args):
+ pass
+
+ def do_GET(self):
+ self.dispatch("GET")
+
+ def do_POST(self):
+ self.dispatch("POST")
+
+ def send(self, status, data, content_type, max_age=0):
+ self.send_response(status)
+ self.send_header("Content-Type", content_type)
+ self.send_header("Content-Length", str(len(data)))
+ self.send_header("Cache-Control", f"max-age={max_age}" if max_age else "no-store")
+ self.send_header("X-Content-Type-Options", "nosniff")
+ self.end_headers()
+ self.wfile.write(data)
+
+ def dispatch(self, method):
+ app = self.server.app
+ # Refuse other sites reaching this server through DNS rebinding.
+ if self.headers.get("Host") not in self.server.hosts:
+ return self.send(403, b"Forbidden", "text/plain")
+ address = urlsplit(self.path)
+ parts = [unquote(part) for part in address.path.split("/") if part]
+ try:
+ body = {}
+ if method == "POST":
+ # JSON bodies need a CORS preflight, which this server never grants.
+ if self.headers.get("Content-Type", "").split(";")[0].strip() != "application/json":
+ raise ValueError("Send JSON.")
+ body = json.loads(self.rfile.read(int(self.headers.get("Content-Length") or 0)) or b"{}")
+ if not isinstance(body, dict):
+ raise ValueError("Send a JSON object.")
+ result = app.handle(method, parts, parse_qs(address.query), body)
+ if isinstance(result, tuple):
+ return self.send(200, *result)
+ self.send(200, json.dumps(result, separators=(",", ":")).encode(), "application/json")
+ except (BrokenPipeError, ConnectionResetError):
+ pass
+ except Exception as error:
+ status = (404 if isinstance(error, FileNotFoundError) else 409 if isinstance(error, Busy)
+ else 502 if isinstance(error, RequestError) else 400 if isinstance(error, ValueError) else 500)
+ if status == 500:
+ print(f"alephgeo dashboard: {method} {address.path}: {error!r}", file=sys.stderr)
+ message = str(error) or type(error).__name__
+ try:
+ self.send(status, json.dumps(dict(error=message)).encode(), "application/json")
+ except OSError:
+ pass
+
+
+def serve(root, port, *, cache_dir, refresh=False, open_browser=True):
+ server = ThreadingHTTPServer(("127.0.0.1", port), Handler)
+ server.daemon_threads = True
+ server.app = app = Dashboard(root, cache_dir, refresh)
+ port = server.server_address[1]
+ server.hosts = {f"127.0.0.1:{port}", f"localhost:{port}"}
+ address = f"http://127.0.0.1:{port}/"
+ print(f"Aleph dashboard at {address}\nCaptures in {app.root}\nPress Ctrl-C to quit.", file=sys.stderr)
+ if open_browser:
+ webbrowser.open(address)
+ try:
+ server.serve_forever()
+ except KeyboardInterrupt:
+ job = app.job
+ if job and job.state == "running":
+ print("\nStopping the running task. Press Ctrl-C again to quit now.", file=sys.stderr)
+ job.stop.set()
+ try:
+ job.thread.join()
+ except KeyboardInterrupt:
+ return 130
+ finally:
+ server.server_close()
+ return 0
diff --git a/src/layers.py b/src/layers.py
new file mode 100644
index 0000000..0b19279
--- /dev/null
+++ b/src/layers.py
@@ -0,0 +1,334 @@
+"""Browser-ready views of saved captures: imagery and terrain tiles, and OSM as GeoJSON."""
+
+import math
+import struct
+import sys
+import threading
+import zlib
+from collections import OrderedDict, defaultdict
+from io import BytesIO
+from itertools import accumulate
+from xml.etree import ElementTree as ET
+
+from PIL import Image
+
+from . import terrain
+from .common import contained
+from .geo import collection, feature, ring_contains, signed_area
+
+CACHE_BYTES = 384 * 2**20
+OVERVIEWS = 6 # Zoom levels built below a grid's own zoom.
+
+AREA_TAGS = {
+ "building", "landuse", "amenity", "leisure", "boundary", "place", "shop",
+ "tourism", "historic", "public_transport", "office", "building:part", "military",
+ "ruins", "area:highway", "craft", "golf", "indoor",
+}
+AREA_VALUES = {
+ "highway": {"services", "rest_area", "escape", "elevator"},
+ "waterway": {"riverbank", "dock", "boatyard", "dam"},
+ "barrier": {"city_wall", "ditch", "hedge", "retaining_wall", "wall", "spikes"},
+ "railway": {"station", "turntable", "roundhouse", "platform"},
+ "power": {"plant", "substation", "generator", "transformer"},
+}
+LINE_VALUES = {
+ "natural": {"coastline", "cliff", "ridge", "arete", "tree_row"},
+ "man_made": {"cutline", "embankment", "pipeline"}, "aeroway": {"taxiway"},
+}
+TAGS = {"building", "landuse", "natural", "water", "leisure", "highway", "waterway", "name", "type"}
+MAJOR_ROADS = {"motorway", "trunk", "primary", "secondary", "tertiary"}
+PATHS = {"footway", "path", "cycleway", "steps", "pedestrian", "track", "bridleway", "corridor"}
+
+
+def saved(grid, count, z, x, y):
+ """One past the last saved grid tile inside tile z/x/y, or 0; downloads are row-major."""
+ factor = 2 ** (grid["zoom"] - z)
+ left = max(x * factor - grid["x0"], 0)
+ right = min((x + 1) * factor - grid["x0"], grid["columns"])
+ top = max(y * factor - grid["y0"], 0)
+ bottom = min((y + 1) * factor - grid["y0"], grid["rows"])
+ if left >= right or top >= bottom:
+ return 0
+ columns = grid["columns"]
+ row = min(bottom - 1, (count - 1) // columns)
+ end = min(right, count - row * columns)
+ if end <= left:
+ row, end = row - 1, right
+ return row * columns + end if row >= top else 0
+
+
+def unpredict(data, width):
+ """Undo the TIFF floating point predictor, giving big-endian Float32 rows."""
+ rows = bytearray()
+ for y in range(0, len(data), width * 4):
+ # Each row holds byte differences across four planes, most significant first.
+ planes = bytes(v & 255 for v in accumulate(data[y:y + width * 4]))
+ row = bytearray(width * 4)
+ for plane in range(4):
+ row[plane::4] = planes[plane * width:(plane + 1) * width]
+ rows += row
+ return bytes(rows)
+
+
+def undifference(data, width, order):
+ """Undo the TIFF horizontal predictor for 16-bit samples."""
+ fmt = f"{order}{width}H"
+ return b"".join(struct.pack(fmt, *(v & 0xFFFF for v in accumulate(struct.unpack(fmt, data[y:y + width * 2]))))
+ for y in range(0, len(data), width * 2))
+
+
+def heights(path):
+ """Decode one saved 512-pixel Int16 or Float32 terrain tile without libtiff."""
+ with path.open("rb") as stream:
+ source = terrain.TIFF(stream)
+ size = source.value(322)
+ per_row = 512 // size
+ image = Image.new("F", (512, 512))
+ for i, (offset, length) in enumerate(zip(source.values(324), source.values(325))):
+ data = source.read(offset, length)
+ if source.value(259) != 1:
+ data = zlib.decompress(data)
+ big = source.order == ">"
+ if source.value(317, 1) == 3:
+ data, big = unpredict(data, size), True
+ elif source.value(317, 1) == 2:
+ data = undifference(data, size, source.order)
+ mode, raw_mode = ("F", "F;32BF" if big else "F;32F") if source.float else ("I", "I;16BS" if big else "I;16S")
+ with (
+ Image.frombytes(mode, (size, size), data, "raw", raw_mode) as block,
+ block.convert("F") as values,
+ ):
+ image.paste(values, (i % per_row * size, i // per_row * size))
+ nodata = float(b"".join(source.values(42113)).rstrip(b"\0"))
+ # Terrarium has no NoData value. Unknown heights use sea level.
+ image.putdata([v if math.isfinite(v) and v != nodata else 0
+ for (v,) in struct.iter_unpack("=f", image.tobytes())])
+ return image
+
+
+def terrarium(image):
+ """Encode heights as RGB, where meters = R * 256 + G + B / 256 - 32768."""
+ with image.point(lambda h: h * 256 + 32768 * 256) as scaled, scaled.convert("I") as values:
+ # Native 32-bit integers hold the three channels below an unused high byte.
+ raw = "BGRX" if sys.byteorder == "little" else "XRGB"
+ return Image.frombytes("RGB", image.size, values.tobytes(), "raw", raw)
+
+
+def png(image):
+ with BytesIO() as buffer:
+ image.save(buffer, format="PNG", compress_level=1)
+ return buffer.getvalue()
+
+
+class Tiles:
+ """Satellite and terrain tiles; overviews merge four children and are cached by saved progress."""
+
+ def __init__(self):
+ self.cache = OrderedDict()
+ self.used = 0
+ self.lock = threading.Lock()
+
+ def get(self, folder, stage, z, x, y):
+ """Return (bytes, content type), or None where nothing is saved yet."""
+ grid = stage["grid"]
+ if not grid["zoom"] - OVERVIEWS <= z <= grid["zoom"] or not (0 <= x < 2**z and 0 <= y < 2**z):
+ return None
+ if stage["mode"] == "satellite" and z == grid["zoom"]:
+ # Saved patches are already browser images.
+ version = saved(grid, len(stage["results"]), z, x, y)
+ if not version:
+ return None
+ path = contained(folder, stage["results"][version - 1]["filename"])
+ return path.read_bytes(), "image/png" if path.suffix == ".png" else "image/jpeg"
+ image = self.image(folder, stage, z, x, y)
+ if image is None:
+ return None
+ if stage["mode"] == "terrain":
+ with terrarium(image) as rgb:
+ return png(rgb), "image/png"
+ return png(image), "image/png"
+
+ def image(self, folder, stage, z, x, y):
+ grid, results = stage["grid"], stage["results"]
+ version = saved(grid, len(results), z, x, y)
+ if not version:
+ return None
+ key = folder, stage["mode"], z, x, y
+ with self.lock:
+ entry = self.cache.get(key)
+ if entry and entry[0] == version:
+ self.cache.move_to_end(key)
+ return entry[1]
+ elevation = stage["mode"] == "terrain"
+ if z == grid["zoom"]:
+ path = contained(folder, results[version - 1]["filename"])
+ if elevation:
+ image = heights(path)
+ else:
+ with Image.open(path) as patch:
+ image = patch.convert("RGBA")
+ else:
+ size = 512 if elevation else 256
+ half = size // 2
+ image = Image.new("F" if elevation else "RGBA", (size, size))
+ missing, means = [], []
+ for dy in range(2):
+ for dx in range(2):
+ child = self.image(folder, stage, z + 1, 2 * x + dx, 2 * y + dy)
+ if child is None:
+ missing.append((dx * half, dy * half))
+ continue
+ with child.resize((half, half), Image.Resampling.BOX) as smaller:
+ image.paste(smaller, (dx * half, dy * half))
+ if elevation:
+ with smaller.resize((1, 1), Image.Resampling.BOX) as mean:
+ means.append(mean.getpixel((0, 0)))
+ # Sea level outside the grid would draw cliffs at its edges; use the tile's mean height.
+ for left, top in missing if means else ():
+ image.paste(sum(means) / len(means), (left, top, left + half, top + half))
+ with self.lock:
+ previous = self.cache.pop(key, None)
+ if previous:
+ self.used -= previous[1].width * previous[1].height * 4
+ self.cache[key] = version, image
+ self.used += image.width * image.height * 4
+ while self.used > CACHE_BYTES:
+ _, (_, dropped) = self.cache.popitem(last=False)
+ self.used -= dropped.width * dropped.height * 4
+ return image
+
+
+def is_area(tags):
+ if "area" in tags:
+ return tags["area"] != "no"
+ return (any(tags.get(key, "no") != "no" for key in AREA_TAGS)
+ or any(tags.get(key) in values for key, values in AREA_VALUES.items())
+ or any(key in tags and tags[key] != "no" and tags[key] not in values
+ for key, values in LINE_VALUES.items()))
+
+
+def properties(tags, polygon):
+ """Map styling class of an OSM object, or None when it is not drawn."""
+ if not polygon:
+ highway = tags.get("highway")
+ if highway:
+ road = "major" if highway.removesuffix("_link") in MAJOR_ROADS else "path" if highway in PATHS else "minor"
+ return dict(kind="road", road=road, name=tags.get("name"))
+ return dict(kind="waterway") if "waterway" in tags else None
+ if tags.get("building", "no") != "no":
+ return dict(kind="building", name=tags.get("name"))
+ if tags.get("natural") == "water" or "water" in tags or tags.get("landuse") == "reservoir":
+ return dict(kind="water")
+ if "landuse" in tags or "leisure" in tags or tags.get("natural") in ("wood", "grassland", "scrub", "heath"):
+ return dict(kind="land")
+ return None
+
+
+def objects(path):
+ """Stream complete OSM elements without retaining the XML tree."""
+ try:
+ with path.open("rb") as stream:
+ parser = ET.iterparse(stream, events=("start", "end"))
+ _, root = next(parser)
+ if root.tag != "osm":
+ raise ValueError("OSM file contains no osm root.")
+ for event, obj in parser:
+ if event == "end" and obj.tag in ("node", "way", "relation"):
+ yield obj
+ root.clear()
+ except (ET.ParseError, StopIteration) as error:
+ raise ValueError("OSM file contains invalid XML.") from error
+
+
+def read_osm(path):
+ nodes, ways, relations = {}, {}, []
+ for element in objects(path):
+ identity = int(element.attrib["id"])
+ if element.tag == "node":
+ nodes[identity] = [float(element.attrib["lon"]), float(element.attrib["lat"])]
+ else:
+ tags = {tag.attrib["k"]: tag.attrib["v"] for tag in element.findall("tag")}
+ area = is_area(tags)
+ tags = {key: value for key, value in tags.items() if key in TAGS}
+ if element.tag == "way":
+ refs = [int(nd.attrib["ref"]) for nd in element.findall("nd")]
+ ways[identity] = refs, tags, area
+ elif tags.get("type") in ("multipolygon", "boundary", "route", "waterway"):
+ members = [(int(m.attrib["ref"]), m.get("role", ""))
+ for m in element.findall("member") if m.get("type") == "way"]
+ relations.append((tags, members))
+ return nodes, ways, relations
+
+
+def rings(identities, ways, nodes):
+ pending = {identity: ways[identity][0] for identity in identities if identity in ways
+ and len(ways[identity][0]) >= 2 and all(n in nodes for n in ways[identity][0])}
+ ends = defaultdict(set)
+ for identity, refs in pending.items():
+ ends[refs[0]].add(identity)
+ ends[refs[-1]].add(identity)
+ while pending:
+ identity, refs = pending.popitem()
+ ring, used = list(refs), {identity}
+ while ring[0] != ring[-1]:
+ identity = next((i for i in ends[ring[-1]] if i in pending), None)
+ if identity is None:
+ break
+ refs = pending.pop(identity)
+ used.add(identity)
+ ring.extend(refs[1:] if refs[0] == ring[-1] else refs[-2::-1])
+ if len(ring) >= 4 and ring[0] == ring[-1]:
+ yield [nodes[n] for n in ring], used
+
+
+def osm(path):
+ """Buildings, roads, water, and land from a saved map.osm."""
+ nodes, ways, relations = read_osm(path)
+ features, consumed = [], set()
+ for tags, members in relations:
+ if tags["type"] in ("route", "waterway"):
+ props = properties(tags, False)
+ if not props:
+ continue
+ lines = [[nodes[n] for n in ways[ref][0]] for ref, _ in members if ref in ways
+ and len(ways[ref][0]) >= 2 and all(n in nodes for n in ways[ref][0])]
+ if lines:
+ features.append(feature("MultiLineString", lines, props))
+ continue
+ outers = [ref for ref, role in members if role in ("", "outer")]
+ # Older multipolygons can carry their area tags on a single outer way.
+ if len(outers) == 1 and outers[0] in ways and not properties(tags, True):
+ tags = dict(ways[outers[0]][1], **tags)
+ props = properties(tags, True)
+ if not props:
+ continue
+ polygons, used = [], set()
+ for ring, identities in rings(outers, ways, nodes):
+ if signed_area(ring) < 0:
+ ring.reverse()
+ polygons.append([ring])
+ used.update(identities)
+ for ring, identities in rings([ref for ref, role in members if role == "inner"], ways, nodes):
+ owners = [p for p in polygons if ring_contains(p[0], ring[0])]
+ if owners:
+ if signed_area(ring) > 0:
+ ring.reverse()
+ min(owners, key=lambda p: abs(signed_area(p[0]))).append(ring)
+ used.update(identities)
+ if polygons:
+ features.append(feature("MultiPolygon", polygons, props))
+ # Retain independently tagged members, but do not fill holes twice.
+ consumed.update(ref for ref in used if all(tags.get(k) == v
+ for k, v in ways[ref][1].items() if k != "type"))
+ for identity, (refs, tags, area) in ways.items():
+ if identity in consumed or len(refs) < 2 or any(n not in nodes for n in refs):
+ continue
+ polygon = area and len(refs) >= 4 and refs[0] == refs[-1]
+ props = properties(tags, polygon)
+ if props:
+ coordinates = [nodes[n] for n in refs]
+ if polygon and signed_area(coordinates) < 0:
+ coordinates.reverse()
+ features.append(feature("Polygon" if polygon else "LineString",
+ [coordinates] if polygon else coordinates, props))
+ return collection(features)
diff --git a/src/web/app.js b/src/web/app.js
new file mode 100644
index 0000000..264a712
--- /dev/null
+++ b/src/web/app.js
@@ -0,0 +1,1023 @@
+"use strict";
+
+const BASEMAP = "https://tiles.openfreemap.org/styles/positron";
+const EMPTY = {type: "FeatureCollection", features: []};
+const NAMES = {streetview: "Street View", satellite: "Satellite", osm: "OSM map", terrain: "Terrain", mesh: "3D mesh"};
+const STATES = {planned: "Planned", running: "Capturing", interrupted: "Interrupted", stopped: "Stopped",
+ failed: "Failed", complete: "Complete", unreadable: "Unreadable"};
+const NUMBERS = ["step", "fov", "sphere_zoom", "satellite_zoom", "terrain_zoom", "mesh_level", "delay",
+ "streetview_workers", "satellite_workers", "terrain_workers", "mesh_workers"];
+const EARTH = 6371008.8;
+// Progress phases that a capture stage row already shows.
+const DOWNLOADS = new Set(["Street View", "Satellite", "Downloading terrain tiles", "3D mesh"]);
+
+// Helpers
+
+const $ = (selector, root = document) => root.querySelector(selector);
+const $$ = (selector, root = document) => [...root.querySelectorAll(selector)];
+const esc = value => String(value ?? "").replace(/[&<>"']/g, c => `&#${c.charCodeAt(0)};`);
+const number = value => Math.round(value).toLocaleString("en-US");
+const plural = (count, one, many = `${one}s`) => `${number(count)} ${count === 1 ? one : many}`;
+const css = name => getComputedStyle(document.documentElement).getPropertyValue(name).trim();
+const absolute = path => location.origin + path;
+const capturePath = (id, path = "") => `/api/captures/${encodeURIComponent(id)}${path}`;
+
+const store = {
+ get(key, fallback) {
+ try { return JSON.parse(localStorage.getItem(`aleph:${key}`)) ?? fallback; } catch { return fallback; }
+ },
+ set(key, value) {
+ try { localStorage.setItem(`aleph:${key}`, JSON.stringify(value)); } catch { /* Private windows may refuse. */ }
+ },
+};
+
+async function api(path, body) {
+ const response = await fetch(path, body === undefined ? {} : {
+ method: "POST", headers: {"Content-Type": "application/json"}, body: JSON.stringify(body),
+ });
+ const data = await response.json().catch(() => null);
+ if (!response.ok) throw new Error(data?.error || `${response.status} ${response.statusText}`);
+ return data;
+}
+
+function duration(seconds) {
+ if (seconds < 60) return `${Math.max(1, Math.round(seconds))} s`;
+ const minutes = Math.round(seconds / 60);
+ return minutes < 60 ? `${minutes} min` : `${Math.floor(minutes / 60)} h ${minutes % 60} min`;
+}
+
+const meters = m => m >= 1000 ? `${(m / 1000).toFixed(m >= 10000 ? 0 : 1)} km` : `${Math.round(m)} m`;
+const resolution = m => `${m < 1 ? m.toFixed(2) : m.toFixed(1)} m/px`;
+const megabytes = bytes => bytes >= 1e9 ? `${(bytes / 1e9).toFixed(1)} GB` : bytes >= 1e6 ? `${(bytes / 1e6).toFixed(1)} MB`
+ : `${Math.max(1, Math.round(bytes / 1e3))} KB`;
+
+function distance([lat1, lon1], [lat2, lon2]) {
+ const r = Math.PI / 180;
+ const a = Math.sin((lat2 - lat1) * r / 2) ** 2 + Math.cos(lat1 * r) * Math.cos(lat2 * r) * Math.sin((lon2 - lon1) * r / 2) ** 2;
+ return 2 * EARTH * Math.asin(Math.sqrt(a));
+}
+
+function size([s, w, n, e]) {
+ const middle = (s + n) / 2;
+ return [distance([middle, w], [middle, e]), distance([s, w], [n, w])];
+}
+
+const dimensions = area => size(area).map(meters).join(" × ");
+const ring = ([s, w, n, e]) => [[w, s], [e, s], [e, n], [w, n], [w, s]];
+const polygon = (area, properties = {}) => ({type: "Feature", properties, geometry: {type: "Polygon", coordinates: [ring(area)]}});
+const point = (coordinates, properties = {}) => ({type: "Feature", properties, geometry: {type: "Point", coordinates}});
+const collection = features => ({type: "FeatureCollection", features});
+const lngLatBounds = ([s, w, n, e]) => [[w, s], [e, n]];
+
+function when(iso) {
+ const date = new Date(iso);
+ return `${date.toLocaleDateString(undefined, {day: "numeric", month: "short", year: "numeric"})} · ${
+ date.toLocaleTimeString(undefined, {hour: "2-digit", minute: "2-digit"})}`;
+}
+
+function destination([lon, lat], heading, length) {
+ const r = Math.PI / 180, d = length / EARTH, h = heading * r, phi = lat * r;
+ const phi2 = Math.asin(Math.sin(phi) * Math.cos(d) + Math.cos(phi) * Math.sin(d) * Math.cos(h));
+ const lambda = lon * r + Math.atan2(Math.sin(h) * Math.sin(d) * Math.cos(phi), Math.cos(d) - Math.sin(phi) * Math.sin(phi2));
+ return [lambda / r, phi2 / r];
+}
+
+// State
+
+const state = {
+ config: null,
+ captures: [],
+ job: null,
+ view: null,
+ area: store.get("area", null),
+ drawing: false,
+ drag: null,
+ preview: null,
+ planError: null,
+ captureId: null,
+ capture: null,
+ photos: [],
+ photoCount: 0,
+ photoLoading: false,
+ photoAgain: false,
+ live: {},
+ selected: null,
+ search: [],
+ toggles: {photos: true, route: true, satellite: true, terrain: true, buildings: true, roads: true, water: true,
+ outline: true, basemap: true, ...store.get("toggles", {})},
+};
+
+let map;
+let basemapLayers = [];
+const themed = new Map(); // Layer id → paint with CSS variable names, resolved per color scheme.
+
+// Map styling
+
+// Replace "--name" strings, including inside expressions, with the current CSS value.
+const resolve = paint => JSON.parse(JSON.stringify(paint), (key, value) =>
+ typeof value === "string" && value.startsWith("--") ? css(value) : value);
+
+function tint(layer) {
+ const source = layer["source-layer"] || "";
+ if (layer.type === "background") return {"background-color": "--paper"};
+ if (layer.type === "fill") {
+ if (source === "water") return {"fill-color": "--map-water"};
+ if (source === "building") return {"fill-color": "--map-building", "fill-outline-color": "--map-building-line"};
+ return {"fill-color": "--map-land"};
+ }
+ if (layer.type === "line") {
+ if (source === "waterway") return {"line-color": "--map-water"};
+ if (source === "boundary") return {"line-color": "--map-boundary"};
+ if (layer.id.includes("rail")) return {"line-color": "--map-rail"};
+ return {"line-color": layer.id.includes("casing") ? "--map-casing" : "--map-road"};
+ }
+ if (layer.type === "symbol") return {"text-color": "--map-label", "text-halo-color": "--paper"};
+ return {};
+}
+
+async function basemap() {
+ try {
+ const style = await (await fetch(BASEMAP)).json();
+ // Shields and icons would bring color back; keep the map to paper and ink.
+ style.layers = style.layers.filter(layer => !(layer.type === "symbol" && layer.layout?.["icon-image"]));
+ for (const layer of style.layers) {
+ themed.set(layer.id, tint(layer));
+ layer.paint = {...layer.paint, ...resolve(tint(layer))};
+ }
+ basemapLayers = style.layers.map(layer => layer.id);
+ return style;
+ } catch {
+ // Offline: saved captures still display on plain paper.
+ themed.set("background", {"background-color": "--paper"});
+ basemapLayers = ["background"];
+ return {version: 8, sources: {}, layers: [{id: "background", type: "background", paint: resolve({"background-color": "--paper"})}]};
+ }
+}
+
+const is = (key, value) => ["==", ["get", key], value];
+const hover = (on, off) => ["case", ["boolean", ["feature-state", "hover"], false], on, off];
+const grow = (low, high) => ["interpolate", ["linear"], ["zoom"], 14, low, 19, high];
+
+const OVERLAYS = [
+ {id: "osm-land", source: "osm", type: "fill", filter: is("kind", "land"), paint: {"fill-color": "--ink", "fill-opacity": 0.05}},
+ {id: "osm-water", source: "osm", type: "fill", filter: is("kind", "water"), paint: {"fill-color": "--ink", "fill-opacity": 0.14}},
+ {id: "osm-waterways", source: "osm", type: "line", filter: is("kind", "waterway"),
+ paint: {"line-color": "--ink", "line-opacity": 0.4, "line-width": 1}},
+ {id: "osm-buildings", source: "osm", type: "fill", filter: is("kind", "building"), paint: {"fill-color": "--ink", "fill-opacity": 0.14}},
+ {id: "osm-building-lines", source: "osm", type: "line", filter: is("kind", "building"),
+ paint: {"line-color": "--ink", "line-opacity": 0.7, "line-width": 0.75}},
+ {id: "osm-paths", source: "osm", type: "line", filter: ["all", is("kind", "road"), is("road", "path")],
+ paint: {"line-color": "--ink", "line-opacity": 0.6, "line-width": 1, "line-dasharray": [2, 1.5]}},
+ {id: "osm-roads", source: "osm", type: "line", filter: ["all", is("kind", "road"), ["!=", ["get", "road"], "path"]],
+ layout: {"line-cap": "round", "line-join": "round"},
+ paint: {"line-color": "--ink", "line-opacity": 0.75, "line-width": ["interpolate", ["linear"], ["zoom"],
+ 13, ["match", ["get", "road"], "major", 1.2, 0.6], 18, ["match", ["get", "road"], "major", 4, 2]]}},
+ {id: "bounds", source: "bounds", type: "line", paint: {"line-color": "--ink", "line-width": 1, "line-dasharray": [4, 3]}},
+ {id: "plan-grid", source: "plan", type: "line", filter: is("kind", "satellite"),
+ paint: {"line-color": "--ink", "line-opacity": 0.3, "line-width": 0.5}},
+ {id: "plan-terrain", source: "plan", type: "line", filter: is("kind", "terrain"),
+ paint: {"line-color": "--muted", "line-width": 1, "line-dasharray": [2, 2]}},
+ {id: "plan-paths", source: "plan", type: "line", filter: is("kind", "path"), layout: {"line-cap": "round", "line-join": "round"},
+ paint: {"line-color": "--muted", "line-opacity": 0.6, "line-width": 2}},
+ {id: "route-paths", source: "plan", type: "line", filter: is("kind", "path"), layout: {"line-cap": "round", "line-join": "round"},
+ paint: {"line-color": "--muted", "line-opacity": 0.35, "line-width": 1.5}},
+ {id: "plan-gaps", source: "plan", type: "line", filter: is("kind", "gap"),
+ paint: {"line-color": "--accent", "line-width": 2, "line-dasharray": [1, 1.5]}},
+ {id: "plan-stops", source: "plan", type: "circle", filter: is("kind", "stop"),
+ paint: {"circle-radius": grow(1.5, 4), "circle-color": "--accent"}},
+ {id: "route-stops", source: "plan", type: "circle", filter: is("kind", "stop"),
+ paint: {"circle-radius": grow(1.5, 4.5), "circle-color": "--paper", "circle-stroke-color": "--muted", "circle-stroke-width": 1}},
+ {id: "photos", source: "photos", type: "circle",
+ paint: {"circle-radius": grow(2, 5.5), "circle-color": "--ink", "circle-stroke-color": "--paper", "circle-stroke-width": 1.5}},
+ {id: "selected-view", source: "selected", type: "line", filter: ["==", ["geometry-type"], "LineString"],
+ layout: {"line-cap": "round"}, paint: {"line-color": "--accent", "line-width": 2.5}},
+ {id: "selected", source: "selected", type: "circle", filter: ["==", ["geometry-type"], "Point"],
+ paint: {"circle-radius": 6, "circle-color": "--accent", "circle-stroke-color": "--paper", "circle-stroke-width": 2}},
+ {id: "outlines-fill", source: "outlines", type: "fill", paint: {"fill-color": "--accent", "fill-opacity": hover(0.08, 0)}},
+ {id: "outlines", source: "outlines", type: "line", paint: {"line-color": hover("--accent", "--ink"), "line-width": hover(2, 1)}},
+ {id: "area-fill", source: "area", type: "fill", paint: {"fill-color": "--accent", "fill-opacity": 0.07}},
+ {id: "area-line", source: "area", type: "line", paint: {"line-color": "--accent", "line-width": 1.5}},
+ {id: "corners", source: "corners", type: "symbol",
+ layout: {"icon-image": "corner", "icon-allow-overlap": true, "icon-ignore-placement": true}},
+];
+
+// Result layers each toggle shows.
+const GROUPS = {
+ photos: ["photos", "selected", "selected-view"],
+ route: ["route-paths", "route-stops"],
+ satellite: ["satellite"],
+ terrain: ["hillshade"],
+ buildings: ["osm-buildings", "osm-building-lines"],
+ roads: ["osm-roads", "osm-paths"],
+ water: ["osm-land", "osm-water", "osm-waterways"],
+ outline: ["bounds"],
+};
+
+function addLayer(layer, before) {
+ themed.set(layer.id, layer.paint || {});
+ map.addLayer({...layer, paint: resolve(layer.paint || {})}, before);
+}
+
+function cornerImage() {
+ const canvas = document.createElement("canvas");
+ canvas.width = canvas.height = 20;
+ const context = canvas.getContext("2d");
+ context.fillStyle = css("--accent");
+ context.fillRect(0, 0, 20, 20);
+ context.fillStyle = css("--paper");
+ context.fillRect(3, 3, 14, 14);
+ return context.getImageData(0, 0, 20, 20);
+}
+
+function applyTheme() {
+ for (const [id, paint] of themed) {
+ if (!map.getLayer(id)) continue;
+ for (const [key, value] of Object.entries(resolve(paint))) map.setPaintProperty(id, key, value);
+ }
+ map.updateImage("corner", cornerImage());
+}
+
+function visibleLayers() {
+ const on = new Set();
+ const add = (...ids) => ids.forEach(id => on.add(id));
+ if (state.view === "library") add("outlines", "outlines-fill");
+ if (state.view === "new" || state.view === "preview") add("area-fill", "area-line");
+ if (state.view === "new" && state.area && !state.drawing) add("corners");
+ if (state.view === "preview" && state.preview) add("plan-grid", "plan-terrain", "plan-paths", "plan-gaps", "plan-stops");
+ if (state.view === "capture") {
+ for (const [group, ids] of Object.entries(GROUPS)) if (state.toggles[group]) add(...ids);
+ }
+ return on;
+}
+
+function syncMap() {
+ if (!map?.getLayer("corners")) return;
+ const on = visibleLayers();
+ for (const id of [...OVERLAYS.map(layer => layer.id), "satellite", "hillshade"]) {
+ if (map.getLayer(id)) map.setLayoutProperty(id, "visibility", on.has(id) ? "visible" : "none");
+ }
+ const base = state.view !== "capture" || state.toggles.basemap;
+ for (const id of basemapLayers) {
+ if (id !== "background" && map.getLayer(id)) map.setLayoutProperty(id, "visibility", base ? "visible" : "none");
+ }
+}
+
+function setData(source, data) {
+ map.getSource(source)?.setData(data);
+}
+
+// Rasters are added once a capture has saved tiles; their URLs carry the saved count.
+function setRaster(mode, info) {
+ const tiles = [absolute(capturePath(state.capture.id, `/${mode}/{z}/{x}/{y}?v=${info.done}`))];
+ const source = map.getSource(mode);
+ if (source) return source.setTiles(tiles);
+ const [s, w, n, e] = state.capture.bounds;
+ const spec = {tiles, bounds: [w, s, e, n], minzoom: Math.max(0, info.zoom - state.config.overviews), maxzoom: info.zoom};
+ if (mode === "satellite") {
+ map.addSource(mode, {type: "raster", tileSize: 256, ...spec});
+ addLayer({id: "satellite", type: "raster", source: mode, paint: {"raster-fade-duration": 0}}, "osm-land");
+ } else {
+ map.addSource(mode, {type: "raster-dem", encoding: "terrarium", tileSize: 512, ...spec});
+ addLayer({id: "hillshade", type: "hillshade", source: mode, paint: {
+ "hillshade-shadow-color": "--hill-shadow", "hillshade-highlight-color": "--hill-light",
+ "hillshade-accent-color": "--hill-shadow", "hillshade-exaggeration": 0.55}}, "osm-land");
+ }
+ syncMap();
+}
+
+function clearCaptureLayers() {
+ for (const [layer, source] of [["satellite", "satellite"], ["hillshade", "terrain"]]) {
+ if (map.getLayer(layer)) map.removeLayer(layer);
+ if (map.getSource(source)) map.removeSource(source);
+ themed.delete(layer);
+ }
+ for (const source of ["osm", "photos", "selected", "bounds", "plan"]) setData(source, EMPTY);
+ Object.assign(state, {photos: [], photoCount: 0, photoAgain: false, live: {}, selected: null});
+ $("#viewer").hidden = true;
+}
+
+// Area drawing
+
+function setArea(area) {
+ state.area = area;
+ setData("area", area ? collection([polygon(area)]) : EMPTY);
+ setData("corners", area ? collection(ring(area).slice(0, 4).map(c => point(c))) : EMPTY);
+ renderArea();
+}
+
+function areaFrom(a, b) {
+ const clampLat = value => Math.max(-85.05, Math.min(85.05, value));
+ const clampLon = value => Math.max(-180, Math.min(180, value));
+ return [clampLat(Math.min(a.lat, b.lat)), clampLon(Math.min(a.lng, b.lng)),
+ clampLat(Math.max(a.lat, b.lat)), clampLon(Math.max(a.lng, b.lng))];
+}
+
+function cornerAt(pixel) {
+ if (!state.area) return null;
+ const corners = ring(state.area).slice(0, 4);
+ const index = corners.findIndex(corner => {
+ const p = map.project(corner);
+ return Math.abs(p.x - pixel.x) <= 9 && Math.abs(p.y - pixel.y) <= 9;
+ });
+ if (index < 0) return null;
+ const [lng, lat] = corners[(index + 2) % 4];
+ return {index, anchor: {lng, lat}};
+}
+
+function setDrawing(on) {
+ state.drawing = on;
+ $("#hint").hidden = !on;
+ map.getCanvas().style.cursor = on ? "crosshair" : "";
+ renderArea();
+ syncMap();
+}
+
+function startDrag(event) {
+ if (state.view !== "new" || event.originalEvent.button !== 0) return;
+ const corner = state.drawing ? null : cornerAt(event.point);
+ if (!state.drawing && !corner) return;
+ event.preventDefault(); // Keeps the map from panning.
+ state.drag = {anchor: corner ? corner.anchor : event.lngLat, previous: state.area};
+}
+
+function moveDrag(event) {
+ if (state.drag) return setArea(areaFrom(state.drag.anchor, event.lngLat));
+ if (state.view === "new" && !state.drawing) {
+ const corner = cornerAt(event.point);
+ map.getCanvas().style.cursor = corner ? (corner.index % 2 ? "nwse-resize" : "nesw-resize") : "";
+ }
+}
+
+function endDrag() {
+ if (!state.drag) return;
+ const {previous} = state.drag;
+ state.drag = null;
+ const [width, height] = state.area ? size(state.area) : [0, 0];
+ if (width < 5 || height < 5) {
+ setArea(previous); // A click, not a drag.
+ return;
+ }
+ store.set("area", state.area);
+ setDrawing(false);
+ estimate();
+}
+
+// Settings
+
+function fillForm(options) {
+ for (const input of $("#settings").elements) {
+ const name = input.name;
+ if (!name) continue;
+ if (name === "include") input.checked = options.include.includes(input.value);
+ else if (name === "camera") input.checked = (input.value === "sphere") === options.full_sphere;
+ else if (input.type === "radio") input.checked = String(options[name]) === input.value;
+ else if (name in options) input.value = options[name];
+ }
+ updateForm();
+}
+
+function readForm() {
+ const data = new FormData($("#settings"));
+ const options = {include: data.getAll("include"), full_sphere: data.get("camera") === "sphere", depth: data.get("depth"),
+ streetview_format: data.get("streetview_format"), satellite_format: data.get("satellite_format")};
+ for (const name of NUMBERS) options[name] = Number(data.get(name));
+ return options;
+}
+
+function updateForm() {
+ const options = readForm();
+ for (const fieldset of $$(".source")) fieldset.classList.toggle("on", options.include.includes(fieldset.dataset.source));
+ for (const field of $$("[data-camera]")) field.hidden = (field.dataset.camera === "sphere") !== options.full_sphere;
+ const labels = {satellite_zoom: z => `z${z}`, terrain_zoom: z => `z${z}`, mesh_level: level => level,
+ sphere_zoom: z => `${number(512 * 2 ** z)} px`};
+ for (const output of $$("output[data-for]")) output.textContent = labels[output.dataset.for](options[output.dataset.for]);
+ $("#preview-button").disabled = !state.area || !options.include.length;
+ store.set("options", options);
+}
+
+let estimateTimer = null;
+let estimateCount = 0;
+
+function estimate() {
+ clearTimeout(estimateTimer);
+ estimateTimer = setTimeout(async () => {
+ const count = ++estimateCount;
+ const {include, satellite_zoom, terrain_zoom, satellite_workers, terrain_workers, delay} = readForm();
+ const outputs = {satellite: $("[data-source=satellite] .estimate"), osm: $("[data-source=osm] .estimate")};
+ const details = {satellite: $("[data-detail=satellite]"), terrain: $("[data-detail=terrain]")};
+ let result = {};
+ if (state.area && (include.includes("satellite") || include.includes("osm"))) {
+ try {
+ result = await api("/api/estimate", {bounds: state.area, options:
+ {include, satellite_zoom, terrain_zoom, satellite_workers, terrain_workers, delay}});
+ } catch {
+ // Invalid values are reported by Preview.
+ }
+ }
+ if (count !== estimateCount) return;
+ const {satellite, terrain} = result;
+ outputs.satellite.textContent = satellite ? `${plural(satellite.tiles, "tile")} · ~${duration(satellite.seconds)}` : "";
+ details.satellite.textContent = satellite
+ ? `${resolution(satellite.meters_per_pixel)} · ${number(satellite.width)} × ${number(satellite.height)} px` : "";
+ outputs.osm.textContent = terrain ? `${plural(terrain.tiles, "terrain tile")}` : "";
+ details.terrain.textContent = terrain ? `${resolution(terrain.meters_per_pixel)} elevation` : "";
+ }, 120);
+}
+
+function renderArea() {
+ const area = state.area;
+ $("#area-empty").hidden = !!area;
+ $("#area-set").hidden = !area;
+ const redraw = $("#redraw");
+ redraw.hidden = false;
+ redraw.textContent = state.drawing ? "Cancel drawing" : area ? "Redraw" : "Draw area";
+ if (area) {
+ const [width, height] = size(area);
+ $("#area-size").textContent = dimensions(area);
+ $("#area-km").textContent = `${(width * height / 1e6).toFixed(width * height < 1e5 ? 3 : 2)} km²`;
+ $("#area-coordinates").textContent = `S ${area[0].toFixed(5)} W ${area[1].toFixed(5)}\nN ${area[2].toFixed(5)} E ${area[3].toFixed(5)}`;
+ }
+ $("#area-empty").textContent = state.drawing ? "Drag on the map to draw a rectangle." : "No area yet.";
+ $("#preview-button").disabled = !area || !readForm().include.length;
+}
+
+// Progress
+
+function renderProgress(container, job) {
+ const bar = $(".bar", container);
+ const known = job.total != null && job.total > 0;
+ bar.classList.toggle("indeterminate", !known);
+ $("i", bar).style.width = known ? `${Math.min(100, job.done / job.total * 100)}%` : "";
+ let amount = "";
+ if (job.unit === "bytes") amount = `${(job.done / 1e6).toFixed(1)}${job.total ? ` / ${(job.total / 1e6).toFixed(1)}` : ""} MB`;
+ else if (known) amount = `${number(job.done)} / ${number(job.total)}`;
+ else if (job.done) amount = number(job.done);
+ $(".progress-text", container).innerHTML =
+ `<span>${esc(job.stopping ? "Stopping…" : job.phase)}</span><span>${esc(amount)}</span>`;
+}
+
+const running = (kind, id) => {
+ const job = state.job;
+ return job?.state === "running" && job.kind === kind && (id === undefined || job.capture === id);
+};
+
+// Library
+
+async function loadCaptures() {
+ try {
+ state.captures = await api("/api/captures");
+ } catch (error) {
+ $("#captures").innerHTML = `<li class="empty error">${esc(error.message)}</li>`;
+ return;
+ }
+ setData("outlines", collection(state.captures.filter(c => c.bounds).map(c => polygon(c.bounds, {id: c.id}))));
+ renderLibrary();
+}
+
+function renderLibrary() {
+ const list = $("#captures");
+ $("#capture-count").textContent = state.captures.length || "";
+ if (!state.captures.length) {
+ list.innerHTML = `<li class="empty">No captures here yet.</li>`;
+ return;
+ }
+ list.innerHTML = state.captures.map(c => {
+ if (!c.bounds) {
+ return `<li><div class="capture"><span class="when">${esc(c.id)}</span><span class="state failed">${STATES[c.state]}</span>
+ <span class="detail">${esc(c.error)}</span></div></li>`;
+ }
+ const live = running("capture", c.id);
+ const bar = live ? `<span class="bar"><i style="width:${libraryProgress()}%"></i></span>` : "";
+ const status = live ? "running" : c.state;
+ return `<li><button type="button" class="capture" data-id="${esc(c.id)}">
+ <span class="when">${esc(when(c.started_at))}</span><span class="state ${status}">${STATES[status]}</span>
+ <span class="detail">${esc(dimensions(c.bounds))} · ${esc(c.options.include.map(s => NAMES[s]).join(", "))}</span>${bar}
+ </button></li>`;
+ }).join("");
+}
+
+function libraryProgress() {
+ const stages = Object.values(state.job.stages);
+ return (stages.reduce((sum, stage) => sum + stage.done / Math.max(1, stage.total), 0) / stages.length * 100).toFixed(1);
+}
+
+function hoverCapture(id) {
+ for (const button of $$(".capture[data-id]")) button.classList.toggle("hover", button.dataset.id === id);
+ if (state.hovered === id) return;
+ if (state.hovered) map.setFeatureState({source: "outlines", id: state.hovered}, {hover: false});
+ if (id) map.setFeatureState({source: "outlines", id}, {hover: true});
+ state.hovered = id;
+}
+
+// Preview
+
+const stageRows = {
+ streetview: s => ["stops", plural(s.photos, s.sphere ? "sphere" : "photo"), !s.meters ? "No mapped roads at this depth"
+ : !s.stops ? "No panoramas on the selected roads"
+ : `${plural(s.stops, "stop")} along ${meters(s.meters)} of road` + (s.gaps ? ` · ${plural(s.gaps, "spacing gap")}` : "")],
+ satellite: s => ["grid", plural(s.tiles, "tile"), `${number(s.width)} × ${number(s.height)} px · ${resolution(s.meters_per_pixel)}`],
+ osm: () => ["solid", "1 extract", "Clipped from a Geofabrik regional file"],
+ terrain: s => ["dashed", plural(s.tiles, "tile"), `Zoom ${s.zoom} · ${resolution(s.meters_per_pixel)}`],
+ mesh: s => ["cube", plural(s.nodes, "node"), `Detail level ${s.level}`],
+};
+
+function renderPreview() {
+ const job = state.job;
+ const planning = running("plan");
+ $("#planning").hidden = !planning;
+ if (planning) renderProgress($("#planning .progress"), job);
+ $("#cancel-plan").hidden = !planning;
+ $("#cancel-plan").disabled = !!job?.stopping;
+ $("#plan").hidden = !state.preview;
+ $("#start").hidden = !state.preview;
+ $("#plan-error").hidden = !state.planError;
+ $("#plan-error").textContent = state.planError || "";
+ if (!state.preview) return;
+ $("#plan-stages").innerHTML = Object.entries(state.preview.stages).map(([mode, info]) => {
+ const [swatch, value, detail] = stageRows[mode](info);
+ return `<li><i class="swatch ${swatch}"></i><strong>${NAMES[mode]}</strong><span class="value">${esc(value)}</span>
+ <span class="detail">${esc(detail)}</span></li>`;
+ }).join("");
+ $("#plan-time").textContent = `~ ${duration(state.preview.seconds)}`;
+}
+
+async function previewPlan(event) {
+ event.preventDefault();
+ const error = $("#settings-error");
+ error.hidden = true;
+ if (!state.area) return;
+ Object.assign(state, {preview: null, planError: null});
+ setData("plan", EMPTY);
+ try {
+ state.job = await api("/api/plan", {bounds: state.area, options: readForm()});
+ } catch (failure) {
+ error.textContent = failure.message;
+ error.hidden = false;
+ return;
+ }
+ location.hash = "#/preview";
+ poll();
+}
+
+function showPlan() {
+ setData("plan", state.preview.layers);
+ map.fitBounds(lngLatBounds(state.preview.bounds), {padding: 80, maxZoom: 18, duration: 600});
+ syncMap();
+}
+
+// Capture
+
+async function openCapture(id) {
+ let detail;
+ try {
+ detail = await api(capturePath(id));
+ } catch (error) {
+ if (state.captureId !== id) return;
+ $("#capture-title").textContent = "Capture";
+ $("#capture-error").textContent = error.message;
+ $("#capture-error").hidden = false;
+ return;
+ }
+ if (state.view !== "capture" || state.captureId !== id) return;
+ const first = state.capture?.id !== id;
+ state.capture = detail;
+ if (first) {
+ setData("bounds", collection([polygon(detail.bounds)]));
+ setData("plan", absolute(capturePath(id, "/plan")));
+ map.fitBounds(lngLatBounds(detail.bounds), {padding: 60, maxZoom: 18, duration: 600});
+ }
+ refresh(detail.stages, true);
+ renderCapture();
+ syncMap();
+}
+
+// Bring map data up to the saved counts; imagery reloads at most every few seconds while it grows.
+function refresh(stages, force = false) {
+ const id = state.capture.id, live = state.live;
+ if (stages.streetview && stages.streetview.done !== live.streetview) {
+ live.streetview = stages.streetview.done;
+ loadPhotos();
+ }
+ for (const mode of ["satellite", "terrain"]) {
+ const info = stages[mode];
+ if (!info?.done || info.done === live[mode]) continue;
+ if (!force && info.done < info.total && Date.now() - (live[`${mode}At`] || 0) < 2500) continue;
+ live[mode] = info.done;
+ live[`${mode}At`] = Date.now();
+ setRaster(mode, {...info, zoom: info.zoom ?? state.capture.stages[mode].zoom});
+ }
+ if (stages.osm?.done && !live.osm) {
+ live.osm = true;
+ setData("osm", absolute(capturePath(id, "/osm")));
+ }
+}
+
+async function loadPhotos() {
+ if (state.photoLoading) {
+ state.photoAgain = true;
+ return;
+ }
+ const id = state.capture.id;
+ state.photoLoading = true;
+ try {
+ const data = await api(capturePath(id, `/photos?after=${state.photoCount}`));
+ if (state.capture?.id !== id) return;
+ state.photoCount = data.count;
+ state.photos.push(...data.features);
+ setData("photos", collection(state.photos));
+ renderLayers();
+ } catch {
+ // The next progress update retries.
+ } finally {
+ state.photoLoading = false;
+ if (state.photoAgain && state.capture?.id === id) {
+ state.photoAgain = false;
+ loadPhotos();
+ }
+ }
+}
+
+function renderCapture() {
+ const c = state.capture;
+ if (!c) return;
+ const job = state.job;
+ const live = running("capture", c.id);
+ const status = live ? "running" : c.state;
+ $("#capture-title").textContent = when(c.started_at);
+ $("#capture-meta").textContent = `${STATES[status]} · ${dimensions(c.bounds)}`;
+ $("#progress").hidden = !live;
+ if (live) {
+ $("#phase").hidden = DOWNLOADS.has(job.phase) && !job.stopping;
+ renderProgress($("#phase"), job);
+ const downloading = Object.values(job.stages).some(stage => stage.done < stage.total);
+ $("#progress .label").textContent = downloading ? `Capturing · about ${duration(job.seconds)} left` : "Building files";
+ $("#progress-stages").innerHTML = Object.entries(job.stages).map(([mode, s]) => {
+ const finished = s.done >= s.total;
+ return `<li class="${finished ? "done" : ""}"><span>${NAMES[mode]}</span>
+ <span class="value">${finished ? "Done" : `${number(s.done)} / ${number(s.total)}`}</span>
+ <span class="bar"><i style="width:${(s.done / Math.max(1, s.total) * 100).toFixed(1)}%"></i></span></li>`;
+ }).join("");
+ }
+ // Stopping on request is not an error worth showing.
+ const error = !live && c.error && c.state !== "complete" && c.error !== "Interrupted";
+ $("#capture-error").hidden = !error;
+ $("#capture-error").textContent = error ? c.error : "";
+ $("#stop").hidden = !live;
+ $("#stop").disabled = !!job?.stopping;
+ $("#stop").textContent = job?.stopping ? "Stopping…" : "Stop";
+ $("#resume").hidden = live || c.state === "complete";
+ $("#resume").disabled = running("plan") || running("capture");
+ $("#folder").textContent = c.folder;
+ $("#files").innerHTML = Object.entries(c.files).map(([name, bytes]) =>
+ `<li><span>${esc(name)}</span><span class="value">${megabytes(bytes)}</span></li>`).join("")
+ || `<li class="muted">No merged files yet.</li>`;
+ renderLayers();
+}
+
+function renderLayers() {
+ const c = state.capture;
+ if (!c) return;
+ const s = c.stages;
+ const toggle = (key, name, value = "", disabled = false) => `<label class="toggle">
+ <input type="checkbox" data-toggle="${key}" ${state.toggles[key] ? "checked" : ""} ${disabled ? "disabled" : ""}>
+ <span>${name}</span><span class="value">${esc(value)}</span></label>`;
+ const groups = [];
+ if (s.streetview) {
+ const skipped = s.streetview.skipped ? ` · ${number(s.streetview.skipped)} skipped` : "";
+ groups.push(["Street View", toggle("photos", "Photos", `${number(state.photos.length)}${skipped}`)
+ + toggle("route", "Planned route")]);
+ }
+ if (s.satellite) {
+ groups.push(["Satellite", toggle("satellite", "Imagery", `z${s.satellite.zoom} · ${tileCount("satellite")}`)]);
+ }
+ if (s.osm) {
+ const saved = state.live.osm || s.osm.done;
+ const note = saved ? "" : "not saved";
+ groups.push(["OSM map", toggle("buildings", "Buildings", note, !saved) + toggle("roads", "Roads and paths", note, !saved)
+ + toggle("water", "Water and land", note, !saved)]);
+ }
+ if (s.terrain) groups.push(["Terrain", toggle("terrain", "Hillshade", `z${s.terrain.zoom} · ${tileCount("terrain")}`)]);
+ if (s.mesh) {
+ const glb = c.files["mesh.glb"];
+ groups.push(["3D mesh", `<p class="toggle"><i class="swatch cube"></i><span>mesh.glb</span><span class="value">${
+ glb ? megabytes(glb) : `${number(s.mesh.done)} / ${plural(s.mesh.total, "node")}`}</span></p>`]);
+ }
+ groups.push(["Map", toggle("outline", "Capture outline") + toggle("basemap", "Basemap")]);
+ $("#layers").innerHTML = groups.map(([name, rows]) => `<li class="group"><p>${name}</p>${rows}</li>`).join("");
+}
+
+function tileCount(mode) {
+ const stage = state.capture.stages[mode];
+ const done = state.live[mode] ?? stage.done;
+ return done >= stage.total ? plural(stage.total, "tile") : `${number(done)} / ${plural(stage.total, "tile")}`;
+}
+
+// Photo viewer
+
+function showPhoto(index) {
+ const photo = state.photos[index];
+ if (!photo) return;
+ state.selected = index;
+ const p = photo.properties;
+ const image = $("#viewer-image");
+ image.src = absolute(capturePath(state.capture.id, `/files/${p.filename.split("/").map(encodeURIComponent).join("/")}`));
+ image.classList.toggle("sphere", p.heading == null);
+ const facts = [`#${p.sequence}`, p.side ?? "360°", p.heading != null ? `${Math.round(p.heading)}°` : null, p.imagery_date];
+ $("#viewer-text").innerHTML = `<strong>${esc(p.path_name || "Unnamed road")}</strong><span>${esc(facts.filter(Boolean).join(" · "))}</span>`;
+ $("#viewer-link").href = p.streetview_url;
+ $("#viewer-prev").disabled = index === 0;
+ $("#viewer-next").disabled = index === state.photos.length - 1;
+ $("#viewer").hidden = false;
+ const at = photo.geometry.coordinates;
+ const features = [point(at)];
+ if (p.heading != null) features.unshift({type: "Feature", properties: {},
+ geometry: {type: "LineString", coordinates: [at, destination(at, p.heading, 18)]}});
+ setData("selected", collection(features));
+ if (!map.getBounds().contains(at)) map.easeTo({center: at});
+}
+
+function closeViewer() {
+ $("#viewer").hidden = true;
+ state.selected = null;
+ setData("selected", EMPTY);
+}
+
+// Jobs
+
+let pollTimer = null;
+
+async function poll() {
+ clearTimeout(pollTimer);
+ let job;
+ try {
+ job = await api("/api/job");
+ } catch {
+ pollTimer = setTimeout(poll, 3000);
+ return;
+ }
+ const previous = state.job;
+ state.job = job;
+ const finished = job && job.state !== "running" && previous?.id === job.id && previous.state === "running";
+ if (job?.kind === "plan" && finished) {
+ if (job.state === "done") {
+ try {
+ state.preview = await api("/api/preview");
+ if (state.view === "preview") showPlan();
+ } catch (error) {
+ state.planError = error.message;
+ }
+ } else if (job.state === "failed") {
+ state.planError = job.error;
+ } else if (state.view === "preview") {
+ location.hash = "#/new";
+ }
+ }
+ if (state.view === "preview") renderPreview();
+ if (job?.kind === "capture" && state.capture?.id === job.capture && state.view === "capture") {
+ if (finished) {
+ await openCapture(job.capture);
+ } else {
+ refresh(job.stages);
+ renderCapture();
+ }
+ }
+ if (state.view === "library") {
+ const bar = job?.kind === "capture" && $(`.capture[data-id="${CSS.escape(job.capture)}"] .bar i`);
+ if (finished || (running("capture") && !bar)) loadCaptures();
+ else if (bar) bar.style.width = `${libraryProgress()}%`;
+ }
+ if (job?.state === "running") pollTimer = setTimeout(poll, 700);
+}
+
+// Views
+
+function show(view) {
+ for (const section of $$(".view")) section.hidden = section.id !== view;
+ if (view !== "new" && state.drawing) setDrawing(false);
+ if (view !== "capture" && state.captureId) {
+ clearCaptureLayers();
+ state.capture = state.captureId = null;
+ }
+ state.view = view;
+ if (map.getCanvas().style.cursor !== "crosshair") map.getCanvas().style.cursor = "";
+ syncMap();
+}
+
+function route() {
+ const [, view, id] = (location.hash.slice(1) || "/").split("/");
+ if (view === "new") {
+ show("new");
+ renderArea();
+ estimate();
+ if (!state.area) setDrawing(true);
+ } else if (view === "preview") {
+ if (!state.preview && !running("plan")) {
+ location.replace("#/new");
+ return;
+ }
+ show("preview");
+ renderPreview();
+ if (state.preview) showPlan();
+ } else if (view === "capture" && id) {
+ const captureId = decodeURIComponent(id);
+ if (state.captureId !== captureId) {
+ show("capture");
+ clearCaptureLayers();
+ state.captureId = captureId;
+ state.capture = null;
+ $("#capture-title").textContent = "";
+ $("#capture-meta").textContent = "";
+ $("#layers").innerHTML = "";
+ $("#files").innerHTML = "";
+ $("#capture-error").hidden = true;
+ $("#progress").hidden = true;
+ }
+ openCapture(captureId);
+ } else {
+ show("library");
+ loadCaptures();
+ }
+}
+
+// Events
+
+function bind() {
+ $("#settings").addEventListener("input", () => {
+ updateForm();
+ estimate();
+ });
+ $("#settings").addEventListener("submit", previewPlan);
+ $("#redraw").addEventListener("click", () => setDrawing(!state.drawing));
+
+ $("#preview-back").addEventListener("click", async () => {
+ if (running("plan")) await api("/api/stop", {}).catch(() => null);
+ location.hash = "#/new";
+ });
+ $("#cancel-plan").addEventListener("click", async () => {
+ state.job = await api("/api/stop", {}).catch(() => state.job);
+ renderPreview();
+ });
+ $("#start").addEventListener("click", async () => {
+ $("#start").disabled = true;
+ try {
+ state.job = await api("/api/capture", {plan: state.preview.plan});
+ state.preview = null;
+ location.hash = `#/capture/${encodeURIComponent(state.job.capture)}`;
+ poll();
+ } catch (error) {
+ state.planError = error.message;
+ renderPreview();
+ } finally {
+ $("#start").disabled = false;
+ }
+ });
+
+ $("#captures").addEventListener("click", event => {
+ const button = event.target.closest(".capture[data-id]");
+ if (button) location.hash = `#/capture/${encodeURIComponent(button.dataset.id)}`;
+ });
+ $("#captures").addEventListener("mouseover", event => hoverCapture(event.target.closest(".capture[data-id]")?.dataset.id ?? null));
+ $("#captures").addEventListener("mouseleave", () => hoverCapture(null));
+
+ $("#layers").addEventListener("change", event => {
+ const key = event.target.dataset.toggle;
+ if (!key) return;
+ state.toggles[key] = event.target.checked;
+ store.set("toggles", state.toggles);
+ if (key === "photos" && !event.target.checked) closeViewer();
+ syncMap();
+ });
+ $("#stop").addEventListener("click", async () => {
+ state.job = await api("/api/stop", {}).catch(() => state.job);
+ renderCapture();
+ });
+ $("#resume").addEventListener("click", async () => {
+ try {
+ state.job = await api(capturePath(state.capture.id, "/resume"), {});
+ renderCapture();
+ poll();
+ } catch (error) {
+ $("#capture-error").textContent = error.message;
+ $("#capture-error").hidden = false;
+ }
+ });
+ $("#copy-folder").addEventListener("click", async event => {
+ try {
+ await navigator.clipboard.writeText(state.capture.folder);
+ event.target.textContent = "Copied";
+ setTimeout(() => { event.target.textContent = "Copy path"; }, 1500);
+ } catch { /* Clipboard access can be refused. */ }
+ });
+
+ $("#viewer-prev").addEventListener("click", () => showPhoto(state.selected - 1));
+ $("#viewer-next").addEventListener("click", () => showPhoto(state.selected + 1));
+ $("#viewer-close").addEventListener("click", closeViewer);
+
+ const search = $("#search"), results = $("#search-results");
+ search.addEventListener("submit", async event => {
+ event.preventDefault();
+ const query = search.q.value.trim();
+ if (!query) return;
+ results.hidden = false;
+ results.innerHTML = `<li class="note">Searching…</li>`;
+ try {
+ state.search = await api(`/api/search?q=${encodeURIComponent(query)}`);
+ results.innerHTML = state.search.map((place, i) => `<li><button type="button" data-index="${i}">${esc(place.name)}
+ <span class="detail">${esc(place.label.split(", ").slice(1).join(", "))}</span></button></li>`).join("")
+ || `<li class="note">No places found.</li>`;
+ } catch (error) {
+ results.innerHTML = `<li class="note">${esc(error.message)}</li>`;
+ }
+ });
+ results.addEventListener("click", event => {
+ const place = state.search[event.target.closest("[data-index]")?.dataset.index];
+ if (!place) return;
+ results.hidden = true;
+ map.flyTo({center: [place.lon, place.lat], zoom: 16});
+ });
+ search.q.addEventListener("input", () => { if (!search.q.value) results.hidden = true; });
+
+ document.addEventListener("keydown", event => {
+ if (event.target.matches("input, select, textarea") && event.key !== "Escape") return;
+ if (event.key === "Escape") {
+ if (state.drawing && !state.drag) setDrawing(false);
+ else if (!results.hidden) results.hidden = true;
+ else if (!$("#viewer").hidden) closeViewer();
+ } else if (!$("#viewer").hidden && (event.key === "ArrowLeft" || event.key === "ArrowRight")) {
+ showPhoto(state.selected + (event.key === "ArrowLeft" ? -1 : 1));
+ }
+ });
+ window.addEventListener("hashchange", route);
+ window.addEventListener("mouseup", endDrag);
+ matchMedia("(prefers-color-scheme: dark)").addEventListener("change", applyTheme);
+}
+
+function bindMap() {
+ map.on("mousedown", startDrag);
+ map.on("mousemove", moveDrag);
+ map.on("mouseup", endDrag);
+ map.on("click", "photos", event => {
+ const sequence = event.features[0].properties.sequence;
+ showPhoto(state.photos.findIndex(photo => photo.properties.sequence === sequence));
+ });
+ map.on("click", "outlines-fill", event => {
+ location.hash = `#/capture/${encodeURIComponent(event.features[0].properties.id)}`;
+ });
+ map.on("mousemove", "outlines-fill", event => hoverCapture(event.features[0].properties.id));
+ map.on("mouseleave", "outlines-fill", () => hoverCapture(null));
+ for (const layer of ["photos", "outlines-fill"]) {
+ map.on("mouseenter", layer, () => { if (!state.drawing) map.getCanvas().style.cursor = "pointer"; });
+ map.on("mouseleave", layer, () => { if (!state.drawing) map.getCanvas().style.cursor = ""; });
+ }
+ map.on("moveend", () => store.set("view", {center: map.getCenter().toArray(), zoom: map.getZoom()}));
+ map.on("error", event => {
+ // Tiles not saved yet are expected while a capture runs.
+ if (event.sourceId === "satellite" || event.sourceId === "terrain") return;
+ console.warn(event.error);
+ });
+}
+
+async function init() {
+ state.config = await api("/api/config");
+ $("#root").textContent = state.config.root;
+ $("#root").title = state.config.root;
+ fillForm({...state.config.defaults, ...store.get("options", {})});
+
+ const view = store.get("view", {center: [12.49, 41.89], zoom: 2});
+ map = new maplibregl.Map({container: "map", style: await basemap(), center: view.center, zoom: view.zoom,
+ attributionControl: {compact: true}, dragRotate: false, pitchWithRotate: false});
+ map.touchZoomRotate.disableRotation();
+ map.addControl(new maplibregl.NavigationControl({showCompass: false}), "top-right");
+ map.addControl(new maplibregl.ScaleControl({unit: "metric"}), "bottom-left");
+ await map.once("load");
+
+ map.addImage("corner", cornerImage(), {pixelRatio: 2});
+ for (const source of ["osm", "bounds", "plan", "photos", "selected", "area", "corners"]) {
+ map.addSource(source, {type: "geojson", data: EMPTY});
+ }
+ map.addSource("outlines", {type: "geojson", data: EMPTY, promoteId: "id"});
+ for (const layer of OVERLAYS) addLayer(layer);
+ bindMap();
+ bind();
+ setArea(state.area);
+
+ state.job = await api("/api/job").catch(() => null);
+ if (state.job?.kind === "plan" && state.job.state === "done") state.preview = await api("/api/preview").catch(() => null);
+ if (running("plan") && !location.hash.startsWith("#/preview")) location.hash = "#/preview";
+ if (running("capture") && !location.hash.startsWith("#/capture")) location.hash = `#/capture/${encodeURIComponent(state.job.capture)}`;
+ route();
+ if (state.job?.state === "running") poll();
+ if (!store.get("view", null) && state.view === "library") {
+ await loadCaptures();
+ const bounds = state.captures.filter(c => c.bounds).map(c => c.bounds);
+ if (bounds.length) {
+ map.fitBounds(lngLatBounds([Math.min(...bounds.map(b => b[0])), Math.min(...bounds.map(b => b[1])),
+ Math.max(...bounds.map(b => b[2])), Math.max(...bounds.map(b => b[3]))]),
+ {padding: 80, maxZoom: 16, duration: 0});
+ }
+ }
+}
+
+init().catch(error => {
+ document.body.insertAdjacentHTML("afterbegin", `<p class="error fatal">Aleph could not start: ${esc(error.message)}</p>`);
+});
diff --git a/src/web/index.html b/src/web/index.html
new file mode 100644
index 0000000..d09fd19
--- /dev/null
+++ b/src/web/index.html
@@ -0,0 +1,233 @@
+<!doctype html>
+<html lang="en">
+<head>
+ <meta charset="utf-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1">
+ <title>Aleph</title>
+ <link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3E%3Ccircle cx='8' cy='8' r='7.5' fill='%23F8F1E5' stroke='%2334302B'/%3E%3Cpath d='M6 1c-1 3 2 5 1 7s2 4 3 7' stroke='%23FF4938' stroke-width='2' fill='none'/%3E%3C/svg%3E">
+ <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=IM+Fell+English&display=swap">
+ <link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/maplibre-gl.css">
+ <link rel="stylesheet" href="/style.css">
+ <script defer src="https://unpkg.com/[email protected]/dist/maplibre-gl.js"></script>
+ <script defer src="/app.js"></script>
+</head>
+<body>
+ <aside class="panel">
+ <header class="brand">
+ <a href="#/" aria-label="Aleph, all captures">
+ <svg class="logo" viewBox="4 4 88 88" aria-hidden="true">
+ <defs><clipPath id="logo-world"><circle cx="48" cy="48" r="36"/></clipPath></defs>
+ <g clip-path="url(#logo-world)">
+ <circle cx="48" cy="48" r="36" class="logo-paper"/>
+ <g class="logo-lines" fill="none" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5">
+ <path d="M7 30.2C12.4 26.3 17.8 24.1 22.1 24.7 26.6 24.9 28.6 27.5 29.7 31.1 31.2 35.3 29.2 39.8 27.5 44.1 25.6 48 25.1 51.2 26.3 54.5 28.2 59.1 32.8 62.1 34.4 67 36 71 35 74.8 33.9 79.1L30.1 89"/>
+ <path d="M5 43.3C9.2 39.2 13.5 36.8 16.2 37.7 19.6 38.2 20.1 40.7 19.7 43.2 19.8 47.3 17.5 51.1 17.7 56 17.4 60 18.9 63.3 21.4 66.5 24.3 70.3 27 73.1 26.1 77.7 25.9 80.2 24.2 82.2 22.8 84.2"/>
+ <path d="M5 60.3C8.2 57.4 11.1 58.7 12.1 62.2 13.9 65.6 13.4 70.3 11.8 74"/>
+ <path d="M53.8 8C56.1 15.1 57.3 23.2 59.8 30.1 62.2 37.4 64.4 43.9 68.9 49.8 74.2 57.1 80.4 62.1 89.2 67.3"/>
+ <path d="M71.1 12C71.5 18.3 73 23.9 74.7 29.4 76.9 35.1 81.4 39.7 85.2 43.2L91.1 47"/>
+ <path d="M43 26.2C49.4 27.2 55 26.5 61.2 25.8 67.3 25.4 72.3 24.1 77.2 25.3 80.3 25.5 82.3 27.3 85 28.1"/>
+ <path d="M47 44.2C52.4 44.8 58.5 43.7 63.2 42.4 69.1 40.9 73.4 38.3 78.7 38.1 82.2 37.6 85.7 39.6 89 40.9"/>
+ <path d="M55 60.2C60.1 60.8 64.7 59.1 68.6 57.1 73.4 55 77.1 53 82 53.1L88 53.3"/>
+ <path d="M41.8 86C40.9 81.3 42.4 77.2 45.6 76 48.2 74.4 51.3 75.4 54.2 78.2 57.5 81 60.5 82 64.2 81.5 66.2 81.5 68.3 80 70 78.8"/>
+ </g>
+ <path class="logo-river" d="M35.8 7.5C32.6 12.2 33.2 16.4 34.6 20.2 36 24.1 39.2 27.4 40.8 31.7 42.5 36 39.6 41.2 37.7 46.6 35.5 52.8 39.1 58.6 45.3 61.9 51.1 65.5 55.6 66.8 59.2 71.3 62.4 75.6 59.1 81.9 54.4 85.2L59.8 89C66.1 82 68.6 76.7 64.4 69.7 61.1 64.1 54.7 61.4 50.8 59.3 46.1 56.6 42 54.4 43.1 49.9 44.6 44.7 48 38.9 47 33.9 46.7 28.6 42.6 24.8 40.5 20.3 38.7 16.7 39.4 13.4 42 10.2Z"/>
+ </g>
+ <circle cx="48" cy="48" r="36" class="logo-rim"/>
+ </svg>
+ <span>Aleph</span>
+ </a>
+ </header>
+
+ <!-- Library -->
+ <section id="library" class="view" hidden>
+ <div class="scroll">
+ <div class="heading">
+ <h1>Captures <span id="capture-count" class="count"></span></h1>
+ </div>
+ <ol id="captures" class="captures"></ol>
+ </div>
+ <footer class="actions">
+ <p class="root" title="Captures folder"><span class="label">Folder</span><code id="root"></code></p>
+ <a class="button primary wide" href="#/new">New capture</a>
+ </footer>
+ </section>
+
+ <!-- New capture: area, sources, settings -->
+ <section id="new" class="view" hidden>
+ <form id="settings" class="scroll" novalidate autocomplete="off">
+ <div class="heading">
+ <a class="back" href="#/">← Captures</a>
+ <h1>New capture</h1>
+ </div>
+
+ <section class="block">
+ <h2 class="label">Area</h2>
+ <div id="area" class="area">
+ <p id="area-empty" class="muted">Drag on the map to draw a rectangle.</p>
+ <div id="area-set" hidden>
+ <p class="area-size"><strong id="area-size"></strong> <span id="area-km" class="muted"></span></p>
+ <p id="area-coordinates" class="coordinates"></p>
+ </div>
+ </div>
+ <button id="redraw" type="button" class="small" hidden>Redraw</button>
+ </section>
+
+ <section class="block">
+ <h2 class="label">Sources</h2>
+
+ <fieldset class="source" data-source="streetview">
+ <label class="source-head"><input type="checkbox" name="include" value="streetview"><span>Street View</span><output class="estimate"></output></label>
+ <div class="fields">
+ <label class="field"><span>Roads</span>
+ <span class="segmented">
+ <label><input type="radio" name="depth" value="main"><span>Main</span></label>
+ <label><input type="radio" name="depth" value="roads"><span>Roads</span></label>
+ <label><input type="radio" name="depth" value="all"><span>All paths</span></label>
+ </span>
+ </label>
+ <label class="field"><span>Spacing</span><span class="unit"><input type="number" name="step" min="1" step="any"><i>m</i></span></label>
+ <label class="field"><span>Camera</span>
+ <span class="segmented">
+ <label><input type="radio" name="camera" value="sides"><span>Left + right</span></label>
+ <label><input type="radio" name="camera" value="sphere"><span>360° sphere</span></label>
+ </span>
+ </label>
+ <label class="field" data-camera="sides"><span>Field of view</span><span class="unit"><input type="number" name="fov" min="5" max="175" step="1"><i>°</i></span></label>
+ <label class="field" data-camera="sphere"><span>Resolution</span><span class="range"><input type="range" name="sphere_zoom" min="0" max="5" step="1"><output data-for="sphere_zoom"></output></span></label>
+ <label class="field"><span>Format</span>
+ <span class="segmented">
+ <label><input type="radio" name="streetview_format" value="jpg"><span>JPG</span></label>
+ <label><input type="radio" name="streetview_format" value="png"><span>PNG</span></label>
+ </span>
+ </label>
+ <label class="field"><span>Parallel requests</span><input type="number" name="streetview_workers" min="1" max="64" step="1"></label>
+ </div>
+ </fieldset>
+
+ <fieldset class="source" data-source="satellite">
+ <label class="source-head"><input type="checkbox" name="include" value="satellite"><span>Satellite</span><output class="estimate"></output></label>
+ <div class="fields">
+ <label class="field"><span>Zoom</span><span class="range"><input type="range" name="satellite_zoom" min="12" max="21" step="1"><output data-for="satellite_zoom"></output></span></label>
+ <p class="detail" data-detail="satellite"></p>
+ <label class="field"><span>Tile format</span>
+ <span class="segmented">
+ <label><input type="radio" name="satellite_format" value="jpg"><span>JPG</span></label>
+ <label><input type="radio" name="satellite_format" value="png"><span>PNG</span></label>
+ </span>
+ </label>
+ <label class="field"><span>Parallel requests</span><input type="number" name="satellite_workers" min="1" max="64" step="1"></label>
+ </div>
+ </fieldset>
+
+ <fieldset class="source" data-source="osm">
+ <label class="source-head"><input type="checkbox" name="include" value="osm"><span>OSM map + terrain</span><output class="estimate"></output></label>
+ <div class="fields">
+ <p class="detail">OpenStreetMap data clipped to the area, and elevation tiles.</p>
+ <label class="field"><span>Terrain zoom</span><span class="range"><input type="range" name="terrain_zoom" min="8" max="14" step="1"><output data-for="terrain_zoom"></output></span></label>
+ <p class="detail" data-detail="terrain"></p>
+ <label class="field"><span>Parallel requests</span><input type="number" name="terrain_workers" min="1" max="64" step="1"></label>
+ </div>
+ </fieldset>
+
+ <fieldset class="source" data-source="mesh">
+ <label class="source-head"><input type="checkbox" name="include" value="mesh"><span>3D mesh</span><output class="estimate"></output></label>
+ <div class="fields">
+ <p class="detail">Google Earth photogrammetry, saved as mesh.glb.</p>
+ <label class="field"><span>Detail level</span><span class="range"><input type="range" name="mesh_level" min="14" max="22" step="1"><output data-for="mesh_level"></output></span></label>
+ <label class="field"><span>Parallel requests</span><input type="number" name="mesh_workers" min="1" max="64" step="1"></label>
+ </div>
+ </fieldset>
+ </section>
+
+ <details class="block advanced">
+ <summary class="label">Advanced</summary>
+ <label class="field"><span>Pause between requests</span><span class="unit"><input type="number" name="delay" min="0" step="any"><i>s</i></span></label>
+ <p class="detail">A pause also makes requests sequential.</p>
+ </details>
+ </form>
+ <footer class="actions">
+ <p id="settings-error" class="error" hidden></p>
+ <button id="preview-button" class="primary wide" type="submit" form="settings" disabled>Preview</button>
+ </footer>
+ </section>
+
+ <!-- Preview of a planned capture -->
+ <section id="preview" class="view" hidden>
+ <div class="scroll">
+ <div class="heading">
+ <button id="preview-back" type="button" class="back">← Settings</button>
+ <h1>Preview</h1>
+ </div>
+ <div id="planning" class="block" hidden>
+ <p class="label">Planning</p>
+ <div class="progress"><div class="bar"><i></i></div><p class="progress-text"></p></div>
+ </div>
+ <div id="plan" hidden>
+ <ul id="plan-stages" class="stages"></ul>
+ <div class="block total">
+ <p class="label">Estimated time</p>
+ <p id="plan-time" class="big"></p>
+ <p class="detail">Excludes the first download of a regional OSM file and building the final files.</p>
+ </div>
+ </div>
+ <p id="plan-error" class="error" hidden></p>
+ </div>
+ <footer class="actions">
+ <button id="cancel-plan" type="button" class="wide" hidden>Cancel</button>
+ <button id="start" type="button" class="accent wide" hidden>Start capture</button>
+ </footer>
+ </section>
+
+ <!-- One capture: live progress and results -->
+ <section id="capture" class="view" hidden>
+ <div class="scroll">
+ <div class="heading">
+ <a class="back" href="#/">← Captures</a>
+ <h1 id="capture-title"></h1>
+ <p id="capture-meta" class="meta"></p>
+ </div>
+ <div id="progress" class="block" hidden>
+ <p class="label">Capturing</p>
+ <ul id="progress-stages" class="stages compact"></ul>
+ <div id="phase" class="progress"><div class="bar"><i></i></div><p class="progress-text"></p></div>
+ </div>
+ <p id="capture-error" class="error" hidden></p>
+ <div class="block">
+ <h2 class="label">Layers</h2>
+ <ul id="layers" class="layers"></ul>
+ </div>
+ <div class="block">
+ <h2 class="label">Files</h2>
+ <ul id="files" class="files"></ul>
+ <p class="root"><code id="folder"></code><button id="copy-folder" type="button" class="small">Copy path</button></p>
+ </div>
+ </div>
+ <footer class="actions">
+ <button id="stop" type="button" class="wide" hidden>Stop</button>
+ <button id="resume" type="button" class="primary wide" hidden>Resume capture</button>
+ </footer>
+ </section>
+ </aside>
+
+ <main class="stage">
+ <div id="map"></div>
+ <form id="search" class="search" role="search">
+ <input type="search" name="q" placeholder="Search places" aria-label="Search places" autocomplete="off">
+ <ol id="search-results" hidden></ol>
+ </form>
+ <p id="hint" class="hint" hidden>Drag to draw the capture area · Esc to pan instead</p>
+ <figure id="viewer" class="viewer" hidden>
+ <img id="viewer-image" alt="">
+ <figcaption>
+ <div id="viewer-text"></div>
+ <div class="viewer-actions">
+ <button id="viewer-prev" type="button" class="small" aria-label="Previous photo">←</button>
+ <button id="viewer-next" type="button" class="small" aria-label="Next photo">→</button>
+ <a id="viewer-link" class="button small" target="_blank" rel="noopener">Google Maps ↗</a>
+ <button id="viewer-close" type="button" class="small" aria-label="Close">×</button>
+ </div>
+ </figcaption>
+ </figure>
+ </main>
+</body>
+</html>
diff --git a/src/web/style.css b/src/web/style.css
new file mode 100644
index 0000000..91364f7
--- /dev/null
+++ b/src/web/style.css
@@ -0,0 +1,440 @@
+:root {
+ --paper: #f8f1e5;
+ --surface: #fcf8f1;
+ --ink: #34302b;
+ --muted: #776d60;
+ --line: #ddd3c2;
+ --accent: #ff4938;
+ --on-accent: #fff;
+
+ /* Basemap */
+ --map-water: #e6dfd1;
+ --map-land: #efe7d8;
+ --map-building: #ebe2d2;
+ --map-building-line: #ddd2bf;
+ --map-road: #fffbf4;
+ --map-casing: #e2d8c6;
+ --map-rail: #d3c8b5;
+ --map-boundary: #c9bda9;
+ --map-label: #8a7f70;
+ --hill-shadow: #34302b;
+ --hill-light: #ffffff;
+
+ --serif: "IM Fell English", Georgia, serif;
+ --sans: ui-sans-serif, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif;
+ --mono: ui-monospace, "SF Mono", Menlo, Consolas, monospace;
+ color-scheme: light;
+}
+
+@media (prefers-color-scheme: dark) {
+ :root {
+ --paper: #1b1b18;
+ --surface: #22221e;
+ --ink: #f3eee3;
+ --muted: #a0978a;
+ --line: #36352f;
+ --accent: #ff5a48;
+ --on-accent: #1b1b18;
+
+ --map-water: #121210;
+ --map-land: #1f1f1b;
+ --map-building: #25241f;
+ --map-building-line: #2f2d28;
+ --map-road: #2e2d28;
+ --map-casing: #24231f;
+ --map-rail: #3a3832;
+ --map-boundary: #4a463f;
+ --map-label: #8f877a;
+ --hill-shadow: #000000;
+ --hill-light: #f3eee3;
+ color-scheme: dark;
+ }
+}
+
+* { box-sizing: border-box; }
+[hidden] { display: none !important; }
+
+html, body { height: 100%; margin: 0; }
+
+body {
+ display: flex;
+ background: var(--paper);
+ color: var(--ink);
+ font: 13px/1.45 var(--sans);
+ -webkit-font-smoothing: antialiased;
+}
+
+h1, h2, p, ol, ul, figure { margin: 0; }
+ol, ul { padding: 0; list-style: none; }
+a { color: inherit; }
+code { font: 11px/1.4 var(--mono); }
+
+/* Panel */
+
+.panel {
+ display: flex;
+ flex-direction: column;
+ width: 360px;
+ flex: none;
+ border-right: 1px solid var(--ink);
+ background: var(--paper);
+ min-height: 0;
+}
+
+.brand {
+ padding: 14px 20px;
+ border-bottom: 1px solid var(--ink);
+}
+.brand a {
+ display: inline-flex;
+ align-items: center;
+ gap: 10px;
+ text-decoration: none;
+ font: 26px/1 var(--serif);
+}
+.logo { width: 30px; height: 30px; }
+.logo-paper { fill: var(--paper); }
+.logo-lines { stroke: var(--ink); }
+.logo-river { fill: var(--accent); }
+.logo-rim { fill: none; stroke: var(--ink); stroke-width: 1.5; }
+
+.view { display: flex; flex-direction: column; flex: 1; min-height: 0; }
+.scroll { flex: 1; overflow-y: auto; padding: 0 20px 24px; }
+
+.heading { padding: 20px 0 6px; }
+h1 { font: 30px/1.1 var(--serif); font-weight: normal; }
+.count { color: var(--muted); font: 13px var(--mono); vertical-align: middle; }
+.meta { margin-top: 6px; color: var(--muted); }
+.back {
+ display: inline-block;
+ margin-bottom: 10px;
+ padding: 0;
+ border: 0;
+ background: none;
+ color: var(--muted);
+ font: 12px var(--sans);
+ text-decoration: none;
+ cursor: pointer;
+}
+.back:hover { color: var(--ink); background: none; }
+
+.label {
+ display: block;
+ color: var(--muted);
+ font: 10.5px/1.4 var(--mono);
+ letter-spacing: .08em;
+ text-transform: uppercase;
+}
+
+.block { padding: 16px 0; border-top: 1px solid var(--line); }
+.heading + .block, .heading + #planning { border-top: 0; }
+.block > .label { margin-bottom: 10px; }
+
+.muted { color: var(--muted); }
+.detail { color: var(--muted); font-size: 12px; }
+.error {
+ padding: 8px 10px;
+ border-left: 2px solid var(--accent);
+ background: var(--surface);
+ white-space: pre-wrap;
+ overflow-wrap: anywhere;
+}
+.big { font: 300 32px/1.15 var(--sans); letter-spacing: -.02em; margin-bottom: 6px; }
+
+.actions {
+ display: flex;
+ flex-direction: column;
+ gap: 10px;
+ padding: 14px 20px;
+ border-top: 1px solid var(--ink);
+}
+.actions:not(:has(> :not([hidden]))) { display: none; }
+
+.root { display: flex; align-items: baseline; gap: 8px; min-width: 0; }
+.root code { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--muted); direction: rtl; text-align: left; }
+.root .label { flex: none; }
+
+/* Controls */
+
+button, .button {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ gap: 6px;
+ padding: 9px 14px;
+ border: 1px solid var(--ink);
+ border-radius: 0;
+ background: transparent;
+ color: var(--ink);
+ font: 500 13px var(--sans);
+ text-decoration: none;
+ cursor: pointer;
+}
+button:hover, .button:hover { background: var(--ink); color: var(--paper); }
+button:disabled { opacity: .35; cursor: default; }
+button:disabled:hover { background: transparent; color: var(--ink); }
+.primary { background: var(--ink); color: var(--paper); }
+.primary:hover { background: var(--paper); color: var(--ink); }
+.primary:disabled:hover { background: var(--ink); color: var(--paper); }
+.accent { background: var(--accent); border-color: var(--accent); color: var(--on-accent); }
+.accent:hover { background: var(--ink); border-color: var(--ink); color: var(--paper); }
+.small { padding: 3px 8px; font-size: 12px; }
+.wide { width: 100%; }
+:focus-visible { outline: 2px solid var(--accent); outline-offset: 1px; }
+
+input[type=number], input[type=search] {
+ width: 76px;
+ padding: 4px 6px;
+ border: 1px solid var(--line);
+ border-radius: 0;
+ background: var(--surface);
+ color: var(--ink);
+ font: 12px var(--mono);
+ text-align: right;
+}
+input[type=number]:hover, input[type=search]:hover { border-color: var(--muted); }
+input[type=number]:focus, input[type=search]:focus { border-color: var(--ink); outline: none; }
+
+input[type=checkbox] {
+ appearance: none;
+ flex: none;
+ width: 13px;
+ height: 13px;
+ margin: 0;
+ border: 1px solid var(--ink);
+ background: transparent;
+ cursor: pointer;
+}
+input[type=checkbox]:checked { background: var(--ink); box-shadow: inset 0 0 0 2px var(--paper); }
+
+input[type=range] {
+ appearance: none;
+ flex: 1;
+ height: 16px;
+ margin: 0;
+ background: transparent;
+ cursor: pointer;
+}
+input[type=range]::-webkit-slider-runnable-track { height: 1px; background: var(--ink); }
+input[type=range]::-moz-range-track { height: 1px; background: var(--ink); }
+input[type=range]::-webkit-slider-thumb { appearance: none; width: 8px; height: 16px; margin-top: -7.5px; border: 0; background: var(--ink); }
+input[type=range]::-moz-range-thumb { width: 8px; height: 16px; border: 0; border-radius: 0; background: var(--ink); }
+
+.segmented { display: inline-flex; }
+.segmented label { position: relative; cursor: pointer; }
+.segmented input { position: absolute; opacity: 0; pointer-events: none; }
+.segmented span {
+ display: block;
+ padding: 3px 8px;
+ border: 1px solid var(--line);
+ margin-left: -1px;
+ font-size: 12px;
+ white-space: nowrap;
+}
+.segmented label:first-child span { margin-left: 0; }
+.segmented label:hover span { border-color: var(--muted); position: relative; }
+.segmented input:checked + span { position: relative; border-color: var(--ink); background: var(--ink); color: var(--paper); }
+.segmented input:focus-visible + span { outline: 2px solid var(--accent); }
+
+.unit { display: inline-flex; align-items: center; gap: 4px; }
+.unit i { color: var(--muted); font: 12px var(--mono); font-style: normal; width: 10px; }
+.range { display: flex; align-items: center; gap: 10px; width: 170px; }
+.range output { min-width: 26px; font: 12px var(--mono); text-align: right; }
+
+/* Area and sources */
+
+.area-size strong { font: 500 20px/1.2 var(--sans); letter-spacing: -.01em; }
+.coordinates { margin-top: 4px; color: var(--muted); font: 11px/1.5 var(--mono); white-space: pre; }
+#redraw { margin-top: 10px; }
+
+.source { margin: 0; padding: 0; border: 0; border-top: 1px solid var(--line); min-width: 0; }
+.source:first-of-type { border-top: 0; }
+.source-head {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ padding: 10px 0;
+ font-weight: 600;
+ cursor: pointer;
+}
+.estimate { margin-left: auto; color: var(--muted); font: 400 11px var(--mono); }
+.source .fields { display: none; padding: 0 0 14px 23px; }
+.source.on .fields { display: grid; gap: 9px; }
+
+.field {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 12px;
+ min-height: 26px;
+}
+.field > span:first-child { color: var(--muted); }
+.advanced summary { cursor: pointer; list-style: none; }
+.advanced summary::before { content: "+ "; }
+.advanced[open] summary::before { content: "− "; }
+.advanced[open] summary { margin-bottom: 10px; }
+.advanced .detail { margin-top: 4px; }
+
+/* Plan and progress */
+
+.stages li {
+ display: grid;
+ grid-template-columns: 14px 1fr auto;
+ gap: 2px 10px;
+ align-items: baseline;
+ padding: 11px 0;
+ border-top: 1px solid var(--line);
+}
+.stages li:first-child { border-top: 0; }
+.stages strong { font-weight: 600; }
+.stages .value { font: 12px var(--mono); text-align: right; }
+.stages .detail { grid-column: 2 / 4; }
+.stages.compact li { padding: 7px 0; grid-template-columns: 1fr auto; }
+.stages.compact .bar { grid-column: 1 / 3; height: 2px; }
+.stages.compact .done .bar i { background: var(--muted); }
+
+.swatch { width: 12px; height: 12px; align-self: center; }
+.swatch.stops { background: radial-gradient(circle, var(--accent) 3px, transparent 3.5px); }
+.swatch.grid {
+ border: 1px solid var(--muted);
+ background: linear-gradient(var(--muted), var(--muted)) center / 1px 100% no-repeat,
+ linear-gradient(var(--muted), var(--muted)) center / 100% 1px no-repeat;
+}
+.swatch.dashed { border: 1px dashed var(--muted); }
+.swatch.solid { border: 1px solid var(--muted); }
+.swatch.cube { border: 1px solid var(--muted); box-shadow: 3px -3px 0 -1px var(--paper), 3px -3px 0 0 var(--muted); }
+
+.bar { height: 4px; background: var(--line); overflow: hidden; }
+.bar i { display: block; height: 100%; width: 0; background: var(--accent); transition: width .3s; }
+.bar.indeterminate i { width: 30%; animation: slide 1.2s ease-in-out infinite; }
+@keyframes slide { from { transform: translateX(-100%); } to { transform: translateX(340%); } }
+.progress-text { display: flex; justify-content: space-between; gap: 12px; margin-top: 8px; }
+.progress-text span:last-child { color: var(--muted); font: 12px var(--mono); }
+#phase { margin-top: 12px; }
+.done { color: var(--muted); }
+
+/* Library */
+
+.captures li { border-top: 1px solid var(--line); }
+.captures li:first-child { border-top: 0; }
+.capture {
+ display: grid;
+ grid-template-columns: 1fr auto;
+ gap: 3px 12px;
+ width: 100%;
+ padding: 12px 0;
+ border: 0;
+ background: none;
+ text-align: left;
+ font-weight: 400;
+}
+.capture:hover, .capture:focus-visible, .capture.hover { background: none; color: var(--ink); }
+.capture:hover .when, .capture.hover .when { text-decoration: underline; text-underline-offset: 3px; }
+.when { font: 17px/1.25 var(--serif); }
+.state { font: 10.5px var(--mono); letter-spacing: .08em; text-transform: uppercase; color: var(--muted); align-self: center; }
+.state.failed, .state.running { color: var(--accent); }
+.capture .detail { grid-column: 1 / 3; }
+.capture .bar { grid-column: 1 / 3; margin-top: 6px; height: 2px; }
+.empty { padding: 24px 0; color: var(--muted); }
+
+/* Layers and files */
+
+.layers .group { margin-top: 14px; }
+.layers .group:first-child { margin-top: 0; }
+.layers .group > p:first-child { margin-bottom: 2px; font-weight: 600; }
+.toggle {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ padding: 5px 0;
+ cursor: pointer;
+}
+.toggle .value, .files .value { margin-left: auto; color: var(--muted); font: 11px var(--mono); }
+.files li { display: flex; gap: 10px; padding: 4px 0; font: 12px var(--mono); }
+.files + .root { margin-top: 10px; }
+
+/* Map */
+
+.stage { position: relative; flex: 1; min-width: 0; }
+#map { position: absolute; inset: 0; background: var(--paper); }
+
+.search { position: absolute; top: 16px; left: 16px; width: 300px; z-index: 2; }
+.search input {
+ width: 100%;
+ padding: 9px 12px;
+ border: 1px solid var(--ink);
+ background: var(--paper);
+ font: 13px var(--sans);
+ text-align: left;
+}
+.search input:hover, .search input:focus { border-color: var(--ink); }
+.search ol { border: 1px solid var(--ink); border-top: 0; background: var(--paper); max-height: 50vh; overflow-y: auto; }
+.search li button {
+ display: block;
+ width: 100%;
+ padding: 8px 12px;
+ border: 0;
+ border-top: 1px solid var(--line);
+ text-align: left;
+ font-weight: 400;
+}
+.search li:first-child button { border-top: 0; }
+.search li .detail { display: block; }
+.search .note { padding: 8px 12px; color: var(--muted); }
+.fatal { position: fixed; top: 16px; left: 50%; transform: translateX(-50%); z-index: 10; }
+.search li button:hover .detail { color: inherit; }
+
+.hint {
+ position: absolute;
+ top: 16px;
+ left: 50%;
+ transform: translateX(-50%);
+ padding: 7px 12px;
+ background: var(--ink);
+ color: var(--paper);
+ font: 11px var(--mono);
+ letter-spacing: .04em;
+ pointer-events: none;
+ z-index: 2;
+}
+
+.viewer {
+ position: absolute;
+ right: 16px;
+ bottom: 40px;
+ width: min(560px, calc(100% - 32px));
+ border: 1px solid var(--ink);
+ background: var(--paper);
+ z-index: 2;
+}
+.viewer img { display: block; width: 100%; aspect-ratio: 16 / 9; object-fit: cover; background: var(--line); }
+.viewer img.sphere { aspect-ratio: 2 / 1; }
+.viewer figcaption { display: flex; align-items: center; gap: 12px; padding: 8px 10px; }
+#viewer-text { flex: 1; min-width: 0; }
+#viewer-text strong { display: block; font-weight: 600; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+#viewer-text span { color: var(--muted); font: 11px var(--mono); }
+.viewer-actions { display: flex; gap: 4px; }
+
+.maplibregl-ctrl-group, .maplibregl-ctrl-group:not(:empty) {
+ border: 1px solid var(--ink);
+ border-radius: 0;
+ box-shadow: none;
+ background: var(--paper);
+}
+.maplibregl-ctrl-group button { border-radius: 0 !important; border: 0; }
+.maplibregl-ctrl-group button + button { border-top: 1px solid var(--line); }
+.maplibregl-ctrl-group button:hover { background: var(--surface) !important; }
+.maplibregl-ctrl-scale { border-color: var(--ink); background: color-mix(in srgb, var(--paper) 80%, transparent); color: var(--ink); font: 10px var(--mono); }
+.maplibregl-ctrl-attrib, .maplibregl-ctrl-attrib.maplibregl-compact { border-radius: 0; background: var(--paper); color: var(--muted); }
+.maplibregl-ctrl-attrib a { color: var(--muted); }
+@media (prefers-color-scheme: dark) {
+ .maplibregl-ctrl button .maplibregl-ctrl-icon, .maplibregl-ctrl-attrib-button { filter: invert(1); }
+}
+
+@media (max-width: 760px) {
+ body { flex-direction: column-reverse; }
+ .panel { width: auto; height: 52vh; border-right: 0; border-top: 1px solid var(--ink); }
+ .brand { display: none; }
+ .search { width: auto; right: 16px; }
+ .viewer { bottom: 16px; }
+}
diff --git a/tests/test_imagery.py b/tests/test_imagery.py
index e54e0bc..593e479 100644
--- a/tests/test_imagery.py
+++ b/tests/test_imagery.py
@@ -12,7 +12,7 @@ from unittest.mock import patch
from PIL import Image
-from src import geo, satellite, terrain
+from src import geo, layers, satellite, terrain
def quiet(*args):
@@ -138,7 +138,7 @@ def int16_tile(order, x=8):
tag(325, 4, [len(block) for block in blocks])
cursor = len(terrain.header(tags, order))
tag(324, 4, list(accumulate([cursor] + [len(block) for block in blocks[:-1]])))
- return terrain.header(tags, order) + b"".join(blocks)
+ return terrain.header(tags, order) + b"".join(blocks), heights
def decode_float_block(data, predictor):
@@ -190,7 +190,7 @@ class TerrainTests(unittest.TestCase):
for order in ("<", ">"):
with self.subTest(order=order), TemporaryDirectory() as directory:
folder = Path(directory)
- data = int16_tile(order)
+ data, heights = int16_tile(order)
(folder / "8.tif").write_bytes(data)
terrain.validate(terrain.TIFF(BytesIO(data)), dict(x=8, y=5, zoom=4))
terrain.merge(folder / "terrain.tif", folder, [dict(x=8, y=5, zoom=4, filename="8.tif")],
@@ -198,3 +198,9 @@ class TerrainTests(unittest.TestCase):
with (folder / "terrain.tif").open("rb") as stream:
merged = terrain.TIFF(stream)
self.assertEqual((merged.value(258), merged.value(317)), (16, 2))
+ # The dashboard decodes saved tiles itself and encodes them as Terrarium RGB.
+ with layers.heights(folder / "8.tif") as decoded, layers.terrarium(decoded) as rgb:
+ self.assertEqual(list(struct.unpack(f"={512 * 512}f", decoded.tobytes())), heights)
+ pixels = rgb.tobytes()
+ self.assertEqual([pixels[i] * 256 + pixels[i + 1] + pixels[i + 2] / 256 - 32768
+ for i in range(0, len(pixels), 3)], heights)