//! Migration sites shared by the animals of a clan. use crate::{ behavior_clock::{next_crt_rand, next_deadline}, projectile::ANIMAL_UNIT_CLASS, ClanBody, LoadedMissionState, MissionDocument, MissionObjectDraft, }; use fparkan_world::{identity_metadata, ObjectHandle, OwnerId, World}; const MIGRATION_BASE: u16 = 937; const MIGRATION_JITTER: u16 = 1875; #[derive(Clone, Copy)] pub(super) struct MigrationSite { pub(super) center: [f32; 2], pub(super) radius: f32, } #[derive(Clone)] pub(super) struct AnimalMigration { pub(super) owner: OwnerId, pub(super) animals: Vec, sites: Vec, selected: Option, deadline_ms: u32, } impl AnimalMigration { pub(super) fn from_mission( world: &World, mission: &MissionDocument, drafts: &[MissionObjectDraft], handles: &[ObjectHandle], ) -> Vec { mission .clans .iter() .enumerate() .filter_map(|(index, clan)| { let ClanBody::Spatial { spatial_groups, .. } = &clan.body else { return None; }; let owner = OwnerId(u16::try_from(index).ok()?); let sites: Vec<_> = spatial_groups .iter() .flat_map(|group| &group.records) .filter_map(|&[x, y, _, _, radius]| { (x.is_finite() && y.is_finite() && radius.is_finite() && radius > 0.0) .then_some(MigrationSite { center: [x, y], radius, }) }) .collect(); if sites.is_empty() { return None; } let animals: Vec<_> = drafts .iter() .zip(handles) .filter(|(draft, handle)| { draft.unit_dat_header_flags == Some(ANIMAL_UNIT_CLASS) && identity_metadata(world, **handle) .is_ok_and(|identity| identity.owner_id == Some(owner)) }) .map(|(_, &handle)| handle) .collect(); (!animals.is_empty()).then_some(Self { owner, animals, sites, selected: None, deadline_ms: 0, }) }) .collect() } pub(super) fn select(&mut self, now_ms: u32, rng: &mut u32) -> Option { if self.selected.is_some() { if now_ms <= self.deadline_ms { return None; } // The native expiry check rolls a deadline before the site picker rolls again. next_deadline(now_ms, MIGRATION_BASE, MIGRATION_JITTER, rng); } self.deadline_ms = next_deadline(now_ms, MIGRATION_BASE, MIGRATION_JITTER, rng); let index = next_crt_rand(rng) as usize % self.sites.len(); let previous = self.selected.replace(index); (previous != Some(index)).then_some(self.sites[index]) } } pub(super) fn flight_clearance(rng: &mut u32) -> f32 { 45.0 + next_crt_rand(rng) as f32 * (50.0 / 32767.0) } pub(super) fn vertical_limit(mission: &LoadedMissionState, handle: ObjectHandle) -> f32 { mission .control_device_tables .iter() .find(|table| table.handle == handle) .and_then(|table| table.owner_profile.as_ref()) .map(|profile| f32::from_bits(profile.current_words[8])) .filter(|limit| limit.is_finite() && *limit >= 0.0) .unwrap_or(f32::INFINITY) } #[cfg(test)] mod tests { use super::*; #[test] fn the_clan_reuses_its_site_until_the_deadline_expires() { let mut rng = 1; let sites = vec![ MigrationSite { center: [10.0, 20.0], radius: 40.0, }, MigrationSite { center: [50.0, 70.0], radius: 50.0, }, ]; let mut migration = AnimalMigration { owner: OwnerId(1), animals: Vec::new(), sites, selected: None, deadline_ms: 0, }; let first = migration.select(0, &mut rng).unwrap(); assert_eq!(first.center, [50.0, 70.0]); let deadline = migration.deadline_ms; assert_eq!(deadline, 79_186); let after_selection = rng; assert!(migration.select(deadline, &mut rng).is_none()); assert_eq!(rng, after_selection); migration.select(deadline + 1, &mut rng); assert!(migration.deadline_ms > deadline); assert_ne!(rng, after_selection); } #[test] #[ignore = "requires licensed corpus"] fn licensed_constructor_animals_take_off_and_migrate_from_stock_start() { use crate::{ create, frame, load_gameplay_mission, mission_object_handle, EngineServices, MissionMode, MissionRequest, MissionStartupInput, }; use fparkan_terrain::SurfaceQuery; use fparkan_vfs::DirectoryVfs; use fparkan_world::{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.02/data.tma".into(), mode: MissionMode::SingleMission, }, MissionStartupInput { queue_time_ms: 0, research_creation_gate: false, }, None, ) .unwrap(); let animals = [2, 3].map(|id| mission_object_handle(&engine, OriginalObjectId(id)).unwrap()); let pose = |engine: &crate::Engine, handle| { transform_state(&engine.world, handle) .unwrap() .position .map(f32::from_bits) }; let initial = animals.map(|handle| pose(&engine, handle)); for now in (0..=60_000).step_by(100) { frame(&mut engine, now).unwrap(); if now == 1_000 { for (handle, [_, _, z0]) in animals.into_iter().zip(initial) { let [_, _, z] = pose(&engine, handle); assert!((z - z0 - 2.0).abs() < 0.01, "unexpected climb speed"); } } } let terrain = &engine.loaded.as_ref().unwrap().terrain; for (handle, [x0, y0, _]) in animals.into_iter().zip(initial) { let [x, y, z] = pose(&engine, handle); assert!((x - x0).hypot(y - y0) > 1.0, "animal stayed at [{x}, {y}]"); let ground = terrain.height_at([x, y]).unwrap().unwrap(); assert!( z - ground >= 45.0, "animal flew at clearance {}", z - ground ); } } }