diff --git a/apps/launcher/src/renderer/src/i18n/locales/en.json b/apps/launcher/src/renderer/src/i18n/locales/en.json index 559c22e..7642034 100644 --- a/apps/launcher/src/renderer/src/i18n/locales/en.json +++ b/apps/launcher/src/renderer/src/i18n/locales/en.json @@ -516,6 +516,7 @@ "fireControl": "Fire control & fire gate", "navigation": "Driving & navigation", "navEngine": "Map navigation mesh & path costs", + "pathFollow": "Path following & unstick", "crowd": "Spacing & crowd dispersal", "terrain": "Terrain & ridge limits", "runtime": "Tick cadence & diagnostics" @@ -531,8 +532,9 @@ "tactics": "Vision range, audio detection, radio sharing and target memory", "estimation": "Sample-based velocity lead, exit watch and natural shot spread", "fireControl": "Range bands, speed gates, barrel settle and ballistic safety", - "navigation": "Drive backend, corner braking, pivot turns and unstick reverse", + "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", + "pathFollow": "Replanning, lookahead steering, corner and arrival braking, narrow passages, bumper rays, traffic yielding, three-level unstick and temporary path costs", "crowd": "Personal space and ally cluster dispersal", "terrain": "Climb/drop slope limits, water depth and ridge peek caps", "runtime": "Script update intervals and telemetry logging" @@ -670,19 +672,17 @@ "steerSign": "Steering input polarity", "deadEchoSec": "Dead-echo detection timeout", "controlTimeoutSec": "Native control release timeout", - "cornerBrakeAccel": "Corner braking deceleration", "movingFireSpeedRampMps": "Speed error for full throttle or braking while firing on the move", "pivotAngleDeg": "Neutral pivot turn angle threshold", - "stuckWindowSec": "Stuck detection window", - "stuckMinMoveM": "Stuck min movement distance", - "unstickReverseSec": "Unstick reverse duration", "tacticalReverseDistM": "Tactical reverse max distance", "tacticalReverseMaxSec": "Tactical reverse max duration" }, "navEngine": { "enabled": "Use map navigation packs", "allowFallback": "Fall back to the old pathing for the battle when a pack is missing or broken", - "snapRadiusM": "Max distance from a path's start or goal to the mesh" + "snapRadiusM": "Max distance from a path's start or goal to the mesh", + "goalSnapRadiusM": "Max distance a path goal may be moved onto the mesh", + "pathBudgetMsPerFrame": "Path search time per frame" }, "navCostsTracked": { "road": "Tracked · road cost", @@ -704,6 +704,44 @@ "shallowWater": "Wheeled · shallow water cost", "chokepoint": "Wheeled · chokepoint multiplier" }, + "pathFollow": { + "replanIntervalSec": "Regular path replanning interval", + "replanGoalMoveM": "Goal movement that triggers a new path", + "offCorridorReplanM": "Distance off the path that triggers a new path", + "lookaheadTimeSec": "Lookahead time at current speed", + "trackedLookaheadMinM": "Tracked · min lookahead distance", + "trackedLookaheadMaxM": "Tracked · max lookahead distance", + "wheeledLookaheadMinM": "Wheeled · min lookahead distance", + "wheeledLookaheadMaxM": "Wheeled · max lookahead distance", + "cornerAngleDeg": "Path corner angle that needs slowing down", + "cornerLateralAccelMps2": "Allowed sideways acceleration in corners", + "cornerBrakeDecelMps2": "Braking deceleration before corners and the destination", + "arriveRadiusM": "Arrival radius at the destination", + "arriveMinSpeedMps": "Min speed while approaching the destination", + "narrowWallMarginM": "Room to the mesh edge below which a passage counts as narrow", + "narrowSpeedMps": "Speed cap in narrow passages", + "bumperRayM": "Front corner ray length", + "bumperStopM": "Stop distance before an obstacle hit by the front rays", + "bumperBlockSec": "Time blocked before an obstacle is reported", + "trafficTtcSec": "Vehicle collision look-ahead time", + "avoidShiftM": "Sideways step around vehicles and wrecks", + "yieldWaitMaxSec": "Max wait while giving way in narrow passages", + "stuckWindowSec": "Stuck detection window", + "stuckMinProgressM": "Min progress within the stuck window", + "unstickReverseM": "Unstick reverse distance", + "unstickReverseSec": "Unstick reverse max duration", + "unstickRepeatSec": "Time within which a repeated stuck escalates", + "unstickMaxAttempts": "Unstick attempts before giving up the order", + "jamRadiusM": "Jam cost radius", + "jamCostMul": "Jam path cost multiplier", + "jamTtlSec": "Jam cost duration", + "rubbleRadiusM": "Fresh obstacle cost radius", + "rubbleCostMul": "Fresh obstacle path cost multiplier", + "rubbleTtlSec": "Fresh obstacle cost duration", + "wreckRadiusM": "Wreck cost radius", + "wreckCostMul": "Wreck path cost multiplier", + "wreckTtlSec": "Wreck cost duration" + }, "crowd": { "personalSpaceM": "Personal spacing distance", "clusterRadiusM": "Ally cluster detection radius", 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 12b25c4..94ee57a 100644 --- a/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json +++ b/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json @@ -516,6 +516,7 @@ "fireControl": "火控与开火许可", "navigation": "机动与寻路控制", "navEngine": "地图导航网格与通行代价", + "pathFollow": "跟路驾驶与脱困", "crowd": "编队间距与避让", "terrain": "地形与棱线约束", "runtime": "运行频率与诊断" @@ -531,8 +532,9 @@ "tactics": "视距、听觉发现范围、电台共享与记忆时长", "estimation": "本车目击测速、守出口时长与自然散布", "fireControl": "距离分档、车速门槛、稳定等待与弹道防误伤", - "navigation": "底层驱动方式、转向刹车与脱困倒车", + "navigation": "驱动方式、原地转向与战术倒车", "navEngine": "离线地图导航包的启用与降级,以及履带 / 轮式车在各类地表上的寻路代价", + "pathFollow": "重新寻路、前瞻跟路、弯道与到达前减速、窄路限速、车头射线、会车让路、三级脱困与临时寻路代价", "crowd": "友军安全间距与扎堆疏散", "terrain": "爬坡 / 下坡角度、涉水深度与探头限制", "runtime": "脚本刷新间隔与调试遥测日志" @@ -670,19 +672,17 @@ "steerSign": "转向输入方向", "deadEchoSec": "无响应回声判定时长", "controlTimeoutSec": "原生控制超时归还时长", - "cornerBrakeAccel": "弯道减速制动强度", "movingFireSpeedRampMps": "行进射击时全油门或全制动对应的速度差", "pivotAngleDeg": "原地中性转向角度阈值", - "stuckWindowSec": "卡死检测窗口时长", - "stuckMinMoveM": "卡死判定最小位移", - "unstickReverseSec": "脱困倒车持续时长", "tacticalReverseDistM": "战术倒车最大距离", "tacticalReverseMaxSec": "战术倒车最长时长" }, "navEngine": { "enabled": "启用地图导航包", "allowFallback": "缺少或损坏时整局退回旧寻路", - "snapRadiusM": "起终点吸附到导航网格的最大距离" + "snapRadiusM": "起终点吸附到导航网格的最大距离", + "goalSnapRadiusM": "目标点吸附到导航网格的最远距离", + "pathBudgetMsPerFrame": "每帧寻路计算时间上限" }, "navCostsTracked": { "road": "履带车 · 道路代价", @@ -704,6 +704,44 @@ "shallowWater": "轮式车 · 浅滩涉水代价", "chokepoint": "轮式车 · 窄口代价倍率" }, + "pathFollow": { + "replanIntervalSec": "定时重新寻路间隔", + "replanGoalMoveM": "目标移动多远后重新寻路", + "offCorridorReplanM": "偏离路线多远后重新寻路", + "lookaheadTimeSec": "按当前车速前瞻的时间", + "trackedLookaheadMinM": "履带车 · 最短前瞻距离", + "trackedLookaheadMaxM": "履带车 · 最长前瞻距离", + "wheeledLookaheadMinM": "轮式车 · 最短前瞻距离", + "wheeledLookaheadMaxM": "轮式车 · 最长前瞻距离", + "cornerAngleDeg": "需要减速的路线拐角角度", + "cornerLateralAccelMps2": "过弯允许的横向加速度", + "cornerBrakeDecelMps2": "弯前和到达前的减速度", + "arriveRadiusM": "到达目标的判定半径", + "arriveMinSpeedMps": "接近目标时的最低车速", + "narrowWallMarginM": "离网格边缘小于多少算窄路", + "narrowSpeedMps": "窄路限速", + "bumperRayM": "车头两侧射线长度", + "bumperStopM": "车头射线碰到障碍时的停车距离", + "bumperBlockSec": "被挡多久后上报障碍", + "trafficTtcSec": "车辆碰撞预判时间", + "avoidShiftM": "绕开车辆和残骸的横移距离", + "yieldWaitMaxSec": "窄路让路最长等待时间", + "stuckWindowSec": "卡住检测窗口时长", + "stuckMinProgressM": "检测窗口内的最小前进距离", + "unstickReverseM": "脱困倒车距离", + "unstickReverseSec": "脱困倒车最长时长", + "unstickRepeatSec": "多久内再次卡住就升级处理", + "unstickMaxAttempts": "放弃当前任务前的脱困次数", + "jamRadiusM": "堵车点代价半径", + "jamCostMul": "堵车点寻路代价倍率", + "jamTtlSec": "堵车点代价持续时间", + "rubbleRadiusM": "新障碍代价半径", + "rubbleCostMul": "新障碍寻路代价倍率", + "rubbleTtlSec": "新障碍代价持续时间", + "wreckRadiusM": "残骸代价半径", + "wreckCostMul": "残骸寻路代价倍率", + "wreckTtlSec": "残骸代价持续时间" + }, "crowd": { "personalSpaceM": "单车安全个人空间", "clusterRadiusM": "扎堆检测半径", 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 c9238ad..f94425d 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 @@ -262,12 +262,8 @@ export const BOT_TUNING_GROUPS: readonly BotTuningGroup[] = [ { id: 'groundAi.navigation.steerSign', section: 'navigation', field: 'steerSign', kind: 'steerSign' }, num('navigation', 'deadEchoSec', 0.3, 10, 's'), num('navigation', 'controlTimeoutSec', 0.3, 10, 's'), - num('navigation', 'cornerBrakeAccel', 0.5, 8), num('navigation', 'movingFireSpeedRampMps', 0.2, 5, 'm/s'), num('navigation', 'pivotAngleDeg', 25, 150, '°'), - num('navigation', 'stuckWindowSec', 1, 15, 's'), - num('navigation', 'stuckMinMoveM', 0.5, 10, 'm'), - num('navigation', 'unstickReverseSec', 0.8, 10, 's'), num('navigation', 'tacticalReverseDistM', 10, 90, 'm'), num('navigation', 'tacticalReverseMaxSec', 2, 25, 's'), ], @@ -280,10 +276,55 @@ export const BOT_TUNING_GROUPS: readonly BotTuningGroup[] = [ { id: 'groundAi.navEngine.enabled', section: 'navEngine', field: 'enabled', kind: 'bool' }, { id: 'groundAi.navEngine.allowFallback', section: 'navEngine', field: 'allowFallback', kind: 'bool' }, num('navEngine', 'snapRadiusM', 2, 40, 'm'), + num('navEngine', 'goalSnapRadiusM', 5, 150, 'm'), + num('navEngine', 'pathBudgetMsPerFrame', 0.05, 5, 'ms'), ...NAV_COST_FIELDS.map((field) => num('navCostsTracked', field, 0.1, 20)), ...NAV_COST_FIELDS.map((field) => num('navCostsWheeled', field, 0.1, 20)), ], }, + { + id: 'pathFollow', + defaultOpen: false, + customOnly: true, + fields: [ + num('pathFollow', 'replanIntervalSec', 1, 15, 's'), + num('pathFollow', 'replanGoalMoveM', 3, 80, 'm'), + num('pathFollow', 'offCorridorReplanM', 3, 60, 'm'), + num('pathFollow', 'lookaheadTimeSec', 0.3, 5, 's'), + num('pathFollow', 'trackedLookaheadMinM', 2, 40, 'm'), + num('pathFollow', 'trackedLookaheadMaxM', 4, 60, 'm'), + num('pathFollow', 'wheeledLookaheadMinM', 2, 40, 'm'), + num('pathFollow', 'wheeledLookaheadMaxM', 4, 60, 'm'), + num('pathFollow', 'cornerAngleDeg', 10, 120, '°'), + num('pathFollow', 'cornerLateralAccelMps2', 0.5, 10, 'm/s²'), + num('pathFollow', 'cornerBrakeDecelMps2', 0.5, 10, 'm/s²'), + num('pathFollow', 'arriveRadiusM', 1, 20, 'm'), + num('pathFollow', 'arriveMinSpeedMps', 0.3, 6, 'm/s'), + num('pathFollow', 'narrowWallMarginM', 0.2, 6, 'm'), + num('pathFollow', 'narrowSpeedMps', 1, 15, 'm/s'), + num('pathFollow', 'bumperRayM', 2, 20, 'm'), + num('pathFollow', 'bumperStopM', 0.3, 6, 'm'), + num('pathFollow', 'bumperBlockSec', 0.2, 5, 's'), + num('pathFollow', 'trafficTtcSec', 0.5, 8, 's'), + num('pathFollow', 'avoidShiftM', 0.5, 10, 'm'), + num('pathFollow', 'yieldWaitMaxSec', 0.5, 15, 's'), + num('pathFollow', 'stuckWindowSec', 1, 15, 's'), + num('pathFollow', 'stuckMinProgressM', 0.2, 10, 'm'), + num('pathFollow', 'unstickReverseM', 2, 25, 'm'), + num('pathFollow', 'unstickReverseSec', 0.8, 10, 's'), + num('pathFollow', 'unstickRepeatSec', 2, 60, 's'), + int('pathFollow', 'unstickMaxAttempts', 1, 10), + num('pathFollow', 'jamRadiusM', 2, 50, 'm'), + num('pathFollow', 'jamCostMul', 1, 50), + num('pathFollow', 'jamTtlSec', 5, 600, 's'), + num('pathFollow', 'rubbleRadiusM', 1, 40, 'm'), + num('pathFollow', 'rubbleCostMul', 1, 50), + num('pathFollow', 'rubbleTtlSec', 5, 600, 's'), + num('pathFollow', 'wreckRadiusM', 1, 40, 'm'), + num('pathFollow', 'wreckCostMul', 1, 50), + num('pathFollow', 'wreckTtlSec', 5, 600, 's'), + ], + }, { id: 'crowd', defaultOpen: false, diff --git a/apps/launcher/src/shared/schemas/tuning.ts b/apps/launcher/src/shared/schemas/tuning.ts index e953f6d..be651db 100644 --- a/apps/launcher/src/shared/schemas/tuning.ts +++ b/apps/launcher/src/shared/schemas/tuning.ts @@ -90,12 +90,8 @@ const GroundAiNavigationSchema = z.object({ steerSign: z.union([z.literal(1), z.literal(-1)]), deadEchoSec: z.number().min(0.3).max(10), controlTimeoutSec: z.number().min(0.3).max(10), - cornerBrakeAccel: z.number().min(0.5).max(8), movingFireSpeedRampMps: z.number().min(0.2).max(5), pivotAngleDeg: z.number().min(25).max(150), - stuckWindowSec: z.number().min(1).max(15), - stuckMinMoveM: z.number().min(0.5).max(10), - unstickReverseSec: z.number().min(0.8).max(10), tacticalReverseDistM: z.number().min(10).max(90), tacticalReverseMaxSec: z.number().min(2).max(25), }); @@ -104,6 +100,8 @@ const GroundAiNavEngineSchema = z.object({ enabled: z.boolean(), allowFallback: z.boolean(), snapRadiusM: z.number().min(2).max(40), + goalSnapRadiusM: z.number().min(5).max(150), + pathBudgetMsPerFrame: z.number().min(0.05).max(5), }); const navCost = z.number().min(0.1).max(20); @@ -118,6 +116,45 @@ const GroundAiNavCostsSchema = z.object({ chokepoint: navCost, }); +const GroundAiPathFollowSchema = z.object({ + replanIntervalSec: z.number().min(1).max(15), + replanGoalMoveM: z.number().min(3).max(80), + offCorridorReplanM: z.number().min(3).max(60), + lookaheadTimeSec: z.number().min(0.3).max(5), + trackedLookaheadMinM: z.number().min(2).max(40), + trackedLookaheadMaxM: z.number().min(4).max(60), + wheeledLookaheadMinM: z.number().min(2).max(40), + wheeledLookaheadMaxM: z.number().min(4).max(60), + cornerAngleDeg: z.number().min(10).max(120), + cornerLateralAccelMps2: z.number().min(0.5).max(10), + cornerBrakeDecelMps2: z.number().min(0.5).max(10), + arriveRadiusM: z.number().min(1).max(20), + arriveMinSpeedMps: z.number().min(0.3).max(6), + narrowWallMarginM: z.number().min(0.2).max(6), + narrowSpeedMps: z.number().min(1).max(15), + bumperRayM: z.number().min(2).max(20), + bumperStopM: z.number().min(0.3).max(6), + bumperBlockSec: z.number().min(0.2).max(5), + trafficTtcSec: z.number().min(0.5).max(8), + avoidShiftM: z.number().min(0.5).max(10), + yieldWaitMaxSec: z.number().min(0.5).max(15), + stuckWindowSec: z.number().min(1).max(15), + stuckMinProgressM: z.number().min(0.2).max(10), + unstickReverseM: z.number().min(2).max(25), + unstickReverseSec: z.number().min(0.8).max(10), + unstickRepeatSec: z.number().min(2).max(60), + unstickMaxAttempts: z.number().int().min(1).max(10), + jamRadiusM: z.number().min(2).max(50), + jamCostMul: z.number().min(1).max(50), + jamTtlSec: z.number().min(5).max(600), + rubbleRadiusM: z.number().min(1).max(40), + rubbleCostMul: z.number().min(1).max(50), + rubbleTtlSec: z.number().min(5).max(600), + wreckRadiusM: z.number().min(1).max(40), + wreckCostMul: z.number().min(1).max(50), + wreckTtlSec: z.number().min(5).max(600), +}); + const GroundAiPerceptionSchema = z.object({ foliageTransparency: z.number().min(0.001).max(1), nearSpotRangeM: z.number().min(20).max(250), @@ -215,6 +252,7 @@ export const GroundAiTuningSchema = z.object({ navEngine: GroundAiNavEngineSchema, navCostsTracked: GroundAiNavCostsSchema, navCostsWheeled: GroundAiNavCostsSchema, + pathFollow: GroundAiPathFollowSchema, perception: GroundAiPerceptionSchema, stateMachine: GroundAiStateMachineSchema, tactics: GroundAiTacticsSchema, @@ -236,6 +274,7 @@ export const GroundAiTuningPatchSchema = z.object({ navEngine: GroundAiNavEngineSchema.partial().optional(), navCostsTracked: GroundAiNavCostsSchema.partial().optional(), navCostsWheeled: GroundAiNavCostsSchema.partial().optional(), + pathFollow: GroundAiPathFollowSchema.partial().optional(), perception: GroundAiPerceptionSchema.partial().optional(), stateMachine: GroundAiStateMachineSchema.partial().optional(), tactics: GroundAiTacticsSchema.partial().optional(), diff --git a/apps/server/src/tuning/ground-ai-tuning.ts b/apps/server/src/tuning/ground-ai-tuning.ts index 5302a95..53c7014 100644 --- a/apps/server/src/tuning/ground-ai-tuning.ts +++ b/apps/server/src/tuning/ground-ai-tuning.ts @@ -9,6 +9,7 @@ import { type GroundAiDriveMode, type GroundAiMode, type GroundAiNavCosts, + type GroundAiPathFollow, } from '@wto/patcher'; import type { TankLineupWeights } from '../battle/battle-ranks.ts'; import { tuningFiles } from './tuning-loader.ts'; @@ -48,6 +49,10 @@ export function readGroundAiTuning(reader: TuningReader): GroundAiTuning { navEngine: readNavEngineSection(reader.object('navEngine')), navCostsTracked: readNavCosts(reader.object('navCostsTracked')), navCostsWheeled: readNavCosts(reader.object('navCostsWheeled')), + pathFollow: readPathFollowSection(reader.object('pathFollow')), + navBake: { + crushableMaxRiExtraHp: reader.object('navBake').number('crushableMaxRiExtraHp', { min: 0, max: 1000 }), + }, perception: readPerceptionSection(reader.object('perception')), stateMachine: readStateMachineSection(reader.object('stateMachine')), tactics: readTacticsSection(reader.object('tactics')), @@ -182,6 +187,8 @@ function readNavEngineSection(engine: TuningReader): GroundAiTuning['navEngine'] enabled: engine.bool('enabled'), allowFallback: engine.bool('allowFallback'), snapRadiusM: engine.number('snapRadiusM', { min: 2, max: 40 }), + goalSnapRadiusM: engine.number('goalSnapRadiusM', { min: 5, max: 150 }), + pathBudgetMsPerFrame: engine.number('pathBudgetMsPerFrame', { min: 0.05, max: 5 }), }; } @@ -199,6 +206,54 @@ function readNavCosts(costs: TuningReader): GroundAiNavCosts { }; } +function readPathFollowSection(pf: TuningReader): GroundAiPathFollow { + const n = (key: keyof GroundAiPathFollow, min: number, max: number) => pf.number(key, { min, max }); + const lookahead = { + trackedLookaheadMinM: n('trackedLookaheadMinM', 2, 40), + trackedLookaheadMaxM: n('trackedLookaheadMaxM', 4, 60), + wheeledLookaheadMinM: n('wheeledLookaheadMinM', 2, 40), + wheeledLookaheadMaxM: n('wheeledLookaheadMaxM', 4, 60), + }; + if (lookahead.trackedLookaheadMaxM < lookahead.trackedLookaheadMinM || lookahead.wheeledLookaheadMaxM < lookahead.wheeledLookaheadMinM) { + throw new TuningError('tuning file ground-ai.jsonc: pathFollow lookahead maximum must not be below its minimum'); + } + return { + replanIntervalSec: n('replanIntervalSec', 1, 15), + replanGoalMoveM: n('replanGoalMoveM', 3, 80), + offCorridorReplanM: n('offCorridorReplanM', 3, 60), + lookaheadTimeSec: n('lookaheadTimeSec', 0.3, 5), + ...lookahead, + cornerAngleDeg: n('cornerAngleDeg', 10, 120), + cornerLateralAccelMps2: n('cornerLateralAccelMps2', 0.5, 10), + cornerBrakeDecelMps2: n('cornerBrakeDecelMps2', 0.5, 10), + arriveRadiusM: n('arriveRadiusM', 1, 20), + arriveMinSpeedMps: n('arriveMinSpeedMps', 0.3, 6), + narrowWallMarginM: n('narrowWallMarginM', 0.2, 6), + narrowSpeedMps: n('narrowSpeedMps', 1, 15), + bumperRayM: n('bumperRayM', 2, 20), + bumperStopM: n('bumperStopM', 0.3, 6), + bumperBlockSec: n('bumperBlockSec', 0.2, 5), + trafficTtcSec: n('trafficTtcSec', 0.5, 8), + avoidShiftM: n('avoidShiftM', 0.5, 10), + yieldWaitMaxSec: n('yieldWaitMaxSec', 0.5, 15), + stuckWindowSec: n('stuckWindowSec', 1, 15), + stuckMinProgressM: n('stuckMinProgressM', 0.2, 10), + unstickReverseM: n('unstickReverseM', 2, 25), + unstickReverseSec: n('unstickReverseSec', 0.8, 10), + unstickRepeatSec: n('unstickRepeatSec', 2, 60), + unstickMaxAttempts: pf.int('unstickMaxAttempts', { min: 1, max: 10 }), + jamRadiusM: n('jamRadiusM', 2, 50), + jamCostMul: n('jamCostMul', 1, 50), + jamTtlSec: n('jamTtlSec', 5, 600), + rubbleRadiusM: n('rubbleRadiusM', 1, 40), + rubbleCostMul: n('rubbleCostMul', 1, 50), + rubbleTtlSec: n('rubbleTtlSec', 5, 600), + wreckRadiusM: n('wreckRadiusM', 1, 40), + wreckCostMul: n('wreckCostMul', 1, 50), + wreckTtlSec: n('wreckTtlSec', 5, 600), + }; +} + function readNavigationSection(nav: TuningReader): GroundAiTuning['navigation'] { const driveModeRaw = nav.string('driveMode'); const driveMode = GROUND_AI_DRIVE_MODES.find((candidate): candidate is GroundAiDriveMode => candidate === driveModeRaw); @@ -215,12 +270,8 @@ function readNavigationSection(nav: TuningReader): GroundAiTuning['navigation'] steerSign, deadEchoSec: nav.number('deadEchoSec', { min: 0.3, max: 10 }), controlTimeoutSec: nav.number('controlTimeoutSec', { min: 0.3, max: 10 }), - cornerBrakeAccel: nav.number('cornerBrakeAccel', { min: 0.5, max: 8 }), movingFireSpeedRampMps: nav.number('movingFireSpeedRampMps', { min: 0.2, max: 5 }), pivotAngleDeg: nav.number('pivotAngleDeg', { min: 25, max: 150 }), - stuckWindowSec: nav.number('stuckWindowSec', { min: 1, max: 15 }), - stuckMinMoveM: nav.number('stuckMinMoveM', { min: 0.5, max: 10 }), - unstickReverseSec: nav.number('unstickReverseSec', { min: 0.8, max: 10 }), tacticalReverseDistM: nav.number('tacticalReverseDistM', { min: 10, max: 90 }), tacticalReverseMaxSec: nav.number('tacticalReverseMaxSec', { min: 2, max: 25 }), }; diff --git a/apps/server/tuning/ground-ai.jsonc b/apps/server/tuning/ground-ai.jsonc index c3ad4ac..95d6aba 100644 --- a/apps/server/tuning/ground-ai.jsonc +++ b/apps/server/tuning/ground-ai.jsonc @@ -123,13 +123,9 @@ "steerSign": 1.0, "deadEchoSec": 1.2, "controlTimeoutSec": 1.0, - "cornerBrakeAccel": 1.75, // Speed error at which the moving-fire controller applies full throttle or braking. "movingFireSpeedRampMps": 1.0, "pivotAngleDeg": 75.0, - "stuckWindowSec": 3.6, - "stuckMinMoveM": 2.0, - "unstickReverseSec": 3.0, "tacticalReverseDistM": 34.0, "tacticalReverseMaxSec": 9.5 }, @@ -142,7 +138,13 @@ // battle start, never in the middle of a battle. "allowFallback": true, // Farthest a path's start or goal may lie from the mesh. - "snapRadiusM": 12.0 + "snapRadiusM": 12.0, + // A goal farther than snapRadiusM from the mesh (a position chosen by tactics inside a building + // or on a slope) is moved to the nearest walkable point within this distance; beyond it the + // goal counts as unreachable. Also used to find the way back onto the mesh. + "goalSnapRadiusM": 40.0, + // Path searches are spread over frames; this is the search time allowed per frame. + "pathBudgetMsPerFrame": 0.5 }, // Path cost multipliers per surface for tracked vehicles; chokepoint multiplies the surface cost @@ -170,6 +172,56 @@ "chokepoint": 2.2 }, + // Following the path, local avoidance and unstick (offline values). + "pathFollow": { + // Plan again after this long, when the goal moved this far, or when the bot is this far off its path. + "replanIntervalSec": 3.5, + "replanGoalMoveM": 15.0, + "offCorridorReplanM": 12.0, + // Steering point: speed times lookaheadTimeSec, kept within the range of the vehicle kind. + "lookaheadTimeSec": 1.4, + "trackedLookaheadMinM": 6.0, + "trackedLookaheadMaxM": 18.0, + "wheeledLookaheadMinM": 10.0, + "wheeledLookaheadMaxM": 24.0, + // Path corners sharper than cornerAngleDeg are taken at the speed the sideways acceleration + // allows; the vehicle brakes toward it (and toward its destination) at cornerBrakeDecelMps2. + "cornerAngleDeg": 35.0, + "cornerLateralAccelMps2": 2.8, + "cornerBrakeDecelMps2": 2.0, + "arriveRadiusM": 3.0, + "arriveMinSpeedMps": 1.5, + // The mesh already keeps the vehicle's half width from walls; less room than this beyond it, + // or a baked chokepoint, counts as a narrow passage. + "narrowWallMarginM": 1.5, + "narrowSpeedMps": 4.5, + // Rays from both front corners of the hull for obstacles the baked mesh does not know. + "bumperRayM": 7.0, + "bumperStopM": 1.5, + "bumperBlockSec": 0.6, + // Vehicles and wrecks that come within reach in trafficTtcSec: follow, step aside, or give way. + "trafficTtcSec": 2.5, + "avoidShiftM": 3.0, + "yieldWaitMaxSec": 3.0, + // Less progress than stuckMinProgressM within stuckWindowSec while wanting to move is stuck. + "stuckWindowSec": 3.0, + "stuckMinProgressM": 0.8, + "unstickReverseM": 6.5, + "unstickReverseSec": 3.0, + "unstickRepeatSec": 8.0, + "unstickMaxAttempts": 3, + // Temporary path costs: jams found by unstick, fresh obstacles hit by the front rays, wrecks. + "jamRadiusM": 10.0, + "jamCostMul": 4.0, + "jamTtlSec": 45.0, + "rubbleRadiusM": 6.0, + "rubbleCostMul": 8.0, + "rubbleTtlSec": 90.0, + "wreckRadiusM": 6.0, + "wreckCostMul": 6.0, + "wreckTtlSec": 120.0 + }, + // Exposure-based visual perception (offline values; foliageTransparency matches stock infantry AI). "perception": { "foliageTransparency": 0.01, diff --git a/game-ai/ground/wto_ai_avoid_common.das b/game-ai/ground/wto_ai_avoid_common.das new file mode 100644 index 0000000..c784f06 --- /dev/null +++ b/game-ai/ground/wto_ai_avoid_common.das @@ -0,0 +1,176 @@ +// Local avoidance on top of the path: what the baked mesh cannot know. Two short physical rays +// from the front corners of the hull catch fresh obstacles (rubble, collapsed buildings) and let +// the vehicle drive through what it can knock down (fences, light walls); a +// time-to-collision check against vehicles and wrecks makes a bot follow slower traffic, step +// aside, or (in narrow passages) wait while the vehicle with priority passes. +options indenting = 2 +options no_global_heap = true +module wto_ai_avoid_common shared + +require ecs +require math +require DagorMath +require Dacoll +require RendInst +require PhysMat +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 + +let private AVOID_STATIC_MASK = ETF_STRUCTURES | ETF_FRT + +// Placed objects a tank cannot knock down. Matches the bake: riExtra objects up to +// navBake.crushableMaxRiExtraHp are crushable, destructible generated objects (fences, posts) +// fall over, indestructible ones block. +[never_inline] +def private wto_avoid_ri_blocks(desc : RendInstDesc const&) : bool + if desc.isValid && desc.isRiExtra && desc.riExtraHandle != RIEX_HANDLE_NULL + let handle = desc.riExtraHandle + let poolId = uint(handle_to_ri_type(handle)) + if rendinst_isRIExtraGenPosInst(poolId) + return false + if riex_isImmortal(poolId) || riex_isInvincible(handle) + return true + return riex_getInitialHP(handle) > WTO_AI_NAVBAKE_CRUSH_MAX_HP + if !desc.isValid + return true + if rendinst_isRIGenPosInst(desc) + return false + return !rendinst_isRIGenDestr(desc) + +// Clear distance along dir up to the first wall-like surface a tank cannot drive through. +[never_inline] +def private wto_avoid_drive_ray(startPos, dir : float3; maxRange : float) : float + var structDist = maxRange + var sTraveled = 0.0 + for _hop in range(0, 4) + var hitD = maxRange - sTraveled + if hitD <= 0.0 + break + var mat = PHYSMAT_INVALID + var norm = float3(0.0) + var desc = RendInstDesc() + let sOrigin = startPos + dir * sTraveled + if !traceray_normalized(sOrigin, dir, hitD, mat, norm, AVOID_STATIC_MASK, desc, PHYSMAT_INVALID) + break + if norm.y < 0.72 + structDist = clamp(sTraveled + hitD, 0.0, maxRange) + break + sTraveled += max(0.0, hitD) + 0.5 + var traveled = 0.0 + for _hop in range(0, 4) + var hitDist = structDist - traveled + if hitDist <= 0.0 + break + var riMat = PHYSMAT_INVALID + var riNorm = float3(0.0) + var riDesc = RendInstDesc() + let origin = startPos + dir * traveled + if !traceray_normalized(origin, dir, hitDist, riMat, riNorm, ETF_RI | ETF_RI_PHYS, riDesc, PHYSMAT_INVALID) + break + if riNorm.y < 0.72 && wto_avoid_ri_blocks(riDesc) + return clamp(traveled + hitDist, 0.0, structDist) + traveled += max(0.0, hitDist) + 0.35 + return structDist + +// Clear distance ahead along `dir` from both front corners of the hull (the shorter of the two). +[never_inline] +def public wto_avoid_bumper(myPos, dir : float3; spec : WtoVehicleSpec const&) : float + let left = float3(-dir.z, 0.0, dir.x) + let base = myPos + dir * max(0.5, spec.halfLen - 0.4) + float3(0.0, 1.0, 0.0) + let side = max(0.4, spec.halfWid - 0.25) + let clearL = wto_avoid_drive_ray(base + left * side, dir, WTO_AI_PF_BUMPER_RAY_M) + let clearR = wto_avoid_drive_ray(base - left * side, dir, WTO_AI_PF_BUMPER_RAY_M) + return min(clearL, clearR) + +// Whether another body ahead comes within reach in the next trafficTtcSec; `tHit` is when. +[never_inline] +def private wto_avoid_conflict(myPos, myVel, dir : float3; selfRad : float; otherPos, otherVel : float3; + otherRad : float; var tHit : float&) : bool + let rel = float3(otherPos.x - myPos.x, 0.0, otherPos.z - myPos.z) + if dot(rel, dir) <= 0.0 || dot(rel, rel) > 1600.0 + return false + let relVel = float3(otherVel.x - myVel.x, 0.0, otherVel.z - myVel.z) + let vv = dot(relVel, relVel) + tHit = vv > 0.01 ? clamp(-dot(rel, relVel) / vv, 0.0, WTO_AI_PF_TRAFFIC_TTC_SEC) : 0.0 + let closest = rel + relVel * tHit + let reach = selfRad + otherRad + 0.8 + return dot(closest, closest) < reach * reach + +// Earliest conflict among vehicles and wrecks; -1 when there is none. +[never_inline] +def private wto_avoid_find(world : WtoWorldSnap const&; myPos, dir : float3; speedMps : float; + slot : WtoBotSlot const&; var isWreck : bool&) : int + let selfRad = max(slot.spec.halfWid, 1.2) + let myVel = dir * speedMps + var best = 99.0 + var found = -1 + for i in range(world.unitCount) + assume u = world.units[i] + if !u.isAlive || !u.isGround || u.eid == slot.eid + continue + var tUnit = 0.0 + if wto_avoid_conflict(myPos, myVel, dir, selfRad, u.pos, u.vel, max(u.halfWid, 1.0), tUnit) && tUnit < best + best = tUnit + found = i + isWreck = false + for w in range(world.wreckCount) + var tWreck = 0.0 + let still = float3(0.0, 0.0, 0.0) + if wto_avoid_conflict(myPos, myVel, dir, selfRad, world.wrecks[w].pos, still, max(world.wrecks[w].halfWid, 1.0), tWreck) && tWreck < best + best = tWreck + found = w + isWreck = true + return found + +// The bigger vehicle goes first; equal sizes by entity id. Players always keep their way. +[never_inline] +def private wto_avoid_has_priority(slot : WtoBotSlot const&; other : WtoUnitSnap const&) : bool + if other.isHuman + return false + let mine = slot.spec.halfLen * slot.spec.halfWid + let theirs = other.halfLen * other.halfWid + if abs(mine - theirs) > 0.5 + return mine > theirs + return uint(slot.eid) < uint(other.eid) + +// Waits for the vehicle with priority, at most yieldWaitMaxSec, then not again for as long. +[never_inline] +def private wto_avoid_yield(now : float; var nav : WtoNavState&) + if nav.yieldUntil < now && now >= nav.yieldCooldownUntil + nav.yieldUntil = now + WTO_AI_PF_YIELD_WAIT_SEC + nav.yieldCooldownUntil = nav.yieldUntil + WTO_AI_PF_YIELD_WAIT_SEC + nav.avoidSpeedCap = now < nav.yieldUntil ? 0.0 : 2.0 + +// Sets slot.nav.avoidShiftM (sideways step, left positive) and avoidSpeedCap for this tick. +[never_inline] +def public wto_avoid_traffic(world : WtoWorldSnap const&; now : float; myPos, dir : float3; + speedMps : float; narrow : bool; var slot : WtoBotSlot&) + assume nav = slot.nav + nav.avoidShiftM = 0.0 + nav.avoidSpeedCap = 99.0 + var isWreck = false + let idx = wto_avoid_find(world, myPos, dir, speedMps, slot, isWreck) + if idx < 0 + nav.yieldUntil = -100.0 + return + let otherPos = isWreck ? world.wrecks[idx].pos : world.units[idx].pos + let otherVel = isWreck ? float3(0.0, 0.0, 0.0) : world.units[idx].vel + let along = dot(otherVel, dir) + if !isWreck && along > 1.0 && along > 0.7 * length(otherVel) + let gap = sqrt(wto_xz_dist_sq(myPos, otherPos)) + nav.avoidSpeedCap = along + max(0.0, gap - 12.0) * 0.4 + return + if !isWreck && wto_avoid_has_priority(slot, world.units[idx]) + return + let lateral = dot(otherPos - myPos, float3(-dir.z, 0.0, dir.x)) + if !narrow + nav.avoidShiftM = (lateral >= 0.0 ? -1.0 : 1.0) * WTO_AI_PF_AVOID_SHIFT_M + nav.avoidSpeedCap = max(2.0, speedMps * 0.7) + return + if isWreck + slot.route.replanRequested = true + nav.avoidSpeedCap = 2.0 + return + wto_avoid_yield(now, nav) diff --git a/game-ai/ground/wto_ai_commander_common.das b/game-ai/ground/wto_ai_commander_common.das index d766afd..dc332a2 100644 --- a/game-ai/ground/wto_ai_commander_common.das +++ b/game-ai/ground/wto_ai_commander_common.das @@ -13,6 +13,7 @@ require %appGame.wtoai.wto_ai_order_common require %appGame.wtoai.wto_ai_types_common require %appGame.wtoai.wto_ai_world_common require %appGame.wtoai.wto_ai_lanes_common +require %appGame.wtoai.wto_ai_lanes_build_common require %appGame.wtoai.wto_ai_commander_anchors_common require %appGame.wtoai.wto_ai_commander_plans_common @@ -193,5 +194,4 @@ def public wto_commander_update_all(world : WtoWorldSnap const&; now : float; wto_lanes_update_team_intel(world, now, lanes) wto_cmd_assign_army(world, 1, now, forceRebalance, lanes, bots) wto_cmd_assign_army(world, 2, now, forceRebalance, lanes, bots) - wto_lanes_update_rallies(world, 1, now, lanes, bots) - wto_lanes_update_rallies(world, 2, now, lanes, bots) + wto_lanes_tick_rallies(world, now, lanes, bots) diff --git a/game-ai/ground/wto_ai_diag_common.das b/game-ai/ground/wto_ai_diag_common.das index d8348e5..db2205d 100644 --- a/game-ai/ground/wto_ai_diag_common.das +++ b/game-ai/ground/wto_ai_diag_common.das @@ -5,8 +5,8 @@ module wto_ai_diag_common shared require ecs require math -require pathfinder require %appGame.wtoai.wto_ai_types_common +require %appGame.wtoai.wto_ai_nav_types_common require %appGame.wtoai.wto_ai_world_common [never_inline] @@ -16,7 +16,7 @@ def private wto_log_bot_and_cap_samples(world : WtoWorldSnap const&; bots : WtoB if !bots[i].used || sampled >= 2 continue assume b = bots[i] - print("WTO_AI|BOT_SAMPLE|eid={uint(b.eid)}|role={b.spec.role}|stab={b.spec.hasVertStab}|v0={b.fire.activeSpeedMps}|st={b.tactics.state}|allyD={b.crowd.nearestAllyDistM}|clust={b.crowd.clusterAllyCount}|ridge={b.tactics.onExposedRidge}|los={b.perceive.hasClearLos}|fc={b.fire.gunReady}/{b.fire.reloading}/{b.fire.lastAligned}|err={b.fire.lastAimErrDeg}|drift={b.fire.aimDriftDegSec}|mode={b.driveCmd.mode}|v={b.drive.lastVFwd}|clr={b.nav.frontClearM}/{b.nav.rearClearM}|wp={b.route.corridorIdx}/{b.route.corridorLen}|proj={b.route.lastStartOk}/{b.route.lastGoalOk}\n") + print("WTO_AI|BOT_SAMPLE|eid={uint(b.eid)}|role={b.spec.role}|stab={b.spec.hasVertStab}|v0={b.fire.activeSpeedMps}|st={b.tactics.state}|allyD={b.crowd.nearestAllyDistM}|clust={b.crowd.clusterAllyCount}|ridge={b.tactics.onExposedRidge}|los={b.perceive.hasClearLos}|fc={b.fire.gunReady}/{b.fire.reloading}/{b.fire.lastAligned}|err={b.fire.lastAimErrDeg}|drift={b.fire.aimDriftDegSec}|mode={b.driveCmd.mode}|v={b.drive.lastVFwd}|clr={b.nav.frontClearM}/{b.nav.rearClearM}|bump={b.nav.bumperClearM}|wall={b.nav.wallDistM}|seg={b.route.segIdx}/{b.route.corridorLen}|src={b.route.source}|path={b.route.lastStatus}|off={b.route.offTrackM}\n") sampled++ for c in range(world.capCount) assume z = world.caps[c] @@ -33,7 +33,10 @@ def public wto_diag_log_telemetry(world : WtoWorldSnap const&; now : float; var ridgeNow = 0 var revEvents = 0 var ridgeWithdraws = 0 - var detours = 0 + var stuckEv = 0 + var unreachable = 0 + var noGoal = 0 + var paths = 0 var shots = 0 var errSum = 0.0 var maxErr = 0.0 @@ -53,12 +56,14 @@ def public wto_diag_log_telemetry(world : WtoWorldSnap const&; now : float; ridgeNow += b.tactics.onExposedRidge ? 1 : 0 revEvents += b.nav.reverseCount ridgeWithdraws += b.nav.ridgeWithdrawEvents - detours += b.route.detourCount + stuckEv += b.nav.unstickEvents + unreachable += b.nav.unreachableEvents + noGoal += b.route.noGoalCount + paths += b.route.requests shots += b.fire.shotCount errSum += b.fire.shotErrSumDeg maxErr = max(maxErr, b.fire.maxShotErrDeg) let avgErr = shots > 0 ? (errSum / float(shots)) : 0.0 let jams = wto_world_active_jams(world, now) - let nm1 = pathfinder_is_loaded_ex(1) - print("WTO_AI|STAT|t={now}|bots={active}|roles={roles[0]}/{roles[1]}/{roles[2]}/{roles[3]}/{roles[4]}|crowd={crowd.crowdedBotCount}|maxClust={crowd.maxClusterSize}|minAllyD={crowd.minPairDistM}|dispNow={dispNow}|dispEv={crowd.disperseEvents}|ridgeNow={ridgeNow}|ridgeRevEv={ridgeWithdraws}|eng={engNow}|revNow={revNow}|revEv={revEvents}|jams={jams}|detours={detours}|shots={shots}|avgAimErr={avgErr}|maxAimErr={maxErr}|routeB={routeB}|caps={world.capCount}|nm1={nm1}\n") + print("WTO_AI|STAT|t={now}|bots={active}|roles={roles[0]}/{roles[1]}/{roles[2]}/{roles[3]}/{roles[4]}|crowd={crowd.crowdedBotCount}|maxClust={crowd.maxClusterSize}|minAllyD={crowd.minPairDistM}|dispNow={dispNow}|dispEv={crowd.disperseEvents}|ridgeNow={ridgeNow}|ridgeRevEv={ridgeWithdraws}|eng={engNow}|revNow={revNow}|revEv={revEvents}|jams={jams}|paths={paths}|stuckEv={stuckEv}|unreachable={unreachable}|noGoal={noGoal}|shots={shots}|avgAimErr={avgErr}|maxAimErr={maxErr}|routeB={routeB}|caps={world.capCount}\n") wto_log_bot_and_cap_samples(world, bots) diff --git a/game-ai/ground/wto_ai_drive_common.das b/game-ai/ground/wto_ai_drive_common.das index 7206bc1..f0d0b57 100644 --- a/game-ai/ground/wto_ai_drive_common.das +++ b/game-ai/ground/wto_ai_drive_common.das @@ -1,6 +1,7 @@ // Chassis drive actuator: translates `WtoDriveCmd` into closed-loop `VehiclePhysActor` axes // (throttle, steering, brakes, auto-transmission) with space-aware 3-point turns, smooth -// long-distance reverse control, and dead-echo watchdog return to stock movement. +// reverse control, and a dead-echo watchdog. Speed limits for corners and obstacles come from +// the navigation layer through the command; heading error alone slows the vehicle here. options indenting = 2 options no_global_heap = true module wto_ai_drive_common shared @@ -130,9 +131,7 @@ def private wto_compute_cruise_axes(cmd : WtoDriveCmd const&; spec : WtoVehicleS var vLimit = min(cmd.speedMps, spec.vMaxFwd) if absErr > 0.22 let radiusEst = max(4.0, 14.0 / max(0.25, absErr)) - vLimit = min(vLimit, sqrt(WTO_AI_NAV_CORNER_BRAKE_ACCEL * radiusEst)) - if cmd.frontClearM < 12.0 - vLimit = min(vLimit, max(2.2, (cmd.frontClearM - 2.0) * 0.75)) + vLimit = min(vLimit, sqrt(WTO_AI_PF_CORNER_LAT_ACCEL * radiusEst)) let vErr = vLimit - speedMps if firingOnMove let response = vErr / WTO_AI_NAV_MOVING_FIRE_SPEED_RAMP_MPS diff --git a/game-ai/ground/wto_ai_follow_common.das b/game-ai/ground/wto_ai_follow_common.das new file mode 100644 index 0000000..1505fdd --- /dev/null +++ b/game-ai/ground/wto_ai_follow_common.das @@ -0,0 +1,88 @@ +// Pure-pursuit path following on a bot's corridor: where the bot is along it, the lookahead point +// it steers at, and how fast it may go so it slows down before sharp corners and its destination +// instead of braking at the wall. +options indenting = 2 +options no_global_heap = true +module wto_ai_follow_common shared + +require math +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 +require %appGame.wtoai.wto_ai_polyline_common + +[never_inline] +def public wto_drive_cmd_set(var cmd : WtoDriveCmd&; mode : int; targetPos, desiredDir : float3; + speedMps, frontClr, rearClr : float) + cmd.valid = true + cmd.mode = mode + cmd.targetPos = targetPos + cmd.desiredDir = desiredDir + cmd.speedMps = speedMps + cmd.frontClearM = frontClr + cmd.rearClearM = rearClr + +// Moves the bot's place on its corridor forward and records its XZ distance from the corridor. +[never_inline] +def public wto_follow_track(myPos : float3; var rt : WtoRouteState&) + var seg = 0 + var t = 0.0 + rt.offTrackM = wto_poly_track(rt.corridor, rt.corridorLen, rt.segIdx, myPos, seg, t) + rt.segIdx = seg + rt.segT = t + +// Lookahead distance: grows with speed, wheeled vehicles look further (wider turns). +[never_inline] +def public wto_follow_lookahead(spec : WtoVehicleSpec const&; speedMps : float) : float + let lookMin = spec.isTracked ? WTO_AI_PF_TRACKED_LOOK_MIN_M : WTO_AI_PF_WHEELED_LOOK_MIN_M + let lookMax = spec.isTracked ? WTO_AI_PF_TRACKED_LOOK_MAX_M : WTO_AI_PF_WHEELED_LOOK_MAX_M + return clamp(abs(speedMps) * WTO_AI_PF_LOOKAHEAD_SEC, lookMin, max(lookMin, lookMax)) + +[never_inline] +def public wto_follow_target(rt : WtoRouteState const&; lookM : float) : float3 + return wto_poly_walk(rt.corridor, rt.corridorLen, rt.segIdx, rt.segT, lookM) + +// Highest speed at `distToB` metres before corner b (a -> b -> c) that still allows turning it. +[never_inline] +def private wto_follow_corner_cap(a, b, c : float3; distToB, lookM, halfLen : float) : float + let inDir = wto_xz_normalize(b - a, float3(1.0, 0.0, 0.0)) + let outDir = wto_xz_normalize(c - b, inDir) + let turnRad = acos(clamp(dot(inDir, outDir), -1.0, 1.0)) + if turnRad * WTO_RAD_TO_DEG < WTO_AI_PF_CORNER_ANGLE_DEG + return 99.0 + let legs = min(sqrt(wto_xz_dist_sq(a, b)), sqrt(wto_xz_dist_sq(b, c))) + let cut = max(1.0, min(lookM * 0.5, legs * 0.5)) + let radius = max(2.5, cut / max(0.05, tan(turnRad * 0.5))) + let vCorner = sqrt(WTO_AI_PF_CORNER_LAT_ACCEL * radius) + return sqrt(vCorner * vCorner + 2.0 * WTO_AI_PF_BRAKE_DECEL * max(0.0, distToB - halfLen)) + +// Speed allowed by the next two corners and, when the corridor ends at the destination, by it. +[never_inline] +def public wto_follow_speed_cap(rt : WtoRouteState const&; spec : WtoVehicleSpec const&; lookM : float) : float + if rt.corridorLen < 2 + return 99.0 + let s = clamp(rt.segIdx, 0, rt.corridorLen - 2) + let here = lerp(rt.corridor[s], rt.corridor[s + 1], rt.segT) + var dist = sqrt(wto_xz_dist_sq(here, rt.corridor[s + 1])) + var cap = 99.0 + for j in range(2) + let b = s + 1 + j + if b >= rt.corridorLen - 1 + break + cap = min(cap, wto_follow_corner_cap(rt.corridor[b - 1], rt.corridor[b], rt.corridor[b + 1], dist, lookM, spec.halfLen)) + dist += sqrt(wto_xz_dist_sq(rt.corridor[b], rt.corridor[b + 1])) + if rt.truncated || s < rt.corridorLen - 4 + return cap + var remaining = sqrt(wto_xz_dist_sq(here, rt.corridor[s + 1])) + for k in range(s + 1, rt.corridorLen - 1) + remaining += sqrt(wto_xz_dist_sq(rt.corridor[k], rt.corridor[k + 1])) + let arrive = sqrt(2.0 * WTO_AI_PF_BRAKE_DECEL * max(0.0, remaining - WTO_AI_PF_ARRIVE_RADIUS_M)) + return min(cap, max(WTO_AI_PF_ARRIVE_MIN_MPS, arrive)) + +// True when the corridor ends at the destination and the bot is within the arrival radius of it. +[never_inline] +def public wto_follow_arrived(rt : WtoRouteState const&; myPos : float3) : bool + if rt.corridorLen <= 0 || rt.truncated + return false + return wto_xz_dist_sq(myPos, rt.corridor[rt.corridorLen - 1]) <= wto_sq(WTO_AI_PF_ARRIVE_RADIUS_M) diff --git a/game-ai/ground/wto_ai_lanes_build_common.das b/game-ai/ground/wto_ai_lanes_build_common.das new file mode 100644 index 0000000..d96aa88 --- /dev/null +++ b/game-ai/ground/wto_ai_lanes_build_common.das @@ -0,0 +1,236 @@ +// Builds the flank lanes of every team x capture zone and releases their 40% rally points. +// With the battle's navigation pack the paths are queued native searches (one step per call until +// built); without it (fallback) they come from the stock road mesh at once. Center: spawn to the +// zone. Flanks: spawn to a walkable relay beside the center path's middle, then on to the zone; +// a flank longer than flankMaxLengthRatio times the center path is dropped. +options indenting = 2 +options no_global_heap = true +module wto_ai_lanes_build_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_order_common +require %appGame.wtoai.wto_ai_types_common +require %appGame.wtoai.wto_ai_terrain_common +require %appGame.wtoai.wto_ai_world_common +require %appGame.wtoai.wto_ai_polyline_common +require %appGame.wtoai.wto_ai_navquery_common +require %appGame.wtoai.wto_ai_navmesh_common +require %appGame.wtoai.wto_ai_stockpath_common +require %appGame.wtoai.wto_ai_lanes_common + +[never_inline] +def private wto_lanes_slot(k, leg : int) : int + return WTO_NAVQ_LANE_SLOT0 + k * 5 + leg + +// Center path known: length, rally at rallyProgressFrac and middle of the path. +[never_inline] +def private wto_lanes_set_center(k : int; pts : float3[96]; count : int; var lanes : WtoTeamLanes&) + lanes.centerLen[k] = wto_poly_length(pts, count) + lanes.centerMid[k] = wto_poly_sample(pts, count, 0.5) + lanes.rallyPos[k * 3 + WTO_LANE_CENTER] = wto_poly_sample(pts, count, WTO_AI_CMD_RALLY_PROG_FRAC) + +// No center path: straight-line stand-ins, no flanks. +[never_inline] +def private wto_lanes_set_straight(world : WtoWorldSnap const&; army, capIdx, k : int; var lanes : WtoTeamLanes&) + let spawnPt = world.teamSpawnCenter[army] + let capPt = world.caps[capIdx].center + lanes.centerLen[k] = max(80.0, sqrt(wto_xz_dist_sq(spawnPt, capPt))) + lanes.centerMid[k] = lerp(spawnPt, capPt, 0.5) + lanes.rallyPos[k * 3 + WTO_LANE_CENTER] = lerp(spawnPt, capPt, WTO_AI_CMD_RALLY_PROG_FRAC) + +// Relay of one side beside the center path's middle, on walkable ground; false when unusable. +[never_inline] +def private wto_lanes_relay(world : WtoWorldSnap const&; army, capIdx, k, side : int; + lanes : WtoTeamLanes const&; var relay : float3&) : bool + let spawnPt = world.teamSpawnCenter[army] + let capPt = world.caps[capIdx].center + let toCap = wto_xz_normalize(capPt - spawnPt, float3(1.0, 0.0, 0.0)) + let lat = float3(-toCap.z, 0.0, toCap.x) + let swing = clamp(sqrt(wto_xz_dist_sq(spawnPt, capPt)) * 0.34, 80.0, 260.0) + let sign = side == 0 ? 1.0 : -1.0 + relay = wto_clamp_battle_xz(lerp(spawnPt, capPt, 0.5) + lat * (sign * swing), world.battleCenter, world.battleRadius, 45.0) + if lanes.navState == WTO_NAVMESH_LOADED + var onMesh = relay + if !wto_navq_nearest(WTO_NAVMESH_TIER_STANDARD, WTO_NAVMESH_FILTER_TRACKED, relay, WTO_AI_NAVMESH_GOAL_SNAP_M, onMesh) + return false + relay = onMesh + if !wto_terrain_point_valid(army, relay) + return false + return sqrt(wto_xz_dist_sq(relay, lanes.centerMid[k])) >= WTO_AI_CMD_FLANK_MIN_SEP_M + +// A flank whose two legs are known: keep it when it is not too long. +[never_inline] +def private wto_lanes_accept_flank(k, side : int; leg1 : float3[96]; count1 : int; len2 : float; + relay : float3; var lanes : WtoTeamLanes&) + let fKey = k * 2 + side + lanes.flankValid[fKey] = false + if (wto_poly_length(leg1, count1) + len2) > lanes.centerLen[k] * WTO_AI_CMD_FLANK_MAX_RATIO + return + lanes.flankValid[fKey] = true + lanes.flankRelay[fKey] = relay + lanes.rallyPos[k * 3 + side + 1] = wto_poly_sample(leg1, count1, 0.8) + +// Fallback battles: every path from the stock road mesh at once. +[never_inline] +def private wto_lanes_build_stock(world : WtoWorldSnap const&; army, capIdx, k : int; var lanes : WtoTeamLanes&) + lanes.phase[k] = WTO_LANES_BUILT + var pts : float3[96] + var count = 0 + if !wto_stock_path(world.teamSpawnCenter[army], world.caps[capIdx].center, pts, count) + wto_lanes_set_straight(world, army, capIdx, k, lanes) + return + wto_lanes_set_center(k, pts, count, lanes) + var leg2 : float3[96] + for side in range(2) + var relay = float3(0.0, 0.0, 0.0) + lanes.flankValid[k * 2 + side] = false + if !wto_lanes_relay(world, army, capIdx, k, side, lanes, relay) + continue + var count2 = 0 + if !wto_stock_path(world.teamSpawnCenter[army], relay, pts, count) || !wto_stock_path(relay, world.caps[capIdx].center, leg2, count2) + continue + wto_lanes_accept_flank(k, side, pts, count, wto_poly_length(leg2, count2), pts[count - 1], lanes) + +// Queues both legs of each usable flank (slots k*5+1..4). +[never_inline] +def private wto_lanes_request_legs(world : WtoWorldSnap const&; army, capIdx, k : int; var lanes : WtoTeamLanes&) + for side in range(2) + var relay = float3(0.0, 0.0, 0.0) + lanes.flankValid[k * 2 + side] = false + lanes.ticket[k * 5 + 1 + side * 2] = 0 + lanes.ticket[k * 5 + 2 + side * 2] = 0 + if !wto_lanes_relay(world, army, capIdx, k, side, lanes, relay) + continue + lanes.flankRelay[k * 2 + side] = relay + lanes.ticket[k * 5 + 1 + side * 2] = wto_navq_path_request(wto_lanes_slot(k, 1 + side * 2), WTO_NAVMESH_TIER_STANDARD, + WTO_NAVMESH_FILTER_TRACKED, world.teamSpawnCenter[army], relay) + lanes.ticket[k * 5 + 2 + side * 2] = wto_navq_path_request(wto_lanes_slot(k, 2 + side * 2), WTO_NAVMESH_TIER_STANDARD, + WTO_NAVMESH_FILTER_TRACKED, relay, world.caps[capIdx].center) + lanes.phase[k] = WTO_LANES_LEGS + +// Center path queued: take it once found and queue the flank legs. +[never_inline] +def private wto_lanes_mesh_center(world : WtoWorldSnap const&; army, capIdx, k : int; var lanes : WtoTeamLanes&) + var pts : float3[96] + var count = 0 + var lenM = 0.0 + var truncated = false + let status = wto_navq_path_result(wto_lanes_slot(k, 0), lanes.ticket[k * 5], pts, count, lenM, truncated) + if status == WTO_PATH_PENDING + return + if (status != WTO_PATH_FULL && status != WTO_PATH_PARTIAL) || count < 2 + wto_lanes_set_straight(world, army, capIdx, k, lanes) + lanes.phase[k] = WTO_LANES_BUILT + return + wto_lanes_set_center(k, pts, count, lanes) + wto_lanes_request_legs(world, army, capIdx, k, lanes) + +// Flank legs queued: once none is pending, keep the flanks whose legs both arrived. +[never_inline] +def private wto_lanes_mesh_legs(k : int; var lanes : WtoTeamLanes&) + var leg1 : float3[96] + var leg2 : float3[96] + for side in range(2) + var count1 = 0 + var count2 = 0 + var len1 = 0.0 + var len2 = 0.0 + var trunc1 = false + var trunc2 = false + let t1 = lanes.ticket[k * 5 + 1 + side * 2] + let t2 = lanes.ticket[k * 5 + 2 + side * 2] + if t1 == 0 || t2 == 0 + continue + let s1 = wto_navq_path_result(wto_lanes_slot(k, 1 + side * 2), t1, leg1, count1, len1, trunc1) + let s2 = wto_navq_path_result(wto_lanes_slot(k, 2 + side * 2), t2, leg2, count2, len2, trunc2) + if s1 == WTO_PATH_PENDING || s2 == WTO_PATH_PENDING + return + lanes.ticket[k * 5 + 1 + side * 2] = 0 + lanes.ticket[k * 5 + 2 + side * 2] = 0 + if s1 == WTO_PATH_FULL && s2 == WTO_PATH_FULL && count1 >= 2 + wto_lanes_accept_flank(k, side, leg1, count1, len2, lanes.flankRelay[k * 2 + side], lanes) + lanes.phase[k] = WTO_LANES_BUILT + +// Builds (or advances the building of) the lanes of one team x capture zone. +[never_inline] +def public wto_lanes_ensure_cap(world : WtoWorldSnap const&; army, capIdx : int; var lanes : WtoTeamLanes&) + let k = wto_lanes_cap_key(army, capIdx) + if lanes.phase[k] == WTO_LANES_BUILT || capIdx < 0 || capIdx >= world.capCount || !world.teamSpawnValid[army] + return + if lanes.navState != WTO_NAVMESH_LOADED + if lanes.navState == WTO_NAVMESH_FALLBACK || lanes.navState == WTO_NAVMESH_OFF + wto_lanes_build_stock(world, army, capIdx, k, lanes) + return + if lanes.phase[k] == WTO_LANES_IDLE + lanes.ticket[k * 5] = wto_navq_path_request(wto_lanes_slot(k, 0), WTO_NAVMESH_TIER_STANDARD, WTO_NAVMESH_FILTER_TRACKED, + world.teamSpawnCenter[army], world.caps[capIdx].center) + lanes.phase[k] = WTO_LANES_CENTER + elif lanes.phase[k] == WTO_LANES_CENTER + wto_lanes_mesh_center(world, army, capIdx, k, lanes) + else + wto_lanes_mesh_legs(k, lanes) + +[never_inline] +def private wto_lanes_update_rallies(world : WtoWorldSnap const&; army : int; now : float; + var lanes : WtoTeamLanes&; bots : WtoBotSlot[64]) + let rallyRadSq = wto_sq(WTO_AI_CMD_RALLY_RADIUS_M) + for c in range(world.capCount) + wto_lanes_ensure_cap(world, army, c, lanes) + if lanes.phase[wto_lanes_cap_key(army, c)] != WTO_LANES_BUILT + continue + for lane in range(3) + let sk = wto_lanes_sub_key(army, c, lane) + if lanes.rallyReleased[sk] + continue + let rPos = lanes.rallyPos[sk] + if length_sq(rPos) < 1.0 + lanes.rallyReleased[sk] = true + continue + let rDistToCapSq = wto_xz_dist_sq(rPos, world.caps[c].center) + var assigned = 0 + var arrived = 0 + for i in range(WTO_MAX_BOTS) + assume b = bots[i] + if !b.used || b.army != army || !b.order.valid || b.order.capIndex != c || b.order.laneId != lane || !wto_order_is_offensive(b.order.role) + continue + let uIdx = wto_world_find_unit(world, b.eid) + if uIdx < 0 + continue + assigned++ + let pos = world.units[uIdx].pos + if wto_xz_dist_sq(pos, rPos) <= rallyRadSq || wto_xz_dist_sq(pos, world.caps[c].center) < rDistToCapSq + arrived++ + if assigned <= 1 + lanes.rallyReleased[sk] = true + continue + if arrived > 0 && lanes.rallyStartAt[sk] < 0.0 + lanes.rallyStartAt[sk] = now + let enough = float(arrived) >= float(assigned) * WTO_AI_CMD_RALLY_MIN_FRAC + let timedOut = lanes.rallyStartAt[sk] >= 0.0 && (now - lanes.rallyStartAt[sk]) >= WTO_AI_CMD_RALLY_WAIT_SEC + if enough || timedOut + lanes.rallyReleased[sk] = true + if WTO_AI_DIAG_TELEMETRY + print("WTO_AI|RALLY_GO|t={now}|army={army}|cap={c}|lane={lane}|arrived={arrived}/{assigned}|timeout={timedOut}\n") + +// Once a second: advance lane building, release rallies and send released bots on their way. +[never_inline] +def public wto_lanes_tick_rallies(world : WtoWorldSnap const&; now : float; var lanes : WtoTeamLanes&; + var bots : WtoBotSlot[64]&) + wto_lanes_update_rallies(world, 1, now, lanes, bots) + wto_lanes_update_rallies(world, 2, now, lanes, bots) + for i in range(WTO_MAX_BOTS) + assume b = bots[i] + if !b.used || !b.order.valid || !b.order.rallyHold || b.order.capIndex < 0 + continue + if !lanes.rallyReleased[wto_lanes_sub_key(b.army, b.order.capIndex, b.order.laneId)] + continue + b.order.rallyHold = false + if b.order.role == WTO_CMD_FLANK && b.order.laneId > 0 + let fKey = wto_lanes_cap_key(b.army, b.order.capIndex) * 2 + b.order.laneId - 1 + b.order.routeRelayValid = lanes.flankValid[fKey] + b.order.routeRelayPos = lanes.flankRelay[fKey] + else + b.order.routeRelayValid = false \ No newline at end of file diff --git a/game-ai/ground/wto_ai_lanes_common.das b/game-ai/ground/wto_ai_lanes_common.das index 25e52cf..99815d9 100644 --- a/game-ai/ground/wto_ai_lanes_common.das +++ b/game-ai/ground/wto_ai_lanes_common.das @@ -1,26 +1,32 @@ -// Team-level navmesh flank lanes (center / left / right), 40% rally staging & launch state, -// cap recall timers, and enemy air threat tracking. +// Team-level flank lanes (center / left / right) and their 40% rally staging state, cap recall +// timers, and enemy air threat tracking. Lanes are built in wto_ai_lanes_build_common. options indenting = 2 options no_global_heap = true module wto_ai_lanes_common shared require ecs require math -require pathfinder require %appGame.wtoai.wto_ai_config_common require %appGame.wtoai.wto_ai_math_common require %appGame.wtoai.wto_ai_order_common require %appGame.wtoai.wto_ai_types_common -require %appGame.wtoai.wto_ai_terrain_common require %appGame.wtoai.wto_ai_world_common let public WTO_LANE_CENTER = 0 let public WTO_LANE_LEFT = 1 let public WTO_LANE_RIGHT = 2 +// Lane building per team x capture zone: not started, center path queued, flank legs queued, done. +let public WTO_LANES_IDLE = 0 +let public WTO_LANES_CENTER = 1 +let public WTO_LANES_LEGS = 2 +let public WTO_LANES_BUILT = 3 + [safe_when_uninitialized] struct public WtoTeamLanes - built : bool[16] + navState : int = 0 + phase : int[16] + ticket : int[80] centerLen : float[16] centerMid : float3[16] flankValid : bool[32] @@ -44,7 +50,7 @@ def public wto_lanes_sub_key(army, capIdx, laneId : int) : int [never_inline] def public wto_lanes_reset(var lanes : WtoTeamLanes&) for i in range(16) - lanes.built[i] = false + lanes.phase[i] = WTO_LANES_IDLE lanes.centerLen[i] = 0.0 lanes.centerMid[i] = float3(0.0, 0.0, 0.0) lanes.capSafeSince[i] = -100.0 @@ -56,6 +62,8 @@ def public wto_lanes_reset(var lanes : WtoTeamLanes&) lanes.rallyPos[i] = float3(0.0, 0.0, 0.0) lanes.rallyStartAt[i] = -100.0 lanes.rallyReleased[i] = false + for i in range(80) + lanes.ticket[i] = 0 for a in range(3) lanes.enemyAirActive[a] = false lanes.enemyAirSeenAt[a] = -100.0 @@ -66,92 +74,6 @@ def public wto_lanes_reset_rallies(var lanes : WtoTeamLanes&) lanes.rallyStartAt[i] = -100.0 lanes.rallyReleased[i] = false -[never_inline] -def private wto_nav_project_pt(navIdx : int; var pt : float3&) : bool - if project_to_nearest_navmesh_point_no_obstacles_ex(navIdx, pt, float3(28.0, 64.0, 28.0)) - return true - return project_to_nearest_navmesh_point_no_obstacles_ex(navIdx, pt, float3(150.0, 120.0, 150.0)) - -[never_inline] -def private wto_measure_nav_path(navIdx : int; fromPt, toPt : float3; sampleFrac : float; - var outLen : float&; var outSample : float3&) : bool - var sPt = fromPt - var gPt = toPt - if !wto_nav_project_pt(navIdx, sPt) || !wto_nav_project_pt(navIdx, gPt) - return false - var ok = false - var totalLen = 0.0 - var sample = lerp(sPt, gPt, sampleFrac) - find_path_ex(navIdx, sPt, gPt, float3(32.0, 48.0, 32.0), 9.0, 2.5, null) <| $(path : array#) - let n = length(path) - if n < 2 - return - ok = true - for i in range(1, n) - totalLen += length(path[i] - path[i - 1]) - let targetD = totalLen * clamp(sampleFrac, 0.05, 0.95) - var acc = 0.0 - sample = path[n - 1] - for i in range(1, n) - let seg = length(path[i] - path[i - 1]) - if acc + seg >= targetD && seg > 0.01 - sample = lerp(path[i - 1], path[i], (targetD - acc) / seg) - break - acc += seg - outLen = totalLen - outSample = sample - return ok && totalLen > 1.0 - -[never_inline] -def public wto_lanes_ensure_cap(world : WtoWorldSnap const&; army, capIdx : int; - var lanes : WtoTeamLanes&) - let k = wto_lanes_cap_key(army, capIdx) - if lanes.built[k] || capIdx < 0 || capIdx >= world.capCount || !world.teamSpawnValid[army] - return - let navIdx = pathfinder_is_loaded_ex(1) ? 1 : (pathfinder_is_loaded_ex(0) ? 0 : -1) - if navIdx < 0 - return - lanes.built[k] = true - let spawnPt = world.teamSpawnCenter[army] - let capPt = world.caps[capIdx].center - var cLen = 0.0 - var cRally = lerp(spawnPt, capPt, WTO_AI_CMD_RALLY_PROG_FRAC) - if !wto_measure_nav_path(navIdx, spawnPt, capPt, WTO_AI_CMD_RALLY_PROG_FRAC, cLen, cRally) - cLen = max(80.0, sqrt(wto_xz_dist_sq(spawnPt, capPt))) - var cMid = lerp(spawnPt, capPt, 0.5) - var dummyLen = 0.0 - let _midOk = wto_measure_nav_path(navIdx, spawnPt, capPt, 0.5, dummyLen, cMid) - lanes.centerLen[k] = cLen - lanes.centerMid[k] = cMid - lanes.rallyPos[k * 3 + WTO_LANE_CENTER] = cRally - - let toCap = wto_xz_normalize(capPt - spawnPt, float3(1.0, 0.0, 0.0)) - let lat = float3(-toCap.z, 0.0, toCap.x) - let straightD = sqrt(wto_xz_dist_sq(spawnPt, capPt)) - let swing = clamp(straightD * 0.34, 80.0, 260.0) - for side in range(2) - let sign = side == 0 ? 1.0 : -1.0 - var relay = wto_clamp_battle_xz(lerp(spawnPt, capPt, 0.5) + lat * (sign * swing), world.battleCenter, world.battleRadius, 45.0) - let fKey = k * 2 + side - lanes.flankValid[fKey] = false - if !wto_nav_project_pt(navIdx, relay) || !wto_terrain_point_valid(army, relay) - continue - if sqrt(wto_xz_dist_sq(relay, cMid)) < WTO_AI_CMD_FLANK_MIN_SEP_M - continue - var len1 = 0.0 - var len2 = 0.0 - var rPt = lerp(spawnPt, relay, 0.8) - var dummy = relay - if !wto_measure_nav_path(navIdx, spawnPt, relay, 0.8, len1, rPt) - continue - if !wto_measure_nav_path(navIdx, relay, capPt, 0.5, len2, dummy) - continue - if (len1 + len2) > cLen * WTO_AI_CMD_FLANK_MAX_RATIO - continue - lanes.flankValid[fKey] = true - lanes.flankRelay[fKey] = relay - lanes.rallyPos[k * 3 + side + 1] = rPt - [never_inline] def public wto_lanes_update_team_intel(world : WtoWorldSnap const&; now : float; var lanes : WtoTeamLanes&) @@ -193,42 +115,3 @@ def public wto_lanes_update_recall(world : WtoWorldSnap const&; army : int; now elif lanes.recallActive[k] && (now - lanes.capSafeSince[k]) >= WTO_AI_CMD_RECALL_SAFE_SEC lanes.recallActive[k] = false -[never_inline] -def public wto_lanes_update_rallies(world : WtoWorldSnap const&; army : int; now : float; - var lanes : WtoTeamLanes&; var bots : WtoBotSlot[64]&) - let rallyRadSq = wto_sq(WTO_AI_CMD_RALLY_RADIUS_M) - for c in range(world.capCount) - wto_lanes_ensure_cap(world, army, c, lanes) - for lane in range(3) - let sk = wto_lanes_sub_key(army, c, lane) - if lanes.rallyReleased[sk] - continue - let rPos = lanes.rallyPos[sk] - if length_sq(rPos) < 1.0 - lanes.rallyReleased[sk] = true - continue - let rDistToCapSq = wto_xz_dist_sq(rPos, world.caps[c].center) - var assigned = 0 - var arrived = 0 - for i in range(WTO_MAX_BOTS) - assume b = bots[i] - if !b.used || b.army != army || !b.order.valid || b.order.capIndex != c || b.order.laneId != lane || !wto_order_is_offensive(b.order.role) - continue - let uIdx = wto_world_find_unit(world, b.eid) - if uIdx < 0 - continue - assigned++ - let pos = world.units[uIdx].pos - if wto_xz_dist_sq(pos, rPos) <= rallyRadSq || wto_xz_dist_sq(pos, world.caps[c].center) < rDistToCapSq - arrived++ - if assigned <= 1 - lanes.rallyReleased[sk] = true - continue - if arrived > 0 && lanes.rallyStartAt[sk] < 0.0 - lanes.rallyStartAt[sk] = now - let enough = float(arrived) >= float(assigned) * WTO_AI_CMD_RALLY_MIN_FRAC - let timedOut = lanes.rallyStartAt[sk] >= 0.0 && (now - lanes.rallyStartAt[sk]) >= WTO_AI_CMD_RALLY_WAIT_SEC - if enough || timedOut - lanes.rallyReleased[sk] = true - if WTO_AI_DIAG_TELEMETRY - print("WTO_AI|RALLY_GO|t={now}|army={army}|cap={c}|lane={lane}|arrived={arrived}/{assigned}|timeout={timedOut}\n") diff --git a/game-ai/ground/wto_ai_nav_common.das b/game-ai/ground/wto_ai_nav_common.das index f067fe1..cb614e3 100644 --- a/game-ai/ground/wto_ai_nav_common.das +++ b/game-ai/ground/wto_ai_nav_common.das @@ -1,8 +1,8 @@ -// Bidirectional non-holonomic local planner: -// - Directed 7-arc reverse trajectory planner for ridge withdrawals, tactical peeks, cliff escapes, -// and jam unsticking (enabling sustained 30-50m reverse transfers); -// - Stationary combat hull discipline (zero hull-pivot whip on turreted tanks during ENGAGE_HALT); -// - Forward 9-arc DWA rollout with cliff rejection, TTC ally overtaking, and jam/crowd penalties. +// Navigation layer of one bot per nav tick: turns the tactics goal into a drive command. +// Stationary and hull-angle states hold or pivot in place; tactical withdrawals and unstick +// manoeuvres back up along checked ground; otherwise the bot follows its corridor (route) with a +// lookahead point (follow), slows for corners, narrow passages, traffic and fresh obstacles +// (avoid), and escalates when it stops making progress (unstick). options indenting = 2 options no_global_heap = true module wto_ai_nav_common shared @@ -12,147 +12,21 @@ require math 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 require %appGame.wtoai.wto_ai_terrain_common -require %appGame.wtoai.wto_ai_world_common -require %appGame.wtoai.wto_ai_crowd_common +require %appGame.wtoai.wto_ai_navquery_common +require %appGame.wtoai.wto_ai_navmesh_common require %appGame.wtoai.wto_ai_route_common +require %appGame.wtoai.wto_ai_follow_common +require %appGame.wtoai.wto_ai_avoid_common +require %appGame.wtoai.wto_ai_unstick_common [never_inline] -def private wto_wreck_or_ally_clearance(world : WtoWorldSnap const&; selfEid : EntityId; - pt : float3; tSec, selfRad : float) : float - var pen = 0.0 - for w in range(world.wreckCount) - let r = selfRad + max(world.wrecks[w].halfLen, world.wrecks[w].halfWid) + WTO_AI_TERRAIN_MARGIN_M - let dSq = wto_xz_dist_sq(pt, world.wrecks[w].pos) - if dSq < r * r - return 1.0e6 - elif dSq < wto_sq(r + 3.5) - pen += 18.0 - for i in range(world.unitCount) - assume u = world.units[i] - if !u.isAlive || !u.isGround || u.eid == selfEid - continue - let predPos = u.pos + u.vel * min(tSec, 1.6) - let r = selfRad + max(u.halfLen, u.halfWid) + WTO_AI_TERRAIN_MARGIN_M - let dSq = wto_xz_dist_sq(pt, predPos) - if dSq < r * r - return 1.0e6 - elif dSq < wto_sq(r + 5.0) - pen += 22.0 - return pen - -// Evaluate 7 curved rear trajectories (`16m` behind chassis) toward `reverseGoal`. -[never_inline] -def private wto_eval_reverse_arcs(world : WtoWorldSnap const&; now : float; - myPos, hullFwd, reverseGoal : float3; - var slot : WtoBotSlot&; var outRearDir : float3&) : bool - let rearBase = -wto_xz_normalize(hullFwd, float3(1.0, 0.0, 0.0)) - let baseYaw = atan2(rearBase.z, rearBase.x) - let wishDir = wto_xz_normalize(reverseGoal - myPos, rearBase) - let selfRad = max(slot.spec.halfWid, 1.65) - var bestScore = -1.0e9 - var found = false - outRearDir = rearBase - for a in range(7) - let steerFrac = float(a - 3) / 3.0 - let arcCurv = steerFrac * 0.042 - var cur = myPos - var blocked = false - var arcPen = abs(steerFrac) * 2.5 - for s in range(1, 5) - let dist = float(s) * 3.8 - let yaw = baseYaw + arcCurv * dist - let stepDir = float3(cos(yaw), 0.0, sin(yaw)) - let nx = cur.x + stepDir.x * 3.8 - let nz = cur.z + stepDir.z * 3.8 - var gy = cur.y - if !wto_terrain_drivable_y(cur, nx, nz, gy) - blocked = true - break - if wto_terrain_hard_ray(cur + float3(0.0, 1.25, 0.0), stepDir, 4.2) < 3.7 - blocked = true - break - let nxt = float3(nx, gy, nz) - let dynPen = wto_wreck_or_ally_clearance(world, slot.eid, nxt, dist / max(1.8, slot.spec.vMaxRev), selfRad) - if dynPen >= 1.0e5 - blocked = true - break - arcPen += dynPen * 0.25 + wto_crowd_point_penalty(world, slot.army, slot.eid, nxt) * 0.2 - cur = nxt - if blocked - continue - let firstYaw = baseYaw + arcCurv * 5.5 - let candDir = float3(cos(firstYaw), 0.0, sin(firstYaw)) - if wto_terrain_has_cliff_ahead(myPos, candDir, 15.0) - continue - let score = dot(candDir, wishDir) * 35.0 - arcPen - wto_world_jam_penalty(world, cur, now) * 0.4 - if score > bestScore - bestScore = score - outRearDir = candDir - found = true - return found - -// Evaluate 9 curved forward trajectories (`22m` ahead) with hard cliff rejection and traffic cost. -[never_inline] -def private wto_eval_forward_arcs(world : WtoWorldSnap const&; now : float; - myPos, hullFwd, wishDir : float3; speedCmd : float; - var slot : WtoBotSlot&; var outFwdDir : float3&) : bool - let fwdBase = wto_xz_normalize(hullFwd, float3(1.0, 0.0, 0.0)) - let baseYaw = atan2(fwdBase.z, fwdBase.x) - let selfRad = max(slot.spec.halfWid, 1.65) - var bestScore = -1.0e9 - var found = false - outFwdDir = wishDir - for a in range(9) - let steerFrac = float(a - 4) / 4.0 - let arcCurv = steerFrac * 0.038 - let firstYaw = baseYaw + arcCurv * 6.5 - let candDir = float3(cos(firstYaw), 0.0, sin(firstYaw)) - if wto_terrain_has_cliff_ahead(myPos, candDir, WTO_AI_TERRAIN_CREST_LOOKAHEAD_M) - continue - var cur = myPos - var blocked = false - var arcPen = abs(steerFrac) * 2.2 - for s in range(1, 6) - let dist = float(s) * 4.2 - let yaw = baseYaw + arcCurv * dist - let stepDir = float3(cos(yaw), 0.0, sin(yaw)) - let nx = cur.x + stepDir.x * 4.2 - let nz = cur.z + stepDir.z * 4.2 - var gy = cur.y - if !wto_terrain_drivable_y(cur, nx, nz, gy) - blocked = true - break - if wto_terrain_hard_ray(cur + float3(0.0, 1.3, 0.0), stepDir, 4.6) < 4.1 - blocked = true - break - let nxt = float3(nx, gy, nz) - let dynPen = wto_wreck_or_ally_clearance(world, slot.eid, nxt, dist / max(2.5, speedCmd), selfRad) - if dynPen >= 1.0e5 - blocked = true - break - arcPen += dynPen * 0.3 + wto_crowd_point_penalty(world, slot.army, slot.eid, nxt) * 0.35 - cur = nxt - if blocked - continue - let align = dot(candDir, wishDir) * 40.0 + dot(candDir, slot.nav.steerDir) * 4.5 - let score = align - arcPen - wto_world_jam_penalty(world, cur, now) - if score > bestScore - bestScore = score - outFwdDir = candDir - found = true - return found - -[never_inline] -def private wto_set_drive_cmd(var cmd : WtoDriveCmd&; mode : int; targetPos, desiredDir : float3; - speedMps, frontClr, rearClr : float) - cmd.valid = true - cmd.mode = mode - cmd.targetPos = targetPos - cmd.desiredDir = desiredDir - cmd.speedMps = speedMps - cmd.frontClearM = frontClr - cmd.rearClearM = rearClr +def private wto_nav_halt(myPos, hullFwd : float3; var slot : WtoBotSlot&) + slot.nav.stuckCheckAt = -100.0 + slot.nav.stuckOrigin = myPos + wto_drive_cmd_set(slot.driveCmd, WTO_DRIVE_HALT, myPos, hullFwd, 0.0, slot.nav.frontClearM, slot.nav.rearClearM) + slot.nav.bumperBlockedSince = -100.0 [never_inline] def private wto_handle_stationary_engage(myPos, hullFwd : float3; var slot : WtoBotSlot&) @@ -161,56 +35,135 @@ def private wto_handle_stationary_engage(myPos, hullFwd : float3; var slot : Wto let toTgt = wto_xz_normalize(slot.perceive.knownPos - myPos, hullFwd) let angDeg = acos(clamp(dot(toTgt, hullFwd), -1.0, 1.0)) * WTO_RAD_TO_DEG if angDeg > slot.spec.yawLimitDeg * 0.78 - wto_set_drive_cmd(slot.driveCmd, WTO_DRIVE_PIVOT, myPos + toTgt * 18.0, toTgt, 2.0, slot.nav.frontClearM, slot.nav.rearClearM) + slot.nav.stuckCheckAt = -100.0 + wto_drive_cmd_set(slot.driveCmd, WTO_DRIVE_PIVOT, myPos + toTgt * 18.0, toTgt, 2.0, slot.nav.frontClearM, slot.nav.rearClearM) return - // Turreted tanks (and aligned TDs) hold chassis completely still so barrel settles cleanly! - wto_set_drive_cmd(slot.driveCmd, WTO_DRIVE_HALT, myPos, hullFwd, 0.0, slot.nav.frontClearM, slot.nav.rearClearM) + // Turreted tanks (and aligned TDs) hold the chassis still so the barrel settles cleanly. + wto_nav_halt(myPos, hullFwd, slot) [never_inline] -def private wto_check_stuck_watchdog(var world : WtoWorldSnap&; now : float; - myPos, wishDir : float3; var slot : WtoBotSlot&) - assume nav = slot.nav - let movingIntent = slot.tactics.desiredSpeedMps > 1.2 && now >= nav.reverseUntil - if !movingIntent - nav.stuckOrigin = myPos - nav.stuckCheckAt = now + WTO_AI_NAV_STUCK_WINDOW_SEC - return - if nav.stuckCheckAt < -50.0 - nav.stuckOrigin = myPos - nav.stuckCheckAt = now + WTO_AI_NAV_STUCK_WINDOW_SEC - return - if now < nav.stuckCheckAt - return - let moved = sqrt(wto_xz_dist_sq(myPos, nav.stuckOrigin)) - nav.stuckOrigin = myPos - nav.stuckCheckAt = now + WTO_AI_NAV_STUCK_WINDOW_SEC - if moved >= WTO_AI_NAV_STUCK_MIN_MOVE_M - return - wto_world_record_jam(world, myPos + wishDir * 6.0, now) - wto_route_request_detour(world, now, myPos, wishDir, slot) - let backIdx = clamp(slot.route.corridorIdx - 2, 0, max(0, slot.route.corridorLen - 1)) - nav.reverseAnchor = slot.route.corridorLen > 0 ? slot.route.corridor[backIdx] : (myPos - wishDir * 22.0) - nav.reverseUntil = now + max(WTO_AI_NAV_UNSTICK_REV_SEC, 3.6) - nav.reverseCount++ +def private wto_nav_hull_angle(myPos, hullFwd : float3; var slot : WtoBotSlot&) + let wishAngle = wto_xz_normalize(slot.tactics.hullAngleDir, hullFwd) + let angErr = acos(clamp(dot(wishAngle, hullFwd), -1.0, 1.0)) * WTO_RAD_TO_DEG + if angErr > 8.0 + slot.nav.stuckCheckAt = -100.0 + wto_drive_cmd_set(slot.driveCmd, WTO_DRIVE_PIVOT, myPos + wishAngle * 14.0, wishAngle, 0.0, slot.nav.frontClearM, slot.nav.rearClearM) + else + wto_nav_halt(myPos, hullFwd, slot) +// Ridge withdrawal and backing into cover: reverse straight to the goal when the way is free. [never_inline] -def private wto_try_reverse_drive(world : WtoWorldSnap const&; now : float; - myPos, hullFwd : float3; var slot : WtoBotSlot&) : bool - let stMode = slot.tactics.state - let wantTacRev = stMode == WTO_STATE_RIDGE_WITHDRAW || (stMode == WTO_STATE_RETREAT_COVER && slot.tactics.retreatReverse) - if !wantTacRev && now >= slot.nav.reverseUntil +def private wto_nav_tactical_reverse(navState : int; myPos, hullFwd : float3; var slot : WtoBotSlot&) : bool + let st = slot.tactics.state + if st != WTO_STATE_RIDGE_WITHDRAW && !(st == WTO_STATE_RETREAT_COVER && slot.tactics.retreatReverse) return false - let revGoal = wantTacRev ? slot.tactics.moveGoal : slot.nav.reverseAnchor - var rearDir = -hullFwd - if slot.nav.rearClearM > 2.4 && wto_eval_reverse_arcs(world, now, myPos, hullFwd, revGoal, slot, rearDir) - slot.nav.steerDir = rearDir - wto_set_drive_cmd(slot.driveCmd, WTO_DRIVE_REVERSE, myPos + rearDir * 18.0, rearDir, max(2.0, slot.spec.vMaxRev), slot.nav.frontClearM, slot.nav.rearClearM) - return true - slot.nav.reverseUntil = -100.0 - return false + let goal = slot.tactics.moveGoal + let dist = sqrt(wto_xz_dist_sq(myPos, goal)) + if dist < 2.0 || slot.nav.rearClearM < 2.4 + return false + if navState == WTO_NAVMESH_LOADED && slot.route.tier >= 0 + var frac = 0.0 + if wto_navq_raycast(slot.route.tier, slot.route.filter, myPos, goal, frac) == 0 && frac * dist < 3.0 + return false + 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) + return true + +// Surface, flags and room to the mesh edge under the bot (battles with a pack only). +[never_inline] +def private wto_nav_probe_mesh(navState : int; myPos : float3; var slot : WtoBotSlot&) + assume nav = slot.nav + nav.onMesh = false + nav.wallDistM = 99.0 + nav.surfaceArea = 0 + nav.chokepoint = false + if navState != WTO_NAVMESH_LOADED || slot.route.tier < 0 + return + var probe = WtoNavProbeOut() + if !wto_navq_probe(slot.route.tier, slot.route.filter, myPos, WTO_AI_PF_NARROW_WALL_M + 1.0, probe) || !probe.onMesh + return + nav.onMesh = true + nav.wallDistM = probe.wallDistM + nav.surfaceArea = probe.area + nav.chokepoint = (probe.flags & WTO_NAVQ_FLAG_CHOKEPOINT) != 0 + +// A sideways step is taken only when the mesh allows the straight line to it. +[never_inline] +def private wto_nav_apply_shift(navState : int; myPos, target, dir : float3; var slot : WtoBotSlot&) : float3 + let shift = slot.nav.avoidShiftM + if abs(shift) < 0.01 + return target + let shifted = target + float3(-dir.z, 0.0, dir.x) * shift + if navState != WTO_NAVMESH_LOADED || slot.route.tier < 0 + return shifted + var frac = 0.0 + if wto_navq_raycast(slot.route.tier, slot.route.filter, myPos, shifted, frac) != 0 + return shifted + slot.nav.avoidShiftM = 0.0 + slot.nav.avoidSpeedCap = min(slot.nav.avoidSpeedCap, 2.0) + return target + +// A fresh obstacle in front for bumperBlockSec: mark it for path searches and plan again. +[never_inline] +def private wto_nav_bumper_block(navState : int; now : float; myPos, dir : float3; clear : float; var slot : WtoBotSlot&) + assume nav = slot.nav + if clear >= WTO_AI_PF_BUMPER_STOP_M + 0.5 + nav.bumperBlockedSince = -100.0 + return + if nav.bumperBlockedSince < -50.0 + nav.bumperBlockedSince = now + return + if now - nav.bumperBlockedSince < WTO_AI_PF_BUMPER_BLOCK_SEC + return + nav.bumperBlockedSince = -100.0 + let spot = myPos + dir * (slot.spec.halfLen + clear + 1.0) + if navState == WTO_NAVMESH_LOADED + wto_navq_add_dynamic(spot, WTO_AI_PF_RUBBLE_RADIUS_M, WTO_AI_PF_RUBBLE_COST_MUL, now + WTO_AI_PF_RUBBLE_TTL_SEC) + slot.route.replanRequested = true + print("WTO_AI|NAV_BLOCKED|eid={uint(slot.eid)}|pos={myPos}|spot={spot}\n") [never_inline] -def public wto_nav_update(var world : WtoWorldSnap&; now : float; +def private wto_nav_speed(navState : int; now : float; myPos, dir : float3; lookM : float; narrow : bool; + var slot : WtoBotSlot&) : float + var speed = min(slot.tactics.desiredSpeedMps, wto_follow_speed_cap(slot.route, slot.spec, lookM)) + if narrow + speed = min(speed, WTO_AI_PF_NARROW_SPEED_MPS) + speed = min(speed, slot.nav.avoidSpeedCap) + let clear = wto_avoid_bumper(myPos, dir, slot.spec) + slot.nav.bumperClearM = clear + if clear < WTO_AI_PF_BUMPER_RAY_M + speed = min(speed, max(0.0, clear - WTO_AI_PF_BUMPER_STOP_M) * 1.2) + wto_nav_bumper_block(navState, now, myPos, dir, clear, slot) + return speed + +[never_inline] +def private wto_nav_follow(var world : WtoWorldSnap&; navState : int; now : float; myPos, hullFwd : float3; + var slot : WtoBotSlot&) + assume rt = slot.route + if rt.corridorLen == 0 || wto_follow_arrived(rt, myPos) + wto_nav_halt(myPos, hullFwd, slot) + return + wto_follow_track(myPos, rt) + let speedNow = abs(slot.drive.lastVFwd) + let lookM = wto_follow_lookahead(slot.spec, speedNow) + let pathTarget = wto_follow_target(rt, lookM) + let pathDir = wto_xz_normalize(pathTarget - myPos, hullFwd) + let narrow = slot.nav.wallDistM < WTO_AI_PF_NARROW_WALL_M || slot.nav.chokepoint + wto_avoid_traffic(world, now, myPos, pathDir, speedNow, narrow, slot) + let target = wto_nav_apply_shift(navState, myPos, pathTarget, pathDir, slot) + let dir = wto_xz_normalize(target - myPos, hullFwd) + let speed = wto_nav_speed(navState, now, myPos, dir, lookM, narrow, slot) + slot.nav.steerDir = dir + let turnDeg = acos(clamp(dot(dir, hullFwd), -1.0, 1.0)) * WTO_RAD_TO_DEG + let mode = turnDeg >= WTO_AI_NAV_PIVOT_ANGLE_DEG ? WTO_DRIVE_PIVOT : WTO_DRIVE_CRUISE + wto_drive_cmd_set(slot.driveCmd, mode, target, dir, speed, slot.nav.frontClearM, slot.nav.rearClearM) + 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) + +[never_inline] +def public wto_nav_update(var world : WtoWorldSnap&; navState, slotIdx : int; now : float; myPos, rawHullFwd : float3; var slot : WtoBotSlot&) if !WTO_AI_LAYER_NAVIGATION slot.driveCmd.valid = false @@ -219,40 +172,19 @@ def public wto_nav_update(var world : WtoWorldSnap&; now : float; 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) - slot.nav.cliffAhead = wto_terrain_has_cliff_ahead(myPos, hullFwd, WTO_AI_TERRAIN_CREST_LOOKAHEAD_M) - - if slot.tactics.state == WTO_STATE_HULL_ANGLE - slot.nav.stuckCheckAt = now + WTO_AI_NAV_STUCK_WINDOW_SEC - let wishAngle = wto_xz_normalize(slot.tactics.hullAngleDir, hullFwd) - let angErr = acos(clamp(dot(wishAngle, hullFwd), -1.0, 1.0)) * WTO_RAD_TO_DEG - if angErr > 8.0 - wto_set_drive_cmd(slot.driveCmd, WTO_DRIVE_PIVOT, myPos + wishAngle * 14.0, wishAngle, 0.0, slot.nav.frontClearM, slot.nav.rearClearM) - else - wto_set_drive_cmd(slot.driveCmd, WTO_DRIVE_HALT, myPos, hullFwd, 0.0, slot.nav.frontClearM, slot.nav.rearClearM) + let st = slot.tactics.state + if st == WTO_STATE_HULL_ANGLE + wto_nav_hull_angle(myPos, hullFwd, slot) return - if slot.tactics.state == WTO_STATE_SHORT_HALT || slot.tactics.state == WTO_STATE_COVER_RELOAD || slot.tactics.desiredSpeedMps <= 0.05 - slot.nav.stuckCheckAt = now + WTO_AI_NAV_STUCK_WINDOW_SEC + if st == WTO_STATE_SHORT_HALT || st == WTO_STATE_COVER_RELOAD || slot.tactics.desiredSpeedMps <= 0.05 wto_handle_stationary_engage(myPos, hullFwd, slot) return - if wto_try_reverse_drive(world, now, myPos, hullFwd, slot) + if wto_nav_tactical_reverse(navState, myPos, hullFwd, slot) || wto_unstick_reversing(now, myPos, slot) return - - let wp = wto_route_select_waypoint(world, now, myPos, slot.tactics.moveGoal, slot) - let wishDir = wto_xz_normalize(wp - myPos, hullFwd) - wto_check_stuck_watchdog(world, now, myPos, wishDir, slot) - - var bestDir = wishDir - if !wto_eval_forward_arcs(world, now, myPos, hullFwd, wishDir, slot.tactics.desiredSpeedMps, slot, bestDir) - if slot.nav.rearClearM > 3.2 - slot.nav.reverseAnchor = myPos - hullFwd * 26.0 - slot.nav.reverseUntil = now + 4.8 - slot.nav.reverseCount++ - wto_set_drive_cmd(slot.driveCmd, WTO_DRIVE_REVERSE, slot.nav.reverseAnchor, -hullFwd, max(2.0, slot.spec.vMaxRev), slot.nav.frontClearM, slot.nav.rearClearM) - return - bestDir = wishDir - - slot.nav.steerDir = bestDir - let turnDeg = acos(clamp(dot(wishDir, hullFwd), -1.0, 1.0)) * WTO_RAD_TO_DEG - let needPivot = turnDeg >= WTO_AI_NAV_PIVOT_ANGLE_DEG || (slot.nav.frontClearM < slot.spec.halfLen + 1.8 && turnDeg > 32.0) - let cmdDir = needPivot ? wishDir : bestDir - wto_set_drive_cmd(slot.driveCmd, needPivot ? WTO_DRIVE_PIVOT : WTO_DRIVE_CRUISE, myPos + cmdDir * 22.0, cmdDir, slot.tactics.desiredSpeedMps, slot.nav.frontClearM, slot.nav.rearClearM) + if navState == WTO_NAVMESH_UNDECIDED + wto_nav_halt(myPos, hullFwd, slot) + return + let goal = wto_route_active_goal(myPos, slot.tactics.moveGoal, slot) + wto_route_update(navState, slotIdx, now, myPos, goal, slot) + wto_nav_probe_mesh(navState, myPos, slot) + wto_nav_follow(world, navState, now, myPos, hullFwd, slot) diff --git a/game-ai/ground/wto_ai_nav_types_common.das b/game-ai/ground/wto_ai_nav_types_common.das new file mode 100644 index 0000000..318f4db --- /dev/null +++ b/game-ai/ground/wto_ai_nav_types_common.das @@ -0,0 +1,65 @@ +// Per-bot path, path-following, avoidance and unstick state (route / follow / avoid / unstick / +// nav modules) and the shared constants of the navigation layer. +options indenting = 2 +options no_global_heap = true +module wto_ai_nav_types_common shared + +// Corners a path may carry; matches WTO_NAV_RT_MAX_CORNERS of the native engine. +let public WTO_NAV_MAX_CORNERS = 96 + +// Where a bot's corridor came from. +let public WTO_ROUTE_SRC_NONE = 0 +let public WTO_ROUTE_SRC_MESH = 1 +let public WTO_ROUTE_SRC_STOCK = 2 +let public WTO_ROUTE_SRC_RECOVER = 3 + +[safe_when_uninitialized] +struct public WtoRouteState + corridor : float3[96] + corridorLen : int = 0 + source : int = 0 + segIdx : int = 0 + segT : float = 0.0 + offTrackM : float = 0.0 + goal : float3 = float3(0.0, 0.0, 0.0) + truncated : bool = false + pending : bool = false + ticket : int = 0 + pendingGoal : float3 = float3(0.0, 0.0, 0.0) + nextReplanAt : float = -100.0 + replanRequested : bool = false + tier : int = -1 + filter : int = 0 + lastStatus : int = -1 + goalUnreachable : bool = false + unreachableGoal : float3 = float3(0.0, 0.0, 0.0) + requests : int = 0 + noGoalCount : int = 0 + +[safe_when_uninitialized] +struct public WtoNavState + steerDir : float3 = float3(1.0, 0.0, 0.0) + frontClearM : float = 30.0 + rearClearM : float = 16.0 + onMesh : bool = false + wallDistM : float = 99.0 + surfaceArea : int = 0 + chokepoint : bool = false + bumperClearM : float = 99.0 + bumperBlockedSince : float = -100.0 + yieldUntil : float = -100.0 + yieldCooldownUntil : float = -100.0 + avoidShiftM : float = 0.0 + avoidSpeedCap : float = 99.0 + stuckOrigin : float3 = float3(0.0, 0.0, 0.0) + stuckCheckAt : float = -100.0 + unstickAnchor : float3 = float3(0.0, 0.0, 0.0) + unstickLevel : int = 0 + unstickAttempts : int = 0 + lastUnstickAt : float = -100.0 + reverseTarget : float3 = float3(0.0, 0.0, 0.0) + reverseUntil : float = -100.0 + reverseCount : int = 0 + unstickEvents : int = 0 + unreachableEvents : int = 0 + ridgeWithdrawEvents : int = 0 diff --git a/game-ai/ground/wto_ai_navmesh_common.das b/game-ai/ground/wto_ai_navmesh_common.das index 670b10f..e14f978 100644 --- a/game-ai/ground/wto_ai_navmesh_common.das +++ b/game-ai/ground/wto_ai_navmesh_common.das @@ -1,7 +1,8 @@ // Baked navigation pack of the battle (native/wto-nav through the "wtoNav" mission action). -// The native side answers synchronously into the request DataBlock; see local_mp_nav.c. -// The pack is loaded once at battle start; whether the battle uses it, keeps the script's own -// navigation or refuses to drive is decided by that load and never changes mid-battle. +// The pack is read in the background while the battle loads (prefetch) and taken at the first +// world tick (load_map); whether the battle uses it, falls back to stock road paths or refuses to +// drive is decided by that load and never changes mid-battle. Queued path searches advance once +// per world tick within the per-frame budget (pump). options indenting = 2 options no_global_heap = true module wto_ai_navmesh_common shared @@ -13,6 +14,7 @@ require DagorSystem require Mission require %appGame.wtoai.wto_ai_config_common require %appGame.wtoai.wto_ai_types_common +require %appGame.wtoai.wto_ai_navquery_common let public WTO_NAVMESH_UNDECIDED = 0 let public WTO_NAVMESH_LOADED = 1 @@ -22,11 +24,14 @@ let public WTO_NAVMESH_OFF = 4 let public WTO_NAVMESH_TIER_STANDARD = 1 let public WTO_NAVMESH_FILTER_TRACKED = 0 -let public WTO_NAVMESH_MAX_POINTS = 96 -let public WTO_NAVMESH_PATH_FULL = 0 -let public WTO_NAVMESH_PATH_PARTIAL = 1 -let public WTO_NAVMESH_PATH_FAILED = 2 +[safe_when_uninitialized] +struct public WtoNavmeshBattle + state : int = 0 + selfTestPhase : int = 0 + selfTestTicket : int[3] + lastQueries : int = -1 + lastMeshQueries : int = -1 [never_inline] def private wto_navmesh_add_costs(var blk : DataBlock&) @@ -47,6 +52,19 @@ def private wto_navmesh_add_costs(var blk : DataBlock&) add(blk, "w_shallowWater", "{WTO_AI_NAVMESH_W_SHALLOW_WATER}") add(blk, "w_chokepoint", "{WTO_AI_NAVMESH_W_CHOKEPOINT}") +// Battle loading: start reading this battle's pack on a background thread. +[never_inline] +def public wto_navmesh_prefetch() + if !WTO_AI_NAVMESH_ENABLED + return + using() <| $(var blk : DataBlock) + add(blk, "op", "prefetch") + call_mission_action("wtoNav", blk) + let answer = datablock_getStr(blk, "state", "") + let level = datablock_getStr(blk, "level", "") + let reason = datablock_getStr(blk, "reason", "") + print("WTO_AI|NAVMESH_PREFETCH|state={answer}|level={level}|reason={reason}\n") + // Asks the native engine for this battle's pack once; returns a WTO_NAVMESH_* state. [never_inline] def public wto_navmesh_load() : int @@ -75,83 +93,87 @@ def public wto_navmesh_load() : int return state [never_inline] -def public wto_navmesh_unload() +def private wto_navmesh_unload() using() <| $(var blk : DataBlock) add(blk, "op", "unload_map") call_mission_action("wtoNav", blk) -// Corners of a path on the mesh of `tier`; returns WTO_NAVMESH_PATH_* and fills count/lenM. +// Advances queued path searches within the per-frame budget and expires dynamic costs. [never_inline] -def public wto_navmesh_find_path(tier, costFilter : int; start, goal : float3; - var pts : float3[96]&; var count : int&; var lenM : float&) : int - var status = WTO_NAVMESH_PATH_FAILED - count = 0 - lenM = 0.0 +def private wto_navmesh_pump(now : float) using() <| $(var blk : DataBlock) - add(blk, "op", "find_path") - add(blk, "tier", "{tier}") - add(blk, "filter", "{costFilter}") - add(blk, "max", "{WTO_NAVMESH_MAX_POINTS}") - add(blk, "snap", "{WTO_AI_NAVMESH_SNAP_M}") - add(blk, "sx", "{start.x}") - add(blk, "sy", "{start.y}") - add(blk, "sz", "{start.z}") - add(blk, "gx", "{goal.x}") - add(blk, "gy", "{goal.y}") - add(blk, "gz", "{goal.z}") + add(blk, "op", "pump") + add(blk, "now", "{now}") + add(blk, "budgetUs", "{WTO_AI_NAVMESH_PATH_BUDGET_US}") call_mission_action("wtoNav", blk) - let answer = datablock_getStr(blk, "status", "") - status = answer == "full" ? WTO_NAVMESH_PATH_FULL : answer == "partial" ? WTO_NAVMESH_PATH_PARTIAL : WTO_NAVMESH_PATH_FAILED - if status == WTO_NAVMESH_PATH_FAILED - return - count = clamp(datablock_getInt(blk, "count", 0), 0, WTO_NAVMESH_MAX_POINTS) - lenM = float(datablock_getInt(blk, "lenCm", 0)) * 0.01 - for i in range(count) - let px = datablock_getInt(blk, "p{i}x", 0) - let py = datablock_getInt(blk, "p{i}y", 0) - let pz = datablock_getInt(blk, "p{i}z", 0) - pts[i] = float3(float(px) * 0.01, float(py) * 0.01, float(pz) * 0.01) - return status -// Logs one path per team from its spawn to the first capture zone; proves the round trip. +// One path per team from its spawn to the first capture zone through the queued search. [never_inline] -def public wto_navmesh_self_test(world : WtoWorldSnap const&) : bool - if world.capCount <= 0 || !world.teamSpawnValid[1] || !world.teamSpawnValid[2] - return false +def private wto_navmesh_self_test(world : WtoWorldSnap const&; var nm : WtoNavmeshBattle&) + if nm.selfTestPhase == 0 + if world.capCount <= 0 || !world.teamSpawnValid[1] || !world.teamSpawnValid[2] + return + for army in range(1, 3) + nm.selfTestTicket[army] = wto_navq_path_request(WTO_NAVQ_SELFTEST_SLOT0 + army - 1, WTO_NAVMESH_TIER_STANDARD, + WTO_NAVMESH_FILTER_TRACKED, world.teamSpawnCenter[army], world.caps[0].center) + nm.selfTestPhase = 1 + return + if nm.selfTestPhase != 1 + return var pts : float3[96] + var finished = 0 for army in range(1, 3) var count = 0 var lenM = 0.0 - let status = wto_navmesh_find_path(WTO_NAVMESH_TIER_STANDARD, WTO_NAVMESH_FILTER_TRACKED, - world.teamSpawnCenter[army], world.caps[0].center, pts, count, lenM) + var truncated = false + let status = wto_navq_path_result(WTO_NAVQ_SELFTEST_SLOT0 + army - 1, nm.selfTestTicket[army], pts, count, lenM, truncated) + if status == WTO_PATH_PENDING + continue + finished++ + if nm.selfTestTicket[army] == 0 + continue let last = count > 0 ? pts[count - 1] : float3(0.0, 0.0, 0.0) print("WTO_AI|NAVMESH_SELFTEST|army={army}|status={status}|corners={count}|lenM={lenM}|from={world.teamSpawnCenter[army]}|to={world.caps[0].center}|end={last}\n") - return true + nm.selfTestTicket[army] = 0 + if finished == 2 + nm.selfTestPhase = 2 -// Per world tick: decide the battle's navigation once, then prove a path per team once. +// Per world tick: decide the battle's navigation once, then pump searches and run the self test. [never_inline] -def public wto_navmesh_battle_tick(world : WtoWorldSnap const&; var state : int&; var selfTested : bool&) - if state == WTO_NAVMESH_UNDECIDED - state = wto_navmesh_load() - if state == WTO_NAVMESH_LOADED && !selfTested - selfTested = wto_navmesh_self_test(world) +def public wto_navmesh_battle_tick(world : WtoWorldSnap const&; now : float; var nm : WtoNavmeshBattle&) + if nm.state == WTO_NAVMESH_UNDECIDED + nm.state = wto_navmesh_load() + if nm.state != WTO_NAVMESH_LOADED + return + wto_navmesh_pump(now) + wto_navmesh_self_test(world, nm) // Battle end: release the pack and forget the decision. [never_inline] -def public wto_navmesh_battle_reset(var state : int&; var selfTested : bool&) - if state != WTO_NAVMESH_UNDECIDED && state != WTO_NAVMESH_OFF +def public wto_navmesh_battle_reset(var nm : WtoNavmeshBattle&) + if nm.state != WTO_NAVMESH_UNDECIDED && nm.state != WTO_NAVMESH_OFF wto_navmesh_unload() - state = WTO_NAVMESH_UNDECIDED - selfTested = false + nm = WtoNavmeshBattle() +// Engine statistics, printed only when they changed since the last print. [never_inline] -def public wto_navmesh_log_stats() +def public wto_navmesh_log_stats(var nm : WtoNavmeshBattle&) + if nm.state != WTO_NAVMESH_LOADED + return using() <| $(var blk : DataBlock) add(blk, "op", "get_stats") call_mission_action("wtoNav", blk) - let loaded = datablock_getInt(blk, "loaded", 0) let queries = datablock_getInt(blk, "queries", 0) + let meshQueries = datablock_getInt(blk, "meshQueries", 0) + if queries == nm.lastQueries && meshQueries == nm.lastMeshQueries + return + nm.lastQueries = queries + nm.lastMeshQueries = meshQueries let failures = datablock_getInt(blk, "failures", 0) let avgUs = datablock_getInt(blk, "avgUs", 0) let maxUs = datablock_getInt(blk, "maxUs", 0) - print("WTO_AI|NAVMESH_STATS|loaded={loaded}|queries={queries}|failures={failures}|avgUs={avgUs}|maxUs={maxUs}\n") + let maxFrames = datablock_getInt(blk, "maxFrames", 0) + let pumpMaxUs = datablock_getInt(blk, "pumpMaxUs", 0) + let pending = datablock_getInt(blk, "pending", 0) + let dynCount = datablock_getInt(blk, "dynamic", 0) + print("WTO_AI|NAVMESH_STATS|paths={queries}|failures={failures}|avgUs={avgUs}|maxUs={maxUs}|maxFrames={maxFrames}|pumpMaxUs={pumpMaxUs}|pending={pending}|dynamic={dynCount}|meshQueries={meshQueries}\n") diff --git a/game-ai/ground/wto_ai_navquery_common.das b/game-ai/ground/wto_ai_navquery_common.das new file mode 100644 index 0000000..ffac737 --- /dev/null +++ b/game-ai/ground/wto_ai_navquery_common.das @@ -0,0 +1,173 @@ +// Script side of the native navigation queries ("wtoNav" mission action, local_mp_nav.c): +// queued path searches, mesh probes, mesh raycasts, nearest walkable point and dynamic costs. +// Requests are strings; replies are ints (coordinates in centimetres) and strings. +options indenting = 2 +options no_global_heap = true +module wto_ai_navquery_common shared + +require ecs +require math +require DagorDataBlock +require DagorSystem +require Mission +require %appGame.wtoai.wto_ai_config_common + +let public WTO_PATH_FULL = 0 +let public WTO_PATH_PARTIAL = 1 +let public WTO_PATH_NO_START = 2 +let public WTO_PATH_NO_GOAL = 3 +let public WTO_PATH_FAILED = 4 +let public WTO_PATH_PENDING = 5 +let public WTO_PATH_STALE = 6 + +// Path slots of the native engine: 0..63 bots, 64..143 team lanes, 144..145 battle self test. +let public WTO_NAVQ_LANE_SLOT0 = 64 +let public WTO_NAVQ_SELFTEST_SLOT0 = 144 + +let public WTO_NAVQ_FLAG_CHOKEPOINT = 8 +let public WTO_NAVQ_FLAG_ROAD = 32 + +[safe_when_uninitialized] +struct public WtoNavProbeOut + onMesh : bool = false + nearest : float3 = float3(0.0, 0.0, 0.0) + offsetM : float = 0.0 + wallDistM : float = 99.0 + area : int = 0 + flags : int = 0 + +[never_inline] +def private wto_navq_status(answer : string) : int + if answer == "full" + return WTO_PATH_FULL + if answer == "partial" + return WTO_PATH_PARTIAL + if answer == "no_start" + return WTO_PATH_NO_START + if answer == "no_goal" + return WTO_PATH_NO_GOAL + if answer == "pending" + return WTO_PATH_PENDING + if answer == "stale" + return WTO_PATH_STALE + return WTO_PATH_FAILED + +[never_inline] +def private wto_navq_add_point(var blk : DataBlock&; prefix : string; p : float3) + add(blk, "{prefix}x", "{p.x}") + add(blk, "{prefix}y", "{p.y}") + add(blk, "{prefix}z", "{p.z}") + +[never_inline] +def private wto_navq_get_point(blk : DataBlock const&; kx, ky, kz : string) : float3 + let x = float(datablock_getInt(blk, kx, 0)) * 0.01 + let y = float(datablock_getInt(blk, ky, 0)) * 0.01 + let z = float(datablock_getInt(blk, kz, 0)) * 0.01 + return float3(x, y, z) + +// Queues a path search in native slot `slot`; returns its ticket (0 when refused). +[never_inline] +def public wto_navq_path_request(slot, tier, costFilter : int; start, goal : float3) : int + var ticket = 0 + using() <| $(var blk : DataBlock) + add(blk, "op", "path_request") + add(blk, "slot", "{slot}") + add(blk, "tier", "{tier}") + add(blk, "filter", "{costFilter}") + add(blk, "snap", "{WTO_AI_NAVMESH_SNAP_M}") + add(blk, "goalSnap", "{WTO_AI_NAVMESH_GOAL_SNAP_M}") + wto_navq_add_point(blk, "s", start) + wto_navq_add_point(blk, "g", goal) + call_mission_action("wtoNav", blk) + ticket = datablock_getInt(blk, "ticket", 0) + return ticket + +// Result of a ticket; corners are copied into `pts` only for full and partial paths. +[never_inline] +def public wto_navq_path_result(slot, ticket : int; var pts : float3[96]&; var count : int&; + var lenM : float&; var truncated : bool&) : int + var status = WTO_PATH_FAILED + using() <| $(var blk : DataBlock) + add(blk, "op", "path_result") + add(blk, "slot", "{slot}") + add(blk, "ticket", "{ticket}") + call_mission_action("wtoNav", blk) + status = wto_navq_status(datablock_getStr(blk, "status", "")) + if status != WTO_PATH_FULL && status != WTO_PATH_PARTIAL + return + count = clamp(datablock_getInt(blk, "count", 0), 0, 96) + lenM = float(datablock_getInt(blk, "lenCm", 0)) * 0.01 + truncated = datablock_getInt(blk, "truncated", 0) != 0 + for i in range(count) + pts[i] = wto_navq_get_point(blk, "p{i}x", "p{i}y", "p{i}z") + return status + +// Surface, flags and distance to the mesh edge under `pos`; false when the engine gave no answer. +[never_inline] +def public wto_navq_probe(tier, costFilter : int; pos : float3; wallRadiusM : float; + var probe : WtoNavProbeOut&) : bool + var answered = false + using() <| $(var blk : DataBlock) + add(blk, "op", "probe") + add(blk, "tier", "{tier}") + add(blk, "filter", "{costFilter}") + add(blk, "snap", "{WTO_AI_NAVMESH_SNAP_M}") + add(blk, "wallR", "{wallRadiusM}") + wto_navq_add_point(blk, "p", pos) + call_mission_action("wtoNav", blk) + let onMesh = datablock_getInt(blk, "onMesh", -1) + answered = onMesh >= 0 + probe.onMesh = onMesh == 1 + if !probe.onMesh + return + probe.offsetM = float(datablock_getInt(blk, "offCm", 0)) * 0.01 + probe.wallDistM = float(datablock_getInt(blk, "wallCm", 0)) * 0.01 + probe.area = datablock_getInt(blk, "area", 0) + probe.flags = datablock_getInt(blk, "flags", 0) + probe.nearest = wto_navq_get_point(blk, "nx", "ny", "nz") + return answered + +// 1 when the mesh lets a vehicle go straight from start to goal, 0 when an edge blocks it +// (`hitFrac` of the way), -1 when start is off the mesh or the engine gave no answer. +[never_inline] +def public wto_navq_raycast(tier, costFilter : int; start, goal : float3; var hitFrac : float&) : int + var clear = -1 + hitFrac = 0.0 + using() <| $(var blk : DataBlock) + add(blk, "op", "raycast") + add(blk, "tier", "{tier}") + add(blk, "filter", "{costFilter}") + add(blk, "snap", "{WTO_AI_NAVMESH_SNAP_M}") + wto_navq_add_point(blk, "s", start) + wto_navq_add_point(blk, "g", goal) + call_mission_action("wtoNav", blk) + clear = datablock_getInt(blk, "clear", -1) + hitFrac = float(datablock_getInt(blk, "hitPm", 0)) * 0.001 + return clear + +// Nearest walkable point within `radiusM` horizontally (any height). +[never_inline] +def public wto_navq_nearest(tier, costFilter : int; pos : float3; radiusM : float; var outPt : float3&) : bool + var found = false + using() <| $(var blk : DataBlock) + add(blk, "op", "nearest") + add(blk, "tier", "{tier}") + add(blk, "filter", "{costFilter}") + add(blk, "radius", "{radiusM}") + wto_navq_add_point(blk, "p", pos) + call_mission_action("wtoNav", blk) + found = datablock_getInt(blk, "found", 0) == 1 + if found + outPt = wto_navq_get_point(blk, "x", "y", "z") + return found + +// Makes later path searches avoid a circle (wreck, jam, rubble) until script time `untilAt`. +[never_inline] +def public wto_navq_add_dynamic(pos : float3; radiusM, costMul, untilAt : float) + using() <| $(var blk : DataBlock) + add(blk, "op", "dynamic") + wto_navq_add_point(blk, "p", pos) + add(blk, "radius", "{radiusM}") + add(blk, "mul", "{costMul}") + add(blk, "until", "{untilAt}") + call_mission_action("wtoNav", blk) diff --git a/game-ai/ground/wto_ai_polyline_common.das b/game-ai/ground/wto_ai_polyline_common.das new file mode 100644 index 0000000..e0e4428 --- /dev/null +++ b/game-ai/ground/wto_ai_polyline_common.das @@ -0,0 +1,97 @@ +// XZ geometry on path corner lists (float3[96] plus a count): length, sampling, tracking a +// position along the path and walking forward or back from it. +options indenting = 2 +options no_global_heap = true +module wto_ai_polyline_common shared + +require math +require %appGame.wtoai.wto_ai_math_common + +// Closest point of segment a-b to p in the XZ plane: `t` in 0..1, returns the squared distance. +[never_inline] +def public wto_poly_seg_closest(a, b, p : float3; var t : float&) : float + let abx = b.x - a.x + let abz = b.z - a.z + let lenSq = abx * abx + abz * abz + t = lenSq > 1.0e-6 ? clamp(((p.x - a.x) * abx + (p.z - a.z) * abz) / lenSq, 0.0, 1.0) : 0.0 + let cx = a.x + abx * t + let cz = a.z + abz * t + return wto_sq(p.x - cx) + wto_sq(p.z - cz) + +[never_inline] +def public wto_poly_length(pts : float3[96]; count : int) : float + var total = 0.0 + for i in range(1, count) + total += sqrt(wto_xz_dist_sq(pts[i - 1], pts[i])) + return total + +// Point `frac` (0..1) of the way along the path. +[never_inline] +def public wto_poly_sample(pts : float3[96]; count : int; frac : float) : float3 + if count <= 0 + return float3(0.0, 0.0, 0.0) + let target = wto_poly_length(pts, count) * clamp(frac, 0.0, 1.0) + var acc = 0.0 + for i in range(1, count) + let seg = sqrt(wto_xz_dist_sq(pts[i - 1], pts[i])) + if acc + seg >= target && seg > 0.01 + return lerp(pts[i - 1], pts[i], (target - acc) / seg) + acc += seg + return pts[count - 1] + +// Segment closest to `pos` among the few after `fromSeg` (never behind it); returns the XZ distance. +[never_inline] +def public wto_poly_track(pts : float3[96]; count : int; fromSeg : int; pos : float3; + var seg : int&; var t : float&) : float + seg = clamp(fromSeg, 0, max(0, count - 2)) + t = 0.0 + if count < 2 + return count == 1 ? sqrt(wto_xz_dist_sq(pos, pts[0])) : 0.0 + var bestSq = 1.0e12 + let last = min(count - 2, seg + 6) + for k in range(seg, last + 1) + var tk = 0.0 + let dSq = wto_poly_seg_closest(pts[k], pts[k + 1], pos, tk) + if dSq <= bestSq + bestSq = dSq + seg = k + t = tk + return sqrt(bestSq) + +// Point `dist` metres further along the path than (seg, t); the last corner when past the end. +[never_inline] +def public wto_poly_walk(pts : float3[96]; count : int; seg : int; t, dist : float) : float3 + if count <= 0 + return float3(0.0, 0.0, 0.0) + if count == 1 + return pts[0] + let s0 = clamp(seg, 0, count - 2) + var cur = lerp(pts[s0], pts[s0 + 1], t) + var left = dist + for k in range(s0 + 1, count) + let segLen = sqrt(wto_xz_dist_sq(cur, pts[k])) + if segLen >= left && segLen > 1.0e-3 + return lerp(cur, pts[k], left / segLen) + left -= segLen + cur = pts[k] + return pts[count - 1] + +// Point `dist` metres back along the path from (seg, t); the first corner when past the start. +[never_inline] +def public wto_poly_walk_back(pts : float3[96]; count : int; seg : int; t, dist : float) : float3 + if count <= 0 + return float3(0.0, 0.0, 0.0) + if count == 1 + return pts[0] + let s0 = clamp(seg, 0, count - 2) + var cur = lerp(pts[s0], pts[s0 + 1], t) + var left = dist + var k = s0 + while k >= 0 + let segLen = sqrt(wto_xz_dist_sq(cur, pts[k])) + if segLen >= left && segLen > 1.0e-3 + return lerp(cur, pts[k], left / segLen) + left -= segLen + cur = pts[k] + k-- + return pts[0] diff --git a/game-ai/ground/wto_ai_route_common.das b/game-ai/ground/wto_ai_route_common.das index 086eef2..9185276 100644 --- a/game-ai/ground/wto_ai_route_common.das +++ b/game-ai/ground/wto_ai_route_common.das @@ -1,169 +1,160 @@ -// Corridor route planner: wide-projected `nm1` NavMesh pathfinding (fixing off-road hill caps), -// 5-wing lateral approach relays, crest-safe cross-country shortcuts, and corridor-independent -// jam/cluster bypass waypoints. +// Corridor of every bot: which mesh tier and cost filter fit the vehicle, when to plan again +// (goal moved, off the corridor, timer, obstacle reported) and where the path comes from — queued +// native searches on the battle's pack, or the stock road mesh when the battle fell back. options indenting = 2 options no_global_heap = true module wto_ai_route_common shared require ecs require math -require pathfinder 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_terrain_common -require %appGame.wtoai.wto_ai_world_common -require %appGame.wtoai.wto_ai_crowd_common +require %appGame.wtoai.wto_ai_nav_types_common +require %appGame.wtoai.wto_ai_polyline_common +require %appGame.wtoai.wto_ai_navquery_common +require %appGame.wtoai.wto_ai_navmesh_common +require %appGame.wtoai.wto_ai_stockpath_common + +// Mesh tier by vehicle width as baked: narrow up to 2.9 m, standard up to 3.6 m, wide above. +// spec.halfWid carries the 0.18 m collision margin of wto_specs_load, removed here. +[never_inline] +def public wto_route_tier(spec : WtoVehicleSpec const&) : int + let width = max(0.0, spec.halfWid - 0.18) * 2.0 + if width <= 2.9 + return 0 + if width <= 3.6 + return 1 + return 2 [never_inline] -def private wto_project_nav_wide(navIdx : int; var pt : float3&) : bool - if project_to_nearest_navmesh_point_no_obstacles_ex(navIdx, pt, float3(28.0, 64.0, 28.0)) - return true - return project_to_nearest_navmesh_point_no_obstacles_ex(navIdx, pt, float3(165.0, 130.0, 165.0)) +def public wto_route_filter(spec : WtoVehicleSpec const&) : int + return spec.isTracked ? 0 : 1 +// Destination of this tick: the order's relay (flank or rally) while marching toward it. [never_inline] -def private wto_replan_corridor(now : float; myPos, goal : float3; var rt : WtoRouteState&) - rt.nextReplanAt = now + 2.8 - rt.corridorGoal = goal - rt.corridorLen = 0 - rt.corridorIdx = 0 - let navIdx = pathfinder_is_loaded_ex(1) ? 1 : (pathfinder_is_loaded_ex(0) ? 0 : -1) - if navIdx < 0 - rt.lastStartOk = false - rt.lastGoalOk = false - return - var sPt = myPos - var gPt = goal - rt.lastStartOk = wto_project_nav_wide(navIdx, sPt) - rt.lastGoalOk = wto_project_nav_wide(navIdx, gPt) - if !rt.lastStartOk || !rt.lastGoalOk - return - let maxKeep = WTO_MAX_PATH_PTS - 1 - find_path_ex(navIdx, sPt, gPt, float3(32.0, 48.0, 32.0), 9.0, 2.5, null) <| $(path : array#) - let total = length(path) - if total <= 0 - return - rt.corridor[0] = path[0] - rt.corridorLen = 1 - let minStepSq = total > maxKeep ? wto_sq(max(12.0, float(total) * 9.0 / float(maxKeep))) : 0.0 - for i in range(1, total) - if rt.corridorLen >= maxKeep - break - let prev = rt.corridor[rt.corridorLen - 1] - var isCorner = false - if i + 1 < total - let d0 = wto_xz_normalize(path[i] - prev, float3(1.0, 0.0, 0.0)) - let d1 = wto_xz_normalize(path[i + 1] - path[i], d0) - isCorner = dot(d0, d1) < 0.86 - if i == total - 1 || isCorner || wto_xz_dist_sq(prev, path[i]) >= minStepSq - rt.corridor[rt.corridorLen] = path[i] - rt.corridorLen++ - if rt.corridorLen < maxKeep && wto_xz_dist_sq(rt.corridor[rt.corridorLen - 1], path[total - 1]) > 9.0 - rt.corridor[rt.corridorLen] = path[total - 1] - rt.corridorLen++ - if rt.corridorLen > 0 && rt.corridorLen < WTO_MAX_PATH_PTS && wto_xz_dist_sq(rt.corridor[rt.corridorLen - 1], goal) > 64.0 - rt.corridor[rt.corridorLen] = goal - rt.corridorLen++ - -// Validate a crest-safe cross-country shortcut (<= 145m) with zero cliff drop-offs or jams. -[never_inline] -def private wto_try_shortcut(world : WtoWorldSnap const&; now : float; myPos, target : float3; - var slot : WtoBotSlot&) - assume rt = slot.route - rt.shortcutValid = false - rt.nextShortcutAt = now + 1.1 - let dist = sqrt(wto_xz_dist_sq(myPos, target)) - if dist < 22.0 || dist > 145.0 - return - let dir = wto_xz_normalize(target - myPos, float3(1.0, 0.0, 0.0)) - if wto_terrain_has_cliff_ahead(myPos, dir, min(dist, WTO_AI_TERRAIN_CREST_LOOKAHEAD_M + 8.0)) - return - let steps = clamp(int(dist / 7.5), 2, 20) - var prev = myPos - for s in range(1, steps + 1) - let d = (dist * float(s)) / float(steps) - let tx = myPos.x + dir.x * d - let tz = myPos.z + dir.z * d - var gy = prev.y - if !wto_terrain_drivable_y(prev, tx, tz, gy) - return - let samplePt = float3(tx, gy, tz) - if wto_world_jam_penalty(world, samplePt, now) > 4.0 || wto_crowd_point_penalty(world, slot.army, slot.eid, samplePt) > 18.0 - return - if wto_terrain_hard_ray(prev + float3(0.0, 1.3, 0.0), dir, 8.0) < 7.5 - return - prev = samplePt - rt.shortcutPos = target - rt.shortcutValid = true - -// Generate a lateral bypass waypoint around an obstacle/jam, even when no NavMesh corridor exists. -[never_inline] -def public wto_route_request_detour(world : WtoWorldSnap const&; now : float; - myPos, blockedDir : float3; var slot : WtoBotSlot&) - assume rt = slot.route - let fwd = wto_xz_normalize(blockedDir, float3(1.0, 0.0, 0.0)) - let lat = float3(-fwd.z, 0.0, fwd.x) - let pref = ((uint(slot.eid) + uint(rt.detourCount)) & 1u) == 0u ? 1.0 : -1.0 - var bestScore = -1.0e9 - var found = false - var bestPt = myPos - for k in range(4) - let side = (k % 2 == 0 ? pref : -pref) * (k < 2 ? 38.0 : 56.0) - let fwdStep = k < 2 ? 22.0 : 12.0 - var cand = wto_clamp_battle_xz(myPos + fwd * fwdStep + lat * side, world.battleCenter, world.battleRadius, 35.0) - if !wto_terrain_point_valid(slot.army, cand) - continue - let candDir = wto_xz_normalize(cand - myPos, lat) - if wto_terrain_has_cliff_ahead(myPos, candDir, 18.0) - continue - if wto_terrain_hard_ray(myPos + float3(0.0, 1.3, 0.0), candDir, 16.0) < 10.0 - continue - let score = -wto_world_jam_penalty(world, cand, now) - wto_crowd_point_penalty(world, slot.army, slot.eid, cand) - if score > bestScore - bestScore = score - bestPt = cand - found = true - if found - rt.detourPos = bestPt - rt.detourValid = true - rt.detourUntil = now + 11.0 - rt.detourCount++ - -[never_inline] -def public wto_route_select_waypoint(world : WtoWorldSnap const&; now : float; - myPos, finalGoal : float3; var slot : WtoBotSlot&) : float3 - assume rt = slot.route - if rt.detourValid - if now < rt.detourUntil && wto_xz_dist_sq(myPos, rt.detourPos) > 100.0 - return rt.detourPos - rt.detourValid = false - - if !rt.wingInit - rt.wingInit = true - rt.laneOffsetM = float(int((uint(slot.eid) / 5u) % 5u) - 2) * 4.0 +def public wto_route_active_goal(myPos, finalGoal : float3; slot : WtoBotSlot const&) : float3 let st = slot.tactics.state - let useRelay = (st == WTO_STATE_MARCH || st == WTO_STATE_PREAIM || st == WTO_STATE_RELOAD_ADVANCE) && slot.order.routeRelayValid - var activeGoal = finalGoal - if useRelay - let relay = slot.order.routeRelayPos - let distMeToRelaySq = wto_xz_dist_sq(myPos, relay) - let distMeToGoalSq = wto_xz_dist_sq(myPos, finalGoal) - let distRelayToGoalSq = wto_xz_dist_sq(relay, finalGoal) - if slot.order.rallyHold || (distMeToRelaySq > 1444.0 && distMeToGoalSq > distRelayToGoalSq) - activeGoal = relay + let marching = st == WTO_STATE_MARCH || st == WTO_STATE_PREAIM || st == WTO_STATE_RELOAD_ADVANCE + if !marching || !slot.order.routeRelayValid + return finalGoal + let relay = slot.order.routeRelayPos + let meToRelaySq = wto_xz_dist_sq(myPos, relay) + if slot.order.rallyHold || (meToRelaySq > 1444.0 && wto_xz_dist_sq(myPos, finalGoal) > wto_xz_dist_sq(relay, finalGoal)) + return relay + return finalGoal - if now >= rt.nextShortcutAt - wto_try_shortcut(world, now, myPos, activeGoal, slot) - if rt.shortcutValid && wto_xz_dist_sq(rt.shortcutPos, activeGoal) <= 144.0 - return activeGoal +[never_inline] +def private wto_route_accept(var rt : WtoRouteState&; count : int; goal : float3; truncated : bool; source : int) + rt.corridorLen = count + rt.segIdx = 0 + rt.segT = 0.0 + rt.offTrackM = 0.0 + rt.goal = goal + rt.truncated = truncated + rt.source = source + rt.goalUnreachable = false - if now >= rt.nextReplanAt || wto_xz_dist_sq(rt.corridorGoal, activeGoal) > 400.0 - wto_replan_corridor(now, myPos, activeGoal, rt) - while rt.corridorIdx < rt.corridorLen - 1 && wto_xz_dist_sq(myPos, rt.corridor[rt.corridorIdx]) <= 256.0 - rt.corridorIdx++ - if rt.corridorLen > 0 && rt.corridorIdx < rt.corridorLen - let wp = rt.corridor[rt.corridorIdx] - let toWp = wto_xz_normalize(wp - myPos, float3(1.0, 0.0, 0.0)) - let lat = float3(-toWp.z, 0.0, toWp.x) - return wp + lat * clamp(rt.laneOffsetM, -6.0, 6.0) - return activeGoal +// Straight two-point corridor (stock fallback without a road path, or back onto the mesh). +[never_inline] +def private wto_route_straight(var rt : WtoRouteState&; myPos, goal : float3; source : int) + rt.corridor[0] = myPos + rt.corridor[1] = goal + wto_route_accept(rt, 2, goal, source == WTO_ROUTE_SRC_RECOVER, source) + +[never_inline] +def private wto_route_request(navState, slotIdx : int; now : float; myPos, goal : float3; var slot : WtoBotSlot&) + assume rt = slot.route + rt.tier = wto_route_tier(slot.spec) + rt.filter = wto_route_filter(slot.spec) + rt.nextReplanAt = now + WTO_AI_PF_REPLAN_SEC + rt.replanRequested = false + rt.requests++ + if navState == WTO_NAVMESH_LOADED + rt.ticket = wto_navq_path_request(slotIdx, rt.tier, rt.filter, myPos, goal) + rt.pending = rt.ticket > 0 + rt.pendingGoal = goal + return + var count = 0 + if wto_stock_path(myPos, goal, rt.corridor, count) + wto_route_accept(rt, count, goal, false, WTO_ROUTE_SRC_STOCK) + else + wto_route_straight(rt, myPos, goal, WTO_ROUTE_SRC_STOCK) + +// The bot stands off the mesh: head for the nearest walkable point, then plan again from there. +[never_inline] +def private wto_route_recover(now : float; myPos : float3; var rt : WtoRouteState&) + var onMesh = myPos + rt.nextReplanAt = now + 1.0 + if wto_navq_nearest(rt.tier, rt.filter, myPos, WTO_AI_NAVMESH_GOAL_SNAP_M, onMesh) + wto_route_straight(rt, myPos, onMesh, WTO_ROUTE_SRC_RECOVER) + else + rt.corridorLen = 0 + +[never_inline] +def private wto_route_poll(slotIdx : int; now : float; myPos : float3; var slot : WtoBotSlot&) + assume rt = slot.route + var count = 0 + var lenM = 0.0 + var truncated = false + let status = wto_navq_path_result(slotIdx, rt.ticket, rt.corridor, count, lenM, truncated) + if status == WTO_PATH_PENDING + return + rt.pending = false + rt.lastStatus = status + if (status == WTO_PATH_FULL || status == WTO_PATH_PARTIAL) && count >= 1 + wto_route_accept(rt, count, rt.pendingGoal, truncated, WTO_ROUTE_SRC_MESH) + elif status == WTO_PATH_NO_START + wto_route_recover(now, myPos, rt) + elif status == WTO_PATH_NO_GOAL + rt.corridorLen = 0 + rt.goalUnreachable = true + rt.unreachableGoal = rt.pendingGoal + rt.noGoalCount++ + print("WTO_AI|ROUTE_NO_GOAL|eid={uint(slot.eid)}|tier={rt.tier}|pos={myPos}|goal={rt.pendingGoal}\n") + else + rt.nextReplanAt = now + 1.0 + +[never_inline] +def private wto_route_needs_plan(now : float; goal : float3; slot : WtoBotSlot const&) : bool + assume rt = slot.route + let moveSq = wto_sq(WTO_AI_PF_REPLAN_GOAL_MOVE_M) + if rt.goalUnreachable && wto_xz_dist_sq(rt.unreachableGoal, goal) <= moveSq + return now >= rt.nextReplanAt + return (rt.corridorLen == 0 || rt.replanRequested || now >= rt.nextReplanAt || + wto_xz_dist_sq(rt.goal, goal) > moveSq || rt.offTrackM > WTO_AI_PF_OFF_TRACK_REPLAN_M || + rt.tier != wto_route_tier(slot.spec) || rt.filter != wto_route_filter(slot.spec)) + +// Per nav tick: collect a finished search, then plan again when the corridor no longer fits. +[never_inline] +def public wto_route_update(navState, slotIdx : int; now : float; myPos, goal : float3; var slot : WtoBotSlot&) + assume rt = slot.route + if rt.pending + wto_route_poll(slotIdx, now, myPos, slot) + if rt.pending && wto_xz_dist_sq(rt.pendingGoal, goal) <= wto_sq(WTO_AI_PF_REPLAN_GOAL_MOVE_M) + return + if wto_route_needs_plan(now, goal, slot) + wto_route_request(navState, slotIdx, now, myPos, goal, slot) + +// Bots whose corridor ahead passes near a new obstacle (wreck, rubble) plan again next tick. +[never_inline] +def public wto_route_note_obstacle(pos : float3; radiusM : float; var bots : WtoBotSlot[64]&) + let reachSq = wto_sq(radiusM + 4.0) + for i in range(WTO_MAX_BOTS) + assume rt = bots[i].route + if !bots[i].used || rt.corridorLen < 2 + continue + let last = min(rt.corridorLen - 2, rt.segIdx + 8) + for k in range(rt.segIdx, last + 1) + var t = 0.0 + if wto_poly_seg_closest(rt.corridor[k], rt.corridor[k + 1], pos, t) <= reachSq + rt.replanRequested = true + break + +// A vehicle died at `pos`: later path searches route around its wreck, nearby bots plan again. +[never_inline] +def public wto_route_report_wreck(navState : int; now : float; pos : float3; var bots : WtoBotSlot[64]&) + if navState != WTO_NAVMESH_LOADED + return + wto_navq_add_dynamic(pos, WTO_AI_PF_WRECK_RADIUS_M, WTO_AI_PF_WRECK_COST_MUL, now + WTO_AI_PF_WRECK_TTL_SEC) + wto_route_note_obstacle(pos, WTO_AI_PF_WRECK_RADIUS_M, bots) \ No newline at end of file diff --git a/game-ai/ground/wto_ai_runtime.das b/game-ai/ground/wto_ai_runtime.das index 22f0cc4..c4912f6 100644 --- a/game-ai/ground/wto_ai_runtime.das +++ b/game-ai/ground/wto_ai_runtime.das @@ -24,13 +24,16 @@ require %appGame.wtoai.wto_ai_config_common require %appGame.wtoai.wto_ai_order_common require %appGame.wtoai.wto_ai_combat_types_common require %appGame.wtoai.wto_ai_types_common +require %appGame.wtoai.wto_ai_nav_types_common require %appGame.wtoai.wto_ai_specs_common require %appGame.wtoai.wto_ai_world_common require %appGame.wtoai.wto_ai_crowd_common require %appGame.wtoai.wto_ai_lanes_common +require %appGame.wtoai.wto_ai_lanes_build_common require %appGame.wtoai.wto_ai_commander_common require %appGame.wtoai.wto_ai_perceive_common require %appGame.wtoai.wto_ai_tactics_common +require %appGame.wtoai.wto_ai_route_common require %appGame.wtoai.wto_ai_nav_common require %appGame.wtoai.wto_ai_navmesh_common require %appGame.wtoai.wto_ai_drive_common @@ -48,8 +51,7 @@ var private g_cmd_dirty : bool = true var private g_last_zone_ver : int = -1 var private g_fire_budget : int = 0 var private g_next_diag_at : float = 0.0 -var private g_navmesh_state : int = 0 -var private g_navmesh_tested : bool = false +var private @safe_when_uninitialized g_navmesh : WtoNavmeshBattle def private wto_any_layer_active() : bool return WTO_AI_ENABLED && (WTO_AI_LAYER_MACRO || WTO_AI_LAYER_TACTICS || WTO_AI_LAYER_NAVIGATION || WTO_AI_LAYER_FIRE_CONTROL) @@ -69,7 +71,7 @@ def private wto_reset_runtime() g_cmd_dirty = true g_last_zone_ver = -1 g_next_diag_at = 0.0 - wto_navmesh_battle_reset(g_navmesh_state, g_navmesh_tested) + 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) @@ -84,6 +86,20 @@ def private wto_find_slot(eid : EntityId) : int 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) @@ -124,6 +140,12 @@ def wto_ai_mission_reset_es(evt : Event) wto_reset_runtime() wto_drive_announce_script_ready() +// Battle loading: read the navigation pack in the background before the first world tick. +[es(tag=server, on_event=EventEcsMissionLoaded)] +def wto_ai_mission_loaded_es(evt : Event) + if wto_any_layer_active() && WTO_AI_LAYER_NAVIGATION + wto_navmesh_prefetch() + [es(tag=server)] def wto_ai_zone_captured_es(evt : EventZoneCaptured) if !wto_any_layer_active() @@ -136,32 +158,14 @@ def wto_ai_zone_captured_es(evt : EventZoneCaptured) def wto_ai_unit_dead_es(evt : Event; eid : EntityId; unit__ref : UnitRef) let u = unit__ref.unit if u != null && as_gm(u) != null && (int(u.army) == 1 || int(u.army) == 2) - wto_world_record_death(g_world, eid, int(u.army), u.pos, float(get_app().usefulTotalTime)) - 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 + 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) [es(tag=server, on_disappear, on_event=EventUnitRespawn)] def wto_ai_unit_cleanup_es(evt : Event; 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 + wto_forget_unit(eid) [es(tag=server)] def wto_ai_unit_damage_es(evt : EventUnitDamage; eid : EntityId; unit__ref : UnitRef) @@ -212,7 +216,8 @@ def wto_ai_world_tick_es(act : UpdateStageInfoAct) print("WTO_AI|RUNTIME_READY\n") wto_world_refresh(now, g_world) if WTO_AI_LAYER_NAVIGATION - wto_navmesh_battle_tick(g_world, g_navmesh_state, g_navmesh_tested) + wto_navmesh_battle_tick(g_world, now, g_navmesh) + g_lanes.navState = g_navmesh.state wto_crowd_update_all(g_world, g_bots, g_crowd) let zoneChanged = g_world.zoneVersion != g_last_zone_ver if zoneChanged @@ -226,25 +231,11 @@ def wto_ai_world_tick_es(act : UpdateStageInfoAct) wto_commander_update_all(g_world, now, zoneChanged, g_lanes, g_bots) elif WTO_AI_LAYER_MACRO && now >= g_next_rally_at g_next_rally_at = now + 1.0 - wto_lanes_update_rallies(g_world, 1, now, g_lanes, g_bots) - wto_lanes_update_rallies(g_world, 2, now, g_lanes, g_bots) - for i in range(WTO_MAX_BOTS) - assume b = g_bots[i] - if b.used && b.order.valid && b.order.rallyHold && b.order.capIndex >= 0 - let sk = wto_lanes_sub_key(b.army, b.order.capIndex, b.order.laneId) - if g_lanes.rallyReleased[sk] - b.order.rallyHold = false - if b.order.role == WTO_CMD_FLANK && b.order.laneId > 0 - let ck = wto_lanes_cap_key(b.army, b.order.capIndex) - b.order.routeRelayValid = g_lanes.flankValid[ck * 2 + b.order.laneId - 1] - b.order.routeRelayPos = g_lanes.flankRelay[ck * 2 + b.order.laneId - 1] - else - b.order.routeRelayValid = false + wto_lanes_tick_rallies(g_world, now, g_lanes, g_bots) if WTO_AI_DIAG_TELEMETRY && now >= g_next_diag_at g_next_diag_at = now + WTO_AI_DIAG_INTERVAL_SEC wto_diag_log_telemetry(g_world, now, g_bots, g_crowd) - if g_navmesh_state == WTO_NAVMESH_LOADED - wto_navmesh_log_stats() + wto_navmesh_log_stats(g_navmesh) [es(tag=server, no_order)] def wto_ai_pipeline_es(act : UpdateStageInfoAct; eid : EntityId; var unit__ref : UnitRef&; @@ -273,15 +264,15 @@ def wto_ai_pipeline_es(act : UpdateStageInfoAct; eid : EntityId; var unit__ref : wto_perceive_update(g_world, now, WTO_AI_TACTICS_TICK_SEC, unit.pos, unit.unitTm[0], 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) // A failed pack with navEngine.allowFallback off leaves every bot standing for the battle. - if now >= slot.nextNavAt && g_navmesh_state != WTO_NAVMESH_FAILED + if now >= slot.nextNavAt && g_navmesh.state != WTO_NAVMESH_FAILED slot.nextNavAt = now + WTO_AI_NAV_TICK_SEC - wto_nav_update(g_world, now, unit.pos, unit.unitTm[0], slot) + wto_nav_update(g_world, g_navmesh.state, idx, now, unit.pos, unit.unitTm[0], slot) wto_fire_update(g_world, unit, now, act.dt, slot, g_fire_budget) [es(tag=server, after=wto_ai_pipeline_es)] def wto_ai_phys_tick_es(act : UpdateStageInfoAct; eid : EntityId; var unit__ref : UnitRef&; unit__missionName : string; var vehicle_net_phys : VehiclePhysActor&) - if !wto_any_layer_active() || !WTO_AI_LAYER_NAVIGATION || WTO_AI_NAV_DRIVE_MODE != "vehicle_phys" || g_navmesh_state == WTO_NAVMESH_FAILED + if !wto_any_layer_active() || !WTO_AI_LAYER_NAVIGATION || WTO_AI_NAV_DRIVE_MODE != "vehicle_phys" || g_navmesh.state == WTO_NAVMESH_FAILED return var unit = unit__ref.unit if unit == null || !unit.isAlive || unit.isDelayed || unit.isHumanPlayer || vehicle_net_phys.physEdit == null diff --git a/game-ai/ground/wto_ai_stockpath_common.das b/game-ai/ground/wto_ai_stockpath_common.das new file mode 100644 index 0000000..146805c --- /dev/null +++ b/game-ai/ground/wto_ai_stockpath_common.das @@ -0,0 +1,53 @@ +// Path source for battles without a baked navigation pack (navEngine fallback): the level's stock +// road navmesh, thinned to direction changes. Used only when the battle decided on the fallback. +options indenting = 2 +options no_global_heap = true +module wto_ai_stockpath_common shared + +require ecs +require math +require pathfinder +require %appGame.wtoai.wto_ai_config_common +require %appGame.wtoai.wto_ai_math_common + +[never_inline] +def private wto_stock_project(navIdx : int; var pt : float3&) : bool + if project_to_nearest_navmesh_point_no_obstacles_ex(navIdx, pt, float3(WTO_AI_NAVMESH_SNAP_M, 64.0, WTO_AI_NAVMESH_SNAP_M)) + return true + return project_to_nearest_navmesh_point_no_obstacles_ex(navIdx, pt, float3(WTO_AI_NAVMESH_GOAL_SNAP_M, 130.0, WTO_AI_NAVMESH_GOAL_SNAP_M)) + +// Stock road path from start to goal as at most 96 corners; false when the stock mesh has none. +[never_inline] +def public wto_stock_path(start, goal : float3; var pts : float3[96]&; var count : int&) : bool + count = 0 + let navIdx = pathfinder_is_loaded_ex(1) ? 1 : (pathfinder_is_loaded_ex(0) ? 0 : -1) + if navIdx < 0 + return false + var sPt = start + var gPt = goal + if !wto_stock_project(navIdx, sPt) || !wto_stock_project(navIdx, gPt) + return false + let maxKeep = 95 + find_path_ex(navIdx, sPt, gPt, float3(32.0, 48.0, 32.0), 9.0, 2.5, null) <| $(path : array#) + let total = length(path) + if total <= 0 + return + pts[0] = path[0] + count = 1 + let minStepSq = total > maxKeep ? wto_sq(max(12.0, float(total) * 9.0 / float(maxKeep))) : 0.0 + for i in range(1, total) + if count >= maxKeep + break + let prev = pts[count - 1] + var isCorner = false + if i + 1 < total + let d0 = wto_xz_normalize(path[i] - prev, float3(1.0, 0.0, 0.0)) + let d1 = wto_xz_normalize(path[i + 1] - path[i], d0) + isCorner = dot(d0, d1) < 0.86 + if i == total - 1 || isCorner || wto_xz_dist_sq(prev, path[i]) >= minStepSq + pts[count] = path[i] + count++ + if count < maxKeep && wto_xz_dist_sq(pts[count - 1], path[total - 1]) > 9.0 + pts[count] = path[total - 1] + count++ + return count >= 2 diff --git a/game-ai/ground/wto_ai_tactics_actions_common.das b/game-ai/ground/wto_ai_tactics_actions_common.das index 39f772f..14c4f52 100644 --- a/game-ai/ground/wto_ai_tactics_actions_common.das +++ b/game-ai/ground/wto_ai_tactics_actions_common.das @@ -12,6 +12,7 @@ require %appGame.wtoai.wto_ai_math_common require %appGame.wtoai.wto_ai_order_common require %appGame.wtoai.wto_ai_combat_types_common require %appGame.wtoai.wto_ai_types_common +require %appGame.wtoai.wto_ai_nav_types_common require %appGame.wtoai.wto_ai_terrain_common require %appGame.wtoai.wto_ai_cover_common diff --git a/game-ai/ground/wto_ai_tactics_common.das b/game-ai/ground/wto_ai_tactics_common.das index 29faf95..6e684c0 100644 --- a/game-ai/ground/wto_ai_tactics_common.das +++ b/game-ai/ground/wto_ai_tactics_common.das @@ -13,6 +13,7 @@ require %appGame.wtoai.wto_ai_order_common require %appGame.wtoai.wto_ai_combat_types_common require %appGame.wtoai.wto_ai_fire_speed_common require %appGame.wtoai.wto_ai_types_common +require %appGame.wtoai.wto_ai_nav_types_common require %appGame.wtoai.wto_ai_terrain_common require %appGame.wtoai.wto_ai_crowd_common require %appGame.wtoai.wto_ai_cover_common diff --git a/game-ai/ground/wto_ai_types_common.das b/game-ai/ground/wto_ai_types_common.das index 89e117d..d388ff8 100644 --- a/game-ai/ground/wto_ai_types_common.das +++ b/game-ai/ground/wto_ai_types_common.das @@ -6,12 +6,12 @@ module wto_ai_types_common shared require ecs require %appGame.wtoai.wto_ai_order_common require %appGame.wtoai.wto_ai_combat_types_common +require %appGame.wtoai.wto_ai_nav_types_common let public WTO_MAX_BOTS = 64 let public WTO_MAX_UNITS = 96 let public WTO_MAX_WRECKS = 64 let public WTO_MAX_CAPS = 8 -let public WTO_MAX_PATH_PTS = 32 let public WTO_MAX_DEATHS = 32 let public WTO_MAX_JAMS = 24 let public WTO_MAX_RADIO = 24 @@ -200,42 +200,6 @@ struct public WtoTacticsState disperseGoal : float3 = float3(0.0, 0.0, 0.0) disperseUntil : float = -100.0 -[safe_when_uninitialized] -struct public WtoRouteState - corridor : float3[32] - corridorLen : int = 0 - corridorIdx : int = 0 - corridorGoal : float3 = float3(0.0, 0.0, 0.0) - nextReplanAt : float = -100.0 - nextShortcutAt : float = -100.0 - wingInit : bool = false - wingSign : int = 0 - laneOffsetM : float = 0.0 - wingCapIdx : int = -2 - wingRelayPos : float3 = float3(0.0, 0.0, 0.0) - wingRelayValid : bool = false - shortcutPos : float3 = float3(0.0, 0.0, 0.0) - shortcutValid : bool = false - detourPos : float3 = float3(0.0, 0.0, 0.0) - detourValid : bool = false - detourUntil : float = -100.0 - detourCount : int = 0 - lastStartOk : bool = false - lastGoalOk : bool = false - -[safe_when_uninitialized] -struct public WtoNavState - steerDir : float3 = float3(1.0, 0.0, 0.0) - frontClearM : float = 30.0 - rearClearM : float = 16.0 - cliffAhead : bool = false - stuckOrigin : float3 = float3(0.0, 0.0, 0.0) - stuckCheckAt : float = -100.0 - reverseAnchor : float3 = float3(0.0, 0.0, 0.0) - reverseUntil : float = -100.0 - reverseCount : int = 0 - ridgeWithdrawEvents : int = 0 - [safe_when_uninitialized] struct public WtoDriveCmd valid : bool = false diff --git a/game-ai/ground/wto_ai_unstick_common.das b/game-ai/ground/wto_ai_unstick_common.das new file mode 100644 index 0000000..b9c4249 --- /dev/null +++ b/game-ai/ground/wto_ai_unstick_common.das @@ -0,0 +1,115 @@ +// Deterministic three-level unstick. A bot that wants to move but makes no progress within +// stuckWindowSec backs up along the corridor it came by (level 1). Stuck again soon after, it also +// marks the spot ahead as a jam that path searches avoid and plans again (level 2). After +// unstickMaxAttempts without real progress it logs the place, marks it harder and gives its order +// back to the commander (level 3). +options indenting = 2 +options no_global_heap = true +module wto_ai_unstick_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_types_common +require %appGame.wtoai.wto_ai_nav_types_common +require %appGame.wtoai.wto_ai_world_common +require %appGame.wtoai.wto_ai_polyline_common +require %appGame.wtoai.wto_ai_navquery_common +require %appGame.wtoai.wto_ai_navmesh_common +require %appGame.wtoai.wto_ai_follow_common + +// Where to back up to: unstickReverseM back along the corridor (or straight back), cut short +// where the mesh ends; false when there is no room behind. +[never_inline] +def private wto_unstick_reverse_target(navState : int; myPos, hullFwd : float3; slot : WtoBotSlot const&; + var target : float3&) : bool + if slot.nav.rearClearM < 2.5 + return false + assume rt = slot.route + let straightBack = myPos - hullFwd * WTO_AI_PF_UNSTICK_REV_M + target = rt.corridorLen >= 2 ? wto_poly_walk_back(rt.corridor, rt.corridorLen, rt.segIdx, rt.segT, WTO_AI_PF_UNSTICK_REV_M) : straightBack + if wto_xz_dist_sq(myPos, target) < 4.0 + target = straightBack + if navState != WTO_NAVMESH_LOADED || rt.tier < 0 + return true + var frac = 0.0 + if wto_navq_raycast(rt.tier, rt.filter, myPos, target, frac) != 0 + return true + if frac * sqrt(wto_xz_dist_sq(myPos, target)) < 2.0 + return false + target = lerp(myPos, target, frac * 0.9) + return true + +[never_inline] +def private wto_unstick_start_reverse(navState : int; now : float; myPos, hullFwd : float3; var slot : WtoBotSlot&) + var target = myPos + if !wto_unstick_reverse_target(navState, myPos, hullFwd, slot, target) + return + slot.nav.reverseTarget = target + slot.nav.reverseUntil = now + WTO_AI_PF_UNSTICK_REV_SEC + slot.nav.reverseCount++ + +[never_inline] +def private wto_unstick_mark(var world : WtoWorldSnap&; navState : int; now : float; pos : float3; radiusM, costMul : float) + wto_world_record_jam(world, pos, now) + if navState == WTO_NAVMESH_LOADED + wto_navq_add_dynamic(pos, radiusM, costMul, now + WTO_AI_PF_JAM_TTL_SEC) + +[never_inline] +def private wto_unstick_give_up(var world : WtoWorldSnap&; navState : int; now : float; myPos, ahead : float3; + var slot : WtoBotSlot&) + print("WTO_AI|NAV_UNREACHABLE|eid={uint(slot.eid)}|tier={slot.route.tier}|pos={myPos}|goal={slot.route.goal}|attempts={slot.nav.unstickAttempts}\n") + wto_unstick_mark(world, navState, now, ahead, WTO_AI_PF_JAM_RADIUS_M * 1.5, WTO_AI_PF_JAM_COST_MUL * 2.0) + slot.order.expiresAt = now + slot.nav.unreachableEvents++ + slot.nav.unstickAttempts = 0 + slot.nav.unstickLevel = 0 + +// Backing up after being stuck; true while the manoeuvre runs (the drive command is set). +[never_inline] +def public wto_unstick_reversing(now : float; myPos : float3; var slot : WtoBotSlot&) : bool + assume nav = slot.nav + if now >= nav.reverseUntil + return false + if wto_xz_dist_sq(myPos, nav.reverseTarget) < 1.0 || nav.rearClearM < 2.1 + nav.reverseUntil = -100.0 + nav.stuckCheckAt = -100.0 + return false + let dir = wto_xz_normalize(nav.reverseTarget - myPos, -nav.steerDir) + nav.steerDir = dir + wto_drive_cmd_set(slot.driveCmd, WTO_DRIVE_REVERSE, nav.reverseTarget, dir, max(2.0, slot.spec.vMaxRev), nav.frontClearM, nav.rearClearM) + return true + +// Per nav tick while following: detects no progress and escalates through the three levels. +[never_inline] +def public wto_unstick_watch(var world : WtoWorldSnap&; navState : int; now : float; myPos, hullFwd, ahead : float3; + movingIntent : bool; var slot : WtoBotSlot&) + assume nav = slot.nav + if !movingIntent || nav.stuckCheckAt < -50.0 + nav.stuckOrigin = myPos + nav.stuckCheckAt = now + WTO_AI_PF_STUCK_WINDOW_SEC + return + if now < nav.stuckCheckAt + return + let moved = sqrt(wto_xz_dist_sq(myPos, nav.stuckOrigin)) + nav.stuckOrigin = myPos + nav.stuckCheckAt = now + WTO_AI_PF_STUCK_WINDOW_SEC + if moved >= WTO_AI_PF_STUCK_MIN_PROGRESS_M + if wto_xz_dist_sq(myPos, nav.unstickAnchor) > 144.0 + nav.unstickAttempts = 0 + nav.unstickLevel = 0 + return + nav.unstickAttempts++ + nav.unstickEvents++ + nav.unstickLevel = (now - nav.lastUnstickAt) <= WTO_AI_PF_UNSTICK_REPEAT_SEC ? min(nav.unstickLevel + 1, 2) : 1 + nav.lastUnstickAt = now + nav.unstickAnchor = myPos + print("WTO_AI|NAV_STUCK|eid={uint(slot.eid)}|level={nav.unstickLevel}|attempt={nav.unstickAttempts}|pos={myPos}\n") + if nav.unstickAttempts >= WTO_AI_PF_UNSTICK_MAX_ATTEMPTS + wto_unstick_give_up(world, navState, now, myPos, ahead, slot) + slot.route.replanRequested = true + elif nav.unstickLevel >= 2 + wto_unstick_mark(world, navState, now, ahead, WTO_AI_PF_JAM_RADIUS_M, WTO_AI_PF_JAM_COST_MUL) + slot.route.replanRequested = true + wto_unstick_start_reverse(navState, now, myPos, hullFwd, slot) diff --git a/native/wto-nav/wto_nav_internal.h b/native/wto-nav/wto_nav_internal.h new file mode 100644 index 0000000..0cdae48 --- /dev/null +++ b/native/wto-nav/wto_nav_internal.h @@ -0,0 +1,81 @@ +/* + * State shared by the navigation engine's translation units (wto_nav_runtime.cpp: packs and + * loading; wto_nav_paths.cpp: queued sliced path searches; wto_nav_queries.cpp: point queries and + * dynamic costs). Everything below is guarded by g_lock unless noted. + */ +#pragma once + +#include "wto_nav_runtime.h" +#include "wto_nav_format.h" + +#include "DetourCommon.h" +#include "DetourNavMesh.h" +#include "DetourNavMeshQuery.h" + +#include + +#include + +#ifndef DT_VIRTUAL_QUERYFILTER +#error "Detour must be built with DT_VIRTUAL_QUERYFILTER for the chokepoint and dynamic cost filter" +#endif + +namespace wtonav { + +constexpr int kPathSearchNodes = 32768; /* Node pool of the sliced path search, per tier */ +constexpr int kPointSearchNodes = 2048; /* Node pool of point queries (wall distance) */ +constexpr int kMaxPathPolys = 4096; + +/* A circle that multiplies the cost of every edge whose midpoint lies inside it. */ +struct DynamicCost { + float pos[3]; + float radius; + float mul; + float until; +}; + +extern DynamicCost g_dynamic[WTO_NAV_RT_MAX_DYNAMIC]; +extern uint32_t g_dynamic_count; + +/* Area costs per WtoPolyArea, times the chokepoint multiplier and live dynamic costs. */ +class QueryFilter : public dtQueryFilter { +public: + float chokepointMul = 1.0f; + + float getCost(const float *pa, const float *pb, + const dtPolyRef, const dtMeshTile *, const dtPoly *, + const dtPolyRef, const dtMeshTile *, const dtPoly *curPoly, + const dtPolyRef, const dtMeshTile *, const dtPoly *) const override; +}; + +struct Pack { + float heightSpan = 0.0f; /* Vertical extent of the mesh bounds */ + dtNavMesh *meshes[WTO_NAV_TIER_COUNT] = {}; + dtNavMeshQuery *pathQueries[WTO_NAV_TIER_COUNT] = {}; /* Owned by the sliced path search */ + dtNavMeshQuery *pointQueries[WTO_NAV_TIER_COUNT] = {}; /* Snapping, raycasts, wall distance */ + std::vector covers; + std::vector tactical; +}; + +extern SRWLOCK g_lock; +extern Pack *g_pack; +extern QueryFilter g_filters[WTO_NAV_RT_FILTER_COUNT]; +extern WtoNavStats g_stats; + +double now_micros(); + +/* + * Nearest polygon within `snap` metres; mission points (spawn and capture zone centres) carry + * heights that are not on the ground, so a miss is retried over the mesh's whole height range, + * still within `snap` horizontally. + */ +bool snap_to_mesh(const dtNavMeshQuery *query, const dtQueryFilter &filter, float snap, float height_span, + const float point[3], dtPolyRef *ref, float nearest[3]); + +/* Called with g_lock held whenever the loaded pack changes. */ +void paths_reset_locked(); +void dynamic_reset_locked(); +void dynamic_expire_locked(float now); +uint32_t paths_pending_locked(); + +} // namespace wtonav diff --git a/native/wto-nav/wto_nav_paths.cpp b/native/wto-nav/wto_nav_paths.cpp new file mode 100644 index 0000000..4c76d3a --- /dev/null +++ b/native/wto-nav/wto_nav_paths.cpp @@ -0,0 +1,246 @@ +/* + * Queued path searches (wto_nav_runtime.h): every slot holds at most one request. Requests are + * searched one at a time, oldest first, with Detour's sliced search; wto_nav_pump advances the + * search in small iteration chunks until its per-frame time budget is spent, so one long path + * across a 4 km map spreads over several frames instead of stalling one. + */ +#include "wto_nav_internal.h" + +#include + +namespace wtonav { +namespace { + +constexpr int kIterChunk = 64; /* Detour node expansions between budget checks */ + +enum class JobState : uint8_t { Empty, Queued, Running, Done }; + +struct PathJob { + uint32_t ticket; + JobState state; + uint32_t tier; + uint32_t filter; + dtPolyRef startRef; + dtPolyRef goalRef; + float startPt[3]; + float goalPt[3]; + double searchMicros; + uint32_t frames; + uint32_t lastPump; + WtoNavPathResult result; + float corners[WTO_NAV_RT_MAX_CORNERS * 3]; +}; + +PathJob g_jobs[WTO_NAV_RT_PATH_SLOTS]; +uint32_t g_next_ticket = 1; +uint32_t g_pump_serial; +int g_active = -1; /* Slot whose search owns its tier's path query */ +dtPolyRef g_poly_path[kMaxPathPolys]; + +void finish(PathJob &job, WtoNavPathStatus status) +{ + job.state = JobState::Done; + job.result.status = status; + if (g_pack == nullptr) + return; + g_stats.queries++; + if (status != WTO_NAV_PATH_FULL) + g_stats.failures++; + g_stats.totalMicros += job.searchMicros; + if (job.searchMicros > g_stats.maxMicros) + g_stats.maxMicros = job.searchMicros; + if (job.frames > g_stats.maxFrames) + g_stats.maxFrames = job.frames; +} + +/* Snaps start and goal; on success the job is queued, otherwise it is finished. */ +void prepare(PathJob &job, const WtoNavPathRequest &req) +{ + if (g_pack == nullptr || req.tier >= WTO_NAV_TIER_COUNT || req.filter >= WTO_NAV_RT_FILTER_COUNT || !(req.snapM > 0.0f)) { + finish(job, WTO_NAV_PATH_FAILED); + return; + } + const dtNavMeshQuery *query = g_pack->pointQueries[req.tier]; + const QueryFilter &filter = g_filters[req.filter]; + if (!snap_to_mesh(query, filter, req.snapM, g_pack->heightSpan, req.start, &job.startRef, job.startPt)) { + finish(job, WTO_NAV_PATH_NO_START); + return; + } + if (!snap_to_mesh(query, filter, req.snapM, g_pack->heightSpan, req.goal, &job.goalRef, job.goalPt)) { + if (!(req.goalSnapM > req.snapM) || + !snap_to_mesh(query, filter, req.goalSnapM, g_pack->heightSpan, req.goal, &job.goalRef, job.goalPt)) { + finish(job, WTO_NAV_PATH_NO_GOAL); + return; + } + job.result.goalMoved = 1; + } + job.state = JobState::Queued; +} + +int next_queued() +{ + int best = -1; + for (int i = 0; i < WTO_NAV_RT_PATH_SLOTS; i++) { + if (g_jobs[i].state == JobState::Queued && (best < 0 || g_jobs[i].ticket < g_jobs[best].ticket)) + best = i; + } + return best; +} + +/* Turns a finished polygon corridor into straight-path corners. */ +void finalize(PathJob &job, dtNavMeshQuery *query) +{ + int count = 0; + dtStatus status = query->finalizeSlicedFindPath(g_poly_path, &count, kMaxPathPolys); + if (dtStatusFailed(status) || count == 0) { + finish(job, WTO_NAV_PATH_FAILED); + return; + } + const bool partial = dtStatusDetail(status, DT_PARTIAL_RESULT) || g_poly_path[count - 1] != job.goalRef; + float goal[3]; + dtVcopy(goal, job.goalPt); + if (partial && dtStatusFailed(query->closestPointOnPoly(g_poly_path[count - 1], job.goalPt, goal, nullptr))) { + finish(job, WTO_NAV_PATH_FAILED); + return; + } + int corners = 0; + status = query->findStraightPath(job.startPt, goal, g_poly_path, count, job.corners, nullptr, nullptr, + &corners, WTO_NAV_RT_MAX_CORNERS, 0); + if (dtStatusFailed(status) || corners == 0) { + finish(job, WTO_NAV_PATH_FAILED); + return; + } + float length = 0.0f; + for (int i = 1; i < corners; i++) + length += dtVdist(job.corners + (i - 1) * 3, job.corners + i * 3); + job.result.count = corners; + job.result.lengthM = length; + job.result.truncated = dtStatusDetail(status, DT_BUFFER_TOO_SMALL) ? 1 : 0; + finish(job, partial ? WTO_NAV_PATH_PARTIAL : WTO_NAV_PATH_FULL); +} + +/* Starts the oldest queued search; false when nothing is left to search. */ +bool start_next() +{ + for (;;) { + const int slot = next_queued(); + if (slot < 0) + return false; + PathJob &job = g_jobs[slot]; + dtNavMeshQuery *query = g_pack->pathQueries[job.tier]; + if (dtStatusFailed(query->initSlicedFindPath(job.startRef, job.goalRef, job.startPt, job.goalPt, + &g_filters[job.filter], 0))) { + finish(job, WTO_NAV_PATH_FAILED); + continue; + } + job.state = JobState::Running; + g_active = slot; + return true; + } +} + +} // namespace + +void paths_reset_locked() +{ + memset(g_jobs, 0, sizeof(g_jobs)); + g_active = -1; +} + +uint32_t paths_pending_locked() +{ + uint32_t pending = 0; + for (const PathJob &job : g_jobs) + pending += job.state == JobState::Queued || job.state == JobState::Running; + return pending; +} + +} // namespace wtonav + +using namespace wtonav; + +extern "C" uint32_t wto_nav_path_request(uint32_t slot, const WtoNavPathRequest *request) +{ + if (slot >= WTO_NAV_RT_PATH_SLOTS || request == nullptr) + return 0; + AcquireSRWLockExclusive(&g_lock); + PathJob &job = g_jobs[slot]; + if (g_active == (int)slot) + g_active = -1; /* The next initSlicedFindPath discards the abandoned search */ + memset(&job, 0, sizeof(job)); + if (g_next_ticket == 0) + g_next_ticket = 1; + job.ticket = g_next_ticket++; + job.tier = request->tier; + job.filter = request->filter; + prepare(job, *request); + const uint32_t ticket = job.ticket; + ReleaseSRWLockExclusive(&g_lock); + return ticket; +} + +extern "C" void wto_nav_path_result(uint32_t slot, uint32_t ticket, float *points, int max_points, WtoNavPathResult *result) +{ + memset(result, 0, sizeof(*result)); + result->status = WTO_NAV_PATH_STALE; + if (slot >= WTO_NAV_RT_PATH_SLOTS || ticket == 0) + return; + AcquireSRWLockShared(&g_lock); + const PathJob &job = g_jobs[slot]; + if (job.ticket == ticket) { + if (job.state == JobState::Queued || job.state == JobState::Running) { + result->status = WTO_NAV_PATH_PENDING; + } else if (job.state == JobState::Done) { + *result = job.result; + if (result->count > max_points) + result->count = max_points < 0 ? 0 : max_points; + if (points != nullptr && result->count > 0) + memcpy(points, job.corners, sizeof(float) * 3 * (size_t)result->count); + } + } + ReleaseSRWLockShared(&g_lock); +} + +extern "C" void wto_nav_pump(double budget_us, float now) +{ + AcquireSRWLockExclusive(&g_lock); + const double began = now_micros(); + dynamic_expire_locked(now); + g_pump_serial++; + if (g_pack == nullptr) { + for (PathJob &job : g_jobs) { + if (job.state == JobState::Queued || job.state == JobState::Running) + finish(job, WTO_NAV_PATH_FAILED); + } + g_active = -1; + ReleaseSRWLockExclusive(&g_lock); + return; + } + for (;;) { + if (g_active < 0 && !start_next()) + break; + PathJob &job = g_jobs[g_active]; + dtNavMeshQuery *query = g_pack->pathQueries[job.tier]; + if (job.lastPump != g_pump_serial) { + job.lastPump = g_pump_serial; + job.frames++; + } + const double chunk_began = now_micros(); + int done = 0; + const dtStatus status = query->updateSlicedFindPath(kIterChunk, &done); + job.searchMicros += now_micros() - chunk_began; + if (dtStatusFailed(status)) { + finish(job, WTO_NAV_PATH_FAILED); + g_active = -1; + } else if (!dtStatusInProgress(status)) { + finalize(job, query); + g_active = -1; + } + if (now_micros() - began >= budget_us) + break; + } + const double spent = now_micros() - began; + if (spent > g_stats.pumpMaxMicros) + g_stats.pumpMaxMicros = spent; + ReleaseSRWLockExclusive(&g_lock); +} diff --git a/native/wto-nav/wto_nav_queries.cpp b/native/wto-nav/wto_nav_queries.cpp new file mode 100644 index 0000000..9518ff4 --- /dev/null +++ b/native/wto-nav/wto_nav_queries.cpp @@ -0,0 +1,164 @@ +/* + * Point queries on the loaded pack (wto_nav_runtime.h) for the ground AI's path follower: what + * lies under a vehicle (surface, flags, distance to the mesh edge), whether the mesh lets it go + * straight somewhere, the nearest walkable point, and dynamic cost circles (wrecks, jams, rubble) + * that later path searches route around. + */ +#include "wto_nav_internal.h" + +#include +#include + +namespace wtonav { + +DynamicCost g_dynamic[WTO_NAV_RT_MAX_DYNAMIC]; +uint32_t g_dynamic_count; + +void dynamic_reset_locked() +{ + g_dynamic_count = 0; +} + +void dynamic_expire_locked(float now) +{ + uint32_t kept = 0; + for (uint32_t i = 0; i < g_dynamic_count; i++) { + if (g_dynamic[i].until >= now) + g_dynamic[kept++] = g_dynamic[i]; + } + g_dynamic_count = kept; +} + +namespace { + +bool valid_query(uint32_t tier, uint32_t filter) +{ + return g_pack != nullptr && tier < WTO_NAV_TIER_COUNT && filter < WTO_NAV_RT_FILTER_COUNT; +} + +/* An existing circle overlapping most of the new one, or -1. */ +int find_dynamic(const float pos[3], float radius) +{ + for (uint32_t i = 0; i < g_dynamic_count; i++) { + const float dx = g_dynamic[i].pos[0] - pos[0], dz = g_dynamic[i].pos[2] - pos[2]; + const float reach = (g_dynamic[i].radius > radius ? g_dynamic[i].radius : radius) * 0.5f; + if (dx * dx + dz * dz <= reach * reach) + return (int)i; + } + return -1; +} + +int soonest_dynamic() +{ + int best = 0; + for (uint32_t i = 1; i < g_dynamic_count; i++) { + if (g_dynamic[i].until < g_dynamic[best].until) + best = (int)i; + } + return best; +} + +} // namespace +} // namespace wtonav + +using namespace wtonav; + +extern "C" int wto_nav_probe(uint32_t tier, uint32_t filter, const float pos[3], float snap_m, float wall_radius_m, WtoNavProbe *probe) +{ + memset(probe, 0, sizeof(*probe)); + AcquireSRWLockExclusive(&g_lock); /* findDistanceToWall uses the query's node pool */ + if (!valid_query(tier, filter) || !(snap_m > 0.0f)) { + ReleaseSRWLockExclusive(&g_lock); + return 0; + } + g_stats.meshQueries++; + dtNavMeshQuery *query = g_pack->pointQueries[tier]; + const QueryFilter &qf = g_filters[filter]; + dtPolyRef ref = 0; + if (snap_to_mesh(query, qf, snap_m, g_pack->heightSpan, pos, &ref, probe->nearest)) { + const dtMeshTile *tile = nullptr; + const dtPoly *poly = nullptr; + probe->onMesh = 1; + probe->offsetM = dtVdist2D(pos, probe->nearest); + if (dtStatusSucceed(g_pack->meshes[tier]->getTileAndPolyByRef(ref, &tile, &poly))) { + probe->area = poly->getArea(); + probe->flags = poly->flags; + } + float hit_pos[3], hit_normal[3]; + float dist = wall_radius_m; + if (wall_radius_m > 0.0f && + dtStatusFailed(query->findDistanceToWall(ref, probe->nearest, wall_radius_m, &qf, &dist, hit_pos, hit_normal))) + dist = wall_radius_m; + probe->wallDistM = dist; + } + ReleaseSRWLockExclusive(&g_lock); + return 1; +} + +extern "C" int wto_nav_raycast(uint32_t tier, uint32_t filter, float snap_m, const float start[3], const float goal[3], + float *hit_frac, float hit[3]) +{ + *hit_frac = 0.0f; + dtVcopy(hit, start); + AcquireSRWLockShared(&g_lock); + if (!valid_query(tier, filter) || !(snap_m > 0.0f)) { + ReleaseSRWLockShared(&g_lock); + return -1; + } + InterlockedIncrement((volatile LONG *)&g_stats.meshQueries); + const dtNavMeshQuery *query = g_pack->pointQueries[tier]; + const QueryFilter &qf = g_filters[filter]; + dtPolyRef ref = 0; + float from[3]; + int clear = -1; + if (snap_to_mesh(query, qf, snap_m, g_pack->heightSpan, start, &ref, from)) { + float t = 0.0f, normal[3]; + dtPolyRef visited[64]; + int visited_count = 0; + if (dtStatusSucceed(query->raycast(ref, from, goal, &qf, &t, normal, visited, &visited_count, 64))) { + clear = t == FLT_MAX ? 1 : 0; + *hit_frac = t == FLT_MAX ? 1.0f : t; + dtVlerp(hit, from, goal, *hit_frac); + } + } + ReleaseSRWLockShared(&g_lock); + return clear; +} + +extern "C" int wto_nav_nearest(uint32_t tier, uint32_t filter, float radius_m, const float pos[3], float out[3]) +{ + int found = 0; + AcquireSRWLockShared(&g_lock); + if (valid_query(tier, filter) && radius_m > 0.0f) { + InterlockedIncrement((volatile LONG *)&g_stats.meshQueries); + dtPolyRef ref = 0; + found = snap_to_mesh(g_pack->pointQueries[tier], g_filters[filter], radius_m, g_pack->heightSpan, pos, &ref, out); + } + ReleaseSRWLockShared(&g_lock); + return found; +} + +extern "C" uint32_t wto_nav_add_dynamic(const float pos[3], float radius_m, float cost_mul, float until) +{ + if (!(radius_m > 0.0f) || !(cost_mul > 0.0f)) + return 0; + AcquireSRWLockExclusive(&g_lock); + int at = find_dynamic(pos, radius_m); + if (at >= 0) { + DynamicCost &d = g_dynamic[at]; + dtVcopy(d.pos, pos); + d.radius = d.radius > radius_m ? d.radius : radius_m; + d.mul = d.mul > cost_mul ? d.mul : cost_mul; + d.until = d.until > until ? d.until : until; + } else { + at = g_dynamic_count < WTO_NAV_RT_MAX_DYNAMIC ? (int)g_dynamic_count++ : soonest_dynamic(); + DynamicCost &d = g_dynamic[at]; + dtVcopy(d.pos, pos); + d.radius = radius_m; + d.mul = cost_mul; + d.until = until; + } + const uint32_t count = g_dynamic_count; + ReleaseSRWLockExclusive(&g_lock); + return count; +} diff --git a/native/wto-nav/wto_nav_runtime.cpp b/native/wto-nav/wto_nav_runtime.cpp index 43b5871..72c5f61 100644 --- a/native/wto-nav/wto_nav_runtime.cpp +++ b/native/wto-nav/wto_nav_runtime.cpp @@ -1,69 +1,49 @@ /* * In-game navigation engine (wto_nav_runtime.h): loads one `.wtonav` pack written by - * tools/navgen/bake into upstream Detour meshes and answers path queries for the ground AI. + * tools/navgen/bake into upstream Detour meshes, optionally on a background thread while the + * battle is still loading. Path searches live in wto_nav_paths.cpp, point queries and dynamic + * costs in wto_nav_queries.cpp. */ -#include "wto_nav_runtime.h" -#include "wto_nav_format.h" +#include "wto_nav_internal.h" #include "DetourAlloc.h" -#include "DetourCommon.h" -#include "DetourNavMesh.h" -#include "DetourNavMeshQuery.h" - -#include #include #include -#include +#include -#ifndef DT_VIRTUAL_QUERYFILTER -#error "Detour must be built with DT_VIRTUAL_QUERYFILTER for the chokepoint cost filter" -#endif +namespace wtonav { + +SRWLOCK g_lock = SRWLOCK_INIT; +Pack *g_pack; +QueryFilter g_filters[WTO_NAV_RT_FILTER_COUNT]; +WtoNavStats g_stats; namespace { -constexpr int kMaxSearchNodes = 32768; -constexpr int kMaxPathPolys = 4096; constexpr size_t kMaxPackBytes = 512u * 1024u * 1024u; constexpr size_t kMaxEverBytes = 64u * 1024u; constexpr int kMaxLevelBlocks = 4096; -/* Area costs per WtoPolyArea, times a multiplier on chokepoint polygons. */ -class WtoQueryFilter : public dtQueryFilter { -public: - float chokepointMul = 1.0f; - - float getCost(const float *pa, const float *pb, - const dtPolyRef, const dtMeshTile *, const dtPoly *, - const dtPolyRef, const dtMeshTile *, const dtPoly *curPoly, - const dtPolyRef, const dtMeshTile *, const dtPoly *) const override - { - float cost = dtVdist(pa, pb) * getAreaCost(curPoly->getArea()); - if (curPoly->flags & WTO_FLAG_CHOKEPOINT) - cost *= chokepointMul; - return cost; - } -}; - -struct Pack { - float heightSpan = 0.0f; /* Vertical extent of the mesh bounds */ - dtNavMesh *meshes[WTO_NAV_TIER_COUNT] = {}; - dtNavMeshQuery *queries[WTO_NAV_TIER_COUNT] = {}; - std::vector covers; - std::vector tactical; -}; - -SRWLOCK g_lock = SRWLOCK_INIT; -Pack *g_pack; -WtoQueryFilter g_filters[WTO_NAV_RT_FILTER_COUNT]; bool g_filters_ready; -WtoNavStats g_stats; + +/* A pack read on a background thread, waiting for wto_nav_load. Guarded by g_stage_lock. */ +struct Staged { + std::wstring packPath; + std::wstring levelPath; + HANDLE thread = nullptr; + Pack *pack = nullptr; + WtoNavLoadInfo info = {}; +}; + +SRWLOCK g_stage_lock = SRWLOCK_INIT; +Staged *g_staged; void init_filters_locked() { if (g_filters_ready) return; - for (WtoQueryFilter &filter : g_filters) { + for (QueryFilter &filter : g_filters) { filter.setIncludeFlags(WTO_FLAG_WALK); filter.setExcludeFlags(WTO_FLAG_DEEP_WATER | WTO_FLAG_BLOCKED); } @@ -75,7 +55,8 @@ void free_pack(Pack *pack) if (pack == nullptr) return; for (uint32_t t = 0; t < WTO_NAV_TIER_COUNT; t++) { - dtFreeNavMeshQuery(pack->queries[t]); + dtFreeNavMeshQuery(pack->pathQueries[t]); + dtFreeNavMeshQuery(pack->pointQueries[t]); dtFreeNavMesh(pack->meshes[t]); } delete pack; @@ -109,6 +90,15 @@ bool fits(const std::vector &data, uint64_t offset, uint64_t size) return offset <= data.size() && size <= data.size() - offset; } +bool init_queries(Pack *pack, uint32_t tier) +{ + pack->pathQueries[tier] = dtAllocNavMeshQuery(); + pack->pointQueries[tier] = dtAllocNavMeshQuery(); + return pack->pathQueries[tier] != nullptr && pack->pointQueries[tier] != nullptr && + dtStatusSucceed(pack->pathQueries[tier]->init(pack->meshes[tier], kPathSearchNodes)) && + dtStatusSucceed(pack->pointQueries[tier]->init(pack->meshes[tier], kPointSearchNodes)); +} + bool load_tier(const std::vector &data, const WtoNavHeader &hdr, uint32_t tier, Pack *pack, uint32_t *polys, char *detail, size_t detail_size) { uint64_t at = hdr.tierOffsets[tier]; @@ -156,8 +146,7 @@ bool load_tier(const std::vector &data, const WtoNavHeader &hdr, uint32 } *polys += (uint32_t)((const dtMeshHeader *)tile)->polyCount; } - pack->queries[tier] = dtAllocNavMeshQuery(); - if (pack->queries[tier] == nullptr || dtStatusFailed(pack->queries[tier]->init(pack->meshes[tier], kMaxSearchNodes))) { + if (!init_queries(pack, tier)) { snprintf(detail, detail_size, "tier %u query init failed", tier); return false; } @@ -204,11 +193,96 @@ Pack *parse_pack(const std::vector &data, WtoNavLoadInfo *info) return pack; } -/* - * Nearest polygon within `snap` metres; mission points (spawn and capture zone centres) carry - * heights that are not on the ground, so a miss is retried over the mesh's whole height range, - * still within `snap` horizontally. - */ +/* Reads and parses a pack plus the level fingerprint; runs on any thread, touches no globals. */ +Pack *read_pack(const wchar_t *pack_path, const wchar_t *level_path, WtoNavLoadInfo *info) +{ + const double began = now_micros(); + std::vector data; + Pack *pack = nullptr; + + memset(info, 0, sizeof(*info)); + if (level_path != nullptr && level_path[0] != L'\0') + info->fingerprintKnown = wto_nav_read_level_fingerprint(level_path, info->levelSha1); + if (read_file(pack_path, data, info)) { + pack = parse_pack(data, info); + info->result = pack != nullptr ? WTO_NAV_LOAD_OK : WTO_NAV_LOAD_CORRUPT; + } + if (pack != nullptr && info->fingerprintKnown) + info->fingerprintMatch = memcmp(info->packSha1, info->levelSha1, sizeof(info->packSha1)) == 0; + info->readMs = (now_micros() - began) / 1000.0; + return pack; +} + +DWORD WINAPI prefetch_main(void *arg) +{ + Staged *staged = (Staged *)arg; + staged->pack = read_pack(staged->packPath.c_str(), staged->levelPath.c_str(), &staged->info); + return 0; +} + +/* Waits for the background read of `staged` and frees what it produced. */ +void discard_staged(Staged *staged) +{ + if (staged == nullptr) + return; + if (staged->thread != nullptr) { + WaitForSingleObject(staged->thread, INFINITE); + CloseHandle(staged->thread); + } + free_pack(staged->pack); + delete staged; +} + +/* Takes the staged pack if it is `pack_path`; the caller then owns (and joins) it. */ +Staged *take_staged(const wchar_t *pack_path) +{ + AcquireSRWLockExclusive(&g_stage_lock); + Staged *staged = g_staged; + if (staged != nullptr && staged->packPath == pack_path) + g_staged = nullptr; + else + staged = nullptr; + ReleaseSRWLockExclusive(&g_stage_lock); + return staged; +} + +void replace_pack(Pack *pack) +{ + AcquireSRWLockExclusive(&g_lock); + init_filters_locked(); + free_pack(g_pack); + g_pack = pack; + paths_reset_locked(); + dynamic_reset_locked(); + memset(&g_stats, 0, sizeof(g_stats)); + g_stats.loaded = pack != nullptr; + ReleaseSRWLockExclusive(&g_lock); +} + +} // namespace + +float QueryFilter::getCost(const float *pa, const float *pb, + const dtPolyRef, const dtMeshTile *, const dtPoly *, + const dtPolyRef, const dtMeshTile *, const dtPoly *curPoly, + const dtPolyRef, const dtMeshTile *, const dtPoly *) const +{ + float cost = dtVdist(pa, pb) * getAreaCost(curPoly->getArea()); + if (curPoly->flags & WTO_FLAG_CHOKEPOINT) + cost *= chokepointMul; + if (g_dynamic_count != 0) { + const float mx = (pa[0] + pb[0]) * 0.5f, mz = (pa[2] + pb[2]) * 0.5f; + float mul = 1.0f; + for (uint32_t i = 0; i < g_dynamic_count; i++) { + const DynamicCost &d = g_dynamic[i]; + const float dx = mx - d.pos[0], dz = mz - d.pos[2]; + if (dx * dx + dz * dz < d.radius * d.radius && d.mul > mul) + mul = d.mul; + } + cost *= mul; + } + return cost; +} + bool snap_to_mesh(const dtNavMeshQuery *query, const dtQueryFilter &filter, float snap, float height_span, const float point[3], dtPolyRef *ref, float nearest[3]) { @@ -229,45 +303,9 @@ double now_micros() return (double)counter.QuadPart * 1e6 / (double)frequency.QuadPart; } -WtoNavPathStatus find_path_locked(uint32_t tier, uint32_t filter_index, float snap_radius_m, - const float start[3], const float goal[3], - float *points, int max_points, int *count, float *length_m) -{ - if (g_pack == nullptr || tier >= WTO_NAV_TIER_COUNT || filter_index >= WTO_NAV_RT_FILTER_COUNT || - points == nullptr || max_points < 2 || !(snap_radius_m > 0.0f)) - return WTO_NAV_PATH_FAILED; - dtNavMeshQuery *query = g_pack->queries[tier]; - const WtoQueryFilter &filter = g_filters[filter_index]; - dtPolyRef start_ref = 0, goal_ref = 0; - float start_pt[3], goal_pt[3]; +} // namespace wtonav - if (!snap_to_mesh(query, filter, snap_radius_m, g_pack->heightSpan, start, &start_ref, start_pt)) - return WTO_NAV_PATH_NO_START; - if (!snap_to_mesh(query, filter, snap_radius_m, g_pack->heightSpan, goal, &goal_ref, goal_pt)) - return WTO_NAV_PATH_NO_GOAL; - - static dtPolyRef path[kMaxPathPolys]; - int path_count = 0; - dtStatus status = query->findPath(start_ref, goal_ref, start_pt, goal_pt, &filter, path, &path_count, kMaxPathPolys); - if (dtStatusFailed(status) || path_count == 0) - return WTO_NAV_PATH_FAILED; - bool partial = dtStatusDetail(status, DT_PARTIAL_RESULT) || path[path_count - 1] != goal_ref; - if (partial && dtStatusFailed(query->closestPointOnPoly(path[path_count - 1], goal, goal_pt, nullptr))) - return WTO_NAV_PATH_FAILED; - - int corners = 0; - status = query->findStraightPath(start_pt, goal_pt, path, path_count, points, nullptr, nullptr, &corners, max_points, 0); - if (dtStatusFailed(status) || corners == 0) - return WTO_NAV_PATH_FAILED; - float length = 0.0f; - for (int i = 1; i < corners; i++) - length += dtVdist(points + (i - 1) * 3, points + i * 3); - *count = corners; - *length_m = length; - return partial ? WTO_NAV_PATH_PARTIAL : WTO_NAV_PATH_FULL; -} - -} // namespace +using namespace wtonav; extern "C" int wto_nav_read_level_fingerprint(const wchar_t *level_path, uint8_t sha1[20]) { @@ -314,39 +352,54 @@ extern "C" int wto_nav_read_level_fingerprint(const wchar_t *level_path, uint8_t return found; } -extern "C" void wto_nav_load(const wchar_t *pack_path, const uint8_t *level_sha1, WtoNavLoadInfo *info) +extern "C" void wto_nav_prefetch(const wchar_t *pack_path, const wchar_t *level_path) { - std::vector data; - Pack *pack = nullptr; - - memset(info, 0, sizeof(*info)); - if (level_sha1 != nullptr) { - info->fingerprintKnown = 1; - memcpy(info->levelSha1, level_sha1, sizeof(info->levelSha1)); + if (pack_path == nullptr || pack_path[0] == L'\0') + return; + AcquireSRWLockExclusive(&g_stage_lock); + if (g_staged != nullptr && g_staged->packPath == pack_path) { + ReleaseSRWLockExclusive(&g_stage_lock); + return; } - if (read_file(pack_path, data, info)) { - pack = parse_pack(data, info); - info->result = pack != nullptr ? WTO_NAV_LOAD_OK : WTO_NAV_LOAD_CORRUPT; + Staged *previous = g_staged; + Staged *staged = new Staged(); + staged->packPath = pack_path; + staged->levelPath = level_path != nullptr ? level_path : L""; + staged->thread = CreateThread(nullptr, 0, prefetch_main, staged, 0, nullptr); + if (staged->thread == nullptr) { + delete staged; + staged = nullptr; } - if (pack != nullptr && level_sha1 != nullptr) - info->fingerprintMatch = memcmp(info->packSha1, level_sha1, sizeof(info->packSha1)) == 0; + g_staged = staged; + ReleaseSRWLockExclusive(&g_stage_lock); + discard_staged(previous); +} - AcquireSRWLockExclusive(&g_lock); - init_filters_locked(); - free_pack(g_pack); - g_pack = pack; - memset(&g_stats, 0, sizeof(g_stats)); - g_stats.loaded = pack != nullptr; - ReleaseSRWLockExclusive(&g_lock); +extern "C" void wto_nav_load(const wchar_t *pack_path, const wchar_t *level_path, WtoNavLoadInfo *info) +{ + const double began = now_micros(); + Staged *staged = take_staged(pack_path); + Pack *pack; + + if (staged != nullptr) { + WaitForSingleObject(staged->thread, INFINITE); + CloseHandle(staged->thread); + staged->thread = nullptr; + pack = staged->pack; + staged->pack = nullptr; + *info = staged->info; + info->prefetched = 1; + discard_staged(staged); + } else { + pack = read_pack(pack_path, level_path, info); + } + info->waitMs = (now_micros() - began) / 1000.0; + replace_pack(pack); } extern "C" void wto_nav_unload(void) { - AcquireSRWLockExclusive(&g_lock); - free_pack(g_pack); - g_pack = nullptr; - g_stats.loaded = 0; - ReleaseSRWLockExclusive(&g_lock); + replace_pack(nullptr); } extern "C" int wto_nav_is_loaded(void) @@ -369,31 +422,11 @@ extern "C" void wto_nav_set_costs(uint32_t filter, const WtoNavCosts *costs) ReleaseSRWLockExclusive(&g_lock); } -extern "C" WtoNavPathStatus wto_nav_find_path(uint32_t tier, uint32_t filter, float snap_radius_m, - const float start[3], const float goal[3], - float *points, int max_points, int *count, float *length_m) -{ - *count = 0; - *length_m = 0.0f; - AcquireSRWLockExclusive(&g_lock); - const double began = now_micros(); - const WtoNavPathStatus status = find_path_locked(tier, filter, snap_radius_m, start, goal, points, max_points, count, length_m); - const double spent = now_micros() - began; - if (g_pack != nullptr) { - g_stats.queries++; - g_stats.totalMicros += spent; - if (spent > g_stats.maxMicros) - g_stats.maxMicros = spent; - if (status != WTO_NAV_PATH_FULL) - g_stats.failures++; - } - ReleaseSRWLockExclusive(&g_lock); - return status; -} - extern "C" void wto_nav_get_stats(WtoNavStats *stats) { - AcquireSRWLockShared(&g_lock); + AcquireSRWLockExclusive(&g_lock); + g_stats.pending = paths_pending_locked(); + g_stats.dynamic = g_dynamic_count; *stats = g_stats; - ReleaseSRWLockShared(&g_lock); + ReleaseSRWLockExclusive(&g_lock); } diff --git a/native/wto-nav/wto_nav_runtime.h b/native/wto-nav/wto_nav_runtime.h index a278edc..e29c64a 100644 --- a/native/wto-nav/wto_nav_runtime.h +++ b/native/wto-nav/wto_nav_runtime.h @@ -1,7 +1,7 @@ /* * In-game navigation engine: one baked `.wtonav` pack (tools/navgen) held for the battle in * progress, queried through upstream Detour. The C side (wto-net local_mp_nav.c) owns the - * daScript request protocol; this interface only knows packs, levels and paths. + * daScript request protocol; this interface only knows packs, levels, paths and mesh queries. * * Every function is safe to call from any thread; queries are serialized internally. */ @@ -13,8 +13,11 @@ extern "C" { #endif -#define WTO_NAV_RT_AREA_COUNT 12 /* WtoPolyArea values 0..11 */ -#define WTO_NAV_RT_FILTER_COUNT 2 /* 0 tracked, 1 wheeled */ +#define WTO_NAV_RT_AREA_COUNT 12 /* WtoPolyArea values 0..11 */ +#define WTO_NAV_RT_FILTER_COUNT 2 /* 0 tracked, 1 wheeled */ +#define WTO_NAV_RT_PATH_SLOTS 160 /* Independent path searches the script may keep in flight */ +#define WTO_NAV_RT_MAX_CORNERS 96 /* Straight-path corners returned per path */ +#define WTO_NAV_RT_MAX_DYNAMIC 64 /* Live dynamic cost circles (wrecks, jams, rubble) */ /* Detour traversal costs for one vehicle class, indexed by WtoPolyArea. */ typedef struct WtoNavCosts { @@ -33,11 +36,14 @@ typedef struct WtoNavLoadInfo { WtoNavLoadResult result; int fingerprintKnown; /* 1 when the level file's eVER SHA-1 was read */ int fingerprintMatch; /* 1 when it equals the pack's; meaningful only when known */ + int prefetched; /* 1 when the pack was read in the background beforehand */ uint8_t packSha1[20]; uint8_t levelSha1[20]; uint32_t tiers; uint32_t covers; uint32_t polys[3]; + double readMs; /* Time spent reading and parsing, wherever it happened */ + double waitMs; /* Time the caller of wto_nav_load was held up */ char detail[96]; /* Why loading failed, for the log */ } WtoNavLoadInfo; @@ -45,26 +51,68 @@ typedef enum WtoNavPathStatus { WTO_NAV_PATH_FULL = 0, WTO_NAV_PATH_PARTIAL, /* Ends at the reachable polygon closest to the goal */ WTO_NAV_PATH_NO_START, /* Start not within the snap radius of the mesh */ - WTO_NAV_PATH_NO_GOAL, + WTO_NAV_PATH_NO_GOAL, /* Goal not within the goal snap radius of the mesh */ WTO_NAV_PATH_FAILED, /* No pack loaded, bad tier or Detour failure */ + WTO_NAV_PATH_PENDING, /* Queued or being searched; ask again after the next pump */ + WTO_NAV_PATH_STALE, /* The slot holds another (newer) request, or none */ } WtoNavPathStatus; +typedef struct WtoNavPathRequest { + uint32_t tier; /* 0 narrow, 1 standard, 2 wide */ + uint32_t filter; /* 0 tracked, 1 wheeled */ + float snapM; /* Start (and first goal) snap radius */ + float goalSnapM; /* Wider horizontal goal snap when the goal misses snapM */ + float start[3]; + float goal[3]; +} WtoNavPathRequest; + +typedef struct WtoNavPathResult { + WtoNavPathStatus status; + int count; /* Corners written, the first being the snapped start */ + int truncated; /* 1 when the path has more corners than were returned */ + int goalMoved; /* 1 when the goal was snapped with goalSnapM */ + float lengthM; /* Length of the returned corners */ +} WtoNavPathResult; + +/* What the mesh says about one point of the tier's mesh. */ +typedef struct WtoNavProbe { + int onMesh; /* 1 when a polygon lies within the snap radius */ + float nearest[3]; /* Closest point on that polygon */ + float offsetM; /* Horizontal distance from the asked point to `nearest` */ + float wallDistM; /* Distance to the mesh edge, capped at the search radius */ + uint32_t area; /* WtoPolyArea of the polygon */ + uint32_t flags; /* WtoPolyFlag bits of the polygon */ +} WtoNavProbe; + typedef struct WtoNavStats { int loaded; - uint32_t queries; - uint32_t failures; - double totalMicros; - double maxMicros; + uint32_t queries; /* Finished path searches */ + uint32_t failures; /* Of which not FULL */ + double totalMicros; /* Search time of finished paths, summed over their frames */ + double maxMicros; /* Longest search time of a single path */ + uint32_t maxFrames; /* Most pump frames a single path took */ + double pumpMaxMicros; /* Longest single pump */ + uint32_t pending; /* Paths waiting or being searched now */ + uint32_t dynamic; /* Live dynamic cost circles */ + uint32_t meshQueries; /* Probe, raycast and nearest calls */ } WtoNavStats; /* Reads the eVER SHA-1 of a Dagor level file (levels/.bin) without loading the level. */ int wto_nav_read_level_fingerprint(const wchar_t *level_path, uint8_t sha1[20]); /* - * Loads `pack_path`, replacing any loaded pack. `level_sha1` is the fingerprint of the level the - * game runs (NULL when unknown); a mismatch is reported but never refuses the pack. + * Starts reading `pack_path` (and the fingerprint of `level_path`) on a background thread so a + * later wto_nav_load of the same pack only takes the result. Nothing happens when that pack is + * already being read or waiting; a different one replaces it. */ -void wto_nav_load(const wchar_t *pack_path, const uint8_t *level_sha1, WtoNavLoadInfo *info); +void wto_nav_prefetch(const wchar_t *pack_path, const wchar_t *level_path); + +/* + * Makes `pack_path` the loaded pack, replacing any other: from the background read when it is + * the same file (waiting for it to finish), otherwise read here. A fingerprint mismatch is + * reported but never refuses the pack. Clears paths in flight and dynamic costs. + */ +void wto_nav_load(const wchar_t *pack_path, const wchar_t *level_path, WtoNavLoadInfo *info); void wto_nav_unload(void); int wto_nav_is_loaded(void); @@ -72,12 +120,38 @@ int wto_nav_is_loaded(void); void wto_nav_set_costs(uint32_t filter, const WtoNavCosts *costs); /* - * Straight-line corners from `start` to `goal` on the mesh of `tier` (0 narrow, 1 standard, - * 2 wide). `points` receives up to `max_points` xyz triples; the first is the snapped start. + * Queues a path search in `slot`, replacing whatever the slot held. Start and goal are snapped + * at once; a miss is final and reported through the ticket's result. Returns the ticket that + * wto_nav_path_result must quote (0 when the slot or request is invalid). */ -WtoNavPathStatus wto_nav_find_path(uint32_t tier, uint32_t filter, float snap_radius_m, - const float start[3], const float goal[3], - float *points, int max_points, int *count, float *length_m); +uint32_t wto_nav_path_request(uint32_t slot, const WtoNavPathRequest *request); + +/* Result of `ticket` in `slot`; `points` receives up to `max_points` xyz triples. */ +void wto_nav_path_result(uint32_t slot, uint32_t ticket, float *points, int max_points, WtoNavPathResult *result); + +/* + * Advances queued searches for at most `budget_us` microseconds (one call per game frame) and + * expires dynamic costs whose end time is before `now` (script time, seconds). + */ +void wto_nav_pump(double budget_us, float now); + +int wto_nav_probe(uint32_t tier, uint32_t filter, const float pos[3], float snap_m, float wall_radius_m, WtoNavProbe *probe); + +/* + * Walks the mesh surface from `start` toward `goal`. Returns 1 when nothing blocks the way, + * 0 when a mesh edge does (`hit_frac` and `hit` tell where), -1 when `start` is off the mesh. + */ +int wto_nav_raycast(uint32_t tier, uint32_t filter, float snap_m, const float start[3], const float goal[3], + float *hit_frac, float hit[3]); + +/* Closest point of the tier's mesh within `radius_m` (horizontally, any height); 1 if found. */ +int wto_nav_nearest(uint32_t tier, uint32_t filter, float radius_m, const float pos[3], float out[3]); + +/* + * Adds a circle that multiplies path costs by `cost_mul` until script time `until`; a circle + * close to an existing one updates it. Returns the number of live circles. + */ +uint32_t wto_nav_add_dynamic(const float pos[3], float radius_m, float cost_mul, float until); void wto_nav_get_stats(WtoNavStats *stats); diff --git a/native/wto-net/build.ps1 b/native/wto-net/build.ps1 index c786288..79c979d 100644 --- a/native/wto-net/build.ps1 +++ b/native/wto-net/build.ps1 @@ -32,7 +32,7 @@ $sources = Quote @( "$src\dll_main.c", "$src\hook_config.c", "$src\redirect_rules.c", "$src\resolver_hooks.c", "$src\connection_hooks.c", "$src\local_mp_core.c", "$src\local_mp_values.c", "$src\local_mp_players.c", "$src\local_mp_loadout.c", "$src\local_mp_actions.c", "$src\local_mp_awards.c", "$src\local_mp_kills.c", "$src\local_mp_events.c", "$src\local_mp_scores.c", "$src\local_mp_nuke.c", "$src\local_mp_support.c", "$src\local_mp_damage_notifications.c", "$src\local_mp_air_events.c", "$src\local_mp_ground_ai.c", "$src\local_mp_nav.c", "$src\local_mp_zones.c", - "$nav\wto_nav_runtime.cpp", + "$nav\wto_nav_runtime.cpp", "$nav\wto_nav_paths.cpp", "$nav\wto_nav_queries.cpp", "$mh\src\hook.c", "$mh\src\buffer.c", "$mh\src\trampoline.c", "$mh\src\hde\hde64.c" ) $detourSources = Quote (Get-ChildItem "$dt\Source\*.cpp").FullName diff --git a/native/wto-net/src/local_mp_nav.c b/native/wto-net/src/local_mp_nav.c index 3377b54..6c391d1 100644 --- a/native/wto-net/src/local_mp_nav.c +++ b/native/wto-net/src/local_mp_nav.c @@ -3,22 +3,33 @@ * battle's navigation pack (native/wto-nav). The script fills a DataBlock with the request, this * module answers synchronously by writing into the same block: * - * op=load_map allowFallback="0|1", tracked/wheeled costs t_, w_ - * -> state=loaded|fallback|failed, fingerprint=match|mismatch|unknown, level, - * reason, tiers, covers - * op=unload_map -> ok - * op=find_path tier, filter (0 tracked, 1 wheeled), max, snap, sx..sz, gx..gz - * -> status=full|partial|no_start|no_goal|failed, count, lenCm, - * px/py/pz in centimetres (ints) - * op=get_stats -> loaded, queries, failures, avgUs, maxUs + * op=prefetch -> state=started|skipped, level, reason (battle still loading) + * op=load_map allowFallback="0|1", tracked/wheeled costs t_, w_ + * -> state=loaded|fallback|failed, fingerprint=match|mismatch|unknown, level, + * reason, tiers, covers + * op=unload_map -> ok + * op=pump now (script seconds), budgetUs -> pending + * op=path_request slot, tier, filter (0 tracked, 1 wheeled), snap, goalSnap, sx..sz, gx..gz + * -> ticket + * op=path_result slot, ticket -> status=pending|full|partial|no_start|no_goal|failed|stale, + * count, lenCm, truncated, goalMoved, px/py/pz + * op=probe tier, filter, snap, wallR, px..pz -> onMesh, offCm, wallCm, area, flags, + * nx/ny/nz + * op=raycast tier, filter, snap, sx..sz, gx..gz -> clear=1|0|-1, hitPm, hx/hy/hz + * op=nearest tier, filter, radius, px..pz -> found, x/y/z + * op=dynamic px..pz, radius, mul, until (script seconds) -> count + * op=get_stats -> loaded, queries, failures, avgUs, maxUs, maxFrames, pumpMaxUs, pending, + * dynamic, meshQueries * - * Request values are strings: the script only uses the DataBlock string add it already relies on. - * Replies are ints and strings written with the setters local_mp_awards resolves. + * Coordinates in replies are centimetres (ints). Request values are strings: the script only uses + * the DataBlock string add it already relies on. Replies are ints and strings written with the + * setters local_mp_awards resolves. * * The level comes from the mission settings (customBots wtoLevel, written by the local server), - * the pack folder from wto_ws.cfg (nav.dir). Whether the battle uses the pack, falls back to the - * script's own navigation or refuses to drive is decided by the first load_map of the battle and - * kept until unload_map or the end of the session; it never changes in the middle of a battle. + * the pack folder from wto_ws.cfg (nav.dir). The script asks for a prefetch while the battle + * loads, so the pack is read on a background thread. Whether the battle uses the pack, falls back + * to stock road paths or refuses to drive is decided by the first load_map of the battle and kept + * until unload_map or the end of the session; it never changes in the middle of a battle. */ #include "hook_config.h" #include "local_mp_internal.h" @@ -30,7 +41,6 @@ #include #include -#define NAV_MAX_POINTS 96 #define NAV_LEVEL_MAX 64 typedef void (__fastcall *BlkSetStrFn)(void *blk, const char *name, const char *value); @@ -107,6 +117,17 @@ static long get_long(const void *blk, const char *name, long def) return *end == '\0' ? value : def; } +/* x, y, z */ +static void get_vec(const void *blk, char prefix, float out[3]) +{ + char key[3] = { prefix, 'x', '\0' }; + out[0] = get_real(blk, key, 0.0f); + key[1] = 'y'; + out[1] = get_real(blk, key, 0.0f); + key[1] = 'z'; + out[2] = get_real(blk, key, 0.0f); +} + static int32_t to_cm(float metres) { const float cm = metres * 100.0f; @@ -117,6 +138,13 @@ static int32_t to_cm(float metres) return (int32_t)(cm >= 0.0f ? cm + 0.5f : cm - 0.5f); } +static void set_vec_cm(void *blk, const char *x, const char *y, const char *z, const float v[3]) +{ + set_int(blk, x, to_cm(v[0])); + set_int(blk, y, to_cm(v[1])); + set_int(blk, z, to_cm(v[2])); +} + static void hex20(const uint8_t *sha1, char out[41]) { static const char digits[] = "0123456789abcdef"; @@ -172,6 +200,32 @@ static int level_file_path(const char *level, wchar_t *out, size_t out_count) return _snwprintf_s(out, out_count, _TRUNCATE, L"%s\\levels\\%S.bin", exe, level) > 0; } +/* + * Pack and level paths of the battle in the mission settings; on failure `reason` says why. + * `level_path` is left empty when the level file cannot be located (fingerprint unknown). + */ +static int battle_paths(char level[NAV_LEVEL_MAX], wchar_t pack[MAX_PATH], wchar_t level_path[MAX_PATH], + char *reason, size_t reason_size) +{ + const wchar_t *dir = config_nav_dir(); + if (!battle_level(level)) { + level[0] = '\0'; + snprintf(reason, reason_size, "battle level unknown (customBots wtoLevel)"); + return 0; + } + if (dir[0] == L'\0') { + snprintf(reason, reason_size, "no pack folder (wto_ws.cfg nav.dir)"); + return 0; + } + if (_snwprintf_s(pack, MAX_PATH, _TRUNCATE, L"%s\\%S.wtonav", dir, level) <= 0) { + snprintf(reason, reason_size, "pack path too long"); + return 0; + } + if (!level_file_path(level, level_path, MAX_PATH)) + level_path[0] = L'\0'; + return 1; +} + static void read_costs(const void *blk, const char *prefix, WtoNavCosts *costs) { char key[48]; @@ -191,49 +245,43 @@ static void read_costs(const void *blk, const char *prefix, WtoNavCosts *costs) costs->chokepointMul = 1.0f; } +static void log_loaded(const WtoNavLoadInfo *info) +{ + char expected[41], actual[41]; + hex20(info->packSha1, expected); + hex20(info->levelSha1, actual); + if (info->fingerprintKnown && !info->fingerprintMatch) + log_line("WTO_NAV|FINGERPRINT_MISMATCH|level=%s|expected=%s|actual=%s", g_battle.level, expected, actual); + log_line("WTO_NAV|LOADED|level=%s|fingerprint=%s|tiers=%u|covers=%u|polys=%u/%u/%u|prefetched=%d|readMs=%.0f|waitMs=%.1f", + g_battle.level, g_battle.fingerprint, info->tiers, info->covers, + info->polys[0], info->polys[1], info->polys[2], info->prefetched, info->readMs, info->waitMs); +} + static void decide_locked(const void *blk, int allow_fallback) { wchar_t pack[MAX_PATH], level_path[MAX_PATH]; - const wchar_t *dir = config_nav_dir(); - uint8_t level_sha1[20]; - int have_level_sha1 = 0; WtoNavLoadInfo info; - double began = (double)GetTickCount64(); WtoNavCosts costs; memset(&info, 0, sizeof(info)); - if (!battle_level(g_battle.level)) { - snprintf(g_battle.reason, sizeof(g_battle.reason), "battle level unknown (customBots wtoLevel)"); - } else if (dir[0] == L'\0') { - snprintf(g_battle.reason, sizeof(g_battle.reason), "no pack folder (wto_ws.cfg nav.dir)"); - } else if (_snwprintf_s(pack, MAX_PATH, _TRUNCATE, L"%s\\%S.wtonav", dir, g_battle.level) <= 0) { - snprintf(g_battle.reason, sizeof(g_battle.reason), "pack path too long"); - } else { - have_level_sha1 = level_file_path(g_battle.level, level_path, MAX_PATH) && - wto_nav_read_level_fingerprint(level_path, level_sha1); + info.result = WTO_NAV_LOAD_MISSING; + if (battle_paths(g_battle.level, pack, level_path, g_battle.reason, sizeof(g_battle.reason))) { read_costs(blk, "t", &costs); wto_nav_set_costs(0, &costs); read_costs(blk, "w", &costs); wto_nav_set_costs(1, &costs); - wto_nav_load(pack, have_level_sha1 ? level_sha1 : NULL, &info); + wto_nav_load(pack, level_path[0] ? level_path : NULL, &info); if (info.result != WTO_NAV_LOAD_OK) snprintf(g_battle.reason, sizeof(g_battle.reason), "%s", info.detail); } if (info.result == WTO_NAV_LOAD_OK && g_battle.reason[0] == '\0') { - char expected[41], actual[41]; g_battle.decision = NAV_LOADED; g_battle.tiers = info.tiers; g_battle.covers = info.covers; snprintf(g_battle.fingerprint, sizeof(g_battle.fingerprint), "%s", !info.fingerprintKnown ? "unknown" : info.fingerprintMatch ? "match" : "mismatch"); - hex20(info.packSha1, expected); - hex20(info.levelSha1, actual); - if (info.fingerprintKnown && !info.fingerprintMatch) - log_line("WTO_NAV|FINGERPRINT_MISMATCH|level=%s|expected=%s|actual=%s", g_battle.level, expected, actual); - log_line("WTO_NAV|LOADED|level=%s|fingerprint=%s|tiers=%u|covers=%u|polys=%u/%u/%u|ms=%.0f", - g_battle.level, g_battle.fingerprint, info.tiers, info.covers, - info.polys[0], info.polys[1], info.polys[2], (double)GetTickCount64() - began); + log_loaded(&info); return; } snprintf(g_battle.fingerprint, sizeof(g_battle.fingerprint), "unknown"); @@ -244,6 +292,27 @@ static void decide_locked(const void *blk, int allow_fallback) log_line("WTO_NAV|LOAD_FAILED_NO_FALLBACK|level=%s|reason=%s", g_battle.level, g_battle.reason); } +static void prefetch(void *blk) +{ + wchar_t pack[MAX_PATH], level_path[MAX_PATH]; + char level[NAV_LEVEL_MAX], reason[96] = ""; + int started = 0; + + AcquireSRWLockExclusive(&g_battle_lock); + if (g_battle.decision != NAV_UNDECIDED) { + snprintf(reason, sizeof(reason), "battle already decided"); + level[0] = '\0'; + } else if (battle_paths(level, pack, level_path, reason, sizeof(reason))) { + wto_nav_prefetch(pack, level_path); + started = 1; + log_line("WTO_NAV|PREFETCH|level=%s", level); + } + ReleaseSRWLockExclusive(&g_battle_lock); + set_str(blk, "state", started ? "started" : "skipped"); + set_str(blk, "level", level); + set_str(blk, "reason", reason); +} + static void load_map(void *blk) { static const char *const STATES[] = { "", "loaded", "fallback", "failed" }; @@ -268,45 +337,108 @@ static void unload_locked(const char *why) if (wto_nav_is_loaded()) { WtoNavStats stats; wto_nav_get_stats(&stats); - log_line("WTO_NAV|UNLOADED|level=%s|why=%s|queries=%u|failures=%u|avgUs=%.0f|maxUs=%.0f", + log_line("WTO_NAV|UNLOADED|level=%s|why=%s|paths=%u|failures=%u|avgUs=%.0f|maxUs=%.0f|maxFrames=%u|pumpMaxUs=%.0f|meshQueries=%u", g_battle.level, why, stats.queries, stats.failures, - stats.queries ? stats.totalMicros / stats.queries : 0.0, stats.maxMicros); + stats.queries ? stats.totalMicros / stats.queries : 0.0, stats.maxMicros, + stats.maxFrames, stats.pumpMaxMicros, stats.meshQueries); wto_nav_unload(); } memset(&g_battle, 0, sizeof(g_battle)); } -static void find_path(void *blk) +static void path_request(void *blk) { - static const char *const STATUS[] = { "full", "partial", "no_start", "no_goal", "failed" }; - float points[NAV_MAX_POINTS * 3]; - const float start[3] = { get_real(blk, "sx", 0.0f), get_real(blk, "sy", 0.0f), get_real(blk, "sz", 0.0f) }; - const float goal[3] = { get_real(blk, "gx", 0.0f), get_real(blk, "gy", 0.0f), get_real(blk, "gz", 0.0f) }; - const long tier = get_long(blk, "tier", -1), filter = get_long(blk, "filter", 0); - long max = get_long(blk, "max", NAV_MAX_POINTS); - int count = 0, i; - float length = 0.0f; - char key[16]; - WtoNavPathStatus status; + WtoNavPathRequest req; + const long slot = get_long(blk, "slot", -1), tier = get_long(blk, "tier", -1), filter = get_long(blk, "filter", 0); + uint32_t ticket = 0; - if (max < 2 || max > NAV_MAX_POINTS) - max = NAV_MAX_POINTS; - status = (tier < 0 || filter < 0) ? WTO_NAV_PATH_FAILED - : wto_nav_find_path((uint32_t)tier, (uint32_t)filter, get_real(blk, "snap", 0.0f), - start, goal, points, (int)max, &count, &length); - set_str(blk, "status", STATUS[status]); - set_int(blk, "count", count); - set_int(blk, "lenCm", to_cm(length)); - for (i = 0; i < count; i++) { + memset(&req, 0, sizeof(req)); + req.tier = (uint32_t)tier; + req.filter = (uint32_t)filter; + req.snapM = get_real(blk, "snap", 0.0f); + req.goalSnapM = get_real(blk, "goalSnap", 0.0f); + get_vec(blk, 's', req.start); + get_vec(blk, 'g', req.goal); + if (slot >= 0 && tier >= 0 && filter >= 0) + ticket = wto_nav_path_request((uint32_t)slot, &req); + set_int(blk, "ticket", (int32_t)ticket); +} + +static void path_result(void *blk) +{ + static const char *const STATUS[] = { "full", "partial", "no_start", "no_goal", "failed", "pending", "stale" }; + float points[WTO_NAV_RT_MAX_CORNERS * 3]; + const long slot = get_long(blk, "slot", -1), ticket = get_long(blk, "ticket", 0); + WtoNavPathResult result; + char key[16]; + int i; + + wto_nav_path_result(slot < 0 ? UINT32_MAX : (uint32_t)slot, ticket <= 0 ? 0u : (uint32_t)ticket, + points, WTO_NAV_RT_MAX_CORNERS, &result); + set_str(blk, "status", STATUS[result.status]); + set_int(blk, "count", result.count); + set_int(blk, "lenCm", to_cm(result.lengthM)); + set_int(blk, "truncated", result.truncated); + set_int(blk, "goalMoved", result.goalMoved); + for (i = 0; i < result.count; i++) { + char ky[16], kz[16]; snprintf(key, sizeof(key), "p%dx", i); - set_int(blk, key, to_cm(points[i * 3])); - snprintf(key, sizeof(key), "p%dy", i); - set_int(blk, key, to_cm(points[i * 3 + 1])); - snprintf(key, sizeof(key), "p%dz", i); - set_int(blk, key, to_cm(points[i * 3 + 2])); + snprintf(ky, sizeof(ky), "p%dy", i); + snprintf(kz, sizeof(kz), "p%dz", i); + set_vec_cm(blk, key, ky, kz, points + i * 3); } } +static void probe(void *blk) +{ + WtoNavProbe info; + float pos[3]; + get_vec(blk, 'p', pos); + if (!wto_nav_probe((uint32_t)get_long(blk, "tier", 0), (uint32_t)get_long(blk, "filter", 0), pos, + get_real(blk, "snap", 0.0f), get_real(blk, "wallR", 0.0f), &info)) + info.onMesh = -1; + set_int(blk, "onMesh", info.onMesh); + if (info.onMesh != 1) + return; + set_int(blk, "offCm", to_cm(info.offsetM)); + set_int(blk, "wallCm", to_cm(info.wallDistM)); + set_int(blk, "area", (int32_t)info.area); + set_int(blk, "flags", (int32_t)info.flags); + set_vec_cm(blk, "nx", "ny", "nz", info.nearest); +} + +static void raycast(void *blk) +{ + float start[3], goal[3], hit[3], frac = 0.0f; + int clear; + get_vec(blk, 's', start); + get_vec(blk, 'g', goal); + clear = wto_nav_raycast((uint32_t)get_long(blk, "tier", 0), (uint32_t)get_long(blk, "filter", 0), + get_real(blk, "snap", 0.0f), start, goal, &frac, hit); + set_int(blk, "clear", clear); + set_int(blk, "hitPm", (int32_t)(frac * 1000.0f + 0.5f)); + set_vec_cm(blk, "hx", "hy", "hz", hit); +} + +static void nearest(void *blk) +{ + float pos[3], out[3] = { 0.0f, 0.0f, 0.0f }; + int found; + get_vec(blk, 'p', pos); + found = wto_nav_nearest((uint32_t)get_long(blk, "tier", 0), (uint32_t)get_long(blk, "filter", 0), + get_real(blk, "radius", 0.0f), pos, out); + set_int(blk, "found", found); + set_vec_cm(blk, "x", "y", "z", out); +} + +static void add_dynamic(void *blk) +{ + float pos[3]; + get_vec(blk, 'p', pos); + set_int(blk, "count", (int32_t)wto_nav_add_dynamic(pos, get_real(blk, "radius", 0.0f), get_real(blk, "mul", 1.0f), + get_real(blk, "until", 0.0f))); +} + static void get_stats(void *blk) { WtoNavStats stats; @@ -316,6 +448,19 @@ static void get_stats(void *blk) set_int(blk, "failures", (int32_t)stats.failures); set_int(blk, "avgUs", stats.queries ? (int32_t)(stats.totalMicros / stats.queries) : 0); set_int(blk, "maxUs", (int32_t)stats.maxMicros); + set_int(blk, "maxFrames", (int32_t)stats.maxFrames); + set_int(blk, "pumpMaxUs", (int32_t)stats.pumpMaxMicros); + set_int(blk, "pending", (int32_t)stats.pending); + set_int(blk, "dynamic", (int32_t)stats.dynamic); + set_int(blk, "meshQueries", (int32_t)stats.meshQueries); +} + +static void pump(void *blk) +{ + WtoNavStats stats; + wto_nav_pump((double)get_real(blk, "budgetUs", 500.0f), get_real(blk, "now", 0.0f)); + wto_nav_get_stats(&stats); + set_int(blk, "pending", (int32_t)stats.pending); } void local_mp_nav_request(void *blk) @@ -327,8 +472,22 @@ void local_mp_nav_request(void *blk) op = g_lmp_datablock_get_str(blk, "op", ""); if (op == NULL) return; - if (strcmp(op, "find_path") == 0) { - find_path(blk); + if (strcmp(op, "probe") == 0) { + probe(blk); + } else if (strcmp(op, "path_result") == 0) { + path_result(blk); + } else if (strcmp(op, "path_request") == 0) { + path_request(blk); + } else if (strcmp(op, "raycast") == 0) { + raycast(blk); + } else if (strcmp(op, "pump") == 0) { + pump(blk); + } else if (strcmp(op, "nearest") == 0) { + nearest(blk); + } else if (strcmp(op, "dynamic") == 0) { + add_dynamic(blk); + } else if (strcmp(op, "prefetch") == 0) { + prefetch(blk); } else if (strcmp(op, "load_map") == 0) { load_map(blk); } else if (strcmp(op, "unload_map") == 0) { diff --git a/packages/patcher/src/ground-ai/ground-ai-config.ts b/packages/patcher/src/ground-ai/ground-ai-config.ts index 72c188c..a4f2500 100644 --- a/packages/patcher/src/ground-ai/ground-ai-config.ts +++ b/packages/patcher/src/ground-ai/ground-ai-config.ts @@ -35,6 +35,46 @@ export interface GroundAiNavCosts { readonly chokepoint: number; } +/** Path following, local avoidance and unstick of the ground AI (navigation plan section 8). */ +export interface GroundAiPathFollow { + readonly replanIntervalSec: number; + readonly replanGoalMoveM: number; + readonly offCorridorReplanM: number; + readonly lookaheadTimeSec: number; + readonly trackedLookaheadMinM: number; + readonly trackedLookaheadMaxM: number; + readonly wheeledLookaheadMinM: number; + readonly wheeledLookaheadMaxM: number; + readonly cornerAngleDeg: number; + readonly cornerLateralAccelMps2: number; + readonly cornerBrakeDecelMps2: number; + readonly arriveRadiusM: number; + readonly arriveMinSpeedMps: number; + readonly narrowWallMarginM: number; + readonly narrowSpeedMps: number; + readonly bumperRayM: number; + readonly bumperStopM: number; + readonly bumperBlockSec: number; + readonly trafficTtcSec: number; + readonly avoidShiftM: number; + readonly yieldWaitMaxSec: number; + readonly stuckWindowSec: number; + readonly stuckMinProgressM: number; + readonly unstickReverseM: number; + readonly unstickReverseSec: number; + readonly unstickRepeatSec: number; + readonly unstickMaxAttempts: number; + readonly jamRadiusM: number; + readonly jamCostMul: number; + readonly jamTtlSec: number; + readonly rubbleRadiusM: number; + readonly rubbleCostMul: number; + readonly rubbleTtlSec: number; + readonly wreckRadiusM: number; + readonly wreckCostMul: number; + readonly wreckTtlSec: number; +} + export const GROUND_AI_NAV_COST_KEYS = [ 'road', 'bridge', 'ground', 'rough', 'forest', 'crushable', 'shallowWater', 'chokepoint', ] as const satisfies readonly (keyof GroundAiNavCosts)[]; @@ -106,12 +146,8 @@ export interface GroundAiConfig { readonly steerSign: 1 | -1; readonly deadEchoSec: number; readonly controlTimeoutSec: number; - readonly cornerBrakeAccel: number; readonly movingFireSpeedRampMps: number; readonly pivotAngleDeg: number; - readonly stuckWindowSec: number; - readonly stuckMinMoveM: number; - readonly unstickReverseSec: number; readonly tacticalReverseDistM: number; readonly tacticalReverseMaxSec: number; }; @@ -120,9 +156,21 @@ export interface GroundAiConfig { readonly enabled: boolean; readonly allowFallback: boolean; readonly snapRadiusM: number; + /** Farther goal snap when a goal misses snapRadiusM (positions picked off the mesh). */ + readonly goalSnapRadiusM: number; + /** Time queued path searches may take per game frame. */ + readonly pathBudgetMsPerFrame: number; }; readonly navCostsTracked: GroundAiNavCosts; readonly navCostsWheeled: GroundAiNavCosts; + readonly pathFollow: GroundAiPathFollow; + /** + * Bake-time values the runtime must agree with (the rest of navBake is read by tools/navgen): + * riExtra objects up to this stock hp are crushable, so the bumper rays drive through them. + */ + readonly navBake: { + readonly crushableMaxRiExtraHp: number; + }; readonly perception: { readonly foliageTransparency: number; readonly nearSpotRangeM: number; @@ -298,19 +346,19 @@ function collectConfigEntries(c: GroundAiConfig): readonly DasEntry[] { ['WTO_AI_NAV_STEER_SIGN', 'float', c.navigation.steerSign], ['WTO_AI_NAV_DEAD_ECHO_SEC', 'float', c.navigation.deadEchoSec], ['WTO_AI_NAV_CONTROL_TIMEOUT_SEC', 'float', c.navigation.controlTimeoutSec], - ['WTO_AI_NAV_CORNER_BRAKE_ACCEL', 'float', c.navigation.cornerBrakeAccel], ['WTO_AI_NAV_MOVING_FIRE_SPEED_RAMP_MPS', 'float', c.navigation.movingFireSpeedRampMps], ['WTO_AI_NAV_PIVOT_ANGLE_DEG', 'float', c.navigation.pivotAngleDeg], - ['WTO_AI_NAV_STUCK_WINDOW_SEC', 'float', c.navigation.stuckWindowSec], - ['WTO_AI_NAV_STUCK_MIN_MOVE_M', 'float', c.navigation.stuckMinMoveM], - ['WTO_AI_NAV_UNSTICK_REV_SEC', 'float', c.navigation.unstickReverseSec], ['WTO_AI_NAV_TAC_REV_DIST_M', 'float', c.navigation.tacticalReverseDistM], ['WTO_AI_NAV_TAC_REV_MAX_SEC', 'float', c.navigation.tacticalReverseMaxSec], ['WTO_AI_NAVMESH_ENABLED', 'bool', c.navEngine.enabled], ['WTO_AI_NAVMESH_ALLOW_FALLBACK', 'bool', c.navEngine.allowFallback], ['WTO_AI_NAVMESH_SNAP_M', 'float', c.navEngine.snapRadiusM], + ['WTO_AI_NAVMESH_GOAL_SNAP_M', 'float', c.navEngine.goalSnapRadiusM], + ['WTO_AI_NAVMESH_PATH_BUDGET_US', 'float', c.navEngine.pathBudgetMsPerFrame * 1000], ...navCostEntries('T', c.navCostsTracked), ...navCostEntries('W', c.navCostsWheeled), + ...pathFollowEntries(c.pathFollow), + ['WTO_AI_NAVBAKE_CRUSH_MAX_HP', 'float', c.navBake.crushableMaxRiExtraHp], ['WTO_AI_PERC_FOLIAGE_TRANS', 'float', c.perception.foliageTransparency], ['WTO_AI_PERC_NEAR_SPOT_M', 'float', c.perception.nearSpotRangeM], ['WTO_AI_PERC_FIRING_SPOT_M', 'float', c.perception.firingSpotRangeM], @@ -387,6 +435,48 @@ function navCostEntries(prefix: 'T' | 'W', costs: GroundAiNavCosts): readonly Da ]); } +/** WTO_AI_PF_* constants of the path following, avoidance and unstick modules. */ +function pathFollowEntries(p: GroundAiPathFollow): readonly DasEntry[] { + return [ + ['WTO_AI_PF_REPLAN_SEC', 'float', p.replanIntervalSec], + ['WTO_AI_PF_REPLAN_GOAL_MOVE_M', 'float', p.replanGoalMoveM], + ['WTO_AI_PF_OFF_TRACK_REPLAN_M', 'float', p.offCorridorReplanM], + ['WTO_AI_PF_LOOKAHEAD_SEC', 'float', p.lookaheadTimeSec], + ['WTO_AI_PF_TRACKED_LOOK_MIN_M', 'float', p.trackedLookaheadMinM], + ['WTO_AI_PF_TRACKED_LOOK_MAX_M', 'float', p.trackedLookaheadMaxM], + ['WTO_AI_PF_WHEELED_LOOK_MIN_M', 'float', p.wheeledLookaheadMinM], + ['WTO_AI_PF_WHEELED_LOOK_MAX_M', 'float', p.wheeledLookaheadMaxM], + ['WTO_AI_PF_CORNER_ANGLE_DEG', 'float', p.cornerAngleDeg], + ['WTO_AI_PF_CORNER_LAT_ACCEL', 'float', p.cornerLateralAccelMps2], + ['WTO_AI_PF_BRAKE_DECEL', 'float', p.cornerBrakeDecelMps2], + ['WTO_AI_PF_ARRIVE_RADIUS_M', 'float', p.arriveRadiusM], + ['WTO_AI_PF_ARRIVE_MIN_MPS', 'float', p.arriveMinSpeedMps], + ['WTO_AI_PF_NARROW_WALL_M', 'float', p.narrowWallMarginM], + ['WTO_AI_PF_NARROW_SPEED_MPS', 'float', p.narrowSpeedMps], + ['WTO_AI_PF_BUMPER_RAY_M', 'float', p.bumperRayM], + ['WTO_AI_PF_BUMPER_STOP_M', 'float', p.bumperStopM], + ['WTO_AI_PF_BUMPER_BLOCK_SEC', 'float', p.bumperBlockSec], + ['WTO_AI_PF_TRAFFIC_TTC_SEC', 'float', p.trafficTtcSec], + ['WTO_AI_PF_AVOID_SHIFT_M', 'float', p.avoidShiftM], + ['WTO_AI_PF_YIELD_WAIT_SEC', 'float', p.yieldWaitMaxSec], + ['WTO_AI_PF_STUCK_WINDOW_SEC', 'float', p.stuckWindowSec], + ['WTO_AI_PF_STUCK_MIN_PROGRESS_M', 'float', p.stuckMinProgressM], + ['WTO_AI_PF_UNSTICK_REV_M', 'float', p.unstickReverseM], + ['WTO_AI_PF_UNSTICK_REV_SEC', 'float', p.unstickReverseSec], + ['WTO_AI_PF_UNSTICK_REPEAT_SEC', 'float', p.unstickRepeatSec], + ['WTO_AI_PF_UNSTICK_MAX_ATTEMPTS', 'int', p.unstickMaxAttempts], + ['WTO_AI_PF_JAM_RADIUS_M', 'float', p.jamRadiusM], + ['WTO_AI_PF_JAM_COST_MUL', 'float', p.jamCostMul], + ['WTO_AI_PF_JAM_TTL_SEC', 'float', p.jamTtlSec], + ['WTO_AI_PF_RUBBLE_RADIUS_M', 'float', p.rubbleRadiusM], + ['WTO_AI_PF_RUBBLE_COST_MUL', 'float', p.rubbleCostMul], + ['WTO_AI_PF_RUBBLE_TTL_SEC', 'float', p.rubbleTtlSec], + ['WTO_AI_PF_WRECK_RADIUS_M', 'float', p.wreckRadiusM], + ['WTO_AI_PF_WRECK_COST_MUL', 'float', p.wreckCostMul], + ['WTO_AI_PF_WRECK_TTL_SEC', 'float', p.wreckTtlSec], + ]; +} + function formatDasLiteral(name: string, kind: 'bool' | 'int' | 'float' | 'string', value: boolean | number | string): string { if (kind === 'bool') { if (typeof value !== 'boolean') throw new Error(`ground AI config ${name} must be boolean`); diff --git a/packages/patcher/src/index.ts b/packages/patcher/src/index.ts index f820fb3..3296136 100644 --- a/packages/patcher/src/index.ts +++ b/packages/patcher/src/index.ts @@ -77,6 +77,7 @@ export { type GroundAiLoadoutConfig, type GroundAiMode, type GroundAiNavCosts, + type GroundAiPathFollow, } from './ground-ai/ground-ai-config.ts'; export { rebuildGuiPack, type AppliedGuiPatch, type GuiPackResult } from './gui-pack.ts'; export { loadGuiPatches, type GuiScriptEdit, type GuiScriptPatch, type GuiScriptVariant } from './gui-patch-definition.ts';