aboutsummaryrefslogtreecommitdiff
path: root/crates
diff options
context:
space:
mode:
Diffstat (limited to 'crates')
-rw-r--r--crates/fparkan-runtime/src/lib.rs4
-rw-r--r--crates/fparkan-runtime/src/turret_aim.rs118
-rw-r--r--crates/fparkan-runtime/src/unit_combat.rs95
-rw-r--r--crates/fparkan-runtime/src/weapon_pose.rs63
4 files changed, 236 insertions, 44 deletions
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()],
})],