]> git.mxchange.org Git - simgear.git/blob - simgear/sound/xmlsound.cxx
Use quadtree to improve culling of STG objects
[simgear.git] / simgear / sound / xmlsound.cxx
1 // sound.cxx -- Sound class implementation
2 //
3 // Started by Erik Hofman, February 2002
4 // (Reuses some code from  fg_fx.cxx created by David Megginson)
5 //
6 // Copyright (C) 2002  Curtis L. Olson - http://www.flightgear.org/~curt
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 as
10 // published by the Free Software Foundation; either version 2 of the
11 // License, or (at your option) any later version.
12 //
13 // This program is distributed in the hope that it will be useful, but
14 // WITHOUT ANY WARRANTY; without even the implied warranty of
15 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16 // 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 // $Id$
23
24 #ifdef HAVE_CONFIG_H
25 #  include <simgear_config.h>
26 #endif
27
28 #include "xmlsound.hxx"
29
30
31 #include <simgear/compiler.h>
32
33 #include <string.h>
34
35 #include <simgear/debug/logstream.hxx>
36 #include <simgear/props/props.hxx>
37 #include <simgear/props/condition.hxx>
38 #include <simgear/structure/exception.hxx>
39 #include <simgear/misc/sg_path.hxx>
40
41 #include "sample_group.hxx"
42 #include "sample_openal.hxx"
43
44 using std::string;
45
46 // static double _snd_lin(double v)   { return v; }
47 static double _snd_inv(double v)   { return (v == 0) ? 1e99 : 1/v; }
48 static double _snd_abs(double v)   { return (v >= 0) ? v : -v; }
49 static double _snd_sqrt(double v)  { return sqrt(fabs(v)); }
50 static double _snd_log10(double v) { return log10(fabs(v)+1e-9); }
51 static double _snd_log(double v)   { return log(fabs(v)+1e-9); }
52 // static double _snd_sqr(double v)   { return v*v; }
53 // static double _snd_pow3(double v)  { return v*v*v; }
54
55 static const struct {
56         const char *name;
57         double (*fn)(double);
58 } __sound_fn[] = {
59         {"inv", _snd_inv},
60         {"abs", _snd_abs},
61         {"sqrt", _snd_sqrt},
62         {"log", _snd_log10},
63         {"ln", _snd_log},
64         {"", NULL}
65 };
66
67 SGXmlSound::SGXmlSound()
68   : _sample(NULL),
69     _active(false),
70     _name(""),
71     _mode(SGXmlSound::ONCE),
72     _prev_value(0),
73     _dt_play(0.0),
74     _dt_stop(0.0),
75     _delay(0.0),
76     _stopping(0.0),
77     _initialized(false)
78 {
79 }
80
81 SGXmlSound::~SGXmlSound()
82 {
83     if (_sample)
84         _sample->stop();
85
86     _volume.clear();
87     _pitch.clear();
88 }
89
90 void
91 SGXmlSound::init( SGPropertyNode *root,
92                   SGPropertyNode *node,
93                   SGSampleGroup *sgrp,
94                   SGSampleGroup *avionics,
95                   const SGPath& path )
96 {
97
98    //
99    // set global sound properties
100    //
101
102    _name = node->getStringValue("name", "");
103    SG_LOG(SG_SOUND, SG_DEBUG, "Loading sound information for: " << _name );
104
105    string mode_str = node->getStringValue("mode", "");
106    if ( mode_str == "looped" ) {
107        _mode = SGXmlSound::LOOPED;
108
109    } else if ( mode_str == "in-transit" ) {
110        _mode = SGXmlSound::IN_TRANSIT;
111
112    } else {
113       _mode = SGXmlSound::ONCE;
114    }
115
116    bool is_avionics = false;
117    string type_str = node->getStringValue("type", "fx");
118    if ( type_str == "avionics" )
119       is_avionics = true;
120
121    string propval = node->getStringValue("property", "");
122    if (propval != "")
123       _property = root->getNode(propval, true);
124
125    SGPropertyNode *condition = node->getChild("condition");
126    if (condition != NULL)
127       _condition = sgReadCondition(root, condition);
128
129    if (!_property && !_condition)
130       SG_LOG(SG_SOUND, SG_WARN,
131              "  Neither a condition nor a property specified");
132
133    _delay = node->getDoubleValue("delay-sec", 0.0);
134
135    //
136    // set volume properties
137    //
138    unsigned int i;
139    float v = 0.0;
140    std::vector<SGPropertyNode_ptr> kids = node->getChildren("volume");
141    for (i = 0; (i < kids.size()) && (i < SGXmlSound::MAXPROP); i++) {
142       _snd_prop volume = {NULL, NULL, NULL, 1.0, 0.0, 0.0, 0.0, false};
143
144       propval = kids[i]->getStringValue("property", "");
145       if ( propval != "" )
146          volume.prop = root->getNode(propval, true);
147
148       string intern_str = kids[i]->getStringValue("internal", "");
149       if (intern_str == "dt_play")
150          volume.intern = &_dt_play;
151       else if (intern_str == "dt_stop")
152          volume.intern = &_dt_stop;
153
154       if ((volume.factor = kids[i]->getDoubleValue("factor", 1.0)) != 0.0)
155          if (volume.factor < 0.0) {
156             volume.factor = -volume.factor;
157             volume.subtract = true;
158          }
159
160       string type_str = kids[i]->getStringValue("type", "");
161       if ( type_str != "" ) {
162
163          for (int j=0; __sound_fn[j].fn; j++)
164            if ( type_str == __sound_fn[j].name ) {
165                volume.fn = __sound_fn[j].fn;
166                break;
167             }
168
169          if (!volume.fn)
170             SG_LOG(SG_SOUND,SG_INFO,
171                    "  Unknown volume type, default to 'lin'");
172       }
173
174       volume.offset = kids[i]->getDoubleValue("offset", 0.0);
175
176       if ((volume.min = kids[i]->getDoubleValue("min", 0.0)) < 0.0)
177          SG_LOG( SG_SOUND, SG_WARN,
178           "Volume minimum value below 0. Forced to 0.");
179
180       volume.max = kids[i]->getDoubleValue("max", 0.0);
181       if (volume.max && (volume.max < volume.min) )
182          SG_LOG(SG_SOUND,SG_ALERT,
183                 "  Volume maximum below minimum. Neglected.");
184
185       _volume.push_back(volume);
186       v += volume.offset;
187
188    }
189
190    // rule of thumb: make reference distance a 100th of the maximum distance.
191    float reference_dist = node->getDoubleValue("reference-dist", 60.0);
192    float max_dist = node->getDoubleValue("max-dist", 6000.0);
193
194    //
195    // set pitch properties
196    //
197    float p = 0.0;
198    kids = node->getChildren("pitch");
199    for (i = 0; (i < kids.size()) && (i < SGXmlSound::MAXPROP); i++) {
200       _snd_prop pitch = {NULL, NULL, NULL, 1.0, 1.0, 0.0, 0.0, false};
201
202       propval = kids[i]->getStringValue("property", "");
203       if (propval != "")
204          pitch.prop = root->getNode(propval, true);
205
206       string intern_str = kids[i]->getStringValue("internal", "");
207       if (intern_str == "dt_play")
208          pitch.intern = &_dt_play;
209       else if (intern_str == "dt_stop")
210          pitch.intern = &_dt_stop;
211
212       if ((pitch.factor = kids[i]->getDoubleValue("factor", 1.0)) != 0.0)
213          if (pitch.factor < 0.0) {
214             pitch.factor = -pitch.factor;
215             pitch.subtract = true;
216          }
217
218       string type_str = kids[i]->getStringValue("type", "");
219       if ( type_str != "" ) {
220
221          for (int j=0; __sound_fn[j].fn; j++) 
222             if ( type_str == __sound_fn[j].name ) {
223                pitch.fn = __sound_fn[j].fn;
224                break;
225             }
226
227          if (!pitch.fn)
228             SG_LOG(SG_SOUND,SG_INFO,
229                    "  Unknown pitch type, default to 'lin'");
230       }
231      
232       pitch.offset = kids[i]->getDoubleValue("offset", 1.0);
233
234       if ((pitch.min = kids[i]->getDoubleValue("min", 0.0)) < 0.0)
235          SG_LOG(SG_SOUND,SG_WARN,
236                 "  Pitch minimum value below 0. Forced to 0.");
237
238       pitch.max = kids[i]->getDoubleValue("max", 0.0);
239       if (pitch.max && (pitch.max < pitch.min) )
240          SG_LOG(SG_SOUND,SG_ALERT,
241                 "  Pitch maximum below minimum. Neglected");
242
243       _pitch.push_back(pitch);
244       p += pitch.offset;
245    }
246
247    //
248    // Relative position
249    //
250    SGVec3f offset_pos = SGVec3f::zeros();
251    SGPropertyNode_ptr prop = node->getChild("position");
252    if ( prop != NULL ) {
253        offset_pos[0] = -prop->getDoubleValue("x", 0.0);
254        offset_pos[1] = -prop->getDoubleValue("y", 0.0);
255        offset_pos[2] = -prop->getDoubleValue("z", 0.0);
256    }
257
258    //
259    // Orientation
260    //
261    SGVec3f dir = SGVec3f::zeros();
262    float inner = 360.0;
263    float outer = 360.0;
264    float outer_gain = 0.0;
265    prop = node->getChild("orientation");
266    if ( prop != NULL ) {
267       dir = SGVec3f(-prop->getFloatValue("x", 0.0),
268                     -prop->getFloatValue("y", 0.0),
269                     -prop->getFloatValue("z", 0.0));
270       inner = prop->getFloatValue("inner-angle", 360.0);
271       outer = prop->getFloatValue("outer-angle", 360.0);
272       outer_gain = prop->getFloatValue("outer-gain", 0.0);
273    }
274
275    //
276    // Initialize the sample
277    //
278    if ((is_avionics)&&(avionics)) {
279       _sgrp = avionics;
280    } else {
281       _sgrp = sgrp;
282    }
283    string soundFileStr = node->getStringValue("path", "");
284    _sample = new SGSoundSample(soundFileStr.c_str(), path);
285    if (!_sample->file_path().exists()) {
286       throw sg_io_exception("XML sound: couldn't find file: '" + soundFileStr + "'");
287    }
288    
289    _sample->set_relative_position( offset_pos );
290    _sample->set_direction( dir );
291    _sample->set_audio_cone( inner, outer, outer_gain );
292    _sample->set_reference_dist( reference_dist );
293    _sample->set_max_dist( max_dist );
294    _sample->set_volume( v );
295    _sample->set_pitch( p );
296    _sgrp->add( _sample, _name );
297 }
298
299 void
300 SGXmlSound::update (double dt)
301 {
302    double curr_value = 0.0;
303
304    //
305    // If the state changes to false, stop playing.
306    //
307    if (_property)
308        curr_value = _property->getDoubleValue();
309
310    if (!_initialized)
311    {
312        // update initial value before detecting changes
313        _prev_value  = curr_value;
314        _initialized = true;
315    }
316
317    // If a condition is defined, test whether it is FALSE,
318    // else
319    //   if a property is defined then test if it's value is FALSE
320    //      or if the mode is IN_TRANSIT then
321    //            test whether the current value matches the previous value.
322    if (                                                 // Lisp, anyone?
323        (_condition && !_condition->test()) ||
324        (!_condition && _property &&
325         (
326          !curr_value ||
327          ( (_mode == SGXmlSound::IN_TRANSIT) && (curr_value == _prev_value) )
328          )
329         )
330        )
331    {
332        if ((_mode != SGXmlSound::IN_TRANSIT) || (_stopping > MAX_TRANSIT_TIME))
333        {
334            if (_sample->is_playing()) {
335                SG_LOG(SG_SOUND, SG_DEBUG, "Stopping audio after " << _dt_play
336                       << " sec: " << _name );
337
338                _sample->stop();
339            }
340
341            _active = false;
342            _dt_stop += dt;
343            _dt_play = 0.0;
344        } else {
345            _stopping += dt;
346        }
347
348        return;
349    }
350
351    //
352    // mode is ONCE and the sound is still playing?
353    //
354    if (_active && (_mode == SGXmlSound::ONCE)) {
355
356       if (!_sample->is_playing()) {
357          _dt_stop += dt;
358          _dt_play = 0.0;
359       } else {
360          _dt_play += dt;
361       }
362
363    } else {
364
365       //
366       // Update the playing time, cache the current value and
367       // clear the delay timer.
368       //
369       _dt_play += dt;
370       _prev_value = curr_value;
371       _stopping = 0.0;
372    }
373
374    if (_dt_play < _delay)
375       return;
376
377    //
378    // Update the volume
379    //
380    int i;
381    int max = _volume.size();
382    double volume = 1.0;
383    double volume_offset = 0.0;
384
385    for(i = 0; i < max; i++) {
386       double v = 1.0;
387
388       if (_volume[i].prop)
389          v = _volume[i].prop->getDoubleValue();
390
391       else if (_volume[i].intern)
392          v = *_volume[i].intern;
393
394       if (_volume[i].fn)
395          v = _volume[i].fn(v);
396
397       v *= _volume[i].factor;
398
399       if (_volume[i].max && (v > _volume[i].max))
400          v = _volume[i].max;
401
402       else if (v < _volume[i].min)
403          v = _volume[i].min;
404
405       if (_volume[i].subtract)                          // Hack!
406          volume = _volume[i].offset - v;
407
408       else {
409          volume_offset += _volume[i].offset;
410          volume *= v;
411       }
412    }
413
414    //
415    // Update the pitch
416    //
417    max = _pitch.size();
418    double pitch = 1.0;
419    double pitch_offset = 0.0;
420
421    for(i = 0; i < max; i++) {
422       double p = 1.0;
423
424       if (_pitch[i].prop)
425          p = _pitch[i].prop->getDoubleValue();
426
427       else if (_pitch[i].intern)
428          p = *_pitch[i].intern;
429
430       if (_pitch[i].fn)
431          p = _pitch[i].fn(p);
432
433       p *= _pitch[i].factor;
434
435       if (_pitch[i].max && (p > _pitch[i].max))
436          p = _pitch[i].max;
437
438       else if (p < _pitch[i].min)
439          p = _pitch[i].min;
440
441       if (_pitch[i].subtract)                           // Hack!
442          pitch = _pitch[i].offset - p;
443
444       else {
445          pitch_offset += _pitch[i].offset;
446          pitch *= p;
447       }
448    }
449
450    //
451    // Change sample state
452    //
453
454    double vol = volume_offset + volume;
455    if (vol > 1.0) {
456       SG_LOG(SG_SOUND, SG_DEBUG, "Sound volume too large for '"
457               << _name << "':  " << vol << "  ->  clipping to 1.0");
458       vol = 1.0;
459    }
460    _sample->set_volume(vol);
461    _sample->set_pitch( pitch_offset + pitch );
462
463
464    //
465    // Do we need to start playing the sample?
466    //
467    if (!_active) {
468
469       if (_mode == SGXmlSound::ONCE)
470          _sample->play(false);
471
472       else
473          _sample->play(true);
474
475       SG_LOG(SG_SOUND, SG_DEBUG, "Playing audio after " << _dt_stop
476                                    << " sec: " << _name);
477       SG_LOG(SG_SOUND, SG_DEBUG,
478                          "Playing " << ((_mode == ONCE) ? "once" : "looped"));
479
480       _active = true;
481       _dt_stop = 0.0;
482    }
483 }