]> git.mxchange.org Git - simgear.git/blob - simgear/sound/soundmgr_openal.cxx
Rename update() to update_late() for the sound manager to be able to initialize it...
[simgear.git] / simgear / sound / soundmgr_openal.cxx
1 // soundmgr.cxx -- Sound effect management class
2 //
3 // Sound manager initially written by David Findlay
4 // <david_j_findlay@yahoo.com.au> 2001
5 //
6 // C++-ified by Curtis Olson, started March 2001.
7 //
8 // Copyright (C) 2001  Curtis L. Olson - http://www.flightgear.org/~curt
9 //
10 // This program is free software; you can redistribute it and/or
11 // modify it under the terms of the GNU General Public License as
12 // published by the Free Software Foundation; either version 2 of the
13 // License, or (at your option) any later version.
14 //
15 // This program is distributed in the hope that it will be useful, but
16 // WITHOUT ANY WARRANTY; without even the implied warranty of
17 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18 // General Public License for more details.
19 //
20 // You should have received a copy of the GNU General Public License
21 // along with this program; if not, write to the Free Software Foundation,
22 // Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
23 //
24 // $Id$
25
26 #ifdef HAVE_CONFIG_H
27 #  include <simgear_config.h>
28 #endif
29
30 #if defined( __APPLE__ )
31 # include <OpenAL/alut.h>
32 #else
33 # include <AL/alut.h>
34 #endif
35
36 #include <iostream>
37
38 #include "soundmgr_openal.hxx"
39
40 #include <simgear/structure/exception.hxx>
41 #include <simgear/debug/logstream.hxx>
42 #include <simgear/misc/sg_path.hxx>
43 #include <simgear/math/SGMath.hxx>
44
45
46 #define MAX_SOURCES     128
47
48 //
49 // Sound Manager
50 //
51
52 int SGSoundMgr::_alut_init = 0;
53
54 // constructor
55 SGSoundMgr::SGSoundMgr() :
56     _working(false),
57     _changed(true),
58     _volume(0.5),
59     _device(NULL),
60     _context(NULL),
61     _listener_pos(SGVec3d::zeros().data()),
62     _listener_vel(SGVec3f::zeros().data()),
63     _devname(NULL)
64 {
65 #if defined(ALUT_API_MAJOR_VERSION) && ALUT_API_MAJOR_VERSION >= 1
66     if (_alut_init == 0) {
67         if ( !alutInitWithoutContext(NULL, NULL) ) {
68             testForALUTError("alut initialization");
69             return;
70         }
71         _alut_init++;
72     }
73     _alut_init++;
74 #endif
75 }
76
77 // destructor
78
79 SGSoundMgr::~SGSoundMgr() {
80     stop();
81 #if defined(ALUT_API_MAJOR_VERSION) && ALUT_API_MAJOR_VERSION >= 1
82     _alut_init--;
83     if (_alut_init == 0) {
84         alutExit ();
85     }
86 #endif
87 }
88
89 // initialize the sound manager
90 void SGSoundMgr::init() {
91
92     SG_LOG( SG_GENERAL, SG_INFO, "Initializing OpenAL sound manager" );
93
94     ALCdevice *device = alcOpenDevice(_devname);
95     if ( testForError(device, "No default audio device available.") ) {
96         return;
97     }
98
99     ALCcontext *context = alcCreateContext(device, NULL);
100     if ( testForError(context, "Unable to create a valid context.") ) {
101         return;
102     }
103
104     if ( !alcMakeContextCurrent(context) ) {
105         testForALCError("context initialization");
106         return;
107     }
108
109     _context = context;
110     _working = true;
111
112     _listener_ori[0] = 0.0; _listener_ori[1] = 0.0; _listener_ori[2] = -1.0;
113     _listener_ori[3] = 0.0; _listener_ori[4] = 1.0; _listener_ori[5] = 0.0;
114
115     alListenerf( AL_GAIN, 0.2f );
116     alListenerfv( AL_POSITION, toVec3f(_listener_pos).data() );
117     alListenerfv( AL_ORIENTATION, _listener_ori );
118     alListenerfv( AL_VELOCITY, _listener_vel.data() );
119
120     alDopplerFactor(1.0);
121     alDopplerVelocity(340.3);   // speed of sound in meters per second.
122
123     if ( alIsExtensionPresent((const ALchar*)"EXT_exponent_distance") ) {
124         alDistanceModel(AL_EXPONENT_DISTANCE);
125     } else {
126         alDistanceModel(AL_INVERSE_DISTANCE);
127     }
128
129     testForALError("listener initialization");
130
131     alGetError(); // clear any undetetced error, just to be sure
132
133     // get a free source one at a time
134     // if an error is returned no more (hardware) sources are available
135     for (unsigned int i=0; i<MAX_SOURCES; i++) {
136         ALuint source;
137         ALenum error;
138
139         alGetError();
140         alGenSources(1, &source);
141         error = alGetError();
142         if ( error == AL_NO_ERROR ) {
143             _free_sources.push_back( source );
144         }
145         else break;
146     }
147 }
148
149 // suspend the sound manager
150 void SGSoundMgr::stop() {
151     if (_working) {
152         _working = false;
153
154         _context = alcGetCurrentContext();
155         _device = alcGetContextsDevice(_context);
156         alcMakeContextCurrent(NULL);
157         alcDestroyContext(_context);
158         alcCloseDevice(_device);
159     }
160 }
161
162 void SGSoundMgr::suspend() {
163     if (_working) {
164         sample_group_map_iterator sample_grp_current = _sample_groups.begin();
165         sample_group_map_iterator sample_grp_end = _sample_groups.end();
166         for ( ; sample_grp_current != sample_grp_end; ++sample_grp_current ) {
167             SGSampleGroup *sgrp = sample_grp_current->second;
168             sgrp->suspend();
169         }
170     }
171 }
172
173
174 void SGSoundMgr::bind ()
175 {
176     _free_sources.clear();
177     _free_sources.reserve( MAX_SOURCES );
178     _sources_in_use.clear();
179     _sources_in_use.reserve( MAX_SOURCES );
180 }
181
182
183 void SGSoundMgr::unbind ()
184 {
185     _sample_groups.clear();
186
187     // delete free sources
188     for (unsigned int i=0; i<_free_sources.size(); i++) {
189         ALuint source = _free_sources.at( i );
190         alDeleteSources( 1 , &source );
191     }
192
193     _free_sources.clear();
194     _sources_in_use.clear();
195 }
196
197 void SGSoundMgr::update( double dt )
198 {
199     // nothing to do in the regular update,e verything is done on the following
200     // function
201 }
202
203
204 // run the audio scheduler
205 void SGSoundMgr::update_late( double dt ) {
206     if (_working) {
207         sample_group_map_iterator sample_grp_current = _sample_groups.begin();
208         sample_group_map_iterator sample_grp_end = _sample_groups.end();
209         for ( ; sample_grp_current != sample_grp_end; ++sample_grp_current ) {
210             SGSampleGroup *sgrp = sample_grp_current->second;
211             sgrp->update(dt);
212         }
213
214         if (_changed) {
215             alListenerf( AL_GAIN, _volume );
216             alListenerfv( AL_VELOCITY, _listener_vel.data() );
217             alListenerfv( AL_ORIENTATION, _listener_ori );
218             alListenerfv( AL_POSITION, toVec3f(_listener_pos).data() );
219             // alDopplerVelocity(340.3);        // TODO: altitude dependent
220             testForALError("update");
221             _changed = false;
222         }
223     }
224 }
225
226
227 void
228 SGSoundMgr::resume ()
229 {
230     if (_working) {
231         sample_group_map_iterator sample_grp_current = _sample_groups.begin();
232         sample_group_map_iterator sample_grp_end = _sample_groups.end();
233         for ( ; sample_grp_current != sample_grp_end; ++sample_grp_current ) {
234             SGSampleGroup *sgrp = sample_grp_current->second;
235             sgrp->resume();
236         }
237     }
238 }
239
240
241 // add a sampel group, return true if successful
242 bool SGSoundMgr::add( SGSampleGroup *sgrp, const string& refname )
243 {
244     sample_group_map_iterator sample_grp_it = _sample_groups.find( refname );
245     if ( sample_grp_it != _sample_groups.end() ) {
246         // sample group already exists
247         return false;
248     }
249
250     _sample_groups[refname] = sgrp;
251
252     return true;
253 }
254
255
256 // remove a sound effect, return true if successful
257 bool SGSoundMgr::remove( const string &refname )
258 {
259     sample_group_map_iterator sample_grp_it = _sample_groups.find( refname );
260     if ( sample_grp_it == _sample_groups.end() ) {
261         // sample group was not found.
262         return false;
263     }
264
265     _sample_groups.erase( refname );
266
267     return true;
268 }
269
270
271 // return true of the specified sound exists in the sound manager system
272 bool SGSoundMgr::exists( const string &refname ) {
273     sample_group_map_iterator sample_grp_it = _sample_groups.find( refname );
274     if ( sample_grp_it == _sample_groups.end() ) {
275         // sample group was not found.
276         return false;
277     }
278
279     return true;
280 }
281
282
283 // return a pointer to the SGSampleGroup if the specified sound exists
284 // in the sound manager system, otherwise return NULL
285 SGSampleGroup *SGSoundMgr::find( const string &refname, bool create ) {
286     sample_group_map_iterator sample_grp_it = _sample_groups.find( refname );
287     if ( sample_grp_it == _sample_groups.end() ) {
288         // sample group was not found.
289         if (create) {
290             SGSampleGroup* sgrp = new SGSampleGroup(this, refname);
291             return sgrp;
292         }
293         else 
294             return NULL;
295     }
296
297     return sample_grp_it->second;
298 }
299
300
301 void SGSoundMgr::set_volume( float v )
302 {
303     _volume = v;
304     if (_volume > 1.0) _volume = 1.0;
305     if (_volume < 0.0) _volume = 0.0;
306     _changed = true;
307 }
308
309 // Get an unused source id
310 //
311 // The Sound Manager should keep track of the sources in use, the distance
312 // of these sources to the listener and the volume (also based on audio cone
313 // and hence orientation) of the sources.
314 //
315 // The Sound Manager is (and should be) the only one knowing about source
316 // management. Sources further away should be suspendped to free resources for
317 // newly added sounds close by.
318 unsigned int SGSoundMgr::request_source()
319 {
320     unsigned int source = NO_SOURCE;
321
322     if (_free_sources.size() > 0) {
323        source = _free_sources.back();
324        _free_sources.pop_back();
325
326        _sources_in_use.push_back(source);
327     }
328
329     return source;
330 }
331
332 // Free up a source id for further use
333 void SGSoundMgr::release_source( unsigned int source )
334 {
335     for (unsigned int i = 0; i<_sources_in_use.size(); i++) {
336         if ( _sources_in_use[i] == source ) {
337             ALint result;
338
339             alGetSourcei( source, AL_SOURCE_STATE, &result );
340             if ( result == AL_PLAYING ) {
341                 alSourceStop( source );
342             }
343             testForALError("release source");
344
345             _free_sources.push_back(source);
346             _sources_in_use.erase(_sources_in_use.begin()+i,
347                                   _sources_in_use.begin()+i+1);
348             break;
349         }
350     }
351 }
352
353 bool SGSoundMgr::load(string &samplepath, void **dbuf, int *fmt,
354                                           unsigned int *sz, int *frq )
355 {
356     ALenum format = (ALenum)*fmt;
357     ALsizei size = (ALsizei)*sz;
358     ALsizei freq = (ALsizei)*frq;
359     ALvoid *data;
360
361 #if defined(ALUT_API_MAJOR_VERSION) && ALUT_API_MAJOR_VERSION >= 1
362     ALfloat freqf;
363     data = alutLoadMemoryFromFile(samplepath.c_str(), &format, &size, &freqf );
364     freq = (ALsizei)freqf;
365     if (data == NULL) {
366         int error = alutGetError();
367         string msg = "Failed to load wav file: ";
368         msg.append(alutGetErrorString(error));
369         throw sg_io_exception(msg.c_str(), sg_location(samplepath));
370         return false;
371     }
372
373 #else
374     ALbyte *fname = (ALbyte *)samplepath.c_str();
375 # if defined (__APPLE__)
376     alutLoadWAVFile( fname, &format, &data, &size, &freq );
377 # else
378     ALboolean loop;
379     alutLoadWAVFile( fname, &format, &data, &size, &freq, &loop );
380 # endif
381     ALenum error =  alutGetError();
382     if ( error != ALUT_ERROR_NO_ERROR ) {
383         string msg = "Failed to load wav file: ";
384         msg.append(alutGetErrorString(error));
385         throw sg_io_exception(msg.c_str(), sg_location(samplepath));
386         return false;
387     }
388 #endif
389
390     *dbuf = (void *)data;
391     *fmt = (int)format;
392     *sz = (unsigned int)size;
393     *frq = (int)freq;
394
395     return true;
396 }
397
398
399 /**
400  * set the orientation of the listener (in opengl coordinates)
401  *
402  * Description: ORIENTATION is a pair of 3-tuples representing the
403  * 'at' direction vector and 'up' direction of the Object in
404  * Cartesian space. AL expects two vectors that are orthogonal to
405  * each other. These vectors are not expected to be normalized. If
406  * one or more vectors have zero length, implementation behavior
407  * is undefined. If the two vectors are linearly dependent,
408  * behavior is undefined.
409  */
410 void SGSoundMgr::set_orientation( SGQuatd ori )
411 {
412     SGVec3d sgv_up = ori.rotate(SGVec3d::e2());
413     SGVec3d sgv_at = ori.rotate(SGVec3d::e3());
414     for (int i=0; i<3; i++) {
415        _listener_ori[i] = sgv_at[i];
416        _listener_ori[i+3] = sgv_up[i];
417     }
418     _changed = true;
419 }
420
421
422 bool SGSoundMgr::testForError(void *p, string s)
423 {
424    if (p == NULL) {
425       SG_LOG( SG_GENERAL, SG_ALERT, "Error: " << s);
426       return true;
427    }
428    return false;
429 }
430
431
432 bool SGSoundMgr::testForALError(string s)
433 {
434     ALenum error = alGetError();
435     if (error != AL_NO_ERROR)  {
436        SG_LOG( SG_GENERAL, SG_ALERT, "AL Error (sound manager): "
437                                       << alGetString(error) << " at " << s);
438        return true;
439     }
440     return false;
441 }
442
443 bool SGSoundMgr::testForALCError(string s)
444 {
445     ALCenum error;
446     error = alcGetError(_device);
447     if (error != ALC_NO_ERROR) {
448         SG_LOG( SG_GENERAL, SG_ALERT, "ALC Error (sound manager): "
449                                        << alcGetString(_device, error) << " at "
450                                        << s);
451         return true;
452     }
453     return false;
454 }
455
456 bool SGSoundMgr::testForALUTError(string s)
457 {
458     ALenum error;
459     error =  alutGetError ();
460     if (error != ALUT_ERROR_NO_ERROR) {
461         SG_LOG( SG_GENERAL, SG_ALERT, "ALUT Error (sound manager): "
462                                        << alutGetErrorString(error) << " at "
463                                        << s);
464         return true;
465     }
466     return false;
467 }