//! Speed and scale readings for the currently controlled cockpit. use crate::{ unit_patrol::PreparedPatrol, Engine, LoadedMissionState, RemoteWarbotControl, StartingCockpit, }; /// The reading in km/h and the first visible row of the fill. #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub struct Speedometer { pub speed: i32, pub scale_top: u32, } impl Speedometer { fn from_speeds(speed: f32, limit: f32) -> Self { // iron3d+0x3fcd8 multiplies by the stored float in x87, then rounds both values. let kmh = |meters_per_second| { (f64::from(meters_per_second) * f64::from(3.6_f32)).round_ties_even() as i32 }; let speed = kmh(speed); let limit = kmh(limit); let percent = if limit == 0 { 0 } else { (i64::from(speed) * 100 / i64::from(limit)).clamp(0, 100) as u32 }; Self { speed, scale_top: (100 - percent) * 105 / 100, } } } /// Reads Control's speed and forward scale for the active body. #[must_use] pub fn cockpit_speedometer(engine: &Engine, cockpit: StartingCockpit) -> Option { let mission = engine.loaded.as_ref()?; let active = mission .boarding .map_or_else(|| mission.local_hero, |board| Some(board.cockpit.handle)); if active != Some(cockpit.handle) { return None; } // Control selector 0x90 reads word seven from the owner's profile. let limit = mission .control_device_tables .iter() .find(|table| table.handle == cockpit.handle) .and_then(|table| table.owner_profile.as_ref()) .map_or(0.0, |profile| f32::from_bits(profile.current_words[7])); Some(Speedometer::from_speeds(mission.cockpit_speed, limit)) } pub(super) fn record_route_speed( mission: &mut LoadedMissionState, patrol: Option<&PreparedPatrol>, ) { let driving = mission .boarding .as_mut() .filter(|board| board.control_mode == RemoteWarbotControl::Autopilot) .zip(patrol); mission.cockpit_speed = driving.map_or(0.0, |(board, patrol)| { if board.can_fly { if let Some(velocity) = patrol.flight_velocity_of(board.cockpit.handle) { board.flight_velocity = velocity; } } patrol.speed_of(board.cockpit.handle, board.can_fly) }); } pub(super) fn length(vector: [f32; 3]) -> f32 { vector .map(f64::from) .into_iter() .map(|v| v * v) .sum::() .sqrt() as f32 } pub(super) fn translation_speed(before: [f32; 3], after: [f32; 3], seconds: f32) -> f32 { if seconds > 0.0 { length(std::array::from_fn(|axis| after[axis] - before[axis])) / seconds } else { 0.0 } } #[cfg(test)] mod tests { use super::*; #[test] fn original_speedometer_rounds_both_values_before_clipping_the_strip() { for (velocity, limit, expected, scale_top) in [ ([0.0, 0.0, 0.0], 14.0, 0, 105), ([3.0, 4.0, 0.0], 14.0, 18, 67), ([0.0, 0.0, 7.0], 14.0, 25, 52), ([-14.0, 0.0, 0.0], 14.0, 50, 0), ([9.0, 12.0, 0.0], 8.0, 54, 0), ([3.0, 4.0, 0.0], 0.0, 18, 105), ([1.25, 0.0, 0.0], 14.0, 4, 96), ] { assert_eq!( Speedometer::from_speeds(length(velocity), limit), Speedometer { speed: expected, scale_top } ); } } }