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 sgrefGhostDestroy(void* g);
51 naGhostType PositionedGhostType = { sgrefGhostDestroy, "positioned" };
52 naGhostType WayptGhostType = { sgrefGhostDestroy, "waypoint" };
54 static void hashset(naContext c, naRef hash, const char* key, naRef val)
56 naRef s = naNewString(c);
57 naStr_fromdata(s, (char*)key, strlen(key));
58 naHash_set(hash, s, val);
61 static naRef stringToNasal(naContext c, const std::string& s)
63 return naStr_fromdata(naNewString(c),
64 const_cast<char *>(s.c_str()),
68 static FGPositioned* positionedGhost(naRef r)
70 if (naGhost_type(r) == &PositionedGhostType)
71 return (FGPositioned*) naGhost_ptr(r);
75 static flightgear::Waypt* wayptGhost(naRef r)
77 if (naGhost_type(r) == &WayptGhostType)
78 return (flightgear::Waypt*) naGhost_ptr(r);
82 static void sgrefGhostDestroy(void* g)
84 SGReferenced* ref = (SGReferenced*)g;
85 SGReferenced::put(ref); // unref
88 static naRef airportPrototype;
89 static naRef routePrototype;
90 static naRef waypointPrototype;
92 naRef ghostForPositioned(naContext c, const FGPositioned* pos)
98 SGReferenced::get(pos); // take a ref
99 return naNewGhost(c, &PositionedGhostType, (void*) pos);
102 naRef ghostForWaypt(naContext c, const flightgear::Waypt* wpt)
108 SGReferenced::get(wpt); // take a ref
109 return naNewGhost(c, &WayptGhostType, (void*) wpt);
112 naRef hashForAirport(naContext c, const FGAirport* apt)
114 std::string id = apt->ident();
115 std::string name = apt->name();
117 // build runways hash
118 naRef rwys = naNewHash(c);
119 for(unsigned int r=0; r<apt->numRunways(); ++r) {
120 FGRunway* rwy(apt->getRunwayByIndex(r));
121 naRef rwyid = stringToNasal(c, rwy->ident());
122 naRef rwydata = hashForRunway(c, rwy);
123 naHash_set(rwys, rwyid, rwydata);
126 naRef aptdata = naNewHash(c);
127 hashset(c, aptdata, "id", stringToNasal(c, id));
128 hashset(c, aptdata, "name", stringToNasal(c, name));
129 hashset(c, aptdata, "lat", naNum(apt->getLatitude()));
130 hashset(c, aptdata, "lon", naNum(apt->getLongitude()));
131 hashset(c, aptdata, "elevation", naNum(apt->getElevation() * SG_FEET_TO_METER));
132 hashset(c, aptdata, "has_metar", naNum(apt->getMetar()));
133 hashset(c, aptdata, "runways", rwys);
134 hashset(c, aptdata, "_positioned", ghostForPositioned(c, apt));
135 naRef parents = naNewVector(c);
136 naVec_append(parents, airportPrototype);
137 hashset(c, aptdata, "parents", parents);
142 naRef hashForWaypoint(naContext c, flightgear::Waypt* wpt, flightgear::Waypt* next)
144 SGGeod pos = wpt->position();
145 naRef h = naNewHash(c);
147 flightgear::Procedure* proc = dynamic_cast<flightgear::Procedure*>(wpt->owner());
149 hashset(c, h, "wp_parent_name", stringToNasal(c, proc->ident()));
150 // set 'wp_parent' route object to query the SID / STAR / airway?
151 // TODO - needs some extensions to flightgear::Route
154 if (wpt->type() == "hold") {
155 hashset(c, h, "fly_type", stringToNasal(c, "Hold"));
156 } else if (wpt->flag(flightgear::WPT_OVERFLIGHT)) {
157 hashset(c, h, "fly_type", stringToNasal(c, "flyOver"));
159 hashset(c, h, "fly_type", stringToNasal(c, "flyBy"));
162 hashset(c, h, "wp_type", stringToNasal(c, wpt->type()));
163 hashset(c, h, "wp_name", stringToNasal(c, wpt->ident()));
164 hashset(c, h, "wp_lat", naNum(pos.getLatitudeDeg()));
165 hashset(c, h, "wp_lon", naNum(pos.getLongitudeDeg()));
166 hashset(c, h, "alt_cstr", naNum(wpt->altitudeFt()));
168 if (wpt->speedRestriction() == flightgear::SPEED_RESTRICT_MACH) {
169 hashset(c, h, "spd_cstr", naNum(wpt->speedMach()));
171 hashset(c, h, "spd_cstr", naNum(wpt->speedKts()));
175 std::pair<double, double> crsDist =
176 next->courseAndDistanceFrom(pos);
177 hashset(c, h, "leg_distance", naNum(crsDist.second * SG_METER_TO_NM));
178 hashset(c, h, "leg_bearing", naNum(crsDist.first));
179 hashset(c, h, "hdg_radial", naNum(wpt->headingRadialDeg()));
182 // leg bearing, distance, etc
185 // parents and ghost of the C++ object
186 hashset(c, h, "_waypt", ghostForWaypt(c, wpt));
187 naRef parents = naNewVector(c);
188 naVec_append(parents, waypointPrototype);
189 hashset(c, h, "parents", parents);
195 naRef hashForRunway(naContext c, FGRunway* rwy)
197 naRef rwyid = stringToNasal(c, rwy->ident());
198 naRef rwydata = naNewHash(c);
199 #define HASHSET(s,l,n) naHash_set(rwydata, naStr_fromdata(naNewString(c),s,l),n)
200 HASHSET("id", 2, rwyid);
201 HASHSET("lat", 3, naNum(rwy->latitude()));
202 HASHSET("lon", 3, naNum(rwy->longitude()));
203 HASHSET("heading", 7, naNum(rwy->headingDeg()));
204 HASHSET("length", 6, naNum(rwy->lengthM()));
205 HASHSET("width", 5, naNum(rwy->widthM()));
206 HASHSET("threshold", 9, naNum(rwy->displacedThresholdM()));
207 HASHSET("stopway", 7, naNum(rwy->stopwayM()));
210 HASHSET("ils_frequency_mhz", 17, naNum(rwy->ILS()->get_freq() / 100.0));
211 HASHSET("ils", 3, hashForNavRecord(c, rwy->ILS(), SGGeod()));
214 HASHSET("_positioned", 11, ghostForPositioned(c, rwy));
219 naRef hashForNavRecord(naContext c, const FGNavRecord* nav, const SGGeod& rel)
221 naRef navdata = naNewHash(c);
222 #define HASHSET(s,l,n) naHash_set(navdata, naStr_fromdata(naNewString(c),s,l),n)
223 HASHSET("id", 2, stringToNasal(c, nav->ident()));
224 HASHSET("name", 4, stringToNasal(c, nav->name()));
225 HASHSET("frequency", 9, naNum(nav->get_freq()));
226 HASHSET("lat", 3, naNum(nav->get_lat()));
227 HASHSET("lon", 3, naNum(nav->get_lon()));
228 HASHSET("elevation", 9, naNum(nav->get_elev_ft() * SG_FEET_TO_METER));
229 HASHSET("type", 4, stringToNasal(c, nav->nameForType(nav->type())));
231 // FIXME - get rid of these, people should use courseAndDistance instead
232 HASHSET("distance", 8, naNum(SGGeodesy::distanceNm( rel, nav->geod() ) * SG_NM_TO_METER ) );
233 HASHSET("bearing", 7, naNum(SGGeodesy::courseDeg( rel, nav->geod() ) ) );
235 // record the real object as a ghost for further operations
236 HASHSET("_positioned",11, ghostForPositioned(c, nav));
242 bool geodFromHash(naRef ref, SGGeod& result)
244 if (!naIsHash(ref)) {
248 // first, see if the hash contains a FGPositioned ghost - in which case
249 // we can read off its position directly
250 naRef posGhost = naHash_cget(ref, (char*) "_positioned");
251 if (!naIsNil(posGhost)) {
252 FGPositioned* pos = positionedGhost(posGhost);
253 result = pos->geod();
257 naRef ghost = naHash_cget(ref, (char*) "_waypt");
258 if (!naIsNil(ghost)) {
259 flightgear::Waypt* w = wayptGhost(ghost);
260 result = w->position();
264 // then check for manual latitude / longitude names
265 naRef lat = naHash_cget(ref, (char*) "lat");
266 naRef lon = naHash_cget(ref, (char*) "lon");
267 if (naIsNum(lat) && naIsNum(lon)) {
268 result = SGGeod::fromDeg(naNumValue(lat).num, naNumValue(lon).num);
272 // check for geo.Coord type
274 // check for any synonyms?
275 // latitude + longitude?
280 static int geodFromArgs(naRef* args, int offset, int argc, SGGeod& result)
282 if (offset >= argc) {
286 if (geodFromHash(args[offset], result)) {
290 if (((argc - offset) >= 2) && naIsNum(args[offset]) && naIsNum(args[offset + 1])) {
291 double lat = naNumValue(args[0]).num,
292 lon = naNumValue(args[1]).num;
293 result = SGGeod::fromDeg(lon, lat);
300 // Convert a cartesian point to a geodetic lat/lon/altitude.
301 static naRef f_carttogeod(naContext c, naRef me, int argc, naRef* args)
303 double lat, lon, alt, xyz[3];
304 if(argc != 3) naRuntimeError(c, "carttogeod() expects 3 arguments");
305 for(int i=0; i<3; i++)
306 xyz[i] = naNumValue(args[i]).num;
307 sgCartToGeod(xyz, &lat, &lon, &alt);
308 lat *= SG_RADIANS_TO_DEGREES;
309 lon *= SG_RADIANS_TO_DEGREES;
310 naRef vec = naNewVector(c);
311 naVec_append(vec, naNum(lat));
312 naVec_append(vec, naNum(lon));
313 naVec_append(vec, naNum(alt));
317 // Convert a geodetic lat/lon/altitude to a cartesian point.
318 static naRef f_geodtocart(naContext c, naRef me, int argc, naRef* args)
320 if(argc != 3) naRuntimeError(c, "geodtocart() expects 3 arguments");
321 double lat = naNumValue(args[0]).num * SG_DEGREES_TO_RADIANS;
322 double lon = naNumValue(args[1]).num * SG_DEGREES_TO_RADIANS;
323 double alt = naNumValue(args[2]).num;
325 sgGeodToCart(lat, lon, alt, xyz);
326 naRef vec = naNewVector(c);
327 naVec_append(vec, naNum(xyz[0]));
328 naVec_append(vec, naNum(xyz[1]));
329 naVec_append(vec, naNum(xyz[2]));
333 // For given geodetic point return array with elevation, and a material data
334 // hash, or nil if there's no information available (tile not loaded). If
335 // information about the material isn't available, then nil is returned instead
337 static naRef f_geodinfo(naContext c, naRef me, int argc, naRef* args)
339 #define HASHSET(s,l,n) naHash_set(matdata, naStr_fromdata(naNewString(c),s,l),n)
340 if(argc < 2 || argc > 3)
341 naRuntimeError(c, "geodinfo() expects 2 or 3 arguments: lat, lon [, maxalt]");
342 double lat = naNumValue(args[0]).num;
343 double lon = naNumValue(args[1]).num;
344 double elev = argc == 3 ? naNumValue(args[2]).num : 10000;
345 const SGMaterial *mat;
346 SGGeod geod = SGGeod::fromDegM(lon, lat, elev);
347 if(!globals->get_scenery()->get_elevation_m(geod, elev, &mat))
349 naRef vec = naNewVector(c);
350 naVec_append(vec, naNum(elev));
351 naRef matdata = naNil();
353 matdata = naNewHash(c);
354 naRef names = naNewVector(c);
355 BOOST_FOREACH(const std::string& n, mat->get_names())
356 naVec_append(names, stringToNasal(c, n));
358 HASHSET("names", 5, names);
359 HASHSET("solid", 5, naNum(mat->get_solid()));
360 HASHSET("friction_factor", 15, naNum(mat->get_friction_factor()));
361 HASHSET("rolling_friction", 16, naNum(mat->get_rolling_friction()));
362 HASHSET("load_resistance", 15, naNum(mat->get_load_resistance()));
363 HASHSET("bumpiness", 9, naNum(mat->get_bumpiness()));
364 HASHSET("light_coverage", 14, naNum(mat->get_light_coverage()));
366 naVec_append(vec, matdata);
372 class AirportInfoFilter : public FGAirport::AirportFilter
375 AirportInfoFilter() : type(FGPositioned::AIRPORT) {
378 bool fromArg(naRef arg)
380 const char *s = naStr_data(arg);
381 if(!strcmp(s, "airport")) type = FGPositioned::AIRPORT;
382 else if(!strcmp(s, "seaport")) type = FGPositioned::SEAPORT;
383 else if(!strcmp(s, "heliport")) type = FGPositioned::HELIPORT;
390 virtual FGPositioned::Type minType() const {
394 virtual FGPositioned::Type maxType() const {
398 FGPositioned::Type type;
401 // Returns data hash for particular or nearest airport of a <type>, or nil
404 // airportinfo(<id>); e.g. "KSFO"
405 // airportinfo(<type>); type := ("airport"|"seaport"|"heliport")
406 // airportinfo() same as airportinfo("airport")
407 // airportinfo(<lat>, <lon> [, <type>]);
408 static naRef f_airportinfo(naContext c, naRef me, int argc, naRef* args)
410 SGGeod pos = globals->get_aircraft_position();
411 FGAirport* apt = NULL;
413 if(argc >= 2 && naIsNum(args[0]) && naIsNum(args[1])) {
414 pos = SGGeod::fromDeg(args[1].num, args[0].num);
419 double maxRange = 10000.0; // expose this? or pick a smaller value?
421 AirportInfoFilter filter; // defaults to airports only
424 // fall through and use AIRPORT
425 } else if(argc == 1 && naIsString(args[0])) {
426 if (filter.fromArg(args[0])) {
429 // user provided an <id>, hopefully
430 apt = FGAirport::findByIdent(naStr_data(args[0]));
432 // return nil here, but don't raise a runtime error; this is a
433 // legitamate way to validate an ICAO code, for example in a
434 // dialog box or similar.
439 naRuntimeError(c, "airportinfo() with invalid function arguments");
444 apt = FGAirport::findClosest(pos, maxRange, &filter);
445 if(!apt) return naNil();
448 return hashForAirport(c, apt);
451 static naRef f_findAirportsWithinRange(naContext c, naRef me, int argc, naRef* args)
454 SGGeod pos = globals->get_aircraft_position();
455 argOffset += geodFromArgs(args, 0, argc, pos);
457 if (!naIsNum(args[argOffset])) {
458 naRuntimeError(c, "findAirportsWithinRange expected range (in nm) as arg %d", argOffset);
461 AirportInfoFilter filter; // defaults to airports only
462 double rangeNm = args[argOffset++].num;
463 if (argOffset < argc) {
464 filter.fromArg(args[argOffset++]);
467 naRef r = naNewVector(c);
469 FGPositioned::List apts = FGPositioned::findWithinRange(pos, rangeNm, &filter);
470 FGPositioned::sortByRange(apts, pos);
472 BOOST_FOREACH(FGPositionedRef a, apts) {
473 FGAirport* apt = (FGAirport*) a.get();
474 naVec_append(r, hashForAirport(c, apt));
480 static naRef f_findAirportsByICAO(naContext c, naRef me, int argc, naRef* args)
482 if (!naIsString(args[0])) {
483 naRuntimeError(c, "findAirportsByICAO expects string as arg 0");
487 string prefix(naStr_data(args[argOffset++]));
488 AirportInfoFilter filter; // defaults to airports only
489 if (argOffset < argc) {
490 filter.fromArg(args[argOffset++]);
493 naRef r = naNewVector(c);
495 FGPositioned::List apts = FGPositioned::findAllWithIdent(prefix, &filter, false);
497 BOOST_FOREACH(FGPositionedRef a, apts) {
498 FGAirport* apt = (FGAirport*) a.get();
499 naVec_append(r, hashForAirport(c, apt));
505 static FGAirport* airportFromMe(naRef me)
507 naRef ghost = naHash_cget(me, (char*) "_positioned");
508 if (naIsNil(ghost)) {
512 FGPositioned* pos = positionedGhost(ghost);
513 if (pos && FGAirport::isAirportType(pos)) {
514 return (FGAirport*) pos;
520 static naRef f_airport_tower(naContext c, naRef me, int argc, naRef* args)
522 FGAirport* apt = airportFromMe(me);
524 naRuntimeError(c, "airport.tower called on non-airport object");
527 // build a hash for the tower position
528 SGGeod towerLoc = apt->getTowerLocation();
529 naRef tower = naNewHash(c);
530 hashset(c, tower, "lat", naNum(towerLoc.getLatitudeDeg()));
531 hashset(c, tower, "lon", naNum(towerLoc.getLongitudeDeg()));
532 hashset(c, tower, "elevation", naNum(towerLoc.getElevationM()));
536 static naRef f_airport_comms(naContext c, naRef me, int argc, naRef* args)
538 FGAirport* apt = airportFromMe(me);
540 naRuntimeError(c, "airport.comms called on non-airport object");
542 naRef comms = naNewVector(c);
544 // if we have an explicit type, return a simple vector of frequencies
545 if (argc > 0 && naIsScalar(args[0])) {
546 std::string commName = naStr_data(args[0]);
547 FGPositioned::Type commType = FGPositioned::typeFromName(commName);
549 BOOST_FOREACH(flightgear::CommStation* comm, apt->commStationsOfType(commType)) {
550 naVec_append(comms, naNum(comm->freqMHz()));
553 // otherwise return a vector of hashes, one for each comm station.
554 BOOST_FOREACH(flightgear::CommStation* comm, apt->commStations()) {
555 naRef commHash = naNewHash(c);
556 hashset(c, commHash, "frequency", naNum(comm->freqMHz()));
557 hashset(c, commHash, "ident", stringToNasal(c, comm->ident()));
558 naVec_append(comms, commHash);
565 static naRef f_airport_sids(naContext c, naRef me, int argc, naRef* args)
567 FGAirport* apt = airportFromMe(me);
569 naRuntimeError(c, "airport.sids called on non-airport object");
572 naRef sids = naNewVector(c);
574 // if we have an explicit type, return a simple vector of frequencies
575 if (argc > 0 && naIsString(args[0])) {
576 if (!apt->hasRunwayWithIdent(naStr_data(args[0]))) {
580 FGRunway* rwy = apt->getRunwayByIdent(naStr_data(args[0]));
581 BOOST_FOREACH(flightgear::SID* sid, rwy->getSIDs()) {
582 naRef procId = stringToNasal(c, sid->ident());
583 naVec_append(sids, procId);
586 for (unsigned int s=0; s<apt->numSIDs(); ++s) {
587 flightgear::SID* sid = apt->getSIDByIndex(s);
588 naRef procId = stringToNasal(c, sid->ident());
589 naVec_append(sids, procId);
596 static naRef f_airport_stars(naContext c, naRef me, int argc, naRef* args)
598 FGAirport* apt = airportFromMe(me);
600 naRuntimeError(c, "airport.stars called on non-airport object");
603 naRef stars = naNewVector(c);
605 // if we have an explicit type, return a simple vector of frequencies
606 if (argc > 0 && naIsString(args[0])) {
607 if (!apt->hasRunwayWithIdent(naStr_data(args[0]))) {
611 FGRunway* rwy = apt->getRunwayByIdent(naStr_data(args[0]));
612 BOOST_FOREACH(flightgear::STAR* s, rwy->getSTARs()) {
613 naRef procId = stringToNasal(c, s->ident());
614 naVec_append(stars, procId);
617 for (unsigned int s=0; s<apt->numSTARs(); ++s) {
618 flightgear::STAR* star = apt->getSTARByIndex(s);
619 naRef procId = stringToNasal(c, star->ident());
620 naVec_append(stars, procId);
627 static naRef f_airport_parking(naContext c, naRef me, int argc, naRef* args)
629 FGAirport* apt = airportFromMe(me);
631 naRuntimeError(c, "airport.parking called on non-airport object");
634 naRef r = naNewVector(c);
636 bool onlyAvailable = false;
638 if (argc > 0 && naIsString(args[0])) {
639 type = naStr_data(args[0]);
642 if ((argc > 1) && naIsNum(args[1])) {
643 onlyAvailable = (args[1].num != 0.0);
646 FGAirportDynamics* dynamics = apt->getDynamics();
647 for (int i=0; i<dynamics->getNrOfParkings(); ++i) {
648 FGParking* park = dynamics->getParking(i);
649 // filter out based on availability and type
650 if (onlyAvailable && !park->isAvailable()) {
654 if (!type.empty() && (park->getType() != type)) {
658 naRef nm = stringToNasal(c, park->getName());
665 // Returns vector of data hash for navaid of a <type>, nil on error
666 // navaids sorted by ascending distance
667 // navinfo([<lat>,<lon>],[<type>],[<id>])
668 // lat/lon (numeric): use latitude/longitude instead of ac position
669 // type: ("fix"|"vor"|"ndb"|"ils"|"dme"|"tacan"|"any")
670 // id: (partial) id of the fix
672 // navinfo("vor") returns all vors
673 // navinfo("HAM") return all navaids who's name start with "HAM"
674 // navinfo("vor", "HAM") return all vor who's name start with "HAM"
675 //navinfo(34,48,"vor","HAM") return all vor who's name start with "HAM"
676 // sorted by distance relative to lat=34, lon=48
677 static naRef f_navinfo(naContext c, naRef me, int argc, naRef* args)
681 if(argc >= 2 && naIsNum(args[0]) && naIsNum(args[1])) {
682 pos = SGGeod::fromDeg(args[1].num, args[0].num);
686 pos = globals->get_aircraft_position();
689 FGPositioned::Type type = FGPositioned::INVALID;
690 nav_list_type navlist;
691 const char * id = "";
693 if(argc > 0 && naIsString(args[0])) {
694 const char *s = naStr_data(args[0]);
695 if(!strcmp(s, "any")) type = FGPositioned::INVALID;
696 else if(!strcmp(s, "fix")) type = FGPositioned::FIX;
697 else if(!strcmp(s, "vor")) type = FGPositioned::VOR;
698 else if(!strcmp(s, "ndb")) type = FGPositioned::NDB;
699 else if(!strcmp(s, "ils")) type = FGPositioned::ILS;
700 else if(!strcmp(s, "dme")) type = FGPositioned::DME;
701 else if(!strcmp(s, "tacan")) type = FGPositioned::TACAN;
702 else id = s; // this is an id
707 if(argc > 0 && naIsString(args[0])) {
709 naRuntimeError(c, "navinfo() called with navaid id");
712 id = naStr_data(args[0]);
718 naRuntimeError(c, "navinfo() called with too many arguments");
722 navlist = globals->get_navlist()->findByIdentAndFreq( pos, id, 0.0, type );
724 naRef reply = naNewVector(c);
725 for( nav_list_type::const_iterator it = navlist.begin(); it != navlist.end(); ++it ) {
726 naVec_append( reply, hashForNavRecord(c, *it, pos) );
731 static naRef f_findNavaidsWithinRange(naContext c, naRef me, int argc, naRef* args)
734 SGGeod pos = globals->get_aircraft_position();
735 argOffset += geodFromArgs(args, 0, argc, pos);
737 if (!naIsNum(args[argOffset])) {
738 naRuntimeError(c, "findNavaidsWithinRange expected range (in nm) as arg %d", argOffset);
741 FGPositioned::Type type = FGPositioned::INVALID;
742 double rangeNm = args[argOffset++].num;
743 if (argOffset < argc) {
744 type = FGPositioned::typeFromName(naStr_data(args[argOffset]));
747 naRef r = naNewVector(c);
748 FGNavList::TypeFilter filter(type);
749 FGPositioned::List navs = FGPositioned::findWithinRange(pos, rangeNm, &filter);
750 FGPositioned::sortByRange(navs, pos);
752 BOOST_FOREACH(FGPositionedRef a, navs) {
753 FGNavRecord* nav = (FGNavRecord*) a.get();
754 naVec_append(r, hashForNavRecord(c, nav, pos));
760 static naRef f_findNavaidByFrequency(naContext c, naRef me, int argc, naRef* args)
763 SGGeod pos = globals->get_aircraft_position();
764 argOffset += geodFromArgs(args, 0, argc, pos);
766 if (!naIsNum(args[argOffset])) {
767 naRuntimeError(c, "findNavaidByFrequency expectes frequency (in Mhz) as arg %d", argOffset);
770 FGPositioned::Type type = FGPositioned::INVALID;
771 double freqMhz = args[argOffset++].num;
772 if (argOffset < argc) {
773 type = FGPositioned::typeFromName(naStr_data(args[argOffset]));
776 nav_list_type navs = globals->get_navlist()->findAllByFreq(freqMhz, pos, type);
781 return hashForNavRecord(c, navs.front().ptr(), pos);
784 static naRef f_findNavaidsByFrequency(naContext c, naRef me, int argc, naRef* args)
787 SGGeod pos = globals->get_aircraft_position();
788 argOffset += geodFromArgs(args, 0, argc, pos);
790 if (!naIsNum(args[argOffset])) {
791 naRuntimeError(c, "findNavaidsByFrequency expectes frequency (in Mhz) as arg %d", argOffset);
794 FGPositioned::Type type = FGPositioned::INVALID;
795 double freqMhz = args[argOffset++].num;
796 if (argOffset < argc) {
797 type = FGPositioned::typeFromName(naStr_data(args[argOffset]));
800 naRef r = naNewVector(c);
801 nav_list_type navs = globals->get_navlist()->findAllByFreq(freqMhz, pos, type);
803 BOOST_FOREACH(nav_rec_ptr a, navs) {
804 naVec_append(r, hashForNavRecord(c, a.ptr(), pos));
810 static naRef f_findNavaidsByIdent(naContext c, naRef me, int argc, naRef* args)
813 SGGeod pos = globals->get_aircraft_position();
814 argOffset += geodFromArgs(args, 0, argc, pos);
816 if (!naIsString(args[argOffset])) {
817 naRuntimeError(c, "findNavaidsByIdent expectes ident string as arg %d", argOffset);
820 FGPositioned::Type type = FGPositioned::INVALID;
821 string ident = naStr_data(args[argOffset++]);
822 if (argOffset < argc) {
823 type = FGPositioned::typeFromName(naStr_data(args[argOffset]));
826 naRef r = naNewVector(c);
827 nav_list_type navs = globals->get_navlist()->findByIdentAndFreq(pos, ident, 0.0, type);
829 BOOST_FOREACH(nav_rec_ptr a, navs) {
830 naVec_append(r, hashForNavRecord(c, a.ptr(), pos));
837 // Convert a cartesian point to a geodetic lat/lon/altitude.
838 static naRef f_magvar(naContext c, naRef me, int argc, naRef* args)
840 SGGeod pos = globals->get_aircraft_position();
842 // fine, use aircraft position
843 } else if (geodFromArgs(args, 0, argc, pos)) {
846 naRuntimeError(c, "magvar() expects no arguments, a positioned hash or lat,lon pair");
849 double jd = globals->get_time_params()->getJD();
850 double magvarDeg = sgGetMagVar(pos, jd) * SG_RADIANS_TO_DEGREES;
851 return naNum(magvarDeg);
854 static naRef f_courseAndDistance(naContext c, naRef me, int argc, naRef* args)
856 SGGeod from = globals->get_aircraft_position(), to, p;
857 int argOffset = geodFromArgs(args, 0, argc, p);
858 if (geodFromArgs(args, argOffset, argc, to)) {
859 from = p; // we parsed both FROM and TO args, so first was from
861 to = p; // only parsed one arg, so FROM is current
864 if (argOffset == 0) {
865 naRuntimeError(c, "invalid arguments to courseAndDistance");
868 double course, course2, d;
869 SGGeodesy::inverse(from, to, course, course2, d);
871 naRef result = naNewVector(c);
872 naVec_append(result, naNum(course));
873 naVec_append(result, naNum(d * SG_METER_TO_NM));
877 static naRef f_tilePath(naContext c, naRef me, int argc, naRef* args)
879 SGGeod pos = globals->get_aircraft_position();
880 geodFromArgs(args, 0, argc, pos);
882 return stringToNasal(c, b.gen_base_path());
885 static naRef f_route(naContext c, naRef me, int argc, naRef* args)
887 naRef route = naNewHash(c);
889 // return active route hash by default,
890 // other routes in the future
892 naRef parents = naNewVector(c);
893 naVec_append(parents, routePrototype);
894 hashset(c, route, "parents", parents);
899 static naRef f_route_getWP(naContext c, naRef me, int argc, naRef* args)
901 FGRouteMgr* rm = static_cast<FGRouteMgr*>(globals->get_subsystem("route-manager"));
905 index = rm->currentIndex();
907 index = (int) naNumValue(args[0]).num;
910 if ((index < 0) || (index >= rm->numWaypts())) {
914 flightgear::Waypt* next = NULL;
915 if (index < (rm->numWaypts() - 1)) {
916 next = rm->wayptAtIndex(index + 1);
918 return hashForWaypoint(c, rm->wayptAtIndex(index), next);
921 static naRef f_route_currentWP(naContext c, naRef me, int argc, naRef* args)
923 FGRouteMgr* rm = static_cast<FGRouteMgr*>(globals->get_subsystem("route-manager"));
924 flightgear::Waypt* next = NULL;
925 if (rm->currentIndex() < (rm->numWaypts() - 1)) {
926 next = rm->wayptAtIndex(rm->currentIndex() + 1);
928 return hashForWaypoint(c, rm->currentWaypt(), next);
931 static naRef f_route_currentIndex(naContext c, naRef me, int argc, naRef* args)
933 FGRouteMgr* rm = static_cast<FGRouteMgr*>(globals->get_subsystem("route-manager"));
934 return naNum(rm->currentIndex());
937 static naRef f_route_numWaypoints(naContext c, naRef me, int argc, naRef* args)
939 FGRouteMgr* rm = static_cast<FGRouteMgr*>(globals->get_subsystem("route-manager"));
940 return naNum(rm->numWaypts());
943 static flightgear::Waypt* wayptFromMe(naRef me)
945 naRef ghost = naHash_cget(me, (char*) "_waypt");
946 if (naIsNil(ghost)) {
950 return wayptGhost(ghost);
953 static naRef f_waypoint_navaid(naContext c, naRef me, int argc, naRef* args)
955 flightgear::Waypt* w = wayptFromMe(me);
957 naRuntimeError(c, "waypoint.navaid called on non-waypoint object");
960 FGPositioned* pos = w->source();
965 switch (pos->type()) {
966 case FGPositioned::VOR:
967 case FGPositioned::NDB:
968 case FGPositioned::ILS:
969 case FGPositioned::LOC:
970 case FGPositioned::GS:
971 case FGPositioned::DME:
972 case FGPositioned::TACAN: {
973 FGNavRecord* nav = (FGNavRecord*) pos;
974 return hashForNavRecord(c, nav, globals->get_aircraft_position());
982 static naRef f_waypoint_airport(naContext c, naRef me, int argc, naRef* args)
984 flightgear::Waypt* w = wayptFromMe(me);
986 naRuntimeError(c, "waypoint.navaid called on non-waypoint object");
989 FGPositioned* pos = w->source();
990 if (!pos || FGAirport::isAirportType(pos)) {
994 return hashForAirport(c, (FGAirport*) pos);
997 static naRef f_waypoint_runway(naContext c, naRef me, int argc, naRef* args)
999 flightgear::Waypt* w = wayptFromMe(me);
1001 naRuntimeError(c, "waypoint.navaid called on non-waypoint object");
1004 FGPositioned* pos = w->source();
1005 if (!pos || (pos->type() != FGPositioned::RUNWAY)) {
1009 return hashForRunway(c, (FGRunway*) pos);
1012 // Table of extension functions. Terminate with zeros.
1013 static struct { const char* name; naCFunction func; } funcs[] = {
1014 { "carttogeod", f_carttogeod },
1015 { "geodtocart", f_geodtocart },
1016 { "geodinfo", f_geodinfo },
1017 { "airportinfo", f_airportinfo },
1018 { "findAirportsWithinRange", f_findAirportsWithinRange },
1019 { "findAirportsByICAO", f_findAirportsByICAO },
1020 { "navinfo", f_navinfo },
1021 { "findNavaidsWithinRange", f_findNavaidsWithinRange },
1022 { "findNavaidByFrequency", f_findNavaidByFrequency },
1023 { "findNavaidsByFrequency", f_findNavaidsByFrequency },
1024 { "findNavaidsByID", f_findNavaidsByIdent },
1025 { "route", f_route },
1026 { "magvar", f_magvar },
1027 { "courseAndDistance", f_courseAndDistance },
1028 { "bucketPath", f_tilePath },
1033 naRef initNasalPositioned(naRef globals, naContext c, naRef gcSave)
1035 airportPrototype = naNewHash(c);
1036 hashset(c, gcSave, "airportProto", airportPrototype);
1038 hashset(c, airportPrototype, "tower", naNewFunc(c, naNewCCode(c, f_airport_tower)));
1039 hashset(c, airportPrototype, "comms", naNewFunc(c, naNewCCode(c, f_airport_comms)));
1040 hashset(c, airportPrototype, "sids", naNewFunc(c, naNewCCode(c, f_airport_sids)));
1041 hashset(c, airportPrototype, "stars", naNewFunc(c, naNewCCode(c, f_airport_stars)));
1042 hashset(c, airportPrototype, "parking", naNewFunc(c, naNewCCode(c, f_airport_parking)));
1044 routePrototype = naNewHash(c);
1045 hashset(c, gcSave, "routeProto", routePrototype);
1047 hashset(c, routePrototype, "getWP", naNewFunc(c, naNewCCode(c, f_route_getWP)));
1048 hashset(c, routePrototype, "currentWP", naNewFunc(c, naNewCCode(c, f_route_currentWP)));
1049 hashset(c, routePrototype, "currentIndex", naNewFunc(c, naNewCCode(c, f_route_currentIndex)));
1050 hashset(c, routePrototype, "getPlanSize", naNewFunc(c, naNewCCode(c, f_route_numWaypoints)));
1052 waypointPrototype = naNewHash(c);
1053 hashset(c, gcSave, "wayptProto", waypointPrototype);
1055 hashset(c, waypointPrototype, "navaid", naNewFunc(c, naNewCCode(c, f_waypoint_navaid)));
1056 hashset(c, waypointPrototype, "runway", naNewFunc(c, naNewCCode(c, f_waypoint_runway)));
1057 hashset(c, waypointPrototype, "airport", naNewFunc(c, naNewCCode(c, f_waypoint_airport)));
1059 for(int i=0; funcs[i].name; i++) {
1060 hashset(c, globals, funcs[i].name,
1061 naNewFunc(c, naNewCCode(c, funcs[i].func)));