aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--apps/fparkan-game/src/altimeter_hud.rs182
-rw-r--r--apps/fparkan-game/src/main.rs1
-rw-r--r--apps/fparkan-game/src/mission_overlay.rs46
-rw-r--r--apps/fparkan-game/src/weapon_hud.rs14
-rw-r--r--crates/fparkan-assets/src/ui_sprite.rs36
-rw-r--r--crates/fparkan-runtime/src/cockpit_altimeter.rs58
-rw-r--r--crates/fparkan-runtime/src/lib.rs1
-rw-r--r--crates/fparkan-terrain/src/lib.rs32
-rw-r--r--docs/appendices/ui-shell.md16
9 files changed, 358 insertions, 28 deletions
diff --git a/apps/fparkan-game/src/altimeter_hud.rs b/apps/fparkan-game/src/altimeter_hud.rs
new file mode 100644
index 00000000..48114bf1
--- /dev/null
+++ b/apps/fparkan-game/src/altimeter_hud.rs
@@ -0,0 +1,182 @@
+use super::{
+ append_environment_gradient_material, append_environment_range, environment_vertex,
+ mission_overlay::source_over, 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_page,
+ RgbaImage,
+};
+use fparkan_runtime::cockpit_altimeter::Altimeter;
+use std::path::Path;
+
+const LEFT: u32 = 221;
+const TOP: u32 = 347;
+const WIDTH: u32 = 50;
+const HEIGHT: u32 = 110;
+const WHITE: [u8; 3] = [255; 3];
+const UV: [[f32; 2]; 4] = [[0.0, 0.0], [0.0, 1.0], [1.0, 1.0], [1.0, 0.0]];
+
+pub(super) struct AltimeterHud {
+ range: EnvironmentGpuRange,
+ backing: VulkanStaticTexture,
+ page: RgbaImage,
+ font: BitmapFont,
+ previous: Option<Altimeter>,
+}
+
+impl AltimeterHud {
+ pub(super) fn load(root: &Path, preview: &mut StaticPreviewScene) -> Result<Self, String> {
+ let vfs = DirectoryVfs::new(root);
+ let page = load_ui_page(&vfs, "page6")?;
+ let icons = load_ui_page(&vfs, "ui_menu3")?;
+ if [page.width, page.height, icons.width, icons.height] != [256; 4] {
+ return Err("unexpected native altimeter atlas dimensions".into());
+ }
+ let font = load_layout_font(&vfs)?;
+ let mut backing = VulkanStaticTexture {
+ width: WIDTH,
+ height: HEIGHT,
+ rgba8: vec![0; (WIDTH * HEIGHT * 4) as usize],
+ mip_levels: Vec::new(),
+ };
+ // The gauge bracket and number well are part of the mirrored radar frame.
+ blit(
+ &mut backing,
+ &page,
+ [228, 52, 21, 63],
+ [227, 379],
+ true,
+ WHITE,
+ );
+ blit(
+ &mut backing,
+ &page,
+ [219, 115, 36, 14],
+ [221, 442],
+ true,
+ WHITE,
+ );
+ // iron3d+0x3f6a0 and +0x3ff00 select and position the altitude icon.
+ blit(
+ &mut backing,
+ &icons,
+ [215, 0, 15, 28],
+ [230, 383],
+ false,
+ WHITE,
+ );
+
+ 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 = backing.clone();
+ 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 {
+ range,
+ backing,
+ page,
+ font,
+ previous: None,
+ })
+ }
+
+ 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],
+ state: Option<Altimeter>,
+ ) -> Result<(), String> {
+ renderer
+ .set_draw_range_index_count(self.range_index(), if state.is_some() { 6 } else { 0 })
+ .map_err(|error| error.to_string())?;
+ let Some(state) = state else { return Ok(()) };
+ if self.previous != Some(state) {
+ let mut sprite = self.backing.clone();
+ let text = self
+ .font
+ .centered_line(&state.altitude.to_string(), 28, 11)?;
+ blit(
+ &mut sprite,
+ &text,
+ [0, 0, text.width, text.height],
+ [226, 445],
+ false,
+ WHITE,
+ );
+ // iron3d+0x3fc18 crops the same rows from the texture and the screen;
+ // the lower end stays fixed and the top follows the indicated altitude.
+ blit(
+ &mut sprite,
+ &self.page,
+ [
+ 121,
+ state.scale_top,
+ 31,
+ Altimeter::SCALE_HEIGHT - state.scale_top,
+ ],
+ [240, TOP + state.scale_top],
+ true,
+ [0xff, 0xb4, 0x50],
+ );
+ renderer
+ .update_material_texture(self.range.material_index, 0, &sprite)
+ .map_err(|error| error.to_string())?;
+ self.previous = Some(state);
+ }
+
+ let [sx, sy] = [viewport[0] / 640.0, viewport[1] / 480.0];
+ let half_width = WIDTH as f32 * 0.5;
+ let half_height = HEIGHT as f32 * 0.5;
+ let center = [
+ (LEFT as f32 + half_width) * sx,
+ (TOP as f32 + half_height) * sy,
+ ];
+ let start = self.range.vertex_start;
+ mesh.vertices[start..start + 4].copy_from_slice(&screen_tl_quad_vertices_pixels(
+ center,
+ half_width * sx,
+ half_height * sy,
+ viewport,
+ [1.0; 3],
+ 1.0,
+ UV,
+ ));
+ Ok(())
+ }
+}
+
+fn blit(
+ target: &mut VulkanStaticTexture,
+ source: &RgbaImage,
+ [x, y, width, height]: [u32; 4],
+ [left, top]: [u32; 2],
+ flip_x: bool,
+ tint: [u8; 3],
+) {
+ for row in 0..height {
+ for col in 0..width {
+ let sx = x + if flip_x { width - 1 - col } else { col };
+ let src = (((y + row) * source.width + sx) * 4) as usize;
+ let mut pixel: [u8; 4] = source.rgba8[src..src + 4].try_into().expect("RGBA pixel");
+ for (channel, tint) in pixel.iter_mut().zip(tint) {
+ *channel = ((u16::from(*channel) * u16::from(tint) + 127) / 255) as u8;
+ }
+ let dst = (((top - TOP + row) * WIDTH + left - LEFT + col) * 4) as usize;
+ source_over(&mut target.rgba8[dst..dst + 4], &pixel);
+ }
+ }
+}
diff --git a/apps/fparkan-game/src/main.rs b/apps/fparkan-game/src/main.rs
index afb553e4..4e044abe 100644
--- a/apps/fparkan-game/src/main.rs
+++ b/apps/fparkan-game/src/main.rs
@@ -4,6 +4,7 @@
use fparkan_runtime::initial_component_node_times as static_preview_node_times;
+mod altimeter_hud;
mod camera_capture;
mod chassis_animation;
mod cockpit_geometry;
diff --git a/apps/fparkan-game/src/mission_overlay.rs b/apps/fparkan-game/src/mission_overlay.rs
index 6c87492c..a3b37d50 100644
--- a/apps/fparkan-game/src/mission_overlay.rs
+++ b/apps/fparkan-game/src/mission_overlay.rs
@@ -1,12 +1,31 @@
+use super::{
+ altimeter_hud::AltimeterHud, satellite_map::SatelliteMap, StaticPreviewScene, StaticVulkanApp,
+};
#[cfg(windows)]
use super::{mission_hints::MissionHints, weapon_hud::WeaponHud};
-use super::{satellite_map::SatelliteMap, StaticPreviewScene, StaticVulkanApp};
-use fparkan_runtime::{Engine, StartingCockpit};
+use fparkan_runtime::{cockpit_altimeter::cockpit_altimeter, Engine, StartingCockpit};
use std::path::Path;
+/// Source-over composition for original sprite texels and their alpha masks.
+pub(super) fn source_over(pixel: &mut [u8], source: &[u8]) {
+ let alpha = u32::from(source[3]);
+ if alpha == 0 {
+ return;
+ }
+ 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;
+}
+
#[derive(Default)]
pub(super) struct MissionOverlay {
pub(super) satellite_map: Option<SatelliteMap>,
+ altimeter: Option<AltimeterHud>,
#[cfg(windows)]
pub(super) hints: Option<MissionHints>,
#[cfg(windows)]
@@ -24,6 +43,15 @@ impl MissionOverlay {
let Some(engine) = engine else {
return Self::default();
};
+ // The original draws the cockpit instruments before the satellite map.
+ let altimeter = cockpit.and_then(|_| {
+ AltimeterHud::load(root, preview)
+ .map(Some)
+ .unwrap_or_else(|error| {
+ eprintln!("altimeter_unavailable reason={error}");
+ None
+ })
+ });
#[cfg(windows)]
let hints = MissionHints::load(root, mission, preview)
.map(Some)
@@ -45,10 +73,9 @@ impl MissionOverlay {
None
})
});
- #[cfg(not(windows))]
- let _ = cockpit;
Self {
satellite_map,
+ altimeter,
#[cfg(windows)]
hints,
#[cfg(windows)]
@@ -72,6 +99,9 @@ impl MissionOverlay {
remove(range, ranges, counts);
}
}
+ if let Some(altimeter) = &self.altimeter {
+ remove(altimeter.range_index(), ranges, counts);
+ }
#[cfg(windows)]
if let Some(hints) = &self.hints {
remove(hints.range_index(), ranges, counts);
@@ -96,6 +126,14 @@ impl StaticVulkanApp {
.map(|(engine, cockpit)| (engine, cockpit, self.boarding_target));
map.draw(renderer, &mut self.mesh, frame.viewport, player)?;
}
+ if let Some(altimeter) = &mut self.overlay.altimeter {
+ let state = self
+ .mission_engine
+ .as_ref()
+ .zip(self.cockpit)
+ .and_then(|(engine, cockpit)| cockpit_altimeter(engine, cockpit));
+ altimeter.draw(renderer, &mut self.mesh, frame.viewport, state)?;
+ }
#[cfg(windows)]
if let Some(hints) = &mut self.overlay.hints {
let outcome = self
diff --git a/apps/fparkan-game/src/weapon_hud.rs b/apps/fparkan-game/src/weapon_hud.rs
index 68144b28..93db51db 100644
--- a/apps/fparkan-game/src/weapon_hud.rs
+++ b/apps/fparkan-game/src/weapon_hud.rs
@@ -242,18 +242,6 @@ fn paint(image: &mut VulkanStaticTexture, sprite: &RgbaImage, left: u32, top: u3
}
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;
+ super::mission_overlay::source_over(&mut image.rgba8[start..start + 4], source);
}
diff --git a/crates/fparkan-assets/src/ui_sprite.rs b/crates/fparkan-assets/src/ui_sprite.rs
index 157b851c..fe4c77e8 100644
--- a/crates/fparkan-assets/src/ui_sprite.rs
+++ b/crates/fparkan-assets/src/ui_sprite.rs
@@ -1,11 +1,21 @@
//! 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_nres::{decode, EntryId, NresDocument, ReadProfile};
use fparkan_texm::{decode_mip_rgba8, decode_texm, RgbaImage};
use fparkan_vfs::Vfs;
use std::{collections::HashMap, sync::Arc};
+/// Load a named page from the original game UI texture catalog.
+pub fn load_ui_page(vfs: &dyn Vfs, name: &str) -> Result<RgbaImage, String> {
+ 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 page = number(&textures, &name.to_ascii_uppercase())?;
+ let archive = open_atlas(vfs, field(&textures, "LIBRARY")?)?;
+ decode_page(&archive, page)
+}
+
pub fn load_ui_sprites<const N: usize>(
vfs: &dyn Vfs,
config: &str,
@@ -16,11 +26,7 @@ pub fn load_ui_sprites<const N: usize>(
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 archive = open_atlas(vfs, field(&textures, "LIBRARY")?)?;
let mut pages = HashMap::new();
let mut sprites = Vec::with_capacity(N);
for name in names {
@@ -30,11 +36,7 @@ pub fn load_ui_sprites<const N: usize>(
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())?)
+ entry.insert(decode_page(&archive, page)?)
}
};
let [x, y, width, height] =
@@ -66,3 +68,15 @@ pub fn load_ui_sprites<const N: usize>(
.try_into()
.expect("one rectangle per UI sprite name"))
}
+
+fn open_atlas(vfs: &dyn Vfs, path: &str) -> Result<NresDocument, String> {
+ decode(read(vfs, path)?, ReadProfile::Strict).map_err(|error| error.to_string())
+}
+
+fn decode_page(archive: &NresDocument, page: u32) -> Result<RgbaImage, String> {
+ 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())?;
+ decode_mip_rgba8(&texture, 0).map_err(|error| error.to_string())
+}
diff --git a/crates/fparkan-runtime/src/cockpit_altimeter.rs b/crates/fparkan-runtime/src/cockpit_altimeter.rs
new file mode 100644
index 00000000..e511872a
--- /dev/null
+++ b/crates/fparkan-runtime/src/cockpit_altimeter.rs
@@ -0,0 +1,58 @@
+//! The cockpit altimeter samples the controlled object's origin in world space.
+
+use crate::{loaded_terrain, Engine, StartingCockpit};
+use fparkan_world::transform_state;
+
+/// The signed reading and the first visible scanline of the altitude scale.
+#[derive(Clone, Copy, Debug, Eq, PartialEq)]
+pub struct Altimeter {
+ pub altitude: i32,
+ pub scale_top: u32,
+}
+
+impl Altimeter {
+ pub const SCALE_HEIGHT: u32 = 105;
+
+ fn from_elevations(z: f32, sea_level: f32) -> Self {
+ // iron3d+0x3fa62 subtracts the two source floats in x87 and rounds to integer.
+ let altitude = (f64::from(z) - f64::from(sea_level)).round_ties_even() as i32;
+ let percent = (altitude.clamp(-100, 100) + 100) as u32 * 100 / 200;
+ Self {
+ altitude,
+ scale_top: (100 - percent) * Self::SCALE_HEIGHT / 100,
+ }
+ }
+}
+
+/// Reads the altimeter for the active hero or boarded vehicle.
+#[must_use]
+pub fn cockpit_altimeter(engine: &Engine, cockpit: StartingCockpit) -> Option<Altimeter> {
+ let sea_level = loaded_terrain(engine)?.sea_level();
+ let pose = transform_state(&engine.world, cockpit.handle).ok()?;
+ let z = f32::from_bits(pose.position[2]);
+ Some(Altimeter::from_elevations(z, sea_level))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::Altimeter;
+
+ #[test]
+ fn original_altimeter_rounds_the_signed_distance_then_clips_only_the_scale() {
+ for (z, sea, altitude, scale_top) in [
+ (14.09392, -1.72549, 16, 44),
+ (2.5, 0.0, 2, 51),
+ (-2.5, 0.0, -2, 53),
+ (-150.0, 0.0, -150, 105),
+ (170.0, 0.0, 170, 0),
+ ] {
+ assert_eq!(
+ Altimeter::from_elevations(z, sea),
+ Altimeter {
+ altitude,
+ scale_top
+ }
+ );
+ }
+ }
+}
diff --git a/crates/fparkan-runtime/src/lib.rs b/crates/fparkan-runtime/src/lib.rs
index a53e32f0..2a5497f1 100644
--- a/crates/fparkan-runtime/src/lib.rs
+++ b/crates/fparkan-runtime/src/lib.rs
@@ -101,6 +101,7 @@ pub use destruction::{
collect_unit_destruction_effects, take_unit_destruction_effects,
unit_destruction_effect_sources, DestroyedMesh, UnitDestructionEffect,
};
+pub mod cockpit_altimeter;
mod flight_altitude;
mod ground_support;
mod laboratory;
diff --git a/crates/fparkan-terrain/src/lib.rs b/crates/fparkan-terrain/src/lib.rs
index fd4a28a2..7e2ae588 100644
--- a/crates/fparkan-terrain/src/lib.rs
+++ b/crates/fparkan-terrain/src/lib.rs
@@ -33,6 +33,7 @@ pub struct TerrainWorld {
surfaces: Vec<RuntimeTriangle>,
surface_bvh: SurfaceBvh,
source_mesh: Option<LandMeshDocument>,
+ sea_level: Option<f32>,
basement_foundation: Option<BasementFoundation>,
}
@@ -299,6 +300,7 @@ impl TerrainWorld {
surfaces: Vec::new(),
surface_bvh: SurfaceBvh::default(),
source_mesh: None,
+ sea_level: None,
basement_foundation: None,
})
}
@@ -314,6 +316,7 @@ impl TerrainWorld {
surfaces: build_surfaces(mesh)?,
surface_bvh: SurfaceBvh::default(),
source_mesh: Some(mesh.clone()),
+ sea_level: authored_sea_level(mesh),
..Self::default()
}
.with_surface_bvh())
@@ -333,6 +336,7 @@ impl TerrainWorld {
world.surfaces = build_surfaces(mesh)?;
world.surface_bvh = SurfaceBvh::from_surfaces(&world.surfaces);
world.source_mesh = Some(mesh.clone());
+ world.sea_level = authored_sea_level(mesh);
Ok(world)
}
@@ -460,6 +464,12 @@ impl TerrainWorld {
self.source_mesh.as_ref()
}
+ /// The first vertex of the first authored water face, or −1 on a dry map.
+ #[must_use]
+ pub fn sea_level(&self) -> f32 {
+ self.sea_level.unwrap_or(-1.0)
+ }
+
/// Returns source terrain positions without exposing parser ownership to apps.
#[must_use]
pub fn source_positions(&self) -> Option<&[[f32; 3]]> {
@@ -1090,6 +1100,15 @@ impl RuntimeGrid {
}
}
+fn authored_sea_level(mesh: &LandMeshDocument) -> Option<f32> {
+ // Terrain+0xf2f7 scans the original faces before building its surface index.
+ let water = mesh
+ .faces
+ .iter()
+ .find(|face| face.flags.0 & 0x0002_0000 != 0)?;
+ Some(mesh.positions.get(usize::from(water.vertices[0]))?[2])
+}
+
fn build_surfaces(mesh: &LandMeshDocument) -> Result<Vec<RuntimeTriangle>, TerrainError> {
let assignments = mesh
.face_lod_assignments()
@@ -1879,6 +1898,19 @@ mod tests {
}
}
+ #[test]
+ fn sea_level_uses_the_first_water_face_in_source_order() {
+ let mut mesh = synthetic_land_mesh();
+ assert_eq!(
+ TerrainWorld::from_land_msh(&mesh).unwrap().sea_level(),
+ -1.0
+ );
+ mesh.faces[1].flags.0 |= 0x0002_0000;
+ assert_eq!(TerrainWorld::from_land_msh(&mesh).unwrap().sea_level(), 1.0);
+ mesh.faces[0].flags.0 |= 0x0002_0000;
+ assert_eq!(TerrainWorld::from_land_msh(&mesh).unwrap().sea_level(), 0.0);
+ }
+
fn synthetic_land_mesh() -> LandMeshDocument {
use fparkan_terrain_format::{TerrainSlotTable, TerrainStream};
diff --git a/docs/appendices/ui-shell.md b/docs/appendices/ui-shell.md
index 8e70861a..8860cbc9 100644
--- a/docs/appendices/ui-shell.md
+++ b/docs/appendices/ui-shell.md
@@ -256,6 +256,22 @@ Control. Оружейный цикл в `Control.dll` по RVA `0x29ca0` разÐ
640×480. После выстрела счётчик показывает остаток, а длина полосы меняется
вместе с зарядом накопителя.
+## Высотомер кабины
+
+У высотомера общий ноль для всей миссии. `Terrain.dll` по RVA `0xf2f7`
+берёт Z первой вершины первой грани `Land.msh` с флагом воды `0x20000`.
+На сухой карте остаётся начальное значение −1. Геттер по RVA `0xfe80`
+передаёт уровень моря в `iron3d.dll`, где код по RVA `0x3fa62` вычитает его
+из высоты корпуса управляемого объекта и округляет до целого. На штатном
+старте «Огневого рубежа» высота корпуса около 14,09, уровень моря −1,72549,
+показание 16. При смене кабины прибор читает положение новой машины.
+
+Число знаковое. Например, на высоте −150 прибор показывает −150, хотя
+шкала ограничена интервалом от −100 до +100. RVA `0x3fb8f` переводит этот
+интервал в высоту оранжевой шкалы из `page6`, у которой неподвижен нижний
+край. Число использует `GAME_FONT`, пиктограмма берётся из `ui_menu3`.
+[Хеш сборки Terrain.dll](../reference/original-binaries.md).
+
## Контракт новой реализации
UI scene хранит корневые widgets, focus, viewport/clip rectangles и modal