Add permanent trims and semantic map layers

This commit is contained in:
lucio committed 2026-08-08 18:47:56 -07:00
1 parent 3abdc95500
commit e71447da5d
13 files changed
+1929 -114

No files matched your search

+2
View File
@@ -16,7 +16,9 @@ sources/overall/*
# Generated by tools/build.py -- rebuildable from sources/, so not tracked.
build/
web/tiles/
web/tiles-trimmed/
web/data/world.json
web/data/markers.json
# Fetched by server/get-caddy.ps1 -- a 47 MB binary, not source.
server/caddy.exe
+51 -4
View File
@@ -300,15 +300,23 @@ around 8 GB for the largest PSDs.
| `minZoom` | no | Raise the automatically derived zoom at which a nested detail layer appears |
| `place` | yes | `{cx, cy, w, h?}`: center anchor and dimensions in **rotated** overall-map pixels |
| `pxPerMeter` | no | From the map's scale bar; recorded for future use |
| `trim` | no | `{points, outsideTransparency}` playable-area polygon; see below |
| `parent` | no | parent map id for grouped navigation and dropdown ordering |
`place.w` is the map's width in overall-map pixels. Height follows from the
source aspect ratio unless optional `place.h` is set, in which case width and
height can be tuned independently.
`minZoom` is normally derived from placed size so a layer does not load while
it would be a speck. An explicit value is a lower visibility bound: it can
delay a nested detail layer until a closer zoom, but cannot force it to appear
earlier than the automatic threshold or above its native tile level.
Detail layers default to `minZoom: 0`, keeping main location maps visible in
the overview. An explicit `minZoom` delays a nested detail layer until a closer
zoom, and cannot be set above its native tile level.
`trim.points` is a list of `[x, y]` vertices normalized to the map rectangle,
where both axes run from 0 to 1. Normalization keeps the boundary attached when
the map is moved or stretched. `outsideTransparency` runs from 0 (unchanged)
to 1 (fully transparent). Saving generates `build/<id>/trimmed.png` and a
separate `web/tiles-trimmed/<id>/` pyramid; `base.png` and the original tile
pyramid remain available and unchanged.
**Changing `world.rotate` by hand will move every map**, because `place` lives
in the rotated frame. Use `python tools/retilt.py <deg>`, which converts each
@@ -354,6 +362,21 @@ of the map's geometry, zoom range and source file stamp — see §11.
## 8. The viewer
### Semantic PSD markers
`tools/extract_markers.py` reads PSD layer metadata only; it never composites
marker pixels. Visible leaves in on-map overlay/marker groups are classified,
normalized against the configured crop, and deduplicated when a PSD icon and
text component share the same point. Legends, credits, titles, compass art and
large region overlays are excluded. The generated `web/data/markers.json`
contains `{mapId, x, y, category, label, source}` records.
The viewer converts normalized coordinates through each map's current
`origin`/`size`, so placement and stretch changes also move the marker layer.
One **Markers** control toggles the complete layer. Focus limits rendering to
the active parent/sub-map family, while consistent CSS category symbols remain
visible at broad zooms and labels appear from zoom 6.
`web/app.js`, 179 lines, no build step, no framework, vendored Leaflet.
### Layers
@@ -425,12 +448,36 @@ drag or numeric X/Y edit translates the map's dedicated Leaflet pane live.
Width and Height scale the same pane independently around the anchor, providing
horizontal and vertical stretch with a live aspect-ratio readout.
Placement editing temporarily hides any trim overlay and renders the complete
selected map at exactly 50% opacity, making underlying satellite landmarks
visible during alignment.
**Save & rebuild** posts the new center and dimensions to `server/serve.py`.
The server writes `maps.json` atomically, runs a tiles-only build for that map,
and returns only after `world.json` contains its new origin, size and
cache-busting version. Use
`pwsh server/run.ps1 -Editable`; the Caddy-only mode remains read-only.
### Trim editor
**Trim area** authors a single playable-area polygon. Map clicks append points;
points are draggable, and Undo/Clear support correction. The outside
transparency slider previews the result immediately.
While editing, the untouched tile pane and a clipped duplicate provide an
immediate preview without rebuilding on every drag. **Save trim** posts the
normalized points and transparency to `/api/trim`; the server writes
`maps.json`, bakes the outside alpha into `build/<id>/trimmed.png`, and creates
a separately versioned `web/tiles-trimmed/<id>/` pyramid. The normal viewer
then uses those already-rasterized tiles with no dynamic CSS mask. Clearing and
saving a trim returns the viewer to the original tiles. The trim-only build
leaves both `base.png` and `web/tiles/<id>/` untouched.
The original rectangle remains the raster/tile coordinate frame so alignment
does not move. The viewer separately derives a viewable bounding box and exact
point-in-polygon hit area from `trim.points`; map-button focusing and automatic
active-map selection therefore follow the saved playable zone.
---
## 9. Serving
+40 -4
View File
@@ -57,7 +57,7 @@ maps.json the only thing you edit to add or change a map
tools/
psd_tree.py inspect a PSD's layer tree
export_base.py PSD -> build/<id>/base.png (base group only)
tile.py base.png -> web/tiles/<id>/{z}/{x}/{y}.webp
tile.py base.png -> original and optional permanently trimmed tiles
build.py orchestrator; also writes web/data/world.json
preview.py stitch built tiles into one overview image
place_preview.py gridded base map for positioning maps
@@ -67,7 +67,8 @@ server/serve.py dependency-free static server with sane cache headers
web/ the site: index.html, app.js, style.css, vendored Leaflet
sources/ gitignored — source PSDs
build/ gitignored — intermediate PNGs
web/tiles/ gitignored — generated tiles
web/tiles/ gitignored — generated original tiles
web/tiles-trimmed/ gitignored — generated permanently trimmed tiles
```
## How the shared canvas works
@@ -90,8 +91,9 @@ the nearest cell boundary and only visits tiles containing real content. Exact
placement, integral grid, and the padding costs nothing.
Each map is tiled only down to its **native level** — the deepest zoom still
downscaling its source — and has a `minZoom` below which it doesn't load at
all. So the overview is just the base map, and detail maps appear as you go in.
downscaling its source. Main maps default to `minZoom: 0`, so they remain
visible in the overview. Nested detail maps can set a later `minZoom` and only
appear as you zoom in.
### Interactive placement
@@ -106,6 +108,40 @@ writable local server with:
pwsh server/run.ps1 -Port 8081 -Editable
```
Placement mode renders the selected map at 50% opacity so landmarks on the
overall map remain visible underneath it.
### Playable-area trimming
Select a detail map and choose **Trim area**. Click around the playable boundary
to add polygon points; drag any yellow point to refine it. The Outside
transparency slider controls how strongly the unplayable portion fades while
the polygon interior remains fully opaque. **Save trim** stores normalized
polygon points in `maps.json`, leaves `build/<id>/base.png` and the original
tile pyramid untouched, and writes a separate permanent `build/<id>/trimmed.png`
plus `web/tiles-trimmed/<id>/` pyramid. The normal viewer loads that rasterized
copy; only the editor uses a temporary live mask for previewing unsaved edits.
Trim saves use a trim-only build, so they do not regenerate the original tiles.
Map navigation and active-map detection are recalculated from the saved trim
polygon, rather than continuing to use the untrimmed rectangular canvas.
### Semantic marker layer
**Markers** toggles a real Leaflet data layer; no PSD marker artwork is placed
over the tiles. `tools/extract_markers.py` reads visible on-map PSD layer
metadata, ignores legends and title furniture, classifies and deduplicates
markers, and writes normalized records to `web/data/markers.json`:
```bash
python tools/extract_markers.py
python tools/extract_markers.py --source-root C:/path/to/source-checkout
```
Every map uses the same HTML/CSS symbols, colors and labels. Only the focused
parent/sub-map family is shown, symbols appear at broad zooms, and text labels
appear at zoom 6 or closer to avoid covering the map. The toggle is persisted
in local browser storage.
## No black gaps
The base map is the backdrop. It is 85 tiles / 0.3 MB, always resident, and
+18 -3
View File
@@ -73,7 +73,9 @@ solid fills, so they may need `excludeLayers`.
| `crop` | `[x0, y0, x1, y1]` in PSD pixels, or `null` for the full canvas |
| `minZoom` | optional close-view reveal threshold for nested detail maps; otherwise derived from size |
| `place` | center anchor and dimensions on the world map; optional `h` enables independent stretch — see step 4 |
| `parent` | optional parent map id; groups the sub-map directly below its parent and includes it in parent focus |
| `pxPerMeter` | optional, from the map's scale bar; recorded for later use |
| `trim` | optional normalized playable-area polygon and outside transparency |
---
@@ -158,8 +160,15 @@ python tools/build.py # base + every map
python tools/build.py overall # just retile the base map
python tools/build.py --tiles-only # re-tile after a place/crop change
python tools/build.py --force-export # re-render even if base.png is current
python tools/extract_markers.py <id> # PSD metadata -> semantic marker JSON
```
Marker extraction recognizes visible on-map groups whose paths use names such
as `Overlay`, `OnMap`, `Map Markers`, extracts, spawns, caches and locations.
Keep legends and title furniture in clearly named groups so the extractor can
exclude them. Marker coordinates are stored normalized to the configured crop,
not as raster overlays.
`build.py` skips the PSD render when `base.png` is newer than the PSD, so
iterating on `place` and `crop` is seconds, not minutes.
@@ -186,12 +195,18 @@ grid, and the padding costs nothing.
Each map is also only tiled down to its **native level** — the deepest zoom at
which we are still downscaling its source. Past that the browser upscales,
which looks the same as upscaling during the build but without storing tiles.
`minZoom` likewise stops a map loading while it would be a speck on screen.
The build derives it from the placed size by default. Set it explicitly for a
nested detail view that should stay out of the main view until the user zooms
`minZoom` defaults to 0 so a main map remains visible in the overview. Set it
explicitly for a nested detail view that should stay out of the main view until the user zooms
closer; the configured value can only raise the automatic threshold.
For visual placement, run `pwsh server/run.ps1 -Editable`, select the map in
the viewer, and use **Edit placement**. Dragging the center anchor previews the
move immediately. Width and Height stretch it independently around that anchor;
**Save & rebuild** updates `maps.json` and retiles that map.
Use **Trim area** in the same viewer to add a playable-area polygon. Its points
are normalized to the displayed map, so later placement and stretching do not
invalidate the boundary. **Save trim** updates local configuration, preserves
the PSD, `base.png`, and original tile pyramid, then writes a derived
`build/<id>/trimmed.png` and `web/tiles-trimmed/<id>/` pyramid. The normal
viewer uses the derived copy; the original remains available to edit again.
+715 -7
View File
@@ -10,6 +10,7 @@
"overallScale": 64
},
"$comment_place": "`place` is in ROTATED overall-map pixels (the north-up image, which is what tools/place_preview.py draws a grid over): cx/cy = centre, w = width, optional h = explicit height for independent vertical/horizontal stretch. Positions are deliberately approximate -- the game's maps do not tile exactly onto the satellite view.",
"$comment_trim": "Optional trim.points is a playable-area polygon in normalized map coordinates from 0 to 1. outsideTransparency controls the unplayable area's transparency without deleting source pixels.",
"maps": [
{
"id": "customs",
@@ -33,22 +34,297 @@
"cy": 979.34,
"w": 281.5,
"h": 142.0
},
"trim": {
"points": [
[
0.046459,
0.270467
],
[
0.028356,
0.498749
],
[
0.046567,
0.504974
],
[
0.03652,
0.569709
],
[
0.027728,
0.674281
],
[
0.018936,
0.75022
],
[
0.02082,
0.798771
],
[
0.044683,
0.819935
],
[
0.085502,
0.817445
],
[
0.113133,
0.846078
],
[
0.133857,
0.897119
],
[
0.156464,
0.930732
],
[
0.193515,
0.958119
],
[
0.258197,
0.987997
],
[
0.296504,
0.94567
],
[
0.342974,
0.88467
],
[
0.375001,
0.883425
],
[
0.4064,
0.923262
],
[
0.449731,
0.95065
],
[
0.49683,
0.974303
],
[
0.534025,
0.957967
],
[
0.56214,
0.917038
],
[
0.587755,
0.867298
],
[
0.609238,
0.826159
],
[
0.639265,
0.841769
],
[
0.668572,
0.837368
],
[
0.694327,
0.830326
],
[
0.696992,
0.802157
],
[
0.7001,
0.696523
],
[
0.768484,
0.693002
],
[
0.812889,
0.660431
],
[
0.846636,
0.614657
],
[
0.879052,
0.579445
],
[
0.920349,
0.538072
],
[
0.967418,
0.487016
],
[
0.980295,
0.441241
],
[
0.98296,
0.287192
],
[
0.985399,
0.204951
],
[
0.976607,
0.168849
],
[
0.961536,
0.147685
],
[
0.849127,
0.141461
],
[
0.81082,
0.172584
],
[
0.773141,
0.193747
],
[
0.748022,
0.211176
],
[
0.751162,
0.272176
],
[
0.723531,
0.29085
],
[
0.693388,
0.295829
],
[
0.663873,
0.29334
],
[
0.641265,
0.310768
],
[
0.623054,
0.302054
],
[
0.622426,
0.253503
],
[
0.559628,
0.267196
],
[
0.528857,
0.278401
],
[
0.512529,
0.223625
],
[
0.505621,
0.1564
],
[
0.525717,
0.066767
],
[
0.485526,
0.02693
],
[
0.412356,
0.196523
],
[
0.316885,
0.233495
],
[
0.323102,
0.333847
]
],
"outsideTransparency": 1.0
}
},
{
"id": "customs-dorms",
"name": "Customs — Dorms",
"parent": "customs",
"psd": "sources/customs/customs-dorms.psd",
"baseLayers": [
"LOCATION"
],
"crop": null,
"minZoom": 6,
"minZoom": 0,
"place": {
"cx": 1047.0,
"cy": 990.0,
"cx": 1089.07,
"cy": 1041.03,
"w": 70.0,
"h": 79.81
},
"trim": {
"points": [
[
0.016534,
0.056157
],
[
0.016534,
0.530272
],
[
0.11564,
0.567148
],
[
0.147173,
0.983316
],
[
0.992575,
0.993852
],
[
0.985067,
0.046938
]
],
"outsideTransparency": 1.0
}
},
{
@@ -61,8 +337,8 @@
],
"crop": null,
"place": {
"cx": 833.68,
"cy": 766.15,
"cx": 826.6,
"cy": 765.64,
"w": 450.0,
"h": 450.0
}
@@ -75,7 +351,7 @@
"3DRENDER"
],
"crop": null,
"minZoom": 6,
"minZoom": 0,
"place": {
"cx": 1202.97,
"cy": 849.77,
@@ -96,6 +372,83 @@
"cy": 1113.56,
"w": 238.0,
"h": 132.75
},
"trim": {
"points": [
[
0.138459,
0.015537
],
[
0.102744,
0.060734
],
[
0.044971,
0.324388
],
[
0.002954,
0.506121
],
[
0.017135,
0.55791
],
[
0.060727,
0.572976
],
[
0.247177,
0.572034
],
[
0.288143,
0.65113
],
[
0.281316,
0.734934
],
[
0.308101,
0.80838
],
[
0.369551,
0.839454
],
[
0.429425,
0.841337
],
[
0.474068,
0.837571
],
[
0.960412,
0.817797
],
[
0.985097,
0.600282
],
[
0.981946,
0.362994
],
[
0.906841,
0.050377
],
[
0.793395,
0.012712
]
],
"outsideTransparency": 1.0
}
},
{
@@ -111,18 +464,184 @@
"cy": 1340.5,
"w": 460.0,
"h": 333.75
},
"trim": {
"points": [
[
0.17138,
0.204358
],
[
0.137772,
0.238208
],
[
0.102872,
0.334414
],
[
0.106749,
0.443981
],
[
0.137126,
0.509009
],
[
0.173965,
0.534842
],
[
0.17849,
0.553549
],
[
0.230194,
0.564238
],
[
0.228255,
0.579382
],
[
0.212098,
0.607887
],
[
0.22567,
0.659553
],
[
0.268326,
0.653317
],
[
0.282545,
0.58918
],
[
0.277375,
0.561566
],
[
0.295471,
0.563347
],
[
0.338774,
0.581163
],
[
0.362687,
0.593634
],
[
0.40082,
0.620358
],
[
0.445415,
0.636392
],
[
0.479023,
0.651536
],
[
0.506814,
0.648863
],
[
0.528789,
0.655099
],
[
0.557226,
0.705874
],
[
0.591481,
0.726362
],
[
0.632844,
0.742396
],
[
0.659989,
0.717454
],
[
0.672269,
0.684495
],
[
0.739485,
0.687167
],
[
0.817042,
0.688949
],
[
0.840309,
0.775356
],
[
0.905586,
0.76912
],
[
0.954059,
0.569583
],
[
0.936609,
0.451998
],
[
0.910757,
0.287202
],
[
0.782141,
0.294328
],
[
0.745302,
0.012838
],
[
0.58114,
0.019073
],
[
0.446061,
0.024418
],
[
0.296118,
0.045797
],
[
0.206927,
0.076975
]
],
"outsideTransparency": 1.0
}
},
{
"id": "shoreline-resort",
"name": "Shoreline — Resort",
"parent": "shoreline",
"psd": "sources/shoreline-resort/shoreline-resort.psd",
"baseLayers": [
"BGCOLOR PATTERN",
"BASEMAP+2DLAYERS"
],
"crop": null,
"minZoom": 6,
"minZoom": 0,
"place": {
"cx": 1045.65,
"cy": 1220.14,
@@ -143,6 +662,195 @@
"cy": 1198.5,
"w": 375.0,
"h": 421.72
},
"trim": {
"points": [
[
0.550609,
0.029787
],
[
0.562865,
0.058292
],
[
0.514782,
0.064999
],
[
0.534581,
0.108594
],
[
0.511954,
0.219257
],
[
0.505354,
0.319861
],
[
0.452557,
0.368486
],
[
0.433701,
0.456514
],
[
0.520439,
0.474958
],
[
0.512896,
0.682872
],
[
0.395988,
0.713892
],
[
0.291336,
0.80695
],
[
0.295108,
0.883241
],
[
0.311135,
0.962885
],
[
0.399759,
0.992228
],
[
0.573236,
0.99642
],
[
0.834394,
0.992228
],
[
0.862679,
0.873181
],
[
0.865507,
0.827909
],
[
0.855136,
0.766708
],
[
0.784425,
0.75581
],
[
0.764627,
0.682034
],
[
0.774997,
0.595682
],
[
0.795739,
0.529452
],
[
0.837223,
0.516038
],
[
0.910762,
0.517715
],
[
0.944703,
0.47412
],
[
0.957902,
0.422141
],
[
0.951303,
0.373516
],
[
0.942817,
0.334952
],
[
0.95036,
0.281296
],
[
0.942817,
0.225964
],
[
0.934332,
0.177339
],
[
0.893791,
0.160572
],
[
0.884363,
0.138775
],
[
0.906991,
0.125361
],
[
0.904162,
0.091826
],
[
0.873992,
0.068352
],
[
0.840994,
0.076736
],
[
0.833452,
0.111109
],
[
0.822138,
0.131229
],
[
0.776883,
0.130391
],
[
0.747656,
0.125361
],
[
0.749542,
0.04404
],
[
0.593978,
0.045716
],
[
0.58455,
0.016374
]
],
"outsideTransparency": 1.0
}
},
{
+98 -10
View File
@@ -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:
+4 -2
View File
@@ -3,6 +3,7 @@
python tools/build.py # base + every map
python tools/build.py customs # just one map
python tools/build.py --tiles-only # skip the slow PSD render
python tools/build.py shoreline --tiles-only --trim-only
python tools/build.py --force-export # re-render even if base.png exists
Exporting a 1 GB PSD takes minutes, so base.png is reused unless it is older
@@ -29,7 +30,8 @@ def needs_export(m: dict, force: bool) -> bool:
def main(argv: list[str]) -> None:
tiles_only = "--tiles-only" in argv
trim_only = "--trim-only" in argv
tiles_only = "--tiles-only" in argv or trim_only
force = "--force-export" in argv
ids = [a for a in argv if not a.startswith("--")]
@@ -68,7 +70,7 @@ def main(argv: list[str]) -> None:
if m["id"] != WORLD_ID and not (BUILD / m["id"] / "base.png").exists():
print(f"[{m['id']}] no base.png, skipping tiling")
continue
entries.append(tile.tile_map(cfg, m))
entries.append(tile.tile_map(cfg, m, trim_only=trim_only))
# Keep maps that weren't part of this run so partial builds don't drop them.
by_id = {e["id"]: e for e in entries}
+1
View File
@@ -30,6 +30,7 @@ ROOT = Path(__file__).resolve().parent.parent
CONFIG = ROOT / "maps.json"
BUILD = ROOT / "build"
TILES = ROOT / "web" / "tiles"
TRIMMED_TILES = ROOT / "web" / "tiles-trimmed"
DATA = ROOT / "web" / "data"
WORLD_ID = "overall"
+267
View File
@@ -0,0 +1,267 @@
"""Extract semantic marker records from PSD layer metadata.
The PSD artwork is never composited. Visible leaf layers inside on-map marker
groups become normalized JSON records which the viewer renders with one shared
HTML/CSS style.
python tools/extract_markers.py
python tools/extract_markers.py customs woods
python tools/extract_markers.py --source-root C:/path/to/checkout
"""
from __future__ import annotations
import json
import re
import sys
from pathlib import Path
from psd_tools import PSDImage
from common import DATA, ROOT, find_map, load_config
CONTEXT = ("overlay", "onmap", "on map", "map marker", "mapmarker", "extractinformation")
EXCLUDED = (
"legend", "credit", "title section", "raid detail", "compass", "coloredmarkers",
"colored markers", "mapinfo", "duration", "version",
)
LEAF_KINDS = {"type", "smartobject", "pixel"}
GENERIC = re.compile(
r"^(layer|group|shape|form|icon|marker|scav|boss|pmcspawn|player ?spawn|extractbg|"
r"cache|corpse|aiscav)(?:\s*\d+)?$",
re.IGNORECASE,
)
CATEGORY_LABELS = {
"extract-pmc": "PMC extract", "extract-scav": "Scav extract",
"extract-neutral": "Co-op extract", "extract-hidden": "Hidden extract",
"transit": "Transit", "spawn": "PMC spawn", "scav": "Scav area",
"boss": "Boss area", "cultist": "Cultist area", "sniper": "Sniper area",
"cache": "Cache", "key": "Key", "loot": "Loot", "hazard": "Hazard",
"quest": "Quest", "location": "Location", "poi": "Point of interest",
}
def clean_name(value: str) -> str:
value = "".join(char if char.isprintable() else " " for char in value)
value = re.sub(r"\s+(?:copy|kopiera)(?:\s+\d+)?$", "", value, flags=re.IGNORECASE)
value = re.sub(r"(?<=[a-z])(?=[A-Z])", " ", value)
value = value.replace("_", " ")
value = re.sub(r"\s+", " ", value).strip(" _-")
return value[:80]
def display_label(category: str, value: str) -> str:
value = clean_name(value)
lower = value.lower()
noisy = (not any(char.isalnum() for char in value)
or GENERIC.match(value)
or len(value) > 48
or lower.startswith(("layer ", "shape ", "form ", "ellipse ", "handpainted"))
or lower.startswith("read description")
or set(value) <= {".", " ", "•"})
if (category.startswith("extract-") or category == "transit") \
and 0 < len(value) <= 4 and any(c.isalnum() for c in value):
return value.upper()
if category in {"spawn", "cache", "loot"}:
return CATEGORY_LABELS[category]
if noisy:
return CATEGORY_LABELS.get(category, "Point of interest")
return value or CATEGORY_LABELS.get(category, "Point of interest")
def category_for(path: tuple[str, ...]) -> str | None:
text = " / ".join(path).lower().replace("_", " ")
if any(term in text for term in EXCLUDED):
return None
if not any(term in text for term in CONTEXT):
return None
if "extract" in text or "exfil" in text:
if "scav" in text:
return "extract-scav"
if "neutral" in text:
return "extract-neutral"
if "hidden" in text:
return "extract-hidden"
if "transit" in text:
return "transit"
return "extract-pmc"
if "overlay captions" in text:
if "scav" in text:
return "extract-scav"
if "hidden" in text:
return "extract-hidden"
if "neutral" in text:
return "extract-neutral"
if "pmc" in text:
return "extract-pmc"
if "overlay neutral" in text:
return "extract-neutral"
if "overlay hidden" in text:
return "extract-hidden"
if "transit" in text:
return "transit"
if "player spawn" in text or "playerspawn" in text or "pmcspawn" in text or "pmc spawn" in text:
return "spawn"
if "sniper" in text:
return "sniper"
if any(term in text for term in ("boss", "glukhar", "killa", "sanitar", "goons")):
return "boss"
if "cultist" in text:
return "cultist"
if "scav" in text:
return "scav"
if "cache" in text or "stash" in text:
return "cache"
if "key" in text:
return "key"
if any(term in text for term in ("corpse", "loot", "gun")):
return "loot"
if any(term in text for term in ("mine", "deathzone", "border")):
return "hazard"
if "quest" in text:
return "quest"
if any(term in text for term in ("location", "caption", "house name", "housename", "text")):
return "location"
return "poi"
def layer_text(layer) -> str:
if layer.kind == "type":
try:
text = clean_name(layer.text)
if text:
return text
except Exception: # noqa: BLE001 - malformed text engine data is common
pass
return clean_name(layer.name)
def marker_score(layer, label: str) -> int:
score = {"type": 4, "smartobject": 3, "pixel": 2}.get(layer.kind, 0)
if label and not GENERIC.match(label):
score += 3
if len(label) <= 30:
score += 1
return score
def source_path(m: dict, source_root: Path | None) -> Path:
local = ROOT / m["psd"]
if local.exists():
return local
if source_root:
fallback = source_root / m["psd"]
if fallback.exists():
return fallback
raise FileNotFoundError(f"{m['psd']} is unavailable")
def extract_map(m: dict, source_root: Path | None) -> list[dict]:
path = source_path(m, source_root)
print(f"[{m['id']}] reading marker metadata from {path.name}")
psd = PSDImage.open(path)
crop = m.get("crop") or [0, 0, psd.width, psd.height]
left, top, right, bottom = map(float, crop)
width, height = right - left, bottom - top
candidates: list[dict] = []
def walk(node, prefix: tuple[str, ...], ancestors_visible: bool) -> None:
for layer in node:
visible = ancestors_visible and layer.visible
layer_path = prefix + (layer.name,)
if layer.is_group():
walk(layer, layer_path, visible)
continue
if not visible or layer.kind not in LEAF_KINDS:
continue
category = category_for(layer_path)
if not category:
continue
x0, y0, x1, y1 = map(float, layer.bbox)
if x1 <= x0 or y1 <= y0:
continue
cx, cy = (x0 + x1) / 2, (y0 + y1) / 2
if not (left <= cx <= right and top <= cy <= bottom):
continue
# Very large leaves are region overlays or artwork, not point data.
if x1 - x0 > width * 0.16 or y1 - y0 > height * 0.16:
continue
label = layer_text(layer)
if label in {"☠", "☢"}:
category = "hazard"
label = display_label(category, label)
candidates.append({
"x": (cx - left) / width,
"y": (cy - top) / height,
"category": category,
"label": label,
"source": "/".join(layer_path),
"score": marker_score(layer, label),
})
walk(psd, (), True)
# A logical PSD marker is often two or three co-located leaves (background,
# icon and type). Keep the most semantic record within each small cluster.
kept: list[dict] = []
for candidate in sorted(candidates, key=lambda item: -item["score"]):
duplicate = next((item for item in kept if item["category"] == candidate["category"]
and (item["x"] - candidate["x"]) ** 2
+ (item["y"] - candidate["y"]) ** 2 < 0.0035 ** 2), None)
if duplicate:
continue
candidate.pop("score")
kept.append(candidate)
kept.sort(key=lambda item: (item["category"], item["y"], item["x"]))
for index, marker in enumerate(kept, 1):
marker["id"] = f"{m['id']}-{index}"
marker["mapId"] = m["id"]
print(f"[{m['id']}] extracted {len(kept)} marker(s)")
return kept
def main(argv: list[str]) -> None:
source_root = None
if "--source-root" in argv:
index = argv.index("--source-root")
try:
source_root = Path(argv[index + 1]).resolve()
except IndexError as exc:
raise SystemExit("--source-root needs a path") from exc
del argv[index:index + 2]
cfg = load_config()
targets = [find_map(cfg, map_id) for map_id in argv] if argv else cfg.maps
destination = DATA / "markers.json"
markers = []
successful: set[str] = set()
errors = []
for m in targets:
try:
markers.extend(extract_map(m, source_root))
successful.add(m["id"])
except Exception as exc: # noqa: BLE001
errors.append(f"{m['id']}: {exc}")
print(f"[{m['id']}] SKIPPED: {exc}")
# Targeted runs replace only the maps successfully extracted. This makes
# `extract_markers.py customs` safe after a complete build, and preserves
# the previous records for a PSD that is temporarily unavailable.
if destination.exists():
previous = json.loads(destination.read_text(encoding="utf-8")).get("markers", [])
markers = [item for item in previous if item.get("mapId") not in successful] + markers
for marker in markers:
marker["label"] = display_label(marker["category"], marker.get("label", ""))
markers.sort(key=lambda item: (item["mapId"], item["category"], item["id"]))
DATA.mkdir(parents=True, exist_ok=True)
destination.write_text(json.dumps({"version": 1, "markers": markers}, indent=2), encoding="utf-8")
print(f"wrote {destination.relative_to(ROOT)} with {len(markers)} marker(s)")
if errors:
print("skipped maps: " + "; ".join(errors))
if __name__ == "__main__":
main(sys.argv[1:])
+103 -33
View File
@@ -5,6 +5,7 @@
Reads build/<id>/base.png (or the overall image, for the base layer)
Writes web/tiles/<id>/{z}/{x}/{y}.webp
build/<id>/trimmed.png and web/tiles-trimmed/<id>/... when trim is set
Each map is scaled to the world size implied by its `place` entry and padded
up-and-left to a cell boundary so its tile grid stays integral -- see
@@ -13,43 +14,41 @@ padding is free.
A map is only tiled down to its *native* level, the deepest zoom at which we
are still downscaling the source. Past that the browser upscales, which is
identical to upscaling here but without storing the tiles.
identical to upscaling here but without storing the tiles. A trim never
overwrites base.png or its original tiles; it produces a separate raster and
tile pyramid selected by the normal viewer.
"""
from __future__ import annotations
import hashlib
import json
import math
import shutil
import sys
from PIL import Image
from PIL import Image, ImageChops, ImageDraw
from common import BUILD, ROOT, TILES, WORLD_ID, Config, find_map, load_config
from common import BUILD, ROOT, TILES, TRIMMED_TILES, WORLD_ID, Config, find_map, load_config
Image.MAX_IMAGE_PIXELS = None
WEBP = {"format": "WEBP", "quality": 82, "method": 4}
MIN_VISIBLE_PX = 160 # a map below this on screen isn't worth loading
def minimum_zoom(m: dict, zmax: int, native_level: int, world_width: float) -> int:
def minimum_zoom(m: dict, zmax: int, native_level: int) -> int:
"""First zoom at which a detail layer may be shown and requested.
The automatic threshold keeps tiny maps out of the overview. A map can
raise that threshold with ``minZoom`` in maps.json when it is a nested
detail view that should only appear once the user is close to it.
Main maps default to zero so they remain visible in the overview. A nested
detail view can set ``minZoom`` in maps.json to stay hidden until the user
zooms close to it.
"""
if m["id"] == WORLD_ID:
return 0
automatic = max(0, math.ceil(zmax + math.log2(MIN_VISIBLE_PX / world_width))) \
if world_width > 0 else 0
automatic = min(automatic, native_level)
configured = m.get("minZoom")
if configured is None:
return automatic
return 0
if type(configured) is not int or not 0 <= configured <= zmax:
raise SystemExit(
f"[{m['id']}] minZoom must be an integer from 0 to {zmax}, got {configured!r}"
@@ -59,7 +58,7 @@ def minimum_zoom(m: dict, zmax: int, native_level: int, world_width: float) -> i
f"[{m['id']}] minZoom {configured} is above its native tile level "
f"{native_level}; lower minZoom or increase the map's source/placed resolution"
)
return max(automatic, configured)
return configured
def load_source(cfg: Config, m: dict) -> tuple[Image.Image, tuple[float, float, float, float]]:
@@ -85,26 +84,50 @@ def load_source(cfg: Config, m: dict) -> tuple[Image.Image, tuple[float, float,
return img, (pl["cx"] - tw / 2, pl["cy"] - th / 2, pl["cx"] + tw / 2, pl["cy"] + th / 2)
def tile_map(cfg: Config, m: dict) -> dict:
img, (x0, y0, x1, y1) = load_source(cfg, m)
tw, th = x1 - x0, y1 - y0
ts, zmax, cell = cfg.tile_size, cfg.max_zoom, cfg.cell_size
def render_trimmed_copy(m: dict, img: Image.Image) -> Image.Image | None:
"""Bake the saved playable polygon into a separate RGBA source image.
# Deepest level worth generating. Plain floor() is too strict: Customs
# lands at 7.88, and rounding down to 7 would render its 7832 px source at
# 4240 px, throwing away half the detail. Allowing a quarter-level of slack
# tolerates up to a 1.19x upscale, which is invisible, to keep that detail.
native = zmax + math.log2(img.size[0] / tw) if tw > 0 else zmax
native_level = max(0, min(zmax, math.floor(native + 0.25)))
``base.png`` is deliberately never written. The derived image uses the
configured outside transparency as real per-pixel alpha, so the normal
viewer no longer needs a moving CSS clip-path mask.
"""
trim = m.get("trim")
points = trim.get("points", []) if isinstance(trim, dict) else []
if len(points) < 3:
return None
# Don't bother rendering the map when it would be a speck on screen.
# Nested detail views can opt into a later reveal with maps.json minZoom.
min_zoom = minimum_zoom(m, zmax, native_level, tw)
rgba = img.convert("RGBA")
width, height = rgba.size
outside_alpha = round(255 * (1 - float(trim.get("outsideTransparency", 0.75))))
mask = Image.new("L", rgba.size, outside_alpha)
polygon = [
(round(float(x) * (width - 1)), round(float(y) * (height - 1)))
for x, y in points
]
ImageDraw.Draw(mask).polygon(polygon, fill=255)
rgba.putalpha(ImageChops.multiply(rgba.getchannel("A"), mask))
gx, gy = math.floor(x0 / cell), math.floor(y0 / cell)
pad_x, pad_y = x0 - gx * cell, y0 - gy * cell
destination = BUILD / m["id"] / "trimmed.png"
destination.parent.mkdir(parents=True, exist_ok=True)
temporary = destination.with_name(f"{destination.stem}.tmp{destination.suffix}")
rgba.save(temporary, format="PNG", compress_level=1)
temporary.replace(destination)
return rgba
out = TILES / m["id"]
def write_pyramid(
img: Image.Image,
out,
ts: int,
zmax: int,
min_zoom: int,
native_level: int,
tw: float,
th: float,
pad_x: float,
pad_y: float,
) -> tuple[int, int, float]:
"""Write one tile pyramid and return (written, skipped, megabytes)."""
if out.exists():
shutil.rmtree(out)
@@ -132,9 +155,41 @@ def tile_map(cfg: Config, m: dict) -> dict:
written += 1
size_mb = sum(f.stat().st_size for f in out.rglob("*.webp")) / 1e6 if out.exists() else 0
print(f"[{m['id']:<17}] src {img.size[0]}x{img.size[1]} -> world {round(tw)}x{round(th)} "
f"@({round(x0)},{round(y0)}) z{min_zoom}-{native_level} "
f"{written} tiles ({skipped} empty), {size_mb:.1f} MB")
return written, skipped, size_mb
def tile_map(cfg: Config, m: dict, trim_only: bool = False) -> dict:
img, (x0, y0, x1, y1) = load_source(cfg, m)
tw, th = x1 - x0, y1 - y0
ts, zmax, cell = cfg.tile_size, cfg.max_zoom, cfg.cell_size
# Deepest level worth generating. Plain floor() is too strict: Customs
# lands at 7.88, and rounding down to 7 would render its 7832 px source at
# 4240 px, throwing away half the detail. Allowing a quarter-level of slack
# tolerates up to a 1.19x upscale, which is invisible, to keep that detail.
native = zmax + math.log2(img.size[0] / tw) if tw > 0 else zmax
native_level = max(0, min(zmax, math.floor(native + 0.25)))
# Main maps are visible throughout the overview. Nested detail views can
# opt into a later reveal with maps.json minZoom.
min_zoom = minimum_zoom(m, zmax, native_level)
gx, gy = math.floor(x0 / cell), math.floor(y0 / cell)
pad_x, pad_y = x0 - gx * cell, y0 - gy * cell
original_out = TILES / m["id"]
if trim_only and original_out.exists():
written = sum(1 for _ in original_out.rglob("*.webp"))
skipped = 0
size_mb = sum(f.stat().st_size for f in original_out.rglob("*.webp")) / 1e6
print(f"[{m['id']:<17}] keeping {written} original tiles unchanged ({size_mb:.1f} MB)")
else:
written, skipped, size_mb = write_pyramid(
img, original_out, ts, zmax, min_zoom, native_level, tw, th, pad_x, pad_y,
)
print(f"[{m['id']:<17}] src {img.size[0]}x{img.size[1]} -> world {round(tw)}x{round(th)} "
f"@({round(x0)},{round(y0)}) z{min_zoom}-{native_level} "
f"{written} tiles ({skipped} empty), {size_mb:.1f} MB")
# Tile URLs are stable across rebuilds but their *contents* are not: move a
# map's `place` and tiles/<id>/6/17/33.webp is suddenly different imagery.
@@ -149,9 +204,22 @@ def tile_map(cfg: Config, m: dict) -> dict:
st = cfg.base_image_path().stat()
stamp += f",{int(st.st_mtime)},{st.st_size},{cfg.rotate},{cfg.overall_scale}"
trimmed_version = None
trimmed = render_trimmed_copy(m, img) if m["id"] != WORLD_ID else None
if trimmed is not None:
trim_written, trim_skipped, trim_mb = write_pyramid(
trimmed, TRIMMED_TILES / m["id"], ts, zmax, min_zoom, native_level,
tw, th, pad_x, pad_y,
)
trim_stamp = stamp + "," + json.dumps(m["trim"], sort_keys=True, separators=(",", ":"))
trimmed_version = hashlib.sha1(trim_stamp.encode()).hexdigest()[:8]
print(f"[{m['id']:<17}] permanent trim: {trim_written} tiles "
f"({trim_skipped} empty), {trim_mb:.1f} MB")
return {
"id": m["id"],
"name": m["name"],
"parent": m.get("parent"),
"cell": [gx, gy],
"origin": [round(x0), round(y0)],
"size": [round(tw), round(th)],
@@ -159,7 +227,9 @@ def tile_map(cfg: Config, m: dict) -> dict:
"maxNativeZoom": native_level,
"base": m["id"] == WORLD_ID,
"version": hashlib.sha1(stamp.encode()).hexdigest()[:8],
"trimmedVersion": trimmed_version,
"pxPerMeter": m.get("pxPerMeter"),
"trim": m.get("trim"),
}
+487 -44
View File
@@ -38,6 +38,39 @@ const rectOf = (m) => L.latLngBounds(
[m.origin[1] + m.size[1], m.origin[0] + m.size[0]],
);
const trimPointsOf = (m) => (
Array.isArray(m.trim?.points) && m.trim.points.length >= 3 ? m.trim.points : null
);
// The aligned raster keeps its original rectangle, but navigation should use
// the portion the trim polygon says is actually playable/visible.
const viewRectOf = (m) => {
const points = trimPointsOf(m);
if (!points) return rectOf(m);
const xs = points.map(([x]) => x);
const ys = points.map(([, y]) => y);
return L.latLngBounds(
[m.origin[1] + Math.min(...ys) * m.size[1], m.origin[0] + Math.min(...xs) * m.size[0]],
[m.origin[1] + Math.max(...ys) * m.size[1], m.origin[0] + Math.max(...xs) * m.size[0]],
);
};
const viewContains = (m, latlng) => {
const points = trimPointsOf(m);
if (!points) return rectOf(m).contains(latlng);
const x = (latlng.lng - m.origin[0]) / m.size[0];
const y = (latlng.lat - m.origin[1]) / m.size[1];
let inside = false;
for (let i = 0, j = points.length - 1; i < points.length; j = i, i += 1) {
const [xi, yi] = points[i];
const [xj, yj] = points[j];
if ((yi > y) !== (yj > y) && x < ((xj - xi) * (y - yi)) / (yj - yi) + xi) {
inside = !inside;
}
}
return inside;
};
const centerOf = (m) => L.latLng(
m.origin[1] + m.size[1] / 2,
m.origin[0] + m.size[0] / 2,
@@ -62,10 +95,15 @@ function readHash() {
}
async function main() {
const world = await fetch('data/world.json', { cache: 'no-cache' }).then((r) => {
if (!r.ok) throw new Error(`world.json: ${r.status}`);
return r.json();
});
const [world, markerData] = await Promise.all([
fetch('data/world.json', { cache: 'no-cache' }).then((r) => {
if (!r.ok) throw new Error(`world.json: ${r.status}`);
return r.json();
}),
fetch('data/markers.json', { cache: 'no-cache' })
.then((r) => (r.ok ? r.json() : { markers: [] }))
.catch(() => ({ markers: [] })),
]);
if (!world.maps.length) throw new Error('world.json contains no maps');
const ZMAX = world.maxZoom;
@@ -113,15 +151,51 @@ async function main() {
const TOP_Z = 2 + stackOrder.length;
const layers = new Map();
const panes = new Map();
const insideLayers = new Map();
const insidePanes = new Map();
const previewGeometry = new Map(detail.map((m) => [m.id, geometryOf(m)]));
const savedTrim = (m) => ({
points: Array.isArray(m.trim?.points) ? m.trim.points.map((p) => [...p]) : [],
transparency: Number.isFinite(m.trim?.outsideTransparency)
? m.trim.outsideTransparency : 0.75,
});
const paneZ = (id, focused = false) => (
focused ? 600 + TOP_Z * 2 : 300 + baseZ.get(id) * 2
);
let updateMarkerFocus = () => {};
const focus = (id) => {
const selected = detail.find((m) => m.id === id);
const rootId = selected?.parent ?? selected?.id;
const family = rootId
? detail.filter((m) => m.id === rootId || m.parent === rootId)
: [];
updateMarkerFocus(family.map((m) => m.id));
for (const [mid, pane] of panes) {
if (mid === base.id) continue;
pane.style.zIndex = String(mid === id ? 300 + TOP_Z : 300 + baseZ.get(mid));
const familyIndex = family.findIndex((m) => m.id === mid);
let z = paneZ(mid);
if (familyIndex >= 0) z = 600 + TOP_Z * 2 + familyIndex * 2;
// A directly selected child remains the top member of its family. When
// the parent is selected, children naturally follow above it.
if (selected?.parent && mid === id) z += family.length * 2;
pane.style.zIndex = String(z);
const inside = insidePanes.get(mid);
if (inside) inside.style.zIndex = String(z + 1);
}
};
const familyViewRect = (m) => {
const own = viewRectOf(m);
const combined = L.latLngBounds(own.getSouthWest(), own.getNorthEast());
if (!m.parent) {
detail.filter((child) => child.parent === m.id)
.forEach((child) => combined.extend(viewRectOf(child)));
}
return combined;
};
const updatePreviewTransform = (m) => {
const pane = panes.get(m.id);
if (!pane) return;
@@ -133,12 +207,102 @@ async function main() {
const sx = preview.width / saved.width;
const sy = preview.height / saved.height;
const origin = map.latLngToLayerPoint(saved.center);
pane.style.transformOrigin = `${origin.x}px ${origin.y}px`;
pane.style.transform = `translate3d(${dx}px, ${dy}px, 0) scale(${sx}, ${sy})`;
for (const target of [pane, insidePanes.get(m.id)].filter(Boolean)) {
target.style.transformOrigin = `${origin.x}px ${origin.y}px`;
target.style.transform = `translate3d(${dx}px, ${dy}px, 0) scale(${sx}, ${sy})`;
}
};
const updatePreviewTransforms = () => detail.forEach(updatePreviewTransform);
const usesPermanentTrim = (m) => !m.base && !!m.trim && !!m.trimmedVersion;
const tileUrl = (m, trimmed = false) => (
`${trimmed ? 'tiles-trimmed' : 'tiles'}/${m.id}/{z}/{x}/{y}.webp`
);
const tileOptions = (m, paneName, isBase = false, version = m.version) => ({
cell: m.cell,
bounds: rectOf(m),
pane: isBase ? 'tilePane' : paneName,
version,
baseTileSize: world.tileSize,
tileSize: world.tileSize / 2 ** boost,
zoomOffset: boost,
minZoom: isBase ? 0 : m.minZoom,
maxZoom: ZMAX + ZOOM_HEADROOM,
maxNativeZoom: Math.max(0, m.maxNativeZoom - boost),
minNativeZoom: 0,
noWrap: true,
keepBuffer: isBase ? 6 : 2,
updateWhenIdle: false,
errorTileUrl: BLANK,
zIndex: isBase ? BASE_Z : baseZ.get(m.id),
className: isBase ? 'tile-base' : undefined,
});
const setLayerSource = (m, trimmed) => {
const layer = layers.get(m.id);
if (!layer) return;
const nextKind = trimmed && usesPermanentTrim(m) ? 'trimmed' : 'original';
if (layer._tarkovSource === nextKind) return;
layer._tarkovSource = nextKind;
layer.options.version = nextKind === 'trimmed' ? m.trimmedVersion : m.version;
layer.setUrl(tileUrl(m, nextKind === 'trimmed'));
};
const ensureInsideLayer = (m) => {
if (insideLayers.has(m.id)) return insideLayers.get(m.id);
const paneName = `map-${m.id}-inside`;
const pane = map.createPane(paneName);
pane.style.zIndex = String(paneZ(m.id) + 1);
pane.style.pointerEvents = 'none';
pane.style.display = 'none';
insidePanes.set(m.id, pane);
const layer = new OffsetTileLayer(
`tiles/${m.id}/{z}/{x}/{y}.webp`, tileOptions(m, paneName),
).addTo(map);
insideLayers.set(m.id, layer);
updatePreviewTransform(m);
return layer;
};
const updateTrimClip = (m, points) => {
const pane = insidePanes.get(m.id);
if (!pane || points.length < 3) return;
const projected = points.map(([x, y]) => map.latLngToLayerPoint([
m.origin[1] + y * m.size[1],
m.origin[0] + x * m.size[0],
]));
pane.style.clipPath = `polygon(${projected.map((p) => `${p.x}px ${p.y}px`).join(',')})`;
};
const renderTrim = (m, points, transparency) => {
const outside = panes.get(m.id);
if (!outside) return;
// Editing uses the untouched source plus a live preview. The normal saved
// view switches back to the separately rasterized trimmed tile pyramid.
setLayerSource(m, false);
if (points.length < 3) {
outside.style.opacity = '1';
const inside = insidePanes.get(m.id);
if (inside) inside.style.display = 'none';
return;
}
ensureInsideLayer(m);
outside.style.opacity = String(1 - transparency);
const inside = insidePanes.get(m.id);
inside.style.display = '';
updateTrimClip(m, points);
};
const restoreMapAppearance = (m) => {
if (!m || m.base) return;
panes.get(m.id).style.opacity = '1';
const inside = insidePanes.get(m.id);
if (inside) inside.style.display = 'none';
setLayerSource(m, true);
};
for (const m of world.maps) {
// The base map is the backdrop: it is a handful of tiles, always loaded,
// and Leaflet upscales it past its native level -- so a gap while detail
@@ -148,35 +312,90 @@ async function main() {
if (!isBase) {
paneName = `map-${m.id}`;
const pane = map.createPane(paneName);
pane.style.zIndex = String(300 + baseZ.get(m.id));
pane.style.zIndex = String(paneZ(m.id));
pane.style.pointerEvents = 'none';
panes.set(m.id, pane);
}
const layer = new OffsetTileLayer(`tiles/${m.id}/{z}/{x}/{y}.webp`, {
cell: m.cell,
bounds: rectOf(m),
pane: isBase ? 'tilePane' : paneName,
version: m.version,
baseTileSize: world.tileSize,
tileSize: world.tileSize / 2 ** boost,
zoomOffset: boost,
minZoom: isBase ? 0 : m.minZoom,
maxZoom: ZMAX + ZOOM_HEADROOM,
maxNativeZoom: Math.max(0, m.maxNativeZoom - boost),
minNativeZoom: 0,
noWrap: true,
keepBuffer: isBase ? 6 : 2,
updateWhenIdle: false,
errorTileUrl: BLANK,
zIndex: isBase ? BASE_Z : baseZ.get(m.id),
className: isBase ? 'tile-base' : undefined,
}).addTo(map);
const trimmed = usesPermanentTrim(m);
const version = trimmed ? m.trimmedVersion : m.version;
const layer = new OffsetTileLayer(
tileUrl(m, trimmed), tileOptions(m, paneName, isBase, version),
).addTo(map);
layer._tarkovSource = trimmed ? 'trimmed' : 'original';
layers.set(m.id, layer);
}
// --- semantic PSD markers --------------------------------------------
const markerPane = map.createPane('semantic-markers');
markerPane.style.zIndex = '900';
markerPane.style.pointerEvents = 'none';
const markerLayer = L.layerGroup();
const markerLayersByMap = new Map();
const markerSymbols = {
'extract-pmc': '↗', 'extract-scav': '↗', 'extract-neutral': '↗',
'extract-hidden': '↗', transit: 'T', spawn: 'P', scav: 'S', boss: 'B',
cultist: 'C', sniper: '△', cache: '◇', key: 'K', loot: 'L', hazard: '!',
quest: '?', location: '•', poi: '•',
};
const escapeHTML = (value) => String(value ?? '').replace(
/[&<>"']/g, (char) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[char]),
);
const markerMaps = new Map(world.maps.map((m) => [m.id, m]));
for (const marker of markerData.markers ?? []) {
const m = markerMaps.get(marker.mapId);
if (!m || !Number.isFinite(marker.x) || !Number.isFinite(marker.y)) continue;
const category = String(marker.category || 'poi').replace(/[^a-z0-9-]/gi, '');
const label = marker.label || category.replaceAll('-', ' ');
const icon = L.divIcon({
className: `poi-icon marker-${category}`,
iconSize: [18, 18],
iconAnchor: [9, 9],
html: '<span class="poi-content" aria-hidden="true">'
+ `<span class="poi-dot">${escapeHTML(markerSymbols[category] ?? '•')}</span>`
+ `<span class="poi-label">${escapeHTML(label)}</span></span>`,
});
if (!markerLayersByMap.has(m.id)) markerLayersByMap.set(m.id, L.layerGroup());
L.marker([
m.origin[1] + marker.y * m.size[1],
m.origin[0] + marker.x * m.size[0],
], { icon, pane: 'semantic-markers', interactive: false, keyboard: false })
.addTo(markerLayersByMap.get(m.id));
}
markerLayersByMap.forEach((layer) => markerLayer.addLayer(layer));
updateMarkerFocus = (mapIds) => {
const visible = new Set(mapIds);
markerLayersByMap.forEach((layer, mapId) => {
if (!visible.size || visible.has(mapId)) markerLayer.addLayer(layer);
else markerLayer.removeLayer(layer);
});
};
const markerButton = document.getElementById('toggle-markers');
let markersVisible = localStorage.getItem('tarkov-markers-visible') !== 'false';
const renderMarkerVisibility = () => {
if (markersVisible && !map.hasLayer(markerLayer)) markerLayer.addTo(map);
if (!markersVisible && map.hasLayer(markerLayer)) map.removeLayer(markerLayer);
markerButton.setAttribute('aria-pressed', String(markersVisible));
markerButton.textContent = `Markers (${markerData.markers?.length ?? 0})`;
};
markerButton.addEventListener('click', () => {
markersVisible = !markersVisible;
localStorage.setItem('tarkov-markers-visible', String(markersVisible));
renderMarkerVisibility();
});
renderMarkerVisibility();
const updateMarkerDensity = () => {
map.getContainer().classList.toggle('marker-labels-visible', map.getZoom() >= 6);
map.getContainer().classList.toggle('marker-overview', map.getZoom() < 2.5);
};
map.on('zoom zoomend', updateMarkerDensity);
updateMarkerDensity();
// --- picker -----------------------------------------------------------
const list = document.getElementById('maplist');
const editButton = document.getElementById('edit-placement');
const trimButton = document.getElementById('edit-trim');
const editorPanel = document.getElementById('placement-editor');
const editorName = document.getElementById('placement-name');
const xInput = document.getElementById('placement-x');
@@ -187,6 +406,15 @@ async function main() {
const resetButton = document.getElementById('placement-reset');
const saveButton = document.getElementById('placement-save');
const status = document.getElementById('placement-status');
const trimPanel = document.getElementById('trim-editor');
const trimName = document.getElementById('trim-name');
const trimTransparency = document.getElementById('trim-transparency');
const trimTransparencyValue = document.getElementById('trim-transparency-value');
const trimPointCount = document.getElementById('trim-point-count');
const trimUndo = document.getElementById('trim-undo');
const trimClear = document.getElementById('trim-clear');
const trimSave = document.getElementById('trim-save');
const trimStatus = document.getElementById('trim-status');
const byId = new Map(world.maps.map((m) => [m.id, m]));
const editor = {
selectedId: null,
@@ -194,6 +422,14 @@ async function main() {
marker: null,
outline: null,
};
const trimEditor = {
selectedId: null,
active: false,
points: [],
transparency: 0.75,
markers: [],
outline: null,
};
const showStatus = (message, isError = false) => {
status.textContent = message;
@@ -233,27 +469,31 @@ async function main() {
const closeEditor = () => {
const m = byId.get(editor.selectedId);
resetPreview(m);
restoreMapAppearance(m);
clearEditorLayers();
editor.active = false;
editorPanel.hidden = true;
editButton.setAttribute('aria-pressed', 'false');
editButton.textContent = editor.selectedId ? 'Edit placement' : 'Select a map to edit';
showStatus('');
};
const openEditor = (m) => {
if (!m || m.base) return;
if (trimEditor.active) closeTrimEditor();
const previous = byId.get(editor.selectedId);
if (previous && previous.id !== m.id) resetPreview(previous);
if (previous && previous.id !== m.id) {
resetPreview(previous);
restoreMapAppearance(previous);
}
clearEditorLayers();
editor.selectedId = m.id;
editor.active = true;
editorPanel.hidden = false;
editButton.disabled = false;
editButton.textContent = 'Close placement editor';
editButton.setAttribute('aria-pressed', 'true');
editorName.textContent = m.name;
showStatus('Unsaved changes stay in this preview until you save.');
setLayerSource(m, false);
const geometry = previewGeometry.get(m.id) ?? geometryOf(m);
editor.outline = L.rectangle(rectAt(geometry), {
@@ -274,30 +514,41 @@ async function main() {
}));
editor.marker.on('dragend', () => showStatus('Ready to save and rebuild.'));
writeGeometry(geometry);
panes.get(m.id).style.opacity = '0.5';
const inside = insidePanes.get(m.id);
if (inside) inside.style.display = 'none';
focus(m.id);
};
const selectTarget = (m) => {
const previous = byId.get(editor.selectedId);
if (editor.active && previous && previous.id !== m.id) resetPreview(previous);
const mode = editor.active ? 'placement' : (trimEditor.active ? 'trim' : null);
if (editor.active) closeEditor();
if (trimEditor.active) closeTrimEditor();
editor.selectedId = m.base ? null : m.id;
trimEditor.selectedId = m.base ? null : m.id;
editButton.disabled = !!m.base;
editButton.textContent = m.base ? 'Select a map to edit' : 'Edit placement';
trimButton.disabled = !!m.base;
buttons.forEach((b) => { b.dataset.selected = String(b.dataset.id === m.id); });
if (editor.active) {
if (m.base) closeEditor();
else openEditor(m);
}
if (!m.base && mode === 'placement') openEditor(m);
if (!m.base && mode === 'trim') openTrimEditor(m);
};
const targets = [base, ...world.maps.filter((m) => !m.base)];
const roots = detail.filter((m) => !m.parent);
const orderedDetail = roots.flatMap((m) => [
m,
...detail.filter((child) => child.parent === m.id),
]);
const orderedIds = new Set(orderedDetail.map((m) => m.id));
orderedDetail.push(...detail.filter((m) => !orderedIds.has(m.id)));
const targets = [base, ...orderedDetail];
const buttons = targets.map((m) => {
const b = document.createElement('button');
b.textContent = m.base ? 'Overview' : m.name;
b.dataset.id = m.id;
b.dataset.subMap = String(!!m.parent);
b.addEventListener('click', () => {
selectTarget(m);
map.flyToBounds(rectOf(m), { padding: [24, 24], duration: 0.7 });
map.flyToBounds(familyViewRect(m), { padding: [24, 24], duration: 0.7 });
if (window.matchMedia('(max-width: 640px)').matches) {
document.getElementById('panel').open = false;
}
@@ -307,11 +558,15 @@ async function main() {
});
editButton.setAttribute('aria-pressed', 'false');
editButton.textContent = 'Select a map to edit';
trimButton.setAttribute('aria-pressed', 'false');
editButton.addEventListener('click', () => {
if (editor.active) closeEditor();
else openEditor(byId.get(editor.selectedId));
});
trimButton.addEventListener('click', () => {
if (trimEditor.active) closeTrimEditor();
else openTrimEditor(byId.get(trimEditor.selectedId));
});
const applyInputs = () => {
const m = byId.get(editor.selectedId);
@@ -377,26 +632,214 @@ async function main() {
}
});
// --- playable-area trim editor ---------------------------------------
const showTrimStatus = (message, isError = false) => {
trimStatus.textContent = message;
trimStatus.dataset.error = String(isError);
};
const trimLatLngs = (m) => trimEditor.points.map(([x, y]) => L.latLng(
m.origin[1] + y * m.size[1],
m.origin[0] + x * m.size[0],
));
const normalizedPoint = (m, latlng) => {
const x = (latlng.lng - m.origin[0]) / m.size[0];
const y = (latlng.lat - m.origin[1]) / m.size[1];
if (x < 0 || x > 1 || y < 0 || y > 1) return null;
return [Math.max(0, Math.min(1, x)), Math.max(0, Math.min(1, y))];
};
const updateTrimUI = () => {
const count = trimEditor.points.length;
trimPointCount.textContent = `${count} point${count === 1 ? '' : 's'}`;
trimTransparency.value = String(Math.round(trimEditor.transparency * 100));
trimTransparencyValue.textContent = `${Math.round(trimEditor.transparency * 100)}%`;
trimUndo.disabled = count === 0;
trimClear.disabled = count === 0;
trimSave.disabled = count === 1 || count === 2;
};
const clearTrimEditorLayers = () => {
trimEditor.markers.forEach((marker) => map.removeLayer(marker));
trimEditor.markers = [];
if (trimEditor.outline) map.removeLayer(trimEditor.outline);
trimEditor.outline = null;
};
const updateTrimShape = (m) => {
const latlngs = trimLatLngs(m);
if (trimEditor.outline) {
const shape = latlngs.length >= 3 ? [...latlngs, latlngs[0]] : latlngs;
trimEditor.outline.setLatLngs(shape);
}
renderTrim(m, trimEditor.points, trimEditor.transparency);
updateTrimUI();
};
const rebuildTrimEditorLayers = (m) => {
clearTrimEditorLayers();
const latlngs = trimLatLngs(m);
if (latlngs.length) {
const shape = latlngs.length >= 3 ? [...latlngs, latlngs[0]] : latlngs;
trimEditor.outline = L.polyline(shape, {
color: '#ffcf4a',
weight: 2,
dashArray: '7 6',
interactive: false,
}).addTo(map);
}
trimEditor.markers = latlngs.map((latlng, index) => {
const marker = L.marker(latlng, {
draggable: true,
zIndexOffset: 11000,
icon: L.divIcon({ className: 'trim-vertex', iconSize: [14, 14] }),
}).addTo(map);
marker.on('drag', (event) => {
const point = normalizedPoint(m, event.target.getLatLng());
if (!point) return;
trimEditor.points[index] = point;
updateTrimShape(m);
});
marker.on('dragend', () => showTrimStatus('Ready to save.'));
return marker;
});
updateTrimShape(m);
};
function closeTrimEditor() {
const m = byId.get(trimEditor.selectedId);
clearTrimEditorLayers();
trimEditor.active = false;
trimPanel.hidden = true;
trimButton.setAttribute('aria-pressed', 'false');
restoreMapAppearance(m);
showTrimStatus('');
}
function openTrimEditor(m) {
if (!m || m.base) return;
if (editor.active) closeEditor();
clearTrimEditorLayers();
const saved = savedTrim(m);
trimEditor.selectedId = m.id;
trimEditor.active = true;
trimEditor.points = saved.points;
trimEditor.transparency = saved.transparency;
trimPanel.hidden = false;
trimButton.disabled = false;
trimButton.setAttribute('aria-pressed', 'true');
trimName.textContent = m.name;
setLayerSource(m, false);
showTrimStatus(saved.points.length
? 'Drag existing points or click the map to add more.'
: 'Add at least three points around the playable area.');
rebuildTrimEditorLayers(m);
focus(m.id);
}
trimTransparency.addEventListener('input', () => {
const m = byId.get(trimEditor.selectedId);
if (!m) return;
trimEditor.transparency = Number(trimTransparency.value) / 100;
renderTrim(m, trimEditor.points, trimEditor.transparency);
updateTrimUI();
showTrimStatus('Ready to save.');
});
trimUndo.addEventListener('click', () => {
const m = byId.get(trimEditor.selectedId);
if (!m || !trimEditor.points.length) return;
trimEditor.points.pop();
rebuildTrimEditorLayers(m);
showTrimStatus(trimEditor.points.length >= 3 ? 'Ready to save.' : 'Add at least three points.');
});
trimClear.addEventListener('click', () => {
const m = byId.get(trimEditor.selectedId);
if (!m) return;
trimEditor.points = [];
rebuildTrimEditorLayers(m);
showTrimStatus('Trim cleared. Save to restore the full map.');
});
trimSave.addEventListener('click', async () => {
const m = byId.get(trimEditor.selectedId);
if (!m || (trimEditor.points.length > 0 && trimEditor.points.length < 3)) return;
trimSave.disabled = true;
showTrimStatus('Saving and rendering a permanent trimmed copy…');
try {
const response = await fetch('api/trim', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
id: m.id,
points: trimEditor.points,
outsideTransparency: trimEditor.transparency,
}),
});
const responseText = await response.text();
let result;
try { result = JSON.parse(responseText); } catch { result = {}; }
if (!response.ok) throw new Error(
result.error || 'This server is read-only; start it with server/run.ps1 -Editable',
);
m.trim = result.trim;
m.version = result.map.version;
m.trimmedVersion = result.map.trimmedVersion;
showTrimStatus('Saved. Loading the permanent trimmed tiles…');
closeTrimEditor();
} catch (error) {
showTrimStatus(`Save failed: ${error.message}`, true);
} finally {
updateTrimUI();
}
});
map.on('click', (event) => {
if (!trimEditor.active) return;
const m = byId.get(trimEditor.selectedId);
const point = m && normalizedPoint(m, event.latlng);
if (!m || !point) {
showTrimStatus('Click inside the selected map to add a point.', true);
return;
}
trimEditor.points.push(point);
rebuildTrimEditorLayers(m);
showTrimStatus(trimEditor.points.length >= 3 ? 'Ready to save.' : 'Add at least three points.');
});
const updateAllTrimClips = () => {
if (!trimEditor.active) return;
const m = byId.get(trimEditor.selectedId);
if (m && trimEditor.points.length >= 3) updateTrimClip(m, trimEditor.points);
};
const syncUI = () => {
const c = map.getCenter();
// Smallest non-base map containing the centre wins -- Dorms beats Customs.
const hit = world.maps
.filter((m) => !m.base && rectOf(m).contains(c) && map.getZoom() >= m.minZoom)
.filter((m) => !m.base && viewContains(m, c) && map.getZoom() >= m.minZoom)
.sort((a, b) => a.size[0] * a.size[1] - b.size[0] * b.size[1])[0];
buttons.forEach((b) => b.setAttribute(
'aria-current', String(hit ? hit.id === b.dataset.id : b.dataset.id === base.id)));
focus(editor.active ? editor.selectedId : hit?.id);
focus(editor.active ? editor.selectedId : (trimEditor.active ? trimEditor.selectedId : hit?.id));
const z = Math.round(map.getZoom() * 4) / 4;
history.replaceState(null, '', `#${z}/${Math.round(c.lat)}/${Math.round(c.lng)}`);
};
map.on('moveend zoomend', syncUI);
map.on('move zoom zoomend', updatePreviewTransforms);
map.on('move zoom zoomend', () => {
updatePreviewTransforms();
updateAllTrimClips();
});
const h = readHash();
if (h) map.setView([h.y, h.x], h.z);
else map.fitBounds(rectOf(base), { padding: [10, 10] });
detail.forEach(restoreMapAppearance);
syncUI();
document.getElementById('boot').remove();
+23 -1
View File
@@ -15,7 +15,13 @@
<summary>Maps</summary>
<nav id="maplist"></nav>
<section id="placement-tools">
<button id="edit-placement" type="button" disabled>Edit placement</button>
<div class="layer-actions">
<button id="toggle-markers" type="button" aria-pressed="true">Markers</button>
</div>
<div class="editor-mode-actions">
<button id="edit-placement" type="button" disabled>Placement</button>
<button id="edit-trim" type="button" disabled>Trim area</button>
</div>
<div id="placement-editor" hidden>
<strong id="placement-name"></strong>
<p>Drag the center anchor to align this map with the overall map.</p>
@@ -34,6 +40,22 @@
</div>
<output id="placement-status" role="status"></output>
</div>
<div id="trim-editor" hidden>
<strong id="trim-name"></strong>
<p>Click around the playable boundary to add points. Drag a point to refine it.</p>
<label class="transparency-field">
Outside transparency
<input id="trim-transparency" type="range" min="0" max="100" step="1" value="75">
<output id="trim-transparency-value">75%</output>
</label>
<output id="trim-point-count">0 points</output>
<div class="placement-actions trim-actions">
<button id="trim-undo" type="button">Undo point</button>
<button id="trim-clear" type="button">Clear</button>
</div>
<button id="trim-save" type="button">Save trim</button>
<output id="trim-status" role="status"></output>
</div>
</section>
</details>
+120 -6
View File
@@ -89,6 +89,12 @@ html, body {
#maplist button[aria-current="true"]::before { content: "●"; font-size: 9px; }
#maplist button:not([aria-current="true"])::before { content: "○"; font-size: 9px; color: var(--muted); }
#maplist button[data-selected="true"] { background: #ffffff12; }
#maplist button[data-sub-map="true"] {
min-height: 40px;
padding-left: 34px;
color: #c7cdd5;
font-size: 13px;
}
/* --- interactive placement editor ---------------------------------- */
@@ -102,7 +108,8 @@ html, body {
font: inherit;
}
#edit-placement,
.layer-actions button,
.editor-mode-actions button,
.placement-actions button {
min-height: 38px;
border: 1px solid var(--line);
@@ -112,12 +119,19 @@ html, body {
cursor: pointer;
}
#edit-placement { width: 100%; }
#edit-placement:disabled { cursor: default; opacity: .45; }
#edit-placement[aria-pressed="true"] { border-color: var(--accent); color: var(--accent); }
.layer-actions { margin-bottom: 7px; }
.layer-actions button { width: 100%; min-height: 38px; }
.layer-actions button[aria-pressed="true"] { border-color: #57806a; color: var(--accent); }
.layer-actions button[aria-pressed="false"] { opacity: .65; }
.editor-mode-actions { display: flex; gap: 7px; }
.editor-mode-actions button { flex: 1; }
.editor-mode-actions button:disabled { cursor: default; opacity: .45; }
.editor-mode-actions button[aria-pressed="true"] { border-color: var(--accent); color: var(--accent); }
#placement-editor { padding-top: 10px; }
#placement-editor p { margin: 5px 0 9px; color: var(--muted); font-size: 12px; }
#placement-editor,
#trim-editor { padding-top: 10px; }
#placement-editor p,
#trim-editor p { margin: 5px 0 9px; color: var(--muted); font-size: 12px; }
.coordinate-fields,
.placement-actions {
@@ -151,6 +165,106 @@ html, body {
#placement-status { display: block; min-height: 17px; margin-top: 7px; color: var(--muted); font-size: 11px; }
#placement-status[data-error="true"] { color: #ff9b94; }
.transparency-field {
display: grid;
grid-template-columns: 1fr auto;
gap: 3px 8px;
color: var(--muted);
font-size: 11px;
}
.transparency-field input { grid-column: 1 / -1; width: 100%; accent-color: var(--accent); }
#trim-point-count,
#trim-status {
display: block;
min-height: 17px;
margin-top: 7px;
color: var(--muted);
font-size: 11px;
}
#trim-status[data-error="true"] { color: #ff9b94; }
#trim-save {
width: 100%;
min-height: 38px;
margin-top: 8px;
border: 1px solid #3f7957;
border-radius: 5px;
background: #27513a;
color: var(--text);
cursor: pointer;
}
/* --- semantic marker layer ----------------------------------------- */
.leaflet-marker-icon.poi-icon {
overflow: visible;
border: 0;
background: none;
}
.poi-content { position: absolute; inset: 0; }
.poi-dot {
position: absolute;
inset: 0;
display: grid;
place-items: center;
border: 2px solid #f5f7f8;
border-radius: 50%;
background: #3d78a8;
color: white;
font: 700 10px/1 system-ui, sans-serif;
box-shadow: 0 1px 4px #000c;
}
.poi-label {
position: absolute;
left: 21px;
top: 50%;
width: max-content;
max-width: 210px;
transform: translateY(-50%);
padding: 2px 5px;
border-radius: 3px;
background: #111820d9;
color: #f5f7f8;
font: 600 11px/1.25 system-ui, sans-serif;
letter-spacing: .01em;
text-shadow: 0 1px 2px #000;
box-shadow: 0 1px 3px #0008;
white-space: nowrap;
}
#map:not(.marker-labels-visible) .poi-label { display: none; }
#map.marker-overview .poi-icon { opacity: .7; }
#map.marker-overview .poi-dot { inset: 3px; font-size: 0; border-width: 1px; }
.marker-extract-pmc .poi-dot { background: #39946a; }
.marker-extract-scav .poi-dot { background: #d18a32; }
.marker-extract-neutral .poi-dot { background: #4a9fa5; }
.marker-extract-hidden .poi-dot { background: #7957a6; }
.marker-transit .poi-dot { background: #406fbd; }
.marker-spawn .poi-dot { background: #4f8ac7; }
.marker-scav .poi-dot { background: #c28135; }
.marker-boss .poi-dot { background: #bd3f45; }
.marker-cultist .poi-dot { background: #7552a0; }
.marker-sniper .poi-dot,
.marker-hazard .poi-dot { background: #b43c3c; }
.marker-cache .poi-dot,
.marker-loot .poi-dot { background: #8a7140; }
.marker-key .poi-dot,
.marker-quest .poi-dot { background: #9a7830; }
.marker-location .poi-dot,
.marker-poi .poi-dot { background: #5d6876; }
.trim-vertex {
width: 14px !important;
height: 14px !important;
margin: -7px 0 0 -7px !important;
border: 2px solid #ffcf4a;
border-radius: 50%;
background: #18202a;
box-shadow: 0 0 0 2px #111a;
}
.placement-anchor {
width: 28px !important;
height: 28px !important;