From c3813cf23f80b0fd190cdf20f2b8e65a53fd02b9 Mon Sep 17 00:00:00 2001 From: Valentin Popov Date: Sat, 14 Nov 2026 15:49:41 +0400 Subject: feat(game): show player health and clan resources --- README.md | 2 + apps/fparkan-game/src/main.rs | 76 +++++++++++++++++++---------- crates/fparkan-runtime/src/lib.rs | 20 ++++++++ crates/fparkan-runtime/src/player_status.rs | 69 ++++++++++++++++++++++++++ docs/appendices/knowledge-boundaries.md | 8 ++- docs/tomes/06-behavior.md | 10 ++++ 6 files changed, 157 insertions(+), 28 deletions(-) create mode 100644 crates/fparkan-runtime/src/player_status.rs diff --git a/README.md b/README.md index c3759baf..38d563a0 100644 --- a/README.md +++ b/README.md @@ -48,6 +48,8 @@ cargo run --release -p fparkan-game -- ` открывается с видом из его кабины. Стрелки двигают героя вперёд, назад и вбок. Мышь поворачивает корпус по горизонтали и наклоняет взгляд по вертикали. `Esc` освобождает указатель, правая кнопка возвращает захват. +Заголовок окна показывает, кем вы управляете, здоровье, запас руды и +доступную и запрошенную энергию клана. Цифры выбирают орудие, `0` выбирает все. Левая кнопка запускает огонь с оригинальным звуком доступных орудий. Контакт с рельефом завершает полёт. Попадания по юнитам наносят приближённый урон и могут уничтожить цель. diff --git a/apps/fparkan-game/src/main.rs b/apps/fparkan-game/src/main.rs index 7895e6d9..55994b28 100644 --- a/apps/fparkan-game/src/main.rs +++ b/apps/fparkan-game/src/main.rs @@ -10110,6 +10110,8 @@ struct StaticVulkanApp { player_mine_pressed: bool, player_disembark_pressed: bool, boarded_hero_index: Option, + laboratory_status: Option, + mission_title: String, audio: Option, camera_mode: &'static str, mesh_components: usize, @@ -10245,6 +10247,8 @@ impl StaticVulkanApp { player_mine_pressed: false, player_disembark_pressed: false, boarded_hero_index: None, + laboratory_status: None, + mission_title: String::new(), audio, camera_mode: preview.camera_mode, mesh_components: preview.mesh_components, @@ -10956,7 +10960,7 @@ impl StaticVulkanApp { } } - fn update_mission_title(&self) { + fn update_mission_title(&mut self) { let Some(window) = &self.window else { return; }; @@ -10965,19 +10969,46 @@ impl StaticVulkanApp { .as_ref() .and_then(fparkan_runtime::loaded_mission_script_outcome) .unwrap_or_default(); - window.set_title( - match ( - outcome, - self.mission_paused, - self.boarded_hero_index.is_some(), - ) { - (fparkan_runtime::MissionScriptOutcome::Completed, _, _) => "Миссия выполнена", - (fparkan_runtime::MissionScriptOutcome::Failed, _, _) => "Миссия провалена", - (_, true, _) => "FParkan mission — Пауза", - (_, _, true) => "FParkan mission — Варбот", - _ => "FParkan mission", - }, - ); + use fparkan_runtime::MissionScriptOutcome::{Completed, Failed}; + let title = match (outcome, self.mission_paused) { + (Completed, _) => "Миссия выполнена".into(), + (Failed, _) => "Миссия провалена".into(), + (_, true) => "FParkan mission — Пауза".into(), + _ => { + let mut title = "FParkan mission".to_owned(); + if let (Some(engine), Some(cockpit), None) = + (&self.mission_engine, self.cockpit, &self.demo_camera) + { + use std::fmt::Write as _; + let unit = if self.boarded_hero_index.is_some() { + "Варбот" + } else { + "Герой" + }; + let _ = write!(title, " — {unit}"); + if let Some(status) = fparkan_runtime::player_status(engine, cockpit.handle) { + if let Some(health) = status.health_percent { + let _ = write!(title, " · Здоровье {health}%"); + } + if let Some(ore) = status.ore_in_buffer { + let _ = write!(title, " · Руда {ore:.0}"); + } + if let Some((available, demand)) = status.power { + let _ = write!(title, " · Энергия {available:.0}/{demand:.0}"); + } + } + } + if let Some(status) = &self.laboratory_status { + title.push_str(" — "); + title.push_str(status); + } + title + } + }; + if self.mission_title != title { + window.set_title(&title); + self.mission_title = title; + } } fn update_shadow( @@ -11071,7 +11102,6 @@ impl StaticVulkanApp { let control_clock_ms = clock.time_ms; self.advance_player_projectiles(control_clock_ms)?; let mut player_step = None; - let boarded_before = self.boarded_hero_index; if let Some(engine) = self.mission_engine.as_mut() { let disembark = std::mem::take(&mut self.player_disembark_pressed); if let Some(vehicle) = player_vehicle(engine) { @@ -11140,9 +11170,8 @@ impl StaticVulkanApp { ) { match order_lab_research(engine, cockpit, control_clock_ms) { Ok((component, duration)) => { - if let Some(window) = &self.window { - window.set_title(&format!("Лаборатория — исследуется {component}")); - } + self.laboratory_status = + Some(format!("Лаборатория — исследуется {component}")); eprintln!("laboratory_research_order component={component} duration_ms={duration} queue_time_ms={control_clock_ms}"); } Err(error) => eprintln!("laboratory_research_rejected {error}"), @@ -11273,9 +11302,7 @@ impl StaticVulkanApp { eprintln!("sim_coverage factory_spawn_failed=1 reason={error}"); } if let Some(component) = &frame.researched_component { - if let Some(window) = &self.window { - window.set_title(&format!("Лаборатория — разработано {component}")); - } + self.laboratory_status = Some(format!("Лаборатория — разработано {component}")); eprintln!("laboratory_research_complete component={component} queue_time_ms={control_clock_ms}"); } if frame.autodemo_reinforcement_unavailable != 0 { @@ -11325,15 +11352,10 @@ impl StaticVulkanApp { } } } - if tick.notices.iter().any(|notice| { - matches!(notice, MissionNotice::Completed | MissionNotice::Failed) - }) { - self.update_mission_title(); - } } self.mission_frame = Some(frame); } - if self.boarded_hero_index != boarded_before { + if self.mission_engine.is_some() { self.update_mission_title(); } if let Some(frame) = &self.mission_frame { diff --git a/crates/fparkan-runtime/src/lib.rs b/crates/fparkan-runtime/src/lib.rs index 6de6b386..24b6f281 100644 --- a/crates/fparkan-runtime/src/lib.rs +++ b/crates/fparkan-runtime/src/lib.rs @@ -48,6 +48,7 @@ mod mesh_collision; mod mining; mod mission_events; mod player_motion; +mod player_status; mod player_weapon; mod production; mod projectile; @@ -68,6 +69,7 @@ pub use mission_events::{ MissionEventTick, MissionNotice, }; pub use player_motion::{plan_player_motion, PlayerMotion, PlayerMotionStep}; +pub use player_status::{player_status, PlayerStatus}; pub use player_weapon::{prepared_warbot_weapons, starting_player_weapons, PlayerWeapons}; pub use production::order_factory_robot; pub use projectile::{ @@ -18125,6 +18127,23 @@ mod tests { .autodemo_combat_events .is_empty()); let hero = starting_cockpit(&engine).unwrap(); + let status = player_status(&engine, hero.handle).unwrap(); + assert_eq!(status.health_percent, Some(100)); + let table = loaded_mission_control_device_tables(&engine) + .unwrap() + .iter() + .find(|table| table.handle == hero.handle) + .unwrap(); + let root = control_node_provider_row(table, 0).unwrap(); + let quarter = f32::from_bits(root.initial_amount_bits) * 0.25; + let changed = apply_projectile_hit(&mut engine, hero.handle, quarter) + .unwrap() + .expect("hero damage provider"); + assert!(!changed.1); + assert_eq!( + player_status(&engine, hero.handle).unwrap().health_percent, + Some(75) + ); let enemy = mission_object_handle(&engine, OriginalObjectId(11)).unwrap(); let enemy_pose = transform_state(&engine.world, enemy).unwrap(); let [x, y, z] = enemy_pose.position.map(f32::from_bits); @@ -18160,6 +18179,7 @@ mod tests { enemy_pose.position ); assert!(transform_state(&engine.world, hero.handle).is_err()); + assert_eq!(player_status(&engine, hero.handle), None); assert_eq!(failures, 1); assert_eq!( loaded_mission_script_outcome(&engine), diff --git a/crates/fparkan-runtime/src/player_status.rs b/crates/fparkan-runtime/src/player_status.rs new file mode 100644 index 00000000..52af212c --- /dev/null +++ b/crates/fparkan-runtime/src/player_status.rs @@ -0,0 +1,69 @@ +use crate::{Engine, MissionControlNodeProviderTableStatus}; +use fparkan_world::{identity_metadata, ObjectHandle}; + +/// Current values for the player's controlled unit and clan. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct PlayerStatus { + /// Remaining root Control capacity as a percentage. + pub health_percent: Option, + /// Ore stored in the clan's buffer. + pub ore_in_buffer: Option, + /// Available power and total power demand. + pub power: Option<(f32, f32)>, +} + +/// Reads the values used by combat and the clan's current distributor. +#[must_use] +pub fn player_status(engine: &Engine, controlled: ObjectHandle) -> Option { + let mission = engine.loaded.as_ref()?; + let owner = identity_metadata(&engine.world, controlled) + .ok()? + .owner_id?; + let health_percent = mission + .control_device_tables + .iter() + .find(|table| table.handle == controlled) + .and_then(|table| { + let MissionControlNodeProviderTableStatus::Available(rows) = + &table.node_provider_status + else { + return None; + }; + let root = rows.first()?; + health_percent( + f32::from_bits(root.current_amount_bits), + f32::from_bits(root.initial_amount_bits), + ) + }); + let resources = mission + .script_bundles + .iter() + .find(|bundle| bundle.clan_index == usize::from(owner.0)) + .and_then(|bundle| bundle.behavior_warm_start); + Some(PlayerStatus { + health_percent, + ore_in_buffer: resources.map(|state| f32::from_bits(state.cleared_words[2])), + power: resources.map(|state| { + let [available, _, _, demand, _] = state.cleared_words.map(f32::from_bits); + (available, demand) + }), + }) +} + +fn health_percent(current: f32, initial: f32) -> Option { + (current.is_finite() && initial.is_finite() && initial > 0.0) + .then(|| (100.0 * (current / initial).clamp(0.0, 1.0)).round() as u32) +} + +#[cfg(test)] +mod tests { + use super::health_percent; + + #[test] + fn reports_current_capacity_within_display_range() { + assert_eq!(health_percent(23.0, 80.0), Some(29)); + assert_eq!(health_percent(90.0, 80.0), Some(100)); + assert_eq!(health_percent(-5.0, 80.0), Some(0)); + assert_eq!(health_percent(0.0, 0.0), None); + } +} diff --git a/docs/appendices/knowledge-boundaries.md b/docs/appendices/knowledge-boundaries.md index fa907504..36085e4d 100644 --- a/docs/appendices/knowledge-boundaries.md +++ b/docs/appendices/knowledge-boundaries.md @@ -87,7 +87,13 @@ authoring API без динамического подтверждения. с допуском по высоте, включая внутреннюю площадку генератора. Границы нативного триггера, допуск оригинала для вражеских зданий, режим МЦУ и доступ разных типоразмеров роботов открыты. `player_building_floor_approx` отмечает временные -пределы шага и спуска по коллизии здания. +пределы шага и спуска по коллизии здания. Выход из среднего бункера +«Двух крепостей» пока открыт для исследования. Подстановка открытой позы +дверей не устранила остановку на геометрии неподвижных секций. + +Здоровье и ресурсы одиночной миссии выводятся в заголовке окна. +`mission_message_ui_stub` по-прежнему отмечает отсутствие текста +сценарных подсказок поверх сцены. `factory_orders_approx` отмечает восемь слотов живых роботов, один заказ в работе, выбор первой схемы `prebuild` или явного DAT при запуске, diff --git a/docs/tomes/06-behavior.md b/docs/tomes/06-behavior.md index ba5a4768..1e320625 100644 --- a/docs/tomes/06-behavior.md +++ b/docs/tomes/06-behavior.md @@ -2020,6 +2020,16 @@ PgUp и PgDn. FParkan использует эти же клавиши. Отпу `CanFly`. FParkan пока определяет доступность полёта по штатным ключам шасси. Скорости подъёма, снижения и движения постоянны. +### Состояние героя и базы + +В одиночной миссии верхняя строка окна показывает героя или варбота, которым +управляет игрок. Здоровье — оставшаяся доля запаса корневого узла Control, +по которому сейчас считаются попадания. При посадке строка показывает запас +машины. Руда — текущий запас в буфере клана. Два числа энергии показывают +подачу и суммарный запрос по последнему такту распределителя. Когда запрос +выше подачи, строительство и другие потребители конкурируют за энергию. +Сообщения о паузе и исходе миссии имеют приоритет. + ### Коммуникатор здания В «Конструкторе» главный машинный зал отмечен указателями. Подсказка -- cgit v1.2.3