Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/presentation2/src/orxonox/sound/SoundManager.cc @ 6381

Last change on this file since 6381 was 6378, checked in by rgrieder, 15 years ago

Added missing includes (revealed only with PCH and compilations).

  • Property svn:eol-style set to native
File size: 20.0 KB
Line 
1/*
2 *   ORXONOX - the hottest 3D action shooter ever to exist
3 *                    > www.orxonox.net <
4 *
5 *
6 *   License notice:
7 *
8 *   This program is free software; you can redistribute it and/or
9 *   modify it under the terms of the GNU General Public License
10 *   as published by the Free Software Foundation; either version 2
11 *   of the License, or (at your option) any later version.
12 *
13 *   This program is distributed in the hope that it will be useful,
14 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
15 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 *   GNU General Public License for more details.
17 *
18 *   You should have received a copy of the GNU General Public License
19 *   along with this program; if not, write to the Free Software
20 *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
21 *
22 *   Author:
23 *       Erwin 'vaiursch' Herrsche
24 *       Kevin Young
25 *       Reto Grieder
26 *   Co-authors:
27 *      ...
28 *
29 */
30
31#include "SoundManager.h"
32
33#include <AL/alut.h>
34#include <utility>
35
36#include "util/Exception.h"
37#include "util/Math.h"
38#include "util/ScopeGuard.h"
39#include "util/Clock.h"
40#include "core/ConfigValueIncludes.h"
41#include "core/CoreIncludes.h"
42#include "core/GameMode.h"
43#include "core/ScopedSingletonManager.h"
44#include "core/Resource.h"
45#include "SoundBuffer.h"
46#include "BaseSound.h"
47#include "AmbientSound.h"
48#include "WorldSound.h"
49
50namespace orxonox
51{
52    ManageScopedSingleton(SoundManager, ScopeID::Graphics, true);
53
54    std::string SoundManager::getALErrorString(ALenum code)
55    {
56        switch (code)
57        {
58        case AL_NO_ERROR:          return "No error";
59        case AL_INVALID_NAME:      return "Invalid AL parameter name";
60        case AL_INVALID_ENUM:      return "Invalid AL enum";
61        case AL_INVALID_VALUE:     return "Invalid AL value";
62        case AL_INVALID_OPERATION: return "Invalid AL operation";
63        case AL_OUT_OF_MEMORY:     return "AL reports out of memory";
64        default:                   return "Unknown AL error";
65        }
66    }
67
68    SoundManager::SoundManager()
69        : effectsPoolSize_(0)
70    {
71        RegisterRootObject(SoundManager);
72
73        // See whether we even want to load
74        bool bDisableSound_ = false;
75        SetConfigValue(bDisableSound_, false);
76        if (bDisableSound_)
77            ThrowException(InitialisationAborted, "Sound: Not loading at all");
78
79        if (!alutInitWithoutContext(NULL, NULL))
80            ThrowException(InitialisationFailed, "Sound Error: ALUT initialisation failed: " << alutGetErrorString(alutGetError()));
81        Loki::ScopeGuard alutExitGuard = Loki::MakeGuard(&alutExit);
82
83/*
84        // Get list of available sound devices and display them
85        const char* devices = alcGetString(NULL, ALC_DEVICE_SPECIFIER);
86        char* device = new char[strlen(devices)+1];
87        strcpy(device, devices);
88        std::string renderDevice;
89        SetConfigValue(renderDevice, std::string(device)).description("Sound device used for rendering");
90        COUT(4) << "Sound: Available devices: ";
91        while (true)
92        {
93            this->deviceNames_.push_back(devices);
94            COUT(4) << "\"" << devices << "\", ";
95            devices += strlen(devices) + 1;
96            if (*devices == '\0')
97                break;
98        }
99        COUT(4) << std::endl;
100
101        // Open the selected device
102        COUT(3) << "Sound: Opening device \"" << renderDevice << "\"" << std::endl;
103        this->device_ = alcOpenDevice(renderDevice.c_str());
104*/
105        this->device_ = alcOpenDevice(NULL);
106        if (this->device_ == NULL)
107        {
108            COUT(1) << "Sound: Could not open sound device. Have you installed OpenAL?" << std::endl;
109#ifdef ORXONOX_PLATFORM_WINDOWS
110            COUT(1) << "Sound: Just getting the DLL with the dependencies is not enough for Windows (esp. Windows 7)!" << std::endl;
111#endif
112            ThrowException(InitialisationFailed, "Sound Error: Could not open sound device.");
113        }
114        Loki::ScopeGuard closeDeviceGuard = Loki::MakeGuard(&alcCloseDevice, this->device_);
115
116        // Create sound context and make it the currently used one
117        this->context_ = alcCreateContext(this->device_, NULL);
118        if (this->context_ == NULL)
119            ThrowException(InitialisationFailed, "Sound Error: Could not create ALC context");
120        Loki::ScopeGuard desroyContextGuard = Loki::MakeGuard(&alcDestroyContext, this->context_);
121        if (!alcMakeContextCurrent(this->context_))
122            ThrowException(InitialisationFailed, "Sound Error: Could not use ALC context");
123
124        GameMode::setPlaysSound(true);
125        Loki::ScopeGuard resetPlaysSoundGuard = Loki::MakeGuard(&GameMode::setPlaysSound, false);
126
127        // Get some information about the sound
128        if (const char* version = alGetString(AL_VERSION))
129            COUT(4) << "Sound: --- OpenAL Version: " << version << std::endl;
130        if (const char* vendor = alGetString(AL_VENDOR))
131            COUT(4) << "Sound: --- OpenAL Vendor : " << vendor << std::endl;
132        if (const char* types = alutGetMIMETypes(ALUT_LOADER_BUFFER))
133            COUT(4) << "Sound: --- Supported MIME Types: " << types << std::endl;
134        else
135            COUT(2) << "Sound Warning: MIME Type retrieval failed: " << alutGetErrorString(alutGetError()) << std::endl;
136       
137        this->mute_[SoundType::All]     = 1.0f;
138        this->mute_[SoundType::Music]   = 1.0f;
139        this->mute_[SoundType::Effects] = 1.0f;
140
141        this->setConfigValues();
142
143        // Try to get at least one source
144        ALuint source;
145        alGenSources(1, &source);
146        if (!alGetError() && alIsSource(source))
147            this->soundSources_.push_back(source);
148        else
149            ThrowException(InitialisationFailed, "Sound Error: Could not even create a single source");
150        // Get the rest of the sources
151        alGenSources(1, &source);
152        unsigned int count = 1;
153        while (alIsSource(source) && !alGetError() && count <= this->maxSources_)
154        {
155            this->soundSources_.push_back(source);
156            alGenSources(1, &source);
157            ++count;
158        }
159
160        // Disarm guards
161        alutExitGuard.Dismiss();
162        closeDeviceGuard.Dismiss();
163        desroyContextGuard.Dismiss();
164        resetPlaysSoundGuard.Dismiss();
165
166        COUT(4) << "Sound: Initialisation complete" << std::endl;
167    }
168
169    SoundManager::~SoundManager()
170    {
171        GameMode::setPlaysSound(false);
172
173        // Relieve context to destroy it
174        if (!alcMakeContextCurrent(NULL))
175            COUT(1) << "Sound Error: Could not unset ALC context" << std::endl;
176        alcDestroyContext(this->context_);
177        if (ALCenum error = alcGetError(this->device_))
178        {
179            if (error == AL_INVALID_OPERATION)
180                COUT(1) << "Sound Error: Could not destroy ALC context because it is the current one" << std::endl;
181            else
182                COUT(1) << "Sound Error: Could not destroy ALC context because it is invalid" << std::endl;
183        }
184#ifdef AL_VERSION_1_1
185        if (!alcCloseDevice(this->device_))
186            COUT(1) << "Sound Error: Could not destroy ALC device. This might be because there are still buffers in use!" << std::endl;
187#else
188        alcCloseDevice(this->device_);
189#endif
190        if (!alutExit())
191            COUT(1) << "Sound Error: Closing ALUT failed: " << alutGetErrorString(alutGetError()) << std::endl;
192    }
193
194    void SoundManager::preUpdate(const Clock& time)
195    {
196        this->processCrossFading(time.getDeltaTime());
197    }
198
199    void SoundManager::setConfigValues()
200    {
201        SetConfigValue(crossFadeStep_, 0.2f)
202            .description("Determines how fast sounds should fade, per second.")
203            .callback(this, &SoundManager::checkFadeStepValidity);
204
205        SetConfigValueAlias(volume_[SoundType::All], "soundVolume_", 1.0f)
206            .description("Defines the overall volume.")
207            .callback(this, &SoundManager::checkSoundVolumeValidity);
208        SetConfigValueAlias(volume_[SoundType::Music], "ambientVolume_", 1.0f)
209            .description("Defines the ambient volume.")
210            .callback(this, &SoundManager::checkAmbientVolumeValidity);
211        SetConfigValueAlias(volume_[SoundType::Effects], "effectsVolume_", 1.0f)
212            .description("Defines the effects volume.")
213            .callback(this, &SoundManager::checkEffectsVolumeValidity);
214
215        SetConfigValue(maxSources_, 1024)
216            .description("Maximum number of sources to be made available");
217    }
218
219    void SoundManager::checkFadeStepValidity()
220    {
221        if (crossFadeStep_ <= 0.0 || crossFadeStep_ >= 1.0 )
222        {
223            COUT(2) << "Sound warning: fade step out of range, ignoring change." << std::endl;
224            ResetConfigValue(crossFadeStep_);
225        }
226    }
227
228    void SoundManager::checkVolumeValidity(SoundType::Value type)
229    {
230        float clampedVolume = clamp(this->volume_[type], 0.0f, 1.0f);
231        if (clampedVolume != this->volume_[type])
232            COUT(2) << "Sound warning: Volume setting (" << type << ") out of range, clamping." << std::endl;
233        this->updateVolume(type);
234    }
235
236    void SoundManager::setVolume(float vol, SoundType::Value type)
237    {
238        if (type < 0 || type > SoundType::Effects)
239            return;
240        this->volume_[type] = vol;
241        this->checkVolumeValidity(type);
242    }
243
244    float SoundManager::getVolume(SoundType::Value type) 
245    {
246        if (type < 0 || type > SoundType::Effects)
247            return 0.0f;
248        return this->volume_[type];
249    }
250
251    float SoundManager::getRealVolume(SoundType::Value type) 
252    {
253        if (type != SoundType::Music && type != SoundType::Effects)
254            return 0.0f;
255        return this->volume_[SoundType::All] * this->mute_[SoundType::All] * this->volume_[type] * this->mute_[type];
256    }
257
258    void SoundManager::updateVolume(SoundType::Value type)
259    {
260        switch(type)
261        {
262        case SoundType::All:
263            for (ObjectList<BaseSound>::iterator it = ObjectList<BaseSound>::begin(); it != ObjectList<BaseSound>::end(); ++it)
264                (*it)->updateVolume();
265            break;
266        case SoundType::Music:
267            for (ObjectList<AmbientSound>::iterator it = ObjectList<AmbientSound>::begin(); it != ObjectList<AmbientSound>::end(); ++it)
268                (*it)->updateVolume();
269            break;
270        case SoundType::Effects:
271            for (ObjectList<WorldSound>::iterator it = ObjectList<WorldSound>::begin(); it != ObjectList<WorldSound>::end(); ++it)
272                (*it)->updateVolume();
273            break;
274        default:
275            assert(false);
276        }
277    }
278
279    void SoundManager::toggleMute(SoundType::Value type)
280    {
281        if (type < 0 || type > SoundType::Effects)
282            return;
283        this->mute_[type] = (this->mute_[type] == 0) ? 1.0f : 0.0f;
284        this->updateVolume(type);
285    }
286
287    bool SoundManager::getMute(SoundType::Value type)
288    {
289        if (type < 0 || type > SoundType::Effects)
290            return true;
291        return (this->mute_[type] == 0);
292    }
293
294    void SoundManager::setListenerPosition(const Vector3& position)
295    {
296        alListener3f(AL_POSITION, position.x, position.y, position.z);
297        ALenum error = alGetError();
298        if (error == AL_INVALID_VALUE)
299            COUT(2) << "Sound: OpenAL: Invalid listener position" << std::endl;
300    }
301
302    void SoundManager::setListenerOrientation(const Quaternion& orientation)
303    {
304        // update listener orientation
305        const Vector3& direction = -orientation.zAxis();
306        const Vector3& up = orientation.yAxis();
307
308        ALfloat orient[6] = { direction.x, direction.y, direction.z, up.x, up.y, up.z };
309
310        alListenerfv(AL_ORIENTATION, orient);
311        ALenum error = alGetError();
312        if (error == AL_INVALID_VALUE)
313            COUT(2) << "Sound: OpenAL: Invalid listener orientation" << std::endl;
314    }
315
316    void SoundManager::registerAmbientSound(AmbientSound* newAmbient)
317    {
318        if (newAmbient != NULL)
319        {
320            for (AmbientList::const_iterator it = this->ambientSounds_.begin(); it != this->ambientSounds_.end(); ++it)
321            {
322                if (it->first == newAmbient)
323                {
324                    COUT(2) << "Sound warning: Will not play an AmbientSound twice." << std::endl;
325                    return;
326                }
327            }
328
329            if (!this->ambientSounds_.empty()) 
330            {
331                this->fadeOut(ambientSounds_.front().first);
332            }
333            this->ambientSounds_.push_front(std::make_pair(newAmbient, false));
334            newAmbient->doPlay();
335            this->fadeIn(newAmbient);
336        }
337    }
338
339    void SoundManager::unregisterAmbientSound(AmbientSound* oldAmbient)
340    {
341        if (oldAmbient == NULL || ambientSounds_.empty())
342            return;
343
344        if (this->ambientSounds_.front().first == oldAmbient) 
345        {
346            this->fadeOut(oldAmbient);
347            this->ambientSounds_.pop_front();
348            if (!this->ambientSounds_.empty())
349            {
350                if (!this->ambientSounds_.front().second) // Not paused before
351                {
352                    this->ambientSounds_.front().first->doPlay();
353                }
354                this->fadeIn(this->ambientSounds_.front().first);
355            }
356        }
357        else
358        {
359            for (AmbientList::iterator it = this->ambientSounds_.begin(); it != this->ambientSounds_.end(); ++it)
360            {
361                if (it->first == oldAmbient)
362                {
363                    this->fadeOut(oldAmbient);
364                    this->ambientSounds_.erase(it);
365                    break;
366                }
367            }
368        }
369    }
370
371    void SoundManager::pauseAmbientSound(AmbientSound* ambient)
372    {
373        if (ambient != NULL)
374        {
375            for (AmbientList::iterator it = this->ambientSounds_.begin(); it != this->ambientSounds_.end(); ++it)
376            {
377                if (it->first == ambient)
378                {
379                    it->second = true;
380                    this->fadeOut(it->first);
381                    return;
382                }
383            }
384        }
385    }
386
387    void SoundManager::fadeIn(const SmartPtr<AmbientSound>& sound)
388    {
389        // If we're already fading out --> remove that
390        for (std::list<SmartPtr<AmbientSound> >::iterator it = this->fadeOutList_.begin(); it != this->fadeOutList_.end(); it++)
391        {
392            if (*it == sound)
393            {
394                this->fadeOutList_.erase(it);
395                break;
396            }
397        }
398        // No duplicate entries
399        if (std::find(this->fadeInList_.begin(), this->fadeInList_.end(), sound) == this->fadeInList_.end())
400            this->fadeInList_.push_back(sound);
401    }
402
403    void SoundManager::fadeOut(const SmartPtr<AmbientSound>& sound)
404    {
405        // If we're already fading in --> remove that
406        for (std::list<SmartPtr<AmbientSound> >::iterator it = this->fadeInList_.begin(); it != this->fadeInList_.end(); it++)
407        {
408            if (*it == sound)
409            {
410                this->fadeInList_.erase(it);
411                break;
412            }
413        }
414        // No duplicate entries
415        if (std::find(this->fadeOutList_.begin(), this->fadeOutList_.end(), sound) == this->fadeOutList_.end())
416            this->fadeOutList_.push_back(sound);
417    }
418
419    void SoundManager::processCrossFading(float dt)
420    {
421       
422        // Hacky solution to the fade delay while loading a level.
423        if(dt > 0.2)
424        {
425            return;
426        }
427       
428        // FADE IN
429        for (std::list<SmartPtr<AmbientSound> >::iterator it= this->fadeInList_.begin(); it != this->fadeInList_.end(); )
430        {
431            if ((*it)->getVolume() + this->crossFadeStep_*dt > 1.0f)
432            {
433                (*it)->setVolume(1.0f);
434                this->fadeInList_.erase(it++);
435            }
436            else
437            {
438                (*it)->setVolume((*it)->getVolume() + this->crossFadeStep_*dt);
439                ++it;
440            }
441        }
442
443        // FADE OUT
444        for (std::list<SmartPtr<AmbientSound> >::iterator it = this->fadeOutList_.begin(); it != this->fadeOutList_.end(); )
445        {
446            if ((*it)->getVolume() - this->crossFadeStep_*dt < 0.0f)
447            {
448                (*it)->setVolume(0.0f);
449
450                // If sound is in the ambient list --> pause
451                for (AmbientList::const_iterator it2 = this->ambientSounds_.begin(); it2 != this->ambientSounds_.end(); ++it2)
452                {
453                    if (it2->first == *it)
454                    {
455                        (*it)->doPause();
456                        break;
457                    }
458                }
459                // If not pause (by loop above for instance) --> stop
460                if (!(*it)->isPaused())
461                    (*it)->doStop();
462
463                this->fadeOutList_.erase(it++);
464            }
465            else
466            {
467                (*it)->setVolume((*it)->getVolume() - this->crossFadeStep_*dt);
468                ++it;
469            }
470        }
471    }
472
473    shared_ptr<SoundBuffer> SoundManager::getSoundBuffer(const std::string& filename)
474    {
475        shared_ptr<SoundBuffer> buffer;
476        // Check active or pooled buffers
477        SoundBufferMap::const_iterator it = this->soundBuffers_.find(filename);
478        if (it != this->soundBuffers_.end())
479        {
480            buffer = it->second;
481
482            // Remove from effects pool if not active used before
483            if (buffer->poolIterator_ != this->effectsPool_.end())
484            {
485                this->effectsPoolSize_ -= buffer->getSize();
486                this->effectsPool_.erase(buffer->poolIterator_);
487                buffer->poolIterator_ = this->effectsPool_.end();
488            }
489        }
490        else
491        {
492            try
493            {
494                buffer.reset(new SoundBuffer(filename, this->effectsPool_.end()));
495            }
496            catch (...)
497            {
498                COUT(1) << Exception::handleMessage() << std::endl;
499                return buffer;
500            }
501            this->soundBuffers_[filename] = buffer;
502        }
503        return buffer;
504    }
505
506    void SoundManager::releaseSoundBuffer(const shared_ptr<SoundBuffer>& buffer, bool bPoolBuffer)
507    {
508        // Check if others are still using the buffer
509        if (buffer.use_count() != 2)
510            return;
511        SoundBufferMap::iterator it = this->soundBuffers_.find(buffer->getFilename());
512        if (it != this->soundBuffers_.end())
513        {
514            if (bPoolBuffer)
515            {
516                // Pool already too large?
517                while (this->effectsPoolSize_ + it->second->getSize() > this->maxEffectsPoolSize_s && !this->effectsPool_.empty())
518                {
519                    shared_ptr<SoundBuffer> bufferDel = this->effectsPool_.back();
520                    this->effectsPoolSize_ -= bufferDel->getSize();
521                    bufferDel->poolIterator_ = this->effectsPool_.end();
522                    this->effectsPool_.pop_back();
523                    // Remove from buffer map too
524                    SoundBufferMap::iterator itDel = this->soundBuffers_.find(bufferDel->getFilename());
525                    if (itDel != this->soundBuffers_.end())
526                        this->soundBuffers_.erase(itDel);
527                }
528                // Put buffer into the pool
529                this->effectsPoolSize_ += it->second->getSize();
530                this->effectsPool_.push_front(it->second);
531                it->second->poolIterator_ = this->effectsPool_.begin();
532            }
533            else
534                this->soundBuffers_.erase(it);
535        }
536    }
537
538    ALuint SoundManager::getSoundSource()
539    {
540        if (!this->soundSources_.empty())
541        {
542            ALuint source = this->soundSources_.back();
543            this->soundSources_.pop_back();
544            return source;
545        }
546        else
547        {
548            // Return no source ID
549            ALuint source = 123456789;
550            while (alIsSource(++source));
551            return source;
552        }
553    }
554
555    void SoundManager::releaseSoundSource(ALuint source)
556    {
557#ifndef NDEBUG
558        for (std::vector<ALuint>::const_iterator it = this->soundSources_.begin(); it != this->soundSources_.end(); ++it)
559            assert((*it) != source);
560#endif
561        this->soundSources_.push_back(source);
562    }
563}
Note: See TracBrowser for help on using the repository browser.