diff options
| -rw-r--r-- | apps/fparkan-game/src/script_coverage.rs | 3 | ||||
| -rw-r--r-- | crates/fparkan-runtime/src/clan_ai_events.rs | 201 | ||||
| -rw-r--r-- | crates/fparkan-runtime/src/lib.rs | 6 | ||||
| -rw-r--r-- | crates/fparkan-runtime/src/mission_events.rs | 23 | ||||
| -rw-r--r-- | crates/fparkan-script/src/lib.rs | 5 | ||||
| -rw-r--r-- | docs/appendices/knowledge-boundaries.md | 5 | ||||
| -rw-r--r-- | docs/appendices/script-vm.md | 7 |
7 files changed, 213 insertions, 37 deletions
diff --git a/apps/fparkan-game/src/script_coverage.rs b/apps/fparkan-game/src/script_coverage.rs index e54e1faa..3df8ab46 100644 --- a/apps/fparkan-game/src/script_coverage.rs +++ b/apps/fparkan-game/src/script_coverage.rs @@ -21,6 +21,9 @@ pub(super) fn log_script_init(engine: &Engine, mission: &str) { } pub(super) fn log_clan_ai_stops(report: &SimulationReport) { + for &(clan, kind, count) in &report.clan_problem_starts { + eprintln!("sim_coverage script_problem_starts_approx={count} clan={clan} problem={kind}"); + } for (&(clan, kind), count) in &report.clan_problem_dispatch_stubs { eprintln!("sim_coverage script_problem_dispatch_stubs={count} clan={clan} problem={kind}"); } diff --git a/crates/fparkan-runtime/src/clan_ai_events.rs b/crates/fparkan-runtime/src/clan_ai_events.rs index 56f2f0cf..56396242 100644 --- a/crates/fparkan-runtime/src/clan_ai_events.rs +++ b/crates/fparkan-runtime/src/clan_ai_events.rs @@ -1,6 +1,7 @@ use crate::{BehaviorOreState, LoadedMissionState, MissionEventStop}; use fparkan_script::{ - Handler2RecordInput, Handler2RecordScheduler, ScriptDispatchSelector, VarSet, VarSetDefault, + Handler2Record, Handler2RecordInput, Handler2RecordScheduler, ScriptDispatchSelector, VarSet, + VarSetDefault, }; use fparkan_world::{identity_metadata, registration_sequence, OwnerId, World}; use std::collections::BTreeMap; @@ -14,6 +15,7 @@ pub(super) struct ClanAiEvents { stops: BTreeMap<(usize, usize, usize), (MissionEventStop, u64)>, research_stubs: BTreeMap<(usize, u8), u64>, problems: BTreeMap<usize, Handler2RecordScheduler>, + started: BTreeMap<(usize, u32), u64>, } impl LoadedMissionState { @@ -46,11 +48,44 @@ impl LoadedMissionState { else { continue; }; - let result = varset.declarations.execute_event_prefix( - event, - bundle.formula_table.as_ref(), - &mut state.values, - |instruction, values| match instruction.dispatch_selector() { + let mut next = Some((event_index, event, None)); + while let Some((event_index, event, problem)) = next.take() { + let mut solved = false; + let result = varset.declarations.execute_event_prefix( + event, + bundle.formula_table.as_ref(), + &mut state.values, + |instruction, values| match instruction.dispatch_selector() { + ScriptDispatchSelector::Handler(8) if problem.is_some() => { + if single_dword(&instruction.references, values) != Some(2) { + return Err("Handler(8) only supports ST_SOLVED".into()); + } + solved = true; + Ok(None) + } + ScriptDispatchSelector::Handler(14) if problem.is_some() => { + let (mode, class) = instruction.dword_pair(values) + .ok_or("Handler(14) requires a unit mode and class")?; + if mode != 2 { + return Err("Handler(14) only supports UNIT_ANY_UNIT".into()); + } + // shortcut: only unassigned placed objects until PBM owns roster slots. + let id = self.mission_events.first_available_placed_unit( + &self.mission, world, clan, class + ); + Ok(Some(VarSetDefault::Dword(id.unwrap_or(u32::MAX)))) + } + ScriptDispatchSelector::Handler(29) => { + let problem: &Handler2Record = problem.as_ref().ok_or("Handler(29) requires a current problem")?; + let bits = match single_dword(&instruction.references, values) { + Some(0) => problem.key.scalar_4_bits, + Some(1) => problem.key.scalar_5_bits, + Some(2) => problem.scalar_6.to_bits(), + _ => return Err("Handler(29) requires a problem argument index from 0 to 2".into()), + }; + Ok(Some(VarSetDefault::Dword(problem_dword(bits).ok_or("Handler(29) argument is outside the supported DWORD range")?))) + } + ScriptDispatchSelector::Handler(0) if problem.is_some() && instruction.references.len() == 1 => Ok(Some(VarSetDefault::Dword(1))), ScriptDispatchSelector::Handler(2) => { let (name, input) = problem_operands(&varset.declarations, values, &instruction.references) .ok_or("Handler(2) requires seven numeric problem operands")?; @@ -133,33 +168,113 @@ impl LoadedMissionState { } selector => Err(format!("{selector:?}")), }, - ); - if let Err((instruction_index, reason)) = result { - let (stop, count) = self + ); + if let Err((instruction_index, reason)) = result { + let (stop, count) = self + .clan_ai_events + .stops + .entry((clan, event_index, instruction_index)) + .or_insert_with(|| { + ( + MissionEventStop { + clan_index: clan, + script_path: bundle.script_path.clone(), + event_index, + instruction_index, + reason, + }, + 0, + ) + }); + *count += 1; + if *count == 1 { + eprintln!("sim_coverage script_clan_ai_unsupported=1 clan={clan} script={} event={event_index} instruction={instruction_index} reason={}", stop.script_path, stop.reason); + } + } + if let Some(problem) = problem { + if solved { + self.clan_ai_events + .problems + .entry(clan) + .or_default() + .remove(problem.key); + } + continue; + } + // shortcut: run one highest-priority Start per tick until ties, decay and Continue are wired. + let Some(problem) = self .clan_ai_events - .stops - .entry((clan, event_index, instruction_index)) - .or_insert_with(|| { - ( - MissionEventStop { - clan_index: clan, - script_path: bundle.script_path.clone(), - event_index, - instruction_index, - reason, - }, - 0, - ) - }); - *count += 1; - if *count == 1 { - eprintln!("sim_coverage script_clan_ai_unsupported=1 clan={clan} script={} event={event_index} instruction={instruction_index} reason={}", stop.script_path, stop.reason); + .problems + .get(&clan) + .and_then(|queue| highest_problem(queue.records())) + .cloned() + else { + continue; + }; + let Some(kind) = varset.declarations.declarations.iter().find(|entry| { + entry.name.starts_with("PBM_") + && entry.default_value == VarSetDefault::Dword(problem.key.word_0) + }) else { + continue; + }; + let problem_id = problem.key.word_0; + let start = format!("{}_Start\0", kind.name); + next = bundle + .package + .events + .iter() + .enumerate() + .find(|(_, event)| { + event.name_raw == start.as_bytes() && !event.instructions.is_empty() + }) + .map(|(index, event)| (index, event, Some(problem))); + if next.is_some() { + let count = self + .clan_ai_events + .started + .entry((clan, problem_id)) + .or_default(); + *count += 1; + if *count == 1 { + eprintln!( + "sim_coverage script_problem_start_approx=1 clan={clan} problem={}", + kind.name + ); + } } } } } } +fn highest_problem(problems: &[Handler2Record]) -> Option<&Handler2Record> { + problems + .iter() + .filter(|record| record.scalar_1 > 0.0) + .reduce(|best, record| { + if record.scalar_1 > best.scalar_1 { + record + } else { + best + } + }) +} + +fn single_dword(references: &[u32], values: &[VarSetDefault]) -> Option<u32> { + let &[index] = references else { + return None; + }; + values.get(index as usize)?.as_dword() +} + +fn problem_dword(bits: u32) -> Option<u32> { + let value = f64::from(f32::from_bits(bits)); + let limit = 9_223_372_036_854_775_808.0; + (-limit..limit) + .contains(&value) + .then(|| value.trunc() as i64 as u32) +} + fn problem_operands<'a>( varset: &'a VarSet, values: &[VarSetDefault], @@ -171,13 +286,7 @@ fn problem_operands<'a>( let value = |index: u32| values.get(index as usize).copied(); let word = |index| match value(index)? { VarSetDefault::Dword(value) => Some(value), - VarSetDefault::FloatBits(bits) => { - let value = f64::from(f32::from_bits(bits)); - let limit = 9_223_372_036_854_775_808.0; - (-limit..limit) - .contains(&value) - .then(|| value.trunc() as i64 as u32) - } + VarSetDefault::FloatBits(bits) => problem_dword(bits), }; let scalar = |index| match value(index)? { VarSetDefault::Dword(value) => Some(value as f32), @@ -243,6 +352,12 @@ impl ClanAiEvents { .map(move |record| (clan, record.key.word_0)) }) } + + pub(super) fn started_problems(&self) -> impl Iterator<Item = (usize, u32, u64)> + '_ { + self.started + .iter() + .map(|(&(clan, kind), &count)| (clan, kind, count)) + } } #[cfg(test)] @@ -294,6 +409,26 @@ mod tests { } #[test] + fn problem_selection_requires_a_positive_priority_and_preserves_order_on_ties() { + let mut queue = Handler2RecordScheduler::default(); + for (word_0, scalar_1) in [(1, 0.0), (2, -3.0), (3, 0.5), (4, 0.5)] { + queue.submit(Handler2RecordInput { + word_0, + scalar_1, + word_2: 0, + word_3: 0, + scalar_4: 0.0, + scalar_5: 0.0, + scalar_6: 0.0, + }); + } + let first = highest_problem(queue.records()).unwrap().key; + assert_eq!(first.word_0, 3); + queue.remove(first); + assert_eq!(highest_problem(queue.records()).unwrap().key.word_0, 4); + } + + #[test] fn free_ore_space_follows_storage_ownership_and_lifecycle() { use fparkan_world::{ construct_object, new, register_object, request_delete, set_owner, step, InputSnapshot, diff --git a/crates/fparkan-runtime/src/lib.rs b/crates/fparkan-runtime/src/lib.rs index 6fb2b320..3087d175 100644 --- a/crates/fparkan-runtime/src/lib.rs +++ b/crates/fparkan-runtime/src/lib.rs @@ -2904,6 +2904,8 @@ pub struct SimulationReport { pub clan_research_status_stubs: Vec<(usize, u8, u64)>, /// Counts of pending script problems by clan and problem kind. pub clan_problem_dispatch_stubs: std::collections::BTreeMap<(usize, u32), u64>, + /// Starts under the approximate scheduler, grouped by clan and problem kind. + pub clan_problem_starts: Vec<(usize, u32, u64)>, /// Total requests for mission information messages. pub mission_messages: u64, /// Clock of the first autonomous shot, in milliseconds. @@ -2940,6 +2942,7 @@ pub fn simulate_mission_report( clan_ai_event_stops: Vec::new(), clan_research_status_stubs: Vec::new(), clan_problem_dispatch_stubs: Default::default(), + clan_problem_starts: Vec::new(), mission_messages: 0, autodemo_first_shot_ms: None, autodemo_first_destroyed_ms: None, @@ -3000,6 +3003,9 @@ pub fn simulate_mission_report( .entry(problem) .or_default() += 1; } + report + .clan_problem_starts + .extend(loaded.clan_ai_events.started_problems()); } Ok(report) } diff --git a/crates/fparkan-runtime/src/mission_events.rs b/crates/fparkan-runtime/src/mission_events.rs index b97b154f..d040e4f8 100644 --- a/crates/fparkan-runtime/src/mission_events.rs +++ b/crates/fparkan-runtime/src/mission_events.rs @@ -158,6 +158,29 @@ impl MissionEvents { .count() as u32 } + pub(super) fn first_available_placed_unit( + &self, + mission: &super::MissionDocument, + world: &World, + clan: usize, + class: u32, + ) -> Option<u32> { + self.placed_clan_objects + .iter() + .find_map(|&(handle, candidate)| { + if candidate != class || self.reserved_units.contains(&(clan, handle)) { + return None; + } + registration_sequence(world, handle).ok()??; + let identity = identity_metadata(world, handle).ok()?; + if identity.owner_id != Some(OwnerId(clan as u16)) { + return None; + } + let object = mission.objects.get(identity.original_id?.0 as usize)?; + Some(object.identity_or_clan_raw) + }) + } + pub(super) fn set_reservation( &mut self, mission: &super::MissionDocument, diff --git a/crates/fparkan-script/src/lib.rs b/crates/fparkan-script/src/lib.rs index 2c3eccf1..336828ea 100644 --- a/crates/fparkan-script/src/lib.rs +++ b/crates/fparkan-script/src/lib.rs @@ -2021,6 +2021,11 @@ impl Handler2RecordScheduler { &self.records } + /// Forgets a solved problem so a later submission can create it again. + pub fn remove(&mut self, key: Handler2RecordKey) { + self.records.retain(|record| record.key != key); + } + /// Inserts or refreshes one resolved handler input. /// /// The original compares the three identity words bit-for-bit. On an diff --git a/docs/appendices/knowledge-boundaries.md b/docs/appendices/knowledge-boundaries.md index f48595bd..a2723958 100644 --- a/docs/appendices/knowledge-boundaries.md +++ b/docs/appendices/knowledge-boundaries.md @@ -441,8 +441,9 @@ core и `ResearchCandidateSet::refresh_selection`: последний получ `script_research_status_stubs` считает вызовы `Handler(65)` без каталога и `Handler(56)` без подключённого флага автоматических исследований. `script_problem_dispatch_stubs` считает накопленные заявки по клану и типу. -Очередь принимает заявки с секциями `_Start` и `_Continue`. Исполнение -этих секций и порядок выбора заявок ещё открыты. +Очередь принимает заявки с секциями `_Start` и `_Continue`. +`script_problem_start_approx` отмечает выбор одной заявки с наибольшим весом +за тик. Исполнение `_Continue`, равные приоритеты и старение заявок открыты. Оригинальный getter `ai.dll+0x111d0` возвращает ноль в этом состоянии. `Handler(15)` для `ORDER_ROBOT_SEARCH` генератора пока проходит как `script_init_handler_stub`. GOG Behavior.dll по RVA `0x30110` настраивает diff --git a/docs/appendices/script-vm.md b/docs/appendices/script-vm.md index 1dca528f..9d597ef1 100644 --- a/docs/appendices/script-vm.md +++ b/docs/appendices/script-vm.md @@ -327,8 +327,11 @@ record fields `+0x0c` и `+0x14`, затем вызывает его refresh pat `<base>_Continue`, сохраняет их IDs в indexed state и materializes новый internal record. В этой ветке не видно прямого World3D/Behavior call, поэтому это граница очереди заявок. FParkan проверяет наличие обеих секций в пакете -и передаёт значения планировщику клана. Заявка учитывается в отчёте покрытия -до подключения запуска секций при обновлении AI. +и передаёт значения планировщику клана. После `Problems0` ядро FParkan +выбирает одну заявку с наибольшим положительным весом и запускает её +`_Start`. В оригинале RVA `0x1bf0` сначала собирает весь набор равных +наибольших весов, затем исполняет секции. `Handler(29)` читает три аргумента +текущей заявки, `Handler(14)` выбирает исполнителя заданного класса. У этой границы также нет скрытого immediate dispatch: после добавления новой записи `0x100059f0` вызывает `0x1000f920`, а Ghidra 12.1.2 декомпилирует эту |
