diff --git a/apps/server/tuning/maps/avg_berlin.jsonc b/apps/server/tuning/maps/avg_berlin.jsonc new file mode 100644 index 0000000..8c6ce5b --- /dev/null +++ b/apps/server/tuning/maps/avg_berlin.jsonc @@ -0,0 +1,24 @@ +{ + "level": "avg_berlin", + "version": 1, + "bake": { + // The original arterial and ring roads use this LMp2 material. + "roadMaterials": ["concrete"], + "walkableRendinst": ["fountain_base_b_body"], + "downhillLinks": [ + // Dry endpoints verified on the two meshes at the eastern canal bank. + { + "from": { "x": 2476.0, "y": 43.34, "z": 1124.0 }, + "to": { "x": 2460.0, "y": 36.61, "z": 1124.0 }, + "radiusM": 0.75, + "widthTiers": [0] + }, + { + "from": { "x": 2476.0, "y": 43.12, "z": 1135.5 }, + "to": { "x": 2458.0, "y": 36.59, "z": 1135.5 }, + "radiusM": 0.75, + "widthTiers": [1] + } + ] + } +} diff --git a/native/wto-nav/wto_nav_format.h b/native/wto-nav/wto_nav_format.h index ec18188..efdc3d8 100644 --- a/native/wto-nav/wto_nav_format.h +++ b/native/wto-nav/wto_nav_format.h @@ -14,8 +14,9 @@ extern "C" { #endif #define WTO_GEO_MAGIC "WTOGEO\0\1" -#define WTO_GEO_VERSION 2u +#define WTO_GEO_VERSION 3u #define WTO_GEO_FLAG_ROAD_MASK 0x01u +#define WTO_GEO_FLAG_DOWNHILL_LINKS 0x02u #define WTO_NAV_MAGIC "WTONAV\0\1" #define WTO_NAV_VERSION 1u @@ -47,7 +48,10 @@ enum WtoPolyFlag { WTO_FLAG_SHALLOW_WATER = 0x02, WTO_FLAG_DEEP_WATER = 0x04, WTO_FLAG_CHOKEPOINT = 0x08, - WTO_FLAG_BLOCKED = 0x10 + WTO_FLAG_BLOCKED = 0x10, + WTO_FLAG_ROAD = 0x20, /* Surface identity, retained on chokepoint polygons */ + WTO_FLAG_DOWNHILL = 0x40, /* One-way Detour connection */ + WTO_FLAG_PLATFORM = 0x80 /* Walkable top of a validated placed object */ }; /* Obstacle classification written into `.wtogeo` by the extractor. */ @@ -57,7 +61,9 @@ enum WtoObstacleClass { WTO_OBS_CRUSHABLE = 2, /* Wooden fences, hedges, low-HP destructibles */ WTO_OBS_TREE_THICK = 3, /* Thick immovable tree trunks (r >= 0.25 m) */ WTO_OBS_TREE_THIN = 4, /* Thin tree trunks / saplings (high-cost forest) */ - WTO_OBS_HARD_NO_COVER = 5 /* Vehicle collision with no eligible cover surface */ + WTO_OBS_HARD_NO_COVER = 5, /* Vehicle collision with no eligible cover surface */ + WTO_OBS_PLATFORM = 6, /* Placed geometry with eligible upward-facing support surfaces */ + WTO_OBS_PLATFORM_NO_COVER = 7 /* Support surfaces from vehicle-only collision */ }; /* Baked tank cover classifications. */ @@ -92,6 +98,13 @@ typedef struct WtoGeoRoadMask { float cellSize; } WtoGeoRoadMask; +/* Optional downhill links trailer: uint32_t count followed by records. */ +typedef struct WtoGeoDownhillLink { + float endpoints[6]; /* From XYZ (high) followed by to XYZ (low) */ + float radiusM; /* Detour endpoint attachment radius */ + uint32_t tierMask; +} WtoGeoDownhillLink; + /* Baked tank cover point (68 bytes). */ typedef struct WtoCoverPoint { float pos[3]; /* World XYZ parking position behind cover */ diff --git a/tools/navgen/bake/bake.cpp b/tools/navgen/bake/bake.cpp index 7a91552..86c89fc 100644 --- a/tools/navgen/bake/bake.cpp +++ b/tools/navgen/bake/bake.cpp @@ -93,6 +93,12 @@ static constexpr float kTurretLowerM = 2.05f; static constexpr float kHullColumnSpacingM = 0.9f; 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; + +static bool hasCoverGeometry(uint8_t cls) { + return cls == WTO_OBS_HARD_SOLID || cls == WTO_OBS_PLATFORM; +} static constexpr float kPeekSightM = 14.0f; static constexpr float kHullDownSightM = 22.0f; static constexpr float kCoverHeightToleranceM = 1.2f; @@ -102,6 +108,7 @@ struct GeoData { std::vector heights; WtoGeoRoadMask roads{}; std::vector roadCells; + std::vector downhillLinks; std::vector obsVerts; std::vector obsTris; float minY = 1e9f; @@ -136,7 +143,7 @@ static bool loadGeo(const std::string &path, GeoData &out) { std::ifstream in(path, std::ios::binary); if (!in) return false; in.read(reinterpret_cast(&out.hdr), sizeof(WtoGeoHeader)); - if (!in || std::memcmp(out.hdr.magic, WTO_GEO_MAGIC, 8) != 0 || (out.hdr.version != 1u && out.hdr.version != WTO_GEO_VERSION)) { + if (!in || std::memcmp(out.hdr.magic, WTO_GEO_MAGIC, 8) != 0 || (out.hdr.version < 1u || out.hdr.version > WTO_GEO_VERSION)) { std::fprintf(stderr, "Invalid .wtogeo header: %s\n", path.c_str()); return false; } @@ -162,6 +169,18 @@ static bool loadGeo(const std::string &path, GeoData &out) { out.roadCells.resize((size_t)out.roads.size * out.roads.size); in.read(reinterpret_cast(out.roadCells.data()), out.roadCells.size()); } + if (out.hdr.flags & WTO_GEO_FLAG_DOWNHILL_LINKS) { + uint32_t count = 0; + in.read(reinterpret_cast(&count), sizeof(count)); + if (!in || count > UINT16_MAX) return false; + out.downhillLinks.resize(count); + in.read(reinterpret_cast(out.downhillLinks.data()), count * sizeof(WtoGeoDownhillLink)); + for (const auto &link : out.downhillLinks) { + if (!std::all_of(std::begin(link.endpoints), std::end(link.endpoints), [](float v) { return std::isfinite(v); }) || + !(link.radiusM > 0.0f) || !std::isfinite(link.radiusM) || link.endpoints[1] <= link.endpoints[4] || + !link.tierMask || link.tierMask >= (1u << WTO_NAV_TIER_COUNT)) return false; + } + } if (!in) return false; for (float h : out.heights) { @@ -378,7 +397,7 @@ struct TileBakeResult { static TileBakeResult buildSingleTile( const GeoData &geo, const std::vector &triBucket, - const TierSpec &tier, + uint32_t tierIndex, int tx, int tz, float mapMinX, float mapMinZ, const CoverBake &coverTuning, bool bakeCovers @@ -387,6 +406,7 @@ static TileBakeResult buildSingleTile( res.tile.tx = tx; res.tile.tz = tz; + const TierSpec &tier = kTiers[tierIndex]; rcContext ctx(false); rcConfig cfg{}; cfg.cs = kCellSize; @@ -490,6 +510,11 @@ static TileBakeResult buildSingleTile( if (hardHf && t.cls == WTO_OBS_HARD_SOLID) { rcRasterizeTriangle(&ctx, &v0.x, &v1.x, &v2.x, 1, *hardHf, 1); } + } else if (t.cls == WTO_OBS_PLATFORM || t.cls == WTO_OBS_PLATFORM_NO_COVER) { + float ny = triNormalYRightHanded(v0, v1, v2); + unsigned char area = ny >= cosMaxSlope ? kPlatformArea : RC_NULL_AREA; + rcRasterizeTriangle(&ctx, &v0.x, &v1.x, &v2.x, area, *solid, cfg.walkableClimb); + if (hardHf && hasCoverGeometry(t.cls)) rcRasterizeTriangle(&ctx, &v0.x, &v1.x, &v2.x, 1, *hardHf, 1); } else if (t.cls == WTO_OBS_BRIDGE_DECK) { float ny = triNormalYRightHanded(v0, v1, v2); if (std::fabs(ny) >= cosMaxSlope) { @@ -607,7 +632,11 @@ static TileBakeResult buildSingleTile( 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; - else if (a != RC_NULL_AREA) pmesh->flags[i] = WTO_FLAG_WALK; + else if (a == WTO_AREA_ROAD) pmesh->flags[i] = WTO_FLAG_WALK | WTO_FLAG_ROAD; + else if (a == kPlatformArea) { + pmesh->areas[i] = WTO_AREA_GROUND; + 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; } @@ -636,6 +665,30 @@ static TileBakeResult buildSingleTile( params.ch = cfg.ch; params.buildBvTree = true; + std::vector endpoints, radii; + std::vector linkFlags; + std::vector linkAreas, linkDirections; + std::vector linkIds; + for (size_t i = 0; i < geo.downhillLinks.size(); ++i) { + const auto &link = geo.downhillLinks[i]; + if (!(link.tierMask & (1u << tierIndex))) continue; + float x = link.endpoints[0], z = link.endpoints[2]; + if (x < params.bmin[0] || x >= params.bmax[0] || z < params.bmin[2] || z >= params.bmax[2]) continue; + endpoints.insert(endpoints.end(), std::begin(link.endpoints), std::end(link.endpoints)); + radii.push_back(link.radiusM); + linkFlags.push_back(WTO_FLAG_WALK | WTO_FLAG_DOWNHILL); + linkAreas.push_back(WTO_AREA_ROUGH); + linkDirections.push_back(0); + linkIds.push_back((unsigned int)i + 1); + } + params.offMeshConCount = (int)linkIds.size(); + params.offMeshConVerts = endpoints.data(); + params.offMeshConRad = radii.data(); + params.offMeshConFlags = linkFlags.data(); + params.offMeshConAreas = linkAreas.data(); + params.offMeshConDir = linkDirections.data(); + params.offMeshConUserID = linkIds.data(); + unsigned char *navData = nullptr; int navDataSize = 0; if (dtCreateNavMeshData(¶ms, &navData, &navDataSize)) { @@ -723,6 +776,63 @@ static int pruneUnreachableIslands(dtNavMesh *mesh, dtNavMeshQuery *query, const return pruned; } +static bool hasPolygonLink(const dtNavMesh &mesh, dtPolyRef from, dtPolyRef to) { + const dtMeshTile *tile = nullptr; + const dtPoly *poly = nullptr; + if (dtStatusFailed(mesh.getTileAndPolyByRef(from, &tile, &poly))) return false; + for (unsigned int i = poly->firstLink; i != DT_NULL_LINK; i = tile->links[i].next) { + if (tile->links[i].ref == to) return true; + } + return false; +} + +static bool verifyDownhillLinks(const dtNavMesh &mesh, const GeoData &geo, uint32_t tierIndex) { + if (geo.downhillLinks.empty()) return true; + std::vector attached(geo.downhillLinks.size()); + for (int i = 0; i < mesh.getMaxTiles(); ++i) { + const dtMeshTile *tile = mesh.getTile(i); + if (!tile || !tile->header) continue; + for (int n = 0; n < tile->header->offMeshConCount; ++n) { + const dtOffMeshConnection &con = tile->offMeshCons[n]; + if (con.userId == 0 || con.userId > attached.size() || attached[con.userId - 1] || + (con.flags & DT_OFFMESH_CON_BIDIR)) return false; + + const dtPoly &poly = tile->polys[con.poly]; + if ((poly.flags & WTO_FLAG_DOWNHILL) == 0) return false; + dtPolyRef ref = mesh.getPolyRefBase(tile) | con.poly; + dtPolyRef endpoints[2] = {}; + for (unsigned int j = poly.firstLink; j != DT_NULL_LINK; j = tile->links[j].next) { + const dtLink &link = tile->links[j]; + if (link.edge < 2) endpoints[link.edge] = link.ref; + } + unsigned short startFlags = 0, endFlags = 0; + if (!endpoints[0] || !endpoints[1] || endpoints[0] == endpoints[1] || + dtStatusFailed(mesh.getPolyFlags(endpoints[0], &startFlags)) || + dtStatusFailed(mesh.getPolyFlags(endpoints[1], &endFlags)) || + !(startFlags & WTO_FLAG_WALK) || !(endFlags & WTO_FLAG_WALK) || + !hasPolygonLink(mesh, endpoints[0], ref) || hasPolygonLink(mesh, endpoints[1], ref)) { + std::fprintf(stderr, "Downhill link %u (%.2f, %.2f -> %.2f, %.2f) unattached on %s.\n", con.userId, + con.pos[0], con.pos[2], con.pos[3], con.pos[5], kTiers[tierIndex].name); + return false; + } + const float *from = &tile->verts[poly.verts[0] * 3]; + const float *to = &tile->verts[poly.verts[1] * 3]; + if (from[1] <= to[1]) return false; + attached[con.userId - 1] = true; + std::printf(" Downhill link %u on %s: (%.2f, %.2f, %.2f) -> (%.2f, %.2f, %.2f)\n", + con.userId, kTiers[tierIndex].name, from[0], from[1], from[2], to[0], to[1], to[2]); + } + } + for (size_t i = 0; i < geo.downhillLinks.size(); ++i) { + bool expected = (geo.downhillLinks[i].tierMask & (1u << tierIndex)) != 0; + if (expected != (bool)attached[i]) { + std::fprintf(stderr, "Missing downhill link %zu on %s\n", i + 1, kTiers[tierIndex].name); + return false; + } + } + return true; +} + static void markChokepoints(dtNavMesh *mesh, dtNavMeshQuery *query, float chokeDistM) { dtQueryFilter filter; filter.setIncludeFlags(WTO_FLAG_WALK); @@ -819,7 +929,7 @@ public: cells.resize((size_t)cols * rows); for (uint32_t i = 0; i < geo.obsTris.size(); ++i) { const auto &tri = geo.obsTris[i]; - if (tri.cls != WTO_OBS_HARD_SOLID) continue; + if (!hasCoverGeometry(tri.cls)) continue; const auto &a = geo.obsVerts[tri.i0]; const auto &b = geo.obsVerts[tri.i1]; @@ -1148,7 +1258,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], kTiers[tierIdx], tx, tz, mapMinX, mapMinZ, pois.cover, doCovers); + auto br = buildSingleTile(geo, buckets[(size_t)idx], tierIdx, tx, tz, mapMinX, mapMinZ, pois.cover, doCovers); tierTiles[tierIdx][(size_t)idx] = br.tile; if (doCovers && !br.covers.empty()) { localCov.insert(localCov.end(), br.covers.begin(), br.covers.end()); @@ -1174,6 +1284,7 @@ int main(int argc, char **argv) { if (tl && tl->header) polyCnt += tl->header->polyCount; } 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); } @@ -1366,7 +1477,7 @@ int main(int argc, char **argv) { std::vector pHeight((size_t)pw * ph); std::vector pFlags((size_t)pw * ph, 0); /* Bit 0: T0 walkable, Bit 1: T1 walkable, Bit 2: T2 walkable, Bit 3: shallow water, - * Bit 4: deep water, Bit 5: chokepoint, Bit 6: crushable/forest, Bit 7: bridge, Bit 8: road */ + * Bit 4: deep water, Bit 5: chokepoint, Bit 6: crushable/forest, Bit 7: bridge, Bit 8: road, Bit 9: platform */ dtQueryFilter anyF; anyF.setIncludeFlags(0xFFFF); anyF.setExcludeFlags(WTO_FLAG_BLOCKED); @@ -1403,11 +1514,14 @@ int main(int argc, char **argv) { else { fl |= (1u << ti); if (ti == WTO_NAV_TIER_STANDARD) { + unsigned short flags = 0; + meshes[ti]->getPolyFlags(ref, &flags); if (area == WTO_AREA_SHALLOW_WATER) fl |= 8; - else if (area == WTO_AREA_CHOKEPOINT) fl |= 32; - else if (area == WTO_AREA_CRUSHABLE || area == WTO_AREA_FOREST) fl |= 64; - else if (area == WTO_AREA_BRIDGE) fl |= 128; - else if (area == WTO_AREA_ROAD) fl |= 256; + if (flags & WTO_FLAG_CHOKEPOINT) fl |= 32; + if (area == WTO_AREA_CRUSHABLE || area == WTO_AREA_FOREST) fl |= 64; + if (area == WTO_AREA_BRIDGE) fl |= 128; + if ((flags & WTO_FLAG_ROAD) || area == WTO_AREA_ROAD) fl |= 256; + if (flags & WTO_FLAG_PLATFORM) fl |= 512; } } } @@ -1445,6 +1559,11 @@ int main(int argc, char **argv) { pout.write(reinterpret_cast(&npts), 4); pout.write(reinterpret_cast(sp.pts.data()), sp.pts.size() * sizeof(float)); } + if (!geo.downhillLinks.empty()) { + uint32_t count = (uint32_t)geo.downhillLinks.size(); + pout.write(reinterpret_cast(&count), sizeof(count)); + pout.write(reinterpret_cast(geo.downhillLinks.data()), count * sizeof(WtoGeoDownhillLink)); + } } for (uint32_t ti = 0; ti < WTO_NAV_TIER_COUNT; ++ti) { diff --git a/tools/navgen/extract/src/main.rs b/tools/navgen/extract/src/main.rs index 1016274..bf75484 100644 --- a/tools/navgen/extract/src/main.rs +++ b/tools/navgen/extract/src/main.rs @@ -16,8 +16,9 @@ use wt_unpack::vromfs::Vromfs; mod phys_map; const WTO_GEO_MAGIC: &[u8; 8] = b"WTOGEO\0\x01"; -const WTO_GEO_VERSION: u32 = 2; +const WTO_GEO_VERSION: u32 = 3; const WTO_GEO_FLAG_ROAD_MASK: u32 = 1; +const WTO_GEO_FLAG_DOWNHILL_LINKS: u32 = 2; const OBS_HARD_SOLID: u8 = 0; const OBS_BRIDGE_DECK: u8 = 1; @@ -25,6 +26,8 @@ const OBS_CRUSHABLE: u8 = 2; const OBS_TREE_THICK: u8 = 3; const OBS_TREE_THIN: u8 = 4; const OBS_HARD_NO_COVER: u8 = 5; +const OBS_PLATFORM: u8 = 6; +const OBS_PLATFORM_NO_COVER: u8 = 7; #[derive(Debug, Deserialize)] struct LevelPois { @@ -37,6 +40,8 @@ struct LevelPois { bounds_max: [f32; 2], #[serde(rename = "coverBake", default)] cover: CoverBakeInput, + #[serde(rename = "mapBake", default)] + map: MapBakeInput, } #[derive(Debug, Default, Deserialize)] @@ -45,6 +50,46 @@ struct CoverBakeInput { excluded_rendinst: Vec, } +#[derive(Debug, Default, Deserialize)] +#[serde(default, rename_all = "camelCase")] +struct MapBakeInput { + road_materials: Vec, + walkable_rendinst: Vec, + downhill_links: Vec, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase")] +struct DownhillLink { + from: [f32; 3], + to: [f32; 3], + radius_m: f32, + width_tiers: Vec, +} + +impl DownhillLink { + fn write(&self, out: &mut impl Write) -> Result<()> { + let mut mask = 0u32; + for &tier in &self.width_tiers { + if tier >= 3 { + bail!("invalid downhill width tier {tier}"); + } + mask |= 1 << tier; + } + if mask == 0 || self.from[1] <= self.to[1] || self.radius_m <= 0.0 || + !self.radius_m.is_finite() || !self.from.iter().chain(&self.to).all(|v| v.is_finite()) + { + bail!("invalid downhill link {:?} -> {:?}", self.from, self.to); + } + for &value in self.from.iter().chain(&self.to) { + out.write_all(&value.to_le_bytes())?; + } + out.write_all(&self.radius_m.to_le_bytes())?; + out.write_all(&mask.to_le_bytes())?; + Ok(()) + } +} + #[derive(Debug, Clone)] struct PoolMeta { is_bridge: bool, @@ -273,7 +318,7 @@ fn tri_normal_y(a: [f32; 3], b: [f32; 3], c: [f32; 3]) -> f32 { if len > 1e-6 { (ny / len).abs() } else { 0.0 } } -fn build_cached_collision(c: &Collision, meta: &PoolMeta, cover_allowed: bool) -> Option { +fn build_cached_collision(c: &Collision, meta: &PoolMeta, cover_allowed: bool, platform: bool) -> Option { if meta.is_soft_foliage { return None; } @@ -294,7 +339,9 @@ fn build_cached_collision(c: &Collision, meta: &PoolMeta, cover_allowed: bool) - let scale = det3(&n.tm).abs().cbrt(); let hard_class = if cover_allowed && n.traceable() { OBS_HARD_SOLID } else { OBS_HARD_NO_COVER }; let obstacle_class = |a, b, c| { - if meta.is_bridge && tri_normal_y(a, b, c) >= 0.72 { + if platform { + if hard_class == OBS_HARD_SOLID { OBS_PLATFORM } else { OBS_PLATFORM_NO_COVER } + } else if meta.is_bridge && tri_normal_y(a, b, c) >= 0.72 { OBS_BRIDGE_DECK } else if meta.is_crushable { OBS_CRUSHABLE @@ -382,7 +429,7 @@ 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).with_context(|| format!("extracting {} roads", pois.level))?; + let roads = phys_map::RoadMask::read(&level, &pois.map.road_materials).with_context(|| format!("extracting {} roads", pois.level))?; let hm = level.heightmap()?.with_context(|| format!("{} has no HM2 heightmap", pois.level))?; let (cw, ch, crop_origin, heights) = crop_heightmap( @@ -435,6 +482,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(); for (pack_path, items) in &by_pack { let Ok(bytes) = fs::read(pack_path) else { continue }; @@ -445,7 +493,7 @@ fn main() -> Result<()> { 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)) { + if let Some(cc) = build_cached_collision(&col, &meta, !excluded_cover.contains(&key), platforms.contains(&key)) { cached_cols.insert(pool_name.clone(), cc); } } @@ -456,7 +504,7 @@ fn main() -> Result<()> { 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; 6]; + let mut cls_counts = [0usize; 8]; for layer in &layers { let instances = layer.instances()?; @@ -493,7 +541,7 @@ fn main() -> Result<()> { } println!( - " RIGz: pools={} cols={} noCol={} instancesInBounds={} obsTris={} [hard={} bridge={} crush={} treeThick={} treeThin={} collisionOnly={}] ({:.2}s)", + " RIGz: pools={} cols={} noCol={} instancesInBounds={} obsTris={} [hard={} bridge={} crush={} treeThick={} treeThin={} collisionOnly={} platform={} platformCollisionOnly={}] ({:.2}s)", pool_names.len(), cached_cols.len(), no_collision, @@ -505,6 +553,8 @@ fn main() -> Result<()> { cls_counts[3], cls_counts[4], cls_counts[5], + cls_counts[6], + cls_counts[7], t0.elapsed().as_secs_f32() ); @@ -515,7 +565,13 @@ fn main() -> Result<()> { // 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())?; - let flags = if roads.is_some() { WTO_GEO_FLAG_ROAD_MASK } else { 0 }; + let mut flags = 0; + if roads.is_some() { + flags |= WTO_GEO_FLAG_ROAD_MASK; + } + if !pois.map.downhill_links.is_empty() { + flags |= WTO_GEO_FLAG_DOWNHILL_LINKS; + } w.write_all(&flags.to_le_bytes())?; w.write_all(&ever_sha1)?; w.write_all(&water_level.to_le_bytes())?; @@ -551,6 +607,12 @@ fn main() -> Result<()> { if let Some(roads) = roads { roads.write(&mut w)?; } + if !pois.map.downhill_links.is_empty() { + w.write_all(&(pois.map.downhill_links.len() as u32).to_le_bytes())?; + for link in &pois.map.downhill_links { + link.write(&mut w)?; + } + } w.flush()?; println!(" wrote {} ({:.1} MB)", out_path.display(), fs::metadata(&out_path)?.len() as f64 / (1024.0 * 1024.0)); Ok(()) diff --git a/tools/navgen/extract/src/phys_map.rs b/tools/navgen/extract/src/phys_map.rs index 2e127e0..bc414cc 100644 --- a/tools/navgen/extract/src/phys_map.rs +++ b/tools/navgen/extract/src/phys_map.rs @@ -18,7 +18,7 @@ pub struct RoadMask { } impl RoadMask { - pub fn read(level: &Level<'_>) -> Result> { + pub fn read(level: &Level<'_>, road_materials: &[String]) -> Result> { let Some(info) = level.phys_map_info()? else { return Ok(None); }; @@ -44,7 +44,7 @@ impl RoadMask { matches!( name.to_ascii_lowercase().as_str(), "road" | "roadsoil" | "roadsand" | "roadsnow" | "roadmud" - ) + ) || road_materials.iter().any(|material| name.eq_ignore_ascii_case(material)) }) .collect(); if !is_road.contains(&true) { diff --git a/tools/navgen/mission-bounds.mts b/tools/navgen/mission-bounds.mts index 707e76f..d17f57d 100644 --- a/tools/navgen/mission-bounds.mts +++ b/tools/navgen/mission-bounds.mts @@ -9,7 +9,7 @@ * --out "build\nav-work" \ * --levels avg_berlin,avg_poland,avg_hurtgen */ -import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'; +import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'; import { join, resolve } from 'node:path'; import { TuningReader } from '../../apps/server/src/tuning/tuning-reader.ts'; import { parseJsonc } from '../../packages/jsonc/src/index.ts'; @@ -35,6 +35,7 @@ interface LevelPois { readonly team2Spawns: readonly PoiPoint[]; readonly captureZones: readonly PoiPoint[]; readonly coverBake: ReturnType; + readonly mapBake?: NonNullable>; } function parseArgs(argv: string[]) { @@ -161,6 +162,31 @@ function readCoverBake() { }; } +function readMapBake(level: string) { + const path = join(import.meta.dirname, '..', '..', 'apps', 'server', 'tuning', 'maps', level + '.jsonc'); + if (!existsSync(path)) return undefined; + const map = new TuningReader(path, parseJsonc(readFileSync(path, 'utf8'))); + if (map.string('level') !== level) throw new Error('Mismatched level in ' + path); + map.int('version', { min: 1, max: 1 }); + if (!map.has('bake')) return undefined; + const bake = map.object('bake'); + const point = (r: TuningReader) => [r.number('x'), r.number('y'), r.number('z')] as const; + const downhillLinks = bake.has('downhillLinks') ? bake.list('downhillLinks', (link) => { + const from = point(link.object('from')); + const to = point(link.object('to')); + const widthTiers = link.intList('widthTiers', { min: 0, max: 2 }); + if (!widthTiers.length || from[1] <= to[1] || (from[0] === to[0] && from[2] === to[2])) { + throw new Error('Invalid downhill link in ' + path); + } + return { from, to, radiusM: link.number('radiusM', { min: 0.01 }), widthTiers }; + }) : []; + return { + roadMaterials: bake.has('roadMaterials') ? bake.stringList('roadMaterials') : [], + walkableRendinst: bake.has('walkableRendinst') ? bake.stringList('walkableRendinst') : [], + downhillLinks, + }; +} + function main() { const { gameDir, outDir, levelsFilter } = parseArgs(process.argv.slice(2)); const coverBake = readCoverBake(); @@ -276,6 +302,7 @@ function main() { } // Expand battle-area union by 120m safety padding const margin = 120; + const mapBake = readMapBake(levelKey); const out: LevelPois = { level: levelKey, levelPath: acc.levelPath, @@ -286,6 +313,7 @@ function main() { team2Spawns: t2, captureZones: caps, coverBake, + ...(mapBake && { mapBake }), }; const outPath = join(outDir, `${levelKey}.pois.json`); writeFileSync(outPath, `${JSON.stringify(out, null, 2)}\n`, 'utf8'); diff --git a/tools/navgen/render-preview.py b/tools/navgen/render-preview.py index 6b33d84..819b5b6 100644 --- a/tools/navgen/render-preview.py +++ b/tools/navgen/render-preview.py @@ -127,6 +127,13 @@ def main() -> None: off += npts * 12 paths.append([(pts[i * 3], pts[i * 3 + 2]) for i in range(npts)]) + downhill = [] + if off < len(data): + count, = struct.unpack_from(" None: # Bright green = T2 (wide heavy) + T1 + T0 walkable # Mid-green = T1 + T0 walkable (standard tank fits, wide heavy doesn't) # Yellow-green = T0 only (narrow tank alley) - # Tan = road, Orange = chokepoint, Olive = crushable/forest, Teal = bridge + # Tan = road, Ochre = narrow road, Orange = chokepoint, + # Olive = crushable/forest, Teal = bridge, Pale green = platform r, g, b = base, base, base if fl & 16: # deep water r, g, b = 22, 58, 125 @@ -165,12 +173,14 @@ def main() -> None: r, g, b = 55, 130, 185 elif fl & 128: # bridge r, g, b = 70, 210, 210 + elif fl & 512: # platform + r, g, b = 102, 185, 152 + elif fl & 256: # road, including road polygons flagged as narrow + r, g, b = (197, 154, 97) if fl & 32 else (174, 149, 108) elif fl & 32: # chokepoint r, g, b = 220, 145, 45 elif fl & 64: # crushable/forest r, g, b = int(base * 0.6 + 65), int(base * 0.8 + 85), int(base * 0.5 + 35) - elif fl & 256: # road - r, g, b = 174, 149, 108 elif fl & 4: # T2 wide walkable r, g, b = int(base * 0.5 + 48), int(base * 0.7 + 125), int(base * 0.5 + 52) elif fl & 2: # T1 standard walkable @@ -209,6 +219,21 @@ def main() -> None: x1, y1 = world_to_px(*path[i + 1]) draw_line(nav_rgb, pw, ph, x0, y0, x1, y1, (0, 245, 255), thick=2) + for link in downhill: + x0, y0 = world_to_px(link[0], link[2]) + x1, y1 = world_to_px(link[3], link[5]) + length = math.hypot(x1 - x0, y1 - y0) + if length == 0: + continue + color = (244, 108, 210) + ux, uy = (x1 - x0) / length, (y1 - y0) / length + head = min(6.0, length / 2) + draw_line(nav_rgb, pw, ph, x0, y0, x1, y1, color, thick=2) + for side in (-1, 1): + bx = round(x1 - head * ux - side * head * uy * 0.5) + by = round(y1 - head * uy + side * head * ux * 0.5) + draw_line(nav_rgb, pw, ph, x1, y1, bx, by, color, thick=2) + # Overlay spawns & capture zones on BOTH maps for rgb in (nav_rgb, cov_rgb): for sp in pois.get("team1Spawns", []):