diff options
| author | Valentin Popov <valentin@popov.link> | 2026-12-01 07:55:10 +0300 |
|---|---|---|
| committer | Valentin Popov <valentin@popov.link> | 2026-12-01 07:55:10 +0300 |
| commit | 79635316902c69a363f1d1a9ebef110d94190356 (patch) | |
| tree | 806e345cc9d5553cea330483b828cb080bd22061 | |
| parent | 777f48345c7faf891ac105fc4a831114914aff5d (diff) | |
| download | fparkan-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.
| -rw-r--r-- | apps/fparkan-game/src/damage_visibility.rs | 12 | ||||
| -rw-r--r-- | apps/fparkan-game/src/debris.rs | 41 | ||||
| -rw-r--r-- | crates/fparkan-runtime/src/destruction.rs | 33 | ||||
| -rw-r--r-- | crates/fparkan-runtime/src/lib.rs | 2 | ||||
| -rw-r--r-- | crates/fparkan-runtime/src/mobile_budget.rs | 36 | ||||
| -rw-r--r-- | crates/fparkan-runtime/src/player_weapon.rs | 12 | ||||
| -rw-r--r-- | crates/fparkan-runtime/src/projectile.rs | 130 | ||||
| -rw-r--r-- | crates/fparkan-runtime/src/projectile_parts.rs | 148 | ||||
| -rw-r--r-- | crates/fparkan-runtime/src/unit_combat.rs | 27 | ||||
| -rw-r--r-- | crates/fparkan-runtime/src/weapon_pose.rs | 27 | ||||
| -rw-r--r-- | docs/appendices/knowledge-boundaries.md | 7 | ||||
| -rw-r--r-- | docs/tomes/06-behavior.md | 25 |
12 files changed, 428 insertions, 72 deletions
diff --git a/apps/fparkan-game/src/damage_visibility.rs b/apps/fparkan-game/src/damage_visibility.rs index 14d6a39b..e9ffdf53 100644 --- a/apps/fparkan-game/src/damage_visibility.rs +++ b/apps/fparkan-game/src/damage_visibility.rs @@ -4,7 +4,7 @@ use super::DynamicComponentGeometry; use fparkan_animation::NodePoseBuffer; use fparkan_msh::{draw_batches, selected_slot, Group, Lod, NodeId}; use fparkan_render_vulkan::{VulkanSmokeRenderer, VulkanStaticMesh}; -use fparkan_runtime::{depleted_chassis_nodes, Engine}; +use fparkan_runtime::{depleted_warbot_nodes, Engine}; pub(super) fn apply( engine: &Engine, @@ -14,17 +14,17 @@ pub(super) fn apply( renderer: &mut VulkanSmokeRenderer, fragment_is_visible: impl Fn(usize) -> bool, ) -> Result<(), String> { - for (object, node) in depleted_chassis_nodes(engine) { + for (object, component_index, node) in depleted_warbot_nodes(engine) { let Some(component) = geometry .get(object) - .and_then(|v| v.first()) + .and_then(|v| v.get(component_index)) .and_then(Option::as_ref) else { continue; }; if !poses .get(object) - .and_then(|v| v.first()) + .and_then(|v| v.get(component_index)) .is_some_and(Option::is_some) { continue; @@ -38,7 +38,9 @@ pub(super) fn apply( { renderer .set_draw_range_index_count(range, 0) - .map_err(|error| format!("hide damaged chassis node {object}:{node}: {error}"))?; + .map_err(|error| { + format!("hide damaged warbot node {object}:{component_index}:{node}: {error}") + })?; } } Ok(()) diff --git a/apps/fparkan-game/src/debris.rs b/apps/fparkan-game/src/debris.rs index b595b441..156ba95f 100644 --- a/apps/fparkan-game/src/debris.rs +++ b/apps/fparkan-game/src/debris.rs @@ -24,19 +24,31 @@ pub(super) fn capture( terrain: &TerrainWorld, ) -> Vec<MeshFragment> { match destroyed { - DestroyedMesh::Mounted { object_index } => { - capture_mounted(object_index, origin, geometry, mesh, terrain) - } + DestroyedMesh::Mounted { + object_index, + depleted_nodes, + } => capture_mounted( + object_index, + &depleted_nodes, + origin, + geometry, + mesh, + terrain, + ), DestroyedMesh::ChassisNode { object_index, + component_index, node, hull_origin, } => { - let root = geometry + let component = geometry .get(object_index) - .and_then(|parts| parts.first()) + .and_then(|parts| parts.get(component_index)) .and_then(Option::as_ref); - root.and_then(|root| capture_node(object_index, node, hull_origin, root, mesh, terrain)) + component + .and_then(|model| { + capture_node(object_index, node, hull_origin, model, mesh, terrain) + }) .into_iter() .collect() } @@ -45,6 +57,7 @@ pub(super) fn capture( fn capture_mounted( object_index: usize, + depleted_nodes: &[(usize, usize)], hull: [f32; 3], geometry: &[Vec<Option<DynamicComponentGeometry>>], mesh: &VulkanStaticMesh, @@ -58,17 +71,27 @@ fn capture_mounted( }; components .iter() + .enumerate() .skip(1) - .flatten() - .filter_map(|component| { + .filter_map(|(component_index, component)| { + let component = component.as_ref()?; let window = component.vertex_start..component.vertex_start + component.vertex_count; + let depleted: Vec<_> = depleted_nodes + .iter() + .filter(|&&(index, _)| index == component_index) + .filter_map(|&(_, node)| node_draw_ranges(mesh, component, object_index, node)) + .flatten() + .collect(); let ranges: Vec<_> = mesh .draw_ranges .iter() .enumerate() .filter_map(|(i, range)| { let vertex = *mesh.indices.get(range.first_index as usize)? as usize; - (range.owner_scope == owner_scope && window.contains(&vertex)).then_some(i) + (range.owner_scope == owner_scope + && window.contains(&vertex) + && !depleted.contains(&i)) + .then_some(i) }) .collect(); capture_fragment(mesh, window, ranges, hull, terrain) 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![], diff --git a/docs/appendices/knowledge-boundaries.md b/docs/appendices/knowledge-boundaries.md index 713c8b15..a5ec27cd 100644 --- a/docs/appendices/knowledge-boundaries.md +++ b/docs/appendices/knowledge-boundaries.md @@ -179,7 +179,8 @@ CTL типа 24 и дорожки выстрела типа 2. Точное ус охватывает наружные модели по начальной позе креплений. Сфера героя, пересчёт при анимации и отрыве детали, отдельная поверхность столкновения, исключения для снарядов и `Op3` остаются открыты. -`player_projectile_hull_stub` остаётся для навесных моделей и живых поз. +`player_projectile_hull_stub` остаётся для поз шасси и навески без доступной +позы CPU. Поддержанные башни и орудия проверяются по треугольникам. Исчерпанные узлы шасси без замещающей модели скрываются. `Op10` с пустой ссылкой запускает полёт такой детали по приближённой баллистике. Смена стадий, тени и влияние повреждений на движение ещё открыты. @@ -1356,8 +1357,8 @@ Dirty-ветвь `0x12a40` обновляет means и FCA0, включая ав Для остальных эффектов режима 14 остаётся `control_damage_fx_activation_approx`. Попадание, истощившее секцию шасси, запускает обход `0x11130`, а неподдержанная ветвь обхода отмечается `chassis_depletion_cascade_stub`. -Сверка момента обхода, сменные стадии модели, скрытие навесных узлов и -эффекты дочерних узлов остаются открыты. Аварийное истощение использует +Сверка момента обхода, сменные стадии модели и эффекты дочерних узлов +остаются открыты. Аварийное истощение использует общее удаление корпуса. Изменения scalar и расход ходовой при переключении состояний CTL ещё открыты. Отдельные constructor, setter и loader-пути уже прослежены; физические единицы diff --git a/docs/tomes/06-behavior.md b/docs/tomes/06-behavior.md index c6a0f2dd..d4200576 100644 --- a/docs/tomes/06-behavior.md +++ b/docs/tomes/06-behavior.md @@ -2980,15 +2980,18 @@ FParkan отдельно проверяет, пора ли корпусу ост позе и креплению компонента. Поворот корпуса переводит их в координаты мира. Баллистика и порядок фаз в полёте остаются открытыми. -Полёт также проверяет пересечение отрезка с живым юнитом. Сфера корневой -модели ограничивает поиск, а у варбота внутри неё проверяются треугольники -шасси. Повреждённый узел с собственным запасом расходует его отдельно +Полёт также проверяет пересечение отрезка с живым юнитом. Сферы ограничивают +поиск, а у варбота проверяются треугольники шасси и навесных моделей. +Треугольники башни и орудия используют ту же цепочку креплений, что и точка +выстрела. Поэтому снаряд может попасть в ствол за пределами сферы шасси. +Повреждённый узел с собственным запасом расходует его отдельно и запускает свой `EXPL` при истощении. Если узел не задаёт отдельную модель разрушения, он исчезает с корпуса. В GOG `Control.dll` ветвь по RVA `0x11220` при достижении последней стадии вызывает `0x11920` для обновления видимости. Например, у тяжёлого гусеничного варбота `w_b_trk1` исчерпание -узла 7 скрывает одну гусеничную секцию. Проверку ещё не подключённых -навесных моделей заменяет выход из сферы. Срабатывает первое пересечение +узла 7 скрывает одну гусеничную секцию. Если геометрическое попадание в +варбота не найдено, остаётся приближение по выходу из сферы шасси. +Срабатывает первое пересечение по ходу отрезка, включая рельеф. Животные класса `0x20000000` используют сферу. Например, у медузы в «Конструкторе» попадание расходует запас её корневой записи NDP, @@ -3066,15 +3069,19 @@ GOG `Control.dll` выбор выполняется по RVA `0x2c590`, а сиÐ детали. Смысл параметров `Op10` и точная баллистика ещё открыты. В оригинале `Control.dll+0x10f30` при исчерпании корневого или критического -узла начинает процедуру уничтожения. В AutoDemo обработчик `0x10030` -получал прямые попадания в узлы 0, 9, 16 и 26. Расчёт входящего урона, -проверка навесных моделей и фазы разрушения ещё открыты. +узла начинает процедуру уничтожения. Прямой контакт берёт номер из пакета +по смещению `+0x10` и передаёт его из `0xee29` в `0x10030`. В запущенном +AutoDemo это были, среди прочих, узлы 16 и 26. Такой номер относится ко +всему собранному варботу. В FParkan локальный узел навесной модели переводится +в номер строки общего NDP. Когда эта строка или её потомок питает орудие, +истощение строки останавливает цикл выстрела. Расчёт входящего урона и фазы +разрушения ещё открыты. Связи узлов определяют, что ещё теряет варбот вслед за поражённой деталью. В оригинале после обработки пакетов проход `0x12ce0` запускает обход `0x11130`, если запасы узлов изменились. При переходе к более повреждённой стадии или исчерпании запаса обход истощает дочерние узлы в глубину. FParkan -применяет этот обход при исчерпании секции шасси от попадания. Поэтому +применяет этот обход при исчерпании секции шасси или навесной детали. Поэтому у шагающего варбота из AutoDemo при потере верхней секции ноги исчезают и все прикреплённые к ней звенья. Другая нога сохраняет свой запас. Отдельный обломок пока создаётся для детали, в которую попал снаряд. |
