diff options
| author | Valentin Popov <valentin@popov.link> | 2026-11-25 11:57:40 +0300 |
|---|---|---|
| committer | Valentin Popov <valentin@popov.link> | 2026-11-25 11:57:40 +0300 |
| commit | 6cce33ff5b29616fb3d5caf9325729068d0631eb (patch) | |
| tree | 87aac161166c735ef9924d088ab7498a0bafdee9 | |
| parent | c4439f993e3cd30f98acf65d0cd088abbb389232 (diff) | |
| download | fparkan-6cce33ff5b29616fb3d5caf9325729068d0631eb.tar.xz fparkan-6cce33ff5b29616fb3d5caf9325729068d0631eb.zip | |
feat(ai): select free factories for scripted production
Handler(13) UNIT_FREE_UNIT now selects the first live clan object of the
requested exact class. Reserved objects, assigned runtime workers and
busy factories are skipped. Coverage records each selected logical ID.
Campaign mission 8 can execute PBM_ROBOT_NEEDED and replenish its guards.
Original GOG ai.dll RVA 0x86fb confirmed roster order, exact class matching,
exclusion of busy and reserved entries, and ERROR when none are free.
Validated with matching Rust roster cases, a licensed stock mission 8
production test, fmt/check/test workspace, and 900-second simulations
of missions 8 and 28. Mission 8 also ran in the window with Vulkan validation.
Occupancy is inferred from runtime jobs; native problem-slot ownership,
other selection modes and mission chronology beside the original remain open.
| -rw-r--r-- | apps/fparkan-game/src/script_coverage.rs | 5 | ||||
| -rw-r--r-- | crates/fparkan-runtime/src/clan_ai_events.rs | 93 | ||||
| -rw-r--r-- | crates/fparkan-runtime/src/lib.rs | 5 | ||||
| -rw-r--r-- | crates/fparkan-runtime/src/mission_events.rs | 73 | ||||
| -rw-r--r-- | docs/appendices/knowledge-boundaries.md | 3 | ||||
| -rw-r--r-- | docs/tomes/06-behavior.md | 15 |
6 files changed, 182 insertions, 12 deletions
diff --git a/apps/fparkan-game/src/script_coverage.rs b/apps/fparkan-game/src/script_coverage.rs index 56d05436..fb1db2bc 100644 --- a/apps/fparkan-game/src/script_coverage.rs +++ b/apps/fparkan-game/src/script_coverage.rs @@ -52,6 +52,11 @@ pub(super) fn log_clan_ai_stops(report: &SimulationReport) { "sim_coverage script_point_patrol_continue_approx={count} clan={clan} x={x} y={y}" ); } + for &(clan, class, unit, count) in &report.script_free_unit_queries { + eprintln!( + "sim_coverage script_free_unit_approx={count} clan={clan} class={class} unit={unit}" + ); + } for &(clan, problem, count) in &report.script_problem_waits { eprintln!("sim_coverage script_problem_wait_approx={count} clan={clan} problem={problem}"); } diff --git a/crates/fparkan-runtime/src/clan_ai_events.rs b/crates/fparkan-runtime/src/clan_ai_events.rs index 99e568c6..5b28aaf2 100644 --- a/crates/fparkan-runtime/src/clan_ai_events.rs +++ b/crates/fparkan-runtime/src/clan_ai_events.rs @@ -250,6 +250,7 @@ pub(super) struct ClanAiEvents { group_orders: BTreeMap<(usize, u32), u64>, point_group_orders: BTreeMap<(usize, u32, u32), u64>, point_patrol_continues: BTreeMap<(usize, u32, u32), u64>, + free_unit_queries: BTreeMap<(usize, u32, u32), u64>, } impl LoadedMissionState { @@ -573,17 +574,30 @@ impl LoadedMissionState { // shortcut: include unfinished structures once construction registers with the roster. Ok(Some(VarSetDefault::Dword(u32::from(count >= limit)))) } - ScriptDispatchSelector::Handler(13) - if instruction.dword_pair(values) - == Some((0, crate::mining::MINE_CLASS)) => - { + ScriptDispatchSelector::Handler(13) => { + let (mode, class) = instruction.dword_pair(values) + .ok_or("Handler(13) requires a unit mode and class")?; + if mode != 0 { + return Err("Handler(13) only supports UNIT_FREE_UNIT".into()); + } + let owner = OwnerId(clan as u16); + // shortcut: infer roster occupancy from runtime jobs until native problem-slot ownership is wired. let id = self.mission_events.first_available_placed_unit( &self.mission, world, clan, - crate::mining::MINE_CLASS, - ); - Ok(Some(VarSetDefault::Dword(id.unwrap_or(u32::MAX)))) + class, + |unit| !self.clan_ai_events.unit_assigned(unit) + && !self.construction.active(unit) + && !production.is_some_and(|queue| queue.is_building_at(unit, owner)) + && !orders.iter().any(|order: &ScriptFactoryOrder| order.plant == unit), + ).unwrap_or(u32::MAX); + let count = self.clan_ai_events.free_unit_queries.entry((clan, class, id)).or_default(); + *count += 1; + if *count == 1 { + eprintln!("sim_coverage script_free_unit_approx=1 clan={clan} class={class} unit={id}"); + } + Ok(Some(VarSetDefault::Dword(id))) } ScriptDispatchSelector::Handler(15) => { let order = varset @@ -891,7 +905,7 @@ impl LoadedMissionState { return Err("Handler(14) only supports UNIT_ANY_UNIT".into()); } let id = self.mission_events.first_available_placed_unit( - &self.mission, world, clan, class, + &self.mission, world, clan, class, |_| true, ); Ok(Some(VarSetDefault::Dword(id.unwrap_or(u32::MAX)))) } @@ -1320,9 +1334,15 @@ impl ClanAiEvents { } fn unit_assigned(&self, unit: ObjectHandle) -> bool { - self.capture_orders - .iter() - .any(|&(_, _, order)| order.unit == unit) + self.factory_jobs.iter().any(|&(_, plant)| plant == unit) + || self + .transports + .iter() + .any(|(_, transport)| transport.unit == unit) + || self + .capture_orders + .iter() + .any(|&(_, _, order)| order.unit == unit) || self .groups .values() @@ -1335,6 +1355,12 @@ impl ClanAiEvents { .map(|(&(clan, target), &count)| (clan, target, count)) } + pub(super) fn free_unit_queries(&self) -> impl Iterator<Item = (usize, u32, u32, u64)> + '_ { + self.free_unit_queries + .iter() + .map(|(&(clan, class, unit), &count)| (clan, class, unit, count)) + } + pub(super) fn point_group_orders(&self) -> impl Iterator<Item = (usize, u32, u32, u64)> + '_ { self.point_group_orders .iter() @@ -1468,6 +1494,51 @@ mod tests { #[test] #[ignore = "requires licensed corpus"] + fn licensed_free_factory_query_dispatches_robot_production_from_stock_start() { + use crate::{EngineServices, MissionMode, MissionRequest, MissionStartupInput}; + use fparkan_vfs::DirectoryVfs; + use std::sync::Arc; + + let root = std::env::var_os("FPARKAN_CORPUS_PART1_ROOT").expect("licensed corpus root"); + let mut engine = + crate::create(EngineServices::new(Arc::new(DirectoryVfs::new(root)))).unwrap(); + crate::load_gameplay_mission( + &mut engine, + MissionRequest { + key: "MISSIONS/CAMPAIGN/CAMPAIGN.01/Mission.03/data.tma".into(), + mode: MissionMode::SingleMission, + }, + MissionStartupInput { + queue_time_ms: 0, + research_creation_gate: false, + }, + None, + ) + .unwrap(); + + for now in (0..=90_000).step_by(100) { + crate::frame(&mut engine, now).unwrap(); + } + let loaded = engine.loaded.as_ref().unwrap(); + assert!(loaded + .clan_ai_events + .free_unit_queries() + .any(|(clan, class, id, count)| { + clan == 1 && class == 0x8000_0010 && id != u32::MAX && count > 0 + })); + assert!(loaded + .clan_ai_events + .factory_orders + .iter() + .any(|(&(owner, _), &count)| owner == 1 && count > 0)); + assert!(loaded + .clan_ai_events + .stops() + .all(|(stop, _)| !stop.reason.starts_with("Handler(13)"))); + } + + #[test] + #[ignore = "requires licensed corpus"] fn licensed_point_protection_patrols_and_resumes_from_stock_start() { use crate::{EngineServices, MissionMode, MissionRequest, MissionStartupInput}; use fparkan_vfs::DirectoryVfs; diff --git a/crates/fparkan-runtime/src/lib.rs b/crates/fparkan-runtime/src/lib.rs index a4f3fdb8..1a878d75 100644 --- a/crates/fparkan-runtime/src/lib.rs +++ b/crates/fparkan-runtime/src/lib.rs @@ -2972,6 +2972,7 @@ pub struct SimulationReport { pub script_group_orders: Vec<(usize, u32, u64)>, pub script_point_group_orders: Vec<(usize, u32, u32, u64)>, pub script_point_patrol_continues: Vec<(usize, u32, u32, u64)>, + pub script_free_unit_queries: Vec<(usize, u32, u32, u64)>, pub script_problem_waits: Vec<(usize, u32, u64)>, pub script_factory_patrol_continues: Vec<(usize, u32, u64)>, pub script_ore_transport_orders: Vec<(usize, u32, u64)>, @@ -3030,6 +3031,7 @@ pub fn simulate_mission_report( script_group_orders: Vec::new(), script_point_group_orders: Vec::new(), script_point_patrol_continues: Vec::new(), + script_free_unit_queries: Vec::new(), script_problem_waits: Vec::new(), script_factory_patrol_continues: Vec::new(), script_ore_transport_orders: Vec::new(), @@ -3144,6 +3146,9 @@ pub fn simulate_mission_report( .script_point_patrol_continues .extend(loaded.clan_ai_events.point_patrol_continues()); report + .script_free_unit_queries + .extend(loaded.clan_ai_events.free_unit_queries()); + report .script_problem_waits .extend(loaded.clan_ai_events.wait_starts()); report diff --git a/crates/fparkan-runtime/src/mission_events.rs b/crates/fparkan-runtime/src/mission_events.rs index a00e449c..fd0cc72a 100644 --- a/crates/fparkan-runtime/src/mission_events.rs +++ b/crates/fparkan-runtime/src/mission_events.rs @@ -188,11 +188,15 @@ impl MissionEvents { world: &World, clan: usize, class: u32, + available: impl Fn(ObjectHandle) -> bool, ) -> Option<u32> { self.placed_clan_objects .iter() .find_map(|&(handle, candidate)| { - if candidate != class || self.reserved_units.contains(&(clan, handle)) { + if candidate != class + || self.reserved_units.contains(&(clan, handle)) + || !available(handle) + { return None; } registration_sequence(world, handle).ok()??; @@ -1095,6 +1099,73 @@ mod tests { }; #[test] + fn free_unit_selection_skips_busy_reserved_foreign_and_removed_entries() { + let mission = crate::MissionDocument { + format_version: 1, + clan_section_version: 6, + object_section_version: 10, + extra_section_version: 1, + versions: vec![], + paths: vec![], + clans: vec![], + objects: vec![], + land_path: Default::default(), + mission_flag: 0, + description_raw: Default::default(), + extras: vec![], + raw: std::sync::Arc::from([]), + }; + let mut world = new(WorldConfig); + let factory = 0x8000_0010; + let mut events = MissionEvents::default(); + let entries = [ + (91, 0x0100_8000, 1), + (12345, factory, 1), + (45678, factory, 1), + (45679, factory, 2), + ] + .map(|(id, class, owner)| { + let unit = construct_object(&mut world, ObjectDraft { original_id: None }).unwrap(); + set_owner(&mut world, unit, Some(OwnerId(owner))).unwrap(); + register_object(&mut world, unit).unwrap(); + events.placed_clan_objects.push((unit, class)); + events.issued_logic_ids.insert(unit, id); + unit + }); + assert_eq!( + events.first_available_placed_unit(&mission, &world, 1, factory, |_| true), + Some(12345) + ); + assert_eq!( + events.first_available_placed_unit(&mission, &world, 1, factory, |unit| unit + != entries[1]), + Some(45678) + ); + events.reserved_units.insert((1, entries[1])); + assert_eq!( + events.first_available_placed_unit(&mission, &world, 1, factory, |_| true), + Some(45678) + ); + events.reserved_units.insert((1, entries[2])); + assert_eq!( + events.first_available_placed_unit(&mission, &world, 1, factory, |_| true), + None + ); + events.reserved_units.remove(&(1, entries[2])); + request_delete(&mut world, entries[2]).unwrap(); + assert_eq!( + events.first_available_placed_unit(&mission, &world, 1, factory, |_| true), + None + ); + events.reserved_units.clear(); + set_owner(&mut world, entries[1], Some(OwnerId(2))).unwrap(); + assert_eq!( + events.first_available_placed_unit(&mission, &world, 1, factory, |_| true), + None + ); + } + + #[test] #[ignore = "requires licensed corpus"] fn licensed_clan_checks_for_live_unit_in_problems0() { use crate::{EngineServices, MissionMode, MissionRequest, MissionStartupInput}; diff --git a/docs/appendices/knowledge-boundaries.md b/docs/appendices/knowledge-boundaries.md index 163e51e8..7d7e234a 100644 --- a/docs/appendices/knowledge-boundaries.md +++ b/docs/appendices/knowledge-boundaries.md @@ -476,6 +476,9 @@ ID выпущенной машины внутренний. Подъезд, выÐ фундамент и боевое поведение новой башни открыты. Разные заводы могут собирать одновременно. `script_factory_rejections` считает отклонения по клану и заводу. +`script_free_unit_approx` считает выбор через `Handler(13)` по клану, классу +и выбранному ID. Занятость берётся из текущих задач FParkan и производства; +переназначение с менее важных заявок в других режимах выбора открыто. `script_combat_strength_approx` считает запросы `Handler(38)` по паре кланов. Оценка использует текущую прочность Control и проектные боезапасы. Масштабирование `0x36` и остатки боеприпасов требуют сверки. diff --git a/docs/tomes/06-behavior.md b/docs/tomes/06-behavior.md index 4c2e607a..4b0a8a99 100644 --- a/docs/tomes/06-behavior.md +++ b/docs/tomes/06-behavior.md @@ -325,6 +325,21 @@ RVA `0x6700` ищет самое дальнее строение клана вн при повторе с теми же данными. FParkan использует начало координат карты как постоянную точку оценки. +### Свободный исполнитель + +Сценарий может искать свободный объект заданного класса через `Handler(13)` +с режимом `UNIT_FREE_UNIT`. GOG `ai.dll` по RVA `0x86fb` идёт по реестру +своего клана и возвращает первый объект с точным совпадением класса и +состоянием назначения `0xffffffff`. Занятая или зарезервированная запись +пропускается. Если подходящих записей нет, результат равен `ERROR`. +Это правило подтверждено вызовом DLL; SHA-256 +`c19cd6cd31cd2896f8c4ba0f0e700dd3408aec8182daaf4863d98a7d233a2abc`. + +Например, заявка `PBM_ROBOT_NEEDED` ищет `BUILDING_PLANT` (`0x80000010`). +Полученный ID поступает в приказ производства. Пока завод занят сборкой, +FParkan пропускает его при следующем поиске. Выбор также учитывает живого +владельца, резервирование и действующие назначения AI. + ### Боевые группы `Handler(67)` находит первый завод в списке клана и суммирует силу |
