aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--apps/fparkan-game/src/cockpit_instrument.rs24
-rw-r--r--apps/fparkan-game/src/mission_overlay.rs2
-rw-r--r--crates/fparkan-runtime/src/cockpit_instruments.rs63
-rw-r--r--crates/fparkan-runtime/src/projectile_shield.rs8
-rw-r--r--crates/fparkan-runtime/src/weapon_pose.rs50
-rw-r--r--docs/appendices/knowledge-boundaries.md3
-rw-r--r--docs/appendices/ui-shell.md19
7 files changed, 149 insertions, 20 deletions
diff --git a/apps/fparkan-game/src/cockpit_instrument.rs b/apps/fparkan-game/src/cockpit_instrument.rs
index 76533778..37023fea 100644
--- a/apps/fparkan-game/src/cockpit_instrument.rs
+++ b/apps/fparkan-game/src/cockpit_instrument.rs
@@ -17,8 +17,8 @@ use fparkan_render_vulkan::{
};
use fparkan_runtime::{
cockpit_instruments::{
- instrument_distance, instrument_readout, instrument_sphere, InstrumentReadout,
- InstrumentStatus,
+ instrument_bounds, instrument_distance, instrument_readout, instrument_sphere,
+ InstrumentReadout, InstrumentStatus,
},
Engine, StartingCockpit,
};
@@ -47,6 +47,7 @@ struct PanelReadout {
}
struct Model {
+ bounds: Option<([f32; 3], f32)>,
ranges: Range<usize>,
counts: Vec<u32>,
components: Vec<ModelComponent>,
@@ -65,7 +66,11 @@ pub(super) struct LiveModels<'a> {
}
impl CockpitInstrument {
- pub(super) fn load(root: &Path, scene: &mut StaticPreviewScene) -> Result<Self, String> {
+ pub(super) fn load(
+ root: &Path,
+ engine: &Engine,
+ scene: &mut StaticPreviewScene,
+ ) -> Result<Self, String> {
let images = Images::load(&DirectoryVfs::new(root))?;
let strings = StringResources::open(&root.join("iron3d.dll"))?;
let panels = [
@@ -123,6 +128,7 @@ impl CockpitInstrument {
}
let ranges = start..scene.mesh.draw_ranges.len();
models.push(Model {
+ bounds: instrument_bounds(engine, object),
ranges,
counts,
components: projected,
@@ -161,6 +167,10 @@ impl CockpitInstrument {
}
let mut views = [None, None];
let mut active = [None; 2];
+ let sphere = |engine, subject, object_index| {
+ let model: &Model = self.models.get(object_index)?;
+ instrument_sphere(engine, subject, object_index, model.bounds)
+ };
for (index, panel) in self.panels.iter_mut().enumerate() {
let mut model_pose = None;
let reading = live.and_then(|(engine, cockpit, snapshot)| {
@@ -171,13 +181,13 @@ impl CockpitInstrument {
cockpit.handle
};
let unit = instrument_readout(engine, cockpit, subject)?;
- let sphere = instrument_sphere(engine, subject, unit.object_index);
+ let subject_sphere = sphere(engine, subject, unit.object_index);
let observer = if observing {
- instrument_sphere(engine, cockpit.handle, cockpit.object_index)
+ sphere(engine, cockpit.handle, cockpit.object_index)
} else {
None
};
- let centers = sphere.zip(observer);
+ let centers = subject_sphere.zip(observer);
let distance = if observing {
centers
.and_then(|((center, _), (origin, _))| instrument_distance(origin, center))
@@ -185,7 +195,7 @@ impl CockpitInstrument {
None
};
views[index] = (|| {
- let (center, radius) = sphere?;
+ let (center, radius) = subject_sphere?;
let pose = live_root_pose(subject, snapshot)?;
model_pose = Some(pose);
let forward = if observing {
diff --git a/apps/fparkan-game/src/mission_overlay.rs b/apps/fparkan-game/src/mission_overlay.rs
index 717bbd17..06db1c90 100644
--- a/apps/fparkan-game/src/mission_overlay.rs
+++ b/apps/fparkan-game/src/mission_overlay.rs
@@ -100,7 +100,7 @@ impl MissionOverlay {
});
#[cfg(windows)]
let instrument = cockpit.and_then(|_| {
- CockpitInstrument::load(root, preview)
+ CockpitInstrument::load(root, engine, preview)
.inspect_err(|error| eprintln!("cockpit_instrument_unavailable reason={error}"))
.ok()
});
diff --git a/crates/fparkan-runtime/src/cockpit_instruments.rs b/crates/fparkan-runtime/src/cockpit_instruments.rs
index 6aa2e3f6..88ea8df5 100644
--- a/crates/fparkan-runtime/src/cockpit_instruments.rs
+++ b/crates/fparkan-runtime/src/cockpit_instruments.rs
@@ -3,8 +3,10 @@
use crate::{
control_device_provider_value, control_device_selector_zero,
projectile::unit_sphere,
+ projectile_shield::{enclosing_sphere, world_sphere},
query_control_device_table_selector,
strategic_map_readout::{contact_readout, ContactReadout},
+ weapon_pose::WeaponPoses,
Engine, MissionControlDeviceTableStatus, StartingCockpit, HERO_UNIT_CLASS,
};
use fparkan_world::{identity_metadata, transform_state, ObjectHandle};
@@ -87,15 +89,27 @@ pub fn instrument_readout(
})
}
-/// The same root sphere used for the live object's spatial queries.
+/// Local sphere used by AniMesh selector 2 with the targeter's node filter.
+pub fn instrument_bounds(engine: &Engine, object_index: usize) -> Option<([f32; 3], f32)> {
+ let mission = engine.loaded.as_ref()?;
+ let draft = mission.object_drafts.get(object_index)?;
+ let poses = WeaponPoses::new(draft, &mission.mission_assets, object_index);
+ enclosing_sphere(&poses.instrument_node_spheres(&mission.mission_assets, object_index))
+}
+
+/// Places the sphere in the object's current world pose.
pub fn instrument_sphere(
engine: &Engine,
subject: ObjectHandle,
object_index: usize,
+ bounds: Option<([f32; 3], f32)>,
) -> Option<([f32; 3], f32)> {
let mission = engine.loaded.as_ref()?;
let pose = transform_state(&engine.world, subject).ok()?;
- unit_sphere(&mission.mission_assets, object_index, pose)
+ bounds.map_or_else(
+ || unit_sphere(&mission.mission_assets, object_index, pose),
+ |bounds| world_sphere(bounds, pose),
+ )
}
/// Targeter distance is the 3D separation of the two centers in world units.
@@ -138,3 +152,48 @@ fn targeter_distance_includes_height_and_rounds_to_even() {
assert_eq!(instrument_distance([0.0; 3], [0.0, 0.0, 4.5]), Some(4));
assert_eq!(instrument_distance([0.0; 3], [0.0; 3]), None);
}
+
+#[cfg(test)]
+#[test]
+#[ignore = "requires licensed corpus"]
+fn licensed_targeter_bounds_match_the_original_hero_and_bunker() {
+ use crate::{
+ create, load_gameplay_mission, starting_cockpit, EngineServices, MissionMode,
+ MissionRequest, MissionStartupInput,
+ };
+ use fparkan_vfs::DirectoryVfs;
+ 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/Single.01/data.tma".into(),
+ mode: MissionMode::SingleMission,
+ },
+ MissionStartupInput {
+ queue_time_ms: 0,
+ research_creation_gate: false,
+ },
+ None,
+ )
+ .unwrap();
+
+ // Local bounds observed on the stock start, AniMesh+0xf3b0.
+ let hero = starting_cockpit(&engine).unwrap();
+ for (index, expected_center, expected_radius) in [
+ (
+ hero.object_index,
+ [-0.001875045, -0.17754595, 0.0161541],
+ 1.5871644,
+ ),
+ (0, [-0.00038418506, -0.036218945, 5.9308352], 54.111202),
+ ] {
+ let (center, radius) = instrument_bounds(&engine, index).unwrap();
+ for (actual, expected) in center.into_iter().zip(expected_center) {
+ assert!((actual - expected).abs() < 0.0001, "{center:?}");
+ }
+ assert!((radius - expected_radius).abs() < 0.0001, "{radius}");
+ }
+}
diff --git a/crates/fparkan-runtime/src/projectile_shield.rs b/crates/fparkan-runtime/src/projectile_shield.rs
index bb766fc5..5ff876a0 100644
--- a/crates/fparkan-runtime/src/projectile_shield.rs
+++ b/crates/fparkan-runtime/src/projectile_shield.rs
@@ -228,7 +228,7 @@ pub(super) fn absorb(engine: &mut Engine, hit: ProjectileContact, volume: f32) -
remaining
}
-fn world_sphere(
+pub(super) fn world_sphere(
(center, radius): ([f32; 3], f32),
pose: TransformState,
) -> Option<([f32; 3], f32)> {
@@ -243,9 +243,9 @@ fn world_sphere(
))
}
-fn enclosing_sphere(parts: &[([f32; 3], f32)]) -> Option<([f32; 3], f32)> {
- // AniMesh+0x9510 weights model centers by the authored radii. A second
- // pass then puts even the most distant model sphere inside the result.
+pub(super) fn enclosing_sphere(parts: &[([f32; 3], f32)]) -> Option<([f32; 3], f32)> {
+ // AniMesh+0x9510 weights centers by the authored radii. A second pass
+ // puts even the most distant part inside the result.
let weight: f32 = parts.iter().map(|(_, radius)| radius).sum();
if weight <= 0.0 {
return None;
diff --git a/crates/fparkan-runtime/src/weapon_pose.rs b/crates/fparkan-runtime/src/weapon_pose.rs
index f01a93e1..97f239aa 100644
--- a/crates/fparkan-runtime/src/weapon_pose.rs
+++ b/crates/fparkan-runtime/src/weapon_pose.rs
@@ -10,7 +10,8 @@ use fparkan_assets::{
PreparedControlNodeBinding, PreparedControlPoint,
};
use fparkan_msh::{
- node38_fallback_hierarchy, node38_fallback_pose, node38_sampled_hierarchy_at_times, NodeId,
+ node38_fallback_hierarchy, node38_fallback_pose, node38_metadata, node38_sampled_hierarchy,
+ node38_sampled_hierarchy_at_times, selected_slot, Group, Lod, NodeId,
};
use fparkan_prototype::{unit_component_tree, PROTOTYPE_TYPE_EXTO};
use fparkan_render::LegacyIron3dEulerTransform;
@@ -251,6 +252,53 @@ impl WeaponPoses {
.collect()
}
+ pub(super) fn instrument_node_spheres(
+ &self,
+ assets: &MissionAssets,
+ index: usize,
+ ) -> Vec<([f32; 3], f32)> {
+ // AniMesh+0x9510 builds the filtered sphere in unit space at frame zero.
+ let models: Vec<_> = assets
+ .visuals_for_object(index)
+ .iter()
+ .map(|&id| assets.model_by_id(assets.visual_by_id(id)?.model_id?))
+ .collect();
+ let hierarchies: Vec<_> = models
+ .iter()
+ .map(|model| node38_sampled_hierarchy(&(*model)?.validated, 0))
+ .collect();
+ let mut parts = Vec::new();
+ for (component, model) in models.into_iter().enumerate() {
+ let Some(model) = model else { continue };
+ if matches!(self.mounts[component], Mount::Unavailable) {
+ continue;
+ }
+ let model = &model.validated;
+ // The attached model's root is replaced by the parent's socket.
+ let first_node = usize::from(component != 0);
+ for node in first_node..model.node_count {
+ let id = NodeId(node as u32);
+ if !node38_metadata(model, id).is_some_and(|meta| meta.header_flags & 1 == 0) {
+ continue;
+ }
+ let Some(slot) = selected_slot(model, id, Lod(0), Group(0)) else {
+ continue;
+ };
+ let slot = &model.slots[slot.0 as usize];
+ if let Some(center) = mounted_point(
+ &hierarchies,
+ &self.mounts,
+ component,
+ node,
+ slot.sphere_center,
+ ) {
+ parts.push((center, slot.sphere_radius));
+ }
+ }
+ }
+ parts
+ }
+
#[cfg(test)]
pub(super) fn has_aim(&self) -> bool {
self.aims.iter().any(Option::is_some)
diff --git a/docs/appendices/knowledge-boundaries.md b/docs/appendices/knowledge-boundaries.md
index 7b74fac4..976dba0b 100644
--- a/docs/appendices/knowledge-boundaries.md
+++ b/docs/appendices/knowledge-boundaries.md
@@ -1462,7 +1462,8 @@ semantics, focus/navigation и HUD state machine.
В нижнем радаре ещё открыты захват цели правой кнопкой, отметки группы,
спидометр и кнопки на рамке прибора. Порядок объектов при одинаковой дальности
и при смене режима ручного управления требует проверки.
-У боковых приборов требуют сверки сферы, свет и геометрия повреждённых моделей.
+У боковых приборов требуют сверки проекция камеры, свет и выбор слотов по стадии
+повреждения. Если сферы узлов недоступны, используется сфера заголовка корневого MSH.
Звуковые предупреждения при низких показаниях ещё открыты.
Оружейные строки показывают боезапас, заряд и цикл выстрела. Для управляемых
ракет ещё открыты состояния наведения и подпись «ВНЕ ЗОНЫ ЗАХВАТА».
diff --git a/docs/appendices/ui-shell.md b/docs/appendices/ui-shell.md
index 3ce6ec40..5afc83e5 100644
--- a/docs/appendices/ui-shell.md
+++ b/docs/appendices/ui-shell.md
@@ -848,8 +848,19 @@ Control. Оружейный цикл в `Control.dll` по RVA `0x29ca0` разÐ
читаются из оригинальных ресурсов. [Хеши сборок](../reference/original-binaries.md).
FParkan рисует живые модели поверх рамок с текущими позами. У каждой
-миниатюры свои камера, прямоугольник и область очистки глубины. Для
-дальности и размещения модели используются сферы корневых компонентов.
+миниатюры свои камера, прямоугольник и область очистки глубины.
+
+Для дальномера и камеры `iron3d.dll` по RVA `0x41aea` запрашивает у
+AniMesh сферу объекта с фильтром `[0xfff, 0, 1, 2]`. Ветка
+`AniMesh.dll` по RVA `0x9510` использует сферы слотов LOD 0 для узлов,
+у которых сброшен младший бит заголовка Node38. Центры переносятся по
+иерархии и точкам крепления в координаты объекта на нулевом кадре.
+Центр общей сферы — среднее с весами по радиусам. Общий радиус равен
+наибольшей сумме расстояния от этого центра до узла и радиуса узла.
+При показе прибора готовая сфера переносится в текущую позу объекта.
+Герой и средний бункер в «Двух крепостях» используют радиусы 1,587 и
+54,111 м соответственно.
+
В оригинале вызов миниатюры по RVA `0x42141` передаёт маску `0x7f0`.
Для среднего бункера и малого склада этот вызов входит в отрисовщик
строения `Terrain.dll` по RVA `0x34260`. По RVA `0x34d16` маска уже равна
@@ -860,8 +871,8 @@ FParkan рисует живые модели поверх рамок с теку
приборов из этих слотов, используя текущие позы и крепления.
[Хеши сборок](../reference/original-binaries.md).
-Выбор сферы и освещения предстоит сверить. Миниатюры пока используют
-слоты исходной стадии повреждения.
+Проекцию камеры и освещение предстоит сверить. Миниатюры и их сферы
+пока используют слоты исходной стадии повреждения.
## Контракт новой реализации