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