]> git.mxchange.org Git - flightgear.git/blob - src/Airports/apt_loader.cxx
Code cleanups, code updates and fix at least on (possible) devide-by-zero
[flightgear.git] / src / Airports / apt_loader.cxx
1 // apt_loader.cxx -- a front end loader of the apt.dat file.  This loader
2 //                   populates the runway and basic classes.
3 //
4 // Written by Curtis Olson, started August 2000.
5 //
6 // Copyright (C) 2000  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
25 #ifdef HAVE_CONFIG_H
26 #  include <config.h>
27 #endif
28
29 #include "apt_loader.hxx"
30
31 #include <simgear/compiler.h>
32
33 #include <stdlib.h> // atof(), atoi()
34 #include <string.h> // memchr()
35 #include <ctype.h> // isspace()
36
37 #include <simgear/constants.h>
38 #include <simgear/debug/logstream.hxx>
39 #include <simgear/misc/sgstream.hxx>
40 #include <simgear/misc/strutils.hxx>
41 #include <simgear/structure/exception.hxx>
42 #include <simgear/misc/sg_path.hxx>
43
44 #include <string>
45
46 #include "airport.hxx"
47 #include "runways.hxx"
48 #include "pavement.hxx"
49 #include <Navaids/NavDataCache.hxx>
50 #include <ATC/CommStation.hxx>
51
52 #include <iostream>
53 #include <sstream>              // std::istringstream
54
55 using namespace std;
56
57 typedef SGSharedPtr<FGPavement> FGPavementPtr;
58
59 static FGPositioned::Type fptypeFromRobinType(int aType)
60 {
61   switch (aType) {
62   case 1: return FGPositioned::AIRPORT;
63   case 16: return FGPositioned::SEAPORT;
64   case 17: return FGPositioned::HELIPORT;
65   default:
66     SG_LOG(SG_GENERAL, SG_ALERT, "unsupported type:" << aType);
67     throw sg_range_exception("Unsupported airport type", "fptypeFromRobinType");
68   }
69 }
70
71 // generated by 'wc -l' on the uncompressed file
72 const unsigned int LINES_IN_APT_DAT = 2465648;
73
74 namespace flightgear
75 {
76   
77 class APTLoader
78 {
79 public:
80
81   APTLoader()
82   :  last_apt_id(""),
83      last_apt_elev(0.0),
84      last_apt_info("")
85   {
86     currentAirportID = 0;
87     cache = NavDataCache::instance();
88   }
89
90   void parseAPT(const SGPath &aptdb_file)
91   {
92     std::string apt_dat = aptdb_file.str();
93     sg_gzifstream in(apt_dat);
94
95     if ( !in.is_open() ) {
96       SG_LOG( SG_GENERAL, SG_ALERT, "Cannot open file: " << apt_dat );
97       throw sg_io_exception("cannot open apt.dat file", apt_dat.c_str());
98     }
99
100     string line;
101
102     unsigned int line_id = 0;
103     unsigned int line_num = 0;
104
105     // Read the apt.dat header (two lines)
106     while ( line_num < 2 && std::getline(in, line) ) {
107       // 'line' may end with an \r character (tested on Linux, only \n was
108       // stripped: std::getline() only discards the _native_ line terminator)
109       line_num++;
110
111       if ( line_num == 1 ) {
112         std::string stripped_line = simgear::strutils::strip(line);
113         // First line indicates IBM ("I") or Macintosh ("A") line endings.
114         if ( stripped_line != "I" && stripped_line != "A" ) {
115           std::string pb = "invalid first line (neither 'I' nor 'A')";
116           SG_LOG( SG_GENERAL, SG_ALERT, apt_dat << ": " << pb);
117           throw sg_format_exception("cannot parse apt.dat file: " + pb,
118                                     apt_dat);
119         }
120       } else {     // second line of the file
121         std::istringstream s(line);
122         int apt_dat_format_version;
123         s >> apt_dat_format_version;
124         SG_LOG( SG_GENERAL, SG_INFO,
125                 "apt.dat format version: " << apt_dat_format_version );
126       }
127     } // end of the apt.dat header
128
129     throwExceptionIfStreamError(in, "apt.dat", apt_dat);
130
131     while ( std::getline(in, line) ) {
132       // 'line' may end with an \r character, see above
133       line_num++;
134
135       if ( isBlankOrCommentLine(line) )
136         continue;
137
138       if ((line_num % 100) == 0) {
139         // every 100 lines
140         unsigned int percent = (line_num * 100) / LINES_IN_APT_DAT;
141         cache->setRebuildPhaseProgress(NavDataCache::REBUILD_AIRPORTS, percent);
142       }
143
144       // Extract the first field into 'line_id'
145       line_id = atoi(line.c_str());
146
147       if ( line_id == 1 /* Airport */ ||
148            line_id == 16 /* Seaplane base */ ||
149            line_id == 17 /* Heliport */ ) {
150         parseAirportLine(simgear::strutils::split(line));
151       } else if ( line_id == 10 ) { // Runway v810
152         parseRunwayLine810(simgear::strutils::split(line));
153       } else if ( line_id == 100 ) { // Runway v850
154         parseRunwayLine850(simgear::strutils::split(line));
155       } else if ( line_id == 101 ) { // Water Runway v850
156         parseWaterRunwayLine850(simgear::strutils::split(line));
157       } else if ( line_id == 102 ) { // Helipad v850
158         parseHelipadLine850(simgear::strutils::split(line));
159       } else if ( line_id == 18 ) {
160             // beacon entry (ignore)
161       } else if ( line_id == 14 ) {
162         // control tower entry
163         vector<string> token(simgear::strutils::split(line));
164         
165         double lat = atof( token[1].c_str() );
166         double lon = atof( token[2].c_str() );
167         double elev = atof( token[3].c_str() );
168         tower = SGGeod::fromDegFt(lon, lat, elev + last_apt_elev);        
169         cache->insertTower(currentAirportID, tower);
170       } else if ( line_id == 19 ) {
171           // windsock entry (ignore)
172       } else if ( line_id == 20 ) {
173           // Taxiway sign (ignore)
174       } else if ( line_id == 21 ) {
175           // lighting objects (ignore)
176       } else if ( line_id == 15 ) {
177           // custom startup locations (ignore)
178       } else if ( line_id == 0 ) {
179           // ??
180       } else if ( line_id >= 50 && line_id <= 56) {
181         parseCommLine(line_id, simgear::strutils::split(line));
182       } else if ( line_id == 110 ) {
183         pavement = true;
184         parsePavementLine850(simgear::strutils::split(line, 0, 4));
185       } else if ( line_id >= 111 && line_id <= 114 ) {
186         if ( pavement )
187           parsePavementNodeLine850(line_id, simgear::strutils::split(line));
188       } else if ( line_id >= 115 && line_id <= 116 ) {
189           // other pavement nodes (ignore)
190       } else if ( line_id == 120 ) {
191         pavement = false;
192       } else if ( line_id == 130 ) {
193         pavement = false;
194       } else if ( line_id >= 1000 ) {
195           // airport traffic flow (ignore)
196       } else if ( line_id == 99 ) {
197           SG_LOG( SG_GENERAL, SG_DEBUG, "End of file reached" );
198       } else {
199           SG_LOG( SG_GENERAL, SG_ALERT, 
200                   "Unknown line(#" << line_num << ") in apt.dat file: " << line );
201           throw sg_format_exception("malformed line in apt.dat:", line);
202       }
203     }
204
205     throwExceptionIfStreamError(in, "apt.dat", apt_dat);
206     finishAirport();
207   }
208   
209 private:
210   vector<string> token;
211   double rwy_lat_accum;
212   double rwy_lon_accum;
213   double last_rwy_heading;
214   int rwy_count;
215   string last_apt_id;
216   double last_apt_elev;
217   SGGeod tower;
218   string last_apt_info;
219   string pavement_ident;
220   bool pavement;
221   
222   //vector<FGRunwayPtr> runways;
223   //vector<FGTaxiwayPtr> taxiways;
224   vector<FGPavementPtr> pavements;
225   
226   NavDataCache* cache;
227   PositionedID currentAirportID;
228
229   // Tell whether an apt.dat line is blank or a comment line
230   bool isBlankOrCommentLine(const std::string& line)
231   {
232     size_t pos = line.find_first_not_of(" \t");
233     return ( pos == std::string::npos || line.find("##", pos) == pos );
234   }
235
236   void throwExceptionIfStreamError(const sg_gzifstream& input_stream,
237                                    const std::string& short_name,
238                                    const std::string& full_path)
239   {
240     if ( input_stream.bad() ) {
241       // strerror() isn't thread-safe, unfortunately...
242       SG_LOG( SG_GENERAL, SG_ALERT, "error while reading " << full_path );
243       throw sg_io_exception("error while reading " + short_name,
244                             full_path.c_str());
245     }
246   }
247
248   void finishAirport()
249   {
250     if (currentAirportID == 0) {
251       return;
252     }
253     
254     if (!rwy_count) {
255       currentAirportID = 0;
256       SG_LOG(SG_GENERAL, SG_ALERT, "ERROR: No runways for " << last_apt_id
257               << ", skipping." );
258       return;
259     }
260
261     double lat = rwy_lat_accum / (double)rwy_count;
262     double lon = rwy_lon_accum / (double)rwy_count;
263
264     SGGeod pos(SGGeod::fromDegFt(lon, lat, last_apt_elev));
265     cache->updatePosition(currentAirportID, pos);
266     
267     currentAirportID = 0;
268   }
269   
270   void parseAirportLine(const vector<string>& token)
271   {
272     const string& id(token[4]);
273     double elev = atof( token[1].c_str() );
274
275   // finish the previous airport
276     finishAirport();
277             
278     last_apt_elev = elev;
279
280     string name;
281     // build the name
282     for ( unsigned int i = 5; i < token.size() - 1; ++i ) {
283         name += token[i] + " ";
284     }
285     name += token[token.size() - 1];
286
287     // clear runway list for start of next airport
288     rwy_lon_accum = 0.0;
289     rwy_lat_accum = 0.0;
290     rwy_count = 0;
291     
292     int robinType = atoi(token[0].c_str());
293     currentAirportID = cache->insertAirport(fptypeFromRobinType(robinType), id, name);
294   }
295   
296   void parseRunwayLine810(const vector<string>& token)
297   {
298     double lat = atof( token[1].c_str() );
299     double lon = atof( token[2].c_str() );
300     rwy_lat_accum += lat;
301     rwy_lon_accum += lon;
302     rwy_count++;
303
304     const string& rwy_no(token[3]);
305
306     double heading = atof( token[4].c_str() );
307     double length = atoi( token[5].c_str() );
308     double width = atoi( token[8].c_str() );
309     length *= SG_FEET_TO_METER;
310     width *= SG_FEET_TO_METER;
311
312     // adjust lat / lon to the start of the runway/taxiway, not the middle
313     SGGeod pos_1 = SGGeodesy::direct( SGGeod::fromDegFt(lon, lat, last_apt_elev), heading, -length/2 );
314
315     last_rwy_heading = heading;
316
317     int surface_code = atoi( token[10].c_str() );
318
319     if (rwy_no[0] == 'x') {  // Taxiway
320       cache->insertRunway(FGPositioned::TAXIWAY, rwy_no, pos_1, currentAirportID,
321                           heading, length, width, 0.0, 0.0, surface_code);
322     } else if (rwy_no[0] == 'H') {  // Helipad
323       SGGeod pos(SGGeod::fromDegFt(lon, lat, last_apt_elev));
324       cache->insertRunway(FGPositioned::HELIPAD, rwy_no, pos, currentAirportID,
325                           heading, length, width, 0.0, 0.0, surface_code);
326     } else {
327       // (pair of) runways
328       string rwy_displ_threshold = token[6];
329       vector<string> displ
330           = simgear::strutils::split( rwy_displ_threshold, "." );
331       double displ_thresh1 = atof( displ[0].c_str() );
332       double displ_thresh2 = atof( displ[1].c_str() );
333       displ_thresh1 *= SG_FEET_TO_METER;
334       displ_thresh2 *= SG_FEET_TO_METER;
335
336       string rwy_stopway = token[7];
337       vector<string> stop
338           = simgear::strutils::split( rwy_stopway, "." );
339       double stopway1 = atof( stop[0].c_str() );
340       double stopway2 = atof( stop[1].c_str() );
341       stopway1 *= SG_FEET_TO_METER;
342       stopway2 *= SG_FEET_TO_METER;
343
344       SGGeod pos_2 = SGGeodesy::direct( pos_1, heading, length );
345
346       PositionedID rwy = cache->insertRunway(FGPositioned::RUNWAY, rwy_no, pos_1,
347                                              currentAirportID, heading, length,
348                                              width, displ_thresh1, stopway1,
349                                              surface_code);
350       
351       PositionedID reciprocal = cache->insertRunway(FGPositioned::RUNWAY,
352                                              FGRunway::reverseIdent(rwy_no), pos_2,
353                                              currentAirportID,
354                                              SGMiscd::normalizePeriodic(0, 360, heading + 180.0),
355                                              length, width, displ_thresh2, stopway2,
356                                              surface_code);
357
358       cache->setRunwayReciprocal(rwy, reciprocal);
359     }
360   }
361
362   void parseRunwayLine850(const vector<string>& token)
363   {
364     double width = atof( token[1].c_str() );
365     int surface_code = atoi( token[2].c_str() );
366
367     double lat_1 = atof( token[9].c_str() );
368     double lon_1 = atof( token[10].c_str() );
369     SGGeod pos_1(SGGeod::fromDegFt(lon_1, lat_1, 0.0));
370     rwy_lat_accum += lat_1;
371     rwy_lon_accum += lon_1;
372     rwy_count++;
373
374     double lat_2 = atof( token[18].c_str() );
375     double lon_2 = atof( token[19].c_str() );
376     SGGeod pos_2(SGGeod::fromDegFt(lon_2, lat_2, 0.0));
377     rwy_lat_accum += lat_2;
378     rwy_lon_accum += lon_2;
379     rwy_count++;
380
381     double length, heading_1, heading_2;
382     SGGeodesy::inverse( pos_1, pos_2, heading_1, heading_2, length );
383
384     last_rwy_heading = heading_1;
385
386     const string& rwy_no_1(token[8]);
387     const string& rwy_no_2(token[17]);
388     if ( rwy_no_1.empty() || rwy_no_2.empty() )
389         return;
390
391     double displ_thresh1 = atof( token[11].c_str() );
392     double displ_thresh2 = atof( token[20].c_str() );
393
394     double stopway1 = atof( token[12].c_str() );
395     double stopway2 = atof( token[21].c_str() );
396
397     PositionedID rwy = cache->insertRunway(FGPositioned::RUNWAY, rwy_no_1, pos_1,
398                                            currentAirportID, heading_1, length,
399                                            width, displ_thresh1, stopway1,
400                                            surface_code);
401     
402     PositionedID reciprocal = cache->insertRunway(FGPositioned::RUNWAY,
403                                                   rwy_no_2, pos_2,
404                                                   currentAirportID, heading_2, length,
405                                                   width, displ_thresh2, stopway2,
406                                                   surface_code);
407     
408     cache->setRunwayReciprocal(rwy, reciprocal);
409   }
410
411   void parseWaterRunwayLine850(const vector<string>& token)
412   {
413     double width = atof( token[1].c_str() );
414
415     double lat_1 = atof( token[4].c_str() );
416     double lon_1 = atof( token[5].c_str() );
417     SGGeod pos_1(SGGeod::fromDegFt(lon_1, lat_1, 0.0));
418     rwy_lat_accum += lat_1;
419     rwy_lon_accum += lon_1;
420     rwy_count++;
421
422     double lat_2 = atof( token[7].c_str() );
423     double lon_2 = atof( token[8].c_str() );
424     SGGeod pos_2(SGGeod::fromDegFt(lon_2, lat_2, 0.0));
425     rwy_lat_accum += lat_2;
426     rwy_lon_accum += lon_2;
427     rwy_count++;
428
429     double length, heading_1, heading_2;
430     SGGeodesy::inverse( pos_1, pos_2, heading_1, heading_2, length );
431
432     last_rwy_heading = heading_1;
433
434     const string& rwy_no_1(token[3]);
435     const string& rwy_no_2(token[6]);
436
437     PositionedID rwy = cache->insertRunway(FGPositioned::RUNWAY, rwy_no_1, pos_1,
438                                            currentAirportID, heading_1, length,
439                                            width, 0.0, 0.0, 13);
440     
441     PositionedID reciprocal = cache->insertRunway(FGPositioned::RUNWAY,
442                                                   rwy_no_2, pos_2,
443                                                   currentAirportID, heading_2, length,
444                                                   width, 0.0, 0.0, 13);
445     
446     cache->setRunwayReciprocal(rwy, reciprocal);
447   }
448
449   void parseHelipadLine850(const vector<string>& token)
450   {
451     double length = atof( token[5].c_str() );
452     double width = atof( token[6].c_str() );
453
454     double lat = atof( token[2].c_str() );
455     double lon = atof( token[3].c_str() );
456     SGGeod pos(SGGeod::fromDegFt(lon, lat, 0.0));
457     rwy_lat_accum += lat;
458     rwy_lon_accum += lon;
459     rwy_count++;
460
461     double heading = atof( token[4].c_str() );
462
463     last_rwy_heading = heading;
464
465     const string& rwy_no(token[1]);
466     int surface_code = atoi( token[7].c_str() );
467
468     cache->insertRunway(FGPositioned::HELIPAD, rwy_no, pos,
469                         currentAirportID, heading, length,
470                         width, 0.0, 0.0, surface_code);
471   }
472
473   void parsePavementLine850(const vector<string>& token)
474   {
475     if ( token.size() >= 5 ) {
476       pavement_ident = token[4];
477       if ( !pavement_ident.empty() && pavement_ident[pavement_ident.size()-1] == '\r' )
478         pavement_ident.erase( pavement_ident.size()-1 );
479     } else {
480       pavement_ident = "xx";
481     }
482   }
483
484   void parsePavementNodeLine850(int num, const vector<string>& token)
485   {
486     double lat = atof( token[1].c_str() );
487     double lon = atof( token[2].c_str() );
488     SGGeod pos(SGGeod::fromDegFt(lon, lat, 0.0));
489
490     FGPavement* pvt = 0;
491     if ( !pavement_ident.empty() ) {
492       pvt = new FGPavement( 0, pavement_ident, pos );
493       pavements.push_back( pvt );
494       pavement_ident = "";
495     } else {
496       pvt = pavements.back();
497     }
498     if ( num == 112 || num == 114 ) {
499       double lat_b = atof( token[3].c_str() );
500       double lon_b = atof( token[4].c_str() );
501       SGGeod pos_b(SGGeod::fromDegFt(lon_b, lat_b, 0.0));
502       pvt->addBezierNode(pos, pos_b, num == 114);
503     } else {
504       pvt->addNode(pos, num == 113);
505     }
506   }
507
508   void parseCommLine(int lineId, const vector<string>& token) 
509   {
510     if ( rwy_count <= 0 ) {
511       SG_LOG( SG_GENERAL, SG_ALERT, "No runways; skipping comm for " + last_apt_id);
512     }
513  
514     SGGeod pos = SGGeod::fromDegFt(rwy_lon_accum / (double)rwy_count, 
515         rwy_lat_accum / (double)rwy_count, last_apt_elev);
516     
517     // short int representing tens of kHz:
518     int freqKhz = atoi(token[1].c_str()) * 10;
519     int rangeNm = 50;
520     FGPositioned::Type ty;
521     // Make sure we only pass on stations with at least a name
522     if (token.size() >2){
523
524         switch (lineId) {
525             case 50:
526                 ty = FGPositioned::FREQ_AWOS;
527                 for( size_t i = 2; i < token.size(); ++i )
528                 {
529                   if( token[i] == "ATIS" )
530                   {
531                     ty = FGPositioned::FREQ_ATIS;
532                     break;
533                   }
534                 }
535                 break;
536
537             case 51:    ty = FGPositioned::FREQ_UNICOM; break;
538             case 52:    ty = FGPositioned::FREQ_CLEARANCE; break;
539             case 53:    ty = FGPositioned::FREQ_GROUND; break;
540             case 54:    ty = FGPositioned::FREQ_TOWER; break;
541             case 55:
542             case 56:    ty = FGPositioned::FREQ_APP_DEP; break;
543             default:
544                 throw sg_range_exception("unsupported apt.dat comm station type");
545         }
546
547       // Name can contain white spaces. All tokens after the second token are
548       // part of the name.
549       std::string name = token[2];
550       for( size_t i = 3; i < token.size(); ++i )
551         name += ' ' + token[i];
552
553       cache->insertCommStation(ty, name, pos, freqKhz, rangeNm, currentAirportID);
554     }
555     else SG_LOG( SG_GENERAL, SG_DEBUG, "Found unnamed comm. Skipping: " << lineId);
556   }
557
558 };
559   
560 // Load the airport data base from the specified aptdb file.  The
561 // metar file is used to mark the airports as having metar available
562 // or not.
563 bool airportDBLoad( const SGPath &aptdb_file )
564 {
565   APTLoader ld;
566   ld.parseAPT(aptdb_file);
567   return true;
568 }
569   
570 bool metarDataLoad(const SGPath& metar_file)
571 {
572   sg_gzifstream metar_in( metar_file.str() );
573   if ( !metar_in.is_open() ) {
574     SG_LOG( SG_GENERAL, SG_ALERT, "Cannot open file: " << metar_file );
575     return false;
576   }
577   
578   NavDataCache* cache = NavDataCache::instance();
579
580   string ident;
581   while ( metar_in ) {
582     metar_in >> ident;
583     if ( ident == "#" || ident == "//" ) {
584       metar_in >> skipeol;
585     } else {
586       cache->setAirportMetar(ident, true);
587     }
588   }
589   
590   return true;
591 }
592
593 } // of namespace flightgear