use glam::Vec3; use project_cold_water::audio::bvh::AcousticBvh; use project_cold_water::core::materials::MaterialId; use project_cold_water::modding::blueprint::{ starter_map_blueprint, starter_vehicle_blueprint, starter_weapon_blueprint, AssetBlueprint, }; use project_cold_water::modding::csg::{ evaluate_csg_tree, polygons_to_actor_mesh, AssetStampKind, CsgNode, CsgOp, PrimitiveKind, }; use project_cold_water::modding::registry::ModRegistry; use project_cold_water::sim::vehicles::Vehicle; use project_cold_water::world::terrain::TerrainGrid; use project_cold_water::world::Faction; #[test] fn test_csg_boolean_operations_and_stamps() { // 1. Box - Cylinder subtraction produces enclosed cavity faces with valid unit normals let sub_nodes = vec![ CsgNode::new_primitive( 1, "Outer Block", CsgOp::Union, PrimitiveKind::Box, [0.0, 1.0, 0.0], [0.0, 0.0, 0.0], [2.0, 2.0, 2.0], MaterialId::Concrete, ), CsgNode::new_primitive( 2, "Bore Hole", CsgOp::Subtract, PrimitiveKind::Cylinder { segments: 12 }, [0.0, 1.0, 0.0], [90.0, 0.0, 0.0], [0.8, 3.0, 0.8], MaterialId::Gunmetal, ), ]; let sub_polys = evaluate_csg_tree(&sub_nodes); let (verts, idx, bmin, bmax) = polygons_to_actor_mesh(&sub_polys); assert!(verts.len() > 24 && idx.len() >= 36, "Expected rich sculpted CSG subtract mesh"); assert!(bmin.y >= -0.05 && bmax.y <= 2.05); for v in &verts { let n = Vec3::from_array(v.normal); assert!(n.is_finite() && (n.length() - 1.0).abs() < 0.02, "Non-unit normal {n:?}"); } for &i in &idx { assert!((i as usize) < verts.len()); } // 2. Box U Wedge union let union_nodes = vec![ CsgNode::new_primitive(1, "Base", CsgOp::Union, PrimitiveKind::Box, [0.0, 0.5, 0.0], [0.0; 3], [2.0, 1.0, 2.0], MaterialId::Concrete), CsgNode::new_primitive(2, "Ramp", CsgOp::Union, PrimitiveKind::Wedge, [2.0, 0.5, 0.0], [0.0; 3], [2.0, 1.0, 2.0], MaterialId::Gunmetal), ]; let u_polys = evaluate_csg_tree(&union_nodes); let (uv, ui, _, _) = polygons_to_actor_mesh(&u_polys); assert!(!uv.is_empty() && !ui.is_empty()); // 3. Box n Sphere intersection let isect_nodes = vec![ CsgNode::new_primitive(1, "Cube", CsgOp::Union, PrimitiveKind::Box, [0.0, 0.0, 0.0], [0.0; 3], [1.6, 1.6, 1.6], MaterialId::Concrete), CsgNode::new_primitive(2, "Sphere", CsgOp::Intersect, PrimitiveKind::Sphere { rings: 8, sectors: 12 }, [0.0, 0.0, 0.0], [0.0; 3], [2.0, 2.0, 2.0], MaterialId::Gunmetal), ]; let i_polys = evaluate_csg_tree(&isect_nodes); let (iv, ii, imin, imax) = polygons_to_actor_mesh(&i_polys); assert!(!iv.is_empty() && !ii.is_empty()); assert!(imax.x <= 0.85 && imin.x >= -0.85); // 4. AssetStamps compile cleanly for stamp in [AssetStampKind::Ak74m, AssetStampKind::Ural4320Body, AssetStampKind::BunkerShell] { let s_nodes = vec![CsgNode::new_primitive( 1, stamp.label(), CsgOp::Union, PrimitiveKind::AssetStamp(stamp), [0.0; 3], [0.0; 3], [1.0; 3], MaterialId::AfghankaOlive, )]; let sp = evaluate_csg_tree(&s_nodes); let (sv, si, _, _) = polygons_to_actor_mesh(&sp); assert!(sv.len() >= 12 && si.len() >= 12, "Empty stamp mesh for {:?}", stamp); } } #[test] fn test_blueprint_json_registry_bvh_and_heightmap_roundtrip() { for bp in [ starter_weapon_blueprint(), starter_vehicle_blueprint(), starter_map_blueprint(), ] { let json = serde_json::to_string_pretty(&bp).expect("serialize blueprint"); let parsed: AssetBlueprint = serde_json::from_str(&json).expect("deserialize blueprint"); assert_eq!(parsed.id, bp.id); assert_eq!(parsed.name, bp.name); } let tmp_root = std::env::temp_dir().join(format!("pcw_mod_test_{}", std::process::id())); let _ = std::fs::remove_dir_all(&tmp_root); let mods = ModRegistry::load_or_init_dir(&tmp_root); assert!(mods.find_weapon("as_val_custom").is_some(), "Missing starter weapon mod"); let zsu = mods.find_vehicle("gun_truck_zsu").expect("Missing starter vehicle mod"); assert!(zsu.turret_slice.is_some()); let custom_veh = Vehicle::new_custom( 0, zsu.blueprint.name.clone(), zsu, Faction::Federal, Vec3::ZERO, 0.0, None, ); assert!(custom_veh.effective_spec().has_turret); assert!(!custom_veh.seats.is_empty()); // Build starter bunker outpost map from generated demo heightmap PNG let hm_path = tmp_root.join("heightmaps").join("caucasus_valley.png"); assert!(hm_path.exists(), "Demo heightmap PNG was not generated"); let (hm_grid, hm_v, hm_i, _, _, _, _) = TerrainGrid::build_from_heightmap_png(&hm_path, 200.0, 4.0, -4.0, 44.0, -0.6, true) .expect("load generated demo heightmap PNG"); assert!(!hm_v.is_empty() && !hm_i.is_empty()); assert!(hm_grid.cells_per_side > 20); let mut map_bp = starter_map_blueprint(); if let project_cold_water::modding::blueprint::BlueprintPayload::Map(ref mut mb) = map_bp.payload { if let project_cold_water::modding::blueprint::MapTerrainBase::HeightmapPng { ref mut png_path, .. } = mb.base_terrain { *png_path = hm_path.to_string_lossy().into_owned(); } } let world = mods.build_world_from_map(&map_bp).expect("reconstruct world from MapBlueprint"); let bvh = AcousticBvh::build(world.acoustic_triangles.clone()); // Cast ray downward/forward into sculpted CSG bastion centered around (0, 3.4, 0) let hit = bvh.raycast(Vec3::new(0.0, 12.0, 0.0), Vec3::NEG_Y, 20.0); assert!(hit.is_some(), "AcousticBVH should hit sculpted CSG concrete bastion"); let _ = std::fs::remove_dir_all(&tmp_root); } #[test] fn test_studio_gizmo_hit_test_translate_scale_and_rotate() { use glam::Vec2; use project_cold_water::camera::CameraController; use project_cold_water::modding::blueprint::starter_vehicle_blueprint; use project_cold_water::modding::studio::{AssetStudioState, GizmoHandle, GizmoMode, StudioMode}; let mut studio = AssetStudioState::default(); studio.switch_new_mode(StudioMode::Map); studio.load_blueprint(starter_vehicle_blueprint()); studio.selected_node_id = Some(2); // "Welded Cab Armor Plate" let mut cam = CameraController::new(); studio.apply_to_camera(&mut cam); let screen = Vec2::new(1280.0, 720.0); // 1. Translate: hit X handle tip, drag positively, verify movement & cancel rollback studio.gizmo_mode = GizmoMode::Translate; let orig = studio.selected_gizmo_origin().expect("selected gizmo origin"); let start_pos = studio.selected_node().unwrap().pos; let len = studio.gizmo_world_length(&cam, orig); let axes = studio.gizmo_axes_world(); let tip_x = AssetStudioState::project_world_point(orig + axes[0] * (len * 0.75), screen, &cam) .expect("project X tip"); assert_eq!(studio.hit_test_gizmo(tip_x, screen, 1.0, &cam), Some(GizmoHandle::AxisX)); assert!(studio.begin_gizmo_drag(tip_x, screen, 1.0, &cam)); let drag_target = AssetStudioState::project_world_point(orig + axes[0] * (len * 0.75 + 1.5), screen, &cam) .expect("project dragged X"); studio.update_gizmo_drag(drag_target, screen, 1.0, &cam, false); assert!( (studio.selected_node().unwrap().pos[0] - start_pos[0]).abs() > 0.25, "Translate X drag should move node" ); studio.cancel_gizmo_drag(); assert!( (studio.selected_node().unwrap().pos[0] - start_pos[0]).abs() < 1e-4, "Cancelling drag must restore start position" ); // 2. Scale: hit center Uniform ring & Y handle studio.gizmo_mode = GizmoMode::Scale; let orig_2d = AssetStudioState::project_world_point(orig, screen, &cam).unwrap(); assert_eq!(studio.hit_test_gizmo(orig_2d, screen, 1.0, &cam), Some(GizmoHandle::Uniform)); let start_scl = studio.selected_node().unwrap().scale; assert!(studio.begin_gizmo_drag(orig_2d, screen, 1.0, &cam)); studio.update_gizmo_drag(orig_2d + Vec2::new(60.0, -20.0), screen, 1.0, &cam, false); assert!(studio.selected_node().unwrap().scale[0] > start_scl[0]); studio.end_gizmo_drag(); let tip_y = AssetStudioState::project_world_point(orig + studio.gizmo_axes_world()[1] * (len * 0.75), screen, &cam) .unwrap(); assert_eq!(studio.hit_test_gizmo(tip_y, screen, 1.0, &cam), Some(GizmoHandle::AxisY)); // 3. Rotate: hit Y ring and drag with snap studio.gizmo_mode = GizmoMode::Rotate; let ring_pt = AssetStudioState::project_world_point(orig + Vec3::X * (len * 0.85), screen, &cam).unwrap(); assert!(studio.hit_test_gizmo(ring_pt, screen, 1.0, &cam).is_some()); assert!(studio.begin_gizmo_drag(ring_pt, screen, 1.0, &cam)); studio.update_gizmo_drag(ring_pt + Vec2::new(-35.0, 45.0), screen, 1.0, &cam, true); studio.end_gizmo_drag(); } #[test] fn test_custom_turreted_vehicle_gets_gunner_seat_and_optic() { use project_cold_water::modding::blueprint::{ BlueprintPayload, VehicleBlueprint, SCHEMA_VERSION, }; use project_cold_water::sim::Simulation; use project_cold_water::sim::vehicles::VehicleSeatRole; use project_cold_water::world::VehicleKind; let mut vb = VehicleBlueprint::from_archetype(VehicleKind::Uaz469); vb.has_turret = true; vb.seat_roles = vec![ VehicleSeatRole::Driver, VehicleSeatRole::Passenger, VehicleSeatRole::Passenger, ]; vb.turret_nodes.push(CsgNode::new_primitive( 99, "Custom Turret Cupola", CsgOp::Union, PrimitiveKind::Cylinder { segments: 10 }, [0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.8, 0.6, 0.8], MaterialId::SteelHulk, )); let bp = AssetBlueprint { schema_version: SCHEMA_VERSION, id: "uaz_brdm_test".into(), name: "BRDM Test".into(), author: "ColdWater".into(), payload: BlueprintPayload::Vehicle(vb), }; let tmp_root = std::env::temp_dir().join(format!("pcw_brdm_test_{}", std::process::id())); let _ = std::fs::remove_dir_all(&tmp_root); let mut reg = ModRegistry::load_or_init_dir(&tmp_root); reg.save_blueprint(&tmp_root, bp).expect("save brdm test bp"); let compiled = reg.find_vehicle("uaz_brdm_test").expect("compiled vehicle"); let world = reg .build_world_from_map(&starter_map_blueprint()) .expect("build world"); let mut sim = Simulation::new(&world); sim.vehicles.clear(); let veh = Vehicle::new_custom( 0, "Test BRDM-2".into(), compiled, Faction::Federal, Vec3::ZERO, 0.0, None, ); assert_eq!(veh.seats[0].0, VehicleSeatRole::Driver); assert_eq!(veh.seats[1].0, VehicleSeatRole::Gunner); assert!(veh.effective_spec().has_turret); sim.vehicles.push(veh); let s = sim.soldiers[0].clone(); sim.player.deploy_into_soldier(&s); sim.player.pos = Vec3::new(0.0, 0.0, 1.5); assert!(sim.try_player_toggle_vehicle().is_some()); assert!(!sim.player.is_btr_optic_active(&sim.vehicles)); let msg = sim.try_player_switch_seat(1).expect("switch to gunner seat with Digit2"); assert!(msg.contains("Gunner"), "expected gunner role message, got {msg}"); assert!(sim.vehicles[0].gunner_is_player()); assert!(sim.player.is_btr_optic_active(&sim.vehicles)); let _ = std::fs::remove_dir_all(&tmp_root); } #[test] fn test_studio_gizmo_edits_turret_muzzle_and_wheel_axles() { use glam::Vec2; use project_cold_water::camera::CameraController; use project_cold_water::modding::blueprint::{starter_vehicle_blueprint, BlueprintPayload}; use project_cold_water::modding::studio::{AssetStudioState, GizmoHandle, StudioAnchor, StudioMode}; let mut studio = AssetStudioState::default(); studio.load_blueprint(starter_vehicle_blueprint()); let mut cam = CameraController::new(); studio.apply_to_camera(&mut cam); let screen = Vec2::new(1280.0, 720.0); // 1. Turret mount pivot drag along Y & cancel rollback studio.select_anchor(StudioAnchor::VehicleTurretMount); let mount_orig = studio.selected_gizmo_origin().expect("turret origin"); let mount_start_y = mount_orig.y; let len = studio.gizmo_world_length(&cam, mount_orig); let tip_y = AssetStudioState::project_world_point(mount_orig + Vec3::Y * len, screen, &cam).unwrap(); assert_eq!(studio.hit_test_gizmo(tip_y, screen, 1.0, &cam), Some(GizmoHandle::AxisY)); assert!(studio.begin_gizmo_drag(tip_y, screen, 1.0, &cam)); let dragged_y = AssetStudioState::project_world_point(mount_orig + Vec3::Y * (len + 0.65), screen, &cam).unwrap(); studio.update_gizmo_drag(dragged_y, screen, 1.0, &cam, false); if let BlueprintPayload::Vehicle(ref vb) = studio.blueprint.payload { assert!((vb.turret_mount_local[1] - mount_start_y).abs() > 0.25); } else { panic!("expected vehicle"); } studio.cancel_gizmo_drag(); if let BlueprintPayload::Vehicle(ref vb) = studio.blueprint.payload { assert!((vb.turret_mount_local[1] - mount_start_y).abs() < 1e-4); } // 2. Turret muzzle drag along Z without altering turret mount studio.select_anchor(StudioAnchor::VehicleTurretMuzzle); let muz_orig = studio.selected_gizmo_origin().expect("turret muzzle origin"); let (mount_before, muz_start_z) = match &studio.blueprint.payload { BlueprintPayload::Vehicle(vb) => (vb.turret_mount_local, vb.turret_muzzle_local[2]), _ => panic!("expected vehicle"), }; let muz_len = studio.gizmo_world_length(&cam, muz_orig); let muz_tip_z = AssetStudioState::project_world_point(muz_orig + Vec3::Z * muz_len, screen, &cam).unwrap(); assert!(studio.begin_gizmo_drag(muz_tip_z, screen, 1.0, &cam)); let muz_drag_z = AssetStudioState::project_world_point(muz_orig + Vec3::Z * (muz_len + 0.8), screen, &cam).unwrap(); studio.update_gizmo_drag(muz_drag_z, screen, 1.0, &cam, false); studio.end_gizmo_drag(); if let BlueprintPayload::Vehicle(ref vb) = studio.blueprint.payload { assert_eq!(vb.turret_mount_local, mount_before); assert!(vb.turret_muzzle_local[2] > muz_start_z + 0.2); } // 3. Wheel axle 0 symmetrical track (X) & fore/aft (Z) drag studio.select_anchor(StudioAnchor::VehicleWheelAxle(0)); let ax_orig = studio.selected_gizmo_origin().expect("axle 0 origin"); let ax_len = studio.gizmo_world_length(&cam, ax_orig); let (start_x0, start_z0) = match &studio.blueprint.payload { BlueprintPayload::Vehicle(vb) => (vb.wheel_offsets[0][0], vb.wheel_offsets[0][1]), _ => panic!("expected vehicle"), }; let ax_tip_x = AssetStudioState::project_world_point(ax_orig + Vec3::X * ax_len, screen, &cam).unwrap(); assert!(studio.begin_gizmo_drag(ax_tip_x, screen, 1.0, &cam)); let ax_drag_x = AssetStudioState::project_world_point(ax_orig + Vec3::X * (ax_len + 0.55), screen, &cam).unwrap(); studio.update_gizmo_drag(ax_drag_x, screen, 1.0, &cam, false); studio.end_gizmo_drag(); if let BlueprintPayload::Vehicle(ref vb) = studio.blueprint.payload { assert!((vb.wheel_offsets[0][0] + vb.wheel_offsets[1][0]).abs() < 1e-4, "left/right track must stay symmetric"); assert!(vb.wheel_offsets[0][0].abs() > start_x0.abs() + 0.15); } let ax_orig2 = studio.selected_gizmo_origin().expect("axle 0 updated origin"); let ax_tip_z = AssetStudioState::project_world_point(ax_orig2 + Vec3::Z * ax_len, screen, &cam).unwrap(); assert!(studio.begin_gizmo_drag(ax_tip_z, screen, 1.0, &cam)); let ax_drag_z = AssetStudioState::project_world_point(ax_orig2 + Vec3::Z * (ax_len + 0.70), screen, &cam).unwrap(); studio.update_gizmo_drag(ax_drag_z, screen, 1.0, &cam, false); studio.end_gizmo_drag(); if let BlueprintPayload::Vehicle(ref vb) = studio.blueprint.payload { assert!((vb.wheel_offsets[0][1] - start_z0) > 0.2); assert!((vb.wheel_offsets[0][1] - vb.wheel_offsets[1][1]).abs() < 1e-4); } // 4. Weapon mode: screen-pick MUZZLE marker & drag Z studio.switch_new_mode(StudioMode::Weapon); studio.apply_to_camera(&mut cam); let w_muz = studio.anchor_world_pos(StudioAnchor::WeaponMuzzle).expect("weapon muzzle"); let w_muz_2d = AssetStudioState::project_world_point(w_muz, screen, &cam).unwrap(); assert!(studio.pick_node_at_screen(w_muz_2d, screen, &cam)); assert_eq!(studio.selected_anchor, Some(StudioAnchor::WeaponMuzzle)); let w_len = studio.gizmo_world_length(&cam, w_muz); let w_tip_z = AssetStudioState::project_world_point(w_muz + Vec3::Z * w_len, screen, &cam).unwrap(); assert!(studio.begin_gizmo_drag(w_tip_z, screen, 1.0, &cam)); let w_drag_z = AssetStudioState::project_world_point(w_muz + Vec3::Z * (w_len + 0.25), screen, &cam).unwrap(); studio.update_gizmo_drag(w_drag_z, screen, 1.0, &cam, false); studio.end_gizmo_drag(); if let BlueprintPayload::Weapon(ref wb) = studio.blueprint.payload { assert!(wb.muzzle_local[2] > w_muz.z + 0.08); } } #[test] fn test_wip_empty_hull_vehicle_still_loads_in_registry() { use project_cold_water::modding::blueprint::{ BlueprintPayload, VehicleBlueprint, SCHEMA_VERSION, }; use project_cold_water::world::VehicleKind; let mut vb = VehicleBlueprint::from_archetype(VehicleKind::Uaz469); vb.hull_nodes.clear(); let bp = AssetBlueprint { schema_version: SCHEMA_VERSION, id: "wip_empty_hull".into(), name: "WIP Empty Hull".into(), author: "ColdWater".into(), payload: BlueprintPayload::Vehicle(vb), }; let tmp_root = std::env::temp_dir().join(format!("pcw_wip_empty_{}", std::process::id())); let _ = std::fs::remove_dir_all(&tmp_root); let mut reg = ModRegistry::load_or_init_dir(&tmp_root); reg.save_blueprint(&tmp_root, bp).expect("save wip blueprint"); reg.reload_from_dir(&tmp_root); let loaded = reg .find_vehicle("wip_empty_hull") .expect("WIP vehicle with empty hull_nodes must still load"); assert_eq!(loaded.hull_slice.index_count, 0); assert!(loaded.wheel_slice.index_count > 0); assert!(loaded.half_extents.x > 0.5 && loaded.half_extents.z > 1.0); let _ = std::fs::remove_dir_all(&tmp_root); } #[test] fn test_map_stamp_creator_save_stamp_into_map_and_compile_world() { use project_cold_water::modding::blueprint::{ starter_map_stamp_blueprint, BlueprintPayload, MapStampBlueprint, MapTerrainBase, SCHEMA_VERSION, }; use project_cold_water::modding::csg::{count_csg_nodes, CsgShape}; use project_cold_water::modding::studio::{AssetStudioState, StudioMode}; use project_cold_water::net::handshake::{HandshakeMapSource, ServerHandshake}; // 1. Auto-seeding starter stamp & custom stamp creation let tmp_root = std::env::temp_dir().join(format!("pcw_stamp_test_{}", std::process::id())); let _ = std::fs::remove_dir_all(&tmp_root); let mut reg = ModRegistry::load_or_init_dir(&tmp_root); assert!( reg.find_stamp("guard_watchtower").is_some(), "Starter Watchtower Stamp should auto-seed into mods/stamps/" ); // 2. Sculpt custom Map Stamp initially shifted above ground & off-center let mut studio = AssetStudioState::default(); studio.switch_new_mode(StudioMode::MapStamp); let custom_stamp = AssetBlueprint { schema_version: SCHEMA_VERSION, id: "checkpoint_arch".into(), name: "Checkpoint Archway".into(), author: "ColdWater".into(), payload: BlueprintPayload::MapStamp(MapStampBlueprint { nodes: vec![ CsgNode::new_primitive( 1, "Arch Block", CsgOp::Union, PrimitiveKind::Box, [4.0, 4.0, -3.0], [0.0, 0.0, 0.0], [5.0, 3.6, 2.4], MaterialId::Concrete, ), CsgNode::new_primitive( 2, "Passage Cutout", CsgOp::Subtract, PrimitiveKind::Box, [4.0, 3.4, -3.0], [0.0, 0.0, 0.0], [2.6, 2.4, 3.0], MaterialId::Concrete, ), CsgNode::new_primitive( 3, "Roof Beacon Box", CsgOp::Union, PrimitiveKind::Box, [4.0, 6.0, -3.0], [0.0, 0.0, 0.0], [5.4, 0.4, 2.8], MaterialId::SteelHulk, ), ], description: "Fortified checkpoint archway".into(), blocks_navigation: true, }), }; studio.load_blueprint(custom_stamp); studio.align_stamp_to_ground_and_center(true); studio.recompile_preview(); assert!( studio.preview_bounds_min.y.abs() < 0.05, "Expected ground-aligned min_y ~ 0, got {}", studio.preview_bounds_min.y ); let cx = (studio.preview_bounds_min.x + studio.preview_bounds_max.x) * 0.5; let cz = (studio.preview_bounds_min.z + studio.preview_bounds_max.z) * 0.5; assert!( cx.abs() < 0.05 && cz.abs() < 0.05, "Expected centered XZ pivot, got ({cx}, {cz})" ); // 3. Save custom stamp to ./mods/stamps/ and verify registry & MP manifest include it let saved_stamp_bp = studio.blueprint.clone(); reg.save_blueprint(&tmp_root, saved_stamp_bp) .expect("save map stamp"); let loaded_stamp = reg .find_stamp("checkpoint_arch") .expect("saved stamp must appear in ModRegistry::stamps") .clone(); let hs = ServerHandshake::build_from_registry( "Stamp Server", 30, 16, 0, HandshakeMapSource::ClassicFoothills, ®, ); assert!( hs.mod_manifest .iter() .any(|e| e.category == "stamps" && e.id == "checkpoint_arch"), "ServerHandshake mod_manifest must list stamps" ); // 4. Switch to Map mode, stamp twice into map, test unpack_selected_group on a 3rd copy let watchtower = starter_map_stamp_blueprint(); studio.switch_new_mode(StudioMode::Map); if let BlueprintPayload::Map(ref mut mb) = studio.blueprint.payload { mb.base_terrain = MapTerrainBase::FlatSandbox { half_extent: 140.0, material: MaterialId::WinterMud, }; mb.nodes.clear(); } studio.orbit_target = Vec3::new(0.0, 0.0, 0.0); studio.add_custom_map_stamp(&loaded_stamp); studio.orbit_target = Vec3::new(18.0, 0.0, 0.0); studio.add_custom_map_stamp(&watchtower); if let Some(wt_node) = studio.selected_node_mut() { wt_node.rot_deg[1] = 45.0; } // Verify nested node counter counts Group + inner primitives assert!( count_csg_nodes(studio.active_nodes()) > 10, "count_csg_nodes should recursively count Group children" ); // Test Unpack Group preserves world transform & produces editable primitives studio.orbit_target = Vec3::new(-18.0, 0.0, 6.0); studio.add_custom_map_stamp(&loaded_stamp); let count_before_unpack = studio.active_nodes().len(); assert!(matches!( studio.selected_node().unwrap().shape, CsgShape::Group(_) )); studio.unpack_selected_group(); assert!( studio.active_nodes().len() > count_before_unpack, "Unpacking group must expand child nodes into top-level list" ); // 5. Compile resulting MapBlueprint -> WorldData and verify BVH + NavGrid let world = reg .build_world_from_map(&studio.blueprint) .expect("compile map containing custom stamped groups"); let bvh = AcousticBvh::build(world.acoustic_triangles.clone()); // Raycast directly onto Watchtower roof at (18, 12, 0) let hit = bvh.raycast(Vec3::new(18.0, 12.0, 0.0), Vec3::NEG_Y, 15.0); assert!(hit.is_some(), "AcousticBVH must hit stamped Watchtower group"); assert!( hit.unwrap().t < 9.0, "Expected Watchtower geometry well above flat ground (y=0)" ); // NavGrid should carry CSG wall data (walls/posts carve transitions instead of a solid footprint) assert!(world.nav_grid.wall_bvh.is_some(), "CSG wall BVH must be attached to NavGrid"); assert!( world.nav_grid.edge_blocks.iter().any(|&b| b != 0), "NavGrid should block transitions crossing stamped walls" ); let _ = std::fs::remove_dir_all(&tmp_root); } #[test] fn test_csg_building_is_enterable_through_doorway_but_walls_block() { use project_cold_water::modding::blueprint::{ BlueprintPayload, MapBlueprint, MapModSpawn, MapTerrainBase, SCHEMA_VERSION, }; use project_cold_water::modding::csg::{CsgShape}; use project_cold_water::sim::player::FpsInput; use project_cold_water::sim::Simulation; // Hollow 8x3x8 concrete house with a 1.6m doorway on its -Z wall, stamped as a Group (like a Map Stamp) let house_parts = vec![ CsgNode::new_primitive(1, "Shell", CsgOp::Union, PrimitiveKind::Box, [0.0, 1.5, 0.0], [0.0; 3], [8.0, 3.0, 8.0], MaterialId::Concrete), CsgNode::new_primitive(2, "Room", CsgOp::Subtract, PrimitiveKind::Box, [0.0, 1.45, 0.0], [0.0; 3], [7.4, 2.7, 7.4], MaterialId::Concrete), CsgNode::new_primitive(3, "Door", CsgOp::Subtract, PrimitiveKind::Box, [0.0, 1.1, -4.0], [0.0; 3], [1.6, 2.2, 1.4], MaterialId::Concrete), ]; let map_bp = AssetBlueprint { schema_version: SCHEMA_VERSION, id: "house_test".into(), name: "House Test".into(), author: "ColdWater".into(), payload: BlueprintPayload::Map(MapBlueprint { base_terrain: MapTerrainBase::FlatSandbox { half_extent: 120.0, material: MaterialId::WinterMud }, nodes: vec![CsgNode { id: 10, name: "House Stamp".into(), op: CsgOp::Union, shape: CsgShape::Group(house_parts), pos: [0.0, 0.0, 0.0], rot_deg: [0.0; 3], scale: [1.0; 3], material: MaterialId::Concrete, override_stamp_material: false, visible: true, modifiers: Vec::new(), }], spawns: vec![ MapModSpawn { name: "Fed".into(), faction: Faction::Federal, pos: [0.0, 0.0, -30.0], ..Default::default() }, MapModSpawn { name: "Mil".into(), faction: Faction::Militia, pos: [0.0, 0.0, 40.0], ..Default::default() }, ], objectives: Vec::new(), vehicles: Vec::new(), named_curves: Vec::new(), script_hooks: Vec::new(), mission_defaults: Default::default(), }), }; let reg = ModRegistry::default(); let world = reg.build_world_from_map(&map_bp).expect("build house map"); let nav = &world.nav_grid; // 1. Interior is walkable (no solid footprint), and AI can path from outside into the room assert!(nav.is_walkable_world(1.0, 1.0), "House interior must be walkable"); let inside = Vec3::new(1.0, 0.0, 1.0); let path = nav.find_path(Vec3::new(0.0, 0.0, -20.0), inside); let last = *path.last().expect("path"); assert!( Vec3::new(last.x - inside.x, 0.0, last.z - inside.z).length() < 1.5, "AI path should reach house interior through the doorway, got {path:?}" ); // A path from directly behind the +Z wall must not string-pull straight through the wall assert!(!nav.is_segment_walkable(Vec3::new(1.0, 0.0, 9.0), inside), "Segment through solid wall must be rejected"); // 2. FPS player walks through the doorway into the room and stops at the back wall let bvh = AcousticBvh::build(world.acoustic_triangles.clone()); let mut sim = Simulation::new(&world); let s = sim.soldiers[0].clone(); sim.player.deploy_into_soldier(&s); let walk = FpsInput { move_fwd: 1.0, ..Default::default() }; sim.player.pos = Vec3::new(0.0, 0.0, -10.0); sim.player.yaw = std::f32::consts::PI; // flat_forward = +Z sim.player.pitch = 0.0; for _ in 0..300 { sim.step_fps_player(1.0 / 60.0, &walk, &bvh); } let pz = sim.player.pos.z; assert!(pz > 0.0 && pz < 3.7, "Player should enter through doorway and stop at back wall, z={pz}"); // 3. Walking into the solid front wall (beside the doorway) is blocked sim.player.pos = Vec3::new(2.6, 0.0, -10.0); for _ in 0..300 { sim.step_fps_player(1.0 / 60.0, &walk, &bvh); } let pz2 = sim.player.pos.z; assert!(pz2 < -4.0, "Player must not pass through the house wall, z={pz2}"); // 4. Player can't walk out through the side wall from inside sim.player.pos = Vec3::new(0.0, 0.0, 0.0); sim.player.yaw = std::f32::consts::FRAC_PI_2; // +X for _ in 0..240 { sim.step_fps_player(1.0 / 60.0, &walk, &bvh); } assert!(sim.player.pos.x < 3.7, "Player must stay inside side wall, x={}", sim.player.pos.x); } #[test] fn test_csg_subtraction_destruction_opens_walkable_and_shootable_breach() { use project_cold_water::modding::blueprint::{ BlueprintPayload, MapBlueprint, MapModSpawn, MapTerrainBase, SCHEMA_VERSION, }; use project_cold_water::modding::csg::CsgShape; use project_cold_water::sim::player::FpsInput; use project_cold_water::sim::Simulation; let wall_parts = vec![CsgNode::new_primitive( 1, "Solid Concrete Wall", CsgOp::Union, PrimitiveKind::Box, [0.0, 1.5, 0.0], [0.0; 3], [8.0, 3.0, 0.8], MaterialId::Concrete, )]; let map_bp = AssetBlueprint { schema_version: SCHEMA_VERSION, id: "destruction_breach_test".into(), name: "Destruction Breach Test".into(), author: "ColdWater".into(), payload: BlueprintPayload::Map(MapBlueprint { base_terrain: MapTerrainBase::FlatSandbox { half_extent: 120.0, material: MaterialId::WinterMud, }, nodes: vec![CsgNode { id: 1, name: "Wall".into(), op: CsgOp::Union, shape: CsgShape::Group(wall_parts), pos: [0.0, 0.0, 0.0], rot_deg: [0.0; 3], scale: [1.0; 3], material: MaterialId::Concrete, override_stamp_material: false, visible: true, modifiers: Vec::new(), }], spawns: vec![ MapModSpawn { name: "Fed".into(), faction: Faction::Federal, pos: [0.0, 0.0, -20.0], ..Default::default() }, MapModSpawn { name: "Mil".into(), faction: Faction::Militia, pos: [0.0, 0.0, 20.0], ..Default::default() }, ], objectives: Vec::new(), vehicles: Vec::new(), named_curves: Vec::new(), script_hooks: Vec::new(), mission_defaults: Default::default(), }), }; let reg = ModRegistry::default(); let world = reg .build_world_from_map(&map_bp) .expect("build destructible wall map"); assert!(!world.destructible.is_empty(), "CSG map wall must register as destructible"); let bvh_before = AcousticBvh::build(world.acoustic_triangles.clone()); assert!( bvh_before .raycast(Vec3::new(0.0, 1.2, -5.0), Vec3::Z, 10.0) .is_some(), "Solid wall must block projectile ray before destruction" ); let mut sim = Simulation::new(&world); let s = sim.soldiers[0].clone(); sim.player.deploy_into_soldier(&s); let walk = FpsInput { move_fwd: 1.0, ..Default::default() }; sim.player.pos = Vec3::new(0.0, 0.0, -5.0); sim.player.yaw = std::f32::consts::PI; // flat_forward = +Z sim.player.pitch = 0.0; for _ in 0..240 { sim.step_fps_player(1.0 / 60.0, &walk, &bvh_before); } assert!( sim.player.pos.z < -0.2, "Solid wall must block player before cratering (z={})", sim.player.pos.z ); // Apply CSG crater right through center of wall at (0, 1.2, 0) assert!( sim.apply_destruction_crater(Vec3::new(0.0, 1.2, 0.0), 1.85, 42), "Explosion crater must carve overlapping CSG wall" ); assert!( sim.take_world_geometry_dirty(), "Applying crater must mark world geometry dirty for GPU/BVH rebuild" ); let bvh_after = AcousticBvh::build(sim.acoustic_triangles.clone()); assert!( bvh_after .raycast(Vec3::new(0.0, 1.2, -5.0), Vec3::Z, 10.0) .is_none(), "Projectile ray must pass cleanly through blasted breach" ); sim.player.pos = Vec3::new(0.0, 0.0, -5.0); for _ in 0..240 { sim.step_fps_player(1.0 / 60.0, &walk, &bvh_after); } assert!( sim.player.pos.z > 1.5, "Player must walk cleanly through blasted wall breach (z={})", sim.player.pos.z ); } #[test] fn test_configurable_turret_blueprint_roundtrip() { use project_cold_water::modding::blueprint::{ BlueprintPayload, ProjectileGuidance, TurretWeaponKind, TurretWeaponSpec, VehicleBlueprint, VehicleLocomotion, }; let mut bp = starter_vehicle_blueprint(); if let BlueprintPayload::Vehicle(ref mut vb) = bp.payload { vb.locomotion = VehicleLocomotion::Helicopter; vb.rotor_radius = 7.4; vb.lift_power = 21.0; vb.max_climb_rate = 13.5; vb.turret_primary = TurretWeaponSpec::preset(TurretWeaponKind::Autocannon30mm); vb.turret_secondary = Some(TurretWeaponSpec::preset(TurretWeaponKind::TowAtgmLauncher)); } let json = serde_json::to_string_pretty(&bp).expect("serialize vehicle blueprint"); let decoded: AssetBlueprint = serde_json::from_str(&json).expect("deserialize vehicle blueprint"); let BlueprintPayload::Vehicle(dv) = decoded.payload else { panic!("Expected vehicle payload"); }; assert_eq!(dv.locomotion, VehicleLocomotion::Helicopter); assert!((dv.rotor_radius - 7.4).abs() < 1e-4); assert_eq!(dv.turret_primary.kind, TurretWeaponKind::Autocannon30mm); let sec = dv.turret_secondary.expect("secondary weapon preserved"); assert_eq!(sec.kind, TurretWeaponKind::TowAtgmLauncher); assert_eq!(sec.guidance, ProjectileGuidance::SaclosWireGuided); // Verify legacy VehicleBlueprint JSON missing new fields deserializes with safe defaults let legacy_json = serde_json::to_value(&bp).unwrap(); let mut legacy_map = legacy_json.as_object().unwrap().clone(); let payload_obj = legacy_map .get_mut("payload") .unwrap() .as_object_mut() .unwrap() .get_mut("Vehicle") .unwrap() .as_object_mut() .unwrap(); for k in [ "locomotion", "turret_primary", "turret_secondary", "turret_optic_fov_deg", "rotor_mount_local", "tail_rotor_mount_local", "rotor_radius", "lift_power", "max_climb_rate", ] { payload_obj.remove(k); } let hydrated: VehicleBlueprint = serde_json::from_value(legacy_map["payload"]["Vehicle"].clone()) .expect("legacy blueprint must hydrate via serde defaults"); assert_eq!(hydrated.locomotion, VehicleLocomotion::Wheeled); assert_eq!(hydrated.turret_primary.kind, TurretWeaponKind::HeavyMg14_5mm); } #[test] fn test_tracked_vehicle_blueprint_roundtrip_and_bmp2_amphibious_spec() { use project_cold_water::modding::blueprint::{ BlueprintPayload, TurretWeaponKind, VehicleBlueprint, VehicleLocomotion, }; use project_cold_water::world::VehicleKind; let mut t72_vb = VehicleBlueprint::from_archetype(VehicleKind::T72B); assert_eq!(t72_vb.locomotion, VehicleLocomotion::Tracked); assert_eq!(t72_vb.turret_primary.kind, TurretWeaponKind::TankCannon125mm); assert_eq!(t72_vb.roadwheel_count, 6); t72_vb.track_half_width = 1.66; t72_vb.track_length = 5.45; t72_vb.track_height = 0.88; t72_vb.roadwheel_count = 7; t72_vb.pivot_turn_rate = 1.42; let mut bp = starter_vehicle_blueprint(); bp.payload = BlueprintPayload::Vehicle(t72_vb); let json = serde_json::to_string_pretty(&bp).expect("serialize tracked vehicle blueprint"); let decoded: AssetBlueprint = serde_json::from_str(&json).expect("deserialize tracked vehicle blueprint"); let BlueprintPayload::Vehicle(dv) = decoded.payload else { panic!("Expected vehicle payload"); }; assert_eq!(dv.locomotion, VehicleLocomotion::Tracked); assert_eq!(dv.turret_primary.kind, TurretWeaponKind::TankCannon125mm); assert!((dv.track_half_width - 1.66).abs() < 1e-4); assert!((dv.track_length - 5.45).abs() < 1e-4); assert!((dv.track_height - 0.88).abs() < 1e-4); assert_eq!(dv.roadwheel_count, 7); assert!((dv.pivot_turn_rate - 1.42).abs() < 1e-4); // Legacy JSON missing the 5 tracked fields must hydrate via serde defaults let mut val = serde_json::to_value(&bp).unwrap(); let vobj = val .as_object_mut() .unwrap() .get_mut("payload") .unwrap() .as_object_mut() .unwrap() .get_mut("Vehicle") .unwrap() .as_object_mut() .unwrap(); for k in [ "track_half_width", "track_length", "track_height", "roadwheel_count", "pivot_turn_rate", ] { vobj.remove(k); } let hydrated: VehicleBlueprint = serde_json::from_value(val["payload"]["Vehicle"].clone()) .expect("legacy tracked blueprint must hydrate track defaults"); assert!(hydrated.track_half_width > 1.0); assert!(hydrated.track_length > 3.0); assert!(hydrated.track_height > 0.5); assert!(hydrated.roadwheel_count >= 5); assert!(hydrated.pivot_turn_rate > 0.5); let bmp2 = VehicleBlueprint::from_archetype(VehicleKind::Bmp2); assert_eq!(bmp2.locomotion, VehicleLocomotion::Tracked); assert!(bmp2.is_amphibious); assert_eq!(bmp2.turret_primary.kind, TurretWeaponKind::Autocannon30mm); assert_eq!( bmp2.turret_secondary.as_ref().map(|s| s.kind), Some(TurretWeaponKind::TowAtgmLauncher) ); let mtlb = VehicleBlueprint::from_archetype(VehicleKind::MtLb); assert_eq!(mtlb.locomotion, VehicleLocomotion::Tracked); assert!(mtlb.is_amphibious); } #[test] fn test_csg_destruction_many_repeated_holes_on_same_wall_and_building() { use project_cold_water::audio::bvh::AcousticBvh; use project_cold_water::modding::csg::{polygons_to_static_world, CsgNode, CsgOp, PrimitiveKind}; use project_cold_water::modding::destruction::{DestructibleStructure, DestructibleWorld}; use project_cold_water::world::structures::StructureBuilder; use project_cold_water::world::{HeightQuery, StaticVertex}; struct ZeroHeight; impl HeightQuery for ZeroHeight { fn height_at(&self, _x: f32, _z: f32) -> f32 { 0.0 } fn river_center_x(&self, _z: f32) -> f32 { 1000.0 } fn water_level(&self) -> f32 { -10.0 } } // Part A: 25 repeated + overlapping craters carved into ONE single 18m x 4m concrete wall let wall_node = CsgNode::new_primitive( 1, "LongWall", CsgOp::Union, PrimitiveKind::Box, [0.0, 2.0, 0.0], [0.0, 0.0, 0.0], [18.0, 4.0, 0.5], MaterialId::Concrete, ); let wall_polys = project_cold_water::modding::csg::evaluate_csg_tree(&[wall_node]); let ds = DestructibleStructure::from_polygons(1, wall_polys, 1.0).expect("wall structure"); let mut dw = DestructibleWorld { structures: vec![ds], ..Default::default() }; let mut carved_centers = Vec::new(); for i in 0..25usize { let x = -7.8 + (i as f32) * 0.65; let y = if i % 2 == 0 { 1.35 } else { 2.55 }; let center = Vec3::new(x, y, 0.0); let dirty = dw.apply_crater(center, 0.72, 1000 + i as u64); assert!( dirty.is_some(), "Crater #{i} at {center:?} must keep carving into same wall (polys={})", dw.structures[0].polys.len() ); assert!( dw.structures[0].polys.len() < 2000, "CSG polygon count must remain bounded without BSP blowup (after #{i}: {})", dw.structures[0].polys.len() ); carved_centers.push(center); } let mut verts: Vec = Vec::new(); let mut idxs: Vec = Vec::new(); let mut tris = Vec::new(); dw.rebuild_buffers(&mut verts, &mut idxs, &mut tris); let bvh = AcousticBvh::build(tris); for (i, &c) in carved_centers.iter().enumerate() { let ray_origin = Vec3::new(c.x, c.y, -4.0); assert!( bvh.raycast(ray_origin, Vec3::Z, 8.0).is_none(), "Projectile ray through hole #{i} at {c:?} must pass unobstructed" ); } // Part B: Full 3-story Khrushchyovka subdivided per panel handles 30+ holes cleanly let hq = ZeroHeight; let mut s_verts = Vec::new(); let mut s_idxs = Vec::new(); let mut s_tris = Vec::new(); let mut covers = Vec::new(); let mut nav_obs = Vec::new(); let mut nav_bridges = Vec::new(); let mut sb = StructureBuilder { vertices: &mut s_verts, indices: &mut s_idxs, acoustic: &mut s_tris, cover_nodes: &mut covers, nav_obstacles: &mut nav_obs, nav_bridges: &mut nav_bridges, height_query: &hq, destructibles: Vec::new(), active_destructible: None, }; sb.add_khrushchyovka(Vec3::ZERO, 0.0, 3, false); let mut bldg_dw = sb.finish_destructible_world(); assert!( bldg_dw.structures.len() >= 15, "Building must be decomposed into per-panel destructible pieces (got {})", bldg_dw.structures.len() ); let mut shots_hit = 0usize; let initial_aabbs: Vec<_> = bldg_dw.structures.iter().map(|s| s.aabb).collect(); for i in 0..30usize { let panel_aabb = initial_aabbs[(i * 3) % initial_aabbs.len()]; let frac = 0.25 + ((i % 3) as f32) * 0.25; let hit_pt = panel_aabb.min.lerp(panel_aabb.max, frac); if bldg_dw.apply_crater(hit_pt, 1.15, 5000 + i as u64).is_some() { shots_hit += 1; } } assert!( shots_hit >= 24, "At least 24/30 shots across multi-story building must keep carving holes (got {shots_hit})" ); let _ = polygons_to_static_world; } #[test] fn test_multibarrel_weapon_blueprint_roundtrip_and_legacy_defaults() { use project_cold_water::modding::blueprint::{ BarrelFireMode, BarrelLayout, BlueprintPayload, TurretWeaponKind, TurretWeaponSpec, VehicleBlueprint, VehicleLocomotion, }; use project_cold_water::world::VehicleKind; let mut bmpt = VehicleBlueprint::from_archetype(VehicleKind::BmptTerminator); assert_eq!(bmpt.locomotion, VehicleLocomotion::Tracked); assert_eq!(bmpt.turret_primary.kind, TurretWeaponKind::TwinAutocannon30mm); assert_eq!(bmpt.turret_primary.barrel_count, 2); assert_eq!(bmpt.turret_primary.barrel_fire_mode, BarrelFireMode::Alternating); let sec = bmpt.turret_secondary.as_ref().expect("BMPT quad ATGM"); assert_eq!(sec.kind, TurretWeaponKind::AtakaQuadAtgm); assert_eq!(sec.barrel_count, 4); assert_eq!(sec.barrel_layout, BarrelLayout::QuadGrid); bmpt.turret_primary.barrel_count = 6; bmpt.turret_primary.barrel_layout = BarrelLayout::Rotary; bmpt.turret_primary.barrel_fire_mode = BarrelFireMode::Salvo; bmpt.turret_primary.barrel_spacing = 0.64; let mut bp = starter_vehicle_blueprint(); bp.payload = BlueprintPayload::Vehicle(bmpt); let json = serde_json::to_string_pretty(&bp).expect("serialize multi-barrel vehicle"); let decoded: AssetBlueprint = serde_json::from_str(&json).expect("deserialize multi-barrel vehicle"); let BlueprintPayload::Vehicle(dv) = decoded.payload else { panic!("Expected vehicle payload"); }; assert_eq!(dv.turret_primary.barrel_count, 6); assert_eq!(dv.turret_primary.barrel_layout, BarrelLayout::Rotary); assert_eq!(dv.turret_primary.barrel_fire_mode, BarrelFireMode::Salvo); assert!((dv.turret_primary.barrel_spacing - 0.64).abs() < 1e-4); // Legacy TurretWeaponSpec JSON missing multi-barrel fields must hydrate with safe 1-barrel defaults let mut val = serde_json::to_value(TurretWeaponSpec::preset(TurretWeaponKind::TwinAutocannon23mm)) .unwrap(); let obj = val.as_object_mut().unwrap(); for k in [ "barrel_count", "barrel_fire_mode", "barrel_layout", "barrel_spacing", ] { obj.remove(k); } let hydrated: TurretWeaponSpec = serde_json::from_value(val).expect("legacy turret spec must hydrate defaults"); assert_eq!(hydrated.barrel_count, 1); assert_eq!(hydrated.barrel_fire_mode, BarrelFireMode::Alternating); assert_eq!(hydrated.barrel_layout, BarrelLayout::Horizontal); assert_eq!(hydrated.barrel_spacing, 0.0); } #[test] fn test_csg_no_midair_collision_or_floating_holes_after_repeated_overlapping_shots() { use project_cold_water::audio::bvh::AcousticBvh; use project_cold_water::modding::csg::{evaluate_csg_tree, CsgNode, CsgOp, PrimitiveKind}; use project_cold_water::modding::destruction::{DestructibleStructure, DestructibleWorld}; let wall_node = CsgNode::new_primitive( 1, "TestWallPanel", CsgOp::Union, PrimitiveKind::Box, [0.0, 1.5, 0.0], [0.0, 0.0, 0.0], [4.0, 3.0, 0.36], MaterialId::Concrete, ); let wall_polys = evaluate_csg_tree(&[wall_node]); let ds = DestructibleStructure::from_box_polygons(1, wall_polys, 1.0).expect("box panel"); let mut dw = DestructibleWorld { structures: vec![ds], ..Default::default() }; let mut bvh = AcousticBvh::build_split(Vec::new(), &dw); // Blast primary hole #1 right through the center assert!(dw.apply_crater(Vec3::new(0.0, 1.5, 0.18), 1.05, 101).is_some()); bvh = bvh.with_updated_destructibles(&dw); // Firing a smaller 23mm/30mm round directly into empty air inside Hole #1 must do nothing let air_shot = dw.apply_crater(Vec3::new(0.0, 1.5, 0.0), 0.55, 202); assert!( air_shot.is_none(), "Round aimed through an already-carved hole must not carve mid-air geometry" ); // Now blast 10 overlapping craters right around the rim of Hole #1 let rim_shots = [ (Vec3::new(0.55, 1.5, 0.18), 0.62, 301), (Vec3::new(-0.55, 1.5, -0.18), 0.62, 302), (Vec3::new(0.0, 2.05, 0.18), 0.58, 303), (Vec3::new(0.0, 0.95, -0.18), 0.58, 304), (Vec3::new(0.45, 1.90, 0.0), 0.52, 305), (Vec3::new(-0.45, 1.10, 0.0), 0.52, 306), (Vec3::new(0.75, 1.5, 0.0), 0.55, 307), (Vec3::new(-0.75, 1.5, 0.0), 0.55, 308), (Vec3::new(0.25, 1.5, 0.18), 0.45, 309), (Vec3::new(-0.25, 1.5, -0.18), 0.45, 310), ]; for &(pos, rad, seed) in &rim_shots { let _ = dw.apply_crater(pos, rad, seed); bvh = bvh.with_updated_destructibles(&dw); } // Invariant 1: ZERO vertices may leak outside the original [-2..2, 0..3, -0.18..0.18] wall box for p in &dw.structures[0].polys { for &v in &p.verts { assert!( v.x.abs() <= 2.002 && v.y >= -0.002 && v.y <= 3.002 && v.z.abs() <= 0.182, "Leaked vertex {v:?} outside original wall bounds" ); } } // Invariant 2: 5x5 ray grid through the breached interior must pass cleanly from BOTH sides for ix in -2..=2 { for iy in -2..=2 { let x = (ix as f32) * 0.20; let y = 1.5 + (iy as f32) * 0.16; assert!( bvh.raycast(Vec3::new(x, y, -4.0), Vec3::Z, 8.0).is_none(), "Mid-air +Z ray hit invisible debris at ({x}, {y})" ); assert!( bvh.raycast(Vec3::new(x, y, 4.0), -Vec3::Z, 8.0).is_none(), "Mid-air -Z ray hit invisible debris at ({x}, {y})" ); } } } #[test] fn test_map_editor_gizmo_moves_spawns_objectives_and_vehicles() { use glam::Vec2; use project_cold_water::camera::CameraController; use project_cold_water::modding::blueprint::{ BlueprintPayload, MapModVehiclePlacement, }; use project_cold_water::modding::studio::{ AssetStudioState, GizmoMode, StudioAnchor, StudioMode, }; use project_cold_water::world::{Faction, VehicleKind}; let mut studio = AssetStudioState::default(); studio.load_starter(StudioMode::Map); if let BlueprintPayload::Map(ref mut mb) = studio.blueprint.payload { mb.vehicles.push(MapModVehiclePlacement { name: "BTR-80A Support".into(), stock_kind: VehicleKind::Btr80A, custom_vehicle_id: None, faction: Faction::Federal, pos: [-12.0, 0.0, 6.0], yaw_deg: 15.0, crewed: false, ..Default::default() }); } let markers = studio.anchor_markers(); assert!(markers .iter() .any(|(a, _, _, _)| matches!(a, StudioAnchor::MapSpawn(0)))); assert!(markers .iter() .any(|(a, _, _, _)| matches!(a, StudioAnchor::MapObjective(0)))); assert!(markers .iter() .any(|(a, _, _, _)| matches!(a, StudioAnchor::MapVehicle(0)))); let screen = Vec2::new(1280.0, 720.0); let mut cam = CameraController::new(); // 1. Screen-pick MapSpawn(0) & Translate along +X + Undo studio.select_anchor(StudioAnchor::MapSpawn(0)); let sp0_orig = studio.selected_gizmo_origin().expect("spawn 0 origin"); studio.focus_world_point(sp0_orig); studio.apply_to_camera(&mut cam); let sp0_2d = AssetStudioState::project_world_point(sp0_orig, screen, &cam).unwrap(); studio.select_node(None); assert!(studio.pick_node_at_screen(sp0_2d, screen, &cam)); assert_eq!(studio.selected_anchor, Some(StudioAnchor::MapSpawn(0))); let sp_len = studio.gizmo_world_length(&cam, sp0_orig); let sp_tip_x = AssetStudioState::project_world_point(sp0_orig + Vec3::X * sp_len, screen, &cam).unwrap(); assert!(studio.begin_gizmo_drag(sp_tip_x, screen, 1.0, &cam)); let sp_drag_x = AssetStudioState::project_world_point(sp0_orig + Vec3::X * (sp_len + 4.5), screen, &cam) .unwrap(); studio.update_gizmo_drag(sp_drag_x, screen, 1.0, &cam, false); studio.end_gizmo_drag(); if let BlueprintPayload::Map(ref mb) = studio.blueprint.payload { assert!( mb.spawns[0].pos[0] > sp0_orig.x + 2.0, "Spawn 0 must translate +X via 3D gizmo (got {})", mb.spawns[0].pos[0] ); } studio.undo(); if let BlueprintPayload::Map(ref mb) = studio.blueprint.payload { assert!( (mb.spawns[0].pos[0] - sp0_orig.x).abs() < 1e-3, "Undo must restore Spawn 0 X position" ); } // 2. Objective Translate & Scale (Radius) studio.select_anchor(StudioAnchor::MapObjective(0)); let ob0_orig = studio.selected_gizmo_origin().expect("objective 0 origin"); studio.focus_world_point(ob0_orig); studio.apply_to_camera(&mut cam); let ob_len = studio.gizmo_world_length(&cam, ob0_orig); let ob_tip_z = AssetStudioState::project_world_point(ob0_orig + Vec3::Z * ob_len, screen, &cam).unwrap(); assert!(studio.begin_gizmo_drag(ob_tip_z, screen, 1.0, &cam)); let ob_drag_z = AssetStudioState::project_world_point(ob0_orig + Vec3::Z * (ob_len + 3.2), screen, &cam) .unwrap(); studio.update_gizmo_drag(ob_drag_z, screen, 1.0, &cam, false); studio.end_gizmo_drag(); if let BlueprintPayload::Map(ref mb) = studio.blueprint.payload { assert!(mb.objectives[0].pos[2] > ob0_orig.z + 1.5); } studio.gizmo_mode = GizmoMode::Scale; let ob_orig2 = studio.selected_gizmo_origin().unwrap(); studio.focus_world_point(ob_orig2); studio.apply_to_camera(&mut cam); let start_rad = match &studio.blueprint.payload { BlueprintPayload::Map(mb) => mb.objectives[0].radius, _ => 0.0, }; let ob_len2 = studio.gizmo_world_length(&cam, ob_orig2); let ob_scale_x = AssetStudioState::project_world_point(ob_orig2 + Vec3::X * ob_len2, screen, &cam).unwrap(); assert!(studio.begin_gizmo_drag(ob_scale_x, screen, 1.0, &cam)); let ob_scale_drag = AssetStudioState::project_world_point(ob_orig2 + Vec3::X * (ob_len2 + 5.0), screen, &cam) .unwrap(); studio.update_gizmo_drag(ob_scale_drag, screen, 1.0, &cam, false); studio.end_gizmo_drag(); if let BlueprintPayload::Map(ref mb) = studio.blueprint.payload { assert!( mb.objectives[0].radius > start_rad + 2.0 && mb.objectives[0].radius <= 60.0, "Objective scale gizmo must grow radius (start={start_rad}, now={})", mb.objectives[0].radius ); } // 3. Vehicle Translate & Rotate (Yaw) studio.gizmo_mode = GizmoMode::Translate; studio.select_anchor(StudioAnchor::MapVehicle(0)); let veh_orig = studio.selected_gizmo_origin().expect("vehicle 0 origin"); studio.focus_world_point(veh_orig); studio.apply_to_camera(&mut cam); let v_len = studio.gizmo_world_length(&cam, veh_orig); let v_tip_x = AssetStudioState::project_world_point(veh_orig + Vec3::X * v_len, screen, &cam).unwrap(); assert!(studio.begin_gizmo_drag(v_tip_x, screen, 1.0, &cam)); let v_drag_x = AssetStudioState::project_world_point(veh_orig + Vec3::X * (v_len + 3.0), screen, &cam) .unwrap(); studio.update_gizmo_drag(v_drag_x, screen, 1.0, &cam, false); studio.end_gizmo_drag(); if let BlueprintPayload::Map(ref mb) = studio.blueprint.payload { assert!(mb.vehicles[0].pos[0] > veh_orig.x + 1.0); } studio.gizmo_mode = GizmoMode::Rotate; let veh_orig2 = studio.selected_gizmo_origin().unwrap(); studio.focus_world_point(veh_orig2); studio.apply_to_camera(&mut cam); let ring_r = studio.gizmo_world_length(&cam, veh_orig2) * 0.85; let start_yaw = match &studio.blueprint.payload { BlueprintPayload::Map(mb) => mb.vehicles[0].yaw_deg, _ => 0.0, }; let ring_pt = AssetStudioState::project_world_point(veh_orig2 + Vec3::X * ring_r, screen, &cam).unwrap(); assert!(studio.begin_gizmo_drag(ring_pt, screen, 1.0, &cam)); let ring_drag = AssetStudioState::project_world_point(veh_orig2 + Vec3::Z * ring_r, screen, &cam).unwrap(); studio.update_gizmo_drag(ring_drag, screen, 1.0, &cam, false); studio.end_gizmo_drag(); if let BlueprintPayload::Map(ref mb) = studio.blueprint.payload { assert!( (mb.vehicles[0].yaw_deg - start_yaw).abs() > 5.0, "Vehicle Rotate gizmo must rotate yaw_deg (before={start_yaw}, after={})", mb.vehicles[0].yaw_deg ); } // Verify 3D overlay lines generate cleanly for all entities and bounds cleanup on delete let overlay = studio.build_overlay_lines(); assert!(!overlay.is_empty()); for (a, b, col) in overlay { assert!(a.is_finite() && b.is_finite()); assert!(col.iter().all(|c| c.is_finite())); } if let BlueprintPayload::Map(ref mut mb) = studio.blueprint.payload { mb.vehicles.clear(); } studio.validate_anchor(); assert_eq!(studio.selected_anchor, None); } #[test] fn array_linear_radial_grid_and_caps() { use glam::Vec3; use project_cold_water::modding::csg::{CsgNode, CsgOp, PrimitiveKind}; use project_cold_water::modding::modifiers::{ evaluate_node_modifiers, ArrayMode, ModifierEvalContext, ModifierKind, NodeModifier, MAX_MODIFIER_INSTANCES, }; let ctx = ModifierEvalContext::default(); let bounds = Vec3::new(2.0, 1.0, 1.0); // 1. Linear with constant + relative bounds offset + huge count safety clamp let mut node = CsgNode::new_primitive( 1, "Barrier", CsgOp::Union, PrimitiveKind::Box, [0.0, 0.5, 0.0], [0.0; 3], [1.0, 1.0, 1.0], MaterialId::Concrete, ); node.modifiers.push(NodeModifier { id: 1, name: "Lin".into(), enabled: true, kind: ModifierKind::Array { mode: ArrayMode::Linear, count: 5, offset: [1.0, 0.0, 0.0], relative_offset: [1.0, 0.0, 0.0], step_rot_deg: [0.0, 0.0, 0.0], step_scale: [0.0, 0.0, 0.0], radial_radius: 5.0, radial_arc_deg: 360.0, radial_align: true, grid_count_z: 1, grid_spacing_z: 1.0, snap_to_terrain: false, }, }); let res = evaluate_node_modifiers(&node, bounds, &ctx); assert!(res.errors.is_empty()); assert_eq!(res.instances.len(), 5); // step = offset(1.0) + relative(1.0) * bounds.x(2.0) = 3.0m assert!((res.instances[0].pos.x - 0.0).abs() < 1e-4); assert!((res.instances[4].pos.x - 12.0).abs() < 1e-4); // Count > MAX_MODIFIER_INSTANCES is safely clamped if let ModifierKind::Array { ref mut count, .. } = node.modifiers[0].kind { *count = 500; } let capped = evaluate_node_modifiers(&node, bounds, &ctx); assert_eq!(capped.instances.len(), MAX_MODIFIER_INSTANCES); // 2. Radial array around ring node.modifiers[0].kind = ModifierKind::Array { mode: ArrayMode::Radial, count: 8, offset: [0.0; 3], relative_offset: [0.0; 3], step_rot_deg: [0.0; 3], step_scale: [0.0; 3], radial_radius: 10.0, radial_arc_deg: 360.0, radial_align: true, grid_count_z: 1, grid_spacing_z: 1.0, snap_to_terrain: false, }; let rad = evaluate_node_modifiers(&node, bounds, &ctx); assert_eq!(rad.instances.len(), 8); for inst in &rad.instances { let d = Vec3::new(inst.pos.x, 0.0, inst.pos.z).length(); assert!((d - 10.0).abs() < 1e-3, "Radial distance must equal 10.0m, got {d}"); } assert!((rad.instances[2].rot_deg.y - 90.0).abs() < 1e-3); // 3. 2D Grid array node.modifiers[0].kind = ModifierKind::Array { mode: ArrayMode::Grid, count: 4, offset: [3.0, 0.0, 0.0], relative_offset: [0.0; 3], step_rot_deg: [0.0; 3], step_scale: [0.0; 3], radial_radius: 5.0, radial_arc_deg: 360.0, radial_align: true, grid_count_z: 3, grid_spacing_z: 5.0, snap_to_terrain: false, }; let grid = evaluate_node_modifiers(&node, bounds, &ctx); assert_eq!(grid.instances.len(), 12); assert!((grid.instances[11].pos.x - 9.0).abs() < 1e-3); assert!((grid.instances[11].pos.z - 10.0).abs() < 1e-3); } #[test] fn array_plus_curve_catmull_rom_closed_loop_and_gizmo_undo() { use glam::Vec2; use project_cold_water::camera::CameraController; use project_cold_water::modding::blueprint::{BlueprintPayload, MapTerrainBase}; use project_cold_water::modding::csg::{CsgNode, CsgOp, PrimitiveKind}; use project_cold_water::modding::modifiers::{ evaluate_node_modifiers, CurveForwardAxis, CurveInterpolation, CurvePlacementMode, MapNamedCurve, ModifierEvalContext, ModifierKind, NodeModifier, }; use project_cold_water::modding::studio::{AssetStudioState, GizmoMode, StudioAnchor, StudioMode}; // 1. Standalone Curve in FixedSpacing mode auto-expands copies along spline let mut node = CsgNode::new_primitive( 1, "Post", CsgOp::Union, PrimitiveKind::Box, [0.0, 0.0, 0.0], [0.0; 3], [0.5, 1.5, 0.5], MaterialId::WoodFurniture, ); node.modifiers.push(NodeModifier { id: 1, name: "RoadCurve".into(), enabled: true, kind: ModifierKind::Curve { points: vec![[0.0, 0.0, 0.0], [10.0, 0.0, 5.0], [20.0, 0.0, 0.0]], shared_curve_id: None, interpolation: CurveInterpolation::CatmullRom, closed_loop: false, placement: CurvePlacementMode::FixedSpacing, spacing_m: 3.0, follow_tangent: true, forward_axis: CurveForwardAxis::PosZ, bank_pitch: false, lateral_offset: 0.0, vertical_offset: 0.0, snap_to_terrain: false, align_to_slope: false, }, }); let res_standalone = evaluate_node_modifiers(&node, Vec3::ONE, &ModifierEvalContext::default()); assert!( res_standalone.instances.len() >= 7 && res_standalone.instances.len() <= 10, "FixedSpacing standalone curve should auto-place posts along ~22m path, got {}", res_standalone.instances.len() ); assert!( (res_standalone.instances[0].rot_deg.y - res_standalone.instances[res_standalone.instances.len() - 1].rot_deg.y).abs() > 10.0, "Tangent yaw should curve across spline" ); // 2. Array + Shared MapNamedCurve closed loop let mut wall_node = node.clone(); wall_node.modifiers = vec![ NodeModifier::array_preset(10, false), NodeModifier { id: 11, name: "SharedPerimeter".into(), enabled: true, kind: ModifierKind::Curve { points: vec![[0.0; 3], [5.0, 0.0, 0.0]], shared_curve_id: Some("perimeter".into()), interpolation: CurveInterpolation::CatmullRom, closed_loop: false, placement: CurvePlacementMode::FitCount, spacing_m: 4.0, follow_tangent: true, forward_axis: CurveForwardAxis::PosX, bank_pitch: false, lateral_offset: 1.5, vertical_offset: 0.0, snap_to_terrain: false, align_to_slope: false, }, }, ]; if let ModifierKind::Array { ref mut count, .. } = wall_node.modifiers[0].kind { *count = 8; } let shared = vec![MapNamedCurve { id: "perimeter".into(), name: "Perimeter".into(), points: vec![ [-10.0, 0.0, -10.0], [10.0, 0.0, -10.0], [10.0, 0.0, 10.0], [-10.0, 0.0, 10.0], ], interpolation: CurveInterpolation::Polyline, closed_loop: true, }]; let shared_ctx = ModifierEvalContext { height_query: None, shared_curves: &shared, }; let shared_res = evaluate_node_modifiers(&wall_node, Vec3::ONE, &shared_ctx); assert_eq!(shared_res.instances.len(), 8); // 3. Asset Studio 3D CurveControlPoint gizmo drag + Undo rollback let mut studio = AssetStudioState::default(); studio.switch_new_mode(StudioMode::Map); if let BlueprintPayload::Map(ref mut mb) = studio.blueprint.payload { mb.base_terrain = MapTerrainBase::FlatSandbox { half_extent: 120.0, material: MaterialId::WinterMud, }; } studio.add_primitive( "Curved Barrier", PrimitiveKind::Box, CsgOp::Union, MaterialId::Concrete, ); let arr_md = NodeModifier::array_preset(studio.alloc_modifier_id(), false); let crv_md = NodeModifier::curve_preset(studio.alloc_modifier_id(), false); let crv_id = crv_md.id; studio.add_modifier_to_selected(arr_md); studio.add_modifier_to_selected(crv_md); let sel_id = studio.selected_node_id.expect("selected node"); let anchor = StudioAnchor::CurveControlPoint { node_id: sel_id, modifier_id: crv_id, point_idx: 1, }; studio.select_anchor(anchor); assert_eq!(studio.selected_node_id, Some(sel_id), "Curve point selection must keep node selected"); let orig_pt = studio.selected_gizmo_origin().expect("curve pt origin"); studio.gizmo_mode = GizmoMode::Translate; studio.focus_world_point(orig_pt); let mut cam = CameraController::new(); studio.apply_to_camera(&mut cam); let screen = Vec2::new(1280.0, 720.0); let len = studio.gizmo_world_length(&cam, orig_pt); let tip_x = AssetStudioState::project_world_point(orig_pt + Vec3::X * len, screen, &cam).unwrap(); assert!(studio.begin_gizmo_drag(tip_x, screen, 1.0, &cam)); let drag_x = AssetStudioState::project_world_point(orig_pt + Vec3::X * (len + 4.5), screen, &cam).unwrap(); studio.update_gizmo_drag(drag_x, screen, 1.0, &cam, false); studio.end_gizmo_drag(); let moved_pt = studio.selected_gizmo_origin().unwrap(); assert!(moved_pt.x > orig_pt.x + 2.0, "Curve PT 2 must move along +X via 3D gizmo"); // Overlay lines include curve spline cleanly let overlay = studio.build_overlay_lines(); assert!(overlay.iter().all(|(a, b, c)| a.is_finite() && b.is_finite() && c.iter().all(|x| x.is_finite()))); // Undo restores control point position studio.undo(); let restored_pt = studio.anchor_world_pos(anchor).unwrap(); assert!((restored_pt.x - orig_pt.x).abs() < 1e-3, "Undo must restore Curve PT 2 X position"); } #[test] fn randomize_transforms_deterministic_seed_uniform_scale_and_skip() { use project_cold_water::modding::csg::{CsgNode, CsgOp, PrimitiveKind}; use project_cold_water::modding::modifiers::{ evaluate_node_modifiers, ArrayMode, ModifierEvalContext, ModifierKind, NodeModifier, }; let ctx = ModifierEvalContext::default(); let mut node = CsgNode::new_primitive( 7, "Tree", CsgOp::Union, PrimitiveKind::Box, [0.0; 3], [0.0; 3], [1.0; 3], MaterialId::WinterPine, ); node.modifiers.push(NodeModifier { id: 1, name: "Row".into(), enabled: true, kind: ModifierKind::Array { mode: ArrayMode::Linear, count: 20, offset: [4.0, 0.0, 0.0], relative_offset: [0.0; 3], step_rot_deg: [0.0; 3], step_scale: [0.0; 3], radial_radius: 5.0, radial_arc_deg: 360.0, radial_align: true, grid_count_z: 1, grid_spacing_z: 1.0, snap_to_terrain: false, }, }); node.modifiers.push(NodeModifier { id: 2, name: "Jitter".into(), enabled: true, kind: ModifierKind::RandomizeTransform { seed: 4242, pos_min: [-1.5, 0.0, -1.5], pos_max: [1.5, 0.5, 1.5], rot_min_deg: [0.0, -180.0, 0.0], rot_max_deg: [0.0, 180.0, 0.0], scale_min: [0.7, 0.7, 0.7], scale_max: [1.4, 1.4, 1.4], uniform_scale: true, skip_chance: 0.35, snap_to_terrain: false, }, }); let run1 = evaluate_node_modifiers(&node, Vec3::ONE, &ctx); let run2 = evaluate_node_modifiers(&node, Vec3::ONE, &ctx); assert_eq!(run1.instances.len(), 20); for (a, b) in run1.instances.iter().zip(run2.instances.iter()) { assert!((a.pos - b.pos).length() < 1e-6); assert!((a.rot_deg - b.rot_deg).length() < 1e-5); assert!((a.scale - b.scale).length() < 1e-6); assert_eq!(a.visible, b.visible); assert!((a.scale.x - a.scale.y).abs() < 1e-5 && (a.scale.y - a.scale.z).abs() < 1e-5); } let hidden_cnt = run1.instances.iter().filter(|i| !i.visible).count(); assert!(hidden_cnt > 0 && hidden_cnt < 20, "Skip chance should hide a subset, hidden={hidden_cnt}"); if let ModifierKind::RandomizeTransform { ref mut seed, .. } = node.modifiers[1].kind { *seed = 99999; } let run3 = evaluate_node_modifiers(&node, Vec3::ONE, &ctx); assert!( run1.instances .iter() .zip(run3.instances.iter()) .any(|(a, b)| (a.pos - b.pos).length() > 0.05), "Changing seed must produce distinct scatter positions" ); } #[test] fn map_blueprint_modifiers_per_instance_destructibles_nav_bake_and_json_compat() { use project_cold_water::modding::blueprint::{ AssetBlueprint, BlueprintPayload, MapBlueprint, MapModSpawn, MapTerrainBase, SCHEMA_VERSION, }; use project_cold_water::modding::csg::{CsgNode, CsgOp, CsgShape, PrimitiveKind}; use project_cold_water::modding::modifiers::{ArrayMode, ModifierKind, NodeModifier}; use project_cold_water::modding::registry::ModRegistry; use project_cold_water::modding::studio::{AssetStudioState, StudioMode}; use project_cold_water::world::Faction; // 1. Legacy JSON without "modifiers" or "named_curves" must still deserialize cleanly let legacy_node_json = r#"{ "id": 1, "name": "Legacy Box", "op": "Union", "shape": {"Primitive": "Box"}, "pos": [0.0, 1.0, 0.0], "rot_deg": [0.0, 0.0, 0.0], "scale": [2.0, 2.0, 2.0], "material": "Concrete" }"#; let legacy_node: CsgNode = serde_json::from_str(legacy_node_json).expect("legacy CsgNode deser"); assert!(legacy_node.modifiers.is_empty()); // 2. Map with an Arrayed + Curved barrier node creates per-instance DestructibleStructures & NavObstacles let mut barrier = CsgNode::new_primitive( 5, "Curved Concrete Wall", CsgOp::Union, PrimitiveKind::Box, [0.0, 1.2, 0.0], [0.0; 3], [3.5, 2.4, 0.9], MaterialId::Concrete, ); barrier.modifiers = vec![ NodeModifier { id: 1, name: "WallArray".into(), enabled: true, kind: ModifierKind::Array { mode: ArrayMode::Linear, count: 6, offset: [4.5, 0.0, 0.0], relative_offset: [0.0; 3], step_rot_deg: [0.0; 3], step_scale: [0.0; 3], radial_radius: 5.0, radial_arc_deg: 360.0, radial_align: true, grid_count_z: 1, grid_spacing_z: 1.0, snap_to_terrain: false, }, }, NodeModifier::curve_preset(2, true), ]; let bp = AssetBlueprint { schema_version: SCHEMA_VERSION, id: "mod_wall_map".into(), name: "Modified Wall Map".into(), author: "ColdWater".into(), payload: BlueprintPayload::Map(MapBlueprint { base_terrain: MapTerrainBase::FlatSandbox { half_extent: 120.0, material: MaterialId::WinterMud, }, nodes: vec![barrier.clone()], spawns: vec![ MapModSpawn { name: "Fed".into(), faction: Faction::Federal, pos: [-30.0, 0.0, -30.0], ..Default::default() }, MapModSpawn { name: "Mil".into(), faction: Faction::Militia, pos: [30.0, 0.0, 30.0], ..Default::default() }, ], objectives: Vec::new(), vehicles: Vec::new(), named_curves: Vec::new(), script_hooks: Vec::new(), mission_defaults: Default::default(), }), }; let json = serde_json::to_string(&bp).expect("serialize blueprint with modifiers"); let roundtrip: AssetBlueprint = serde_json::from_str(&json).expect("roundtrip deserialize"); let world = ModRegistry::default() .build_world_from_map(&roundtrip) .expect("build map with modifiers"); assert_eq!( world.destructible.structures.len(), 6, "Each arrayed barrier segment must become its own DestructibleStructure" ); assert!( world.nav_grid.obstacles.len() >= 6, "NavGrid must emit obstacles for every modified wall segment, got {}", world.nav_grid.obstacles.len() ); // 3. Bake to Group / Nodes and Undo in AssetStudioState let mut studio = AssetStudioState::default(); studio.switch_new_mode(StudioMode::Map); studio.load_blueprint(roundtrip); assert_eq!(studio.active_nodes().len(), 1); studio.select_node(Some(5)); studio.bake_selected_node_modifiers(true); assert_eq!(studio.active_nodes().len(), 1); match &studio.active_nodes()[0].shape { CsgShape::Group(children) => assert_eq!(children.len(), 6), other => panic!("Expected baked Group(6), got {other:?}"), } studio.undo(); assert_eq!(studio.active_nodes()[0].modifiers.len(), 2, "Undo must restore non-destructive modifier stack"); studio.bake_selected_node_modifiers(false); assert_eq!(studio.active_nodes().len(), 6, "Bake to Nodes must expand into 6 top-level nodes"); assert!(studio.active_nodes().iter().all(|n| n.modifiers.is_empty())); } #[test] fn test_building_collapse_load_bearing_threshold_triggers_and_rebuilds_mesh() { use project_cold_water::audio::bvh::AcousticBvh; use project_cold_water::modding::destruction::DestructibleWorld; use project_cold_water::world::structures::StructureBuilder; use project_cold_water::world::{HeightQuery, StaticVertex}; struct FlatGround; impl HeightQuery for FlatGround { fn height_at(&self, _x: f32, _z: f32) -> f32 { 0.0 } fn river_center_x(&self, _z: f32) -> f32 { 1000.0 } fn water_level(&self) -> f32 { -10.0 } } let hq = FlatGround; let mut s_verts = Vec::new(); let mut s_idxs = Vec::new(); let mut s_tris = Vec::new(); let mut covers = Vec::new(); let mut nav_obs = Vec::new(); let mut nav_bridges = Vec::new(); let mut sb = StructureBuilder { vertices: &mut s_verts, indices: &mut s_idxs, acoustic: &mut s_tris, cover_nodes: &mut covers, nav_obstacles: &mut nav_obs, nav_bridges: &mut nav_bridges, height_query: &hq, destructibles: Vec::new(), active_destructible: None, }; sb.add_khrushchyovka(Vec3::ZERO, 0.0, 3, false); let mut dw: DestructibleWorld = sb.finish_destructible_world(); assert_eq!(dw.buildings.len(), 1, "Building cluster must register automatically"); assert!(!dw.buildings[0].collapsed); assert!( dw.structures.iter().any(|s| s.is_load_bearing), "Ground-story walls must be classified as load-bearing" ); let initial_max_y = dw .structures .iter() .filter(|s| s.aabb.is_valid()) .map(|s| s.aabb.max.y) .fold(0.0_f32, f32::max); assert!(initial_max_y > 8.5, "Intact 3-story building should exceed 8.5m (got {initial_max_y})"); // Blast ground-floor supports along the perimeter until load-bearing threshold triggers let mut collapses = Vec::new(); let hits = [ Vec3::new(-6.0, 1.2, 4.4), Vec3::new(0.0, 1.2, 4.4), Vec3::new(6.0, 1.2, 4.4), Vec3::new(-6.0, 1.2, -4.4), Vec3::new(0.0, 1.2, -4.4), Vec3::new(6.0, 1.2, -4.4), Vec3::new(-7.3, 1.2, 0.0), Vec3::new(7.3, 1.2, 0.0), ]; for (idx, &p) in hits.iter().enumerate() { let (_, evs) = dw.apply_crater_with_collapses(p, 2.8, 700 + idx as u64); collapses.extend(evs); if dw.buildings[0].collapsed { break; } } assert_eq!(collapses.len(), 1, "Building must collapse cleanly once threshold is crossed"); assert!(dw.buildings[0].collapsed); let collapsed_max_y = dw .structures .iter() .filter(|s| s.aabb.is_valid()) .map(|s| s.aabb.max.y) .fold(0.0_f32, f32::max); assert!( collapsed_max_y <= 5.5 && collapsed_max_y > 1.5, "Collapsed ruin max_y must drop cleanly from {initial_max_y}m to rubble profile (got {collapsed_max_y}m)" ); let mut verts: Vec = Vec::new(); let mut idxs: Vec = Vec::new(); let mut tris = Vec::new(); dw.rebuild_buffers(&mut verts, &mut idxs, &mut tris); assert!(!verts.is_empty() && !idxs.is_empty() && !tris.is_empty()); assert!(verts.iter().all(|v| v.position.iter().all(|x| x.is_finite()))); let bvh = AcousticBvh::build(tris); assert!( bvh.raycast(Vec3::new(0.0, 12.0, 0.0), Vec3::NEG_Y, 15.0).is_some(), "Collapsed ruin BVH must still catch vertical rays onto rubble" ); // Follow-up craters must still carve cleanly into the collapsed rubble! let target_ruin = dw.structures[0].aabb; let ruin_center = (target_ruin.min + target_ruin.max) * 0.5; assert!( dw.apply_crater(ruin_center, 1.2, 9999).is_some(), "Follow-up shots should still carve craters into collapsed rubble" ); } #[test] fn test_building_collapse_all_three_modes_pancake_cantilever_v_and_aframe() { use project_cold_water::core::events::SoundKind; use project_cold_water::modding::blueprint::{ AssetBlueprint, BlueprintPayload, MapBlueprint, MapModSpawn, MapTerrainBase, SCHEMA_VERSION, }; use project_cold_water::modding::destruction::{CollapseMode, DestructibleWorld}; use project_cold_water::modding::registry::ModRegistry; use project_cold_water::sim::Simulation; use project_cold_water::world::structures::StructureBuilder; use project_cold_water::world::{Faction, HeightQuery}; struct FlatGround; impl HeightQuery for FlatGround { fn height_at(&self, _x: f32, _z: f32) -> f32 { 0.0 } fn river_center_x(&self, _z: f32) -> f32 { 1000.0 } fn water_level(&self) -> f32 { -10.0 } } let build_khrush = || -> DestructibleWorld { let hq = FlatGround; let mut v = Vec::new(); let mut i = Vec::new(); let mut t = Vec::new(); let mut c = Vec::new(); let mut o = Vec::new(); let mut b = Vec::new(); let mut sb = StructureBuilder { vertices: &mut v, indices: &mut i, acoustic: &mut t, cover_nodes: &mut c, nav_obstacles: &mut o, nav_bridges: &mut b, height_query: &hq, destructibles: Vec::new(), active_destructible: None, }; sb.add_khrushchyovka(Vec3::ZERO, 0.0, 3, false); sb.finish_destructible_world() }; let sample_max_y_in_x = |dw: &DestructibleWorld, x_min: f32, x_max: f32| -> f32 { let mut max_y = 0.0_f32; for s in &dw.structures { for p in &s.polys { for &v in &p.verts { if v.x >= x_min && v.x <= x_max { max_y = max_y.max(v.y); } } } } max_y }; // 1. Center core demolition -> Cantilever V-Frame let mut dw_v = build_khrush(); let core_hits = [ Vec3::new(0.0, 1.2, 4.4), Vec3::new(-2.2, 1.2, 4.4), Vec3::new(2.2, 1.2, 4.4), Vec3::new(0.0, 1.2, -4.4), Vec3::new(-2.2, 1.2, -4.4), Vec3::new(2.2, 1.2, -4.4), Vec3::new(0.0, 1.2, 2.5), Vec3::new(0.0, 1.2, -2.5), Vec3::new(-3.2, 1.2, 4.4), Vec3::new(3.2, 1.2, 4.4), Vec3::new(-3.2, 1.2, -4.4), Vec3::new(3.2, 1.2, -4.4), ]; let mut ev_v = Vec::new(); for (idx, &p) in core_hits.iter().enumerate() { let (_, evs) = dw_v.apply_crater_with_collapses(p, 2.9, 100 + idx as u64); ev_v.extend(evs); if dw_v.buildings[0].collapsed { break; } } assert_eq!(ev_v.len(), 1); assert_eq!(ev_v[0].mode, CollapseMode::CantileverV); let v_center_y = sample_max_y_in_x(&dw_v, -1.5, 1.5); let v_outer_y = sample_max_y_in_x(&dw_v, 5.5, 8.0) .max(sample_max_y_in_x(&dw_v, -8.0, -5.5)); assert!( v_outer_y > v_center_y + 0.4, "CantileverV outer piers ({v_outer_y}) must rise above central V-trough ({v_center_y})" ); // 2. Outer wall demolition -> A-Frame Tent let mut dw_a = build_khrush(); let edge_hits = [ Vec3::new(-6.8, 1.2, 4.4), Vec3::new(6.8, 1.2, 4.4), Vec3::new(-6.8, 1.2, -4.4), Vec3::new(6.8, 1.2, -4.4), Vec3::new(-7.4, 1.2, 0.0), Vec3::new(7.4, 1.2, 0.0), Vec3::new(-5.8, 1.5, 4.4), Vec3::new(5.8, 1.5, 4.4), Vec3::new(-5.8, 1.5, -4.4), Vec3::new(5.8, 1.5, -4.4), ]; let mut ev_a = Vec::new(); for (idx, &p) in edge_hits.iter().enumerate() { let (_, evs) = dw_a.apply_crater_with_collapses(p, 2.8, 200 + idx as u64); ev_a.extend(evs); if dw_a.buildings[0].collapsed { break; } } assert_eq!(ev_a.len(), 1); assert_eq!(ev_a[0].mode, CollapseMode::AFrame); let a_center_y = sample_max_y_in_x(&dw_a, -1.5, 1.5); let a_outer_y = sample_max_y_in_x(&dw_a, 6.2, 9.0) .max(sample_max_y_in_x(&dw_a, -9.0, -6.2)); assert!( a_center_y > a_outer_y + 0.7, "AFrame center apex ({a_center_y}) must peak cleanly above outer eaves ({a_outer_y})" ); // 3. Broad uniform base demolition -> Pancake Crush + full Simulation FX/Audio/Crush verification let map_bp = AssetBlueprint { schema_version: SCHEMA_VERSION, id: "collapse_sim_test".into(), name: "Collapse Sim Test".into(), author: "ColdWater".into(), payload: BlueprintPayload::Map(MapBlueprint { base_terrain: MapTerrainBase::FlatSandbox { half_extent: 120.0, material: MaterialId::WinterMud, }, nodes: Vec::new(), spawns: vec![ MapModSpawn { name: "Fed".into(), faction: Faction::Federal, pos: [-40.0, 0.0, 0.0], ..Default::default() }, MapModSpawn { name: "Mil".into(), faction: Faction::Militia, pos: [40.0, 0.0, 0.0], ..Default::default() }, ], objectives: Vec::new(), vehicles: Vec::new(), named_curves: Vec::new(), script_hooks: Vec::new(), mission_defaults: Default::default(), }), }; let mut world = ModRegistry::default().build_world_from_map(&map_bp).unwrap(); let mut sb = StructureBuilder { vertices: &mut world.static_vertices, indices: &mut world.static_indices, acoustic: &mut world.acoustic_triangles, cover_nodes: &mut world.cover_nodes, nav_obstacles: &mut world.nav_grid.obstacles, nav_bridges: &mut world.nav_grid.bridges, height_query: &world.height_grid, destructibles: Vec::new(), active_destructible: None, }; sb.add_khrushchyovka(Vec3::ZERO, 0.0, 3, false); world.destructible = sb.finish_destructible_world(); let mut sim = Simulation::new(&world); // Place an enemy soldier right inside the ground floor so the collapse crushes him sim.soldiers[0].alive = true; sim.soldiers[0].in_vehicle = None; sim.soldiers[0].pos = Vec3::new(0.0, 0.5, 0.0); let uniform_hits = [ Vec3::new(-7.4, 1.2, 0.0), Vec3::new(7.4, 1.2, 0.0), Vec3::new(0.0, 1.2, 2.8), Vec3::new(0.0, 1.2, -4.4), Vec3::new(-5.6, 1.2, 4.4), Vec3::new(5.6, 1.2, -4.4), Vec3::new(0.0, 1.2, -2.6), Vec3::new(-5.6, 1.2, -4.4), Vec3::new(5.6, 1.2, 4.4), Vec3::new(-2.0, 1.2, 4.4), Vec3::new(2.0, 1.2, -4.4), ]; for (idx, &p) in uniform_hits.iter().enumerate() { sim.apply_destruction_crater_batched(p, 2.05, 300 + idx as u64); if sim.collapsed_building_count() > 0 { break; } } sim.flush_destruction_updates(); assert_eq!(sim.collapsed_building_count(), 1); assert_eq!(sim.destructible.buildings[0].collapse_mode, Some(CollapseMode::Pancake)); let pancake_max_y = sample_max_y_in_x(&sim.destructible, -9.0, 9.0); assert!( pancake_max_y < 4.5, "Pancake collapse must crush height below 4.5m (got {pancake_max_y})" ); assert!( sim.impact_effects.particles.len() >= 30, "Building collapse must spawn abundant dust puffs & rubble chunks (got {})", sim.impact_effects.particles.len() ); assert!( sim.pending_sounds.iter().any(|s| s.kind == SoundKind::WallCollapse && s.gain >= 1.4), "Building collapse must emit layered thunderous WallCollapse audio" ); assert!( !sim.soldiers[0].alive, "Soldier caught inside collapsing building must be crushed" ); } #[test] fn test_cwassetopack_roundtrip_load_override_scripts_grids_and_unpack() { use project_cold_water::modding::blueprint::{ starter_map_blueprint, starter_map_stamp_blueprint, starter_vehicle_blueprint, starter_weapon_blueprint, }; use project_cold_water::modding::pack::{ delete_asset_pack, save_asset_pack, unpack_asset_pack_to_dir, AssetPack, AssetPackGrid, ASSET_PACK_EXTENSION, }; use project_cold_water::modding::registry::ModRegistry; use project_cold_water::scripting::runtime::ScriptingRuntime; use project_cold_water::scripting::storage::{ list_script_assets, load_autoload_scripts, SavedScriptAsset, SavedScriptCategory, SavedScriptKind, SCRIPT_SCHEMA_VERSION, }; use project_cold_water::world::generator::{CustomGridSpec, GridCellScope}; use project_cold_water::world::palette::MapGenPalette; use project_cold_water::world::terrain::ZoneType; let tmp_root = std::env::temp_dir().join("cw_test_assetopack_roundtrip"); let _ = std::fs::remove_dir_all(&tmp_root); let mut wep = starter_weapon_blueprint(); wep.id = "pack_ak_mod".into(); wep.name = "Packed AK Variant".into(); let mut veh = starter_vehicle_blueprint(); veh.id = "pack_truck_mod".into(); veh.name = "Packed Gun Truck".into(); let mut map = starter_map_blueprint(); map.id = "pack_outpost_map".into(); map.name = "Packed Outpost".into(); let mut stamp = starter_map_stamp_blueprint(); stamp.id = "pack_bunker_stamp".into(); stamp.name = "Packed Bunker Stamp".into(); let mut pal = MapGenPalette::default_engine_blockout(); pal.id = "pack_winter_palette".into(); pal.name = "Packed Winter Palette".into(); let grid = AssetPackGrid { name: "pack_river_sector".into(), grid: CustomGridSpec::new(4, 4, GridCellScope::District64m, ZoneType::SovietCityCore), }; let script = SavedScriptAsset { schema_version: SCRIPT_SCHEMA_VERSION, id: "pack_autoload_banner".into(), name: "Packed Autoload Script".into(), kind: SavedScriptKind::Luau, category: SavedScriptCategory::Gameplay, auto_load: true, description: "Test script inside .cwassetopack.json".into(), graph: None, lua_source: r#"cw.set_var("pack_loaded", 42)"#.into(), }; let pack = AssetPack { id: "heavy_bundle".into(), name: "Heavy Bundle".into(), author: "Tester".into(), version: "1.2.0".into(), description: "Combined pack without heightmaps".into(), assets: vec![wep.clone(), veh, map, stamp], mapgen_palettes: vec![pal], grids: vec![grid], scripts: vec![script], ..Default::default() }; // 1. Export .cwassetopack.json let pack_path = save_asset_pack(&tmp_root, &pack).expect("save .cwassetopack.json"); assert!( pack_path.to_string_lossy().ends_with(ASSET_PACK_EXTENSION), "Saved pack must end with {ASSET_PACK_EXTENSION}: {}", pack_path.display() ); assert!(pack_path.exists()); // 2. Load via ModRegistry and verify weapons, vehicles, maps, stamps, palettes, grids, scripts let mut reg = ModRegistry::load_project_dir(&tmp_root, false); assert_eq!(reg.packs.len(), 1); assert_eq!(reg.find_weapon("pack_ak_mod").unwrap().blueprint.name, "Packed AK Variant"); assert!(reg.find_vehicle("pack_truck_mod").is_some()); assert!(reg.find_map("pack_outpost_map").is_some()); assert!(reg.find_stamp("pack_bunker_stamp").is_some()); assert!(reg.find_palette("pack_winter_palette").is_some()); assert!(reg.list_all_grid_names(&tmp_root).contains(&"pack_river_sector".to_string())); let loaded_grid = reg.find_grid(&tmp_root, "pack_river_sector").expect("load packed grid"); assert_eq!(loaded_grid.width, 4); let listed_scripts = list_script_assets(&tmp_root); assert!(listed_scripts.iter().any(|(_, s)| s.id == "pack_autoload_banner")); let mut rt = ScriptingRuntime::default(); let loaded_cnt = load_autoload_scripts(&tmp_root, &mut rt, 0.0); assert_eq!(loaded_cnt, 1); // 3. Loose file overrides packed asset of the same ID let mut loose_wep = wep; loose_wep.name = "Loose Override AK".into(); reg.save_blueprint(&tmp_root, loose_wep).expect("save loose override"); assert_eq!( reg.find_weapon("pack_ak_mod").unwrap().blueprint.name, "Loose Override AK", "Loose weapon JSON must take priority over packed version" ); // 4. Unpack to loose directories, delete the pack file, reload, and verify everything remains let loose_wep_path = tmp_root.join("weapons").join("pack_ak_mod.json"); let _ = std::fs::remove_file(&loose_wep_path); let unpacked_cnt = unpack_asset_pack_to_dir(&tmp_root, &pack).expect("unpack pack"); assert_eq!(unpacked_cnt, 7); assert!(loose_wep_path.exists()); assert!(tmp_root.join("grids").join("pack_river_sector.cwgrid.json").exists()); assert!(tmp_root.join("scripts").join("pack_autoload_banner.coldflux.json").exists()); assert!(tmp_root.join("mapgen_palettes").join("pack_winter_palette.json").exists()); delete_asset_pack(&pack_path).expect("delete pack file"); reg.reload_from_dir(&tmp_root); assert_eq!(reg.packs.len(), 0); assert_eq!(reg.find_weapon("pack_ak_mod").unwrap().blueprint.name, "Packed AK Variant"); assert!(reg.find_grid(&tmp_root, "pack_river_sector").is_ok()); let _ = std::fs::remove_dir_all(&tmp_root); } #[test] fn test_map_editor_dynamic_grid_corridor_quad_and_3km_roundtrip_and_build() { use project_cold_water::modding::blueprint::{ starter_map_blueprint, AssetBlueprint, BlueprintPayload, MapTerrainBase, }; use project_cold_water::modding::csg::{CsgNode, CsgOp, PrimitiveKind}; use project_cold_water::modding::registry::{build_world_from_map_spec, ModRegistry}; use project_cold_water::ui::mapgen_ui::GridDesignerState; use project_cold_water::world::generator::{ CustomGridSpec, GridCellScope, GridTemplateKind, MapGenConfig, MapLayoutMode, }; use project_cold_water::world::palette::MapGenPalette; use project_cold_water::world::terrain::ZoneType; let mut reg = ModRegistry::default(); let pal = MapGenPalette::platform_default(); let pal_id = pal.id.clone(); reg.mapgen_palettes.push(pal); // 1. Custom Grid (4x4 Block32m) inside a MapBlueprint + custom CSG wall node let mut grid = CustomGridSpec::new(4, 4, GridCellScope::Block32m, ZoneType::OpenField); grid.apply_template(GridTemplateKind::ValleyRiver, 404); let mut grid_cfg = MapGenConfig::custom_grid(grid, 404); grid_cfg.palette_id = Some(pal_id.clone()); let mut bp = starter_map_blueprint(); bp.id = "map_editor_grid_test".into(); bp.name = "Map Editor Custom Grid Test".into(); if let BlueprintPayload::Map(ref mut mb) = bp.payload { mb.base_terrain = MapTerrainBase::Dynamic(grid_cfg.clone()); mb.nodes.push(CsgNode::new_primitive( 901, "Custom Editor Blockhouse", CsgOp::Union, PrimitiveKind::Box, [0.0, 2.5, 0.0], [0.0; 3], [4.0, 3.0, 4.0], MaterialId::Concrete, )); } // Roundtrip via JSON let json = serde_json::to_string_pretty(&bp).expect("serialize MapBlueprint with CustomGrid"); let decoded: AssetBlueprint = serde_json::from_str(&json).expect("deserialize MapBlueprint"); let BlueprintPayload::Map(ref dec_mb) = decoded.payload else { panic!("expected Map payload"); }; let w_grid = build_world_from_map_spec(&decoded.name, dec_mb, ®).expect("build CustomGrid map"); assert!(w_grid.static_vertices.len() > 100); assert!( !w_grid.destructible.structures.is_empty(), "CustomGrid MapBlueprint with destructible CSG node must keep destructible structures" ); // GridDesignerState roundtrip helper let mut designer = GridDesignerState::default(); designer.load_from_map_gen_config(&grid_cfg, ®); let rebuilt_cfg = designer.build_map_gen_config(); assert_eq!(rebuilt_cfg.seed, 404); assert_eq!(rebuilt_cfg.palette_id.as_deref(), Some(pal_id.as_str())); assert!(matches!(rebuilt_cfg.layout, MapLayoutMode::CustomGrid(ref g) if g.width == 4 && g.height == 4)); // 2. StitchedCorridor, StitchedQuad, and 3 km MacroTheater inside MapBlueprint for (label, cfg) in [ ( "Corridor Map", MapGenConfig::stitched_corridor( [ ZoneType::FoothillRidge, ZoneType::RiverCrossing, ZoneType::SovietCityCore, ], 505, ), ), ( "Quad Map", MapGenConfig::stitched_quad( [ ZoneType::FoothillRidge, ZoneType::IndustrialOutskirts, ZoneType::RiverCrossing, ZoneType::SovietCityCore, ], 606, ), ), ] { let mut m = dec_mb.clone(); m.nodes.clear(); m.base_terrain = MapTerrainBase::Dynamic(cfg); let w = build_world_from_map_spec(label, &m, ®).expect("build stitched map from MapBlueprint"); assert!(w.world_half_extent >= 150.0, "{label} must build full playable extent"); } let mut m3 = dec_mb.clone(); m3.nodes.clear(); m3.base_terrain = MapTerrainBase::Dynamic(MapGenConfig::macro_theater_3km(707)); let w3 = build_world_from_map_spec("3km Theater Map", &m3, ®).expect("build 3km MapBlueprint"); assert!( w3.terrain_chunks.is_some() && w3.world_half_extent >= 1400.0, "MacroTheater3km in MapBlueprint must produce chunked 3km terrain" ); } #[test] fn test_map_editor_mission_default_and_per_unit_behaviors() { use project_cold_water::core::config::AiSkillLevel; use project_cold_water::modding::blueprint::{ AssetBlueprint, BlueprintPayload, MapBlueprint, MapMissionDefaults, MapModObjective, MapModSpawn, MapModVehiclePlacement, MapSquadBehavior, MapTerrainBase, SCHEMA_VERSION, }; use project_cold_water::modding::registry::{build_world_from_map_spec, ModRegistry}; use project_cold_water::sim::objectives::ObjectiveKind; use project_cold_water::sim::orders::{RulesOfEngagement, SquadFormation, TacticalOrder}; use project_cold_water::sim::vehicles::{GroundVehicleTactic, HeliBehavior, VehicleTacticMode}; use project_cold_water::sim::Simulation; use project_cold_water::world::{Faction, VehicleKind}; let mut defaults = MapMissionDefaults::default(); defaults.friendly_faction = Faction::Militia; defaults.federal_behavior = MapSquadBehavior::HoldCover; defaults.federal_formation = SquadFormation::Line; defaults.federal_roe = RulesOfEngagement::HoldFire; defaults.militia_behavior = MapSquadBehavior::AssaultObjective; defaults.militia_formation = SquadFormation::Spread; defaults.militia_roe = RulesOfEngagement::WeaponsFree; defaults.default_vehicle_tactic = VehicleTacticMode::Ground(GroundVehicleTactic::ArmoredPush); defaults.vehicles_engage_objective = true; defaults.auto_director_waves = true; defaults.default_ai_skill = Some(AiSkillLevel::Spetsnaz); defaults.respawn_delay_secs = 12.5; defaults.sandbox_all_weapons = true; let bp = AssetBlueprint { schema_version: SCHEMA_VERSION, id: "mission_behavior_test".into(), name: "Mission Behavior Test".into(), author: "ColdWater".into(), payload: BlueprintPayload::Map(MapBlueprint { base_terrain: MapTerrainBase::FlatSandbox { half_extent: 220.0, material: MaterialId::WinterMud, }, nodes: Vec::new(), objectives: vec![ MapModObjective { title: "Primary Town".into(), brief: "Primary sector".into(), kind: ObjectiveKind::AssaultPosition { hold_secs: 6.0 }, pos: [10.0, 0.0, 10.0], radius: 15.0, }, MapModObjective { title: "Overwatch Hill".into(), brief: "Secondary sector".into(), kind: ObjectiveKind::SuppressPosition { required_secs: 8.0 }, pos: [-60.0, 0.0, 50.0], radius: 14.0, }, ], spawns: vec![ // Follows Federal MissionDefault -> HoldCover / Line / HoldFire MapModSpawn { name: "Fed Garrison".into(), faction: Faction::Federal, pos: [-25.0, 0.0, -25.0], ..Default::default() }, // Overrides behavior, formation, ROE & targets Objective #2 MapModSpawn { name: "Fed Overwatcher".into(), faction: Faction::Federal, pos: [-50.0, 0.0, -10.0], behavior: MapSquadBehavior::SuppressObjective, formation: Some(SquadFormation::Column), roe: Some(RulesOfEngagement::ReturnFireOnly), target_objective_idx: Some(1), }, // Follows Militia MissionDefault -> AssaultObjective / Spread / WeaponsFree targeting Objective #1 MapModSpawn { name: "Mil Assault".into(), faction: Faction::Militia, pos: [55.0, 0.0, 20.0], ..Default::default() }, ], vehicles: vec![ // Follows default_vehicle_tactic (ArmoredPush) + engages Primary Objective MapModVehiclePlacement { name: "Default BTR".into(), stock_kind: VehicleKind::Btr80A, custom_vehicle_id: None, faction: Faction::Militia, pos: [40.0, 0.0, 0.0], yaw_deg: 0.0, crewed: true, ..Default::default() }, // Overrides Heli Cas + disables objective engage on start MapModVehiclePlacement { name: "Gunship Override".into(), stock_kind: VehicleKind::Mi24Gunship, custom_vehicle_id: None, faction: Faction::Federal, pos: [-70.0, 0.0, -40.0], yaw_deg: 0.0, crewed: true, tactic_mode: Some(VehicleTacticMode::Heli(HeliBehavior::Cas)), engage_objective: Some(false), target_objective_idx: None, }, ], named_curves: Vec::new(), script_hooks: Vec::new(), mission_defaults: defaults, }), }; // 1. Serialize & deserialize roundtrip (and verify old-format JSON without mission_defaults still loads) let json = serde_json::to_string(&bp).expect("serialize mission behavior MapBlueprint"); let decoded: AssetBlueprint = serde_json::from_str(&json).expect("deserialize mission behavior MapBlueprint"); let legacy_json = r#"{"schema_version":1,"id":"legacy","name":"Legacy","author":"Old","payload":{"Map":{"base_terrain":{"FlatSandbox":{"half_extent":150.0,"material":"WinterMud"}},"nodes":[],"spawns":[{"name":"Fed","faction":"Federal","pos":[0.0,0.0,-20.0]}],"objectives":[],"vehicles":[]}}}"#; let legacy_bp: AssetBlueprint = serde_json::from_str(legacy_json).expect("legacy MapBlueprint JSON without new fields must deserialize"); let BlueprintPayload::Map(ref legacy_mb) = legacy_bp.payload else { panic!("expected Map"); }; assert_eq!(legacy_mb.mission_defaults.friendly_faction, Faction::Federal); assert_eq!(legacy_mb.spawns[0].behavior, MapSquadBehavior::MissionDefault); // 2. Compile WorldData and spawn Simulation let BlueprintPayload::Map(ref dec_mb) = decoded.payload else { panic!("expected Map"); }; let reg = ModRegistry::default(); let world = build_world_from_map_spec(&decoded.name, dec_mb, ®).expect("build world"); assert_eq!(world.mission_defaults.default_ai_skill, Some(AiSkillLevel::Spetsnaz)); let mut sim = Simulation::new_with_mods(&world, ®); let check_sim = |s: &Simulation| { assert_eq!(s.mission.friendly_faction, Faction::Militia); assert_eq!(s.respawn.selected_faction, Faction::Militia); assert!(s.director.auto_director_waves); assert!((s.respawn.respawn_delay_secs - 12.5).abs() < 0.01); assert!(s.respawn.sandbox_all_weapons); let fed_gar = s.squads.iter().find(|sq| sq.name == "Fed Garrison").expect("Fed Garrison"); assert_eq!(fed_gar.order, TacticalOrder::HoldCover); assert_eq!(fed_gar.formation, SquadFormation::Line); assert_eq!(fed_gar.roe, RulesOfEngagement::HoldFire); let fed_ow = s.squads.iter().find(|sq| sq.name == "Fed Overwatcher").expect("Fed Overwatcher"); assert!(matches!(fed_ow.order, TacticalOrder::SuppressArea(p) if p.distance(glam::Vec3::new(-60.0, p.y, 50.0)) < 6.0)); assert_eq!(fed_ow.formation, SquadFormation::Column); assert_eq!(fed_ow.roe, RulesOfEngagement::ReturnFireOnly); let mil_assault = s.squads.iter().find(|sq| sq.name == "Mil Assault").expect("Mil Assault"); assert!(matches!(mil_assault.order, TacticalOrder::Assault(p) if p.distance(glam::Vec3::new(10.0, p.y, 10.0)) < 6.0)); assert_eq!(mil_assault.formation, SquadFormation::Spread); assert_eq!(mil_assault.roe, RulesOfEngagement::WeaponsFree); let def_btr = s.vehicles.iter().find(|v| v.name == "Default BTR").expect("Default BTR"); assert_eq!(def_btr.tactic_mode, VehicleTacticMode::Ground(GroundVehicleTactic::ArmoredPush)); assert!(def_btr.ai_target.is_some()); let cas_heli = s.vehicles.iter().find(|v| v.name == "Gunship Override").expect("Gunship Override"); assert_eq!(cas_heli.tactic_mode, VehicleTacticMode::Heli(HeliBehavior::Cas)); assert!(cas_heli.ai_target.is_none()); }; check_sim(&sim); // 3. Rules & behaviors persist across reset_skirmish() sim.reset_skirmish(); check_sim(&sim); }