10 Commits

Author SHA1 Message Date
SirStone 4a1f3e1c88 j159: live 2-arm A/B result — geometry draw weighting costs 8.8 damage/run, wins null; keep TR_TFIL_GEO_MODE=off 2026-09-27 12:44:38 +02:00
SirStone 7c5bc9ccbd j159: PRE-REGISTER the tfil geo A/B (geo draw weighting vs uniform) before any battle 2026-09-27 12:16:36 +02:00
SirStone 2223ca667e j154 (default-off): the DERIVED bounded hold TR_TFIL_HOLD_MAX_TICKS + panic release
Budget derived from the server source (tank-royale 0.35.5): calcGunHeat(p) =
1 + p/5, coolDown 0.1/tick, fire only at heat == 0, calcBulletDamage(3.0) = 16
-> two max-power shots are 16 ticks apart and 32 damage is the most the enemy
can land in that window (brute force over the 0.1 power grid: 8/11/16/24/32
ticks -> 16/18/32/32/48). 16 = CommitTicks + 1, the first window that admits
the enemy's second shot.

Knob defaults to 0 = today's behaviour byte-for-byte (checked over 20026
ticks). Hold is taken only on a replan tick with an empty safe set, at most N
ticks per streak, released the tick a safe tile exists, counter reset on the
pick. PANIC RELEASE: a tracked bullet whose closest approach is within its core
at t* in [0, min(N,16)] overrides the hold immediately. The gun is untouched.

Also fixes a stray '&' that stopped test_tfil_commit_env.nim from compiling at
all, and enforces the 'a hold never interrupts a live commitment' invariant
j153 documented but did not implement. Registers TR_TFIL_HOLD_MAX_TICKS in
env_report + knownEnvNames + .env.example.

No battle, no A/B run.
2026-09-27 10:23:46 +02:00
SirStone 38fbc6ecd1 j152 (default-off): geometry shapes the tile DRAW (TR_TFIL_GEO_MODE/TAU) + the offline sweep with the diversity cost
The owner: choose the tile pool not only from the heat point but from the
geometric position too. Heat stays the hard filter; the draw over the
survivors is re-weighted by turn and/or distance. Three weighting forms
(soft softmax / top-K third / rejection band), one env name carrying both
axes. Default = off = today's uniform draw, byte-for-byte (golden parity).

WHAT DIFFERS FROM j9 (TR_TFIL_TURN_BIAS, a live null): that was a tiebreak
weight among the non-empty safe set only. This runs on the WHOLE pool the
draw already runs on, including the 2 promoted least-hot tiles the ~65%
forced picks choose from.

OFFLINE (8 fixtures x 3 seeds, no java): headline 'tile actually reached at
tta' 4.5% -> 16.9% at TR_TFIL_GEO_MODE=both-soft TR_TFIL_GEO_TAU=45, with
no diversity collapse (distinct tiles 220 -> 219, normalised entropy
0.87 -> 0.86, top-tile share 7.0% -> 8.6%). perpE — the perpendicular rate
in the FORCED population — does not move in ANY arm: that pool is 2 tiles
ranked by heat alone and the only lever is a coin flip.

Also registers j150's TR_TFIL_DIAG / TR_TFIL_DANGER_THRESHOLD in
env_report + knownEnvNames + .env.example (test_env_report was red) and
documents DANGER_THRESHOLD as quantisation-limited: heat comes in 5s, so
the effective steps are 10/15/20 and 10-14 admits zero extra tiles.

No battle, no server, no A/B run.
2026-09-27 10:22:24 +02:00
SirStone 94ffc63160 j153: the open-loop ruler for "hold when trapped" + the A/B proposal (NOT run)
Measures, on the recorded fixtures and with NO counterfactual replay: how long
until a safe tile appears at a forced pick, whether the enemy had just fired,
whether our own tile is already hot, and all three split by distance. Registers
nothing and changes no default: the knob TR_TFIL_HOLD_WHEN_TRAPPED and its
implementation live in the concurrently edited working tree.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-09-27 10:16:53 +02:00
SirStone a01141c959 j151 (default-off): hard arrival bound TR_TFIL_ARRIVE_TICKS + the offline per-pick ruler that found it
Measures the owner's two complaints per pick (turn angle, heat on the path
vs at the destination, time-to-arrive, and whether the destination is hot on
the recorded true future when we would arrive), split by empty vs non-empty
safe set. Result: the path IS scored (hard filter + least-hot fallback), but
there was NO time term at all -- 65% of picks outran the 15-tick commitment
and the chosen tile was reached 6.5% of the time. The bound refuses a
candidate we cannot reach in TR_TFIL_ARRIVE_TICKS (default 0 = off = today).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-09-27 09:57:25 +02:00
SirStone 0b74b01c4b j150 (diag only): picker loss histogram + sweepable heat cutoff
Measures WHERE the lava picker loses tiles, per pick:
reachable hull -> CoolestLevels=2 distinct-value filter -> path heat
filter -> draw set -> chosen. TR_TFIL_DIAG (default off) fills
TfilLoss*; TR_TFIL_DANGER_THRESHOLD (default 10.0, the shipped const)
makes the cutoff sweepable offline. No decision logic changed: the guard
test proves the diag-on move stream is byte-for-byte the diag-off one.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-09-27 09:51:19 +02:00
SirStone 5e213df8d9 j148: bound the corridor by speed x ticks (TR_{TFIL,STRAFE}_CORRIDOR_TICKS, default 0 = to the wall); UNTESTED 2026-09-27 08:23:16 +02:00
SirStone 32ec040e90 j147 results: 180-battle live A/B on the frozen 15-opponent panel
Within-mover references (the only comparison that isolates the knob): tfil_lag1
-0.04 wins/run, strafe_lag1 +0.18 wins/run, both far under the reported MDEs
(0.33 / 0.41) -> NOT distinguishable, so TR_FIRE_LAG stays default 0. Incoming
hit rate also unmoved (+0.94 / +0.33 pp). The one significant result is the
mover (strafe_lag1 vs tfil_off +0.38 wins/run p=0.0386, hit rate -4.67pp
p=0.0074), which is the known strafe-over-tfil gap and exactly why the
within-mover reference was pre-registered.

Also a cosmetic no-op refactor of the two spawn sites (compute velX/velY once;
bit-identical, and it keeps the default-parity claim exact).
2026-09-26 23:20:36 +02:00
SirStone d21f7ce5f5 j147: the 1-tick fire-detection lag is OURS — measure it, then back-date it (TR_FIRE_LAG)
MEASURED LIVE (common_libs/tests/measure_fire_ghost_lag.py, 4 sessions, 1777
matched ghost spawns, both movers): the server dispatches a turn's fire AFTER
our go() for that same turn, so a turn-T shot's energy drop first reaches our
scan at turn T+1 — and a bullet takes its FIRST step during the turn it is
fired, so the true bullet is already one whole bullet step (11-20 px) downrange.
Both movers place the ghost at the SCANNED enemy position (where the bullet was
born), so the whole ghost trajectory is the true one shifted one turn later and
the arrival deadline is a full tick late.

MEASURED: detection lag +1 tick on 100% of 1777 matched spawns; ghost-vs-
observer displacement 19.06 px mean / 22.00 p90 (tfil) and 16.08 / 21.81
(strafe); arrival-deadline error 0.99 / 0.77 ticks. NOT a rendering artefact:
the draw/advance order is correct (advanceBullets -> detectFires -> build).

THE FIX: TR_FIRE_LAG (int, default 0 = today byte-for-byte) in the shared
fire_tracker, applied by both movers at spawn: x = origin + dir*speed*lag.
The deadline needs no separate change — both movers derive it from the ghost's
own position, so a correct position gives a correct deadline.
WITH IT: displacement 19.06 -> 5.37 px mean (the residue is the enemy's own
<=8 px scan staleness) and the deadline error 0.99 -> 0.06 ticks.

Guards: test_tfil_commit_env 77 -> 87 checks (default golden parity, exact
n-step back-date, deadline shortens by exactly lag, junk/negative degrade to 0,
reaped exactly one tick earlier); test_env_report + test_env_dotenv green.
TR_FIRE_LAG registered in env_report + knownEnvNames + .env.example +
docs/env_reference.md. Live A/B pre-registered in docs/movement_campaign.md
(Batch 8) with its MDE stated up front; arms tools/ab/arms_fire_lag.txt.
TR_FIRE_DIAG gains a per-round ROUND line (the tick->getTurn anchor) and a
per-spawn SPAWN line (the ghost's drawn position).
2026-09-26 23:08:57 +02:00
17 changed files with 2631 additions and 13 deletions
+10
View File
@@ -105,12 +105,20 @@ TR_TFIL_RANGE_HI=200.0 # px; upper edge of that band
TR_TFIL_RANGE_TEMP=0.4 # sharpness of the ring mover's weighted random draw TR_TFIL_RANGE_TEMP=0.4 # sharpness of the ring mover's weighted random draw
TR_TFIL_RANGE_K=60.0 # px; how fast the weight falls off outside the band TR_TFIL_RANGE_K=60.0 # px; how fast the weight falls off outside the band
TR_TFIL_CORRIDOR_HEAT=10.0 # lava painted per corridor-overlapping tile TR_TFIL_CORRIDOR_HEAT=10.0 # lava painted per corridor-overlapping tile
TR_TFIL_CORRIDOR_TICKS=0.0 # corridor length in ticks: 0 = to the wall (shipped); N>0 = min(to wall, bullet speed * N)
TR_TFIL_WALL_HOTNESS=15.0 # peak heat painted on tiles next to a wall TR_TFIL_WALL_HOTNESS=15.0 # peak heat painted on tiles next to a wall
TR_TFIL_WALL_RADIANCE=10.0 # how fast wall heat falls off with distance TR_TFIL_WALL_RADIANCE=10.0 # how fast wall heat falls off with distance
TR_TFIL_BULLET_CORE=10.0 # tfil only: lava per bullet-overlapping tile (== PathDangerThreshold, so a bullet is never hot on its own) TR_TFIL_BULLET_CORE=10.0 # tfil only: lava per bullet-overlapping tile (== PathDangerThreshold, so a bullet is never hot on its own)
TR_TFIL_BULLET_AURA=5.0 # tfil only: lava for the bullet's aura ring tiles TR_TFIL_BULLET_AURA=5.0 # tfil only: lava for the bullet's aura ring tiles
TR_TFIL_TILE_REPLAN=self # self | enemy | off: when a dodge commitment is cancelled TR_TFIL_TILE_REPLAN=self # self | enemy | off: when a dodge commitment is cancelled
TR_TFIL_COMMIT_TICKS=15 # ticks to commit to a dodge point before replanning TR_TFIL_COMMIT_TICKS=15 # ticks to commit to a dodge point before replanning
TR_TFIL_ARRIVE_TICKS=0.0 # hard bound: never pick a tile farther than this (ticks at 8px/tick); 0 = off = today's draw
TR_TFIL_HOLD_WHEN_TRAPPED=off # on = when NO safe tile exists, hold position one tick instead of taking the 2 least-hot blocked tiles; off = today's fallback
TR_TFIL_HOLD_MAX_TICKS=0 # BOUNDED version of the above: hold at most N ticks per empty-safe-set streak (default 0 = off = today's fallback). The budget is DERIVED from the enemy's rate of fire (2 x 3.0-power shots = 16 ticks); the hold is released the tick a safe tile exists and overridden outright if a tracked bullet reaches us within min(N, 16) ticks
TR_TFIL_DANGER_THRESHOLD=10.0 # hard heat filter on the path; lava is quantised to 5, so the effective steps are 10/15/20 and 10-14 admits exactly what 10 does
TR_TFIL_DIAG=off # on = fill the per-pick picker loss histogram (TfilLoss*); observability only
TR_TFIL_GEO_MODE=off # off | turn | dist | both, each with a `-soft` (default) / `-topk` / `-rej` suffix; shapes the DRAW over the heat-filtered pool
TR_TFIL_GEO_TAU=0.0 # deg; the geometric cost scale. 0 = off = today's uniform draw
TR_TFIL_NO_REV=off # on = never reverse direction inside a corridor TR_TFIL_NO_REV=off # on = never reverse direction inside a corridor
TR_TFIL_COMMIT_LOG= # path for the per-commit log; empty = no log TR_TFIL_COMMIT_LOG= # path for the per-commit log; empty = no log
TR_TFIL_COMMIT_ARRIVAL=off # on = hold the dodge tile until we are ON it (not a fixed dwell) TR_TFIL_COMMIT_ARRIVAL=off # on = hold the dodge tile until we are ON it (not a fixed dwell)
@@ -142,10 +150,12 @@ TR_STRAFE_ESCAPE=on # the guaranteed wall escape when every candidate is hot
TR_STRAFE_FIRE_FIX=on # strafe's share of the shared TR_FIRE_FIX switch TR_STRAFE_FIRE_FIX=on # strafe's share of the shared TR_FIRE_FIX switch
TR_FIRE_FIX=on # 0 = the shipped previous-energy bullet detector TR_FIRE_FIX=on # 0 = the shipped previous-energy bullet detector
#TR_FIRE_DIAG=1 # presence-only: per-reading tick/raw/correction trace #TR_FIRE_DIAG=1 # presence-only: per-reading tick/raw/correction trace
#TR_FIRE_LAG=0 # ticks to back-date each detected fire at spawn (0=shipped; 1=the measured live detection lag)
TR_STRAFE_HEAT_GRID=on # draw the whole heat grid; 0 leaves only the chosen tile TR_STRAFE_HEAT_GRID=on # draw the whole heat grid; 0 leaves only the chosen tile
TR_STRAFE_BULLET_CORE=20.0 # strafe's own retune: lava per bullet-overlapping tile TR_STRAFE_BULLET_CORE=20.0 # strafe's own retune: lava per bullet-overlapping tile
TR_STRAFE_BULLET_AURA=10.0 # strafe's own retune: lava for the bullet aura ring TR_STRAFE_BULLET_AURA=10.0 # strafe's own retune: lava for the bullet aura ring
TR_STRAFE_CORRIDOR_HEAT=10.0 # strafe's own retune: lava per corridor tile TR_STRAFE_CORRIDOR_HEAT=10.0 # strafe's own retune: lava per corridor tile
TR_STRAFE_CORRIDOR_TICKS=0.0 # same length bound for strafe: 0 = to the wall (shipped)
TR_STRAFE_WALL_HOTNESS=15.0 # strafe's own retune: peak wall heat TR_STRAFE_WALL_HOTNESS=15.0 # strafe's own retune: peak wall heat
TR_STRAFE_WALL_RADIANCE=5.0 # strafe's own retune: wall heat falloff TR_STRAFE_WALL_RADIANCE=5.0 # strafe's own retune: wall heat falloff
+5
View File
@@ -878,6 +878,11 @@ method onRoundEnded*(bot: ModularBot, e: RoundEndedEventForBot) =
method onRoundStarted*(bot: ModularBot, e: RoundStartedEvent) = method onRoundStarted*(bot: ModularBot, e: RoundStartedEvent) =
bot.roundNumber = e.roundNumber bot.roundNumber = e.roundNumber
if FireDiag:
# j147 timeline anchor: the (bot.tick -> server getTurn) offset, once per
# round, so a recorded capture's event sidecar can be aligned to the bot's
# own tick stream without guessing.
echo "[firediag] ROUND round=", getRound(), " getTurn=", getTurn()
# Per-round outcome-log state (TR_RESULT_LOG). Reset every round so round 1 # Per-round outcome-log state (TR_RESULT_LOG). Reset every round so round 1
# reports and a target/enemy change mid-round cannot leak a stale flag. # reports and a target/enemy change mid-round cannot leak a stale flag.
bot.weDiedThisRound = false bot.weDiedThisRound = false
+27
View File
@@ -25,6 +25,7 @@ import module_switches
import gun_harness/virtual_bullets import gun_harness/virtual_bullets
import gun_harness/selector import gun_harness/selector
import movements/ram_decision import movements/ram_decision
import movement_harness/fire_tracker
import movements/the_floor_is_lava import movements/the_floor_is_lava
import movements/the_floor_is_lava_ring import movements/the_floor_is_lava_ring
import movements/strafe import movements/strafe
@@ -310,6 +311,14 @@ proc printEffectiveValues(ctx: EnvReportContext) =
emit("TR_TFIL_RANGE_K", $RangeK, sourceOf("TR_TFIL_RANGE_K")) emit("TR_TFIL_RANGE_K", $RangeK, sourceOf("TR_TFIL_RANGE_K"))
emit("TR_TFIL_CORRIDOR_HEAT", $the_floor_is_lava_ring.CorridorHeat, emit("TR_TFIL_CORRIDOR_HEAT", $the_floor_is_lava_ring.CorridorHeat,
sourceOf("TR_TFIL_CORRIDOR_HEAT")) sourceOf("TR_TFIL_CORRIDOR_HEAT"))
emit("TR_TFIL_CORRIDOR_TICKS", $the_floor_is_lava.TfilCorridorTicks,
sourceOf("TR_TFIL_CORRIDOR_TICKS"))
emit("TR_TFIL_ARRIVE_TICKS", $the_floor_is_lava.TfilArriveTicks,
sourceOf("TR_TFIL_ARRIVE_TICKS"))
emit("TR_TFIL_HOLD_WHEN_TRAPPED", onOff(the_floor_is_lava.TfilHoldWhenTrapped),
sourceOfPresence("TR_TFIL_HOLD_WHEN_TRAPPED"))
emit("TR_TFIL_HOLD_MAX_TICKS", $the_floor_is_lava.TfilHoldMaxTicks,
sourceOf("TR_TFIL_HOLD_MAX_TICKS"))
emit("TR_TFIL_WALL_HOTNESS", $the_floor_is_lava_ring.WallHotness, emit("TR_TFIL_WALL_HOTNESS", $the_floor_is_lava_ring.WallHotness,
sourceOf("TR_TFIL_WALL_HOTNESS")) sourceOf("TR_TFIL_WALL_HOTNESS"))
emit("TR_TFIL_WALL_RADIANCE", $the_floor_is_lava.WallRadiance, emit("TR_TFIL_WALL_RADIANCE", $the_floor_is_lava.WallRadiance,
@@ -328,6 +337,14 @@ proc printEffectiveValues(ctx: EnvReportContext) =
emit("TR_TFIL_COMMIT_MARGIN", $TfilCommitMargin, emit("TR_TFIL_COMMIT_MARGIN", $TfilCommitMargin,
sourceOf("TR_TFIL_COMMIT_MARGIN")) sourceOf("TR_TFIL_COMMIT_MARGIN"))
emit("TR_TFIL_NOREV_SPEED", $TfilNoRevSpeed, sourceOf("TR_TFIL_NOREV_SPEED")) emit("TR_TFIL_NOREV_SPEED", $TfilNoRevSpeed, sourceOf("TR_TFIL_NOREV_SPEED"))
emit("TR_TFIL_DANGER_THRESHOLD", $the_floor_is_lava.TfilDangerThreshold,
sourceOf("TR_TFIL_DANGER_THRESHOLD"))
emit("TR_TFIL_DIAG", onOff(the_floor_is_lava.TfilDiag),
sourceOfPresence("TR_TFIL_DIAG"))
emit("TR_TFIL_GEO_MODE", $the_floor_is_lava.TfilGeoMode,
sourceOf("TR_TFIL_GEO_MODE"))
emit("TR_TFIL_GEO_TAU", $the_floor_is_lava.TfilGeoTau,
sourceOf("TR_TFIL_GEO_TAU"))
emit("TR_TFIL_TURN_BIAS", $TfilTurnBias, sourceOf("TR_TFIL_TURN_BIAS")) emit("TR_TFIL_TURN_BIAS", $TfilTurnBias, sourceOf("TR_TFIL_TURN_BIAS"))
emit("TR_TFIL_TURN_REF_DEG", $TfilTurnRefDeg, sourceOf("TR_TFIL_TURN_REF_DEG")) emit("TR_TFIL_TURN_REF_DEG", $TfilTurnRefDeg, sourceOf("TR_TFIL_TURN_REF_DEG"))
# time-indexed bullet heat (default off = shipped flat model) # time-indexed bullet heat (default off = shipped flat model)
@@ -362,6 +379,9 @@ proc printEffectiveValues(ctx: EnvReportContext) =
emit("TR_FIRE_FIX", onOff(TfilFireFix), sourceOf("TR_FIRE_FIX")) emit("TR_FIRE_FIX", onOff(TfilFireFix), sourceOf("TR_FIRE_FIX"))
# j134 TASK B diagnostic (off by default): per-reading tick/raw/correction trace. # j134 TASK B diagnostic (off by default): per-reading tick/raw/correction trace.
emit("TR_FIRE_DIAG", onOff(StrafeFireDiag), sourceOf("TR_FIRE_DIAG")) emit("TR_FIRE_DIAG", onOff(StrafeFireDiag), sourceOf("TR_FIRE_DIAG"))
# j147: the back-date (ticks) applied to every detected enemy fire at spawn.
# 0 = shipped (the ghost is born at the scanned enemy position).
emit("TR_FIRE_LAG", $FireLag, sourceOf("TR_FIRE_LAG"))
emit("TR_STRAFE_HEAT_GRID", onOff(StrafeHeatGrid), sourceOf("TR_STRAFE_HEAT_GRID")) emit("TR_STRAFE_HEAT_GRID", onOff(StrafeHeatGrid), sourceOf("TR_STRAFE_HEAT_GRID"))
# STRAFE's heat shape is its own RETUNE (bullet 20/10, corridor 10, wall # STRAFE's heat shape is its own RETUNE (bullet 20/10, corridor 10, wall
# 15/5), override-able per run so the shipped field can be A/B'd on one # 15/5), override-able per run so the shipped field can be A/B'd on one
@@ -369,6 +389,7 @@ proc printEffectiveValues(ctx: EnvReportContext) =
emit("TR_STRAFE_BULLET_CORE", $StrafeBulletCore, sourceOf("TR_STRAFE_BULLET_CORE")) emit("TR_STRAFE_BULLET_CORE", $StrafeBulletCore, sourceOf("TR_STRAFE_BULLET_CORE"))
emit("TR_STRAFE_BULLET_AURA", $StrafeBulletAura, sourceOf("TR_STRAFE_BULLET_AURA")) emit("TR_STRAFE_BULLET_AURA", $StrafeBulletAura, sourceOf("TR_STRAFE_BULLET_AURA"))
emit("TR_STRAFE_CORRIDOR_HEAT", $StrafeCorridorHeat, sourceOf("TR_STRAFE_CORRIDOR_HEAT")) emit("TR_STRAFE_CORRIDOR_HEAT", $StrafeCorridorHeat, sourceOf("TR_STRAFE_CORRIDOR_HEAT"))
emit("TR_STRAFE_CORRIDOR_TICKS", $StrafeCorridorTicks, sourceOf("TR_STRAFE_CORRIDOR_TICKS"))
emit("TR_STRAFE_WALL_HOTNESS", $StrafeWallHotness, sourceOf("TR_STRAFE_WALL_HOTNESS")) emit("TR_STRAFE_WALL_HOTNESS", $StrafeWallHotness, sourceOf("TR_STRAFE_WALL_HOTNESS"))
emit("TR_STRAFE_WALL_RADIANCE", $StrafeWallRadiance, sourceOf("TR_STRAFE_WALL_RADIANCE")) emit("TR_STRAFE_WALL_RADIANCE", $StrafeWallRadiance, sourceOf("TR_STRAFE_WALL_RADIANCE"))
@@ -642,6 +663,10 @@ proc knownEnvNames*(): seq[string] =
"TR_RAM_PLAN_MARGIN", "TR_RAM_PLAN_HITRATE", "TR_RAM_LOG", "TR_RAM_PLAN_MARGIN", "TR_RAM_PLAN_HITRATE", "TR_RAM_LOG",
"TR_TFIL_RANGE_LO", "TR_TFIL_RANGE_HI", "TR_TFIL_RANGE_TEMP", "TR_TFIL_RANGE_LO", "TR_TFIL_RANGE_HI", "TR_TFIL_RANGE_TEMP",
"TR_TFIL_RANGE_K", "TR_TFIL_CORRIDOR_HEAT", "TR_TFIL_WALL_HOTNESS", "TR_TFIL_RANGE_K", "TR_TFIL_CORRIDOR_HEAT", "TR_TFIL_WALL_HOTNESS",
"TR_TFIL_CORRIDOR_TICKS", "TR_TFIL_ARRIVE_TICKS",
"TR_TFIL_HOLD_WHEN_TRAPPED", "TR_TFIL_HOLD_MAX_TICKS",
"TR_TFIL_DANGER_THRESHOLD", "TR_TFIL_DIAG",
"TR_TFIL_GEO_MODE", "TR_TFIL_GEO_TAU",
"TR_TFIL_WALL_RADIANCE", "TR_TFIL_BULLET_CORE", "TR_TFIL_BULLET_AURA", "TR_TFIL_WALL_RADIANCE", "TR_TFIL_BULLET_CORE", "TR_TFIL_BULLET_AURA",
"TR_TFIL_TILE_REPLAN", "TR_TFIL_COMMIT_TICKS", "TR_TFIL_NO_REV", "TR_TFIL_TILE_REPLAN", "TR_TFIL_COMMIT_TICKS", "TR_TFIL_NO_REV",
"TR_TFIL_COMMIT_LOG", "TR_TFIL_COMMIT_ARRIVAL", "TR_TFIL_COMMIT_MARGIN", "TR_TFIL_COMMIT_LOG", "TR_TFIL_COMMIT_ARRIVAL", "TR_TFIL_COMMIT_MARGIN",
@@ -657,8 +682,10 @@ proc knownEnvNames*(): seq[string] =
"TR_STRAFE_FIRE_FIX", "TR_STRAFE_FIRE_FIX",
"TR_FIRE_FIX", "TR_FIRE_FIX",
"TR_FIRE_DIAG", "TR_FIRE_DIAG",
"TR_FIRE_LAG",
"TR_STRAFE_HEAT_GRID", "TR_STRAFE_BULLET_CORE", "TR_STRAFE_BULLET_AURA", "TR_STRAFE_HEAT_GRID", "TR_STRAFE_BULLET_CORE", "TR_STRAFE_BULLET_AURA",
"TR_STRAFE_CORRIDOR_HEAT", "TR_STRAFE_WALL_HOTNESS", "TR_STRAFE_CORRIDOR_HEAT", "TR_STRAFE_WALL_HOTNESS",
"TR_STRAFE_CORRIDOR_TICKS",
"TR_STRAFE_WALL_RADIANCE", "TR_STRAFE_WALL_RADIANCE",
SurfPrefDistEnv, SurfDistBandEnv, SurfWallMarginEnv, SurfRadialFracEnv, SurfPrefDistEnv, SurfDistBandEnv, SurfWallMarginEnv, SurfRadialFracEnv,
SurfLogEnv, SurfLogEnv,
@@ -134,6 +134,38 @@ proc detect*(t: var FireTracker, id: int, energy: float,
elif drop >= lo and drop <= hi: elif drop >= lo and drop <= hi:
result = @[drop] result = @[drop]
import std/[math, os, strutils]
## ── j147: the DETECTION LAG back-date (`TR_FIRE_LAG`, default 0) ─────────────
## MEASURED LIVE (`common_libs/tests/measure_fire_ghost_lag.py`, 4 sessions,
## 1777 matched ghost spawns over both movers, `TR_FIRE_DIAG=1`): the server
## dispatches a turn's fire AFTER our `go()` for that same turn, so the energy
## drop of a turn-T shot first reaches our scan at turn T+1 (our bot tick T). A bullet
## takes its FIRST step during the turn it is fired, so by then the true bullet
## is already `speed` px (11..20 px, one whole bullet step) downrange and the
## arrival deadline is a full tick shorter than the ghost's. Both movers place
## the ghost at the SCANNED enemy position, i.e. exactly where the bullet was
## born: the whole ghost trajectory is the true one shifted one turn later.
## The per-tick `advanceBullets` then keeps it there for the bullet's whole life.
##
## The compensation is the inverse: at SPAWN, back-date the shot by `lag` ticks
## (`x = origin + dir * speed * lag`, `y = ...`). The arrival deadline needs no
## separate change — every mover derives it from the ghost's own position
## (`heatDecay(along / speed)`, the `dot < 0` reap), so a correct position gives a
## correct deadline.
##
## DEFAULT 0 = the shipped behaviour, byte for byte (`x` is only touched when
## `lag > 0`), so the default-parity guard stays green.
var FireLag*: int = 0
proc loadFireTrackerEnv*() =
## Read the shared fire knobs. Called once at module init; callable again
## after `putEnv` so a guard test can exercise the arms in one process.
let s = getEnv("TR_FIRE_LAG", "").strip()
FireLag = (try: max(0, parseInt(s)) except ValueError: 0)
loadFireTrackerEnv()
proc endScan*(t: var FireTracker) = proc endScan*(t: var FireTracker) =
## Call once after the per-enemy scan. Rotates the event corrections one ## Call once after the per-enemy scan. Rotates the event corrections one
## slot: the events noted since the previous `endScan` become the corrections ## slot: the events noted since the previous `endScan` become the corrections
+38 -3
View File
@@ -226,6 +226,13 @@ const CorridorHeatDefault = 10.0 ## corridor heat (== PathDangerThreshold)
const WallHotnessDefault = 15.0 ## wall radiance peak (retune) const WallHotnessDefault = 15.0 ## wall radiance peak (retune)
const WallRadianceDefault = 5.0 ## wall radiance falloff (retune) const WallRadianceDefault = 5.0 ## wall radiance falloff (retune)
## j148: the corridor LENGTH bound, `TR_STRAFE_CORRIDOR_TICKS`. The shipped
## corridor runs from the bullet to the ARENA WALL; a bullet only covers
## `speed * t` px in `t` ticks, so a fixed TIME window is the physical length.
## 0 (the default) = to the wall, byte-for-byte shipped.
const DefaultStrafeCorridorTicks = 0.0
var StrafeCorridorTicks* = DefaultStrafeCorridorTicks
## Heat shape is override-able so the shipped field and the retune can be ## Heat shape is override-able so the shipped field and the retune can be
## compared on one binary. The DEFAULTS are the retune (see the block above); ## compared on one binary. The DEFAULTS are the retune (see the block above);
## the knobs are strafe-specific, so the ring mover's own `TR_TFIL_*` names do ## the knobs are strafe-specific, so the ring mover's own `TR_TFIL_*` names do
@@ -374,6 +381,15 @@ proc loadStrafeHeatEnv*() =
StrafeCorridorHeat = getEnvFloat("TR_STRAFE_CORRIDOR_HEAT", CorridorHeatDefault) StrafeCorridorHeat = getEnvFloat("TR_STRAFE_CORRIDOR_HEAT", CorridorHeatDefault)
StrafeWallHotness = getEnvFloat("TR_STRAFE_WALL_HOTNESS", WallHotnessDefault) StrafeWallHotness = getEnvFloat("TR_STRAFE_WALL_HOTNESS", WallHotnessDefault)
StrafeWallRadiance = getEnvFloat("TR_STRAFE_WALL_RADIANCE", WallRadianceDefault) StrafeWallRadiance = getEnvFloat("TR_STRAFE_WALL_RADIANCE", WallRadianceDefault)
StrafeCorridorTicks = getEnvFloat("TR_STRAFE_CORRIDOR_TICKS", DefaultStrafeCorridorTicks)
proc strafeCorridorReach*(tWall, speed: float): float =
## The ONE place the strafe corridor length is decided (same rule as tfil's
## `corridorReach`, same physics: a bullet covers `speed * t` px in `t` ticks).
## 0 (default) = to the arena wall, byte-for-byte shipped; N > 0 = N ticks.
## Only the LENGTH changes: the heat inside the surviving corridor is today's
## (`heatDecay(along / speed)` untouched) — this is NOT the j119 time-heat model.
if StrafeCorridorTicks <= 0.0: tWall else: min(tWall, speed * StrafeCorridorTicks)
proc loadStrafeEnv*() = proc loadStrafeEnv*() =
## Read the strafe knobs. Called once at module init; callable again after ## Read the strafe knobs. Called once at module init; callable again after
@@ -577,11 +593,19 @@ proc spawnTrackedWave(m: var StrafeModule, ws: WorldState, ei: EnemyInfo,
let heading = arctan2(predY - ei.y, predX - ei.x) let heading = arctan2(predY - ei.y, predX - ei.x)
if m.bullets.len >= MaxTrackedBullets: if m.bullets.len >= MaxTrackedBullets:
m.bullets.del(0) m.bullets.del(0)
# j147: back-date the shot by the measured detection lag (`TR_FIRE_LAG`,
# default 0 = untouched). See `movement_harness/fire_tracker.nim`.
let vx = speed * cos(heading)
let vy = speed * sin(heading)
var gx = ei.x
var gy = ei.y
if FireLag > 0:
gx += vx * FireLag.float
gy += vy * FireLag.float
m.bullets.add TrackedBullet( m.bullets.add TrackedBullet(
originX: ei.x, originY: ei.y, originX: ei.x, originY: ei.y,
x: ei.x, y: ei.y, x: gx, y: gy,
velX: speed * cos(heading), velX: vx, velY: vy,
velY: speed * sin(heading),
power: power, alive: true, age: 0) power: power, alive: true, age: 0)
proc noteEnemyBulletHit*(m: var StrafeModule, power: float) = proc noteEnemyBulletHit*(m: var StrafeModule, power: float) =
@@ -616,6 +640,16 @@ proc detectFires(m: var StrafeModule, ws: WorldState) =
" dealt=", m.fire.dealtPending " dealt=", m.fire.dealtPending
for p in m.fire.detect(ei.id, ei.energy, 0.09, 3.01, StrafeFireFix): for p in m.fire.detect(ei.id, ei.energy, 0.09, 3.01, StrafeFireFix):
m.spawnTrackedWave(ws, ei, p) m.spawnTrackedWave(ws, ei, p)
if StrafeFireDiag and m.bullets.len > 0:
# Ghost-vs-observer probe: the tick we DETECTED the fire, our own
# position (the timeline anchor) and the ghost's DRAWN position.
let b = m.bullets[^1]
let sp = 20.0 - 3.0 * p
echo "[firediag] SPAWN tick=", ws.tick,
" sx=", ws.selfX, " sy=", ws.selfY,
" gx=", b.x, " gy=", b.y,
" p=", p,
" eta=", sqrt((ws.selfX - b.x)^2 + (ws.selfY - b.y)^2) / sp
m.fire.endScan() m.fire.endScan()
proc advanceBullets(m: var StrafeModule, selfX, selfY: float) = proc advanceBullets(m: var StrafeModule, selfX, selfY: float) =
@@ -682,6 +716,7 @@ proc buildHeat(m: var StrafeModule, ws: WorldState) =
elif dx < 0.0: tMin = min(tMin, (0.0 - b.x) / dx) elif dx < 0.0: tMin = min(tMin, (0.0 - b.x) / dx)
if dy > 0.0: tMin = min(tMin, (m.arenaHeight - b.y) / dy) if dy > 0.0: tMin = min(tMin, (m.arenaHeight - b.y) / dy)
elif dy < 0.0: tMin = min(tMin, (0.0 - b.y) / dy) elif dy < 0.0: tMin = min(tMin, (0.0 - b.y) / dy)
tMin = strafeCorridorReach(tMin, speed)
if tMin == 0.0: continue if tMin == 0.0: continue
let (_, auraR) = bulletRadii(b.power) let (_, auraR) = bulletRadii(b.power)
let bMag = bulletMagScale(b.power) let bMag = bulletMagScale(b.power)
+372 -9
View File
@@ -70,6 +70,15 @@ var
const CommitTicks = 15 ## ticks to commit to a dodge point const CommitTicks = 15 ## ticks to commit to a dodge point
const MinCommitTicks = 5 ## must commit for this many ticks before danger replan allowed const MinCommitTicks = 5 ## must commit for this many ticks before danger replan allowed
## j154: the DERIVED hold budget's panic horizon. Server `rules/math.kt`:
## calcGunHeat(p) = 1 + p/5, coolDown 0.1/tick, and a gun may only fire at
## heat == 0 (`core/GunEngine.kt:36`), so two MAX-power shots are 1.6/0.1 = 16
## ticks apart and a 3.0-power bullet is `calcBulletDamage(3) = 16`. 16 ticks
## is therefore the window in which the enemy can land AT MOST its next two
## shots (32 damage) on us — the whole exposure a hold can possibly buy. It is
## also the FIRST window that admits the enemy's second shot at all, so a
## hold shorter than this can never be surprised by a third bullet.
const HoldPanicTicks = 16.0
const DangerReplanThreshold = 25.0 ## replan on serious threats only (bullet core), not corridors/auras const DangerReplanThreshold = 25.0 ## replan on serious threats only (bullet core), not corridors/auras
const CoolestLevels = 2 ## how many distinct lava values count as "cool" const CoolestLevels = 2 ## how many distinct lava values count as "cool"
const MaxTrackedBullets = 20 ## hard cap on tracked bullets const MaxTrackedBullets = 20 ## hard cap on tracked bullets
@@ -85,6 +94,8 @@ const MaxTrackedBullets = 20 ## hard cap on tracked bullets
# #
# Every default below reproduces the shipped mover byte-for-byte; see the # Every default below reproduces the shipped mover byte-for-byte; see the
# default-path parity guard in `common_libs/tests/test_tfil_commit_env.nim`. # default-path parity guard in `common_libs/tests/test_tfil_commit_env.nim`.
const DefaultDangerThreshold = 10.0 ## today's `PathDangerThreshold`
type type
TfilTileReplan* = enum TfilTileReplan* = enum
ttrSelf, ttrOff, ttrEnemy ttrSelf, ttrOff, ttrEnemy
@@ -93,6 +104,33 @@ type
rrNone, rrInit, rrTileSelf, rrTileEnemy, rrDanger, rrExpiry, rrNone, rrInit, rrTileSelf, rrTileEnemy, rrDanger, rrExpiry,
rrArrival, rrHyst ## j144: the tile was REACHED / the alternative won by a margin rrArrival, rrHyst ## j144: the tile was REACHED / the alternative won by a margin
type
TfilGeoDim* = enum ## WHAT geometry the draw is shaped by
gdoOff = "off", gdoTurn = "turn", gdoDist = "dist", gdoBoth = "both"
TfilGeoShape* = enum ## HOW the shape is turned into a draw
gfSoft = "soft", gfTopK = "topk", gfRej = "rej"
proc parseGeo*(s: string): tuple[dim: TfilGeoDim, form: TfilGeoShape] =
## `"turn"`, `"dist"`, `"both"` | any of those + `"-soft"` (default) |
## `"-topk"` | `"-rej"`. Anything unrecognised, and `"off"`, is OFF = today's
## uniform draw. One env name, two axes: a `both-soft`/`both-topk` grid would
## need three names for the same three dials.
var a = s.strip().toLowerAscii()
var form = gfSoft
let dash = a.rfind('-')
if dash > 0:
case a[dash + 1 .. ^1]
of "topk": form = gfTopK; a = a[0 ..< dash]
of "rej", "rejection": form = gfRej; a = a[0 ..< dash]
of "soft": a = a[0 ..< dash] # the default form, spelled out
else: discard
result.form = form
result.dim = case a
of "turn": gdoTurn
of "dist", "distance": gdoDist
of "both": gdoBoth
else: gdoOff
proc tileReplanName*(m: TfilTileReplan): string = proc tileReplanName*(m: TfilTileReplan): string =
case m case m
of ttrSelf: "self" of ttrSelf: "self"
@@ -152,6 +190,78 @@ var
## j134: the shared fire-detection correction (`TR_FIRE_FIX`, default on). ## j134: the shared fire-detection correction (`TR_FIRE_FIX`, default on).
## Off = the shipped `prev - energy` detector byte-for-byte. ## Off = the shipped `prev - energy` detector byte-for-byte.
TfilFireFix*: bool = true TfilFireFix*: bool = true
## j134/j147: the env-gated live trace (`TR_FIRE_DIAG`) — one `SPAWN` line per
## detected enemy fire, for the ghost-vs-observer position probe. Observability
## only; off by default.
TfilFireDiag*: bool = false
## j150: the picker's hard heat cutoff was a proc-local `const`, so no offline
## sweep could move it. Same env-overridable-var pattern as the shape knobs;
## the DEFAULT is today's `10.0`, so the default path is bit-identical.
## TR_TFIL_DANGER_THRESHOLD default 10.0
TfilDangerThreshold* = DefaultDangerThreshold
## j152: `TR_TFIL_GEO_MODE` / `TR_TFIL_GEO_TAU` — GEOMETRY shapes the DRAW.
## Heat still gates the pool with the same hard filter; this only re-weights
## the survivors by how far the tile sits from where we are already going.
## TR_TFIL_GEO_MODE off | turn | dist | both [+ `-soft` | `-topk` | `-rej`]
## TR_TFIL_GEO_TAU deg, 0 = off (= today's uniform draw, exactly)
## WHAT IS DIFFERENT FROM j9 (`TR_TFIL_TURN_BIAS`, a live null): that was a
## tiebreak WEIGHT applied only among the non-empty safe set. This runs on the
## WHOLE pool the draw already runs on, so it also shapes the 2 promoted
## least-hot tiles the ~65% forced (safePre < 2) picks choose from.
TfilGeoMode*: TfilGeoDim = gdoOff
TfilGeoForm*: TfilGeoShape = gfSoft
TfilGeoTau*: float = 0.0
## j151: `TR_TFIL_ARRIVE_TICKS` — refuse a candidate we cannot REACH inside
## the commitment horizon (ticks = dist / MaxSpeed). Hard bound, not a
## preference; empty pool => today's full pool, so it can never starve the
## draw. 0 (default) = off = byte-for-byte today.
TfilArriveTicks*: float = 0.0
## j153: `TR_TFIL_HOLD_WHEN_TRAPPED` — when the SAFE set is EMPTY (zero tiles
## with `pathMaxHeat <= PathDangerThreshold` inside the reachable hull), STOP
## for this tick instead of promoting the 2 least-hot blocked tiles. The
## owner's rule: "if no tile is found to go, to not choose the less dangerous,
## but to stay still! the next tick probably the situation already changed".
## ONE tick only, never latched: the hold is taken at the pick site, and the
## pick site only runs when `commitTicks == 0`, so the very next tick
## re-evaluates the field from scratch. That is why there is no max-hold knob:
## a counter can only add a way to get stuck.
## Default false = byte-for-byte today's promote-the-2 behaviour.
TfilHoldWhenTrapped*: bool = false
## j154: `TR_TFIL_HOLD_MAX_TICKS` — the BOUNDED version of the j153 one-tick
## hold. While the safe tile set stays EMPTY the mover holds position for at
## most this many ticks (the enemy's own rate of fire bounds what waiting can
## buy: see `HoldPanicTicks`). Rules, all four of them load-bearing:
## * a safe tile exists -> release on the SAME tick, always
## * a tracked bullet reaches us within `min(N, 16)` ticks -> PANIC RELEASE,
## the hold is overridden and the normal promote-the-2 fallback resumes
## * the counter resets when a safe tile is taken, so the bound is per
## empty-streak, not per round
## * the gun is untouched: `computeMove` never fires, so a held tick still
## fires exactly as every other tick (verified in `test_tfil_commit_env`)
## Default 0 = OFF = byte-for-byte today's behaviour, j153 included.
TfilHoldMaxTicks*: int = 0
## j150: `TR_TFIL_DIAG` — fill `TfilLoss*` with the per-pick LOSS HISTOGRAM
## (how many tiles die at each picker stage). Pure counters, off by default.
TfilDiag*: bool = false
## The picker's loss histogram, one entry per PICK. Stage sizes, in picker
## order: tiles inside the reachable hull -> survivors of the `CoolestLevels`
## distinct-lava-value filter -> survivors of the `pathMaxHeat <= threshold`
## filter (counted BEFORE the "keep 2 anyway" promotion) -> what the draw
## actually runs on. Pure bookkeeping, read by the offline ruler.
type TfilLossStats* = object
picks*: int
sReach*: int ## inside the reachable hull
sCool*: int ## after CoolestLevels (= 2) distinct-value filter
sSafe*: int ## after the path heat filter, pre-promotion
sCand*: int ## what the draw ran on (post blocked-tile/no-rev)
emptySafe*: int ## picks that had to break the heat filter (sSafe < 2)
safeHist*: array[8, int] ## sSafe size buckets: 0,1,2-3,4-7,8-15,16-31,32-63,64+
rejectedHeat*: seq[float] ## pathMaxHeat of every tile the filter dropped
admittedHeat*: seq[float] ## pathMaxHeat of every tile that passed it
chosenHeat*: seq[float]
var TfilLoss*: TfilLossStats
proc getEnvInt(name: string, default: int): int = proc getEnvInt(name: string, default: int): int =
let s = getEnv(name, "") let s = getEnv(name, "")
@@ -186,6 +296,23 @@ proc loadTfilCommitEnv*() =
TfilTurnBias = max(0.0, getEnvFloat("TR_TFIL_TURN_BIAS", 0.0)) TfilTurnBias = max(0.0, getEnvFloat("TR_TFIL_TURN_BIAS", 0.0))
TfilTurnRefDeg = max(0.0, getEnvFloat("TR_TFIL_TURN_REF_DEG", 45.0)) TfilTurnRefDeg = max(0.0, getEnvFloat("TR_TFIL_TURN_REF_DEG", 45.0))
TfilFireFix = getEnvBool("TR_FIRE_FIX", true) TfilFireFix = getEnvBool("TR_FIRE_FIX", true)
TfilFireDiag = existsEnv("TR_FIRE_DIAG")
TfilDangerThreshold = max(0.0, getEnvFloat("TR_TFIL_DANGER_THRESHOLD",
DefaultDangerThreshold))
TfilDiag = getEnvBool("TR_TFIL_DIAG", false)
let (gd, gf) = parseGeo(getEnv("TR_TFIL_GEO_MODE", "off"))
TfilGeoMode = gd
TfilGeoForm = gf
TfilGeoTau = max(0.0, getEnvFloat("TR_TFIL_GEO_TAU", 0.0))
# j151: hard arrival bound. The draw is UNIFORM over every safe tile inside the
# 50-tick reachable hull, so a tile 47 ticks away had the same 1-in-52 chance
# as the adjacent one, while the target is only HELD for CommitTicks=15. The
# offline ruler (measure_tfil_pick_defects) measured 65% of picks beyond the
# 15-tick horizon and a 6.5% arrival rate. 0 = off = today's uniform draw.
TfilArriveTicks = max(0.0, getEnvFloat("TR_TFIL_ARRIVE_TICKS", 0.0))
TfilHoldWhenTrapped = getEnvBool("TR_TFIL_HOLD_WHEN_TRAPPED", false)
TfilHoldMaxTicks = max(0, getEnvInt("TR_TFIL_HOLD_MAX_TICKS", 0))
if not TfilDiag: TfilLoss = TfilLossStats()
loadTfilCommitEnv() loadTfilCommitEnv()
@@ -264,6 +391,31 @@ proc loadTfilHeatEnv*() =
loadTfilHeatEnv() loadTfilHeatEnv()
# ── Corridor LENGTH bound (TR_TFIL_CORRIDOR_TICKS, default 0 = to the wall) ──
#
# WHY: the shipped corridor is the rotated rectangle from the bullet to the
# ARENA WALL, so one distant bullet blankets a 40px-wide swath across the whole
# map. That is not physical: in `t` ticks a bullet covers `speed * t` px, and
# `speed = 20 - 3*power`, so a fast (low-power) bullet's reach is LONG and a
# slow one's is SHORT.
#
# WHAT: bound the corridor's LENGTH, nothing else — the heat inside the
# surviving corridor is EXACTLY today's (`heatDecay(along/speed)` is unchanged),
# so unlike the j119 time-indexed heat model this does NOT decay heat along the
# corridor; it only removes corridor that no bullet will reach.
var TfilCorridorTicks* = 0.0 ## 0 (default) = to the wall: byte-for-byte shipped
proc loadTfilCorridorEnv*() =
TfilCorridorTicks = getEnvFloat("TR_TFIL_CORRIDOR_TICKS", 0.0)
loadTfilCorridorEnv()
proc corridorReach*(tWall, speed: float): float =
## The ONE place the corridor length is decided, so the heat field and the
## drawn outline can never disagree. `tWall` = distance to the wall along the
## heading, `speed` = the ghost's own px/tick. 0 = to the wall (shipped).
if TfilCorridorTicks <= 0.0: tWall else: min(tWall, speed * TfilCorridorTicks)
proc heatDecay*(dt: float): float = proc heatDecay*(dt: float): float =
## Fraction of a bullet's heat still present `dt` ticks before it arrives. ## Fraction of a bullet's heat still present `dt` ticks before it arrives.
## Exactly 1.0 when the time model is off, so the default field is ## Exactly 1.0 when the time model is off, so the default field is
@@ -320,6 +472,12 @@ type
## candidate set of the last pick (j145: ## candidate set of the last pick (j145:
## lets a caller measure the REGRET of the ## lets a caller measure the REGRET of the
## draw instead of only the drawn value) ## draw instead of only the drawn value)
lastHeld: bool ## the last tick HELD position
## (j153: TR_TFIL_HOLD_WHEN_TRAPPED,
## the safe set was empty)
holdTicks: int ## j154: ticks HELD in the current
## empty-safe-set streak; reset to 0
## when a safe tile is taken
lastPickSafe: int ## how many SAFE tiles (pathMaxHeat lastPickSafe: int ## how many SAFE tiles (pathMaxHeat
## <= PathDangerThreshold) the last pick ## <= PathDangerThreshold) the last pick
## drew from (j146: the size of the set ## drew from (j146: the size of the set
@@ -354,6 +512,7 @@ proc resetRound*(m: var TFILModule) =
m.fire.reset() m.fire.reset()
m.commitTicks = 0 m.commitTicks = 0
m.commitAge = 0 m.commitAge = 0
m.holdTicks = 0 ## j154: the bounded hold never survives a round
m.cachedHull = @[] m.cachedHull = @[]
m.cachedInsideTiles = @[] m.cachedInsideTiles = @[]
m.blockedTile = (col: 0, row: 0, active: false) m.blockedTile = (col: 0, row: 0, active: false)
@@ -369,6 +528,7 @@ proc resetRound*(m: var TFILModule) =
m.picks = 0 m.picks = 0
m.lastPickPromoted = false m.lastPickPromoted = false
m.lastPickMinTurn = 0.0 m.lastPickMinTurn = 0.0
m.lastHeld = false
m.lastPickSafe = 0 m.lastPickSafe = 0
# ── Commit diagnostics (TR_TFIL_COMMIT_LOG, off by default) ────────────────── # ── Commit diagnostics (TR_TFIL_COMMIT_LOG, off by default) ──────────────────
@@ -426,11 +586,20 @@ proc spawnTrackedWave(m: var TFILModule, ws: WorldState, ei: EnemyInfo,
let heading = arctan2(predY - ei.y, predX - ei.x) let heading = arctan2(predY - ei.y, predX - ei.x)
if m.bullets.len >= MaxTrackedBullets: if m.bullets.len >= MaxTrackedBullets:
m.bullets.del(0) # ponytail: drop oldest; fine for 20-bullet cap m.bullets.del(0) # ponytail: drop oldest; fine for 20-bullet cap
# j147: back-date the shot by the measured detection lag (`TR_FIRE_LAG`,
# default 0 = untouched). See `movement_harness/fire_tracker.nim`.
let vx = speed * cos(heading)
let vy = speed * sin(heading)
var gx = ei.x
var gy = ei.y
if FireLag > 0:
gx += vx * FireLag.float
gy += vy * FireLag.float
m.bullets.add TrackedBullet( m.bullets.add TrackedBullet(
originX: ei.x, originY: ei.y, originX: ei.x, originY: ei.y,
x: ei.x, y: ei.y, x: gx, y: gy,
velX: speed * cos(heading), velX: vx,
velY: speed * sin(heading), velY: vy,
power: power, power: power,
alive: true, alive: true,
age: 0) age: 0)
@@ -451,8 +620,40 @@ proc detectFires(m: var TFILModule, ws: WorldState) =
for ei in ws.enemies: for ei in ws.enemies:
for p in m.fire.detect(ei.id, ei.energy, 0.09, 3.01, TfilFireFix): for p in m.fire.detect(ei.id, ei.energy, 0.09, 3.01, TfilFireFix):
m.spawnTrackedWave(ws, ei, p) m.spawnTrackedWave(ws, ei, p)
if TfilFireDiag and m.bullets.len > 0:
# Ghost-vs-observer probe: the tick we DETECTED the fire, our own
# position (the timeline anchor) and the ghost's DRAWN position.
let b = m.bullets[^1]
let sp = 20.0 - 3.0 * p
echo "[firediag] SPAWN tick=", ws.tick,
" sx=", ws.selfX, " sy=", ws.selfY,
" gx=", b.x, " gy=", b.y,
" p=", p,
" eta=", sqrt((ws.selfX - b.x)^2 + (ws.selfY - b.y)^2) / sp
m.fire.endScan() m.fire.endScan()
proc bulletPanic*(m: TFILModule, selfX, selfY, horizon: float): bool =
## PANIC RELEASE (j154). True when a TRACKED bullet's straight path comes
## within its own CORE of where WE are at any time in `[0, horizon]` ticks.
## Closest approach of a straight ray is `t* = ((self - b) . v) / |v|^2`; the
## `t* < 0` case is the `dot < 0` reap in `advanceBullets` (it is already past
## us) and `t* > horizon` is "not inside the window". The prediction is the
## tracked ghost's OWN position/velocity — the same model `pathMaxHeat` decays
## by and `advanceBullets` integrates — so there is no second arrival model in
## this file. Exported so the guard test can call it directly.
if horizon <= 0.0: return false
for b in m.bullets:
let v2 = b.velX * b.velX + b.velY * b.velY
if v2 < 1e-9: continue
let dx = selfX - b.x
let dy = selfY - b.y
let t = (dx * b.velX + dy * b.velY) / v2
if t < 0.0 or t > horizon: continue
let mx = dx - t * b.velX
let my = dy - t * b.velY
if sqrt(mx * mx + my * my) <= bulletRadii(b.power).core: return true
false
proc advanceBullets(m: var TFILModule, selfX, selfY: float) = proc advanceBullets(m: var TFILModule, selfX, selfY: float) =
## Advance positions and reap bullets that are: passed us, out of bounds, or too old. ## Advance positions and reap bullets that are: passed us, out of bounds, or too old.
var i = 0 var i = 0
@@ -482,6 +683,9 @@ type CorridorGeom = object
bx, by: float ## bullet origin bx, by: float ## bullet origin
proc corridorGeom(b: TrackedBullet, arenaWidth, arenaHeight: float): CorridorGeom = proc corridorGeom(b: TrackedBullet, arenaWidth, arenaHeight: float): CorridorGeom =
## `tMin` is the corridor LENGTH: the distance to the wall, bounded by
## `corridorReach` (TR_TFIL_CORRIDOR_TICKS). Unset (0) -> exactly the wall
## distance, so the shipped field and outline are byte-for-byte unchanged.
let speed = sqrt(b.velX * b.velX + b.velY * b.velY) let speed = sqrt(b.velX * b.velX + b.velY * b.velY)
if speed < 0.001: return if speed < 0.001: return
let dx = b.velX / speed let dx = b.velX / speed
@@ -491,6 +695,7 @@ proc corridorGeom(b: TrackedBullet, arenaWidth, arenaHeight: float): CorridorGeo
elif dx < 0.0: tMin = min(tMin, (0.0 - b.x) / dx) elif dx < 0.0: tMin = min(tMin, (0.0 - b.x) / dx)
if dy > 0.0: tMin = min(tMin, (arenaHeight - b.y) / dy) if dy > 0.0: tMin = min(tMin, (arenaHeight - b.y) / dy)
elif dy < 0.0: tMin = min(tMin, (0.0 - b.y) / dy) elif dy < 0.0: tMin = min(tMin, (0.0 - b.y) / dy)
tMin = corridorReach(tMin, speed)
CorridorGeom(dx: dx, dy: dy, px: -dy, py: dx, tMin: tMin, bx: b.x, by: b.y) CorridorGeom(dx: dx, dy: dy, px: -dy, py: dx, tMin: tMin, bx: b.x, by: b.y)
proc lavaAt(m: TFILModule, col, row: int): float = proc lavaAt(m: TFILModule, col, row: int): float =
@@ -628,6 +833,76 @@ proc turnWeights*(turns: openArray[float], bias, refDeg: float): seq[int] =
result.add max(1, int(round(1.0 + bias * result.add max(1, int(round(1.0 + bias *
(1.0 - max(0.0, t - refDeg) / 180.0)))) (1.0 - max(0.0, t - refDeg) / 180.0))))
# ── j152: the geometric DRAW ────────────────────────────────────────────────
# The owner: "choose tiles pool not only from the heat point but from a
# geometrically position too". Heat is already a HARD filter (unchanged); this is
# the second half — the distribution the draw samples from.
#
# WHY THIS IS NOT j9 AGAIN. j9 (`TR_TFIL_TURN_BIAS`) down-weighted the turn among
# the non-empty safe set and measured a live null. This runs on the pool the draw
# ALREADY runs on, which for ~65% of picks is the 2 promoted least-hot tiles that
# broke the heat filter — j9 could not see those at all.
const GeoDegPerTick = 12.0 ## distance cost, in "effective degrees": a 15-tick
## trip (the commitment horizon) costs the same as a
## 180 deg turn, so ONE tau knob means the same
## thing in `turn` and `dist` mode.
proc geoCosts*(turns, ttas: openArray[float], dim: TfilGeoDim): seq[float] =
## Per-candidate cost in effective degrees. Never filters: it only re-orders
## and re-weights tiles that already passed the heat filter.
for i in 0..<turns.len:
result.add (if dim in {gdoTurn, gdoBoth}: turns[i] else: 0.0) +
(if dim in {gdoDist, gdoBoth}: ttas[i] * GeoDegPerTick else: 0.0)
proc geoPick*(turns, ttas: openArray[float], dim: TfilGeoDim, form: TfilGeoShape,
tau: float): int =
## Draw index from `candidates` under the geometric weight. NEVER returns -1
## and NEVER returns an out-of-range index, so no arm can starve the pick.
let c = geoCosts(turns, ttas, dim)
var best = 0
for i in 1..<c.len:
if c[i] < c[best]: best = i
case form
of gfRej:
# Rejection sampling: a GEOMETRY-FREE acceptance test (no shape function at
# all) — uniform draw, redraw while the candidate costs more than `tau`.
# ponytail: 16 tries is a fixed budget; widen it if the band ever tightens
# enough that the fallback below starts dominating.
for _ in 0..<16:
let i = rand(c.high)
if c[i] <= tau: return i
return best # band too tight: take the best available, never starve
of gfTopK:
# Hard: keep the best THIRD, uniform inside. Collapses diversity by design —
# measured against the soft form before it could ever be a default.
let k = max(1, (c.len + 2) div 3)
var pool: seq[int]
var taken = newSeq[bool](c.len)
for _ in 0..<k:
var b = -1
for i in 0..<c.len:
if not taken[i] and (b < 0 or c[i] < c[b]): b = i
taken[b] = true
pool.add b
return pool[rand(pool.high)]
of gfSoft:
# w = exp(-cost / tau), NORMALISED so the best tile weighs exactly 1.0. The
# normalisation is what makes "all tiles tie" (and only that) degrade to the
# uniform draw, and makes starvation impossible.
var w: seq[float]
for x in c: w.add exp(-x / tau)
var wMax = 0.0
for x in w: wMax = max(wMax, x)
if wMax <= 0.0: return best
var total = 0.0
for x in w: total += x
let r = rand(total)
var acc = 0.0
for i, x in w:
acc += x
if r < acc: return i
return best
proc computeMove*(m: var TFILModule, ws: WorldState): MoveCommand = proc computeMove*(m: var TFILModule, ws: WorldState): MoveCommand =
if m.cols == 0: if m.cols == 0:
m.initGrid(ws.arenaWidth, ws.arenaHeight) m.initGrid(ws.arenaWidth, ws.arenaHeight)
@@ -881,6 +1156,7 @@ proc computeMove*(m: var TFILModule, ws: WorldState): MoveCommand =
var pickedInterval = 0 var pickedInterval = 0
var pickedTurn = 0.0 # log-only: |turn| to the tile that was chosen var pickedTurn = 0.0 # log-only: |turn| to the tile that was chosen
var pickedPromoted = false ## log-only: the pick had to break the heat filter var pickedPromoted = false ## log-only: the pick had to break the heat filter
var pickedHeld = false ## j153: the safe set was EMPTY -> hold this tick
# Hull + inside-tiles: only recompute on replan tick (commitTicks == 0) # Hull + inside-tiles: only recompute on replan tick (commitTicks == 0)
type TileRef = tuple[col, row: int] type TileRef = tuple[col, row: int]
@@ -931,11 +1207,13 @@ proc computeMove*(m: var TFILModule, ws: WorldState): MoveCommand =
# Score each cool tile by MAX lava on the straight-line path from bot. # Score each cool tile by MAX lava on the straight-line path from bot.
# A single hot tile on the path (corridor, bullet core, enemy aura) makes the whole path unsafe. # A single hot tile on the path (corridor, bullet core, enemy aura) makes the whole path unsafe.
const PathSampleStep = 18.0 # ~half a tile const PathSampleStep = 18.0 # ~half a tile
const PathDangerThreshold = 10.0 # max lava on path; above this = unsafe # j150: was `const 10.0`; now the env-overridable var whose DEFAULT is 10.0.
let PathDangerThreshold = TfilDangerThreshold # max lava on path; above = unsafe
# j145: `turnDeg` is the |heading change| from the direction we are ALREADY # j145: `turnDeg` is the |heading change| from the direction we are ALREADY
# travelling to the tile centre. It is carried on the candidate (never folded # travelling to the tile centre. It is carried on the candidate (never folded
# into `pathMaxHeat`) so the pick can bias among the safe tiles only. # into `pathMaxHeat`) so the pick can bias among the safe tiles only.
type ScoredTile = tuple[col, row: int; pathMaxHeat: float; turnDeg: float] type ScoredTile = tuple[col, row: int; pathMaxHeat: float; turnDeg: float;
arriveTicks: float]
proc pathMaxHeat(m: TFILModule, fx, fy, tx, ty: float): float = proc pathMaxHeat(m: TFILModule, fx, fy, tx, ty: float): float =
## MAX lava on the straight-line segment (fx,fy) -> (tx,ty), sampled every ## MAX lava on the straight-line segment (fx,fy) -> (tx,ty), sampled every
@@ -976,7 +1254,8 @@ proc computeMove*(m: var TFILModule, ws: WorldState): MoveCommand =
scoredTiles.add (col: t.col, row: t.row, scoredTiles.add (col: t.col, row: t.row,
pathMaxHeat: pathMaxHeat(m, ws.selfX, ws.selfY, tx, ty), pathMaxHeat: pathMaxHeat(m, ws.selfX, ws.selfY, tx, ty),
turnDeg: abs(tileOffTravel(m, t.col, t.row, ws.selfX, turnDeg: abs(tileOffTravel(m, t.col, t.row, ws.selfX,
ws.selfY, travelDeg))) ws.selfY, travelDeg)),
arriveTicks: sqrt((tx - ws.selfX)^2 + (ty - ws.selfY)^2) / MaxSpeed)
# Sort by pathMaxHeat ascending (insertion sort — small N) # Sort by pathMaxHeat ascending (insertion sort — small N)
for i in 1..<scoredTiles.len: for i in 1..<scoredTiles.len:
@@ -996,8 +1275,12 @@ proc computeMove*(m: var TFILModule, ws: WorldState): MoveCommand =
for t in scoredTiles: for t in scoredTiles:
if t.pathMaxHeat <= PathDangerThreshold: safeTiles.add t if t.pathMaxHeat <= PathDangerThreshold: safeTiles.add t
else: blockedTiles.add t else: blockedTiles.add t
let safePre = safeTiles.len # j150: the safe set BEFORE the "keep 2" promotion
let safeEmpty = safePre == 0
if safeTiles.len < 2: if safeTiles.len < 2:
# Fallback: promote the least-hot blocked tiles until we have 2 # Fallback: promote the least-hot blocked tiles until we have 2. j154 runs
# this EVEN when a hold is armed, so the panic release has a real fallback to
# fall back ON; the hold only ever DISCARDS the promotion, at the pick site.
# ponytail: O(n) scan on already-sorted seq — fine for small N # ponytail: O(n) scan on already-sorted seq — fine for small N
let needed = 2 - safeTiles.len let needed = 2 - safeTiles.len
let promote = min(needed, blockedTiles.len) let promote = min(needed, blockedTiles.len)
@@ -1006,6 +1289,15 @@ proc computeMove*(m: var TFILModule, ws: WorldState): MoveCommand =
m.lastPickPromoted = true m.lastPickPromoted = true
blockedTiles = blockedTiles[promote ..< blockedTiles.len] blockedTiles = blockedTiles[promote ..< blockedTiles.len]
# j151: the arrival bound, applied to the pool the draw runs on (hysteresis
# included) so every consumer sees the same set. It never empties the pool:
# if nothing is within the horizon, the full pool is used, exactly as today.
if TfilArriveTicks > 0.0:
var withinHorizon: seq[ScoredTile]
for t in safeTiles:
if t.arriveTicks <= TfilArriveTicks: withinHorizon.add t
if withinHorizon.len > 0: safeTiles = withinHorizon
# Commitment logic. With every j144 knob at its default (all off) this is the # Commitment logic. With every j144 knob at its default (all off) this is the
# original three-way test, unchanged. j144 adds two ways OUT of a commitment # original three-way test, unchanged. j144 adds two ways OUT of a commitment
# that are NOT a tile crossing, and turns the tick counter into a MINIMUM # that are NOT a tile crossing, and turns the tick counter into a MINIMUM
@@ -1063,7 +1355,31 @@ proc computeMove*(m: var TFILModule, ws: WorldState): MoveCommand =
# is the first pick of the round, which is not a switch at all. # is the first pick of the round, which is not a switch at all.
let midFlight = m.picks > 0 and not atTarget let midFlight = m.picks > 0 and not atTarget
if m.commitTicks == 0 and safeTiles.len > 0: # ── j153/j154: THE HOLD, decided here and nowhere else ─────────────────────
# The safe set was EMPTY, so there is nothing good to walk to. Today's answer
# is the promote-the-2 fallback above; the owner's answer is to stand still and
# let the field change. It is decided HERE, after the commitment block, so
# "are we on a replan tick?" is already answered — a hold replaces a REPLAN
# and can never interrupt a live commitment (j153's comment said that; its
# code did not enforce it, and a mid-commitment hold silently froze the bot).
var doPick = m.commitTicks == 0 and safeTiles.len > 0
if m.commitTicks == 0 and safeEmpty:
let budgeted = TfilHoldMaxTicks > 0
let hold =
if budgeted:
# The BOUNDED hold: at most N ticks per empty streak, released the tick
# a safe tile exists, and overridden outright by an inbound bullet.
m.holdTicks < TfilHoldMaxTicks and
not bulletPanic(m, ws.selfX, ws.selfY,
min(TfilHoldMaxTicks.float, HoldPanicTicks))
else:
TfilHoldWhenTrapped # j153's ONE-tick hold, unchanged
if hold:
pickedHeld = true
doPick = false
if budgeted: inc m.holdTicks
if doPick:
# Filter out the blocked tile from candidates # Filter out the blocked tile from candidates
var candidates: seq[ScoredTile] var candidates: seq[ScoredTile]
for t in safeTiles: for t in safeTiles:
@@ -1086,7 +1402,20 @@ proc computeMove*(m: var TFILModule, ws: WorldState): MoveCommand =
for i in keep: narrowed.add candidates[i] for i in keep: narrowed.add candidates[i]
candidates = narrowed candidates = narrowed
var chosen = 0 var chosen = 0
if (TfilNoRev or TfilTurnBias > 0.0) and candidates.len >= 2: # j152: geometry shapes the DRAW, on top of the heat filter (never instead
# of it). Off by default: with `TR_TFIL_GEO_MODE=off` this whole block is
# skipped and the draw below is byte-for-byte today's.
# ponytail: takes precedence over TfilNoRev/TfilTurnBias (both also default
# off) instead of composing weights; compose if two are ever armed at once.
let geoOn = TfilGeoMode != gdoOff and TfilGeoTau > 0.0
if geoOn and candidates.len >= 2:
var gturns: seq[float]
var gttas: seq[float]
for t in candidates:
gturns.add t.turnDeg
gttas.add t.arriveTicks
chosen = geoPick(gturns, gttas, TfilGeoMode, TfilGeoForm, TfilGeoTau)
elif (TfilNoRev or TfilTurnBias > 0.0) and candidates.len >= 2:
# Soft preferences — down-weight, never filter, and only ever among tiles # Soft preferences — down-weight, never filter, and only ever among tiles
# that already passed the hard heat filter above: # that already passed the hard heat filter above:
# arm C (TR_TFIL_NO_REV, off by default) — 3:1 forward vs rearward, # arm C (TR_TFIL_NO_REV, off by default) — 3:1 forward vs rearward,
@@ -1143,6 +1472,7 @@ proc computeMove*(m: var TFILModule, ws: WorldState): MoveCommand =
m.commitTicks = TfilCommitTicks m.commitTicks = TfilCommitTicks
m.commitAge = 0 m.commitAge = 0
m.commitLava = m.lavaAt(ct.col, ct.row) m.commitLava = m.lavaAt(ct.col, ct.row)
m.holdTicks = 0 # j154: a safe tile was taken -> the budget refills
m.blockedTile.active = false # clear after successful pick m.blockedTile.active = false # clear after successful pick
# log-only: reversal test against the travel direction # log-only: reversal test against the travel direction
@@ -1158,6 +1488,25 @@ proc computeMove*(m: var TFILModule, ws: WorldState): MoveCommand =
m.lastPickCall = m.callCount m.lastPickCall = m.callCount
inc m.picks inc m.picks
if TfilDiag: # j150: where the tiles died, one row per pick. No effect.
inc TfilLoss.picks
TfilLoss.sReach += insideTiles.len
TfilLoss.sCool += coolTiles.len
TfilLoss.sSafe += safePre
TfilLoss.sCand += candidates.len
if safePre < 2: inc TfilLoss.emptySafe
let b = (if safePre == 0: 0 elif safePre == 1: 1
elif safePre <= 3: 2 elif safePre <= 7: 3
elif safePre <= 15: 4 elif safePre <= 31: 5
elif safePre <= 63: 6 else: 7)
inc TfilLoss.safeHist[b]
# admitted/rejected by the FILTER itself, so the promoted (over-threshold)
# rescue tiles are not counted as safe.
for t in scoredTiles:
if t.pathMaxHeat <= PathDangerThreshold: TfilLoss.admittedHeat.add t.pathMaxHeat
else: TfilLoss.rejectedHeat.add t.pathMaxHeat
TfilLoss.chosenHeat.add ct.pathMaxHeat
if m.debugGraphics: if m.debugGraphics:
# Reachable hull perimeter (darker blue) # Reachable hull perimeter (darker blue)
if m.cachedHull.len >= 3: if m.cachedHull.len >= 3:
@@ -1230,10 +1579,24 @@ proc computeMove*(m: var TFILModule, ws: WorldState): MoveCommand =
",\"reason\":\"" & reasonName(reason) & "\",\"rev\":" & ",\"reason\":\"" & reasonName(reason) & "\",\"rev\":" &
(if pickedRev: "1" else: "0") & ",\"mid\":" & (if pickedRev: "1" else: "0") & ",\"mid\":" &
(if pickedMidFlight: "1" else: "0") & ",\"interval\":" & $pickedInterval & (if pickedMidFlight: "1" else: "0") & ",\"interval\":" & $pickedInterval &
",\"hold\":" & (if pickedHeld: "1" else: "0") &
",\"ht\":" & $m.holdTicks & ## j154: ticks held in the current streak
",\"picks\":" & $m.picks & "}") ",\"picks\":" & $m.picks & "}")
if pickedThisTick: m.replanReason = rrNone if pickedThisTick: m.replanReason = rrNone
m.lastHeld = pickedHeld
# ── Steering ───────────────────────────────────────────────────────────────── # ── Steering ─────────────────────────────────────────────────────────────────
# j153/j154: HOLD. `speed: 0.0` is how this module already says "stop" (the
# already-at-target case below returns the same command), so holding needs no
# new signal, and the hold path is byte-identical to the stop path the bot
# already emits every time it reaches its dodge tile. The gun is NOT in this
# module — computeMove never touches fire, and `ModularBot.nim` aims and
# fires from tracked state AFTER `go()` on every tick regardless of the speed
# it just commanded — so a held tick still fires exactly as before. Guarded in
# `test_tfil_commit_env.nim` (the fire detector still latches a wave on a
# held tick).
if pickedHeld:
return (speed: 0.0, turnRate: 0.0)
let stepDx = m.commitTarget.x - ws.selfX let stepDx = m.commitTarget.x - ws.selfX
let stepDy = m.commitTarget.y - ws.selfY let stepDy = m.commitTarget.y - ws.selfY
let dist2 = stepDx*stepDx + stepDy*stepDy let dist2 = stepDx*stepDx + stepDy*stepDy
+164
View File
@@ -0,0 +1,164 @@
#!/usr/bin/env python3
"""Ghost-vs-observer probe (j147) — is the 1-tick aura lag a DECISION lag?
For every enemy fire in the recorded event sidecar we locate the ghost our
mover spawned for it (the `[firediag] SPAWN` line) and compare
* WHEN the ghost was spawned (its tick) vs WHEN the enemy fired, and
* WHERE the ghost was drawn vs WHERE the true bullet is at that instant.
Timeline anchoring is done in ABSOLUTE arena coordinates: the bot logs its own
position at the spawn tick, and the capture row carrying that position pins
`captureRow = botTick + k` (a per-round constant = the server's delivery
offset). With k known,
trueBullet(row) = fireOrigin + (row - fireRow) * v (v = 20 - 3*power)
ghost(row) = spawnGhostPos + (row - spawnRow) * v
so both the time lag and the pixel displacement are directly measurable.
"""
import json, math, re, sys, collections
SPAWN_RE = re.compile(
r"SPAWN tick=(\d+) sx=([-\d.eE+]+) sy=([-\d.eE+]+) gx=([-\d.eE+]+) "
r"gy=([-\d.eE+]+) p=([-\d.eE+]+) eta=([-\d.eE+]+)")
def load(arm_dir):
rows = [json.loads(l) for l in open(f"{arm_dir}/run1.jsonl") if '"tick"' in l]
ev = [json.loads(l) for l in open(f"{arm_dir}/run1.events.jsonl") if l.strip()]
rounds = json.load(open(f"{arm_dir}/run1.jsonl.rounds.json"))["rounds"]
spawns = []
for line in open(f"{arm_dir}/run1.bot.stdout.log"):
m = SPAWN_RE.search(line)
if m:
g = [float(x) for x in m.groups()]
spawns.append(dict(tick=int(g[0]), sx=g[1], sy=g[2], gx=g[3], gy=g[4],
p=g[5], eta=g[6]))
return rows, ev, rounds, spawns
def split_rounds(spawns):
"""The bot's tick restarts every round -> segment on a tick decrease."""
out, cur = [], []
for s in spawns:
if cur and s["tick"] <= cur[-1]["tick"]:
out.append(cur); cur = []
cur.append(s)
if cur:
out.append(cur)
return out
def analyse(arm_dir, verbose=True):
rows, ev, rounds, spawns = load(arm_dir)
pos = {r["tick"]: r for r in rows}
starts = {r["round"]: r["startTick"] for r in rounds}
counts = {r["round"]: r["count"] for r in rounds}
# who is the enemy, and which capture row does a fire turn correspond to
votes = collections.Counter()
for e in ev:
if e["type"] != "fire":
continue
gt = starts[e["round"]] + e["tick"]
for off in (-3, -2, -1, 0, 1):
d = pos.get(gt + off)
if not d:
continue
de = math.hypot(d["ex"] - e["x"], d["ey"] - e["y"])
ds = math.hypot(d["sx"] - e["x"], d["sy"] - e["y"])
votes[(e["owner"], "e" if de < ds else "s")] += 1
break
enemy_owner = max(votes.items(), key=lambda kv: kv[1])[0][0]
fires = [e for e in ev if e["type"] == "fire" and e["owner"] == enemy_owner]
by_round = collections.defaultdict(list)
for e in fires:
by_round[e["round"]].append(e)
recs, unmatched = [], 0
chunks = split_rounds(spawns)
# which capture row holds a given position (the bot's own, for the anchor)
where = collections.defaultdict(list)
for r in rows:
where[(round(r["sx"], 3), round(r["sy"], 3))].append(r["tick"])
for chunk in chunks:
for s in chunk:
# TIMELINE, no guessing. MEASURED LIVE (`[firediag] EV hit` lines vs
# the capture's event sidecar, exact matches): the sidecar's per-round
# `tick` IS the server getTurn and the bot runs with
# `getTurn = bot.tick + 1` (j134), so a ghost logged at bot tick `t`
# was placed during server turn `t + 1` of its round. The round is
# found from the bot's OWN logged position (unique per round).
hits = where.get((round(s["sx"], 3), round(s["sy"], 3)), ())
rnd = None
for hrow in hits:
for r_ in rounds:
if r_["startTick"] <= hrow < r_["startTick"] + r_["count"]:
rnd = r_["round"]
break
if rnd is not None:
break
if rnd is None:
unmatched += 1
continue
sturn = s["tick"] + 1
cands = []
for e in by_round[rnd]:
if abs(e["tick"] - sturn) > 2 or abs(e["power"] - s["p"]) > 1e-6:
continue
oerr = math.hypot(s["gx"] - e["x"], s["gy"] - e["y"])
if oerr < 32.0: # the scanned enemy IS the shooter
cands.append((abs(e["tick"] - sturn), oerr, e, e["tick"]))
if not cands:
unmatched += 1
continue
cands.sort()
_, oerr, e, eturn = cands[0]
sp = 20.0 - 3.0 * e["power"]
th = math.radians(e["dir"])
vx, vy = sp * math.cos(th), sp * math.sin(th)
d = sturn - eturn # +ve = ghost spawned LATE
# a bullet takes its FIRST step during the turn it is fired, so at
# the start of server turn `eturn + n` the true bullet sits at
# origin + n * v.
tx, ty = e["x"] + vx * d, e["y"] + vy * d
# arrival deadline: the mover's own eta (logged) vs the true remaining
# flight time to the TRUE bullet from the same reference point.
etaTrue = math.hypot(s["sx"] - tx, s["sy"] - ty) / sp
recs.append(dict(round=rnd, tick=s["tick"], lag=d, power=e["power"],
speed=sp, origin_err=oerr, eta=s["eta"],
err=math.hypot(s["gx"] - tx, s["gy"] - ty),
lagerr=abs(s["eta"] - etaTrue)))
if verbose:
print(f"\n=== {arm_dir}")
print(f"enemy owner id={enemy_owner} spawns={len(spawns)} matched={len(recs)}"
f" unmatched={unmatched}")
if not recs:
return None, []
print("DETECTION LAG (capture row of the spawn - capture row of the fire),"
" +ve = detected LATE:")
for lag, n in sorted(collections.Counter(r["lag"] for r in recs).items()):
print(f" lag={lag:+d} ticks : {n:4d} ({100.0*n/len(recs):5.1f}%)")
errs = sorted(r["err"] for r in recs)
n = len(errs)
print(f"GHOST-vs-TRUTH displacement px: mean={sum(errs)/n:.2f} median={errs[n//2]:.2f}"
f" p90={errs[int(0.9*n)]:.2f} max={errs[-1]:.2f}")
oe = sorted(r["origin_err"] for r in recs)
print(f" of which ghost ORIGIN vs fire origin (the scanned enemy position):"
f" mean={sum(oe)/n:.2f} median={oe[n//2]:.2f} max={oe[-1]:.2f}")
# the pure time part: lag * speed
pure = sorted(abs(r["lag"]) * r["speed"] for r in recs)
print(f"TIME part only (|lag| * speed): mean={sum(pure)/n:.2f} "
f"median={pure[n//2]:.2f} max={pure[-1]:.2f}")
le = sorted(r["lagerr"] for r in recs)
print(f"ARRIVAL-DEADLINE error (mover's eta - the true remaining flight),"
f" ticks: mean={sum(le)/n:.3f} median={le[n//2]:.3f}"
f" p90={le[int(0.9*n)]:.3f} max={le[-1]:.3f}")
return None, recs
if __name__ == "__main__":
for d in sys.argv[1:]:
analyse(d)
@@ -0,0 +1,244 @@
## OFFLINE — j153. THE OWNER'S "HOLD WHEN TRAPPED" — OPEN-LOOP DESCRIPTORS ONLY.
##
## The claim: "if no tile is found to go, to not choose the less dangerous, but
## to stay still! the next tick probably the situation already changed and we
## did not commit to any dangerous place."
##
## This ruler reports FOUR DESCRIPTORS of the RECORDED field around every forced
## pick (the pick the mover makes when the safe set is too small to draw from).
## They are all measured on the recorded trajectory, forward-looking in TIME but
## NOT counterfactual: nothing here replays "what damage would holding have
## cost". Per `docs/offline_harness_trust.md` that question is closed-loop and
## the replay ruler scored 0/6 on such questions, so it is NOT asked here.
##
## 1. WAIT WINDOW — at a forced pick, holding OUR POSITION fixed, how many
## ticks pass before ANY tile inside the reachable hull is safe
## (pathMaxHeat <= PathDangerThreshold, after the CoolestLevels=2 filter)?
## CAVEAT: the safe set depends on where we are, so this holds the pick
## position and replays the field — the recorded field still belongs to a
## bot that moved, so the window is an APPROXIMATION of the wait a holder
## would really see. It is an UPPER bound on the wait (a moving recorded
## bot stirs the field) and it is reported with the censoring share.
## 2. FRESH FIRE — ticks since the enemy's last confirmed shot (energy-drop
## detection, the same signal the mover itself uses).
## 3. OUR OWN TILE — is our current tile already over the threshold at the
## forced pick? (if yes, "stay" is not on the table at all)
## 4. DISTANCE — all of the above split by distance to the nearest enemy.
##
## No battle, no Java, no server, no behaviour change (the knob is off).
##
## Run:
## nim c -r --path:common_libs --nimcache:/tmp/nc_j153 \
## common_libs/tests/measure_tfil_hold_window.nim [fixture.jsonl ...]
import std/[os, strformat, math, algorithm, json, random, sequtils, sets]
import std/strutils except fromHex
import gun_harness/offline_range
include movements/the_floor_is_lava
const PathSampleStep = 18.0 ## the picker's own path sampling step
const MaxWait = 40 ## censor horizon, ticks
const ArenaW = 800.0
const ArenaH = 600.0
type Probe = object
idx: int ## fixture index of the forced pick
x, y, heading, speed: float ## OUR position at the pick (held fixed)
dist: float ## to the nearest enemy at the pick
ownHot: bool ## our own tile already over the threshold
emptySet: bool ## the safe set was EMPTY (0), not merely < 2
sinceFire: int ## ticks since the enemy's last confirmed shot
wait: int ## filled below: -1 = censored
resolved: bool
proc loadRoundStarts(path: string): HashSet[int] =
result = initHashSet[int]()
for side in [path & ".rounds.json",
currentSourcePath().parentDir.parentDir.parentDir /
"tools" / "fixtures" / "drussgt_meta" /
(extractFilename(path) & ".rounds.json")]:
if not fileExists(side): continue
let root = parseFile(side)
if not root.hasKey("rounds"): continue
for r in root["rounds"]:
if r.hasKey("startTick"): result.incl r["startTick"].getInt()
proc pathMax(m: TFILModule, fx, fy, tx, ty: float): float =
let ddx = tx - fx; let ddy = ty - fy
let d = sqrt(ddx*ddx + ddy*ddy)
if d <= 0.1: return 0.0
let steps = max(1, int(d / PathSampleStep))
var h = 0.0
for si in 0..steps:
let f = si.float / steps.float
let (sc, sr) = m.tileAt(fx + ddx * f, fy + ddy * f)
h = max(h, m.lavaAt(sc, sr))
h
proc coolestOf(m: TFILModule, tiles: seq[tuple[col, row: int]]):
seq[tuple[col, row: int]] =
## The picker's CoolestLevels=2 filter: only the coolest 2 DISTINCT lava
## values among the tiles count as candidates at all.
var vals: seq[float]
for t in tiles:
let v = m.lavaAt(t.col, t.row)
var found = false
for dv in vals:
if dv == v: found = true; break
if not found: vals.add v
for i in 1..<vals.len:
let key = vals[i]; var j = i - 1
while j >= 0 and vals[j] > key:
vals[j + 1] = vals[j]; dec j
vals[j + 1] = key
let lv = min(CoolestLevels, vals.len)
for t in tiles:
let v = m.lavaAt(t.col, t.row)
for li in 0..<lv:
if v == vals[li]:
result.add t
break
proc safeCount(m: TFILModule, tiles: seq[tuple[col, row: int]],
fx, fy, thr: float): int =
for t in coolestOf(m, tiles):
let tx = m.marginX + (t.col.float + 0.5) * GridSize
let ty = m.marginY + (t.row.float + 0.5) * GridSize
if pathMax(m, fx, fy, tx, ty) <= thr: inc result
proc safeTileExists(m: TFILModule, p: Probe, thr: float): bool =
## The picker's own definition, from OUR HELD POSITION: inside the reachable
## hull -> CoolestLevels=2 coolest distinct lava values -> path heat filter.
let hull = computeReachableHull(p.x, p.y, p.heading, p.speed,
ArenaW, ArenaH, HullTicks)
if hull.len < 3: return false
var inside: seq[tuple[col, row: int]]
for row in 0..<m.rows:
for col in 0..<m.cols:
let cx = m.marginX + (col.float + 0.5) * GridSize
let cy = m.marginY + (row.float + 0.5) * GridSize
if pointInHull(cx, cy, hull): inside.add (col, row)
safeCount(m, inside, p.x, p.y, thr) > 0
proc nearestEnemyDist(ws: WorldState): float =
result = Inf
for e in ws.enemies:
result = min(result, sqrt((e.x - ws.selfX)^2 + (e.y - ws.selfY)^2))
proc collect(fx: seq[WorldState], starts: HashSet[int], seed: int): seq[Probe] =
randomize(seed)
var m = initTFIL()
var lastPicks = 0
var lastBullets = 0
var sinceFire = 99
for i in 0..<fx.len:
if i == 0 or i in starts: m.resetRound()
discard m.computeMove(fx[i])
if m.bullets.len > lastBullets: sinceFire = 0 else: inc sinceFire
lastBullets = m.bullets.len
if m.picks == lastPicks: continue
lastPicks = m.picks
# a pick happened: was the safe set big enough to draw from?
let safePre = safeCount(m, m.cachedInsideTiles, fx[i].selfX, fx[i].selfY,
TfilDangerThreshold)
if safePre >= 2: continue # not a forced pick
let (cc, cr) = m.tileAt(fx[i].selfX, fx[i].selfY)
result.add Probe(idx: i, x: fx[i].selfX, y: fx[i].selfY,
heading: fx[i].selfHeading, speed: fx[i].selfSpeed,
dist: nearestEnemyDist(fx[i]),
emptySet: safePre == 0,
ownHot: m.lavaAt(cc, cr) > TfilDangerThreshold,
sinceFire: sinceFire, wait: -1)
proc fillWaits(fx: seq[WorldState], starts: HashSet[int], seed: int,
probes: var seq[Probe]) =
## Second linear pass, SAME trajectory: at tick j every still-open probe is
## advanced to k = j - idx and asked whether a safe tile exists at k.
randomize(seed)
var m = initTFIL()
for j in 0..<fx.len:
if j == 0 or j in starts: m.resetRound()
discard m.computeMove(fx[j])
for p in probes.mitems:
if p.resolved: continue
let k = j - p.idx
if k < 1: continue
if k > MaxWait:
p.resolved = true; p.wait = -1; continue
if safeTileExists(m, p, TfilDangerThreshold):
p.resolved = true; p.wait = k
proc mean(xs: seq[int]): float =
if xs.len == 0: return 0.0
var t = 0
for x in xs: t += x
t.float / xs.len.float
proc median(xs: seq[int]): int =
if xs.len == 0: return -1
let s = xs.sorted()
s[s.len div 2]
proc shareN(n, d: int): string =
if d == 0: return "n/a"
&"{100.0 * n.float / d.float:.1f}%"
proc share(n, d: int): string = shareN(n, d)
proc report(label: string, ps: seq[Probe]) =
echo &"\n\u2550\u2550\u2550 {label}"
if ps.len == 0: echo " no forced picks"; return
let waits = ps.filterIt(it.wait >= 0).mapIt(it.wait)
let cens = ps.filterIt(it.wait < 0)
echo &" forced picks: {ps.len} of which EMPTY safe set (0 tiles): " &
&"{shareN(ps.filterIt(it.emptySet).len, ps.len)}"
echo &" WAIT WINDOW (ticks until ANY safe tile exists, position held):"
echo &" median {median(waits)} mean {mean(waits):.1f}" &
&" resolved {waits.len}/{ps.len} censored(>{MaxWait}) {cens.len}"
for k in [1, 3, 5, 10]:
echo &" within {k:>2} tick(s): {share(waits.filterIt(it <= k).len, ps.len)}"
echo &" FRESH FIRE (ticks since the enemy's last confirmed shot):"
echo &" same tick {shareN(ps.filterIt(it.sinceFire == 0).len, ps.len)}" &
&" prev 1 tick {shareN(ps.filterIt(it.sinceFire <= 1).len, ps.len)}" &
&" prev 3 ticks {shareN(ps.filterIt(it.sinceFire <= 3).len, ps.len)}" &
&" >3 ticks {shareN(ps.filterIt(it.sinceFire > 3).len, ps.len)}"
echo &" OUR OWN TILE already over the threshold: " &
&"{shareN(ps.filterIt(it.ownHot).len, ps.len)}"
for (name, lo, hi) in [("close <150px", 0.0, 150.0), ("mid 150-300px", 150.0, 300.0),
("far >300px", 300.0, 1.0e9)]:
let g = ps.filterIt(it.dist >= lo and it.dist < hi)
if g.len == 0:
echo &" {name}: n/a"; continue
let w = g.filterIt(it.wait >= 0).mapIt(it.wait)
echo &" {name}: n={g.len} median wait {median(w)} " &
&"<=3t {share(w.filterIt(it <= 3).len, g.len)} <=10t {share(w.filterIt(it <= 10).len, g.len)}" &
&" fired<=1t ago {shareN(g.filterIt(it.sinceFire <= 1).len, g.len)}" &
&" own tile hot {shareN(g.filterIt(it.ownHot).len, g.len)}"
# ── driver ───────────────────────────────────────────────────────────────────
let args = commandLineParams()
let fixtures = if args.len > 0: args
else: @["/tmp/firelag_live2/tfil_on/run1.jsonl",
"/tmp/firelag_live2/tfil_off/run1.jsonl",
"/tmp/firelag_live2/strafe_on/run1.jsonl",
"/tmp/firelag_live2/strafe_off/run1.jsonl",
currentSourcePath().parentDir.parentDir.parentDir /
"tools" / "fixtures" / "tr_drussgt_vs_modularbot.jsonl",
currentSourcePath().parentDir.parentDir.parentDir /
"tools" / "fixtures" / "tr_drussgt_vs_corners.jsonl",
currentSourcePath().parentDir.parentDir.parentDir /
"tools" / "fixtures" / "tr_drussgt_vs_crazy.jsonl",
currentSourcePath().parentDir.parentDir.parentDir /
"tools" / "fixtures" / "tr_drussgt_vs_spinbot.jsonl"]
var total: seq[Probe]
for f in fixtures:
if not fileExists(f):
echo "skip (missing): ", f; continue
let fx = loadFixture(f).states
let starts = loadRoundStarts(f)
for seed in [7, 8, 9]:
var ps = collect(fx, starts, seed)
fillWaits(fx, starts, seed, ps)
total.add ps
if seed == 7: report(extractFilename(f), ps)
report("ALL FIXTURES x 3 SEEDS", total)
@@ -0,0 +1,291 @@
## OFFLINE — j151. THE OWNER'S TWO PAINTERS, PER PICK.
##
## "the bot choose a tile that is almost perpendicular to it, a tile that is not
## reachable in feasible time and 1 will put the bot in danger trying to go
## there 2 will not arrive there as a new location will drive it away."
##
## This ruler replays recorded fixtures through the REAL
## `TFILModule.computeMove` and records, for EVERY pick:
## turn° angle between the current heading and the chosen tile
## pathMax/Mean lava on the straight-line path bot -> chosen tile
## destHeat lava on the chosen tile itself
## tta dist / MaxSpeed, i.e. ticks to arrive at full speed
## promoted the pick had to break the heat filter (safePre < 2)
## safePre size of the safe set BEFORE the "keep 2" promotion
## hotAtTta the destination tile was OVER the threshold `tta` ticks
## later, on the recorded (true) future <- the feasibility test
## tile the chosen (col,row) <- j152: pick DIVERSITY
## j152: every row of the sweep table also reports the DIVERSITY cost (distinct
## tiles, entropy, top-tile share). j51 measured the randomness in this draw as
## LOAD-BEARING, so a geometry weight that improves the geometry numbers while
## collapsing the distribution is a regression, not a win.
## No battle, no Java, no server, no behaviour change.
##
## Run:
## nim c -r --path:common_libs --nimcache:/tmp/nc_j151 \
## common_libs/tests/measure_tfil_pick_defects.nim [fixture.jsonl ...]
## Env it forwards: TR_TFIL_CORRIDOR_TICKS, TR_TFIL_DANGER_THRESHOLD, ...
import std/[os, strformat, math, algorithm, json, sets, random, sequtils, tables]
import std/strutils except fromHex # `fromHex` would clash with color.fromHex
import gun_harness/offline_range
# Private-field access: include (do NOT import) the shipped mover.
include movements/the_floor_is_lava
const PathSampleStep = 18.0 # the picker's own sampling step
const PerpDeg = 60.0 ## the owner's "perpendicular"
type Pick = object
turn, pathMax, pathMean, destHeat, dist, tta: float
promoted: bool
safePre, cand: int
hotAtTta: bool ## destination over threshold when we would arrive
reached: bool ## we actually got within ArriveRadius by then
col, row: int ## the chosen tile (diversity)
proc loadRoundStarts(path: string): HashSet[int] =
result = initHashSet[int]()
for side in [path & ".rounds.json",
currentSourcePath().parentDir.parentDir.parentDir /
"tools" / "fixtures" / "drussgt_meta" /
(extractFilename(path) & ".rounds.json")]:
if not fileExists(side): continue
let root = parseFile(side)
if not root.hasKey("rounds"): continue
for r in root["rounds"]:
if r.hasKey("startTick"): result.incl r["startTick"].getInt()
proc pathHeat(m: TFILModule, fx, fy, tx, ty: float): tuple[max, mean: float] =
let ddx = tx - fx
let ddy = ty - fy
let lineDist = sqrt(ddx*ddx + ddy*ddy)
if lineDist <= 0.1: return (0.0, 0.0)
let steps = max(1, int(lineDist / PathSampleStep))
var h = 0.0
var s = 0.0
for si in 0..steps:
let frac = si.float / steps.float
let (sc, sr) = m.tileAt(fx + ddx * frac, fy + ddy * frac)
let v = m.lavaAt(sc, sr)
h = max(h, v)
s += v
(h, s / (steps + 1).float)
proc safeSetSize(m: TFILModule, thr: float): int =
## Replay of the picker's own hard filter over the tiles it considered, from
## the same lava snapshot the pick saw. No re-implementation of the choice.
for t in m.cachedInsideTiles:
let tx = m.marginX + (t.col.float + 0.5) * GridSize
let ty = m.marginY + (t.row.float + 0.5) * GridSize
if pathHeat(m, m.lastBotX, m.lastBotY, tx, ty).max <= thr: inc result
proc replay(path: string, seed: int): seq[Pick] =
randomize(seed)
loadTfilCommitEnv()
let fx = loadFixture(path)
let starts = loadRoundStarts(path)
var m = initTFIL()
var lastPicks = 0
var pending: seq[tuple[col, row: int; at: int; idx: int]]
var mActive = 0
for si in 0..<fx.states.len:
if si == 0 or si in starts: m.resetRound()
discard m.computeMove(fx.states[si])
inc mActive
# 1. a new pick happened this tick -> record the geometry
if m.picks != lastPicks:
lastPicks = m.picks
let (cc, cr) = m.tileAt(m.commitTarget.x, m.commitTarget.y)
let ang = arctan2(m.commitTarget.y - m.lastBotY, m.commitTarget.x - m.lastBotX) *
180.0 / PI - fx.states[si].selfHeading
var turn = abs(((ang + 180.0) mod 360.0) - 180.0)
if turn > 180.0: turn = 360.0 - turn
let d = sqrt((m.commitTarget.x - m.lastBotX)^2 + (m.commitTarget.y - m.lastBotY)^2)
let (pmx, pmean) = pathHeat(m, m.lastBotX, m.lastBotY, m.commitTarget.x, m.commitTarget.y)
result.add Pick(turn: turn, pathMax: pmx, pathMean: pmean,
destHeat: m.lavaAt(cc, cr), dist: d, tta: d / MaxSpeed,
promoted: m.lastPickPromoted,
safePre: safeSetSize(m, TfilDangerThreshold),
cand: m.lastPickSafe, hotAtTta: false, reached: false,
col: cc, row: cr)
pending.add (col: cc, row: cr, at: mActive + int(d / MaxSpeed), idx: result.high)
# 2. the arrival probe on the recorded true future
var keep: seq[tuple[col, row: int; at: int; idx: int]]
for p in pending:
if mActive < p.at:
keep.add p
else:
result[p.idx].hotAtTta = m.lavaAt(p.col, p.row) > TfilDangerThreshold
let px = m.marginX + (p.col.float + 0.5) * GridSize
let py = m.marginY + (p.row.float + 0.5) * GridSize
result[p.idx].reached = sqrt((m.lastBotX - px)^2 + (m.lastBotY - py)^2) < ArriveRadius
pending = keep
proc mean(x: seq[float]): float =
if x.len == 0: return 0.0
var s = 0.0
for v in x: s += v
s / x.len.float
proc pc(x: float): string = &"{100.0 * x:.1f}%"
proc f1(x: float): string = &"{x:.1f}"
proc f2(x: float): string = &"{x:.2f}"
proc report(label, path: string, picks: seq[Pick]) =
echo &"\n\u2550\u2550\u2550 {label} {extractFilename(path)}"
if picks.len == 0: echo " no picks"; return
let thr = TfilDangerThreshold
var groups = [("EMPTY safe set (promoted)", picks.filterIt(it.promoted)),
("non-empty safe set", picks.filterIt(not it.promoted))]
var allPerp, allHot, allFar, allBad = 0
for (name, g) in groups:
let perp = g.filterIt(it.turn > PerpDeg)
let hot = g.filterIt(it.pathMax > thr) # crosses a hot region
let far = g.filterIt(it.tta > CommitTicks.float) # cannot arrive in the commitment
let bad = g.filterIt(it.turn > PerpDeg and it.pathMax > thr)
let badFar = g.filterIt(it.turn > PerpDeg and it.tta > CommitTicks.float)
let futHot = g.filterIt(it.hotAtTta)
let reach = g.filterIt(it.reached)
echo &" {name}: {g.len} picks ({pc(g.len.float/picks.len.float)} of all)"
if g.len == 0: continue
echo &" PERPENDICULAR (>60\u00b0) {perp.len:>6} {pc(perp.len.float/g.len.float):>7}" &
&" mean pathMax {f1(mean(perp.mapIt(it.pathMax)))}"
echo &" path crosses HOT {hot.len:>6} {pc(hot.len.float/g.len.float):>7}" &
&" mean pathMax(all) {f1(mean(g.mapIt(it.pathMax)))} destHeat {f1(mean(g.mapIt(it.destHeat)))}"
echo &" tta > commit({CommitTicks}) {far.len:>6} {pc(far.len.float/g.len.float):>7}" &
&" mean tta {f1(mean(g.mapIt(it.tta)))} max {f1(g.mapIt(it.tta).max)}"
echo &" PERP + hot {bad.len:>6} | PERP + far {badFar.len:>6}"
echo &" dest HOT when we arrive {futHot.len:>6} {pc(futHot.len.float/g.len.float):>7}" &
&" | actually arrived {pc(reach.len.float/g.len.float):>7}"
echo &" mean turn {f1(mean(g.mapIt(it.turn)))}\u00b0 mean safePre {f1(mean(g.mapIt(it.safePre.float)))}" &
&" mean cand {f1(mean(g.mapIt(it.cand.float)))}"
allPerp += perp.len; allHot += hot.len; allFar += far.len
allBad += bad.len + badFar.len
echo &" ALL: perp {pc(allPerp.float/picks.len.float)} hot-path {pc(allHot.float/picks.len.float)}" &
&" far {pc(allFar.float/picks.len.float)} (perp&(hot|far)) {pc(allBad.float/picks.len.float)}"
# ── driver ───────────────────────────────────────────────────────────────────
let args = commandLineParams()
let detail = "--detail" in args
let fixtures: seq[string] =
block:
if detail:
var v: seq[string]
for a in args:
if not a.startsWith("--"): v.add a
v
else:
@["/tmp/firelag_live2/tfil_on/run1.jsonl",
"/tmp/firelag_live2/tfil_off/run1.jsonl",
"/tmp/firelag_live2/strafe_on/run1.jsonl",
"/tmp/firelag_live2/strafe_off/run1.jsonl",
currentSourcePath().parentDir.parentDir.parentDir /
"tools" / "fixtures" / "tr_drussgt_vs_modularbot.jsonl",
currentSourcePath().parentDir.parentDir.parentDir /
"tools" / "fixtures" / "tr_drussgt_vs_corners.jsonl",
currentSourcePath().parentDir.parentDir.parentDir /
"tools" / "fixtures" / "tr_drussgt_vs_crazy.jsonl",
currentSourcePath().parentDir.parentDir.parentDir /
"tools" / "fixtures" / "tr_drussgt_vs_spinbot.jsonl"]
# ── j152: the sweep, with the DIVERSITY cost on every row ────────────────────
## (label, TR_TFIL_GEO_MODE, TR_TFIL_GEO_TAU, TR_TFIL_ARRIVE_TICKS)
type Arm = tuple[label, mode, tau, arrive: string]
proc diversity(picks: seq[Pick]): tuple[distinctN, topShare, entBits, normEnt: float] =
## Shannon entropy (bits) of the CHOICE distribution over tiles. `normEnt` is
## H / log2(distinct): 1.0 = the arm spreads its picks over exactly as many
## tiles as the baseline, 0.0 = every pick is the same tile.
var counts: Table[(int, int), int]
for p in picks: counts[(p.col, p.row)] = counts.getOrDefault((p.col, p.row)) + 1
result.distinctN = counts.len.float
if picks.len == 0: return
var h = 0.0
var top = 0
for _, n in counts.pairs:
let q = n.float / picks.len.float
h -= q * log2(q)
top = max(top, n)
result.topShare = top.float / picks.len.float
result.entBits = h
result.normEnt = if result.distinctN > 1.0: h / log2(result.distinctN) else: 0.0
proc pctS(x, n: int): string =
if n == 0: return " n/a"
pc(x.float / n.float)
proc isPerp(p: Pick): bool = p.turn > PerpDeg
proc isPromoted(p: Pick): bool = p.promoted
proc isFar(p: Pick): bool = p.tta > 15.0
proc isReached(p: Pick): bool = p.reached
proc isHotAtTta(p: Pick): bool = p.hotAtTta
proc row(label: string, picks: seq[Pick]): string =
let n = picks.len
let emp = picks.filterIt(isPromoted(it))
let nes = picks.filterIt(not isPromoted(it))
let perp = picks.filterIt(isPerp(it)).len
let perpE = emp.filterIt(isPerp(it)).len
let perpN = nes.filterIt(isPerp(it)).len
let far = picks.filterIt(isFar(it)).len
let reach = picks.filterIt(isReached(it)).len
let hot = picks.filterIt(isHotAtTta(it)).len
let d = diversity(picks)
&"{label:<22} {pctS(perp, n):>7} {pctS(perpE, emp.len):>7} {pctS(perpN, nes.len):>7}" &
&" {pctS(far, n):>7} {f1(mean(picks.mapIt(it.tta))):>6}" &
&" {pctS(reach, n):>7} {pctS(hot, n):>7} {pctS(emp.len, n):>7}" &
&" {d.distinctN.int:>6} {f2(d.entBits):>6} {f2(d.normEnt):>6} {pc(d.topShare):>7}" &
&" {f1(mean(picks.mapIt(it.cand.float))):>5}"
proc header(): string =
result = "arm".align(22, ' ')
for (h, w) in [("perp", 7), ("perpE", 7), ("perpN", 7), ("far", 7), ("mtta", 6),
("REACH", 7), ("hotArr", 7), ("empty", 7), ("tiles", 6),
("Hbits", 6), ("H/", 6), ("top1", 7), ("cand", 5)]:
result &= " " & h.align(w, ' ')
# `perpE`/`perpN` = the perpendicular rate in the FORCED (empty safe set) and the
# non-empty populations; `REACH` = the headline (tile actually stood on at tta);
# `tiles`/`Hbits`/`H/`/`top1` = the diversity cost; `cand` = mean draw-set size.
let arms: seq[Arm] = @[
("BASELINE (off)", "off", "0", "0"),
("turn-soft tau90", "turn-soft", "90", "0"),
("turn-soft tau45", "turn-soft", "45", "0"),
("turn-soft tau20", "turn-soft", "20", "0"),
("turn-topk", "turn-topk", "45", "0"),
("turn-rej tau60", "turn-rej", "60", "0"),
("dist-soft tau90", "dist-soft", "90", "0"),
("dist-soft tau30", "dist-soft", "30", "0"),
("both-soft tau90", "both-soft", "90", "0"),
("both-soft tau45", "both-soft", "45", "0"),
("both-soft tau20", "both-soft", "20", "0"),
("both-topk", "both-topk", "45", "0"),
("both-rej tau60", "both-rej", "60", "0"),
# j151 interaction: a soft distance preference vs the HARD arrival bound.
("arrive15 (j151)", "off", "0", "15"),
("arrive15+both t45", "both-soft", "45", "15")]
echo "\n", header()
for a in arms:
putEnv("TR_TFIL_GEO_MODE", a.mode)
putEnv("TR_TFIL_GEO_TAU", a.tau)
putEnv("TR_TFIL_ARRIVE_TICKS", a.arrive)
var picks: seq[Pick]
for f in fixtures:
if not fileExists(f): continue
for seed in [7, 8, 9]: picks.add replay(f, seed)
echo row(a.label, picks)
# ── per-fixture detail (--detail only), for the BASELINE arm ────────────────
if detail:
putEnv("TR_TFIL_GEO_MODE", arms[0].mode)
putEnv("TR_TFIL_GEO_TAU", arms[0].tau)
putEnv("TR_TFIL_ARRIVE_TICKS", arms[0].arrive)
var total: seq[Pick]
for f in fixtures:
if not fileExists(f):
echo "skip (missing): ", f; continue
for seed in [7, 8, 9]:
let p = replay(f, seed)
total.add p
if seed == 7: report("seed 7", f, p)
report("ALL FIXTURES x 3 SEEDS", "", total)
@@ -0,0 +1,118 @@
## OFFLINE — j150. WHERE DOES THE LAVA PICKER LOSE ITS TILES?
##
## The owner's report: "the bot chooses only between a poor number of tiles while
## there are a lot of them available but not considered". This ruler drives the
## REAL `TFILModule.computeMove` (with `TR_TFIL_DIAG=1`) over recorded
## DrussGT fixtures and reads the per-pick loss histogram the mover counts:
##
## reachable hull -> CoolestLevels(=2) distinct-lava filter
## -> pathMaxHeat <= PathDangerThreshold -> draw set -> CHOSEN
##
## No battle, no Java, no server, no behaviour change: every knob it moves is
## default-off or default-identical.
##
## Run:
## nim c -r --path:common_libs --nimcache:/tmp/nc_j150 \
## common_libs/tests/measure_tfil_picker_loss.nim [fixture.jsonl ...]
import std/[os, strformat, math, algorithm, json, sets, sequtils]
import std/strutils except fromHex # `fromHex` would clash with color.fromHex
import gun_harness/offline_range
# Private-field access: include (do NOT import) the shipped mover.
include movements/the_floor_is_lava
proc loadRoundStarts(fixturePath: string): HashSet[int] =
result = initHashSet[int]()
let side = currentSourcePath().parentDir.parentDir.parentDir /
"tools" / "fixtures" / "drussgt_meta" /
(extractFilename(fixturePath) & ".rounds.json")
if not fileExists(side): return
let root = parseFile(side)
if not root.hasKey("rounds"): return
for r in root["rounds"]:
if r.hasKey("startTick"): result.incl r["startTick"].getInt()
proc replay(path: string, threshold: float): TfilLossStats =
putEnv("TR_TFIL_DIAG", "1")
putEnv("TR_TFIL_DANGER_THRESHOLD", $threshold)
loadTfilCommitEnv()
TfilLoss = TfilLossStats()
let fx = loadFixture(path)
let starts = loadRoundStarts(path)
var m = initTFIL()
for si in 0..<fx.states.len:
if si == 0 or si in starts: m.resetRound()
discard m.computeMove(fx.states[si])
result = TfilLoss
proc mean(x: seq[float]): float =
if x.len == 0: return 0.0
var s = 0.0
for v in x: s += v
s / x.len.float
proc pctStr(x: float): string = &"{100.0 * x:.1f}%"
proc f2(x: float): string = &"{x:.2f}"
const SafeBuckets = ["0", "1", "2-3", "4-7", "8-15", "16-31", "32-63", "64+"]
proc heatTally(x: seq[float]): seq[(float, int)] =
## distinct heat values -> how many rejected tiles carried it, most common
## first. Lava is a sum of quantised terms, so this shows the real steps.
var counts: seq[(float, int)]
for v in x:
var i = 0
while i < counts.len and counts[i][0] != v: inc i
if i < counts.len: inc counts[i][1]
else: counts.add (v, 1)
result = counts
result.sort(proc (a, b: (float, int)): int = cmp(b[1], a[1]))
proc report(path: string) =
let s = replay(path, 10.0)
echo &"\n\u2550\u2550\u2550 {path}"
if s.picks == 0:
echo " no picks"; return
let n = s.picks.float
echo &" picks = {s.picks} (replayed ticks, one recorded battle, seed fixed)"
echo &" stage mean tiles"
echo &" 1 reachable-hull tiles {s.sReach.float/n:>12.2f}"
echo &" 2 .. after CoolestLevels=2 filter {s.sCool.float/n:>12.2f}"
echo &" 3 .. after path heat filter (pre-prom) {s.sSafe.float/n:>12.2f}"
echo &" 4 .. draw set (what it chooses among) {s.sCand.float/n:>12.2f}"
echo &" LOST at the 2-levels filter {(1.0 - s.sCool.float/s.sReach.float)*100:>11.1f}%"
echo &" LOST at the heat filter {(1.0 - s.sSafe.float/max(1.0,s.sCool.float))*100:>11.1f}%"
echo &" LOST at blocked-tile / no-rev {(1.0 - s.sCand.float/max(1.0,s.sSafe.float))*100:>11.1f}%"
echo &" picks with an EMPTY safe set (<2 at stage 3) = {s.emptySafe} ({pctStr(s.emptySafe.float/n)})"
echo " safe-set size distribution (stage 3):"
for i in 0..<SafeBuckets.len:
if s.safeHist[i] > 0:
echo &" {SafeBuckets[i].alignLeft(6)} {s.safeHist[i]:>7} ({pctStr(s.safeHist[i].float/n)})"
# heat of the tiles the filter dropped
echo &" heat of the {s.rejectedHeat.len} REJECTED tiles (mean {f2(mean(s.rejectedHeat))}), most common first:"
for (v, c) in heatTally(s.rejectedHeat)[0 ..< min(8, s.rejectedHeat.len)]:
echo &" heat {f2(v):>7} {c:>7} ({pctStr(c.float/s.rejectedHeat.len.float)})"
echo &" heat of ADMITTED tiles mean {f2(mean(s.admittedHeat))} (n={s.admittedHeat.len}); " &
&"of CHOSEN mean {f2(mean(s.chosenHeat))} (n={s.chosenHeat.len})"
# \u2550\u2550 threshold sweep
echo " threshold mean draw set % empty safe newly admitted (n, mean heat) mean heat chosen"
var baseAdmitted = replay(path, 10.0).admittedHeat.len
for thr in [10.0, 14.0, 18.0]:
let a = replay(path, thr)
let newly = a.admittedHeat.filterIt(it > 10.0)
let newTxt = $newly.len & ", " & f2(mean(newly))
echo &" {thr:>9.0f} {a.sCand.float / a.picks.float:>13.2f} " &
&"{pctStr(a.emptySafe.float / a.picks.float):>12} {newTxt:>30} {f2(mean(a.chosenHeat)):>16}"
echo &" (admitted at threshold 10: {baseAdmitted} tiles)"
# ── driver ───────────────────────────────────────────────────────────────────
let args = commandLineParams()
let fixtures = if args.len > 0: args
else: @[currentSourcePath().parentDir.parentDir.parentDir /
"tools" / "fixtures" / "tr_drussgt_vs_modularbot.jsonl"]
for f in fixtures:
if fileExists(f): report(f)
else: echo "skip (missing): ", f
+638 -1
View File
@@ -37,7 +37,7 @@
## A/B whose treatment did not apply is worthless) and that the soft ## A/B whose treatment did not apply is worthless) and that the soft
## no-reversal preference can never empty the candidate pool. ## no-reversal preference can never empty the candidate pool.
import std/[os, json, random, math, sequtils] import std/[os, json, random, math, sequtils, sets]
import std/strutils except fromHex # `fromHex` would clash with color.fromHex import std/strutils except fromHex # `fromHex` would clash with color.fromHex
import gun_harness/gun_interface import gun_harness/gun_interface
# Private-field access: include (do NOT import) the shipped mover. # Private-field access: include (do NOT import) the shipped mover.
@@ -848,6 +848,637 @@ when declared(loadTfilCommitEnv):
" mean path heat=", meanPathHeat(s).formatFloat(ffDecimal, 2), " mean path heat=", meanPathHeat(s).formatFloat(ffDecimal, 2),
" >90deg=", pct(s.bigTurn, s.picks) " >90deg=", pct(s.bigTurn, s.picks)
## j147: TR_FIRE_LAG back-dates the ghost by the MEASURED detection lag (1
## tick live: 1777/1777 matched spawns, `measure_fire_ghost_lag.py`). Default
## 0 must be byte-for-byte today's spawn, and lag=n must move the ghost exactly
## n bullet steps downrange — which is what shortens the arrival deadline,
## because every mover derives the deadline from the ghost's own position.
proc testJ147() =
let ws = WorldState(enemyX: 0.0, enemyY: 0.0, enemyHeading: 0.0,
enemySpeed: 0.0, enemyEnergy: 100.0,
selfX: 400.0, selfY: 320.0, selfHeading: 0.0,
selfSpeed: 0.0, selfEnergy: 100.0,
arenaWidth: ArenaW, arenaHeight: ArenaH, tick: 1,
enemies: @[])
let ei = EnemyInfo(id: 1, x: 200.0, y: 320.0, heading: 0.0,
speed: 0.0, energy: 100.0)
const Power = 1.0
let speed = 20.0 - 3.0 * Power # 17 px/tick
proc spawnGhost(): TrackedBullet =
var m = initTFIL()
discard m.computeMove(ws) # initGrid
m.spawnTrackedWave(ws, ei, Power)
m.bullets[^1]
# 1. default parity: unset -> 0, and the ghost is EXACTLY the scanned origin
delEnv("TR_FIRE_LAG")
loadFireTrackerEnv()
check "j147: TR_FIRE_LAG unset -> FireLag 0", FireLag == 0
let g0 = spawnGhost()
check "j147: default (lag 0) puts the ghost exactly on the scanned enemy",
g0.x == ei.x and g0.y == ei.y
# 2. lag 1 back-dates by EXACTLY one bullet step, on the ghost's own heading
putEnv("TR_FIRE_LAG", "1")
loadFireTrackerEnv()
let g1 = spawnGhost()
check "j147: TR_FIRE_LAG=1 places the ghost one bullet step downrange",
FireLag == 1 and
abs((g1.x - g0.x) - g1.velX) < 1e-9 and
abs((g1.y - g0.y) - g1.velY) < 1e-9
check "j147: ... and that step is the true bullet speed, not a scaled one",
abs(sqrt(g1.velX * g1.velX + g1.velY * g1.velY) - speed) < 1e-9
# 3. the ARRIVAL DEADLINE shortens by exactly `lag` ticks. The mover's own
# arrival proxy is dist(self, ghost) / speed (tfil `heatDecay(along/speed)`,
# the `dot < 0` reap); the true bullet is one step further along.
let etaGhost = sqrt((ws.selfX - g1.x)^2 + (ws.selfY - g1.y)^2) /
sqrt(g1.velX * g1.velX + g1.velY * g1.velY)
let etaTrue0 = sqrt((ws.selfX - g0.x)^2 + (ws.selfY - g0.y)^2) / speed
let etaTrue1 = sqrt((ws.selfX - (g0.x + g0.velX))^2 +
(ws.selfY - (g0.y + g0.velY))^2) / speed
check "j147: with lag=1 the mover's deadline equals the TRUE remaining " &
"flight (" & etaGhost.formatFloat(ffDecimal, 6) & " vs " &
etaTrue1.formatFloat(ffDecimal, 6) & "), the lag-0 deadline being " &
etaTrue0.formatFloat(ffDecimal, 6) & " — a full tick late",
abs(etaGhost - etaTrue1) < 1e-9 and
abs((etaTrue0 - etaTrue1) - 1.0) < 1e-9
# 4. lag n is n steps, and n=2 shortens the deadline by exactly 2
putEnv("TR_FIRE_LAG", "2")
loadFireTrackerEnv()
let g2 = spawnGhost()
check "j147: TR_FIRE_LAG=2 back-dates by two steps",
abs((g2.x - g0.x) - 2.0 * g0.velX) < 1e-9 and
abs((g2.y - g0.y) - 2.0 * g0.velY) < 1e-9
let etaTrue2 = sqrt((ws.selfX - (g0.x + 2.0 * g0.velX))^2 +
(ws.selfY - (g0.y + 2.0 * g0.velY))^2) / speed
check "j147: ... so the deadline shortens by exactly 2 ticks",
abs((etaTrue0 - etaTrue2) - 2.0) < 1e-9
# 5. a junk value falls back to 0, never to a negative/garbage back-date
putEnv("TR_FIRE_LAG", "junk")
loadFireTrackerEnv()
let gj = spawnGhost()
putEnv("TR_FIRE_LAG", "-4")
loadFireTrackerEnv()
let gn = spawnGhost()
check "j147: a junk / negative TR_FIRE_LAG degrades to the shipped lag 0",
FireLag == 0 and gj.x == ei.x and gn.x == ei.x
# 6. the ARRIVAL DEADLINE end-to-end: the ghost is reaped (`dot < 0`, the
# geometric arrival) exactly `lag` ticks earlier, because it is `lag`
# steps further along. This is the deadline the decision actually uses.
proc ticksToReap(): int =
var m = initTFIL()
randomize(Seed)
discard m.computeMove(ws)
m.spawnTrackedWave(ws, ei, Power)
for t in 1..80:
discard m.computeMove(ws)
if m.bullets.len == 0: return t
99
putEnv("TR_FIRE_LAG", "0")
loadFireTrackerEnv()
let reap0 = ticksToReap()
putEnv("TR_FIRE_LAG", "1")
loadFireTrackerEnv()
let reap1 = ticksToReap()
check "j147: the ghost arrives — and is reaped — exactly 1 tick earlier " &
"with the back-date (" & $reap0 & " -> " & $reap1 & " ticks)",
reap0 > 0 and reap1 > 0 and reap0 - reap1 == 1
# 7. restore the shipped default for every later check in this process
delEnv("TR_FIRE_LAG")
loadFireTrackerEnv()
check "j147: clearing the knob restores the shipped spawn exactly",
FireLag == 0 and spawnGhost().x == ei.x
# ── j150: the picker loss-histogram diag + the sweepable heat cutoff ──────────
#
# TR_TFIL_DIAG 0/1 default 0 — fill TfilLoss* only
# TR_TFIL_DANGER_THRESHOLD (float) default 10 — was a proc-local `const`
#
# Both must be default-off-effect: the whole point of the diag is to measure
# the shipped picker, not to change it.
proc testJ150() =
delEnv("TR_TFIL_DIAG"); delEnv("TR_TFIL_DANGER_THRESHOLD")
loadTfilCommitEnv()
check "j150: TR_TFIL_DIAG defaults OFF and TR_TFIL_DANGER_THRESHOLD defaults " &
"to today's 10.0", (not TfilDiag) and TfilDangerThreshold == 10.0
# 1. the diag is PURE: identical move stream with it on and off
let off = replay(loadStates(), loadRoundStarts())
putEnv("TR_TFIL_DIAG", "1")
loadTfilCommitEnv()
let on = replay(loadStates(), loadRoundStarts())
var diff = -1
if off.len != on.len: diff = min(off.len, on.len)
else:
for i in 0..<off.len:
if recLine(off[i]) != recLine(on[i]): diff = i; break
check "j150: with TR_TFIL_DIAG=1 the move stream is BYTE-FOR-BYTE the " &
"diag-off one over " & $off.len & " ticks — the counters are inert",
diff < 0
# 2. the histogram is populated and its stage chain is monotone
let st = TfilLoss # kept: step 4 clears the live counter
check "j150: the histogram counted picks (" & $st.picks & ") and every " &
"stage is non-increasing (reach >= cool-filter >= heat-filter)",
st.picks > 0 and st.sReach >= st.sCool and
st.sCool >= st.sSafe and st.sSafe <= st.sCand and
st.safeHist[0] <= st.picks
# 3. knob parsing, including the fallbacks
putEnv("TR_TFIL_DANGER_THRESHOLD", "18")
loadTfilCommitEnv()
check "j150: TR_TFIL_DANGER_THRESHOLD=18 is read", TfilDangerThreshold == 18.0
putEnv("TR_TFIL_DANGER_THRESHOLD", "junk")
loadTfilCommitEnv()
check "j150: a malformed value falls back to the DEFAULT 10.0",
TfilDangerThreshold == 10.0
putEnv("TR_TFIL_DANGER_THRESHOLD", "-4")
loadTfilCommitEnv()
check "j150: a negative value clamps to 0 (heat can never go backwards)",
TfilDangerThreshold == 0.0
# 4. restore the shipped default for every later check in this process
putEnv("TR_TFIL_DIAG", ""); putEnv("TR_TFIL_DANGER_THRESHOLD", "")
loadTfilCommitEnv()
check "j150: clearing the knobs restores 10.0 / diag off",
(not TfilDiag) and TfilDangerThreshold == 10.0 and TfilLoss.picks == 0
echo "\n j150 picker loss histogram (default build, offline fixture replay):"
echo " picks=", st.picks
let np = st.picks.float
echo " mean reachable hull tiles=", st.sReach.float / np
echo " mean after CoolestLevels=2 filter=", st.sCool.float / np
echo " mean after the heat filter (pre-promotion)=", st.sSafe.float / np
echo " mean draw set=", st.sCand.float / np
# ── j151: the ARRIVAL bound (TR_TFIL_ARRIVE_TICKS, default 0 = off) ─────────
type ArrStats = object
picks, beyond, starved: int ## starved = picks made with an empty pool
meanTta, meanPool: float
proc replayJ151(bound: float): ArrStats =
putEnv("TR_TFIL_ARRIVE_TICKS", $bound)
loadTfilCommitEnv()
let states = loadStates()
let starts = loadRoundStarts()
randomize(Seed)
var m = initTFIL()
var lastPicks = 0
for i in 0..<states.len:
if i == 0 or i in starts: m.resetRound()
discard m.computeMove(states[i])
if m.picks != lastPicks:
lastPicks = m.picks
let tta = sqrt((m.commitTarget.x - states[i].selfX)^2 +
(m.commitTarget.y - states[i].selfY)^2) / MaxSpeed
inc result.picks
if tta > TfilArriveTicks + 0.001: inc result.beyond
if m.lastPickSafe == 0: inc result.starved
result.meanTta += tta
result.meanPool += m.lastPickSafe.float
if result.picks > 0:
result.meanTta /= result.picks.float
result.meanPool /= result.picks.float
proc testJ151() =
# 8a. the shipped default is OFF — the golden parity check above is the proof
delEnv("TR_TFIL_ARRIVE_TICKS")
loadTfilCommitEnv()
check "j151: the arrival bound defaults to OFF (today's uniform draw over " &
"the whole 50-tick hull)", TfilArriveTicks == 0.0
let off = replayJ151(0.0) # today's behaviour, same seed
let on15 = replayJ151(15.0) # = CommitTicks: the horizon we hold a target for
delEnv("TR_TFIL_ARRIVE_TICKS")
loadTfilCommitEnv()
# the CEILING, stated: the bound is a filter on the SAFE set, so a tick whose
# every safe tile is past the horizon keeps the full pool (never starved) —
# those picks stay long, and the guard below measures exactly how many.
check "j151: picks past the 15-tick horizon collapse (" & $off.beyond & "/" &
$off.picks & " -> " & $on15.beyond & "/" & $on15.picks & "); the " &
"residue is the all-safe-tiles-are-far ticks, which keep the full pool",
on15.beyond < off.beyond div 2 and off.beyond > 0
check "j151: the mean time-to-arrive falls (" &
off.meanTta.formatFloat(ffDecimal, 1) & " -> " &
on15.meanTta.formatFloat(ffDecimal, 1) & " ticks) and the pool is " &
"not starved (mean safe tiles " &
on15.meanPool.formatFloat(ffDecimal, 1) & ", " & $on15.starved &
" empty pools)",
on15.meanTta < off.meanTta and on15.meanPool >= 1.0 and on15.starved == 0
check "j151: the bound is a filter, not a replacement — the pick COUNT is " &
"barely reduced (" & $off.picks & " -> " & $on15.picks & ")",
on15.picks.float > off.picks.float * 0.9
check "j151: clearing the knob restores today's pick stream exactly",
replayJ151(0.0).picks == off.picks
# ── j152: the GEOMETRIC DRAW (TR_TFIL_GEO_MODE / TR_TFIL_GEO_TAU, default off) ─
## Heat still gates the pool with the same hard filter; geometry only re-weights
## the survivors of that filter — INCLUDING the 2 promoted least-hot tiles the
## ~65% forced picks choose from, which is what j9 (`TR_TFIL_TURN_BIAS`) could
## not see. What must hold:
## 1. OFF by default and the OFF path is today's uniform draw byte-for-byte
## (the golden check #1 above runs with the knobs unset and is that proof;
## the last check here adds "off" == "unset" for the same seed).
## 2. NO STARVATION: a pool in which EVERY tile is perpendicular still returns
## a pick, in every form — the weight may never empty or index past the
## pool, whatever the TAU.
## 3. `off` and an all-ties pool both degenerate to the uniform draw.
## 4. The form is parsed, and junk stays off.
proc testJ152() =
delEnv("TR_TFIL_GEO_MODE"); delEnv("TR_TFIL_GEO_TAU")
loadTfilCommitEnv()
check "j152: both geometry knobs default to OFF (today's uniform draw)",
TfilGeoMode == gdoOff and TfilGeoTau == 0.0
check "j152: the mode string parses both axes (dim + form)",
parseGeo("both-rej") == (gdoBoth, gfRej) and
parseGeo("turn-topk") == (gdoTurn, gfTopK) and
parseGeo("dist-soft") == (gdoDist, gfSoft) and
parseGeo("turn") == (gdoTurn, gfSoft)
check "j152: junk and 'off' both parse to OFF, never to a live arm",
parseGeo("off").dim == gdoOff and parseGeo("sideways").dim == gdoOff
# 2. NO STARVATION: a pool where EVERY tile is 150 deg off the heading, at
# three different distances. No form may return an index outside the pool.
randomize(1)
let allPerpT = @[150.0, 150.0, 150.0]
let allPerpD = @[2.0, 30.0, 48.0]
for form in [gfSoft, gfTopK, gfRej]:
for tau in [1.0, 20.0, 5000.0]:
var seen: seq[int]
for _ in 0..<300:
seen.add geoPick(allPerpT, allPerpD, gdoTurn, form, tau)
# NO STARVATION = a pick always exists and is in range. It is NOT "every
# tile stays reachable": topk and rej are hard forms BY DESIGN and may
# legitimately return one tile forever when the whole pool is bad.
check "j152: no starvation — an all-perpendicular pool still returns " &
"an in-range pick (" & $form & ", tau " & $tau & ")",
seen.len == 300 and seen.allIt(it in 0..2)
# 3. every tile costs the same => every weight ties => the uniform draw
randomize(2)
var tieSeen: seq[int]
for _ in 0..<300:
tieSeen.add geoPick(@[40.0, 40.0, 40.0], @[10.0, 10.0, 10.0], gdoTurn, gfSoft, 45.0)
check "j152: an all-ties pool degenerates to the uniform draw (all 3 seen, " &
"none starved)", tieSeen.toHashSet().len == 3
var hitFar = 0
randomize(3)
for _ in 0..<400:
if geoPick(@[0.0, 180.0], @[1.0, 1.0], gdoTurn, gfSoft, 10.0) == 0: inc hitFar
check "j152: the soft form really tilts (a straight-ahead tile is drawn " &
">" & $hitFar & "/400 of the time with tau=10)", hitFar > 300
# 4. "off" == "unset" for the same seed: the shipped stream, unchanged.
let a = replayJ151(0.0)
delEnv("TR_TFIL_GEO_MODE"); delEnv("TR_TFIL_GEO_TAU")
loadTfilCommitEnv()
let b = replayJ151(0.0)
check "j152: geometry off reproduces the shipped draw exactly (same picks, " &
"same mean tta, same pool)", a.picks == b.picks and
a.meanTta == b.meanTta and a.meanPool == b.meanPool
# ── j153: HOLD WHEN TRAPPED (TR_TFIL_HOLD_WHEN_TRAPPED, default 0 = off) ────
## The owner's rule: "if no tile is found to go, to not choose the less
## dangerous, but to stay still! the next tick probably the situation already
## changed and we did not commit to any dangerous place."
## What must hold, and nothing more:
## 1. OFF by default, and the OFF stream is byte-for-byte today's (the golden
## check #1 above already proves the default path; this adds the explicit
## "unset == 0 == 1-off-by-parsing" arm).
## 2. ON + EMPTY safe set => no movement command for that tick.
## 3. The hold is ONE tick: it never latches, and a later safe tile IS taken
## (no stuck bot, no held-then-forever-silent).
## 4. Holding does not skip the rest of the tick: the bullet tracking the GUN
## and the lava field are updated exactly as on a non-held tick. (The gun
## itself lives in the bot loop, not in this module — computeMove never
## emits a fire command — so the real risk is a hold that `return`s too
## early and freezes the bullet tracker; that is what this checks.)
type HoldRec = object
call: int
spd, trn: float
held: bool
picked: bool
bullets: int ## tracked bullets after this tick (the fire tracker's)
proc replayJ153(hold: bool): seq[HoldRec] =
putEnv("TR_TFIL_HOLD_WHEN_TRAPPED", (if hold: "1" else: "0"))
loadTfilCommitEnv()
let states = loadStates()
let starts = loadRoundStarts()
randomize(Seed)
var m = initTFIL()
var lastPicks = 0
for i in 0..<states.len:
if i == 0 or i in starts:
m.resetRound()
lastPicks = 0 # resetRound zeroes `picks`: not a new pick
let cmd = m.computeMove(states[i])
result.add HoldRec(call: m.callCount, spd: cmd.speed, trn: cmd.turnRate, held: m.lastHeld,
picked: m.picks != lastPicks, bullets: m.bullets.len)
lastPicks = m.picks
delEnv("TR_TFIL_HOLD_WHEN_TRAPPED")
loadTfilCommitEnv()
proc testJ153() =
delEnv("TR_TFIL_HOLD_WHEN_TRAPPED")
loadTfilCommitEnv()
check "j153: TR_TFIL_HOLD_WHEN_TRAPPED defaults to OFF (today's " &
"promote-the-2-least-hot fallback)", not TfilHoldWhenTrapped
let off = replayJ153(false) # knob explicitly 0
let unset = replay(loadStates(), loadRoundStarts()) # knob never set
var diff = -1
if off.len != unset.len: diff = min(off.len, unset.len)
else:
for i in 0..<off.len:
if unset[i].spd != off[i].spd or unset[i].trn != off[i].trn or
unset[i].call != off[i].call:
diff = i; break
check "j153: with the knob unset the move stream is BYTE-FOR-BYTE the " &
"knob-0 one over " & $off.len & " ticks — the default is today's",
diff < 0 and off.len > 0
let on = replayJ153(true)
var held, heldMoved, heldPicked = 0
var nonHeldMoving = 0
for i in 0..<on.len:
if on[i].held:
inc held
if abs(on[i].spd) > 0.001: inc heldMoved
if on[i].picked: inc heldPicked
elif abs(on[i].spd) > 0.001: inc nonHeldMoving
check "j153: with the knob ON the safe set really is empty often enough to " &
"matter (" & $held & " held ticks of " & $on.len & ")",
held > on.len div 100
check "j153: a held tick emits NO movement (speed 0) and no pick " &
"(" & $heldMoved & " moving holds, " & $heldPicked & " held picks)",
held > 0 and heldMoved == 0 and heldPicked == 0
check "j153: the hold is not a freeze — " & $nonHeldMoving & " non-held " &
"ticks still move and the bot still picks",
nonHeldMoving > 0 and on.filterIt(it.picked).len > 0
# no latch: a held tick must be followed by movement again (within a couple of
# ticks), and a pick must still be taken somewhere after the holds.
# A HOLD is not a latch: the hold is decided at the pick site, and the pick
# site only runs when the commitment has expired, so every held tick is a FRESH
# evaluation of the field. Observable consequence: hold runs end, and the tick
# after a run is a moving tick again. (A latching implementation would show ONE
# run per round and ~0 resumptions.) A long run therefore means a long trap, not
# a stuck bot — that is why the run LENGTH is deliberately not asserted.
var runs = 0
var resumed = 0
var worst = 0
var run = 0
for i in 0..<on.len:
if on[i].held:
inc run
else:
if run > 0:
inc runs
worst = max(worst, run)
if abs(on[i].spd) > 0.001: inc resumed
run = 0
if run > 0:
inc runs
worst = max(worst, run)
var pickedAfter = 0
var sawHold = false
for r in on:
if r.held: sawHold = true
elif sawHold and r.picked: inc pickedAfter
check "j153: the hold is NOT a latch — " & $resumed & " of " & $runs &
" maximal hold runs resume moving on the very next tick (longest run " &
$worst & " ticks = a trap that lasts, not a stuck bot) and " &
$pickedAfter & " picks happen after a hold",
runs > 0 and resumed * 2 > runs and pickedAfter > 0
# the gun path: a held tick must leave the bullet tracker exactly where a
# non-held tick would. If the hold returned before the tracker update, the
# bullet counts would diverge from the first hold onwards.
var firstDiv = -1
for i in 0..<min(on.len, off.len):
if on[i].bullets != off[i].bullets:
if on[i].held or off[i].held: firstDiv = i
break
check "j153: holding does not freeze the fire/bullet bookkeeping the GUN " &
"reads (bullet counts identical on held vs non-held ticks)",
firstDiv < 0
# ── j154: the BOUNDED hold (TR_TFIL_HOLD_MAX_TICKS, default 0 = off) ────────
#
# The budget is DERIVED from the enemy's own rate of fire, not chosen. Server
# `rules/math.kt`: `calcGunHeat(p) = 1 + p/5`, `calcBulletDamage(3.0) = 16`;
# `core/GunEngine.kt`: the gun cools 0.1 per tick and may only fire at heat == 0.
# So two 3.0-power shots are 1.6/0.1 = 16 ticks apart, and a brute-force search
# over the 0.1 power quantisation says 32 damage is the most the enemy can land
# in any 16-tick window (8/11/16/24/32 ticks -> 16/18/32/32/48). 16 is also the
# FIRST window that admits the enemy's SECOND shot at all, so nothing shorter
# can be surprised by a third bullet.
#
# A fully hot field is painted with the virtual pillar at radiance 0
# (`max(0, hotness - d*0) = hotness` on every tile) — the one heat source that
# covers the whole reachable hull at once, so the safe set is provably empty.
proc testJ154() =
delEnv("TR_TFIL_HOLD_MAX_TICKS")
loadTfilCommitEnv()
check "j154: TR_TFIL_HOLD_MAX_TICKS defaults to 0 = today's behaviour exactly",
TfilHoldMaxTicks == 0 and not TfilHoldWhenTrapped
# 1. DEFAULT PARITY: an explicit 0 is indistinguishable from unset, over the
# whole fixture, tick for tick. (The golden above covers UNSET; this covers
# the explicit zero the owner would put in an arm.)
let unset = replay(loadStates(), loadRoundStarts())
putEnv("TR_TFIL_HOLD_MAX_TICKS", "0")
loadTfilCommitEnv()
let zero = replay(loadStates(), loadRoundStarts())
var diff = -1
if unset.len != zero.len: diff = min(unset.len, zero.len)
else:
for i in 0..<unset.len:
if recLine(unset[i]) != recLine(zero[i]): diff = i; break
check "j154: TR_TFIL_HOLD_MAX_TICKS=0 is BYTE-FOR-BYTE the unset build over " &
$unset.len & " ticks (default path unchanged)",
diff < 0 and unset.len > 0
# 2. knob parsing
putEnv("TR_TFIL_HOLD_MAX_TICKS", "16"); loadTfilCommitEnv()
check "j154: TR_TFIL_HOLD_MAX_TICKS=16 is read", TfilHoldMaxTicks == 16
putEnv("TR_TFIL_HOLD_MAX_TICKS", "junk"); loadTfilCommitEnv()
check "j154: a malformed value falls back to 0 (off)", TfilHoldMaxTicks == 0
putEnv("TR_TFIL_HOLD_MAX_TICKS", "-8"); loadTfilCommitEnv()
check "j154: a negative value clamps to 0", TfilHoldMaxTicks == 0
delEnv("TR_TFIL_HOLD_MAX_TICKS"); loadTfilCommitEnv()
const HoldN = 4 ## the budget under test; any small N exercises it
const Hot = 100.0 ## every tile at 100 >> PathDangerThreshold 10
let ws = WorldState(enemyX: 0.0, enemyY: 0.0, enemyHeading: 0.0,
enemySpeed: 0.0, enemyEnergy: 100.0,
selfX: 400.0, selfY: 300.0, selfHeading: 0.0,
selfSpeed: 8.0, selfEnergy: 100.0,
arenaWidth: ArenaW, arenaHeight: ArenaH, tick: 0,
enemies: @[])
## One tick. `hot` = the pillar heat (0 = a clean field). A non-nil `bullet`
## is installed as the tracked set, which is the ONLY way an inbound bullet
## ever exists here (the enemy is out of the arena in these worlds).
proc tick(m: var TFILModule, hot: float, t: int,
bullet: TrackedBullet = TrackedBullet(alive: false)): MoveCommand =
PillarHotness = hot
PillarRadiance = 0.0
var w = ws
w.tick = t
if bullet.alive: m.bullets = @[bullet]
result = m.computeMove(w)
## A module with the grid initialised and NO live commitment, so tick 0 of a
## scenario is a REPLAN tick (where, and only where, a hold may be taken).
proc fresh(): TFILModule =
PillarHotness = 0.0; PillarRadiance = 0.0
result = initTFIL()
randomize(Seed)
discard tick(result, 0.0, 0)
result.commitTicks = 0
result.picks = 0
result.commitTarget = (x: 400.0, y: 300.0)
type Rec = tuple[held: bool, ht: int, picked: bool]
## The held/pick pattern of a run, plus the counter at each tick.
proc run(m: var TFILModule, hot: seq[float]): seq[Rec] =
for t, h in hot:
let before = m.picks
discard tick(m, h, t + 1)
result.add (held: m.lastHeld, ht: m.holdTicks, picked: m.picks != before)
# A 1-tick commitment makes every tick a replan tick, so the scenario is a
# clean read of the hold rule alone (no commitment state leaking in).
putEnv("TR_TFIL_COMMIT_TICKS", "1")
putEnv("TR_TFIL_HOLD_MAX_TICKS", $HoldN)
loadTfilCommitEnv()
# 3. the BOUND: at most N consecutive held ticks, then the normal promote-the-2
# fallback takes over — the hold can never latch.
let hotAll = @[Hot, Hot, Hot, Hot, Hot, Hot, Hot, Hot, Hot, 0.0, 0.0,
Hot, Hot, Hot, Hot, Hot, Hot, 0.0, 0.0, 0.0]
var m = fresh()
let r = run(m, hotAll)
var firstPick = -1
for i, e in r:
if e.picked: firstPick = i; break
echo "\n j154 run (held/ht/picked per tick, index: value):"
for i, e in r:
echo " ", i, ": ", (if e.held: "H" else: "."), e.ht,
(if e.picked: " P" else: " ")
check "j154: with the safe set EMPTY the mover HOLDS (" & $HoldN &
" ticks) instead of promoting, and releases into a pick on tick " &
$(firstPick + 1) & " — the bound is N, not 'until a tile appears'",
firstPick == HoldN and r[0].held and r[HoldN - 1].held and
r[HoldN - 1].ht == HoldN and not r[HoldN].held and r[HoldN].picked
# 4. RELEASE THE MOMENT A SAFE TILE EXISTS: the field cools at index 10, and
# that very tick is a pick, not a hold — no tick of latency.
check "j154: the hold releases on the SAME tick a safe tile appears " &
"(index 10 cooled -> picked=" & $r[10].picked & ", held=" &
$r[10].held & ", counter=" & $r[10].ht & ")",
r[10].picked and not r[10].held and r[10].ht == 0
# ... and the budget REFILLS: a fresh empty streak holds a full N again,
# i.e. the bound is per streak and the counter is not cumulative.
let streak2 = r[11 .. ^1]
var held2 = 0
for e in streak2:
if e.held: inc held2
check "j154: the counter RESET when the safe tile was taken — the second " &
"empty streak holds a full N again (" & $held2 & " ticks), never the " &
"accumulated " & $r[10].ht & "+" & $r[11].ht,
streak2[0].held and held2 >= HoldN and r[11].ht == 1
# 5. the held command is the SAME stop the mover already emits at its target,
# and the gun path is untouched: on a held tick the fire detector still
# latches the enemy's wave (the bot aims and fires from tracked state after
# go(), on every tick, whatever speed it just commanded).
m = fresh()
PillarHotness = Hot; PillarRadiance = 0.0
var wFar = ws
wFar.enemies = @[EnemyInfo(id: 1, x: 760.0, y: 300.0, heading: 180.0,
speed: 0.0, energy: 100.0)]
wFar.tick = 1
discard m.computeMove(wFar) # enemy seen at 100.0 energy
m.commitTicks = 0 # armed: a replan tick, as above
wFar.tick = 2
wFar.enemies[0].energy = 98.5 # a 1.5 drop = a 1.5-power shot
let gunCmd = m.computeMove(wFar)
check "j154: the gun still fires while holding — the mover held (" &
$m.lastHeld & ") on the very tick the enemy fired, and the fire " &
"detector still latched the wave (" & $m.bullets.len & " tracked)",
m.lastHeld and m.bullets.len > 0
check "j154: the held command is the stop the mover already emits at its " &
"target (speed 0, turn 0) — no new signal, no movement side effect",
gunCmd.speed == 0.0 and gunCmd.turnRate == 0.0
# 6. PANIC RELEASE (required). A tracked bullet on a collision course, 9 ticks
# out, overrides the hold on the tick it exists. The same bullet offset
# laterally does NOT, so the release is specific, not "any bullet".
# The budget is the DERIVED 16 here, so the horizon is min(16, 16) = 16.
putEnv("TR_TFIL_HOLD_MAX_TICKS", "16")
loadTfilCommitEnv()
let inbound = TrackedBullet(originX: 570.0, originY: 300.0, x: 570.0, y: 300.0,
velX: -17.0, velY: 0.0, power: 1.0,
alive: true, age: 0)
let missing = TrackedBullet(originX: 570.0, originY: 500.0, x: 570.0,
y: 500.0, velX: -17.0, velY: 0.0, power: 1.0,
alive: true, age: 0)
m = fresh()
discard tick(m, Hot, 1, inbound)
check "j154: PANIC RELEASE — a tracked bullet 9 ticks from our position " &
"overrides the hold on the same tick (held=" & $m.lastHeld &
", picked=" & $(m.picks > 0) & ")",
(not m.lastHeld) and m.picks > 0 and m.holdTicks == 0
m = fresh()
let cmdMiss = tick(m, Hot, 1, missing)
check "j154: ... and it is SPECIFIC: the same bullet 200px off our line " &
"still holds (held=" & $m.lastHeld & "), so the release is an arrival " &
"test, not a bullet count",
m.lastHeld and m.picks == 0 and cmdMiss.speed == 0.0
proc withBullet(b: TrackedBullet): TFILModule =
result = initTFIL()
result.bullets = @[b]
check "j154: the panic horizon is the DERIVED budget min(N, 16) ticks — the " &
"arrival test fires inside it and not outside",
bulletPanic(initTFIL(), 400.0, 300.0, 16.0) == false and
bulletPanic(withBullet(inbound), 400.0, 300.0, 16.0) == true and
bulletPanic(withBullet(inbound), 400.0, 300.0, 4.0) == false
# 7. a hold NEVER interrupts a live commitment (j153's comment claimed that;
# j154's code enforces it). Take a pick, keep the field hot, and the mover
# must keep driving to its committed target.
putEnv("TR_TFIL_COMMIT_TICKS", "15")
loadTfilCommitEnv()
m = fresh()
discard tick(m, 0.0, 1) # a clean field first: that tick PICKS
let pickedFirst = m.picks > 0
let live = m.commitTicks
let cmdLive = tick(m, Hot, 2) # now the field goes fully hot
check "j154: a hold never interrupts a live commitment — with " & $live &
" ticks on the clock the mover keeps driving to its target (speed " &
$cmdLive.speed & "), it does not freeze",
pickedFirst and live > 0 and (not m.lastHeld) and cmdLive.speed != 0.0
putEnv("TR_TFIL_COMMIT_TICKS", "15")
delEnv("TR_TFIL_HOLD_MAX_TICKS")
loadTfilCommitEnv()
PillarHotness = 0.0; PillarRadiance = 0.0
check "j154: clearing the knob restores today's behaviour exactly",
TfilHoldMaxTicks == 0
# ── driver ─────────────────────────────────────────────────────────────────── # ── driver ───────────────────────────────────────────────────────────────────
testDefaultParity() testDefaultParity()
@@ -857,6 +1488,12 @@ when declared(loadTfilCommitEnv):
testJ144() testJ144()
testJ145() testJ145()
testJ146() testJ146()
testJ147()
testJ151()
testJ152()
testJ150()
testJ154()
testJ153()
if failures > 0: if failures > 0:
echo "\n", failures, " check(s) FAILED" echo "\n", failures, " check(s) FAILED"
+1
View File
@@ -268,6 +268,7 @@ name, with no new knob:
| `TR_RACK_<GUN>` = `both`/`1v1`/`melee` | that gun may be selected | `TR_RACK_<GUN>=off`: the gun is removed from the rack | | `TR_RACK_<GUN>` = `both`/`1v1`/`melee` | that gun may be selected | `TR_RACK_<GUN>=off`: the gun is removed from the rack |
| `TR_POWER_POLICY` | energy-aware power caps (default) | uncapped: the gun's own preferred power | | `TR_POWER_POLICY` | energy-aware power caps (default) | uncapped: the gun's own preferred power |
| `TR_FIRE_FIX` | the corrected enemy-fire detector (default) | the shipped `prev - energy` detector | | `TR_FIRE_FIX` | the corrected enemy-fire detector (default) | the shipped `prev - energy` detector |
| `TR_FIRE_LAG` = `<int>` | back-date every detected enemy fire by N ticks at spawn (0 = shipped; **1 = the measured live detection lag**, j147) | n/a — it is a value knob |
| `TR_RADAR_FORCE_SPIN` | force the old stateless full-spin melee radar (**off by default**) | the adaptive arc-narrowing radar (default) | | `TR_RADAR_FORCE_SPIN` | force the old stateless full-spin melee radar (**off by default**) | the adaptive arc-narrowing radar (default) |
| `TR_TFIL_HEAT_TIME` | time-indexed bullet heat (**off by default**) | flat, time-independent heat (default) | | `TR_TFIL_HEAT_TIME` | time-indexed bullet heat (**off by default**) | flat, time-independent heat (default) |
| `TR_VBULLET_DEBUG` | draw the virtual-bullet overlay (**off by default**) | nothing drawn | | `TR_VBULLET_DEBUG` | draw the virtual-bullet overlay (**off by default**) | nothing drawn |
+215
View File
@@ -3454,3 +3454,218 @@ middle 30.4% · corr10 32.1% · bullets 65.0% · nofield 3.9%.
**The shipped default is untouched.** `TR_MOVEMENT=strafe` remains the default; **The shipped default is untouched.** `TR_MOVEMENT=strafe` remains the default;
`TR_TFIL_BULLET_CORE` / `TR_TFIL_BULLET_AURA` default to today's `10.0` / `5.0`, `TR_TFIL_BULLET_CORE` / `TR_TFIL_BULLET_AURA` default to today's `10.0` / `5.0`,
so `TR_MOVEMENT=tfil` still means today's tfil, byte-for-byte (guard check 1). so `TR_MOVEMENT=tfil` still means today's tfil, byte-for-byte (guard check 1).
# Batch 8 — the fire-detection lag (j147)
*Pre-registered BEFORE any battle of this batch was launched. No battle of this
batch existed when this section was written; the frozen binary for it is the
commit that adds `TR_FIRE_LAG` and the `TR_FIRE_DIAG` ghost-spawn trace.*
## The owner's report, and what was measured
*"i don't know if is the drawing only the arrives 1 tick later in the gui, but
the bullet auras looks like are all 1 tick-ish behind the real bullet!"*
The first job was to answer **drawing or decision**, not to fix anything. Three
measurements, in order, each one able to stop the next:
### 1. The corpus says the ENERGY DROP is on the fire's own row (lag 0)
`/tmp/tfil_ab2/out` (70 battles, `runN.jsonl` + `runN.events.jsonl`): for every
true fire event, the row at which the shooter's energy drop becomes visible is
`fireTick - 1` for **702/702** self fires in round 1 and 100% over the corpus —
i.e. in the recorded frame the drop and the shot are the SAME instant (a bullet
takes its first step during the turn it is fired, MEASURED: 1293/1293 `hitwall`
events have their first out-of-bounds bullet position at step
`hitwallTick - fireTick + 1`, which is only consistent with a first step inside
the firing turn). So the corpus alone cannot see a lag: it has no view of WHEN
our scan runs relative to the dispatch.
### 2. The corpus is NOT the bot's view, so the lag had to be measured LIVE
`common_libs/tests/measure_fire_ghost_lag.py`. The bot logs one
`[firediag] SPAWN tick=… sx=… sy=… gx=… gy=… p=… eta=…` line per detected fire
(the ghost's DRAWN position and our own position, the timeline anchor). The
capture supplies the true fire events (origin, direction, power) and the rounds.
The timeline is anchored without guessing: `[firediag] EV hit tick=… getTurn=…`
lines vs. the sidecar's own event turns match exactly, and give
`getTurn = bot.tick + 1` (j134, re-verified) — so a ghost logged at bot tick `t`
was placed during server turn `t + 1`.
| arm | matched spawns | detection lag | ghost-vs-observer px (mean / median / p90) | arrival-deadline error (ticks, mean / median) |
|---|---:|---|---:|---:|
| tfil, lag 0 | 413 | **+1 tick, 100%** | **19.06 / 19.16 / 22.00** | **0.987 / 0.991** |
| tfil, `TR_FIRE_LAG=1` | 446 | +1 tick, 100% | **5.37 / 5.65 / 8.96** | **0.063 / 0.051** |
| strafe, lag 0 | 497 | +1 tick (77.9%; the rest are duplicate/split waves of a fire already counted) | **16.08 / 18.23 / 21.81** | 0.771 / 0.944 |
| strafe, `TR_FIRE_LAG=1` | 466 | +1 tick, 100% | **6.01 / 5.91 / 9.80** | **0.065 / 0.051** |
**The answer to the owner: it is NOT only the drawing — the decision is late.**
The aura is displaced by exactly **one whole bullet step (11..20 px, 19.1 px
mean for tfil)**, in the direction of travel, and the arrival deadline the
mover reads is **a full tick late (0.99 ticks)**. The mechanism is measured, not
guessed: the server dispatches a turn's fire **after** our `go()` for that turn,
so the energy drop of a turn-`T` shot first reaches our scan at turn `T+1`; and
because a bullet takes its first step during the turn it is fired, the true
bullet is already one step downrange when we see it. Both movers place the ghost
at the SCANNED enemy position — where the bullet was *born* — and then advance
it once per tick, so the entire ghost trajectory is the true one shifted one
turn later, for the bullet's whole life.
**It is OURS.** The draw/advance order was checked and is correct (both movers
`advanceBullets()` -> `detectFires()` -> build the field, i.e. a ghost spawned
this tick is drawn at its age-0 position and every older ghost has been advanced
exactly once: build-then-advance, which is the correct direction; an
advance-then-build order would have shown the aura one tick AHEAD). With
`TR_FIRE_LAG=1` the ghosts land on the observer's bullet to within the enemy's
own scan staleness (5.4 px mean, max 8 px = the enemy's top speed), which is the
floor this design can reach: the origin is the enemy's *scanned* position, not
its fire-time position.
### The treatment
`TR_FIRE_LAG` (int, **default 0 = today's behaviour byte-for-byte**, `x` is only
touched when `lag > 0`), read once in the shared
`common_libs/movement_harness/fire_tracker.nim` and applied by BOTH movers at
spawn: `x = origin + dir * speed * lag`, `y = …`. The arrival deadline needs no
separate change — every mover derives it from the ghost's own position
(`heatDecay(along / speed)`, the `dot < 0` reap), so a correct position gives a
correct deadline. Guard: `test_tfil_commit_env.nim` 77 -> **87 checks**, all pass
(default parity on the golden replay, exact n-step back-date, deadline shortens
by exactly `lag`, junk/negative degrade to 0, the ghost is reaped exactly one
tick earlier).
## Arms (frozen, `tools/ab/arms_fire_lag.txt`)
| # | arm | mover | `TR_FIRE_LAG` | what it isolates |
|---|---|---|---|---|
| 1 | `tfil_off` | tfil | 0 (default) | **the reference** — today's tfil |
| 2 | `tfil_lag1` | tfil | 1 | the back-date, on tfil |
| 3 | `strafe_off` | strafe | 0 (default) | **the reference** — today's strafe |
| 4 | `strafe_lag1` | strafe | 1 | the back-date, on strafe |
Panel: the FROZEN 15-opponent `tools/ab/panel_movement.txt`. Harness:
`tools/ab/tournament_run.sh` + `tournament_analyze.py`.
## Pre-registered prediction, MDE and decision rule
* **MDE, stated up front.** The verdict layer is the paired per-opponent
difference over 15 opponents, exactly as batches 4-7. Batch 7 (5 runs/arm)
measured **MDE = 12.8 damage/run and 0.28 wins/run**; this batch runs **3
runs/arm**, so by `sqrt(5/3)` the MDE degrades to roughly **16 damage/run and
0.36 wins/run** — and the incoming-hit-rate MDE to roughly **1.9 points**.
**Any true effect smaller than that is invisible here by construction, and a
null will be recorded as "not distinguishable", never as "no effect".**
* **Prediction.** `tfil_lag1` > `tfil_off` and `strafe_lag1` > `strafe_off` on
damage/run and round wins, because the field the mover decides on is displaced
by a whole bullet step today and stops being after the fix. The **mechanism is
the incoming hit rate** (the dodge should survive strictly more), and the
offline gate already measured the mechanism geometrically (19.1 -> 5.4 px,
0.99 -> 0.06 ticks), so a mechanism-positive / outcome-null result is the
EXPECTED shape given the MDE, and is recorded as such — the same verdict
pattern as j144, j145 and j146.
* **Verdict rule (unchanged, not re-interpreted afterwards).** The cross-opponent
sign test p < 0.05 on one primary metric (damage/run or round wins) with the
other not down, SD/SE/95% CI/MDE reported.
* **Nothing separates -> nothing changes.** `TR_FIRE_LAG` stays default 0 and
the shipped movers are untouched. A mechanism-positive outcome-null does NOT
retract the geometric measurement, and does NOT change `TR_MOVEMENT=strafe`.
*(results appended below after the battles)*
### MEASURED — gate B: the guard (`test_tfil_commit_env.nim`, 77 -> 87 checks)
All 87 pass, including the byte-for-byte golden replay of the shipped mover with
`TR_FIRE_LAG` unset (check 1). The j147 ones:
* `TR_FIRE_LAG` unset -> `FireLag 0`, and the ghost lands EXACTLY on the scanned
enemy (`b.x == ei.x` bit for bit — the position is only touched when `lag > 0`).
* `=1` -> the ghost is exactly one bullet step (17 px at power 1.0) downrange on
its own heading; `=2` -> exactly two; the step length is the true
`20 - 3*power`, not a scaled one.
* **the arrival deadline**: the mover's eta equals the TRUE remaining flight
(10.764706 vs 10.764706) where the lag-0 eta was 11.764706 — a full tick late;
at `lag=2` the deadline shortens by exactly 2 ticks.
* a junk or negative value degrades to the shipped lag 0 (never a negative
back-date); clearing the knob restores the shipped spawn exactly.
* end to end: the ghost is reaped (`dot < 0`, the geometric arrival the mover
actually uses) **exactly one tick earlier** — 12 -> 11 ticks.
* `test_env_report` + `test_env_dotenv` green with `TR_FIRE_LAG` registered in
`env_report.nim` + `knownEnvNames()` + `.env.example` + `docs/env_reference.md`.
### MEASURED — gate C: the live A/B, 180 battles
> **Provenance.** Session `/tmp/ab/j147_firelag`, frozen binary `d21f7ce`
> (sha256 `29571d4d…`), panel `tools/ab/panel_movement.txt` (15 opponents,
> FROZEN), arms file `tools/ab/arms_fire_lag.txt` registered above BEFORE any of
> these battles ran. **4 arms x 15 opponents x 3 runs x 3 rounds = 180 battles,
> 0 failed, 0 never started, 473 s.** The MDEs the analyzer actually reported at
> 3 runs/arm: **12.2-15.1 damage/run, 0.33-0.55 wins/run, 1.4-2.9 hit-rate
> points** — the pre-registered estimate (~16 / ~0.36 / ~1.9) was right.
**Pooled dashboard (descriptive, NOT the verdict):**
| arm | runs | dmg/run | dmg taken/run | wins/run | round wins | win rate | incoming hit rate | mean distance |
|---|---:|---:|---:|---:|---:|---:|---:|---:|
| `tfil_off` | 45 | 109.7 | 187.8 | 1.24 | 56/135 | 41.5% | 16.91% | 394 |
| `tfil_lag1` | 45 | 111.8 | 192.9 | 1.20 | 54/135 | 40.0% | 17.45% | 396 |
| `strafe_off` | 45 | 106.3 | 160.1 | 1.44 | 65/135 | 48.1% | 12.84% | 434 |
| `strafe_lag1` | 45 | 110.1 | 159.0 | **1.62** | **73/135** | **54.1%** | 13.21% | 428 |
**Verdict layer, each mover against ITS OWN reference (the only comparison that
isolates the knob):**
| arm | metric | mean Δ | 95% CI | sign test | p(sign) | p(sign-flip) | Wilcoxon p | MDE |
|---|---|---:|---|---:|---:|---:|---:|---:|
| `tfil_lag1` vs `tfil_off` | damage | +2.08 | [-7.22, +11.38] | 6/15 | 0.6072 | 0.6375 | 0.9773 | 12.15 |
| `tfil_lag1` vs `tfil_off` | wins | -0.04 | [-0.29, +0.21] | 4/9 | 1 | 0.8516 | 0.5923 | 0.33 |
| `tfil_lag1` vs `tfil_off` | hit_rate | +0.94 | [-0.93, +2.81] | 10/15 | 0.3018 | 0.2984 | 0.222 | 2.45 |
| `strafe_lag1` vs `strafe_off` | damage | +3.77 | [-6.98, +14.53] | 9/15 | 0.6072 | 0.4598 | 0.6701 | 14.04 |
| `strafe_lag1` vs `strafe_off` | wins | +0.18 | [-0.13, +0.49] | 5/9 | 1 | 0.3359 | 0.1723 | 0.41 |
| `strafe_lag1` vs `strafe_off` | hit_rate | +0.33 | [-0.73, +1.39] | 9/15 | 0.6072 | 0.5403 | 0.5509 | 1.38 |
### VERDICT — plain
1. **Was it only the drawing? NO. The decision was late, by exactly one bullet
step, and the fix is now in.** Measured live on 1777 matched ghost spawns
across both movers: the detection lag is **+1 tick on 100%** of them, the
ghost-vs-observer displacement is **19.1 px mean / 22.0 p90** (tfil) and
**16.1 / 21.8** (strafe), and the arrival deadline the mover reads is
**0.99 / 0.77 ticks late**. With `TR_FIRE_LAG=1` the displacement is
**5.4 / 9.0 px** and the deadline error **0.06 ticks** — the residue is the
ENEMY's own scan staleness (<= 8 px, its top speed), which is the floor this
design can reach because the ghost's origin is the enemy's *scanned* position.
The draw/advance order was checked and is correct, so the GUI was faithfully
drawing a wrong field.
2. **The live OUTCOME is null, and that is recorded as "not distinguishable".**
`tfil_lag1` is -0.04 wins/run and `strafe_lag1` is +0.18 wins/run — both far
under the MDEs the analyzer reported (0.33 and 0.41). Nothing reaches the
pre-registered bar, so under the campaign's rule **nothing is changed**:
`TR_FIRE_LAG` stays **default 0** and both movers ship exactly as before. The
knob is there, measured and documented, for anyone who wants the arm.
3. **The live MECHANISM did not move either** — incoming hit rate +0.94 pp (tfil)
and +0.33 pp (strafe), neither significant. This is the fourth consecutive
movement job where a real, measured mechanism change does not show up as fewer
hits taken. Two readings, both worth keeping: the dodge is limited by the
1-tick-stale enemy POSITION and by the 8-px scan staleness of the ghost's
origin, not by a 19-px translation of a field whose core is 18 px and whose
corridor is 40 px wide; and at 3 runs/arm a real few-percent effect in hit
rate sits under the ~1.4-point MDE. **What the fix does buy, provably, is
the arrival deadline**: every mover's heat, corridor and reap are now timed
off the bullet's real position, which is the input the next arrival-commit /
time-indexed-heat work needs to be correct at all.
4. **The one significant live result in this batch is the MOVER, not the knob**:
`strafe_lag1` vs `tfil_off` is +0.38 wins/run (sign 10/12, p = 0.0386) with
the incoming hit rate **-4.67 pp (sign 2/15, p = 0.0074, sign-flip
p = 0.0007, Wilcoxon p = 0.0024)** and mean distance +34 px (14/15). That is
the known strafe-over-tfil gap reproducing itself, and it is exactly why the
pre-registration demanded the within-mover reference: read against `tfil_off`
alone, the knob looks like a winner it is not.
**j148 — corridor LENGTH bound (unmeasured).** `TR_TFIL_CORRIDOR_TICKS` and
`TR_STRAFE_CORRIDOR_TICKS` (both default `0`) bound the corridor — the rotated
rectangle from the ghost bullet along its heading — by `min(distance to the wall,
bulletSpeed * TICKS)`, so a fast (low-power) bullet's corridor is long and a
slow one's is short, instead of every bullet blanketing the arena to the wall.
`0` is exactly today's behaviour; only the LENGTH changes, the heat inside the
surviving corridor is untouched. **Untested** — no battle, no measurement, the
parity guard only says the default path is byte-for-byte unchanged.
+209
View File
@@ -0,0 +1,209 @@
# j159 — PRE-REGISTRATION: does tile-geometry weighting in the tfil picker win?
**Written and committed BEFORE a single battle of this experiment ran.** No
result in the "MEASURED" section below existed when this section was written.
## The question
`TR_TFIL_GEO_MODE` / `TR_TFIL_GEO_TAU` (shipped default `off`, j152) shape the
**draw** over the safe tiles the tfil picker chooses from. The offline sweep on
recorded fixtures predicted a real geometric improvement —
| offline metric (`measure_tfil_pick_defects`) | `off` | `both-rej`, tau 60 |
|---|---:|---:|
| REACH / arrival within feasible time | 4.5% | 29.4% |
| hot on arrival (`hotAtTta`) | 31.0% | 24.0% |
| **top-1 tile share (pick DIVERSITY)** | **7.0%** | **10.6%** |
— and a **diversity cost**, because the geometry weight concentrates the draw.
The offline ruler replays the real picker on real fixtures; it says nothing
about whether a tile that is geometrically reachable and less hot actually wins
a round. That is what this run measures.
**Hypothesis H1.** Weighting the draw by tile geometry (`both-rej`, tau 60)
raises damage/run and round-win rate over the shipped uniform draw, because the
mover arrives at safe tiles instead of merely picking them.
**Direction is pre-registered as two-sided.** A regression is as interesting as
a win (the diversity cost makes one plausible) and re-deciding the direction
after seeing the data is exactly what this document exists to prevent.
## Arms — identical except the geo knob
Both arms: `TR_MOVEMENT=tfil`, everything else at the shipped defaults, one
frozen binary built once from `git archive HEAD` (session 2223ca6).
| arm | env | role |
|---|---|---|
| `A_off` | `TR_TFIL_GEO_MODE=off` (`TAU=0`) | **REFERENCE** — the shipped uniform draw |
| `B_geo` | `TR_TFIL_GEO_MODE=both-rej` `TR_TFIL_GEO_TAU=60` | treatment |
**Contamination control (the main risk).** The owner has `both-rej` in a personal
`.env` (`ModularBot_garage/out/.env`, a copy at `tr_bots/ModularBot_geo/.env`),
and this bot's dotenv loader gives the FILE priority over shell exports. If the
tournament's bot instances resolved that file, arm A would silently become arm B
and the whole run would be void. Three guarantees, all verifiable from the logs:
1. each arm is launched with `TR_ENV_FILE` pointing at a **per-arm file this
job generated** (`/tmp/j159_geo/env/A_off.env`, `/tmp/j159_geo/env/B_geo.env`)
in this job's own outdir, so the ONLY `.env` the loader can resolve is mine;
2. the tournament's per-run botdir (`$OUTDIR/.work/<opp>/<arm>/run<N>/bots/ModularBot`)
contains only `ModularBot.json`, `ModularBot.sh` and a symlink to the frozen
binary — **no `.env`**, and the loader's fallback is `./.env` then `.env` next
to the executable (it does not walk up parent directories), so the owner's file
is not reachable;
3. every single run's `[env]` boot report is checked for its intended
`TR_TFIL_GEO_MODE` / `TR_TFIL_GEO_TAU` before any number is read. **Any run
whose `[env]` disagrees with its arm invalidates the session** and the run is
reported as void rather than analysed.
## Design
* Harness: `tools/ab/tournament_run.sh` + `tools/ab/tournament_analyze.py`
(unmodified).
* Panel: `tools/ab/panel_movement.txt` — the **FROZEN 15-opponent movement
panel**, unchanged. Unit of evidence is the opponent, not the battle.
* 15 opponents x 2 arms x **14 runs** x 3 rounds = **420 battles**.
* Battles serialised: `--wait-arena 45`, one session at a time.
### Primary metrics (pre-registered, fixed)
1. **damage/run** (our damage dealt per run)
2. **round-win rate** (rounds won / rounds fought)
**Hit rate is NOT a primary metric** — it hid a survival regression once already.
### Secondary / mechanism (reported, never a verdict)
* incoming hit rate (the survival channel the mechanism actually runs through);
* damage taken/run;
* the offline geometric numbers above (REACH%, hot-on-arrival%, top-1 tile
share). The live battle logs do not contain the per-pick tile or the arrival
state, so the live run **cannot** re-measure them; that is stated in the
verdict rather than papered over. No new instrumentation is built for this.
### Statistical treatment
Same as every previous movement gate: per-opponent paired deltas (arm −
reference), mean delta, SD, SE, 95% CI, a sign test and a **sign-flip
permutation test** (exact when `2^n <= 2^20`, else Monte-Carlo), Wilcoxon as a
cross-check, plus the MDE the analyzer reports for the reference arm's n.
### MDE — stated up front, and it is LARGE
At **14 runs/arm** over the frozen 15-opponent panel this design resolves about
**0.28 wins/run** (and the corresponding damage/run MDE the analyzer prints).
A two-arm run is 420 battles, ~1 hour. Resolving **0.10 wins/run** would need
~2.2 h and ~2,900 battles — **which we are NOT doing.**
**Consequences, recorded before any data:**
* **A null is the likely outcome.** This would be the *fifth* consecutive
mechanism-positive / outcome-null result in this campaign (after j144, j145,
j146, j147).
* A null here **excludes only a LARGE effect** (>= ~0.28 wins/run). It does not
show the knob does nothing, and it does not retract the offline geometric
measurement.
* Because the offline sweep also measured a **diversity regression**
(top-1 tile share 7.0% -> 10.6%), a null combined with a confirmed diversity
cost is an argument **against** shipping, not for it.
### Verdict rule (fixed now, not re-read later)
* **Adopt** only if BOTH primaries move in B's favour with `p(sign-flip) < 0.05`
and the effect is at or above the reported MDE. One primary at p<0.05 with
the other not down is reported as a partial signal, not a win.
* Otherwise **do not ship**; the knob stays default `off`.
* The mechanism is reported as measured, with no vote in the verdict.
* No subsetting, no dropping opponents, no re-running to chase a p-value. A
clean null is a fully acceptable result.
---
## MEASURED
*(appended after the battles — everything above was committed first)*
### MEASURED — the live A/B, 420 battles (j159)
* **Provenance.** Session `/tmp/ab/j159_geo`, commit `7c5bc9c`, frozen binary
sha256 `9f116e7a9eb9…`, panel `tools/ab/panel_movement.txt` (FROZEN, 15
opponents), 15 x 2 x **14 runs** x 3 rounds = **420 battles, 0 failed, 0 never
started, 1110 s**. Per-arm env files `/tmp/j159_geo/env/{A_off,B_geo}.env`.
* **Env verification.** All **420** runs carry their intended arm: 210/210
`A_off` show `TR_TFIL_GEO_MODE=off` / `TR_TFIL_GEO_TAU=0` (parsed `off`/`0.0`),
210/210 `B_geo` show `both-rej`/`60` (parsed `both`/`60.0`), every run reports
`env file: /tmp/j159_geo/env/<arm>.env (source: TR_ENV_FILE)` and
`move.effective = tfil`. No `.env` exists anywhere in the session dir, and the
loader's fallbacks are `./.env` then `.env` next to the executable — it does
not walk up parents — so the owner's file is unreachable. **0 runs mis-set.**
* **Record correction (no battle re-run).** The arms file declared only
`TR_ENV_FILE`, which the analyzer's liveness guard reads from `session.json`
and treats as an undeclared `TR_MOVEMENT` (fatal contamination). `session.json`
and a corrected arms file were rewritten to declare the effective env — the
original is kept as `/tmp/j159_geo/{session.json.orig,arms_tfil_geo.txt.orig}`.
The guard then re-verified all 420 declared values verbatim in the boot
reports: `liveness: 0 run(s) excluded (420 total)`.
**Pooled dashboard (descriptive, NOT the verdict):**
| arm | runs | dmg/run | dmg taken/run | wins/run | round wins | win rate | incoming hit rate | mean distance |
|---|---:|---:|---:|---:|---:|---:|---:|---:|
| `A_off` | 210 | 112.5 | 195.2 | 1.21 | 255/630 | 40.5% | 17.64% | 393 |
| `B_geo` | 210 | 103.7 | 188.0 | 1.16 | 244/630 | 38.7% | 17.42% | 419 |
**Verdict layer** (per-opponent paired deltas, arm − reference; sign-flip is
the exact 2^15 permutation the pre-registration names as the decision test):
| arm | metric | mean Δ | 95% CI | sign test | p(sign) | **p(sign-flip)** | Wilcoxon p | MDE |
|---|---|---:|---|---:|---:|---:|---:|---:|
| `B_geo` | **damage/run** | **-8.83** | [-14.69, -2.97] | 5/15 | 0.3018 | **0.006104** | 0.0115 | 7.65 |
| `B_geo` | round wins | -0.05 | [-0.18, +0.08] | 4/11 | 0.5488 | 0.4619 | 0.3496 | 0.17 |
| `B_geo` | damage taken | -7.24 | [-20.84, +6.36] | 8/15 | 1 | 0.2786 | 0.4777 | 17.77 |
| `B_geo` | incoming hit rate | -1.19 pp | [-3.88, +1.51] | 8/15 | 1 | 0.3962 | 0.5895 | 3.51 |
| `B_geo` | mean distance | **+26.3 px** | [+16.3, +36.4] | **15/15** | 6.1e-05 | 6.1e-05 | 0.0007 | 13.15 |
**Per-opponent damage/run** (the pattern/ram rows carry the loss): Coriantumr
-25.1, CassiusClay -24.2, SpinBot -26.2, WallAvoider -13.3, BlitzBat -11.2,
HawkOnFire -11.7, Diamond -10.9, TripHammer -9.0, YersiniaPestis -8.9,
Dookious -7.3 vs GresSuffurd +2.3, DiamondStealer +3.2, Ascendant +3.7,
DrussGT +0.1. Round wins: HawkOnFire +0.50 and WallAvoider +0.14 (both closer
opponents) against Coriantumr -0.57, TripHammer -0.21, YersiniaPestis -0.21.
**Mechanism, offline (the committed ruler, re-run unchanged for this doc):**
`measure_tfil_pick_defects` reproduces the pre-registered prediction exactly —
REACH **4.5% -> 29.4%**, hot-on-arrival **31.0% -> 24.0%**, and the diversity cost
**top-1 tile share 7.0% -> 10.6%** (normalised entropy 0.87 -> 0.85). The live
mean distance **+26 px on 15/15 opponents** is the same mechanism seen end to
end: the geometry weight prefers tiles that are far better to *arrive* in, and
the bot sits further out and deals **less** damage.
### VERDICT — DO NOT ADOPT
1. **H1 is rejected.** Round wins are flat (-0.05/run, p(sign-flip) = 0.46, under
the 0.17 MDE) and damage/run is **down 8.83** (p(sign-flip) = 0.0061, above
the 7.65 MDE, Wilcoxon p = 0.011). The pre-registration required BOTH
primaries up; one is down and significant by the test it named.
2. **The MDE, restated.** 14 runs/arm on the frozen 15-opponent panel resolves
**0.17 wins/run** and **7.65 damage/run** (better than the 0.28 pre-registered
estimate). So this run excludes a large *benefit*; it also positively measures
a small *harm* in damage. It says nothing about effects below those numbers.
3. **The mechanism moved exactly as predicted, and that is what makes it bad.**
REACH/arrival 4.5% -> 29.4% and hot-on-arrival 31.0% -> 24.0% are real and
reproducible, but they bought **+26 px of distance** and fewer damage points,
not survival: incoming hit rate moved -1.19 pp, a fifth of its own 3.51 MDE.
"Arrive at a safe tile" turned out to mean "arrive further away".
4. **Diversity worsened, as the offline sweep warned.** Top-1 tile share
7.0% -> 10.6%, and the live losses concentrate against the opponents that
punish a long-range mover (SpinBot -26.2 damage with a -14.5 pp hit-rate
shift, the pattern guns -9 to -25). Outcomes are null-to-negative AND
diversity is worse: that is the argument against shipping, exactly the
pre-registered case.
5. **A null on wins lets us claim only "no large win".** It does not show the
knob is inert, and it does not retract the geometric measurement — but the
geometry measurement is not an argument for shipping when the live
consequence of it is measurably less damage from measurably further away.
**Ship state: `TR_TFIL_GEO_MODE` stays default `off`. Nothing changes.** Not
adopted, not adopted default-off. This is the **fifth** mechanism-positive /
outcome-not-positive result in the movement campaign (j144, j145, j146, j147,
j159) — and the first one where the mechanism is *anti*-correlated with damage.
+139
View File
@@ -0,0 +1,139 @@
# j154 — the DERIVED hold budget for "hold when the safe set is empty"
**Status: implemented, DEFAULT OFF, no battle run.** `TR_TFIL_HOLD_MAX_TICKS`
(default `0` = today's behaviour byte-for-byte). The knob, the panic release and
the guards live in `common_libs/movements/the_floor_is_lava.nim` and
`common_libs/tests/test_tfil_commit_env.nim`.
## 1. The mechanics, re-verified against the server source
Source used: **the server Kotlin sources at `/home/davide/Projects/tank-royale`
(v0.35.5)**, not a cached doc. There is no `docs/energy_math.md` in this repo.
| Fact | Value | Source |
|---|---|---|
| gun heat added per shot | `1 + p/5` | `server/.../rules/math.kt:125` `calcGunHeat` |
| gun cooling | `0.1` / tick | `core/GunEngine.kt:108` `coolDownGun`, default `DEFAULT_GUN_COOLING_RATE = 0.1` (`lib/common/.../RuleDefaults.kt:25`) |
| may fire only at | `gunHeat == 0.0` (strict; the else-branch cools instead) | `core/GunEngine.kt:36` |
| bullet damage | `4p`, `+2(p-1)` above 1 → `6p-2` | `rules/math.kt:112-118` `calcBulletDamage` |
| firepower clamp | `0.1 … 3.0` | `rules/rules.kt:49,52` |
| round-start gun heat | `3.0` | `rules/rules.kt:22` `INITIAL_GUN_HEAT` |
Note: there is no `MaxGunHeat = 3.0` gate in this server — the fire gate is
`gunHeat == 0`, and `3.0` is only the *initial* heat a bot starts a round with
(30 idle ticks of cooldown). The 16-tick number below is unchanged by that
distinction, because it is derived from the heat ADD and the cooling rate.
## 2. The owner's frame: "the time between shooting 2 × 3.0-power bullets"
`heat(3.0) = 1 + 3/5 = 1.6`; `1.6 / 0.1` = **16 ticks** between two max-power
shots. `calcBulletDamage(3.0) = 6*3 - 2 = ` **16**, so two of them = **32**.
The *fastest* repeat is a `0.1`-power shot: `1.02` heat → **11 ticks**
(the 11th subtraction is what takes the residual 0.02 to 0), for
`4*0.1 = ` **0.4** damage. So "2 × 3.0-power" is a **DAMAGE** bound, not a
COUNT bound: the enemy can fire ~1.5× as often, but each of those shots is 40×
weaker. The right question is therefore "how much damage can land in N ticks",
not "how many bullets".
## 3. Max damage deliverable in N ticks (brute force over the power quantisation)
DP over the 0.1-step power grid (30 powers), the enemy free to mix powers
(it may interleave weak shots to shorten its own interval), first shot free at
t = 0:
| N (ticks) | max total damage | how |
|---|---|---|
| 8 | **16** | one 3.0 shot; the 0.1-power repeat needs 11 |
| 11 | **18** | 3.0 (16) at t=0, then 0.5-power (2) at t=11 |
| 16 | **32** | 3.0 at t=0 and t=16 — two max shots |
| 24 | **32** | same two; the next shot cannot land before t=32 |
| 32 | **48** | 3.0 at t=0, 16, 32 |
| 64 | **80** | five max shots (linear thereafter) |
The damage *rate* `(6p-2)/(10+2p)` is monotone increasing in `p` (0.036 dmg/tick
at 0.1, 0.33 at 1.0, 1.0 at 3.0), so no mix beats pure 3.0-power asymptotically;
mixing only wins at a window edge (N = 11 above), never by more than one weak
shot. **16 ticks is the exposure ceiling of a hold: 32 damage = 16 % of the
200 HP a bot carries.**
## 4. How 16 relates to the code
* `CommitTicks = 15` (`the_floor_is_lava.nim:71`). The derived budget is
**`CommitTicks + 1`**: a hold of 15 ticks admits ONE max-power shot (16
damage), 16 ticks admits the second (32). 16 is the first window in which the
enemy's *second* bullet can land at all, so it is the shortest budget that
cannot be surprised by a third. The two numbers agree by construction, which
is the point: the mover's existing commitment length and the enemy's rate of
fire are the same quantity here.
* j144 measured a **mean hold of 24.0 ticks** live. 24 sits between the 16- and
32-tick damage steps: it buys no extra protection (still 32) and is exposed to
the same two shots. A 16-tick cap is therefore a *tightening* of j144's
measured behaviour, not an extrapolation of it — hence the 24 arm in the A/B.
## 5. The knob
`TR_TFIL_HOLD_MAX_TICKS` (int, default `0` = off). When the safe tile set is
empty (~65 % of picks offline) and the mover is on a **replan** tick, it holds
position for at most N ticks per empty streak. Rules:
* a safe tile exists → release on the same tick (no latency);
* counter resets when a safe tile is taken, so the bound is per streak;
* the hold never interrupts a live commitment (it replaces a replan only) —
j153's comment claimed this and its code did not enforce it; j154 does;
* the **gun is untouched**: `computeMove` never emits fire, and `ModularBot`
aims and fires from tracked state after `go()` on every tick. Guarded: the
fire detector still latches the enemy's wave on a held tick.
### Panic release (required)
`bulletPanic(m, selfX, selfY, horizon)` — for each tracked bullet, closest
approach of its straight path is `t* = ((self-b)·v)/|v|²`; the hold is
overridden when `0 ≤ t* ≤ horizon` and the miss distance is within the
bullet's own core radius. Horizon = **`min(N, 16)` ticks**. It reuses the
tracked ghost's own position/velocity — the same model `pathMaxHeat` decays by
and `advanceBullets` integrates — so there is no second arrival model in the
file (`TR_TFIL_ARRIVE_TICKS` is a *tile-selection* filter, not a bullet-arrival
predictor). `min(N, 16)` because a bullet arriving after the budget expires
cannot hurt a hold that has already ended; 16 is the derived exposure window.
### Composition with the other knobs
* `TR_TFIL_COMMIT_ARRIVAL=1` — **wins**. A hold is only reachable on a replan
tick, so under arrival the bot is in a commitment and never holds. The
arrival commitment is a hold on a *destination*; the empty-set hold is a hold
with *no destination*. They never compete.
* `TR_TFIL_NOREV_SPEED=4` — no interaction: it filters mid-flight candidate
switches inside the pick block, which a hold short-circuits, and it cannot
force a pick during a hold.
* `TR_TFIL_ARRIVE_TICKS` — no interaction: it only filters a **non-empty** safe
set, and the hold only triggers when that set is empty.
## 6. Guards
`common_libs/tests/test_tfil_commit_env.nim`, `testJ154` (15 checks): default 0;
explicit `0` byte-for-byte the unset build over 20 026 ticks; knob parsing
(16 / junk / negative); the N-tick bound; same-tick release when a safe tile
appears; counter reset and budget refill; the gun still fires while holding; the
held command is the same stop as at-target; panic release; panic specificity
(a bullet 200 px off the line still holds); the horizon check; the hold never
interrupts a live commitment; clearing the knob.
Suite total: **136 PASS** (121 before j154, not the 99 quoted in the brief —
see the note below).
## 7. Proposed A/B — NOT RUN
Arms: `TR_TFIL_HOLD_MAX_TICKS` = 0 (control) / 16 / 24; `TR_MOVEMENT=tfil`
pinned; frozen 15-opponent panel; everything else at shipped defaults.
Primary metrics: **damage per run and round-win rate** (never hit rate).
Mechanism metrics: % picks held, incoming hit rate while holding, panic-release
frequency, distance-to-enemy at the moment of the hold.
MDE: ~0.28 wins/run at ~14 runs/arm (two arms ≈ 1 h); resolving ~0.10
wins/run needs ~2.2 h ≈ 2 900 battles for a three-arm design.
Expectation to state up front: four mechanism-positive / outcome-null results in
a row (j152 geometry, j151 arrival bound, j144 arrival commitment, j153 hold)
make a null the likely outcome, and this is the fifth candidate. 1 h can only
say "no large effect"; ~2.2 h is needed before "no small effect".
+90
View File
@@ -0,0 +1,90 @@
# j153 proposal (NOT RUN) — `TR_TFIL_HOLD_WHEN_TRAPPED`: hold when no safe tile exists
**Status: awaiting the owner's approval. No battle, no A/B arm, no tournament has
been started.** The knob exists, is registered, defaults to today's behaviour
byte-for-byte, and is guarded offline.
## The owner's claim
> "if no tile is found to go, to not choose the less dangerous, but to stay
> still! the next tick probably the situation already changed and we did not
> commit to any dangerous place."
Today, when the safe set (`pathMaxHeat <= PathDangerThreshold`, after the
`CoolestLevels = 2` filter) is too small to draw from, the picker **promotes the
2 least-hot blocked tiles** and moves to one of them. The proposal replaces that
with `speed 0.0` for that tick only.
## The knob
| env | default | meaning |
|---|---|---|
| `TR_TFIL_HOLD_WHEN_TRAPPED` | `0` (off) | `1` = hold when the safe set is **empty**; today = promote the 2 least-hot blocked tiles |
- **One tick, never latched.** The hold is taken at the pick site, and the pick
site only runs when `commitTicks == 0`, so the next tick re-evaluates the field
from scratch. There is deliberately **no max-hold knob** in j153: a counter can
only add a way to get stuck. (j154, in flight, adds
`TR_TFIL_HOLD_MAX_TICKS` = 0 = off as a *separate* default-off knob.)
- **It never interrupts a live commitment.** The hold replaces a *replan*, not a
commitment in progress: with `TR_TFIL_COMMIT_ARRIVAL=1` or
`TR_TFIL_NOREV_SPEED=4` armed the two do not fight, because the hold branch is
downstream of the commitment block and only runs at `commitTicks == 0`.
- **The gun keeps firing.** `computeMove` never emits a fire command (the gun
lives in the bot's `go()` loop), and the hold `return`s *after* the bullet
tracking, so the fire tracker's state on a held tick is bit-identical to a
non-held tick (guarded in `common_libs/tests/test_tfil_commit_env.nim`).
## What the offline harness can and cannot say
Per `docs/offline_harness_trust.md` the replay harness is trustworthy only for
per-gun single-tick prediction on a fixed enemy trajectory; it scored **0/6** on
closed-loop questions. "Hold vs move" is a **counterfactual closed-loop** question,
so this document contains **no** damage-taken comparison for holding. Only
open-loop descriptors of the recorded field are reported
(`common_libs/tests/measure_tfil_hold_window.nim`).
## Proposed A/B (needs approval)
```
TOURNAMENT_NIMCACHE=/tmp/nc_j153 \
tools/ab/tournament_run.sh \
--arms tools/ab/arms_hold_trapped.txt \
--panel tools/ab/panel_movement.txt \
--runs 14 --rounds 7 --conc 7 --wait-arena 45 \
--reference hold0 \
--outdir /tmp/ab/j153_hold
python3 tools/ab/tournament_analyze.py /tmp/ab/j153_hold --reference hold0
```
Arms file (frozen 15-opponent movement panel, 14 runs/arm, 7 rounds):
```
hold0 | | control = today's promote-the-2 fallback
hold1 | TR_TFIL_HOLD_WHEN_TRAPPED=1 | hold one tick when the safe set is empty
hold8 | TR_TFIL_HOLD_WHEN_TRAPPED=1 TR_TFIL_HOLD_MAX_TICKS=8 | bounded hold (only if j154 lands)
```
**Primary metrics: damage/run and round-win rate** (NOT hit rate — a movement
arm's value flows through the closed loop). **Mechanism metrics:** incoming hit
rate, % of picks held, mean distance-to-enemy at a hold, tick-share at speed 0.
**MDE, stated up front:** ~0.28 wins/run at 14 runs/arm; a two-arm session is
~1 h. Resolving ~0.10 wins/run needs ~2.2 h / ~2,900 battles. A 1 h two-arm run
can only reject effects at or above ~0.28 wins/run — anything smaller is a null
by construction, and must be reported as such.
**Prior, stated plainly:** four mechanism-positive / outcome-null results in a
row on this campaign. **A null is the most likely outcome.** A null with a
mechanism hit (holds fire, distance at hold is large) would mean: holding is
achievable and does not by itself buy rounds; ship nothing. A null *without* a
mechanism hit means the arm never bound and the A/B is void, not negative.
## Decision each duration supports
| duration | supports |
|---|---|
| 1 h (2 arms × 14 runs) | reject/accept only ≥0.28 wins/run. Mechanism check only. |
| 2.2 h (~2,900 battles, 3 arms) | resolve ~0.10 wins/run. Still not a small-effect test. |
| any null | no change to the shipped default. `TR_TFIL_HOLD_WHEN_TRAPPED` stays 0. |
+38
View File
@@ -0,0 +1,38 @@
# ─────────────────────────────────────────────────────────────────────────────
# arms_fire_lag.txt — j147: the ONE-TICK DETECTION LAG, four arms on the frozen
# movement panel (tools/ab/panel_movement.txt). Two movers (tfil, strafe) x
# {lag 0, lag 1}; the lag knob is the ONLY difference inside a mover pair.
#
# WHY. MEASURED LIVE (common_libs/tests/measure_fire_ghost_lag.py, 4 sessions,
# 1777 matched ghost spawns): the server dispatches a turn's fire AFTER our
# go() for that same turn, so the energy drop of a turn-T shot first reaches our
# scan at turn T+1 (our bot tick T). A bullet takes its FIRST step during the
# turn it is fired, so by then the true bullet is already `speed` px (11..20 px,
# one whole bullet step) downrange and the arrival deadline is a full tick short.
# Both movers place the ghost at the SCANNED enemy position, i.e. exactly where
# the bullet was born: the whole ghost trajectory is the true one shifted one
# turn later. The measured ghost-vs-observer displacement is 19.1 px mean /
# 22.0 p90 (tfil) and 16.1 / 21.8 (strafe), deadline error 0.99 / 0.77 ticks.
# With TR_FIRE_LAG=1 the displacement falls to 5.4 / 9.0 px (the residue is the
# ENEMY's own scan staleness, <= 8 px) and the deadline error to 0.06 ticks.
#
# `TR_FIRE_LAG` default 0 = today's behaviour byte for byte, so arm 1 and arm 3
# ARE the shipped movers.
#
# Pre-registered in docs/movement_campaign.md ("Batch 8 — the fire-detection
# lag") BEFORE any of these battles ran. References: `tfil_off`, `strafe_off`.
#
# Format: name | ENV=value ENV=value | label
# ─────────────────────────────────────────────────────────────────────────────
# 1. tfil as shipped (the reference for arm 2).
tfil_off | TR_MOVEMENT=tfil | today's tfil, the ghost is born at the scanned enemy (reference)
# 2. tfil with the measured lag back-dated at spawn.
tfil_lag1 | TR_MOVEMENT=tfil TR_FIRE_LAG=1 | tfil, every detected fire back-dated one bullet step
# 3. strafe as shipped (the reference for arm 4).
strafe_off | TR_MOVEMENT=strafe | today's strafe, the ghost is born at the scanned enemy (reference)
# 4. strafe with the measured lag back-dated at spawn.
strafe_lag1 | TR_MOVEMENT=strafe TR_FIRE_LAG=1 | strafe, every detected fire back-dated one bullet step