diff options
Diffstat (limited to 'crates')
| -rw-r--r-- | crates/fparkan-runtime/src/autodemo_combat.rs | 8 | ||||
| -rw-r--r-- | crates/fparkan-runtime/src/lib.rs | 33 | ||||
| -rw-r--r-- | crates/fparkan-runtime/src/mission_events.rs | 60 | ||||
| -rw-r--r-- | crates/fparkan-runtime/src/production.rs | 60 | ||||
| -rw-r--r-- | crates/fparkan-runtime/src/unit_patrol.rs | 53 | ||||
| -rw-r--r-- | crates/fparkan-script/src/lib.rs | 129 |
6 files changed, 261 insertions, 82 deletions
diff --git a/crates/fparkan-runtime/src/autodemo_combat.rs b/crates/fparkan-runtime/src/autodemo_combat.rs index 5769b647..ab48f376 100644 --- a/crates/fparkan-runtime/src/autodemo_combat.rs +++ b/crates/fparkan-runtime/src/autodemo_combat.rs @@ -285,6 +285,14 @@ impl AutoDemoCombat { }; let targets = self.targets(&engine.world, &mission.mission_assets); for unit in &mut self.units { + if mission.script_host_mode == super::MissionMode::SingleMission + && !mission + .unit_patrol + .as_ref() + .is_some_and(|patrol| patrol.is_patrolling(unit.handle)) + { + continue; + } let aim = targets .iter() .find(|(handle, target)| *handle == unit.handle && target.in_range) diff --git a/crates/fparkan-runtime/src/lib.rs b/crates/fparkan-runtime/src/lib.rs index c129a535..6780cf0a 100644 --- a/crates/fparkan-runtime/src/lib.rs +++ b/crates/fparkan-runtime/src/lib.rs @@ -2401,15 +2401,31 @@ fn load_mission_with_options( script_varset_state_count: loaded_scripts.varset_states.len(), }; - let unit_patrol = (request.mode == MissionMode::AutoDemo && options.start_autodemo) - .then(|| { - unit_patrol::UnitPatrol::new( + let unit_patrol = if options.start_autodemo { + match request.mode { + MissionMode::AutoDemo => unit_patrol::UnitPatrol::new( &mission, &object_drafts[..reserve_start], &handles[..reserve_start], - ) - }) - .flatten(); + ), + MissionMode::SingleMission => loaded_scripts + .bundles + .iter() + .find(|bundle| bundle.clan_index == 0) + .is_some_and(|bundle| { + bundle.package.events.iter().any(|event| { + event.name_raw.as_slice() == b"Mission\0" + && event.instructions.iter().any(|instruction| { + instruction.dispatch_selector() + == fparkan_script::ScriptDispatchSelector::Handler(15) + }) + }) + }) + .then(unit_patrol::UnitPatrol::scripted), + } + } else { + None + }; let autodemo_combat = unit_patrol.as_ref().map(|_| { autodemo_combat::AutoDemoCombat::new( &vfs, @@ -2583,6 +2599,9 @@ pub fn step_headless( } else { (None, None) }; + if let (Some(combat), Some(unit)) = (&mut engine.autodemo_combat, produced_unit) { + combat.activate(&engine.world, unit.object_index, unit.handle); + } if produced_unit.is_some() || !autodemo_reinforcements.is_empty() || autodemo_combat_events @@ -2660,7 +2679,7 @@ pub fn frame_with_player_motion( /// Coverage entries for the subsystems still absent from the mission loop. pub const SIMULATION_COVERAGE: &str = - "sim_coverage research_startup_gate_stub=1 mission_handlers_stub=1 unit_behavior_stub=1 render_object_lifecycle_stub=1 render_winding_change_stub=1 mission_event_clock_approx=1 mission_tactical_ids_stub=1 mission_clan_roster_stub=1 mission_message_ui_stub=1 factory_orders_approx=1 mine_orders_approx=1"; + "sim_coverage research_startup_gate_stub=1 mission_handlers_stub=1 unit_behavior_stub=1 render_object_lifecycle_stub=1 render_winding_change_stub=1 mission_event_clock_approx=1 mission_tactical_ids_stub=1 mission_clan_roster_stub=1 mission_message_ui_stub=1 factory_orders_approx=1 mine_orders_approx=1 mission_patrol_approx=1"; /// Totals from a headless mission coverage run. #[derive(Clone, Debug, Eq, PartialEq)] diff --git a/crates/fparkan-runtime/src/mission_events.rs b/crates/fparkan-runtime/src/mission_events.rs index 6f434390..3d101c53 100644 --- a/crates/fparkan-runtime/src/mission_events.rs +++ b/crates/fparkan-runtime/src/mission_events.rs @@ -7,7 +7,8 @@ use super::{ use fparkan_msh::{draw_batches, node38_sampled_hierarchy, selected_slot, Group, Lod, NodeId}; use fparkan_render::LegacyIron3dEulerTransform; use fparkan_script::{ - ScriptDispatchSelector, ScriptInstruction, VarSetDefault, VmHostCallbackCommand, + Handler15TargetPayload, ScriptDispatchSelector, ScriptInstruction, VarSetDefault, + VmHostCallbackCommand, }; use fparkan_world::{ handle_by_original_id, identity_metadata, registration_sequence, set_owner, transform_state, @@ -37,6 +38,8 @@ pub struct MissionEventTick { pub stop: Option<MissionEventStop>, /// Notifications produced by this invocation, in script order. pub notices: Vec<MissionNotice>, + /// Newly assigned or changed place patrols in script order. + pub patrol_orders: Vec<(ObjectHandle, [u32; 2])>, } /// A notification emitted by the scenario host. @@ -473,6 +476,7 @@ impl LoadedMissionState { .find(|state| state.clan_index == bundle.clan_index)?; let mission_events = &mut self.mission_events; let mut notices = Vec::new(); + let mut patrol_orders = Vec::new(); let stop = declarations .execute_mission_prefix( event, @@ -517,6 +521,54 @@ impl LoadedMissionState { .find_map(|handle| identity_metadata(world, handle).ok()?.owner_id); Ok(Some(clan.map_or(u32::MAX, |owner| u32::from(owner.0)))) } + ScriptDispatchSelector::Handler(15) => { + let order = declarations + .resolve_handler15_with_values(instruction, values) + .map_err(|error| error.to_string())?; + let (4, 3, Handler15TargetPayload::ByPlace { first, second }) = + (order.word_1, order.word_2, order.target) + else { + return Err(format!( + "Handler(15) order={} insertion={} target={:?}", + order.word_1, order.word_2, order.target + )); + }; + let Some(handle) = + self.mission + .objects + .iter() + .enumerate() + .find_map(|(index, object)| { + let class = self.object_drafts[index].unit_dat_header_flags?; + (class == super::boarding::WARBOT_CLASS + && object.identity_or_clan_raw == order.word_0) + .then(|| { + handle_by_original_id( + world, + OriginalObjectId(index as u32), + ) + }) + .flatten() + }) + else { + // The native handler sets its missing-target status and advances. + return Ok(None); + }; + let Some(patrol) = &mut self.unit_patrol else { + return Err("Handler(15) patrol runtime is unavailable".into()); + }; + // shortcut: default place radius and a routed random point; + // native patrol timing and profile overrides remain open. + let radius = if matches!(order.word_3, 0 | u32::MAX) { + 60.0 + } else { + order.word_3 as f32 + }; + if patrol.order(world, handle, [first as f32, second as f32], radius) { + patrol_orders.push((handle, [first, second])); + } + Ok(None) + } ScriptDispatchSelector::Handler(30) => { let command = declarations .resolve_handler30_with_values(instruction, values) @@ -575,7 +627,11 @@ impl LoadedMissionState { instruction_index, reason, }); - Some(MissionEventTick { stop, notices }) + Some(MissionEventTick { + stop, + notices, + patrol_orders, + }) } } diff --git a/crates/fparkan-runtime/src/production.rs b/crates/fparkan-runtime/src/production.rs index 9416e626..54ccef42 100644 --- a/crates/fparkan-runtime/src/production.rs +++ b/crates/fparkan-runtime/src/production.rs @@ -525,6 +525,12 @@ mod tests { .is_none()); } let factory_position = pose.position; + pose.position = [1288.99_f32, 807.4, 74.08].map(f32::to_bits); + set_transform(&mut engine.world, cockpit.handle, pose).unwrap(); + assert_eq!( + capture_neutral_building(&mut engine, cockpit).unwrap(), + Some(OriginalObjectId(0)) + ); pose.position = [1026.08_f32, 902.706, 81.24426].map(f32::to_bits); set_transform(&mut engine.world, cockpit.handle, pose).unwrap(); crate::deploy_mine(&mut engine, cockpit).unwrap(); @@ -546,10 +552,21 @@ mod tests { pose.position = factory_position; set_transform(&mut engine.world, cockpit.handle, pose).unwrap(); let mut produced = 0; - let mut complete = false; + let mut dispatched_at = None; + let enemy = handle_by_original_id(&engine.world, OriginalObjectId(2)).unwrap(); + let enemy_start = transform_state(&engine.world, enemy).unwrap().position; for now in (30_150..=190_100).step_by(50) { let frame = step_headless(&mut engine, InputSnapshot::default(), now).unwrap(); assert!( + frame + .mission_event + .as_ref() + .and_then(|event| event.stop.as_ref()) + .is_none(), + "{:?}", + frame.mission_event + ); + assert!( frame.production_failure.is_none(), "{:?}", frame.production_failure @@ -563,15 +580,50 @@ mod tests { } } if frame.mission_event.is_some_and(|event| { - event + if event .notices .contains(&crate::MissionNotice::ObjectiveComplete(3)) + { + assert_eq!(event.patrol_orders.len(), 3); + assert_eq!(event.patrol_orders[0].1, [1124, 783]); + assert_eq!(event.patrol_orders[1].1, [606, 993]); + return true; + } + false }) { - complete = true; + dispatched_at = Some(now); break; } } assert_eq!(produced, 4); - assert!(complete, "factory objective must follow the fourth robot"); + let dispatched_at = dispatched_at.expect("factory objective must follow the fourth robot"); + for now in (dispatched_at + 50..=dispatched_at + 5_000).step_by(50) { + step_headless(&mut engine, InputSnapshot::default(), now).unwrap(); + } + assert_ne!( + transform_state(&engine.world, enemy).unwrap().position, + enemy_start + ); + let enemies = + [2, 3, 4].map(|id| handle_by_original_id(&engine.world, OriginalObjectId(id)).unwrap()); + for handle in enemies { + assert_eq!( + crate::apply_projectile_hit(&mut engine, handle, f32::MAX).unwrap(), + Some((0.0, true)) + ); + } + let tick = step_headless(&mut engine, InputSnapshot::default(), dispatched_at + 8_000) + .unwrap() + .mission_event + .unwrap(); + assert!( + tick.notices + .contains(&crate::MissionNotice::ObjectiveComplete(4)), + "{tick:?}" + ); + assert!( + tick.notices.contains(&crate::MissionNotice::Completed), + "{tick:?}" + ); } } diff --git a/crates/fparkan-runtime/src/unit_patrol.rs b/crates/fparkan-runtime/src/unit_patrol.rs index be0d0a35..8f1fcb03 100644 --- a/crates/fparkan-runtime/src/unit_patrol.rs +++ b/crates/fparkan-runtime/src/unit_patrol.rs @@ -8,7 +8,7 @@ use std::collections::VecDeque; #[derive(Clone)] pub(super) struct UnitPatrol { - center: [f32; 2], + center: Option<[f32; 2]>, units: Vec<PatrollingUnit>, clock_ms: u32, rng: u32, @@ -17,6 +17,8 @@ pub(super) struct UnitPatrol { #[derive(Clone)] struct PatrollingUnit { handle: ObjectHandle, + center: [f32; 2], + radius: f32, points: VecDeque<[f32; 2]>, retry_ms: u32, attack: Option<ObjectHandle>, @@ -28,15 +30,53 @@ pub(super) struct PreparedPatrol { } impl UnitPatrol { - pub(super) fn activate(&mut self, world: &World, handle: ObjectHandle) { + pub(super) fn scripted() -> Self { + Self { + center: None, + units: Vec::new(), + clock_ms: 0, + rng: 1, + } + } + + pub(super) fn order( + &mut self, + world: &World, + handle: ObjectHandle, + center: [f32; 2], + radius: f32, + ) -> bool { self.units .retain(|unit| transform_state(world, unit.handle).is_ok()); + if let Some(unit) = self.units.iter_mut().find(|unit| unit.handle == handle) { + if unit.center != center || unit.radius != radius { + unit.center = center; + unit.radius = radius; + unit.points.clear(); + unit.retry_ms = 0; + return true; + } + return false; + } self.units.push(PatrollingUnit { handle, + center, + radius, points: VecDeque::new(), retry_ms: 0, attack: None, }); + true + } + + pub(super) fn is_patrolling(&self, handle: ObjectHandle) -> bool { + self.units.iter().any(|unit| unit.handle == handle) + } + + pub(super) fn activate(&mut self, world: &World, handle: ObjectHandle) { + if let Some(center) = self.center { + self.order(world, handle, center, 150.0); + } } pub(super) fn new( @@ -58,13 +98,15 @@ impl UnitPatrol { }) .map(|(_, &handle)| PatrollingUnit { handle, + center, + radius: 150.0, points: VecDeque::new(), retry_ms: 0, attack: None, }) .collect(); Some(Self { - center, + center: Some(center), units, clock_ms: 0, rng: 1, @@ -116,7 +158,7 @@ impl UnitPatrol { unit.points = if let Some(enemy) = enemy { route_points(terrain, from, enemy.center)?.unwrap_or_default() } else { - choose_route(terrain, from, state.center, &mut state.rng)? + choose_route(terrain, from, unit.center, unit.radius, &mut state.rng)? }; unit.retry_ms = now_ms.saturating_add(1_000); } @@ -175,12 +217,13 @@ fn choose_route( terrain: &TerrainWorld, from: [f32; 3], center: [f32; 2], + radius: f32, rng: &mut u32, ) -> Result<VecDeque<[f32; 2]>, EngineError> { // shortcut: choose one routed patrol point at a time with separate RNG state. for _ in 0..16 { let [x, y] = - center.map(|axis| axis + (next_crt_rand(rng) as f32 / 32767.0 * 2.0 - 1.0) * 150.0); + center.map(|axis| axis + (next_crt_rand(rng) as f32 / 32767.0 * 2.0 - 1.0) * radius); let Some(z) = terrain.height_at([x, y]).map_err(EngineError::Terrain)? else { continue; }; diff --git a/crates/fparkan-script/src/lib.rs b/crates/fparkan-script/src/lib.rs index be7bd9cc..c69b393c 100644 --- a/crates/fparkan-script/src/lib.rs +++ b/crates/fparkan-script/src/lib.rs @@ -1150,28 +1150,61 @@ impl VarSet { &self, instruction: &ScriptInstruction, ) -> Result<Handler15Invocation, Handler15ResolveError> { - let word_0 = self.resolve_handler15_dword(instruction, 0)?; - let word_1 = self.resolve_handler15_dword(instruction, 1)?; - let word_2 = self.resolve_handler15_dword(instruction, 2)?; - let word_3 = self.resolve_handler15_dword(instruction, 3)?; - let scalar_4 = self.resolve_handler15_float(instruction, 4)?; - let scalar_5 = self.resolve_handler15_float(instruction, 5)?; - let scalar_6 = self.resolve_handler15_float(instruction, 6)?; - let scalar_7 = self.resolve_handler15_float(instruction, 7)?; - let target = match self.resolve_handler15_dword(instruction, 8)? { + self.resolve_handler15_with(instruction, None) + } + + /// Resolves an order against live script cells, including prior assignments. + /// + /// # Errors + /// + /// Returns an error for missing or mistyped operands or an unknown target mode. + pub fn resolve_handler15_with_values( + &self, + instruction: &ScriptInstruction, + values: &[VarSetDefault], + ) -> Result<Handler15Invocation, Handler15ResolveError> { + self.resolve_handler15_with(instruction, Some(values)) + } + + fn resolve_handler15_with( + &self, + instruction: &ScriptInstruction, + values: Option<&[VarSetDefault]>, + ) -> Result<Handler15Invocation, Handler15ResolveError> { + let dword = |pos| match self.handler15_value(instruction, values, pos)? { + VarSetDefault::Dword(value) => Ok(value), + VarSetDefault::FloatBits(_) => Err(Handler15ResolveError::UnexpectedType { + position: pos, + expected: VarSetType::Dword, + found: VarSetType::Float, + }), + }; + let scalar = |pos| match self.handler15_value(instruction, values, pos)? { + VarSetDefault::FloatBits(bits) => Ok(f32::from_bits(bits)), + VarSetDefault::Dword(_) => Err(Handler15ResolveError::UnexpectedType { + position: pos, + expected: VarSetType::Float, + found: VarSetType::Dword, + }), + }; + let word_0 = dword(0)?; + let word_1 = dword(1)?; + let word_2 = dword(2)?; + let word_3 = dword(3)?; + let scalar_4 = scalar(4)?; + let scalar_5 = scalar(5)?; + let scalar_6 = scalar(6)?; + let scalar_7 = scalar(7)?; + let target = match dword(8)? { 0 => Handler15TargetPayload::None, - 0x0201 => { - Handler15TargetPayload::ByLogicId(self.resolve_handler15_dword(instruction, 9)?) - } + 0x0201 => Handler15TargetPayload::ByLogicId(dword(9)?), 0x0202 => Handler15TargetPayload::ByPlace { - first: self.resolve_handler15_dword(instruction, 9)?, - second: self.resolve_handler15_dword(instruction, 10)?, + first: dword(9)?, + second: dword(10)?, }, - 0x0203 => Handler15TargetPayload::ByType(self.resolve_handler15_dword(instruction, 9)?), - 0x0204 => { - Handler15TargetPayload::NotDefined(self.resolve_handler15_dword(instruction, 9)?) - } - 0x0205 => Handler15TargetPayload::ByName(self.resolve_handler15_dword(instruction, 9)?), + 0x0203 => Handler15TargetPayload::ByType(dword(9)?), + 0x0204 => Handler15TargetPayload::NotDefined(dword(9)?), + 0x0205 => Handler15TargetPayload::ByName(dword(9)?), mode => return Err(Handler15ResolveError::UnsupportedTargetMode(mode)), }; Ok(Handler15Invocation { @@ -1187,59 +1220,27 @@ impl VarSet { }) } - fn resolve_handler15_dword( + fn handler15_value( &self, instruction: &ScriptInstruction, + values: Option<&[VarSetDefault]>, position: usize, - ) -> Result<u32, Handler15ResolveError> { - match self.resolve_handler15_declaration(instruction, position)? { - VarSetDeclaration { - type_name: VarSetType::Dword, - default_value: VarSetDefault::Dword(value), - .. - } => Ok(*value), - declaration => Err(Handler15ResolveError::UnexpectedType { - position, - expected: VarSetType::Dword, - found: declaration.type_name, - }), - } - } - - fn resolve_handler15_float( - &self, - instruction: &ScriptInstruction, - position: usize, - ) -> Result<f32, Handler15ResolveError> { - match self.resolve_handler15_declaration(instruction, position)? { - VarSetDeclaration { - type_name: VarSetType::Float, - default_value: VarSetDefault::FloatBits(bits), - .. - } => Ok(f32::from_bits(*bits)), - declaration => Err(Handler15ResolveError::UnexpectedType { - position, - expected: VarSetType::Float, - found: declaration.type_name, - }), - } - } - - fn resolve_handler15_declaration( - &self, - instruction: &ScriptInstruction, - position: usize, - ) -> Result<&VarSetDeclaration, Handler15ResolveError> { + ) -> Result<VarSetDefault, Handler15ResolveError> { let index = *instruction .references .get(position) .ok_or(Handler15ResolveError::MissingReference { position })?; - self.declarations + let missing = Handler15ResolveError::VarSetIndexOutOfBounds { + index, + declarations: self.declarations.len(), + }; + let declaration = self + .declarations .get(index as usize) - .ok_or(Handler15ResolveError::VarSetIndexOutOfBounds { - index, - declarations: self.declarations.len(), - }) + .ok_or(missing.clone())?; + values.map_or(Ok(declaration.default_value), |cells| { + cells.get(index as usize).copied().ok_or(missing) + }) } } |
