//! Control radar returns a cached scan. The world rebuilds each clan's contacts every frame. use crate::satellite_contacts::{clan_tint, OWN_TINT}; use crate::{ control_device_provider_value, EffectiveControlDevice, Engine, MissionControlDeviceTableState, MissionControlDeviceTableStatus, StartingCockpit, HERO_UNIT_CLASS, UNIT_DAT_CONTROL_CLASS_HIGH_BIT, }; use fparkan_render::cockpit_radar::ContactMark; use fparkan_world::{ identity_metadata, registration_sequence, transform_state, ObjectHandle, OwnerId, }; use std::collections::{HashMap, HashSet}; #[derive(Default)] pub(super) struct Radar { scans: HashMap, contacts: HashSet<(OwnerId, ObjectHandle)>, } #[derive(Default)] struct Scan { deadline: Option, targets: Vec, } impl Radar { pub(super) fn contains(&self, observer: OwnerId, target: ObjectHandle) -> bool { self.contacts.contains(&(observer, target)) } } /// A target on the controlled object's own radar screen. pub struct CockpitContact { pub offset: [f32; 2], pub mark: ContactMark, pub tint: [u8; 3], pub selected: bool, handle: ObjectHandle, distance_squared: f32, affiliation: Affiliation, } #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] enum Affiliation { Enemy, Friendly, Other, } /// The target-selection commands in `ui_other.man`. #[derive(Clone, Copy)] pub enum CockpitTargetCommand { Next, Enemy, Friend, } /// Select from the same live scan that supplies the contacts on the radar. pub fn select_cockpit_target( engine: &Engine, cockpit: StartingCockpit, selected: Option, command: CockpitTargetCommand, ) -> Option { let (_, contacts) = cockpit_contacts(engine, cockpit, selected)?; select_contact(contacts, command) } /// Keep a live target in range or choose one when the cockpit has no target. pub fn refresh_cockpit_target( engine: &Engine, cockpit: StartingCockpit, selected: Option, ) -> Option { let (range, contacts) = cockpit_contacts(engine, cockpit, selected)?; let mut contacts = contacts.peekable(); contacts.peek()?; let world = &engine.world; let mission = engine.loaded.as_ref()?; let active = selected.filter(|&target| { if target == cockpit.handle || registration_sequence(world, target) .ok() .flatten() .is_none() || mission .boarding .is_some_and(|boarding| boarding.hero.handle == target) || !mission .control_device_tables .iter() .any(|table| table.handle == target && !table.node_provider_depletion_marked) { return false; } let (Ok(observer), Ok(target)) = ( transform_state(world, cockpit.handle), transform_state(world, target), ) else { return false; }; let [x, y] = horizontal_offset(observer.position, target.position); x * x + y * y <= range * range }); // iron3d+0x90e00 tries enemies first, then its own clan, then any contact. active.or_else(|| { contacts .min_by(|a, b| { a.affiliation .cmp(&b.affiliation) .then_with(|| a.distance_squared.total_cmp(&b.distance_squared)) }) .map(|contact| contact.handle) }) } fn select_contact( contacts: impl Iterator, command: CockpitTargetCommand, ) -> Option { let affiliation = match command { CockpitTargetCommand::Next => None, CockpitTargetCommand::Enemy => Some(Affiliation::Enemy), CockpitTargetCommand::Friend => Some(Affiliation::Friendly), }; let mut eligible = contacts.filter(|contact| affiliation.is_none_or(|team| team == contact.affiliation)); let first = eligible.next()?; let mut wrap = first.selected; let mut nearest = (first.handle, first.distance_squared); for contact in eligible { if wrap { return Some(contact.handle); } wrap = contact.selected; if contact.distance_squared < nearest.1 { nearest = (contact.handle, contact.distance_squared); } } // With a matching selection, the original searches forward and then wraps. Some(if wrap || affiliation.is_none() { first.handle } else { nearest.0 }) } #[cfg(test)] #[test] fn contact_selection_wraps_and_filters_by_affiliation() { let first = ObjectHandle { slot: 0, generation: 1, }; let second = ObjectHandle { slot: 1, generation: 1, }; let third = ObjectHandle { slot: 2, generation: 1, }; let fourth = ObjectHandle { slot: 3, generation: 1, }; let select = |selected, command| { let contacts = [ (first, Affiliation::Enemy, 100.0), (second, Affiliation::Other, 1.0), (third, Affiliation::Enemy, 25.0), (fourth, Affiliation::Friendly, 36.0), ]; select_contact( contacts .into_iter() .map(|(handle, affiliation, distance_squared)| CockpitContact { offset: [0.0; 2], mark: ContactMark::Unit, tint: [0; 3], selected: selected == Some(handle), handle, distance_squared, affiliation, }), command, ) }; assert_eq!(select(None, CockpitTargetCommand::Next), Some(first)); assert_eq!( select(Some(first), CockpitTargetCommand::Next), Some(second) ); assert_eq!( select(Some(fourth), CockpitTargetCommand::Next), Some(first) ); assert_eq!( select(Some(first), CockpitTargetCommand::Enemy), Some(third) ); assert_eq!(select(None, CockpitTargetCommand::Enemy), Some(third)); assert_eq!( select(Some(third), CockpitTargetCommand::Enemy), Some(first) ); assert_eq!( select(Some(first), CockpitTargetCommand::Friend), Some(fourth) ); } /// The range printed on the cockpit dial, even when the antenna is unpowered. #[must_use] pub fn cockpit_range_readout(engine: &Engine, cockpit: StartingCockpit) -> i32 { range_readout(cockpit_radar_coefficient(engine, cockpit, 3)) } /// The installed radar's period for the HUD sweep, from Control selector 0xa9. #[must_use] pub fn cockpit_radar_period(engine: &Engine, cockpit: StartingCockpit) -> Option { cockpit_radar_coefficient(engine, cockpit, 4) .filter(|period| period.is_finite() && *period > 0.0) } fn cockpit_radar_coefficient( engine: &Engine, cockpit: StartingCockpit, index: usize, ) -> Option { let table = engine .loaded .as_ref()? .control_device_tables .iter() .find(|table| table.handle == cockpit.handle)?; Some(f32::from_bits( radar_device(table)?.coefficient_bits?[index], )) } fn range_readout(range: Option) -> i32 { // iron3d+0x91d80 substitutes 1 before the text's x87 integer conversion. range .filter(|range| range.is_finite() && *range > 0.0) .unwrap_or(1.0) .round_ties_even() as i32 } /// Range in world units and the contacts from this cockpit's scan. pub fn cockpit_contacts( engine: &Engine, cockpit: StartingCockpit, selected: Option, ) -> Option<(f32, impl Iterator + '_)> { let mission = engine.loaded.as_ref()?; let world = &engine.world; let observer = identity_metadata(world, cockpit.handle).ok()?.owner_id?; let origin = transform_state(world, cockpit.handle).ok()?.position; let scan = mission.radar.scans.get(&cockpit.handle)?; let local_table = mission .control_device_tables .iter() .find(|table| table.handle == cockpit.handle)?; let range = antenna(local_table)?.range; let contacts = scan.targets.iter().filter_map(move |&handle| { registration_sequence(world, handle).ok()??; let table = mission .control_device_tables .iter() .find(|table| table.handle == handle)?; if table.node_provider_depletion_marked || mission .boarding .is_some_and(|board| board.hero.handle == handle) { return None; } let id = table.original_id?.0; let class = mission .object_drafts .get(id as usize)? .unit_dat_header_flags?; let clan = identity_metadata(world, handle).ok()?.owner_id?; let mark = if class & UNIT_DAT_CONTROL_CLASS_HIGH_BIT != 0 { ContactMark::Building } else if mission .unit_chassis_flags .get(&id) .is_some_and(|flags| flags.chassis_type == Some(1)) { ContactMark::Cross } else { ContactMark::Unit }; let (tint, affiliation) = if clan == observer { (OWN_TINT, Affiliation::Friendly) } else { let observer = mission.mission.clans.get(usize::from(observer.0))?; let target = mission.mission.clans.get(usize::from(clan.0))?; let relation = target .relations .iter() .find(|entry| entry.other_clan_name.raw == observer.name.raw) .map(|entry| entry.relation_value); if mark != ContactMark::Building && target.mode != 0 && relation == Some(0) && mission .unit_patrol .as_ref() .is_some_and(|patrol| patrol.is_shut_down(handle)) { return None; } let affiliation = if target.mode != 0 && relation == Some(0) { Affiliation::Enemy } else { Affiliation::Other }; (clan_tint(target.mode, relation), affiliation) }; let position = transform_state(world, handle).ok()?.position; let [x, y] = horizontal_offset(origin, position); Some(CockpitContact { offset: [x, y], mark, tint, selected: selected == Some(handle), handle, distance_squared: x * x + y * y, affiliation, }) }); Some((range, contacts)) } fn horizontal_offset(origin: [u32; 3], target: [u32; 3]) -> [f32; 2] { std::array::from_fn(|axis| f32::from_bits(target[axis]) - f32::from_bits(origin[axis])) } struct Actor<'a> { table: &'a MissionControlDeviceTableState, owner: OwnerId, class: u32, position: [f32; 3], } pub(super) fn tick(engine: &mut Engine, now_ms: u32) { let Some(mission) = &mut engine.loaded else { return; }; let world = &engine.world; let passenger = mission.boarding.map(|boarding| boarding.hero.handle); let player_owner = mission .local_hero .and_then(|hero| identity_metadata(world, hero).ok()?.owner_id); let actors: Vec<_> = mission .control_device_tables .iter() .filter_map(|table| { if table.node_provider_depletion_marked || passenger == Some(table.handle) { return None; } let draft = mission.object_drafts.get(table.original_id?.0 as usize)?; let class = draft.unit_dat_header_flags?; // Terrain+0x17340 enumerates static and animated objects (mask 0x18). // iron3d+0x91de0 also drops the two fixed scenery classes. if !is_radar_actor(class) { return None; } registration_sequence(world, table.handle).ok()??; Some(Actor { table, owner: identity_metadata(world, table.handle).ok()?.owner_id?, class, position: transform_state(world, table.handle) .ok()? .position .map(f32::from_bits), }) }) .collect(); let radar = &mut mission.radar; radar.contacts.clear(); radar.scans.retain(|handle, _| { registration_sequence(world, *handle) .ok() .flatten() .is_some() }); for actor in &actors { let Some(antenna) = antenna(actor.table) else { continue; }; let scan = radar.scans.entry(actor.table.handle).or_default(); let now = now_ms as f32; if scan.deadline.is_none_or(|deadline| now > deadline) { scan.deadline = Some(now + antenna.period_ms); scan.targets.clear(); for target in &actors { if actor.table.handle == target.table.handle { continue; } if target.class == HERO_UNIT_CLASS && player_owner == Some(target.owner) { continue; } let offset = std::array::from_fn(|axis| target.position[axis] - actor.position[axis]); if falloff(offset, antenna.range).is_some_and(|loss| { signature(target.table) .is_some_and(|signal| received(loss, antenna.channels, signal)) }) { scan.targets.push(target.table.handle); } } } radar .contacts .extend(scan.targets.iter().map(|&target| (actor.owner, target))); } } fn is_radar_actor(class: u32) -> bool { class & (crate::autodemo::MOBILE_UNIT | UNIT_DAT_CONTROL_CLASS_HIGH_BIT) != 0 && !matches!(class, 0x8000_1000 | 0x8000_2000) || class == crate::projectile::ANIMAL_UNIT_CLASS } struct Antenna { range: f32, period_ms: f32, channels: [f64; 3], } pub(super) fn radar_device( table: &MissionControlDeviceTableState, ) -> Option<&EffectiveControlDevice> { let MissionControlDeviceTableStatus::Available(devices) = &table.status else { return None; }; // Control+0x2d5cb stores the last device created by factory 8. devices.iter().rev().find(|device| device.factory_tag == 8) } fn antenna(table: &MissionControlDeviceTableState) -> Option { let device = radar_device(table)?; let provider = control_device_provider_value(table, device).ok()?; if device.native_word_50_bits? == 0 || provider == 0.0 { return None; } let coeff = device.coefficient_bits?.map(f32::from_bits); let multiplier = f32::from_bits(device.multiplier_bits?); let [range, period_ms] = [coeff[3], coeff[4]]; (range > 0.0 && range.is_finite() && period_ms.is_finite()).then_some(Antenna { range, period_ms, channels: [coeff[0], coeff[1], coeff[2]] .map(|gain| f64::from(gain) * f64::from(provider) * f64::from(multiplier)), }) } fn signature(table: &MissionControlDeviceTableState) -> Option<[f32; 3]> { let base = table .owner_profile .as_ref()? .load_projection .as_ref() .ok()?; let MissionControlDeviceTableStatus::Available(devices) = &table.status else { return None; }; // The query order is Control selectors 0x45, 0x43, 0x44. let mut values = [ f32::from_bits(base.aggregate_538_bits), f32::from_bits(base.aggregate_530_bits) * f32::from_bits(table.current_output_rate_5dc_bits), f32::from_bits(base.aggregate_534_bits) * f32::from_bits(table.current_output_rate_5e0_bits), ]; for device in devices .iter() .rev() .filter(|device| device.descriptor.tag == 10) { let coefficients = device.coefficient_bits?.map(f32::from_bits); let state = f64::from(control_device_provider_value(table, device).ok()?); let multiplier = f64::from(f32::from_bits(device.multiplier_bits?)); for (value, &gain) in values.iter_mut().zip(&coefficients[..3]) { if *value <= 0.0 { continue; } // Control+0x2bb40 attenuates each channel with the tag-10 getter. let mut factor = (1.0 - f64::from(gain) * state * multiplier).max(0.0) as f32; if device.native_word_50_bits == Some(0x1000) { factor *= (1.0 - coefficients[3]).max(0.0); } *value *= factor; } } Some(values) } fn falloff(offset: [f32; 3], range: f32) -> Option { let squared = offset .map(|d| f64::from(d).powi(2)) .into_iter() .sum::(); let range = f64::from(range); (squared.sqrt() < range).then(|| (1.0 - squared / (range * range)) as f32) } fn received(falloff: f32, gains: [f64; 3], signal: [f32; 3]) -> bool { gains .into_iter() .zip(signal) .any(|(gain, value)| gain * f64::from(value) * f64::from(falloff) >= 1.0) } #[cfg(test)] mod tests { use super::{falloff, range_readout, received}; #[test] fn cockpit_range_uses_native_fallback_and_nearest_even_rounding() { assert_eq!(range_readout(None), 1); assert_eq!(range_readout(Some(0.0)), 1); assert_eq!(range_readout(Some(-1.0)), 1); assert_eq!(range_readout(Some(299.5)), 300); assert_eq!(range_readout(Some(300.5)), 300); assert_eq!(range_readout(Some(301.5)), 302); } #[test] fn native_scan_uses_strict_3d_range_and_an_independent_threshold_per_channel() { assert_eq!(falloff([0.0, 0.0, 100.0], 100.0), None); let near = falloff([0.0, 0.0, 60.0], 100.0).unwrap(); let far = falloff([0.0, 0.0, 80.0], 100.0).unwrap(); assert!(received(near, [1.0; 3], [2.0, 0.0, 0.0])); assert!(!received(far, [1.0; 3], [2.0; 3])); assert!(received(far, [1.0; 3], [0.0, 3.0, 0.0])); assert!(received(far, [1.0; 3], [0.0, 0.0, 3.0])); } #[test] #[ignore = "requires licensed corpus"] fn stock_neutral_warbot_appears_and_expires_on_the_hero_radar_clock() { use crate::{ create, frame, load_gameplay_mission, loaded_mission_control_device_tables, satellite_contacts::{landscape_extent, visible_units}, starting_cockpit, EngineServices, MissionMode, MissionRequest, MissionStartupInput, }; use fparkan_vfs::DirectoryVfs; use fparkan_world::{ handle_by_original_id, identity_metadata, set_transform, transform_state, OriginalObjectId, }; use std::sync::Arc; let root = std::env::var_os("FPARKAN_CORPUS_PART1_ROOT").expect("licensed corpus"); let mut engine = create(EngineServices::new(Arc::new(DirectoryVfs::new(root)))).unwrap(); load_gameplay_mission( &mut engine, MissionRequest { key: "MISSIONS/CAMPAIGN/CAMPAIGN.00/Mission.01/data.tma".into(), mode: MissionMode::SingleMission, }, MissionStartupInput { queue_time_ms: 0, research_creation_gate: false, }, None, ) .unwrap(); let hero = starting_cockpit(&engine).unwrap(); let extent = landscape_extent(&engine).unwrap(); let target = handle_by_original_id(&engine.world, OriginalObjectId(11)).unwrap(); let original = transform_state(&engine.world, hero.handle).unwrap(); let owner = identity_metadata(&engine.world, hero.handle) .unwrap() .owner_id .unwrap(); let table = loaded_mission_control_device_tables(&engine) .unwrap() .iter() .find(|table| table.handle == hero.handle) .expect("hero Control table"); let period = super::antenna(table).expect("stock hero radar").period_ms as u32; assert!(period > 0); let seen = |engine: &crate::Engine| { engine .loaded .as_ref() .unwrap() .radar .contains(owner, target) }; let displayed = |engine: &crate::Engine| { let (range, mut contacts) = super::cockpit_contacts(engine, hero, Some(target)).unwrap(); assert_eq!(range, 300.0); contacts.any(|mark| mark.selected && mark.tint == [160; 3]) }; frame(&mut engine, 0).unwrap(); assert!(!seen(&engine)); assert!(!displayed(&engine)); let mut near = original; near.position = transform_state(&engine.world, target).unwrap().position; near.position[0] = (f32::from_bits(near.position[0]) - 5.0).to_bits(); set_transform(&mut engine.world, hero.handle, near).unwrap(); frame(&mut engine, period).unwrap(); assert!(!seen(&engine)); frame(&mut engine, period + 1).unwrap(); assert!(seen(&engine)); assert!(displayed(&engine)); assert!(visible_units(&engine, hero, extent, None).any(|mark| mark.tint == [160; 3])); set_transform(&mut engine.world, hero.handle, original).unwrap(); frame(&mut engine, period * 2 + 1).unwrap(); assert!(seen(&engine)); frame(&mut engine, period * 2 + 2).unwrap(); assert!(!seen(&engine)); assert!(!displayed(&engine)); } }