]> git.mxchange.org Git - flightgear.git/blob - src/ATCDCL/atis.cxx
Use deferred models for scenery tile models.
[flightgear.git] / src / ATCDCL / atis.cxx
1 // atis.cxx - routines to generate the ATIS info string
2 // This is the implementation of the FGATIS class
3 //
4 // Written by David Luff, started October 2001.
5 //
6 // Copyright (C) 2001  David C Luff - david.luff@nottingham.ac.uk
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 /////
23 ///// TODO:  _Cumulative_ sky coverage.
24 ///// TODO:  wind _gust_
25 ///// TODO:  more-sensible encoding of voice samples
26 /////       u-law?  outright synthesis?
27 /////
28
29 #ifdef HAVE_CONFIG_H
30 #  include <config.h>
31 #endif
32
33 #include "atis.hxx"
34 #include "atis_lexicon.hxx"
35
36 #include <simgear/compiler.h>
37 #include <simgear/math/sg_random.h>
38 #include <simgear/misc/sg_path.hxx>
39
40 #include <stdlib.h> // atoi()
41 #include <stdio.h>  // sprintf
42 #include <string>
43 #include <iostream>
44
45 #include <boost/tuple/tuple.hpp>
46 #include <boost/algorithm/string.hpp>
47 #include <boost/algorithm/string/case_conv.hpp>
48
49 #include <Environment/environment_mgr.hxx>
50 #include <Environment/environment.hxx>
51 #include <Environment/atmosphere.hxx>
52
53 #include <Main/fg_props.hxx>
54 #include <Main/globals.hxx>
55 #include <Airports/runways.hxx>
56 #include <Airports/dynamics.hxx>
57
58
59 #include "ATCutils.hxx"
60 #include "ATCmgr.hxx"
61
62 using std::string;
63 using std::map;
64 using std::cout;
65 using std::cout;
66 using boost::ref;
67 using boost::tie;
68
69 FGATIS::FGATIS() :
70   transmission(""),
71   trans_ident(""),
72   old_volume(0),
73   atis_failed(false),
74   msg_OK(0),
75   attention(0),
76   _prev_display(0),
77   refname("atis")
78 {
79   _vPtr = globals->get_ATC_mgr()->GetVoicePointer(ATIS);
80   _voiceOK = (_vPtr == NULL ? false : true);
81   if (!(_type != ATIS || _type == AWOS)) {
82        SG_LOG(SG_ATC, SG_ALERT, "ERROR - _type not ATIS or AWOS in atis.cxx");
83   }
84   fgTie("/environment/attention", this, (int_getter)0, &FGATIS::attend);
85
86 ///////////////
87 // FIXME:  This would be more flexible and more extensible
88 // if the mappings were taken from an XML file, not hard-coded ...
89 // ... although having it in a .hxx file is better than nothing.
90 //
91 // Load the remap list from the .hxx file:
92   using namespace lex;
93 # define NIL ""
94 # define REMAP(from,to) _remap[#from] = to;
95 # include "atis_remap.hxx"
96 # undef REMAP
97 # undef NIL
98
99 #ifdef ATIS_TEST
100   SG_LOG(SG_ATC, SG_ALERT, "ATIS initialized");
101 #endif
102 }
103
104 // Hint:
105 // http://localhost:5400/environment/attention?value=1&submit=update
106
107 FGATIS::~FGATIS() {
108   fgUntie("/environment/attention");
109 }
110
111 void FGATIS::Init() {
112 // Nothing to see here.  Move along.
113 }
114
115 void
116 FGATIS::attend (int attn)
117 {
118   attention = attn;
119 #ifdef ATMO_TEST
120   int flag = fgGetInt("/sim/logging/atmo");
121   if (flag) {
122     FGAltimeter().check_model();
123         FGAltimeter().dump_stack();
124   }
125 #endif
126 }
127
128
129 // Main update function - checks whether we are displaying or not the correct message.
130 void FGATIS::Update(double dt) {
131   cur_time = globals->get_time_params()->get_cur_time();
132   msg_OK = (msg_time < cur_time);
133 #ifdef ATIS_TEST
134   if (msg_OK || _display != _prev_display) {
135     cout << "ATIS Update: " << _display << "  " << _prev_display
136       << "  len: " << transmission.length()
137       << "  oldvol: " << old_volume
138       << "  dt: " << dt << endl;
139     msg_time = cur_time;
140   }
141 #endif
142   if(_display) {
143     double volume(0);
144     for (map<string,int>::iterator act = active_on.begin();
145     act != active_on.end(); act++) {
146       string prop = "/instrumentation/" + act->first + "/volume";
147       volume += globals->get_props()->getDoubleValue(prop.c_str());
148     }
149
150 // Check if we need to update the message
151 // - basically every hour and if the weather changes significantly at the station
152 // If !_prev_display, the radio had been detuned for a while and our
153 // "transmission" variable was lost when we were de-instantiated.
154     int rslt = GenTransmission(!_prev_display, attention);
155     TreeOut(msg_OK);
156     if (rslt || volume != old_volume) {
157       //cout << "ATIS calling ATC::render  volume: " << volume << endl;
158       Render(transmission, volume, refname, true);
159       old_volume = volume;
160     }
161   } else {
162 // We shouldn't be displaying
163     //cout << "ATIS.CXX - calling NoRender()..." << endl;
164     NoRender(refname);
165   }
166   _prev_display = _display;
167   attention = 0;
168 }
169
170 string uppercase(const string &s) {
171   string rslt(s);
172   for(string::iterator p = rslt.begin(); p != rslt.end(); p++){
173     *p = toupper(*p);
174   }
175   return rslt;
176 }
177
178 // Replace all occurrences of a given word.
179 // Words in the original string must be separated by hyphens (not spaces).
180 // We check for the word as given, and for the all-caps version thereof.
181 string replace_word(const string _orig, const string _www, const string _nnn){
182 // The following are so we can match words at the beginning
183 // and end of the string.
184   string orig = "-" + _orig + "-";
185   string www = "-" + _www + "-";
186   string nnn = "-" + _nnn + "-";
187
188   size_t where(0);
189   for ( ; (where = orig.find(www, where)) != string::npos ; ) {
190     orig.replace(where, www.length(), nnn);
191     where += nnn.length();
192   }
193   
194   www = uppercase(www);
195   for ( ; (where = orig.find(www, where)) != string::npos ; ) {
196     orig.replace(where, www.length(), nnn);
197     where += nnn.length();
198   }
199   where = orig.length();
200   return orig.substr(1, where-2);
201 }
202
203 // Normally the interval is 1 hour, 
204 // but you can shorten it for testing.
205 const int minute(60);           // measured in seconds
206 #ifdef ATIS_TEST
207   const int ATIS_interval(2*minute);
208 #else
209   const int ATIS_interval(60*minute);
210 #endif
211
212 // FIXME:  This is heuristic.  It gets the right answer for
213 // more than 90% of the world's airports, which is a lot
214 // better than nothing ... but it's not 100%.
215 // We know "most" of the world uses millibars,
216 // but the US, Canada and *some* other places use inches of mercury,
217 // but (a) we have not implemented a reliable method of
218 // ascertaining which airports are in the US, let alone
219 // (b) ascertaining which other places use inches.
220 //
221 int Apt_US_CA(const string id) {
222 // Assume all IDs have length 3 or 4.
223 // No counterexamples have been seen.
224   if (id.length() == 4) {
225     if (id.substr(0,1) == "K") return 1;
226     if (id.substr(0,2) == "CY") return 1;
227   }
228   for (string::const_iterator ptr = id.begin(); ptr != id.end();  ptr++) {
229     if (isdigit(*ptr)) return 1;
230   }
231   return 0;
232 }
233
234 // Generate the actual broadcast ATIS transmission.
235 // Regen means regenerate the /current/ transmission.
236 // Special means generate a new transmission, with a new sequence.
237 // Returns 1 if we actually generated something.
238 int FGATIS::GenTransmission(const int regen, const int special) {
239   using namespace atmodel;
240   using namespace lex;
241
242   string BRK = ".\n";
243   string PAUSE = " / ";
244
245   int interval = _type == ATIS ?
246         ATIS_interval   // ATIS updated hourly
247       : 2*minute;       // AWOS updated more frequently
248
249   FGAirport* apt = FGAirport::findByIdent(ident);
250   int sequence = apt->getDynamics()->updateAtisSequence(interval, special);
251   if (!regen && sequence > LTRS) {
252 //xx      if (msg_OK) cout << "ATIS:  no change: " << sequence << endl;
253 //xx      msg_time = cur_time;
254     return 0;   // no change since last time
255   }
256
257   const int bs(100);
258   char buf[bs];
259   string time_str = fgGetString("sim/time/gmt-string");
260   string hours, mins;
261   string phonetic_seq_string;
262
263   transmission = "";
264
265   int US_CA = Apt_US_CA(ident);
266
267   if (!US_CA) {
268 // UK CAA radiotelephony manual indicates ATIS transmissions start
269 // with "This is ..." 
270     transmission += This_is + " ";
271   } else {
272     // In the US they just start with the airport name.
273   }
274
275   // SG_LOG(SG_ATC, SG_ALERT, "ATIS: facility name: " << name);
276
277 // Note that at this point, multi-word facility names
278 // will sometimes contain hyphens, not spaces.
279   
280   vector<string> name_words;
281   boost::split(name_words, name, boost::is_any_of(" -"));
282
283   for (vector<string>::const_iterator wordp = name_words.begin();
284                 wordp != name_words.end(); wordp++) {
285     string word(*wordp);
286 // Remap some abbreviations that occur in apt.dat, to
287 // make things nicer for the text-to-speech system:
288     for (MSS::const_iterator replace = _remap.begin();
289           replace != _remap.end(); replace++) {
290       // Due to inconsistent capitalisation in the apt.dat file, we need
291       // to do a case-insensitive comparison here.
292       string tmp1 = word, tmp2 = replace->first;
293       boost::algorithm::to_lower(tmp1);
294       boost::algorithm::to_lower(tmp2);
295       if (tmp1 == tmp2) {
296         word = replace->second;
297         break;
298       }
299     }
300     transmission += word + " ";
301   }
302
303   if (_type == ATIS /* as opposed to AWOS */) {
304     transmission += airport_information + " ";
305   } else {
306     transmission += Automated_weather_observation + " ";
307   }
308
309   phonetic_seq_string = GetPhoneticLetter(sequence);  // Add the sequence letter
310   transmission += phonetic_seq_string + BRK;
311
312 // Warning - this is fragile if the time string format changes
313   hours = time_str.substr(0,2).c_str();
314   mins  = time_str.substr(3,2).c_str();
315 // speak each digit separately:
316   transmission += ConvertNumToSpokenDigits(hours + mins);
317   transmission += " " + zulu + " " + weather + BRK;
318
319   transmission += wind + ": ";
320
321   double wind_speed = fgGetDouble("/environment/config/boundary/entry[0]/wind-speed-kt");
322   double wind_dir = fgGetDouble("/environment/config/boundary/entry[0]/wind-from-heading-deg");
323   while (wind_dir <= 0) wind_dir += 360;
324 // The following isn't as bad a kludge as it might seem.
325 // It combines the magvar at the /aircraft/ location with
326 // the wind direction in the environment/config array.
327 // But if the aircraft is close enough to the station to
328 // be receiving the ATIS signal, this should be a good-enough
329 // approximation.  For more-distant aircraft, the wind_dir
330 // shouldn't be corrected anyway.
331 // The less-kludgy approach would be to use the magvar associated
332 // with the station, but that is not tabulated in the stationweather
333 // structure as it stands, and computing it would be expensive.
334 // Also note that as it stands, there is only one environment in
335 // the entire FG universe, so the aircraft environment is the same
336 // as the station environment anyway.
337   wind_dir -= fgGetDouble("/environment/magnetic-variation-deg");       // wind_dir now magnetic
338   if (wind_speed == 0) {
339 // Force west-facing rwys to be used in no-wind situations
340 // which is consistent with Flightgear's initial setup:
341       wind_dir = 270;
342       transmission += " " + light_and_variable;
343   } else {
344       // FIXME: get gust factor in somehow
345       snprintf(buf, bs, "%03.0f", 5*SGMiscd::round(wind_dir/5));
346       transmission += ConvertNumToSpokenDigits(buf);
347
348       snprintf(buf, bs, "%1.0f", wind_speed);
349       transmission += " " + at + " " + ConvertNumToSpokenDigits(buf) + BRK;
350   }
351
352 // Sounds better with a pause in there:
353   transmission += PAUSE;
354
355   int did_some(0);
356   int did_ceiling(0);
357
358   for (int layer = 0; layer <= 4; layer++) {
359     snprintf(buf, bs, "/environment/clouds/layer[%i]/coverage", layer);
360     string coverage = fgGetString(buf);
361     if (coverage == clear) continue;
362     snprintf(buf, bs, "/environment/clouds/layer[%i]/thickness-ft", layer);
363     if (fgGetDouble(buf) == 0) continue;
364     snprintf(buf, bs, "/environment/clouds/layer[%i]/elevation-ft", layer);
365     double ceiling = int(fgGetDouble(buf) - _geod.getElevationFt());
366     if (ceiling > 12000) continue;
367
368 // BEWARE:  At the present time, the environment system has no
369 // way (so far as I know) to represent a "thin broken" or
370 // "thin overcast" layer.  If/when such things are implemented
371 // in the environment system, code will have to be written here
372 // to handle them.
373
374 // First, do the prefix if any:
375     if (coverage == scattered || coverage == few) {
376       if (!did_some) {
377         transmission += "   " + Sky_condition + ": ";
378         did_some++;
379       }
380     } else /* must be a ceiling */  if (!did_ceiling) {
381       transmission += "   " + Ceiling + ": ";
382       did_ceiling++;
383       did_some++;
384     } else {
385       transmission += "   ";    // no prefix required
386     }
387     int cig00  = int(SGMiscd::round(ceiling/100));  // hundreds of feet
388     if (cig00) {
389       int cig000 = cig00/10;
390       cig00 -= cig000*10;       // just the hundreds digit
391       if (cig000) {
392         snprintf(buf, bs, "%i", cig000);
393         transmission += ConvertNumToSpokenDigits(buf);
394         transmission += " " + thousand + " ";
395       }
396       if (cig00) {
397         snprintf(buf, bs, "%i", cig00);
398         transmission += ConvertNumToSpokenDigits(buf);
399         transmission += " " + hundred + " ";
400       }
401     } else {
402       // Should this be "sky obscured?"
403       transmission += " " + zero + " ";     // not "zero hundred"
404     }
405     transmission += coverage + BRK;
406   }
407   if (!did_some) transmission += "   " + Sky + " " + clear + BRK;
408
409   transmission += Temperature + ": ";
410   double Tsl = fgGetDouble("/environment/temperature-sea-level-degc");
411   int temp = int(SGMiscd::round(FGAtmo().fake_T_vs_a_us(_geod.getElevationFt(), Tsl)));
412   if(temp < 0) {
413       transmission += lex::minus + " ";
414   }
415   snprintf(buf, bs, "%i", abs(temp));
416   transmission += ConvertNumToSpokenDigits(buf);
417   if (US_CA) transmission += " " + Celsius;
418   transmission += " " + dewpoint + " ";
419   double dpsl = fgGetDouble("/environment/dewpoint-sea-level-degc");
420   temp = int(SGMiscd::round(FGAtmo().fake_dp_vs_a_us(dpsl, _geod.getElevationFt())));
421   if(temp < 0) {
422       transmission += lex::minus + " ";
423   }
424   snprintf(buf, bs, "%i", abs(temp));
425   transmission += ConvertNumToSpokenDigits(buf);
426   if (US_CA) transmission += " " + Celsius;
427   transmission += BRK;
428
429   transmission += Visibility + ": ";
430   double visibility = fgGetDouble("/environment/config/boundary/entry[0]/visibility-m");
431   visibility /= atmodel::sm;    // convert to statute miles
432   if (visibility < 0.25) {
433     transmission += less_than_one_quarter;
434   } else if (visibility < 0.5) {
435     transmission += one_quarter;
436   } else if (visibility < 0.75) {
437     transmission += one_half;
438   } else if (visibility < 1.0) {
439     transmission += three_quarters;
440   } else if (visibility >= 1.5 && visibility < 2.0) {
441     transmission += one_and_one_half;
442   } else {
443     // integer miles
444     if (visibility > 10) visibility = 10;
445     sprintf(buf, "%i", int(.5 + visibility));
446     transmission += ConvertNumToSpokenDigits(buf);
447   }
448   transmission += BRK;
449
450   double myQNH;
451   double Psl = fgGetDouble("/environment/pressure-sea-level-inhg");
452   {
453     double press, temp;
454     
455     tie(press, temp) = PT_vs_hpt(_geod.getElevationM(), Psl*inHg, Tsl + freezing);
456 #if 0
457     SG_LOG(SG_ATC, SG_ALERT, "Field P: " << press << "  T: " << temp);
458     SG_LOG(SG_ATC, SG_ALERT, "based on elev " << elev 
459                                 << "  Psl: " << Psl
460                                 << "  Tsl: " << Tsl);
461 #endif
462     myQNH = FGAtmo().QNH(_geod.getElevationM(), press);
463   }
464
465 // Convert to millibars for most of the world (not US, not CA)
466   if((!US_CA) && fgGetBool("/sim/atc/use-millibars")) {
467     transmission += QNH + ": ";
468     myQNH /= mbar;
469     if  (myQNH > 1000) myQNH -= 1000;       // drop high digit
470     snprintf(buf, bs, "%03.0f", myQNH);
471     transmission += ConvertNumToSpokenDigits(buf) + " " + millibars + BRK;
472   } else {
473     transmission += Altimeter + ": ";
474     double asetting = myQNH / inHg;         // use inches of mercury
475     asetting *= 100.;                       // shift two decimal places
476     snprintf(buf, bs, "%04.0f", asetting);
477     transmission += ConvertNumToSpokenDigits(buf) + BRK;
478   }
479
480   if (_type == ATIS /* as opposed to AWOS */) {
481     const FGAirport* apt = fgFindAirportID(ident);
482     if (apt) {
483       string rwy_no = apt->getActiveRunwayForUsage()->ident();
484       if(rwy_no != "NN") {
485         transmission += Landing_and_departing_runway + " ";
486         transmission += ConvertRwyNumToSpokenString(rwy_no) + BRK;
487 #ifdef ATIS_TEST
488         if (msg_OK) {
489           msg_time = cur_time;
490           cout << "In atis.cxx, r.rwy_no: " << rwy_no
491              << " wind_dir: " << wind_dir << endl;
492         }
493 #endif
494       }
495     }
496     transmission += On_initial_contact_advise_you_have_information + " ";
497     transmission += phonetic_seq_string;
498     transmission += "... " + BRK + PAUSE + PAUSE;
499   }
500   transmission_readable = transmission;
501 // Take the previous readable string and munge it to
502 // be relatively-more acceptable to the primitive tts system.
503 // Note that : ; and . are among the token-delimeters recognized
504 // by the tts system.
505   for (size_t where;;) {
506     where = transmission.find_first_of(":.");
507     if (where == string::npos) break;
508     transmission.replace(where, 1, PAUSE);
509   }
510   return 1;
511 }
512
513 // Put the transmission into the property tree,
514 // possibly in multiple places if multiple radios
515 // are tuned to the same ATIS.
516 // You can see it by pointing a web browser
517 // at the property tree.  The second comm radio is:
518 // http://localhost:5400/instrumentation/comm[1]
519 //
520 // (Also, if in debug mode, dump it to the console.)
521 void FGATIS::TreeOut(int msg_OK){
522   for (map<string,int>::iterator act = active_on.begin();
523                 act != active_on.end();
524                 act++){
525     string prop = "/instrumentation/" + act->first + "/atis";
526     globals->get_props()->setStringValue(prop.c_str(),
527       ("<pre>\n" + transmission_readable + "</pre>\n").c_str());
528 #ifdef ATIS_TEST
529     if (msg_OK) cout << "**** ATIS active on: " << prop << endl;
530 #endif
531   }
532 #ifdef ATIS_TEST
533   if (msg_OK) cout << transmission_readable << endl;
534 #endif
535 }