From 071ec6a8619c9dfd37582c56dd97108aae3e6c6e Mon Sep 17 00:00:00 2001 From: Valentin Popov Date: Sat, 14 Nov 2026 20:33:41 +0400 Subject: feat(ai): honor scenario warbot shutdown orders Behavior.dll task dispatch selects ShutDown for order 0x13. Stop autonomous motion and fire until a new supported order is assigned. The field-camp clan now completes Init and all three placed warbots receive the shutdown order. --- crates/fparkan-runtime/src/autodemo_combat.rs | 423 ------------------------ crates/fparkan-runtime/src/clan_script_init.rs | 24 +- crates/fparkan-runtime/src/lib.rs | 69 ++-- crates/fparkan-runtime/src/mission_events.rs | 7 +- crates/fparkan-runtime/src/script_patrol.rs | 33 +- crates/fparkan-runtime/src/unit_combat.rs | 426 +++++++++++++++++++++++++ crates/fparkan-runtime/src/unit_patrol.rs | 43 ++- 7 files changed, 550 insertions(+), 475 deletions(-) delete mode 100644 crates/fparkan-runtime/src/autodemo_combat.rs create mode 100644 crates/fparkan-runtime/src/unit_combat.rs (limited to 'crates/fparkan-runtime') diff --git a/crates/fparkan-runtime/src/autodemo_combat.rs b/crates/fparkan-runtime/src/autodemo_combat.rs deleted file mode 100644 index fea7a8ab..00000000 --- a/crates/fparkan-runtime/src/autodemo_combat.rs +++ /dev/null @@ -1,423 +0,0 @@ -use super::{ - apply_projectile_contact, - autodemo::MOBILE_UNIT, - player_weapon::prepare_unit_weapons, - projectile::{load_projectile, segment_sphere_fraction, unit_sphere}, - projectile_terrain_hit, projectile_unit_hit, - unit_patrol::UnitPatrol, - Engine, MissionAssets, MissionDocument, MissionObjectDraft, ObjectHandle, PlayerProjectile, - PlayerWeapons, -}; -use fparkan_vfs::Vfs; -use fparkan_world::{identity_metadata, transform_state}; -use std::sync::Arc; - -// Behavior's default Patrol_Attack_Range and Attack_MaxFireDistance. -const ATTACK_RANGE: f32 = 400.0; -const FIRE_RANGE: f32 = 200.0; - -/// An autonomous projectile type, in render-pool order. -pub struct AutoDemoProjectileType { - /// Prototype archive. - pub archive: String, - /// Prototype name. - pub name: String, - /// Maximum concurrent flights for the prepared weapons. - pub capacity: u32, - speed: f32, - lifetime_ms: u32, - volume: Option, -} - -/// One autonomous combat event on the mission clock. -#[derive(Clone, Copy, Debug, Eq, PartialEq)] -pub enum AutoDemoCombatEvent { - /// A weapon released a projectile. - Shot { - /// Owner of the weapon. - shooter: ObjectHandle, - /// Object the weapon was aimed at. - target: ObjectHandle, - /// Projectile type in render-pool order. - projectile: usize, - }, - /// A projectile exhausted a unit's health. - Destroyed { - /// Owner of the weapon. - shooter: ObjectHandle, - /// Unit removed from the world. - target: ObjectHandle, - }, - /// An autonomous shot changed a building part's health. - BuildingHit { - /// Owner of the weapon. - shooter: ObjectHandle, - /// Building struck by the projectile. - target: ObjectHandle, - /// Provider row associated with the struck part. - node: u32, - /// Remaining health of the part as raw f32 bits. - remaining_bits: u32, - }, -} - -pub(super) struct AutoDemoCombat { - units: Vec, - reserve: Vec, - hostile: Vec>, - guard_clans: Vec, - projectiles: Vec, - flights: Vec, - pub(super) unavailable: usize, -} - -#[derive(Clone, Copy)] -pub(super) struct CombatTarget { - pub(super) handle: ObjectHandle, - pub(super) center: [f32; 3], - radius: f32, - pub(super) in_range: bool, -} - -#[derive(Clone)] -struct Unit { - handle: ObjectHandle, - index: usize, - weapons: PlayerWeapons, - slots: Vec>, -} - -struct Flight { - shooter: ObjectHandle, - projectile: usize, - pose: PlayerProjectile, -} - -impl AutoDemoCombat { - pub(super) fn new( - vfs: &Arc, - mission: &MissionDocument, - drafts: &[MissionObjectDraft], - handles: &[ObjectHandle], - assets: &MissionAssets, - reserve_start: usize, - guard_clans: Vec, - ) -> Self { - let hostile = mission - .clans - .iter() - .map(|clan| { - mission - .clans - .iter() - .map(|other| { - clan.relations.iter().any(|relation| { - relation.relation_value == 0 - && relation.other_clan_name.raw == other.name.raw - }) - }) - .collect() - }) - .collect(); - let mut battle = Self { - units: Vec::new(), - reserve: Vec::new(), - hostile, - guard_clans, - projectiles: Vec::new(), - flights: Vec::new(), - unavailable: 0, - }; - for (index, (draft, &handle)) in drafts.iter().zip(handles).enumerate() { - if !draft - .unit_dat_header_flags - .is_some_and(|class| class & MOBILE_UNIT != 0) - { - continue; - } - let weapons = prepare_unit_weapons( - assets - .object_component_controls - .get(index) - .map_or(&[], Vec::as_slice), - ); - let slots = weapons - .weapons() - .iter() - .map(|weapon| { - let archive = &weapon.projectile_archive; - let name = &weapon.projectile; - let slot = battle - .projectiles - .iter() - .position(|entry| { - entry.archive.eq_ignore_ascii_case(archive) - && entry.name.eq_ignore_ascii_case(name) - }) - .or_else(|| { - let Ok(data) = load_projectile(vfs, archive, name) else { - battle.unavailable += 1; - return None; - }; - battle.projectiles.push(AutoDemoProjectileType { - archive: archive.clone(), - name: name.clone(), - capacity: 0, - speed: data.speed, - lifetime_ms: data.lifetime_ms, - volume: data.volume, - }); - Some(battle.projectiles.len() - 1) - })?; - let entry = &mut battle.projectiles[slot]; - entry.capacity = entry - .capacity - .saturating_add(entry.lifetime_ms.div_ceil(weapon.interval_ms())); - Some(slot) - }) - .collect(); - battle.unavailable += usize::from(weapons.weapons().is_empty()); - let units = if index < reserve_start { - &mut battle.units - } else { - &mut battle.reserve - }; - units.push(Unit { - handle, - index, - weapons, - slots, - }); - } - battle - } - - pub(super) fn activate( - &mut self, - world: &fparkan_world::World, - index: usize, - handle: ObjectHandle, - ) { - self.units - .retain(|unit| transform_state(world, unit.handle).is_ok()); - if let Some(template) = self.reserve.iter().find(|unit| unit.index == index) { - self.units.push(Unit { - handle, - ..template.clone() - }); - } - } - - pub(super) fn types(&self) -> &[AutoDemoProjectileType] { - &self.projectiles - } - - pub(super) fn guard_clan_count(&self) -> usize { - self.guard_clans.iter().filter(|&&enabled| enabled).count() - } - - pub(super) fn flights(&self) -> impl Iterator + '_ { - self.flights - .iter() - .map(|flight| (flight.projectile, flight.pose)) - } - - pub(super) fn targets( - &self, - world: &fparkan_world::World, - assets: &MissionAssets, - patrol: Option<&UnitPatrol>, - ) -> Vec<(ObjectHandle, CombatTarget)> { - let live: Vec<_> = self - .units - .iter() - .filter_map(|unit| { - let owner = identity_metadata(world, unit.handle).ok()?.owner_id?; - let state = transform_state(world, unit.handle).ok()?; - let (center, radius) = unit_sphere(assets, unit.index, state)?; - Some(( - unit.handle, - usize::from(owner.0), - center, - radius, - state.position.map(f32::from_bits), - )) - }) - .collect(); - live.iter() - .filter_map(|&(handle, clan, from, _, position)| { - let limit = patrol.and_then(|patrol| patrol.attack_limit(handle)); - if limit.is_some_and(|limit| !limit.allows_attack(position)) { - return None; - } - let (enemy, center, radius, distance) = live - .iter() - .filter_map(|&(enemy, other, to, radius, target_position)| { - let distance = (to[0] - from[0]).hypot(to[1] - from[1]); - (enemy != handle - && distance <= ATTACK_RANGE - && limit - .is_none_or(|limit| limit.allows_target(enemy, target_position)) - && self.hostile.get(clan)?.get(other) == Some(&true)) - .then_some((enemy, to, radius, distance)) - }) - .min_by(|a, b| a.3.total_cmp(&b.3))?; - Some(( - handle, - CombatTarget { - handle: enemy, - center, - radius, - in_range: distance <= FIRE_RANGE, - }, - )) - }) - .collect() - } - - pub(super) fn tick( - &mut self, - engine: &mut Engine, - now: u32, - ) -> (Vec, usize) { - let mut events = Vec::new(); - let mut unavailable = 0; - self.flights.retain_mut(|flight| { - let mut contact = None; - let Some(mission) = &engine.loaded else { - return false; - }; - let stays = flight.pose.advance(now, |segment| { - let ground = projectile_terrain_hit(&mission.terrain, segment)?; - contact = projectile_unit_hit(engine, flight.shooter, segment) - .filter(|hit| ground.is_none_or(|fraction| hit.fraction < fraction)); - Ok(ground.is_some() || contact.is_some()) - }); - if let Some(hit) = contact { - let data = &self.projectiles[flight.projectile]; - match data - .volume - .map(|volume| apply_projectile_contact(engine, hit, volume)) - { - Some(Ok(Some((_, true)))) => events.push(AutoDemoCombatEvent::Destroyed { - shooter: flight.shooter, - target: hit.handle, - }), - Some(Ok(Some((remaining, false)))) => { - if let Some(node) = hit.building_node { - events.push(AutoDemoCombatEvent::BuildingHit { - shooter: flight.shooter, - target: hit.handle, - node, - remaining_bits: remaining.to_bits(), - }); - } - } - _ => unavailable += 1, - } - } - match stays { - Ok(stays) => stays, - Err(_) => { - unavailable += 1; - false - } - } - }); - let Some(mission) = &engine.loaded else { - return (events, unavailable); - }; - let targets = self.targets( - &engine.world, - &mission.mission_assets, - mission.unit_patrol.as_ref(), - ); - for unit in &mut self.units { - // shortcut: armed AI units defend their position while their Init is incomplete. - let owner = identity_metadata(&engine.world, unit.handle) - .ok() - .and_then(|identity| identity.owner_id); - let guard = owner - .is_some_and(|owner| self.guard_clans.get(usize::from(owner.0)) == Some(&true)); - if mission.script_host_mode == super::MissionMode::SingleMission - && !guard - && !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) - .and_then(|(_, target)| { - let state = transform_state(&engine.world, unit.handle).ok()?; - let (from, _) = unit_sphere(&mission.mission_assets, unit.index, state)?; - match projectile_terrain_hit(&mission.terrain, [from, target.center]) { - Ok(ground) => { - // shortcut: use the same hull sphere as the projectile until per-node aiming is wired. - segment_sphere_fraction( - [from, target.center], - target.center, - target.radius, - ) - .filter(|&contact| ground.is_none_or(|ground| contact < ground)) - .map(|_| (target.handle, from, target.center)) - } - Err(_) => { - unavailable += 1; - None - } - } - }) - .or_else(|| { - let (factory, index) = - mission.unit_patrol.as_ref()?.raid_factory(unit.handle)?; - let target_owner = identity_metadata(&engine.world, factory).ok()?.owner_id?; - if self - .hostile - .get(usize::from(owner?.0))? - .get(usize::from(target_owner.0)) - != Some(&true) - { - return None; - } - let state = transform_state(&engine.world, unit.handle).ok()?; - let (from, _) = unit_sphere(&mission.mission_assets, unit.index, state)?; - let target = transform_state(&engine.world, factory).ok()?; - let (to, _) = unit_sphere(&mission.mission_assets, index, target)?; - if (to[0] - from[0]).hypot(to[1] - from[1]) > FIRE_RANGE { - return None; - } - // shortcut: aim at the root bounds center until the native attack task selects a node. - projectile_terrain_hit(&mission.terrain, [from, to]) - .is_ok_and(|ground| ground.is_none()) - .then_some((factory, from, to)) - }); - for (slot, _, _) in unit.weapons.fire(aim.is_some(), now) { - let (Some((target, from, to)), Some(projectile)) = (aim, unit.slots[slot]) else { - continue; - }; - let data = &self.projectiles[projectile]; - // shortcut: aim from the root hull center until animated AI barrel poses are sampled. - let direction = std::array::from_fn(|axis| to[axis] - from[axis]); - if let Some(pose) = - PlayerProjectile::new(from, direction, data.speed, data.lifetime_ms, now) - { - self.flights.push(Flight { - shooter: unit.handle, - projectile, - pose, - }); - events.push(AutoDemoCombatEvent::Shot { - shooter: unit.handle, - target, - projectile, - }); - } - } - } - (events, unavailable) - } -} diff --git a/crates/fparkan-runtime/src/clan_script_init.rs b/crates/fparkan-runtime/src/clan_script_init.rs index 98d899c2..2d5ac129 100644 --- a/crates/fparkan-runtime/src/clan_script_init.rs +++ b/crates/fparkan-runtime/src/clan_script_init.rs @@ -1,8 +1,11 @@ use crate::script_patrol::ScriptPatrol; -use fparkan_script::{ScriptDispatchSelector, ScriptInstruction, VarSet, VarSetDefault}; +use fparkan_script::{ + Handler15TargetPayload, ScriptDispatchSelector, ScriptInstruction, VarSet, VarSetDefault, +}; pub(super) enum InitOrder { Patrol(ScriptPatrol), + Shutdown(u32), Reserve { clan: usize, id: u32, @@ -24,22 +27,27 @@ pub(super) fn reservation( Some((id, flag != 0)) } -pub(super) fn patrol_order( +pub(super) fn unit_order( declarations: &VarSet, instruction: &ScriptInstruction, values: &[VarSetDefault], -) -> Option { +) -> Option { if instruction.dispatch_selector() != ScriptDispatchSelector::Handler(15) || instruction.header_words[1] != u32::MAX || instruction.header_words[3] != u32::MAX { return None; } - ScriptPatrol::from_order( - declarations - .resolve_handler15_with_values(instruction, values) - .ok()?, - ) + let order = declarations + .resolve_handler15_with_values(instruction, values) + .ok()?; + if matches!( + (order.word_1, order.word_2, order.target), + (0x13, 3, Handler15TargetPayload::None) + ) { + return Some(InitOrder::Shutdown(order.word_0)); + } + ScriptPatrol::from_order(order).map(InitOrder::Patrol) } pub(super) fn stubbed_handler(instruction: &ScriptInstruction) -> Option { diff --git a/crates/fparkan-runtime/src/lib.rs b/crates/fparkan-runtime/src/lib.rs index 6bd697a8..624560a3 100644 --- a/crates/fparkan-runtime/src/lib.rs +++ b/crates/fparkan-runtime/src/lib.rs @@ -42,7 +42,6 @@ use std::num::NonZeroUsize; use std::sync::Arc; mod autodemo; -mod autodemo_combat; mod boarding; mod building_door; mod clan_script_init; @@ -57,12 +56,12 @@ mod projectile; mod research; mod script_patrol; mod script_time; +mod unit_combat; mod unit_patrol; pub use autodemo::{ autodemo_camera, AutoDemoCamera, AutoDemoReinforcement, AutoDemoView, SpawnedUnit, }; -pub use autodemo_combat::{AutoDemoCombatEvent, AutoDemoProjectileType}; pub use boarding::{board_friendly_warbot, disembark_warbot, player_vehicle}; pub use building_door::{has_proximity_doors, sample_proximity_doors}; pub use fparkan_assets::MissionAssets; @@ -87,6 +86,7 @@ pub use projectile::{ projectile_unit_hit, PlayerProjectile, ProjectileAssets, ProjectileContact, }; pub use research::order_lab_research; +pub use unit_combat::{AutoDemoCombatEvent, AutoDemoProjectileType}; const MISSION_DECODED_PAYLOAD_CACHE_ENTRIES: usize = 256; const MAX_MISSION_AI_RECORD_SLOTS: usize = 1_000_000; @@ -1327,7 +1327,7 @@ pub struct Engine { world: World, loaded: Option, behavior_rng_state: u32, - autodemo_combat: Option, + autodemo_combat: Option, autodemo_reinforcements: Option, production: Option, } @@ -2442,22 +2442,25 @@ fn load_mission_with_options( &object_drafts[..reserve_start], &handles[..reserve_start], ), - MissionMode::SingleMission => (init_orders + MissionMode::SingleMission => (init_orders.iter().any(|order| { + matches!( + order, + clan_script_init::InitOrder::Patrol(_) + | clan_script_init::InitOrder::Shutdown(_) + ) + }) || loaded_scripts + .bundles .iter() - .any(|order| matches!(order, clan_script_init::InitOrder::Patrol(_))) - || 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) - }) - }) - })) + .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 { @@ -2537,10 +2540,28 @@ fn load_mission_with_options( clan_script_init::InitOrder::Reserve { clan, id, reserved } => { mission_events.set_reservation(&mission, &new_runtime_world, clan, id, reserved); } + clan_script_init::InitOrder::Shutdown(id) => { + let Some(patrol) = &mut unit_patrol else { + continue; + }; + if let Some(handle) = script_patrol::warbot_by_logic_id( + &mission, + &object_drafts, + &new_runtime_world, + id, + ) { + if patrol.shut_down(handle) { + eprintln!( + "sim_coverage unit_shutdown_approx=1 unit={} id={id}", + handle.slot + ); + } + } + } } } let autodemo_combat = (unit_patrol.is_some() || guard_clans.contains(&true)).then(|| { - autodemo_combat::AutoDemoCombat::new( + unit_combat::AutoDemoCombat::new( &vfs, &mission, &object_drafts, @@ -2917,7 +2938,7 @@ pub fn autodemo_projectile_types(engine: &Engine) -> &[AutoDemoProjectileType] { engine .autodemo_combat .as_ref() - .map_or(&[], autodemo_combat::AutoDemoCombat::types) + .map_or(&[], unit_combat::AutoDemoCombat::types) } /// Active autonomous flights in the current world. @@ -2927,7 +2948,7 @@ pub fn autodemo_projectiles( engine .autodemo_combat .iter() - .flat_map(autodemo_combat::AutoDemoCombat::flights) + .flat_map(unit_combat::AutoDemoCombat::flights) } /// Counts autonomous weapons or projectile profiles that could not be prepared. @@ -2945,7 +2966,7 @@ pub fn mission_guard_fallback_count(engine: &Engine) -> usize { engine .autodemo_combat .as_ref() - .map_or(0, autodemo_combat::AutoDemoCombat::guard_clan_count) + .map_or(0, unit_combat::AutoDemoCombat::guard_clan_count) } /// Counts AI clans approximating the scripted raid on a hostile factory. @@ -8138,9 +8159,9 @@ fn resolve_init_states( return Some(Some(write)); } if let Some(order) = - clan_script_init::patrol_order(&varset.declarations, instruction, values) + clan_script_init::unit_order(&varset.declarations, instruction, values) { - init_orders.push(clan_script_init::InitOrder::Patrol(order)); + init_orders.push(order); return Some(None); } if let Some((id, reserved)) = clan_script_init::reservation(instruction, values) diff --git a/crates/fparkan-runtime/src/mission_events.rs b/crates/fparkan-runtime/src/mission_events.rs index d63ea43c..1d4c7856 100644 --- a/crates/fparkan-runtime/src/mission_events.rs +++ b/crates/fparkan-runtime/src/mission_events.rs @@ -653,10 +653,9 @@ impl LoadedMissionState { .ok() .flatten() .is_none() - || self - .unit_patrol - .as_ref() - .is_some_and(|patrol| patrol.is_patrolling(handle)) + || self.unit_patrol.as_ref().is_some_and(|patrol| { + patrol.is_patrolling(handle) || patrol.is_shut_down(handle) + }) || self .boarding .is_some_and(|boarding| boarding.cockpit.handle == handle) diff --git a/crates/fparkan-runtime/src/script_patrol.rs b/crates/fparkan-runtime/src/script_patrol.rs index 6d349c9b..d67874c6 100644 --- a/crates/fparkan-runtime/src/script_patrol.rs +++ b/crates/fparkan-runtime/src/script_patrol.rs @@ -3,6 +3,26 @@ use crate::{MissionDocument, MissionObjectDraft}; use fparkan_script::{Handler15Invocation, Handler15TargetPayload}; use fparkan_world::{handle_by_original_id, ObjectHandle, OriginalObjectId, World}; +pub(super) fn warbot_by_logic_id( + mission: &MissionDocument, + drafts: &[MissionObjectDraft], + world: &World, + id: u32, +) -> Option { + mission + .objects + .iter() + .zip(drafts) + .enumerate() + .find_map(|(index, (object, draft))| { + (id != u32::MAX + && object.identity_or_clan_raw == id + && draft.unit_dat_header_flags == Some(crate::boarding::WARBOT_CLASS)) + .then(|| handle_by_original_id(world, OriginalObjectId(index as u32))) + .flatten() + }) +} + #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub(super) struct ScriptPatrol { pub(super) actor_id: u32, @@ -31,18 +51,7 @@ impl ScriptPatrol { drafts: &[MissionObjectDraft], world: &World, ) -> Option { - let (index, _) = - mission - .objects - .iter() - .zip(drafts) - .enumerate() - .find(|(_, (object, draft))| { - self.actor_id != u32::MAX - && object.identity_or_clan_raw == self.actor_id - && draft.unit_dat_header_flags == Some(crate::boarding::WARBOT_CLASS) - })?; - let handle = handle_by_original_id(world, OriginalObjectId(index as u32))?; + let handle = warbot_by_logic_id(mission, drafts, world, self.actor_id)?; // shortcut: use the verified default radius until per-unit patrol profiles are wired. let radius = match self.radius { 0 | u32::MAX => 60.0, diff --git a/crates/fparkan-runtime/src/unit_combat.rs b/crates/fparkan-runtime/src/unit_combat.rs new file mode 100644 index 00000000..56141775 --- /dev/null +++ b/crates/fparkan-runtime/src/unit_combat.rs @@ -0,0 +1,426 @@ +use super::{ + apply_projectile_contact, + autodemo::MOBILE_UNIT, + player_weapon::prepare_unit_weapons, + projectile::{load_projectile, segment_sphere_fraction, unit_sphere}, + projectile_terrain_hit, projectile_unit_hit, + unit_patrol::UnitPatrol, + Engine, MissionAssets, MissionDocument, MissionObjectDraft, ObjectHandle, PlayerProjectile, + PlayerWeapons, +}; +use fparkan_vfs::Vfs; +use fparkan_world::{identity_metadata, transform_state}; +use std::sync::Arc; + +// Behavior's default Patrol_Attack_Range and Attack_MaxFireDistance. +const ATTACK_RANGE: f32 = 400.0; +const FIRE_RANGE: f32 = 200.0; + +/// An autonomous projectile type, in render-pool order. +pub struct AutoDemoProjectileType { + /// Prototype archive. + pub archive: String, + /// Prototype name. + pub name: String, + /// Maximum concurrent flights for the prepared weapons. + pub capacity: u32, + speed: f32, + lifetime_ms: u32, + volume: Option, +} + +/// One autonomous combat event on the mission clock. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum AutoDemoCombatEvent { + /// A weapon released a projectile. + Shot { + /// Owner of the weapon. + shooter: ObjectHandle, + /// Object the weapon was aimed at. + target: ObjectHandle, + /// Projectile type in render-pool order. + projectile: usize, + }, + /// A projectile exhausted a unit's health. + Destroyed { + /// Owner of the weapon. + shooter: ObjectHandle, + /// Unit removed from the world. + target: ObjectHandle, + }, + /// An autonomous shot changed a building part's health. + BuildingHit { + /// Owner of the weapon. + shooter: ObjectHandle, + /// Building struck by the projectile. + target: ObjectHandle, + /// Provider row associated with the struck part. + node: u32, + /// Remaining health of the part as raw f32 bits. + remaining_bits: u32, + }, +} + +pub(super) struct AutoDemoCombat { + units: Vec, + reserve: Vec, + hostile: Vec>, + guard_clans: Vec, + projectiles: Vec, + flights: Vec, + pub(super) unavailable: usize, +} + +#[derive(Clone, Copy)] +pub(super) struct CombatTarget { + pub(super) handle: ObjectHandle, + pub(super) center: [f32; 3], + radius: f32, + pub(super) in_range: bool, +} + +#[derive(Clone)] +struct Unit { + handle: ObjectHandle, + index: usize, + weapons: PlayerWeapons, + slots: Vec>, +} + +struct Flight { + shooter: ObjectHandle, + projectile: usize, + pose: PlayerProjectile, +} + +impl AutoDemoCombat { + pub(super) fn new( + vfs: &Arc, + mission: &MissionDocument, + drafts: &[MissionObjectDraft], + handles: &[ObjectHandle], + assets: &MissionAssets, + reserve_start: usize, + guard_clans: Vec, + ) -> Self { + let hostile = mission + .clans + .iter() + .map(|clan| { + mission + .clans + .iter() + .map(|other| { + clan.relations.iter().any(|relation| { + relation.relation_value == 0 + && relation.other_clan_name.raw == other.name.raw + }) + }) + .collect() + }) + .collect(); + let mut battle = Self { + units: Vec::new(), + reserve: Vec::new(), + hostile, + guard_clans, + projectiles: Vec::new(), + flights: Vec::new(), + unavailable: 0, + }; + for (index, (draft, &handle)) in drafts.iter().zip(handles).enumerate() { + if !draft + .unit_dat_header_flags + .is_some_and(|class| class & MOBILE_UNIT != 0) + { + continue; + } + let weapons = prepare_unit_weapons( + assets + .object_component_controls + .get(index) + .map_or(&[], Vec::as_slice), + ); + let slots = weapons + .weapons() + .iter() + .map(|weapon| { + let archive = &weapon.projectile_archive; + let name = &weapon.projectile; + let slot = battle + .projectiles + .iter() + .position(|entry| { + entry.archive.eq_ignore_ascii_case(archive) + && entry.name.eq_ignore_ascii_case(name) + }) + .or_else(|| { + let Ok(data) = load_projectile(vfs, archive, name) else { + battle.unavailable += 1; + return None; + }; + battle.projectiles.push(AutoDemoProjectileType { + archive: archive.clone(), + name: name.clone(), + capacity: 0, + speed: data.speed, + lifetime_ms: data.lifetime_ms, + volume: data.volume, + }); + Some(battle.projectiles.len() - 1) + })?; + let entry = &mut battle.projectiles[slot]; + entry.capacity = entry + .capacity + .saturating_add(entry.lifetime_ms.div_ceil(weapon.interval_ms())); + Some(slot) + }) + .collect(); + battle.unavailable += usize::from(weapons.weapons().is_empty()); + let units = if index < reserve_start { + &mut battle.units + } else { + &mut battle.reserve + }; + units.push(Unit { + handle, + index, + weapons, + slots, + }); + } + battle + } + + pub(super) fn activate( + &mut self, + world: &fparkan_world::World, + index: usize, + handle: ObjectHandle, + ) { + self.units + .retain(|unit| transform_state(world, unit.handle).is_ok()); + if let Some(template) = self.reserve.iter().find(|unit| unit.index == index) { + self.units.push(Unit { + handle, + ..template.clone() + }); + } + } + + pub(super) fn types(&self) -> &[AutoDemoProjectileType] { + &self.projectiles + } + + pub(super) fn guard_clan_count(&self) -> usize { + self.guard_clans.iter().filter(|&&enabled| enabled).count() + } + + pub(super) fn flights(&self) -> impl Iterator + '_ { + self.flights + .iter() + .map(|flight| (flight.projectile, flight.pose)) + } + + pub(super) fn targets( + &self, + world: &fparkan_world::World, + assets: &MissionAssets, + patrol: Option<&UnitPatrol>, + ) -> Vec<(ObjectHandle, CombatTarget)> { + let live: Vec<_> = self + .units + .iter() + .filter_map(|unit| { + let owner = identity_metadata(world, unit.handle).ok()?.owner_id?; + let state = transform_state(world, unit.handle).ok()?; + let (center, radius) = unit_sphere(assets, unit.index, state)?; + Some(( + unit.handle, + usize::from(owner.0), + center, + radius, + state.position.map(f32::from_bits), + )) + }) + .collect(); + live.iter() + .filter_map(|&(handle, clan, from, _, position)| { + if patrol.is_some_and(|patrol| patrol.is_shut_down(handle)) { + return None; + } + let limit = patrol.and_then(|patrol| patrol.attack_limit(handle)); + if limit.is_some_and(|limit| !limit.allows_attack(position)) { + return None; + } + let (enemy, center, radius, distance) = live + .iter() + .filter_map(|&(enemy, other, to, radius, target_position)| { + let distance = (to[0] - from[0]).hypot(to[1] - from[1]); + (enemy != handle + && distance <= ATTACK_RANGE + && limit + .is_none_or(|limit| limit.allows_target(enemy, target_position)) + && self.hostile.get(clan)?.get(other) == Some(&true)) + .then_some((enemy, to, radius, distance)) + }) + .min_by(|a, b| a.3.total_cmp(&b.3))?; + Some(( + handle, + CombatTarget { + handle: enemy, + center, + radius, + in_range: distance <= FIRE_RANGE, + }, + )) + }) + .collect() + } + + pub(super) fn tick( + &mut self, + engine: &mut Engine, + now: u32, + ) -> (Vec, usize) { + let mut events = Vec::new(); + let mut unavailable = 0; + self.flights.retain_mut(|flight| { + let mut contact = None; + let Some(mission) = &engine.loaded else { + return false; + }; + let stays = flight.pose.advance(now, |segment| { + let ground = projectile_terrain_hit(&mission.terrain, segment)?; + contact = projectile_unit_hit(engine, flight.shooter, segment) + .filter(|hit| ground.is_none_or(|fraction| hit.fraction < fraction)); + Ok(ground.is_some() || contact.is_some()) + }); + if let Some(hit) = contact { + let data = &self.projectiles[flight.projectile]; + match data + .volume + .map(|volume| apply_projectile_contact(engine, hit, volume)) + { + Some(Ok(Some((_, true)))) => events.push(AutoDemoCombatEvent::Destroyed { + shooter: flight.shooter, + target: hit.handle, + }), + Some(Ok(Some((remaining, false)))) => { + if let Some(node) = hit.building_node { + events.push(AutoDemoCombatEvent::BuildingHit { + shooter: flight.shooter, + target: hit.handle, + node, + remaining_bits: remaining.to_bits(), + }); + } + } + _ => unavailable += 1, + } + } + match stays { + Ok(stays) => stays, + Err(_) => { + unavailable += 1; + false + } + } + }); + let Some(mission) = &engine.loaded else { + return (events, unavailable); + }; + let targets = self.targets( + &engine.world, + &mission.mission_assets, + mission.unit_patrol.as_ref(), + ); + for unit in &mut self.units { + // shortcut: armed AI units defend their position while their Init is incomplete. + let owner = identity_metadata(&engine.world, unit.handle) + .ok() + .and_then(|identity| identity.owner_id); + let guard = owner + .is_some_and(|owner| self.guard_clans.get(usize::from(owner.0)) == Some(&true)); + if mission.script_host_mode == super::MissionMode::SingleMission + && !guard + && !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) + .and_then(|(_, target)| { + let state = transform_state(&engine.world, unit.handle).ok()?; + let (from, _) = unit_sphere(&mission.mission_assets, unit.index, state)?; + match projectile_terrain_hit(&mission.terrain, [from, target.center]) { + Ok(ground) => { + // shortcut: use the same hull sphere as the projectile until per-node aiming is wired. + segment_sphere_fraction( + [from, target.center], + target.center, + target.radius, + ) + .filter(|&contact| ground.is_none_or(|ground| contact < ground)) + .map(|_| (target.handle, from, target.center)) + } + Err(_) => { + unavailable += 1; + None + } + } + }) + .or_else(|| { + let (factory, index) = + mission.unit_patrol.as_ref()?.raid_factory(unit.handle)?; + let target_owner = identity_metadata(&engine.world, factory).ok()?.owner_id?; + if self + .hostile + .get(usize::from(owner?.0))? + .get(usize::from(target_owner.0)) + != Some(&true) + { + return None; + } + let state = transform_state(&engine.world, unit.handle).ok()?; + let (from, _) = unit_sphere(&mission.mission_assets, unit.index, state)?; + let target = transform_state(&engine.world, factory).ok()?; + let (to, _) = unit_sphere(&mission.mission_assets, index, target)?; + if (to[0] - from[0]).hypot(to[1] - from[1]) > FIRE_RANGE { + return None; + } + // shortcut: aim at the root bounds center until the native attack task selects a node. + projectile_terrain_hit(&mission.terrain, [from, to]) + .is_ok_and(|ground| ground.is_none()) + .then_some((factory, from, to)) + }); + for (slot, _, _) in unit.weapons.fire(aim.is_some(), now) { + let (Some((target, from, to)), Some(projectile)) = (aim, unit.slots[slot]) else { + continue; + }; + let data = &self.projectiles[projectile]; + // shortcut: aim from the root hull center until animated AI barrel poses are sampled. + let direction = std::array::from_fn(|axis| to[axis] - from[axis]); + if let Some(pose) = + PlayerProjectile::new(from, direction, data.speed, data.lifetime_ms, now) + { + self.flights.push(Flight { + shooter: unit.handle, + projectile, + pose, + }); + events.push(AutoDemoCombatEvent::Shot { + shooter: unit.handle, + target, + projectile, + }); + } + } + } + (events, unavailable) + } +} diff --git a/crates/fparkan-runtime/src/unit_patrol.rs b/crates/fparkan-runtime/src/unit_patrol.rs index 205af4ea..8be60d89 100644 --- a/crates/fparkan-runtime/src/unit_patrol.rs +++ b/crates/fparkan-runtime/src/unit_patrol.rs @@ -1,19 +1,21 @@ use super::{ autodemo::{MOBILE_UNIT, PLANT_CLASS}, - autodemo_combat::CombatTarget, boarding::WARBOT_CLASS, - next_crt_rand, EngineError, MissionDocument, MissionObjectDraft, MissionScriptBundle, - ObjectHandle, TerrainWorld, TransformState, World, + next_crt_rand, + unit_combat::CombatTarget, + EngineError, MissionDocument, MissionObjectDraft, MissionScriptBundle, ObjectHandle, + TerrainWorld, TransformState, World, }; use fparkan_script::{Handler15TargetPayload, ScriptDispatchSelector, VarSet}; use fparkan_terrain::{NavigationQuery, RouteRequest, SurfaceQuery}; use fparkan_world::{set_transform, transform_state}; -use std::collections::VecDeque; +use std::collections::{HashSet, VecDeque}; #[derive(Clone)] pub(super) struct UnitPatrol { center: Option<[f32; 2]>, units: Vec, + shut_down: HashSet, clock_ms: u32, rng: u32, pub(super) factory_raid_clans: usize, @@ -132,6 +134,7 @@ impl UnitPatrol { Self { center: None, units: Vec::new(), + shut_down: HashSet::new(), clock_ms: 0, rng: 1, factory_raid_clans: 0, @@ -145,6 +148,7 @@ impl UnitPatrol { center: [f32; 2], radius: f32, ) -> bool { + self.shut_down.remove(&handle); self.units .retain(|unit| transform_state(world, unit.handle).is_ok()); if let Some(unit) = self.units.iter_mut().find(|unit| unit.handle == handle) { @@ -174,6 +178,16 @@ impl UnitPatrol { self.units.iter().any(|unit| unit.handle == handle) } + pub(super) fn shut_down(&mut self, handle: ObjectHandle) -> bool { + // shortcut: stop autonomous movement and fire until the native shutdown task is modeled. + self.units.retain(|unit| unit.handle != handle); + self.shut_down.insert(handle) + } + + pub(super) fn is_shut_down(&self, handle: ObjectHandle) -> bool { + self.shut_down.contains(&handle) + } + pub(super) fn raid_factory(&self, handle: ObjectHandle) -> Option<(ObjectHandle, usize)> { self.units .iter() @@ -230,6 +244,7 @@ impl UnitPatrol { Some(Self { center: Some(center), units, + shut_down: HashSet::new(), clock_ms: 0, rng: 1, factory_raid_clans: 0, @@ -324,6 +339,26 @@ impl UnitPatrol { } } +#[cfg(test)] +#[test] +fn shutdown_clears_patrol_until_a_new_order_arrives() { + let mut world = fparkan_world::new(fparkan_world::WorldConfig::default()); + let handle = fparkan_world::construct_object( + &mut world, + fparkan_world::ObjectDraft { original_id: None }, + ) + .unwrap(); + fparkan_world::register_object(&mut world, handle).unwrap(); + let mut patrol = UnitPatrol::scripted(); + assert!(patrol.order(&world, handle, [20.0, 30.0], 60.0)); + assert!(patrol.shut_down(handle)); + assert!(patrol.is_shut_down(handle)); + assert!(!patrol.is_patrolling(handle)); + assert!(patrol.order(&world, handle, [35.0, 45.0], 60.0)); + assert!(!patrol.is_shut_down(handle)); + assert!(patrol.is_patrolling(handle)); +} + fn distance_to_patrol([x, y]: [f32; 2], [px, py, _]: [f32; 3]) -> f32 { // shortcut: use the horizontal distance until patrol orders carry their native Z. (px - x).hypot(py - y) -- cgit v1.2.3