//! Control's sight ray and convergence point for offset barrels. use crate::{ projectile::segment_point, projectile_terrain_hit, projectile_unit_hit, Engine, ObjectHandle, ProjectileContact, }; use fparkan_assets::{PreparedComponentControl, PreparedControlPoint}; /// The origin CPT and direction CPT selected by Control's turret rows. pub fn turret_sight_points( control: &PreparedComponentControl, ) -> Option<[&PreparedControlPoint; 2]> { let turret = control .typed_records .iter() .find(|record| record.tag == 1)?; let [azimuth, elevation, ..] = *turret.values.as_slice() else { return None; }; let origin = control.timeline_rows.get(azimuth as usize)?.raw_parameters[0]; let direction = control .timeline_rows .get(elevation as usize)? .raw_parameters[1]; let points = &control.point_list.as_ref()?.points; Some([ points.get(origin as usize)?, points.get(direction as usize)?, ]) } /// Resolves the first physical hit along the sights and clamps near convergence. /// A clear ray leaves the barrel direction unchanged. pub fn projectile_sight_target( engine: &Engine, shooter: ObjectHandle, origin: [f32; 3], axis: [f32; 3], ) -> Option<[f32; 3]> { sight_target(engine, origin, axis, |segment| { projectile_unit_hit(engine, shooter, segment) }) } pub(super) fn sight_target( engine: &Engine, origin: [f32; 3], axis: [f32; 3], body_contact: impl FnOnce([[f32; 3]; 2]) -> Option, ) -> Option<[f32; 3]> { let mission = engine.loaded.as_ref()?; let length = axis[0].hypot(axis[1]).hypot(axis[2]); if !length.is_finite() || length <= 0.0 { return None; } let axis = axis.map(|value| value / length); let at = |distance: f32| std::array::from_fn(|i| origin[i] + axis[i] * distance); let segment = [at(5.0), at(1_000_000.0)]; let terrain = projectile_terrain_hit(&mission.terrain, segment).ok()?; let unit = body_contact(segment).map(|hit| hit.fraction); let fraction = terrain.into_iter().chain(unit).min_by(f32::total_cmp)?; Some(convergence_point( origin, axis, segment_point(segment, fraction), )) } fn convergence_point(origin: [f32; 3], axis: [f32; 3], hit: [f32; 3]) -> [f32; 3] { // Control+0x2a610 clamps the range from the sight origin, before // constructing the direction from the muzzle. if (0..3).map(|i| (hit[i] - origin[i]).powi(2)).sum::() < 100.0_f32.powi(2) { std::array::from_fn(|i| origin[i] + axis[i] * 100.0) } else { hit } } #[cfg(test)] mod tests { use super::*; #[test] fn near_sight_contacts_use_the_native_minimum_from_the_sight_origin() { let origin = [10.0, 20.0, 30.0]; let axis = [0.0, 1.0, 0.0]; assert_eq!( convergence_point(origin, axis, [10.0, 40.0, 30.0]), [10.0, 120.0, 30.0] ); assert_eq!( convergence_point(origin, axis, [10.0, 220.0, 30.0]), [10.0, 220.0, 30.0] ); } }