aboutsummaryrefslogtreecommitdiff
path: root/apps/fparkan-game/src
diff options
context:
space:
mode:
authorValentin Popov <valentin@popov.link>2026-12-01 06:18:14 +0300
committerValentin Popov <valentin@popov.link>2026-12-01 06:18:14 +0300
commitc83b6fcdc97a193184552b436086a76679d024ba (patch)
treea7d2385630e2187ad21cec5a7b86f6c1e7102eff /apps/fparkan-game/src
parent659f80b53bcc1ed45b2cd30832ca4423cd2391ee (diff)
downloadfparkan-c83b6fcdc97a193184552b436086a76679d024ba.tar.xz
fparkan-c83b6fcdc97a193184552b436086a76679d024ba.zip
fix(audio): play engine loops for autonomous missiles
Keep one spatial Op2 source per flight while it moves, with separate identities from manual and scene emitters. Confirm the original mode 5 phase and verify launch, overlap and teardown on the GOG AutoDemo. Flight-speed changes and a listening comparison with the original remain open.
Diffstat (limited to 'apps/fparkan-game/src')
-rw-r--r--apps/fparkan-game/src/audio.rs58
-rw-r--r--apps/fparkan-game/src/main.rs6
-rw-r--r--apps/fparkan-game/src/projectile_sound.rs91
3 files changed, 125 insertions, 30 deletions
diff --git a/apps/fparkan-game/src/audio.rs b/apps/fparkan-game/src/audio.rs
index ec64df1e..256a88d2 100644
--- a/apps/fparkan-game/src/audio.rs
+++ b/apps/fparkan-game/src/audio.rs
@@ -16,7 +16,7 @@ use rodio::source::{ChannelVolume, SeekError};
use rodio::{
ChannelCount, Decoder, DeviceSinkBuilder, MixerDeviceSink, Player, SampleRate, Source,
};
-use std::collections::BTreeMap;
+use std::collections::{BTreeMap, BTreeSet};
use std::io::Cursor;
use std::sync::{Arc, Mutex};
use std::time::{SystemTime, UNIX_EPOCH};
@@ -31,6 +31,13 @@ const AMBIENT_NIGHT_LENGTH: f32 = 1.1;
const AMBIENT_MIN_DELAY_SECONDS: f32 = 10.0;
const AMBIENT_DELAY_VARIANTS: u32 = 10;
+#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
+pub(crate) enum ControlSoundId {
+ Effect(usize),
+ PlayerProjectile(usize),
+ AutonomousProjectile(u64, usize),
+}
+
/// Position and orientation of the listener in world coordinates.
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct Listener {
@@ -631,7 +638,7 @@ pub(crate) struct GameAudio {
mission_voice: Player,
mission_cfg: NormalizedPath,
weather_loop: NativeSpatialPlayer,
- control_sounds: BTreeMap<usize, NativeSpatialPlayer>,
+ control_sounds: BTreeMap<ControlSoundId, NativeSpatialPlayer>,
one_shots: Vec<SpatialOneShot>,
library: AudioLibrary,
ambience: AmbienceScheduler,
@@ -855,7 +862,7 @@ impl GameAudio {
/// loop or another instance using the same sample.
pub(crate) fn handle_control_sound(
&mut self,
- id: usize,
+ id: ControlSoundId,
event: &SoundEvent,
) -> Result<(), AudioError> {
validate_point(event.position, "Control emitter")?;
@@ -879,7 +886,7 @@ impl GameAudio {
if let Some(previous) = self.control_sounds.insert(id, voice.player) {
previous.stop();
}
- eprintln!("control_sound_start id={id} resource={}:{} loop={} position={:?} range={}/{} frequency={}", event.archive, event.name, event.action == SoundAction::StartLoop, event.position, event.min_distance, event.max_distance, event.frequency_ratio);
+ eprintln!("control_sound_start id={id:?} resource={}:{} loop={} position={:?} range={}/{} frequency={}", event.archive, event.name, event.action == SoundAction::StartLoop, event.position, event.min_distance, event.max_distance, event.frequency_ratio);
}
SoundAction::SetLoopVolume => {
if let Some(player) = self.control_sounds.get(&id) {
@@ -896,14 +903,25 @@ impl GameAudio {
Ok(())
}
- pub(crate) fn stop_control_sound(&mut self, id: usize) {
+ pub(crate) fn stop_control_sound(&mut self, id: ControlSoundId) {
if let Some(player) = self.control_sounds.remove(&id) {
player.stop();
- eprintln!("control_sound_stop id={id}");
+ eprintln!("control_sound_stop id={id:?}");
}
}
- pub(crate) fn control_sound_is_playing(&self, id: usize) -> bool {
+ pub(crate) fn stop_finished_projectile_sounds(&mut self, live: &BTreeSet<u64>) {
+ self.control_sounds.retain(|id, player| {
+ if matches!(*id, ControlSoundId::AutonomousProjectile(flight, _) if !live.contains(&flight)) {
+ player.stop();
+ eprintln!("control_sound_stop id={id:?}");
+ return false;
+ }
+ true
+ });
+ }
+
+ pub(crate) fn control_sound_is_playing(&self, id: ControlSoundId) -> bool {
self.control_sounds
.get(&id)
.is_some_and(|player| !player.empty())
@@ -1983,13 +2001,13 @@ mod tests {
action: SoundAction::StartLoop,
};
audio
- .handle_control_sound(0, &machine)
+ .handle_control_sound(ControlSoundId::Effect(0), &machine)
.expect("first machine");
audio
- .handle_control_sound(1, &machine)
+ .handle_control_sound(ControlSoundId::Effect(1), &machine)
.expect("second machine");
- assert!(audio.control_sound_is_playing(0));
- assert!(audio.control_sound_is_playing(1));
+ assert!(audio.control_sound_is_playing(ControlSoundId::Effect(0)));
+ assert!(audio.control_sound_is_playing(ControlSoundId::Effect(1)));
assert!(!audio.weather_loop.empty());
audio.set_paused(true);
assert!(audio
@@ -2003,11 +2021,23 @@ mod tests {
.all(|player| !player.is_paused()));
machine.action = SoundAction::StopLoop;
audio
- .handle_control_sound(0, &machine)
+ .handle_control_sound(ControlSoundId::Effect(0), &machine)
.expect("stop one machine");
- assert!(!audio.control_sound_is_playing(0));
- assert!(audio.control_sound_is_playing(1));
+ assert!(!audio.control_sound_is_playing(ControlSoundId::Effect(0)));
+ assert!(audio.control_sound_is_playing(ControlSoundId::Effect(1)));
assert!(!audio.weather_loop.empty());
+ machine.action = SoundAction::StartLoop;
+ let manual = ControlSoundId::PlayerProjectile(1);
+ let expired = ControlSoundId::AutonomousProjectile(1, 0);
+ let flying = ControlSoundId::AutonomousProjectile(2, 0);
+ for id in [manual, expired, flying] {
+ audio.handle_control_sound(id, &machine).unwrap();
+ }
+ audio.stop_finished_projectile_sounds(&BTreeSet::from([2]));
+ assert!(!audio.control_sound_is_playing(expired));
+ for id in [ControlSoundId::Effect(1), manual, flying] {
+ assert!(audio.control_sound_is_playing(id));
+ }
audio
.update_listener([10.0, 20.0, 30.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0])
.expect("move listener");
diff --git a/apps/fparkan-game/src/main.rs b/apps/fparkan-game/src/main.rs
index 8d5c0c68..6f050780 100644
--- a/apps/fparkan-game/src/main.rs
+++ b/apps/fparkan-game/src/main.rs
@@ -11682,9 +11682,11 @@ impl StaticVulkanApp {
projectile_sound::update(
audio,
&mut self.projectile_draws,
- self.control_sound_slots.len(),
+ &self.autodemo_draws,
+ self.mission_engine.as_ref(),
)?;
for (id, sound) in self.control_sound_slots.iter_mut().enumerate() {
+ let id = audio::ControlSoundId::Effect(id);
let slot = &mut sound.effect;
if self
.removed_mission_roots
@@ -11731,7 +11733,7 @@ impl StaticVulkanApp {
) {
audio
.handle_control_sound(id, &event)
- .map_err(|error| format!("play Control sound {id}: {error}"))?;
+ .map_err(|error| format!("play Control sound {id:?}: {error}"))?;
}
}
}
diff --git a/apps/fparkan-game/src/projectile_sound.rs b/apps/fparkan-game/src/projectile_sound.rs
index d8eef2ef..bdb3eed6 100644
--- a/apps/fparkan-game/src/projectile_sound.rs
+++ b/apps/fparkan-game/src/projectile_sound.rs
@@ -1,7 +1,7 @@
-//! Spatial Op2 engine loops owned by live player projectiles.
+//! Spatial Op2 engine loops owned by live projectiles.
use super::{
- audio::GameAudio,
+ audio::{ControlSoundId, GameAudio},
control_matrix_from_columns, control_row_points, control_type4_effect_local_matrix,
matrix_to_row_major, multiply_row_major,
projectile_render::{flight_basis, ProjectileDraw, ProjectileEffect},
@@ -10,7 +10,8 @@ use fparkan_fx::{
ambient_sound::{Op2SoundCommand, Op2SoundState},
clock::{FxInstanceClock, FxPhaseProvider},
};
-use fparkan_runtime::{PlayerProjectile, ProjectileAssets};
+use fparkan_runtime::{autonomous_projectile_flights, Engine, PlayerProjectile, ProjectileAssets};
+use std::collections::BTreeSet;
pub(super) struct EngineSound {
command: Op2SoundCommand,
@@ -92,15 +93,55 @@ impl EngineSound {
playing,
)
}
+
+ fn update(
+ &self,
+ audio: &mut GameAudio,
+ id: ControlSoundId,
+ flight: &PlayerProjectile,
+ ) -> Result<(), String> {
+ if let Some(event) = self.sample(flight, audio.control_sound_is_playing(id)) {
+ audio
+ .handle_control_sound(id, &event)
+ .map_err(|error| format!("play projectile engine sound: {error}"))?;
+ }
+ Ok(())
+ }
}
pub(super) fn update(
audio: &mut GameAudio,
draws: &mut [Option<ProjectileDraw>],
- first_sound_id: usize,
+ autonomous_draws: &[Option<ProjectileDraw>],
+ engine: Option<&Engine>,
+) -> Result<(), String> {
+ update_player(audio, draws)?;
+ let mut live = BTreeSet::new();
+ for (flight_id, projectile, flight) in
+ engine.into_iter().flat_map(autonomous_projectile_flights)
+ {
+ let Some(draw) = autonomous_draws.get(projectile).and_then(Option::as_ref) else {
+ continue;
+ };
+ for (index, sound) in draw.engine_sounds.iter().enumerate() {
+ live.insert(flight_id);
+ sound.update(
+ audio,
+ ControlSoundId::AutonomousProjectile(flight_id, index),
+ &flight,
+ )?;
+ }
+ }
+ audio.stop_finished_projectile_sounds(&live);
+ Ok(())
+}
+
+fn update_player(
+ audio: &mut GameAudio,
+ draws: &mut [Option<ProjectileDraw>],
) -> Result<(), String> {
// Manual projectile slots keep their indices until collision or expiry.
- let mut id = first_sound_id;
+ let mut index = 0;
for draw in draws
.iter_mut()
.flatten()
@@ -111,19 +152,14 @@ pub(super) fn update(
let replaced = born_ms != instance.sound_born_ms;
instance.sound_born_ms = born_ms;
for sound in &draw.engine_sounds {
+ let id = ControlSoundId::PlayerProjectile(index);
if replaced {
audio.stop_control_sound(id);
}
- if let Some(event) = instance
- .flight
- .as_ref()
- .and_then(|flight| sound.sample(flight, audio.control_sound_is_playing(id)))
- {
- audio
- .handle_control_sound(id, &event)
- .map_err(|error| format!("play projectile engine sound: {error}"))?;
+ if let Some(flight) = &instance.flight {
+ sound.update(audio, id, flight)?;
}
- id += 1;
+ index += 1;
}
}
}
@@ -172,4 +208,31 @@ mod tests {
assert!((next.position[0] - start.position[0] - 7.0).abs() < 0.0001);
assert_eq!(&next.position[1..], &[20.0, 30.0]);
}
+
+ #[test]
+ #[ignore = "requires licensed projectile and effect resources"]
+ fn licensed_warbot_missile_engines_start_in_flight() {
+ let root = PathBuf::from(std::env::var_os("FPARKAN_CORPUS_PART1_ROOT").unwrap());
+ let engine = create(EngineServices::new(Arc::new(DirectoryVfs::new(&root)))).unwrap();
+ for name in ["bm_l_01", "bm_m_01"] {
+ let missile = load_player_projectile(&engine, "objects.rlb", name).unwrap();
+ let effects = initial_effects(&root, &missile, name);
+ let sounds = prepare(&missile, &effects);
+ let [sound] = sounds.as_slice() else {
+ panic!("expected one engine loop for {name}");
+ };
+ let flight = PlayerProjectile::new(
+ [10.0, 20.0, 30.0],
+ [1.0, 0.0, 0.0],
+ missile.speed,
+ missile.lifetime_ms,
+ 100,
+ )
+ .unwrap();
+ let event = sound.sample(&flight, false).unwrap();
+ assert_eq!(event.name, "eng_mis.wav");
+ assert_eq!(event.action, SoundAction::StartLoop);
+ assert!(event.position[0] < flight.position[0]);
+ }
+ }
}