diff options
Diffstat (limited to 'crates/fparkan-runtime')
| -rw-r--r-- | crates/fparkan-runtime/src/factory_release.rs | 173 | ||||
| -rw-r--r-- | crates/fparkan-runtime/src/production.rs | 33 | ||||
| -rw-r--r-- | crates/fparkan-runtime/src/unit_combat.rs | 4 | ||||
| -rw-r--r-- | crates/fparkan-runtime/src/unit_patrol.rs | 49 | ||||
| -rw-r--r-- | crates/fparkan-runtime/src/unit_patrol/orders.rs | 7 |
5 files changed, 231 insertions, 35 deletions
diff --git a/crates/fparkan-runtime/src/factory_release.rs b/crates/fparkan-runtime/src/factory_release.rs index d6b29eda..03975a0f 100644 --- a/crates/fparkan-runtime/src/factory_release.rs +++ b/crates/fparkan-runtime/src/factory_release.rs @@ -1,11 +1,20 @@ //! Select a free point on the ground for the current outdoor factory release. use crate::{ + flight_altitude::FlightClearance, + ground_support::GroundSupport, + route_motion::{follow_route, RouteClearance, WAYPOINT_TOLERANCE}, route_obstacles::{BuildingFootprints, Footprint}, route_traffic::{body_radius, FrameTraffic}, EngineError, LoadedMissionState, ObjectHandle, TransformState, World, }; use fparkan_terrain::SurfaceQuery; +use std::collections::VecDeque; + +pub(super) struct ReleaseSite { + pub(super) position: [f32; 3], + pub(super) exit: Option<[f32; 2]>, +} pub(super) fn clear_release_position( world: &World, @@ -14,7 +23,7 @@ pub(super) fn clear_release_position( plant: ObjectHandle, slot: usize, preferred: [f32; 3], -) -> Result<Option<[f32; 3]>, EngineError> { +) -> Result<Option<ReleaseSite>, EngineError> { let draft = &mission.object_drafts[slot]; let pose = TransformState { position: preferred.map(f32::to_bits), @@ -27,7 +36,10 @@ pub(super) fn clear_release_position( buildings.for_handle(plant), body_radius(&mission.mission_assets, slot, pose), ) else { - return Ok(Some(preferred)); + return Ok(Some(ReleaseSite { + position: preferred, + exit: None, + })); }; let mut blocked = buildings.with_clearance(radius); let [x, y, _] = preferred; @@ -36,58 +48,175 @@ pub(super) fn clear_release_position( return Ok(None); }; blocked.extend(neighbors); - release_position([x, y], plant_bounds.expanded(radius), &blocked, |point| { - mission - .terrain - .height_at(point) - .map_err(EngineError::Terrain) - }) + release_position( + [x, y], + plant_bounds.expanded(radius), + radius, + &blocked, + |point| { + mission + .terrain + .height_at(point) + .map_err(EngineError::Terrain) + }, + ) } fn release_position( preferred: [f32; 2], plant: Footprint, + radius: f32, blocked: &[Footprint], mut height_at: impl FnMut([f32; 2]) -> Result<Option<f32>, EngineError>, -) -> Result<Option<[f32; 3]>, EngineError> { +) -> Result<Option<ReleaseSite>, EngineError> { let center = plant.center(); let mut alternatives = Vec::from(plant.exits(center)); alternatives.extend(plant.corners()); let distance = |p: [f32; 2]| (p[0] - preferred[0]).hypot(p[1] - preferred[1]); alternatives.sort_by(|&a, &b| distance(a).total_cmp(&distance(b))); - for point in std::iter::once(preferred).chain(alternatives) { + let apron = plant.expanded(radius); + for point in alternatives.into_iter().chain([preferred]) { if blocked.iter().any(|bounds| bounds.contains(point)) { continue; } - if let Some(z) = height_at(point)? { - return Ok(Some([point[0], point[1], z + 2.0])); + let Some(z) = height_at(point)? else { + continue; + }; + let position = [point[0], point[1], z + 2.0]; + if !apron.contains(point) { + return Ok(Some(ReleaseSite { + position, + exit: None, + })); + } + let mut exits = apron.exits(point); + let distance = |p: [f32; 2]| (p[0] - point[0]).hypot(p[1] - point[1]); + exits.sort_by(|&a, &b| distance(a).total_cmp(&distance(b))); + for exit in exits { + if !blocked.iter().any(|bounds| bounds.intersects(point, exit)) + && height_at(exit)?.is_some() + { + return Ok(Some(ReleaseSite { + position, + exit: Some(exit), + })); + } } } Ok(None) } +#[derive(Clone)] +pub(super) struct FactoryDeparture { + pub(super) handle: ObjectHandle, + goal: [f32; 2], + ground: Option<GroundSupport>, + airborne: bool, +} + +impl FactoryDeparture { + pub(super) fn new( + handle: ObjectHandle, + index: usize, + goal: [f32; 2], + mission: &LoadedMissionState, + ) -> Self { + let airborne = mission.object_drafts[index] + .original_id + .and_then(|id| mission.unit_chassis_flags.get(&id.0)) + .and_then(|chassis| chassis.can_fly) + == Some(true); + let ground = (!airborne) + .then(|| GroundSupport::prepare(&mission.mission_assets, index)) + .flatten(); + Self { + handle, + goal, + ground, + airborne, + } + } + + pub(super) fn move_out( + &self, + before: TransformState, + mission: &LoadedMissionState, + traffic: &mut FrameTraffic, + buildings: &BuildingFootprints, + seconds: f32, + ) -> Result<TransformState, EngineError> { + let [x, y, _] = before.position.map(f32::from_bits); + let radius = traffic.radius(self.handle); + let Some(neighbors) = traffic.blockers(self.handle, [x, y], radius) else { + return Ok(before); + }; + let flight = (self.airborne && radius > 0.0).then_some(FlightClearance { + body_radius: radius, + }); + let speed = mission + .control_device_tables + .iter() + .find(|table| table.handle == self.handle) + .and_then(|table| table.owner_profile.as_ref()) + .map(|profile| f32::from_bits(profile.current_words[7])) + .filter(|speed| speed.is_finite() && *speed >= 0.0) + .unwrap_or(9.0); + let (after, swept) = follow_route( + before, + &mut VecDeque::from([self.goal]), + speed, + seconds, + RouteClearance { + buildings: &buildings.with_clearance(radius), + traffic: &neighbors, + flight, + ground: self.ground, + }, + |point| { + mission + .terrain + .height_at(point) + .map_err(EngineError::Terrain) + }, + )?; + traffic.reserve(self.handle, swept); + Ok(after) + } + + pub(super) fn finished(&self, pose: TransformState) -> bool { + let [x, y, _] = pose.position.map(f32::from_bits); + (x - self.goal[0]).hypot(y - self.goal[1]) <= WAYPOINT_TOLERANCE + } +} + #[cfg(test)] mod tests { use super::*; #[test] - fn release_keeps_the_preferred_clear_point_or_checks_the_factory_perimeter() { + fn release_keeps_the_cleared_path_out_of_the_factory_apron() { let plant = Footprint::point([0.0; 2]).expanded(5.0); let parked = Footprint::point([6.0, 0.0]).expanded(1.0); let flat = |_| Ok(Some(3.0)); - assert_eq!( - release_position([7.5, 0.0], plant, &[plant, parked], flat).unwrap(), - Some([7.5, 0.0, 5.0]) - ); - let [x, y, z] = release_position([6.0, 0.0], plant, &[plant, parked], flat) + let site = release_position([6.0, 0.0], plant, 2.0, &[plant, parked], flat) .unwrap() .unwrap(); + let [x, y, z] = site.position; + let exit = site.exit.unwrap(); assert!(!plant.contains([x, y]) && !parked.contains([x, y])); + assert!(!plant.expanded(2.0).contains(exit)); + assert!(!parked.intersects([x, y], exit)); assert_eq!(z, 5.0); let occupied = Footprint::point([0.0; 2]).expanded(8.0); - assert_eq!( - release_position([6.0, 0.0], plant, &[occupied], flat).unwrap(), - None - ); + assert!(release_position([6.0, 0.0], plant, 2.0, &[occupied], flat) + .unwrap() + .is_none()); + let open_ground = release_position([8.0, 0.0], plant, 2.0, &[plant], |point| { + Ok((point == [8.0, 0.0]).then_some(3.0)) + }) + .unwrap() + .unwrap(); + assert_eq!(open_ground.position, [8.0, 0.0, 5.0]); + assert!(open_ground.exit.is_none()); } } diff --git a/crates/fparkan-runtime/src/production.rs b/crates/fparkan-runtime/src/production.rs index ed39eb6a..f1ba5035 100644 --- a/crates/fparkan-runtime/src/production.rs +++ b/crates/fparkan-runtime/src/production.rs @@ -1,6 +1,7 @@ use super::{ autodemo::{reinforcement_position, MOBILE_UNIT, PLANT_CLASS}, behavior_ore_index_for_handle, + factory_release::FactoryDeparture, mission_events::on_communicator, normalize_engine_path, query_behavior_profile_ore_rate, research::{load_clan_table, RESEARCHED}, @@ -294,8 +295,8 @@ impl Production { return Ok(None); } let pose = transform_state(world, order.plant)?; - // shortcut: prefer the old outdoor point until the factory's elevated - // release and protected exit order are simulated. + // shortcut: the outdoor direction selects an apron until the elevated + // assembly platform and its ramp are simulated. let preferred = reinforcement_position( pose.position.map(f32::from_bits), pose.orientation.map(f32::from_bits), @@ -305,7 +306,7 @@ impl Production { &mission.terrain, &mut self.rng, )?; - let Some(position) = super::factory_release::clear_release_position( + let Some(site) = super::factory_release::clear_release_position( world, mission, &mut self.buildings, @@ -321,7 +322,7 @@ impl Production { mission, order.slot, order.owner.0, - position, + site.position, self.controls[order.slot - self.reserve_start].clone(), )?; let draft = &mission.object_drafts[order.slot]; @@ -355,6 +356,13 @@ impl Production { .expect("free order belongs to a prepared factory"); *count -= 1; } + if let Some(exit) = site.exit { + let departure = FactoryDeparture::new(handle, order.slot, exit, mission); + mission + .unit_patrol + .get_or_insert_with(crate::unit_patrol::UnitPatrol::scripted) + .begin_factory_departure(departure, now_ms); + } Ok(Some(SpawnedUnit { object_index: order.slot, handle, @@ -934,6 +942,7 @@ mod tests { let cargo_slots = production.reserve_start + transport_index * RESERVE_SLOTS; assert!((cargo_slots..cargo_slots + RESERVE_SLOTS).contains(&production.pending[0].slot)); let mut completed = Vec::new(); + let mut departures = Vec::new(); for time in (40_016..=40_000 + duration + 2000).step_by(16) { if let Some(unit) = step_headless(&mut engine, InputSnapshot::default(), time) .unwrap() @@ -960,6 +969,13 @@ mod tests { .unwrap() .iter() .all(|bounds| !bounds.contains([x, y]))); + if mission + .unit_patrol + .as_ref() + .is_some_and(|patrol| patrol.is_leaving_factory(unit.handle)) + { + departures.push((unit.handle, [x, y])); + } completed.push((unit.clan, unit.object_index)); } } @@ -1008,6 +1024,15 @@ mod tests { .clan_ai_events .transport_orders() .any(|(clan, unit, _)| clan == 1 && unit == handle.slot)); + assert!(departures.into_iter().any(|(actor, start)| { + let Some(patrol) = loaded.unit_patrol.as_ref() else { + return false; + }; + transform_state(&engine.world, actor).is_ok_and(|pose| { + let [x, y, _] = pose.position.map(f32::from_bits); + !patrol.is_leaving_factory(actor) && [x, y] != start + }) + })); return; } } diff --git a/crates/fparkan-runtime/src/unit_combat.rs b/crates/fparkan-runtime/src/unit_combat.rs index 60123dcd..7059a09b 100644 --- a/crates/fparkan-runtime/src/unit_combat.rs +++ b/crates/fparkan-runtime/src/unit_combat.rs @@ -342,7 +342,9 @@ impl AutoDemoCombat { live.iter() .filter_map(|&(handle, clan, from, _, position)| { if patrol.is_some_and(|patrol| { - patrol.is_shut_down(handle) || patrol.is_moving_to_destination(handle) + patrol.is_shut_down(handle) + || patrol.is_moving_to_destination(handle) + || patrol.is_leaving_factory(handle) }) { return None; } diff --git a/crates/fparkan-runtime/src/unit_patrol.rs b/crates/fparkan-runtime/src/unit_patrol.rs index 0eaf04fc..8050caac 100644 --- a/crates/fparkan-runtime/src/unit_patrol.rs +++ b/crates/fparkan-runtime/src/unit_patrol.rs @@ -1,6 +1,7 @@ use super::{ autodemo::{MOBILE_UNIT, PLANT_CLASS}, boarding::WARBOT_CLASS, + factory_release::FactoryDeparture, flight_altitude::FlightClearance, ground_support::GroundSupport, next_crt_rand, @@ -25,6 +26,7 @@ pub(super) use orders::supports_order; pub(super) struct UnitPatrol { center: Option<[f32; 2]>, units: Vec<PatrollingUnit>, + factory_departures: Vec<FactoryDeparture>, shut_down: HashSet<ObjectHandle>, script_orders: Vec<(ObjectHandle, VecDeque<orders::UnitOrder>)>, script_order_counts: BTreeMap<(u32, u32), u64>, @@ -155,6 +157,7 @@ impl UnitPatrol { Self { center: None, units: Vec::new(), + factory_departures: Vec::new(), shut_down: HashSet::new(), script_orders: Vec::new(), script_order_counts: BTreeMap::new(), @@ -303,6 +306,19 @@ impl UnitPatrol { self.shut_down.contains(&handle) } + pub(super) fn begin_factory_departure(&mut self, departure: FactoryDeparture, now_ms: u32) { + if self.units.is_empty() && self.factory_departures.is_empty() { + self.clock_ms = now_ms; + } + self.factory_departures.push(departure); + } + + pub(super) fn is_leaving_factory(&self, unit: ObjectHandle) -> bool { + self.factory_departures + .iter() + .any(|departure| departure.handle == unit) + } + pub(super) fn is_moving_to_destination(&self, handle: ObjectHandle) -> bool { self.units .iter() @@ -401,6 +417,7 @@ impl UnitPatrol { Some(Self { center: Some(center), units, + factory_departures: Vec::new(), shut_down: HashSet::new(), script_orders: Vec::new(), script_order_counts: BTreeMap::new(), @@ -435,14 +452,34 @@ impl UnitPatrol { }); let seconds = now_ms.saturating_sub(state.clock_ms) as f32 * 0.001; state.clock_ms = state.clock_ms.max(now_ms); - let mut traffic = if seconds > 0.0 && !state.units.is_empty() { - state.buildings.refresh(world, mission); - FrameTraffic::read(world, mission) - } else { - FrameTraffic::default() - }; + let mut traffic = + if seconds > 0.0 && (!state.units.is_empty() || !state.factory_departures.is_empty()) { + state.buildings.refresh(world, mission); + FrameTraffic::read(world, mission) + } else { + FrameTraffic::default() + }; let mut poses = Vec::new(); + if seconds > 0.0 { + for departure in std::mem::take(&mut state.factory_departures) { + let handle = departure.handle; + let Ok(before) = transform_state(world, handle) else { + continue; + }; + let after = + departure.move_out(before, mission, &mut traffic, &state.buildings, seconds)?; + if after != before { + poses.push((handle, before, after)); + } + if !departure.finished(after) { + state.factory_departures.push(departure); + } + } + } for unit in &mut state.units { + if self.is_leaving_factory(unit.handle) { + continue; + } let Ok(before) = transform_state(world, unit.handle) else { continue; }; diff --git a/crates/fparkan-runtime/src/unit_patrol/orders.rs b/crates/fparkan-runtime/src/unit_patrol/orders.rs index 41f68cf7..f3ab609b 100644 --- a/crates/fparkan-runtime/src/unit_patrol/orders.rs +++ b/crates/fparkan-runtime/src/unit_patrol/orders.rs @@ -110,7 +110,9 @@ impl UnitPatrol { order.opcode() ); } - if append && (self.is_patrolling(actor) || self.is_shut_down(actor)) { + if self.is_leaving_factory(actor) + || (append && (self.is_patrolling(actor) || self.is_shut_down(actor))) + { if let Some((_, queue)) = self .script_orders .iter_mut() @@ -186,7 +188,8 @@ impl UnitPatrol { continue; }; // shortcut: Go still uses the temporary arrival tolerance. - let complete = !self.is_shut_down(actor) + let complete = !self.is_leaving_factory(actor) + && !self.is_shut_down(actor) && self .units .iter() |
