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