feat(ground-ai): add offline tank navmesh and cover baking prototype

Add Stage 0 offline map geometry extraction and Recast/Detour baking tools for ground AI navigation on feat/tank-ai-nav:

- Vendor upstream recastnavigation Recast and Detour sources (zlib license) under native/third_party/recastnavigation.
- Define shared .wtogeo and .wtonav binary layouts in native/wto-nav/wto_nav_format.h.
- Add mission-bounds.mts to collect union ground battle areas, spawns, and capture zones across mission templates.
- Add Rust extractor (tools/navgen/extract) using wt-unpack and config/rendinst_dmg.blk destructionImpulse thresholds to classify hard solids, bridges, crushable objects, and tree trunks in Dagor world space.
- Add multi-threaded MSVC C++ baker (tools/navgen/bake) producing 3 vehicle-width tiled Detour navmeshes, island pruning, dual-height voxel tank covers (full, hull-down, corner peek, retreat-verified), 8m tactical grids, and spawn-to-cap connectivity checks.
- Add zero-dependency PNG top-down preview renderer (tools/navgen/render-preview.py).

Verified: Rust release build (0 warnings), MSVC x64 baker build (0 warnings), root typecheck, and end-to-end extraction/baking/100% 3-tier connectivity and preview rendering on avg_berlin, avg_poland, and avg_hurtgen (2.61.0.58).
This commit is contained in:
N0VAN0M4LY committed 2026-12-04 11:33:32 +08:00
1 parent 688406bb76
commit 842ee23fa4
40 files changed
+22824

No files matched your search

+550
View File
@@ -0,0 +1,550 @@
use std::collections::{HashMap, HashSet};
use std::fs::{self, File};
use std::io::{BufWriter, Write};
use std::path::{Path, PathBuf};
use std::time::Instant;
use anyhow::{bail, Context, Result};
use serde::Deserialize;
use wt_formats::grp::GrpPack;
use wt_unpack::blk::{self, Value};
use wt_unpack::collision::{Collision, CollisionNode, NodeKind, COLLISION};
use wt_unpack::level::{Heightmap, Level};
use wt_unpack::rendinst::ResourceIndex;
use wt_unpack::vromfs::Vromfs;
const WTO_GEO_MAGIC: &[u8; 8] = b"WTOGEO\0\x01";
const WTO_GEO_VERSION: u32 = 1;
const OBS_HARD_SOLID: u8 = 0;
const OBS_BRIDGE_DECK: u8 = 1;
const OBS_CRUSHABLE: u8 = 2;
const OBS_TREE_THICK: u8 = 3;
const OBS_TREE_THIN: u8 = 4;
#[derive(Debug, Deserialize)]
struct LevelPois {
level: String,
#[serde(rename = "levelPath")]
level_path: String,
#[serde(rename = "boundsMin")]
bounds_min: [f32; 2],
#[serde(rename = "boundsMax")]
bounds_max: [f32; 2],
}
#[derive(Debug, Clone)]
struct PoolMeta {
is_bridge: bool,
is_crushable: bool,
is_soft_foliage: bool,
}
#[derive(Debug)]
struct CachedCollision {
max_radius: f32,
tris: Vec<([f32; 3], [f32; 3], [f32; 3], u8)>,
}
fn parse_args() -> Result<(PathBuf, PathBuf, PathBuf)> {
let mut game: Option<PathBuf> = None;
let mut pois: Option<PathBuf> = None;
let mut out: Option<PathBuf> = None;
let mut args = std::env::args().skip(1);
while let Some(a) = args.next() {
match a.as_str() {
"--game" => game = args.next().map(PathBuf::from),
"--pois" => pois = args.next().map(PathBuf::from),
"--out" => out = args.next().map(PathBuf::from),
other => bail!("unknown argument: {other}"),
}
}
Ok((
game.context("missing --game <clientDir>")?,
pois.context("missing --pois <level.pois.json>")?,
out.context("missing --out <level.wtogeo>")?,
))
}
struct AcesMeta {
water_level: f32,
/// Authoritative tank-crushable impulse threshold from `config/rendinst_dmg.blk` (lowercase name -> destructionImpulse).
destr_impulse: HashMap<String, f32>,
}
fn read_aces_meta(game: &Path, level_name: &str) -> AcesMeta {
let mut meta = AcesMeta { water_level: -1.0e6, destr_impulse: HashMap::new() };
let aces_path = game.join("aces.vromfs.bin");
let Ok(raw) = fs::read(&aces_path) else { return meta; };
let Ok(arc) = Vromfs::parse(&raw) else { return meta; };
let shared = arc
.files
.iter()
.find(|f| f.name == wt_unpack::vromfs::SHARED_NAMEMAP_NAME)
.and_then(|nm| blk::SharedContext::from_namemap(&nm.data).ok())
.map(|(mut ctx, dict_name)| {
if let Some(df) = arc.files.iter().find(|f| f.name.eq_ignore_ascii_case(&dict_name)) {
ctx.dict = Some(df.data.clone());
}
ctx
});
let target = format!("levels/{}.blk", level_name.to_lowercase());
if let Some(entry) = arc.files.iter().find(|f| f.name.eq_ignore_ascii_case(&target)) {
if let Ok(doc) = blk::parse(&entry.data, shared.as_ref()) {
for (name, value) in &doc.params {
if name.eq_ignore_ascii_case("water_level") {
match value {
Value::Real(v) => meta.water_level = *v,
Value::Int(v) => meta.water_level = *v as f32,
_ => {}
}
}
}
}
}
if let Some(dmg_entry) = arc.files.iter().find(|f| f.name.eq_ignore_ascii_case("config/rendinst_dmg.blk")) {
if let Ok(doc) = blk::parse(&dmg_entry.data, shared.as_ref()) {
for b in &doc.blocks {
let mut rname: Option<&str> = None;
let mut impulse: Option<f32> = None;
for (k, v) in &b.params {
if k.eq_ignore_ascii_case("name") {
if let Value::Str(s) = v { rname = Some(s.as_str()); }
} else if k.eq_ignore_ascii_case("destructionImpulse") {
match v {
Value::Real(x) => impulse = Some(*x),
Value::Int(x) => impulse = Some(*x as f32),
_ => {}
}
}
}
if let (Some(n), Some(imp)) = (rname, impulse) {
meta.destr_impulse.insert(n.to_lowercase(), imp);
}
}
}
}
meta
}
fn classify_pool(name: &str, destr_impulse: Option<f32>) -> PoolMeta {
let lower = name.to_lowercase();
let is_bridge = lower.contains("bridge")
|| lower.contains("viaduct")
|| lower.contains("overpass")
|| lower.contains("pontoon")
|| lower.contains("jetty")
|| lower.contains("pier");
let always_hard = lower.contains("rock")
|| lower.contains("cliff")
|| lower.contains("bunker")
|| lower.contains("house")
|| lower.contains("building")
|| lower.contains("castle")
|| lower.contains("tower")
|| lower.contains("church")
|| lower.contains("factory")
|| lower.contains("hangar")
|| lower.contains("wagon")
|| lower.contains("train")
|| lower.contains("locomotive")
|| lower.contains("container")
|| lower.contains("tank_wreck")
|| is_bridge;
let is_soft_foliage = !always_hard
&& (lower.starts_with("bush_")
|| lower.contains("_bush_")
|| lower.starts_with("shrub_")
|| lower.contains("_shrub_")
|| lower.contains("grass")
|| lower.contains("reed")
|| lower.contains("flower")
|| lower.contains("fern"));
// Authoritative War Thunder physics: objects in `config/rendinst_dmg.blk` with low
// `destructionImpulse` (<= 45,000 N*s) are crushed on contact by moving tanks (wooden fences,
// lamp posts, hedges, benches, sheds, destructible thin walls, small trees).
let is_crushable = !always_hard
&& match destr_impulse {
Some(imp) if imp > 0.0 && imp <= 45_000.0 => true,
_ => lower.contains("fence_wood")
|| lower.contains("wooden_fence")
|| lower.contains("hedge")
|| lower.contains("sign_")
|| lower.contains("bench")
|| lower.contains("hay"),
};
PoolMeta { is_bridge, is_crushable, is_soft_foliage }
}
fn transform_point(tm: &[[f32; 3]; 4], p: [f32; 3]) -> [f32; 3] {
[
tm[0][0] * p[0] + tm[1][0] * p[1] + tm[2][0] * p[2] + tm[3][0],
tm[0][1] * p[0] + tm[1][1] * p[1] + tm[2][1] * p[2] + tm[3][1],
tm[0][2] * p[0] + tm[1][2] * p[1] + tm[2][2] * p[2] + tm[3][2],
]
}
fn det3(tm: &[[f32; 3]; 4]) -> f32 {
let [a, b, c] = [tm[0], tm[1], tm[2]];
a[0] * (b[1] * c[2] - b[2] * c[1]) - a[1] * (b[0] * c[2] - b[2] * c[0])
+ a[2] * (b[0] * c[1] - b[1] * c[0])
}
fn box_tris(n: &CollisionNode) -> Vec<([f32; 3], [f32; 3], [f32; 3])> {
let [lo, hi] = n.bbox;
let c = |i: usize| {
n.to_object([
if i & 1 == 0 { lo[0] } else { hi[0] },
if i & 2 == 0 { lo[1] } else { hi[1] },
if i & 4 == 0 { lo[2] } else { hi[2] },
])
};
let pts: Vec<[f32; 3]> = (0..8).map(c).collect();
let quads = [[0, 2, 3, 1], [4, 5, 7, 6], [0, 1, 5, 4], [2, 6, 7, 3], [0, 4, 6, 2], [1, 3, 7, 5]];
let mut tris = Vec::with_capacity(12);
for q in quads {
tris.push((pts[q[0]], pts[q[1]], pts[q[2]]));
tris.push((pts[q[0]], pts[q[2]], pts[q[3]]));
}
tris
}
fn capsule_tris(a: [f32; 3], b: [f32; 3], r: f32) -> Vec<([f32; 3], [f32; 3], [f32; 3])> {
let dx = b[0] - a[0];
let dy = b[1] - a[1];
let dz = b[2] - a[2];
let len = (dx * dx + dy * dy + dz * dz).sqrt();
let axis = if len > 1e-4 { [dx / len, dy / len, dz / len] } else { [0.0, 1.0, 0.0] };
let up = if axis[1].abs() < 0.9 { [0.0, 1.0, 0.0] } else { [1.0, 0.0, 0.0] };
let cross = |u: [f32; 3], v: [f32; 3]| {
[u[1] * v[2] - u[2] * v[1], u[2] * v[0] - u[0] * v[2], u[0] * v[1] - u[1] * v[0]]
};
let norm = |v: [f32; 3]| {
let l = (v[0] * v[0] + v[1] * v[1] + v[2] * v[2]).sqrt().max(1e-6);
[v[0] / l, v[1] / l, v[2] / l]
};
let u = norm(cross(axis, up));
let v = norm(cross(axis, u));
let segs = 6usize;
let mut ring_a = Vec::with_capacity(segs);
let mut ring_b = Vec::with_capacity(segs);
for i in 0..segs {
let ang = (i as f32) * std::f32::consts::TAU / (segs as f32);
let (ca, sa) = (ang.cos() * r, ang.sin() * r);
let off = [u[0] * ca + v[0] * sa, u[1] * ca + v[1] * sa, u[2] * ca + v[2] * sa];
ring_a.push([a[0] + off[0], a[1] + off[1], a[2] + off[2]]);
ring_b.push([b[0] + off[0], b[1] + off[1], b[2] + off[2]]);
}
let mut tris = Vec::with_capacity(segs * 2);
for i in 0..segs {
let j = (i + 1) % segs;
tris.push((ring_a[i], ring_a[j], ring_b[j]));
tris.push((ring_a[i], ring_b[j], ring_b[i]));
}
tris
}
fn tri_normal_y(a: [f32; 3], b: [f32; 3], c: [f32; 3]) -> f32 {
let e1 = [b[0] - a[0], b[1] - a[1], b[2] - a[2]];
let e2 = [c[0] - a[0], c[1] - a[1], c[2] - a[2]];
let nx = e1[1] * e2[2] - e1[2] * e2[1];
let ny = e1[2] * e2[0] - e1[0] * e2[2];
let nz = e1[0] * e2[1] - e1[1] * e2[0];
let len = (nx * nx + ny * ny + nz * nz).sqrt();
if len > 1e-6 { (ny / len).abs() } else { 0.0 }
}
fn build_cached_collision(c: &Collision, meta: &PoolMeta) -> Option<CachedCollision> {
if meta.is_soft_foliage {
return None;
}
let mut tris = Vec::new();
for n in &c.nodes {
// Vehicles only collide with physics_collidable nodes (behavior bit 1).
if !n.physics_collidable() {
continue;
}
let mat_soft = !n.materials.is_empty()
&& n.materials.iter().all(|m| {
let ml = m.to_lowercase();
ml.contains("bush") || ml.contains("foliage") || ml.contains("leaves") || ml.contains("glass")
});
if mat_soft {
continue;
}
let scale = det3(&n.tm).abs().cbrt();
match n.kind {
NodeKind::Mesh | NodeKind::Convex => {
if n.indices.len() < 3 {
continue;
}
for t in n.indices.chunks_exact(3) {
let p0 = n.to_object(n.positions[t[0] as usize]);
let p1 = n.to_object(n.positions[t[1] as usize]);
let p2 = n.to_object(n.positions[t[2] as usize]);
let cls = if meta.is_bridge && tri_normal_y(p0, p1, p2) >= 0.72 {
OBS_BRIDGE_DECK
} else if meta.is_crushable {
OBS_CRUSHABLE
} else {
OBS_HARD_SOLID
};
tris.push((p0, p1, p2, cls));
}
}
NodeKind::Box => {
for (p0, p1, p2) in box_tris(n) {
let cls = if meta.is_bridge && tri_normal_y(p0, p1, p2) >= 0.72 {
OBS_BRIDGE_DECK
} else if meta.is_crushable {
OBS_CRUSHABLE
} else {
OBS_HARD_SOLID
};
tris.push((p0, p1, p2, cls));
}
}
NodeKind::Capsule => {
if let Some(cap) = n.capsule {
let a = n.to_object(cap.a);
let b = n.to_object(cap.b);
let r = (cap.radius * scale).max(0.08);
let cls = if r >= 0.28 { OBS_TREE_THICK } else { OBS_TREE_THIN };
for (p0, p1, p2) in capsule_tris(a, b, r) {
tris.push((p0, p1, p2, cls));
}
}
}
NodeKind::Points | NodeKind::Sphere => {}
}
}
if tris.is_empty() {
return None;
}
let bmin = c.bbox[0];
let bmax = c.bbox[1];
let max_r = [bmin[0].abs().max(bmax[0].abs()), bmin[2].abs().max(bmax[2].abs())]
.iter()
.copied()
.fold(0.0f32, f32::max)
* 1.42;
Some(CachedCollision { max_radius: max_r.max(4.0), tris })
}
fn crop_heightmap(hm: &Heightmap, min_x: f32, min_z: f32, max_x: f32, max_z: f32) -> (u32, u32, [f32; 2], Vec<f32>) {
let cs = hm.cell_size;
let x0 = (((min_x - hm.origin[0]) / cs).floor() as i32).clamp(0, (hm.width as i32) - 2) as u32;
let z0 = (((min_z - hm.origin[1]) / cs).floor() as i32).clamp(0, (hm.height as i32) - 2) as u32;
let x1 = (((max_x - hm.origin[0]) / cs).ceil() as i32).clamp((x0 as i32) + 1, (hm.width as i32) - 1) as u32;
let z1 = (((max_z - hm.origin[1]) / cs).ceil() as i32).clamp((z0 as i32) + 1, (hm.height as i32) - 1) as u32;
let cw = x1 - x0 + 1;
let ch = z1 - z0 + 1;
let mut heights = Vec::with_capacity((cw * ch) as usize);
for z in z0..=z1 {
let row = (z as usize) * (hm.width as usize);
for x in x0..=x1 {
heights.push(hm.metres(hm.data[row + x as usize]));
}
}
let origin = [hm.origin[0] + (x0 as f32) * cs, hm.origin[1] + (z0 as f32) * cs];
(cw, ch, origin, heights)
}
fn main() -> Result<()> {
let t0 = Instant::now();
let (game_dir, pois_path, out_path) = parse_args()?;
let pois: LevelPois = serde_json::from_str(
&fs::read_to_string(&pois_path).with_context(|| format!("reading {}", pois_path.display()))?,
)?;
let level_file = game_dir.join(&pois.level_path);
let raw = fs::read(&level_file).with_context(|| format!("reading {}", level_file.display()))?;
let level = Level::parse(&raw).with_context(|| format!("parsing {}", level_file.display()))?;
let ever_sha1 = level.export_info()?.and_then(|e| e.sha1).unwrap_or([0u8; 20]);
let aces_meta = read_aces_meta(&game_dir, &pois.level);
let water_level = aces_meta.water_level;
if let Some(pm) = level.phys_map_info()? {
println!(
" LMp2: {}x{} scale={:.2}m origin=({:.0},{:.0}) mats={:?}",
pm.size[0],
pm.size[1],
pm.metres_per_texel,
pm.world_origin[0],
pm.world_origin[1],
&pm.materials[..pm.materials.len().min(10)]
);
}
let hm = level.heightmap()?.with_context(|| format!("{} has no HM2 heightmap", pois.level))?;
let (cw, ch, crop_origin, heights) = crop_heightmap(
&hm,
pois.bounds_min[0],
pois.bounds_min[1],
pois.bounds_max[0],
pois.bounds_max[1],
);
let crop_max_x = crop_origin[0] + ((cw - 1) as f32) * hm.cell_size;
let crop_max_z = crop_origin[1] + ((ch - 1) as f32) * hm.cell_size;
println!(
"{}: HM2 full={}x{} cs={:.2}m -> crop={}x{} [{:.0}..{:.0}]x[{:.0}..{:.0}] water={:.2}m",
pois.level,
hm.width,
hm.height,
hm.cell_size,
cw,
ch,
crop_origin[0],
crop_max_x,
crop_origin[1],
crop_max_z,
water_level
);
// Collect distinct placed RendInst pools from RIGz
let layers = level.rendinst_layers()?;
let mut pool_names: HashSet<String> = HashSet::new();
for layer in &layers {
for (pool, cnt) in layer.pools.iter().zip(layer.counts()) {
if cnt > 0 {
pool_names.insert(pool.name.clone());
}
}
}
let res_index = ResourceIndex::build(&game_dir, &[COLLISION])?;
// Group collision loads by .grp file so each pack is read once
let mut by_pack: HashMap<PathBuf, Vec<(String, String)>> = HashMap::new();
let mut no_collision = 0usize;
for name in &pool_names {
let res_name = format!("{name}_collision");
if let Some(p) = res_index.find(COLLISION, &res_name) {
by_pack.entry(p.to_path_buf()).or_default().push((name.clone(), res_name));
} else {
no_collision += 1;
}
}
let mut cached_cols: HashMap<String, CachedCollision> = HashMap::new();
for (pack_path, items) in &by_pack {
let Ok(bytes) = fs::read(pack_path) else { continue };
let Ok(pack) = GrpPack::parse(&bytes) else { continue };
for (pool_name, res_name) in items {
let Some(res) = pack.find(res_name, COLLISION) else { continue };
let Ok(col) = Collision::parse(res_name, pack.data(res)) else { continue };
let imp = aces_meta.destr_impulse.get(&pool_name.to_lowercase()).copied();
let meta = classify_pool(pool_name, imp);
if let Some(cc) = build_cached_collision(&col, &meta) {
cached_cols.insert(pool_name.clone(), cc);
}
}
}
// Stream placed collision triangles inside the cropped battle area
let pad = 16.0;
let mut verts: Vec<[f32; 3]> = Vec::with_capacity(200_000);
let mut tris: Vec<([u32; 3], u8)> = Vec::with_capacity(100_000);
let mut inst_used = 0usize;
let mut cls_counts = [0usize; 5];
for layer in &layers {
let instances = layer.instances()?;
for inst in instances {
let Some(pool) = layer.pools.get(inst.pool) else { continue };
let Some(cc) = cached_cols.get(&pool.name) else { continue };
let pos = inst.tm[3];
// Quick XZ culling using instance scale + object bounding radius
let sx = (inst.tm[0][0].powi(2) + inst.tm[0][1].powi(2) + inst.tm[0][2].powi(2)).sqrt();
let sz = (inst.tm[2][0].powi(2) + inst.tm[2][1].powi(2) + inst.tm[2][2].powi(2)).sqrt();
let rad = cc.max_radius * sx.max(sz).max(1.0);
if pos[0] + rad < crop_origin[0] - pad
|| pos[0] - rad > crop_max_x + pad
|| pos[2] + rad < crop_origin[1] - pad
|| pos[2] - rad > crop_max_z + pad
{
continue;
}
inst_used += 1;
for &(p0, p1, p2, cls) in &cc.tris {
let w0 = transform_point(&inst.tm, p0);
let w1 = transform_point(&inst.tm, p1);
let w2 = transform_point(&inst.tm, p2);
let base = verts.len() as u32;
verts.push(w0);
verts.push(w1);
verts.push(w2);
tris.push(([base, base + 1, base + 2], cls));
if (cls as usize) < cls_counts.len() {
cls_counts[cls as usize] += 1;
}
}
}
}
println!(
" RIGz: pools={} cols={} noCol={} instancesInBounds={} obsTris={} [hard={} bridge={} crush={} treeThick={} treeThin={}] ({:.2}s)",
pool_names.len(),
cached_cols.len(),
no_collision,
inst_used,
tris.len(),
cls_counts[0],
cls_counts[1],
cls_counts[2],
cls_counts[3],
cls_counts[4],
t0.elapsed().as_secs_f32()
);
if let Some(parent) = out_path.parent() {
fs::create_dir_all(parent)?;
}
let mut w = BufWriter::new(File::create(&out_path)?);
// WtoGeoHeader (must match native/wto-nav/wto_nav_format.h byte-for-byte)
w.write_all(WTO_GEO_MAGIC)?;
w.write_all(&WTO_GEO_VERSION.to_le_bytes())?;
w.write_all(&0u32.to_le_bytes())?; // flags
w.write_all(&ever_sha1)?;
w.write_all(&water_level.to_le_bytes())?;
w.write_all(&crop_origin[0].to_le_bytes())?;
w.write_all(&crop_origin[1].to_le_bytes())?;
w.write_all(&crop_max_x.to_le_bytes())?;
w.write_all(&crop_max_z.to_le_bytes())?;
w.write_all(&cw.to_le_bytes())?;
w.write_all(&ch.to_le_bytes())?;
w.write_all(&hm.cell_size.to_le_bytes())?;
w.write_all(&crop_origin[0].to_le_bytes())?;
w.write_all(&crop_origin[1].to_le_bytes())?;
w.write_all(&(verts.len() as u32).to_le_bytes())?;
w.write_all(&(tris.len() as u32).to_le_bytes())?;
// Heightmap float32 samples
for h in &heights {
w.write_all(&h.to_le_bytes())?;
}
// Obstacle vertices (float32 x 3)
for v in &verts {
w.write_all(&v[0].to_le_bytes())?;
w.write_all(&v[1].to_le_bytes())?;
w.write_all(&v[2].to_le_bytes())?;
}
// Obstacle triangles (uint32 x 3 + uint8 class)
for (idx, cls) in &tris {
w.write_all(&idx[0].to_le_bytes())?;
w.write_all(&idx[1].to_le_bytes())?;
w.write_all(&idx[2].to_le_bytes())?;
w.write_all(&[*cls])?;
}
w.flush()?;
println!(" wrote {} ({:.1} MB)", out_path.display(), fs::metadata(&out_path)?.len() as f64 / (1024.0 * 1024.0));
Ok(())
}