diff options
| author | Valentin Popov <valentin@popov.link> | 2026-11-14 22:19:00 +0300 |
|---|---|---|
| committer | Valentin Popov <valentin@popov.link> | 2026-11-14 22:19:00 +0300 |
| commit | 41ff7eec69baff620f97a636bd5a7709f7e27eb1 (patch) | |
| tree | cbfe7e0c454f57e8038afc1d3d095b3191bf559a /crates/fparkan-runtime/src | |
| parent | 16450724fa9d3052d315442a07b71e8d445c6cc3 (diff) | |
| download | fparkan-41ff7eec69baff620f97a636bd5a7709f7e27eb1.tar.xz fparkan-41ff7eec69baff620f97a636bd5a7709f7e27eb1.zip | |
feat(ai): evaluate factory guards and threats to the base
Single.01 reaches the end of Problems0 and enters its building protection and construction jobs. Confirm radius boundaries, first-factory order, hero priority and duplicate exclusion via GOG ai.dll. Unavailable building upgrades log a stub and return no eligible target.
Diffstat (limited to 'crates/fparkan-runtime/src')
| -rw-r--r-- | crates/fparkan-runtime/src/clan_ai_events.rs | 62 | ||||
| -rw-r--r-- | crates/fparkan-runtime/src/clan_targeting.rs | 174 | ||||
| -rw-r--r-- | crates/fparkan-runtime/src/lib.rs | 10 | ||||
| -rw-r--r-- | crates/fparkan-runtime/src/mission_events.rs | 2 |
4 files changed, 224 insertions, 24 deletions
diff --git a/crates/fparkan-runtime/src/clan_ai_events.rs b/crates/fparkan-runtime/src/clan_ai_events.rs index 284a9bc8..f7841366 100644 --- a/crates/fparkan-runtime/src/clan_ai_events.rs +++ b/crates/fparkan-runtime/src/clan_ai_events.rs @@ -194,6 +194,8 @@ pub(super) struct ClanAiEvents { strength_queries: BTreeMap<(usize, u16), u64>, capture_queries: BTreeMap<usize, u64>, attack_queries: BTreeMap<usize, u64>, + factory_defence_queries: BTreeMap<(usize, u32), u64>, + base_threat_queries: BTreeMap<(usize, u32), u64>, base_radius_limits: BTreeMap<usize, f32>, capturer_queries: BTreeMap<usize, u64>, capture_orders: Vec<(OwnerId, Handler2RecordKey, CaptureApproach)>, @@ -768,6 +770,54 @@ impl LoadedMissionState { ), ))) } + ScriptDispatchSelector::Handler(58) => { + single_dword(&instruction.references, values) + .ok_or("Handler(58) requires a DWORD building index")?; + // shortcut: an unavailable upgrade catalog exposes no eligible buildings. + self.clan_ai_events.log_research_stub(clan, 58, &bundle.script_path); + Ok(Some(VarSetDefault::Dword(u32::MAX))) + } + ScriptDispatchSelector::Handler(handler @ (47 | 67)) => { + let (output, selection) = match (handler, instruction.references.as_slice()) { + (47, &[extension, output]) => { + let extension = values.get(extension as usize).and_then(|cell| cell.as_dword()) + .ok_or("Handler(47) requires a DWORD extension of the base radius")?; + 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), + |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) + }), + ); + (output, selection) + } + (67, &[output]) => { + let units = self.mission_events.clan_units(world, OwnerId(clan as u16), false); + (output, crate::clan_targeting::factory_defence(world, &self.object_drafts, &self.control_device_tables, units)) + } + _ => return Err("defence query requires a strength output".into()), + }; + let cell = values.get_mut(output as usize) + .ok_or("defence query strength output is unavailable")?; + let (id, power) = selection.unwrap_or((u32::MAX, 0.0)); + let power = crate::clan_targeting::encode_strength(power); + *cell = match *cell { + VarSetDefault::Dword(_) => VarSetDefault::Dword(power as u32), + VarSetDefault::FloatBits(_) => VarSetDefault::FloatBits(power.to_bits()), + }; + let (queries, name) = if handler == 47 { + (&mut self.clan_ai_events.base_threat_queries, "script_base_threat_approx") + } else { + (&mut self.clan_ai_events.factory_defence_queries, "script_factory_defence_approx") + }; + let count = queries.entry((clan, id)).or_default(); + *count += 1; + if *count == 1 { + eprintln!("sim_coverage {name}=1 clan={clan} target={id} strength={power}"); + } + Ok(Some(VarSetDefault::Dword(id))) + } ScriptDispatchSelector::Handler(handler @ (56 | 65)) if instruction.references.is_empty() => { @@ -976,6 +1026,18 @@ fn storage_space(ores: &[BehaviorOreState], world: &World, clan: OwnerId) -> f32 } impl ClanAiEvents { + pub(super) fn base_threat_queries(&self) -> impl Iterator<Item = (usize, u32, u64)> + '_ { + self.base_threat_queries + .iter() + .map(|(&(clan, id), &count)| (clan, id, count)) + } + + pub(super) fn factory_defence_queries(&self) -> impl Iterator<Item = (usize, u32, u64)> + '_ { + self.factory_defence_queries + .iter() + .map(|(&(clan, id), &count)| (clan, id, count)) + } + pub(super) fn wait_starts(&self) -> impl Iterator<Item = (usize, u32, u64)> + '_ { self.wait_starts .iter() diff --git a/crates/fparkan-runtime/src/clan_targeting.rs b/crates/fparkan-runtime/src/clan_targeting.rs index 909c14eb..e81af415 100644 --- a/crates/fparkan-runtime/src/clan_targeting.rs +++ b/crates/fparkan-runtime/src/clan_targeting.rs @@ -144,6 +144,48 @@ pub(super) fn encode_strength(strength: f32) -> f32 { (strength as i64 as u32) as f32 } +pub(super) fn factory_defence( + world: &World, + drafts: &[MissionObjectDraft], + controls: &[MissionControlDeviceTableState], + units: impl Iterator<Item = ObjectHandle> + Clone, +) -> Option<(u32, f32)> { + let (id, position) = units.clone().find_map(|handle| { + let index = identity_metadata(world, handle).ok()?.original_id?.0 as usize; + let draft = drafts.get(index)?; + (draft.unit_dat_header_flags == Some(crate::autodemo::PLANT_CLASS)).then_some(())?; + Some(( + draft.identity_or_clan_raw, + transform_state(world, handle) + .ok()? + .position + .map(f32::from_bits), + )) + })?; + // shortcut: sum from live Control tables until the ArealMap street records are available. + let guards = units.filter(|&handle| { + let mobile = identity_metadata(world, handle) + .ok() + .and_then(|identity| drafts.get(identity.original_id?.0 as usize)) + .and_then(|draft| draft.unit_dat_header_flags) + .is_some_and(|class| class & crate::autodemo::MOBILE_UNIT != 0); + mobile + && transform_state(world, handle).is_ok_and(|pose| { + within_factory_radius(position, pose.position.map(f32::from_bits)) + }) + }); + Some(( + id, + guards + .map(|handle| unit_strength(controls, handle)) + .fold(0.0, |sum, amount| sum + amount), + )) +} + +fn within_factory_radius([x, y, _]: [f32; 3], [px, py, _]: [f32; 3]) -> bool { + (x - px).hypot(y - py) < 250.0 +} + pub(super) fn capture_target( mission: &MissionDocument, drafts: &[MissionObjectDraft], @@ -174,28 +216,7 @@ pub(super) fn attack_target( radius: f32, base_radius_limit: f32, ) -> Option<(u32, f32)> { - let anchor = mission - .clans - .get(clan)? - .anchor - .map(|axis| (axis.round_ties_even() as i64 as u32) as f32); - let distance = |[x, y, _]: [f32; 3]| (x - anchor[0]).hypot(y - anchor[1]); - let base_radius = base_radius( - base_radius_limit, - drafts.iter().filter_map(|draft| { - (draft.unit_dat_header_flags? & 0x8000_0000 != 0).then_some(())?; - let handle = handle_by_original_id(world, draft.original_id?)?; - registration_sequence(world, handle).ok()??; - (usize::from(identity_metadata(world, handle).ok()?.owner_id?.0) == clan) - .then_some(())?; - Some(distance( - transform_state(world, handle) - .ok()? - .position - .map(f32::from_bits), - )) - }), - ); + let (anchor, base_radius) = clan_area(mission, drafts, world, clan, base_radius_limit)?; building_target( mission, drafts, @@ -207,12 +228,100 @@ pub(super) fn attack_target( // initializing it here. Use the map origin for a stable estimate. Some([0.0; 3]), |_, _, position| { - let distance = distance(position); + let distance = distance_from_anchor(anchor, position); (distance >= base_radius).then_some(distance) }, ) } +pub(super) fn base_threat( + mission: &MissionDocument, + drafts: &[MissionObjectDraft], + controls: &[MissionControlDeviceTableState], + world: &World, + clan: usize, + extension: u32, + limit: f32, + already_targeted: impl Fn(u32) -> bool, +) -> Option<(u32, f32)> { + let (anchor, radius) = clan_area(mission, drafts, world, clan, limit)?; + let source = mission.clans.get(clan)?; + // shortcut: use placed logical IDs and mission order until the ArealMap roster is wired. + let candidates = drafts + .iter() + .take(mission.objects.len()) + .filter_map(|draft| { + let class = draft.unit_dat_header_flags?; + let id = draft.identity_or_clan_raw; + if class & crate::autodemo::MOBILE_UNIT == 0 || id == u32::MAX || already_targeted(id) { + return None; + } + let handle = handle_by_original_id(world, draft.original_id?)?; + registration_sequence(world, handle).ok()??; + let owner = usize::from(identity_metadata(world, handle).ok()?.owner_id?.0); + let other = mission.clans.get(owner)?; + if owner == clan + || !source.relations.iter().any(|relation| { + relation.relation_value == 0 && relation.other_clan_name.raw == other.name.raw + }) + { + return None; + } + let position = transform_state(world, handle) + .ok()? + .position + .map(f32::from_bits); + (distance_from_anchor(anchor, position).trunc() < radius + extension as f32) + .then(|| (id, class, unit_strength(controls, handle))) + }); + strongest_threat(candidates) +} + +fn strongest_threat(candidates: impl IntoIterator<Item = (u32, u32, f32)>) -> Option<(u32, f32)> { + let mut strongest = None; + for (id, class, strength) in candidates { + if class == crate::HERO_UNIT_CLASS { + return Some((id, strength)); + } + if strength > strongest.map_or(0.0, |(_, power)| power) { + strongest = Some((id, strength)); + } + } + strongest +} + +fn clan_area( + mission: &MissionDocument, + drafts: &[MissionObjectDraft], + world: &World, + clan: usize, + limit: f32, +) -> Option<([f32; 2], f32)> { + let anchor = mission + .clans + .get(clan)? + .anchor + .map(|axis| (axis.round_ties_even() as i64 as u32) as f32); + let distances = drafts.iter().filter_map(|draft| { + (draft.unit_dat_header_flags? & 0x8000_0000 != 0).then_some(())?; + let handle = handle_by_original_id(world, draft.original_id?)?; + registration_sequence(world, handle).ok()??; + (usize::from(identity_metadata(world, handle).ok()?.owner_id?.0) == clan).then_some(())?; + Some(distance_from_anchor( + anchor, + transform_state(world, handle) + .ok()? + .position + .map(f32::from_bits), + )) + }); + Some((anchor, base_radius(limit, distances))) +} + +fn distance_from_anchor([ax, ay]: [f32; 2], [x, y, _]: [f32; 3]) -> f32 { + (x - ax).hypot(y - ay) +} + fn base_radius(limit: f32, distances: impl IntoIterator<Item = f32>) -> f32 { let furthest = distances .into_iter() @@ -333,4 +442,23 @@ mod tests { assert_eq!(encode_strength(8.2), 8.0); assert_eq!(encode_strength(1e12), 3_567_583_232.0); } + + #[test] + fn factory_defence_uses_a_strict_horizontal_radius() { + assert!(within_factory_radius([100., 100., 75.], [249., 100., 0.])); + assert!(!within_factory_radius([100., 100., 75.], [250., 300., 75.])); + } + + #[test] + fn threats_prioritize_the_hero_and_keep_the_first_equal_strength() { + let bots = [ + (7, crate::boarding::WARBOT_CLASS, 40.), + (9, crate::boarding::WARBOT_CLASS, 40.), + ]; + assert_eq!(strongest_threat(bots), Some((7, 40.))); + assert_eq!( + strongest_threat(bots.into_iter().chain([(3, crate::HERO_UNIT_CLASS, 0.)])), + Some((3, 0.)) + ); + } } diff --git a/crates/fparkan-runtime/src/lib.rs b/crates/fparkan-runtime/src/lib.rs index 56063ca9..aca04ebd 100644 --- a/crates/fparkan-runtime/src/lib.rs +++ b/crates/fparkan-runtime/src/lib.rs @@ -2931,6 +2931,8 @@ pub struct SimulationReport { pub script_strength_queries: Vec<(usize, u16, u64)>, pub script_capture_queries: Vec<(usize, u64)>, pub script_attack_queries: Vec<(usize, u64)>, + pub script_factory_defence_queries: Vec<(usize, u32, u64)>, + pub script_base_threat_queries: Vec<(usize, u32, u64)>, pub script_group_orders: Vec<(usize, u32, u64)>, pub script_problem_waits: Vec<(usize, u32, u64)>, pub script_capturer_queries: Vec<(usize, u64)>, @@ -2979,6 +2981,8 @@ pub fn simulate_mission_report( script_strength_queries: Vec::new(), script_capture_queries: Vec::new(), script_attack_queries: Vec::new(), + script_factory_defence_queries: Vec::new(), + script_base_threat_queries: Vec::new(), script_group_orders: Vec::new(), script_problem_waits: Vec::new(), script_capturer_queries: Vec::new(), @@ -3069,6 +3073,12 @@ pub fn simulate_mission_report( .script_attack_queries .extend(loaded.clan_ai_events.attack_queries()); report + .script_factory_defence_queries + .extend(loaded.clan_ai_events.factory_defence_queries()); + report + .script_base_threat_queries + .extend(loaded.clan_ai_events.base_threat_queries()); + report .script_group_orders .extend(loaded.clan_ai_events.group_orders()); report diff --git a/crates/fparkan-runtime/src/mission_events.rs b/crates/fparkan-runtime/src/mission_events.rs index e90743fd..c19c53f8 100644 --- a/crates/fparkan-runtime/src/mission_events.rs +++ b/crates/fparkan-runtime/src/mission_events.rs @@ -157,7 +157,7 @@ impl MissionEvents { world: &'a World, owner: OwnerId, free_only: bool, - ) -> impl Iterator<Item = ObjectHandle> + 'a { + ) -> impl Iterator<Item = ObjectHandle> + Clone + 'a { self.placed_clan_objects .iter() .filter_map(move |&(handle, class)| { |
