Add per-map editable markers and backups

This commit is contained in:
lucio committed 2026-08-08 22:03:49 -07:00
1 parent e71447da5d
commit bbb4cadddd
23 files changed
+11090 -129

No files matched your search

+320 -45
View File
@@ -11,6 +11,8 @@ HTML/CSS style.
from __future__ import annotations
from collections import Counter
import hashlib
import json
import re
import sys
@@ -20,10 +22,15 @@ from psd_tools import PSDImage
from common import DATA, ROOT, find_map, load_config
CONTEXT = ("overlay", "onmap", "on map", "map marker", "mapmarker", "extractinformation")
CONTEXT = (
"overlay", "onmap", "on map", "map marker", "mapmarker",
"extractinformation", "extractnames", "extractmarkers",
)
EXCLUDED = (
"legend", "credit", "title section", "raid detail", "compass", "coloredmarkers",
"colored markers", "mapinfo", "duration", "version",
"colored markers", "mapinfo", "duration", "sideindicator",
"side indicator", "extract letter overlay", "description", "requirement",
"only for bw", "onlyforbw",
)
LEAF_KINDS = {"type", "smartobject", "pixel"}
GENERIC = re.compile(
@@ -39,6 +46,38 @@ CATEGORY_LABELS = {
"cache": "Cache", "key": "Key", "loot": "Loot", "hazard": "Hazard",
"quest": "Quest", "location": "Location", "poi": "Point of interest",
}
LABEL_CORRECTIONS = {
"holeinthefence": "HOLE IN THE FENCE",
"powerstation v-ex": "POWER STATION V-EX",
"pier boat": "PIER BOAT",
}
MAP_CATEGORY_OVERRIDES = {
("reserve", "sewer manhole"): "extract-pmc",
}
EXTRACT_CATEGORIES = {
"extract-pmc", "extract-scav", "extract-neutral", "extract-hidden", "transit",
}
EXTRACT_LABEL_PATHS = (
"overlay captions", "extract name text / extract text pmc",
"extract name text / extract text scav", "extract name text / extract text neutral",
"extract name text / transit text", "onmap exfil names / text",
"new onmap / exfil names", "on map extract text", "extract names / pmc",
"extract names / scav", "extract names / neutral", "extract names / transit",
"on map overlay / extracts / text",
)
EXTRACT_LABEL_NOISE = (
"requires ", "req. ", "warning", "not always", "this extract",
"check legend", "approach exfil", "located in the sniper zone",
)
EXTRACT_ANCHOR_PATHS = (
"overlay pmc extracts", "overlay scav extracts", "overlay neutral",
"overlay transit", "overlay hidden", "extract dots", "onmap exfil icons",
"map markers / pmc extracts", "map markers / scav extracts",
"map markers / neutral extracts", "running man markers", "hidden exfil onmap",
"transit onmap", "on map overlay / extracts / pmc",
"on map overlay / extracts / scav", "on map overlay / extracts / transit",
"extract markers for bw",
)
def clean_name(value: str) -> str:
@@ -53,6 +92,7 @@ def clean_name(value: str) -> str:
def display_label(category: str, value: str) -> str:
value = clean_name(value)
lower = value.lower()
value = LABEL_CORRECTIONS.get(lower, value)
noisy = (not any(char.isalnum() for char in value)
or GENERIC.match(value)
or len(value) > 48
@@ -66,25 +106,34 @@ def display_label(category: str, value: str) -> str:
return CATEGORY_LABELS[category]
if noisy:
return CATEGORY_LABELS.get(category, "Point of interest")
if category in EXTRACT_CATEGORIES:
return value.upper()
return value or CATEGORY_LABELS.get(category, "Point of interest")
def category_for(path: tuple[str, ...]) -> str | None:
text = " / ".join(path).lower().replace("_", " ")
if any(term in text for term in EXCLUDED):
excluded = [term for term in EXCLUDED if term != "legend" and not (
term in {"only for bw", "onlyforbw"} and "extractmarkersforbw" in text.replace(" ", "")
)]
if any(term in text for term in excluded):
return None
# Several real on-map icons retain source names such as PMCLegend copy.
# Exclude legend artwork by location, not merely by a leaf-name fragment.
if "legend" in text and not any(term in text for term in EXTRACT_ANCHOR_PATHS):
return None
if not any(term in text for term in CONTEXT):
return None
if "extract" in text or "exfil" in text:
if "scav" in text:
return "extract-scav"
if "neutral" in text:
if "transit" in text:
return "transit"
if "co-op" in text or "coop" in text or "neutral" in text:
return "extract-neutral"
if "hidden" in text:
return "extract-hidden"
if "transit" in text:
return "transit"
if "scav" in text:
return "extract-scav"
return "extract-pmc"
if "overlay captions" in text:
if "scav" in text:
@@ -121,9 +170,130 @@ def category_for(path: tuple[str, ...]) -> str | None:
return "hazard"
if "quest" in text:
return "quest"
if any(term in text for term in ("location", "caption", "house name", "housename", "text")):
if any(term in text for term in ("location", "caption", "house name", "housename", "room")):
return "location"
return "poi"
if any(term in text for term in ("poi", "point of interest", "note", "address")):
return "poi"
return None
def normalized_path(path: tuple[str, ...]) -> str:
return " / ".join(clean_name(part).lower().replace("_", " ") for part in path)
def is_extract_label_path(path: tuple[str, ...], label: str) -> bool:
text = normalized_path(path)
return (any(term in text for term in EXTRACT_LABEL_PATHS)
and not label.lower().startswith(EXTRACT_LABEL_NOISE))
def explicit_extract_category(path: tuple[str, ...], label: str) -> str | None:
lower_label = label.lower()
if ("smuggler" in lower_label and "basement" in lower_label) \
or "passage by the lake" in lower_label:
return "extract-hidden"
if any(term in lower_label for term in ("co-op", "coop")) \
or any(term in lower_label for term in (
"scav camp", "factory gate", "scav lands", "emercom checkpoint",
"railway exfil", "armored train", "bunker hermetic door",
"road to customs", "smuggler’s path", "smuggler's path",
)):
return "extract-neutral"
# Walk from the leaf upward so a direct PMC/SCAV subgroup wins over a
# broad ancestor such as Shoreline's "Hidden + Transit" container.
for raw_part in reversed(path):
part = clean_name(raw_part).lower().replace("_", " ")
words = set(re.findall(r"[a-z]+", part))
if "neutral" in words or ("pmc" in words and "scav" in words):
return "extract-neutral"
if part in {"scav", "scav extracts", "extract dots scav", "extract dot scav"}:
return "extract-scav"
if part in {"pmc", "pmc extracts", "extract dots pmc", "extract dot pmc"}:
return "extract-pmc"
if part in {"hidden", "hidden exfil", "hidden exfil onmap"}:
return "extract-hidden"
if part in {"transit", "transits", "transit dots", "transit onmap"}:
return "transit"
return None
def semantic_path_label(path: tuple[str, ...], category: str) -> str:
ignored = {
"icons", "main", "letters", "text", "pmc", "scav", "neutral", "hidden",
"transit", "extracts", "extract dots", "extract dot pmc", "extract dots scav",
"extract dots neutral", "transit dots", "onmap", "overlay", "overlays",
"markers", "running man markers", "on map extract information",
"neutral extracts", "pmc extracts", "scav extracts",
"transit letters", "transit onmap", "hidden+transit", "re3mr.com",
}
for part in reversed(path[:-1]):
label = clean_name(part)
normalized = label.lower().replace("_", " ")
if normalized in ignored or any(term in normalized for term in ("copy", "background")):
continue
if normalized.startswith(("overlay ", "onmap ", "extract", "map marker")):
continue
if len(label) > 2:
return display_label(category, label)
return CATEGORY_LABELS[category]
def point_segment_distance(px: float, py: float, ax: float, ay: float,
bx: float, by: float) -> float:
dx, dy = bx - ax, by - ay
if dx == 0 and dy == 0:
return ((px - ax) ** 2 + (py - ay) ** 2) ** 0.5
t = max(0.0, min(1.0, ((px - ax) * dx + (py - ay) * dy) / (dx * dx + dy * dy)))
qx, qy = ax + t * dx, ay + t * dy
return ((px - qx) ** 2 + (py - qy) ** 2) ** 0.5
def inside_playable(m: dict, x: float, y: float, margin: float = 0.018) -> bool:
points = m.get("trim", {}).get("points", [])
if len(points) < 3:
return True
inside = False
for index, (xi, yi) in enumerate(points):
xj, yj = points[index - 1]
if (yi > y) != (yj > y) and x < (xj - xi) * (y - yi) / (yj - yi) + xi:
inside = not inside
if point_segment_distance(x, y, xi, yi, xj, yj) <= margin:
return True
return inside
def cluster_candidates(candidates: list[dict], radius: float) -> list[dict]:
clusters: list[list[dict]] = []
for candidate in sorted(candidates, key=lambda item: -item["score"]):
cluster = next((items for items in clusters
if items[0]["category"] == candidate["category"]
and (sum(item["x"] for item in items) / len(items) - candidate["x"]) ** 2
+ (sum(item["y"] for item in items) / len(items) - candidate["y"]) ** 2
< radius ** 2), None)
if cluster is None:
clusters.append([candidate])
else:
cluster.append(candidate)
result = []
for items in clusters:
best = max(items, key=lambda item: item["score"])
result.append({
**best,
"x": sum(item["x"] for item in items) / len(items),
"y": sum(item["y"] for item in items) / len(items),
})
return result
def anchor_matches_label(anchor_label: str, label: str) -> bool:
ignored = {"extract", "exfil", "transit", "to", "of", "tarkov", "v", "ex"}
anchor_words = set(re.findall(r"[a-z0-9]+", anchor_label.lower())) - ignored
label_words = set(re.findall(r"[a-z0-9]+", label.lower())) - ignored
if anchor_words and anchor_words <= label_words:
return True
compact_anchor = re.sub(r"[^a-z0-9]", "", anchor_label.lower())
compact_label = re.sub(r"[^a-z0-9]", "", label.lower())
return len(compact_anchor) >= 5 and compact_anchor in compact_label
def layer_text(layer) -> str:
@@ -165,6 +335,8 @@ def extract_map(m: dict, source_root: Path | None) -> list[dict]:
left, top, right, bottom = map(float, crop)
width, height = right - left, bottom - top
candidates: list[dict] = []
extract_labels: list[dict] = []
extract_anchors: list[dict] = []
def walk(node, prefix: tuple[str, ...], ancestors_visible: bool) -> None:
for layer in node:
@@ -190,33 +362,139 @@ def extract_map(m: dict, source_root: Path | None) -> list[dict]:
label = layer_text(layer)
if label in {"☠", "☢"}:
category = "hazard"
label = display_label(category, label)
candidates.append({
record = {
"x": (cx - left) / width,
"y": (cy - top) / height,
"category": category,
"label": label,
"label": display_label(category, label),
"source": "/".join(layer_path),
"score": marker_score(layer, label),
})
}
if category in EXTRACT_CATEGORIES:
path_text = normalized_path(layer_path)
label_context = any(term in path_text for term in EXTRACT_LABEL_PATHS)
if label_context:
if layer.kind != "type" or not is_extract_label_path(layer_path, label):
continue
explicit = explicit_extract_category(layer_path, label)
explicit = MAP_CATEGORY_OVERRIDES.get(
(m["id"], clean_name(label).lower()), explicit,
)
record["explicitCategory"] = explicit
if explicit:
record["category"] = explicit
record["label"] = display_label(record["category"], label)
extract_labels.append(record)
else:
if not any(term in path_text for term in EXTRACT_ANCHOR_PATHS):
continue
# Some PSDs place PMC and Scav marker groups inside a broad
# "Hidden + Transit" parent. Prefer the closest semantic
# group over that inherited parent-folder wording.
explicit = explicit_extract_category(layer_path, label)
if explicit:
record["category"] = explicit
leaf_label = display_label(record["category"], label)
if layer.kind == "type" and len(clean_name(label)) > 4 \
and not GENERIC.match(clean_name(label)):
record["label"] = leaf_label
else:
record["label"] = semantic_path_label(layer_path, record["category"])
extract_anchors.append(record)
else:
candidates.append(record)
walk(psd, (), True)
# A logical PSD marker is often two or three co-located leaves (background,
# icon and type). Keep the most semantic record within each small cluster.
kept: list[dict] = []
for candidate in sorted(candidates, key=lambda item: -item["score"]):
duplicate = next((item for item in kept if item["category"] == candidate["category"]
and (item["x"] - candidate["x"]) ** 2
+ (item["y"] - candidate["y"]) ** 2 < 0.0035 ** 2), None)
if duplicate:
# PSD extracts are usually represented twice: a semantic text label and a
# nearby icon made from several leaves. Cluster the icon components, then
# pair each visible on-map name with its nearest compatible icon. This
# keeps the exact extract position and readable name without duplicating
# the background, letter, caption and side-indicator layers.
anchors = cluster_candidates(extract_anchors, 0.01)
used_anchors: set[int] = set()
extracts: list[dict] = []
unmatched_labels = set(range(len(extract_labels)))
# Assign globally closest pairs first. A top-to-bottom greedy pass can
# steal a nearby icon from the correct label on dense maps such as Shoreline.
pairs = []
for label_index, label in enumerate(extract_labels):
explicit = label.get("explicitCategory")
special_neutral = explicit == "extract-neutral" and any(
term in label["label"].lower() for term in ("co-op", "coop", "scav camp", "factory gate", "scav lands")
)
for anchor_index, anchor in enumerate(anchors):
if explicit is not None and not special_neutral and anchor["category"] != explicit:
continue
distance = ((anchor["x"] - label["x"]) ** 2
+ (anchor["y"] - label["y"]) ** 2)
if distance <= 0.12 ** 2:
pairs.append((distance, label_index, anchor_index))
for _, label_index, anchor_index in sorted(pairs):
if label_index not in unmatched_labels or anchor_index in used_anchors:
continue
candidate.pop("score")
kept.append(candidate)
label = extract_labels[label_index]
anchor = anchors[anchor_index]
explicit = label.get("explicitCategory")
unmatched_labels.remove(label_index)
used_anchors.add(anchor_index)
anchor_is_playable = inside_playable(m, anchor["x"], anchor["y"])
extracts.append({
**label,
"x": anchor["x"] if anchor_is_playable else label["x"],
"y": anchor["y"] if anchor_is_playable else label["y"],
"category": explicit or anchor["category"],
})
for label_index in sorted(unmatched_labels):
extracts.append(extract_labels[label_index])
unmatched = [anchor for index, anchor in enumerate(anchors) if index not in used_anchors]
unmatched_by_name: dict[tuple[str, str], dict] = {}
for anchor in unmatched:
if anchor["label"] == CATEGORY_LABELS[anchor["category"]]:
continue
if any(anchor_matches_label(anchor["label"], label["label"])
for label in extract_labels):
continue
key = (anchor["category"], anchor["label"].lower())
existing = unmatched_by_name.get(key)
if existing is None or anchor["source"].lower().count("copy") \
< existing["source"].lower().count("copy"):
unmatched_by_name[key] = anchor
extracts.extend(unmatched_by_name.values())
icon_summary = ", ".join(
f"{category}={count}" for category, count in sorted(Counter(
anchor["category"] for anchor in anchors
).items())
)
print(f"[{m['id']}] reconciled {len(extract_labels)} extract label(s) "
f"with {len(anchors)} icon cluster(s) ({icon_summary or 'none'}) "
f"into {len(extracts)} marker(s)")
# Non-extract icons still commonly contain a background, glyph and label.
# A slightly larger visual cluster removes those redundant leaves.
if m.get("parent"):
extracts = []
kept = cluster_candidates(candidates, 0.006) + extracts
kept = [item for item in kept if inside_playable(m, item["x"], item["y"])]
for marker in kept:
marker.pop("score", None)
marker.pop("explicitCategory", None)
kept.sort(key=lambda item: (item["category"], item["y"], item["x"]))
for index, marker in enumerate(kept, 1):
marker["id"] = f"{m['id']}-{index}"
used_ids: set[str] = set()
for marker in kept:
seed = f"{marker['source']}|{marker['category']}|{marker['x']:.5f}|{marker['y']:.5f}"
digest = hashlib.sha1(seed.encode("utf-8")).hexdigest()[:12]
marker_id = f"{m['id']}-{digest}"
suffix = 2
while marker_id in used_ids:
marker_id = f"{m['id']}-{digest}-{suffix}"
suffix += 1
used_ids.add(marker_id)
marker["id"] = marker_id
marker["mapId"] = m["id"]
print(f"[{m['id']}] extracted {len(kept)} marker(s)")
return kept
@@ -234,31 +512,28 @@ def main(argv: list[str]) -> None:
cfg = load_config()
targets = [find_map(cfg, map_id) for map_id in argv] if argv else cfg.maps
destination = DATA / "markers.json"
markers = []
successful: set[str] = set()
destination_dir = DATA / "markers"
destination_dir.mkdir(parents=True, exist_ok=True)
written = 0
errors = []
for m in targets:
try:
markers.extend(extract_map(m, source_root))
successful.add(m["id"])
markers = extract_map(m, source_root)
for marker in markers:
marker["label"] = display_label(marker["category"], marker.get("label", ""))
markers.sort(key=lambda item: (item["category"], item["id"]))
destination = destination_dir / f"{m['id']}.json"
destination.write_text(json.dumps({
"version": 2,
"mapId": m["id"],
"markers": markers,
}, indent=2) + "\n", encoding="utf-8")
written += len(markers)
print(f"wrote {destination.relative_to(ROOT)} with {len(markers)} marker(s)")
except Exception as exc: # noqa: BLE001
errors.append(f"{m['id']}: {exc}")
print(f"[{m['id']}] SKIPPED: {exc}")
# Targeted runs replace only the maps successfully extracted. This makes
# `extract_markers.py customs` safe after a complete build, and preserves
# the previous records for a PSD that is temporarily unavailable.
if destination.exists():
previous = json.loads(destination.read_text(encoding="utf-8")).get("markers", [])
markers = [item for item in previous if item.get("mapId") not in successful] + markers
for marker in markers:
marker["label"] = display_label(marker["category"], marker.get("label", ""))
markers.sort(key=lambda item: (item["mapId"], item["category"], item["id"]))
DATA.mkdir(parents=True, exist_ok=True)
destination.write_text(json.dumps({"version": 1, "markers": markers}, indent=2), encoding="utf-8")
print(f"wrote {destination.relative_to(ROOT)} with {len(markers)} marker(s)")
print(f"wrote {written} marker(s) across {len(targets) - len(errors)} map file(s)")
if errors:
print("skipped maps: " + "; ".join(errors))