feat(ground-ai): add sample-based lead estimation, exit watch, and bounded bias

Replace direct reads of true enemy velocity with an own-sight sample
estimator, add 2-5 s last-seen exit watching, and sample bounded aiming
bias once per shooting opportunity:

- Add the estimation section to tuning/ground-ai.jsonc (watchMinSec,
  watchMaxSec, velSampleMinSpanSec, velStableSpanSec, velJumpResetMps,
  baseAimSigmaM, leadErrorFrac, maxBiasM), validated in
  ground-ai-tuning.ts and compiled into WTO_AI_EST_* constants.
- Add wto_ai_estimate_common.das:
  - Maintain a 6-sample timestamped ring buffer from each bot's own
    visual sightings; compute smoothed observed velocity and convergence
    quality, dropping quality and re-seeding bias on sudden braking/turns
    or target switches.
  - On LOS loss from an active ground engagement, freeze watchPos at the
    last-seen exit point, clear observed velocity, and draw one random
    2-5 s watch duration; stationary overwatch/defend bots hold their
    post while watching, whereas pushing/retreating bots keep moving
    while keeping their turret on the exit.
  - Compute lead from observed velocity and loaded-shell flight time,
    sampling one bounded bias vector per shooting opportunity (target,
    shot count, state, 12 m position cell) that narrows as observation
    quality improves and still passes the single fire-permission gate.

Verified root and launcher type checks, isolated 2.61.0.58 build (25
ground AI modules packed), and clean in-engine daScript compilation/load
(wto_ai_runtime.das loaded in 184 ms, 0 compile errors). Live battle
acceptance deferred until the full pipeline is wired.
This commit is contained in:
N0VAN0M4LY committed 2026-12-03 18:23:12 +08:00
1 parent 80113bdd2e
commit 45ff082a36
8 files changed
+223 -14

No files matched your search

@@ -42,6 +42,7 @@ export function readGroundAiTuning(reader: TuningReader): GroundAiTuning {
perception: readPerceptionSection(reader.object('perception')),
stateMachine: readStateMachineSection(reader.object('stateMachine')),
tactics: readTacticsSection(reader.object('tactics')),
estimation: readEstimationSection(reader.object('estimation')),
fireControl: readFireControlSection(reader.object('fireControl')),
diagnostics: {
telemetry: diag.bool('telemetry'),
@@ -230,6 +231,29 @@ function readTacticsSection(tactics: TuningReader): GroundAiTuning['tactics'] {
};
}
function readEstimationSection(est: TuningReader): GroundAiTuning['estimation'] {
const watchMinSec = est.number('watchMinSec', { min: 0.5, max: 10.0 });
const watchMaxSec = est.number('watchMaxSec', { min: 1.0, max: 15.0 });
if (watchMaxSec < watchMinSec) {
throw new TuningError('tuning file ground-ai.jsonc: estimation.watchMaxSec must be >= watchMinSec');
}
const velSampleMinSpanSec = est.number('velSampleMinSpanSec', { min: 0.05, max: 2.0 });
const velStableSpanSec = est.number('velStableSpanSec', { min: 0.2, max: 6.0 });
if (velStableSpanSec <= velSampleMinSpanSec) {
throw new TuningError('tuning file ground-ai.jsonc: estimation.velStableSpanSec must be > velSampleMinSpanSec');
}
return {
watchMinSec,
watchMaxSec,
velSampleMinSpanSec,
velStableSpanSec,
velJumpResetMps: est.number('velJumpResetMps', { min: 1.0, max: 20.0 }),
baseAimSigmaM: est.number('baseAimSigmaM', { min: 0.0, max: 2.0 }),
leadErrorFrac: est.number('leadErrorFrac', { min: 0.0, max: 1.0 }),
maxBiasM: est.number('maxBiasM', { min: 0.0, max: 6.0 }),
};
}
function readFireControlSection(fc: TuningReader): GroundAiTuning['fireControl'] {
const closeRangeM = fc.number('closeRangeM', { min: 30, max: 250 });
const midRangeM = fc.number('midRangeM', { min: 100, max: 600 });
+12
View File
@@ -140,6 +140,18 @@
"peekCooldownSec": 6.0
},
// Target velocity estimation from own visual samples, last-seen watch, and bounded shot bias.
"estimation": {
"watchMinSec": 2.0,
"watchMaxSec": 5.0,
"velSampleMinSpanSec": 0.25,
"velStableSpanSec": 1.2,
"velJumpResetMps": 4.5,
"baseAimSigmaM": 0.28,
"leadErrorFrac": 0.26,
"maxBiasM": 2.2
},
"fireControl": {
"maxEngageRangeM": 1250.0,
"closeRangeM": 100.0,
+15 -1
View File
@@ -6,6 +6,7 @@ module wto_ai_combat_types_common shared
require ecs
let public WTO_MAX_EXPOSURE_TRACKS = 8
let public WTO_MAX_VEL_SAMPLES = 6
let public WTO_MAX_SHELL_PROFILES = 12
let public WTO_BLOCK_NONE = 0
@@ -46,7 +47,20 @@ struct public WtoPerceiveState
goodLosSec : float = 0.0
visibleAimPt : float3 = float3(0.0, 0.0, 0.0)
knownPos : float3 = float3(0.0, 0.0, 0.0)
smoothedVel : float3 = float3(0.0, 0.0, 0.0)
estVel : float3 = float3(0.0, 0.0, 0.0)
velQuality : float = 0.0
sampleTargetEid : EntityId = INVALID_ENTITY_ID
sampleCount : int = 0
sampleHead : int = 0
samplePos : float3[6]
sampleAt : float[6]
wasEngaging : bool = false
watchPos : float3 = float3(0.0, 0.0, 0.0)
watchUntil : float = -100.0
oppKey : uint = 0u
oppBiasU : float = 0.0
oppBiasV : float = 0.0
oppSeeded : bool = false
lastSeenAt : float = -100.0
lockedEid : EntityId = INVALID_ENTITY_ID
lockedUntil : float = -100.0
+134
View File
@@ -0,0 +1,134 @@
// Own-sight target velocity estimator, bounded 2-5 s last-seen exit watch, and
// once-per-opportunity bounded aiming bias (never reads true target velocity).
options indenting = 2
options no_global_heap = true
module wto_ai_estimate_common shared
require ecs
require math
require %appGame.wtoai.wto_ai_config_common
require %appGame.wtoai.wto_ai_math_common
require %appGame.wtoai.wto_ai_combat_types_common
require %appGame.wtoai.wto_ai_types_common
[never_inline]
def private wto_est_hash(seed : uint) : uint
var x = seed ^ 0x9e3779b9u
x = (x ^ (x >> 16u)) * 0x85ebca6bu
x = (x ^ (x >> 13u)) * 0xc2b2ae35u
return x ^ (x >> 16u)
[never_inline]
def private wto_est_rand01(seed : uint) : float
return float(wto_est_hash(seed) & 0xffffu) / 65535.0
[never_inline]
def public wto_est_reset_samples(var p : WtoPerceiveState&)
p.sampleCount = 0
p.sampleHead = 0
p.estVel = float3(0.0, 0.0, 0.0)
p.velQuality = 0.0
p.oppSeeded = false
[never_inline]
def public wto_est_push_visual_sample(now : float; tgtEid : EntityId; tgtPos : float3;
var p : WtoPerceiveState&)
if p.sampleTargetEid != tgtEid
p.sampleTargetEid = tgtEid
wto_est_reset_samples(p)
if p.sampleCount > 0
let lastIdx = (p.sampleHead + WTO_MAX_VEL_SAMPLES - 1) % WTO_MAX_VEL_SAMPLES
if (now - p.sampleAt[lastIdx]) < 0.05
return
let dst = p.sampleHead
p.samplePos[dst] = tgtPos
p.sampleAt[dst] = now
p.sampleHead = (dst + 1) % WTO_MAX_VEL_SAMPLES
p.sampleCount = min(p.sampleCount + 1, WTO_MAX_VEL_SAMPLES)
// Find oldest still-fresh sample (<= 1.8 s old) to compute smoothed observed velocity.
var oldIdx = dst
var oldestAt = now
for k in range(p.sampleCount)
let idx = (dst + WTO_MAX_VEL_SAMPLES - k) % WTO_MAX_VEL_SAMPLES
let t = p.sampleAt[idx]
if (now - t) <= 1.8 && t < oldestAt
oldestAt = t
oldIdx = idx
let span = now - oldestAt
if span < WTO_AI_EST_MIN_SPAN_SEC
p.estVel = float3(0.0, 0.0, 0.0)
p.velQuality = 0.0
return
var vRaw = (tgtPos - p.samplePos[oldIdx]) / span
let rawSpd = length(vRaw)
if rawSpd > 34.0
vRaw = vRaw * (34.0 / rawSpd)
let vDiff = length(vRaw - p.estVel)
if p.velQuality > 0.25 && vDiff > WTO_AI_EST_JUMP_RESET_MPS
p.oppSeeded = false
p.estVel = lerp(p.estVel, vRaw, 0.58)
p.velQuality *= 0.35
return
p.estVel = p.velQuality <= 0.01 ? vRaw : lerp(p.estVel, vRaw, 0.38)
let spanQ = clamp((span - WTO_AI_EST_MIN_SPAN_SEC) / max(0.1, WTO_AI_EST_STABLE_SPAN_SEC - WTO_AI_EST_MIN_SPAN_SEC), 0.0, 1.0)
let steadyQ = clamp(1.0 - vDiff * 0.07, 0.35, 1.0)
p.velQuality = spanQ * steadyQ
[never_inline]
def public wto_est_on_los_lost(now : float; selfEid : EntityId; var p : WtoPerceiveState&)
wto_est_reset_samples(p)
if !p.wasEngaging
return
p.wasEngaging = false
if !p.targetEid || p.targetIsAir
return
p.watchPos = length_sq(p.visibleAimPt) > 1.0 ? p.visibleAimPt : (p.knownPos + float3(0.0, 1.4, 0.0))
let seed = uint(selfEid) ^ (uint(p.targetEid) * 2654435761u) ^ uint(max(0.0, now * 100.0))
let frac = wto_est_rand01(seed)
let dur = lerp(WTO_AI_EST_WATCH_MIN_SEC, WTO_AI_EST_WATCH_MAX_SEC, frac)
p.watchUntil = now + dur
if WTO_AI_DIAG_TELEMETRY
print("WTO_AI|WATCH|eid={uint(selfEid)}|tgt={uint(p.targetEid)}|dur={dur}\n")
[never_inline]
def public wto_est_compute_biased_lead(muzzlePos, myVel, aimBase : float3;
var slot : WtoBotSlot&;
var outLeadPt : float3&) : float
assume p = slot.perceive
let rawDelta = aimBase - muzzlePos
let rawDist = length(rawDelta)
let dragLoss = clamp(slot.fire.activeDragCx * 0.00011 * rawDist, 0.0, 0.28)
let vEff = max(120.0, slot.fire.activeSpeedMps * (1.0 - dragLoss))
// Lead uses ONLY our own visual velocity estimate, scaled by observation quality.
let leadScale = p.sampleCount >= 2 ? clamp(0.35 + 0.65 * p.velQuality, 0.0, 1.0) : 0.0
let usedVel = p.estVel * leadScale
var leadPt = aimBase
var tof = 0.0
for _iter in range(2)
tof = clamp(length(leadPt - muzzlePos) / vEff, 0.0, 3.5)
leadPt = aimBase + usedVel * tof - myVel * (tof * 0.85)
// Sample bounded natural bias ONCE per shooting opportunity (target + shot + state + 12m grid).
let gx = uint(int(muzzlePos.x / 12.0) + 4096)
let gz = uint(int(muzzlePos.z / 12.0) + 4096)
let key = (uint(p.targetEid) ^ (uint(slot.fire.shotCount) * 2654435761u) ^
(uint(slot.tactics.state) * 40503u) ^ (gx * 73856093u) ^ (gz * 19349663u))
if !p.oppSeeded || p.oppKey != key
p.oppKey = key
p.oppSeeded = true
let sBase = key ^ (uint(slot.eid) * 2246822519u)
p.oppBiasU = (wto_est_rand01(sBase) + wto_est_rand01(sBase ^ 0x517cc1b7u)) - 1.0
p.oppBiasV = (wto_est_rand01(sBase ^ 0x9e3779b9u) + wto_est_rand01(sBase ^ 0x85ebca6bu)) - 1.0
// Error envelope shrinks naturally as observation quality converges.
let tgtSpd = length(p.estVel)
let leadSpread = tgtSpd * tof * WTO_AI_EST_LEAD_ERR_FRAC * (1.0 - 0.72 * p.velQuality)
let distSpread = WTO_AI_EST_BASE_SIGMA_M * clamp(rawDist / 350.0, 0.25, 2.6) * (1.2 - 0.55 * p.velQuality)
let latOff = clamp((leadSpread + distSpread) * p.oppBiasU, -WTO_AI_EST_MAX_BIAS_M, WTO_AI_EST_MAX_BIAS_M)
let vertOff = clamp(distSpread * 0.65 * p.oppBiasV, -WTO_AI_EST_MAX_BIAS_M * 0.5, WTO_AI_EST_MAX_BIAS_M * 0.5)
let toAimXZ = wto_xz_normalize(rawDelta, float3(1.0, 0.0, 0.0))
let latAxis = float3(-toAimXZ.z, 0.0, toAimXZ.x)
outLeadPt = leadPt + latAxis * latOff + float3(0.0, vertOff, 0.0)
return rawDist
+8 -8
View File
@@ -19,6 +19,7 @@ require %appGame.wtoai.wto_ai_config_common
require %appGame.wtoai.wto_ai_math_common
require %appGame.wtoai.wto_ai_combat_types_common
require %appGame.wtoai.wto_ai_types_common
require %appGame.wtoai.wto_ai_estimate_common
require %appGame.wtoai.wto_ai_fire_gate_common
[never_inline]
@@ -122,16 +123,12 @@ def private wto_inspect_primary_weapon(unit : Unit const?; now : float;
fc.prevLoadedAmmo = totalLoaded
[never_inline]
def private wto_solve_ballistic_aim(muzzlePos, myVel : float3; slot : WtoBotSlot const&;
def private wto_solve_ballistic_aim(muzzlePos, myVel : float3; var slot : WtoBotSlot&;
aimBase : float3; var outAimPt, outWishDir : float3&) : float
let rawDist = length(aimBase - muzzlePos)
var leadPt = aimBase
let rawDist = wto_est_compute_biased_lead(muzzlePos, myVel, aimBase, slot, leadPt)
let dragLoss = clamp(slot.fire.activeDragCx * 0.00011 * rawDist, 0.0, 0.28)
let vEff = max(120.0, slot.fire.activeSpeedMps * (1.0 - dragLoss))
var leadPt = aimBase
for _iter in range(2)
let tof = clamp(length(leadPt - muzzlePos) / vEff, 0.0, 3.2)
let selfComp = myVel * (tof * 0.85)
leadPt = aimBase + slot.perceive.smoothedVel * tof - selfComp
outAimPt = leadPt
var arcDir = float3(0.0, 0.0, 0.0)
if calculate_arc_low_start_dir(muzzlePos, leadPt, vEff, arcDir) && length_sq(arcDir) > 0.25
@@ -236,7 +233,10 @@ def public wto_fire_update(world : WtoWorldSnap const&; var unit : Unit?;
let engageValid = (slot.perceive.hasClearLos && !!slot.perceive.targetEid && !slot.perceive.targetIsAir &&
!(slot.spec.role == WTO_ROLE_SPAA && slot.tactics.state == WTO_STATE_DISABLED))
if engageValid
distToTgt = wto_solve_ballistic_aim(muzzlePos, unit.vel, slot, slot.perceive.visibleAimPt, aimPt, wishWorldDir)
let baseAim = slot.perceive.visibleAimPt
distToTgt = wto_solve_ballistic_aim(muzzlePos, unit.vel, slot, baseAim, aimPt, wishWorldDir)
elif now < slot.perceive.watchUntil
wishWorldDir = normalize(slot.perceive.watchPos - muzzlePos)
elif !!slot.perceive.targetEid && (now - slot.perceive.lastSeenAt) <= WTO_AI_TACTICS_MEMORY_TTL_SEC
wishWorldDir = normalize((slot.perceive.knownPos + float3(0.0, 1.4, 0.0)) - muzzlePos)
elif now < slot.perceive.alertUntil
+7 -5
View File
@@ -12,6 +12,7 @@ require %appGame.wtoai.wto_ai_combat_types_common
require %appGame.wtoai.wto_ai_types_common
require %appGame.wtoai.wto_ai_terrain_common
require %appGame.wtoai.wto_ai_sight_common
require %appGame.wtoai.wto_ai_estimate_common
require %appGame.wtoai.wto_ai_world_common
[never_inline]
@@ -173,7 +174,6 @@ def public wto_perceive_update(var world : WtoWorldSnap&; now, dt : float;
wto_scan_visual_exposure(world, now, dt, myEye, lookDir, slot, bestIdx, visCount, goodLosSec, aimPt)
if bestIdx >= 0
assume tgt = world.units[bestIdx]
let sameTarget = p.targetEid == tgt.eid
p.targetEid = tgt.eid
p.targetIsAir = tgt.isAir
p.hasClearLos = true
@@ -181,9 +181,10 @@ def public wto_perceive_update(var world : WtoWorldSnap&; now, dt : float;
p.goodLosSec = goodLosSec
p.visibleAimPt = aimPt
p.knownPos = tgt.pos
let alpha = sameTarget ? clamp(dt * 6.0, 0.18, 0.65) : 1.0
p.smoothedVel = sameTarget ? lerp(p.smoothedVel, tgt.vel, alpha) : tgt.vel
p.lastSeenAt = now
p.wasEngaging = !tgt.isAir
p.watchUntil = -100.0
wto_est_push_visual_sample(now, tgt.eid, tgt.pos, p)
if p.lockedEid != tgt.eid || now >= p.lockedUntil - 0.5
p.lockedEid = tgt.eid
p.lockedUntil = now + WTO_AI_TACTICS_STICKY_SEC
@@ -192,15 +193,16 @@ def public wto_perceive_update(var world : WtoWorldSnap&; now, dt : float;
wto_world_broadcast_radio(world, slot.army, tgt.eid, tgt.pos, now)
return
// Lost visual confirmation: immediately revoke LOS, zero velocity lead, freeze knownPos.
// Lost visual confirmation: immediately revoke LOS, freeze exit point for 2-5 s watch, zero velocity.
p.hasClearLos = false
p.visiblePointCount = 0
p.goodLosSec = 0.0
p.smoothedVel = float3(0.0, 0.0, 0.0)
wto_est_on_los_lost(now, slot.eid, p)
let tgtIdx = wto_world_find_unit(world, p.targetEid)
if !!p.targetEid && (tgtIdx < 0 || !world.units[tgtIdx].isAlive || (now - p.lastSeenAt) > WTO_AI_TACTICS_MEMORY_TTL_SEC)
p.targetEid = INVALID_ENTITY_ID
p.lockedEid = INVALID_ENTITY_ID
p.watchUntil = -100.0
wto_update_audio_and_radio_alerts(world, now, myPos, slot)
[never_inline]
+5
View File
@@ -178,6 +178,11 @@ def public wto_tactics_update(world : WtoWorldSnap const&; now, dt : float;
if slot.fire.reloading && !!p.targetEid && (now - p.lastSeenAt) <= WTO_AI_TACTICS_MEMORY_TTL_SEC
if wto_sm_start_reload_action(world, now, myPos, hullFwd, threatPos, baseGoal, distXZ, distGoal, slot)
return
// Stationary overwatch/defend bots hold their firing post briefly to watch the enemy's last exit point;
// marching/pushing bots keep advancing while the turret watches.
if !hasGroundTgt && now < p.watchUntil && slot.order.urgency != WTO_URGENCY_HIGH && distGoal <= 35.0
wto_sm_set_state(now, WTO_STATE_MARCH, myPos, 0.0, "watch_last_exit", distXZ, slot)
return
let marchSpd = wto_sm_march_speed(slot, distGoal)
let marchGoal = distGoal <= 8.0 ? myPos : baseGoal
wto_sm_set_state(now, WTO_STATE_MARCH, marchGoal, marchSpd, "march_task", distXZ, slot)
@@ -121,6 +121,16 @@ export interface GroundAiConfig {
readonly targetStickinessSec: number;
readonly peekCooldownSec: number;
};
readonly estimation: {
readonly watchMinSec: number;
readonly watchMaxSec: number;
readonly velSampleMinSpanSec: number;
readonly velStableSpanSec: number;
readonly velJumpResetMps: number;
readonly baseAimSigmaM: number;
readonly leadErrorFrac: number;
readonly maxBiasM: number;
};
readonly fireControl: {
readonly maxEngageRangeM: number;
readonly closeRangeM: number;
@@ -278,6 +288,14 @@ function collectConfigEntries(c: GroundAiConfig): readonly DasEntry[] {
['WTO_AI_TACTICS_MEMORY_TTL_SEC', 'float', c.tactics.memoryTtlSec],
['WTO_AI_TACTICS_STICKY_SEC', 'float', c.tactics.targetStickinessSec],
['WTO_AI_TACTICS_PEEK_COOLDOWN_SEC', 'float', c.tactics.peekCooldownSec],
['WTO_AI_EST_WATCH_MIN_SEC', 'float', c.estimation.watchMinSec],
['WTO_AI_EST_WATCH_MAX_SEC', 'float', c.estimation.watchMaxSec],
['WTO_AI_EST_MIN_SPAN_SEC', 'float', c.estimation.velSampleMinSpanSec],
['WTO_AI_EST_STABLE_SPAN_SEC', 'float', c.estimation.velStableSpanSec],
['WTO_AI_EST_JUMP_RESET_MPS', 'float', c.estimation.velJumpResetMps],
['WTO_AI_EST_BASE_SIGMA_M', 'float', c.estimation.baseAimSigmaM],
['WTO_AI_EST_LEAD_ERR_FRAC', 'float', c.estimation.leadErrorFrac],
['WTO_AI_EST_MAX_BIAS_M', 'float', c.estimation.maxBiasM],
['WTO_AI_FC_MAX_RANGE_M', 'float', c.fireControl.maxEngageRangeM],
['WTO_AI_FC_CLOSE_RANGE_M', 'float', c.fireControl.closeRangeM],
['WTO_AI_FC_MID_RANGE_M', 'float', c.fireControl.midRangeM],