chore(battle): snapshot the LocalMP rework baseline

Records the uncommitted battle-session work exactly as it was left
(local service matchmaking, settlement, chat, native LocalMP hooks,
battle gui/exe patches) so the following review and rework commits
show every correction as a diff against this state.

This commit is not reviewed and is known to be incomplete: in-game
testing reported wrong settlement rewards, single-country teams,
missing random/fixed supplement slots, misattributed hit messages and
other regressions. Do not merge this branch before the rework lands.
This commit is contained in:
N0VAN0M4LY committed 2026-11-28 03:15:47 +08:00
1 parent 5c9204c031
commit b260d2899e
97 files changed
+7676 -396

No files matched your search

+3 -2
View File
@@ -2,6 +2,7 @@
Each group of commands lives in its own module and registers itself here:
- exe_commands: check-patches, patch-exe
- gui_commands: check-gui
Run `wtotools <command> --help` for the arguments of one command.
"""
@@ -9,14 +10,14 @@ from __future__ import annotations
import argparse
from . import exe_commands
from . import exe_commands, gui_commands
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(prog="wtotools", description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
commands = parser.add_subparsers(dest="command", required=True)
for group in (exe_commands,):
for group in (exe_commands, gui_commands):
group.register(commands)
args = parser.parse_args(argv)
return args.handler(args)
+16
View File
@@ -1,6 +1,7 @@
"""Commands that work on the game executable.
wtotools check-patches --exe <aces.exe> [--patches exe-patches]
wtotools check-offsets --exe <aces.exe> [--header native/wto-net/src/local_mp_offsets.h]
wtotools patch-exe --exe <aces.exe> --out <aces.exe> [--patches exe-patches] [--force]
The input executable is only ever read. `patch-exe` refuses to write over its input and
@@ -15,9 +16,11 @@ from pathlib import Path
from ..exepatch import apply_writes, changed_ranges, load_patches, plan_patches
from ..exepatch.assemble import disagreement
from ..offset_check import parse_offset_header, verify_offsets
from ..pe import PeImage
DEFAULT_PATCHES = Path("exe-patches")
DEFAULT_OFFSET_HEADER = Path("native/wto-net/src/local_mp_offsets.h")
def register(commands: argparse._SubParsersAction) -> None:
@@ -25,6 +28,11 @@ def register(commands: argparse._SubParsersAction) -> None:
_add_common(check)
check.set_defaults(handler=_check_patches)
offsets = commands.add_parser("check-offsets", help="verify native LocalMP signatures and anchor strings")
offsets.add_argument("--exe", type=Path, required=True, help="the game executable to read")
offsets.add_argument("--header", type=Path, default=DEFAULT_OFFSET_HEADER, help="C header with LMP_SIG_* and @anchor tags")
offsets.set_defaults(handler=_check_offsets)
patch = commands.add_parser("patch-exe", help="apply every patch to a copy of the executable")
_add_common(patch)
patch.add_argument("--out", type=Path, required=True, help="where to write the patched copy")
@@ -55,6 +63,14 @@ def _check_patches(args: argparse.Namespace) -> int:
return 0 if plan.complete and not mismatched else 1
def _check_offsets(args: argparse.Namespace) -> int:
spec = parse_offset_header(args.header)
ok, lines = verify_offsets(PeImage(args.exe.read_bytes()), spec)
for line in lines:
print(line)
return 0 if ok else 1
def _patch_exe(args: argparse.Namespace) -> int:
if args.out.resolve() == args.exe.resolve():
print("refusing to write over the input executable; choose a different --out", file=sys.stderr)
+39
View File
@@ -0,0 +1,39 @@
"""Command to verify `gui-patches/` against `gui.vromfs.bin` with Quirrel bytecode compilation.
wtotools check-gui --gui <gui.vromfs.bin> [--patches gui-patches] [--sq build/quirrel-check/sq.exe]
"""
from __future__ import annotations
import argparse
import sys
from pathlib import Path
from ..gui_check import verify_gui_patches
DEFAULT_GUI_PATCHES = Path("gui-patches")
DEFAULT_SQ_EXE = Path("build/quirrel-check/sq.exe")
def register(commands: argparse._SubParsersAction) -> None:
check = commands.add_parser(
"check-gui",
help="apply gui-patches in memory and bytecode-compile every modified .nut script",
)
check.add_argument("--gui", type=Path, required=True, help="stock gui.vromfs.bin to read")
check.add_argument("--patches", type=Path, default=DEFAULT_GUI_PATCHES, help="gui-patches directory")
check.add_argument("--sq", type=Path, default=DEFAULT_SQ_EXE, help="Quirrel compiler sq.exe path")
check.set_defaults(handler=_check_gui)
def _check_gui(args: argparse.Namespace) -> int:
if not args.sq.exists():
print(f"Quirrel compiler not found: {args.sq}", file=sys.stderr)
return 2
report = verify_gui_patches(args.gui, args.patches, args.sq)
print(f"{report.patches_applied} GUI patch(es) applied across {report.files_checked} .nut file(s)")
if report.errors:
for error in report.errors:
print(f" {error}", file=sys.stderr)
return 1
print(" every patched .nut file compiled to Quirrel bytecode with zero lexical/constant errors")
return 0
+309
View File
@@ -0,0 +1,309 @@
"""Offline Quirrel bytecode & lexical-scope verifier for `gui-patches/`.
`sq.exe --syntax-check` only runs `sq_parsetoast` and skips `CodeGenVisitor`, missing
`Unknown variable`, forward references, and `Named binding name conflicts with existing
constant/enum/import`. Driving `sq.exe` via `compilestring(src, chunkname, bindings)`
with the target script's real `gui.vromfs.bin` imports runs the full `SQParser` +
`CodeGenVisitor` pipeline without executing any game code.
"""
from __future__ import annotations
import json
import re
import subprocess
import tempfile
from dataclasses import dataclass
from pathlib import Path
from .vromfs import Archive, read_archive
MOUNT_PREFIXES: tuple[tuple[str, str], ...] = (
("%scripts/", "scripts/"),
("%globalScripts/", "globalscripts/"),
("%sqstd/", "std/"),
("%sqStdLibs/", "sqstdlibs/"),
("%appGlobals/", "globals/"),
("%gui/", "gui/"),
("%rGui/", "reactivegui/"),
("%darg/", "darg/"),
)
MODULE_BUILTINS: tuple[str, ...] = (
"require",
"require_optional",
"persist",
"keepref",
"__name__",
"__filename__",
"__static_analysis__",
)
HARNESS_SOURCE = """\
let io = require("io")
let types = require("types")
class DummyClass {}
class Proxy {
function _get(_k) { return this }
function _add(_o) { return 0 }
function _sub(_o) { return 0 }
function _mul(_o) { return 0 }
function _div(_o) { return 1 }
function _modulo(_o) { return 0 }
function _unm() { return 0 }
function _cmp(_o) { return 0 }
}
let proxy = Proxy()
let typeMap = {
String = types.String
Table = types.Table
Array = types.Array
Function = types.Function
Integer = types.Integer
Float = types.Float
Bool = types.Bool
}
function readText(p) {
let f = io.file(p, "rb")
let s = f.readblob(f.len()).as_string()
f.close()
return s
}
let manifestPath = __argv[0]
let lines = readText(manifestPath).split("\\n")
local failed = 0
foreach (line in lines) {
let trimmed = line.strip()
if (trimmed == "")
continue
let parts = trimmed.split("\\t")
let filePath = parts[0]
let display = parts[1]
let names = parts.len() > 2 && parts[2] != "" ? parts[2].split(",") : []
let classNames = parts.len() > 3 && parts[3] != "" ? parts[3].split(",") : []
let bindings = {}
foreach (n in names)
bindings[n] <- (n in typeMap) ? typeMap[n] : proxy
foreach (cn in classNames)
bindings[cn] <- DummyClass
let src = readText(filePath)
try {
compilestring(src, display, bindings)
} catch (e) {
print($"COMPILE_ERROR {display}: {e}\\n")
failed++
}
}
if (failed > 0)
throw $"Quirrel bytecode check failed on {failed} file(s)"
"""
@dataclass(frozen=True)
class GuiCheckReport:
patches_applied: int
files_checked: int
errors: tuple[str, ...]
def verify_gui_patches(
gui_pack_path: Path,
patches_dir: Path,
sq_exe: Path,
endpoint: str = "127.0.0.1:47115",
) -> GuiCheckReport:
archive = read_archive(gui_pack_path.read_bytes())
patch_files = sorted(patches_dir.rglob("patch.json"))
touched_files: list[str] = []
errors: list[str] = []
for patch_path in patch_files:
raw = json.loads(patch_path.read_text(encoding="utf-8"))
target = raw["file"].lower()
if target not in archive.files:
errors.append(f"{raw['id']}: missing file {target} in gui.vromfs.bin")
continue
current = archive.files[target].decode("utf-8")
find_text = raw["edit"]["find"]
first = current.find(find_text)
if first == -1:
errors.append(f"{raw['id']}: target snippet not found in {target}")
continue
if current.find(find_text, first + len(find_text)) != -1:
errors.append(f"{raw['id']}: target snippet appears more than once in {target}")
continue
replace_text = raw["edit"]["replace"].replace("{{LOCAL_ENDPOINT}}", endpoint)
if "`" in replace_text:
errors.append(f"{raw['id']}: backtick string syntax is unsupported by 2.61.0.37 Quirrel VM; use $\"...\" or +")
continue
updated = current[:first] + replace_text + current[first + len(find_text):]
archive.put(target, updated.encode("utf-8"))
if target not in touched_files:
touched_files.append(target)
if errors:
return GuiCheckReport(len(patch_files), 0, tuple(errors))
export_cache: dict[str, set[str]] = {}
native_syms = _collect_all_named_imports(archive)
stock_archive = read_archive(gui_pack_path.read_bytes())
for patch_path in patch_files:
raw = json.loads(patch_path.read_text(encoding="utf-8"))
target = raw["file"].lower()
stock_src = stock_archive.files[target].decode("utf-8")
imp_names, imp_classes = _resolve_file_bindings(stock_src, stock_archive, export_cache, native_syms)
reserved = (imp_names | imp_classes) - set(MODULE_BUILTINS)
new_locals = _declared_locals(raw["edit"]["replace"]) - _declared_locals(raw["edit"]["find"])
collisions = sorted(new_locals & reserved)
if collisions:
errors.append(f"{raw['id']}: local binding(s) {collisions} conflict with module imports in {target}")
if errors:
return GuiCheckReport(len(patch_files), 0, tuple(errors))
with tempfile.TemporaryDirectory(prefix="wto-gui-check-") as tmp:
tmp_dir = Path(tmp)
harness_path = tmp_dir / "harness.nut"
harness_path.write_text(HARNESS_SOURCE, encoding="utf-8")
manifest_lines: list[str] = []
for index, rel_path in enumerate(touched_files):
source = archive.files[rel_path].decode("utf-8")
names, class_names = _resolve_file_bindings(source, archive, export_cache, native_syms)
nut_file = tmp_dir / f"check_{index}.nut"
nut_file.write_bytes(archive.files[rel_path])
manifest_lines.append(
f"{nut_file}\t{rel_path}\t{','.join(sorted(names))}\t{','.join(sorted(class_names))}"
)
manifest_path = tmp_dir / "manifest.tsv"
manifest_path.write_text("\n".join(manifest_lines), encoding="utf-8")
proc = subprocess.run(
[str(sq_exe), str(harness_path), str(manifest_path)],
capture_output=True,
text=True,
encoding="utf-8",
errors="replace",
)
if proc.returncode != 0:
out = (proc.stdout + "\n" + proc.stderr).strip()
for line in out.splitlines():
if line.strip():
errors.append(line.strip())
return GuiCheckReport(len(patch_files), len(touched_files), tuple(errors))
def _resolve_vromfs_path(spec: str) -> str | None:
for prefix, target in MOUNT_PREFIXES:
if spec.startswith(prefix):
return (target + spec[len(prefix):]).lower()
if spec.endswith(".nut"):
return spec.lstrip("/").lower()
return None
def _collect_all_named_imports(archive: Archive) -> dict[str, set[str]]:
by_mod: dict[str, set[str]] = {}
pattern = re.compile(r'^from\s+"([^"]+)"\s+import\s+([^\r\n]+(?:\r?\n\s*,[^\r\n]+)*)', re.MULTILINE)
for content in archive.files.values():
text = content.decode("utf-8", errors="ignore")
for match in pattern.finditer(text):
mod, items = match.group(1), match.group(2)
if items.strip() == "*":
continue
bucket = by_mod.setdefault(mod, set())
for raw_item in items.replace("\r", " ").replace("\n", " ").split(","):
token = raw_item.strip()
if not token:
continue
orig = token.split()[0]
if orig.isidentifier():
bucket.add(orig)
return by_mod
def _exports_of_module(spec: str, archive: Archive, cache: dict[str, set[str]], native_syms: dict[str, set[str]]) -> set[str]:
if spec in cache:
return cache[spec]
vpath = _resolve_vromfs_path(spec)
if not vpath or vpath not in archive.files:
res = set(native_syms.get(spec, set()))
cache[spec] = res
return res
cache[spec] = set()
text = archive.files[vpath].decode("utf-8", errors="ignore")
keys: set[str] = set(native_syms.get(spec, set()))
if vpath == "scripts/dagui_library.nut":
keys |= _exports_of_module("%globalScripts/logs.nut", archive, cache, native_syms)
keys |= _exports_of_module("%scripts/sqDagui/daguiNativeApi.nut", archive, cache, native_syms)
keys |= _exports_of_module("%globalScripts/sharedEnums.nut", archive, cache, native_syms)
for arr_match in re.finditer(r"let\s+fields\s*=\s*\[(.*?)\]", text, re.DOTALL):
for s_match in re.finditer(r'"([A-Za-z_][A-Za-z0-9_]*)"', arr_match.group(1)):
keys.add(s_match.group(1))
for ret_match in re.finditer(r"return\s+(?:freeze\s*\(\s*)?\{([^{}]*(?:\{[^{}]*\}[^{}]*)*)\}", text, re.DOTALL):
body = ret_match.group(1)
for line in body.splitlines():
stripped = line.strip().rstrip(",")
if not stripped or stripped.startswith("//"):
continue
m_assign = re.match(r"^([A-Za-z_][A-Za-z0-9_]*)\s*=", stripped)
if m_assign:
keys.add(m_assign.group(1))
elif stripped.isidentifier():
keys.add(stripped)
for m_slot in re.finditer(r'\b(?:export|res)\s*(?:\.\s*([A-Za-z_][A-Za-z0-9_]*)|\[\s*"([A-Za-z_][A-Za-z0-9_]*)"\s*\])\s*<-', text):
keys.add(m_slot.group(1) or m_slot.group(2))
cache[spec] = keys
return keys
def _resolve_file_bindings(
source: str,
archive: Archive,
cache: dict[str, set[str]],
native_syms: dict[str, set[str]],
) -> tuple[set[str], set[str]]:
names: set[str] = set(MODULE_BUILTINS)
class_names: set[str] = set()
used_as_base = set(re.findall(r"\bclass\s*(?:[A-Za-z_][A-Za-z0-9_]*)?\s*\(\s*([A-Za-z_][A-Za-z0-9_]*)\s*\)", source))
for match in re.finditer(r'^import\s+"([^"]+)"\s+as\s+([A-Za-z_][A-Za-z0-9_]*)', source, re.MULTILINE):
alias = match.group(2)
(class_names if alias in used_as_base else names).add(alias)
from_pattern = re.compile(r'^from\s+"([^"]+)"\s+import\s+([^\r\n]+(?:\r?\n\s*,[^\r\n]+)*)', re.MULTILINE)
for match in from_pattern.finditer(source):
spec, raw_items = match.group(1), match.group(2).strip()
if raw_items == "*":
for sym in _exports_of_module(spec, archive, cache, native_syms):
(class_names if sym in used_as_base else names).add(sym)
continue
for token in raw_items.replace("\r", " ").replace("\n", " ").split(","):
parts = token.strip().split()
if not parts:
continue
bound = parts[2] if len(parts) >= 3 and parts[1] == "as" else parts[0]
if bound.isidentifier():
(class_names if bound in used_as_base else names).add(bound)
return names - class_names, class_names
def _declared_locals(snippet: str) -> set[str]:
found: set[str] = set()
for m in re.finditer(r"\b(?:let|local)\s+([A-Za-z_][A-Za-z0-9_]*)\s*=", snippet):
found.add(m.group(1))
for m in re.finditer(r"\b(?:let|local)\s*\{([^}]+)\}\s*=", snippet):
for tok in m.group(1).split(","):
parts = tok.strip().split(":")
ident = parts[-1].strip()
if ident.isidentifier():
found.add(ident)
return found
+134
View File
@@ -0,0 +1,134 @@
"""Verify native LocalMP signatures, RIP opcodes, and English anchor strings against aces.exe.
Parses `native/wto-net/src/local_mp_offsets.h` directly as the single source of truth so
C hook code and binary calibration checks can never drift apart across game updates.
"""
from __future__ import annotations
import re
from dataclasses import dataclass
from pathlib import Path
from .pe import PeImage
_SIG_RE = re.compile(r'^#define\s+(LMP_SIG_\w+)\s+"([0-9a-fA-F? ]+)"', re.MULTILINE)
_RIP_RE = re.compile(r"@rip_check\s+(LMP_SIG_\w+)\s*\+\s*0x([0-9a-fA-F]+)\s*:\s*([0-9a-fA-F ]+)")
_ANCHOR_RE = re.compile(r'^\s*\*\s*@anchor\s+"([^"]+)"', re.MULTILINE)
_LEA_RE = re.compile(rb"[\x48\x4c]\x8d[\x05\x0d\x15\x1d\x25\x2d\x35\x3d](....)", re.DOTALL)
@dataclass(frozen=True)
class RipCheckSpec:
sig_name: str
offset: int
expected_prefix: bytes
@dataclass(frozen=True)
class OffsetHeaderSpec:
signatures: list[tuple[str, str]]
rip_checks: list[RipCheckSpec]
anchors: list[str]
def parse_offset_header(header_path: Path) -> OffsetHeaderSpec:
source = header_path.read_text(encoding="utf-8")
signatures = _SIG_RE.findall(source)
rip_checks = [
RipCheckSpec(name, int(off_hex, 16), bytes.fromhex(prefix_hex))
for name, off_hex, prefix_hex in _RIP_RE.findall(source)
]
anchors = list(dict.fromkeys(_ANCHOR_RE.findall(source)))
return OffsetHeaderSpec(signatures=signatures, rip_checks=rip_checks, anchors=anchors)
def _compile_signature(spec: str) -> re.Pattern[bytes]:
parts: list[bytes] = []
for token in spec.split():
if token == "??":
parts.append(b".")
else:
parts.append(re.escape(bytes([int(token, 16)])))
return re.compile(b"".join(parts), re.DOTALL)
def _index_rip_lea_targets(text_rva: int, text_bytes: bytes) -> dict[int, list[int]]:
targets: dict[int, list[int]] = {}
for match in _LEA_RE.finditer(text_bytes):
insn_rva = text_rva + match.start()
disp = int.from_bytes(match.group(1), "little", signed=True)
target_rva = insn_rva + 7 + disp
bucket = targets.get(target_rva)
if bucket is None:
targets[target_rva] = [insn_rva]
elif len(bucket) < 4:
bucket.append(insn_rva)
return targets
def _find_cstring_rvas(pe: PeImage, text: str) -> list[int]:
needle = text.encode("ascii") + b"\x00"
rvas: list[int] = []
for sec in pe.sections:
if sec.name == ".text" or sec.raw_size == 0:
continue
raw = pe.data[sec.raw_offset : sec.raw_offset + min(sec.virtual_size, sec.raw_size)]
pos = 0
while True:
idx = raw.find(needle, pos)
if idx < 0:
break
rvas.append(sec.rva + idx)
pos = idx + len(needle)
return rvas
def verify_offsets(pe: PeImage, spec: OffsetHeaderSpec) -> tuple[bool, list[str]]:
lines: list[str] = []
failures = 0
text_sec = pe.section(".text")
text_bytes = pe.section_bytes(".text")
resolved_sigs: dict[str, int] = {}
lines.append(f"Checking {len(spec.signatures)} .text signature(s):")
for name, pattern in spec.signatures:
hits = [text_sec.rva + m.start() for m in _compile_signature(pattern).finditer(text_bytes)]
if len(hits) == 1:
resolved_sigs[name] = hits[0]
lines.append(f" [OK] {name:<34} -> {hits[0]:#09x}")
else:
failures += 1
lines.append(f" [FAIL] {name:<34} -> {len(hits)} match(es)")
lines.append(f"Checking {len(spec.rip_checks)} RIP displacement anchor(s):")
for chk in spec.rip_checks:
base_rva = resolved_sigs.get(chk.sig_name)
if base_rva is None:
failures += 1
lines.append(f" [FAIL] {chk.sig_name} + {chk.offset:#x}: base signature unresolved")
continue
actual = pe.read(base_rva + chk.offset, len(chk.expected_prefix))
if actual == chk.expected_prefix:
lines.append(f" [OK] {chk.sig_name} + {chk.offset:#x} == {actual.hex(' ')}")
else:
failures += 1
lines.append(
f" [FAIL] {chk.sig_name} + {chk.offset:#x}: expected {chk.expected_prefix.hex(' ')}, got {actual.hex(' ')}"
)
lea_targets = _index_rip_lea_targets(text_sec.rva, text_bytes)
lines.append(f"Checking {len(spec.anchors)} English anchor string(s):")
for anchor in spec.anchors:
str_rvas = _find_cstring_rvas(pe, anchor)
xrefs = [xr for sr in str_rvas for xr in lea_targets.get(sr, ())]
if str_rvas and xrefs:
fn_range = pe.function_containing(xrefs[0])
fn_str = f"{fn_range[0]:#x}" if fn_range else f"{xrefs[0]:#x}"
lines.append(f" [OK] {anchor!r:<58} -> str {str_rvas[0]:#x}, fn {fn_str}")
elif str_rvas:
lines.append(f" [OK] {anchor!r:<58} -> str {str_rvas[0]:#x} (table/data ref)")
else:
failures += 1
lines.append(f" [FAIL] {anchor!r}: string not found in image")
return failures == 0, lines