diff --git a/apps/launcher/src/renderer/src/i18n/locales/en.json b/apps/launcher/src/renderer/src/i18n/locales/en.json index 7642034..34e5f6a 100644 --- a/apps/launcher/src/renderer/src/i18n/locales/en.json +++ b/apps/launcher/src/renderer/src/i18n/locales/en.json @@ -534,7 +534,7 @@ "fireControl": "Range bands, speed gates, barrel settle and ballistic safety", "navigation": "Drive backend, pivot turns and tactical reverse", "navEngine": "Baked map navigation packs, their fallback, and path costs per surface for tracked and wheeled vehicles", - "pathFollow": "Replanning, lookahead steering, corner and arrival braking, narrow passages, bumper rays, traffic yielding, three-level unstick and temporary path costs", + "pathFollow": "Replanning, lookahead steering, corner and arrival braking, narrow passages, bumper rays, passing stopped vehicles and wrecks, giving way, 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" @@ -682,7 +682,11 @@ "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", "goalSnapRadiusM": "Max distance a path goal may be moved onto the mesh", - "pathBudgetMsPerFrame": "Path search time per frame" + "pathBudgetMsPerFrame": "Path search time per frame", + "trafficCostPerPath": "Team traffic · extra path cost per teammate route", + "trafficCostMaxMul": "Team traffic · max path cost multiplier", + "trafficHoldSec": "Team traffic · how long a planned route counts", + "cornerOffsetM": "Distance path corners keep from the walls they turn around" }, "navCostsTracked": { "road": "Tracked · road cost", @@ -724,8 +728,14 @@ "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", + "stationarySpeedMps": "Speed below which a vehicle counts as an obstacle", + "passMarginM": "Gap kept between hulls when passing", + "passSpeedMps": "Speed cap while passing an obstacle", + "blockWaitSec": "Wait before a blocked passage is marked and replanned", + "blockTtlSec": "Blocked passage cost duration", + "contactGapM": "Gap to an obstacle that counts as contact", + "contactReverseSec": "Time in contact before backing off", "stuckWindowSec": "Stuck detection window", "stuckMinProgressM": "Min progress within the stuck window", "unstickReverseM": "Unstick reverse distance", @@ -735,6 +745,8 @@ "jamRadiusM": "Jam cost radius", "jamCostMul": "Jam path cost multiplier", "jamTtlSec": "Jam cost duration", + "giveUpRadiusM": "Given-up place cost radius", + "giveUpCostMul": "Given-up place path cost multiplier", "rubbleRadiusM": "Fresh obstacle cost radius", "rubbleCostMul": "Fresh obstacle path cost multiplier", "rubbleTtlSec": "Fresh obstacle cost duration", 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 94ee57a..2f0f6d2 100644 --- a/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json +++ b/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json @@ -534,7 +534,7 @@ "fireControl": "距离分档、车速门槛、稳定等待与弹道防误伤", "navigation": "驱动方式、原地转向与战术倒车", "navEngine": "离线地图导航包的启用与降级,以及履带 / 轮式车在各类地表上的寻路代价", - "pathFollow": "重新寻路、前瞻跟路、弯道与到达前减速、窄路限速、车头射线、会车让路、三级脱困与临时寻路代价", + "pathFollow": "重新寻路、前瞻跟路、弯道与到达前减速、窄路限速、车头射线、绕过停车和残骸、会车让路、三级脱困与临时寻路代价", "crowd": "友军安全间距与扎堆疏散", "terrain": "爬坡 / 下坡角度、涉水深度与探头限制", "runtime": "脚本刷新间隔与调试遥测日志" @@ -682,7 +682,11 @@ "allowFallback": "缺少或损坏时整局退回旧寻路", "snapRadiusM": "起终点吸附到导航网格的最大距离", "goalSnapRadiusM": "目标点吸附到导航网格的最远距离", - "pathBudgetMsPerFrame": "每帧寻路计算时间上限" + "pathBudgetMsPerFrame": "每帧寻路计算时间上限", + "trafficCostPerPath": "同队分流 · 每条队友路线增加的寻路代价", + "trafficCostMaxMul": "同队分流 · 寻路代价最高倍率", + "trafficHoldSec": "同队分流 · 规划出的路线计入多久", + "cornerOffsetM": "路线拐点离所绕墙角的距离" }, "navCostsTracked": { "road": "履带车 · 道路代价", @@ -724,8 +728,14 @@ "bumperStopM": "车头射线碰到障碍时的停车距离", "bumperBlockSec": "被挡多久后上报障碍", "trafficTtcSec": "车辆碰撞预判时间", - "avoidShiftM": "绕开车辆和残骸的横移距离", "yieldWaitMaxSec": "窄路让路最长等待时间", + "stationarySpeedMps": "车速低于多少算作障碍物", + "passMarginM": "绕行时与对方车体保持的间距", + "passSpeedMps": "绕行障碍时的限速", + "blockWaitSec": "无路可绕时等待多久后标记并重新寻路", + "blockTtlSec": "被堵路段代价持续时间", + "contactGapM": "离障碍多近算作顶上", + "contactReverseSec": "顶上多久后倒车", "stuckWindowSec": "卡住检测窗口时长", "stuckMinProgressM": "检测窗口内的最小前进距离", "unstickReverseM": "脱困倒车距离", @@ -735,6 +745,8 @@ "jamRadiusM": "堵车点代价半径", "jamCostMul": "堵车点寻路代价倍率", "jamTtlSec": "堵车点代价持续时间", + "giveUpRadiusM": "放弃地点代价半径", + "giveUpCostMul": "放弃地点寻路代价倍率", "rubbleRadiusM": "新障碍代价半径", "rubbleCostMul": "新障碍寻路代价倍率", "rubbleTtlSec": "新障碍代价持续时间", 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 f94425d..b9325f5 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 @@ -278,6 +278,10 @@ export const BOT_TUNING_GROUPS: readonly BotTuningGroup[] = [ num('navEngine', 'snapRadiusM', 2, 40, 'm'), num('navEngine', 'goalSnapRadiusM', 5, 150, 'm'), num('navEngine', 'pathBudgetMsPerFrame', 0.05, 5, 'ms'), + num('navEngine', 'trafficCostPerPath', 0, 3), + num('navEngine', 'trafficCostMaxMul', 1, 10), + num('navEngine', 'trafficHoldSec', 0, 120, 's'), + num('navEngine', 'cornerOffsetM', 0, 5, 'm'), ...NAV_COST_FIELDS.map((field) => num('navCostsTracked', field, 0.1, 20)), ...NAV_COST_FIELDS.map((field) => num('navCostsWheeled', field, 0.1, 20)), ], @@ -306,8 +310,14 @@ export const BOT_TUNING_GROUPS: readonly BotTuningGroup[] = [ 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', 'stationarySpeedMps', 0.2, 4, 'm/s'), + num('pathFollow', 'passMarginM', 0.2, 4, 'm'), + num('pathFollow', 'passSpeedMps', 1, 12, 'm/s'), + num('pathFollow', 'blockWaitSec', 0.5, 15, 's'), + num('pathFollow', 'blockTtlSec', 3, 120, 's'), + num('pathFollow', 'contactGapM', 0.2, 3, 'm'), + num('pathFollow', 'contactReverseSec', 0.3, 5, 's'), num('pathFollow', 'stuckWindowSec', 1, 15, 's'), num('pathFollow', 'stuckMinProgressM', 0.2, 10, 'm'), num('pathFollow', 'unstickReverseM', 2, 25, 'm'), @@ -317,6 +327,8 @@ export const BOT_TUNING_GROUPS: readonly BotTuningGroup[] = [ num('pathFollow', 'jamRadiusM', 2, 50, 'm'), num('pathFollow', 'jamCostMul', 1, 50), num('pathFollow', 'jamTtlSec', 5, 600, 's'), + num('pathFollow', 'giveUpRadiusM', 3, 50, 'm'), + num('pathFollow', 'giveUpCostMul', 1, 200), num('pathFollow', 'rubbleRadiusM', 1, 40, 'm'), num('pathFollow', 'rubbleCostMul', 1, 50), num('pathFollow', 'rubbleTtlSec', 5, 600, 's'), diff --git a/apps/launcher/src/shared/schemas/tuning.ts b/apps/launcher/src/shared/schemas/tuning.ts index be651db..94b4217 100644 --- a/apps/launcher/src/shared/schemas/tuning.ts +++ b/apps/launcher/src/shared/schemas/tuning.ts @@ -102,6 +102,10 @@ const GroundAiNavEngineSchema = z.object({ snapRadiusM: z.number().min(2).max(40), goalSnapRadiusM: z.number().min(5).max(150), pathBudgetMsPerFrame: z.number().min(0.05).max(5), + trafficCostPerPath: z.number().min(0).max(3), + trafficCostMaxMul: z.number().min(1).max(10), + trafficHoldSec: z.number().min(0).max(120), + cornerOffsetM: z.number().min(0).max(5), }); const navCost = z.number().min(0.1).max(20); @@ -136,8 +140,14 @@ const GroundAiPathFollowSchema = z.object({ 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), + stationarySpeedMps: z.number().min(0.2).max(4), + passMarginM: z.number().min(0.2).max(4), + passSpeedMps: z.number().min(1).max(12), + blockWaitSec: z.number().min(0.5).max(15), + blockTtlSec: z.number().min(3).max(120), + contactGapM: z.number().min(0.2).max(3), + contactReverseSec: z.number().min(0.3).max(5), stuckWindowSec: z.number().min(1).max(15), stuckMinProgressM: z.number().min(0.2).max(10), unstickReverseM: z.number().min(2).max(25), @@ -147,6 +157,8 @@ const GroundAiPathFollowSchema = z.object({ jamRadiusM: z.number().min(2).max(50), jamCostMul: z.number().min(1).max(50), jamTtlSec: z.number().min(5).max(600), + giveUpRadiusM: z.number().min(3).max(50), + giveUpCostMul: z.number().min(1).max(200), rubbleRadiusM: z.number().min(1).max(40), rubbleCostMul: z.number().min(1).max(50), rubbleTtlSec: z.number().min(5).max(600), diff --git a/apps/server/src/tuning/ground-ai-tuning.ts b/apps/server/src/tuning/ground-ai-tuning.ts index 53c7014..1d94c8c 100644 --- a/apps/server/src/tuning/ground-ai-tuning.ts +++ b/apps/server/src/tuning/ground-ai-tuning.ts @@ -189,6 +189,10 @@ function readNavEngineSection(engine: TuningReader): GroundAiTuning['navEngine'] 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 }), + trafficCostPerPath: engine.number('trafficCostPerPath', { min: 0, max: 3 }), + trafficCostMaxMul: engine.number('trafficCostMaxMul', { min: 1, max: 10 }), + trafficHoldSec: engine.number('trafficHoldSec', { min: 0, max: 120 }), + cornerOffsetM: engine.number('cornerOffsetM', { min: 0, max: 5 }), }; } @@ -234,8 +238,14 @@ function readPathFollowSection(pf: TuningReader): GroundAiPathFollow { 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), + stationarySpeedMps: n('stationarySpeedMps', 0.2, 4), + passMarginM: n('passMarginM', 0.2, 4), + passSpeedMps: n('passSpeedMps', 1, 12), + blockWaitSec: n('blockWaitSec', 0.5, 15), + blockTtlSec: n('blockTtlSec', 3, 120), + contactGapM: n('contactGapM', 0.2, 3), + contactReverseSec: n('contactReverseSec', 0.3, 5), stuckWindowSec: n('stuckWindowSec', 1, 15), stuckMinProgressM: n('stuckMinProgressM', 0.2, 10), unstickReverseM: n('unstickReverseM', 2, 25), @@ -245,6 +255,8 @@ function readPathFollowSection(pf: TuningReader): GroundAiPathFollow { jamRadiusM: n('jamRadiusM', 2, 50), jamCostMul: n('jamCostMul', 1, 50), jamTtlSec: n('jamTtlSec', 5, 600), + giveUpRadiusM: n('giveUpRadiusM', 3, 50), + giveUpCostMul: n('giveUpCostMul', 1, 200), rubbleRadiusM: n('rubbleRadiusM', 1, 40), rubbleCostMul: n('rubbleCostMul', 1, 50), rubbleTtlSec: n('rubbleTtlSec', 5, 600), diff --git a/apps/server/tuning/ground-ai.jsonc b/apps/server/tuning/ground-ai.jsonc index 95d6aba..f19fab9 100644 --- a/apps/server/tuning/ground-ai.jsonc +++ b/apps/server/tuning/ground-ai.jsonc @@ -113,7 +113,15 @@ // this value (wooden fences 2, dry-stone fences 12, car wrecks 20; buses 40). "crushableMaxRiExtraHp": 20, // Passages narrower than this many standard-tier vehicle widths are flagged as chokepoints. - "chokepointMaxWidthVehicles": 2.0 + "chokepointMaxWidthVehicles": 2.0, + // Water up to maxFordDepthM is forded (shallow water cost). Deeper water is a wall: besides the + // vehicle's half width, the mesh keeps deepWaterMarginM more ground from it where the bank is + // less than deepWaterBankHeightM above the water line, + // because low banks slope into the water and a hull at the water line slides in. Higher quays + // and ramps keep only the half width. + "maxFordDepthM": 0.9, + "deepWaterMarginM": 1.5, + "deepWaterBankHeightM": 1.0 }, "navigation": { @@ -144,7 +152,15 @@ // 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 + "pathBudgetMsPerFrame": 0.5, + // Team traffic: each teammate path planned within trafficHoldSec through a stretch of mesh + // raises its cost for the team's next searches by trafficCostPerPath, up to trafficCostMaxMul, + // so a team spreads over parallel routes instead of queueing on one road. + "trafficCostPerPath": 0.35, + "trafficCostMaxMul": 2.5, + "trafficHoldSec": 12.0, + // Path corners are moved this far away from the building or wall they turn around. + "cornerOffsetM": 1.5 }, // Path cost multipliers per surface for tracked vehicles; chokepoint multiplies the surface cost @@ -199,10 +215,21 @@ "bumperRayM": 7.0, "bumperStopM": 1.5, "bumperBlockSec": 0.6, - // Vehicles and wrecks that come within reach in trafficTtcSec: follow, step aside, or give way. + // Moving vehicles that come within reach in trafficTtcSec: follow them, or in narrow passages + // give way to the bigger one for at most yieldWaitMaxSec. "trafficTtcSec": 2.5, - "avoidShiftM": 3.0, "yieldWaitMaxSec": 3.0, + // Vehicles slower than stationarySpeedMps, wrecks and players' vehicles in the way are passed + // on the side the mesh leaves room, keeping passMarginM between hulls, at up to passSpeedMps. + "stationarySpeedMps": 1.0, + "passMarginM": 0.8, + "passSpeedMps": 4.0, + // No side free: stop short, and after blockWaitSec mark the obstacle for path searches for + // blockTtlSec and plan again. A hull within contactGapM of it for contactReverseSec backs off. + "blockWaitSec": 2.0, + "blockTtlSec": 15.0, + "contactGapM": 0.8, + "contactReverseSec": 1.0, // Less progress than stuckMinProgressM within stuckWindowSec while wanting to move is stuck. "stuckWindowSec": 3.0, "stuckMinProgressM": 0.8, @@ -211,11 +238,15 @@ "unstickRepeatSec": 8.0, "unstickMaxAttempts": 3, // Temporary path costs: jams found by unstick, fresh obstacles hit by the front rays, wrecks. + // A place given up on after unstickMaxAttempts is all but closed (giveUp*), so the next order + // routes elsewhere instead of returning to it. "jamRadiusM": 10.0, - "jamCostMul": 4.0, + "jamCostMul": 12.0, "jamTtlSec": 45.0, + "giveUpRadiusM": 15.0, + "giveUpCostMul": 40.0, "rubbleRadiusM": 6.0, - "rubbleCostMul": 8.0, + "rubbleCostMul": 25.0, "rubbleTtlSec": 90.0, "wreckRadiusM": 6.0, "wreckCostMul": 6.0, diff --git a/game-ai/ground/wto_ai_avoid_common.das b/game-ai/ground/wto_ai_avoid_common.das index c784f06..650bfbe 100644 --- a/game-ai/ground/wto_ai_avoid_common.das +++ b/game-ai/ground/wto_ai_avoid_common.das @@ -1,8 +1,7 @@ -// 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. +// Fresh static obstacles on top of the path: what the baked mesh cannot know. Two short physical +// rays from the front corners of the hull catch rubble and collapsed buildings and let the vehicle +// drive through what it can knock down (fences, light walls). Vehicles and wrecks are handled by +// wto_ai_traffic_common. options indenting = 2 options no_global_heap = true module wto_ai_avoid_common shared @@ -14,9 +13,7 @@ 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 @@ -83,94 +80,3 @@ def public wto_avoid_bumper(myPos, dir : float3; spec : WtoVehicleSpec const&) : 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_lanes_build_common.das b/game-ai/ground/wto_ai_lanes_build_common.das index d96aa88..a0b5e4a 100644 --- a/game-ai/ground/wto_ai_lanes_build_common.das +++ b/game-ai/ground/wto_ai_lanes_build_common.das @@ -106,9 +106,9 @@ def private wto_lanes_request_legs(world : WtoWorldSnap const&; army, capIdx, k 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) + WTO_NAVMESH_FILTER_TRACKED, 0, 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) + WTO_NAVMESH_FILTER_TRACKED, 0, relay, world.caps[capIdx].center) lanes.phase[k] = WTO_LANES_LEGS // Center path queued: take it once found and queue the flank legs. @@ -166,7 +166,7 @@ def public wto_lanes_ensure_cap(world : WtoWorldSnap const&; army, capIdx : int; 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) + 0, 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) diff --git a/game-ai/ground/wto_ai_nav_common.das b/game-ai/ground/wto_ai_nav_common.das index cb614e3..10a34c8 100644 --- a/game-ai/ground/wto_ai_nav_common.das +++ b/game-ai/ground/wto_ai_nav_common.das @@ -1,8 +1,9 @@ // 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). +// lookahead point it can reach in a straight line (follow), passes or follows vehicles and wrecks +// (traffic), slows for corners, narrow passages and fresh obstacles (avoid), backs off at once +// when pressed against a vehicle, and escalates when it stops making progress (unstick). options indenting = 2 options no_global_heap = true module wto_ai_nav_common shared @@ -19,6 +20,7 @@ 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_traffic_common require %appGame.wtoai.wto_ai_unstick_common [never_inline] @@ -89,21 +91,23 @@ def private wto_nav_probe_mesh(navState : int; myPos : float3; var slot : WtoBot 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. +// Lookahead point the bot can drive to in a straight line: around a corner the full lookahead +// would cut through the building the path turns around, so it is pulled back along the path +// until the mesh allows the straight line, at worst to the next path corner. [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 +def private wto_nav_visible_target(navState : int; myPos : float3; lookM : float; slot : WtoBotSlot const&) : float3 + assume rt = slot.route + var look = lookM + var target = wto_follow_target(rt, look) + if navState != WTO_NAVMESH_LOADED || rt.tier < 0 || rt.source != WTO_ROUTE_SRC_MESH 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 + for _try in range(3) + var frac = 0.0 + if wto_navq_raycast(rt.tier, rt.filter, myPos, target, frac) != 0 + return target + look *= 0.5 + target = wto_follow_target(rt, look) + return rt.corridor[min(rt.segIdx + 1, rt.corridorLen - 1)] // A fresh obstacle in front for bumperBlockSec: mark it for path searches and plan again. [never_inline] @@ -148,11 +152,16 @@ def private wto_nav_follow(var world : WtoWorldSnap&; navState : int; now : floa 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 pathTarget = wto_nav_visible_target(navState, myPos, lookM, slot) 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) + wto_traffic_update(world, navState, now, myPos, pathDir, speedNow, narrow, slot) + if wto_traffic_in_contact(now, slot.nav) + wto_unstick_contact(navState, now, myPos, hullFwd, slot) + if !wto_unstick_reversing(now, myPos, slot) + wto_nav_halt(myPos, hullFwd, slot) + return + let target = slot.nav.avoidActive ? slot.nav.avoidTarget : pathTarget let dir = wto_xz_normalize(target - myPos, hullFwd) let speed = wto_nav_speed(navState, now, myPos, dir, lookM, narrow, slot) slot.nav.steerDir = dir diff --git a/game-ai/ground/wto_ai_nav_types_common.das b/game-ai/ground/wto_ai_nav_types_common.das index 318f4db..e0bd269 100644 --- a/game-ai/ground/wto_ai_nav_types_common.das +++ b/game-ai/ground/wto_ai_nav_types_common.das @@ -49,8 +49,13 @@ struct public WtoNavState bumperBlockedSince : float = -100.0 yieldUntil : float = -100.0 yieldCooldownUntil : float = -100.0 - avoidShiftM : float = 0.0 + avoidActive : bool = false + avoidTarget : float3 = float3(0.0, 0.0, 0.0) + avoidSide : float = 0.0 + avoidSideUntil : float = -100.0 avoidSpeedCap : float = 99.0 + blockedSince : float = -100.0 + contactSince : float = -100.0 stuckOrigin : float3 = float3(0.0, 0.0, 0.0) stuckCheckAt : float = -100.0 unstickAnchor : float3 = float3(0.0, 0.0, 0.0) @@ -61,5 +66,7 @@ struct public WtoNavState reverseUntil : float = -100.0 reverseCount : int = 0 unstickEvents : int = 0 + contactEvents : int = 0 + blockEvents : 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 e14f978..6e17912 100644 --- a/game-ai/ground/wto_ai_navmesh_common.das +++ b/game-ai/ground/wto_ai_navmesh_common.das @@ -52,6 +52,14 @@ 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}") +// Team traffic and corner offset of the battle's searches. +[never_inline] +def private wto_navmesh_add_tuning(var blk : DataBlock&) + add(blk, "trafficPerPath", "{WTO_AI_NAVMESH_TRAFFIC_PER_PATH}") + add(blk, "trafficMaxMul", "{WTO_AI_NAVMESH_TRAFFIC_MAX_MUL}") + add(blk, "trafficHoldSec", "{WTO_AI_NAVMESH_TRAFFIC_HOLD_SEC}") + add(blk, "cornerOffset", "{WTO_AI_NAVMESH_CORNER_OFFSET_M}") + // Battle loading: start reading this battle's pack on a background thread. [never_inline] def public wto_navmesh_prefetch() @@ -76,6 +84,7 @@ def public wto_navmesh_load() : int add(blk, "op", "load_map") add(blk, "allowFallback", WTO_AI_NAVMESH_ALLOW_FALLBACK ? "1" : "0") wto_navmesh_add_costs(blk) + wto_navmesh_add_tuning(blk) call_mission_action("wtoNav", blk) let answer = datablock_getStr(blk, "state", "") if answer == "loaded" @@ -115,7 +124,7 @@ def private wto_navmesh_self_test(world : WtoWorldSnap const&; var nm : WtoNavme 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) + WTO_NAVMESH_FILTER_TRACKED, 0, world.teamSpawnCenter[army], world.caps[0].center) nm.selfTestPhase = 1 return if nm.selfTestPhase != 1 @@ -176,4 +185,6 @@ def public wto_navmesh_log_stats(var nm : WtoNavmeshBattle&) 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") + let traffic = datablock_getInt(blk, "traffic", 0) + let moved = datablock_getInt(blk, "cornersMoved", 0) + print("WTO_AI|NAVMESH_STATS|paths={queries}|failures={failures}|avgUs={avgUs}|maxUs={maxUs}|maxFrames={maxFrames}|pumpMaxUs={pumpMaxUs}|pending={pending}|dynamic={dynCount}|meshQueries={meshQueries}|traffic={traffic}|cornersMoved={moved}\n") diff --git a/game-ai/ground/wto_ai_navquery_common.das b/game-ai/ground/wto_ai_navquery_common.das index ffac737..626f01b 100644 --- a/game-ai/ground/wto_ai_navquery_common.das +++ b/game-ai/ground/wto_ai_navquery_common.das @@ -65,15 +65,17 @@ def private wto_navq_get_point(blk : DataBlock const&; kx, ky, kz : string) : fl 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). +// Queues a path search in native slot `slot`; returns its ticket (0 when refused). With a team +// (`group` 1 or 2) the search avoids routes teammates planned recently and counts as one itself. [never_inline] -def public wto_navq_path_request(slot, tier, costFilter : int; start, goal : float3) : int +def public wto_navq_path_request(slot, tier, costFilter, group : 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, "group", "{group}") add(blk, "snap", "{WTO_AI_NAVMESH_SNAP_M}") add(blk, "goalSnap", "{WTO_AI_NAVMESH_GOAL_SNAP_M}") wto_navq_add_point(blk, "s", start) diff --git a/game-ai/ground/wto_ai_route_common.das b/game-ai/ground/wto_ai_route_common.das index 9185276..a249f93 100644 --- a/game-ai/ground/wto_ai_route_common.das +++ b/game-ai/ground/wto_ai_route_common.das @@ -71,7 +71,7 @@ def private wto_route_request(navState, slotIdx : int; now : float; myPos, goal rt.replanRequested = false rt.requests++ if navState == WTO_NAVMESH_LOADED - rt.ticket = wto_navq_path_request(slotIdx, rt.tier, rt.filter, myPos, goal) + rt.ticket = wto_navq_path_request(slotIdx, rt.tier, rt.filter, slot.army, myPos, goal) rt.pending = rt.ticket > 0 rt.pendingGoal = goal return diff --git a/game-ai/ground/wto_ai_traffic_common.das b/game-ai/ground/wto_ai_traffic_common.das new file mode 100644 index 0000000..9cc3bbf --- /dev/null +++ b/game-ai/ground/wto_ai_traffic_common.das @@ -0,0 +1,239 @@ +// Vehicles and wrecks on the path: what the baked mesh cannot know. Distances use each hull's +// length and width along the bot's heading, not a circle. A vehicle slower than stationarySpeedMps, +// a wreck or a parked player is an obstacle whatever its size: the bot passes it on the side where +// the mesh leaves room for its hull, or stops short and, after blockWaitSec, marks it for path +// searches and plans again. Moving traffic ahead is followed at its speed; oncoming traffic is +// passed in the open, and in narrow passages the bigger vehicle goes first. +options indenting = 2 +options no_global_heap = true +module wto_ai_traffic_common shared + +require ecs +require math +require %appGame.wtoai.wto_ai_config_common +require %appGame.wtoai.wto_ai_types_common +require %appGame.wtoai.wto_ai_nav_types_common +require %appGame.wtoai.wto_ai_navquery_common +require %appGame.wtoai.wto_ai_navmesh_common + +// A vehicle or wreck seen from the bot: how far ahead (along) and to the left (lat) its centre is, +// and the half extents of its hull along and across the bot's heading. +[safe_when_uninitialized] +struct private WtoTrafficBody + idx : int = -1 + isWreck : bool = false + pos : float3 = float3(0.0, 0.0, 0.0) + vel : float3 = float3(0.0, 0.0, 0.0) + along : float = 0.0 + lat : float = 0.0 + extAlong : float = 0.0 + extLat : float = 0.0 + +[never_inline] +def private wto_traffic_frame(myPos, dir, pos, vel, fwd : float3; halfLen, halfWid : float; var body : WtoTrafficBody&) + let left = float3(-dir.z, 0.0, dir.x) + let rel = float3(pos.x - myPos.x, 0.0, pos.z - myPos.z) + let fd = abs(dot(fwd, dir)) + let fl = abs(dot(fwd, left)) + body.pos = pos + body.vel = vel + body.along = dot(rel, dir) + body.lat = dot(rel, left) + body.extAlong = halfLen * fd + halfWid * fl + body.extLat = halfLen * fl + halfWid * fd + +// Free distance from the bot's front to the body's near end; negative once they overlap. +[never_inline] +def private wto_traffic_gap(body : WtoTrafficBody const&; spec : WtoVehicleSpec const&) : float + return body.along - spec.halfLen - body.extAlong + +// Sideways distance between the centres that lets the hulls pass with passMarginM between them. +[never_inline] +def private wto_traffic_need(body : WtoTrafficBody const&; spec : WtoVehicleSpec const&) : float + return spec.halfWid + body.extLat + WTO_AI_PF_PASS_MARGIN_M + +[never_inline] +def private wto_traffic_in_lane(body : WtoTrafficBody const&; spec : WtoVehicleSpec const&; maxGap : float) : bool + return body.along > 0.0 && abs(body.lat) < wto_traffic_need(body, spec) && wto_traffic_gap(body, spec) < maxGap + +// The nearest standing body (stopped vehicle or wreck) in the bot's lane within `lookM`. +[never_inline] +def private wto_traffic_find_standing(world : WtoWorldSnap const&; myPos, dir : float3; lookM : float; + slot : WtoBotSlot const&; var best : WtoTrafficBody&) : bool + var maxGap = lookM + var found = false + var body = WtoTrafficBody() + for i in range(world.unitCount) + assume u = world.units[i] + let flatVel = float3(u.vel.x, 0.0, u.vel.z) + if !u.isAlive || !u.isGround || u.eid == slot.eid || length(flatVel) >= WTO_AI_PF_STATIONARY_MPS + continue + wto_traffic_frame(myPos, dir, u.pos, flatVel, u.hullFwd, u.halfLen, u.halfWid, body) + if wto_traffic_in_lane(body, slot.spec, maxGap) + maxGap = wto_traffic_gap(body, slot.spec) + body.idx = i + body.isWreck = false + best = body + found = true + let still = float3(0.0, 0.0, 0.0) + for w in range(world.wreckCount) + assume wr = world.wrecks[w] + wto_traffic_frame(myPos, dir, wr.pos, still, wr.hullFwd, wr.halfLen, wr.halfWid, body) + if wto_traffic_in_lane(body, slot.spec, maxGap) + maxGap = wto_traffic_gap(body, slot.spec) + body.idx = w + body.isWreck = true + best = body + found = true + return found + +// Whether a moving body and the bot come within passing distance in the next trafficTtcSec. +[never_inline] +def private wto_traffic_meets(dir : float3; speedMps : float; body : WtoTrafficBody const&; spec : WtoVehicleSpec const&) : bool + let left = float3(-dir.z, 0.0, dir.x) + let closeAlong = dot(body.vel, dir) - speedMps + let closeLat = dot(body.vel, left) + let need = wto_traffic_need(body, spec) + let reach = spec.halfLen + body.extAlong + WTO_AI_PF_PASS_MARGIN_M + for k in range(5) + let t = WTO_AI_PF_TRAFFIC_TTC_SEC * float(k) * 0.25 + if abs(body.lat + closeLat * t) < need && abs(body.along + closeAlong * t) < reach + return true + return false + +// Moving vehicles: one ahead in the lane going the same way caps the speed so the bot can still +// stop behind it; the nearest one the bot would meet is returned in `oncoming`. +[never_inline] +def private wto_traffic_moving(world : WtoWorldSnap const&; myPos, dir : float3; speedMps : float; + var slot : WtoBotSlot&; var oncoming : WtoTrafficBody&) : bool + let lookM = max(WTO_AI_PF_BUMPER_RAY_M, speedMps * WTO_AI_PF_TRAFFIC_TTC_SEC) + var nearest = 99999.0 + var body = WtoTrafficBody() + for i in range(world.unitCount) + assume u = world.units[i] + let flatVel = float3(u.vel.x, 0.0, u.vel.z) + let speed = length(flatVel) + if !u.isAlive || !u.isGround || u.eid == slot.eid || speed < WTO_AI_PF_STATIONARY_MPS + continue + wto_traffic_frame(myPos, dir, u.pos, flatVel, u.hullFwd, u.halfLen, u.halfWid, body) + let ahead = dot(flatVel, dir) + if ahead > 0.7 * speed + if wto_traffic_in_lane(body, slot.spec, lookM) + let room = max(0.0, wto_traffic_gap(body, slot.spec) - WTO_AI_PF_BUMPER_STOP_M) + slot.nav.avoidSpeedCap = min(slot.nav.avoidSpeedCap, ahead + sqrt(2.0 * WTO_AI_PF_BRAKE_DECEL * room)) + continue + if body.along > 0.0 && body.along < nearest && wto_traffic_meets(dir, speedMps, body, slot.spec) + nearest = body.along + body.idx = i + oncoming = body + return nearest < 99990.0 + +// Side room for the hull: the mesh must allow the straight line to the passing point. +[never_inline] +def private wto_traffic_room(navState : int; myPos, wp : float3; slot : WtoBotSlot const&) : bool + if navState != WTO_NAVMESH_LOADED || slot.route.tier < 0 + return true + var frac = 0.0 + return wto_navq_raycast(slot.route.tier, slot.route.filter, myPos, wp, frac) != 0 + +// Steers past `body` on the side with room: the nearer side first (or the side chosen within the +// last blockWaitSec, so the bot does not swing between sides), then the other. +[never_inline] +def private wto_traffic_pass(navState : int; now : float; myPos, dir : float3; body : WtoTrafficBody const&; + var slot : WtoBotSlot&) : bool + assume nav = slot.nav + let left = float3(-dir.z, 0.0, dir.x) + let need = wto_traffic_need(body, slot.spec) + var side = abs(body.lat + need) <= abs(body.lat - need) ? 1.0 : -1.0 + if now < nav.avoidSideUntil && nav.avoidSide != 0.0 + side = nav.avoidSide + let beyond = max(body.along + body.extAlong + slot.spec.halfLen, WTO_AI_PF_BUMPER_RAY_M) + for _k in range(2) + let wp = myPos + dir * beyond + left * (body.lat + side * need) + if wto_traffic_room(navState, myPos, wp, slot) + nav.avoidActive = true + nav.avoidTarget = wp + nav.avoidSide = side + nav.avoidSideUntil = now + WTO_AI_PF_BLOCK_WAIT_SEC + nav.avoidSpeedCap = min(nav.avoidSpeedCap, WTO_AI_PF_PASS_SPEED_MPS) + return true + side = -side + return false + +// No way past: stop short; after blockWaitSec mark the body for path searches and plan again. +[never_inline] +def private wto_traffic_blocked(navState : int; now : float; body : WtoTrafficBody const&; var slot : WtoBotSlot&) + assume nav = slot.nav + nav.avoidSpeedCap = min(nav.avoidSpeedCap, max(0.0, wto_traffic_gap(body, slot.spec) - WTO_AI_PF_CONTACT_GAP_M)) + if nav.blockedSince < -50.0 + nav.blockedSince = now + return + if now - nav.blockedSince < WTO_AI_PF_BLOCK_WAIT_SEC + return + nav.blockedSince = -100.0 + nav.blockEvents++ + if navState == WTO_NAVMESH_LOADED + wto_navq_add_dynamic(body.pos, wto_traffic_need(body, slot.spec), WTO_AI_PF_RUBBLE_COST_MUL, now + WTO_AI_PF_BLOCK_TTL_SEC) + slot.route.replanRequested = true + print("WTO_AI|NAV_BLOCKED_BY|eid={uint(slot.eid)}|wreck={body.isWreck}|pos={body.pos}\n") + +// The bigger vehicle goes first; equal sizes by entity id. Players always keep their way. +[never_inline] +def private wto_traffic_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_traffic_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 = min(nav.avoidSpeedCap, now < nav.yieldUntil ? 0.0 : WTO_AI_PF_PASS_SPEED_MPS) + +// Hull pressed against a standing body: when that started (cleared once there is room again). +[never_inline] +def private wto_traffic_contact(now, gap, speedMps : float; var nav : WtoNavState&) + if gap >= WTO_AI_PF_CONTACT_GAP_M || speedMps >= WTO_AI_PF_STATIONARY_MPS + nav.contactSince = -100.0 + elif nav.contactSince < -50.0 + nav.contactSince = now + +// True after contactReverseSec pressed against a vehicle or wreck: the caller backs off at once. +[never_inline] +def public wto_traffic_in_contact(now : float; nav : WtoNavState const&) : bool + return nav.contactSince > -50.0 && now - nav.contactSince >= WTO_AI_PF_CONTACT_REVERSE_SEC + +// Per nav tick: sets slot.nav.avoidActive / avoidTarget (a point beside an obstacle to steer at) +// and avoidSpeedCap for the bot heading along `dir` on its path. +[never_inline] +def public wto_traffic_update(world : WtoWorldSnap const&; navState : int; now : float; myPos, dir : float3; + speedMps : float; narrow : bool; var slot : WtoBotSlot&) + assume nav = slot.nav + nav.avoidActive = false + nav.avoidSpeedCap = 99.0 + var oncoming = WtoTrafficBody() + let meets = wto_traffic_moving(world, myPos, dir, speedMps, slot, oncoming) + var standing = WtoTrafficBody() + let lookM = max(WTO_AI_PF_BUMPER_RAY_M, speedMps * WTO_AI_PF_TRAFFIC_TTC_SEC) + if wto_traffic_find_standing(world, myPos, dir, lookM, slot, standing) + wto_traffic_contact(now, wto_traffic_gap(standing, slot.spec), speedMps, nav) + if !wto_traffic_pass(navState, now, myPos, dir, standing, slot) + wto_traffic_blocked(navState, now, standing, slot) + return + nav.blockedSince = -100.0 + nav.contactSince = -100.0 + if !meets + nav.yieldUntil = -100.0 + return + if !narrow + if !wto_traffic_pass(navState, now, myPos, dir, oncoming, slot) + nav.avoidSpeedCap = min(nav.avoidSpeedCap, WTO_AI_PF_PASS_SPEED_MPS) + return + if !wto_traffic_has_priority(slot, world.units[oncoming.idx]) + wto_traffic_yield(now, nav) diff --git a/game-ai/ground/wto_ai_types_common.das b/game-ai/ground/wto_ai_types_common.das index d388ff8..ca95f11 100644 --- a/game-ai/ground/wto_ai_types_common.das +++ b/game-ai/ground/wto_ai_types_common.das @@ -88,6 +88,7 @@ struct public WtoUnitSnap struct public WtoWreckSnap eid : EntityId = INVALID_ENTITY_ID pos : float3 = float3(0.0, 0.0, 0.0) + hullFwd : float3 = float3(1.0, 0.0, 0.0) halfLen : float = 3.4 halfWid : float = 1.75 diff --git a/game-ai/ground/wto_ai_unstick_common.das b/game-ai/ground/wto_ai_unstick_common.das index b9c4249..7f4b5bf 100644 --- a/game-ai/ground/wto_ai_unstick_common.das +++ b/game-ai/ground/wto_ai_unstick_common.das @@ -60,12 +60,23 @@ def private wto_unstick_mark(var world : WtoWorldSnap&; navState : int; now : fl 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) + wto_unstick_mark(world, navState, now, ahead, WTO_AI_PF_GIVE_UP_RADIUS_M, WTO_AI_PF_GIVE_UP_COST_MUL) slot.order.expiresAt = now slot.nav.unreachableEvents++ slot.nav.unstickAttempts = 0 slot.nav.unstickLevel = 0 +// Pressed against a vehicle or wreck: back up at once instead of waiting for the stuck window, +// and plan again so the next path or passing point accounts for it. +[never_inline] +def public wto_unstick_contact(navState : int; now : float; myPos, hullFwd : float3; var slot : WtoBotSlot&) + slot.nav.contactSince = -100.0 + slot.nav.contactEvents++ + slot.nav.stuckCheckAt = -100.0 + slot.route.replanRequested = true + print("WTO_AI|NAV_CONTACT|eid={uint(slot.eid)}|pos={myPos}\n") + wto_unstick_start_reverse(navState, now, myPos, hullFwd, slot) + // 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 diff --git a/game-ai/ground/wto_ai_world_common.das b/game-ai/ground/wto_ai_world_common.das index 475be20..14b32e2 100644 --- a/game-ai/ground/wto_ai_world_common.das +++ b/game-ai/ground/wto_ai_world_common.das @@ -129,6 +129,7 @@ def private wto_record_wreck_once(var snap : WtoWorldSnap&; eid : EntityId; u : let wIdx = snap.wreckCount snap.wrecks[wIdx].eid = eid snap.wrecks[wIdx].pos = u.pos + snap.wrecks[wIdx].hullFwd = wto_xz_normalize(u.unitTm[0], float3(1.0, 0.0, 0.0)) snap.wrecks[wIdx].halfLen = max(2.0, max(abs(box.boxMin.x), abs(box.boxMax.x))) snap.wrecks[wIdx].halfWid = max(1.1, max(abs(box.boxMin.z), abs(box.boxMax.z))) snap.wreckCount = wIdx + 1 diff --git a/native/wto-nav/wto_nav_internal.h b/native/wto-nav/wto_nav_internal.h index 0cdae48..968d33a 100644 --- a/native/wto-nav/wto_nav_internal.h +++ b/native/wto-nav/wto_nav_internal.h @@ -37,14 +37,15 @@ struct DynamicCost { 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. */ +/* Area costs per WtoPolyArea, times the chokepoint multiplier, live dynamic costs and the + * traffic of the searching path's group. */ 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 curRef, const dtMeshTile *, const dtPoly *curPoly, const dtPolyRef, const dtMeshTile *, const dtPoly *) const override; }; @@ -55,15 +56,27 @@ struct Pack { dtNavMeshQuery *pointQueries[WTO_NAV_TIER_COUNT] = {}; /* Snapping, raycasts, wall distance */ std::vector covers; std::vector tactical; + /* First flat polygon index of every tile slot, and per traffic group how many counted paths + * cross each polygon (indexed by tileBase[tile] + polygon). */ + std::vector tileBase[WTO_NAV_TIER_COUNT]; + std::vector traffic[WTO_NAV_TIER_COUNT][WTO_NAV_RT_TRAFFIC_GROUPS]; }; extern SRWLOCK g_lock; extern Pack *g_pack; extern QueryFilter g_filters[WTO_NAV_RT_FILTER_COUNT]; extern WtoNavStats g_stats; +extern WtoNavTuning g_tuning; + +/* Tier and traffic group (0-based, -1 none) of the search being advanced; read by getCost. */ +extern int g_cost_tier; +extern int g_cost_group; double now_micros(); +/* Flat polygon index for Pack::traffic, or -1. */ +int poly_index(const Pack &pack, uint32_t tier, dtPolyRef ref); + /* * 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, @@ -77,5 +90,6 @@ void paths_reset_locked(); void dynamic_reset_locked(); void dynamic_expire_locked(float now); uint32_t paths_pending_locked(); +uint32_t traffic_paths_locked(); } // namespace wtonav diff --git a/native/wto-nav/wto_nav_paths.cpp b/native/wto-nav/wto_nav_paths.cpp index 4c76d3a..5d16de2 100644 --- a/native/wto-nav/wto_nav_paths.cpp +++ b/native/wto-nav/wto_nav_paths.cpp @@ -3,15 +3,23 @@ * 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. + * + * Paths of a traffic group (a team) are remembered per slot for trafficHoldSec: their polygons + * cost more for the group's later searches, so a team spreads over parallel routes instead of + * queueing on one road. Finished corners are pulled away from the edges they turn around, so a + * vehicle cutting a corner does not clip the building the mesh was eroded from. */ #include "wto_nav_internal.h" +#include #include namespace wtonav { namespace { -constexpr int kIterChunk = 64; /* Detour node expansions between budget checks */ +constexpr int kIterChunk = 64; /* Detour node expansions between budget checks */ +constexpr float kStraightCos = 0.985f; /* Corners turning less than ~10 degrees stay put */ +constexpr int kCornerRayPolys = 256; enum class JobState : uint8_t { Empty, Queued, Running, Done }; @@ -20,6 +28,7 @@ struct PathJob { JobState state; uint32_t tier; uint32_t filter; + int group; /* 0-based traffic group, -1 none */ dtPolyRef startRef; dtPolyRef goalRef; float startPt[3]; @@ -31,11 +40,136 @@ struct PathJob { float corners[WTO_NAV_RT_MAX_CORNERS * 3]; }; +/* Polygons of a slot's last finished path while they count as its group's traffic. */ +struct Occupancy { + int group = -1; + uint32_t tier = 0; + float until = 0.0f; + std::vector polys; +}; + PathJob g_jobs[WTO_NAV_RT_PATH_SLOTS]; +Occupancy g_occupancy[WTO_NAV_RT_PATH_SLOTS]; uint32_t g_next_ticket = 1; uint32_t g_pump_serial; +float g_pump_now; int g_active = -1; /* Slot whose search owns its tier's path query */ dtPolyRef g_poly_path[kMaxPathPolys]; +dtPolyRef g_corner_refs[WTO_NAV_RT_MAX_CORNERS]; +unsigned char g_corner_flags[WTO_NAV_RT_MAX_CORNERS]; +dtPolyRef g_ray_polys[kCornerRayPolys]; + +void release(Occupancy &occ) +{ + if (occ.group >= 0 && g_pack != nullptr) { + std::vector &counts = g_pack->traffic[occ.tier][occ.group]; + for (uint32_t at : occ.polys) { + if (at < counts.size() && counts[at] != 0) + counts[at]--; + } + } + occ.group = -1; + occ.polys.clear(); +} + +void occupy(Occupancy &occ, const PathJob &job, int count) +{ + release(occ); + if (job.group < 0 || !(g_tuning.trafficCostPerPath > 0.0f) || !(g_tuning.trafficHoldSec > 0.0f)) + return; + std::vector &counts = g_pack->traffic[job.tier][job.group]; + for (int i = 0; i < count; i++) { + const int at = poly_index(*g_pack, job.tier, g_poly_path[i]); + if (at < 0 || counts[(size_t)at] == UINT16_MAX) + continue; + counts[(size_t)at]++; + occ.polys.push_back((uint32_t)at); + } + occ.group = job.group; + occ.tier = job.tier; + occ.until = g_pump_now + g_tuning.trafficHoldSec; +} + +void expire_occupancy(float now) +{ + for (Occupancy &occ : g_occupancy) { + if (occ.group >= 0 && occ.until < now) + release(occ); + } +} + +void normalize_xz(float v[3]) +{ + v[1] = 0.0f; + const float len = dtMathSqrtf(v[0] * v[0] + v[2] * v[2]); + if (len > 1e-4f) { + v[0] /= len; + v[2] /= len; + } else { + v[0] = v[2] = 0.0f; + } +} + +/* Whether the mesh lets a vehicle go straight from `from` (on `ref`) to `to`; `end` gets the + * polygon reached. */ +bool open_line(const dtNavMeshQuery *query, const dtQueryFilter &filter, dtPolyRef ref, const float from[3], + const float to[3], dtPolyRef *end) +{ + float t = 0.0f, normal[3]; + int visited = 0; + if (dtStatusFailed(query->raycast(ref, from, to, &filter, &t, normal, g_ray_polys, &visited, kCornerRayPolys)) || + t != FLT_MAX || visited <= 0) + return false; + if (end != nullptr) + *end = g_ray_polys[visited - 1]; + return true; +} + +/* Moves corner i (between corners i-1 and i+1) up to cornerOffsetM away from the edge it turns + * around, keeping both legs and the move itself on the mesh. */ +bool push_corner(const dtNavMeshQuery *query, const dtQueryFilter &filter, float *corners, int i, dtPolyRef prev_ref) +{ + float *c = corners + i * 3; + const float *p = c - 3, *n = c + 3; + float in[3] = { c[0] - p[0], 0.0f, c[2] - p[2] }, out[3] = { n[0] - c[0], 0.0f, n[2] - c[2] }; + normalize_xz(in); + normalize_xz(out); + if (dtVdot2D(in, out) > kStraightCos) + return false; + float push[3] = { in[0] - out[0], 0.0f, in[2] - out[2] }; + normalize_xz(push); + for (float scale = 1.0f; scale > 0.2f; scale *= 0.5f) { + const float step = g_tuning.cornerOffsetM * scale; + float moved[3] = { c[0] + push[0] * step, c[1], c[2] + push[2] * step }; + dtPolyRef moved_ref = 0; + if (!open_line(query, filter, g_corner_refs[i], c, moved, &moved_ref) || + !open_line(query, filter, prev_ref, p, moved, nullptr) || + !open_line(query, filter, moved_ref, moved, n, nullptr)) + continue; + float height = 0.0f; + if (dtStatusSucceed(query->getPolyHeight(moved_ref, moved, &height))) + moved[1] = height; + dtVcopy(c, moved); + g_corner_refs[i] = moved_ref; + return true; + } + return false; +} + +/* Corners on either end of an off-mesh link (one-way downhill) stay where they are. */ +void push_corners(const PathJob &job, float *corners, int count) +{ + if (!(g_tuning.cornerOffsetM > 0.0f) || count < 3) + return; + const dtNavMeshQuery *query = g_pack->pointQueries[job.tier]; + const QueryFilter &filter = g_filters[job.filter]; + for (int i = 1; i < count - 1; i++) { + const bool linked = (g_corner_flags[i] | g_corner_flags[i - 1]) & DT_STRAIGHTPATH_OFFMESH_CONNECTION; + if (!linked && g_corner_refs[i] != 0 && g_corner_refs[i - 1] != 0 && + push_corner(query, filter, corners, i, g_corner_refs[i - 1])) + g_stats.cornersMoved++; + } +} void finish(PathJob &job, WtoNavPathStatus status) { @@ -104,12 +238,14 @@ void finalize(PathJob &job, dtNavMeshQuery *query) return; } int corners = 0; - status = query->findStraightPath(job.startPt, goal, g_poly_path, count, job.corners, nullptr, nullptr, + status = query->findStraightPath(job.startPt, goal, g_poly_path, count, job.corners, g_corner_flags, g_corner_refs, &corners, WTO_NAV_RT_MAX_CORNERS, 0); if (dtStatusFailed(status) || corners == 0) { finish(job, WTO_NAV_PATH_FAILED); return; } + push_corners(job, job.corners, corners); + occupy(g_occupancy[&job - g_jobs], job, count); float length = 0.0f; for (int i = 1; i < corners; i++) length += dtVdist(job.corners + (i - 1) * 3, job.corners + i * 3); @@ -141,12 +277,25 @@ bool start_next() } // namespace +/* The pack is already replaced: its traffic counters start at zero, so nothing is released. */ void paths_reset_locked() { memset(g_jobs, 0, sizeof(g_jobs)); + for (Occupancy &occ : g_occupancy) { + occ.group = -1; + occ.polys.clear(); + } g_active = -1; } +uint32_t traffic_paths_locked() +{ + uint32_t paths = 0; + for (const Occupancy &occ : g_occupancy) + paths += occ.group >= 0; + return paths; +} + uint32_t paths_pending_locked() { uint32_t pending = 0; @@ -168,11 +317,13 @@ extern "C" uint32_t wto_nav_path_request(uint32_t slot, const WtoNavPathRequest if (g_active == (int)slot) g_active = -1; /* The next initSlicedFindPath discards the abandoned search */ memset(&job, 0, sizeof(job)); + release(g_occupancy[slot]); /* A path never counts as traffic against its own replacement */ if (g_next_ticket == 0) g_next_ticket = 1; job.ticket = g_next_ticket++; job.tier = request->tier; job.filter = request->filter; + job.group = request->group >= 1 && request->group <= WTO_NAV_RT_TRAFFIC_GROUPS ? (int)request->group - 1 : -1; prepare(job, *request); const uint32_t ticket = job.ticket; ReleaseSRWLockExclusive(&g_lock); @@ -207,6 +358,8 @@ extern "C" void wto_nav_pump(double budget_us, float now) const double began = now_micros(); dynamic_expire_locked(now); g_pump_serial++; + g_pump_now = now; + expire_occupancy(now); if (g_pack == nullptr) { for (PathJob &job : g_jobs) { if (job.state == JobState::Queued || job.state == JobState::Running) @@ -227,7 +380,10 @@ extern "C" void wto_nav_pump(double budget_us, float now) } const double chunk_began = now_micros(); int done = 0; + g_cost_tier = (int)job.tier; + g_cost_group = g_tuning.trafficCostPerPath > 0.0f ? job.group : -1; const dtStatus status = query->updateSlicedFindPath(kIterChunk, &done); + g_cost_group = -1; job.searchMicros += now_micros() - chunk_began; if (dtStatusFailed(status)) { finish(job, WTO_NAV_PATH_FAILED); diff --git a/native/wto-nav/wto_nav_runtime.cpp b/native/wto-nav/wto_nav_runtime.cpp index 72c5f61..a2b1824 100644 --- a/native/wto-nav/wto_nav_runtime.cpp +++ b/native/wto-nav/wto_nav_runtime.cpp @@ -18,6 +18,9 @@ SRWLOCK g_lock = SRWLOCK_INIT; Pack *g_pack; QueryFilter g_filters[WTO_NAV_RT_FILTER_COUNT]; WtoNavStats g_stats; +WtoNavTuning g_tuning; +int g_cost_tier = -1; +int g_cost_group = -1; namespace { @@ -99,6 +102,23 @@ bool init_queries(Pack *pack, uint32_t tier) dtStatusSucceed(pack->pointQueries[tier]->init(pack->meshes[tier], kPointSearchNodes)); } +/* Traffic counters: one per polygon and group, addressed through each tile slot's first index. */ +void init_traffic(Pack *pack, uint32_t tier) +{ + const dtNavMesh *mesh = pack->meshes[tier]; + const int max_tiles = mesh->getMaxTiles(); + uint32_t total = 0; + pack->tileBase[tier].assign((size_t)max_tiles, 0); + for (int i = 0; i < max_tiles; i++) { + pack->tileBase[tier][(size_t)i] = total; + const dtMeshTile *tile = mesh->getTile(i); + if (tile != nullptr && tile->header != nullptr) + total += (uint32_t)tile->header->polyCount; + } + for (std::vector &counts : pack->traffic[tier]) + counts.assign(total, 0); +} + 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]; @@ -146,6 +166,7 @@ bool load_tier(const std::vector &data, const WtoNavHeader &hdr, uint32 } *polys += (uint32_t)((const dtMeshHeader *)tile)->polyCount; } + init_traffic(pack, tier); if (!init_queries(pack, tier)) { snprintf(detail, detail_size, "tier %u query init failed", tier); return false; @@ -263,12 +284,20 @@ void replace_pack(Pack *pack) float QueryFilter::getCost(const float *pa, const float *pb, const dtPolyRef, const dtMeshTile *, const dtPoly *, - const dtPolyRef, const dtMeshTile *, const dtPoly *curPoly, + const dtPolyRef curRef, 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_cost_group >= 0 && g_pack != nullptr) { + const int at = poly_index(*g_pack, (uint32_t)g_cost_tier, curRef); + const uint16_t paths = at >= 0 ? g_pack->traffic[g_cost_tier][g_cost_group][(size_t)at] : 0; + if (paths != 0) { + const float mul = 1.0f + g_tuning.trafficCostPerPath * (float)paths; + cost *= mul < g_tuning.trafficCostMaxMul ? mul : g_tuning.trafficCostMaxMul; + } + } 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; @@ -293,6 +322,19 @@ bool snap_to_mesh(const dtNavMeshQuery *query, const dtQueryFilter &filter, floa return dtStatusSucceed(query->findNearestPoly(point, column_extents, &filter, ref, nearest)) && *ref != 0; } +int poly_index(const Pack &pack, uint32_t tier, dtPolyRef ref) +{ + if (tier >= WTO_NAV_TIER_COUNT || pack.meshes[tier] == nullptr || ref == 0) + return -1; + unsigned int salt = 0, tile = 0, poly = 0; + pack.meshes[tier]->decodePolyId(ref, salt, tile, poly); + const std::vector &base = pack.tileBase[tier]; + if (tile >= base.size()) + return -1; + const size_t at = (size_t)base[tile] + poly; + return at < pack.traffic[tier][0].size() ? (int)at : -1; +} + double now_micros() { static LARGE_INTEGER frequency; @@ -422,10 +464,28 @@ extern "C" void wto_nav_set_costs(uint32_t filter, const WtoNavCosts *costs) ReleaseSRWLockExclusive(&g_lock); } +extern "C" void wto_nav_set_tuning(const WtoNavTuning *tuning) +{ + if (tuning == nullptr) + return; + AcquireSRWLockExclusive(&g_lock); + g_tuning = *tuning; + if (!(g_tuning.trafficCostPerPath > 0.0f)) + g_tuning.trafficCostPerPath = 0.0f; + if (!(g_tuning.trafficCostMaxMul >= 1.0f)) + g_tuning.trafficCostMaxMul = 1.0f; + if (!(g_tuning.trafficHoldSec > 0.0f)) + g_tuning.trafficHoldSec = 0.0f; + if (!(g_tuning.cornerOffsetM > 0.0f)) + g_tuning.cornerOffsetM = 0.0f; + ReleaseSRWLockExclusive(&g_lock); +} + extern "C" void wto_nav_get_stats(WtoNavStats *stats) { AcquireSRWLockExclusive(&g_lock); g_stats.pending = paths_pending_locked(); + g_stats.trafficPaths = traffic_paths_locked(); g_stats.dynamic = g_dynamic_count; *stats = g_stats; ReleaseSRWLockExclusive(&g_lock); diff --git a/native/wto-nav/wto_nav_runtime.h b/native/wto-nav/wto_nav_runtime.h index e29c64a..7917c6a 100644 --- a/native/wto-nav/wto_nav_runtime.h +++ b/native/wto-nav/wto_nav_runtime.h @@ -18,6 +18,15 @@ extern "C" { #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) */ +#define WTO_NAV_RT_TRAFFIC_GROUPS 2 /* Teams whose planned paths count as traffic for each other */ + +/* Battle-wide search behaviour, set before the pack loads. */ +typedef struct WtoNavTuning { + float trafficCostPerPath; /* Cost added per path of the same group through a polygon; 0 = off */ + float trafficCostMaxMul; /* Highest traffic multiplier */ + float trafficHoldSec; /* A finished path counts as traffic this long (script seconds) */ + float cornerOffsetM; /* Path corners are moved this far away from the edge they turn around */ +} WtoNavTuning; /* Detour traversal costs for one vehicle class, indexed by WtoPolyArea. */ typedef struct WtoNavCosts { @@ -62,6 +71,7 @@ typedef struct WtoNavPathRequest { 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 */ + uint32_t group; /* 1..WTO_NAV_RT_TRAFFIC_GROUPS: avoids and adds to that group's traffic; 0 none */ float start[3]; float goal[3]; } WtoNavPathRequest; @@ -95,6 +105,8 @@ typedef struct WtoNavStats { uint32_t pending; /* Paths waiting or being searched now */ uint32_t dynamic; /* Live dynamic cost circles */ uint32_t meshQueries; /* Probe, raycast and nearest calls */ + uint32_t trafficPaths; /* Finished paths counting as traffic now */ + uint32_t cornersMoved; /* Path corners moved away from the edge they turn around */ } WtoNavStats; /* Reads the eVER SHA-1 of a Dagor level file (levels/.bin) without loading the level. */ @@ -119,10 +131,17 @@ int wto_nav_is_loaded(void); /* Replaces the traversal costs of one filter (0 tracked, 1 wheeled). */ void wto_nav_set_costs(uint32_t filter, const WtoNavCosts *costs); +/* Replaces the traffic and corner settings; applies to searches started afterwards. */ +void wto_nav_set_tuning(const WtoNavTuning *tuning); + /* * 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). + * + * With a traffic group the search pays more for polygons that other paths of the group (finished + * within trafficHoldSec) pass through, and its own result counts for the next ones. The slot's + * previous path stops counting as soon as the new request arrives. */ uint32_t wto_nav_path_request(uint32_t slot, const WtoNavPathRequest *request); diff --git a/native/wto-net/src/local_mp_nav.c b/native/wto-net/src/local_mp_nav.c index 6c391d1..0fb4c43 100644 --- a/native/wto-net/src/local_mp_nav.c +++ b/native/wto-net/src/local_mp_nav.c @@ -4,13 +4,14 @@ * module answers synchronously by writing into the same block: * * op=prefetch -> state=started|skipped, level, reason (battle still loading) - * op=load_map allowFallback="0|1", tracked/wheeled costs t_, w_ + * op=load_map allowFallback="0|1", tracked/wheeled costs t_, w_, + * trafficPerPath, trafficMaxMul, trafficHoldSec, cornerOffset * -> 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_request slot, tier, filter (0 tracked, 1 wheeled), group (team, 0 none), 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, @@ -19,7 +20,7 @@ * 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 + * dynamic, meshQueries, traffic, cornersMoved * * 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 @@ -245,6 +246,16 @@ static void read_costs(const void *blk, const char *prefix, WtoNavCosts *costs) costs->chokepointMul = 1.0f; } +static void read_tuning(const void *blk) +{ + WtoNavTuning tuning; + tuning.trafficCostPerPath = get_real(blk, "trafficPerPath", 0.0f); + tuning.trafficCostMaxMul = get_real(blk, "trafficMaxMul", 1.0f); + tuning.trafficHoldSec = get_real(blk, "trafficHoldSec", 0.0f); + tuning.cornerOffsetM = get_real(blk, "cornerOffset", 0.0f); + wto_nav_set_tuning(&tuning); +} + static void log_loaded(const WtoNavLoadInfo *info) { char expected[41], actual[41]; @@ -270,6 +281,7 @@ static void decide_locked(const void *blk, int allow_fallback) wto_nav_set_costs(0, &costs); read_costs(blk, "w", &costs); wto_nav_set_costs(1, &costs); + read_tuning(blk); 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); @@ -337,10 +349,10 @@ 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|paths=%u|failures=%u|avgUs=%.0f|maxUs=%.0f|maxFrames=%u|pumpMaxUs=%.0f|meshQueries=%u", + log_line("WTO_NAV|UNLOADED|level=%s|why=%s|paths=%u|failures=%u|avgUs=%.0f|maxUs=%.0f|maxFrames=%u|pumpMaxUs=%.0f|meshQueries=%u|cornersMoved=%u", g_battle.level, why, stats.queries, stats.failures, stats.queries ? stats.totalMicros / stats.queries : 0.0, stats.maxMicros, - stats.maxFrames, stats.pumpMaxMicros, stats.meshQueries); + stats.maxFrames, stats.pumpMaxMicros, stats.meshQueries, stats.cornersMoved); wto_nav_unload(); } memset(&g_battle, 0, sizeof(g_battle)); @@ -350,11 +362,13 @@ static void path_request(void *blk) { WtoNavPathRequest req; const long slot = get_long(blk, "slot", -1), tier = get_long(blk, "tier", -1), filter = get_long(blk, "filter", 0); + const long group = get_long(blk, "group", 0); uint32_t ticket = 0; memset(&req, 0, sizeof(req)); req.tier = (uint32_t)tier; req.filter = (uint32_t)filter; + req.group = group > 0 ? (uint32_t)group : 0u; req.snapM = get_real(blk, "snap", 0.0f); req.goalSnapM = get_real(blk, "goalSnap", 0.0f); get_vec(blk, 's', req.start); @@ -453,6 +467,8 @@ static void get_stats(void *blk) set_int(blk, "pending", (int32_t)stats.pending); set_int(blk, "dynamic", (int32_t)stats.dynamic); set_int(blk, "meshQueries", (int32_t)stats.meshQueries); + set_int(blk, "traffic", (int32_t)stats.trafficPaths); + set_int(blk, "cornersMoved", (int32_t)stats.cornersMoved); } static void pump(void *blk) diff --git a/packages/patcher/src/ground-ai/ground-ai-config.ts b/packages/patcher/src/ground-ai/ground-ai-config.ts index a4f2500..17e2f18 100644 --- a/packages/patcher/src/ground-ai/ground-ai-config.ts +++ b/packages/patcher/src/ground-ai/ground-ai-config.ts @@ -56,8 +56,14 @@ export interface GroundAiPathFollow { readonly bumperStopM: number; readonly bumperBlockSec: number; readonly trafficTtcSec: number; - readonly avoidShiftM: number; readonly yieldWaitMaxSec: number; + readonly stationarySpeedMps: number; + readonly passMarginM: number; + readonly passSpeedMps: number; + readonly blockWaitSec: number; + readonly blockTtlSec: number; + readonly contactGapM: number; + readonly contactReverseSec: number; readonly stuckWindowSec: number; readonly stuckMinProgressM: number; readonly unstickReverseM: number; @@ -67,6 +73,8 @@ export interface GroundAiPathFollow { readonly jamRadiusM: number; readonly jamCostMul: number; readonly jamTtlSec: number; + readonly giveUpRadiusM: number; + readonly giveUpCostMul: number; readonly rubbleRadiusM: number; readonly rubbleCostMul: number; readonly rubbleTtlSec: number; @@ -160,6 +168,12 @@ export interface GroundAiConfig { readonly goalSnapRadiusM: number; /** Time queued path searches may take per game frame. */ readonly pathBudgetMsPerFrame: number; + /** Team traffic: cost added per teammate path through a polygon, its cap, and how long a path counts. */ + readonly trafficCostPerPath: number; + readonly trafficCostMaxMul: number; + readonly trafficHoldSec: number; + /** Path corners are moved this far away from the edge they turn around. */ + readonly cornerOffsetM: number; }; readonly navCostsTracked: GroundAiNavCosts; readonly navCostsWheeled: GroundAiNavCosts; @@ -355,6 +369,10 @@ function collectConfigEntries(c: GroundAiConfig): readonly DasEntry[] { ['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], + ['WTO_AI_NAVMESH_TRAFFIC_PER_PATH', 'float', c.navEngine.trafficCostPerPath], + ['WTO_AI_NAVMESH_TRAFFIC_MAX_MUL', 'float', c.navEngine.trafficCostMaxMul], + ['WTO_AI_NAVMESH_TRAFFIC_HOLD_SEC', 'float', c.navEngine.trafficHoldSec], + ['WTO_AI_NAVMESH_CORNER_OFFSET_M', 'float', c.navEngine.cornerOffsetM], ...navCostEntries('T', c.navCostsTracked), ...navCostEntries('W', c.navCostsWheeled), ...pathFollowEntries(c.pathFollow), @@ -457,8 +475,14 @@ function pathFollowEntries(p: GroundAiPathFollow): readonly DasEntry[] { ['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_STATIONARY_MPS', 'float', p.stationarySpeedMps], + ['WTO_AI_PF_PASS_MARGIN_M', 'float', p.passMarginM], + ['WTO_AI_PF_PASS_SPEED_MPS', 'float', p.passSpeedMps], + ['WTO_AI_PF_BLOCK_WAIT_SEC', 'float', p.blockWaitSec], + ['WTO_AI_PF_BLOCK_TTL_SEC', 'float', p.blockTtlSec], + ['WTO_AI_PF_CONTACT_GAP_M', 'float', p.contactGapM], + ['WTO_AI_PF_CONTACT_REVERSE_SEC', 'float', p.contactReverseSec], ['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], @@ -468,6 +492,8 @@ function pathFollowEntries(p: GroundAiPathFollow): readonly DasEntry[] { ['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_GIVE_UP_RADIUS_M', 'float', p.giveUpRadiusM], + ['WTO_AI_PF_GIVE_UP_COST_MUL', 'float', p.giveUpCostMul], ['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], diff --git a/tools/navgen/bake/bake.cpp b/tools/navgen/bake/bake.cpp index c72fdc0..c01d259 100644 --- a/tools/navgen/bake/bake.cpp +++ b/tools/navgen/bake/bake.cpp @@ -19,8 +19,10 @@ #include #include #include +#include #include #include +#include #include #include #include @@ -57,9 +59,17 @@ struct CoverBake { float retreatMinM; }; +/* navBake water settings (ground-ai.jsonc, copied into the POI file by mission-bounds.mts). */ +struct WaterBake { + float maxFordDepthM; /* Deeper water is a wall */ + float marginM; /* Extra room kept from it on low banks */ + float bankHeightM; /* Banks up to this height above the water line get the extra room */ +}; + struct PoisData { CoverBake cover{}; float chokepointMaxWidthVehicles = 0.0f; + WaterBake water{ -1.0f, -1.0f, -1.0f }; std::vector t1Spawns; std::vector t2Spawns; std::vector caps; @@ -83,7 +93,6 @@ static constexpr float kCellSize = 0.50f; static constexpr float kCellHeight = 0.25f; static constexpr int kTileSize = 256; /* 128.0 m per tile */ static constexpr float kTileWorldSize = kTileSize * kCellSize; -static constexpr float kShallowWaterMaxM = 0.60f; static constexpr float kShallowWaterMinM = 0.05f; static constexpr float kRoughSlopeDeg = 18.0f; static constexpr float kCoverProbeStartM = 0.6f; @@ -275,7 +284,15 @@ static bool loadPois(const std::string &path, PoisData &out) { return false; } out.chokepointMaxWidthVehicles = readJsonNumber(content, "chokepointMaxWidthVehicles", -1.0f); - if (!(out.chokepointMaxWidthVehicles >= 1.0f && out.chokepointMaxWidthVehicles <= 4.0f)) { + out.water = { + readJsonNumber(content, "maxFordDepthM", -1.0f), + readJsonNumber(content, "deepWaterMarginM", -1.0f), + readJsonNumber(content, "deepWaterBankHeightM", -1.0f) + }; + if (!(out.chokepointMaxWidthVehicles >= 1.0f && out.chokepointMaxWidthVehicles <= 4.0f) || + !(out.water.maxFordDepthM >= 0.1f && out.water.maxFordDepthM <= 3.0f) || + !(out.water.marginM >= 0.0f && out.water.marginM <= 10.0f) || + !(out.water.bankHeightM >= 0.0f && out.water.bankHeightM <= 10.0f)) { std::fprintf(stderr, "Invalid navigation baking settings in %s. Regenerate it with mission-bounds.mts.\n", path.c_str()); return false; } @@ -328,6 +345,65 @@ static bool isCoverArea(unsigned char area) { return area != RC_NULL_AREA && area != WTO_AREA_DEEP_WATER && area != WTO_AREA_SHALLOW_WATER; } +/* Turns deep water into a wall before erosion, so walkable ground keeps the tier's radius from it + * like from any obstacle. Returns the indices of the water spans for wallOffWaterBank. */ +static std::vector wallOffDeepWater(rcCompactHeightfield &chf) { + std::vector water; + for (int i = 0; i < chf.spanCount; ++i) { + if (chf.areas[i] == WTO_AREA_DEEP_WATER) { + chf.areas[i] = RC_NULL_AREA; + water.push_back(i); + } + } + return water; +} + +/* After erosion: removes every span within `reachCells` of deep water (radius plus bank margin) + * whose surface is at most `maxSpanY` (cells), i.e. low bank that slopes into the water. The walk + * follows span connections and stops at higher ground, so bridges, quays and ramps above the + * water line keep only the erosion. Each span keeps the cell of its nearest water source; a span + * is revisited when a closer source reaches it. */ +static void wallOffWaterBank(rcCompactHeightfield &chf, const std::vector &water, float reachCells, int maxSpanY) { + if (water.empty() || !(reachCells > 0.0f)) return; + std::vector cellOf(chf.spanCount, -1); + for (int z = 0; z < chf.height; ++z) { + for (int x = 0; x < chf.width; ++x) { + const rcCompactCell &c = chf.cells[x + z * chf.width]; + for (int i = (int)c.index, n = (int)(c.index + c.count); i < n; ++i) cellOf[i] = x + z * chf.width; + } + } + const float limit = reachCells * reachCells; + std::vector source(chf.spanCount, -1); + std::vector best(chf.spanCount, FLT_MAX); + std::deque open; + for (int i : water) { + source[i] = cellOf[i]; + best[i] = 0.0f; + open.push_back(i); + } + while (!open.empty()) { + const int i = open.front(); + open.pop_front(); + const int cell = cellOf[i]; + const int x = cell % chf.width, z = cell / chf.width; + const int sx = source[i] % chf.width, sz = source[i] / chf.width; + for (int dir = 0; dir < 4; ++dir) { + const int con = rcGetCon(chf.spans[i], dir); + if (con == RC_NOT_CONNECTED) continue; + const int nx = x + rcGetDirOffsetX(dir), nz = z + rcGetDirOffsetY(dir); + const int ni = (int)chf.cells[nx + nz * chf.width].index + con; + const float d2 = (float)((nx - sx) * (nx - sx) + (nz - sz) * (nz - sz)); + if (d2 > limit || d2 >= best[ni] || (int)chf.spans[ni].y > maxSpanY) continue; + best[ni] = d2; + source[ni] = source[i]; + open.push_back(ni); + } + } + for (int i = 0; i < chf.spanCount; ++i) { + if (best[i] < FLT_MAX) chf.areas[i] = RC_NULL_AREA; + } +} + static bool isCoverBoundary(const rcCompactHeightfield &field, int x, int z, const rcCompactSpan &span) { for (int dir = 0; dir < 4; ++dir) { int connection = rcGetCon(span, dir); @@ -493,7 +569,7 @@ static TileBakeResult buildSingleTile( int tx, int tz, float mapMinX, float mapMinZ, const CoverBake &coverTuning, bool bakeCovers, - float chokeClearanceM + float chokeClearanceM, const WaterBake &water ) { TileBakeResult res; res.tile.tx = tx; @@ -514,7 +590,7 @@ static TileBakeResult buildSingleTile( cfg.mergeRegionArea = 400; cfg.maxVertsPerPoly = 6; cfg.tileSize = kTileSize; - cfg.borderSize = cfg.walkableRadius + 3; + cfg.borderSize = cfg.walkableRadius + (int)std::ceil(water.marginM / cfg.cs) + 3; // Cover and corner rays must see hard collision on the other side of tile boundaries. if (bakeCovers) cfg.borderSize = std::max(cfg.borderSize, coverBorderCells(coverTuning)); // Erosion walls off the heightfield edge; chokepoint reach must stay clear of that band. @@ -567,7 +643,7 @@ static TileBakeResult buildSingleTile( float cy = (a.y + b.y + c.y) * (1.0f / 3.0f); if (hasWater) { float depth = waterY - cy; - if (depth > kShallowWaterMaxM) return WTO_AREA_DEEP_WATER; + if (depth > water.maxFordDepthM) return WTO_AREA_DEEP_WATER; if (depth > kShallowWaterMinM) return WTO_AREA_SHALLOW_WATER; } if (ny < cosRoughSlope) return WTO_AREA_ROUGH; @@ -647,12 +723,16 @@ static TileBakeResult buildSingleTile( rcFreeHeightField(solid); solid = nullptr; - /* Erode walkable area by tank radius (guaranteed full hull clearance from hard obstacles!) */ + /* Erode walkable area by tank radius (guaranteed full hull clearance from hard obstacles and + * deep water), then keep the bank margin from deep water on top of it. */ + const std::vector deepWater = wallOffDeepWater(*chf); if (!rcErodeWalkableArea(&ctx, cfg.walkableRadius, *chf)) { rcFreeHeightField(hardHf); rcFreeCompactHeightfield(chf); return res; } + wallOffWaterBank(*chf, deepWater, (tier.agentRadius + water.marginM) / cfg.cs, + (int)std::floor((waterY + water.bankHeightM - cfg.bmin[1]) / cfg.ch)); /* Tag crushable fences & thin forest areas directly onto overlapping walkable cells (O(N), fast!) */ for (const auto &sm : softMarks) { @@ -1339,7 +1419,8 @@ int main(int argc, char **argv) { if (idx >= totalTiles) break; int tx = idx % tilesX; int tz = idx / tilesX; - auto br = buildSingleTile(geo, buckets[(size_t)idx], tierIdx, tx, tz, mapMinX, mapMinZ, pois.cover, doCovers, chokeClearanceM); + auto br = buildSingleTile(geo, buckets[(size_t)idx], tierIdx, tx, tz, mapMinX, mapMinZ, pois.cover, doCovers, + chokeClearanceM, pois.water); tierTiles[tierIdx][(size_t)idx] = br.tile; if (doCovers && !br.covers.empty()) { localCov.insert(localCov.end(), br.covers.begin(), br.covers.end()); @@ -1605,6 +1686,9 @@ int main(int argc, char **argv) { } } } + /* Deep water is no longer part of any mesh; mark it from the terrain. */ + if ((fl & 7u) == 0 && geo.hdr.waterLevel > -1e5f && geo.hdr.waterLevel - gy > pois.water.maxFordDepthM) + fl |= 16; pFlags[(size_t)rz * pw + rx] = fl; } } diff --git a/tools/navgen/mission-bounds.mts b/tools/navgen/mission-bounds.mts index a3b6e91..bd3b178 100644 --- a/tools/navgen/mission-bounds.mts +++ b/tools/navgen/mission-bounds.mts @@ -162,6 +162,9 @@ function readNavBake() { crushableMaxImpulse: nav.number('crushableMaxImpulse', { min: 0 }), crushableMaxRiExtraHp: nav.number('crushableMaxRiExtraHp', { min: 0 }), chokepointMaxWidthVehicles: nav.number('chokepointMaxWidthVehicles', { min: 1, max: 4 }), + maxFordDepthM: nav.number('maxFordDepthM', { min: 0.1, max: 3 }), + deepWaterMarginM: nav.number('deepWaterMarginM', { min: 0, max: 10 }), + deepWaterBankHeightM: nav.number('deepWaterBankHeightM', { min: 0, max: 10 }), }; }