From e1f26ba007532eca4b6afe4d49aca58799c1ce05 Mon Sep 17 00:00:00 2001 From: Valentin Popov Date: Sat, 14 Nov 2026 23:04:26 +0400 Subject: feat(ai): dispatch scripted warbot groups Single.01 selects a free warbot for the capture problem and issues a patrol around the moving capturer from stock startup. Group recruitment uses the supported TAKE_BY_HITS branch. Priority preemption and group expression scheduling remain open. --- crates/fparkan-runtime/src/clan_ai_events.rs | 88 ++++++++++++++++- crates/fparkan-runtime/src/clan_combat_groups.rs | 119 +++++++++++++++++++++++ crates/fparkan-runtime/src/lib.rs | 37 ++++--- crates/fparkan-runtime/src/unit_patrol.rs | 11 +++ 4 files changed, 242 insertions(+), 13 deletions(-) create mode 100644 crates/fparkan-runtime/src/clan_combat_groups.rs (limited to 'crates/fparkan-runtime/src') diff --git a/crates/fparkan-runtime/src/clan_ai_events.rs b/crates/fparkan-runtime/src/clan_ai_events.rs index 565fd41f..bc4e7408 100644 --- a/crates/fparkan-runtime/src/clan_ai_events.rs +++ b/crates/fparkan-runtime/src/clan_ai_events.rs @@ -1,4 +1,4 @@ -use crate::clan_targeting::CaptureApproach; +use crate::{clan_combat_groups::CombatGroup, clan_targeting::CaptureApproach}; use crate::{BehaviorOreState, LoadedMissionState, MissionEventStop}; use fparkan_script::{ Handler15TargetPayload, Handler2Record, Handler2RecordInput, Handler2RecordKey, @@ -75,6 +75,27 @@ pub(super) fn tick(engine: &mut crate::Engine, now_ms: u32) { let Some(loaded) = &mut engine.loaded else { return; }; + loaded.clan_ai_events.groups.retain(|&(clan, _), group| { + if !identity_metadata(&engine.world, group.target) + .is_ok_and(|identity| identity.owner_id == group.target_owner) + { + if let Some(patrol) = &mut loaded.unit_patrol { + for &member in &group.members { + patrol.clear_object_order(member, group.target); + } + } + return false; + } + group.members.retain(|&member| { + identity_metadata(&engine.world, member) + .is_ok_and(|identity| identity.owner_id == Some(OwnerId(clan as u16))) + && loaded + .unit_patrol + .as_ref() + .is_some_and(|patrol| patrol.has_object_order(member, group.target)) + }); + !group.members.is_empty() + }); let active = &mut loaded.clan_ai_events.factory_jobs; active.retain(|((clan, _), plant)| { engine @@ -147,6 +168,8 @@ pub(super) struct ClanAiEvents { capturer_queries: BTreeMap, capture_orders: Vec<(OwnerId, Handler2RecordKey, CaptureApproach)>, capture_approaches: BTreeMap<(u32, u32), u64>, + groups: BTreeMap<(usize, Handler2RecordKey), CombatGroup>, + group_orders: BTreeMap<(usize, u32), u64>, } impl LoadedMissionState { @@ -192,6 +215,7 @@ impl LoadedMissionState { let mut assignment = None; let mut solving = false; let mut capturer = None; + let mut group = None; let result = varset.declarations.execute_event_prefix( event, bundle.formula_table.as_ref(), @@ -262,6 +286,45 @@ impl LoadedMissionState { } Ok(Some(VarSetDefault::Dword(target))) } + ScriptDispatchSelector::Handler(25) if problem.is_some() => { + let &[mode, hits, target_mode, target] = instruction.references.as_slice() else { + return Err("Handler(25) requires TAKE_BY_HITS and a logical ID".into()); + }; + let word = |index: u32| values.get(index as usize)?.as_dword(); + let (Some(2), Some(requested), Some(0x201), Some(target)) = + (word(mode), word(hits), word(target_mode), word(target)) + else { + return Err("Handler(25) requires TAKE_BY_HITS and a logical ID".into()); + }; + // shortcut: use free warbots until lower-priority orders can be preempted. + let units = self.mission_events.clan_units(world, OwnerId(clan as u16), true) + .filter(|&unit| !self.clan_ai_events.unit_assigned(unit)) + .filter(|&unit| self.unit_patrol.as_ref().is_none_or(|patrol| !patrol.is_shut_down(unit))); + let (recruited, strength) = crate::clan_combat_groups::recruit( + world, units, &self.control_device_tables, &self.mission, target, requested, + ); + if strength < requested as f32 || strength == 0.0 { + values[hits as usize] = VarSetDefault::Dword(strength as u32); + } + group = recruited; + // shortcut: group IDs stay local until groups are script-visible across events. + Ok(Some(VarSetDefault::Dword(if group.is_some() { 0 } else { u32::MAX }))) + } + ScriptDispatchSelector::Handler(28) if problem.is_some() => { + let order = varset.declarations.resolve_handler15_with_values(instruction, values) + .map_err(|error| error.to_string())?; + let group = group.take().ok_or("Handler(28) requires an active combat group")?; + let patrol = self.unit_patrol.get_or_insert_with(crate::unit_patrol::UnitPatrol::scripted); + group.dispatch(patrol, world, &self.mission, order) + .ok_or("Handler(28) requires a patrol or attack on the group's target")?; + let key = problem.as_ref().expect("group order requires a problem").key; + let target = group.target.slot; + let count = self.clan_ai_events.group_orders.entry((clan, target)).or_default(); + *count += 1; + eprintln!("sim_coverage script_group_order_approx=1 clan={clan} target={target} order={} units={:?}", order.word_1, group.members.iter().map(|unit| unit.slot).collect::>()); + self.clan_ai_events.groups.insert((clan, key), group); + Ok(Some(VarSetDefault::Dword(1))) + } ScriptDispatchSelector::Handler(38) => { let (target, mode) = instruction.dword_pair(values) .ok_or("Handler(38) requires a clan and unit-selection mode")?; @@ -272,6 +335,7 @@ impl LoadedMissionState { return Ok(Some(VarSetDefault::Dword(0))); }; let sum = self.mission_events.clan_units(world, OwnerId(target), mode == 0) + .filter(|&handle| mode != 0 || !self.clan_ai_events.unit_assigned(handle)) .map(|handle| crate::clan_combat_strength::unit_strength(&self.control_device_tables, handle)) .fold(0.0, |sum, contribution| sum + contribution); let count = self.clan_ai_events.strength_queries.entry((clan, target)).or_default(); @@ -497,7 +561,7 @@ impl LoadedMissionState { capturer = crate::clan_targeting::nearest_capturer( &self.mission, &self.object_drafts, &self.mission_events, world, OwnerId(clan as u16), target, |handle| { - !self.clan_ai_events.capture_orders.iter().any(|&(_, _, order)| order.unit == handle) + !self.clan_ai_events.unit_assigned(handle) && self.unit_patrol.as_ref().is_none_or(|patrol| !patrol.is_shut_down(handle)) }, ); @@ -713,6 +777,10 @@ impl LoadedMissionState { .any(|&(owner, key, _)| { owner == OwnerId(clan as u16) && key == problem.key }) + || self + .clan_ai_events + .groups + .contains_key(&(clan, problem.key)) { continue; } @@ -842,6 +910,22 @@ fn storage_space(ores: &[BehaviorOreState], world: &World, clan: OwnerId) -> f32 } impl ClanAiEvents { + fn unit_assigned(&self, unit: ObjectHandle) -> bool { + self.capture_orders + .iter() + .any(|&(_, _, order)| order.unit == unit) + || self + .groups + .values() + .any(|group| group.members.contains(&unit)) + } + + pub(super) fn group_orders(&self) -> impl Iterator + '_ { + self.group_orders + .iter() + .map(|(&(clan, target), &count)| (clan, target, 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_combat_groups.rs b/crates/fparkan-runtime/src/clan_combat_groups.rs new file mode 100644 index 00000000..5b4cf453 --- /dev/null +++ b/crates/fparkan-runtime/src/clan_combat_groups.rs @@ -0,0 +1,119 @@ +use crate::clan_combat_strength::unit_strength; +use crate::unit_patrol::UnitPatrol; +use crate::{MissionControlDeviceTableState, MissionDocument}; +use fparkan_script::{Handler15Invocation, Handler15TargetPayload}; +use fparkan_world::{identity_metadata, transform_state, ObjectHandle, OwnerId, World}; + +pub(super) struct CombatGroup { + pub(super) members: Vec, + pub(super) target: ObjectHandle, + pub(super) target_owner: Option, +} + +pub(super) fn recruit( + world: &World, + units: impl Iterator, + controls: &[MissionControlDeviceTableState], + mission: &MissionDocument, + target_id: u32, + requested: u32, +) -> (Option, f32) { + let Some(target) = + crate::mission_events::placed_logic_objects(mission, world, target_id).next() + else { + return (None, 0.0); + }; + let Ok(pose) = transform_state(world, target) else { + return (None, 0.0); + }; + let [x, y, _] = pose.position.map(f32::from_bits); + let mut candidates: Vec<_> = units + .filter_map(|unit| { + let [ux, uy, _] = transform_state(world, unit) + .ok()? + .position + .map(f32::from_bits); + Some(((ux - x).hypot(uy - y), unit_strength(controls, unit), unit)) + }) + .collect(); + let (members, strength) = take_by_hits(&mut candidates, requested); + let group = (strength > 0.0).then(|| CombatGroup { + members, + target, + target_owner: identity_metadata(world, target) + .ok() + .and_then(|identity| identity.owner_id), + }); + (group, strength) +} + +fn take_by_hits( + candidates: &mut [(f32, f32, ObjectHandle)], + requested: u32, +) -> (Vec, f32) { + candidates.sort_by(|a, b| a.0.total_cmp(&b.0)); + let mut members = Vec::new(); + let mut strength = 0.0; + for &(_, power, member) in candidates.iter() { + members.push(member); + strength += power; + if strength >= requested as f32 { + break; + } + } + (members, strength) +} + +impl CombatGroup { + pub(super) fn dispatch( + &self, + patrol: &mut UnitPatrol, + world: &World, + mission: &MissionDocument, + order: Handler15Invocation, + ) -> Option<()> { + let (0, kind @ (3 | 4), 3, Handler15TargetPayload::ByLogicId(target_id)) = + (order.word_0, order.word_1, order.word_2, order.target) + else { + return None; + }; + let target = + crate::mission_events::placed_logic_objects(mission, world, target_id).next()?; + if target != self.target { + return None; + } + let index = identity_metadata(world, target).ok()?.original_id?.0 as usize; + let [x, y, _] = transform_state(world, target) + .ok()? + .position + .map(f32::from_bits); + for &unit in &self.members { + if kind == 3 { + patrol.set_attack_target(world, unit, target, index, [x, y]); + } else { + let radius = match order.word_3 { + 0 | u32::MAX => 60.0, + radius => radius as f32, + }; + patrol.order_around_object(world, unit, target, [x, y], radius); + } + } + Some(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn recruits_by_distance_until_the_threshold_and_keeps_partial_groups() { + let [a, b, c] = [1, 2, 3].map(|slot| ObjectHandle { + slot, + generation: 1, + }); + let mut candidates = [(18.0, 20.0, c), (8.0, 5.0, a), (15.0, 7.0, b)]; + assert_eq!(take_by_hits(&mut candidates, 12), (vec![a, b], 12.0)); + assert_eq!(take_by_hits(&mut candidates, 40), (vec![a, b, c], 32.0)); + } +} diff --git a/crates/fparkan-runtime/src/lib.rs b/crates/fparkan-runtime/src/lib.rs index 72c291b5..6c7f0fe7 100644 --- a/crates/fparkan-runtime/src/lib.rs +++ b/crates/fparkan-runtime/src/lib.rs @@ -45,6 +45,7 @@ mod autodemo; mod boarding; mod building_door; mod clan_ai_events; +mod clan_combat_groups; mod clan_combat_strength; mod clan_script_init; mod clan_targeting; @@ -2607,17 +2608,26 @@ fn load_mission_with_options( } } } - let autodemo_combat = (unit_patrol.is_some() || guard_clans.contains(&true)).then(|| { - unit_combat::AutoDemoCombat::new( - &vfs, - &mission, - &object_drafts, - &handles, - &mission_assets, - reserve_start, - guard_clans, - ) - }); + let periodic_ai = + options.start_autodemo + && loaded_scripts.bundles.iter().any(|bundle| { + mission.clans[bundle.clan_index].mode == 2 + && bundle.package.events.iter().any(|event| { + event.name_raw == b"Problems0\0" && !event.instructions.is_empty() + }) + }); + let autodemo_combat = (unit_patrol.is_some() || guard_clans.contains(&true) || periodic_ai) + .then(|| { + unit_combat::AutoDemoCombat::new( + &vfs, + &mission, + &object_drafts, + &handles, + &mission_assets, + reserve_start, + guard_clans, + ) + }); for &handle in &handles[reserve_start..] { fparkan_world::request_delete(&mut new_runtime_world, handle)?; } @@ -2920,6 +2930,7 @@ 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_group_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. @@ -2966,6 +2977,7 @@ pub fn simulate_mission_report( script_strength_queries: Vec::new(), script_capture_queries: Vec::new(), script_attack_queries: Vec::new(), + script_group_orders: Vec::new(), script_capturer_queries: Vec::new(), script_capture_approaches: Vec::new(), first_factory_completion_ms: Default::default(), @@ -3053,6 +3065,9 @@ pub fn simulate_mission_report( report .script_attack_queries .extend(loaded.clan_ai_events.attack_queries()); + report + .script_group_orders + .extend(loaded.clan_ai_events.group_orders()); report .script_capturer_queries .extend(loaded.clan_ai_events.capturer_queries()); diff --git a/crates/fparkan-runtime/src/unit_patrol.rs b/crates/fparkan-runtime/src/unit_patrol.rs index c4b3b969..bc2dc3a4 100644 --- a/crates/fparkan-runtime/src/unit_patrol.rs +++ b/crates/fparkan-runtime/src/unit_patrol.rs @@ -242,6 +242,17 @@ impl UnitPatrol { self.units.iter().any(|unit| unit.handle == handle) } + pub(super) fn has_object_order(&self, handle: ObjectHandle, target: ObjectHandle) -> bool { + self.units + .iter() + .any(|unit| unit.handle == handle && unit.center_object == Some(target)) + } + + pub(super) fn clear_object_order(&mut self, handle: ObjectHandle, target: ObjectHandle) { + self.units + .retain(|unit| unit.handle != handle || unit.center_object != Some(target)); + } + 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); -- cgit v1.2.3