//! Behavior task 5 in mode 0x204: find a reachable hostile mobile unit. use super::{ObjectHandle, UnitPatrol, World}; use crate::{ attack_target, next_crt_rand, route_motion::route_points, EngineError, LoadedMissionState, MissionControlDeviceTableState, }; use fparkan_terrain::{NavigationQuery, SurfaceQuery}; use fparkan_world::{identity_metadata, registration_sequence, transform_state}; use std::collections::VecDeque; #[derive(Clone, Default)] pub(super) struct Search { target: Option, } impl UnitPatrol { pub(super) fn start_search(&mut self, world: &World, actor: ObjectHandle) -> bool { let Ok(pose) = transform_state(world, actor) else { return false; }; let [x, y, _] = pose.position.map(f32::from_bits); self.order(world, actor, [x, y], f32::INFINITY); if let Some(unit) = self.units.iter_mut().find(|unit| unit.handle == actor) { unit.search = Some(Search::default()); } true } /// Outer option denotes an active search, inner option its current target. pub(crate) fn search_target(&self, actor: ObjectHandle) -> Option> { let unit = self.units.iter().find(|unit| unit.handle == actor)?; Some(unit.search.as_ref()?.target) } } impl Search { pub(super) fn forget_depleted( &mut self, world: &World, controls: &[MissionControlDeviceTableState], ) -> bool { if self .target .is_some_and(|target| attack_target::complete(world, controls, target)) { self.target = None; return true; } false } pub(super) fn route( &mut self, world: &World, mission: &LoadedMissionState, actor: ObjectHandle, from: [f32; 3], crt: &mut u32, ) -> Result, EngineError> { let terrain = &mission.terrain; let clans = &mission.mission.clans; let owner = identity_metadata(world, actor) .ok() .and_then(|meta| meta.owner_id); let clan = owner.and_then(|owner| clans.get(usize::from(owner.0))); // Behavior+0x30d27 walks native object groups. Use the live Control registry // until the search task's native group membership is available. let candidates = mission.control_device_tables.iter().filter_map(|table| { let handle = table.handle; let class = mission .object_drafts .get(table.original_id?.0 as usize)? .unit_dat_header_flags?; let target_owner = identity_metadata(world, handle).ok()?.owner_id?; let target_clan = clans.get(usize::from(target_owner.0))?; if Some(target_owner) == owner || !clan?.relations.iter().any(|relation| { relation.relation_value == 0 && relation.other_clan_name.raw == target_clan.name.raw }) || table.node_provider_depletion_marked || registration_sequence(world, handle).ok()?.is_none() { return None; } let position = transform_state(world, handle) .ok()? .position .map(f32::from_bits); (position != [0.0; 3]).then_some((handle, class, position)) }); if let Some((target, points)) = nearest_reachable(candidates, from, |goal| route_points(terrain, from, goal))? { self.target = Some(target); return Ok(points); } self.target = None; let Some(bounds) = terrain.surface_bounds() else { return Ok(VecDeque::new()); }; // Behavior+0x30ecd draws up to 150 points, inset 100 units from each edge. for _ in 0..150 { let xy = [0, 1].map(|axis| { let fraction = next_crt_rand(crt) as f32 * (1.0 / 32767.0); bounds[0][axis] + 100.0 + fraction * (bounds[1][axis] - bounds[0][axis] - 200.0) }); let Some(z) = terrain.height_at(xy).map_err(EngineError::Terrain)? else { continue; }; let goal = [xy[0], xy[1], z]; let areal = terrain.locate_areal(goal).map_err(EngineError::Terrain)?; if areal .and_then(|areal| terrain.areal_logic_flag(areal)) .is_some_and(|flag| flag != 0) { return Ok(route_points(terrain, from, goal)?.unwrap_or_default()); } } Ok(VecDeque::new()) } } fn nearest_reachable( candidates: impl Iterator, from: [f32; 3], mut route_to: impl FnMut([f32; 3]) -> Result, EngineError>, ) -> Result, EngineError> { let mut best_distance = 3000.0; let mut best = None; for (handle, class, to) in candidates { if class == 0 || class & 0x0100_e000 != class { continue; } let [dx, dy, dz] = std::array::from_fn(|axis| to[axis] - from[axis]); let distance = dx.hypot(dy).hypot(dz); if distance <= best_distance { if let Some(route) = route_to(to)? { best_distance = distance; best = Some((handle, route)); } } } Ok(best) } #[cfg(test)] mod tests { use super::*; #[test] fn search_prefers_the_last_equally_close_reachable_mobile_target() { let handle = |slot| ObjectHandle { slot, generation: 1, }; let closest = [10.0, 0.0, 0.0]; let blocked = [0.0, 0.0, 9.0]; let last = [-10.0, 0.0, 0.0]; let candidates = [ (handle(0), 0x0100_4000, closest), (handle(1), 0x0100_8000, blocked), (handle(2), 0x8001_0000, [1.0, 0.0, 0.0]), (handle(3), 0x0100_2000, last), (handle(4), 0x0100_4000, [3000.0, 0.0, 15.0]), ]; let selected = nearest_reachable(candidates.into_iter(), [0.0; 3], |point| { assert!(point == closest || point == blocked || point == last); Ok((point != blocked).then_some(point)) }) .unwrap(); assert_eq!(selected, Some((handle(3), last))); } }