aboutsummaryrefslogtreecommitdiff
path: root/crates
diff options
context:
space:
mode:
Diffstat (limited to 'crates')
-rw-r--r--crates/fparkan-runtime/src/lib.rs2
-rw-r--r--crates/fparkan-runtime/src/projectile.rs103
-rw-r--r--crates/fparkan-runtime/src/projectile_damage.rs11
-rw-r--r--crates/fparkan-runtime/src/projectile_flight.rs99
-rw-r--r--crates/fparkan-runtime/src/projectile_parts.rs20
-rw-r--r--crates/fparkan-runtime/src/projectile_shield.rs227
-rw-r--r--crates/fparkan-runtime/src/unit_combat.rs93
7 files changed, 428 insertions, 127 deletions
diff --git a/crates/fparkan-runtime/src/lib.rs b/crates/fparkan-runtime/src/lib.rs
index 3f60eb42..c2b4f7e5 100644
--- a/crates/fparkan-runtime/src/lib.rs
+++ b/crates/fparkan-runtime/src/lib.rs
@@ -125,6 +125,7 @@ mod player_weapon;
mod production;
mod projectile;
mod projectile_damage;
+mod projectile_flight;
mod projectile_parts;
mod projectile_shield;
mod weapon_deployment;
@@ -192,6 +193,7 @@ pub use projectile::{
load_player_projectile, projectile_terrain_hit, projectile_unit_hit, PlayerProjectile,
ProjectileAssets, ProjectileContact, ProjectileImpact, ProjectileNode,
};
+pub use projectile_flight::{ProjectileFlightHit, ProjectileFlightStep};
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};
diff --git a/crates/fparkan-runtime/src/projectile.rs b/crates/fparkan-runtime/src/projectile.rs
index 55e5da46..720aad08 100644
--- a/crates/fparkan-runtime/src/projectile.rs
+++ b/crates/fparkan-runtime/src/projectile.rs
@@ -103,6 +103,7 @@ pub struct PlayerProjectile {
lifetime_ms: u32,
born_ms: u32,
updated_ms: u32,
+ pub(super) volume: Option<f32>,
}
impl PlayerProjectile {
@@ -131,9 +132,16 @@ impl PlayerProjectile {
lifetime_ms,
born_ms: clock_ms,
updated_ms: clock_ms,
+ volume: None,
})
}
+ /// Sets the launch volume. A pierced shield spends part of this volume in flight.
+ pub fn with_volume(mut self, volume: Option<f32>) -> Self {
+ self.volume = volume;
+ self
+ }
+
/// Queue time at launch, retained when the projectile's pose changes.
pub fn born_ms(&self) -> u32 {
self.born_ms
@@ -209,9 +217,30 @@ impl ProjectileContact {
None
}
}
+
+ /// Applies the volume remaining after crossing any fields along the flight.
+ pub fn apply_body_impact(
+ self,
+ engine: &mut Engine,
+ volume: f32,
+ ) -> Result<ProjectileImpact, ControlResourceAccessError> {
+ let key = match self.node {
+ Some(ProjectileNode::CaptureBarrier) => return Ok(ProjectileImpact::Unresolved),
+ None | Some(ProjectileNode::Chassis(0)) => None,
+ Some(
+ ProjectileNode::Chassis(key)
+ | ProjectileNode::Mounted(key)
+ | ProjectileNode::Building(key),
+ ) => Some(key),
+ };
+ Ok(match apply_contact_damage(engine, self, key, volume)? {
+ Some((remaining, removed)) => ProjectileImpact::Damage { remaining, removed },
+ None => ProjectileImpact::Unresolved,
+ })
+ }
}
-/// Finds the first unit or building intersected by this flight segment.
+/// Finds the first physical unit or building contact along this flight segment.
pub fn projectile_unit_hit(
engine: &Engine,
shooter: ObjectHandle,
@@ -261,7 +290,6 @@ pub(super) fn projectile_unit_hit_with_poses<'a>(
handle,
state,
segment,
- (center, radius),
sphere_fraction,
poses(index),
)?
@@ -271,9 +299,7 @@ pub(super) fn projectile_unit_hit_with_poses<'a>(
Some(ProjectileContact {
handle,
fraction,
- position: std::array::from_fn(|axis| {
- segment[0][axis] + (segment[1][axis] - segment[0][axis]) * fraction
- }),
+ position: segment_point(segment, fraction),
node,
})
})
@@ -331,25 +357,14 @@ pub fn apply_projectile_impact(
contact: ProjectileContact,
volume: f32,
) -> Result<ProjectileImpact, ControlResourceAccessError> {
- let key = match contact.node {
- Some(ProjectileNode::CaptureBarrier) => return Ok(ProjectileImpact::Unresolved),
- None | Some(ProjectileNode::Chassis(0)) => None,
- Some(
- ProjectileNode::Chassis(key)
- | ProjectileNode::Mounted(key)
- | ProjectileNode::Building(key),
- ) => Some(key),
- };
+ if contact.node == Some(ProjectileNode::CaptureBarrier) {
+ return Ok(ProjectileImpact::Unresolved);
+ }
let unabsorbed = super::projectile_shield::absorb(engine, contact, volume);
if volume > 0.0 && unabsorbed == 0.0 {
return Ok(ProjectileImpact::ShieldAbsorbed);
}
- Ok(
- match apply_contact_damage(engine, contact, key, unabsorbed)? {
- Some((remaining, removed)) => ProjectileImpact::Damage { remaining, removed },
- None => ProjectileImpact::Unresolved,
- },
- )
+ contact.apply_body_impact(engine, unabsorbed)
}
fn apply_contact_damage(
@@ -433,10 +448,31 @@ fn apply_contact_damage(
Ok(Some(((remaining - volume).max(0.0), false)))
}
+pub(super) fn segment_point([start, end]: [[f32; 3]; 2], fraction: f32) -> [f32; 3] {
+ std::array::from_fn(|axis| start[axis] + (end[axis] - start[axis]) * fraction)
+}
+
pub(super) fn segment_sphere_fraction(
+ segment: [[f32; 3]; 2],
+ center: [f32; 3],
+ radius: f32,
+) -> Option<f32> {
+ segment_sphere_query(segment, center, radius, true)
+}
+
+pub(super) fn segment_sphere_entrance(
+ segment: [[f32; 3]; 2],
+ center: [f32; 3],
+ radius: f32,
+) -> Option<f32> {
+ segment_sphere_query(segment, center, radius, false)
+}
+
+fn segment_sphere_query(
[start, end]: [[f32; 3]; 2],
center: [f32; 3],
radius: f32,
+ include_overlap: bool,
) -> Option<f32> {
if !radius.is_finite() || radius <= 0.0 {
return None;
@@ -445,11 +481,15 @@ pub(super) fn segment_sphere_fraction(
let rel: [f32; 3] = std::array::from_fn(|i| start[i] - center[i]);
let dot = |a: [f32; 3], b: [f32; 3]| a.into_iter().zip(b).map(|(a, b)| a * b).sum::<f32>();
let c = dot(rel, rel) - radius * radius;
- if c <= 0.0 {
+ if include_overlap && c <= 0.0 {
return Some(0.0);
}
let a = dot(dir, dir);
let b = dot(rel, dir);
+ // Control+0x1e9f0 reports overlap without a crossing flag inside the sphere.
+ if !include_overlap && (c < 0.0 || a < 1e-6 || b > 0.0) {
+ return None;
+ }
let d = b * b - a * c;
let fraction = (-b - d.sqrt()) / a;
(0.0..=1.0).contains(&fraction).then_some(fraction)
@@ -866,3 +906,24 @@ mod tests {
.unwrap());
}
}
+#[test]
+fn shield_entrance_is_distinct_from_an_initial_overlap() {
+ let center = [0.0; 3];
+ let exit = [10.0, 4.0, 0.0];
+ assert_eq!(
+ segment_sphere_entrance([[-10.0, 4.0, 0.0], exit], center, 5.0),
+ Some(0.35)
+ );
+ assert_eq!(
+ segment_sphere_entrance([[0.0, 4.0, 0.0], exit], center, 5.0),
+ None
+ );
+ assert_eq!(
+ segment_sphere_entrance([[-3.0, 4.0, 0.0], exit], center, 5.0),
+ Some(0.0)
+ );
+ assert_eq!(
+ segment_sphere_entrance([[-3.0, 4.0, 0.0], [-10.0, 4.0, 0.0]], center, 5.0),
+ None
+ );
+}
diff --git a/crates/fparkan-runtime/src/projectile_damage.rs b/crates/fparkan-runtime/src/projectile_damage.rs
index 7214f636..308186b9 100644
--- a/crates/fparkan-runtime/src/projectile_damage.rs
+++ b/crates/fparkan-runtime/src/projectile_damage.rs
@@ -33,9 +33,9 @@ mod tests {
#[ignore = "requires licensed corpus"]
fn licensed_autodemo_contact_uses_the_loaded_protection() {
use crate::{
- apply_projectile_contact, control_node_provider_row, create, load_gameplay_mission,
+ control_node_provider_row, create, load_gameplay_mission,
loaded_mission_control_device_tables, EngineServices, MissionMode, MissionRequest,
- MissionStartupInput, ProjectileContact,
+ MissionStartupInput, ProjectileContact, ProjectileImpact,
};
use fparkan_vfs::DirectoryVfs;
use fparkan_world::transform_state;
@@ -81,8 +81,11 @@ mod tests {
node: None,
};
assert_eq!(
- apply_projectile_contact(&mut engine, contact, 235.0).unwrap(),
- Some((remaining, false))
+ contact.apply_body_impact(&mut engine, 235.0).unwrap(),
+ ProjectileImpact::Damage {
+ remaining,
+ removed: false
+ }
);
}
}
diff --git a/crates/fparkan-runtime/src/projectile_flight.rs b/crates/fparkan-runtime/src/projectile_flight.rs
new file mode 100644
index 00000000..2efb8bb7
--- /dev/null
+++ b/crates/fparkan-runtime/src/projectile_flight.rs
@@ -0,0 +1,99 @@
+//! Order field crossings and physical contacts along the traveled segment.
+
+use crate::{
+ projectile::{projectile_unit_hit_with_poses, segment_point},
+ projectile_shield::{absorb, shield_crossings},
+ projectile_terrain_hit, Engine, ObjectHandle, PlayerProjectile, ProjectileContact,
+};
+use fparkan_terrain::TerrainError;
+
+/// What ended this flight segment before its planned endpoint.
+pub enum ProjectileFlightHit {
+ /// The flight reached the ground or water surface.
+ Terrain,
+ /// A charged field absorbed all the remaining volume.
+ Shield,
+ /// The segment reached geometry or a physical collision fallback.
+ Body(ProjectileContact),
+}
+
+/// Result of one queue tick of projectile flight.
+pub struct ProjectileFlightStep {
+ pub flying: bool,
+ /// Traveled trace clipped to the contact, absent if this tick covered no distance.
+ pub segment: Option<[[f32; 3]; 2]>,
+ pub hit: Option<ProjectileFlightHit>,
+ /// Volume remaining for any physical impact or the next tick.
+ pub volume: Option<f32>,
+}
+
+impl PlayerProjectile {
+ /// Advances a player shot through the mission terrain, fields and live bodies.
+ pub fn advance_in_world(
+ &mut self,
+ engine: &mut Engine,
+ shooter: ObjectHandle,
+ clock_ms: u32,
+ ) -> Result<ProjectileFlightStep, TerrainError> {
+ self.advance_in_world_with(engine, shooter, clock_ms, crate::projectile_unit_hit)
+ }
+
+ pub(super) fn advance_in_world_with_poses<'a>(
+ &mut self,
+ engine: &mut Engine,
+ shooter: ObjectHandle,
+ clock_ms: u32,
+ poses: impl Fn(usize) -> Option<&'a crate::weapon_pose::WeaponPoses>,
+ ) -> Result<ProjectileFlightStep, TerrainError> {
+ self.advance_in_world_with(engine, shooter, clock_ms, |engine, shooter, segment| {
+ projectile_unit_hit_with_poses(engine, shooter, segment, &poses)
+ })
+ }
+
+ fn advance_in_world_with(
+ &mut self,
+ engine: &mut Engine,
+ shooter: ObjectHandle,
+ clock_ms: u32,
+ body_contact: impl Fn(&Engine, ObjectHandle, [[f32; 3]; 2]) -> Option<ProjectileContact>,
+ ) -> Result<ProjectileFlightStep, TerrainError> {
+ let mut traveled = None;
+ let mut hit = None;
+ let mut volume = self.volume;
+ let flying = self.advance(clock_ms, |segment| {
+ let Some(mission) = &engine.loaded else {
+ return Ok(true);
+ };
+ let ground = projectile_terrain_hit(&mission.terrain, segment)?;
+ let body = body_contact(engine, shooter, segment)
+ .filter(|contact| ground.is_none_or(|fraction| contact.fraction < fraction));
+ let mut stop = body.as_ref().map(|contact| contact.fraction).or(ground);
+ hit = body
+ .map(ProjectileFlightHit::Body)
+ .or_else(|| ground.map(|_| ProjectileFlightHit::Terrain));
+ if let Some(mut remaining) = volume {
+ for crossing in shield_crossings(engine, shooter, segment, stop) {
+ remaining = absorb(engine, crossing, remaining);
+ if remaining == 0.0 {
+ stop = Some(crossing.fraction);
+ hit = Some(ProjectileFlightHit::Shield);
+ break;
+ }
+ }
+ volume = Some(remaining);
+ }
+ traveled = Some(match stop {
+ Some(fraction) => [segment[0], segment_point(segment, fraction)],
+ None => segment,
+ });
+ Ok(stop.is_some())
+ })?;
+ self.volume = volume;
+ Ok(ProjectileFlightStep {
+ flying,
+ segment: traveled,
+ hit,
+ volume,
+ })
+ }
+}
diff --git a/crates/fparkan-runtime/src/projectile_parts.rs b/crates/fparkan-runtime/src/projectile_parts.rs
index 2a035e2f..eef5422f 100644
--- a/crates/fparkan-runtime/src/projectile_parts.rs
+++ b/crates/fparkan-runtime/src/projectile_parts.rs
@@ -57,7 +57,6 @@ pub(super) fn chassis_part_contact(
handle: ObjectHandle,
state: TransformState,
segment: [[f32; 3]; 2],
- (center, radius): ([f32; 3], f32),
sphere_fraction: Option<f32>,
poses: Option<&WeaponPoses>,
) -> Option<(f32, Option<ProjectileNode>)> {
@@ -102,26 +101,11 @@ pub(super) fn chassis_part_contact(
viable,
)
});
- if let Some((fraction, node)) = chassis
+ chassis
.into_iter()
.chain(mounted)
.min_by(|a, b| a.0.total_cmp(&b.0))
- {
- 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))
- .sum::<f32>()
- <= radius * radius
- {
- return None;
- }
- let reverse = segment_sphere_fraction([end, start], center, radius)?;
- Some((1.0 - reverse, None))
+ .map(|(fraction, node)| (fraction, Some(node)))
}
fn mounted_triangle_hit(
diff --git a/crates/fparkan-runtime/src/projectile_shield.rs b/crates/fparkan-runtime/src/projectile_shield.rs
index 541a6cb0..91715cc1 100644
--- a/crates/fparkan-runtime/src/projectile_shield.rs
+++ b/crates/fparkan-runtime/src/projectile_shield.rs
@@ -2,8 +2,11 @@
use crate::{
control_device_budget_coefficient, control_device_selector_zero, fixed_words_ascii_c_string,
- projectile::unit_sphere, turret_aim::hull_local_point, weapon_pose::WeaponPoses, Engine,
- MissionAssets, MissionControlDeviceTableStatus, MissionObjectDraft, ProjectileContact,
+ projectile::{segment_point, segment_sphere_entrance, unit_sphere},
+ turret_aim::hull_local_point,
+ weapon_pose::WeaponPoses,
+ Engine, LoadedMissionState, MissionAssets, MissionControlDeviceTableStatus, MissionObjectDraft,
+ ProjectileContact,
};
use fparkan_render::LegacyIron3dEulerTransform;
use fparkan_world::{transform_state, TransformState};
@@ -18,6 +21,61 @@ pub struct ShieldImpact {
pub world_from_effect: [[f32; 4]; 4],
}
+/// Sphere entrances before the first physical collision, in travel order.
+pub(super) fn shield_crossings(
+ engine: &Engine,
+ shooter: crate::ObjectHandle,
+ segment: [[f32; 3]; 2],
+ stop: Option<f32>,
+) -> Vec<ProjectileContact> {
+ let Some(mission) = &engine.loaded else {
+ return Vec::new();
+ };
+ let passenger = mission.boarding.map(|boarding| boarding.hero.handle);
+ let mut crossings: Vec<_> = mission
+ .control_device_tables
+ .iter()
+ .filter_map(|table| {
+ if table.handle == shooter || passenger == Some(table.handle) {
+ return None;
+ }
+ let MissionControlDeviceTableStatus::Available(devices) = &table.status else {
+ return None;
+ };
+ if !devices.iter().any(|device| device.factory_tag == 9) {
+ return None;
+ }
+ let pose = transform_state(&engine.world, table.handle).ok()?;
+ let index = table.original_id?.0 as usize;
+ let (center, radius) = contact_sphere(mission, index, pose)?;
+ let fraction = segment_sphere_entrance(segment, center, radius)?;
+ stop.is_none_or(|limit| fraction < limit)
+ .then(|| ProjectileContact {
+ handle: table.handle,
+ fraction,
+ position: segment_point(segment, fraction),
+ node: None,
+ })
+ })
+ .collect();
+ crossings.sort_by(|a, b| a.fraction.total_cmp(&b.fraction));
+ crossings
+}
+
+fn contact_sphere(
+ mission: &LoadedMissionState,
+ index: usize,
+ pose: TransformState,
+) -> Option<([f32; 3], f32)> {
+ mission
+ .shield_spheres
+ .get(index)
+ .copied()
+ .flatten()
+ .and_then(|sphere| world_sphere(sphere, pose))
+ .or_else(|| unit_sphere(&mission.mission_assets, index, pose))
+}
+
pub(super) fn prepare_shield_spheres(
assets: &MissionAssets,
drafts: &[MissionObjectDraft],
@@ -92,33 +150,23 @@ pub(super) fn absorb(engine: &mut Engine, hit: ProjectileContact, volume: f32) -
let Some(mission) = engine.loaded.as_mut() else {
return volume;
};
- let Some(table) = mission
+ let Some(table_index) = mission
.control_device_tables
- .iter_mut()
- .find(|table| table.handle == hit.handle)
+ .iter()
+ .position(|table| table.handle == hit.handle)
else {
return volume;
};
- let MissionControlDeviceTableStatus::Available(devices) = &mut table.status else {
- return volume;
- };
- let Some(strength) = devices.iter().rfind(|device| device.factory_tag == 21) else {
- return volume;
- };
- let Some(index) = table.original_id.map(|id| id.0 as usize) else {
+ let Some(index) = mission.control_device_tables[table_index]
+ .original_id
+ .map(|id| id.0 as usize)
+ else {
return volume;
};
let Ok(pose) = transform_state(&engine.world, hit.handle) else {
return volume;
};
- let Some((center, radius)) = mission
- .shield_spheres
- .get(index)
- .copied()
- .flatten()
- .and_then(|sphere| world_sphere(sphere, pose))
- .or_else(|| unit_sphere(&mission.mission_assets, index, pose))
- else {
+ let Some((center, radius)) = contact_sphere(mission, index, pose) else {
return volume;
};
let shield_pose = TransformState {
@@ -129,6 +177,14 @@ pub(super) fn absorb(engine: &mut Engine, hit: ProjectileContact, volume: f32) -
let Some(sector) = hull_local_point(shield_pose, hit.position).and_then(contact_sector) else {
return volume;
};
+ let MissionControlDeviceTableStatus::Available(devices) =
+ &mut mission.control_device_tables[table_index].status
+ else {
+ return volume;
+ };
+ let Some(strength) = devices.iter().rfind(|device| device.factory_tag == 21) else {
+ return volume;
+ };
let Ok(multiplier) = control_device_budget_coefficient(strength, sector) else {
return volume;
};
@@ -271,6 +327,137 @@ mod tests {
#[test]
#[ignore = "requires licensed corpus"]
+ fn licensed_autodemo_grazing_shot_can_pierce_a_field_and_miss_the_body() {
+ use crate::{
+ create, load_gameplay_mission, projectile::segment_sphere_fraction,
+ projectile_terrain_hit, projectile_unit_hit, EngineServices, MissionMode,
+ MissionRequest, MissionStartupInput, PlayerProjectile, ProjectileFlightHit,
+ };
+ use fparkan_vfs::DirectoryVfs;
+ use fparkan_world::{handle_by_original_id, OriginalObjectId};
+ 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/Autodemo.00/data.tma".into(),
+ mode: MissionMode::AutoDemo,
+ },
+ MissionStartupInput {
+ queue_time_ms: 0,
+ research_creation_gate: false,
+ },
+ None,
+ )
+ .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 health_before = table.node_provider_amount_bits;
+ let MissionControlDeviceTableStatus::Available(devices) = &table.status else {
+ panic!("stock shield and resistance devices");
+ };
+ let shield = devices
+ .iter()
+ .rfind(|device| device.factory_tag == 9)
+ .unwrap();
+ let resistance = devices
+ .iter()
+ .rfind(|device| device.factory_tag == 21)
+ .unwrap();
+ let (center, radius) = contact_sphere(mission, 0, pose).unwrap();
+ let (hull_center, hull_radius) = unit_sphere(&mission.mission_assets, 0, pose).unwrap();
+ let (segment, crossing) = (0..2)
+ .flat_map(|axis| (-10..=10).flat_map(move |a| (-10..=10).map(move |b| (axis, a, b))))
+ .find_map(|(axis, a, b)| {
+ let mut line = center;
+ line[1 - axis] += a as f32 * radius / 10.0;
+ line[2] += b as f32 * radius / 10.0;
+ let mut segment = [line; 2];
+ segment[0][axis] -= radius * 2.0;
+ segment[1][axis] += radius * 2.0;
+ segment_sphere_fraction(segment, hull_center, hull_radius)?;
+ let crossings = shield_crossings(&engine, shooter, segment, None);
+ let [crossing] = crossings.as_slice() else {
+ return None;
+ };
+ (crossing.handle == target
+ && crossing.fraction < 0.5
+ && projectile_unit_hit(&engine, shooter, segment).is_none()
+ && projectile_terrain_hit(&mission.terrain, segment)
+ .ok()?
+ .is_none())
+ .then_some((segment, *crossing))
+ })
+ .expect(
+ "a stock shot crosses the field and chassis sphere while missing all triangles",
+ );
+ let shield_pose = TransformState {
+ position: center.map(f32::to_bits),
+ scale: [1.0_f32.to_bits(); 3],
+ ..pose
+ };
+ let sector =
+ contact_sector(hull_local_point(shield_pose, crossing.position).unwrap()).unwrap();
+ let capacity = control_device_selector_zero(shield).unwrap()
+ * control_device_budget_coefficient(resistance, sector).unwrap();
+ assert!(capacity > 0.0);
+ let direction = std::array::from_fn(|i| segment[1][i] - segment[0][i]);
+ let speed = direction
+ .into_iter()
+ .map(|axis| axis * axis)
+ .sum::<f32>()
+ .sqrt();
+ let launch = |volume| {
+ PlayerProjectile::new(segment[0], direction, speed, 2_000, 0)
+ .unwrap()
+ .with_volume(Some(volume))
+ };
+ collect_shield_impacts(&mut engine);
+
+ let stopped = launch(capacity * 0.5)
+ .advance_in_world(&mut engine, shooter, 500)
+ .unwrap();
+ assert!(matches!(stopped.hit, Some(ProjectileFlightHit::Shield)));
+ assert!(!stopped.flying);
+ assert!(stopped.segment.unwrap()[1]
+ .into_iter()
+ .zip(crossing.position)
+ .all(|(actual, expected)| (actual - expected).abs() < 0.001));
+ assert_eq!(take_shield_impacts(&mut engine).len(), 1);
+
+ let mut flight = launch(capacity * 0.5 + 20.0);
+ let pierced = flight.advance_in_world(&mut engine, shooter, 500).unwrap();
+ assert!(pierced.flying && pierced.hit.is_none());
+ assert!((pierced.volume.unwrap() - 20.0).abs() < 0.001);
+ assert_eq!(take_shield_impacts(&mut engine).len(), 1);
+ let tail = flight
+ .advance_in_world(&mut engine, shooter, 1_000)
+ .unwrap();
+ assert!(tail.flying && tail.hit.is_none());
+ assert_eq!(tail.volume, pierced.volume);
+ assert!(take_shield_impacts(&mut engine).is_empty());
+ let table = engine
+ .loaded
+ .as_ref()
+ .unwrap()
+ .control_device_tables
+ .iter()
+ .find(|table| table.handle == target)
+ .unwrap();
+ assert_eq!(table.node_provider_amount_bits, health_before);
+ }
+
+ #[test]
+ #[ignore = "requires licensed corpus"]
fn licensed_autodemo_shield_blocks_and_then_exposes_one_sector() {
use crate::{
apply_projectile_impact, create, load_gameplay_mission, EngineServices, MissionMode,
diff --git a/crates/fparkan-runtime/src/unit_combat.rs b/crates/fparkan-runtime/src/unit_combat.rs
index 92c81d0e..01f1e164 100644
--- a/crates/fparkan-runtime/src/unit_combat.rs
+++ b/crates/fparkan-runtime/src/unit_combat.rs
@@ -1,13 +1,10 @@
use super::{
- apply_projectile_impact,
autodemo::MOBILE_UNIT,
combat_report::{CombatObject, CombatReport},
default_weapon_target::{self, DefaultWeaponTarget},
player_weapon::prepare_unit_weapons,
- projectile::{
- load_projectile, projectile_unit_hit_with_poses, segment_sphere_fraction, unit_sphere,
- ANIMAL_UNIT_CLASS,
- },
+ projectile::{load_projectile, segment_sphere_fraction, unit_sphere, ANIMAL_UNIT_CLASS},
+ projectile_flight::ProjectileFlightHit,
projectile_terrain_hit,
turret_aim::{hull_local_point, TurretAim},
unit_patrol::UnitPatrol,
@@ -512,32 +509,32 @@ impl AutoDemoCombat {
self.finished_segments.clear();
let units = &self.units;
self.flights.retain_mut(|flight| {
- let mut contact = None;
- let mut travelled = None;
- let Some(mission) = &engine.loaded else {
- return false;
+ let step = match flight.pose.advance_in_world_with_poses(
+ engine,
+ flight.shooter,
+ now,
+ |index| collision_poses(units, index),
+ ) {
+ Ok(step) => step,
+ Err(_) => {
+ unavailable += 1;
+ self.report
+ .unavailable(flight.shooter_identity, "projectile_advance", now, 1);
+ return false;
+ }
};
- let stays = flight.pose.advance(now, |segment| {
- let ground = projectile_terrain_hit(&mission.terrain, 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));
- Ok(ground.is_some() || contact.is_some())
- });
- if let Some(hit) =
- contact.filter(|hit| hit.node != Some(crate::ProjectileNode::CaptureBarrier))
- {
- let data = &self.projectiles[flight.projectile];
+ let contact = match step.hit {
+ Some(ProjectileFlightHit::Body(hit))
+ if hit.node != Some(crate::ProjectileNode::CaptureBarrier) => Some(hit),
+ _ => None,
+ };
+ if let Some(hit) = contact {
// Capture the target before applying damage, which may remove it.
let target = CombatObject::read(&engine.world, hit.handle);
- match data
+ match step
.volume
- .map(|volume| apply_projectile_impact(engine, hit, volume))
+ .map(|volume| hit.apply_body_impact(engine, volume))
{
- Some(Ok(ProjectileImpact::ShieldAbsorbed)) => {}
Some(Ok(ProjectileImpact::Damage { removed: true, .. })) => {
self.report.destroyed(flight.shooter_identity, target, now);
events.push(AutoDemoCombatEvent::Destroyed {
@@ -571,24 +568,12 @@ impl AutoDemoCombat {
}
}
}
- match stays {
- Ok(true) => {
- flight.segment = travelled;
- true
- }
- Ok(false) => {
- if let Some(segment) = travelled {
- self.finished_segments.push((flight.projectile, segment));
- }
- false
- }
- Err(_) => {
- unavailable += 1;
- self.report
- .unavailable(flight.shooter_identity, "projectile_advance", now, 1);
- false
- }
+ if step.flying {
+ flight.segment = step.segment;
+ } else if let Some(segment) = step.segment {
+ self.finished_segments.push((flight.projectile, segment));
}
+ step.flying
});
let Some(mission) = &engine.loaded else {
return (events, unavailable);
@@ -744,7 +729,7 @@ impl AutoDemoCombat {
shooter: unit.handle,
shooter_identity: shooter,
projectile,
- pose,
+ pose: pose.with_volume(data.volume),
segment: None,
});
self.next_flight_id += 1;
@@ -813,17 +798,6 @@ fn within_firing_distance(from: [f32; 3], to: [f32; 3], range: f32) -> bool {
distance_sq <= range * range
}
-fn clip_segment([start, end]: [[f32; 3]; 2], fraction: f32) -> [[f32; 3]; 2] {
- if fraction == 1.0 {
- [start, end]
- } else {
- [
- start,
- std::array::from_fn(|i| start[i] + (end[i] - start[i]) * fraction),
- ]
- }
-}
-
#[cfg(test)]
mod tests {
use super::*;
@@ -841,15 +815,6 @@ mod tests {
));
}
- #[test]
- fn visible_segment_ends_at_world_contact() {
- let segment = [[10.0, 20.0, 8.0], [18.0, 24.0, 0.0]];
- assert_eq!(
- clip_segment(segment, 0.25),
- [[10.0, 20.0, 8.0], [12.0, 21.0, 6.0]]
- );
- assert_eq!(clip_segment(segment, 1.0), segment);
- }
use crate::{
apply_projectile_hit, control_node_provider_row, create, frame, load_gameplay_mission,
loaded_mission_assets, loaded_mission_control_device_tables, loaded_mission_script_outcome,