Add permanent trims and semantic map layers
This commit is contained in:
1 parent
3abdc95500
commit
e71447da5d
13 files changed
+1929
-114
No files matched your search
+98
-10
@@ -1,4 +1,4 @@
|
||||
"""Static server for web/, reachable from other devices on the LAN.
|
||||
"""Static server plus local placement/trim editing API, reachable on the LAN.
|
||||
|
||||
python server/serve.py [port] # default 8080
|
||||
|
||||
@@ -53,7 +53,8 @@ class Handler(http.server.SimpleHTTPRequestHandler):
|
||||
self.wfile.write(body)
|
||||
|
||||
def do_POST(self) -> None: # noqa: N802 - stdlib handler API
|
||||
if urlsplit(self.path).path != "/api/placement":
|
||||
path = urlsplit(self.path).path
|
||||
if path not in {"/api/placement", "/api/trim"}:
|
||||
self.send_json(404, {"error": "unknown API endpoint"})
|
||||
return
|
||||
|
||||
@@ -63,27 +64,36 @@ class Handler(http.server.SimpleHTTPRequestHandler):
|
||||
raise ValueError("request body must be between 1 and 16384 bytes")
|
||||
payload = json.loads(self.rfile.read(length))
|
||||
map_id = payload["id"]
|
||||
cx, cy = float(payload["cx"]), float(payload["cy"])
|
||||
width, height = float(payload["w"]), float(payload["h"])
|
||||
if not isinstance(map_id, str) or not map_id or map_id == "overall":
|
||||
raise ValueError("id must name a detail map")
|
||||
if not all(math.isfinite(v) for v in (cx, cy, width, height)):
|
||||
raise ValueError("cx, cy, w and h must be finite numbers")
|
||||
if width <= 0 or height <= 0:
|
||||
raise ValueError("w and h must be greater than zero")
|
||||
if path == "/api/placement":
|
||||
cx, cy = float(payload["cx"]), float(payload["cy"])
|
||||
width, height = float(payload["w"]), float(payload["h"])
|
||||
if not all(math.isfinite(v) for v in (cx, cy, width, height)):
|
||||
raise ValueError("cx, cy, w and h must be finite numbers")
|
||||
if width <= 0 or height <= 0:
|
||||
raise ValueError("w and h must be greater than zero")
|
||||
else:
|
||||
points = normalize_trim_points(payload["points"])
|
||||
transparency = float(payload["outsideTransparency"])
|
||||
if not math.isfinite(transparency) or not 0 <= transparency <= 1:
|
||||
raise ValueError("outsideTransparency must be between 0 and 1")
|
||||
except (KeyError, TypeError, ValueError, json.JSONDecodeError) as exc:
|
||||
self.send_json(400, {"error": str(exc)})
|
||||
return
|
||||
|
||||
try:
|
||||
result = save_placement(map_id, cx, cy, width, height)
|
||||
if path == "/api/placement":
|
||||
result = save_placement(map_id, cx, cy, width, height)
|
||||
else:
|
||||
result = save_trim(map_id, points, transparency)
|
||||
except PlacementError as exc:
|
||||
self.send_json(exc.status, {"error": str(exc)})
|
||||
return
|
||||
self.send_json(200, result)
|
||||
|
||||
def end_headers(self):
|
||||
if "/tiles/" in self.path:
|
||||
if "/tiles/" in self.path or "/tiles-trimmed/" in self.path:
|
||||
self.send_header("Cache-Control", "public, max-age=604800, immutable")
|
||||
else:
|
||||
self.send_header("Cache-Control", "no-cache")
|
||||
@@ -99,6 +109,22 @@ class PlacementError(Exception):
|
||||
self.status = status
|
||||
|
||||
|
||||
def normalize_trim_points(value) -> list[list[float]]:
|
||||
if not isinstance(value, list) or len(value) > 500:
|
||||
raise ValueError("points must be a list containing at most 500 vertices")
|
||||
if value and len(value) < 3:
|
||||
raise ValueError("a trim polygon needs at least three points, or none to clear it")
|
||||
points = []
|
||||
for point in value:
|
||||
if not isinstance(point, list) or len(point) != 2:
|
||||
raise ValueError("each trim point must be [x, y]")
|
||||
x, y = float(point[0]), float(point[1])
|
||||
if not math.isfinite(x) or not math.isfinite(y) or not 0 <= x <= 1 or not 0 <= y <= 1:
|
||||
raise ValueError("trim point coordinates must be finite values from 0 to 1")
|
||||
points.append([round(x, 6), round(y, 6)])
|
||||
return points
|
||||
|
||||
|
||||
def _write_config(raw: dict) -> None:
|
||||
temporary = CONFIG.with_name(f"{CONFIG.name}.{os.getpid()}.tmp")
|
||||
temporary.write_text(
|
||||
@@ -107,6 +133,68 @@ def _write_config(raw: dict) -> None:
|
||||
temporary.replace(CONFIG)
|
||||
|
||||
|
||||
def _write_world(raw: dict) -> None:
|
||||
path = WEB / "data" / "world.json"
|
||||
temporary = path.with_name(f"{path.name}.{os.getpid()}.tmp")
|
||||
temporary.write_text(
|
||||
json.dumps(raw, indent=2, ensure_ascii=False) + "\n", encoding="utf-8"
|
||||
)
|
||||
temporary.replace(path)
|
||||
|
||||
|
||||
def save_trim(map_id: str, points: list[list[float]], transparency: float) -> dict:
|
||||
"""Persist a polygon and build a separate, permanently masked raster copy."""
|
||||
with CONFIG_LOCK:
|
||||
original_config = CONFIG.read_text(encoding="utf-8")
|
||||
raw = json.loads(original_config)
|
||||
selected = next((m for m in raw["maps"] if m["id"] == map_id), None)
|
||||
if selected is None:
|
||||
raise PlacementError(f"unknown map id: {map_id}", 404)
|
||||
|
||||
world_path = WEB / "data" / "world.json"
|
||||
base = ROOT / "build" / map_id / "base.png"
|
||||
if not base.exists():
|
||||
raise PlacementError(
|
||||
f"{base.relative_to(ROOT)} is missing; export the map before saving a trim",
|
||||
409,
|
||||
)
|
||||
|
||||
trim = {
|
||||
"points": points,
|
||||
"outsideTransparency": round(transparency, 3),
|
||||
}
|
||||
if points:
|
||||
selected["trim"] = trim
|
||||
else:
|
||||
selected.pop("trim", None)
|
||||
trim = None
|
||||
try:
|
||||
_write_config(raw)
|
||||
proc = subprocess.run(
|
||||
[sys.executable, str(BUILD_TOOL), map_id, "--tiles-only", "--trim-only"],
|
||||
cwd=ROOT,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=300,
|
||||
check=False,
|
||||
)
|
||||
except (OSError, subprocess.TimeoutExpired) as exc:
|
||||
CONFIG.write_text(original_config, encoding="utf-8")
|
||||
raise PlacementError(
|
||||
f"permanent trim could not be built; maps.json was restored: {exc}"
|
||||
) from exc
|
||||
if proc.returncode:
|
||||
CONFIG.write_text(original_config, encoding="utf-8")
|
||||
raise PlacementError(
|
||||
"permanent trim build failed; maps.json was restored\n"
|
||||
+ (proc.stderr or proc.stdout)[-2000:]
|
||||
)
|
||||
|
||||
manifest = json.loads(world_path.read_text(encoding="utf-8"))
|
||||
entry = next(m for m in manifest["maps"] if m["id"] == map_id)
|
||||
return {"ok": True, "id": map_id, "trim": trim, "map": entry}
|
||||
|
||||
|
||||
def save_placement(map_id: str, cx: float, cy: float, width: float, height: float) -> dict:
|
||||
"""Persist one map's center and dimensions, then rebuild its tile pyramid."""
|
||||
with CONFIG_LOCK:
|
||||
|
||||
Reference in new issue
Block a user