aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorValentin Popov <valentin@popov.link>2026-12-01 15:38:57 +0300
committerValentin Popov <valentin@popov.link>2026-12-01 15:38:57 +0300
commit1e0128c6de44aa73e446451a27469e9873bc7e93 (patch)
treedd056fd39a9223f11d27b21fca5d600b658bb5c7
parent2de3fd6567d6eee36910af260f1e5767213ba89c (diff)
downloadfparkan-1e0128c6de44aa73e446451a27469e9873bc7e93.tar.xz
fparkan-1e0128c6de44aa73e446451a27469e9873bc7e93.zip
fix(combat): fire autonomous turrets along their barrel and sights
Transform the live CPT axis through the weapon sockets and the chassis. Mounted weapons use the same sight convergence as manual shots for compatible profiles. The autonomous ray checks current chassis and mounted geometry. Checked the Control.dll CPT transform and convergence oracle against the Rust path, observed the initial AutoDemo combat in the Vulkan window, and ran the licensed AutoDemo combat test.
-rw-r--r--crates/fparkan-runtime/src/aim_convergence.rs14
-rw-r--r--crates/fparkan-runtime/src/unit_combat.rs43
-rw-r--r--crates/fparkan-runtime/src/weapon_pose.rs62
-rw-r--r--docs/appendices/knowledge-boundaries.md6
-rw-r--r--docs/tomes/06-behavior.md14
5 files changed, 124 insertions, 15 deletions
diff --git a/crates/fparkan-runtime/src/aim_convergence.rs b/crates/fparkan-runtime/src/aim_convergence.rs
index c67a9ab0..36acc2dc 100644
--- a/crates/fparkan-runtime/src/aim_convergence.rs
+++ b/crates/fparkan-runtime/src/aim_convergence.rs
@@ -2,6 +2,7 @@
use crate::{
projectile::segment_point, projectile_terrain_hit, projectile_unit_hit, Engine, ObjectHandle,
+ ProjectileContact,
};
use fparkan_assets::{PreparedComponentControl, PreparedControlPoint};
@@ -36,6 +37,17 @@ pub fn projectile_sight_target(
origin: [f32; 3],
axis: [f32; 3],
) -> Option<[f32; 3]> {
+ sight_target(engine, origin, axis, |segment| {
+ projectile_unit_hit(engine, shooter, segment)
+ })
+}
+
+pub(super) fn sight_target(
+ engine: &Engine,
+ origin: [f32; 3],
+ axis: [f32; 3],
+ body_contact: impl FnOnce([[f32; 3]; 2]) -> Option<ProjectileContact>,
+) -> Option<[f32; 3]> {
let mission = engine.loaded.as_ref()?;
let length = axis[0].hypot(axis[1]).hypot(axis[2]);
if !length.is_finite() || length <= 0.0 {
@@ -45,7 +57,7 @@ pub fn projectile_sight_target(
let at = |distance: f32| std::array::from_fn(|i| origin[i] + axis[i] * distance);
let segment = [at(5.0), at(1_000_000.0)];
let terrain = projectile_terrain_hit(&mission.terrain, segment).ok()?;
- let unit = projectile_unit_hit(engine, shooter, segment).map(|hit| hit.fraction);
+ let unit = body_contact(segment).map(|hit| hit.fraction);
let fraction = terrain.into_iter().chain(unit).min_by(f32::total_cmp)?;
Some(convergence_point(
origin,
diff --git a/crates/fparkan-runtime/src/unit_combat.rs b/crates/fparkan-runtime/src/unit_combat.rs
index 01f1e164..e616a605 100644
--- a/crates/fparkan-runtime/src/unit_combat.rs
+++ b/crates/fparkan-runtime/src/unit_combat.rs
@@ -1,9 +1,13 @@
use super::{
+ aim_convergence::sight_target,
autodemo::MOBILE_UNIT,
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::{
+ load_projectile, projectile_unit_hit_with_poses, segment_sphere_fraction, unit_sphere,
+ ANIMAL_UNIT_CLASS,
+ },
projectile_flight::ProjectileFlightHit,
projectile_terrain_hit,
turret_aim::{hull_local_point, TurretAim},
@@ -31,6 +35,7 @@ pub struct AutoDemoProjectileType {
speed: f32,
lifetime_ms: u32,
volume: Option<f32>,
+ sight_convergence: bool,
autonomous_fire_distance: f32,
}
@@ -254,6 +259,7 @@ impl AutoDemoCombat {
speed: data.speed,
lifetime_ms: data.lifetime_ms,
volume: data.volume,
+ sight_convergence: data.sight_convergence,
autonomous_fire_distance: data.autonomous_fire_distance,
});
Some(battle.projectiles.len() - 1)
@@ -585,7 +591,9 @@ impl AutoDemoCombat {
&mission.control_device_tables,
Some(now),
);
- for unit in &mut self.units {
+ for unit_index in 0..self.units.len() {
+ let (before, tail) = self.units.split_at_mut(unit_index);
+ let (unit, after) = tail.split_first_mut().expect("unit index in bounds");
unit.weapons.read_control_energy(engine, unit.handle);
let Ok(state) = transform_state(&engine.world, unit.handle) else {
continue;
@@ -720,7 +728,36 @@ impl AutoDemoCombat {
continue;
}
let data = &self.projectiles[projectile];
- let direction = std::array::from_fn(|axis| to[axis] - from[axis]);
+ let direction = poses
+ .turret_sight_component(weapon.component_index)
+ .and_then(|component| {
+ let axis = poses.cpt_axis(state, weapon.component_index, barrel)?;
+ let hit = if data.sight_convergence {
+ poses
+ .sight_ray(&mission.mission_assets, unit.index, state, component)
+ .and_then(|[origin, axis]| {
+ sight_target(engine, origin, axis, |segment| {
+ projectile_unit_hit_with_poses(
+ engine,
+ unit.handle,
+ segment,
+ |index| {
+ collision_poses(before, index)
+ .or_else(|| collision_poses(after, index))
+ },
+ )
+ })
+ })
+ } else {
+ None
+ };
+ Some(hit.map_or(axis, |hit| {
+ std::array::from_fn(|axis| hit[axis] - from[axis])
+ }))
+ })
+ // shortcut: weapons without a sampled turret still use the
+ // target direction until their aiming controller is restored.
+ .unwrap_or_else(|| std::array::from_fn(|axis| to[axis] - from[axis]));
if let Some(pose) =
PlayerProjectile::new(from, direction, data.speed, data.lifetime_ms, now)
{
diff --git a/crates/fparkan-runtime/src/weapon_pose.rs b/crates/fparkan-runtime/src/weapon_pose.rs
index b7a9f48f..f01a93e1 100644
--- a/crates/fparkan-runtime/src/weapon_pose.rs
+++ b/crates/fparkan-runtime/src/weapon_pose.rs
@@ -2,7 +2,7 @@
use crate::{
turret_aim::{apply_autonomous_turret_pose, has_turret_aim, TurretAim},
- MissionAssets, MissionObjectDraft,
+ turret_sight_points, MissionAssets, MissionObjectDraft,
};
use fparkan_animation::{AnimationTime, NodePoseBuffer, Pose};
use fparkan_assets::{
@@ -276,6 +276,60 @@ impl WeaponPoses {
}
.try_transform_scaled_point(point, state.scale.map(f32::from_bits))
}
+
+ pub(super) fn cpt_axis(
+ &self,
+ state: TransformState,
+ component: usize,
+ point: &PreparedControlPoint,
+ ) -> Option<[f32; 3]> {
+ let node = usize::try_from(point.raw_signed_field_04).ok()?;
+ let to_hull =
+ |point| mounted_point(&self.hierarchies, &self.mounts, component, node, point);
+ let origin = to_hull([0.0; 3])?;
+ let tip = to_hull(point.direction)?;
+ LegacyIron3dEulerTransform {
+ translation: [0.0; 3],
+ orientation_radians: state.orientation.map(f32::from_bits),
+ }
+ .try_transform_scaled_point(
+ std::array::from_fn(|axis| tip[axis] - origin[axis]),
+ state.scale.map(f32::from_bits),
+ )
+ .filter(|axis| *axis != [0.0; 3])
+ }
+
+ pub(super) fn turret_sight_component(&self, mut component: usize) -> Option<usize> {
+ for _ in 0..self.mounts.len() {
+ if self.aim(component).is_some() {
+ return Some(component);
+ }
+ let Mount::Socket(parent, _) = *self.mounts.get(component)? else {
+ return None;
+ };
+ component = parent;
+ }
+ None
+ }
+
+ pub(super) fn sight_ray(
+ &self,
+ assets: &MissionAssets,
+ object: usize,
+ state: TransformState,
+ component: usize,
+ ) -> Option<[[f32; 3]; 2]> {
+ let control = assets
+ .object_component_controls
+ .get(object)?
+ .get(component)?
+ .as_ref()?;
+ let [origin, axis] = turret_sight_points(control)?;
+ Some([
+ self.muzzle(state, component, origin)?,
+ self.cpt_axis(state, component, axis)?,
+ ])
+ }
}
fn mounted_point(
@@ -411,13 +465,17 @@ mod tests {
raw_signed_field_04: 0,
raw_signed_field_08: 0,
position: [1.0, 2.0, 3.0],
- direction: [0.0, 1.0, 0.0],
+ direction: [1.0, 2.0, 3.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);
}
+ let axis = poses.cpt_axis(state, 0, &barrel).unwrap();
+ for (actual, expected) in axis.into_iter().zip([-6.0, 2.0, 12.0]) {
+ assert!((actual - expected).abs() < 0.00001);
+ }
}
#[test]
diff --git a/docs/appendices/knowledge-boundaries.md b/docs/appendices/knowledge-boundaries.md
index 6cf44852..f4d5b30a 100644
--- a/docs/appendices/knowledge-boundaries.md
+++ b/docs/appendices/knowledge-boundaries.md
@@ -132,9 +132,9 @@ authoring API без динамического подтверждения.
`unit_weapon_pose_fallback` считает выборки неподдержанной анимации по объекту
и компоненту: используется начальная Control-поза. `unit_weapon_pose_stub`
считает выборки огня с неразрешённым креплением CPT. Башня наводится
-в осях модели по исходному повороту корня MSH. Ручной выстрел учитывает
-сведение по лучу CPT. Сведение огня AI, достоверность всех целей луча,
-динамика приводов и отдача открыты.
+в осях модели по исходному повороту корня MSH. Ручной огонь и оружие
+с наведением башни используют сведение по лучу CPT. Оси оружия без
+восстановленного наведения, состав целей луча, приводы и отдача открыты.
`mission_factory_raid_approx` считает кланы на отдельных картах `Single.*`,
чей `Init` оборвался и чьи исходные боевые машины идут к ближайшим вражеским
заводам. В штатном корпусе завершённый `Init` оставляет этот счётчик нулевым.
diff --git a/docs/tomes/06-behavior.md b/docs/tomes/06-behavior.md
index 87c861c9..b973e600 100644
--- a/docs/tomes/06-behavior.md
+++ b/docs/tomes/06-behavior.md
@@ -2948,8 +2948,8 @@ FParkan обновляет позу ствола перед расчётом еÐ
`bcb86318089028548a178b03a21accdce15df0cc85ddd91674cf3c2f55012c6e`),
RVA `0x1b4f0`, и преобразований `Ngi32.dll`. При масштабе (2, 3, 4),
повороте на 90° вокруг Z и переносе (30, 40, 50) тройка (1, 2, 3)
-даёт точку (24, 42, 62) и вектор (−6, 2, 12). Мировую матрицу для
-вектора ствола FParkan ещё предстоит восстановить.
+даёт точку (24, 42, 62) и вектор (−6, 2, 12). Вращение креплений и
+масштаб корпуса меняют ось ствола. Перенос корпуса меняет точку дула.
Запись CPT хранит два соседних слова. При создании записи для выстрела
`Control.dll` по RVA `0xb210` сохраняет узел из слова по `+4`. Вызов
@@ -2982,10 +2982,12 @@ FParkan отдельно проверяет, пора ли корпусу ост
проверенные башни AutoDemo используют кадры 7–11 для полного оборота и 12–14
для подъёма ствола. Окно и расчёт точки выстрела используют одинаковые углы.
-Снаряд пока направляется в центр цели по прямой. В исходной GOG
-`Control.dll` ветвь по RVA `0x2a610` может корректировать вектор CPT по
-пересечению луча от пары прицельных точек. Применение поправки к AI,
-скорость приводов и отдача ещё открыты. Как и оконный рендер,
+Снаряд башенного варбота летит по оси ствола. Если луч прицела встречает
+поверхность и профиль разрешает сведение, направление уточняется по той же
+паре CPT, что и при ручном огне. В GOG `Control.dll` это ветвь по RVA
+`0x2a610`. В FParkan поиск точки учитывает рельеф и геометрию машин.
+Оружие без разрешённого наведения башни пока стреляет в центр цели.
+Скорость приводов и отдача ещё открыты. Как и оконный рендер,
неподдержанную анимацию этот путь
заменяет начальной позой Control, но считает такие выборки по объекту и
компоненту. Неизвестное крепление пропускает выстрел и попадает в отчёт,