From 20161fbf4fab9080a2d0d6ceedbf1344435cfda0 Mon Sep 17 00:00:00 2001 From: Valentin Popov Date: Wed, 2 Dec 2026 11:40:01 +0400 Subject: feat(ui): show live Control stats in the warbot card --- crates/fparkan-assets/src/explosion_profile.rs | 20 +++ crates/fparkan-assets/src/lib.rs | 3 +- crates/fparkan-assets/src/strategic_roster.rs | 45 +++++- crates/fparkan-assets/src/warbot_card.rs | 188 ++++++++++++++++++++++ crates/fparkan-runtime/src/lib.rs | 80 ++++----- crates/fparkan-runtime/src/projectile_capacity.rs | 88 ++++++++++ crates/fparkan-runtime/src/radar.rs | 4 +- crates/fparkan-runtime/src/strategic_roster.rs | 12 ++ crates/fparkan-runtime/src/warbot_stats.rs | 160 ++++++++++++++++++ 9 files changed, 543 insertions(+), 57 deletions(-) create mode 100644 crates/fparkan-assets/src/warbot_card.rs create mode 100644 crates/fparkan-runtime/src/projectile_capacity.rs create mode 100644 crates/fparkan-runtime/src/warbot_stats.rs (limited to 'crates') diff --git a/crates/fparkan-assets/src/explosion_profile.rs b/crates/fparkan-assets/src/explosion_profile.rs index af9c5a3e..d9f15229 100644 --- a/crates/fparkan-assets/src/explosion_profile.rs +++ b/crates/fparkan-assets/src/explosion_profile.rs @@ -1,5 +1,13 @@ //! Effect references carried by the version-1 explosion descriptor. +/// The contribution of an EXPL descriptor to Control's projectile capacity. +pub fn decode_explosion_capacity(bytes: &[u8]) -> Option { + if bytes.len() != 792 || !matches!(u32::from_le_bytes(bytes[..4].try_into().ok()?), 1..=3) { + return None; + } + Some(f32::from_le_bytes(bytes[4..8].try_into().ok()?)) +} + /// Reads the initial effect archive and name from a version-1 EXPL payload. /// Other versions and malformed references require separate interpretation. pub fn decode_explosion_effect(bytes: &[u8]) -> Option<(&str, &str)> { @@ -34,4 +42,16 @@ mod tests { bytes[0] = 2; assert_eq!(decode_explosion_effect(&bytes), None); } + + #[test] + fn reads_capacity_in_each_observed_explosion_layout() { + let mut bytes = [0; 792]; + bytes[4..8].copy_from_slice(&300.0_f32.to_le_bytes()); + for version in 1..=3_u32 { + bytes[..4].copy_from_slice(&version.to_le_bytes()); + assert_eq!(decode_explosion_capacity(&bytes), Some(300.0)); + } + bytes[0] = 4; + assert_eq!(decode_explosion_capacity(&bytes), None); + } } diff --git a/crates/fparkan-assets/src/lib.rs b/crates/fparkan-assets/src/lib.rs index 090c6c78..253920fa 100644 --- a/crates/fparkan-assets/src/lib.rs +++ b/crates/fparkan-assets/src/lib.rs @@ -52,12 +52,13 @@ pub mod strategy_toolbar; mod turret_elevation; mod ui_configuration; pub mod ui_sprite; +pub mod warbot_card; pub use behavior_profile_values::{ decode_behavior_go_speed_percent, decode_behavior_work_rates, BehaviorWorkRates, }; pub use chassis_profile::{decode_chassis_can_fly, decode_chassis_flags, ChassisFlags}; pub use control_drive::{ControlDriveStates, PreparedControlDrive}; -pub use explosion_profile::decode_explosion_effect; +pub use explosion_profile::{decode_explosion_capacity, decode_explosion_effect}; pub use turret_elevation::{apply_manual_turret_elevation, turret_elevation_row}; mod research; pub use research::{ diff --git a/crates/fparkan-assets/src/strategic_roster.rs b/crates/fparkan-assets/src/strategic_roster.rs index 3a28ac2a..0faeb7e4 100644 --- a/crates/fparkan-assets/src/strategic_roster.rs +++ b/crates/fparkan-assets/src/strategic_roster.rs @@ -4,6 +4,7 @@ use crate::{ game_font::{load_layout_font, BitmapFont}, mission_pager::copy_sprite, ui_sprite::{atlas_region, load_ui_page, load_ui_sprites}, + warbot_card::{self, CardLine}, RgbaImage, }; use fparkan_vfs::Vfs; @@ -47,6 +48,7 @@ pub struct Row<'a> { pub size: u32, pub chassis: u32, pub selected: bool, + pub durability_percent: Option, } /// Resident art for the header, selected-unit frame, and rows. @@ -150,14 +152,19 @@ impl RosterImages { }) } - /// Renders the visible rows and the identity of the selected unit. - pub fn paint(&self, rows: &[Row<'_>]) -> Result { + /// Renders the visible rows and card of the selected unit. + pub fn paint( + &self, + rows: &[Row<'_>], + card: &[Option>], + ) -> Result { let mut panel = self.background.clone(); if let Some(row) = rows.iter().find(|row| row.selected) { self.icons(&mut panel, row, [9, 27]); let width = u32::from(self.font.line_metrics(row.label)?[0]).min(263); let name = self.font.centered_line(row.label, width as u16, 16)?; stamp(&mut panel, &name, [49, 25, 49 + width, 41], [255, 255, 0]); + warbot_card::paint(&self.font, &mut panel, card)?; } for (index, row) in rows.iter().take(19).enumerate() { let y = ROW_TOP + index as u32 * ROW_PITCH; @@ -179,6 +186,19 @@ impl RosterImages { ); } self.icons(&mut panel, row, [12, y + 2]); + if let Some((width, rgba)) = row.durability_percent.and_then(durability_fill) { + let fill = RgbaImage { + width: 1, + height: 1, + rgba8: rgba.to_vec(), + }; + stamp( + &mut panel, + &fill, + [TEXT_LEFT + 2, y + 3, TEXT_LEFT + width, bottom - 3], + [255; 3], + ); + } let name = self .font .centered_line(row.label, TEXT_WIDTH as u16, ROW_HEIGHT as u16)?; @@ -221,6 +241,17 @@ fn stamp(panel: &mut RgbaImage, sprite: &RgbaImage, bounds: [u32; 4], tint: [u8; copy_sprite(panel, sprite, bounds, [false; 2], tint); } +fn durability_fill(percent: i32) -> Option<(u32, [u8; 4])> { + let width = (f64::from(percent.min(100)) * f64::from(TEXT_WIDTH) * f64::from(0.01_f32)) + .round_ties_even() as u32; + let rgba = match percent { + ..=19 => [128, 0, 0, 128], + 20..=79 => [128, 128, 0, 128], + _ => [0, 128, 0, 128], + }; + (width > 2).then_some((width, rgba)) +} + #[cfg(test)] mod tests { use super::*; @@ -234,4 +265,14 @@ mod tests { assert_eq!(hit_test([200.0, 158.0], 2), None); assert_eq!(hit_test([200.0, 480.0], 20), None); } + + #[test] + fn original_durability_colours_follow_the_rounded_health_percentage() { + assert_eq!(durability_fill(0), None); + assert_eq!(durability_fill(19), Some((47, [128, 0, 0, 128]))); + assert_eq!(durability_fill(20), Some((50, [128, 128, 0, 128]))); + assert_eq!(durability_fill(79), Some((196, [128, 128, 0, 128]))); + assert_eq!(durability_fill(80), Some((198, [0, 128, 0, 128]))); + assert_eq!(durability_fill(100), Some((248, [0, 128, 0, 128]))); + } } diff --git a/crates/fparkan-assets/src/warbot_card.rs b/crates/fparkan-assets/src/warbot_card.rs new file mode 100644 index 00000000..015bddce --- /dev/null +++ b/crates/fparkan-assets/src/warbot_card.rs @@ -0,0 +1,188 @@ +//! Formatting and layout for the five original strategic card readings. + +use crate::{game_font::BitmapFont, mission_pager::copy_sprite, RgbaImage}; + +/// The installed game's labels and unit strings, in card row order. +pub struct CardLabels { + pub labels: [String; 5], + pub tonnes: String, + pub speed: String, + pub metres: String, +} + +/// The `[TEMP]` ratings scale read by iron3d+0x6fb60. +#[derive(Default)] +pub struct RatingScale { + /// Defence and offence intervals when normalization is enabled. + limits: Option<[[f32; 2]; 2]>, +} + +impl RatingScale { + /// Reads the five scale settings from the installed game's profile. + pub fn from_ini(ini: &str) -> Self { + let mut in_temp = false; + let mut normalize = false; + let mut defence = [0.0; 2]; + let mut offence = [0.0; 2]; + for line in ini + .lines() + .map(|line| line.trim_start_matches('\u{feff}').trim()) + { + if line.starts_with('[') { + in_temp = line.eq_ignore_ascii_case("[TEMP]"); + } else if in_temp { + let Some((key, value)) = line.split_once('=') else { + continue; + }; + let value = value.split(';').next().unwrap_or_default().trim(); + match key.trim().to_ascii_uppercase().as_str() { + "NORMALIZE" => normalize = value.parse::().unwrap_or(0) != 0, + "DEFENCE_MIN" => defence[0] = value.parse().unwrap_or(0.0), + "DEFENCE_MAX" => defence[1] = value.parse().unwrap_or(0.0), + "OFFENCE_MIN" => offence[0] = value.parse().unwrap_or(0.0), + "OFFENCE_MAX" => offence[1] = value.parse().unwrap_or(0.0), + _ => {} + } + } + } + Self { + limits: normalize.then_some([defence, offence]), + } + } + + fn format(&self, index: usize, value: f32) -> (String, &'static str) { + if let Some(limits) = self.limits { + let [min, max] = limits[index]; + let percent = if value <= min { + 0.0 + } else if value >= max { + 100.0 + } else { + (f64::from(value) - f64::from(min)) * 100.0 / (f64::from(max) - f64::from(min)) + }; + (format!("{percent:.0}"), "%") + } else { + (format!("{value:.6}"), "") + } + } +} + +/// One card reading. The number has a separate tint and aligns with the unit column. +pub struct CardLine<'a> { + label: &'a str, + number: String, + unit: &'a str, + warn: bool, +} + +impl CardLabels { + /// Formats the values in the order used by iron3d+0x70090. + pub fn lines( + &self, + weight: Option<[f32; 2]>, + stats: [Option; 4], + scale: &RatingScale, + ) -> [Option>; 5] { + let [speed, defence, offence, radar] = stats; + let line = |index: usize, number, unit, warn| CardLine { + label: &self.labels[index], + number, + unit, + warn, + }; + [ + weight.map(|[weight, capacity]| { + let [weight, capacity] = [weight, capacity].map(|value| value * 0.001_f32); + line( + 0, + format!("{weight:.0} / {capacity:.0}"), + &self.tonnes, + capacity == 0.0, + ) + }), + speed.map(|speed| { + line( + 1, + format!("{:.0}", f64::from(speed) * f64::from(3.6_f32)), + &self.speed, + false, + ) + }), + defence.map(|value| { + let (number, unit) = scale.format(0, value); + line(2, number, unit, false) + }), + offence.map(|value| { + let (number, unit) = scale.format(1, value); + line(3, number, unit, false) + }), + radar.map(|range| line(4, format!("{range:.0}"), &self.metres, false)), + ] + } +} + +pub(super) fn paint( + font: &BitmapFont, + panel: &mut RgbaImage, + lines: &[Option>], +) -> Result<(), String> { + let height = u32::from(font.line_metrics("A")?[1]); + for (index, line) in lines.iter().enumerate() { + let Some(line) = line else { continue }; + let y = 40 + index as u32 * (height + 2); + let green = [0, 255, 0]; + let value = if line.warn { + [255, 0, 0] + } else { + [180, 180, 255] + }; + for (text, x, align_right, tint) in [ + (line.label, 71_u32, false, green), + (line.number.as_str(), 203, true, value), + (line.unit, 206, false, green), + ] { + if text.is_empty() { + continue; + } + let width = font.line_metrics(text)?[0]; + let x = if align_right { + x.saturating_sub(u32::from(width)) + } else { + x + }; + let text = font.centered_line(text, width, height as u16)?; + copy_sprite( + panel, + &text, + [x, y, x + u32::from(width), y + height], + [false; 2], + tint, + ); + } + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn uses_original_ini_ranges_and_honours_the_raw_mode() { + let scale = RatingScale::from_ini("[TEMP]\nNormalIze=1\nOFFENCE_MIN=0\nOFFENCE_MAX=6550\nDEFENCE_MIN=0\nDEFENCE_MAX=24400\n[Other]\nOFFENCE_MAX=9"); + assert_eq!( + scale.format(1, f32::from_bits(0x4556_9556)), + ("52".into(), "%") + ); + assert_eq!( + scale.format(0, f32::from_bits(0x465f_e6ea)), + ("59".into(), "%") + ); + assert_eq!(scale.format(0, -1.0), ("0".into(), "%")); + assert_eq!(scale.format(0, 25_000.0), ("100".into(), "%")); + assert_eq!( + RatingScale::default().format(0, 59.0), + ("59.000000".into(), "") + ); + } +} diff --git a/crates/fparkan-runtime/src/lib.rs b/crates/fparkan-runtime/src/lib.rs index 96a39732..0cc96e6f 100644 --- a/crates/fparkan-runtime/src/lib.rs +++ b/crates/fparkan-runtime/src/lib.rs @@ -70,10 +70,12 @@ mod control_resources; mod mobile_budget; mod node_amount; mod node_stage; +mod projectile_capacity; pub mod satellite_contacts; pub mod strategic_balance; pub mod strategic_roster; pub mod strategic_view; +pub mod warbot_stats; 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}; @@ -502,10 +504,13 @@ fn resolve_factory2_pair_from_assets( if !factory2_selected_fx_resources_are_representable(asset_manager, control, &opcodes)? { return Ok(Factory2PairOutcome::Unrepresentable); } - match factory2_node_data_maximum_bits(&node_data.rows) { - Ok(bits) => Ok(Factory2PairOutcome::Value(bits)), - Err(_) => Ok(Factory2PairOutcome::Unrepresentable), - } + Ok( + projectile_capacity::projectile_capacity_bits(asset_manager.repository(), &node_data.rows)? + .map_or( + Factory2PairOutcome::Unrepresentable, + Factory2PairOutcome::Value, + ), + ) } fn factory2_selected_fx_resources_are_representable( @@ -630,19 +635,6 @@ fn factory2_fx_resource_is_representable( })) } -fn factory2_node_data_maximum_bits( - rows: &[PreparedControlNodeDataRow], -) -> Result { - let mut maximum = 0.0_f32; - for row in rows { - let value = checked_control_float(2, "factory-2 NDP Max", row.max_volume) - .map_err(|_| "NDP Max float")?; - maximum = checked_control_sum(2, "factory-2 NDP Max sum", maximum, value) - .map_err(|_| "NDP Max sum")?; - } - Ok(maximum.to_bits()) -} - /// Common fields known for one row in a host object's Control device table. /// /// The row index is its position in the containing `Vec`. This stores the @@ -745,6 +737,8 @@ pub struct MissionControlNodeProviderRow { pub initial_mesh_state: Option, /// Current model-node fields, when its global ordinal was resolved. pub mesh_state: Option, + /// Visible stages whose LOD-0 mesh slot has a nonzero AniMesh selector 0x0f. + pub armored_mesh_stages: Option, } /// Node-property publication applied to CPU model state after an amount change. @@ -6959,6 +6953,7 @@ fn build_control_device_projection_with_class( } let mut global_mesh_states = Vec::new(); + let mut global_mesh_armor = Vec::new(); let mut global_control_profile_slots = Vec::new(); let mut global_mesh_component_ids = Vec::new(); let mut root_control_profile_model_known = false; @@ -7010,6 +7005,9 @@ fn build_control_device_projection_with_class( global_mesh_states.push(model.and_then(|model| { initial_control_mesh_state(model, source_node_index, parent_base, mount_node) })); + global_mesh_armor.push(model.and_then(|model| { + warbot_stats::armored_stages(model, source_node_index, draft.scale) + })); global_control_profile_slots.push( model.and_then(|model| initial_control_profile_slot(model, source_node_index)), ); @@ -7211,6 +7209,9 @@ fn build_control_device_projection_with_class( } if let MissionControlNodeProviderTableStatus::Available(rows) = &mut node_provider_status { attach_initial_mesh_states_by_global_ordinal(rows, &global_mesh_states); + for (row, stages) in rows.iter_mut().zip(global_mesh_armor) { + row.armored_mesh_stages = stages; + } } let owner_profile = owner_profile.map( |(source, unit_component_index, native_component_id, original_words)| { @@ -7313,6 +7314,7 @@ fn append_control_node_provider_rows( current_stage: 0, initial_mesh_state: None, mesh_state: None, + armored_mesh_stages: None, }); } } @@ -8220,35 +8222,6 @@ mod tests { assert_eq!(upper.cache_key(), lower.cache_key()); } - #[test] - fn factory2_ndp_maximum_uses_ordered_f32_sum_and_accepts_empty_tables() { - let mut rows = [0.0_f32; 3].map(|max_volume| PreparedControlNodeDataRow { - raw_flags: 0, - max_volume, - mobility_per_volume: 0.0, - effect: PreparedControlResourcePair { - archive: [0; 32], - name: [0; 32], - }, - }); - rows[0].max_volume = 16_777_216.0; - rows[1].max_volume = 1.0; - rows[2].max_volume = -16_777_216.0; - - assert_eq!( - factory2_node_data_maximum_bits(&rows), - Ok(0.0_f32.to_bits()) - ); - assert_eq!(factory2_node_data_maximum_bits(&[]), Ok(0.0_f32.to_bits())); - assert_eq!( - factory2_node_data_maximum_bits(&[PreparedControlNodeDataRow { - max_volume: f32::from_bits(1), - ..rows[0].clone() - }]), - Err("NDP Max float") - ); - } - fn factory2_test_nres(entries: &[(&[u8], u32, u32, &[u8])]) -> Vec { let mut bytes = vec![0; 16]; let mut offsets = Vec::with_capacity(entries.len()); @@ -9098,6 +9071,7 @@ mod tests { current_stage: 0, initial_mesh_state: None, mesh_state: None, + armored_mesh_stages: None, } } @@ -16658,13 +16632,13 @@ mod tests { }); let expected_vectors = [ - ("bb_m_01", 0x43f9_8000), - ("bm_m_01", 0x4422_8000), - ("bl_l_01", 0x436a_0000), - ("br_b_01", 0x44c8_0000), - ("bf_b_01", 0x443b_8000), - ("bl_m_01", 0x443b_4000), - ("bm_l_01", 0x4334_0000), + ("bb_m_01", 0x43fa_0000), + ("bm_m_01", 0x444a_8000), + ("bl_l_01", 0x436b_0000), + ("br_b_01", 0x44ed_8000), + ("bf_b_01", 0x4445_8000), + ("bl_m_01", 0x443b_8000), + ("bm_l_01", 0x43aa_0000), ]; let tables = loaded_mission_control_device_tables(&engine).expect("Control tables"); let mut observed = Vec::new(); diff --git a/crates/fparkan-runtime/src/projectile_capacity.rs b/crates/fparkan-runtime/src/projectile_capacity.rs new file mode 100644 index 00000000..6da04342 --- /dev/null +++ b/crates/fparkan-runtime/src/projectile_capacity.rs @@ -0,0 +1,88 @@ +//! Control selector 0x35 for the material and explosion of a fresh BULL object. + +use crate::{bounded_ascii_c_string, checked_control_sum, AssetPreparationError}; +use fparkan_assets::{ + decode_explosion_capacity, PreparedControlNodeDataRow, PreparedControlResourcePair, +}; +use fparkan_path::{normalize_relative, PathPolicy}; +use fparkan_resource::{resource_name, ResourceError, ResourceRepository}; + +pub(super) fn projectile_capacity_bits( + repository: &dyn ResourceRepository, + rows: &[PreparedControlNodeDataRow], +) -> Result, AssetPreparationError> { + let mut total = 0.0; + for row in rows { + let Some(explosion) = explosion_capacity(repository, &row.effect)? else { + return Ok(None); + }; + let Some(next) = add_row(total, row.max_volume, explosion) else { + return Ok(None); + }; + total = next; + } + Ok(Some(total.to_bits())) +} + +fn add_row(total: f32, volume: f32, explosion: f32) -> Option { + // Control+0x13620 publishes each addition separately at single precision. + let volume_sum = checked_control_sum(2, "projectile NDP capacity", total, volume).ok()?; + checked_control_sum(2, "projectile EXPL capacity", volume_sum, explosion).ok() +} + +fn explosion_capacity( + repository: &dyn ResourceRepository, + pair: &PreparedControlResourcePair, +) -> Result, AssetPreparationError> { + let (Some(archive), Some(name)) = ( + bounded_ascii_c_string(&pair.archive), + bounded_ascii_c_string(&pair.name), + ) else { + return Ok(None); + }; + if archive.is_empty() || name.is_empty() { + return Ok(Some(0.0)); + } + let Ok(path) = normalize_relative(archive.as_bytes(), PathPolicy::StrictLegacy) else { + return Ok(None); + }; + let resource_error = |source| AssetPreparationError::Resource { + context: format!("projectile explosion {archive}:{name}"), + source: Box::new(source), + }; + let archive_id = match repository.open_archive_unchanged(&path) { + Ok(id) => id, + Err(ResourceError::MissingArchive { .. }) => return Ok(Some(0.0)), + Err(source) => return Err(resource_error(source)), + }; + let Some(entry) = repository + .find(archive_id, &resource_name(name.as_bytes())) + .map_err(resource_error)? + else { + return Ok(Some(0.0)); + }; + if repository + .entry_info(entry) + .map_err(resource_error)? + .key + .type_id + != Some(u32::from_le_bytes(*b"EXPL")) + { + return Ok(None); + } + let payload = repository.read(entry).map_err(resource_error)?; + Ok(decode_explosion_capacity(payload.as_slice())) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn includes_explosion_capacity_after_the_node_volume() { + assert_eq!(add_row(0.0, 1600.0, 300.0), Some(1900.0)); + assert_eq!(add_row(0.0, 899.0, 1.0), Some(900.0)); + assert_eq!(add_row(16_777_216.0, 1.0, -16_777_216.0), Some(0.0)); + assert_eq!(add_row(0.0, f32::from_bits(1), 0.0), None); + } +} diff --git a/crates/fparkan-runtime/src/radar.rs b/crates/fparkan-runtime/src/radar.rs index 677c3348..46eb8576 100644 --- a/crates/fparkan-runtime/src/radar.rs +++ b/crates/fparkan-runtime/src/radar.rs @@ -254,7 +254,9 @@ struct Antenna { channels: [f64; 3], } -fn radar_device(table: &MissionControlDeviceTableState) -> Option<&EffectiveControlDevice> { +pub(super) fn radar_device( + table: &MissionControlDeviceTableState, +) -> Option<&EffectiveControlDevice> { let MissionControlDeviceTableStatus::Available(devices) = &table.status else { return None; }; diff --git a/crates/fparkan-runtime/src/strategic_roster.rs b/crates/fparkan-runtime/src/strategic_roster.rs index acf22590..df615e0a 100644 --- a/crates/fparkan-runtime/src/strategic_roster.rs +++ b/crates/fparkan-runtime/src/strategic_roster.rs @@ -71,6 +71,8 @@ pub struct WarbotRow { pub chassis: u32, /// Whether the unit is eligible for automatic selection. pub selectable: bool, + /// Remaining provider capacity of all nodes, rounded as in the original list. + pub durability_percent: Option, } /// Returns the player's warbots in registration order, including any entries whose controller is depleted. @@ -122,6 +124,7 @@ pub fn warbot_rows(engine: &Engine, cockpit: StartingCockpit) -> Vec size, chassis, selectable: !table.node_provider_depletion_marked, + durability_percent: crate::warbot_stats::durability_percent(table), }; Some((sequence, row)) }) @@ -209,6 +212,15 @@ mod tests { ] ); + let heavy = crate::warbot_stats::warbot_stats(&engine, rows[1].handle).unwrap(); + assert_eq!(rows[1].durability_percent, Some(100)); + assert_eq!(heavy.radar, Some(400.0)); + assert_eq!(heavy.offence.unwrap().to_bits(), 0x4556_9556); + assert!( + (heavy.defence.unwrap() - 14_329.729).abs() < 0.5, + "{heavy:?}" + ); + set_owner(&mut engine.world, rows[0].handle, None).unwrap(); assert_eq!(warbot_rows(&engine, cockpit), rows[1..]); } diff --git a/crates/fparkan-runtime/src/warbot_stats.rs b/crates/fparkan-runtime/src/warbot_stats.rs new file mode 100644 index 00000000..c7eab4b7 --- /dev/null +++ b/crates/fparkan-runtime/src/warbot_stats.rs @@ -0,0 +1,160 @@ +//! Live Control readings requested by the strategic warbot card. + +use crate::{ + control_device_selector_zero, Engine, MissionControlDeviceTableState, + MissionControlDeviceTableStatus, MissionControlNodeProviderTableStatus, +}; +use fparkan_assets::PreparedModel; +use fparkan_msh::{selected_slot, Group, Lod, NodeId}; +use fparkan_world::ObjectHandle; + +/// Measurements for the current selection before applying UI units and scales. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct WarbotStats { + /// Loaded weight and available weight limit in Control's native units. + pub weight: Option<[f32; 2]>, + /// Current forward speed limit in metres per second. + pub speed: Option, + /// Protection returned by Control selector 0xb1. + pub defence: Option, + /// Weapon rating returned by Control selector 0xb2. + pub offence: Option, + /// Range of the installed sensor in metres. + pub radar: Option, +} + +/// Reads the selected unit's current Control state for the strategic card. +pub fn warbot_stats(engine: &Engine, handle: ObjectHandle) -> Option { + let table = engine + .loaded + .as_ref()? + .control_device_tables + .iter() + .find(|table| table.handle == handle)?; + let profile = table.owner_profile.as_ref(); + let weight = profile.and_then(|profile| { + let load = profile.load_projection.as_ref().ok()?; + let weight = [load.aggregate_538_bits, profile.current_words[26]].map(f32::from_bits); + weight + .iter() + .all(|value| value.is_finite()) + .then_some(weight) + }); + let speed = profile.and_then(|profile| finite(profile.current_words[7])); + let MissionControlDeviceTableStatus::Available(devices) = &table.status else { + return Some(WarbotStats { + weight, + speed, + ..WarbotStats::default() + }); + }; + let weapons = devices + .iter() + .filter(|device| device.descriptor.tag == 2) + .map(|device| { + (device.factory_tag == 2).then_some(())?; + Some(( + finite(device.device174_bits?)?, + finite(device.coefficient_bits?[3])?, + )) + }); + let radar = crate::radar::radar_device(table) + .map_or(Some(0.0), |device| finite(device.coefficient_bits?[3])); + Some(WarbotStats { + weight, + speed, + defence: defence(table, devices), + offence: offence(weapons), + radar, + }) +} + +pub(super) fn durability_percent(table: &MissionControlDeviceTableState) -> Option { + let capacity = finite(table.node_provider_maximum_amount_bits?)?; + let amount = finite(table.node_provider_amount_bits?)?; + (capacity > 0.0).then(|| (f64::from(amount / capacity) * 100.0).round_ties_even() as i32) +} + +pub(super) fn armored_stages(model: &PreparedModel, node: usize, scale: [f32; 3]) -> Option { + let node_id = NodeId(u32::try_from(node).ok()?); + let mut stages = 0; + for stage in 0..3 { + if let Some(slot) = selected_slot(&model.validated, node_id, Lod(stage), Group(0)) { + let raw = model.validated.slots.get(slot.0 as usize)?.opaque[0]; + let coverage = + (f64::from(scale[1]) * f64::from(scale[0]) * f64::from(finite(raw)?)) as f32; + if coverage != 0.0 { + stages |= 1 << stage; + } + } + } + Some(stages) +} + +fn defence( + table: &MissionControlDeviceTableState, + devices: &[crate::EffectiveControlDevice], +) -> Option { + let MissionControlNodeProviderTableStatus::Available(nodes) = &table.node_provider_status + else { + return None; + }; + let mut volume = 0.0; + for node in nodes { + let stage = node.mesh_state?.visible_stage; + if node.armored_mesh_stages?.checked_shr(stage).unwrap_or(0) & 1 != 0 { + // Control+0xdc40 reads the descriptor capacity, which survives damage to the node. + volume = node.source_row.max_volume; + break; + } + } + if let Some([divisor, _]) = table.projectile_resistance_bits { + let divisor = finite(divisor)?; + if divisor == 0.0 { + return Some(f32::MAX); + } + volume /= divisor; + } + let shield = devices.iter().rfind(|device| device.factory_tag == 9); + let binding = devices.iter().rfind(|device| device.factory_tag == 21); + if let Some((shield, binding)) = shield.zip(binding) { + volume += + control_device_selector_zero(shield).ok()? * finite(binding.coefficient_bits?[0])?; + } + volume.is_finite().then_some(volume) +} + +fn offence(weapons: impl Iterator>) -> Option { + let mut value = 0.0_f32; + for weapon in weapons { + let (damage, period) = weapon?; + // Control+0x2b62b divides, multiplies and adds under x87 single precision. + value += 1000.0 / period.max(1.0) * damage; + } + value.is_finite().then_some(value) +} + +fn finite(bits: u32) -> Option { + let value = f32::from_bits(bits); + value.is_finite().then_some(value) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn weapon_rating_uses_each_weapon_reload_and_limits_the_minimum_period() { + let weapons = [ + (1900.0, 1500.0), + (1900.0, 1500.0), + (900.0, 2000.0), + (900.0, 2000.0), + ]; + assert_eq!( + offence(weapons.into_iter().map(Some)).unwrap().to_bits(), + 0x4556_9556 + ); + assert_eq!(offence([Some((2.0, 0.5))].into_iter()), Some(2000.0)); + } +} -- cgit v1.2.3