diff options
| author | Valentin Popov <valentin@popov.link> | 2026-12-01 18:13:13 +0300 |
|---|---|---|
| committer | Valentin Popov <valentin@popov.link> | 2026-12-01 18:13:13 +0300 |
| commit | 72ae7666d428c783a03b5378658890947f205de0 (patch) | |
| tree | 7ab19d6b3104c906a84d5cf9839b103735d27e47 /crates/fparkan-runtime | |
| parent | f7c5c3bffd565bb6b0995a220ecb7788471b7848 (diff) | |
| download | fparkan-72ae7666d428c783a03b5378658890947f205de0.tar.xz fparkan-72ae7666d428c783a03b5378658890947f205de0.zip | |
fix(ai): dispatch building loss to the former clan
Diffstat (limited to 'crates/fparkan-runtime')
| -rw-r--r-- | crates/fparkan-runtime/src/clan_ai_events.rs | 219 | ||||
| -rw-r--r-- | crates/fparkan-runtime/src/clan_capture_event.rs | 132 | ||||
| -rw-r--r-- | crates/fparkan-runtime/src/clan_targeting.rs | 15 | ||||
| -rw-r--r-- | crates/fparkan-runtime/src/lib.rs | 1 | ||||
| -rw-r--r-- | crates/fparkan-runtime/src/mission_events.rs | 3 |
5 files changed, 322 insertions, 48 deletions
diff --git a/crates/fparkan-runtime/src/clan_ai_events.rs b/crates/fparkan-runtime/src/clan_ai_events.rs index 65e602a6..2373f220 100644 --- a/crates/fparkan-runtime/src/clan_ai_events.rs +++ b/crates/fparkan-runtime/src/clan_ai_events.rs @@ -315,13 +315,24 @@ impl LoadedMissionState { let Some(clock) = self.clan_ai_events.clocks.tick(clan, elapsed_ms, rng) else { continue; }; - let Some((event_index, event)) = - bundle.package.events.iter().enumerate().find(|(_, event)| { - event.name_raw == b"Problems0\0" && !event.instructions.is_empty() - }) + let Some((event_index, event)) = bundle + .package + .events + .iter() + .enumerate() + .find(|(_, event)| event.name_raw == b"Problems0\0") else { continue; }; + if event.instructions.is_empty() + && self + .clan_ai_events + .problems + .get(&clan) + .is_none_or(|queue| queue.records().is_empty()) + { + continue; + } let Some(state) = self .script_varset_states .iter_mut() @@ -578,7 +589,7 @@ impl LoadedMissionState { crate::clan_targeting::attack_target( &self.mission, &self.object_drafts, &self.control_device_tables, world, clan, radius, - self.clan_ai_events.base_radius_limits.get(&clan).copied().unwrap_or(700.0), + self.clan_ai_events.base_radius_limit(clan), ) } else { crate::clan_targeting::capture_target( &self.mission, &self.object_drafts, &self.control_device_tables, @@ -1124,31 +1135,13 @@ impl LoadedMissionState { Ok(None) } ScriptDispatchSelector::Handler(2) => { - let (name, input) = problem_operands( + self.clan_ai_events.submit_problem( + clan, + &bundle.package, &varset.declarations, values, &instruction.references, - ) - .ok_or("Handler(2) requires seven numeric problem operands")?; - let start = format!("{name}_Start\0"); - let resume = format!("{name}_Continue\0"); - if bundle - .package - .events - .iter() - .any(|event| event.name_raw == start.as_bytes()) - && bundle - .package - .events - .iter() - .any(|event| event.name_raw == resume.as_bytes()) - { - self.clan_ai_events - .problems - .entry(clan) - .or_default() - .submit(input); - } + )?; Ok(None) } ScriptDispatchSelector::Handler(3) if instruction.references.is_empty() => { @@ -1271,7 +1264,7 @@ impl LoadedMissionState { let selection = crate::clan_targeting::base_threat( &self.mission, &self.object_drafts, &self.control_device_tables, world, clan, extension, - self.clan_ai_events.base_radius_limits.get(&clan).copied().unwrap_or(700.0), + self.clan_ai_events.base_radius_limit(clan), |id| self.clan_ai_events.problems.get(&clan).is_some_and(|queue| { queue.records().iter().any(|record| record.key.word_0 == 12 && record.key.argument_0 == id) }), @@ -1344,26 +1337,12 @@ impl LoadedMissionState { }, ); if let Err((stopped_event, instruction_index, reason)) = result { - let (stop, count) = self - .clan_ai_events - .stops - .entry((clan, stopped_event, instruction_index)) - .or_insert_with(|| { - ( - MissionEventStop { - clan_index: clan, - script_path: bundle.script_path.clone(), - event_index: stopped_event, - instruction_index, - reason, - }, - 0, - ) - }); - *count += 1; - if *count == 1 { - eprintln!("sim_coverage script_clan_ai_unsupported=1 clan={clan} script={} event={stopped_event} instruction={instruction_index} reason={}", stop.script_path, stop.reason); - } + self.clan_ai_events.report_stop( + bundle, + stopped_event, + instruction_index, + reason, + ); } if let Some(problem) = problem { if problems_event.is_none() && !solved && !solving { @@ -1466,6 +1445,62 @@ fn storage_space(ores: &[BehaviorOreState], world: &World, clan: OwnerId) -> f32 } impl ClanAiEvents { + pub(super) fn submit_problem( + &mut self, + clan: usize, + package: &fparkan_script::ScriptPackage, + varset: &VarSet, + values: &[VarSetDefault], + references: &[u32], + ) -> Result<(), String> { + let (name, input) = problem_operands(varset, values, references) + .ok_or("Handler(2) requires seven numeric problem operands")?; + let start = format!("{name}_Start\0"); + let resume = format!("{name}_Continue\0"); + if [start, resume].iter().all(|name| { + package + .events + .iter() + .any(|event| event.name_raw == name.as_bytes()) + }) { + self.problems.entry(clan).or_default().submit(input); + } + Ok(()) + } + + pub(super) fn report_stop( + &mut self, + bundle: &crate::MissionScriptBundle, + event_index: usize, + instruction_index: usize, + reason: String, + ) { + let clan = bundle.clan_index; + let (stop, count) = self + .stops + .entry((clan, event_index, instruction_index)) + .or_insert_with(|| { + ( + MissionEventStop { + clan_index: clan, + script_path: bundle.script_path.clone(), + event_index, + instruction_index, + reason, + }, + 0, + ) + }); + *count += 1; + if *count == 1 { + eprintln!("sim_coverage script_clan_ai_unsupported=1 clan={clan} script={} event={event_index} instruction={instruction_index} reason={}", stop.script_path, stop.reason); + } + } + + pub(super) fn base_radius_limit(&self, clan: usize) -> f32 { + self.base_radius_limits.get(&clan).copied().unwrap_or(700.0) + } + pub(super) fn research_scan_queries(&self) -> impl Iterator<Item = (usize, u32, u64)> + '_ { self.research_scan_queries .iter() @@ -1746,6 +1781,94 @@ mod tests { #[test] #[ignore = "requires licensed corpus"] + fn licensed_enemy_factory_capture_queues_a_counterattack() { + use crate::{EngineServices, MissionMode, MissionRequest, MissionStartupInput}; + use fparkan_vfs::DirectoryVfs; + use fparkan_world::{ + handle_by_original_id, set_transform, transform_state, OriginalObjectId, + }; + use std::sync::Arc; + + let root = std::env::var_os("FPARKAN_CORPUS_PART1_ROOT").expect("licensed corpus root"); + let mut engine = + crate::create(EngineServices::new(Arc::new(DirectoryVfs::new(root)))).unwrap(); + crate::load_gameplay_mission( + &mut engine, + MissionRequest { + key: "MISSIONS/Single.01/data.tma".into(), + mode: MissionMode::SingleMission, + }, + MissionStartupInput { + queue_time_ms: 0, + research_creation_gate: false, + }, + None, + ) + .unwrap(); + let enemy_factory = OriginalObjectId(9); + let factory = handle_by_original_id(&engine.world, enemy_factory).unwrap(); + let world = &engine.world; + let mission = engine.loaded.as_ref().unwrap(); + let logic_id = mission + .mission_events + .logic_id(&mission.mission, world, factory) + .unwrap(); + let pose = transform_state(world, factory).unwrap(); + let [a, b, c] = crate::mission_events::communicator_triangles( + &mission.mission_assets, + enemy_factory.0 as usize, + 0x8000_0010, + pose, + ) + .unwrap()[0]; + let hero = crate::starting_cockpit(&engine).unwrap(); + let start = transform_state(world, hero.handle).unwrap(); + let mut pose = start; + // Exercise the communicator entry point at the stock platform in isolation. + pose.position = std::array::from_fn(|axis| ((a[axis] + b[axis] + c[axis]) / 3.0).to_bits()); + set_transform(&mut engine.world, hero.handle, pose).unwrap(); + assert_eq!( + crate::capture_building(&mut engine, hero).unwrap(), + Some(enemy_factory) + ); + assert_eq!( + identity_metadata(&engine.world, factory).unwrap().owner_id, + Some(OwnerId(0)) + ); + let ai = &engine.loaded.as_ref().unwrap().clan_ai_events; + let request = ai + .problems + .get(&1) + .unwrap() + .records() + .iter() + .find(|record| record.key.word_0 == 14 && record.key.argument_0 == logic_id) + .expect("Fort_Captured requested recapture for the former owner"); + assert!((request.scalar_1 - 0.85).abs() < 1e-6); + assert!(!ai.problems.contains_key(&0)); + let key = request.key; + + // The isolated capture must not also put the hero in the clan's + // immediate defence radius, which can take over the capturer. + set_transform(&mut engine.world, hero.handle, start).unwrap(); + for now in (0..=10_000).step_by(100) { + crate::frame(&mut engine, now).unwrap(); + let ai = &engine.loaded.as_ref().unwrap().clan_ai_events; + if ai + .capture_orders + .iter() + .any(|&(owner, assigned, approach)| { + owner == OwnerId(1) && assigned == key && approach.target == factory + }) + { + return; + } + } + panic!("the script must send a capturer to retake the lost factory"); + } + + #[test] + #[ignore = "requires licensed corpus"] fn licensed_mine_request_waits_for_its_capture_order() { use crate::{EngineServices, MissionMode, MissionRequest, MissionStartupInput}; use fparkan_vfs::DirectoryVfs; diff --git a/crates/fparkan-runtime/src/clan_capture_event.rs b/crates/fparkan-runtime/src/clan_capture_event.rs new file mode 100644 index 00000000..4410f792 --- /dev/null +++ b/crates/fparkan-runtime/src/clan_capture_event.rs @@ -0,0 +1,132 @@ +//! Script notifications for a building's former owner. + +use crate::LoadedMissionState; +use fparkan_script::{ScriptDispatchSelector, VarSetDefault}; +use fparkan_world::{identity_metadata, ObjectHandle, OwnerId, World}; + +pub(super) fn dispatch( + mission: &mut LoadedMissionState, + world: &World, + building: ObjectHandle, + former_owner: OwnerId, +) { + let Some(id) = mission + .mission_events + .logic_id(&mission.mission, world, building) + else { + return; + }; + if id == u32::MAX { + return; + } + let clan = usize::from(former_owner.0); + let Some(bundle) = mission + .script_bundles + .iter() + .find(|bundle| bundle.clan_index == clan && bundle.behavior_warm_start.is_some()) + else { + return; + }; + let Some(event) = + bundle.package.events.iter().position(|event| { + event.name_raw == b"Fort_Captured\0" && !event.instructions.is_empty() + }) + else { + return; + }; + let Some(varset) = mission.script_varset.as_ref().map(|set| &set.declarations) else { + return; + }; + let Some(values) = mission + .script_varset_states + .iter_mut() + .find(|state| state.clan_index == clan) + .map(|state| &mut state.values) + else { + return; + }; + let Some(sender) = varset + .declarations + .iter() + .position(|cell| cell.name == "dCurrentSender") + .and_then(|index| values.get_mut(index)) + else { + return; + }; + *sender = VarSetDefault::Dword(id); + let result = varset.execute_package_event_prefix( + &bundle.package, + event, + bundle.formula_table.as_ref(), + values, + |_, instruction, values| { + let lookup = |index: u32| { + let id = values.get(index as usize)?.as_dword()?; + mission + .mission_events + .logic_objects(&mission.mission, world, id) + .next() + }; + match instruction.dispatch_selector() { + ScriptDispatchSelector::Handler(63) => { + let &[id] = instruction.references.as_slice() else { + return Err("Handler(63) requires a building ID".into()); + }; + let inside = lookup(id).is_some_and(|handle| { + crate::clan_targeting::inside_clan_area( + &mission.mission, + &mission.object_drafts, + world, + clan, + mission.clan_ai_events.base_radius_limit(clan), + handle, + ) + }); + Ok(Some(VarSetDefault::Dword(u32::from(inside)))) + } + ScriptDispatchSelector::Handler(66) => { + let &[id, output] = instruction.references.as_slice() else { + return Err("Handler(66) requires a building ID and weight output".into()); + }; + let Some(class) = lookup(id) + .and_then(|handle| identity_metadata(world, handle).ok()?.original_id) + .and_then(|id| mission.object_drafts.get(id.0 as usize)) + .and_then(|draft| draft.unit_dat_header_flags) + else { + return Ok(None); + }; + let cell = values + .get_mut(output as usize) + .filter(|value| matches!(value, VarSetDefault::FloatBits(_))) + .ok_or("Handler(66) requires a float weight output")?; + *cell = VarSetDefault::FloatBits(building_weight(class).to_bits()); + Ok(Some(VarSetDefault::Dword(class))) + } + ScriptDispatchSelector::Handler(2) => { + mission.clan_ai_events.submit_problem( + clan, + &bundle.package, + varset, + values, + &instruction.references, + )?; + Ok(None) + } + selector => Err(format!("{selector:?}")), + } + }, + ); + if let Err((event, instruction, reason)) = result { + mission + .clan_ai_events + .report_stop(bundle, event, instruction, reason); + } +} + +fn building_weight(class: u32) -> f32 { + match class { + 0x8000_0002 => 0.04, + 0x8000_0010 => 0.05, + _ => 0.0, + } +} diff --git a/crates/fparkan-runtime/src/clan_targeting.rs b/crates/fparkan-runtime/src/clan_targeting.rs index ef580e43..4e710bca 100644 --- a/crates/fparkan-runtime/src/clan_targeting.rs +++ b/crates/fparkan-runtime/src/clan_targeting.rs @@ -365,6 +365,21 @@ fn strongest_threat(candidates: impl IntoIterator<Item = (u32, u32, f32)>) -> Op strongest } +pub(super) fn inside_clan_area( + mission: &MissionDocument, + drafts: &[MissionObjectDraft], + world: &World, + clan: usize, + limit: f32, + building: ObjectHandle, +) -> bool { + clan_area(mission, drafts, world, clan, limit).is_some_and(|(anchor, radius)| { + transform_state(world, building).is_ok_and(|pose| { + distance_from_anchor(anchor, pose.position.map(f32::from_bits)) < radius + }) + }) +} + fn clan_area( mission: &MissionDocument, drafts: &[MissionObjectDraft], diff --git a/crates/fparkan-runtime/src/lib.rs b/crates/fparkan-runtime/src/lib.rs index e6c53a20..970e8551 100644 --- a/crates/fparkan-runtime/src/lib.rs +++ b/crates/fparkan-runtime/src/lib.rs @@ -61,6 +61,7 @@ mod clan_ai_events; mod clan_area_strength; mod clan_build_limits; mod clan_building_queries; +mod clan_capture_event; mod clan_clock; mod combat_report; pub use combat_report::{CombatObject, CombatOccurrences, CombatReport}; diff --git a/crates/fparkan-runtime/src/mission_events.rs b/crates/fparkan-runtime/src/mission_events.rs index 62564970..6cd0c9df 100644 --- a/crates/fparkan-runtime/src/mission_events.rs +++ b/crates/fparkan-runtime/src/mission_events.rs @@ -588,6 +588,9 @@ impl LoadedMissionState { new_owner: OwnerId, class: u32, ) -> Result<(), EngineError> { + if former_owner != new_owner { + crate::clan_capture_event::dispatch(self, world, handle, former_owner); + } set_owner(world, handle, Some(new_owner))?; if former_owner != new_owner { self.note_clan_registration(new_owner, handle); |
