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)
72 std::string Waypt::ident() const
77 bool Waypt::flag(WayptFlag aFlag) const
79 return ((_flags & aFlag) != 0);
82 void Waypt::setFlag(WayptFlag aFlag, bool aV)
84 _flags = (_flags & ~aFlag);
85 if (aV) _flags |= aFlag;
88 bool Waypt::matches(Waypt* aOther) const
91 if (ident() != aOther->ident()) { // cheap check first
95 return matches(aOther->position());
99 bool Waypt::matches(const SGGeod& aPos) const
101 double d = SGGeodesy::distanceM(position(), aPos);
102 return (d < 100.0); // 100 metres seems plenty
105 void Waypt::setAltitude(double aAlt, RouteRestriction aRestrict)
108 _altRestrict = aRestrict;
111 void Waypt::setSpeed(double aSpeed, RouteRestriction aRestrict)
114 _speedRestrict = aRestrict;
117 double Waypt::speedKts() const
119 assert(_speedRestrict != SPEED_RESTRICT_MACH);
123 double Waypt::speedMach() const
125 assert(_speedRestrict == SPEED_RESTRICT_MACH);
129 std::pair<double, double>
130 Waypt::courseAndDistanceFrom(const SGGeod& aPos) const
132 if (flag(WPT_DYNAMIC)) {
133 return std::make_pair(0.0, 0.0);
136 double course, az2, distance;
137 SGGeodesy::inverse(aPos, position(), course, az2, distance);
138 return std::make_pair(course, distance);
141 double Waypt::magvarDeg() const
143 if (_magVarDeg == NO_MAG_VAR) {
144 // derived classes with a default pos must override this method
145 assert(!(position() == SGGeod()));
147 double jd = globals->get_time_params()->getJD();
148 _magVarDeg = sgGetMagVar(position(), jd);
154 ///////////////////////////////////////////////////////////////////////////
157 static RouteRestriction restrictionFromString(const char* aStr)
159 std::string l = boost::to_lower_copy(std::string(aStr));
161 if (l == "at") return RESTRICT_AT;
162 if (l == "above") return RESTRICT_ABOVE;
163 if (l == "below") return RESTRICT_BELOW;
164 if (l == "none") return RESTRICT_NONE;
165 if (l == "mach") return SPEED_RESTRICT_MACH;
167 if (l.empty()) return RESTRICT_NONE;
168 throw sg_io_exception("unknown restriction specification:" + l,
169 "Route restrictFromString");
172 static const char* restrictionToString(RouteRestriction aRestrict)
175 case RESTRICT_AT: return "at";
176 case RESTRICT_BELOW: return "below";
177 case RESTRICT_ABOVE: return "above";
178 case RESTRICT_NONE: return "none";
179 case SPEED_RESTRICT_MACH: return "mach";
182 throw sg_exception("invalid route restriction",
183 "Route restrictToString");
187 Waypt* Waypt::createInstance(Route* aOwner, const std::string& aTypeName)
190 if (aTypeName == "basic") {
191 r = new BasicWaypt(aOwner);
192 } else if (aTypeName == "navaid") {
193 r = new NavaidWaypoint(aOwner);
194 } else if (aTypeName == "offset-navaid") {
195 r = new OffsetNavaidWaypoint(aOwner);
196 } else if (aTypeName == "hold") {
197 r = new Hold(aOwner);
198 } else if (aTypeName == "runway") {
199 r = new RunwayWaypt(aOwner);
200 } else if (aTypeName == "hdgToAlt") {
201 r = new HeadingToAltitude(aOwner);
202 } else if (aTypeName == "dmeIntercept") {
203 r = new DMEIntercept(aOwner);
204 } else if (aTypeName == "radialIntercept") {
205 r = new RadialIntercept(aOwner);
206 } else if (aTypeName == "vectors") {
207 r = new ATCVectors(aOwner);
210 if (!r || (r->type() != aTypeName)) {
211 throw sg_exception("broken factory method for type:" + aTypeName,
212 "Waypt::createInstance");
218 WayptRef Waypt::createFromProperties(Route* aOwner, SGPropertyNode_ptr aProp)
220 if (!aProp->hasChild("type")) {
221 throw sg_io_exception("bad props node, no type provided",
222 "Waypt::createFromProperties");
225 WayptRef nd(createInstance(aOwner, aProp->getStringValue("type")));
226 nd->initFromProperties(aProp);
230 void Waypt::saveAsNode(SGPropertyNode* n) const
232 n->setStringValue("type", type());
233 writeToProperties(n);
236 void Waypt::initFromProperties(SGPropertyNode_ptr aProp)
238 if (aProp->hasChild("generated")) {
239 setFlag(WPT_GENERATED, aProp->getBoolValue("generated"));
242 if (aProp->hasChild("overflight")) {
243 setFlag(WPT_OVERFLIGHT, aProp->getBoolValue("overflight"));
246 if (aProp->hasChild("arrival")) {
247 setFlag(WPT_ARRIVAL, aProp->getBoolValue("arrival"));
250 if (aProp->hasChild("departure")) {
251 setFlag(WPT_DEPARTURE, aProp->getBoolValue("departure"));
254 if (aProp->hasChild("miss")) {
255 setFlag(WPT_MISS, aProp->getBoolValue("miss"));
258 if (aProp->hasChild("alt-restrict")) {
259 _altRestrict = restrictionFromString(aProp->getStringValue("alt-restrict"));
260 _altitudeFt = aProp->getDoubleValue("altitude-ft");
263 if (aProp->hasChild("speed-restrict")) {
264 _speedRestrict = restrictionFromString(aProp->getStringValue("speed-restrict"));
265 _speed = aProp->getDoubleValue("speed");
271 void Waypt::writeToProperties(SGPropertyNode_ptr aProp) const
273 if (flag(WPT_OVERFLIGHT)) {
274 aProp->setBoolValue("overflight", true);
277 if (flag(WPT_DEPARTURE)) {
278 aProp->setBoolValue("departure", true);
281 if (flag(WPT_ARRIVAL)) {
282 aProp->setBoolValue("arrival", true);
285 if (flag(WPT_MISS)) {
286 aProp->setBoolValue("miss", true);
289 if (flag(WPT_GENERATED)) {
290 aProp->setBoolValue("generated", true);
293 if (_altRestrict != RESTRICT_NONE) {
294 aProp->setStringValue("alt-restrict", restrictionToString(_altRestrict));
295 aProp->setDoubleValue("altitude-ft", _altitudeFt);
298 if (_speedRestrict != RESTRICT_NONE) {
299 aProp->setStringValue("speed-restrict", restrictionToString(_speedRestrict));
300 aProp->setDoubleValue("speed", _speed);
304 void Route::dumpRouteToFile(const WayptVec& aRoute, const std::string& aName)
306 SGPath p = "/Users/jmt/Desktop/" + aName + ".kml";
308 f.open(p.str().c_str(), fstream::out | fstream::app);
310 SG_LOG(SG_GENERAL, SG_WARN, "unable to open:" << p.str());
315 f << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
316 "<kml xmlns=\"http://www.opengis.net/kml/2.2\">\n"
319 dumpRouteToLineString(aName, aRoute, f);
327 void Route::dumpRouteToLineString(const std::string& aIdent,
328 const WayptVec& aRoute, std::ostream& aStream)
331 aStream << "<Placemark>\n";
332 aStream << "<name>" << aIdent << "</name>\n";
333 aStream << "<LineString>\n";
334 aStream << "<tessellate>1</tessellate>\n";
335 aStream << "<coordinates>\n";
338 for (unsigned int i=0; i<aRoute.size(); ++i) {
339 SGGeod pos = aRoute[i]->position();
340 aStream << pos.getLongitudeDeg() << "," << pos.getLatitudeDeg() << " " << endl;
344 aStream << "</coordinates>\n"
346 "</Placemark>\n" << endl;
349 ///////////////////////////////////////////////////////////////////////////
351 class NavdataVisitor : public XMLVisitor {
353 NavdataVisitor(FGAirport* aApt, const SGPath& aPath);
356 virtual void startXML ();
357 virtual void endXML ();
358 virtual void startElement (const char * name, const XMLAttributes &atts);
359 virtual void endElement (const char * name);
360 virtual void data (const char * s, int len);
361 virtual void pi (const char * target, const char * data);
362 virtual void warning (const char * message, int line, int column);
363 virtual void error (const char * message, int line, int column);
366 Waypt* buildWaypoint();
367 void processRunways(ArrivalDeparture* aProc, const XMLAttributes &atts);
369 void finishApproach();
375 string _text; ///< last element text value
381 WayptVec _waypoints; ///< waypoint list for current approach/sid/star
382 WayptVec _transWaypts; ///< waypoint list for current transition
386 string _ident; // id of segment under construction
388 double _longitude, _latitude, _altitude, _speed;
389 RouteRestriction _altRestrict;
391 double _holdRadial; // inbound hold radial, or -1 if radial is 'inbound'
392 double _holdTD; ///< hold time (seconds) or distance (nm), based on flag below
393 bool _holdRighthanded;
394 bool _holdDistance; // true, TD is distance in nm; false, TD is time in seconds
396 double _course, _radial, _dmeDistance;
399 void Route::loadAirportProcedures(const SGPath& aPath, FGAirport* aApt)
403 NavdataVisitor visitor(aApt, aPath);
404 readXML(aPath.str(), visitor);
405 } catch (sg_io_exception& ex) {
406 SG_LOG(SG_GENERAL, SG_WARN, "failured parsing procedures: " << aPath.str() <<
407 "\n\t" << ex.getMessage() << "\n\tat:" << ex.getLocation().asString());
408 } catch (sg_exception& ex) {
409 SG_LOG(SG_GENERAL, SG_WARN, "failured parsing procedures: " << aPath.str() <<
410 "\n\t" << ex.getMessage());
414 NavdataVisitor::NavdataVisitor(FGAirport* aApt, const SGPath& aPath):
423 void NavdataVisitor::startXML()
427 void NavdataVisitor::endXML()
431 void NavdataVisitor::startElement(const char* name, const XMLAttributes &atts)
435 if (tag == "Airport") {
436 string icao(atts.getValue("ICAOcode"));
437 if (_airport->ident() != icao) {
438 throw sg_format_exception("Airport and ICAO mismatch", icao, _path.str());
440 } else if (tag == "Sid") {
441 string ident(atts.getValue("Name"));
442 _sid = new SID(ident);
444 processRunways(_sid, atts);
445 } else if (tag == "Star") {
446 string ident(atts.getValue("Name"));
447 _star = new STAR(ident);
449 processRunways(_star, atts);
450 } else if ((tag == "Sid_Waypoint") ||
451 (tag == "App_Waypoint") ||
452 (tag == "Star_Waypoint") ||
453 (tag == "AppTr_Waypoint") ||
454 (tag == "SidTr_Waypoint") ||
455 (tag == "RwyTr_Waypoint"))
457 // reset waypoint data
459 _altRestrict = RESTRICT_NONE;
461 } else if (tag == "Approach") {
462 _ident = atts.getValue("Name");
464 _approach = new Approach(_ident);
465 } else if ((tag == "Sid_Transition") ||
466 (tag == "App_Transition") ||
467 (tag == "Star_Transition")) {
468 _transIdent = atts.getValue("Name");
469 _transWaypts.clear();
470 } else if (tag == "RunwayTransition") {
471 _transIdent = atts.getValue("Runway");
472 _transWaypts.clear();
478 void NavdataVisitor::processRunways(ArrivalDeparture* aProc, const XMLAttributes &atts)
481 if (atts.hasAttribute("Runways")) {
482 v = atts.getValue("Runways");
486 for (unsigned int r=0; r<_airport->numRunways(); ++r) {
487 aProc->addRunway(_airport->getRunwayByIndex(r));
493 boost::split(rwys, v, boost::is_any_of(" ,"));
494 for (unsigned int r=0; r<rwys.size(); ++r) {
495 FGRunway* rwy = _airport->getRunwayByIdent(rwys[r]);
496 aProc->addRunway(rwy);
500 void NavdataVisitor::endElement(const char* name)
503 if ((tag == "Sid_Waypoint") ||
504 (tag == "App_Waypoint") ||
505 (tag == "Star_Waypoint"))
507 _waypoints.push_back(buildWaypoint());
508 } else if ((tag == "AppTr_Waypoint") ||
509 (tag == "SidTr_Waypoint") ||
510 (tag == "RwyTr_Waypoint") ||
511 (tag == "StarTr_Waypoint"))
513 _transWaypts.push_back(buildWaypoint());
514 } else if (tag == "Sid_Transition") {
516 // SID waypoints are stored backwards, to share code with STARs
517 std::reverse(_transWaypts.begin(), _transWaypts.end());
518 Transition* t = new Transition(_transIdent, _sid, _transWaypts);
519 _sid->addTransition(t);
520 } else if (tag == "Star_Transition") {
522 Transition* t = new Transition(_transIdent, _star, _transWaypts);
523 _star->addTransition(t);
524 } else if (tag == "App_Transition") {
526 Transition* t = new Transition(_transIdent, _approach, _transWaypts);
527 _approach->addTransition(t);
528 } else if (tag == "RunwayTransition") {
529 ArrivalDeparture* ad;
531 // SID waypoints are stored backwards, to share code with STARs
532 std::reverse(_transWaypts.begin(), _transWaypts.end());
538 Transition* t = new Transition(_transIdent, ad, _transWaypts);
539 FGRunwayRef rwy = _airport->getRunwayByIdent(_transIdent);
540 ad->addRunwayTransition(rwy, t);
541 } else if (tag == "Approach") {
543 } else if (tag == "Sid") {
545 } else if (tag == "Star") {
547 } else if (tag == "Longitude") {
548 _longitude = atof(_text.c_str());
549 } else if (tag == "Latitude") {
550 _latitude = atof(_text.c_str());
551 } else if (tag == "Name") {
553 } else if (tag == "Type") {
555 } else if (tag == "Speed") {
556 _speed = atoi(_text.c_str());
557 } else if (tag == "Altitude") {
558 _altitude = atof(_text.c_str());
559 } else if (tag == "AltitudeRestriction") {
561 _altRestrict = RESTRICT_AT;
562 } else if (_text == "above") {
563 _altRestrict = RESTRICT_ABOVE;
564 } else if (_text == "below") {
565 _altRestrict = RESTRICT_BELOW;
567 throw sg_format_exception("Unrecognized altitude restriction", _text);
569 } else if (tag == "Hld_Rad_or_Inbd") {
570 if (_text == "Inbd") {
573 } else if (tag == "Hld_Time_or_Dist") {
574 _holdDistance = (_text == "Dist");
575 } else if (tag == "Hld_Rad_value") {
576 _holdRadial = atof(_text.c_str());
577 } else if (tag == "Hld_Turn") {
578 _holdRighthanded = (_text == "Right");
579 } else if (tag == "Hld_td_value") {
580 _holdTD = atof(_text.c_str());
581 } else if (tag == "Hdg_Crs_value") {
582 _course = atof(_text.c_str());
583 } else if (tag == "DMEtoIntercept") {
584 _dmeDistance = atof(_text.c_str());
585 } else if (tag == "RadialtoIntercept") {
586 _radial = atof(_text.c_str());
592 Waypt* NavdataVisitor::buildWaypoint()
595 if (_wayptType == "Normal") {
596 // new LatLonWaypoint
597 SGGeod pos(SGGeod::fromDeg(_longitude, _latitude));
598 wp = new BasicWaypt(pos, _wayptName, NULL);
599 } else if (_wayptType == "Runway") {
600 string ident = _wayptName.substr(2);
601 FGRunwayRef rwy = _airport->getRunwayByIdent(ident);
602 wp = new RunwayWaypt(rwy, NULL);
603 } else if (_wayptType == "Hold") {
604 SGGeod pos(SGGeod::fromDeg(_longitude, _latitude));
605 Hold* h = new Hold(pos, _wayptName, NULL);
607 if (_holdRighthanded) {
614 h->setHoldDistance(_holdTD);
616 h->setHoldTime(_holdTD * 60.0);
619 if (_holdRadial >= 0.0) {
620 h->setHoldRadial(_holdRadial);
622 } else if (_wayptType == "Vectors") {
623 wp = new ATCVectors(NULL, _airport);
624 } else if ((_wayptType == "Intc") || (_wayptType == "VorRadialIntc")) {
625 SGGeod pos(SGGeod::fromDeg(_longitude, _latitude));
626 wp = new RadialIntercept(NULL, _wayptName, pos, _course, _radial);
627 } else if (_wayptType == "DmeIntc") {
628 SGGeod pos(SGGeod::fromDeg(_longitude, _latitude));
629 wp = new DMEIntercept(NULL, _wayptName, pos, _course, _dmeDistance);
630 } else if (_wayptType == "ConstHdgtoAlt") {
631 wp = new HeadingToAltitude(NULL, _wayptName, _course);
633 SG_LOG(SG_GENERAL, SG_ALERT, "implement waypoint type:" << _wayptType);
634 throw sg_format_exception("Unrecognized waypt type", _wayptType);
638 if ((_altitude > 0.0) && (_altRestrict != RESTRICT_NONE)) {
639 wp->setAltitude(_altitude,_altRestrict);
643 wp->setSpeed(_speed, RESTRICT_AT); // or _BELOW?
649 void NavdataVisitor::finishApproach()
651 WayptVec::iterator it;
654 // find the runway node
655 for (it = _waypoints.begin(); it != _waypoints.end(); ++it) {
656 FGPositionedRef navid = (*it)->source();
661 if (navid->type() == FGPositioned::RUNWAY) {
662 rwy = (FGRunway*) navid.get();
668 throw sg_format_exception("Malformed approach, no runway waypt", _ident);
671 WayptVec primary(_waypoints.begin(), it);
672 // erase all points up to and including the runway, to leave only the
674 _waypoints.erase(_waypoints.begin(), ++it);
676 _approach->setRunway(rwy);
677 _approach->setPrimaryAndMissed(primary, _waypoints);
678 _airport->addApproach(_approach);
682 void NavdataVisitor::finishSid()
684 // reverse order, because that's how we deal with commonality between
685 // STARs and SIDs. SID::route undoes this
686 std::reverse(_waypoints.begin(), _waypoints.end());
687 _sid->setCommon(_waypoints);
688 _airport->addSID(_sid);
692 void NavdataVisitor::finishStar()
694 _star->setCommon(_waypoints);
695 _airport->addSTAR(_star);
699 void NavdataVisitor::data (const char * s, int len)
701 _text += string(s, len);
705 void NavdataVisitor::pi (const char * target, const char * data) {
706 //cout << "Processing instruction " << target << ' ' << data << endl;
709 void NavdataVisitor::warning (const char * message, int line, int column) {
710 SG_LOG(SG_IO, SG_WARN, "Warning: " << message << " (" << line << ',' << column << ')');
713 void NavdataVisitor::error (const char * message, int line, int column) {
714 SG_LOG(SG_IO, SG_ALERT, "Error: " << message << " (" << line << ',' << column << ')');
717 } // of namespace flightgear