//! Behavior task 8: approach a friendly recharge point, service, then leave. use super::{ObjectHandle, PatrollingUnit, UnitPatrol, World}; use crate::{ building_passage::{building_entrance, BuildingPassage, PassageLeg}, LoadedMissionState, }; use fparkan_terrain::SurfaceQuery; use fparkan_world::{identity_metadata, registration_sequence, transform_state, OwnerId}; use std::collections::VecDeque; #[derive(Clone)] pub(super) enum Recharge { FindFacility, Approach { facility: ObjectHandle, exit: VecDeque, }, Service { facility: ObjectHandle, exit: VecDeque, since_ms: u32, }, Leave { facility: ObjectHandle, }, } impl UnitPatrol { pub(super) fn start_recharge(&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.recharge = Some(Recharge::FindFacility); unit.destinations = Some(VecDeque::new()); } true } pub(crate) fn is_servicing(&self, actor: ObjectHandle) -> bool { self.units.iter().any(|unit| { unit.handle == actor && matches!(unit.recharge, Some(Recharge::Service { .. })) }) } } impl PatrollingUnit { /// Returns whether the recharge task is still active. pub(super) fn advance_recharge( &mut self, world: &World, mission: &LoadedMissionState, now_ms: u32, from: [f32; 3], clearance: f32, ) -> bool { let Some(task) = self.recharge.take() else { return false; }; let owner = identity_metadata(world, self.handle) .ok() .and_then(|meta| meta.owner_id); let travel_complete = self.destinations.as_ref().is_none_or(VecDeque::is_empty) && self .building_passage .as_ref() .is_none_or(|route| route.legs.is_empty()); self.recharge = match task { Recharge::FindFacility => owner.and_then(|owner| { let (destination, passage, exit) = approach(world, mission, owner, from, clearance)?; let facility = passage.building; self.destinations = Some(VecDeque::from([destination])); self.building_passage = Some(passage); Some(Recharge::Approach { facility, exit }) }), Recharge::Approach { facility, exit } if travel_complete => Some(Recharge::Service { facility, exit, since_ms: now_ms, }), Recharge::Service { facility, exit, since_ms, } if now_ms.saturating_sub(since_ms) > 10_000 => { // Behavior+0x2eaa0 changes from service to leaving after ten seconds. self.building_passage = Some(BuildingPassage { building: facility, legs: exit, opening: None, }); Some(Recharge::Leave { facility }) } Recharge::Leave { .. } if travel_complete => None, _ => Some(task), }; let valid = self.recharge.as_ref().is_some_and(|task| match task { Recharge::FindFacility => false, Recharge::Approach { facility, .. } | Recharge::Service { facility, .. } | Recharge::Leave { facility } => usable(world, mission, *facility, owner), }); if !valid { self.recharge = None; self.destinations = Some(VecDeque::new()); self.points.clear(); self.building_passage = None; } valid } } fn approach( world: &World, mission: &LoadedMissionState, owner: OwnerId, from: [f32; 3], clearance: f32, ) -> Option<([f32; 2], BuildingPassage, VecDeque)> { mission .control_device_tables .iter() .filter_map(|table| { let facility = table.handle; let index = table.original_id?.0 as usize; let class = mission.object_drafts.get(index)?.unit_dat_header_flags?; if class & 0x8000_0000 == 0 || !usable(world, mission, facility, Some(owner)) { return None; } let pose = transform_state(world, facility).ok()?; // Behavior+0x23b60 requests a Hallway point with mask 0x620. let entry = building_entrance( &mission.mission_assets, &mission.terrain, index, pose, from, clearance, 0x620, )?; let ground = mission.terrain.height_at(entry.staging).ok()??; let distance = (from[0] - entry.staging[0]).hypot(from[1] - entry.staging[1]); let exit = entry.exit(ground); Some(( distance, entry.staging, BuildingPassage { building: facility, legs: entry.legs, opening: None, }, exit, )) }) .min_by(|a, b| a.0.total_cmp(&b.0)) .map(|(_, staging, passage, exit)| (staging, passage, exit)) } fn usable( world: &World, mission: &LoadedMissionState, facility: ObjectHandle, owner: Option, ) -> bool { owner.is_some() && registration_sequence(world, facility).is_ok_and(|sequence| sequence.is_some()) && identity_metadata(world, facility).is_ok_and(|meta| meta.owner_id == owner) && !mission .control_device_tables .iter() .any(|table| table.handle == facility && table.node_provider_depletion_marked) } #[cfg(test)] mod tests { use super::*; use crate::{ create, frame, load_gameplay_mission, starting_cockpit, strategic_orders, strategic_roster, EngineServices, MissionControlDeviceTableStatus, MissionMode, MissionRequest, MissionStartupInput, }; use fparkan_vfs::DirectoryVfs; use std::sync::Arc; #[test] #[ignore = "requires licensed corpus"] fn licensed_fortresses_recharges_the_first_warbot_from_its_start() { 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/Single.01/data.tma".into(), mode: MissionMode::SingleMission, }, MissionStartupInput { queue_time_ms: 0, research_creation_gate: false, }, None, ) .unwrap(); let cockpit = starting_cockpit(&engine).unwrap(); let actor = strategic_roster::warbot_rows(&engine, cockpit)[0].handle; let before = transform_state(&engine.world, actor).unwrap(); let mission = engine.loaded.as_mut().unwrap(); let table = mission .control_device_tables .iter_mut() .find(|table| table.handle == actor) .unwrap(); let MissionControlDeviceTableStatus::Available(devices) = &mut table.status else { panic!("stock LTW-3 has no Control devices"); }; let (gun, device) = devices .iter_mut() .enumerate() .find(|(_, device)| { device.descriptor.tag == 2 && device.weapon_rounds.is_some_and(|rounds| rounds > 0) }) .unwrap(); device.weapon_rounds = Some(0); assert!(strategic_orders::recharge(&mut engine, cockpit, actor)); assert_eq!( strategic_roster::warbot_rows(&engine, cockpit)[0].order_label, 0x1831 ); let mut docked = None; for now in (0..=90_000).step_by(100) { frame(&mut engine, now).unwrap(); let mission = engine.loaded.as_ref().unwrap(); let patrol = mission.unit_patrol.as_ref().unwrap(); assert!(patrol.satellite_route(actor).is_empty()); if patrol.is_servicing(actor) { docked = Some(transform_state(&engine.world, actor).unwrap()); } if patrol.active_order_code(actor) == 0 { let docked = docked.expect("recharge finished before reaching the service point"); let after = transform_state(&engine.world, actor).unwrap(); assert_ne!(docked.position, before.position); assert_ne!(after.position, docked.position); let table = mission .control_device_tables .iter() .find(|table| table.handle == actor) .unwrap(); let MissionControlDeviceTableStatus::Available(devices) = &table.status else { panic!("stock LTW-3 lost its Control devices"); }; assert!(devices[gun].weapon_rounds.unwrap() > 0); return; } } let last = transform_state(&engine.world, actor).unwrap(); panic!( "stock LTW-3 did not leave its recharge facility: start={:?} docked={} end={:?}", before.position.map(f32::from_bits), docked.is_some(), last.position.map(f32::from_bits) ); } }