Files
SirRoboGarage/common_libs/guns/pattern_matcher.nim
T
SirStone e53690036b fix(guns): speed-sensitive caches, dead stop-shot branch, exact TM trace pairing
Four guns cached a whole prediction per tick while predict() is called once
per power bin, so every bin after the first (and the real fired shot, which
shares lastState) reused the power-1.0 lead. Fixed by caching only the
speed-INDEPENDENT derived state and recomputing the lead per requested speed:
- stop_shot: also fixes prevSpeed being written before it was read, which
  made abs(speed) < abs(prev) permanently false and the entire
  stop-prediction branch unreachable (it was just Linear).
- displacement: the cache key included bulletSpeed, so the guard missed on
  all four bins and the 15-tick window advanced ~4x/tick, making the
  inferred velocity ~4x too small.
- averaged_lead: tick cache removed outright. pattern_matcher: split into
  speed-independent match+path and per-call lead.

FeedbackEvent gains fireTick/powerBin (additive; only virtual_bullets
constructs one) so guns can pair feedback to the exact shot instead of
guessing by coordinates. tsetlin uses it: traces are now keyed exactly by
(fireTick, powerBin) with a 1024-slot ring, and the 10-frame window shifts
at most once per tick (it was shifting ~4-5x/tick, so isWarmedUp tripped
after ~2 ticks).

KNOWN INCOMPLETE: tsetlin still does not diverge from Linear in battle. The
two named bugs are fixed (a 600-tick sim shows trainedShots=2141,
traceMisses=0, and a fixed-input probe converges to a 9.6px correction), but
the TM's clause feedback itself is broken: ~131 of 1740 literals end up
included per clause, so its conjunction never fires. Sweeping TM_S,
TM_N_CLAUSES and a two-branch Type-I update did not change the correction
from 0. Needs a real TM fix or removal, not another bug fix.

First-ever guard tests for the gun selector: common_libs/tests/
test_gun_harness.nim (14 checks, headless, no Java). There were none before,
which is how six broken guns survived a full analysis cycle. Against the
previous HEAD, 5 of these checks FAIL - that is the regression guard.
2026-09-20 22:47:26 +02:00

173 lines
6.5 KiB
Nim

## Pattern-matching gun: searches movement history for a matching sequence,
## then plays it forward to predict future position.
## Reference: https://robowiki.net/wiki/Pattern_Matching
## Coordinate system: 0° = East, CCW positive (Tank Royale standard).
import std/math
import gun_harness/gun_interface
const
HistorySize* = 500
PatternLen* = 10 # ticks used as search key; ponytail: fixed, expose if tuning needed
type
MoveTick = object
velocity: float ## signed speed (px/tick)
headingDelta: float ## heading change in radians this tick
PatternMatcherGun* = object
buf: array[HistorySize, MoveTick]
head: int ## next write index (circular)
count: int ## filled entries (capped at HistorySize)
prevHeading: float
prevSpeed: float
prevTick: int
hasPrev: bool
# Per-tick, speed-INDEPENDENT pattern state. Both the history search and the
# replayed enemy path depend only on observed movement, never on bulletSpeed,
# so they are built at most once per tick. The bullet lead (number of replay
# steps + coast) is derived from this path on every call.
cacheValid: bool
cacheTick: int
bestMatch: int ## -1 = no usable match (linear fallback)
playStart: int
playAvail: int
pathX: array[HistorySize + 1, float]
pathY: array[HistorySize + 1, float]
pathHeading: array[HistorySize + 1, float] ## radians after s steps
pathSpeed: array[HistorySize + 1, float] ## speed after s steps
debugGraphics*: bool
# --- circular buffer helpers ---
proc write(g: var PatternMatcherGun, m: MoveTick) {.inline.} =
g.buf[g.head] = m
g.head = (g.head + 1) mod HistorySize
if g.count < HistorySize: inc g.count
proc readAt(g: PatternMatcherGun, i: int): MoveTick {.inline.} =
## i = 0 is oldest, i = count-1 is newest
g.buf[(g.head - g.count + i + HistorySize * 2) mod HistorySize]
# --- linear fallback (same style as linear.nim) ---
proc linearPredict(state: WorldState, bulletSpeed: float): (float, float) =
let dist = hypot(state.enemyX - state.selfX, state.enemyY - state.selfY)
let t = dist / bulletSpeed
let hRad = degToRad(state.enemyHeading)
let ex = clamp(state.enemyX + cos(hRad) * state.enemySpeed * t,
BotRadius, state.arenaWidth - BotRadius)
let ey = clamp(state.enemyY + sin(hRad) * state.enemySpeed * t,
BotRadius, state.arenaHeight - BotRadius)
(ex, ey)
# --- pattern search + play-forward ---
proc findBestMatch(g: PatternMatcherGun): int =
## Speed-independent history search. Returns the start index of the best
## matching pattern, or -1 when there is not enough history.
if g.count < PatternLen * 2:
return -1
# key = last PatternLen entries
let keyStart = g.count - PatternLen
# scan backwards for best match (exclude the key itself)
var bestScore = Inf
var bestMatch = -1
let scanEnd = g.count - PatternLen - 1 # last valid match start
for i in countdown(scanEnd, 0):
var score = 0.0
for k in 0 ..< PatternLen:
let a = g.readAt(keyStart + k)
let b = g.readAt(i + k)
let dv = a.velocity - b.velocity
let dh = a.headingDelta - b.headingDelta
score += dv * dv + dh * dh
if score < bestScore:
bestScore = score
bestMatch = i
bestMatch
proc buildPath(g: var PatternMatcherGun, state: WorldState, bestMatch: int) =
## Precompute the matched pattern replayed forward from the current state.
## Only depends on observed movement, so it is valid for every power bin.
g.playStart = bestMatch + PatternLen
g.playAvail = g.count - 1 - g.playStart # ticks we can replay
g.pathX[0] = state.enemyX
g.pathY[0] = state.enemyY
g.pathHeading[0] = degToRad(state.enemyHeading)
g.pathSpeed[0] = state.enemySpeed
for s in 1 .. g.playAvail:
let m = g.readAt(g.playStart + s - 1)
g.pathHeading[s] = g.pathHeading[s - 1] + m.headingDelta
g.pathSpeed[s] = m.velocity
g.pathX[s] = g.pathX[s - 1] + cos(g.pathHeading[s]) * g.pathSpeed[s]
g.pathY[s] = g.pathY[s - 1] + sin(g.pathHeading[s]) * g.pathSpeed[s]
proc projectFromPath(g: PatternMatcherGun, state: WorldState,
bulletSpeed: float): (float, float) =
## Speed-dependent lead: walk the cached path as far as this bulletSpeed's
## estimated flight time reaches, then coast linearly for the remainder.
# iterative time estimate
let dist0 = hypot(state.enemyX - state.selfX, state.enemyY - state.selfY)
var t = dist0 / bulletSpeed
var ex = state.enemyX
var ey = state.enemyY
for _ in 0..4:
let steps = min(int(t + 0.5), g.playAvail)
ex = g.pathX[steps]
ey = g.pathY[steps]
# if we ran out of replay data, coast linearly from last simulated pos
let remaining = t - steps.float
if remaining > 0.0:
ex += cos(g.pathHeading[steps]) * g.pathSpeed[steps] * remaining
ey += sin(g.pathHeading[steps]) * g.pathSpeed[steps] * remaining
let ndx = ex - state.selfX
let ndy = ey - state.selfY
t = sqrt(ndx * ndx + ndy * ndy) / bulletSpeed
ex = clamp(ex, BotRadius, state.arenaWidth - BotRadius)
ey = clamp(ey, BotRadius, state.arenaHeight - BotRadius)
(ex, ey)
# --- Gun interface ---
proc predict*(g: var PatternMatcherGun, state: WorldState,
bulletSpeed: float): GunPrediction =
if bulletSpeed <= 0.0:
return GunPrediction(x: state.enemyX, y: state.enemyY)
# Roll history forward and (re)build the speed-independent pattern path at
# most once per tick. The old code returned a single cached (x, y) per tick,
# so all four power bins shared bin 0's lead.
if not g.cacheValid or state.tick != g.cacheTick:
if g.hasPrev:
var dh = degToRad(state.enemyHeading) - degToRad(g.prevHeading)
# wrap to [-π, π]
while dh > PI: dh -= 2.0 * PI
while dh < -PI: dh += 2.0 * PI
g.write(MoveTick(velocity: g.prevSpeed, headingDelta: dh))
g.prevHeading = state.enemyHeading
g.prevSpeed = state.enemySpeed
g.prevTick = state.tick
g.hasPrev = true
g.cacheValid = true
g.cacheTick = state.tick
g.bestMatch = g.findBestMatch()
if g.bestMatch >= 0:
g.buildPath(state, g.bestMatch)
if g.bestMatch < 0:
let (px, py) = linearPredict(state, bulletSpeed)
return GunPrediction(x: px, y: py)
let (px, py) = g.projectFromPath(state, bulletSpeed)
GunPrediction(x: px, y: py)
proc onResult*(g: var PatternMatcherGun, e: FeedbackEvent) =
discard # pattern matcher learns from movement observation, not feedback