diff --git a/bots/btd_allies.gsc b/bots/btd_allies.gsc new file mode 100644 index 00000000..0634d313 --- /dev/null +++ b/bots/btd_allies.gsc @@ -0,0 +1,252 @@ +// Allied native clients for Before the Dawn. Original integration, AGPL-3.0-or-later. +// Vendor zombie navigation remains authoritative and is only read here. +init() +{ + setdvar("bot_ai_ready", 0); + if (!getdvarint("btd_allies_enable") || getdvar("g_gametype") != "war" || getdvarint("sv_pure") != 1) + return; + level endon("game_ended"); + level.btd_ally_sequence = 0; + while (!isdefined(level.waypointcount) || level.waypointcount < 1) wait 0.1; + // Register before enabling native creation, so no connect notification is lost. + level thread connections(); + level thread ended(); + setdvar("bot_ai_ready", 1); + players = getentarray("player", "classname"); + for (i = 0; i < players.size; i++) + if (players[i].isbot) players[i] thread attach(); +} + +ended() +{ + level waittill("game_ended"); + setdvar("bot_ai_ready", 0); + players = getentarray("player", "classname"); + for (i = 0; i < players.size; i++) + if (players[i].isbot) players[i] botstop(); +} + +connections() +{ + level endon("game_ended"); + for (;;) + { + level waittill("connected", player); + if (isdefined(player) && player.isbot) player thread attach(); + } +} + +human_players() +{ + result = []; + players = getentarray("player", "classname"); + for (i = 0; i < players.size; i++) + if (!players[i].isbot) result[result.size] = players[i]; + return result; +} + +attach() +{ + self endon("disconnect"); + level endon("game_ended"); + if (isdefined(self.btd_ally_attached)) return; + self.btd_ally_attached = true; + self.btd_ally = true; + // Cycle 3 easy / 2 medium; never modify vendor zombie difficulty. + self.btd_ally_skill = "easy"; + if (level.btd_ally_sequence % 5 >= 3) self.btd_ally_skill = "medium"; + level.btd_ally_sequence++; + self.pers["isBot"] = true; + wait 1; + self maps\mp\gametypes\_globallogic::menuAllies(); + wait 0.2; + // Vendor validates class and grants its normal weapons/ammunition. + self maps\mp\gametypes\_globallogic::menuClass("specops_mp,0"); + self thread think(); +} + +think() +{ + self endon("disconnect"); + level endon("game_ended"); + previous = undefined; + acquired = 0; + next_shot = 0; + next_route = 0; + for (;;) + { + self botaction("-fire"); + if (!getdvarint("btd_allies_enable") || !isalive(self) || self.sessionstate != "playing") + { + self botstop(); + previous = undefined; + wait 0.2; + continue; + } + target = self target_zombie(); + now = gettime(); + reaction = 1400; + interval = 1000; + error = 65; + if (self.btd_ally_skill == "medium") + { + reaction = 900; + interval = 700; + error = 40; + } + if (!isdefined(target) || !isdefined(previous) || target != previous) + { + acquired = now; + previous = target; + } + if (now >= next_route) + { + self follow_human(); + next_route = now + 1000; + } + if (isdefined(target)) + { + aim = target.origin + (randomfloatrange(0 - error, error), randomfloatrange(0 - error, error), 32); + self botlookat(aim, 0.3); + weapon = self select_weapon(); + self botweapon(weapon); + if (self getweaponammoclip(weapon) <= 0) + { + self botaction("+reload"); + wait 2; + self botaction("-reload"); + } + else if (now - acquired >= reaction && now >= next_shot) + { + // Let the native turn finish before any firing pulse: do not + // sweep fire across players while turning toward a zombie. + wait 0.35; + if (self safe_shot(aim, target)) + { + self botaction("+fire"); + wait 0.1; + self botaction("-fire"); + } + next_shot = gettime() + interval; + } + } + wait 0.1; + } +} + +target_zombie() +{ + zombies = getentarray("zom", "targetname"); + best = undefined; + range = 900; + for (i = 0; i < zombies.size; i++) + { + zombie = zombies[i]; + if (!isdefined(zombie.health) || zombie.health <= 0) continue; + separation = distance(self.origin, zombie.origin); + if (separation >= range) continue; + trace = bullettrace(self geteye(), zombie.origin + (0, 0, 32), true, self); + // Script-model damage surfaces may not be returned as the trace entity. + // A clear segment to the zombie is also visible; player blockers remain solid. + if (trace["fraction"] == 1 || (isdefined(trace["entity"]) && trace["entity"] == zombie)) + { + best = zombie; + range = separation; + } + } + return best; +} + +safe_shot(aim, target) +{ + if (!isalive(self) || self.sessionstate != "playing" || !getdvarint("btd_allies_enable")) return false; + // Trace with player collision: never intentionally fire through a human. + trace = bullettrace(self geteye(), aim, true, self); + if (isdefined(trace["entity"]) && isplayer(trace["entity"])) return false; + // Native aim interpolation may still be turning from the previous target. + direction = anglestoforward(self getplayerangles()); + actual = bullettrace(self geteye(), self geteye() + direction * 1000, true, self); + if (isdefined(actual["entity"]) && isplayer(actual["entity"])) return false; + return isdefined(target) && isdefined(target.health) && target.health > 0; +} + +follow_human() +{ + humans = human_players(); + leader = undefined; + range = 999999; + for (i = 0; i < humans.size; i++) + { + if (!isalive(humans[i]) || humans[i].sessionstate != "playing") continue; + separation = distance(self.origin, humans[i].origin); + if (separation < range) { leader = humans[i]; range = separation; } + } + if (!isdefined(leader) || range < 220) { self stop_movement(); return; } + trace = bullettrace(self.origin + (0, 0, 40), leader.origin + (0, 0, 40), false, self); + if (trace["fraction"] == 1) { self botmoveto(leader.origin); return; } + start = self nearest_node(self.origin, true); + goal = self nearest_node(leader.origin, false); + if (start < 0 || goal < 0) { self stop_movement(); return; } + // Local BFS arrays, no writes to the vendor graph or its search metadata. + queue = []; parent = []; queue[0] = start; parent[start] = start; + for (head = 0; head < queue.size && !isdefined(parent[goal]); head++) + { + node = queue[head]; + children = level.waypoints[node].children; + for (j = 0; j < children.size; j++) + { + child = children[j]; + if (child < 0 || child >= level.waypointcount || isdefined(parent[child])) continue; + parent[child] = node; + queue[queue.size] = child; + } + } + if (!isdefined(parent[goal])) { self stop_movement(); return; } + next = goal; + while (parent[next] != start && parent[next] != next) next = parent[next]; + destination = level.waypoints[next].origin; + if (distance(self.origin, level.waypoints[start].origin) > 70) destination = level.waypoints[start].origin; + self botmoveto(destination); +} + +select_weapon() +{ + weapon = self getcurrentweapon(); + if (weapon == "none" || weapon == "" || weapon == "defaultweapon_mp" || + (self getweaponammoclip(weapon) <= 0 && self getweaponammostock(weapon) <= 0)) + { + owned = self getweaponslistprimaries(); + for (i = 0; i < owned.size; i++) + { + candidate = owned[i]; + if (self getweaponammoclip(candidate) > 0 || self getweaponammostock(candidate) > 0) + return candidate; + } + } + return weapon; +} + +stop_movement() +{ + weapon = self select_weapon(); + self botstop(); + self botweapon(weapon); +} + +nearest_node(origin, visible) +{ + best = -1; range = 999999; + for (i = 0; i < level.waypointcount; i++) + { + candidate = level.waypoints[i].origin; + separation = distance(origin, candidate); + if (separation >= range) continue; + if (visible) + { + trace = bullettrace(origin + (0, 0, 40), candidate + (0, 0, 40), false, self); + if (trace["fraction"] < 1) continue; + } + best = i; range = separation; + } + return best; +} diff --git a/docs/zombies-allied-bots.md b/docs/zombies-allied-bots.md new file mode 100644 index 00000000..eda020da --- /dev/null +++ b/docs/zombies-allied-bots.md @@ -0,0 +1,197 @@ +# Native allied soldiers for Zombies Classic + +Protected engine baseline: `24f5cfabfb2dabacfb154b3430c06607c9a19897` +(PR #24), configuration master +`9f0fa1a0b0c1483ea20a89fc7beaf26c9b7c2201`, workspace master +`da5360d`. PRs #20/#21/#23/#24 provide the death/spawn fixes, Classic policy, +Killhouse navigation and prepared map declaration. Existing Promod command +behavior includes PR #12. The earlier single-bot investigation on +`feat/zombies-allies-qualification`, evidence +`/tmp/btd-death-regression-fk40my4r`, is preserved; it does not qualify this work. + +## Integration + +Preparation is explicitly opt-in: add `--allies` to `tools/btd/prepare.py`. +Baseline preparation remains available. Allied preparation requires the companion +workspace asset-validation change; older packaging rejects its additional code. +No original inputs are edited or proprietary source files committed. + +The independent authored controller uses native client inputs and reads BTD's +waypoint graph. It never initializes Bot Warfare or writes enemy pathfinding +state. Bots follow living human survivors and target only living vendor zombies. +First-use ammo-drop eligibility is initialized only when absent for any survivor. +The vendor pickup and grace-period cooldown still perform restocking. Both ammo +cooldown threads cancel on disconnect before resuming into a removed entity. Vendor loadouts, ammunition, +damage, zombie construction and wave spawning remain +authoritative. There are no scripted enemy damage/kill shortcuts. + +The native manager gates creation on the exact BTD mod, `war`, pure mode and +script readiness. `btd_allies_enable=1` and `btd_allies_limit=5` are defaults; +a baseline runtime without the allied overlay never signals readiness. Explicit +`btd_allies_enable=0` disables the controller. Promod retains its existing +`bot_enable`, twelve-client fill policy and difficulty settings. + +Five default allies cycle through three easy and two medium profiles. Easy bots +have a 1.4-second acquisition delay, 1-second shot interval and 65-unit horizontal +aim error; medium uses 0.9 seconds, 0.7 seconds and 40 units. Both use short firing +pulses and wait for native turning before checking human obstructions. These are +implementation settings, not measured balance against competent humans. The +vendor's unconditional player-versus-player damage protection is pinned and +preserved independently of aim checks. + +Human-only overlays cover wave population calculations, stock survivor counts +and vendor elimination monitoring. Native allies remain combat targets for +zombies but cannot sustain a round after the last human survivor dies. Native +capacity accounting includes connected humans; allies yield public slots through +the existing validated connection path. + +## Administration + +Existing command names and strict decimal count range `0..12` remain unchanged: + +| Command | Permission | Behavior | +| --- | --- | --- | +| `bot_add count` | 80 | Add within current limit and capacity | +| `bot_kick count` | 80 | Remove native allies and pause Auto-Fill | +| `bot_kickall` | 80 | Remove allies and pause before disconnect callbacks | +| `bot_killall` | 80 | Normal death callback for living native allies; keep connections | +| `bot_status` | 20 | Population, readiness, fill state and profile mode | + +Enemies are script entities, never native bot clients. These commands do not +affect humans or enemy zombies. No single-bot kill command is added. Bots killed during an active wave wait for the vendor joining window; killing +them does not bypass Zombies respawn rules. Existing +`bot_autofill 1` explicitly resumes filling; the prior last-human-leaves pause +policy is retained across maps. `bot_limit` selects the BTD-specific limit in +BTD, leaving Promod's limit untouched. Status reports profile mode, not measured +per-profile population. + +## Provenance and repeatable validation + +Original fastfile SHA-256 remains +`50911fdd0273b50e26983723619881acfaed4aa65f4d91a799a341464c2224a6`. +All private source identities are pinned in `tools/btd/dependencies.json`. +Allied preparation declares exactly seven overlays with hashes; packaging checks +those identities and rejects undeclared source files and symlinks. The existing +three-overlay recipe, licenses, original configuration and eight administrative +headers remain preserved. `sv_pure=1` stays mandatory. + +```sh +make -j4 +python3 -m unittest discover -s tests -p 'test_*.py' +gcc -Wall -Wextra -Werror tests/test_bot_policy.c -o /tmp/allied-bot-policy +/tmp/allied-bot-policy +python3 tests/run_map_rotation.py +python3 tests/run_map_voting.py +python3 tests/run_btd_allies.py --runtime PRIVATE_PACKAGED_RUNTIME --game GAME_DATA --binary bin/cod4x18_dedrun +python3 tests/run_btd_navigation.py --runtime PRIVATE_BASELINE_RUNTIME --game GAME_DATA --binary bin/cod4x18_dedrun +python3 tests/run_btd_integration.py --runtime PRIVATE_BASELINE_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 allied runner creates disposable loopback processes. Synthetic human clients +complete actual UDP admission and are classified as native humans. Its test-only +plugin enters them into the world, acknowledges reliable traffic and supplies +headless pure/profile completion; this does not test graphical client pure +verification or profile upload. The fixture raises only human health for sustained +observation and accelerates grace/initial-wave size. It does not grant ammunition +or fake enemy damage. Full private runtime logs stay outside Git. + +## Delivery and rollback + +Owner review and manual merge require green existing mandatory checks. No new +workflow, deployment system, image publication or monitoring is introduced. +After approved merges, prepare a fresh private artifact using the exact reviewed +engine and packaging revisions. Deployment requires separate operator approval; +qualification requires supervised graphical gameplay on homologation, including +five allies together, human kill dominance, navigation/obstacles, ammunition, +death/respawn, all-human elimination, waves, reconnection and map transitions. +Synthetic tests cannot certify those balance and graphical-client gates. + +Production remains on its known-good Promod artifact. No production, AWS, Bard, +or existing running service is changed by this work. Roll back through reviewed +reverts or reprepare without `--allies`; retain accepted death/spawn, Classic and +Killhouse repairs. Any running-service rollback needs operator authorization and +the exact previously approved artifact. Preserve the old PoC and all failed and +successful qualification directories. + +## Baseline verification in this change + +The pre-commit native executable SHA-256 is +`2aac8c013b234a4dee8272bcb8e3fc09f5df3e35a7f8f936ccf0bb464e607b70`. +Existing linker text-relocation warnings remain; compilation succeeds. + +- Engine unit suite: 70 tests, passed with one optional public-client checkout + skipped (`COD4X_CLIENT_SOURCE` unset). Native execution requires an unsandboxed + local test process because sandbox restrictions cause SIGSYS/socket failures. +- Native population policy, linked map rotation and map voting suites passed. +- Fresh Promod runtime: 53/53 checks, including bot administration and maps, + `/tmp/cod4x-promod-integration-fi4rcfpt/results.json`. +- Original BTD preparation: 73/73 checks across all 16 maps and restart, + `/tmp/cod4-btd-qualified-9ci8h2bm/results.json`. +- Existing native Killhouse suite: 12/12, + `/tmp/btd-navigation-pxn0vvrh/results.json`, including native enemy navigation, + melee, 20 bullet hits/five credited kills, wave progression and transitions. + This baseline suite does not independently certify allied obstacle traversal. +- Companion packaging: all 50 Python tests and the full mocked Operations suite + passed. Actual new private allied preparation plus packaging passed, retaining + original assets and the exact seven-overlay manifest. +- Separate architecture, gameplay, native-testing and independent-review agents + participated. Final source review found no blocking issue; native evidence and + operator qualification are distinct gates. + +Earlier native runs remain preserved, including scriptadmin connection rejection +(`/tmp/btd-five-allies-q1yrx1ow`), headless transport/visibility problems +(`/tmp/btd-five-allies-ecze7vy_`) and an old-fixture wave-respawn expectation +(`/tmp/btd-five-allies-b2dxxb4n`). Failed runs are not qualification evidence. + +A further rejected run, `/tmp/btd-five-allies-kzstcxhj`, exposed missing +first-use vendor ammo-drop eligibility during native capacity refill; the +undefined-only pickup initialization above addresses that failure. A subsequent +removed-player cooldown error required the pinned seventh ammo safety overlay. + + +## Final allied native qualification + +**52/52 checks passed** at +`/tmp/btd-five-allies-1efma7z3/results.json`, with no script errors and both +process shutdowns returning zero. The source audit at that same directory matches +all seven production overlays after removing exactly the two documented test-only +injections, and matches the observer fixture. Its dependency-lock SHA-256 is +`b145c6dcc94dfe2486fb8c0c9e8e165c387df7b321e10fcfa04540557882bb76`. + +- Five default living allies, exactly three easy/two medium; no human/no wave. +- All five original client slots fired actual rounds at live vendor zombies. + Combat snapshot: 13 attributed native allied bullet hits, 140 vendor melee + damage events against allies, zero allied kills versus eight synthetic-human + kills, and no allied damage to humans. Six positive/blocked shot-guard trials. +- Five actual administrative deaths and normal grace respawn; live-wave deaths + respect the joining window. Kick, kickall pause, explicit re-add, empty killall, + invalid counts, authenticated/denied RCON, and human preservation passed. +- Full capacity: 11 allies plus one actual human; a second human connection + reclaimed one slot, leaving ten allies and two humans. Reconnection passed. +- Active wave three: ten living allies and two living humans before suicide; + actual vendor end event had ten living allies and zero living humans. +- Killhouse→Crash→Killhouse, restart with five living allies, pure mode and eight + administrative headers passed. Dynamic mode produced exactly 28 zombies for + one human plus five allies, rather than the 58 that six counted players imply. +- Native horizontal following displacement from grace respawn to autonomous + observation: slot zero 369.198 units; slot four 341.192 units. This does not + qualify a dedicated allied obstacle/BFS route or all-map allied gameplay. + +Runner SHA-256: +`c90818a77734a420d7130dd89e473e9ddc9cd8ef4e6dea63f86d7e4d865f0e06`; +observer fixture: +`0192315dd0eb0fc1ab0ee57413e1b5c6f1e06fd191e5fc58bd6f5a14725f6a34`. +The earlier seven-overlay run `/tmp/btd-five-allies-km2cjkwf` remains **50/52, +failed**: its assertions raced legitimate grace spawning and human respawn. +The accepted runner waits for normal spawn ticks and requires an active wave +before elimination; no game state or damage was fabricated to satisfy them. + +Implementation is [engine PR #25](https://github.com/ghptc/cod4x-server/pull/25); +packaging is [workspace PR #17](https://github.com/ghptc/ec2-workspace/pull/17), +head `c118e84984f8a2351c75756fdc6e6a215732a3b2`. Linux and Windows CI passed +implementation head `58ac058b694ec687d2607b463fbc85a6a974921e`; workspace +Operations passed its final head. The final evidence/runner commit must retain +green mandatory Linux CI before owner merge. No merge or deployment is authorized +by these synthetic results; operator-supervised balance and real-client +qualification remain outstanding. diff --git a/src/sv_bot_manager.c b/src/sv_bot_manager.c index 2e2b0644..fde88bab 100644 --- a/src/sv_bot_manager.c +++ b/src/sv_bot_manager.c @@ -1,4 +1,5 @@ -/* Promod bot population and human admission. See docs/bots.md. AGPL-3.0-or-later. */ +/* Native bot population and human admission. See docs/bots.md and + * docs/zombies-allied-bots.md. AGPL-3.0-or-later. */ #include "server.h" #include "cmd.h" #include "cvar.h" @@ -6,8 +7,10 @@ #include "qcommon_io.h" #include "sv_bot_policy.h" #include "g_sv_shared.h" +#include "filesystem.h" static cvar_t *bot_enable, *bot_ai_ready, *bot_fill_limit, *bot_skill; +static cvar_t *btd_allies_enable, *btd_allies_limit; static bot_fill_state_t fill_state = BOT_FILL_ACTIVE; static int next_fill; @@ -20,11 +23,24 @@ static int BotCount(void) return count; } +static qboolean BotAlliedMode(void) +{ + return fs_gameDirVar && + !strcmp(fs_gameDirVar->string, "mods/btd_alpha_001") && + !strcmp(sv_g_gametype->string, "war"); +} + +static int BotLimitValue(void) +{ + return BotAlliedMode() ? btd_allies_limit->integer : bot_fill_limit->integer; +} + static qboolean BotCanAdd(void) { - return com_sv_running && com_sv_running->integer && bot_enable->boolean && + return com_sv_running && com_sv_running->integer && bot_ai_ready->boolean && sv.state == SS_GAME && !sv.restarting && - sv_pure->boolean && !strcmp(sv_g_gametype->string, "sd"); + sv_pure->boolean && ((BotAlliedMode() && btd_allies_enable->boolean) || + (bot_enable->boolean && !strcmp(sv_g_gametype->string, "sd"))); } static qboolean BotQueueWaiting(void) @@ -38,7 +54,7 @@ static qboolean BotQueueWaiting(void) static qboolean BotAddOne(void) { char name[32]; - Com_sprintf(name, sizeof(name), "[BOT] Promod %02d", BotCount() + 1); + Com_sprintf(name, sizeof(name), "[BOT] %s %02d", BotAlliedMode() ? "Ally" : "Promod", BotCount() + 1); return SV_AddBotClient(name) != NULL; } @@ -104,7 +120,7 @@ static void BotAdd(void) Com_Printf(CON_CHANNEL_SERVER, "Bots not ready, or a human connection is queued. No bots added.\n"); return; } - allowed = BotFill_Target(BotHumanCount(NULL), sv_maxclients->integer, bot_fill_limit->integer) - BotCount(); + allowed = BotFill_Target(BotHumanCount(NULL), sv_maxclients->integer, BotLimitValue()) - BotCount(); while (added < count && added < allowed && BotAddOne()) ++added; Com_Printf(CON_CHANNEL_SERVER, "Added %d bots.\n", added); } @@ -122,7 +138,7 @@ static void BotLimit(void) { int count; if (!BotCountArgument(&count)) return; - Cvar_SetInt(bot_fill_limit, count); + Cvar_SetInt(BotAlliedMode() ? btd_allies_limit : bot_fill_limit, count); /* Enforce zero/reductions even while Auto-Fill is paused. */ while (BotCount() > count && SV_RemoveBot()) {} } @@ -146,7 +162,7 @@ static void BotAutoFill(void) return; } if (!strcmp(Cmd_Argv(1), "1")) { - Cvar_SetBool(bot_enable, qtrue); + Cvar_SetBool(BotAlliedMode() ? btd_allies_enable : bot_enable, qtrue); fill_state = BOT_FILL_ACTIVE; } else { fill_state = BotFill_Pause(BotHumanCount(NULL)); @@ -169,8 +185,8 @@ static void BotStatus(void) else if (cl->state != CS_ACTIVE) ++pending; } Com_Printf(CON_CHANNEL_SERVER, "BOT_STATUS enabled=%d state=%s humans=%d connecting=%d bots=%d ready=%d pure=%d limit=%d difficulty=%s\n", - bot_enable->boolean, state, BotHumanCount(NULL), pending, bots, bot_ai_ready->boolean, sv_pure->integer, - bot_fill_limit->integer, bot_skill->integer == -1 ? "fixed" : bot_skill->integer == 0 ? "mixed" : va("%d", bot_skill->integer)); + BotAlliedMode() ? btd_allies_enable->boolean : bot_enable->boolean, state, BotHumanCount(NULL), pending, bots, bot_ai_ready->boolean, sv_pure->integer, + BotLimitValue(), BotAlliedMode() ? "allied-mixed" : bot_skill->integer == -1 ? "fixed" : bot_skill->integer == 0 ? "mixed" : va("%d", bot_skill->integer)); } void SV_BotManagerInit(void) @@ -179,6 +195,8 @@ void SV_BotManagerInit(void) bot_ai_ready = Cvar_RegisterBool("bot_ai_ready", qfalse, 0, "Set by the server AI script after loading map navigation"); bot_fill_limit = Cvar_RegisterInt("bot_fill_limit", 12, 0, 12, 0, "Maximum AI bots; humans also consume the 12-slot population"); bot_skill = Cvar_RegisterInt("bot_skill", -1, -1, 7, 0, "Bot skill: -1 original fixed profile, 0 mixed, 1..7 Bot Warfare tiers"); + btd_allies_enable = Cvar_RegisterBool("btd_allies_enable", qtrue, 0, "Enable the isolated BTD allied controller"); + btd_allies_limit = Cvar_RegisterInt("btd_allies_limit", 5, 0, 12, 0, "Maximum allied BTD bots"); Cvar_RegisterBool("bot_debug", qfalse, 0, "Write bot gameplay evidence to the game log"); Cmd_AddPCommand("bot_kickall", BotKickAll, 80); Cmd_AddPCommand("bot_killall", BotKillAll, 80); @@ -219,7 +237,7 @@ void SV_BotManagerFrame(void) int bots, target; if (!com_sv_running || !com_sv_running->integer || sv.state != SS_GAME || sv.restarting) return; bots = BotCount(); - target = BotFill_Target(BotHumanCount(NULL), sv_maxclients->integer, bot_fill_limit->integer); + target = BotFill_Target(BotHumanCount(NULL), sv_maxclients->integer, BotLimitValue()); if (bots > target) { SV_RemoveBot(); return; } if (!BotCanAdd() || fill_state != BOT_FILL_ACTIVE) return; if (next_fill > svs.time && next_fill - svs.time < 3000) return; diff --git a/tests/btd_allies.gsc b/tests/btd_allies.gsc new file mode 100644 index 00000000..13c19327 --- /dev/null +++ b/tests/btd_allies.gsc @@ -0,0 +1,234 @@ +// Disposable observer and synthetic human input driver; never packaged. +main() +{ + wait 5; + level.btd_allies_test_hits = 0; + level.btd_allies_test_melee = 0; + level.btd_allies_test_human_hits = 0; + level.btd_allies_test_human_damage = 0; + level.btd_allies_test_original_damage = level.callbackPlayerDamage; + level.callbackPlayerDamage = ::observe_player_damage; + level thread observer(); + level thread requests(); + level thread ended(); + setdvar("btd_allies_test_ready", "1"); +} + +observer() +{ + for (;;) + { + players = getentarray("player", "classname"); + for (i = 0; i < players.size; i++) + { + player = players[i]; + if (player.isbot && isdefined(player.btd_ally) && isalive(player)) + { + weapon = player getcurrentweapon(); + clip = player getweaponammoclip(weapon); + target = player btd_allies::target_zombie(); + if (isdefined(target)) + { + player.btd_allies_test_target = target getentitynumber(); + player.btd_allies_test_target_time = gettime(); + } + if (isdefined(player.btd_allies_test_last_weapon) && player.btd_allies_test_last_weapon == weapon && + clip < player.btd_allies_test_last_clip && isdefined(player.btd_allies_test_target_time) && + gettime() - player.btd_allies_test_target_time < 1000) + println("BTD_ALLIES_NATIVE_SHOT slot=" + player getentitynumber() + " weapon=" + weapon + + " before=" + player.btd_allies_test_last_clip + " after=" + clip + " target=" + player.btd_allies_test_target); + player.btd_allies_test_last_weapon = weapon; + player.btd_allies_test_last_clip = clip; + } + if (!player.isbot && !isdefined(player.btd_allies_test_human)) + { + player.btd_allies_test_human = true; + player thread synthetic_human(); + } + } + zombies = getentarray("zom", "targetname"); + for (i = 0; i < zombies.size; i++) + { + if (!isdefined(zombies[i].btd_allies_test_observed)) + { + zombies[i].btd_allies_test_observed = true; + zombies[i] thread observe_zombie_damage(); + } + } + wait 0.05; + } +} + +synthetic_human() +{ + self endon("disconnect"); + wait 0.5; + self maps\mp\gametypes\_globallogic::menuAllies(); + wait 0.5; + self maps\mp\gametypes\_globallogic::menuClass("specops_mp,0"); + for (;;) + { + if (!isalive(self) || self.sessionstate != "playing") { wait 0.1; continue; } + if (getdvar("btd_allies_test_mortal") != "1") + { + self.maxhealth = 100000; + self.health = 100000; + } + zombies = getentarray("zom", "targetname"); + nearest = undefined; + separation = 1000000; + for (i = 0; i < zombies.size; i++) + { + zombie = zombies[i]; + if (!isdefined(zombie.health) || zombie.health <= 0) continue; + range = distance(self.origin, zombie.origin); + if (range >= separation) continue; + trace = bullettrace(self.origin + (0,0,55), zombie.origin + (0,0,35), false, self); + if (trace["fraction"] < 1 && (!isdefined(trace["entity"]) || trace["entity"] != zombie)) continue; + nearest = zombie; + separation = range; + } + if (isdefined(nearest)) self setplayerangles(vectortoangles(nearest.origin + (0,0,35) - (self.origin + (0,0,55)))); + setdvar("btd_allies_test_fire_" + self getentitynumber(), isdefined(nearest)); + weapons = self getweaponslistprimaries(); + if (weapons.size) setdvar("btd_allies_test_reload_" + self getentitynumber(), self getweaponammoclip(weapons[0]) == 0); + wait 0.05; + } +} + +requests() +{ + for (;;) + { + request = getdvar("btd_allies_test_request"); + if (request != "") + { + setdvar("btd_allies_test_request", ""); + if (request == "all_humans_die") + { + players = getentarray("player", "classname"); + for (i = 0; i < players.size; i++) + if (!players[i].isbot && isalive(players[i])) players[i] suicide(); + } + if (request == "protection") protection(); + snapshot(request); + } + wait 0.05; + } +} + +protection() +{ + players = getentarray("player", "classname"); + human = undefined; + for (i = 0; i < players.size; i++) + if (!players[i].isbot && isalive(players[i])) human = players[i]; + if (!isdefined(human)) return; + zombies = getentarray("zom", "targetname"); + original = human.origin; + for (i = 0; i < players.size; i++) + { + ally = players[i]; + if (!ally.isbot || !isalive(ally) || !isdefined(ally.btd_ally)) continue; + for (j = 0; j < zombies.size; j++) + { + target = zombies[j]; + if (!isdefined(target.health) || target.health <= 0) continue; + // Use a real live target and require an unblocked positive control + // before placing the synthetic human into the native firing ray. + aim = target.origin + (0,0,32); + ally setplayerangles(vectortoangles(aim - ally geteye())); + baseline = ally btd_allies::safe_shot(aim, target); + if (!baseline) continue; + forward = anglestoforward(ally getplayerangles()); + human setorigin(ally.origin + forward * 60); + trace = bullettrace(ally geteye(), ally geteye() + forward * 1000, true, ally); + blocked = isdefined(trace["entity"]) && trace["entity"] == human; + guarded = ally btd_allies::safe_shot(aim, target); + guarded = !guarded; + human setorigin(original); + if (blocked && guarded) + { + println("BTD_ALLIES_PROTECTION baseline=1 blocked=1 guarded=1"); + return; + } + } + } + println("BTD_ALLIES_PROTECTION no_clear_live_trial=1"); +} + +ended() +{ + level waittill("game_ended"); + snapshot("eliminated"); + println("BTD_ALLIES_HUMAN_ELIMINATION ended=1"); +} + +snapshot(label) +{ + players = getentarray("player", "classname"); + allies = 0; alive = 0; humans = 0; human_alive = 0; kills = 0; human_kills = 0; + for (i = 0; i < players.size; i++) + { + player = players[i]; + if (!player.isbot) + { + humans++; + if (isalive(player) && player.sessionstate == "playing") human_alive++; + if (isdefined(player.kills)) human_kills += player.kills; + println("BTD_ALLIES_PLAYER label=" + label + " slot=" + player getentitynumber() + + " human=1 alive=" + isalive(player) + " state=" + player.sessionstate); + continue; + } + if (!isdefined(player.btd_ally) || !player.btd_ally) continue; + allies++; + if (isalive(player) && player.sessionstate == "playing") alive++; + if (isdefined(player.kills)) kills += player.kills; + weapon = player getcurrentweapon(); + target = player btd_allies::target_zombie(); + target_number = -1; + if (isdefined(target)) target_number = target getentitynumber(); + println("BTD_ALLIES_PLAYER label=" + label + " slot=" + player getentitynumber() + + " human=0 alive=" + isalive(player) + " state=" + player.sessionstate + " skill=" + player.btd_ally_skill + " origin=" + player.origin + + " weapon=" + weapon + " clip=" + player getweaponammoclip(weapon) + " target=" + target_number); + } + wave = 0; + if (isdefined(level.currentwave)) wave = level.currentwave; + canjoin = false; + if (isdefined(level.canjoin)) canjoin = level.canjoin == "yes"; + total = 0; + if (isdefined(level.totalzomsinwave)) total = level.totalzomsinwave; + println("BTD_ALLIES_SNAPSHOT label=" + label + " allies=" + allies + " alive=" + alive + + " humans=" + humans + " human_alive=" + human_alive + " kills=" + kills + " human_kills=" + human_kills + " wave=" + wave + + " canjoin=" + canjoin + " total=" + total + " hits=" + level.btd_allies_test_hits + " melee=" + level.btd_allies_test_melee + + " human_hits=" + level.btd_allies_test_human_hits + " human_damage=" + level.btd_allies_test_human_damage); +} + +observe_zombie_damage() +{ + self endon("death"); + for (;;) + { + self waittill("damage", amount, attacker, direction, point, means); + if (!isdefined(attacker) || !isplayer(attacker) || amount <= 0) continue; + if (means != "MOD_RIFLE_BULLET" && means != "MOD_PISTOL_BULLET") continue; + if (attacker.isbot && isdefined(attacker.btd_ally) && attacker.btd_ally) + { + level.btd_allies_test_hits++; + println("BTD_ALLIES_NATIVE_HIT slot=" + attacker getentitynumber() + " skill=" + attacker.btd_ally_skill + " amount=" + amount); + } + else if (!attacker.isbot) level.btd_allies_test_human_hits++; + } +} + +observe_player_damage(inflictor, attacker, amount, flags, means, weapon, point, direction, hitloc, offset) +{ + before = self.health; + self [[level.btd_allies_test_original_damage]](inflictor, attacker, amount, flags, means, weapon, point, direction, hitloc, offset); + if (!isdefined(self) || !isdefined(self.health)) return; + if (self.isbot && isdefined(self.btd_ally) && self.btd_ally && self.health < before && + isdefined(inflictor) && isdefined(inflictor.targetname) && inflictor.targetname == "zom" && means == "MOD_MELEE") + level.btd_allies_test_melee++; + if (!self.isbot && self.health < before && isdefined(attacker) && isplayer(attacker) && attacker.isbot) + level.btd_allies_test_human_damage++; +} diff --git a/tests/btd_allies_fixture.c b/tests/btd_allies_fixture.c new file mode 100644 index 00000000..dd310d06 --- /dev/null +++ b/tests/btd_allies_fixture.c @@ -0,0 +1,81 @@ +/* Disposable loopback test driver. Never package in a server runtime image. + * AGPL-3.0-or-later. Only activates clients that completed a real UDP admission. + */ +#include "../src/plugin_handler.h" +#include "../src/g_sv_shared.h" +#include "../src/q_math.h" +#include "../src/cvar.h" + +extern void Plugin_AddCommand(const char *, xcommand_t, int); + +static int driven[MAX_CLIENTS]; +static int firing[MAX_CLIENTS]; + +static void Fixture(void) +{ + int slot; + if (Cmd_Argc() != 3) return; + slot = atoi(Cmd_Argv(2)); + if (slot < 0 || slot >= sv_maxclients->integer) return; + client_t *cl = &svs.clients[slot]; + if (cl->state < CS_CONNECTED || cl->netchan.remoteAddress.type != NA_IP || + cl->netchan.remoteAddress.ip[0] != 127) return; + if (!strcmp(Cmd_Argv(1), "activate")) { + usercmd_t cmd = {0}; + cmd.serverTime = svs.time; + /* Headless fixture has no graphical client's checksum/profile exchange. + * This bypass is local to the explicitly activated test connection; + * sv_pure, server checksums and production authentication are unchanged. + */ + cl->pureAuthentic = 1; + SV_ClientEnterWorld(cl, &cmd); + driven[slot] = 1; + Com_Printf(CON_CHANNEL_SERVER, "BTD_ALLIES_HUMAN_ACTIVE slot=%d\n", slot); + } else if (!strcmp(Cmd_Argv(1), "fire")) firing[slot] = 1; + else if (!strcmp(Cmd_Argv(1), "stop")) firing[slot] = 0; +} + +void OnFrame(void) +{ + for (int slot = 0; slot < sv_maxclients->integer; ++slot) { + if (!driven[slot]) continue; + client_t *cl = &svs.clients[slot]; + if (cl->state != CS_ACTIVE || cl->netchan.remoteAddress.type != NA_IP || + cl->netchan.remoteAddress.ip[0] != 127) { + driven[slot] = firing[slot] = 0; + continue; + } + cl->lastPacketTime = svs.time; + cl->reliableAcknowledge = cl->reliableSequence; + if (!cl->gentity || !cl->gentity->client) continue; + playerState_t *ps = &cl->gentity->client->ps; + usercmd_t cmd = {0}; + cmd.serverTime = svs.time; + cmd.weapon = ps->weapon; + for (int axis = 0; axis < 3; ++axis) + cmd.angles[axis] = ANGLE2SHORT(ps->viewangles[axis] - ps->delta_angles[axis]); + if (firing[slot]) { + char name[64]; + Com_sprintf(name, sizeof(name), "btd_allies_test_reload_%d", slot); + if (Cvar_GetInt(name)) cmd.buttons = KEY_MASK_RELOAD; + else { + Com_sprintf(name, sizeof(name), "btd_allies_test_fire_%d", slot); + if (Cvar_GetInt(name)) cmd.buttons = KEY_MASK_FIRE; + } + } + SV_ClientThink(cl, &cmd); + } +} + +int OnInit(void) +{ + Plugin_AddCommand("btd_allies_fixture", Fixture, 100); + return 0; +} + +void OnInfoRequest(pluginInfo_t *info) +{ + info->handlerVersion.major = PLUGIN_HANDLER_VERSION_MAJOR; + info->handlerVersion.minor = PLUGIN_HANDLER_VERSION_MINOR; + Q_strncpyz(info->fullName, "Disposable allied bot qualification", sizeof(info->fullName)); +} diff --git a/tests/run_btd_allies.py b/tests/run_btd_allies.py new file mode 100644 index 00000000..3fc78d03 --- /dev/null +++ b/tests/run_btd_allies.py @@ -0,0 +1,310 @@ +#!/usr/bin/env python3 +"""Disposable native five-ally qualification. No simulated zombie damage or kills. + +Synthetic loopback humans receive normal weapons and native user commands. Only +their health is increased for sustained observation. This cannot certify balance +against competent graphical players or replace operator gameplay qualification. +""" +import argparse +import hashlib +import importlib.util +import json +from pathlib import Path +import re +import secrets +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() +p = argparse.ArgumentParser(description=__doc__) +for name in ('runtime', 'game', 'binary'): + p.add_argument('--' + name, required=True, type=Path) +p.add_argument('--observe-seconds', default=130, type=int) +a = p.parse_args() +assert (a.runtime / '.bot-test-runtime').is_file() +home = Path(tempfile.mkdtemp(prefix='btd-five-allies-')) +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' +spec = importlib.util.spec_from_file_location('allied_preparation', ROOT / 'tools/btd/prepare.py') +prepare = importlib.util.module_from_spec(spec) +spec.loader.exec_module(prepare) +lock = json.loads((ROOT / 'tools/btd/dependencies.json').read_text()) +ff = (mod / 'mod.ff').read_bytes() +assert hashlib.sha256(ff).hexdigest() == lock['files']['btd_alpha_001/mod.ff'] +for name, data in prepare.allied_overlays(ff, lock).items(): + target = mod / name + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) +global_script = mod / prepare.SCRIPT.replace('.gsc', '.gsx') +source = global_script.read_bytes() +assert source.count(b'init()\r\n{') == 1 +source = source.replace(b'init()\r\n{', b'init()\r\n{\r\n thread btd_allies_test::main();', 1) +# The non-graphical UDP clients have no profile upload. Supply the five vendor +# integrity sentinel stats only in the disposable fixture, preserving isbot=false. +sentinel = b'\tlevel notify( "connected", self );' +assert source.count(sentinel) == 1 +source = source.replace(sentinel, b'\tif (!self.isbot) for (fixture_stat = 0; fixture_stat < 5; fixture_stat++) self setstat(205 + fixture_stat * 10, 1);\r\n' + sentinel, 1) +global_script.write_bytes(source) +shutil.copy2(ROOT / 'tests/btd_allies.gsc', mod / 'btd_allies_test.gsc') +(home / 'plugins').mkdir() +subprocess.run(['gcc', '-m32', '-shared', '-fPIC', '-Wall', '-Wextra', '-Werror', + str(ROOT / 'tests/btd_allies_fixture.c'), '-o', str(home / 'plugins/btd_allies_fixture.so')], check=True) +baseline = {name: hashlib.sha256((mod / name).read_bytes()).hexdigest() + for name in ('canonical-shared.cfg', 'canonical-mode.cfg')} +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"\n') +password = secrets.token_hex(16) +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', 'rcon_password', password, + '+exec', 'canonical-shared.cfg', '+exec', 'canonical-mode.cfg', '+map', 'mp_killhouse'] +checks = {} +snapshots = {} +failure = None +logpath = home / 'console.log' + +def console(): + return re.sub(r'\^[0-9]', '', logpath.read_text(errors='replace')) + +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() + def rcon(value, credential=password): + with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as channel: + channel.settimeout(4) + channel.sendto(b'\xff' * 4 + f'rcon {credential} {value}'.encode(), ('127.0.0.1', port)) + return re.sub(r'\^[0-9]', '', channel.recv(65535).decode(errors='replace')) + def snapshot(label): + send('set btd_allies_test_request ' + label) + deadline = time.monotonic() + 3 + while time.monotonic() < deadline: + match = re.search(r'BTD_ALLIES_SNAPSHOT label=' + label + r' ([^\r\n]+)', console()) + if match: + result = {k: int(v) for k, v in re.findall(r'(\w+)=(\d+)', match[1])} + snapshots[label] = result + return result + time.sleep(.1) + raise AssertionError('Missing native snapshot ' + label + ': ' + str(home)) + def admit(number): + with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as channel: + channel.bind(('127.0.0.2', 0)) + channel.settimeout(4) + channel.sendto(b'\xff' * 4 + b'getchallenge 123456', ('127.0.0.1', port)) + challenge = channel.recv(2048)[4:].decode().split()[1] + name = 'AlliesHumanFixture' + str(number) + payload = f'connect "\\protocol\\21\\challenge\\{challenge}\\qport\\{24444 + number}\\name\\{name}\\rate\\25000\\snaps\\20"' + channel.sendto(b'\xff' * 4 + payload.encode(), ('127.0.0.1', port)) + assert b'connectResponse' in channel.recv(2048) + time.sleep(.2) + slot = int(re.findall(r'CS_CONNECTED for ' + name + r' num (\d+)', console())[-1]) + send('btd_allies_fixture activate ' + str(slot)) + return slot + try: + time.sleep(12) + send('loadplugin btd_allies_fixture') + time.sleep(1) + initial = snapshot('initial') + checks['five_default_alive'] = initial['allies'] == initial['alive'] == 5 + records = re.findall(r'BTD_ALLIES_PLAYER label=initial .*?skill=(easy|medium)', console()) + checks['three_easy_two_medium'] = records.count('easy') == 3 and records.count('medium') == 2 + checks['no_human_no_wave'] = initial['humans'] == initial['wave'] == 0 + checks['bad_rcon_denied'] = 'Bad rcon' in rcon('bot_killall', 'invalid-fixture') + checks['pure_enabled'] = bool(re.search(r'"sv_pure" is: "1"', rcon('sv_pure'))) + for invalid in ('-1', '13', '1x', '+1', '1 2'): + checks['add_validation_' + invalid] = 'Usage:' in rcon('bot_add ' + invalid) + checks['kick_validation_' + invalid] = 'Usage:' in rcon('bot_kick ' + invalid) + human = admit(1) + time.sleep(3) + joined = snapshot('joined') + checks['actual_human_spawned'] = joined['humans'] == 1 + early_kill = rcon('bot_killall') + checks['grace_killall_actual'] = 'Killed 5 bots' in early_kill + time.sleep(.2) + checks['grace_killall_dead'] = snapshot('grace_dead')['alive'] == 0 + time.sleep(5) + checks['grace_respawn'] = snapshot('grace_respawn')['alive'] == 5 + # Observe the five autonomous allies before enabling native human fire. + for second in range(35): + time.sleep(1) + if second >= 20: + send('set btd_allies_test_request protection') + snapshot('autonomous') + send('set btd_allies_test_request protection') + time.sleep(.3) + checks['human_shot_obstruction'] = 'BTD_ALLIES_PROTECTION baseline=1 blocked=1 guarded=1' in console() + send('btd_allies_fixture fire ' + str(human)) + deadline = time.monotonic() + a.observe_seconds + while time.monotonic() < deadline and proc.poll() is None: + time.sleep(1) + if re.search(r'script (?:runtime|compile) error', console()): break + send('set btd_allies_test_request progress' + str(int(deadline - time.monotonic()))) + if re.search(r'BTD_ALLIES_SNAPSHOT .* wave=[2-9]', console()): break + # Give the original five a second wave of naturally spawned enemies; + # weak reaction/accuracy means not every ally gets a hit in wave one. + send('btd_allies_fixture stop ' + str(human)) + time.sleep(12) + send('btd_allies_fixture fire ' + str(human)) + time.sleep(3) + combat = snapshot('combat') + checks['ally_native_bullet_hits'] = combat['hits'] > 0 + hitting_slots = set(re.findall(r'BTD_ALLIES_NATIVE_HIT slot=(\d+)', console())) + # Intentionally inaccurate allies need not all hit in a five-zombie + # wave. Require per-slot native hits OR actual ammunition expenditure + # with a live zombie target, rather than aggregate damage from one bot. + initial_clips = {slot: (weapon, int(clip)) for slot, weapon, clip in re.findall( + r'BTD_ALLIES_PLAYER label=initial slot=(\d+) .*?weapon=(\w+) clip=(\d+)', console())} + engaged = set(hitting_slots) | set(re.findall(r'BTD_ALLIES_NATIVE_SHOT slot=(\d+)', console())) + for slot, weapon, clip, target in re.findall( + r'BTD_ALLIES_PLAYER label=autonomous slot=(\d+) .*?weapon=(\w+) clip=(\d+) target=(-?\d+)', console()): + if slot in initial_clips and initial_clips[slot][0] == weapon and int(clip) < initial_clips[slot][1] and int(target) >= 0: + engaged.add(slot) + checks['five_allies_native_engagement'] = len(engaged) == 5 + checks['zombie_native_melee_ally'] = combat['melee'] > 0 + checks['human_no_ally_damage'] = combat['human_damage'] == 0 + checks['human_native_bullet_hits'] = combat['human_hits'] > 0 + checks['native_wave_progression'] = combat['wave'] >= 2 + checks['synthetic_human_kill_majority'] = combat['human_kills'] > combat['kills'] + before = rcon('bot_status') + killed_reply = rcon('bot_killall') + killed_match = re.search(r'Killed (\d+) bots', killed_reply) + # The earlier grace trial requires five real deaths. In live waves some + # allies can already be dead; zero then is the correct administration result. + checks['wave_killall_population'] = bool(killed_match and int(killed_match[1]) <= combat['alive']) + time.sleep(.3) + killed = snapshot('killed') + checks['killall_preserves_humans'] = killed['humans'] == combat['humans'] + checks['killall_observed_deaths'] = killed['alive'] == 0 + time.sleep(15) + respawn = snapshot('respawn') + for attempt in range(8): + if not respawn['canjoin'] or respawn['alive'] == respawn['allies']: break + time.sleep(1) + respawn = snapshot('grace_recovery_' + str(attempt)) + checks['bot_respawn_respects_wave'] = (respawn['alive'] == respawn['allies'] if respawn['canjoin'] else respawn['alive'] == 0) + checks['kickall_command'] = 'Bots removed' in rcon('bot_kickall') + time.sleep(4) + empty = snapshot('empty') + checks['kickall_no_immediate_refill'] = empty['allies'] == 0 + checks['empty_killall_safe'] = 'Killed 0 bots' in rcon('bot_killall') + checks['explicit_add'] = 'Added 5 bots' in rcon('bot_add 5') + time.sleep(6) + checks['explicit_five'] = snapshot('readded')['allies'] == 5 + checks['kick_count'] = 'Removed 2 bots' in rcon('bot_kick 2') + time.sleep(1) + checks['kick_count_population'] = snapshot('kicked')['allies'] == 3 + # Reconnect and capacity exercise actual UDP admission, not script clients. + replacement = admit(2) + time.sleep(2) + admitted_replacement = snapshot('replacement_waiting') + for attempt in range(90): + if admitted_replacement['human_alive'] == 2: break + time.sleep(1) + admitted_replacement = snapshot('replacement_spawn_' + str(attempt)) + checks['replacement_respects_join_window'] = admitted_replacement['human_alive'] == 2 + rcon('clientkick ' + str(human)) + human = replacement + time.sleep(3) + checks['reconnect'] = snapshot('reconnect')['humans'] == 1 + rcon('bot_kickall') + rcon('bot_limit 12') + rcon('bot_add 12') + time.sleep(6) + capacity = snapshot('capacity') + checks['capacity_respected'] = capacity['allies'] + capacity['humans'] == 12 + human2 = admit(3) + time.sleep(2) + admitted = snapshot('reclaimed') + checks['human_admission_at_capacity'] = admitted['humans'] == 2 and admitted['allies'] == capacity['allies'] - 1 + send('btd_allies_fixture fire ' + str(human)) + # Require a real active wave with living allies and humans. Killing in + # grace races the vendor's legitimate human respawn before its queued end. + ready = admitted + for attempt in range(90): + if ready['alive'] > 0 and ready['human_alive'] > 0 and not ready['canjoin']: break + time.sleep(1) + ready = snapshot('elimination_ready_' + str(attempt)) + checks['living_allies_before_human_death'] = ready['alive'] > 0 and not ready['canjoin'] + boundary = len(console()) + send('set btd_allies_test_request all_humans_die') + time.sleep(4) + eliminated = re.search(r'BTD_ALLIES_SNAPSHOT label=eliminated ([^\r\n]+)', console()[boundary:]) + ended_state = {k: int(v) for k, v in re.findall(r'(\w+)=(\d+)', eliminated[1])} if eliminated else {} + checks['all_humans_dead_ends_survival'] = (ready['alive'] > 0 and ended_state.get('alive', 0) > 0 and ended_state.get('human_alive') == 0) + rcon('bot_limit 5') + rcon('bot_autofill 1') + for mapname in ('mp_crash', 'mp_killhouse'): + send('map ' + mapname) + time.sleep(12) + state = snapshot('transition_' + mapname) + checks['transition_' + mapname] = state['allies'] == 5 + except (AssertionError, OSError) as exc: + failure = str(exc) + checks['runner_completed'] = False + finally: + if proc.poll() is None: + try: send('quit') + except BrokenPipeError: pass + try: checks['shutdown_zero'] = proc.wait(timeout=10) == 0 + except subprocess.TimeoutExpired: + proc.kill(); proc.wait(); checks['shutdown_zero'] = False + +text = console() +if failure is None: + logpath = home / 'console-restart.log' + with logpath.open('w') as output: + proc = subprocess.Popen(command, cwd=home, stdin=subprocess.PIPE, stdout=output, stderr=subprocess.STDOUT) + try: + time.sleep(12) + restarted = snapshot('restart') + checks['restart_five_alive'] = restarted['allies'] == restarted['alive'] == 5 + send('loadplugin btd_allies_fixture') + time.sleep(.5) + send('set btd_wave_settings 1') + dynamic_human = admit(10) + dynamic = restarted + for attempt in range(45): + time.sleep(1) + dynamic = snapshot('dynamic_' + str(attempt)) + if dynamic['wave'] == 1: break + checks['dynamic_wave_human_only_scaling'] = (dynamic['humans'] == 1 and dynamic['allies'] == 5 and + dynamic['wave'] == 1 and dynamic['total'] == 28) + except (AssertionError, OSError) as exc: + failure = str(exc) + checks['restart_five_alive'] = False + finally: + if proc.poll() is None: + try: send('quit') + except BrokenPipeError: pass + try: checks['restart_shutdown_zero'] = proc.wait(timeout=10) == 0 + except subprocess.TimeoutExpired: + proc.kill(); proc.wait(); checks['restart_shutdown_zero'] = False + text += '\n' + console() +checks['no_script_errors'] = not re.search(r'script (?:compile|runtime) error|Sys_Error:|Segmentation fault', text, re.I) +checks['eight_headers'] = 'Loaded 8 administrative IWD checksums' in text +result = {'evidence': str(home), 'checks': checks, 'snapshots': snapshots, + 'failure': failure, + 'operator_gameplay_qualified': False, 'balance_qualified': False, + 'binary_sha256': hashlib.sha256((home / 'cod4x18_dedrun').read_bytes()).hexdigest(), + 'fixture_sha256': hashlib.sha256((mod / 'btd_allies_test.gsc').read_bytes()).hexdigest(), + 'runner_sha256': RUNNER_SHA256, + 'plugin_sha256': hashlib.sha256((home / 'plugins/btd_allies_fixture.so').read_bytes()).hexdigest(), + 'baseline_config_sha256': baseline} +(home / 'results.json').write_text(json.dumps(result, indent=2) + '\n') +print(json.dumps(result, indent=2)) +assert all(checks.values()), 'Native allied qualification failed: ' + str(home) diff --git a/tests/test_btd_allies.py b/tests/test_btd_allies.py new file mode 100644 index 00000000..4e6060b7 --- /dev/null +++ b/tests/test_btd_allies.py @@ -0,0 +1,108 @@ +"""Public adapter policy and fail-closed private-overlay regression tests.""" +import hashlib +import importlib.util +import json +from pathlib import Path +import struct +import unittest +import zlib + +ROOT = Path(__file__).resolve().parents[1] +spec = importlib.util.spec_from_file_location('allied_prepare', ROOT / 'tools/btd/prepare.py') +btd = importlib.util.module_from_spec(spec) +spec.loader.exec_module(btd) + + +def fastfile(sources): + payload = b'' + for name, source in sources.items(): + raw = source.encode() + payload += b'\0' * 4 + struct.pack(' +#include +typedef int qboolean; +#define SS_GAME 2 +typedef struct {int boolean,integer;const char *string;} cvar_t; +cvar_t enabled={1},ready={1},running={1,1},pure={1},btd={1}, + fill={0,12},allied_fill={0,5},game={0,0,"war"},dir={0,0,"mods/btd_alpha_001"}; +cvar_t *bot_enable=&enabled,*bot_ai_ready=&ready,*com_sv_running=&running, + *sv_pure=&pure,*btd_allies_enable=&btd,*bot_fill_limit=&fill, + *btd_allies_limit=&allied_fill,*sv_g_gametype=&game,*fs_gameDirVar=&dir; +struct {int state,restarting;} sv={SS_GAME,0}; +''' + for signature in ('static qboolean BotAlliedMode(', 'static int BotLimitValue(', + 'static qboolean BotCanAdd('): + fixture += body('src/sv_bot_manager.c', signature) + '\n' + fixture += r''' +int main(void) { + assert(BotAlliedMode() && BotCanAdd() && BotLimitValue()==5); + enabled.boolean=0; assert(BotCanAdd()); + btd.boolean=0; assert(BotAlliedMode() && !BotCanAdd() && BotLimitValue()==5); + btd.boolean=1;ready.boolean=0;assert(!BotCanAdd());ready.boolean=1; + pure.boolean=0;assert(!BotCanAdd());pure.boolean=1; + sv.restarting=1;assert(!BotCanAdd());sv.restarting=0; + game.string="sd";dir.string="mods/pml220"; + assert(!BotAlliedMode() && !BotCanAdd() && BotLimitValue()==12); + enabled.boolean=1;assert(BotCanAdd()); + game.string="war";assert(!BotCanAdd()); + dir.string="mods/other";assert(!BotCanAdd()); + return 0; +} +''' + with tempfile.TemporaryDirectory() as directory: + source = Path(directory) / 'manager.c' + binary = Path(directory) / 'manager' + source.write_text(fixture) + subprocess.run(['cc', str(source), '-o', str(binary)], check=True) + subprocess.run([str(binary)], check=True) + + def test_contract_permissions(self): + source = (ROOT / 'src/sv_bot_manager.c').read_text() + for command, handler, power in [('bot_add','BotAdd',80),('bot_kick','BotKick',80), + ('bot_kickall','BotKickAll',80),('bot_killall','BotKillAll',80),('bot_status','BotStatus',20)]: + self.assertIn(f'Cmd_AddPCommand("{command}", {handler}, {power});', source) diff --git a/tests/test_btd_prepare.py b/tests/test_btd_prepare.py index 62a685ae..a2a7ca6a 100644 --- a/tests/test_btd_prepare.py +++ b/tests/test_btd_prepare.py @@ -60,6 +60,37 @@ def setUp(self): def prepare(self): return btd.prepare(self.source, self.headers, self.binary, self.output) + def test_optional_allied_manifest_and_overlay_hashes(self): + sources = { + btd.SCRIPT: ('init()\r\n{}\r\nCallback_PlayerConnect()\r\n{}\r\nspawnPlayer()\r\n{}\r\n' + + btd.DEATH_CONDITION + '\r\n' + btd.PLAYER_DAMAGE_GUARD + '\r\nupdateTeamStatus()\r\n{players = level.players;}\r\nisValidClass(x){}').encode(), + btd.SPAWN_SCRIPT: self.spawn_raw, + btd.NAVIGATION_SCRIPT: self.navigation_raw, + btd.ALLIED_SURVIVAL_SCRIPT: b'getentarray("player","classname");' * 4, + btd.ALLIED_AMMO_SCRIPT: btd.AMMO_PICKUP_GUARD.encode() + b'\r\nammoingwait()\r\n{}\r\nhashadammo()\r\n{}', + btd.ALLIED_ZOMBIE_SCRIPT: b'monitorplayers()\r\n{getentarray("player","classname");}\r\nmonitorme(){}', + } + payload = b'fixture!' + for name, raw in sources.items(): + payload += struct.pack('