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