aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorValentin Popov <valentin@popov.link>2026-11-26 05:52:25 +0300
committerValentin Popov <valentin@popov.link>2026-11-26 05:52:25 +0300
commit3dd13b710e1e559ef3f5cf15f3c6b50e8377d161 (patch)
treee025018284116f03f10a1fa09b5546a58aaa2ff6
parent5a2aa6ff6b6f4ab2480eed5be90957377d00c9e2 (diff)
downloadfparkan-3dd13b710e1e559ef3f5cf15f3c6b50e8377d161.tar.xz
fparkan-3dd13b710e1e559ef3f5cf15f3c6b50e8377d161.zip
feat(combat): activate mounted flash effects on autonomous shots
Carry the prepared effect row with each shot. Use the existing mode 4 visual effect for that component at release, with its authored geometry, lights and CPT placement. Keep the one-shot sound on its existing event path. Verified stock AutoDemo shot frames submit the authored muzzle light with Vulkan validation clean. A matched on-screen comparison and the full flash curve remain open.
-rw-r--r--apps/fparkan-game/src/control_effects.rs45
-rw-r--r--apps/fparkan-game/src/main.rs22
-rw-r--r--crates/fparkan-runtime/src/lib.rs2
-rw-r--r--crates/fparkan-runtime/src/player_weapon.rs33
-rw-r--r--crates/fparkan-runtime/src/unit_combat.rs39
-rw-r--r--docs/appendices/knowledge-boundaries.md4
-rw-r--r--docs/tomes/06-behavior.md5
7 files changed, 130 insertions, 20 deletions
diff --git a/apps/fparkan-game/src/control_effects.rs b/apps/fparkan-game/src/control_effects.rs
index e70b33e5..a21606d4 100644
--- a/apps/fparkan-game/src/control_effects.rs
+++ b/apps/fparkan-game/src/control_effects.rs
@@ -4,8 +4,8 @@ use super::{
MissionRenderRoot, SceneSampleId,
};
use fparkan_fx::clock::{FxInstanceClock, FxPhaseProvider};
-use fparkan_runtime::{loaded_mission_control_device_tables, Engine};
-use std::collections::HashMap;
+use fparkan_runtime::{loaded_mission_control_device_tables, AutoDemoCombatEvent, Engine};
+use std::collections::{HashMap, HashSet};
pub(super) fn owner_control_capacity(
engine: &Engine,
@@ -108,3 +108,44 @@ pub(super) fn advance_control_effect_instances(
)
.collect()
}
+
+pub(super) fn activate_firing_flashes(
+ samples: &mut HashMap<ControlEffectInstanceKey, ControlEffectFrameSample>,
+ ambient_slots: &[AmbientEffectGpuSlot],
+ point_light_slots: &[ControlEffectSlot],
+ events: &[AutoDemoCombatEvent],
+) -> HashSet<ControlEffectInstanceKey> {
+ events
+ .iter()
+ .filter_map(|event| {
+ let AutoDemoCombatEvent::Shot {
+ effect_instance: Some(effect),
+ ..
+ } = *event
+ else {
+ return None;
+ };
+ let key = ControlEffectInstanceKey {
+ object_index: effect.object_index,
+ component_index: effect.component_index,
+ table_index: effect.table_index,
+ row_index: effect.row_index,
+ };
+ let has_external_flash = ambient_slots
+ .iter()
+ .any(|slot| slot.random_instance_key == key && slot.time_mode == 4)
+ || point_light_slots
+ .iter()
+ .any(|slot| slot.random_instance_key == key && slot.time_mode == 4);
+ if !has_external_flash {
+ 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;
+ Some(key)
+ })
+ .collect()
+}
diff --git a/apps/fparkan-game/src/main.rs b/apps/fparkan-game/src/main.rs
index 6b337fc8..98a34f6e 100644
--- a/apps/fparkan-game/src/main.rs
+++ b/apps/fparkan-game/src/main.rs
@@ -8,7 +8,9 @@ mod camera_capture;
mod chassis_animation;
#[cfg(windows)]
mod control_effects;
-use control_effects::{advance_control_effect_instances, owner_control_capacity};
+use control_effects::{
+ activate_firing_flashes, advance_control_effect_instances, owner_control_capacity,
+};
mod mission_hints;
mod mission_notices;
mod mission_pause;
@@ -11414,7 +11416,7 @@ impl StaticVulkanApp {
} else {
None
};
- let control_effect_random_samples = advance_control_effect_instances(
+ 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,
@@ -11432,6 +11434,18 @@ impl StaticVulkanApp {
)
},
);
+ let firing_flashes = self
+ .mission_frame
+ .as_ref()
+ .map(|frame| {
+ activate_firing_flashes(
+ &mut control_effect_random_samples,
+ &self.ambient_effect_slots,
+ &self.control_point_light_slots,
+ &frame.autodemo_combat_events,
+ )
+ })
+ .unwrap_or_default();
let control_point_lights = update_control_point_lights(
&mut self.control_point_light_slots,
&mut self.op1_jitter,
@@ -11628,6 +11642,10 @@ impl StaticVulkanApp {
audio.stop_control_sound(id);
continue;
}
+ // The same firing event starts its one-shot directly.
+ if firing_flashes.contains(&slot.random_instance_key) {
+ continue;
+ }
if slot.owner_component_is_mounted {
slot.mount_pose = self
.component_mount_poses
diff --git a/crates/fparkan-runtime/src/lib.rs b/crates/fparkan-runtime/src/lib.rs
index 71afd080..9d7deec8 100644
--- a/crates/fparkan-runtime/src/lib.rs
+++ b/crates/fparkan-runtime/src/lib.rs
@@ -150,7 +150,7 @@ pub use projectile::{
projectile_unit_hit, PlayerProjectile, ProjectileAssets, ProjectileContact,
};
pub use research::order_lab_research;
-pub use unit_combat::{AutoDemoCombatEvent, AutoDemoProjectileType};
+pub use unit_combat::{AutoDemoCombatEvent, AutoDemoProjectileType, FiringEffectInstance};
pub use unit_spawn::SpawnedUnit;
const MISSION_DECODED_PAYLOAD_CACHE_ENTRIES: usize = 256;
diff --git a/crates/fparkan-runtime/src/player_weapon.rs b/crates/fparkan-runtime/src/player_weapon.rs
index 48517342..00ead0db 100644
--- a/crates/fparkan-runtime/src/player_weapon.rs
+++ b/crates/fparkan-runtime/src/player_weapon.rs
@@ -1,7 +1,7 @@
use crate::{Engine, StartingCockpit};
use fparkan_assets::{
- PreparedComponentControl, PreparedControlEffectSection, PreparedControlPoint,
- PreparedControlTimelineRow,
+ PreparedComponentControl, PreparedControlEffectRow, PreparedControlEffectSection,
+ PreparedControlPoint, PreparedControlTimelineRow,
};
/// A unit's selectable weapon devices, in resource order.
@@ -27,6 +27,7 @@ pub struct PlayerWeapon {
pub projectile_archive: String,
/// Optional type-4 effect started by this weapon.
pub effect: Option<(String, String)>,
+ pub(super) effect_row: Option<(usize, usize)>,
barrels: Vec<Barrel>,
barrel_index: usize,
rounds_remaining: Option<u32>,
@@ -301,7 +302,13 @@ fn prepare_weapons(
} else {
return None;
};
- let effect = firing_effect(control, row);
+ let effect_row = firing_effect_row(control, row);
+ let effect = effect_row.and_then(|row| {
+ Some((
+ crate::bounded_ascii_c_string(&row.resource.archive)?,
+ crate::bounded_ascii_c_string(&row.resource.name)?,
+ ))
+ });
Some(PlayerWeapon {
component_index,
control_record_index,
@@ -310,6 +317,7 @@ fn prepare_weapons(
projectile,
projectile_archive,
effect,
+ effect_row: effect_row.map(|row| (row.table_index, row.row_index)),
barrels,
barrel_index: 0,
rounds_remaining,
@@ -323,21 +331,21 @@ fn prepare_weapons(
.collect()
}
-fn firing_effect(
- control: &PreparedComponentControl,
+fn firing_effect_row<'a>(
+ control: &'a PreparedComponentControl,
muzzle: &PreparedControlTimelineRow,
-) -> Option<(String, String)> {
+) -> Option<&'a PreparedControlEffectRow> {
let PreparedControlEffectSection::Parsed(rows) = &control.effect_section else {
return None;
};
let group = control.initial_effect_group?;
- let row = if let Some(&(_, _, selector)) = control
+ if let Some(&(_, _, selector)) = control
.node_effect_links
.iter()
.find(|&&(table, node, _)| table == group && node as usize == muzzle.node_index)
{
rows.iter()
- .find(|row| row.table_index == group && row.selector == selector)?
+ .find(|row| row.table_index == group && row.selector == selector)
} else {
// Separate gun meshes can have one firing record and an effect whose
// first control point is the same muzzle. Ambiguous rows stay unresolved.
@@ -359,12 +367,8 @@ fn firing_effect(
if candidates.next().is_some() {
return None;
}
- row
- };
- Some((
- crate::bounded_ascii_c_string(&row.resource.archive)?,
- crate::bounded_ascii_c_string(&row.resource.name)?,
- ))
+ Some(row)
+ }
}
pub(super) fn prepare_unit_weapons(controls: &[Option<PreparedComponentControl>]) -> PlayerWeapons {
@@ -394,6 +398,7 @@ mod tests {
projectile: String::from("test"),
projectile_archive: String::from("test.rlb"),
effect: None,
+ effect_row: None,
barrels: vec![Barrel {
muzzle: PreparedControlPoint {
raw_flags: 0,
diff --git a/crates/fparkan-runtime/src/unit_combat.rs b/crates/fparkan-runtime/src/unit_combat.rs
index 885bf328..777aee89 100644
--- a/crates/fparkan-runtime/src/unit_combat.rs
+++ b/crates/fparkan-runtime/src/unit_combat.rs
@@ -32,6 +32,19 @@ pub struct AutoDemoProjectileType {
volume: Option<f32>,
}
+/// The prepared scene instance associated with a weapon's firing effect.
+#[derive(Clone, Copy, Debug, Eq, PartialEq)]
+pub struct FiringEffectInstance {
+ /// Index of the unit's prepared object draft.
+ pub object_index: usize,
+ /// Index of the component owning the effect.
+ pub component_index: usize,
+ /// Control effect table.
+ pub table_index: usize,
+ /// Effect row within that table.
+ pub row_index: usize,
+}
+
/// One autonomous combat event on the mission clock.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum AutoDemoCombatEvent {
@@ -45,6 +58,8 @@ pub enum AutoDemoCombatEvent {
projectile: usize,
/// Optional weapon effect in shared resource order.
effect: Option<usize>,
+ /// Prepared component effect activated by this release.
+ effect_instance: Option<FiringEffectInstance>,
/// World-space muzzle position as raw IEEE-754 coordinates.
muzzle_bits: [u32; 3],
},
@@ -588,6 +603,14 @@ impl AutoDemoCombat {
target,
projectile,
effect: unit.effects[slot],
+ effect_instance: weapon.effect_row.map(|(table_index, row_index)| {
+ FiringEffectInstance {
+ object_index: unit.index,
+ component_index: weapon.component_index,
+ table_index,
+ row_index,
+ }
+ }),
muzzle_bits: from.map(f32::to_bits),
});
} else {
@@ -743,6 +766,7 @@ mod tests {
let AutoDemoCombatEvent::Shot {
shooter,
effect,
+ effect_instance,
muzzle_bits,
..
} = *event
@@ -753,6 +777,21 @@ mod tests {
assert_eq!(flight.pose.position.map(f32::to_bits), muzzle_bits);
if let Some(effect) = effect {
assert!(effect < combat.weapon_effects().len());
+ let instance = effect_instance.expect("shot names its prepared effect row");
+ let assets = &engine.loaded.as_ref().unwrap().mission_assets;
+ let control = assets.object_component_controls[instance.object_index]
+ [instance.component_index]
+ .as_ref()
+ .unwrap();
+ let fparkan_assets::PreparedControlEffectSection::Parsed(rows) =
+ &control.effect_section
+ else {
+ panic!("effect table is unprepared")
+ };
+ assert!(rows
+ .iter()
+ .any(|row| row.table_index == instance.table_index
+ && row.row_index == instance.row_index));
observed_weapon_effect = true;
}
let shooter = combat
diff --git a/docs/appendices/knowledge-boundaries.md b/docs/appendices/knowledge-boundaries.md
index 6ca744de..9a82aac9 100644
--- a/docs/appendices/knowledge-boundaries.md
+++ b/docs/appendices/knowledge-boundaries.md
@@ -94,7 +94,9 @@ authoring API без динамического подтверждения.
и коэффициенту Behavior; `go_speed_stub` считает подмену 9 при отсутствии данных.
Удержание запроса MWalker входит в незавершённый `unit_motion_controller_stub`.
`autodemo_combat_approx` отмечает выбор цели, наведение и
-приближённый урон. Вспышки, звуки хода и боевое уклонение открыты.
+приближённый урон. Звуки хода и боевое уклонение открыты.
+Дульная вспышка автономного орудия выбирает фазу 0.5 на такте выпуска.
+Нарастание, затухание и остальные команды эффекта ещё открыты.
Звук выстрела использует одноразовую команду `Op2`. Отдельные задержки и
смещения внутри эффекта выстрела ещё открыты. У отдельного орудия без
привязки к узлу используется однозначная строка по точке дула.
diff --git a/docs/tomes/06-behavior.md b/docs/tomes/06-behavior.md
index 3bdf2cf9..2fbdf289 100644
--- a/docs/tomes/06-behavior.md
+++ b/docs/tomes/06-behavior.md
@@ -2658,6 +2658,11 @@ Simulation читает подготовленный input snapshot. Renderer н
занимают места в пуле независимо, поэтому снаряд, выпущенный в том же
такте, может появиться рядом с последним следом предыдущего выстрела.
+В том же такте выбранная пушка активирует свой эффект дульной вспышки.
+Свет `Op1` и поддержанные спрайты берут цвет, размеры и положение из
+ресурса эффекта. Точки CPT и поза оружия задают мировое крепление. Для
+режима 4 отрисовка сейчас берёт середину фазы выпуска на одном такте.
+
В изолированном вызове `Control.dll` RVA `0x1b4f0` смещение узла меняло
точку, а поворот менял и точку, и направление. Для перехода на это правило
нужна сверка живых матриц: подстановка текущих поз FParkan дала почти