From 1590a2fea9095faf38adc4246ba6097092078635 Mon Sep 17 00:00:00 2001 From: N0VAN0M4LY <224130499+N0VAN0M4LY@users.noreply.github.com> Date: Sun, 6 Dec 2026 00:03:55 +0800 Subject: [PATCH] feat(ground-ai): layered perception, threat table and turret channel First step of the single-bot decision layer. Not yet checked in game: the decision layer is coupled, so it is tested once its hull and fire parts are in. Perception is layered: the gun sight covers perception.gunFovHalfDeg either side of the barrel; within nearAwareM the crew notices enemies around the hull except a rear blind arc, which a periodic look-around opens; within midAwareM the commander covers the hull's front half. Near and mid layers take longer to see an enemy clearly. Each track remembers when and where its enemy was last in sight. Each bot keeps a threat table of the enemies it has discovered, rated by distance, whether seen clearly, whether aiming at it or recently hitting it, and whether it is in their sight. Penetration is left out until the engine damage test is usable. The turret no longer rests on the hull's front: without a clearly seen target it looks at the most dangerous discovered threat, then the last exit, the remembered target, cues, and otherwise sweeps across the route. A threat clearly more dangerous than the engaged target takes the turret first. Bot slot bookkeeping moves out of the runtime entry into wto_ai_slots_common.das, and battle statistics count an enemy as known when it is in the threat table. Tuning: perception gains nine settings and loses frontConeHalfDeg and peripheralCloseM, tactics loses visionFovDeg and peripheralRangeM, and the new threat and turret sections are wired through the server reader, generated constants and launcher fields in both languages. --- .../src/renderer/src/i18n/locales/en.json | 32 ++++- .../src/renderer/src/i18n/locales/zh-CN.json | 32 ++++- .../src/pages/tuning/bot-tuning-fields.ts | 38 +++++- apps/launcher/src/shared/schemas/tuning.ts | 34 ++++- apps/server/src/tuning/ground-ai-tuning.ts | 36 ++++- apps/server/tuning/ground-ai.jsonc | 47 ++++++- game-ai/ground/wto_ai_combat_types_common.das | 33 +++++ game-ai/ground/wto_ai_fire_common.das | 13 +- game-ai/ground/wto_ai_perceive_common.das | 128 ++++++++++++------ game-ai/ground/wto_ai_runtime.das | 107 +++------------ game-ai/ground/wto_ai_slots_common.das | 113 ++++++++++++++++ game-ai/ground/wto_ai_stats_common.das | 6 +- game-ai/ground/wto_ai_threat_common.das | 76 +++++++++++ game-ai/ground/wto_ai_turret_common.das | 70 ++++++++++ game-ai/ground/wto_ai_types_common.das | 2 + .../patcher/src/ground-ai/ground-ai-config.ts | 52 +++++-- 16 files changed, 642 insertions(+), 177 deletions(-) create mode 100644 game-ai/ground/wto_ai_slots_common.das create mode 100644 game-ai/ground/wto_ai_threat_common.das create mode 100644 game-ai/ground/wto_ai_turret_common.das diff --git a/apps/launcher/src/renderer/src/i18n/locales/en.json b/apps/launcher/src/renderer/src/i18n/locales/en.json index 4f6ead7..da1d14a 100644 --- a/apps/launcher/src/renderer/src/i18n/locales/en.json +++ b/apps/launcher/src/renderer/src/i18n/locales/en.json @@ -533,6 +533,8 @@ "perception": "Visual perception & exposure", "tactics": "Situational awareness & memory", "estimation": "Lead estimation & aim bias", + "threat": "Threat assessment", + "turret": "Turret attention", "fireControl": "Fire control & fire gate", "navigation": "Driving & navigation", "navEngine": "Map navigation mesh & path costs", @@ -551,6 +553,8 @@ "perception": "Foliage transparency, exposure accumulation and decay", "tactics": "Vision range, audio detection, radio sharing and target memory", "estimation": "Sample-based velocity lead, exit watch and natural shot spread", + "threat": "How dangerous each discovered enemy is: distance, aim, line of sight and recent hits", + "turret": "Where the turret looks without a target: threats, cues and scanning along the route", "fireControl": "Range bands, speed gates, barrel settle and ballistic safety", "navigation": "Drive backend, pivot turns and tactical reverse", "navEngine": "Baked map navigation packs, their fallback, and path costs per surface for tracked and wheeled vehicles", @@ -639,13 +643,18 @@ "normalSpotSec": "Normal exposure spot time", "farSpotSec": "Long-range exposure spot time", "decayPerSec": "Exposure decay rate per second", - "frontConeHalfDeg": "Forward vision cone half-angle", - "peripheralCloseM": "Close peripheral spot distance" + "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)", + "nearSpotMul": "Close awareness spotting time multiplier", + "midSpotMul": "Commander awareness spotting time multiplier", + "lookAroundSec": "Look-around interval", + "lookAroundHoldSec": "Look-around duration", + "discoverScore": "Exposure at which an enemy counts as discovered" }, "tactics": { "visionRangeM": "Max visual detection range", - "visionFovDeg": "Vision field of view", - "peripheralRangeM": "Peripheral detection range", "engineAudioRangeM": "Engine audio hearing range", "shotAudioRangeM": "Gunshot audio hearing range", "radioShareRangeM": "Allied radio sharing range", @@ -663,6 +672,21 @@ "leadErrorFrac": "Lead estimation error fraction", "maxBiasM": "Max per-opportunity aim bias" }, + "threat": { + "rangeScaleM": "Distance at which danger halves", + "discoveredMul": "Danger multiplier until seen clearly", + "aimConeDeg": "Cone in which an enemy counts as aiming at the bot", + "notAimingMul": "Danger multiplier when not aiming at the bot", + "unseenMul": "Danger multiplier when the bot is out of its sight", + "hitMemorySec": "How long a hit raises the shooter's danger", + "hitMul": "Danger multiplier after a hit" + }, + "turret": { + "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" + }, "fireControl": { "maxEngageRangeM": "Max engagement range", "closeRangeM": "Close range band threshold", 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 522490d..2be4ada 100644 --- a/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json +++ b/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json @@ -533,6 +533,8 @@ "perception": "视觉感知与曝光", "tactics": "态势感知与目标记忆", "estimation": "目击测速与瞄准偏差", + "threat": "威胁评估", + "turret": "炮塔关注方向", "fireControl": "火控与开火许可", "navigation": "机动与寻路控制", "navEngine": "地图导航网格与通行代价", @@ -551,6 +553,8 @@ "perception": "植被透光、曝光累计速度与衰减", "tactics": "视距、听觉发现范围、电台共享与记忆时长", "estimation": "本车目击测速、守出口时长与自然散布", + "threat": "每个已发现敌人的危险程度:距离、是否瞄着本车、视线与最近是否命中本车", + "turret": "没有目标时炮塔看哪里:威胁、线索与沿路线扫视", "fireControl": "距离分档、车速门槛、稳定等待与弹道防误伤", "navigation": "驱动方式、原地转向与战术倒车", "navEngine": "离线地图导航包的启用与降级,以及履带 / 轮式车在各类地表上的寻路代价", @@ -639,13 +643,18 @@ "normalSpotSec": "常规曝光用时", "farSpotSec": "远距曝光用时", "decayPerSec": "失联曝光每秒衰减率", - "frontConeHalfDeg": "前向主视锥半角", - "peripheralCloseM": "近身余光发现距离" + "gunFovHalfDeg": "瞄准镜视野半角", + "nearAwareM": "近距环视感知距离", + "nearArcDeg": "近距感知覆盖车体周围的角度", + "midAwareM": "车长感知距离(车体前半球)", + "nearSpotMul": "近距感知看清耗时倍数", + "midSpotMul": "车长感知看清耗时倍数", + "lookAroundSec": "环视间隔", + "lookAroundHoldSec": "环视持续时间", + "discoverScore": "曝光积分达到多少算发现" }, "tactics": { "visionRangeM": "最大视觉索敌距离", - "visionFovDeg": "视野总张角", - "peripheralRangeM": "外围余光索敌距离", "engineAudioRangeM": "引擎声听觉距离", "shotAudioRangeM": "炮声听觉距离", "radioShareRangeM": "友军电台报点共享距离", @@ -663,6 +672,21 @@ "leadErrorFrac": "提前量误差比例", "maxBiasM": "单次射击最大偏移上限" }, + "threat": { + "rangeScaleM": "危险度减半的距离", + "discoveredMul": "尚未看清时的危险度倍数", + "aimConeDeg": "算作对方瞄着本车的夹角范围", + "notAimingMul": "对方没瞄着本车时的危险度倍数", + "unseenMul": "本车不在对方视线内时的危险度倍数", + "hitMemorySec": "被命中后提高射手危险度的时长", + "hitMul": "被命中后的危险度倍数" + }, + "turret": { + "minDwellSec": "选定的观察方向至少保持的时间", + "switchMargin": "从交战目标转向其他威胁所需高出的危险度", + "scanArcDeg": "沿路线向两侧扫视的角度", + "scanPeriodSec": "扫视一个来回的时长" + }, "fireControl": { "maxEngageRangeM": "最大交战开火距离", "closeRangeM": "近距交战分界距离", 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 a569ed3..5fb1f94 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 @@ -189,8 +189,15 @@ export const BOT_TUNING_GROUPS: readonly BotTuningGroup[] = [ num('perception', 'normalSpotSec', 0.1, 3, 's'), num('perception', 'farSpotSec', 0.3, 6, 's'), num('perception', 'decayPerSec', 0.2, 10), - num('perception', 'frontConeHalfDeg', 10, 90, '°'), - num('perception', 'peripheralCloseM', 30, 250, 'm'), + num('perception', 'gunFovHalfDeg', 5, 90, '°'), + num('perception', 'nearAwareM', 30, 400, 'm'), + num('perception', 'nearArcDeg', 90, 360, '°'), + num('perception', 'midAwareM', 100, 1500, 'm'), + num('perception', 'nearSpotMul', 1, 5), + num('perception', 'midSpotMul', 1, 6), + num('perception', 'lookAroundSec', 2, 60, 's'), + num('perception', 'lookAroundHoldSec', 0.2, 5, 's'), + num('perception', 'discoverScore', 0.05, 0.95), ], }, { @@ -199,8 +206,6 @@ export const BOT_TUNING_GROUPS: readonly BotTuningGroup[] = [ customOnly: true, fields: [ num('tactics', 'visionRangeM', 200, 3500, 'm'), - num('tactics', 'visionFovDeg', 40, 180, '°'), - num('tactics', 'peripheralRangeM', 30, 800, 'm'), num('tactics', 'engineAudioRangeM', 10, 250, 'm'), num('tactics', 'shotAudioRangeM', 50, 1200, 'm'), num('tactics', 'radioShareRangeM', 50, 1500, 'm'), @@ -224,6 +229,31 @@ export const BOT_TUNING_GROUPS: readonly BotTuningGroup[] = [ num('estimation', 'maxBiasM', 0, 6, 'm'), ], }, + { + id: 'threat', + defaultOpen: false, + customOnly: true, + fields: [ + num('threat', 'rangeScaleM', 50, 3000, 'm'), + num('threat', 'discoveredMul', 0, 1), + num('threat', 'aimConeDeg', 5, 90, '°'), + num('threat', 'notAimingMul', 0, 1), + num('threat', 'unseenMul', 0, 1), + num('threat', 'hitMemorySec', 0, 60, 's'), + num('threat', 'hitMul', 1, 5), + ], + }, + { + id: 'turret', + defaultOpen: false, + customOnly: true, + fields: [ + num('turret', 'minDwellSec', 0, 5, 's'), + num('turret', 'switchMargin', 0, 3), + num('turret', 'scanArcDeg', 0, 180, '°'), + num('turret', 'scanPeriodSec', 1, 30, 's'), + ], + }, { id: 'fireControl', defaultOpen: false, diff --git a/apps/launcher/src/shared/schemas/tuning.ts b/apps/launcher/src/shared/schemas/tuning.ts index 3296b13..c900114 100644 --- a/apps/launcher/src/shared/schemas/tuning.ts +++ b/apps/launcher/src/shared/schemas/tuning.ts @@ -176,8 +176,15 @@ const GroundAiPerceptionSchema = z.object({ normalSpotSec: z.number().min(0.1).max(3), farSpotSec: z.number().min(0.3).max(6), decayPerSec: z.number().min(0.2).max(10), - frontConeHalfDeg: z.number().min(10).max(90), - peripheralCloseM: z.number().min(30).max(250), + gunFovHalfDeg: z.number().min(5).max(90), + nearAwareM: z.number().min(30).max(400), + nearArcDeg: z.number().min(90).max(360), + midAwareM: z.number().min(100).max(1500), + nearSpotMul: z.number().min(1).max(5), + midSpotMul: z.number().min(1).max(6), + lookAroundSec: z.number().min(2).max(60), + lookAroundHoldSec: z.number().min(0.2).max(5), + discoverScore: z.number().min(0.05).max(0.95), }); const GroundAiStateMachineSchema = z.object({ @@ -202,8 +209,6 @@ const GroundAiStateMachineSchema = z.object({ const GroundAiTacticsSchema = z.object({ visionRangeM: z.number().min(200).max(3500), - visionFovDeg: z.number().min(40).max(180), - peripheralRangeM: z.number().min(30).max(800), engineAudioRangeM: z.number().min(10).max(250), shotAudioRangeM: z.number().min(50).max(1200), radioShareRangeM: z.number().min(50).max(1500), @@ -212,6 +217,23 @@ const GroundAiTacticsSchema = z.object({ peekCooldownSec: z.number().min(1).max(30), }); +const GroundAiThreatSchema = z.object({ + rangeScaleM: z.number().min(50).max(3000), + discoveredMul: z.number().min(0).max(1), + aimConeDeg: z.number().min(5).max(90), + notAimingMul: z.number().min(0).max(1), + unseenMul: z.number().min(0).max(1), + hitMemorySec: z.number().min(0).max(60), + hitMul: z.number().min(1).max(5), +}); + +const GroundAiTurretSchema = z.object({ + minDwellSec: z.number().min(0).max(5), + switchMargin: z.number().min(0).max(3), + scanArcDeg: z.number().min(0).max(180), + scanPeriodSec: z.number().min(1).max(30), +}); + const GroundAiEstimationSchema = z.object({ watchMinSec: z.number().min(0.5).max(10), watchMaxSec: z.number().min(1).max(15), @@ -275,6 +297,8 @@ export const GroundAiTuningSchema = z.object({ stateMachine: GroundAiStateMachineSchema, tactics: GroundAiTacticsSchema, estimation: GroundAiEstimationSchema, + threat: GroundAiThreatSchema, + turret: GroundAiTurretSchema, fireControl: GroundAiFireControlSchema, diagnostics: GroundAiDiagnosticsSchema, }); @@ -297,6 +321,8 @@ export const GroundAiTuningPatchSchema = z.object({ stateMachine: GroundAiStateMachineSchema.partial().optional(), tactics: GroundAiTacticsSchema.partial().optional(), estimation: GroundAiEstimationSchema.partial().optional(), + threat: GroundAiThreatSchema.partial().optional(), + turret: GroundAiTurretSchema.partial().optional(), fireControl: GroundAiFireControlSchema.partial().optional(), diagnostics: GroundAiDiagnosticsSchema.partial().optional(), }); diff --git a/apps/server/src/tuning/ground-ai-tuning.ts b/apps/server/src/tuning/ground-ai-tuning.ts index 76d882e..2865a5c 100644 --- a/apps/server/src/tuning/ground-ai-tuning.ts +++ b/apps/server/src/tuning/ground-ai-tuning.ts @@ -57,6 +57,8 @@ export function readGroundAiTuning(reader: TuningReader): GroundAiTuning { stateMachine: readStateMachineSection(reader.object('stateMachine')), tactics: readTacticsSection(reader.object('tactics')), estimation: readEstimationSection(reader.object('estimation')), + threat: readThreatSection(reader.object('threat')), + turret: readTurretSection(reader.object('turret')), fireControl: readFireControlSection(reader.object('fireControl')), diagnostics: { telemetry: diag.bool('telemetry'), @@ -304,8 +306,15 @@ function readPerceptionSection(perc: TuningReader): GroundAiTuning['perception'] normalSpotSec: perc.number('normalSpotSec', { min: 0.1, max: 3.0 }), farSpotSec: perc.number('farSpotSec', { min: 0.3, max: 6.0 }), decayPerSec: perc.number('decayPerSec', { min: 0.2, max: 10.0 }), - frontConeHalfDeg: perc.number('frontConeHalfDeg', { min: 10, max: 90 }), - peripheralCloseM: perc.number('peripheralCloseM', { min: 30, max: 250 }), + gunFovHalfDeg: perc.number('gunFovHalfDeg', { min: 5, max: 90 }), + nearAwareM: perc.number('nearAwareM', { min: 30, max: 400 }), + nearArcDeg: perc.number('nearArcDeg', { min: 90, max: 360 }), + midAwareM: perc.number('midAwareM', { min: 100, max: 1500 }), + nearSpotMul: perc.number('nearSpotMul', { min: 1, max: 5 }), + midSpotMul: perc.number('midSpotMul', { min: 1, max: 6 }), + lookAroundSec: perc.number('lookAroundSec', { min: 2, max: 60 }), + lookAroundHoldSec: perc.number('lookAroundHoldSec', { min: 0.2, max: 5 }), + discoverScore: perc.number('discoverScore', { min: 0.05, max: 0.95 }), }; } @@ -339,8 +348,6 @@ function readStateMachineSection(sm: TuningReader): GroundAiTuning['stateMachine function readTacticsSection(tactics: TuningReader): GroundAiTuning['tactics'] { return { visionRangeM: tactics.number('visionRangeM', { min: 200, max: 3500 }), - visionFovDeg: tactics.number('visionFovDeg', { min: 40, max: 180 }), - peripheralRangeM: tactics.number('peripheralRangeM', { min: 30, max: 800 }), engineAudioRangeM: tactics.number('engineAudioRangeM', { min: 10, max: 250 }), shotAudioRangeM: tactics.number('shotAudioRangeM', { min: 50, max: 1200 }), radioShareRangeM: tactics.number('radioShareRangeM', { min: 50, max: 1500 }), @@ -350,6 +357,27 @@ function readTacticsSection(tactics: TuningReader): GroundAiTuning['tactics'] { }; } +function readThreatSection(threat: TuningReader): GroundAiTuning['threat'] { + return { + rangeScaleM: threat.number('rangeScaleM', { min: 50, max: 3000 }), + discoveredMul: threat.number('discoveredMul', { min: 0, max: 1 }), + aimConeDeg: threat.number('aimConeDeg', { min: 5, max: 90 }), + notAimingMul: threat.number('notAimingMul', { min: 0, max: 1 }), + unseenMul: threat.number('unseenMul', { min: 0, max: 1 }), + hitMemorySec: threat.number('hitMemorySec', { min: 0, max: 60 }), + hitMul: threat.number('hitMul', { min: 1, max: 5 }), + }; +} + +function readTurretSection(turret: TuningReader): GroundAiTuning['turret'] { + return { + minDwellSec: turret.number('minDwellSec', { min: 0, max: 5 }), + switchMargin: turret.number('switchMargin', { min: 0, max: 3 }), + scanArcDeg: turret.number('scanArcDeg', { min: 0, max: 180 }), + scanPeriodSec: turret.number('scanPeriodSec', { min: 1, max: 30 }), + }; +} + function readEstimationSection(est: TuningReader): GroundAiTuning['estimation'] { const watchMinSec = est.number('watchMinSec', { min: 0.5, max: 10.0 }); const watchMaxSec = est.number('watchMaxSec', { min: 1.0, max: 15.0 }); diff --git a/apps/server/tuning/ground-ai.jsonc b/apps/server/tuning/ground-ai.jsonc index 68e5fa4..a001f75 100644 --- a/apps/server/tuning/ground-ai.jsonc +++ b/apps/server/tuning/ground-ai.jsonc @@ -265,8 +265,21 @@ "normalSpotSec": 0.60, "farSpotSec": 1.45, "decayPerSec": 1.5, - "frontConeHalfDeg": 60.0, - "peripheralCloseM": 100.0 + // 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). + "gunFovHalfDeg": 30.0, + "nearAwareM": 150.0, + "nearArcDeg": 270.0, + "midAwareM": 600.0, + "nearSpotMul": 1.5, + "midSpotMul": 2.0, + "lookAroundSec": 8.0, + "lookAroundHoldSec": 1.0, + "discoverScore": 0.35 }, // Per-bot hull state machine timings and thresholds (offline values). @@ -293,9 +306,7 @@ "tactics": { "visionRangeM": 1250.0, - "visionFovDeg": 115.0, - "peripheralRangeM": 230.0, - "engineAudioRangeM": 65.0, + "engineAudioRangeM": 150.0, "shotAudioRangeM": 380.0, "radioShareRangeM": 450.0, "memoryTtlSec": 12.0, @@ -315,6 +326,32 @@ "maxBiasM": 2.2 }, + // Threat table (decision layer design, section 4): how dangerous each discovered enemy is to the + // bot. Danger falls with distance as 1 / (1 + distance / rangeScaleM) and is multiplied by + // discoveredMul until the enemy is seen clearly, by notAimingMul unless its hull or gun points + // within aimConeDeg of the bot (or it hit the bot), by unseenMul when the bot is out of its + // sight, and by hitMul for hitMemorySec after it hit the bot. Penetration is not counted yet. + "threat": { + "rangeScaleM": 400.0, + "discoveredMul": 0.7, + "aimConeDeg": 25.0, + "notAimingMul": 0.5, + "unseenMul": 0.4, + "hitMemorySec": 6.0, + "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. + "turret": { + "minDwellSec": 0.6, + "switchMargin": 0.25, + "scanArcDeg": 60.0, + "scanPeriodSec": 6.0 + }, + "fireControl": { "maxEngageRangeM": 1250.0, "closeRangeM": 100.0, diff --git a/game-ai/ground/wto_ai_combat_types_common.das b/game-ai/ground/wto_ai_combat_types_common.das index 14a0301..a949a3f 100644 --- a/game-ai/ground/wto_ai_combat_types_common.das +++ b/game-ai/ground/wto_ai_combat_types_common.das @@ -76,6 +76,39 @@ struct public WtoPerceiveState expEids : EntityId[8] expScore : float[8] expGoodLosSec : float[8] + expSeenAt : float[8] + expPos : float3[8] + nextLookAroundAt : float = 0.0 + lookAroundUntil : float = -100.0 + +// One discovered enemy in the bot's threat table (decision layer design, section 4). `seen`: seen +// clearly (fireable); `seesMe`: in line of sight this tick; `aiming`: its hull points at the bot or +// it hit the bot recently. +[safe_when_uninitialized] +struct public WtoThreatEntry + eid : EntityId = INVALID_ENTITY_ID + seen : bool = false + pos : float3 = float3(0.0, 0.0, 0.0) + dist : float = 0.0 + aiming : bool = false + 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). +[safe_when_uninitialized] +struct public WtoThreatTable + count : int = 0 + entries : WtoThreatEntry[8] + topIdx : int = -1 + topUnseenIdx : int = -1 + +// Turret channel (decision layer design, section 5): the threat it is looking at and until when +// that look is held. +[safe_when_uninitialized] +struct public WtoTurretState + lookEid : EntityId = INVALID_ENTITY_ID + holdUntil : float = -100.0 [safe_when_uninitialized] struct public WtoGunTraverse diff --git a/game-ai/ground/wto_ai_fire_common.das b/game-ai/ground/wto_ai_fire_common.das index 73bfcbd..a2dd027 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_turret_common [never_inline] def private wto_sync_active_shell(gun : WTGun const?; spec : WtoVehicleSpec const&; var fc : WtoFireState&) @@ -220,17 +221,15 @@ def public wto_fire_update(world : WtoWorldSnap const&; var unit : Unit?; classN var wishWorldDir = hFwd var aimPt = muzzlePos + hFwd * 50.0 var distToTgt = 9999.0 + // A clearly seen target is aimed at unless a more dangerous threat calls the turret away; + // otherwise the turret channel picks where to look (wto_ai_turret_common.das). let engageValid = (slot.perceive.hasClearLos && !!slot.perceive.targetEid && !slot.perceive.targetIsAir && - !(slot.spec.role == WTO_ROLE_SPAA && slot.tactics.state == WTO_STATE_DISABLED)) + !(slot.spec.role == WTO_ROLE_SPAA && slot.tactics.state == WTO_STATE_DISABLED) && !wto_turret_prefers_threat(slot)) if engageValid let baseAim = slot.perceive.visibleAimPt distToTgt = wto_solve_ballistic_aim(muzzlePos, unit.vel, slot, baseAim, aimPt, wishWorldDir) - elif now < slot.perceive.watchUntil - wishWorldDir = normalize(slot.perceive.watchPos - muzzlePos) - elif !!slot.perceive.targetEid && (now - slot.perceive.lastSeenAt) <= WTO_AI_TACTICS_MEMORY_TTL_SEC - wishWorldDir = normalize((slot.perceive.knownPos + float3(0.0, 1.4, 0.0)) - muzzlePos) - elif now < slot.perceive.alertUntil - wishWorldDir = float3(cos(slot.perceive.alertYawRad), 0.0, sin(slot.perceive.alertYawRad)) + else + wishWorldDir = wto_turret_look_dir(now, muzzlePos, unit.pos, hFwd, slot) var wishYaw = 0.0 var wishPitch = 0.0 diff --git a/game-ai/ground/wto_ai_perceive_common.das b/game-ai/ground/wto_ai_perceive_common.das index afb560b..c46018d 100644 --- a/game-ai/ground/wto_ai_perceive_common.das +++ b/game-ai/ground/wto_ai_perceive_common.das @@ -54,7 +54,7 @@ def private wto_exp_decay_all(world : WtoWorldSnap const&; dt : float; var p : W [never_inline] def private wto_spot_fill_time(dist : float; cosAngle : float; isShooting : bool; visCount : int) : float - let cosFront = cos(WTO_AI_PERC_FRONT_CONE_DEG * WTO_DEG_TO_RAD) + let cosFront = cos(WTO_AI_PERC_GUN_FOV_HALF_DEG * WTO_DEG_TO_RAD) var t = WTO_AI_PERC_FAR_SPOT_SEC if dist < WTO_AI_PERC_NEAR_SPOT_M || (isShooting && dist < WTO_AI_PERC_FIRING_SPOT_M) t = WTO_AI_PERC_FAST_SPOT_SEC @@ -99,15 +99,70 @@ 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) + 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)) + return WTO_AI_PERC_NEAR_SPOT_MUL + if dist <= WTO_AI_PERC_MID_AWARE_M && cosHull >= 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. `vis` gets the visible sample count, `aimPt` the first visible one. +[never_inline] +def private wto_exp_observe(world : WtoWorldSnap const&; now, dt : float; myEye, lookDir, hullDir : float3; + lookAround : bool; u : WtoUnitSnap const&; var slot : WtoBotSlot&; + var vis : int&; var aimPt : float3&) : int + assume p = slot.perceive + let delta = u.pos - 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) + 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 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.expGoodLosSec[tIdx] = vis >= 2 ? (p.expGoodLosSec[tIdx] + dt) : 0.0 + 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 + [never_inline] def private wto_scan_visual_exposure(world : WtoWorldSnap const&; now, dt : float; - myEye, lookDir : float3; var slot : WtoBotSlot&; + myEye, lookDir, hullDir : float3; lookAround : bool; var slot : WtoBotSlot&; var outBestIdx, outVisCount : int&; var outGoodLosSec : float&; var outAimPt : float3&) assume p = slot.perceive - let cosHalfFov = cos(0.5 * WTO_AI_TACTICS_VISION_FOV_DEG * WTO_DEG_TO_RAD) let isSpaa = slot.spec.role == WTO_ROLE_SPAA - let decay = WTO_AI_PERC_DECAY_PER_SEC * dt var bestScore = 1.0e9 outBestIdx = -1 outVisCount = 0 @@ -116,62 +171,49 @@ def private wto_scan_visual_exposure(world : WtoWorldSnap const&; now, dt : floa assume u = world.units[i] if !u.isAlive || u.army == slot.army || (u.isAir && !isSpaa) continue - let delta = u.pos - myEye - let dist = length(delta) - let maxRange = u.isAir ? 2600.0 : WTO_AI_TACTICS_VISION_RANGE_M - if dist > maxRange || dist < 1.0 + var vis = 0 + var aimPt = u.pos + let tIdx = wto_exp_observe(world, now, dt, myEye, lookDir, hullDir, lookAround, u, slot, vis, aimPt) + if tIdx < 0 || p.expScore[tIdx] < 0.999 continue - let dirXZ = wto_xz_normalize(delta, lookDir) - let cosAng = dot(dirXZ, lookDir) - let inFov = cosAng >= cosHalfFov || (dist <= WTO_AI_PERC_PERIPH_CLOSE_M && cosAng >= 0.0) - if !inFov && !u.isAir - continue - let maxSamples = dist > WTO_AI_FC_LONG_RANGE_M ? 2 : 4 - var samplePt = u.pos + float3(0.0, 1.3, 0.0) - let vis = wto_sight_check_target_samples(world, slot.eid, myEye, u, maxSamples, samplePt) - if vis <= 0 - for k in range(WTO_MAX_EXPOSURE_TRACKS) - if p.expEids[k] == u.eid - p.expGoodLosSec[k] = 0.0 - continue - let tIdx = wto_exp_find_or_alloc(p, u.eid) - let fillSec = wto_spot_fill_time(dist, cosAng, u.isShooting, vis) - p.expScore[tIdx] = clamp(p.expScore[tIdx] + decay + dt / fillSec, 0.0, 1.0) - p.expGoodLosSec[tIdx] = vis >= 2 ? (p.expGoodLosSec[tIdx] + dt) : 0.0 - if p.expScore[tIdx] < 0.999 - continue - 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 + let score = wto_exp_target_score(now, length(u.pos - myEye), u, isSpaa, p) if score < bestScore bestScore = score outBestIdx = i outVisCount = vis outGoodLosSec = p.expGoodLosSec[tIdx] - outAimPt = samplePt + 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)) + if p.nextLookAroundAt <= 0.0 + p.nextLookAroundAt = now + float(int(uint(slot.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 + return now < p.lookAroundUntil [never_inline] def public wto_perceive_update(var world : WtoWorldSnap&; now, dt : float; myPos, hullFwd : float3; var slot : WtoBotSlot&) assume p = slot.perceive let myEye = myPos + float3(0.0, 2.15, 0.0) - var lookDir = wto_xz_normalize(hullFwd, float3(1.0, 0.0, 0.0)) - if slot.fire.servoInit - let worldYaw = atan2(hullFwd.z, hullFwd.x) - slot.fire.curYawDeg * WTO_DEG_TO_RAD - lookDir = float3(cos(worldYaw), 0.0, sin(worldYaw)) - + 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) var bestIdx = -1 var visCount = 0 var goodLosSec = 0.0 var aimPt = myPos - wto_scan_visual_exposure(world, now, dt, myEye, lookDir, slot, bestIdx, visCount, goodLosSec, aimPt) + wto_scan_visual_exposure(world, now, dt, myEye, lookDir, hullDir, lookAround, slot, bestIdx, visCount, goodLosSec, aimPt) if bestIdx >= 0 assume tgt = world.units[bestIdx] p.targetEid = tgt.eid diff --git a/game-ai/ground/wto_ai_runtime.das b/game-ai/ground/wto_ai_runtime.das index 8916db4..10ac9f8 100644 --- a/game-ai/ground/wto_ai_runtime.das +++ b/game-ai/ground/wto_ai_runtime.das @@ -40,6 +40,8 @@ require %appGame.wtoai.wto_ai_drive_common require %appGame.wtoai.wto_ai_fire_common require %appGame.wtoai.wto_ai_diag_common require %appGame.wtoai.wto_ai_stats_common +require %appGame.wtoai.wto_ai_slots_common +require %appGame.wtoai.wto_ai_threat_common var private @safe_when_uninitialized g_world : WtoWorldSnap var private @safe_when_uninitialized g_crowd : WtoCrowdSummary @@ -79,68 +81,7 @@ def private wto_reset_runtime() g_last_zone_ver = -1 g_next_diag_at = 0.0 wto_navmesh_battle_reset(g_navmesh) - for i in range(WTO_MAX_BOTS) - if g_bots[i].drive.routeBOwned - wto_drive_request_control(g_bots[i].eid, 0) - g_bots[i] = WtoBotSlot() - wto_drive_release_all() - -[never_inline] -def private wto_find_slot(eid : EntityId) : int - let cap = min(WTO_MAX_BOTS, WTO_AI_MAX_TRACKED_BOTS) - for i in range(cap) - if g_bots[i].used && g_bots[i].eid == eid - return i - return -1 - -[never_inline] -def private wto_forget_unit(eid : EntityId) - let idx = wto_find_slot(eid) - if idx >= 0 - if g_bots[idx].drive.routeBOwned - wto_drive_request_control(eid, 0) - g_bots[idx] = WtoBotSlot() - g_cmd_dirty = true - for i in range(WTO_MAX_BOTS) - if g_bots[i].used && g_bots[i].tactics.engageTargetEid == eid - g_bots[i].tactics.engageShotsNoEffect = 0 - g_bots[i].tactics.engageNoShotHalts = 0 - g_bots[i].tactics.engageTotalHaltSec = 0.0 - -[never_inline] -def private wto_acquire_slot(eid : EntityId; army : int; now : float) : int - let cap = min(WTO_MAX_BOTS, WTO_AI_MAX_TRACKED_BOTS) - var freeIdx = -1 - for i in range(cap) - if g_bots[i].used && g_bots[i].eid == eid - g_bots[i].army = army - g_bots[i].lastSeenAt = now - return i - if !g_bots[i].used && freeIdx < 0 - freeIdx = i - if freeIdx >= 0 - g_bots[freeIdx] = WtoBotSlot() - g_bots[freeIdx].used = true - g_bots[freeIdx].eid = eid - g_bots[freeIdx].army = army - g_bots[freeIdx].lastSeenAt = now - g_bots[freeIdx].nextTacticsAt = now - 0.01 - g_bots[freeIdx].nextNavAt = now - 0.01 - g_bots[freeIdx].route.nextReplanAt = now - 0.01 - g_cmd_dirty = true - return freeIdx - -[never_inline] -def private wto_phys_slot_available() : bool - if WTO_AI_NAV_MAX_PHYS_BOTS <= 0 - return false - var count = 0 - for i in range(WTO_MAX_BOTS) - if g_bots[i].used && g_bots[i].drive.routeBOwned && !g_bots[i].drive.routeAFallback - count++ - if count >= WTO_AI_NAV_MAX_PHYS_BOTS - return false - return true + wto_slots_reset_all(g_bots) [es(tag=server, on_event=(EventMissionUnload, EventEntityManagerBeforeClear, EventEcsMissionLoaded))] def wto_ai_mission_reset_es(evt : Event) @@ -168,11 +109,13 @@ def wto_ai_unit_dead_es(evt : Event; eid : EntityId; unit__ref : UnitRef) let now = float(get_app().usefulTotalTime) wto_world_record_death(g_world, eid, int(u.army), u.pos, now) wto_route_report_wreck(g_navmesh.state, now, u.pos, g_bots) - wto_forget_unit(eid) + if wto_slots_forget(g_bots, eid) + g_cmd_dirty = true [es(tag=server, on_disappear, on_event=EventUnitRespawn)] def wto_ai_unit_cleanup_es(evt : Event; eid : EntityId) - wto_forget_unit(eid) + if wto_slots_forget(g_bots, eid) + g_cmd_dirty = true [es(tag=server)] def wto_ai_unit_damage_es(evt : EventUnitDamage; eid : EntityId; unit__ref : UnitRef) @@ -182,27 +125,8 @@ def wto_ai_unit_damage_es(evt : EventUnitDamage; eid : EntityId; unit__ref : Uni let u = unit__ref.unit if u == null || !offEid || offEid == eid return - let now = float(get_app().usefulTotalTime) - let vicArmy = int(u.army) - // Outgoing effective damage confirmation for our firing bot (resets stalemate counters). - let offBotIdx = wto_find_slot(offEid) - if offBotIdx >= 0 && g_bots[offBotIdx].army != vicArmy && uint(evt.hpFixed) < uint(evt.prevHpFixed) - assume tac = g_bots[offBotIdx].tactics - if tac.engageTargetEid == eid || g_bots[offBotIdx].perceive.targetEid == eid - tac.engageShotsNoEffect = 0 - tac.engageNoShotHalts = 0 - tac.lastEffectAt = now - // Incoming hit direction cue for our damaged bot (never leaks hidden offender coords). - let idx = wto_find_slot(eid) - if idx < 0 - return - let offUnitIdx = wto_world_find_unit(g_world, offEid) - if offUnitIdx >= 0 && g_world.units[offUnitIdx].army == g_bots[idx].army - return - let imp = evt.pos - u.pos - g_bots[idx].perceive.lastHitYawRad = (imp.x * imp.x + imp.z * imp.z) > 0.04 ? atan2(imp.z, imp.x) : atan2(u.unitTm[0].z, u.unitTm[0].x) - g_bots[idx].perceive.lastDamagedAt = now - g_bots[idx].perceive.lastOffenderEid = offEid + let hpDropped = uint(evt.hpFixed) < uint(evt.prevHpFixed) + wto_slots_on_damage(g_world, g_bots, eid, offEid, u, evt.pos, hpDropped, float(get_app().usefulTotalTime)) [es(tag=server, before=wto_ai_pipeline_es)] def wto_ai_world_tick_es(act : UpdateStageInfoAct) @@ -215,9 +139,7 @@ def wto_ai_world_tick_es(act : UpdateStageInfoAct) let now = float(get_app().usefulTotalTime) if g_world.valid && now < g_world.time - 1.0 wto_reset_runtime() - for i in range(WTO_MAX_BOTS) - if g_bots[i].used && (now - g_bots[i].lastSeenAt) > 3.5 - g_bots[i] = WtoBotSlot() + wto_slots_drop_stale(g_bots, now) if !g_world.valid wto_drive_announce_script_ready() print("WTO_AI|RUNTIME_READY\n") @@ -259,7 +181,9 @@ def wto_ai_pipeline_es(act : UpdateStageInfoAct; eid : EntityId; var unit__ref : if (army != 1 && army != 2) || gm == null || gm.moveSys == null || as_hv(unit) == null return let now = float(get_app().usefulTotalTime) - let idx = wto_acquire_slot(eid, army, now) + var created = false + let idx = wto_slots_acquire(g_bots, eid, army, now, created) + g_cmd_dirty = g_cmd_dirty || created if idx < 0 return assume slot = g_bots[idx] @@ -270,6 +194,7 @@ def wto_ai_pipeline_es(act : UpdateStageInfoAct; eid : EntityId; var unit__ref : 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_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) // A failed pack with navEngine.allowFallback off leaves every bot standing for the battle. @@ -286,10 +211,10 @@ def wto_ai_phys_tick_es(act : UpdateStageInfoAct; eid : EntityId; var unit__ref var unit = unit__ref.unit if unit == null || !unit.isAlive || unit.isDelayed || unit.isHumanPlayer || vehicle_net_phys.physEdit == null return - let idx = wto_find_slot(eid) + let idx = wto_slots_find(g_bots, eid) if idx < 0 return - if !g_bots[idx].drive.routeBOwned && !wto_phys_slot_available() + if !g_bots[idx].drive.routeBOwned && !wto_slots_phys_available(g_bots) return let now = float(get_app().usefulTotalTime) wto_drive_step_phys(unit, unit__missionName, as_gm(unit), vehicle_net_phys, act.dt, now, g_bots[idx]) diff --git a/game-ai/ground/wto_ai_slots_common.das b/game-ai/ground/wto_ai_slots_common.das new file mode 100644 index 0000000..fd19219 --- /dev/null +++ b/game-ai/ground/wto_ai_slots_common.das @@ -0,0 +1,113 @@ +// Bot slots of the ground AI runtime: finding, acquiring and freeing a bot's slot, the cap on +// bots driven through vehicle physics, and the per-hit bookkeeping of EventUnitDamage. +options indenting = 2 +options no_global_heap = true +module wto_ai_slots_common shared + +require ecs +require math +require Unit +require %appGame.wtoai.wto_ai_config_common +require %appGame.wtoai.wto_ai_combat_types_common +require %appGame.wtoai.wto_ai_types_common +require %appGame.wtoai.wto_ai_world_common +require %appGame.wtoai.wto_ai_drive_common + +[never_inline] +def public wto_slots_find(bots : WtoBotSlot[64]; eid : EntityId) : int + let cap = min(WTO_MAX_BOTS, WTO_AI_MAX_TRACKED_BOTS) + for i in range(cap) + if bots[i].used && bots[i].eid == eid + return i + return -1 + +// Frees the unit's slot and clears engagement counters aimed at it; true when a slot was freed. +[never_inline] +def public wto_slots_forget(var bots : WtoBotSlot[64]; eid : EntityId) : bool + let idx = wto_slots_find(bots, eid) + if idx >= 0 + if bots[idx].drive.routeBOwned + wto_drive_request_control(eid, 0) + bots[idx] = WtoBotSlot() + for i in range(WTO_MAX_BOTS) + if bots[i].used && bots[i].tactics.engageTargetEid == eid + bots[i].tactics.engageShotsNoEffect = 0 + bots[i].tactics.engageNoShotHalts = 0 + bots[i].tactics.engageTotalHaltSec = 0.0 + return idx >= 0 + +// The unit's slot, taking a free one for a new unit (then `created` is set); -1 when full. +[never_inline] +def public wto_slots_acquire(var bots : WtoBotSlot[64]; eid : EntityId; army : int; now : float; + var created : bool&) : int + let cap = min(WTO_MAX_BOTS, WTO_AI_MAX_TRACKED_BOTS) + var freeIdx = -1 + for i in range(cap) + if bots[i].used && bots[i].eid == eid + bots[i].army = army + bots[i].lastSeenAt = now + return i + if !bots[i].used && freeIdx < 0 + freeIdx = i + if freeIdx >= 0 + bots[freeIdx] = WtoBotSlot() + bots[freeIdx].used = true + bots[freeIdx].eid = eid + bots[freeIdx].army = army + bots[freeIdx].lastSeenAt = now + bots[freeIdx].nextTacticsAt = now - 0.01 + bots[freeIdx].nextNavAt = now - 0.01 + bots[freeIdx].route.nextReplanAt = now - 0.01 + created = true + return freeIdx + +// Releases vehicle control of every bot and clears all slots. +[never_inline] +def public wto_slots_reset_all(var bots : WtoBotSlot[64]) + for i in range(WTO_MAX_BOTS) + if bots[i].drive.routeBOwned + wto_drive_request_control(bots[i].eid, 0) + bots[i] = WtoBotSlot() + wto_drive_release_all() + +// Slots not refreshed by the pipeline for a while belong to units that are gone. +[never_inline] +def public wto_slots_drop_stale(var bots : WtoBotSlot[64]; now : float) + for i in range(WTO_MAX_BOTS) + if bots[i].used && (now - bots[i].lastSeenAt) > 3.5 + bots[i] = WtoBotSlot() + +[never_inline] +def public wto_slots_phys_available(bots : WtoBotSlot[64]) : bool + if WTO_AI_NAV_MAX_PHYS_BOTS <= 0 + return false + var count = 0 + for i in range(WTO_MAX_BOTS) + if bots[i].used && bots[i].drive.routeBOwned && !bots[i].drive.routeAFallback + count++ + if count >= WTO_AI_NAV_MAX_PHYS_BOTS + return false + return true + +// A hit on `eid` by `offEid`: confirms an effective shot of our firing bot (resetting its stalemate +// counters) and gives our damaged bot the direction it was hit from (never the offender's position). +[never_inline] +def public wto_slots_on_damage(world : WtoWorldSnap const&; var bots : WtoBotSlot[64]; eid, offEid : EntityId; + u : Unit const?; hitPos : float3; hpDropped : bool; now : float) + let offBotIdx = wto_slots_find(bots, offEid) + if offBotIdx >= 0 && bots[offBotIdx].army != int(u.army) && hpDropped + assume tac = bots[offBotIdx].tactics + if tac.engageTargetEid == eid || bots[offBotIdx].perceive.targetEid == eid + tac.engageShotsNoEffect = 0 + tac.engageNoShotHalts = 0 + tac.lastEffectAt = now + let idx = wto_slots_find(bots, eid) + if idx < 0 + return + let offUnitIdx = wto_world_find_unit(world, offEid) + if offUnitIdx >= 0 && world.units[offUnitIdx].army == bots[idx].army + return + let imp = hitPos - u.pos + bots[idx].perceive.lastHitYawRad = (imp.x * imp.x + imp.z * imp.z) > 0.04 ? atan2(imp.z, imp.x) : atan2(u.unitTm[0].z, u.unitTm[0].x) + bots[idx].perceive.lastDamagedAt = now + bots[idx].perceive.lastOffenderEid = offEid diff --git a/game-ai/ground/wto_ai_stats_common.das b/game-ai/ground/wto_ai_stats_common.das index 1004683..83fce0c 100644 --- a/game-ai/ground/wto_ai_stats_common.das +++ b/game-ai/ground/wto_ai_stats_common.das @@ -3,7 +3,7 @@ // ends: time from acquiring a target to the first shot at it, time with a target in sight and the // gun ready split by the last reason a shot was refused, shots by distance band and motion, and a // sample every statsSampleSec of the nearest enemy in line of sight (known or not, turret error, -// rear facing it). +// rear facing it). "Known" means discovered: in the bot's threat table. options indenting = 2 options no_global_heap = true module wto_ai_stats_common shared @@ -139,8 +139,8 @@ def private wto_stats_nearest_seen(world : WtoWorldSnap const&; myPos : float3; def private wto_stats_knows(slot : WtoBotSlot const&; eid : EntityId) : bool if slot.perceive.targetEid == eid return true - for k in range(WTO_MAX_EXPOSURE_TRACKS) - if slot.perceive.expEids[k] == eid && slot.perceive.expScore[k] >= 0.5 + for i in range(slot.threat.count) + if slot.threat.entries[i].eid == eid return true return false diff --git a/game-ai/ground/wto_ai_threat_common.das b/game-ai/ground/wto_ai_threat_common.das new file mode 100644 index 0000000..41ffeee --- /dev/null +++ b/game-ai/ground/wto_ai_threat_common.das @@ -0,0 +1,76 @@ +// 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). +options indenting = 2 +options no_global_heap = true +module wto_ai_threat_common shared + +require ecs +require math +require %appGame.wtoai.wto_ai_config_common +require %appGame.wtoai.wto_ai_math_common +require %appGame.wtoai.wto_ai_combat_types_common +require %appGame.wtoai.wto_ai_types_common +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 + return true + 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 + 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 + +[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.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) + 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 + tt.count++ + +// Per perception tick, right after wto_perceive_update. +[never_inline] +def public wto_threat_update(world : WtoWorldSnap const&; now : float; myPos : float3; var slot : WtoBotSlot&) + 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 + continue + let uIdx = wto_world_find_unit(world, p.expEids[k]) + if uIdx >= 0 && world.units[uIdx].isAlive && !world.units[uIdx].isAir + wto_threat_add(now, myPos, world.units[uIdx], k, slot) + +// Danger of `eid` in the bot's table; 0 when it is not there. +def public wto_threat_danger_of(slot : WtoBotSlot const&; eid : EntityId) : float + for i in range(slot.threat.count) + if slot.threat.entries[i].eid == eid + return slot.threat.entries[i].danger + return 0.0 diff --git a/game-ai/ground/wto_ai_turret_common.das b/game-ai/ground/wto_ai_turret_common.das new file mode 100644 index 0000000..28f71db --- /dev/null +++ b/game-ai/ground/wto_ai_turret_common.das @@ -0,0 +1,70 @@ +// 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. +options indenting = 2 +options no_global_heap = true +module wto_ai_turret_common shared + +require ecs +require math +require %appGame.wtoai.wto_ai_config_common +require %appGame.wtoai.wto_ai_math_common +require %appGame.wtoai.wto_ai_combat_types_common +require %appGame.wtoai.wto_ai_types_common +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 + 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) + +// 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 + tr.holdUntil = now + WTO_AI_TURRET_MIN_DWELL_SEC + return top + +// Sweep across the route: scanArcDeg either side of where the bot drives (or of its order goal +// when it stands), one sweep every scanPeriodSec, phase spread by entity id. +[never_inline] +def private wto_turret_scan_dir(now : float; myPos, hullFwd : float3; slot : WtoBotSlot const&) : float3 + var base = wto_xz_normalize(hullFwd, float3(1.0, 0.0, 0.0)) + if slot.tactics.desiredSpeedMps > 0.5 + base = wto_xz_normalize(slot.nav.steerDir, base) + elif slot.order.valid + base = wto_xz_normalize(slot.order.goalPos - myPos, base) + let phase = now * 6.2831853 / WTO_AI_TURRET_SCAN_PERIOD_SEC + float(int(uint(slot.eid) % 16u)) * 0.4 + let yaw = atan2(base.z, base.x) + WTO_AI_TURRET_SCAN_ARC_DEG * WTO_DEG_TO_RAD * sin(phase) + return float3(cos(yaw), 0.0, sin(yaw)) + +// World direction from the muzzle for the turret when it is not aiming at an engaged target. +[never_inline] +def public wto_turret_look_dir(now : float; muzzlePos, myPos, hullFwd : float3; var slot : WtoBotSlot&) : float3 + assume p = slot.perceive + let threat = wto_turret_pick_threat(now, slot) + if threat >= 0 + return normalize((slot.threat.entries[threat].pos + float3(0.0, 1.4, 0.0)) - muzzlePos) + if now < p.watchUntil + return normalize(p.watchPos - muzzlePos) + if !!p.targetEid && (now - p.lastSeenAt) <= WTO_AI_TACTICS_MEMORY_TTL_SEC + return normalize((p.knownPos + float3(0.0, 1.4, 0.0)) - muzzlePos) + if now < p.alertUntil + return float3(cos(p.alertYawRad), 0.0, sin(p.alertYawRad)) + return wto_turret_scan_dir(now, myPos, hullFwd, slot) diff --git a/game-ai/ground/wto_ai_types_common.das b/game-ai/ground/wto_ai_types_common.das index a1e8964..ae643b9 100644 --- a/game-ai/ground/wto_ai_types_common.das +++ b/game-ai/ground/wto_ai_types_common.das @@ -251,3 +251,5 @@ struct public WtoBotSlot drive : WtoDriveState = WtoDriveState() fire : WtoFireState = WtoFireState() stats : WtoBotStats = WtoBotStats() + threat : WtoThreatTable = WtoThreatTable() + turret : WtoTurretState = WtoTurretState() diff --git a/packages/patcher/src/ground-ai/ground-ai-config.ts b/packages/patcher/src/ground-ai/ground-ai-config.ts index 54b66ce..e06c03f 100644 --- a/packages/patcher/src/ground-ai/ground-ai-config.ts +++ b/packages/patcher/src/ground-ai/ground-ai-config.ts @@ -194,8 +194,15 @@ export interface GroundAiConfig { readonly normalSpotSec: number; readonly farSpotSec: number; readonly decayPerSec: number; - readonly frontConeHalfDeg: number; - readonly peripheralCloseM: number; + readonly gunFovHalfDeg: number; + readonly nearAwareM: number; + readonly nearArcDeg: number; + readonly midAwareM: number; + readonly nearSpotMul: number; + readonly midSpotMul: number; + readonly lookAroundSec: number; + readonly lookAroundHoldSec: number; + readonly discoverScore: number; }; readonly stateMachine: { readonly preaimAngleDeg: number; @@ -218,8 +225,6 @@ export interface GroundAiConfig { }; readonly tactics: { readonly visionRangeM: number; - readonly visionFovDeg: number; - readonly peripheralRangeM: number; readonly engineAudioRangeM: number; readonly shotAudioRangeM: number; readonly radioShareRangeM: number; @@ -237,6 +242,21 @@ export interface GroundAiConfig { readonly leadErrorFrac: number; readonly maxBiasM: number; }; + readonly threat: { + readonly rangeScaleM: number; + readonly discoveredMul: number; + readonly aimConeDeg: number; + readonly notAimingMul: number; + readonly unseenMul: number; + readonly hitMemorySec: number; + readonly hitMul: number; + }; + readonly turret: { + readonly minDwellSec: number; + readonly switchMargin: number; + readonly scanArcDeg: number; + readonly scanPeriodSec: number; + }; readonly fireControl: { readonly maxEngageRangeM: number; readonly closeRangeM: number; @@ -390,8 +410,15 @@ function collectConfigEntries(c: GroundAiConfig): readonly DasEntry[] { ['WTO_AI_PERC_NORMAL_SPOT_SEC', 'float', c.perception.normalSpotSec], ['WTO_AI_PERC_FAR_SPOT_SEC', 'float', c.perception.farSpotSec], ['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_PERC_GUN_FOV_HALF_DEG', 'float', c.perception.gunFovHalfDeg], + ['WTO_AI_PERC_NEAR_AWARE_M', 'float', c.perception.nearAwareM], + ['WTO_AI_PERC_NEAR_ARC_DEG', 'float', c.perception.nearArcDeg], + ['WTO_AI_PERC_MID_AWARE_M', 'float', c.perception.midAwareM], + ['WTO_AI_PERC_NEAR_SPOT_MUL', 'float', c.perception.nearSpotMul], + ['WTO_AI_PERC_MID_SPOT_MUL', 'float', c.perception.midSpotMul], + ['WTO_AI_PERC_LOOK_AROUND_SEC', 'float', c.perception.lookAroundSec], + ['WTO_AI_PERC_LOOK_AROUND_HOLD_SEC', 'float', c.perception.lookAroundHoldSec], + ['WTO_AI_PERC_DISCOVER_SCORE', 'float', c.perception.discoverScore], ['WTO_AI_SM_PREAIM_DEG', 'float', c.stateMachine.preaimAngleDeg], ['WTO_AI_SM_MOVING_SHOT_WAIT_SEC', 'float', c.stateMachine.movingShotWaitSec], ['WTO_AI_SM_SHORT_HALT_MAX_SEC', 'float', c.stateMachine.shortHaltMaxSec], @@ -410,8 +437,6 @@ function collectConfigEntries(c: GroundAiConfig): readonly DasEntry[] { ['WTO_AI_SM_REPOS_STEP_M', 'float', c.stateMachine.repositionStepM], ['WTO_AI_SM_REPAIR_SAFE_DIST_M', 'float', c.stateMachine.repairSafeEnemyDistM], ['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], ['WTO_AI_TACTICS_ENGINE_AUDIO_M', 'float', c.tactics.engineAudioRangeM], ['WTO_AI_TACTICS_SHOT_AUDIO_M', 'float', c.tactics.shotAudioRangeM], ['WTO_AI_TACTICS_RADIO_SHARE_M', 'float', c.tactics.radioShareRangeM], @@ -426,6 +451,17 @@ function collectConfigEntries(c: GroundAiConfig): readonly DasEntry[] { ['WTO_AI_EST_BASE_SIGMA_M', 'float', c.estimation.baseAimSigmaM], ['WTO_AI_EST_LEAD_ERR_FRAC', 'float', c.estimation.leadErrorFrac], ['WTO_AI_EST_MAX_BIAS_M', 'float', c.estimation.maxBiasM], + ['WTO_AI_THREAT_RANGE_SCALE_M', 'float', c.threat.rangeScaleM], + ['WTO_AI_THREAT_DISCOVERED_MUL', 'float', c.threat.discoveredMul], + ['WTO_AI_THREAT_AIM_CONE_DEG', 'float', c.threat.aimConeDeg], + ['WTO_AI_THREAT_NOT_AIMING_MUL', 'float', c.threat.notAimingMul], + ['WTO_AI_THREAT_UNSEEN_MUL', 'float', c.threat.unseenMul], + ['WTO_AI_THREAT_HIT_MEMORY_SEC', 'float', c.threat.hitMemorySec], + ['WTO_AI_THREAT_HIT_MUL', 'float', c.threat.hitMul], + ['WTO_AI_TURRET_MIN_DWELL_SEC', 'float', c.turret.minDwellSec], + ['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_FC_MAX_RANGE_M', 'float', c.fireControl.maxEngageRangeM], ['WTO_AI_FC_CLOSE_RANGE_M', 'float', c.fireControl.closeRangeM], ['WTO_AI_FC_MID_RANGE_M', 'float', c.fireControl.midRangeM],