From 8ac763f7bfda827016d17c66372d02b85d5a9bb5 Mon Sep 17 00:00:00 2001 From: Valentin Popov Date: Thu, 26 Nov 2026 01:38:43 +0400 Subject: feat(combat): feed weapon charge from Control energy budgets Keep factory-2/30 charge in the owner's Control table. AI and player banks read it before firing, debit completed shots and wait for regeneration. Preserve one charge across bank changes and accumulate energy waits by object, including an idle bank publishing after an active bank. Mobile owners now run the resource budget. Restore the shared factory-1 callbacks, factory-2/30 charging and factory-10 passive upkeep. Factory 30 uses the weapon constructor's native disabled default. Motion demand is still an explicit zero-rate stub; unsupported budgets disable charge limiting for that owner and record the reason. Execute unmodified GOG Control.dll callbacks at RVA 0x29a40/0x29a90, 0x264b0/0x26510 and 0x21860/0x21890; check the common constructor at 0x294c0. Rust golden vectors cover disabled refill, zero capacity, negative charge and x87 rounding at control word 0x007f. SHA-256: bcb86318089028548a178b03a21accdce15df0cc85ddd91674cf3c2f55012c6e. Validated fmt, workspace check/tests, release, licensed shared-bank charge exhaustion/recovery, stock combat and damaged-profile regressions. All 29 stock missions reached 900 seconds; the only mobile-budget stub was the known motion input. Observed stock window combat and replenishment. Full live native mission comparison and motion energy remain open. --- apps/fparkan-game/src/main.rs | 6 + apps/fparkan-game/src/script_coverage.rs | 13 + crates/fparkan-runtime/src/control_resources.rs | 46 ++- crates/fparkan-runtime/src/lib.rs | 33 +- crates/fparkan-runtime/src/mobile_budget.rs | 412 ++++++++++++++++++++++++ crates/fparkan-runtime/src/patrol_speed.rs | 2 +- crates/fparkan-runtime/src/player_weapon.rs | 58 +++- crates/fparkan-runtime/src/unit_combat.rs | 4 + docs/appendices/knowledge-boundaries.md | 9 +- docs/appendices/script-vm.md | 38 ++- docs/tomes/06-behavior.md | 37 ++- 11 files changed, 635 insertions(+), 23 deletions(-) create mode 100644 crates/fparkan-runtime/src/mobile_budget.rs diff --git a/apps/fparkan-game/src/main.rs b/apps/fparkan-game/src/main.rs index ef7602ea..87690e3d 100644 --- a/apps/fparkan-game/src/main.rs +++ b/apps/fparkan-game/src/main.rs @@ -10494,6 +10494,9 @@ impl StaticVulkanApp { // shortcut: the camera supplies a shared aim direction until native // per-weapon CPT direction and turret alignment agree in world space. let direction = self.view_camera.forward; + if let Some(engine) = &self.mission_engine { + weapons.read_control_energy(engine, cockpit.handle); + } for (slot, weapon, barrel) in weapons.fire(trigger, clock_ms) { let hierarchy = self .component_pose_buffers @@ -10573,6 +10576,9 @@ impl StaticVulkanApp { } } } + if let Some(engine) = &mut self.mission_engine { + weapons.publish_control_energy(engine, cockpit.handle); + } } fn advance_player_projectiles(&mut self, clock_ms: u32) -> Result<(), String> { diff --git a/apps/fparkan-game/src/script_coverage.rs b/apps/fparkan-game/src/script_coverage.rs index abb63e15..56bb19ed 100644 --- a/apps/fparkan-game/src/script_coverage.rs +++ b/apps/fparkan-game/src/script_coverage.rs @@ -21,6 +21,19 @@ pub(super) fn log_script_init(engine: &Engine, mission: &str) { } pub(super) fn log_clan_ai_stops(report: &SimulationReport) { + for (object, count) in &report.mobile_budget.ticks { + eprintln!("sim_coverage control_mobile_budget_approx={count} object={object}"); + } + for ((object, reason), count) in &report.mobile_budget.stubs { + eprintln!( + "sim_coverage control_mobile_budget_stub={count} object={object} reason={reason}" + ); + } + for (object, count) in &report.mobile_budget.weapon_waits { + if *count > 0 { + eprintln!("sim_coverage weapon_energy_wait={count} object={object}"); + } + } for (object, count) in &report.control_profiles.ticks { eprintln!("sim_coverage control_profile_clock_approx={count} object={object}"); } diff --git a/crates/fparkan-runtime/src/control_resources.rs b/crates/fparkan-runtime/src/control_resources.rs index 86a402e1..f8eedee0 100644 --- a/crates/fparkan-runtime/src/control_resources.rs +++ b/crates/fparkan-runtime/src/control_resources.rs @@ -1,16 +1,19 @@ use crate::{ control_profile, control_resource_budget_pass, ControlProfileReport, LoadedMissionState, + MissionControlDeviceTableStatus, MobileBudgetReport, }; use fparkan_world::{transform_state, ObjectHandle, World}; use std::collections::BTreeMap; -/// Factory and laboratory Control budgets; other owners and global RNG ordering remain open. +/// Supported Control budgets; motion callbacks and global RNG ordering remain open. pub(super) struct Resources { clocks: Vec<(ObjectHandle, ResourceClock)>, rng: u32, ticks: BTreeMap, stops: BTreeMap, pub(super) profiles: ControlProfileReport, + pub(super) mobile: MobileBudgetReport, + blocked_budgets: Vec, } impl Default for Resources { @@ -22,11 +25,17 @@ impl Default for Resources { ticks: BTreeMap::new(), stops: BTreeMap::new(), profiles: ControlProfileReport::default(), + mobile: MobileBudgetReport::default(), + blocked_budgets: Vec::new(), } } } impl Resources { + pub(super) fn energy_available(&self, handle: ObjectHandle) -> bool { + !self.blocked_budgets.contains(&handle) + } + pub(super) fn ticks(&self) -> impl Iterator + '_ { self.ticks.iter().map(|(&unit, &count)| (unit, count)) } @@ -43,6 +52,9 @@ pub(super) fn tick(mission: &mut LoadedMissionState, world: &World, now_ms: u32) state .clocks .retain(|(handle, _)| transform_state(world, *handle).is_ok()); + state + .blocked_budgets + .retain(|handle| transform_state(world, *handle).is_ok()); for table in &mut mission.control_device_tables { let flags = table .original_id @@ -121,18 +133,42 @@ pub(super) fn tick(mission: &mut LoadedMissionState, world: &World, now_ms: u32) } } } - if !budget_owner { - continue; - } match control_resource_budget_pass(table, seconds) { Ok(()) => { + state + .blocked_budgets + .retain(|handle| *handle != table.handle); + if mobile_owner { + *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 matches!(device.factory_tag, 2 | 30) + && f32::from_bits(device.descriptor.fixed_words[8]) != 0.0 + { + state.mobile.stub(object, "weapon_command_mode".into()); + } + } + } + } let count = state.ticks.entry(table.handle.slot).or_default(); *count += 1; if *count == 1 { - eprintln!("sim_coverage control_resource_clock_approx=1 unit={} (factory and laboratory owners; Control RNG seed and global order remain open)", table.handle.slot); + eprintln!("sim_coverage control_resource_clock_approx=1 unit={} (supported owners; Control RNG seed, activation and global order remain open)", table.handle.slot); } } Err(reason) => { + if !state.blocked_budgets.contains(&table.handle) { + state.blocked_budgets.push(table.handle); + } + if mobile_owner { + state.mobile.stub(object, format!("budget_{reason:?}")); + continue; + } let stop = state .stops .entry(table.handle.slot) diff --git a/crates/fparkan-runtime/src/lib.rs b/crates/fparkan-runtime/src/lib.rs index a1866dd3..103c669e 100644 --- a/crates/fparkan-runtime/src/lib.rs +++ b/crates/fparkan-runtime/src/lib.rs @@ -53,9 +53,11 @@ mod clan_building_queries; mod clan_clock; mod control_profile; mod control_resources; +mod mobile_budget; pub use clan_clock::note_mission_pause_elapsed; use control_profile::project_initial as project_control_owner_profile_fca0; pub use control_profile::{ControlProfileReport, ControlProfileScalars}; +pub use mobile_budget::MobileBudgetReport; mod clan_combat_groups; mod clan_combat_strength; mod clan_factory_schemes; @@ -555,6 +557,8 @@ pub struct EffectiveControlDevice { pub tag26_extra_rate_bits: Option, /// Factory-2 value read by selector 6 at native `+0x174`. pub device174_bits: Option, + /// Factory-2 charge at native +0x120, initialized by the weapon reader. + pub weapon_charge_bits: Option, /// Six class-9 budget values at native `+0x98..+0xac`. pub class9_values_bits: Option<[u32; 6]>, /// Six accumulated class-9 changes at native `+0xb0..+0xc4`. @@ -2988,6 +2992,7 @@ pub struct SimulationReport { pub patrol_points: PatrolPointReport, pub patrol_speeds: PatrolSpeedReport, pub control_profiles: ControlProfileReport, + pub mobile_budget: MobileBudgetReport, /// Approximate clan strength queries, grouped by caller and target clan. pub script_strength_queries: Vec<(usize, u16, u64)>, pub script_capture_queries: Vec<(usize, u64)>, @@ -3068,6 +3073,7 @@ pub fn simulate_mission_report( patrol_points: PatrolPointReport::default(), patrol_speeds: PatrolSpeedReport::default(), control_profiles: ControlProfileReport::default(), + mobile_budget: MobileBudgetReport::default(), script_strength_queries: Vec::new(), script_capture_queries: Vec::new(), script_attack_queries: Vec::new(), @@ -3176,6 +3182,7 @@ pub fn simulate_mission_report( .extend(loaded.clan_ai_events.research_catalogs()); report.laboratory = loaded.laboratories.report(); report.control_profiles = loaded.control_resources.profiles.clone(); + report.mobile_budget = loaded.control_resources.mobile.clone(); if let Some(patrol) = &loaded.unit_patrol { report.patrol_points = patrol.point_report.clone(); report.patrol_speeds = patrol.speed_report.clone(); @@ -4816,7 +4823,7 @@ fn control_resource_budget_pass_inner( for index in 0..device_count { let device = control_budget_device(table, index)?; control_budget_category(device.descriptor.tag)?; - if !matches!(device.factory_tag, 9 | 15 | 19 | 26) + if !matches!(device.factory_tag, 1 | 2 | 5 | 9 | 10 | 15 | 19 | 26 | 30) && !control_factory_uses_generic_budget_callbacks(device.factory_tag) { return Err(ControlResourceAccessError::UnsupportedFactoryTag { @@ -5093,6 +5100,9 @@ fn control_device_resource_rate( device: &EffectiveControlDevice, delta_time_seconds: f32, ) -> Result { + if matches!(device.factory_tag, 2 | 30) { + return mobile_budget::weapon_rate(table, device, delta_time_seconds); + } let Some(provider_value) = control_device_budget_active_provider_value(table, device)? else { return Ok(0.0); }; @@ -5100,6 +5110,8 @@ fn control_device_resource_rate( control_device_budget_descriptor_float(device, 8, "descriptor resource rate +0x20")?; match device.factory_tag { + 5 => Ok(mobile_budget::unmodeled_motion_rate()), + 10 => mobile_budget::passive_device_rate(device, delta_time_seconds), 9 => { let coefficient_0 = control_device_budget_coefficient(device, 0)?; let coefficient_1 = control_device_budget_coefficient(device, 1)?; @@ -5362,6 +5374,12 @@ fn control_device_resource_update( delta_time_seconds: f32, allocation: f32, ) -> Result<(), ControlResourceAccessError> { + if matches!( + control_budget_device(table, device_index)?.factory_tag, + 2 | 30 + ) { + return mobile_budget::weapon_update(table, device_index, delta_time_seconds, allocation); + } let device = control_budget_device(table, device_index)?; let Some(provider_value) = control_device_budget_active_provider_value(table, &device)? else { return Ok(()); @@ -5573,7 +5591,7 @@ fn control_device_resource_update( )?; } } - 26 => set_control_device_multiplier(table, device_index, allocation)?, + 5 | 10 | 26 => set_control_device_multiplier(table, device_index, allocation)?, factory_tag if control_factory_uses_generic_budget_callbacks(factory_tag) => { set_control_device_multiplier(table, device_index, allocation)?; } @@ -7232,6 +7250,7 @@ fn append_effective_control_device( class9_selector0_scale_bits: (descriptor.tag == 9).then_some(0x3f80_0000), tag26_extra_rate_bits: (descriptor.tag == 26).then_some(0), device174_bits: (descriptor.tag == 2).then_some(0), + weapon_charge_bits: matches!(descriptor.tag, 2 | 30).then_some(coefficient_words[1]), class9_values_bits: (descriptor.tag == 9).then_some([0x3f80_0000; 6]), class9_deltas_bits: (descriptor.tag == 9).then_some([0; 6]), native_word_50_bits, @@ -7310,6 +7329,9 @@ fn apply_effective_control_override( let mut coefficient_words = [0; 16]; coefficient_words.copy_from_slice(&descriptor.fixed_words[11..27]); device.coefficient_bits = Some(coefficient_words); + if matches!(device.factory_tag, 2 | 30) { + device.weapon_charge_bits = Some(coefficient_words[1]); + } if descriptor.fixed_words[6] != u32::MAX { device.native_word_50_bits = Some(descriptor.fixed_words[6]); } @@ -7319,7 +7341,7 @@ fn apply_effective_control_override( } fn control_factory_uses_generic_budget_callbacks(factory_tag: u32) -> bool { - !matches!(factory_tag, 1 | 2 | 5 | 9 | 10 | 15 | 17 | 19 | 26 | 30) + !matches!(factory_tag, 2 | 5 | 9 | 10 | 15 | 17 | 19 | 26 | 30) } fn control_factory_override_is_supported(factory_tag: u32) -> bool { @@ -7332,7 +7354,7 @@ fn native_control_factory_defaults(factory_tag: u32) -> (Option, Option (Some(0x3f80_0000), Some(0x5)), 10 => (Some(0x3f80_0000), Some(0x2000)), 17 | 19 => (Some(0x3f80_0000), Some(0x20)), - 2 | 27 => (Some(0x3f80_0000), Some(0)), + 2 | 27 | 30 => (Some(0x3f80_0000), Some(0)), 9 => (Some(0x3f80_0000), Some(0x20)), 15 => (Some(0x3f80_0000), Some(0)), _ => (Some(0x3f80_0000), Some(0x5)), @@ -9979,6 +10001,7 @@ mod tests { class9_selector0_scale_bits: class9_scale_bits, tag26_extra_rate_bits: (factory_tag == 26).then_some(0), device174_bits: (factory_tag == 2).then_some(0), + weapon_charge_bits: matches!(factory_tag, 2 | 30).then_some(coefficients[1]), class9_values_bits: (factory_tag == 9).then_some([0x3f80_0000; 6]), class9_deltas_bits: (factory_tag == 9).then_some([0; 6]), native_word_50_bits, @@ -10452,7 +10475,7 @@ mod tests { #[test] fn control_budget_generic_default_callbacks_match_native_rate_and_update() { - for factory_tag in [3, 4, 6, 8, 12, 13, 21, 25, 27, 34] { + for factory_tag in [1, 3, 4, 6, 8, 12, 13, 21, 25, 27, 34] { let mut device = synthetic_effective_control_device( factory_tag, factory_tag, diff --git a/crates/fparkan-runtime/src/mobile_budget.rs b/crates/fparkan-runtime/src/mobile_budget.rs new file mode 100644 index 00000000..ee643cb1 --- /dev/null +++ b/crates/fparkan-runtime/src/mobile_budget.rs @@ -0,0 +1,412 @@ +//! Mobile Control device budgets and weapon charge snapshots. + +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, +}; +use std::collections::BTreeMap; + +#[derive(Clone, Debug)] +pub(super) struct Charge { + pub(super) capacity: f32, + pub(super) cost: f32, + pub(super) amount: f32, +} + +impl Charge { + pub(super) fn can_start(&self) -> bool { + self.capacity <= 0.0 || self.cost <= self.amount + } + + pub(super) fn finish_shot(&mut self) { + if self.capacity > 0.0 && self.cost <= self.amount { + self.amount -= self.cost; + } + } +} + +/// Mobile budget steps, omitted motion inputs and energy waits, by original ID. +#[derive(Clone, Debug, Default, Eq, PartialEq)] +pub struct MobileBudgetReport { + pub ticks: BTreeMap, + pub stubs: BTreeMap<(u32, String), u64>, + pub weapon_waits: BTreeMap, +} + +impl MobileBudgetReport { + pub(super) fn stub(&mut self, object: u32, reason: String) { + let count = self.stubs.entry((object, reason.clone())).or_default(); + *count += 1; + if *count == 1 { + eprintln!("control_mobile_budget_stub object={object} reason={reason}"); + } + } +} + +fn charge_rate( + amount: f32, + capacity: f32, + dt: f32, + upkeep: f32, + active: bool, +) -> Result { + let deficit = checked_control_sum(2, "weapon charge deficit", amount, -capacity)?; + if active { + checked_control_sum( + 2, + "weapon charge and upkeep", + deficit, + -checked_control_product(2, "weapon upkeep interval", dt, upkeep)?, + ) + } else { + Ok(deficit) + } +} + +fn charge_update( + amount: f32, + capacity: f32, + dt: f32, + upkeep: f32, + active: bool, + allocation: f32, +) -> Result<(f32, Option), ControlResourceAccessError> { + let rate = charge_rate(amount, capacity, dt, upkeep, active)?; + let mut received = -checked_control_product(2, "weapon allocated charge", rate, allocation)?; + if active { + received = checked_control_sum( + 2, + "weapon received minus upkeep", + received, + -checked_control_product(2, "weapon upkeep interval", dt, upkeep)?, + )?; + } + if capacity <= 0.0 { + return Ok((amount, None)); + } + let amount = checked_control_sum(2, "weapon updated charge", received, amount)?; + Ok(( + amount, + Some(checked_control_ratio( + "weapon charge ratio", + amount, + capacity, + )?), + )) +} + +fn weapon_amount(device: &EffectiveControlDevice) -> Result { + let bits = device + .weapon_charge_bits + .ok_or(ControlResourceAccessError::UnsupportedField { + factory_tag: 2, + field: "weapon charge +0x120", + })?; + checked_control_float(2, "weapon charge", f32::from_bits(bits)) +} + +pub(super) fn weapon_rate( + table: &MissionControlDeviceTableState, + device: &EffectiveControlDevice, + dt: f32, +) -> Result { + let active = control_device_budget_active_provider_value(table, device)?.is_some(); + charge_rate( + weapon_amount(device)?, + control_device_budget_coefficient(device, 1)?, + dt, + control_device_budget_descriptor_float(device, 8, "weapon upkeep")?, + active, + ) +} + +pub(super) fn weapon_update( + table: &mut MissionControlDeviceTableState, + index: usize, + dt: f32, + allocation: f32, +) -> Result<(), ControlResourceAccessError> { + let device = control_budget_device(table, index)?; + let active = control_device_budget_active_provider_value(table, device)?.is_some(); + let (amount, ratio) = charge_update( + weapon_amount(device)?, + control_device_budget_coefficient(device, 1)?, + dt, + control_device_budget_descriptor_float(device, 8, "weapon upkeep")?, + active, + allocation, + )?; + let MissionControlDeviceTableStatus::Available(devices) = &mut table.status else { + unreachable!("checked table") + }; + devices[index].weapon_charge_bits = Some(amount.to_bits()); + if let Some(ratio) = ratio { + devices[index].multiplier_bits = Some(ratio.to_bits()); + } + Ok(()) +} + +pub(super) fn passive_device_rate( + device: &EffectiveControlDevice, + dt: f32, +) -> Result { + if device.native_word_50_bits != Some(0x2000) { + return Err(ControlResourceAccessError::UnsupportedField { + factory_tag: 10, + field: "active mode +0x50", + }); + } + Ok(-checked_control_product( + 10, + "passive device upkeep", + dt, + control_device_budget_descriptor_float(device, 8, "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. + 0.0 +} + +pub(super) fn read( + mission: &crate::LoadedMissionState, + handle: crate::ObjectHandle, + weapons: &mut [crate::player_weapon::PlayerWeapon], +) { + let table = mission + .control_device_tables + .iter() + .find(|table| table.handle == handle); + let devices = table.and_then(|table| match &table.status { + MissionControlDeviceTableStatus::Available(devices) => Some(devices), + _ => None, + }); + for weapon in weapons { + weapon.charge = if mission.control_resources.energy_available(handle) { + devices + .and_then(|devices| devices.iter().find(|device| matches_weapon(device, weapon))) + .and_then(|device| { + let coefficients = device.coefficient_bits?; + let charge = Charge { + capacity: f32::from_bits(coefficients[1]), + cost: f32::from_bits(coefficients[2]), + amount: f32::from_bits(device.weapon_charge_bits?), + }; + [charge.capacity, charge.cost, charge.amount] + .into_iter() + .all(|value| value.is_finite() && !value.is_subnormal()) + .then_some(charge) + }) + } else { + None + }; + } +} + +fn matches_weapon( + device: &EffectiveControlDevice, + weapon: &crate::player_weapon::PlayerWeapon, +) -> bool { + device.factory_tag == 2 + && device.factory_provenance.unit_component_index == weapon.component_index + && device.factory_provenance.typed_record_index == weapon.control_record_index +} + +pub(super) fn publish( + mission: &mut crate::LoadedMissionState, + handle: crate::ObjectHandle, + weapons: &mut [crate::player_weapon::PlayerWeapon], +) { + if weapons.is_empty() { + return; + } + let available = mission.control_resources.energy_available(handle); + let Some(table) = mission + .control_device_tables + .iter_mut() + .find(|table| table.handle == handle) + else { + mission + .control_resources + .mobile + .stub(handle.slot, "weapon_owner_table".into()); + return; + }; + let object = table.original_id.map_or(handle.slot, |id| id.0); + let waits: u64 = weapons.iter().map(|weapon| weapon.energy_waits).sum(); + let total = mission + .control_resources + .mobile + .weapon_waits + .entry(object) + .or_default(); + let previous = *total; + *total += waits; + if previous == 0 && waits > 0 { + eprintln!("weapon_energy_wait object={object} samples={waits}"); + } + for weapon in weapons { + weapon.energy_waits = 0; + let Some(charge) = &weapon.charge else { + if available { + mission.control_resources.mobile.stub( + object, + format!( + "weapon_link_{}_{}", + weapon.component_index, weapon.control_record_index + ), + ); + } + continue; + }; + if let MissionControlDeviceTableStatus::Available(devices) = &mut table.status { + if let Some(device) = devices + .iter_mut() + .find(|device| matches_weapon(device, weapon)) + { + device.weapon_charge_bits = Some(charge.amount.to_bits()); + if charge.capacity > 0.0 { + device.multiplier_bits = Some((charge.amount / charge.capacity).to_bits()); + } + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[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 [ + ( + 10.0, 3.0, 0.25, 4.0, 0.5, true, 0xc1000000, 0x40c00000, 0x3f19999a, + ), + ( + 10.0, 10.0, 0.25, 4.0, 0.5, true, 0xbf800000, 0x41180000, 0x3f733333, + ), + ( + 10.0, 3.0, 0.25, 4.0, 0.5, false, 0xc0e00000, 0x40d00000, 0x3f266666, + ), + ( + 10.0, 3.0, 0.25, 4.0, 0.0, true, 0xc1000000, 0x40000000, 0x3e4ccccd, + ), + (0.0, 0.0, 0.25, 4.0, 1.0, true, 0xbf800000, 0, 0x3e800000), + ( + 10.0, 0.5, 0.25, 4.0, 0.0, true, 0xc1280000, 0xbf000000, 0xbd4ccccd, + ), + ( + 19.81, 0.23, 0.375491, 17.258, 0.234267, true, 0xc1d07b56, 0xbe14a841, 0xbbf02203, + ), + ] { + let rate_value = charge_rate(amount, capacity, dt, upkeep, active).unwrap(); + assert_eq!(rate_value.to_bits(), rate); + let (amount, ratio) = + charge_update(amount, capacity, dt, upkeep, active, allocation).unwrap(); + assert_eq!(amount.to_bits(), charge); + assert_eq!(ratio.unwrap_or(0.25).to_bits(), multiplier); + } + } + + #[test] + fn charge_allows_equality_and_is_spent_after_a_completed_shot() { + let mut charge = Charge { + capacity: 10.0, + cost: 4.0, + amount: 8.0, + }; + assert!(charge.can_start()); + charge.finish_shot(); + assert!(charge.can_start()); + charge.finish_shot(); + assert!(!charge.can_start()); + let unlimited = Charge { + capacity: 0.0, + cost: 4.0, + amount: 0.0, + }; + assert!(unlimited.can_start()); + } + + #[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, + 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(); + // Isolate a held trigger on an unchanged stock unit; this is not mission acceptance. + engine.autodemo_combat = None; + let mission = engine.loaded.as_ref().unwrap(); + let handle = mission.control_device_tables[1].handle; + let mut weapons = crate::player_weapon::prepare_unit_weapons( + &mission.mission_assets.object_component_controls[1], + ); + let mut idle_bank = weapons.clone(); + assert_eq!(weapons.weapons().len(), 2); + assert!(weapons + .weapons() + .iter() + .all(|weapon| weapon.rounds_remaining().is_none())); + let mut shots = 0; + frame(&mut engine, 0).unwrap(); + for now in (50..=120_000).step_by(50) { + frame(&mut engine, now).unwrap(); + weapons.read_control_energy(&engine, handle); + shots += weapons.fire(true, now).count(); + weapons.publish_control_energy(&mut engine, handle); + idle_bank.read_control_energy(&engine, handle); + idle_bank.publish_control_energy(&mut engine, handle); + } + let report = &engine.loaded.as_ref().unwrap().control_resources.mobile; + assert!(shots > 0); + assert!( + report.weapon_waits[&1] > 0, + "expected depleted laser charge" + ); + assert!( + !report.stubs.keys().any(|(object, reason)| *object == 1 + && (reason.starts_with("budget_") || reason.starts_with("weapon_link"))), + "{:?}", + report.stubs + ); + for now in (120_050..=140_000).step_by(50) { + frame(&mut engine, now).unwrap(); + weapons.read_control_energy(&engine, handle); + weapons.fire(false, now).count(); + weapons.publish_control_energy(&mut engine, handle); + } + let mut resumed = 0; + for now in (140_050..=142_000).step_by(50) { + frame(&mut engine, now).unwrap(); + weapons.read_control_energy(&engine, handle); + resumed += weapons.fire(true, now).count(); + weapons.publish_control_energy(&mut engine, handle); + } + assert!(resumed > 0, "laser must resume after regeneration"); + } +} diff --git a/crates/fparkan-runtime/src/patrol_speed.rs b/crates/fparkan-runtime/src/patrol_speed.rs index 4f8b88ca..ef61472c 100644 --- a/crates/fparkan-runtime/src/patrol_speed.rs +++ b/crates/fparkan-runtime/src/patrol_speed.rs @@ -37,7 +37,7 @@ pub(super) fn place_speed( Ok((limit, speed)) => { let sample = report.samples.entry(object).or_default(); if sample.0 == 0 { - eprintln!("patrol_speed_profile_approx object={object} limit={} requested={speed} (mobile Control budgets and owner activation remain open)", f32::from_bits(limit)); + eprintln!("patrol_speed_profile_approx object={object} limit={} requested={speed} (motion energy and owner activation remain open)", f32::from_bits(limit)); } *sample = (sample.0 + 1, limit, speed.to_bits()); speed diff --git a/crates/fparkan-runtime/src/player_weapon.rs b/crates/fparkan-runtime/src/player_weapon.rs index 763ba585..b301bc1a 100644 --- a/crates/fparkan-runtime/src/player_weapon.rs +++ b/crates/fparkan-runtime/src/player_weapon.rs @@ -17,6 +17,9 @@ pub struct PlayerWeapons { pub struct PlayerWeapon { /// Component containing the barrel's CPT point. pub component_index: usize, + pub(super) control_record_index: usize, + pub(super) charge: Option, + pub(super) energy_waits: u64, /// Name of the projectile prototype. pub projectile: String, /// Archive named by the weapon's projectile descriptor. @@ -50,6 +53,20 @@ enum FirePhase { } impl PlayerWeapons { + /// Reads the authoritative Control charge before sampling this weapon bank. + pub fn read_control_energy(&mut self, engine: &Engine, handle: crate::ObjectHandle) { + if let Some(mission) = &engine.loaded { + crate::mobile_budget::read(mission, handle, &mut self.weapons); + } + } + + /// Publishes completed shots to Control before its next resource budget. + pub fn publish_control_energy(&mut self, engine: &mut Engine, handle: crate::ObjectHandle) { + if let Some(mission) = &mut engine.loaded { + crate::mobile_budget::publish(mission, handle, &mut self.weapons); + } + } + /// Returns the prepared devices in selection order. pub fn weapons(&self) -> &[PlayerWeapon] { &self.weapons @@ -118,6 +135,17 @@ impl PlayerWeapon { self.phase = FirePhase::Idle; break; } + if self + .charge + .as_ref() + .is_some_and(|charge| !charge.can_start()) + { + self.energy_waits += 1; + self.phase = FirePhase::Idle; + self.phase_start_ms = now; + self.phase_end_ms = now; + break; + } self.phase = FirePhase::Shot; barrel.travel_to(0.5) } @@ -137,6 +165,9 @@ impl PlayerWeapon { if let Some(rounds) = &mut self.rounds_remaining { *rounds -= 1; } + if let Some(charge) = &mut self.charge { + charge.finish_shot(); + } self.reload_ms } }; @@ -217,8 +248,9 @@ fn prepare_weapons( control .typed_records .iter() - .filter(|record| record.tag == 2) - .filter_map(|record| { + .enumerate() + .filter(|(_, record)| record.tag == 2) + .filter_map(|(control_record_index, record)| { let projectile_archive = crate::fixed_words_ascii_c_string(&record.fixed_words[27..35])?; let projectile = crate::fixed_words_ascii_c_string(&record.fixed_words[35..43])?; @@ -290,6 +322,9 @@ fn prepare_weapons( }; Some(PlayerWeapon { component_index, + control_record_index, + charge: None, + energy_waits: 0, projectile, projectile_archive, effect, @@ -323,10 +358,13 @@ mod tests { use super::*; #[test] - fn shot_finishes_after_trigger_release_and_then_spends_ammo() { + fn shot_finishes_after_trigger_release_and_spends_ammo_and_charge() { let mut weapons = PlayerWeapons { weapons: vec![PlayerWeapon { component_index: 0, + control_record_index: 0, + charge: None, + energy_waits: 0, projectile: String::from("test"), projectile_archive: String::from("test.rlb"), effect: None, @@ -352,12 +390,26 @@ mod tests { }], ..PlayerWeapons::default() }; + weapons.weapons[0].charge = Some(crate::mobile_budget::Charge { + capacity: 10.0, + cost: 4.0, + amount: 8.0, + }); assert!(weapons.fire(true, 0).next().is_none()); assert!(weapons.fire(false, 10).next().is_none()); assert_eq!(weapons.fire(false, 11).next().unwrap().0, 0); assert_eq!(weapons.weapons()[0].rounds_remaining(), Some(1)); + assert_eq!(weapons.weapons[0].charge.as_ref().unwrap().amount, 8.0); assert!(weapons.fire(false, 22).next().is_none()); assert_eq!(weapons.weapons()[0].rounds_remaining(), Some(0)); + assert_eq!(weapons.weapons[0].charge.as_ref().unwrap().amount, 4.0); assert!(weapons.fire(true, 100).next().is_none()); + weapons.weapons[0].rounds_remaining = None; + weapons.weapons[0].charge.as_mut().unwrap().amount = 0.0; + assert!(weapons.fire(true, 150).next().is_none()); + assert!(weapons.weapons[0].energy_waits > 0); + weapons.weapons[0].charge.as_mut().unwrap().amount = 4.0; + assert!(weapons.fire(true, 10_000).next().is_none()); + assert!(weapons.fire(true, 10_011).next().is_some()); } } diff --git a/crates/fparkan-runtime/src/unit_combat.rs b/crates/fparkan-runtime/src/unit_combat.rs index 57ce5ef8..ed6a2758 100644 --- a/crates/fparkan-runtime/src/unit_combat.rs +++ b/crates/fparkan-runtime/src/unit_combat.rs @@ -370,6 +370,7 @@ impl AutoDemoCombat { mission.unit_patrol.as_ref(), ); for unit in &mut self.units { + unit.weapons.read_control_energy(engine, unit.handle); let Ok(state) = transform_state(&engine.world, unit.handle) else { continue; }; @@ -490,6 +491,9 @@ impl AutoDemoCombat { unavailable += missing as usize; } } + for unit in &mut self.units { + unit.weapons.publish_control_energy(engine, unit.handle); + } (events, unavailable) } } diff --git a/docs/appendices/knowledge-boundaries.md b/docs/appendices/knowledge-boundaries.md index e6121080..5676b46e 100644 --- a/docs/appendices/knowledge-boundaries.md +++ b/docs/appendices/knowledge-boundaries.md @@ -157,15 +157,18 @@ Behavior: самостоятельная защита до получения п Платные заказы используют текущий `E00` после ресурсного бюджета Control. Полный Control tick остальных владельцев, проверка выхода, конструктор и эффекты сборки открыты. -`control_resource_clock_approx` считает бюджетные шаги заводов и лабораторий; исходная фаза, +`control_resource_clock_approx` считает бюджетные шаги поддержанных владельцев; исходная фаза, seed и общий порядок Control RNG открыты. `control_resource_budget_stub` считает неподдержанные шаги по объектам и сохраняет первую причину отказа. +`control_mobile_budget_approx` считает мобильные бюджетные шаги. `control_mobile_budget_stub` +считает нулевую подмену расхода ходовой, открытый режим оружия и отказы бюджета/связи орудия; +при отказе бюджета ограничение стрельбы зарядом отключается до успешного шага. `mission_patrol_approx` отмечает приказы варботам патрулировать точку из `Mission`. Маршрут и бой используют текущую модель AutoDemo. Темп, профиль, расход RNG и варианты других приказов ещё открыты. `patrol_speed_profile_approx` считает запросы скорости патруля точки по объектам: -слово 7 текущего профиля Control × 0,8; бюджет мобильных владельцев и activation ещё открыты. +слово 7 текущего профиля Control × 0,8; расход ходовой и activation ещё открыты. `patrol_speed_stub` считает подмену скоростью 9 при недоступном или неверном профиле. `control_profile_clock_approx` считает ресурсные проверки профиля по объектам; seed, порядок владельцев и activation открыты. `control_profile_update_stub` считает @@ -1233,7 +1236,7 @@ Unit DAT loader-а или gameplay. Rust helper поддерживает тол Полный динамический жизненный цикл после начальной загрузки не подтверждён: activation, placement и полный Control tick не сведены в одну проверенную трассу. Обычная dirty-ветвь `0x12a40` обновляет means и FCA0 на ресурсных часах; -изменения scalar, аварийное повреждение и бюджет мобильных устройств ещё открыты. +изменения scalar, аварийное повреждение и расход ходовой ещё открыты. Отдельные constructor, setter и loader-пути уже прослежены; физические единицы слов профиля и накопителей остаются неизвестны. Для закрытия границы нужны динамическая трассировка и сравнение полного Unit DAT load с оригинальным diff --git a/docs/appendices/script-vm.md b/docs/appendices/script-vm.md index 43496cdb..0e7bf447 100644 --- a/docs/appendices/script-vm.md +++ b/docs/appendices/script-vm.md @@ -1191,12 +1191,14 @@ provider getter и изменение количества не подменен Rust предоставляет явный CPU-вызов `advance_loaded_mission_control_budget(engine, handle, dt)`. Он переносит -исходные callbacks factory tags `9`, `15`, `19`, `26` и общий default callback, +исходные callbacks factory tags `2/30`, `9`, `15`, `19`, `26`, штатный режим `10` +и общий default callback, включая фабрику `1`, а категории выбирает по текущему descriptor tag. Native map подтверждён только для префикса тегов `0..=34`; неизвестная категория, неподдержанный специализированный callback, provider или численный диапазон возвращает ошибку без публикации частичных изменений. Ставки `+0x5dc/+0x5e0` сохраняются отдельно, -а сам вызов ещё не включён в Control clock. +а сам вызов включён в ресурсные часы заводов, лабораторий и мобильных владельцев. +Расход ходовой пока подменён нулём с отдельным счётчиком. Нативный oracle проверяет пустую таблицу с отрицательным нулём в обеих выходных ставках, невырожденную пару исходных устройств tag 19/tag 15 при `dt = 0.375` @@ -1205,6 +1207,38 @@ Rust предоставляет явный CPU-вызов Rust также отклоняет нулевой знаменатель обновления tag 19; тест вызывает эту ошибку после изменения provider потребителем и подтверждает откат всей таблицы. +#### Заряд оружия в бюджетном проходе + +В GOG `Control.dll` с SHA-256 +`bcb86318089028548a178b03a21accdce15df0cc85ddd91674cf3c2f55012c6e` +фабрики `2` и `30` создают один класс с vtable RVA `0x3cbd8`: rate — `0x29a40`, update — +`0x29a90`. Селекторы `1` и `2` общего getter возвращают ёмкость и цену +выстрела без множителей состояния. Reader `0x29650` заполняет заряд `+0x120` +до ёмкости; `0x29cfd` блокирует начало при нехватке, а `0x2a055` списывает +цену при завершении цикла. + +Rate начинает с `charge - capacity` и при включённом исправном устройстве +вычитает `dt * descriptor[8]`. Update умножает отрицательную rate на +выделенный коэффициент, вычитает текущее потребление и прибавляет остаток +к заряду. При положительной ёмкости он также пишет `M = charge / capacity`. +Заряд не ограничивается снизу: при нехватке питания возможны отрицательные +charge и M. При неположительной ёмкости update сохраняет оба поля. + +Прямые вызовы DLL при x87 CW `0x007f` проверяют включённый и выключенный +путь, сломанный provider, нулевую ёмкость и отрицательный результат. +Вектор `capacity=19.81`, `charge=0.23`, `dt=0.375491`, `upkeep=17.258`, +`allocation=0.234267` даёт биты rate `0xc1d07b56`, charge `0xbe14a841` +и M `0xbbf02203`; Rust повторяет их. + +У фабрики `1` vtable `0x3caf8` указывает на общий rate/update +`0x21860/0x21890`; нативный вызов подтверждает эту маршрутизацию. Для фабрики +`10` vtable `0x3ca20` ведёт на `0x264b0/0x26510`: режим `0x2000` использует +обычное потребление и публикацию M, активный `0x1000` ещё открыт. +Ходовая фабрика `5` использует rate `0x265c0`: максимум модулей текущего +вектора `owner+0x1c8`, делённый на максимум исходных пределов `[6..8]`, +умножается на descriptor rate, динамическое `owner+0x154` и интервал. +Динамические входы ещё не поставляются временным контроллером FParkan. + #### Генератор tag 19 в том же бюджетном проходе Отдельный вектор заменяет mock-генератор исходным устройством tag `19`: diff --git a/docs/tomes/06-behavior.md b/docs/tomes/06-behavior.md index e3d9c932..e70400e8 100644 --- a/docs/tomes/06-behavior.md +++ b/docs/tomes/06-behavior.md @@ -311,6 +311,34 @@ Control. Снаряд использует скорость, время жизн исчезает из мира и окна. Формула урона пока та же приближённая, что у оружия героя. После потери цели робот снова ищет противника или патрулирует. +### Заряд орудия и питание робота + +Орудие хранит число патронов и отдельный запас заряда. Ёмкость и цена выстрела +берутся из коэффициентов Control с индексами 1 и 2. При чтении профиля заряд +заполняется до ёмкости. Если ёмкость положительна, новый цикл ждёт, пока +заряда хватит на выстрел; равенство разрешает пуск. Списание происходит при +завершении цикла вместе с патроном. Ёмкость не больше нуля отключает только +это ограничение, сохраняя обычный учёт патронов. + +Ресурсный бюджет восполняет заряд из питания владельца. Орудие запрашивает +недостающий запас даже в выключенном состоянии. Включённое устройство +дополнительно оплачивает свою текущую ставку потребления. Например, при +ёмкости 10, заряде 3, ставке 4 в секунду и интервале четверть секунды +заявка равна −8. Если бюджет выделяет половину, из четырёх полученных единиц +одна уходит на текущее потребление, и запас становится равен 6. + +У игрока и AI общий запас в таблице Control. Перед выборкой стрельбы банк +орудий читает его, после завершения циклов публикует расход. Пауза в огне +даёт бюджету восстановить заряд; ожидание не создаёт выстрел задним числом. +Общий ресурсный шаг также обслуживает устройство tag 10 в штатном режиме +`0x2000`. Фабрика 1 использует те же бюджетные методы, что простые устройства. + +Расход ходовой пока подменён нулём с отдельным счётчиком по владельцу: +оригинал использует в нём динамические поля полного контроллера движения. +Активный режим tag 10 и неполные бюджетные таблицы останавливаются явно; +для такого владельца ограничение стрельбы зарядом временно отключается. +Поэтому этот путь ещё не устанавливает точный энергетический баланс боя. + ### Заявка на захват строения `Handler(35)` даёт сценарию две величины: ID строения и оценку боевой силы @@ -1538,8 +1566,8 @@ Rust хранит исходные слова отдельно, считает общий порог количества используется только при нуле или одном таком узле. Проход с аварийным повреждением пока останавливается явно: он требует сигнализации и дополнительного изменения количества в узлах. Динамический -бюджет ходовой зависит от скоростей Control, а бюджет оружия — от его -состояния; они ещё не подключены к временному контроллеру движения. +расход ходовой ещё не связан с полным контроллером движения. Заряд орудий +и их пополнение уже участвуют в общем бюджете владельца. Отчёт считает ресурсные проверки, обновления и отказы по объектам и сохраняет эти числа после уничтожения робота. @@ -1602,8 +1630,9 @@ setter-поведение. reader, затем сохраняет selector `1` в `+0x120`, округляет selector `0` через x87 `FISTP` в `+0x124` и заново обнуляет массив `+0x12c` по накопленному числу map-строк. Native тест получает `1.25`, округление `3.5 → 4` и четыре нулевых -элемента после повторного override. Rust хранит общую проекцию устройства; -эти оружейные кэши и дальнейшая стрельба в неё пока не входят. Slot `+0x24` +элемента после повторного override. Rust хранит заряд `+0x120` в таблице +Control и связывает его с банком стрельбы по исходным компоненту и номеру +записи; число патронов и фазы пока хранятся в банке. Slot `+0x24` этого класса (`0x29940`) проверен только с неизменной пустой парой ресурсов. Tag `9` проверяется без FX-хоста (`+0x3c == 0`) и без map-строк; его FX-путь этим опытом также не подтверждён. -- cgit v1.2.3