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");
446 } else if (!strcmp(fieldName, "heading_course")) {
447 *out = naNum(wpt->headingRadialDeg());
449 return NULL; // member not found
455 static void waypointCommonSetMember(naContext c, Waypt* wpt, const char* fieldName, naRef value)
457 if (!strcmp(fieldName, "wp_role")) {
458 if (!naIsString(value)) naRuntimeError(c, "wp_role must be a string");
459 if (wpt->owner() != NULL) naRuntimeError(c, "cannot override wp_role on waypoint with parent");
460 WayptFlag f = wayptFlagFromString(naStr_data(value));
462 naRuntimeError(c, "unrecognized wp_role value %s", naStr_data(value));
465 wpt->setFlag(f, true);
469 static const char* wayptGhostGetMember(naContext c, void* g, naRef field, naRef* out)
471 const char* fieldName = naStr_data(field);
472 Waypt* wpt = (flightgear::Waypt*) g;
473 return waypointCommonGetMember(c, wpt, fieldName, out);
476 static RouteRestriction routeRestrictionFromString(const char* s)
480 if (u == "computed") return RESTRICT_COMPUTED;
481 if (u == "at") return RESTRICT_AT;
482 if (u == "mach") return SPEED_RESTRICT_MACH;
483 if (u == "computed-mach") return SPEED_COMPUTED_MACH;
484 if (u == "delete") return RESTRICT_DELETE;
485 return RESTRICT_NONE;
488 naRef routeRestrictionToNasal(naContext c, RouteRestriction rr)
491 case RESTRICT_NONE: return naNil();
492 case RESTRICT_AT: return stringToNasal(c, "at");
493 case RESTRICT_ABOVE: return stringToNasal(c, "above");
494 case RESTRICT_BELOW: return stringToNasal(c, "below");
495 case SPEED_RESTRICT_MACH: return stringToNasal(c, "mach");
496 case RESTRICT_COMPUTED: return stringToNasal(c, "computed");
497 case SPEED_COMPUTED_MACH: return stringToNasal(c, "computed-mach");
498 case RESTRICT_DELETE: return stringToNasal(c, "delete");
504 static const char* legGhostGetMember(naContext c, void* g, naRef field, naRef* out)
506 const char* fieldName = naStr_data(field);
507 FlightPlan::Leg* leg = (FlightPlan::Leg*) g;
508 Waypt* wpt = leg->waypoint();
510 if (!strcmp(fieldName, "parents")) {
511 *out = naNewVector(c);
512 naVec_append(*out, fpLegPrototype);
513 naVec_append(*out, waypointPrototype);
514 } else if (!strcmp(fieldName, "index")) {
515 *out = naNum(leg->index());
516 } else if (!strcmp(fieldName, "alt_cstr")) {
517 *out = naNum(leg->altitudeFt());
518 } else if (!strcmp(fieldName, "alt_cstr_type")) {
519 *out = routeRestrictionToNasal(c, leg->altitudeRestriction());
520 } else if (!strcmp(fieldName, "speed_cstr")) {
521 double s = isMachRestrict(leg->speedRestriction()) ? leg->speedMach() : leg->speedKts();
523 } else if (!strcmp(fieldName, "speed_cstr_type")) {
524 *out = routeRestrictionToNasal(c, leg->speedRestriction());
525 } else if (!strcmp(fieldName, "leg_distance")) {
526 *out = naNum(leg->distanceNm());
527 } else if (!strcmp(fieldName, "leg_bearing")) {
528 *out = naNum(leg->courseDeg());
529 } else if (!strcmp(fieldName, "distance_along_route")) {
530 *out = naNum(leg->distanceAlongRoute());
531 } else { // check for fields defined on the underlying waypoint
532 return waypointCommonGetMember(c, wpt, fieldName, out);
535 return ""; // success
538 static void waypointGhostSetMember(naContext c, void* g, naRef field, naRef value)
540 const char* fieldName = naStr_data(field);
541 Waypt* wpt = (Waypt*) g;
542 waypointCommonSetMember(c, wpt, fieldName, value);
545 static void legGhostSetMember(naContext c, void* g, naRef field, naRef value)
547 const char* fieldName = naStr_data(field);
548 FlightPlan::Leg* leg = (FlightPlan::Leg*) g;
550 waypointCommonSetMember(c, leg->waypoint(), fieldName, value);
553 static const char* flightplanGhostGetMember(naContext c, void* g, naRef field, naRef* out)
555 const char* fieldName = naStr_data(field);
556 FlightPlan* fp = (FlightPlan*) g;
558 if (!strcmp(fieldName, "parents")) {
559 *out = naNewVector(c);
560 naVec_append(*out, flightplanPrototype);
561 } else if (!strcmp(fieldName, "id")) *out = stringToNasal(c, fp->ident());
562 else if (!strcmp(fieldName, "departure")) *out = ghostForAirport(c, fp->departureAirport());
563 else if (!strcmp(fieldName, "destination")) *out = ghostForAirport(c, fp->destinationAirport());
564 else if (!strcmp(fieldName, "departure_runway")) *out = ghostForRunway(c, fp->departureRunway());
565 else if (!strcmp(fieldName, "destination_runway")) *out = ghostForRunway(c, fp->destinationRunway());
566 else if (!strcmp(fieldName, "sid")) *out = ghostForProcedure(c, fp->sid());
567 else if (!strcmp(fieldName, "sid_trans")) *out = ghostForProcedure(c, fp->sidTransition());
568 else if (!strcmp(fieldName, "star")) *out = ghostForProcedure(c, fp->star());
569 else if (!strcmp(fieldName, "star_trans")) *out = ghostForProcedure(c, fp->starTransition());
570 else if (!strcmp(fieldName, "approach")) *out = ghostForProcedure(c, fp->approach());
571 else if (!strcmp(fieldName, "current")) *out = naNum(fp->currentIndex());
579 static void flightplanGhostSetMember(naContext c, void* g, naRef field, naRef value)
581 const char* fieldName = naStr_data(field);
582 FlightPlan* fp = (FlightPlan*) g;
584 if (!strcmp(fieldName, "id")) {
585 if (!naIsString(value)) naRuntimeError(c, "flightplan.id must be a string");
586 fp->setIdent(naStr_data(value));
587 } else if (!strcmp(fieldName, "current")) {
588 int index = value.num;
589 if ((index < 0) || (index >= fp->numLegs())) {
592 fp->setCurrentIndex(index);
593 } else if (!strcmp(fieldName, "departure")) {
594 FGAirport* apt = airportGhost(value);
596 fp->setDeparture(apt);
600 FGRunway* rwy = runwayGhost(value);
602 fp->setDeparture(rwy);
606 if (naIsNil(value)) {
607 fp->setDeparture(static_cast<FGAirport*>(NULL));
611 naRuntimeError(c, "bad argument type setting departure");
612 } else if (!strcmp(fieldName, "destination")) {
613 FGAirport* apt = airportGhost(value);
615 fp->setDestination(apt);
619 FGRunway* rwy = runwayGhost(value);
621 fp->setDestination(rwy);
625 naRuntimeError(c, "bad argument type setting destination");
626 } else if (!strcmp(fieldName, "departure_runway")) {
627 FGRunway* rwy = runwayGhost(value);
629 fp->setDeparture(rwy);
633 naRuntimeError(c, "bad argument type setting departure runway");
634 } else if (!strcmp(fieldName, "destination_runway")) {
635 FGRunway* rwy = runwayGhost(value);
637 fp->setDestination(rwy);
641 naRuntimeError(c, "bad argument type setting destination runway");
642 } else if (!strcmp(fieldName, "sid")) {
643 Procedure* proc = procedureGhost(value);
644 if (proc && (proc->type() == PROCEDURE_SID)) {
645 fp->setSID((flightgear::SID*) proc);
648 // allow a SID transition to be set, implicitly include the SID itself
649 if (proc && (proc->type() == PROCEDURE_TRANSITION)) {
650 fp->setSID((Transition*) proc);
654 if (naIsString(value)) {
655 FGAirport* apt = fp->departureAirport();
656 fp->setSID(apt->findSIDWithIdent(naStr_data(value)));
660 naRuntimeError(c, "bad argument type setting SID");
661 } else if (!strcmp(fieldName, "star")) {
662 Procedure* proc = procedureGhost(value);
663 if (proc && (proc->type() == PROCEDURE_STAR)) {
664 fp->setSTAR((STAR*) proc);
668 if (proc && (proc->type() == PROCEDURE_TRANSITION)) {
669 fp->setSTAR((Transition*) proc);
673 if (naIsString(value)) {
674 FGAirport* apt = fp->destinationAirport();
675 fp->setSTAR(apt->findSTARWithIdent(naStr_data(value)));
679 naRuntimeError(c, "bad argument type setting STAR");
680 } else if (!strcmp(fieldName, "approach")) {
681 Procedure* proc = procedureGhost(value);
682 if (proc && Approach::isApproach(proc->type())) {
683 fp->setApproach((Approach*) proc);
687 if (naIsString(value)) {
688 FGAirport* apt = fp->destinationAirport();
689 fp->setApproach(apt->findApproachWithIdent(naStr_data(value)));
693 naRuntimeError(c, "bad argument type setting approach");
698 static naRef procedureTpType(naContext c, ProcedureType ty)
701 case PROCEDURE_SID: return stringToNasal(c, "sid");
702 case PROCEDURE_STAR: return stringToNasal(c, "star");
703 case PROCEDURE_APPROACH_VOR:
704 case PROCEDURE_APPROACH_ILS:
705 case PROCEDURE_APPROACH_RNAV:
706 case PROCEDURE_APPROACH_NDB:
707 return stringToNasal(c, "IAP");
713 static naRef procedureRadioType(naContext c, ProcedureType ty)
716 case PROCEDURE_APPROACH_VOR: return stringToNasal(c, "VOR");
717 case PROCEDURE_APPROACH_ILS: return stringToNasal(c, "ILS");
718 case PROCEDURE_APPROACH_RNAV: return stringToNasal(c, "RNAV");
719 case PROCEDURE_APPROACH_NDB: return stringToNasal(c, "NDB");
725 static const char* procedureGhostGetMember(naContext c, void* g, naRef field, naRef* out)
727 const char* fieldName = naStr_data(field);
728 Procedure* proc = (Procedure*) g;
730 if (!strcmp(fieldName, "parents")) {
731 *out = naNewVector(c);
732 naVec_append(*out, procedurePrototype);
733 } else if (!strcmp(fieldName, "id")) *out = stringToNasal(c, proc->ident());
734 else if (!strcmp(fieldName, "airport")) *out = ghostForAirport(c, proc->airport());
735 else if (!strcmp(fieldName, "tp_type")) *out = procedureTpType(c, proc->type());
736 else if (!strcmp(fieldName, "radio")) *out = procedureRadioType(c, proc->type());
737 else if (!strcmp(fieldName, "runways")) {
738 *out = naNewVector(c);
739 BOOST_FOREACH(FGRunwayRef rwy, proc->runways()) {
740 naVec_append(*out, stringToNasal(c, rwy->ident()));
742 } else if (!strcmp(fieldName, "transitions")) {
743 if ((proc->type() != PROCEDURE_SID) && (proc->type() != PROCEDURE_STAR)) {
748 ArrivalDeparture* ad = static_cast<ArrivalDeparture*>(proc);
749 *out = naNewVector(c);
750 BOOST_FOREACH(std::string id, ad->transitionIdents()) {
751 naVec_append(*out, stringToNasal(c, id));
760 static const char* runwayGhostGetMember(naContext c, void* g, naRef field, naRef* out)
762 const char* fieldName = naStr_data(field);
763 FGRunwayBase* base = (FGRunwayBase*) g;
765 if (!strcmp(fieldName, "id")) *out = stringToNasal(c, base->ident());
766 else if (!strcmp(fieldName, "lat")) *out = naNum(base->latitude());
767 else if (!strcmp(fieldName, "lon")) *out = naNum(base->longitude());
768 else if (!strcmp(fieldName, "heading")) *out = naNum(base->headingDeg());
769 else if (!strcmp(fieldName, "length")) *out = naNum(base->lengthM());
770 else if (!strcmp(fieldName, "width")) *out = naNum(base->widthM());
771 else if (!strcmp(fieldName, "surface")) *out = naNum(base->surface());
772 else if (base->type() == FGRunwayBase::RUNWAY) {
773 FGRunway* rwy = (FGRunway*) g;
774 if (!strcmp(fieldName, "threshold")) *out = naNum(rwy->displacedThresholdM());
775 else if (!strcmp(fieldName, "stopway")) *out = naNum(rwy->stopwayM());
776 else if (!strcmp(fieldName, "reciprocal")) {
777 *out = ghostForRunway(c, rwy->reciprocalRunway());
778 } else if (!strcmp(fieldName, "ils_frequency_mhz")) {
779 *out = rwy->ILS() ? naNum(rwy->ILS()->get_freq() / 100.0) : naNil();
780 } else if (!strcmp(fieldName, "ils")) {
781 *out = ghostForNavaid(c, rwy->ILS());
792 static const char* navaidGhostGetMember(naContext c, void* g, naRef field, naRef* out)
794 const char* fieldName = naStr_data(field);
795 FGNavRecord* nav = (FGNavRecord*) g;
797 if (!strcmp(fieldName, "id")) *out = stringToNasal(c, nav->ident());
798 else if (!strcmp(fieldName, "name")) *out = stringToNasal(c, nav->name());
799 else if (!strcmp(fieldName, "lat")) *out = naNum(nav->get_lat());
800 else if (!strcmp(fieldName, "lon")) *out = naNum(nav->get_lon());
801 else if (!strcmp(fieldName, "elevation")) {
802 *out = naNum(nav->get_elev_ft() * SG_FEET_TO_METER);
803 } else if (!strcmp(fieldName, "type")) {
804 *out = stringToNasal(c, nav->nameForType(nav->type()));
805 } else if (!strcmp(fieldName, "frequency")) {
806 *out = naNum(nav->get_freq());
807 } else if (!strcmp(fieldName, "range_nm")) {
808 *out = naNum(nav->get_range());
809 } else if (!strcmp(fieldName, "course")) {
810 if ((nav->type() == FGPositioned::ILS) || (nav->type() == FGPositioned::LOC)) {
811 double radial = nav->get_multiuse();
812 SG_NORMALIZE_RANGE(radial, 0.0, 360.0);
813 *out = naNum(radial);
824 static const char* fixGhostGetMember(naContext c, void* g, naRef field, naRef* out)
826 const char* fieldName = naStr_data(field);
827 FGFix* fix = (FGFix*) g;
829 if (!strcmp(fieldName, "id")) *out = stringToNasal(c, fix->ident());
830 else if (!strcmp(fieldName, "lat")) *out = naNum(fix->get_lat());
831 else if (!strcmp(fieldName, "lon")) *out = naNum(fix->get_lon());
839 static bool hashIsCoord(naRef h)
841 naRef parents = naHash_cget(h, (char*) "parents");
842 if (!naIsVector(parents)) {
846 return naEqual(naVec_get(parents, 0), geoCoordClass) != 0;
849 bool geodFromHash(naRef ref, SGGeod& result)
851 if (!naIsHash(ref)) {
856 // check for manual latitude / longitude names
857 naRef lat = naHash_cget(ref, (char*) "lat");
858 naRef lon = naHash_cget(ref, (char*) "lon");
859 if (naIsNum(lat) && naIsNum(lon)) {
860 result = SGGeod::fromDeg(naNumValue(lon).num, naNumValue(lat).num);
864 if (hashIsCoord(ref)) {
865 naRef lat = naHash_cget(ref, (char*) "_lat");
866 naRef lon = naHash_cget(ref, (char*) "_lon");
867 if (naIsNum(lat) && naIsNum(lon)) {
868 result = SGGeod::fromRad(naNumValue(lon).num, naNumValue(lat).num);
873 // check for any synonyms?
874 // latitude + longitude?
879 static int geodFromArgs(naRef* args, int offset, int argc, SGGeod& result)
881 if (offset >= argc) {
885 if (naIsGhost(args[offset])) {
886 naGhostType* gt = naGhost_type(args[offset]);
887 if (gt == &AirportGhostType) {
888 result = airportGhost(args[offset])->geod();
892 if (gt == &NavaidGhostType) {
893 result = navaidGhost(args[offset])->geod();
897 if (gt == &RunwayGhostType) {
898 result = runwayGhost(args[offset])->geod();
902 if (gt == &TaxiwayGhostType) {
903 result = taxiwayGhost(args[offset])->geod();
907 if (gt == &FixGhostType) {
908 result = fixGhost(args[offset])->geod();
912 if (gt == &WayptGhostType) {
913 result = wayptGhost(args[offset])->position();
918 if (geodFromHash(args[offset], result)) {
922 if (((argc - offset) >= 2) && naIsNum(args[offset]) && naIsNum(args[offset + 1])) {
923 double lat = naNumValue(args[0]).num,
924 lon = naNumValue(args[1]).num;
925 result = SGGeod::fromDeg(lon, lat);
932 // Convert a cartesian point to a geodetic lat/lon/altitude.
933 static naRef f_carttogeod(naContext c, naRef me, int argc, naRef* args)
935 double lat, lon, alt, xyz[3];
936 if(argc != 3) naRuntimeError(c, "carttogeod() expects 3 arguments");
937 for(int i=0; i<3; i++)
938 xyz[i] = naNumValue(args[i]).num;
939 sgCartToGeod(xyz, &lat, &lon, &alt);
940 lat *= SG_RADIANS_TO_DEGREES;
941 lon *= SG_RADIANS_TO_DEGREES;
942 naRef vec = naNewVector(c);
943 naVec_append(vec, naNum(lat));
944 naVec_append(vec, naNum(lon));
945 naVec_append(vec, naNum(alt));
949 // Convert a geodetic lat/lon/altitude to a cartesian point.
950 static naRef f_geodtocart(naContext c, naRef me, int argc, naRef* args)
952 if(argc != 3) naRuntimeError(c, "geodtocart() expects 3 arguments");
953 double lat = naNumValue(args[0]).num * SG_DEGREES_TO_RADIANS;
954 double lon = naNumValue(args[1]).num * SG_DEGREES_TO_RADIANS;
955 double alt = naNumValue(args[2]).num;
957 sgGeodToCart(lat, lon, alt, xyz);
958 naRef vec = naNewVector(c);
959 naVec_append(vec, naNum(xyz[0]));
960 naVec_append(vec, naNum(xyz[1]));
961 naVec_append(vec, naNum(xyz[2]));
965 // For given geodetic point return array with elevation, and a material data
966 // hash, or nil if there's no information available (tile not loaded). If
967 // information about the material isn't available, then nil is returned instead
969 static naRef f_geodinfo(naContext c, naRef me, int argc, naRef* args)
971 #define HASHSET(s,l,n) naHash_set(matdata, naStr_fromdata(naNewString(c),s,l),n)
972 if(argc < 2 || argc > 3)
973 naRuntimeError(c, "geodinfo() expects 2 or 3 arguments: lat, lon [, maxalt]");
974 double lat = naNumValue(args[0]).num;
975 double lon = naNumValue(args[1]).num;
976 double elev = argc == 3 ? naNumValue(args[2]).num : 10000;
977 const simgear::BVHMaterial *material;
978 SGGeod geod = SGGeod::fromDegM(lon, lat, elev);
979 if(!globals->get_scenery()->get_elevation_m(geod, elev, &material))
981 const SGMaterial *mat = dynamic_cast<const SGMaterial *>(material);
982 naRef vec = naNewVector(c);
983 naVec_append(vec, naNum(elev));
984 naRef matdata = naNil();
986 matdata = naNewHash(c);
987 naRef names = naNewVector(c);
988 BOOST_FOREACH(const std::string& n, mat->get_names())
989 naVec_append(names, stringToNasal(c, n));
991 HASHSET("names", 5, names);
992 HASHSET("solid", 5, naNum(mat->get_solid()));
993 HASHSET("friction_factor", 15, naNum(mat->get_friction_factor()));
994 HASHSET("rolling_friction", 16, naNum(mat->get_rolling_friction()));
995 HASHSET("load_resistance", 15, naNum(mat->get_load_resistance()));
996 HASHSET("bumpiness", 9, naNum(mat->get_bumpiness()));
997 HASHSET("light_coverage", 14, naNum(mat->get_light_coverage()));
999 naVec_append(vec, matdata);
1005 // Returns data hash for particular or nearest airport of a <type>, or nil
1008 // airportinfo(<id>); e.g. "KSFO"
1009 // airportinfo(<type>); type := ("airport"|"seaport"|"heliport")
1010 // airportinfo() same as airportinfo("airport")
1011 // airportinfo(<lat>, <lon> [, <type>]);
1012 static naRef f_airportinfo(naContext c, naRef me, int argc, naRef* args)
1014 SGGeod pos = globals->get_aircraft_position();
1015 FGAirport* apt = NULL;
1017 if(argc >= 2 && naIsNum(args[0]) && naIsNum(args[1])) {
1018 pos = SGGeod::fromDeg(args[1].num, args[0].num);
1023 double maxRange = 10000.0; // expose this? or pick a smaller value?
1025 FGAirport::TypeRunwayFilter filter; // defaults to airports only
1028 // fall through and use AIRPORT
1029 } else if(argc == 1 && naIsString(args[0])) {
1030 if (filter.fromTypeString(naStr_data(args[0]))) {
1033 // user provided an <id>, hopefully
1034 apt = FGAirport::findByIdent(naStr_data(args[0]));
1036 // return nil here, but don't raise a runtime error; this is a
1037 // legitamate way to validate an ICAO code, for example in a
1038 // dialog box or similar.
1043 naRuntimeError(c, "airportinfo() with invalid function arguments");
1048 apt = FGAirport::findClosest(pos, maxRange, &filter);
1049 if(!apt) return naNil();
1052 return ghostForAirport(c, apt);
1055 static naRef f_findAirportsWithinRange(naContext c, naRef me, int argc, naRef* args)
1058 SGGeod pos = globals->get_aircraft_position();
1059 argOffset += geodFromArgs(args, 0, argc, pos);
1061 if (!naIsNum(args[argOffset])) {
1062 naRuntimeError(c, "findAirportsWithinRange expected range (in nm) as arg %d", argOffset);
1065 FGAirport::TypeRunwayFilter filter; // defaults to airports only
1066 double rangeNm = args[argOffset++].num;
1067 if (argOffset < argc) {
1068 filter.fromTypeString(naStr_data(args[argOffset++]));
1071 naRef r = naNewVector(c);
1073 FGPositionedList apts = FGPositioned::findWithinRange(pos, rangeNm, &filter);
1074 FGPositioned::sortByRange(apts, pos);
1076 BOOST_FOREACH(FGPositionedRef a, apts) {
1077 FGAirport* apt = (FGAirport*) a.get();
1078 naVec_append(r, ghostForAirport(c, apt));
1084 static naRef f_findAirportsByICAO(naContext c, naRef me, int argc, naRef* args)
1086 if (!naIsString(args[0])) {
1087 naRuntimeError(c, "findAirportsByICAO expects string as arg 0");
1091 std::string prefix(naStr_data(args[argOffset++]));
1092 FGAirport::TypeRunwayFilter filter; // defaults to airports only
1093 if (argOffset < argc) {
1094 filter.fromTypeString(naStr_data(args[argOffset++]));
1097 naRef r = naNewVector(c);
1099 FGPositionedList apts = FGPositioned::findAllWithIdent(prefix, &filter, false);
1101 BOOST_FOREACH(FGPositionedRef a, apts) {
1102 FGAirport* apt = (FGAirport*) a.get();
1103 naVec_append(r, ghostForAirport(c, apt));
1109 static naRef f_airport_tower(naContext c, naRef me, int argc, naRef* args)
1111 FGAirport* apt = airportGhost(me);
1113 naRuntimeError(c, "airport.tower called on non-airport object");
1116 // build a hash for the tower position
1117 SGGeod towerLoc = apt->getTowerLocation();
1118 naRef tower = naNewHash(c);
1119 hashset(c, tower, "lat", naNum(towerLoc.getLatitudeDeg()));
1120 hashset(c, tower, "lon", naNum(towerLoc.getLongitudeDeg()));
1121 hashset(c, tower, "elevation", naNum(towerLoc.getElevationM()));
1125 static naRef f_airport_comms(naContext c, naRef me, int argc, naRef* args)
1127 FGAirport* apt = airportGhost(me);
1129 naRuntimeError(c, "airport.comms called on non-airport object");
1131 naRef comms = naNewVector(c);
1133 // if we have an explicit type, return a simple vector of frequencies
1134 if (argc > 0 && !naIsString(args[0])) {
1135 naRuntimeError(c, "airport.comms argument must be a frequency type name");
1139 std::string commName = naStr_data(args[0]);
1140 FGPositioned::Type commType = FGPositioned::typeFromName(commName);
1142 BOOST_FOREACH(flightgear::CommStation* comm, apt->commStationsOfType(commType)) {
1143 naVec_append(comms, naNum(comm->freqMHz()));
1146 // otherwise return a vector of hashes, one for each comm station.
1147 BOOST_FOREACH(flightgear::CommStation* comm, apt->commStations()) {
1148 naRef commHash = naNewHash(c);
1149 hashset(c, commHash, "frequency", naNum(comm->freqMHz()));
1150 hashset(c, commHash, "ident", stringToNasal(c, comm->ident()));
1151 naVec_append(comms, commHash);
1158 static naRef f_airport_runway(naContext c, naRef me, int argc, naRef* args)
1160 FGAirport* apt = airportGhost(me);
1162 naRuntimeError(c, "airport.runway called on non-airport object");
1165 if ((argc < 1) || !naIsString(args[0])) {
1166 naRuntimeError(c, "airport.runway expects a runway ident argument");
1169 std::string ident(naStr_data(args[0]));
1170 boost::to_upper(ident);
1172 if (apt->hasRunwayWithIdent(ident)) {
1173 return ghostForRunway(c, apt->getRunwayByIdent(ident));
1174 } else if (apt->hasHelipadWithIdent(ident)) {
1175 return ghostForHelipad(c, apt->getHelipadByIdent(ident));
1180 static naRef f_airport_runwaysWithoutReciprocals(naContext c, naRef me, int argc, naRef* args)
1182 FGAirport* apt = airportGhost(me);
1184 naRuntimeError(c, "airport.runwaysWithoutReciprocals called on non-airport object");
1187 FGRunwayList rwylist(apt->getRunwaysWithoutReciprocals());
1188 naRef runways = naNewVector(c);
1189 for (unsigned int r=0; r<rwylist.size(); ++r) {
1190 FGRunway* rwy(rwylist[r]);
1191 naVec_append(runways, ghostForRunway(c, apt->getRunwayByIdent(rwy->ident())));
1196 static naRef f_airport_sids(naContext c, naRef me, int argc, naRef* args)
1198 FGAirport* apt = airportGhost(me);
1200 naRuntimeError(c, "airport.sids called on non-airport object");
1203 naRef sids = naNewVector(c);
1205 FGRunway* rwy = NULL;
1206 if (argc > 0 && naIsString(args[0])) {
1207 if (!apt->hasRunwayWithIdent(naStr_data(args[0]))) {
1211 rwy = apt->getRunwayByIdent(naStr_data(args[0]));
1212 } else if (argc > 0) {
1213 rwy = runwayGhost(args[0]);
1217 BOOST_FOREACH(flightgear::SID* sid, rwy->getSIDs()) {
1218 naRef procId = stringToNasal(c, sid->ident());
1219 naVec_append(sids, procId);
1222 for (unsigned int s=0; s<apt->numSIDs(); ++s) {
1223 flightgear::SID* sid = apt->getSIDByIndex(s);
1224 naRef procId = stringToNasal(c, sid->ident());
1225 naVec_append(sids, procId);
1232 static naRef f_airport_stars(naContext c, naRef me, int argc, naRef* args)
1234 FGAirport* apt = airportGhost(me);
1236 naRuntimeError(c, "airport.stars called on non-airport object");
1239 naRef stars = naNewVector(c);
1241 FGRunway* rwy = NULL;
1242 if (argc > 0 && naIsString(args[0])) {
1243 if (!apt->hasRunwayWithIdent(naStr_data(args[0]))) {
1247 rwy = apt->getRunwayByIdent(naStr_data(args[0]));
1248 } else if (argc > 0) {
1249 rwy = runwayGhost(args[0]);
1253 BOOST_FOREACH(flightgear::STAR* s, rwy->getSTARs()) {
1254 naRef procId = stringToNasal(c, s->ident());
1255 naVec_append(stars, procId);
1258 for (unsigned int s=0; s<apt->numSTARs(); ++s) {
1259 flightgear::STAR* star = apt->getSTARByIndex(s);
1260 naRef procId = stringToNasal(c, star->ident());
1261 naVec_append(stars, procId);
1268 static naRef f_airport_approaches(naContext c, naRef me, int argc, naRef* args)
1270 FGAirport* apt = airportGhost(me);
1272 naRuntimeError(c, "airport.getApproachList called on non-airport object");
1275 naRef approaches = naNewVector(c);
1277 ProcedureType ty = PROCEDURE_INVALID;
1278 if ((argc > 1) && naIsString(args[1])) {
1279 std::string u(naStr_data(args[1]));
1281 if (u == "NDB") ty = PROCEDURE_APPROACH_NDB;
1282 if (u == "VOR") ty = PROCEDURE_APPROACH_VOR;
1283 if (u == "ILS") ty = PROCEDURE_APPROACH_ILS;
1284 if (u == "RNAV") ty = PROCEDURE_APPROACH_RNAV;
1287 FGRunway* rwy = NULL;
1288 if (argc > 0 && (rwy = runwayGhost(args[0]))) {
1290 } else if (argc > 0 && naIsString(args[0])) {
1291 if (!apt->hasRunwayWithIdent(naStr_data(args[0]))) {
1295 rwy = apt->getRunwayByIdent(naStr_data(args[0]));
1299 BOOST_FOREACH(Approach* s, rwy->getApproaches()) {
1300 if ((ty != PROCEDURE_INVALID) && (s->type() != ty)) {
1304 naRef procId = stringToNasal(c, s->ident());
1305 naVec_append(approaches, procId);
1308 // no runway specified, report them all
1309 for (unsigned int s=0; s<apt->numApproaches(); ++s) {
1310 Approach* app = apt->getApproachByIndex(s);
1311 if ((ty != PROCEDURE_INVALID) && (app->type() != ty)) {
1315 naRef procId = stringToNasal(c, app->ident());
1316 naVec_append(approaches, procId);
1323 static naRef f_airport_parking(naContext c, naRef me, int argc, naRef* args)
1325 FGAirport* apt = airportGhost(me);
1327 naRuntimeError(c, "airport.parking called on non-airport object");
1330 naRef r = naNewVector(c);
1332 bool onlyAvailable = false;
1334 if (argc > 0 && naIsString(args[0])) {
1335 type = naStr_data(args[0]);
1338 if ((argc > 1) && naIsNum(args[1])) {
1339 onlyAvailable = (args[1].num != 0.0);
1342 FGAirportDynamics* dynamics = apt->getDynamics();
1343 PositionedIDVec parkings = flightgear::NavDataCache::instance()->airportItemsOfType(apt->guid(),
1344 FGPositioned::PARKING);
1346 BOOST_FOREACH(PositionedID parking, parkings) {
1347 // filter out based on availability and type
1348 if (onlyAvailable && !dynamics->isParkingAvailable(parking)) {
1352 FGParking* park = dynamics->getParking(parking);
1353 if (!type.empty() && (park->getType() != type)) {
1357 const SGGeod& parkLoc = park->geod();
1358 naRef ph = naNewHash(c);
1359 hashset(c, ph, "name", stringToNasal(c, park->getName()));
1360 hashset(c, ph, "lat", naNum(parkLoc.getLatitudeDeg()));
1361 hashset(c, ph, "lon", naNum(parkLoc.getLongitudeDeg()));
1362 hashset(c, ph, "elevation", naNum(parkLoc.getElevationM()));
1363 naVec_append(r, ph);
1369 static naRef f_airport_getSid(naContext c, naRef me, int argc, naRef* args)
1371 FGAirport* apt = airportGhost(me);
1373 naRuntimeError(c, "airport.getSid called on non-airport object");
1376 if ((argc != 1) || !naIsString(args[0])) {
1377 naRuntimeError(c, "airport.getSid passed invalid argument");
1380 std::string ident = naStr_data(args[0]);
1381 return ghostForProcedure(c, apt->findSIDWithIdent(ident));
1384 static naRef f_airport_getStar(naContext c, naRef me, int argc, naRef* args)
1386 FGAirport* apt = airportGhost(me);
1388 naRuntimeError(c, "airport.getStar called on non-airport object");
1391 if ((argc != 1) || !naIsString(args[0])) {
1392 naRuntimeError(c, "airport.getStar passed invalid argument");
1395 std::string ident = naStr_data(args[0]);
1396 return ghostForProcedure(c, apt->findSTARWithIdent(ident));
1399 static naRef f_airport_getApproach(naContext c, naRef me, int argc, naRef* args)
1401 FGAirport* apt = airportGhost(me);
1403 naRuntimeError(c, "airport.getIAP called on non-airport object");
1406 if ((argc != 1) || !naIsString(args[0])) {
1407 naRuntimeError(c, "airport.getIAP passed invalid argument");
1410 std::string ident = naStr_data(args[0]);
1411 return ghostForProcedure(c, apt->findApproachWithIdent(ident));
1414 static naRef f_airport_findBestRunway(naContext c, naRef me, int argc, naRef* args)
1416 FGAirport* apt = airportGhost(me);
1418 naRuntimeError(c, "findBestRunway called on non-airport object");
1422 if (!geodFromArgs(args, 0, argc, pos)) {
1423 naRuntimeError(c, "findBestRunway must be passed a position");
1426 return ghostForRunway(c, apt->findBestRunwayForPos(pos));
1429 static naRef f_airport_toString(naContext c, naRef me, int argc, naRef* args)
1431 FGAirport* apt = airportGhost(me);
1433 naRuntimeError(c, "airport.tostring called on non-airport object");
1436 return stringToNasal(c, "an airport " + apt->ident());
1439 // Returns vector of data hash for navaid of a <type>, nil on error
1440 // navaids sorted by ascending distance
1441 // navinfo([<lat>,<lon>],[<type>],[<id>])
1442 // lat/lon (numeric): use latitude/longitude instead of ac position
1443 // type: ("fix"|"vor"|"ndb"|"ils"|"dme"|"tacan"|"any")
1444 // id: (partial) id of the fix
1446 // navinfo("vor") returns all vors
1447 // navinfo("HAM") return all navaids who's name start with "HAM"
1448 // navinfo("vor", "HAM") return all vor who's name start with "HAM"
1449 //navinfo(34,48,"vor","HAM") return all vor who's name start with "HAM"
1450 // sorted by distance relative to lat=34, lon=48
1451 static naRef f_navinfo(naContext c, naRef me, int argc, naRef* args)
1455 if(argc >= 2 && naIsNum(args[0]) && naIsNum(args[1])) {
1456 pos = SGGeod::fromDeg(args[1].num, args[0].num);
1460 pos = globals->get_aircraft_position();
1463 FGPositioned::Type type = FGPositioned::INVALID;
1464 nav_list_type navlist;
1465 const char * id = "";
1467 if(argc > 0 && naIsString(args[0])) {
1468 const char *s = naStr_data(args[0]);
1469 if(!strcmp(s, "any")) type = FGPositioned::INVALID;
1470 else if(!strcmp(s, "fix")) type = FGPositioned::FIX;
1471 else if(!strcmp(s, "vor")) type = FGPositioned::VOR;
1472 else if(!strcmp(s, "ndb")) type = FGPositioned::NDB;
1473 else if(!strcmp(s, "ils")) type = FGPositioned::ILS;
1474 else if(!strcmp(s, "dme")) type = FGPositioned::DME;
1475 else if(!strcmp(s, "tacan")) type = FGPositioned::TACAN;
1476 else id = s; // this is an id
1481 if(argc > 0 && naIsString(args[0])) {
1483 naRuntimeError(c, "navinfo() called with navaid id");
1486 id = naStr_data(args[0]);
1492 naRuntimeError(c, "navinfo() called with too many arguments");
1496 FGNavList::TypeFilter filter(type);
1497 navlist = FGNavList::findByIdentAndFreq( pos, id, 0.0, &filter );
1499 naRef reply = naNewVector(c);
1500 for( nav_list_type::const_iterator it = navlist.begin(); it != navlist.end(); ++it ) {
1501 naVec_append( reply, ghostForNavaid(c, *it) );
1506 static naRef f_findNavaidsWithinRange(naContext c, naRef me, int argc, naRef* args)
1509 SGGeod pos = globals->get_aircraft_position();
1510 argOffset += geodFromArgs(args, 0, argc, pos);
1512 if (!naIsNum(args[argOffset])) {
1513 naRuntimeError(c, "findNavaidsWithinRange expected range (in nm) as arg %d", argOffset);
1516 FGPositioned::Type type = FGPositioned::INVALID;
1517 double rangeNm = args[argOffset++].num;
1518 if (argOffset < argc) {
1519 type = FGPositioned::typeFromName(naStr_data(args[argOffset]));
1522 naRef r = naNewVector(c);
1523 FGNavList::TypeFilter filter(type);
1524 FGPositionedList navs = FGPositioned::findWithinRange(pos, rangeNm, &filter);
1525 FGPositioned::sortByRange(navs, pos);
1527 BOOST_FOREACH(FGPositionedRef a, navs) {
1528 FGNavRecord* nav = (FGNavRecord*) a.get();
1529 naVec_append(r, ghostForNavaid(c, nav));
1535 static naRef f_findNavaidByFrequency(naContext c, naRef me, int argc, naRef* args)
1538 SGGeod pos = globals->get_aircraft_position();
1539 argOffset += geodFromArgs(args, 0, argc, pos);
1541 if (!naIsNum(args[argOffset])) {
1542 naRuntimeError(c, "findNavaidByFrequency expectes frequency (in Mhz) as arg %d", argOffset);
1545 FGPositioned::Type type = FGPositioned::INVALID;
1546 double freqMhz = args[argOffset++].num;
1547 if (argOffset < argc) {
1548 type = FGPositioned::typeFromName(naStr_data(args[argOffset]));
1551 FGNavList::TypeFilter filter(type);
1552 nav_list_type navs = FGNavList::findAllByFreq(freqMhz, pos, &filter);
1557 return ghostForNavaid(c, navs.front().ptr());
1560 static naRef f_findNavaidsByFrequency(naContext c, naRef me, int argc, naRef* args)
1563 SGGeod pos = globals->get_aircraft_position();
1564 argOffset += geodFromArgs(args, 0, argc, pos);
1566 if (!naIsNum(args[argOffset])) {
1567 naRuntimeError(c, "findNavaidsByFrequency expectes frequency (in Mhz) as arg %d", argOffset);
1570 FGPositioned::Type type = FGPositioned::INVALID;
1571 double freqMhz = args[argOffset++].num;
1572 if (argOffset < argc) {
1573 type = FGPositioned::typeFromName(naStr_data(args[argOffset]));
1576 naRef r = naNewVector(c);
1578 FGNavList::TypeFilter filter(type);
1579 nav_list_type navs = FGNavList::findAllByFreq(freqMhz, pos, &filter);
1581 BOOST_FOREACH(nav_rec_ptr a, navs) {
1582 naVec_append(r, ghostForNavaid(c, a.ptr()));
1588 static naRef f_findNavaidsByIdent(naContext c, naRef me, int argc, naRef* args)
1591 SGGeod pos = globals->get_aircraft_position();
1592 argOffset += geodFromArgs(args, 0, argc, pos);
1594 if (!naIsString(args[argOffset])) {
1595 naRuntimeError(c, "findNavaidsByIdent expectes ident string as arg %d", argOffset);
1598 FGPositioned::Type type = FGPositioned::INVALID;
1599 std::string ident = naStr_data(args[argOffset++]);
1600 if (argOffset < argc) {
1601 type = FGPositioned::typeFromName(naStr_data(args[argOffset]));
1604 FGNavList::TypeFilter filter(type);
1605 naRef r = naNewVector(c);
1606 nav_list_type navs = FGNavList::findByIdentAndFreq(pos, ident, 0.0, &filter);
1608 BOOST_FOREACH(nav_rec_ptr a, navs) {
1609 naVec_append(r, ghostForNavaid(c, a.ptr()));
1615 static naRef f_findFixesByIdent(naContext c, naRef me, int argc, naRef* args)
1618 SGGeod pos = globals->get_aircraft_position();
1619 argOffset += geodFromArgs(args, 0, argc, pos);
1621 if (!naIsString(args[argOffset])) {
1622 naRuntimeError(c, "findFixesByIdent expectes ident string as arg %d", argOffset);
1625 std::string ident(naStr_data(args[argOffset]));
1626 naRef r = naNewVector(c);
1628 FGPositioned::TypeFilter filter(FGPositioned::FIX);
1629 FGPositionedList fixes = FGPositioned::findAllWithIdent(ident, &filter);
1630 FGPositioned::sortByRange(fixes, pos);
1632 BOOST_FOREACH(FGPositionedRef f, fixes) {
1633 naVec_append(r, ghostForFix(c, (FGFix*) f.ptr()));
1639 // Convert a cartesian point to a geodetic lat/lon/altitude.
1640 static naRef f_magvar(naContext c, naRef me, int argc, naRef* args)
1642 SGGeod pos = globals->get_aircraft_position();
1644 // fine, use aircraft position
1645 } else if (geodFromArgs(args, 0, argc, pos)) {
1648 naRuntimeError(c, "magvar() expects no arguments, a positioned hash or lat,lon pair");
1651 double jd = globals->get_time_params()->getJD();
1652 double magvarDeg = sgGetMagVar(pos, jd) * SG_RADIANS_TO_DEGREES;
1653 return naNum(magvarDeg);
1656 static naRef f_courseAndDistance(naContext c, naRef me, int argc, naRef* args)
1658 SGGeod from = globals->get_aircraft_position(), to, p;
1659 int argOffset = geodFromArgs(args, 0, argc, p);
1660 if (geodFromArgs(args, argOffset, argc, to)) {
1661 from = p; // we parsed both FROM and TO args, so first was from
1663 to = p; // only parsed one arg, so FROM is current
1666 if (argOffset == 0) {
1667 naRuntimeError(c, "invalid arguments to courseAndDistance");
1670 double course, course2, d;
1671 SGGeodesy::inverse(from, to, course, course2, d);
1673 naRef result = naNewVector(c);
1674 naVec_append(result, naNum(course));
1675 naVec_append(result, naNum(d * SG_METER_TO_NM));
1679 static naRef f_greatCircleMove(naContext c, naRef me, int argc, naRef* args)
1681 SGGeod from = globals->get_aircraft_position(), to;
1684 // complication - don't inerpret two doubles (as the only args)
1685 // as a lat,lon pair - only do so if we have at least three args.
1687 argOffset = geodFromArgs(args, 0, argc, from);
1690 if ((argOffset + 1) >= argc) {
1691 naRuntimeError(c, "isufficent arguments to greatCircleMove");
1694 if (!naIsNum(args[argOffset]) || !naIsNum(args[argOffset+1])) {
1695 naRuntimeError(c, "invalid arguments %d and %d to greatCircleMove",
1696 argOffset, argOffset + 1);
1699 double course = args[argOffset].num, course2;
1700 double distanceNm = args[argOffset + 1].num;
1701 SGGeodesy::direct(from, course, distanceNm * SG_NM_TO_METER, to, course2);
1704 naRef coord = naNewHash(c);
1705 hashset(c, coord, "lat", naNum(to.getLatitudeDeg()));
1706 hashset(c, coord, "lon", naNum(to.getLongitudeDeg()));
1710 static naRef f_tilePath(naContext c, naRef me, int argc, naRef* args)
1712 SGGeod pos = globals->get_aircraft_position();
1713 geodFromArgs(args, 0, argc, pos);
1715 return stringToNasal(c, b.gen_base_path());
1718 static naRef f_tileIndex(naContext c, naRef me, int argc, naRef* args)
1720 SGGeod pos = globals->get_aircraft_position();
1721 geodFromArgs(args, 0, argc, pos);
1723 return naNum(b.gen_index());
1726 static naRef f_route(naContext c, naRef me, int argc, naRef* args)
1729 FGRouteMgr* rm = static_cast<FGRouteMgr*>(globals->get_subsystem("route-manager"));
1730 return ghostForFlightPlan(c, rm->flightPlan());
1733 if ((argc > 0) && naIsString(args[0])) {
1734 flightgear::FlightPlan* fp = new flightgear::FlightPlan;
1735 SGPath path(naStr_data(args[0]));
1736 if (!path.exists()) {
1737 naRuntimeError(c, "flightplan, no file at path %s", path.c_str());
1740 if (!fp->load(path)) {
1741 SG_LOG(SG_NASAL, SG_WARN, "failed to load flight-plan from " << path);
1746 return ghostForFlightPlan(c, fp);
1749 naRuntimeError(c, "bad arguments to flightplan()");
1753 class NasalFPDelegate : public FlightPlan::Delegate
1756 NasalFPDelegate(FlightPlan* fp, FGNasalSys* sys, naRef ins) :
1761 _gcSaveKey = _nasal->gcSave(ins);
1764 virtual ~NasalFPDelegate()
1766 _nasal->gcRelease(_gcSaveKey);
1769 virtual void departureChanged()
1771 callDelegateMethod("departureChanged");
1774 virtual void arrivalChanged()
1776 callDelegateMethod("arrivalChanged");
1779 virtual void waypointsChanged()
1781 callDelegateMethod("waypointsChanged");
1784 virtual void currentWaypointChanged()
1786 callDelegateMethod("currentWaypointChanged");
1789 virtual void cleared()
1791 callDelegateMethod("cleared");
1794 virtual void endOfFlightPlan()
1796 callDelegateMethod("endOfFlightPlan");
1800 void callDelegateMethod(const char* method)
1803 naContext ctx = naNewContext();
1805 if (naMember_cget(ctx, _instance, method, &f) != 0) {
1807 arg[0] = ghostForFlightPlan(ctx, _plan);
1808 _nasal->callMethod(f, _instance, 1, arg, naNil());
1821 class NasalFPDelegateFactory : public FlightPlan::DelegateFactory
1824 NasalFPDelegateFactory(naRef code)
1826 _nasal = (FGNasalSys*) globals->get_subsystem("nasal");
1828 _gcSaveKey = _nasal->gcSave(_func);
1831 virtual ~NasalFPDelegateFactory()
1833 _nasal->gcRelease(_gcSaveKey);
1836 virtual FlightPlan::Delegate* createFlightPlanDelegate(FlightPlan* fp)
1839 naContext ctx = naNewContext();
1840 args[0] = ghostForFlightPlan(ctx, fp);
1841 naRef instance = _nasal->call(_func, 1, args, naNil());
1843 FlightPlan::Delegate* result = NULL;
1844 if (!naIsNil(instance)) {
1845 // will GC-save instance
1846 result = new NasalFPDelegate(fp, _nasal, instance);
1858 static std::vector<NasalFPDelegateFactory*> static_nasalDelegateFactories;
1860 void shutdownNasalPositioned()
1862 std::vector<NasalFPDelegateFactory*>::iterator it;
1863 for (it = static_nasalDelegateFactories.begin();
1864 it != static_nasalDelegateFactories.end(); ++it)
1866 FlightPlan::unregisterDelegateFactory(*it);
1869 static_nasalDelegateFactories.clear();
1872 static naRef f_registerFPDelegate(naContext c, naRef me, int argc, naRef* args)
1874 if ((argc < 1) || !naIsFunc(args[0])) {
1875 naRuntimeError(c, "non-function argument to registerFlightPlanDelegate");
1878 NasalFPDelegateFactory* factory = new NasalFPDelegateFactory(args[0]);
1879 FlightPlan::registerDelegateFactory(factory);
1880 static_nasalDelegateFactories.push_back(factory);
1884 static WayptRef wayptFromArg(naRef arg)
1886 WayptRef r = wayptGhost(arg);
1891 FGPositioned* pos = positionedGhost(arg);
1893 // let's check if the arg is hash, coudl extra a geod and hence build
1894 // a simple waypoint
1899 // special-case for runways
1900 if (pos->type() == FGPositioned::RUNWAY) {
1901 return new RunwayWaypt((FGRunway*) pos, NULL);
1904 return new NavaidWaypoint(pos, NULL);
1907 static naRef convertWayptVecToNasal(naContext c, const WayptVec& wps)
1909 naRef result = naNewVector(c);
1910 BOOST_FOREACH(WayptRef wpt, wps) {
1911 naVec_append(result, ghostForWaypt(c, wpt.get()));
1916 static naRef f_airwaySearch(naContext c, naRef me, int argc, naRef* args)
1919 naRuntimeError(c, "airwaysSearch needs at least two arguments");
1922 WayptRef start = wayptFromArg(args[0]),
1923 end = wayptFromArg(args[1]);
1925 if (!start || !end) {
1926 SG_LOG(SG_NASAL, SG_WARN, "airwaysSearch: start or end points are invalid");
1930 bool highLevel = true;
1931 if ((argc > 2) && naIsString(args[2])) {
1932 if (!strcmp(naStr_data(args[2]), "lowlevel")) {
1939 Airway::highLevel()->route(start, end, route);
1941 Airway::lowLevel()->route(start, end, route);
1944 return convertWayptVecToNasal(c, route);
1947 static naRef f_createWP(naContext c, naRef me, int argc, naRef* args)
1950 int argOffset = geodFromArgs(args, 0, argc, pos);
1952 if (((argc - argOffset) < 1) || !naIsString(args[argOffset])) {
1953 naRuntimeError(c, "createWP: no identifier supplied");
1956 std::string ident = naStr_data(args[argOffset++]);
1957 WayptRef wpt = new BasicWaypt(pos, ident, NULL);
1959 // set waypt flags - approach, departure, pseudo, etc
1960 if (argc > argOffset) {
1961 WayptFlag f = wayptFlagFromString(naStr_data(args[argOffset++]));
1963 naRuntimeError(c, "createWP: bad waypoint role");
1969 return ghostForWaypt(c, wpt);
1972 static naRef f_createWPFrom(naContext c, naRef me, int argc, naRef* args)
1975 naRuntimeError(c, "createWPFrom: need at least one argument");
1978 FGPositioned* positioned = positionedGhost(args[0]);
1980 naRuntimeError(c, "createWPFrom: couldn;t convert arg[0] to FGPositioned");
1984 if (positioned->type() == FGPositioned::RUNWAY) {
1985 wpt = new RunwayWaypt((FGRunway*) positioned, NULL);
1987 wpt = new NavaidWaypoint(positioned, NULL);
1990 // set waypt flags - approach, departure, pseudo, etc
1992 WayptFlag f = wayptFlagFromString(naStr_data(args[1]));
1994 naRuntimeError(c, "createWPFrom: bad waypoint role");
1999 return ghostForWaypt(c, wpt);
2002 static naRef f_flightplan_getWP(naContext c, naRef me, int argc, naRef* args)
2004 FlightPlan* fp = flightplanGhost(me);
2006 naRuntimeError(c, "flightplan.getWP called on non-flightplan object");
2011 index = fp->currentIndex();
2013 index = (int) naNumValue(args[0]).num;
2016 if ((index < 0) || (index >= fp->numLegs())) {
2020 return ghostForLeg(c, fp->legAtIndex(index));
2023 static naRef f_flightplan_currentWP(naContext c, naRef me, int argc, naRef* args)
2025 FlightPlan* fp = flightplanGhost(me);
2027 naRuntimeError(c, "flightplan.currentWP called on non-flightplan object");
2029 return ghostForLeg(c, fp->currentLeg());
2032 static naRef f_flightplan_nextWP(naContext c, naRef me, int argc, naRef* args)
2034 FlightPlan* fp = flightplanGhost(me);
2036 naRuntimeError(c, "flightplan.nextWP called on non-flightplan object");
2038 return ghostForLeg(c, fp->nextLeg());
2041 static naRef f_flightplan_numWaypoints(naContext c, naRef me, int argc, naRef* args)
2043 FlightPlan* fp = flightplanGhost(me);
2045 naRuntimeError(c, "flightplan.numWaypoints called on non-flightplan object");
2047 return naNum(fp->numLegs());
2050 static naRef f_flightplan_appendWP(naContext c, naRef me, int argc, naRef* args)
2052 FlightPlan* fp = flightplanGhost(me);
2054 naRuntimeError(c, "flightplan.appendWP called on non-flightplan object");
2057 WayptRef wp = wayptGhost(args[0]);
2058 int index = fp->numLegs();
2059 fp->insertWayptAtIndex(wp.get(), index);
2060 return naNum(index);
2063 static naRef f_flightplan_insertWP(naContext c, naRef me, int argc, naRef* args)
2065 FlightPlan* fp = flightplanGhost(me);
2067 naRuntimeError(c, "flightplan.insertWP called on non-flightplan object");
2070 WayptRef wp = wayptGhost(args[0]);
2071 int index = -1; // append
2072 if ((argc > 1) && naIsNum(args[1])) {
2073 index = (int) args[1].num;
2076 fp->insertWayptAtIndex(wp.get(), index);
2080 static naRef f_flightplan_insertWPAfter(naContext c, naRef me, int argc, naRef* args)
2082 FlightPlan* fp = flightplanGhost(me);
2084 naRuntimeError(c, "flightplan.insertWPAfter called on non-flightplan object");
2087 WayptRef wp = wayptGhost(args[0]);
2088 int index = -1; // append
2089 if ((argc > 1) && naIsNum(args[1])) {
2090 index = (int) args[1].num;
2093 fp->insertWayptAtIndex(wp.get(), index + 1);
2097 static naRef f_flightplan_insertWaypoints(naContext c, naRef me, int argc, naRef* args)
2099 FlightPlan* fp = flightplanGhost(me);
2101 naRuntimeError(c, "flightplan.insertWaypoints called on non-flightplan object");
2105 if (!naIsVector(args[0])) {
2106 naRuntimeError(c, "flightplan.insertWaypoints expects vector as first arg");
2109 int count = naVec_size(args[0]);
2110 for (int i=0; i<count; ++i) {
2111 Waypt* wp = wayptGhost(naVec_get(args[0], i));
2117 int index = -1; // append
2118 if ((argc > 1) && naIsNum(args[1])) {
2119 index = (int) args[1].num;
2122 fp->insertWayptsAtIndex(wps, index);
2126 static naRef f_flightplan_deleteWP(naContext c, naRef me, int argc, naRef* args)
2128 FlightPlan* fp = flightplanGhost(me);
2130 naRuntimeError(c, "flightplan.deleteWP called on non-flightplan object");
2133 if ((argc < 1) || !naIsNum(args[0])) {
2134 naRuntimeError(c, "bad argument to flightplan.deleteWP");
2137 int index = (int) args[0].num;
2138 fp->deleteIndex(index);
2142 static naRef f_flightplan_clearPlan(naContext c, naRef me, int argc, naRef* args)
2144 FlightPlan* fp = flightplanGhost(me);
2146 naRuntimeError(c, "flightplan.clearPlan called on non-flightplan object");
2153 static naRef f_flightplan_clearWPType(naContext c, naRef me, int argc, naRef* args)
2155 FlightPlan* fp = flightplanGhost(me);
2157 naRuntimeError(c, "flightplan.clearWPType called on non-flightplan object");
2161 naRuntimeError(c, "insufficent args to flightplan.clearWPType");
2164 WayptFlag flag = wayptFlagFromString(naStr_data(args[0]));
2166 naRuntimeError(c, "clearWPType: bad waypoint role");
2169 fp->clearWayptsWithFlag(flag);
2173 static naRef f_flightplan_clone(naContext c, naRef me, int argc, naRef* args)
2175 FlightPlan* fp = flightplanGhost(me);
2177 naRuntimeError(c, "flightplan.clone called on non-flightplan object");
2180 return ghostForFlightPlan(c, fp->clone());
2183 static naRef f_flightplan_pathGeod(naContext c, naRef me, int argc, naRef* args)
2185 FlightPlan* fp = flightplanGhost(me);
2187 naRuntimeError(c, "flightplan.clone called on non-flightplan object");
2190 if ((argc < 1) || !naIsNum(args[0])) {
2191 naRuntimeError(c, "bad argument to flightplan.pathGeod");
2194 if ((argc > 1) && !naIsNum(args[1])) {
2195 naRuntimeError(c, "bad argument to flightplan.pathGeod");
2198 int index = (int) args[0].num;
2199 double offset = (argc > 1) ? args[1].num : 0.0;
2200 naRef result = naNewHash(c);
2201 SGGeod g = fp->pointAlongRoute(index, offset);
2202 hashset(c, result, "lat", naNum(g.getLatitudeDeg()));
2203 hashset(c, result, "lon", naNum(g.getLongitudeDeg()));
2207 static naRef f_flightplan_finish(naContext c, naRef me, int argc, naRef* args)
2209 FlightPlan* fp = flightplanGhost(me);
2211 naRuntimeError(c, "flightplan.finish called on non-flightplan object");
2218 static naRef f_flightplan_indexOfWp(naContext c, naRef me, int argc, naRef* args)
2220 FlightPlan* fp = flightplanGhost(me);
2222 naRuntimeError(c, "flightplan.indexOfWP called on non-flightplan object");
2225 FGPositioned* positioned = positionedGhost(args[0]);
2227 return naNum(fp->findWayptIndex(positioned));
2231 int argOffset = geodFromArgs(args, 0, argc, pos);
2232 if (argOffset > 0) {
2233 return naNum(fp->findWayptIndex(pos));
2239 static naRef f_leg_setSpeed(naContext c, naRef me, int argc, naRef* args)
2241 FlightPlan::Leg* leg = fpLegGhost(me);
2243 naRuntimeError(c, "leg.setSpeed called on non-flightplan-leg object");
2247 if ((argc < 2) || !convertToNum(args[0], speed))
2248 naRuntimeError(c, "bad arguments to setSpeed");
2250 RouteRestriction rr = routeRestrictionFromString(naStr_data(args[1]));
2251 leg->setSpeed(rr, speed);
2256 static naRef f_leg_setAltitude(naContext c, naRef me, int argc, naRef* args)
2258 FlightPlan::Leg* leg = fpLegGhost(me);
2260 naRuntimeError(c, "leg.setAltitude called on non-flightplan-leg object");
2264 if ((argc < 2) || !convertToNum(args[0], alt))
2265 naRuntimeError(c, "bad arguments to leg.setAltitude");
2267 RouteRestriction rr = routeRestrictionFromString(naStr_data(args[1]));
2268 leg->setAltitude(rr, alt);
2273 static naRef f_leg_path(naContext c, naRef me, int argc, naRef* args)
2275 FlightPlan::Leg* leg = fpLegGhost(me);
2277 naRuntimeError(c, "leg.setAltitude called on non-flightplan-leg object");
2280 RoutePath path(leg->owner());
2281 SGGeodVec gv(path.pathForIndex(leg->index()));
2283 naRef result = naNewVector(c);
2284 BOOST_FOREACH(SGGeod p, gv) {
2285 // construct a geo.Coord!
2286 naRef coord = naNewHash(c);
2287 hashset(c, coord, "lat", naNum(p.getLatitudeDeg()));
2288 hashset(c, coord, "lon", naNum(p.getLongitudeDeg()));
2289 naVec_append(result, coord);
2295 static naRef f_leg_courseAndDistanceFrom(naContext c, naRef me, int argc, naRef* args)
2297 FlightPlan::Leg* leg = fpLegGhost(me);
2299 naRuntimeError(c, "leg.courseAndDistanceFrom called on non-flightplan-leg object");
2303 geodFromArgs(args, 0, argc, pos);
2305 RoutePath path(leg->owner());
2306 SGGeod wpPos = path.positionForIndex(leg->index());
2307 double courseDeg, az2, distanceM;
2308 SGGeodesy::inverse(pos, wpPos, courseDeg, az2, distanceM);
2310 naRef result = naNewVector(c);
2311 naVec_append(result, naNum(courseDeg));
2312 naVec_append(result, naNum(distanceM * SG_METER_TO_NM));
2316 static naRef f_waypoint_navaid(naContext c, naRef me, int argc, naRef* args)
2318 flightgear::Waypt* w = wayptGhost(me);
2320 naRuntimeError(c, "waypoint.navaid called on non-waypoint object");
2323 FGPositioned* pos = w->source();
2328 switch (pos->type()) {
2329 case FGPositioned::VOR:
2330 case FGPositioned::NDB:
2331 case FGPositioned::ILS:
2332 case FGPositioned::LOC:
2333 case FGPositioned::GS:
2334 case FGPositioned::DME:
2335 case FGPositioned::TACAN: {
2336 FGNavRecord* nav = (FGNavRecord*) pos;
2337 return ghostForNavaid(c, nav);
2345 static naRef f_waypoint_airport(naContext c, naRef me, int argc, naRef* args)
2347 flightgear::Waypt* w = wayptGhost(me);
2349 naRuntimeError(c, "waypoint.navaid called on non-waypoint object");
2352 FGPositioned* pos = w->source();
2353 if (!pos || FGAirport::isAirportType(pos)) {
2357 return ghostForAirport(c, (FGAirport*) pos);
2360 static naRef f_waypoint_runway(naContext c, naRef me, int argc, naRef* args)
2362 flightgear::Waypt* w = wayptGhost(me);
2364 naRuntimeError(c, "waypoint.navaid called on non-waypoint object");
2367 FGPositioned* pos = w->source();
2368 if (!pos || (pos->type() != FGPositioned::RUNWAY)) {
2372 return ghostForRunway(c, (FGRunway*) pos);
2375 static naRef f_procedure_transition(naContext c, naRef me, int argc, naRef* args)
2377 Procedure* proc = procedureGhost(me);
2379 naRuntimeError(c, "procedure.transition called on non-procedure object");
2382 if ((proc->type() != PROCEDURE_SID) && (proc->type() != PROCEDURE_STAR)) {
2383 naRuntimeError(c, "procedure.transition called on non-SID or -STAR");
2386 ArrivalDeparture* ad = (ArrivalDeparture*) proc;
2387 Transition* trans = ad->findTransitionByName(naStr_data(args[0]));
2389 return ghostForProcedure(c, trans);
2392 static naRef f_procedure_route(naContext c, naRef me, int argc, naRef* args)
2394 Procedure* proc = procedureGhost(me);
2396 naRuntimeError(c, "procedure.route called on non-procedure object");
2399 // wrapping up tow different routines here - approach routing from the IAF
2400 // to the associated runway, and SID/STAR routing via an enroute transition
2401 // and possibly a runway transition or not.
2402 if (Approach::isApproach(proc->type())) {
2405 iaf = wayptFromArg(args[0]);
2409 Approach* app = (Approach*) proc;
2410 if (!app->route(iaf, r)) {
2411 SG_LOG(SG_NASAL, SG_WARN, "procedure.route failed for Approach somehow");
2415 return convertWayptVecToNasal(c, r);
2416 } else if ((proc->type() != PROCEDURE_SID) && (proc->type() != PROCEDURE_STAR)) {
2417 naRuntimeError(c, "procedure.route called on unsuitable procedure type");
2421 FGRunway* rwy = runwayGhost(args[0]);
2422 if (rwy) ++argOffset;
2424 ArrivalDeparture* ad = (ArrivalDeparture*) proc;
2425 Transition* trans = NULL;
2426 if (argOffset < argc) {
2427 trans = (Transition*) procedureGhost(args[argOffset]);
2430 // note either runway or trans may be NULL - that's ok
2432 if (!ad->route(rwy, trans, r)) {
2433 SG_LOG(SG_NASAL, SG_WARN, "prcoedure.route failed for ArrvialDeparture somehow");
2437 return convertWayptVecToNasal(c, r);
2441 // Table of extension functions. Terminate with zeros.
2442 static struct { const char* name; naCFunction func; } funcs[] = {
2443 { "carttogeod", f_carttogeod },
2444 { "geodtocart", f_geodtocart },
2445 { "geodinfo", f_geodinfo },
2446 { "airportinfo", f_airportinfo },
2447 { "findAirportsWithinRange", f_findAirportsWithinRange },
2448 { "findAirportsByICAO", f_findAirportsByICAO },
2449 { "navinfo", f_navinfo },
2450 { "findNavaidsWithinRange", f_findNavaidsWithinRange },
2451 { "findNavaidByFrequency", f_findNavaidByFrequency },
2452 { "findNavaidsByFrequency", f_findNavaidsByFrequency },
2453 { "findNavaidsByID", f_findNavaidsByIdent },
2454 { "findFixesByID", f_findFixesByIdent },
2455 { "flightplan", f_route },
2456 { "registerFlightPlanDelegate", f_registerFPDelegate },
2457 { "createWP", f_createWP },
2458 { "createWPFrom", f_createWPFrom },
2459 { "airwaysRoute", f_airwaySearch },
2460 { "magvar", f_magvar },
2461 { "courseAndDistance", f_courseAndDistance },
2462 { "greatCircleMove", f_greatCircleMove },
2463 { "tileIndex", f_tileIndex },
2464 { "tilePath", f_tilePath },
2469 naRef initNasalPositioned(naRef globals, naContext c)
2471 airportPrototype = naNewHash(c);
2472 naSave(c, airportPrototype);
2474 hashset(c, airportPrototype, "runway", naNewFunc(c, naNewCCode(c, f_airport_runway)));
2475 hashset(c, airportPrototype, "runwaysWithoutReciprocals", naNewFunc(c, naNewCCode(c, f_airport_runwaysWithoutReciprocals)));
2476 hashset(c, airportPrototype, "helipad", naNewFunc(c, naNewCCode(c, f_airport_runway)));
2477 hashset(c, airportPrototype, "tower", naNewFunc(c, naNewCCode(c, f_airport_tower)));
2478 hashset(c, airportPrototype, "comms", naNewFunc(c, naNewCCode(c, f_airport_comms)));
2479 hashset(c, airportPrototype, "sids", naNewFunc(c, naNewCCode(c, f_airport_sids)));
2480 hashset(c, airportPrototype, "stars", naNewFunc(c, naNewCCode(c, f_airport_stars)));
2481 hashset(c, airportPrototype, "getApproachList", naNewFunc(c, naNewCCode(c, f_airport_approaches)));
2482 hashset(c, airportPrototype, "parking", naNewFunc(c, naNewCCode(c, f_airport_parking)));
2483 hashset(c, airportPrototype, "getSid", naNewFunc(c, naNewCCode(c, f_airport_getSid)));
2484 hashset(c, airportPrototype, "getStar", naNewFunc(c, naNewCCode(c, f_airport_getStar)));
2485 hashset(c, airportPrototype, "getIAP", naNewFunc(c, naNewCCode(c, f_airport_getApproach)));
2486 hashset(c, airportPrototype, "findBestRunwayForPos", naNewFunc(c, naNewCCode(c, f_airport_findBestRunway)));
2487 hashset(c, airportPrototype, "tostring", naNewFunc(c, naNewCCode(c, f_airport_toString)));
2489 flightplanPrototype = naNewHash(c);
2490 naSave(c, flightplanPrototype);
2492 hashset(c, flightplanPrototype, "getWP", naNewFunc(c, naNewCCode(c, f_flightplan_getWP)));
2493 hashset(c, flightplanPrototype, "currentWP", naNewFunc(c, naNewCCode(c, f_flightplan_currentWP)));
2494 hashset(c, flightplanPrototype, "nextWP", naNewFunc(c, naNewCCode(c, f_flightplan_nextWP)));
2495 hashset(c, flightplanPrototype, "getPlanSize", naNewFunc(c, naNewCCode(c, f_flightplan_numWaypoints)));
2496 hashset(c, flightplanPrototype, "appendWP", naNewFunc(c, naNewCCode(c, f_flightplan_appendWP)));
2497 hashset(c, flightplanPrototype, "insertWP", naNewFunc(c, naNewCCode(c, f_flightplan_insertWP)));
2498 hashset(c, flightplanPrototype, "deleteWP", naNewFunc(c, naNewCCode(c, f_flightplan_deleteWP)));
2499 hashset(c, flightplanPrototype, "insertWPAfter", naNewFunc(c, naNewCCode(c, f_flightplan_insertWPAfter)));
2500 hashset(c, flightplanPrototype, "insertWaypoints", naNewFunc(c, naNewCCode(c, f_flightplan_insertWaypoints)));
2501 hashset(c, flightplanPrototype, "cleanPlan", naNewFunc(c, naNewCCode(c, f_flightplan_clearPlan)));
2502 hashset(c, flightplanPrototype, "clearWPType", naNewFunc(c, naNewCCode(c, f_flightplan_clearWPType)));
2503 hashset(c, flightplanPrototype, "clone", naNewFunc(c, naNewCCode(c, f_flightplan_clone)));
2504 hashset(c, flightplanPrototype, "pathGeod", naNewFunc(c, naNewCCode(c, f_flightplan_pathGeod)));
2505 hashset(c, flightplanPrototype, "finish", naNewFunc(c, naNewCCode(c, f_flightplan_finish)));
2506 hashset(c, flightplanPrototype, "indexOfWP", naNewFunc(c, naNewCCode(c, f_flightplan_indexOfWp)));
2508 waypointPrototype = naNewHash(c);
2509 naSave(c, waypointPrototype);
2511 hashset(c, waypointPrototype, "navaid", naNewFunc(c, naNewCCode(c, f_waypoint_navaid)));
2512 hashset(c, waypointPrototype, "runway", naNewFunc(c, naNewCCode(c, f_waypoint_runway)));
2513 hashset(c, waypointPrototype, "airport", naNewFunc(c, naNewCCode(c, f_waypoint_airport)));
2515 procedurePrototype = naNewHash(c);
2516 naSave(c, procedurePrototype);
2517 hashset(c, procedurePrototype, "transition", naNewFunc(c, naNewCCode(c, f_procedure_transition)));
2518 hashset(c, procedurePrototype, "route", naNewFunc(c, naNewCCode(c, f_procedure_route)));
2520 fpLegPrototype = naNewHash(c);
2521 naSave(c, fpLegPrototype);
2522 hashset(c, fpLegPrototype, "setSpeed", naNewFunc(c, naNewCCode(c, f_leg_setSpeed)));
2523 hashset(c, fpLegPrototype, "setAltitude", naNewFunc(c, naNewCCode(c, f_leg_setAltitude)));
2524 hashset(c, fpLegPrototype, "path", naNewFunc(c, naNewCCode(c, f_leg_path)));
2525 hashset(c, fpLegPrototype, "courseAndDistanceFrom", naNewFunc(c, naNewCCode(c, f_leg_courseAndDistanceFrom)));
2527 for(int i=0; funcs[i].name; i++) {
2528 hashset(c, globals, funcs[i].name,
2529 naNewFunc(c, naNewCCode(c, funcs[i].func)));
2535 void postinitNasalPositioned(naRef globals, naContext c)
2537 naRef geoModule = naHash_cget(globals, (char*) "geo");
2538 if (naIsNil(geoModule)) {
2539 SG_LOG(SG_GENERAL, SG_WARN, "postinitNasalPositioned: geo.nas not loaded");
2543 geoCoordClass = naHash_cget(geoModule, (char*) "Coord");