diff --git a/apps/launcher/src/renderer/src/i18n/locales/en.json b/apps/launcher/src/renderer/src/i18n/locales/en.json index 13e0c5e..559c22e 100644 --- a/apps/launcher/src/renderer/src/i18n/locales/en.json +++ b/apps/launcher/src/renderer/src/i18n/locales/en.json @@ -515,6 +515,7 @@ "estimation": "Lead estimation & aim bias", "fireControl": "Fire control & fire gate", "navigation": "Driving & navigation", + "navEngine": "Map navigation mesh & path costs", "crowd": "Spacing & crowd dispersal", "terrain": "Terrain & ridge limits", "runtime": "Tick cadence & diagnostics" @@ -531,6 +532,7 @@ "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", + "navEngine": "Baked map navigation packs, their fallback, and path costs per surface for tracked and wheeled vehicles", "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" @@ -677,6 +679,31 @@ "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" + }, + "navCostsTracked": { + "road": "Tracked · road cost", + "bridge": "Tracked · bridge cost", + "ground": "Tracked · open ground cost", + "rough": "Tracked · steep or rocky ground cost", + "forest": "Tracked · forest cost", + "crushable": "Tracked · crushable obstacle cost", + "shallowWater": "Tracked · shallow water cost", + "chokepoint": "Tracked · chokepoint multiplier" + }, + "navCostsWheeled": { + "road": "Wheeled · road cost", + "bridge": "Wheeled · bridge cost", + "ground": "Wheeled · open ground cost", + "rough": "Wheeled · steep or rocky ground cost", + "forest": "Wheeled · forest cost", + "crushable": "Wheeled · crushable obstacle cost", + "shallowWater": "Wheeled · shallow water cost", + "chokepoint": "Wheeled · chokepoint multiplier" + }, "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 8f515b8..12b25c4 100644 --- a/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json +++ b/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json @@ -515,6 +515,7 @@ "estimation": "目击测速与瞄准偏差", "fireControl": "火控与开火许可", "navigation": "机动与寻路控制", + "navEngine": "地图导航网格与通行代价", "crowd": "编队间距与避让", "terrain": "地形与棱线约束", "runtime": "运行频率与诊断" @@ -531,6 +532,7 @@ "estimation": "本车目击测速、守出口时长与自然散布", "fireControl": "距离分档、车速门槛、稳定等待与弹道防误伤", "navigation": "底层驱动方式、转向刹车与脱困倒车", + "navEngine": "离线地图导航包的启用与降级,以及履带 / 轮式车在各类地表上的寻路代价", "crowd": "友军安全间距与扎堆疏散", "terrain": "爬坡 / 下坡角度、涉水深度与探头限制", "runtime": "脚本刷新间隔与调试遥测日志" @@ -677,6 +679,31 @@ "tacticalReverseDistM": "战术倒车最大距离", "tacticalReverseMaxSec": "战术倒车最长时长" }, + "navEngine": { + "enabled": "启用地图导航包", + "allowFallback": "缺少或损坏时整局退回旧寻路", + "snapRadiusM": "起终点吸附到导航网格的最大距离" + }, + "navCostsTracked": { + "road": "履带车 · 道路代价", + "bridge": "履带车 · 桥面代价", + "ground": "履带车 · 普通地面代价", + "rough": "履带车 · 陡坡碎石代价", + "forest": "履带车 · 树林代价", + "crushable": "履带车 · 可碾压障碍代价", + "shallowWater": "履带车 · 浅滩涉水代价", + "chokepoint": "履带车 · 窄口代价倍率" + }, + "navCostsWheeled": { + "road": "轮式车 · 道路代价", + "bridge": "轮式车 · 桥面代价", + "ground": "轮式车 · 普通地面代价", + "rough": "轮式车 · 陡坡碎石代价", + "forest": "轮式车 · 树林代价", + "crushable": "轮式车 · 可碾压障碍代价", + "shallowWater": "轮式车 · 浅滩涉水代价", + "chokepoint": "轮式车 · 窄口代价倍率" + }, "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 d818982..c9238ad 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 @@ -68,6 +68,9 @@ function int( }; } +/** Surfaces of the baked navigation mesh, in the order of tuning/ground-ai.jsonc navCosts*. */ +const NAV_COST_FIELDS = ['road', 'bridge', 'ground', 'rough', 'forest', 'crushable', 'shallowWater', 'chokepoint'] as const; + export const BOT_TUNING_GROUPS: readonly BotTuningGroup[] = [ { id: 'general', @@ -269,6 +272,18 @@ export const BOT_TUNING_GROUPS: readonly BotTuningGroup[] = [ num('navigation', 'tacticalReverseMaxSec', 2, 25, 's'), ], }, + { + id: 'navEngine', + defaultOpen: false, + customOnly: true, + fields: [ + { 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'), + ...NAV_COST_FIELDS.map((field) => num('navCostsTracked', field, 0.1, 20)), + ...NAV_COST_FIELDS.map((field) => num('navCostsWheeled', field, 0.1, 20)), + ], + }, { id: 'crowd', defaultOpen: false, diff --git a/apps/launcher/src/shared/schemas/tuning.ts b/apps/launcher/src/shared/schemas/tuning.ts index 4ae2c15..e953f6d 100644 --- a/apps/launcher/src/shared/schemas/tuning.ts +++ b/apps/launcher/src/shared/schemas/tuning.ts @@ -100,6 +100,24 @@ const GroundAiNavigationSchema = z.object({ tacticalReverseMaxSec: z.number().min(2).max(25), }); +const GroundAiNavEngineSchema = z.object({ + enabled: z.boolean(), + allowFallback: z.boolean(), + snapRadiusM: z.number().min(2).max(40), +}); + +const navCost = z.number().min(0.1).max(20); +const GroundAiNavCostsSchema = z.object({ + road: navCost, + bridge: navCost, + ground: navCost, + rough: navCost, + forest: navCost, + crushable: navCost, + shallowWater: navCost, + chokepoint: navCost, +}); + const GroundAiPerceptionSchema = z.object({ foliageTransparency: z.number().min(0.001).max(1), nearSpotRangeM: z.number().min(20).max(250), @@ -194,6 +212,9 @@ export const GroundAiTuningSchema = z.object({ crowd: GroundAiCrowdSchema, terrain: GroundAiTerrainSchema, navigation: GroundAiNavigationSchema, + navEngine: GroundAiNavEngineSchema, + navCostsTracked: GroundAiNavCostsSchema, + navCostsWheeled: GroundAiNavCostsSchema, perception: GroundAiPerceptionSchema, stateMachine: GroundAiStateMachineSchema, tactics: GroundAiTacticsSchema, @@ -212,6 +233,9 @@ export const GroundAiTuningPatchSchema = z.object({ crowd: GroundAiCrowdSchema.partial().optional(), terrain: GroundAiTerrainSchema.partial().optional(), navigation: GroundAiNavigationSchema.partial().optional(), + navEngine: GroundAiNavEngineSchema.partial().optional(), + navCostsTracked: GroundAiNavCostsSchema.partial().optional(), + navCostsWheeled: GroundAiNavCostsSchema.partial().optional(), perception: GroundAiPerceptionSchema.partial().optional(), stateMachine: GroundAiStateMachineSchema.partial().optional(), tactics: GroundAiTacticsSchema.partial().optional(), diff --git a/apps/server/src/battle/battle-mission-settings.ts b/apps/server/src/battle/battle-mission-settings.ts index a62b74a..7813a51 100644 --- a/apps/server/src/battle/battle-mission-settings.ts +++ b/apps/server/src/battle/battle-mission-settings.ts @@ -131,6 +131,8 @@ function customBotsBlock(plan: BattleLaunchPlan): BlkBlock { setParam(bots, 'wtoTeamACountries', text(plan.countriesAllies.join(';'))); setParam(bots, 'wtoTeamBCountries', text(plan.countriesAxis.join(';'))); if (plan.mission.groundMode !== undefined) setParam(bots, 'wtoGroundMode', text(plan.mission.groundMode)); + // The battle's level file: the ground AI loads its navigation pack by this name (native local_mp_nav.c). + if (plan.level !== undefined) setParam(bots, 'wtoLevel', text(plan.level)); if (plan.maxRespawns === UNLIMITED_RESPAWNS) setParam(bots, 'wtoUnlimitedRespawns', text('1')); setParam(bots, 'numBotRespawnsInMultiSlot', integer(plan.airBotRespawns)); setParam(bots, 'numTankBotRespawnsInMultiSlot', integer(plan.tankBotRespawns)); diff --git a/apps/server/src/tuning/ground-ai-tuning.ts b/apps/server/src/tuning/ground-ai-tuning.ts index 1bb7e90..5302a95 100644 --- a/apps/server/src/tuning/ground-ai-tuning.ts +++ b/apps/server/src/tuning/ground-ai-tuning.ts @@ -8,6 +8,7 @@ import { type GroundAiConfig, type GroundAiDriveMode, type GroundAiMode, + type GroundAiNavCosts, } from '@wto/patcher'; import type { TankLineupWeights } from '../battle/battle-ranks.ts'; import { tuningFiles } from './tuning-loader.ts'; @@ -44,6 +45,9 @@ export function readGroundAiTuning(reader: TuningReader): GroundAiTuning { crowd: readCrowdSection(reader.object('crowd')), terrain: readTerrainSection(reader.object('terrain')), navigation: readNavigationSection(reader.object('navigation')), + navEngine: readNavEngineSection(reader.object('navEngine')), + navCostsTracked: readNavCosts(reader.object('navCostsTracked')), + navCostsWheeled: readNavCosts(reader.object('navCostsWheeled')), perception: readPerceptionSection(reader.object('perception')), stateMachine: readStateMachineSection(reader.object('stateMachine')), tactics: readTacticsSection(reader.object('tactics')), @@ -173,6 +177,28 @@ function readTerrainSection(terrain: TuningReader): GroundAiTuning['terrain'] { }; } +function readNavEngineSection(engine: TuningReader): GroundAiTuning['navEngine'] { + return { + enabled: engine.bool('enabled'), + allowFallback: engine.bool('allowFallback'), + snapRadiusM: engine.number('snapRadiusM', { min: 2, max: 40 }), + }; +} + +function readNavCosts(costs: TuningReader): GroundAiNavCosts { + const read = (key: keyof GroundAiNavCosts) => costs.number(key, { min: 0.1, max: 20 }); + return { + road: read('road'), + bridge: read('bridge'), + ground: read('ground'), + rough: read('rough'), + forest: read('forest'), + crushable: read('crushable'), + shallowWater: read('shallowWater'), + chokepoint: read('chokepoint'), + }; +} + function readNavigationSection(nav: TuningReader): GroundAiTuning['navigation'] { const driveModeRaw = nav.string('driveMode'); const driveMode = GROUND_AI_DRIVE_MODES.find((candidate): candidate is GroundAiDriveMode => candidate === driveModeRaw); diff --git a/apps/server/tuning/ground-ai.jsonc b/apps/server/tuning/ground-ai.jsonc index 4a719c8..c3ad4ac 100644 --- a/apps/server/tuning/ground-ai.jsonc +++ b/apps/server/tuning/ground-ai.jsonc @@ -134,6 +134,42 @@ "tacticalReverseMaxSec": 9.5 }, + // Baked navigation packs (tools/navgen), loaded once per battle by the native engine. + "navEngine": { + "enabled": true, + // When the battle's pack is missing or broken: true keeps the script's own navigation for the + // whole battle, false leaves the bots standing so the problem shows (testing). Decided once at + // 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 + }, + + // Path cost multipliers per surface for tracked vehicles; chokepoint multiplies the surface cost + // of passages narrower than navBake.chokepointMaxWidthVehicles. + "navCostsTracked": { + "road": 0.75, + "bridge": 0.9, + "ground": 1.0, + "rough": 1.65, + "forest": 2.1, + "crushable": 2.4, + "shallowWater": 2.6, + "chokepoint": 1.8 + }, + + // The same for wheeled vehicles. + "navCostsWheeled": { + "road": 0.55, + "bridge": 0.75, + "ground": 1.15, + "rough": 3.2, + "forest": 2.8, + "crushable": 3.5, + "shallowWater": 4.0, + "chokepoint": 2.2 + }, + // Exposure-based visual perception (offline values; foliageTransparency matches stock infantry AI). "perception": { "foliageTransparency": 0.01, diff --git a/game-ai/ground/wto_ai_navmesh_common.das b/game-ai/ground/wto_ai_navmesh_common.das new file mode 100644 index 0000000..670b10f --- /dev/null +++ b/game-ai/ground/wto_ai_navmesh_common.das @@ -0,0 +1,157 @@ +// 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. +options indenting = 2 +options no_global_heap = true +module wto_ai_navmesh_common shared + +require ecs +require math +require DagorDataBlock +require DagorSystem +require Mission +require %appGame.wtoai.wto_ai_config_common +require %appGame.wtoai.wto_ai_types_common + +let public WTO_NAVMESH_UNDECIDED = 0 +let public WTO_NAVMESH_LOADED = 1 +let public WTO_NAVMESH_FALLBACK = 2 +let public WTO_NAVMESH_FAILED = 3 +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 + +[never_inline] +def private wto_navmesh_add_costs(var blk : DataBlock&) + add(blk, "t_road", "{WTO_AI_NAVMESH_T_ROAD}") + add(blk, "t_bridge", "{WTO_AI_NAVMESH_T_BRIDGE}") + add(blk, "t_ground", "{WTO_AI_NAVMESH_T_GROUND}") + add(blk, "t_rough", "{WTO_AI_NAVMESH_T_ROUGH}") + add(blk, "t_forest", "{WTO_AI_NAVMESH_T_FOREST}") + add(blk, "t_crushable", "{WTO_AI_NAVMESH_T_CRUSHABLE}") + add(blk, "t_shallowWater", "{WTO_AI_NAVMESH_T_SHALLOW_WATER}") + add(blk, "t_chokepoint", "{WTO_AI_NAVMESH_T_CHOKEPOINT}") + add(blk, "w_road", "{WTO_AI_NAVMESH_W_ROAD}") + add(blk, "w_bridge", "{WTO_AI_NAVMESH_W_BRIDGE}") + add(blk, "w_ground", "{WTO_AI_NAVMESH_W_GROUND}") + add(blk, "w_rough", "{WTO_AI_NAVMESH_W_ROUGH}") + add(blk, "w_forest", "{WTO_AI_NAVMESH_W_FOREST}") + add(blk, "w_crushable", "{WTO_AI_NAVMESH_W_CRUSHABLE}") + add(blk, "w_shallowWater", "{WTO_AI_NAVMESH_W_SHALLOW_WATER}") + add(blk, "w_chokepoint", "{WTO_AI_NAVMESH_W_CHOKEPOINT}") + +// Asks the native engine for this battle's pack once; returns a WTO_NAVMESH_* state. +[never_inline] +def public wto_navmesh_load() : int + if !WTO_AI_NAVMESH_ENABLED + print("WTO_AI|NAVMESH|state=off\n") + return WTO_NAVMESH_OFF + var state = WTO_AI_NAVMESH_ALLOW_FALLBACK ? WTO_NAVMESH_FALLBACK : WTO_NAVMESH_FAILED + using() <| $(var blk : DataBlock) + add(blk, "op", "load_map") + add(blk, "allowFallback", WTO_AI_NAVMESH_ALLOW_FALLBACK ? "1" : "0") + wto_navmesh_add_costs(blk) + call_mission_action("wtoNav", blk) + let answer = datablock_getStr(blk, "state", "") + if answer == "loaded" + state = WTO_NAVMESH_LOADED + elif answer == "fallback" + state = WTO_NAVMESH_FALLBACK + elif answer == "failed" + state = WTO_NAVMESH_FAILED + let reason = answer == "" ? "native navigation unavailable" : datablock_getStr(blk, "reason", "") + let level = datablock_getStr(blk, "level", "") + let fp = datablock_getStr(blk, "fingerprint", "") + let tiers = datablock_getInt(blk, "tiers", 0) + let covers = datablock_getInt(blk, "covers", 0) + print("WTO_AI|NAVMESH|state={state}|answer={answer}|level={level}|fp={fp}|tiers={tiers}|covers={covers}|reason={reason}\n") + return state + +[never_inline] +def public 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. +[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 + 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}") + 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. +[never_inline] +def public wto_navmesh_self_test(world : WtoWorldSnap const&) : bool + if world.capCount <= 0 || !world.teamSpawnValid[1] || !world.teamSpawnValid[2] + return false + var pts : float3[96] + 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) + 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 + +// Per world tick: decide the battle's navigation once, then prove a path per team once. +[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) + +// 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 + wto_navmesh_unload() + state = WTO_NAVMESH_UNDECIDED + selfTested = false + +[never_inline] +def public wto_navmesh_log_stats() + 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 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") diff --git a/game-ai/ground/wto_ai_runtime.das b/game-ai/ground/wto_ai_runtime.das index 775e92b..22f0cc4 100644 --- a/game-ai/ground/wto_ai_runtime.das +++ b/game-ai/ground/wto_ai_runtime.das @@ -32,6 +32,7 @@ require %appGame.wtoai.wto_ai_commander_common require %appGame.wtoai.wto_ai_perceive_common require %appGame.wtoai.wto_ai_tactics_common require %appGame.wtoai.wto_ai_nav_common +require %appGame.wtoai.wto_ai_navmesh_common require %appGame.wtoai.wto_ai_drive_common require %appGame.wtoai.wto_ai_fire_common require %appGame.wtoai.wto_ai_diag_common @@ -47,6 +48,8 @@ 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 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) @@ -66,6 +69,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) for i in range(WTO_MAX_BOTS) if g_bots[i].drive.routeBOwned wto_drive_request_control(g_bots[i].eid, 0) @@ -207,6 +211,8 @@ def wto_ai_world_tick_es(act : UpdateStageInfoAct) wto_drive_announce_script_ready() 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_crowd_update_all(g_world, g_bots, g_crowd) let zoneChanged = g_world.zoneVersion != g_last_zone_ver if zoneChanged @@ -237,6 +243,8 @@ def wto_ai_world_tick_es(act : UpdateStageInfoAct) 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() [es(tag=server, no_order)] def wto_ai_pipeline_es(act : UpdateStageInfoAct; eid : EntityId; var unit__ref : UnitRef&; @@ -264,7 +272,8 @@ def wto_ai_pipeline_es(act : UpdateStageInfoAct; eid : EntityId; var unit__ref : if WTO_AI_LAYER_TACTICS || WTO_AI_LAYER_FIRE_CONTROL wto_perceive_update(g_world, now, WTO_AI_TACTICS_TICK_SEC, unit.pos, unit.unitTm[0], slot) wto_tactics_update(g_world, now, WTO_AI_TACTICS_TICK_SEC, unit.pos, unit.unitTm[0], unit.isBurn, repair_system_remaining_repair_time, slot, g_crowd) - if now >= slot.nextNavAt + // A failed pack with navEngine.allowFallback off leaves every bot standing for the battle. + 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_fire_update(g_world, unit, now, act.dt, slot, g_fire_budget) @@ -272,7 +281,7 @@ def wto_ai_pipeline_es(act : UpdateStageInfoAct; eid : EntityId; var unit__ref : [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" + 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/native/wto-nav/wto_nav_runtime.cpp b/native/wto-nav/wto_nav_runtime.cpp new file mode 100644 index 0000000..43b5871 --- /dev/null +++ b/native/wto-nav/wto_nav_runtime.cpp @@ -0,0 +1,399 @@ +/* + * 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. + */ +#include "wto_nav_runtime.h" +#include "wto_nav_format.h" + +#include "DetourAlloc.h" +#include "DetourCommon.h" +#include "DetourNavMesh.h" +#include "DetourNavMeshQuery.h" + +#include + +#include +#include +#include + +#ifndef DT_VIRTUAL_QUERYFILTER +#error "Detour must be built with DT_VIRTUAL_QUERYFILTER for the chokepoint cost filter" +#endif + +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; + +void init_filters_locked() +{ + if (g_filters_ready) + return; + for (WtoQueryFilter &filter : g_filters) { + filter.setIncludeFlags(WTO_FLAG_WALK); + filter.setExcludeFlags(WTO_FLAG_DEEP_WATER | WTO_FLAG_BLOCKED); + } + g_filters_ready = true; +} + +void free_pack(Pack *pack) +{ + if (pack == nullptr) + return; + for (uint32_t t = 0; t < WTO_NAV_TIER_COUNT; t++) { + dtFreeNavMeshQuery(pack->queries[t]); + dtFreeNavMesh(pack->meshes[t]); + } + delete pack; +} + +bool read_file(const wchar_t *path, std::vector &out, WtoNavLoadInfo *info) +{ + FILE *file = nullptr; + if (_wfopen_s(&file, path, L"rb") != 0 || file == nullptr) { + info->result = GetFileAttributesW(path) == INVALID_FILE_ATTRIBUTES ? WTO_NAV_LOAD_MISSING : WTO_NAV_LOAD_UNREADABLE; + snprintf(info->detail, sizeof(info->detail), "%s", info->result == WTO_NAV_LOAD_MISSING ? "no pack file" : "cannot open pack"); + return false; + } + bool ok = _fseeki64(file, 0, SEEK_END) == 0; + long long size = ok ? _ftelli64(file) : -1; + ok = ok && size > 0 && (unsigned long long)size <= kMaxPackBytes && _fseeki64(file, 0, SEEK_SET) == 0; + if (ok) { + out.resize((size_t)size); + ok = fread(out.data(), 1, out.size(), file) == out.size(); + } + fclose(file); + if (!ok) { + info->result = WTO_NAV_LOAD_UNREADABLE; + snprintf(info->detail, sizeof(info->detail), "cannot read pack (%lld bytes)", size); + } + return ok; +} + +bool fits(const std::vector &data, uint64_t offset, uint64_t size) +{ + return offset <= data.size() && size <= data.size() - offset; +} + +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]; + const uint64_t end = at + hdr.tierSizes[tier]; + dtNavMeshParams params; + uint32_t tile_count = 0; + + if (!fits(data, at, hdr.tierSizes[tier]) || hdr.tierSizes[tier] < sizeof(params) + sizeof(tile_count)) { + snprintf(detail, detail_size, "tier %u outside the file", tier); + return false; + } + memcpy(¶ms, data.data() + at, sizeof(params)); + at += sizeof(params); + memcpy(&tile_count, data.data() + at, sizeof(tile_count)); + at += sizeof(tile_count); + + pack->meshes[tier] = dtAllocNavMesh(); + if (pack->meshes[tier] == nullptr || dtStatusFailed(pack->meshes[tier]->init(¶ms))) { + snprintf(detail, detail_size, "tier %u mesh parameters rejected", tier); + return false; + } + for (uint32_t i = 0; i < tile_count; i++) { + uint32_t size = 0; + if (at + sizeof(size) > end) { + snprintf(detail, detail_size, "tier %u tile %u header truncated", tier, i); + return false; + } + memcpy(&size, data.data() + at, sizeof(size)); + at += sizeof(size); + if (size == 0 || at + size > end) { + snprintf(detail, detail_size, "tier %u tile %u truncated", tier, i); + return false; + } + unsigned char *tile = (unsigned char *)dtAlloc(size, DT_ALLOC_PERM); + if (tile == nullptr) { + snprintf(detail, detail_size, "out of memory for tier %u", tier); + return false; + } + memcpy(tile, data.data() + at, size); + at += size; + if (dtStatusFailed(pack->meshes[tier]->addTile(tile, (int)size, DT_TILE_FREE_DATA, 0, nullptr))) { + dtFree(tile); + snprintf(detail, detail_size, "tier %u tile %u rejected by Detour", tier, i); + return false; + } + *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))) { + snprintf(detail, detail_size, "tier %u query init failed", tier); + return false; + } + return true; +} + +Pack *parse_pack(const std::vector &data, WtoNavLoadInfo *info) +{ + WtoNavHeader hdr; + if (data.size() < sizeof(hdr)) { + snprintf(info->detail, sizeof(info->detail), "file shorter than the header"); + return nullptr; + } + memcpy(&hdr, data.data(), sizeof(hdr)); + if (memcmp(hdr.magic, WTO_NAV_MAGIC, sizeof(hdr.magic)) != 0 || hdr.version != WTO_NAV_VERSION || + hdr.tierCount != WTO_NAV_TIER_COUNT) { + snprintf(info->detail, sizeof(info->detail), "not a version %u pack", WTO_NAV_VERSION); + return nullptr; + } + const uint64_t cover_bytes = (uint64_t)hdr.coverCount * sizeof(WtoCoverPoint); + const uint64_t tac_bytes = (uint64_t)hdr.tacCols * hdr.tacRows * sizeof(WtoTacticalCell); + if (!fits(data, hdr.coverOffset, cover_bytes) || !fits(data, hdr.tacOffset, tac_bytes)) { + snprintf(info->detail, sizeof(info->detail), "cover or tactical grid outside the file"); + return nullptr; + } + memcpy(info->packSha1, hdr.everSha1, sizeof(info->packSha1)); + + Pack *pack = new Pack(); + pack->heightSpan = hdr.bmax[1] - hdr.bmin[1]; + for (uint32_t t = 0; t < WTO_NAV_TIER_COUNT; t++) { + if (!load_tier(data, hdr, t, pack, &info->polys[t], info->detail, sizeof(info->detail))) { + free_pack(pack); + return nullptr; + } + } + pack->covers.resize(hdr.coverCount); + if (cover_bytes != 0) + memcpy(pack->covers.data(), data.data() + hdr.coverOffset, (size_t)cover_bytes); + pack->tactical.resize((size_t)hdr.tacCols * hdr.tacRows); + if (tac_bytes != 0) + memcpy(pack->tactical.data(), data.data() + hdr.tacOffset, (size_t)tac_bytes); + info->tiers = WTO_NAV_TIER_COUNT; + info->covers = hdr.coverCount; + 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. + */ +bool snap_to_mesh(const dtNavMeshQuery *query, const dtQueryFilter &filter, float snap, float height_span, + const float point[3], dtPolyRef *ref, float nearest[3]) +{ + const float near_extents[3] = { snap, snap, snap }; + if (dtStatusSucceed(query->findNearestPoly(point, near_extents, &filter, ref, nearest)) && *ref != 0) + return true; + const float column_extents[3] = { snap, height_span > snap ? height_span : snap, snap }; + return dtStatusSucceed(query->findNearestPoly(point, column_extents, &filter, ref, nearest)) && *ref != 0; +} + +double now_micros() +{ + static LARGE_INTEGER frequency; + LARGE_INTEGER counter; + if (frequency.QuadPart == 0) + QueryPerformanceFrequency(&frequency); + QueryPerformanceCounter(&counter); + 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]; + + 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 + +extern "C" int wto_nav_read_level_fingerprint(const wchar_t *level_path, uint8_t sha1[20]) +{ + FILE *file = nullptr; + uint8_t header[12]; + int found = 0; + + if (level_path == nullptr || _wfopen_s(&file, level_path, L"rb") != 0 || file == nullptr) + return 0; + if (fread(header, 1, sizeof(header), file) != sizeof(header) || memcmp(header, "DBLD3x64", 8) != 0) { + fclose(file); + return 0; + } + /* Tagged top-level blocks: u32 length (low 30 bits, tag included), 4-byte NUL-padded tag. */ + for (int block = 0; block < kMaxLevelBlocks && !found; block++) { + uint32_t len_flags = 0; + char tag[4]; + if (fread(&len_flags, 1, 4, file) != 4 || fread(tag, 1, 4, file) != 4) + break; + const uint32_t len = len_flags & 0x3FFFFFFFu; + if (len < 4) + break; + if (memcmp(tag, "\0END", 4) == 0) + break; + if (memcmp(tag, "eVER", 4) != 0) { + if (_fseeki64(file, (long long)len - 4, SEEK_CUR) != 0) + break; + continue; + } + /* Exporter version string (u32 length, bytes padded to 4), section count, level SHA-1. */ + std::vector body(len - 4 <= kMaxEverBytes ? len - 4 : 0); + if (body.empty() || fread(body.data(), 1, body.size(), file) != body.size()) + break; + uint32_t text_len = 0; + memcpy(&text_len, body.data(), body.size() >= 4 ? 4 : 0); + const size_t at = 4 + (((size_t)text_len + 3u) & ~(size_t)3u); + if (body.size() >= 4 && at + 4 + 20 <= body.size()) { + memcpy(sha1, body.data() + at + 4, 20); + found = 1; + } + break; + } + fclose(file); + return found; +} + +extern "C" void wto_nav_load(const wchar_t *pack_path, const uint8_t *level_sha1, WtoNavLoadInfo *info) +{ + 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 (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 && level_sha1 != nullptr) + info->fingerprintMatch = memcmp(info->packSha1, level_sha1, sizeof(info->packSha1)) == 0; + + 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_unload(void) +{ + AcquireSRWLockExclusive(&g_lock); + free_pack(g_pack); + g_pack = nullptr; + g_stats.loaded = 0; + ReleaseSRWLockExclusive(&g_lock); +} + +extern "C" int wto_nav_is_loaded(void) +{ + AcquireSRWLockShared(&g_lock); + const int loaded = g_pack != nullptr; + ReleaseSRWLockShared(&g_lock); + return loaded; +} + +extern "C" void wto_nav_set_costs(uint32_t filter, const WtoNavCosts *costs) +{ + if (filter >= WTO_NAV_RT_FILTER_COUNT || costs == nullptr) + return; + AcquireSRWLockExclusive(&g_lock); + init_filters_locked(); + for (int area = 0; area < WTO_NAV_RT_AREA_COUNT; area++) + g_filters[filter].setAreaCost(area, costs->area[area]); + g_filters[filter].chokepointMul = costs->chokepointMul; + 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); + *stats = g_stats; + ReleaseSRWLockShared(&g_lock); +} diff --git a/native/wto-nav/wto_nav_runtime.h b/native/wto-nav/wto_nav_runtime.h new file mode 100644 index 0000000..a278edc --- /dev/null +++ b/native/wto-nav/wto_nav_runtime.h @@ -0,0 +1,86 @@ +/* + * 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. + * + * Every function is safe to call from any thread; queries are serialized internally. + */ +#pragma once + +#include + +#ifdef __cplusplus +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 */ + +/* Detour traversal costs for one vehicle class, indexed by WtoPolyArea. */ +typedef struct WtoNavCosts { + float area[WTO_NAV_RT_AREA_COUNT]; + float chokepointMul; /* Multiplies the area cost on WTO_FLAG_CHOKEPOINT polygons */ +} WtoNavCosts; + +typedef enum WtoNavLoadResult { + WTO_NAV_LOAD_OK = 0, + WTO_NAV_LOAD_MISSING, /* No pack file for the level */ + WTO_NAV_LOAD_UNREADABLE, /* The file exists but cannot be read */ + WTO_NAV_LOAD_CORRUPT, /* Bad header, offsets or Detour tile data */ +} WtoNavLoadResult; + +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 */ + uint8_t packSha1[20]; + uint8_t levelSha1[20]; + uint32_t tiers; + uint32_t covers; + uint32_t polys[3]; + char detail[96]; /* Why loading failed, for the log */ +} WtoNavLoadInfo; + +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_FAILED, /* No pack loaded, bad tier or Detour failure */ +} WtoNavPathStatus; + +typedef struct WtoNavStats { + int loaded; + uint32_t queries; + uint32_t failures; + double totalMicros; + double maxMicros; +} 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. + */ +void wto_nav_load(const wchar_t *pack_path, const uint8_t *level_sha1, WtoNavLoadInfo *info); +void wto_nav_unload(void); +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); + +/* + * 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. + */ +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); + +void wto_nav_get_stats(WtoNavStats *stats); + +#ifdef __cplusplus +} +#endif diff --git a/native/wto-net/build.ps1 b/native/wto-net/build.ps1 index 4e45c3a..c786288 100644 --- a/native/wto-net/build.ps1 +++ b/native/wto-net/build.ps1 @@ -5,6 +5,8 @@ Output: \wto_ws.dll (default build\native). Static C runtime (/MT), so the DLL needs nothing but the system's ws2_32.dll. MinHook comes from native\third_party\minhook (BSD-2). + The ground AI navigation engine (native\wto-nav) links upstream Detour from + native\third_party\recastnavigation (zlib), compiled separately at its own warning level. #> param([string]$Out = (Join-Path $PSScriptRoot '..\..\build\native')) $ErrorActionPreference = 'Stop' @@ -16,19 +18,34 @@ $vcvars = Join-Path $vs 'VC\Auxiliary\Build\vcvars64.bat' $src = Join-Path $PSScriptRoot 'src' $mh = Join-Path $PSScriptRoot '..\third_party\minhook' +$nav = Join-Path $PSScriptRoot '..\wto-nav' +$dt = Join-Path $PSScriptRoot '..\third_party\recastnavigation\Detour' New-Item -ItemType Directory -Force $Out | Out-Null $obj = Join-Path $Out 'obj' New-Item -ItemType Directory -Force $obj | Out-Null +$dtObj = Join-Path $obj 'detour' +New-Item -ItemType Directory -Force $dtObj | Out-Null -$sources = @( +function Quote($paths) { $paths | ForEach-Object { '"' + (Resolve-Path $_) + '"' } } + +$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_zones.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", "$mh\src\hook.c", "$mh\src\buffer.c", "$mh\src\trampoline.c", "$mh\src\hde\hde64.c" -) | ForEach-Object { '"' + (Resolve-Path $_) + '"' } +) +$detourSources = Quote (Get-ChildItem "$dt\Source\*.cpp").FullName +$detourObjects = (Get-ChildItem "$dt\Source\*.cpp") | ForEach-Object { '"' + (Join-Path $dtObj ($_.BaseName + '.obj')) + '"' } +# Every translation unit that sees dtQueryFilter must agree on its layout (wto_nav_runtime.cpp). +$detourFlags = "/DDT_VIRTUAL_QUERYFILTER /I`"$dt\Include`"" -$command = "`"$vcvars`" >nul && cl /nologo /LD /O2 /MT /W4 /wd4100 /D_CRT_SECURE_NO_WARNINGS /DWIN32_LEAN_AND_MEAN " + - "/I`"$mh\include`" /Fo`"$obj\\`" $($sources -join ' ') /Fe`"$Out\wto_ws.dll`" " + +$detour = "`"$vcvars`" >nul && cl /nologo /c /O2 /MT /EHsc /W3 $detourFlags /Fo`"$dtObj\\`" $($detourSources -join ' ')" +cmd /c $detour +if ($LASTEXITCODE -ne 0) { throw "cl (Detour) failed with $LASTEXITCODE" } + +$command = "`"$vcvars`" >nul && cl /nologo /LD /O2 /MT /EHsc /W4 /wd4100 /D_CRT_SECURE_NO_WARNINGS /DWIN32_LEAN_AND_MEAN $detourFlags " + + "/I`"$mh\include`" /I`"$nav`" /Fo`"$obj\\`" $($sources -join ' ') $($detourObjects -join ' ') /Fe`"$Out\wto_ws.dll`" " + "/link /DEF:`"$src\wto_ws.def`" ws2_32.lib" cmd /c $command if ($LASTEXITCODE -ne 0) { throw "cl failed with $LASTEXITCODE" } diff --git a/native/wto-net/src/hook_config.c b/native/wto-net/src/hook_config.c index a049a16..df86dd0 100644 --- a/native/wto-net/src/hook_config.c +++ b/native/wto-net/src/hook_config.c @@ -9,6 +9,7 @@ * exe.size_of_image=0x... * native.= what the LocalMP modules need from the executable: RVAs of * functions and globals, structure offsets (local_mp_values.c) + * nav.dir= optional, UTF-8: where the ground AI finds .wtonav packs * * wto_ws.log: which host names were answered locally and which connections were redirected or * refused, so a run shows every address the game tried (the audit handover 6.2 asks for). @@ -32,6 +33,7 @@ typedef struct NativeValue { } NativeValue; static wchar_t g_folder[MAX_PATH]; +static wchar_t g_nav_dir[MAX_PATH]; static CRITICAL_SECTION g_log_lock; static FILE *g_log; static int g_log_enabled = 1; @@ -87,10 +89,16 @@ static void read_native_value(const char *line) g_native_count++; } +static void read_nav_dir(const char *utf8) +{ + if (MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, utf8, -1, g_nav_dir, MAX_PATH) == 0) + g_nav_dir[0] = L'\0'; +} + static void read_settings(void) { wchar_t path[MAX_PATH]; - char line[160]; + char line[1024]; FILE *file; if (_snwprintf_s(path, MAX_PATH, _TRUNCATE, L"%swto_ws.cfg", g_folder) < 0) return; @@ -108,10 +116,17 @@ static void read_settings(void) parse_value(line + 18, &g_exe_size_of_image); else if (strncmp(line, NATIVE_PREFIX, sizeof(NATIVE_PREFIX) - 1) == 0) read_native_value(line); + else if (strncmp(line, "nav.dir=", 8) == 0) + read_nav_dir(line + 8); } fclose(file); } +const wchar_t *config_nav_dir(void) +{ + return g_nav_dir; +} + int config_native_value(const char *name, int64_t *value) { size_t i; diff --git a/native/wto-net/src/hook_config.h b/native/wto-net/src/hook_config.h index 5e232f8..db45fb4 100644 --- a/native/wto-net/src/hook_config.h +++ b/native/wto-net/src/hook_config.h @@ -13,3 +13,5 @@ void describe_address(const struct sockaddr *name, int length, char *text, size_ int config_native_value(const char *name, int64_t *value); /* Whether the settings were resolved for the executable this process runs (PE time stamp and size). */ int config_native_matches_executable(void); +/* Folder of the ground AI navigation packs (wto_ws.cfg "nav.dir="); empty when not configured. */ +const wchar_t *config_nav_dir(void); diff --git a/native/wto-net/src/local_mp_ground_ai.c b/native/wto-net/src/local_mp_ground_ai.c index 9dbbcf7..37a13be 100644 --- a/native/wto-net/src/local_mp_ground_ai.c +++ b/native/wto-net/src/local_mp_ground_ai.c @@ -19,6 +19,7 @@ #define SCRIPT_READY_ACTION "wtoGroundAiScriptReady" #define DRIVE_CONTROL_ACTION "wtoGroundAiDriveControl" +#define NAV_ACTION "wtoNav" typedef void (__fastcall *MissionActionFn)(const char *name, const void *blk); typedef uint8_t *(__fastcall *AsGroundModelFn)(uint8_t *unit); @@ -139,6 +140,11 @@ static void __fastcall hook_mission_action(const char *name, const void *blk) } return; } + if (name != NULL && strcmp(name, NAV_ACTION) == 0) { + /* The script's request block doubles as the reply (local_mp_nav.c). */ + local_mp_nav_request((void *)blk); + return; + } if (name == NULL || strcmp(name, DRIVE_CONTROL_ACTION) != 0) { orig_mission_action(name, blk); return; @@ -162,6 +168,8 @@ void local_mp_ground_ai_update(float dt) if (orig_mission_action == NULL) return; hosting = local_mp_is_host(); + if (!hosting) + local_mp_nav_session_ended(); AcquireSRWLockExclusive(&control_lock); for (i = 0; i < sizeof(controls) / sizeof(controls[0]); i++) { GroundAiDriveControl *control = &controls[i]; diff --git a/native/wto-net/src/local_mp_internal.h b/native/wto-net/src/local_mp_internal.h index a0c84b6..fba5627 100644 --- a/native/wto-net/src/local_mp_internal.h +++ b/native/wto-net/src/local_mp_internal.h @@ -112,3 +112,7 @@ void local_mp_zones_reset(void); int install_local_mp_air_event_hooks(void); int install_local_mp_ground_ai_hooks(void); void local_mp_ground_ai_update(float dt); + +/* "wtoNav" requests of the ground AI script and the battle's navigation pack (local_mp_nav.c). */ +void local_mp_nav_request(void *blk); +void local_mp_nav_session_ended(void); diff --git a/native/wto-net/src/local_mp_nav.c b/native/wto-net/src/local_mp_nav.c new file mode 100644 index 0000000..3377b54 --- /dev/null +++ b/native/wto-net/src/local_mp_nav.c @@ -0,0 +1,352 @@ +/* + * "wtoNav" requests of the ground AI script (call_mission_action, local_mp_ground_ai.c) and the + * 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 + * + * 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. + */ +#include "hook_config.h" +#include "local_mp_internal.h" +#include "local_mp_offsets.h" +#include "local_mp_values.h" +#include "wto_nav_runtime.h" + +#include +#include +#include + +#define NAV_MAX_POINTS 96 +#define NAV_LEVEL_MAX 64 + +typedef void (__fastcall *BlkSetStrFn)(void *blk, const char *name, const char *value); +typedef void (__fastcall *BlkSetIntFn)(void *blk, const char *name, const int32_t *value); +typedef void (__fastcall *BlkToOwnedFn)(void *blk); + +typedef enum NavDecision { + NAV_UNDECIDED = 0, + NAV_LOADED, + NAV_FALLBACK, + NAV_FAILED, +} NavDecision; + +typedef struct NavBattle { + NavDecision decision; + char level[NAV_LEVEL_MAX]; + char fingerprint[16]; + char reason[96]; + uint32_t tiers; + uint32_t covers; +} NavBattle; + +/* Costs in the order of WtoPolyArea; empty names are areas the mesh never carries. */ +static const char *const AREA_KEYS[WTO_NAV_RT_AREA_COUNT] = { + "", "road", "bridge", "ground", "rough", "forest", "crushable", "shallowWater", "", "exposed", "", "", +}; + +static NavBattle g_battle; +static SRWLOCK g_battle_lock = SRWLOCK_INIT; +static LONG g_missing_values_logged; + +static int values_ready(void) +{ + if (g_lmp.blk_set_str && g_lmp.blk_set_int && g_lmp.blk_to_owned && + g_lmp_datablock_get_str && g_local_mp_mission_settings) + return 1; + if (InterlockedExchange(&g_missing_values_logged, 1) == 0) + log_line("WTO_NAV|UNAVAILABLE|reason=DataBlock setters of local_mp_awards not resolved"); + return 0; +} + +static void set_str(void *blk, const char *name, const char *value) +{ + ((BlkSetStrFn)g_lmp.blk_set_str)(blk, name, value ? value : ""); +} + +/* Integer setters expect an owned DataBlock (as in local_mp_awards.c). */ +static void set_int(void *blk, const char *name, int32_t value) +{ + if (*(int32_t *)((uint8_t *)blk + LMP_BLK_OFF_OWNED_STATE) != -1) + ((BlkToOwnedFn)g_lmp.blk_to_owned)(blk); + ((BlkSetIntFn)g_lmp.blk_set_int)(blk, name, &value); +} + +static float get_real(const void *blk, const char *name, float def) +{ + const char *text = g_lmp_datablock_get_str(blk, name, ""); + char *end; + float value; + if (text == NULL || text[0] == '\0') + return def; + value = strtof(text, &end); + return (*end == '\0' && value == value) ? value : def; +} + +static long get_long(const void *blk, const char *name, long def) +{ + const char *text = g_lmp_datablock_get_str(blk, name, ""); + char *end; + long value; + if (text == NULL || text[0] == '\0') + return def; + value = strtol(text, &end, 10); + return *end == '\0' ? value : def; +} + +static int32_t to_cm(float metres) +{ + const float cm = metres * 100.0f; + if (cm > 2.0e9f) + return INT32_MAX; + if (cm < -2.0e9f) + return INT32_MIN; + return (int32_t)(cm >= 0.0f ? cm + 0.5f : cm - 0.5f); +} + +static void hex20(const uint8_t *sha1, char out[41]) +{ + static const char digits[] = "0123456789abcdef"; + int i; + for (i = 0; i < 20; i++) { + out[i * 2] = digits[sha1[i] >> 4]; + out[i * 2 + 1] = digits[sha1[i] & 15]; + } + out[40] = '\0'; +} + +/* "levels/avg_berlin.bin" -> "avg_berlin"; only names the bake could have produced. */ +static int battle_level(char out[NAV_LEVEL_MAX]) +{ + const char *path = g_lmp_datablock_get_str(g_local_mp_mission_settings + LMP_MIS_OFF_CUSTOM_BOTS, "wtoLevel", ""); + const char *name, *dot; + size_t len, i; + + if (path == NULL || path[0] == '\0') + return 0; + name = strrchr(path, '/'); + name = name ? name + 1 : path; + dot = strrchr(name, '.'); + len = dot ? (size_t)(dot - name) : strlen(name); + if (len == 0 || len >= NAV_LEVEL_MAX) + return 0; + for (i = 0; i < len; i++) { + const char c = name[i]; + if (!((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_')) + return 0; + out[i] = c; + } + out[len] = '\0'; + return 1; +} + +/* \levels\.bin, the game folder being the parent of the executable's win64 folder. */ +static int level_file_path(const char *level, wchar_t *out, size_t out_count) +{ + wchar_t exe[MAX_PATH]; + wchar_t *slash; + DWORD length = GetModuleFileNameW(NULL, exe, MAX_PATH); + int i; + + if (length == 0 || length >= MAX_PATH) + return 0; + for (i = 0; i < 2; i++) { + slash = wcsrchr(exe, L'\\'); + if (slash == NULL) + return 0; + *slash = L'\0'; + } + return _snwprintf_s(out, out_count, _TRUNCATE, L"%s\\levels\\%S.bin", exe, level) > 0; +} + +static void read_costs(const void *blk, const char *prefix, WtoNavCosts *costs) +{ + char key[48]; + int area; + for (area = 0; area < WTO_NAV_RT_AREA_COUNT; area++) { + costs->area[area] = 1.0f; + if (AREA_KEYS[area][0] == '\0') + continue; + snprintf(key, sizeof(key), "%s_%s", prefix, AREA_KEYS[area]); + costs->area[area] = get_real(blk, key, 1.0f); + if (!(costs->area[area] > 0.0f)) + costs->area[area] = 1.0f; + } + snprintf(key, sizeof(key), "%s_chokepoint", prefix); + costs->chokepointMul = get_real(blk, key, 1.0f); + if (!(costs->chokepointMul > 0.0f)) + costs->chokepointMul = 1.0f; +} + +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); + 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); + 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); + return; + } + snprintf(g_battle.fingerprint, sizeof(g_battle.fingerprint), "unknown"); + g_battle.decision = allow_fallback ? NAV_FALLBACK : NAV_FAILED; + if (allow_fallback) + log_line("WTO_NAV|FALLBACK_STOCK_NAV|level=%s|reason=%s", g_battle.level, g_battle.reason); + else + log_line("WTO_NAV|LOAD_FAILED_NO_FALLBACK|level=%s|reason=%s", g_battle.level, g_battle.reason); +} + +static void load_map(void *blk) +{ + static const char *const STATES[] = { "", "loaded", "fallback", "failed" }; + const int allow_fallback = get_long(blk, "allowFallback", 1) != 0; + + AcquireSRWLockExclusive(&g_battle_lock); + if (g_battle.decision == NAV_UNDECIDED) + decide_locked(blk, allow_fallback); + set_str(blk, "state", STATES[g_battle.decision]); + set_str(blk, "fingerprint", g_battle.fingerprint); + set_str(blk, "level", g_battle.level); + set_str(blk, "reason", g_battle.reason); + set_int(blk, "tiers", (int32_t)g_battle.tiers); + set_int(blk, "covers", (int32_t)g_battle.covers); + ReleaseSRWLockExclusive(&g_battle_lock); +} + +static void unload_locked(const char *why) +{ + if (g_battle.decision == NAV_UNDECIDED) + return; + 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", + g_battle.level, why, stats.queries, stats.failures, + stats.queries ? stats.totalMicros / stats.queries : 0.0, stats.maxMicros); + wto_nav_unload(); + } + memset(&g_battle, 0, sizeof(g_battle)); +} + +static void find_path(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; + + 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++) { + 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])); + } +} + +static void get_stats(void *blk) +{ + WtoNavStats stats; + wto_nav_get_stats(&stats); + set_int(blk, "loaded", stats.loaded); + set_int(blk, "queries", (int32_t)stats.queries); + 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); +} + +void local_mp_nav_request(void *blk) +{ + const char *op; + + if (blk == NULL || !values_ready()) + return; + op = g_lmp_datablock_get_str(blk, "op", ""); + if (op == NULL) + return; + if (strcmp(op, "find_path") == 0) { + find_path(blk); + } else if (strcmp(op, "load_map") == 0) { + load_map(blk); + } else if (strcmp(op, "unload_map") == 0) { + AcquireSRWLockExclusive(&g_battle_lock); + unload_locked("battle ended"); + ReleaseSRWLockExclusive(&g_battle_lock); + set_int(blk, "ok", 1); + } else if (strcmp(op, "get_stats") == 0) { + get_stats(blk); + } else { + log_line("WTO_NAV|BAD_REQUEST|op=%s", op); + } +} + +void local_mp_nav_session_ended(void) +{ + if (TryAcquireSRWLockExclusive(&g_battle_lock)) { + unload_locked("session ended"); + ReleaseSRWLockExclusive(&g_battle_lock); + } +} diff --git a/packages/patcher/src/build-game-copy.ts b/packages/patcher/src/build-game-copy.ts index 2666592..de01a2f 100644 --- a/packages/patcher/src/build-game-copy.ts +++ b/packages/patcher/src/build-game-copy.ts @@ -69,6 +69,8 @@ export interface GameCopyInputs { readonly extraStockPacks?: Partial>; /** Optional modular ground AI scripts and tuning compiled into `game.vromfs.bin` when active. */ readonly groundAi?: GroundAiBuildInputs; + /** Absolute folder of the `.wtonav` navigation packs the ground AI loads per battle. */ + readonly mapNavFolder?: string; } /** One file of the game copy, by its path relative to the copy folder. */ @@ -140,6 +142,7 @@ export function buildGameCopy(inputs: GameCopyInputs): GameCopyBuild { const executableFolder = dirname(GAME_FILES.executable); const hookSettings = networkHookSettings(endpoint, stockImage, native.values, { loggingEnabled: inputs.hookLogging ?? true, + ...(inputs.mapNavFolder !== undefined ? { mapNavFolder: inputs.mapNavFolder } : {}), }); const files: GameCopyFile[] = [ { path: GAME_FILES.charPack, content: core.charPack }, diff --git a/packages/patcher/src/ground-ai/ground-ai-config.ts b/packages/patcher/src/ground-ai/ground-ai-config.ts index 471fab1..72c188c 100644 --- a/packages/patcher/src/ground-ai/ground-ai-config.ts +++ b/packages/patcher/src/ground-ai/ground-ai-config.ts @@ -23,6 +23,22 @@ export interface GroundAiLoadoutConfig { readonly penetrationCompareDistM: number; } +/** Path cost multipliers per baked surface; chokepoint multiplies the surface cost. */ +export interface GroundAiNavCosts { + readonly road: number; + readonly bridge: number; + readonly ground: number; + readonly rough: number; + readonly forest: number; + readonly crushable: number; + readonly shallowWater: number; + readonly chokepoint: number; +} + +export const GROUND_AI_NAV_COST_KEYS = [ + 'road', 'bridge', 'ground', 'rough', 'forest', 'crushable', 'shallowWater', 'chokepoint', +] as const satisfies readonly (keyof GroundAiNavCosts)[]; + export interface GroundAiConfig { readonly mode: GroundAiMode; readonly loadout: GroundAiLoadoutConfig; @@ -99,6 +115,14 @@ export interface GroundAiConfig { readonly tacticalReverseDistM: number; readonly tacticalReverseMaxSec: number; }; + /** Baked navigation packs loaded by the native engine (native/wto-nav). */ + readonly navEngine: { + readonly enabled: boolean; + readonly allowFallback: boolean; + readonly snapRadiusM: number; + }; + readonly navCostsTracked: GroundAiNavCosts; + readonly navCostsWheeled: GroundAiNavCosts; readonly perception: { readonly foliageTransparency: number; readonly nearSpotRangeM: number; @@ -282,6 +306,11 @@ function collectConfigEntries(c: GroundAiConfig): readonly DasEntry[] { ['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], + ...navCostEntries('T', c.navCostsTracked), + ...navCostEntries('W', c.navCostsWheeled), ['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], @@ -351,6 +380,13 @@ function collectConfigEntries(c: GroundAiConfig): readonly DasEntry[] { ]; } +/** WTO_AI_NAVMESH__, e.g. WTO_AI_NAVMESH_T_SHALLOW_WATER. */ +function navCostEntries(prefix: 'T' | 'W', costs: GroundAiNavCosts): readonly DasEntry[] { + return GROUND_AI_NAV_COST_KEYS.map((key): DasEntry => [ + `WTO_AI_NAVMESH_${prefix}_${key.replace(/[A-Z]/g, (c) => `_${c}`).toUpperCase()}`, 'float', costs[key], + ]); +} + 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 f44934a..f820fb3 100644 --- a/packages/patcher/src/index.ts +++ b/packages/patcher/src/index.ts @@ -70,11 +70,13 @@ export { compileGroundAiConfigDas, GROUND_AI_DRIVE_MODES, GROUND_AI_MODES, + GROUND_AI_NAV_COST_KEYS, isGroundAiActive, type GroundAiConfig, type GroundAiDriveMode, type GroundAiLoadoutConfig, type GroundAiMode, + type GroundAiNavCosts, } 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'; diff --git a/packages/patcher/src/network/network-hook.ts b/packages/patcher/src/network/network-hook.ts index 583dbbf..911ccba 100644 --- a/packages/patcher/src/network/network-hook.ts +++ b/packages/patcher/src/network/network-hook.ts @@ -3,8 +3,10 @@ * online/network-hook-library makes aces.exe load win64/wto_ws.dll, which reads its settings * from win64/wto_ws.cfg: the local server port, and the values its LocalMP modules need from the * executable (native/native-settings.ts). Both files are written next to the executable; the DLL - * is built from native/wto-net (build.ps1). + * is built from native/wto-net (build.ps1). `mapNavFolder` tells the ground AI where the + * `.wtonav` navigation packs are (native/wto-net/src/local_mp_nav.c). */ +import { isAbsolute, win32 } from 'node:path'; import type { PeImage } from '@wto/exepatch'; import { nativeSettingsLines } from '../native/native-settings.ts'; import type { LocalEndpoint } from './local-endpoint.ts'; @@ -17,12 +19,17 @@ export function networkHookSettings( endpoint: LocalEndpoint, stock: PeImage, nativeValues: ReadonlyMap, - options?: { readonly loggingEnabled?: boolean }, + options?: { readonly loggingEnabled?: boolean; readonly mapNavFolder?: string }, ): { name: string; content: Uint8Array } { + const navFolder = options?.mapNavFolder; + if (navFolder !== undefined && (/[\r\n\0]/.test(navFolder) || !isAbsolute(navFolder))) { + throw new Error(`map navigation folder must be a single-line absolute path: ${navFolder}`); + } const lines = [ `port=${endpoint.port}`, ...(options?.loggingEnabled === false ? ['log=0'] : []), ...nativeSettingsLines(stock, nativeValues), + ...(navFolder !== undefined ? [`nav.dir=${win32.normalize(navFolder).replace(/\\+$/, '')}`] : []), ]; return { name: SETTINGS, content: new TextEncoder().encode(`${lines.join('\n')}\n`) }; } diff --git a/patches/native/local_mp_ground_ai.jsonc b/patches/native/local_mp_ground_ai.jsonc index 2c6d023..e7dd07e 100644 --- a/patches/native/local_mp_ground_ai.jsonc +++ b/patches/native/local_mp_ground_ai.jsonc @@ -1,10 +1,12 @@ // Temporary movement ownership for custom ground AI on a LocalMP host. // The local server cannot restore the MoveSystem flag if a game script stops running. // Without this module, stock tank movement keeps ownership of the vehicle. +// The same mission action carries the script's "wtoNav" navigation queries, answered through the +// DataBlock setters of local_mp_awards. { "module": "local_mp_ground_ai", "features": ["K-AI opponents and teammates"], - "requires": ["local_mp_core", "local_mp_players"], + "requires": ["local_mp_core", "local_mp_players", "local_mp_awards"], "sites": { // daScript call_mission_action binding, capturing the registered native function. // 2.61.0.37: 0xa6be4d -> 0xa63750. 2.61.0.58: 0xa6eb0d -> 0xa66410. diff --git a/scripts/build-game-copy.ts b/scripts/build-game-copy.ts index cfd760a..2e87ada 100644 --- a/scripts/build-game-copy.ts +++ b/scripts/build-game-copy.ts @@ -5,6 +5,7 @@ * --data * [--patches ] * [--native ] [--decal-cache ] + * [--map-nav .wtonav packs>] * [--skip-unavailable] [--verbose] * * Writes /char.vromfs.bin, /aces.vromfs.bin, /gui.vromfs.bin, /win64/aces.exe @@ -13,14 +14,15 @@ * --data is the folder the local server will run with: the store packs it sells there (its tuning * with that folder's overrides) get bundle GUIDs in gui.blk. --decal-cache names the cache/content * folder of the player's online installation; it is copied to /cache/content, otherwise - * char.vromfs.bin gets the placeholder decal index. + * char.vromfs.bin gets the placeholder decal index. --map-nav names the folder of the baked + * ground AI navigation packs (tools/navgen); wto_ws.dll loads them from there, nothing is copied. * When a patch is unavailable nothing is written, unless --skip-unavailable is given and none of * the unavailable patches is essential (the patcher's essential-features.ts). * The patch set (exe, GUI and native definitions) and the hook library default to this * repository's patches/ and build/native. The launcher runs the same build at every launch, with the port the player chose. */ import { existsSync, readFileSync } from 'node:fs'; -import { join } from 'node:path'; +import { join, resolve } from 'node:path'; import { fileURLToPath } from 'node:url'; import { parseArgs } from 'node:util'; import type { PatchFailure } from '@wto/exepatch'; @@ -47,7 +49,7 @@ import { loadGroundAiTuning, multiVehiclePackIds } from '@wto/server'; const REPOSITORY = fileURLToPath(new URL('..', import.meta.url)); const USAGE = 'usage: build-game-copy.ts --game --out --port --data ' + '[--patches ] [--native ] [--ground-ai ] ' - + '[--mods-dir --mod ...] [--decal-cache ] [--skip-unavailable] [--verbose]'; + + '[--mods-dir --mod ...] [--decal-cache ] [--map-nav ] [--skip-unavailable] [--verbose]'; function resolveCliMods(modsDir: string | undefined, modIds: readonly string[] | undefined): DiscoveredMod[] { if (!modsDir || !modIds || modIds.length === 0) return []; @@ -73,6 +75,7 @@ function parseCliOptions() { 'mods-dir': { type: 'string' }, mod: { type: 'string', multiple: true }, 'decal-cache': { type: 'string' }, + 'map-nav': { type: 'string' }, 'skip-unavailable': { type: 'boolean', default: false }, verbose: { type: 'boolean', default: false }, }, @@ -99,6 +102,12 @@ function main(): number { return 1; } + const mapNav = values['map-nav'] === undefined ? undefined : resolve(values['map-nav']); + if (mapNav !== undefined && !existsSync(mapNav)) { + console.error(`--map-nav: ${mapNav} not found; nothing was written`); + return 1; + } + const port = Number(values.port); const enabledMods = resolveCliMods(values['mods-dir'], values.mod); const groundAiConfig = loadGroundAiTuning(values.data, (line) => console.log(line), enabledMods); @@ -123,6 +132,7 @@ function main(): number { ...(enabledMods.length > 0 ? { mods: enabledMods } : {}), ...(extraStockPacks ? { extraStockPacks } : {}), groundAi: { scriptsFolder: values['ground-ai'], config: groundAiConfig }, + ...(mapNav !== undefined ? { mapNavFolder: mapNav } : {}), }); report(build, values.verbose); return finishCliWrite(values, build, enabledMods, optionalPacksInBuild, groundAiConfig, port);