1 // NasalPositioned.cxx -- expose FGPositioned classes to Nasal
3 // Written by James Turner, started 2012.
5 // Copyright (C) 2012 James Turner
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.
27 #include "NasalPositioned.hxx"
29 #include <boost/foreach.hpp>
30 #include <boost/algorithm/string/case_conv.hpp>
31 #include <boost/tuple/tuple.hpp> // for boost::tie
33 #include <simgear/sg_inlines.h>
34 #include <simgear/scene/material/mat.hxx>
35 #include <simgear/magvar/magvar.hxx>
36 #include <simgear/timing/sg_time.hxx>
37 #include <simgear/bucket/newbucket.hxx>
39 #include <Airports/runways.hxx>
40 #include <Airports/airport.hxx>
41 #include <Airports/dynamics.hxx>
42 #include <Airports/parking.hxx>
43 #include <Scripting/NasalSys.hxx>
44 #include <Navaids/navlist.hxx>
45 #include <Navaids/procedure.hxx>
46 #include <Main/globals.hxx>
47 #include <Main/fg_props.hxx>
48 #include <Scenery/scenery.hxx>
49 #include <ATC/CommStation.hxx>
50 #include <Navaids/FlightPlan.hxx>
51 #include <Navaids/waypoint.hxx>
52 #include <Navaids/fix.hxx>
53 #include <Autopilot/route_mgr.hxx>
54 #include <Navaids/routePath.hxx>
55 #include <Navaids/procedure.hxx>
56 #include <Navaids/airways.hxx>
57 #include <Navaids/NavDataCache.hxx>
59 using namespace flightgear;
61 static void positionedGhostDestroy(void* g);
62 static void wayptGhostDestroy(void* g);
63 static void legGhostDestroy(void* g);
64 static void routeBaseGhostDestroy(void* g);
66 naGhostType PositionedGhostType = { positionedGhostDestroy, "positioned" };
68 static const char* airportGhostGetMember(naContext c, void* g, naRef field, naRef* out);
69 naGhostType AirportGhostType = { positionedGhostDestroy, "airport", airportGhostGetMember, 0 };
71 static const char* navaidGhostGetMember(naContext c, void* g, naRef field, naRef* out);
72 naGhostType NavaidGhostType = { positionedGhostDestroy, "navaid", navaidGhostGetMember, 0 };
74 static const char* runwayGhostGetMember(naContext c, void* g, naRef field, naRef* out);
75 naGhostType RunwayGhostType = { positionedGhostDestroy, "runway", runwayGhostGetMember, 0 };
76 naGhostType HelipadGhostType = { positionedGhostDestroy, "helipad", runwayGhostGetMember, 0 };
77 naGhostType TaxiwayGhostType = { positionedGhostDestroy, "taxiway", runwayGhostGetMember, 0 };
79 static const char* fixGhostGetMember(naContext c, void* g, naRef field, naRef* out);
80 naGhostType FixGhostType = { positionedGhostDestroy, "fix", fixGhostGetMember, 0 };
82 static const char* wayptGhostGetMember(naContext c, void* g, naRef field, naRef* out);
83 static void waypointGhostSetMember(naContext c, void* g, naRef field, naRef value);
85 naGhostType WayptGhostType = { wayptGhostDestroy,
88 waypointGhostSetMember};
90 static const char* legGhostGetMember(naContext c, void* g, naRef field, naRef* out);
91 static void legGhostSetMember(naContext c, void* g, naRef field, naRef value);
93 naGhostType FPLegGhostType = { legGhostDestroy,
98 static const char* flightplanGhostGetMember(naContext c, void* g, naRef field, naRef* out);
99 static void flightplanGhostSetMember(naContext c, void* g, naRef field, naRef value);
101 naGhostType FlightPlanGhostType = { routeBaseGhostDestroy,
103 flightplanGhostGetMember,
104 flightplanGhostSetMember
107 static const char* procedureGhostGetMember(naContext c, void* g, naRef field, naRef* out);
108 naGhostType ProcedureGhostType = { routeBaseGhostDestroy,
110 procedureGhostGetMember,
113 static void hashset(naContext c, naRef hash, const char* key, naRef val)
115 naRef s = naNewString(c);
116 naStr_fromdata(s, (char*)key, strlen(key));
117 naHash_set(hash, s, val);
120 static naRef stringToNasal(naContext c, const std::string& s)
122 return naStr_fromdata(naNewString(c),
123 const_cast<char *>(s.c_str()),
127 static bool convertToNum(naRef v, double& result)
129 naRef n = naNumValue(v);
131 return false; // couldn't convert
138 static WayptFlag wayptFlagFromString(const char* s)
140 if (!strcmp(s, "sid")) return WPT_DEPARTURE;
141 if (!strcmp(s, "star")) return WPT_ARRIVAL;
142 if (!strcmp(s, "approach")) return WPT_APPROACH;
143 if (!strcmp(s, "missed")) return WPT_MISS;
144 if (!strcmp(s, "pseudo")) return WPT_PSEUDO;
146 return (WayptFlag) 0;
149 static naRef wayptFlagToNasal(naContext c, unsigned int flags)
151 if (flags & WPT_PSEUDO) return stringToNasal(c, "pseudo");
152 if (flags & WPT_DEPARTURE) return stringToNasal(c, "sid");
153 if (flags & WPT_ARRIVAL) return stringToNasal(c, "star");
154 if (flags & WPT_MISS) return stringToNasal(c, "missed");
155 if (flags & WPT_APPROACH) return stringToNasal(c, "approach");
159 static FGPositioned* positionedGhost(naRef r)
161 if ((naGhost_type(r) == &AirportGhostType) ||
162 (naGhost_type(r) == &NavaidGhostType) ||
163 (naGhost_type(r) == &RunwayGhostType) ||
164 (naGhost_type(r) == &FixGhostType))
166 return (FGPositioned*) naGhost_ptr(r);
172 static FGAirport* airportGhost(naRef r)
174 if (naGhost_type(r) == &AirportGhostType)
175 return (FGAirport*) naGhost_ptr(r);
179 static FGNavRecord* navaidGhost(naRef r)
181 if (naGhost_type(r) == &NavaidGhostType)
182 return (FGNavRecord*) naGhost_ptr(r);
186 static FGRunway* runwayGhost(naRef r)
188 if (naGhost_type(r) == &RunwayGhostType)
189 return (FGRunway*) naGhost_ptr(r);
193 static FGTaxiway* taxiwayGhost(naRef r)
195 if (naGhost_type(r) == &TaxiwayGhostType)
196 return (FGTaxiway*) naGhost_ptr(r);
200 static FGFix* fixGhost(naRef r)
202 if (naGhost_type(r) == &FixGhostType)
203 return (FGFix*) naGhost_ptr(r);
208 static void positionedGhostDestroy(void* g)
210 FGPositioned* pos = (FGPositioned*)g;
211 if (!FGPositioned::put(pos)) // unref
215 static Waypt* wayptGhost(naRef r)
217 if (naGhost_type(r) == &WayptGhostType)
218 return (Waypt*) naGhost_ptr(r);
220 if (naGhost_type(r) == &FPLegGhostType) {
221 FlightPlan::Leg* leg = (FlightPlan::Leg*) naGhost_ptr(r);
222 return leg->waypoint();
228 static void wayptGhostDestroy(void* g)
230 Waypt* wpt = (Waypt*)g;
231 if (!Waypt::put(wpt)) // unref
235 static void legGhostDestroy(void* g)
241 static FlightPlan::Leg* fpLegGhost(naRef r)
243 if (naGhost_type(r) == &FPLegGhostType)
244 return (FlightPlan::Leg*) naGhost_ptr(r);
248 static Procedure* procedureGhost(naRef r)
250 if (naGhost_type(r) == &ProcedureGhostType)
251 return (Procedure*) naGhost_ptr(r);
255 static FlightPlan* flightplanGhost(naRef r)
257 if (naGhost_type(r) == &FlightPlanGhostType)
258 return (FlightPlan*) naGhost_ptr(r);
262 static void routeBaseGhostDestroy(void* g)
267 static naRef airportPrototype;
268 static naRef flightplanPrototype;
269 static naRef waypointPrototype;
270 static naRef geoCoordClass;
271 static naRef fpLegPrototype;
272 static naRef procedurePrototype;
274 naRef ghostForAirport(naContext c, const FGAirport* apt)
280 FGPositioned::get(apt); // take a ref
281 return naNewGhost2(c, &AirportGhostType, (void*) apt);
284 naRef ghostForNavaid(naContext c, const FGNavRecord* n)
290 FGPositioned::get(n); // take a ref
291 return naNewGhost2(c, &NavaidGhostType, (void*) n);
294 naRef ghostForRunway(naContext c, const FGRunway* r)
300 FGPositioned::get(r); // take a ref
301 return naNewGhost2(c, &RunwayGhostType, (void*) r);
304 naRef ghostForHelipad(naContext c, const FGHelipad* r)
310 FGPositioned::get(r); // take a ref
311 return naNewGhost2(c, &HelipadGhostType, (void*) r);
314 naRef ghostForTaxiway(naContext c, const FGTaxiway* r)
320 FGPositioned::get(r); // take a ref
321 return naNewGhost2(c, &TaxiwayGhostType, (void*) r);
324 naRef ghostForFix(naContext c, const FGFix* r)
330 FGPositioned::get(r); // take a ref
331 return naNewGhost2(c, &FixGhostType, (void*) r);
335 naRef ghostForWaypt(naContext c, const Waypt* wpt)
341 Waypt::get(wpt); // take a ref
342 return naNewGhost2(c, &WayptGhostType, (void*) wpt);
345 naRef ghostForLeg(naContext c, const FlightPlan::Leg* leg)
351 return naNewGhost2(c, &FPLegGhostType, (void*) leg);
354 naRef ghostForFlightPlan(naContext c, const FlightPlan* fp)
360 return naNewGhost2(c, &FlightPlanGhostType, (void*) fp);
363 naRef ghostForProcedure(naContext c, const Procedure* proc)
369 return naNewGhost2(c, &ProcedureGhostType, (void*) proc);
372 static const char* airportGhostGetMember(naContext c, void* g, naRef field, naRef* out)
374 const char* fieldName = naStr_data(field);
375 FGAirport* apt = (FGAirport*) g;
377 if (!strcmp(fieldName, "parents")) {
378 *out = naNewVector(c);
379 naVec_append(*out, airportPrototype);
380 } else if (!strcmp(fieldName, "id")) *out = stringToNasal(c, apt->ident());
381 else if (!strcmp(fieldName, "name")) *out = stringToNasal(c, apt->name());
382 else if (!strcmp(fieldName, "lat")) *out = naNum(apt->getLatitude());
383 else if (!strcmp(fieldName, "lon")) *out = naNum(apt->getLongitude());
384 else if (!strcmp(fieldName, "elevation")) {
385 *out = naNum(apt->getElevation() * SG_FEET_TO_METER);
386 } else if (!strcmp(fieldName, "has_metar")) {
387 *out = naNum(apt->getMetar());
388 } else if (!strcmp(fieldName, "runways")) {
390 double minLengthFt = fgGetDouble("/sim/navdb/min-runway-length-ft");
391 for(unsigned int r=0; r<apt->numRunways(); ++r) {
392 FGRunway* rwy(apt->getRunwayByIndex(r));
393 // ignore unusably short runways
394 if (rwy->lengthFt() < minLengthFt) {
397 naRef rwyid = stringToNasal(c, rwy->ident());
398 naRef rwydata = ghostForRunway(c, rwy);
399 naHash_set(*out, rwyid, rwydata);
401 } else if (!strcmp(fieldName, "helipads")) {
404 for(unsigned int r=0; r<apt->numHelipads(); ++r) {
405 FGHelipad* hp(apt->getHelipadByIndex(r));
407 naRef rwyid = stringToNasal(c, hp->ident());
408 naRef rwydata = ghostForHelipad(c, hp);
409 naHash_set(*out, rwyid, rwydata);
412 } else if (!strcmp(fieldName, "taxiways")) {
413 *out = naNewVector(c);
414 for(unsigned int r=0; r<apt->numTaxiways(); ++r) {
415 FGTaxiway* taxi(apt->getTaxiwayByIndex(r));
416 naRef taxidata = ghostForTaxiway(c, taxi);
417 naVec_append(*out, taxidata);
427 static const char* waypointCommonGetMember(naContext c, Waypt* wpt, const char* fieldName, naRef* out)
429 if (!strcmp(fieldName, "wp_name") || !strcmp(fieldName, "id")) *out = stringToNasal(c, wpt->ident());
430 else if (!strcmp(fieldName, "wp_type")) *out = stringToNasal(c, wpt->type());
431 else if (!strcmp(fieldName, "wp_role")) *out = wayptFlagToNasal(c, wpt->flags());
432 else if (!strcmp(fieldName, "wp_lat") || !strcmp(fieldName, "lat")) *out = naNum(wpt->position().getLatitudeDeg());
433 else if (!strcmp(fieldName, "wp_lon") || !strcmp(fieldName, "lon")) *out = naNum(wpt->position().getLongitudeDeg());
434 else if (!strcmp(fieldName, "wp_parent_name")) {
435 Procedure* proc = dynamic_cast<Procedure*>(wpt->owner());
436 *out = proc ? stringToNasal(c, proc->ident()) : naNil();
437 } else if (!strcmp(fieldName, "wp_parent")) {
438 Procedure* proc = dynamic_cast<Procedure*>(wpt->owner());
439 *out = ghostForProcedure(c, proc);
440 } else if (!strcmp(fieldName, "fly_type")) {
441 if (wpt->type() == "hold") {
442 *out = stringToNasal(c, "Hold");
444 *out = stringToNasal(c, wpt->flag(WPT_OVERFLIGHT) ? "flyOver" : "flyBy");
447 return NULL; // member not found
453 static void waypointCommonSetMember(naContext c, Waypt* wpt, const char* fieldName, naRef value)
455 if (!strcmp(fieldName, "wp_role")) {
456 if (!naIsString(value)) naRuntimeError(c, "wp_role must be a string");
457 if (wpt->owner() != NULL) naRuntimeError(c, "cannot override wp_role on waypoint with parent");
458 WayptFlag f = wayptFlagFromString(naStr_data(value));
460 naRuntimeError(c, "unrecognized wp_role value %s", naStr_data(value));
463 wpt->setFlag(f, true);
467 static const char* wayptGhostGetMember(naContext c, void* g, naRef field, naRef* out)
469 const char* fieldName = naStr_data(field);
470 Waypt* wpt = (flightgear::Waypt*) g;
471 return waypointCommonGetMember(c, wpt, fieldName, out);
474 static RouteRestriction routeRestrictionFromString(const char* s)
478 if (u == "computed") return RESTRICT_COMPUTED;
479 if (u == "at") return RESTRICT_AT;
480 if (u == "mach") return SPEED_RESTRICT_MACH;
481 if (u == "computed-mach") return SPEED_COMPUTED_MACH;
482 if (u == "delete") return RESTRICT_DELETE;
483 return RESTRICT_NONE;
486 naRef routeRestrictionToNasal(naContext c, RouteRestriction rr)
489 case RESTRICT_NONE: return naNil();
490 case RESTRICT_AT: return stringToNasal(c, "at");
491 case RESTRICT_ABOVE: return stringToNasal(c, "above");
492 case RESTRICT_BELOW: return stringToNasal(c, "below");
493 case SPEED_RESTRICT_MACH: return stringToNasal(c, "mach");
494 case RESTRICT_COMPUTED: return stringToNasal(c, "computed");
495 case SPEED_COMPUTED_MACH: return stringToNasal(c, "computed-mach");
496 case RESTRICT_DELETE: return stringToNasal(c, "delete");
502 static const char* legGhostGetMember(naContext c, void* g, naRef field, naRef* out)
504 const char* fieldName = naStr_data(field);
505 FlightPlan::Leg* leg = (FlightPlan::Leg*) g;
506 Waypt* wpt = leg->waypoint();
508 if (!strcmp(fieldName, "parents")) {
509 *out = naNewVector(c);
510 naVec_append(*out, fpLegPrototype);
511 naVec_append(*out, waypointPrototype);
512 } else if (!strcmp(fieldName, "index")) {
513 *out = naNum(leg->index());
514 } else if (!strcmp(fieldName, "alt_cstr")) {
515 *out = naNum(leg->altitudeFt());
516 } else if (!strcmp(fieldName, "alt_cstr_type")) {
517 *out = routeRestrictionToNasal(c, leg->altitudeRestriction());
518 } else if (!strcmp(fieldName, "speed_cstr")) {
519 double s = isMachRestrict(leg->speedRestriction()) ? leg->speedMach() : leg->speedKts();
521 } else if (!strcmp(fieldName, "speed_cstr_type")) {
522 *out = routeRestrictionToNasal(c, leg->speedRestriction());
523 } else if (!strcmp(fieldName, "leg_distance")) {
524 *out = naNum(leg->distanceNm());
525 } else if (!strcmp(fieldName, "leg_bearing")) {
526 *out = naNum(leg->courseDeg());
527 } else if (!strcmp(fieldName, "distance_along_route")) {
528 *out = naNum(leg->distanceAlongRoute());
529 } else { // check for fields defined on the underlying waypoint
530 return waypointCommonGetMember(c, wpt, fieldName, out);
533 return ""; // success
536 static void waypointGhostSetMember(naContext c, void* g, naRef field, naRef value)
538 const char* fieldName = naStr_data(field);
539 Waypt* wpt = (Waypt*) g;
540 waypointCommonSetMember(c, wpt, fieldName, value);
543 static void legGhostSetMember(naContext c, void* g, naRef field, naRef value)
545 const char* fieldName = naStr_data(field);
546 FlightPlan::Leg* leg = (FlightPlan::Leg*) g;
548 waypointCommonSetMember(c, leg->waypoint(), fieldName, value);
551 static const char* flightplanGhostGetMember(naContext c, void* g, naRef field, naRef* out)
553 const char* fieldName = naStr_data(field);
554 FlightPlan* fp = (FlightPlan*) g;
556 if (!strcmp(fieldName, "parents")) {
557 *out = naNewVector(c);
558 naVec_append(*out, flightplanPrototype);
559 } else if (!strcmp(fieldName, "id")) *out = stringToNasal(c, fp->ident());
560 else if (!strcmp(fieldName, "departure")) *out = ghostForAirport(c, fp->departureAirport());
561 else if (!strcmp(fieldName, "destination")) *out = ghostForAirport(c, fp->destinationAirport());
562 else if (!strcmp(fieldName, "departure_runway")) *out = ghostForRunway(c, fp->departureRunway());
563 else if (!strcmp(fieldName, "destination_runway")) *out = ghostForRunway(c, fp->destinationRunway());
564 else if (!strcmp(fieldName, "sid")) *out = ghostForProcedure(c, fp->sid());
565 else if (!strcmp(fieldName, "sid_trans")) *out = ghostForProcedure(c, fp->sidTransition());
566 else if (!strcmp(fieldName, "star")) *out = ghostForProcedure(c, fp->star());
567 else if (!strcmp(fieldName, "star_trans")) *out = ghostForProcedure(c, fp->starTransition());
568 else if (!strcmp(fieldName, "approach")) *out = ghostForProcedure(c, fp->approach());
569 else if (!strcmp(fieldName, "current")) *out = naNum(fp->currentIndex());
577 static void flightplanGhostSetMember(naContext c, void* g, naRef field, naRef value)
579 const char* fieldName = naStr_data(field);
580 FlightPlan* fp = (FlightPlan*) g;
582 if (!strcmp(fieldName, "id")) {
583 if (!naIsString(value)) naRuntimeError(c, "flightplan.id must be a string");
584 fp->setIdent(naStr_data(value));
585 } else if (!strcmp(fieldName, "current")) {
586 int index = value.num;
587 if ((index < 0) || (index >= fp->numLegs())) {
590 fp->setCurrentIndex(index);
591 } else if (!strcmp(fieldName, "departure")) {
592 FGAirport* apt = airportGhost(value);
594 fp->setDeparture(apt);
598 FGRunway* rwy = runwayGhost(value);
600 fp->setDeparture(rwy);
604 if (naIsNil(value)) {
605 fp->setDeparture(static_cast<FGAirport*>(NULL));
609 naRuntimeError(c, "bad argument type setting departure");
610 } else if (!strcmp(fieldName, "destination")) {
611 FGAirport* apt = airportGhost(value);
613 fp->setDestination(apt);
617 FGRunway* rwy = runwayGhost(value);
619 fp->setDestination(rwy);
623 naRuntimeError(c, "bad argument type setting destination");
624 } else if (!strcmp(fieldName, "departure_runway")) {
625 FGRunway* rwy = runwayGhost(value);
627 fp->setDeparture(rwy);
631 naRuntimeError(c, "bad argument type setting departure runway");
632 } else if (!strcmp(fieldName, "destination_runway")) {
633 FGRunway* rwy = runwayGhost(value);
635 fp->setDestination(rwy);
639 naRuntimeError(c, "bad argument type setting destination runway");
640 } else if (!strcmp(fieldName, "sid")) {
641 Procedure* proc = procedureGhost(value);
642 if (proc && (proc->type() == PROCEDURE_SID)) {
643 fp->setSID((flightgear::SID*) proc);
646 // allow a SID transition to be set, implicitly include the SID itself
647 if (proc && (proc->type() == PROCEDURE_TRANSITION)) {
648 fp->setSID((Transition*) proc);
652 if (naIsString(value)) {
653 FGAirport* apt = fp->departureAirport();
654 fp->setSID(apt->findSIDWithIdent(naStr_data(value)));
658 naRuntimeError(c, "bad argument type setting SID");
659 } else if (!strcmp(fieldName, "star")) {
660 Procedure* proc = procedureGhost(value);
661 if (proc && (proc->type() == PROCEDURE_STAR)) {
662 fp->setSTAR((STAR*) proc);
666 if (proc && (proc->type() == PROCEDURE_TRANSITION)) {
667 fp->setSTAR((Transition*) proc);
671 if (naIsString(value)) {
672 FGAirport* apt = fp->destinationAirport();
673 fp->setSTAR(apt->findSTARWithIdent(naStr_data(value)));
677 naRuntimeError(c, "bad argument type setting STAR");
678 } else if (!strcmp(fieldName, "approach")) {
679 Procedure* proc = procedureGhost(value);
680 if (proc && Approach::isApproach(proc->type())) {
681 fp->setApproach((Approach*) proc);
685 if (naIsString(value)) {
686 FGAirport* apt = fp->destinationAirport();
687 fp->setApproach(apt->findApproachWithIdent(naStr_data(value)));
691 naRuntimeError(c, "bad argument type setting approach");
696 static naRef procedureTpType(naContext c, ProcedureType ty)
699 case PROCEDURE_SID: return stringToNasal(c, "sid");
700 case PROCEDURE_STAR: return stringToNasal(c, "star");
701 case PROCEDURE_APPROACH_VOR:
702 case PROCEDURE_APPROACH_ILS:
703 case PROCEDURE_APPROACH_RNAV:
704 case PROCEDURE_APPROACH_NDB:
705 return stringToNasal(c, "IAP");
711 static naRef procedureRadioType(naContext c, ProcedureType ty)
714 case PROCEDURE_APPROACH_VOR: return stringToNasal(c, "VOR");
715 case PROCEDURE_APPROACH_ILS: return stringToNasal(c, "ILS");
716 case PROCEDURE_APPROACH_RNAV: return stringToNasal(c, "RNAV");
717 case PROCEDURE_APPROACH_NDB: return stringToNasal(c, "NDB");
723 static const char* procedureGhostGetMember(naContext c, void* g, naRef field, naRef* out)
725 const char* fieldName = naStr_data(field);
726 Procedure* proc = (Procedure*) g;
728 if (!strcmp(fieldName, "parents")) {
729 *out = naNewVector(c);
730 naVec_append(*out, procedurePrototype);
731 } else if (!strcmp(fieldName, "id")) *out = stringToNasal(c, proc->ident());
732 else if (!strcmp(fieldName, "airport")) *out = ghostForAirport(c, proc->airport());
733 else if (!strcmp(fieldName, "tp_type")) *out = procedureTpType(c, proc->type());
734 else if (!strcmp(fieldName, "radio")) *out = procedureRadioType(c, proc->type());
735 else if (!strcmp(fieldName, "runways")) {
736 *out = naNewVector(c);
737 BOOST_FOREACH(FGRunwayRef rwy, proc->runways()) {
738 naVec_append(*out, stringToNasal(c, rwy->ident()));
740 } else if (!strcmp(fieldName, "transitions")) {
741 if ((proc->type() != PROCEDURE_SID) && (proc->type() != PROCEDURE_STAR)) {
746 ArrivalDeparture* ad = static_cast<ArrivalDeparture*>(proc);
747 *out = naNewVector(c);
748 BOOST_FOREACH(std::string id, ad->transitionIdents()) {
749 naVec_append(*out, stringToNasal(c, id));
758 static const char* runwayGhostGetMember(naContext c, void* g, naRef field, naRef* out)
760 const char* fieldName = naStr_data(field);
761 FGRunwayBase* base = (FGRunwayBase*) g;
763 if (!strcmp(fieldName, "id")) *out = stringToNasal(c, base->ident());
764 else if (!strcmp(fieldName, "lat")) *out = naNum(base->latitude());
765 else if (!strcmp(fieldName, "lon")) *out = naNum(base->longitude());
766 else if (!strcmp(fieldName, "heading")) *out = naNum(base->headingDeg());
767 else if (!strcmp(fieldName, "length")) *out = naNum(base->lengthM());
768 else if (!strcmp(fieldName, "width")) *out = naNum(base->widthM());
769 else if (!strcmp(fieldName, "surface")) *out = naNum(base->surface());
770 else if (base->type() == FGRunwayBase::RUNWAY) {
771 FGRunway* rwy = (FGRunway*) g;
772 if (!strcmp(fieldName, "threshold")) *out = naNum(rwy->displacedThresholdM());
773 else if (!strcmp(fieldName, "stopway")) *out = naNum(rwy->stopwayM());
774 else if (!strcmp(fieldName, "reciprocal")) {
775 *out = ghostForRunway(c, rwy->reciprocalRunway());
776 } else if (!strcmp(fieldName, "ils_frequency_mhz")) {
777 *out = rwy->ILS() ? naNum(rwy->ILS()->get_freq() / 100.0) : naNil();
778 } else if (!strcmp(fieldName, "ils")) {
779 *out = ghostForNavaid(c, rwy->ILS());
790 static const char* navaidGhostGetMember(naContext c, void* g, naRef field, naRef* out)
792 const char* fieldName = naStr_data(field);
793 FGNavRecord* nav = (FGNavRecord*) g;
795 if (!strcmp(fieldName, "id")) *out = stringToNasal(c, nav->ident());
796 else if (!strcmp(fieldName, "name")) *out = stringToNasal(c, nav->name());
797 else if (!strcmp(fieldName, "lat")) *out = naNum(nav->get_lat());
798 else if (!strcmp(fieldName, "lon")) *out = naNum(nav->get_lon());
799 else if (!strcmp(fieldName, "elevation")) {
800 *out = naNum(nav->get_elev_ft() * SG_FEET_TO_METER);
801 } else if (!strcmp(fieldName, "type")) {
802 *out = stringToNasal(c, nav->nameForType(nav->type()));
803 } else if (!strcmp(fieldName, "frequency")) {
804 *out = naNum(nav->get_freq());
805 } else if (!strcmp(fieldName, "range_nm")) {
806 *out = naNum(nav->get_range());
807 } else if (!strcmp(fieldName, "course")) {
808 if ((nav->type() == FGPositioned::ILS) || (nav->type() == FGPositioned::LOC)) {
809 double radial = nav->get_multiuse();
810 SG_NORMALIZE_RANGE(radial, 0.0, 360.0);
811 *out = naNum(radial);
822 static const char* fixGhostGetMember(naContext c, void* g, naRef field, naRef* out)
824 const char* fieldName = naStr_data(field);
825 FGFix* fix = (FGFix*) g;
827 if (!strcmp(fieldName, "id")) *out = stringToNasal(c, fix->ident());
828 else if (!strcmp(fieldName, "lat")) *out = naNum(fix->get_lat());
829 else if (!strcmp(fieldName, "lon")) *out = naNum(fix->get_lon());
837 static bool hashIsCoord(naRef h)
839 naRef parents = naHash_cget(h, (char*) "parents");
840 if (!naIsVector(parents)) {
844 return naEqual(naVec_get(parents, 0), geoCoordClass) != 0;
847 bool geodFromHash(naRef ref, SGGeod& result)
849 if (!naIsHash(ref)) {
854 // check for manual latitude / longitude names
855 naRef lat = naHash_cget(ref, (char*) "lat");
856 naRef lon = naHash_cget(ref, (char*) "lon");
857 if (naIsNum(lat) && naIsNum(lon)) {
858 result = SGGeod::fromDeg(naNumValue(lon).num, naNumValue(lat).num);
862 if (hashIsCoord(ref)) {
863 naRef lat = naHash_cget(ref, (char*) "_lat");
864 naRef lon = naHash_cget(ref, (char*) "_lon");
865 if (naIsNum(lat) && naIsNum(lon)) {
866 result = SGGeod::fromRad(naNumValue(lon).num, naNumValue(lat).num);
871 // check for any synonyms?
872 // latitude + longitude?
877 static int geodFromArgs(naRef* args, int offset, int argc, SGGeod& result)
879 if (offset >= argc) {
883 if (naIsGhost(args[offset])) {
884 naGhostType* gt = naGhost_type(args[offset]);
885 if (gt == &AirportGhostType) {
886 result = airportGhost(args[offset])->geod();
890 if (gt == &NavaidGhostType) {
891 result = navaidGhost(args[offset])->geod();
895 if (gt == &RunwayGhostType) {
896 result = runwayGhost(args[offset])->geod();
900 if (gt == &TaxiwayGhostType) {
901 result = taxiwayGhost(args[offset])->geod();
905 if (gt == &FixGhostType) {
906 result = fixGhost(args[offset])->geod();
910 if (gt == &WayptGhostType) {
911 result = wayptGhost(args[offset])->position();
916 if (geodFromHash(args[offset], result)) {
920 if (((argc - offset) >= 2) && naIsNum(args[offset]) && naIsNum(args[offset + 1])) {
921 double lat = naNumValue(args[0]).num,
922 lon = naNumValue(args[1]).num;
923 result = SGGeod::fromDeg(lon, lat);
930 // Convert a cartesian point to a geodetic lat/lon/altitude.
931 static naRef f_carttogeod(naContext c, naRef me, int argc, naRef* args)
933 double lat, lon, alt, xyz[3];
934 if(argc != 3) naRuntimeError(c, "carttogeod() expects 3 arguments");
935 for(int i=0; i<3; i++)
936 xyz[i] = naNumValue(args[i]).num;
937 sgCartToGeod(xyz, &lat, &lon, &alt);
938 lat *= SG_RADIANS_TO_DEGREES;
939 lon *= SG_RADIANS_TO_DEGREES;
940 naRef vec = naNewVector(c);
941 naVec_append(vec, naNum(lat));
942 naVec_append(vec, naNum(lon));
943 naVec_append(vec, naNum(alt));
947 // Convert a geodetic lat/lon/altitude to a cartesian point.
948 static naRef f_geodtocart(naContext c, naRef me, int argc, naRef* args)
950 if(argc != 3) naRuntimeError(c, "geodtocart() expects 3 arguments");
951 double lat = naNumValue(args[0]).num * SG_DEGREES_TO_RADIANS;
952 double lon = naNumValue(args[1]).num * SG_DEGREES_TO_RADIANS;
953 double alt = naNumValue(args[2]).num;
955 sgGeodToCart(lat, lon, alt, xyz);
956 naRef vec = naNewVector(c);
957 naVec_append(vec, naNum(xyz[0]));
958 naVec_append(vec, naNum(xyz[1]));
959 naVec_append(vec, naNum(xyz[2]));
963 // For given geodetic point return array with elevation, and a material data
964 // hash, or nil if there's no information available (tile not loaded). If
965 // information about the material isn't available, then nil is returned instead
967 static naRef f_geodinfo(naContext c, naRef me, int argc, naRef* args)
969 #define HASHSET(s,l,n) naHash_set(matdata, naStr_fromdata(naNewString(c),s,l),n)
970 if(argc < 2 || argc > 3)
971 naRuntimeError(c, "geodinfo() expects 2 or 3 arguments: lat, lon [, maxalt]");
972 double lat = naNumValue(args[0]).num;
973 double lon = naNumValue(args[1]).num;
974 double elev = argc == 3 ? naNumValue(args[2]).num : 10000;
975 const simgear::BVHMaterial *material;
976 SGGeod geod = SGGeod::fromDegM(lon, lat, elev);
977 if(!globals->get_scenery()->get_elevation_m(geod, elev, &material))
979 const SGMaterial *mat = dynamic_cast<const SGMaterial *>(material);
980 naRef vec = naNewVector(c);
981 naVec_append(vec, naNum(elev));
982 naRef matdata = naNil();
984 matdata = naNewHash(c);
985 naRef names = naNewVector(c);
986 BOOST_FOREACH(const std::string& n, mat->get_names())
987 naVec_append(names, stringToNasal(c, n));
989 HASHSET("names", 5, names);
990 HASHSET("solid", 5, naNum(mat->get_solid()));
991 HASHSET("friction_factor", 15, naNum(mat->get_friction_factor()));
992 HASHSET("rolling_friction", 16, naNum(mat->get_rolling_friction()));
993 HASHSET("load_resistance", 15, naNum(mat->get_load_resistance()));
994 HASHSET("bumpiness", 9, naNum(mat->get_bumpiness()));
995 HASHSET("light_coverage", 14, naNum(mat->get_light_coverage()));
997 naVec_append(vec, matdata);
1003 // Returns data hash for particular or nearest airport of a <type>, or nil
1006 // airportinfo(<id>); e.g. "KSFO"
1007 // airportinfo(<type>); type := ("airport"|"seaport"|"heliport")
1008 // airportinfo() same as airportinfo("airport")
1009 // airportinfo(<lat>, <lon> [, <type>]);
1010 static naRef f_airportinfo(naContext c, naRef me, int argc, naRef* args)
1012 SGGeod pos = globals->get_aircraft_position();
1013 FGAirport* apt = NULL;
1015 if(argc >= 2 && naIsNum(args[0]) && naIsNum(args[1])) {
1016 pos = SGGeod::fromDeg(args[1].num, args[0].num);
1021 double maxRange = 10000.0; // expose this? or pick a smaller value?
1023 FGAirport::TypeRunwayFilter filter; // defaults to airports only
1026 // fall through and use AIRPORT
1027 } else if(argc == 1 && naIsString(args[0])) {
1028 if (filter.fromTypeString(naStr_data(args[0]))) {
1031 // user provided an <id>, hopefully
1032 apt = FGAirport::findByIdent(naStr_data(args[0]));
1034 // return nil here, but don't raise a runtime error; this is a
1035 // legitamate way to validate an ICAO code, for example in a
1036 // dialog box or similar.
1041 naRuntimeError(c, "airportinfo() with invalid function arguments");
1046 apt = FGAirport::findClosest(pos, maxRange, &filter);
1047 if(!apt) return naNil();
1050 return ghostForAirport(c, apt);
1053 static naRef f_findAirportsWithinRange(naContext c, naRef me, int argc, naRef* args)
1056 SGGeod pos = globals->get_aircraft_position();
1057 argOffset += geodFromArgs(args, 0, argc, pos);
1059 if (!naIsNum(args[argOffset])) {
1060 naRuntimeError(c, "findAirportsWithinRange expected range (in nm) as arg %d", argOffset);
1063 FGAirport::TypeRunwayFilter filter; // defaults to airports only
1064 double rangeNm = args[argOffset++].num;
1065 if (argOffset < argc) {
1066 filter.fromTypeString(naStr_data(args[argOffset++]));
1069 naRef r = naNewVector(c);
1071 FGPositionedList apts = FGPositioned::findWithinRange(pos, rangeNm, &filter);
1072 FGPositioned::sortByRange(apts, pos);
1074 BOOST_FOREACH(FGPositionedRef a, apts) {
1075 FGAirport* apt = (FGAirport*) a.get();
1076 naVec_append(r, ghostForAirport(c, apt));
1082 static naRef f_findAirportsByICAO(naContext c, naRef me, int argc, naRef* args)
1084 if (!naIsString(args[0])) {
1085 naRuntimeError(c, "findAirportsByICAO expects string as arg 0");
1089 std::string prefix(naStr_data(args[argOffset++]));
1090 FGAirport::TypeRunwayFilter filter; // defaults to airports only
1091 if (argOffset < argc) {
1092 filter.fromTypeString(naStr_data(args[argOffset++]));
1095 naRef r = naNewVector(c);
1097 FGPositionedList apts = FGPositioned::findAllWithIdent(prefix, &filter, false);
1099 BOOST_FOREACH(FGPositionedRef a, apts) {
1100 FGAirport* apt = (FGAirport*) a.get();
1101 naVec_append(r, ghostForAirport(c, apt));
1107 static naRef f_airport_tower(naContext c, naRef me, int argc, naRef* args)
1109 FGAirport* apt = airportGhost(me);
1111 naRuntimeError(c, "airport.tower called on non-airport object");
1114 // build a hash for the tower position
1115 SGGeod towerLoc = apt->getTowerLocation();
1116 naRef tower = naNewHash(c);
1117 hashset(c, tower, "lat", naNum(towerLoc.getLatitudeDeg()));
1118 hashset(c, tower, "lon", naNum(towerLoc.getLongitudeDeg()));
1119 hashset(c, tower, "elevation", naNum(towerLoc.getElevationM()));
1123 static naRef f_airport_comms(naContext c, naRef me, int argc, naRef* args)
1125 FGAirport* apt = airportGhost(me);
1127 naRuntimeError(c, "airport.comms called on non-airport object");
1129 naRef comms = naNewVector(c);
1131 // if we have an explicit type, return a simple vector of frequencies
1132 if (argc > 0 && !naIsString(args[0])) {
1133 naRuntimeError(c, "airport.comms argument must be a frequency type name");
1137 std::string commName = naStr_data(args[0]);
1138 FGPositioned::Type commType = FGPositioned::typeFromName(commName);
1140 BOOST_FOREACH(flightgear::CommStation* comm, apt->commStationsOfType(commType)) {
1141 naVec_append(comms, naNum(comm->freqMHz()));
1144 // otherwise return a vector of hashes, one for each comm station.
1145 BOOST_FOREACH(flightgear::CommStation* comm, apt->commStations()) {
1146 naRef commHash = naNewHash(c);
1147 hashset(c, commHash, "frequency", naNum(comm->freqMHz()));
1148 hashset(c, commHash, "ident", stringToNasal(c, comm->ident()));
1149 naVec_append(comms, commHash);
1156 static naRef f_airport_runway(naContext c, naRef me, int argc, naRef* args)
1158 FGAirport* apt = airportGhost(me);
1160 naRuntimeError(c, "airport.runway called on non-airport object");
1163 if ((argc < 1) || !naIsString(args[0])) {
1164 naRuntimeError(c, "airport.runway expects a runway ident argument");
1167 std::string ident(naStr_data(args[0]));
1168 boost::to_upper(ident);
1170 if (apt->hasRunwayWithIdent(ident)) {
1171 return ghostForRunway(c, apt->getRunwayByIdent(ident));
1172 } else if (apt->hasHelipadWithIdent(ident)) {
1173 return ghostForHelipad(c, apt->getHelipadByIdent(ident));
1178 static naRef f_airport_runwaysWithoutReciprocals(naContext c, naRef me, int argc, naRef* args)
1180 FGAirport* apt = airportGhost(me);
1182 naRuntimeError(c, "airport.runwaysWithoutReciprocals called on non-airport object");
1185 FGRunwayList rwylist(apt->getRunwaysWithoutReciprocals());
1186 naRef runways = naNewVector(c);
1187 for (unsigned int r=0; r<rwylist.size(); ++r) {
1188 FGRunway* rwy(rwylist[r]);
1189 naVec_append(runways, ghostForRunway(c, apt->getRunwayByIdent(rwy->ident())));
1194 static naRef f_airport_sids(naContext c, naRef me, int argc, naRef* args)
1196 FGAirport* apt = airportGhost(me);
1198 naRuntimeError(c, "airport.sids called on non-airport object");
1201 naRef sids = naNewVector(c);
1203 FGRunway* rwy = NULL;
1204 if (argc > 0 && naIsString(args[0])) {
1205 if (!apt->hasRunwayWithIdent(naStr_data(args[0]))) {
1209 rwy = apt->getRunwayByIdent(naStr_data(args[0]));
1210 } else if (argc > 0) {
1211 rwy = runwayGhost(args[0]);
1215 BOOST_FOREACH(flightgear::SID* sid, rwy->getSIDs()) {
1216 naRef procId = stringToNasal(c, sid->ident());
1217 naVec_append(sids, procId);
1220 for (unsigned int s=0; s<apt->numSIDs(); ++s) {
1221 flightgear::SID* sid = apt->getSIDByIndex(s);
1222 naRef procId = stringToNasal(c, sid->ident());
1223 naVec_append(sids, procId);
1230 static naRef f_airport_stars(naContext c, naRef me, int argc, naRef* args)
1232 FGAirport* apt = airportGhost(me);
1234 naRuntimeError(c, "airport.stars called on non-airport object");
1237 naRef stars = naNewVector(c);
1239 FGRunway* rwy = NULL;
1240 if (argc > 0 && naIsString(args[0])) {
1241 if (!apt->hasRunwayWithIdent(naStr_data(args[0]))) {
1245 rwy = apt->getRunwayByIdent(naStr_data(args[0]));
1246 } else if (argc > 0) {
1247 rwy = runwayGhost(args[0]);
1251 BOOST_FOREACH(flightgear::STAR* s, rwy->getSTARs()) {
1252 naRef procId = stringToNasal(c, s->ident());
1253 naVec_append(stars, procId);
1256 for (unsigned int s=0; s<apt->numSTARs(); ++s) {
1257 flightgear::STAR* star = apt->getSTARByIndex(s);
1258 naRef procId = stringToNasal(c, star->ident());
1259 naVec_append(stars, procId);
1266 static naRef f_airport_approaches(naContext c, naRef me, int argc, naRef* args)
1268 FGAirport* apt = airportGhost(me);
1270 naRuntimeError(c, "airport.getApproachList called on non-airport object");
1273 naRef approaches = naNewVector(c);
1275 ProcedureType ty = PROCEDURE_INVALID;
1276 if ((argc > 1) && naIsString(args[1])) {
1277 std::string u(naStr_data(args[1]));
1279 if (u == "NDB") ty = PROCEDURE_APPROACH_NDB;
1280 if (u == "VOR") ty = PROCEDURE_APPROACH_VOR;
1281 if (u == "ILS") ty = PROCEDURE_APPROACH_ILS;
1282 if (u == "RNAV") ty = PROCEDURE_APPROACH_RNAV;
1285 FGRunway* rwy = NULL;
1286 if (argc > 0 && (rwy = runwayGhost(args[0]))) {
1288 } else if (argc > 0 && naIsString(args[0])) {
1289 if (!apt->hasRunwayWithIdent(naStr_data(args[0]))) {
1293 rwy = apt->getRunwayByIdent(naStr_data(args[0]));
1297 BOOST_FOREACH(Approach* s, rwy->getApproaches()) {
1298 if ((ty != PROCEDURE_INVALID) && (s->type() != ty)) {
1302 naRef procId = stringToNasal(c, s->ident());
1303 naVec_append(approaches, procId);
1306 // no runway specified, report them all
1307 for (unsigned int s=0; s<apt->numApproaches(); ++s) {
1308 Approach* app = apt->getApproachByIndex(s);
1309 if ((ty != PROCEDURE_INVALID) && (app->type() != ty)) {
1313 naRef procId = stringToNasal(c, app->ident());
1314 naVec_append(approaches, procId);
1321 static naRef f_airport_parking(naContext c, naRef me, int argc, naRef* args)
1323 FGAirport* apt = airportGhost(me);
1325 naRuntimeError(c, "airport.parking called on non-airport object");
1328 naRef r = naNewVector(c);
1330 bool onlyAvailable = false;
1332 if (argc > 0 && naIsString(args[0])) {
1333 type = naStr_data(args[0]);
1336 if ((argc > 1) && naIsNum(args[1])) {
1337 onlyAvailable = (args[1].num != 0.0);
1340 FGAirportDynamics* dynamics = apt->getDynamics();
1341 PositionedIDVec parkings = flightgear::NavDataCache::instance()->airportItemsOfType(apt->guid(),
1342 FGPositioned::PARKING);
1344 BOOST_FOREACH(PositionedID parking, parkings) {
1345 // filter out based on availability and type
1346 if (onlyAvailable && !dynamics->isParkingAvailable(parking)) {
1350 FGParking* park = dynamics->getParking(parking);
1351 if (!type.empty() && (park->getType() != type)) {
1355 const SGGeod& parkLoc = park->geod();
1356 naRef ph = naNewHash(c);
1357 hashset(c, ph, "name", stringToNasal(c, park->getName()));
1358 hashset(c, ph, "lat", naNum(parkLoc.getLatitudeDeg()));
1359 hashset(c, ph, "lon", naNum(parkLoc.getLongitudeDeg()));
1360 hashset(c, ph, "elevation", naNum(parkLoc.getElevationM()));
1361 naVec_append(r, ph);
1367 static naRef f_airport_getSid(naContext c, naRef me, int argc, naRef* args)
1369 FGAirport* apt = airportGhost(me);
1371 naRuntimeError(c, "airport.getSid called on non-airport object");
1374 if ((argc != 1) || !naIsString(args[0])) {
1375 naRuntimeError(c, "airport.getSid passed invalid argument");
1378 std::string ident = naStr_data(args[0]);
1379 return ghostForProcedure(c, apt->findSIDWithIdent(ident));
1382 static naRef f_airport_getStar(naContext c, naRef me, int argc, naRef* args)
1384 FGAirport* apt = airportGhost(me);
1386 naRuntimeError(c, "airport.getStar called on non-airport object");
1389 if ((argc != 1) || !naIsString(args[0])) {
1390 naRuntimeError(c, "airport.getStar passed invalid argument");
1393 std::string ident = naStr_data(args[0]);
1394 return ghostForProcedure(c, apt->findSTARWithIdent(ident));
1397 static naRef f_airport_getApproach(naContext c, naRef me, int argc, naRef* args)
1399 FGAirport* apt = airportGhost(me);
1401 naRuntimeError(c, "airport.getIAP called on non-airport object");
1404 if ((argc != 1) || !naIsString(args[0])) {
1405 naRuntimeError(c, "airport.getIAP passed invalid argument");
1408 std::string ident = naStr_data(args[0]);
1409 return ghostForProcedure(c, apt->findApproachWithIdent(ident));
1412 static naRef f_airport_findBestRunway(naContext c, naRef me, int argc, naRef* args)
1414 FGAirport* apt = airportGhost(me);
1416 naRuntimeError(c, "findBestRunway called on non-airport object");
1420 if (!geodFromArgs(args, 0, argc, pos)) {
1421 naRuntimeError(c, "findBestRunway must be passed a position");
1424 return ghostForRunway(c, apt->findBestRunwayForPos(pos));
1427 static naRef f_airport_toString(naContext c, naRef me, int argc, naRef* args)
1429 FGAirport* apt = airportGhost(me);
1431 naRuntimeError(c, "airport.tostring called on non-airport object");
1434 return stringToNasal(c, "an airport " + apt->ident());
1437 // Returns vector of data hash for navaid of a <type>, nil on error
1438 // navaids sorted by ascending distance
1439 // navinfo([<lat>,<lon>],[<type>],[<id>])
1440 // lat/lon (numeric): use latitude/longitude instead of ac position
1441 // type: ("fix"|"vor"|"ndb"|"ils"|"dme"|"tacan"|"any")
1442 // id: (partial) id of the fix
1444 // navinfo("vor") returns all vors
1445 // navinfo("HAM") return all navaids who's name start with "HAM"
1446 // navinfo("vor", "HAM") return all vor who's name start with "HAM"
1447 //navinfo(34,48,"vor","HAM") return all vor who's name start with "HAM"
1448 // sorted by distance relative to lat=34, lon=48
1449 static naRef f_navinfo(naContext c, naRef me, int argc, naRef* args)
1453 if(argc >= 2 && naIsNum(args[0]) && naIsNum(args[1])) {
1454 pos = SGGeod::fromDeg(args[1].num, args[0].num);
1458 pos = globals->get_aircraft_position();
1461 FGPositioned::Type type = FGPositioned::INVALID;
1462 nav_list_type navlist;
1463 const char * id = "";
1465 if(argc > 0 && naIsString(args[0])) {
1466 const char *s = naStr_data(args[0]);
1467 if(!strcmp(s, "any")) type = FGPositioned::INVALID;
1468 else if(!strcmp(s, "fix")) type = FGPositioned::FIX;
1469 else if(!strcmp(s, "vor")) type = FGPositioned::VOR;
1470 else if(!strcmp(s, "ndb")) type = FGPositioned::NDB;
1471 else if(!strcmp(s, "ils")) type = FGPositioned::ILS;
1472 else if(!strcmp(s, "dme")) type = FGPositioned::DME;
1473 else if(!strcmp(s, "tacan")) type = FGPositioned::TACAN;
1474 else id = s; // this is an id
1479 if(argc > 0 && naIsString(args[0])) {
1481 naRuntimeError(c, "navinfo() called with navaid id");
1484 id = naStr_data(args[0]);
1490 naRuntimeError(c, "navinfo() called with too many arguments");
1494 FGNavList::TypeFilter filter(type);
1495 navlist = FGNavList::findByIdentAndFreq( pos, id, 0.0, &filter );
1497 naRef reply = naNewVector(c);
1498 for( nav_list_type::const_iterator it = navlist.begin(); it != navlist.end(); ++it ) {
1499 naVec_append( reply, ghostForNavaid(c, *it) );
1504 static naRef f_findNavaidsWithinRange(naContext c, naRef me, int argc, naRef* args)
1507 SGGeod pos = globals->get_aircraft_position();
1508 argOffset += geodFromArgs(args, 0, argc, pos);
1510 if (!naIsNum(args[argOffset])) {
1511 naRuntimeError(c, "findNavaidsWithinRange expected range (in nm) as arg %d", argOffset);
1514 FGPositioned::Type type = FGPositioned::INVALID;
1515 double rangeNm = args[argOffset++].num;
1516 if (argOffset < argc) {
1517 type = FGPositioned::typeFromName(naStr_data(args[argOffset]));
1520 naRef r = naNewVector(c);
1521 FGNavList::TypeFilter filter(type);
1522 FGPositionedList navs = FGPositioned::findWithinRange(pos, rangeNm, &filter);
1523 FGPositioned::sortByRange(navs, pos);
1525 BOOST_FOREACH(FGPositionedRef a, navs) {
1526 FGNavRecord* nav = (FGNavRecord*) a.get();
1527 naVec_append(r, ghostForNavaid(c, nav));
1533 static naRef f_findNavaidByFrequency(naContext c, naRef me, int argc, naRef* args)
1536 SGGeod pos = globals->get_aircraft_position();
1537 argOffset += geodFromArgs(args, 0, argc, pos);
1539 if (!naIsNum(args[argOffset])) {
1540 naRuntimeError(c, "findNavaidByFrequency expectes frequency (in Mhz) as arg %d", argOffset);
1543 FGPositioned::Type type = FGPositioned::INVALID;
1544 double freqMhz = args[argOffset++].num;
1545 if (argOffset < argc) {
1546 type = FGPositioned::typeFromName(naStr_data(args[argOffset]));
1549 FGNavList::TypeFilter filter(type);
1550 nav_list_type navs = FGNavList::findAllByFreq(freqMhz, pos, &filter);
1555 return ghostForNavaid(c, navs.front().ptr());
1558 static naRef f_findNavaidsByFrequency(naContext c, naRef me, int argc, naRef* args)
1561 SGGeod pos = globals->get_aircraft_position();
1562 argOffset += geodFromArgs(args, 0, argc, pos);
1564 if (!naIsNum(args[argOffset])) {
1565 naRuntimeError(c, "findNavaidsByFrequency expectes frequency (in Mhz) as arg %d", argOffset);
1568 FGPositioned::Type type = FGPositioned::INVALID;
1569 double freqMhz = args[argOffset++].num;
1570 if (argOffset < argc) {
1571 type = FGPositioned::typeFromName(naStr_data(args[argOffset]));
1574 naRef r = naNewVector(c);
1576 FGNavList::TypeFilter filter(type);
1577 nav_list_type navs = FGNavList::findAllByFreq(freqMhz, pos, &filter);
1579 BOOST_FOREACH(nav_rec_ptr a, navs) {
1580 naVec_append(r, ghostForNavaid(c, a.ptr()));
1586 static naRef f_findNavaidsByIdent(naContext c, naRef me, int argc, naRef* args)
1589 SGGeod pos = globals->get_aircraft_position();
1590 argOffset += geodFromArgs(args, 0, argc, pos);
1592 if (!naIsString(args[argOffset])) {
1593 naRuntimeError(c, "findNavaidsByIdent expectes ident string as arg %d", argOffset);
1596 FGPositioned::Type type = FGPositioned::INVALID;
1597 std::string ident = naStr_data(args[argOffset++]);
1598 if (argOffset < argc) {
1599 type = FGPositioned::typeFromName(naStr_data(args[argOffset]));
1602 FGNavList::TypeFilter filter(type);
1603 naRef r = naNewVector(c);
1604 nav_list_type navs = FGNavList::findByIdentAndFreq(pos, ident, 0.0, &filter);
1606 BOOST_FOREACH(nav_rec_ptr a, navs) {
1607 naVec_append(r, ghostForNavaid(c, a.ptr()));
1613 static naRef f_findFixesByIdent(naContext c, naRef me, int argc, naRef* args)
1616 SGGeod pos = globals->get_aircraft_position();
1617 argOffset += geodFromArgs(args, 0, argc, pos);
1619 if (!naIsString(args[argOffset])) {
1620 naRuntimeError(c, "findFixesByIdent expectes ident string as arg %d", argOffset);
1623 std::string ident(naStr_data(args[argOffset]));
1624 naRef r = naNewVector(c);
1626 FGPositioned::TypeFilter filter(FGPositioned::FIX);
1627 FGPositionedList fixes = FGPositioned::findAllWithIdent(ident, &filter);
1628 FGPositioned::sortByRange(fixes, pos);
1630 BOOST_FOREACH(FGPositionedRef f, fixes) {
1631 naVec_append(r, ghostForFix(c, (FGFix*) f.ptr()));
1637 // Convert a cartesian point to a geodetic lat/lon/altitude.
1638 static naRef f_magvar(naContext c, naRef me, int argc, naRef* args)
1640 SGGeod pos = globals->get_aircraft_position();
1642 // fine, use aircraft position
1643 } else if (geodFromArgs(args, 0, argc, pos)) {
1646 naRuntimeError(c, "magvar() expects no arguments, a positioned hash or lat,lon pair");
1649 double jd = globals->get_time_params()->getJD();
1650 double magvarDeg = sgGetMagVar(pos, jd) * SG_RADIANS_TO_DEGREES;
1651 return naNum(magvarDeg);
1654 static naRef f_courseAndDistance(naContext c, naRef me, int argc, naRef* args)
1656 SGGeod from = globals->get_aircraft_position(), to, p;
1657 int argOffset = geodFromArgs(args, 0, argc, p);
1658 if (geodFromArgs(args, argOffset, argc, to)) {
1659 from = p; // we parsed both FROM and TO args, so first was from
1661 to = p; // only parsed one arg, so FROM is current
1664 if (argOffset == 0) {
1665 naRuntimeError(c, "invalid arguments to courseAndDistance");
1668 double course, course2, d;
1669 SGGeodesy::inverse(from, to, course, course2, d);
1671 naRef result = naNewVector(c);
1672 naVec_append(result, naNum(course));
1673 naVec_append(result, naNum(d * SG_METER_TO_NM));
1677 static naRef f_greatCircleMove(naContext c, naRef me, int argc, naRef* args)
1679 SGGeod from = globals->get_aircraft_position(), to;
1682 // complication - don't inerpret two doubles (as the only args)
1683 // as a lat,lon pair - only do so if we have at least three args.
1685 argOffset = geodFromArgs(args, 0, argc, from);
1688 if ((argOffset + 1) >= argc) {
1689 naRuntimeError(c, "isufficent arguments to greatCircleMove");
1692 if (!naIsNum(args[argOffset]) || !naIsNum(args[argOffset+1])) {
1693 naRuntimeError(c, "invalid arguments %d and %d to greatCircleMove",
1694 argOffset, argOffset + 1);
1697 double course = args[argOffset].num, course2;
1698 double distanceNm = args[argOffset + 1].num;
1699 SGGeodesy::direct(from, course, distanceNm * SG_NM_TO_METER, to, course2);
1702 naRef coord = naNewHash(c);
1703 hashset(c, coord, "lat", naNum(to.getLatitudeDeg()));
1704 hashset(c, coord, "lon", naNum(to.getLongitudeDeg()));
1708 static naRef f_tilePath(naContext c, naRef me, int argc, naRef* args)
1710 SGGeod pos = globals->get_aircraft_position();
1711 geodFromArgs(args, 0, argc, pos);
1713 return stringToNasal(c, b.gen_base_path());
1716 static naRef f_tileIndex(naContext c, naRef me, int argc, naRef* args)
1718 SGGeod pos = globals->get_aircraft_position();
1719 geodFromArgs(args, 0, argc, pos);
1721 return naNum(b.gen_index());
1724 static naRef f_route(naContext c, naRef me, int argc, naRef* args)
1727 FGRouteMgr* rm = static_cast<FGRouteMgr*>(globals->get_subsystem("route-manager"));
1728 return ghostForFlightPlan(c, rm->flightPlan());
1731 if ((argc > 0) && naIsString(args[0])) {
1732 flightgear::FlightPlan* fp = new flightgear::FlightPlan;
1733 SGPath path(naStr_data(args[0]));
1734 if (!path.exists()) {
1735 naRuntimeError(c, "flightplan, no file at path %s", path.c_str());
1738 if (!fp->load(path)) {
1739 SG_LOG(SG_NASAL, SG_WARN, "failed to load flight-plan from " << path);
1744 return ghostForFlightPlan(c, fp);
1747 naRuntimeError(c, "bad arguments to flightplan()");
1751 class NasalFPDelegate : public FlightPlan::Delegate
1754 NasalFPDelegate(FlightPlan* fp, FGNasalSys* sys, naRef ins) :
1759 _gcSaveKey = _nasal->gcSave(ins);
1762 virtual ~NasalFPDelegate()
1764 _nasal->gcRelease(_gcSaveKey);
1767 virtual void departureChanged()
1769 callDelegateMethod("departureChanged");
1772 virtual void arrivalChanged()
1774 callDelegateMethod("arrivalChanged");
1777 virtual void waypointsChanged()
1779 callDelegateMethod("waypointsChanged");
1782 virtual void currentWaypointChanged()
1784 callDelegateMethod("currentWaypointChanged");
1787 virtual void cleared()
1789 callDelegateMethod("cleared");
1792 virtual void endOfFlightPlan()
1794 callDelegateMethod("endOfFlightPlan");
1798 void callDelegateMethod(const char* method)
1801 naContext ctx = naNewContext();
1803 if (naMember_cget(ctx, _instance, method, &f) != 0) {
1805 arg[0] = ghostForFlightPlan(ctx, _plan);
1806 _nasal->callMethod(f, _instance, 1, arg, naNil());
1819 class NasalFPDelegateFactory : public FlightPlan::DelegateFactory
1822 NasalFPDelegateFactory(naRef code)
1824 _nasal = (FGNasalSys*) globals->get_subsystem("nasal");
1826 _gcSaveKey = _nasal->gcSave(_func);
1829 virtual ~NasalFPDelegateFactory()
1831 _nasal->gcRelease(_gcSaveKey);
1834 virtual FlightPlan::Delegate* createFlightPlanDelegate(FlightPlan* fp)
1837 naContext ctx = naNewContext();
1838 args[0] = ghostForFlightPlan(ctx, fp);
1839 naRef instance = _nasal->call(_func, 1, args, naNil());
1841 FlightPlan::Delegate* result = NULL;
1842 if (!naIsNil(instance)) {
1843 // will GC-save instance
1844 result = new NasalFPDelegate(fp, _nasal, instance);
1856 static std::vector<NasalFPDelegateFactory*> static_nasalDelegateFactories;
1858 void shutdownNasalPositioned()
1860 std::vector<NasalFPDelegateFactory*>::iterator it;
1861 for (it = static_nasalDelegateFactories.begin();
1862 it != static_nasalDelegateFactories.end(); ++it)
1864 FlightPlan::unregisterDelegateFactory(*it);
1867 static_nasalDelegateFactories.clear();
1870 static naRef f_registerFPDelegate(naContext c, naRef me, int argc, naRef* args)
1872 if ((argc < 1) || !naIsFunc(args[0])) {
1873 naRuntimeError(c, "non-function argument to registerFlightPlanDelegate");
1876 NasalFPDelegateFactory* factory = new NasalFPDelegateFactory(args[0]);
1877 FlightPlan::registerDelegateFactory(factory);
1878 static_nasalDelegateFactories.push_back(factory);
1882 static WayptRef wayptFromArg(naRef arg)
1884 WayptRef r = wayptGhost(arg);
1889 FGPositioned* pos = positionedGhost(arg);
1891 // let's check if the arg is hash, coudl extra a geod and hence build
1892 // a simple waypoint
1897 // special-case for runways
1898 if (pos->type() == FGPositioned::RUNWAY) {
1899 return new RunwayWaypt((FGRunway*) pos, NULL);
1902 return new NavaidWaypoint(pos, NULL);
1905 static naRef convertWayptVecToNasal(naContext c, const WayptVec& wps)
1907 naRef result = naNewVector(c);
1908 BOOST_FOREACH(WayptRef wpt, wps) {
1909 naVec_append(result, ghostForWaypt(c, wpt.get()));
1914 static naRef f_airwaySearch(naContext c, naRef me, int argc, naRef* args)
1917 naRuntimeError(c, "airwaysSearch needs at least two arguments");
1920 WayptRef start = wayptFromArg(args[0]),
1921 end = wayptFromArg(args[1]);
1923 if (!start || !end) {
1924 SG_LOG(SG_NASAL, SG_WARN, "airwaysSearch: start or end points are invalid");
1928 bool highLevel = true;
1929 if ((argc > 2) && naIsString(args[2])) {
1930 if (!strcmp(naStr_data(args[2]), "lowlevel")) {
1937 Airway::highLevel()->route(start, end, route);
1939 Airway::lowLevel()->route(start, end, route);
1942 return convertWayptVecToNasal(c, route);
1945 static naRef f_createWP(naContext c, naRef me, int argc, naRef* args)
1948 int argOffset = geodFromArgs(args, 0, argc, pos);
1950 if (((argc - argOffset) < 1) || !naIsString(args[argOffset])) {
1951 naRuntimeError(c, "createWP: no identifier supplied");
1954 std::string ident = naStr_data(args[argOffset++]);
1955 WayptRef wpt = new BasicWaypt(pos, ident, NULL);
1957 // set waypt flags - approach, departure, pseudo, etc
1958 if (argc > argOffset) {
1959 WayptFlag f = wayptFlagFromString(naStr_data(args[argOffset++]));
1961 naRuntimeError(c, "createWP: bad waypoint role");
1967 return ghostForWaypt(c, wpt);
1970 static naRef f_createWPFrom(naContext c, naRef me, int argc, naRef* args)
1973 naRuntimeError(c, "createWPFrom: need at least one argument");
1976 FGPositioned* positioned = positionedGhost(args[0]);
1978 naRuntimeError(c, "createWPFrom: couldn;t convert arg[0] to FGPositioned");
1982 if (positioned->type() == FGPositioned::RUNWAY) {
1983 wpt = new RunwayWaypt((FGRunway*) positioned, NULL);
1985 wpt = new NavaidWaypoint(positioned, NULL);
1988 // set waypt flags - approach, departure, pseudo, etc
1990 WayptFlag f = wayptFlagFromString(naStr_data(args[1]));
1992 naRuntimeError(c, "createWPFrom: bad waypoint role");
1997 return ghostForWaypt(c, wpt);
2000 static naRef f_flightplan_getWP(naContext c, naRef me, int argc, naRef* args)
2002 FlightPlan* fp = flightplanGhost(me);
2004 naRuntimeError(c, "flightplan.getWP called on non-flightplan object");
2009 index = fp->currentIndex();
2011 index = (int) naNumValue(args[0]).num;
2014 if ((index < 0) || (index >= fp->numLegs())) {
2018 return ghostForLeg(c, fp->legAtIndex(index));
2021 static naRef f_flightplan_currentWP(naContext c, naRef me, int argc, naRef* args)
2023 FlightPlan* fp = flightplanGhost(me);
2025 naRuntimeError(c, "flightplan.currentWP called on non-flightplan object");
2027 return ghostForLeg(c, fp->currentLeg());
2030 static naRef f_flightplan_nextWP(naContext c, naRef me, int argc, naRef* args)
2032 FlightPlan* fp = flightplanGhost(me);
2034 naRuntimeError(c, "flightplan.nextWP called on non-flightplan object");
2036 return ghostForLeg(c, fp->nextLeg());
2039 static naRef f_flightplan_numWaypoints(naContext c, naRef me, int argc, naRef* args)
2041 FlightPlan* fp = flightplanGhost(me);
2043 naRuntimeError(c, "flightplan.numWaypoints called on non-flightplan object");
2045 return naNum(fp->numLegs());
2048 static naRef f_flightplan_appendWP(naContext c, naRef me, int argc, naRef* args)
2050 FlightPlan* fp = flightplanGhost(me);
2052 naRuntimeError(c, "flightplan.appendWP called on non-flightplan object");
2055 WayptRef wp = wayptGhost(args[0]);
2056 int index = fp->numLegs();
2057 fp->insertWayptAtIndex(wp.get(), index);
2058 return naNum(index);
2061 static naRef f_flightplan_insertWP(naContext c, naRef me, int argc, naRef* args)
2063 FlightPlan* fp = flightplanGhost(me);
2065 naRuntimeError(c, "flightplan.insertWP called on non-flightplan object");
2068 WayptRef wp = wayptGhost(args[0]);
2069 int index = -1; // append
2070 if ((argc > 1) && naIsNum(args[1])) {
2071 index = (int) args[1].num;
2074 fp->insertWayptAtIndex(wp.get(), index);
2078 static naRef f_flightplan_insertWPAfter(naContext c, naRef me, int argc, naRef* args)
2080 FlightPlan* fp = flightplanGhost(me);
2082 naRuntimeError(c, "flightplan.insertWPAfter called on non-flightplan object");
2085 WayptRef wp = wayptGhost(args[0]);
2086 int index = -1; // append
2087 if ((argc > 1) && naIsNum(args[1])) {
2088 index = (int) args[1].num;
2091 fp->insertWayptAtIndex(wp.get(), index + 1);
2095 static naRef f_flightplan_insertWaypoints(naContext c, naRef me, int argc, naRef* args)
2097 FlightPlan* fp = flightplanGhost(me);
2099 naRuntimeError(c, "flightplan.insertWaypoints called on non-flightplan object");
2103 if (!naIsVector(args[0])) {
2104 naRuntimeError(c, "flightplan.insertWaypoints expects vector as first arg");
2107 int count = naVec_size(args[0]);
2108 for (int i=0; i<count; ++i) {
2109 Waypt* wp = wayptGhost(naVec_get(args[0], i));
2115 int index = -1; // append
2116 if ((argc > 1) && naIsNum(args[1])) {
2117 index = (int) args[1].num;
2120 fp->insertWayptsAtIndex(wps, index);
2124 static naRef f_flightplan_deleteWP(naContext c, naRef me, int argc, naRef* args)
2126 FlightPlan* fp = flightplanGhost(me);
2128 naRuntimeError(c, "flightplan.deleteWP called on non-flightplan object");
2131 if ((argc < 1) || !naIsNum(args[0])) {
2132 naRuntimeError(c, "bad argument to flightplan.deleteWP");
2135 int index = (int) args[0].num;
2136 fp->deleteIndex(index);
2140 static naRef f_flightplan_clearPlan(naContext c, naRef me, int argc, naRef* args)
2142 FlightPlan* fp = flightplanGhost(me);
2144 naRuntimeError(c, "flightplan.clearPlan called on non-flightplan object");
2151 static naRef f_flightplan_clearWPType(naContext c, naRef me, int argc, naRef* args)
2153 FlightPlan* fp = flightplanGhost(me);
2155 naRuntimeError(c, "flightplan.clearWPType called on non-flightplan object");
2159 naRuntimeError(c, "insufficent args to flightplan.clearWPType");
2162 WayptFlag flag = wayptFlagFromString(naStr_data(args[0]));
2164 naRuntimeError(c, "clearWPType: bad waypoint role");
2167 fp->clearWayptsWithFlag(flag);
2171 static naRef f_flightplan_clone(naContext c, naRef me, int argc, naRef* args)
2173 FlightPlan* fp = flightplanGhost(me);
2175 naRuntimeError(c, "flightplan.clone called on non-flightplan object");
2178 return ghostForFlightPlan(c, fp->clone());
2181 static naRef f_flightplan_pathGeod(naContext c, naRef me, int argc, naRef* args)
2183 FlightPlan* fp = flightplanGhost(me);
2185 naRuntimeError(c, "flightplan.clone called on non-flightplan object");
2188 if ((argc < 1) || !naIsNum(args[0])) {
2189 naRuntimeError(c, "bad argument to flightplan.pathGeod");
2192 if ((argc > 1) && !naIsNum(args[1])) {
2193 naRuntimeError(c, "bad argument to flightplan.pathGeod");
2196 int index = (int) args[0].num;
2197 double offset = (argc > 1) ? args[1].num : 0.0;
2198 naRef result = naNewHash(c);
2199 SGGeod g = fp->pointAlongRoute(index, offset);
2200 hashset(c, result, "lat", naNum(g.getLatitudeDeg()));
2201 hashset(c, result, "lon", naNum(g.getLongitudeDeg()));
2205 static naRef f_flightplan_finish(naContext c, naRef me, int argc, naRef* args)
2207 FlightPlan* fp = flightplanGhost(me);
2209 naRuntimeError(c, "flightplan.finish called on non-flightplan object");
2216 static naRef f_flightplan_indexOfWp(naContext c, naRef me, int argc, naRef* args)
2218 FlightPlan* fp = flightplanGhost(me);
2220 naRuntimeError(c, "flightplan.indexOfWP called on non-flightplan object");
2223 FGPositioned* positioned = positionedGhost(args[0]);
2225 return naNum(fp->findWayptIndex(positioned));
2229 int argOffset = geodFromArgs(args, 0, argc, pos);
2230 if (argOffset > 0) {
2231 return naNum(fp->findWayptIndex(pos));
2237 static naRef f_leg_setSpeed(naContext c, naRef me, int argc, naRef* args)
2239 FlightPlan::Leg* leg = fpLegGhost(me);
2241 naRuntimeError(c, "leg.setSpeed called on non-flightplan-leg object");
2245 if ((argc < 2) || !convertToNum(args[0], speed))
2246 naRuntimeError(c, "bad arguments to setSpeed");
2248 RouteRestriction rr = routeRestrictionFromString(naStr_data(args[1]));
2249 leg->setSpeed(rr, speed);
2254 static naRef f_leg_setAltitude(naContext c, naRef me, int argc, naRef* args)
2256 FlightPlan::Leg* leg = fpLegGhost(me);
2258 naRuntimeError(c, "leg.setAltitude called on non-flightplan-leg object");
2262 if ((argc < 2) || !convertToNum(args[0], alt))
2263 naRuntimeError(c, "bad arguments to leg.setAltitude");
2265 RouteRestriction rr = routeRestrictionFromString(naStr_data(args[1]));
2266 leg->setAltitude(rr, alt);
2271 static naRef f_leg_path(naContext c, naRef me, int argc, naRef* args)
2273 FlightPlan::Leg* leg = fpLegGhost(me);
2275 naRuntimeError(c, "leg.setAltitude called on non-flightplan-leg object");
2278 RoutePath path(leg->owner());
2279 SGGeodVec gv(path.pathForIndex(leg->index()));
2281 naRef result = naNewVector(c);
2282 BOOST_FOREACH(SGGeod p, gv) {
2283 // construct a geo.Coord!
2284 naRef coord = naNewHash(c);
2285 hashset(c, coord, "lat", naNum(p.getLatitudeDeg()));
2286 hashset(c, coord, "lon", naNum(p.getLongitudeDeg()));
2287 naVec_append(result, coord);
2293 static naRef f_leg_courseAndDistanceFrom(naContext c, naRef me, int argc, naRef* args)
2295 FlightPlan::Leg* leg = fpLegGhost(me);
2297 naRuntimeError(c, "leg.courseAndDistanceFrom called on non-flightplan-leg object");
2301 geodFromArgs(args, 0, argc, pos);
2305 boost::tie(courseDeg, distanceM) = leg->waypoint()->courseAndDistanceFrom(pos);
2307 naRef result = naNewVector(c);
2308 naVec_append(result, naNum(courseDeg));
2309 naVec_append(result, naNum(distanceM * SG_METER_TO_NM));
2313 static naRef f_waypoint_navaid(naContext c, naRef me, int argc, naRef* args)
2315 flightgear::Waypt* w = wayptGhost(me);
2317 naRuntimeError(c, "waypoint.navaid called on non-waypoint object");
2320 FGPositioned* pos = w->source();
2325 switch (pos->type()) {
2326 case FGPositioned::VOR:
2327 case FGPositioned::NDB:
2328 case FGPositioned::ILS:
2329 case FGPositioned::LOC:
2330 case FGPositioned::GS:
2331 case FGPositioned::DME:
2332 case FGPositioned::TACAN: {
2333 FGNavRecord* nav = (FGNavRecord*) pos;
2334 return ghostForNavaid(c, nav);
2342 static naRef f_waypoint_airport(naContext c, naRef me, int argc, naRef* args)
2344 flightgear::Waypt* w = wayptGhost(me);
2346 naRuntimeError(c, "waypoint.navaid called on non-waypoint object");
2349 FGPositioned* pos = w->source();
2350 if (!pos || FGAirport::isAirportType(pos)) {
2354 return ghostForAirport(c, (FGAirport*) pos);
2357 static naRef f_waypoint_runway(naContext c, naRef me, int argc, naRef* args)
2359 flightgear::Waypt* w = wayptGhost(me);
2361 naRuntimeError(c, "waypoint.navaid called on non-waypoint object");
2364 FGPositioned* pos = w->source();
2365 if (!pos || (pos->type() != FGPositioned::RUNWAY)) {
2369 return ghostForRunway(c, (FGRunway*) pos);
2372 static naRef f_procedure_transition(naContext c, naRef me, int argc, naRef* args)
2374 Procedure* proc = procedureGhost(me);
2376 naRuntimeError(c, "procedure.transition called on non-procedure object");
2379 if ((proc->type() != PROCEDURE_SID) && (proc->type() != PROCEDURE_STAR)) {
2380 naRuntimeError(c, "procedure.transition called on non-SID or -STAR");
2383 ArrivalDeparture* ad = (ArrivalDeparture*) proc;
2384 Transition* trans = ad->findTransitionByName(naStr_data(args[0]));
2386 return ghostForProcedure(c, trans);
2389 static naRef f_procedure_route(naContext c, naRef me, int argc, naRef* args)
2391 Procedure* proc = procedureGhost(me);
2393 naRuntimeError(c, "procedure.route called on non-procedure object");
2396 // wrapping up tow different routines here - approach routing from the IAF
2397 // to the associated runway, and SID/STAR routing via an enroute transition
2398 // and possibly a runway transition or not.
2399 if (Approach::isApproach(proc->type())) {
2402 iaf = wayptFromArg(args[0]);
2406 Approach* app = (Approach*) proc;
2407 if (!app->route(iaf, r)) {
2408 SG_LOG(SG_NASAL, SG_WARN, "procedure.route failed for Approach somehow");
2412 return convertWayptVecToNasal(c, r);
2413 } else if ((proc->type() != PROCEDURE_SID) && (proc->type() != PROCEDURE_STAR)) {
2414 naRuntimeError(c, "procedure.route called on unsuitable procedure type");
2418 FGRunway* rwy = runwayGhost(args[0]);
2419 if (rwy) ++argOffset;
2421 ArrivalDeparture* ad = (ArrivalDeparture*) proc;
2422 Transition* trans = NULL;
2423 if (argOffset < argc) {
2424 trans = (Transition*) procedureGhost(args[argOffset]);
2427 // note either runway or trans may be NULL - that's ok
2429 if (!ad->route(rwy, trans, r)) {
2430 SG_LOG(SG_NASAL, SG_WARN, "prcoedure.route failed for ArrvialDeparture somehow");
2434 return convertWayptVecToNasal(c, r);
2438 // Table of extension functions. Terminate with zeros.
2439 static struct { const char* name; naCFunction func; } funcs[] = {
2440 { "carttogeod", f_carttogeod },
2441 { "geodtocart", f_geodtocart },
2442 { "geodinfo", f_geodinfo },
2443 { "airportinfo", f_airportinfo },
2444 { "findAirportsWithinRange", f_findAirportsWithinRange },
2445 { "findAirportsByICAO", f_findAirportsByICAO },
2446 { "navinfo", f_navinfo },
2447 { "findNavaidsWithinRange", f_findNavaidsWithinRange },
2448 { "findNavaidByFrequency", f_findNavaidByFrequency },
2449 { "findNavaidsByFrequency", f_findNavaidsByFrequency },
2450 { "findNavaidsByID", f_findNavaidsByIdent },
2451 { "findFixesByID", f_findFixesByIdent },
2452 { "flightplan", f_route },
2453 { "registerFlightPlanDelegate", f_registerFPDelegate },
2454 { "createWP", f_createWP },
2455 { "createWPFrom", f_createWPFrom },
2456 { "airwaysRoute", f_airwaySearch },
2457 { "magvar", f_magvar },
2458 { "courseAndDistance", f_courseAndDistance },
2459 { "greatCircleMove", f_greatCircleMove },
2460 { "tileIndex", f_tileIndex },
2461 { "tilePath", f_tilePath },
2466 naRef initNasalPositioned(naRef globals, naContext c)
2468 airportPrototype = naNewHash(c);
2469 naSave(c, airportPrototype);
2471 hashset(c, airportPrototype, "runway", naNewFunc(c, naNewCCode(c, f_airport_runway)));
2472 hashset(c, airportPrototype, "runwaysWithoutReciprocals", naNewFunc(c, naNewCCode(c, f_airport_runwaysWithoutReciprocals)));
2473 hashset(c, airportPrototype, "helipad", naNewFunc(c, naNewCCode(c, f_airport_runway)));
2474 hashset(c, airportPrototype, "tower", naNewFunc(c, naNewCCode(c, f_airport_tower)));
2475 hashset(c, airportPrototype, "comms", naNewFunc(c, naNewCCode(c, f_airport_comms)));
2476 hashset(c, airportPrototype, "sids", naNewFunc(c, naNewCCode(c, f_airport_sids)));
2477 hashset(c, airportPrototype, "stars", naNewFunc(c, naNewCCode(c, f_airport_stars)));
2478 hashset(c, airportPrototype, "getApproachList", naNewFunc(c, naNewCCode(c, f_airport_approaches)));
2479 hashset(c, airportPrototype, "parking", naNewFunc(c, naNewCCode(c, f_airport_parking)));
2480 hashset(c, airportPrototype, "getSid", naNewFunc(c, naNewCCode(c, f_airport_getSid)));
2481 hashset(c, airportPrototype, "getStar", naNewFunc(c, naNewCCode(c, f_airport_getStar)));
2482 hashset(c, airportPrototype, "getIAP", naNewFunc(c, naNewCCode(c, f_airport_getApproach)));
2483 hashset(c, airportPrototype, "findBestRunwayForPos", naNewFunc(c, naNewCCode(c, f_airport_findBestRunway)));
2484 hashset(c, airportPrototype, "tostring", naNewFunc(c, naNewCCode(c, f_airport_toString)));
2486 flightplanPrototype = naNewHash(c);
2487 naSave(c, flightplanPrototype);
2489 hashset(c, flightplanPrototype, "getWP", naNewFunc(c, naNewCCode(c, f_flightplan_getWP)));
2490 hashset(c, flightplanPrototype, "currentWP", naNewFunc(c, naNewCCode(c, f_flightplan_currentWP)));
2491 hashset(c, flightplanPrototype, "nextWP", naNewFunc(c, naNewCCode(c, f_flightplan_nextWP)));
2492 hashset(c, flightplanPrototype, "getPlanSize", naNewFunc(c, naNewCCode(c, f_flightplan_numWaypoints)));
2493 hashset(c, flightplanPrototype, "appendWP", naNewFunc(c, naNewCCode(c, f_flightplan_appendWP)));
2494 hashset(c, flightplanPrototype, "insertWP", naNewFunc(c, naNewCCode(c, f_flightplan_insertWP)));
2495 hashset(c, flightplanPrototype, "deleteWP", naNewFunc(c, naNewCCode(c, f_flightplan_deleteWP)));
2496 hashset(c, flightplanPrototype, "insertWPAfter", naNewFunc(c, naNewCCode(c, f_flightplan_insertWPAfter)));
2497 hashset(c, flightplanPrototype, "insertWaypoints", naNewFunc(c, naNewCCode(c, f_flightplan_insertWaypoints)));
2498 hashset(c, flightplanPrototype, "cleanPlan", naNewFunc(c, naNewCCode(c, f_flightplan_clearPlan)));
2499 hashset(c, flightplanPrototype, "clearWPType", naNewFunc(c, naNewCCode(c, f_flightplan_clearWPType)));
2500 hashset(c, flightplanPrototype, "clone", naNewFunc(c, naNewCCode(c, f_flightplan_clone)));
2501 hashset(c, flightplanPrototype, "pathGeod", naNewFunc(c, naNewCCode(c, f_flightplan_pathGeod)));
2502 hashset(c, flightplanPrototype, "finish", naNewFunc(c, naNewCCode(c, f_flightplan_finish)));
2503 hashset(c, flightplanPrototype, "indexOfWP", naNewFunc(c, naNewCCode(c, f_flightplan_indexOfWp)));
2505 waypointPrototype = naNewHash(c);
2506 naSave(c, waypointPrototype);
2508 hashset(c, waypointPrototype, "navaid", naNewFunc(c, naNewCCode(c, f_waypoint_navaid)));
2509 hashset(c, waypointPrototype, "runway", naNewFunc(c, naNewCCode(c, f_waypoint_runway)));
2510 hashset(c, waypointPrototype, "airport", naNewFunc(c, naNewCCode(c, f_waypoint_airport)));
2512 procedurePrototype = naNewHash(c);
2513 naSave(c, procedurePrototype);
2514 hashset(c, procedurePrototype, "transition", naNewFunc(c, naNewCCode(c, f_procedure_transition)));
2515 hashset(c, procedurePrototype, "route", naNewFunc(c, naNewCCode(c, f_procedure_route)));
2517 fpLegPrototype = naNewHash(c);
2518 naSave(c, fpLegPrototype);
2519 hashset(c, fpLegPrototype, "setSpeed", naNewFunc(c, naNewCCode(c, f_leg_setSpeed)));
2520 hashset(c, fpLegPrototype, "setAltitude", naNewFunc(c, naNewCCode(c, f_leg_setAltitude)));
2521 hashset(c, fpLegPrototype, "path", naNewFunc(c, naNewCCode(c, f_leg_path)));
2522 hashset(c, fpLegPrototype, "courseAndDistanceFrom", naNewFunc(c, naNewCCode(c, f_leg_courseAndDistanceFrom)));
2524 for(int i=0; funcs[i].name; i++) {
2525 hashset(c, globals, funcs[i].name,
2526 naNewFunc(c, naNewCCode(c, funcs[i].func)));
2532 void postinitNasalPositioned(naRef globals, naContext c)
2534 naRef geoModule = naHash_cget(globals, (char*) "geo");
2535 if (naIsNil(geoModule)) {
2536 SG_LOG(SG_GENERAL, SG_WARN, "postinitNasalPositioned: geo.nas not loaded");
2540 geoCoordClass = naHash_cget(geoModule, (char*) "Coord");