diff options
| -rw-r--r-- | apps/fparkan-game/src/main.rs | 57 | ||||
| -rw-r--r-- | apps/fparkan-game/src/mission_notices.rs | 55 | ||||
| -rw-r--r-- | crates/fparkan-runtime/src/clan_ai_events.rs | 20 | ||||
| -rw-r--r-- | crates/fparkan-runtime/src/clan_building_queries.rs | 23 | ||||
| -rw-r--r-- | crates/fparkan-runtime/src/lib.rs | 11 | ||||
| -rw-r--r-- | crates/fparkan-runtime/src/mission_events.rs | 56 | ||||
| -rw-r--r-- | crates/fparkan-runtime/src/script_host.rs | 115 | ||||
| -rw-r--r-- | docs/appendices/knowledge-boundaries.md | 5 | ||||
| -rw-r--r-- | docs/appendices/script-vm.md | 15 |
9 files changed, 251 insertions, 106 deletions
diff --git a/apps/fparkan-game/src/main.rs b/apps/fparkan-game/src/main.rs index b1a4f1e0..96dfd756 100644 --- a/apps/fparkan-game/src/main.rs +++ b/apps/fparkan-game/src/main.rs @@ -7,6 +7,7 @@ mod camera_capture; mod control_effects; use control_effects::{advance_control_effect_instances, owner_control_capacity}; mod mission_hints; +mod mission_notices; mod player_collision; mod projectile_trail; mod script_coverage; @@ -98,9 +99,9 @@ use fparkan_runtime::{ projectile_terrain_hit, projectile_unit_hit, query_building_segment_world, simulate_mission_report, starting_cockpit, starting_player_weapons, AutoDemoCamera, AutoDemoView, BasementPlacementMode, BuildingMeshNode, Engine, EngineError, EngineServices, - FrameResult, LoadedMission, MissionAssets, MissionEventStop, MissionMode, MissionNotice, - MissionObjectDraft, MissionRequest, MissionStartupInput, PlayerMotion, PlayerProjectile, - PlayerWeapons, StartingCockpit, SIMULATION_COVERAGE, + FrameResult, LoadedMission, MissionAssets, MissionEventStop, MissionMode, MissionObjectDraft, + MissionRequest, MissionStartupInput, PlayerMotion, PlayerProjectile, PlayerWeapons, + StartingCockpit, SIMULATION_COVERAGE, }; #[cfg(test)] use fparkan_runtime::{load_mission_with_init_stubs, plan_player_motion}; @@ -11376,48 +11377,14 @@ impl StaticVulkanApp { for &(handle, [x, y]) in &tick.patrol_orders { eprintln!("mission_patrol_order unit={} target=[{x},{y}] queue_time_ms={control_clock_ms}", handle.slot); } - for ¬ice in &tick.notices { - match notice { - MissionNotice::ObjectiveComplete(index) => eprintln!("mission_objective index={index} status=complete queue_time_ms={control_clock_ms}"), - MissionNotice::Completed | MissionNotice::Failed => { - let status = if notice == MissionNotice::Completed { - "completed" - } else { - "failed" - }; - eprintln!("mission_outcome status={status} queue_time_ms={control_clock_ms}"); - } - MissionNotice::Information(index) => { - #[cfg(windows)] - { - let queued = self.mission_hints.as_mut() - .ok_or_else(|| "mission text resources unavailable".to_string()) - .and_then(|hints| hints.enqueue(index)); - if let Err(error) = queued { - eprintln!("sim_coverage mission_text_unavailable=1 index={index} reason={error}"); - } - } - #[cfg(not(windows))] - eprintln!("sim_coverage mission_text_unavailable=1 index={index} reason=platform"); - } - } - if let Some(audio) = &mut self.audio { - let voice = match notice { - MissionNotice::Information(index) => audio.queue_mission_voice(index), - MissionNotice::ObjectiveComplete(_) => { - audio.queue_game_voice("VOICE_OBJ_COMPLETE") - } - MissionNotice::Completed => { - audio.queue_game_voice("VOICE_MISSION_COMPLETE") - } - MissionNotice::Failed => audio.queue_game_voice("VOICE_MISSION_FAIL"), - }; - match voice { - Ok(resource) => eprintln!("mission_voice notice={notice:?} resource={resource} queue_time_ms={control_clock_ms}"), - Err(error) => eprintln!("sim_coverage mission_voice_unavailable=1 notice={notice:?} reason={error}"), - } - } - } + } + for ¬ice in frame + .mission_event + .iter() + .flat_map(|tick| &tick.notices) + .chain(&frame.clan_notices) + { + self.present_mission_notice(notice, control_clock_ms); } self.mission_frame = Some(frame); } diff --git a/apps/fparkan-game/src/mission_notices.rs b/apps/fparkan-game/src/mission_notices.rs new file mode 100644 index 00000000..a4ea8f05 --- /dev/null +++ b/apps/fparkan-game/src/mission_notices.rs @@ -0,0 +1,55 @@ +use crate::StaticVulkanApp; +use fparkan_runtime::MissionNotice; + +impl StaticVulkanApp { + pub(super) fn present_mission_notice(&mut self, notice: MissionNotice, clock_ms: u32) { + match notice { + MissionNotice::ObjectiveComplete(index) => { + eprintln!( + "mission_objective index={index} status=complete queue_time_ms={clock_ms}" + ); + } + MissionNotice::Completed | MissionNotice::Failed => { + let status = if notice == MissionNotice::Completed { + "completed" + } else { + "failed" + }; + eprintln!("mission_outcome status={status} queue_time_ms={clock_ms}"); + } + MissionNotice::Information(index) => { + #[cfg(windows)] + { + let queued = self + .mission_hints + .as_mut() + .ok_or_else(|| "mission text resources unavailable".to_string()) + .and_then(|hints| hints.enqueue(index)); + if let Err(error) = queued { + eprintln!( + "sim_coverage mission_text_unavailable=1 index={index} reason={error}" + ); + } + } + #[cfg(not(windows))] + eprintln!("sim_coverage mission_text_unavailable=1 index={index} reason=platform"); + } + } + if let Some(audio) = &mut self.audio { + let voice = match notice { + MissionNotice::Information(index) => audio.queue_mission_voice(index), + MissionNotice::ObjectiveComplete(_) => audio.queue_game_voice("VOICE_OBJ_COMPLETE"), + MissionNotice::Completed => audio.queue_game_voice("VOICE_MISSION_COMPLETE"), + MissionNotice::Failed => audio.queue_game_voice("VOICE_MISSION_FAIL"), + }; + match voice { + Ok(resource) => eprintln!( + "mission_voice notice={notice:?} resource={resource} queue_time_ms={clock_ms}" + ), + Err(error) => eprintln!( + "sim_coverage mission_voice_unavailable=1 notice={notice:?} reason={error}" + ), + } + } + } +} diff --git a/crates/fparkan-runtime/src/clan_ai_events.rs b/crates/fparkan-runtime/src/clan_ai_events.rs index 5af3c086..573318cf 100644 --- a/crates/fparkan-runtime/src/clan_ai_events.rs +++ b/crates/fparkan-runtime/src/clan_ai_events.rs @@ -4,7 +4,7 @@ use crate::{ clan_combat_groups::{CombatGroup, GroupTarget}, clan_targeting::CaptureApproach, }; -use crate::{BehaviorOreState, LoadedMissionState, MissionEventStop}; +use crate::{BehaviorOreState, LoadedMissionState, MissionEventStop, MissionNotice}; use fparkan_script::{ Handler15TargetPayload, Handler2Record, Handler2RecordInput, Handler2RecordKey, Handler2RecordScheduler, ScriptDispatchSelector, VarSet, VarSetDefault, @@ -83,9 +83,10 @@ pub(super) fn resolve_captures( Ok(captured) } -pub(super) fn tick(engine: &mut crate::Engine, now_ms: u32) { +pub(super) fn tick(engine: &mut crate::Engine, now_ms: u32) -> Vec<MissionNotice> { + let mut notices = Vec::new(); let Some(loaded) = &mut engine.loaded else { - return; + return notices; }; crate::construction::tick(loaded, &mut engine.world, now_ms); loaded.clan_ai_events.groups.retain(|&(clan, _), group| { @@ -166,6 +167,7 @@ pub(super) fn tick(engine: &mut crate::Engine, now_ms: u32) { engine.production.as_ref(), engine.services.vfs.as_deref(), now_ms, + &mut notices, ) { match crate::production::order_script_factory( engine, @@ -213,6 +215,7 @@ pub(super) fn tick(engine: &mut crate::Engine, now_ms: u32) { } } } + notices } #[derive(Default)] @@ -264,6 +267,7 @@ impl LoadedMissionState { production: Option<&crate::production::Production>, vfs: Option<&dyn fparkan_vfs::Vfs>, now_ms: u32, + notices: &mut Vec<MissionNotice>, ) -> Vec<ScriptFactoryOrder> { let mut orders = Vec::new(); let Some(varset) = &self.script_varset else { @@ -420,6 +424,16 @@ impl LoadedMissionState { .scalar_1; Ok(Some(VarSetDefault::FloatBits(priority.to_bits()))) } + ScriptDispatchSelector::Handler(30) => { + let command = varset.declarations + .resolve_handler30_with_values(instruction, values) + .map_err(|error| error.to_string())?; + crate::script_host::apply( + self.script_host_mode, &mut self.script_host_status, + &mut self.script_outcome, &mut self.mission_events, command, notices, + )?; + Ok(None) + } ScriptDispatchSelector::Handler(71) => { let &[radius, class, estimate] = instruction.references.as_slice() else { return Err("Handler(71) requires radius, class and strength output".into()); diff --git a/crates/fparkan-runtime/src/clan_building_queries.rs b/crates/fparkan-runtime/src/clan_building_queries.rs index 399dd28c..c179c2e1 100644 --- a/crates/fparkan-runtime/src/clan_building_queries.rs +++ b/crates/fparkan-runtime/src/clan_building_queries.rs @@ -83,8 +83,9 @@ mod tests { None, ) .unwrap(); + let mut heard = Vec::new(); for now in (0..=900_000).step_by(100) { - crate::frame(&mut engine, now).unwrap(); + heard.extend(crate::frame(&mut engine, now).unwrap().clan_notices); if engine .loaded .as_ref() @@ -96,6 +97,13 @@ mod tests { break; } } + assert_eq!( + heard + .iter() + .filter(|&¬ice| notice == crate::MissionNotice::Information(0)) + .count(), + 1 + ); let loaded = engine.loaded.as_ref().unwrap(); let actor = loaded .mission_events @@ -126,12 +134,13 @@ mod tests { .clan_ai_events .size_class_queries() .any(|(clan, id, count)| clan == 1 && id == 0x8000_0003 && count > 0)); - assert!(loaded - .clan_ai_events - .stops() - .all(|(stop, _)| !["Handler(71)", "Handler(72)"] - .iter() - .any(|handler| stop.reason.starts_with(handler)))); + assert!(loaded.clan_ai_events.stops().all(|(stop, _)| ![ + "Handler(30)", + "Handler(71)", + "Handler(72)" + ] + .iter() + .any(|handler| stop.reason.starts_with(handler)))); let classified = loaded .mission_events diff --git a/crates/fparkan-runtime/src/lib.rs b/crates/fparkan-runtime/src/lib.rs index 0b250ad5..0d1ea501 100644 --- a/crates/fparkan-runtime/src/lib.rs +++ b/crates/fparkan-runtime/src/lib.rs @@ -65,6 +65,7 @@ mod player_weapon; mod production; mod projectile; mod research; +mod script_host; mod script_patrol; mod script_time; mod unit_combat; @@ -1317,6 +1318,8 @@ pub struct FrameResult { pub snapshot: WorldSnapshot, /// Periodic script event attempted on this step, if due. pub mission_event: Option<MissionEventTick>, + /// Notifications emitted by clan AI scripts on this step. + pub clan_notices: Vec<MissionNotice>, /// Vertical aim of the controlled hero as an IEEE-754 radian value. pub player_pitch_bits: u32, /// Autonomous combat events during the step. @@ -2865,7 +2868,7 @@ pub fn step_headless( .loaded .as_mut() .and_then(|state| state.tick_mission_event(&engine.world, queue_time_ms)); - clan_ai_events::tick(engine, queue_time_ms); + let clan_notices = clan_ai_events::tick(engine, queue_time_ms); let researched_component = engine .loaded .as_mut() @@ -2873,6 +2876,7 @@ pub fn step_headless( Ok(FrameResult { snapshot, mission_event, + clan_notices, autodemo_combat_events, autodemo_combat_unavailable, autodemo_reinforcements, @@ -3088,6 +3092,11 @@ pub fn simulate_mission_report( AutoDemoCombatEvent::BuildingHit { .. } => continue, }; } + report.mission_messages += frame + .clan_notices + .iter() + .filter(|notice| matches!(notice, MissionNotice::Information(_))) + .count() as u64; if let Some(event) = frame.mission_event { report.mission_events += 1; report.mission_event_stops.extend(event.stop); diff --git a/crates/fparkan-runtime/src/mission_events.rs b/crates/fparkan-runtime/src/mission_events.rs index 3405120b..6b200ef1 100644 --- a/crates/fparkan-runtime/src/mission_events.rs +++ b/crates/fparkan-runtime/src/mission_events.rs @@ -66,7 +66,7 @@ enum ObjectiveState { } #[derive(Default)] -struct MissionObjectives { +pub(super) struct MissionObjectives { primary_count: usize, states: Vec<ObjectiveState>, } @@ -111,7 +111,7 @@ impl MissionObjectives { } } - fn apply( + pub(super) fn apply( &mut self, command: u32, index: u32, @@ -145,12 +145,12 @@ pub(super) struct MissionEvents { next_ms: u32, reported_stops: HashSet<(usize, usize)>, inside_hero_exit: bool, - voiced_messages: HashSet<u32>, + pub(super) voiced_messages: HashSet<u32>, reserved_units: HashSet<(usize, ObjectHandle)>, placed_clan_objects: Vec<(ObjectHandle, u32)>, issued_logic_ids: HashMap<ObjectHandle, u32>, next_logic_id: u32, - objectives: MissionObjectives, + pub(super) objectives: MissionObjectives, } impl MissionEvents { @@ -938,46 +938,14 @@ impl LoadedMissionState { let command = declarations .resolve_handler30_with_values(instruction, values) .map_err(|error| error.to_string())?; - if self.script_host_mode == super::MissionMode::AutoDemo { - return Ok(None); - } - let outcome = match command.first { - 0 => Some(command), - 1 => { - if mission_events.voiced_messages.insert(command.second) { - notices.push(MissionNotice::Information(command.second)); - } - None - } - 3..=5 => mission_events - .objectives - .apply(command.first, command.second, &mut notices)? - .then_some(VmHostCallbackCommand { - mode: 0, - first: 0, - second: 1, - }), - _ => return Err(format!("Handler(30) command {}", command.first)), - }; - if let Some(outcome) = outcome { - match apply_recovered_script_host_callback( - self.script_host_mode, - &mut self.script_host_status, - &mut self.script_outcome, - outcome, - ) { - MissionScriptHostEffect::MissionCompleted => { - notices.push(MissionNotice::Completed) - } - MissionScriptHostEffect::MissionFailed => { - notices.push(MissionNotice::Failed) - } - MissionScriptHostEffect::NoChange => {} - MissionScriptHostEffect::Unhandled => { - return Err(format!("Handler(30) outcome {}", outcome.second)) - } - } - } + crate::script_host::apply( + self.script_host_mode, + &mut self.script_host_status, + &mut self.script_outcome, + mission_events, + command, + &mut notices, + )?; Ok(None) } selector => Err(format!("{selector:?}")), diff --git a/crates/fparkan-runtime/src/script_host.rs b/crates/fparkan-runtime/src/script_host.rs new file mode 100644 index 00000000..d87f6348 --- /dev/null +++ b/crates/fparkan-runtime/src/script_host.rs @@ -0,0 +1,115 @@ +use crate::{ + apply_recovered_script_host_callback, mission_events::MissionEvents, MissionMode, + MissionNotice, MissionScriptHostEffect, MissionScriptOutcome, +}; +use fparkan_script::VmHostCallbackCommand; + +pub(super) fn apply( + mode: MissionMode, + status: &mut u32, + outcome: &mut MissionScriptOutcome, + events: &mut MissionEvents, + command: VmHostCallbackCommand, + notices: &mut Vec<MissionNotice>, +) -> Result<(), String> { + if mode == MissionMode::AutoDemo { + return Ok(()); + } + let outcome_command = match command.first { + 0 => Some(command), + 1 => { + // shortcut: present the first message until the native repeated-message UI is wired. + if events.voiced_messages.insert(command.second) { + notices.push(MissionNotice::Information(command.second)); + } + None + } + 3..=5 => events + .objectives + .apply(command.first, command.second, notices)? + .then_some(VmHostCallbackCommand { + mode: 0, + first: 0, + second: 1, + }), + _ => return Err(format!("Handler(30) command {}", command.first)), + }; + if let Some(command) = outcome_command { + match apply_recovered_script_host_callback(mode, status, outcome, command) { + MissionScriptHostEffect::MissionCompleted => notices.push(MissionNotice::Completed), + MissionScriptHostEffect::MissionFailed => notices.push(MissionNotice::Failed), + MissionScriptHostEffect::NoChange => {} + MissionScriptHostEffect::Unhandled => { + return Err(format!("Handler(30) outcome {}", command.second)); + } + } + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn information_is_presented_once_across_script_callers() { + let mut events = MissionEvents::default(); + let mut status = 5; + let mut outcome = MissionScriptOutcome::Active; + let mut notices = Vec::new(); + for index in [0, 0, 1, 0, 1] { + apply( + MissionMode::SingleMission, + &mut status, + &mut outcome, + &mut events, + VmHostCallbackCommand { + mode: 0, + first: 1, + second: index, + }, + &mut notices, + ) + .unwrap(); + } + assert_eq!( + notices, + [MissionNotice::Information(0), MissionNotice::Information(1)] + ); + assert_eq!(outcome, MissionScriptOutcome::Active); + assert_eq!(status, 5); + } + + #[test] + fn autodemo_does_not_consume_an_information_message() { + let mut events = MissionEvents::default(); + let mut status = 5; + let mut outcome = MissionScriptOutcome::Active; + let mut notices = Vec::new(); + let command = VmHostCallbackCommand { + mode: 0, + first: 1, + second: 0, + }; + apply( + MissionMode::AutoDemo, + &mut status, + &mut outcome, + &mut events, + command, + &mut notices, + ) + .unwrap(); + assert!(notices.is_empty()); + apply( + MissionMode::SingleMission, + &mut status, + &mut outcome, + &mut events, + command, + &mut notices, + ) + .unwrap(); + assert_eq!(notices, [MissionNotice::Information(0)]); + } +} diff --git a/docs/appendices/knowledge-boundaries.md b/docs/appendices/knowledge-boundaries.md index f426fc36..88f7dd3e 100644 --- a/docs/appendices/knowledge-boundaries.md +++ b/docs/appendices/knowledge-boundaries.md @@ -147,6 +147,9 @@ authoring API без динамического подтверждения. `mission_hero_exit_approx` отмечает обычную зону выхода главного телепорта в исходной позе узла. Движущиеся зоны, размеры из вспомогательных векторов и переход к следующей миссии ещё открыты. +`mission_message_ui_stub` также покрывает повторные интерфейсные ветви +`Handler(30)`: FParkan показывает и озвучивает сообщение только впервые, +с общим состоянием для `Mission` и сценариев кланов. `autodemo_camera_follow_approx` и `autodemo_camera_target_approx` отмечают приближённое слежение и выбор размещённых юнитов с камерой через селектор AI. @@ -689,7 +692,7 @@ selector `3` или `4` по старшему биту. Для ветки GOG `A выставляет режим 1 (RVA `0x29142`), а обработчик таймера — режим 3 (RVA `0x70f3`). Небольшая тестовая x86-программа сравнивает этот обратный вызов с исходной DLL на синтетических структурах. Rust применяет переход исхода из периодического -события `Mission`. Голоса и заголовок подключены, исходный экран результатов +события `Mission` и событий AI. Голоса и заголовок подключены, исходный экран результатов и переход к следующей миссии ещё открыты. Закрывающий эксперимент: найти dispatcher loop в `ai.dll`, сопоставить jump diff --git a/docs/appendices/script-vm.md b/docs/appendices/script-vm.md index ed8fa718..2bf98686 100644 --- a/docs/appendices/script-vm.md +++ b/docs/appendices/script-vm.md @@ -82,6 +82,11 @@ FParkan проверяет текущую позицию размещённогÐ показе сообщения оригинал запускает голос (RVA `0x61fb0`). FParkan читает голосовой ключ из `messages.cfg`, разрешает архив и файл через `mission.cfg` и воспроизводит реплики в порядке вызова. +Обратный вызов общий для всех кланов: сообщение из `Problems0` попадает +в ту же очередь, что и сообщение из `Mission`. В «Конвое» клан 2 после +сценарного приказа атаковать запрашивает сообщение 0. Прямой вызов +обработчика `ai.dll` RVA `0xc266` подтвердил `(0, 1, 0)` для контекстов +кланов 0 и 2; аргументы читаются из текущих ячеек varset. `Handler(31)` считает объекты выбранного клана. В той же сборке `ai.dll` (RVA `0xc2fd`) обработчик читает список объектов клана, @@ -2335,8 +2340,8 @@ Native-часть этих ABI проверок воспроизводит ветвям игры; режим `2` выполняет отдельный вызов IGame, а ветви для режима `1` в этой функции нет. -Статический анализ восстановил также `command == 1`, но не дал основания -присвоить этой ветви предметное имя. Её аргумент `payload` — знаковый ключ +Команда `1`, обозначенная в varset как `MESSAGE_INFO`, выбирает сообщение. +Её аргумент `payload` — знаковый ключ бинарного дерева поиска. Поле `+0x04` у получателя указывает на корневой сторожевой узел; в каждом узле ссылки на дочерние узлы лежат по `+0x08` и `+0x0c`, ключ — по `+0x10`, а передаваемый дальше аргумент — по `+0x14`. При @@ -2346,9 +2351,9 @@ Native-часть этих ABI проверок воспроизводит слот `+0x1c` и передаёт значение `+0x0c` объекта-аргумента в `FUN_10061fb0`. При повторных вызовах используются идентификаторы менеджера ресурсов `0x181a` и `0x184f`, селектор IGame `0x2ed` и непрозрачный запрос с категорией `3` или -`4`, выбираемой по `+0x18`. Это подтверждает поиск и различие первого и -повторных вызовов, но не назначение сообщения интерфейса или смысл этих -идентификаторов; в Rust команда `1` поэтому остаётся `Unhandled`. +`4`, выбираемой по `+0x18`. FParkan показывает текст и запускает голос +при первом вызове; состояние показа общее для сценариев всех кланов. +Повторные интерфейсные ветви с этими идентификаторами ещё не воспроизведены. ### Состояние обратного вызова исхода миссии |
