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