AVA2 cross-platform client parity baseline
This commit is contained in:
@@ -0,0 +1,578 @@
|
||||
#include "SoundManager.h"
|
||||
|
||||
#define DR_MP3_IMPLEMENTATION
|
||||
#include "third_party/extern_include/dr_mp3.h"
|
||||
|
||||
#include <iostream>
|
||||
#include <filesystem>
|
||||
#include <fstream>
|
||||
#include <sstream>
|
||||
#include <cmath>
|
||||
#include <algorithm>
|
||||
|
||||
namespace ava2 {
|
||||
|
||||
namespace {
|
||||
|
||||
inline std::string ToLower(std::string s) {
|
||||
for (char& c : s) {
|
||||
if (c >= 'A' && c <= 'Z') c = static_cast<char>(c + 32);
|
||||
else if (c == '\\') c = '/';
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
inline void CrossProduct(float ax, float ay, float az, float bx, float by, float bz, float& rx, float& ry, float& rz) {
|
||||
rx = ay * bz - az * by;
|
||||
ry = az * bx - ax * bz;
|
||||
rz = ax * by - ay * bx;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
SoundManager& SoundManager::Instance() {
|
||||
static SoundManager s_instance;
|
||||
return s_instance;
|
||||
}
|
||||
|
||||
SoundManager::SoundManager() {
|
||||
m_instances.resize(MAX_SOUND_INSTANCES);
|
||||
for (size_t i = 0; i < MAX_SOUND_INSTANCES; ++i) {
|
||||
m_instances[i].id = static_cast<int>(i + 1);
|
||||
}
|
||||
}
|
||||
|
||||
SoundManager::~SoundManager() {
|
||||
Destroy();
|
||||
}
|
||||
|
||||
bool SoundManager::Initialize() {
|
||||
if (m_initialized) return true;
|
||||
|
||||
if (!SDL_InitSubSystem(SDL_INIT_AUDIO)) {
|
||||
SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION, "SDL_InitSubSystem(SDL_INIT_AUDIO) warning: %s", SDL_GetError());
|
||||
}
|
||||
|
||||
m_deviceSpec.format = SDL_AUDIO_F32;
|
||||
m_deviceSpec.channels = 2;
|
||||
m_deviceSpec.freq = 44100;
|
||||
|
||||
m_deviceId = SDL_OpenAudioDevice(SDL_AUDIO_DEVICE_DEFAULT_PLAYBACK, &m_deviceSpec);
|
||||
if (m_deviceId != 0) {
|
||||
SDL_ResumeAudioDevice(m_deviceId);
|
||||
SDL_Log("SoundManager: Audio device opened successfully (ID %u, 44.1kHz Stereo F32)", m_deviceId);
|
||||
} else {
|
||||
SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION, "SoundManager: Running without physical audio device: %s", SDL_GetError());
|
||||
}
|
||||
|
||||
// Initialize SFX streams
|
||||
for (size_t i = 0; i < MAX_SOUND_INSTANCES; ++i) {
|
||||
m_instances[i].inUse = false;
|
||||
m_instances[i].stream = SDL_CreateAudioStream(&m_deviceSpec, &m_deviceSpec);
|
||||
if (m_instances[i].stream && m_deviceId != 0) {
|
||||
SDL_BindAudioStream(m_deviceId, m_instances[i].stream);
|
||||
}
|
||||
}
|
||||
|
||||
// Initialize Music streaming channels
|
||||
for (size_t c = 0; c < 2; ++c) {
|
||||
m_musicChannels[c].state = MusicState::Off;
|
||||
m_musicChannels[c].stream = SDL_CreateAudioStream(&m_deviceSpec, &m_deviceSpec);
|
||||
if (m_musicChannels[c].stream && m_deviceId != 0) {
|
||||
SDL_BindAudioStream(m_deviceId, m_musicChannels[c].stream);
|
||||
}
|
||||
}
|
||||
|
||||
m_initialized = true;
|
||||
return true;
|
||||
}
|
||||
|
||||
void SoundManager::Destroy() {
|
||||
if (!m_initialized) return;
|
||||
m_initialized = false;
|
||||
bool sdl_alive = (SDL_WasInit(SDL_INIT_AUDIO) != 0);
|
||||
|
||||
for (size_t i = 0; i < MAX_SOUND_INSTANCES; ++i) {
|
||||
if (m_instances[i].stream) {
|
||||
if (m_deviceId != 0 && sdl_alive) SDL_UnbindAudioStream(m_instances[i].stream);
|
||||
if (sdl_alive) SDL_DestroyAudioStream(m_instances[i].stream);
|
||||
m_instances[i].stream = nullptr;
|
||||
}
|
||||
m_instances[i].inUse = false;
|
||||
}
|
||||
|
||||
for (size_t c = 0; c < 2; ++c) {
|
||||
if (m_musicChannels[c].stream) {
|
||||
if (m_deviceId != 0 && sdl_alive) SDL_UnbindAudioStream(m_musicChannels[c].stream);
|
||||
if (sdl_alive) SDL_DestroyAudioStream(m_musicChannels[c].stream);
|
||||
m_musicChannels[c].stream = nullptr;
|
||||
}
|
||||
m_musicChannels[c].state = MusicState::Off;
|
||||
}
|
||||
|
||||
if (m_deviceId != 0 && sdl_alive) {
|
||||
SDL_CloseAudioDevice(m_deviceId);
|
||||
m_deviceId = 0;
|
||||
}
|
||||
|
||||
m_soundCache.clear();
|
||||
}
|
||||
|
||||
std::string SoundManager::ResolveAudioPath(const std::string& filename) const {
|
||||
if (filename.empty()) return "";
|
||||
|
||||
std::string clean = filename;
|
||||
for (char& c : clean) {
|
||||
if (c == '\\') c = '/';
|
||||
}
|
||||
// Strip drive letters like "d:/" or "D:/"
|
||||
if (clean.size() >= 3 && clean[1] == ':' && clean[2] == '/') {
|
||||
clean = clean.substr(3);
|
||||
}
|
||||
|
||||
std::vector<std::string> candidates = {
|
||||
clean,
|
||||
ToLower(clean),
|
||||
"sound/" + clean,
|
||||
"bgm/" + clean,
|
||||
"BGM/" + clean,
|
||||
"/Users/shen/Work/Code/Metin2/AVA2/TEST/1. Client DEV/pack_maker/Sound/" + clean,
|
||||
"/Users/shen/Work/Code/Metin2/AVA2/TEST/1. Client DEV/pack_maker/BGM/" + clean,
|
||||
"/Users/shen/Work/Code/Metin2/AVA2/TEST/1. Client DEV/pack_maker/ETC/" + clean,
|
||||
"/Users/shen/Work/Code/Metin2/AVA2/TEST/1. Client DEV/pack_maker/Sound/sound/" + clean,
|
||||
"/Users/shen/Work/Code/Metin2/AVA2/TEST/1. Client DEV/pack_maker/BGM/bgm/" + clean,
|
||||
"build/dev/" + clean
|
||||
};
|
||||
|
||||
for (const auto& path : candidates) {
|
||||
if (std::filesystem::exists(path)) {
|
||||
return path;
|
||||
}
|
||||
}
|
||||
return clean;
|
||||
}
|
||||
|
||||
const SoundManager::CachedAudio* SoundManager::GetOrLoadAudio(const std::string& filename) {
|
||||
std::string key = ToLower(filename);
|
||||
auto it = m_soundCache.find(key);
|
||||
if (it != m_soundCache.end()) {
|
||||
return &it->second;
|
||||
}
|
||||
|
||||
std::string resolved = ResolveAudioPath(filename);
|
||||
if (!std::filesystem::exists(resolved)) {
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
CachedAudio audio;
|
||||
bool ok = false;
|
||||
std::string ext = "";
|
||||
auto dotPos = resolved.rfind('.');
|
||||
if (dotPos != std::string::npos) {
|
||||
ext = ToLower(resolved.substr(dotPos));
|
||||
}
|
||||
|
||||
if (ext == ".wav") {
|
||||
ok = LoadWavFile(resolved, audio);
|
||||
} else if (ext == ".mp3") {
|
||||
ok = LoadMp3File(resolved, audio);
|
||||
}
|
||||
|
||||
if (ok) {
|
||||
auto [inserted_it, _] = m_soundCache.emplace(key, std::move(audio));
|
||||
return &inserted_it->second;
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
bool SoundManager::LoadWavFile(const std::string& resolvedPath, CachedAudio& outAudio) {
|
||||
SDL_AudioSpec file_spec{};
|
||||
Uint8* wav_buffer = nullptr;
|
||||
Uint32 wav_length = 0;
|
||||
|
||||
if (!SDL_LoadWAV(resolvedPath.c_str(), &file_spec, &wav_buffer, &wav_length)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
outAudio.spec = file_spec;
|
||||
outAudio.data.assign(wav_buffer, wav_buffer + wav_length);
|
||||
SDL_free(wav_buffer);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool SoundManager::LoadMp3File(const std::string& resolvedPath, CachedAudio& outAudio) {
|
||||
drmp3_config config{};
|
||||
drmp3_uint64 total_pcm_frames = 0;
|
||||
float* pcm = drmp3_open_file_and_read_pcm_frames_f32(resolvedPath.c_str(), &config, &total_pcm_frames, nullptr);
|
||||
if (!pcm) {
|
||||
return false;
|
||||
}
|
||||
|
||||
outAudio.spec.format = SDL_AUDIO_F32;
|
||||
outAudio.spec.channels = static_cast<Uint8>(config.channels);
|
||||
outAudio.spec.freq = static_cast<int>(config.sampleRate);
|
||||
|
||||
size_t byte_count = total_pcm_frames * config.channels * sizeof(float);
|
||||
outAudio.data.resize(byte_count);
|
||||
std::memcpy(outAudio.data.data(), pcm, byte_count);
|
||||
|
||||
drmp3_free(pcm, nullptr);
|
||||
return true;
|
||||
}
|
||||
|
||||
float SoundManager::ConvertRatioVolumeToApplyVolume(float ratio) const {
|
||||
if (ratio < 0.1f) return std::max(0.0f, ratio);
|
||||
return std::pow(10.0f, -1.0f + ratio);
|
||||
}
|
||||
|
||||
float SoundManager::ConvertGradeVolumeToApplyVolume(int grade) const {
|
||||
return ConvertRatioVolumeToApplyVolume(static_cast<float>(grade) / 5.0f);
|
||||
}
|
||||
|
||||
void SoundManager::SetSoundVolume(float volume) {
|
||||
m_soundVolume = std::clamp(volume, 0.0f, 1.0f);
|
||||
m_backupSoundVolume = m_soundVolume;
|
||||
}
|
||||
|
||||
void SoundManager::SetSoundVolumeRatio(float ratio) {
|
||||
SetSoundVolume(ConvertRatioVolumeToApplyVolume(ratio));
|
||||
}
|
||||
|
||||
void SoundManager::SetSoundVolumeGrade(int grade) {
|
||||
SetSoundVolume(ConvertGradeVolumeToApplyVolume(grade));
|
||||
}
|
||||
|
||||
void SoundManager::SetMusicVolume(float volume) {
|
||||
m_musicVolume = std::clamp(volume, 0.0f, 1.0f);
|
||||
m_backupMusicVolume = m_musicVolume;
|
||||
|
||||
for (auto& ch : m_musicChannels) {
|
||||
if (ch.state == MusicState::Play) {
|
||||
ch.volume = m_musicVolume;
|
||||
if (ch.stream) SDL_SetAudioStreamGain(ch.stream, ch.volume);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void SoundManager::SetMusicVolumeRatio(float ratio) {
|
||||
SetMusicVolume(ConvertRatioVolumeToApplyVolume(ratio));
|
||||
}
|
||||
|
||||
void SoundManager::SetMusicVolumeGrade(int grade) {
|
||||
SetMusicVolume(ConvertGradeVolumeToApplyVolume(grade));
|
||||
}
|
||||
|
||||
void SoundManager::SaveVolume() {
|
||||
m_backupSoundVolume = m_soundVolume;
|
||||
m_backupMusicVolume = m_musicVolume;
|
||||
}
|
||||
|
||||
void SoundManager::RestoreVolume() {
|
||||
SetSoundVolume(m_backupSoundVolume);
|
||||
SetMusicVolume(m_backupMusicVolume);
|
||||
}
|
||||
|
||||
void SoundManager::SetPosition(float fx, float fy, float fz) {
|
||||
m_listenerX = fx;
|
||||
m_listenerY = fy;
|
||||
m_listenerZ = fz;
|
||||
}
|
||||
|
||||
void SoundManager::SetDirection(float fxDir, float fyDir, float fzDir, float fxUp, float fyUp, float fzUp) {
|
||||
float len = std::sqrt(fxDir*fxDir + fyDir*fyDir + fzDir*fzDir);
|
||||
if (len > 1e-4f) {
|
||||
m_listenerDirX = fxDir / len;
|
||||
m_listenerDirY = fyDir / len;
|
||||
m_listenerDirZ = fzDir / len;
|
||||
}
|
||||
float ulen = std::sqrt(fxUp*fxUp + fyUp*fyUp + fzUp*fzUp);
|
||||
if (ulen > 1e-4f) {
|
||||
m_listenerUpX = fxUp / ulen;
|
||||
m_listenerUpY = fyUp / ulen;
|
||||
m_listenerUpZ = fzUp / ulen;
|
||||
}
|
||||
}
|
||||
|
||||
void SoundManager::PlaySound2D(const std::string& filename) {
|
||||
if (m_soundVolume <= 0.0f) return;
|
||||
const auto* audio = GetOrLoadAudio(filename);
|
||||
if (!audio || audio->data.empty()) return;
|
||||
|
||||
SoundInstance* target = nullptr;
|
||||
for (auto& inst : m_instances) {
|
||||
if (!inst.inUse || (inst.stream && SDL_GetAudioStreamAvailable(inst.stream) == 0)) {
|
||||
target = &inst;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (!target) target = &m_instances[0];
|
||||
|
||||
target->filename = filename;
|
||||
target->is3D = false;
|
||||
target->volume = m_soundVolume;
|
||||
target->inUse = true;
|
||||
|
||||
if (target->stream) {
|
||||
SDL_ClearAudioStream(target->stream);
|
||||
SDL_SetAudioStreamFormat(target->stream, &audio->spec, &m_deviceSpec);
|
||||
SDL_SetAudioStreamGain(target->stream, m_soundVolume);
|
||||
SDL_PutAudioStreamData(target->stream, audio->data.data(), static_cast<int>(audio->data.size()));
|
||||
SDL_FlushAudioStream(target->stream);
|
||||
}
|
||||
}
|
||||
|
||||
void SoundManager::PlaySound3D(float fx, float fy, float fz, const std::string& filename, int playCount) {
|
||||
if (m_soundVolume <= 0.0f) return;
|
||||
const auto* audio = GetOrLoadAudio(filename);
|
||||
if (!audio || audio->data.empty()) return;
|
||||
|
||||
float dx = fx - m_listenerX;
|
||||
float dy = fy - m_listenerY;
|
||||
float dz = fz - m_listenerZ;
|
||||
float dist = std::sqrt(dx*dx + dy*dy + dz*dz);
|
||||
|
||||
// Distance attenuation matching Metin2 formula: 1.0 / (1.0 + (dist / scale))
|
||||
float attn = 1.0f / (1.0f + std::max(0.0f, dist - 80.0f) / m_soundScale);
|
||||
float gain = std::clamp(attn * m_soundVolume, 0.0f, 1.0f);
|
||||
if (gain < 0.005f) return; // Inaudible
|
||||
|
||||
SoundInstance* target = nullptr;
|
||||
for (auto& inst : m_instances) {
|
||||
if (!inst.inUse || (inst.stream && SDL_GetAudioStreamAvailable(inst.stream) == 0)) {
|
||||
target = &inst;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!target) target = &m_instances[0];
|
||||
|
||||
target->filename = filename;
|
||||
target->is3D = true;
|
||||
target->worldX = fx; target->worldY = fy; target->worldZ = fz;
|
||||
target->scale = m_soundScale;
|
||||
target->volume = gain;
|
||||
target->playCount = playCount;
|
||||
target->inUse = true;
|
||||
|
||||
if (target->stream) {
|
||||
SDL_ClearAudioStream(target->stream);
|
||||
SDL_SetAudioStreamFormat(target->stream, &audio->spec, &m_deviceSpec);
|
||||
SDL_SetAudioStreamGain(target->stream, gain);
|
||||
SDL_PutAudioStreamData(target->stream, audio->data.data(), static_cast<int>(audio->data.size()));
|
||||
SDL_FlushAudioStream(target->stream);
|
||||
}
|
||||
}
|
||||
|
||||
int SoundManager::PlayAmbienceSound3D(float fx, float fy, float fz, const std::string& filename, int playCount) {
|
||||
float oldScale = m_soundScale;
|
||||
m_soundScale = m_ambienceScale;
|
||||
PlaySound3D(fx, fy, fz, filename, playCount);
|
||||
m_soundScale = oldScale;
|
||||
return m_nextInstanceId++;
|
||||
}
|
||||
|
||||
void SoundManager::StopSound3D(int index) {
|
||||
for (auto& inst : m_instances) {
|
||||
if (inst.id == index && inst.inUse) {
|
||||
if (inst.stream) SDL_ClearAudioStream(inst.stream);
|
||||
inst.inUse = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void SoundManager::StopAllSound3D() {
|
||||
for (auto& inst : m_instances) {
|
||||
if (inst.is3D && inst.inUse) {
|
||||
if (inst.stream) SDL_ClearAudioStream(inst.stream);
|
||||
inst.inUse = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void SoundManager::PlayMusic(const std::string& filename) {
|
||||
FadeInMusic(filename, 10.0f); // Instant / direct start
|
||||
}
|
||||
|
||||
void SoundManager::FadeInMusic(const std::string& filename, float speed) {
|
||||
if (filename.empty()) return;
|
||||
|
||||
// If already playing this music on active channel, ensure it fades in to full volume
|
||||
for (size_t c = 0; c < 2; ++c) {
|
||||
if (m_musicChannels[c].filename == filename && m_musicChannels[c].state != MusicState::Off) {
|
||||
m_musicChannels[c].state = MusicState::FadeIn;
|
||||
m_musicChannels[c].volumeSpeed = speed;
|
||||
m_currentMusicFile = filename;
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// Fade out other music channels
|
||||
FadeOutAllMusic();
|
||||
|
||||
// Select available music channel
|
||||
MusicChannel* ch = &m_musicChannels[0];
|
||||
if (ch->state != MusicState::Off) ch = &m_musicChannels[1];
|
||||
|
||||
const auto* audio = GetOrLoadAudio(filename);
|
||||
if (!audio || audio->data.empty()) return;
|
||||
|
||||
ch->filename = filename;
|
||||
ch->cachedPcm = *audio;
|
||||
ch->playOffsetBytes = 0;
|
||||
ch->volume = (speed > 5.0f) ? m_musicVolume : 0.0f;
|
||||
ch->targetVolume = m_musicVolume;
|
||||
ch->volumeSpeed = speed;
|
||||
ch->state = (speed > 5.0f) ? MusicState::Play : MusicState::FadeIn;
|
||||
m_currentMusicFile = filename;
|
||||
|
||||
if (ch->stream) {
|
||||
SDL_ClearAudioStream(ch->stream);
|
||||
SDL_SetAudioStreamFormat(ch->stream, &ch->cachedPcm.spec, &m_deviceSpec);
|
||||
SDL_SetAudioStreamGain(ch->stream, ch->volume);
|
||||
|
||||
// Pre-buffer first chunk
|
||||
size_t chunk = std::min(ch->cachedPcm.data.size(), static_cast<size_t>(65536));
|
||||
SDL_PutAudioStreamData(ch->stream, ch->cachedPcm.data.data(), static_cast<int>(chunk));
|
||||
ch->playOffsetBytes = chunk;
|
||||
}
|
||||
}
|
||||
|
||||
void SoundManager::FadeOutMusic(const std::string& filename, float speed) {
|
||||
for (size_t c = 0; c < 2; ++c) {
|
||||
if (m_musicChannels[c].filename == filename && m_musicChannels[c].state != MusicState::Off) {
|
||||
m_musicChannels[c].state = MusicState::FadeOut;
|
||||
m_musicChannels[c].volumeSpeed = speed;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void SoundManager::FadeLimitOutMusic(const std::string& filename, float limitVolume, float speed) {
|
||||
for (size_t c = 0; c < 2; ++c) {
|
||||
if (m_musicChannels[c].filename == filename && m_musicChannels[c].state != MusicState::Off) {
|
||||
m_musicChannels[c].state = MusicState::FadeLimitOut;
|
||||
m_musicChannels[c].limitVolume = ConvertRatioVolumeToApplyVolume(limitVolume);
|
||||
m_musicChannels[c].volumeSpeed = speed;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void SoundManager::FadeOutAllMusic() {
|
||||
for (size_t c = 0; c < 2; ++c) {
|
||||
if (m_musicChannels[c].state != MusicState::Off) {
|
||||
m_musicChannels[c].state = MusicState::FadeOut;
|
||||
m_musicChannels[c].volumeSpeed = 0.02f;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void SoundManager::Update(float dt) {
|
||||
if (!m_initialized) return;
|
||||
|
||||
// 1. Update SFX instances
|
||||
for (auto& inst : m_instances) {
|
||||
if (inst.inUse && inst.stream) {
|
||||
if (SDL_GetAudioStreamAvailable(inst.stream) == 0) {
|
||||
inst.inUse = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Update BGM streaming and fading
|
||||
for (size_t c = 0; c < 2; ++c) {
|
||||
auto& ch = m_musicChannels[c];
|
||||
if (ch.state == MusicState::Off || !ch.stream) continue;
|
||||
|
||||
switch (ch.state) {
|
||||
case MusicState::FadeIn:
|
||||
ch.volume = std::min(m_musicVolume, ch.volume + ch.volumeSpeed * dt * 5.0f);
|
||||
if (ch.volume >= m_musicVolume) {
|
||||
ch.volume = m_musicVolume;
|
||||
ch.state = MusicState::Play;
|
||||
}
|
||||
SDL_SetAudioStreamGain(ch.stream, ch.volume);
|
||||
break;
|
||||
case MusicState::FadeOut:
|
||||
ch.volume = std::max(0.0f, ch.volume - ch.volumeSpeed * dt * 5.0f);
|
||||
if (ch.volume <= 0.0f) {
|
||||
ch.volume = 0.0f;
|
||||
ch.state = MusicState::Off;
|
||||
SDL_ClearAudioStream(ch.stream);
|
||||
}
|
||||
SDL_SetAudioStreamGain(ch.stream, ch.volume);
|
||||
break;
|
||||
case MusicState::FadeLimitOut:
|
||||
ch.volume = std::max(ch.limitVolume, ch.volume - ch.volumeSpeed * dt * 5.0f);
|
||||
if (ch.volume <= ch.limitVolume) {
|
||||
ch.volume = ch.limitVolume;
|
||||
ch.state = MusicState::Play;
|
||||
}
|
||||
SDL_SetAudioStreamGain(ch.stream, ch.volume);
|
||||
break;
|
||||
case MusicState::Play:
|
||||
SDL_SetAudioStreamGain(ch.stream, m_musicVolume);
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
// Loop buffering: refill stream when available buffer is low (< 32KB)
|
||||
if (ch.state != MusicState::Off && !ch.cachedPcm.data.empty()) {
|
||||
int avail = SDL_GetAudioStreamAvailable(ch.stream);
|
||||
if (avail < 32768) {
|
||||
size_t remaining = ch.cachedPcm.data.size() - ch.playOffsetBytes;
|
||||
size_t toWrite = std::min(remaining, static_cast<size_t>(32768));
|
||||
if (toWrite > 0) {
|
||||
SDL_PutAudioStreamData(ch.stream, ch.cachedPcm.data.data() + ch.playOffsetBytes, static_cast<int>(toWrite));
|
||||
ch.playOffsetBytes += toWrite;
|
||||
}
|
||||
if (ch.playOffsetBytes >= ch.cachedPcm.data.size()) {
|
||||
// Loop back to beginning
|
||||
ch.playOffsetBytes = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
size_t SoundManager::GetActiveSoundCount() const {
|
||||
size_t count = 0;
|
||||
for (const auto& inst : m_instances) {
|
||||
if (inst.inUse) ++count;
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
bool SoundManager::LoadCharacterSoundScript(const std::string& mssPath, std::vector<CharacterSoundEvent>& outEvents) const {
|
||||
std::string resolved = ResolveAudioPath(mssPath);
|
||||
std::ifstream file(resolved);
|
||||
if (!file.is_open()) return false;
|
||||
|
||||
outEvents.clear();
|
||||
std::string line;
|
||||
while (std::getline(file, line)) {
|
||||
if (line.empty() || line[0] == '#') continue;
|
||||
std::istringstream iss(line);
|
||||
std::string token;
|
||||
iss >> token;
|
||||
|
||||
if (token.rfind("SoundData", 0) == 0 && token != "SoundDataCount") {
|
||||
float timeVal = 0.0f;
|
||||
std::string soundFile;
|
||||
if (iss >> timeVal) {
|
||||
std::getline(iss, soundFile);
|
||||
auto firstQuote = soundFile.find('"');
|
||||
auto lastQuote = soundFile.rfind('"');
|
||||
if (firstQuote != std::string::npos && lastQuote != std::string::npos && lastQuote > firstQuote) {
|
||||
soundFile = soundFile.substr(firstQuote + 1, lastQuote - firstQuote - 1);
|
||||
} else {
|
||||
auto nonSpace = soundFile.find_first_not_of(" \t");
|
||||
if (nonSpace != std::string::npos) soundFile = soundFile.substr(nonSpace);
|
||||
}
|
||||
outEvents.push_back({timeVal, soundFile});
|
||||
}
|
||||
}
|
||||
}
|
||||
return !outEvents.empty();
|
||||
}
|
||||
|
||||
} // namespace ava2
|
||||
@@ -0,0 +1,159 @@
|
||||
#pragma once
|
||||
|
||||
#include <SDL3/SDL.h>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <unordered_map>
|
||||
#include <memory>
|
||||
#include <cstdint>
|
||||
|
||||
namespace ava2 {
|
||||
|
||||
struct CharacterSoundEvent {
|
||||
float time = 0.0f;
|
||||
std::string soundFile;
|
||||
};
|
||||
|
||||
// 1:1 Implementation of Metin2 / MilesLib CSoundManager using SDL3 modern Audio Streams
|
||||
class SoundManager {
|
||||
public:
|
||||
static SoundManager& Instance();
|
||||
|
||||
SoundManager();
|
||||
~SoundManager();
|
||||
|
||||
bool Initialize();
|
||||
void Destroy();
|
||||
bool IsInitialized() const { return m_initialized; }
|
||||
bool HasAudioDevice() const { return m_deviceId != 0; }
|
||||
|
||||
// Frame update for music fades, 3D stream lifetimes, and looping
|
||||
void Update(float dt = 0.016f);
|
||||
|
||||
// 3D Listener Orientation (Camera / Player)
|
||||
void SetPosition(float fx, float fy, float fz);
|
||||
void SetDirection(float fxDir, float fyDir, float fzDir, float fxUp = 0.0f, float fyUp = 1.0f, float fzUp = 0.0f);
|
||||
void GetPosition(float& fx, float& fy, float& fz) const { fx = m_listenerX; fy = m_listenerY; fz = m_listenerZ; }
|
||||
|
||||
// Volume & Scale configuration
|
||||
void SetSoundVolume(float volume);
|
||||
void SetSoundVolumeRatio(float ratio);
|
||||
void SetSoundVolumeGrade(int grade);
|
||||
float GetSoundVolume() const { return m_soundVolume; }
|
||||
|
||||
void SetMusicVolume(float volume);
|
||||
void SetMusicVolumeRatio(float ratio);
|
||||
void SetMusicVolumeGrade(int grade);
|
||||
float GetMusicVolume() const { return m_musicVolume; }
|
||||
|
||||
void SetSoundScale(float scale) { m_soundScale = (scale > 0.0f) ? scale : 200.0f; }
|
||||
float GetSoundScale() const { return m_soundScale; }
|
||||
|
||||
void SetAmbienceSoundScale(float scale) { m_ambienceScale = (scale > 0.0f) ? scale : 1000.0f; }
|
||||
float GetAmbienceSoundScale() const { return m_ambienceScale; }
|
||||
|
||||
void SaveVolume();
|
||||
void RestoreVolume();
|
||||
|
||||
// 2D & 3D Sound Effects
|
||||
void PlaySound2D(const std::string& filename);
|
||||
void PlaySound3D(float fx, float fy, float fz, const std::string& filename, int playCount = 1);
|
||||
int PlayAmbienceSound3D(float fx, float fy, float fz, const std::string& filename, int playCount = 1);
|
||||
void StopSound3D(int index);
|
||||
void StopAllSound3D();
|
||||
|
||||
// Background Music (BGM) Streaming & Fading
|
||||
void PlayMusic(const std::string& filename);
|
||||
void FadeInMusic(const std::string& filename, float speed = 0.016f);
|
||||
void FadeOutMusic(const std::string& filename, float speed = 0.016f);
|
||||
void FadeLimitOutMusic(const std::string& filename, float limitVolume, float speed = 0.016f);
|
||||
void FadeOutAllMusic();
|
||||
std::string GetCurrentMusic() const { return m_currentMusicFile; }
|
||||
|
||||
// Character Sound Script (.mss) Parser
|
||||
bool LoadCharacterSoundScript(const std::string& mssPath, std::vector<CharacterSoundEvent>& outEvents) const;
|
||||
|
||||
// Cache & diagnostics
|
||||
std::string ResolveAudioPath(const std::string& filename) const;
|
||||
size_t GetCachedSoundCount() const { return m_soundCache.size(); }
|
||||
size_t GetActiveSoundCount() const;
|
||||
|
||||
private:
|
||||
struct CachedAudio {
|
||||
SDL_AudioSpec spec;
|
||||
std::vector<uint8_t> data;
|
||||
};
|
||||
|
||||
enum class MusicState {
|
||||
Off,
|
||||
Play,
|
||||
FadeIn,
|
||||
FadeOut,
|
||||
FadeLimitOut
|
||||
};
|
||||
|
||||
struct MusicChannel {
|
||||
std::string filename;
|
||||
SDL_AudioStream* stream = nullptr;
|
||||
MusicState state = MusicState::Off;
|
||||
float volume = 0.0f;
|
||||
float targetVolume = 1.0f;
|
||||
float limitVolume = 0.0f;
|
||||
float volumeSpeed = 0.016f;
|
||||
CachedAudio cachedPcm;
|
||||
size_t playOffsetBytes = 0;
|
||||
};
|
||||
|
||||
struct SoundInstance {
|
||||
int id = 0;
|
||||
SDL_AudioStream* stream = nullptr;
|
||||
std::string filename;
|
||||
bool is3D = false;
|
||||
float worldX = 0.0f, worldY = 0.0f, worldZ = 0.0f;
|
||||
float scale = 200.0f;
|
||||
float volume = 1.0f;
|
||||
int playCount = 1;
|
||||
bool inUse = false;
|
||||
};
|
||||
|
||||
const CachedAudio* GetOrLoadAudio(const std::string& filename);
|
||||
bool LoadWavFile(const std::string& resolvedPath, CachedAudio& outAudio);
|
||||
bool LoadMp3File(const std::string& resolvedPath, CachedAudio& outAudio);
|
||||
|
||||
float ConvertRatioVolumeToApplyVolume(float ratio) const;
|
||||
float ConvertGradeVolumeToApplyVolume(int grade) const;
|
||||
|
||||
bool m_initialized = false;
|
||||
SDL_AudioDeviceID m_deviceId = 0;
|
||||
SDL_AudioSpec m_deviceSpec{};
|
||||
|
||||
// Listener
|
||||
float m_listenerX = 0.0f, m_listenerY = 0.0f, m_listenerZ = 0.0f;
|
||||
float m_listenerDirX = 0.0f, m_listenerDirY = 0.0f, m_listenerDirZ = 1.0f;
|
||||
float m_listenerUpX = 0.0f, m_listenerUpY = 1.0f, m_listenerUpZ = 0.0f;
|
||||
|
||||
// Volume
|
||||
float m_soundVolume = 1.0f;
|
||||
float m_musicVolume = 1.0f;
|
||||
float m_backupSoundVolume = 1.0f;
|
||||
float m_backupMusicVolume = 1.0f;
|
||||
float m_soundScale = 200.0f;
|
||||
float m_ambienceScale = 1000.0f;
|
||||
|
||||
// Cache
|
||||
std::unordered_map<std::string, CachedAudio> m_soundCache;
|
||||
|
||||
// Sound instance pool (32 channels for 2D/3D SFX)
|
||||
static constexpr size_t MAX_SOUND_INSTANCES = 32;
|
||||
std::vector<SoundInstance> m_instances;
|
||||
int m_nextInstanceId = 1;
|
||||
|
||||
// Music streaming (up to 2 channels for seamless cross-fading)
|
||||
MusicChannel m_musicChannels[2];
|
||||
std::string m_currentMusicFile;
|
||||
};
|
||||
|
||||
// Typedef alias for 1:1 legacy Metin2 code compatibility
|
||||
using CSoundManager = SoundManager;
|
||||
|
||||
} // namespace ava2
|
||||
Reference in New Issue
Block a user