83 lines
2.9 KiB
Python
83 lines
2.9 KiB
Python
"""Elevation lookup from Terrarium-encoded terrain tiles (AWS Open Data).
|
|
|
|
decode: elevation_m = (R * 256 + G + B / 256) - 32768
|
|
Tiles are cached on disk under data_dir/terrain so offline packs and the
|
|
segmenter share the same cache.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import io
|
|
import logging
|
|
import math
|
|
from pathlib import Path
|
|
|
|
import httpx
|
|
from PIL import Image
|
|
|
|
from app.config import settings
|
|
from app.models.route import TrkPt
|
|
|
|
log = logging.getLogger("trekker.elevation")
|
|
|
|
TILE_SIZE = 256
|
|
DEFAULT_ZOOM = 12
|
|
|
|
|
|
def lonlat_to_tile(lon: float, lat: float, zoom: int) -> tuple[int, int, float, float]:
|
|
"""Tile x/y plus fractional pixel offset within the tile."""
|
|
n = 2**zoom
|
|
xf = (lon + 180.0) / 360.0 * n
|
|
lat_r = math.radians(lat)
|
|
yf = (1.0 - math.asinh(math.tan(lat_r)) / math.pi) / 2.0 * n
|
|
x, y = int(xf), int(yf)
|
|
return x, y, (xf - x) * TILE_SIZE, (yf - y) * TILE_SIZE
|
|
|
|
|
|
class ElevationService:
|
|
def __init__(self, cache_dir: str | None = None, terrain_url: str | None = None):
|
|
self.terrain_url = terrain_url or settings.tiles.terrain_url
|
|
self.cache_dir = Path(cache_dir or Path(settings.data_dir) / "terrain")
|
|
self._mem: dict[tuple[int, int, int], Image.Image] = {}
|
|
|
|
def _tile(self, z: int, x: int, y: int) -> Image.Image | None:
|
|
key = (z, x, y)
|
|
if key in self._mem:
|
|
return self._mem[key]
|
|
path = self.cache_dir / str(z) / str(x) / f"{y}.png"
|
|
if not path.is_file():
|
|
url = self.terrain_url.format(z=z, x=x, y=y)
|
|
try:
|
|
resp = httpx.get(url, timeout=30,
|
|
headers={"User-Agent": settings.tiles.user_agent})
|
|
resp.raise_for_status()
|
|
except httpx.HTTPError as e:
|
|
log.warning("terrain tile %s/%s/%s fetch failed: %s", z, x, y, e)
|
|
return None
|
|
path.parent.mkdir(parents=True, exist_ok=True)
|
|
path.write_bytes(resp.content)
|
|
img = Image.open(io.BytesIO(path.read_bytes())).convert("RGB")
|
|
if len(self._mem) > 64:
|
|
self._mem.clear()
|
|
self._mem[key] = img
|
|
return img
|
|
|
|
def elevation_at(self, lat: float, lon: float, zoom: int = DEFAULT_ZOOM) -> float | None:
|
|
x, y, px, py = lonlat_to_tile(lon, lat, zoom)
|
|
img = self._tile(zoom, x, y)
|
|
if img is None:
|
|
return None
|
|
r, g, b = img.getpixel((min(int(px), TILE_SIZE - 1), min(int(py), TILE_SIZE - 1)))[:3]
|
|
return (r * 256 + g + b / 256) - 32768
|
|
|
|
def fill_missing_elevations(self, points: list[TrkPt], zoom: int = DEFAULT_ZOOM) -> int:
|
|
"""Populate ele on points lacking it. Returns count filled."""
|
|
filled = 0
|
|
for p in points:
|
|
if p.ele is None:
|
|
ele = self.elevation_at(p.lat, p.lon, zoom)
|
|
if ele is not None:
|
|
p.ele = round(ele, 1)
|
|
filled += 1
|
|
return filled
|