acoustics_and_sim.rs 87 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284
  1. use std::sync::{atomic::AtomicUsize, Arc};
  2. use glam::Vec3;
  3. use project_cold_water::audio::bvh::AcousticBvh;
  4. use project_cold_water::audio::dsp::{compute_binaural_params, HadamardFdn8, RealTimeDsp};
  5. use project_cold_water::audio::patch::{compute_spectrum_bars, synthesize_patch, AudioPatchBank};
  6. use project_cold_water::audio::propagation::{estimate_environment, trace_sound_event};
  7. use project_cold_water::audio::synth::ambience::ProceduralAmbience;
  8. use project_cold_water::audio::synth::ProceduralSoundBank;
  9. use project_cold_water::core::config::{AudioConfig, SimConfig};
  10. use project_cold_water::core::events::{ListenerPose, SoundEvent, SoundKind};
  11. use project_cold_water::core::materials::MaterialId;
  12. use project_cold_water::sim::ballistics::{step_projectiles, Projectile, ProjectileKind};
  13. use project_cold_water::sim::orders::TacticalOrder;
  14. use project_cold_water::sim::Simulation;
  15. use project_cold_water::world::maps::foothill_river_town::FoothillRiverTownMap;
  16. use project_cold_water::world::{AcousticTriangle, Faction, MapScenario};
  17. fn make_quad_tris(p00: Vec3, p10: Vec3, p11: Vec3, p01: Vec3, mat: MaterialId) -> [AcousticTriangle; 2] {
  18. [
  19. AcousticTriangle::new(p00, p10, p11, mat),
  20. AcousticTriangle::new(p00, p11, p01, mat),
  21. ]
  22. }
  23. #[test]
  24. fn test_bvh_raycast_and_occlusion_diffraction() {
  25. // Build a concrete wall between source (-8, 1.5, 0) and listener (+8, 1.5, 0)
  26. let mut tris = Vec::new();
  27. tris.extend(make_quad_tris(
  28. Vec3::new(0.0, 0.0, -5.0),
  29. Vec3::new(0.0, 0.0, 5.0),
  30. Vec3::new(0.0, 4.0, 5.0),
  31. Vec3::new(0.0, 4.0, -5.0),
  32. MaterialId::Concrete,
  33. ));
  34. let bvh = AcousticBvh::build(tris);
  35. let hit = bvh
  36. .raycast(Vec3::new(-5.0, 1.5, 0.0), Vec3::X, 20.0)
  37. .expect("should hit concrete wall");
  38. assert!((hit.t - 5.0).abs() < 1e-3);
  39. assert_eq!(hit.material, MaterialId::Concrete);
  40. let ev = SoundEvent {
  41. kind: SoundKind::Ak74mShot,
  42. position: Vec3::new(-8.0, 1.5, 0.0),
  43. velocity: Vec3::ZERO,
  44. gain: 1.0,
  45. pitch_jitter: 1.0,
  46. };
  47. let listener = ListenerPose {
  48. position: Vec3::new(8.0, 1.5, 0.0),
  49. ..Default::default()
  50. };
  51. let cfg = AudioConfig::default();
  52. let (taps, _) = trace_sound_event(&ev, &listener, &bvh, &cfg, None);
  53. assert!(!taps.is_empty(), "diffracted tap should arrive around the wall");
  54. // Verify knife-edge diffraction preserves low band strictly more than high band
  55. let first = taps[0];
  56. assert!(
  57. first.band_gains[0] > first.band_gains[2] * 2.0,
  58. "low band ({}) should diffract significantly stronger than high band ({})",
  59. first.band_gains[0],
  60. first.band_gains[2]
  61. );
  62. }
  63. #[test]
  64. fn test_multi_bounce_canyon_echoes_finite_speed_of_sound() {
  65. // Ground plane + distant rocky canyon cliff at x = +90m
  66. let mut tris = Vec::new();
  67. tris.extend(make_quad_tris(
  68. Vec3::new(-120.0, 0.0, -120.0),
  69. Vec3::new(120.0, 0.0, -120.0),
  70. Vec3::new(120.0, 0.0, 120.0),
  71. Vec3::new(-120.0, 0.0, 120.0),
  72. MaterialId::WinterMud,
  73. ));
  74. tris.extend(make_quad_tris(
  75. Vec3::new(90.0, 0.0, -80.0),
  76. Vec3::new(90.0, 0.0, 80.0),
  77. Vec3::new(90.0, 65.0, 80.0),
  78. Vec3::new(90.0, 65.0, -80.0),
  79. MaterialId::MountainRock,
  80. ));
  81. let bvh = AcousticBvh::build(tris);
  82. let ev = SoundEvent {
  83. kind: SoundKind::SvdShot,
  84. position: Vec3::new(-10.0, 2.0, 0.0),
  85. velocity: Vec3::ZERO,
  86. gain: 1.2,
  87. pitch_jitter: 1.0,
  88. };
  89. let listener = ListenerPose {
  90. position: Vec3::new(0.0, 2.0, 0.0),
  91. ..Default::default()
  92. };
  93. let cfg = AudioConfig::default();
  94. let (taps, bounces) = trace_sound_event(&ev, &listener, &bvh, &cfg, None);
  95. assert!(bounces > 20, "expected many multi-bounce ray hits in canyon");
  96. assert!(taps.len() >= 3, "expected direct + ground + canyon cliff reflection taps");
  97. let direct_delay = taps[0].delay_secs;
  98. assert!((direct_delay - 10.0 / 331.5).abs() < 0.005);
  99. // At least one delayed canyon reflection > 0.45s (round-trip off +90m cliff is ~190m / 331.5 = 0.57s)
  100. let has_canyon_echo = taps.iter().any(|t| t.delay_secs > 0.45 && t.band_gains[1] > 0.0005);
  101. assert!(has_canyon_echo, "expected delayed mountain canyon echo > 0.45s; got taps: {taps:?}");
  102. }
  103. #[test]
  104. fn test_procedural_sound_bank_all_generators_clean() {
  105. let bank = ProceduralSoundBank::generate(48_000);
  106. let kinds = [
  107. SoundKind::Ak74mShot,
  108. SoundKind::AkmShot,
  109. SoundKind::Aks74uShot,
  110. SoundKind::PkmShot,
  111. SoundKind::SvdShot,
  112. SoundKind::RpgLaunch,
  113. SoundKind::RpgRocketLoop,
  114. SoundKind::RpgExplosion,
  115. SoundKind::MortarWhistle,
  116. SoundKind::MortarExplosion,
  117. SoundKind::SupersonicCrack,
  118. SoundKind::Ricochet,
  119. SoundKind::ImpactConcrete,
  120. SoundKind::ImpactSteel,
  121. SoundKind::ImpactMud,
  122. SoundKind::ImpactWater,
  123. SoundKind::RadioSquelch,
  124. ];
  125. for kind in kinds {
  126. let buf = bank.get(kind);
  127. assert!(buf.len() > 200, "{kind:?} buffer too short");
  128. let mut rms_acc = 0.0_f64;
  129. let mut peak = 0.0_f32;
  130. for &s in buf {
  131. assert!(s.is_finite(), "{kind:?} produced NaN/Inf");
  132. peak = peak.max(s.abs());
  133. rms_acc += (s as f64) * (s as f64);
  134. }
  135. let rms = (rms_acc / buf.len() as f64).sqrt();
  136. assert!(rms > 0.01, "{kind:?} unexpectedly silent (rms={rms})");
  137. assert!(peak <= 1.0, "{kind:?} exceeded unit peak ({peak})");
  138. }
  139. let mut amb = ProceduralAmbience::new(48_000);
  140. for _ in 0..4800 {
  141. let (l, r) = amb.next_stereo(0.25, 0.2, 0.1);
  142. assert!(l.is_finite() && r.is_finite());
  143. }
  144. }
  145. #[test]
  146. fn test_hadamard_fdn_stability_and_binaural_itd_ild() {
  147. // 1. 10 seconds of impulse response in Hadamard FDN must decay cleanly without blowing up
  148. let mut fdn = HadamardFdn8::new(48_000);
  149. let mut max_early = 0.0_f32;
  150. let mut max_late = 0.0_f32;
  151. for i in 0..480_000 {
  152. let imp = if i == 0 { 1.0 } else { 0.0 };
  153. let (l, r) = fdn.process_stereo(imp, imp);
  154. assert!(l.is_finite() && r.is_finite(), "FDN produced NaN at sample {i}");
  155. if i < 24_000 {
  156. max_early = max_early.max(l.abs()).max(r.abs());
  157. }
  158. if i > 432_000 {
  159. max_late = max_late.max(l.abs()).max(r.abs());
  160. }
  161. }
  162. assert!(max_early > 0.01, "FDN should respond to impulse");
  163. assert!(max_late < max_early * 0.05, "FDN should decay cleanly over 10s (early={max_early}, late={max_late})");
  164. // 2. Binaural ITD/ILD: source directly to the LEFT (-X) arrives louder and with 0 delay on left ear
  165. let (gl, gr, itd_l, itd_r, al, ar) = compute_binaural_params(-Vec3::X, Vec3::X, -Vec3::Z, 48_000.0);
  166. assert!(gl > gr * 2.0, "left ear gain ({gl}) should exceed right ear gain ({gr})");
  167. assert_eq!(itd_l, 0.0);
  168. assert!(itd_r > 15.0, "right ear should be delayed by ITD samples ({itd_r})");
  169. assert!(al > ar, "right ear should have stronger head-shadow LPF ({al} vs {ar})");
  170. // 3. Full RealTimeDsp render smoke check
  171. let bank = ProceduralSoundBank::generate(48_000);
  172. let mut dsp = RealTimeDsp::new(48_000, bank, Arc::new(AtomicUsize::new(0)));
  173. dsp.enqueue_tap(project_cold_water::audio::AcousticTapCommand {
  174. kind: SoundKind::Ak74mShot,
  175. delay_secs: 0.0,
  176. band_gains: [0.9, 0.9, 0.9],
  177. arrival_dir: -Vec3::X,
  178. pitch_rate: 1.0,
  179. bypass_spatial: false,
  180. reverb_send: 0.3,
  181. attack_smooth_ms: 0.0,
  182. });
  183. let mut block = vec![0.0_f32; 1024];
  184. dsp.render_block(&mut block);
  185. assert!(block.iter().all(|s| s.is_finite()));
  186. assert!(block.iter().any(|&s| s.abs() > 0.01));
  187. }
  188. #[test]
  189. fn test_patch_bank_fx_chain_json_and_rifle_crack_spectrum() {
  190. let mut bank = AudioPatchBank::default_chechnya_presets();
  191. // Verify all 17 patches synthesize cleanly and rifle patches have bright high-freq crack energy
  192. for kind in [SoundKind::Ak74mShot, SoundKind::AkmShot, SoundKind::Aks74uShot, SoundKind::PkmShot, SoundKind::SvdShot] {
  193. let buf = synthesize_patch(bank.get(kind), 48_000);
  194. assert!(buf.iter().all(|s| s.is_finite()));
  195. let spec = compute_spectrum_bars(&buf, 48_000, 24);
  196. let high_avg: f32 = spec[14..].iter().sum::<f32>() / (spec.len() - 14) as f32;
  197. assert!(high_avg > 0.28, "{kind:?} lacks high-freq gunshot crack (high_avg={high_avg})");
  198. }
  199. // Exercise every FX module turned ON simultaneously
  200. let patch = bank.get_mut(SoundKind::Ak74mShot);
  201. patch.fx.transient_on = true;
  202. patch.fx.comb_on = true;
  203. patch.fx.drive_on = true;
  204. patch.fx.eq_on = true;
  205. patch.fx.grit_on = true;
  206. patch.fx.slap_on = true;
  207. let fx_buf = synthesize_patch(patch, 48_000);
  208. assert!(fx_buf.iter().all(|s| s.is_finite()));
  209. assert!(fx_buf.iter().any(|&s| s.abs() > 0.1));
  210. // Verify JSON round-trip serialization
  211. let json = serde_json::to_string_pretty(&bank).expect("serialize patch bank");
  212. let decoded: AudioPatchBank = serde_json::from_str(&json).expect("deserialize patch bank");
  213. assert_eq!(decoded.get(SoundKind::Ak74mShot).fx.grit_on, true);
  214. }
  215. #[test]
  216. fn test_nav_grid_forbids_water_and_routes_over_bridge() {
  217. use project_cold_water::world::terrain::TerrainGrid;
  218. let world = FoothillRiverTownMap.build();
  219. let nav = &world.nav_grid;
  220. // 1. River channel away from bridge MUST be non-walkable
  221. let river_x_south = TerrainGrid::river_center_x_static(35.0);
  222. assert!(
  223. !nav.is_walkable_world(river_x_south, 35.0),
  224. "river water at ({river_x_south}, 35.0) must be blocked"
  225. );
  226. let river_x_north = TerrainGrid::river_center_x_static(-55.0);
  227. assert!(
  228. !nav.is_walkable_world(river_x_north, -55.0),
  229. "river water at ({river_x_north}, -55.0) must be blocked"
  230. );
  231. // 2. Clicking on river water snaps to nearest dry walkable bank
  232. let snapped = nav.nearest_walkable(Vec3::new(river_x_south, 0.0, 35.0));
  233. assert!(nav.is_walkable_world(snapped.x, snapped.z));
  234. // 3. Cross-river A* path from West bank (-60, 35) to East bank (50, 35) must cross bridge without touching water!
  235. let start = Vec3::new(-60.0, 3.0, 35.0);
  236. let goal = Vec3::new(50.0, 3.0, 35.0);
  237. let path = nav.find_path(start, goal);
  238. assert!(path.len() >= 2, "expected multi-waypoint cross-river path via bridge");
  239. let mut prev = nav.nearest_walkable(start);
  240. let mut crossed_bridge = false;
  241. let bridge_z = TerrainGrid::bridge_z();
  242. let bridge_cx = TerrainGrid::river_center_x_static(bridge_z);
  243. for wp in &path {
  244. assert!(
  245. nav.is_segment_walkable(prev, *wp),
  246. "segment {:?} -> {:?} crossed unwalkable water or obstacle!",
  247. prev,
  248. wp
  249. );
  250. if (wp.z - bridge_z).abs() < 4.5 && (wp.x - bridge_cx).abs() < 18.0 && wp.y > 2.4 {
  251. crossed_bridge = true;
  252. }
  253. prev = *wp;
  254. }
  255. assert!(crossed_bridge, "cross-river path must route over the concrete bridge! path={path:?}");
  256. // 4. Step 300 ticks of cross-river Assault in Simulation -> zero soldiers ever touch water!
  257. let bvh = AcousticBvh::build(world.acoustic_triangles.clone());
  258. let mut sim = Simulation::new(&world);
  259. sim.issue_order(0, TacticalOrder::Assault(Vec3::new(40.0, 3.0, 20.0)));
  260. sim.issue_order(1, TacticalOrder::Assault(Vec3::new(40.0, 3.0, -20.0)));
  261. let cfg = SimConfig::default();
  262. for tick in 0..300 {
  263. sim.step(&cfg, 331.5, &bvh, Vec3::new(0.0, 15.0, 30.0));
  264. for s in &sim.soldiers {
  265. if s.alive {
  266. assert!(
  267. sim.nav_grid.is_walkable_world(s.pos.x, s.pos.z),
  268. "tick {tick}: soldier {} stepped onto unwalkable cell at {:?}",
  269. s.id,
  270. s.pos
  271. );
  272. }
  273. }
  274. }
  275. }
  276. #[test]
  277. fn test_unified_soldier_variety() {
  278. use std::collections::HashSet;
  279. let world = FoothillRiverTownMap.build();
  280. let sim = Simulation::new(&world);
  281. let mut jackets = HashSet::new();
  282. let mut trousers = HashSet::new();
  283. let mut headgears = HashSet::new();
  284. let mut vests = HashSet::new();
  285. for s in &sim.soldiers {
  286. assert!(s.appearance.jacket_mat.gpu_layer() < MaterialId::GPU_LAYER_COUNT);
  287. assert!(s.appearance.trouser_mat.gpu_layer() < MaterialId::GPU_LAYER_COUNT);
  288. assert!(s.appearance.headgear_mat.gpu_layer() < MaterialId::GPU_LAYER_COUNT);
  289. assert!(s.appearance.vest_mat.gpu_layer() < MaterialId::GPU_LAYER_COUNT);
  290. jackets.insert(s.appearance.jacket_mat);
  291. trousers.insert(s.appearance.trouser_mat);
  292. headgears.insert(s.appearance.headgear);
  293. vests.insert(s.appearance.vest);
  294. }
  295. assert!(jackets.len() >= 3, "expected >=3 varied uniform tops, got {}", jackets.len());
  296. assert!(trousers.len() >= 3, "expected >=3 varied uniform bottoms, got {}", trousers.len());
  297. assert!(headgears.len() >= 4, "expected >=4 varied headgear types, got {}", headgears.len());
  298. assert!(vests.len() >= 3, "expected >=3 varied vest/rig types, got {}", vests.len());
  299. }
  300. #[test]
  301. fn test_world_sim_ballistics_and_supersonic_cpa() {
  302. let world = FoothillRiverTownMap.build();
  303. let bvh = AcousticBvh::build(world.acoustic_triangles.clone());
  304. assert!(bvh.triangle_count() > 20_000);
  305. // Check enclosure estimator indoors vs open valley
  306. let open_env = estimate_environment(Vec3::new(0.0, 20.0, 0.0), &bvh, 1.0);
  307. assert!(open_env.sky_openness > 0.4);
  308. // Check supersonic bullet CPA trigger passing 4m from listener
  309. let mut projs = vec![Projectile {
  310. pos: Vec3::new(-10.0, 2.0, 4.0),
  311. prev_pos: Vec3::new(-10.0, 2.0, 4.0),
  312. vel: Vec3::new(880.0, 0.0, 0.0),
  313. kind: ProjectileKind::Bullet,
  314. faction: Faction::Federal,
  315. damage: 35.0,
  316. suppression: 0.2,
  317. blast_radius: 0.0,
  318. drag: 0.0,
  319. crater_radius: 0.0,
  320. age: 0.0,
  321. max_age: 1.0,
  322. is_tracer: false,
  323. crack_triggered: false,
  324. whistle_emitted: true,
  325. from_player: false,
  326. owner_player: None,
  327. visual_offset: Vec3::ZERO,
  328. guidance: Default::default(),
  329. guide_vehicle_id: None,
  330. is_heavy_ap: false,
  331. }];
  332. let mut sounds = Vec::new();
  333. let mut soldier_hits = Vec::new();
  334. let mut impacts = Vec::new();
  335. let mut explosions = Vec::new();
  336. let mut tracers = Vec::new();
  337. let mut lights = Vec::new();
  338. step_projectiles(
  339. &mut projs,
  340. 0.025, // moves from x=-10 to x=+12, passing x=0 at dist=4m
  341. 331.5,
  342. &bvh,
  343. &[],
  344. Vec3::new(0.0, 2.0, 0.0),
  345. &mut sounds,
  346. &mut soldier_hits,
  347. &mut impacts,
  348. &mut explosions,
  349. &mut tracers,
  350. &mut lights,
  351. );
  352. assert!(
  353. sounds.iter().any(|s| s.kind == SoundKind::SupersonicCrack),
  354. "supersonic bullet passing 4m from listener must emit SupersonicCrack at CPA"
  355. );
  356. // Check Simulation step & tactical orders
  357. let mut sim = Simulation::new(&world);
  358. sim.issue_order(0, TacticalOrder::Assault(Vec3::new(-10.0, 2.0, -6.0)));
  359. let cfg = SimConfig::default();
  360. for _ in 0..30 {
  361. sim.step(&cfg, 331.5, &bvh, Vec3::new(0.0, 12.0, 20.0));
  362. }
  363. let (fed, mil) = sim.alive_counts();
  364. assert!(fed > 0 && mil > 0);
  365. }
  366. #[test]
  367. fn test_all_six_weapons_have_distinct_detailed_meshes_and_meta() {
  368. use std::collections::HashSet;
  369. use project_cold_water::world::actors_mesh::ActorMeshLibrary;
  370. use project_cold_water::world::weapons_mesh::weapon_model_meta;
  371. use project_cold_water::world::WeaponKind;
  372. let lib = ActorMeshLibrary::build();
  373. let mut offsets = HashSet::new();
  374. for v in &lib.vertices {
  375. assert!(v.mat_id < MaterialId::GPU_LAYER_COUNT, "weapon/actor vertex mat_id out of bounds: {}", v.mat_id);
  376. }
  377. for kind in WeaponKind::ALL {
  378. let slice = lib.weapon_slice(kind);
  379. assert!(
  380. slice.index_count >= 120,
  381. "{kind:?} weapon mesh too simple (index_count={})",
  382. slice.index_count
  383. );
  384. assert!(
  385. offsets.insert(slice.index_offset),
  386. "{kind:?} shares mesh slice with another weapon!"
  387. );
  388. let meta = weapon_model_meta(kind);
  389. assert!(meta.mag_capacity > 0);
  390. assert!(meta.sight_height_y > 0.05);
  391. assert!(meta.muzzle_local.z > 0.45);
  392. }
  393. assert!(lib.launcher_rpg_warhead.index_count >= 60);
  394. assert!(lib.vm_sleeve_arms.index_count >= 60);
  395. assert!(lib.vm_gloves.index_count >= 60);
  396. assert!(lib.vm_muzzle_flash.index_count >= 60);
  397. }
  398. #[test]
  399. fn test_fps_player_all_six_weapons_movement_and_ballistics() {
  400. use project_cold_water::sim::player::FpsInput;
  401. use project_cold_water::world::actors_mesh::ActorMeshLibrary;
  402. use project_cold_water::world::terrain::TerrainGrid;
  403. use project_cold_water::world::weapons_mesh::weapon_model_meta;
  404. use project_cold_water::world::WeaponKind;
  405. let world = FoothillRiverTownMap.build();
  406. let bvh = AcousticBvh::build(world.acoustic_triangles.clone());
  407. let mut sim = Simulation::new(&world);
  408. let lib = ActorMeshLibrary::build();
  409. let s = sim.soldiers[0].clone();
  410. sim.player.deploy_into_soldier(&s);
  411. assert!(sim.player.active && sim.player.alive);
  412. // 1. Water safety: place player on dry west riverbank facing the water and try walking forward into water
  413. let bank_z = 35.0;
  414. let river_x = TerrainGrid::river_center_x_static(bank_z);
  415. sim.player.pos = sim.nav_grid.nearest_walkable(Vec3::new(river_x - 8.0, 3.0, bank_z));
  416. sim.player.yaw = std::f32::consts::FRAC_PI_2; // facing +X directly toward river!
  417. sim.player.pitch = 0.0;
  418. let walk_fwd = FpsInput {
  419. move_fwd: 1.0,
  420. ..Default::default()
  421. };
  422. for _ in 0..180 {
  423. sim.step_fps_player(1.0 / 60.0, &walk_fwd, &bvh);
  424. assert!(
  425. sim.nav_grid.is_walkable_world(sim.player.pos.x, sim.player.pos.z),
  426. "FPS player stepped into river/blocked cell at {:?}",
  427. sim.player.pos
  428. );
  429. }
  430. // 2. Bridge crossing: place player at west approach of bridge and walk +X across the river deck
  431. let bz = TerrainGrid::bridge_z();
  432. let bcx = TerrainGrid::river_center_x_static(bz);
  433. sim.player.pos = sim.nav_grid.nearest_walkable(Vec3::new(bcx - 16.0, 3.0, bz));
  434. for _ in 0..360 {
  435. sim.step_fps_player(1.0 / 60.0, &walk_fwd, &bvh);
  436. }
  437. assert!(
  438. sim.player.pos.x > bcx,
  439. "expected FPS player to cross over bridge past x={bcx}, got x={}",
  440. sim.player.pos.x
  441. );
  442. // 3. Test ALL 6 weapons: select -> verify ammo -> fire projectile + sound + recoil -> viewmodel -> reload!
  443. for kind in WeaponKind::ALL {
  444. sim.pending_sounds.clear();
  445. sim.projectiles.clear();
  446. sim.player.select_weapon(kind);
  447. assert_eq!(sim.player.weapon, kind);
  448. let meta = weapon_model_meta(kind);
  449. let spec = kind.spec();
  450. assert_eq!(sim.player.current_ammo().in_mag, meta.mag_capacity);
  451. // Cooldown elapse after switch
  452. for _ in 0..15 {
  453. sim.step_fps_player(1.0 / 60.0, &FpsInput::default(), &bvh);
  454. }
  455. // Fire one shot
  456. let fire_in = FpsInput {
  457. fire_held: true,
  458. fire_just_pressed: true,
  459. ..Default::default()
  460. };
  461. sim.step_fps_player(1.0 / 60.0, &fire_in, &bvh);
  462. assert_eq!(
  463. sim.player.current_ammo().in_mag,
  464. meta.mag_capacity - 1,
  465. "{kind:?} failed to consume ammo on fire"
  466. );
  467. assert!(
  468. sim.projectiles.iter().any(|p| p.from_player
  469. && if kind == WeaponKind::Rpg7v {
  470. p.kind == ProjectileKind::RpgRocket
  471. } else {
  472. p.kind == ProjectileKind::Bullet
  473. }),
  474. "{kind:?} failed to spawn player projectile"
  475. );
  476. assert!(
  477. sim.pending_sounds.iter().any(|ev| ev.kind == spec.sound),
  478. "{kind:?} failed to emit expected SoundKind {:?}",
  479. spec.sound
  480. );
  481. assert!(sim.player.recoil_kick_z > 0.0, "{kind:?} missing viewmodel recoil");
  482. let draws = sim.player.build_viewmodel_draws(
  483. sim.player.pos + Vec3::Y * 1.6,
  484. sim.player.forward(),
  485. sim.player.flat_right(),
  486. Vec3::Y,
  487. &lib,
  488. );
  489. // RPG-7V should hide PG-7V warhead while mag is empty (0/4)
  490. let has_warhead = draws.iter().any(|(s, _)| s.index_offset == lib.launcher_rpg_warhead.index_offset);
  491. if kind == WeaponKind::Rpg7v {
  492. assert!(!has_warhead, "RPG-7V warhead should vanish after firing");
  493. }
  494. // Reload and advance past reload_secs
  495. let rel_in = FpsInput {
  496. reload_pressed: true,
  497. ..Default::default()
  498. };
  499. sim.step_fps_player(1.0 / 60.0, &rel_in, &bvh);
  500. let reload_steps = ((meta.reload_secs + 0.25) * 60.0) as usize;
  501. for _ in 0..reload_steps {
  502. sim.step_fps_player(1.0 / 60.0, &FpsInput::default(), &bvh);
  503. }
  504. assert_eq!(
  505. sim.player.current_ammo().in_mag,
  506. meta.mag_capacity,
  507. "{kind:?} reload did not refill magazine"
  508. );
  509. if kind == WeaponKind::Rpg7v {
  510. let draws_reloaded = sim.player.build_viewmodel_draws(
  511. sim.player.pos + Vec3::Y * 1.6,
  512. sim.player.forward(),
  513. sim.player.flat_right(),
  514. Vec3::Y,
  515. &lib,
  516. );
  517. assert!(
  518. draws_reloaded.iter().any(|(s, _)| s.index_offset == lib.launcher_rpg_warhead.index_offset),
  519. "RPG-7V warhead should reappear after reload"
  520. );
  521. }
  522. }
  523. // 4. Verify SVD ADS triggers PSO-1 optic overlay
  524. sim.player.select_weapon(WeaponKind::Svd);
  525. let ads_in = FpsInput {
  526. ads_held: true,
  527. ..Default::default()
  528. };
  529. for _ in 0..45 {
  530. sim.step_fps_player(1.0 / 60.0, &ads_in, &bvh);
  531. }
  532. assert!(sim.player.is_pso1_overlay_active(), "SVD ADS should activate PSO-1 overlay");
  533. }
  534. #[test]
  535. fn test_fps_player_near_miss_suppression_spikes_and_decays() {
  536. use project_cold_water::sim::player::FpsInput;
  537. let world = FoothillRiverTownMap.build();
  538. let bvh = AcousticBvh::build(world.acoustic_triangles.clone());
  539. let mut sim = Simulation::new(&world);
  540. let s = sim.soldiers[0].clone();
  541. sim.player.deploy_into_soldier(&s);
  542. sim.player.suppression = 0.0;
  543. sim.projectiles.clear();
  544. // Spawn a Militia rifle round whistling 1.2m beside the FPS player's head
  545. let eye = sim.player.eye_position(&bvh);
  546. let near_miss_start = eye + Vec3::new(-6.0, 0.0, 1.2);
  547. sim.projectiles.push(Projectile {
  548. pos: near_miss_start,
  549. prev_pos: near_miss_start,
  550. vel: Vec3::new(820.0, 0.0, 0.0),
  551. kind: ProjectileKind::Bullet,
  552. faction: Faction::Militia,
  553. damage: 34.0,
  554. suppression: 0.30,
  555. blast_radius: 0.0,
  556. crater_radius: 0.0,
  557. drag: 0.0,
  558. age: 0.0,
  559. max_age: 1.0,
  560. is_tracer: true,
  561. crack_triggered: false,
  562. whistle_emitted: true,
  563. from_player: false,
  564. owner_player: None,
  565. visual_offset: Vec3::ZERO,
  566. guidance: Default::default(),
  567. guide_vehicle_id: None,
  568. is_heavy_ap: false,
  569. });
  570. let cfg = SimConfig::default();
  571. sim.step(&cfg, 331.5, &bvh, eye);
  572. assert!(
  573. sim.player.suppression > 0.15,
  574. "near-miss enemy bullet should spike FPS suppression (> 0.15), got {}",
  575. sim.player.suppression
  576. );
  577. // Advance 1.0 second with no further incoming rounds in the combined sim+FPS loop -> snappy decay
  578. for s in &mut sim.soldiers {
  579. if s.faction != sim.player.faction {
  580. s.alive = false;
  581. }
  582. }
  583. sim.projectiles.clear();
  584. sim.player.suppression = 1.0;
  585. if let Some(sid) = sim.player.soldier_id {
  586. sim.soldiers[sid].suppression = 1.0;
  587. }
  588. for _ in 0..60 {
  589. sim.step_fps_player(1.0 / 60.0, &FpsInput::default(), &bvh);
  590. sim.step(&cfg, 331.5, &bvh, eye);
  591. }
  592. assert!(
  593. sim.player.suppression < 0.05,
  594. "player suppression should decay snappily within 1s after calm period, got {}",
  595. sim.player.suppression
  596. );
  597. if let Some(sid) = sim.player.soldier_id {
  598. assert!(
  599. sim.soldiers[sid].suppression < 0.05,
  600. "controlled soldier suppression must stay synced and not latch high, got {}",
  601. sim.soldiers[sid].suppression
  602. );
  603. }
  604. }
  605. #[test]
  606. fn test_all_six_mission_objective_types_progress_and_complete() {
  607. use project_cold_water::sim::objectives::ObjectiveKind;
  608. use project_cold_water::sim::player::FpsInput;
  609. let world = FoothillRiverTownMap.build();
  610. let bvh = AcousticBvh::build(world.acoustic_triangles.clone());
  611. let mut sim = Simulation::new(&world);
  612. let cfg = SimConfig::default();
  613. // Verify all 6 requested objective archetypes exist in order
  614. assert_eq!(sim.mission.objectives.len(), 6);
  615. assert!(matches!(sim.mission.objectives[0].kind, ObjectiveKind::MoveToPosition));
  616. assert!(matches!(sim.mission.objectives[1].kind, ObjectiveKind::SuppressPosition { .. }));
  617. assert!(matches!(sim.mission.objectives[2].kind, ObjectiveKind::CallArtillery { .. }));
  618. assert!(matches!(sim.mission.objectives[3].kind, ObjectiveKind::AssaultPosition { .. }));
  619. assert!(matches!(sim.mission.objectives[4].kind, ObjectiveKind::ClearBuilding));
  620. assert!(matches!(sim.mission.objectives[5].kind, ObjectiveKind::DefendPosition { .. }));
  621. let f_soldier = sim.soldiers[0].clone();
  622. sim.player.deploy_into_soldier(&f_soldier);
  623. // 1. Move to Position -> completes when FPS player reaches Stage 1
  624. let p0 = sim.mission.objectives[0].position;
  625. sim.player.pos = p0;
  626. sim.step(&cfg, 331.5, &bvh, p0 + Vec3::Y * 1.6);
  627. assert_eq!(sim.mission.active_index, 1, "Stage 1 MoveToPosition should complete on arrival");
  628. // 2. Suppress Position -> fire / pin inside Stage 2 zone until complete
  629. let p1 = sim.mission.objectives[1].position;
  630. for _ in 0..240 {
  631. if sim.mission.active_index != 1 {
  632. break;
  633. }
  634. sim.projectiles.push(Projectile {
  635. pos: p1 + Vec3::new(0.0, 1.5, 0.0),
  636. prev_pos: p1 + Vec3::new(-2.0, 1.5, 0.0),
  637. vel: Vec3::new(800.0, 0.0, 0.0),
  638. kind: ProjectileKind::Bullet,
  639. faction: Faction::Federal,
  640. damage: 0.0,
  641. suppression: 0.25,
  642. blast_radius: 0.0,
  643. crater_radius: 0.0,
  644. drag: 0.0,
  645. age: 0.0,
  646. max_age: 0.2,
  647. is_tracer: false,
  648. crack_triggered: true,
  649. whistle_emitted: true,
  650. from_player: true,
  651. owner_player: None,
  652. visual_offset: Vec3::ZERO,
  653. guidance: Default::default(),
  654. guide_vehicle_id: None,
  655. is_heavy_ap: false,
  656. });
  657. sim.step(&cfg, 331.5, &bvh, p0 + Vec3::Y * 1.6);
  658. }
  659. assert_eq!(sim.mission.active_index, 2, "Stage 2 SuppressPosition should advance to CallArtillery");
  660. // 3. Call Artillery -> call_artillery_strike on Stage 3 target
  661. let p2 = sim.mission.objectives[2].position;
  662. assert!(sim.call_artillery_strike(p2));
  663. assert!(sim.mission.arty_cooldown > 5.0);
  664. assert!(sim.projectiles.iter().any(|p| p.kind == ProjectileKind::MortarShell));
  665. sim.step(&cfg, 331.5, &bvh, p0 + Vec3::Y * 1.6);
  666. assert_eq!(sim.mission.active_index, 3, "Stage 3 CallArtillery should advance to AssaultPosition");
  667. // 4. Assault Position -> clear immediate radius & hold inside Stage 4
  668. let p3 = sim.mission.objectives[3].position;
  669. for s in &mut sim.soldiers {
  670. if s.faction != Faction::Federal && s.pos.distance(p3) < 20.0 {
  671. s.alive = false;
  672. s.hp = 0.0;
  673. }
  674. }
  675. sim.player.pos = p3;
  676. sim.projectiles.clear();
  677. for _ in 0..280 {
  678. if sim.mission.active_index != 3 {
  679. break;
  680. }
  681. sim.step(&cfg, 331.5, &bvh, p3 + Vec3::Y * 1.6);
  682. }
  683. assert_eq!(sim.mission.active_index, 4, "Stage 4 AssaultPosition should advance to ClearBuilding");
  684. // 5. Clear Building -> move player into building zone and eliminate remaining defenders there
  685. let p4 = sim.mission.objectives[4].position;
  686. sim.player.pos = p4;
  687. for s in &mut sim.soldiers {
  688. if s.faction != Faction::Federal && Vec3::new(s.pos.x - p4.x, 0.0, s.pos.z - p4.z).length() < 26.0 {
  689. s.alive = false;
  690. s.hp = 0.0;
  691. }
  692. }
  693. sim.step(&cfg, 331.5, &bvh, p4 + Vec3::Y * 1.6);
  694. assert_eq!(sim.mission.active_index, 5, "Stage 5 ClearBuilding should advance to DefendPosition");
  695. assert!(sim.mission.counterattack_triggered, "Entering Defend stage should trigger enemy counterattack");
  696. // 6. Defend Position -> hold inside defend perimeter for duration_secs -> Operation Complete!
  697. let p5 = sim.mission.objectives[5].position;
  698. sim.player.pos = p5;
  699. for _ in 0..1600 {
  700. if sim.mission.completed {
  701. break;
  702. }
  703. // Keep player alive during automated defense test
  704. sim.player.hp = 100.0;
  705. sim.player.alive = true;
  706. if let Some(sid) = sim.player.soldier_id {
  707. sim.soldiers[sid].hp = 100.0;
  708. sim.soldiers[sid].alive = true;
  709. }
  710. sim.step_fps_player(1.0 / 60.0, &FpsInput::default(), &bvh);
  711. sim.step(&cfg, 331.5, &bvh, p5 + Vec3::Y * 1.6);
  712. }
  713. assert!(sim.mission.completed, "Stage 6 DefendPosition should complete the entire operation");
  714. }
  715. #[test]
  716. fn test_dynamic_map_generator_all_archetypes_and_connected_points() {
  717. use project_cold_water::world::generator::{DynamicMapGenerator, MapArchetype, MapGenConfig};
  718. use project_cold_water::world::points::{ObjectiveRole, SpawnRole};
  719. use project_cold_water::world::HeightQuery;
  720. for &archetype in &MapArchetype::ALL {
  721. let cfg = MapGenConfig::for_archetype(archetype, 1999);
  722. let world = DynamicMapGenerator::new(cfg.clone()).build();
  723. let graph = &world.point_graph;
  724. // 1. Center of Operations + all 6 tactical ObjectivePoints exist
  725. assert!(
  726. graph.center_of_operations().is_some(),
  727. "{:?} missing CenterOfOperations objective",
  728. archetype
  729. );
  730. assert_eq!(graph.objectives.len(), 6, "{:?} expected 6 objectives", archetype);
  731. let coo = graph.center_of_operations().unwrap();
  732. assert_eq!(coo.role, ObjectiveRole::CenterOfOperations);
  733. // 2. Every ObjectivePoint has valid connected SpawnPoints (bidirectional integrity)
  734. for obj in &graph.objectives {
  735. assert!(
  736. !obj.connected_spawn_ids.is_empty(),
  737. "{:?} objective {} has zero connected spawns",
  738. archetype,
  739. obj.name
  740. );
  741. let linked = graph.spawns_for_objective(obj.id, None);
  742. assert_eq!(linked.len(), obj.connected_spawn_ids.len());
  743. for sp in linked {
  744. assert_eq!(sp.linked_objective_id, obj.id);
  745. assert!(
  746. world.nav_grid.is_walkable_world(sp.position.x, sp.position.z),
  747. "{:?} spawn {} not on walkable nav cell",
  748. archetype,
  749. sp.id
  750. );
  751. }
  752. }
  753. assert!(
  754. graph.reinforcement_spawn_for(coo.id, Faction::Militia).is_some(),
  755. "{:?} missing connected ReinforcementSpawn for CenterOfOperations",
  756. archetype
  757. );
  758. assert!(
  759. graph.spawns.iter().any(|s| s.role == SpawnRole::InitialSquadSpawn),
  760. "{:?} missing InitialSquadSpawn",
  761. archetype
  762. );
  763. // 3. Pathfinding connects staging spawn to Center of Operations across bridges if river present
  764. let fed_spawn = graph
  765. .spawns
  766. .iter()
  767. .find(|s| s.role == SpawnRole::InitialSquadSpawn && s.faction == Faction::Federal)
  768. .expect("federal staging spawn")
  769. .position;
  770. let path = world.nav_grid.find_path(fed_spawn, coo.position);
  771. let last_wp = *path.last().expect("path must be non-empty");
  772. assert!(
  773. last_wp.distance(coo.position) < 3.0,
  774. "{:?}: no navigable path from staging spawn {:?} to COO {:?} (ended at {:?})",
  775. archetype,
  776. fed_spawn,
  777. coo.position,
  778. last_wp
  779. );
  780. if world.height_grid.params.has_river {
  781. for pt in &path {
  782. let h = world.height_grid.height_at(pt.x, pt.z);
  783. let on_bridge = world.nav_grid.surface_height(pt.x, pt.z, &world.height_grid)
  784. > world.height_grid.water_level + 0.5;
  785. assert!(
  786. h >= world.height_grid.water_level + 0.1 || on_bridge,
  787. "{:?} path crossed deep water at ({:.1}, {:.1})",
  788. archetype,
  789. pt.x,
  790. pt.z
  791. );
  792. }
  793. }
  794. // 4. Simulation boots cleanly from point_graph and ticks 60 frames without crossing water
  795. let bvh = AcousticBvh::build(world.acoustic_triangles.clone());
  796. let mut sim = Simulation::new(&world);
  797. assert_eq!(sim.mission.objectives.len(), 6);
  798. let sim_cfg = SimConfig::default();
  799. for _ in 0..60 {
  800. sim.step(&sim_cfg, 331.5, &bvh, fed_spawn + Vec3::Y * 4.0);
  801. }
  802. if world.height_grid.params.has_river {
  803. for s in &sim.soldiers {
  804. if s.alive {
  805. let on_bridge = world.nav_grid.surface_height(s.pos.x, s.pos.z, &world.height_grid)
  806. > world.height_grid.water_level + 0.5;
  807. let terrain_h = world.height_grid.height_at(s.pos.x, s.pos.z);
  808. assert!(
  809. on_bridge || terrain_h >= world.height_grid.water_level + 0.1,
  810. "{:?}: soldier #{} walked into water",
  811. archetype,
  812. s.id
  813. );
  814. }
  815. }
  816. }
  817. }
  818. }
  819. #[test]
  820. fn test_stitched_corridor_and_quad_maps_with_transitions() {
  821. use project_cold_water::world::generator::{DynamicMapGenerator, MapGenConfig};
  822. use project_cold_water::world::points::{ObjectiveRole, SpawnRole};
  823. use project_cold_water::world::terrain::{TerrainGrid, ZoneType};
  824. use project_cold_water::world::HeightQuery;
  825. let cases = [
  826. (
  827. "corridor_wet",
  828. MapGenConfig::stitched_corridor(
  829. [ZoneType::FoothillRidge, ZoneType::RiverCrossing, ZoneType::SovietCityCore],
  830. 2025,
  831. ),
  832. true,
  833. glam::Vec2::new(-68.0, 0.0),
  834. ),
  835. (
  836. "quad_wet",
  837. MapGenConfig::stitched_quad(
  838. [
  839. ZoneType::FoothillRidge,
  840. ZoneType::IndustrialOutskirts,
  841. ZoneType::RiverCrossing,
  842. ZoneType::SovietCityCore,
  843. ],
  844. 2026,
  845. ),
  846. true,
  847. glam::Vec2::new(0.0, 0.0),
  848. ),
  849. (
  850. "corridor_dry",
  851. MapGenConfig::stitched_corridor(
  852. [ZoneType::FoothillRidge, ZoneType::SuburbanTown, ZoneType::IndustrialOutskirts],
  853. 2027,
  854. ),
  855. false,
  856. glam::Vec2::new(-68.0, 0.0),
  857. ),
  858. ];
  859. for (label, cfg, expect_water, seam_center) in cases {
  860. let world = DynamicMapGenerator::new(cfg).build();
  861. assert_eq!(world.water_indices.is_empty(), !expect_water, "{label}: water mismatch");
  862. // 1. Verify smooth normalized zone blending across transition seam
  863. let mut saw_blended = false;
  864. for step in -6..=6 {
  865. let sx = seam_center.x + step as f32 * 4.0;
  866. let weights = TerrainGrid::evaluate_zone_weights(&world.height_grid.params, sx, seam_center.y);
  867. let sum: f32 = weights.iter().map(|&(_, w)| w).sum();
  868. assert!((sum - 1.0).abs() < 1e-3, "{label}: zone weights did not normalize ({sum})");
  869. if weights.iter().any(|&(_, w)| w > 0.15 && w < 0.85) {
  870. saw_blended = true;
  871. }
  872. }
  873. assert!(saw_blended, "{label}: expected blended transition weights near seam {:?}", seam_center);
  874. // 2. Verify smooth road elevation continuity (no sharp cliff drops per 3m step)
  875. if let Some(primary_road) = world.height_grid.params.roads.first().copied() {
  876. let rz = primary_road.coord;
  877. let mut prev_y = world.nav_grid.surface_height(-150.0, rz, &world.height_grid);
  878. let mut x = -147.0_f32;
  879. while x <= 150.0 {
  880. let y = world.nav_grid.surface_height(x, rz, &world.height_grid);
  881. let on_river = world.height_grid.params.has_river
  882. && (x - world.height_grid.river_center_x_at(rz)).abs() < 16.0;
  883. if !on_river {
  884. assert!(
  885. (y - prev_y).abs() <= 2.2,
  886. "{label}: sharp height jump {:.2}m at road x={x:.1}, z={rz:.1}",
  887. (y - prev_y).abs()
  888. );
  889. }
  890. prev_y = y;
  891. x += 3.0;
  892. }
  893. }
  894. // 3. Connected Point Graph + COO + NavGrid reachability
  895. let graph = &world.point_graph;
  896. let coo = graph.center_of_operations().expect("missing COO");
  897. assert_eq!(coo.role, ObjectiveRole::CenterOfOperations);
  898. assert_eq!(graph.objectives.len(), 6);
  899. for obj in &graph.objectives {
  900. assert!(!obj.connected_spawn_ids.is_empty(), "{label}: objective {} unlinked", obj.name);
  901. }
  902. assert!(graph.reinforcement_spawn_for(coo.id, Faction::Militia).is_some());
  903. let fed_spawn = graph
  904. .spawns
  905. .iter()
  906. .find(|s| s.role == SpawnRole::InitialSquadSpawn && s.faction == Faction::Federal)
  907. .expect("federal spawn")
  908. .position;
  909. let path = world.nav_grid.find_path(fed_spawn, coo.position);
  910. let last_wp = *path.last().expect("non-empty path");
  911. assert!(
  912. last_wp.distance(coo.position) < 4.5,
  913. "{label}: unreachable COO from {:?} (ended at {:?})",
  914. fed_spawn,
  915. last_wp
  916. );
  917. // 4. Simulation stability over 60 ticks with zero water crossings
  918. let bvh = AcousticBvh::build(world.acoustic_triangles.clone());
  919. let mut sim = Simulation::new(&world);
  920. let sim_cfg = SimConfig::default();
  921. for _ in 0..60 {
  922. sim.step(&sim_cfg, 331.5, &bvh, fed_spawn + Vec3::Y * 4.0);
  923. }
  924. if world.height_grid.params.has_river {
  925. for s in &sim.soldiers {
  926. if s.alive {
  927. let on_bridge = world.nav_grid.surface_height(s.pos.x, s.pos.z, &world.height_grid)
  928. > world.height_grid.water_level + 0.5;
  929. let terrain_h = world.height_grid.height_at(s.pos.x, s.pos.z);
  930. assert!(
  931. on_bridge || terrain_h >= world.height_grid.water_level + 0.1,
  932. "{label}: soldier #{} walked into water",
  933. s.id
  934. );
  935. }
  936. }
  937. }
  938. }
  939. }
  940. #[test]
  941. fn test_swept_capsule_hit_detection_open_field_headshot_wall_occlusion_and_point_blank() {
  942. use project_cold_water::sim::ballistics::{
  943. intersect_soldier_hitbox, HitZone, SoldierHitbox,
  944. };
  945. use project_cold_water::sim::player::{FpsInput, HitMarkerKind};
  946. use project_cold_water::world::actors_mesh::ActorPosture;
  947. use project_cold_water::world::WeaponKind;
  948. let world = FoothillRiverTownMap.build();
  949. let bvh = AcousticBvh::build(world.acoustic_triangles.clone());
  950. let mut sim = Simulation::new(&world);
  951. let cfg = SimConfig::default();
  952. // Clear 28m open-field meadow lane on west bank (`(-68, -12)` -> `(-40, -12)`)
  953. let p_origin = world.nav_grid.nearest_walkable(Vec3::new(-68.0, 3.0, -12.0));
  954. let target_pos = world.nav_grid.nearest_walkable(Vec3::new(-40.0, 3.0, -12.0));
  955. let fed_id = sim.soldiers.iter().position(|s| s.faction == Faction::Federal).unwrap();
  956. let mil_id = sim.soldiers.iter().position(|s| s.faction == Faction::Militia).unwrap();
  957. for (i, s) in sim.soldiers.iter_mut().enumerate() {
  958. if i != fed_id && i != mil_id {
  959. s.alive = false;
  960. s.hp = 0.0;
  961. }
  962. }
  963. sim.soldiers[fed_id].pos = p_origin;
  964. sim.soldiers[fed_id].alive = true;
  965. sim.soldiers[fed_id].hp = 100.0;
  966. sim.soldiers[mil_id].pos = target_pos;
  967. sim.soldiers[mil_id].move_target = target_pos;
  968. sim.soldiers[mil_id].cover_node = None;
  969. sim.soldiers[mil_id].alive = true;
  970. sim.soldiers[mil_id].hp = 200.0;
  971. sim.soldiers[mil_id].posture = ActorPosture::Standing;
  972. sim.soldiers[mil_id].fire_timer = 999.0;
  973. let shooter = sim.soldiers[fed_id].clone();
  974. sim.player.deploy_into_soldier(&shooter);
  975. sim.player.select_weapon(WeaponKind::Ak74m);
  976. sim.player.ads_blend = 1.0;
  977. let aim_at = |player: &mut project_cold_water::sim::player::FpsPlayerState, b: &AcousticBvh, pt: Vec3| {
  978. let eye = player.eye_position(b);
  979. let d = (pt - eye).normalize();
  980. player.yaw = d.x.atan2(-d.z);
  981. player.pitch = d.y.asin();
  982. };
  983. // Case A: Open-Field Direct Chest Hit (~32m, no wall behind target)
  984. let chest = target_pos + Vec3::new(0.0, 1.12, 0.0);
  985. aim_at(&mut sim.player, &bvh, chest);
  986. sim.player.fire_cooldown = 0.0;
  987. sim.step_fps_player(1.0 / 60.0, &FpsInput { fire_held: true, ads_held: true, ..Default::default() }, &bvh);
  988. for _ in 0..8 {
  989. sim.soldiers[mil_id].fire_timer = 999.0;
  990. sim.step(&cfg, 331.5, &bvh, p_origin + Vec3::Y * 1.6);
  991. }
  992. assert!(sim.soldiers[mil_id].hp < 195.0, "Open-field chest shot failed to register hit! hp={}", sim.soldiers[mil_id].hp);
  993. assert!(sim.player.hit_marker_timer > 0.0, "Missing hit marker on open-field chest hit");
  994. assert!(sim.projectiles.is_empty(), "Bullet should terminate upon striking soldier");
  995. // Case B: Open-Field Headshot (2.2x damage + Headshot/Kill marker)
  996. sim.soldiers[mil_id].hp = 200.0;
  997. sim.player.select_weapon(WeaponKind::Svd);
  998. sim.player.ads_blend = 1.0;
  999. sim.player.fire_cooldown = 0.0;
  1000. let head = SoldierHitbox::from_soldier(&sim.soldiers[mil_id]).head_center;
  1001. aim_at(&mut sim.player, &bvh, head);
  1002. sim.step_fps_player(1.0 / 60.0, &FpsInput { fire_just_pressed: true, ads_held: true, ..Default::default() }, &bvh);
  1003. for _ in 0..8 {
  1004. sim.soldiers[mil_id].fire_timer = 999.0;
  1005. sim.step(&cfg, 331.5, &bvh, p_origin + Vec3::Y * 1.6);
  1006. }
  1007. let dmg_dealt = 200.0 - sim.soldiers[mil_id].hp;
  1008. assert!(dmg_dealt > 85.0 * 1.8, "Expected 2.2x SVD headshot damage (>153), got {dmg_dealt}");
  1009. assert!(
  1010. matches!(sim.player.hit_marker_kind, HitMarkerKind::Headshot | HitMarkerKind::Kill),
  1011. "Expected Headshot or Kill hitmarker, got {:?}",
  1012. sim.player.hit_marker_kind
  1013. );
  1014. // Case C: Point-Blank Shot (0.6m directly in front of eye)
  1015. sim.soldiers[mil_id].alive = true;
  1016. sim.soldiers[mil_id].hp = 100.0;
  1017. sim.soldiers[mil_id].posture = ActorPosture::Standing;
  1018. let close_pos = sim.player.pos + Vec3::new(0.6, 0.0, 0.0);
  1019. sim.soldiers[mil_id].pos = close_pos;
  1020. sim.soldiers[mil_id].move_target = close_pos;
  1021. aim_at(&mut sim.player, &bvh, close_pos + Vec3::new(0.0, 1.25, 0.0));
  1022. sim.player.fire_cooldown = 0.0;
  1023. sim.player.hit_marker_timer = 0.0;
  1024. sim.step_fps_player(1.0 / 60.0, &FpsInput { fire_just_pressed: true, ads_held: true, ..Default::default() }, &bvh);
  1025. sim.soldiers[mil_id].fire_timer = 999.0;
  1026. sim.step(&cfg, 331.5, &bvh, p_origin + Vec3::Y * 1.6);
  1027. assert!(sim.soldiers[mil_id].hp < 100.0, "Point-blank shot tunneled past enemy!");
  1028. // Case D: Wall Occlusion (brick wall between shooter and enemy blocks bullet completely)
  1029. let wall_bvh = AcousticBvh::build(
  1030. make_quad_tris(
  1031. Vec3::new(-2.0, -1.0, -5.0),
  1032. Vec3::new(-2.0, 6.0, -5.0),
  1033. Vec3::new(-2.0, 6.0, 5.0),
  1034. Vec3::new(-2.0, -1.0, 5.0),
  1035. MaterialId::Concrete,
  1036. )
  1037. .to_vec(),
  1038. );
  1039. sim.soldiers[mil_id].alive = true;
  1040. sim.soldiers[mil_id].hp = 100.0;
  1041. sim.soldiers[mil_id].pos = Vec3::new(4.0, 0.0, 0.0);
  1042. sim.soldiers[mil_id].move_target = Vec3::new(4.0, 0.0, 0.0);
  1043. let hb_wall = SoldierHitbox::from_soldier(&sim.soldiers[mil_id]);
  1044. let mut occ_projs = vec![Projectile {
  1045. pos: Vec3::new(-6.0, 1.2, 0.0),
  1046. prev_pos: Vec3::new(-6.0, 1.2, 0.0),
  1047. vel: Vec3::new(880.0, 0.0, 0.0),
  1048. kind: ProjectileKind::Bullet,
  1049. faction: Faction::Federal,
  1050. damage: 34.0,
  1051. suppression: 0.2,
  1052. blast_radius: 0.0,
  1053. crater_radius: 0.0,
  1054. drag: 0.0,
  1055. age: 0.0,
  1056. max_age: 1.0,
  1057. is_tracer: false,
  1058. crack_triggered: true,
  1059. whistle_emitted: true,
  1060. from_player: true,
  1061. owner_player: None,
  1062. visual_offset: Vec3::ZERO,
  1063. guidance: Default::default(),
  1064. guide_vehicle_id: None,
  1065. is_heavy_ap: false,
  1066. }];
  1067. let mut occ_hits = Vec::new();
  1068. let mut dummy_s = Vec::new();
  1069. let mut dummy_i = Vec::new();
  1070. let mut dummy_e = Vec::new();
  1071. let mut dummy_t = Vec::new();
  1072. let mut dummy_l = Vec::new();
  1073. step_projectiles(
  1074. &mut occ_projs,
  1075. 0.03,
  1076. 331.5,
  1077. &wall_bvh,
  1078. &[hb_wall],
  1079. Vec3::ZERO,
  1080. &mut dummy_s,
  1081. &mut occ_hits,
  1082. &mut dummy_i,
  1083. &mut dummy_e,
  1084. &mut dummy_t,
  1085. &mut dummy_l,
  1086. );
  1087. assert!(occ_hits.is_empty(), "Bullet penetrated wall BVH to hit enemy behind wall!");
  1088. assert!(!dummy_i.is_empty(), "Bullet should have impacted the wall BVH");
  1089. // Case E: Near-Miss Does Not Deal Phantom Ground-Splash Damage
  1090. let side_hit = intersect_soldier_hitbox(
  1091. Vec3::new(-6.0, 1.1, 1.0),
  1092. Vec3::X,
  1093. 20.0,
  1094. &hb_wall,
  1095. );
  1096. assert!(side_hit.is_none(), "1.0m side miss should not hit soldier hitbox");
  1097. // Case F: Crouched Hitbox Respects Lower Stance Height
  1098. let mut crouched = sim.soldiers[mil_id].clone();
  1099. crouched.pos = Vec3::ZERO;
  1100. crouched.posture = ActorPosture::Crouched;
  1101. let hb_crouch = SoldierHitbox::from_soldier(&crouched);
  1102. assert!(
  1103. intersect_soldier_hitbox(Vec3::new(-5.0, 1.68, 0.0), Vec3::X, 15.0, &hb_crouch).is_none(),
  1104. "High shot at y=1.68 should pass cleanly over crouched soldier head"
  1105. );
  1106. let crouch_chest = intersect_soldier_hitbox(Vec3::new(-5.0, 0.90, 0.0), Vec3::X, 15.0, &hb_crouch);
  1107. assert!(
  1108. matches!(crouch_chest, Some((_, HitZone::Torso | HitZone::Head))),
  1109. "Chest-level shot at y=0.90 should hit crouched soldier, got {:?}",
  1110. crouch_chest
  1111. );
  1112. }
  1113. #[test]
  1114. fn test_game_director_spawning_recycling_objectives_and_player_respawn() {
  1115. use project_cold_water::sim::director::{GmEntityPreset, GmSelection};
  1116. use project_cold_water::sim::objectives::ObjectiveKind;
  1117. use project_cold_water::world::{WeaponKind, MAX_SKINNED_SOLDIERS};
  1118. let world = FoothillRiverTownMap.build();
  1119. let bvh = AcousticBvh::build(world.acoustic_triangles.clone());
  1120. let mut sim = Simulation::new(&world);
  1121. let cfg = SimConfig::default();
  1122. // 1. Default PlayerSpawnPoints are populated for both factions
  1123. assert!(sim.player_spawns.iter().any(|s| s.active && s.faction == Faction::Federal));
  1124. assert!(sim.player_spawns.iter().any(|s| s.active && s.faction == Faction::Militia));
  1125. // 2. GM places Federal squad, Militia warband, teleport, heal, custom objective & smoke screen
  1126. sim.director.active = true;
  1127. sim.gm_place_preset(GmEntityPreset::FedRifleSquad, Vec3::new(-44.0, 3.0, -14.0));
  1128. let fed_sq = match sim.director.selection {
  1129. GmSelection::Squad(id) => id,
  1130. other => panic!("expected squad selection after GM spawn, got {:?}", other),
  1131. };
  1132. assert!(sim.squads[fed_sq].alive_count(&sim.soldiers) >= 4);
  1133. // Damage and heal squad
  1134. for &id in &sim.squads[fed_sq].member_ids {
  1135. sim.soldiers[id].hp = 35.0;
  1136. sim.soldiers[id].suppression = 0.8;
  1137. }
  1138. sim.gm_heal_squad(fed_sq);
  1139. for &id in &sim.squads[fed_sq].member_ids {
  1140. assert_eq!(sim.soldiers[id].hp, 100.0);
  1141. assert_eq!(sim.soldiers[id].suppression, 0.0);
  1142. }
  1143. // Teleport squad safely onto east bank
  1144. sim.gm_teleport_squad(fed_sq, Vec3::new(26.0, 3.0, -6.0));
  1145. assert!(sim.squads[fed_sq].center_pos(&sim.soldiers).x > 10.0);
  1146. // Custom GM objective injection & activation
  1147. let prev_objs = sim.mission.objectives.len();
  1148. sim.gm_place_preset(GmEntityPreset::ObjAssault, Vec3::new(32.0, 3.0, 6.0));
  1149. assert_eq!(sim.mission.objectives.len(), prev_objs + 1);
  1150. assert!(matches!(
  1151. sim.mission.active_objective().unwrap().kind,
  1152. ObjectiveKind::AssaultPosition { .. }
  1153. ));
  1154. // Smoke screen spawns long-lived puffs
  1155. sim.gm_place_preset(GmEntityPreset::SmokeScreen, Vec3::new(10.0, 3.0, 0.0));
  1156. assert!(sim.smoke_puffs.len() >= 20);
  1157. // 3. Dead-slot recycling past MAX_SKINNED_SOLDIERS = 192
  1158. for _ in 0..(MAX_SKINNED_SOLDIERS / 5 + 3) {
  1159. sim.gm_place_preset(GmEntityPreset::MilFighterBand, Vec3::new(42.0, 3.0, 12.0));
  1160. if let GmSelection::Squad(sq_id) = sim.director.selection {
  1161. assert!(sim.squads[sq_id].alive_count(&sim.soldiers) > 0);
  1162. sim.gm_delete_squad(sq_id);
  1163. }
  1164. }
  1165. assert!(
  1166. sim.soldiers.len() <= MAX_SKINNED_SOLDIERS,
  1167. "GM dead-slot recycler exceeded MAX_SKINNED_SOLDIERS ({})",
  1168. sim.soldiers.len()
  1169. );
  1170. // Spawning a fresh squad after hitting capacity still succeeds cleanly
  1171. sim.gm_place_preset(GmEntityPreset::MilSniperPair, Vec3::new(40.0, 3.0, -10.0));
  1172. let mil_sq = match sim.director.selection {
  1173. GmSelection::Squad(id) => id,
  1174. _ => panic!("expected militia squad selection"),
  1175. };
  1176. assert_eq!(sim.squads[mil_sq].alive_count(&sim.soldiers), 2);
  1177. // 4. Custom GM PlayerSpawnPoint + Player KIA -> Countdown -> Respawn Flow
  1178. let gm_spawn_pos = world.nav_grid.nearest_walkable(Vec3::new(-32.0, 3.0, -12.0));
  1179. let gm_spawn_id = sim.gm_add_player_spawn(Faction::Federal, gm_spawn_pos);
  1180. assert!(sim.spawn_player_at(gm_spawn_id, WeaponKind::Ak74m));
  1181. assert!(sim.player.active && sim.player.alive);
  1182. // Kill player and verify automatic KIA countdown + deploy menu open
  1183. let psid = sim.player.soldier_id.unwrap();
  1184. sim.soldiers[psid].hp = 0.0;
  1185. sim.soldiers[psid].alive = false;
  1186. sim.respawn.respawn_delay_secs = 0.5;
  1187. for _ in 0..45 {
  1188. sim.step(&cfg, 331.5, &bvh, gm_spawn_pos + Vec3::Y * 4.0);
  1189. }
  1190. assert!(!sim.player.alive);
  1191. assert!(sim.respawn.menu_open, "KIA must automatically open respawn menu");
  1192. assert_eq!(sim.respawn.respawn_countdown, 0.0, "Respawn countdown should finish after 0.75s");
  1193. // Respawn player with PKM at the GM spawn point!
  1194. assert!(sim.spawn_player_at(gm_spawn_id, WeaponKind::Pkm));
  1195. assert!(sim.player.active && sim.player.alive);
  1196. assert_eq!(sim.player.hp, 100.0);
  1197. assert_eq!(sim.player.weapon, WeaponKind::Pkm);
  1198. assert!(!sim.respawn.menu_open);
  1199. assert!(sim.player.pos.distance(gm_spawn_pos) < 3.0);
  1200. let new_psid = sim.player.soldier_id.unwrap();
  1201. assert!(sim.soldiers[new_psid].alive);
  1202. }
  1203. #[test]
  1204. fn test_phase1_ai_reaction_delay_aim_settling_suppression_and_192_capacity() {
  1205. use project_cold_water::core::config::AiSkillLevel;
  1206. use project_cold_water::sim::ai::compute_ai_shot_spread;
  1207. use project_cold_water::sim::director::GmEntityPreset;
  1208. use project_cold_water::world::actors_mesh::{ActorPosture, ActorRenderBatch};
  1209. use project_cold_water::world::MAX_SKINNED_SOLDIERS;
  1210. assert_eq!(MAX_SKINNED_SOLDIERS, 192);
  1211. let world = FoothillRiverTownMap.build();
  1212. let bvh = AcousticBvh::build(world.acoustic_triangles.clone());
  1213. let mut sim = Simulation::new(&world);
  1214. let cfg = SimConfig::default();
  1215. // Isolate one Federal soldier and one Militia soldier 28m apart in clear west meadow
  1216. let p_fed = world.nav_grid.nearest_walkable(Vec3::new(-68.0, 3.0, -12.0));
  1217. let p_mil = world.nav_grid.nearest_walkable(Vec3::new(-40.0, 3.0, -12.0));
  1218. let fed_id = sim.soldiers.iter().position(|s| s.faction == Faction::Federal).unwrap();
  1219. let mil_id = sim.soldiers.iter().position(|s| s.faction == Faction::Militia).unwrap();
  1220. for (i, s) in sim.soldiers.iter_mut().enumerate() {
  1221. if i != fed_id && i != mil_id {
  1222. s.alive = false;
  1223. s.hp = 0.0;
  1224. }
  1225. }
  1226. sim.soldiers[fed_id].pos = p_fed;
  1227. sim.soldiers[fed_id].move_target = p_fed;
  1228. sim.soldiers[fed_id].cover_node = None;
  1229. sim.soldiers[fed_id].hp = 500.0;
  1230. sim.soldiers[fed_id].yaw = std::f32::consts::FRAC_PI_2;
  1231. sim.soldiers[fed_id].fire_timer = 999.0;
  1232. sim.soldiers[mil_id].pos = p_mil;
  1233. sim.soldiers[mil_id].move_target = p_mil;
  1234. sim.soldiers[mil_id].cover_node = None;
  1235. sim.soldiers[mil_id].hp = 500.0;
  1236. sim.soldiers[mil_id].yaw = -std::f32::consts::FRAC_PI_2; // facing fed_id
  1237. sim.soldiers[mil_id].posture = ActorPosture::Standing;
  1238. sim.soldiers[mil_id].fire_timer = 0.0;
  1239. sim.soldiers[mil_id].shots_fired = 0;
  1240. // A1. Spotting reaction delay: after 10 ticks (~0.17s), defender is still recognizing target & hasn't laser-fired
  1241. for _ in 0..10 {
  1242. sim.soldiers[fed_id].fire_timer = 999.0;
  1243. sim.step(&cfg, 331.5, &bvh, p_fed + Vec3::Y * 4.0);
  1244. }
  1245. assert_eq!(
  1246. sim.soldiers[mil_id].shots_fired, 0,
  1247. "AI should not fire instantaneously within first 0.17s (spot_progress={})",
  1248. sim.soldiers[mil_id].spot_progress
  1249. );
  1250. assert!(sim.soldiers[mil_id].spot_progress > 0.1 && sim.soldiers[mil_id].spot_progress < 1.0);
  1251. // A2. After completing spot reaction (< 1.25s), AI spots & opens suppressive fire
  1252. for _ in 0..65 {
  1253. sim.soldiers[fed_id].fire_timer = 999.0;
  1254. sim.step(&cfg, 331.5, &bvh, p_fed + Vec3::Y * 4.0);
  1255. }
  1256. assert!(sim.soldiers[mil_id].spot_progress >= 1.0);
  1257. assert!(sim.soldiers[mil_id].shots_fired > 0, "AI failed to engage after spotting");
  1258. // A3. Vision cone + Gunfire hearing alert: turn mil_id 180 deg away from silent fed_id
  1259. sim.projectiles.clear();
  1260. sim.soldiers[mil_id].yaw = std::f32::consts::FRAC_PI_2; // facing east, away from -68
  1261. sim.soldiers[mil_id].spot_target = None;
  1262. sim.soldiers[mil_id].spot_progress = 0.0;
  1263. sim.soldiers[mil_id].alert_pos = None;
  1264. sim.soldiers[mil_id].alert_timer = 0.0;
  1265. let initial_yaw = sim.soldiers[mil_id].yaw;
  1266. for _ in 0..30 {
  1267. sim.soldiers[fed_id].fire_timer = 999.0;
  1268. sim.step(&cfg, 331.5, &bvh, p_fed + Vec3::Y * 4.0);
  1269. }
  1270. assert_eq!(sim.soldiers[mil_id].spot_progress, 0.0, "Blind spot behind soldier should not spot silent target 28m away");
  1271. // Fire a shot within hearing_range (28m < 88m) -> mil_id hears it & turns toward shooter!
  1272. sim.trigger_test_shot(p_fed + Vec3::Y * 1.4, Vec3::Z, SoundKind::Ak74mShot);
  1273. for _ in 0..8 {
  1274. sim.soldiers[fed_id].fire_timer = 999.0;
  1275. sim.step(&cfg, 331.5, &bvh, p_fed + Vec3::Y * 4.0);
  1276. }
  1277. assert!(sim.soldiers[mil_id].alert_pos.is_some(), "Nearby gunshot should trigger AI hearing alert");
  1278. assert!(
  1279. (sim.soldiers[mil_id].yaw - initial_yaw).abs() > 0.2,
  1280. "Hearing alert should rotate soldier toward threat"
  1281. );
  1282. // B. Aim settling, suppression, movement & Skill preset accuracy curves
  1283. let base = 0.024;
  1284. let s_open = compute_ai_shot_spread(base, AiSkillLevel::Regular, 0.0, 0.0, false, false, 40.0);
  1285. let s_settled = compute_ai_shot_spread(base, AiSkillLevel::Regular, 1.0, 0.0, false, false, 40.0);
  1286. let s_moving = compute_ai_shot_spread(base, AiSkillLevel::Regular, 1.0, 0.0, true, false, 40.0);
  1287. let s_supp = compute_ai_shot_spread(base, AiSkillLevel::Regular, 1.0, 0.85, false, false, 40.0);
  1288. let s_spets = compute_ai_shot_spread(base, AiSkillLevel::Spetsnaz, 1.0, 0.0, false, false, 40.0);
  1289. let s_con = compute_ai_shot_spread(base, AiSkillLevel::Conscript, 1.0, 0.0, false, false, 40.0);
  1290. assert!(s_open > s_settled * 2.0, "Opening shot spread must be >2x settled spread");
  1291. assert!(s_moving > s_settled * 1.5, "Moving shot spread must degrade accuracy");
  1292. assert!(s_supp > s_settled * 3.0, "Heavy suppression must heavily degrade accuracy");
  1293. assert!(s_spets < s_settled && s_settled < s_con);
  1294. // C. 192-Actor Capacity: Spawn >100 simultaneous live soldiers & pack ActorRenderBatch cleanly
  1295. let mut cap_sim = Simulation::new(&world);
  1296. for k in 0..16 {
  1297. let z = -30.0 + (k as f32) * 3.5;
  1298. cap_sim.gm_place_preset(GmEntityPreset::FedRifleSquad, Vec3::new(-44.0, 3.0, z));
  1299. }
  1300. let (fed_cnt, mil_cnt) = cap_sim.alive_counts();
  1301. let total_live = fed_cnt + mil_cnt;
  1302. assert!(total_live > 100 && total_live <= MAX_SKINNED_SOLDIERS, "Unexpected total_live={total_live}");
  1303. let mut batch = ActorRenderBatch::default();
  1304. cap_sim.build_actor_batch(Some(0), &mut batch);
  1305. assert_eq!(batch.soldier_count as usize, total_live);
  1306. }
  1307. #[test]
  1308. fn test_3km_chunked_theater_lod_and_hierarchical_nav() {
  1309. use project_cold_water::world::generator::{DynamicMapGenerator, MapGenConfig};
  1310. let t0 = std::time::Instant::now();
  1311. let world = DynamicMapGenerator::new(MapGenConfig::macro_theater_3km(4242)).build();
  1312. let elapsed = t0.elapsed();
  1313. assert!(elapsed.as_secs_f32() < 4.5, "3km theater took too long to build: {:?}", elapsed);
  1314. assert_eq!(world.world_half_extent, 1536.0);
  1315. let chunks = world
  1316. .terrain_chunks
  1317. .as_ref()
  1318. .expect("3km theater must emit TerrainChunkMesh");
  1319. assert_eq!(chunks.chunks.len(), 256, "Expected 16x16 terrain chunks");
  1320. for ch in &chunks.chunks {
  1321. assert!(ch.lods[0].index_count > ch.lods[1].index_count);
  1322. assert!(ch.lods[1].index_count > ch.lods[2].index_count);
  1323. assert!(ch.lods[2].index_count > 0);
  1324. }
  1325. assert!(world.nav_grid.is_hierarchical, "3km theater should bake coarse hierarchical NavGrid");
  1326. assert!(world.nav_grid.bridges.len() >= 3, "3km theater must stamp 3 cross-river highway bridges");
  1327. // Verify coarse regional vehicle route spans >900m from West bank (-520, 0) across central bridge to East bank (520, 0)
  1328. let west = world.nav_grid.nearest_walkable(Vec3::new(-520.0, 0.0, 0.0));
  1329. let east = world.nav_grid.nearest_walkable(Vec3::new(520.0, 0.0, 0.0));
  1330. let path = world.nav_grid.find_vehicle_path(west, east);
  1331. let end = path.last().copied().unwrap_or(west);
  1332. assert!(
  1333. end.distance(east) < 18.0,
  1334. "Hierarchical vehicle path failed to reach East bank across 3km river! end={:?} east={:?}",
  1335. end,
  1336. east
  1337. );
  1338. for p in &path {
  1339. assert!(world.nav_grid.is_walkable_world(p.x, p.z), "Vehicle waypoint {:?} fell into blocked river", p);
  1340. }
  1341. }
  1342. #[test]
  1343. fn test_vehicles_driving_suspension_btr_armor_turret_and_dismount() {
  1344. use project_cold_water::sim::vehicles::{VehicleInput, VehicleSeatRole};
  1345. use project_cold_water::world::actors_mesh::ActorRenderBatch;
  1346. use project_cold_water::world::VehicleKind;
  1347. let world = FoothillRiverTownMap.build();
  1348. let bvh = AcousticBvh::build(world.acoustic_triangles.clone());
  1349. let mut sim = Simulation::new(&world);
  1350. let cfg = SimConfig::default();
  1351. // Verify all 3 vehicle meshes exist cleanly in ActorMeshLibrary
  1352. assert!(!sim.vehicles.is_empty());
  1353. let uaz_idx = sim
  1354. .vehicles
  1355. .iter()
  1356. .position(|v| v.kind == VehicleKind::Uaz469)
  1357. .expect("UAZ-469 starter missing");
  1358. let btr_idx = sim
  1359. .vehicles
  1360. .iter()
  1361. .position(|v| v.kind == VehicleKind::Btr80)
  1362. .expect("BTR-80 starter missing");
  1363. // 1. Player deploys on foot, walks beside UAZ-469, enters [F], drives forward, switches seats, and exits [F]
  1364. let s0 = sim.soldiers[0].clone();
  1365. sim.player.deploy_into_soldier(&s0);
  1366. sim.player.pos = sim.vehicles[uaz_idx].pos + Vec3::new(0.0, 0.0, 2.0);
  1367. assert!(sim.try_player_toggle_vehicle().is_some(), "Should enter nearby UAZ-469");
  1368. assert_eq!(sim.player.in_vehicle, Some((uaz_idx, 0)));
  1369. let start_pos = sim.vehicles[uaz_idx].pos;
  1370. let drive_in = VehicleInput {
  1371. throttle: 1.0,
  1372. steer: 0.25,
  1373. ..Default::default()
  1374. };
  1375. for _ in 0..45 {
  1376. sim.step_with_vehicle_input(&cfg, 331.5, &bvh, start_pos, Some(&drive_in));
  1377. }
  1378. assert!(
  1379. sim.vehicles[uaz_idx].pos.distance(start_pos) > 3.0,
  1380. "Driven UAZ-469 did not accelerate forward! delta={}",
  1381. sim.vehicles[uaz_idx].pos.distance(start_pos)
  1382. );
  1383. sim.try_player_toggle_vehicle();
  1384. assert!(sim.player.in_vehicle.is_none(), "Player should exit vehicle cleanly");
  1385. // 2. BTR-80 Armor Immunity vs Small Arms & Gunner 14.5mm KPVT Fire
  1386. let btr_hp_before = sim.vehicles[btr_idx].hp;
  1387. let btr_p = sim.vehicles[btr_idx].pos + Vec3::Y * 1.1;
  1388. // Militia 5.45/7.62 bullet fired directly into Federal BTR-80 glacis -> ricochets with ZERO hull damage!
  1389. sim.projectiles.clear();
  1390. sim.projectiles.push(Projectile {
  1391. pos: btr_p + Vec3::new(0.0, 0.0, 6.0),
  1392. prev_pos: btr_p + Vec3::new(0.0, 0.0, 6.0),
  1393. vel: Vec3::new(0.0, 0.0, -850.0),
  1394. kind: ProjectileKind::Bullet,
  1395. faction: Faction::Militia,
  1396. damage: 38.0,
  1397. suppression: 0.2,
  1398. blast_radius: 0.0,
  1399. crater_radius: 0.0,
  1400. drag: 0.0,
  1401. age: 0.0,
  1402. max_age: 1.0,
  1403. is_tracer: false,
  1404. crack_triggered: false,
  1405. whistle_emitted: true,
  1406. from_player: false,
  1407. owner_player: None,
  1408. visual_offset: Vec3::ZERO,
  1409. guidance: Default::default(),
  1410. guide_vehicle_id: None,
  1411. is_heavy_ap: false,
  1412. });
  1413. for _ in 0..5 {
  1414. sim.step(&cfg, 331.5, &bvh, btr_p);
  1415. }
  1416. assert_eq!(sim.vehicles[btr_idx].hp, btr_hp_before, "Rifle bullet should ricochet off BTR-80 armor!");
  1417. assert!(
  1418. sim.pending_sounds.iter().any(|ev| ev.kind == SoundKind::Ricochet),
  1419. "BTR-80 armor deflection should emit Ricochet sound"
  1420. );
  1421. // RPG-7V warhead hits BTR-80 -> penetrates armor and deals heavy damage!
  1422. sim.projectiles.push(Projectile {
  1423. pos: btr_p + Vec3::new(0.0, 0.0, 6.0),
  1424. prev_pos: btr_p + Vec3::new(0.0, 0.0, 6.0),
  1425. vel: Vec3::new(0.0, 0.0, -280.0),
  1426. kind: ProjectileKind::RpgRocket,
  1427. faction: Faction::Militia,
  1428. damage: 210.0,
  1429. suppression: 1.0,
  1430. blast_radius: 6.0,
  1431. crater_radius: 1.65,
  1432. drag: 0.0,
  1433. age: 0.0,
  1434. max_age: 1.0,
  1435. is_tracer: false,
  1436. crack_triggered: false,
  1437. whistle_emitted: true,
  1438. from_player: false,
  1439. owner_player: None,
  1440. visual_offset: Vec3::ZERO,
  1441. guidance: Default::default(),
  1442. guide_vehicle_id: None,
  1443. is_heavy_ap: true,
  1444. });
  1445. for _ in 0..5 {
  1446. sim.step(&cfg, 331.5, &bvh, btr_p);
  1447. }
  1448. assert!(sim.vehicles[btr_idx].hp < btr_hp_before - 150.0, "RPG-7V warhead must damage BTR-80!");
  1449. // Player enters BTR-80, switches to Seat 2 (Gunner), and fires 14.5mm KPVT!
  1450. sim.player.pos = sim.vehicles[btr_idx].pos + Vec3::new(0.0, 0.0, 2.0);
  1451. sim.try_player_toggle_vehicle();
  1452. sim.try_player_switch_seat(1);
  1453. let (_, seat_i) = sim.player.in_vehicle.unwrap();
  1454. assert_eq!(sim.vehicles[btr_idx].seats[seat_i].0, VehicleSeatRole::Gunner);
  1455. sim.pending_sounds.clear();
  1456. let shoot_in = VehicleInput {
  1457. turret_fire: true,
  1458. aim_yaw_pitch: Some((1.2, 0.05)),
  1459. ..Default::default()
  1460. };
  1461. sim.step_with_vehicle_input(&cfg, 331.5, &bvh, btr_p, Some(&shoot_in));
  1462. assert!(sim.pending_sounds.iter().any(|ev| ev.kind == SoundKind::KpvtShot), "14.5mm KPVT must emit KpvtShot");
  1463. sim.try_player_toggle_vehicle();
  1464. // 3. Game Director spawns crewed Ural-4320 & taking fire automatically dismounts passengers
  1465. let vid = sim.gm_spawn_vehicle(Faction::Federal, VehicleKind::Ural4320, Vec3::new(-64.0, 3.0, -6.0), true);
  1466. let v_idx = sim.vehicles.iter().position(|v| v.id == vid).unwrap();
  1467. assert!(sim.vehicles[v_idx].passenger_count() > 0, "Crewed Ural must have passengers");
  1468. sim.vehicles[v_idx].taking_fire_timer = 2.0;
  1469. sim.step(&cfg, 331.5, &bvh, Vec3::ZERO);
  1470. assert_eq!(sim.vehicles[v_idx].passenger_count(), 0, "AI passengers must dismount under fire!");
  1471. let mut batch = ActorRenderBatch::default();
  1472. sim.build_actor_batch(Some(0), &mut batch);
  1473. assert!(!batch.veh_uaz_body.is_empty() && !batch.veh_ural_body.is_empty() && !batch.veh_btr_hull.is_empty());
  1474. }
  1475. #[test]
  1476. fn test_bullet_hit_effects_all_materials_vehicles_and_soldiers() {
  1477. use project_cold_water::core::materials::MaterialId;
  1478. use project_cold_water::sim::ballistics::HitZone;
  1479. use project_cold_water::sim::effects::{HitParticleKind, ImpactEffectsState};
  1480. use project_cold_water::world::actors_mesh::ActorRenderBatch;
  1481. let mut fx = ImpactEffectsState::default();
  1482. let mut lights = Vec::new();
  1483. // 1. World material impacts (Concrete, Steel, Brick, Snow, Mud, Wood, Water)
  1484. for mat in [
  1485. MaterialId::Concrete,
  1486. MaterialId::SteelHulk,
  1487. MaterialId::BrickRubble,
  1488. MaterialId::WinterSnow,
  1489. MaterialId::WinterMud,
  1490. MaterialId::WoodFurniture,
  1491. MaterialId::ColdWater,
  1492. ] {
  1493. fx.spawn_world_impact(Vec3::new(1.0, 2.0, 3.0), Vec3::Y, mat, 42.0, &mut lights);
  1494. }
  1495. assert!(
  1496. fx.particles.iter().any(|p| p.kind == HitParticleKind::Chunk),
  1497. "Material hits must spawn debris chunks"
  1498. );
  1499. assert!(
  1500. fx.particles.iter().any(|p| p.kind == HitParticleKind::Puff),
  1501. "Material hits must spawn dust/spray/flash puffs"
  1502. );
  1503. assert!(!fx.sparks.is_empty(), "Steel/concrete/water hits must spawn spark/droplet streaks");
  1504. assert!(!lights.is_empty(), "Steel/concrete hits should emit dynamic flash lights");
  1505. // Water should NOT create surface decal; the other 6 materials should create 6 decals
  1506. assert_eq!(fx.decals.len(), 6, "Expected 6 solid-surface bullet decals and 0 on water");
  1507. // 2. Vehicle armor ricochet & soldier helmet/torso hits + explosion burst
  1508. fx.spawn_vehicle_hit(Vec3::ZERO, Vec3::Z, true, true, &mut lights);
  1509. fx.spawn_soldier_hit(Vec3::new(0.0, 1.7, 0.0), Vec3::Z, HitZone::Head, true, &mut lights);
  1510. fx.spawn_soldier_hit(Vec3::new(0.0, 1.1, 0.0), Vec3::Z, HitZone::Torso, false, &mut lights);
  1511. fx.spawn_explosion_burst(Vec3::new(5.0, 0.5, 5.0), 8.0);
  1512. // 3. Step simulation and verify batch packing + finite spark segments
  1513. for _ in 0..8 {
  1514. fx.step(0.016);
  1515. }
  1516. let mut batch = ActorRenderBatch::default();
  1517. fx.push_instances(&[], &mut batch);
  1518. assert!(!batch.fx_chunks.is_empty());
  1519. assert!(!batch.fx_puffs.is_empty());
  1520. assert!(!batch.fx_decals.is_empty());
  1521. let mut spark_lines = Vec::new();
  1522. fx.push_spark_lines(&mut spark_lines);
  1523. assert!(!spark_lines.is_empty());
  1524. for (a, b, c) in &spark_lines {
  1525. assert!(a.is_finite() && b.is_finite());
  1526. assert!(c.iter().all(|v| v.is_finite()));
  1527. }
  1528. // 4. Advance past decal max_age and confirm full expiration cleanup
  1529. for _ in 0..250 {
  1530. fx.step(0.2);
  1531. }
  1532. assert!(fx.particles.is_empty());
  1533. assert!(fx.sparks.is_empty());
  1534. assert!(fx.decals.is_empty());
  1535. }
  1536. fn build_flat_vehicle_sandbox_world() -> project_cold_water::world::WorldData {
  1537. use project_cold_water::modding::blueprint::{
  1538. AssetBlueprint, BlueprintPayload, MapBlueprint, MapModSpawn, MapTerrainBase, SCHEMA_VERSION,
  1539. };
  1540. use project_cold_water::modding::registry::ModRegistry;
  1541. let bp = AssetBlueprint {
  1542. schema_version: SCHEMA_VERSION,
  1543. id: "flat_sim_sandbox".into(),
  1544. name: "Flat Sim Sandbox".into(),
  1545. author: "ColdWater".into(),
  1546. payload: BlueprintPayload::Map(MapBlueprint {
  1547. base_terrain: MapTerrainBase::FlatSandbox {
  1548. half_extent: 220.0,
  1549. material: MaterialId::WinterMud,
  1550. },
  1551. nodes: Vec::new(),
  1552. spawns: vec![
  1553. MapModSpawn {
  1554. name: "Fed".into(),
  1555. faction: Faction::Federal,
  1556. pos: [0.0, 0.0, -40.0],
  1557. ..Default::default()
  1558. },
  1559. MapModSpawn {
  1560. name: "Mil".into(),
  1561. faction: Faction::Militia,
  1562. pos: [0.0, 0.0, 120.0],
  1563. ..Default::default()
  1564. },
  1565. ],
  1566. objectives: Vec::new(),
  1567. vehicles: Vec::new(),
  1568. named_curves: Vec::new(),
  1569. script_hooks: Vec::new(),
  1570. mission_defaults: Default::default(),
  1571. }),
  1572. };
  1573. ModRegistry::default()
  1574. .build_world_from_map(&bp)
  1575. .expect("flat sandbox world")
  1576. }
  1577. #[test]
  1578. fn test_tow_saclos_guidance_tracks_aim_beam_and_destroys_armor() {
  1579. use project_cold_water::sim::vehicles::{Vehicle, VehicleInput, VehicleOccupant};
  1580. use project_cold_water::world::VehicleKind;
  1581. let world = build_flat_vehicle_sandbox_world();
  1582. let bvh = AcousticBvh::build(world.acoustic_triangles.clone());
  1583. let mut sim = Simulation::new(&world);
  1584. // Clear distractions
  1585. for s in &mut sim.soldiers {
  1586. s.alive = false;
  1587. }
  1588. let mut tow = Vehicle::new(
  1589. 0,
  1590. "TOW".into(),
  1591. VehicleKind::TowTripod,
  1592. Faction::Federal,
  1593. Vec3::new(0.0, 0.0, 0.0),
  1594. 0.0,
  1595. None,
  1596. );
  1597. tow.seats[0].1 = Some(VehicleOccupant::Player);
  1598. let btr = Vehicle::new(
  1599. 1,
  1600. "Enemy BTR".into(),
  1601. VehicleKind::Btr80,
  1602. Faction::Militia,
  1603. Vec3::new(6.0, 0.0, 75.0),
  1604. 0.0,
  1605. None,
  1606. );
  1607. let start_hp = btr.hp;
  1608. sim.vehicles = vec![tow, btr];
  1609. sim.player.active = true;
  1610. sim.player.alive = true;
  1611. sim.player.faction = Faction::Federal;
  1612. sim.player.in_vehicle = Some((0, 0));
  1613. let cfg = SimConfig::default();
  1614. // 1. Fire TOW straight downrange (aimed 6m left of target)
  1615. let launch_in = VehicleInput {
  1616. turret_fire: true,
  1617. aim_yaw_pitch: Some((0.0, 0.02)),
  1618. ..Default::default()
  1619. };
  1620. sim.step_with_vehicle_input(&cfg, 331.5, &bvh, Vec3::ZERO, Some(&launch_in));
  1621. assert!(
  1622. sim.projectiles
  1623. .iter()
  1624. .any(|p| p.kind == ProjectileKind::GuidedMissile),
  1625. "Firing TOW must spawn a SACLOS GuidedMissile"
  1626. );
  1627. // 2. Steer gunner optic toward the laterally offset BTR-80 at (6, 1.35, 75)
  1628. for _ in 0..180 {
  1629. let optic_eye = sim.vehicles[0].gunner_optic_pose().0;
  1630. let to_btr = sim.vehicles[1].pos + Vec3::new(0.0, 1.35, 0.0) - optic_eye;
  1631. let yaw = to_btr.x.atan2(to_btr.z);
  1632. let pitch = (to_btr.y / to_btr.length().max(0.1)).clamp(-0.4, 0.5).asin();
  1633. let track_in = VehicleInput {
  1634. aim_yaw_pitch: Some((yaw, pitch)),
  1635. ..Default::default()
  1636. };
  1637. sim.step_with_vehicle_input(&cfg, 331.5, &bvh, Vec3::ZERO, Some(&track_in));
  1638. if !sim.vehicles[1].alive || sim.vehicles[1].hp < start_hp * 0.5 {
  1639. break;
  1640. }
  1641. }
  1642. assert!(
  1643. !sim.vehicles[1].alive || sim.vehicles[1].hp < start_hp * 0.5,
  1644. "SACLOS wire-guided TOW must track optic beam and destroy/cripple offset BTR (hp {} vs start {})",
  1645. sim.vehicles[1].hp,
  1646. start_hp
  1647. );
  1648. }
  1649. #[test]
  1650. fn test_helicopter_collective_takeoff_hover_cyclic_flight_and_landing() {
  1651. use glam::Vec2;
  1652. use project_cold_water::sim::vehicles::{Vehicle, VehicleInput, VehicleOccupant};
  1653. use project_cold_water::world::VehicleKind;
  1654. let world = build_flat_vehicle_sandbox_world();
  1655. let bvh = AcousticBvh::build(world.acoustic_triangles.clone());
  1656. let mut sim = Simulation::new(&world);
  1657. for s in &mut sim.soldiers {
  1658. s.alive = false;
  1659. }
  1660. let mut heli = Vehicle::new(
  1661. 0,
  1662. "Mi-24V".into(),
  1663. VehicleKind::Mi24Gunship,
  1664. Faction::Federal,
  1665. Vec3::ZERO,
  1666. 0.0,
  1667. None,
  1668. );
  1669. heli.seats[0].1 = Some(VehicleOccupant::Player);
  1670. sim.vehicles = vec![heli];
  1671. sim.player.active = true;
  1672. sim.player.alive = true;
  1673. sim.player.faction = Faction::Federal;
  1674. sim.player.in_vehicle = Some((0, 0));
  1675. let cfg = SimConfig::default();
  1676. // 1. Spool rotors & climb with collective up
  1677. let climb_in = VehicleInput {
  1678. collective: 1.0,
  1679. ..Default::default()
  1680. };
  1681. for _ in 0..240 {
  1682. sim.step_with_vehicle_input(&cfg, 331.5, &bvh, Vec3::ZERO, Some(&climb_in));
  1683. }
  1684. assert!(
  1685. sim.vehicles[0].rotor_rpm > 0.85,
  1686. "Rotor RPM must spool up under pilot collective (got {})",
  1687. sim.vehicles[0].rotor_rpm
  1688. );
  1689. assert!(
  1690. sim.vehicles[0].pos.y > 5.0,
  1691. "Helicopter must climb cleanly into air (pos.y={})",
  1692. sim.vehicles[0].pos.y
  1693. );
  1694. // 2. Engage Auto-Hover & settle vertical rate
  1695. let toggle_in = VehicleInput {
  1696. toggle_hover: true,
  1697. ..Default::default()
  1698. };
  1699. sim.step_with_vehicle_input(&cfg, 331.5, &bvh, Vec3::ZERO, Some(&toggle_in));
  1700. assert!(sim.vehicles[0].auto_hover);
  1701. let hover_in = VehicleInput::default();
  1702. for _ in 0..180 {
  1703. sim.step_with_vehicle_input(&cfg, 331.5, &bvh, Vec3::ZERO, Some(&hover_in));
  1704. }
  1705. assert!(
  1706. sim.vehicles[0].vel.y.abs() < 1.5 && sim.vehicles[0].pos.y > 4.0,
  1707. "Auto-hover must arrest vertical speed without losing altitude (vel.y={}, y={})",
  1708. sim.vehicles[0].vel.y,
  1709. sim.vehicles[0].pos.y
  1710. );
  1711. // 3. Apply cyclic pitch forward + slight collective + tail rotor yaw
  1712. let start_yaw = sim.vehicles[0].yaw;
  1713. let fly_in = VehicleInput {
  1714. collective: 0.25,
  1715. cyclic_pitch: 0.85,
  1716. yaw_pedal: 0.35,
  1717. ..Default::default()
  1718. };
  1719. for _ in 0..180 {
  1720. sim.step_with_vehicle_input(&cfg, 331.5, &bvh, Vec3::ZERO, Some(&fly_in));
  1721. }
  1722. let h_spd = Vec2::new(sim.vehicles[0].vel.x, sim.vehicles[0].vel.z).length();
  1723. assert!(h_spd > 5.0, "Cyclic pitch must accelerate helicopter forward (h_spd={h_spd})");
  1724. assert!(
  1725. (sim.vehicles[0].yaw - start_yaw).abs() > 0.3,
  1726. "Tail rotor pedal must yaw helicopter"
  1727. );
  1728. // 4. Disengage hover & land smoothly on ground without exploding
  1729. sim.step_with_vehicle_input(&cfg, 331.5, &bvh, Vec3::ZERO, Some(&toggle_in));
  1730. let descend_in = VehicleInput {
  1731. collective: -0.45,
  1732. ..Default::default()
  1733. };
  1734. for _ in 0..420 {
  1735. sim.step_with_vehicle_input(&cfg, 331.5, &bvh, Vec3::ZERO, Some(&descend_in));
  1736. if sim.vehicles[0].pos.y <= 0.15 {
  1737. break;
  1738. }
  1739. }
  1740. assert!(
  1741. sim.vehicles[0].alive && sim.vehicles[0].pos.y <= 0.5,
  1742. "Helicopter must touch down intact on flat terrain (alive={}, y={})",
  1743. sim.vehicles[0].alive,
  1744. sim.vehicles[0].pos.y
  1745. );
  1746. }
  1747. #[test]
  1748. fn test_tracked_vehicle_differential_neutral_pivot_recoil_and_instanced_shoes() {
  1749. use glam::Vec2;
  1750. use project_cold_water::sim::vehicles::{
  1751. push_vehicle_instances, Vehicle, VehicleInput, VehicleOccupant,
  1752. };
  1753. use project_cold_water::world::actors_mesh::ActorRenderBatch;
  1754. use project_cold_water::world::VehicleKind;
  1755. let world = build_flat_vehicle_sandbox_world();
  1756. let bvh = AcousticBvh::build(world.acoustic_triangles.clone());
  1757. let mut sim = Simulation::new(&world);
  1758. for s in &mut sim.soldiers {
  1759. s.alive = false;
  1760. }
  1761. let mut tank = Vehicle::new(
  1762. 0,
  1763. "T-72B".into(),
  1764. VehicleKind::T72B,
  1765. Faction::Federal,
  1766. Vec3::ZERO,
  1767. 0.0,
  1768. None,
  1769. );
  1770. tank.seats[0].1 = Some(VehicleOccupant::Player);
  1771. sim.vehicles = vec![tank];
  1772. sim.player.active = true;
  1773. sim.player.alive = true;
  1774. sim.player.faction = Faction::Federal;
  1775. sim.player.in_vehicle = Some((0, 0));
  1776. let cfg = SimConfig::default();
  1777. // 1. Neutral pivot turn in place (counter-rotating left/right tracks)
  1778. let pivot_in = VehicleInput {
  1779. throttle: 0.0,
  1780. steer: 1.0,
  1781. ..Default::default()
  1782. };
  1783. for _ in 0..90 {
  1784. sim.step_with_vehicle_input(&cfg, 331.5, &bvh, Vec3::ZERO, Some(&pivot_in));
  1785. }
  1786. let horiz_disp = Vec2::new(sim.vehicles[0].pos.x, sim.vehicles[0].pos.z).length();
  1787. assert!(
  1788. sim.vehicles[0].yaw > 0.5,
  1789. "T-72B must pivot left significantly in place (yaw={})",
  1790. sim.vehicles[0].yaw
  1791. );
  1792. assert!(
  1793. horiz_disp < 0.35,
  1794. "Neutral pivot must stay near pivot center (disp={horiz_disp})"
  1795. );
  1796. // `left_track_offset` / `right_track_offset` wrap via `.rem_euclid(1000.0)` so negative
  1797. // reverse track travel lands just below 1000.0 while positive forward travel starts at 0.0.
  1798. let left_rev_dist = if sim.vehicles[0].left_track_offset > 500.0 {
  1799. 1000.0 - sim.vehicles[0].left_track_offset
  1800. } else {
  1801. -sim.vehicles[0].left_track_offset
  1802. };
  1803. assert!(
  1804. left_rev_dist > 0.5 && sim.vehicles[0].right_track_offset > 0.5 && sim.vehicles[0].right_track_offset < 100.0,
  1805. "Left and right tracks must counter-rotate during neutral pivot (L={}, R={})",
  1806. sim.vehicles[0].left_track_offset,
  1807. sim.vehicles[0].right_track_offset
  1808. );
  1809. // 2. Forward acceleration along current heading
  1810. let l_before_fwd = sim.vehicles[0].left_track_offset;
  1811. let r_before_fwd = sim.vehicles[0].right_track_offset;
  1812. let fwd_in = VehicleInput {
  1813. throttle: 1.0,
  1814. steer: 0.0,
  1815. ..Default::default()
  1816. };
  1817. for _ in 0..90 {
  1818. sim.step_with_vehicle_input(&cfg, 331.5, &bvh, Vec3::ZERO, Some(&fwd_in));
  1819. }
  1820. let l_fwd_delta = (sim.vehicles[0].left_track_offset - l_before_fwd).rem_euclid(1000.0);
  1821. let r_fwd_delta = (sim.vehicles[0].right_track_offset - r_before_fwd).rem_euclid(1000.0);
  1822. assert!(
  1823. sim.vehicles[0].speed > 5.0,
  1824. "T-72B must accelerate forward under twin-track drive (speed={})",
  1825. sim.vehicles[0].speed
  1826. );
  1827. assert!(
  1828. l_fwd_delta > 1.0 && l_fwd_delta < 500.0 && r_fwd_delta > 1.0 && r_fwd_delta < 500.0,
  1829. "Both track offsets must advance forward (dl={l_fwd_delta}, dr={r_fwd_delta})"
  1830. );
  1831. // 3. Fire 125mm 2A46M smoothbore cannon & verify hull recoil impulse + sound + shell
  1832. sim.vehicles[0].seats[0].1 = None;
  1833. sim.vehicles[0].seats[1].1 = Some(VehicleOccupant::Player);
  1834. sim.player.in_vehicle = Some((0, 1));
  1835. sim.pending_sounds.clear();
  1836. let fire_in = VehicleInput {
  1837. turret_fire: true,
  1838. aim_yaw_pitch: Some((sim.vehicles[0].yaw, 0.0)),
  1839. ..Default::default()
  1840. };
  1841. sim.step_with_vehicle_input(&cfg, 331.5, &bvh, Vec3::ZERO, Some(&fire_in));
  1842. assert!(
  1843. sim.vehicles[0].recoil_pitch_impulse.abs() > 0.01,
  1844. "125mm main gun firing must impart hull pitch recoil (recoil={})",
  1845. sim.vehicles[0].recoil_pitch_impulse
  1846. );
  1847. assert!(
  1848. sim.pending_sounds
  1849. .iter()
  1850. .any(|s| s.kind == SoundKind::TankCannon125mm),
  1851. "125mm firing must emit SoundKind::TankCannon125mm"
  1852. );
  1853. assert!(
  1854. sim.projectiles
  1855. .iter()
  1856. .any(|p| p.kind == ProjectileKind::AutocannonShell && p.blast_radius >= 6.0),
  1857. "125mm cannon must spawn heavy HE/APFSDS shell"
  1858. );
  1859. // 4. Option A instanced 3D track shoes & roadwheels
  1860. let mut batch = ActorRenderBatch::default();
  1861. push_vehicle_instances(&sim.vehicles, None, &mut batch);
  1862. assert_eq!(batch.veh_t72_hull.len(), 1);
  1863. assert_eq!(batch.veh_t72_turret.len(), 1);
  1864. assert_eq!(batch.veh_track_shoe.len(), 56);
  1865. assert_eq!(batch.veh_track_roadwheel.len(), 16);
  1866. for inst in batch
  1867. .veh_track_shoe
  1868. .iter()
  1869. .chain(batch.veh_track_roadwheel.iter())
  1870. {
  1871. for col in inst.model_cols {
  1872. for val in col {
  1873. assert!(val.is_finite(), "Track/wheel transform must be finite");
  1874. }
  1875. }
  1876. }
  1877. }
  1878. #[test]
  1879. fn test_t72b_directional_armor_front_glacis_vs_rear_engine_deck() {
  1880. use project_cold_water::modding::blueprint::ProjectileGuidance;
  1881. use project_cold_water::sim::vehicles::Vehicle;
  1882. use project_cold_water::world::VehicleKind;
  1883. let world = build_flat_vehicle_sandbox_world();
  1884. let bvh = AcousticBvh::build(world.acoustic_triangles.clone());
  1885. let cfg = SimConfig::default();
  1886. let run_hit_scenario = |spawn_pos: Vec3, vel: Vec3| -> f32 {
  1887. let mut sim = Simulation::new(&world);
  1888. for s in &mut sim.soldiers {
  1889. s.alive = false;
  1890. }
  1891. let tank = Vehicle::new(
  1892. 0,
  1893. "T-72B".into(),
  1894. VehicleKind::T72B,
  1895. Faction::Federal,
  1896. Vec3::ZERO,
  1897. 0.0,
  1898. None,
  1899. );
  1900. let start_hp = tank.hp;
  1901. sim.vehicles = vec![tank];
  1902. sim.projectiles.push(Projectile {
  1903. pos: spawn_pos,
  1904. prev_pos: spawn_pos,
  1905. vel,
  1906. kind: ProjectileKind::AutocannonShell,
  1907. faction: Faction::Militia,
  1908. damage: 240.0,
  1909. suppression: 4.0,
  1910. blast_radius: 0.0,
  1911. crater_radius: 0.0,
  1912. drag: 0.0,
  1913. age: 0.0,
  1914. max_age: 2.0,
  1915. is_tracer: false,
  1916. crack_triggered: false,
  1917. whistle_emitted: false,
  1918. from_player: false,
  1919. owner_player: None,
  1920. visual_offset: Vec3::ZERO,
  1921. guidance: ProjectileGuidance::default(),
  1922. guide_vehicle_id: None,
  1923. is_heavy_ap: true,
  1924. });
  1925. for _ in 0..30 {
  1926. sim.step(&cfg, 331.5, &bvh, Vec3::ZERO);
  1927. if sim.vehicles[0].hp < start_hp {
  1928. break;
  1929. }
  1930. }
  1931. start_hp - sim.vehicles[0].hp
  1932. };
  1933. // Tank faces +Z (yaw = 0.0): front glacis hit approaches from +Z; rear engine deck hit from -Z
  1934. let front_damage = run_hit_scenario(Vec3::new(0.0, 1.15, 10.0), Vec3::new(0.0, 0.0, -350.0));
  1935. let rear_damage = run_hit_scenario(Vec3::new(0.0, 1.15, -10.0), Vec3::new(0.0, 0.0, 350.0));
  1936. assert!(
  1937. front_damage > 10.0 && rear_damage > front_damage * 2.0,
  1938. "Rear engine-deck hit must deal far greater damage than frontal glacis (front={front_damage}, rear={rear_damage})"
  1939. );
  1940. }
  1941. #[test]
  1942. fn test_multibarrel_zu23_salvo_and_bmpt_terminator_alternating_systems() {
  1943. use project_cold_water::modding::blueprint::ProjectileGuidance;
  1944. use project_cold_water::sim::vehicles::{
  1945. push_vehicle_instances, Vehicle, VehicleInput, VehicleOccupant,
  1946. };
  1947. use project_cold_water::world::actors_mesh::ActorRenderBatch;
  1948. use project_cold_water::world::VehicleKind;
  1949. let world = build_flat_vehicle_sandbox_world();
  1950. let bvh = AcousticBvh::build(world.acoustic_triangles.clone());
  1951. let cfg = SimConfig::default();
  1952. // Part A: ZU-23-2 Twin 23mm Linked Salvo at high +80 deg AA elevation
  1953. let mut sim = Simulation::new(&world);
  1954. for s in &mut sim.soldiers {
  1955. s.alive = false;
  1956. }
  1957. let mut zu23 = Vehicle::new(
  1958. 0,
  1959. "ZU-23-2".into(),
  1960. VehicleKind::Zu23Emplacement,
  1961. Faction::Militia,
  1962. Vec3::ZERO,
  1963. 0.0,
  1964. None,
  1965. );
  1966. zu23.seats[0].1 = Some(VehicleOccupant::Player);
  1967. sim.vehicles = vec![zu23];
  1968. sim.player.active = true;
  1969. sim.player.alive = true;
  1970. sim.player.faction = Faction::Militia;
  1971. sim.player.in_vehicle = Some((0, 0));
  1972. let aim_pitch = 80.0_f32.to_radians();
  1973. let aim_in = VehicleInput {
  1974. aim_yaw_pitch: Some((0.0, aim_pitch)),
  1975. ..Default::default()
  1976. };
  1977. for _ in 0..90 {
  1978. sim.step_with_vehicle_input(&cfg, 331.5, &bvh, Vec3::ZERO, Some(&aim_in));
  1979. }
  1980. assert!(
  1981. sim.vehicles[0].turret_pitch > 75.0_f32.to_radians(),
  1982. "ZU-23-2 must elevate cleanly to AA angle (pitch={})",
  1983. sim.vehicles[0].turret_pitch.to_degrees()
  1984. );
  1985. sim.projectiles.clear();
  1986. sim.pending_sounds.clear();
  1987. let salvo_in = VehicleInput {
  1988. turret_fire: true,
  1989. aim_yaw_pitch: Some((0.0, aim_pitch)),
  1990. ..Default::default()
  1991. };
  1992. sim.step_with_vehicle_input(&cfg, 331.5, &bvh, Vec3::ZERO, Some(&salvo_in));
  1993. assert_eq!(
  1994. sim.projectiles.len(),
  1995. 2,
  1996. "ZU-23-2 linked salvo must spawn 2 projectiles per trigger pull"
  1997. );
  1998. assert!(sim
  1999. .projectiles
  2000. .iter()
  2001. .all(|p| p.kind == ProjectileKind::AutocannonShell));
  2002. let sep = (sim.projectiles[0].prev_pos - sim.projectiles[1].prev_pos).length();
  2003. assert!(
  2004. (sep - 0.28).abs() < 0.04,
  2005. "Twin 23mm barrels must stay ~0.28m apart even at +80 deg pitch (sep={sep})"
  2006. );
  2007. assert_eq!(sim.vehicles[0].primary_ammo, 98);
  2008. assert!(
  2009. sim.pending_sounds
  2010. .iter()
  2011. .any(|s| s.kind == SoundKind::Autocannon23mm),
  2012. "ZU-23-2 must emit SoundKind::Autocannon23mm"
  2013. );
  2014. let mut zu_batch = ActorRenderBatch::default();
  2015. push_vehicle_instances(&sim.vehicles, None, &mut zu_batch);
  2016. assert_eq!(zu_batch.veh_zu23_base.len(), 1);
  2017. assert_eq!(zu_batch.veh_zu23_turret.len(), 1);
  2018. // Part B: BMPT Terminator alternating Twin 30mm + Quad 9M120 Ataka-T ATGM + Tracked Chassis
  2019. let mut sim_bmpt = Simulation::new(&world);
  2020. for s in &mut sim_bmpt.soldiers {
  2021. s.alive = false;
  2022. }
  2023. let mut bmpt = Vehicle::new(
  2024. 0,
  2025. "BMPT".into(),
  2026. VehicleKind::BmptTerminator,
  2027. Faction::Federal,
  2028. Vec3::ZERO,
  2029. 0.0,
  2030. None,
  2031. );
  2032. bmpt.seats[1].1 = Some(VehicleOccupant::Player);
  2033. sim_bmpt.vehicles = vec![bmpt];
  2034. sim_bmpt.player.active = true;
  2035. sim_bmpt.player.alive = true;
  2036. sim_bmpt.player.faction = Faction::Federal;
  2037. sim_bmpt.player.in_vehicle = Some((0, 1));
  2038. let fire_30mm = VehicleInput {
  2039. turret_fire: true,
  2040. aim_yaw_pitch: Some((0.0, 0.0)),
  2041. ..Default::default()
  2042. };
  2043. sim_bmpt.projectiles.clear();
  2044. sim_bmpt.step_with_vehicle_input(&cfg, 331.5, &bvh, Vec3::ZERO, Some(&fire_30mm));
  2045. let shot_a = sim_bmpt.projectiles.last().expect("1st 30mm shot").prev_pos;
  2046. for _ in 0..12 {
  2047. sim_bmpt.step_with_vehicle_input(&cfg, 331.5, &bvh, Vec3::ZERO, Some(&VehicleInput::default()));
  2048. }
  2049. sim_bmpt.step_with_vehicle_input(&cfg, 331.5, &bvh, Vec3::ZERO, Some(&fire_30mm));
  2050. let shot_b = sim_bmpt.projectiles.last().expect("2nd 30mm shot").prev_pos;
  2051. assert!(
  2052. shot_a.x * shot_b.x < 0.0,
  2053. "BMPT twin 30mm must alternate left/right barrels (x0={}, x1={})",
  2054. shot_a.x,
  2055. shot_b.x
  2056. );
  2057. let twin_sep = (shot_a - shot_b).length();
  2058. assert!(
  2059. (twin_sep - 0.44).abs() < 0.05,
  2060. "BMPT twin 30mm muzzles must be separated by ~0.44m (sep={twin_sep})"
  2061. );
  2062. assert_eq!(sim_bmpt.vehicles[0].primary_ammo, 118);
  2063. // Quad Ataka-T secondary salvo across all 4 pods
  2064. let mut atgm_origins = Vec::new();
  2065. let fire_atgm = VehicleInput {
  2066. secondary_fire: true,
  2067. aim_yaw_pitch: Some((0.0, 0.0)),
  2068. ..Default::default()
  2069. };
  2070. for shot_idx in 0..4 {
  2071. sim_bmpt.projectiles.clear();
  2072. sim_bmpt.step_with_vehicle_input(&cfg, 331.5, &bvh, Vec3::ZERO, Some(&fire_atgm));
  2073. let m = sim_bmpt
  2074. .projectiles
  2075. .last()
  2076. .unwrap_or_else(|| panic!("ATGM #{shot_idx} must launch"));
  2077. assert_eq!(m.kind, ProjectileKind::GuidedMissile);
  2078. assert_eq!(m.guidance, ProjectileGuidance::SaclosWireGuided);
  2079. atgm_origins.push(m.prev_pos);
  2080. // Wait > 2.2s cooldown before next missile
  2081. for _ in 0..145 {
  2082. sim_bmpt.step_with_vehicle_input(
  2083. &cfg,
  2084. 331.5,
  2085. &bvh,
  2086. Vec3::ZERO,
  2087. Some(&VehicleInput::default()),
  2088. );
  2089. }
  2090. }
  2091. assert_eq!(sim_bmpt.vehicles[0].secondary_ammo, 0);
  2092. let min_x = atgm_origins.iter().map(|p| p.x).fold(f32::INFINITY, f32::min);
  2093. let max_x = atgm_origins.iter().map(|p| p.x).fold(f32::NEG_INFINITY, f32::max);
  2094. let min_y = atgm_origins.iter().map(|p| p.y).fold(f32::INFINITY, f32::min);
  2095. let max_y = atgm_origins.iter().map(|p| p.y).fold(f32::NEG_INFINITY, f32::max);
  2096. assert!(
  2097. (max_x - min_x - 1.52).abs() < 0.08 && (max_y - min_y - 0.32).abs() < 0.08,
  2098. "Quad Ataka-T tubes must fire from 2x2 cluster (~1.52m wide x 0.32m tall), got dx={}, dy={}",
  2099. max_x - min_x,
  2100. max_y - min_y
  2101. );
  2102. let mut bmpt_batch = ActorRenderBatch::default();
  2103. push_vehicle_instances(&sim_bmpt.vehicles, None, &mut bmpt_batch);
  2104. assert_eq!(bmpt_batch.veh_t72_hull.len(), 1);
  2105. assert_eq!(bmpt_batch.veh_bmpt_turret.len(), 1);
  2106. assert_eq!(bmpt_batch.veh_track_shoe.len(), 56);
  2107. assert_eq!(bmpt_batch.veh_track_roadwheel.len(), 16);
  2108. }