diff options
| author | Valentin Popov <valentin@popov.link> | 2026-12-01 07:33:51 +0300 |
|---|---|---|
| committer | Valentin Popov <valentin@popov.link> | 2026-12-01 07:33:51 +0300 |
| commit | 777f48345c7faf891ac105fc4a831114914aff5d (patch) | |
| tree | a9e550c582aa976d87e6c0ae4297e7c29e6e5526 | |
| parent | 352026c1ce039443efc779876b27654d992bfff1 (diff) | |
| download | fparkan-777f48345c7faf891ac105fc4a831114914aff5d.tar.xz fparkan-777f48345c7faf891ac105fc4a831114914aff5d.zip | |
fix(combat): charge the drive before refilling weapons
Read the resource multiplier from CTL when all authored states agree and price the latest local motion in the existing Control budget. A licensed AutoDemo flyer charges its weapons more slowly when the drive is drawing from the same supply. Control.dll oracle vectors, the AutoDemo window, and all 29 mission startup sweeps pass.
| -rw-r--r-- | apps/fparkan-game/src/main.rs | 1 | ||||
| -rw-r--r-- | crates/fparkan-assets/src/lib.rs | 20 | ||||
| -rw-r--r-- | crates/fparkan-runtime/src/control_resources.rs | 35 | ||||
| -rw-r--r-- | crates/fparkan-runtime/src/lib.rs | 20 | ||||
| -rw-r--r-- | crates/fparkan-runtime/src/mobile_budget.rs | 196 | ||||
| -rw-r--r-- | docs/appendices/knowledge-boundaries.md | 6 | ||||
| -rw-r--r-- | docs/appendices/script-vm.md | 10 | ||||
| -rw-r--r-- | docs/tomes/06-behavior.md | 17 |
8 files changed, 278 insertions, 27 deletions
diff --git a/apps/fparkan-game/src/main.rs b/apps/fparkan-game/src/main.rs index 8075ef2c..2ed8b995 100644 --- a/apps/fparkan-game/src/main.rs +++ b/apps/fparkan-game/src/main.rs @@ -14409,6 +14409,7 @@ mod tests { type_id: None, }, native_profile_words: [0; 27], + uniform_drive_factor_bits: None, model_node_count: 2, bindings: vec![], timeline_rows: vec![PreparedControlTimelineRow { diff --git a/crates/fparkan-assets/src/lib.rs b/crates/fparkan-assets/src/lib.rs index 4738f175..88c3b193 100644 --- a/crates/fparkan-assets/src/lib.rs +++ b/crates/fparkan-assets/src/lib.rs @@ -1039,6 +1039,8 @@ pub struct PreparedComponentControl { pub source: ResourceKey, /// The 27 raw native owner-profile words at CTLD bytes 20..128. pub native_profile_words: [u32; 27], + /// Drive demand multiplier when all authored CTL states agree. + pub uniform_drive_factor_bits: Option<u32>, /// Number of nodes in the component model this control targets. pub model_node_count: usize, /// Enabled source rows in their original order, including duplicate nodes. @@ -4281,12 +4283,11 @@ fn decode_component_control_payload_with_opcodes( let per_section_node_bytes = SECTION_NODE_BYTES .checked_mul(per_section_nodes) .ok_or_else(|| invalid("section node bytes overflow"))?; + let section_stride = SECTION_FIXED_BYTES + .checked_add(per_section_node_bytes) + .ok_or_else(|| invalid("section size overflows"))?; let section_bytes = section_count - .checked_mul( - SECTION_FIXED_BYTES - .checked_add(per_section_node_bytes) - .ok_or_else(|| invalid("section size overflows"))?, - ) + .checked_mul(section_stride) .ok_or_else(|| invalid("section table bytes overflow"))?; let matrix_bytes = section_count .checked_mul(section_count) @@ -4381,10 +4382,19 @@ fn decode_component_control_payload_with_opcodes( )?; let initial_group_opcodes = decoded_effect.initial_group_opcodes; + // Control copies CTL state +0x54 into the active owner field +0x154. + let state_start = HEADER_BYTES + FIXED_SECTION_BYTES; + let mut factors = payload[state_start..state_start + section_bytes] + .chunks_exact(section_stride) + .map(|state| control_u32_at(state, 0x54).expect("complete CTL state")); + let uniform_drive_factor_bits = factors + .next() + .filter(|&first| factors.all(|next| next == first)); Ok(( PreparedComponentControl { source, native_profile_words, + uniform_drive_factor_bits, model_node_count, bindings, timeline_rows, diff --git a/crates/fparkan-runtime/src/control_resources.rs b/crates/fparkan-runtime/src/control_resources.rs index e34a3dfc..0b1f853b 100644 --- a/crates/fparkan-runtime/src/control_resources.rs +++ b/crates/fparkan-runtime/src/control_resources.rs @@ -1,11 +1,11 @@ use crate::{ - control_profile, control_resource_budget_pass, repair_zone, ControlProfileReport, Engine, - MissionControlDeviceTableStatus, MobileBudgetReport, + control_profile, control_resource_budget_pass_with_motion, mobile_budget::DriveMotion, + repair_zone, ControlProfileReport, Engine, MissionControlDeviceTableStatus, MobileBudgetReport, }; -use fparkan_world::{transform_state, ObjectHandle}; +use fparkan_world::{transform_state, ObjectHandle, TransformState}; use std::collections::BTreeMap; -/// Supported Control budgets; motion callbacks and global RNG ordering remain open. +/// Supported Control budgets and per-owner resource clocks. pub(super) struct Resources { clocks: Vec<(ObjectHandle, ResourceClock)>, rng: u32, @@ -109,6 +109,8 @@ pub(super) fn tick(engine: &mut Engine, now_ms: u32) { .expect("new Control resource clock") .1 }; + let frame_seconds = (now_ms as f32 - clock.frame_ms) * 0.001; + let previous_pose = clock.previous_pose.replace(pose); // Control.dll+0x42480: default resource period; this is a separate RNG from Behavior. let Some(seconds) = clock.step(now_ms as f32, true, 250.0, &mut state.rng) else { continue; @@ -160,7 +162,20 @@ pub(super) fn tick(engine: &mut Engine, now_ms: u32) { } } } - match control_resource_budget_pass(table, seconds) { + let motion = previous_pose.filter(|_| mobile_owner).and_then(|previous| { + let can_fly = table + .original_id + .and_then(|id| mission.unit_chassis_flags.get(&id.0)) + .and_then(|flags| flags.can_fly)?; + DriveMotion::sample( + table, + &mission.mission_assets, + [previous, pose], + frame_seconds, + can_fly, + ) + }); + match control_resource_budget_pass_with_motion(table, seconds, motion) { Ok(()) => { state .blocked_budgets @@ -169,10 +184,11 @@ pub(super) fn tick(engine: &mut Engine, now_ms: u32) { *state.mobile.ticks.entry(object).or_default() += 1; if let MissionControlDeviceTableStatus::Available(devices) = &table.status { for device in devices { - if device.factory_tag == 5 && device.native_word_50_bits != Some(0) { - state - .mobile - .stub(object, format!("motion_factory_{}", device.factory_tag)); + if motion.is_none() + && device.factory_tag == 5 + && device.native_word_50_bits != Some(0) + { + state.mobile.stub(object, "motion_factory_5".into()); } if matches!(device.factory_tag, 2 | 30) && f32::from_bits(device.descriptor.fixed_words[8]) != 0.0 @@ -220,6 +236,7 @@ pub(super) fn tick(engine: &mut Engine, now_ms: u32) { #[derive(Default)] struct ResourceClock { frame_ms: f32, + previous_pose: Option<TransformState>, resource_ms: f32, forced: u32, alarm: control_profile::DamageAlarm, diff --git a/crates/fparkan-runtime/src/lib.rs b/crates/fparkan-runtime/src/lib.rs index 5f3f436e..0ac5197f 100644 --- a/crates/fparkan-runtime/src/lib.rs +++ b/crates/fparkan-runtime/src/lib.rs @@ -4496,10 +4496,18 @@ fn control_resource_budget_pass( table: &mut MissionControlDeviceTableState, delta_time_seconds: f32, ) -> Result<(), ControlResourceAccessError> { + control_resource_budget_pass_with_motion(table, delta_time_seconds, None) +} + +fn control_resource_budget_pass_with_motion( + table: &mut MissionControlDeviceTableState, + delta_time_seconds: f32, + motion: Option<mobile_budget::DriveMotion>, +) -> Result<(), ControlResourceAccessError> { let delta_time_seconds = checked_control_float(0, "Control resource interval", delta_time_seconds)?; let mut updated = table.clone(); - control_resource_budget_pass_inner(&mut updated, delta_time_seconds)?; + control_resource_budget_pass_inner(&mut updated, delta_time_seconds, motion)?; *table = updated; Ok(()) } @@ -4507,6 +4515,7 @@ fn control_resource_budget_pass( fn control_resource_budget_pass_inner( table: &mut MissionControlDeviceTableState, delta_time_seconds: f32, + motion: Option<mobile_budget::DriveMotion>, ) -> Result<(), ControlResourceAccessError> { let device_count = match &table.status { MissionControlDeviceTableStatus::Available(devices) => devices.len(), @@ -4534,7 +4543,12 @@ fn control_resource_budget_pass_inner( let mut positive_rate_sum = 0.0_f32; for index in 0..device_count { let device = control_budget_device(table, index)?; - let rate = control_device_resource_rate(table, &device, delta_time_seconds)?; + let rate = match motion { + Some(motion) if device.factory_tag == 5 => { + motion.rate(table, device, delta_time_seconds)? + } + _ => control_device_resource_rate(table, device, delta_time_seconds)?, + }; if rate > 0.0 { positive_rate_sum = checked_control_sum( device.factory_tag, @@ -8381,6 +8395,7 @@ mod tests { PreparedComponentControl { source: synthetic_resource_key(940), native_profile_words: [0; 27], + uniform_drive_factor_bits: None, model_node_count: 3, bindings: Vec::new(), timeline_rows: Vec::new(), @@ -8888,6 +8903,7 @@ mod tests { PreparedComponentControl { source: synthetic_resource_key(100 + index), native_profile_words: [0; 27], + uniform_drive_factor_bits: None, model_node_count: 0, bindings: Vec::new(), timeline_rows: Vec::new(), diff --git a/crates/fparkan-runtime/src/mobile_budget.rs b/crates/fparkan-runtime/src/mobile_budget.rs index ee643cb1..06dc251e 100644 --- a/crates/fparkan-runtime/src/mobile_budget.rs +++ b/crates/fparkan-runtime/src/mobile_budget.rs @@ -4,8 +4,8 @@ use crate::{ checked_control_float, checked_control_product, checked_control_ratio, checked_control_sum, control_budget_device, control_device_budget_active_provider_value, control_device_budget_coefficient, control_device_budget_descriptor_float, - ControlResourceAccessError, EffectiveControlDevice, MissionControlDeviceTableState, - MissionControlDeviceTableStatus, + ControlResourceAccessError, EffectiveControlDevice, MissionAssets, + MissionControlDeviceTableState, MissionControlDeviceTableStatus, TransformState, }; use std::collections::BTreeMap; @@ -168,11 +168,91 @@ pub(super) fn passive_device_rate( } pub(super) fn unmodeled_motion_rate() -> f32 { - // shortcut: Control motion vectors and +0x154 are not supplied by the - // temporary movement controller. Resources counts this omission per owner. + // shortcut: omit demand where the live CTL state has not been recovered. 0.0 } +#[derive(Clone, Copy)] +pub(super) struct DriveMotion { + local_speed: f32, + profile_limit: f32, + state_factor: f32, +} + +impl DriveMotion { + pub(super) fn sample( + table: &MissionControlDeviceTableState, + assets: &MissionAssets, + [previous, current]: [TransformState; 2], + frame_seconds: f32, + can_fly: bool, + ) -> Option<Self> { + let object = table.original_id?.0 as usize; + let profile = table.owner_profile.as_ref()?; + let control = assets + .object_component_controls + .get(object)? + .get(profile.unit_component_index)? + .as_ref()?; + let state_factor = f32::from_bits(control.uniform_drive_factor_bits?); + let limits = profile.original_words[6..9] + .iter() + .map(|&word| f32::from_bits(word)); + let profile_limit = largest_component(limits)?; + let [dx, dy, dz] = std::array::from_fn(|axis| { + f32::from_bits(current.position[axis]) - f32::from_bits(previous.position[axis]) + }); + let (sin, cos) = f32::from_bits(current.orientation[2]).sin_cos(); + // shortcut: use the frame's realized displacement until native motion publishes its local vector. + let local_speed = largest_component([ + (cos * dx + sin * dy) / frame_seconds, + (-sin * dx + cos * dy) / frame_seconds, + if can_fly { dz / frame_seconds } else { 0.0 }, + ])?; + (profile_limit > 0.0 && state_factor.is_finite() && !state_factor.is_subnormal()).then_some( + Self { + local_speed, + profile_limit, + state_factor, + }, + ) + } + + pub(super) fn rate( + self, + table: &MissionControlDeviceTableState, + device: &EffectiveControlDevice, + seconds: f32, + ) -> Result<f32, ControlResourceAccessError> { + if control_device_budget_active_provider_value(table, device)?.is_none() { + return Ok(0.0); + } + self.demand( + control_device_budget_descriptor_float(device, 8, "drive rate")?, + seconds, + ) + } + + fn demand(self, descriptor_rate: f32, seconds: f32) -> Result<f32, ControlResourceAccessError> { + let fraction = + checked_control_ratio("drive speed fraction", self.local_speed, self.profile_limit)?; + let rate = checked_control_product(5, "drive nominal demand", fraction, descriptor_rate)?; + let rate = checked_control_product(5, "drive state demand", rate, self.state_factor)?; + Ok(-checked_control_product( + 5, + "drive interval demand", + rate, + seconds, + )?) + } +} + +fn largest_component(values: impl IntoIterator<Item = f32>) -> Option<f32> { + values.into_iter().try_fold(0.0_f32, |largest, value| { + (value.is_finite() && !value.is_subnormal()).then(|| largest.max(value.abs())) + }) +} + pub(super) fn read( mission: &crate::LoadedMissionState, handle: crate::ObjectHandle, @@ -283,6 +363,24 @@ mod tests { use super::*; #[test] + fn drive_demand_uses_largest_local_axis_and_the_ctl_factor() { + let profile_limit = largest_component([5.0, 14.0, 7.0]).unwrap(); + for (velocity, state_factor, seconds, expected) in [ + ([0.0, -7.0, 2.0], 0.8, 0.25, 0xbe80_0000), + ([-14.0, 1.0, 2.0], 1.0, 0.5, 0xbfa0_0000), + ([1.0, 2.0, -7.0], 1.0, 1.0, 0xbfa0_0000), + ([0.0, -7.0, 2.0], 0.0, 0.25, 0x8000_0000), + ] { + let motion = DriveMotion { + local_speed: largest_component(velocity).unwrap(), + profile_limit, + state_factor, + }; + assert_eq!(motion.demand(2.5, seconds).unwrap().to_bits(), expected); + } + } + + #[test] fn native_weapon_budget_refills_disabled_devices_and_can_go_negative() { // GOG Control.dll +0x29a40 / +0x29a90, x87 CW 0x007f. for (capacity, amount, dt, upkeep, allocation, active, rate, charge, multiplier) in [ @@ -337,6 +435,96 @@ mod tests { #[test] #[ignore = "requires licensed corpus"] + fn licensed_autodemo_flyer_uses_its_drive_budget_in_motion() { + use crate::{ + create, frame, load_gameplay_mission, EngineServices, MissionMode, MissionRequest, + MissionStartupInput, + }; + use fparkan_vfs::DirectoryVfs; + use std::sync::Arc; + + let root = std::env::var_os("FPARKAN_CORPUS_PART1_ROOT").unwrap(); + let mut engine = create(EngineServices::new(Arc::new(DirectoryVfs::new(root)))).unwrap(); + load_gameplay_mission( + &mut engine, + MissionRequest { + key: "MISSIONS/Autodemo.00/data.tma".into(), + mode: MissionMode::AutoDemo, + }, + MissionStartupInput { + queue_time_ms: 0, + research_creation_gate: false, + }, + None, + ) + .unwrap(); + engine.autodemo_combat = None; + let mission = engine.loaded.as_ref().unwrap(); + let flyer = mission + .control_device_tables + .iter() + .position(|table| table.original_id == Some(fparkan_world::OriginalObjectId(2))) + .unwrap(); + let handle = mission.control_device_tables[flyer].handle; + let start = fparkan_world::transform_state(&engine.world, handle) + .unwrap() + .position; + let mut drive_spent = false; + for now in (0..=6_000).step_by(100) { + frame(&mut engine, now).unwrap(); + let mission = engine.loaded.as_ref().unwrap(); + drive_spent |= + f32::from_bits(mission.control_device_tables[flyer].current_output_rate_5e0_bits) + > 0.0; + } + let end = fparkan_world::transform_state(&engine.world, handle) + .unwrap() + .position; + assert_ne!(start, end); + let stubs = &engine + .loaded + .as_ref() + .unwrap() + .control_resources + .mobile + .stubs; + assert!(!stubs.contains_key(&(2, "motion_factory_5".into()))); + assert!(drive_spent, "motion must draw from the budget"); + + let mut at_rest = engine.loaded.as_ref().unwrap().control_device_tables[flyer].clone(); + let MissionControlDeviceTableStatus::Available(devices) = &mut at_rest.status else { + panic!("stock flyer has a complete Control table"); + }; + for device in devices.iter_mut().filter(|device| device.factory_tag == 2) { + device.weapon_charge_bits = Some(0); + } + let mut in_motion = at_rest.clone(); + crate::control_resource_budget_pass(&mut at_rest, 0.5).unwrap(); + crate::control_resource_budget_pass_with_motion( + &mut in_motion, + 0.5, + Some(DriveMotion { + local_speed: 10.0, + profile_limit: 10.0, + state_factor: 1.0, + }), + ) + .unwrap(); + let charge = |table: &MissionControlDeviceTableState| { + let MissionControlDeviceTableStatus::Available(devices) = &table.status else { + panic!("stock flyer has a complete Control table"); + }; + let weapon = devices + .iter() + .find(|device| device.factory_tag == 2) + .unwrap(); + f32::from_bits(weapon.weapon_charge_bits.unwrap()) + }; + assert!(charge(&in_motion) < charge(&at_rest)); + } + + #[test] + #[ignore = "requires licensed corpus"] fn licensed_stock_lasers_wait_for_charge_and_recover_from_the_unit_budget() { use crate::{ create, frame, load_gameplay_mission, EngineServices, MissionMode, MissionRequest, diff --git a/docs/appendices/knowledge-boundaries.md b/docs/appendices/knowledge-boundaries.md index e00f43d5..713c8b15 100644 --- a/docs/appendices/knowledge-boundaries.md +++ b/docs/appendices/knowledge-boundaries.md @@ -258,7 +258,9 @@ CTL типа 24 и дорожки выстрела типа 2. Точное ус seed и общий порядок Control RNG открыты. `control_resource_budget_stub` считает неподдержанные шаги по объектам и сохраняет первую причину отказа. `control_mobile_budget_approx` считает мобильные бюджетные шаги. `control_mobile_budget_stub` -считает нулевую подмену расхода ходовой, открытый режим оружия и отказы бюджета/связи орудия; +считает нулевую подмену расхода при недоступном состоянии ходовой, открытый +режим оружия и отказы бюджета/связи орудия. Для одинакового коэффициента CTL +расход уже учитывается, локальная скорость берётся из перемещения за кадр; при отказе бюджета ограничение стрельбы зарядом отключается до успешного шага. `mission_patrol_approx` отмечает приказы варботам патрулировать точку из @@ -1357,7 +1359,7 @@ Dirty-ветвь `0x12a40` обновляет means и FCA0, включая ав Сверка момента обхода, сменные стадии модели, скрытие навесных узлов и эффекты дочерних узлов остаются открыты. Аварийное истощение использует общее удаление корпуса. -Изменения scalar и расход ходовой ещё открыты. +Изменения scalar и расход ходовой при переключении состояний CTL ещё открыты. Отдельные constructor, setter и loader-пути уже прослежены; физические единицы слов профиля и накопителей остаются неизвестны. Для закрытия границы нужны динамическая трассировка и сравнение полного Unit DAT load с оригинальным diff --git a/docs/appendices/script-vm.md b/docs/appendices/script-vm.md index b61be594..70874021 100644 --- a/docs/appendices/script-vm.md +++ b/docs/appendices/script-vm.md @@ -1256,7 +1256,15 @@ charge и M. При неположительной ёмкости update сохÑ Ходовая фабрика `5` использует rate `0x265c0`: максимум модулей текущего вектора `owner+0x1c8`, делённый на максимум исходных пределов `[6..8]`, умножается на descriptor rate, динамическое `owner+0x154` и интервал. -Динамические входы ещё не поставляются временным контроллером FParkan. +В запущенном AutoDemo выбранная запись состояния копируется в `owner+0x100` +по RVA `0xc37a` той же GOG `Control.dll`. Загрузчик `0x8f40` вызывает +`0x1730`, который переносит фиксированные поля CTL, включая `+0x54`, в +записи по `owner+0x39c`. Номер текущего состояния хранится в `owner+0xfc`. +В единственном состоянии `r_b_02.ctl` коэффициент равен `1`. У `r_b_01.ctl` +состояние 0 даёт `0`, а состояние 19 даёт `1`. Переходы наблюдались на +живых варботах, в том числе при ненулевом векторе движения. +FParkan использует подтверждённое поле, если все состояния дают одинаковый +коэффициент, и оценивает локальный вектор по перемещению за кадр. #### Генератор tag 19 в том же бюджетном проходе diff --git a/docs/tomes/06-behavior.md b/docs/tomes/06-behavior.md index 0dda087d..c6a0f2dd 100644 --- a/docs/tomes/06-behavior.md +++ b/docs/tomes/06-behavior.md @@ -354,8 +354,17 @@ Control. Снаряд использует скорость, время жизн Общий ресурсный шаг также обслуживает устройство tag 10 в штатном режиме `0x2000`. Фабрика 1 использует те же бюджетные методы, что простые устройства. -Расход ходовой пока подменён нулём с отдельным счётчиком по владельцу: -оригинал использует в нём динамические поля полного контроллера движения. +Ходовая запрашивает часть того же питания до зарядки оружия. Оригинал +делит самый большой модуль скорости вдоль осей корпуса на самый большой +предел из исходного профиля. Затем умножает эту долю на ставку устройства, +коэффициент текущего состояния CTL и длительность ресурсного шага. При +ставке 2,5, половине предельной скорости, коэффициенте 0,8 и шаге в +четверть секунды ходовая запрашивает 0,25 единицы питания. + +В FParkan этот расчёт работает у машин, у которых коэффициент одинаков во +всех записанных состояниях CTL. Скорость по осям считается по фактическому +перемещению за кадр. Переключения состояний с разными коэффициентами пока +отмечаются заглушкой. Активный режим tag 10 и неполные бюджетные таблицы останавливаются явно; для такого владельца ограничение стрельбы зарядом временно отключается. Поэтому этот путь ещё не устанавливает точный энергетический баланс боя. @@ -1683,8 +1692,8 @@ Rust хранит исходные слова отдельно, считает Ð Предел хода с двумя исчерпанными группами равен нулю. Восстановление обеих групп до 30% прекращает потерю прочности и возвращает ход. Бортовой ремонт остаётся выключенным. Полная цепочка разрушения узлов остаётся приближённой. -Динамический расход ходовой пока открыт. Заряд -орудий и их пополнение уже участвуют в общем бюджете владельца. +Расход поддержанных ходовых делит питание с зарядом орудий, как описано +в разделе о мобильном бюджете. У варботов AutoDemo первая группа CTL создаёт `smoke_fr_01` на узле корпуса. Заголовок FXID с флагом `0x40` оставляет его выключенным. Ссылки CTL по |
