]> git.mxchange.org Git - simgear.git/blob - simgear/sound/sample_group.cxx
- stop sounds when removing a sound group
[simgear.git] / simgear / sound / sample_group.cxx
1 // sample_group.cxx -- Manage a group of samples relative to a base position
2 //
3 // Written for the new SoundSystem by Erik Hofman, October 2009
4 //
5 // Copyright (C) 2009 Erik Hofman <erik@ehofman.com>
6 //
7 // This program is free software; you can redistribute it and/or
8 // modify it under the terms of the GNU General Public License as
9 // published by the Free Software Foundation; either version 2 of the
10 // License, or (at your option) any later version.
11 //
12 // This program is distributed in the hope that it will be useful, but
13 // WITHOUT ANY WARRANTY; without even the implied warranty of
14 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15 // General Public License for more details.
16 //
17 // You should have received a copy of the GNU General Public License
18 // along with this program; if not, write to the Free Software Foundation,
19 // Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
20 //
21 // $Id$
22
23 #ifdef HAVE_CONFIG_H
24 #  include <simgear_config.h>
25 #endif
26
27 #include <simgear/compiler.h>
28
29 #include "soundmgr_openal.hxx"
30 #include "sample_group.hxx"
31
32 bool isNaN(float *v) {
33    return (isnan(v[0]) || isnan(v[1]) || isnan(v[2]));
34 }
35
36 SGSampleGroup::SGSampleGroup () :
37     _smgr(NULL),
38     _refname(""),
39     _active(false),
40     _changed(false),
41     _pause(false),
42     _volume(1.0),
43     _tied_to_listener(false),
44     _velocity(SGVec3d::zeros()),
45     _orientation(SGQuatd::zeros())
46 {
47     _samples.clear();
48 }
49
50 SGSampleGroup::SGSampleGroup ( SGSoundMgr *smgr, const string &refname ) :
51     _smgr(smgr),
52     _refname(refname),
53     _active(false), 
54     _changed(false),
55     _pause(false),
56     _volume(1.0),
57     _tied_to_listener(false),
58     _velocity(SGVec3d::zeros()),
59     _orientation(SGQuatd::zeros())
60 {
61     _smgr->add(this, refname);
62     _samples.clear();
63 }
64
65 SGSampleGroup::~SGSampleGroup ()
66 {
67     _active = false;
68
69     this->stop();
70
71     _smgr = 0;
72 }
73
74 void SGSampleGroup::update( double dt ) {
75
76     if ( !_active || _pause ) return;
77
78     testForALError("start of update!!\n");
79
80     // Delete any OpenAL buffers that might still be in use.
81     unsigned int size = _removed_samples.size();
82     for (unsigned int i=0; i<size; ) {
83         SGSoundSample *sample = _removed_samples[i];
84         ALint result = AL_STOPPED;
85
86         if ( sample->is_valid_source() ) {
87             int source = sample->get_source();
88
89             alGetSourcei( source, AL_SOURCE_STATE, &result );
90             if ( sample->is_looping() ) {
91                 if ( result != AL_STOPPED ) {
92                     alSourceStop( source );
93                     alGetSourcei( source, AL_SOURCE_STATE, &result );
94                 }
95             }
96             if ( result == AL_STOPPED ) {
97                 sample->no_valid_source();
98                 _smgr->release_source( source );
99             }
100         }
101
102         if ( result == AL_STOPPED ) {
103             sample->stop();
104             if (( !sample->is_queue() )&&
105                 (sample->is_valid_buffer()))
106             {
107                 _smgr->release_buffer(sample);
108             }
109             _removed_samples.erase( _removed_samples.begin()+i );
110             size--;
111             continue;
112         }
113         i++;
114     }
115
116     // Update the position and orientation information for all samples.
117     if ( _changed || _smgr->has_changed() ) {
118         update_pos_and_orientation();
119         _changed = false;
120     }
121
122     sample_map_iterator sample_current = _samples.begin();
123     sample_map_iterator sample_end = _samples.end();
124     for ( ; sample_current != sample_end; ++sample_current ) {
125         SGSoundSample *sample = sample_current->second;
126
127         if ( !sample->is_valid_source() && sample->is_playing() && !sample->test_out_of_range()) {
128             //
129             // a request to start playing a sound has been filed.
130             //
131             ALuint source = _smgr->request_source();
132             if (alIsSource(source) == AL_TRUE )
133             {
134                 ALboolean looping = sample->is_looping() ? AL_TRUE : AL_FALSE;
135                 if ( sample->is_queue() )
136                 {
137                     sample->set_source( source );
138                     update_sample_config( sample );
139
140                     alSourcef( source, AL_ROLLOFF_FACTOR, 0.3 );
141                     alSourcei( source, AL_LOOPING, looping );
142                     alSourcei( source, AL_SOURCE_RELATIVE, AL_FALSE );
143                     alSourcePlay( source );
144                     testForALError("sample play");
145                 }
146                 else
147                 {
148                     ALuint buffer = _smgr->request_buffer(sample);
149                     if (buffer == SGSoundMgr::FAILED_BUFFER ||
150                         buffer == SGSoundMgr::NO_BUFFER)
151                     {
152                         _smgr->release_source(source);
153                         continue;
154                     }
155
156                     // start playing the sample
157                     buffer = sample->get_buffer();
158                     if ( alIsBuffer(buffer) == AL_TRUE )
159                     {
160                         alSourcei( source, AL_BUFFER, buffer );
161                         testForALError("assign buffer to source");
162
163                         sample->set_source( source );
164                         update_sample_config( sample );
165
166                         alSourcei( source, AL_LOOPING, looping );
167                         alSourcef( source, AL_ROLLOFF_FACTOR, 0.3 );
168                         alSourcei( source, AL_SOURCE_RELATIVE, AL_FALSE );
169                         alSourcePlay( source );
170                         testForALError("sample play");
171                     } else
172                         SG_LOG( SG_SOUND, SG_ALERT, "No such buffer!");
173                 }
174             }
175
176         } else if ( sample->is_valid_source() ) {
177             // check if the sound has stopped by itself
178
179             unsigned int source = sample->get_source();
180             int result;
181
182             alGetSourcei( source, AL_SOURCE_STATE, &result );
183             if ( result == AL_STOPPED ) {
184                 // sample is stopped because it wasn't looping
185                 sample->stop();
186                 sample->no_valid_source();
187                 _smgr->release_source( source );
188                 _smgr->release_buffer( sample );
189                 remove( sample->get_sample_name() );
190             }
191             else
192             if ( sample->has_changed() ) {
193                 if ( !sample->is_playing() ) {
194                     // a request to stop playing the sound has been filed.
195                     sample->stop();
196                     sample->no_valid_source();
197                     _smgr->release_source( sample->get_source() );
198                 } else if ( _smgr->has_changed() ) {
199                     update_sample_config( sample );
200                 }
201             }
202
203         }
204         testForALError("update");
205     }
206 }
207
208 // add a sound effect, return true if successful
209 bool SGSampleGroup::add( SGSharedPtr<SGSoundSample> sound, const string& refname ) {
210
211     sample_map_iterator sample_it = _samples.find( refname );
212     if ( sample_it != _samples.end() ) {
213         // sample name already exists
214         return false;
215     }
216
217     _samples[refname] = sound;
218     return true;
219 }
220
221
222 // remove a sound effect, return true if successful
223 bool SGSampleGroup::remove( const string &refname ) {
224
225     sample_map_iterator sample_it = _samples.find( refname );
226     if ( sample_it == _samples.end() ) {
227         // sample was not found
228         return false;
229     }
230
231     if ( sample_it->second->is_valid_buffer() )
232         _removed_samples.push_back( sample_it->second );
233
234     _samples.erase( sample_it );
235
236     return true;
237 }
238
239
240 // return true of the specified sound exists in the sound manager system
241 bool SGSampleGroup::exists( const string &refname ) {
242     sample_map_iterator sample_it = _samples.find( refname );
243     if ( sample_it == _samples.end() ) {
244         // sample was not found
245         return false;
246     }
247
248     return true;
249 }
250
251
252 // return a pointer to the SGSoundSample if the specified sound exists
253 // in the sound manager system, otherwise return NULL
254 SGSoundSample *SGSampleGroup::find( const string &refname ) {
255     sample_map_iterator sample_it = _samples.find( refname );
256     if ( sample_it == _samples.end() ) {
257         // sample was not found
258         return NULL;
259     }
260
261     return sample_it->second;
262 }
263
264
265 void
266 SGSampleGroup::stop ()
267 {
268     _pause = true;
269     sample_map_iterator sample_current = _samples.begin();
270     sample_map_iterator sample_end = _samples.end();
271     for ( ; sample_current != sample_end; ++sample_current ) {
272         SGSoundSample *sample = sample_current->second;
273
274         if ( sample->is_valid_source() ) {
275             ALint source = sample->get_source();
276             if ( sample->is_playing() ) {
277                 alSourceStop( source );
278             }
279             _smgr->release_source( source );
280             sample->no_valid_source();
281         }
282
283         if ( sample->is_valid_buffer() ) {
284             _smgr->release_buffer( sample );
285             sample->no_valid_buffer();
286         }
287     }
288     testForALError("stop");
289 }
290
291 // stop playing all associated samples
292 void
293 SGSampleGroup::suspend ()
294 {
295     if (_active && _pause == false) {
296         _pause = true;
297         sample_map_iterator sample_current = _samples.begin();
298         sample_map_iterator sample_end = _samples.end();
299         for ( ; sample_current != sample_end; ++sample_current ) {
300             SGSoundSample *sample = sample_current->second;
301
302             if ( sample->is_valid_source() && sample->is_playing() ) {
303                 alSourcePause( sample->get_source() );
304             }
305         }
306         testForALError("suspend");
307     }
308 }
309
310 // resume playing all associated samples
311 void
312 SGSampleGroup::resume ()
313 {
314     if (_active && _pause == true) {
315         sample_map_iterator sample_current = _samples.begin();
316         sample_map_iterator sample_end = _samples.end();
317         for ( ; sample_current != sample_end; ++sample_current ) {
318             SGSoundSample *sample = sample_current->second;
319
320             if ( sample->is_valid_source() && sample->is_playing() ) {
321                 alSourcePlay( sample->get_source() );
322             }
323         }
324         testForALError("resume");
325         _pause = false;
326     }
327 }
328
329
330 // tell the scheduler to play the indexed sample in a continuous loop
331 bool SGSampleGroup::play( const string &refname, bool looping = false ) {
332     SGSoundSample *sample = find( refname );
333
334     if ( sample == NULL ) {
335         return false;
336     }
337
338     sample->play( looping );
339     return true;
340 }
341
342
343 // return true of the specified sound is currently being played
344 bool SGSampleGroup::is_playing( const string& refname ) {
345     SGSoundSample *sample = find( refname );
346
347     if ( sample == NULL ) {
348         return false;
349     }
350
351     return ( sample->is_playing() ) ? true : false;
352 }
353
354 // immediate stop playing the sound
355 bool SGSampleGroup::stop( const string& refname ) {
356     SGSoundSample *sample  = find( refname );
357
358     if ( sample == NULL ) {
359         return false;
360     }
361
362     sample->stop();
363     return true;
364 }
365
366 void SGSampleGroup::set_volume( float vol )
367 {
368     if (vol > _volume*1.01 || vol < _volume*0.99) {
369         _volume = vol;
370         if (_volume < 0.0) _volume = 0.0;
371         if (_volume > 1.0) _volume = 1.0;
372         _changed = true;
373     }
374 }
375
376 // set the source position and orientation of all managed sounds
377 void SGSampleGroup::update_pos_and_orientation() {
378  
379     SGVec3d position = SGVec3d::fromGeod(_base_pos) - _smgr->get_position();
380     SGQuatd hlOr = SGQuatd::fromLonLat(_base_pos);
381     SGQuatd ec2body = hlOr*_orientation;
382
383     SGVec3f velocity = SGVec3f::zeros();
384     if ( _velocity[0] || _velocity[1] || _velocity[2] ) {
385        velocity = toVec3f( hlOr.backTransform(_velocity*SG_FEET_TO_METER) );
386     }
387
388     sample_map_iterator sample_current = _samples.begin();
389     sample_map_iterator sample_end = _samples.end();
390     for ( ; sample_current != sample_end; ++sample_current ) {
391         SGSoundSample *sample = sample_current->second;
392         sample->set_master_volume( _volume );
393         sample->set_orientation( _orientation );
394         sample->set_rotation( ec2body );
395         sample->set_position( position );
396         sample->set_velocity( velocity );
397
398         // Test if a sample is farther away than max distance, if so
399         // stop the sound playback and free it's source.
400         if (!_tied_to_listener) {
401             float max2 = sample->get_max_dist() * sample->get_max_dist();
402             float dist2 = position[0]*position[0]
403                           + position[1]*position[1] + position[2]*position[2];
404             if ((dist2 > max2) && !sample->test_out_of_range()) {
405                 sample->set_out_of_range(true);
406             } else if ((dist2 < max2) && sample->test_out_of_range()) {
407                 sample->set_out_of_range(false);
408             }
409         }
410     }
411 }
412
413 void SGSampleGroup::update_sample_config( SGSoundSample *sample ) {
414     SGVec3f orientation, velocity;
415     SGVec3d position;
416
417     if ( _tied_to_listener ) {
418         orientation = _smgr->get_direction();
419         position = SGVec3d::zeros();
420         velocity = _smgr->get_velocity();
421     } else {
422         sample->update_pos_and_orientation();
423         orientation = sample->get_orientation();
424         position = sample->get_position();
425         velocity = sample->get_velocity();
426     }
427
428     if (_smgr->bad_doppler_effect()) {
429         velocity *= 100.0f;
430     }
431
432 #if 0
433     if (length(position) > 20000)
434         printf("%s source and listener distance greater than 20km!\n",
435                _refname.c_str());
436     if (isNaN(toVec3f(position).data())) printf("NaN in source position\n");
437     if (isNaN(orientation.data())) printf("NaN in source orientation\n");
438     if (isNaN(velocity.data())) printf("NaN in source velocity\n");
439 #endif
440
441     unsigned int source = sample->get_source();
442     alSourcefv( source, AL_POSITION, toVec3f(position).data() );
443     alSourcefv( source, AL_VELOCITY, velocity.data() );
444     alSourcefv( source, AL_DIRECTION, orientation.data() );
445     testForALError("position and orientation");
446
447     alSourcef( source, AL_PITCH, sample->get_pitch() );
448     alSourcef( source, AL_GAIN, sample->get_volume() );
449     testForALError("pitch and gain");
450
451     if ( sample->has_static_data_changed() ) {
452         alSourcef( source, AL_CONE_INNER_ANGLE, sample->get_innerangle() );
453         alSourcef( source, AL_CONE_OUTER_ANGLE, sample->get_outerangle() );
454         alSourcef( source, AL_CONE_OUTER_GAIN, sample->get_outergain() );
455         testForALError("audio cone");
456
457         alSourcef( source, AL_MAX_DISTANCE, sample->get_max_dist() );
458         alSourcef( source, AL_REFERENCE_DISTANCE,
459                            sample->get_reference_dist() );
460         testForALError("distance rolloff");
461     }
462 }
463
464 bool SGSampleGroup::testForError(void *p, string s)
465 {
466    if (p == NULL) {
467       SG_LOG( SG_SOUND, SG_ALERT, "Error (sample group): " << s);
468       return true;
469    }
470    return false;
471 }
472
473 bool SGSampleGroup::testForALError(string s)
474 {
475     ALenum error = alGetError();
476     if (error != AL_NO_ERROR)  {
477        SG_LOG( SG_SOUND, SG_ALERT, "AL Error (" << _refname << "): "
478                                       << alGetString(error) << " at " << s);
479        return true;
480     }
481     return false;
482 }
483