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>
32 #include <simgear/sg_inlines.h>
33 #include <simgear/scene/material/mat.hxx>
34 #include <simgear/magvar/magvar.hxx>
35 #include <simgear/timing/sg_time.hxx>
36 #include <simgear/bucket/newbucket.hxx>
38 #include <Airports/runways.hxx>
39 #include <Airports/simple.hxx>
40 #include <Airports/dynamics.hxx>
41 #include <Airports/parking.hxx>
42 #include <Navaids/navlist.hxx>
43 #include <Navaids/procedure.hxx>
44 #include <Main/globals.hxx>
45 #include <Main/fg_props.hxx>
46 #include <Scenery/scenery.hxx>
47 #include <ATC/CommStation.hxx>
48 #include <Navaids/route.hxx>
49 #include <Navaids/waypoint.hxx>
50 #include <Autopilot/route_mgr.hxx>
51 #include <Navaids/procedure.hxx>
52 #include <Navaids/airways.hxx>
54 using namespace flightgear;
56 static void positionedGhostDestroy(void* g);
57 static void wayptGhostDestroy(void* g);
58 static void legGhostDestroy(void* g);
59 static void routeBaseGhostDestroy(void* g);
61 naGhostType PositionedGhostType = { positionedGhostDestroy, "positioned" };
63 static const char* airportGhostGetMember(naContext c, void* g, naRef field, naRef* out);
64 naGhostType AirportGhostType = { positionedGhostDestroy, "airport", airportGhostGetMember, 0 };
66 static const char* navaidGhostGetMember(naContext c, void* g, naRef field, naRef* out);
67 naGhostType NavaidGhostType = { positionedGhostDestroy, "navaid", navaidGhostGetMember, 0 };
69 static const char* runwayGhostGetMember(naContext c, void* g, naRef field, naRef* out);
70 naGhostType RunwayGhostType = { positionedGhostDestroy, "runway", runwayGhostGetMember, 0 };
72 static const char* wayptGhostGetMember(naContext c, void* g, naRef field, naRef* out);
73 naGhostType WayptGhostType = { wayptGhostDestroy,
78 static const char* legGhostGetMember(naContext c, void* g, naRef field, naRef* out);
79 naGhostType FPLegGhostType = { legGhostDestroy,
84 static const char* flightplanGhostGetMember(naContext c, void* g, naRef field, naRef* out);
85 static void flightplanGhostSetMember(naContext c, void* g, naRef field, naRef value);
87 naGhostType FlightPlanGhostType = { routeBaseGhostDestroy,
89 flightplanGhostGetMember,
90 flightplanGhostSetMember
93 static const char* procedureGhostGetMember(naContext c, void* g, naRef field, naRef* out);
94 naGhostType ProcedureGhostType = { routeBaseGhostDestroy,
96 procedureGhostGetMember,
99 static void hashset(naContext c, naRef hash, const char* key, naRef val)
101 naRef s = naNewString(c);
102 naStr_fromdata(s, (char*)key, strlen(key));
103 naHash_set(hash, s, val);
106 static naRef stringToNasal(naContext c, const std::string& s)
108 return naStr_fromdata(naNewString(c),
109 const_cast<char *>(s.c_str()),
113 static FGPositioned* positionedGhost(naRef r)
115 if ((naGhost_type(r) == &AirportGhostType) ||
116 (naGhost_type(r) == &NavaidGhostType) ||
117 (naGhost_type(r) == &RunwayGhostType))
119 return (FGPositioned*) naGhost_ptr(r);
125 static FGAirport* airportGhost(naRef r)
127 if (naGhost_type(r) == &AirportGhostType)
128 return (FGAirport*) naGhost_ptr(r);
132 static FGNavRecord* navaidGhost(naRef r)
134 if (naGhost_type(r) == &NavaidGhostType)
135 return (FGNavRecord*) naGhost_ptr(r);
139 static FGRunway* runwayGhost(naRef r)
141 if (naGhost_type(r) == &RunwayGhostType)
142 return (FGRunway*) naGhost_ptr(r);
146 static void positionedGhostDestroy(void* g)
148 FGPositioned* pos = (FGPositioned*)g;
149 if (!FGPositioned::put(pos)) // unref
153 static Waypt* wayptGhost(naRef r)
155 if (naGhost_type(r) == &WayptGhostType)
156 return (Waypt*) naGhost_ptr(r);
158 if (naGhost_type(r) == &FPLegGhostType) {
159 FlightPlan::Leg* leg = (FlightPlan::Leg*) naGhost_ptr(r);
160 return leg->waypoint();
166 static void wayptGhostDestroy(void* g)
168 Waypt* wpt = (Waypt*)g;
169 if (!Waypt::put(wpt)) // unref
173 static void legGhostDestroy(void* g)
179 static FlightPlan::Leg* fpLegGhost(naRef r)
181 if (naGhost_type(r) == &FPLegGhostType)
182 return (FlightPlan::Leg*) naGhost_ptr(r);
186 static Procedure* procedureGhost(naRef r)
188 if (naGhost_type(r) == &ProcedureGhostType)
189 return (Procedure*) naGhost_ptr(r);
193 static FlightPlan* flightplanGhost(naRef r)
195 if (naGhost_type(r) == &FlightPlanGhostType)
196 return (FlightPlan*) naGhost_ptr(r);
200 static void routeBaseGhostDestroy(void* g)
205 static naRef airportPrototype;
206 static naRef flightplanPrototype;
207 static naRef waypointPrototype;
208 static naRef geoCoordClass;
209 static naRef fpLegPrototype;
210 static naRef procedurePrototype;
212 naRef ghostForAirport(naContext c, const FGAirport* apt)
218 FGPositioned::get(apt); // take a ref
219 return naNewGhost2(c, &AirportGhostType, (void*) apt);
222 naRef ghostForNavaid(naContext c, const FGNavRecord* n)
228 FGPositioned::get(n); // take a ref
229 return naNewGhost2(c, &NavaidGhostType, (void*) n);
232 naRef ghostForRunway(naContext c, const FGRunway* r)
238 FGPositioned::get(r); // take a ref
239 return naNewGhost2(c, &RunwayGhostType, (void*) r);
242 naRef ghostForWaypt(naContext c, const Waypt* wpt)
248 Waypt::get(wpt); // take a ref
249 return naNewGhost2(c, &WayptGhostType, (void*) wpt);
252 naRef ghostForLeg(naContext c, const FlightPlan::Leg* leg)
258 return naNewGhost2(c, &FPLegGhostType, (void*) leg);
261 naRef ghostForFlightPlan(naContext c, const FlightPlan* fp)
267 return naNewGhost2(c, &FlightPlanGhostType, (void*) fp);
270 naRef ghostForProcedure(naContext c, const Procedure* proc)
276 return naNewGhost2(c, &ProcedureGhostType, (void*) proc);
279 static const char* airportGhostGetMember(naContext c, void* g, naRef field, naRef* out)
281 const char* fieldName = naStr_data(field);
282 FGAirport* apt = (FGAirport*) g;
284 if (!strcmp(fieldName, "parents")) {
285 *out = naNewVector(c);
286 naVec_append(*out, airportPrototype);
287 } else if (!strcmp(fieldName, "id")) *out = stringToNasal(c, apt->ident());
288 else if (!strcmp(fieldName, "name")) *out = stringToNasal(c, apt->name());
289 else if (!strcmp(fieldName, "lat")) *out = naNum(apt->getLatitude());
290 else if (!strcmp(fieldName, "lon")) *out = naNum(apt->getLongitude());
291 else if (!strcmp(fieldName, "elevation")) {
292 *out = naNum(apt->getElevation() * SG_FEET_TO_METER);
293 } else if (!strcmp(fieldName, "has_metar")) {
294 *out = naNum(apt->getMetar());
295 } else if (!strcmp(fieldName, "runways")) {
297 for(unsigned int r=0; r<apt->numRunways(); ++r) {
298 FGRunway* rwy(apt->getRunwayByIndex(r));
299 naRef rwyid = stringToNasal(c, rwy->ident());
300 naRef rwydata = ghostForRunway(c, rwy);
301 naHash_set(*out, rwyid, rwydata);
311 static const char* waypointCommonGetMember(naContext c, Waypt* wpt, const char* fieldName, naRef* out)
313 if (!strcmp(fieldName, "wp_name")) *out = stringToNasal(c, wpt->ident());
314 else if (!strcmp(fieldName, "wp_type")) *out = stringToNasal(c, wpt->type());
315 else if (!strcmp(fieldName, "wp_lat")) *out = naNum(wpt->position().getLatitudeDeg());
316 else if (!strcmp(fieldName, "wp_lon")) *out = naNum(wpt->position().getLongitudeDeg());
317 else if (!strcmp(fieldName, "wp_parent_name")) {
318 Procedure* proc = dynamic_cast<Procedure*>(wpt->owner());
319 *out = proc ? stringToNasal(c, proc->ident()) : naNil();
320 } else if (!strcmp(fieldName, "wp_parent")) {
321 Procedure* proc = dynamic_cast<Procedure*>(wpt->owner());
322 *out = ghostForProcedure(c, proc);
323 } else if (!strcmp(fieldName, "fly_type")) {
324 if (wpt->type() == "hold") {
325 *out = stringToNasal(c, "Hold");
327 *out = stringToNasal(c, wpt->flag(WPT_OVERFLIGHT) ? "flyOver" : "flyBy");
330 return NULL; // member not found
336 static const char* wayptGhostGetMember(naContext c, void* g, naRef field, naRef* out)
338 const char* fieldName = naStr_data(field);
339 Waypt* wpt = (flightgear::Waypt*) g;
340 return waypointCommonGetMember(c, wpt, fieldName, out);
343 static RouteRestriction routeRestrictionFromString(const char* s)
347 if (u == "computed") return RESTRICT_COMPUTED;
348 if (u == "at") return RESTRICT_AT;
349 if (u == "mach") return SPEED_RESTRICT_MACH;
350 if (u == "computed-mach") return SPEED_COMPUTED_MACH;
351 if (u == "delete") return RESTRICT_DELETE;
352 return RESTRICT_NONE;
355 naRef routeRestrictionToNasal(naContext c, RouteRestriction rr)
358 case RESTRICT_NONE: return naNil();
359 case RESTRICT_AT: return stringToNasal(c, "at");
360 case RESTRICT_ABOVE: return stringToNasal(c, "above");
361 case RESTRICT_BELOW: return stringToNasal(c, "below");
362 case SPEED_RESTRICT_MACH: return stringToNasal(c, "mach");
363 case RESTRICT_COMPUTED: return stringToNasal(c, "computed");
364 case SPEED_COMPUTED_MACH: return stringToNasal(c, "computed-mach");
365 case RESTRICT_DELETE: return stringToNasal(c, "delete");
371 static const char* legGhostGetMember(naContext c, void* g, naRef field, naRef* out)
373 const char* fieldName = naStr_data(field);
374 FlightPlan::Leg* leg = (FlightPlan::Leg*) g;
375 Waypt* wpt = leg->waypoint();
377 if (!strcmp(fieldName, "parents")) {
378 *out = naNewVector(c);
379 naVec_append(*out, fpLegPrototype);
380 } else if (!strcmp(fieldName, "alt_cstr")) {
381 *out = naNum(leg->altitudeFt());
382 } else if (!strcmp(fieldName, "alt_cstr_type")) {
383 *out = routeRestrictionToNasal(c, leg->altitudeRestriction());
384 } else if (!strcmp(fieldName, "speed_cstr")) {
385 double s = isMachRestrict(leg->speedRestriction()) ? leg->speedMach() : leg->speedKts();
387 } else if (!strcmp(fieldName, "speed_cstr_type")) {
388 *out = routeRestrictionToNasal(c, leg->speedRestriction());
389 } else if (!strcmp(fieldName, "leg_distance")) {
390 *out = naNum(leg->distanceNm());
391 } else if (!strcmp(fieldName, "leg_bearing")) {
392 *out = naNum(leg->courseDeg());
393 } else if (!strcmp(fieldName, "distance_along_route")) {
394 *out = naNum(leg->distanceAlongRoute());
395 } else { // check for fields defined on the underlying waypoint
396 return waypointCommonGetMember(c, wpt, fieldName, out);
399 return ""; // success
402 static const char* flightplanGhostGetMember(naContext c, void* g, naRef field, naRef* out)
404 const char* fieldName = naStr_data(field);
405 FlightPlan* fp = (FlightPlan*) g;
407 if (!strcmp(fieldName, "parents")) {
408 *out = naNewVector(c);
409 naVec_append(*out, flightplanPrototype);
410 } else if (!strcmp(fieldName, "id")) *out = stringToNasal(c, fp->ident());
411 else if (!strcmp(fieldName, "departure")) *out = ghostForAirport(c, fp->departureAirport());
412 else if (!strcmp(fieldName, "destination")) *out = ghostForAirport(c, fp->destinationAirport());
413 else if (!strcmp(fieldName, "departure_runway")) *out = ghostForRunway(c, fp->departureRunway());
414 else if (!strcmp(fieldName, "destination_runway")) *out = ghostForRunway(c, fp->destinationRunway());
415 else if (!strcmp(fieldName, "sid")) *out = ghostForProcedure(c, fp->sid());
416 else if (!strcmp(fieldName, "sid_trans")) *out = ghostForProcedure(c, fp->sidTransition());
417 else if (!strcmp(fieldName, "star")) *out = ghostForProcedure(c, fp->star());
418 else if (!strcmp(fieldName, "star_trans")) *out = ghostForProcedure(c, fp->starTransition());
419 else if (!strcmp(fieldName, "approach")) *out = ghostForProcedure(c, fp->approach());
420 else if (!strcmp(fieldName, "current")) *out = naNum(fp->currentIndex());
428 static void flightplanGhostSetMember(naContext c, void* g, naRef field, naRef value)
430 const char* fieldName = naStr_data(field);
431 FlightPlan* fp = (FlightPlan*) g;
433 if (!strcmp(fieldName, "id")) {
434 if (!naIsString(value)) naRuntimeError(c, "flightplan.id must be a string");
435 fp->setIdent(naStr_data(value));
436 } else if (!strcmp(fieldName, "current")) {
437 int index = value.num;
438 if ((index < 0) || (index >= fp->numLegs())) {
441 fp->setCurrentIndex(index);
442 } else if (!strcmp(fieldName, "departure")) {
443 FGAirport* apt = airportGhost(value);
445 fp->setDeparture(apt);
449 FGRunway* rwy = runwayGhost(value);
451 fp->setDeparture(rwy);
455 naRuntimeError(c, "bad argument type setting departure");
456 } else if (!strcmp(fieldName, "destination")) {
457 FGAirport* apt = airportGhost(value);
459 fp->setDestination(apt);
463 FGRunway* rwy = runwayGhost(value);
465 fp->setDestination(rwy);
469 naRuntimeError(c, "bad argument type setting destination");
470 } else if (!strcmp(fieldName, "departure_runway")) {
471 FGRunway* rwy = runwayGhost(value);
473 fp->setDeparture(rwy);
477 naRuntimeError(c, "bad argument type setting departure");
478 } else if (!strcmp(fieldName, "destination_runway")) {
479 FGRunway* rwy = runwayGhost(value);
481 fp->setDestination(rwy);
485 naRuntimeError(c, "bad argument type setting departure");
486 } else if (!strcmp(fieldName, "sid")) {
487 Procedure* proc = procedureGhost(value);
488 if (proc && (proc->type() == PROCEDURE_SID)) {
489 fp->setSID((flightgear::SID*) proc);
492 // allow a SID transition to be set, implicitly include the SID itself
493 if (proc && (proc->type() == PROCEDURE_TRANSITION)) {
494 fp->setSID((Transition*) proc);
498 if (naIsString(value)) {
499 FGAirport* apt = fp->departureAirport();
500 fp->setSID(apt->findSIDWithIdent(naStr_data(value)));
504 naRuntimeError(c, "bad argument type setting SID");
505 } else if (!strcmp(fieldName, "star")) {
506 Procedure* proc = procedureGhost(value);
507 if (proc && (proc->type() == PROCEDURE_STAR)) {
508 fp->setSTAR((STAR*) proc);
512 if (proc && (proc->type() == PROCEDURE_TRANSITION)) {
513 fp->setSTAR((Transition*) proc);
517 if (naIsString(value)) {
518 FGAirport* apt = fp->destinationAirport();
519 fp->setSTAR(apt->findSTARWithIdent(naStr_data(value)));
523 naRuntimeError(c, "bad argument type setting STAR");
524 } else if (!strcmp(fieldName, "approach")) {
525 Procedure* proc = procedureGhost(value);
526 if (proc && Approach::isApproach(proc->type())) {
527 fp->setApproach((Approach*) proc);
531 if (naIsString(value)) {
532 FGAirport* apt = fp->destinationAirport();
533 fp->setApproach(apt->findApproachWithIdent(naStr_data(value)));
537 naRuntimeError(c, "bad argument type setting approach");
542 static naRef procedureTpType(naContext c, ProcedureType ty)
545 case PROCEDURE_SID: return stringToNasal(c, "sid");
546 case PROCEDURE_STAR: return stringToNasal(c, "star");
547 case PROCEDURE_APPROACH_VOR:
548 case PROCEDURE_APPROACH_ILS:
549 case PROCEDURE_APPROACH_RNAV:
550 case PROCEDURE_APPROACH_NDB:
551 return stringToNasal(c, "IAP");
557 static naRef procedureRadioType(naContext c, ProcedureType ty)
560 case PROCEDURE_APPROACH_VOR: return stringToNasal(c, "VOR");
561 case PROCEDURE_APPROACH_ILS: return stringToNasal(c, "ILS");
562 case PROCEDURE_APPROACH_RNAV: return stringToNasal(c, "RNAV");
563 case PROCEDURE_APPROACH_NDB: return stringToNasal(c, "NDB");
569 static const char* procedureGhostGetMember(naContext c, void* g, naRef field, naRef* out)
571 const char* fieldName = naStr_data(field);
572 Procedure* proc = (Procedure*) g;
574 if (!strcmp(fieldName, "parents")) {
575 *out = naNewVector(c);
576 naVec_append(*out, procedurePrototype);
577 } else if (!strcmp(fieldName, "id")) *out = stringToNasal(c, proc->ident());
578 else if (!strcmp(fieldName, "airport")) *out = ghostForAirport(c, proc->airport());
579 else if (!strcmp(fieldName, "tp_type")) *out = procedureTpType(c, proc->type());
580 else if (!strcmp(fieldName, "radio")) *out = procedureRadioType(c, proc->type());
581 else if (!strcmp(fieldName, "runways")) {
582 *out = naNewVector(c);
583 BOOST_FOREACH(FGRunwayPtr rwy, proc->runways()) {
584 naVec_append(*out, stringToNasal(c, rwy->ident()));
586 } else if (!strcmp(fieldName, "transitions")) {
587 if ((proc->type() != PROCEDURE_SID) && (proc->type() != PROCEDURE_STAR)) {
592 ArrivalDeparture* ad = static_cast<ArrivalDeparture*>(proc);
593 *out = naNewVector(c);
594 BOOST_FOREACH(string id, ad->transitionIdents()) {
595 naVec_append(*out, stringToNasal(c, id));
604 static const char* runwayGhostGetMember(naContext c, void* g, naRef field, naRef* out)
606 const char* fieldName = naStr_data(field);
607 FGRunway* rwy = (FGRunway*) g;
609 if (!strcmp(fieldName, "id")) *out = stringToNasal(c, rwy->ident());
610 else if (!strcmp(fieldName, "lat")) *out = naNum(rwy->latitude());
611 else if (!strcmp(fieldName, "lon")) *out = naNum(rwy->longitude());
612 else if (!strcmp(fieldName, "heading")) *out = naNum(rwy->headingDeg());
613 else if (!strcmp(fieldName, "length")) *out = naNum(rwy->lengthM());
614 else if (!strcmp(fieldName, "width")) *out = naNum(rwy->widthM());
615 else if (!strcmp(fieldName, "threshold")) *out = naNum(rwy->displacedThresholdM());
616 else if (!strcmp(fieldName, "stopway")) *out = naNum(rwy->stopwayM());
617 else if (!strcmp(fieldName, "ils_frequency_mhz")) {
618 *out = rwy->ILS() ? naNum(rwy->ILS()->get_freq() / 100.0) : naNil();
619 } else if (!strcmp(fieldName, "ils")) {
620 *out = ghostForNavaid(c, rwy->ILS());
628 static const char* navaidGhostGetMember(naContext c, void* g, naRef field, naRef* out)
630 const char* fieldName = naStr_data(field);
631 FGNavRecord* nav = (FGNavRecord*) g;
633 if (!strcmp(fieldName, "id")) *out = stringToNasal(c, nav->ident());
634 else if (!strcmp(fieldName, "name")) *out = stringToNasal(c, nav->name());
635 else if (!strcmp(fieldName, "lat")) *out = naNum(nav->get_lat());
636 else if (!strcmp(fieldName, "lon")) *out = naNum(nav->get_lon());
637 else if (!strcmp(fieldName, "elevation")) {
638 *out = naNum(nav->get_elev_ft() * SG_FEET_TO_METER);
639 } else if (!strcmp(fieldName, "type")) {
640 *out = stringToNasal(c, nav->nameForType(nav->type()));
641 } else if (!strcmp(fieldName, "frequency")) {
642 *out = naNum(nav->get_freq());
643 } else if (!strcmp(fieldName, "range_nm")) {
644 *out = naNum(nav->get_range());
645 } else if (!strcmp(fieldName, "course")) {
646 if ((nav->type() == FGPositioned::ILS) || (nav->type() == FGPositioned::LOC)) {
647 double radial = nav->get_multiuse();
648 SG_NORMALIZE_RANGE(radial, 0.0, 360.0);
649 *out = naNum(radial);
660 static bool hashIsCoord(naRef h)
662 naRef parents = naHash_cget(h, (char*) "parents");
663 if (!naIsVector(parents)) {
667 return naEqual(naVec_get(parents, 0), geoCoordClass);
670 bool geodFromHash(naRef ref, SGGeod& result)
672 if (!naIsHash(ref)) {
677 // check for manual latitude / longitude names
678 naRef lat = naHash_cget(ref, (char*) "lat");
679 naRef lon = naHash_cget(ref, (char*) "lon");
680 if (naIsNum(lat) && naIsNum(lon)) {
681 result = SGGeod::fromDeg(naNumValue(lon).num, naNumValue(lat).num);
685 if (hashIsCoord(ref)) {
686 naRef lat = naHash_cget(ref, (char*) "_lat");
687 naRef lon = naHash_cget(ref, (char*) "_lon");
688 if (naIsNum(lat) && naIsNum(lon)) {
689 result = SGGeod::fromRad(naNumValue(lon).num, naNumValue(lat).num);
694 // check for any synonyms?
695 // latitude + longitude?
700 static int geodFromArgs(naRef* args, int offset, int argc, SGGeod& result)
702 if (offset >= argc) {
706 if (naIsGhost(args[offset])) {
707 naGhostType* gt = naGhost_type(args[offset]);
708 if (gt == &AirportGhostType) {
709 result = airportGhost(args[offset])->geod();
713 if (gt == &NavaidGhostType) {
714 result = navaidGhost(args[offset])->geod();
718 if (gt == &RunwayGhostType) {
719 result = runwayGhost(args[offset])->geod();
723 if (gt == &WayptGhostType) {
724 result = wayptGhost(args[offset])->position();
729 if (geodFromHash(args[offset], result)) {
733 if (((argc - offset) >= 2) && naIsNum(args[offset]) && naIsNum(args[offset + 1])) {
734 double lat = naNumValue(args[0]).num,
735 lon = naNumValue(args[1]).num;
736 result = SGGeod::fromDeg(lon, lat);
743 // Convert a cartesian point to a geodetic lat/lon/altitude.
744 static naRef f_carttogeod(naContext c, naRef me, int argc, naRef* args)
746 double lat, lon, alt, xyz[3];
747 if(argc != 3) naRuntimeError(c, "carttogeod() expects 3 arguments");
748 for(int i=0; i<3; i++)
749 xyz[i] = naNumValue(args[i]).num;
750 sgCartToGeod(xyz, &lat, &lon, &alt);
751 lat *= SG_RADIANS_TO_DEGREES;
752 lon *= SG_RADIANS_TO_DEGREES;
753 naRef vec = naNewVector(c);
754 naVec_append(vec, naNum(lat));
755 naVec_append(vec, naNum(lon));
756 naVec_append(vec, naNum(alt));
760 // Convert a geodetic lat/lon/altitude to a cartesian point.
761 static naRef f_geodtocart(naContext c, naRef me, int argc, naRef* args)
763 if(argc != 3) naRuntimeError(c, "geodtocart() expects 3 arguments");
764 double lat = naNumValue(args[0]).num * SG_DEGREES_TO_RADIANS;
765 double lon = naNumValue(args[1]).num * SG_DEGREES_TO_RADIANS;
766 double alt = naNumValue(args[2]).num;
768 sgGeodToCart(lat, lon, alt, xyz);
769 naRef vec = naNewVector(c);
770 naVec_append(vec, naNum(xyz[0]));
771 naVec_append(vec, naNum(xyz[1]));
772 naVec_append(vec, naNum(xyz[2]));
776 // For given geodetic point return array with elevation, and a material data
777 // hash, or nil if there's no information available (tile not loaded). If
778 // information about the material isn't available, then nil is returned instead
780 static naRef f_geodinfo(naContext c, naRef me, int argc, naRef* args)
782 #define HASHSET(s,l,n) naHash_set(matdata, naStr_fromdata(naNewString(c),s,l),n)
783 if(argc < 2 || argc > 3)
784 naRuntimeError(c, "geodinfo() expects 2 or 3 arguments: lat, lon [, maxalt]");
785 double lat = naNumValue(args[0]).num;
786 double lon = naNumValue(args[1]).num;
787 double elev = argc == 3 ? naNumValue(args[2]).num : 10000;
788 const SGMaterial *mat;
789 SGGeod geod = SGGeod::fromDegM(lon, lat, elev);
790 if(!globals->get_scenery()->get_elevation_m(geod, elev, &mat))
792 naRef vec = naNewVector(c);
793 naVec_append(vec, naNum(elev));
794 naRef matdata = naNil();
796 matdata = naNewHash(c);
797 naRef names = naNewVector(c);
798 BOOST_FOREACH(const std::string& n, mat->get_names())
799 naVec_append(names, stringToNasal(c, n));
801 HASHSET("names", 5, names);
802 HASHSET("solid", 5, naNum(mat->get_solid()));
803 HASHSET("friction_factor", 15, naNum(mat->get_friction_factor()));
804 HASHSET("rolling_friction", 16, naNum(mat->get_rolling_friction()));
805 HASHSET("load_resistance", 15, naNum(mat->get_load_resistance()));
806 HASHSET("bumpiness", 9, naNum(mat->get_bumpiness()));
807 HASHSET("light_coverage", 14, naNum(mat->get_light_coverage()));
809 naVec_append(vec, matdata);
815 class AirportInfoFilter : public FGAirport::AirportFilter
818 AirportInfoFilter() : type(FGPositioned::AIRPORT) {
821 bool fromArg(naRef arg)
823 const char *s = naStr_data(arg);
824 if(!strcmp(s, "airport")) type = FGPositioned::AIRPORT;
825 else if(!strcmp(s, "seaport")) type = FGPositioned::SEAPORT;
826 else if(!strcmp(s, "heliport")) type = FGPositioned::HELIPORT;
833 virtual FGPositioned::Type minType() const {
837 virtual FGPositioned::Type maxType() const {
841 FGPositioned::Type type;
844 // Returns data hash for particular or nearest airport of a <type>, or nil
847 // airportinfo(<id>); e.g. "KSFO"
848 // airportinfo(<type>); type := ("airport"|"seaport"|"heliport")
849 // airportinfo() same as airportinfo("airport")
850 // airportinfo(<lat>, <lon> [, <type>]);
851 static naRef f_airportinfo(naContext c, naRef me, int argc, naRef* args)
853 SGGeod pos = globals->get_aircraft_position();
854 FGAirport* apt = NULL;
856 if(argc >= 2 && naIsNum(args[0]) && naIsNum(args[1])) {
857 pos = SGGeod::fromDeg(args[1].num, args[0].num);
862 double maxRange = 10000.0; // expose this? or pick a smaller value?
864 AirportInfoFilter filter; // defaults to airports only
867 // fall through and use AIRPORT
868 } else if(argc == 1 && naIsString(args[0])) {
869 if (filter.fromArg(args[0])) {
872 // user provided an <id>, hopefully
873 apt = FGAirport::findByIdent(naStr_data(args[0]));
875 // return nil here, but don't raise a runtime error; this is a
876 // legitamate way to validate an ICAO code, for example in a
877 // dialog box or similar.
882 naRuntimeError(c, "airportinfo() with invalid function arguments");
887 apt = FGAirport::findClosest(pos, maxRange, &filter);
888 if(!apt) return naNil();
891 return ghostForAirport(c, apt);
894 static naRef f_findAirportsWithinRange(naContext c, naRef me, int argc, naRef* args)
897 SGGeod pos = globals->get_aircraft_position();
898 argOffset += geodFromArgs(args, 0, argc, pos);
900 if (!naIsNum(args[argOffset])) {
901 naRuntimeError(c, "findAirportsWithinRange expected range (in nm) as arg %d", argOffset);
904 AirportInfoFilter filter; // defaults to airports only
905 double rangeNm = args[argOffset++].num;
906 if (argOffset < argc) {
907 filter.fromArg(args[argOffset++]);
910 naRef r = naNewVector(c);
912 FGPositioned::List apts = FGPositioned::findWithinRange(pos, rangeNm, &filter);
913 FGPositioned::sortByRange(apts, pos);
915 BOOST_FOREACH(FGPositionedRef a, apts) {
916 FGAirport* apt = (FGAirport*) a.get();
917 naVec_append(r, ghostForAirport(c, apt));
923 static naRef f_findAirportsByICAO(naContext c, naRef me, int argc, naRef* args)
925 if (!naIsString(args[0])) {
926 naRuntimeError(c, "findAirportsByICAO expects string as arg 0");
930 string prefix(naStr_data(args[argOffset++]));
931 AirportInfoFilter filter; // defaults to airports only
932 if (argOffset < argc) {
933 filter.fromArg(args[argOffset++]);
936 naRef r = naNewVector(c);
938 FGPositioned::List apts = FGPositioned::findAllWithIdent(prefix, &filter, false);
940 BOOST_FOREACH(FGPositionedRef a, apts) {
941 FGAirport* apt = (FGAirport*) a.get();
942 naVec_append(r, ghostForAirport(c, apt));
948 static naRef f_airport_tower(naContext c, naRef me, int argc, naRef* args)
950 FGAirport* apt = airportGhost(me);
952 naRuntimeError(c, "airport.tower called on non-airport object");
955 // build a hash for the tower position
956 SGGeod towerLoc = apt->getTowerLocation();
957 naRef tower = naNewHash(c);
958 hashset(c, tower, "lat", naNum(towerLoc.getLatitudeDeg()));
959 hashset(c, tower, "lon", naNum(towerLoc.getLongitudeDeg()));
960 hashset(c, tower, "elevation", naNum(towerLoc.getElevationM()));
964 static naRef f_airport_comms(naContext c, naRef me, int argc, naRef* args)
966 FGAirport* apt = airportGhost(me);
968 naRuntimeError(c, "airport.comms called on non-airport object");
970 naRef comms = naNewVector(c);
972 // if we have an explicit type, return a simple vector of frequencies
973 if (argc > 0 && naIsScalar(args[0])) {
974 std::string commName = naStr_data(args[0]);
975 FGPositioned::Type commType = FGPositioned::typeFromName(commName);
977 BOOST_FOREACH(flightgear::CommStation* comm, apt->commStationsOfType(commType)) {
978 naVec_append(comms, naNum(comm->freqMHz()));
981 // otherwise return a vector of hashes, one for each comm station.
982 BOOST_FOREACH(flightgear::CommStation* comm, apt->commStations()) {
983 naRef commHash = naNewHash(c);
984 hashset(c, commHash, "frequency", naNum(comm->freqMHz()));
985 hashset(c, commHash, "ident", stringToNasal(c, comm->ident()));
986 naVec_append(comms, commHash);
993 static naRef f_airport_runway(naContext c, naRef me, int argc, naRef* args)
995 FGAirport* apt = airportGhost(me);
997 naRuntimeError(c, "airport.runway called on non-airport object");
1000 if ((argc < 1) || !naIsString(args[0])) {
1001 naRuntimeError(c, "airport.runway expects a runway ident argument");
1004 std::string ident(naStr_data(args[0]));
1005 boost::to_upper(ident);
1006 if (!apt->hasRunwayWithIdent(ident)) {
1010 return ghostForRunway(c, apt->getRunwayByIdent(ident));
1013 static naRef f_airport_sids(naContext c, naRef me, int argc, naRef* args)
1015 FGAirport* apt = airportGhost(me);
1017 naRuntimeError(c, "airport.sids called on non-airport object");
1020 naRef sids = naNewVector(c);
1022 FGRunway* rwy = NULL;
1023 if (argc > 0 && naIsString(args[0])) {
1024 if (!apt->hasRunwayWithIdent(naStr_data(args[0]))) {
1028 rwy = apt->getRunwayByIdent(naStr_data(args[0]));
1029 } else if (argc > 0) {
1030 rwy = runwayGhost(args[0]);
1034 BOOST_FOREACH(flightgear::SID* sid, rwy->getSIDs()) {
1035 naRef procId = stringToNasal(c, sid->ident());
1036 naVec_append(sids, procId);
1039 for (unsigned int s=0; s<apt->numSIDs(); ++s) {
1040 flightgear::SID* sid = apt->getSIDByIndex(s);
1041 naRef procId = stringToNasal(c, sid->ident());
1042 naVec_append(sids, procId);
1049 static naRef f_airport_stars(naContext c, naRef me, int argc, naRef* args)
1051 FGAirport* apt = airportGhost(me);
1053 naRuntimeError(c, "airport.stars called on non-airport object");
1056 naRef stars = naNewVector(c);
1058 FGRunway* rwy = NULL;
1059 if (argc > 0 && naIsString(args[0])) {
1060 if (!apt->hasRunwayWithIdent(naStr_data(args[0]))) {
1064 rwy = apt->getRunwayByIdent(naStr_data(args[0]));
1065 } else if (argc > 0) {
1066 rwy = runwayGhost(args[0]);
1070 BOOST_FOREACH(flightgear::STAR* s, rwy->getSTARs()) {
1071 naRef procId = stringToNasal(c, s->ident());
1072 naVec_append(stars, procId);
1075 for (unsigned int s=0; s<apt->numSTARs(); ++s) {
1076 flightgear::STAR* star = apt->getSTARByIndex(s);
1077 naRef procId = stringToNasal(c, star->ident());
1078 naVec_append(stars, procId);
1085 static naRef f_airport_approaches(naContext c, naRef me, int argc, naRef* args)
1087 FGAirport* apt = airportGhost(me);
1089 naRuntimeError(c, "airport.getApproachList called on non-airport object");
1092 naRef approaches = naNewVector(c);
1094 ProcedureType ty = PROCEDURE_INVALID;
1095 if ((argc > 1) && naIsString(args[1])) {
1096 std::string u(naStr_data(args[1]));
1098 if (u == "NDB") ty = PROCEDURE_APPROACH_NDB;
1099 if (u == "VOR") ty = PROCEDURE_APPROACH_VOR;
1100 if (u == "ILS") ty = PROCEDURE_APPROACH_ILS;
1101 if (u == "RNAV") ty = PROCEDURE_APPROACH_RNAV;
1104 FGRunway* rwy = NULL;
1105 if (argc > 0 && (rwy = runwayGhost(args[0]))) {
1107 } else if (argc > 0 && naIsString(args[0])) {
1108 if (!apt->hasRunwayWithIdent(naStr_data(args[0]))) {
1112 rwy = apt->getRunwayByIdent(naStr_data(args[0]));
1116 BOOST_FOREACH(Approach* s, rwy->getApproaches()) {
1117 if ((ty != PROCEDURE_INVALID) && (s->type() != ty)) {
1121 naRef procId = stringToNasal(c, s->ident());
1122 naVec_append(approaches, procId);
1125 // no runway specified, report them all
1126 for (unsigned int s=0; s<apt->numApproaches(); ++s) {
1127 Approach* app = apt->getApproachByIndex(s);
1128 if ((ty != PROCEDURE_INVALID) && (app->type() != ty)) {
1132 naRef procId = stringToNasal(c, app->ident());
1133 naVec_append(approaches, procId);
1140 static naRef f_airport_parking(naContext c, naRef me, int argc, naRef* args)
1142 FGAirport* apt = airportGhost(me);
1144 naRuntimeError(c, "airport.parking called on non-airport object");
1147 naRef r = naNewVector(c);
1149 bool onlyAvailable = false;
1151 if (argc > 0 && naIsString(args[0])) {
1152 type = naStr_data(args[0]);
1155 if ((argc > 1) && naIsNum(args[1])) {
1156 onlyAvailable = (args[1].num != 0.0);
1159 FGAirportDynamics* dynamics = apt->getDynamics();
1160 for (int i=0; i<dynamics->getNrOfParkings(); ++i) {
1161 FGParking* park = dynamics->getParking(i);
1162 // filter out based on availability and type
1163 if (onlyAvailable && !park->isAvailable()) {
1167 if (!type.empty() && (park->getType() != type)) {
1171 naRef nm = stringToNasal(c, park->getName());
1172 naVec_append(r, nm);
1178 static naRef f_airport_getSid(naContext c, naRef me, int argc, naRef* args)
1180 FGAirport* apt = airportGhost(me);
1182 naRuntimeError(c, "airport.getSid called on non-airport object");
1185 if ((argc != 1) || !naIsString(args[0])) {
1186 naRuntimeError(c, "airport.getSid passed invalid argument");
1189 string ident = naStr_data(args[0]);
1190 return ghostForProcedure(c, apt->findSIDWithIdent(ident));
1193 static naRef f_airport_getStar(naContext c, naRef me, int argc, naRef* args)
1195 FGAirport* apt = airportGhost(me);
1197 naRuntimeError(c, "airport.getStar called on non-airport object");
1200 if ((argc != 1) || !naIsString(args[0])) {
1201 naRuntimeError(c, "airport.getStar passed invalid argument");
1204 string ident = naStr_data(args[0]);
1205 return ghostForProcedure(c, apt->findSTARWithIdent(ident));
1208 static naRef f_airport_getApproach(naContext c, naRef me, int argc, naRef* args)
1210 FGAirport* apt = airportGhost(me);
1212 naRuntimeError(c, "airport.getIAP called on non-airport object");
1215 if ((argc != 1) || !naIsString(args[0])) {
1216 naRuntimeError(c, "airport.getIAP passed invalid argument");
1219 string ident = naStr_data(args[0]);
1220 return ghostForProcedure(c, apt->findApproachWithIdent(ident));
1223 // Returns vector of data hash for navaid of a <type>, nil on error
1224 // navaids sorted by ascending distance
1225 // navinfo([<lat>,<lon>],[<type>],[<id>])
1226 // lat/lon (numeric): use latitude/longitude instead of ac position
1227 // type: ("fix"|"vor"|"ndb"|"ils"|"dme"|"tacan"|"any")
1228 // id: (partial) id of the fix
1230 // navinfo("vor") returns all vors
1231 // navinfo("HAM") return all navaids who's name start with "HAM"
1232 // navinfo("vor", "HAM") return all vor who's name start with "HAM"
1233 //navinfo(34,48,"vor","HAM") return all vor who's name start with "HAM"
1234 // sorted by distance relative to lat=34, lon=48
1235 static naRef f_navinfo(naContext c, naRef me, int argc, naRef* args)
1239 if(argc >= 2 && naIsNum(args[0]) && naIsNum(args[1])) {
1240 pos = SGGeod::fromDeg(args[1].num, args[0].num);
1244 pos = globals->get_aircraft_position();
1247 FGPositioned::Type type = FGPositioned::INVALID;
1248 nav_list_type navlist;
1249 const char * id = "";
1251 if(argc > 0 && naIsString(args[0])) {
1252 const char *s = naStr_data(args[0]);
1253 if(!strcmp(s, "any")) type = FGPositioned::INVALID;
1254 else if(!strcmp(s, "fix")) type = FGPositioned::FIX;
1255 else if(!strcmp(s, "vor")) type = FGPositioned::VOR;
1256 else if(!strcmp(s, "ndb")) type = FGPositioned::NDB;
1257 else if(!strcmp(s, "ils")) type = FGPositioned::ILS;
1258 else if(!strcmp(s, "dme")) type = FGPositioned::DME;
1259 else if(!strcmp(s, "tacan")) type = FGPositioned::TACAN;
1260 else id = s; // this is an id
1265 if(argc > 0 && naIsString(args[0])) {
1267 naRuntimeError(c, "navinfo() called with navaid id");
1270 id = naStr_data(args[0]);
1276 naRuntimeError(c, "navinfo() called with too many arguments");
1280 navlist = globals->get_navlist()->findByIdentAndFreq( pos, id, 0.0, type );
1282 naRef reply = naNewVector(c);
1283 for( nav_list_type::const_iterator it = navlist.begin(); it != navlist.end(); ++it ) {
1284 naVec_append( reply, ghostForNavaid(c, *it) );
1289 static naRef f_findNavaidsWithinRange(naContext c, naRef me, int argc, naRef* args)
1292 SGGeod pos = globals->get_aircraft_position();
1293 argOffset += geodFromArgs(args, 0, argc, pos);
1295 if (!naIsNum(args[argOffset])) {
1296 naRuntimeError(c, "findNavaidsWithinRange expected range (in nm) as arg %d", argOffset);
1299 FGPositioned::Type type = FGPositioned::INVALID;
1300 double rangeNm = args[argOffset++].num;
1301 if (argOffset < argc) {
1302 type = FGPositioned::typeFromName(naStr_data(args[argOffset]));
1305 naRef r = naNewVector(c);
1306 FGNavList::TypeFilter filter(type);
1307 FGPositioned::List navs = FGPositioned::findWithinRange(pos, rangeNm, &filter);
1308 FGPositioned::sortByRange(navs, pos);
1310 BOOST_FOREACH(FGPositionedRef a, navs) {
1311 FGNavRecord* nav = (FGNavRecord*) a.get();
1312 naVec_append(r, ghostForNavaid(c, nav));
1318 static naRef f_findNavaidByFrequency(naContext c, naRef me, int argc, naRef* args)
1321 SGGeod pos = globals->get_aircraft_position();
1322 argOffset += geodFromArgs(args, 0, argc, pos);
1324 if (!naIsNum(args[argOffset])) {
1325 naRuntimeError(c, "findNavaidByFrequency expectes frequency (in Mhz) as arg %d", argOffset);
1328 FGPositioned::Type type = FGPositioned::INVALID;
1329 double freqMhz = args[argOffset++].num;
1330 if (argOffset < argc) {
1331 type = FGPositioned::typeFromName(naStr_data(args[argOffset]));
1334 nav_list_type navs = globals->get_navlist()->findAllByFreq(freqMhz, pos, type);
1339 return ghostForNavaid(c, navs.front().ptr());
1342 static naRef f_findNavaidsByFrequency(naContext c, naRef me, int argc, naRef* args)
1345 SGGeod pos = globals->get_aircraft_position();
1346 argOffset += geodFromArgs(args, 0, argc, pos);
1348 if (!naIsNum(args[argOffset])) {
1349 naRuntimeError(c, "findNavaidsByFrequency expectes frequency (in Mhz) as arg %d", argOffset);
1352 FGPositioned::Type type = FGPositioned::INVALID;
1353 double freqMhz = args[argOffset++].num;
1354 if (argOffset < argc) {
1355 type = FGPositioned::typeFromName(naStr_data(args[argOffset]));
1358 naRef r = naNewVector(c);
1359 nav_list_type navs = globals->get_navlist()->findAllByFreq(freqMhz, pos, type);
1361 BOOST_FOREACH(nav_rec_ptr a, navs) {
1362 naVec_append(r, ghostForNavaid(c, a.ptr()));
1368 static naRef f_findNavaidsByIdent(naContext c, naRef me, int argc, naRef* args)
1371 SGGeod pos = globals->get_aircraft_position();
1372 argOffset += geodFromArgs(args, 0, argc, pos);
1374 if (!naIsString(args[argOffset])) {
1375 naRuntimeError(c, "findNavaidsByIdent expectes ident string as arg %d", argOffset);
1378 FGPositioned::Type type = FGPositioned::INVALID;
1379 string ident = naStr_data(args[argOffset++]);
1380 if (argOffset < argc) {
1381 type = FGPositioned::typeFromName(naStr_data(args[argOffset]));
1384 naRef r = naNewVector(c);
1385 nav_list_type navs = globals->get_navlist()->findByIdentAndFreq(pos, ident, 0.0, type);
1387 BOOST_FOREACH(nav_rec_ptr a, navs) {
1388 naVec_append(r, ghostForNavaid(c, a.ptr()));
1395 // Convert a cartesian point to a geodetic lat/lon/altitude.
1396 static naRef f_magvar(naContext c, naRef me, int argc, naRef* args)
1398 SGGeod pos = globals->get_aircraft_position();
1400 // fine, use aircraft position
1401 } else if (geodFromArgs(args, 0, argc, pos)) {
1404 naRuntimeError(c, "magvar() expects no arguments, a positioned hash or lat,lon pair");
1407 double jd = globals->get_time_params()->getJD();
1408 double magvarDeg = sgGetMagVar(pos, jd) * SG_RADIANS_TO_DEGREES;
1409 return naNum(magvarDeg);
1412 static naRef f_courseAndDistance(naContext c, naRef me, int argc, naRef* args)
1414 SGGeod from = globals->get_aircraft_position(), to, p;
1415 int argOffset = geodFromArgs(args, 0, argc, p);
1416 if (geodFromArgs(args, argOffset, argc, to)) {
1417 from = p; // we parsed both FROM and TO args, so first was from
1419 to = p; // only parsed one arg, so FROM is current
1422 if (argOffset == 0) {
1423 naRuntimeError(c, "invalid arguments to courseAndDistance");
1426 double course, course2, d;
1427 SGGeodesy::inverse(from, to, course, course2, d);
1429 naRef result = naNewVector(c);
1430 naVec_append(result, naNum(course));
1431 naVec_append(result, naNum(d * SG_METER_TO_NM));
1435 static naRef f_greatCircleMove(naContext c, naRef me, int argc, naRef* args)
1437 SGGeod from = globals->get_aircraft_position(), to;
1440 // complication - don't inerpret two doubles (as the only args)
1441 // as a lat,lon pair - only do so if we have at least three args.
1443 argOffset = geodFromArgs(args, 0, argc, from);
1446 if ((argOffset + 1) >= argc) {
1447 naRuntimeError(c, "isufficent arguments to greatCircleMove");
1450 if (!naIsNum(args[argOffset]) || !naIsNum(args[argOffset+1])) {
1451 naRuntimeError(c, "invalid arguments %d and %d to greatCircleMove",
1452 argOffset, argOffset + 1);
1455 double course = args[argOffset].num, course2;
1456 double distanceNm = args[argOffset + 1].num;
1457 SGGeodesy::direct(from, course, distanceNm * SG_NM_TO_METER, to, course2);
1460 naRef coord = naNewHash(c);
1461 hashset(c, coord, "lat", naNum(to.getLatitudeDeg()));
1462 hashset(c, coord, "lon", naNum(to.getLongitudeDeg()));
1466 static naRef f_tilePath(naContext c, naRef me, int argc, naRef* args)
1468 SGGeod pos = globals->get_aircraft_position();
1469 geodFromArgs(args, 0, argc, pos);
1471 return stringToNasal(c, b.gen_base_path());
1474 static naRef f_tileIndex(naContext c, naRef me, int argc, naRef* args)
1476 SGGeod pos = globals->get_aircraft_position();
1477 geodFromArgs(args, 0, argc, pos);
1479 return naNum(b.gen_index());
1482 static naRef f_route(naContext c, naRef me, int argc, naRef* args)
1485 FGRouteMgr* rm = static_cast<FGRouteMgr*>(globals->get_subsystem("route-manager"));
1486 return ghostForFlightPlan(c, rm->flightPlan());
1489 if ((argc > 0) && naIsString(args[0])) {
1490 flightgear::FlightPlan* fp = new flightgear::FlightPlan;
1491 SGPath path(naStr_data(args[0]));
1492 if (!path.exists()) {
1493 naRuntimeError(c, "flightplan, no file at path %s", path.c_str());
1496 if (!fp->load(path)) {
1497 SG_LOG(SG_NASAL, SG_WARN, "failed to load flight-plan from " << path);
1502 return ghostForFlightPlan(c, fp);
1505 naRuntimeError(c, "bad arguments to flightplan()");
1509 static naRef f_airwaySearch(naContext c, naRef me, int argc, naRef* args)
1512 naRuntimeError(c, "airwaysSearch needs at least two arguments");
1515 WayptRef start = wayptGhost(args[0]),
1516 end = wayptGhost(args[1]);
1518 if (!start && positionedGhost(args[0])) {
1519 start = new NavaidWaypoint(positionedGhost(args[0]), NULL);
1522 if (!end && positionedGhost(args[1])) {
1523 end = new NavaidWaypoint(positionedGhost(args[1]), NULL);
1526 if (!start || !end) {
1527 SG_LOG(SG_NASAL, SG_WARN, "airwaysSearch: start or end points are invalid");
1531 bool highLevel = true;
1532 if ((argc > 2) && naIsString(args[2])) {
1533 if (!strcmp(naStr_data(args[2]), "lowlevel")) {
1540 Airway::highLevel()->route(start, end, route);
1542 Airway::lowLevel()->route(start, end, route);
1545 naRef result = naNewVector(c);
1546 BOOST_FOREACH(WayptRef wpt, route) {
1547 naVec_append(result, ghostForWaypt(c, wpt.get()));
1552 static naRef f_createWP(naContext c, naRef me, int argc, naRef* args)
1555 int argOffset = geodFromArgs(args, 0, argc, pos);
1558 // if we were created from an FGPositioned, we can use its ident
1559 FGPositioned* positioned = positionedGhost(args[0]);
1561 ident = positioned->ident();
1564 if (ident.empty()) {
1565 if (((argc - argOffset) < 1) || !naIsString(args[argOffset])) {
1566 naRuntimeError(c, "createWP: no identifier supplied");
1569 ident = naStr_data(args[argOffset++]);
1572 WayptRef wpt = new BasicWaypt(pos, ident, NULL);
1573 return ghostForWaypt(c, wpt);
1576 static naRef f_flightplan_getWP(naContext c, naRef me, int argc, naRef* args)
1578 FlightPlan* fp = flightplanGhost(me);
1580 naRuntimeError(c, "flightplan.getWP called on non-flightplan object");
1585 index = fp->currentIndex();
1587 index = (int) naNumValue(args[0]).num;
1590 if ((index < 0) || (index >= fp->numLegs())) {
1594 return ghostForLeg(c, fp->legAtIndex(index));
1597 static naRef f_flightplan_currentWP(naContext c, naRef me, int argc, naRef* args)
1599 FlightPlan* fp = flightplanGhost(me);
1601 naRuntimeError(c, "flightplan.currentWP called on non-flightplan object");
1603 return ghostForLeg(c, fp->currentLeg());
1606 static naRef f_flightplan_nextWP(naContext c, naRef me, int argc, naRef* args)
1608 FlightPlan* fp = flightplanGhost(me);
1610 naRuntimeError(c, "flightplan.nextWP called on non-flightplan object");
1612 return ghostForLeg(c, fp->nextLeg());
1615 static naRef f_flightplan_numWaypoints(naContext c, naRef me, int argc, naRef* args)
1617 FlightPlan* fp = flightplanGhost(me);
1619 naRuntimeError(c, "flightplan.numWaypoints called on non-flightplan object");
1621 return naNum(fp->numLegs());
1624 static naRef f_flightplan_appendWP(naContext c, naRef me, int argc, naRef* args)
1626 FlightPlan* fp = flightplanGhost(me);
1628 naRuntimeError(c, "flightplan.appendWP called on non-flightplan object");
1631 WayptRef wp = wayptGhost(args[0]);
1632 int index = fp->numLegs();
1633 fp->insertWayptAtIndex(wp.get(), index);
1634 return naNum(index);
1637 static naRef f_flightplan_insertWP(naContext c, naRef me, int argc, naRef* args)
1639 FlightPlan* fp = flightplanGhost(me);
1641 naRuntimeError(c, "flightplan.insertWP called on non-flightplan object");
1644 WayptRef wp = wayptGhost(args[0]);
1645 int index = -1; // append
1646 if ((argc > 1) && naIsNum(args[1])) {
1647 index = (int) args[1].num;
1650 fp->insertWayptAtIndex(wp.get(), index);
1654 static naRef f_flightplan_insertWPAfter(naContext c, naRef me, int argc, naRef* args)
1656 FlightPlan* fp = flightplanGhost(me);
1658 naRuntimeError(c, "flightplan.insertWPAfter called on non-flightplan object");
1661 WayptRef wp = wayptGhost(args[0]);
1662 int index = -1; // append
1663 if ((argc > 1) && naIsNum(args[1])) {
1664 index = (int) args[1].num;
1667 fp->insertWayptAtIndex(wp.get(), index + 1);
1671 static naRef f_flightplan_insertWaypoints(naContext c, naRef me, int argc, naRef* args)
1673 FlightPlan* fp = flightplanGhost(me);
1675 naRuntimeError(c, "flightplan.insertWaypoints called on non-flightplan object");
1679 if (!naIsVector(args[0])) {
1680 naRuntimeError(c, "flightplan.insertWaypoints expects vector as first arg");
1683 int count = naVec_size(args[0]);
1684 for (int i=0; i<count; ++i) {
1685 Waypt* wp = wayptGhost(naVec_get(args[0], i));
1691 int index = -1; // append
1692 if ((argc > 1) && naIsNum(args[1])) {
1693 index = (int) args[1].num;
1696 fp->insertWayptsAtIndex(wps, index);
1700 static naRef f_flightplan_deleteWP(naContext c, naRef me, int argc, naRef* args)
1702 FlightPlan* fp = flightplanGhost(me);
1704 naRuntimeError(c, "flightplan.deleteWP called on non-flightplan object");
1707 if ((argc < 1) || !naIsNum(args[0])) {
1708 naRuntimeError(c, "bad argument to flightplan.deleteWP");
1711 int index = (int) args[0].num;
1712 fp->deleteIndex(index);
1716 static naRef f_flightplan_clearPlan(naContext c, naRef me, int argc, naRef* args)
1718 FlightPlan* fp = flightplanGhost(me);
1720 naRuntimeError(c, "flightplan.clearPlan called on non-flightplan object");
1727 static WayptFlag wayptFlagFromString(const char* s)
1729 if (!strcmp(s, "sid")) return WPT_DEPARTURE;
1730 if (!strcmp(s, "star")) return WPT_ARRIVAL;
1731 if (!strcmp(s, "approach")) return WPT_APPROACH;
1732 if (!strcmp(s, "missed")) return WPT_MISS;
1733 if (!strcmp(s, "pseudo")) return WPT_PSEUDO;
1735 return (WayptFlag) 0;
1738 static naRef f_flightplan_clearWPType(naContext c, naRef me, int argc, naRef* args)
1740 FlightPlan* fp = flightplanGhost(me);
1742 naRuntimeError(c, "flightplan.clearWPType called on non-flightplan object");
1746 naRuntimeError(c, "insufficent args to flightplan.clearWPType");
1749 WayptFlag flag = wayptFlagFromString(naStr_data(args[0]));
1750 fp->clearWayptsWithFlag(flag);
1754 static naRef f_flightplan_clone(naContext c, naRef me, int argc, naRef* args)
1756 FlightPlan* fp = flightplanGhost(me);
1758 naRuntimeError(c, "flightplan.clone called on non-flightplan object");
1761 return ghostForFlightPlan(c, fp->clone());
1764 static naRef f_leg_setSpeed(naContext c, naRef me, int argc, naRef* args)
1766 FlightPlan::Leg* leg = fpLegGhost(me);
1768 naRuntimeError(c, "leg.setSpeed called on non-flightplan-leg object");
1772 naRuntimeError(c, "bad arguments to leg.setSpeed");
1775 RouteRestriction rr = routeRestrictionFromString(naStr_data(args[1]));
1776 leg->setSpeed(rr, args[0].num);
1780 static naRef f_leg_setAltitude(naContext c, naRef me, int argc, naRef* args)
1782 FlightPlan::Leg* leg = fpLegGhost(me);
1784 naRuntimeError(c, "leg.setAltitude called on non-flightplan-leg object");
1788 naRuntimeError(c, "bad arguments to leg.setAltitude");
1791 RouteRestriction rr = routeRestrictionFromString(naStr_data(args[1]));
1792 leg->setAltitude(rr, args[0].num);
1796 static naRef f_waypoint_navaid(naContext c, naRef me, int argc, naRef* args)
1798 flightgear::Waypt* w = wayptGhost(me);
1800 naRuntimeError(c, "waypoint.navaid called on non-waypoint object");
1803 FGPositioned* pos = w->source();
1808 switch (pos->type()) {
1809 case FGPositioned::VOR:
1810 case FGPositioned::NDB:
1811 case FGPositioned::ILS:
1812 case FGPositioned::LOC:
1813 case FGPositioned::GS:
1814 case FGPositioned::DME:
1815 case FGPositioned::TACAN: {
1816 FGNavRecord* nav = (FGNavRecord*) pos;
1817 return ghostForNavaid(c, nav);
1825 static naRef f_waypoint_airport(naContext c, naRef me, int argc, naRef* args)
1827 flightgear::Waypt* w = wayptGhost(me);
1829 naRuntimeError(c, "waypoint.navaid called on non-waypoint object");
1832 FGPositioned* pos = w->source();
1833 if (!pos || FGAirport::isAirportType(pos)) {
1837 return ghostForAirport(c, (FGAirport*) pos);
1840 static naRef f_waypoint_runway(naContext c, naRef me, int argc, naRef* args)
1842 flightgear::Waypt* w = wayptGhost(me);
1844 naRuntimeError(c, "waypoint.navaid called on non-waypoint object");
1847 FGPositioned* pos = w->source();
1848 if (!pos || (pos->type() != FGPositioned::RUNWAY)) {
1852 return ghostForRunway(c, (FGRunway*) pos);
1855 static naRef f_procedure_transition(naContext c, naRef me, int argc, naRef* args)
1857 Procedure* proc = procedureGhost(me);
1859 naRuntimeError(c, "procedure.transition called on non-procedure object");
1862 if ((proc->type() != PROCEDURE_SID) && (proc->type() != PROCEDURE_STAR)) {
1863 naRuntimeError(c, "procedure.transition called on non-SID or -STAR");
1866 ArrivalDeparture* ad = (ArrivalDeparture*) proc;
1867 Transition* trans = ad->findTransitionByName(naStr_data(args[0]));
1869 return ghostForProcedure(c, trans);
1872 // Table of extension functions. Terminate with zeros.
1873 static struct { const char* name; naCFunction func; } funcs[] = {
1874 { "carttogeod", f_carttogeod },
1875 { "geodtocart", f_geodtocart },
1876 { "geodinfo", f_geodinfo },
1877 { "airportinfo", f_airportinfo },
1878 { "findAirportsWithinRange", f_findAirportsWithinRange },
1879 { "findAirportsByICAO", f_findAirportsByICAO },
1880 { "navinfo", f_navinfo },
1881 { "findNavaidsWithinRange", f_findNavaidsWithinRange },
1882 { "findNavaidByFrequency", f_findNavaidByFrequency },
1883 { "findNavaidsByFrequency", f_findNavaidsByFrequency },
1884 { "findNavaidsByID", f_findNavaidsByIdent },
1885 { "flightplan", f_route },
1886 { "createWP", f_createWP },
1887 { "airwaysRoute", f_airwaySearch },
1888 { "magvar", f_magvar },
1889 { "courseAndDistance", f_courseAndDistance },
1890 { "greatCircleMove", f_greatCircleMove },
1891 { "tileIndex", f_tileIndex },
1892 { "tilePath", f_tilePath },
1897 naRef initNasalPositioned(naRef globals, naContext c, naRef gcSave)
1899 airportPrototype = naNewHash(c);
1900 hashset(c, gcSave, "airportProto", airportPrototype);
1902 hashset(c, airportPrototype, "runway", naNewFunc(c, naNewCCode(c, f_airport_runway)));
1903 hashset(c, airportPrototype, "tower", naNewFunc(c, naNewCCode(c, f_airport_tower)));
1904 hashset(c, airportPrototype, "comms", naNewFunc(c, naNewCCode(c, f_airport_comms)));
1905 hashset(c, airportPrototype, "sids", naNewFunc(c, naNewCCode(c, f_airport_sids)));
1906 hashset(c, airportPrototype, "stars", naNewFunc(c, naNewCCode(c, f_airport_stars)));
1907 hashset(c, airportPrototype, "getApproachList", naNewFunc(c, naNewCCode(c, f_airport_approaches)));
1908 hashset(c, airportPrototype, "parking", naNewFunc(c, naNewCCode(c, f_airport_parking)));
1909 hashset(c, airportPrototype, "getSid", naNewFunc(c, naNewCCode(c, f_airport_getSid)));
1910 hashset(c, airportPrototype, "getStar", naNewFunc(c, naNewCCode(c, f_airport_getStar)));
1911 hashset(c, airportPrototype, "getIAP", naNewFunc(c, naNewCCode(c, f_airport_getApproach)));
1913 flightplanPrototype = naNewHash(c);
1914 hashset(c, gcSave, "flightplanProto", flightplanPrototype);
1916 hashset(c, flightplanPrototype, "getWP", naNewFunc(c, naNewCCode(c, f_flightplan_getWP)));
1917 hashset(c, flightplanPrototype, "currentWP", naNewFunc(c, naNewCCode(c, f_flightplan_currentWP)));
1918 hashset(c, flightplanPrototype, "nextWP", naNewFunc(c, naNewCCode(c, f_flightplan_nextWP)));
1919 hashset(c, flightplanPrototype, "getPlanSize", naNewFunc(c, naNewCCode(c, f_flightplan_numWaypoints)));
1920 hashset(c, flightplanPrototype, "appendWP", naNewFunc(c, naNewCCode(c, f_flightplan_appendWP)));
1921 hashset(c, flightplanPrototype, "insertWP", naNewFunc(c, naNewCCode(c, f_flightplan_insertWP)));
1922 hashset(c, flightplanPrototype, "deleteWP", naNewFunc(c, naNewCCode(c, f_flightplan_deleteWP)));
1923 hashset(c, flightplanPrototype, "insertWPAfter", naNewFunc(c, naNewCCode(c, f_flightplan_insertWPAfter)));
1924 hashset(c, flightplanPrototype, "insertWaypoints", naNewFunc(c, naNewCCode(c, f_flightplan_insertWaypoints)));
1925 hashset(c, flightplanPrototype, "cleanPlan", naNewFunc(c, naNewCCode(c, f_flightplan_clearPlan)));
1926 hashset(c, flightplanPrototype, "clearWPType", naNewFunc(c, naNewCCode(c, f_flightplan_clearWPType)));
1927 hashset(c, flightplanPrototype, "clone", naNewFunc(c, naNewCCode(c, f_flightplan_clone)));
1929 waypointPrototype = naNewHash(c);
1930 hashset(c, gcSave, "wayptProto", waypointPrototype);
1932 hashset(c, waypointPrototype, "navaid", naNewFunc(c, naNewCCode(c, f_waypoint_navaid)));
1933 hashset(c, waypointPrototype, "runway", naNewFunc(c, naNewCCode(c, f_waypoint_runway)));
1934 hashset(c, waypointPrototype, "airport", naNewFunc(c, naNewCCode(c, f_waypoint_airport)));
1936 procedurePrototype = naNewHash(c);
1937 hashset(c, gcSave, "procedureProto", procedurePrototype);
1938 // hashset(c, procedurePrototype, "runwayTransition", naNewFunc(c, naNewCCode(c, f_procedure_runwayTransition)));
1939 hashset(c, procedurePrototype, "transition", naNewFunc(c, naNewCCode(c, f_procedure_transition)));
1940 // hashset(c, procedurePrototype, "buildPath", naNewFunc(c, naNewCCode(c, f_procedure_build)));
1942 fpLegPrototype = naNewHash(c);
1943 hashset(c, gcSave, "fpLegProto", fpLegPrototype);
1944 hashset(c, fpLegPrototype, "setSpeed", naNewFunc(c, naNewCCode(c, f_leg_setSpeed)));
1945 hashset(c, fpLegPrototype, "setAltitude", naNewFunc(c, naNewCCode(c, f_leg_setAltitude)));
1947 for(int i=0; funcs[i].name; i++) {
1948 hashset(c, globals, funcs[i].name,
1949 naNewFunc(c, naNewCCode(c, funcs[i].func)));
1955 void postinitNasalPositioned(naRef globals, naContext c)
1957 naRef geoModule = naHash_cget(globals, (char*) "geo");
1958 if (naIsNil(geoModule)) {
1959 SG_LOG(SG_GENERAL, SG_WARN, "postinitNasalPositioned: geo.nas not loaded");
1963 geoCoordClass = naHash_cget(geoModule, (char*) "Coord");