diff --git a/docs/killhouse-navigation.md b/docs/killhouse-navigation.md new file mode 100644 index 00000000..ecb4da2f --- /dev/null +++ b/docs/killhouse-navigation.md @@ -0,0 +1,176 @@ +# Killhouse navigation recovery + +## Root cause and scope + +Protected baselines on 2026-10-27: engine +`dc11efab474a4ad81d91ca158f2bada827c9dfae`, config +`ec4432e36e723f83b4a4e4033d4d5fd4b6a6963d`, workspace +`6c5b4b3a0ff92d2898a179904335c5c85e8863ee`. Death-inflictor guarding, +spawn-angle initialization, Classic `btd_anticamp=0`, the administrator message, +`sv_pure=1`, eight administrative headers and native voting remain intact. +Production and existing evidence runtimes were not changed. + +Killhouse navigation is present in the original BTD Alpha 001 fastfile. The +map directory selects global offset 4827 in `waypoints/PeZBOT_WP_4.csv`. +Keys 4827..4927 contain 101 nodes. Key 4928, column 1, is `"end "`, with a +trailing ASCII space. Every other relevant loader sentinel is `"end"`. +`LoadStaticWaypoints()` compares that cell literally with `"end"`; the padded +marker fails comparison and is tokenized as an XYZ vector. Only token zero +exists. Undefined coordinate tokens reach `atof()` (`svr/pezbot.gsc:1928`, called +from coordinate conversion at line 2029), terminating the native server. +This is a malformed terminal cell, not missing navigation or missing coordinates +inside the 101-node graph. + +The exact native negative control records `BTD_NAV_MARKER value=[end ] length=4` +and the original stack. Original fastfile SHA-256 remains +`50911fdd0273b50e26983723619881acfaed4aa65f4d91a799a341464c2224a6`; +its decompressed payload has exactly one `end ` followed by NUL at offset +2219104. PeZBOT plaintext source is pinned to +`ebe235fd9a6f5879c1aacb7b79e1ff87fb99d617ca8dd347737e5e88abc91f09`. + +## Small correction and private preparation + +`tools/btd/prepare.py` generates private `svr/pezbot.gsx` from that pinned +plaintext source. One ASCII insertion normalizes the marker only when all of +map name, table name, offset, node count and original padded value match this +specific defect. It then executes the original terminal check. No coordinates, +children, node types, pathfinding, zombie health/speed/damage, wave defaults or +player callbacks are changed. Other malformed inputs still fail. + +The original FF is copied byte-for-byte. The original script has CP1252 comment +bytes, so navigation generation uses a reversible Latin-1 byte mapping rather +than UTF-8 replacement/recoding. Removing the insertion reconstructs every +original source byte. Existing death and spawn overlays are preserved. +No graph regeneration or new waypoint coordinates are necessary. Altering the +serialized fastfile in place would risk pointer/offset corruption and is avoided. +The generated proprietary source and all extracted tables stay outside Git. + +The preparation manifest records the third overlay hash and pinned +`navigation_source_sha256`. The companion workspace change validates the exact +three-overlay set and file identities. Legacy two-overlay preparations remain +usable only without navigation declarations/files and without requested Killhouse. +Missing, changed, extra, unpinned or symlinked navigation is rejected. No checks +are bypassed to package the new runtime. + +## Graph and geometry evidence + +Private export validation found 101 distinct finite XYZ nodes and 374 directed +edges. Every child index is in range, every edge is reciprocal, and every node +is reachable from every other node. There are no duplicate origins/self-links. +All nodes are `stand`; this table has no angle column. Spawn angles are provided +by the existing initialized-vector fix, not invented from waypoint data. +All 25 vendor spawn positions associate with this connected graph; maximum +nearest-node distance is 153.463451349 engine units. Proximity alone is not +collision clearance, and graph connectivity alone does not prove gameplay. + +`tools/btd/navigation.py` validates private CSV exports, including exact node +keys and terminal shape, three ASCII numeric coordinates representable as finite +native floats, strict child syntax, index bounds, reciprocal links, connectivity +and all 25 spawn indices. Synthetic tests reject malformed/undefined/nonfinite +coordinates, malformed markers, disconnected graphs and invalid links. + +## Private table inspection provenance + +Existing local OpenAssetTools Unlinker v0.34.0 was used only for inspection: +SHA-256 `fe36b530f638b87410a3a651663217824c89c98209211ac4265e733b1409ea23`. +It is not a preparation/runtime dependency and was not downloaded or committed. + +```sh +/tmp/cod4x-oat-v0.34.0/Unlinker --no-color --include-assets stringtable -o /tmp/killhouse-nav-inspect/tables /tmp/cod4-btd-prepared/mods/btd_alpha_001/mod.ff +python3 tools/btd/navigation.py --table /tmp/killhouse-nav-inspect/killhouse-fixed-table.csv --spawns /tmp/btd-allies-inspect/btd_gametypes/survival/_survival_spawns.gsc +``` + +The private validation copy replaces the unique bytes `4928,end ,0,0` with +`4928,end,0,0`; this copy is never packaged. Original CSV SHA-256: +`784b1dbf458d6281ef3c67c39898d5ec88f00b642c9944a542890850fa11ba40`; +validation CSV: `4c5623e87bf6757f0934cf47efa058744bfdfa3090b0f9f902e3d04dcca34bc8`. +Both have 1104 rows and identical shapes; all node cells remain unchanged. +The private spawn source matches its existing preparation lock. + +## Reproduction and current qualification gate + +Prepare a NEW private runtime using the existing authorized recipe and package +it against the reviewed workspace/config checkout. Preserve the source package, +existing PoC, and older evidence directories. For native tests: + +```sh +python3 tests/run_btd_navigation.py --runtime PRIVATE_RUNTIME --game GAME_DATA --binary bin/cod4x18_dedrun --original-waypoints --expect-waypoint-defect +python3 tests/run_btd_navigation.py --runtime PRIVATE_RUNTIME --game GAME_DATA --binary bin/cod4x18_dedrun +python3 -m unittest discover -s tests -p 'test_*.py' +python3 tests/run_btd_integration.py --runtime PRIVATE_RUNTIME --game GAME_DATA --catalog CONFIG_CHECKOUT --workspace WORKSPACE_CHECKOUT +python3 tests/run_promod_integration.py --runtime FRESH_PROMOD_RUNTIME --game GAME_DATA --catalog CONFIG_CHECKOUT --workspace WORKSPACE_CHECKOUT +``` + +The native navigation fixture uses actual vendor zombies, authored graph nodes +and native collision traces, not synthetic movement or damage notifications. +Fixture-only grace and initial-wave size shorten waiting; AI speed, damage, +enemy health and production configuration stay unchanged. The fixture gives +only its synthetic player high health so the same zombie can be observed through +an extended chase; this is not balance or player-survival evidence. A second +synthetic survivor keeps the vendor's normal sole-survivor game-over logic from +ending the initial suicide/respawn case; it is removed before the wave trial. + +Spawn-to-node checks and continuous chest-height trajectory checks use native +rays and point floor traces, not swept collision-hull tests. A tracked obstacle +detour does not cover every graph edge, elevated route or many-player condition. +Synthetic client behavior does not certify graphical client gameplay. Full +private logs are never committed. + +## Final local evidence + +Native Killhouse: **12/12** checks at +`/tmp/btd-navigation-bp4wboij/results.json`. The final fixture and runner hashes +match that run. Native original-failure control: **2/2** checks at +`/tmp/btd-navigation-_0ak_ar_/results.json`, preserving the original marker and +exact undefined-coordinate stack. Both retain the original FF bytes. + +| Native measurement | Result | +| --- | --- | +| Loaded nodes / floor-supported visible spawn links | 101 / 25 | +| Maximum spawn-link distance | 153.463 units | +| Settled elevation above lowest authored surface | 232 units | +| Initially blocked direct path | 684.002 units | +| Continuous tracked-zombie route / waypoint changes | 820.466 units / 3 | +| Closest approach / attributed melee | 35.3553 units / passed | +| Native firearm hits / vendor-credited kills | 25 / 5 | +| Vendor wave two / native death and respawn | passed / passed | +| Elevated camping without punishment / teleport | passed | +| Killhouse → Crash → Killhouse / script errors | passed / none | + +Fixture SHA-256: +`aee120ec5da1d122bbc798cd0bd830947ee1447fd30eac69b50f18943d4e0fbc`; +runner: `6b8de903314e4e61ea5ff7b7cab252538d0f966e97607f308adaf0992cc4fe5d`. +Generated navigation overlay: +`10fb2268d2ea64c14d0a7040e180151265a4b2827ebc44068e82831a18ff9c56`. +Native executable: +`ea3d0097320095f7d9080248b6f4ea63a65d646a3bd10f68794a8756a6368918`. +Results also record prepared manifest and baseline/fixture configuration hashes. + +Existing 15-map integration passed 71/71 checks at +`/tmp/cod4-btd-qualified-p1egu0_k`: both startup/restart, all supported maps, +configuration precedence, pure mode, eight headers, administration and no script +errors. Engine unit suite: 59 tests, success with one optional public-client test +skipped. Native vote and rotation suites passed. All seven existing BTD native +expression/death/Classic/negative-control/lifecycle scenarios passed; aggregate +private evidence: `/tmp/killhouse-baseline-regression-results.json`, including +lifecycle `/tmp/btd-death-regression-ossnz59o`. +Freshly generated pinned Promod overlays passed **53/53** checks at +`/tmp/cod4x-promod-integration-0gz_upfe`, including all map loads, ready-up, +voting, match transitions and bot administration. Companion workspace: all +50 Python tests and the complete mocked operations suite passed. Independent +review passed after corrections to tokenizer parity and native evidence gates. +Hosted CI status and owner review remain explicit PR gates. + +Killhouse stays outside the Zombies rotation and preparation's original rotation +map list. Do not describe loader success as full playability. Owner approval is +required before merge; existing mandatory CI must pass. After approved merges, +prepare homologation using the existing reviewed workflow and request explicit +operator authorization before deploying it. Then require supervised real-client +chase/obstacles, elevated/camping positions, attacks/kills, waves, death/respawn, +reconnection and transitions. Only then review the rotation/manifest qualification +change. No merge, deployment or promotion is automatic. + +Rollback: revert the focused preparation/packaging PRs through the existing +reviewed process; retain the death/spawn fixes and Classic policy. Existing +legacy prepared runtimes remain supported for the original 15 maps. Any service +rollback requires operator approval and the exact previously approved artifact. diff --git a/tests/btd_navigation.gsc b/tests/btd_navigation.gsc new file mode 100644 index 00000000..a22d46db --- /dev/null +++ b/tests/btd_navigation.gsc @@ -0,0 +1,306 @@ +// Disposable native qualification fixture. Never packaged in a server image. +main() +{ + marker = tablelookup("waypoints/PeZBOT_WP_4.csv", 0, 4928, 1); + println("BTD_NAV_MARKER value=[" + marker + "] length=" + marker.size); + wait 4; + if (getdvar("btd_nav_scenario") == "idle") + { + setdvar("btd_nav_nodes", level.waypointcount); + setdvar("btd_nav_map", getdvar("mapname")); + return; + } + setdvar("btd_nav_nodes", level.waypointcount); + setdvar("btd_nav_phase", "spawn_links"); + if (level.waypointcount < 2) { fail("nodes"); return; } + linked_spawns = 0; + max_spawn_link = 0; + for (i = 0; i < level.zomspawns.size; i++) + { + origin = level.zomspawns[i].origin; + if (!isdefined(supported_floor(origin))) { fail("spawn_floor"); return; } + closest_link = 1000000; + for (j = 0; j < level.waypointcount; j++) + { + node = level.waypoints[j].origin; + separation = distance(origin, node); + if (separation > 256 || separation >= closest_link) continue; + trace = bullettrace(origin + (0, 0, 30), node + (0, 0, 30), false, undefined); + if (trace["fraction"] >= 1) closest_link = separation; + } + if (closest_link > 256) { fail("spawn_visibility"); return; } + linked_spawns++; + if (closest_link > max_spawn_link) max_spawn_link = closest_link; + } + if (linked_spawns != 25) { fail("spawn_count"); return; } + setdvar("btd_nav_linked_spawns", linked_spawns); + setdvar("btd_nav_max_spawn_link", max_spawn_link); + setdvar("btd_nav_phase", "spawn_respawn"); + player = addtestclient("NavigationFixture"); + player.pers["isBot"] = true; + wait 1; + player maps\mp\gametypes\_globallogic::menuAllies(); + wait 1; + player maps\mp\gametypes\_globallogic::menuClass("specops_mp,0"); + if (!player await_spawn()) { fail("spawn"); return; } + guardian = addtestclient("RespawnWitness"); + guardian.pers["isBot"] = true; + wait 1; + guardian maps\mp\gametypes\_globallogic::menuAllies(); + wait 1; + guardian maps\mp\gametypes\_globallogic::menuClass("specops_mp,0"); + if (!guardian await_spawn()) { fail("witness_spawn"); return; } + wait 1; + player suicide(); + wait 2; + if (!player await_spawn()) { fail("respawn"); return; } + setdvar("btd_nav_respawn", "passed"); + kick(guardian getentitynumber()); + player.maxhealth = 100000; + player.health = 100000; + player.btd_nav_fixture = true; + level.btd_nav_damage_callback = level.callbackPlayerDamage; + level.callbackPlayerDamage = ::observe_player_damage; + weapons = player getweaponslistprimaries(); + if (!weapons.size) { fail("loadout"); return; } + player.btd_nav_weapon = weapons[0]; + player botstop(); + player freezecontrols(true); + // Use authored nodes and collision-supported ground, never invented positions. + setdvar("btd_nav_phase", "camping"); + highest = undefined; + lowest = 1000000; + for (i = 0; i < level.waypointcount; i++) + { + floor = supported_floor(level.waypoints[i].origin); + if (!isdefined(floor)) continue; + if (!isdefined(highest) || floor[2] > highest[2]) highest = floor; + if (floor[2] < lowest) lowest = floor[2]; + } + if (!isdefined(highest)) { fail("floor"); return; } + player setorigin(highest + (0, 0, 1)); + wait 2; + settled = player.origin; + hp = player.health; + setdvar("btd_nav_elevation", settled[2] - lowest); + if (distance2d(settled, highest) > 16 || settled[2] < highest[2] - 8 || + settled[2] > highest[2] + 8 || settled[2] - lowest < 128) + { fail("elevated_position"); return; } + if (isdefined(player.campingtime)) { fail("camp_timer"); return; } + triggers = getentarray("trigger_radius", "classname"); + for (i = 0; i < triggers.size; i++) + if (isdefined(triggers[i].goto)) { fail("camp_trigger"); return; } + wait 6; + if (distance(player.origin, settled) > 8 || player.health != hp || + isdefined(player.campingtime)) { fail("camping"); return; } + setdvar("btd_nav_camping", "passed"); + if (getdvarint("btd_anticamp") != 0) { fail("classic_policy"); return; } + + setdvar("btd_nav_phase", "chase"); + destination = undefined; + for (i = 0; i < level.waypointcount; i++) + { + floor = supported_floor(level.waypoints[i].origin); + if (!isdefined(floor)) continue; + d = distance(level.zomspawns[0].origin, floor); + if (d < 500 || d > 1800) continue; + trace = bullettrace(level.zomspawns[0].origin + (0, 0, 30), + floor + (0, 0, 30), false, undefined); + if (trace["fraction"] >= 1) continue; + destination = floor; + break; + } + if (!isdefined(destination)) { fail("obstacle_pair"); return; } + player setorigin(destination + (0, 0, 1)); + wait 1; + setdvar("btd_nav_player_position", player.origin); + zombies = []; + for (i = 0; i < 600; i++) + { + zombies = getentarray("zom", "targetname"); + if (zombies.size > 0 && isdefined(zombies[0].health)) break; + wait 0.1; + } + if (!zombies.size) { fail("zombie_spawn"); return; } + target = zombies[0]; + level.btd_nav_tracked = target; + start = target.origin; + initial = distance(start, player.origin); + trace = bullettrace(start + (0, 0, 30), player.origin + (0, 0, 30), false, target); + if (trace["fraction"] >= 1 || initial < 400) { fail("obstacle_start"); return; } + setdvar("btd_nav_blocked_direct_path", "passed"); + setdvar("btd_nav_initial_distance", initial); + moved = 0; + closest = initial; + usedwaypoint = false; + previous = start; + route_length = 0; + previous_wp = -1; + waypoint_changes = 0; + for (i = 0; i < 900; i++) + { + if (!isdefined(target)) { fail("tracked_zombie_lost"); return; } + step = distance(previous, target.origin); + if (step > 100) { fail("navigation_jump"); return; } + segment = bullettrace(previous + (0, 0, 30), target.origin + (0, 0, 30), false, target); + if (segment["fraction"] < 1) { fail("navigation_wall_crossing"); return; } + if (i % 20 == 0) + println("BTD_NAV_SAMPLE tick=" + i + " pos=" + target.origin + " step=" + step + + " trace=" + segment["fraction"] + " wp=" + target.currentStaticWp); + route_length += step; + previous = target.origin; + displacement = distance(start, target.origin); + if (displacement > moved) moved = displacement; + separation = distance(target.origin, player.origin); + if (separation < closest) closest = separation; + if (isdefined(target.currentStaticWp) && target.currentStaticWp >= 0) + { + usedwaypoint = true; + if (target.currentStaticWp != previous_wp) + { + waypoint_changes++; + previous_wp = target.currentStaticWp; + } + } + if (getdvar("btd_nav_melee") == "passed" && moved > 256 && + closest < initial - 200 && waypoint_changes >= 2 && route_length > initial * 1.05) break; + wait 0.1; + } + setdvar("btd_nav_displacement", moved); + setdvar("btd_nav_closest_distance", closest); + setdvar("btd_nav_used_waypoint", usedwaypoint); + setdvar("btd_nav_route_length", route_length); + setdvar("btd_nav_waypoint_changes", waypoint_changes); + if (getdvar("btd_nav_melee") != "passed" || moved <= 256 || + closest >= initial - 200 || waypoint_changes < 2 || route_length <= initial * 1.05) { fail("chase"); return; } + setdvar("btd_nav_chase", "passed"); + setdvar("btd_nav_phase", "native_fire_wave"); + player freezecontrols(false); + player botstop(); + level.btd_nav_bullet_hits = 0; + initial_kills = player.kills; + for (i = 0; i < 1200; i++) + { + if (level.currentwave >= 2) break; + zombies = getentarray("zom", "targetname"); + nearest = undefined; + nearest_distance = 1000000; + for (j = 0; j < zombies.size; j++) + { + zombie = zombies[j]; + if (!isdefined(zombie.health) || zombie.health <= 0) continue; + if (!isdefined(zombie.btd_nav_observed)) + { + zombie.btd_nav_observed = true; + zombie thread observe_zombie_damage(player); + } + separation = distance(zombie.origin, player.origin); + if (separation < nearest_distance) + { + nearest_distance = separation; + nearest = zombie; + } + } + if (!isdefined(nearest)) + { + player botaction("-fire"); + wait 0.1; + continue; + } + // A stationary client can overlap melee attackers and spend its normal + // ammunition firing through nearby geometry. Walk to a collision-visible + // authored node, using native player input, instead of moving entities. + if (nearest_distance < 140 && (!isdefined(player.btd_nav_retreat) || + distance2d(player.origin, player.btd_nav_retreat) < 40)) + { + retreat = undefined; + for (k = 0; k < level.waypointcount; k++) + { + candidate = level.waypoints[k].origin; + separation = distance(player.origin, candidate); + if (separation < 200 || separation > 450 || + candidate[2] > player.origin[2] + 80 || candidate[2] < player.origin[2] - 80) + continue; + if (distance(candidate, nearest.origin) < nearest_distance + 150) continue; + clear = bullettrace(player.origin + (0, 0, 40), candidate + (0, 0, 40), false, player); + if (clear["fraction"] < 1) continue; + retreat = candidate; + break; + } + if (isdefined(retreat)) + { + player.btd_nav_retreat = retreat; + player botmoveto(retreat); + println("BTD_NAV_NATIVE_PLAYER_MOVE destination=" + retreat); + } + } + weapon = player.btd_nav_weapon; + player botweapon(weapon); + player botlookat(nearest.origin + (0, 0, 35), 0.1); + if (i % 50 == 0) + println("BTD_NAV_FIRE tick=" + i + " weapon=" + weapon + " ammo=" + + player getweaponammoclip(weapon) + " stock=" + player getweaponammostock(weapon) + + " kills=" + (player.kills - initial_kills) + " zombies=" + zombies.size + + " targetpos=" + nearest.origin + " targethp=" + nearest.health + + " wp=" + nearest.currentStaticWp + " playerpos=" + player.origin); + if (player getweaponammoclip(weapon) <= 0) + { + player botaction("-fire"); + player botaction("+reload"); + wait 2; + player botaction("-reload"); + } + else player botaction("+fire"); + wait 0.1; + } + player botstop(); + setdvar("btd_nav_bullet_hits", level.btd_nav_bullet_hits); + setdvar("btd_nav_bullet_kills", player.kills - initial_kills); + if (level.currentwave < 2 || level.btd_nav_bullet_hits < 1 || player.kills - initial_kills < 5) { fail("native_wave"); return; } + setdvar("btd_nav_wave", "passed"); + setdvar("btd_nav_result", "passed"); +} + +await_spawn() +{ + for (i = 0; i < 200; i++) + { + if (isalive(self) && self.sessionstate == "playing") return true; + wait 0.1; + } + return false; +} + +supported_floor(point) +{ + trace = bullettrace(point + (0, 0, 32), point - (0, 0, 80), false, undefined); + if (trace["fraction"] >= 1) return undefined; + return trace["position"]; +} + +observe_zombie_damage(player) +{ + for (;;) + { + self waittill("damage", amount, attacker, direction, point, means); + if (isdefined(attacker) && attacker == player && amount > 0 && + (means == "MOD_RIFLE_BULLET" || means == "MOD_PISTOL_BULLET")) + level.btd_nav_bullet_hits++; + } +} + +observe_player_damage(inflictor, attacker, amount, flags, means, weapon, point, direction, hitloc, offset) +{ + before = self.health; + self [[level.btd_nav_damage_callback]](inflictor, attacker, amount, flags, + means, weapon, point, direction, hitloc, offset); + if (isdefined(self.btd_nav_fixture) && self.health < before && + isdefined(inflictor) && isdefined(level.btd_nav_tracked) && + inflictor == level.btd_nav_tracked && means == "MOD_MELEE") + setdvar("btd_nav_melee", "passed"); +} + +fail(reason) +{ + setdvar("btd_nav_result", "failed_" + reason); +} diff --git a/tests/run_btd_navigation.py b/tests/run_btd_navigation.py new file mode 100644 index 00000000..d17004ae --- /dev/null +++ b/tests/run_btd_navigation.py @@ -0,0 +1,166 @@ +#!/usr/bin/env python3 +"""Private native BTD navigation qualification; never touches an existing runtime. + +Synthetic clients and authored-node collision traces do not replace graphical +operator-supervised qualification. Original assets and all full logs stay private. +""" +import argparse +import hashlib +import importlib.util +import json +from pathlib import Path +import re +import shutil +import socket +import subprocess +import tempfile +import time + +ROOT = Path(__file__).resolve().parents[1] +RUNNER_SHA256 = hashlib.sha256(Path(__file__).read_bytes()).hexdigest() +parser = argparse.ArgumentParser(description=__doc__) +for name in ('runtime', 'game', 'binary'): + parser.add_argument('--' + name, required=True, type=Path) +parser.add_argument('--original-waypoints', action='store_true', + help='Remove only the generated PeZBOT overlay in the disposable copy') +parser.add_argument('--expect-waypoint-defect', action='store_true', + help='Require the original exact Killhouse undefined-coordinate error') +a = parser.parse_args() +if a.expect_waypoint_defect and not a.original_waypoints: + parser.error('--expect-waypoint-defect requires --original-waypoints') +assert (a.runtime / '.bot-test-runtime').is_file() +spec = importlib.util.spec_from_file_location('btd_navigation_prepare', ROOT / 'tools/btd/prepare.py') +btd = importlib.util.module_from_spec(spec) +spec.loader.exec_module(btd) +home = Path(tempfile.mkdtemp(prefix='btd-navigation-')) +for name in ('mods', 'integrity'): + shutil.copytree(a.runtime / name, home / name) +for name in ('main', 'zone'): + (home / name).symlink_to((a.game / name).resolve(), target_is_directory=True) +shutil.copy2(a.binary, home / 'cod4x18_dedrun') +mod = home / 'mods/btd_alpha_001' +lock = json.loads((ROOT / 'tools/btd/dependencies.json').read_text()) +fastfile = mod / 'mod.ff' +assert hashlib.sha256(fastfile.read_bytes()).hexdigest() == lock['files']['btd_alpha_001/mod.ff'] +source = btd.death_overlay(fastfile.read_bytes(), lock['death_callback_source_sha256']).decode() +source = source.replace('init()\r\n{', 'init()\r\n{\r\n thread btd_navigation::main();', 1) +assert 'thread btd_navigation::main();' in source +out = mod / btd.SCRIPT.replace('.gsc', '.gsx') +out.parent.mkdir(parents=True, exist_ok=True) +out.write_bytes(source.encode()) +spawn = mod / btd.SPAWN_SCRIPT.replace('.gsc', '.gsx') +spawn.parent.mkdir(parents=True, exist_ok=True) +spawn.write_bytes(btd.spawn_overlay(fastfile.read_bytes(), lock['spawn_points_source_sha256'])) +nav_overlay = mod / 'svr/pezbot.gsx' +if a.original_waypoints: + if nav_overlay.exists(): + nav_overlay.unlink() +else: + assert nav_overlay.is_file(), 'A prepared, pinned PeZBOT navigation overlay is required' + expected = btd.navigation_overlay(fastfile.read_bytes(), lock['navigation_source_sha256']) + assert nav_overlay.read_bytes() == expected, 'Prepared PeZBOT overlay does not match pinned preparation' +shutil.copy2(ROOT / 'tests/btd_navigation.gsc', mod / 'btd_navigation.gsc') +baseline_config_hashes = {name: hashlib.sha256((mod / name).read_bytes()).hexdigest() + for name in ('canonical-shared.cfg', 'canonical-mode.cfg')} +manifest = a.runtime / 'inputs.json' +prepared_manifest = json.loads(manifest.read_text()) if manifest.is_file() else None +# Accelerate fixture grace/wave size and disabled camping thresholds. Enemy +# speed, damage and health are unchanged; fixture player health is increased. +with (mod / 'canonical-mode.cfg').open('a') as cfg: + cfg.write('\nset btd_grace_time "30"\nset btd_wave_settings "2"\nset btd_start_zoms "5"\nset btd_camp_max_time "2"\nset btd_camp_message_time "1"\n') +with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as channel: + channel.bind(('127.0.0.1', 0)) + port = channel.getsockname()[1] +command = [str(home / 'cod4x18_dedrun'), '+set', 'dedicated', '1', '+set', 'net_ip', '127.0.0.1', + '+set', 'net_port', str(port), '+set', 'fs_basepath', str(home), '+set', 'fs_homepath', str(home / 'persistent'), + '+set', 'fs_game', 'mods/btd_alpha_001', '+set', 'sv_autoupdate', '0', '+set', 'developer', '1', + '+set', 'developer_script', '1', '+set', 'fs_localizedHeadersPath', str(home / 'integrity'), + '+set', 'sv_maxclients', '12', '+set', 'btd_nav_scenario', 'navigation', + '+exec', 'canonical-shared.cfg', '+exec', 'canonical-mode.cfg', '+map', 'mp_killhouse'] +logpath = home / 'console.log' +checks = {} +measurements = {} + +def status(): + with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as channel: + channel.settimeout(3) + channel.sendto(b'\xff' * 4 + b'getstatus\n', ('127.0.0.1', port)) + data = channel.recv(65535) + assert b'statusResponse' in data + fields = data.split(b'\n')[1].split(b'\\') + return dict(zip(fields[1::2], fields[2::2])) + +with logpath.open('w') as output: + proc = subprocess.Popen(command, cwd=home, stdin=subprocess.PIPE, stdout=output, stderr=subprocess.STDOUT) + def send(value): + assert proc.poll() is None, 'Native server exited: ' + str(home) + proc.stdin.write((value + '\n').encode()) + proc.stdin.flush() + try: + text = '' + deadline = time.monotonic() + 300 + while time.monotonic() < deadline and proc.poll() is None: + time.sleep(.25) + text = re.sub(r'\^[0-9]', '', logpath.read_text(errors='replace')) + if re.search(r'script (?:runtime|compile) error', text): + break + send('btd_nav_result\nbtd_nav_phase') + if re.search(r'"btd_nav_result" is: "(?:passed|failed_[^"]+)"', text): + break + if not a.expect_waypoint_defect and proc.poll() is None and not re.search(r'script (?:runtime|compile) error', text): + for key in ('phase', 'respawn', 'camping', 'elevation', 'nodes', 'linked_spawns', 'max_spawn_link', 'blocked_direct_path', 'initial_distance', + 'displacement', 'closest_distance', 'used_waypoint', 'route_length', 'waypoint_changes', + 'melee', 'chase', 'bullet_hits', 'bullet_kills', 'wave'): + send('btd_nav_' + key) + time.sleep(.03) + if '"btd_nav_result" is: "passed"' in text and not a.expect_waypoint_defect: + send('set btd_nav_scenario idle') + for name in ('mp_crash', 'mp_killhouse'): + send('map ' + name) + time.sleep(5) + values = status() + checks['transition_' + name] = values.get(b'mapname') == name.encode() and values.get(b'sv_pure') == b'1' and values.get(b'g_gametype') == b'war' + send('btd_nav_nodes\nbtd_nav_map\nbtd_anticamp') + time.sleep(.25) + finally: + if proc.poll() is None: + try: + send('quit') + except (AssertionError, BrokenPipeError): + pass # A fatal native error may finish shutdown after poll(). + try: + proc.wait(timeout=8) + except subprocess.TimeoutExpired: + proc.kill() + proc.wait() +text = re.sub(r'\^[0-9]', '', logpath.read_text(errors='replace')) +error = bool(re.search(r'script (?:runtime|compile) error', text)) +original_defect = (error and 'cannot cast undefined to string' in text and + "file 'svr/pezbot.gsc', line 1928" in text and 'LoadStaticWaypoints();' in text) +checks['original_marker_preserved'] = 'BTD_NAV_MARKER value=[end ] length=4' in text +if a.expect_waypoint_defect: + checks['expected_original_defect'] = original_defect +else: + checks['no_script_error'] = not error + checks['navigation_pass'] = '"btd_nav_result" is: "passed"' in text + checks['eight_headers'] = 'Loaded 8 administrative IWD checksums' in text + for name in ('respawn', 'camping', 'blocked_direct_path', 'melee', 'chase', 'wave'): + checks[name] = f'"btd_nav_{name}" is: "passed"' in text + for name in ('nodes', 'linked_spawns', 'max_spawn_link', 'elevation', 'initial_distance', 'displacement', 'closest_distance', 'used_waypoint', 'route_length', 'waypoint_changes', 'bullet_hits', 'bullet_kills'): + matches = re.findall(r'"btd_nav_' + name + r'" is: "([^"]+)"', text) + measurements[name] = matches[-1] if matches else None +result = {'evidence': str(home), 'checks': checks, 'measurements': measurements, + 'original_waypoints': a.original_waypoints, 'runtime_error': error, + 'gameplay_qualified': False, 'binary_sha256': hashlib.sha256((home / 'cod4x18_dedrun').read_bytes()).hexdigest(), + 'mod_ff_sha256': hashlib.sha256(fastfile.read_bytes()).hexdigest(), + 'navigation_overlay_sha256': hashlib.sha256(nav_overlay.read_bytes()).hexdigest() if nav_overlay.exists() else None, + 'fixture_sha256': hashlib.sha256((mod / 'btd_navigation.gsc').read_bytes()).hexdigest(), + 'runner_sha256': RUNNER_SHA256, + 'baseline_config_sha256': baseline_config_hashes, + 'fixture_config_sha256': {name: hashlib.sha256((mod / name).read_bytes()).hexdigest() + for name in ('canonical-shared.cfg', 'canonical-mode.cfg')}, + 'prepared_inputs': prepared_manifest} + +(home / 'results.json').write_text(json.dumps(result, indent=2) + '\n') +print(json.dumps(result, indent=2)) +assert all(checks.values()), 'Native navigation qualification failed: ' + str(home) diff --git a/tests/test_btd_navigation.py b/tests/test_btd_navigation.py new file mode 100644 index 00000000..767e0327 --- /dev/null +++ b/tests/test_btd_navigation.py @@ -0,0 +1,91 @@ +"""Synthetic map graph fixtures; no vendor coordinates or waypoint data.""" +import importlib.util +from pathlib import Path +import unittest + +spec = importlib.util.spec_from_file_location('btd_navigation', Path(__file__).parents[1] / 'tools/btd/navigation.py') +nav = importlib.util.module_from_spec(spec) +spec.loader.exec_module(nav) + + +class NavigationValidation(unittest.TestCase): + def rows(self): + return [['10', '0 0 0', '1 2', 'stand'], + ['11', '10 0 0', '0 2', 'stand'], + ['12', '10 10 0', '0 1', 'stand'], ['13', 'end', '0', '0']] + + def validate(self, rows, **kwargs): + return nav.validate_rows(rows, offset=10, count=3, **kwargs) + + def test_valid_connected_reciprocal_graph(self): + report = self.validate(self.rows()) + self.assertEqual(report['nodes'], 3) + self.assertEqual(report['directed_edges'], 6) + self.assertTrue(report['connected']) + self.assertFalse(report['geometry_qualified']) + self.assertFalse(report['gameplay_qualified']) + self.assertFalse(report['angle_column']) + + def test_original_trailing_space_terminal_rejected(self): + rows = self.rows(); rows[-1][1] = 'end ' + with self.assertRaisesRegex(ValueError, 'terminal'): + self.validate(rows) + + def test_missing_invalid_or_nonfinite_coordinates(self): + for value in ['', '1', '1 2', '1 2 3 4', '1 x 3', 'nan 1 2', '1 inf 2', '1e999 1 2', '1e39 1 2', '1_0 2 3', '١ 2 3', '1\t2 3', '1\n2 3', '1\u00a02 3']: + with self.subTest(value=value): + rows = self.rows(); rows[0][1] = value + with self.assertRaises(ValueError): self.validate(rows) + for value in [None, [1, 2], [1, None, 3]]: + with self.subTest(value=value): + with self.assertRaises(ValueError): nav.vector(value) + + def test_missing_duplicate_or_malformed_map_rows(self): + for rows in [self.rows()[:-1], self.rows() + [self.rows()[0]], + [self.rows()[0][:-1]] + self.rows()[1:]]: + with self.assertRaises(ValueError): self.validate(rows) + + def test_invalid_child_syntax_bounds_self_duplicates(self): + for value in ['', '-1 2', '+1 2', '1.0 2', 'x 2', '1 3', '0 1', '1 1', '1\t2', '1\n2', '1\u00a02']: + with self.subTest(value=value): + rows = self.rows(); rows[0][2] = value + with self.assertRaises(ValueError): self.validate(rows) + + def test_nonreciprocal_edge_rejected(self): + rows = self.rows(); rows[1][2] = '2' + with self.assertRaisesRegex(ValueError, 'Nonreciprocal'): self.validate(rows) + + def test_disconnected_graph_rejected(self): + rows = [['10', '0 0 0', '1', 'stand'], ['11', '1 0 0', '0', 'stand'], + ['12', '2 0 0', '3', 'stand'], ['13', '3 0 0', '2', 'stand'], + ['14', 'end', '0', '0']] + with self.assertRaisesRegex(ValueError, 'Disconnected'): + nav.validate_rows(rows, offset=10, count=4) + + def test_duplicate_origins_and_unknown_type_rejected(self): + rows = self.rows(); rows[1][1] = rows[0][1] + with self.assertRaisesRegex(ValueError, 'Duplicate waypoint origin'): self.validate(rows) + rows = self.rows(); rows[0][3] = 'unknown' + with self.assertRaisesRegex(ValueError, 'type'): self.validate(rows) + + def test_unrelated_map_rows_do_not_change_selected_graph(self): + rows = [['broken unrelated cell'], ['99', 'bad', 'bad', 'bad']] + self.rows() + self.assertEqual(self.validate(rows), self.validate(self.rows())) + + def test_all_spawn_associations_and_explicit_proximity_gate(self): + spawns = {index: (1, 1, 0) for index in range(25)} + report = self.validate(self.rows(), spawns=spawns, max_spawn_distance=2) + self.assertEqual(len(report['spawn_associations']), 25) + self.assertTrue(all(item['node'] == 0 for item in report['spawn_associations'])) + with self.assertRaisesRegex(ValueError, 'distance'): + self.validate(self.rows(), spawns=spawns, max_spawn_distance=1) + del spawns[0] + with self.assertRaisesRegex(ValueError, '25'): self.validate(self.rows(), spawns=spawns) + + def test_spawn_branch_parser_rejects_missing_ambiguous_duplicates(self): + marker = 'else if(getDvar("mapname") == "mp_killhouse")' + source = marker + '{' + ''.join(f'zomspawnpoint[{i}] = (1,2,3);' for i in range(25)) + '} // Overgrown' + self.assertEqual(len(nav.spawn_points(source)), 25) + for invalid in ['', marker + source, source.replace('[24]', '[23]'), + source.replace('(1,2,3)', '(1,2)', 1)]: + with self.assertRaises(ValueError): nav.spawn_points(invalid) diff --git a/tests/test_btd_prepare.py b/tests/test_btd_prepare.py index 41e9768a..43816e89 100644 --- a/tests/test_btd_prepare.py +++ b/tests/test_btd_prepare.py @@ -32,6 +32,8 @@ def setUp(self): payload = b'fixture!' + struct.pack('= count or item == index for item in linked): + raise ValueError('Out-of-range or self child index') + if row[3] != 'stand': + raise ValueError('Unexpected Killhouse waypoint type') + children.append(linked) + if len(set(origins)) != count: + raise ValueError('Duplicate waypoint origin') + for index, linked in enumerate(children): + if any(index not in children[other] for other in linked): + raise ValueError('Nonreciprocal child edge') + seen, todo = {0}, [0] + while todo: + for other in children[todo.pop()]: + if other not in seen: + seen.add(other) + todo.append(other) + if len(seen) != count: + raise ValueError('Disconnected waypoint graph') + report = {'map': MAP, 'offset': offset, 'nodes': count, + 'directed_edges': sum(map(len, children)), 'connected': True, + 'reciprocal': True, 'angle_column': False, + 'bounds': [[min(v[i] for v in origins), max(v[i] for v in origins)] + for i in range(3)], + 'geometry_qualified': False, 'gameplay_qualified': False} + if max_spawn_distance is not None and (not math.isfinite(max_spawn_distance) or max_spawn_distance <= 0): + raise ValueError('Invalid maximum spawn distance') + if spawns is not None: + if set(spawns) != set(range(25)): + raise ValueError('Expected all 25 distinct vendor spawn indices') + associations = [] + for index in range(25): + origin = vector(spawns[index]) + nearest = min(range(count), key=lambda n: math.dist(origin, origins[n])) + distance = math.dist(origin, origins[nearest]) + if max_spawn_distance is not None and distance > max_spawn_distance: + raise ValueError('Spawn exceeds specified nearest-node distance') + associations.append({'spawn': index, 'node': nearest, 'distance': distance}) + report['spawn_associations'] = associations + report['spawn_distance_max'] = max(item['distance'] for item in associations) + return report + + +def spawn_points(source): + """Read only the original Killhouse branch from a private pinned GSC input.""" + marker = 'else if(getDvar("mapname") == "mp_killhouse")' + if source.count(marker) != 1: + raise ValueError('Missing or ambiguous Killhouse spawn branch') + branch = source.split(marker, 1)[1].split('// Overgrown', 1)[0] + matches = re.findall(r'zomspawnpoint\[(\d+)\]\s*=\s*\(([^)]+)\);', branch) + result = {} + for index, raw in matches: + index = int(index) + if index in result: + raise ValueError('Duplicate spawn index') + result[index] = vector(raw.split(',')) + if set(result) != set(range(25)): + raise ValueError('Expected all 25 vendor spawn points') + return result + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--table', type=Path, required=True, help='Private CSV export of waypoint table 4 with the terminal marker corrected') + parser.add_argument('--spawns', type=Path, help='Private original survival spawn GSC source') + parser.add_argument('--max-spawn-distance', type=float, help='Optional explicit geometric proximity gate; not proof of collision clearance') + args = parser.parse_args() + try: + spawns = spawn_points(args.spawns.read_text()) if args.spawns else None + # Stringtable exports may include non-UTF8 cells belonging to other maps. + # Native lookup also selects by exact global key; those cells stay private. + with args.table.open(encoding='latin1', newline='') as stream: + report = validate_rows(csv.reader(stream), spawns=spawns, + max_spawn_distance=args.max_spawn_distance) + except (OSError, ValueError) as exc: + parser.exit(1, f'Navigation validation failed: {exc}\n') + print(json.dumps(report, indent=2)) + + +if __name__ == '__main__': + main() diff --git a/tools/btd/prepare.py b/tools/btd/prepare.py index deff6f4b..bde4e7c9 100644 --- a/tools/btd/prepare.py +++ b/tools/btd/prepare.py @@ -24,7 +24,7 @@ def digest(path): ' && eInflictor.targetname == "zom"') -def raw_source(fastfile, name, expected): +def raw_source(fastfile, name, expected, encoding='utf-8'): # This member is plaintext GSC already stored in the verified fastfile. # No bytecode decompiler or asset rebuild is involved. Never save the source # in the repository; only the operator's private prepared runtime receives it. @@ -40,7 +40,7 @@ def raw_source(fastfile, name, expected): raw = data[start:start + length] if hashlib.sha256(raw).hexdigest() != expected: raise ValueError('BTD death callback source hash mismatch') - return raw.decode('utf-8') + return raw.decode(encoding) def death_overlay(fastfile, expected): @@ -64,6 +64,28 @@ def spawn_overlay(fastfile, expected): ' temp.angles = (0, 0, 0);').encode('utf-8') +NAVIGATION_SCRIPT = 'svr/pezbot.gsc' +NAVIGATION_END_CHECK = ' if(!isDefined(string) || string == "" || string == "end")' +# The pinned Killhouse table contains 101 valid nodes, then the marker "end ". +# Keep all node coordinates, connectivity and the other map loaders unchanged. +KILLHOUSE_TERMINATOR_REPAIR = ( + ' // Modified 2026-10-27: repair only the pinned Killhouse terminator.\r\n' + ' if(getdvar("mapname") == "mp_killhouse" && iLineOffset == 4827 &&\r\n' + ' compiledFilename == "waypoints/PeZBOT_WP_4.csv" &&\r\n' + ' level.waypointCount == 101 && string == "end ")\r\n' + ' string = "end";\r\n\r\n') + + +def navigation_overlay(fastfile, expected): + # Latin-1 is a reversible byte mapping: this vendor file has CP1252 comments. + # Inserting ASCII must not recode or discard the original source bytes. + source = raw_source(fastfile, NAVIGATION_SCRIPT, expected, encoding='latin-1') + if source.count(NAVIGATION_END_CHECK) != 1: + raise ValueError('Unexpected BTD waypoint termination check') + return source.replace(NAVIGATION_END_CHECK, + KILLHOUSE_TERMINATOR_REPAIR + NAVIGATION_END_CHECK).encode('latin-1') + + def prepare(source, headers, binary, output): lock = json.loads((ROOT / 'tools/btd/dependencies.json').read_text()) header_lock = json.loads((ROOT / 'bots/dependencies.json').read_text())['integrity_headers'] @@ -78,6 +100,8 @@ def prepare(source, headers, binary, output): lock['death_callback_source_sha256']) spawn = spawn_overlay((source / 'btd_alpha_001/mod.ff').read_bytes(), lock['spawn_points_source_sha256']) + navigation = navigation_overlay((source / 'btd_alpha_001/mod.ff').read_bytes(), + lock['navigation_source_sha256']) binary_hash = digest(binary) if output.exists(): raise ValueError('Output must be a new directory; existing runtimes are never overwritten') @@ -99,6 +123,9 @@ def prepare(source, headers, binary, output): spawn_path = mod / SPAWN_SCRIPT.replace('.gsc', '.gsx') spawn_path.parent.mkdir(parents=True, exist_ok=True) spawn_path.write_bytes(spawn) + navigation_path = mod / NAVIGATION_SCRIPT.replace('.gsc', '.gsx') + navigation_path.parent.mkdir(parents=True, exist_ok=True) + navigation_path.write_bytes(navigation) notices = output / 'licenses' notices.mkdir() shutil.copy2(source / 'readme.txt', notices / 'Before-the-Dawn-readme.txt') @@ -116,9 +143,11 @@ def prepare(source, headers, binary, output): if k.startswith('btd_alpha_001/') and Path(k).name != 'server.cfg'}, 'default_cfgs': lock['default_cfgs'], 'overlays': {str(patched.relative_to(mod)): digest(patched), - str(spawn_path.relative_to(mod)): digest(spawn_path)}, + str(spawn_path.relative_to(mod)): digest(spawn_path), + str(navigation_path.relative_to(mod)): digest(navigation_path)}, 'death_callback_source_sha256': lock['death_callback_source_sha256'], 'spawn_points_source_sha256': lock['spawn_points_source_sha256'], + 'navigation_source_sha256': lock['navigation_source_sha256'], 'dependency_lock_sha256': digest(ROOT / 'tools/btd/dependencies.json'), 'qualification': 'original package map list; gameplay qualification is separate'} (output / 'inputs.json').write_text(json.dumps(record, indent=2) + '\n')