aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorValentin Popov <valentin@popov.link>2026-11-27 01:41:33 +0300
committerValentin Popov <valentin@popov.link>2026-11-27 01:41:33 +0300
commit5a29afc412a129d9b8d3bd8e6840cc3250921952 (patch)
tree33034062ac069bf4361b1282fb1bd85a3026beea
parentfa8b449bf66997506feeef9d85e07e89bc7c20b4 (diff)
downloadfparkan-5a29afc412a129d9b8d3bd8e6840cc3250921952.tar.xz
fparkan-5a29afc412a129d9b8d3bd8e6840cc3250921952.zip
fix(render): drive manual firing flashes from linked barrel nodes
Use the current authored barrel blend as Effect mode 4 input when Control links the effect to that node. Leave projectile release and direct shot audio on their existing clocks. Verified the bound node and phase flags against GOG AniMesh and Effect, covered the stock Constructor cannon, and compared the flash at two phases in a validation-clean mission window.
-rw-r--r--apps/fparkan-game/src/control_effects.rs76
-rw-r--r--apps/fparkan-game/src/main.rs41
-rw-r--r--crates/fparkan-runtime/src/player_weapon.rs127
-rw-r--r--docs/appendices/knowledge-boundaries.md5
-rw-r--r--docs/tomes/06-behavior.md9
5 files changed, 208 insertions, 50 deletions
diff --git a/apps/fparkan-game/src/control_effects.rs b/apps/fparkan-game/src/control_effects.rs
index 735a0975..910bba81 100644
--- a/apps/fparkan-game/src/control_effects.rs
+++ b/apps/fparkan-game/src/control_effects.rs
@@ -9,7 +9,7 @@ use fparkan_runtime::{
};
use std::collections::{HashMap, HashSet};
-pub(super) fn owner_control_capacity(
+fn owner_control_capacity(
engine: &Engine,
roots: &[Option<MissionRenderRoot>],
index: usize,
@@ -36,6 +36,62 @@ impl From<FiringEffectInstance> for ControlEffectInstanceKey {
}
impl StaticVulkanApp {
+ pub(super) fn sample_control_effects(
+ &mut self,
+ sample_id: SceneSampleId,
+ clock_ms: u32,
+ manager_flag: bool,
+ player_shots: Vec<FiringEffectInstance>,
+ ) -> (
+ HashMap<ControlEffectInstanceKey, ControlEffectFrameSample>,
+ HashSet<ControlEffectInstanceKey>,
+ ) {
+ let weapon_phases: HashMap<_, _> = self
+ .cockpit
+ .and_then(|cockpit| {
+ let weapons = self.player_weapon_banks.get(&cockpit.handle)?;
+ Some(weapons.firing_effect_phases(cockpit.object_index))
+ })
+ .into_iter()
+ .flatten()
+ .map(|(effect, phase)| (effect.into(), phase))
+ .collect();
+ let mut samples = advance_control_effect_instances(
+ &mut self.control_effect_instance_states,
+ &self.ambient_effect_slots,
+ &self.control_point_light_slots,
+ &self.control_sound_slots,
+ sample_id,
+ clock_ms,
+ manager_flag,
+ |index| {
+ owner_control_capacity(
+ self.mission_engine.as_ref()?,
+ &self.mission_render_roots,
+ index,
+ )
+ },
+ |index| self.motion_effects.provider(index),
+ |key| weapon_phases.get(&key).copied(),
+ );
+ let mut direct_shot_sounds = activate_firing_flashes(
+ &mut samples,
+ &self.ambient_effect_slots,
+ &self.control_point_light_slots,
+ self.mission_frame
+ .as_ref()
+ .map_or(&[][..], |frame| &frame.autodemo_combat_events),
+ player_shots,
+ &weapon_phases,
+ );
+ // Manual weapon audio is already emitted with the projectile.
+ direct_shot_sounds.extend(self.control_sound_slots.iter().filter_map(|sound| {
+ let key = sound.effect.random_instance_key;
+ (sound.effect.time_mode == 4 && weapon_phases.contains_key(&key)).then_some(key)
+ }));
+ (samples, direct_shot_sounds)
+ }
+
pub(super) fn start_windup_sounds(
&mut self,
control_clock_ms: u32,
@@ -103,6 +159,7 @@ pub(super) fn advance_control_effect_instances(
manager_flag: bool,
owner_capacity: impl Fn(usize) -> Option<(f32, f32)>,
owner_motion: impl Fn(usize) -> Option<FxPhaseProvider>,
+ owner_effect_phase: impl Fn(ControlEffectInstanceKey) -> Option<f32>,
) -> HashMap<ControlEffectInstanceKey, ControlEffectFrameSample> {
let mut specifications = HashMap::new();
for slot in ambient_slots {
@@ -155,6 +212,11 @@ pub(super) fn advance_control_effect_instances(
eprintln!("render_coverage control_fx_owner_state_stub=1 (missing Control capacity; instance={key:?} mode={mode})");
}
}
+ } else if mode == 4 {
+ if let Some(phase) = owner_effect_phase(key) {
+ provider.effect_value = phase;
+ resolved = true;
+ }
} else if matches!(mode, 5 | 15) {
if let Some(motion) = owner_motion(key.object_index) {
provider = motion;
@@ -191,12 +253,13 @@ pub(super) fn advance_control_effect_instances(
.collect()
}
-pub(super) fn activate_firing_flashes(
+fn activate_firing_flashes(
samples: &mut HashMap<ControlEffectInstanceKey, ControlEffectFrameSample>,
ambient_slots: &[AmbientEffectGpuSlot],
point_light_slots: &[ControlEffectSlot],
events: &[AutoDemoCombatEvent],
player_effects: Vec<FiringEffectInstance>,
+ weapon_phases: &HashMap<ControlEffectInstanceKey, f32>,
) -> HashSet<ControlEffectInstanceKey> {
let autonomous_effects = events.iter().filter_map(|event| match *event {
AutoDemoCombatEvent::Shot {
@@ -219,10 +282,11 @@ pub(super) fn activate_firing_flashes(
return None;
}
let sample = samples.get_mut(&key)?;
- // shortcut: the release occurs at the midpoint of the weapon cycle.
- // Keep the flash to this snapshot until the full effect phase is wired.
- sample.phase = Some(0.5);
- sample.elapsed_seconds = 0.0;
+ if !weapon_phases.contains_key(&key) {
+ // shortcut: a shot supplies one visual sample when the bound node is unavailable.
+ sample.phase = Some(0.5);
+ sample.elapsed_seconds = 0.0;
+ }
Some(key)
})
.collect()
diff --git a/apps/fparkan-game/src/main.rs b/apps/fparkan-game/src/main.rs
index b479d3c3..8d5c0c68 100644
--- a/apps/fparkan-game/src/main.rs
+++ b/apps/fparkan-game/src/main.rs
@@ -9,16 +9,15 @@ mod chassis_animation;
mod cockpit_geometry;
#[cfg(windows)]
mod control_effects;
+#[cfg(test)]
+use control_effects::advance_control_effect_instances;
mod damage_visibility;
mod debris;
mod destruction_effects;
-mod motion_effects;
-use control_effects::{
- activate_firing_flashes, advance_control_effect_instances, owner_control_capacity,
-};
mod mission_hints;
mod mission_notices;
mod mission_pause;
+mod motion_effects;
mod player_collision;
mod player_fire;
mod player_footsteps;
@@ -11446,32 +11445,12 @@ impl StaticVulkanApp {
None
};
self.start_windup_sounds(control_clock_ms, weapon_windup_sounds);
- let mut control_effect_random_samples = advance_control_effect_instances(
- &mut self.control_effect_instance_states,
- &self.ambient_effect_slots,
- &self.control_point_light_slots,
- &self.control_sound_slots,
+ let (control_effect_random_samples, direct_shot_sounds) = self.sample_control_effects(
clock.id,
control_clock_ms,
environment
.as_ref()
.is_some_and(|frame| frame.control_effect_manager_flag),
- |index| {
- owner_control_capacity(
- self.mission_engine.as_ref()?,
- &self.mission_render_roots,
- index,
- )
- },
- |index| self.motion_effects.provider(index),
- );
- let firing_flashes = activate_firing_flashes(
- &mut control_effect_random_samples,
- &self.ambient_effect_slots,
- &self.control_point_light_slots,
- self.mission_frame
- .as_ref()
- .map_or(&[][..], |frame| &frame.autodemo_combat_events),
player_firing_effects,
);
let control_point_lights = update_control_point_lights(
@@ -11715,7 +11694,7 @@ impl StaticVulkanApp {
continue;
}
// The same firing event starts its one-shot directly.
- if firing_flashes.contains(&slot.random_instance_key) {
+ if direct_shot_sounds.contains(&slot.random_instance_key) {
continue;
}
if slot.owner_component_is_mounted {
@@ -19290,6 +19269,7 @@ mod tests {
false,
|_| None,
|_| None,
+ |_| None,
);
assert!(update_control_point_lights(
&mut [inactive],
@@ -19311,6 +19291,7 @@ mod tests {
false,
|_| None,
|_| None,
+ |_| None,
);
let lights = update_control_point_lights(
std::slice::from_mut(&mut slot),
@@ -19357,6 +19338,7 @@ mod tests {
false,
|_| None,
|_| None,
+ |_| None,
);
assert_eq!(first.len(), 1);
let key = slot.random_instance_key;
@@ -19385,6 +19367,7 @@ mod tests {
false,
|_| None,
|_| None,
+ |_| None,
)[&key],
first_sample,
"a repeated read of the same captured update reuses the shared sample"
@@ -19399,6 +19382,7 @@ mod tests {
false,
|_| None,
|_| None,
+ |_| None,
);
let expected = expected_state.advance(SceneSampleId::Replay(8), 500, 1.0);
assert_eq!(second[&key].phase_jitter, expected.phase_jitter);
@@ -19425,6 +19409,7 @@ mod tests {
false,
|_| None,
|_| None,
+ |_| None,
);
assert_eq!(later[&key].phase, Some(1.0));
assert_eq!(later[&key].elapsed_seconds, 0.5);
@@ -19438,6 +19423,7 @@ mod tests {
false,
|_| None,
|_| None,
+ |_| None,
);
assert_eq!(restarted[&key].phase, Some(0.0));
assert_eq!(restarted[&key].elapsed_seconds, 0.0);
@@ -19477,6 +19463,7 @@ mod tests {
daylight,
|_| None,
|_| None,
+ |_| None,
);
assert_eq!(samples[&key].phase, Some(expected));
}
@@ -19494,6 +19481,7 @@ mod tests {
false,
|_| None,
|_| None,
+ |_| None,
);
assert_eq!(
samples[&key].phase,
@@ -19518,6 +19506,7 @@ mod tests {
false,
|_| Some((remaining, 100.0)),
|_| None,
+ |_| None,
);
assert_eq!(samples[&key].phase, expected);
if expected.is_none() {
diff --git a/crates/fparkan-runtime/src/player_weapon.rs b/crates/fparkan-runtime/src/player_weapon.rs
index 8e350d16..d0c14d7d 100644
--- a/crates/fparkan-runtime/src/player_weapon.rs
+++ b/crates/fparkan-runtime/src/player_weapon.rs
@@ -29,6 +29,7 @@ pub struct PlayerWeapon {
/// Optional type-4 effect started by this weapon.
pub effect: Option<(String, String)>,
effect_row: Option<(usize, usize)>,
+ effect_node: Option<usize>,
windup_sound_rows: Vec<(usize, usize)>,
windup_started: bool,
barrels: Vec<Barrel>,
@@ -90,6 +91,28 @@ impl PlayerWeapons {
.flat_map(move |weapon| weapon.windup_sounds(object_index))
}
+ /// Current blends of the model nodes explicitly linked to firing effects.
+ pub fn firing_effect_phases(
+ &self,
+ object_index: usize,
+ ) -> impl Iterator<Item = (FiringEffectInstance, f32)> + '_ {
+ self.weapons.iter().filter_map(move |weapon| {
+ let node = weapon.effect_node?;
+ let blend = self
+ .weapons
+ .iter()
+ .rev()
+ .filter(|track| track.component_index == weapon.component_index)
+ .find_map(|track| {
+ let index = track.barrels.iter().rposition(|barrel| {
+ barrel.row.node_index == node && barrel.row.flags & 4 == 0
+ })?;
+ Some(track.barrel_blend(index, self.clock_ms))
+ })?;
+ Some((weapon.firing_effect(object_index)?, blend))
+ })
+ }
+
/// Samples the barrel tracks after advancing the weapon bank on this frame.
pub fn apply_firing_pose(&self, component: usize, node_times: &mut [Option<f32>]) {
for weapon in self
@@ -104,21 +127,7 @@ impl PlayerWeapons {
let Some(time) = node_times.get_mut(barrel.row.node_index) else {
continue;
};
- let mut blend = barrel.blend;
- if index == weapon.barrel_index
- && matches!(weapon.phase, FirePhase::Shot | FirePhase::Finish)
- {
- let duration = weapon.phase_end_ms - weapon.phase_start_ms;
- if duration > 0.0 {
- let progress =
- ((self.clock_ms - weapon.phase_start_ms) / duration).clamp(0.0, 1.0);
- blend = barrel.from_blend + progress * (blend - barrel.from_blend);
- }
- }
- let mut blend = blend as f32;
- if barrel.row.flags & 2 != 0 {
- blend = 1.0 - blend;
- }
+ let blend = weapon.barrel_blend(index, self.clock_ms);
*time = Some((1.0 - blend) * barrel.row.frame_a + blend * barrel.row.frame_b);
}
}
@@ -166,6 +175,24 @@ impl PlayerWeapons {
}
impl PlayerWeapon {
+ fn barrel_blend(&self, index: usize, now: f64) -> f32 {
+ let barrel = &self.barrels[index];
+ let mut blend = barrel.blend;
+ if index == self.barrel_index && matches!(self.phase, FirePhase::Shot | FirePhase::Finish) {
+ let duration = self.phase_end_ms - self.phase_start_ms;
+ if duration > 0.0 {
+ let progress = ((now - self.phase_start_ms) / duration).clamp(0.0, 1.0);
+ blend = barrel.from_blend + progress * (blend - barrel.from_blend);
+ }
+ }
+ let blend = blend as f32;
+ if barrel.row.flags & 2 != 0 {
+ 1.0 - blend
+ } else {
+ blend
+ }
+ }
+
fn sample_fire(&mut self, trigger: bool, now: f64) -> Option<usize> {
let mut shot = None;
self.windup_started = false;
@@ -385,6 +412,15 @@ fn prepare_weapons(
return None;
};
let effect_row = firing_effect_row(control, row);
+ let effect_node = effect_row
+ .filter(|effect| {
+ control.node_effect_links.contains(&(
+ effect.table_index,
+ row.node_index as u32,
+ effect.selector,
+ ))
+ })
+ .map(|_| row.node_index);
let effect = effect_row.and_then(|row| {
Some((
crate::bounded_ascii_c_string(&row.resource.archive)?,
@@ -401,6 +437,7 @@ fn prepare_weapons(
projectile_archive,
effect,
effect_row: effect_row.map(|row| (row.table_index, row.row_index)),
+ effect_node,
windup_sound_rows: control
.weapon_windup_sound_rows(record)
.map(|row| (row.table_index, row.row_index))
@@ -477,6 +514,60 @@ mod tests {
use super::*;
#[test]
+ #[ignore = "requires licensed corpus"]
+ fn licensed_constructor_cannon_effect_reads_its_barrel_node() {
+ use crate::{
+ create, load_gameplay_mission, starting_cockpit, EngineServices, MissionMode,
+ MissionRequest, MissionStartupInput,
+ };
+ use fparkan_vfs::DirectoryVfs;
+ use std::sync::Arc;
+
+ let root = std::env::var_os("FPARKAN_CORPUS_PART1_ROOT").expect("licensed root");
+ let mut engine = create(EngineServices::new(Arc::new(DirectoryVfs::new(root)))).unwrap();
+ load_gameplay_mission(
+ &mut engine,
+ MissionRequest {
+ key: "MISSIONS/CAMPAIGN/CAMPAIGN.00/Mission.02/data.tma".into(),
+ mode: MissionMode::SingleMission,
+ },
+ MissionStartupInput {
+ queue_time_ms: 0,
+ research_creation_gate: false,
+ },
+ None,
+ )
+ .unwrap();
+ let hero = starting_cockpit(&engine).unwrap();
+ let mut weapons = starting_player_weapons(&engine, hero);
+ let slot = weapons
+ .weapons()
+ .iter()
+ .position(|weapon| weapon.projectile == "bb_h_01")
+ .unwrap();
+ let effect = weapons.weapons()[slot]
+ .firing_effect(hero.object_index)
+ .unwrap();
+ weapons.select(slot + 1);
+ assert!(weapons.fire(true, 0).next().is_none());
+ for (now, expected) in [
+ (0, 0.0),
+ (63, 0.252),
+ (125, 0.5),
+ (126, 0.5),
+ (188, 0.748),
+ (252, 0.0),
+ ] {
+ weapons.fire(false, now).for_each(|_| {});
+ let phase = weapons
+ .firing_effect_phases(hero.object_index)
+ .find_map(|(key, phase)| (key == effect).then_some(phase))
+ .expect("the authored effect is linked to the cannon node");
+ assert!((phase - expected).abs() < 0.001, "{now} ms: {phase}");
+ }
+ }
+
+ #[test]
fn shot_finishes_after_trigger_release_and_spends_ammo_and_charge() {
let mut weapons = PlayerWeapons {
weapons: vec![PlayerWeapon {
@@ -489,6 +580,7 @@ mod tests {
projectile_archive: String::from("test.rlb"),
effect: None,
effect_row: Some((2, 3)),
+ effect_node: Some(0),
windup_sound_rows: vec![(0, 1)],
windup_started: false,
barrels: vec![Barrel {
@@ -543,9 +635,12 @@ mod tests {
assert!(weapons.started_windup_sounds(7).next().is_none());
weapons.apply_firing_pose(0, &mut node_times);
assert_eq!(node_times, [Some(5.0)]);
+ let effect = weapons.weapons()[0].firing_effect(7).unwrap();
+ assert_eq!(weapons.firing_effect_phases(7).next(), Some((effect, 0.25)));
assert!(weapons.fire(false, 10).next().is_none());
weapons.apply_firing_pose(0, &mut node_times);
assert_eq!(node_times, [Some(6.0)]);
+ assert_eq!(weapons.firing_effect_phases(7).next(), Some((effect, 0.5)));
let (slot, weapon, _) = weapons.fire(false, 11).next().unwrap();
assert_eq!(slot, 0);
assert_eq!(
@@ -560,11 +655,13 @@ mod tests {
assert!(weapons.fire(false, 16).next().is_none());
weapons.apply_firing_pose(0, &mut node_times);
assert_eq!(node_times, [Some(7.0)]);
+ assert_eq!(weapons.firing_effect_phases(7).next(), Some((effect, 0.75)));
assert_eq!(weapons.weapons()[0].rounds_remaining(), Some(1));
assert_eq!(weapons.weapons[0].charge.as_ref().unwrap().amount, 8.0);
assert!(weapons.fire(false, 22).next().is_none());
weapons.apply_firing_pose(0, &mut node_times);
assert_eq!(node_times, [Some(4.0)]);
+ assert_eq!(weapons.firing_effect_phases(7).next(), Some((effect, 0.0)));
assert_eq!(weapons.weapons()[0].rounds_remaining(), Some(0));
assert_eq!(weapons.weapons[0].charge.as_ref().unwrap().amount, 4.0);
assert!(weapons.fire(true, 100).next().is_none());
diff --git a/docs/appendices/knowledge-boundaries.md b/docs/appendices/knowledge-boundaries.md
index 8a7f2159..e9fdb7f1 100644
--- a/docs/appendices/knowledge-boundaries.md
+++ b/docs/appendices/knowledge-boundaries.md
@@ -191,8 +191,9 @@ authoring API без динамического подтверждения.
позиция по матрице узла и переход к модели руин остаются открытыми.
Параметры `Op10`, частицы и отстрел отдельных узлов открыты.
`player_projectile_hull_stub` отмечает проверку по сфере вместо узлов у машин.
-`player_weapon_fx_stub` отмечает открытую последовательность эффекта режима 4.
-Ручной и автономный выстрел используют фазу 0,5 только в такте выпуска.
+`player_weapon_fx_stub` отмечает вспышки без восстановленной фазы узла.
+Ручные вспышки с явной привязкой используют ход ствола. Автономные
+и непривязанные вспышки используют фазу 0,5 в такте выпуска.
В начале «Конструктора» дуло 25-мм пушки остаётся вне кадра из кабины.
`projectile_trail_approx` отмечает слои следа `Op5` с одной лентой на слой.
Разбиение ленты на части и фазы материала остаются открыты.
diff --git a/docs/tomes/06-behavior.md b/docs/tomes/06-behavior.md
index 598933b7..1f42486b 100644
--- a/docs/tomes/06-behavior.md
+++ b/docs/tomes/06-behavior.md
@@ -2902,7 +2902,14 @@ FParkan отдельно проверяет, пора ли корпусу ост
В GOG `Control.dll` (SHA-256 `BCB86318089028548A178B03A21ACCDCE15DF0CC85DDD91674CF3C2F55012C6E`) команда 14 в обработчике по RVA `0x2800` связывает эффект с узлом.
`Effect.dll` (SHA-256 `386A3E8DB1CE23F61957825D633C7DAE1ED40C25CAB0CF10A534385FD7CEE789`)
запоминает эту привязку в `0x4b70` и в режиме 4 запрашивает фазу узла
-по `0x5d3f`. В FParkan вспышка пока видна в такте выстрела с фазой 0,5.
+по `0x5d3f`. В GOG `AniMesh.dll` (SHA-256
+`65659bf67f20e5be77d67a5b2f59968f61b94293143807fa59ca451c560c4f7e`)
+метод `0x5630` сохраняет фазу анимации, а метод `0x5600` возвращает её
+для указанного узла. Вызов обеих DLL подтвердил, что эффект читает фазу
+выбранного узла. Флаг `0x20` преобразует фазы 0,25, 0,5 и 0,75 в
+0,5, 1 и 0,5. У ручного оружия с такой привязкой вспышка получает
+ту же фазу, что и ствол. Автономные и непривязанные вспышки пока занимают
+одну выборку при выпуске снаряда.
В изолированном вызове `Control.dll` RVA `0x1b4f0` смещение узла меняло
точку, а поворот менял и точку, и направление. Для перехода на это правило