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/scene/material/mat.hxx>
32 #include <simgear/magvar/magvar.hxx>
33 #include <simgear/timing/sg_time.hxx>
34 #include <simgear/bucket/newbucket.hxx>
36 #include <Airports/runways.hxx>
37 #include <Airports/simple.hxx>
38 #include <Airports/dynamics.hxx>
39 #include <Airports/parking.hxx>
40 #include <Navaids/navlist.hxx>
41 #include <Navaids/procedure.hxx>
42 #include <Main/globals.hxx>
43 #include <Main/fg_props.hxx>
44 #include <Scenery/scenery.hxx>
45 #include <ATC/CommStation.hxx>
46 #include <Navaids/route.hxx>
47 #include <Autopilot/route_mgr.hxx>
48 #include <Navaids/procedure.hxx>
50 static void positionedGhostDestroy(void* g);
51 static void wayptGhostDestroy(void* g);
52 naGhostType PositionedGhostType = { positionedGhostDestroy, "positioned" };
53 naGhostType WayptGhostType = { wayptGhostDestroy, "waypoint" };
55 static void hashset(naContext c, naRef hash, const char* key, naRef val)
57 naRef s = naNewString(c);
58 naStr_fromdata(s, (char*)key, strlen(key));
59 naHash_set(hash, s, val);
62 static naRef stringToNasal(naContext c, const std::string& s)
64 return naStr_fromdata(naNewString(c),
65 const_cast<char *>(s.c_str()),
69 static FGPositioned* positionedGhost(naRef r)
71 if (naGhost_type(r) == &PositionedGhostType)
72 return (FGPositioned*) naGhost_ptr(r);
76 static void positionedGhostDestroy(void* g)
78 FGPositioned* pos = (FGPositioned*)g;
79 if (!FGPositioned::put(pos)) // unref
83 static flightgear::Waypt* wayptGhost(naRef r)
85 if (naGhost_type(r) == &WayptGhostType)
86 return (flightgear::Waypt*) naGhost_ptr(r);
90 static void wayptGhostDestroy(void* g)
92 flightgear::Waypt* wpt = (flightgear::Waypt*)g;
93 if (!flightgear::Waypt::put(wpt)) // unref
97 static naRef airportPrototype;
98 static naRef routePrototype;
99 static naRef waypointPrototype;
101 naRef ghostForPositioned(naContext c, const FGPositioned* pos)
107 FGPositioned::get(pos); // take a ref
108 return naNewGhost(c, &PositionedGhostType, (void*) pos);
111 naRef ghostForWaypt(naContext c, const flightgear::Waypt* wpt)
117 flightgear::Waypt::get(wpt); // take a ref
118 return naNewGhost(c, &WayptGhostType, (void*) wpt);
121 naRef hashForAirport(naContext c, const FGAirport* apt)
123 std::string id = apt->ident();
124 std::string name = apt->name();
126 // build runways hash
127 naRef rwys = naNewHash(c);
128 for(unsigned int r=0; r<apt->numRunways(); ++r) {
129 FGRunway* rwy(apt->getRunwayByIndex(r));
130 naRef rwyid = stringToNasal(c, rwy->ident());
131 naRef rwydata = hashForRunway(c, rwy);
132 naHash_set(rwys, rwyid, rwydata);
135 naRef aptdata = naNewHash(c);
136 hashset(c, aptdata, "id", stringToNasal(c, id));
137 hashset(c, aptdata, "name", stringToNasal(c, name));
138 hashset(c, aptdata, "lat", naNum(apt->getLatitude()));
139 hashset(c, aptdata, "lon", naNum(apt->getLongitude()));
140 hashset(c, aptdata, "elevation", naNum(apt->getElevation() * SG_FEET_TO_METER));
141 hashset(c, aptdata, "has_metar", naNum(apt->getMetar()));
142 hashset(c, aptdata, "runways", rwys);
143 hashset(c, aptdata, "_positioned", ghostForPositioned(c, apt));
144 naRef parents = naNewVector(c);
145 naVec_append(parents, airportPrototype);
146 hashset(c, aptdata, "parents", parents);
151 naRef hashForWaypoint(naContext c, flightgear::Waypt* wpt, flightgear::Waypt* next)
153 SGGeod pos = wpt->position();
154 naRef h = naNewHash(c);
156 flightgear::Procedure* proc = dynamic_cast<flightgear::Procedure*>(wpt->owner());
158 hashset(c, h, "wp_parent_name", stringToNasal(c, proc->ident()));
159 // set 'wp_parent' route object to query the SID / STAR / airway?
160 // TODO - needs some extensions to flightgear::Route
163 if (wpt->type() == "hold") {
164 hashset(c, h, "fly_type", stringToNasal(c, "Hold"));
165 } else if (wpt->flag(flightgear::WPT_OVERFLIGHT)) {
166 hashset(c, h, "fly_type", stringToNasal(c, "flyOver"));
168 hashset(c, h, "fly_type", stringToNasal(c, "flyBy"));
171 hashset(c, h, "wp_type", stringToNasal(c, wpt->type()));
172 hashset(c, h, "wp_name", stringToNasal(c, wpt->ident()));
173 hashset(c, h, "wp_lat", naNum(pos.getLatitudeDeg()));
174 hashset(c, h, "wp_lon", naNum(pos.getLongitudeDeg()));
175 hashset(c, h, "alt_cstr", naNum(wpt->altitudeFt()));
177 if (wpt->speedRestriction() == flightgear::SPEED_RESTRICT_MACH) {
178 hashset(c, h, "spd_cstr", naNum(wpt->speedMach()));
180 hashset(c, h, "spd_cstr", naNum(wpt->speedKts()));
184 std::pair<double, double> crsDist =
185 next->courseAndDistanceFrom(pos);
186 hashset(c, h, "leg_distance", naNum(crsDist.second * SG_METER_TO_NM));
187 hashset(c, h, "leg_bearing", naNum(crsDist.first));
188 hashset(c, h, "hdg_radial", naNum(wpt->headingRadialDeg()));
191 // leg bearing, distance, etc
194 // parents and ghost of the C++ object
195 hashset(c, h, "_waypt", ghostForWaypt(c, wpt));
196 naRef parents = naNewVector(c);
197 naVec_append(parents, waypointPrototype);
198 hashset(c, h, "parents", parents);
204 naRef hashForRunway(naContext c, FGRunway* rwy)
206 naRef rwyid = stringToNasal(c, rwy->ident());
207 naRef rwydata = naNewHash(c);
208 #define HASHSET(s,l,n) naHash_set(rwydata, naStr_fromdata(naNewString(c),s,l),n)
209 HASHSET("id", 2, rwyid);
210 HASHSET("lat", 3, naNum(rwy->latitude()));
211 HASHSET("lon", 3, naNum(rwy->longitude()));
212 HASHSET("heading", 7, naNum(rwy->headingDeg()));
213 HASHSET("length", 6, naNum(rwy->lengthM()));
214 HASHSET("width", 5, naNum(rwy->widthM()));
215 HASHSET("threshold", 9, naNum(rwy->displacedThresholdM()));
216 HASHSET("stopway", 7, naNum(rwy->stopwayM()));
219 HASHSET("ils_frequency_mhz", 17, naNum(rwy->ILS()->get_freq() / 100.0));
220 HASHSET("ils", 3, hashForNavRecord(c, rwy->ILS(), SGGeod()));
223 HASHSET("_positioned", 11, ghostForPositioned(c, rwy));
228 naRef hashForNavRecord(naContext c, const FGNavRecord* nav, const SGGeod& rel)
230 naRef navdata = naNewHash(c);
231 #define HASHSET(s,l,n) naHash_set(navdata, naStr_fromdata(naNewString(c),s,l),n)
232 HASHSET("id", 2, stringToNasal(c, nav->ident()));
233 HASHSET("name", 4, stringToNasal(c, nav->name()));
234 HASHSET("frequency", 9, naNum(nav->get_freq()));
235 HASHSET("lat", 3, naNum(nav->get_lat()));
236 HASHSET("lon", 3, naNum(nav->get_lon()));
237 HASHSET("elevation", 9, naNum(nav->get_elev_ft() * SG_FEET_TO_METER));
238 HASHSET("type", 4, stringToNasal(c, nav->nameForType(nav->type())));
240 // FIXME - get rid of these, people should use courseAndDistance instead
241 HASHSET("distance", 8, naNum(SGGeodesy::distanceNm( rel, nav->geod() ) * SG_NM_TO_METER ) );
242 HASHSET("bearing", 7, naNum(SGGeodesy::courseDeg( rel, nav->geod() ) ) );
244 // record the real object as a ghost for further operations
245 HASHSET("_positioned",11, ghostForPositioned(c, nav));
251 bool geodFromHash(naRef ref, SGGeod& result)
253 if (!naIsHash(ref)) {
257 // first, see if the hash contains a FGPositioned ghost - in which case
258 // we can read off its position directly
259 naRef posGhost = naHash_cget(ref, (char*) "_positioned");
260 if (!naIsNil(posGhost)) {
261 FGPositioned* pos = positionedGhost(posGhost);
262 result = pos->geod();
266 naRef ghost = naHash_cget(ref, (char*) "_waypt");
267 if (!naIsNil(ghost)) {
268 flightgear::Waypt* w = wayptGhost(ghost);
269 result = w->position();
273 // then check for manual latitude / longitude names
274 naRef lat = naHash_cget(ref, (char*) "lat");
275 naRef lon = naHash_cget(ref, (char*) "lon");
276 if (naIsNum(lat) && naIsNum(lon)) {
277 result = SGGeod::fromDeg(naNumValue(lat).num, naNumValue(lon).num);
281 // check for geo.Coord type
283 // check for any synonyms?
284 // latitude + longitude?
289 static int geodFromArgs(naRef* args, int offset, int argc, SGGeod& result)
291 if (offset >= argc) {
295 if (geodFromHash(args[offset], result)) {
299 if (((argc - offset) >= 2) && naIsNum(args[offset]) && naIsNum(args[offset + 1])) {
300 double lat = naNumValue(args[0]).num,
301 lon = naNumValue(args[1]).num;
302 result = SGGeod::fromDeg(lon, lat);
309 // Convert a cartesian point to a geodetic lat/lon/altitude.
310 static naRef f_carttogeod(naContext c, naRef me, int argc, naRef* args)
312 double lat, lon, alt, xyz[3];
313 if(argc != 3) naRuntimeError(c, "carttogeod() expects 3 arguments");
314 for(int i=0; i<3; i++)
315 xyz[i] = naNumValue(args[i]).num;
316 sgCartToGeod(xyz, &lat, &lon, &alt);
317 lat *= SG_RADIANS_TO_DEGREES;
318 lon *= SG_RADIANS_TO_DEGREES;
319 naRef vec = naNewVector(c);
320 naVec_append(vec, naNum(lat));
321 naVec_append(vec, naNum(lon));
322 naVec_append(vec, naNum(alt));
326 // Convert a geodetic lat/lon/altitude to a cartesian point.
327 static naRef f_geodtocart(naContext c, naRef me, int argc, naRef* args)
329 if(argc != 3) naRuntimeError(c, "geodtocart() expects 3 arguments");
330 double lat = naNumValue(args[0]).num * SG_DEGREES_TO_RADIANS;
331 double lon = naNumValue(args[1]).num * SG_DEGREES_TO_RADIANS;
332 double alt = naNumValue(args[2]).num;
334 sgGeodToCart(lat, lon, alt, xyz);
335 naRef vec = naNewVector(c);
336 naVec_append(vec, naNum(xyz[0]));
337 naVec_append(vec, naNum(xyz[1]));
338 naVec_append(vec, naNum(xyz[2]));
342 // For given geodetic point return array with elevation, and a material data
343 // hash, or nil if there's no information available (tile not loaded). If
344 // information about the material isn't available, then nil is returned instead
346 static naRef f_geodinfo(naContext c, naRef me, int argc, naRef* args)
348 #define HASHSET(s,l,n) naHash_set(matdata, naStr_fromdata(naNewString(c),s,l),n)
349 if(argc < 2 || argc > 3)
350 naRuntimeError(c, "geodinfo() expects 2 or 3 arguments: lat, lon [, maxalt]");
351 double lat = naNumValue(args[0]).num;
352 double lon = naNumValue(args[1]).num;
353 double elev = argc == 3 ? naNumValue(args[2]).num : 10000;
354 const SGMaterial *mat;
355 SGGeod geod = SGGeod::fromDegM(lon, lat, elev);
356 if(!globals->get_scenery()->get_elevation_m(geod, elev, &mat))
358 naRef vec = naNewVector(c);
359 naVec_append(vec, naNum(elev));
360 naRef matdata = naNil();
362 matdata = naNewHash(c);
363 naRef names = naNewVector(c);
364 BOOST_FOREACH(const std::string& n, mat->get_names())
365 naVec_append(names, stringToNasal(c, n));
367 HASHSET("names", 5, names);
368 HASHSET("solid", 5, naNum(mat->get_solid()));
369 HASHSET("friction_factor", 15, naNum(mat->get_friction_factor()));
370 HASHSET("rolling_friction", 16, naNum(mat->get_rolling_friction()));
371 HASHSET("load_resistance", 15, naNum(mat->get_load_resistance()));
372 HASHSET("bumpiness", 9, naNum(mat->get_bumpiness()));
373 HASHSET("light_coverage", 14, naNum(mat->get_light_coverage()));
375 naVec_append(vec, matdata);
381 class AirportInfoFilter : public FGAirport::AirportFilter
384 AirportInfoFilter() : type(FGPositioned::AIRPORT) {
387 bool fromArg(naRef arg)
389 const char *s = naStr_data(arg);
390 if(!strcmp(s, "airport")) type = FGPositioned::AIRPORT;
391 else if(!strcmp(s, "seaport")) type = FGPositioned::SEAPORT;
392 else if(!strcmp(s, "heliport")) type = FGPositioned::HELIPORT;
399 virtual FGPositioned::Type minType() const {
403 virtual FGPositioned::Type maxType() const {
407 FGPositioned::Type type;
410 // Returns data hash for particular or nearest airport of a <type>, or nil
413 // airportinfo(<id>); e.g. "KSFO"
414 // airportinfo(<type>); type := ("airport"|"seaport"|"heliport")
415 // airportinfo() same as airportinfo("airport")
416 // airportinfo(<lat>, <lon> [, <type>]);
417 static naRef f_airportinfo(naContext c, naRef me, int argc, naRef* args)
419 SGGeod pos = globals->get_aircraft_position();
420 FGAirport* apt = NULL;
422 if(argc >= 2 && naIsNum(args[0]) && naIsNum(args[1])) {
423 pos = SGGeod::fromDeg(args[1].num, args[0].num);
428 double maxRange = 10000.0; // expose this? or pick a smaller value?
430 AirportInfoFilter filter; // defaults to airports only
433 // fall through and use AIRPORT
434 } else if(argc == 1 && naIsString(args[0])) {
435 if (filter.fromArg(args[0])) {
438 // user provided an <id>, hopefully
439 apt = FGAirport::findByIdent(naStr_data(args[0]));
441 // return nil here, but don't raise a runtime error; this is a
442 // legitamate way to validate an ICAO code, for example in a
443 // dialog box or similar.
448 naRuntimeError(c, "airportinfo() with invalid function arguments");
453 apt = FGAirport::findClosest(pos, maxRange, &filter);
454 if(!apt) return naNil();
457 return hashForAirport(c, apt);
460 static naRef f_findAirportsWithinRange(naContext c, naRef me, int argc, naRef* args)
463 SGGeod pos = globals->get_aircraft_position();
464 argOffset += geodFromArgs(args, 0, argc, pos);
466 if (!naIsNum(args[argOffset])) {
467 naRuntimeError(c, "findAirportsWithinRange expected range (in nm) as arg %d", argOffset);
470 AirportInfoFilter filter; // defaults to airports only
471 double rangeNm = args[argOffset++].num;
472 if (argOffset < argc) {
473 filter.fromArg(args[argOffset++]);
476 naRef r = naNewVector(c);
478 FGPositioned::List apts = FGPositioned::findWithinRange(pos, rangeNm, &filter);
479 FGPositioned::sortByRange(apts, pos);
481 BOOST_FOREACH(FGPositionedRef a, apts) {
482 FGAirport* apt = (FGAirport*) a.get();
483 naVec_append(r, hashForAirport(c, apt));
489 static naRef f_findAirportsByICAO(naContext c, naRef me, int argc, naRef* args)
491 if (!naIsString(args[0])) {
492 naRuntimeError(c, "findAirportsByICAO expects string as arg 0");
496 string prefix(naStr_data(args[argOffset++]));
497 AirportInfoFilter filter; // defaults to airports only
498 if (argOffset < argc) {
499 filter.fromArg(args[argOffset++]);
502 naRef r = naNewVector(c);
504 FGPositioned::List apts = FGPositioned::findAllWithIdent(prefix, &filter, false);
506 BOOST_FOREACH(FGPositionedRef a, apts) {
507 FGAirport* apt = (FGAirport*) a.get();
508 naVec_append(r, hashForAirport(c, apt));
514 static FGAirport* airportFromMe(naRef me)
516 naRef ghost = naHash_cget(me, (char*) "_positioned");
517 if (naIsNil(ghost)) {
521 FGPositioned* pos = positionedGhost(ghost);
522 if (pos && FGAirport::isAirportType(pos)) {
523 return (FGAirport*) pos;
529 static naRef f_airport_tower(naContext c, naRef me, int argc, naRef* args)
531 FGAirport* apt = airportFromMe(me);
533 naRuntimeError(c, "airport.tower called on non-airport object");
536 // build a hash for the tower position
537 SGGeod towerLoc = apt->getTowerLocation();
538 naRef tower = naNewHash(c);
539 hashset(c, tower, "lat", naNum(towerLoc.getLatitudeDeg()));
540 hashset(c, tower, "lon", naNum(towerLoc.getLongitudeDeg()));
541 hashset(c, tower, "elevation", naNum(towerLoc.getElevationM()));
545 static naRef f_airport_comms(naContext c, naRef me, int argc, naRef* args)
547 FGAirport* apt = airportFromMe(me);
549 naRuntimeError(c, "airport.comms called on non-airport object");
551 naRef comms = naNewVector(c);
553 // if we have an explicit type, return a simple vector of frequencies
554 if (argc > 0 && naIsScalar(args[0])) {
555 std::string commName = naStr_data(args[0]);
556 FGPositioned::Type commType = FGPositioned::typeFromName(commName);
558 BOOST_FOREACH(flightgear::CommStation* comm, apt->commStationsOfType(commType)) {
559 naVec_append(comms, naNum(comm->freqMHz()));
562 // otherwise return a vector of hashes, one for each comm station.
563 BOOST_FOREACH(flightgear::CommStation* comm, apt->commStations()) {
564 naRef commHash = naNewHash(c);
565 hashset(c, commHash, "frequency", naNum(comm->freqMHz()));
566 hashset(c, commHash, "ident", stringToNasal(c, comm->ident()));
567 naVec_append(comms, commHash);
574 static naRef f_airport_sids(naContext c, naRef me, int argc, naRef* args)
576 FGAirport* apt = airportFromMe(me);
578 naRuntimeError(c, "airport.sids called on non-airport object");
581 naRef sids = naNewVector(c);
583 // if we have an explicit type, return a simple vector of frequencies
584 if (argc > 0 && naIsString(args[0])) {
585 if (!apt->hasRunwayWithIdent(naStr_data(args[0]))) {
589 FGRunway* rwy = apt->getRunwayByIdent(naStr_data(args[0]));
590 BOOST_FOREACH(flightgear::SID* sid, rwy->getSIDs()) {
591 naRef procId = stringToNasal(c, sid->ident());
592 naVec_append(sids, procId);
595 for (unsigned int s=0; s<apt->numSIDs(); ++s) {
596 flightgear::SID* sid = apt->getSIDByIndex(s);
597 naRef procId = stringToNasal(c, sid->ident());
598 naVec_append(sids, procId);
605 static naRef f_airport_stars(naContext c, naRef me, int argc, naRef* args)
607 FGAirport* apt = airportFromMe(me);
609 naRuntimeError(c, "airport.stars called on non-airport object");
612 naRef stars = naNewVector(c);
614 // if we have an explicit type, return a simple vector of frequencies
615 if (argc > 0 && naIsString(args[0])) {
616 if (!apt->hasRunwayWithIdent(naStr_data(args[0]))) {
620 FGRunway* rwy = apt->getRunwayByIdent(naStr_data(args[0]));
621 BOOST_FOREACH(flightgear::STAR* s, rwy->getSTARs()) {
622 naRef procId = stringToNasal(c, s->ident());
623 naVec_append(stars, procId);
626 for (unsigned int s=0; s<apt->numSTARs(); ++s) {
627 flightgear::STAR* star = apt->getSTARByIndex(s);
628 naRef procId = stringToNasal(c, star->ident());
629 naVec_append(stars, procId);
636 static naRef f_airport_parking(naContext c, naRef me, int argc, naRef* args)
638 FGAirport* apt = airportFromMe(me);
640 naRuntimeError(c, "airport.parking called on non-airport object");
643 naRef r = naNewVector(c);
645 bool onlyAvailable = false;
647 if (argc > 0 && naIsString(args[0])) {
648 type = naStr_data(args[0]);
651 if ((argc > 1) && naIsNum(args[1])) {
652 onlyAvailable = (args[1].num != 0.0);
655 FGAirportDynamics* dynamics = apt->getDynamics();
656 for (int i=0; i<dynamics->getNrOfParkings(); ++i) {
657 FGParking* park = dynamics->getParking(i);
658 // filter out based on availability and type
659 if (onlyAvailable && !park->isAvailable()) {
663 if (!type.empty() && (park->getType() != type)) {
667 naRef nm = stringToNasal(c, park->getName());
674 // Returns vector of data hash for navaid of a <type>, nil on error
675 // navaids sorted by ascending distance
676 // navinfo([<lat>,<lon>],[<type>],[<id>])
677 // lat/lon (numeric): use latitude/longitude instead of ac position
678 // type: ("fix"|"vor"|"ndb"|"ils"|"dme"|"tacan"|"any")
679 // id: (partial) id of the fix
681 // navinfo("vor") returns all vors
682 // navinfo("HAM") return all navaids who's name start with "HAM"
683 // navinfo("vor", "HAM") return all vor who's name start with "HAM"
684 //navinfo(34,48,"vor","HAM") return all vor who's name start with "HAM"
685 // sorted by distance relative to lat=34, lon=48
686 static naRef f_navinfo(naContext c, naRef me, int argc, naRef* args)
690 if(argc >= 2 && naIsNum(args[0]) && naIsNum(args[1])) {
691 pos = SGGeod::fromDeg(args[1].num, args[0].num);
695 pos = globals->get_aircraft_position();
698 FGPositioned::Type type = FGPositioned::INVALID;
699 nav_list_type navlist;
700 const char * id = "";
702 if(argc > 0 && naIsString(args[0])) {
703 const char *s = naStr_data(args[0]);
704 if(!strcmp(s, "any")) type = FGPositioned::INVALID;
705 else if(!strcmp(s, "fix")) type = FGPositioned::FIX;
706 else if(!strcmp(s, "vor")) type = FGPositioned::VOR;
707 else if(!strcmp(s, "ndb")) type = FGPositioned::NDB;
708 else if(!strcmp(s, "ils")) type = FGPositioned::ILS;
709 else if(!strcmp(s, "dme")) type = FGPositioned::DME;
710 else if(!strcmp(s, "tacan")) type = FGPositioned::TACAN;
711 else id = s; // this is an id
716 if(argc > 0 && naIsString(args[0])) {
718 naRuntimeError(c, "navinfo() called with navaid id");
721 id = naStr_data(args[0]);
727 naRuntimeError(c, "navinfo() called with too many arguments");
731 navlist = globals->get_navlist()->findByIdentAndFreq( pos, id, 0.0, type );
733 naRef reply = naNewVector(c);
734 for( nav_list_type::const_iterator it = navlist.begin(); it != navlist.end(); ++it ) {
735 naVec_append( reply, hashForNavRecord(c, *it, pos) );
740 static naRef f_findNavaidsWithinRange(naContext c, naRef me, int argc, naRef* args)
743 SGGeod pos = globals->get_aircraft_position();
744 argOffset += geodFromArgs(args, 0, argc, pos);
746 if (!naIsNum(args[argOffset])) {
747 naRuntimeError(c, "findNavaidsWithinRange expected range (in nm) as arg %d", argOffset);
750 FGPositioned::Type type = FGPositioned::INVALID;
751 double rangeNm = args[argOffset++].num;
752 if (argOffset < argc) {
753 type = FGPositioned::typeFromName(naStr_data(args[argOffset]));
756 naRef r = naNewVector(c);
757 FGNavList::TypeFilter filter(type);
758 FGPositioned::List navs = FGPositioned::findWithinRange(pos, rangeNm, &filter);
759 FGPositioned::sortByRange(navs, pos);
761 BOOST_FOREACH(FGPositionedRef a, navs) {
762 FGNavRecord* nav = (FGNavRecord*) a.get();
763 naVec_append(r, hashForNavRecord(c, nav, pos));
769 static naRef f_findNavaidByFrequency(naContext c, naRef me, int argc, naRef* args)
772 SGGeod pos = globals->get_aircraft_position();
773 argOffset += geodFromArgs(args, 0, argc, pos);
775 if (!naIsNum(args[argOffset])) {
776 naRuntimeError(c, "findNavaidByFrequency expectes frequency (in Mhz) as arg %d", argOffset);
779 FGPositioned::Type type = FGPositioned::INVALID;
780 double freqMhz = args[argOffset++].num;
781 if (argOffset < argc) {
782 type = FGPositioned::typeFromName(naStr_data(args[argOffset]));
785 nav_list_type navs = globals->get_navlist()->findAllByFreq(freqMhz, pos, type);
790 return hashForNavRecord(c, navs.front().ptr(), pos);
793 static naRef f_findNavaidsByFrequency(naContext c, naRef me, int argc, naRef* args)
796 SGGeod pos = globals->get_aircraft_position();
797 argOffset += geodFromArgs(args, 0, argc, pos);
799 if (!naIsNum(args[argOffset])) {
800 naRuntimeError(c, "findNavaidsByFrequency expectes frequency (in Mhz) as arg %d", argOffset);
803 FGPositioned::Type type = FGPositioned::INVALID;
804 double freqMhz = args[argOffset++].num;
805 if (argOffset < argc) {
806 type = FGPositioned::typeFromName(naStr_data(args[argOffset]));
809 naRef r = naNewVector(c);
810 nav_list_type navs = globals->get_navlist()->findAllByFreq(freqMhz, pos, type);
812 BOOST_FOREACH(nav_rec_ptr a, navs) {
813 naVec_append(r, hashForNavRecord(c, a.ptr(), pos));
819 static naRef f_findNavaidsByIdent(naContext c, naRef me, int argc, naRef* args)
822 SGGeod pos = globals->get_aircraft_position();
823 argOffset += geodFromArgs(args, 0, argc, pos);
825 if (!naIsString(args[argOffset])) {
826 naRuntimeError(c, "findNavaidsByIdent expectes ident string as arg %d", argOffset);
829 FGPositioned::Type type = FGPositioned::INVALID;
830 string ident = naStr_data(args[argOffset++]);
831 if (argOffset < argc) {
832 type = FGPositioned::typeFromName(naStr_data(args[argOffset]));
835 naRef r = naNewVector(c);
836 nav_list_type navs = globals->get_navlist()->findByIdentAndFreq(pos, ident, 0.0, type);
838 BOOST_FOREACH(nav_rec_ptr a, navs) {
839 naVec_append(r, hashForNavRecord(c, a.ptr(), pos));
846 // Convert a cartesian point to a geodetic lat/lon/altitude.
847 static naRef f_magvar(naContext c, naRef me, int argc, naRef* args)
849 SGGeod pos = globals->get_aircraft_position();
851 // fine, use aircraft position
852 } else if (geodFromArgs(args, 0, argc, pos)) {
855 naRuntimeError(c, "magvar() expects no arguments, a positioned hash or lat,lon pair");
858 double jd = globals->get_time_params()->getJD();
859 double magvarDeg = sgGetMagVar(pos, jd) * SG_RADIANS_TO_DEGREES;
860 return naNum(magvarDeg);
863 static naRef f_courseAndDistance(naContext c, naRef me, int argc, naRef* args)
865 SGGeod from = globals->get_aircraft_position(), to, p;
866 int argOffset = geodFromArgs(args, 0, argc, p);
867 if (geodFromArgs(args, argOffset, argc, to)) {
868 from = p; // we parsed both FROM and TO args, so first was from
870 to = p; // only parsed one arg, so FROM is current
873 if (argOffset == 0) {
874 naRuntimeError(c, "invalid arguments to courseAndDistance");
877 double course, course2, d;
878 SGGeodesy::inverse(from, to, course, course2, d);
880 naRef result = naNewVector(c);
881 naVec_append(result, naNum(course));
882 naVec_append(result, naNum(d * SG_METER_TO_NM));
886 static naRef f_tilePath(naContext c, naRef me, int argc, naRef* args)
888 SGGeod pos = globals->get_aircraft_position();
889 geodFromArgs(args, 0, argc, pos);
891 return stringToNasal(c, b.gen_base_path());
894 static naRef f_route(naContext c, naRef me, int argc, naRef* args)
896 naRef route = naNewHash(c);
898 // return active route hash by default,
899 // other routes in the future
901 naRef parents = naNewVector(c);
902 naVec_append(parents, routePrototype);
903 hashset(c, route, "parents", parents);
908 static naRef f_route_getWP(naContext c, naRef me, int argc, naRef* args)
910 FGRouteMgr* rm = static_cast<FGRouteMgr*>(globals->get_subsystem("route-manager"));
914 index = rm->currentIndex();
916 index = (int) naNumValue(args[0]).num;
919 if ((index < 0) || (index >= rm->numWaypts())) {
923 flightgear::Waypt* next = NULL;
924 if (index < (rm->numWaypts() - 1)) {
925 next = rm->wayptAtIndex(index + 1);
927 return hashForWaypoint(c, rm->wayptAtIndex(index), next);
930 static naRef f_route_currentWP(naContext c, naRef me, int argc, naRef* args)
932 FGRouteMgr* rm = static_cast<FGRouteMgr*>(globals->get_subsystem("route-manager"));
933 flightgear::Waypt* next = NULL;
934 if (rm->currentIndex() < (rm->numWaypts() - 1)) {
935 next = rm->wayptAtIndex(rm->currentIndex() + 1);
937 return hashForWaypoint(c, rm->currentWaypt(), next);
940 static naRef f_route_currentIndex(naContext c, naRef me, int argc, naRef* args)
942 FGRouteMgr* rm = static_cast<FGRouteMgr*>(globals->get_subsystem("route-manager"));
943 return naNum(rm->currentIndex());
946 static naRef f_route_numWaypoints(naContext c, naRef me, int argc, naRef* args)
948 FGRouteMgr* rm = static_cast<FGRouteMgr*>(globals->get_subsystem("route-manager"));
949 return naNum(rm->numWaypts());
952 static flightgear::Waypt* wayptFromMe(naRef me)
954 naRef ghost = naHash_cget(me, (char*) "_waypt");
955 if (naIsNil(ghost)) {
959 return wayptGhost(ghost);
962 static naRef f_waypoint_navaid(naContext c, naRef me, int argc, naRef* args)
964 flightgear::Waypt* w = wayptFromMe(me);
966 naRuntimeError(c, "waypoint.navaid called on non-waypoint object");
969 FGPositioned* pos = w->source();
974 switch (pos->type()) {
975 case FGPositioned::VOR:
976 case FGPositioned::NDB:
977 case FGPositioned::ILS:
978 case FGPositioned::LOC:
979 case FGPositioned::GS:
980 case FGPositioned::DME:
981 case FGPositioned::TACAN: {
982 FGNavRecord* nav = (FGNavRecord*) pos;
983 return hashForNavRecord(c, nav, globals->get_aircraft_position());
991 static naRef f_waypoint_airport(naContext c, naRef me, int argc, naRef* args)
993 flightgear::Waypt* w = wayptFromMe(me);
995 naRuntimeError(c, "waypoint.navaid called on non-waypoint object");
998 FGPositioned* pos = w->source();
999 if (!pos || FGAirport::isAirportType(pos)) {
1003 return hashForAirport(c, (FGAirport*) pos);
1006 static naRef f_waypoint_runway(naContext c, naRef me, int argc, naRef* args)
1008 flightgear::Waypt* w = wayptFromMe(me);
1010 naRuntimeError(c, "waypoint.navaid called on non-waypoint object");
1013 FGPositioned* pos = w->source();
1014 if (!pos || (pos->type() != FGPositioned::RUNWAY)) {
1018 return hashForRunway(c, (FGRunway*) pos);
1021 // Table of extension functions. Terminate with zeros.
1022 static struct { const char* name; naCFunction func; } funcs[] = {
1023 { "carttogeod", f_carttogeod },
1024 { "geodtocart", f_geodtocart },
1025 { "geodinfo", f_geodinfo },
1026 { "airportinfo", f_airportinfo },
1027 { "findAirportsWithinRange", f_findAirportsWithinRange },
1028 { "findAirportsByICAO", f_findAirportsByICAO },
1029 { "navinfo", f_navinfo },
1030 { "findNavaidsWithinRange", f_findNavaidsWithinRange },
1031 { "findNavaidByFrequency", f_findNavaidByFrequency },
1032 { "findNavaidsByFrequency", f_findNavaidsByFrequency },
1033 { "findNavaidsByID", f_findNavaidsByIdent },
1034 { "route", f_route },
1035 { "magvar", f_magvar },
1036 { "courseAndDistance", f_courseAndDistance },
1037 { "bucketPath", f_tilePath },
1042 naRef initNasalPositioned(naRef globals, naContext c, naRef gcSave)
1044 airportPrototype = naNewHash(c);
1045 hashset(c, gcSave, "airportProto", airportPrototype);
1047 hashset(c, airportPrototype, "tower", naNewFunc(c, naNewCCode(c, f_airport_tower)));
1048 hashset(c, airportPrototype, "comms", naNewFunc(c, naNewCCode(c, f_airport_comms)));
1049 hashset(c, airportPrototype, "sids", naNewFunc(c, naNewCCode(c, f_airport_sids)));
1050 hashset(c, airportPrototype, "stars", naNewFunc(c, naNewCCode(c, f_airport_stars)));
1051 hashset(c, airportPrototype, "parking", naNewFunc(c, naNewCCode(c, f_airport_parking)));
1053 routePrototype = naNewHash(c);
1054 hashset(c, gcSave, "routeProto", routePrototype);
1056 hashset(c, routePrototype, "getWP", naNewFunc(c, naNewCCode(c, f_route_getWP)));
1057 hashset(c, routePrototype, "currentWP", naNewFunc(c, naNewCCode(c, f_route_currentWP)));
1058 hashset(c, routePrototype, "currentIndex", naNewFunc(c, naNewCCode(c, f_route_currentIndex)));
1059 hashset(c, routePrototype, "getPlanSize", naNewFunc(c, naNewCCode(c, f_route_numWaypoints)));
1061 waypointPrototype = naNewHash(c);
1062 hashset(c, gcSave, "wayptProto", waypointPrototype);
1064 hashset(c, waypointPrototype, "navaid", naNewFunc(c, naNewCCode(c, f_waypoint_navaid)));
1065 hashset(c, waypointPrototype, "runway", naNewFunc(c, naNewCCode(c, f_waypoint_runway)));
1066 hashset(c, waypointPrototype, "airport", naNewFunc(c, naNewCCode(c, f_waypoint_airport)));
1068 for(int i=0; funcs[i].name; i++) {
1069 hashset(c, globals, funcs[i].name,
1070 naNewFunc(c, naNewCCode(c, funcs[i].func)));