1
0
mirror of https://gitlab.com/OpenMW/openmw.git synced 2025-02-06 00:40:04 +00:00
OpenMW/apps/openmw/mwsound/soundmanagerimp.cpp

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

1289 lines
42 KiB
C++
Raw Normal View History

#include "soundmanagerimp.hpp"
#include <algorithm>
#include <map>
2017-08-25 16:08:49 -04:00
#include <numeric>
#include <sstream>
#include <osg/Matrixf>
2018-08-14 23:05:43 +04:00
#include <components/debug/debuglog.hpp>
#include <components/misc/resourcehelpers.hpp>
2015-04-22 17:58:55 +02:00
#include <components/misc/rng.hpp>
2023-10-12 20:25:55 +02:00
#include <components/settings/values.hpp>
2015-04-13 22:48:37 +02:00
#include <components/vfs/manager.hpp>
#include <components/vfs/pathutil.hpp>
#include <components/vfs/recursivedirectoryiterator.hpp>
2015-04-13 22:48:37 +02:00
#include "../mwbase/environment.hpp"
#include "../mwbase/statemanager.hpp"
2023-09-18 10:11:35 +04:00
#include "../mwbase/windowmanager.hpp"
#include "../mwbase/world.hpp"
2014-02-23 20:11:05 +01:00
#include "../mwworld/cellstore.hpp"
#include "../mwworld/esmstore.hpp"
2015-08-21 21:12:39 +12:00
#include "../mwmechanics/actorutil.hpp"
#include "constants.hpp"
#include "ffmpeg_decoder.hpp"
#include "openal_output.hpp"
2012-03-17 02:45:18 -07:00
#include "sound.hpp"
#include "sound_buffer.hpp"
#include "sound_decoder.hpp"
2018-05-07 20:40:53 +04:00
#include "sound_output.hpp"
namespace MWSound
{
namespace
{
2020-06-28 13:49:05 +02:00
constexpr float sMinUpdateInterval = 1.0f / 30.0f;
constexpr float sSfxFadeInDuration = 1.0f;
constexpr float sSfxFadeOutDuration = 1.0f;
constexpr float sSoundCullDistance = 2000.f;
2020-06-28 13:49:05 +02:00
WaterSoundUpdaterSettings makeWaterSoundUpdaterSettings()
{
WaterSoundUpdaterSettings settings;
settings.mNearWaterRadius = Fallback::Map::getInt("Water_NearWaterRadius");
settings.mNearWaterPoints = Fallback::Map::getInt("Water_NearWaterPoints");
settings.mNearWaterIndoorTolerance = Fallback::Map::getFloat("Water_NearWaterIndoorTolerance");
settings.mNearWaterOutdoorTolerance = Fallback::Map::getFloat("Water_NearWaterOutdoorTolerance");
settings.mNearWaterIndoorID = ESM::RefId::stringRefId(Fallback::Map::getString("Water_NearWaterIndoorID"));
settings.mNearWaterOutdoorID
Initial commit: In ESM structures, replace the string members that are RefIds to other records, to a new strong type The strong type is actually just a string underneath, but this will help in the future to have a distinction so it's easier to search and replace when we use an integer ID Slowly going through all the changes to make, still hundreds of errors a lot of functions/structures use std::string or stringview to designate an ID. So it takes time Continues slowly replacing ids. There are technically more and more compilation errors I have good hope that there is a point where the amount of errors will dramatically go down as all the main functions use the ESM::RefId type Continue moving forward, changes to the stores slowly moving along Starting to see the fruit of those changes. still many many error, but more and more Irun into a situation where a function is sandwiched between two functions that use the RefId type. More replacements. Things are starting to get easier I can see more and more often the issue is that the function is awaiting a RefId, but is given a string there is less need to go down functions and to fix a long list of them. Still moving forward, and for the first time error count is going down! Good pace, not sure about topics though, mId and mName are actually the same thing and are used interchangeably Cells are back to using string for the name, haven't fixed everything yet. Many other changes Under the bar of 400 compilation errors. more good progress <100 compile errors! More progress Game settings store can use string for find, it was a bit absurd how every use of it required to create refId from string some more progress on other fronts Mostly game settings clean one error opened a lot of other errors. Down to 18, but more will prbably appear only link errors left?? Fixed link errors OpenMW compiles, and launches, with some issues, but still!
2022-09-25 13:17:09 +02:00
= ESM::RefId::stringRefId(Fallback::Map::getString("Water_NearWaterOutdoorID"));
return settings;
}
float initialFadeVolume(float squaredDist, Sound_Buffer* sfx, Type type, PlayMode mode)
{
// If a sound is farther away than its maximum distance, start playing it with a zero fade volume.
// It can still become audible once the player moves closer.
const float maxDist = sfx->getMaxDist();
if (squaredDist > (maxDist * maxDist))
return 0.0f;
// This is a *heuristic* that causes environment sounds to fade in. The idea is the following:
// - Only looped sounds playing through the effects channel are environment sounds
// - Do not fade in sounds if the player is already so close that the sound plays at maximum volume
const float minDist = sfx->getMinDist();
if ((squaredDist > (minDist * minDist)) && (type == Type::Sfx) && (mode & PlayMode::Loop))
return 0.0f;
return 1.0;
}
2023-10-12 20:25:55 +02:00
// Gets the combined volume settings for the given sound type
float volumeFromType(Type type)
{
float volume = Settings::sound().mMasterVolume;
switch (type)
{
case Type::Sfx:
volume *= Settings::sound().mSfxVolume;
break;
case Type::Voice:
volume *= Settings::sound().mVoiceVolume;
break;
case Type::Foot:
volume *= Settings::sound().mFootstepsVolume;
break;
case Type::Music:
volume *= Settings::sound().mMusicVolume;
break;
case Type::Movie:
case Type::Mask:
break;
}
return volume;
}
}
// For combining PlayMode and Type flags
inline int operator|(PlayMode a, Type b)
{
return static_cast<int>(a) | static_cast<int>(b);
}
SoundManager::SoundManager(const VFS::Manager* vfs, bool useSound)
2015-04-13 22:48:37 +02:00
: mVFS(vfs)
2023-03-02 22:58:07 +01:00
, mOutput(std::make_unique<OpenAL_Output>(*this))
, mWaterSoundUpdater(makeWaterSoundUpdaterSettings())
2023-05-31 23:11:03 +02:00
, mSoundBuffers(*mOutput)
, mMusicType(MWSound::MusicType::Normal)
, mListenerUnderwater(false)
, mListenerPos(0, 0, 0)
, mListenerDir(1, 0, 0)
, mListenerUp(0, 0, 1)
, mUnderwaterSound(nullptr)
, mNearWaterSound(nullptr)
, mPlaybackPaused(false)
2020-10-28 18:02:31 +04:00
, mTimePassed(0.f)
, mLastCell(nullptr)
, mCurrentRegionSound(nullptr)
{
2015-12-08 21:12:05 +01:00
if (!useSound)
{
2018-08-14 23:05:43 +04:00
Log(Debug::Info) << "Sound disabled.";
2015-12-08 21:12:05 +01:00
return;
}
2015-12-08 21:12:05 +01:00
2023-10-12 20:25:55 +02:00
if (!mOutput->init(Settings::sound().mDevice, Settings::sound().mHrtf, Settings::sound().mHrtfEnable))
{
2018-08-14 23:05:43 +04:00
Log(Debug::Error) << "Failed to initialize audio output, sound disabled";
return;
}
std::vector<std::string> names = mOutput->enumerate();
2018-08-14 23:05:43 +04:00
std::stringstream stream;
stream << "Enumerated output devices:\n";
2017-09-16 01:56:58 -07:00
for (const std::string& name : names)
2018-08-14 23:05:43 +04:00
stream << " " << name;
Log(Debug::Info) << stream.str();
stream.str("");
names = mOutput->enumerateHrtf();
if (!names.empty())
{
2018-08-14 23:05:43 +04:00
stream << "Enumerated HRTF names:\n";
2017-09-16 01:56:58 -07:00
for (const std::string& name : names)
2018-08-14 23:05:43 +04:00
stream << " " << name;
Log(Debug::Info) << stream.str();
}
}
SoundManager::~SoundManager()
{
SoundManager::clear();
mSoundBuffers.clear();
mOutput.reset();
}
// Return a new decoder instance, used as needed by the output implementations
DecoderPtr SoundManager::getDecoder()
{
2021-01-08 22:18:37 +01:00
return std::make_shared<FFmpeg_Decoder>(mVFS);
}
DecoderPtr SoundManager::loadVoice(VFS::Path::NormalizedView voicefile)
{
try
{
DecoderPtr decoder = getDecoder();
decoder->open(Misc::ResourceHelpers::correctSoundPath(voicefile, *decoder->mResourceMgr));
return decoder;
}
catch (std::exception& e)
{
Log(Debug::Error) << "Failed to load audio from " << voicefile << ": " << e.what();
}
return nullptr;
}
2020-06-28 18:25:23 +02:00
SoundPtr SoundManager::getSoundRef()
{
return mSounds.get();
}
2020-06-28 18:25:23 +02:00
StreamPtr SoundManager::getStreamRef()
{
return mStreams.get();
}
2020-06-28 18:25:23 +02:00
StreamPtr SoundManager::playVoice(DecoderPtr decoder, const osg::Vec3f& pos, bool playlocal)
{
MWBase::World* world = MWBase::Environment::get().getWorld();
2018-08-29 18:38:12 +03:00
static const float fAudioMinDistanceMult
= world->getStore().get<ESM::GameSetting>().find("fAudioMinDistanceMult")->mValue.getFloat();
static const float fAudioMaxDistanceMult
= world->getStore().get<ESM::GameSetting>().find("fAudioMaxDistanceMult")->mValue.getFloat();
static const float fAudioVoiceDefaultMinDistance
= world->getStore().get<ESM::GameSetting>().find("fAudioVoiceDefaultMinDistance")->mValue.getFloat();
static const float fAudioVoiceDefaultMaxDistance
= world->getStore().get<ESM::GameSetting>().find("fAudioVoiceDefaultMaxDistance")->mValue.getFloat();
static float minDistance = std::max(fAudioVoiceDefaultMinDistance * fAudioMinDistanceMult, 1.0f);
static float maxDistance = std::max(fAudioVoiceDefaultMaxDistance * fAudioMaxDistanceMult, minDistance);
bool played;
float basevol = volumeFromType(Type::Voice);
2020-06-28 18:25:23 +02:00
StreamPtr sound = getStreamRef();
if (playlocal)
{
2020-07-12 15:25:14 +02:00
sound->init([&] {
SoundParams params;
params.mBaseVolume = basevol;
params.mFlags = PlayMode::NoEnv | Type::Voice | Play_2D;
return params;
}());
2024-01-24 20:39:04 +04:00
played = mOutput->streamSound(std::move(decoder), sound.get(), true);
}
else
{
2020-07-12 15:25:14 +02:00
sound->init([&] {
SoundParams params;
params.mPos = pos;
params.mBaseVolume = basevol;
params.mMinDistance = minDistance;
params.mMaxDistance = maxDistance;
params.mFlags = PlayMode::Normal | Type::Voice | Play_3D;
return params;
}());
2024-01-24 20:39:04 +04:00
played = mOutput->streamSound3D(std::move(decoder), sound.get(), true);
}
if (!played)
return nullptr;
return sound;
}
void SoundManager::stopMusic()
{
2012-03-17 02:45:18 -07:00
if (mMusic)
{
2020-06-28 18:25:23 +02:00
mOutput->finishStream(mMusic.get());
mMusic = nullptr;
}
}
2011-06-12 16:36:18 -04:00
void SoundManager::streamMusicFull(VFS::Path::NormalizedView filename)
2011-06-15 22:33:31 +02:00
{
if (!mOutput->isInitialized())
return;
stopMusic();
if (filename.value().empty())
2023-01-21 01:16:08 +03:00
return;
2023-08-18 11:03:37 +04:00
Log(Debug::Info) << "Playing \"" << filename << "\"";
DecoderPtr decoder = getDecoder();
try
{
decoder->open(filename);
}
catch (const std::exception& e)
{
2023-08-18 11:03:37 +04:00
Log(Debug::Error) << "Failed to load audio from \"" << filename << "\": " << e.what();
return;
}
mMusic = getStreamRef();
2020-07-12 15:25:14 +02:00
mMusic->init([&] {
SoundParams params;
params.mBaseVolume = volumeFromType(Type::Music);
2022-07-03 12:51:28 +00:00
params.mFlags = PlayMode::NoEnvNoScaling | Type::Music | Play_2D;
2020-07-12 15:25:14 +02:00
return params;
}());
2024-01-24 20:39:04 +04:00
mOutput->streamSound(std::move(decoder), mMusic.get());
2011-01-05 22:18:21 +01:00
}
2010-11-11 19:47:26 -05:00
void SoundManager::advanceMusic(VFS::Path::NormalizedView filename, float fadeOut)
2017-08-06 20:10:56 +02:00
{
if (!isMusicPlaying())
{
streamMusicFull(filename);
return;
}
mNextMusic = filename;
2023-08-18 11:03:37 +04:00
mMusic->setFadeout(fadeOut);
2017-08-06 20:10:56 +02:00
}
2023-08-18 11:03:37 +04:00
bool SoundManager::isMusicPlaying()
{
2023-08-18 11:03:37 +04:00
return mMusic && mOutput->isStreamPlaying(mMusic.get());
}
void SoundManager::streamMusic(VFS::Path::NormalizedView filename, MusicType type, float fade)
{
2023-08-18 11:03:37 +04:00
// Can not interrupt scripted music by built-in playlists
if (mMusicType == MusicType::MWScript && type != MusicType::MWScript)
2023-08-18 11:03:37 +04:00
return;
mMusicType = type;
advanceMusic(filename, fade);
2019-03-04 01:31:51 +03:00
}
void SoundManager::say(const MWWorld::ConstPtr& ptr, VFS::Path::NormalizedView filename)
{
if (!mOutput->isInitialized())
return;
DecoderPtr decoder = loadVoice(filename);
if (!decoder)
return;
MWBase::World* world = MWBase::Environment::get().getWorld();
const osg::Vec3f pos = world->getActorHeadTransform(ptr).getTrans();
stopSay(ptr);
2024-01-24 20:39:04 +04:00
StreamPtr sound = playVoice(std::move(decoder), pos, (ptr == MWMechanics::getPlayer()));
if (!sound)
return;
mSaySoundsQueue.emplace(ptr.mRef, SaySound{ ptr.mCell, std::move(sound) });
}
2015-12-18 18:11:30 +01:00
float SoundManager::getSaySoundLoudness(const MWWorld::ConstPtr& ptr) const
{
SaySoundMap::const_iterator snditer = mActiveSaySounds.find(ptr.mRef);
if (snditer != mActiveSaySounds.end())
{
Stream* sound = snditer->second.mStream.get();
return mOutput->getStreamLoudness(sound);
}
return 0.0f;
}
void SoundManager::say(VFS::Path::NormalizedView filename)
{
if (!mOutput->isInitialized())
return;
DecoderPtr decoder = loadVoice(filename);
if (!decoder)
return;
stopSay(MWWorld::ConstPtr());
2024-01-24 20:39:04 +04:00
StreamPtr sound = playVoice(std::move(decoder), osg::Vec3f(), true);
if (!sound)
return;
mActiveSaySounds.emplace(nullptr, SaySound{ nullptr, std::move(sound) });
}
2015-12-18 18:11:30 +01:00
bool SoundManager::sayDone(const MWWorld::ConstPtr& ptr) const
{
SaySoundMap::const_iterator snditer = mActiveSaySounds.find(ptr.mRef);
if (snditer != mActiveSaySounds.end())
{
if (mOutput->isStreamPlaying(snditer->second.mStream.get()))
return false;
return true;
}
return true;
}
bool SoundManager::sayActive(const MWWorld::ConstPtr& ptr) const
{
SaySoundMap::const_iterator snditer = mSaySoundsQueue.find(ptr.mRef);
if (snditer != mSaySoundsQueue.end())
{
if (mOutput->isStreamPlaying(snditer->second.mStream.get()))
return true;
return false;
}
snditer = mActiveSaySounds.find(ptr.mRef);
if (snditer != mActiveSaySounds.end())
{
if (mOutput->isStreamPlaying(snditer->second.mStream.get()))
return true;
return false;
}
return false;
}
2015-12-18 18:11:30 +01:00
void SoundManager::stopSay(const MWWorld::ConstPtr& ptr)
{
SaySoundMap::iterator snditer = mSaySoundsQueue.find(ptr.mRef);
if (snditer != mSaySoundsQueue.end())
{
mOutput->finishStream(snditer->second.mStream.get());
mSaySoundsQueue.erase(snditer);
}
snditer = mActiveSaySounds.find(ptr.mRef);
if (snditer != mActiveSaySounds.end())
{
mOutput->finishStream(snditer->second.mStream.get());
mActiveSaySounds.erase(snditer);
}
}
Stream* SoundManager::playTrack(const DecoderPtr& decoder, Type type)
{
if (!mOutput->isInitialized())
return nullptr;
2020-06-28 18:25:23 +02:00
StreamPtr track = getStreamRef();
2020-07-12 15:25:14 +02:00
track->init([&] {
SoundParams params;
params.mBaseVolume = volumeFromType(type);
2022-07-03 12:51:28 +00:00
params.mFlags = PlayMode::NoEnvNoScaling | type | Play_2D;
2020-07-12 15:25:14 +02:00
return params;
}());
2020-06-28 18:25:23 +02:00
if (!mOutput->streamSound(decoder, track.get()))
return nullptr;
2020-06-28 18:25:23 +02:00
Stream* result = track.get();
const auto it = std::lower_bound(mActiveTracks.begin(), mActiveTracks.end(), track);
mActiveTracks.insert(it, std::move(track));
return result;
}
void SoundManager::stopTrack(Stream* stream)
{
mOutput->finishStream(stream);
2020-06-28 18:25:23 +02:00
TrackList::iterator iter = std::lower_bound(mActiveTracks.begin(), mActiveTracks.end(), stream,
[](const StreamPtr& lhs, Stream* rhs) { return lhs.get() < rhs; });
if (iter != mActiveTracks.end() && iter->get() == stream)
2015-12-01 11:28:37 -08:00
mActiveTracks.erase(iter);
}
double SoundManager::getTrackTimeDelay(Stream* stream)
{
return mOutput->getStreamDelay(stream);
}
bool SoundManager::remove3DSoundAtDistance(PlayMode mode, const MWWorld::ConstPtr& ptr) const
{
if (!mOutput->isInitialized())
return true;
const osg::Vec3f objpos(ptr.getRefData().getPosition().asVec3());
const float squaredDist = (mListenerPos - objpos).length2();
if ((mode & PlayMode::RemoveAtDistance) && squaredDist > sSoundCullDistance * sSoundCullDistance)
return true;
return false;
}
Sound* SoundManager::playSound(Sound_Buffer* sfx, float volume, float pitch, Type type, PlayMode mode, float offset)
{
if (!mOutput->isInitialized())
return nullptr;
2018-05-01 16:21:58 +04:00
// Only one copy of given sound can be played at time, so stop previous copy
2018-05-07 20:40:53 +04:00
stopSound(sfx, MWWorld::ConstPtr());
2018-05-01 16:21:58 +04:00
2020-06-28 18:25:23 +02:00
SoundPtr sound = getSoundRef();
2020-07-12 15:25:14 +02:00
sound->init([&] {
SoundParams params;
params.mVolume = volume * sfx->getVolume();
2020-07-12 15:25:14 +02:00
params.mBaseVolume = volumeFromType(type);
params.mPitch = pitch;
params.mFlags = mode | type | Play_2D;
return params;
}());
if (!mOutput->playSound(sound.get(), sfx->getHandle(), offset))
return nullptr;
2020-06-28 18:25:23 +02:00
Sound* result = sound.get();
mActiveSounds[nullptr].mList.emplace_back(std::move(sound), sfx);
mSoundBuffers.use(*sfx);
2020-06-28 18:25:23 +02:00
return result;
}
Sound* SoundManager::playSound(
std::string_view fileName, float volume, float pitch, Type type, PlayMode mode, float offset)
{
if (!mOutput->isInitialized())
return nullptr;
std::string normalizedName = VFS::Path::normalizeFilename(fileName);
2023-08-19 13:46:20 +04:00
if (!mVFS->exists(normalizedName))
return nullptr;
Sound_Buffer* sfx = mSoundBuffers.load(normalizedName);
if (!sfx)
return nullptr;
return playSound(sfx, volume, pitch, type, mode, offset);
}
Sound* SoundManager::playSound(
const ESM::RefId& soundId, float volume, float pitch, Type type, PlayMode mode, float offset)
{
if (!mOutput->isInitialized())
return nullptr;
Initial commit: In ESM structures, replace the string members that are RefIds to other records, to a new strong type The strong type is actually just a string underneath, but this will help in the future to have a distinction so it's easier to search and replace when we use an integer ID Slowly going through all the changes to make, still hundreds of errors a lot of functions/structures use std::string or stringview to designate an ID. So it takes time Continues slowly replacing ids. There are technically more and more compilation errors I have good hope that there is a point where the amount of errors will dramatically go down as all the main functions use the ESM::RefId type Continue moving forward, changes to the stores slowly moving along Starting to see the fruit of those changes. still many many error, but more and more Irun into a situation where a function is sandwiched between two functions that use the RefId type. More replacements. Things are starting to get easier I can see more and more often the issue is that the function is awaiting a RefId, but is given a string there is less need to go down functions and to fix a long list of them. Still moving forward, and for the first time error count is going down! Good pace, not sure about topics though, mId and mName are actually the same thing and are used interchangeably Cells are back to using string for the name, haven't fixed everything yet. Many other changes Under the bar of 400 compilation errors. more good progress <100 compile errors! More progress Game settings store can use string for find, it was a bit absurd how every use of it required to create refId from string some more progress on other fronts Mostly game settings clean one error opened a lot of other errors. Down to 18, but more will prbably appear only link errors left?? Fixed link errors OpenMW compiles, and launches, with some issues, but still!
2022-09-25 13:17:09 +02:00
Sound_Buffer* sfx = mSoundBuffers.load(soundId);
if (!sfx)
return nullptr;
return playSound(sfx, volume, pitch, type, mode, offset);
}
Sound* SoundManager::playSound3D(const MWWorld::ConstPtr& ptr, Sound_Buffer* sfx, float volume, float pitch,
Type type, PlayMode mode, float offset)
{
if (!mOutput->isInitialized())
return nullptr;
// Only one copy of given sound can be played at time on ptr, so stop previous copy
2018-05-07 20:40:53 +04:00
stopSound(sfx, ptr);
const osg::Vec3f objpos(ptr.getRefData().getPosition().asVec3());
const float squaredDist = (mListenerPos - objpos).length2();
bool played;
2020-06-28 18:25:23 +02:00
SoundPtr sound = getSoundRef();
if (!(mode & PlayMode::NoPlayerLocal) && ptr == MWMechanics::getPlayer())
{
2020-07-12 15:25:14 +02:00
sound->init([&] {
SoundParams params;
params.mVolume = volume * sfx->getVolume();
2020-07-12 15:25:14 +02:00
params.mBaseVolume = volumeFromType(type);
params.mPitch = pitch;
params.mFlags = mode | type | Play_2D;
return params;
}());
played = mOutput->playSound(sound.get(), sfx->getHandle(), offset);
}
else
{
2020-07-12 15:25:14 +02:00
sound->init([&] {
SoundParams params;
params.mPos = objpos;
params.mVolume = volume * sfx->getVolume();
2020-07-12 15:25:14 +02:00
params.mBaseVolume = volumeFromType(type);
params.mFadeVolume = initialFadeVolume(squaredDist, sfx, type, mode);
2020-07-12 15:25:14 +02:00
params.mPitch = pitch;
params.mMinDistance = sfx->getMinDist();
params.mMaxDistance = sfx->getMaxDist();
2020-07-12 15:25:14 +02:00
params.mFlags = mode | type | Play_3D;
return params;
}());
played = mOutput->playSound3D(sound.get(), sfx->getHandle(), offset);
}
if (!played)
return nullptr;
2020-06-28 18:25:23 +02:00
Sound* result = sound.get();
auto it = mActiveSounds.find(ptr.mRef);
if (it == mActiveSounds.end())
it = mActiveSounds.emplace(ptr.mRef, ActiveSound{ ptr.mCell, {} }).first;
it->second.mList.emplace_back(std::move(sound), sfx);
mSoundBuffers.use(*sfx);
2020-06-28 18:25:23 +02:00
return result;
}
Sound* SoundManager::playSound3D(const MWWorld::ConstPtr& ptr, const ESM::RefId& soundId, float volume, float pitch,
Type type, PlayMode mode, float offset)
{
if (remove3DSoundAtDistance(mode, ptr))
return nullptr;
// Look up the sound in the ESM data
Sound_Buffer* sfx = mSoundBuffers.load(soundId);
if (!sfx)
return nullptr;
return playSound3D(ptr, sfx, volume, pitch, type, mode, offset);
}
Sound* SoundManager::playSound3D(const MWWorld::ConstPtr& ptr, std::string_view fileName, float volume, float pitch,
Type type, PlayMode mode, float offset)
{
if (remove3DSoundAtDistance(mode, ptr))
return nullptr;
// Look up the sound
std::string normalizedName = VFS::Path::normalizeFilename(fileName);
2023-08-19 13:46:20 +04:00
if (!mVFS->exists(normalizedName))
return nullptr;
Sound_Buffer* sfx = mSoundBuffers.load(normalizedName);
if (!sfx)
return nullptr;
return playSound3D(ptr, sfx, volume, pitch, type, mode, offset);
}
Initial commit: In ESM structures, replace the string members that are RefIds to other records, to a new strong type The strong type is actually just a string underneath, but this will help in the future to have a distinction so it's easier to search and replace when we use an integer ID Slowly going through all the changes to make, still hundreds of errors a lot of functions/structures use std::string or stringview to designate an ID. So it takes time Continues slowly replacing ids. There are technically more and more compilation errors I have good hope that there is a point where the amount of errors will dramatically go down as all the main functions use the ESM::RefId type Continue moving forward, changes to the stores slowly moving along Starting to see the fruit of those changes. still many many error, but more and more Irun into a situation where a function is sandwiched between two functions that use the RefId type. More replacements. Things are starting to get easier I can see more and more often the issue is that the function is awaiting a RefId, but is given a string there is less need to go down functions and to fix a long list of them. Still moving forward, and for the first time error count is going down! Good pace, not sure about topics though, mId and mName are actually the same thing and are used interchangeably Cells are back to using string for the name, haven't fixed everything yet. Many other changes Under the bar of 400 compilation errors. more good progress <100 compile errors! More progress Game settings store can use string for find, it was a bit absurd how every use of it required to create refId from string some more progress on other fronts Mostly game settings clean one error opened a lot of other errors. Down to 18, but more will prbably appear only link errors left?? Fixed link errors OpenMW compiles, and launches, with some issues, but still!
2022-09-25 13:17:09 +02:00
Sound* SoundManager::playSound3D(const osg::Vec3f& initialPos, const ESM::RefId& soundId, float volume, float pitch,
Type type, PlayMode mode, float offset)
{
if (!mOutput->isInitialized())
return nullptr;
// Look up the sound in the ESM data
Initial commit: In ESM structures, replace the string members that are RefIds to other records, to a new strong type The strong type is actually just a string underneath, but this will help in the future to have a distinction so it's easier to search and replace when we use an integer ID Slowly going through all the changes to make, still hundreds of errors a lot of functions/structures use std::string or stringview to designate an ID. So it takes time Continues slowly replacing ids. There are technically more and more compilation errors I have good hope that there is a point where the amount of errors will dramatically go down as all the main functions use the ESM::RefId type Continue moving forward, changes to the stores slowly moving along Starting to see the fruit of those changes. still many many error, but more and more Irun into a situation where a function is sandwiched between two functions that use the RefId type. More replacements. Things are starting to get easier I can see more and more often the issue is that the function is awaiting a RefId, but is given a string there is less need to go down functions and to fix a long list of them. Still moving forward, and for the first time error count is going down! Good pace, not sure about topics though, mId and mName are actually the same thing and are used interchangeably Cells are back to using string for the name, haven't fixed everything yet. Many other changes Under the bar of 400 compilation errors. more good progress <100 compile errors! More progress Game settings store can use string for find, it was a bit absurd how every use of it required to create refId from string some more progress on other fronts Mostly game settings clean one error opened a lot of other errors. Down to 18, but more will prbably appear only link errors left?? Fixed link errors OpenMW compiles, and launches, with some issues, but still!
2022-09-25 13:17:09 +02:00
Sound_Buffer* sfx = mSoundBuffers.load(soundId);
if (!sfx)
return nullptr;
const float squaredDist = (mListenerPos - initialPos).length2();
2020-06-28 18:25:23 +02:00
SoundPtr sound = getSoundRef();
2020-07-12 15:25:14 +02:00
sound->init([&] {
SoundParams params;
params.mPos = initialPos;
params.mVolume = volume * sfx->getVolume();
2020-07-12 15:25:14 +02:00
params.mBaseVolume = volumeFromType(type);
params.mFadeVolume = initialFadeVolume(squaredDist, sfx, type, mode);
2020-07-12 15:25:14 +02:00
params.mPitch = pitch;
params.mMinDistance = sfx->getMinDist();
params.mMaxDistance = sfx->getMaxDist();
2020-07-12 15:25:14 +02:00
params.mFlags = mode | type | Play_3D;
return params;
}());
if (!mOutput->playSound3D(sound.get(), sfx->getHandle(), offset))
return nullptr;
2020-06-28 18:25:23 +02:00
Sound* result = sound.get();
mActiveSounds[nullptr].mList.emplace_back(std::move(sound), sfx);
mSoundBuffers.use(*sfx);
2020-06-28 18:25:23 +02:00
return result;
}
void SoundManager::stopSound(Sound* sound)
{
if (sound)
mOutput->finishSound(sound);
}
2018-05-07 20:40:53 +04:00
void SoundManager::stopSound(Sound_Buffer* sfx, const MWWorld::ConstPtr& ptr)
{
SoundMap::iterator snditer = mActiveSounds.find(ptr.mRef);
if (snditer != mActiveSounds.end())
{
for (SoundBufferRefPair& snd : snditer->second.mList)
{
2017-09-16 01:56:58 -07:00
if (snd.second == sfx)
2020-06-28 18:25:23 +02:00
mOutput->finishSound(snd.first.get());
}
}
}
Initial commit: In ESM structures, replace the string members that are RefIds to other records, to a new strong type The strong type is actually just a string underneath, but this will help in the future to have a distinction so it's easier to search and replace when we use an integer ID Slowly going through all the changes to make, still hundreds of errors a lot of functions/structures use std::string or stringview to designate an ID. So it takes time Continues slowly replacing ids. There are technically more and more compilation errors I have good hope that there is a point where the amount of errors will dramatically go down as all the main functions use the ESM::RefId type Continue moving forward, changes to the stores slowly moving along Starting to see the fruit of those changes. still many many error, but more and more Irun into a situation where a function is sandwiched between two functions that use the RefId type. More replacements. Things are starting to get easier I can see more and more often the issue is that the function is awaiting a RefId, but is given a string there is less need to go down functions and to fix a long list of them. Still moving forward, and for the first time error count is going down! Good pace, not sure about topics though, mId and mName are actually the same thing and are used interchangeably Cells are back to using string for the name, haven't fixed everything yet. Many other changes Under the bar of 400 compilation errors. more good progress <100 compile errors! More progress Game settings store can use string for find, it was a bit absurd how every use of it required to create refId from string some more progress on other fronts Mostly game settings clean one error opened a lot of other errors. Down to 18, but more will prbably appear only link errors left?? Fixed link errors OpenMW compiles, and launches, with some issues, but still!
2022-09-25 13:17:09 +02:00
void SoundManager::stopSound3D(const MWWorld::ConstPtr& ptr, const ESM::RefId& soundId)
2018-05-07 20:40:53 +04:00
{
if (!mOutput->isInitialized())
return;
Initial commit: In ESM structures, replace the string members that are RefIds to other records, to a new strong type The strong type is actually just a string underneath, but this will help in the future to have a distinction so it's easier to search and replace when we use an integer ID Slowly going through all the changes to make, still hundreds of errors a lot of functions/structures use std::string or stringview to designate an ID. So it takes time Continues slowly replacing ids. There are technically more and more compilation errors I have good hope that there is a point where the amount of errors will dramatically go down as all the main functions use the ESM::RefId type Continue moving forward, changes to the stores slowly moving along Starting to see the fruit of those changes. still many many error, but more and more Irun into a situation where a function is sandwiched between two functions that use the RefId type. More replacements. Things are starting to get easier I can see more and more often the issue is that the function is awaiting a RefId, but is given a string there is less need to go down functions and to fix a long list of them. Still moving forward, and for the first time error count is going down! Good pace, not sure about topics though, mId and mName are actually the same thing and are used interchangeably Cells are back to using string for the name, haven't fixed everything yet. Many other changes Under the bar of 400 compilation errors. more good progress <100 compile errors! More progress Game settings store can use string for find, it was a bit absurd how every use of it required to create refId from string some more progress on other fronts Mostly game settings clean one error opened a lot of other errors. Down to 18, but more will prbably appear only link errors left?? Fixed link errors OpenMW compiles, and launches, with some issues, but still!
2022-09-25 13:17:09 +02:00
Sound_Buffer* sfx = mSoundBuffers.lookup(soundId);
2018-05-07 20:40:53 +04:00
if (!sfx)
return;
stopSound(sfx, ptr);
}
void SoundManager::stopSound3D(const MWWorld::ConstPtr& ptr, std::string_view fileName)
{
2023-08-19 13:46:20 +04:00
if (!mOutput->isInitialized())
return;
std::string normalizedName = VFS::Path::normalizeFilename(fileName);
2023-08-19 13:46:20 +04:00
Sound_Buffer* sfx = mSoundBuffers.lookup(normalizedName);
if (!sfx)
return;
stopSound(sfx, ptr);
}
2015-12-18 18:11:30 +01:00
void SoundManager::stopSound3D(const MWWorld::ConstPtr& ptr)
{
SoundMap::iterator snditer = mActiveSounds.find(ptr.mRef);
if (snditer != mActiveSounds.end())
{
for (SoundBufferRefPair& snd : snditer->second.mList)
2020-06-28 18:25:23 +02:00
mOutput->finishSound(snd.first.get());
}
SaySoundMap::iterator sayiter = mSaySoundsQueue.find(ptr.mRef);
2019-05-26 19:23:42 +03:00
if (sayiter != mSaySoundsQueue.end())
mOutput->finishStream(sayiter->second.mStream.get());
sayiter = mActiveSaySounds.find(ptr.mRef);
2017-09-16 01:56:58 -07:00
if (sayiter != mActiveSaySounds.end())
mOutput->finishStream(sayiter->second.mStream.get());
}
void SoundManager::stopSound(const MWWorld::CellStore* cell)
{
for (auto& [ref, sound] : mActiveSounds)
{
if (ref != nullptr && ref != MWMechanics::getPlayer().mRef && sound.mCell == cell)
{
for (SoundBufferRefPair& sndbuf : sound.mList)
2020-06-28 18:25:23 +02:00
mOutput->finishSound(sndbuf.first.get());
}
}
2018-05-07 20:40:53 +04:00
for (const auto& [ref, sound] : mSaySoundsQueue)
2019-05-26 19:23:42 +03:00
{
if (ref != nullptr && ref != MWMechanics::getPlayer().mRef && sound.mCell == cell)
mOutput->finishStream(sound.mStream.get());
2019-05-26 19:23:42 +03:00
}
for (const auto& [ref, sound] : mActiveSaySounds)
{
if (ref != nullptr && ref != MWMechanics::getPlayer().mRef && sound.mCell == cell)
mOutput->finishStream(sound.mStream.get());
}
}
Initial commit: In ESM structures, replace the string members that are RefIds to other records, to a new strong type The strong type is actually just a string underneath, but this will help in the future to have a distinction so it's easier to search and replace when we use an integer ID Slowly going through all the changes to make, still hundreds of errors a lot of functions/structures use std::string or stringview to designate an ID. So it takes time Continues slowly replacing ids. There are technically more and more compilation errors I have good hope that there is a point where the amount of errors will dramatically go down as all the main functions use the ESM::RefId type Continue moving forward, changes to the stores slowly moving along Starting to see the fruit of those changes. still many many error, but more and more Irun into a situation where a function is sandwiched between two functions that use the RefId type. More replacements. Things are starting to get easier I can see more and more often the issue is that the function is awaiting a RefId, but is given a string there is less need to go down functions and to fix a long list of them. Still moving forward, and for the first time error count is going down! Good pace, not sure about topics though, mId and mName are actually the same thing and are used interchangeably Cells are back to using string for the name, haven't fixed everything yet. Many other changes Under the bar of 400 compilation errors. more good progress <100 compile errors! More progress Game settings store can use string for find, it was a bit absurd how every use of it required to create refId from string some more progress on other fronts Mostly game settings clean one error opened a lot of other errors. Down to 18, but more will prbably appear only link errors left?? Fixed link errors OpenMW compiles, and launches, with some issues, but still!
2022-09-25 13:17:09 +02:00
void SoundManager::fadeOutSound3D(const MWWorld::ConstPtr& ptr, const ESM::RefId& soundId, float duration)
{
SoundMap::iterator snditer = mActiveSounds.find(ptr.mRef);
if (snditer != mActiveSounds.end())
{
Initial commit: In ESM structures, replace the string members that are RefIds to other records, to a new strong type The strong type is actually just a string underneath, but this will help in the future to have a distinction so it's easier to search and replace when we use an integer ID Slowly going through all the changes to make, still hundreds of errors a lot of functions/structures use std::string or stringview to designate an ID. So it takes time Continues slowly replacing ids. There are technically more and more compilation errors I have good hope that there is a point where the amount of errors will dramatically go down as all the main functions use the ESM::RefId type Continue moving forward, changes to the stores slowly moving along Starting to see the fruit of those changes. still many many error, but more and more Irun into a situation where a function is sandwiched between two functions that use the RefId type. More replacements. Things are starting to get easier I can see more and more often the issue is that the function is awaiting a RefId, but is given a string there is less need to go down functions and to fix a long list of them. Still moving forward, and for the first time error count is going down! Good pace, not sure about topics though, mId and mName are actually the same thing and are used interchangeably Cells are back to using string for the name, haven't fixed everything yet. Many other changes Under the bar of 400 compilation errors. more good progress <100 compile errors! More progress Game settings store can use string for find, it was a bit absurd how every use of it required to create refId from string some more progress on other fronts Mostly game settings clean one error opened a lot of other errors. Down to 18, but more will prbably appear only link errors left?? Fixed link errors OpenMW compiles, and launches, with some issues, but still!
2022-09-25 13:17:09 +02:00
Sound_Buffer* sfx = mSoundBuffers.lookup(soundId);
2020-06-29 00:05:25 +02:00
if (sfx == nullptr)
return;
for (SoundBufferRefPair& sndbuf : snditer->second.mList)
{
2017-09-16 01:56:58 -07:00
if (sndbuf.second == sfx)
sndbuf.first->setFadeout(duration);
}
}
}
bool SoundManager::getSoundPlaying(const MWWorld::ConstPtr& ptr, std::string_view fileName) const
{
std::string normalizedName = VFS::Path::normalizeFilename(fileName);
2023-08-19 13:46:20 +04:00
SoundMap::const_iterator snditer = mActiveSounds.find(ptr.mRef);
if (snditer != mActiveSounds.end())
{
Sound_Buffer* sfx = mSoundBuffers.lookup(normalizedName);
if (!sfx)
return false;
return std::find_if(snditer->second.mList.cbegin(), snditer->second.mList.cend(),
[this, sfx](const SoundBufferRefPair& snd) -> bool {
return snd.second == sfx && mOutput->isSoundPlaying(snd.first.get());
})
!= snditer->second.mList.cend();
}
return false;
}
Initial commit: In ESM structures, replace the string members that are RefIds to other records, to a new strong type The strong type is actually just a string underneath, but this will help in the future to have a distinction so it's easier to search and replace when we use an integer ID Slowly going through all the changes to make, still hundreds of errors a lot of functions/structures use std::string or stringview to designate an ID. So it takes time Continues slowly replacing ids. There are technically more and more compilation errors I have good hope that there is a point where the amount of errors will dramatically go down as all the main functions use the ESM::RefId type Continue moving forward, changes to the stores slowly moving along Starting to see the fruit of those changes. still many many error, but more and more Irun into a situation where a function is sandwiched between two functions that use the RefId type. More replacements. Things are starting to get easier I can see more and more often the issue is that the function is awaiting a RefId, but is given a string there is less need to go down functions and to fix a long list of them. Still moving forward, and for the first time error count is going down! Good pace, not sure about topics though, mId and mName are actually the same thing and are used interchangeably Cells are back to using string for the name, haven't fixed everything yet. Many other changes Under the bar of 400 compilation errors. more good progress <100 compile errors! More progress Game settings store can use string for find, it was a bit absurd how every use of it required to create refId from string some more progress on other fronts Mostly game settings clean one error opened a lot of other errors. Down to 18, but more will prbably appear only link errors left?? Fixed link errors OpenMW compiles, and launches, with some issues, but still!
2022-09-25 13:17:09 +02:00
bool SoundManager::getSoundPlaying(const MWWorld::ConstPtr& ptr, const ESM::RefId& soundId) const
{
SoundMap::const_iterator snditer = mActiveSounds.find(ptr.mRef);
2015-11-23 04:10:56 -08:00
if (snditer != mActiveSounds.end())
{
Initial commit: In ESM structures, replace the string members that are RefIds to other records, to a new strong type The strong type is actually just a string underneath, but this will help in the future to have a distinction so it's easier to search and replace when we use an integer ID Slowly going through all the changes to make, still hundreds of errors a lot of functions/structures use std::string or stringview to designate an ID. So it takes time Continues slowly replacing ids. There are technically more and more compilation errors I have good hope that there is a point where the amount of errors will dramatically go down as all the main functions use the ESM::RefId type Continue moving forward, changes to the stores slowly moving along Starting to see the fruit of those changes. still many many error, but more and more Irun into a situation where a function is sandwiched between two functions that use the RefId type. More replacements. Things are starting to get easier I can see more and more often the issue is that the function is awaiting a RefId, but is given a string there is less need to go down functions and to fix a long list of them. Still moving forward, and for the first time error count is going down! Good pace, not sure about topics though, mId and mName are actually the same thing and are used interchangeably Cells are back to using string for the name, haven't fixed everything yet. Many other changes Under the bar of 400 compilation errors. more good progress <100 compile errors! More progress Game settings store can use string for find, it was a bit absurd how every use of it required to create refId from string some more progress on other fronts Mostly game settings clean one error opened a lot of other errors. Down to 18, but more will prbably appear only link errors left?? Fixed link errors OpenMW compiles, and launches, with some issues, but still!
2022-09-25 13:17:09 +02:00
Sound_Buffer* sfx = mSoundBuffers.lookup(soundId);
2023-08-19 13:46:20 +04:00
if (!sfx)
return false;
return std::find_if(snditer->second.mList.cbegin(), snditer->second.mList.cend(),
2017-09-16 01:56:58 -07:00
[this, sfx](const SoundBufferRefPair& snd) -> bool {
2020-06-28 18:25:23 +02:00
return snd.second == sfx && mOutput->isSoundPlaying(snd.first.get());
})
!= snditer->second.mList.cend();
2015-11-23 04:10:56 -08:00
}
return false;
}
void SoundManager::pauseSounds(BlockerType blocker, int types)
{
if (mOutput->isInitialized())
{
if (mPausedSoundTypes[blocker] != 0)
resumeSounds(blocker);
2020-03-31 12:29:58 +04:00
types = types & Type::Mask;
mOutput->pauseSounds(types);
mPausedSoundTypes[blocker] = types;
}
}
void SoundManager::resumeSounds(BlockerType blocker)
{
if (mOutput->isInitialized())
{
mPausedSoundTypes[blocker] = 0;
2020-03-31 12:29:58 +04:00
int types = int(Type::Mask);
for (int currentBlocker = 0; currentBlocker < BlockerType::MaxCount; currentBlocker++)
2020-03-31 12:29:58 +04:00
{
if (currentBlocker != blocker)
types &= ~mPausedSoundTypes[currentBlocker];
2020-03-31 12:29:58 +04:00
}
mOutput->resumeSounds(types);
}
}
void SoundManager::pausePlayback()
{
if (mPlaybackPaused)
return;
mPlaybackPaused = true;
mOutput->pauseActiveDevice();
}
void SoundManager::resumePlayback()
{
if (!mPlaybackPaused)
return;
mPlaybackPaused = false;
mOutput->resumeActiveDevice();
}
void SoundManager::updateRegionSound(float duration)
{
MWBase::World* world = MWBase::Environment::get().getWorld();
2015-12-18 18:11:30 +01:00
const MWWorld::ConstPtr player = world->getPlayerPtr();
auto cell = player.getCell()->getCell();
2024-10-19 10:43:50 +02:00
if (!cell->isExterior() && !cell->isQuasiExterior())
return;
2020-10-25 12:20:14 +01:00
if (mCurrentRegionSound && mOutput->isSoundPlaying(mCurrentRegionSound))
return;
2024-03-09 17:14:43 +01:00
ESM::RefId next = mRegionSoundSelector.getNextRandom(duration, cell->getRegion());
if (!next.empty())
mCurrentRegionSound = playSound(next, 1.0f, 1.0f);
}
void SoundManager::updateWaterSound()
2016-11-27 21:19:52 +01:00
{
MWBase::World* world = MWBase::Environment::get().getWorld();
const MWWorld::ConstPtr player = world->getPlayerPtr();
2023-01-23 21:44:49 +01:00
const MWWorld::Cell* curcell = player.getCell()->getCell();
const auto update = mWaterSoundUpdater.update(player, *world);
2016-11-27 21:19:52 +01:00
WaterSoundAction action;
Sound_Buffer* sfx;
std::tie(action, sfx) = getWaterSoundAction(update, curcell);
switch (action)
{
case WaterSoundAction::DoNothing:
break;
case WaterSoundAction::SetVolume:
mNearWaterSound->setVolume(update.mVolume * sfx->getVolume());
2021-11-04 15:56:23 -04:00
mNearWaterSound->setFade(sSfxFadeInDuration, 1.0f, Play_FadeExponential);
break;
case WaterSoundAction::FinishSound:
2021-11-04 15:56:23 -04:00
mNearWaterSound->setFade(sSfxFadeOutDuration, 0.0f, Play_FadeExponential | Play_StopAtFadeEnd);
break;
case WaterSoundAction::PlaySound:
if (mNearWaterSound)
mOutput->finishSound(mNearWaterSound);
mNearWaterSound = playSound(update.mId, update.mVolume, 1.0f, Type::Sfx, PlayMode::Loop);
break;
}
mLastCell = curcell;
}
std::pair<SoundManager::WaterSoundAction, Sound_Buffer*> SoundManager::getWaterSoundAction(
const WaterSoundUpdate& update, const MWWorld::Cell* cell) const
{
2016-11-27 21:19:52 +01:00
if (mNearWaterSound)
{
if (update.mVolume == 0.0f)
return { WaterSoundAction::FinishSound, nullptr };
2016-11-27 21:19:52 +01:00
bool soundIdChanged = false;
2016-11-27 21:19:52 +01:00
Sound_Buffer* sfx = mSoundBuffers.lookup(update.mId);
if (mLastCell != cell)
{
const auto snditer = mActiveSounds.find(nullptr);
if (snditer != mActiveSounds.end())
2016-11-27 21:19:52 +01:00
{
const auto pairiter = std::find_if(snditer->second.mList.begin(), snditer->second.mList.end(),
[this](const SoundBufferRefPairList::value_type& item) -> bool {
2020-06-28 18:25:23 +02:00
return mNearWaterSound == item.first.get();
});
if (pairiter != snditer->second.mList.end() && pairiter->second != sfx)
soundIdChanged = true;
2016-11-27 21:19:52 +01:00
}
}
if (soundIdChanged)
return { WaterSoundAction::PlaySound, nullptr };
if (sfx)
return { WaterSoundAction::SetVolume, sfx };
2016-11-27 21:19:52 +01:00
}
else if (update.mVolume > 0.0f)
return { WaterSoundAction::PlaySound, nullptr };
return { WaterSoundAction::DoNothing, nullptr };
2016-11-27 21:19:52 +01:00
}
void SoundManager::cull3DSound(SoundBase* sound)
{
// Hard-coded distance is from an original engine
const float maxDist = sound->getDistanceCull() ? sSoundCullDistance : sound->getMaxDistance();
const float squaredMaxDist = maxDist * maxDist;
const osg::Vec3f pos = sound->getPosition();
const float squaredDist = (mListenerPos - pos).length2();
if (squaredDist > squaredMaxDist)
{
// If getDistanceCull() is set, delete the sound after it has faded out
sound->setFade(
sSfxFadeOutDuration, 0.0f, Play_FadeExponential | (sound->getDistanceCull() ? Play_StopAtFadeEnd : 0));
}
else
{
// Fade sounds back in once they are in range
sound->setFade(sSfxFadeInDuration, 1.0f, Play_FadeExponential);
}
}
void SoundManager::updateSounds(float duration)
{
// We update active say sounds map for specific actors here
// because for vanilla compatibility we can't do it immediately.
SaySoundMap::iterator queuesayiter = mSaySoundsQueue.begin();
while (queuesayiter != mSaySoundsQueue.end())
{
2020-06-28 18:25:23 +02:00
const auto dst = mActiveSaySounds.find(queuesayiter->first);
if (dst == mActiveSaySounds.end())
mActiveSaySounds.emplace(queuesayiter->first, std::move(queuesayiter->second));
else
dst->second = std::move(queuesayiter->second);
mSaySoundsQueue.erase(queuesayiter++);
}
2020-06-28 13:49:05 +02:00
mTimePassed += duration;
if (mTimePassed < sMinUpdateInterval)
return;
2020-06-28 13:49:05 +02:00
duration = mTimePassed;
mTimePassed = 0.0f;
Environment env = Env_Normal;
if (mListenerUnderwater)
env = Env_Underwater;
else if (mUnderwaterSound)
2013-08-08 19:16:05 +02:00
{
mOutput->finishSound(mUnderwaterSound);
mUnderwaterSound = nullptr;
2013-08-08 19:16:05 +02:00
}
mOutput->startUpdate();
mOutput->updateListener(mListenerPos, mListenerDir, mListenerUp, env);
updateMusic(duration);
// Check if any sounds are finished playing, and trash them
SoundMap::iterator snditer = mActiveSounds.begin();
while (snditer != mActiveSounds.end())
{
MWWorld::ConstPtr ptr = snditer->first;
SoundBufferRefPairList::iterator sndidx = snditer->second.mList.begin();
while (sndidx != snditer->second.mList.end())
{
2020-06-28 18:25:23 +02:00
Sound* sound = sndidx->first.get();
if (sound->getIs3D())
2015-11-23 06:35:01 -08:00
{
if (!ptr.isEmpty())
sound->setPosition(ptr.getRefData().getPosition().asVec3());
cull3DSound(sound);
}
if (!sound->updateFade(duration) || !mOutput->isSoundPlaying(sound))
2015-11-23 06:35:01 -08:00
{
mOutput->finishSound(sound);
2020-06-28 18:25:23 +02:00
if (sound == mUnderwaterSound)
mUnderwaterSound = nullptr;
2020-06-28 18:25:23 +02:00
if (sound == mNearWaterSound)
mNearWaterSound = nullptr;
mSoundBuffers.release(*sndidx->second);
sndidx = snditer->second.mList.erase(sndidx);
2015-11-23 06:35:01 -08:00
}
2015-11-23 04:31:15 -08:00
else
{
2015-11-30 14:34:14 -08:00
mOutput->updateSound(sound);
++sndidx;
}
}
if (snditer->second.mList.empty())
snditer = mActiveSounds.erase(snditer);
else
++snditer;
}
SaySoundMap::iterator sayiter = mActiveSaySounds.begin();
2019-05-26 19:23:42 +03:00
while (sayiter != mActiveSaySounds.end())
{
2015-12-18 18:11:30 +01:00
MWWorld::ConstPtr ptr = sayiter->first;
Stream* sound = sayiter->second.mStream.get();
if (sound->getIs3D())
{
if (!ptr.isEmpty())
{
MWBase::World* world = MWBase::Environment::get().getWorld();
sound->setPosition(world->getActorHeadTransform(ptr).getTrans());
}
cull3DSound(sound);
}
if (!sound->updateFade(duration) || !mOutput->isStreamPlaying(sound))
{
mOutput->finishStream(sound);
sayiter = mActiveSaySounds.erase(sayiter);
}
2015-11-23 04:31:15 -08:00
else
{
2015-11-30 14:34:14 -08:00
mOutput->updateStream(sound);
2015-11-23 04:31:15 -08:00
++sayiter;
}
2015-11-23 04:31:15 -08:00
}
2015-12-01 11:28:37 -08:00
TrackList::iterator trkiter = mActiveTracks.begin();
while (trkiter != mActiveTracks.end())
2015-11-23 04:31:15 -08:00
{
2020-06-28 18:25:23 +02:00
Stream* sound = trkiter->get();
2015-12-01 11:28:37 -08:00
if (!mOutput->isStreamPlaying(sound))
{
mOutput->finishStream(sound);
2015-12-01 11:28:37 -08:00
trkiter = mActiveTracks.erase(trkiter);
}
2015-12-01 11:28:37 -08:00
else
{
sound->updateFade(duration);
2015-11-26 09:11:52 -08:00
2015-12-01 11:28:37 -08:00
mOutput->updateStream(sound);
++trkiter;
}
}
if (mListenerUnderwater)
{
// Play underwater sound (after updating sounds)
if (!mUnderwaterSound)
mUnderwaterSound
= playSound(ESM::RefId::stringRefId("Underwater"), 1.0f, 1.0f, Type::Sfx, PlayMode::LoopNoEnv);
}
mOutput->finishUpdate();
}
2015-11-23 04:31:15 -08:00
2017-08-06 20:10:56 +02:00
void SoundManager::updateMusic(float duration)
{
2023-01-21 01:16:08 +03:00
if (!mMusic || !mMusic->updateFade(duration) || !mOutput->isStreamPlaying(mMusic.get()))
2017-08-06 20:10:56 +02:00
{
2023-01-21 01:16:08 +03:00
stopMusic();
if (!mNextMusic.value().empty())
2017-08-06 20:10:56 +02:00
{
streamMusicFull(mNextMusic);
mNextMusic = VFS::Path::Normalized();
2017-08-06 20:10:56 +02:00
}
else
mMusicType = MusicType::Normal;
2017-08-06 20:10:56 +02:00
}
2023-01-21 01:16:08 +03:00
else
{
mOutput->updateStream(mMusic.get());
}
2017-08-06 20:10:56 +02:00
}
void SoundManager::update(float duration)
{
if (!mOutput->isInitialized() || mPlaybackPaused)
return;
2023-09-14 09:17:59 +04:00
MWBase::StateManager::State state = MWBase::Environment::get().getStateManager()->getState();
2023-09-18 10:11:35 +04:00
bool isMainMenu = MWBase::Environment::get().getWindowManager()->containsMode(MWGui::GM_MainMenu)
&& state == MWBase::StateManager::State_NoGame;
if (isMainMenu && !isMusicPlaying())
2023-09-14 09:17:59 +04:00
{
if (mVFS->exists(MWSound::titleMusic))
2023-09-19 19:29:26 +04:00
streamMusic(MWSound::titleMusic, MWSound::MusicType::Normal);
2023-09-14 09:17:59 +04:00
}
2019-03-04 01:31:51 +03:00
updateSounds(duration);
2023-09-18 10:11:35 +04:00
if (state != MWBase::StateManager::State_NoGame)
{
updateRegionSound(duration);
updateWaterSound();
}
}
2012-05-24 04:34:53 +02:00
void SoundManager::processChangedSettings(const Settings::CategorySettingVector& settings)
{
if (!mOutput->isInitialized())
return;
mOutput->startUpdate();
2017-09-16 01:56:58 -07:00
for (SoundMap::value_type& snd : mActiveSounds)
{
for (SoundBufferRefPair& sndbuf : snd.second.mList)
{
2020-06-28 18:25:23 +02:00
Sound* sound = sndbuf.first.get();
2015-11-26 09:11:52 -08:00
sound->setBaseVolume(volumeFromType(sound->getPlayType()));
2015-11-30 14:34:14 -08:00
mOutput->updateSound(sound);
}
}
2017-09-16 01:56:58 -07:00
for (SaySoundMap::value_type& snd : mActiveSaySounds)
2015-11-23 04:48:18 -08:00
{
Stream* sound = snd.second.mStream.get();
2015-11-26 09:11:52 -08:00
sound->setBaseVolume(volumeFromType(sound->getPlayType()));
2015-11-30 14:34:14 -08:00
mOutput->updateStream(sound);
2015-11-23 04:48:18 -08:00
}
for (SaySoundMap::value_type& snd : mSaySoundsQueue)
{
Stream* sound = snd.second.mStream.get();
sound->setBaseVolume(volumeFromType(sound->getPlayType()));
mOutput->updateStream(sound);
}
2020-06-28 18:25:23 +02:00
for (const StreamPtr& sound : mActiveTracks)
2015-12-01 11:28:37 -08:00
{
2015-11-26 09:11:52 -08:00
sound->setBaseVolume(volumeFromType(sound->getPlayType()));
2020-06-28 18:25:23 +02:00
mOutput->updateStream(sound.get());
2015-11-23 04:48:18 -08:00
}
if (mMusic)
{
2015-11-26 09:11:52 -08:00
mMusic->setBaseVolume(volumeFromType(mMusic->getPlayType()));
2020-06-28 18:25:23 +02:00
mOutput->updateStream(mMusic.get());
}
mOutput->finishUpdate();
2012-05-24 04:34:53 +02:00
}
void SoundManager::setListenerPosDir(
const osg::Vec3f& pos, const osg::Vec3f& dir, const osg::Vec3f& up, bool underwater)
{
mListenerPos = pos;
mListenerDir = dir;
mListenerUp = up;
mListenerUnderwater = underwater;
mWaterSoundUpdater.setUnderwater(underwater);
}
2015-12-18 18:11:30 +01:00
void SoundManager::updatePtr(const MWWorld::ConstPtr& old, const MWWorld::ConstPtr& updated)
{
SoundMap::iterator snditer = mActiveSounds.find(old.mRef);
if (snditer != mActiveSounds.end())
snditer->second.mCell = updated.mCell;
if (const auto it = mSaySoundsQueue.find(old.mRef); it != mSaySoundsQueue.end())
it->second.mCell = updated.mCell;
if (const auto it = mActiveSaySounds.find(old.mRef); it != mActiveSaySounds.end())
it->second.mCell = updated.mCell;
}
// Default readAll implementation, for decoders that can't do anything
// better
void Sound_Decoder::readAll(std::vector<char>& output)
{
size_t total = output.size();
size_t got;
output.resize(total + 32768);
while ((got = read(&output[total], output.size() - total)) > 0)
{
total += got;
output.resize(total * 2);
}
output.resize(total);
}
const char* getSampleTypeName(SampleType type)
{
switch (type)
{
case SampleType_UInt8:
return "U8";
case SampleType_Int16:
return "S16";
case SampleType_Float32:
return "Float32";
}
return "(unknown sample type)";
}
const char* getChannelConfigName(ChannelConfig config)
{
switch (config)
{
case ChannelConfig_Mono:
return "Mono";
case ChannelConfig_Stereo:
return "Stereo";
case ChannelConfig_Quad:
return "Quad";
case ChannelConfig_5point1:
return "5.1 Surround";
case ChannelConfig_7point1:
return "7.1 Surround";
}
return "(unknown channel config)";
}
2012-03-19 05:29:04 -07:00
size_t framesToBytes(size_t frames, ChannelConfig config, SampleType type)
{
switch (config)
{
case ChannelConfig_Mono:
frames *= 1;
break;
case ChannelConfig_Stereo:
frames *= 2;
break;
case ChannelConfig_Quad:
frames *= 4;
break;
case ChannelConfig_5point1:
frames *= 6;
break;
case ChannelConfig_7point1:
frames *= 8;
break;
2012-03-19 05:29:04 -07:00
}
switch (type)
{
case SampleType_UInt8:
frames *= 1;
break;
case SampleType_Int16:
frames *= 2;
break;
case SampleType_Float32:
frames *= 4;
break;
2012-03-19 05:29:04 -07:00
}
return frames;
}
size_t bytesToFrames(size_t bytes, ChannelConfig config, SampleType type)
{
return bytes / framesToBytes(1, config, type);
}
void SoundManager::clear()
{
stopMusic();
mMusicType = MusicType::Normal;
2017-09-16 01:56:58 -07:00
for (SoundMap::value_type& snd : mActiveSounds)
{
for (SoundBufferRefPair& sndbuf : snd.second.mList)
2015-11-23 06:35:01 -08:00
{
2020-06-28 18:25:23 +02:00
mOutput->finishSound(sndbuf.first.get());
mSoundBuffers.release(*sndbuf.second);
2015-11-23 06:35:01 -08:00
}
}
mActiveSounds.clear();
2017-09-16 01:56:58 -07:00
mUnderwaterSound = nullptr;
mNearWaterSound = nullptr;
for (SaySoundMap::value_type& snd : mSaySoundsQueue)
mOutput->finishStream(snd.second.mStream.get());
mSaySoundsQueue.clear();
2017-09-16 01:56:58 -07:00
for (SaySoundMap::value_type& snd : mActiveSaySounds)
mOutput->finishStream(snd.second.mStream.get());
mActiveSaySounds.clear();
2017-09-16 01:56:58 -07:00
2020-06-28 18:25:23 +02:00
for (StreamPtr& sound : mActiveTracks)
mOutput->finishStream(sound.get());
2015-12-01 11:28:37 -08:00
mActiveTracks.clear();
mPlaybackPaused = false;
std::fill(std::begin(mPausedSoundTypes), std::end(mPausedSoundTypes), 0);
}
}