aboutsummaryrefslogtreecommitdiff
path: root/crates/fparkan-runtime/src
diff options
context:
space:
mode:
authorValentin Popov <valentin@popov.link>2026-12-01 14:01:30 +0300
committerValentin Popov <valentin@popov.link>2026-12-01 14:01:30 +0300
commit85082a1c829050f375ad688d9ed563d753b3727b (patch)
tree58137bbf74beccd37fefcb80accb366137c0f514 /crates/fparkan-runtime/src
parent2dc43ad60e04922c630449f033f52e9e6839e2df (diff)
downloadfparkan-85082a1c829050f375ad688d9ed563d753b3727b.tar.xz
fparkan-85082a1c829050f375ad688d9ed563d753b3727b.zip
feat(movement): migrate animals between authored sites
Select shared migration sites on the ArealMap cadence and feed them to the common route follower with the animal flight clearance and Control climb limit. In The Constructor, both medusas lift off and travel around the selected site from their stock positions. The window showed the change at a fixed viewpoint with clean Vulkan validation. Path details and threat acquisition remain approximate.
Diffstat (limited to 'crates/fparkan-runtime/src')
-rw-r--r--crates/fparkan-runtime/src/animal_migration.rs202
-rw-r--r--crates/fparkan-runtime/src/factory_release.rs2
-rw-r--r--crates/fparkan-runtime/src/flight_altitude.rs7
-rw-r--r--crates/fparkan-runtime/src/lib.rs14
-rw-r--r--crates/fparkan-runtime/src/route_motion.rs12
-rw-r--r--crates/fparkan-runtime/src/unit_patrol.rs61
6 files changed, 290 insertions, 8 deletions
diff --git a/crates/fparkan-runtime/src/animal_migration.rs b/crates/fparkan-runtime/src/animal_migration.rs
new file mode 100644
index 00000000..58cf6dba
--- /dev/null
+++ b/crates/fparkan-runtime/src/animal_migration.rs
@@ -0,0 +1,202 @@
+//! 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<ObjectHandle>,
+ sites: Vec<MigrationSite>,
+ selected: Option<usize>,
+ deadline_ms: u32,
+}
+
+impl AnimalMigration {
+ pub(super) fn from_mission(
+ world: &World,
+ mission: &MissionDocument,
+ drafts: &[MissionObjectDraft],
+ handles: &[ObjectHandle],
+ ) -> Vec<Self> {
+ 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<MigrationSite> {
+ 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
+ );
+ }
+ }
+}
diff --git a/crates/fparkan-runtime/src/factory_release.rs b/crates/fparkan-runtime/src/factory_release.rs
index 93eb0c79..d9730fc5 100644
--- a/crates/fparkan-runtime/src/factory_release.rs
+++ b/crates/fparkan-runtime/src/factory_release.rs
@@ -207,6 +207,8 @@ impl FactoryDeparture {
};
let flight = (self.airborne && radius > 0.0).then_some(FlightClearance {
body_radius: radius,
+ height: 2.0 * radius,
+ vertical_limit: f32::INFINITY,
});
let speed = mission
.control_device_tables
diff --git a/crates/fparkan-runtime/src/flight_altitude.rs b/crates/fparkan-runtime/src/flight_altitude.rs
index 4bf5f7a9..ca8c085e 100644
--- a/crates/fparkan-runtime/src/flight_altitude.rs
+++ b/crates/fparkan-runtime/src/flight_altitude.rs
@@ -5,13 +5,14 @@ use crate::EngineError;
#[derive(Clone, Copy)]
pub(super) struct FlightClearance {
pub(super) body_radius: f32,
+ pub(super) height: f32,
+ pub(super) vertical_limit: f32,
}
impl FlightClearance {
pub(super) fn raised(self, altitude: f32, ground: f32, speed: f32, seconds: f32) -> (f32, f32) {
- // Keep approximately one radius of air under the hull, even when a
- // parked actor starts on the surface. No descent is requested here.
- let target = ground + 2.0 * self.body_radius;
+ let speed = speed.min(self.vertical_limit);
+ let target = ground + self.height;
if target <= altitude || speed <= 0.0 {
return (altitude, seconds);
}
diff --git a/crates/fparkan-runtime/src/lib.rs b/crates/fparkan-runtime/src/lib.rs
index adff6d00..3f60eb42 100644
--- a/crates/fparkan-runtime/src/lib.rs
+++ b/crates/fparkan-runtime/src/lib.rs
@@ -40,6 +40,7 @@ use std::collections::HashMap;
use std::num::NonZeroUsize;
use std::sync::Arc;
+mod animal_migration;
mod attack_target;
mod autodemo;
mod behavior_clock;
@@ -2721,6 +2722,19 @@ node_provider_distribution_suspended: false,
&& object_drafts[..reserve_start]
.iter()
.any(|draft| draft.unit_dat_header_flags == Some(projectile::ANIMAL_UNIT_CLASS));
+ if animals {
+ let migration = animal_migration::AnimalMigration::from_mission(
+ &new_runtime_world,
+ &mission,
+ &object_drafts[..reserve_start],
+ &handles[..reserve_start],
+ );
+ if !migration.is_empty() {
+ unit_patrol
+ .get_or_insert_with(unit_patrol::UnitPatrol::scripted)
+ .set_animal_migration(migration);
+ }
+ }
let autodemo_combat =
(unit_patrol.is_some() || guard_clans.contains(&true) || periodic_ai || animals).then(
|| {
diff --git a/crates/fparkan-runtime/src/route_motion.rs b/crates/fparkan-runtime/src/route_motion.rs
index 5ebaae78..8428d386 100644
--- a/crates/fparkan-runtime/src/route_motion.rs
+++ b/crates/fparkan-runtime/src/route_motion.rs
@@ -165,7 +165,11 @@ mod tests {
let start = TransformState::default();
let mut route = VecDeque::from([[0.0, 8.0]]);
let clearance = RouteClearance {
- flight: Some(FlightClearance { body_radius: 1.0 }),
+ flight: Some(FlightClearance {
+ body_radius: 1.0,
+ height: 2.0,
+ vertical_limit: f32::INFINITY,
+ }),
..Default::default()
};
let flat = |_| Ok(Some(0.0));
@@ -183,7 +187,11 @@ mod tests {
};
let mut route = VecDeque::from([[0.0, 10.0]]);
let clearance = RouteClearance {
- flight: Some(FlightClearance { body_radius: 1.0 }),
+ flight: Some(FlightClearance {
+ body_radius: 1.0,
+ height: 2.0,
+ vertical_limit: f32::INFINITY,
+ }),
..Default::default()
};
let ground = |[_, y]: [f32; 2]| Ok(Some(if (3.0..5.0).contains(&y) { 4.0 } else { 0.0 }));
diff --git a/crates/fparkan-runtime/src/unit_patrol.rs b/crates/fparkan-runtime/src/unit_patrol.rs
index b4b81c7f..59965b4c 100644
--- a/crates/fparkan-runtime/src/unit_patrol.rs
+++ b/crates/fparkan-runtime/src/unit_patrol.rs
@@ -1,4 +1,5 @@
use super::{
+ animal_migration::{flight_clearance, AnimalMigration},
autodemo::{MOBILE_UNIT, PLANT_CLASS},
boarding::WARBOT_CLASS,
building_passage::CapturePassage,
@@ -9,7 +10,7 @@ use super::{
patrol_points::{PatrolPointReport, PatrolPoints},
route_motion::{follow_route, route_points, turn_toward, RouteClearance},
route_obstacles::BuildingFootprints,
- route_traffic::FrameTraffic,
+ route_traffic::{body_radius, FrameTraffic},
unit_combat::CombatTarget,
unit_speed::{order_speed, UnitSpeedKind, UnitSpeedReport},
EngineError, LoadedMissionState, MissionDocument, MissionObjectDraft, MissionScriptBundle,
@@ -28,6 +29,8 @@ pub(super) struct UnitPatrol {
center: Option<[f32; 2]>,
units: Vec<PatrollingUnit>,
factory_departures: Vec<FactoryDeparture>,
+ animal_migration: Vec<AnimalMigration>,
+ migration_rng: u32,
shut_down: HashSet<ObjectHandle>,
script_orders: Vec<(ObjectHandle, VecDeque<orders::UnitOrder>)>,
script_order_counts: BTreeMap<(u32, u32), u64>,
@@ -55,6 +58,7 @@ struct PatrollingUnit {
raid_factory: Option<(ObjectHandle, usize)>,
ground_support: Option<Option<GroundSupport>>,
capture_passage: Option<CapturePassage>,
+ animal_clearance: Option<f32>,
}
pub(super) struct PreparedPatrol {
@@ -160,6 +164,8 @@ impl UnitPatrol {
center: None,
units: Vec::new(),
factory_departures: Vec::new(),
+ animal_migration: Vec::new(),
+ migration_rng: 1,
shut_down: HashSet::new(),
script_orders: Vec::new(),
script_order_counts: BTreeMap::new(),
@@ -217,6 +223,7 @@ impl UnitPatrol {
raid_factory: None,
ground_support: None,
capture_passage: None,
+ animal_clearance: None,
});
true
}
@@ -260,6 +267,39 @@ impl UnitPatrol {
}
}
+ pub(super) fn set_animal_migration(&mut self, migration: Vec<AnimalMigration>) {
+ for clan in &migration {
+ eprintln!(
+ "animal_migration_approx clan={} (animal route, arrival and RNG order remain open)",
+ clan.owner.0
+ );
+ }
+ self.animal_migration = migration;
+ }
+
+ fn advance_animal_migration(&mut self, world: &World, now_ms: u32, crt: &mut u32) {
+ let mut migrations = std::mem::take(&mut self.animal_migration);
+ for migration in &mut migrations {
+ migration
+ .animals
+ .retain(|&handle| transform_state(world, handle).is_ok());
+ if migration.animals.is_empty() {
+ continue;
+ }
+ let Some(site) = migration.select(now_ms, &mut self.migration_rng) else {
+ continue;
+ };
+ for &handle in &migration.animals {
+ self.order(world, handle, site.center, site.radius);
+ if let Some(unit) = self.units.iter_mut().find(|unit| unit.handle == handle) {
+ unit.animal_clearance = Some(flight_clearance(crt));
+ }
+ }
+ }
+ migrations.retain(|migration| !migration.animals.is_empty());
+ self.animal_migration = migrations;
+ }
+
pub(super) fn hallway_doors(
&self,
building: ObjectHandle,
@@ -445,12 +485,15 @@ impl UnitPatrol {
raid_factory: None,
ground_support: None,
capture_passage: None,
+ animal_clearance: None,
})
.collect();
Some(Self {
center: Some(center),
units,
factory_departures: Vec::new(),
+ animal_migration: Vec::new(),
+ migration_rng: 1,
shut_down: HashSet::new(),
script_orders: Vec::new(),
script_order_counts: BTreeMap::new(),
@@ -477,6 +520,7 @@ impl UnitPatrol {
let chassis = &mission.unit_chassis_flags;
let mut state = self.clone();
state.advance_script_orders(world, &mission.control_device_tables);
+ state.advance_animal_migration(world, now_ms, crt);
state.units.retain(|unit| {
(unit
.destinations
@@ -524,7 +568,10 @@ impl UnitPatrol {
let from = before.position.map(f32::from_bits);
let motion_object = crate::CombatObject::read(world, unit.handle);
let original_id = motion_object.original_id.unwrap_or(unit.handle.slot);
- let can_fly = chassis.get(&original_id).and_then(|flags| flags.can_fly);
+ let can_fly = unit
+ .animal_clearance
+ .map(|_| true)
+ .or_else(|| chassis.get(&original_id).and_then(|flags| flags.can_fly));
if let Some(destinations) = &mut unit.destinations {
if destinations
.front()
@@ -653,9 +700,17 @@ impl UnitPatrol {
continue;
}
state.motion_report.update(motion_object, now_ms);
- let radius = traffic.radius(unit.handle);
+ let radius = if unit.animal_clearance.is_some() {
+ body_radius(&mission.mission_assets, original_id as usize, before).unwrap_or(1.0)
+ } else {
+ traffic.radius(unit.handle)
+ };
let flight = (can_fly == Some(true) && radius > 0.0).then_some(FlightClearance {
body_radius: radius,
+ height: unit.animal_clearance.unwrap_or(2.0 * radius),
+ vertical_limit: unit.animal_clearance.map_or(f32::INFINITY, |_| {
+ super::animal_migration::vertical_limit(mission, unit.handle)
+ }),
});
let ground = if can_fly == Some(false) {
*unit.ground_support.get_or_insert_with(|| {