diff options
| author | Valentin Popov <valentin@popov.link> | 2026-11-26 05:07:45 +0300 |
|---|---|---|
| committer | Valentin Popov <valentin@popov.link> | 2026-11-26 05:07:45 +0300 |
| commit | 81eb7cd67af54780756a98475145a864b72cbee0 (patch) | |
| tree | f9a388c0c4410ac4c2059d96fb976f89c162bb37 | |
| parent | 4e4a0795fccbcc4a2dd2f4b51c8f8f7802812791 (diff) | |
| download | fparkan-81eb7cd67af54780756a98475145a864b72cbee0.tar.xz fparkan-81eb7cd67af54780756a98475145a864b72cbee0.zip | |
feat(combat): aim autonomous turrets with authored tracks
Convert the selected target to the turret mount space and sample the authored azimuth and elevation tracks for rendering and the CPU muzzle query. Leave trigger cadence and target selection intact.
Verified the stock AutoDemo launch, turret swivel with Vulkan validation clean, and a stock combat regression. Aim slew and recoil providers remain open.
| -rw-r--r-- | apps/fparkan-game/src/main.rs | 42 | ||||
| -rw-r--r-- | crates/fparkan-runtime/src/lib.rs | 4 | ||||
| -rw-r--r-- | crates/fparkan-runtime/src/turret_aim.rs | 118 | ||||
| -rw-r--r-- | crates/fparkan-runtime/src/unit_combat.rs | 95 | ||||
| -rw-r--r-- | crates/fparkan-runtime/src/weapon_pose.rs | 63 | ||||
| -rw-r--r-- | docs/appendices/knowledge-boundaries.md | 2 | ||||
| -rw-r--r-- | docs/tomes/06-behavior.md | 11 |
7 files changed, 284 insertions, 51 deletions
diff --git a/apps/fparkan-game/src/main.rs b/apps/fparkan-game/src/main.rs index b8b81c19..d0d6d2b8 100644 --- a/apps/fparkan-game/src/main.rs +++ b/apps/fparkan-game/src/main.rs @@ -7302,7 +7302,7 @@ fn update_gameplay_animation_pose_buffers( native_clock_ms: u32, aim: Option<(StartingCockpit, f32)>, player_doors: Option<([f32; 3], f32, &[BuildingCollisionBinding])>, - motion: Option<(&[Option<MissionRenderRoot>], &WorldSnapshot)>, + motion: Option<(&[Option<MissionRenderRoot>], &WorldSnapshot, &Engine)>, ) -> Result<(), String> { for (object_index, components) in instances.iter_mut().enumerate() { let Some(object_pose_buffers) = pose_buffers.get_mut(object_index) else { @@ -7383,11 +7383,26 @@ fn update_gameplay_animation_pose_buffers( } } } - let walking = motion.is_some_and(|(roots, snapshot)| { + let walking = motion.is_some_and(|(roots, snapshot, engine)| { roots .get(object_index) .and_then(Option::as_ref) .is_some_and(|root| { + if aim.is_none_or(|(cockpit, _)| cockpit.object_index != object_index) + && fparkan_runtime::has_turret_aim(&instance.control) + { + if let Some(aim) = fparkan_runtime::autonomous_turret_aim( + engine, + root.handle, + component_index, + ) { + fparkan_runtime::apply_autonomous_turret_pose( + &instance.control, + aim, + &mut node_times, + ); + } + } chassis_animation::sample(instance, root, snapshot, &mut node_times) }) }); @@ -7416,6 +7431,7 @@ fn control_tree_chain_animates( tree: Option<&[fparkan_prototype::UnitComponentTreeNode]>, controls: &[Option<PreparedComponentControl>], turret_component: Option<usize>, + autonomous: bool, ) -> bool { let mut current = Some(component_index); let mut remaining = controls.len(); @@ -7426,6 +7442,7 @@ fn control_tree_chain_animates( .and_then(Option::as_ref) .is_some_and(|control| { fparkan_runtime::has_proximity_doors(control) + || (autonomous && fparkan_runtime::has_turret_aim(control)) || control.typed_records.iter().any(|record| record.tag == 21) }) { @@ -8416,6 +8433,10 @@ fn static_preview_mesh_and_materials( cockpit .filter(|cockpit| cockpit.object_index == object_index) .map(|cockpit| cockpit.component_index), + live_roots + && mission_root + .unit_dat_header_flags + .is_some_and(|class| class & 0x0100_0000 != 0), )); // Native AniMesh only resolves global MSH node sockets for EXTO // geometry. Internal INTO components use controller/equipment @@ -11405,7 +11426,14 @@ impl StaticVulkanApp { player_doors, self.mission_frame .as_ref() - .map(|frame| (self.mission_render_roots.as_slice(), &frame.snapshot)), + .zip(self.mission_engine.as_ref()) + .map(|(frame, engine)| { + ( + self.mission_render_roots.as_slice(), + &frame.snapshot, + engine, + ) + }), )?; let placements = self .mission_frame @@ -14862,7 +14890,13 @@ mod tests { }; let control = socket_timeline_control(); let controls = vec![None, Some(control.clone()), None]; - assert!(control_tree_chain_animates(2, Some(&tree), &controls, None)); + assert!(control_tree_chain_animates( + 2, + Some(&tree), + &controls, + None, + false + )); let mut instances = vec![vec![ None, Some(ControlAnimationInstance { diff --git a/crates/fparkan-runtime/src/lib.rs b/crates/fparkan-runtime/src/lib.rs index 9fb9a262..dda56734 100644 --- a/crates/fparkan-runtime/src/lib.rs +++ b/crates/fparkan-runtime/src/lib.rs @@ -102,6 +102,10 @@ use resource_distribution::advance_behavior_distributor_tick; mod script_host; mod script_patrol; mod script_time; +mod turret_aim; +pub use turret_aim::{ + apply_autonomous_turret_pose, autonomous_turret_aim, has_turret_aim, TurretAim, +}; mod unit_chassis; pub use unit_chassis::loaded_walk_chassis; mod unit_combat; diff --git a/crates/fparkan-runtime/src/turret_aim.rs b/crates/fparkan-runtime/src/turret_aim.rs new file mode 100644 index 00000000..2c9c66e7 --- /dev/null +++ b/crates/fparkan-runtime/src/turret_aim.rs @@ -0,0 +1,118 @@ +//! Aim a mount through the azimuth and elevation tracks supplied by its asset. + +use crate::{Engine, ObjectHandle, TransformState}; +use fparkan_assets::{ + apply_manual_turret_elevation, PreparedComponentControl, PreparedControlTimelineRow, +}; +use fparkan_render::LegacyIron3dEulerTransform; + +/// An autonomous turret's selected direction in its mount's coordinates. +#[derive(Clone, Copy, Debug)] +pub struct TurretAim { + azimuth: f32, + elevation: f32, +} + +impl TurretAim { + pub(super) fn toward([x, y, z]: [f32; 3]) -> Option<Self> { + let horizontal = x.hypot(y); + if !horizontal.is_finite() || !z.is_finite() || horizontal.hypot(z) <= f32::EPSILON { + return None; + } + Some(Self { + azimuth: (-x).atan2(y), + elevation: z.atan2(horizontal), + }) + } +} + +/// Last aim used by the weapon sampler for a live autonomous component. +pub fn autonomous_turret_aim( + engine: &Engine, + handle: ObjectHandle, + component: usize, +) -> Option<TurretAim> { + engine + .autodemo_combat + .as_ref()? + .turret_aim(handle, component) +} + +fn azimuth_row(control: &PreparedComponentControl) -> Option<&PreparedControlTimelineRow> { + let row = control + .typed_records + .iter() + .find(|record| record.tag == 1)? + .values + .first()?; + let row = control.timeline_rows.get(*row as usize)?; + let span = f32::from_bits(row.raw_parameters[3]); + (row.flags & 4 == 0 && span.is_finite() && span > 0.0).then_some(row) +} + +/// Whether a component supplies a usable turret azimuth track. +pub fn has_turret_aim(control: &PreparedComponentControl) -> bool { + azimuth_row(control).is_some() +} + +/// Sample the same tracks for the rendered turret and the CPU muzzle pose. +pub fn apply_autonomous_turret_pose( + control: &PreparedComponentControl, + aim: TurretAim, + node_times: &mut [Option<f32>], +) { + let Some(row) = azimuth_row(control) else { + return; + }; + let blend = row.initial_blend + aim.azimuth / f32::from_bits(row.raw_parameters[3]); + if let Some(time) = node_times.get_mut(row.node_index) { + let mut blend = if row.flags & 1 != 0 { + blend.rem_euclid(1.0) + } else { + blend.clamp(0.0, 1.0) + }; + if row.flags & 2 != 0 { + blend = 1.0 - blend; + } + let sample = (1.0 - blend) * row.frame_a + blend * row.frame_b; + if sample.is_finite() && sample >= 0.0 { + *time = Some(sample); + } + } + apply_manual_turret_elevation(control, aim.elevation, node_times); +} + +pub(super) fn hull_local_point(state: TransformState, target: [f32; 3]) -> Option<[f32; 3]> { + let translation = state.position.map(f32::from_bits); + let matrix = LegacyIron3dEulerTransform { + translation, + orientation_radians: state.orientation.map(f32::from_bits), + } + .try_row_major()?; + let [dx, dy, dz] = std::array::from_fn(|i| target[i] - translation[i]); + let scale = state.scale.map(f32::from_bits); + let point = std::array::from_fn(|i| { + (matrix[i] * dx + matrix[4 + i] * dy + matrix[8 + i] * dz) / scale[i] + }); + point.iter().all(|value| value.is_finite()).then_some(point) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::f32::consts::{FRAC_PI_2, FRAC_PI_4}; + + #[test] + fn target_uses_hull_rotation_and_scale_before_computing_aim() { + let hull = TransformState { + position: [20.0, 30.0, 40.0].map(f32::to_bits), + orientation: [0.0, 0.0, FRAC_PI_2].map(f32::to_bits), + scale: [2.0, 3.0, 4.0].map(f32::to_bits), + }; + let local_target = hull_local_point(hull, [20.0, 32.0, 44.0]).unwrap(); + let aim = TurretAim::toward(local_target).unwrap(); + assert!((aim.azimuth + FRAC_PI_2).abs() < 1e-5); + assert!((aim.elevation - FRAC_PI_4).abs() < 1e-5); + assert!(TurretAim::toward([0.0; 3]).is_none()); + } +} diff --git a/crates/fparkan-runtime/src/unit_combat.rs b/crates/fparkan-runtime/src/unit_combat.rs index ea951314..abf6d8ee 100644 --- a/crates/fparkan-runtime/src/unit_combat.rs +++ b/crates/fparkan-runtime/src/unit_combat.rs @@ -5,6 +5,7 @@ use super::{ player_weapon::prepare_unit_weapons, projectile::{load_projectile, segment_sphere_fraction, unit_sphere}, projectile_terrain_hit, projectile_unit_hit, + turret_aim::{hull_local_point, TurretAim}, unit_patrol::UnitPatrol, weapon_pose::WeaponPoses, Engine, MissionAssets, MissionDocument, MissionObjectDraft, ObjectHandle, PlayerProjectile, @@ -244,6 +245,14 @@ impl AutoDemoCombat { &self.pose_failures } + pub(super) fn turret_aim(&self, handle: ObjectHandle, component: usize) -> Option<TurretAim> { + self.units + .iter() + .find(|unit| unit.handle == handle)? + .poses + .aim(component) + } + pub(super) fn flights(&self) -> impl Iterator<Item = (usize, PlayerProjectile)> + '_ { self.flights .iter() @@ -413,54 +422,61 @@ impl AutoDemoCombat { if unit.weapons.weapons().is_empty() { continue; } - unit.poses.sample( - &mission.mission_assets, - unit.index, - unit.original_id, - now, - &mut self.pose_failures, - ); // shortcut: armed AI units defend their position while their Init is incomplete. let owner = identity_metadata(&engine.world, unit.handle) .ok() .and_then(|identity| identity.owner_id); let guard = owner .is_some_and(|owner| self.guard_clans.get(usize::from(owner.0)) == Some(&true)); - if mission.script_host_mode == super::MissionMode::SingleMission - && !guard - && !mission + let eligible = mission.script_host_mode != super::MissionMode::SingleMission + || guard + || mission .unit_patrol .as_ref() - .is_some_and(|patrol| patrol.is_patrolling(unit.handle)) - { + .is_some_and(|patrol| patrol.is_patrolling(unit.handle)); + let aim = eligible + .then(|| { + targets + .iter() + .find(|(handle, target)| *handle == unit.handle && target.in_range) + .map(|(_, target)| (target.handle, target.center, target.radius)) + .or_else(|| { + let (factory, index) = + mission.unit_patrol.as_ref()?.raid_factory(unit.handle)?; + let target_owner = + identity_metadata(&engine.world, factory).ok()?.owner_id?; + if self + .hostile + .get(usize::from(owner?.0))? + .get(usize::from(target_owner.0)) + != Some(&true) + { + return None; + } + let state = transform_state(&engine.world, unit.handle).ok()?; + let (from, _) = + unit_sphere(&mission.mission_assets, unit.index, state)?; + let target = transform_state(&engine.world, factory).ok()?; + let (to, _) = unit_sphere(&mission.mission_assets, index, target)?; + if (to[0] - from[0]).hypot(to[1] - from[1]) > FIRE_RANGE { + return None; + } + // shortcut: the native attack task's selected building node is unresolved. + Some((factory, to, 0.0)) + }) + }) + .flatten(); + unit.poses.sample( + &mission.mission_assets, + unit.index, + unit.original_id, + now, + aim.and_then(|(_, target, _)| hull_local_point(state, target)), + &mut self.pose_failures, + ); + if !eligible { continue; } - let aim = targets - .iter() - .find(|(handle, target)| *handle == unit.handle && target.in_range) - .map(|(_, target)| (target.handle, target.center, target.radius)) - .or_else(|| { - let (factory, index) = - mission.unit_patrol.as_ref()?.raid_factory(unit.handle)?; - let target_owner = identity_metadata(&engine.world, factory).ok()?.owner_id?; - if self - .hostile - .get(usize::from(owner?.0))? - .get(usize::from(target_owner.0)) - != Some(&true) - { - return None; - } - let state = transform_state(&engine.world, unit.handle).ok()?; - let (from, _) = unit_sphere(&mission.mission_assets, unit.index, state)?; - let target = transform_state(&engine.world, factory).ok()?; - let (to, _) = unit_sphere(&mission.mission_assets, index, target)?; - if (to[0] - from[0]).hypot(to[1] - from[1]) > FIRE_RANGE { - return None; - } - // shortcut: the native attack task's selected building node is unresolved. - Some((factory, to, 0.0)) - }); let mut missing = 0; let mut due_missing = 0; let poses = &unit.poses; @@ -599,6 +615,7 @@ mod tests { ) .unwrap(); let mut observed_shots = 0; + let mut observed_aimed_turret = false; let mut observed_unavailable = engine.autodemo_combat.as_ref().unwrap().unavailable as u64; for now in (0..=120_000).step_by(50) { let frame = frame(&mut engine, now).unwrap(); @@ -636,6 +653,7 @@ mod tests { .find(|unit| unit.handle == flight.shooter) .unwrap(); let state = transform_state(&engine.world, shooter.handle).unwrap(); + observed_aimed_turret |= shooter.poses.has_aim(); let (center, _) = unit_sphere( &engine.loaded.as_ref().unwrap().mission_assets, shooter.index, @@ -670,6 +688,7 @@ mod tests { assert_eq!(total.first_ms, now); assert_eq!(total.count, 1); assert!(observed_shots > 0); + assert!(observed_aimed_turret, "no stock turret tracked its target"); return; } } diff --git a/crates/fparkan-runtime/src/weapon_pose.rs b/crates/fparkan-runtime/src/weapon_pose.rs index 07bd7f29..2df14f27 100644 --- a/crates/fparkan-runtime/src/weapon_pose.rs +++ b/crates/fparkan-runtime/src/weapon_pose.rs @@ -1,6 +1,9 @@ //! CPU poses for mounted weapon CPT points, independent of the renderer. -use crate::{MissionAssets, MissionObjectDraft}; +use crate::{ + turret_aim::{apply_autonomous_turret_pose, has_turret_aim, TurretAim}, + MissionAssets, MissionObjectDraft, +}; use fparkan_animation::{AnimationTime, NodePoseBuffer, Pose}; use fparkan_assets::{ sample_control_node_times, ControlInstanceState, PreparedControlGateProvider, @@ -33,6 +36,7 @@ pub(super) struct WeaponPoses { mounts: Vec<Mount>, states: Vec<ControlInstanceState>, hierarchies: Vec<Option<NodePoseBuffer>>, + aims: Vec<Option<TurretAim>>, } impl WeaponPoses { @@ -64,6 +68,7 @@ impl WeaponPoses { mounts, states: vec![ControlInstanceState::default(); visuals.len()], hierarchies: vec![None; visuals.len()], + aims: vec![None; visuals.len()], } } @@ -73,6 +78,7 @@ impl WeaponPoses { index: usize, object: u32, now: u32, + hull_local_target: Option<[f32; 3]>, report: &mut WeaponPoseReport, ) { for (component, &visual) in assets.visuals_for_object(index).iter().enumerate() { @@ -86,17 +92,21 @@ impl WeaponPoses { .get(index) .and_then(|controls| controls.get(component)) .and_then(Option::as_ref); + let aim = control + .filter(|control| has_turret_aim(control)) + .and_then(|_| self.aim_at(component, hull_local_target?)); + self.aims[component] = aim; let times = control.and_then(|control| { - // Match the renderer's current gate inputs. Native AI aim and - // recoil providers are still outside this pose contract. + // Match the renderer's query gates. Recoil still uses the + // initial Control providers. let gates = control.typed_records.iter().filter(|record| record.tag == 21) .map(|record| match record.gate_provider { PreparedControlGateProvider::Resolved { initial_type1_value, .. } if initial_type1_value.is_finite() => Some(initial_type1_value), _ => None, }).collect::<Vec<_>>(); - match sample_control_node_times(control, now, &gates, &mut self.states[component]) { - Ok(times) => Some(times.into_iter().map(|time| time.map(AnimationTime)).collect()), + let mut times = match sample_control_node_times(control, now, &gates, &mut self.states[component]) { + Ok(times) => times, Err(error) => { let (count, reason) = report.fallbacks.entry((object, component)).or_default(); if *count == 0 { @@ -104,9 +114,14 @@ impl WeaponPoses { *reason = format!("{error:?}"); } *count += 1; - initial_component_node_times(model.validated.node_count, &control.bindings).ok() + initial_component_node_times(model.validated.node_count, &control.bindings).ok()? + .into_iter().map(|time| time.map(|time| time.0)).collect() } + }; + if let Some(aim) = aim { + apply_autonomous_turret_pose(control, aim, &mut times); } + Some(times.into_iter().map(|time| time.map(AnimationTime)).collect()) }); let times = times.or_else(|| { control @@ -120,6 +135,41 @@ impl WeaponPoses { } } + fn aim_at(&self, component: usize, target: [f32; 3]) -> Option<TurretAim> { + let local = match *self.mounts.get(component)? { + Mount::Root => target, + Mount::Unavailable => return None, + Mount::Socket(parent, socket) => { + let to_hull = + |point| mounted_point(&self.hierarchies, &self.mounts, parent, socket, point); + let origin = to_hull([0.0; 3])?; + let project = |axis| { + let end = to_hull(axis)?; + Some( + (0..3) + .map(|i| (end[i] - origin[i]) * (target[i] - origin[i])) + .sum(), + ) + }; + [ + project([1.0, 0.0, 0.0])?, + project([0.0, 1.0, 0.0])?, + project([0.0, 0.0, 1.0])?, + ] + } + }; + TurretAim::toward(local) + } + + pub(super) fn aim(&self, component: usize) -> Option<TurretAim> { + self.aims.get(component).copied().flatten() + } + + #[cfg(test)] + pub(super) fn has_aim(&self) -> bool { + self.aims.iter().any(Option::is_some) + } + pub(super) fn muzzle( &self, state: TransformState, @@ -259,6 +309,7 @@ mod tests { let poses = WeaponPoses { mounts: vec![Mount::Root], states: vec![], + aims: vec![], hierarchies: vec![Some(NodePoseBuffer { poses: vec![Pose::default()], })], diff --git a/docs/appendices/knowledge-boundaries.md b/docs/appendices/knowledge-boundaries.md index 731f4d1f..c0f5366b 100644 --- a/docs/appendices/knowledge-boundaries.md +++ b/docs/appendices/knowledge-boundaries.md @@ -93,6 +93,8 @@ authoring API без динамического подтверждения. Удержание запроса MWalker входит в незавершённый `unit_motion_controller_stub`. `autodemo_combat_approx` отмечает выбор цели, наведение и приближённый урон. Звуки, эффекты боя и боевое уклонение открыты. +Башня сразу принимает углы на центр цели. Скорость приводов, упреждение и +влияние позы ходовой на вычисляемую CPU точку выстрела пока открыты. Счётчики `autodemo_weapon_unavailable` и `autodemo_combat_unavailable` отмечают пропуски подготовки и расчёта попаданий. `unit_combat_unavailable` считает эти пропуски по объекту, поколению и причине; diff --git a/docs/tomes/06-behavior.md b/docs/tomes/06-behavior.md index 53c6dff7..f8726d15 100644 --- a/docs/tomes/06-behavior.md +++ b/docs/tomes/06-behavior.md @@ -2618,9 +2618,14 @@ Simulation читает подготовленный input snapshot. Renderer н переносе `(20, 30, 40)` даёт `(14, 32, 52)`. Проверка рельефа начинается у выбранного ствола, поэтому низкий гребень -перед корпусом не закрывает орудие, установленное выше него. Направление AI -пока вычисляется прямо на центр цели; отдельные приводы наведения и отдача -не восстановлены. Как и оконный рендер, неподдержанную анимацию этот путь +перед корпусом не закрывает орудие, установленное выше него. Цель переводится +в систему координат крепления башни. Две строки CTLD связывают азимут и +возвышение с кадрами MSH. Например, проверенные башни AutoDemo используют +кадры 7–11 для полного оборота и 12–14 для подъёма ствола. Окно и расчёт +точки выстрела используют одинаковые углы наведения. + +Снаряд пока направляется в центр цели по прямой. Скорость приводов и отдача +ещё открыты. Как и оконный рендер, неподдержанную анимацию этот путь заменяет начальной позой Control, но считает такие выборки по объекту и компоненту. Неизвестное крепление пропускает выстрел и попадает в отчёт, вместо пуска из центра корпуса. |
