]> git.mxchange.org Git - simgear.git/blob - simgear/sound/xmlsound.cxx
0c8c3fd92ebf37ba64402701115ba1d90283c4f2
[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., 675 Mass Ave, Cambridge, MA 02139, USA.
21 //
22 // $Id$
23
24 #include <simgear/compiler.h>
25
26 #ifdef SG_HAVE_STD_INCLUDES
27 #  include <cmath>
28 #else
29 #  include <math.h>
30 #endif
31 #include <string.h>
32
33 #include <simgear/debug/logstream.hxx>
34 #include <simgear/props/condition.hxx>
35 #include <simgear/math/fastmath.hxx>
36
37
38 #include "xmlsound.hxx"
39
40
41 #define LOG_ABS(x) (((x) > 1) ? (x) : (((x) < -1) ? -(x) : 0))
42 // static double _snd_lin(double v)   { return v; }
43 static double _snd_inv(double v)   { return (v == 0) ? 1e99 : 1/v; }
44 static double _snd_abs(double v)   { return (v >= 0) ? v : -v; }
45 static double _snd_sqrt(double v)  { return (v < 0) ? sqrt(-v) : sqrt(v); }
46 static double _snd_log10(double v) { return fast_log10( LOG_ABS(v) ); }
47 static double _snd_log(double v)   { return fast_log( LOG_ABS(v) ); }
48 // static double _snd_sqr(double v)   { return v*v; }
49 // static double _snd_pow3(double v)  { return v*v*v; }
50
51 static const struct {
52         char *name;
53         double (*fn)(double);
54 } __sound_fn[] = {
55 //      {"lin", _snd_lin},
56         {"inv", _snd_inv},
57         {"abs", _snd_abs},
58         {"sqrt", _snd_sqrt},
59         {"log", _snd_log10},
60         {"ln", _snd_log},
61 //      {"sqr", _snd_sqr},
62 //      {"pow3", _snd_pow3},
63         {"", NULL}
64 };
65
66 SGXmlSound::SGXmlSound()
67   : _sample(NULL),
68     _condition(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     _stopping(0.0)
76 {
77 }
78
79 SGXmlSound::~SGXmlSound()
80 {
81     _sample->stop();
82
83     delete _condition;
84
85     _volume.clear();
86     _pitch.clear();
87 }
88
89 void
90 SGXmlSound::init(SGPropertyNode *root, SGPropertyNode *node, SGSoundMgr *sndmgr,
91                  const string &path)
92 {
93
94    //
95    // set global sound properties
96    //
97    
98    _name = node->getStringValue("name", "");
99    SG_LOG(SG_GENERAL, SG_INFO, "Loading sound information for: " << _name );
100
101    const char *mode_str = node->getStringValue("mode", "");
102    if ( !strcmp(mode_str, "looped") ) {
103        _mode = SGXmlSound::LOOPED;
104
105    } else if ( !strcmp(mode_str, "in-transit") ) {
106        _mode = SGXmlSound::IN_TRANSIT;
107
108    } else {
109       _mode = SGXmlSound::ONCE;
110
111       if ( strcmp(mode_str, "") )
112          SG_LOG(SG_GENERAL,SG_INFO, "  Unknown sound mode, default to 'once'");
113    }
114
115    _property = root->getNode(node->getStringValue("property", ""), true);
116    SGPropertyNode *condition = node->getChild("condition");
117    if (condition != NULL)
118       _condition = sgReadCondition(root, condition);
119
120    if (!_property && !_condition)
121       SG_LOG(SG_GENERAL, SG_WARN,
122              "  Neither a condition nor a property specified");
123
124    //
125    // set volume properties
126    //
127    unsigned int i;
128    float v = 0.0;
129    vector<SGPropertyNode_ptr> kids = node->getChildren("volume");
130    for (i = 0; (i < kids.size()) && (i < SGXmlSound::MAXPROP); i++) {
131       _snd_prop volume = {NULL, NULL, NULL, 1.0, 0.0, 0.0, 0.0, false};
132
133       if (strcmp(kids[i]->getStringValue("property"), ""))
134          volume.prop = root->getNode(kids[i]->getStringValue("property", ""), true);
135
136       const char *intern_str = kids[i]->getStringValue("internal", "");
137       if (!strcmp(intern_str, "dt_play"))
138          volume.intern = &_dt_play;
139       else if (!strcmp(intern_str, "dt_stop"))
140          volume.intern = &_dt_stop;
141
142       if ((volume.factor = kids[i]->getDoubleValue("factor", 1.0)) != 0.0)
143          if (volume.factor < 0.0) {
144             volume.factor = -volume.factor;
145             volume.subtract = true;
146          }
147
148       const char *type_str = kids[i]->getStringValue("type", "");
149       if ( strcmp(type_str, "") ) {
150
151          for (int j=0; __sound_fn[j].fn; j++)
152            if ( !strcmp(type_str, __sound_fn[j].name) ) {
153                volume.fn = __sound_fn[j].fn;
154                break;
155             }
156
157          if (!volume.fn)
158             SG_LOG(SG_GENERAL,SG_INFO,
159                    "  Unknown volume type, default to 'lin'");
160       }
161
162       volume.offset = kids[i]->getDoubleValue("offset", 0.0);
163
164       if ((volume.min = kids[i]->getDoubleValue("min", 0.0)) < 0.0)
165          SG_LOG( SG_GENERAL, SG_WARN,
166           "Volume minimum value below 0. Forced to 0.");
167
168       volume.max = kids[i]->getDoubleValue("max", 0.0);
169       if (volume.max && (volume.max < volume.min) )
170          SG_LOG(SG_GENERAL,SG_ALERT,
171                 "  Volume maximum below minimum. Neglected.");
172
173       _volume.push_back(volume);
174       v += volume.offset;
175
176    }
177
178    float reference_dist = node->getDoubleValue("reference-dist", 500.0);
179    float max_dist = node->getDoubleValue("max-dist", 3000.0);
180  
181    //
182    // set pitch properties
183    //
184    float p = 0.0;
185    kids = node->getChildren("pitch");
186    for (i = 0; (i < kids.size()) && (i < SGXmlSound::MAXPROP); i++) {
187       _snd_prop pitch = {NULL, NULL, NULL, 1.0, 1.0, 0.0, 0.0, false};
188
189       if (strcmp(kids[i]->getStringValue("property", ""), ""))
190          pitch.prop = root->getNode(kids[i]->getStringValue("property", ""), true);
191
192       const char *intern_str = kids[i]->getStringValue("internal", "");
193       if (!strcmp(intern_str, "dt_play"))
194          pitch.intern = &_dt_play;
195       else if (!strcmp(intern_str, "dt_stop"))
196          pitch.intern = &_dt_stop;
197
198       if ((pitch.factor = kids[i]->getDoubleValue("factor", 1.0)) != 0.0)
199          if (pitch.factor < 0.0) {
200             pitch.factor = -pitch.factor;
201             pitch.subtract = true;
202          }
203
204       const char *type_str = kids[i]->getStringValue("type", "");
205       if ( strcmp(type_str, "") ) {
206
207          for (int j=0; __sound_fn[j].fn; j++) 
208             if ( !strcmp(type_str, __sound_fn[j].name) ) {
209                pitch.fn = __sound_fn[j].fn;
210                break;
211             }
212
213          if (!pitch.fn)
214             SG_LOG(SG_GENERAL,SG_INFO,
215                    "  Unknown pitch type, default to 'lin'");
216       }
217      
218       pitch.offset = kids[i]->getDoubleValue("offset", 1.0);
219
220       if ((pitch.min = kids[i]->getDoubleValue("min", 0.0)) < 0.0)
221          SG_LOG(SG_GENERAL,SG_WARN,
222                 "  Pitch minimum value below 0. Forced to 0.");
223
224       pitch.max = kids[i]->getDoubleValue("max", 0.0);
225       if (pitch.max && (pitch.max < pitch.min) )
226          SG_LOG(SG_GENERAL,SG_ALERT,
227                 "  Pitch maximum below minimum. Neglected");
228
229       _pitch.push_back(pitch);
230       p += pitch.offset;
231    }
232
233    //
234    // Relative position
235    //
236    sgVec3 offset_pos;
237    sgSetVec3( offset_pos, 0.0, 0.0, 0.0 );
238    SGPropertyNode_ptr pos = node->getChild("position");
239    if ( pos != NULL ) {
240        offset_pos[0] = pos->getDoubleValue("x", 0.0);
241        offset_pos[1] = pos->getDoubleValue("y", 0.0);
242        offset_pos[2] = pos->getDoubleValue("z", 0.0);
243    }
244
245    //
246    // Orientation
247    //
248    sgVec3 dir;
249    float inner, outer, outer_gain;
250    sgSetVec3( dir, 0.0, 0.0, 0.0 );
251    inner = outer = 360.0;
252    outer_gain = 0.0;
253    pos = node->getChild("orientation");
254    if ( pos != NULL ) {
255       dir[0] = pos->getDoubleValue("x", 0.0);
256       dir[1] = pos->getDoubleValue("y", 0.0);
257       dir[2] = pos->getDoubleValue("z", 0.0);
258       inner = pos->getDoubleValue("inner-angle", 360.0);
259       outer = pos->getDoubleValue("outer-angle", 360.0);
260       outer_gain = pos->getDoubleValue("outer-gain", 0.0);
261    }
262    
263    //
264    // Initialize the sample
265    //
266    _mgr = sndmgr;
267    if ( (_sample = _mgr->find(_name)) == NULL ) {
268        // FIXME: Does it make sense to overwrite a previous entry's
269        // configuration just because a new entry has the same name?
270        // Note that we can't match on identical "path" because we the
271        // new entry could be at a different location with different
272        // configuration so we need a new sample which creates a new
273        // "alSource".  The semantics of what is going on here seems
274        // confused and needs to be thought through more carefully.
275         _sample = new SGSoundSample( path.c_str(),
276                                     node->getStringValue("path", "") );
277
278        _mgr->add( _sample, _name );
279    }
280
281    _sample->set_offset_pos( offset_pos );
282    _sample->set_orientation(dir, inner, outer, outer_gain);
283    _sample->set_volume(v);
284    _sample->set_reference_dist( reference_dist );
285    _sample->set_max_dist( max_dist );
286    _sample->set_pitch(p);
287 }
288
289 void
290 SGXmlSound::update (double dt)
291 {
292    double curr_value = 0.0;
293
294    //
295    // If the state changes to false, stop playing.
296    //
297    if (_property)
298        curr_value = _property->getDoubleValue();
299
300    if (                                                 // Lisp, anyone?
301        (_condition && !_condition->test()) ||
302        (!_condition && _property &&
303         (
304          !curr_value ||
305          ( (_mode == SGXmlSound::IN_TRANSIT) && (curr_value == _prev_value) )
306          )
307         )
308        )
309    {
310        if ((_mode != SGXmlSound::IN_TRANSIT) || (_stopping > MAX_TRANSIT_TIME)) {
311            if (_sample->is_playing()) {
312                SG_LOG(SG_GENERAL, SG_INFO, "Stopping audio after " << _dt_play
313                       << " sec: " << _name );
314
315                _sample->stop();
316            }
317
318            _active = false;
319            _dt_stop += dt;
320            _dt_play = 0.0;
321        } else {
322            _stopping += dt;
323        }
324
325        return;
326    }
327
328    //
329    // If the mode is ONCE and the sound is still playing,
330    //  we have nothing to do anymore.
331    //
332    if (_active && (_mode == SGXmlSound::ONCE)) {
333
334       if (!_sample->is_playing()) {
335          _dt_stop += dt;
336          _dt_play = 0.0;
337       } else {
338          _dt_play += dt;
339       }
340
341       return;
342    }
343
344    //
345    // Update the playing time, cache the current value and
346    // clear the delay timer.
347    //
348    _dt_play += dt;
349    _prev_value = curr_value;
350    _stopping = 0.0;
351
352    //
353    // Update the volume
354    //
355    int i;
356    int max = _volume.size();
357    double volume = 1.0;
358    double volume_offset = 0.0;
359
360    for(i = 0; i < max; i++) {
361       double v = 1.0;
362
363       if (_volume[i].prop)
364          v = _volume[i].prop->getDoubleValue();
365
366       else if (_volume[i].intern)
367          v = *_volume[i].intern;
368
369       if (_volume[i].fn)
370          v = _volume[i].fn(v);
371
372       v *= _volume[i].factor;
373
374       if (_volume[i].max && (v > _volume[i].max))
375          v = _volume[i].max;
376
377       else if (v < _volume[i].min)
378          v = _volume[i].min;
379
380       if (_volume[i].subtract)                          // Hack!
381          volume = _volume[i].offset - v;
382
383       else {
384          volume_offset += _volume[i].offset;
385          volume *= v;
386       }
387    }
388
389    //
390    // Update the pitch
391    //
392    max = _pitch.size();
393    double pitch = 1.0;
394    double pitch_offset = 0.0;
395
396    for(i = 0; i < max; i++) {
397       double p = 1.0;
398
399       if (_pitch[i].prop)
400          p = _pitch[i].prop->getDoubleValue();
401
402       else if (_pitch[i].intern)
403          p = *_pitch[i].intern;
404
405       if (_pitch[i].fn)
406          p = _pitch[i].fn(p);
407
408       p *= _pitch[i].factor;
409
410       if (_pitch[i].max && (p > _pitch[i].max))
411          p = _pitch[i].max;
412
413       else if (p < _pitch[i].min)
414          p = _pitch[i].min;
415
416       if (_pitch[i].subtract)                           // Hack!
417          pitch = _pitch[i].offset - p;
418
419       else {
420          pitch_offset += _pitch[i].offset;
421          pitch *= p;
422       }
423    }
424
425    //
426    // Change sample state
427    //
428    _sample->set_pitch( pitch_offset + pitch );
429    if ((volume_offset + volume ) > 1.0)
430    {
431       _sample->set_volume( 1.0 );
432       SG_LOG(SG_GENERAL, SG_WARN,
433              "Volume larger than 1.0 in configuration for '" << _name
434               << "', clipping.");
435    } else 
436       _sample->set_volume( volume_offset + volume );
437
438
439    //
440    // Do we need to start playing the sample?
441    //
442    if (!_active) {
443
444       if (_mode == SGXmlSound::ONCE)
445          _sample->play(false);
446
447       else
448          _sample->play(true);
449
450       SG_LOG(SG_GENERAL, SG_INFO, "Playing audio after " << _dt_stop 
451                                    << " sec: " << _name);
452       SG_LOG(SG_GENERAL, SG_BULK,
453                          "Playing " << ((_mode == ONCE) ? "once" : "looped"));
454
455       _active = true;
456       _dt_stop = 0.0;
457    }
458 }