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>
31 #include <simgear/sg_inlines.h>
32 #include <simgear/scene/material/mat.hxx>
33 #include <simgear/magvar/magvar.hxx>
34 #include <simgear/timing/sg_time.hxx>
35 #include <simgear/bucket/newbucket.hxx>
37 #include <Airports/runways.hxx>
38 #include <Airports/simple.hxx>
39 #include <Airports/dynamics.hxx>
40 #include <Airports/parking.hxx>
41 #include <Navaids/navlist.hxx>
42 #include <Navaids/procedure.hxx>
43 #include <Main/globals.hxx>
44 #include <Main/fg_props.hxx>
45 #include <Scenery/scenery.hxx>
46 #include <ATC/CommStation.hxx>
47 #include <Navaids/route.hxx>
48 #include <Autopilot/route_mgr.hxx>
49 #include <Navaids/procedure.hxx>
51 static void positionedGhostDestroy(void* g);
52 static void wayptGhostDestroy(void* g);
53 naGhostType PositionedGhostType = { positionedGhostDestroy, "positioned" };
55 static const char* airportGhostGetMember(naContext c, void* g, naRef field, naRef* out);
56 naGhostType AirportGhostType = { positionedGhostDestroy, "airport", airportGhostGetMember, 0 };
58 static const char* navaidGhostGetMember(naContext c, void* g, naRef field, naRef* out);
59 naGhostType NavaidGhostType = { positionedGhostDestroy, "navaid", navaidGhostGetMember, 0 };
61 static const char* runwayGhostGetMember(naContext c, void* g, naRef field, naRef* out);
62 naGhostType RunwayGhostType = { positionedGhostDestroy, "runway", runwayGhostGetMember, 0 };
64 static const char* wayptGhostGetMember(naContext c, void* g, naRef field, naRef* out);
66 naGhostType WayptGhostType = { wayptGhostDestroy,
71 static void hashset(naContext c, naRef hash, const char* key, naRef val)
73 naRef s = naNewString(c);
74 naStr_fromdata(s, (char*)key, strlen(key));
75 naHash_set(hash, s, val);
78 static naRef stringToNasal(naContext c, const std::string& s)
80 return naStr_fromdata(naNewString(c),
81 const_cast<char *>(s.c_str()),
85 static FGPositioned* positionedGhost(naRef r)
87 if (naGhost_type(r) == &PositionedGhostType)
88 return (FGPositioned*) naGhost_ptr(r);
92 static FGAirport* airportGhost(naRef r)
94 if (naGhost_type(r) == &AirportGhostType)
95 return (FGAirport*) naGhost_ptr(r);
99 static FGNavRecord* navaidGhost(naRef r)
101 if (naGhost_type(r) == &NavaidGhostType)
102 return (FGNavRecord*) naGhost_ptr(r);
106 static FGRunway* runwayGhost(naRef r)
108 if (naGhost_type(r) == &RunwayGhostType)
109 return (FGRunway*) naGhost_ptr(r);
113 static void positionedGhostDestroy(void* g)
115 FGPositioned* pos = (FGPositioned*)g;
116 if (!FGPositioned::put(pos)) // unref
120 static flightgear::Waypt* wayptGhost(naRef r)
122 if (naGhost_type(r) == &WayptGhostType)
123 return (flightgear::Waypt*) naGhost_ptr(r);
127 static void wayptGhostDestroy(void* g)
129 flightgear::Waypt* wpt = (flightgear::Waypt*)g;
130 if (!flightgear::Waypt::put(wpt)) // unref
134 static naRef airportPrototype;
135 static naRef routePrototype;
136 static naRef waypointPrototype;
137 static naRef geoCoordClass;
139 naRef ghostForPositioned(naContext c, const FGPositioned* pos)
145 FGPositioned::get(pos); // take a ref
146 return naNewGhost(c, &PositionedGhostType, (void*) pos);
149 naRef ghostForAirport(naContext c, const FGAirport* apt)
155 FGPositioned::get(apt); // take a ref
156 return naNewGhost2(c, &AirportGhostType, (void*) apt);
159 naRef ghostForNavaid(naContext c, const FGNavRecord* n)
165 FGPositioned::get(n); // take a ref
166 return naNewGhost2(c, &NavaidGhostType, (void*) n);
169 naRef ghostForRunway(naContext c, const FGRunway* r)
175 FGPositioned::get(r); // take a ref
176 return naNewGhost2(c, &RunwayGhostType, (void*) r);
179 naRef ghostForWaypt(naContext c, const flightgear::Waypt* wpt)
185 flightgear::Waypt::get(wpt); // take a ref
186 return naNewGhost2(c, &WayptGhostType, (void*) wpt);
189 static const char* airportGhostGetMember(naContext c, void* g, naRef field, naRef* out)
191 const char* fieldName = naStr_data(field);
192 FGAirport* apt = (FGAirport*) g;
194 if (!strcmp(fieldName, "parents")) {
195 *out = naNewVector(c);
196 naVec_append(*out, airportPrototype);
197 } else if (!strcmp(fieldName, "id")) *out = stringToNasal(c, apt->ident());
198 else if (!strcmp(fieldName, "name")) *out = stringToNasal(c, apt->name());
199 else if (!strcmp(fieldName, "lat")) *out = naNum(apt->getLatitude());
200 else if (!strcmp(fieldName, "lon")) *out = naNum(apt->getLongitude());
201 else if (!strcmp(fieldName, "elevation")) {
202 *out = naNum(apt->getElevation() * SG_FEET_TO_METER);
203 } else if (!strcmp(fieldName, "has_metar")) {
204 *out = naNum(apt->getMetar());
205 } else if (!strcmp(fieldName, "runways")) {
207 for(unsigned int r=0; r<apt->numRunways(); ++r) {
208 FGRunway* rwy(apt->getRunwayByIndex(r));
209 naRef rwyid = stringToNasal(c, rwy->ident());
210 naRef rwydata = ghostForRunway(c, rwy);
211 naHash_set(*out, rwyid, rwydata);
221 static const char* wayptGhostGetMember(naContext c, void* g, naRef field, naRef* out)
223 const char* fieldName = naStr_data(field);
224 flightgear::Waypt* wpt = (flightgear::Waypt*) g;
226 if (!strcmp(fieldName, "parents")) {
227 *out = naNewVector(c);
228 naVec_append(*out, waypointPrototype);
229 } else if (!strcmp(fieldName, "wp_name")) *out =stringToNasal(c, wpt->ident());
230 else if (!strcmp(fieldName, "wp_type")) *out = stringToNasal(c, wpt->type());
231 else if (!strcmp(fieldName, "wp_lat")) *out = naNum(wpt->position().getLatitudeDeg());
232 else if (!strcmp(fieldName, "wp_lon")) *out = naNum(wpt->position().getLongitudeDeg());
233 else if (!strcmp(fieldName, "wp_parent_name")) {
234 flightgear::Procedure* proc = dynamic_cast<flightgear::Procedure*>(wpt->owner());
235 *out = proc ? stringToNasal(c, proc->ident()) : naNil();
236 } else if (!strcmp(fieldName, "fly_type")) {
237 if (wpt->type() == "hold") {
238 *out = stringToNasal(c, "Hold");
240 *out = stringToNasal(c, wpt->flag(flightgear::WPT_OVERFLIGHT) ? "flyOver" : "flyBy");
242 } else if (!strcmp(fieldName, "alt_cstr")) *out = naNum(wpt->altitudeFt());
243 else if (!strcmp(fieldName, "speed_cstr")) {
244 double s = (wpt->speedRestriction() == flightgear::SPEED_RESTRICT_MACH)
245 ? wpt->speedMach() : wpt->speedKts();
247 } else if (!strcmp(fieldName, "leg_distance")) {
248 return "please implement me";
249 } else if (!strcmp(fieldName, "leg_bearing")) {
250 return "please implement me";
252 return NULL; // member not found
255 return ""; // success
258 static const char* runwayGhostGetMember(naContext c, void* g, naRef field, naRef* out)
260 const char* fieldName = naStr_data(field);
261 FGRunway* rwy = (FGRunway*) g;
263 if (!strcmp(fieldName, "id")) *out = stringToNasal(c, rwy->ident());
264 else if (!strcmp(fieldName, "lat")) *out = naNum(rwy->latitude());
265 else if (!strcmp(fieldName, "lon")) *out = naNum(rwy->longitude());
266 else if (!strcmp(fieldName, "heading")) *out = naNum(rwy->headingDeg());
267 else if (!strcmp(fieldName, "length")) *out = naNum(rwy->lengthM());
268 else if (!strcmp(fieldName, "width")) *out = naNum(rwy->widthM());
269 else if (!strcmp(fieldName, "threshold")) *out = naNum(rwy->displacedThresholdM());
270 else if (!strcmp(fieldName, "stopway")) *out = naNum(rwy->stopwayM());
271 else if (!strcmp(fieldName, "ils_frequency_mhz")) {
272 *out = rwy->ILS() ? naNum(rwy->ILS()->get_freq() / 100.0) : naNil();
273 } else if (!strcmp(fieldName, "ils")) {
274 *out = ghostForNavaid(c, rwy->ILS());
282 static const char* navaidGhostGetMember(naContext c, void* g, naRef field, naRef* out)
284 const char* fieldName = naStr_data(field);
285 FGNavRecord* nav = (FGNavRecord*) g;
287 if (!strcmp(fieldName, "id")) *out = stringToNasal(c, nav->ident());
288 else if (!strcmp(fieldName, "name")) *out = stringToNasal(c, nav->name());
289 else if (!strcmp(fieldName, "lat")) *out = naNum(nav->get_lat());
290 else if (!strcmp(fieldName, "lon")) *out = naNum(nav->get_lon());
291 else if (!strcmp(fieldName, "elevation")) {
292 *out = naNum(nav->get_elev_ft() * SG_FEET_TO_METER);
293 } else if (!strcmp(fieldName, "type")) {
294 *out = stringToNasal(c, nav->nameForType(nav->type()));
295 } else if (!strcmp(fieldName, "frequency")) {
296 *out = naNum(nav->get_freq());
297 } else if (!strcmp(fieldName, "range_nm")) {
298 *out = naNum(nav->get_range());
299 } else if (!strcmp(fieldName, "course")) {
300 if ((nav->type() == FGPositioned::ILS) || (nav->type() == FGPositioned::LOC)) {
301 double radial = nav->get_multiuse();
302 SG_NORMALIZE_RANGE(radial, 0.0, 360.0);
303 *out = naNum(radial);
314 static bool hashIsCoord(naRef h)
316 naRef parents = naHash_cget(h, (char*) "parents");
317 if (!naIsVector(parents)) {
321 return naEqual(naVec_get(parents, 0), geoCoordClass);
324 bool geodFromHash(naRef ref, SGGeod& result)
326 if (!naIsHash(ref)) {
330 // first, see if the hash contains a FGPositioned ghost - in which case
331 // we can read off its position directly
332 naRef posGhost = naHash_cget(ref, (char*) "_positioned");
333 if (!naIsNil(posGhost)) {
334 FGPositioned* pos = positionedGhost(posGhost);
335 result = pos->geod();
339 // then check for manual latitude / longitude names
340 naRef lat = naHash_cget(ref, (char*) "lat");
341 naRef lon = naHash_cget(ref, (char*) "lon");
342 if (naIsNum(lat) && naIsNum(lon)) {
343 result = SGGeod::fromDeg(naNumValue(lon).num, naNumValue(lat).num);
347 if (hashIsCoord(ref)) {
348 naRef lat = naHash_cget(ref, (char*) "_lat");
349 naRef lon = naHash_cget(ref, (char*) "_lon");
350 if (naIsNum(lat) && naIsNum(lon)) {
351 result = SGGeod::fromRad(naNumValue(lon).num, naNumValue(lat).num);
356 // check for any synonyms?
357 // latitude + longitude?
362 static int geodFromArgs(naRef* args, int offset, int argc, SGGeod& result)
364 if (offset >= argc) {
368 if (naIsGhost(args[offset])) {
369 naGhostType* gt = naGhost_type(args[offset]);
370 if (gt == &AirportGhostType) {
371 result = airportGhost(args[offset])->geod();
375 if (gt == &NavaidGhostType) {
376 result = navaidGhost(args[offset])->geod();
380 if (gt == &RunwayGhostType) {
381 result = runwayGhost(args[offset])->geod();
385 if (gt == &WayptGhostType) {
386 result = wayptGhost(args[offset])->position();
391 if (geodFromHash(args[offset], result)) {
395 if (((argc - offset) >= 2) && naIsNum(args[offset]) && naIsNum(args[offset + 1])) {
396 double lat = naNumValue(args[0]).num,
397 lon = naNumValue(args[1]).num;
398 result = SGGeod::fromDeg(lon, lat);
405 // Convert a cartesian point to a geodetic lat/lon/altitude.
406 static naRef f_carttogeod(naContext c, naRef me, int argc, naRef* args)
408 double lat, lon, alt, xyz[3];
409 if(argc != 3) naRuntimeError(c, "carttogeod() expects 3 arguments");
410 for(int i=0; i<3; i++)
411 xyz[i] = naNumValue(args[i]).num;
412 sgCartToGeod(xyz, &lat, &lon, &alt);
413 lat *= SG_RADIANS_TO_DEGREES;
414 lon *= SG_RADIANS_TO_DEGREES;
415 naRef vec = naNewVector(c);
416 naVec_append(vec, naNum(lat));
417 naVec_append(vec, naNum(lon));
418 naVec_append(vec, naNum(alt));
422 // Convert a geodetic lat/lon/altitude to a cartesian point.
423 static naRef f_geodtocart(naContext c, naRef me, int argc, naRef* args)
425 if(argc != 3) naRuntimeError(c, "geodtocart() expects 3 arguments");
426 double lat = naNumValue(args[0]).num * SG_DEGREES_TO_RADIANS;
427 double lon = naNumValue(args[1]).num * SG_DEGREES_TO_RADIANS;
428 double alt = naNumValue(args[2]).num;
430 sgGeodToCart(lat, lon, alt, xyz);
431 naRef vec = naNewVector(c);
432 naVec_append(vec, naNum(xyz[0]));
433 naVec_append(vec, naNum(xyz[1]));
434 naVec_append(vec, naNum(xyz[2]));
438 // For given geodetic point return array with elevation, and a material data
439 // hash, or nil if there's no information available (tile not loaded). If
440 // information about the material isn't available, then nil is returned instead
442 static naRef f_geodinfo(naContext c, naRef me, int argc, naRef* args)
444 #define HASHSET(s,l,n) naHash_set(matdata, naStr_fromdata(naNewString(c),s,l),n)
445 if(argc < 2 || argc > 3)
446 naRuntimeError(c, "geodinfo() expects 2 or 3 arguments: lat, lon [, maxalt]");
447 double lat = naNumValue(args[0]).num;
448 double lon = naNumValue(args[1]).num;
449 double elev = argc == 3 ? naNumValue(args[2]).num : 10000;
450 const SGMaterial *mat;
451 SGGeod geod = SGGeod::fromDegM(lon, lat, elev);
452 if(!globals->get_scenery()->get_elevation_m(geod, elev, &mat))
454 naRef vec = naNewVector(c);
455 naVec_append(vec, naNum(elev));
456 naRef matdata = naNil();
458 matdata = naNewHash(c);
459 naRef names = naNewVector(c);
460 BOOST_FOREACH(const std::string& n, mat->get_names())
461 naVec_append(names, stringToNasal(c, n));
463 HASHSET("names", 5, names);
464 HASHSET("solid", 5, naNum(mat->get_solid()));
465 HASHSET("friction_factor", 15, naNum(mat->get_friction_factor()));
466 HASHSET("rolling_friction", 16, naNum(mat->get_rolling_friction()));
467 HASHSET("load_resistance", 15, naNum(mat->get_load_resistance()));
468 HASHSET("bumpiness", 9, naNum(mat->get_bumpiness()));
469 HASHSET("light_coverage", 14, naNum(mat->get_light_coverage()));
471 naVec_append(vec, matdata);
477 class AirportInfoFilter : public FGAirport::AirportFilter
480 AirportInfoFilter() : type(FGPositioned::AIRPORT) {
483 bool fromArg(naRef arg)
485 const char *s = naStr_data(arg);
486 if(!strcmp(s, "airport")) type = FGPositioned::AIRPORT;
487 else if(!strcmp(s, "seaport")) type = FGPositioned::SEAPORT;
488 else if(!strcmp(s, "heliport")) type = FGPositioned::HELIPORT;
495 virtual FGPositioned::Type minType() const {
499 virtual FGPositioned::Type maxType() const {
503 FGPositioned::Type type;
506 // Returns data hash for particular or nearest airport of a <type>, or nil
509 // airportinfo(<id>); e.g. "KSFO"
510 // airportinfo(<type>); type := ("airport"|"seaport"|"heliport")
511 // airportinfo() same as airportinfo("airport")
512 // airportinfo(<lat>, <lon> [, <type>]);
513 static naRef f_airportinfo(naContext c, naRef me, int argc, naRef* args)
515 SGGeod pos = globals->get_aircraft_position();
516 FGAirport* apt = NULL;
518 if(argc >= 2 && naIsNum(args[0]) && naIsNum(args[1])) {
519 pos = SGGeod::fromDeg(args[1].num, args[0].num);
524 double maxRange = 10000.0; // expose this? or pick a smaller value?
526 AirportInfoFilter filter; // defaults to airports only
529 // fall through and use AIRPORT
530 } else if(argc == 1 && naIsString(args[0])) {
531 if (filter.fromArg(args[0])) {
534 // user provided an <id>, hopefully
535 apt = FGAirport::findByIdent(naStr_data(args[0]));
537 // return nil here, but don't raise a runtime error; this is a
538 // legitamate way to validate an ICAO code, for example in a
539 // dialog box or similar.
544 naRuntimeError(c, "airportinfo() with invalid function arguments");
549 apt = FGAirport::findClosest(pos, maxRange, &filter);
550 if(!apt) return naNil();
553 return ghostForAirport(c, apt);
556 static naRef f_findAirportsWithinRange(naContext c, naRef me, int argc, naRef* args)
559 SGGeod pos = globals->get_aircraft_position();
560 argOffset += geodFromArgs(args, 0, argc, pos);
562 if (!naIsNum(args[argOffset])) {
563 naRuntimeError(c, "findAirportsWithinRange expected range (in nm) as arg %d", argOffset);
566 AirportInfoFilter filter; // defaults to airports only
567 double rangeNm = args[argOffset++].num;
568 if (argOffset < argc) {
569 filter.fromArg(args[argOffset++]);
572 naRef r = naNewVector(c);
574 FGPositioned::List apts = FGPositioned::findWithinRange(pos, rangeNm, &filter);
575 FGPositioned::sortByRange(apts, pos);
577 BOOST_FOREACH(FGPositionedRef a, apts) {
578 FGAirport* apt = (FGAirport*) a.get();
579 naVec_append(r, ghostForAirport(c, apt));
585 static naRef f_findAirportsByICAO(naContext c, naRef me, int argc, naRef* args)
587 if (!naIsString(args[0])) {
588 naRuntimeError(c, "findAirportsByICAO expects string as arg 0");
592 string prefix(naStr_data(args[argOffset++]));
593 AirportInfoFilter filter; // defaults to airports only
594 if (argOffset < argc) {
595 filter.fromArg(args[argOffset++]);
598 naRef r = naNewVector(c);
600 FGPositioned::List apts = FGPositioned::findAllWithIdent(prefix, &filter, false);
602 BOOST_FOREACH(FGPositionedRef a, apts) {
603 FGAirport* apt = (FGAirport*) a.get();
604 naVec_append(r, ghostForAirport(c, apt));
610 static naRef f_airport_tower(naContext c, naRef me, int argc, naRef* args)
612 FGAirport* apt = airportGhost(me);
614 naRuntimeError(c, "airport.tower called on non-airport object");
617 // build a hash for the tower position
618 SGGeod towerLoc = apt->getTowerLocation();
619 naRef tower = naNewHash(c);
620 hashset(c, tower, "lat", naNum(towerLoc.getLatitudeDeg()));
621 hashset(c, tower, "lon", naNum(towerLoc.getLongitudeDeg()));
622 hashset(c, tower, "elevation", naNum(towerLoc.getElevationM()));
626 static naRef f_airport_comms(naContext c, naRef me, int argc, naRef* args)
628 FGAirport* apt = airportGhost(me);
630 naRuntimeError(c, "airport.comms called on non-airport object");
632 naRef comms = naNewVector(c);
634 // if we have an explicit type, return a simple vector of frequencies
635 if (argc > 0 && naIsScalar(args[0])) {
636 std::string commName = naStr_data(args[0]);
637 FGPositioned::Type commType = FGPositioned::typeFromName(commName);
639 BOOST_FOREACH(flightgear::CommStation* comm, apt->commStationsOfType(commType)) {
640 naVec_append(comms, naNum(comm->freqMHz()));
643 // otherwise return a vector of hashes, one for each comm station.
644 BOOST_FOREACH(flightgear::CommStation* comm, apt->commStations()) {
645 naRef commHash = naNewHash(c);
646 hashset(c, commHash, "frequency", naNum(comm->freqMHz()));
647 hashset(c, commHash, "ident", stringToNasal(c, comm->ident()));
648 naVec_append(comms, commHash);
655 static naRef f_airport_runway(naContext c, naRef me, int argc, naRef* args)
657 FGAirport* apt = airportGhost(me);
659 naRuntimeError(c, "airport.runway called on non-airport object");
662 if ((argc < 1) || !naIsString(args[0])) {
663 naRuntimeError(c, "airport.runway expects a runway ident argument");
666 std::string ident(naStr_data(args[0]));
667 if (!apt->hasRunwayWithIdent(ident)) {
671 return ghostForRunway(c, apt->getRunwayByIdent(ident));
674 static naRef f_airport_sids(naContext c, naRef me, int argc, naRef* args)
676 FGAirport* apt = airportGhost(me);
678 naRuntimeError(c, "airport.sids called on non-airport object");
681 naRef sids = naNewVector(c);
683 if (argc > 0 && naIsString(args[0])) {
684 if (!apt->hasRunwayWithIdent(naStr_data(args[0]))) {
688 FGRunway* rwy = apt->getRunwayByIdent(naStr_data(args[0]));
689 BOOST_FOREACH(flightgear::SID* sid, rwy->getSIDs()) {
690 naRef procId = stringToNasal(c, sid->ident());
691 naVec_append(sids, procId);
694 for (unsigned int s=0; s<apt->numSIDs(); ++s) {
695 flightgear::SID* sid = apt->getSIDByIndex(s);
696 naRef procId = stringToNasal(c, sid->ident());
697 naVec_append(sids, procId);
704 static naRef f_airport_stars(naContext c, naRef me, int argc, naRef* args)
706 FGAirport* apt = airportGhost(me);
708 naRuntimeError(c, "airport.stars called on non-airport object");
711 naRef stars = naNewVector(c);
713 if (argc > 0 && naIsString(args[0])) {
714 if (!apt->hasRunwayWithIdent(naStr_data(args[0]))) {
718 FGRunway* rwy = apt->getRunwayByIdent(naStr_data(args[0]));
719 BOOST_FOREACH(flightgear::STAR* s, rwy->getSTARs()) {
720 naRef procId = stringToNasal(c, s->ident());
721 naVec_append(stars, procId);
724 for (unsigned int s=0; s<apt->numSTARs(); ++s) {
725 flightgear::STAR* star = apt->getSTARByIndex(s);
726 naRef procId = stringToNasal(c, star->ident());
727 naVec_append(stars, procId);
734 static naRef f_airport_parking(naContext c, naRef me, int argc, naRef* args)
736 FGAirport* apt = airportGhost(me);
738 naRuntimeError(c, "airport.parking called on non-airport object");
741 naRef r = naNewVector(c);
743 bool onlyAvailable = false;
745 if (argc > 0 && naIsString(args[0])) {
746 type = naStr_data(args[0]);
749 if ((argc > 1) && naIsNum(args[1])) {
750 onlyAvailable = (args[1].num != 0.0);
753 FGAirportDynamics* dynamics = apt->getDynamics();
754 for (int i=0; i<dynamics->getNrOfParkings(); ++i) {
755 FGParking* park = dynamics->getParking(i);
756 // filter out based on availability and type
757 if (onlyAvailable && !park->isAvailable()) {
761 if (!type.empty() && (park->getType() != type)) {
765 naRef nm = stringToNasal(c, park->getName());
772 // Returns vector of data hash for navaid of a <type>, nil on error
773 // navaids sorted by ascending distance
774 // navinfo([<lat>,<lon>],[<type>],[<id>])
775 // lat/lon (numeric): use latitude/longitude instead of ac position
776 // type: ("fix"|"vor"|"ndb"|"ils"|"dme"|"tacan"|"any")
777 // id: (partial) id of the fix
779 // navinfo("vor") returns all vors
780 // navinfo("HAM") return all navaids who's name start with "HAM"
781 // navinfo("vor", "HAM") return all vor who's name start with "HAM"
782 //navinfo(34,48,"vor","HAM") return all vor who's name start with "HAM"
783 // sorted by distance relative to lat=34, lon=48
784 static naRef f_navinfo(naContext c, naRef me, int argc, naRef* args)
788 if(argc >= 2 && naIsNum(args[0]) && naIsNum(args[1])) {
789 pos = SGGeod::fromDeg(args[1].num, args[0].num);
793 pos = globals->get_aircraft_position();
796 FGPositioned::Type type = FGPositioned::INVALID;
797 nav_list_type navlist;
798 const char * id = "";
800 if(argc > 0 && naIsString(args[0])) {
801 const char *s = naStr_data(args[0]);
802 if(!strcmp(s, "any")) type = FGPositioned::INVALID;
803 else if(!strcmp(s, "fix")) type = FGPositioned::FIX;
804 else if(!strcmp(s, "vor")) type = FGPositioned::VOR;
805 else if(!strcmp(s, "ndb")) type = FGPositioned::NDB;
806 else if(!strcmp(s, "ils")) type = FGPositioned::ILS;
807 else if(!strcmp(s, "dme")) type = FGPositioned::DME;
808 else if(!strcmp(s, "tacan")) type = FGPositioned::TACAN;
809 else id = s; // this is an id
814 if(argc > 0 && naIsString(args[0])) {
816 naRuntimeError(c, "navinfo() called with navaid id");
819 id = naStr_data(args[0]);
825 naRuntimeError(c, "navinfo() called with too many arguments");
829 navlist = globals->get_navlist()->findByIdentAndFreq( pos, id, 0.0, type );
831 naRef reply = naNewVector(c);
832 for( nav_list_type::const_iterator it = navlist.begin(); it != navlist.end(); ++it ) {
833 naVec_append( reply, ghostForNavaid(c, *it) );
838 static naRef f_findNavaidsWithinRange(naContext c, naRef me, int argc, naRef* args)
841 SGGeod pos = globals->get_aircraft_position();
842 argOffset += geodFromArgs(args, 0, argc, pos);
844 if (!naIsNum(args[argOffset])) {
845 naRuntimeError(c, "findNavaidsWithinRange expected range (in nm) as arg %d", argOffset);
848 FGPositioned::Type type = FGPositioned::INVALID;
849 double rangeNm = args[argOffset++].num;
850 if (argOffset < argc) {
851 type = FGPositioned::typeFromName(naStr_data(args[argOffset]));
854 naRef r = naNewVector(c);
855 FGNavList::TypeFilter filter(type);
856 FGPositioned::List navs = FGPositioned::findWithinRange(pos, rangeNm, &filter);
857 FGPositioned::sortByRange(navs, pos);
859 BOOST_FOREACH(FGPositionedRef a, navs) {
860 FGNavRecord* nav = (FGNavRecord*) a.get();
861 naVec_append(r, ghostForNavaid(c, nav));
867 static naRef f_findNavaidByFrequency(naContext c, naRef me, int argc, naRef* args)
870 SGGeod pos = globals->get_aircraft_position();
871 argOffset += geodFromArgs(args, 0, argc, pos);
873 if (!naIsNum(args[argOffset])) {
874 naRuntimeError(c, "findNavaidByFrequency expectes frequency (in Mhz) as arg %d", argOffset);
877 FGPositioned::Type type = FGPositioned::INVALID;
878 double freqMhz = args[argOffset++].num;
879 if (argOffset < argc) {
880 type = FGPositioned::typeFromName(naStr_data(args[argOffset]));
883 nav_list_type navs = globals->get_navlist()->findAllByFreq(freqMhz, pos, type);
888 return ghostForNavaid(c, navs.front().ptr());
891 static naRef f_findNavaidsByFrequency(naContext c, naRef me, int argc, naRef* args)
894 SGGeod pos = globals->get_aircraft_position();
895 argOffset += geodFromArgs(args, 0, argc, pos);
897 if (!naIsNum(args[argOffset])) {
898 naRuntimeError(c, "findNavaidsByFrequency expectes frequency (in Mhz) as arg %d", argOffset);
901 FGPositioned::Type type = FGPositioned::INVALID;
902 double freqMhz = args[argOffset++].num;
903 if (argOffset < argc) {
904 type = FGPositioned::typeFromName(naStr_data(args[argOffset]));
907 naRef r = naNewVector(c);
908 nav_list_type navs = globals->get_navlist()->findAllByFreq(freqMhz, pos, type);
910 BOOST_FOREACH(nav_rec_ptr a, navs) {
911 naVec_append(r, ghostForNavaid(c, a.ptr()));
917 static naRef f_findNavaidsByIdent(naContext c, naRef me, int argc, naRef* args)
920 SGGeod pos = globals->get_aircraft_position();
921 argOffset += geodFromArgs(args, 0, argc, pos);
923 if (!naIsString(args[argOffset])) {
924 naRuntimeError(c, "findNavaidsByIdent expectes ident string as arg %d", argOffset);
927 FGPositioned::Type type = FGPositioned::INVALID;
928 string ident = naStr_data(args[argOffset++]);
929 if (argOffset < argc) {
930 type = FGPositioned::typeFromName(naStr_data(args[argOffset]));
933 naRef r = naNewVector(c);
934 nav_list_type navs = globals->get_navlist()->findByIdentAndFreq(pos, ident, 0.0, type);
936 BOOST_FOREACH(nav_rec_ptr a, navs) {
937 naVec_append(r, ghostForNavaid(c, a.ptr()));
944 // Convert a cartesian point to a geodetic lat/lon/altitude.
945 static naRef f_magvar(naContext c, naRef me, int argc, naRef* args)
947 SGGeod pos = globals->get_aircraft_position();
949 // fine, use aircraft position
950 } else if (geodFromArgs(args, 0, argc, pos)) {
953 naRuntimeError(c, "magvar() expects no arguments, a positioned hash or lat,lon pair");
956 double jd = globals->get_time_params()->getJD();
957 double magvarDeg = sgGetMagVar(pos, jd) * SG_RADIANS_TO_DEGREES;
958 return naNum(magvarDeg);
961 static naRef f_courseAndDistance(naContext c, naRef me, int argc, naRef* args)
963 SGGeod from = globals->get_aircraft_position(), to, p;
964 int argOffset = geodFromArgs(args, 0, argc, p);
965 if (geodFromArgs(args, argOffset, argc, to)) {
966 from = p; // we parsed both FROM and TO args, so first was from
968 to = p; // only parsed one arg, so FROM is current
971 if (argOffset == 0) {
972 naRuntimeError(c, "invalid arguments to courseAndDistance");
975 double course, course2, d;
976 SGGeodesy::inverse(from, to, course, course2, d);
978 naRef result = naNewVector(c);
979 naVec_append(result, naNum(course));
980 naVec_append(result, naNum(d * SG_METER_TO_NM));
984 static naRef f_greatCircleMove(naContext c, naRef me, int argc, naRef* args)
986 SGGeod from = globals->get_aircraft_position(), to;
989 // complication - don't inerpret two doubles (as the only args)
990 // as a lat,lon pair - only do so if we have at least three args.
992 argOffset = geodFromArgs(args, 0, argc, from);
995 if ((argOffset + 1) >= argc) {
996 naRuntimeError(c, "isufficent arguments to greatCircleMove");
999 if (!naIsNum(args[argOffset]) || !naIsNum(args[argOffset+1])) {
1000 naRuntimeError(c, "invalid arguments %d and %d to greatCircleMove",
1001 argOffset, argOffset + 1);
1004 double course = args[argOffset].num, course2;
1005 double distanceNm = args[argOffset + 1].num;
1006 SGGeodesy::direct(from, course, distanceNm * SG_NM_TO_METER, to, course2);
1009 naRef coord = naNewHash(c);
1010 hashset(c, coord, "lat", naNum(to.getLatitudeDeg()));
1011 hashset(c, coord, "lon", naNum(to.getLongitudeDeg()));
1015 static naRef f_tilePath(naContext c, naRef me, int argc, naRef* args)
1017 SGGeod pos = globals->get_aircraft_position();
1018 geodFromArgs(args, 0, argc, pos);
1020 return stringToNasal(c, b.gen_base_path());
1023 static naRef f_tileIndex(naContext c, naRef me, int argc, naRef* args)
1025 SGGeod pos = globals->get_aircraft_position();
1026 geodFromArgs(args, 0, argc, pos);
1028 return naNum(b.gen_index());
1031 static naRef f_route(naContext c, naRef me, int argc, naRef* args)
1033 naRef route = naNewHash(c);
1035 // return active route hash by default,
1036 // other routes in the future
1038 naRef parents = naNewVector(c);
1039 naVec_append(parents, routePrototype);
1040 hashset(c, route, "parents", parents);
1045 static naRef f_route_getWP(naContext c, naRef me, int argc, naRef* args)
1047 FGRouteMgr* rm = static_cast<FGRouteMgr*>(globals->get_subsystem("route-manager"));
1051 index = rm->currentIndex();
1053 index = (int) naNumValue(args[0]).num;
1056 if ((index < 0) || (index >= rm->numWaypts())) {
1060 return ghostForWaypt(c, rm->wayptAtIndex(index));
1063 static naRef f_route_currentWP(naContext c, naRef me, int argc, naRef* args)
1065 FGRouteMgr* rm = static_cast<FGRouteMgr*>(globals->get_subsystem("route-manager"));
1066 return ghostForWaypt(c, rm->currentWaypt());
1069 static naRef f_route_nextWP(naContext c, naRef me, int argc, naRef* args)
1071 FGRouteMgr* rm = static_cast<FGRouteMgr*>(globals->get_subsystem("route-manager"));
1072 flightgear::WayptRef wp = rm->nextWaypt();
1076 return ghostForWaypt(c, wp);
1079 static naRef f_route_currentIndex(naContext c, naRef me, int argc, naRef* args)
1081 FGRouteMgr* rm = static_cast<FGRouteMgr*>(globals->get_subsystem("route-manager"));
1082 return naNum(rm->currentIndex());
1085 static naRef f_route_numWaypoints(naContext c, naRef me, int argc, naRef* args)
1087 FGRouteMgr* rm = static_cast<FGRouteMgr*>(globals->get_subsystem("route-manager"));
1088 return naNum(rm->numWaypts());
1091 static naRef f_waypoint_navaid(naContext c, naRef me, int argc, naRef* args)
1093 flightgear::Waypt* w = wayptGhost(me);
1095 naRuntimeError(c, "waypoint.navaid called on non-waypoint object");
1098 FGPositioned* pos = w->source();
1103 switch (pos->type()) {
1104 case FGPositioned::VOR:
1105 case FGPositioned::NDB:
1106 case FGPositioned::ILS:
1107 case FGPositioned::LOC:
1108 case FGPositioned::GS:
1109 case FGPositioned::DME:
1110 case FGPositioned::TACAN: {
1111 FGNavRecord* nav = (FGNavRecord*) pos;
1112 return ghostForNavaid(c, nav);
1120 static naRef f_waypoint_airport(naContext c, naRef me, int argc, naRef* args)
1122 flightgear::Waypt* w = wayptGhost(me);
1124 naRuntimeError(c, "waypoint.navaid called on non-waypoint object");
1127 FGPositioned* pos = w->source();
1128 if (!pos || FGAirport::isAirportType(pos)) {
1132 return ghostForAirport(c, (FGAirport*) pos);
1135 static naRef f_waypoint_runway(naContext c, naRef me, int argc, naRef* args)
1137 flightgear::Waypt* w = wayptGhost(me);
1139 naRuntimeError(c, "waypoint.navaid called on non-waypoint object");
1142 FGPositioned* pos = w->source();
1143 if (!pos || (pos->type() != FGPositioned::RUNWAY)) {
1147 return ghostForRunway(c, (FGRunway*) pos);
1150 // Table of extension functions. Terminate with zeros.
1151 static struct { const char* name; naCFunction func; } funcs[] = {
1152 { "carttogeod", f_carttogeod },
1153 { "geodtocart", f_geodtocart },
1154 { "geodinfo", f_geodinfo },
1155 { "airportinfo", f_airportinfo },
1156 { "findAirportsWithinRange", f_findAirportsWithinRange },
1157 { "findAirportsByICAO", f_findAirportsByICAO },
1158 { "navinfo", f_navinfo },
1159 { "findNavaidsWithinRange", f_findNavaidsWithinRange },
1160 { "findNavaidByFrequency", f_findNavaidByFrequency },
1161 { "findNavaidsByFrequency", f_findNavaidsByFrequency },
1162 { "findNavaidsByID", f_findNavaidsByIdent },
1163 { "route", f_route },
1164 { "magvar", f_magvar },
1165 { "courseAndDistance", f_courseAndDistance },
1166 { "greatCircleMove", f_greatCircleMove },
1167 { "tileIndex", f_tileIndex },
1168 { "tilePath", f_tilePath },
1173 naRef initNasalPositioned(naRef globals, naContext c, naRef gcSave)
1175 airportPrototype = naNewHash(c);
1176 hashset(c, gcSave, "airportProto", airportPrototype);
1178 hashset(c, airportPrototype, "runway", naNewFunc(c, naNewCCode(c, f_airport_runway)));
1179 hashset(c, airportPrototype, "tower", naNewFunc(c, naNewCCode(c, f_airport_tower)));
1180 hashset(c, airportPrototype, "comms", naNewFunc(c, naNewCCode(c, f_airport_comms)));
1181 hashset(c, airportPrototype, "sids", naNewFunc(c, naNewCCode(c, f_airport_sids)));
1182 hashset(c, airportPrototype, "stars", naNewFunc(c, naNewCCode(c, f_airport_stars)));
1183 hashset(c, airportPrototype, "parking", naNewFunc(c, naNewCCode(c, f_airport_parking)));
1185 routePrototype = naNewHash(c);
1186 hashset(c, gcSave, "routeProto", routePrototype);
1188 hashset(c, routePrototype, "getWP", naNewFunc(c, naNewCCode(c, f_route_getWP)));
1189 hashset(c, routePrototype, "currentWP", naNewFunc(c, naNewCCode(c, f_route_currentWP)));
1190 hashset(c, routePrototype, "nextWP", naNewFunc(c, naNewCCode(c, f_route_nextWP)));
1191 hashset(c, routePrototype, "currentIndex", naNewFunc(c, naNewCCode(c, f_route_currentIndex)));
1192 hashset(c, routePrototype, "getPlanSize", naNewFunc(c, naNewCCode(c, f_route_numWaypoints)));
1194 waypointPrototype = naNewHash(c);
1195 hashset(c, gcSave, "wayptProto", waypointPrototype);
1197 hashset(c, waypointPrototype, "navaid", naNewFunc(c, naNewCCode(c, f_waypoint_navaid)));
1198 hashset(c, waypointPrototype, "runway", naNewFunc(c, naNewCCode(c, f_waypoint_runway)));
1199 hashset(c, waypointPrototype, "airport", naNewFunc(c, naNewCCode(c, f_waypoint_airport)));
1201 for(int i=0; funcs[i].name; i++) {
1202 hashset(c, globals, funcs[i].name,
1203 naNewFunc(c, naNewCCode(c, funcs[i].func)));
1209 void postinitNasalPositioned(naRef globals, naContext c)
1211 naRef geoModule = naHash_cget(globals, (char*) "geo");
1212 if (naIsNil(geoModule)) {
1213 SG_LOG(SG_GENERAL, SG_WARN, "postinitNasalPositioned: geo.nas not loaded");
1217 geoCoordClass = naHash_cget(geoModule, (char*) "Coord");