aboutsummaryrefslogtreecommitdiff
path: root/crates/fparkan-runtime
diff options
context:
space:
mode:
authorValentin Popov <valentin@popov.link>2026-12-01 07:55:10 +0300
committerValentin Popov <valentin@popov.link>2026-12-01 07:55:10 +0300
commit79635316902c69a363f1d1a9ebef110d94190356 (patch)
tree806e345cc9d5553cea330483b828cb080bd22061 /crates/fparkan-runtime
parent777f48345c7faf891ac105fc4a831114914aff5d (diff)
downloadfparkan-79635316902c69a363f1d1a9ebef110d94190356.tar.xz
fparkan-79635316902c69a363f1d1a9ebef110d94190356.zip
fix(combat): let projectiles destroy mounted warbot parts
Resolve mounted model triangles through the sampled socket chain and publish the damage to the assembled Control provider. Remove the damaged geometry, stop weapons whose provider was depleted, and preserve already separated ranges when the chassis later dies. Confirmed with a licensed AutoDemo ray query and two frames around a controlled hit in the Vulkan window.
Diffstat (limited to 'crates/fparkan-runtime')
-rw-r--r--crates/fparkan-runtime/src/destruction.rs33
-rw-r--r--crates/fparkan-runtime/src/lib.rs2
-rw-r--r--crates/fparkan-runtime/src/mobile_budget.rs36
-rw-r--r--crates/fparkan-runtime/src/player_weapon.rs12
-rw-r--r--crates/fparkan-runtime/src/projectile.rs130
-rw-r--r--crates/fparkan-runtime/src/projectile_parts.rs148
-rw-r--r--crates/fparkan-runtime/src/unit_combat.rs27
-rw-r--r--crates/fparkan-runtime/src/weapon_pose.rs27
8 files changed, 369 insertions, 46 deletions
diff --git a/crates/fparkan-runtime/src/destruction.rs b/crates/fparkan-runtime/src/destruction.rs
index aa02197b..c19e7ed5 100644
--- a/crates/fparkan-runtime/src/destruction.rs
+++ b/crates/fparkan-runtime/src/destruction.rs
@@ -25,12 +25,16 @@ pub enum DestroyedMesh {
Mounted {
/// Prepared actor index.
object_index: usize,
+ /// Component and node indices of pieces already separated before the chassis failed.
+ depleted_nodes: Vec<(usize, usize)>,
},
- /// One separated node of a still live chassis.
+ /// One separated node of a still live warbot.
ChassisNode {
/// Prepared actor index.
object_index: usize,
- /// Local node of the root model.
+ /// Unit DAT component containing the mesh.
+ component_index: usize,
+ /// Local node of that model.
node: usize,
/// World position of the hull at impact.
hull_origin: [f32; 3],
@@ -86,7 +90,7 @@ pub fn unit_destruction_effect_sources(
Some(if class & UNIT_DAT_CONTROL_CLASS_HIGH_BIT != 0 {
rows.as_slice()
} else if class == super::boarding::WARBOT_CLASS {
- &rows[..rows.partition_point(|row| row.unit_component_index == 0)]
+ rows.as_slice()
} else if class & MOBILE_UNIT != 0 {
rows.get(..1).unwrap_or_default()
} else {
@@ -104,7 +108,7 @@ pub(super) fn part_effect(
) -> Option<UnitDestructionEffect> {
let (archive, name) = node_effect(row)?;
let mesh = match contact.node {
- Some(super::ProjectileNode::Chassis(node))
+ Some(super::ProjectileNode::Chassis(_) | super::ProjectileNode::Mounted(_))
if row.current_flags.is_some_and(|flags| flags & 2 == 0) =>
{
let id = identity_metadata(&engine.world, contact.handle)
@@ -113,7 +117,8 @@ pub(super) fn part_effect(
let hull = transform_state(&engine.world, contact.handle).ok()?;
Some(DestroyedMesh::ChassisNode {
object_index: id.0 as usize,
- node: node as usize,
+ component_index: row.unit_component_index,
+ node: row.source_row_index,
hull_origin: hull.position.map(f32::from_bits),
})
}
@@ -152,7 +157,23 @@ pub(super) fn pending_effect(
.position
.map(f32::from_bits);
Some(UnitDestructionEffect {
- mesh: object_index.map(|object_index| DestroyedMesh::Mounted { object_index }),
+ mesh: object_index.map(|object_index| {
+ let depleted_nodes = match &table.node_provider_status {
+ MissionControlNodeProviderTableStatus::Available(rows) => rows
+ .iter()
+ .filter(|row| {
+ row.unit_component_index != 0
+ && row.current_flags.is_some_and(|flags| flags & 0x12 == 0x10)
+ })
+ .map(|row| (row.unit_component_index, row.source_row_index))
+ .collect(),
+ MissionControlNodeProviderTableStatus::Unavailable(_) => Vec::new(),
+ };
+ DestroyedMesh::Mounted {
+ object_index,
+ depleted_nodes,
+ }
+ }),
position,
archive,
name,
diff --git a/crates/fparkan-runtime/src/lib.rs b/crates/fparkan-runtime/src/lib.rs
index 0ac5197f..1a46e031 100644
--- a/crates/fparkan-runtime/src/lib.rs
+++ b/crates/fparkan-runtime/src/lib.rs
@@ -190,7 +190,7 @@ pub use projectile::{
load_player_projectile, projectile_terrain_hit, projectile_unit_hit, PlayerProjectile,
ProjectileAssets, ProjectileContact, ProjectileImpact, ProjectileNode,
};
-pub use projectile_parts::depleted_chassis_nodes;
+pub use projectile_parts::{depleted_chassis_nodes, depleted_warbot_nodes};
pub use research::order_lab_research;
pub use robot_designer::{load_gameplay_mission, load_gameplay_mission_with_build_parts};
pub use unit_combat::{AutoDemoCombatEvent, AutoDemoProjectileType, FiringEffectInstance};
diff --git a/crates/fparkan-runtime/src/mobile_budget.rs b/crates/fparkan-runtime/src/mobile_budget.rs
index 06dc251e..1df2ab80 100644
--- a/crates/fparkan-runtime/src/mobile_budget.rs
+++ b/crates/fparkan-runtime/src/mobile_budget.rs
@@ -267,21 +267,24 @@ pub(super) fn read(
_ => None,
});
for weapon in weapons {
- weapon.charge = if mission.control_resources.energy_available(handle) {
- devices
- .and_then(|devices| devices.iter().find(|device| matches_weapon(device, weapon)))
- .and_then(|device| {
- let coefficients = device.coefficient_bits?;
- let charge = Charge {
- capacity: f32::from_bits(coefficients[1]),
- cost: f32::from_bits(coefficients[2]),
- amount: f32::from_bits(device.weapon_charge_bits?),
- };
- [charge.capacity, charge.cost, charge.amount]
- .into_iter()
- .all(|value| value.is_finite() && !value.is_subnormal())
- .then_some(charge)
- })
+ let device = devices
+ .and_then(|devices| devices.iter().find(|device| matches_weapon(device, weapon)));
+ weapon.destroyed = device
+ .and_then(|device| crate::control_node_provider_row(table?, device.key).ok())
+ .is_some_and(|row| row.current_flags.is_some_and(|flags| flags & 0x10 != 0));
+ weapon.charge = if !weapon.destroyed && mission.control_resources.energy_available(handle) {
+ device.and_then(|device| {
+ let coefficients = device.coefficient_bits?;
+ let charge = Charge {
+ capacity: f32::from_bits(coefficients[1]),
+ cost: f32::from_bits(coefficients[2]),
+ amount: f32::from_bits(device.weapon_charge_bits?),
+ };
+ [charge.capacity, charge.cost, charge.amount]
+ .into_iter()
+ .all(|value| value.is_finite() && !value.is_subnormal())
+ .then_some(charge)
+ })
} else {
None
};
@@ -332,6 +335,9 @@ pub(super) fn publish(
}
for weapon in weapons {
weapon.energy_waits = 0;
+ if weapon.destroyed {
+ continue;
+ }
let Some(charge) = &weapon.charge else {
if available {
mission.control_resources.mobile.stub(
diff --git a/crates/fparkan-runtime/src/player_weapon.rs b/crates/fparkan-runtime/src/player_weapon.rs
index db24036b..0fe233ac 100644
--- a/crates/fparkan-runtime/src/player_weapon.rs
+++ b/crates/fparkan-runtime/src/player_weapon.rs
@@ -20,6 +20,7 @@ pub struct PlayerWeapon {
pub component_index: usize,
pub(super) control_record_index: usize,
pub(super) charge: Option<crate::mobile_budget::Charge>,
+ pub(super) destroyed: bool,
pub(super) energy_waits: u64,
pub(super) autonomous_fire_distance: f32,
/// Name of the projectile prototype.
@@ -172,6 +173,11 @@ impl PlayerWeapons {
.iter_mut()
.enumerate()
.filter_map(move |(index, weapon)| {
+ if weapon.destroyed {
+ weapon.phase = FirePhase::Idle;
+ weapon.windup_started = false;
+ return None;
+ }
let selected = selected.is_none_or(|selected| selected == index);
let mut start =
selected && trigger(index, weapon, &weapon.barrels[weapon.barrel_index].muzzle);
@@ -467,6 +473,7 @@ fn prepare_weapons(
component_index,
control_record_index,
charge: None,
+ destroyed: false,
energy_waits: 0,
autonomous_fire_distance: f32::from_bits(record.fixed_words[19]),
projectile,
@@ -736,6 +743,7 @@ mod tests {
component_index: 0,
control_record_index: 0,
charge: None,
+ destroyed: false,
energy_waits: 0,
autonomous_fire_distance: 0.0,
projectile: String::from("test"),
@@ -785,6 +793,10 @@ mod tests {
});
let mut node_times = [None];
assert!(weapons.fire(true, 0).next().is_none());
+ let mut interrupted = weapons.clone();
+ interrupted.weapons[0].destroyed = true;
+ assert!(interrupted.fire(true, 11).next().is_none());
+ assert!(interrupted.started_windup_sounds(7).next().is_none());
assert_eq!(
weapons.started_windup_sounds(7).collect::<Vec<_>>(),
[FiringEffectInstance {
diff --git a/crates/fparkan-runtime/src/projectile.rs b/crates/fparkan-runtime/src/projectile.rs
index 5359fc42..b5da26b8 100644
--- a/crates/fparkan-runtime/src/projectile.rs
+++ b/crates/fparkan-runtime/src/projectile.rs
@@ -194,6 +194,8 @@ pub enum ProjectileNode {
Building(u32),
/// A node of the warbot's chassis model.
Chassis(u32),
+ /// A provider index in the assembled warbot's global Control table.
+ Mounted(u32),
/// An indestructible communicator field.
CaptureBarrier,
}
@@ -215,6 +217,17 @@ pub fn projectile_unit_hit(
shooter: ObjectHandle,
segment: [[f32; 3]; 2],
) -> Option<ProjectileContact> {
+ projectile_unit_hit_with_poses(engine, shooter, segment, |index| {
+ engine.autodemo_combat.as_ref()?.poses_for_collision(index)
+ })
+}
+
+pub(super) fn projectile_unit_hit_with_poses<'a>(
+ engine: &Engine,
+ shooter: ObjectHandle,
+ segment: [[f32; 3]; 2],
+ poses: impl Fn(usize) -> Option<&'a super::weapon_pose::WeaponPoses>,
+) -> Option<ProjectileContact> {
let mission = engine.loaded.as_ref()?;
let passenger = mission.boarding.map(|boarding| boarding.hero.handle);
mission
@@ -234,8 +247,9 @@ pub fn projectile_unit_hit(
}
let state = transform_state(&engine.world, handle).ok()?;
let (center, radius) = unit_sphere(&mission.mission_assets, index, state)?;
- let sphere_fraction = segment_sphere_fraction(segment, center, radius)?;
+ let sphere_fraction = segment_sphere_fraction(segment, center, radius);
let (fraction, node) = if building {
+ sphere_fraction?;
let (fraction, node) = crate::capture_barrier::projectile_contact(
mission, index, handle, state, segment,
)?;
@@ -249,9 +263,10 @@ pub fn projectile_unit_hit(
segment,
(center, radius),
sphere_fraction,
+ poses(index),
)?
} else {
- (sphere_fraction, None)
+ (sphere_fraction?, None)
};
Some(ProjectileContact {
handle,
@@ -319,7 +334,11 @@ pub fn apply_projectile_impact(
let key = match contact.node {
Some(ProjectileNode::CaptureBarrier) => return Ok(ProjectileImpact::Unresolved),
None | Some(ProjectileNode::Chassis(0)) => None,
- Some(ProjectileNode::Chassis(key) | ProjectileNode::Building(key)) => Some(key),
+ Some(
+ ProjectileNode::Chassis(key)
+ | ProjectileNode::Mounted(key)
+ | ProjectileNode::Building(key),
+ ) => Some(key),
};
let unabsorbed = super::projectile_shield::absorb(engine, contact, volume);
if volume > 0.0 && unabsorbed == 0.0 {
@@ -365,10 +384,11 @@ fn apply_contact_damage(
{
return Ok(None);
}
- if volume >= remaining
- && matches!(contact.node, Some(ProjectileNode::Chassis(_)))
- && row.current_flags.is_some_and(|flags| flags & 1 != 0)
- {
+ let warbot_part = matches!(
+ contact.node,
+ Some(ProjectileNode::Chassis(_) | ProjectileNode::Mounted(_))
+ );
+ if volume >= remaining && warbot_part && row.current_flags.is_some_and(|flags| flags & 1 != 0) {
super::destruction::destroy(engine, contact.handle)?;
return Ok(Some((0.0, true)));
}
@@ -380,7 +400,7 @@ fn apply_contact_damage(
if updated.is_none() {
return Ok(None);
}
- if volume >= remaining && matches!(contact.node, Some(ProjectileNode::Chassis(_))) {
+ if volume >= remaining && warbot_part {
let table = engine
.loaded
.as_mut()
@@ -467,6 +487,100 @@ mod tests {
#[test]
#[ignore = "requires licensed corpus"]
+ fn licensed_mounted_node_uses_the_stock_warbot_pose_and_provider() {
+ use crate::{
+ collect_unit_destruction_effects, create, frame, load_gameplay_mission,
+ take_unit_destruction_effects, EngineServices, MissionMode, MissionRequest,
+ MissionStartupInput,
+ };
+ use fparkan_vfs::DirectoryVfs;
+ use fparkan_world::OriginalObjectId;
+
+ 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();
+ frame(&mut engine, 0).unwrap();
+ let target = handle_by_original_id(&engine.world, OriginalObjectId(0)).unwrap();
+ let shooter = handle_by_original_id(&engine.world, OriginalObjectId(1)).unwrap();
+ let pose = transform_state(&engine.world, target).unwrap();
+ let mission = engine.loaded.as_ref().unwrap();
+ let table = mission
+ .control_device_tables
+ .iter()
+ .find(|table| table.handle == target)
+ .unwrap();
+ let hull_before = crate::control_node_provider_row(table, 0)
+ .unwrap()
+ .current_amount_bits;
+
+ let (center, radius) = unit_sphere(&mission.mission_assets, 0, pose).unwrap();
+ let hit = (0..3)
+ .flat_map(|axis| (-9..=9).flat_map(move |a| (-9..=9).map(move |b| (axis, a, b))))
+ .find_map(|(axis, a, b)| {
+ let mut center = center;
+ center[(axis + 1) % 3] += a as f32 * radius / 8.0;
+ center[(axis + 2) % 3] += b as f32 * radius / 8.0;
+ let mut segment = [center; 2];
+ segment[0][axis] -= radius * 2.0;
+ segment[1][axis] += radius * 2.0;
+ let hit = projectile_unit_hit(&engine, shooter, segment)?;
+ let Some(ProjectileNode::Mounted(key)) = hit.node else {
+ return None;
+ };
+ let row = crate::control_node_provider_row(table, key).ok()?;
+ (hit.handle == target
+ && row.current_flags == Some(0)
+ && row.source_row.effect.name[0] != 0)
+ .then_some((segment, hit, row.unit_component_index, row.source_row_index))
+ })
+ .expect("a ray hits a mounted part on the stock AutoDemo warbot");
+ let (segment, contact, component_index, local_node) = hit;
+ collect_unit_destruction_effects(&mut engine);
+ assert_eq!(
+ apply_projectile_contact(&mut engine, contact, f32::MAX).unwrap(),
+ Some((0.0, false))
+ );
+ let table = engine
+ .loaded
+ .as_ref()
+ .unwrap()
+ .control_device_tables
+ .iter()
+ .find(|table| table.handle == target)
+ .unwrap();
+ assert_eq!(
+ crate::control_node_provider_row(table, 0)
+ .unwrap()
+ .current_amount_bits,
+ hull_before
+ );
+ assert!(crate::depleted_warbot_nodes(&engine)
+ .any(|node| node == (0, component_index, local_node)));
+ assert_ne!(
+ projectile_unit_hit(&engine, shooter, segment).and_then(|hit| hit.node),
+ contact.node
+ );
+ assert!(
+ matches!(take_unit_destruction_effects(&mut engine).as_slice(),
+ [crate::UnitDestructionEffect { mesh: Some(crate::DestroyedMesh::ChassisNode { component_index: component, node, .. }), .. }]
+ if *component == component_index && *node == local_node)
+ );
+ }
+
+ #[test]
+ #[ignore = "requires licensed corpus"]
fn licensed_chassis_node_takes_damage_without_destroying_the_warbot() {
use crate::{
collect_unit_destruction_effects, create, load_gameplay_mission, starting_cockpit,
diff --git a/crates/fparkan-runtime/src/projectile_parts.rs b/crates/fparkan-runtime/src/projectile_parts.rs
index 67582ef9..8094ba0b 100644
--- a/crates/fparkan-runtime/src/projectile_parts.rs
+++ b/crates/fparkan-runtime/src/projectile_parts.rs
@@ -2,6 +2,8 @@
use crate::{
projectile::{segment_sphere_fraction, ProjectileNode},
+ turret_aim::hull_local_point,
+ weapon_pose::WeaponPoses,
Engine, LoadedMissionState, MissionAssets, MissionControlNodeProviderTableStatus, ObjectHandle,
TransformState,
};
@@ -15,6 +17,12 @@ use fparkan_render::LegacyIron3dEulerTransform;
/// Visible chassis nodes exhausted in live warbots, in mission-object and local MSH order.
pub fn depleted_chassis_nodes(engine: &Engine) -> impl Iterator<Item = (usize, usize)> + '_ {
+ depleted_warbot_nodes(engine)
+ .filter_map(|(object, component, node)| (component == 0).then_some((object, node)))
+}
+
+/// Exhausted nodes of live warbots, with their component and local MSH node indices.
+pub fn depleted_warbot_nodes(engine: &Engine) -> impl Iterator<Item = (usize, usize, usize)> + '_ {
engine.loaded.iter().flat_map(|mission| {
mission
.control_device_tables
@@ -37,9 +45,8 @@ pub fn depleted_chassis_nodes(engine: &Engine) -> impl Iterator<Item = (usize, u
.flat_map(|(index, rows)| {
rows.iter()
.skip(1)
- .take_while(|row| row.unit_component_index == 0)
.filter(|row| row.current_flags.is_some_and(|flags| flags & 0x12 == 0x10))
- .map(move |row| (index, row.source_row_index))
+ .map(move |row| (index, row.unit_component_index, row.source_row_index))
})
})
}
@@ -51,7 +58,8 @@ pub(super) fn chassis_part_contact(
state: TransformState,
segment: [[f32; 3]; 2],
(center, radius): ([f32; 3], f32),
- sphere_fraction: f32,
+ sphere_fraction: Option<f32>,
+ poses: Option<&WeaponPoses>,
) -> Option<(f32, Option<ProjectileNode>)> {
let rows = mission
.control_device_tables
@@ -65,22 +73,43 @@ pub(super) fn chassis_part_contact(
rows.first()
.is_some_and(|root| root.initial_mesh_state.is_some())
}) else {
- return Some((sphere_fraction, None));
+ return Some((sphere_fraction?, None));
};
- if let Some((fraction, node)) =
+ let viable = |row: &crate::MissionControlNodeProviderRow| {
+ f32::from_bits(row.current_amount_bits) > 0.0
+ && row.current_flags.is_some_and(|flags| flags & 0x10 == 0)
+ };
+ let chassis = sphere_fraction.and_then(|_| {
root_triangle_hit(&mission.mission_assets, index, state, segment, |node| {
rows.get(node as usize).is_some_and(|row| {
row.unit_component_index == 0
&& row.source_row_index == node as usize
- && f32::from_bits(row.current_amount_bits) > 0.0
- && row.current_flags.is_some_and(|flags| flags & 0x10 == 0)
+ && viable(row)
})
})
+ .map(|(fraction, node)| (fraction, ProjectileNode::Chassis(node)))
+ });
+ let mounted = poses.and_then(|poses| {
+ mounted_triangle_hit(
+ &mission.mission_assets,
+ index,
+ state,
+ segment,
+ poses,
+ rows,
+ viable,
+ )
+ });
+ if let Some((fraction, node)) = chassis
+ .into_iter()
+ .chain(mounted)
+ .min_by(|a, b| a.0.total_cmp(&b.0))
{
- return Some((fraction, Some(ProjectileNode::Chassis(node))));
+ return Some((fraction, Some(node)));
}
// shortcut: keep the hull sphere for unresolved mounted geometry, but
// give the chassis mesh priority until the projectile exits the sphere.
+ sphere_fraction?;
let [start, end] = segment;
if (0..3)
.map(|axis| (end[axis] - center[axis]).powi(2))
@@ -93,6 +122,81 @@ pub(super) fn chassis_part_contact(
Some((1.0 - reverse, None))
}
+fn mounted_triangle_hit(
+ assets: &MissionAssets,
+ object: usize,
+ state: TransformState,
+ segment: [[f32; 3]; 2],
+ poses: &WeaponPoses,
+ rows: &[crate::MissionControlNodeProviderRow],
+ viable: impl Fn(&crate::MissionControlNodeProviderRow) -> bool,
+) -> Option<(f32, ProjectileNode)> {
+ let max_scale = state
+ .scale
+ .map(f32::from_bits)
+ .into_iter()
+ .map(f32::abs)
+ .fold(0.0, f32::max);
+ segment_sphere_fraction(
+ segment,
+ state.position.map(f32::from_bits),
+ poses.mounted_radius * max_scale,
+ )?;
+ let to_local = |point| hull_local_point(state, point);
+ let hull_segment = [to_local(segment[0])?, to_local(segment[1])?];
+ assets
+ .visuals_for_object(object)
+ .iter()
+ .enumerate()
+ .skip(1)
+ .filter_map(|(component, &visual)| {
+ let model = &assets
+ .model_by_id(assets.visual_by_id(visual)?.model_id?)?
+ .validated;
+ let hierarchy = poses.model_hierarchy(component)?;
+ let map = |p| poses.model_point_on_hull(component, p);
+ segment_sphere_fraction(
+ hull_segment,
+ map(model.bounding_sphere_center)?,
+ model.bounding_sphere_radius,
+ )?;
+ let origin = map([0.0; 3])?;
+ let basis = [
+ map([1.0, 0.0, 0.0])?,
+ map([0.0, 1.0, 0.0])?,
+ map([0.0, 0.0, 1.0])?,
+ ];
+ let model_segment = hull_segment.map(|point| {
+ basis.map(|axis| {
+ (0..3)
+ .map(|i| (axis[i] - origin[i]) * (point[i] - origin[i]))
+ .sum()
+ })
+ });
+ let start = rows.partition_point(|row| row.unit_component_index < component);
+ let end = rows.partition_point(|row| row.unit_component_index <= component);
+ let local = rows.get(start..end)?;
+ let key = |node| {
+ local
+ .iter()
+ .position(|row| row.source_row_index == node as usize && viable(row))
+ };
+ let (fraction, node) = triangle_hit(
+ model,
+ hierarchy,
+ model_segment,
+ [1.0; 3],
+ squared_length(model_segment),
+ |node| key(node).is_some(),
+ )?;
+ Some((
+ fraction,
+ ProjectileNode::Mounted(u32::try_from(start + key(node)?).ok()?),
+ ))
+ })
+ .min_by(|a, b| a.0.total_cmp(&b.0))
+}
+
pub(super) fn root_model(assets: &MissionAssets, index: usize) -> Option<&PreparedModel> {
let visual = assets.visual_by_id(*assets.visuals_for_object(index).first()?)?;
assets.model_by_id(visual.model_id?)
@@ -131,15 +235,37 @@ pub(super) fn model_triangle_hit(
local[i] = (root[i] * x + root[i + 4] * y + root[i + 8] * z) / scale[i];
}
}
- let squared_length: f32 = (0..3)
+ triangle_hit(
+ model,
+ &poses,
+ body_segment,
+ scale,
+ squared_length(segment),
+ accept_node,
+ )
+}
+
+fn squared_length(segment: [[f32; 3]; 2]) -> f32 {
+ (0..3)
.map(|i| (segment[1][i] - segment[0][i]).powi(2))
- .sum();
+ .sum()
+}
+
+fn triangle_hit(
+ model: &ModelAsset,
+ poses: &NodePoseBuffer,
+ body_segment: [[f32; 3]; 2],
+ scale: [f32; 3],
+ squared_length: f32,
+ accept_node: impl Fn(u32) -> bool,
+) -> Option<(f32, u32)> {
if squared_length == 0.0 {
return None;
}
poses
.poses
- .into_iter()
+ .iter()
+ .copied()
.enumerate()
.filter_map(|(i, pose)| {
let node = NodeId(u32::try_from(i).ok()?);
diff --git a/crates/fparkan-runtime/src/unit_combat.rs b/crates/fparkan-runtime/src/unit_combat.rs
index 1ebbac2a..2629aba9 100644
--- a/crates/fparkan-runtime/src/unit_combat.rs
+++ b/crates/fparkan-runtime/src/unit_combat.rs
@@ -4,8 +4,11 @@ use super::{
combat_report::{CombatObject, CombatReport},
default_weapon_target::{self, DefaultWeaponTarget},
player_weapon::prepare_unit_weapons,
- projectile::{load_projectile, segment_sphere_fraction, unit_sphere, ANIMAL_UNIT_CLASS},
- projectile_terrain_hit, projectile_unit_hit,
+ projectile::{
+ load_projectile, projectile_unit_hit_with_poses, segment_sphere_fraction, unit_sphere,
+ ANIMAL_UNIT_CLASS,
+ },
+ projectile_terrain_hit,
turret_aim::{hull_local_point, TurretAim},
unit_patrol::UnitPatrol,
weapon_pose::WeaponPoses,
@@ -123,6 +126,13 @@ struct Unit {
idle_target: DefaultWeaponTarget,
}
+fn collision_poses(units: &[Unit], index: usize) -> Option<&WeaponPoses> {
+ units
+ .iter()
+ .find(|unit| unit.index == index)
+ .map(|unit| &unit.poses)
+}
+
impl Unit {
fn uses_default_targeting(&self, patrol: Option<&UnitPatrol>) -> bool {
self.class == super::boarding::WARBOT_CLASS
@@ -140,6 +150,10 @@ struct Flight {
}
impl AutoDemoCombat {
+ pub(super) fn poses_for_collision(&self, index: usize) -> Option<&WeaponPoses> {
+ collision_poses(&self.units, index)
+ }
+
pub(super) fn new(
vfs: &Arc<dyn Vfs>,
mission: &MissionDocument,
@@ -477,6 +491,7 @@ impl AutoDemoCombat {
let mut events = Vec::new();
let mut unavailable = 0;
self.finished_segments.clear();
+ let units = &self.units;
self.flights.retain_mut(|flight| {
let mut contact = None;
let mut travelled = None;
@@ -485,7 +500,9 @@ impl AutoDemoCombat {
};
let stays = flight.pose.advance(now, |segment| {
let ground = projectile_terrain_hit(&mission.terrain, segment)?;
- contact = projectile_unit_hit(engine, flight.shooter, segment)
+ contact = projectile_unit_hit_with_poses(engine, flight.shooter, segment, |index| {
+ collision_poses(units, index)
+ })
.filter(|hit| ground.is_none_or(|fraction| hit.fraction < fraction));
let fraction = contact.map(|hit| hit.fraction).or(ground).unwrap_or(1.0);
travelled = Some(clip_segment(segment, fraction));
@@ -1076,7 +1093,7 @@ mod tests {
assert!(destruction_effects.iter().any(|event| {
event.archive == "system.rlb"
&& event.name == "explode_rbr_b.exp"
- && matches!(event.mesh, Some(crate::DestroyedMesh::Mounted { object_index })
+ && matches!(event.mesh, Some(crate::DestroyedMesh::Mounted { object_index, .. })
if drafts[object_index].original_id.map(|id| id.0) == retired.original_id)
&& event
.position
@@ -1313,7 +1330,7 @@ mod tests {
let ground = projectile_terrain_hit(&mission.terrain, ray)
.unwrap()
.unwrap();
- let contact = projectile_unit_hit(&engine, enemy, ray).unwrap();
+ let contact = crate::projectile_unit_hit(&engine, enemy, ray).unwrap();
assert_eq!(contact.handle, hero.handle);
assert!(contact.fraction < ground);
let mut shots = Vec::new();
diff --git a/crates/fparkan-runtime/src/weapon_pose.rs b/crates/fparkan-runtime/src/weapon_pose.rs
index f5f7758e..9da98bee 100644
--- a/crates/fparkan-runtime/src/weapon_pose.rs
+++ b/crates/fparkan-runtime/src/weapon_pose.rs
@@ -37,6 +37,7 @@ pub(super) struct WeaponPoses {
states: Vec<ControlInstanceState>,
hierarchies: Vec<Option<NodePoseBuffer>>,
aims: Vec<Option<TurretAim>>,
+ pub(super) mounted_radius: f32,
}
impl WeaponPoses {
@@ -69,6 +70,7 @@ impl WeaponPoses {
states: vec![ControlInstanceState::default(); visuals.len()],
hierarchies: vec![None; visuals.len()],
aims: vec![None; visuals.len()],
+ mounted_radius: 0.0,
}
}
@@ -81,6 +83,7 @@ impl WeaponPoses {
hull_local_target: Option<[f32; 3]>,
report: &mut WeaponPoseReport,
) {
+ self.mounted_radius = 0.0;
for (component, &visual) in assets.visuals_for_object(index).iter().enumerate() {
let model = assets
.visual_by_id(visual)
@@ -132,9 +135,32 @@ impl WeaponPoses {
.as_ref()
.and_then(|times| node38_sampled_hierarchy_at_times(&model.validated, times))
.or_else(|| node38_fallback_hierarchy(&model.validated));
+ if let Some(center) =
+ self.model_point_on_hull(component, model.validated.bounding_sphere_center)
+ {
+ let distance = center[0].hypot(center[1]).hypot(center[2]);
+ self.mounted_radius = self
+ .mounted_radius
+ .max(distance + model.validated.bounding_sphere_radius);
+ }
}
}
+ pub(super) fn model_point_on_hull(
+ &self,
+ component: usize,
+ point: [f32; 3],
+ ) -> Option<[f32; 3]> {
+ let Mount::Socket(parent, socket) = *self.mounts.get(component)? else {
+ return None;
+ };
+ mounted_point(&self.hierarchies, &self.mounts, parent, socket, point)
+ }
+
+ pub(super) fn model_hierarchy(&self, component: usize) -> Option<&NodePoseBuffer> {
+ self.hierarchies.get(component)?.as_ref()
+ }
+
fn aim_at(&self, component: usize, target: [f32; 3]) -> Option<TurretAim> {
let local = match *self.mounts.get(component)? {
Mount::Root => target,
@@ -350,6 +376,7 @@ mod tests {
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 {
+ mounted_radius: 0.0,
mounts: vec![Mount::Root],
states: vec![],
aims: vec![],