From c3e2add9a189879b5e800344e07645af591a2cbd Mon Sep 17 00:00:00 2001 From: Valentin Popov Date: Wed, 2 Dec 2026 00:14:47 +0400 Subject: feat(ui): show live weapon readings in the hero cockpit --- apps/fparkan-game/src/main.rs | 90 +++------- apps/fparkan-game/src/mission_notices.rs | 3 +- apps/fparkan-game/src/mission_overlay.rs | 125 ++++++++++++++ apps/fparkan-game/src/weapon_hud.rs | 259 ++++++++++++++++++++++++++++ crates/fparkan-assets/src/game_font.rs | 20 ++- crates/fparkan-assets/src/lib.rs | 1 + crates/fparkan-assets/src/ui_sprite.rs | 68 ++++++++ crates/fparkan-font/src/bitmap.rs | 36 ++++ crates/fparkan-runtime/src/lib.rs | 1 + crates/fparkan-runtime/src/player_weapon.rs | 94 +++++++++- docs/appendices/ui-shell.md | 17 ++ 11 files changed, 635 insertions(+), 79 deletions(-) create mode 100644 apps/fparkan-game/src/mission_overlay.rs create mode 100644 apps/fparkan-game/src/weapon_hud.rs create mode 100644 crates/fparkan-assets/src/ui_sprite.rs diff --git a/apps/fparkan-game/src/main.rs b/apps/fparkan-game/src/main.rs index 0206b86a..afb553e4 100644 --- a/apps/fparkan-game/src/main.rs +++ b/apps/fparkan-game/src/main.rs @@ -17,10 +17,13 @@ mod destruction_effects; mod mission_hints; mod mission_loading; mod mission_notices; +mod mission_overlay; mod mission_pause; mod motion_effects; mod player_collision; mod satellite_map; +#[cfg(windows)] +mod weapon_hud; #[cfg(test)] use fparkan_runtime::query_building_segment_world; #[cfg(test)] @@ -9588,28 +9591,13 @@ fn run_static_vulkan_mode( .map(|engine| cockpit_geometry::CockpitGeometry::prepare(engine, &mut preview)) .transpose()? .unwrap_or_default(); - #[cfg(windows)] - let mission_hints = if mission_engine.is_some() && demo_camera.is_none() { - mission_hints::MissionHints::load(root, mission, &mut preview) - .map(Some) - .unwrap_or_else(|error| { - eprintln!("sim_coverage mission_text_unavailable=1 reason={error}"); - None - }) - } else { - None - }; - let satellite_map = - if let Some(engine) = mission_engine.as_ref().filter(|_| demo_camera.is_none()) { - satellite_map::SatelliteMap::load(root, mission, engine, &mut preview).unwrap_or_else( - |error| { - eprintln!("satellite_map_unavailable mission={mission} reason={error}"); - None - }, - ) - } else { - None - }; + let overlay = mission_overlay::MissionOverlay::load( + root, + mission, + mission_engine.as_ref().filter(|_| demo_camera.is_none()), + cockpit, + &mut preview, + ); let shadow_base_vertex = preview.mesh.vertices.len(); let shadow_base_index = preview.mesh.indices.len(); let mut app = StaticVulkanApp::new( @@ -9644,22 +9632,11 @@ fn run_static_vulkan_mode( .retain(|index| app.world_range_index_counts.contains_key(index)); } app.shield_effects = shield_effects; - if let Some(map) = &satellite_map { - for range in map.ranges() { - app.world_range_indices.retain(|&index| index != range); - app.world_range_index_counts.remove(&range); - } - } - app.satellite_map = satellite_map; - #[cfg(windows)] - { - if let Some(hints) = &mission_hints { - let range = hints.range_index(); - app.world_range_indices.retain(|&index| index != range); - app.world_range_index_counts.remove(&range); - } - app.mission_hints = mission_hints; - } + overlay.remove_world_ranges( + &mut app.world_range_indices, + &mut app.world_range_index_counts, + ); + app.overlay = overlay; app.demo_camera = demo_camera; app.cockpit = cockpit; app.cockpit_geometry = cockpit_geometry; @@ -9882,9 +9859,7 @@ struct StaticVulkanApp { boarded_hero_index: Option, laboratory_status: Option, mission_title: String, - #[cfg(windows)] - mission_hints: Option, - satellite_map: Option, + overlay: mission_overlay::MissionOverlay, audio: Option, camera_mode: &'static str, mesh_components: usize, @@ -10053,9 +10028,7 @@ impl StaticVulkanApp { boarded_hero_index: None, laboratory_status: None, mission_title: String::new(), - #[cfg(windows)] - mission_hints: None, - satellite_map: None, + overlay: mission_overlay::MissionOverlay::default(), audio, camera_mode: preview.camera_mode, mesh_components: preview.mesh_components, @@ -11664,36 +11637,13 @@ impl StaticVulkanApp { fn render_scene_update(&mut self) -> Result<(), String> { self.upload_live_basements()?; + self.draw_mission_overlay()?; let Some(frame) = self.pending_scene_update.as_ref() else { return Ok(()); }; let Some(renderer) = self.renderer.as_mut() else { return Ok(()); }; - if let Some(map) = &mut self.satellite_map { - map.draw( - renderer, - &mut self.mesh, - frame.viewport, - self.mission_engine - .as_ref() - .zip(self.cockpit) - .map(|(engine, cockpit)| (engine, cockpit, self.boarding_target)), - )?; - } - #[cfg(windows)] - if let Some(hints) = &mut self.mission_hints { - hints.draw( - renderer, - &mut self.mesh, - frame.clock.time_ms, - frame.viewport, - self.mission_engine - .as_ref() - .and_then(fparkan_runtime::loaded_mission_script_outcome) - .unwrap_or_default(), - )?; - } renderer .set_camera(frame.camera.vulkan_camera()) .map_err(|error| format!("apply sampled scene camera: {error}"))?; @@ -12452,7 +12402,7 @@ impl ApplicationHandler for StaticVulkanApp { && !event.repeat && !self.mission_paused { - if let Some(hints) = &mut self.mission_hints { + if let Some(hints) = &mut self.overlay.hints { hints.toggle_current(); } } @@ -12490,7 +12440,7 @@ impl ApplicationHandler for StaticVulkanApp { || self.pressed_keys.contains(&KeyCode::ControlRight) { self.player_mine_pressed = true; - } else if let Some(map) = &mut self.satellite_map { + } else if let Some(map) = &mut self.overlay.satellite_map { map.toggle(); } } diff --git a/apps/fparkan-game/src/mission_notices.rs b/apps/fparkan-game/src/mission_notices.rs index 1a0bc6a2..6b876e3d 100644 --- a/apps/fparkan-game/src/mission_notices.rs +++ b/apps/fparkan-game/src/mission_notices.rs @@ -22,7 +22,8 @@ impl StaticVulkanApp { #[cfg(windows)] { let posted = self - .mission_hints + .overlay + .hints .as_mut() .ok_or_else(|| "mission text resources unavailable".to_string()) .and_then(|hints| hints.post(index, clock_ms)); diff --git a/apps/fparkan-game/src/mission_overlay.rs b/apps/fparkan-game/src/mission_overlay.rs new file mode 100644 index 00000000..6c87492c --- /dev/null +++ b/apps/fparkan-game/src/mission_overlay.rs @@ -0,0 +1,125 @@ +#[cfg(windows)] +use super::{mission_hints::MissionHints, weapon_hud::WeaponHud}; +use super::{satellite_map::SatelliteMap, StaticPreviewScene, StaticVulkanApp}; +use fparkan_runtime::{Engine, StartingCockpit}; +use std::path::Path; + +#[derive(Default)] +pub(super) struct MissionOverlay { + pub(super) satellite_map: Option, + #[cfg(windows)] + pub(super) hints: Option, + #[cfg(windows)] + weapons: Option, +} + +impl MissionOverlay { + pub(super) fn load( + root: &Path, + mission: &str, + engine: Option<&Engine>, + cockpit: Option, + preview: &mut StaticPreviewScene, + ) -> Self { + let Some(engine) = engine else { + return Self::default(); + }; + #[cfg(windows)] + let hints = MissionHints::load(root, mission, preview) + .map(Some) + .unwrap_or_else(|error| { + eprintln!("sim_coverage mission_text_unavailable=1 reason={error}"); + None + }); + let satellite_map = + SatelliteMap::load(root, mission, engine, preview).unwrap_or_else(|error| { + eprintln!("satellite_map_unavailable mission={mission} reason={error}"); + None + }); + #[cfg(windows)] + let weapons = cockpit.and_then(|cockpit| { + WeaponHud::load(root, cockpit.handle, preview) + .map(Some) + .unwrap_or_else(|error| { + eprintln!("weapon_hud_unavailable reason={error}"); + None + }) + }); + #[cfg(not(windows))] + let _ = cockpit; + Self { + satellite_map, + #[cfg(windows)] + hints, + #[cfg(windows)] + weapons, + } + } + + pub(super) fn remove_world_ranges( + &self, + ranges: &mut Vec, + counts: &mut std::collections::HashMap, + ) { + let remove = |range: usize, + ranges: &mut Vec, + counts: &mut std::collections::HashMap| { + ranges.retain(|&index| index != range); + counts.remove(&range); + }; + if let Some(map) = &self.satellite_map { + for range in map.ranges() { + remove(range, ranges, counts); + } + } + #[cfg(windows)] + if let Some(hints) = &self.hints { + remove(hints.range_index(), ranges, counts); + } + #[cfg(windows)] + if let Some(weapons) = &self.weapons { + remove(weapons.range_index(), ranges, counts); + } + } +} + +impl StaticVulkanApp { + pub(super) fn draw_mission_overlay(&mut self) -> Result<(), String> { + let (Some(renderer), Some(frame)) = (&mut self.renderer, &self.pending_scene_update) else { + return Ok(()); + }; + if let Some(map) = &mut self.overlay.satellite_map { + let player = self + .mission_engine + .as_ref() + .zip(self.cockpit) + .map(|(engine, cockpit)| (engine, cockpit, self.boarding_target)); + map.draw(renderer, &mut self.mesh, frame.viewport, player)?; + } + #[cfg(windows)] + if let Some(hints) = &mut self.overlay.hints { + let outcome = self + .mission_engine + .as_ref() + .and_then(fparkan_runtime::loaded_mission_script_outcome) + .unwrap_or_default(); + hints.draw( + renderer, + &mut self.mesh, + frame.clock.time_ms, + frame.viewport, + outcome, + )?; + } + #[cfg(windows)] + if let Some(weapons) = &mut self.overlay.weapons { + let current = self.cockpit.and_then(|cockpit| { + self.player_weapon_banks + .get(&cockpit.handle) + .map(|bank| (cockpit.handle, bank)) + }); + weapons.draw(renderer, &mut self.mesh, frame.viewport, current)?; + } + Ok(()) + } +} diff --git a/apps/fparkan-game/src/weapon_hud.rs b/apps/fparkan-game/src/weapon_hud.rs new file mode 100644 index 00000000..68144b28 --- /dev/null +++ b/apps/fparkan-game/src/weapon_hud.rs @@ -0,0 +1,259 @@ +use super::{ + append_environment_gradient_material, append_environment_range, environment_vertex, + quad_indices, screen_tl_quad_vertices_pixels, world_pipeline_state, DirectoryVfs, + EnvironmentGpuRange, LegacyBlendMode, LegacyDepthMode, StaticPreviewScene, VulkanSmokeRenderer, + VulkanStaticMesh, VulkanStaticTexture, +}; +use fparkan_assets::{ + game_font::{load_layout_font, BitmapFont}, + ui_sprite::load_ui_sprites, + RgbaImage, +}; +use fparkan_platform_winit::text::StringResources; +use fparkan_runtime::{PlayerWeapons, WeaponIndicator, WeaponLamp}; +use fparkan_world::ObjectHandle; +use std::path::Path; + +const ROW_HEIGHT: u16 = 19; +const AMMO_WIDTH: u16 = 24; +const SLOT_WIDTH: u16 = 12; +const NAME_WIDTH: u16 = 120; +const ROW_COUNT: usize = 4; +// The native renderer lays out cells from the right edge, with a one-pixel overlap. +const WIDTH: u32 = 202; +const HEIGHT: u32 = ROW_COUNT as u32 * ROW_HEIGHT as u32; +const UV: [[f32; 2]; 4] = [[0.0, 0.0], [0.0, 1.0], [1.0, 1.0], [1.0, 0.0]]; + +pub(super) struct WeaponHud { + hero: ObjectHandle, + range: EnvironmentGpuRange, + labels: [RgbaImage; ROW_COUNT], + font: BitmapFont, + unlimited: String, + lamps: [RgbaImage; 5], + end: RgbaImage, + digits: RgbaImage, + separator: RgbaImage, + emitter: RgbaImage, + body: RgbaImage, + cap: RgbaImage, + previous: [Option; ROW_COUNT], +} + +impl WeaponHud { + pub(super) fn load( + root: &Path, + hero: ObjectHandle, + preview: &mut StaticPreviewScene, + ) -> Result { + let vfs = DirectoryVfs::new(root); + let [red, yellow1, yellow2, green, black, end, digits, separator, emitter, body, cap] = + load_ui_sprites( + &vfs, + "ui/compaund.cfg", + [ + "ccres_red_lamp", + "ccres_yellow1_lamp", + "ccres_yellow2_lamp", + "ccres_green_lamp", + "ccres_black_lamp", + "ccres_ending_text", + "ccres_body_text", + "ccres_separator_left_text", + "ccres_ray_emitter_off", + "ccres_ray_body", + "ccres_ray_ending", + ], + )?; + let lamps = [red, yellow1, yellow2, green, black]; + if lamps + .iter() + .chain([&end, &digits, &separator, &emitter, &body, &cap]) + .any(|sprite| sprite.height != u32::from(ROW_HEIGHT)) + || lamps.iter().any(|lamp| lamp.width != 19) + || [end.width, separator.width, emitter.width, cap.width] != [5, 5, 10, 6] + { + return Err("inconsistent original weapon HUD sprite dimensions".into()); + } + let font = load_layout_font(&vfs)?; + let strings = StringResources::open(&root.join("iron3d.dll"))?; + let mut labels = Vec::with_capacity(ROW_COUNT); + // The hero uses the ordered labels loaded by iron3d+0x74f40. + for id in 0x0bff..=0x0c02 { + let text = strings + .get(id) + .ok_or_else(|| format!("missing weapon label {id:#x}"))?; + labels.push(font.centered_line(&text, NAME_WIDTH, ROW_HEIGHT)?); + } + let unlimited = strings + .get(0x13e6) + .ok_or("missing unlimited-ammunition label")?; + let material = append_environment_gradient_material(&mut preview.materials)?; + preview.materials[material].screen_tl = true; + preview.materials[material].sky_far_depth = false; + preview.materials[material].texture = blank_texture(); + let range = append_environment_range( + &mut preview.mesh, + material, + vec![environment_vertex([0.0; 3], [1.0; 3], [0.0; 2]); 4], + quad_indices(1)?, + world_pipeline_state(LegacyBlendMode::SourceAlpha, LegacyDepthMode::Disabled), + )?; + Ok(Self { + hero, + range, + font, + unlimited, + end, + digits, + separator, + emitter, + body, + cap, + labels: labels + .try_into() + .map_err(|_| "unexpected weapon label count")?, + lamps, + previous: [None; ROW_COUNT], + }) + } + + pub(super) fn range_index(&self) -> usize { + self.range.range_index + } + + pub(super) fn draw( + &mut self, + renderer: &mut VulkanSmokeRenderer, + mesh: &mut VulkanStaticMesh, + viewport: [f32; 2], + current: Option<(ObjectHandle, &PlayerWeapons)>, + ) -> Result<(), String> { + let bank = + current.filter(|(owner, bank)| *owner == self.hero && !bank.weapons().is_empty()); + renderer + .set_draw_range_index_count(self.range_index(), if bank.is_some() { 6 } else { 0 }) + .map_err(|error| error.to_string())?; + let Some((_, bank)) = bank else { return Ok(()) }; + let mut slots = bank.indicators(); + let state = std::array::from_fn(|_| slots.next()); + if state != self.previous { + let mut image = blank_texture(); + for (index, indicator) in state.iter().enumerate() { + if let Some(indicator) = indicator { + self.draw_row(&mut image, index, *indicator)?; + } + } + renderer + .update_material_texture(self.range.material_index, 0, &image) + .map_err(|error| error.to_string())?; + self.previous = state; + } + let width = WIDTH as f32 * viewport[0] / 640.0; + let height = HEIGHT as f32 * viewport[1] / 480.0; + let start = self.range.vertex_start; + mesh.vertices[start..start + 4].copy_from_slice(&screen_tl_quad_vertices_pixels( + [viewport[0] - width * 0.5, height * 0.5], + width * 0.5, + height * 0.5, + viewport, + [1.0; 3], + 1.0, + UV, + )); + Ok(()) + } + + fn draw_row( + &self, + image: &mut VulkanStaticTexture, + index: usize, + state: WeaponIndicator, + ) -> Result<(), String> { + let y = index as u32 * u32::from(ROW_HEIGHT); + let lamp = &self.lamps[match state.lamp { + WeaponLamp::Unavailable => 0, + WeaponLamp::Reloading => 1, + WeaponLamp::Cycling => 2, + WeaponLamp::Ready => 3, + WeaponLamp::Unselected => 4, + }]; + let mut right = WIDTH; + let mut cell = |sprite: &RgbaImage, width: u32| { + right -= width; + paint(image, sprite, right - 1, y, width + 1); + right + }; + cell(&self.end, self.end.width); + let slot_x = cell(&self.digits, u32::from(SLOT_WIDTH)); + cell(lamp, lamp.width); + let ammo_x = cell(&self.digits, u32::from(AMMO_WIDTH)); + cell(&self.separator, self.separator.width); + cell(&self.emitter, self.emitter.width); + let name_x = cell(&self.body, u32::from(NAME_WIDTH)); + cell(&self.cap, self.cap.width); + let tint = match state.charge_percent { + 0..=19 => [128, 0, 0, 128], + 20..=79 => [128, 128, 0, 128], + _ => [0, 128, 0, 128], + }; + let charged = (f64::from(state.charge_percent) * f64::from(NAME_WIDTH) / 100.0) + .round_ties_even() as u32; + for row in y + 3..y + u32::from(ROW_HEIGHT) - 3 { + for x in name_x + u32::from(NAME_WIDTH) - charged..name_x + u32::from(NAME_WIDTH) - 2 { + paint_pixel(image, x, row, &tint); + } + } + let slot = self + .font + .centered_line(&(index + 1).to_string(), SLOT_WIDTH, ROW_HEIGHT)?; + let rounds = state + .rounds + .map_or_else(|| self.unlimited.clone(), |count| count.to_string()); + let ammo = self.font.centered_line(&rounds, AMMO_WIDTH, ROW_HEIGHT)?; + for (x, glyphs) in [ + (slot_x, &slot), + (ammo_x, &ammo), + (name_x, &self.labels[index]), + ] { + paint(image, glyphs, x, y, glyphs.width); + } + Ok(()) + } +} + +fn blank_texture() -> VulkanStaticTexture { + VulkanStaticTexture { + width: WIDTH, + height: HEIGHT, + rgba8: vec![0; (WIDTH * HEIGHT * 4) as usize], + mip_levels: Vec::new(), + } +} + +fn paint(image: &mut VulkanStaticTexture, sprite: &RgbaImage, left: u32, top: u32, width: u32) { + for y in 0..sprite.height { + for x in 0..width { + let source_x = x * sprite.width / width; + let offset = ((y * sprite.width + source_x) * 4) as usize; + paint_pixel(image, left + x, top + y, &sprite.rgba8[offset..offset + 4]); + } + } +} + +fn paint_pixel(image: &mut VulkanStaticTexture, x: u32, y: u32, source: &[u8]) { + let alpha = u32::from(source[3]); + if alpha == 0 { + return; + } + let start = ((y * WIDTH + x) * 4) as usize; + let pixel = &mut image.rgba8[start..start + 4]; + let under = (u32::from(pixel[3]) * (255 - alpha) + 127) / 255; + let combined = alpha + under; + for index in 0..3 { + pixel[index] = + ((u32::from(source[index]) * alpha + u32::from(pixel[index]) * under + combined / 2) + / combined) as u8; + } + pixel[3] = combined as u8; +} diff --git a/crates/fparkan-assets/src/game_font.rs b/crates/fparkan-assets/src/game_font.rs index 556aa79d..3b88c47e 100644 --- a/crates/fparkan-assets/src/game_font.rs +++ b/crates/fparkan-assets/src/game_font.rs @@ -9,15 +9,29 @@ use std::sync::Arc; /// Load the `GAME_FONT` for the 800×600 pager profile witnessed in the original. pub fn load_game_font(vfs: &dyn Vfs) -> Result { + load_game_font_profile(vfs, 2, [800, 600]) +} + +/// Load the font for composing controls in the original 640×480 layout space. +pub fn load_layout_font(vfs: &dyn Vfs) -> Result { + load_game_font_profile(vfs, 1, [640, 480]) +} + +fn load_game_font_profile( + vfs: &dyn Vfs, + profile: u8, + dimensions: [u32; 2], +) -> Result { let bytes = read(vfs, "ui/game_resources.cfg")?; let cfg = String::from_utf8_lossy(&bytes); - let aliases = object(&cfg, "font_substitutes2").ok_or("missing 800×600 font profile")?; + let aliases = + object(&cfg, &format!("font_substitutes{profile}")).ok_or("missing game font profile")?; if [ number(&aliases, "DIMENSION_X")?, number(&aliases, "DIMENSION_Y")?, - ] != [800, 600] + ] != dimensions { - return Err("unexpected dimensions for the 800×600 font profile".into()); + return Err("unexpected dimensions for the game font profile".into()); } let key = field(&aliases, "GAME_FONT")?.to_ascii_uppercase(); let fonts = object(&cfg, "fonts").ok_or("missing font catalog")?; diff --git a/crates/fparkan-assets/src/lib.rs b/crates/fparkan-assets/src/lib.rs index 75851628..bd66a50a 100644 --- a/crates/fparkan-assets/src/lib.rs +++ b/crates/fparkan-assets/src/lib.rs @@ -39,6 +39,7 @@ pub mod game_font; pub mod satellite_map; mod turret_elevation; mod ui_configuration; +pub mod ui_sprite; pub use behavior_profile_values::{ decode_behavior_go_speed_percent, decode_behavior_work_rates, BehaviorWorkRates, }; diff --git a/crates/fparkan-assets/src/ui_sprite.rs b/crates/fparkan-assets/src/ui_sprite.rs new file mode 100644 index 00000000..157b851c --- /dev/null +++ b/crates/fparkan-assets/src/ui_sprite.rs @@ -0,0 +1,68 @@ +//! Original UI atlas rectangles selected through the game resource table. + +use crate::ui_configuration::{field, number, object, read}; +use fparkan_nres::{decode, EntryId, ReadProfile}; +use fparkan_texm::{decode_mip_rgba8, decode_texm, RgbaImage}; +use fparkan_vfs::Vfs; +use std::{collections::HashMap, sync::Arc}; + +pub fn load_ui_sprites( + vfs: &dyn Vfs, + config: &str, + names: [&str; N], +) -> Result<[RgbaImage; N], String> { + let definitions = read(vfs, config)?; + let definitions = String::from_utf8_lossy(&definitions); + let game = read(vfs, "ui/game_resources.cfg")?; + let game = String::from_utf8_lossy(&game); + let textures = object(&game, "textures").ok_or("missing UI texture catalog")?; + let archive = decode( + read(vfs, field(&textures, "LIBRARY")?)?, + ReadProfile::Strict, + ) + .map_err(|error| error.to_string())?; + let mut pages = HashMap::new(); + let mut sprites = Vec::with_capacity(N); + for name in names { + let region = + object(&definitions, name).ok_or_else(|| format!("missing UI sprite {name}"))?; + let page = number(&textures, &field(®ion, "TEXTURE")?.to_ascii_uppercase())?; + let image = match pages.entry(page) { + std::collections::hash_map::Entry::Occupied(entry) => entry.into_mut(), + std::collections::hash_map::Entry::Vacant(entry) => { + let payload = archive + .payload(EntryId(page)) + .map_err(|error| error.to_string())?; + let texture = decode_texm(Arc::from(payload)).map_err(|error| error.to_string())?; + entry.insert(decode_mip_rgba8(&texture, 0).map_err(|error| error.to_string())?) + } + }; + let [x, y, width, height] = + ["OFFSET_X", "OFFSET_Y", "WIDTH", "HEIGHT"].map(|key| number(®ion, key)); + let [x, y, width, height] = [x?, y?, width?, height?]; + if width == 0 + || height == 0 + || x.checked_add(width).is_none_or(|right| right > image.width) + || y.checked_add(height) + .is_none_or(|bottom| bottom > image.height) + { + return Err(format!("UI sprite {name} is outside atlas page {page}")); + } + let rgba8 = (y..y + height) + .flat_map(|row| { + let start = (row as usize * image.width as usize + x as usize) * 4; + image.rgba8[start..start + width as usize * 4] + .iter() + .copied() + }) + .collect(); + sprites.push(RgbaImage { + width, + height, + rgba8, + }); + } + Ok(sprites + .try_into() + .expect("one rectangle per UI sprite name")) +} diff --git a/crates/fparkan-font/src/bitmap.rs b/crates/fparkan-font/src/bitmap.rs index 7f628b71..c28ce7f4 100644 --- a/crates/fparkan-font/src/bitmap.rs +++ b/crates/fparkan-font/src/bitmap.rs @@ -122,6 +122,42 @@ impl BitmapFont { Ok(((occupied + PADDING) as u32, pixels)) } + /// Renders a single line centered in a transparent RGBA image. + pub fn centered_line(&self, text: &str, width: u16, height: u16) -> Result { + let (bytes, _, unmappable) = WINDOWS_1251.encode(text); + if unmappable { + return Err("game text contains characters outside CP1251".into()); + } + let (width, height) = (usize::from(width), usize::from(height)); + if height < self.glyph_height || width == 0 { + return Err("game text rectangle is too small".into()); + } + let len = width + .checked_mul(height) + .and_then(|area| area.checked_mul(4)) + .filter(|&len| len <= isize::MAX as usize) + .ok_or("game text rectangle is too large")?; + let mut pixels = vec![0; len]; + let advance = bytes.iter().map(|&byte| self.advance(byte)).sum::(); + let mut x = width.saturating_sub(advance) / 2; + let y = (height - self.glyph_height) / 2; + for &byte in bytes.iter() { + self.draw_glyph( + self.glyphs[usize::from(byte)], + &mut pixels, + width, + [x, y], + width - x, + ); + x = (x + self.advance(byte)).min(width); + } + Ok(RgbaImage { + width: width as u32, + height: height as u32, + rgba8: pixels, + }) + } + fn advance(&self, byte: u8) -> usize { self.glyphs[usize::from(byte)].width - 1 + self.spacing } diff --git a/crates/fparkan-runtime/src/lib.rs b/crates/fparkan-runtime/src/lib.rs index 2b148397..a53e32f0 100644 --- a/crates/fparkan-runtime/src/lib.rs +++ b/crates/fparkan-runtime/src/lib.rs @@ -193,6 +193,7 @@ pub use player_motion::{ pub use player_status::{is_player_clan, player_status, PlayerStatus}; pub use player_weapon::{ prepared_warbot_weapons, starting_player_weapons, PlayerWeaponWarning, PlayerWeapons, + WeaponIndicator, WeaponLamp, }; pub use production::{ clan_factory_schemes, factory_schemes, order_clan_factory_scheme, order_factory_robot, diff --git a/crates/fparkan-runtime/src/player_weapon.rs b/crates/fparkan-runtime/src/player_weapon.rs index 347e0450..84408c61 100644 --- a/crates/fparkan-runtime/src/player_weapon.rs +++ b/crates/fparkan-runtime/src/player_weapon.rs @@ -21,6 +21,33 @@ enum WeaponSelection { Slot(usize), } +impl WeaponSelection { + fn includes(self, index: usize) -> bool { + match self { + Self::All => true, + Self::StandardSuit => matches!(index, 0 | 2), + Self::Slot(slot) => slot == index, + } + } +} + +/// The lamp, ammunition and capacitor reading for one cockpit weapon slot. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct WeaponIndicator { + pub rounds: Option, + pub charge_percent: u8, + pub lamp: WeaponLamp, +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum WeaponLamp { + Unavailable, + Reloading, + Cycling, + Ready, + Unselected, +} + /// Cockpit announcements triggered by a weapon's current supply. #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum PlayerWeaponWarning { @@ -83,6 +110,47 @@ enum FirePhase { } impl PlayerWeapons { + /// Read the same slot, cycle and budget that drive manual firing. + pub fn indicators(&self) -> impl Iterator + '_ { + self.weapons.iter().enumerate().map(|(slot, weapon)| { + let ratio = weapon + .charge + .as_ref() + .filter(|charge| charge.capacity > 0.0) + .map_or(1.0, |charge| charge.amount / charge.capacity); + let charge_percent = if (0.0..=1.0).contains(&ratio) { + (f64::from(ratio) * 100.0).round_ties_even() as u8 + } else { + 0 + }; + // iron3d+0x9ccd0 selects the compound-control lamp from Control's status. + let lamp = if !self.selection.includes(slot) { + WeaponLamp::Unselected + } else if weapon.destroyed || weapon.rounds_remaining == Some(0) { + WeaponLamp::Unavailable + } else { + match weapon.phase { + FirePhase::Idle + if weapon + .charge + .as_ref() + .is_some_and(|charge| !charge.can_start()) => + { + WeaponLamp::Reloading + } + FirePhase::Idle => WeaponLamp::Ready, + FirePhase::Reload => WeaponLamp::Reloading, + FirePhase::Shot | FirePhase::Recover | FirePhase::Finish => WeaponLamp::Cycling, + } + }; + WeaponIndicator { + rounds: weapon.rounds_remaining, + charge_percent, + lamp, + } + }) + } + /// Reads the authoritative Control charge and ammunition before firing. pub fn read_control_energy(&mut self, engine: &Engine, handle: crate::ObjectHandle) { if let Some(mission) = &engine.loaded { @@ -232,11 +300,7 @@ impl PlayerWeapons { weapon.windup_started = false; return None; } - let selected = match selection { - WeaponSelection::All => true, - WeaponSelection::StandardSuit => matches!(index, 0 | 2), - WeaponSelection::Slot(slot) => slot == index, - }; + let selected = selection.includes(index); let mut start = selected && trigger(index, weapon, &weapon.barrels[weapon.barrel_index].muzzle); if let Some(deployment) = &mut weapon.deployment { @@ -917,8 +981,20 @@ mod tests { cost: 4.0, amount: 8.0, }); + assert_eq!( + weapons.indicators().next(), + Some(WeaponIndicator { + rounds: Some(1), + charge_percent: 80, + lamp: WeaponLamp::Ready, + }) + ); let mut node_times = [None]; assert!(weapons.fire(true, 0).next().is_none()); + assert_eq!( + weapons.indicators().next().unwrap().lamp, + WeaponLamp::Cycling + ); let mut interrupted = weapons.clone(); interrupted.weapons[0].destroyed = true; assert!(interrupted.fire(true, 11).next().is_none()); @@ -965,6 +1041,14 @@ mod tests { assert_eq!(node_times, [Some(4.0)]); assert_eq!(weapons.firing_effect_phases(7).next(), Some((effect, 0.0))); assert_eq!(weapons.weapons()[0].rounds_remaining(), Some(0)); + assert_eq!( + weapons.indicators().next(), + Some(WeaponIndicator { + rounds: Some(0), + charge_percent: 40, + lamp: WeaponLamp::Unavailable, + }) + ); assert_eq!(weapons.weapons[0].charge.as_ref().unwrap().amount, 4.0); assert_eq!( weapons.take_warnings().next(), diff --git a/docs/appendices/ui-shell.md b/docs/appendices/ui-shell.md index 38886264..8e70861a 100644 --- a/docs/appendices/ui-shell.md +++ b/docs/appendices/ui-shell.md @@ -239,6 +239,23 @@ Control `+0x5dc` и `+0x5e0`. Устройство с тегом 10 может Групповой выбор в стратегическом режиме и указатели внешних камер также остаются открыты. +## Оружейные строки героя + +В `iron3d.dll` RVA `0x74f40` читает четыре имени орудий героя из строк +`0x0bff`–`0x0c02`. RVA `0x9ccd0` обновляет строку орудия, берёт `INF` из +ресурса `0x13e6` для неограниченного боезапаса и выбирает лампу по состоянию +Control. Оружейный цикл в `Control.dll` по RVA `0x29ca0` различает ожидание, +выстрел, перезарядку и недоступность. Например, на старте «Огневого рубежа» +выбраны пушка и лазер, а у пушки горит зелёная лампа и показано 500 патронов. + +Оригинал собирает строку от правого края. Справа идут номер, лампа и +боезапас, слева — имя поверх полосы заряда. Ширины полей 12, 24 и 120 +заданы в вызовах на RVA `0x9d451`–`0x9d548`. RVA `0x98950` читает набор +`ccres_*` из `ui/compaund.cfg`. FParkan читает те же прямоугольники из +атласа установленной игры и рисует строки шрифтом `GAME_FONT` в координатах +640×480. После выстрела счётчик показывает остаток, а длина полосы меняется +вместе с зарядом накопителя. + ## Контракт новой реализации UI scene хранит корневые widgets, focus, viewport/clip rectangles и modal -- cgit v1.2.3