Files
lucioandClaude Fable 5 472c983287 Commit build outputs via LFS; right-click markers, inline edit box, panel pin
Make a fresh clone servable after `git lfs pull` alone, and rebuildable with
`tools/build.py` without re-rendering unchanged PSDs:

- Track build/ (rendered base PNGs, previews, world composites), web/tiles/,
  web/tiles-trimmed/, web/data/world.json and web/data/markers/. Large PNGs
  and the tile pyramids go through Git LFS (.gitattributes); JSON stays plain.
- build.py: decide PSD re-export from build/<id>/base.stamp.json (PSD size,
  mtime, SHA-256 recorded at export time) instead of file mtimes, which are
  meaningless after an LFS checkout. Same size + new mtime hashes once and
  refreshes the stamp; --stamp-only writes stamps for existing base.pngs.
- Ignore .DS_Store and .env files; track sources/**/*.jpg through LFS.

Viewer:
- Right-click (long-press) the map for a category menu that drops a draft
  marker under the pointer and enters marker edit mode for that map.
- Marker editing moves out of the side panel into a box anchored next to the
  marker: Enter or a left click anywhere else saves, Esc cancels, Delete
  inside the box; drags save position plus the box contents.
- Maps panel expands on hover, header click pins/unpins (status shown in the
  header), unpinned collapses 2 s after the pointer leaves; Overview is the
  first list entry instead of a separate button. Only the panel scrolls; the
  page never grows past the viewport. Hover tooltips render above markers.

Also includes the pending source additions (overall square base, skirt
textures, AI regeneration tooling and notes), service worker, Caddyfile and
map config updates.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-22 09:46:02 -07:00

515 lines
21 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
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
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. 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, ImageChops, ImageColor, ImageDraw, ImageFilter
from common import BUILD, ROOT, TILES, TRIMMED_TILES, WORLD_ID, Config, find_map, load_config
Image.MAX_IMAGE_PIXELS = None
# q78 is ~15-20 % smaller than the previous q82 at no visible cost on map art
# (Customs: 8.8 -> ~7.3 KB per tile), and every byte saved here is paid back on
# every slow connection. Method 5 encodes as fast as 4 (~4-6 ms per tile).
# Do NOT use method 6: on tiles with alpha it is ~60x slower (240 ms per tile,
# a 40-minute re-tile) for no size gain over 5.
WEBP = {"format": "WEBP", "quality": 78, "method": 5}
def minimum_zoom(m: dict, zmax: int, native_level: int) -> int:
"""First zoom at which a detail layer may be shown and requested.
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
configured = m.get("minZoom")
if configured is None:
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}"
)
if configured > native_level:
raise SystemExit(
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 configured
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 = pl["height"] if pl["height"] is not None else 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 background_settings(m: dict) -> dict | None:
"""Normalised `background` config, or None when the map has none."""
raw = m.get("background")
if not raw:
return None
if isinstance(raw, str):
raw = {"color": raw}
color = ImageColor.getrgb(str(raw["color"]))[:3]
return {
"color": color,
"halo": max(0, int(raw.get("halo", 48))),
"opacity": min(1.0, max(0.0, float(raw.get("opacity", 1.0)))),
}
def apply_background(m: dict, img: Image.Image) -> Image.Image:
"""Bake a solid colour under the artwork -- only where there is artwork.
Floor plans (Factory, Labyrinth) are drawn on transparency and become
unreadable over the satellite terrain. A rectangle behind the whole map
is ugly, so the fill follows the art instead: the alpha mask is grown by
`halo` source pixels and feathered over the same distance, then filled
with `color` at `opacity` and composited *under* the art. Gaps between
floors and the empty margins stay transparent.
"""
settings = background_settings(m)
if settings is None:
return img
rgba = img.convert("RGBA")
alpha = rgba.getchannel("A")
# Work on a 1/8 mask: PIL's MaxFilter is O(k^2) per pixel, far too slow
# at full resolution, and the halo edge is feathered anyway.
shrink = 8
small = alpha.resize(
(max(1, alpha.width // shrink), max(1, alpha.height // shrink)), Image.BOX,
).point(lambda a: 255 if a > 8 else 0)
grow = settings["halo"] // shrink
if grow:
small = small.filter(ImageFilter.MaxFilter(grow * 2 + 1))
small = small.filter(ImageFilter.GaussianBlur(max(1, grow / 2)))
mask = small.resize(alpha.size, Image.BILINEAR)
if settings["opacity"] < 1:
mask = mask.point(lambda a: round(a * settings["opacity"]))
fill = Image.new("RGBA", rgba.size, settings["color"] + (0,))
fill.putalpha(mask)
return Image.alpha_composite(fill, rgba)
# Bump when render_skirt's output changes for the same inputs, so rebuilt
# trimmed tiles get fresh URLs (they are cached immutable for a year).
SKIRT_RENDER_VERSION = 5
def skirt_settings(m: dict) -> dict | None:
"""Normalised `skirt` config (see tools/skirt.py), or None."""
raw = m.get("skirt")
if not raw:
return None
mode = raw.get("mode", "tile")
img_path = None
if raw.get("image"):
img_path = ROOT / raw["image"]
if not img_path.exists():
raise SystemExit(f"[{m['id']}] skirt texture {raw['image']} missing -- run tools/skirt.py {m['id']}")
elif mode == "aligned":
# Search for available unified world composite
for cand in [BUILD / "world" / "unified-z6.png", BUILD / "world" / "unified-z5.png",
BUILD / "world" / "composite-z6.png", BUILD / "world" / "composite-z5.png",
ROOT / "sources" / "overall" / "overall-square.png"]:
if cand.exists():
img_path = cand
break
if img_path is None:
return None
else:
return None
return {
"mode": mode,
"image": img_path,
"scale": float(raw.get("scale", 0.6)),
"featherIn": max(0, int(raw.get("featherIn", 80))),
"fadeOut": min(0.5, max(0.0, float(raw.get("fadeOut", 0.12)))),
"matchColours": bool(raw.get("matchColours", True)),
# Slight blur at map scale: a backdrop should recede, and WebP
# compresses soft grass ~2x better than crisp grass.
"soften": max(0.0, float(raw.get("soften", 1.5))),
}
def _match_colours(texture: Image.Image, reference: Image.Image, mask: Image.Image,
strength: float = 0.7) -> Image.Image:
"""Pull the texture's per-channel mean/std toward the reference's.
Statistics are taken only where `mask` is set (the band just inside the
playable polygon), on a 256 px thumbnail. `strength` < 1 keeps some of
the texture's own character and avoids over-correcting toward water or
shadow-heavy edges.
"""
import statistics
def masked_stats(im: Image.Image, m: Image.Image | None):
small = im.convert("RGB").resize((256, 256), Image.BOX)
keep = None
if m is not None:
keep = [v > 127 for v in m.resize((256, 256), Image.BOX).getdata()]
out = []
for channel in small.split():
data = list(channel.getdata())
if keep is not None:
data = [v for v, k in zip(data, keep) if k]
if len(data) < 16:
data = list(channel.getdata())
out.append((statistics.fmean(data), max(1.0, statistics.pstdev(data))))
return out
t_stats = masked_stats(texture, None)
r_stats = masked_stats(reference, mask)
channels = []
for channel, (tm, ts), (rm, rs) in zip(texture.convert("RGB").split(), t_stats, r_stats):
gain = min(1.6, max(0.6, rs / ts))
gain = 1 + (gain - 1) * strength
shift = (rm - tm) * strength
lut = [max(0, min(255, round((v - tm) * gain + tm + shift))) for v in range(256)]
channels.append(channel.point(lut))
return Image.merge("RGB", channels)
def _seamless(texture: Image.Image, blend: float = 0.28) -> Image.Image:
"""Offset-and-blend: shift by half, then crossfade the seams with the
original over `blend` of the size, so opposite edges match."""
w, h = texture.size
rolled = ImageChops.offset(texture, w // 2, h // 2)
bw, bh = max(2, round(w * blend)), max(2, round(h * blend))
# Weight 1 near the (now central) seam lines, 0 away from them.
mask = Image.new("L", (w, h), 0)
draw = ImageDraw.Draw(mask)
import math
for i in range(bw):
a = round(255 * (0.5 + 0.5 * math.cos(math.pi * i / bw)))
draw.line([(w // 2 - i, 0), (w // 2 - i, h)], fill=a)
draw.line([(w // 2 + i, 0), (w // 2 + i, h)], fill=a)
vmask = Image.new("L", (w, h), 0)
vdraw = ImageDraw.Draw(vmask)
for i in range(bh):
a = round(255 * (0.5 + 0.5 * math.cos(math.pi * i / bh)))
vdraw.line([(0, h // 2 - i), (w, h // 2 - i)], fill=a)
vdraw.line([(0, h // 2 + i), (w, h // 2 + i)], fill=a)
mask = ImageChops.lighter(mask, vmask)
# The rolled image has its seams in the middle; covering them with the
# original (continuous there) over the feathered mask hides them, and the
# result's outer edges are the rolled image's -- which meet seamlessly.
return Image.composite(texture, rolled, mask)
def render_skirt(cfg: Config, m: dict, rgba: Image.Image, polygon, skirt: dict) -> Image.Image:
"""Replace everything outside the playable polygon with the skirt texture or aligned world terrain.
In "aligned" mode, cuts the surrounding ring directly out of the unified world composite.
In "tile" mode, mirror-tiles the texture with color matching.
"""
width, height = rgba.size
if skirt.get("mode") == "aligned":
unified = Image.open(skirt["image"]).convert("RGB")
uw, uh = unified.size
ww, wh = cfg.world_size()
sx, sy = uw / ww, uh / wh
pl = cfg.placement(m)
tw = pl["width"]
th = pl["height"] if pl["height"] is not None else tw * height / width
x0 = pl["cx"] - tw / 2.0
y0 = pl["cy"] - th / 2.0
ux0 = max(0, min(uw - 1, round(x0 * sx)))
uy0 = max(0, min(uh - 1, round(y0 * sy)))
ux1 = max(ux0 + 1, min(uw, round((x0 + tw) * sx)))
uy1 = max(uy0 + 1, min(uh, round((y0 + th) * sy)))
crop = unified.crop((ux0, uy0, ux1, uy1))
canvas = crop.resize((width, height), Image.LANCZOS)
if skirt["soften"] > 0:
canvas = canvas.filter(ImageFilter.GaussianBlur(skirt["soften"]))
else:
texture = Image.open(skirt["image"]).convert("RGB")
tw = max(64, round(texture.width * skirt["scale"]))
th = max(64, round(texture.height * skirt["scale"]))
texture = texture.resize((tw, th), Image.LANCZOS)
if skirt["soften"] > 0:
texture = texture.filter(ImageFilter.GaussianBlur(skirt["soften"]))
# Playable mask and a band just inside it, for colour matching.
inside = Image.new("L", (width, height), 0)
ImageDraw.Draw(inside).polygon(polygon, fill=255)
if skirt["matchColours"]:
shrink = 8
small = inside.resize((max(1, width // shrink), max(1, height // shrink)), Image.BOX)
eroded = small.filter(ImageFilter.MinFilter(13)).resize((width, height), Image.NEAREST)
band = ImageChops.subtract(inside, eroded)
bbox = band.getbbox()
if bbox:
texture = _match_colours(texture, rgba.crop(bbox), band.crop(bbox))
# Make the texture seamless, then tile with varying flips
texture = _seamless(texture)
variants = [
texture,
texture.transpose(Image.FLIP_LEFT_RIGHT),
texture.transpose(Image.FLIP_TOP_BOTTOM),
texture.transpose(Image.ROTATE_180),
]
canvas = Image.new("RGB", (width, height))
for ty, y in enumerate(range(0, height, th)):
for tx, x in enumerate(range(0, width, tw)):
canvas.paste(variants[(tx * 7 + ty * 13 + (tx * ty) % 5) % 4], (x, y))
inside = Image.new("L", (width, height), 0)
ImageDraw.Draw(inside).polygon(polygon, fill=255)
# Skirt alpha: 1 everywhere, fading to 0 toward the rectangle edge.
fade = round(min(width, height) * skirt["fadeOut"])
skirt_alpha = Image.new("L", (width, height), 255)
if fade > 0:
ramp = ImageDraw.Draw(skirt_alpha)
for i in range(fade):
a = round(255 * i / fade)
ramp.rectangle((i, i, width - 1 - i, height - 1 - i), outline=a)
skirt_rgba = canvas.convert("RGBA")
skirt_rgba.putalpha(skirt_alpha)
# Art alpha: original alpha inside the polygon, soft-cut over featherIn.
cut = inside
if skirt["featherIn"] > 0:
shrink = 4
cut = inside.resize((max(1, width // shrink), max(1, height // shrink)), Image.BOX)
cut = cut.filter(ImageFilter.GaussianBlur(skirt["featherIn"] / shrink / 2)).resize((width, height), Image.BILINEAR)
art = rgba.copy()
art.putalpha(ImageChops.multiply(rgba.getchannel("A"), cut))
return Image.alpha_composite(skirt_rgba, art)
def render_trimmed_copy(cfg: Config, m: dict, img: Image.Image) -> Image.Image | None:
"""Bake the saved playable polygon into a separate RGBA source image.
``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
rgba = img.convert("RGBA")
width, height = rgba.size
polygon = [
(round(float(x) * (width - 1)), round(float(y) * (height - 1)))
for x, y in points
]
skirt = skirt_settings(m)
if skirt is not None:
rgba = render_skirt(cfg, m, rgba, polygon, skirt)
else:
outside_alpha = round(255 * (1 - float(trim.get("outsideTransparency", 0.75))))
mask = Image.new("L", rgba.size, outside_alpha)
ImageDraw.Draw(mask).polygon(polygon, fill=255)
rgba.putalpha(ImageChops.multiply(rgba.getchannel("A"), mask))
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
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)
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
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)
if m["id"] != WORLD_ID:
img = apply_background(m, img)
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.
# 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}"
# The baked backdrop changes the imagery without touching base.png.
stamp += "," + json.dumps(background_settings(m), sort_keys=True)
else:
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(cfg, 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=(",", ":"))
skirt = skirt_settings(m)
if skirt is not None:
st = skirt["image"].stat()
trim_stamp += "," + json.dumps(
{**skirt, "image": skirt["image"].name, "mtime": int(st.st_mtime),
"size": st.st_size, "render": SKIRT_RENDER_VERSION},
sort_keys=True, default=str,
)
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)],
"minZoom": min_zoom,
"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"),
}
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:])