From 9e9833846e7f8b354493b8962123af4508bc0cda Mon Sep 17 00:00:00 2001 From: Valentin Popov Date: Sat, 14 Nov 2026 20:29:40 +0400 Subject: fix(script): honor numeric condition scopes during Init Shares condition execution with Mission and compares a float left operand as f32. Native ai.dll confirms all six operators on the observed difficulty comparison. The complete 900 s corpus has no crashes or periodic Mission stops; remaining Init stops are Handlers 15 and 68. --- crates/fparkan-script/src/lib.rs | 156 ++++++++++++++++++++++++++------ docs/appendices/knowledge-boundaries.md | 3 +- docs/appendices/script-vm.md | 10 ++ 3 files changed, 139 insertions(+), 30 deletions(-) diff --git a/crates/fparkan-script/src/lib.rs b/crates/fparkan-script/src/lib.rs index d28a3d19..9f71c5b8 100644 --- a/crates/fparkan-script/src/lib.rs +++ b/crates/fparkan-script/src/lib.rs @@ -209,6 +209,8 @@ pub enum ScriptInitResolveError { Handler19(Handler19ResolveError), /// The clan-count query has unsupported operands, control, or result type. UnsupportedClanCount, + /// A conditional scope cannot be evaluated with the current cells. + UnsupportedCondition, /// A formula record has an unsupported control word. UnsupportedFormulaControlWord { /// Raw disk word at index 3. @@ -262,6 +264,9 @@ impl std::fmt::Display for ScriptInitResolveError { formatter, "Handler(31) requires an unconditional query with DWORD operands and result" ), + Self::UnsupportedCondition => { + write!(formatter, "unsupported comparison operands in Init") + } Self::UnsupportedFormulaControlWord { found } => write!( formatter, "unsupported formula control word 0x{found:08x}; expected 0x6 or 0xffffffff" @@ -848,7 +853,20 @@ impl VarSet { writes: Vec::new(), stopped_at: None, }; + let mut conditions = Vec::new(); for (instruction_index, instruction) in event.instructions.iter().enumerate() { + match advance_condition(&mut conditions, instruction, &values) { + Ok(EventInstruction::Skip) => continue, + Ok(EventInstruction::Return) => break, + Ok(EventInstruction::Execute) => {} + Err(()) => { + prefix.stopped_at = Some(( + instruction_index, + ScriptInitResolveError::UnsupportedCondition, + )); + break; + } + } let writes = match self.resolve_init_instruction( instruction, input, @@ -1097,34 +1115,14 @@ impl VarSet { ) -> Result<(), (usize, String)> { let mut conditions = Vec::new(); for (index, instruction) in event.instructions.iter().enumerate() { - let active = conditions.last().copied().unwrap_or(true); - let control = instruction.header_words[3]; - match control { - 0 => { - let condition = if active { - mission_condition(instruction, values) - .ok_or_else(|| (index, "unsupported comparison operands".into()))? - } else { - false - }; - conditions.push(condition); - continue; - } - 1 => { - conditions.pop(); - continue; - } - 2 => continue, - _ => {} - } - // The VM gates ordinary actions and branches. Immediate writes - // have their own switch case and still run inside a false branch. - if !active && matches!(control, u32::MAX | 3..=5) { - continue; - } - if control == 5 { - break; + match advance_condition(&mut conditions, instruction, values) + .map_err(|()| (index, "unsupported comparison operands".into()))? + { + EventInstruction::Skip => continue, + EventInstruction::Return => break, + EventInstruction::Execute => {} } + let control = instruction.header_words[3]; if instruction.dispatch_selector() != ScriptDispatchSelector::Sentinel { if control != u32::MAX { return Err((index, format!("unsupported handler control {control}"))); @@ -1752,9 +1750,61 @@ fn varset_value_as_f32(type_name: VarSetType, value: VarSetDefault) -> Option, + instruction: &ScriptInstruction, + values: &[VarSetDefault], +) -> Result { + let active = conditions.last().copied().unwrap_or(true); + Ok(match instruction.header_words[3] { + 0 if instruction.dispatch_selector() == ScriptDispatchSelector::Sentinel => { + conditions.push(active && mission_condition(instruction, values).ok_or(())?); + EventInstruction::Skip + } + 1 if instruction.dispatch_selector() == ScriptDispatchSelector::Sentinel => { + conditions.pop(); + EventInstruction::Skip + } + 2 if instruction.dispatch_selector() == ScriptDispatchSelector::Sentinel => { + EventInstruction::Skip + } + u32::MAX | 3..=5 if !active => EventInstruction::Skip, + 5 if instruction.dispatch_selector() == ScriptDispatchSelector::Sentinel => { + EventInstruction::Return + } + // Immediate writes run even inside a false branch. + _ => EventInstruction::Execute, + }) +} + fn mission_condition(instruction: &ScriptInstruction, values: &[VarSetDefault]) -> Option { - let (lhs, rhs) = instruction.dword_pair(values)?; - match instruction.header_words[4] { + let &[left, right] = instruction.references.as_slice() else { + return None; + }; + let lhs = *values.get(left as usize)?; + let rhs = *values.get(right as usize)?; + let comparison = instruction.header_words[4]; + match (lhs, rhs) { + (VarSetDefault::Dword(lhs), VarSetDefault::Dword(rhs)) => compare(comparison, lhs, rhs), + (VarSetDefault::FloatBits(lhs), rhs) => { + let rhs = match rhs { + VarSetDefault::Dword(rhs) => rhs as f32, + VarSetDefault::FloatBits(rhs) => f32::from_bits(rhs), + }; + compare(comparison, f32::from_bits(lhs), rhs) + } + _ => None, + } +} + +fn compare(comparison: u32, lhs: T, rhs: T) -> Option { + match comparison { 0 => Some(lhs < rhs), 1 => Some(lhs == rhs), 2 => Some(lhs > rhs), @@ -3334,6 +3384,54 @@ STRING( 8, ignored, ignored, ignored)\r\n"; assert!(formulas.evaluate_numeric_literal(0).is_err()); } + #[test] + fn init_float_condition_only_gates_formula_write() { + let varset = parse_varset( + b"VAR(float, fDifficulty, 0.5)\nVAR(float, f0, 0)\nVAR(DWORD, target, 0)\n", + ) + .unwrap(); + let branch = ScriptInstruction { + header_words: [u32::MAX, u32::MAX, u32::MAX, 0, 3, 2, u32::MAX], + references: vec![0, 1], + }; + let close = ScriptInstruction { + header_words: [u32::MAX, u32::MAX, u32::MAX, 1, 6, 0, u32::MAX], + references: Vec::new(), + }; + let immediate = ScriptInstruction { + header_words: [u32::MAX, 2, 100, 6, 6, 0, u32::MAX], + references: Vec::new(), + }; + let package = init_package(vec![ + branch.clone(), + init_formula_assignment(2, 0), + immediate, + close, + ]); + let formulas = one_formula(b"50"); + let prefix = varset + .resolve_init_prefix(&package, init_input(), Some(&formulas)) + .unwrap() + .unwrap(); + assert_eq!(prefix.stopped_at, None); + assert_eq!( + prefix.writes, + [ScriptInitWrite { + index: 2, + value: VarSetDefault::Dword(100) + }] + ); + let mut package = package; + package.events[0].instructions[0].header_words[4] = 2; + let prefix = varset + .resolve_init_prefix(&package, init_input(), Some(&formulas)) + .unwrap() + .unwrap(); + assert_eq!(prefix.stopped_at, None); + assert_eq!(prefix.writes.len(), 2); + assert_eq!(prefix.writes[0].value, VarSetDefault::Dword(50)); + } + #[test] fn script_init_multiplies_before_addition_and_subtraction() { let varset = diff --git a/docs/appendices/knowledge-boundaries.md b/docs/appendices/knowledge-boundaries.md index bf4ddf5e..f37929e6 100644 --- a/docs/appendices/knowledge-boundaries.md +++ b/docs/appendices/knowledge-boundaries.md @@ -15,7 +15,8 @@ authoring API без динамического подтверждения. Проверка сроков `Handler(59/60)` использует секунды с начала миссии. Связь с таймером обновлений каждого AI остаётся открытой. `script_mission_unsupported` считает первые остановки на новых инструкциях. -Вещественные сравнения и переходы ещё открыты. +Переходы за пределами вложенных условий и сравнение DWORD с вещественной +клеткой справа ещё открыты. `mission_tactical_ids_stub` отмечает, что тактические области и запрос клана по логическому ID учитывают размещённые объекты. Назначение логических ID diff --git a/docs/appendices/script-vm.md b/docs/appendices/script-vm.md index 374f3be8..8c331def 100644 --- a/docs/appendices/script-vm.md +++ b/docs/appendices/script-vm.md @@ -2447,6 +2447,16 @@ FParkan исполняет эту ветвь для размещённых ва целые секунды игрового времени после старта миссии. Оригинальный AI продвигает свой счётчик при собственных обновлениях, в частности на 7 по RVA `0x1780`. +### Ветвление по числу + +Открытие и закрытие условий в `Init` используют те же правила, что и в +`Mission`. Диспетчер GOG `ai.dll` по RVA `0x12020` выбирает тип сравнения +по первому операнду. Для вещественной клетки он сравнивает оба операнда как +`f32`. Прямой вызов DLL подтвердил, в частности, что при сложности 0,5 +ветвь `fDifficulty <= f0` с `f0 = 0` пропускается. В такой ветви присваивание +из формулы пропускается, а непосредственная запись остаётся отдельным +случаем диспетчера и выполняется. + ### Резервирование юнита `Handler(51)` в той же сборке `ai.dll` по RVA `0xe00c` ищет логический -- cgit v1.2.3