Files
isaac-port/src/sfx_manager.cpp
T
shweetandClaude Opus 5.5 ddf913f304 Curation round 3: Lua engine, Manager, sound, menus, cutscenes, rooms, item pools, saves; boots past LuaEngine::Init
Seven agents took over LuaEngine (the mod API registration deferred), the rest of Manager (LoadConfigs, fonts, render
surfaces, Update/Render), MusicManager/SFXManager, MenuManager with the title/save/game menus, Cutscene/NightmareScene/
Backdrop, RoomConfig (src/rooms ported and retired) with ItemPool, and PersistentGameData (the original binary save
format) with InfoDisplay. An integration pass moved call sites to the new APIs, declared the taken-over free functions,
fixed two data.cpp crashes (an empty children array, null attribute strings), and made the generator keep a header's own
name where a prototype names another address. Clean build (0 warnings with -Wall -Wextra). build/isaac runs the game's
Lua scripts (without the mod API yet) and stops at reload_resource_paths. 901 functions taken over, boot path 204/615.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 00:53:08 -05:00

402 lines
13 KiB
C++

#include "sfx_manager.h"
#include "data.h"
#include "music_manager.h"
#include "manager.h"
#include <algorithm>
#include <cstdlib>
#include <optional>
// The generator the samples are picked with, as the original's static RNG starts.
constexpr uint32_t SAMPLE_RNG_SEED = 0x12345678;
constexpr uint32_t SAMPLE_RNG_SHIFT_INDEX = 42;
// Below this volume SetAmbientSound stops a sound instead, and it plays one at this frame delay.
constexpr float AMBIENT_VOLUME_MIN = 0.01f;
constexpr int AMBIENT_FRAME_DELAY = 2;
constexpr std::string_view STREAM_EXTENSION = ".ogg";
constexpr std::string_view DOCUMENT_TAG = "#document";
// 00a2add0 Takes a freshly loaded source, setting it back to no loop, full volume, centered and at its own pitch.
void SoundInstance::assign(std::shared_ptr<KAGE::Sound::SoundSource> loaded)
{
reset();
source = std::move(loaded);
if (!source) return;
source->SetLooping(false);
source->SetVolume(1);
source->SetPan(0);
source->SetPitch(1);
}
// 00a2abd0 Lets go of the source, which stops once nothing else holds it.
void SoundInstance::reset()
{
*this = {};
}
// 00a2ac00 Starts the source. A sample starts over, as SampleSourceBase's Play at 00a9fa00 stops it first.
void SoundInstance::Play()
{
if (!source) return;
if (source->type == KAGE::Sound::SOURCE_SAMPLE) source->Stop();
source->Play();
isStarting = true;
isPaused = false;
}
// Stops the source.
void SoundInstance::Stop()
{
if (!source) return;
source->Stop();
isStarting = false;
}
// Pauses the source while it plays or is starting.
void SoundInstance::Pause()
{
if (!source || (!source->IsPlaying() && !isStarting)) return;
source->Pause();
isStarting = false;
isPaused = true;
}
// Carries on after a pause.
void SoundInstance::Resume()
{
if (!source || !isPaused) return;
source->Resume();
isStarting = true;
isPaused = false;
}
// Whether the source plays or was just asked to, forgetting the request once it plays.
bool SoundInstance::IsPlaying()
{
if (!source) return false;
if (isStarting && source->IsPlaying()) isStarting = false;
return source->IsPlaying() || isStarting;
}
// 00a2ac20 Pans the source. Only mono sources pan, so another warns unless centered.
void SoundInstance::SetPan(float pan)
{
if (!source) return;
if (source->spec.channels > 1 && pan != 0)
{
log_printf(LOG_WARN, "Attempting to set pan on non-mono source (%s), this will have no effect\n",
source->path.c_str());
return;
}
source->SetPan(pan);
}
// 0092cfb0 Loads the samples through the mods' redirections. A .wav is loaded now and an .ogg is left to each play.
// The original throws on a path shorter than the extension. Here it is a .wav.
void SoundEffect::Load()
{
for (SoundSample& sample : samples)
{
std::string path = g_manager->modManager.TryRedirectPath(sample.path);
sample.isStream = path.ends_with(STREAM_EXTENSION);
if (!sample.isStream) sample.instance.assign(KAGE::Sound::manager.load_sound(path, KAGE::Sound::SOURCE_SAMPLE));
}
isLoaded = true;
}
// Starts the sample generator where the original's static one starts.
SFXManager::SFXManager()
{
sampleRng.SetSeed(SAMPLE_RNG_SEED, SAMPLE_RNG_SHIFT_INDEX);
}
// The document's root element with this tag, whether the document is that element or holds it.
static std::optional<DataNode> root_find(Data& data, std::string_view tag)
{
if (node_tag(data.root) == tag) return data.root;
if (node_tag(data.root) == DOCUMENT_TAG)
for (DataNode node : node_children(data.root))
if (node_tag(node) == tag) return node;
return std::nullopt;
}
// A <sound>'s samples, from its first <sample> on: every element after that one counts as a sample too.
static void samples_parse(SoundEffect& sound, DataNode node, std::string_view root)
{
bool isSampleFound = false;
for (DataNode child : node_children(node))
{
isSampleFound = isSampleFound || node_tag(child) == "sample";
if (!isSampleFound) continue;
if ((int)sound.samples.size() >= SOUND_SAMPLE_LIMIT)
{
log_printf(LOG_INFO, "[warn] Sound Effect %d exceeding max samples.\n", sound.id);
return;
}
SoundSample& sample = sound.samples.emplace_back();
std::string_view path = node_attr(child, "path");
std::string_view weight = node_attr(child, "weight");
if (!path.empty()) sample.path = std::string(root).append(path);
if (!weight.empty()) sample.weight = std::atoi(weight.data());
}
}
// 0092d140 Loads a sounds.xml and every sound in it. The game's own replaces all the sounds, each at its id. A mod's
// adds its sounds after the last id, whatever id they give. Whether the file opened.
// The original writes a negative id out of the list, and crashes without a <sounds> root. Here both are skipped.
// A sound's lastPlayFrame and volume start uninitialised in the original. Here they start at 0.
bool SFXManager::LoadConfig(std::string_view path, ModEntry* mod)
{
Data data;
data_load(data, path);
if (!data.isLoaded) return false;
if (!mod)
{
sounds.clear();
sounds.resize(SOUND_EFFECT_COUNT);
}
loadedCount = 0;
std::optional<DataNode> root = root_find(data, "sounds");
if (!root) return false;
std::string_view rootPath = node_attr(*root, "root");
for (DataNode node : node_children(*root))
{
SoundEffect sound;
sound.id = std::atoi(node_attr(node, "id").data());
sound.name = node_attr(node, "name");
if (mod)
{
sound.id = (int)sounds.size();
sounds.emplace_back();
}
else if (sound.id < 0 || sound.id >= SOUND_EFFECT_COUNT)
{
if (sound.id > 0)
log_printf(LOG_ASSERT, "Sound Effect %d out of bounds! Update NUM_SOUND_EFFECTS.\n", sound.id);
continue;
}
SoundEffect& slot = sounds[sound.id];
slot = std::move(sound);
samples_parse(slot, node, rootPath);
slot.Load();
loadedCount++;
}
return true;
}
// The sound under an id, or null when the id is out of range.
SoundEffect* SFXManager::sound_find(int soundId)
{
return soundId >= 0 && soundId < (int)sounds.size() ? &sounds[soundId] : nullptr;
}
// The loaded sound under an id, warning when it has no samples.
static SoundEffect* sound_loaded_find(SFXManager& manager, int soundId)
{
SoundEffect* sound = manager.sound_find(soundId);
if (!sound) return nullptr;
if (sound->samples.empty())
{
log_printf(LOG_INFO, "[warn] Sound %d has no samples.\n", soundId);
return nullptr;
}
return sound->isLoaded ? sound : nullptr;
}
// Calls apply on each of the sound's samples that plays.
template <typename Apply> static void samples_playing_apply(SoundEffect* sound, Apply apply)
{
if (!sound) return;
for (SoundSample& sample : sound->samples)
if (sample.instance.IsPlaying()) apply(sample);
}
// A volume as the options and the volume modifier scale it.
static float volume_scale(SFXManager& manager, float volume)
{
return std::max(manager.volumeModifier, 0.0f) * volume * g_manager->optionsConfig.sfxVolume;
}
// 0092cf40 Loads a sound ahead of its first play.
void SFXManager::Preload(int soundId)
{
SoundEffect* sound = sound_find(soundId);
if (!sound || sound->isLoaded) return;
log_printf(LOG_INFO, "Preload sound %d.\n", soundId);
sound->Load();
loadedCount++;
}
// 0092dc30 Plays one of a sound's samples at random, unless the sound played less than its last frame delay ago, in
// frames of 30 a second. A streamed sample loads anew from its own path, which the mods do not redirect.
// The volume is scaled by the options and the volume modifier, up to 1, and the pan is set once it plays.
// Called without a pan (0092df00), it pans to the center.
void SFXManager::Play(int soundId, SoundPlay play)
{
SoundEffect* sound = sound_find(soundId);
if (!sound) return;
if (sound->samples.empty())
{
log_printf(LOG_INFO, "[warn] Sound %d has no samples.\n", soundId);
return;
}
if (!sound->isLoaded)
{
sound->Load();
log_printf(LOG_INFO, "[warn] Sound %d was not preloaded.\n", soundId);
loadedCount++;
}
int frame = (int)(g_manager->framecount / 2);
if (sound->nextPlayFrame > frame && sound->nextPlayFrame >= 0) return;
sound->volume = play.volume;
sound->lastPlayFrame = frame;
sound->nextPlayFrame = frame + play.frameDelay;
SoundSample& sample = sound->samples[sampleRng.RandomInt((uint32_t)sound->samples.size())];
SoundInstance& instance = sample.instance;
if (sample.isStream) instance.assign(KAGE::Sound::manager.load_sound(sample.path, KAGE::Sound::SOURCE_STREAM));
if (instance.source)
{
instance.source->SetLooping(play.loop == SOUND_LOOP);
instance.source->SetPitch(play.pitch);
instance.source->SetVolume(std::min(volume_scale(*this, play.volume), 1.0f));
instance.Play();
}
instance.SetPan(play.pan);
}
// 0092df40 Sets the volume of a sound's playing samples, scaled as Play scales it, and remembers it.
void SFXManager::AdjustVolume(int soundId, float volume)
{
SoundEffect* sound = sound_loaded_find(*this, soundId);
if (sound) sound->volume = volume;
float scaled = std::min(volume_scale(*this, volume), 1.0f);
samples_playing_apply(sound, [&](SoundSample& sample) { sample.instance.source->SetVolume(scaled); });
}
// 0092e050 Sets the pitch of a sound's playing samples.
void SFXManager::AdjustPitch(int soundId, float pitch)
{
samples_playing_apply(sound_loaded_find(*this, soundId),
[&](SoundSample& sample) { sample.instance.source->SetPitch(pitch); });
}
// 0092e120 Pans a sound's playing samples.
// The original reads before the list for a negative id. Here it is out of range.
void SFXManager::pan_adjust(int soundId, float pan)
{
samples_playing_apply(sound_loaded_find(*this, soundId), [&](SoundSample& sample) { sample.instance.SetPan(pan); });
}
// 0092e230 Stops a sound's playing samples and lets it play again right away.
void SFXManager::Stop(int soundId)
{
SoundEffect* sound = sound_loaded_find(*this, soundId);
if (sound) sound->nextPlayFrame = -1;
samples_playing_apply(sound, [](SoundSample& sample) { sample.instance.Stop(); });
}
// 0092e300 Stops every playing sample that loops.
void SFXManager::StopLoopingSounds()
{
for (SoundEffect& sound : sounds)
if (sound.isLoaded)
samples_playing_apply(&sound, [](SoundSample& sample) {
if (sample.instance.source->isLooping) sample.instance.Stop();
});
}
// 0092e430 Applies the volume modifier to every playing sample, at the volume its sound last played at.
// Unlike Play it does not cap the volume at 1.
void SFXManager::ClearVolumeModifier()
{
for (SoundEffect& sound : sounds)
if (sound.isLoaded)
samples_playing_apply(&sound, [&](SoundSample& sample) {
sample.instance.source->SetVolume(volume_scale(*this, sound.volume));
});
}
// Sets the volume modifier, applying it at once when it changes, and lets it return to 1 at the usual step.
void SFXManager::volume_modifier_set(float modifier)
{
if (volumeModifier != modifier)
{
volumeModifier = modifier;
ClearVolumeModifier();
}
volumeModifierStep = VOLUME_MODIFIER_STEP;
}
// Moves the volume modifier a step back toward 1 and applies it, as Manager::Update does while a game runs unpaused.
void SFXManager::volume_modifier_update()
{
if (volumeModifier == 1 || volumeModifierStep == 0) return;
float distance = volumeModifier - 1;
if (std::abs(distance) <= volumeModifierStep) volumeModifier = 1;
else volumeModifier += volumeModifier >= 1 ? -volumeModifierStep : volumeModifierStep;
ClearVolumeModifier();
}
// 0092e560 Whether any of a sound's samples plays.
bool SFXManager::IsPlaying(int soundId)
{
SoundEffect* sound = sound_find(soundId);
if (!sound || sound->samples.empty() || !sound->isLoaded) return false;
return std::any_of(sound->samples.begin(), sound->samples.end(),
[](SoundSample& sample) { return sample.instance.IsPlaying(); });
}
// 0092e620 Keeps a looping room sound going at a volume and pitch, starting it (through the fart seed's override) when
// it is silent and stopping it when the volume drops to almost nothing.
void SFXManager::SetAmbientSound(int soundId, float volume, float pitch)
{
if (volume <= AMBIENT_VOLUME_MIN)
{
if (IsPlaying(soundId)) Stop(soundId);
return;
}
if (IsPlaying(soundId))
{
AdjustVolume(soundId, volume);
AdjustPitch(soundId, pitch);
return;
}
int playedId = soundId;
seed_fart_sound_override(&playedId);
Play(playedId, {.volume = volume, .frameDelay = AMBIENT_FRAME_DELAY, .loop = SOUND_LOOP, .pitch = pitch});
}
// 0092e6e0 The volume a playing sound was last given, or 0.
float SFXManager::GetAmbientSoundVolume(int soundId)
{
SoundEffect* sound = sound_loaded_find(*this, soundId);
return sound && IsPlaying(soundId) ? sound->volume : 0;
}