Files
benilla-octo/third_party/kira/src/manager.rs
T
SamandClaude Fable 5.1 b1294ce9a1 the quest windows go stock, and the 20 ms frames were mis-split pairs
- the quest giver's dialog and the quest log are the reference's own `QuestFrame.xml` and `QuestLogFrame.xml`, run off the player's chain at the reference's own toc seats; our 1366-line and 1999-line copies are deleted, and the verbs the stock files call are built — the four `GameTooltip` quest-item and reward-spell setters, the reward spell itself (parsed on all three packets and dropped by the model until now), and two verbs; the detail pane could never scroll because `UpdateScrollChildRect` measured a frame late where the reference's measure is synchronous, so it measures through the installed font engine now; and ten things the reference does that ours did not, each found by a test that had enshrined ours — a shift-click never selects, an empty log hides the whole detail pane and says "No Active Quests", the abandon confirm lives in the popup registry (1944)
- the quest bindings' law, read off the binary and folded back: no 1.12 packet carries a quest background material — `GetQuestBackgroundMaterial` (`0x502230`) forks on the dialog's SOURCE object, an item answering its template's PageMaterial, a GameObject its template data, a creature nil (FrameXML's "Parchment"), the id naming a `PageTextMaterial.dbc` row whose six words are nowhere in the binary; its twin `ItemTextGetMaterial` has the same body, so the reader window already held every piece and the giver's feed runs the same resolve; `QuestChooseRewardError` is game-error row `0x98`, and the row plays `igQuestFailed` first, which the verb now queues; the reward-spell getters' third return is `Spell.dbc` Attributes bit 5 (1161 of 22357 rows set — craft-cast spells set, `Pattern:` teaching spells clear), read off the catalog now (1946)
- the "20 ms frames" of a raid, chased to their number: the probe's worst frames now carry their churn (entities, assets, first-play sound decodes, live particles, the GPU reading) and in a Blackrock raid with sound on every one of those read flat; then the same window on the PACED clock — under vsync with pipelined rendering the raw delta is mis-split into long/short pairs that sum to exact refresh multiples, so an alone Stormwind leg read 115 of 300 frames over budget with cpu and gpu both at their means, while the paced clock read 0 skipped frames in every leg; what remains real in the raid is `cpu_p99` at 22–23 ms with sound on; and every submesh the streamer spawns now carries why it is an entity, counted per reason — 5.8k resident ADT-doodad submeshes at the Stormwind auction house, 5.3k of them hidden, three prop families the retained pass declines by rule, each riding every per-`Mesh3d` sweep for ~0.4 ms of the alone frame (1947)
- a raid's dozen voices cost the mixer ~1.5 ms of every 60 Hz frame: upstream kira spatializes every frame — normalizes, the attenuation curve and a dB→amplitude `powf` per frame per spatial track, two more `powf`s for the volume tween, ~1.7 M `powf`s a second at 48 kHz × 12 tracks for gains that change imperceptibly across a chunk — so kira 0.12.1 is vendored with one patch: the spatial gains and the volume × fade amplitude are evaluated at the chunk's two ends and interpolated across its ~10.7 ms, the granularity FMOD 3, the reference's own mixer, updates them at; nothing a listener can name changes (1945); and rig poses are evaluated in parallel over rigs — each reads its shared clips and writes only its own pose, and a raid's ~400 live rigs were 0.4 ms of one thread walked serially on the main thread's critical path (1947)

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-04 20:55:12 +07:00

331 lines
9.6 KiB
Rust

//! The main entrypoint for controlling audio from gameplay code.
//!
//! In order to play audio, you'll need to create an [`AudioManager`].
//! The [`AudioManager`] keeps track of playing sounds and manages other
//! resources like clocks, mixer tracks, and spatial scenes. Once the
//! [`AudioManager`] is dropped, its audio output will be stopped.
mod settings;
pub use settings::*;
use std::sync::{Arc, atomic::Ordering};
use crate::{
PlaySoundError, ResourceLimitReached, Value,
backend::{
Backend, DefaultBackend, Renderer, RendererShared,
resources::{ResourceControllers, create_resources},
},
clock::{Clock, ClockHandle, ClockId, ClockSpeed},
listener::{Listener, ListenerHandle, ListenerId},
modulator::{ModulatorBuilder, ModulatorId},
sound::SoundData,
track::{
MainTrackHandle, SendTrackBuilder, SendTrackHandle, SendTrackId, SpatialTrackBuilder,
SpatialTrackHandle, TrackBuilder, TrackHandle,
},
};
/// Controls audio from gameplay code.
pub struct AudioManager<B: Backend = DefaultBackend> {
backend: B,
resource_controllers: ResourceControllers,
renderer_shared: Arc<RendererShared>,
internal_buffer_size: usize,
}
impl<B: Backend> AudioManager<B> {
/**
Creates a new [`AudioManager`].
# Examples
Create an [`AudioManager`] using the [`DefaultBackend`] and the
default settings:
```no_run
use kira::{AudioManager, AudioManagerSettings, DefaultBackend};
let audio_manager = AudioManager::<DefaultBackend>::new(AudioManagerSettings::default())?;
# Result::<(), Box<dyn std::error::Error>>::Ok(())
```
Create an [`AudioManager`] with a reverb effect on the main mixer track:
```no_run
use kira::{
AudioManager, AudioManagerSettings, DefaultBackend,
track::MainTrackBuilder,
effect::reverb::ReverbBuilder,
};
let audio_manager = AudioManager::<DefaultBackend>::new(AudioManagerSettings {
main_track_builder: MainTrackBuilder::new().with_effect(ReverbBuilder::new()),
..Default::default()
})?;
# Result::<(), Box<dyn std::error::Error>>::Ok(())
```
*/
pub fn new(settings: AudioManagerSettings<B>) -> Result<Self, B::Error> {
let (mut backend, sample_rate) =
B::setup(settings.backend_settings, settings.internal_buffer_size)?;
let renderer_shared = Arc::new(RendererShared::new(sample_rate));
let (resources, resource_controllers) = create_resources(
settings.capacities,
settings.main_track_builder,
sample_rate,
settings.internal_buffer_size,
);
let renderer = Renderer::new(
renderer_shared.clone(),
settings.internal_buffer_size,
resources,
);
backend.start(renderer)?;
Ok(Self {
backend,
resource_controllers,
renderer_shared,
internal_buffer_size: settings.internal_buffer_size,
})
}
/**
Plays a sound.
# Examples
```no_run
# use kira::{AudioManager, AudioManagerSettings, DefaultBackend};
use kira::sound::static_sound::{StaticSoundData, StaticSoundSettings};
# let mut manager = AudioManager::<DefaultBackend>::new(AudioManagerSettings::default())?;
let sound_data = StaticSoundData::from_file("sound.ogg")?;
manager.play(sound_data)?;
# Result::<(), Box<dyn std::error::Error>>::Ok(())
```
*/
pub fn play<D: SoundData>(
&mut self,
sound_data: D,
) -> Result<D::Handle, PlaySoundError<D::Error>> {
self.main_track().play(sound_data)
}
/// Creates a mixer sub-track.
pub fn add_sub_track(
&mut self,
builder: TrackBuilder,
) -> Result<TrackHandle, ResourceLimitReached> {
let (mut track, handle) =
builder.build(self.renderer_shared.clone(), self.internal_buffer_size);
track.init_effects(self.renderer_shared.sample_rate.load(Ordering::SeqCst));
self.resource_controllers
.sub_track_controller
.insert(track)?;
Ok(handle)
}
/// Adds a spatial mixer sub-track.
pub fn add_spatial_sub_track(
&mut self,
listener: impl Into<ListenerId>,
position: impl Into<Value<mint::Vector3<f32>>>,
builder: SpatialTrackBuilder,
) -> Result<SpatialTrackHandle, ResourceLimitReached> {
let (mut track, handle) = builder.build(
self.renderer_shared.clone(),
self.internal_buffer_size,
listener.into(),
position.into().to_(),
);
track.init_effects(self.renderer_shared.sample_rate.load(Ordering::SeqCst));
self.resource_controllers
.sub_track_controller
.insert(track)?;
Ok(handle)
}
/// Creates a mixer send track.
pub fn add_send_track(
&mut self,
builder: SendTrackBuilder,
) -> Result<SendTrackHandle, ResourceLimitReached> {
let key = self
.resource_controllers
.send_track_controller
.try_reserve()?;
let id = SendTrackId(key);
let (mut track, handle) = builder.build(id, self.internal_buffer_size);
track.init_effects(self.renderer_shared.sample_rate.load(Ordering::SeqCst));
self.resource_controllers
.send_track_controller
.insert_with_key(key, track);
Ok(handle)
}
/**
Creates a clock.
# Examples
```no_run
# use kira::{AudioManager, AudioManagerSettings, DefaultBackend};
use kira::clock::ClockSpeed;
# let mut manager = AudioManager::<DefaultBackend>::new(AudioManagerSettings::default())?;
let clock = manager.add_clock(ClockSpeed::TicksPerMinute(120.0))?;
# Result::<(), Box<dyn std::error::Error>>::Ok(())
```
*/
pub fn add_clock(
&mut self,
speed: impl Into<Value<ClockSpeed>>,
) -> Result<ClockHandle, ResourceLimitReached> {
let key = self.resource_controllers.clock_controller.try_reserve()?;
let id = ClockId(key);
let (clock, handle) = Clock::new(speed.into(), id);
self.resource_controllers
.clock_controller
.insert_with_key(key, clock);
Ok(handle)
}
/**
Creates a modulator.
# Examples
```no_run
# use kira::{AudioManager, AudioManagerSettings, DefaultBackend};
use kira::modulator::lfo::LfoBuilder;
# let mut manager = AudioManager::<DefaultBackend>::new(AudioManagerSettings::default())?;
let modulator = manager.add_modulator(LfoBuilder::new())?;
# Result::<(), Box<dyn std::error::Error>>::Ok(())
```
*/
pub fn add_modulator<Builder: ModulatorBuilder>(
&mut self,
builder: Builder,
) -> Result<Builder::Handle, ResourceLimitReached> {
let key = self
.resource_controllers
.modulator_controller
.try_reserve()?;
let id = ModulatorId(key);
let (modulator, handle) = builder.build(id);
self.resource_controllers
.modulator_controller
.insert_with_key(key, modulator);
Ok(handle)
}
/**
Creates a listener.
# Examples
```no_run
# use kira::{AudioManager, AudioManagerSettings, DefaultBackend};
# let mut manager = AudioManager::<DefaultBackend>::new(AudioManagerSettings::default())?;
// This example uses `glam`, but you can use any math library that has interoperability
// with `mint`.
let listener = manager.add_listener(glam::vec3(0.0, 0.0, 0.0), glam::Quat::IDENTITY)?;
# Result::<(), Box<dyn std::error::Error>>::Ok(())
```
*/
pub fn add_listener(
&mut self,
position: impl Into<Value<mint::Vector3<f32>>>,
orientation: impl Into<Value<mint::Quaternion<f32>>>,
) -> Result<ListenerHandle, ResourceLimitReached> {
let key = self
.resource_controllers
.listener_controller
.try_reserve()?;
let id = ListenerId(key);
let (listener, handle) = Listener::new(id, position.into().to_(), orientation.into().to_());
self.resource_controllers
.listener_controller
.insert_with_key(key, listener);
Ok(handle)
}
/**
Returns a handle to the main mixer track.
# Examples
Use the main track handle to adjust the volume of all audio:
```no_run
# use kira::{AudioManager, AudioManagerSettings, DefaultBackend};
use kira::Tween;
# let mut manager = AudioManager::<DefaultBackend>::new(AudioManagerSettings::default())?;
manager.main_track().set_volume(-6.0, Tween::default());
# Result::<(), Box<dyn std::error::Error>>::Ok(())
```
*/
#[must_use]
pub fn main_track(&mut self) -> &mut MainTrackHandle {
&mut self.resource_controllers.main_track_handle
}
/// Returns the number of mixer sub-tracks that can exist at a time.
#[must_use]
pub fn sub_track_capacity(&self) -> usize {
self.resource_controllers.sub_track_controller.capacity()
}
/// Returns the number of mixer send tracks that can exist at a time.
#[must_use]
pub fn send_track_capacity(&self) -> usize {
self.resource_controllers.send_track_controller.capacity()
}
/// Returns the number of clocks that can exist at a time.
#[must_use]
pub fn clock_capacity(&self) -> usize {
self.resource_controllers.clock_controller.capacity()
}
/// Returns the number of modulators that can exist at a time.
#[must_use]
pub fn modulator_capacity(&self) -> usize {
self.resource_controllers.modulator_controller.capacity()
}
/// Returns the number of mixer sub-tracks that currently exist.
#[must_use]
pub fn num_sub_tracks(&self) -> usize {
self.resource_controllers.sub_track_controller.len()
}
/// Returns the number of mixer send tracks that currently exist.
#[must_use]
pub fn num_send_tracks(&self) -> usize {
self.resource_controllers.send_track_controller.len()
}
/// Returns the number of clocks that currently exist.
#[must_use]
pub fn num_clocks(&self) -> usize {
self.resource_controllers.clock_controller.len()
}
/// Returns the number of modulators that currently exist.
#[must_use]
pub fn num_modulators(&self) -> usize {
self.resource_controllers.modulator_controller.len()
}
/// Returns a mutable reference to this manager's backend.
#[must_use]
pub fn backend_mut(&mut self) -> &mut B {
&mut self.backend
}
}