Tile paths are stable across rebuilds but their contents are not: moving a map's `place` makes tiles/<id>/6/17/33.webp different imagery at the same URL. Combined with the immutable week-long cache added earlier, a browser that had seen an older build blended the two and drew duplicated, offset terrain -- visible as a second copy of Lighthouse. Each map now carries a `version` in world.json, hashed from its geometry, zoom range and source file stamp, and appended to every tile URL as ?v=. Re-tiled maps get fresh URLs; identical rebuilds keep the same version so nothing is re-fetched needlessly. Also corrects the runbook's base-layer table, which still listed the pre-correction layers for Woods, Reserve, Interchange and Streets. Verified: 733 tiles across seven map views, all carrying ?v=, zero broken, and the focused map topmost in every case. Co-Authored-By: Claude Opus 5 <[email protected]>
154 lines
5.9 KiB
Python
154 lines
5.9 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 hashlib
|
|
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")
|
|
|
|
# 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.
|
|
# Since tiles are served immutable for a week, a browser that saw the old
|
|
# build would blend it with the new one. This version stamp goes into the
|
|
# URL so a rebuilt map simply gets fresh URLs.
|
|
stamp = f"{x0:.1f},{y0:.1f},{tw:.1f},{th:.1f},{min_zoom},{native_level},{written}"
|
|
if m["id"] != WORLD_ID:
|
|
st = (BUILD / m["id"] / "base.png").stat()
|
|
stamp += f",{int(st.st_mtime)},{st.st_size}"
|
|
else:
|
|
st = cfg.base_image_path().stat()
|
|
stamp += f",{int(st.st_mtime)},{st.st_size},{cfg.rotate},{cfg.overall_scale}"
|
|
|
|
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,
|
|
"version": hashlib.sha1(stamp.encode()).hexdigest()[:8],
|
|
"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:])
|