diff --git a/apps/launcher/src/renderer/src/i18n/locales/en.json b/apps/launcher/src/renderer/src/i18n/locales/en.json index a763e0a..be4ecb9 100644 --- a/apps/launcher/src/renderer/src/i18n/locales/en.json +++ b/apps/launcher/src/renderer/src/i18n/locales/en.json @@ -642,8 +642,8 @@ "decayPerSec": "Exposure decay rate per second", "gunFovHalfDeg": "Gun sight half-angle", "nearAwareM": "Close all-round awareness range", - "nearArcDeg": "Close awareness arc around the hull", - "midAwareM": "Commander awareness range (hull front half)", + "nearArcDeg": "Close awareness arc around the barrel", + "midAwareM": "Medium awareness range (barrel front hemisphere)", "nearSpotMul": "Close awareness spotting time multiplier", "midSpotMul": "Commander awareness spotting time multiplier", "lookAroundSec": "Look-around interval", @@ -682,7 +682,8 @@ "minDwellSec": "Minimum time on a chosen look direction", "switchMargin": "Extra danger needed to turn from the engaged target", "scanArcDeg": "Scan arc either side of the route", - "scanPeriodSec": "Scan sweep period" + "scanPeriodSec": "Scan sweep period", + "fixedMountYawSpanDeg": "Max yaw range for hull-mounted guns" }, "behavior": { "scoreIntervalSec": "Behavior scoring interval", diff --git a/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json b/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json index b8b88fd..612b6cb 100644 --- a/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json +++ b/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json @@ -642,8 +642,8 @@ "decayPerSec": "失联曝光每秒衰减率", "gunFovHalfDeg": "瞄准镜视野半角", "nearAwareM": "近距环视感知距离", - "nearArcDeg": "近距感知覆盖车体周围的角度", - "midAwareM": "车长感知距离(车体前半球)", + "nearArcDeg": "以炮口为基准的近距感知角度", + "midAwareM": "中距感知距离(炮口前半球)", "nearSpotMul": "近距感知看清耗时倍数", "midSpotMul": "车长感知看清耗时倍数", "lookAroundSec": "环视间隔", @@ -682,7 +682,8 @@ "minDwellSec": "选定的观察方向至少保持的时间", "switchMargin": "从交战目标转向其他威胁所需高出的危险度", "scanArcDeg": "沿路线向两侧扫视的角度", - "scanPeriodSec": "扫视一个来回的时长" + "scanPeriodSec": "扫视一个来回的时长", + "fixedMountYawSpanDeg": "判定为固定炮座时的最大水平射界" }, "behavior": { "scoreIntervalSec": "行为打分间隔", diff --git a/apps/launcher/src/renderer/src/pages/tuning/bot-tuning-fields.ts b/apps/launcher/src/renderer/src/pages/tuning/bot-tuning-fields.ts index a2a531a..5ed854e 100644 --- a/apps/launcher/src/renderer/src/pages/tuning/bot-tuning-fields.ts +++ b/apps/launcher/src/renderer/src/pages/tuning/bot-tuning-fields.ts @@ -247,6 +247,7 @@ export const BOT_TUNING_GROUPS: readonly BotTuningGroup[] = [ num('turret', 'switchMargin', 0, 3), num('turret', 'scanArcDeg', 0, 180, '°'), num('turret', 'scanPeriodSec', 1, 30, 's'), + num('turret', 'fixedMountYawSpanDeg', 0, 180, '°'), ], }, { diff --git a/apps/launcher/src/shared/schemas/tuning.ts b/apps/launcher/src/shared/schemas/tuning.ts index 1076abc..402b07f 100644 --- a/apps/launcher/src/shared/schemas/tuning.ts +++ b/apps/launcher/src/shared/schemas/tuning.ts @@ -227,6 +227,7 @@ const GroundAiTurretSchema = z.object({ switchMargin: z.number().min(0).max(3), scanArcDeg: z.number().min(0).max(180), scanPeriodSec: z.number().min(1).max(30), + fixedMountYawSpanDeg: z.number().min(0).max(180), }); const GroundAiBehaviorSchema = z.object({ diff --git a/apps/server/src/tuning/ground-ai-tuning.ts b/apps/server/src/tuning/ground-ai-tuning.ts index 399ab50..2da0bca 100644 --- a/apps/server/src/tuning/ground-ai-tuning.ts +++ b/apps/server/src/tuning/ground-ai-tuning.ts @@ -371,6 +371,7 @@ function readTurretSection(turret: TuningReader): GroundAiTuning['turret'] { switchMargin: turret.number('switchMargin', { min: 0, max: 3 }), scanArcDeg: turret.number('scanArcDeg', { min: 0, max: 180 }), scanPeriodSec: turret.number('scanPeriodSec', { min: 1, max: 30 }), + fixedMountYawSpanDeg: turret.number('fixedMountYawSpanDeg', { min: 0, max: 180 }), }; } diff --git a/apps/server/tuning/ground-ai.jsonc b/apps/server/tuning/ground-ai.jsonc index 1e8f6b4..c7f96cf 100644 --- a/apps/server/tuning/ground-ai.jsonc +++ b/apps/server/tuning/ground-ai.jsonc @@ -265,12 +265,10 @@ "normalSpotSec": 0.60, "farSpotSec": 1.45, "decayPerSec": 1.5, - // Layered awareness (decision layer design, section 3): the gun sight sees gunFovHalfDeg either - // side of the barrel; within nearAwareM the crew notices enemies all round the hull except a - // rear blind arc (nearArcDeg wide is covered), and every lookAroundSec for lookAroundHoldSec - // the rear too; within midAwareM the commander covers the hull's front half. Near and mid - // spotting take nearSpotMul / midSpotMul times as long as through the gun sight. An enemy whose - // exposure reaches discoverScore counts as discovered (position known, not yet fireable). + // Every visual arc is relative to the barrel. The sight covers gunFovHalfDeg either side; + // near awareness covers nearArcDeg around the barrel and every lookAroundSec opens the rear + // for lookAroundHoldSec. Mid-distance awareness covers the barrel's front half. + // Near and mid spotting use nearSpotMul and midSpotMul respectively. "gunFovHalfDeg": 30.0, "nearAwareM": 150.0, "nearArcDeg": 270.0, @@ -335,15 +333,15 @@ "hitMul": 2.0 }, - // Turret channel (decision layer design, section 5): with no target in sight the turret looks at - // the most dangerous discovered threat, then at cues, then sweeps scanArcDeg either side of the - // route over scanPeriodSec. It turns from the engaged target to another threat only when that - // one is switchMargin more dangerous, and keeps a chosen look for at least minDwellSec. + // The turret gives visible contacts attention by danger, then checks memory and directional cues. + // While engaged, the competing threat needs switchMargin more danger to take over. + // The turret sweeps the route when it has no contact or cue. "turret": { "minDwellSec": 0.6, "switchMargin": 0.25, "scanArcDeg": 60.0, - "scanPeriodSec": 6.0 + "scanPeriodSec": 6.0, + "fixedMountYawSpanDeg": 60.0 }, // Hull channel: choose a behavior by score, holding each for its configured commitment time diff --git a/game-ai/ground/wto_ai_behavior_common.das b/game-ai/ground/wto_ai_behavior_common.das index 86bd3e2..06ffbb4 100644 --- a/game-ai/ground/wto_ai_behavior_common.das +++ b/game-ai/ground/wto_ai_behavior_common.das @@ -135,7 +135,8 @@ def private wto_bhv_scores(now : float; c : WtoBhvCtx const&; slot : WtoBotSlot let haltRequest = c.haltWanted || c.turnWanted || halting if haltRequest && c.stopRangeOk && !c.atGoal && now >= slot.tactics.shortHaltCooldownUntil let crossfire = float(max(0, c.aimingCount - 1)) - let nearBonus = c.nearThreat ? WTO_AI_BHV_NEAR_HALT_BONUS : 0.0 + let near = c.nearThreat || c.distTarget <= WTO_AI_PERC_NEAR_AWARE_M + let nearBonus = near ? WTO_AI_BHV_NEAR_HALT_BONUS : 0.0 s[WTO_BHV_HALT] = WTO_AI_BHV_HALT + WTO_AI_BHV_URGENCY_W * (1.0 - urgentF) + nearBonus - WTO_AI_BHV_CROSSFIRE * crossfire let coverRetry = now - slot.tactics.coverFailedAt >= WTO_AI_BHV_COVER_RETRY_SEC if slot.fire.reloading && (c.hasTarget || c.remembered) && !slot.spec.isAutocannon && coverRetry diff --git a/game-ai/ground/wto_ai_combat_types_common.das b/game-ai/ground/wto_ai_combat_types_common.das index d173e47..f2cbd77 100644 --- a/game-ai/ground/wto_ai_combat_types_common.das +++ b/game-ai/ground/wto_ai_combat_types_common.das @@ -81,6 +81,7 @@ struct public WtoPerceiveState lastRadioSentAt : float = -100.0 expEids : EntityId[8] expScore : float[8] + expDanger : float[8] expGoodLosSec : float[8] expSeenAt : float[8] expPos : float3[8] @@ -103,14 +104,13 @@ struct public WtoThreatEntry seesMe : bool = false danger : float = 0.0 -// Rebuilt every perception tick; topIdx is the most dangerous entry, topUnseenIdx the most -// dangerous one not seen clearly yet (both -1 when there is none). +// Rebuilt every perception tick, with the highest danger overall and among visible contacts. [safe_when_uninitialized] struct public WtoThreatTable count : int = 0 entries : WtoThreatEntry[8] topIdx : int = -1 - topUnseenIdx : int = -1 + topVisibleIdx : int = -1 // Turret channel (decision layer design, section 5): the threat it is looking at and until when // that look is held. @@ -165,6 +165,8 @@ struct public WtoFireState traverseTurretNo : int = -1 traverse : WtoGunTraverse = WtoGunTraverse() hullAimTarget : EntityId = INVALID_ENTITY_ID + hullAimForPitch : bool = false + mountCanAim : bool = true hullAimDir : float3 = float3(0.0, 0.0, 0.0) gunReady : bool = false reloading : bool = false @@ -181,11 +183,15 @@ struct public WtoFireState activeMassKg : float = 10.0 activeCaliberM : float = 0.09 pitchBlocked : bool = false + pitchAtLimit : bool = false pitchClampSec : float = 0.0 curYawDeg : float = 0.0 curPitchDeg : float = 0.0 prevPitchDeg : float = 0.0 servoInit : bool = false + sightPrimaryIndex : int = -1 + hasBarrelSight : bool = false + barrelSight : float3 = float3(1.0, 0.0, 0.0) aimTargetEid : EntityId = INVALID_ENTITY_ID prevAimOffset : float3 = float3(0.0, 0.0, 0.0) prevAimAt : float = -100.0 diff --git a/game-ai/ground/wto_ai_drive_common.das b/game-ai/ground/wto_ai_drive_common.das index d3b7864..503229f 100644 --- a/game-ai/ground/wto_ai_drive_common.das +++ b/game-ai/ground/wto_ai_drive_common.das @@ -18,6 +18,7 @@ require vehicle require %appGame.wtoai.wto_ai_config_common require %appGame.wtoai.wto_ai_math_common require %appGame.wtoai.wto_ai_types_common +require %appGame.wtoai.wto_ai_nav_types_common [never_inline] def public wto_drive_announce_script_ready() @@ -151,9 +152,9 @@ def private wto_compute_cruise_axes(cmd : WtoDriveCmd const&; spec : WtoVehicleS outThr = clamp(response, 0.0, 1.0) outBrk = clamp(-response, 0.0, 1.0) return - if vErr < -1.5 + if vErr < 0.0 outThr = 0.0 - outBrk = clamp((-vErr - 1.2) * 0.35, 0.2, 1.0) + outBrk = clamp(-vErr / WTO_AI_NAV_MOVING_FIRE_SPEED_RAMP_MPS, 0.0, 1.0) elif vErr >= 0.6 outThr = 1.0 else @@ -193,6 +194,17 @@ def private wto_ensure_phys_owner(gm : IGroundModel const?; var actor : VehicleP st.routeBOwned = true return st.routeBOwned +// Keep the physical brake active even while a pivot or unstick has requested throttle. +def private wto_drive_traffic_brake(vFwd : float; nav : WtoNavState const&; var thr, brk : float&) + if (thr > 0.0 && nav.frontTrafficSpeedCap <= 0.05) || (thr < 0.0 && nav.rearTrafficSpeedCap <= 0.05) + thr = 0.0 + brk = 1.0 + let excess = max(vFwd - nav.frontTrafficSpeedCap, -vFwd - nav.rearTrafficSpeedCap) + if excess > 0.0 + if thr * vFwd > 0.0 + thr = 0.0 + brk = max(brk, clamp(excess / WTO_AI_NAV_MOVING_FIRE_SPEED_RAMP_MPS, 0.0, 1.0)) + [never_inline] def private wto_apply_drive_cmd(var actor : VehiclePhysActor&; fwd, left, velocity : float3; var slot : WtoBotSlot&) @@ -215,6 +227,7 @@ def private wto_apply_drive_cmd(var actor : VehiclePhysActor&; fwd, left, veloci let firingOnMove = slot.tactics.state == WTO_STATE_RUN_AND_GUN let speed = firingOnMove ? length(velocity) : vFwd wto_compute_cruise_axes(cmd, slot.spec, fwd, left, speed, st.omegaYawRad, firingOnMove, thr, str, brk) + wto_drive_traffic_brake(vFwd, slot.nav, thr, brk) st.prevThr = thr st.prevStr = str wto_set_phys_axes(actor, thr, str, brk, hand) diff --git a/game-ai/ground/wto_ai_facing_common.das b/game-ai/ground/wto_ai_facing_common.das index 73c5c25..6df8aec 100644 --- a/game-ai/ground/wto_ai_facing_common.das +++ b/game-ai/ground/wto_ai_facing_common.das @@ -52,8 +52,6 @@ def public wto_face_update(now : float; myPos, hullFwd : float3; var slot : WtoB tac.faceActive = false tac.faceFromThreat = false tac.faceForGun = false - if !slot.perceive.hasClearLos || tac.gunFacingTarget != slot.perceive.targetEid - tac.gunFacingTarget = INVALID_ENTITY_ID var threatPos = myPos if !wto_face_bound(slot.spec) || !wto_face_threat_pos(now, slot, threatPos) return @@ -66,14 +64,12 @@ def public wto_face_update(now : float; myPos, hullFwd : float3; var slot : WtoB [never_inline] def public wto_face_accept_gun(hullFwd : float3; var slot : WtoBotSlot&) assume tac = slot.tactics - if !wto_face_has_request(slot) && !tac.gunFacingTarget + if !wto_face_has_request(slot) return let wanted = wto_xz_normalize(slot.fire.hullAimDir, hullFwd) let allowedAngle = min(90.0, WTO_AI_BHV_HULL_ANGLE_DEG + WTO_AI_BHV_FACE_TOL_DEG) if tac.faceFromThreat && dot(wanted, tac.faceThreatDir) < cos(allowedAngle * WTO_DEG_TO_RAD) - tac.gunFacingTarget = INVALID_ENTITY_ID return - tac.gunFacingTarget = slot.perceive.targetEid tac.faceDir = wanted tac.faceActive = true tac.faceForGun = true diff --git a/game-ai/ground/wto_ai_fire_common.das b/game-ai/ground/wto_ai_fire_common.das index 97dd288..4bcf52b 100644 --- a/game-ai/ground/wto_ai_fire_common.das +++ b/game-ai/ground/wto_ai_fire_common.das @@ -23,6 +23,7 @@ require %appGame.wtoai.wto_ai_world_common require %appGame.wtoai.wto_ai_estimate_common require %appGame.wtoai.wto_ai_fire_gate_common require %appGame.wtoai.wto_ai_traverse_common +require %appGame.wtoai.wto_ai_hull_aim_common require %appGame.wtoai.wto_ai_turret_common require %appGame.wtoai.wto_ai_trigger_common require %appGame.wtoai.wto_ai_fire_aux_common @@ -174,23 +175,45 @@ def private wto_finish_weapon_state(now : float; spec : WtoVehicleSpec const&; a [never_inline] def private wto_sample_muzzle(unit : Unit const?; primaryIndex : int; var outPos, outDir : float3&) : bool - if unit == null || unit.weap == null || primaryIndex < 0 + if unit == null || unit.weap == null return false var sampled = false get_weapons_by_trigger_group(unit.weap.Weapons, WeaponTriggerGroups.TRIGGER_GROUP_PRIMARY) <| $(weapons : array const#) if primaryIndex >= length(weapons) return - assume weapon = weapons[primaryIndex] - if weapon == null - return - var gunTm : float3x4 - weapon_calcShootTm(weapon, unit.unitTm, gunTm) - if length_sq(gunTm[0]) > 0.25 - outPos = gunTm[3] - outDir = normalize(gunTm[0]) - sampled = true + let first = max(0, primaryIndex) + let end = primaryIndex < 0 ? length(weapons) : min(primaryIndex + 1, length(weapons)) + for i in range(first, end) + assume weapon = weapons[i] + if weapon == null || weapon.isDummyGun + continue + var gunTm : float3x4 + weapon_calcShootTm(weapon, unit.unitTm, gunTm) + if wto_is_finite3(gunTm[0]) && length_sq(gunTm[0]) > 0.25 + outPos = gunTm[3] + outDir = normalize(gunTm[0]) + sampled = true + return return sampled +// Sense from the live barrel even when the stock controller is moving the turret. +def public wto_fire_sample_sight(unit : Unit const?; var state : WtoFireState&) + var muzzlePos = float3(0.0, 0.0, 0.0) + var barrelDir = muzzlePos + let primary = state.sightPrimaryIndex + state.hasBarrelSight = wto_sample_muzzle(unit, primary, muzzlePos, barrelDir) + if !state.hasBarrelSight && primary >= 0 + state.hasBarrelSight = wto_sample_muzzle(unit, -1, muzzlePos, barrelDir) + if state.hasBarrelSight + state.barrelSight = barrelDir + +def private wto_fire_sample_primary(unit : Unit const?; var state : WtoFireState&; var muzzlePos, barrelDir : float3&) : bool + if state.sightPrimaryIndex < 0 || !wto_sample_muzzle(unit, state.sightPrimaryIndex, muzzlePos, barrelDir) + return false + state.hasBarrelSight = true + state.barrelSight = barrelDir + return true + def private wto_clear_aim_tracking(var fc : WtoFireState&) fc.aimTargetEid = INVALID_ENTITY_ID fc.aimDriftDegSec = 0.0 @@ -201,7 +224,7 @@ def private wto_clear_aim_tracking(var fc : WtoFireState&) // SPAA vs aircraft only delegates to stock air-target fire control (never ground targets). [never_inline] def private wto_yield_air_fire(var unit : Unit?; var slot : WtoBotSlot&) - wto_set_hull_aim(unit, false, 0.0, unit.unitTm[0], slot) + wto_set_hull_aim(unit, "", false, 0.0, 0.0, unit.unitTm[0], slot) wto_clear_aim_tracking(slot.fire) wto_trig_set_target(INVALID_ENTITY_ID, slot.trigger) var gm = as_gm(unit) @@ -232,10 +255,10 @@ def public wto_fire_update(world : WtoWorldSnap const&; var unit : Unit?; classN return set_unit_attack_type(unit, "dont_aim") let wantSoft = wto_fire_wants_soft(world, slot) - let primaryIndex = wto_inspect_primary_weapon(unit, now, slot.spec, wantSoft, slot.fire) + slot.fire.sightPrimaryIndex = wto_inspect_primary_weapon(unit, now, slot.spec, wantSoft, slot.fire) var muzzlePos = unit.pos + float3(0.0, 1.95, 0.0) var liveBarrelDir = unit.unitTm[0] - let _preSample = wto_sample_muzzle(unit, primaryIndex, muzzlePos, liveBarrelDir) + var muzzleReady = wto_fire_sample_primary(unit, slot.fire, muzzlePos, liveBarrelDir) let hFwd = unit.unitTm[0] var wishWorldDir = hFwd var aimPt = muzzlePos @@ -257,8 +280,9 @@ def public wto_fire_update(world : WtoWorldSnap const&; var unit : Unit?; classN wto_drive_mounted_gun(unit, className, dt, wishYaw, wishPitch, slot) if slot.fire.traverse.known || auxAimed wto_apply_weapon_aim(unit, dt) - let canEngage = engage && distToTgt <= WTO_AI_FC_MAX_RANGE_M && wto_sample_muzzle(unit, primaryIndex, muzzlePos, liveBarrelDir) - wto_set_hull_aim(unit, canEngage, wishYaw, liveBarrelDir, slot) + muzzleReady = wto_fire_sample_primary(unit, slot.fire, muzzlePos, liveBarrelDir) + let canEngage = engage && distToTgt <= WTO_AI_FC_MAX_RANGE_M && muzzleReady + wto_set_hull_aim(unit, className, canEngage, wishYaw, wishPitch, liveBarrelDir, slot) if canEngage wto_fire_gate_try_shoot(world, unit, className, now, distXZ, muzzlePos, aimPt, liveBarrelDir, wishWorldDir, slot, fireBudget) else diff --git a/game-ai/ground/wto_ai_fire_gate_common.das b/game-ai/ground/wto_ai_fire_gate_common.das index 01370be..169f526 100644 --- a/game-ai/ground/wto_ai_fire_gate_common.das +++ b/game-ai/ground/wto_ai_fire_gate_common.das @@ -181,7 +181,7 @@ def public wto_fire_gate_try_shoot(world : WtoWorldSnap const&; var unit : Unit? let turnDegSec = abs(slot.drive.omegaYawRad) * WTO_RAD_TO_DEG let offset = wto_trig_aim_error(liveDir, wishDir) let probOk = wto_trig_evaluate(world, now, unit.pos, length(unit.vel), turnDegSec, distXZ, offset, slot) - let withinTraverse = fc.hullAimTarget == INVALID_ENTITY_ID + let withinTraverse = fc.mountCanAim && fc.hullAimTarget == INVALID_ENTITY_ID if slot.spec.isAutocannon wto_gate_try_burst(world, unit, className, now, distXZ, muzzlePos, aimPt, liveDir, aimErrDeg, withinTraverse, slot, fireBudget) else diff --git a/game-ai/ground/wto_ai_hull_aim_common.das b/game-ai/ground/wto_ai_hull_aim_common.das new file mode 100644 index 0000000..2f950f7 --- /dev/null +++ b/game-ai/ground/wto_ai_hull_aim_common.das @@ -0,0 +1,107 @@ +// The chassis helps a fixed mount that runs out of yaw, or opens an elevation sector for a turret. +options indenting = 2 +options no_global_heap = true +module wto_ai_hull_aim_common shared + +require ecs +require math +require DagorMath +require DagorDataBlock +require Unit +require Weapon +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_traverse_common + +def private wto_pitch_reaches(pitch : float2; wanted : float) : bool + return wto_valid_angle_range(pitch) && wanted >= pitch.x && wanted <= pitch.y + +// Keep some space from a boundary shared by two pitch sectors. +def private wto_pitch_sector_yaw(preferred : float; arc : float2) : float + let margin = min(WTO_AI_FC_BASE_ALIGN_DEG, (arc.y - arc.x) * 0.5) + return clamp(wto_yaw_in_mount_coordinates(preferred, arc), arc.x + margin, arc.y - margin) + +[never_inline] +def private wto_find_pitch_yaw(className : string; triggerNo, weaponIndex : int; + preferred, wantedPitch : float; var traverse : WtoGunTraverse&; + var outYaw : float&) : bool + let arc = traverse.yaw + let preferredYaw = wto_pitch_sector_yaw(preferred, arc) + let preferredPitch = wto_gun_pitch_at_yaw(className, triggerNo, weaponIndex, preferredYaw, traverse) + if wto_pitch_reaches(preferredPitch, wantedPitch) + outYaw = preferredYaw + return true + var best = 360.0 + wto_read_gunner_mount(className, triggerNo, weaponIndex) <| $(mount) + let pitchTable = mount |> datablock_get_block_by_name("limitsTable") + if pitchTable == null + return + for i in 0u..pitchTable.paramCount + if (*pitchTable |> datablock_getParamType(i)) != int(DataBlockParamType.TYPE_POINT4) + continue + let sector = *pitchTable |> datablock_getPoint4(int(i)) + if !wto_pitch_reaches(float2(sector.z, sector.w), wantedPitch) + continue + let yaw = float2(max(arc.x, sector.x), min(arc.y, sector.y)) + if !wto_valid_angle_range(yaw) + continue + let candidate = wto_pitch_sector_yaw(preferred, yaw) + let cost = abs(wto_wrap_deg(candidate - preferred)) + if cost < best + best = cost + outYaw = candidate + return best < 360.0 + +// Prefer a solution that preserves frontal armor if the hull channel has a threat facing. +[never_inline] +def private wto_pitch_turn(unit : Unit const?; className : string; wantedYaw, wantedPitch : float; + var slot : WtoBotSlot&; var outYaw : float&) : bool + assume fc = slot.fire + if !fc.traverse.hasPitchTable || fc.turretNo < 0 || fc.turretNo >= length(unit.weap.turret) + return false + var preferred = wantedYaw + if slot.tactics.faceFromThreat + var armorYaw = 0.0 + var armorPitch = 0.0 + wto_world_to_hull_deg(slot.tactics.faceDir, unit.unitTm[0], unit.unitTm[1], unit.unitTm[2], armorYaw, armorPitch) + preferred = wto_wrap_deg(wantedYaw - armorYaw) + assume turret = unit.weap.turret[fc.turretNo] + return wto_find_pitch_yaw(className, int(turret.triggerNo), int(turret.weaponIndex), preferred, wantedPitch, fc.traverse, outYaw) + +[never_inline] +def public wto_set_hull_aim(unit : Unit const?; className : string; active : bool; + wishYaw, wishPitch : float; liveBarrelDir : float3; var slot : WtoBotSlot&) + assume fc = slot.fire + var target = INVALID_ENTITY_ID + var pitchTurn = false + fc.mountCanAim = true + if active + var arc = fc.traverse.yaw + let hasLimits = fc.traverse.known + let hullMounted = !fc.servoInit || (hasLimits && arc.y - arc.x <= WTO_AI_TURRET_FIXED_MOUNT_SPAN_DEG) + if !fc.servoInit + var fixedYaw = 0.0 + var barrelPitch = 0.0 + wto_world_to_hull_deg(liveBarrelDir, unit.unitTm[0], unit.unitTm[1], unit.unitTm[2], fixedYaw, barrelPitch) + arc = float2(fixedYaw, fixedYaw) + let yaw = wto_yaw_in_mount_coordinates(wishYaw, arc) + let tolerance = arc.x == arc.y ? WTO_AI_FC_BASE_ALIGN_DEG : 0.0 + let limited = hasLimits || !fc.servoInit + let yawBlocked = limited && !wto_full_gun_traverse(arc) && (yaw < arc.x - tolerance || yaw > arc.y + tolerance) + fc.mountCanAim = !yawBlocked && !fc.pitchAtLimit + var mountYaw = 0.5 * (arc.x + arc.y) + let fixedTurn = hullMounted && yawBlocked + if !yawBlocked && fc.pitchAtLimit + pitchTurn = wto_pitch_turn(unit, className, wishYaw, wishPitch, slot, mountYaw) + if fixedTurn || pitchTurn + target = slot.perceive.targetEid + let turn = wto_wrap_deg(wishYaw - mountYaw) + fc.hullAimDir = wto_hull_deg_to_world(turn, 0.0, unit.unitTm[0], unit.unitTm[1], unit.unitTm[2]) + if target != fc.hullAimTarget || pitchTurn != fc.hullAimForPitch + slot.nextNavAt = 0.0 + if WTO_AI_DIAG_TELEMETRY && !!target + print("WTO_AI|HULL_AIM|eid={uint(slot.eid)}|target={uint(target)}|pitch={pitchTurn}\n") + fc.hullAimTarget = target + fc.hullAimForPitch = pitchTurn diff --git a/game-ai/ground/wto_ai_nav_common.das b/game-ai/ground/wto_ai_nav_common.das index 9e66e84..82b4e99 100644 --- a/game-ai/ground/wto_ai_nav_common.das +++ b/game-ai/ground/wto_ai_nav_common.das @@ -24,6 +24,7 @@ require %appGame.wtoai.wto_ai_follow_common require %appGame.wtoai.wto_ai_facing_common require %appGame.wtoai.wto_ai_avoid_common require %appGame.wtoai.wto_ai_traffic_common +require %appGame.wtoai.wto_ai_traffic_geometry_common require %appGame.wtoai.wto_ai_unstick_common [never_inline] @@ -38,6 +39,9 @@ def private wto_nav_halt(myPos, hullFwd : float3; var slot : WtoBotSlot&) [never_inline] def private wto_nav_stand(myPos, hullFwd : float3; var slot : WtoBotSlot&) assume tac = slot.tactics + if tac.state == WTO_STATE_SHORT_HALT && !tac.faceForGun + wto_nav_halt(myPos, hullFwd, slot) + return let limit = tac.faceForGun ? WTO_AI_FC_BASE_ALIGN_DEG : WTO_AI_BHV_FACE_TOL_DEG let errorDeg = acos(clamp(dot(tac.faceDir, hullFwd), -1.0, 1.0)) * WTO_RAD_TO_DEG if tac.faceActive && errorDeg > limit && wto_pivot_drive_mode(slot.spec, slot.nav.frontClearM, slot.nav.rearClearM, true) != WTO_DRIVE_HALT @@ -63,7 +67,8 @@ def private wto_nav_tactical_reverse(navState : int; myPos, hullFwd : float3; va let dir = wto_xz_normalize(goal - myPos, -hullFwd) slot.nav.steerDir = dir slot.nav.stuckCheckAt = -100.0 - wto_drive_cmd_set(slot.driveCmd, WTO_DRIVE_REVERSE, goal, dir, max(2.0, slot.spec.vMaxRev), slot.nav.frontClearM, slot.nav.rearClearM) + let speed = min(slot.spec.vMaxRev, slot.nav.rearTrafficSpeedCap) + wto_drive_cmd_set(slot.driveCmd, WTO_DRIVE_REVERSE, goal, dir, speed, slot.nav.frontClearM, slot.nav.rearClearM) return true // Surface, flags and room to the mesh edge under the bot (battles with a pack only). @@ -160,6 +165,8 @@ def private wto_nav_follow(var world : WtoWorldSnap&; navState : int; now : floa let target = slot.nav.avoidActive ? slot.nav.avoidTarget : pathTarget let dir = wto_xz_normalize(target - myPos, lead) var speed = wto_nav_speed(navState, now, myPos, dir, lookM, narrow, slot) + let trafficLimit = reverse ? slot.nav.rearTrafficSpeedCap : slot.nav.frontTrafficSpeedCap + speed = min(speed, trafficLimit) if reverse speed = min(speed, slot.spec.vMaxRev) slot.nav.steerDir = dir @@ -169,6 +176,20 @@ def private wto_nav_follow(var world : WtoWorldSnap&; navState : int; now : floa let movingIntent = slot.tactics.desiredSpeedMps > 1.2 && now >= slot.nav.yieldUntil wto_unstick_watch(world, navState, now, myPos, hullFwd, myPos + dir * 6.0, movingIntent, slot) +// Check both ends in the actual chassis frame. This also applies during pivots, short halts, +// tactical withdrawal and unstick, when the usual route traffic solver may not run. +[never_inline] +def private wto_nav_clearance(world : WtoWorldSnap const&; myPos, hullFwd : float3; var slot : WtoBotSlot&) + let probeBase = myPos + float3(0.0, 1.25, 0.0) + var traffic = WtoTrafficClearance() + wto_traffic_clearance(world, myPos, hullFwd, slot, traffic) + assume nav = slot.nav + nav.frontClearM = min(wto_terrain_hard_ray(probeBase, hullFwd, 24.0), traffic.frontM) + nav.rearClearM = min(wto_terrain_hard_ray(probeBase, -hullFwd, 18.0), traffic.rearM) + let speed = slot.drive.lastVFwd + nav.frontTrafficSpeedCap = wto_traffic_brake_speed(traffic.frontM, traffic.frontSpeed, max(0.0, speed), slot.spec.halfLen) + nav.rearTrafficSpeedCap = wto_traffic_brake_speed(traffic.rearM, traffic.rearSpeed, max(0.0, -speed), slot.spec.halfLen) + [never_inline] def public wto_nav_update(var world : WtoWorldSnap&; navState, slotIdx : int; now : float; myPos, rawHullFwd : float3; var slot : WtoBotSlot&) @@ -176,9 +197,7 @@ def public wto_nav_update(var world : WtoWorldSnap&; navState, slotIdx : int; no slot.driveCmd.valid = false return let hullFwd = wto_xz_normalize(rawHullFwd, float3(1.0, 0.0, 0.0)) - let probeBase = myPos + float3(0.0, 1.25, 0.0) - slot.nav.frontClearM = wto_terrain_hard_ray(probeBase, hullFwd, 24.0) - slot.nav.rearClearM = wto_terrain_hard_ray(probeBase, -hullFwd, 18.0) + wto_nav_clearance(world, myPos, hullFwd, slot) let st = slot.tactics.state if st != WTO_STATE_MARCH && st != WTO_STATE_RUN_AND_GUN slot.tactics.reverseTravel = false diff --git a/game-ai/ground/wto_ai_nav_types_common.das b/game-ai/ground/wto_ai_nav_types_common.das index 3e92006..41b5db9 100644 --- a/game-ai/ground/wto_ai_nav_types_common.das +++ b/game-ai/ground/wto_ai_nav_types_common.das @@ -41,6 +41,8 @@ struct public WtoNavState steerDir : float3 = float3(1.0, 0.0, 0.0) frontClearM : float = 30.0 rearClearM : float = 16.0 + frontTrafficSpeedCap : float = 99.0 + rearTrafficSpeedCap : float = 99.0 onMesh : bool = false wallDistM : float = 99.0 surfaceArea : int = 0 @@ -51,6 +53,10 @@ struct public WtoNavState yieldCooldownUntil : float = -100.0 avoidActive : bool = false avoidTarget : float3 = float3(0.0, 0.0, 0.0) + passEntry : float3 = float3(0.0, 0.0, 0.0) + passExit : float3 = float3(0.0, 0.0, 0.0) + passAtSide : bool = false + passUntil : float = -100.0 avoidSide : float = 0.0 avoidSideUntil : float = -100.0 avoidSpeedCap : float = 99.0 diff --git a/game-ai/ground/wto_ai_perceive_common.das b/game-ai/ground/wto_ai_perceive_common.das index cf814fc..b7204ac 100644 --- a/game-ai/ground/wto_ai_perceive_common.das +++ b/game-ai/ground/wto_ai_perceive_common.das @@ -10,47 +10,50 @@ 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_terrain_common require %appGame.wtoai.wto_ai_sight_common require %appGame.wtoai.wto_ai_estimate_common require %appGame.wtoai.wto_ai_world_common +require %appGame.wtoai.wto_ai_threat_common +// The current engagement and more dangerous contacts keep their tracks when the table is full. [never_inline] -def private wto_exp_find_or_alloc(var p : WtoPerceiveState&; eid : EntityId) : int +def private wto_exp_find_or_alloc(var p : WtoPerceiveState&; eid : EntityId; now, danger : float) : int var freeIdx = -1 - var minIdx = 0 - var minScore = 2.0 + var weakest = -1 + var minScore = danger for i in range(WTO_MAX_EXPOSURE_TRACKS) if p.expEids[i] == eid return i - if !p.expEids[i] && freeIdx < 0 - freeIdx = i - if p.expScore[i] < minScore - minScore = p.expScore[i] - minIdx = i - let dst = freeIdx >= 0 ? freeIdx : minIdx - p.expEids[dst] = eid - p.expScore[dst] = 0.0 - p.expGoodLosSec[dst] = 0.0 + if !p.expEids[i] + if freeIdx < 0 + freeIdx = i + continue + if p.hasClearLos && p.expEids[i] == p.targetEid + continue + let fresh = now - p.expSeenAt[i] <= WTO_AI_TACTICS_TICK_SEC * 1.5 + let score = p.expDanger[i] * (fresh ? 1.0 : WTO_AI_THREAT_UNSEEN_MUL) + if score < minScore + minScore = score + weakest = i + let dst = freeIdx >= 0 ? freeIdx : weakest + if dst >= 0 + p.expEids[dst] = eid + p.expScore[dst] = 0.0 + p.expGoodLosSec[dst] = 0.0 return dst [never_inline] -def private wto_exp_decay_all(world : WtoWorldSnap const&; dt : float; var p : WtoPerceiveState&) +def private wto_exp_decay_unseen(world : WtoWorldSnap const&; now, dt : float; var p : WtoPerceiveState&) let decay = WTO_AI_PERC_DECAY_PER_SEC * dt for i in range(WTO_MAX_EXPOSURE_TRACKS) - if !p.expEids[i] - continue - let uIdx = wto_world_find_unit(world, p.expEids[i]) - if uIdx < 0 || !world.units[uIdx].isAlive - p.expEids[i] = INVALID_ENTITY_ID - p.expScore[i] = 0.0 - p.expGoodLosSec[i] = 0.0 + if !p.expEids[i] || p.expSeenAt[i] >= now continue + let idx = wto_world_find_unit(world, p.expEids[i]) + p.expGoodLosSec[i] = 0.0 p.expScore[i] = max(0.0, p.expScore[i] - decay) - if p.expScore[i] <= 0.001 + if idx < 0 || !world.units[idx].isAlive || p.expScore[i] <= 0.001 p.expEids[i] = INVALID_ENTITY_ID p.expScore[i] = 0.0 - p.expGoodLosSec[i] = 0.0 [never_inline] def private wto_spot_fill_time(dist : float; cosAngle : float; isShooting : bool; visCount : int) : float @@ -99,23 +102,28 @@ def private wto_update_audio_and_radio_alerts(world : WtoWorldSnap const&; now : p.alertUntil = now + 2.8 return -// Spotting-time multiplier of the perception layer that covers an enemy (decision layer design, -// section 3.1): 1 in the gun sight, nearSpotMul within close awareness around the hull (the rear -// blind arc only during a look-around), midSpotMul in the commander's front half; 0 when no layer -// covers it. -def private wto_perc_layer_mul(dist, cosGun, cosHull : float; lookAround : bool) : float - if cosGun >= cos(WTO_AI_PERC_GUN_FOV_HALF_DEG * WTO_DEG_TO_RAD) +// Horizontal bearings for ground targets use the live barrel yaw. For airborne targets or a +// vertical barrel the full 3D angle gives a bearing without inventing a horizontal forward axis. +def private wto_perc_bearing(delta, barrel : float3; isAir : bool) : float + let ground = float2(delta.x, delta.z) + let sight = float2(barrel.x, barrel.z) + if !isAir && length_sq(ground) > 1.0e-6 && length_sq(sight) > 1.0e-6 + return clamp(dot(normalize(ground), normalize(sight)), -1.0, 1.0) + return clamp(dot(normalize(delta), barrel), -1.0, 1.0) + +def private wto_perc_layer_mul(dist, cosBarrel : float; lookAround : bool) : float + if cosBarrel >= cos(WTO_AI_PERC_GUN_FOV_HALF_DEG * WTO_DEG_TO_RAD) return 1.0 - if dist <= WTO_AI_PERC_NEAR_AWARE_M && (lookAround || cosHull >= cos(0.5 * WTO_AI_PERC_NEAR_ARC_DEG * WTO_DEG_TO_RAD)) + if dist <= WTO_AI_PERC_NEAR_AWARE_M && (lookAround || cosBarrel >= cos(0.5 * WTO_AI_PERC_NEAR_ARC_DEG * WTO_DEG_TO_RAD)) return WTO_AI_PERC_NEAR_SPOT_MUL - if dist <= WTO_AI_PERC_MID_AWARE_M && cosHull >= 0.0 + if dist <= WTO_AI_PERC_MID_AWARE_M && cosBarrel >= 0.0 return WTO_AI_PERC_MID_SPOT_MUL return 0.0 // Integrates one enemy's exposure this tick; its track index, or -1 when no perception layer // covers it or it is hidden. The output is the visible sample count and its center. [never_inline] -def private wto_exp_observe(world : WtoWorldSnap const&; now, dt : float; myEye, lookDir, hullDir : float3; +def private wto_exp_observe(world : WtoWorldSnap const&; now, dt : float; myEye, barrelDir : float3; lookAround : bool; u : WtoUnitSnap const&; var slot : WtoBotSlot&; var vis : int&; var aimPt : float3&) : int assume p = slot.perceive @@ -123,47 +131,43 @@ def private wto_exp_observe(world : WtoWorldSnap const&; now, dt : float; myEye, let dist = length(delta) if dist > (u.isAir ? 2600.0 : WTO_AI_TACTICS_VISION_RANGE_M) || dist < 1.0 return -1 - let dirXZ = wto_xz_normalize(delta, lookDir) - let cosAng = dot(dirXZ, lookDir) - let layerMul = u.isAir ? 1.0 : wto_perc_layer_mul(dist, cosAng, dot(dirXZ, hullDir), lookAround) + let cosAng = wto_perc_bearing(delta, barrelDir, u.isAir) + let airFront = u.isAir && cosAng >= 0.0 + let layerMul = airFront ? 1.0 : wto_perc_layer_mul(dist, cosAng, lookAround) if layerMul <= 0.0 return -1 aimPt = u.pos + float3(0.0, 1.3, 0.0) vis = wto_sight_check_target_samples(world, slot.eid, myEye, u, dist > WTO_AI_FC_LONG_RANGE_M ? 2 : 4, aimPt) if vis <= 0 - for k in range(WTO_MAX_EXPOSURE_TRACKS) - if p.expEids[k] == u.eid - p.expGoodLosSec[k] = 0.0 return -1 - let tIdx = wto_exp_find_or_alloc(p, u.eid) + let danger = wto_threat_observed_danger(now, myEye, u, p) + let tIdx = wto_exp_find_or_alloc(p, u.eid, now, danger) + if tIdx < 0 + return -1 let fillSec = wto_spot_fill_time(dist, cosAng, u.isShooting, vis) * layerMul - p.expScore[tIdx] = clamp(p.expScore[tIdx] + WTO_AI_PERC_DECAY_PER_SEC * dt + dt / fillSec, 0.0, 1.0) + p.expScore[tIdx] = clamp(p.expScore[tIdx] + dt / fillSec, 0.0, 1.0) p.expGoodLosSec[tIdx] = vis >= 2 ? (p.expGoodLosSec[tIdx] + dt) : 0.0 + p.expDanger[tIdx] = danger p.expSeenAt[tIdx] = now p.expPos[tIdx] = u.pos return tIdx -// Target preference among clearly seen enemies: lower is better. -def private wto_exp_target_score(now, dist : float; u : WtoUnitSnap const&; isSpaa : bool; p : WtoPerceiveState const&) : float - var score = dist - (u.isAir && isSpaa ? 900.0 : 0.0) - if u.eid == p.lockedEid && now < p.lockedUntil - score -= 320.0 - elif u.eid == p.lastOffenderEid && (now - p.lastDamagedAt) <= 5.0 - score -= 90.0 - elif u.isShooting && dist < 220.0 - score -= 35.0 - if dist < 45.0 - score -= 180.0 - return score +def private wto_exp_shot_priority(u : WtoUnitSnap const&; myEye : float3; isSpaa : bool) : int + if !isSpaa + return 0 + if u.isAir + return 1 + return wto_xz_dist_sq(u.pos, myEye) <= wto_sq(WTO_AI_FC_CLOSE_RANGE_M) ? 2 : 0 [never_inline] def private wto_scan_visual_exposure(world : WtoWorldSnap const&; now, dt : float; - myEye, lookDir, hullDir : float3; lookAround : bool; var slot : WtoBotSlot&; + myEye, barrelDir : float3; lookAround : bool; var slot : WtoBotSlot&; var outBestIdx, outVisCount : int&; var outGoodLosSec : float&; var outAimPt : float3&) assume p = slot.perceive let isSpaa = slot.spec.role == WTO_ROLE_SPAA - var bestScore = 1.0e9 + var bestScore = -1.0 + var bestPriority = -1 outBestIdx = -1 outVisCount = 0 outGoodLosSec = 0.0 @@ -173,28 +177,24 @@ def private wto_scan_visual_exposure(world : WtoWorldSnap const&; now, dt : floa continue var vis = 0 var aimPt = u.pos - let tIdx = wto_exp_observe(world, now, dt, myEye, lookDir, hullDir, lookAround, u, slot, vis, aimPt) + let tIdx = wto_exp_observe(world, now, dt, myEye, barrelDir, lookAround, u, slot, vis, aimPt) if tIdx < 0 || p.expScore[tIdx] < 0.999 continue - let score = wto_exp_target_score(now, length(u.pos - myEye), u, isSpaa, p) - if score < bestScore + let priority = wto_exp_shot_priority(u, myEye, isSpaa) + let locked = u.eid == p.lockedEid && now < p.lockedUntil + let score = p.expDanger[tIdx] * (locked ? 1.0 + WTO_AI_TURRET_SWITCH_MARGIN : 1.0) + if priority > bestPriority || (priority == bestPriority && score > bestScore) + bestPriority = priority bestScore = score outBestIdx = i outVisCount = vis outGoodLosSec = p.expGoodLosSec[tIdx] outAimPt = aimPt -// The gun sight's flat direction (the hull's until the turret servo is known), and the -// look-around (pressing C): every lookAroundSec, while not engaging, the rear blind arc opens. -[never_inline] -def private wto_perc_look(now : float; hullDir : float3; var slot : WtoBotSlot&; var lookDir : float3&) : bool - assume p = slot.perceive - lookDir = hullDir - if slot.fire.servoInit - let worldYaw = atan2(hullDir.z, hullDir.x) - slot.fire.curYawDeg * WTO_DEG_TO_RAD - lookDir = float3(cos(worldYaw), 0.0, sin(worldYaw)) +// Look-around temporarily opens the close rear arc relative to the barrel. +def private wto_perc_look_around(now : float; eid : EntityId; var p : WtoPerceiveState&) : bool if p.nextLookAroundAt <= 0.0 - p.nextLookAroundAt = now + float(int(uint(slot.eid) % 8u)) + p.nextLookAroundAt = now + float(int(uint(eid) % 8u)) elif now >= p.nextLookAroundAt && !p.hasClearLos p.lookAroundUntil = now + WTO_AI_PERC_LOOK_AROUND_HOLD_SEC p.nextLookAroundAt = now + WTO_AI_PERC_LOOK_AROUND_SEC @@ -213,18 +213,17 @@ def private wto_perc_fleeting(world : WtoWorldSnap const&; myEye : float3; slot [never_inline] def public wto_perceive_update(var world : WtoWorldSnap&; now, dt : float; - myPos, hullFwd : float3; var slot : WtoBotSlot&) + myPos : float3; var slot : WtoBotSlot&) assume p = slot.perceive let myEye = myPos + float3(0.0, 2.15, 0.0) - let hullDir = wto_xz_normalize(hullFwd, float3(1.0, 0.0, 0.0)) - var lookDir = hullDir - let lookAround = wto_perc_look(now, hullDir, slot, lookDir) - wto_exp_decay_all(world, dt, p) + let lookAround = wto_perc_look_around(now, slot.eid, p) var bestIdx = -1 var visCount = 0 var goodLosSec = 0.0 var aimPt = myPos - wto_scan_visual_exposure(world, now, dt, myEye, lookDir, hullDir, lookAround, slot, bestIdx, visCount, goodLosSec, aimPt) + if slot.fire.hasBarrelSight + wto_scan_visual_exposure(world, now, dt, myEye, slot.fire.barrelSight, lookAround, slot, bestIdx, visCount, goodLosSec, aimPt) + wto_exp_decay_unseen(world, now, dt, p) if bestIdx >= 0 assume tgt = world.units[bestIdx] if tgt.isShooting || p.targetEid != tgt.eid @@ -241,7 +240,7 @@ def public wto_perceive_update(var world : WtoWorldSnap&; now, dt : float; p.watchUntil = -100.0 wto_est_push_visual_sample(now, tgt.eid, tgt.pos, p) p.targetFleeting = !tgt.isAir && wto_perc_fleeting(world, myEye, slot) - if p.lockedEid != tgt.eid || now >= p.lockedUntil - 0.5 + if p.lockedEid != tgt.eid p.lockedEid = tgt.eid p.lockedUntil = now + WTO_AI_TACTICS_STICKY_SEC if !tgt.isAir && (now - p.lastRadioSentAt) >= 2.5 @@ -261,30 +260,3 @@ def public wto_perceive_update(var world : WtoWorldSnap&; now, dt : float; p.lockedEid = INVALID_ENTITY_ID p.watchUntil = -100.0 wto_update_audio_and_radio_alerts(world, now, myPos, slot) - -[never_inline] -def public wto_perceive_pick_hunt_pos(world : WtoWorldSnap const&; army : int; eid : EntityId; - myPos : float3; now : float; var outPos : float3&) : bool - var bestDistSq = wto_sq(min(WTO_AI_TACTICS_RADIO_SHARE_M, 560.0)) - var found = false - var spotPos = myPos - for r in range(WTO_MAX_RADIO) - assume sp = world.radioSpots[r] - if sp.untilAt <= now || sp.army != army - continue - let dSq = wto_xz_dist_sq(myPos, sp.pos) - if dSq < bestDistSq && dSq > 2500.0 - bestDistSq = dSq - spotPos = sp.pos - found = true - if !found - return false - let toSpot = wto_xz_normalize(spotPos - myPos, float3(1.0, 0.0, 0.0)) - let lat = float3(-toSpot.z, 0.0, toSpot.x) - let fanOffset = float(int(uint(eid) % 5u) - 2) * 28.0 - var cand = spotPos - toSpot * 65.0 + lat * fanOffset - cand = wto_clamp_battle_xz(cand, world.battleCenter, world.battleRadius, 40.0) - if !wto_terrain_point_valid(army, cand) - cand = spotPos - outPos = cand - return true diff --git a/game-ai/ground/wto_ai_runtime.das b/game-ai/ground/wto_ai_runtime.das index 657e555..a25c5f9 100644 --- a/game-ai/ground/wto_ai_runtime.das +++ b/game-ai/ground/wto_ai_runtime.das @@ -208,7 +208,8 @@ def wto_ai_pipeline_es(act : UpdateStageInfoAct; eid : EntityId; var unit__ref : if now >= slot.nextTacticsAt slot.nextTacticsAt = now + WTO_AI_TACTICS_TICK_SEC 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_fire_sample_sight(unit, slot.fire) + wto_perceive_update(g_world, now, WTO_AI_TACTICS_TICK_SEC, unit.pos, slot) wto_threat_update(g_world, now, unit.pos, slot) wto_tactics_update(g_world, now, WTO_AI_TACTICS_TICK_SEC, unit.pos, unit.unitTm[0], unit.isBurn, repair_system_remaining_repair_time, slot, g_crowd) wto_fire_update(g_world, unit, unit__className, now, act.dt, slot, g_fire_budget) diff --git a/game-ai/ground/wto_ai_stats_common.das b/game-ai/ground/wto_ai_stats_common.das index b1283c0..bcbb6b7 100644 --- a/game-ai/ground/wto_ai_stats_common.das +++ b/game-ai/ground/wto_ai_stats_common.das @@ -165,9 +165,8 @@ def private wto_stats_sample(world : WtoWorldSnap const&; now : float; myPos, hu bs.samples[role]++ if !wto_stats_knows(slot, u.eid) bs.unaware[role]++ - if slot.fire.servoInit - let yaw = atan2(fwd.z, fwd.x) - slot.fire.curYawDeg * WTO_DEG_TO_RAD - let gunDir = float3(cos(yaw), 0.0, sin(yaw)) + if slot.fire.hasBarrelSight + let gunDir = wto_xz_normalize(slot.fire.barrelSight, fwd) bs.turretSamples[role]++ bs.turretErrSum[role] += acos(clamp(dot(gunDir, toEnemy), -1.0, 1.0)) * WTO_RAD_TO_DEG if role == WTO_ROLE_MEDIUM || role == WTO_ROLE_HEAVY || role == WTO_ROLE_TD diff --git a/game-ai/ground/wto_ai_tactics_common.das b/game-ai/ground/wto_ai_tactics_common.das index 4d0b2cc..679c981 100644 --- a/game-ai/ground/wto_ai_tactics_common.das +++ b/game-ai/ground/wto_ai_tactics_common.das @@ -58,7 +58,7 @@ def private wto_sm_handle_ridge(world : WtoWorldSnap const&; now : float; tac.ridgeShotsStart = slot.fire.shotCount 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 + if dwellOver || shotsOver || (slot.fire.pitchBlocked && !slot.fire.hullAimForPitch) 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) @@ -121,9 +121,10 @@ def private wto_tac_engage(now : float; c : WtoBhvCtx const&; var slot : WtoBotS var speed = march assume tr = slot.trigger let fresh = (now - tr.wantSpeedAt) <= WTO_AI_TACTICS_TICK_SEC * 3.0 - let crossExposed = c.urgent && wto_face_side_exposed(slot) + let urgentAdvance = c.urgent && c.distTarget > WTO_AI_PERC_NEAR_AWARE_M + let crossExposed = urgentAdvance && wto_face_side_exposed(slot) if fresh && tr.targetEid == slot.perceive.targetEid && !crossExposed && tr.wantSpeedMps > WTO_AI_FC_STOP_SPEED_MAX_MPS && tr.wantSpeedMps < march - speed = lerp(tr.wantSpeedMps, march, c.urgent ? WTO_AI_BHV_URGENT_SPEED_KEEP : 0.0) + speed = lerp(tr.wantSpeedMps, march, urgentAdvance ? WTO_AI_BHV_URGENT_SPEED_KEEP : 0.0) wto_sm_set_state(now, WTO_STATE_RUN_AND_GUN, c.baseGoal, speed, "engage", c.distTarget, slot) return true @@ -200,5 +201,3 @@ def public wto_tactics_update(world : WtoWorldSnap const&; now, dt : float; if !wto_tac_run(world, now, myPos, hullFwd, c, slot, crowdSummary) wto_bhv_take_over(now, WTO_BHV_ADVANCE, slot) wto_tac_advance(now, myPos, c, slot) - if !slot.tactics.faceForGun - slot.tactics.gunFacingTarget = INVALID_ENTITY_ID diff --git a/game-ai/ground/wto_ai_threat_common.das b/game-ai/ground/wto_ai_threat_common.das index 41ffeee..0e6ccb0 100644 --- a/game-ai/ground/wto_ai_threat_common.das +++ b/game-ai/ground/wto_ai_threat_common.das @@ -1,7 +1,4 @@ -// Threat table (decision layer design, section 4): every enemy the bot has discovered (exposure at -// least perception.discoverScore), with how dangerous it is to the bot. Rebuilt every perception -// tick from the bot's own exposure tracks, so it never knows more than the bot perceived. -// Penetration is not counted yet (see docs/AI-imporve/armor-probe). +// Threats measured by this bot. Near and mid visual contacts can enter before confirmation. options indenting = 2 options no_global_heap = true module wto_ai_threat_common shared @@ -14,10 +11,6 @@ require %appGame.wtoai.wto_ai_combat_types_common require %appGame.wtoai.wto_ai_types_common require %appGame.wtoai.wto_ai_world_common -// Seen this tick: the perception tick writes expSeenAt for every enemy in line of sight. -def private wto_threat_in_sight(now, seenAt : float) : bool - return now - seenAt <= WTO_AI_TACTICS_TICK_SEC * 1.5 - // The enemy's hull points within aimConeDeg of the bot, or it hit the bot within hitMemorySec. def private wto_threat_aiming(now : float; myPos : float3; u : WtoUnitSnap const&; p : WtoPerceiveState const&) : bool if p.lastOffenderEid == u.eid && now - p.lastDamagedAt <= WTO_AI_THREAT_HIT_MEMORY_SEC @@ -25,35 +18,39 @@ def private wto_threat_aiming(now : float; myPos : float3; u : WtoUnitSnap const let toMe = wto_xz_normalize(myPos - u.pos, u.hullFwd) return dot(u.hullFwd, toMe) >= cos(WTO_AI_THREAT_AIM_CONE_DEG * WTO_DEG_TO_RAD) -[never_inline] -def private wto_threat_danger(now : float; e : WtoThreatEntry const&; eid : EntityId; p : WtoPerceiveState const&) : float - var danger = 1.0 / (1.0 + e.dist / WTO_AI_THREAT_RANGE_SCALE_M) - if !e.seen - danger *= WTO_AI_THREAT_DISCOVERED_MUL - if !e.aiming +def private wto_threat_score(now, dist : float; aiming : bool; eid : EntityId; p : WtoPerceiveState const&) : float + var danger = 1.0 / (1.0 + dist / WTO_AI_THREAT_RANGE_SCALE_M) + if !aiming danger *= WTO_AI_THREAT_NOT_AIMING_MUL - if !e.seesMe - danger *= WTO_AI_THREAT_UNSEEN_MUL if p.lastOffenderEid == eid && now - p.lastDamagedAt <= WTO_AI_THREAT_HIT_MEMORY_SEC danger *= WTO_AI_THREAT_HIT_MUL return danger +// The same danger model ranks visible targets at every distance. +def public wto_threat_observed_danger(now : float; eye : float3; u : WtoUnitSnap const&; p : WtoPerceiveState const&) : float + let dist = sqrt(wto_xz_dist_sq(eye, u.pos)) + return wto_threat_score(now, dist, wto_threat_aiming(now, eye, u, p), u.eid, p) + [never_inline] def private wto_threat_add(now : float; myPos : float3; u : WtoUnitSnap const&; track : int; var slot : WtoBotSlot&) assume tt = slot.threat assume p = slot.perceive assume e = tt.entries[tt.count] e.eid = u.eid - e.seesMe = wto_threat_in_sight(now, p.expSeenAt[track]) + e.seesMe = p.expSeenAt[track] >= now e.seen = e.seesMe && p.expScore[track] >= 0.999 e.pos = p.expPos[track] e.dist = sqrt(wto_xz_dist_sq(myPos, e.pos)) e.aiming = wto_threat_aiming(now, myPos, u, p) - e.danger = wto_threat_danger(now, e, u.eid, p) + e.danger = wto_threat_score(now, e.dist, e.aiming, u.eid, p) + if !e.seen + e.danger *= WTO_AI_THREAT_DISCOVERED_MUL + if !e.seesMe + e.danger *= WTO_AI_THREAT_UNSEEN_MUL if tt.topIdx < 0 || e.danger > tt.entries[tt.topIdx].danger tt.topIdx = tt.count - if !e.seen && (tt.topUnseenIdx < 0 || e.danger > tt.entries[tt.topUnseenIdx].danger) - tt.topUnseenIdx = tt.count + if e.seesMe && (tt.topVisibleIdx < 0 || e.danger > tt.entries[tt.topVisibleIdx].danger) + tt.topVisibleIdx = tt.count tt.count++ // Per perception tick, right after wto_perceive_update. @@ -62,7 +59,11 @@ def public wto_threat_update(world : WtoWorldSnap const&; now : float; myPos : f slot.threat = WtoThreatTable() assume p = slot.perceive for k in range(WTO_MAX_EXPOSURE_TRACKS) - if !p.expEids[k] || p.expScore[k] < WTO_AI_PERC_DISCOVER_SCORE + if !p.expEids[k] + continue + let awareness = max(WTO_AI_PERC_NEAR_AWARE_M, WTO_AI_PERC_MID_AWARE_M) + let fresh = p.expSeenAt[k] >= now && wto_xz_dist_sq(myPos, p.expPos[k]) <= wto_sq(awareness) + if p.expScore[k] < WTO_AI_PERC_DISCOVER_SCORE && !fresh continue let uIdx = wto_world_find_unit(world, p.expEids[k]) if uIdx >= 0 && world.units[uIdx].isAlive && !world.units[uIdx].isAir diff --git a/game-ai/ground/wto_ai_traffic_common.das b/game-ai/ground/wto_ai_traffic_common.das index dd27736..334e139 100644 --- a/game-ai/ground/wto_ai_traffic_common.das +++ b/game-ai/ground/wto_ai_traffic_common.das @@ -16,45 +16,8 @@ require %appGame.wtoai.wto_ai_nav_types_common require %appGame.wtoai.wto_ai_navquery_common require %appGame.wtoai.wto_ai_navmesh_common -// A vehicle or wreck seen from the bot: how far ahead (along) and to the left (lat) its centre is, -// and the half extents of its hull along and across the bot's heading. -[safe_when_uninitialized] -struct private WtoTrafficBody - idx : int = -1 - isWreck : bool = false - pos : float3 = float3(0.0, 0.0, 0.0) - vel : float3 = float3(0.0, 0.0, 0.0) - along : float = 0.0 - lat : float = 0.0 - extAlong : float = 0.0 - extLat : float = 0.0 - -[never_inline] -def private wto_traffic_frame(myPos, dir, pos, vel, fwd : float3; halfLen, halfWid : float; var body : WtoTrafficBody&) - let left = float3(-dir.z, 0.0, dir.x) - let rel = float3(pos.x - myPos.x, 0.0, pos.z - myPos.z) - let fd = abs(dot(fwd, dir)) - let fl = abs(dot(fwd, left)) - body.pos = pos - body.vel = vel - body.along = dot(rel, dir) - body.lat = dot(rel, left) - body.extAlong = halfLen * fd + halfWid * fl - body.extLat = halfLen * fl + halfWid * fd - -// Free distance from the bot's front to the body's near end; negative once they overlap. -[never_inline] -def private wto_traffic_gap(body : WtoTrafficBody const&; spec : WtoVehicleSpec const&) : float - return body.along - spec.halfLen - body.extAlong - -// Sideways distance between the centres that lets the hulls pass with passMarginM between them. -[never_inline] -def private wto_traffic_need(body : WtoTrafficBody const&; spec : WtoVehicleSpec const&) : float - return spec.halfWid + body.extLat + WTO_AI_PF_PASS_MARGIN_M - -[never_inline] -def private wto_traffic_in_lane(body : WtoTrafficBody const&; spec : WtoVehicleSpec const&; maxGap : float) : bool - return body.along > 0.0 && abs(body.lat) < wto_traffic_need(body, spec) && wto_traffic_gap(body, spec) < maxGap +require %appGame.wtoai.wto_ai_traffic_geometry_common +require %appGame.wtoai.wto_ai_math_common // The nearest standing body (stopped vehicle or wreck) in the bot's lane within `lookM`. [never_inline] @@ -130,36 +93,68 @@ def private wto_traffic_moving(world : WtoWorldSnap const&; myPos, dir : float3; // Side room for the hull: the mesh must allow the straight line to the passing point. [never_inline] -def private wto_traffic_room(navState : int; myPos, wp : float3; slot : WtoBotSlot const&) : bool +def private wto_traffic_room(world : WtoWorldSnap const&; navState : int; fromPos, toPos : float3; slot : WtoBotSlot const&) : bool + let delta = toPos - fromPos + let dist = wto_xz_len(delta) + if dist <= 0.1 + return true + let dir = wto_xz_normalize(delta, float3(1.0, 0.0, 0.0)) + var body = WtoTrafficBody() + if wto_traffic_find_standing(world, fromPos, dir, dist, slot, body) + return false if navState != WTO_NAVMESH_LOADED || slot.route.tier < 0 return true var frac = 0.0 - return wto_navq_raycast(slot.route.tier, slot.route.filter, myPos, wp, frac) != 0 + return wto_navq_raycast(slot.route.tier, slot.route.filter, fromPos, toPos, frac) != 0 -// Steers past `body` on the side with room: the nearer side first (or the side chosen within the -// last blockWaitSec, so the bot does not swing between sides), then the other. +// A stationary obstruction must be passed in two legs: get to its side before the near end, +// then drive past its far end. Keeping those points prevents a premature return to the path. [never_inline] -def private wto_traffic_pass(navState : int; now : float; myPos, dir : float3; body : WtoTrafficBody const&; - var slot : WtoBotSlot&) : bool +def private wto_traffic_pass(world : WtoWorldSnap const&; navState : int; now : float; myPos, dir : float3; body : WtoTrafficBody const&; + persistent : bool; var slot : WtoBotSlot&) : bool assume nav = slot.nav let left = float3(-dir.z, 0.0, dir.x) let need = wto_traffic_need(body, slot.spec) var side = abs(body.lat + need) <= abs(body.lat - need) ? 1.0 : -1.0 if now < nav.avoidSideUntil && nav.avoidSide != 0.0 side = nav.avoidSide - let beyond = max(body.along + body.extAlong + slot.spec.halfLen, WTO_AI_PF_BUMPER_RAY_M) - for _k in range(2) - let wp = myPos + dir * beyond + left * (body.lat + side * need) - if wto_traffic_room(navState, myPos, wp, slot) + let front = max(0.0, wto_traffic_gap(body, slot.spec) - WTO_AI_PF_BUMPER_STOP_M) + let back = body.along + body.extAlong + slot.spec.halfLen + WTO_AI_PF_BUMPER_STOP_M + for _i in range(2) + let lateral = left * (body.lat + side * (need + WTO_AI_PF_PASS_MARGIN_M)) + let entry = myPos + dir * front + lateral + let exit = myPos + dir * back + lateral + if wto_traffic_room(world, navState, myPos, entry, slot) && wto_traffic_room(world, navState, entry, exit, slot) nav.avoidActive = true - nav.avoidTarget = wp + nav.avoidTarget = entry nav.avoidSide = side nav.avoidSideUntil = now + WTO_AI_PF_BLOCK_WAIT_SEC nav.avoidSpeedCap = min(nav.avoidSpeedCap, WTO_AI_PF_PASS_SPEED_MPS) + if persistent + nav.passEntry = entry + nav.passExit = exit + nav.passAtSide = false + nav.passUntil = now + WTO_AI_PF_BLOCK_TTL_SEC + max(0.0, back) / WTO_AI_PF_PASS_SPEED_MPS return true side = -side return false +[never_inline] +def private wto_traffic_follow_pass(now : float; myPos, routeDir : float3; var nav : WtoNavState&) : bool + if now >= nav.passUntil + return false + let along = wto_xz_normalize(nav.passExit - nav.passEntry, routeDir) + let marginSq = wto_sq(WTO_AI_PF_PASS_MARGIN_M) + if dot(along, routeDir) < 0.0 || wto_xz_dist_sq(myPos, nav.passExit) <= marginSq || dot(myPos - nav.passExit, along) >= 0.0 + nav.passUntil = -100.0 + return false + if wto_xz_dist_sq(myPos, nav.passEntry) <= marginSq + nav.passAtSide = true + nav.avoidActive = true + nav.avoidTarget = nav.passAtSide ? nav.passExit : nav.passEntry + nav.avoidSpeedCap = min(nav.avoidSpeedCap, WTO_AI_PF_PASS_SPEED_MPS) + return true + // No way past: stop short; after blockWaitSec mark the body for path searches and plan again. [never_inline] def private wto_traffic_blocked(navState : int; now : float; body : WtoTrafficBody const&; var slot : WtoBotSlot&) @@ -226,19 +221,24 @@ def public wto_traffic_update(world : WtoWorldSnap const&; navState : int; now : let meets = wto_traffic_moving(world, myPos, dir, speedMps, slot, oncoming) var standing = WtoTrafficBody() let lookM = max(WTO_AI_PF_BUMPER_RAY_M, speedMps * WTO_AI_PF_TRAFFIC_TTC_SEC) - if wto_traffic_find_standing(world, myPos, dir, lookM, slot, standing) + let blockedAhead = wto_traffic_find_standing(world, myPos, dir, lookM, slot, standing) + if blockedAhead wto_traffic_contact(now, speedMps, standing, slot) - if !wto_traffic_pass(navState, now, myPos, dir, standing, slot) + else + nav.contactSince = -100.0 + if wto_traffic_follow_pass(now, myPos, dir, nav) + return + if blockedAhead + if !wto_traffic_pass(world, navState, now, myPos, dir, standing, true, slot) wto_traffic_blocked(navState, now, standing, slot) return nav.blockedSince = -100.0 - nav.contactSince = -100.0 if !meets nav.yieldUntil = -100.0 return if !narrow - if !wto_traffic_pass(navState, now, myPos, dir, oncoming, slot) - nav.avoidSpeedCap = min(nav.avoidSpeedCap, WTO_AI_PF_PASS_SPEED_MPS) + if !wto_traffic_pass(world, navState, now, myPos, dir, oncoming, false, slot) + wto_traffic_yield(now, nav) return if !wto_traffic_has_priority(slot, world.units[oncoming.idx]) wto_traffic_yield(now, nav) diff --git a/game-ai/ground/wto_ai_traffic_geometry_common.das b/game-ai/ground/wto_ai_traffic_geometry_common.das new file mode 100644 index 0000000..8fce273 --- /dev/null +++ b/game-ai/ground/wto_ai_traffic_geometry_common.das @@ -0,0 +1,97 @@ +// Shared hull projections for route traffic, speed caps, and forward and rear clearance. +options indenting = 2 +options no_global_heap = true +module wto_ai_traffic_geometry_common shared + +require ecs +require math +require %appGame.wtoai.wto_ai_config_common +require %appGame.wtoai.wto_ai_types_common + +// A vehicle or wreck seen from the bot: how far ahead (along) and to the left (lat) its centre is, +// and the half extents of its hull along and across the bot's heading. +[safe_when_uninitialized] +struct public WtoTrafficBody + idx : int = -1 + isWreck : bool = false + pos : float3 = float3(0.0, 0.0, 0.0) + vel : float3 = float3(0.0, 0.0, 0.0) + along : float = 0.0 + lat : float = 0.0 + extAlong : float = 0.0 + extLat : float = 0.0 + +[never_inline] +def public wto_traffic_frame(myPos, dir, pos, vel, fwd : float3; halfLen, halfWid : float; var body : WtoTrafficBody&) + let left = float3(-dir.z, 0.0, dir.x) + let rel = float3(pos.x - myPos.x, 0.0, pos.z - myPos.z) + let fd = abs(dot(fwd, dir)) + let fl = abs(dot(fwd, left)) + body.pos = pos + body.vel = vel + body.along = dot(rel, dir) + body.lat = dot(rel, left) + body.extAlong = halfLen * fd + halfWid * fl + body.extLat = halfLen * fl + halfWid * fd + +// Free distance from the bot's front to the body's near end; negative once they overlap. +[never_inline] +def public wto_traffic_gap(body : WtoTrafficBody const&; spec : WtoVehicleSpec const&) : float + return body.along - spec.halfLen - body.extAlong + +// Sideways distance between the centres that lets the hulls pass with passMarginM between them. +[never_inline] +def public wto_traffic_need(body : WtoTrafficBody const&; spec : WtoVehicleSpec const&) : float + return spec.halfWid + body.extLat + WTO_AI_PF_PASS_MARGIN_M + +[never_inline] +def public wto_traffic_in_lane(body : WtoTrafficBody const&; spec : WtoVehicleSpec const&; maxGap : float) : bool + return body.along > 0.0 && abs(body.lat) < wto_traffic_need(body, spec) && wto_traffic_gap(body, spec) < maxGap + +[safe_when_uninitialized] +struct public WtoTrafficClearance + frontM : float = 99.0 + rearM : float = 99.0 + frontSpeed : float = 0.0 + rearSpeed : float = 0.0 + +def private wto_traffic_clip(body : WtoTrafficBody const&; spec : WtoVehicleSpec const&; + hullDir : float3; var clearance : WtoTrafficClearance&) + if abs(body.lat) >= wto_traffic_need(body, spec) + return + let edge = max(0.0, abs(body.along) - body.extAlong) + if body.along >= 0.0 && edge < clearance.frontM + clearance.frontM = edge + clearance.frontSpeed = dot(body.vel, hullDir) + elif body.along < 0.0 && edge < clearance.rearM + clearance.rearM = edge + clearance.rearSpeed = -dot(body.vel, hullDir) + +// Project both ends of the current hull against living vehicles of either team and wrecks. +[never_inline] +def public wto_traffic_clearance(world : WtoWorldSnap const&; myPos, hullDir : float3; + slot : WtoBotSlot const&; var clear : WtoTrafficClearance&) + var body = WtoTrafficBody() + for i in range(world.unitCount) + assume u = world.units[i] + if u.eid == slot.eid || !u.isGround || !u.isAlive + continue + wto_traffic_frame(myPos, hullDir, u.pos, u.vel, u.hullFwd, u.halfLen, u.halfWid, body) + wto_traffic_clip(body, slot.spec, hullDir, clear) + let still = float3(0.0, 0.0, 0.0) + for i in range(world.wreckCount) + assume w = world.wrecks[i] + if w.eid == slot.eid + continue + wto_traffic_frame(myPos, hullDir, w.pos, still, w.hullFwd, w.halfLen, w.halfWid, body) + wto_traffic_clip(body, slot.spec, hullDir, clear) + +def public wto_traffic_brake_speed(edgeM, neighborSpeed, currentSpeed, halfLen : float) : float + if edgeM >= 99.0 + return 99.0 + let room = edgeM - halfLen - WTO_AI_PF_BUMPER_STOP_M + if room <= 0.0 + return 0.0 + let closing = max(0.0, currentSpeed - neighborSpeed) + let remaining = max(0.0, room - closing * WTO_AI_NAV_TICK_SEC) + return max(0.0, neighborSpeed + sqrt(2.0 * WTO_AI_PF_BRAKE_DECEL * remaining)) diff --git a/game-ai/ground/wto_ai_traverse_common.das b/game-ai/ground/wto_ai_traverse_common.das index e9fe26b..d5b99bb 100644 --- a/game-ai/ground/wto_ai_traverse_common.das +++ b/game-ai/ground/wto_ai_traverse_common.das @@ -23,7 +23,7 @@ let private WTO_FIRST_GUNNER_TRIGGER = int(0x13) def public wto_unit_model_path(className : string) : string return find(className, "/") >= 0 ? ("gamedata/units/" + className + ".blk") : ("gamedata/units/tankModels/" + className + ".blk") -def private wto_valid_angle_range(angles : float2) : bool +def public wto_valid_angle_range(angles : float2) : bool return wto_is_finite(angles.x) && wto_is_finite(angles.y) && angles.x <= angles.y [never_inline] @@ -62,15 +62,15 @@ def private wto_load_gun_traverse(className : string; triggerNo, weaponIndex : i let sectors = mount |> datablock_get_block_by_name("limitsTable") traverse.hasPitchTable = sectors != null && sectors.paramCount > 0u -def private wto_full_gun_traverse(yaw : float2) : bool +def public wto_full_gun_traverse(yaw : float2) : bool return yaw.y - yaw.x >= 360.0 -def private wto_yaw_in_mount_coordinates(yaw : float; arc : float2) : float +def public wto_yaw_in_mount_coordinates(yaw : float; arc : float2) : float let center = (arc.x + arc.y) * 0.5 return center + wto_wrap_deg(yaw - center) [never_inline] -def private wto_gun_pitch_at_yaw(className : string; triggerNo, weaponIndex : int; yaw : float; +def public wto_gun_pitch_at_yaw(className : string; triggerNo, weaponIndex : int; yaw : float; var traverse : WtoGunTraverse&) : float2 if !traverse.hasPitchTable return traverse.pitch @@ -115,7 +115,7 @@ def public wto_world_to_hull_deg(worldDir, hullFwd, hullUp, hullLeft : float3; outPitchDeg = atan2(u, max(1.0e-5, horiz)) * WTO_RAD_TO_DEG [never_inline] -def private wto_hull_deg_to_world(yawDeg, pitchDeg : float; hullFwd, hullUp, hullLeft : float3) : float3 +def public wto_hull_deg_to_world(yawDeg, pitchDeg : float; hullFwd, hullUp, hullLeft : float3) : float3 let yr = yawDeg * WTO_DEG_TO_RAD let pr = pitchDeg * WTO_DEG_TO_RAD let cp = cos(pr) @@ -130,11 +130,15 @@ def private wto_step_mounted_yaw(current, desired, step : float; arc : float2) : let clampedTarget = clamp(wto_yaw_in_mount_coordinates(desired, arc), arc.x, arc.y) return clamp(clampedCurrent + clamp(clampedTarget - clampedCurrent, -step, step), arc.x, arc.y) -def private wto_track_blocked_pitch(wishPitchDeg, dtStep : float; var slot : WtoBotSlot&) +def private wto_track_blocked_pitch(wishPitch, wishYaw, cmdYaw, dtStep : float; pitch : float2; var slot : WtoBotSlot&) assume fc = slot.fire let pitchSpd = abs(fc.curPitchDeg - fc.prevPitchDeg) / dtStep fc.prevPitchDeg = fc.curPitchDeg - if slot.perceive.hasClearLos && wishPitchDeg < fc.curPitchDeg - 2.3 && pitchSpd < 0.8 + let align = WTO_AI_FC_BASE_ALIGN_DEG + let aimedYaw = abs(wto_wrap_deg(cmdYaw - wishYaw)) <= align + let outside = wishPitch < pitch.x - align || wishPitch > pitch.y + align + fc.pitchAtLimit = aimedYaw && wto_valid_angle_range(pitch) && outside + if slot.perceive.hasClearLos && fc.pitchAtLimit && pitchSpd < 0.8 fc.pitchClampSec = min(2.0, fc.pitchClampSec + dtStep) fc.pitchBlocked = fc.pitchClampSec >= 0.75 else @@ -147,6 +151,7 @@ def public wto_drive_mounted_gun(var unit : Unit?; className : string; dt : floa wishYawDeg, wishPitchDeg : float; var slot : WtoBotSlot&) assume fc = slot.fire let dtStep = clamp(dt, 0.005, 0.12) + fc.pitchAtLimit = false if fc.traverseTurretNo != fc.turretNo fc.traverseTurretNo = fc.turretNo fc.traverse = WtoGunTraverse() @@ -166,12 +171,12 @@ def public wto_drive_mounted_gun(var unit : Unit?; className : string; dt : floa fc.curPitchDeg = turret.currentState.pitch if !fc.traverse.known return - wto_track_blocked_pitch(wishPitchDeg, dtStep, slot) let yaw = fc.traverse.yaw let maxYawStep = max(24.0, slot.spec.turretYawSpd * 1.1) * dtStep let cmdYaw = wto_step_mounted_yaw(fc.curYawDeg, wishYawDeg, maxYawStep, yaw) let maxPitchStep = max(10.0, slot.spec.turretPitchSpd * 1.1) * dtStep let pitch = wto_gun_pitch_at_yaw(className, triggerNo, weaponIndex, cmdYaw, fc.traverse) + wto_track_blocked_pitch(wishPitchDeg, wishYawDeg, cmdYaw, dtStep, pitch, slot) turret.yawLim = cmdYaw if pitch.x <= pitch.y let pitchDelta = clamp(wishPitchDeg - fc.curPitchDeg, -maxPitchStep, maxPitchStep) @@ -206,23 +211,3 @@ def public wto_aim_aux_mount(var unit : Unit?; className : string; dt : float; t def public wto_apply_weapon_aim(var unit : Unit?; dt : float) var pos = unit.pos updateWeaponAnims(*unit.weap, clamp(dt, 0.005, 0.12), 1.0, pos) - -def public wto_set_hull_aim(unit : Unit const?; active : bool; wishYaw : float; liveBarrelDir : float3; - var slot : WtoBotSlot&) - assume fc = slot.fire - var target = INVALID_ENTITY_ID - if active - var arc = fc.traverse.yaw - if !fc.traverse.known - var fixedYaw, pitch : float - wto_world_to_hull_deg(liveBarrelDir, unit.unitTm[0], unit.unitTm[1], unit.unitTm[2], fixedYaw, pitch) - arc = float2(fixedYaw, fixedYaw) - let aimYaw = wto_yaw_in_mount_coordinates(wishYaw, arc) - let tolerance = arc.x == arc.y ? WTO_AI_FC_BASE_ALIGN_DEG : 0.0 - if !wto_full_gun_traverse(arc) && (aimYaw < arc.x - tolerance || aimYaw > arc.y + tolerance) - target = slot.perceive.targetEid - let yawToTurn = wto_wrap_deg(wishYaw - (arc.x + arc.y) * 0.5) - fc.hullAimDir = wto_hull_deg_to_world(yawToTurn, 0.0, unit.unitTm[0], unit.unitTm[1], unit.unitTm[2]) - if target != fc.hullAimTarget - slot.nextNavAt = 0.0 - fc.hullAimTarget = target diff --git a/game-ai/ground/wto_ai_turret_common.das b/game-ai/ground/wto_ai_turret_common.das index 28f71db..7db5a26 100644 --- a/game-ai/ground/wto_ai_turret_common.das +++ b/game-ai/ground/wto_ai_turret_common.das @@ -1,8 +1,4 @@ -// Turret channel (decision layer design, section 5): where the turret looks when it is not aiming -// at an engaged target. Never the hull's front by default: the most dangerous discovered threat -// not seen clearly yet, then the last exit of a lost target, the remembered target, a cue (hit, -// sound, radio), and otherwise a sweep across the route ahead. A chosen threat is kept for at -// least turret.minDwellSec so the turret does not swing between two of them. +// The turret focuses the most dangerous visible contact, then watches memory and cues or scans. options indenting = 2 options no_global_heap = true module wto_ai_turret_common shared @@ -16,29 +12,35 @@ require %appGame.wtoai.wto_ai_types_common require %appGame.wtoai.wto_ai_nav_types_common require %appGame.wtoai.wto_ai_threat_common -// Whether a threat not seen clearly yet is enough more dangerous than the engaged target that -// the turret should turn to it instead of aiming (turret.switchMargin). def public wto_turret_prefers_threat(slot : WtoBotSlot const&) : bool - let top = slot.threat.topUnseenIdx - if top < 0 + let top = slot.threat.topVisibleIdx + if top < 0 || slot.perceive.targetIsAir + return false + assume threat = slot.threat.entries[top] + if threat.eid == slot.perceive.targetEid return false let engaged = wto_threat_danger_of(slot, slot.perceive.targetEid) - return slot.threat.entries[top].danger > engaged * (1.0 + WTO_AI_TURRET_SWITCH_MARGIN) + return threat.danger > engaged * (1.0 + WTO_AI_TURRET_SWITCH_MARGIN) -// The threat to look at: the most dangerous one not seen clearly, or the one already looked at -// while its minimum dwell lasts and it is still in the table; -1 for none. [never_inline] def private wto_turret_pick_threat(now : float; var slot : WtoBotSlot&) : int assume tr = slot.turret assume tt = slot.threat - if now < tr.holdUntil - for i in range(tt.count) - if tt.entries[i].eid == tr.lookEid && !tt.entries[i].seen - return i - let top = tt.topUnseenIdx - if top >= 0 && tt.entries[top].eid != tr.lookEid - tr.lookEid = tt.entries[top].eid + let top = tt.topVisibleIdx + if top < 0 + tr.lookEid = INVALID_ENTITY_ID + return -1 + assume threat = tt.entries[top] + if threat.eid != tr.lookEid + if now < tr.holdUntil + for i in range(tt.count) + assume held = tt.entries[i] + if held.eid == tr.lookEid && held.seesMe && threat.danger <= held.danger * (1.0 + WTO_AI_TURRET_SWITCH_MARGIN) + return i + tr.lookEid = threat.eid tr.holdUntil = now + WTO_AI_TURRET_MIN_DWELL_SEC + if WTO_AI_DIAG_TELEMETRY + print("WTO_AI|TURRET_FOCUS|eid={uint(slot.eid)}|target={uint(tr.lookEid)}|dist={threat.dist}|danger={threat.danger}\n") return top // Sweep across the route: scanArcDeg either side of where the bot drives (or of its order goal diff --git a/game-ai/ground/wto_ai_types_common.das b/game-ai/ground/wto_ai_types_common.das index 9373fb4..4122da4 100644 --- a/game-ai/ground/wto_ai_types_common.das +++ b/game-ai/ground/wto_ai_types_common.das @@ -227,7 +227,6 @@ struct public WtoTacticsState faceThreatDir : float3 = float3(1.0, 0.0, 0.0) faceFromThreat : bool = false faceForGun : bool = false - gunFacingTarget : EntityId = INVALID_ENTITY_ID reverseTravel : bool = false reverseSince : float = -100.0 diff --git a/game-ai/ground/wto_ai_unstick_common.das b/game-ai/ground/wto_ai_unstick_common.das index 99f87d1..97e2fe2 100644 --- a/game-ai/ground/wto_ai_unstick_common.das +++ b/game-ai/ground/wto_ai_unstick_common.das @@ -49,6 +49,7 @@ def private wto_unstick_start_reverse(navState : int; now : float; myPos, hullFw let forward = slot.tactics.reverseTravel if !wto_unstick_reverse_target(navState, myPos, hullFwd, forward, slot, target) return + slot.nav.passUntil = -100.0 slot.nav.reverseTarget = target slot.nav.unstickForward = forward slot.nav.reverseUntil = now + WTO_AI_PF_UNSTICK_REV_SEC @@ -123,7 +124,8 @@ def public wto_unstick_reversing(now : float; myPos : float3; var slot : WtoBotS let dir = wto_xz_normalize(nav.reverseTarget - myPos, -nav.steerDir) nav.steerDir = dir let mode = nav.unstickForward ? WTO_DRIVE_CRUISE : WTO_DRIVE_REVERSE - let speed = nav.unstickForward ? min(slot.spec.vMaxFwd, slot.spec.vMaxRev) : max(2.0, slot.spec.vMaxRev) + let axisCap = nav.unstickForward ? nav.frontTrafficSpeedCap : nav.rearTrafficSpeedCap + let speed = min(slot.spec.vMaxRev, axisCap) wto_drive_cmd_set(slot.driveCmd, mode, nav.reverseTarget, dir, speed, nav.frontClearM, nav.rearClearM) return true diff --git a/game-ai/ground/wto_ai_world_common.das b/game-ai/ground/wto_ai_world_common.das index 14b32e2..05ce8b8 100644 --- a/game-ai/ground/wto_ai_world_common.das +++ b/game-ai/ground/wto_ai_world_common.das @@ -154,7 +154,7 @@ def private wto_refresh_units(var snap : WtoWorldSnap&) let army = int(u.army) if army != 1 && army != 2 return - let isGround = gm != null && gm.moveSys != null && as_hv(u) != null + let isGround = gm != null && as_hv(u) != null let isAir = u.isFlightModelWrap if !isGround && !isAir return diff --git a/packages/patcher/src/ground-ai/ground-ai-config.ts b/packages/patcher/src/ground-ai/ground-ai-config.ts index 60ff06d..25b7479 100644 --- a/packages/patcher/src/ground-ai/ground-ai-config.ts +++ b/packages/patcher/src/ground-ai/ground-ai-config.ts @@ -251,6 +251,7 @@ export interface GroundAiConfig { readonly switchMargin: number; readonly scanArcDeg: number; readonly scanPeriodSec: number; + readonly fixedMountYawSpanDeg: number; }; readonly behavior: { readonly scoreIntervalSec: number; @@ -507,6 +508,7 @@ function collectConfigEntries(c: GroundAiConfig): readonly DasEntry[] { ['WTO_AI_TURRET_SWITCH_MARGIN', 'float', c.turret.switchMargin], ['WTO_AI_TURRET_SCAN_ARC_DEG', 'float', c.turret.scanArcDeg], ['WTO_AI_TURRET_SCAN_PERIOD_SEC', 'float', c.turret.scanPeriodSec], + ['WTO_AI_TURRET_FIXED_MOUNT_SPAN_DEG', 'float', c.turret.fixedMountYawSpanDeg], ['WTO_AI_BHV_SCORE_SEC', 'float', c.behavior.scoreIntervalSec], ['WTO_AI_BHV_ADVANCE_HOLD_SEC', 'float', c.behavior.advanceHoldSec], ['WTO_AI_BHV_ENGAGE_HOLD_SEC', 'float', c.behavior.engageHoldSec],