From 314bdfe68e7789254deb907844983b1a95e0f852 Mon Sep 17 00:00:00 2001 From: N0VAN0M4LY <224130499+N0VAN0M4LY@users.noreply.github.com> Date: Thu, 3 Dec 2026 17:47:10 +0800 Subject: [PATCH] feat(ground-ai): add hull state machine and two-beat turn driving Replace the legacy tactics posture heuristics with an explicit per-bot hull state machine driven by WtoTaskOrder and the 100/300/800 m distance tiers, and fix chassis steering bugs: - Add the stateMachine section to tuning/ground-ai.jsonc (preaimAngleDeg, shortHaltMaxSec, shortHaltCooldownSec, turnLaunchSpeedMps), validated in ground-ai-tuning.ts and compiled into WTO_AI_SM_* constants. - Replace WTO_POSTURE_* with the unified WTO_STATE_* hull state enum in wto_ai_types_common.das and decouple wto_perceive_update into wto_ai_runtime.das so perception runs independently of hull tactics. - Rewrite wto_ai_tactics_common.das as a priority-arbitrated state machine: safety/SPAA -> ridge withdrawal -> active SHORT_HALT budget (3 s limit with cooldown on timeout) -> crowd dispersion -> distance-tier combat (RUN_AND_GUN <=100 m and high-urgency 100-300 m slow-move-fire; PREAIM keeping the hull moving while gun reloads or turret error >8 deg; SHORT_HALT only when ready and permitted by order.maxStopRangeM / 800 m 4 s window; RELOAD_ADVANCE when reloading away from cover) -> MARCH. Log every state transition with reason, distance and speed. - Fix the inverted neutral-pivot condition in wto_ai_drive_common.das, add 2nd-gear straight-launch before full steering when turning with open front clearance, and use full throttle when accelerating to target speed so the automatic gearbox upshifts cleanly. Verified root and launcher type checks, isolated 2.61.0.58 build (21 ground AI modules packed), and clean in-engine daScript compilation/load (wto_ai_runtime.das loaded in 195 ms, 0 compile errors). Live battle acceptance deferred until the full pipeline is wired. --- apps/server/src/tuning/ground-ai-tuning.ts | 10 + apps/server/tuning/ground-ai.jsonc | 8 + game-ai/ground/wto_ai_drive_common.das | 27 +- game-ai/ground/wto_ai_fire_common.das | 2 +- game-ai/ground/wto_ai_nav_common.das | 6 +- game-ai/ground/wto_ai_route_common.das | 3 +- game-ai/ground/wto_ai_runtime.das | 11 +- game-ai/ground/wto_ai_tactics_common.das | 293 +++++++++--------- game-ai/ground/wto_ai_types_common.das | 24 +- .../patcher/src/ground-ai/ground-ai-config.ts | 10 + 10 files changed, 219 insertions(+), 175 deletions(-) diff --git a/apps/server/src/tuning/ground-ai-tuning.ts b/apps/server/src/tuning/ground-ai-tuning.ts index ce70b4c..3940ddc 100644 --- a/apps/server/src/tuning/ground-ai-tuning.ts +++ b/apps/server/src/tuning/ground-ai-tuning.ts @@ -40,6 +40,7 @@ export function readGroundAiTuning(reader: TuningReader): GroundAiTuning { terrain: readTerrainSection(reader.object('terrain')), navigation: readNavigationSection(reader.object('navigation')), perception: readPerceptionSection(reader.object('perception')), + stateMachine: readStateMachineSection(reader.object('stateMachine')), tactics: readTacticsSection(reader.object('tactics')), fireControl: readFireControlSection(reader.object('fireControl')), diagnostics: { @@ -189,6 +190,15 @@ function readPerceptionSection(perc: TuningReader): GroundAiTuning['perception'] }; } +function readStateMachineSection(sm: TuningReader): GroundAiTuning['stateMachine'] { + return { + preaimAngleDeg: sm.number('preaimAngleDeg', { min: 1.0, max: 30.0 }), + shortHaltMaxSec: sm.number('shortHaltMaxSec', { min: 0.5, max: 12.0 }), + shortHaltCooldownSec: sm.number('shortHaltCooldownSec', { min: 0.5, max: 20.0 }), + turnLaunchSpeedMps: sm.number('turnLaunchSpeedMps', { min: 0.5, max: 6.0 }), + }; +} + function readTacticsSection(tactics: TuningReader): GroundAiTuning['tactics'] { return { visionRangeM: tactics.number('visionRangeM', { min: 200, max: 3500 }), diff --git a/apps/server/tuning/ground-ai.jsonc b/apps/server/tuning/ground-ai.jsonc index 5334a2e..0cf9fa8 100644 --- a/apps/server/tuning/ground-ai.jsonc +++ b/apps/server/tuning/ground-ai.jsonc @@ -108,6 +108,14 @@ "peripheralCloseM": 100.0 }, + // Per-bot hull state machine timings and thresholds (offline values). + "stateMachine": { + "preaimAngleDeg": 8.0, + "shortHaltMaxSec": 3.0, + "shortHaltCooldownSec": 4.0, + "turnLaunchSpeedMps": 2.1 + }, + "tactics": { "visionRangeM": 1250.0, "visionFovDeg": 115.0, diff --git a/game-ai/ground/wto_ai_drive_common.das b/game-ai/ground/wto_ai_drive_common.das index 75ed10a..1d0df91 100644 --- a/game-ai/ground/wto_ai_drive_common.das +++ b/game-ai/ground/wto_ai_drive_common.das @@ -74,18 +74,19 @@ def private wto_compute_pivot_axes(cmd : WtoDriveCmd const&; spec : WtoVehicleSp outBrk = 1.0 outStr = turnSign * WTO_AI_NAV_STEER_SIGN return - let frontRoom = cmd.frontClearM >= spec.halfLen + 2.4 - if spec.canPivot && cmd.frontClearM >= spec.halfLen + 1.2 && cmd.rearClearM >= spec.halfLen + 1.0 && abs(omega) >= 0.22 + let openFront = cmd.frontClearM >= spec.halfLen + 3.5 + if openFront + // Two-beat turn micro: launch straight to 2nd gear before applying full steering. + outThr = 1.0 + outStr = abs(vFwd) < WTO_AI_SM_TURN_LAUNCH_MPS ? 0.0 : (turnSign * WTO_AI_NAV_STEER_SIGN) + return + if spec.canPivot && cmd.frontClearM >= spec.halfLen + 1.2 && cmd.rearClearM >= spec.halfLen + 1.0 outThr = 0.0 outStr = clamp(turnSign - omega * 0.35, -1.0, 1.0) * WTO_AI_NAV_STEER_SIGN return - if frontRoom - outThr = vFwd < 1.9 ? 0.72 : 0.42 - outStr = (vFwd < 1.4 && abs(omega) < 0.22 ? 0.35 : 1.0) * turnSign * WTO_AI_NAV_STEER_SIGN - else - // Tight front obstacle: execute clean 3-point reverse turn instead of ramming the wall! - outThr = vFwd > -1.7 ? -0.78 : -0.48 - outStr = -(vFwd > -1.2 && abs(omega) < 0.22 ? 0.35 : 1.0) * turnSign * WTO_AI_NAV_STEER_SIGN + // Tight front obstacle: execute clean 3-point reverse turn instead of ramming the wall. + outThr = vFwd > -WTO_AI_SM_TURN_LAUNCH_MPS ? -1.0 : -0.6 + outStr = (abs(vFwd) < 1.2 ? 0.0 : -turnSign) * WTO_AI_NAV_STEER_SIGN [never_inline] def private wto_compute_reverse_axes(cmd : WtoDriveCmd const&; spec : WtoVehicleSpec const&; @@ -125,11 +126,13 @@ def private wto_compute_cruise_axes(cmd : WtoDriveCmd const&; spec : WtoVehicleS if cmd.frontClearM < 12.0 vLimit = min(vLimit, max(2.2, (cmd.frontClearM - 2.0) * 0.75)) let vErr = vLimit - vFwd - if vErr < -1.8 + if vErr < -1.5 outThr = 0.0 - outBrk = clamp((-vErr - 1.5) * 0.35, 0.2, 1.0) + outBrk = clamp((-vErr - 1.2) * 0.35, 0.2, 1.0) + elif vErr >= 0.6 + outThr = 1.0 else - outThr = clamp(0.32 + vErr * 0.28, 0.12, 1.0) + outThr = clamp(0.45 + vErr * 0.45, 0.15, 1.0) [never_inline] def private wto_release_phys_owner(gm : IGroundModel const?; var actor : VehiclePhysActor&; diff --git a/game-ai/ground/wto_ai_fire_common.das b/game-ai/ground/wto_ai_fire_common.das index 9b73569..9b3539e 100644 --- a/game-ai/ground/wto_ai_fire_common.das +++ b/game-ai/ground/wto_ai_fire_common.das @@ -234,7 +234,7 @@ def public wto_fire_update(world : WtoWorldSnap const&; var unit : Unit?; var aimPt = muzzlePos + hFwd * 50.0 var distToTgt = 9999.0 let engageValid = (slot.perceive.hasClearLos && !!slot.perceive.targetEid && !slot.perceive.targetIsAir && - !(slot.spec.role == WTO_ROLE_SPAA && slot.tactics.posture == WTO_POSTURE_RETREAT)) + !(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) elif !!slot.perceive.targetEid && (now - slot.perceive.lastSeenAt) <= WTO_AI_TACTICS_MEMORY_TTL_SEC diff --git a/game-ai/ground/wto_ai_nav_common.das b/game-ai/ground/wto_ai_nav_common.das index 085891d..8aa0e83 100644 --- a/game-ai/ground/wto_ai_nav_common.das +++ b/game-ai/ground/wto_ai_nav_common.das @@ -196,8 +196,8 @@ def private wto_check_stuck_watchdog(var world : WtoWorldSnap&; now : float; [never_inline] def private wto_try_reverse_drive(world : WtoWorldSnap const&; now : float; myPos, hullFwd : float3; var slot : WtoBotSlot&) : bool - let posMode = slot.tactics.posture - let wantTacRev = posMode == WTO_POSTURE_REVERSE_WITHDRAW || posMode == WTO_POSTURE_PEEK_BACK + let stMode = slot.tactics.state + let wantTacRev = stMode == WTO_STATE_RIDGE_WITHDRAW || stMode == WTO_STATE_RETREAT_COVER if !wantTacRev && now >= slot.nav.reverseUntil return false let revGoal = wantTacRev ? slot.tactics.moveGoal : slot.nav.reverseAnchor @@ -221,7 +221,7 @@ def public wto_nav_update(var world : WtoWorldSnap&; now : float; slot.nav.rearClearM = wto_terrain_hard_ray(probeBase, -hullFwd, 18.0) slot.nav.cliffAhead = wto_terrain_has_cliff_ahead(myPos, hullFwd, WTO_AI_TERRAIN_CREST_LOOKAHEAD_M) - if slot.tactics.posture == WTO_POSTURE_ENGAGE_HALT || slot.tactics.desiredSpeedMps <= 0.05 + if slot.tactics.state == WTO_STATE_SHORT_HALT || slot.tactics.desiredSpeedMps <= 0.05 slot.nav.stuckCheckAt = now + WTO_AI_NAV_STUCK_WINDOW_SEC wto_handle_stationary_engage(myPos, hullFwd, slot) return diff --git a/game-ai/ground/wto_ai_route_common.das b/game-ai/ground/wto_ai_route_common.das index 3ca2e72..d51bc79 100644 --- a/game-ai/ground/wto_ai_route_common.das +++ b/game-ai/ground/wto_ai_route_common.das @@ -156,7 +156,8 @@ def public wto_route_select_waypoint(world : WtoWorldSnap const&; now : float; return rt.detourPos rt.detourValid = false - let useWing = slot.tactics.posture == WTO_POSTURE_MARCH + let st = slot.tactics.state + let useWing = st == WTO_STATE_MARCH || st == WTO_STATE_PREAIM || st == WTO_STATE_RELOAD_ADVANCE if useWing wto_ensure_wing_relay(world, myPos, finalGoal, slot) if useWing && rt.wingRelayValid && wto_xz_dist_sq(myPos, rt.wingRelayPos) <= 625.0 diff --git a/game-ai/ground/wto_ai_runtime.das b/game-ai/ground/wto_ai_runtime.das index 67bd9bb..fd20eea 100644 --- a/game-ai/ground/wto_ai_runtime.das +++ b/game-ai/ground/wto_ai_runtime.das @@ -28,6 +28,7 @@ require %appGame.wtoai.wto_ai_specs_common require %appGame.wtoai.wto_ai_world_common require %appGame.wtoai.wto_ai_crowd_common require %appGame.wtoai.wto_ai_commander_common +require %appGame.wtoai.wto_ai_perceive_common require %appGame.wtoai.wto_ai_tactics_common require %appGame.wtoai.wto_ai_nav_common require %appGame.wtoai.wto_ai_drive_common @@ -111,7 +112,7 @@ def private wto_log_bot_and_cap_samples() if !g_bots[i].used || sampled >= 2 continue assume b = g_bots[i] - print("WTO_AI|BOT_SAMPLE|eid={uint(b.eid)}|role={b.spec.role}|stab={b.spec.hasVertStab}|v0={b.spec.muzzleSpeedMps}|pos={b.tactics.posture}|allyD={b.crowd.nearestAllyDistM}|clust={b.crowd.clusterAllyCount}|ridge={b.tactics.onExposedRidge}|los={b.perceive.hasClearLos}|fc={b.fire.gunReady}/{b.fire.reloading}/{b.fire.lastAligned}|err={b.fire.lastAimErrDeg}|omB={b.fire.barrelOmegaDegSec}|mode={b.driveCmd.mode}|v={b.drive.lastVFwd}|clr={b.nav.frontClearM}/{b.nav.rearClearM}|wp={b.route.corridorIdx}/{b.route.corridorLen}|proj={b.route.lastStartOk}/{b.route.lastGoalOk}\n") + print("WTO_AI|BOT_SAMPLE|eid={uint(b.eid)}|role={b.spec.role}|stab={b.spec.hasVertStab}|v0={b.fire.activeSpeedMps}|st={b.tactics.state}|allyD={b.crowd.nearestAllyDistM}|clust={b.crowd.clusterAllyCount}|ridge={b.tactics.onExposedRidge}|los={b.perceive.hasClearLos}|fc={b.fire.gunReady}/{b.fire.reloading}/{b.fire.lastAligned}|err={b.fire.lastAimErrDeg}|omB={b.fire.barrelOmegaDegSec}|mode={b.driveCmd.mode}|v={b.drive.lastVFwd}|clr={b.nav.frontClearM}/{b.nav.rearClearM}|wp={b.route.corridorIdx}/{b.route.corridorLen}|proj={b.route.lastStartOk}/{b.route.lastGoalOk}\n") sampled++ for c in range(g_world.capCount) assume z = g_world.caps[c] @@ -142,8 +143,8 @@ def private wto_log_telemetry(now : float) roles[clamp(b.spec.role, 0, 4)]++ routeB += b.drive.routeBOwned ? 1 : 0 revNow += b.driveCmd.mode == WTO_DRIVE_REVERSE ? 1 : 0 - engNow += b.tactics.posture == WTO_POSTURE_ENGAGE_HALT ? 1 : 0 - dispNow += b.tactics.posture == WTO_POSTURE_DISPERSE ? 1 : 0 + engNow += b.tactics.state == WTO_STATE_SHORT_HALT ? 1 : 0 + dispNow += b.tactics.state == WTO_STATE_DISPERSE ? 1 : 0 ridgeNow += b.tactics.onExposedRidge ? 1 : 0 revEvents += b.nav.reverseCount ridgeWithdraws += b.nav.ridgeWithdrawEvents @@ -259,7 +260,9 @@ def wto_ai_pipeline_es(act : UpdateStageInfoAct; eid : EntityId; var unit__ref : wto_specs_load(eid, unit__className, unit, gm, slot.spec) if now >= slot.nextTacticsAt slot.nextTacticsAt = now + WTO_AI_TACTICS_TICK_SEC - wto_tactics_update(g_world, now, WTO_AI_TACTICS_TICK_SEC, unit.pos, unit.unitTm[0], unit.isBurn, slot, g_crowd) + if WTO_AI_LAYER_TACTICS || WTO_AI_LAYER_FIRE_CONTROL + wto_perceive_update(g_world, now, WTO_AI_TACTICS_TICK_SEC, unit.pos, unit.unitTm[0], slot) + wto_tactics_update(g_world, now, unit.pos, unit.unitTm[0], unit.isBurn, slot, g_crowd) if now >= slot.nextNavAt slot.nextNavAt = now + WTO_AI_NAV_TICK_SEC wto_nav_update(g_world, now, unit.pos, unit.unitTm[0], slot) diff --git a/game-ai/ground/wto_ai_tactics_common.das b/game-ai/ground/wto_ai_tactics_common.das index 10a6765..37244e0 100644 --- a/game-ai/ground/wto_ai_tactics_common.das +++ b/game-ai/ground/wto_ai_tactics_common.das @@ -1,5 +1,6 @@ -// Tactical posture arbitrator: arbitrates survival retreat, SPAA priority, high-ground cliff -// ridge dwell/reverse discipline, anti-clustering dispersion, and stabilizer-aware combat halts. +// Per-bot hull state machine: arbitrates safety, ridge withdrawal, ongoing short-halt budget, +// crowd dispersion, and distance-tier x task-order movement/shooting (MARCH, RUN_AND_GUN, +// PREAIM, SHORT_HALT, RELOAD_ADVANCE). Every state transition logs its reason. options indenting = 2 options no_global_heap = true module wto_ai_tactics_common shared @@ -8,198 +9,196 @@ require ecs require math require %appGame.wtoai.wto_ai_config_common require %appGame.wtoai.wto_ai_math_common +require %appGame.wtoai.wto_ai_order_common +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_world_common require %appGame.wtoai.wto_ai_crowd_common -require %appGame.wtoai.wto_ai_perceive_common + +[never_inline] +def private wto_sm_set_state(now : float; newState : int; goalPos : float3; speedMps : float; + reason : string; distXZ : float; var slot : WtoBotSlot&) + assume tac = slot.tactics + if tac.state != newState + if WTO_AI_DIAG_TELEMETRY + print("WTO_AI|STATE|t={now}|eid={uint(slot.eid)}|from={tac.state}|to={newState}|reason={reason}|dist={distXZ}|v={slot.drive.lastVFwd}\n") + tac.state = newState + tac.stateEnteredAt = now + if newState == WTO_STATE_SHORT_HALT + tac.haltEnterAt = now + tac.haltStartShots = slot.fire.shotCount + tac.moveGoal = goalPos + tac.desiredSpeedMps = speedMps [never_inline] def private wto_friendly_retreat_dir(world : WtoWorldSnap const&; army : int; myPos, threatDir : float3) : float3 if world.teamSpawnValid[army] - let toSpawn = world.teamSpawnCenter[army] - myPos - if wto_xz_len(toSpawn) > 25.0 - return wto_xz_normalize(toSpawn, -threatDir) - return -wto_xz_normalize(threatDir, float3(1.0, 0.0, 0.0)) + let toSpawn = wto_xz_normalize(world.teamSpawnCenter[army] - myPos, -threatDir) + let blended = toSpawn * 0.65 - threatDir * 0.35 + return wto_xz_normalize(blended, toSpawn) + return wto_xz_normalize(-threatDir, float3(1.0, 0.0, 0.0)) [never_inline] -def private wto_latch_reverse_withdraw(world : WtoWorldSnap const&; now : float; myPos, backDir : float3; - lateralShift : float; var slot : WtoBotSlot&) - let bDir = wto_xz_normalize(backDir, float3(-1.0, 0.0, 0.0)) - let lat = float3(-bDir.z, 0.0, bDir.x) - let side = ((uint(slot.eid) & 1u) == 0u ? 1.0 : -1.0) * lateralShift - let revDist = WTO_AI_NAV_TAC_REV_DIST_M - var anchor = myPos + bDir * revDist + lat * side - anchor = wto_clamp_battle_xz(anchor, world.battleCenter, world.battleRadius, 35.0) - if !wto_terrain_point_valid(slot.army, anchor) - anchor = myPos + bDir * max(16.0, revDist * 0.6) - slot.tactics.withdrawAnchor = anchor - slot.tactics.withdrawUntil = now + WTO_AI_NAV_TAC_REV_MAX_SEC - slot.tactics.posture = WTO_POSTURE_REVERSE_WITHDRAW - slot.tactics.moveGoal = anchor - slot.tactics.desiredSpeedMps = slot.spec.vMaxRev - slot.nav.ridgeWithdrawEvents++ - -[never_inline] -def private wto_handle_ridge_discipline(world : WtoWorldSnap const&; now : float; - myPos, threatDir : float3; var slot : WtoBotSlot&) : bool +def private wto_sm_handle_safety_or_spaa(world : WtoWorldSnap const&; now : float; + myPos, threatDir : float3; isBurn : bool; + distXZ : float; var slot : WtoBotSlot&) : bool assume tac = slot.tactics - let backDir = wto_friendly_retreat_dir(world, slot.army, myPos, threatDir) - if now < tac.withdrawUntil - if wto_xz_dist_sq(myPos, tac.withdrawAnchor) > 36.0 - tac.posture = WTO_POSTURE_REVERSE_WITHDRAW - tac.moveGoal = tac.withdrawAnchor - tac.desiredSpeedMps = slot.spec.vMaxRev + assume p = slot.perceive + tac.spaaYieldAir = false + if slot.spec.role == WTO_ROLE_SPAA + if p.hasClearLos && p.targetIsAir && !!p.targetEid + tac.spaaYieldAir = true + wto_sm_set_state(now, WTO_STATE_MARCH, myPos, 0.0, "spaa_air_engage", distXZ, slot) return true - tac.withdrawUntil = -100.0 - let onRidge = wto_terrain_is_exposed_ridge(myPos, threatDir, backDir) - if !onRidge + if p.hasClearLos && !p.targetIsAir && !!p.targetEid && distXZ < 220.0 + let backDir = wto_friendly_retreat_dir(world, slot.army, myPos, threatDir) + let goal = wto_clamp_battle_xz(myPos + backDir * 70.0, world.battleCenter, world.battleRadius, 40.0) + wto_sm_set_state(now, WTO_STATE_DISABLED, goal, slot.spec.vMaxFwd, "spaa_evade_tank", distXZ, slot) + return true + if slot.fire.gunDamaged || isBurn + let backDir = wto_friendly_retreat_dir(world, slot.army, myPos, threatDir) + let goal = wto_clamp_battle_xz(myPos + backDir * 75.0, world.battleCenter, world.battleRadius, 40.0) + wto_sm_set_state(now, WTO_STATE_DISABLED, goal, slot.spec.vMaxFwd, slot.fire.gunDamaged ? "gun_damaged" : "burning", distXZ, slot) + return true + return false + +[never_inline] +def private wto_sm_handle_ridge(world : WtoWorldSnap const&; now : float; + myPos, threatDir : float3; distXZ : float; + var slot : WtoBotSlot&) : bool + assume tac = slot.tactics + if now < tac.withdrawUntil + wto_sm_set_state(now, WTO_STATE_RIDGE_WITHDRAW, tac.withdrawAnchor, max(2.2, slot.spec.vMaxRev), "ridge_hold", distXZ, slot) + return true + let backDir = wto_friendly_retreat_dir(world, slot.army, myPos, threatDir) + let exposed = wto_terrain_is_exposed_ridge(myPos, threatDir, backDir) + if !exposed tac.onExposedRidge = false return false if !tac.onExposedRidge tac.onExposedRidge = true tac.ridgeEnterAt = now tac.ridgeShotsStart = slot.fire.shotCount - let shotsOnRidge = slot.fire.shotCount - tac.ridgeShotsStart - let dwellSec = now - tac.ridgeEnterAt - let mustLeave = (shotsOnRidge >= WTO_AI_TERRAIN_RIDGE_MAX_SHOTS || - dwellSec >= WTO_AI_TERRAIN_RIDGE_MAX_DWELL_SEC || slot.fire.pitchBlocked) - if mustLeave && slot.spec.vMaxRev >= 1.6 + let dwellOver = (now - tac.ridgeEnterAt) >= WTO_AI_TERRAIN_RIDGE_MAX_DWELL_SEC + let shotsOver = (slot.fire.shotCount - tac.ridgeShotsStart) >= WTO_AI_TERRAIN_RIDGE_MAX_SHOTS + if dwellOver || shotsOver || slot.fire.pitchBlocked + let lat = float3(-backDir.z, 0.0, backDir.x) + let side = (uint(slot.eid) & 1u) == 0u ? 1.0 : -1.0 + var anc = myPos + backDir * WTO_AI_NAV_TAC_REV_DIST_M + lat * (side * 16.0) + anc = wto_clamp_battle_xz(anc, world.battleCenter, world.battleRadius, 40.0) + tac.withdrawAnchor = anc + tac.withdrawUntil = now + WTO_AI_NAV_TAC_REV_MAX_SEC tac.onExposedRidge = false - wto_latch_reverse_withdraw(world, now, myPos, backDir, 16.0, slot) + slot.nav.ridgeWithdrawEvents++ + wto_sm_set_state(now, WTO_STATE_RIDGE_WITHDRAW, anc, max(2.2, slot.spec.vMaxRev), "ridge_withdraw", distXZ, slot) return true - // Brief ridge snipe window: hold before the cliff edge; never advance toward the drop-off! - tac.posture = WTO_POSTURE_ENGAGE_HALT - tac.moveGoal = myPos - tac.desiredSpeedMps = 0.0 - return true + return false [never_inline] -def private wto_handle_crippled_or_spaa(world : WtoWorldSnap const&; now : float; - myPos, hullFwd, threatDir : float3; - isBurn : bool; var slot : WtoBotSlot&) : bool +def private wto_sm_continue_short_halt(now : float; myPos : float3; hasGroundTgt : bool; + distXZ : float; var slot : WtoBotSlot&) : bool assume tac = slot.tactics - assume p = slot.perceive - tac.spaaYieldAir = slot.spec.role == WTO_ROLE_SPAA && p.hasClearLos && p.targetIsAir - if tac.spaaYieldAir - tac.posture = WTO_POSTURE_ENGAGE_HALT - tac.moveGoal = myPos - tac.desiredSpeedMps = 0.0 - return true - let crippled = isBurn || slot.fire.gunDamaged - let spaaThreatened = (slot.spec.role == WTO_ROLE_SPAA && p.hasClearLos && !p.targetIsAir && - wto_xz_dist_sq(myPos, p.knownPos) < wto_sq(380.0)) - if !crippled && !spaaThreatened + if tac.state != WTO_STATE_SHORT_HALT return false - let backDir = wto_friendly_retreat_dir(world, slot.army, myPos, threatDir) - let enemyInFront = p.hasClearLos && dot(threatDir, hullFwd) > -0.2 - if enemyInFront && slot.spec.vMaxRev >= 2.0 - if now >= tac.withdrawUntil - wto_latch_reverse_withdraw(world, now, myPos, backDir, 12.0, slot) - else - tac.posture = WTO_POSTURE_REVERSE_WITHDRAW - tac.moveGoal = tac.withdrawAnchor - tac.desiredSpeedMps = slot.spec.vMaxRev - return true - var retGoal = wto_clamp_battle_xz(myPos + backDir * 85.0, world.battleCenter, world.battleRadius, 40.0) - let _valid = wto_terrain_point_valid(slot.army, retGoal) - tac.posture = WTO_POSTURE_RETREAT - tac.moveGoal = retGoal - tac.desiredSpeedMps = slot.spec.vMaxFwd + if slot.fire.shotCount > tac.haltStartShots || slot.fire.reloading + return false + if !hasGroundTgt || distXZ > WTO_AI_FC_MAX_RANGE_M + return false + let maxStop = slot.order.valid ? slot.order.maxStopRangeM : WTO_AI_FC_MAX_RANGE_M + if distXZ > maxStop + return false + if distXZ > WTO_AI_FC_LONG_RANGE_M && (slot.perceive.goodLosSec < WTO_AI_FC_LONG_WINDOW_SEC || slot.perceive.visiblePointCount < 2) + return false + if (now - tac.haltEnterAt) >= WTO_AI_SM_SHORT_HALT_MAX_SEC + tac.shortHaltCooldownUntil = now + WTO_AI_SM_SHORT_HALT_COOLDOWN_SEC + return false + wto_sm_set_state(now, WTO_STATE_SHORT_HALT, myPos, 0.0, "halt_continue", distXZ, slot) return true [never_inline] -def private wto_handle_dispersion(world : WtoWorldSnap const&; now : float; - myPos, threatDir : float3; var slot : WtoBotSlot&; - var crowdSummary : WtoCrowdSummary&) : bool +def private wto_sm_handle_dispersion(world : WtoWorldSnap const&; now : float; + myPos, threatDir : float3; distXZ : float; + var slot : WtoBotSlot&; var crowdSummary : WtoCrowdSummary&) : bool assume tac = slot.tactics - if slot.fire.settleHoldSec > 0.08 && slot.perceive.hasClearLos + if distXZ <= WTO_AI_FC_CLOSE_RANGE_M return false if now < tac.disperseUntil && wto_xz_dist_sq(myPos, tac.disperseGoal) > 25.0 - tac.posture = WTO_POSTURE_DISPERSE - tac.moveGoal = tac.disperseGoal - tac.desiredSpeedMps = slot.spec.vMaxFwd * 0.82 + wto_sm_set_state(now, WTO_STATE_DISPERSE, tac.disperseGoal, slot.spec.vMaxFwd * 0.85, "disperse_hold", distXZ, slot) return true if !slot.crowd.isCrowded return false tac.disperseGoal = wto_crowd_pick_disperse_pos(world, slot.army, slot.eid, myPos, threatDir, slot.crowd) tac.disperseUntil = now + WTO_AI_CROWD_DISPERSE_HOLD_SEC - tac.posture = WTO_POSTURE_DISPERSE - tac.moveGoal = tac.disperseGoal - tac.desiredSpeedMps = slot.spec.vMaxFwd * 0.85 crowdSummary.disperseEvents++ + wto_sm_set_state(now, WTO_STATE_DISPERSE, tac.disperseGoal, slot.spec.vMaxFwd * 0.85, "disperse_start", distXZ, slot) return true [never_inline] -def private wto_handle_combat_or_march(world : WtoWorldSnap const&; now : float; - myPos, threatDir : float3; var slot : WtoBotSlot&) - assume tac = slot.tactics - assume p = slot.perceive - let baseGoal = slot.order.valid ? slot.order.goalPos : world.battleCenter - if p.hasClearLos && !!p.targetEid && !p.targetIsAir - let dist = sqrt(wto_xz_dist_sq(myPos, p.knownPos)) - // Shoot-and-scoot: back into cover during reload when medium-close and reverse gear is capable. - if slot.fire.reloading && dist < 520.0 && slot.spec.vMaxRev >= 2.2 && slot.nav.rearClearM > 8.0 - if now >= tac.peekUntil && now >= tac.peekCooldownUntil - let backDir = wto_friendly_retreat_dir(world, slot.army, myPos, threatDir) - tac.peekHomePos = myPos + backDir * 15.0 - tac.peekUntil = now + 3.6 - tac.peekCooldownUntil = now + WTO_AI_TACTICS_PEEK_COOLDOWN_SEC + 3.6 - if now < tac.peekUntil - tac.posture = WTO_POSTURE_PEEK_BACK - tac.moveGoal = tac.peekHomePos - tac.desiredSpeedMps = slot.spec.vMaxRev - return - // Gun ready: respect task order's maxStopRangeM so assault/flank bots keep advancing! - let stopLimit = slot.order.valid ? slot.order.maxStopRangeM : WTO_AI_FC_MAX_RANGE_M - if !slot.fire.reloading && dist <= min(WTO_AI_FC_MAX_RANGE_M, stopLimit) - if !slot.spec.hasVertStab || dist > 420.0 || slot.spec.isLimitedTraverse - tac.posture = WTO_POSTURE_ENGAGE_HALT - tac.moveGoal = myPos - tac.desiredSpeedMps = 0.0 - return - // Two-plane stabilized tank at medium/close range: smooth low-speed tactical creep/flank! - let lat = float3(-threatDir.z, 0.0, threatDir.x) - let flankSign = (uint(slot.eid) & 1u) == 0u ? 1.0 : -1.0 - let engageGoal = dist > 165.0 ? (myPos + threatDir * 35.0 + lat * (flankSign * 22.0)) : (myPos + lat * (flankSign * 30.0)) - tac.posture = WTO_POSTURE_MARCH - tac.moveGoal = wto_clamp_battle_xz(engageGoal, world.battleCenter, world.battleRadius, 35.0) - tac.desiredSpeedMps = WTO_AI_FC_STAB_CREEP_MPS - return - - var marchGoal = baseGoal - if !p.hasClearLos && wto_xz_dist_sq(myPos, baseGoal) > 6400.0 - var huntPos = baseGoal - if slot.spec.role != WTO_ROLE_SPAA && wto_perceive_pick_hunt_pos(world, slot.army, slot.eid, myPos, now, huntPos) - marchGoal = huntPos - tac.posture = WTO_POSTURE_MARCH - tac.moveGoal = marchGoal - let distGoal = sqrt(wto_xz_dist_sq(myPos, marchGoal)) +def private wto_sm_march_speed(slot : WtoBotSlot const&; distGoal : float) : float if distGoal <= 8.0 - tac.posture = WTO_POSTURE_ENGAGE_HALT - tac.desiredSpeedMps = 0.0 - else - let capScale = slot.order.cautious ? 0.72 : 0.96 - tac.desiredSpeedMps = distGoal < 24.0 ? min(slot.spec.vMaxFwd * 0.55, 6.0) : (slot.spec.vMaxFwd * capScale) + return 0.0 + let capScale = slot.order.cautious ? 0.78 : 0.98 + return distGoal < 24.0 ? min(slot.spec.vMaxFwd * 0.55, 6.0) : (slot.spec.vMaxFwd * capScale) [never_inline] -def public wto_tactics_update(var world : WtoWorldSnap&; now, dt : float; +def private wto_sm_handle_combat(now : float; myPos, baseGoal : float3; + distXZ, distGoal : float; var slot : WtoBotSlot&) : bool + assume tac = slot.tactics + assume fc = slot.fire + let marchSpd = wto_sm_march_speed(slot, distGoal) + if fc.reloading + if wto_order_is_offensive(slot.order.role) || distGoal > 35.0 + wto_sm_set_state(now, WTO_STATE_RELOAD_ADVANCE, baseGoal, max(marchSpd, slot.spec.vMaxFwd * 0.85), "reload_push", distXZ, slot) + return true + return false + if distXZ <= WTO_AI_FC_CLOSE_RANGE_M + let closeSpd = slot.spec.hasVertStab ? (slot.spec.vMaxFwd * 0.92) : min(slot.spec.vMaxFwd * 0.65, WTO_AI_FC_MID_SLOW_MAX_MPS) + wto_sm_set_state(now, WTO_STATE_RUN_AND_GUN, baseGoal, max(2.5, closeSpd), "close_run_gun", distXZ, slot) + return true + let urgentPush = slot.order.urgency == WTO_URGENCY_HIGH || distGoal > 130.0 + if distXZ <= WTO_AI_FC_MID_RANGE_M && urgentPush + let slowCap = min(slot.spec.vMaxFwd * WTO_AI_FC_MID_SLOW_RATIO, WTO_AI_FC_MID_SLOW_MAX_MPS) + wto_sm_set_state(now, WTO_STATE_RUN_AND_GUN, baseGoal, max(2.2, slowCap), "mid_slow_fire", distXZ, slot) + return true + let maxStop = slot.order.valid ? slot.order.maxStopRangeM : WTO_AI_FC_MAX_RANGE_M + if distXZ > maxStop || distXZ > WTO_AI_FC_MAX_RANGE_M + return false + if distXZ > WTO_AI_FC_LONG_RANGE_M && (slot.perceive.goodLosSec < WTO_AI_FC_LONG_WINDOW_SEC || slot.perceive.visiblePointCount < 2) + return false + if now < tac.shortHaltCooldownUntil + return false + let aimReady = fc.gunReady && (fc.lastAimErrDeg <= WTO_AI_SM_PREAIM_DEG || slot.spec.isLimitedTraverse) + if !aimReady + wto_sm_set_state(now, WTO_STATE_PREAIM, baseGoal, marchSpd, "preaim_move", distXZ, slot) + return true + wto_sm_set_state(now, WTO_STATE_SHORT_HALT, myPos, 0.0, "short_halt_ready", distXZ, slot) + return true + +[never_inline] +def public wto_tactics_update(world : WtoWorldSnap const&; now : float; myPos, hullFwd : float3; isBurn : bool; var slot : WtoBotSlot&; var crowdSummary : WtoCrowdSummary&) + let baseGoal = slot.order.valid ? slot.order.goalPos : world.battleCenter + let distGoal = sqrt(wto_xz_dist_sq(myPos, baseGoal)) if !WTO_AI_LAYER_TACTICS - slot.tactics.posture = WTO_POSTURE_MARCH - slot.tactics.moveGoal = slot.order.valid ? slot.order.goalPos : myPos - slot.tactics.desiredSpeedMps = slot.spec.vMaxFwd * 0.9 + wto_sm_set_state(now, WTO_STATE_MARCH, slot.order.valid ? slot.order.goalPos : myPos, slot.spec.vMaxFwd * 0.9, "layer_off", 9999.0, slot) return - wto_perceive_update(world, now, dt, myPos, hullFwd, slot) - let fallbackGoal = slot.order.valid ? slot.order.goalPos : world.battleCenter - let threatRef = !!slot.perceive.targetEid ? slot.perceive.knownPos : fallbackGoal + assume p = slot.perceive + let hasGroundTgt = p.hasClearLos && !!p.targetEid && !p.targetIsAir + let distXZ = hasGroundTgt ? sqrt(wto_xz_dist_sq(myPos, p.knownPos)) : 9999.0 + let threatRef = !!p.targetEid ? p.knownPos : baseGoal let threatDir = wto_xz_normalize(threatRef - myPos, wto_xz_normalize(hullFwd, float3(1.0, 0.0, 0.0))) - if wto_handle_crippled_or_spaa(world, now, myPos, hullFwd, threatDir, isBurn, slot) + if wto_sm_handle_safety_or_spaa(world, now, myPos, threatDir, isBurn, distXZ, slot) return - if wto_handle_ridge_discipline(world, now, myPos, threatDir, slot) + if wto_sm_handle_ridge(world, now, myPos, threatDir, distXZ, slot) return - if wto_handle_dispersion(world, now, myPos, threatDir, slot, crowdSummary) + if wto_sm_continue_short_halt(now, myPos, hasGroundTgt, distXZ, slot) return - wto_handle_combat_or_march(world, now, myPos, threatDir, slot) + if wto_sm_handle_dispersion(world, now, myPos, threatDir, distXZ, slot, crowdSummary) + return + if hasGroundTgt && wto_sm_handle_combat(now, myPos, baseGoal, distXZ, distGoal, 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) diff --git a/game-ai/ground/wto_ai_types_common.das b/game-ai/ground/wto_ai_types_common.das index 67aadb4..434c464 100644 --- a/game-ai/ground/wto_ai_types_common.das +++ b/game-ai/ground/wto_ai_types_common.das @@ -22,12 +22,18 @@ let public WTO_ROLE_HEAVY = 2 let public WTO_ROLE_TD = 3 let public WTO_ROLE_SPAA = 4 -let public WTO_POSTURE_MARCH = 0 -let public WTO_POSTURE_DISPERSE = 1 -let public WTO_POSTURE_ENGAGE_HALT = 2 -let public WTO_POSTURE_PEEK_BACK = 4 -let public WTO_POSTURE_REVERSE_WITHDRAW = 5 -let public WTO_POSTURE_RETREAT = 6 +let public WTO_STATE_MARCH = 0 +let public WTO_STATE_RUN_AND_GUN = 1 +let public WTO_STATE_PREAIM = 2 +let public WTO_STATE_SHORT_HALT = 3 +let public WTO_STATE_RETREAT_COVER = 4 +let public WTO_STATE_COVER_RELOAD = 5 +let public WTO_STATE_RELOAD_ADVANCE = 6 +let public WTO_STATE_HULL_ANGLE = 7 +let public WTO_STATE_REPOSITION = 8 +let public WTO_STATE_DISABLED = 9 +let public WTO_STATE_DISPERSE = 10 +let public WTO_STATE_RIDGE_WITHDRAW = 11 let public WTO_DRIVE_HALT = 0 let public WTO_DRIVE_CRUISE = 1 @@ -159,9 +165,13 @@ struct public WtoCrowdSummary [safe_when_uninitialized] struct public WtoTacticsState - posture : int = 0 + state : int = 0 + stateEnteredAt : float = -100.0 moveGoal : float3 = float3(0.0, 0.0, 0.0) desiredSpeedMps : float = 10.0 + haltEnterAt : float = -100.0 + haltStartShots : int = 0 + shortHaltCooldownUntil : float = -100.0 spaaYieldAir : bool = false onExposedRidge : bool = false ridgeEnterAt : float = -100.0 diff --git a/packages/patcher/src/ground-ai/ground-ai-config.ts b/packages/patcher/src/ground-ai/ground-ai-config.ts index bfb17a2..7253433 100644 --- a/packages/patcher/src/ground-ai/ground-ai-config.ts +++ b/packages/patcher/src/ground-ai/ground-ai-config.ts @@ -92,6 +92,12 @@ export interface GroundAiConfig { readonly frontConeHalfDeg: number; readonly peripheralCloseM: number; }; + readonly stateMachine: { + readonly preaimAngleDeg: number; + readonly shortHaltMaxSec: number; + readonly shortHaltCooldownSec: number; + readonly turnLaunchSpeedMps: number; + }; readonly tactics: { readonly visionRangeM: number; readonly visionFovDeg: number; @@ -235,6 +241,10 @@ function collectConfigEntries(c: GroundAiConfig): readonly DasEntry[] { ['WTO_AI_PERC_DECAY_PER_SEC', 'float', c.perception.decayPerSec], ['WTO_AI_PERC_FRONT_CONE_DEG', 'float', c.perception.frontConeHalfDeg], ['WTO_AI_PERC_PERIPH_CLOSE_M', 'float', c.perception.peripheralCloseM], + ['WTO_AI_SM_PREAIM_DEG', 'float', c.stateMachine.preaimAngleDeg], + ['WTO_AI_SM_SHORT_HALT_MAX_SEC', 'float', c.stateMachine.shortHaltMaxSec], + ['WTO_AI_SM_SHORT_HALT_COOLDOWN_SEC', 'float', c.stateMachine.shortHaltCooldownSec], + ['WTO_AI_SM_TURN_LAUNCH_MPS', 'float', c.stateMachine.turnLaunchSpeedMps], ['WTO_AI_TACTICS_VISION_RANGE_M', 'float', c.tactics.visionRangeM], ['WTO_AI_TACTICS_VISION_FOV_DEG', 'float', c.tactics.visionFovDeg], ['WTO_AI_TACTICS_PERIPHERAL_RANGE_M', 'float', c.tactics.peripheralRangeM],