On this page
The sound engine
Sound in Refractor 2 is two layers: an engine in its own library (BF2Audio.dll) that
knows templates, instances, samples and a device, and the game's glue that decides what plays when: a weapon's
fire, an engine's hum, a footstep, the commander's voice. The port reproduces both, down to the software mixer
and the Vorbis decoder, because what a player hears first is what is missing.
Sound templates#
A sound is an object template like any other: ObjectTemplate.create Sound <name>.
| Property | Meaning |
|---|---|
soundFilename | one file, or several split by commas: the variations |
loopCount | 0 loops for ever; 1 plays once |
is3dSound | positioned in the world, or flat |
volume, pitch | the base values; a tweak line multiplies them |
minDistance, halfVolumeDistance | the two distances of the gain curve |
volumeEnvelope, pitchEnvelope | curves over a control value, such as an engine's speed |
stopType | how a playing sample ends when its sound is stopped |
lowSamples, mediumSamples | how many of the files are used at the lower sound qualities |
coneInnerAngle, coneOuterAngle, coneOuterVolume | a directed sound |
reverbLevel, volumeGroup | the send to the reverb, the group fader it belongs to |
A variation is picked per play: among the files the sound quality allows, a random one that differs from the instance's previous pick (BF2Audio.dll!0x10016a60).
Tweak lines. sound.tweakTemplate name volume pitch minDistance halfVolumeDistance reverb radius stores six multipliers and applies all six bases again. The two tweak files of Battlefield 2 have 3,840 such lines. A template without a half volume distance gets twice its minimum distance when a tweak line re-applies it, which is how 2,755 of the game's templates get their curve.
Sounds nobody wrote a template for#
Many sounds have no create Sound line at all. When a template of certain types is created, its post-create hook makes Sound templates named S_<owner>_<suffix> and sets their engine values directly; the game's scripts then only select them (activeSafe) and name a file.
| Owner type | Sounds the hook makes |
|---|---|
| Engine | RotationRpm, Idle, Rpm1, Rpm2, Load (BF2.exe!0x00650df0, EngineSound::initTemplates 0x007e1e40) |
| RotationalBundle, Wing, LandingGear, Camera | RotationRpm |
| Spring | Rotation |
| Soldier | Death, Revive, Swim, Swim_Still, Swim_Sprint |
| a weapon's sound component | Fire1P, Fire1P_Outdoor, Fire3P, BoltClick, TriggerClick, SwitchFireRate, Reload1P, Reload3P, .. |
| a projectile's sound component | Looping |
| a vehicle (PlayerControlObject) | Ambient, AmbientDamaged |
A mod that wonders why its S_myjeep_Engine_Idle has a minimum distance of 3 it never wrote: the hook wrote it.
The gain over the distance#
The device uses the inverse-distance model, clamped at the minimum distance. recompute (BF2Audio.dll!0x10015fc0) turns the template's two distances into the model's rolloff:
min = max(min, 0.01)
if half <= min + 0.01: half = 0; rolloff = 1
else: v = volume * 0.511872
rolloff = v > FLT_EPSILON ? (1/v - 1) * min / (half - min) : 1
gain(d) = min / (min + rolloff * (d - min)) for d >= minSo at the half volume distance the gain is volume x 0.511872, whatever the volume: a louder sound falls off faster to arrive there. There is no maximum distance in the model itself; one is derived for the culling.
One sample's life#
- The play request (
0x10006180). A 3D sound that does not loop for ever (its template's loop count is not- and that is at least 5 m away and outside its minimum stance is culled, never started, when it is beyond its maximum distance or its gain would be under 0.003 0x10004fa0`).
- The delay by distance (
0x10006880). A one-shot 3D sound starts late by the time sound takes to arrive:floor((d - threshold) x factor x 0.002915452 x 30)ticks, 0.002915452 being a second over 343 metres. An explosion 343 m away is heard a second after it is seen. The waiting samples sit in a heap ordered by their start tick. - A slot. A sound instance holds at most two samples at a time (
0x10016b80), and accepts one a frame. The slot is chosen by the instance's policy (SoundSource::chooseSlot0x10016760): the next one, or, for positioned samples, a weighing of front against back, right against left, age and distance; a sample already in the slot is stopped hard. - The mix, every engine update: the distance gain; the 2D / 3D balance; occlusion from a ray cast by the game (a stored value that moves at most 0.1 an update toward the new one); the tinnitus effect, which turns everything else down along its envelope; the cone; Doppler; the reverb send.
- The voice limit. When the device's sources are used up, a new sample steals one by priority.
Engine time is ticks of 1/30 s, and every float-to-int in the library truncates (an inline fistp with the rounding control set to chop): the same trap as the weapons' timers (weapons).
Engine sounds#
A vehicle's engine has four instances: Idle, Rpm1, Rpm2 and Load (EngineSound, constructor BF2.exe!0x007e2150). Their volume and pitch envelopes are read at a control value that follows the engine's speed (engine, gearbox, wheels); EngineSound::update (0x007e2840):
old style: value = |rpm x 0.8333333|
new style: load += clamp(on x throttle - load, -0.2, 0.2)
Rpm1's scale = clamp(1 - load, 0, 1) (coasting)
Rpm2's scale = clamp(load, 0, 1) (under load)
value = clamp(audioRpm x 0.9090909, 0, 1)Rpm1is heard without load andRpm2under load; the load crossfades them, at most 0.2 a tick.- The audio rpm is smoothed toward its target with a critically damped step (
smooth_in_out0x006dc6f0) and gets a small random offset that depends on the ground's material and the wheel's speed, and a sway: a sine whose amplitude ramps after each gear change, halved on a downshift (updateSwayEffect0x007e2530). - A gear change plays the
Loadsound once. - Stopping an engine points
Idle's envelopes at zero and stops the others; a plane or a helicopter above the ground keeps running when its pilot leaves.
Ours: bf2_audio::engine_sound, verified against the original's functions; on the client the engine's speed of a remote vehicle comes from its ghost (ghosts).
Music#
Music.cpp plays one streamed file on a source outside the engine's pool, with twelve buffers of 8 KiB, from a thread of its own (BF2Audio.dll!0x1000fb20): every 10 ms it sets the gain and refills buffers.
Music::stop(seconds)with a time above 0 asks for a fade; the thread lowers a factor by0.01 / secondsan iteration and ends when it reaches 0.- The volume is the music group's fader, read on the main thread and handed over as a whole number of thousandths.
The game's main thread runs the x87 at 24 bits once the Direct3D device exists. The music thread is a plain thread that never loads a control word, so it keeps the 53-bit default; a 24-bit model of the fade differs from the original. The port's fade runs in doubles for that reason (float precision).
Voice-over and radio#
VoiceMessages (GameLogic::loadVoiceMessages BF2.exe!0x004edb40) is a registry of spoken lines, loaded at level load after the level's Init.con, so the two teams' languages are known:
- the help voice speaks the player's language (
common/sound/<language>), falling back to English when the language has no voice files; - the radio voices speak each team's language (
gameLogic.setTeamLanguagein the level'sInit.con), unless the player chose English-only voices; a dedicated server, which has no audio settings, uses the one language; Common/Sound/VoiceMessages.conregisters the lines in four files: triggered automatically, the commander's and squad leaders', help, and triggered by a player (the radio rose).
The server routes a radio message to the players who should hear it; the client plays the file and shows the text. Ours: bf2_audio::voice. The whole path of a call, the comm rose and a soldier's own voice: radio and voices.
The device underneath#
The original mixes in software in BF2OpenAL.dll (a mixer, an emulation of EAX 3.0, a reverb). The port reproduces that device bit for bit (bf2_audio::al) and drives it through the same calls as the original's engine; the Ogg Vorbis decoder (libvorbis 1.0 as linked) is ported bit for bit too, in the crate bf2-vorbis. The browser client's audio runs in an audio worklet (crates/bf2-audio-worklet).
How it is tested#
- The engine's rules (attenuation, culling, scheduling, slot choice, stealing, stop types, the ambient crossfader, the music thread, the engine sounds, the voice registry) run against the original's functions in-process (
crates/bf2-audio/oracle/). - Every sound file, Sound template, ambient trigger, music and voice reference of an install was validated.
- Scenarios listen:
vehicle_engine_sound,sprint_breath, and the invariants fail a run on a pop or a sound that did not resolve (test rigs).
Notes: notes/subsystems/audio.md, notes/formats/audio.md. Code: crates/bf2-audio, crates/bf2-vorbis. The file formats: sounds.
In the code#
The crates this page names, each with its line of docs/release/LAYOUT.md (the list is gathered by the wiki's build from the page itself):
| Crate | What it is |
|---|---|
crates/bf2-audio | the sound system: decoders, sound templates, mixing rules |
crates/bf2-vorbis | Ogg Vorbis decoder |
crates/bf2-audio-worklet | PROGRAM bf2_mixer (wasm): the browser page's sound mixer behind a small C interface |
docs/dev/audio/engine.md · built from bf2-rs e3b4f05 · part of the Battlefield 2 / 2142 / Heroes reimplementation. Not affiliated with EA or DICE.