From a24f98ec17ae4a0713062fb2718f7b6399fcd518 Mon Sep 17 00:00:00 2001 From: Valentin Popov Date: Sat, 14 Nov 2026 18:11:20 +0400 Subject: fix(ai): keep patrol attacks within their assigned area --- crates/fparkan-runtime/src/unit_patrol.rs | 60 +++++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) (limited to 'crates/fparkan-runtime/src/unit_patrol.rs') diff --git a/crates/fparkan-runtime/src/unit_patrol.rs b/crates/fparkan-runtime/src/unit_patrol.rs index cfbee245..205af4ea 100644 --- a/crates/fparkan-runtime/src/unit_patrol.rs +++ b/crates/fparkan-runtime/src/unit_patrol.rs @@ -35,6 +35,24 @@ pub(super) struct PreparedPatrol { poses: Vec<(ObjectHandle, TransformState, TransformState)>, } +#[derive(Clone, Copy)] +pub(super) struct PatrolAttackLimit { + center: [f32; 2], + radius: f32, + current_target: Option, +} + +impl PatrolAttackLimit { + pub(super) fn allows_attack(self, position: [f32; 3]) -> bool { + distance_to_patrol(self.center, position) <= self.radius + 60.0 + } + + pub(super) fn allows_target(self, target: ObjectHandle, position: [f32; 3]) -> bool { + self.current_target == Some(target) + || distance_to_patrol(self.center, position) < self.radius + } +} + impl UnitPatrol { pub(super) fn approximate_factory_raid( &mut self, @@ -163,6 +181,19 @@ impl UnitPatrol { .raid_factory } + pub(super) fn attack_limit(&self, handle: ObjectHandle) -> Option { + // A raid starts with an explicit attack order. It never receives PatrolPlace limits. + let unit = self + .units + .iter() + .find(|unit| unit.handle == handle && unit.raid_factory.is_none())?; + Some(PatrolAttackLimit { + center: unit.center, + radius: unit.radius, + current_target: unit.attack, + }) + } + pub(super) fn activate(&mut self, world: &World, handle: ObjectHandle) { if let Some(center) = self.center { self.order(world, handle, center, 150.0); @@ -293,6 +324,35 @@ impl UnitPatrol { } } +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) +} + +#[cfg(test)] +#[test] +fn patrol_limits_new_targets_and_ends_pursuit_at_the_outer_boundary() { + let tracked = ObjectHandle { + slot: 1, + generation: 1, + }; + let candidate = ObjectHandle { + slot: 2, + generation: 1, + }; + let patrol = PatrolAttackLimit { + center: [500.0, 752.0], + radius: 150.0, + current_target: Some(tracked), + }; + assert!(patrol.allows_target(candidate, [649.0, 752.0, 0.0])); + assert!(!patrol.allows_target(candidate, [650.0, 752.0, 0.0])); + assert!(patrol.allows_target(tracked, [650.0, 752.0, 0.0])); + assert!(patrol.allows_attack([710.0, 752.0, 0.0])); + assert!(!patrol.allows_attack([711.0, 752.0, 0.0])); + assert!(!patrol.allows_attack([650.0, 902.0, 0.0])); +} + fn turn_toward(pose: TransformState, [dx, dy]: [f32; 2], seconds: f32) -> (f32, f32) { let yaw = f32::from_bits(pose.orientation[2]); let goal_yaw = (-dx).atan2(dy); -- cgit v1.2.3