Files
TarkovMaps/tools/tile.py
T
Claude e8d8738892 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]>
2026-08-08 04:02:38 -07:00

139 lines
5.1 KiB
Python

"""Place a map on the world canvas and cut it into an XYZ tile pyramid.
python tools/tile.py # every map plus the base
python tools/tile.py customs # one map
Reads build/<id>/base.png (or the overall image, for the base layer)
Writes web/tiles/<id>/{z}/{x}/{y}.webp
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
import math
import shutil
import sys
from PIL import Image
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:
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)))
# 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
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)
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
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)
# 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 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 {
"id": m["id"],
"name": m["name"],
"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()
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]
if __name__ == "__main__":
main(sys.argv[1:])