diff --git a/apps/server/tuning/ground-ai.jsonc b/apps/server/tuning/ground-ai.jsonc index b6353dd..4a719c8 100644 --- a/apps/server/tuning/ground-ai.jsonc +++ b/apps/server/tuning/ground-ai.jsonc @@ -104,6 +104,18 @@ "excludedCoverRendinst": ["stone_fence_a", "damaged_stone_fence_a", "damaged_stone_fence_b"] }, + // Offline navigation mesh baking parameters, copied into the generator's per-level POI input. + "navBake": { + // Placed objects whose stock destructionImpulse (config/rendinst_dmg.blk) is at most this + // value are knocked down by tanks and baked as crushable rather than solid (N*s). + "crushableMaxImpulse": 45000, + // riExtra objects with no destructionImpulse are crushable when their stock hp is at most + // 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 + }, + "navigation": { // "vehicle_phys" uses custom inputs with native ownership. "movesys" keeps stock movement. "driveMode": "vehicle_phys", diff --git a/apps/server/tuning/maps/avg_poland.jsonc b/apps/server/tuning/maps/avg_poland.jsonc new file mode 100644 index 0000000..d2eb2af --- /dev/null +++ b/apps/server/tuning/maps/avg_poland.jsonc @@ -0,0 +1,8 @@ +{ + "level": "avg_poland", + "version": 1, + "bake": { + // The town streets and squares use this LMp2 material. + "roadMaterials": ["concrete"] + } +} diff --git a/native/wto-nav/wto_nav_format.h b/native/wto-nav/wto_nav_format.h index efdc3d8..119bebc 100644 --- a/native/wto-nav/wto_nav_format.h +++ b/native/wto-nav/wto_nav_format.h @@ -36,7 +36,7 @@ enum WtoPolyArea { WTO_AREA_FOREST = 5, WTO_AREA_CRUSHABLE = 6, WTO_AREA_SHALLOW_WATER = 7, - WTO_AREA_CHOKEPOINT = 8, + WTO_AREA_CHOKEPOINT = 8, /* Not baked: chokepoints keep their surface area, see WTO_FLAG_CHOKEPOINT */ WTO_AREA_EXPOSED = 9, WTO_AREA_DEEP_WATER = 10, WTO_AREA_NO_GO = 11 @@ -47,9 +47,9 @@ enum WtoPolyFlag { WTO_FLAG_WALK = 0x01, WTO_FLAG_SHALLOW_WATER = 0x02, WTO_FLAG_DEEP_WATER = 0x04, - WTO_FLAG_CHOKEPOINT = 0x08, + WTO_FLAG_CHOKEPOINT = 0x08, /* Narrower than navBake.chokepointMaxWidthVehicles for this mesh's tier */ WTO_FLAG_BLOCKED = 0x10, - WTO_FLAG_ROAD = 0x20, /* Surface identity, retained on chokepoint polygons */ + WTO_FLAG_ROAD = 0x20, /* Surface identity, set on road polygons */ WTO_FLAG_DOWNHILL = 0x40, /* One-way Detour connection */ WTO_FLAG_PLATFORM = 0x80 /* Walkable top of a validated placed object */ }; diff --git a/tools/navgen/bake/bake.cpp b/tools/navgen/bake/bake.cpp index 86c89fc..c72fdc0 100644 --- a/tools/navgen/bake/bake.cpp +++ b/tools/navgen/bake/bake.cpp @@ -59,6 +59,7 @@ struct CoverBake { struct PoisData { CoverBake cover{}; + float chokepointMaxWidthVehicles = 0.0f; std::vector t1Spawns; std::vector t2Spawns; std::vector caps; @@ -95,6 +96,9 @@ static constexpr float kExtraCoverColumnM = 2.6f; static constexpr float kGeometryToleranceM = 0.001f; // Intermediate Recast area. Its serialized area is ground. static constexpr unsigned char kPlatformArea = RC_WALKABLE_AREA - 1; +// Intermediate Recast area bit that splits chokepoint polygons from their surroundings. It is +// stripped from the serialized area and becomes WTO_FLAG_CHOKEPOINT. +static constexpr unsigned char kChokeAreaBit = 0x20; static bool hasCoverGeometry(uint8_t cls) { return cls == WTO_OBS_HARD_SOLID || cls == WTO_OBS_PLATFORM; @@ -270,6 +274,11 @@ static bool loadPois(const std::string &path, PoisData &out) { std::fprintf(stderr, "Invalid cover baking settings in %s. Regenerate it with mission-bounds.mts.\n", path.c_str()); return false; } + out.chokepointMaxWidthVehicles = readJsonNumber(content, "chokepointMaxWidthVehicles", -1.0f); + if (!(out.chokepointMaxWidthVehicles >= 1.0f && out.chokepointMaxWidthVehicles <= 4.0f)) { + std::fprintf(stderr, "Invalid navigation baking settings in %s. Regenerate it with mission-bounds.mts.\n", path.c_str()); + return false; + } parsePoiArray(content, "team1Spawns", out.t1Spawns); parsePoiArray(content, "team2Spawns", out.t2Spawns); parsePoiArray(content, "captureZones", out.caps); @@ -376,12 +385,95 @@ static void markRoadAreas(rcCompactHeightfield &field, const GeoData &geo) { if (!geo.isRoad(wx, wz)) continue; const rcCompactCell &cell = field.cells[x + z * field.width]; for (unsigned int i = cell.index; i < cell.index + cell.count; ++i) { - if (field.areas[i] == WTO_AREA_GROUND) field.areas[i] = WTO_AREA_ROAD; + if (field.areas[i] == WTO_AREA_GROUND || field.areas[i] == WTO_AREA_ROUGH) field.areas[i] = WTO_AREA_ROAD; } } } } +/* Visits the up to eight spans around span `i` at cell (x, z) that it connects to. */ +template +static void forEachNeighborSpan(const rcCompactHeightfield &field, int x, int z, int i, Fn &&fn) { + const rcCompactSpan &span = field.spans[i]; + for (int dir = 0; dir < 4; ++dir) { + int con = rcGetCon(span, dir); + if (con == RC_NOT_CONNECTED) continue; + int ax = x + rcGetDirOffsetX(dir); + int az = z + rcGetDirOffsetY(dir); + int ai = (int)field.cells[ax + az * field.width].index + con; + fn(ai, false); + int dir2 = (dir + 1) & 3; + int con2 = rcGetCon(field.spans[ai], dir2); + if (con2 == RC_NOT_CONNECTED) continue; + int bx = ax + rcGetDirOffsetX(dir2); + int bz = az + rcGetDirOffsetY(dir2); + fn((int)field.cells[bx + bz * field.width].index + con2, true); + } +} + +/* + * Flags narrow passages on the eroded compact heightfield. Erosion already removed the vehicle's + * own half width, so a span's chamfer distance to the nearest impassable span is the room left + * beside the vehicle. A span lies in a chokepoint when no passable span within reach has at least + * `clearanceM` of room; spans that touch a wall beside open ground keep their plain surface. + */ +static int markChokepointSpans(rcCompactHeightfield &field, float clearanceM) { + auto passable = [](unsigned char area) { + return area != RC_NULL_AREA && area != WTO_AREA_DEEP_WATER && area != WTO_AREA_NO_GO; + }; + const int threshold = (int)std::lround(2.0f * clearanceM / field.cs); /* 2 = one cell */ + const int reachCells = (int)std::ceil(clearanceM / field.cs) + 1; + const int n = field.spanCount; + std::vector dist((size_t)n, 0); + for (int i = 0; i < n; ++i) dist[(size_t)i] = passable(field.areas[i]) ? 0xffff : 0; + + /* Distances beyond the threshold need not be exact, so relax only as far as it reaches. */ + for (int pass = 0; pass <= threshold / 2 + 1; ++pass) { + for (int z = 0; z < field.height; ++z) { + for (int x = 0; x < field.width; ++x) { + const rcCompactCell &cell = field.cells[x + z * field.width]; + for (int i = (int)cell.index, end = (int)(cell.index + cell.count); i < end; ++i) { + if (!dist[(size_t)i]) continue; + uint16_t best = dist[(size_t)i]; + forEachNeighborSpan(field, x, z, i, [&](int ni, bool diagonal) { + int d = (int)dist[(size_t)ni] + (diagonal ? 3 : 2); + if (d < best) best = (uint16_t)d; + }); + dist[(size_t)i] = best; + } + } + } + } + + std::vector room = dist, next((size_t)n); + for (int step = 0; step < reachCells; ++step) { + for (int z = 0; z < field.height; ++z) { + for (int x = 0; x < field.width; ++x) { + const rcCompactCell &cell = field.cells[x + z * field.width]; + for (int i = (int)cell.index, end = (int)(cell.index + cell.count); i < end; ++i) { + uint16_t best = room[(size_t)i]; + if (dist[(size_t)i]) { + forEachNeighborSpan(field, x, z, i, [&](int ni, bool) { + if (dist[(size_t)ni] && room[(size_t)ni] > best) best = room[(size_t)ni]; + }); + } + next[(size_t)i] = best; + } + } + } + room.swap(next); + } + + int marked = 0; + for (int i = 0; i < n; ++i) { + unsigned char area = field.areas[i]; + if (!dist[(size_t)i] || room[(size_t)i] >= threshold || area >= kChokeAreaBit) continue; + field.areas[i] = (unsigned char)(area | kChokeAreaBit); + marked++; + } + return marked; +} + struct BuiltTile { int tx = 0; int tz = 0; @@ -400,7 +492,8 @@ static TileBakeResult buildSingleTile( uint32_t tierIndex, int tx, int tz, float mapMinX, float mapMinZ, - const CoverBake &coverTuning, bool bakeCovers + const CoverBake &coverTuning, bool bakeCovers, + float chokeClearanceM ) { TileBakeResult res; res.tile.tx = tx; @@ -424,6 +517,10 @@ static TileBakeResult buildSingleTile( cfg.borderSize = cfg.walkableRadius + 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. + if (chokeClearanceM > 0.0f) { + cfg.borderSize = std::max(cfg.borderSize, cfg.walkableRadius + 2 * (int)std::ceil(chokeClearanceM / cfg.cs) + 4); + } cfg.width = cfg.tileSize + cfg.borderSize * 2; cfg.height = cfg.tileSize + cfg.borderSize * 2; cfg.detailSampleDist = 12.0f * cfg.cs; @@ -586,6 +683,7 @@ static TileBakeResult buildSingleTile( rcMedianFilterWalkableArea(&ctx, *chf); rcMedianFilterWalkableArea(&ctx, *chf); markRoadAreas(*chf, geo); + if (chokeClearanceM > 0.0f) markChokepointSpans(*chf, chokeClearanceM); if (!rcBuildDistanceField(&ctx, *chf) || !rcBuildRegions(&ctx, *chf, cfg.borderSize, cfg.minRegionArea, cfg.mergeRegionArea)) { @@ -629,6 +727,8 @@ static TileBakeResult buildSingleTile( /* Assign initial polygon flags from Area ID */ for (int i = 0; i < pmesh->npolys; ++i) { unsigned char a = pmesh->areas[i]; + const bool choke = a != RC_NULL_AREA && a < kPlatformArea && (a & kChokeAreaBit); + if (choke) a = pmesh->areas[i] = (unsigned char)(a & ~kChokeAreaBit); if (a == WTO_AREA_DEEP_WATER) pmesh->flags[i] = WTO_FLAG_DEEP_WATER; else if (a == WTO_AREA_SHALLOW_WATER) pmesh->flags[i] = WTO_FLAG_WALK | WTO_FLAG_SHALLOW_WATER; else if (a == WTO_AREA_NO_GO) pmesh->flags[i] = WTO_FLAG_BLOCKED; @@ -638,6 +738,7 @@ static TileBakeResult buildSingleTile( pmesh->flags[i] = WTO_FLAG_WALK | WTO_FLAG_PLATFORM; } else if (a != RC_NULL_AREA) pmesh->flags[i] = WTO_FLAG_WALK; else pmesh->flags[i] = 0; + if (choke && (pmesh->flags[i] & WTO_FLAG_WALK)) pmesh->flags[i] |= WTO_FLAG_CHOKEPOINT; } dtNavMeshCreateParams params{}; @@ -833,38 +934,16 @@ static bool verifyDownhillLinks(const dtNavMesh &mesh, const GeoData &geo, uint3 return true; } -static void markChokepoints(dtNavMesh *mesh, dtNavMeshQuery *query, float chokeDistM) { - dtQueryFilter filter; - filter.setIncludeFlags(WTO_FLAG_WALK); - filter.setExcludeFlags(WTO_FLAG_DEEP_WATER | WTO_FLAG_BLOCKED); - const dtNavMesh *cmesh = mesh; - for (int i = 0; i < cmesh->getMaxTiles(); ++i) { - const dtMeshTile *tile = cmesh->getTile(i); +static int countChokepointPolys(const dtNavMesh &mesh) { + int count = 0; + for (int i = 0; i < mesh.getMaxTiles(); ++i) { + const dtMeshTile *tile = mesh.getTile(i); if (!tile || !tile->header) continue; - dtPolyRef base = cmesh->getPolyRefBase(tile); for (int p = 0; p < tile->header->polyCount; ++p) { - const dtPoly &poly = tile->polys[p]; - if (poly.getType() == DT_POLYTYPE_OFFMESH_CONNECTION) continue; - uint8_t area = poly.getArea(); - if (area == WTO_AREA_DEEP_WATER || area == WTO_AREA_SHALLOW_WATER) continue; - float cx = 0, cy = 0, cz = 0; - for (int v = 0; v < poly.vertCount; ++v) { - const float *vp = &tile->verts[poly.verts[v] * 3]; - cx += vp[0]; cy += vp[1]; cz += vp[2]; - } - float inv = 1.0f / (float)poly.vertCount; - float pos[3] = { cx * inv, cy * inv, cz * inv }; - dtPolyRef ref = base | (dtPolyRef)p; - float hitDist = 999.0f; - float hitPos[3], hitNorm[3]; - if (dtStatusSucceed(query->findDistanceToWall(ref, pos, chokeDistM + 1.0f, &filter, &hitDist, hitPos, hitNorm))) { - if (hitDist < chokeDistM) { - mesh->setPolyArea(ref, WTO_AREA_CHOKEPOINT); - mesh->setPolyFlags(ref, poly.flags | WTO_FLAG_CHOKEPOINT); - } - } + if (tile->polys[p].flags & WTO_FLAG_CHOKEPOINT) count++; } } + return count; } struct CoverRay { @@ -1245,6 +1324,8 @@ int main(int argc, char **argv) { for (uint32_t tierIdx = 0; tierIdx < WTO_NAV_TIER_COUNT; ++tierIdx) { const bool doCovers = (tierIdx == WTO_NAV_TIER_STANDARD); + /* Room beside the vehicle left in a passage exactly chokepointMaxWidthVehicles wide. */ + const float chokeClearanceM = (pois.chokepointMaxWidthVehicles - 1.0f) * kTiers[tierIdx].agentRadius; tierTiles[tierIdx].resize((size_t)totalTiles); std::atomic nextTile{ 0 }; std::mutex covMtx; @@ -1258,7 +1339,7 @@ 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); + auto br = buildSingleTile(geo, buckets[(size_t)idx], tierIdx, tx, tz, mapMinX, mapMinZ, pois.cover, doCovers, chokeClearanceM); tierTiles[tierIdx][(size_t)idx] = br.tile; if (doCovers && !br.covers.empty()) { localCov.insert(localCov.end(), br.covers.begin(), br.covers.end()); @@ -1285,11 +1366,9 @@ int main(int argc, char **argv) { } int pruned = pruneUnreachableIslands(meshes[tierIdx], queries[tierIdx], geo, pois); if (!verifyDownhillLinks(*meshes[tierIdx], geo, tierIdx)) return 1; - if (tierIdx == WTO_NAV_TIER_STANDARD) { - markChokepoints(meshes[tierIdx], queries[tierIdx], 3.8f); - } - std::printf(" %s (r=%.2fm): tiles=%d/%d polys=%d prunedIslands=%d\n", - kTiers[tierIdx].name, kTiers[tierIdx].agentRadius, builtCnt, totalTiles, polyCnt, pruned); + std::printf(" %s (r=%.2fm): tiles=%d/%d polys=%d chokepointPolys=%d prunedIslands=%d\n", + kTiers[tierIdx].name, kTiers[tierIdx].agentRadius, builtCnt, totalTiles, polyCnt, + countChokepointPolys(*meshes[tierIdx]), pruned); } /* Dedupe + retreat-verify tank covers on Tier 1 */ @@ -1362,7 +1441,6 @@ int main(int argc, char **argv) { pf.setAreaCost(WTO_AREA_FOREST, 2.10f); pf.setAreaCost(WTO_AREA_CRUSHABLE, 2.40f); pf.setAreaCost(WTO_AREA_SHALLOW_WATER, 2.60f); - pf.setAreaCost(WTO_AREA_CHOKEPOINT, 1.80f); const float snapExt[3] = { 12.0f, 12.0f, 12.0f }; std::vector allSpawns = pois.t1Spawns; diff --git a/tools/navgen/extract/src/main.rs b/tools/navgen/extract/src/main.rs index bf75484..5ab795b 100644 --- a/tools/navgen/extract/src/main.rs +++ b/tools/navgen/extract/src/main.rs @@ -5,7 +5,7 @@ use std::path::{Path, PathBuf}; use std::time::Instant; use anyhow::{bail, Context, Result}; -use serde::Deserialize; +use serde::{Deserialize, Serialize}; use wt_formats::grp::GrpPack; use wt_unpack::blk::{self, Value}; use wt_unpack::collision::{Collision, CollisionNode, NodeKind, COLLISION}; @@ -40,10 +40,19 @@ struct LevelPois { bounds_max: [f32; 2], #[serde(rename = "coverBake", default)] cover: CoverBakeInput, + #[serde(rename = "navBake")] + nav: NavBakeInput, #[serde(rename = "mapBake", default)] map: MapBakeInput, } +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase")] +struct NavBakeInput { + crushable_max_impulse: f32, + crushable_max_ri_extra_hp: f32, +} + #[derive(Debug, Default, Deserialize)] struct CoverBakeInput { #[serde(rename = "excludedCoverRendinst", default)] @@ -103,34 +112,105 @@ struct CachedCollision { tris: Vec<([f32; 3], [f32; 3], [f32; 3], u8)>, } -fn parse_args() -> Result<(PathBuf, PathBuf, PathBuf)> { +struct Args { + game: PathBuf, + pois: PathBuf, + out: PathBuf, + report: Option, +} + +fn parse_args() -> Result { let mut game: Option = None; let mut pois: Option = None; let mut out: Option = None; + let mut report: Option = 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), + "--report" => report = args.next().map(PathBuf::from), other => bail!("unknown argument: {other}"), } } - Ok(( - game.context("missing --game ")?, - pois.context("missing --pois ")?, - out.context("missing --out ")?, - )) + Ok(Args { + game: game.context("missing --game ")?, + pois: pois.context("missing --pois ")?, + out: out.context("missing --out ")?, + report, + }) +} + +/// Development report: what the extractor found and how it classified it. +#[derive(Serialize)] +#[serde(rename_all = "camelCase")] +struct ExtractReport { + level: String, + ground_materials: Vec, + pools: Vec, +} + +#[derive(Serialize)] +#[serde(rename_all = "camelCase")] +struct MaterialReport { + name: String, + road: bool, + share: f64, +} + +#[derive(Serialize)] +#[serde(rename_all = "camelCase")] +struct PoolReport { + name: String, + instances: usize, + class: &'static str, + #[serde(skip_serializing_if = "Option::is_none")] + destruction_impulse: Option, + #[serde(skip_serializing_if = "Option::is_none")] + ri_extra_hp: Option, + #[serde(skip_serializing_if = "Option::is_none")] + collision_size: Option<[f32; 3]>, +} + +/// Stock damage data for one placed object from `config/rendinst_dmg.blk`. Plain rendinst are +/// listed in `dmg` blocks by `name`; riExtra objects are blocks named after the object under `riExtra`. +#[derive(Debug, Default, Clone)] +struct DamageInfo { + destruction_impulse: Option, + immortal: bool, + ri_extra_hp: Option, +} + +impl DamageInfo { + /// Whether a moving tank knocks the object down, or `None` when the stock data does not say. + fn crushable(&self, nav: &NavBakeInput) -> Option { + if let Some(impulse) = self.destruction_impulse.filter(|v| *v > 0.0) { + return Some(impulse <= nav.crushable_max_impulse); + } + if self.immortal { + return Some(false); + } + self.ri_extra_hp.filter(|v| *v > 0.0).map(|hp| hp <= nav.crushable_max_ri_extra_hp) + } } struct AcesMeta { water_level: f32, - /// Authoritative tank-crushable impulse threshold from `config/rendinst_dmg.blk` (lowercase name -> destructionImpulse). - destr_impulse: HashMap, + /// Lowercase object name -> stock damage data. + damage: HashMap, +} + +fn blk_number(value: &Value) -> Option { + match value { + Value::Real(x) => Some(*x), + Value::Int(x) => Some(*x as f32), + _ => None, + } } fn read_aces_meta(game: &Path, level_name: &str) -> AcesMeta { - let mut meta = AcesMeta { water_level: -1.0e6, destr_impulse: HashMap::new() }; + let mut meta = AcesMeta { water_level: -1.0e6, damage: 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; }; @@ -164,21 +244,35 @@ fn read_aces_meta(game: &Path, level_name: &str) -> AcesMeta { 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 { + if b.name.eq_ignore_ascii_case("riExtra") { + for entry in &b.blocks { + let info = meta.damage.entry(entry.name.to_lowercase()).or_default(); + for (k, v) in &entry.params { + if k.eq_ignore_ascii_case("destructionImpulse") { + info.destruction_impulse = blk_number(v).or(info.destruction_impulse); + } else if k.eq_ignore_ascii_case("hp") { + info.ri_extra_hp = blk_number(v); + } + } + } + continue; + } let mut rname: Option<&str> = None; let mut impulse: Option = None; + let mut immortal = false; 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), - _ => {} - } + impulse = blk_number(v); + } else if k.eq_ignore_ascii_case("immortal") { + immortal = matches!(v, Value::Bool(true)); } } - if let (Some(n), Some(imp)) = (rname, impulse) { - meta.destr_impulse.insert(n.to_lowercase(), imp); + if let Some(n) = rname { + let info = meta.damage.entry(n.to_lowercase()).or_default(); + info.destruction_impulse = impulse.or(info.destruction_impulse); + info.immortal |= immortal; } } } @@ -186,7 +280,7 @@ fn read_aces_meta(game: &Path, level_name: &str) -> AcesMeta { meta } -fn classify_pool(name: &str, destr_impulse: Option) -> PoolMeta { +fn classify_pool(name: &str, damage: Option<&DamageInfo>, nav: &NavBakeInput) -> PoolMeta { let lower = name.to_lowercase(); let is_bridge = lower.contains("bridge") || lower.contains("viaduct") @@ -212,6 +306,9 @@ fn classify_pool(name: &str, destr_impulse: Option) -> PoolMeta { || lower.contains("tank_wreck") || is_bridge; + // Stock damage data decides when it exists; model names are only a fallback. + let stock_crushable = if is_bridge { None } else { damage.and_then(|d| d.crushable(nav)) }; + let is_soft_foliage = !always_hard && (lower.starts_with("bush_") || lower.contains("_bush_") @@ -222,19 +319,20 @@ fn classify_pool(name: &str, destr_impulse: Option) -> PoolMeta { || 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"), - }; + // Stock War Thunder physics: low destructionImpulse or low riExtra hp means a moving tank + // knocks the object down (wooden and dry-stone fences, lamp posts, sheds, small trees). + let is_crushable = match stock_crushable { + Some(crushable) => crushable, + None => { + !always_hard + && (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 } } @@ -416,7 +514,7 @@ fn crop_heightmap(hm: &Heightmap, min_x: f32, min_z: f32, max_x: f32, max_z: f32 fn main() -> Result<()> { let t0 = Instant::now(); - let (game_dir, pois_path, out_path) = parse_args()?; + let Args { game: game_dir, pois: pois_path, out: out_path, report: report_path } = parse_args()?; let pois: LevelPois = serde_json::from_str( &fs::read_to_string(&pois_path).with_context(|| format!("reading {}", pois_path.display()))?, )?; @@ -429,7 +527,9 @@ fn main() -> Result<()> { let aces_meta = read_aces_meta(&game_dir, &pois.level); let water_level = aces_meta.water_level; - let roads = phys_map::RoadMask::read(&level, &pois.map.road_materials).with_context(|| format!("extracting {} roads", pois.level))?; + let phys_map = phys_map::PhysMap::read(&level, &pois.map.road_materials) + .with_context(|| format!("extracting {} ground materials", pois.level))?; + let roads = phys_map.as_ref().filter(|map| map.has_road()); let hm = level.heightmap()?.with_context(|| format!("{} has no HM2 heightmap", pois.level))?; let (cw, ch, crop_origin, heights) = crop_heightmap( @@ -484,6 +584,7 @@ fn main() -> Result<()> { let excluded_cover: HashSet<_> = pois.cover.excluded_rendinst.iter().map(|name| name.to_ascii_lowercase()).collect(); let platforms: HashSet<_> = pois.map.walkable_rendinst.iter().map(|name| name.to_ascii_lowercase()).collect(); let mut cached_cols: HashMap = HashMap::new(); + let mut pool_reports: HashMap = 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 }; @@ -491,9 +592,33 @@ fn main() -> Result<()> { let Some(res) = pack.find(res_name, COLLISION) else { continue }; let Ok(col) = Collision::parse(res_name, pack.data(res)) else { continue }; let key = pool_name.to_ascii_lowercase(); - let imp = aces_meta.destr_impulse.get(&key).copied(); - let meta = classify_pool(pool_name, imp); - if let Some(cc) = build_cached_collision(&col, &meta, !excluded_cover.contains(&key), platforms.contains(&key)) { + let damage = aces_meta.damage.get(&key); + let meta = classify_pool(pool_name, damage, &pois.nav); + let cover_allowed = !excluded_cover.contains(&key); + let platform = platforms.contains(&key); + let class = if meta.is_soft_foliage { + "foliage" + } else if platform { + "platform" + } else if meta.is_bridge { + "bridge" + } else if meta.is_crushable { + "crushable" + } else if cover_allowed { + "hard" + } else { + "hardNoCover" + }; + let [lo, hi] = col.bbox; + pool_reports.insert(pool_name.clone(), PoolReport { + name: pool_name.clone(), + instances: 0, + class, + destruction_impulse: damage.and_then(|d| d.destruction_impulse), + ri_extra_hp: damage.and_then(|d| d.ri_extra_hp), + collision_size: Some([hi[0] - lo[0], hi[1] - lo[1], hi[2] - lo[2]]), + }); + if let Some(cc) = build_cached_collision(&col, &meta, cover_allowed, platform) { cached_cols.insert(pool_name.clone(), cc); } } @@ -510,8 +635,27 @@ fn main() -> Result<()> { 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]; + if report_path.is_some() + && pos[0] >= crop_origin[0] && pos[0] <= crop_max_x + && pos[2] >= crop_origin[1] && pos[2] <= crop_max_z + { + pool_reports + .entry(pool.name.clone()) + .or_insert_with(|| { + let damage = aces_meta.damage.get(&pool.name.to_ascii_lowercase()); + PoolReport { + name: pool.name.clone(), + instances: 0, + class: "noCollision", + destruction_impulse: damage.and_then(|d| d.destruction_impulse), + ri_extra_hp: damage.and_then(|d| d.ri_extra_hp), + collision_size: None, + } + }) + .instances += 1; + } + let Some(cc) = cached_cols.get(&pool.name) else { continue }; // 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(); @@ -605,7 +749,7 @@ fn main() -> Result<()> { w.write_all(&[*cls])?; } if let Some(roads) = roads { - roads.write(&mut w)?; + roads.write_road_mask(&mut w)?; } if !pois.map.downhill_links.is_empty() { w.write_all(&(pois.map.downhill_links.len() as u32).to_le_bytes())?; @@ -615,5 +759,23 @@ fn main() -> Result<()> { } w.flush()?; println!(" wrote {} ({:.1} MB)", out_path.display(), fs::metadata(&out_path)?.len() as f64 / (1024.0 * 1024.0)); + + if let Some(report_path) = report_path { + let stats = phys_map + .as_ref() + .map(|map| map.material_stats(crop_origin, [crop_max_x, crop_max_z])) + .unwrap_or_default(); + let total = stats.iter().map(|s| s.texels).sum::().max(1) as f64; + let mut ground_materials: Vec<_> = stats + .into_iter() + .map(|s| MaterialReport { name: s.name, road: s.road, share: s.texels as f64 / total }) + .collect(); + ground_materials.sort_by(|a, b| b.share.total_cmp(&a.share)); + let mut pools: Vec<_> = pool_reports.into_values().filter(|p| p.instances > 0).collect(); + pools.sort_by(|a, b| b.instances.cmp(&a.instances).then_with(|| a.name.cmp(&b.name))); + let report = ExtractReport { level: pois.level.clone(), ground_materials, pools }; + fs::write(&report_path, serde_json::to_string_pretty(&report)?)?; + println!(" wrote report {}", report_path.display()); + } Ok(()) } diff --git a/tools/navgen/extract/src/phys_map.rs b/tools/navgen/extract/src/phys_map.rs index bc414cc..282f2aa 100644 --- a/tools/navgen/extract/src/phys_map.rs +++ b/tools/navgen/extract/src/phys_map.rs @@ -10,14 +10,23 @@ const MASK_TEXTURE_SIZE: usize = 32; const MAX_PAYLOAD: usize = 256 * 1024 * 1024; const MAX_GRID_CELLS: usize = 64 * 1024 * 1024; -pub struct RoadMask { +/// The decoded ground material map: one LMp2 material index per texel, with decals painted on top. +pub struct PhysMap { size: usize, origin: [f32; 2], cell_size: f32, cells: Vec, + materials: Vec, + is_road: Vec, } -impl RoadMask { +pub struct MaterialStat { + pub name: String, + pub road: bool, + pub texels: u64, +} + +impl PhysMap { pub fn read(level: &Level<'_>, road_materials: &[String]) -> Result> { let Some(info) = level.phys_map_info()? else { return Ok(None); @@ -47,9 +56,6 @@ impl RoadMask { ) || road_materials.iter().any(|material| name.eq_ignore_ascii_case(material)) }) .collect(); - if !is_road.contains(&true) { - return Ok(None); - } let block = level.find("LMp2").context("missing LMp2 block")?; let mut reader = Reader::at(block.data, 8)?; @@ -72,7 +78,7 @@ impl RoadMask { let payload = unpack(block_header >> 30, packed)?; let mut reader = Reader::new(&payload); if let Some(size) = legacy_size { - read_tree(&mut reader, None, &is_road, [0, 0], size)?; + read_tree(&mut reader, None, [0, 0], size)?; } let mut mask = Self { @@ -80,8 +86,10 @@ impl RoadMask { origin: info.world_origin, cell_size: info.metres_per_texel, cells: vec![0; size * size], + materials: info.materials.clone(), + is_road, }; - read_tree(&mut reader, Some(&mut mask), &is_road, [0, 0], size)?; + read_tree(&mut reader, Some(&mut mask), [0, 0], size)?; let decals = read_decals(&mut reader, info.version)?; let textures = if info.version == 0 { &[][..] @@ -94,40 +102,72 @@ impl RoadMask { let texture_bytes = MASK_TEXTURE_SIZE * size_of::(); let start = usize::from(group.texture_id) * texture_bytes; let texture = textures.get(start..start + texture_bytes); - let road = material_is_road(&is_road, group.material); for (index, face) in group.faces.chunks_exact(6).enumerate() { let vertices = indexed_points(face, &decal.vertices)?; let uvs = texture .map(|_| indexed_points(&group.uv_faces[index * 6..index * 6 + 6], &decal.uvs)) .transpose()?; - mask.paint_triangle(vertices, road, texture.zip(uvs)); + mask.paint_triangle(vertices, group.material, texture.zip(uvs)); } } } - let roads = mask.cells.iter().filter(|&&cell| cell != 0).count(); + let roads = mask.cells.iter().filter(|&&cell| mask.cell_is_road(cell)).count(); println!(" LMp2: {size}x{size} at {:.2} m, {roads} road texels", mask.cell_size); Ok(Some(mask)) } - pub fn write(&self, out: &mut impl Write) -> std::io::Result<()> { + pub fn has_road(&self) -> bool { + self.cells.iter().any(|&cell| self.cell_is_road(cell)) + } + + /// Texel counts per material inside the given world XZ rectangle. + pub fn material_stats(&self, min: [f32; 2], max: [f32; 2]) -> Vec { + let to_cell = |v: f32, axis: usize| { + (((v - self.origin[axis]) / self.cell_size).floor().max(0.0) as usize).min(self.size) + }; + let mut counts = vec![0u64; 256]; + for z in to_cell(min[1], 1)..to_cell(max[1], 1) { + for x in to_cell(min[0], 0)..to_cell(max[0], 0) { + counts[usize::from(self.cells[z * self.size + x])] += 1; + } + } + counts + .iter() + .enumerate() + .filter(|&(_, &texels)| texels > 0) + .map(|(index, &texels)| MaterialStat { + name: self.materials.get(index).cloned().unwrap_or_else(|| format!("#{index}")), + road: self.cell_is_road(index as u8), + texels, + }) + .collect() + } + + /// Writes the `.wtogeo` road mask section: one byte per texel, 1 = road. + pub fn write_road_mask(&self, out: &mut impl Write) -> std::io::Result<()> { out.write_all(&(self.size as u32).to_le_bytes())?; out.write_all(&self.origin[0].to_le_bytes())?; out.write_all(&self.origin[1].to_le_bytes())?; out.write_all(&self.cell_size.to_le_bytes())?; - out.write_all(&self.cells) + let road: Vec = self.cells.iter().map(|&cell| u8::from(self.cell_is_road(cell))).collect(); + out.write_all(&road) } - fn fill(&mut self, [x, z]: [usize; 2], size: usize, road: u8) { + fn cell_is_road(&self, material: u8) -> bool { + self.is_road.get(usize::from(material)).copied().unwrap_or(false) + } + + fn fill(&mut self, [x, z]: [usize; 2], size: usize, material: u8) { for row in z..z + size { let start = row * self.size + x; - self.cells[start..start + size].fill(road); + self.cells[start..start + size].fill(material); } } fn paint_triangle( &mut self, vertices: [[f32; 2]; 3], - road: u8, + material: u8, mask: Option<(&[u8], [[f32; 2]; 3])>, ) { let [a, b, c] = vertices.map(|[x, z]| { @@ -148,7 +188,7 @@ impl RoadMask { if weights.iter().all(|weight| *weight >= 0.0) && mask.is_none_or(|(tex, uv)| mask_covers(tex, uv, weights)) { - self.cells[z * self.size + x] = road; + self.cells[z * self.size + x] = material; } } } @@ -179,15 +219,14 @@ fn unpack(codec: u32, packed: &[u8]) -> Result> { fn read_tree( reader: &mut Reader<'_>, - mut mask: Option<&mut RoadMask>, - is_road: &[bool], + mut mask: Option<&mut PhysMap>, origin: [usize; 2], size: usize, ) -> Result<()> { let flags = reader.u8()?; if reader.u8()? == 0 { if let Some(mask) = mask { - mask.fill(origin, size, material_is_road(is_road, flags)); + mask.fill(origin, size, flags); } return Ok(()); } @@ -199,7 +238,7 @@ fn read_tree( for z in 0..stride { for x in 0..stride { let child = [origin[0] + x * child_size, origin[1] + z * child_size]; - read_tree(reader, mask.as_deref_mut(), is_road, child, child_size)?; + read_tree(reader, mask.as_deref_mut(), child, child_size)?; } } return Ok(()); @@ -224,11 +263,7 @@ fn read_tree( let bit = (z * MIP_SIZE + x) * bits; let value = (usize::from(data[bit / 8]) >> (bit % 8)) & ((1 << bits) - 1); let material = if palette.is_empty() { value as u8 } else { palette[value] }; - mask.fill( - [origin[0] + x * texel, origin[1] + z * texel], - texel, - material_is_road(is_road, material), - ); + mask.fill([origin[0] + x * texel, origin[1] + z * texel], texel, material); } } } @@ -299,10 +334,6 @@ fn indexed_points(indices: &[u8], points: &[[f32; 2]]) -> Result<[[f32; 2]; 3]> Ok(triangle) } -fn material_is_road(is_road: &[bool], material: u8) -> u8 { - u8::from(is_road.get(usize::from(material)).copied().unwrap_or(false)) -} - fn edge(a: [f32; 2], b: [f32; 2], p: [f32; 2]) -> f32 { (b[0] - a[0]) * (p[1] - a[1]) - (b[1] - a[1]) * (p[0] - a[0]) } diff --git a/tools/navgen/mission-bounds.mts b/tools/navgen/mission-bounds.mts index d17f57d..a3b6e91 100644 --- a/tools/navgen/mission-bounds.mts +++ b/tools/navgen/mission-bounds.mts @@ -35,6 +35,7 @@ interface LevelPois { readonly team2Spawns: readonly PoiPoint[]; readonly captureZones: readonly PoiPoint[]; readonly coverBake: ReturnType; + readonly navBake: ReturnType; readonly mapBake?: NonNullable>; } @@ -149,9 +150,23 @@ function dedupePois(pts: PoiPoint[], minDistM: number): PoiPoint[] { return out; } +const groundAiTuningPath = join(import.meta.dirname, '../../apps/server/tuning/ground-ai.jsonc'); + +function readGroundAiTuning() { + return new TuningReader(groundAiTuningPath, parseJsonc(readFileSync(groundAiTuningPath, 'utf8'))); +} + +function readNavBake() { + const nav = readGroundAiTuning().object('navBake'); + return { + crushableMaxImpulse: nav.number('crushableMaxImpulse', { min: 0 }), + crushableMaxRiExtraHp: nav.number('crushableMaxRiExtraHp', { min: 0 }), + chokepointMaxWidthVehicles: nav.number('chokepointMaxWidthVehicles', { min: 1, max: 4 }), + }; +} + function readCoverBake() { - const path = join(import.meta.dirname, '../../apps/server/tuning/ground-ai.jsonc'); - const cover = new TuningReader(path, parseJsonc(readFileSync(path, 'utf8'))).object('coverMap'); + const cover = readGroundAiTuning().object('coverMap'); const peekMinM = cover.number('peekMinM', { min: 0.5 }); return { minCoverHeightM: cover.number('minCoverHeightM', { min: 0.5 }), @@ -190,6 +205,7 @@ function readMapBake(level: string) { function main() { const { gameDir, outDir, levelsFilter } = parseArgs(process.argv.slice(2)); const coverBake = readCoverBake(); + const navBake = readNavBake(); mkdirSync(outDir, { recursive: true }); const charPack = openPack(join(gameDir, 'char.vromfs.bin')); @@ -313,6 +329,7 @@ function main() { team2Spawns: t2, captureZones: caps, coverBake, + navBake, ...(mapBake && { mapBake }), }; const outPath = join(outDir, `${levelKey}.pois.json`); diff --git a/tools/navgen/render-preview.py b/tools/navgen/render-preview.py index 819b5b6..2d36450 100644 --- a/tools/navgen/render-preview.py +++ b/tools/navgen/render-preview.py @@ -8,6 +8,8 @@ import os import struct import zlib +PRINT_DPI = 300 + def write_png(path: str, width: int, height: int, rgb: bytearray) -> None: def chunk(tag: bytes, data: bytes) -> bytes: @@ -21,7 +23,15 @@ def write_png(path: str, width: int, height: int, rgb: bytearray) -> None: row = y * stride raw.extend(rgb[row : row + stride]) ihdr = struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0) - png = b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", ihdr) + chunk(b"IDAT", zlib.compress(bytes(raw), 6)) + chunk(b"IEND", b"") + dots_per_metre = round(PRINT_DPI / 0.0254) + phys = struct.pack(">IIB", dots_per_metre, dots_per_metre, 1) + png = ( + b"\x89PNG\r\n\x1a\n" + + chunk(b"IHDR", ihdr) + + chunk(b"pHYs", phys) + + chunk(b"IDAT", zlib.compress(bytes(raw), 6)) + + chunk(b"IEND", b"") + ) os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True) with open(path, "wb") as f: f.write(png) @@ -259,8 +269,8 @@ def main() -> None: x, y = world_to_px(px_w, pz_w) col = (60, 165, 255) if kind == 1 else (55, 240, 100) draw_circle(cov_rgb, pw, ph, x, y, 2, col, fill=True) - # Direction tick pointing toward blocked threat - x2, y2 = world_to_px(px_w + dx * 8.0, pz_w + dz * 8.0) + # Short direction tick pointing toward the blocked threat, kept short so dense cover rows stay legible + x2, y2 = world_to_px(px_w + dx * 2.0, pz_w + dz * 2.0) draw_line(cov_rgb, pw, ph, x, y, x2, y2, col, thick=1) if c[17]: peeks.append(world_to_px(c[7], c[9]))