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);
466 } else if (!strcmp(fieldName, "fly_type")) {
467 if (!naIsString(value)) naRuntimeError(c, "fly_type must be a string");
468 bool flyOver = (strcmp(naStr_data(value), "flyOver") == 0);
469 wpt->setFlag(WPT_OVERFLIGHT, flyOver);
473 static const char* wayptGhostGetMember(naContext c, void* g, naRef field, naRef* out)
475 const char* fieldName = naStr_data(field);
476 Waypt* wpt = (flightgear::Waypt*) g;
477 return waypointCommonGetMember(c, wpt, fieldName, out);
480 static RouteRestriction routeRestrictionFromString(const char* s)
484 if (u == "computed") return RESTRICT_COMPUTED;
485 if (u == "at") return RESTRICT_AT;
486 if (u == "mach") return SPEED_RESTRICT_MACH;
487 if (u == "computed-mach") return SPEED_COMPUTED_MACH;
488 if (u == "delete") return RESTRICT_DELETE;
489 return RESTRICT_NONE;
492 naRef routeRestrictionToNasal(naContext c, RouteRestriction rr)
495 case RESTRICT_NONE: return naNil();
496 case RESTRICT_AT: return stringToNasal(c, "at");
497 case RESTRICT_ABOVE: return stringToNasal(c, "above");
498 case RESTRICT_BELOW: return stringToNasal(c, "below");
499 case SPEED_RESTRICT_MACH: return stringToNasal(c, "mach");
500 case RESTRICT_COMPUTED: return stringToNasal(c, "computed");
501 case SPEED_COMPUTED_MACH: return stringToNasal(c, "computed-mach");
502 case RESTRICT_DELETE: return stringToNasal(c, "delete");
508 static const char* legGhostGetMember(naContext c, void* g, naRef field, naRef* out)
510 const char* fieldName = naStr_data(field);
511 FlightPlan::Leg* leg = (FlightPlan::Leg*) g;
512 Waypt* wpt = leg->waypoint();
514 if (!strcmp(fieldName, "parents")) {
515 *out = naNewVector(c);
516 naVec_append(*out, fpLegPrototype);
517 naVec_append(*out, waypointPrototype);
518 } else if (!strcmp(fieldName, "index")) {
519 *out = naNum(leg->index());
520 } else if (!strcmp(fieldName, "alt_cstr")) {
521 *out = naNum(leg->altitudeFt());
522 } else if (!strcmp(fieldName, "alt_cstr_type")) {
523 *out = routeRestrictionToNasal(c, leg->altitudeRestriction());
524 } else if (!strcmp(fieldName, "speed_cstr")) {
525 double s = isMachRestrict(leg->speedRestriction()) ? leg->speedMach() : leg->speedKts();
527 } else if (!strcmp(fieldName, "speed_cstr_type")) {
528 *out = routeRestrictionToNasal(c, leg->speedRestriction());
529 } else if (!strcmp(fieldName, "leg_distance")) {
530 *out = naNum(leg->distanceNm());
531 } else if (!strcmp(fieldName, "leg_bearing")) {
532 *out = naNum(leg->courseDeg());
533 } else if (!strcmp(fieldName, "distance_along_route")) {
534 *out = naNum(leg->distanceAlongRoute());
535 } else { // check for fields defined on the underlying waypoint
536 return waypointCommonGetMember(c, wpt, fieldName, out);
539 return ""; // success
542 static void waypointGhostSetMember(naContext c, void* g, naRef field, naRef value)
544 const char* fieldName = naStr_data(field);
545 Waypt* wpt = (Waypt*) g;
546 waypointCommonSetMember(c, wpt, fieldName, value);
549 static void legGhostSetMember(naContext c, void* g, naRef field, naRef value)
551 const char* fieldName = naStr_data(field);
552 FlightPlan::Leg* leg = (FlightPlan::Leg*) g;
554 waypointCommonSetMember(c, leg->waypoint(), fieldName, value);
557 static const char* flightplanGhostGetMember(naContext c, void* g, naRef field, naRef* out)
559 const char* fieldName = naStr_data(field);
560 FlightPlan* fp = (FlightPlan*) g;
562 if (!strcmp(fieldName, "parents")) {
563 *out = naNewVector(c);
564 naVec_append(*out, flightplanPrototype);
565 } else if (!strcmp(fieldName, "id")) *out = stringToNasal(c, fp->ident());
566 else if (!strcmp(fieldName, "departure")) *out = ghostForAirport(c, fp->departureAirport());
567 else if (!strcmp(fieldName, "destination")) *out = ghostForAirport(c, fp->destinationAirport());
568 else if (!strcmp(fieldName, "departure_runway")) *out = ghostForRunway(c, fp->departureRunway());
569 else if (!strcmp(fieldName, "destination_runway")) *out = ghostForRunway(c, fp->destinationRunway());
570 else if (!strcmp(fieldName, "sid")) *out = ghostForProcedure(c, fp->sid());
571 else if (!strcmp(fieldName, "sid_trans")) *out = ghostForProcedure(c, fp->sidTransition());
572 else if (!strcmp(fieldName, "star")) *out = ghostForProcedure(c, fp->star());
573 else if (!strcmp(fieldName, "star_trans")) *out = ghostForProcedure(c, fp->starTransition());
574 else if (!strcmp(fieldName, "approach")) *out = ghostForProcedure(c, fp->approach());
575 else if (!strcmp(fieldName, "current")) *out = naNum(fp->currentIndex());
576 else if (!strcmp(fieldName, "aircraftCategory")) *out = stringToNasal(c, fp->icaoAircraftCategory());
577 else if (!strcmp(fieldName, "followLegTrackToFix")) *out = naNum(fp->followLegTrackToFixes());
585 static void flightplanGhostSetMember(naContext c, void* g, naRef field, naRef value)
587 const char* fieldName = naStr_data(field);
588 FlightPlan* fp = (FlightPlan*) g;
590 if (!strcmp(fieldName, "id")) {
591 if (!naIsString(value)) naRuntimeError(c, "flightplan.id must be a string");
592 fp->setIdent(naStr_data(value));
593 } else if (!strcmp(fieldName, "current")) {
594 int index = value.num;
595 if ((index < 0) || (index >= fp->numLegs())) {
598 fp->setCurrentIndex(index);
599 } else if (!strcmp(fieldName, "departure")) {
600 FGAirport* apt = airportGhost(value);
602 fp->setDeparture(apt);
606 FGRunway* rwy = runwayGhost(value);
608 fp->setDeparture(rwy);
612 if (naIsNil(value)) {
613 fp->setDeparture(static_cast<FGAirport*>(NULL));
617 naRuntimeError(c, "bad argument type setting departure");
618 } else if (!strcmp(fieldName, "destination")) {
619 FGAirport* apt = airportGhost(value);
621 fp->setDestination(apt);
625 FGRunway* rwy = runwayGhost(value);
627 fp->setDestination(rwy);
631 naRuntimeError(c, "bad argument type setting destination");
632 } else if (!strcmp(fieldName, "departure_runway")) {
633 FGRunway* rwy = runwayGhost(value);
635 fp->setDeparture(rwy);
639 naRuntimeError(c, "bad argument type setting departure runway");
640 } else if (!strcmp(fieldName, "destination_runway")) {
641 FGRunway* rwy = runwayGhost(value);
643 fp->setDestination(rwy);
647 naRuntimeError(c, "bad argument type setting destination runway");
648 } else if (!strcmp(fieldName, "sid")) {
649 Procedure* proc = procedureGhost(value);
650 if (proc && (proc->type() == PROCEDURE_SID)) {
651 fp->setSID((flightgear::SID*) proc);
654 // allow a SID transition to be set, implicitly include the SID itself
655 if (proc && (proc->type() == PROCEDURE_TRANSITION)) {
656 fp->setSID((Transition*) proc);
660 if (naIsString(value)) {
661 FGAirport* apt = fp->departureAirport();
662 fp->setSID(apt->findSIDWithIdent(naStr_data(value)));
666 naRuntimeError(c, "bad argument type setting SID");
667 } else if (!strcmp(fieldName, "star")) {
668 Procedure* proc = procedureGhost(value);
669 if (proc && (proc->type() == PROCEDURE_STAR)) {
670 fp->setSTAR((STAR*) proc);
674 if (proc && (proc->type() == PROCEDURE_TRANSITION)) {
675 fp->setSTAR((Transition*) proc);
679 if (naIsString(value)) {
680 FGAirport* apt = fp->destinationAirport();
681 fp->setSTAR(apt->findSTARWithIdent(naStr_data(value)));
685 naRuntimeError(c, "bad argument type setting STAR");
686 } else if (!strcmp(fieldName, "approach")) {
687 Procedure* proc = procedureGhost(value);
688 if (proc && Approach::isApproach(proc->type())) {
689 fp->setApproach((Approach*) proc);
693 if (naIsString(value)) {
694 FGAirport* apt = fp->destinationAirport();
695 fp->setApproach(apt->findApproachWithIdent(naStr_data(value)));
699 naRuntimeError(c, "bad argument type setting approach");
700 } else if (!strcmp(fieldName, "aircraftCategory")) {
701 if (!naIsString(value)) naRuntimeError(c, "aircraftCategory must be a string");
702 fp->setIcaoAircraftCategory(naStr_data(value));
703 } else if (!strcmp(fieldName, "followLegTrackToFix")) {
704 int b = (int) value.num;
705 fp->setFollowLegTrackToFixes(b);
710 static naRef procedureTpType(naContext c, ProcedureType ty)
713 case PROCEDURE_SID: return stringToNasal(c, "sid");
714 case PROCEDURE_STAR: return stringToNasal(c, "star");
715 case PROCEDURE_APPROACH_VOR:
716 case PROCEDURE_APPROACH_ILS:
717 case PROCEDURE_APPROACH_RNAV:
718 case PROCEDURE_APPROACH_NDB:
719 return stringToNasal(c, "IAP");
725 static naRef procedureRadioType(naContext c, ProcedureType ty)
728 case PROCEDURE_APPROACH_VOR: return stringToNasal(c, "VOR");
729 case PROCEDURE_APPROACH_ILS: return stringToNasal(c, "ILS");
730 case PROCEDURE_APPROACH_RNAV: return stringToNasal(c, "RNAV");
731 case PROCEDURE_APPROACH_NDB: return stringToNasal(c, "NDB");
737 static const char* procedureGhostGetMember(naContext c, void* g, naRef field, naRef* out)
739 const char* fieldName = naStr_data(field);
740 Procedure* proc = (Procedure*) g;
742 if (!strcmp(fieldName, "parents")) {
743 *out = naNewVector(c);
744 naVec_append(*out, procedurePrototype);
745 } else if (!strcmp(fieldName, "id")) *out = stringToNasal(c, proc->ident());
746 else if (!strcmp(fieldName, "airport")) *out = ghostForAirport(c, proc->airport());
747 else if (!strcmp(fieldName, "tp_type")) *out = procedureTpType(c, proc->type());
748 else if (!strcmp(fieldName, "radio")) *out = procedureRadioType(c, proc->type());
749 else if (!strcmp(fieldName, "runways")) {
750 *out = naNewVector(c);
751 BOOST_FOREACH(FGRunwayRef rwy, proc->runways()) {
752 naVec_append(*out, stringToNasal(c, rwy->ident()));
754 } else if (!strcmp(fieldName, "transitions")) {
755 if ((proc->type() != PROCEDURE_SID) && (proc->type() != PROCEDURE_STAR)) {
760 ArrivalDeparture* ad = static_cast<ArrivalDeparture*>(proc);
761 *out = naNewVector(c);
762 BOOST_FOREACH(std::string id, ad->transitionIdents()) {
763 naVec_append(*out, stringToNasal(c, id));
772 static const char* runwayGhostGetMember(naContext c, void* g, naRef field, naRef* out)
774 const char* fieldName = naStr_data(field);
775 FGRunwayBase* base = (FGRunwayBase*) g;
777 if (!strcmp(fieldName, "id")) *out = stringToNasal(c, base->ident());
778 else if (!strcmp(fieldName, "lat")) *out = naNum(base->latitude());
779 else if (!strcmp(fieldName, "lon")) *out = naNum(base->longitude());
780 else if (!strcmp(fieldName, "heading")) *out = naNum(base->headingDeg());
781 else if (!strcmp(fieldName, "length")) *out = naNum(base->lengthM());
782 else if (!strcmp(fieldName, "width")) *out = naNum(base->widthM());
783 else if (!strcmp(fieldName, "surface")) *out = naNum(base->surface());
784 else if (base->type() == FGRunwayBase::RUNWAY) {
785 FGRunway* rwy = (FGRunway*) g;
786 if (!strcmp(fieldName, "threshold")) *out = naNum(rwy->displacedThresholdM());
787 else if (!strcmp(fieldName, "stopway")) *out = naNum(rwy->stopwayM());
788 else if (!strcmp(fieldName, "reciprocal")) {
789 *out = ghostForRunway(c, rwy->reciprocalRunway());
790 } else if (!strcmp(fieldName, "ils_frequency_mhz")) {
791 *out = rwy->ILS() ? naNum(rwy->ILS()->get_freq() / 100.0) : naNil();
792 } else if (!strcmp(fieldName, "ils")) {
793 *out = ghostForNavaid(c, rwy->ILS());
804 static const char* navaidGhostGetMember(naContext c, void* g, naRef field, naRef* out)
806 const char* fieldName = naStr_data(field);
807 FGNavRecord* nav = (FGNavRecord*) g;
809 if (!strcmp(fieldName, "id")) *out = stringToNasal(c, nav->ident());
810 else if (!strcmp(fieldName, "name")) *out = stringToNasal(c, nav->name());
811 else if (!strcmp(fieldName, "lat")) *out = naNum(nav->get_lat());
812 else if (!strcmp(fieldName, "lon")) *out = naNum(nav->get_lon());
813 else if (!strcmp(fieldName, "elevation")) {
814 *out = naNum(nav->get_elev_ft() * SG_FEET_TO_METER);
815 } else if (!strcmp(fieldName, "type")) {
816 *out = stringToNasal(c, nav->nameForType(nav->type()));
817 } else if (!strcmp(fieldName, "frequency")) {
818 *out = naNum(nav->get_freq());
819 } else if (!strcmp(fieldName, "range_nm")) {
820 *out = naNum(nav->get_range());
821 } else if (!strcmp(fieldName, "course")) {
822 if ((nav->type() == FGPositioned::ILS) || (nav->type() == FGPositioned::LOC)) {
823 double radial = nav->get_multiuse();
824 SG_NORMALIZE_RANGE(radial, 0.0, 360.0);
825 *out = naNum(radial);
836 static const char* fixGhostGetMember(naContext c, void* g, naRef field, naRef* out)
838 const char* fieldName = naStr_data(field);
839 FGFix* fix = (FGFix*) g;
841 if (!strcmp(fieldName, "id")) *out = stringToNasal(c, fix->ident());
842 else if (!strcmp(fieldName, "lat")) *out = naNum(fix->get_lat());
843 else if (!strcmp(fieldName, "lon")) *out = naNum(fix->get_lon());
851 static bool hashIsCoord(naRef h)
853 naRef parents = naHash_cget(h, (char*) "parents");
854 if (!naIsVector(parents)) {
858 return naEqual(naVec_get(parents, 0), geoCoordClass) != 0;
861 bool geodFromHash(naRef ref, SGGeod& result)
863 if (!naIsHash(ref)) {
868 // check for manual latitude / longitude names
869 naRef lat = naHash_cget(ref, (char*) "lat");
870 naRef lon = naHash_cget(ref, (char*) "lon");
871 if (naIsNum(lat) && naIsNum(lon)) {
872 result = SGGeod::fromDeg(naNumValue(lon).num, naNumValue(lat).num);
876 if (hashIsCoord(ref)) {
877 naRef lat = naHash_cget(ref, (char*) "_lat");
878 naRef lon = naHash_cget(ref, (char*) "_lon");
879 if (naIsNum(lat) && naIsNum(lon)) {
880 result = SGGeod::fromRad(naNumValue(lon).num, naNumValue(lat).num);
885 // check for any synonyms?
886 // latitude + longitude?
891 static int geodFromArgs(naRef* args, int offset, int argc, SGGeod& result)
893 if (offset >= argc) {
897 if (naIsGhost(args[offset])) {
898 naGhostType* gt = naGhost_type(args[offset]);
899 if (gt == &AirportGhostType) {
900 result = airportGhost(args[offset])->geod();
904 if (gt == &NavaidGhostType) {
905 result = navaidGhost(args[offset])->geod();
909 if (gt == &RunwayGhostType) {
910 result = runwayGhost(args[offset])->geod();
914 if (gt == &TaxiwayGhostType) {
915 result = taxiwayGhost(args[offset])->geod();
919 if (gt == &FixGhostType) {
920 result = fixGhost(args[offset])->geod();
924 if (gt == &WayptGhostType) {
925 result = wayptGhost(args[offset])->position();
930 if (geodFromHash(args[offset], result)) {
934 if (((argc - offset) >= 2) && naIsNum(args[offset]) && naIsNum(args[offset + 1])) {
935 double lat = naNumValue(args[0]).num,
936 lon = naNumValue(args[1]).num;
937 result = SGGeod::fromDeg(lon, lat);
944 // Convert a cartesian point to a geodetic lat/lon/altitude.
945 static naRef f_carttogeod(naContext c, naRef me, int argc, naRef* args)
947 double lat, lon, alt, xyz[3];
948 if(argc != 3) naRuntimeError(c, "carttogeod() expects 3 arguments");
949 for(int i=0; i<3; i++)
950 xyz[i] = naNumValue(args[i]).num;
951 sgCartToGeod(xyz, &lat, &lon, &alt);
952 lat *= SG_RADIANS_TO_DEGREES;
953 lon *= SG_RADIANS_TO_DEGREES;
954 naRef vec = naNewVector(c);
955 naVec_append(vec, naNum(lat));
956 naVec_append(vec, naNum(lon));
957 naVec_append(vec, naNum(alt));
961 // Convert a geodetic lat/lon/altitude to a cartesian point.
962 static naRef f_geodtocart(naContext c, naRef me, int argc, naRef* args)
964 if(argc != 3) naRuntimeError(c, "geodtocart() expects 3 arguments");
965 double lat = naNumValue(args[0]).num * SG_DEGREES_TO_RADIANS;
966 double lon = naNumValue(args[1]).num * SG_DEGREES_TO_RADIANS;
967 double alt = naNumValue(args[2]).num;
969 sgGeodToCart(lat, lon, alt, xyz);
970 naRef vec = naNewVector(c);
971 naVec_append(vec, naNum(xyz[0]));
972 naVec_append(vec, naNum(xyz[1]));
973 naVec_append(vec, naNum(xyz[2]));
977 // For given geodetic point return array with elevation, and a material data
978 // hash, or nil if there's no information available (tile not loaded). If
979 // information about the material isn't available, then nil is returned instead
981 static naRef f_geodinfo(naContext c, naRef me, int argc, naRef* args)
983 #define HASHSET(s,l,n) naHash_set(matdata, naStr_fromdata(naNewString(c),s,l),n)
984 if(argc < 2 || argc > 3)
985 naRuntimeError(c, "geodinfo() expects 2 or 3 arguments: lat, lon [, maxalt]");
986 double lat = naNumValue(args[0]).num;
987 double lon = naNumValue(args[1]).num;
988 double elev = argc == 3 ? naNumValue(args[2]).num : 10000;
989 const simgear::BVHMaterial *material;
990 SGGeod geod = SGGeod::fromDegM(lon, lat, elev);
991 if(!globals->get_scenery()->get_elevation_m(geod, elev, &material))
993 const SGMaterial *mat = dynamic_cast<const SGMaterial *>(material);
994 naRef vec = naNewVector(c);
995 naVec_append(vec, naNum(elev));
996 naRef matdata = naNil();
998 matdata = naNewHash(c);
999 naRef names = naNewVector(c);
1000 BOOST_FOREACH(const std::string& n, mat->get_names())
1001 naVec_append(names, stringToNasal(c, n));
1003 HASHSET("names", 5, names);
1004 HASHSET("solid", 5, naNum(mat->get_solid()));
1005 HASHSET("friction_factor", 15, naNum(mat->get_friction_factor()));
1006 HASHSET("rolling_friction", 16, naNum(mat->get_rolling_friction()));
1007 HASHSET("load_resistance", 15, naNum(mat->get_load_resistance()));
1008 HASHSET("bumpiness", 9, naNum(mat->get_bumpiness()));
1009 HASHSET("light_coverage", 14, naNum(mat->get_light_coverage()));
1011 naVec_append(vec, matdata);
1017 // Returns data hash for particular or nearest airport of a <type>, or nil
1020 // airportinfo(<id>); e.g. "KSFO"
1021 // airportinfo(<type>); type := ("airport"|"seaport"|"heliport")
1022 // airportinfo() same as airportinfo("airport")
1023 // airportinfo(<lat>, <lon> [, <type>]);
1024 static naRef f_airportinfo(naContext c, naRef me, int argc, naRef* args)
1026 SGGeod pos = globals->get_aircraft_position();
1027 FGAirport* apt = NULL;
1029 if(argc >= 2 && naIsNum(args[0]) && naIsNum(args[1])) {
1030 pos = SGGeod::fromDeg(args[1].num, args[0].num);
1035 double maxRange = 10000.0; // expose this? or pick a smaller value?
1037 FGAirport::TypeRunwayFilter filter; // defaults to airports only
1040 // fall through and use AIRPORT
1041 } else if(argc == 1 && naIsString(args[0])) {
1042 if (filter.fromTypeString(naStr_data(args[0]))) {
1045 // user provided an <id>, hopefully
1046 apt = FGAirport::findByIdent(naStr_data(args[0]));
1048 // return nil here, but don't raise a runtime error; this is a
1049 // legitamate way to validate an ICAO code, for example in a
1050 // dialog box or similar.
1055 naRuntimeError(c, "airportinfo() with invalid function arguments");
1060 apt = FGAirport::findClosest(pos, maxRange, &filter);
1061 if(!apt) return naNil();
1064 return ghostForAirport(c, apt);
1067 static naRef f_findAirportsWithinRange(naContext c, naRef me, int argc, naRef* args)
1070 SGGeod pos = globals->get_aircraft_position();
1071 argOffset += geodFromArgs(args, 0, argc, pos);
1073 if (!naIsNum(args[argOffset])) {
1074 naRuntimeError(c, "findAirportsWithinRange expected range (in nm) as arg %d", argOffset);
1077 FGAirport::TypeRunwayFilter filter; // defaults to airports only
1078 double rangeNm = args[argOffset++].num;
1079 if (argOffset < argc) {
1080 filter.fromTypeString(naStr_data(args[argOffset++]));
1083 naRef r = naNewVector(c);
1085 FGPositionedList apts = FGPositioned::findWithinRange(pos, rangeNm, &filter);
1086 FGPositioned::sortByRange(apts, pos);
1088 BOOST_FOREACH(FGPositionedRef a, apts) {
1089 FGAirport* apt = (FGAirport*) a.get();
1090 naVec_append(r, ghostForAirport(c, apt));
1096 static naRef f_findAirportsByICAO(naContext c, naRef me, int argc, naRef* args)
1098 if (!naIsString(args[0])) {
1099 naRuntimeError(c, "findAirportsByICAO expects string as arg 0");
1103 std::string prefix(naStr_data(args[argOffset++]));
1104 FGAirport::TypeRunwayFilter filter; // defaults to airports only
1105 if (argOffset < argc) {
1106 filter.fromTypeString(naStr_data(args[argOffset++]));
1109 naRef r = naNewVector(c);
1111 FGPositionedList apts = FGPositioned::findAllWithIdent(prefix, &filter, false);
1113 BOOST_FOREACH(FGPositionedRef a, apts) {
1114 FGAirport* apt = (FGAirport*) a.get();
1115 naVec_append(r, ghostForAirport(c, apt));
1121 static naRef f_airport_tower(naContext c, naRef me, int argc, naRef* args)
1123 FGAirport* apt = airportGhost(me);
1125 naRuntimeError(c, "airport.tower called on non-airport object");
1128 // build a hash for the tower position
1129 SGGeod towerLoc = apt->getTowerLocation();
1130 naRef tower = naNewHash(c);
1131 hashset(c, tower, "lat", naNum(towerLoc.getLatitudeDeg()));
1132 hashset(c, tower, "lon", naNum(towerLoc.getLongitudeDeg()));
1133 hashset(c, tower, "elevation", naNum(towerLoc.getElevationM()));
1137 static naRef f_airport_comms(naContext c, naRef me, int argc, naRef* args)
1139 FGAirport* apt = airportGhost(me);
1141 naRuntimeError(c, "airport.comms called on non-airport object");
1143 naRef comms = naNewVector(c);
1145 // if we have an explicit type, return a simple vector of frequencies
1146 if (argc > 0 && !naIsString(args[0])) {
1147 naRuntimeError(c, "airport.comms argument must be a frequency type name");
1151 std::string commName = naStr_data(args[0]);
1152 FGPositioned::Type commType = FGPositioned::typeFromName(commName);
1154 BOOST_FOREACH(flightgear::CommStation* comm, apt->commStationsOfType(commType)) {
1155 naVec_append(comms, naNum(comm->freqMHz()));
1158 // otherwise return a vector of hashes, one for each comm station.
1159 BOOST_FOREACH(flightgear::CommStation* comm, apt->commStations()) {
1160 naRef commHash = naNewHash(c);
1161 hashset(c, commHash, "frequency", naNum(comm->freqMHz()));
1162 hashset(c, commHash, "ident", stringToNasal(c, comm->ident()));
1163 naVec_append(comms, commHash);
1170 static naRef f_airport_runway(naContext c, naRef me, int argc, naRef* args)
1172 FGAirport* apt = airportGhost(me);
1174 naRuntimeError(c, "airport.runway called on non-airport object");
1177 if ((argc < 1) || !naIsString(args[0])) {
1178 naRuntimeError(c, "airport.runway expects a runway ident argument");
1181 std::string ident(naStr_data(args[0]));
1182 boost::to_upper(ident);
1184 if (apt->hasRunwayWithIdent(ident)) {
1185 return ghostForRunway(c, apt->getRunwayByIdent(ident));
1186 } else if (apt->hasHelipadWithIdent(ident)) {
1187 return ghostForHelipad(c, apt->getHelipadByIdent(ident));
1192 static naRef f_airport_runwaysWithoutReciprocals(naContext c, naRef me, int argc, naRef* args)
1194 FGAirport* apt = airportGhost(me);
1196 naRuntimeError(c, "airport.runwaysWithoutReciprocals called on non-airport object");
1199 FGRunwayList rwylist(apt->getRunwaysWithoutReciprocals());
1200 naRef runways = naNewVector(c);
1201 for (unsigned int r=0; r<rwylist.size(); ++r) {
1202 FGRunway* rwy(rwylist[r]);
1203 naVec_append(runways, ghostForRunway(c, apt->getRunwayByIdent(rwy->ident())));
1208 static naRef f_airport_sids(naContext c, naRef me, int argc, naRef* args)
1210 FGAirport* apt = airportGhost(me);
1212 naRuntimeError(c, "airport.sids called on non-airport object");
1215 naRef sids = naNewVector(c);
1217 FGRunway* rwy = NULL;
1218 if (argc > 0 && naIsString(args[0])) {
1219 if (!apt->hasRunwayWithIdent(naStr_data(args[0]))) {
1223 rwy = apt->getRunwayByIdent(naStr_data(args[0]));
1224 } else if (argc > 0) {
1225 rwy = runwayGhost(args[0]);
1229 BOOST_FOREACH(flightgear::SID* sid, rwy->getSIDs()) {
1230 naRef procId = stringToNasal(c, sid->ident());
1231 naVec_append(sids, procId);
1234 for (unsigned int s=0; s<apt->numSIDs(); ++s) {
1235 flightgear::SID* sid = apt->getSIDByIndex(s);
1236 naRef procId = stringToNasal(c, sid->ident());
1237 naVec_append(sids, procId);
1244 static naRef f_airport_stars(naContext c, naRef me, int argc, naRef* args)
1246 FGAirport* apt = airportGhost(me);
1248 naRuntimeError(c, "airport.stars called on non-airport object");
1251 naRef stars = naNewVector(c);
1253 FGRunway* rwy = NULL;
1254 if (argc > 0 && naIsString(args[0])) {
1255 if (!apt->hasRunwayWithIdent(naStr_data(args[0]))) {
1259 rwy = apt->getRunwayByIdent(naStr_data(args[0]));
1260 } else if (argc > 0) {
1261 rwy = runwayGhost(args[0]);
1265 BOOST_FOREACH(flightgear::STAR* s, rwy->getSTARs()) {
1266 naRef procId = stringToNasal(c, s->ident());
1267 naVec_append(stars, procId);
1270 for (unsigned int s=0; s<apt->numSTARs(); ++s) {
1271 flightgear::STAR* star = apt->getSTARByIndex(s);
1272 naRef procId = stringToNasal(c, star->ident());
1273 naVec_append(stars, procId);
1280 static naRef f_airport_approaches(naContext c, naRef me, int argc, naRef* args)
1282 FGAirport* apt = airportGhost(me);
1284 naRuntimeError(c, "airport.getApproachList called on non-airport object");
1287 naRef approaches = naNewVector(c);
1289 ProcedureType ty = PROCEDURE_INVALID;
1290 if ((argc > 1) && naIsString(args[1])) {
1291 std::string u(naStr_data(args[1]));
1293 if (u == "NDB") ty = PROCEDURE_APPROACH_NDB;
1294 if (u == "VOR") ty = PROCEDURE_APPROACH_VOR;
1295 if (u == "ILS") ty = PROCEDURE_APPROACH_ILS;
1296 if (u == "RNAV") ty = PROCEDURE_APPROACH_RNAV;
1299 FGRunway* rwy = NULL;
1300 if (argc > 0 && (rwy = runwayGhost(args[0]))) {
1302 } else if (argc > 0 && naIsString(args[0])) {
1303 if (!apt->hasRunwayWithIdent(naStr_data(args[0]))) {
1307 rwy = apt->getRunwayByIdent(naStr_data(args[0]));
1311 BOOST_FOREACH(Approach* s, rwy->getApproaches()) {
1312 if ((ty != PROCEDURE_INVALID) && (s->type() != ty)) {
1316 naRef procId = stringToNasal(c, s->ident());
1317 naVec_append(approaches, procId);
1320 // no runway specified, report them all
1321 for (unsigned int s=0; s<apt->numApproaches(); ++s) {
1322 Approach* app = apt->getApproachByIndex(s);
1323 if ((ty != PROCEDURE_INVALID) && (app->type() != ty)) {
1327 naRef procId = stringToNasal(c, app->ident());
1328 naVec_append(approaches, procId);
1335 static naRef f_airport_parking(naContext c, naRef me, int argc, naRef* args)
1337 FGAirport* apt = airportGhost(me);
1339 naRuntimeError(c, "airport.parking called on non-airport object");
1342 naRef r = naNewVector(c);
1344 bool onlyAvailable = false;
1346 if (argc > 0 && naIsString(args[0])) {
1347 type = naStr_data(args[0]);
1350 if ((argc > 1) && naIsNum(args[1])) {
1351 onlyAvailable = (args[1].num != 0.0);
1354 FGAirportDynamicsRef dynamics = apt->getDynamics();
1355 FGParkingList parkings = dynamics->getParkings(onlyAvailable, type);
1356 FGParkingList::const_iterator it;
1357 for (it = parkings.begin(); it != parkings.end(); ++it) {
1358 FGParkingRef park = *it;
1359 const SGGeod& parkLoc = park->geod();
1360 naRef ph = naNewHash(c);
1361 hashset(c, ph, "name", stringToNasal(c, park->getName()));
1362 hashset(c, ph, "lat", naNum(parkLoc.getLatitudeDeg()));
1363 hashset(c, ph, "lon", naNum(parkLoc.getLongitudeDeg()));
1364 hashset(c, ph, "elevation", naNum(parkLoc.getElevationM()));
1365 naVec_append(r, ph);
1371 static naRef f_airport_getSid(naContext c, naRef me, int argc, naRef* args)
1373 FGAirport* apt = airportGhost(me);
1375 naRuntimeError(c, "airport.getSid called on non-airport object");
1378 if ((argc != 1) || !naIsString(args[0])) {
1379 naRuntimeError(c, "airport.getSid passed invalid argument");
1382 std::string ident = naStr_data(args[0]);
1383 return ghostForProcedure(c, apt->findSIDWithIdent(ident));
1386 static naRef f_airport_getStar(naContext c, naRef me, int argc, naRef* args)
1388 FGAirport* apt = airportGhost(me);
1390 naRuntimeError(c, "airport.getStar called on non-airport object");
1393 if ((argc != 1) || !naIsString(args[0])) {
1394 naRuntimeError(c, "airport.getStar passed invalid argument");
1397 std::string ident = naStr_data(args[0]);
1398 return ghostForProcedure(c, apt->findSTARWithIdent(ident));
1401 static naRef f_airport_getApproach(naContext c, naRef me, int argc, naRef* args)
1403 FGAirport* apt = airportGhost(me);
1405 naRuntimeError(c, "airport.getIAP called on non-airport object");
1408 if ((argc != 1) || !naIsString(args[0])) {
1409 naRuntimeError(c, "airport.getIAP passed invalid argument");
1412 std::string ident = naStr_data(args[0]);
1413 return ghostForProcedure(c, apt->findApproachWithIdent(ident));
1416 static naRef f_airport_findBestRunway(naContext c, naRef me, int argc, naRef* args)
1418 FGAirport* apt = airportGhost(me);
1420 naRuntimeError(c, "findBestRunway called on non-airport object");
1424 if (!geodFromArgs(args, 0, argc, pos)) {
1425 naRuntimeError(c, "findBestRunway must be passed a position");
1428 return ghostForRunway(c, apt->findBestRunwayForPos(pos));
1431 static naRef f_airport_toString(naContext c, naRef me, int argc, naRef* args)
1433 FGAirport* apt = airportGhost(me);
1435 naRuntimeError(c, "airport.tostring called on non-airport object");
1438 return stringToNasal(c, "an airport " + apt->ident());
1441 // Returns vector of data hash for navaid of a <type>, nil on error
1442 // navaids sorted by ascending distance
1443 // navinfo([<lat>,<lon>],[<type>],[<id>])
1444 // lat/lon (numeric): use latitude/longitude instead of ac position
1445 // type: ("fix"|"vor"|"ndb"|"ils"|"dme"|"tacan"|"any")
1446 // id: (partial) id of the fix
1448 // navinfo("vor") returns all vors
1449 // navinfo("HAM") return all navaids who's name start with "HAM"
1450 // navinfo("vor", "HAM") return all vor who's name start with "HAM"
1451 //navinfo(34,48,"vor","HAM") return all vor who's name start with "HAM"
1452 // sorted by distance relative to lat=34, lon=48
1453 static naRef f_navinfo(naContext c, naRef me, int argc, naRef* args)
1457 if(argc >= 2 && naIsNum(args[0]) && naIsNum(args[1])) {
1458 pos = SGGeod::fromDeg(args[1].num, args[0].num);
1462 pos = globals->get_aircraft_position();
1465 FGPositioned::Type type = FGPositioned::INVALID;
1466 nav_list_type navlist;
1467 const char * id = "";
1469 if(argc > 0 && naIsString(args[0])) {
1470 const char *s = naStr_data(args[0]);
1471 if(!strcmp(s, "any")) type = FGPositioned::INVALID;
1472 else if(!strcmp(s, "fix")) type = FGPositioned::FIX;
1473 else if(!strcmp(s, "vor")) type = FGPositioned::VOR;
1474 else if(!strcmp(s, "ndb")) type = FGPositioned::NDB;
1475 else if(!strcmp(s, "ils")) type = FGPositioned::ILS;
1476 else if(!strcmp(s, "dme")) type = FGPositioned::DME;
1477 else if(!strcmp(s, "tacan")) type = FGPositioned::TACAN;
1478 else id = s; // this is an id
1483 if(argc > 0 && naIsString(args[0])) {
1485 naRuntimeError(c, "navinfo() called with navaid id");
1488 id = naStr_data(args[0]);
1494 naRuntimeError(c, "navinfo() called with too many arguments");
1498 FGNavList::TypeFilter filter(type);
1499 navlist = FGNavList::findByIdentAndFreq( pos, id, 0.0, &filter );
1501 naRef reply = naNewVector(c);
1502 for( nav_list_type::const_iterator it = navlist.begin(); it != navlist.end(); ++it ) {
1503 naVec_append( reply, ghostForNavaid(c, *it) );
1508 static naRef f_findNavaidsWithinRange(naContext c, naRef me, int argc, naRef* args)
1511 SGGeod pos = globals->get_aircraft_position();
1512 argOffset += geodFromArgs(args, 0, argc, pos);
1514 if (!naIsNum(args[argOffset])) {
1515 naRuntimeError(c, "findNavaidsWithinRange expected range (in nm) as arg %d", argOffset);
1518 FGPositioned::Type type = FGPositioned::INVALID;
1519 double rangeNm = args[argOffset++].num;
1520 if (argOffset < argc) {
1521 type = FGPositioned::typeFromName(naStr_data(args[argOffset]));
1524 naRef r = naNewVector(c);
1525 FGNavList::TypeFilter filter(type);
1526 FGPositionedList navs = FGPositioned::findWithinRange(pos, rangeNm, &filter);
1527 FGPositioned::sortByRange(navs, pos);
1529 BOOST_FOREACH(FGPositionedRef a, navs) {
1530 FGNavRecord* nav = (FGNavRecord*) a.get();
1531 naVec_append(r, ghostForNavaid(c, nav));
1537 static naRef f_findNavaidByFrequency(naContext c, naRef me, int argc, naRef* args)
1540 SGGeod pos = globals->get_aircraft_position();
1541 argOffset += geodFromArgs(args, 0, argc, pos);
1543 if (!naIsNum(args[argOffset])) {
1544 naRuntimeError(c, "findNavaidByFrequency expectes frequency (in Mhz) as arg %d", argOffset);
1547 FGPositioned::Type type = FGPositioned::INVALID;
1548 double freqMhz = args[argOffset++].num;
1549 if (argOffset < argc) {
1550 type = FGPositioned::typeFromName(naStr_data(args[argOffset]));
1553 FGNavList::TypeFilter filter(type);
1554 nav_list_type navs = FGNavList::findAllByFreq(freqMhz, pos, &filter);
1559 return ghostForNavaid(c, navs.front().ptr());
1562 static naRef f_findNavaidsByFrequency(naContext c, naRef me, int argc, naRef* args)
1565 SGGeod pos = globals->get_aircraft_position();
1566 argOffset += geodFromArgs(args, 0, argc, pos);
1568 if (!naIsNum(args[argOffset])) {
1569 naRuntimeError(c, "findNavaidsByFrequency expectes frequency (in Mhz) as arg %d", argOffset);
1572 FGPositioned::Type type = FGPositioned::INVALID;
1573 double freqMhz = args[argOffset++].num;
1574 if (argOffset < argc) {
1575 type = FGPositioned::typeFromName(naStr_data(args[argOffset]));
1578 naRef r = naNewVector(c);
1580 FGNavList::TypeFilter filter(type);
1581 nav_list_type navs = FGNavList::findAllByFreq(freqMhz, pos, &filter);
1583 BOOST_FOREACH(nav_rec_ptr a, navs) {
1584 naVec_append(r, ghostForNavaid(c, a.ptr()));
1590 static naRef f_findNavaidsByIdent(naContext c, naRef me, int argc, naRef* args)
1593 SGGeod pos = globals->get_aircraft_position();
1594 argOffset += geodFromArgs(args, 0, argc, pos);
1596 if (!naIsString(args[argOffset])) {
1597 naRuntimeError(c, "findNavaidsByIdent expectes ident string as arg %d", argOffset);
1600 FGPositioned::Type type = FGPositioned::INVALID;
1601 std::string ident = naStr_data(args[argOffset++]);
1602 if (argOffset < argc) {
1603 type = FGPositioned::typeFromName(naStr_data(args[argOffset]));
1606 FGNavList::TypeFilter filter(type);
1607 naRef r = naNewVector(c);
1608 nav_list_type navs = FGNavList::findByIdentAndFreq(pos, ident, 0.0, &filter);
1610 BOOST_FOREACH(nav_rec_ptr a, navs) {
1611 naVec_append(r, ghostForNavaid(c, a.ptr()));
1617 static naRef f_findFixesByIdent(naContext c, naRef me, int argc, naRef* args)
1620 SGGeod pos = globals->get_aircraft_position();
1621 argOffset += geodFromArgs(args, 0, argc, pos);
1623 if (!naIsString(args[argOffset])) {
1624 naRuntimeError(c, "findFixesByIdent expectes ident string as arg %d", argOffset);
1627 std::string ident(naStr_data(args[argOffset]));
1628 naRef r = naNewVector(c);
1630 FGPositioned::TypeFilter filter(FGPositioned::FIX);
1631 FGPositionedList fixes = FGPositioned::findAllWithIdent(ident, &filter);
1632 FGPositioned::sortByRange(fixes, pos);
1634 BOOST_FOREACH(FGPositionedRef f, fixes) {
1635 naVec_append(r, ghostForFix(c, (FGFix*) f.ptr()));
1641 // Convert a cartesian point to a geodetic lat/lon/altitude.
1642 static naRef f_magvar(naContext c, naRef me, int argc, naRef* args)
1644 SGGeod pos = globals->get_aircraft_position();
1646 // fine, use aircraft position
1647 } else if (geodFromArgs(args, 0, argc, pos)) {
1650 naRuntimeError(c, "magvar() expects no arguments, a positioned hash or lat,lon pair");
1653 double jd = globals->get_time_params()->getJD();
1654 double magvarDeg = sgGetMagVar(pos, jd) * SG_RADIANS_TO_DEGREES;
1655 return naNum(magvarDeg);
1658 static naRef f_courseAndDistance(naContext c, naRef me, int argc, naRef* args)
1660 SGGeod from = globals->get_aircraft_position(), to, p;
1661 int argOffset = geodFromArgs(args, 0, argc, p);
1662 if (geodFromArgs(args, argOffset, argc, to)) {
1663 from = p; // we parsed both FROM and TO args, so first was from
1665 to = p; // only parsed one arg, so FROM is current
1668 if (argOffset == 0) {
1669 naRuntimeError(c, "invalid arguments to courseAndDistance");
1672 double course, course2, d;
1673 SGGeodesy::inverse(from, to, course, course2, d);
1675 naRef result = naNewVector(c);
1676 naVec_append(result, naNum(course));
1677 naVec_append(result, naNum(d * SG_METER_TO_NM));
1681 static naRef f_greatCircleMove(naContext c, naRef me, int argc, naRef* args)
1683 SGGeod from = globals->get_aircraft_position(), to;
1686 // complication - don't inerpret two doubles (as the only args)
1687 // as a lat,lon pair - only do so if we have at least three args.
1689 argOffset = geodFromArgs(args, 0, argc, from);
1692 if ((argOffset + 1) >= argc) {
1693 naRuntimeError(c, "isufficent arguments to greatCircleMove");
1696 if (!naIsNum(args[argOffset]) || !naIsNum(args[argOffset+1])) {
1697 naRuntimeError(c, "invalid arguments %d and %d to greatCircleMove",
1698 argOffset, argOffset + 1);
1701 double course = args[argOffset].num, course2;
1702 double distanceNm = args[argOffset + 1].num;
1703 SGGeodesy::direct(from, course, distanceNm * SG_NM_TO_METER, to, course2);
1706 naRef coord = naNewHash(c);
1707 hashset(c, coord, "lat", naNum(to.getLatitudeDeg()));
1708 hashset(c, coord, "lon", naNum(to.getLongitudeDeg()));
1712 static naRef f_tilePath(naContext c, naRef me, int argc, naRef* args)
1714 SGGeod pos = globals->get_aircraft_position();
1715 geodFromArgs(args, 0, argc, pos);
1717 return stringToNasal(c, b.gen_base_path());
1720 static naRef f_tileIndex(naContext c, naRef me, int argc, naRef* args)
1722 SGGeod pos = globals->get_aircraft_position();
1723 geodFromArgs(args, 0, argc, pos);
1725 return naNum(b.gen_index());
1728 static naRef f_route(naContext c, naRef me, int argc, naRef* args)
1731 FGRouteMgr* rm = static_cast<FGRouteMgr*>(globals->get_subsystem("route-manager"));
1732 return ghostForFlightPlan(c, rm->flightPlan());
1735 if ((argc > 0) && naIsString(args[0])) {
1736 flightgear::FlightPlan* fp = new flightgear::FlightPlan;
1737 SGPath path(naStr_data(args[0]));
1738 if (!path.exists()) {
1739 naRuntimeError(c, "flightplan, no file at path %s", path.c_str());
1742 if (!fp->load(path)) {
1743 SG_LOG(SG_NASAL, SG_WARN, "failed to load flight-plan from " << path);
1748 return ghostForFlightPlan(c, fp);
1751 naRuntimeError(c, "bad arguments to flightplan()");
1755 class NasalFPDelegate : public FlightPlan::Delegate
1758 NasalFPDelegate(FlightPlan* fp, FGNasalSys* sys, naRef ins) :
1763 _gcSaveKey = _nasal->gcSave(ins);
1766 virtual ~NasalFPDelegate()
1768 _nasal->gcRelease(_gcSaveKey);
1771 virtual void departureChanged()
1773 callDelegateMethod("departureChanged");
1776 virtual void arrivalChanged()
1778 callDelegateMethod("arrivalChanged");
1781 virtual void waypointsChanged()
1783 callDelegateMethod("waypointsChanged");
1786 virtual void currentWaypointChanged()
1788 callDelegateMethod("currentWaypointChanged");
1791 virtual void cleared()
1793 callDelegateMethod("cleared");
1796 virtual void endOfFlightPlan()
1798 callDelegateMethod("endOfFlightPlan");
1801 virtual void activated()
1803 callDelegateMethod("activated");
1807 void callDelegateMethod(const char* method)
1810 naContext ctx = naNewContext();
1812 if (naMember_cget(ctx, _instance, method, &f) != 0) {
1814 arg[0] = ghostForFlightPlan(ctx, _plan);
1815 _nasal->callMethod(f, _instance, 1, arg, naNil());
1828 class NasalFPDelegateFactory : public FlightPlan::DelegateFactory
1831 NasalFPDelegateFactory(naRef code)
1833 _nasal = (FGNasalSys*) globals->get_subsystem("nasal");
1835 _gcSaveKey = _nasal->gcSave(_func);
1838 virtual ~NasalFPDelegateFactory()
1840 _nasal->gcRelease(_gcSaveKey);
1843 virtual FlightPlan::Delegate* createFlightPlanDelegate(FlightPlan* fp)
1846 naContext ctx = naNewContext();
1847 args[0] = ghostForFlightPlan(ctx, fp);
1848 naRef instance = _nasal->call(_func, 1, args, naNil());
1850 FlightPlan::Delegate* result = NULL;
1851 if (!naIsNil(instance)) {
1852 // will GC-save instance
1853 result = new NasalFPDelegate(fp, _nasal, instance);
1865 static std::vector<NasalFPDelegateFactory*> static_nasalDelegateFactories;
1867 void shutdownNasalPositioned()
1869 std::vector<NasalFPDelegateFactory*>::iterator it;
1870 for (it = static_nasalDelegateFactories.begin();
1871 it != static_nasalDelegateFactories.end(); ++it)
1873 FlightPlan::unregisterDelegateFactory(*it);
1876 static_nasalDelegateFactories.clear();
1879 static naRef f_registerFPDelegate(naContext c, naRef me, int argc, naRef* args)
1881 if ((argc < 1) || !naIsFunc(args[0])) {
1882 naRuntimeError(c, "non-function argument to registerFlightPlanDelegate");
1885 NasalFPDelegateFactory* factory = new NasalFPDelegateFactory(args[0]);
1886 FlightPlan::registerDelegateFactory(factory);
1887 static_nasalDelegateFactories.push_back(factory);
1891 static WayptRef wayptFromArg(naRef arg)
1893 WayptRef r = wayptGhost(arg);
1898 FGPositioned* pos = positionedGhost(arg);
1900 // let's check if the arg is hash, coudl extra a geod and hence build
1901 // a simple waypoint
1906 // special-case for runways
1907 if (pos->type() == FGPositioned::RUNWAY) {
1908 return new RunwayWaypt((FGRunway*) pos, NULL);
1911 return new NavaidWaypoint(pos, NULL);
1914 static naRef convertWayptVecToNasal(naContext c, const WayptVec& wps)
1916 naRef result = naNewVector(c);
1917 BOOST_FOREACH(WayptRef wpt, wps) {
1918 naVec_append(result, ghostForWaypt(c, wpt.get()));
1923 static naRef f_airwaySearch(naContext c, naRef me, int argc, naRef* args)
1926 naRuntimeError(c, "airwaysSearch needs at least two arguments");
1929 WayptRef start = wayptFromArg(args[0]),
1930 end = wayptFromArg(args[1]);
1932 if (!start || !end) {
1933 SG_LOG(SG_NASAL, SG_WARN, "airwaysSearch: start or end points are invalid");
1937 bool highLevel = true;
1938 if ((argc > 2) && naIsString(args[2])) {
1939 if (!strcmp(naStr_data(args[2]), "lowlevel")) {
1946 Airway::highLevel()->route(start, end, route);
1948 Airway::lowLevel()->route(start, end, route);
1951 return convertWayptVecToNasal(c, route);
1954 static naRef f_createWP(naContext c, naRef me, int argc, naRef* args)
1957 int argOffset = geodFromArgs(args, 0, argc, pos);
1959 if (((argc - argOffset) < 1) || !naIsString(args[argOffset])) {
1960 naRuntimeError(c, "createWP: no identifier supplied");
1963 std::string ident = naStr_data(args[argOffset++]);
1964 WayptRef wpt = new BasicWaypt(pos, ident, NULL);
1966 // set waypt flags - approach, departure, pseudo, etc
1967 if (argc > argOffset) {
1968 WayptFlag f = wayptFlagFromString(naStr_data(args[argOffset++]));
1970 naRuntimeError(c, "createWP: bad waypoint role");
1976 return ghostForWaypt(c, wpt);
1979 static naRef f_createWPFrom(naContext c, naRef me, int argc, naRef* args)
1982 naRuntimeError(c, "createWPFrom: need at least one argument");
1985 FGPositioned* positioned = positionedGhost(args[0]);
1987 naRuntimeError(c, "createWPFrom: couldn;t convert arg[0] to FGPositioned");
1991 if (positioned->type() == FGPositioned::RUNWAY) {
1992 wpt = new RunwayWaypt((FGRunway*) positioned, NULL);
1994 wpt = new NavaidWaypoint(positioned, NULL);
1997 // set waypt flags - approach, departure, pseudo, etc
1999 WayptFlag f = wayptFlagFromString(naStr_data(args[1]));
2001 naRuntimeError(c, "createWPFrom: bad waypoint role");
2006 return ghostForWaypt(c, wpt);
2009 static naRef f_flightplan_getWP(naContext c, naRef me, int argc, naRef* args)
2011 FlightPlan* fp = flightplanGhost(me);
2013 naRuntimeError(c, "flightplan.getWP called on non-flightplan object");
2018 index = fp->currentIndex();
2020 index = (int) naNumValue(args[0]).num;
2023 if ((index < 0) || (index >= fp->numLegs())) {
2027 return ghostForLeg(c, fp->legAtIndex(index));
2030 static naRef f_flightplan_currentWP(naContext c, naRef me, int argc, naRef* args)
2032 FlightPlan* fp = flightplanGhost(me);
2034 naRuntimeError(c, "flightplan.currentWP called on non-flightplan object");
2036 return ghostForLeg(c, fp->currentLeg());
2039 static naRef f_flightplan_nextWP(naContext c, naRef me, int argc, naRef* args)
2041 FlightPlan* fp = flightplanGhost(me);
2043 naRuntimeError(c, "flightplan.nextWP called on non-flightplan object");
2045 return ghostForLeg(c, fp->nextLeg());
2048 static naRef f_flightplan_numWaypoints(naContext c, naRef me, int argc, naRef* args)
2050 FlightPlan* fp = flightplanGhost(me);
2052 naRuntimeError(c, "flightplan.numWaypoints called on non-flightplan object");
2054 return naNum(fp->numLegs());
2057 static naRef f_flightplan_appendWP(naContext c, naRef me, int argc, naRef* args)
2059 FlightPlan* fp = flightplanGhost(me);
2061 naRuntimeError(c, "flightplan.appendWP called on non-flightplan object");
2064 WayptRef wp = wayptGhost(args[0]);
2065 int index = fp->numLegs();
2066 fp->insertWayptAtIndex(wp.get(), index);
2067 return naNum(index);
2070 static naRef f_flightplan_insertWP(naContext c, naRef me, int argc, naRef* args)
2072 FlightPlan* fp = flightplanGhost(me);
2074 naRuntimeError(c, "flightplan.insertWP called on non-flightplan object");
2077 WayptRef wp = wayptGhost(args[0]);
2078 int index = -1; // append
2079 if ((argc > 1) && naIsNum(args[1])) {
2080 index = (int) args[1].num;
2083 fp->insertWayptAtIndex(wp.get(), index);
2087 static naRef f_flightplan_insertWPAfter(naContext c, naRef me, int argc, naRef* args)
2089 FlightPlan* fp = flightplanGhost(me);
2091 naRuntimeError(c, "flightplan.insertWPAfter called on non-flightplan object");
2094 WayptRef wp = wayptGhost(args[0]);
2095 int index = -1; // append
2096 if ((argc > 1) && naIsNum(args[1])) {
2097 index = (int) args[1].num;
2100 fp->insertWayptAtIndex(wp.get(), index + 1);
2104 static naRef f_flightplan_insertWaypoints(naContext c, naRef me, int argc, naRef* args)
2106 FlightPlan* fp = flightplanGhost(me);
2108 naRuntimeError(c, "flightplan.insertWaypoints called on non-flightplan object");
2112 if (!naIsVector(args[0])) {
2113 naRuntimeError(c, "flightplan.insertWaypoints expects vector as first arg");
2116 int count = naVec_size(args[0]);
2117 for (int i=0; i<count; ++i) {
2118 Waypt* wp = wayptGhost(naVec_get(args[0], i));
2124 int index = -1; // append
2125 if ((argc > 1) && naIsNum(args[1])) {
2126 index = (int) args[1].num;
2129 fp->insertWayptsAtIndex(wps, index);
2133 static naRef f_flightplan_deleteWP(naContext c, naRef me, int argc, naRef* args)
2135 FlightPlan* fp = flightplanGhost(me);
2137 naRuntimeError(c, "flightplan.deleteWP called on non-flightplan object");
2140 if ((argc < 1) || !naIsNum(args[0])) {
2141 naRuntimeError(c, "bad argument to flightplan.deleteWP");
2144 int index = (int) args[0].num;
2145 fp->deleteIndex(index);
2149 static naRef f_flightplan_clearPlan(naContext c, naRef me, int argc, naRef* args)
2151 FlightPlan* fp = flightplanGhost(me);
2153 naRuntimeError(c, "flightplan.clearPlan called on non-flightplan object");
2160 static naRef f_flightplan_clearWPType(naContext c, naRef me, int argc, naRef* args)
2162 FlightPlan* fp = flightplanGhost(me);
2164 naRuntimeError(c, "flightplan.clearWPType called on non-flightplan object");
2168 naRuntimeError(c, "insufficent args to flightplan.clearWPType");
2171 WayptFlag flag = wayptFlagFromString(naStr_data(args[0]));
2173 naRuntimeError(c, "clearWPType: bad waypoint role");
2176 fp->clearWayptsWithFlag(flag);
2180 static naRef f_flightplan_clone(naContext c, naRef me, int argc, naRef* args)
2182 FlightPlan* fp = flightplanGhost(me);
2184 naRuntimeError(c, "flightplan.clone called on non-flightplan object");
2187 return ghostForFlightPlan(c, fp->clone());
2190 static naRef f_flightplan_pathGeod(naContext c, naRef me, int argc, naRef* args)
2192 FlightPlan* fp = flightplanGhost(me);
2194 naRuntimeError(c, "flightplan.clone called on non-flightplan object");
2197 if ((argc < 1) || !naIsNum(args[0])) {
2198 naRuntimeError(c, "bad argument to flightplan.pathGeod");
2201 if ((argc > 1) && !naIsNum(args[1])) {
2202 naRuntimeError(c, "bad argument to flightplan.pathGeod");
2205 int index = (int) args[0].num;
2206 double offset = (argc > 1) ? args[1].num : 0.0;
2207 naRef result = naNewHash(c);
2208 SGGeod g = fp->pointAlongRoute(index, offset);
2209 hashset(c, result, "lat", naNum(g.getLatitudeDeg()));
2210 hashset(c, result, "lon", naNum(g.getLongitudeDeg()));
2214 static naRef f_flightplan_finish(naContext c, naRef me, int argc, naRef* args)
2216 FlightPlan* fp = flightplanGhost(me);
2218 naRuntimeError(c, "flightplan.finish called on non-flightplan object");
2225 static naRef f_flightplan_indexOfWp(naContext c, naRef me, int argc, naRef* args)
2227 FlightPlan* fp = flightplanGhost(me);
2229 naRuntimeError(c, "flightplan.indexOfWP called on non-flightplan object");
2232 FGPositioned* positioned = positionedGhost(args[0]);
2234 return naNum(fp->findWayptIndex(positioned));
2238 int argOffset = geodFromArgs(args, 0, argc, pos);
2239 if (argOffset > 0) {
2240 return naNum(fp->findWayptIndex(pos));
2246 static naRef f_leg_setSpeed(naContext c, naRef me, int argc, naRef* args)
2248 FlightPlan::Leg* leg = fpLegGhost(me);
2250 naRuntimeError(c, "leg.setSpeed called on non-flightplan-leg object");
2254 if ((argc < 2) || !convertToNum(args[0], speed))
2255 naRuntimeError(c, "bad arguments to setSpeed");
2257 RouteRestriction rr = routeRestrictionFromString(naStr_data(args[1]));
2258 leg->setSpeed(rr, speed);
2263 static naRef f_leg_setAltitude(naContext c, naRef me, int argc, naRef* args)
2265 FlightPlan::Leg* leg = fpLegGhost(me);
2267 naRuntimeError(c, "leg.setAltitude called on non-flightplan-leg object");
2271 if ((argc < 2) || !convertToNum(args[0], alt))
2272 naRuntimeError(c, "bad arguments to leg.setAltitude");
2274 RouteRestriction rr = routeRestrictionFromString(naStr_data(args[1]));
2275 leg->setAltitude(rr, alt);
2280 static naRef f_leg_path(naContext c, naRef me, int argc, naRef* args)
2282 FlightPlan::Leg* leg = fpLegGhost(me);
2284 naRuntimeError(c, "leg.setAltitude called on non-flightplan-leg object");
2287 RoutePath path(leg->owner());
2288 SGGeodVec gv(path.pathForIndex(leg->index()));
2290 naRef result = naNewVector(c);
2291 BOOST_FOREACH(SGGeod p, gv) {
2292 // construct a geo.Coord!
2293 naRef coord = naNewHash(c);
2294 hashset(c, coord, "lat", naNum(p.getLatitudeDeg()));
2295 hashset(c, coord, "lon", naNum(p.getLongitudeDeg()));
2296 naVec_append(result, coord);
2302 static naRef f_leg_courseAndDistanceFrom(naContext c, naRef me, int argc, naRef* args)
2304 FlightPlan::Leg* leg = fpLegGhost(me);
2306 naRuntimeError(c, "leg.courseAndDistanceFrom called on non-flightplan-leg object");
2310 geodFromArgs(args, 0, argc, pos);
2312 RoutePath path(leg->owner());
2313 SGGeod wpPos = path.positionForIndex(leg->index());
2314 double courseDeg, az2, distanceM;
2315 SGGeodesy::inverse(pos, wpPos, courseDeg, az2, distanceM);
2317 naRef result = naNewVector(c);
2318 naVec_append(result, naNum(courseDeg));
2319 naVec_append(result, naNum(distanceM * SG_METER_TO_NM));
2323 static naRef f_waypoint_navaid(naContext c, naRef me, int argc, naRef* args)
2325 flightgear::Waypt* w = wayptGhost(me);
2327 naRuntimeError(c, "waypoint.navaid called on non-waypoint object");
2330 FGPositioned* pos = w->source();
2335 switch (pos->type()) {
2336 case FGPositioned::VOR:
2337 case FGPositioned::NDB:
2338 case FGPositioned::ILS:
2339 case FGPositioned::LOC:
2340 case FGPositioned::GS:
2341 case FGPositioned::DME:
2342 case FGPositioned::TACAN: {
2343 FGNavRecord* nav = (FGNavRecord*) pos;
2344 return ghostForNavaid(c, nav);
2352 static naRef f_waypoint_airport(naContext c, naRef me, int argc, naRef* args)
2354 flightgear::Waypt* w = wayptGhost(me);
2356 naRuntimeError(c, "waypoint.navaid called on non-waypoint object");
2359 FGPositioned* pos = w->source();
2360 if (!pos || FGAirport::isAirportType(pos)) {
2364 return ghostForAirport(c, (FGAirport*) pos);
2367 static naRef f_waypoint_runway(naContext c, naRef me, int argc, naRef* args)
2369 flightgear::Waypt* w = wayptGhost(me);
2371 naRuntimeError(c, "waypoint.navaid called on non-waypoint object");
2374 FGPositioned* pos = w->source();
2375 if (!pos || (pos->type() != FGPositioned::RUNWAY)) {
2379 return ghostForRunway(c, (FGRunway*) pos);
2382 static naRef f_procedure_transition(naContext c, naRef me, int argc, naRef* args)
2384 Procedure* proc = procedureGhost(me);
2386 naRuntimeError(c, "procedure.transition called on non-procedure object");
2389 if ((proc->type() != PROCEDURE_SID) && (proc->type() != PROCEDURE_STAR)) {
2390 naRuntimeError(c, "procedure.transition called on non-SID or -STAR");
2393 ArrivalDeparture* ad = (ArrivalDeparture*) proc;
2394 Transition* trans = ad->findTransitionByName(naStr_data(args[0]));
2396 return ghostForProcedure(c, trans);
2399 static naRef f_procedure_route(naContext c, naRef me, int argc, naRef* args)
2401 Procedure* proc = procedureGhost(me);
2403 naRuntimeError(c, "procedure.route called on non-procedure object");
2406 // wrapping up tow different routines here - approach routing from the IAF
2407 // to the associated runway, and SID/STAR routing via an enroute transition
2408 // and possibly a runway transition or not.
2409 if (Approach::isApproach(proc->type())) {
2412 iaf = wayptFromArg(args[0]);
2416 Approach* app = (Approach*) proc;
2417 if (!app->route(iaf, r)) {
2421 return convertWayptVecToNasal(c, r);
2422 } else if ((proc->type() != PROCEDURE_SID) && (proc->type() != PROCEDURE_STAR)) {
2423 naRuntimeError(c, "procedure.route called on unsuitable procedure type");
2427 FGRunway* rwy = runwayGhost(args[0]);
2428 if (rwy) ++argOffset;
2430 ArrivalDeparture* ad = (ArrivalDeparture*) proc;
2431 Transition* trans = NULL;
2432 if (argOffset < argc) {
2433 trans = (Transition*) procedureGhost(args[argOffset]);
2436 // note either runway or trans may be NULL - that's ok
2438 if (!ad->route(rwy, trans, r)) {
2439 SG_LOG(SG_NASAL, SG_WARN, "prcoedure.route failed for ArrvialDeparture somehow");
2443 return convertWayptVecToNasal(c, r);
2447 // Table of extension functions. Terminate with zeros.
2448 static struct { const char* name; naCFunction func; } funcs[] = {
2449 { "carttogeod", f_carttogeod },
2450 { "geodtocart", f_geodtocart },
2451 { "geodinfo", f_geodinfo },
2452 { "airportinfo", f_airportinfo },
2453 { "findAirportsWithinRange", f_findAirportsWithinRange },
2454 { "findAirportsByICAO", f_findAirportsByICAO },
2455 { "navinfo", f_navinfo },
2456 { "findNavaidsWithinRange", f_findNavaidsWithinRange },
2457 { "findNavaidByFrequency", f_findNavaidByFrequency },
2458 { "findNavaidsByFrequency", f_findNavaidsByFrequency },
2459 { "findNavaidsByID", f_findNavaidsByIdent },
2460 { "findFixesByID", f_findFixesByIdent },
2461 { "flightplan", f_route },
2462 { "registerFlightPlanDelegate", f_registerFPDelegate },
2463 { "createWP", f_createWP },
2464 { "createWPFrom", f_createWPFrom },
2465 { "airwaysRoute", f_airwaySearch },
2466 { "magvar", f_magvar },
2467 { "courseAndDistance", f_courseAndDistance },
2468 { "greatCircleMove", f_greatCircleMove },
2469 { "tileIndex", f_tileIndex },
2470 { "tilePath", f_tilePath },
2475 naRef initNasalPositioned(naRef globals, naContext c)
2477 airportPrototype = naNewHash(c);
2478 naSave(c, airportPrototype);
2480 hashset(c, airportPrototype, "runway", naNewFunc(c, naNewCCode(c, f_airport_runway)));
2481 hashset(c, airportPrototype, "runwaysWithoutReciprocals", naNewFunc(c, naNewCCode(c, f_airport_runwaysWithoutReciprocals)));
2482 hashset(c, airportPrototype, "helipad", naNewFunc(c, naNewCCode(c, f_airport_runway)));
2483 hashset(c, airportPrototype, "tower", naNewFunc(c, naNewCCode(c, f_airport_tower)));
2484 hashset(c, airportPrototype, "comms", naNewFunc(c, naNewCCode(c, f_airport_comms)));
2485 hashset(c, airportPrototype, "sids", naNewFunc(c, naNewCCode(c, f_airport_sids)));
2486 hashset(c, airportPrototype, "stars", naNewFunc(c, naNewCCode(c, f_airport_stars)));
2487 hashset(c, airportPrototype, "getApproachList", naNewFunc(c, naNewCCode(c, f_airport_approaches)));
2488 hashset(c, airportPrototype, "parking", naNewFunc(c, naNewCCode(c, f_airport_parking)));
2489 hashset(c, airportPrototype, "getSid", naNewFunc(c, naNewCCode(c, f_airport_getSid)));
2490 hashset(c, airportPrototype, "getStar", naNewFunc(c, naNewCCode(c, f_airport_getStar)));
2491 hashset(c, airportPrototype, "getIAP", naNewFunc(c, naNewCCode(c, f_airport_getApproach)));
2492 hashset(c, airportPrototype, "findBestRunwayForPos", naNewFunc(c, naNewCCode(c, f_airport_findBestRunway)));
2493 hashset(c, airportPrototype, "tostring", naNewFunc(c, naNewCCode(c, f_airport_toString)));
2495 flightplanPrototype = naNewHash(c);
2496 naSave(c, flightplanPrototype);
2498 hashset(c, flightplanPrototype, "getWP", naNewFunc(c, naNewCCode(c, f_flightplan_getWP)));
2499 hashset(c, flightplanPrototype, "currentWP", naNewFunc(c, naNewCCode(c, f_flightplan_currentWP)));
2500 hashset(c, flightplanPrototype, "nextWP", naNewFunc(c, naNewCCode(c, f_flightplan_nextWP)));
2501 hashset(c, flightplanPrototype, "getPlanSize", naNewFunc(c, naNewCCode(c, f_flightplan_numWaypoints)));
2502 hashset(c, flightplanPrototype, "appendWP", naNewFunc(c, naNewCCode(c, f_flightplan_appendWP)));
2503 hashset(c, flightplanPrototype, "insertWP", naNewFunc(c, naNewCCode(c, f_flightplan_insertWP)));
2504 hashset(c, flightplanPrototype, "deleteWP", naNewFunc(c, naNewCCode(c, f_flightplan_deleteWP)));
2505 hashset(c, flightplanPrototype, "insertWPAfter", naNewFunc(c, naNewCCode(c, f_flightplan_insertWPAfter)));
2506 hashset(c, flightplanPrototype, "insertWaypoints", naNewFunc(c, naNewCCode(c, f_flightplan_insertWaypoints)));
2507 hashset(c, flightplanPrototype, "cleanPlan", naNewFunc(c, naNewCCode(c, f_flightplan_clearPlan)));
2508 hashset(c, flightplanPrototype, "clearWPType", naNewFunc(c, naNewCCode(c, f_flightplan_clearWPType)));
2509 hashset(c, flightplanPrototype, "clone", naNewFunc(c, naNewCCode(c, f_flightplan_clone)));
2510 hashset(c, flightplanPrototype, "pathGeod", naNewFunc(c, naNewCCode(c, f_flightplan_pathGeod)));
2511 hashset(c, flightplanPrototype, "finish", naNewFunc(c, naNewCCode(c, f_flightplan_finish)));
2512 hashset(c, flightplanPrototype, "indexOfWP", naNewFunc(c, naNewCCode(c, f_flightplan_indexOfWp)));
2514 waypointPrototype = naNewHash(c);
2515 naSave(c, waypointPrototype);
2517 hashset(c, waypointPrototype, "navaid", naNewFunc(c, naNewCCode(c, f_waypoint_navaid)));
2518 hashset(c, waypointPrototype, "runway", naNewFunc(c, naNewCCode(c, f_waypoint_runway)));
2519 hashset(c, waypointPrototype, "airport", naNewFunc(c, naNewCCode(c, f_waypoint_airport)));
2521 procedurePrototype = naNewHash(c);
2522 naSave(c, procedurePrototype);
2523 hashset(c, procedurePrototype, "transition", naNewFunc(c, naNewCCode(c, f_procedure_transition)));
2524 hashset(c, procedurePrototype, "route", naNewFunc(c, naNewCCode(c, f_procedure_route)));
2526 fpLegPrototype = naNewHash(c);
2527 naSave(c, fpLegPrototype);
2528 hashset(c, fpLegPrototype, "setSpeed", naNewFunc(c, naNewCCode(c, f_leg_setSpeed)));
2529 hashset(c, fpLegPrototype, "setAltitude", naNewFunc(c, naNewCCode(c, f_leg_setAltitude)));
2530 hashset(c, fpLegPrototype, "path", naNewFunc(c, naNewCCode(c, f_leg_path)));
2531 hashset(c, fpLegPrototype, "courseAndDistanceFrom", naNewFunc(c, naNewCCode(c, f_leg_courseAndDistanceFrom)));
2533 for(int i=0; funcs[i].name; i++) {
2534 hashset(c, globals, funcs[i].name,
2535 naNewFunc(c, naNewCCode(c, funcs[i].func)));
2541 void postinitNasalPositioned(naRef globals, naContext c)
2543 naRef geoModule = naHash_cget(globals, (char*) "geo");
2544 if (naIsNil(geoModule)) {
2545 SG_LOG(SG_GENERAL, SG_WARN, "postinitNasalPositioned: geo.nas not loaded");
2549 geoCoordClass = naHash_cget(geoModule, (char*) "Coord");