diff options
Diffstat (limited to 'crates/fparkan-runtime')
| -rw-r--r-- | crates/fparkan-runtime/src/clan_ai_events.rs | 52 | ||||
| -rw-r--r-- | crates/fparkan-runtime/src/clan_problem_conditions.rs | 13 | ||||
| -rw-r--r-- | crates/fparkan-runtime/src/lib.rs | 6 | ||||
| -rw-r--r-- | crates/fparkan-runtime/src/mission_events.rs | 60 | ||||
| -rw-r--r-- | crates/fparkan-runtime/src/ore_transport.rs | 182 | ||||
| -rw-r--r-- | crates/fparkan-runtime/src/production.rs | 60 | ||||
| -rw-r--r-- | crates/fparkan-runtime/src/unit_patrol.rs | 5 |
7 files changed, 364 insertions, 14 deletions
diff --git a/crates/fparkan-runtime/src/clan_ai_events.rs b/crates/fparkan-runtime/src/clan_ai_events.rs index 03ac552c..676db9cf 100644 --- a/crates/fparkan-runtime/src/clan_ai_events.rs +++ b/crates/fparkan-runtime/src/clan_ai_events.rs @@ -103,6 +103,14 @@ pub(super) fn tick(engine: &mut crate::Engine, now_ms: u32) { !group.members.is_empty() }); let ai = &mut loaded.clan_ai_events; + ai.transports.retain_mut(|(_, transport)| { + transport.tick( + &engine.world, + &mut loaded.behavior_ore_states, + &mut loaded.unit_patrol, + now_ms, + ) + }); ai.waits.retain(|&(clan, key), conditions| { let group = ai.groups.get(&(clan, key)); let lost_building = key.word_0 == BUILDING_PROTECT @@ -121,6 +129,7 @@ pub(super) fn tick(engine: &mut crate::Engine, now_ms: u32) { OwnerId(clan as u16), loaded.unit_patrol.as_ref(), group, + |unit| ai.transports.iter().any(|(job, task)| *job == (clan, key) && task.unit == unit), ) }); if ready { @@ -214,6 +223,11 @@ pub(super) struct ClanAiEvents { base_radius_limits: BTreeMap<usize, f32>, capturer_queries: BTreeMap<usize, u64>, capture_orders: Vec<(OwnerId, Handler2RecordKey, CaptureApproach)>, + transports: Vec<( + (usize, Handler2RecordKey), + crate::ore_transport::OreTransport, + )>, + transport_orders: BTreeMap<(usize, u32), u64>, capture_approaches: BTreeMap<(u32, u32), u64>, groups: BTreeMap<(usize, Handler2RecordKey), CombatGroup>, waits: BTreeMap<(usize, Handler2RecordKey), Vec<Condition>>, @@ -523,6 +537,25 @@ impl LoadedMissionState { .declarations .resolve_handler15_with_values(instruction, values) .map_err(|error| error.to_string())?; + if let (6, 3, Handler15TargetPayload::NotDefined(_), Some(problem)) = + (order.word_1, order.word_2, order.target, problem.as_ref()) + { + let owner = OwnerId(clan as u16); + let Some(unit) = assignment.filter(|&unit| self.mission_events + .logic_objects(&self.mission, world, order.word_0) + .any(|handle| handle == unit)) else { + return Err("Handler(15) transport requires the assigned unit".into()); + }; + if problem.key.word_0 != OPTIMAL_TRANSPORT + || !self.behavior_ore_states.iter().any(|ore| ore.handle == unit && ore.class_flags == TRANSPORT_CLASS) + { + return Err("Handler(15) transport requires an ore transport".into()); + } + self.clan_ai_events.transports.push(((clan, problem.key), crate::ore_transport::OreTransport::new(unit, owner, now_ms))); + *self.clan_ai_events.transport_orders.entry((clan, unit.slot)).or_default() += 1; + eprintln!("sim_coverage script_ore_transport_approx=1 clan={clan} unit={} id={} queue_time_ms={now_ms}", unit.slot, order.word_0); + return Ok(Some(VarSetDefault::Dword(1))); + } if let (0x11, 3, Handler15TargetPayload::ByLogicId(target_id)) = (order.word_1, order.word_2, order.target) { @@ -623,7 +656,7 @@ impl LoadedMissionState { .into(), ); } - assignment = crate::mission_events::placed_logic_objects( + assignment = self.mission_events.logic_objects( &self.mission, world, id, @@ -689,6 +722,12 @@ impl LoadedMissionState { }; let key = problem.as_ref().expect("condition requires a problem").key; let condition = match (action, mode) { + (2, 0) if key.word_0 == OPTIMAL_TRANSPORT && solving => { + let unit = assignment.filter(|&unit| self.mission_events + .logic_objects(&self.mission, world, id).any(|handle| handle == unit)) + .ok_or("Handler(27) transport wait requires the assigned unit")?; + Some(Condition::TransportInactive(unit)) + } (1 | 3, 0) if matches!(key.word_0, 7 | 9) || (action == 1 && key.word_0 == BUILDING_PROTECT) => { let target = crate::mission_events::placed_logic_objects( &self.mission, world, id @@ -760,11 +799,6 @@ impl LoadedMissionState { let id = self.mission_events.first_available_placed_unit( &self.mission, world, clan, class, ); - if class == TRANSPORT_CLASS && id.is_none() - && self.mission_events.count_clan_class(world, OwnerId(clan as u16), class) != 0 - { - return Err("Handler(14) needs a runtime logic ID for the produced transport".into()); - } Ok(Some(VarSetDefault::Dword(id.unwrap_or(u32::MAX)))) } ScriptDispatchSelector::Handler(29) => { @@ -1155,6 +1189,12 @@ impl ClanAiEvents { .map(|(&(clan, target), &count)| (clan, target, count)) } + pub(super) fn transport_orders(&self) -> impl Iterator<Item = (usize, u32, u64)> + '_ { + self.transport_orders + .iter() + .map(|(&(clan, unit), &count)| (clan, unit, count)) + } + pub(super) fn set_base_radius(&mut self, clan: usize, limit: f32) { if limit.is_finite() && limit > 0.0 { self.base_radius_limits.insert(clan, limit); diff --git a/crates/fparkan-runtime/src/clan_problem_conditions.rs b/crates/fparkan-runtime/src/clan_problem_conditions.rs index bace9ec6..00d39173 100644 --- a/crates/fparkan-runtime/src/clan_problem_conditions.rs +++ b/crates/fparkan-runtime/src/clan_problem_conditions.rs @@ -8,6 +8,7 @@ pub(super) enum Condition { BuildingCaptured(ObjectHandle), GroupDestroyed, GroupIdle, + TransportInactive(ObjectHandle), } impl Condition { @@ -17,6 +18,7 @@ impl Condition { clan: OwnerId, patrol: Option<&UnitPatrol>, group: Option<&CombatGroup>, + transport_active: impl Fn(ObjectHandle) -> bool, ) -> bool { let live = |unit| registration_sequence(world, unit).is_ok_and(|sequence| sequence.is_some()); @@ -30,6 +32,7 @@ impl Condition { Self::GroupDestroyed => { group.is_none_or(|group| group.members.iter().all(|&unit| !live(unit))) } + Self::TransportInactive(unit) => !live(unit) || !transport_active(unit), Self::GroupIdle => group.is_none_or(|group| { group.members.iter().all(|&unit| { !live(unit) || patrol.is_none_or(|patrol| !patrol.is_patrolling(unit)) @@ -53,13 +56,13 @@ mod tests { register_object(&mut world, target).unwrap(); let clan = OwnerId(1); set_owner(&mut world, target, Some(OwnerId(0))).unwrap(); - assert!(!Condition::BuildingCaptured(target).met(&world, clan, None, None)); - assert!(!Condition::ObjectDestroyed(Some(target)).met(&world, clan, None, None)); + assert!(!Condition::BuildingCaptured(target).met(&world, clan, None, None, |_| false)); + assert!(!Condition::ObjectDestroyed(Some(target)).met(&world, clan, None, None, |_| false)); set_owner(&mut world, target, Some(clan)).unwrap(); - assert!(Condition::BuildingCaptured(target).met(&world, clan, None, None)); + assert!(Condition::BuildingCaptured(target).met(&world, clan, None, None, |_| false)); fparkan_world::request_delete(&mut world, target).unwrap(); fparkan_world::step(&mut world, &fparkan_world::InputSnapshot).unwrap(); - assert!(Condition::ObjectDestroyed(Some(target)).met(&world, clan, None, None)); - assert!(!Condition::BuildingCaptured(target).met(&world, clan, None, None)); + assert!(Condition::ObjectDestroyed(Some(target)).met(&world, clan, None, None, |_| false)); + assert!(!Condition::BuildingCaptured(target).met(&world, clan, None, None, |_| false)); } } diff --git a/crates/fparkan-runtime/src/lib.rs b/crates/fparkan-runtime/src/lib.rs index d93a5e5a..9dba33cb 100644 --- a/crates/fparkan-runtime/src/lib.rs +++ b/crates/fparkan-runtime/src/lib.rs @@ -54,6 +54,7 @@ mod clan_transport_schemes; mod mesh_collision; mod mining; mod mission_events; +mod ore_transport; mod player_motion; mod player_status; mod player_weapon; @@ -2951,6 +2952,7 @@ pub struct SimulationReport { pub script_group_orders: Vec<(usize, u32, u64)>, pub script_problem_waits: Vec<(usize, u32, u64)>, pub script_factory_patrol_continues: Vec<(usize, u32, u64)>, + pub script_ore_transport_orders: Vec<(usize, u32, u64)>, pub script_capturer_queries: Vec<(usize, u64)>, pub script_capture_approaches: Vec<(u32, u32, u64)>, /// First factory completion by clan, in milliseconds. @@ -3002,6 +3004,7 @@ pub fn simulate_mission_report( script_group_orders: Vec::new(), script_problem_waits: Vec::new(), script_factory_patrol_continues: Vec::new(), + script_ore_transport_orders: Vec::new(), script_capturer_queries: Vec::new(), script_capture_approaches: Vec::new(), first_factory_completion_ms: Default::default(), @@ -3105,6 +3108,9 @@ pub fn simulate_mission_report( .script_factory_patrol_continues .extend(loaded.clan_ai_events.patrol_continues()); report + .script_ore_transport_orders + .extend(loaded.clan_ai_events.transport_orders()); + report .script_capturer_queries .extend(loaded.clan_ai_events.capturer_queries()); report diff --git a/crates/fparkan-runtime/src/mission_events.rs b/crates/fparkan-runtime/src/mission_events.rs index c19c53f8..67aea865 100644 --- a/crates/fparkan-runtime/src/mission_events.rs +++ b/crates/fparkan-runtime/src/mission_events.rs @@ -13,7 +13,7 @@ use fparkan_world::{ handle_by_original_id, identity_metadata, registration_sequence, set_owner, transform_state, ObjectHandle, OriginalObjectId, OwnerId, World, }; -use std::collections::HashSet; +use std::collections::{HashMap, HashSet}; const MOBILE_HQ_CLASS: u32 = 0x0101_0000; const MAIN_TELEPORT_CLASS: u32 = 0x8000_0200; @@ -148,6 +148,8 @@ pub(super) struct MissionEvents { voiced_messages: HashSet<u32>, reserved_units: HashSet<(usize, ObjectHandle)>, placed_clan_objects: Vec<(ObjectHandle, u32)>, + issued_logic_ids: HashMap<ObjectHandle, u32>, + next_logic_id: u32, objectives: MissionObjectives, } @@ -198,11 +200,63 @@ impl MissionEvents { if identity.owner_id != Some(OwnerId(clan as u16)) { return None; } - let object = mission.objects.get(identity.original_id?.0 as usize)?; - Some(object.identity_or_clan_raw) + self.issued_logic_ids.get(&handle).copied().or_else(|| { + mission + .objects + .get(identity.original_id?.0 as usize) + .map(|object| object.identity_or_clan_raw) + }) }) } + pub(super) fn logic_objects<'a>( + &'a self, + mission: &'a super::MissionDocument, + world: &'a World, + id: u32, + ) -> impl Iterator<Item = ObjectHandle> + 'a { + placed_logic_objects(mission, world, id).chain(self.issued_logic_ids.iter().filter_map( + move |(&handle, &issued)| { + (issued == id + && registration_sequence(world, handle) + .ok() + .flatten() + .is_some()) + .then_some(handle) + }, + )) + } + + pub(super) fn issue_logic_id( + &mut self, + mission: &super::MissionDocument, + world: &World, + handle: ObjectHandle, + ) -> u32 { + self.issued_logic_ids + .retain(|&unit, _| registration_sequence(world, unit).ok().flatten().is_some()); + if let Some(&id) = self.issued_logic_ids.get(&handle) { + return id; + } + // shortcut: allocate an internal script ID until native registration numbers are recovered. + loop { + self.next_logic_id = self.next_logic_id.wrapping_add(1) & 0x7fff_ffff; + if self.next_logic_id != 0 + && !mission + .objects + .iter() + .any(|object| object.identity_or_clan_raw == self.next_logic_id) + && !self + .issued_logic_ids + .values() + .any(|&id| id == self.next_logic_id) + { + self.issued_logic_ids.insert(handle, self.next_logic_id); + return self.next_logic_id; + } + } + } + pub(super) fn set_reservation( &mut self, mission: &super::MissionDocument, diff --git a/crates/fparkan-runtime/src/ore_transport.rs b/crates/fparkan-runtime/src/ore_transport.rs new file mode 100644 index 00000000..0d88cace --- /dev/null +++ b/crates/fparkan-runtime/src/ore_transport.rs @@ -0,0 +1,182 @@ +use crate::unit_patrol::UnitPatrol; +use crate::BehaviorOreState; +use fparkan_world::{ + identity_metadata, registration_sequence, transform_state, ObjectHandle, OwnerId, World, +}; + +pub(super) struct OreTransport { + pub(super) unit: ObjectHandle, + owner: OwnerId, + destination: Option<ObjectHandle>, + unloading: bool, + last_ms: u32, +} + +impl OreTransport { + pub(super) fn new(unit: ObjectHandle, owner: OwnerId, now_ms: u32) -> Self { + Self { + unit, + owner, + destination: None, + unloading: false, + last_ms: now_ms, + } + } + + pub(super) fn tick( + &mut self, + world: &World, + ores: &mut [BehaviorOreState], + patrol: &mut Option<UnitPatrol>, + now_ms: u32, + ) -> bool { + let owned = |unit| { + registration_sequence(world, unit).ok().flatten().is_some() + && identity_metadata(world, unit).is_ok_and(|id| id.owner_id == Some(self.owner)) + }; + let moving = patrol + .as_ref() + .is_some_and(|patrol| patrol.is_moving_to_destination(self.unit)); + if !owned(self.unit) + || patrol + .as_ref() + .is_some_and(|patrol| patrol.is_shut_down(self.unit)) + { + if moving { + patrol.as_mut().unwrap().clear_move(self.unit); + } + return false; + } + let elapsed = now_ms.wrapping_sub(self.last_ms); + self.last_ms = now_ms; + let Some(cargo) = ores.iter().position(|ore| ore.handle == self.unit) else { + return false; + }; + let Ok(pose) = transform_state(world, self.unit) else { + return false; + }; + let [x, y, z] = pose.position.map(f32::from_bits); + let current = f32::from_bits(ores[cargo].current_ore_bits); + let capacity = f32::from_bits(ores[cargo].maximum_ore_bits); + if !capacity.is_finite() || capacity <= 0.0 || !current.is_finite() { + return false; + } + let class = if self.unloading { + 0x8000_0008 + } else { + crate::mining::MINE_CLASS + }; + let endpoints = ores.iter().enumerate().filter_map(|(index, ore)| { + if ore.class_flags != class || !owned(ore.handle) { + return None; + } + let amount = f32::from_bits(ore.current_ore_bits); + if !amount.is_finite() + || (self.unloading && amount >= f32::from_bits(ore.maximum_ore_bits)) + { + return None; + } + let pose = transform_state(world, ore.handle).ok()?; + let [a, b, c] = pose.position.map(f32::from_bits); + let distance = ((x - a).hypot(y - b)).hypot(z - c); + distance + .is_finite() + .then_some((index, ore.handle, [a, b], distance)) + }); + let target = endpoints.min_by(|a, b| { + (self.destination != Some(a.1)) + .cmp(&(self.destination != Some(b.1))) + .then_with(|| a.3.total_cmp(&b.3)) + }); + let Some((index, handle, center, _)) = target else { + if moving { + patrol.as_mut().unwrap().clear_move(self.unit); + } + self.destination = None; + if !self.unloading && current > 0.0 { + self.unloading = true; + } + return true; + }; + let distance = (x - center[0]).hypot(y - center[1]); + // shortcut: use exterior approach points until native dock and port movement are wired. + if distance > 48.0 { + if self.destination != Some(handle) || !moving { + let offset = 40.0 / distance; + let approach = [ + center[0] + (x - center[0]) * offset, + center[1] + (y - center[1]) * offset, + ]; + patrol + .get_or_insert_with(UnitPatrol::scripted) + .move_to(world, self.unit, approach, false); + if self.destination != Some(handle) { + eprintln!( + "script_ore_transport_route clan={} unit={} target={} unloading={} queue_time_ms={now_ms}", + self.owner.0, self.unit.slot, handle.slot, self.unloading, + ); + } + self.destination = Some(handle); + } + return true; + } + if moving { + patrol.as_mut().unwrap().clear_move(self.unit); + } + self.destination = Some(handle); + let (source, sink) = if self.unloading { + (cargo, index) + } else { + (index, cargo) + }; + // shortcut: use the cargo capacity per four seconds until the live transport rate is wired. + let limit = capacity * 0.25 * elapsed as f32 * 0.001; + let clamped = transfer(ores, source, sink, limit); + if clamped && (self.unloading || f32::from_bits(ores[cargo].current_ore_bits) > 0.0) { + if self.unloading { + eprintln!("script_ore_transport_unloaded clan={} unit={} storage={} queue_time_ms={now_ms}", + self.owner.0, self.unit.slot, handle.slot); + } + self.unloading = !self.unloading; + self.destination = None; + } + true + } +} + +fn transfer(ores: &mut [BehaviorOreState], source: usize, sink: usize, limit: f32) -> bool { + let from = f32::from_bits(ores[source].current_ore_bits); + let to = f32::from_bits(ores[sink].current_ore_bits); + let space = f32::from_bits(ores[sink].maximum_ore_bits) - to; + let amount = limit.min(from).min(space).max(0.0); + ores[source].current_ore_bits = (from - amount).to_bits(); + ores[sink].current_ore_bits = (to + amount).to_bits(); + limit >= from.min(space) +} + +#[cfg(test)] +mod tests { + use super::*; + use fparkan_world::OriginalObjectId; + + #[test] + fn transfer_limits_the_batch_to_storage_room_and_preserves_ore() { + let mut ores = + [(100.0_f32, 250.0_f32), (80.0, 100.0)].map(|(current, capacity)| BehaviorOreState { + original_id: OriginalObjectId(0), + handle: ObjectHandle { + slot: 0, + generation: 0, + }, + class_flags: 0, + current_ore_bits: current.to_bits(), + maximum_ore_bits: capacity.to_bits(), + }); + assert!(!transfer(&mut ores, 0, 1, 12.0)); + assert!(transfer(&mut ores, 0, 1, 12.0)); + assert_eq!( + ores.map(|ore| f32::from_bits(ore.current_ore_bits)), + [80.0, 100.0] + ); + } +} diff --git a/crates/fparkan-runtime/src/production.rs b/crates/fparkan-runtime/src/production.rs index 8781febd..6bc3e306 100644 --- a/crates/fparkan-runtime/src/production.rs +++ b/crates/fparkan-runtime/src/production.rs @@ -276,6 +276,26 @@ impl Production { position, self.controls[order.slot - self.reserve_start].clone(), )?; + let draft = &mission.object_drafts[order.slot]; + if draft.unit_dat_header_flags == Some(crate::clan_transport_schemes::TRANSPORT_CLASS) { + let id = draft + .original_id + .expect("prepared factory object has an ID"); + mission + .mission_events + .issue_logic_id(&mission.mission, world, handle); + mission + .behavior_ore_states + .retain(|ore| ore.original_id != id); + mission + .behavior_ore_states + .push(crate::initialize_behavior_ore_state( + id, + handle, + crate::clan_transport_schemes::TRANSPORT_CLASS, + &draft.properties, + )); + } if order.paid.is_none() { let (_, count) = self .plants @@ -810,6 +830,46 @@ mod tests { && (cargo_slots..cargo_slots + RESERVE_SLOTS).contains(&index)), "{completed:?}" ); + let transport = completed + .iter() + .find_map(|&(clan, index)| { + (clan == 1 && (cargo_slots..cargo_slots + RESERVE_SLOTS).contains(&index)) + .then_some(index) + }) + .unwrap(); + let draft = &engine.loaded.as_ref().unwrap().object_drafts[transport]; + let id = draft.original_id.unwrap(); + let handle = handle_by_original_id(&engine.world, id).unwrap(); + let storage = engine + .loaded + .as_ref() + .unwrap() + .behavior_ore_states + .iter() + .find(|ore| { + ore.class_flags == 0x8000_0008 + && identity_metadata(&engine.world, ore.handle) + .unwrap() + .owner_id + == Some(OwnerId(1)) + }) + .unwrap(); + let storage_handle = storage.handle; + let initial_stock = f32::from_bits(storage.current_ore_bits); + for time in ((40_000 + duration + 2016)..=175_000).step_by(200) { + step_headless(&mut engine, InputSnapshot::default(), time).unwrap(); + let loaded = engine.loaded.as_ref().unwrap(); + if loaded.behavior_ore_states.iter().any(|ore| { + ore.handle == storage_handle && f32::from_bits(ore.current_ore_bits) > initial_stock + }) { + assert!(loaded + .clan_ai_events + .transport_orders() + .any(|(clan, unit, _)| clan == 1 && unit == handle.slot)); + return; + } + } + panic!("transport should unload ore into the enemy storage"); } #[test] diff --git a/crates/fparkan-runtime/src/unit_patrol.rs b/crates/fparkan-runtime/src/unit_patrol.rs index bc2dc3a4..149f466b 100644 --- a/crates/fparkan-runtime/src/unit_patrol.rs +++ b/crates/fparkan-runtime/src/unit_patrol.rs @@ -269,6 +269,11 @@ impl UnitPatrol { .any(|unit| unit.handle == handle && unit.destinations.is_some()) } + pub(super) fn clear_move(&mut self, handle: ObjectHandle) { + self.units + .retain(|unit| unit.handle != handle || unit.destinations.is_none()); + } + pub(super) fn raid_factory(&self, handle: ObjectHandle) -> Option<(ObjectHandle, usize)> { self.units .iter() |
