Place all nine maps onto a north-up geographic world canvas

The canvas is no longer an abstract grid of unrelated cells. overall.jpeg is
now the base, rotated 31 degrees so north is up, and every detail map is
scaled and positioned onto its real location. Zoom out for all of Tarkov;
zoom in and the full-resolution re3mr map takes over.

The 31 degrees was measured, not guessed: Customs' detail map is north-up
(its PSD compass confirms it) and runs 2.6:1 east-west, so solving its
259x207 zone outline for the band angle gives 31. rotate_point is verified
sub-pixel against PIL.

Adds Woods, Interchange, Reserve, Shoreline, Shoreline Resort, Lighthouse
and Streets, and moves every source under sources/<id>/.

baseGroup becomes baseLayers, a list of slash-paths. These PSDs share no
naming convention at all -- the base is variously LOCATION, Baselayer, Day,
3DRENDER, BASEMAP+2DLAYERS or Map&Art; several need more than one top-level
layer, and Woods buries its terrain three groups deep. Exports also keep
alpha now, so maps composite onto the terrain instead of sitting in opaque
rectangles.

Placement needs sub-cell precision, but tile grids stay integral only when
a map's origin is a multiple of tileSize * 2^maxZoom (131072 px). So rather
than snapping a map to the grid, the tiler pads it up-and-left to the
nearest cell boundary and visits only tiles holding content: exact
placement, integral grid, no cost. Each map is tiled to its native level
and carries a minZoom, so the overview stays cheap.

Two psd-tools failures worked around: stroke effects on empty-bbox layers
crash scikit-image (patched to skip), and psd_tools.composite exports a
function that shadows its own submodule.

Verified zoom 0-9: 10 layers, zero broken tiles.

Co-Authored-By: Claude Opus 5 <[email protected]>
This commit is contained in:
Claude committed 2026-08-08 04:02:38 -07:00
1 parent f997c2c5e2
commit e8d8738892
13 files changed
+756 -372

No files matched your search

+9 -1
View File
@@ -1,6 +1,14 @@
# Source art: hundreds of MB to >1 GB per map. Keep these on the shared
# drive, never in git. See docs/adding-a-map.md.
sources/
# ...except the overall base map: 1.3 MB, and every placement in maps.json is
# expressed relative to it, so the repo cannot build without it. Git will not
# descend into an excluded directory, so the path has to be re-included one
# level at a time.
sources/*
!sources/overall/
sources/overall/*
!sources/overall/*.jpeg
*.psd
*.psb
*.7z
+28 -18
View File
@@ -9,7 +9,13 @@ PSDs in, XYZ tile pyramid out, every map placed on one shared pannable canvas.
> **Revision 2 (2026-08-07)** — scope narrowed to **base map art only**; marker,
> spawn and label overlays are cut. Architecture changed from "one pyramid per
> map plus a switcher" to a **single shared world canvas** holding unrelated
> maps side by side. Phase 1 is built and running.
> maps side by side.
>
> **Revision 3 (2026-08-08)** — the canvas is now **geographic**. `overall.jpeg`
> is the base, rotated 31° so north is up, and every detail map is scaled and
> positioned onto its real location. Seven more maps added (Woods, Interchange,
> Reserve, Shoreline, Shoreline Resort, Lighthouse, Streets). The abstract grid
> of unrelated cells is gone.
---
@@ -67,35 +73,39 @@ Licence in both files: **CC BY-NC-SA 4.0**, "Made by re3mr.com".
| # | Decision | Notes |
| --- | --- | --- |
| A1 | Leaflet + custom `CRS.Simple`, XYZ pyramid | LatLng is `(y, x)` in world pixels at native resolution |
| A2 | **256 px tiles**, zoom 0–5, 1:1 at z5 | ~500 tiles per map; z0 is a whole-cell thumbnail |
| A2 | **256 px tiles**, world zoom 0–9 | Base map is native at z3; detail maps at z7–z9 |
| A3 | **WebP q82**, transparent padding on edge tiles | 9.8 MB for both maps combined |
| A4 | Chrome cropped away, not rebuilt | Scope is base art only, so there is no legend to rebuild |
| A5 | **Shared world canvas on an 8192 px grid** | See below — this is the core of revision 2 |
| A5 | **Geographic world canvas** on the rotated overall map | See below — the core of revision 3 |
| A6 | `maps.json` in, `web/data/world.json` out | The app hard-codes nothing about any map |
| A7 | Dependency-free static server, long cache on tiles | Caddy/nginx drop-in later if wanted |
| A8 | Pure-Python pipeline (psd-tools + Pillow) | No native binaries to install on three machines |
| A9 | `excludeLayers` escape hatch | Needed because psd-tools fills stroke-only vector shapes |
| A10 | **Coarse underlay layer per map** at `underlayZoom` (2) | Whole world = 17 tiles / 134 KB, on screen in ~120 ms; detail tiles draw over it, so loading gaps never show black |
### The world grid (A5)
### The world canvas (A5)
Each map is tiled independently, numbered from its own top-left corner. A map in
grid cell `(gx, gy)` sits at world pixel `(gx · cellSize, gy · cellSize)` where
The base is `overall.jpeg`, rotated **31°** to put north at the top. That angle
was measured rather than guessed: Customs' detail map is north-up (confirmed by
its PSD compass) and runs 2.6:1 east–west, so solving its 259 × 207 zone
outline for the band angle yields 31°. Rotation maths is verified sub-pixel
against PIL in `rotate_point`.
```
cellSize = tileSize · 2^maxZoom = 256 · 32 = 8192
```
World pixels are overall-map pixels × `overallScale` (64) — chosen so Customs
lands at almost exactly its native 7832 px. Each map's `place` gives centre and
width in **rotated** overall-map pixels; `tools/place_preview.py` draws a
gridded preview to author against.
At that cell size the tile-index shift is exactly `gx · 2^z` at every zoom —
always an integer. So `getTileUrl` converts world tile coords to a map's local
ones with integer arithmetic and no resampling.
Tile grids must stay integral: a map's tile-index offset has to be a whole
number of tiles at every zoom, which only holds when its origin is a multiple
of `tileSize · 2^maxZoom` = 131 072 px — hopeless for positioning. So rather
than moving a map onto the grid, the tiler **pads** it up-and-left to the
nearest cell boundary and visits only tiles containing content. Exact
placement, integral grid, zero padding cost.
Consequences, and the reason this design was chosen:
- Adding a map **never re-tiles another map**.
- Unrelated maps share one continuous, pannable canvas.
- A map must fit one cell (8192²). `maxZoom + 1` doubles the cell.
Current layout: Customs `(0,0)`, Customs — Dorms `(1,0)`.
Each map is tiled only to its **native level** (deepest zoom still downscaling
the source) and carries a `minZoom` below which it does not load, so the
overview is just the base map and detail fades in as you zoom.
---
+42 -20
View File
@@ -1,8 +1,11 @@
# TarkovMap
Self-hosted, mobile-friendly Escape from Tarkov map viewer. Layered PSDs go in,
a Leaflet tile pyramid comes out, and every map — related or not — sits side by
side on one shared canvas you can pan across.
a Leaflet tile pyramid comes out, and every map is placed onto one shared world
canvas — the overall satellite map, rotated so north is up.
Zoom out for the whole of Tarkov; zoom into a location and the full-resolution
re3mr map for it fades in over the terrain.
Only the **base map art** is extracted. Markers, spawns, legends, captions and
titles are dropped during the render.
@@ -59,31 +62,50 @@ web/tiles/ gitignored — generated tiles
## How the shared canvas works
Maps are placed on a grid of 8192 × 8192 px cells (`tileSize · 2^maxZoom`). At
that cell size, a map's tile indices shift into world coordinates by exactly
`cell · 2^z` at every zoom — always an integer. So each map keeps its own
locally numbered pyramid, the browser translates on the fly, and **adding a map
never re-tiles the others**.
The base is `sources/overall/overall.jpeg`, rotated **31°** so north is up. That
angle was measured, not guessed: Customs' detail map is north-up (its PSD
compass says so) and runs 2.6:1 east–west, so solving its 259 × 207 zone
outline for the band angle gives 31°.
A map must fit in one cell. Raising `maxZoom` in `maps.json` doubles the cell.
World pixels are overall-map pixels × `overallScale` (64), which puts Customs
at almost exactly its native 7832 px. Each map's `place` entry gives its centre
and width in rotated overall-map pixels, and the tiler scales it to match.
Tile grids must stay integral — a map's tile-index offset has to be a whole
number of tiles at every zoom, which only holds when its origin is a multiple
of `tileSize · 2^maxZoom` (131 072 px). Far too coarse to position anything. So
rather than *moving* a map onto the grid, the tiler **pads** it up-and-left to
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.
## No black gaps
Each map is drawn twice. Underneath sits a backdrop layer pinned to
`underlayZoom` (default 2) — Leaflet serves that one level at every view zoom,
scaled to fit. The whole world at z2 is 17 tiles / 134 KB, so it lands almost
immediately and then stays resident, and detail tiles draw over it.
Any gap while detail tiles load shows blurry map instead of the page
background. Raising `underlayZoom` sharpens the backdrop but costs a lot more
up front (z3 is 49 tiles / 471 KB) — z2 is the sweet spot.
The base map is the backdrop. It is 70 tiles / 0.2 MB, always resident, and
Leaflet upscales it past its native z3 — so any gap while detail tiles load
shows blurry terrain rather than the page background.
## Current maps
| Map | Source size | Tiled | Tiles |
| --- | --- | --- | --- |
| Customs | 7832 × 5016 | 7832 × 3015 | 503 (8.4 MB) |
| Customs — Dorms | 4301 × 4904 | 4301 × 4904 | 469 (1.4 MB) |
Base: `overall.jpeg` 1308 × 1296 → 1790 × 1786 rotated → world 114 496 × 114 240.
| Map | PSD | Base layers |
| --- | --- | --- |
| Customs | 7832 × 5016 | `LOCATION` |
| Customs — Dorms | 4301 × 4904 | `LOCATION` |
| Woods | 7680 × 5168 | `re3mr.com/Map&Art/Map&OverlayArt/{RawMapLayer,MapBlackout,WaterDetail}` |
| Interchange | 9600 × 5400 | `3DRENDER` |
| Reserve | 5760 × 3240 | `Day copy` |
| Shoreline | 5760 × 3240 | `Baselayer` |
| Shoreline — Resort | 10694 × 6016 | `BGCOLOR PATTERN`, `BASEMAP+2DLAYERS` |
| Lighthouse | 8259 × 7560 | `Day` |
| Streets of Tarkov | 7605 × 4841 | `Layer 1`, `Map - 3D map portion…` |
There is **no shared naming convention** between these PSDs — see
[docs/adding-a-map.md](docs/adding-a-map.md).
## Tile resolution and sharpness
+83 -71
View File
@@ -1,7 +1,7 @@
# Adding a map
The whole job is: point the config at a PSD, name the group that holds the map
art, pick a grid cell, build. Everything else is automatic.
Point the config at a PSD, name the layers holding the map art, say where it
goes on the world map, build. No application code changes.
Budget ~10 minutes plus render time (roughly 3 minutes per GB of PSD).
@@ -13,27 +13,36 @@ Budget ~10 minutes plus render time (roughly 3 minutes per GB of PSD).
python -m pip install -r tools/requirements.txt
```
Put the PSD under `sources/<area>/`. That directory is gitignored — source art
Put the PSD under `sources/<id>/`. That directory is gitignored — source art
lives on the shared drive, never in the repo.
---
## 1. Look at the layer tree
## 1. Find the layers holding the map art
```bash
python tools/psd_tree.py sources/customs/customs.psd
python tools/psd_tree.py sources/woods/woods.psd --depth 2
```
You are answering two questions.
**There is no naming convention.** Every re3mr map does this differently, so
you have to look each time:
**Which top-level group holds the map art?** On every re3mr map so far it is
`LOCATION`, sitting next to `OVERLAY`/`OVERLAYS`, `LEGEND` and `TITLE`. Only the
group you name gets rendered, so markers, legends, captions and titles are
dropped by construction — you never have to hide them one by one.
| Map | Base layers |
| --- | --- |
| Customs, Customs Dorms | `LOCATION` |
| Woods | `re3mr.com/Map&Art` (nested inside a wrapper group) |
| Lighthouse | `Day` (there is also a hidden `Night`) |
| Shoreline | `Baselayer` |
| Shoreline Resort | `BGCOLOR PATTERN`, `BASEMAP+2DLAYERS` |
| Interchange | `Background`, `3DRENDER` |
| Reserve | `Day copy`, `Color Fill 1`, `Group 5` |
| Streets | `Layer 1`, `Map - 3D map portion…` |
**Are there `shape` layers inside it?** Note their names. psd-tools renders a
stroke-only vector shape as a *solid fill*, which can bury the entire map under
one flat colour. These go in `excludeLayers` at step 3.
Note the two shapes this takes: several maps need **more than one** top-level
layer, and some bury the art **inside a wrapper group** (use a slash path).
Also note any `shape` layers — psd-tools renders stroke-only vector shapes as
solid fills, so they may need `excludeLayers`.
---
@@ -41,111 +50,114 @@ one flat colour. These go in `excludeLayers` at step 3.
```json
{
"id": "factory",
"name": "Factory",
"psd": "sources/factory/factory.psd",
"baseGroup": "LOCATION",
"id": "woods",
"name": "Woods",
"psd": "sources/woods/woods.psd",
"baseLayers": ["re3mr.com/Map&Art"],
"excludeLayers": [],
"crop": null,
"cell": [2, 0]
"place": { "cx": 818, "cy": 652, "w": 380 }
}
```
| Field | Meaning |
| --- | --- |
| `id` | URL-safe; becomes `web/tiles/<id>/` |
| `baseGroup` | the group from step 1 |
| `excludeLayers` | layer names to hide anywhere inside `baseGroup` |
| `baseLayers` | slash-paths from the document root; everything else is hidden |
| `excludeLayers` | layer names to hide anywhere inside the kept set |
| `crop` | `[x0, y0, x1, y1]` in PSD pixels, or `null` for the full canvas |
| `cell` | `[col, row]` on the world grid — omit it and the next free cell is used |
| `place` | where it sits on the world map — see step 4 |
| `pxPerMeter` | optional, from the map's scale bar; recorded for later use |
A map must fit inside one grid cell: **8192 × 8192 px** at the default
`maxZoom: 5`. The build fails with a clear message if it doesn't; raising
`maxZoom` by one doubles the cell.
---
## 3. Render the base layer and check it
## 3. Render the base layer and look at it
```bash
python tools/export_base.py factory
python tools/export_base.py woods
```
Open `build/factory/base.png` and actually look at it. You are checking for:
Open `build/woods/base.png` and check for:
- **large flat areas of solid colour** — a shape layer is filling. Add its name
to `excludeLayers` and re-run. (Customs needs `"Map Borders"` for exactly
this reason; without it the whole playable area renders white.)
- **leftover markers or text** — you named the wrong group, or the art has
markers nested inside the base group.
- **how much dead canvas surrounds the art** — that sets your `crop`.
to `excludeLayers`. (Customs needs `"Map Borders"`; without it the whole
playable area renders white.)
- **leftover markers, legends or titles** — wrong `baseLayers`.
- **missing terrain** — you kept the overlay group but not the art beneath it.
- **dead canvas around the art** — that sets your `crop`.
Re-run after any `maps.json` change; `export_base.py` always re-renders.
A failed map no longer aborts the batch; check the summary at the end.
---
## 4. Set the crop
## 4. Position it on the world map
Read the pixel bounds of the real map art off `base.png` and put them in
`crop`. Customs uses `[0, 860, 7832, 3875]` — the PSD reserves the top ~860 px
for the title bar and everything below y=3875 for the legend, and tiling that
empty space just makes the map awkward to pan.
The base of the canvas is `sources/overall/overall.jpeg`, rotated by
`world.rotate` (31°) so north is up. `place` is in **rotated overall-map
pixels** — the north-up image you actually look at.
If the art fills the canvas, leave `crop: null`.
```bash
python tools/place_preview.py
```
That writes `build/place-preview.png`: the rotated base with a 100 px grid and
every current `place` box drawn on it. Read the coordinates for your zone
straight off the grid, set `cx`/`cy`/`w`, re-run. The loop takes seconds
because nothing is tiled.
`w` is the map's width in overall-map pixels; height follows from the source
aspect ratio. Positions are deliberately approximate — the game's individual
maps are not drawn to match the satellite view exactly, so aim for "clearly the
right place", not pixel alignment.
---
## 5. Build and verify
```bash
python tools/build.py factory # export if stale, then tile, then manifest
python tools/preview.py 3 # stitch every map into one overview
python tools/build.py woods
```
`build/world-preview.png` shows all maps at their world positions. Confirm the
new one landed in the cell you intended and doesn't collide with a neighbour.
Then:
```bash
python server/serve.py
python tools/preview.py 4
```
and open the printed URL.
`build/world-preview.png` composites everything at its world position. Then:
```bash
pwsh server/run.ps1
```
---
## Useful variations
```bash
python tools/build.py # every map
python tools/build.py --tiles-only # re-tile after a crop change, skip the slow render
python tools/build.py --force-export # re-render even if base.png looks current
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
```
`build.py` skips the PSD render when `base.png` is newer than the PSD, so
iterating on `crop` is fast — that loop is seconds, not minutes.
Rebuilding one map never touches another map's tiles, and `world.json` keeps
entries for maps that weren't part of this run.
iterating on `place` and `crop` is seconds, not minutes.
---
## Why the grid works
## How placement works
Every map is tiled independently, numbered from its own top-left corner. The
world places a map in grid cell `(gx, gy)` at world pixel
`(gx · cellSize, gy · cellSize)`, where
World pixels are overall-map pixels × `world.overallScale` (64), chosen so the
detail maps land near their native resolution — Customs works out to almost
exactly its 7832 px source width.
```
cellSize = tileSize · 2^maxZoom = 256 · 32 = 8192
```
Tile grids have to stay integral: a map's tile-index offset must be a whole
number of tiles at every zoom, which only holds when its origin is a multiple
of `tileSize · 2^maxZoom`. That is 131 072 world pixels — far too coarse to
position anything. So rather than *moving* a map onto the grid, the tiler
**pads** it: the raster is padded up-and-left to the nearest cell boundary and
only tiles containing real content are ever visited. Exact placement, integral
grid, and the padding costs nothing.
At that cell size the tile-index shift for a cell is exactly `gx · 2^z` at
every zoom level — always a whole number. So the browser can translate world
tile coordinates into a map's local ones with integer arithmetic and no
resampling (`getTileUrl` in `web/app.js`).
That is what lets you add a map without re-tiling any other map, and what keeps
unrelated maps sharing one continuous canvas.
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.
+133 -14
View File
@@ -1,33 +1,152 @@
{
"$comment": "Single source of truth for the whole build. See docs/adding-a-map.md.",
"tileSize": 256,
"maxZoom": 5,
"gridCols": 4,
"$comment_underlayZoom": "Zoom level used for the always-on blurry backdrop that sits under the detail tiles, so loading gaps never show the page background. Every map's whole extent at this zoom is fetched up front, so keep it low: z2 is 17 tiles / 134 KB for the entire world, z3 would be 49 / 471 KB.",
"underlayZoom": 2,
"maxZoom": 9,
"attribution": "Maps by <a href=\"https://re3mr.com\" target=\"_blank\" rel=\"noopener\">re3mr.com</a> &middot; CC BY-NC-SA 4.0",
"$comment_world": "The overall map is the base everything else sits on. It is rotated by `rotate` degrees (counter-clockwise) to put north at the top; 31 deg was measured from the Customs zone outline, whose detail map is north-up and 2.6:1 east-west. `overallScale` is world pixels per overall-map pixel, set so Customs lands at its native 7832 px.",
"world": {
"image": "sources/overall/overall.jpeg",
"rotate": 31,
"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. Positions are deliberately approximate -- the game's maps do not tile exactly onto the satellite view.",
"maps": [
{
"id": "customs",
"name": "Customs",
"psd": "sources/customs/customs.psd",
"baseGroup": "LOCATION",
"excludeLayers": ["Map Borders"],
"crop": [0, 860, 7832, 3875],
"baseLayers": [
"LOCATION"
],
"excludeLayers": [
"Map Borders"
],
"crop": [
0,
860,
7832,
3875
],
"pxPerMeter": 7.39,
"cell": [0, 0]
"place": {
"cx": 952,
"cy": 960,
"w": 265
}
},
{
"id": "customs-dorms",
"name": "Customs — Dorms",
"psd": "sources/customs/customs-dorms.psd",
"baseGroup": "LOCATION",
"baseLayers": [
"LOCATION"
],
"crop": null,
"cell": [1, 0]
"place": {
"cx": 1000,
"cy": 990,
"w": 70
}
},
{
"id": "woods",
"name": "Woods",
"psd": "sources/woods/woods.psd",
"baseLayers": [
"re3mr.com/Map&Art/Map&OverlayArt/RawMapLayer",
"re3mr.com/Map&Art/Map&OverlayArt/WaterDetail"
],
"crop": null,
"place": {
"cx": 818,
"cy": 652,
"w": 380
}
},
{
"id": "interchange",
"name": "Interchange",
"psd": "sources/interchange/interchange.psd",
"baseLayers": [
"3DRENDER"
],
"crop": null,
"place": {
"cx": 1132,
"cy": 875,
"w": 95
}
},
{
"id": "reserve",
"name": "Reserve",
"psd": "sources/reserve/reserve.psd",
"baseLayers": [
"Day copy"
],
"crop": null,
"place": {
"cx": 770,
"cy": 1022,
"w": 140
}
},
{
"id": "shoreline",
"name": "Shoreline",
"psd": "sources/shoreline/shoreline.psd",
"baseLayers": [
"Baselayer"
],
"crop": null,
"place": {
"cx": 735,
"cy": 1222,
"w": 380
}
},
{
"id": "shoreline-resort",
"name": "Shoreline — Resort",
"psd": "sources/shoreline-resort/shoreline-resort.psd",
"baseLayers": [
"BGCOLOR PATTERN",
"BASEMAP+2DLAYERS"
],
"crop": null,
"place": {
"cx": 660,
"cy": 1175,
"w": 130
}
},
{
"id": "lighthouse",
"name": "Lighthouse",
"psd": "sources/lighthouse/lighthouse.psd",
"baseLayers": [
"Day"
],
"crop": null,
"place": {
"cx": 540,
"cy": 1010,
"w": 300
}
},
{
"id": "streets",
"name": "Streets of Tarkov",
"psd": "sources/streets/streets.psd",
"baseLayers": [
"Map - 3D map portion at the bottom [Update this when new basemap available]"
],
"crop": null,
"place": {
"cx": 1130,
"cy": 445,
"w": 110
}
}
]
}
File renamed without changes.

Before

Width:  |  Height:  |  Size: 1.3 MiB

After

Width:  |  Height:  |  Size: 1.3 MiB

+44 -19
View File
@@ -1,12 +1,13 @@
"""Orchestrator: maps.json -> tiles + web/data/world.json.
python tools/build.py # export (if needed) + tile everything
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 --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
than the PSD or --force-export is given.
than the PSD or --force-export is given. The base layer (`overall`) is a plain
image and is always cheap to retile.
"""
from __future__ import annotations
@@ -16,7 +17,7 @@ import sys
import export_base
import tile
from common import BUILD, DATA, ROOT, load_config
from common import BUILD, DATA, ROOT, WORLD_ID, load_config
def needs_export(m: dict, force: bool) -> bool:
@@ -33,44 +34,68 @@ def main(argv: list[str]) -> None:
ids = [a for a in argv if not a.startswith("--")]
cfg = load_config()
targets = [m for m in cfg.maps if m["id"] in ids] if ids else cfg.maps
if ids and len(targets) != len(ids):
raise SystemExit(f"unknown map id in {ids}")
world_m = tile.world_entry(cfg)
if ids:
targets = [world_m] if WORLD_ID in ids else []
targets += [m for m in cfg.maps if m["id"] in ids]
known = {m["id"] for m in cfg.maps} | {WORLD_ID}
unknown = set(ids) - known
if unknown:
raise SystemExit(f"unknown map id(s): {', '.join(sorted(unknown))}")
else:
targets = [world_m] + cfg.maps
if not tiles_only:
failed = []
for m in targets:
if needs_export(m, force):
if m["id"] == WORLD_ID:
continue
if not needs_export(m, force):
print(f"[{m['id']}] base.png up to date, skipping export")
continue
try:
export_base.export(m)
else:
print(f"[{m['id']}] base.png up to date, skipping export "
f"(--force-export to redo)")
except Exception as exc: # noqa: BLE001
failed.append(m["id"])
print(f"[{m['id']}] EXPORT FAILED -- {type(exc).__name__}: {exc}\n")
if failed:
print(f"skipping tiling for failed export(s): {', '.join(failed)}\n")
targets = [m for m in targets if m["id"] not in failed]
entries = [tile.tile_map(cfg, m) for m in targets]
entries = []
for m in targets:
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))
# The world manifest always describes every configured map, not just the
# ones rebuilt this run, so partial builds don't drop maps from the site.
# 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}
world_path = DATA / "world.json"
if world_path.exists():
for e in json.loads(world_path.read_text(encoding="utf-8")).get("maps", []):
by_id.setdefault(e["id"], e)
known = {m["id"] for m in cfg.maps}
maps = sorted((e for e in by_id.values() if e["id"] in known),
key=lambda e: (e["cell"][1], e["cell"][0]))
known = {m["id"] for m in cfg.maps} | {WORLD_ID}
maps = [e for e in by_id.values() if e["id"] in known]
# Base first so it paints underneath everything else.
maps.sort(key=lambda e: (not e.get("base"), -e["size"][0]))
ww, wh = cfg.world_size()
world = {
"tileSize": cfg.tile_size,
"maxZoom": cfg.max_zoom,
"underlayZoom": min(cfg.underlay_zoom, cfg.max_zoom),
"worldSize": [ww, wh],
"cellSize": cfg.cell_size,
"gridCols": cfg.grid_cols,
"rotate": cfg.rotate,
"overallScale": cfg.overall_scale,
"attribution": cfg.attribution,
"maps": maps,
}
DATA.mkdir(parents=True, exist_ok=True)
world_path.write_text(json.dumps(world, indent=2, ensure_ascii=False), encoding="utf-8")
print(f"\nwrote {world_path.relative_to(ROOT)} with {len(maps)} map(s)")
print(f"\nwrote {world_path.relative_to(ROOT)}: world {ww}x{wh}, {len(maps)} layer(s)")
if __name__ == "__main__":
+80 -33
View File
@@ -1,25 +1,29 @@
"""Shared helpers: config loading and the world-grid maths.
"""Shared helpers: config loading and world placement maths.
The whole project rests on one idea: every map is tiled independently, but all
maps share a single world coordinate space so they can sit side by side on one
big canvas.
Every map is tiled independently but they all share one world coordinate
space, so unrelated maps sit on a single pannable canvas.
That works because placements are snapped to a grid of `cellSize` world pixels,
where
The base of that canvas is `overall.jpeg`, rotated to put north at the top.
World pixels are overall-map pixels multiplied by `overallScale`, chosen so the
densest detail map lands at roughly its native resolution.
Alignment relies on one property: a map's tile-index offset must be a whole
number of tiles at every zoom level. That holds when a map's pyramid origin is
a multiple of
cellSize = tileSize * 2 ** maxZoom
At that cell size, a map parked in grid cell (gx, gy) has a tile-index offset of
exactly `gx * 2**z` / `gy * 2**z` at every zoom level z -- always a whole number.
So a map's own tile pyramid, numbered from its own top-left corner, drops into
the world grid with no resampling and no re-tiling of its neighbours.
Adding a map therefore never touches the tiles of any other map.
which is far too coarse to position a map with. So instead of *moving* a map to
the grid, we pad it: the raster is padded up-and-left to the nearest cell
boundary, and `tile.py` only visits tiles that actually contain content. The
map lands exactly where it should, the grid stays integral, and the padding
costs nothing.
"""
from __future__ import annotations
import json
import math
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
@@ -28,43 +32,86 @@ BUILD = ROOT / "build"
TILES = ROOT / "web" / "tiles"
DATA = ROOT / "web" / "data"
WORLD_ID = "overall"
def rotate_point(x: float, y: float, w: int, h: int, deg: float) -> tuple[float, float]:
"""Where (x, y) ends up after PIL's rotate(deg, expand=True) on a w x h image."""
th = math.radians(deg)
c, s = math.cos(th), math.sin(th)
w2 = w * abs(c) + h * abs(s)
h2 = w * abs(s) + h * abs(c)
dx, dy = x - w / 2.0, y - h / 2.0
return (dx * c + dy * s) + w2 / 2.0, (-dx * s + dy * c) + h2 / 2.0
def rotated_size(w: int, h: int, deg: float) -> tuple[int, int]:
th = math.radians(deg)
c, s = abs(math.cos(th)), abs(math.sin(th))
return round(w * c + h * s), round(w * s + h * c)
class Config:
def __init__(self, raw: dict):
self.tile_size: int = raw.get("tileSize", 256)
self.max_zoom: int = raw.get("maxZoom", 5)
self.max_zoom: int = raw.get("maxZoom", 8)
self.underlay_zoom: int = raw.get("underlayZoom", 2)
self.grid_cols: int = raw.get("gridCols", 4)
self.attribution: str = raw.get("attribution", "")
self.world: dict = raw.get("world", {})
self.maps: list[dict] = raw["maps"]
self._base_size: tuple[int, int] | None = None
# --- world geometry ------------------------------------------------
@property
def cell_size(self) -> int:
"""World pixels per grid cell. Also the largest map we can hold."""
return self.tile_size * 2**self.max_zoom
def assign_cells(self) -> None:
"""Fill in any missing `cell` by walking the grid left-to-right."""
taken = {tuple(m["cell"]) for m in self.maps if m.get("cell")}
cursor = 0
for m in self.maps:
if m.get("cell"):
continue
while (cursor % self.grid_cols, cursor // self.grid_cols) in taken:
cursor += 1
cell = (cursor % self.grid_cols, cursor // self.grid_cols)
m["cell"] = list(cell)
taken.add(cell)
@property
def rotate(self) -> float:
return float(self.world.get("rotate", 0))
def origin(self, m: dict) -> tuple[int, int]:
gx, gy = m["cell"]
return gx * self.cell_size, gy * self.cell_size
@property
def overall_scale(self) -> float:
return float(self.world.get("overallScale", 1))
def base_image_path(self) -> Path:
return ROOT / self.world["image"]
def set_base_size(self, size: tuple[int, int]) -> None:
"""Original (unrotated) overall.jpeg size, needed for placement."""
self._base_size = size
def base_size(self) -> tuple[int, int]:
if self._base_size is None:
from PIL import Image
with Image.open(self.base_image_path()) as im:
self._base_size = im.size
return self._base_size
def world_size(self) -> tuple[int, int]:
w, h = rotated_size(*self.base_size(), self.rotate)
s = self.overall_scale
return round(w * s), round(h * s)
def placement(self, m: dict) -> dict:
"""Target rect of a map in world pixels.
`place` is in ROTATED overall-map pixels -- i.e. the north-up image you
actually look at when picking positions (tools/place_preview.py renders
it with a grid). Authoring against the unrotated source is far harder
to eyeball, so the rotation is already baked in here.
"""
p = m["place"]
s = self.overall_scale
return {"cx": p["cx"] * s, "cy": p["cy"] * s, "width": p["w"] * s}
def rotated_base_size(self) -> tuple[int, int]:
return rotated_size(*self.base_size(), self.rotate)
def load_config() -> Config:
cfg = Config(json.loads(CONFIG.read_text(encoding="utf-8")))
cfg.assign_cells()
return cfg
return Config(json.loads(CONFIG.read_text(encoding="utf-8")))
def find_map(cfg: Config, map_id: str) -> dict:
+105 -40
View File
@@ -1,18 +1,25 @@
"""PSD -> flat base-map PNG.
Renders exactly one top-level group (`baseGroup` in maps.json, "LOCATION" for
every re3mr map so far) and discards everything else, so no markers, legend,
title or captions survive into the tiles.
Individual layers inside that group can be suppressed via `excludeLayers`.
That exists because psd-tools renders stroke-only vector shapes as solid
fills -- Customs' "Map Borders" group paints the whole playable area white
if it is left in. Run psd_tree.py and eyeball the output when onboarding a
new map.
Keeps only the layers named in `baseLayers` and hides everything else, so no
markers, legend, title or captions survive into the tiles.
python tools/export_base.py # every map
python tools/export_base.py customs # one map
`baseLayers` is a list of slash-separated paths from the document root:
["LOCATION"] Customs -- one top-level group
["Background", "3DRENDER"] Interchange -- base image plus render, in order
["re3mr.com/Map&Art"] Woods -- nested inside a wrapper group
The re3mr maps do NOT share a naming convention: the base group is variously
LOCATION, Baselayer, Day, 3DRENDER, BASEMAP+2DLAYERS or Map&Art, and several
maps need more than one top-level layer. Run psd_tree.py per map.
`excludeLayers` then hides individual layers by name anywhere in the kept set.
That exists because psd-tools renders stroke-only vector shapes as solid
fills -- Customs' "Map Borders" paints the whole playable area white.
Output: build/<id>/base.png (full PSD canvas, uncropped -- tile.py crops)
"""
@@ -21,39 +28,90 @@ from __future__ import annotations
import sys
import time
import importlib
from PIL import Image
from psd_tools import PSDImage
from common import BUILD, ROOT, find_map, load_config
# `psd_tools.composite` exports a function called `composite`, which shadows
# the submodule of the same name -- so import it explicitly.
_psd_composite = importlib.import_module("psd_tools.composite.composite")
Image.MAX_IMAGE_PIXELS = None
def hide(group, names: list[str], map_id: str) -> None:
"""Hide every descendant layer whose name matches one in `names`."""
def _patch_stroke_effects() -> None:
"""Skip stroke layer-effects instead of dying on them.
psd-tools feeds a zero-size array into scikit-image's rank filter when a
layer carries a stroke effect but has an empty bbox, which raises
"The parameter `image` cannot be an empty array" and kills the whole
render. Woods hits this. A missing outline is a far better outcome than no
map, and the effect is chrome we are dropping anyway.
"""
original = _psd_composite.Compositor._apply_stroke_effect
def safe(self, layer, color, shape, alpha):
try:
return original(self, layer, color, shape, alpha)
except Exception as exc: # noqa: BLE001 - third-party failure mode
print(f" (skipped stroke effect on {layer.name!r}: {type(exc).__name__})")
return None
_psd_composite.Compositor._apply_stroke_effect = safe
_patch_stroke_effects()
def apply_visibility(psd, keep: list[str], map_id: str) -> None:
"""Hide every layer that is not on the path to, or inside, a kept layer."""
kept = [tuple(p.split("/")) for p in keep]
matched: set[tuple[str, ...]] = set()
def walk(node, prefix: tuple[str, ...]):
for layer in node:
path = prefix + (layer.name,)
# Keep a layer if it *is* a target, is an ancestor of one (so the
# target is reachable), or is a descendant of one.
inside = any(path[:len(t)] == t for t in kept)
ancestor = any(t[:len(path)] == path for t in kept)
if inside:
matched.update(t for t in kept if path[:len(t)] == t)
if not (inside or ancestor):
layer.visible = False
continue
layer.visible = True
if layer.is_group():
walk(layer, path)
walk(psd, ())
for t in kept:
if t not in matched:
raise SystemExit(
f"[{map_id}] baseLayers entry {'/'.join(t)!r} matched nothing. "
f"Run: python tools/psd_tree.py <psd> --depth 2"
)
def hide(psd, names: list[str], map_id: str) -> None:
remaining = set(names)
seen: set[str] = set()
def walk(node):
for layer in node:
seen.add(layer.name)
if layer.name in remaining:
layer.visible = False
print(f"[{map_id}] excluding {layer.name!r}")
elif layer.is_group():
walk(layer)
walk(group)
# A name that matches nothing is almost always a typo, and it fails
# silently into a bad render, so say so loudly.
found = set()
def collect(node):
for layer in node:
found.add(layer.name)
if layer.is_group():
collect(layer)
collect(group)
for missing in remaining - found:
walk(psd)
for missing in remaining - seen:
print(f"[{map_id}] WARNING: excludeLayers entry {missing!r} matched nothing")
@@ -69,24 +127,19 @@ def export(m: dict) -> None:
t0 = time.time()
psd = PSDImage.open(psd_path)
wanted = m.get("baseGroup", "LOCATION")
group = next((l for l in psd if l.name == wanted), None)
if group is None:
names = ", ".join(repr(l.name) for l in psd)
raise SystemExit(f"[{m['id']}] no top-level layer named {wanted!r}. Found: {names}")
dropped = [l.name for l in psd if l.name != wanted and l.visible]
print(f"[{m['id']}] canvas {psd.size[0]}x{psd.size[1]}, rendering {wanted!r}")
print(f"[{m['id']}] dropping: {', '.join(repr(n) for n in dropped) or '(nothing)'}")
keep = m.get("baseLayers") or ([m["baseGroup"]] if m.get("baseGroup") else None)
if not keep:
raise SystemExit(f"[{m['id']}] needs baseLayers in maps.json")
print(f"[{m['id']}] canvas {psd.size[0]}x{psd.size[1]}, keeping {', '.join(map(repr, keep))}")
apply_visibility(psd, keep, m["id"])
if m.get("excludeLayers"):
hide(group, m["excludeLayers"], m["id"])
# viewport pins the result to the full canvas so every map's export shares
# the PSD's own coordinate system -- crops in maps.json stay meaningful.
img = group.composite(viewport=psd.viewbox, force=True)
img = img.convert("RGB")
hide(psd, m["excludeLayers"], m["id"])
# Keep alpha: these maps are composited onto the overall base map, so
# anything outside the map art should show the terrain underneath rather
# than an opaque white or black rectangle.
img = psd.composite(viewport=psd.viewbox, force=True).convert("RGBA")
img.save(out, "PNG", optimize=False, compress_level=1)
print(f"[{m['id']}] wrote {out.relative_to(ROOT)} "
f"{img.size[0]}x{img.size[1]} in {time.time() - t0:.0f}s\n")
@@ -95,8 +148,20 @@ def export(m: dict) -> None:
def main(argv: list[str]) -> None:
cfg = load_config()
targets = [find_map(cfg, i) for i in argv] if argv else cfg.maps
failed = []
for m in targets:
export(m)
# One unrenderable PSD shouldn't cost you the whole batch -- these
# take minutes each.
try:
export(m)
except Exception as exc: # noqa: BLE001
failed.append((m["id"], f"{type(exc).__name__}: {exc}"))
print(f"[{m['id']}] FAILED -- {type(exc).__name__}: {exc}\n")
if failed:
print("failed maps:")
for map_id, err in failed:
print(f" {map_id}: {err}")
raise SystemExit(1)
if __name__ == "__main__":
+69
View File
@@ -0,0 +1,69 @@
"""Render the rotated base map with a grid and every map's `place` box.
python tools/place_preview.py
Writes build/place-preview.png. This is the tool for positioning maps: read
coordinates straight off the grid, edit `place` in maps.json, re-run. No
tiling needed, so the loop is a couple of seconds.
Coordinates shown are ROTATED overall-map pixels, which is exactly what
`place.cx/cy/w` expect.
"""
from __future__ import annotations
from PIL import Image, ImageDraw
from common import BUILD, ROOT, load_config
Image.MAX_IMAGE_PIXELS = None
GRID = 100
def main() -> None:
cfg = load_config()
im = Image.open(cfg.base_image_path()).convert("RGB")
cfg.set_base_size(im.size)
if cfg.rotate:
im = im.rotate(cfg.rotate, expand=True, resample=Image.BICUBIC)
im = Image.eval(im, lambda v: min(255, int(v * 2.1))) # the art is very dark
w, h = im.size
d = ImageDraw.Draw(im)
for x in range(0, w, GRID):
d.line([x, 0, x, h], fill=(0, 90, 90))
d.text((x + 2, 2), str(x), fill=(0, 220, 220))
for y in range(0, h, GRID):
d.line([0, y, w, y], fill=(0, 90, 90))
d.text((2, y + 2), str(y), fill=(0, 220, 220))
for m in cfg.maps:
p = m.get("place")
if not p:
continue
src = BUILD / m["id"] / "base.png"
aspect = 0.6
if src.exists():
with Image.open(src) as s:
cw, ch = (m["crop"][2] - m["crop"][0], m["crop"][3] - m["crop"][1]) \
if m.get("crop") else s.size
aspect = ch / cw
hw = p["w"] / 2.0
hh = hw * aspect
box = [p["cx"] - hw, p["cy"] - hh, p["cx"] + hw, p["cy"] + hh]
d.rectangle(box, outline=(255, 70, 70), width=3)
d.text((box[0] + 4, box[1] + 4), m["id"], fill=(255, 255, 0))
d.line([p["cx"] - 6, p["cy"], p["cx"] + 6, p["cy"]], fill=(255, 0, 0), width=2)
d.line([p["cx"], p["cy"] - 6, p["cx"], p["cy"] + 6], fill=(255, 0, 0), width=2)
d.text((10, h - 20), f"rotate={cfg.rotate}deg north up | rotated base {w}x{h}",
fill=(0, 255, 255))
out = BUILD / "place-preview.png"
out.parent.mkdir(parents=True, exist_ok=True)
im.save(out)
print(f"wrote {out.relative_to(ROOT)} {w}x{h}")
print("place boxes use these rotated coordinates; edit maps.json and re-run")
if __name__ == "__main__":
main()
+33 -25
View File
@@ -1,10 +1,13 @@
"""Stitch built tiles into one overview PNG -- a layout sanity check.
python tools/preview.py [zoom] # default 3
python tools/preview.py [zoom] # default 4
Writes build/world-preview.png showing every map at its world position, so you
can confirm a newly added map landed in the grid cell you meant before opening
a browser.
Writes build/world-preview.png showing the base map with every detail map
composited on top at its world position, so you can confirm placements before
opening a browser.
Tile (z, x, y) sits at level pixel (x * tileSize, y * tileSize) because every
map's grid shares the world origin -- padding is baked into the indices.
"""
from __future__ import annotations
@@ -17,46 +20,51 @@ from PIL import Image
from common import BUILD, DATA, ROOT, TILES
Image.MAX_IMAGE_PIXELS = None
MAX_PX = 4000
def main() -> None:
z = int(sys.argv[1]) if len(sys.argv) > 1 else 3
world_path = DATA / "world.json"
if not world_path.exists():
raise SystemExit("web/data/world.json missing -- run tools/build.py first")
world = json.loads(world_path.read_text(encoding="utf-8"))
ts, zmax = world["tileSize"], world["maxZoom"]
if not 0 <= z <= zmax:
raise SystemExit(f"zoom must be 0..{zmax}")
z = int(sys.argv[1]) if len(sys.argv) > 1 else 4
z = max(0, min(z, zmax))
scale = 2.0 ** (z - zmax)
width = max(1, round(world["worldSize"][0] * scale))
height = max(1, round(world["worldSize"][1] * scale))
if max(width, height) > MAX_PX:
raise SystemExit(f"zoom {z} would be {width}x{height}; try a lower zoom")
def at(v: float) -> int:
return round(v * scale)
canvas = Image.new("RGBA", (width, height), (16, 18, 22, 255))
width = max(at(m["origin"][0] + m["size"][0]) for m in world["maps"])
height = max(at(m["origin"][1] + m["size"][1]) for m in world["maps"])
canvas = Image.new("RGB", (width, height), (20, 22, 26))
for m in world["maps"]:
gx, gy = m["cell"]
ox, oy = at(m["origin"][0]), at(m["origin"][1])
tdir = TILES / m["id"] / str(z)
if not tdir.exists():
print(f" {m['id']}: no tiles at z{z}, skipped")
for m in world["maps"]: # base first, already ordered by build.py
# Mirror the browser: fall back to the deepest level a map actually has
# and upscale it, so the base map still shows past its native zoom.
src_z = next((zz for zz in range(z, -1, -1) if (TILES / m["id"] / str(zz)).exists()), None)
if src_z is None:
print(f" {m['id']:<18} no tiles at or below z{z}")
continue
up = 2 ** (z - src_z)
tdir = TILES / m["id"] / str(src_z)
n = 0
for col in tdir.iterdir():
for tile in col.glob("*.webp"):
lx, ly = int(col.name), int(tile.stem)
canvas.paste(Image.open(tile).convert("RGB"),
(ox + lx * ts, oy + ly * ts))
x, y = int(col.name), int(tile.stem)
img = Image.open(tile).convert("RGBA")
if up != 1:
img = img.resize((ts * up, ts * up), Image.LANCZOS)
canvas.alpha_composite(img, (x * ts * up, y * ts * up))
n += 1
print(f" {m['id']:<16} cell {gx},{gy} world {ox},{oy} {n} tiles")
note = "" if up == 1 else f" (z{src_z} upscaled x{up})"
print(f" {m['id']:<18} origin {tuple(m['origin'])} size {tuple(m['size'])} {n} tiles{note}")
out = BUILD / "world-preview.png"
canvas.save(out)
print(f"\nwrote {out.relative_to(ROOT)} {width}x{height} (zoom {z})")
canvas.convert("RGB").save(out)
print(f"\nwrote {out.relative_to(ROOT)} {width}x{height} (zoom {z} of {zmax})")
if __name__ == "__main__":
+88 -54
View File
@@ -1,13 +1,19 @@
"""Flat PNG -> XYZ tile pyramid.
"""Place a map on the world canvas and cut it into an XYZ tile pyramid.
python tools/tile.py # every map
python tools/tile.py # every map plus the base
python tools/tile.py customs # one map
Reads build/<id>/base.png
Writes web/tiles/<id>/{z}/{x}/{y}.webp (z = 0 .. maxZoom, 1:1 at maxZoom)
Reads build/<id>/base.png (or the overall image, for the base layer)
Writes web/tiles/<id>/{z}/{x}/{y}.webp
Tile indices are local to the map's own top-left corner. The web app shifts
them into world space -- see common.py for why that shift is always exact.
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
common.py. Only tiles that actually contain content are visited, so the
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.
"""
from __future__ import annotations
@@ -15,88 +21,116 @@ from __future__ import annotations
import math
import shutil
import sys
import time
from PIL import Image
from common import BUILD, ROOT, TILES, Config, find_map, load_config
from common import BUILD, ROOT, 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 load_source(cfg: Config, m: dict) -> tuple[Image.Image, tuple[float, float, float, float]]:
"""Return (image, world rect x0,y0,x1,y1) for a map or the base layer."""
if m["id"] == WORLD_ID:
img = Image.open(cfg.base_image_path()).convert("RGB")
cfg.set_base_size(img.size)
if cfg.rotate:
img = img.rotate(cfg.rotate, expand=True, resample=Image.BICUBIC)
ww, wh = cfg.world_size()
return img, (0.0, 0.0, float(ww), float(wh))
src = BUILD / m["id"] / "base.png"
if not src.exists():
raise SystemExit(f"[{m['id']}] {src.relative_to(ROOT)} missing -- run export_base.py")
img = Image.open(src).convert("RGBA")
if m.get("crop"):
img = img.crop(tuple(m["crop"]))
pl = cfg.placement(m)
tw = pl["width"]
th = tw * img.size[1] / img.size[0]
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:
src = BUILD / m["id"] / "base.png"
if not src.exists():
raise SystemExit(f"[{m['id']}] {src.relative_to(ROOT)} missing -- run export_base.py first")
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
t0 = time.time()
img = Image.open(src).convert("RGB")
# 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)))
if m.get("crop"):
x0, y0, x1, y1 = m["crop"]
img = img.crop((x0, y0, x1, y1))
w, h = img.size
# Don't bother rendering the map when it would be a speck on screen.
min_zoom = max(0, math.ceil(zmax + math.log2(MIN_VISIBLE_PX / tw))) if tw > 0 else 0
min_zoom = min(min_zoom, native_level)
if m["id"] == WORLD_ID:
min_zoom = 0
cell = cfg.cell_size
if w > cell or h > cell:
raise SystemExit(
f"[{m['id']}] cropped size {w}x{h} exceeds the {cell}px grid cell. "
f"Raise maxZoom in maps.json (each +1 doubles the cell)."
)
gx, gy = math.floor(x0 / cell), math.floor(y0 / cell)
pad_x, pad_y = x0 - gx * cell, y0 - gy * cell
out = TILES / m["id"]
if out.exists():
shutil.rmtree(out)
ts = cfg.tile_size
written = skipped = 0
for z in range(min_zoom, native_level + 1):
s = 2.0 ** (z - zmax)
cw, ch = max(1, round(tw * s)), max(1, round(th * s))
level = img.resize((cw, ch), Image.LANCZOS)
px, py = pad_x * s, pad_y * s
for z in range(cfg.max_zoom, -1, -1):
scale = 2.0 ** (z - cfg.max_zoom)
zw, zh = max(1, round(w * scale)), max(1, round(h * scale))
level = img if z == cfg.max_zoom else img.resize((zw, zh), Image.LANCZOS)
for ty in range(math.ceil(zh / ts)):
for tx in range(math.ceil(zw / ts)):
box = (tx * ts, ty * ts, min((tx + 1) * ts, zw), min((ty + 1) * ts, zh))
piece = level.crop(box)
if piece.size == (ts, ts):
tile = piece # interior tile, stays opaque RGB
else:
# Edge tile: pad to a full square with transparency rather
# than letting the browser stretch a short tile.
tile = Image.new("RGBA", (ts, ts), (0, 0, 0, 0))
tile.paste(piece, (0, 0))
if not tile.getbbox():
skipped += 1
continue
tx0, tx1 = math.floor(px / ts), math.ceil((px + cw) / ts)
ty0, ty1 = math.floor(py / ts), math.ceil((py + ch) / ts)
for ty in range(ty0, ty1):
for tx in range(tx0, tx1):
tile = Image.new("RGBA", (ts, ts), (0, 0, 0, 0))
tile.paste(level, (round(px - tx * ts), round(py - ty * ts)))
if not tile.getbbox():
skipped += 1
continue
dst = out / str(z) / str(tx)
dst.mkdir(parents=True, exist_ok=True)
tile.save(dst / f"{ty}.webp", **WEBP)
# Fully-opaque interior tiles don't need an alpha channel.
flat = tile.convert("RGB") if tile.getchannel("A").getextrema()[0] == 255 else tile
flat.save(dst / f"{ty}.webp", **WEBP)
written += 1
size_mb = sum(f.stat().st_size for f in out.rglob("*.webp")) / 1e6
print(f"[{m['id']}] {w}x{h} -> {written} tiles ({skipped} empty skipped), "
f"{size_mb:.1f} MB, {time.time() - t0:.0f}s")
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")
ox, oy = cfg.origin(m)
return {
"id": m["id"],
"name": m["name"],
"cell": m["cell"],
"origin": [ox, oy],
"size": [w, h],
"cell": [gx, gy],
"origin": [round(x0), round(y0)],
"size": [round(tw), round(th)],
"minZoom": min_zoom,
"maxNativeZoom": native_level,
"base": m["id"] == WORLD_ID,
"pxPerMeter": m.get("pxPerMeter"),
}
def world_entry(cfg: Config) -> dict:
return {"id": WORLD_ID, "name": "Tarkov", "place": None, **cfg.world}
def main(argv: list[str]) -> list[dict]:
cfg = load_config()
targets = [find_map(cfg, i) for i in argv] if argv else cfg.maps
if argv:
targets = [world_entry(cfg) if i == WORLD_ID else find_map(cfg, i) for i in argv]
else:
targets = [world_entry(cfg)] + cfg.maps
return [tile_map(cfg, m) for m in targets]
+42 -77
View File
@@ -1,39 +1,26 @@
/* Tarkov Maps -- every map on one shared canvas.
*
* Coordinates: LatLng is (y, x) in *world pixels* at native resolution.
* A map placed in grid cell (gx, gy) occupies the world rectangle
* [gx*cellSize, gy*cellSize] .. [+width, +height]. Because cellSize is
* tileSize * 2**maxZoom, the tile-index shift for a cell is exactly
* cell * 2**z at every zoom -- so each map keeps its own locally numbered
* pyramid and we translate on the way out in getTileUrl().
* The base layer is the overall satellite map, rotated so north is up. Every
* detail map is scaled and positioned onto it, so zooming into Customs on the
* world map lands you in the full-resolution re3mr Customs map.
*
* Coordinates: LatLng is (y, x) in *world pixels* at native resolution, where
* one world pixel is 1/overallScale of an overall-map pixel. Each map's tiles
* are numbered from its own padded cell origin -- see tools/common.py.
*/
const ZOOM_HEADROOM = 2; // how far past 1:1 the user may zoom
const ZOOM_HEADROOM = 1; // how far past a layer's native detail we allow
const ZOOM_SNAP = 0.25;
const BLANK = 'data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs=';
/* Pixel density.
*
* Leaflet picks its tile level with Math.round(mapZoom), so at zoom 2.25 it
* takes level 2 and stretches it 1.19x. Multiply that by a devicePixelRatio
* of 1.5 and each source pixel covers ~1.8 device pixels -- visibly soft.
*
* DENSITY_BOOST fixes it by halving the CSS size of a tile and asking for one
* level deeper, so we downscale a denser level instead of upscaling a coarser
* one. Costs ~4x the tiles in view, which at ~17 KB each is a fair trade.
*
* Worth it whenever the screen is not 1:1, or whenever fractional zoom can
* land us between levels. Both are true almost everywhere.
*/
const DENSITY_BOOST =
(window.devicePixelRatio > 1.05 || ZOOM_SNAP < 1) ? 1 : 0;
/* Leaflet picks its tile level with Math.round(mapZoom), so at zoom 2.25 it
* takes level 2 and stretches it 1.19x; on a 1.5x display that compounds to a
* visibly soft 1.78x upscale. Halving a tile's CSS size and asking for one
* level deeper makes us downscale a denser level instead. */
const DENSITY_BOOST = (window.devicePixelRatio > 1.05 || ZOOM_SNAP < 1) ? 1 : 0;
const OffsetTileLayer = L.TileLayer.extend({
getTileUrl(coords) {
// Tiles are numbered from each map's own top-left corner, so shift world
// tile coordinates into the map's local grid. A grid cell spans
// baseTileSize * 2**z pixels at this level; divided by the layer's own
// tile size that is always a whole number of tiles, boost or no boost.
const o = this.options;
const perCell = (o.baseTileSize * 2 ** coords.z) / o.tileSize;
return L.Util.template(this._url, {
@@ -61,22 +48,18 @@ async function main() {
if (!r.ok) throw new Error(`world.json: ${r.status}`);
return r.json();
});
if (!world.maps.length) throw new Error('world.json contains no maps');
const ZMAX = world.maxZoom;
const base = world.maps.find((m) => m.base) ?? world.maps[0];
// CRS where one LatLng unit == one source pixel at zoom ZMAX, y pointing
// down so world coordinates read the same way as image coordinates.
const CRS = L.extend({}, L.CRS.Simple, {
transformation: new L.Transformation(1, 0, 1, 0),
scale: (z) => 2 ** (z - ZMAX),
zoom: (s) => Math.log(s) / Math.LN2 + ZMAX,
});
const extent = world.maps.reduce(
(acc, m) => (acc ? acc.extend(rectOf(m)) : rectOf(m)), null,
);
const extent = L.latLngBounds([0, 0], [world.worldSize[1], world.worldSize[0]]);
const map = L.map('map', {
crs: CRS,
@@ -85,7 +68,7 @@ async function main() {
zoomSnap: ZOOM_SNAP,
zoomDelta: 0.5,
wheelPxPerZoomLevel: 90,
maxBounds: extent.pad(0.08),
maxBounds: extent.pad(0.05),
maxBoundsViscosity: 0.75,
attributionControl: false,
});
@@ -94,62 +77,41 @@ async function main() {
.addAttribution(world.attribution)
.addTo(map);
const UNDERLAY_Z = Math.min(world.underlayZoom ?? 2, ZMAX);
const boost = DENSITY_BOOST;
// With the boost on, a level-N request is served by the level-(N+1) files,
// so the deepest level we may ask Leaflet for is one shallower.
const boost = Math.min(DENSITY_BOOST, ZMAX, UNDERLAY_Z);
for (const m of world.maps) {
const url = `tiles/${m.id}/{z}/{x}/{y}.webp`;
const common = {
for (const [i, m] of world.maps.entries()) {
// 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
// tiles load shows blurry terrain rather than the page background.
const isBase = !!m.base;
new OffsetTileLayer(`tiles/${m.id}/{z}/{x}/{y}.webp`, {
cell: m.cell,
bounds: rectOf(m),
baseTileSize: world.tileSize,
tileSize: world.tileSize / 2 ** boost,
zoomOffset: boost,
minZoom: 0,
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,
};
// Backdrop. Pinning min and max native zoom to the same low level makes
// Leaflet serve that level at every view zoom, scaled to fit -- the whole
// world is a handful of tiles, so it lands almost immediately and then
// stays put. Detail tiles draw over it, and any gap between them shows
// blurry map instead of the page background.
new OffsetTileLayer(url, {
...common,
minNativeZoom: UNDERLAY_Z - boost,
maxNativeZoom: UNDERLAY_Z - boost,
keepBuffer: 8 * 2 ** boost,
updateWhenIdle: false,
updateWhenZooming: false,
zIndex: 1,
className: 'tile-underlay',
}).addTo(map);
new OffsetTileLayer(url, {
...common,
maxNativeZoom: ZMAX - boost,
// Small on purpose: boosted tiles are half-size, so a wide buffer costs
// 4x the requests, and the underlay already covers anything a pan
// outruns.
keepBuffer: 2,
updateWhenIdle: false,
zIndex: 2,
zIndex: isBase ? 1 : 2 + i,
className: isBase ? 'tile-base' : undefined,
}).addTo(map);
}
// --- picker -----------------------------------------------------------
const list = document.getElementById('maplist');
const buttons = world.maps.map((m) => {
const targets = [base, ...world.maps.filter((m) => !m.base)];
const buttons = targets.map((m) => {
const b = document.createElement('button');
b.textContent = m.name;
b.textContent = m.base ? 'Overview' : m.name;
b.dataset.id = m.id;
b.addEventListener('click', () => {
map.flyToBounds(rectOf(m), { padding: [20, 20], duration: 0.6 });
map.flyToBounds(rectOf(m), { padding: [24, 24], duration: 0.7 });
if (window.matchMedia('(max-width: 640px)').matches) {
document.getElementById('panel').open = false;
}
@@ -160,23 +122,26 @@ async function main() {
const syncUI = () => {
const c = map.getCenter();
const active = world.maps.find((m) => rectOf(m).contains(c));
buttons.forEach((b) => b.setAttribute('aria-current', String(active?.id === b.dataset.id)));
// 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)
.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)));
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);
// --- initial view -----------------------------------------------------
const h = readHash();
if (h) map.setView([h.y, h.x], h.z);
else map.fitBounds(rectOf(world.maps[0]), { padding: [20, 20] });
else map.fitBounds(rectOf(base), { padding: [10, 10] });
syncUI();
document.getElementById('boot').remove();
window.tarkovMap = map; // handy from the console when checking a new map
window.tarkovMap = map;
window.tarkovWorld = world;
}