| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284 |
- use std::sync::{atomic::AtomicUsize, Arc};
- use glam::Vec3;
- use project_cold_water::audio::bvh::AcousticBvh;
- use project_cold_water::audio::dsp::{compute_binaural_params, HadamardFdn8, RealTimeDsp};
- use project_cold_water::audio::patch::{compute_spectrum_bars, synthesize_patch, AudioPatchBank};
- use project_cold_water::audio::propagation::{estimate_environment, trace_sound_event};
- use project_cold_water::audio::synth::ambience::ProceduralAmbience;
- use project_cold_water::audio::synth::ProceduralSoundBank;
- use project_cold_water::core::config::{AudioConfig, SimConfig};
- use project_cold_water::core::events::{ListenerPose, SoundEvent, SoundKind};
- use project_cold_water::core::materials::MaterialId;
- use project_cold_water::sim::ballistics::{step_projectiles, Projectile, ProjectileKind};
- use project_cold_water::sim::orders::TacticalOrder;
- use project_cold_water::sim::Simulation;
- use project_cold_water::world::maps::foothill_river_town::FoothillRiverTownMap;
- use project_cold_water::world::{AcousticTriangle, Faction, MapScenario};
- fn make_quad_tris(p00: Vec3, p10: Vec3, p11: Vec3, p01: Vec3, mat: MaterialId) -> [AcousticTriangle; 2] {
- [
- AcousticTriangle::new(p00, p10, p11, mat),
- AcousticTriangle::new(p00, p11, p01, mat),
- ]
- }
- #[test]
- fn test_bvh_raycast_and_occlusion_diffraction() {
- // Build a concrete wall between source (-8, 1.5, 0) and listener (+8, 1.5, 0)
- let mut tris = Vec::new();
- tris.extend(make_quad_tris(
- Vec3::new(0.0, 0.0, -5.0),
- Vec3::new(0.0, 0.0, 5.0),
- Vec3::new(0.0, 4.0, 5.0),
- Vec3::new(0.0, 4.0, -5.0),
- MaterialId::Concrete,
- ));
- let bvh = AcousticBvh::build(tris);
- let hit = bvh
- .raycast(Vec3::new(-5.0, 1.5, 0.0), Vec3::X, 20.0)
- .expect("should hit concrete wall");
- assert!((hit.t - 5.0).abs() < 1e-3);
- assert_eq!(hit.material, MaterialId::Concrete);
- let ev = SoundEvent {
- kind: SoundKind::Ak74mShot,
- position: Vec3::new(-8.0, 1.5, 0.0),
- velocity: Vec3::ZERO,
- gain: 1.0,
- pitch_jitter: 1.0,
- };
- let listener = ListenerPose {
- position: Vec3::new(8.0, 1.5, 0.0),
- ..Default::default()
- };
- let cfg = AudioConfig::default();
- let (taps, _) = trace_sound_event(&ev, &listener, &bvh, &cfg, None);
- assert!(!taps.is_empty(), "diffracted tap should arrive around the wall");
- // Verify knife-edge diffraction preserves low band strictly more than high band
- let first = taps[0];
- assert!(
- first.band_gains[0] > first.band_gains[2] * 2.0,
- "low band ({}) should diffract significantly stronger than high band ({})",
- first.band_gains[0],
- first.band_gains[2]
- );
- }
- #[test]
- fn test_multi_bounce_canyon_echoes_finite_speed_of_sound() {
- // Ground plane + distant rocky canyon cliff at x = +90m
- let mut tris = Vec::new();
- tris.extend(make_quad_tris(
- Vec3::new(-120.0, 0.0, -120.0),
- Vec3::new(120.0, 0.0, -120.0),
- Vec3::new(120.0, 0.0, 120.0),
- Vec3::new(-120.0, 0.0, 120.0),
- MaterialId::WinterMud,
- ));
- tris.extend(make_quad_tris(
- Vec3::new(90.0, 0.0, -80.0),
- Vec3::new(90.0, 0.0, 80.0),
- Vec3::new(90.0, 65.0, 80.0),
- Vec3::new(90.0, 65.0, -80.0),
- MaterialId::MountainRock,
- ));
- let bvh = AcousticBvh::build(tris);
- let ev = SoundEvent {
- kind: SoundKind::SvdShot,
- position: Vec3::new(-10.0, 2.0, 0.0),
- velocity: Vec3::ZERO,
- gain: 1.2,
- pitch_jitter: 1.0,
- };
- let listener = ListenerPose {
- position: Vec3::new(0.0, 2.0, 0.0),
- ..Default::default()
- };
- let cfg = AudioConfig::default();
- let (taps, bounces) = trace_sound_event(&ev, &listener, &bvh, &cfg, None);
- assert!(bounces > 20, "expected many multi-bounce ray hits in canyon");
- assert!(taps.len() >= 3, "expected direct + ground + canyon cliff reflection taps");
- let direct_delay = taps[0].delay_secs;
- assert!((direct_delay - 10.0 / 331.5).abs() < 0.005);
- // At least one delayed canyon reflection > 0.45s (round-trip off +90m cliff is ~190m / 331.5 = 0.57s)
- let has_canyon_echo = taps.iter().any(|t| t.delay_secs > 0.45 && t.band_gains[1] > 0.0005);
- assert!(has_canyon_echo, "expected delayed mountain canyon echo > 0.45s; got taps: {taps:?}");
- }
- #[test]
- fn test_procedural_sound_bank_all_generators_clean() {
- let bank = ProceduralSoundBank::generate(48_000);
- let kinds = [
- SoundKind::Ak74mShot,
- SoundKind::AkmShot,
- SoundKind::Aks74uShot,
- SoundKind::PkmShot,
- SoundKind::SvdShot,
- SoundKind::RpgLaunch,
- SoundKind::RpgRocketLoop,
- SoundKind::RpgExplosion,
- SoundKind::MortarWhistle,
- SoundKind::MortarExplosion,
- SoundKind::SupersonicCrack,
- SoundKind::Ricochet,
- SoundKind::ImpactConcrete,
- SoundKind::ImpactSteel,
- SoundKind::ImpactMud,
- SoundKind::ImpactWater,
- SoundKind::RadioSquelch,
- ];
- for kind in kinds {
- let buf = bank.get(kind);
- assert!(buf.len() > 200, "{kind:?} buffer too short");
- let mut rms_acc = 0.0_f64;
- let mut peak = 0.0_f32;
- for &s in buf {
- assert!(s.is_finite(), "{kind:?} produced NaN/Inf");
- peak = peak.max(s.abs());
- rms_acc += (s as f64) * (s as f64);
- }
- let rms = (rms_acc / buf.len() as f64).sqrt();
- assert!(rms > 0.01, "{kind:?} unexpectedly silent (rms={rms})");
- assert!(peak <= 1.0, "{kind:?} exceeded unit peak ({peak})");
- }
- let mut amb = ProceduralAmbience::new(48_000);
- for _ in 0..4800 {
- let (l, r) = amb.next_stereo(0.25, 0.2, 0.1);
- assert!(l.is_finite() && r.is_finite());
- }
- }
- #[test]
- fn test_hadamard_fdn_stability_and_binaural_itd_ild() {
- // 1. 10 seconds of impulse response in Hadamard FDN must decay cleanly without blowing up
- let mut fdn = HadamardFdn8::new(48_000);
- let mut max_early = 0.0_f32;
- let mut max_late = 0.0_f32;
- for i in 0..480_000 {
- let imp = if i == 0 { 1.0 } else { 0.0 };
- let (l, r) = fdn.process_stereo(imp, imp);
- assert!(l.is_finite() && r.is_finite(), "FDN produced NaN at sample {i}");
- if i < 24_000 {
- max_early = max_early.max(l.abs()).max(r.abs());
- }
- if i > 432_000 {
- max_late = max_late.max(l.abs()).max(r.abs());
- }
- }
- assert!(max_early > 0.01, "FDN should respond to impulse");
- assert!(max_late < max_early * 0.05, "FDN should decay cleanly over 10s (early={max_early}, late={max_late})");
- // 2. Binaural ITD/ILD: source directly to the LEFT (-X) arrives louder and with 0 delay on left ear
- let (gl, gr, itd_l, itd_r, al, ar) = compute_binaural_params(-Vec3::X, Vec3::X, -Vec3::Z, 48_000.0);
- assert!(gl > gr * 2.0, "left ear gain ({gl}) should exceed right ear gain ({gr})");
- assert_eq!(itd_l, 0.0);
- assert!(itd_r > 15.0, "right ear should be delayed by ITD samples ({itd_r})");
- assert!(al > ar, "right ear should have stronger head-shadow LPF ({al} vs {ar})");
- // 3. Full RealTimeDsp render smoke check
- let bank = ProceduralSoundBank::generate(48_000);
- let mut dsp = RealTimeDsp::new(48_000, bank, Arc::new(AtomicUsize::new(0)));
- dsp.enqueue_tap(project_cold_water::audio::AcousticTapCommand {
- kind: SoundKind::Ak74mShot,
- delay_secs: 0.0,
- band_gains: [0.9, 0.9, 0.9],
- arrival_dir: -Vec3::X,
- pitch_rate: 1.0,
- bypass_spatial: false,
- reverb_send: 0.3,
- attack_smooth_ms: 0.0,
- });
- let mut block = vec![0.0_f32; 1024];
- dsp.render_block(&mut block);
- assert!(block.iter().all(|s| s.is_finite()));
- assert!(block.iter().any(|&s| s.abs() > 0.01));
- }
- #[test]
- fn test_patch_bank_fx_chain_json_and_rifle_crack_spectrum() {
- let mut bank = AudioPatchBank::default_chechnya_presets();
- // Verify all 17 patches synthesize cleanly and rifle patches have bright high-freq crack energy
- for kind in [SoundKind::Ak74mShot, SoundKind::AkmShot, SoundKind::Aks74uShot, SoundKind::PkmShot, SoundKind::SvdShot] {
- let buf = synthesize_patch(bank.get(kind), 48_000);
- assert!(buf.iter().all(|s| s.is_finite()));
- let spec = compute_spectrum_bars(&buf, 48_000, 24);
- let high_avg: f32 = spec[14..].iter().sum::<f32>() / (spec.len() - 14) as f32;
- assert!(high_avg > 0.28, "{kind:?} lacks high-freq gunshot crack (high_avg={high_avg})");
- }
- // Exercise every FX module turned ON simultaneously
- let patch = bank.get_mut(SoundKind::Ak74mShot);
- patch.fx.transient_on = true;
- patch.fx.comb_on = true;
- patch.fx.drive_on = true;
- patch.fx.eq_on = true;
- patch.fx.grit_on = true;
- patch.fx.slap_on = true;
- let fx_buf = synthesize_patch(patch, 48_000);
- assert!(fx_buf.iter().all(|s| s.is_finite()));
- assert!(fx_buf.iter().any(|&s| s.abs() > 0.1));
- // Verify JSON round-trip serialization
- let json = serde_json::to_string_pretty(&bank).expect("serialize patch bank");
- let decoded: AudioPatchBank = serde_json::from_str(&json).expect("deserialize patch bank");
- assert_eq!(decoded.get(SoundKind::Ak74mShot).fx.grit_on, true);
- }
- #[test]
- fn test_nav_grid_forbids_water_and_routes_over_bridge() {
- use project_cold_water::world::terrain::TerrainGrid;
- let world = FoothillRiverTownMap.build();
- let nav = &world.nav_grid;
- // 1. River channel away from bridge MUST be non-walkable
- let river_x_south = TerrainGrid::river_center_x_static(35.0);
- assert!(
- !nav.is_walkable_world(river_x_south, 35.0),
- "river water at ({river_x_south}, 35.0) must be blocked"
- );
- let river_x_north = TerrainGrid::river_center_x_static(-55.0);
- assert!(
- !nav.is_walkable_world(river_x_north, -55.0),
- "river water at ({river_x_north}, -55.0) must be blocked"
- );
- // 2. Clicking on river water snaps to nearest dry walkable bank
- let snapped = nav.nearest_walkable(Vec3::new(river_x_south, 0.0, 35.0));
- assert!(nav.is_walkable_world(snapped.x, snapped.z));
- // 3. Cross-river A* path from West bank (-60, 35) to East bank (50, 35) must cross bridge without touching water!
- let start = Vec3::new(-60.0, 3.0, 35.0);
- let goal = Vec3::new(50.0, 3.0, 35.0);
- let path = nav.find_path(start, goal);
- assert!(path.len() >= 2, "expected multi-waypoint cross-river path via bridge");
- let mut prev = nav.nearest_walkable(start);
- let mut crossed_bridge = false;
- let bridge_z = TerrainGrid::bridge_z();
- let bridge_cx = TerrainGrid::river_center_x_static(bridge_z);
- for wp in &path {
- assert!(
- nav.is_segment_walkable(prev, *wp),
- "segment {:?} -> {:?} crossed unwalkable water or obstacle!",
- prev,
- wp
- );
- if (wp.z - bridge_z).abs() < 4.5 && (wp.x - bridge_cx).abs() < 18.0 && wp.y > 2.4 {
- crossed_bridge = true;
- }
- prev = *wp;
- }
- assert!(crossed_bridge, "cross-river path must route over the concrete bridge! path={path:?}");
- // 4. Step 300 ticks of cross-river Assault in Simulation -> zero soldiers ever touch water!
- let bvh = AcousticBvh::build(world.acoustic_triangles.clone());
- let mut sim = Simulation::new(&world);
- sim.issue_order(0, TacticalOrder::Assault(Vec3::new(40.0, 3.0, 20.0)));
- sim.issue_order(1, TacticalOrder::Assault(Vec3::new(40.0, 3.0, -20.0)));
- let cfg = SimConfig::default();
- for tick in 0..300 {
- sim.step(&cfg, 331.5, &bvh, Vec3::new(0.0, 15.0, 30.0));
- for s in &sim.soldiers {
- if s.alive {
- assert!(
- sim.nav_grid.is_walkable_world(s.pos.x, s.pos.z),
- "tick {tick}: soldier {} stepped onto unwalkable cell at {:?}",
- s.id,
- s.pos
- );
- }
- }
- }
- }
- #[test]
- fn test_unified_soldier_variety() {
- use std::collections::HashSet;
- let world = FoothillRiverTownMap.build();
- let sim = Simulation::new(&world);
- let mut jackets = HashSet::new();
- let mut trousers = HashSet::new();
- let mut headgears = HashSet::new();
- let mut vests = HashSet::new();
- for s in &sim.soldiers {
- assert!(s.appearance.jacket_mat.gpu_layer() < MaterialId::GPU_LAYER_COUNT);
- assert!(s.appearance.trouser_mat.gpu_layer() < MaterialId::GPU_LAYER_COUNT);
- assert!(s.appearance.headgear_mat.gpu_layer() < MaterialId::GPU_LAYER_COUNT);
- assert!(s.appearance.vest_mat.gpu_layer() < MaterialId::GPU_LAYER_COUNT);
- jackets.insert(s.appearance.jacket_mat);
- trousers.insert(s.appearance.trouser_mat);
- headgears.insert(s.appearance.headgear);
- vests.insert(s.appearance.vest);
- }
- assert!(jackets.len() >= 3, "expected >=3 varied uniform tops, got {}", jackets.len());
- assert!(trousers.len() >= 3, "expected >=3 varied uniform bottoms, got {}", trousers.len());
- assert!(headgears.len() >= 4, "expected >=4 varied headgear types, got {}", headgears.len());
- assert!(vests.len() >= 3, "expected >=3 varied vest/rig types, got {}", vests.len());
- }
- #[test]
- fn test_world_sim_ballistics_and_supersonic_cpa() {
- let world = FoothillRiverTownMap.build();
- let bvh = AcousticBvh::build(world.acoustic_triangles.clone());
- assert!(bvh.triangle_count() > 20_000);
- // Check enclosure estimator indoors vs open valley
- let open_env = estimate_environment(Vec3::new(0.0, 20.0, 0.0), &bvh, 1.0);
- assert!(open_env.sky_openness > 0.4);
- // Check supersonic bullet CPA trigger passing 4m from listener
- let mut projs = vec![Projectile {
- pos: Vec3::new(-10.0, 2.0, 4.0),
- prev_pos: Vec3::new(-10.0, 2.0, 4.0),
- vel: Vec3::new(880.0, 0.0, 0.0),
- kind: ProjectileKind::Bullet,
- faction: Faction::Federal,
- damage: 35.0,
- suppression: 0.2,
- blast_radius: 0.0,
- drag: 0.0,
- crater_radius: 0.0,
- age: 0.0,
- max_age: 1.0,
- is_tracer: false,
- crack_triggered: false,
- whistle_emitted: true,
- from_player: false,
- owner_player: None,
- visual_offset: Vec3::ZERO,
- guidance: Default::default(),
- guide_vehicle_id: None,
- is_heavy_ap: false,
- }];
- let mut sounds = Vec::new();
- let mut soldier_hits = Vec::new();
- let mut impacts = Vec::new();
- let mut explosions = Vec::new();
- let mut tracers = Vec::new();
- let mut lights = Vec::new();
- step_projectiles(
- &mut projs,
- 0.025, // moves from x=-10 to x=+12, passing x=0 at dist=4m
- 331.5,
- &bvh,
- &[],
- Vec3::new(0.0, 2.0, 0.0),
- &mut sounds,
- &mut soldier_hits,
- &mut impacts,
- &mut explosions,
- &mut tracers,
- &mut lights,
- );
- assert!(
- sounds.iter().any(|s| s.kind == SoundKind::SupersonicCrack),
- "supersonic bullet passing 4m from listener must emit SupersonicCrack at CPA"
- );
- // Check Simulation step & tactical orders
- let mut sim = Simulation::new(&world);
- sim.issue_order(0, TacticalOrder::Assault(Vec3::new(-10.0, 2.0, -6.0)));
- let cfg = SimConfig::default();
- for _ in 0..30 {
- sim.step(&cfg, 331.5, &bvh, Vec3::new(0.0, 12.0, 20.0));
- }
- let (fed, mil) = sim.alive_counts();
- assert!(fed > 0 && mil > 0);
- }
- #[test]
- fn test_all_six_weapons_have_distinct_detailed_meshes_and_meta() {
- use std::collections::HashSet;
- use project_cold_water::world::actors_mesh::ActorMeshLibrary;
- use project_cold_water::world::weapons_mesh::weapon_model_meta;
- use project_cold_water::world::WeaponKind;
- let lib = ActorMeshLibrary::build();
- let mut offsets = HashSet::new();
- for v in &lib.vertices {
- assert!(v.mat_id < MaterialId::GPU_LAYER_COUNT, "weapon/actor vertex mat_id out of bounds: {}", v.mat_id);
- }
- for kind in WeaponKind::ALL {
- let slice = lib.weapon_slice(kind);
- assert!(
- slice.index_count >= 120,
- "{kind:?} weapon mesh too simple (index_count={})",
- slice.index_count
- );
- assert!(
- offsets.insert(slice.index_offset),
- "{kind:?} shares mesh slice with another weapon!"
- );
- let meta = weapon_model_meta(kind);
- assert!(meta.mag_capacity > 0);
- assert!(meta.sight_height_y > 0.05);
- assert!(meta.muzzle_local.z > 0.45);
- }
- assert!(lib.launcher_rpg_warhead.index_count >= 60);
- assert!(lib.vm_sleeve_arms.index_count >= 60);
- assert!(lib.vm_gloves.index_count >= 60);
- assert!(lib.vm_muzzle_flash.index_count >= 60);
- }
- #[test]
- fn test_fps_player_all_six_weapons_movement_and_ballistics() {
- use project_cold_water::sim::player::FpsInput;
- use project_cold_water::world::actors_mesh::ActorMeshLibrary;
- use project_cold_water::world::terrain::TerrainGrid;
- use project_cold_water::world::weapons_mesh::weapon_model_meta;
- use project_cold_water::world::WeaponKind;
- let world = FoothillRiverTownMap.build();
- let bvh = AcousticBvh::build(world.acoustic_triangles.clone());
- let mut sim = Simulation::new(&world);
- let lib = ActorMeshLibrary::build();
- let s = sim.soldiers[0].clone();
- sim.player.deploy_into_soldier(&s);
- assert!(sim.player.active && sim.player.alive);
- // 1. Water safety: place player on dry west riverbank facing the water and try walking forward into water
- let bank_z = 35.0;
- let river_x = TerrainGrid::river_center_x_static(bank_z);
- sim.player.pos = sim.nav_grid.nearest_walkable(Vec3::new(river_x - 8.0, 3.0, bank_z));
- sim.player.yaw = std::f32::consts::FRAC_PI_2; // facing +X directly toward river!
- sim.player.pitch = 0.0;
- let walk_fwd = FpsInput {
- move_fwd: 1.0,
- ..Default::default()
- };
- for _ in 0..180 {
- sim.step_fps_player(1.0 / 60.0, &walk_fwd, &bvh);
- assert!(
- sim.nav_grid.is_walkable_world(sim.player.pos.x, sim.player.pos.z),
- "FPS player stepped into river/blocked cell at {:?}",
- sim.player.pos
- );
- }
- // 2. Bridge crossing: place player at west approach of bridge and walk +X across the river deck
- let bz = TerrainGrid::bridge_z();
- let bcx = TerrainGrid::river_center_x_static(bz);
- sim.player.pos = sim.nav_grid.nearest_walkable(Vec3::new(bcx - 16.0, 3.0, bz));
- for _ in 0..360 {
- sim.step_fps_player(1.0 / 60.0, &walk_fwd, &bvh);
- }
- assert!(
- sim.player.pos.x > bcx,
- "expected FPS player to cross over bridge past x={bcx}, got x={}",
- sim.player.pos.x
- );
- // 3. Test ALL 6 weapons: select -> verify ammo -> fire projectile + sound + recoil -> viewmodel -> reload!
- for kind in WeaponKind::ALL {
- sim.pending_sounds.clear();
- sim.projectiles.clear();
- sim.player.select_weapon(kind);
- assert_eq!(sim.player.weapon, kind);
- let meta = weapon_model_meta(kind);
- let spec = kind.spec();
- assert_eq!(sim.player.current_ammo().in_mag, meta.mag_capacity);
- // Cooldown elapse after switch
- for _ in 0..15 {
- sim.step_fps_player(1.0 / 60.0, &FpsInput::default(), &bvh);
- }
- // Fire one shot
- let fire_in = FpsInput {
- fire_held: true,
- fire_just_pressed: true,
- ..Default::default()
- };
- sim.step_fps_player(1.0 / 60.0, &fire_in, &bvh);
- assert_eq!(
- sim.player.current_ammo().in_mag,
- meta.mag_capacity - 1,
- "{kind:?} failed to consume ammo on fire"
- );
- assert!(
- sim.projectiles.iter().any(|p| p.from_player
- && if kind == WeaponKind::Rpg7v {
- p.kind == ProjectileKind::RpgRocket
- } else {
- p.kind == ProjectileKind::Bullet
- }),
- "{kind:?} failed to spawn player projectile"
- );
- assert!(
- sim.pending_sounds.iter().any(|ev| ev.kind == spec.sound),
- "{kind:?} failed to emit expected SoundKind {:?}",
- spec.sound
- );
- assert!(sim.player.recoil_kick_z > 0.0, "{kind:?} missing viewmodel recoil");
- let draws = sim.player.build_viewmodel_draws(
- sim.player.pos + Vec3::Y * 1.6,
- sim.player.forward(),
- sim.player.flat_right(),
- Vec3::Y,
- &lib,
- );
- // RPG-7V should hide PG-7V warhead while mag is empty (0/4)
- let has_warhead = draws.iter().any(|(s, _)| s.index_offset == lib.launcher_rpg_warhead.index_offset);
- if kind == WeaponKind::Rpg7v {
- assert!(!has_warhead, "RPG-7V warhead should vanish after firing");
- }
- // Reload and advance past reload_secs
- let rel_in = FpsInput {
- reload_pressed: true,
- ..Default::default()
- };
- sim.step_fps_player(1.0 / 60.0, &rel_in, &bvh);
- let reload_steps = ((meta.reload_secs + 0.25) * 60.0) as usize;
- for _ in 0..reload_steps {
- sim.step_fps_player(1.0 / 60.0, &FpsInput::default(), &bvh);
- }
- assert_eq!(
- sim.player.current_ammo().in_mag,
- meta.mag_capacity,
- "{kind:?} reload did not refill magazine"
- );
- if kind == WeaponKind::Rpg7v {
- let draws_reloaded = sim.player.build_viewmodel_draws(
- sim.player.pos + Vec3::Y * 1.6,
- sim.player.forward(),
- sim.player.flat_right(),
- Vec3::Y,
- &lib,
- );
- assert!(
- draws_reloaded.iter().any(|(s, _)| s.index_offset == lib.launcher_rpg_warhead.index_offset),
- "RPG-7V warhead should reappear after reload"
- );
- }
- }
- // 4. Verify SVD ADS triggers PSO-1 optic overlay
- sim.player.select_weapon(WeaponKind::Svd);
- let ads_in = FpsInput {
- ads_held: true,
- ..Default::default()
- };
- for _ in 0..45 {
- sim.step_fps_player(1.0 / 60.0, &ads_in, &bvh);
- }
- assert!(sim.player.is_pso1_overlay_active(), "SVD ADS should activate PSO-1 overlay");
- }
- #[test]
- fn test_fps_player_near_miss_suppression_spikes_and_decays() {
- use project_cold_water::sim::player::FpsInput;
- let world = FoothillRiverTownMap.build();
- 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);
- sim.player.suppression = 0.0;
- sim.projectiles.clear();
- // Spawn a Militia rifle round whistling 1.2m beside the FPS player's head
- let eye = sim.player.eye_position(&bvh);
- let near_miss_start = eye + Vec3::new(-6.0, 0.0, 1.2);
- sim.projectiles.push(Projectile {
- pos: near_miss_start,
- prev_pos: near_miss_start,
- vel: Vec3::new(820.0, 0.0, 0.0),
- kind: ProjectileKind::Bullet,
- faction: Faction::Militia,
- damage: 34.0,
- suppression: 0.30,
- blast_radius: 0.0,
- crater_radius: 0.0,
- drag: 0.0,
- age: 0.0,
- max_age: 1.0,
- is_tracer: true,
- crack_triggered: false,
- whistle_emitted: true,
- from_player: false,
- owner_player: None,
- visual_offset: Vec3::ZERO,
- guidance: Default::default(),
- guide_vehicle_id: None,
- is_heavy_ap: false,
- });
- let cfg = SimConfig::default();
- sim.step(&cfg, 331.5, &bvh, eye);
- assert!(
- sim.player.suppression > 0.15,
- "near-miss enemy bullet should spike FPS suppression (> 0.15), got {}",
- sim.player.suppression
- );
- // Advance 1.0 second with no further incoming rounds in the combined sim+FPS loop -> snappy decay
- for s in &mut sim.soldiers {
- if s.faction != sim.player.faction {
- s.alive = false;
- }
- }
- sim.projectiles.clear();
- sim.player.suppression = 1.0;
- if let Some(sid) = sim.player.soldier_id {
- sim.soldiers[sid].suppression = 1.0;
- }
- for _ in 0..60 {
- sim.step_fps_player(1.0 / 60.0, &FpsInput::default(), &bvh);
- sim.step(&cfg, 331.5, &bvh, eye);
- }
- assert!(
- sim.player.suppression < 0.05,
- "player suppression should decay snappily within 1s after calm period, got {}",
- sim.player.suppression
- );
- if let Some(sid) = sim.player.soldier_id {
- assert!(
- sim.soldiers[sid].suppression < 0.05,
- "controlled soldier suppression must stay synced and not latch high, got {}",
- sim.soldiers[sid].suppression
- );
- }
- }
- #[test]
- fn test_all_six_mission_objective_types_progress_and_complete() {
- use project_cold_water::sim::objectives::ObjectiveKind;
- use project_cold_water::sim::player::FpsInput;
- let world = FoothillRiverTownMap.build();
- let bvh = AcousticBvh::build(world.acoustic_triangles.clone());
- let mut sim = Simulation::new(&world);
- let cfg = SimConfig::default();
- // Verify all 6 requested objective archetypes exist in order
- assert_eq!(sim.mission.objectives.len(), 6);
- assert!(matches!(sim.mission.objectives[0].kind, ObjectiveKind::MoveToPosition));
- assert!(matches!(sim.mission.objectives[1].kind, ObjectiveKind::SuppressPosition { .. }));
- assert!(matches!(sim.mission.objectives[2].kind, ObjectiveKind::CallArtillery { .. }));
- assert!(matches!(sim.mission.objectives[3].kind, ObjectiveKind::AssaultPosition { .. }));
- assert!(matches!(sim.mission.objectives[4].kind, ObjectiveKind::ClearBuilding));
- assert!(matches!(sim.mission.objectives[5].kind, ObjectiveKind::DefendPosition { .. }));
- let f_soldier = sim.soldiers[0].clone();
- sim.player.deploy_into_soldier(&f_soldier);
- // 1. Move to Position -> completes when FPS player reaches Stage 1
- let p0 = sim.mission.objectives[0].position;
- sim.player.pos = p0;
- sim.step(&cfg, 331.5, &bvh, p0 + Vec3::Y * 1.6);
- assert_eq!(sim.mission.active_index, 1, "Stage 1 MoveToPosition should complete on arrival");
- // 2. Suppress Position -> fire / pin inside Stage 2 zone until complete
- let p1 = sim.mission.objectives[1].position;
- for _ in 0..240 {
- if sim.mission.active_index != 1 {
- break;
- }
- sim.projectiles.push(Projectile {
- pos: p1 + Vec3::new(0.0, 1.5, 0.0),
- prev_pos: p1 + Vec3::new(-2.0, 1.5, 0.0),
- vel: Vec3::new(800.0, 0.0, 0.0),
- kind: ProjectileKind::Bullet,
- faction: Faction::Federal,
- damage: 0.0,
- suppression: 0.25,
- blast_radius: 0.0,
- crater_radius: 0.0,
- drag: 0.0,
- age: 0.0,
- max_age: 0.2,
- is_tracer: false,
- crack_triggered: true,
- whistle_emitted: true,
- from_player: true,
- owner_player: None,
- visual_offset: Vec3::ZERO,
- guidance: Default::default(),
- guide_vehicle_id: None,
- is_heavy_ap: false,
- });
- sim.step(&cfg, 331.5, &bvh, p0 + Vec3::Y * 1.6);
- }
- assert_eq!(sim.mission.active_index, 2, "Stage 2 SuppressPosition should advance to CallArtillery");
- // 3. Call Artillery -> call_artillery_strike on Stage 3 target
- let p2 = sim.mission.objectives[2].position;
- assert!(sim.call_artillery_strike(p2));
- assert!(sim.mission.arty_cooldown > 5.0);
- assert!(sim.projectiles.iter().any(|p| p.kind == ProjectileKind::MortarShell));
- sim.step(&cfg, 331.5, &bvh, p0 + Vec3::Y * 1.6);
- assert_eq!(sim.mission.active_index, 3, "Stage 3 CallArtillery should advance to AssaultPosition");
- // 4. Assault Position -> clear immediate radius & hold inside Stage 4
- let p3 = sim.mission.objectives[3].position;
- for s in &mut sim.soldiers {
- if s.faction != Faction::Federal && s.pos.distance(p3) < 20.0 {
- s.alive = false;
- s.hp = 0.0;
- }
- }
- sim.player.pos = p3;
- sim.projectiles.clear();
- for _ in 0..280 {
- if sim.mission.active_index != 3 {
- break;
- }
- sim.step(&cfg, 331.5, &bvh, p3 + Vec3::Y * 1.6);
- }
- assert_eq!(sim.mission.active_index, 4, "Stage 4 AssaultPosition should advance to ClearBuilding");
- // 5. Clear Building -> move player into building zone and eliminate remaining defenders there
- let p4 = sim.mission.objectives[4].position;
- sim.player.pos = p4;
- for s in &mut sim.soldiers {
- if s.faction != Faction::Federal && Vec3::new(s.pos.x - p4.x, 0.0, s.pos.z - p4.z).length() < 26.0 {
- s.alive = false;
- s.hp = 0.0;
- }
- }
- sim.step(&cfg, 331.5, &bvh, p4 + Vec3::Y * 1.6);
- assert_eq!(sim.mission.active_index, 5, "Stage 5 ClearBuilding should advance to DefendPosition");
- assert!(sim.mission.counterattack_triggered, "Entering Defend stage should trigger enemy counterattack");
- // 6. Defend Position -> hold inside defend perimeter for duration_secs -> Operation Complete!
- let p5 = sim.mission.objectives[5].position;
- sim.player.pos = p5;
- for _ in 0..1600 {
- if sim.mission.completed {
- break;
- }
- // Keep player alive during automated defense test
- sim.player.hp = 100.0;
- sim.player.alive = true;
- if let Some(sid) = sim.player.soldier_id {
- sim.soldiers[sid].hp = 100.0;
- sim.soldiers[sid].alive = true;
- }
- sim.step_fps_player(1.0 / 60.0, &FpsInput::default(), &bvh);
- sim.step(&cfg, 331.5, &bvh, p5 + Vec3::Y * 1.6);
- }
- assert!(sim.mission.completed, "Stage 6 DefendPosition should complete the entire operation");
- }
- #[test]
- fn test_dynamic_map_generator_all_archetypes_and_connected_points() {
- use project_cold_water::world::generator::{DynamicMapGenerator, MapArchetype, MapGenConfig};
- use project_cold_water::world::points::{ObjectiveRole, SpawnRole};
- use project_cold_water::world::HeightQuery;
- for &archetype in &MapArchetype::ALL {
- let cfg = MapGenConfig::for_archetype(archetype, 1999);
- let world = DynamicMapGenerator::new(cfg.clone()).build();
- let graph = &world.point_graph;
- // 1. Center of Operations + all 6 tactical ObjectivePoints exist
- assert!(
- graph.center_of_operations().is_some(),
- "{:?} missing CenterOfOperations objective",
- archetype
- );
- assert_eq!(graph.objectives.len(), 6, "{:?} expected 6 objectives", archetype);
- let coo = graph.center_of_operations().unwrap();
- assert_eq!(coo.role, ObjectiveRole::CenterOfOperations);
- // 2. Every ObjectivePoint has valid connected SpawnPoints (bidirectional integrity)
- for obj in &graph.objectives {
- assert!(
- !obj.connected_spawn_ids.is_empty(),
- "{:?} objective {} has zero connected spawns",
- archetype,
- obj.name
- );
- let linked = graph.spawns_for_objective(obj.id, None);
- assert_eq!(linked.len(), obj.connected_spawn_ids.len());
- for sp in linked {
- assert_eq!(sp.linked_objective_id, obj.id);
- assert!(
- world.nav_grid.is_walkable_world(sp.position.x, sp.position.z),
- "{:?} spawn {} not on walkable nav cell",
- archetype,
- sp.id
- );
- }
- }
- assert!(
- graph.reinforcement_spawn_for(coo.id, Faction::Militia).is_some(),
- "{:?} missing connected ReinforcementSpawn for CenterOfOperations",
- archetype
- );
- assert!(
- graph.spawns.iter().any(|s| s.role == SpawnRole::InitialSquadSpawn),
- "{:?} missing InitialSquadSpawn",
- archetype
- );
- // 3. Pathfinding connects staging spawn to Center of Operations across bridges if river present
- let fed_spawn = graph
- .spawns
- .iter()
- .find(|s| s.role == SpawnRole::InitialSquadSpawn && s.faction == Faction::Federal)
- .expect("federal staging spawn")
- .position;
- let path = world.nav_grid.find_path(fed_spawn, coo.position);
- let last_wp = *path.last().expect("path must be non-empty");
- assert!(
- last_wp.distance(coo.position) < 3.0,
- "{:?}: no navigable path from staging spawn {:?} to COO {:?} (ended at {:?})",
- archetype,
- fed_spawn,
- coo.position,
- last_wp
- );
- if world.height_grid.params.has_river {
- for pt in &path {
- let h = world.height_grid.height_at(pt.x, pt.z);
- let on_bridge = world.nav_grid.surface_height(pt.x, pt.z, &world.height_grid)
- > world.height_grid.water_level + 0.5;
- assert!(
- h >= world.height_grid.water_level + 0.1 || on_bridge,
- "{:?} path crossed deep water at ({:.1}, {:.1})",
- archetype,
- pt.x,
- pt.z
- );
- }
- }
- // 4. Simulation boots cleanly from point_graph and ticks 60 frames without crossing water
- let bvh = AcousticBvh::build(world.acoustic_triangles.clone());
- let mut sim = Simulation::new(&world);
- assert_eq!(sim.mission.objectives.len(), 6);
- let sim_cfg = SimConfig::default();
- for _ in 0..60 {
- sim.step(&sim_cfg, 331.5, &bvh, fed_spawn + Vec3::Y * 4.0);
- }
- if world.height_grid.params.has_river {
- for s in &sim.soldiers {
- if s.alive {
- let on_bridge = world.nav_grid.surface_height(s.pos.x, s.pos.z, &world.height_grid)
- > world.height_grid.water_level + 0.5;
- let terrain_h = world.height_grid.height_at(s.pos.x, s.pos.z);
- assert!(
- on_bridge || terrain_h >= world.height_grid.water_level + 0.1,
- "{:?}: soldier #{} walked into water",
- archetype,
- s.id
- );
- }
- }
- }
- }
- }
- #[test]
- fn test_stitched_corridor_and_quad_maps_with_transitions() {
- use project_cold_water::world::generator::{DynamicMapGenerator, MapGenConfig};
- use project_cold_water::world::points::{ObjectiveRole, SpawnRole};
- use project_cold_water::world::terrain::{TerrainGrid, ZoneType};
- use project_cold_water::world::HeightQuery;
- let cases = [
- (
- "corridor_wet",
- MapGenConfig::stitched_corridor(
- [ZoneType::FoothillRidge, ZoneType::RiverCrossing, ZoneType::SovietCityCore],
- 2025,
- ),
- true,
- glam::Vec2::new(-68.0, 0.0),
- ),
- (
- "quad_wet",
- MapGenConfig::stitched_quad(
- [
- ZoneType::FoothillRidge,
- ZoneType::IndustrialOutskirts,
- ZoneType::RiverCrossing,
- ZoneType::SovietCityCore,
- ],
- 2026,
- ),
- true,
- glam::Vec2::new(0.0, 0.0),
- ),
- (
- "corridor_dry",
- MapGenConfig::stitched_corridor(
- [ZoneType::FoothillRidge, ZoneType::SuburbanTown, ZoneType::IndustrialOutskirts],
- 2027,
- ),
- false,
- glam::Vec2::new(-68.0, 0.0),
- ),
- ];
- for (label, cfg, expect_water, seam_center) in cases {
- let world = DynamicMapGenerator::new(cfg).build();
- assert_eq!(world.water_indices.is_empty(), !expect_water, "{label}: water mismatch");
- // 1. Verify smooth normalized zone blending across transition seam
- let mut saw_blended = false;
- for step in -6..=6 {
- let sx = seam_center.x + step as f32 * 4.0;
- let weights = TerrainGrid::evaluate_zone_weights(&world.height_grid.params, sx, seam_center.y);
- let sum: f32 = weights.iter().map(|&(_, w)| w).sum();
- assert!((sum - 1.0).abs() < 1e-3, "{label}: zone weights did not normalize ({sum})");
- if weights.iter().any(|&(_, w)| w > 0.15 && w < 0.85) {
- saw_blended = true;
- }
- }
- assert!(saw_blended, "{label}: expected blended transition weights near seam {:?}", seam_center);
- // 2. Verify smooth road elevation continuity (no sharp cliff drops per 3m step)
- if let Some(primary_road) = world.height_grid.params.roads.first().copied() {
- let rz = primary_road.coord;
- let mut prev_y = world.nav_grid.surface_height(-150.0, rz, &world.height_grid);
- let mut x = -147.0_f32;
- while x <= 150.0 {
- let y = world.nav_grid.surface_height(x, rz, &world.height_grid);
- let on_river = world.height_grid.params.has_river
- && (x - world.height_grid.river_center_x_at(rz)).abs() < 16.0;
- if !on_river {
- assert!(
- (y - prev_y).abs() <= 2.2,
- "{label}: sharp height jump {:.2}m at road x={x:.1}, z={rz:.1}",
- (y - prev_y).abs()
- );
- }
- prev_y = y;
- x += 3.0;
- }
- }
- // 3. Connected Point Graph + COO + NavGrid reachability
- let graph = &world.point_graph;
- let coo = graph.center_of_operations().expect("missing COO");
- assert_eq!(coo.role, ObjectiveRole::CenterOfOperations);
- assert_eq!(graph.objectives.len(), 6);
- for obj in &graph.objectives {
- assert!(!obj.connected_spawn_ids.is_empty(), "{label}: objective {} unlinked", obj.name);
- }
- assert!(graph.reinforcement_spawn_for(coo.id, Faction::Militia).is_some());
- let fed_spawn = graph
- .spawns
- .iter()
- .find(|s| s.role == SpawnRole::InitialSquadSpawn && s.faction == Faction::Federal)
- .expect("federal spawn")
- .position;
- let path = world.nav_grid.find_path(fed_spawn, coo.position);
- let last_wp = *path.last().expect("non-empty path");
- assert!(
- last_wp.distance(coo.position) < 4.5,
- "{label}: unreachable COO from {:?} (ended at {:?})",
- fed_spawn,
- last_wp
- );
- // 4. Simulation stability over 60 ticks with zero water crossings
- let bvh = AcousticBvh::build(world.acoustic_triangles.clone());
- let mut sim = Simulation::new(&world);
- let sim_cfg = SimConfig::default();
- for _ in 0..60 {
- sim.step(&sim_cfg, 331.5, &bvh, fed_spawn + Vec3::Y * 4.0);
- }
- if world.height_grid.params.has_river {
- for s in &sim.soldiers {
- if s.alive {
- let on_bridge = world.nav_grid.surface_height(s.pos.x, s.pos.z, &world.height_grid)
- > world.height_grid.water_level + 0.5;
- let terrain_h = world.height_grid.height_at(s.pos.x, s.pos.z);
- assert!(
- on_bridge || terrain_h >= world.height_grid.water_level + 0.1,
- "{label}: soldier #{} walked into water",
- s.id
- );
- }
- }
- }
- }
- }
- #[test]
- fn test_swept_capsule_hit_detection_open_field_headshot_wall_occlusion_and_point_blank() {
- use project_cold_water::sim::ballistics::{
- intersect_soldier_hitbox, HitZone, SoldierHitbox,
- };
- use project_cold_water::sim::player::{FpsInput, HitMarkerKind};
- use project_cold_water::world::actors_mesh::ActorPosture;
- use project_cold_water::world::WeaponKind;
- let world = FoothillRiverTownMap.build();
- let bvh = AcousticBvh::build(world.acoustic_triangles.clone());
- let mut sim = Simulation::new(&world);
- let cfg = SimConfig::default();
- // Clear 28m open-field meadow lane on west bank (`(-68, -12)` -> `(-40, -12)`)
- let p_origin = world.nav_grid.nearest_walkable(Vec3::new(-68.0, 3.0, -12.0));
- let target_pos = world.nav_grid.nearest_walkable(Vec3::new(-40.0, 3.0, -12.0));
- let fed_id = sim.soldiers.iter().position(|s| s.faction == Faction::Federal).unwrap();
- let mil_id = sim.soldiers.iter().position(|s| s.faction == Faction::Militia).unwrap();
- for (i, s) in sim.soldiers.iter_mut().enumerate() {
- if i != fed_id && i != mil_id {
- s.alive = false;
- s.hp = 0.0;
- }
- }
- sim.soldiers[fed_id].pos = p_origin;
- sim.soldiers[fed_id].alive = true;
- sim.soldiers[fed_id].hp = 100.0;
- sim.soldiers[mil_id].pos = target_pos;
- sim.soldiers[mil_id].move_target = target_pos;
- sim.soldiers[mil_id].cover_node = None;
- sim.soldiers[mil_id].alive = true;
- sim.soldiers[mil_id].hp = 200.0;
- sim.soldiers[mil_id].posture = ActorPosture::Standing;
- sim.soldiers[mil_id].fire_timer = 999.0;
- let shooter = sim.soldiers[fed_id].clone();
- sim.player.deploy_into_soldier(&shooter);
- sim.player.select_weapon(WeaponKind::Ak74m);
- sim.player.ads_blend = 1.0;
- let aim_at = |player: &mut project_cold_water::sim::player::FpsPlayerState, b: &AcousticBvh, pt: Vec3| {
- let eye = player.eye_position(b);
- let d = (pt - eye).normalize();
- player.yaw = d.x.atan2(-d.z);
- player.pitch = d.y.asin();
- };
- // Case A: Open-Field Direct Chest Hit (~32m, no wall behind target)
- let chest = target_pos + Vec3::new(0.0, 1.12, 0.0);
- aim_at(&mut sim.player, &bvh, chest);
- sim.player.fire_cooldown = 0.0;
- sim.step_fps_player(1.0 / 60.0, &FpsInput { fire_held: true, ads_held: true, ..Default::default() }, &bvh);
- for _ in 0..8 {
- sim.soldiers[mil_id].fire_timer = 999.0;
- sim.step(&cfg, 331.5, &bvh, p_origin + Vec3::Y * 1.6);
- }
- assert!(sim.soldiers[mil_id].hp < 195.0, "Open-field chest shot failed to register hit! hp={}", sim.soldiers[mil_id].hp);
- assert!(sim.player.hit_marker_timer > 0.0, "Missing hit marker on open-field chest hit");
- assert!(sim.projectiles.is_empty(), "Bullet should terminate upon striking soldier");
- // Case B: Open-Field Headshot (2.2x damage + Headshot/Kill marker)
- sim.soldiers[mil_id].hp = 200.0;
- sim.player.select_weapon(WeaponKind::Svd);
- sim.player.ads_blend = 1.0;
- sim.player.fire_cooldown = 0.0;
- let head = SoldierHitbox::from_soldier(&sim.soldiers[mil_id]).head_center;
- aim_at(&mut sim.player, &bvh, head);
- sim.step_fps_player(1.0 / 60.0, &FpsInput { fire_just_pressed: true, ads_held: true, ..Default::default() }, &bvh);
- for _ in 0..8 {
- sim.soldiers[mil_id].fire_timer = 999.0;
- sim.step(&cfg, 331.5, &bvh, p_origin + Vec3::Y * 1.6);
- }
- let dmg_dealt = 200.0 - sim.soldiers[mil_id].hp;
- assert!(dmg_dealt > 85.0 * 1.8, "Expected 2.2x SVD headshot damage (>153), got {dmg_dealt}");
- assert!(
- matches!(sim.player.hit_marker_kind, HitMarkerKind::Headshot | HitMarkerKind::Kill),
- "Expected Headshot or Kill hitmarker, got {:?}",
- sim.player.hit_marker_kind
- );
- // Case C: Point-Blank Shot (0.6m directly in front of eye)
- sim.soldiers[mil_id].alive = true;
- sim.soldiers[mil_id].hp = 100.0;
- sim.soldiers[mil_id].posture = ActorPosture::Standing;
- let close_pos = sim.player.pos + Vec3::new(0.6, 0.0, 0.0);
- sim.soldiers[mil_id].pos = close_pos;
- sim.soldiers[mil_id].move_target = close_pos;
- aim_at(&mut sim.player, &bvh, close_pos + Vec3::new(0.0, 1.25, 0.0));
- sim.player.fire_cooldown = 0.0;
- sim.player.hit_marker_timer = 0.0;
- sim.step_fps_player(1.0 / 60.0, &FpsInput { fire_just_pressed: true, ads_held: true, ..Default::default() }, &bvh);
- sim.soldiers[mil_id].fire_timer = 999.0;
- sim.step(&cfg, 331.5, &bvh, p_origin + Vec3::Y * 1.6);
- assert!(sim.soldiers[mil_id].hp < 100.0, "Point-blank shot tunneled past enemy!");
- // Case D: Wall Occlusion (brick wall between shooter and enemy blocks bullet completely)
- let wall_bvh = AcousticBvh::build(
- make_quad_tris(
- Vec3::new(-2.0, -1.0, -5.0),
- Vec3::new(-2.0, 6.0, -5.0),
- Vec3::new(-2.0, 6.0, 5.0),
- Vec3::new(-2.0, -1.0, 5.0),
- MaterialId::Concrete,
- )
- .to_vec(),
- );
- sim.soldiers[mil_id].alive = true;
- sim.soldiers[mil_id].hp = 100.0;
- sim.soldiers[mil_id].pos = Vec3::new(4.0, 0.0, 0.0);
- sim.soldiers[mil_id].move_target = Vec3::new(4.0, 0.0, 0.0);
- let hb_wall = SoldierHitbox::from_soldier(&sim.soldiers[mil_id]);
- let mut occ_projs = vec![Projectile {
- pos: Vec3::new(-6.0, 1.2, 0.0),
- prev_pos: Vec3::new(-6.0, 1.2, 0.0),
- vel: Vec3::new(880.0, 0.0, 0.0),
- kind: ProjectileKind::Bullet,
- faction: Faction::Federal,
- damage: 34.0,
- suppression: 0.2,
- blast_radius: 0.0,
- crater_radius: 0.0,
- drag: 0.0,
- age: 0.0,
- max_age: 1.0,
- is_tracer: false,
- crack_triggered: true,
- whistle_emitted: true,
- from_player: true,
- owner_player: None,
- visual_offset: Vec3::ZERO,
- guidance: Default::default(),
- guide_vehicle_id: None,
- is_heavy_ap: false,
- }];
- let mut occ_hits = Vec::new();
- let mut dummy_s = Vec::new();
- let mut dummy_i = Vec::new();
- let mut dummy_e = Vec::new();
- let mut dummy_t = Vec::new();
- let mut dummy_l = Vec::new();
- step_projectiles(
- &mut occ_projs,
- 0.03,
- 331.5,
- &wall_bvh,
- &[hb_wall],
- Vec3::ZERO,
- &mut dummy_s,
- &mut occ_hits,
- &mut dummy_i,
- &mut dummy_e,
- &mut dummy_t,
- &mut dummy_l,
- );
- assert!(occ_hits.is_empty(), "Bullet penetrated wall BVH to hit enemy behind wall!");
- assert!(!dummy_i.is_empty(), "Bullet should have impacted the wall BVH");
- // Case E: Near-Miss Does Not Deal Phantom Ground-Splash Damage
- let side_hit = intersect_soldier_hitbox(
- Vec3::new(-6.0, 1.1, 1.0),
- Vec3::X,
- 20.0,
- &hb_wall,
- );
- assert!(side_hit.is_none(), "1.0m side miss should not hit soldier hitbox");
- // Case F: Crouched Hitbox Respects Lower Stance Height
- let mut crouched = sim.soldiers[mil_id].clone();
- crouched.pos = Vec3::ZERO;
- crouched.posture = ActorPosture::Crouched;
- let hb_crouch = SoldierHitbox::from_soldier(&crouched);
- assert!(
- intersect_soldier_hitbox(Vec3::new(-5.0, 1.68, 0.0), Vec3::X, 15.0, &hb_crouch).is_none(),
- "High shot at y=1.68 should pass cleanly over crouched soldier head"
- );
- let crouch_chest = intersect_soldier_hitbox(Vec3::new(-5.0, 0.90, 0.0), Vec3::X, 15.0, &hb_crouch);
- assert!(
- matches!(crouch_chest, Some((_, HitZone::Torso | HitZone::Head))),
- "Chest-level shot at y=0.90 should hit crouched soldier, got {:?}",
- crouch_chest
- );
- }
- #[test]
- fn test_game_director_spawning_recycling_objectives_and_player_respawn() {
- use project_cold_water::sim::director::{GmEntityPreset, GmSelection};
- use project_cold_water::sim::objectives::ObjectiveKind;
- use project_cold_water::world::{WeaponKind, MAX_SKINNED_SOLDIERS};
- let world = FoothillRiverTownMap.build();
- let bvh = AcousticBvh::build(world.acoustic_triangles.clone());
- let mut sim = Simulation::new(&world);
- let cfg = SimConfig::default();
- // 1. Default PlayerSpawnPoints are populated for both factions
- assert!(sim.player_spawns.iter().any(|s| s.active && s.faction == Faction::Federal));
- assert!(sim.player_spawns.iter().any(|s| s.active && s.faction == Faction::Militia));
- // 2. GM places Federal squad, Militia warband, teleport, heal, custom objective & smoke screen
- sim.director.active = true;
- sim.gm_place_preset(GmEntityPreset::FedRifleSquad, Vec3::new(-44.0, 3.0, -14.0));
- let fed_sq = match sim.director.selection {
- GmSelection::Squad(id) => id,
- other => panic!("expected squad selection after GM spawn, got {:?}", other),
- };
- assert!(sim.squads[fed_sq].alive_count(&sim.soldiers) >= 4);
- // Damage and heal squad
- for &id in &sim.squads[fed_sq].member_ids {
- sim.soldiers[id].hp = 35.0;
- sim.soldiers[id].suppression = 0.8;
- }
- sim.gm_heal_squad(fed_sq);
- for &id in &sim.squads[fed_sq].member_ids {
- assert_eq!(sim.soldiers[id].hp, 100.0);
- assert_eq!(sim.soldiers[id].suppression, 0.0);
- }
- // Teleport squad safely onto east bank
- sim.gm_teleport_squad(fed_sq, Vec3::new(26.0, 3.0, -6.0));
- assert!(sim.squads[fed_sq].center_pos(&sim.soldiers).x > 10.0);
- // Custom GM objective injection & activation
- let prev_objs = sim.mission.objectives.len();
- sim.gm_place_preset(GmEntityPreset::ObjAssault, Vec3::new(32.0, 3.0, 6.0));
- assert_eq!(sim.mission.objectives.len(), prev_objs + 1);
- assert!(matches!(
- sim.mission.active_objective().unwrap().kind,
- ObjectiveKind::AssaultPosition { .. }
- ));
- // Smoke screen spawns long-lived puffs
- sim.gm_place_preset(GmEntityPreset::SmokeScreen, Vec3::new(10.0, 3.0, 0.0));
- assert!(sim.smoke_puffs.len() >= 20);
- // 3. Dead-slot recycling past MAX_SKINNED_SOLDIERS = 192
- for _ in 0..(MAX_SKINNED_SOLDIERS / 5 + 3) {
- sim.gm_place_preset(GmEntityPreset::MilFighterBand, Vec3::new(42.0, 3.0, 12.0));
- if let GmSelection::Squad(sq_id) = sim.director.selection {
- assert!(sim.squads[sq_id].alive_count(&sim.soldiers) > 0);
- sim.gm_delete_squad(sq_id);
- }
- }
- assert!(
- sim.soldiers.len() <= MAX_SKINNED_SOLDIERS,
- "GM dead-slot recycler exceeded MAX_SKINNED_SOLDIERS ({})",
- sim.soldiers.len()
- );
- // Spawning a fresh squad after hitting capacity still succeeds cleanly
- sim.gm_place_preset(GmEntityPreset::MilSniperPair, Vec3::new(40.0, 3.0, -10.0));
- let mil_sq = match sim.director.selection {
- GmSelection::Squad(id) => id,
- _ => panic!("expected militia squad selection"),
- };
- assert_eq!(sim.squads[mil_sq].alive_count(&sim.soldiers), 2);
- // 4. Custom GM PlayerSpawnPoint + Player KIA -> Countdown -> Respawn Flow
- let gm_spawn_pos = world.nav_grid.nearest_walkable(Vec3::new(-32.0, 3.0, -12.0));
- let gm_spawn_id = sim.gm_add_player_spawn(Faction::Federal, gm_spawn_pos);
- assert!(sim.spawn_player_at(gm_spawn_id, WeaponKind::Ak74m));
- assert!(sim.player.active && sim.player.alive);
- // Kill player and verify automatic KIA countdown + deploy menu open
- let psid = sim.player.soldier_id.unwrap();
- sim.soldiers[psid].hp = 0.0;
- sim.soldiers[psid].alive = false;
- sim.respawn.respawn_delay_secs = 0.5;
- for _ in 0..45 {
- sim.step(&cfg, 331.5, &bvh, gm_spawn_pos + Vec3::Y * 4.0);
- }
- assert!(!sim.player.alive);
- assert!(sim.respawn.menu_open, "KIA must automatically open respawn menu");
- assert_eq!(sim.respawn.respawn_countdown, 0.0, "Respawn countdown should finish after 0.75s");
- // Respawn player with PKM at the GM spawn point!
- assert!(sim.spawn_player_at(gm_spawn_id, WeaponKind::Pkm));
- assert!(sim.player.active && sim.player.alive);
- assert_eq!(sim.player.hp, 100.0);
- assert_eq!(sim.player.weapon, WeaponKind::Pkm);
- assert!(!sim.respawn.menu_open);
- assert!(sim.player.pos.distance(gm_spawn_pos) < 3.0);
- let new_psid = sim.player.soldier_id.unwrap();
- assert!(sim.soldiers[new_psid].alive);
- }
- #[test]
- fn test_phase1_ai_reaction_delay_aim_settling_suppression_and_192_capacity() {
- use project_cold_water::core::config::AiSkillLevel;
- use project_cold_water::sim::ai::compute_ai_shot_spread;
- use project_cold_water::sim::director::GmEntityPreset;
- use project_cold_water::world::actors_mesh::{ActorPosture, ActorRenderBatch};
- use project_cold_water::world::MAX_SKINNED_SOLDIERS;
- assert_eq!(MAX_SKINNED_SOLDIERS, 192);
- let world = FoothillRiverTownMap.build();
- let bvh = AcousticBvh::build(world.acoustic_triangles.clone());
- let mut sim = Simulation::new(&world);
- let cfg = SimConfig::default();
- // Isolate one Federal soldier and one Militia soldier 28m apart in clear west meadow
- let p_fed = world.nav_grid.nearest_walkable(Vec3::new(-68.0, 3.0, -12.0));
- let p_mil = world.nav_grid.nearest_walkable(Vec3::new(-40.0, 3.0, -12.0));
- let fed_id = sim.soldiers.iter().position(|s| s.faction == Faction::Federal).unwrap();
- let mil_id = sim.soldiers.iter().position(|s| s.faction == Faction::Militia).unwrap();
- for (i, s) in sim.soldiers.iter_mut().enumerate() {
- if i != fed_id && i != mil_id {
- s.alive = false;
- s.hp = 0.0;
- }
- }
- sim.soldiers[fed_id].pos = p_fed;
- sim.soldiers[fed_id].move_target = p_fed;
- sim.soldiers[fed_id].cover_node = None;
- sim.soldiers[fed_id].hp = 500.0;
- sim.soldiers[fed_id].yaw = std::f32::consts::FRAC_PI_2;
- sim.soldiers[fed_id].fire_timer = 999.0;
- sim.soldiers[mil_id].pos = p_mil;
- sim.soldiers[mil_id].move_target = p_mil;
- sim.soldiers[mil_id].cover_node = None;
- sim.soldiers[mil_id].hp = 500.0;
- sim.soldiers[mil_id].yaw = -std::f32::consts::FRAC_PI_2; // facing fed_id
- sim.soldiers[mil_id].posture = ActorPosture::Standing;
- sim.soldiers[mil_id].fire_timer = 0.0;
- sim.soldiers[mil_id].shots_fired = 0;
- // A1. Spotting reaction delay: after 10 ticks (~0.17s), defender is still recognizing target & hasn't laser-fired
- for _ in 0..10 {
- sim.soldiers[fed_id].fire_timer = 999.0;
- sim.step(&cfg, 331.5, &bvh, p_fed + Vec3::Y * 4.0);
- }
- assert_eq!(
- sim.soldiers[mil_id].shots_fired, 0,
- "AI should not fire instantaneously within first 0.17s (spot_progress={})",
- sim.soldiers[mil_id].spot_progress
- );
- assert!(sim.soldiers[mil_id].spot_progress > 0.1 && sim.soldiers[mil_id].spot_progress < 1.0);
- // A2. After completing spot reaction (< 1.25s), AI spots & opens suppressive fire
- for _ in 0..65 {
- sim.soldiers[fed_id].fire_timer = 999.0;
- sim.step(&cfg, 331.5, &bvh, p_fed + Vec3::Y * 4.0);
- }
- assert!(sim.soldiers[mil_id].spot_progress >= 1.0);
- assert!(sim.soldiers[mil_id].shots_fired > 0, "AI failed to engage after spotting");
- // A3. Vision cone + Gunfire hearing alert: turn mil_id 180 deg away from silent fed_id
- sim.projectiles.clear();
- sim.soldiers[mil_id].yaw = std::f32::consts::FRAC_PI_2; // facing east, away from -68
- sim.soldiers[mil_id].spot_target = None;
- sim.soldiers[mil_id].spot_progress = 0.0;
- sim.soldiers[mil_id].alert_pos = None;
- sim.soldiers[mil_id].alert_timer = 0.0;
- let initial_yaw = sim.soldiers[mil_id].yaw;
- for _ in 0..30 {
- sim.soldiers[fed_id].fire_timer = 999.0;
- sim.step(&cfg, 331.5, &bvh, p_fed + Vec3::Y * 4.0);
- }
- assert_eq!(sim.soldiers[mil_id].spot_progress, 0.0, "Blind spot behind soldier should not spot silent target 28m away");
- // Fire a shot within hearing_range (28m < 88m) -> mil_id hears it & turns toward shooter!
- sim.trigger_test_shot(p_fed + Vec3::Y * 1.4, Vec3::Z, SoundKind::Ak74mShot);
- for _ in 0..8 {
- sim.soldiers[fed_id].fire_timer = 999.0;
- sim.step(&cfg, 331.5, &bvh, p_fed + Vec3::Y * 4.0);
- }
- assert!(sim.soldiers[mil_id].alert_pos.is_some(), "Nearby gunshot should trigger AI hearing alert");
- assert!(
- (sim.soldiers[mil_id].yaw - initial_yaw).abs() > 0.2,
- "Hearing alert should rotate soldier toward threat"
- );
- // B. Aim settling, suppression, movement & Skill preset accuracy curves
- let base = 0.024;
- let s_open = compute_ai_shot_spread(base, AiSkillLevel::Regular, 0.0, 0.0, false, false, 40.0);
- let s_settled = compute_ai_shot_spread(base, AiSkillLevel::Regular, 1.0, 0.0, false, false, 40.0);
- let s_moving = compute_ai_shot_spread(base, AiSkillLevel::Regular, 1.0, 0.0, true, false, 40.0);
- let s_supp = compute_ai_shot_spread(base, AiSkillLevel::Regular, 1.0, 0.85, false, false, 40.0);
- let s_spets = compute_ai_shot_spread(base, AiSkillLevel::Spetsnaz, 1.0, 0.0, false, false, 40.0);
- let s_con = compute_ai_shot_spread(base, AiSkillLevel::Conscript, 1.0, 0.0, false, false, 40.0);
- assert!(s_open > s_settled * 2.0, "Opening shot spread must be >2x settled spread");
- assert!(s_moving > s_settled * 1.5, "Moving shot spread must degrade accuracy");
- assert!(s_supp > s_settled * 3.0, "Heavy suppression must heavily degrade accuracy");
- assert!(s_spets < s_settled && s_settled < s_con);
- // C. 192-Actor Capacity: Spawn >100 simultaneous live soldiers & pack ActorRenderBatch cleanly
- let mut cap_sim = Simulation::new(&world);
- for k in 0..16 {
- let z = -30.0 + (k as f32) * 3.5;
- cap_sim.gm_place_preset(GmEntityPreset::FedRifleSquad, Vec3::new(-44.0, 3.0, z));
- }
- let (fed_cnt, mil_cnt) = cap_sim.alive_counts();
- let total_live = fed_cnt + mil_cnt;
- assert!(total_live > 100 && total_live <= MAX_SKINNED_SOLDIERS, "Unexpected total_live={total_live}");
- let mut batch = ActorRenderBatch::default();
- cap_sim.build_actor_batch(Some(0), &mut batch);
- assert_eq!(batch.soldier_count as usize, total_live);
- }
- #[test]
- fn test_3km_chunked_theater_lod_and_hierarchical_nav() {
- use project_cold_water::world::generator::{DynamicMapGenerator, MapGenConfig};
- let t0 = std::time::Instant::now();
- let world = DynamicMapGenerator::new(MapGenConfig::macro_theater_3km(4242)).build();
- let elapsed = t0.elapsed();
- assert!(elapsed.as_secs_f32() < 4.5, "3km theater took too long to build: {:?}", elapsed);
- assert_eq!(world.world_half_extent, 1536.0);
- let chunks = world
- .terrain_chunks
- .as_ref()
- .expect("3km theater must emit TerrainChunkMesh");
- assert_eq!(chunks.chunks.len(), 256, "Expected 16x16 terrain chunks");
- for ch in &chunks.chunks {
- assert!(ch.lods[0].index_count > ch.lods[1].index_count);
- assert!(ch.lods[1].index_count > ch.lods[2].index_count);
- assert!(ch.lods[2].index_count > 0);
- }
- assert!(world.nav_grid.is_hierarchical, "3km theater should bake coarse hierarchical NavGrid");
- assert!(world.nav_grid.bridges.len() >= 3, "3km theater must stamp 3 cross-river highway bridges");
- // Verify coarse regional vehicle route spans >900m from West bank (-520, 0) across central bridge to East bank (520, 0)
- let west = world.nav_grid.nearest_walkable(Vec3::new(-520.0, 0.0, 0.0));
- let east = world.nav_grid.nearest_walkable(Vec3::new(520.0, 0.0, 0.0));
- let path = world.nav_grid.find_vehicle_path(west, east);
- let end = path.last().copied().unwrap_or(west);
- assert!(
- end.distance(east) < 18.0,
- "Hierarchical vehicle path failed to reach East bank across 3km river! end={:?} east={:?}",
- end,
- east
- );
- for p in &path {
- assert!(world.nav_grid.is_walkable_world(p.x, p.z), "Vehicle waypoint {:?} fell into blocked river", p);
- }
- }
- #[test]
- fn test_vehicles_driving_suspension_btr_armor_turret_and_dismount() {
- use project_cold_water::sim::vehicles::{VehicleInput, VehicleSeatRole};
- use project_cold_water::world::actors_mesh::ActorRenderBatch;
- use project_cold_water::world::VehicleKind;
- let world = FoothillRiverTownMap.build();
- let bvh = AcousticBvh::build(world.acoustic_triangles.clone());
- let mut sim = Simulation::new(&world);
- let cfg = SimConfig::default();
- // Verify all 3 vehicle meshes exist cleanly in ActorMeshLibrary
- assert!(!sim.vehicles.is_empty());
- let uaz_idx = sim
- .vehicles
- .iter()
- .position(|v| v.kind == VehicleKind::Uaz469)
- .expect("UAZ-469 starter missing");
- let btr_idx = sim
- .vehicles
- .iter()
- .position(|v| v.kind == VehicleKind::Btr80)
- .expect("BTR-80 starter missing");
- // 1. Player deploys on foot, walks beside UAZ-469, enters [F], drives forward, switches seats, and exits [F]
- let s0 = sim.soldiers[0].clone();
- sim.player.deploy_into_soldier(&s0);
- sim.player.pos = sim.vehicles[uaz_idx].pos + Vec3::new(0.0, 0.0, 2.0);
- assert!(sim.try_player_toggle_vehicle().is_some(), "Should enter nearby UAZ-469");
- assert_eq!(sim.player.in_vehicle, Some((uaz_idx, 0)));
- let start_pos = sim.vehicles[uaz_idx].pos;
- let drive_in = VehicleInput {
- throttle: 1.0,
- steer: 0.25,
- ..Default::default()
- };
- for _ in 0..45 {
- sim.step_with_vehicle_input(&cfg, 331.5, &bvh, start_pos, Some(&drive_in));
- }
- assert!(
- sim.vehicles[uaz_idx].pos.distance(start_pos) > 3.0,
- "Driven UAZ-469 did not accelerate forward! delta={}",
- sim.vehicles[uaz_idx].pos.distance(start_pos)
- );
- sim.try_player_toggle_vehicle();
- assert!(sim.player.in_vehicle.is_none(), "Player should exit vehicle cleanly");
- // 2. BTR-80 Armor Immunity vs Small Arms & Gunner 14.5mm KPVT Fire
- let btr_hp_before = sim.vehicles[btr_idx].hp;
- let btr_p = sim.vehicles[btr_idx].pos + Vec3::Y * 1.1;
- // Militia 5.45/7.62 bullet fired directly into Federal BTR-80 glacis -> ricochets with ZERO hull damage!
- sim.projectiles.clear();
- sim.projectiles.push(Projectile {
- pos: btr_p + Vec3::new(0.0, 0.0, 6.0),
- prev_pos: btr_p + Vec3::new(0.0, 0.0, 6.0),
- vel: Vec3::new(0.0, 0.0, -850.0),
- kind: ProjectileKind::Bullet,
- faction: Faction::Militia,
- damage: 38.0,
- suppression: 0.2,
- blast_radius: 0.0,
- crater_radius: 0.0,
- drag: 0.0,
- age: 0.0,
- max_age: 1.0,
- is_tracer: false,
- crack_triggered: false,
- whistle_emitted: true,
- from_player: false,
- owner_player: None,
- visual_offset: Vec3::ZERO,
- guidance: Default::default(),
- guide_vehicle_id: None,
- is_heavy_ap: false,
- });
- for _ in 0..5 {
- sim.step(&cfg, 331.5, &bvh, btr_p);
- }
- assert_eq!(sim.vehicles[btr_idx].hp, btr_hp_before, "Rifle bullet should ricochet off BTR-80 armor!");
- assert!(
- sim.pending_sounds.iter().any(|ev| ev.kind == SoundKind::Ricochet),
- "BTR-80 armor deflection should emit Ricochet sound"
- );
- // RPG-7V warhead hits BTR-80 -> penetrates armor and deals heavy damage!
- sim.projectiles.push(Projectile {
- pos: btr_p + Vec3::new(0.0, 0.0, 6.0),
- prev_pos: btr_p + Vec3::new(0.0, 0.0, 6.0),
- vel: Vec3::new(0.0, 0.0, -280.0),
- kind: ProjectileKind::RpgRocket,
- faction: Faction::Militia,
- damage: 210.0,
- suppression: 1.0,
- blast_radius: 6.0,
- crater_radius: 1.65,
- drag: 0.0,
- age: 0.0,
- max_age: 1.0,
- is_tracer: false,
- crack_triggered: false,
- whistle_emitted: true,
- from_player: false,
- owner_player: None,
- visual_offset: Vec3::ZERO,
- guidance: Default::default(),
- guide_vehicle_id: None,
- is_heavy_ap: true,
- });
- for _ in 0..5 {
- sim.step(&cfg, 331.5, &bvh, btr_p);
- }
- assert!(sim.vehicles[btr_idx].hp < btr_hp_before - 150.0, "RPG-7V warhead must damage BTR-80!");
- // Player enters BTR-80, switches to Seat 2 (Gunner), and fires 14.5mm KPVT!
- sim.player.pos = sim.vehicles[btr_idx].pos + Vec3::new(0.0, 0.0, 2.0);
- sim.try_player_toggle_vehicle();
- sim.try_player_switch_seat(1);
- let (_, seat_i) = sim.player.in_vehicle.unwrap();
- assert_eq!(sim.vehicles[btr_idx].seats[seat_i].0, VehicleSeatRole::Gunner);
- sim.pending_sounds.clear();
- let shoot_in = VehicleInput {
- turret_fire: true,
- aim_yaw_pitch: Some((1.2, 0.05)),
- ..Default::default()
- };
- sim.step_with_vehicle_input(&cfg, 331.5, &bvh, btr_p, Some(&shoot_in));
- assert!(sim.pending_sounds.iter().any(|ev| ev.kind == SoundKind::KpvtShot), "14.5mm KPVT must emit KpvtShot");
- sim.try_player_toggle_vehicle();
- // 3. Game Director spawns crewed Ural-4320 & taking fire automatically dismounts passengers
- let vid = sim.gm_spawn_vehicle(Faction::Federal, VehicleKind::Ural4320, Vec3::new(-64.0, 3.0, -6.0), true);
- let v_idx = sim.vehicles.iter().position(|v| v.id == vid).unwrap();
- assert!(sim.vehicles[v_idx].passenger_count() > 0, "Crewed Ural must have passengers");
- sim.vehicles[v_idx].taking_fire_timer = 2.0;
- sim.step(&cfg, 331.5, &bvh, Vec3::ZERO);
- assert_eq!(sim.vehicles[v_idx].passenger_count(), 0, "AI passengers must dismount under fire!");
- let mut batch = ActorRenderBatch::default();
- sim.build_actor_batch(Some(0), &mut batch);
- assert!(!batch.veh_uaz_body.is_empty() && !batch.veh_ural_body.is_empty() && !batch.veh_btr_hull.is_empty());
- }
- #[test]
- fn test_bullet_hit_effects_all_materials_vehicles_and_soldiers() {
- use project_cold_water::core::materials::MaterialId;
- use project_cold_water::sim::ballistics::HitZone;
- use project_cold_water::sim::effects::{HitParticleKind, ImpactEffectsState};
- use project_cold_water::world::actors_mesh::ActorRenderBatch;
- let mut fx = ImpactEffectsState::default();
- let mut lights = Vec::new();
- // 1. World material impacts (Concrete, Steel, Brick, Snow, Mud, Wood, Water)
- for mat in [
- MaterialId::Concrete,
- MaterialId::SteelHulk,
- MaterialId::BrickRubble,
- MaterialId::WinterSnow,
- MaterialId::WinterMud,
- MaterialId::WoodFurniture,
- MaterialId::ColdWater,
- ] {
- fx.spawn_world_impact(Vec3::new(1.0, 2.0, 3.0), Vec3::Y, mat, 42.0, &mut lights);
- }
- assert!(
- fx.particles.iter().any(|p| p.kind == HitParticleKind::Chunk),
- "Material hits must spawn debris chunks"
- );
- assert!(
- fx.particles.iter().any(|p| p.kind == HitParticleKind::Puff),
- "Material hits must spawn dust/spray/flash puffs"
- );
- assert!(!fx.sparks.is_empty(), "Steel/concrete/water hits must spawn spark/droplet streaks");
- assert!(!lights.is_empty(), "Steel/concrete hits should emit dynamic flash lights");
- // Water should NOT create surface decal; the other 6 materials should create 6 decals
- assert_eq!(fx.decals.len(), 6, "Expected 6 solid-surface bullet decals and 0 on water");
- // 2. Vehicle armor ricochet & soldier helmet/torso hits + explosion burst
- fx.spawn_vehicle_hit(Vec3::ZERO, Vec3::Z, true, true, &mut lights);
- fx.spawn_soldier_hit(Vec3::new(0.0, 1.7, 0.0), Vec3::Z, HitZone::Head, true, &mut lights);
- fx.spawn_soldier_hit(Vec3::new(0.0, 1.1, 0.0), Vec3::Z, HitZone::Torso, false, &mut lights);
- fx.spawn_explosion_burst(Vec3::new(5.0, 0.5, 5.0), 8.0);
- // 3. Step simulation and verify batch packing + finite spark segments
- for _ in 0..8 {
- fx.step(0.016);
- }
- let mut batch = ActorRenderBatch::default();
- fx.push_instances(&[], &mut batch);
- assert!(!batch.fx_chunks.is_empty());
- assert!(!batch.fx_puffs.is_empty());
- assert!(!batch.fx_decals.is_empty());
- let mut spark_lines = Vec::new();
- fx.push_spark_lines(&mut spark_lines);
- assert!(!spark_lines.is_empty());
- for (a, b, c) in &spark_lines {
- assert!(a.is_finite() && b.is_finite());
- assert!(c.iter().all(|v| v.is_finite()));
- }
- // 4. Advance past decal max_age and confirm full expiration cleanup
- for _ in 0..250 {
- fx.step(0.2);
- }
- assert!(fx.particles.is_empty());
- assert!(fx.sparks.is_empty());
- assert!(fx.decals.is_empty());
- }
- fn build_flat_vehicle_sandbox_world() -> project_cold_water::world::WorldData {
- use project_cold_water::modding::blueprint::{
- AssetBlueprint, BlueprintPayload, MapBlueprint, MapModSpawn, MapTerrainBase, SCHEMA_VERSION,
- };
- use project_cold_water::modding::registry::ModRegistry;
- let bp = AssetBlueprint {
- schema_version: SCHEMA_VERSION,
- id: "flat_sim_sandbox".into(),
- name: "Flat Sim Sandbox".into(),
- author: "ColdWater".into(),
- payload: BlueprintPayload::Map(MapBlueprint {
- base_terrain: MapTerrainBase::FlatSandbox {
- half_extent: 220.0,
- material: MaterialId::WinterMud,
- },
- nodes: Vec::new(),
- spawns: vec![
- MapModSpawn {
- name: "Fed".into(),
- faction: Faction::Federal,
- pos: [0.0, 0.0, -40.0],
- ..Default::default()
- },
- MapModSpawn {
- name: "Mil".into(),
- faction: Faction::Militia,
- pos: [0.0, 0.0, 120.0],
- ..Default::default()
- },
- ],
- objectives: Vec::new(),
- vehicles: Vec::new(),
- named_curves: Vec::new(),
- script_hooks: Vec::new(),
- mission_defaults: Default::default(),
- }),
- };
- ModRegistry::default()
- .build_world_from_map(&bp)
- .expect("flat sandbox world")
- }
- #[test]
- fn test_tow_saclos_guidance_tracks_aim_beam_and_destroys_armor() {
- use project_cold_water::sim::vehicles::{Vehicle, VehicleInput, VehicleOccupant};
- use project_cold_water::world::VehicleKind;
- let world = build_flat_vehicle_sandbox_world();
- let bvh = AcousticBvh::build(world.acoustic_triangles.clone());
- let mut sim = Simulation::new(&world);
- // Clear distractions
- for s in &mut sim.soldiers {
- s.alive = false;
- }
- let mut tow = Vehicle::new(
- 0,
- "TOW".into(),
- VehicleKind::TowTripod,
- Faction::Federal,
- Vec3::new(0.0, 0.0, 0.0),
- 0.0,
- None,
- );
- tow.seats[0].1 = Some(VehicleOccupant::Player);
- let btr = Vehicle::new(
- 1,
- "Enemy BTR".into(),
- VehicleKind::Btr80,
- Faction::Militia,
- Vec3::new(6.0, 0.0, 75.0),
- 0.0,
- None,
- );
- let start_hp = btr.hp;
- sim.vehicles = vec![tow, btr];
- sim.player.active = true;
- sim.player.alive = true;
- sim.player.faction = Faction::Federal;
- sim.player.in_vehicle = Some((0, 0));
- let cfg = SimConfig::default();
- // 1. Fire TOW straight downrange (aimed 6m left of target)
- let launch_in = VehicleInput {
- turret_fire: true,
- aim_yaw_pitch: Some((0.0, 0.02)),
- ..Default::default()
- };
- sim.step_with_vehicle_input(&cfg, 331.5, &bvh, Vec3::ZERO, Some(&launch_in));
- assert!(
- sim.projectiles
- .iter()
- .any(|p| p.kind == ProjectileKind::GuidedMissile),
- "Firing TOW must spawn a SACLOS GuidedMissile"
- );
- // 2. Steer gunner optic toward the laterally offset BTR-80 at (6, 1.35, 75)
- for _ in 0..180 {
- let optic_eye = sim.vehicles[0].gunner_optic_pose().0;
- let to_btr = sim.vehicles[1].pos + Vec3::new(0.0, 1.35, 0.0) - optic_eye;
- let yaw = to_btr.x.atan2(to_btr.z);
- let pitch = (to_btr.y / to_btr.length().max(0.1)).clamp(-0.4, 0.5).asin();
- let track_in = VehicleInput {
- aim_yaw_pitch: Some((yaw, pitch)),
- ..Default::default()
- };
- sim.step_with_vehicle_input(&cfg, 331.5, &bvh, Vec3::ZERO, Some(&track_in));
- if !sim.vehicles[1].alive || sim.vehicles[1].hp < start_hp * 0.5 {
- break;
- }
- }
- assert!(
- !sim.vehicles[1].alive || sim.vehicles[1].hp < start_hp * 0.5,
- "SACLOS wire-guided TOW must track optic beam and destroy/cripple offset BTR (hp {} vs start {})",
- sim.vehicles[1].hp,
- start_hp
- );
- }
- #[test]
- fn test_helicopter_collective_takeoff_hover_cyclic_flight_and_landing() {
- use glam::Vec2;
- use project_cold_water::sim::vehicles::{Vehicle, VehicleInput, VehicleOccupant};
- use project_cold_water::world::VehicleKind;
- let world = build_flat_vehicle_sandbox_world();
- let bvh = AcousticBvh::build(world.acoustic_triangles.clone());
- let mut sim = Simulation::new(&world);
- for s in &mut sim.soldiers {
- s.alive = false;
- }
- let mut heli = Vehicle::new(
- 0,
- "Mi-24V".into(),
- VehicleKind::Mi24Gunship,
- Faction::Federal,
- Vec3::ZERO,
- 0.0,
- None,
- );
- heli.seats[0].1 = Some(VehicleOccupant::Player);
- sim.vehicles = vec![heli];
- sim.player.active = true;
- sim.player.alive = true;
- sim.player.faction = Faction::Federal;
- sim.player.in_vehicle = Some((0, 0));
- let cfg = SimConfig::default();
- // 1. Spool rotors & climb with collective up
- let climb_in = VehicleInput {
- collective: 1.0,
- ..Default::default()
- };
- for _ in 0..240 {
- sim.step_with_vehicle_input(&cfg, 331.5, &bvh, Vec3::ZERO, Some(&climb_in));
- }
- assert!(
- sim.vehicles[0].rotor_rpm > 0.85,
- "Rotor RPM must spool up under pilot collective (got {})",
- sim.vehicles[0].rotor_rpm
- );
- assert!(
- sim.vehicles[0].pos.y > 5.0,
- "Helicopter must climb cleanly into air (pos.y={})",
- sim.vehicles[0].pos.y
- );
- // 2. Engage Auto-Hover & settle vertical rate
- let toggle_in = VehicleInput {
- toggle_hover: true,
- ..Default::default()
- };
- sim.step_with_vehicle_input(&cfg, 331.5, &bvh, Vec3::ZERO, Some(&toggle_in));
- assert!(sim.vehicles[0].auto_hover);
- let hover_in = VehicleInput::default();
- for _ in 0..180 {
- sim.step_with_vehicle_input(&cfg, 331.5, &bvh, Vec3::ZERO, Some(&hover_in));
- }
- assert!(
- sim.vehicles[0].vel.y.abs() < 1.5 && sim.vehicles[0].pos.y > 4.0,
- "Auto-hover must arrest vertical speed without losing altitude (vel.y={}, y={})",
- sim.vehicles[0].vel.y,
- sim.vehicles[0].pos.y
- );
- // 3. Apply cyclic pitch forward + slight collective + tail rotor yaw
- let start_yaw = sim.vehicles[0].yaw;
- let fly_in = VehicleInput {
- collective: 0.25,
- cyclic_pitch: 0.85,
- yaw_pedal: 0.35,
- ..Default::default()
- };
- for _ in 0..180 {
- sim.step_with_vehicle_input(&cfg, 331.5, &bvh, Vec3::ZERO, Some(&fly_in));
- }
- let h_spd = Vec2::new(sim.vehicles[0].vel.x, sim.vehicles[0].vel.z).length();
- assert!(h_spd > 5.0, "Cyclic pitch must accelerate helicopter forward (h_spd={h_spd})");
- assert!(
- (sim.vehicles[0].yaw - start_yaw).abs() > 0.3,
- "Tail rotor pedal must yaw helicopter"
- );
- // 4. Disengage hover & land smoothly on ground without exploding
- sim.step_with_vehicle_input(&cfg, 331.5, &bvh, Vec3::ZERO, Some(&toggle_in));
- let descend_in = VehicleInput {
- collective: -0.45,
- ..Default::default()
- };
- for _ in 0..420 {
- sim.step_with_vehicle_input(&cfg, 331.5, &bvh, Vec3::ZERO, Some(&descend_in));
- if sim.vehicles[0].pos.y <= 0.15 {
- break;
- }
- }
- assert!(
- sim.vehicles[0].alive && sim.vehicles[0].pos.y <= 0.5,
- "Helicopter must touch down intact on flat terrain (alive={}, y={})",
- sim.vehicles[0].alive,
- sim.vehicles[0].pos.y
- );
- }
- #[test]
- fn test_tracked_vehicle_differential_neutral_pivot_recoil_and_instanced_shoes() {
- use glam::Vec2;
- use project_cold_water::sim::vehicles::{
- push_vehicle_instances, Vehicle, VehicleInput, VehicleOccupant,
- };
- use project_cold_water::world::actors_mesh::ActorRenderBatch;
- use project_cold_water::world::VehicleKind;
- let world = build_flat_vehicle_sandbox_world();
- let bvh = AcousticBvh::build(world.acoustic_triangles.clone());
- let mut sim = Simulation::new(&world);
- for s in &mut sim.soldiers {
- s.alive = false;
- }
- let mut tank = Vehicle::new(
- 0,
- "T-72B".into(),
- VehicleKind::T72B,
- Faction::Federal,
- Vec3::ZERO,
- 0.0,
- None,
- );
- tank.seats[0].1 = Some(VehicleOccupant::Player);
- sim.vehicles = vec![tank];
- sim.player.active = true;
- sim.player.alive = true;
- sim.player.faction = Faction::Federal;
- sim.player.in_vehicle = Some((0, 0));
- let cfg = SimConfig::default();
- // 1. Neutral pivot turn in place (counter-rotating left/right tracks)
- let pivot_in = VehicleInput {
- throttle: 0.0,
- steer: 1.0,
- ..Default::default()
- };
- for _ in 0..90 {
- sim.step_with_vehicle_input(&cfg, 331.5, &bvh, Vec3::ZERO, Some(&pivot_in));
- }
- let horiz_disp = Vec2::new(sim.vehicles[0].pos.x, sim.vehicles[0].pos.z).length();
- assert!(
- sim.vehicles[0].yaw > 0.5,
- "T-72B must pivot left significantly in place (yaw={})",
- sim.vehicles[0].yaw
- );
- assert!(
- horiz_disp < 0.35,
- "Neutral pivot must stay near pivot center (disp={horiz_disp})"
- );
- // `left_track_offset` / `right_track_offset` wrap via `.rem_euclid(1000.0)` so negative
- // reverse track travel lands just below 1000.0 while positive forward travel starts at 0.0.
- let left_rev_dist = if sim.vehicles[0].left_track_offset > 500.0 {
- 1000.0 - sim.vehicles[0].left_track_offset
- } else {
- -sim.vehicles[0].left_track_offset
- };
- assert!(
- left_rev_dist > 0.5 && sim.vehicles[0].right_track_offset > 0.5 && sim.vehicles[0].right_track_offset < 100.0,
- "Left and right tracks must counter-rotate during neutral pivot (L={}, R={})",
- sim.vehicles[0].left_track_offset,
- sim.vehicles[0].right_track_offset
- );
- // 2. Forward acceleration along current heading
- let l_before_fwd = sim.vehicles[0].left_track_offset;
- let r_before_fwd = sim.vehicles[0].right_track_offset;
- let fwd_in = VehicleInput {
- throttle: 1.0,
- steer: 0.0,
- ..Default::default()
- };
- for _ in 0..90 {
- sim.step_with_vehicle_input(&cfg, 331.5, &bvh, Vec3::ZERO, Some(&fwd_in));
- }
- let l_fwd_delta = (sim.vehicles[0].left_track_offset - l_before_fwd).rem_euclid(1000.0);
- let r_fwd_delta = (sim.vehicles[0].right_track_offset - r_before_fwd).rem_euclid(1000.0);
- assert!(
- sim.vehicles[0].speed > 5.0,
- "T-72B must accelerate forward under twin-track drive (speed={})",
- sim.vehicles[0].speed
- );
- assert!(
- l_fwd_delta > 1.0 && l_fwd_delta < 500.0 && r_fwd_delta > 1.0 && r_fwd_delta < 500.0,
- "Both track offsets must advance forward (dl={l_fwd_delta}, dr={r_fwd_delta})"
- );
- // 3. Fire 125mm 2A46M smoothbore cannon & verify hull recoil impulse + sound + shell
- sim.vehicles[0].seats[0].1 = None;
- sim.vehicles[0].seats[1].1 = Some(VehicleOccupant::Player);
- sim.player.in_vehicle = Some((0, 1));
- sim.pending_sounds.clear();
- let fire_in = VehicleInput {
- turret_fire: true,
- aim_yaw_pitch: Some((sim.vehicles[0].yaw, 0.0)),
- ..Default::default()
- };
- sim.step_with_vehicle_input(&cfg, 331.5, &bvh, Vec3::ZERO, Some(&fire_in));
- assert!(
- sim.vehicles[0].recoil_pitch_impulse.abs() > 0.01,
- "125mm main gun firing must impart hull pitch recoil (recoil={})",
- sim.vehicles[0].recoil_pitch_impulse
- );
- assert!(
- sim.pending_sounds
- .iter()
- .any(|s| s.kind == SoundKind::TankCannon125mm),
- "125mm firing must emit SoundKind::TankCannon125mm"
- );
- assert!(
- sim.projectiles
- .iter()
- .any(|p| p.kind == ProjectileKind::AutocannonShell && p.blast_radius >= 6.0),
- "125mm cannon must spawn heavy HE/APFSDS shell"
- );
- // 4. Option A instanced 3D track shoes & roadwheels
- let mut batch = ActorRenderBatch::default();
- push_vehicle_instances(&sim.vehicles, None, &mut batch);
- assert_eq!(batch.veh_t72_hull.len(), 1);
- assert_eq!(batch.veh_t72_turret.len(), 1);
- assert_eq!(batch.veh_track_shoe.len(), 56);
- assert_eq!(batch.veh_track_roadwheel.len(), 16);
- for inst in batch
- .veh_track_shoe
- .iter()
- .chain(batch.veh_track_roadwheel.iter())
- {
- for col in inst.model_cols {
- for val in col {
- assert!(val.is_finite(), "Track/wheel transform must be finite");
- }
- }
- }
- }
- #[test]
- fn test_t72b_directional_armor_front_glacis_vs_rear_engine_deck() {
- use project_cold_water::modding::blueprint::ProjectileGuidance;
- use project_cold_water::sim::vehicles::Vehicle;
- use project_cold_water::world::VehicleKind;
- let world = build_flat_vehicle_sandbox_world();
- let bvh = AcousticBvh::build(world.acoustic_triangles.clone());
- let cfg = SimConfig::default();
- let run_hit_scenario = |spawn_pos: Vec3, vel: Vec3| -> f32 {
- let mut sim = Simulation::new(&world);
- for s in &mut sim.soldiers {
- s.alive = false;
- }
- let tank = Vehicle::new(
- 0,
- "T-72B".into(),
- VehicleKind::T72B,
- Faction::Federal,
- Vec3::ZERO,
- 0.0,
- None,
- );
- let start_hp = tank.hp;
- sim.vehicles = vec![tank];
- sim.projectiles.push(Projectile {
- pos: spawn_pos,
- prev_pos: spawn_pos,
- vel,
- kind: ProjectileKind::AutocannonShell,
- faction: Faction::Militia,
- damage: 240.0,
- suppression: 4.0,
- blast_radius: 0.0,
- crater_radius: 0.0,
- drag: 0.0,
- age: 0.0,
- max_age: 2.0,
- is_tracer: false,
- crack_triggered: false,
- whistle_emitted: false,
- from_player: false,
- owner_player: None,
- visual_offset: Vec3::ZERO,
- guidance: ProjectileGuidance::default(),
- guide_vehicle_id: None,
- is_heavy_ap: true,
- });
- for _ in 0..30 {
- sim.step(&cfg, 331.5, &bvh, Vec3::ZERO);
- if sim.vehicles[0].hp < start_hp {
- break;
- }
- }
- start_hp - sim.vehicles[0].hp
- };
- // Tank faces +Z (yaw = 0.0): front glacis hit approaches from +Z; rear engine deck hit from -Z
- let front_damage = run_hit_scenario(Vec3::new(0.0, 1.15, 10.0), Vec3::new(0.0, 0.0, -350.0));
- let rear_damage = run_hit_scenario(Vec3::new(0.0, 1.15, -10.0), Vec3::new(0.0, 0.0, 350.0));
- assert!(
- front_damage > 10.0 && rear_damage > front_damage * 2.0,
- "Rear engine-deck hit must deal far greater damage than frontal glacis (front={front_damage}, rear={rear_damage})"
- );
- }
- #[test]
- fn test_multibarrel_zu23_salvo_and_bmpt_terminator_alternating_systems() {
- use project_cold_water::modding::blueprint::ProjectileGuidance;
- use project_cold_water::sim::vehicles::{
- push_vehicle_instances, Vehicle, VehicleInput, VehicleOccupant,
- };
- use project_cold_water::world::actors_mesh::ActorRenderBatch;
- use project_cold_water::world::VehicleKind;
- let world = build_flat_vehicle_sandbox_world();
- let bvh = AcousticBvh::build(world.acoustic_triangles.clone());
- let cfg = SimConfig::default();
- // Part A: ZU-23-2 Twin 23mm Linked Salvo at high +80 deg AA elevation
- let mut sim = Simulation::new(&world);
- for s in &mut sim.soldiers {
- s.alive = false;
- }
- let mut zu23 = Vehicle::new(
- 0,
- "ZU-23-2".into(),
- VehicleKind::Zu23Emplacement,
- Faction::Militia,
- Vec3::ZERO,
- 0.0,
- None,
- );
- zu23.seats[0].1 = Some(VehicleOccupant::Player);
- sim.vehicles = vec![zu23];
- sim.player.active = true;
- sim.player.alive = true;
- sim.player.faction = Faction::Militia;
- sim.player.in_vehicle = Some((0, 0));
- let aim_pitch = 80.0_f32.to_radians();
- let aim_in = VehicleInput {
- aim_yaw_pitch: Some((0.0, aim_pitch)),
- ..Default::default()
- };
- for _ in 0..90 {
- sim.step_with_vehicle_input(&cfg, 331.5, &bvh, Vec3::ZERO, Some(&aim_in));
- }
- assert!(
- sim.vehicles[0].turret_pitch > 75.0_f32.to_radians(),
- "ZU-23-2 must elevate cleanly to AA angle (pitch={})",
- sim.vehicles[0].turret_pitch.to_degrees()
- );
- sim.projectiles.clear();
- sim.pending_sounds.clear();
- let salvo_in = VehicleInput {
- turret_fire: true,
- aim_yaw_pitch: Some((0.0, aim_pitch)),
- ..Default::default()
- };
- sim.step_with_vehicle_input(&cfg, 331.5, &bvh, Vec3::ZERO, Some(&salvo_in));
- assert_eq!(
- sim.projectiles.len(),
- 2,
- "ZU-23-2 linked salvo must spawn 2 projectiles per trigger pull"
- );
- assert!(sim
- .projectiles
- .iter()
- .all(|p| p.kind == ProjectileKind::AutocannonShell));
- let sep = (sim.projectiles[0].prev_pos - sim.projectiles[1].prev_pos).length();
- assert!(
- (sep - 0.28).abs() < 0.04,
- "Twin 23mm barrels must stay ~0.28m apart even at +80 deg pitch (sep={sep})"
- );
- assert_eq!(sim.vehicles[0].primary_ammo, 98);
- assert!(
- sim.pending_sounds
- .iter()
- .any(|s| s.kind == SoundKind::Autocannon23mm),
- "ZU-23-2 must emit SoundKind::Autocannon23mm"
- );
- let mut zu_batch = ActorRenderBatch::default();
- push_vehicle_instances(&sim.vehicles, None, &mut zu_batch);
- assert_eq!(zu_batch.veh_zu23_base.len(), 1);
- assert_eq!(zu_batch.veh_zu23_turret.len(), 1);
- // Part B: BMPT Terminator alternating Twin 30mm + Quad 9M120 Ataka-T ATGM + Tracked Chassis
- let mut sim_bmpt = Simulation::new(&world);
- for s in &mut sim_bmpt.soldiers {
- s.alive = false;
- }
- let mut bmpt = Vehicle::new(
- 0,
- "BMPT".into(),
- VehicleKind::BmptTerminator,
- Faction::Federal,
- Vec3::ZERO,
- 0.0,
- None,
- );
- bmpt.seats[1].1 = Some(VehicleOccupant::Player);
- sim_bmpt.vehicles = vec![bmpt];
- sim_bmpt.player.active = true;
- sim_bmpt.player.alive = true;
- sim_bmpt.player.faction = Faction::Federal;
- sim_bmpt.player.in_vehicle = Some((0, 1));
- let fire_30mm = VehicleInput {
- turret_fire: true,
- aim_yaw_pitch: Some((0.0, 0.0)),
- ..Default::default()
- };
- sim_bmpt.projectiles.clear();
- sim_bmpt.step_with_vehicle_input(&cfg, 331.5, &bvh, Vec3::ZERO, Some(&fire_30mm));
- let shot_a = sim_bmpt.projectiles.last().expect("1st 30mm shot").prev_pos;
- for _ in 0..12 {
- sim_bmpt.step_with_vehicle_input(&cfg, 331.5, &bvh, Vec3::ZERO, Some(&VehicleInput::default()));
- }
- sim_bmpt.step_with_vehicle_input(&cfg, 331.5, &bvh, Vec3::ZERO, Some(&fire_30mm));
- let shot_b = sim_bmpt.projectiles.last().expect("2nd 30mm shot").prev_pos;
- assert!(
- shot_a.x * shot_b.x < 0.0,
- "BMPT twin 30mm must alternate left/right barrels (x0={}, x1={})",
- shot_a.x,
- shot_b.x
- );
- let twin_sep = (shot_a - shot_b).length();
- assert!(
- (twin_sep - 0.44).abs() < 0.05,
- "BMPT twin 30mm muzzles must be separated by ~0.44m (sep={twin_sep})"
- );
- assert_eq!(sim_bmpt.vehicles[0].primary_ammo, 118);
- // Quad Ataka-T secondary salvo across all 4 pods
- let mut atgm_origins = Vec::new();
- let fire_atgm = VehicleInput {
- secondary_fire: true,
- aim_yaw_pitch: Some((0.0, 0.0)),
- ..Default::default()
- };
- for shot_idx in 0..4 {
- sim_bmpt.projectiles.clear();
- sim_bmpt.step_with_vehicle_input(&cfg, 331.5, &bvh, Vec3::ZERO, Some(&fire_atgm));
- let m = sim_bmpt
- .projectiles
- .last()
- .unwrap_or_else(|| panic!("ATGM #{shot_idx} must launch"));
- assert_eq!(m.kind, ProjectileKind::GuidedMissile);
- assert_eq!(m.guidance, ProjectileGuidance::SaclosWireGuided);
- atgm_origins.push(m.prev_pos);
- // Wait > 2.2s cooldown before next missile
- for _ in 0..145 {
- sim_bmpt.step_with_vehicle_input(
- &cfg,
- 331.5,
- &bvh,
- Vec3::ZERO,
- Some(&VehicleInput::default()),
- );
- }
- }
- assert_eq!(sim_bmpt.vehicles[0].secondary_ammo, 0);
- let min_x = atgm_origins.iter().map(|p| p.x).fold(f32::INFINITY, f32::min);
- let max_x = atgm_origins.iter().map(|p| p.x).fold(f32::NEG_INFINITY, f32::max);
- let min_y = atgm_origins.iter().map(|p| p.y).fold(f32::INFINITY, f32::min);
- let max_y = atgm_origins.iter().map(|p| p.y).fold(f32::NEG_INFINITY, f32::max);
- assert!(
- (max_x - min_x - 1.52).abs() < 0.08 && (max_y - min_y - 0.32).abs() < 0.08,
- "Quad Ataka-T tubes must fire from 2x2 cluster (~1.52m wide x 0.32m tall), got dx={}, dy={}",
- max_x - min_x,
- max_y - min_y
- );
- let mut bmpt_batch = ActorRenderBatch::default();
- push_vehicle_instances(&sim_bmpt.vehicles, None, &mut bmpt_batch);
- assert_eq!(bmpt_batch.veh_t72_hull.len(), 1);
- assert_eq!(bmpt_batch.veh_bmpt_turret.len(), 1);
- assert_eq!(bmpt_batch.veh_track_shoe.len(), 56);
- assert_eq!(bmpt_batch.veh_track_roadwheel.len(), 16);
- }
|