diff options
| author | Valentin Popov <valentin@popov.link> | 2026-11-26 23:55:21 +0300 |
|---|---|---|
| committer | Valentin Popov <valentin@popov.link> | 2026-11-26 23:55:21 +0300 |
| commit | 7a888d0cde24576a7b36576d26dd9931e3ae8543 (patch) | |
| tree | 614a890305fdd48a1d931aa7dec1f18f426573dc | |
| parent | 65c6181e0ea03fe063c1b2ec588824d1aaf0ef90 (diff) | |
| download | fparkan-7a888d0cde24576a7b36576d26dd9931e3ae8543.tar.xz fparkan-7a888d0cde24576a7b36576d26dd9931e3ae8543.zip | |
fix(ai): rank capturers by Control travel time
The Handler(14) oracle executes ai.dll with the real Control selector 0x91 and verifies faster distant candidates, the one-second bias and the minimum speed. Use the same current forward limit in the stock capture query. Original roster ordering and task preemption remain approximate.
| -rw-r--r-- | crates/fparkan-runtime/src/clan_ai_events.rs | 8 | ||||
| -rw-r--r-- | crates/fparkan-runtime/src/clan_targeting.rs | 37 | ||||
| -rw-r--r-- | docs/appendices/knowledge-boundaries.md | 5 | ||||
| -rw-r--r-- | docs/tomes/06-behavior.md | 13 |
4 files changed, 49 insertions, 14 deletions
diff --git a/crates/fparkan-runtime/src/clan_ai_events.rs b/crates/fparkan-runtime/src/clan_ai_events.rs index ee19f56e..9d035503 100644 --- a/crates/fparkan-runtime/src/clan_ai_events.rs +++ b/crates/fparkan-runtime/src/clan_ai_events.rs @@ -1028,8 +1028,12 @@ 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.unit_assigned(handle) - && self.unit_patrol.as_ref().is_none_or(|patrol| !patrol.is_shut_down(handle)) + if self.clan_ai_events.unit_assigned(handle) + || self.unit_patrol.as_ref().is_some_and(|patrol| patrol.is_shut_down(handle)) + { + return None; + } + self.control_device_tables.iter().find(|table| table.handle == handle) }, ); let id = capturer.map_or(u32::MAX, |unit| unit.id); diff --git a/crates/fparkan-runtime/src/clan_targeting.rs b/crates/fparkan-runtime/src/clan_targeting.rs index 0555e0fb..ef580e43 100644 --- a/crates/fparkan-runtime/src/clan_targeting.rs +++ b/crates/fparkan-runtime/src/clan_targeting.rs @@ -107,25 +107,24 @@ fn at_platform([x, y, z]: [f32; 3], [tx, ty, tz]: [f32; 3]) -> bool { (x - tx).hypot(y - ty) <= 0.05 && (z - tz).abs() <= 2.0 } -pub(super) fn nearest_capturer( +pub(super) fn nearest_capturer<'a>( mission: &MissionDocument, drafts: &[MissionObjectDraft], roster: &crate::mission_events::MissionEvents, world: &World, owner: OwnerId, target_id: u32, - available: impl Fn(ObjectHandle) -> bool, + available_control: impl Fn(ObjectHandle) -> Option<&'a MissionControlDeviceTableState>, ) -> Option<Capturer> { 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 profile = available_control(handle)?.owner_profile.as_ref()?; 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()?; @@ -136,7 +135,8 @@ pub(super) fn nearest_capturer( .ok()? .position .map(f32::from_bits); - let distance = (point[0] - position[0]).hypot(point[1] - position[1]); + let score = + capture_arrival_score(position, point, f32::from_bits(profile.current_words[7]))?; // shortcut: generated ID is local to this script section until native robot IDs are allocated. let id = mission .objects @@ -149,13 +149,26 @@ pub(super) fn nearest_capturer( id, target_id, }, - distance, + score, )) }) .min_by(|(_, a), (_, b)| a.total_cmp(b)) .map(|(unit, _)| unit) } +fn capture_arrival_score([x, y, _]: [f32; 3], [tx, ty, _]: [f32; 3], speed: f32) -> Option<f32> { + if !speed.is_finite() || speed <= 1.0 { + return None; + } + let distance = (tx - x).hypot(ty - y); + let score = if distance <= speed { + 0.0 + } else { + distance / speed + }; + (score < 1e9).then_some(score) +} + 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 @@ -458,6 +471,18 @@ mod tests { use super::*; #[test] + fn capture_arrival_uses_the_live_speed_and_scores_a_one_second_approach_as_zero() { + let score = |x, speed| capture_arrival_score([x, 0.0, 800.0], [0.0; 3], speed); + assert_eq!(score(20.0, 2.0), Some(10.0)); + assert_eq!(score(30.0, 10.0), Some(3.0)); + assert_eq!(score(7.0, 9.0), Some(0.0)); + assert_eq!(score(2.0, 3.0), Some(0.0)); + assert_eq!(score(3.0, 3.0), Some(0.0)); + assert_eq!(score(0.0, 1.0), None); + assert_eq!(score(0.0, 0.5), None); + } + + #[test] fn defence_selects_the_smallest_strength_and_keeps_the_first_tie() { assert_eq!( least_defended([(1, 8.0), (2, 4.0), (3, 4.0)].into_iter()), diff --git a/docs/appendices/knowledge-boundaries.md b/docs/appendices/knowledge-boundaries.md index 2dedeb42..cae2811e 100644 --- a/docs/appendices/knowledge-boundaries.md +++ b/docs/appendices/knowledge-boundaries.md @@ -661,8 +661,9 @@ ID выпущенной машины внутренний. Подъезд исп `script_capture_target_approx` считает запросы `Handler(35)` по кланам. Для выбора цели и оценки охраны используется реестр размещённых объектов. Порядок областей ArealMap и учёт произведённых роботов открыты. -`script_nearest_capturer_approx` отмечает выбор по расстоянию при общей скорости -роботов. `script_capture_approach_stub` считает заявки, где недоступен +`script_nearest_capturer_approx` отмечает оценку подхода по текущему пределу +Control. Порядок записей нативного реестра и вытеснение прежних задач открыты. +`script_capture_approach_stub` считает заявки, где недоступен проход по Res17. Поддержаны свободные связи и симметричные связи с дверью CTLD типа 12. Открыты точный темп двери, остальные условия связи, выход из рубки и резервный обход BAS. diff --git a/docs/tomes/06-behavior.md b/docs/tomes/06-behavior.md index b4d06797..8792c097 100644 --- a/docs/tomes/06-behavior.md +++ b/docs/tomes/06-behavior.md @@ -374,10 +374,15 @@ Control. Снаряд использует скорость, время жизн `c19cd6cd31cd2896f8c4ba0f0e700dd3408aec8182daaf4863d98a7d233a2abc`. Секция заявки обращается к `Handler(14)` за варботом с лёгким или малым шасси -и передаёт его ID в `ORDER_ROBOT_CAPTURE`. В оригинале обработчик по RVA -`0x8a99` сравнивает оценки времени подхода по расстоянию и скорости. В -FParkan скорость движения пока общая, поэтому достаточно сравнить расстояния. -Если подходящий робот ещё собирается, он становится кандидатом после выпуска. +и передаёт его ID в `ORDER_ROBOT_CAPTURE`. `ai.dll` по RVA `0x8a99` +делит расстояние в плоскости карты на текущий передний предел Control, +который селектор `0x91` читает из профиля. При пределе в одну единицу +в секунду и ниже кандидат пропускается. Если варбот покрывает расстояние +за секунду, его оценка равна нулю. При равных оценках сохраняется первый +кандидат. Вызов оригинальных `ai.dll` и `Control.dll` подтвердил, например, +выбор варбота в 30 единицах со скоростью 10 вместо варбота в 20 единицах +со скоростью 2. Если варбот ещё собирается, FParkan включает его в список +после выпуска. Задача оригинала сначала пытается войти в строение (`Behavior.dll`, RVA `0x3094f`). Ветка `0x1402` запрашивает граф проходов и передаёт маску |
