From 04ac1b927abde1e5e448718f94834de83a01fff8 Mon Sep 17 00:00:00 2001 From: Valentin Popov Date: Sat, 14 Nov 2026 22:38:25 +0400 Subject: feat(ai): send scripted capturers toward hostile buildings Single.01 dispatches its placed warbot and later factory robots from stock startup. Approach uses the shared movement task. Ownership transfer, native approach points and the script completion expressions remain open. --- crates/fparkan-runtime/src/clan_ai_events.rs | 69 +++++++++++++++ crates/fparkan-runtime/src/clan_targeting.rs | 126 ++++++++++++++++++++++++++- crates/fparkan-runtime/src/lib.rs | 10 +++ crates/fparkan-runtime/src/mission_events.rs | 2 +- 4 files changed, 205 insertions(+), 2 deletions(-) (limited to 'crates') diff --git a/crates/fparkan-runtime/src/clan_ai_events.rs b/crates/fparkan-runtime/src/clan_ai_events.rs index 17e57b76..7e83a7e9 100644 --- a/crates/fparkan-runtime/src/clan_ai_events.rs +++ b/crates/fparkan-runtime/src/clan_ai_events.rs @@ -21,6 +21,14 @@ pub(super) fn tick(engine: &mut crate::Engine, now_ms: u32) { let Some(loaded) = &mut engine.loaded else { return; }; + loaded + .clan_ai_events + .capture_orders + .retain(|&(owner, _, unit, target)| { + identity_metadata(&engine.world, unit).is_ok_and(|unit| unit.owner_id == Some(owner)) + && identity_metadata(&engine.world, target) + .is_ok_and(|target| target.owner_id != Some(owner)) + }); let active = &mut loaded.clan_ai_events.factory_jobs; active.retain(|((clan, _), plant)| { engine @@ -88,6 +96,9 @@ pub(super) struct ClanAiEvents { factory_rejections: BTreeMap<(u16, u32), u64>, strength_queries: BTreeMap<(usize, u16), u64>, capture_queries: BTreeMap, + capturer_queries: BTreeMap, + capture_orders: Vec<(OwnerId, Handler2RecordKey, ObjectHandle, ObjectHandle)>, + capture_approaches: BTreeMap<(u32, u32), u64>, } impl LoadedMissionState { @@ -132,6 +143,7 @@ impl LoadedMissionState { let mut solved = false; let mut assignment = None; let mut solving = false; + let mut capturer = None; let result = varset.declarations.execute_event_prefix( event, bundle.formula_table.as_ref(), @@ -259,6 +271,22 @@ impl LoadedMissionState { .declarations .resolve_handler15_with_values(instruction, values) .map_err(|error| error.to_string())?; + if let (0x11, 3, Handler15TargetPayload::ByLogicId(target_id)) = + (order.word_1, order.word_2, order.target) + { + let unit = capturer.filter(|unit: &crate::clan_targeting::Capturer| unit.id == order.word_0) + .ok_or("Handler(15) capture requires a selected capturer")?; + let problem = problem.as_ref() + .ok_or("Handler(15) capture requires a current problem")?; + let approach = crate::clan_targeting::send_capturer( + &mut self.unit_patrol, world, &self.object_drafts, unit, target_id, + ); + if let Some((unit, target)) = approach { + self.clan_ai_events.capture_orders.push((OwnerId(clan as u16), problem.key, unit, target)); + *self.clan_ai_events.capture_approaches.entry((unit.slot, target.slot)).or_default() += 1; + } + return Ok(Some(VarSetDefault::Dword(u32::from(approach.is_some())))); + } if order.word_1 == 0x0a && order.word_2 == 3 && order.word_3 == 0 @@ -400,6 +428,28 @@ impl LoadedMissionState { Ok(None) } ScriptDispatchSelector::Handler(14) if problem.is_some() => { + if let &[mode, target_mode, target] = instruction.references.as_slice() { + let word = |index: u32| values.get(index as usize)?.as_dword(); + let (Some(4), Some(0x201), Some(target)) = + (word(mode), word(target_mode), word(target)) + else { + return Err("Handler(14) requires a logical ID for nearest capturer selection".into()); + }; + 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(|&(_, _, unit, _)| unit == handle) + && self.unit_patrol.as_ref().is_none_or(|patrol| !patrol.is_shut_down(handle)) + }, + ); + let id = capturer.map_or(u32::MAX, |unit| unit.id); + let count = self.clan_ai_events.capturer_queries.entry(clan).or_default(); + *count += 1; + if *count == 1 { + eprintln!("sim_coverage script_nearest_capturer_approx=1 clan={clan} target={target} unit={id}"); + } + return Ok(Some(VarSetDefault::Dword(id))); + } let (mode, class) = instruction .dword_pair(values) .ok_or("Handler(14) requires a unit mode and class")?; @@ -597,6 +647,13 @@ impl LoadedMissionState { .factory_jobs .iter() .any(|&(key, _)| key == (clan as u16, problem.key)) + || self + .clan_ai_events + .capture_orders + .iter() + .any(|&(owner, key, _, _)| { + owner == OwnerId(clan as u16) && key == problem.key + }) { continue; } @@ -726,12 +783,24 @@ fn storage_space(ores: &[BehaviorOreState], world: &World, clan: OwnerId) -> f32 } impl ClanAiEvents { + pub(super) fn capture_approaches(&self) -> impl Iterator + '_ { + self.capture_approaches + .iter() + .map(|(&(unit, target), &count)| (unit, target, count)) + } + pub(super) fn capture_queries(&self) -> impl Iterator + '_ { self.capture_queries .iter() .map(|(&clan, &count)| (clan, count)) } + pub(super) fn capturer_queries(&self) -> impl Iterator + '_ { + self.capturer_queries + .iter() + .map(|(&clan, &count)| (clan, count)) + } + pub(super) fn strength_queries(&self) -> impl Iterator + '_ { self.strength_queries .iter() diff --git a/crates/fparkan-runtime/src/clan_targeting.rs b/crates/fparkan-runtime/src/clan_targeting.rs index f8c1b4ca..05ac970a 100644 --- a/crates/fparkan-runtime/src/clan_targeting.rs +++ b/crates/fparkan-runtime/src/clan_targeting.rs @@ -3,9 +3,99 @@ use crate::{ MissionObjectDraft, }; use fparkan_world::{ - handle_by_original_id, identity_metadata, registration_sequence, transform_state, World, + handle_by_original_id, identity_metadata, registration_sequence, transform_state, ObjectHandle, + OwnerId, World, }; +#[derive(Clone, Copy)] +pub(super) struct Capturer { + handle: ObjectHandle, + target: ObjectHandle, + pub(super) id: u32, + target_id: u32, +} + +pub(super) fn send_capturer( + patrol: &mut Option, + world: &World, + drafts: &[MissionObjectDraft], + unit: Capturer, + target_id: u32, +) -> Option<(ObjectHandle, ObjectHandle)> { + let pose = transform_state(world, unit.target).ok()?; + let target = identity_metadata(world, unit.target).ok()?; + if unit.target_id != target_id + || target_id & 0x8000_0000 == 0 + || target.owner_id == identity_metadata(world, unit.handle).ok()?.owner_id + || target + .original_id + .and_then(|id| drafts.get(id.0 as usize)) + .and_then(|draft| draft.unit_dat_header_flags) + == Some(0x8000_0200) + { + return None; + } + let [x, y, _] = pose.position.map(f32::from_bits); + // shortcut: route towards the building; native entrance selection and capture are still open. + patrol + .get_or_insert_with(crate::unit_patrol::UnitPatrol::scripted) + .move_to(world, unit.handle, [x, y], false); + eprintln!( + "sim_coverage script_capture_approach_stub=1 unit={} target={} target_id={target_id}", + unit.handle.slot, unit.target.slot + ); + Some((unit.handle, unit.target)) +} + +pub(super) fn nearest_capturer( + mission: &MissionDocument, + drafts: &[MissionObjectDraft], + roster: &crate::mission_events::MissionEvents, + world: &World, + owner: OwnerId, + target_id: u32, + available: impl Fn(ObjectHandle) -> bool, +) -> Option { + let target = crate::mission_events::placed_logic_objects(mission, world, target_id).next()?; + let point = transform_state(world, target) + .ok()? + .position + .map(f32::from_bits); + // shortcut: all routed robots currently share one speed, so travel time ranks by XY distance. + roster + .clan_units(world, owner, true) + .filter(|&handle| available(handle)) + .filter_map(|handle| { + let original_id = identity_metadata(world, handle).ok()?.original_id?.0; + let index = original_id as usize; + let chassis = drafts.get(index)?.unit_components.first()?; + if !crate::mission_events::capturer_chassis(&chassis.resource_raw) { + return None; + } + let position = transform_state(world, handle) + .ok()? + .position + .map(f32::from_bits); + let distance = (point[0] - position[0]).hypot(point[1] - position[1]); + // shortcut: generated ID is local to this script section until native robot IDs are allocated. + let id = mission + .objects + .get(index) + .map_or(original_id, |object| object.identity_or_clan_raw); + (id != u32::MAX).then_some(( + Capturer { + handle, + target, + id, + target_id, + }, + distance, + )) + }) + .min_by(|(_, a), (_, b)| a.total_cmp(b)) + .map(|(unit, _)| unit) +} + pub(super) fn encode_strength(strength: f32) -> f32 { // The original narrows the truncated x87 result to a DWORD before the script assignment. (strength as i64 as u32) as f32 @@ -73,6 +163,40 @@ fn building_priority(class: u32) -> u8 { mod tests { use super::*; + #[test] + fn capture_order_replaces_patrol_and_rejects_a_friendly_target() { + use fparkan_world::{ + construct_object, new, register_object, set_owner, ObjectDraft, WorldConfig, + }; + + let mut world = new(WorldConfig); + let mut create = |owner| { + let handle = construct_object(&mut world, ObjectDraft { original_id: None }).unwrap(); + register_object(&mut world, handle).unwrap(); + set_owner(&mut world, handle, Some(OwnerId(owner))).unwrap(); + handle + }; + let handle = create(1); + let target = create(0); + let capturer = Capturer { + handle, + target, + id: 3, + target_id: 0x8000_0002, + }; + let mut patrol = None; + assert_eq!( + send_capturer(&mut patrol, &world, &[], capturer, capturer.target_id), + Some((handle, target)) + ); + assert!(patrol.as_ref().unwrap().is_moving_to_destination(handle)); + set_owner(&mut world, target, Some(OwnerId(1))).unwrap(); + assert_eq!( + send_capturer(&mut patrol, &world, &[], capturer, capturer.target_id), + None + ); + } + #[test] fn generators_and_factories_rank_ahead_of_other_buildings() { let classes = [ diff --git a/crates/fparkan-runtime/src/lib.rs b/crates/fparkan-runtime/src/lib.rs index 475a4c2c..5eefdd33 100644 --- a/crates/fparkan-runtime/src/lib.rs +++ b/crates/fparkan-runtime/src/lib.rs @@ -2913,6 +2913,8 @@ pub struct SimulationReport { /// Approximate clan strength queries, grouped by caller and target clan. pub script_strength_queries: Vec<(usize, u16, u64)>, pub script_capture_queries: Vec<(usize, u64)>, + pub script_capturer_queries: Vec<(usize, u64)>, + pub script_capture_approaches: Vec<(u32, u32, u64)>, /// First factory completion by clan, in milliseconds. pub first_factory_completion_ms: std::collections::BTreeMap, /// Total requests for mission information messages. @@ -2956,6 +2958,8 @@ pub fn simulate_mission_report( script_factory_orders: Vec::new(), script_strength_queries: Vec::new(), script_capture_queries: Vec::new(), + script_capturer_queries: Vec::new(), + script_capture_approaches: Vec::new(), first_factory_completion_ms: Default::default(), mission_messages: 0, autodemo_first_shot_ms: None, @@ -3038,6 +3042,12 @@ pub fn simulate_mission_report( report .script_capture_queries .extend(loaded.clan_ai_events.capture_queries()); + report + .script_capturer_queries + .extend(loaded.clan_ai_events.capturer_queries()); + report + .script_capture_approaches + .extend(loaded.clan_ai_events.capture_approaches()); } Ok(report) } diff --git a/crates/fparkan-runtime/src/mission_events.rs b/crates/fparkan-runtime/src/mission_events.rs index d13b6327..ee189ca9 100644 --- a/crates/fparkan-runtime/src/mission_events.rs +++ b/crates/fparkan-runtime/src/mission_events.rs @@ -892,7 +892,7 @@ fn inside_exit_volume([x, y, z]: [f32; 3], [px, py, pz]: [f32; 3]) -> bool { (pz - z).abs() <= 3.0 && (px - x).powi(2) + (py - y).powi(2) <= 25.0 } -fn capturer_chassis(chassis: &[u8; 32]) -> bool { +pub(super) fn capturer_chassis(chassis: &[u8; 32]) -> bool { // shortcut: stock robot keys map to native size classes 1 and 2; // query the effective Behavior controller when custom types are supported. matches!( -- cgit v1.2.3