#!/usr/bin/env python3 """ Build Client/pack/locale_zh_ava2: the 喜相逢 locale_zh item tables plus the items our server has that 喜相逢 lacks. 60ed6669 replaced locale_zh with the 喜相逢 locale (read from locale/newcibn, see Client/locale.cfg), whose item_proto misses ~480 of our server's items and gives ~250 shared vnums a different type. ava2items carries server-matching copies of the four item tables, but the first registered pack wins, so locale_zh hides them. This pack is registered before locale_zh and holds: item_proto 喜相逢 records + ava2items records for vnums 喜相逢 lacks or types differently item_list.txt 喜相逢 rows + ava2items rows for those vnums (an ava2items row whose icon/model is in no registered pack keeps the 喜相逢 row) itemdesc.txt 喜相逢 rows + ava2items rows for those vnums item_scale.txt ava2items rows (9 columns, as LoadItemScale needs) + 喜相逢-only rows padded to 9 columns wiki/*.txt ava2items' wiki texts, which it ships as locale/zh/wiki but the wiki reads from the locale path icons/models an added item_list row's files that no registered pack has, from --assets (AVA2 pack_maker) locale_game_ex.txt data/zh_40250/locale_game_ex_zh_overlay.txt in GB18030; localeinfo.py loads it after locale/common/locale_game_ex.txt, whose Won (cheque) strings are English or wrongly ordered Usage: scripts/build_xxf_item_overlay.py [--build build/switchbot-check] [--pack Client/pack] [--ava2items DIR] """ import argparse import re import shutil import subprocess import sys import tempfile from pathlib import Path REPO = Path(__file__).resolve().parents[1] sys.path.insert(0, str(REPO / "tools/epk_scan")) import epk_scan # noqa: E402 XXF_KEYS = ((45129401, 92367215, 681285731, 1717894), (78952482, 527348324, 1632942, 486277894)) TABLES = ("item_proto", "item_list.txt", "itemdesc.txt", "item_scale.txt") OVERLAY = "locale_zh_ava2" def pack_keys(build: Path): header = (build / "src/port/generated/EterPackKeys.generated.h").read_text() keys = {name: tuple(int(v) for v in values.split(",")) for name, values in re.findall(r"(\w+)\[\] = \{([^}]*)\}", header)} return ((keys["s_adwEterPackKey"], keys["s_adwEterPackSecurityKey"]), XXF_KEYS) def read_index(eix: Path, keys): for index_key, security_key in keys: try: return epk_scan.read_index(eix, index_key)[0], security_key except ValueError: pass raise ValueError(f"{eix}: no known index key") def extract(pack_dir: Path, stem: str, keys, prefix: str, wanted) -> dict[str, bytes]: """Files under prefix (e.g. locale/newcibn/) that wanted(relative name) accepts, keyed by relative name.""" entries, security_key = read_index(pack_dir / f"{stem}.eix", keys) raw = (pack_dir / f"{stem}.epk").read_bytes() out = {} for e in entries: name = e["name"].lower().replace("\\", "/") if not name.startswith(prefix) or not wanted(name[len(prefix):]): continue stored = raw[e["pos"]:e["pos"] + e["size"]] if e["type"] == 0: out[name[len(prefix):]] = stored else: obj = raw[e["pos"]:e["pos"] + epk_scan.lz_object_len(stored[:16])] out[name[len(prefix):]] = epk_scan.lz_object(obj, security_key if e["type"] == 2 else None) return out def tables(pack_dir: Path, stem: str, keys, prefix: str) -> dict[str, bytes]: out = extract(pack_dir, stem, keys, prefix, lambda name: name in TABLES) missing = set(TABLES) - out.keys() if missing: raise SystemExit(f"{stem}: missing {prefix}{sorted(missing)}") return out def registered_packs(pack_dir: Path) -> list[str]: """Pack stems in registration order, without the foreign-locale packs a zh client never mounts.""" lines = [l.strip() for l in (pack_dir / "Index").read_text(errors="replace").splitlines() if l.strip()] return [lines[i + 1] for i in range(1, len(lines) - 1, 2) if lines[i] == "*" or lines[i].startswith("locale/zh") or not lines[i].startswith("locale/")] def rows(text: bytes) -> dict[int, list[bytes]]: """Rows keyed by their leading vnum; a vnum may own several rows (item_scale has one per job/sex).""" out: dict[int, list[bytes]] = {} for line in text.splitlines(): key = line.split(b"\t", 1)[0].strip() if key.isdigit(): out.setdefault(int(key), []).append(line.rstrip(b"\r")) return out def merge_rows(base: bytes, extra: dict[int, list[bytes]], replace: set[int]) -> bytes: """Base lines in order; replace[vnum] rows are swapped in place, the rest of extra is appended.""" newline = b"\r\n" if b"\r\n" in base else b"\n" out, done = [], set() for line in base.splitlines(): line = line.rstrip(b"\r") key = line.split(b"\t", 1)[0].strip() vnum = int(key) if key.isdigit() else None if vnum in replace: if vnum not in done: out.extend(extra[vnum]) done.add(vnum) continue out.append(line) out.extend(line for vnum in sorted(extra.keys() - done) for line in extra[vnum]) return newline.join(out) + newline def dump_proto(tool: Path, data: bytes, tmp: Path, name: str) -> dict[int, bytes]: path = tmp / name path.write_bytes(data) text = subprocess.run([str(tool), "--dump", str(path)], check=True, capture_output=True).stdout return {int(line.split(None, 1)[0]): line for line in text.splitlines() if line.strip()} def shape(record: bytes) -> tuple[int, int]: fields = record.split(b"\t", 1)[0].split() return int(fields[1]), int(fields[2]) def main() -> int: p = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) p.add_argument("--build", type=Path, default=REPO / "build/switchbot-check") p.add_argument("--pack", type=Path, default=REPO / "Client/pack") p.add_argument("--ava2items", type=Path, default=None, help="directory with ava2items.eix/.epk (default: --pack)") p.add_argument("--assets", type=Path, action="append", default=[REPO.parent / "AVA2/TEST/1. Client DEV/pack_maker/icon"], help="loose-file roots for item_list files no registered pack has (copied into the overlay)") a = p.parse_args() keys = pack_keys(a.build) ava2_dir = a.ava2items or a.pack # The client reads app.GetLocalePath() = locale/; ava2items ships its tables as locale/zh. locale = "locale/%s/" % (a.pack.parent / "locale.cfg").read_text().split()[2] xxf = tables(a.pack, "locale_zh", keys, locale) ava2 = tables(ava2_dir, "ava2items", keys, "locale/zh/") wiki = extract(ava2_dir, "ava2items", keys, "locale/zh/", lambda name: name.startswith("wiki/")) with tempfile.TemporaryDirectory() as tmp_name: tmp = Path(tmp_name) tool = a.build / "src/port/item_proto_patch" xxf_proto = dump_proto(tool, xxf["item_proto"], tmp, "xxf.proto") ava2_proto = dump_proto(tool, ava2["item_proto"], tmp, "ava2.proto") added = set(ava2_proto) - set(xxf_proto) retyped = {v for v in set(ava2_proto) & set(xxf_proto) if shape(ava2_proto[v]) != shape(xxf_proto[v])} taken = added | retyped (tmp / "rows.tsv").write_bytes(b"\n".join(ava2_proto[v] for v in sorted(taken)) + b"\n") subprocess.run([str(tool), str(tmp / "xxf.proto"), str(tmp / "rows.tsv"), str(tmp / "out.proto")], check=True, stdout=subprocess.DEVNULL) merged = {"item_proto": (tmp / "out.proto").read_bytes()} known = set() for stem in registered_packs(a.pack): if stem == OVERLAY: continue pack_dir = ava2_dir if stem == "ava2items" else a.pack if (pack_dir / f"{stem}.eix").is_file(): known |= {e["name"].lower().replace("\\", "/") for e in read_index(pack_dir / f"{stem}.eix", keys)[0]} loose = {} def unresolved(row_list): """Icon/model files of these item_list rows that no pack has; files found under --assets go in loose.""" absent = [] for f in (f.strip().lower().replace(b"\\", b"/").decode("latin-1") for row in row_list for f in row.split(b"\t")[2:4] if f.strip()): if f in known or f in loose: continue source = next((root / f for root in a.assets if (root / f).is_file()), None) if source: loose[f] = source else: absent.append(f) return absent ava2_list, xxf_list = rows(ava2["item_list.txt"]), rows(xxf["item_list.txt"]) list_rows, kept_xxf = {}, [] for v in sorted(taken & ava2_list.keys()): if v in xxf_list and unresolved(ava2_list[v]): kept_xxf.append(v) else: list_rows[v] = ava2_list[v] # 喜相逢 rows naming files no pack has (11000-11030 point at questicon .tga, shipped only as .sub) take # the ava2items row when that one resolves. repaired = [v for v in sorted(xxf_list.keys() - list_rows.keys() & ava2_list.keys()) if unresolved(xxf_list[v]) and not unresolved(ava2_list[v])] list_rows.update({v: ava2_list[v] for v in repaired}) merged["item_list.txt"] = merge_rows(xxf["item_list.txt"], list_rows, set(list_rows) & xxf_list.keys()) # 喜相逢 rows can name icons it never shipped (e.g. 31021, 31054); fill those from --assets too. missing_files = {v: f for v, r in rows(merged["item_list.txt"]).items() if (f := unresolved(r))} ava2_desc, xxf_desc = rows(ava2["itemdesc.txt"]), rows(xxf["itemdesc.txt"]) desc_rows = {v: ava2_desc[v] for v in taken & ava2_desc.keys()} merged["itemdesc.txt"] = merge_rows(xxf["itemdesc.txt"], desc_rows, set(desc_rows) & xxf_desc.keys()) # LoadItemScale (AVA2 sash port) needs vnum job sex x y z + position x y z; 喜相逢 rows stop after the # scale, so every one of them is rejected. ava2items rows win; 喜相逢-only vnums get a zero position. ava2_scale, xxf_scale = rows(ava2["item_scale.txt"]), rows(xxf["item_scale.txt"]) scale_rows = {v: [row + b"\t0" * (9 - len(row.split(b"\t"))) for row in r] for v, r in xxf_scale.items() if v not in ava2_scale} scale_rows.update(ava2_scale) merged["item_scale.txt"] = merge_rows(xxf["item_scale.txt"], scale_rows, set(scale_rows) & xxf_scale.keys()) wiki = {name: data for name, data in wiki.items() if locale + name not in known} merged["locale_game_ex.txt"] = (REPO / "data/zh_40250/locale_game_ex_zh_overlay.txt").read_text( encoding="utf-8").replace("\n", "\r\n").encode("gb18030") stage = tmp / "stage" for name, data in {**merged, **wiki}.items(): (stage / locale / name).parent.mkdir(parents=True, exist_ok=True) (stage / locale / name).write_bytes(data) for name, source in loose.items(): (stage / name).parent.mkdir(parents=True, exist_ok=True) shutil.copy2(source, stage / name) subprocess.run([str(a.build / "src/port/eterpack_pack"), str(a.pack / OVERLAY), str(stage), ""], check=True, stdout=subprocess.DEVNULL) index = a.pack / "Index" text = index.read_bytes() newline = b"\r\n" if b"\r\n" in text else b"\n" lines = text.splitlines() if OVERLAY.encode() not in [l.strip() for l in lines]: at = [l.strip() for l in lines].index(b"locale_zh") - 1 lines[at:at] = [b"*", OVERLAY.encode()] index.write_bytes(newline.join(lines) + newline) print(f"item_proto: +{len(added)} new, {len(retyped)} retyped from ava2items") print(f"item_list: {len(list_rows)} rows from ava2items ({len(repaired)} repair 喜相逢 rows with absent files), " f"{len(kept_xxf)} kept 喜相逢 (ava2items files absent)") print(f"loose files copied in: {len(loose)}, wiki texts: {len(wiki)} (as {locale}wiki/)") print(f"itemdesc: {len(desc_rows)} rows, item_scale: {sum(map(len, scale_rows.values()))} rows") if missing_files: print(f"WARNING: {len(missing_files)} items reference files in no registered pack or --assets root:") for v, files in list(missing_files.items())[:20]: print(f" {v}: {files}") print(f"wrote {a.pack / OVERLAY}.eix/.epk; Index has {OVERLAY} before locale_zh") return 0 if __name__ == "__main__": sys.exit(main())