aboutsummaryrefslogtreecommitdiff
path: root/crates/fparkan-runtime
diff options
context:
space:
mode:
Diffstat (limited to 'crates/fparkan-runtime')
-rw-r--r--crates/fparkan-runtime/Cargo.toml4
-rw-r--r--crates/fparkan-runtime/src/lib.rs7
-rw-r--r--crates/fparkan-runtime/src/player_weapon.rs11
-rw-r--r--crates/fparkan-runtime/src/unit_combat.rs192
-rw-r--r--crates/fparkan-runtime/src/weapon_pose.rs338
5 files changed, 519 insertions, 33 deletions
diff --git a/crates/fparkan-runtime/Cargo.toml b/crates/fparkan-runtime/Cargo.toml
index 80e5b78d..cb2dad65 100644
--- a/crates/fparkan-runtime/Cargo.toml
+++ b/crates/fparkan-runtime/Cargo.toml
@@ -6,6 +6,7 @@ license.workspace = true
repository.workspace = true
[dependencies]
+fparkan-animation = { path = "../fparkan-animation" }
fparkan-assets = { path = "../fparkan-assets" }
fparkan-fx = { path = "../fparkan-fx" }
fparkan-msh = { path = "../fparkan-msh" }
@@ -18,6 +19,3 @@ fparkan-resource = { path = "../fparkan-resource" }
fparkan-script = { path = "../fparkan-script" }
fparkan-vfs = { path = "../fparkan-vfs" }
fparkan-world = { path = "../fparkan-world" }
-
-[dev-dependencies]
-fparkan-animation = { path = "../fparkan-animation" }
diff --git a/crates/fparkan-runtime/src/lib.rs b/crates/fparkan-runtime/src/lib.rs
index bb5d496f..917adc2b 100644
--- a/crates/fparkan-runtime/src/lib.rs
+++ b/crates/fparkan-runtime/src/lib.rs
@@ -84,6 +84,8 @@ mod unit_combat;
mod unit_patrol;
mod unit_size_class;
mod unit_spawn;
+mod weapon_pose;
+pub use weapon_pose::{initial_component_node_times, WeaponPoseReport};
pub use autodemo::{autodemo_camera, AutoDemoCamera, AutoDemoReinforcement, AutoDemoView};
pub use boarding::{
@@ -2949,6 +2951,7 @@ pub struct SimulationReport {
pub factory_clock_ticks: Vec<(u16, u32, u64)>,
pub control_resource_ticks: Vec<(u32, u64)>,
pub control_resource_stops: Vec<(u32, u64, String)>,
+ pub weapon_poses: WeaponPoseReport,
/// Approximate clan strength queries, grouped by caller and target clan.
pub script_strength_queries: Vec<(usize, u16, u64)>,
pub script_capture_queries: Vec<(usize, u64)>,
@@ -3025,6 +3028,7 @@ pub fn simulate_mission_report(
factory_clock_ticks: Vec::new(),
control_resource_ticks: Vec::new(),
control_resource_stops: Vec::new(),
+ weapon_poses: WeaponPoseReport::default(),
script_strength_queries: Vec::new(),
script_capture_queries: Vec::new(),
script_attack_queries: Vec::new(),
@@ -3144,6 +3148,9 @@ pub fn simulate_mission_report(
if let Some(production) = &engine.production {
report.factory_clock_ticks.extend(production.clock_ticks());
}
+ if let Some(combat) = &engine.autodemo_combat {
+ report.weapon_poses = combat.pose_report().clone();
+ }
for problem in loaded.clan_ai_events.pending_problems() {
*report
.clan_problem_dispatch_stubs
diff --git a/crates/fparkan-runtime/src/player_weapon.rs b/crates/fparkan-runtime/src/player_weapon.rs
index ce92b053..763ba585 100644
--- a/crates/fparkan-runtime/src/player_weapon.rs
+++ b/crates/fparkan-runtime/src/player_weapon.rs
@@ -71,6 +71,14 @@ impl PlayerWeapons {
trigger: bool,
clock_ms: u32,
) -> impl Iterator<Item = (usize, &PlayerWeapon, &PreparedControlPoint)> {
+ self.fire_where(clock_ms, move |_, _| trigger)
+ }
+
+ pub(super) fn fire_where(
+ &mut self,
+ clock_ms: u32,
+ mut trigger: impl FnMut(&PlayerWeapon, &PreparedControlPoint) -> bool,
+ ) -> impl Iterator<Item = (usize, &PlayerWeapon, &PreparedControlPoint)> {
if let Some(last) = self.last_sample_ms.replace(clock_ms) {
self.clock_ms += f64::from(clock_ms.wrapping_sub(last));
}
@@ -80,7 +88,8 @@ impl PlayerWeapons {
.iter_mut()
.enumerate()
.filter_map(move |(index, weapon)| {
- let start = trigger && selected.is_none_or(|selected| selected == index);
+ let start = selected.is_none_or(|selected| selected == index)
+ && trigger(weapon, &weapon.barrels[weapon.barrel_index].muzzle);
let barrel = weapon.sample_fire(start, now)?;
Some((index, &*weapon, &weapon.barrels[barrel].muzzle))
})
diff --git a/crates/fparkan-runtime/src/unit_combat.rs b/crates/fparkan-runtime/src/unit_combat.rs
index 223c3d76..57ce5ef8 100644
--- a/crates/fparkan-runtime/src/unit_combat.rs
+++ b/crates/fparkan-runtime/src/unit_combat.rs
@@ -5,6 +5,7 @@ use super::{
projectile::{load_projectile, segment_sphere_fraction, unit_sphere},
projectile_terrain_hit, projectile_unit_hit,
unit_patrol::UnitPatrol,
+ weapon_pose::WeaponPoses,
Engine, MissionAssets, MissionDocument, MissionObjectDraft, ObjectHandle, PlayerProjectile,
PlayerWeapons,
};
@@ -68,6 +69,7 @@ pub(super) struct AutoDemoCombat {
guard_clans: Vec<bool>,
projectiles: Vec<AutoDemoProjectileType>,
flights: Vec<Flight>,
+ pose_failures: super::WeaponPoseReport,
pub(super) unavailable: usize,
}
@@ -83,8 +85,10 @@ pub(super) struct CombatTarget {
struct Unit {
handle: ObjectHandle,
index: usize,
+ original_id: u32,
weapons: PlayerWeapons,
slots: Vec<Option<usize>>,
+ poses: WeaponPoses,
}
struct Flight {
@@ -126,6 +130,7 @@ impl AutoDemoCombat {
guard_clans,
projectiles: Vec::new(),
flights: Vec::new(),
+ pose_failures: super::WeaponPoseReport::default(),
unavailable: 0,
};
for (index, (draft, &handle)) in drafts.iter().zip(handles).enumerate() {
@@ -187,6 +192,8 @@ impl AutoDemoCombat {
index,
weapons,
slots,
+ poses: WeaponPoses::new(draft, assets, index),
+ original_id: draft.original_id.map_or(handle.slot, |id| id.0),
});
}
battle
@@ -203,6 +210,10 @@ impl AutoDemoCombat {
if let Some(template) = self.reserve.iter().find(|unit| unit.index == index) {
self.units.push(Unit {
handle,
+ original_id: identity_metadata(world, handle)
+ .ok()
+ .and_then(|identity| identity.original_id)
+ .map_or(handle.slot, |id| id.0),
..template.clone()
});
}
@@ -216,6 +227,10 @@ impl AutoDemoCombat {
self.guard_clans.iter().filter(|&&enabled| enabled).count()
}
+ pub(super) fn pose_report(&self) -> &super::WeaponPoseReport {
+ &self.pose_failures
+ }
+
pub(super) fn flights(&self) -> impl Iterator<Item = (usize, PlayerProjectile)> + '_ {
self.flights
.iter()
@@ -355,6 +370,19 @@ impl AutoDemoCombat {
mission.unit_patrol.as_ref(),
);
for unit in &mut self.units {
+ let Ok(state) = transform_state(&engine.world, unit.handle) else {
+ continue;
+ };
+ 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()
@@ -373,26 +401,7 @@ impl AutoDemoCombat {
let aim = targets
.iter()
.find(|(handle, target)| *handle == unit.handle && target.in_range)
- .and_then(|(_, target)| {
- let state = transform_state(&engine.world, unit.handle).ok()?;
- let (from, _) = unit_sphere(&mission.mission_assets, unit.index, state)?;
- match projectile_terrain_hit(&mission.terrain, [from, target.center]) {
- Ok(ground) => {
- // shortcut: use the same hull sphere as the projectile until per-node aiming is wired.
- segment_sphere_fraction(
- [from, target.center],
- target.center,
- target.radius,
- )
- .filter(|&contact| ground.is_none_or(|ground| contact < ground))
- .map(|_| (target.handle, from, target.center))
- }
- Err(_) => {
- unavailable += 1;
- None
- }
- }
- })
+ .map(|(_, target)| (target.handle, target.center, target.radius))
.or_else(|| {
let (factory, index) =
mission.unit_patrol.as_ref()?.raid_factory(unit.handle)?;
@@ -412,17 +421,42 @@ impl AutoDemoCombat {
if (to[0] - from[0]).hypot(to[1] - from[1]) > FIRE_RANGE {
return None;
}
- // shortcut: aim at the root bounds center until the native attack task selects a node.
- projectile_terrain_hit(&mission.terrain, [from, to])
- .is_ok_and(|ground| ground.is_none())
- .then_some((factory, from, to))
+ // shortcut: the native attack task's selected building node is unresolved.
+ Some((factory, to, 0.0))
});
- for (slot, _, _) in unit.weapons.fire(aim.is_some(), now) {
- let (Some((target, from, to)), Some(projectile)) = (aim, unit.slots[slot]) else {
+ let mut missing = 0;
+ let mut due_missing = 0;
+ let poses = &unit.poses;
+ let clear = |from, to, radius| {
+ projectile_terrain_hit(&mission.terrain, [from, to]).is_ok_and(|ground| {
+ if radius == 0.0 {
+ return ground.is_none();
+ }
+ segment_sphere_fraction([from, to], to, radius)
+ .is_some_and(|contact| ground.is_none_or(|ground| contact < ground))
+ })
+ };
+ for (slot, weapon, barrel) in unit.weapons.fire_where(now, |weapon, barrel| {
+ let Some((_, to, radius)) = aim else {
+ return false;
+ };
+ let Some(from) = poses.muzzle(state, weapon.component_index, barrel) else {
+ missing += 1;
+ return false;
+ };
+ clear(from, to, radius)
+ }) {
+ let (Some((target, to, radius)), Some(projectile)) = (aim, unit.slots[slot]) else {
continue;
};
+ let Some(from) = poses.muzzle(state, weapon.component_index, barrel) else {
+ due_missing += 1;
+ continue;
+ };
+ if !clear(from, to, radius) {
+ continue;
+ }
let data = &self.projectiles[projectile];
- // shortcut: aim from the root hull center until animated AI barrel poses are sampled.
let direction = std::array::from_fn(|axis| to[axis] - from[axis]);
if let Some(pose) =
PlayerProjectile::new(from, direction, data.speed, data.lifetime_ms, now)
@@ -439,6 +473,22 @@ impl AutoDemoCombat {
});
}
}
+ missing += due_missing;
+ if missing > 0 {
+ let count = self
+ .pose_failures
+ .missing
+ .entry(unit.original_id)
+ .or_default();
+ if *count == 0 {
+ eprintln!(
+ "unit_weapon_pose_stub object={} count={missing}",
+ unit.original_id
+ );
+ }
+ *count += missing;
+ unavailable += missing as usize;
+ }
}
(events, unavailable)
}
@@ -478,6 +528,64 @@ mod tests {
#[test]
#[ignore = "requires licensed corpus"]
+ fn licensed_autodemo_shots_start_outside_the_hull_center() {
+ 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/Autodemo.00/data.tma".into(),
+ mode: MissionMode::AutoDemo,
+ },
+ MissionStartupInput {
+ queue_time_ms: 0,
+ research_creation_gate: false,
+ },
+ None,
+ )
+ .unwrap();
+ for now in (0..=120_000).step_by(50) {
+ let frame = frame(&mut engine, now).unwrap();
+ let shots = frame
+ .autodemo_combat_events
+ .iter()
+ .filter(|event| matches!(event, AutoDemoCombatEvent::Shot { .. }))
+ .count();
+ if shots == 0 {
+ continue;
+ }
+ let combat = engine.autodemo_combat.as_ref().unwrap();
+ assert!(combat.flights.len() >= shots);
+ for flight in combat.flights.iter().rev().take(shots) {
+ let shooter = combat
+ .units
+ .iter()
+ .find(|unit| unit.handle == flight.shooter)
+ .unwrap();
+ let state = transform_state(&engine.world, shooter.handle).unwrap();
+ let (center, _) = unit_sphere(
+ &engine.loaded.as_ref().unwrap().mission_assets,
+ shooter.index,
+ state,
+ )
+ .unwrap();
+ let separation: f32 = flight
+ .pose
+ .position
+ .into_iter()
+ .zip(center)
+ .map(|(a, b)| (a - b) * (a - b))
+ .sum();
+ assert!(separation > 0.01, "projectile still starts at hull center");
+ }
+ assert!(combat.pose_report().missing.is_empty());
+ return;
+ }
+ panic!("stock AutoDemo did not fire");
+ }
+
+ #[test]
+ #[ignore = "requires licensed corpus"]
fn licensed_stock_clan_uses_script_orders_without_a_startup_raid() {
let mut engine = stock_two_fortresses();
assert_eq!(mission_guard_fallback_count(&engine), 0);
@@ -491,9 +599,33 @@ mod tests {
frame(&mut engine, 0).unwrap();
assert_eq!(transform_state(&engine.world, waiting).unwrap(), before);
let mut produced = false;
+ let mut scripted_patrol_seen = false;
for now in (100..=90_000).step_by(100) {
let result = frame(&mut engine, now).unwrap();
produced |= result.produced_unit.is_some_and(|unit| unit.clan == 1);
+ scripted_patrol_seen |=
+ engine
+ .autodemo_combat
+ .as_ref()
+ .unwrap()
+ .units
+ .iter()
+ .any(|unit| {
+ if identity_metadata(&engine.world, unit.handle)
+ .ok()
+ .and_then(|identity| identity.owner_id)
+ != Some(OwnerId(1))
+ {
+ return false;
+ }
+ engine
+ .loaded
+ .as_ref()
+ .unwrap()
+ .unit_patrol
+ .as_ref()
+ .is_some_and(|patrol| patrol.is_patrolling(unit.handle))
+ });
}
let loaded = engine.loaded.as_ref().unwrap();
assert!(loaded.clan_ai_events.stops().next().is_none());
@@ -501,8 +633,10 @@ mod tests {
.clan_ai_events
.group_orders()
.any(|(clan, _, count)| clan == 1 && count > 0));
- assert!(loaded.unit_patrol.as_ref().is_some_and(|patrol| patrol
- .is_patrolling(mission_object_handle(&engine, OriginalObjectId(14)).unwrap())));
+ assert!(
+ scripted_patrol_seen,
+ "AI clan never received a scripted patrol"
+ );
assert!(produced, "scripted AI factory did not produce a robot");
}
diff --git a/crates/fparkan-runtime/src/weapon_pose.rs b/crates/fparkan-runtime/src/weapon_pose.rs
new file mode 100644
index 00000000..07bd7f29
--- /dev/null
+++ b/crates/fparkan-runtime/src/weapon_pose.rs
@@ -0,0 +1,338 @@
+//! CPU poses for mounted weapon CPT points, independent of the renderer.
+
+use crate::{MissionAssets, MissionObjectDraft};
+use fparkan_animation::{AnimationTime, NodePoseBuffer, Pose};
+use fparkan_assets::{
+ sample_control_node_times, ControlInstanceState, PreparedControlGateProvider,
+ PreparedControlNodeBinding, PreparedControlPoint,
+};
+use fparkan_msh::{node38_fallback_hierarchy, node38_sampled_hierarchy_at_times};
+use fparkan_prototype::{unit_component_tree, PROTOTYPE_TYPE_EXTO};
+use fparkan_render::LegacyIron3dEulerTransform;
+use fparkan_world::TransformState;
+use std::collections::BTreeMap;
+
+/// Unresolved autonomous weapon poses, grouped by mission object and component.
+#[derive(Clone, Debug, Default, Eq, PartialEq)]
+pub struct WeaponPoseReport {
+ /// Samples using authored initial bindings because a live Control track is unsupported.
+ pub fallbacks: BTreeMap<(u32, usize), (u64, String)>,
+ /// Trigger samples or due shots without a resolvable CPT mount chain.
+ pub missing: BTreeMap<u32, u64>,
+}
+
+#[derive(Clone, Copy)]
+enum Mount {
+ Root,
+ Socket(usize, usize),
+ Unavailable,
+}
+
+#[derive(Clone)]
+pub(super) struct WeaponPoses {
+ mounts: Vec<Mount>,
+ states: Vec<ControlInstanceState>,
+ hierarchies: Vec<Option<NodePoseBuffer>>,
+}
+
+impl WeaponPoses {
+ pub(super) fn new(draft: &MissionObjectDraft, assets: &MissionAssets, index: usize) -> Self {
+ let visuals = assets.visuals_for_object(index);
+ let tree = unit_component_tree(&draft.unit_components).ok();
+ let visible = |component| {
+ component == 0
+ || visuals
+ .get(component)
+ .and_then(|&id| assets.visual_by_id(id))
+ .is_some_and(|visual| visual.source_type == Some(PROTOTYPE_TYPE_EXTO))
+ };
+ let mounts = (0..visuals.len())
+ .map(|component| {
+ if draft.unit_components.is_empty() || component == 0 {
+ return Mount::Root;
+ }
+ let socket = || {
+ let parent = tree.as_ref()?.get(component)?.parent_index?;
+ let socket =
+ usize::try_from(draft.unit_components[component].parent_or_link).ok()?;
+ (visible(component) && visible(parent)).then_some(Mount::Socket(parent, socket))
+ };
+ socket().unwrap_or(Mount::Unavailable)
+ })
+ .collect();
+ Self {
+ mounts,
+ states: vec![ControlInstanceState::default(); visuals.len()],
+ hierarchies: vec![None; visuals.len()],
+ }
+ }
+
+ pub(super) fn sample(
+ &mut self,
+ assets: &MissionAssets,
+ index: usize,
+ object: u32,
+ now: u32,
+ report: &mut WeaponPoseReport,
+ ) {
+ for (component, &visual) in assets.visuals_for_object(index).iter().enumerate() {
+ let model = assets
+ .visual_by_id(visual)
+ .and_then(|visual| visual.model_id)
+ .and_then(|id| assets.model_by_id(id));
+ let Some(model) = model else { continue };
+ let control = assets
+ .object_component_controls
+ .get(index)
+ .and_then(|controls| controls.get(component))
+ .and_then(Option::as_ref);
+ 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.
+ 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()),
+ Err(error) => {
+ let (count, reason) = report.fallbacks.entry((object, component)).or_default();
+ if *count == 0 {
+ eprintln!("unit_weapon_pose_fallback object={object} component={component} reason={error:?}");
+ *reason = format!("{error:?}");
+ }
+ *count += 1;
+ initial_component_node_times(model.validated.node_count, &control.bindings).ok()
+ }
+ }
+ });
+ let times = times.or_else(|| {
+ control
+ .is_none()
+ .then(|| vec![Some(AnimationTime(0.0)); model.validated.node_count])
+ });
+ self.hierarchies[component] = times
+ .as_ref()
+ .and_then(|times| node38_sampled_hierarchy_at_times(&model.validated, times))
+ .or_else(|| node38_fallback_hierarchy(&model.validated));
+ }
+ }
+
+ pub(super) fn muzzle(
+ &self,
+ state: TransformState,
+ component: usize,
+ barrel: &PreparedControlPoint,
+ ) -> Option<[f32; 3]> {
+ let node = usize::try_from(barrel.raw_signed_field_04).ok()?;
+ let point = mounted_point(
+ &self.hierarchies,
+ &self.mounts,
+ component,
+ node,
+ barrel.position,
+ )?;
+ LegacyIron3dEulerTransform {
+ translation: state.position.map(f32::from_bits),
+ orientation_radians: state.orientation.map(f32::from_bits),
+ }
+ .try_transform_scaled_point(point, state.scale.map(f32::from_bits))
+ }
+}
+
+fn mounted_point(
+ hierarchies: &[Option<NodePoseBuffer>],
+ mounts: &[Mount],
+ mut component: usize,
+ mut node: usize,
+ mut point: [f32; 3],
+) -> Option<[f32; 3]> {
+ // Components are a preorder tree, but bound traversal also rejects a bad cycle.
+ for _ in 0..mounts.len() {
+ let hierarchy = hierarchies.get(component)?.as_ref();
+ let pose = match hierarchy {
+ Some(hierarchy) => *hierarchy.poses.get(node)?,
+ None if node == 0 => Pose::default(),
+ None => return None,
+ };
+ point = pose.transform_point(point);
+ match *mounts.get(component)? {
+ Mount::Root => return Some(point),
+ Mount::Unavailable => return None,
+ Mount::Socket(parent, socket) => {
+ if let Some(root) = hierarchy.and_then(|hierarchy| hierarchy.poses.first()) {
+ let [x, y, z, w] = root.rotation;
+ let length_squared = x * x + y * y + z * z + w * w;
+ let rotation = if length_squared.is_finite() && length_squared > f32::EPSILON {
+ [
+ -x / length_squared,
+ -y / length_squared,
+ -z / length_squared,
+ w / length_squared,
+ ]
+ } else {
+ Pose::default().rotation
+ };
+ point = Pose {
+ translation: [0.0; 3],
+ rotation,
+ }
+ .transform_point(std::array::from_fn(|axis| {
+ point[axis] - root.translation[axis]
+ }));
+ }
+ component = parent;
+ node = socket;
+ }
+ }
+ }
+ None
+}
+
+/// Samples the authored initial Control bindings in source order.
+pub fn initial_component_node_times(
+ node_count: usize,
+ bindings: &[PreparedControlNodeBinding],
+) -> Result<Vec<Option<AnimationTime>>, String> {
+ let mut node_times = vec![Some(AnimationTime(0.0)); node_count];
+ for binding in bindings {
+ // Disabled rows are filtered while loading CTLD, but preserve the
+ // native guard here in case a caller constructs MissionAssets itself.
+ if binding.flags & 4 != 0 {
+ continue;
+ }
+ if binding.node_index >= node_count {
+ return Err(format!(
+ "control binding node {} is outside model node count {node_count}",
+ binding.node_index
+ ));
+ }
+ if !binding.frame_a.is_finite()
+ || !binding.frame_b.is_finite()
+ || !binding.initial_blend.is_finite()
+ || binding.frame_a < 0.0
+ || binding.frame_b < 0.0
+ {
+ return Err(format!(
+ "control binding for node {} contains an invalid frame or blend",
+ binding.node_index
+ ));
+ }
+
+ let mut blend = binding.initial_blend;
+ if binding.flags & 1 != 0 {
+ if blend > 1.0 {
+ blend -= 1.0;
+ }
+ if blend < 0.0 {
+ blend += 1.0;
+ }
+ } else {
+ blend = blend.clamp(0.0, 1.0);
+ }
+ if binding.flags & 2 != 0 {
+ blend = 1.0 - blend;
+ }
+ let sample_time = (1.0 - blend) * binding.frame_a + blend * binding.frame_b;
+ if !sample_time.is_finite() || sample_time < 0.0 {
+ return Err(format!(
+ "control binding for node {} produced a negative or non-finite sample time unsupported by the static sampler",
+ binding.node_index
+ ));
+ }
+ // Source order is significant: native initialization writes each
+ // enabled row in turn, so a later row for the same node wins.
+ node_times[binding.node_index] = Some(AnimationTime(sample_time));
+ }
+ Ok(node_times)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn cpt_scale_and_world_transform_match_control_dll_query() {
+ // GOG Control.dll RVA 0x1b4f0, native execution with a supplied node matrix.
+ let poses = WeaponPoses {
+ mounts: vec![Mount::Root],
+ states: vec![],
+ hierarchies: vec![Some(NodePoseBuffer {
+ poses: vec![Pose::default()],
+ })],
+ };
+ let state = TransformState {
+ position: [20.0_f32, 30.0, 40.0].map(f32::to_bits),
+ orientation: [0.0_f32, 0.0, std::f32::consts::FRAC_PI_2].map(f32::to_bits),
+ scale: [2.0_f32, 3.0, 4.0].map(f32::to_bits),
+ };
+ let barrel = PreparedControlPoint {
+ raw_flags: 0,
+ raw_signed_field_04: 0,
+ raw_signed_field_08: 0,
+ position: [1.0, 2.0, 3.0],
+ direction: [0.0, 1.0, 0.0],
+ name: [0; 32],
+ };
+ let actual = poses.muzzle(state, 0, &barrel).unwrap();
+ for (actual, expected) in actual.into_iter().zip([14.0, 32.0, 52.0]) {
+ assert!((actual - expected).abs() < 0.00001);
+ }
+ }
+
+ #[test]
+ fn mounted_muzzle_replaces_child_roots_and_follows_rotated_parent_socket() {
+ let quarter_turn = [
+ 0.0,
+ 0.0,
+ std::f32::consts::FRAC_1_SQRT_2,
+ std::f32::consts::FRAC_1_SQRT_2,
+ ];
+ let translated = |translation| Pose {
+ translation,
+ ..Pose::default()
+ };
+ let poses = [
+ Some(NodePoseBuffer {
+ poses: vec![
+ Pose::default(),
+ Pose {
+ translation: [10.0, 0.0, 0.0],
+ rotation: quarter_turn,
+ },
+ ],
+ }),
+ Some(NodePoseBuffer {
+ poses: vec![
+ Pose {
+ translation: [100.0, 0.0, 0.0],
+ rotation: quarter_turn,
+ },
+ Pose {
+ translation: [96.0, 0.0, 0.0],
+ rotation: quarter_turn,
+ },
+ ],
+ }),
+ Some(NodePoseBuffer {
+ poses: vec![translated([0.0, 200.0, 0.0]), translated([0.0, 200.0, 3.0])],
+ }),
+ ];
+ let mounts = [Mount::Root, Mount::Socket(0, 1), Mount::Socket(1, 1)];
+ let point = mounted_point(&poses, &mounts, 2, 1, [0.0, 2.0, 0.0]).unwrap();
+ for (actual, expected) in point.into_iter().zip([4.0, 0.0, 3.0]) {
+ assert!((actual - expected).abs() < 0.00001, "{point:?}");
+ }
+ assert!(mounted_point(&poses, &mounts, 2, 9, [0.0; 3]).is_none());
+ assert!(mounted_point(
+ &poses,
+ &[Mount::Root, Mount::Unavailable, mounts[2]],
+ 2,
+ 1,
+ [0.0; 3]
+ )
+ .is_none());
+ }
+}