diff options
Diffstat (limited to 'crates/fparkan-runtime')
| -rw-r--r-- | crates/fparkan-runtime/src/lib.rs | 4 | ||||
| -rw-r--r-- | crates/fparkan-runtime/src/radar.rs | 292 | ||||
| -rw-r--r-- | crates/fparkan-runtime/src/satellite_contacts.rs | 130 | ||||
| -rw-r--r-- | crates/fparkan-runtime/src/unit_chassis.rs | 7 |
4 files changed, 399 insertions, 34 deletions
diff --git a/crates/fparkan-runtime/src/lib.rs b/crates/fparkan-runtime/src/lib.rs index 6ebe380c..2b148397 100644 --- a/crates/fparkan-runtime/src/lib.rs +++ b/crates/fparkan-runtime/src/lib.rs @@ -131,6 +131,7 @@ mod projectile_damage; mod projectile_flight; mod projectile_parts; mod projectile_shield; +mod radar; mod weapon_deployment; mod weapon_resupply; pub use projectile_shield::{ @@ -1493,6 +1494,7 @@ struct LoadedMissionState { free_research: research::FreeResearch, laboratories: laboratory::Laboratories, control_resources: control_resources::Resources, + radar: radar::Radar, ai_startup_states: Vec<MissionAiStartupState>, script_bundles: Vec<MissionScriptBundle>, script_varset: Option<MissionScriptVarSet>, @@ -2851,6 +2853,7 @@ node_provider_distribution_suspended: false, free_research, laboratories: Default::default(), control_resources: Default::default(), + radar: Default::default(), ai_startup_states: loaded_scripts.ai_startup_states, script_bundles: loaded_scripts.bundles, script_varset: loaded_scripts.varset, @@ -3027,6 +3030,7 @@ pub fn step_headless( .loaded .as_mut() .and_then(|mission| mission.free_research.tick(&engine.world, queue_time_ms)); + radar::tick(engine, queue_time_ms); Ok(FrameResult { snapshot, mission_event, diff --git a/crates/fparkan-runtime/src/radar.rs b/crates/fparkan-runtime/src/radar.rs new file mode 100644 index 00000000..a5c64206 --- /dev/null +++ b/crates/fparkan-runtime/src/radar.rs @@ -0,0 +1,292 @@ +//! Control radar returns a cached scan. The world rebuilds each clan's contacts every frame. + +use crate::{ + control_device_provider_value, Engine, MissionControlDeviceTableState, + MissionControlDeviceTableStatus, HERO_UNIT_CLASS, UNIT_DAT_CONTROL_CLASS_HIGH_BIT, +}; +use fparkan_world::{ + identity_metadata, registration_sequence, transform_state, ObjectHandle, OwnerId, +}; +use std::collections::{HashMap, HashSet}; + +#[derive(Default)] +pub(super) struct Radar { + scans: HashMap<ObjectHandle, Scan>, + contacts: HashSet<(OwnerId, ObjectHandle)>, +} + +#[derive(Default)] +struct Scan { + deadline: Option<f32>, + targets: Vec<ObjectHandle>, +} + +impl Radar { + pub(super) fn contains(&self, observer: OwnerId, target: ObjectHandle) -> bool { + self.contacts.contains(&(observer, target)) + } +} + +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], +} + +fn antenna(table: &MissionControlDeviceTableState) -> Option<Antenna> { + let MissionControlDeviceTableStatus::Available(devices) = &table.status else { + return None; + }; + // Control+0x2d5cb stores the last device created by factory 8. + let device = devices + .iter() + .rev() + .find(|device| device.factory_tag == 8)?; + 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<f32> { + let squared = offset + .map(|d| f64::from(d).powi(2)) + .into_iter() + .sum::<f64>(); + 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, received}; + + #[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) + }; + frame(&mut engine, 0).unwrap(); + assert!(!seen(&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!(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)); + } +} diff --git a/crates/fparkan-runtime/src/satellite_contacts.rs b/crates/fparkan-runtime/src/satellite_contacts.rs index 2229f9ed..12b45037 100644 --- a/crates/fparkan-runtime/src/satellite_contacts.rs +++ b/crates/fparkan-runtime/src/satellite_contacts.rs @@ -7,11 +7,14 @@ use fparkan_world::{ TransformState, }; +const OWN_TINT: [u8; 3] = [128, 128, 255]; + /// The original icon crop and position within the 256-pixel satellite image. #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub struct BuildingContact { pub pixel: [i32; 2], pub icon_x: u32, + pub tint: [u8; 3], } /// The original mark for a moving unit within the satellite image. @@ -19,6 +22,7 @@ pub struct BuildingContact { pub struct UnitContact { pub pixel: [i32; 2], pub cross: bool, + pub tint: [u8; 3], pub heading: Option<UnitHeading>, pub route: Vec<[i32; 2]>, } @@ -41,18 +45,23 @@ pub fn landscape_extent(engine: &Engine) -> Option<f32> { (extent.is_finite() && extent > 0.0).then_some(extent) } -/// Current contacts for the player's own clan, which needs no detection test. -pub fn owned_buildings( +/// Building marks for the player's own clan and its radar contacts. +pub fn visible_buildings( engine: &Engine, cockpit: StartingCockpit, extent: f32, ) -> impl Iterator<Item = BuildingContact> + '_ { - owned_contacts(engine, cockpit, extent, |_, class| icon_x(class)) - .map(|(pixel, _, _, icon_x)| BuildingContact { pixel, icon_x }) + visible_contacts(engine, cockpit, extent, |_, class| icon_x(class)).map( + |(pixel, _, _, tint, icon_x)| BuildingContact { + pixel, + icon_x, + tint, + }, + ) } -/// Current marks for the player's vehicles, including newly registered factory output. -pub fn owned_units( +/// Unit marks for the player's own clan and its radar contacts. +pub fn visible_units( engine: &Engine, cockpit: StartingCockpit, extent: f32, @@ -64,9 +73,8 @@ pub fn owned_units( .loaded .as_ref() .and_then(|mission| mission.unit_patrol.as_ref()); - owned_contacts(engine, cockpit, extent, move |draft, class| { - let hero = class == crate::HERO_UNIT_CLASS; - if class & crate::autodemo::MOBILE_UNIT == 0 || (hero && boarded.is_some()) { + visible_contacts(engine, cockpit, extent, move |draft, class| { + if !unit_class(class) { return None; } // iron3d+0x77f33 reads Behavior property 0x207 (ChassisType). @@ -75,13 +83,17 @@ pub fn owned_units( .as_ref()? .unit_chassis_flags .get(&draft.original_id?.0)?; - Some((hero, flags.chassis_type == Some(1))) + Some(( + class == crate::HERO_UNIT_CLASS, + flags.chassis_type == Some(1), + )) }) - .map(move |(pixel, handle, pose, (hero, cross))| { + .map(move |(pixel, handle, pose, tint, (hero, cross))| { let selected = selected == Some(handle); UnitContact { pixel, cross, + tint, heading: if hero || selected { unit_heading(pose, cross, selected) } else { @@ -115,38 +127,93 @@ fn unit_heading(pose: TransformState, cross: bool, selected: bool) -> Option<Uni }) } -fn owned_contacts<'a, T>( +fn visible_contacts<'a, T>( engine: &'a Engine, cockpit: StartingCockpit, extent: f32, marker: impl Fn(&MissionObjectDraft, u32) -> Option<T> + Copy + 'a, -) -> impl Iterator<Item = ([i32; 2], ObjectHandle, TransformState, T)> + 'a { +) -> impl Iterator<Item = ([i32; 2], ObjectHandle, TransformState, [u8; 3], T)> + 'a { let owner = identity_metadata(&engine.world, cockpit.handle) .ok() .and_then(|identity| identity.owner_id); engine.loaded.iter().flat_map(move |mission| { mission.object_drafts.iter().filter_map(move |draft| { - let marker = marker(draft, draft.unit_dat_header_flags?)?; + let owner = owner?; + let class = draft.unit_dat_header_flags?; + let marker = marker(draft, class)?; let handle = handle_by_original_id(&engine.world, draft.original_id?)?; let clan = identity_metadata(&engine.world, handle).ok()?.owner_id?; registration_sequence(&engine.world, handle).ok()??; + if mission + .boarding + .is_some_and(|boarding| boarding.hero.handle == handle) + { + return None; + } + let tint = if clan == owner { + OWN_TINT + } else { + if !mission.radar.contains(owner, handle) { + return None; + } + let observer = mission.mission.clans.get(usize::from(owner.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); + // iron3d+0x77ae0 skips dormant hostile units, except the spatial clan. + if unit_class(class) + && target.mode != 0 + && relation == Some(0) + && mission + .unit_patrol + .as_ref() + .is_some_and(|patrol| patrol.is_shut_down(handle)) + { + return None; + } + clan_tint(target.mode, relation) + }; // Both native contact renderers reject Control's 0xfffe sentinel // even while the object is still registered as a ruin. - if Some(clan) != owner - || mission - .control_device_tables - .iter() - .any(|table| table.handle == handle && table.node_provider_depletion_marked) + if mission + .control_device_tables + .iter() + .any(|table| table.handle == handle && table.node_provider_depletion_marked) { return None; } let pose = transform_state(&engine.world, handle).ok()?; let [world_x, world_y, _] = pose.position.map(f32::from_bits); - Some((project([world_x, world_y], extent)?, handle, pose, marker)) + Some(( + project([world_x, world_y], extent)?, + handle, + pose, + tint, + marker, + )) }) }) } +fn unit_class(class: u32) -> bool { + class & crate::autodemo::MOBILE_UNIT != 0 || class == crate::projectile::ANIMAL_UNIT_CLASS +} + +fn clan_tint(mode: u32, relation: Option<i32>) -> [u8; 3] { + // iron3d+0x658a0 selects the observed clan's relation to the viewer. + match (mode, relation) { + (0, _) => [255, 255, 0], + (3, _) => [160; 3], + (_, Some(0)) => [255, 0, 0], + (_, Some(1)) => [255, 0, 255], + (_, Some(2)) => [0, 255, 255], + _ => [255, 255, 0], + } +} + fn icon_x(class: u32) -> Option<u32> { // iron3d+0x9f460 selects the icon. The atlas positions come from +0x65370. Some(match class { @@ -207,7 +274,7 @@ mod tests { #[test] #[ignore = "requires licensed corpus"] fn captured_warbot_mark_uses_its_live_owner_and_position() { - use super::{landscape_extent, owned_units, UnitContact}; + use super::{landscape_extent, visible_units, UnitContact}; use crate::{ create, load_gameplay_mission, starting_cockpit, EngineServices, MissionMode, MissionRequest, MissionStartupInput, @@ -247,7 +314,7 @@ mod tests { let mut pose = transform_state(&engine.world, handle).unwrap(); let [x, y, _] = pose.position.map(f32::from_bits); let start = project([x, y], extent).unwrap(); - assert!(!owned_units(&engine, cockpit, extent, Some(handle)) + assert!(!visible_units(&engine, cockpit, extent, Some(handle)) .any(|contact| contact.pixel == start)); set_owner(&mut engine.world, handle, owner).unwrap(); let destination = [x, y + 50.0]; @@ -258,12 +325,12 @@ mod tests { .unit_patrol .get_or_insert_with(crate::unit_patrol::UnitPatrol::scripted) .move_to(&engine.world, handle, destination, false); - let chosen = owned_units(&engine, cockpit, extent, Some(handle)) + let chosen = visible_units(&engine, cockpit, extent, Some(handle)) .find(|contact| contact.pixel == start) .expect("selected warbot mark"); assert!(chosen.heading.is_some_and(|heading| heading.selected)); assert_eq!(chosen.route, [project(destination, extent).unwrap()]); - let captured = owned_units(&engine, cockpit, extent, None) + let captured = visible_units(&engine, cockpit, extent, None) .find(|contact| contact.pixel == start) .expect("captured warbot mark"); assert_eq!(captured.heading, None); @@ -281,7 +348,7 @@ mod tests { set_transform(&mut engine.world, handle, pose).unwrap(); let moved = project([x + extent / 8.0, y], extent).unwrap(); assert_eq!(moved, [start[0] + 32, start[1]]); - let units: Vec<_> = owned_units(&engine, cockpit, extent, None).collect(); + let units: Vec<_> = visible_units(&engine, cockpit, extent, None).collect(); let moved_contact = UnitContact { pixel: moved, ..captured @@ -299,7 +366,7 @@ mod tests { let vehicle = crate::board_friendly_warbot(&mut engine, Some(handle)) .unwrap() .unwrap(); - let headings: Vec<_> = owned_units(&engine, vehicle, extent, None) + let headings: Vec<_> = visible_units(&engine, vehicle, extent, None) .filter(|unit| unit.heading.is_some()) .collect(); assert_eq!( @@ -310,7 +377,7 @@ mod tests { }] ); assert_eq!(crate::disembark_warbot(&mut engine).unwrap(), Some(cockpit)); - let headings: Vec<_> = owned_units(&engine, cockpit, extent, None) + let headings: Vec<_> = visible_units(&engine, cockpit, extent, None) .filter_map(|unit| unit.heading) .collect(); assert_eq!(headings, [unit_heading(pose, false, false).unwrap()]); @@ -319,7 +386,7 @@ mod tests { #[test] #[ignore = "requires licensed corpus"] fn captured_factory_mark_disappears_at_control_depletion() { - use super::{landscape_extent, owned_buildings, BuildingContact}; + use super::{landscape_extent, visible_buildings, BuildingContact}; use crate::{ apply_loaded_mission_control_node_delta, create, load_gameplay_mission, loaded_mission_control_device_tables, starting_cockpit, EngineServices, @@ -367,15 +434,16 @@ mod tests { let marker = BuildingContact { pixel: project([x, y], extent).unwrap(), icon_x: 72, + tint: super::OWN_TINT, }; - assert!(!owned_buildings(&engine, cockpit, extent).any(|contact| contact == marker)); + assert!(!visible_buildings(&engine, cockpit, extent).any(|contact| contact == marker)); let owner = identity_metadata(&engine.world, cockpit.handle) .unwrap() .owner_id; assert!(owner.is_some()); set_owner(&mut engine.world, handle, owner).unwrap(); - assert!(owned_buildings(&engine, cockpit, extent).any(|contact| contact == marker)); + assert!(visible_buildings(&engine, cockpit, extent).any(|contact| contact == marker)); let table = loaded_mission_control_device_tables(&engine) .unwrap() @@ -396,6 +464,6 @@ mod tests { assert!(registration_sequence(&engine.world, handle) .unwrap() .is_some()); - assert!(!owned_buildings(&engine, cockpit, extent).any(|contact| contact == marker)); + assert!(!visible_buildings(&engine, cockpit, extent).any(|contact| contact == marker)); } } diff --git a/crates/fparkan-runtime/src/unit_chassis.rs b/crates/fparkan-runtime/src/unit_chassis.rs index 15370c8f..02b76ebb 100644 --- a/crates/fparkan-runtime/src/unit_chassis.rs +++ b/crates/fparkan-runtime/src/unit_chassis.rs @@ -11,9 +11,10 @@ pub(super) fn load_flags( drafts .iter() .filter(|draft| { - draft - .unit_dat_header_flags - .is_some_and(|class| class & crate::autodemo::MOBILE_UNIT != 0) + draft.unit_dat_header_flags.is_some_and(|class| { + class & crate::autodemo::MOBILE_UNIT != 0 + || class == crate::projectile::ANIMAL_UNIT_CLASS + }) }) .filter_map(|draft| { draft |
