aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--apps/fparkan-game/src/main.rs26
-rw-r--r--apps/fparkan-game/src/satellite_map.rs123
-rw-r--r--crates/fparkan-assets/src/satellite_map.rs11
-rw-r--r--crates/fparkan-runtime/src/lib.rs1
-rw-r--r--crates/fparkan-runtime/src/satellite_contacts.rs153
-rw-r--r--docs/appendices/ui-shell.md17
6 files changed, 310 insertions, 21 deletions
diff --git a/apps/fparkan-game/src/main.rs b/apps/fparkan-game/src/main.rs
index 328aff46..7f6a98f9 100644
--- a/apps/fparkan-game/src/main.rs
+++ b/apps/fparkan-game/src/main.rs
@@ -9593,14 +9593,17 @@ fn run_static_vulkan_mode(
} else {
None
};
- let satellite_map = if mission_engine.is_some() && demo_camera.is_none() {
- satellite_map::SatelliteMap::load(root, mission, &mut preview).unwrap_or_else(|error| {
- eprintln!("satellite_map_unavailable mission={mission} reason={error}");
+ 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
- })
- } else {
- None
- };
+ };
let cockpit_geometry = mission_engine
.as_ref()
.map(|engine| cockpit_geometry::CockpitGeometry::prepare(engine, &mut preview))
@@ -11666,8 +11669,13 @@ impl StaticVulkanApp {
let Some(renderer) = self.renderer.as_mut() else {
return Ok(());
};
- if let Some(map) = &self.satellite_map {
- map.draw(renderer, &mut self.mesh, frame.viewport)?;
+ if let Some(map) = &mut self.satellite_map {
+ map.draw(
+ renderer,
+ &mut self.mesh,
+ frame.viewport,
+ self.mission_engine.as_ref().zip(self.cockpit),
+ )?;
}
#[cfg(windows)]
if let Some(hints) = &mut self.mission_hints {
diff --git a/apps/fparkan-game/src/satellite_map.rs b/apps/fparkan-game/src/satellite_map.rs
index 6fbbbcc1..83071a52 100644
--- a/apps/fparkan-game/src/satellite_map.rs
+++ b/apps/fparkan-game/src/satellite_map.rs
@@ -5,6 +5,7 @@ use super::{
VulkanStaticTexture,
};
use fparkan_assets::{satellite_map::load_satellite_map, RgbaImage};
+use fparkan_runtime::{satellite_contacts, Engine, StartingCockpit};
use fparkan_vfs::DirectoryVfs;
use std::{path::Path, sync::Arc};
@@ -12,11 +13,16 @@ const UV: [[f32; 2]; 4] = [[0.0, 0.0], [0.0, 1.0], [1.0, 1.0], [1.0, 0.0]];
// Native initial background colour, iron3d+0x74cf0.
const MAP_TINT: [f32; 3] = [55.0 / 255.0, 1.0, 55.0 / 255.0];
const MAP_ALPHA: f32 = 128.0 / 255.0;
+const MAP_SIZE: usize = 256;
pub(super) struct SatelliteMap {
background: EnvironmentGpuRange,
compass: EnvironmentGpuRange,
compass_size: [f32; 2],
+ building_layer: EnvironmentGpuRange,
+ icons: RgbaImage,
+ extent: Option<f32>,
+ buildings: Vec<satellite_contacts::BuildingContact>,
visible: bool,
}
@@ -24,6 +30,7 @@ impl SatelliteMap {
pub(super) fn load(
root: &Path,
mission: &str,
+ engine: &Engine,
preview: &mut StaticPreviewScene,
) -> Result<Option<Self>, String> {
let Some(assets) = load_satellite_map(Arc::new(DirectoryVfs::new(root)), mission)? else {
@@ -34,12 +41,20 @@ impl SatelliteMap {
background: add_sprite(preview, assets.background)?,
compass: add_sprite(preview, assets.compass)?,
compass_size,
+ building_layer: add_sprite(preview, empty_layer())?,
+ icons: assets.icons,
+ extent: satellite_contacts::landscape_extent(engine),
+ buildings: Vec::new(),
visible: false,
}))
}
- pub(super) fn ranges(&self) -> [usize; 2] {
- [self.background.range_index, self.compass.range_index]
+ pub(super) fn ranges(&self) -> [usize; 3] {
+ [
+ self.background.range_index,
+ self.compass.range_index,
+ self.building_layer.range_index,
+ ]
}
pub(super) fn toggle(&mut self) {
@@ -47,10 +62,11 @@ impl SatelliteMap {
}
pub(super) fn draw(
- &self,
+ &mut self,
renderer: &mut VulkanSmokeRenderer,
mesh: &mut VulkanStaticMesh,
viewport: [f32; 2],
+ player: Option<(&Engine, StartingCockpit)>,
) -> Result<(), String> {
let count = if self.visible { 6 } else { 0 };
for index in self.ranges() {
@@ -77,6 +93,7 @@ impl SatelliteMap {
);
mesh.vertices[self.background.vertex_start..self.background.vertex_start + 4]
.copy_from_slice(&background);
+ self.draw_buildings(renderer, mesh, viewport, center, size, player)?;
let scale = size / 256.0;
let [width, height] = self.compass_size.map(|dimension| dimension * scale);
@@ -97,6 +114,99 @@ impl SatelliteMap {
.copy_from_slice(&compass);
Ok(())
}
+
+ fn draw_buildings(
+ &mut self,
+ renderer: &mut VulkanSmokeRenderer,
+ mesh: &mut VulkanStaticMesh,
+ viewport: [f32; 2],
+ center: [f32; 2],
+ size: f32,
+ player: Option<(&Engine, StartingCockpit)>,
+ ) -> Result<(), String> {
+ let buildings =
+ player
+ .zip(self.extent)
+ .map_or_else(Vec::new, |((engine, cockpit), extent)| {
+ satellite_contacts::owned_buildings(engine, cockpit, extent).collect()
+ });
+ if buildings != self.buildings {
+ let mut layer = empty_layer();
+ for building in &buildings {
+ paint_building(&self.icons, &mut layer, *building);
+ }
+ renderer
+ .update_material_texture(self.building_layer.material_index, 0, &texture(layer))
+ .map_err(|error| error.to_string())?;
+ self.buildings = buildings;
+ }
+ let vertices = screen_tl_quad_vertices_pixels(
+ center,
+ size * 0.5,
+ size * 0.5,
+ viewport,
+ [1.0; 3],
+ 1.0,
+ UV,
+ );
+ let start = self.building_layer.vertex_start;
+ mesh.vertices[start..start + 4].copy_from_slice(&vertices);
+ Ok(())
+ }
+}
+
+fn empty_layer() -> RgbaImage {
+ RgbaImage {
+ width: MAP_SIZE as u32,
+ height: MAP_SIZE as u32,
+ rgba8: vec![0; MAP_SIZE * MAP_SIZE * 4],
+ }
+}
+
+fn paint_building(
+ atlas: &RgbaImage,
+ layer: &mut RgbaImage,
+ building: satellite_contacts::BuildingContact,
+) {
+ let [left, top] = building.pixel.map(|center| center.saturating_sub(10));
+ // Native 24×24 icon tile at y=24, displayed as a 20×20 square.
+ for dy in 0..20 {
+ let y = top.saturating_add(dy);
+ if !(0..MAP_SIZE as i32).contains(&y) {
+ continue;
+ }
+ for dx in 0..20 {
+ let x = left.saturating_add(dx);
+ if !(0..MAP_SIZE as i32).contains(&x) {
+ continue;
+ }
+ let src_x = building.icon_x as usize + (dx as usize * 24 + 12) / 20;
+ let src_y = 24 + (dy as usize * 24 + 12) / 20;
+ let src = (src_y * atlas.width as usize + src_x) * 4;
+ let dst = (y as usize * MAP_SIZE + x as usize) * 4;
+ let alpha = u32::from(atlas.rgba8[src + 3]);
+ if alpha == 0 {
+ continue;
+ }
+ let retained = u32::from(layer.rgba8[dst + 3]) * (255 - alpha) / 255;
+ let coverage = alpha + retained;
+ for (axis, tint) in [128, 128, 255].into_iter().enumerate() {
+ let source = u32::from(atlas.rgba8[src + axis]) * tint / 255;
+ let under = u32::from(layer.rgba8[dst + axis]);
+ layer.rgba8[dst + axis] = ((source * alpha + under * retained) / coverage) as u8;
+ }
+ layer.rgba8[dst + 3] = coverage as u8;
+ }
+ }
+}
+
+fn texture(image: RgbaImage) -> VulkanStaticTexture {
+ VulkanStaticTexture {
+ width: image.width,
+ height: image.height,
+ rgba8: image.rgba8,
+ mip_levels: Vec::new(),
+ }
}
fn add_sprite(
@@ -106,12 +216,7 @@ fn add_sprite(
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 = VulkanStaticTexture {
- width: image.width,
- height: image.height,
- rgba8: image.rgba8,
- mip_levels: Vec::new(),
- };
+ preview.materials[material].texture = texture(image);
append_environment_range(
&mut preview.mesh,
material,
diff --git a/crates/fparkan-assets/src/satellite_map.rs b/crates/fparkan-assets/src/satellite_map.rs
index 9a18f2bd..39af61bf 100644
--- a/crates/fparkan-assets/src/satellite_map.rs
+++ b/crates/fparkan-assets/src/satellite_map.rs
@@ -8,10 +8,11 @@ use fparkan_texm::{decode_mip_rgba8, decode_texm, RgbaImage};
use fparkan_vfs::Vfs;
use std::sync::Arc;
-/// The mission map and compass cut from the original interface texture atlas.
+/// The mission map, compass and contact atlas from the installed game.
pub struct SatelliteMapAssets {
pub background: RgbaImage,
pub compass: RgbaImage,
+ pub icons: RgbaImage,
}
/// Resolves `minimap` through the mission CFG and the compass through the game UI CFG.
@@ -63,9 +64,17 @@ pub fn load_satellite_map(
[number(&icon, "OFFSET_X")?, number(&icon, "OFFSET_Y")?],
[number(&icon, "WIDTH")?, number(&icon, "HEIGHT")?],
)?;
+ let icon_page = pages
+ .payload(EntryId(number(&textures, "ICONS")?))
+ .map_err(|error| error.to_string())?;
+ let icons = texture(icon_page)?;
+ if icons.width != 256 || icons.height != 256 {
+ return Err("unexpected satellite icon atlas dimensions".into());
+ }
Ok(Some(SatelliteMapAssets {
background,
compass,
+ icons,
}))
}
diff --git a/crates/fparkan-runtime/src/lib.rs b/crates/fparkan-runtime/src/lib.rs
index 0f2b7e49..6ebe380c 100644
--- a/crates/fparkan-runtime/src/lib.rs
+++ b/crates/fparkan-runtime/src/lib.rs
@@ -70,6 +70,7 @@ mod control_resources;
mod mobile_budget;
mod node_amount;
mod node_stage;
+pub mod satellite_contacts;
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};
diff --git a/crates/fparkan-runtime/src/satellite_contacts.rs b/crates/fparkan-runtime/src/satellite_contacts.rs
new file mode 100644
index 00000000..534ad6f6
--- /dev/null
+++ b/crates/fparkan-runtime/src/satellite_contacts.rs
@@ -0,0 +1,153 @@
+//! Live building contacts for the satellite map.
+
+use crate::{Engine, StartingCockpit};
+use fparkan_world::{
+ handle_by_original_id, identity_metadata, registration_sequence, transform_state,
+};
+
+/// The original icon crop and position within the 256-pixel satellite image.
+#[derive(Clone, Copy, Debug, Eq, PartialEq)]
+pub struct BuildingContact {
+ pub pixel: [i32; 2],
+ pub icon_x: u32,
+}
+
+/// Width of the original landscape square used by the map projection.
+pub fn landscape_extent(engine: &Engine) -> Option<f32> {
+ let source = engine.loaded.as_ref()?.terrain.source_mesh()?;
+ let extent = source
+ .positions
+ .iter()
+ .map(|position| position[0])
+ .reduce(f32::max)?;
+ (extent.is_finite() && extent > 0.0).then_some(extent)
+}
+
+/// Current contacts for the player's own clan, which needs no detection test.
+pub fn owned_buildings(
+ engine: &Engine,
+ cockpit: StartingCockpit,
+ extent: f32,
+) -> impl Iterator<Item = BuildingContact> + '_ {
+ let owner = identity_metadata(&engine.world, cockpit.handle)
+ .ok()
+ .and_then(|identity| identity.owner_id);
+ engine.loaded.iter().flat_map(move |mission| {
+ mission.object_drafts.iter().filter_map(move |draft| {
+ let x = icon_x(draft.unit_dat_header_flags?)?;
+ let handle = handle_by_original_id(&engine.world, draft.original_id?)?;
+ let clan = identity_metadata(&engine.world, handle).ok()?.owner_id?;
+ registration_sequence(&engine.world, handle).ok()??;
+ if Some(clan) != owner {
+ return None;
+ }
+ let [world_x, world_y, _] = transform_state(&engine.world, handle)
+ .ok()?
+ .position
+ .map(f32::from_bits);
+ Some(BuildingContact {
+ pixel: project([world_x, world_y], extent)?,
+ icon_x: x,
+ })
+ })
+ })
+}
+
+fn icon_x(class: u32) -> Option<u32> {
+ // iron3d+0x9f460 selects the icon. The atlas positions come from +0x65370.
+ Some(match class {
+ 0x8000_0002 => 0,
+ 0x8000_0004 => 24,
+ 0x8000_0008 | 0x8000_0400 => 48,
+ 0x8000_0010 => 72,
+ 0x8001_0000 | 0x8002_0000 | 0x8004_0000 => 96,
+ 0x8000_0040 => 120,
+ 0x8010_0000 | 0x8020_0000 => 168,
+ 0x8000_0200 => 216,
+ _ => return None,
+ })
+}
+
+fn project([x, y]: [f32; 2], extent: f32) -> Option<[i32; 2]> {
+ if !x.is_finite() || !y.is_finite() || !extent.is_finite() || extent <= 0.0 {
+ return None;
+ }
+ // iron3d+0x349b0 rounds world coordinates before +0x745f0 scales them.
+ let scale = 256.0 / f64::from(extent);
+ let x = (f64::from(x.round_ties_even()) * scale).round_ties_even() as i32;
+ let y = (f64::from(y.round_ties_even()) * scale).round_ties_even() as i32;
+ Some([x, 256i32.saturating_sub(y)])
+}
+
+#[cfg(test)]
+mod tests {
+ use super::{icon_x, project};
+
+ #[test]
+ fn satellite_coordinates_match_the_original_inset_and_rounding() {
+ assert_eq!(project([300.31543, 556.2101], 1696.6862), Some([45, 172]));
+ assert_eq!(project([0.0, 0.0], 256.0), Some([0, 256]));
+ assert_eq!(project([256.0, 256.0], 256.0), Some([256, 0]));
+ assert_eq!(project([2.5, 3.5], 256.0), Some([2, 252]));
+ assert_eq!(icon_x(0x8000_0010), Some(72));
+ assert_eq!(icon_x(0x8000_0400), Some(48));
+ assert_eq!(icon_x(0x0100_8000), None);
+ }
+
+ #[test]
+ #[ignore = "requires licensed corpus"]
+ fn captured_factory_appears_at_its_existing_position() {
+ use super::{landscape_extent, owned_buildings, BuildingContact};
+ use crate::{
+ create, load_gameplay_mission, starting_cockpit, EngineServices, MissionMode,
+ MissionRequest, MissionStartupInput,
+ };
+ use fparkan_vfs::DirectoryVfs;
+ use fparkan_world::{handle_by_original_id, identity_metadata, set_owner, transform_state};
+ use std::sync::Arc;
+
+ let root = std::env::var_os("FPARKAN_CORPUS_PART1_ROOT").expect("licensed corpus");
+ let mut engine = create(EngineServices::new(Arc::new(DirectoryVfs::new(root)))).unwrap();
+ load_gameplay_mission(
+ &mut engine,
+ MissionRequest {
+ key: "MISSIONS/CAMPAIGN/CAMPAIGN.00/Mission.02/data.tma".into(),
+ mode: MissionMode::SingleMission,
+ },
+ MissionStartupInput {
+ queue_time_ms: 0,
+ research_creation_gate: false,
+ },
+ None,
+ )
+ .unwrap();
+ let cockpit = starting_cockpit(&engine).unwrap();
+ let extent = landscape_extent(&engine).unwrap();
+ assert_eq!(extent.to_bits(), 1696.6862f32.to_bits());
+ let factory = engine
+ .loaded
+ .as_ref()
+ .unwrap()
+ .object_drafts
+ .iter()
+ .find(|draft| draft.unit_dat_header_flags == Some(0x8000_0010))
+ .unwrap();
+ let handle = handle_by_original_id(&engine.world, factory.original_id.unwrap()).unwrap();
+ let [x, y, _] = transform_state(&engine.world, handle)
+ .unwrap()
+ .position
+ .map(f32::from_bits);
+ let marker = BuildingContact {
+ pixel: project([x, y], extent).unwrap(),
+ icon_x: 72,
+ };
+ assert!(!owned_buildings(&engine, cockpit, extent).any(|contact| contact == marker));
+
+ let owner = identity_metadata(&engine.world, cockpit.handle)
+ .unwrap()
+ .owner_id;
+ assert!(owner.is_some());
+ set_owner(&mut engine.world, handle, owner).unwrap();
+ assert!(owned_buildings(&engine, cockpit, extent).any(|contact| contact == marker));
+ }
+}
diff --git a/docs/appendices/ui-shell.md b/docs/appendices/ui-shell.md
index 7f5fa1b4..83302b4f 100644
--- a/docs/appendices/ui-shell.md
+++ b/docs/appendices/ui-shell.md
@@ -154,8 +154,21 @@ RVA `0x802a0`. В запущенном оригинале при 800×600 раз
ставит компас у её правого нижнего угла.
Карта закрыта при старте. Вызовы RVA `0x74540` и `0x74550` подтвердили
-состояния показа и скрытия. Отметки объектов и доступность командного
-режима в разных кабинах требуют отдельной сверки.
+состояния показа и скрытия.
+
+RVA `0x349b0` округляет координаты постройки в мире до целых и передаёт их
+в RVA `0x745f0`. Там обе координаты умножаются на `256 / ширина ландшафта`
+и снова округляются. Экранная ось Y направлена вниз, поэтому из 256
+вычитается результат для Y. В «Конструкторе» ширина 1696,686 совпала у
+работающего оригинала и в исходных вершинах `Land.msh`. Например, точка
+`(300, 556)` попадает в `(45, 172)` от верхнего левого угла изображения.
+
+Свои постройки видны без проверки обнаружения, а для чужой постройки RVA
+`0x7ea80` ищет её в списке обнаруженных объектов. Тип постройки выбирает
+значок по таблице RVA `0x9f460`, а RVA `0x65370` берёт соответствующий
+квадрат 24×24 из страницы `icons`. В FParkan значок своей постройки
+появляется после смены владельца. Отметки варботов, обнаружение чужих
+объектов и доступность командного режима в разных кабинах открыты.
## Контракт новой реализации