1 // route.cxx - classes supporting waypoints and route structures
3 // Written by James Turner, started 2009.
5 // Copyright (C) 2009 Curtis L. Olson
7 // This program is free software; you can redistribute it and/or
8 // modify it under the terms of the GNU General Public License as
9 // published by the Free Software Foundation; either version 2 of the
10 // License, or (at your option) any later version.
12 // This program is distributed in the hope that it will be useful, but
13 // WITHOUT ANY WARRANTY; without even the implied warranty of
14 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 // General Public License for more details.
17 // You should have received a copy of the GNU General Public License
18 // along with this program; if not, write to the Free Software
19 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
32 #include <boost/algorithm/string/case_conv.hpp>
33 #include <boost/algorithm/string.hpp>
36 #include <simgear/structure/exception.hxx>
37 #include <simgear/xml/easyxml.hxx>
38 #include <simgear/misc/sg_path.hxx>
39 #include <simgear/magvar/magvar.hxx>
40 #include <simgear/timing/sg_time.hxx>
43 #include <Main/globals.hxx>
44 #include <Navaids/procedure.hxx>
45 #include <Navaids/waypoint.hxx>
46 #include <Airports/simple.hxx>
53 namespace flightgear {
55 const double NO_MAG_VAR = -1000.0; // an impossible mag-var value
57 Waypt::Waypt(Route* aOwner) :
60 _altRestrict(RESTRICT_NONE),
61 _speedRestrict(RESTRICT_NONE),
64 _magVarDeg(NO_MAG_VAR)
68 std::string Waypt::ident() const
73 bool Waypt::flag(WayptFlag aFlag) const
75 return ((_flags & aFlag) != 0);
78 void Waypt::setFlag(WayptFlag aFlag, bool aV)
80 _flags = (_flags & ~aFlag);
81 if (aV) _flags |= aFlag;
84 bool Waypt::matches(Waypt* aOther) const
87 if (ident() != aOther->ident()) { // cheap check first
91 return matches(aOther->position());
95 bool Waypt::matches(const SGGeod& aPos) const
97 double d = SGGeodesy::distanceM(position(), aPos);
98 return (d < 100.0); // 100 metres seems plenty
101 void Waypt::setAltitude(double aAlt, RouteRestriction aRestrict)
104 _altRestrict = aRestrict;
107 void Waypt::setSpeed(double aSpeed, RouteRestriction aRestrict)
110 _speedRestrict = aRestrict;
113 double Waypt::speedKts() const
115 assert(_speedRestrict != SPEED_RESTRICT_MACH);
119 double Waypt::speedMach() const
121 assert(_speedRestrict == SPEED_RESTRICT_MACH);
125 std::pair<double, double>
126 Waypt::courseAndDistanceFrom(const SGGeod& aPos) const
128 if (flag(WPT_DYNAMIC)) {
129 return std::make_pair(0.0, 0.0);
132 double course, az2, distance;
133 SGGeodesy::inverse(aPos, position(), course, az2, distance);
134 return std::make_pair(course, distance);
137 double Waypt::magvarDeg() const
139 if (_magVarDeg == NO_MAG_VAR) {
140 // derived classes with a default pos must override this method
141 assert(!(position() == SGGeod()));
143 double jd = globals->get_time_params()->getJD();
144 _magVarDeg = sgGetMagVar(position(), jd);
150 ///////////////////////////////////////////////////////////////////////////
153 static RouteRestriction restrictionFromString(const char* aStr)
155 std::string l = boost::to_lower_copy(std::string(aStr));
157 if (l == "at") return RESTRICT_AT;
158 if (l == "above") return RESTRICT_ABOVE;
159 if (l == "below") return RESTRICT_BELOW;
160 if (l == "none") return RESTRICT_NONE;
161 if (l == "mach") return SPEED_RESTRICT_MACH;
163 if (l.empty()) return RESTRICT_NONE;
164 throw sg_io_exception("unknown restriction specification:" + l,
165 "Route restrictFromString");
168 static const char* restrictionToString(RouteRestriction aRestrict)
171 case RESTRICT_AT: return "at";
172 case RESTRICT_BELOW: return "below";
173 case RESTRICT_ABOVE: return "above";
174 case RESTRICT_NONE: return "none";
175 case SPEED_RESTRICT_MACH: return "mach";
178 throw sg_exception("invalid route restriction",
179 "Route restrictToString");
183 Waypt* Waypt::createInstance(Route* aOwner, const std::string& aTypeName)
186 if (aTypeName == "basic") {
187 r = new BasicWaypt(aOwner);
188 } else if (aTypeName == "navaid") {
189 r = new NavaidWaypoint(aOwner);
190 } else if (aTypeName == "offset-navaid") {
191 r = new OffsetNavaidWaypoint(aOwner);
192 } else if (aTypeName == "hold") {
193 r = new Hold(aOwner);
194 } else if (aTypeName == "runway") {
195 r = new RunwayWaypt(aOwner);
196 } else if (aTypeName == "hdgToAlt") {
197 r = new HeadingToAltitude(aOwner);
198 } else if (aTypeName == "dmeIntercept") {
199 r = new DMEIntercept(aOwner);
200 } else if (aTypeName == "radialIntercept") {
201 r = new RadialIntercept(aOwner);
202 } else if (aTypeName == "vectors") {
203 r = new ATCVectors(aOwner);
206 if (!r || (r->type() != aTypeName)) {
207 throw sg_exception("broken factory method for type:" + aTypeName,
208 "Waypt::createInstance");
214 WayptRef Waypt::createFromProperties(Route* aOwner, SGPropertyNode_ptr aProp)
216 if (!aProp->hasChild("type")) {
217 throw sg_io_exception("bad props node, no type provided",
218 "Waypt::createFromProperties");
221 WayptRef nd(createInstance(aOwner, aProp->getStringValue("type")));
222 nd->initFromProperties(aProp);
226 void Waypt::saveAsNode(SGPropertyNode* n) const
228 n->setStringValue("type", type());
229 writeToProperties(n);
232 void Waypt::initFromProperties(SGPropertyNode_ptr aProp)
234 if (aProp->hasChild("generated")) {
235 setFlag(WPT_GENERATED, aProp->getBoolValue("generated"));
238 if (aProp->hasChild("overflight")) {
239 setFlag(WPT_OVERFLIGHT, aProp->getBoolValue("overflight"));
242 if (aProp->hasChild("arrival")) {
243 setFlag(WPT_ARRIVAL, aProp->getBoolValue("arrival"));
246 if (aProp->hasChild("departure")) {
247 setFlag(WPT_DEPARTURE, aProp->getBoolValue("departure"));
250 if (aProp->hasChild("miss")) {
251 setFlag(WPT_MISS, aProp->getBoolValue("miss"));
254 if (aProp->hasChild("alt-restrict")) {
255 _altRestrict = restrictionFromString(aProp->getStringValue("alt-restrict"));
256 _altitudeFt = aProp->getDoubleValue("altitude-ft");
259 if (aProp->hasChild("speed-restrict")) {
260 _speedRestrict = restrictionFromString(aProp->getStringValue("speed-restrict"));
261 _speed = aProp->getDoubleValue("speed");
267 void Waypt::writeToProperties(SGPropertyNode_ptr aProp) const
269 if (flag(WPT_OVERFLIGHT)) {
270 aProp->setBoolValue("overflight", true);
273 if (flag(WPT_DEPARTURE)) {
274 aProp->setBoolValue("departure", true);
277 if (flag(WPT_ARRIVAL)) {
278 aProp->setBoolValue("arrival", true);
281 if (flag(WPT_MISS)) {
282 aProp->setBoolValue("miss", true);
285 if (flag(WPT_GENERATED)) {
286 aProp->setBoolValue("generated", true);
289 if (_altRestrict != RESTRICT_NONE) {
290 aProp->setStringValue("alt-restrict", restrictionToString(_altRestrict));
291 aProp->setDoubleValue("altitude-ft", _altitudeFt);
294 if (_speedRestrict != RESTRICT_NONE) {
295 aProp->setStringValue("speed-restrict", restrictionToString(_speedRestrict));
296 aProp->setDoubleValue("speed", _speed);
300 void Route::dumpRouteToFile(const WayptVec& aRoute, const std::string& aName)
302 SGPath p = "/Users/jmt/Desktop/" + aName + ".kml";
304 f.open(p.str().c_str(), fstream::out | fstream::app);
306 SG_LOG(SG_GENERAL, SG_WARN, "unable to open:" << p.str());
311 f << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
312 "<kml xmlns=\"http://www.opengis.net/kml/2.2\">\n"
315 dumpRouteToLineString(aName, aRoute, f);
323 void Route::dumpRouteToLineString(const std::string& aIdent,
324 const WayptVec& aRoute, std::ostream& aStream)
327 aStream << "<Placemark>\n";
328 aStream << "<name>" << aIdent << "</name>\n";
329 aStream << "<LineString>\n";
330 aStream << "<tessellate>1</tessellate>\n";
331 aStream << "<coordinates>\n";
334 for (unsigned int i=0; i<aRoute.size(); ++i) {
335 SGGeod pos = aRoute[i]->position();
336 aStream << pos.getLongitudeDeg() << "," << pos.getLatitudeDeg() << " " << endl;
340 aStream << "</coordinates>\n"
342 "</Placemark>\n" << endl;
345 ///////////////////////////////////////////////////////////////////////////
347 class NavdataVisitor : public XMLVisitor {
349 NavdataVisitor(FGAirport* aApt, const SGPath& aPath);
352 virtual void startXML ();
353 virtual void endXML ();
354 virtual void startElement (const char * name, const XMLAttributes &atts);
355 virtual void endElement (const char * name);
356 virtual void data (const char * s, int len);
357 virtual void pi (const char * target, const char * data);
358 virtual void warning (const char * message, int line, int column);
359 virtual void error (const char * message, int line, int column);
362 Waypt* buildWaypoint();
363 void processRunways(ArrivalDeparture* aProc, const XMLAttributes &atts);
365 void finishApproach();
371 string _text; ///< last element text value
377 WayptVec _waypoints; ///< waypoint list for current approach/sid/star
378 WayptVec _transWaypts; ///< waypoint list for current transition
382 string _ident; // id of segment under construction
384 double _longitude, _latitude, _altitude, _speed;
385 RouteRestriction _altRestrict;
387 double _holdRadial; // inbound hold radial, or -1 if radial is 'inbound'
388 double _holdTD; ///< hold time (seconds) or distance (nm), based on flag below
389 bool _holdRighthanded;
390 bool _holdDistance; // true, TD is distance in nm; false, TD is time in seconds
392 double _course, _radial, _dmeDistance;
395 void Route::loadAirportProcedures(const SGPath& aPath, FGAirport* aApt)
399 NavdataVisitor visitor(aApt, aPath);
400 readXML(aPath.str(), visitor);
401 } catch (sg_io_exception& ex) {
402 SG_LOG(SG_GENERAL, SG_WARN, "failured parsing procedures: " << aPath.str() <<
403 "\n\t" << ex.getMessage() << "\n\tat:" << ex.getLocation().asString());
404 } catch (sg_exception& ex) {
405 SG_LOG(SG_GENERAL, SG_WARN, "failured parsing procedures: " << aPath.str() <<
406 "\n\t" << ex.getMessage());
410 NavdataVisitor::NavdataVisitor(FGAirport* aApt, const SGPath& aPath):
419 void NavdataVisitor::startXML()
423 void NavdataVisitor::endXML()
427 void NavdataVisitor::startElement(const char* name, const XMLAttributes &atts)
431 if (tag == "Airport") {
432 string icao(atts.getValue("ICAOcode"));
433 if (_airport->ident() != icao) {
434 throw sg_format_exception("Airport and ICAO mismatch", icao, _path.str());
436 } else if (tag == "Sid") {
437 string ident(atts.getValue("Name"));
438 _sid = new SID(ident);
440 processRunways(_sid, atts);
441 } else if (tag == "Star") {
442 string ident(atts.getValue("Name"));
443 _star = new STAR(ident);
445 processRunways(_star, atts);
446 } else if ((tag == "Sid_Waypoint") ||
447 (tag == "App_Waypoint") ||
448 (tag == "Star_Waypoint") ||
449 (tag == "AppTr_Waypoint") ||
450 (tag == "SidTr_Waypoint") ||
451 (tag == "RwyTr_Waypoint"))
453 // reset waypoint data
455 _altRestrict = RESTRICT_NONE;
457 } else if (tag == "Approach") {
458 _ident = atts.getValue("Name");
460 _approach = new Approach(_ident);
461 } else if ((tag == "Sid_Transition") ||
462 (tag == "App_Transition") ||
463 (tag == "Star_Transition")) {
464 _transIdent = atts.getValue("Name");
465 _transWaypts.clear();
466 } else if (tag == "RunwayTransition") {
467 _transIdent = atts.getValue("Runway");
468 _transWaypts.clear();
474 void NavdataVisitor::processRunways(ArrivalDeparture* aProc, const XMLAttributes &atts)
477 if (atts.hasAttribute("Runways")) {
478 v = atts.getValue("Runways");
482 for (unsigned int r=0; r<_airport->numRunways(); ++r) {
483 aProc->addRunway(_airport->getRunwayByIndex(r));
489 boost::split(rwys, v, boost::is_any_of(" ,"));
490 for (unsigned int r=0; r<rwys.size(); ++r) {
491 FGRunway* rwy = _airport->getRunwayByIdent(rwys[r]);
492 aProc->addRunway(rwy);
496 void NavdataVisitor::endElement(const char* name)
499 if ((tag == "Sid_Waypoint") ||
500 (tag == "App_Waypoint") ||
501 (tag == "Star_Waypoint"))
503 _waypoints.push_back(buildWaypoint());
504 } else if ((tag == "AppTr_Waypoint") ||
505 (tag == "SidTr_Waypoint") ||
506 (tag == "RwyTr_Waypoint") ||
507 (tag == "StarTr_Waypoint"))
509 _transWaypts.push_back(buildWaypoint());
510 } else if (tag == "Sid_Transition") {
512 // SID waypoints are stored backwards, to share code with STARs
513 std::reverse(_transWaypts.begin(), _transWaypts.end());
514 Transition* t = new Transition(_transIdent, _sid, _transWaypts);
515 _sid->addTransition(t);
516 } else if (tag == "Star_Transition") {
518 Transition* t = new Transition(_transIdent, _star, _transWaypts);
519 _star->addTransition(t);
520 } else if (tag == "App_Transition") {
522 Transition* t = new Transition(_transIdent, _approach, _transWaypts);
523 _approach->addTransition(t);
524 } else if (tag == "RunwayTransition") {
525 ArrivalDeparture* ad;
527 // SID waypoints are stored backwards, to share code with STARs
528 std::reverse(_transWaypts.begin(), _transWaypts.end());
534 Transition* t = new Transition(_transIdent, ad, _transWaypts);
535 FGRunwayRef rwy = _airport->getRunwayByIdent(_transIdent);
536 ad->addRunwayTransition(rwy, t);
537 } else if (tag == "Approach") {
539 } else if (tag == "Sid") {
541 } else if (tag == "Star") {
543 } else if (tag == "Longitude") {
544 _longitude = atof(_text.c_str());
545 } else if (tag == "Latitude") {
546 _latitude = atof(_text.c_str());
547 } else if (tag == "Name") {
549 } else if (tag == "Type") {
551 } else if (tag == "Speed") {
552 _speed = atoi(_text.c_str());
553 } else if (tag == "Altitude") {
554 _altitude = atof(_text.c_str());
555 } else if (tag == "AltitudeRestriction") {
557 _altRestrict = RESTRICT_AT;
558 } else if (_text == "above") {
559 _altRestrict = RESTRICT_ABOVE;
560 } else if (_text == "below") {
561 _altRestrict = RESTRICT_BELOW;
563 throw sg_format_exception("Unrecognized altitude restriction", _text);
565 } else if (tag == "Hld_Rad_or_Inbd") {
566 if (_text == "Inbd") {
569 } else if (tag == "Hld_Time_or_Dist") {
570 _holdDistance = (_text == "Dist");
571 } else if (tag == "Hld_Rad_value") {
572 _holdRadial = atof(_text.c_str());
573 } else if (tag == "Hld_Turn") {
574 _holdRighthanded = (_text == "Right");
575 } else if (tag == "Hld_td_value") {
576 _holdTD = atof(_text.c_str());
577 } else if (tag == "Hdg_Crs_value") {
578 _course = atof(_text.c_str());
579 } else if (tag == "DMEtoIntercept") {
580 _dmeDistance = atof(_text.c_str());
581 } else if (tag == "RadialtoIntercept") {
582 _radial = atof(_text.c_str());
588 Waypt* NavdataVisitor::buildWaypoint()
591 if (_wayptType == "Normal") {
592 // new LatLonWaypoint
593 SGGeod pos(SGGeod::fromDeg(_longitude, _latitude));
594 wp = new BasicWaypt(pos, _wayptName, NULL);
595 } else if (_wayptType == "Runway") {
596 string ident = _wayptName.substr(2);
597 FGRunwayRef rwy = _airport->getRunwayByIdent(ident);
598 wp = new RunwayWaypt(rwy, NULL);
599 } else if (_wayptType == "Hold") {
600 SGGeod pos(SGGeod::fromDeg(_longitude, _latitude));
601 Hold* h = new Hold(pos, _wayptName, NULL);
603 if (_holdRighthanded) {
610 h->setHoldDistance(_holdTD);
612 h->setHoldTime(_holdTD * 60.0);
615 if (_holdRadial >= 0.0) {
616 h->setHoldRadial(_holdRadial);
618 } else if (_wayptType == "Vectors") {
619 wp = new ATCVectors(NULL, _airport);
620 } else if ((_wayptType == "Intc") || (_wayptType == "VorRadialIntc")) {
621 SGGeod pos(SGGeod::fromDeg(_longitude, _latitude));
622 wp = new RadialIntercept(NULL, _wayptName, pos, _course, _radial);
623 } else if (_wayptType == "DmeIntc") {
624 SGGeod pos(SGGeod::fromDeg(_longitude, _latitude));
625 wp = new DMEIntercept(NULL, _wayptName, pos, _course, _dmeDistance);
626 } else if (_wayptType == "ConstHdgtoAlt") {
627 wp = new HeadingToAltitude(NULL, _wayptName, _course);
629 SG_LOG(SG_GENERAL, SG_ALERT, "implement waypoint type:" << _wayptType);
630 throw sg_format_exception("Unrecognized waypt type", _wayptType);
634 if ((_altitude > 0.0) && (_altRestrict != RESTRICT_NONE)) {
635 wp->setAltitude(_altitude,_altRestrict);
639 wp->setSpeed(_speed, RESTRICT_AT); // or _BELOW?
645 void NavdataVisitor::finishApproach()
647 WayptVec::iterator it;
650 // find the runway node
651 for (it = _waypoints.begin(); it != _waypoints.end(); ++it) {
652 FGPositionedRef navid = (*it)->source();
657 if (navid->type() == FGPositioned::RUNWAY) {
658 rwy = (FGRunway*) navid.get();
664 throw sg_format_exception("Malformed approach, no runway waypt", _ident);
667 WayptVec primary(_waypoints.begin(), it);
668 // erase all points up to and including the runway, to leave only the
670 _waypoints.erase(_waypoints.begin(), ++it);
672 _approach->setRunway(rwy);
673 _approach->setPrimaryAndMissed(primary, _waypoints);
674 _airport->addApproach(_approach);
678 void NavdataVisitor::finishSid()
680 // reverse order, because that's how we deal with commonality between
681 // STARs and SIDs. SID::route undoes this
682 std::reverse(_waypoints.begin(), _waypoints.end());
683 _sid->setCommon(_waypoints);
684 _airport->addSID(_sid);
688 void NavdataVisitor::finishStar()
690 _star->setCommon(_waypoints);
691 _airport->addSTAR(_star);
695 void NavdataVisitor::data (const char * s, int len)
697 _text += string(s, len);
701 void NavdataVisitor::pi (const char * target, const char * data) {
702 //cout << "Processing instruction " << target << ' ' << data << endl;
705 void NavdataVisitor::warning (const char * message, int line, int column) {
706 SG_LOG(SG_IO, SG_WARN, "Warning: " << message << " (" << line << ',' << column << ')');
709 void NavdataVisitor::error (const char * message, int line, int column) {
710 SG_LOG(SG_IO, SG_ALERT, "Error: " << message << " (" << line << ',' << column << ')');
713 } // of namespace flightgear