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