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 <Navaids/navlist.hxx>
39 #include <Navaids/procedure.hxx>
40 #include <Main/globals.hxx>
41 #include <Main/fg_props.hxx>
42 #include <Scenery/scenery.hxx>
43 #include <ATC/CommStation.hxx>
44 #include <Navaids/route.hxx>
45 #include <Autopilot/route_mgr.hxx>
46 #include <Navaids/procedure.hxx>
48 static void sgrefGhostDestroy(void* g);
49 naGhostType PositionedGhostType = { sgrefGhostDestroy, "positioned" };
50 naGhostType WayptGhostType = { sgrefGhostDestroy, "waypoint" };
52 static void hashset(naContext c, naRef hash, const char* key, naRef val)
54 naRef s = naNewString(c);
55 naStr_fromdata(s, (char*)key, strlen(key));
56 naHash_set(hash, s, val);
59 static naRef stringToNasal(naContext c, const std::string& s)
61 return naStr_fromdata(naNewString(c),
62 const_cast<char *>(s.c_str()),
66 static FGPositioned* positionedGhost(naRef r)
68 if (naGhost_type(r) == &PositionedGhostType)
69 return (FGPositioned*) naGhost_ptr(r);
73 static flightgear::Waypt* wayptGhost(naRef r)
75 if (naGhost_type(r) == &WayptGhostType)
76 return (flightgear::Waypt*) naGhost_ptr(r);
80 static void sgrefGhostDestroy(void* g)
82 SGReferenced* ref = (SGReferenced*)g;
83 SGReferenced::put(ref); // unref
86 static naRef airportPrototype;
87 static naRef routePrototype;
88 static naRef waypointPrototype;
90 naRef ghostForPositioned(naContext c, const FGPositioned* pos)
96 SGReferenced::get(pos); // take a ref
97 return naNewGhost(c, &PositionedGhostType, (void*) pos);
100 naRef ghostForWaypt(naContext c, const flightgear::Waypt* wpt)
106 SGReferenced::get(wpt); // take a ref
107 return naNewGhost(c, &WayptGhostType, (void*) wpt);
110 naRef hashForAirport(naContext c, const FGAirport* apt)
112 std::string id = apt->ident();
113 std::string name = apt->name();
115 // build runways hash
116 naRef rwys = naNewHash(c);
117 for(unsigned int r=0; r<apt->numRunways(); ++r) {
118 FGRunway* rwy(apt->getRunwayByIndex(r));
119 naRef rwyid = stringToNasal(c, rwy->ident());
120 naRef rwydata = hashForRunway(c, rwy);
121 naHash_set(rwys, rwyid, rwydata);
124 naRef aptdata = naNewHash(c);
125 hashset(c, aptdata, "id", stringToNasal(c, id));
126 hashset(c, aptdata, "name", stringToNasal(c, name));
127 hashset(c, aptdata, "lat", naNum(apt->getLatitude()));
128 hashset(c, aptdata, "lon", naNum(apt->getLongitude()));
129 hashset(c, aptdata, "elevation", naNum(apt->getElevation() * SG_FEET_TO_METER));
130 hashset(c, aptdata, "has_metar", naNum(apt->getMetar()));
131 hashset(c, aptdata, "runways", rwys);
132 hashset(c, aptdata, "_positioned", ghostForPositioned(c, apt));
133 naRef parents = naNewVector(c);
134 naVec_append(parents, airportPrototype);
135 hashset(c, aptdata, "parents", parents);
140 naRef hashForWaypoint(naContext c, flightgear::Waypt* wpt, flightgear::Waypt* next)
142 SGGeod pos = wpt->position();
143 naRef h = naNewHash(c);
145 flightgear::Procedure* proc = dynamic_cast<flightgear::Procedure*>(wpt->owner());
147 hashset(c, h, "wp_parent_name", stringToNasal(c, proc->ident()));
148 // set 'wp_parent' route object to query the SID / STAR / airway?
149 // TODO - needs some extensions to flightgear::Route
152 if (wpt->type() == "hold") {
153 hashset(c, h, "fly_type", stringToNasal(c, "Hold"));
154 } else if (wpt->flag(flightgear::WPT_OVERFLIGHT)) {
155 hashset(c, h, "fly_type", stringToNasal(c, "flyOver"));
157 hashset(c, h, "fly_type", stringToNasal(c, "flyBy"));
160 hashset(c, h, "wp_type", stringToNasal(c, wpt->type()));
161 hashset(c, h, "wp_name", stringToNasal(c, wpt->ident()));
162 hashset(c, h, "wp_lat", naNum(pos.getLatitudeDeg()));
163 hashset(c, h, "wp_lon", naNum(pos.getLongitudeDeg()));
164 hashset(c, h, "alt_cstr", naNum(wpt->altitudeFt()));
166 if (wpt->speedRestriction() == flightgear::SPEED_RESTRICT_MACH) {
167 hashset(c, h, "spd_cstr", naNum(wpt->speedMach()));
169 hashset(c, h, "spd_cstr", naNum(wpt->speedKts()));
173 std::pair<double, double> crsDist =
174 next->courseAndDistanceFrom(pos);
175 hashset(c, h, "leg_distance", naNum(crsDist.second * SG_METER_TO_NM));
176 hashset(c, h, "leg_bearing", naNum(crsDist.first));
177 hashset(c, h, "hdg_radial", naNum(wpt->headingRadialDeg()));
180 // leg bearing, distance, etc
183 // parents and ghost of the C++ object
184 hashset(c, h, "_waypt", ghostForWaypt(c, wpt));
185 naRef parents = naNewVector(c);
186 naVec_append(parents, waypointPrototype);
187 hashset(c, h, "parents", parents);
193 naRef hashForRunway(naContext c, FGRunway* rwy)
195 naRef rwyid = stringToNasal(c, rwy->ident());
196 naRef rwydata = naNewHash(c);
197 #define HASHSET(s,l,n) naHash_set(rwydata, naStr_fromdata(naNewString(c),s,l),n)
198 HASHSET("id", 2, rwyid);
199 HASHSET("lat", 3, naNum(rwy->latitude()));
200 HASHSET("lon", 3, naNum(rwy->longitude()));
201 HASHSET("heading", 7, naNum(rwy->headingDeg()));
202 HASHSET("length", 6, naNum(rwy->lengthM()));
203 HASHSET("width", 5, naNum(rwy->widthM()));
204 HASHSET("threshold", 9, naNum(rwy->displacedThresholdM()));
205 HASHSET("stopway", 7, naNum(rwy->stopwayM()));
208 HASHSET("ils_frequency_mhz", 17, naNum(rwy->ILS()->get_freq() / 100.0));
209 HASHSET("ils", 3, hashForNavRecord(c, rwy->ILS(), SGGeod()));
212 HASHSET("_positioned", 11, ghostForPositioned(c, rwy));
217 naRef hashForNavRecord(naContext c, const FGNavRecord* nav, const SGGeod& rel)
219 naRef navdata = naNewHash(c);
220 #define HASHSET(s,l,n) naHash_set(navdata, naStr_fromdata(naNewString(c),s,l),n)
221 HASHSET("id", 2, stringToNasal(c, nav->ident()));
222 HASHSET("name", 4, stringToNasal(c, nav->name()));
223 HASHSET("frequency", 9, naNum(nav->get_freq()));
224 HASHSET("lat", 3, naNum(nav->get_lat()));
225 HASHSET("lon", 3, naNum(nav->get_lon()));
226 HASHSET("elevation", 9, naNum(nav->get_elev_ft() * SG_FEET_TO_METER));
227 HASHSET("type", 4, stringToNasal(c, nav->nameForType(nav->type())));
229 // FIXME - get rid of these, people should use courseAndDistance instead
230 HASHSET("distance", 8, naNum(SGGeodesy::distanceNm( rel, nav->geod() ) * SG_NM_TO_METER ) );
231 HASHSET("bearing", 7, naNum(SGGeodesy::courseDeg( rel, nav->geod() ) ) );
233 // record the real object as a ghost for further operations
234 HASHSET("_positioned",11, ghostForPositioned(c, nav));
240 bool geodFromHash(naRef ref, SGGeod& result)
242 if (!naIsHash(ref)) {
246 // first, see if the hash contains a FGPositioned ghost - in which case
247 // we can read off its position directly
248 naRef posGhost = naHash_cget(ref, (char*) "_positioned");
249 if (!naIsNil(posGhost)) {
250 FGPositioned* pos = positionedGhost(posGhost);
251 result = pos->geod();
255 naRef ghost = naHash_cget(ref, (char*) "_waypt");
256 if (!naIsNil(ghost)) {
257 flightgear::Waypt* w = wayptGhost(ghost);
258 result = w->position();
262 // then check for manual latitude / longitude names
263 naRef lat = naHash_cget(ref, (char*) "lat");
264 naRef lon = naHash_cget(ref, (char*) "lon");
265 if (naIsNum(lat) && naIsNum(lon)) {
266 result = SGGeod::fromDeg(naNumValue(lat).num, naNumValue(lon).num);
270 // check for geo.Coord type
272 // check for any synonyms?
273 // latitude + longitude?
278 // Convert a cartesian point to a geodetic lat/lon/altitude.
279 static naRef f_carttogeod(naContext c, naRef me, int argc, naRef* args)
281 double lat, lon, alt, xyz[3];
282 if(argc != 3) naRuntimeError(c, "carttogeod() expects 3 arguments");
283 for(int i=0; i<3; i++)
284 xyz[i] = naNumValue(args[i]).num;
285 sgCartToGeod(xyz, &lat, &lon, &alt);
286 lat *= SG_RADIANS_TO_DEGREES;
287 lon *= SG_RADIANS_TO_DEGREES;
288 naRef vec = naNewVector(c);
289 naVec_append(vec, naNum(lat));
290 naVec_append(vec, naNum(lon));
291 naVec_append(vec, naNum(alt));
295 // Convert a geodetic lat/lon/altitude to a cartesian point.
296 static naRef f_geodtocart(naContext c, naRef me, int argc, naRef* args)
298 if(argc != 3) naRuntimeError(c, "geodtocart() expects 3 arguments");
299 double lat = naNumValue(args[0]).num * SG_DEGREES_TO_RADIANS;
300 double lon = naNumValue(args[1]).num * SG_DEGREES_TO_RADIANS;
301 double alt = naNumValue(args[2]).num;
303 sgGeodToCart(lat, lon, alt, xyz);
304 naRef vec = naNewVector(c);
305 naVec_append(vec, naNum(xyz[0]));
306 naVec_append(vec, naNum(xyz[1]));
307 naVec_append(vec, naNum(xyz[2]));
311 // For given geodetic point return array with elevation, and a material data
312 // hash, or nil if there's no information available (tile not loaded). If
313 // information about the material isn't available, then nil is returned instead
315 static naRef f_geodinfo(naContext c, naRef me, int argc, naRef* args)
317 #define HASHSET(s,l,n) naHash_set(matdata, naStr_fromdata(naNewString(c),s,l),n)
318 if(argc < 2 || argc > 3)
319 naRuntimeError(c, "geodinfo() expects 2 or 3 arguments: lat, lon [, maxalt]");
320 double lat = naNumValue(args[0]).num;
321 double lon = naNumValue(args[1]).num;
322 double elev = argc == 3 ? naNumValue(args[2]).num : 10000;
323 const SGMaterial *mat;
324 SGGeod geod = SGGeod::fromDegM(lon, lat, elev);
325 if(!globals->get_scenery()->get_elevation_m(geod, elev, &mat))
327 naRef vec = naNewVector(c);
328 naVec_append(vec, naNum(elev));
329 naRef matdata = naNil();
331 matdata = naNewHash(c);
332 naRef names = naNewVector(c);
333 BOOST_FOREACH(const std::string& n, mat->get_names())
334 naVec_append(names, stringToNasal(c, n));
336 HASHSET("names", 5, names);
337 HASHSET("solid", 5, naNum(mat->get_solid()));
338 HASHSET("friction_factor", 15, naNum(mat->get_friction_factor()));
339 HASHSET("rolling_friction", 16, naNum(mat->get_rolling_friction()));
340 HASHSET("load_resistance", 15, naNum(mat->get_load_resistance()));
341 HASHSET("bumpiness", 9, naNum(mat->get_bumpiness()));
342 HASHSET("light_coverage", 14, naNum(mat->get_light_coverage()));
344 naVec_append(vec, matdata);
350 class AirportInfoFilter : public FGAirport::AirportFilter
353 AirportInfoFilter() : type(FGPositioned::AIRPORT) {
356 virtual FGPositioned::Type minType() const {
360 virtual FGPositioned::Type maxType() const {
364 FGPositioned::Type type;
367 // Returns data hash for particular or nearest airport of a <type>, or nil
370 // airportinfo(<id>); e.g. "KSFO"
371 // airportinfo(<type>); type := ("airport"|"seaport"|"heliport")
372 // airportinfo() same as airportinfo("airport")
373 // airportinfo(<lat>, <lon> [, <type>]);
374 static naRef f_airportinfo(naContext c, naRef me, int argc, naRef* args)
377 FGAirport* apt = NULL;
379 if(argc >= 2 && naIsNum(args[0]) && naIsNum(args[1])) {
380 pos = SGGeod::fromDeg(args[1].num, args[0].num);
384 pos = globals->get_aircraft_position();
387 double maxRange = 10000.0; // expose this? or pick a smaller value?
389 AirportInfoFilter filter; // defaults to airports only
392 // fall through and use AIRPORT
393 } else if(argc == 1 && naIsString(args[0])) {
394 const char *s = naStr_data(args[0]);
395 if(!strcmp(s, "airport")) filter.type = FGPositioned::AIRPORT;
396 else if(!strcmp(s, "seaport")) filter.type = FGPositioned::SEAPORT;
397 else if(!strcmp(s, "heliport")) filter.type = FGPositioned::HELIPORT;
399 // user provided an <id>, hopefully
400 apt = FGAirport::findByIdent(s);
402 // return nil here, but don't raise a runtime error; this is a
403 // legitamate way to validate an ICAO code, for example in a
404 // dialog box or similar.
409 naRuntimeError(c, "airportinfo() with invalid function arguments");
414 apt = FGAirport::findClosest(pos, maxRange, &filter);
415 if(!apt) return naNil();
418 return hashForAirport(c, apt);
421 static FGAirport* airportFromMe(naRef me)
423 naRef ghost = naHash_cget(me, (char*) "_positioned");
424 if (naIsNil(ghost)) {
428 FGPositioned* pos = positionedGhost(ghost);
429 if (pos && FGAirport::isAirportType(pos)) {
430 return (FGAirport*) pos;
436 static naRef f_airport_tower(naContext c, naRef me, int argc, naRef* args)
438 FGAirport* apt = airportFromMe(me);
440 naRuntimeError(c, "airport.tower called on non-airport object");
443 // build a hash for the tower position
444 SGGeod towerLoc = apt->getTowerLocation();
445 naRef tower = naNewHash(c);
446 hashset(c, tower, "lat", naNum(towerLoc.getLatitudeDeg()));
447 hashset(c, tower, "lon", naNum(towerLoc.getLongitudeDeg()));
448 hashset(c, tower, "elevation", naNum(towerLoc.getElevationM()));
452 static naRef f_airport_comms(naContext c, naRef me, int argc, naRef* args)
454 FGAirport* apt = airportFromMe(me);
456 naRuntimeError(c, "airport.comms called on non-airport object");
458 naRef comms = naNewVector(c);
460 // if we have an explicit type, return a simple vector of frequencies
461 if (argc > 0 && naIsScalar(args[0])) {
462 std::string commName = naStr_data(args[0]);
463 FGPositioned::Type commType = FGPositioned::typeFromName(commName);
465 BOOST_FOREACH(flightgear::CommStation* comm, apt->commStationsOfType(commType)) {
466 naVec_append(comms, naNum(comm->freqMHz()));
469 // otherwise return a vector of hashes, one for each comm station.
470 BOOST_FOREACH(flightgear::CommStation* comm, apt->commStations()) {
471 naRef commHash = naNewHash(c);
472 hashset(c, commHash, "frequency", naNum(comm->freqMHz()));
473 hashset(c, commHash, "ident", stringToNasal(c, comm->ident()));
474 naVec_append(comms, commHash);
481 static naRef f_airport_sids(naContext c, naRef me, int argc, naRef* args)
483 FGAirport* apt = airportFromMe(me);
485 naRuntimeError(c, "airport.sids called on non-airport object");
488 naRef sids = naNewVector(c);
490 // if we have an explicit type, return a simple vector of frequencies
491 if (argc > 0 && naIsString(args[0])) {
492 if (!apt->hasRunwayWithIdent(naStr_data(args[0]))) {
496 FGRunway* rwy = apt->getRunwayByIdent(naStr_data(args[0]));
497 BOOST_FOREACH(flightgear::SID* sid, rwy->getSIDs()) {
498 naRef procId = stringToNasal(c, sid->ident());
499 naVec_append(sids, procId);
502 for (unsigned int s=0; s<apt->numSIDs(); ++s) {
503 flightgear::SID* sid = apt->getSIDByIndex(s);
504 naRef procId = stringToNasal(c, sid->ident());
505 naVec_append(sids, procId);
512 static naRef f_airport_stars(naContext c, naRef me, int argc, naRef* args)
514 FGAirport* apt = airportFromMe(me);
516 naRuntimeError(c, "airport.stars called on non-airport object");
519 naRef stars = naNewVector(c);
521 // if we have an explicit type, return a simple vector of frequencies
522 if (argc > 0 && naIsString(args[0])) {
523 if (!apt->hasRunwayWithIdent(naStr_data(args[0]))) {
527 FGRunway* rwy = apt->getRunwayByIdent(naStr_data(args[0]));
528 BOOST_FOREACH(flightgear::STAR* s, rwy->getSTARs()) {
529 naRef procId = stringToNasal(c, s->ident());
530 naVec_append(stars, procId);
533 for (unsigned int s=0; s<apt->numSTARs(); ++s) {
534 flightgear::STAR* star = apt->getSTARByIndex(s);
535 naRef procId = stringToNasal(c, star->ident());
536 naVec_append(stars, procId);
543 // Returns vector of data hash for navaid of a <type>, nil on error
544 // navaids sorted by ascending distance
545 // navinfo([<lat>,<lon>],[<type>],[<id>])
546 // lat/lon (numeric): use latitude/longitude instead of ac position
547 // type: ("fix"|"vor"|"ndb"|"ils"|"dme"|"tacan"|"any")
548 // id: (partial) id of the fix
550 // navinfo("vor") returns all vors
551 // navinfo("HAM") return all navaids who's name start with "HAM"
552 // navinfo("vor", "HAM") return all vor who's name start with "HAM"
553 //navinfo(34,48,"vor","HAM") return all vor who's name start with "HAM"
554 // sorted by distance relative to lat=34, lon=48
555 static naRef f_navinfo(naContext c, naRef me, int argc, naRef* args)
559 if(argc >= 2 && naIsNum(args[0]) && naIsNum(args[1])) {
560 pos = SGGeod::fromDeg(args[1].num, args[0].num);
564 pos = globals->get_aircraft_position();
567 FGPositioned::Type type = FGPositioned::INVALID;
568 nav_list_type navlist;
569 const char * id = "";
571 if(argc > 0 && naIsString(args[0])) {
572 const char *s = naStr_data(args[0]);
573 if(!strcmp(s, "any")) type = FGPositioned::INVALID;
574 else if(!strcmp(s, "fix")) type = FGPositioned::FIX;
575 else if(!strcmp(s, "vor")) type = FGPositioned::VOR;
576 else if(!strcmp(s, "ndb")) type = FGPositioned::NDB;
577 else if(!strcmp(s, "ils")) type = FGPositioned::ILS;
578 else if(!strcmp(s, "dme")) type = FGPositioned::DME;
579 else if(!strcmp(s, "tacan")) type = FGPositioned::TACAN;
580 else id = s; // this is an id
585 if(argc > 0 && naIsString(args[0])) {
587 naRuntimeError(c, "navinfo() called with navaid id");
590 id = naStr_data(args[0]);
596 naRuntimeError(c, "navinfo() called with too many arguments");
600 navlist = globals->get_navlist()->findByIdentAndFreq( pos, id, 0.0, type );
602 naRef reply = naNewVector(c);
603 for( nav_list_type::const_iterator it = navlist.begin(); it != navlist.end(); ++it ) {
604 naVec_append( reply, hashForNavRecord(c, *it, pos) );
609 // Convert a cartesian point to a geodetic lat/lon/altitude.
610 static naRef f_magvar(naContext c, naRef me, int argc, naRef* args)
612 SGGeod pos = globals->get_aircraft_position();
614 // fine, use aircraft position
615 } else if ((argc == 1) && geodFromHash(args[0], pos)) {
617 } else if ((argc == 2) && naIsNum(args[0]) && naIsNum(args[1])) {
618 double lat = naNumValue(args[0]).num,
619 lon = naNumValue(args[1]).num;
620 pos = SGGeod::fromDeg(lon, lat);
622 naRuntimeError(c, "magvar() expects no arguments, a positioned hash or lat,lon pair");
625 double jd = globals->get_time_params()->getJD();
626 double magvarDeg = sgGetMagVar(pos, jd) * SG_RADIANS_TO_DEGREES;
627 return naNum(magvarDeg);
630 static naRef f_courseAndDistance(naContext c, naRef me, int argc, naRef* args)
632 SGGeod from = globals->get_aircraft_position(), to;
633 if ((argc == 1) && geodFromHash(args[0], to)) {
635 } else if ((argc == 2) && naIsNum(args[0]) && naIsNum(args[1])) {
636 // two number arguments, from = current pos, to = lat+lon
637 double lat = naNumValue(args[0]).num,
638 lon = naNumValue(args[1]).num;
639 to = SGGeod::fromDeg(lon, lat);
640 } else if ((argc == 2) && geodFromHash(args[0], from) && geodFromHash(args[1], to)) {
642 } else if ((argc == 3) && geodFromHash(args[0], from) && naIsNum(args[1]) && naIsNum(args[2])) {
643 double lat = naNumValue(args[1]).num,
644 lon = naNumValue(args[2]).num;
645 to = SGGeod::fromDeg(lon, lat);
646 } else if ((argc == 3) && naIsNum(args[0]) && naIsNum(args[1]) && geodFromHash(args[2], to)) {
647 double lat = naNumValue(args[0]).num,
648 lon = naNumValue(args[1]).num;
649 from = SGGeod::fromDeg(lon, lat);
650 } else if (argc == 4) {
651 if (!naIsNum(args[0]) || !naIsNum(args[1]) || !naIsNum(args[2]) || !naIsNum(args[3])) {
652 naRuntimeError(c, "invalid arguments to courseAndDistance - expected four numbers");
655 from = SGGeod::fromDeg(naNumValue(args[1]).num, naNumValue(args[0]).num);
656 to = SGGeod::fromDeg(naNumValue(args[3]).num, naNumValue(args[2]).num);
658 naRuntimeError(c, "invalid arguments to courseAndDistance");
661 double course, course2, d;
662 SGGeodesy::inverse(from, to, course, course2, d);
664 naRef result = naNewVector(c);
665 naVec_append(result, naNum(course));
666 naVec_append(result, naNum(d * SG_METER_TO_NM));
670 static naRef f_tilePath(naContext c, naRef me, int argc, naRef* args)
672 SGGeod pos = globals->get_aircraft_position();
674 // fine, use aircraft position
675 } else if ((argc == 1) && geodFromHash(args[0], pos)) {
677 } else if ((argc == 2) && naIsNum(args[0]) && naIsNum(args[1])) {
678 double lat = naNumValue(args[0]).num,
679 lon = naNumValue(args[1]).num;
680 pos = SGGeod::fromDeg(lon, lat);
682 naRuntimeError(c, "bucketPath() expects no arguments, a positioned hash or lat,lon pair");
686 return stringToNasal(c, b.gen_base_path());
689 static naRef f_route(naContext c, naRef me, int argc, naRef* args)
691 naRef route = naNewHash(c);
693 // return active route hash by default,
694 // other routes in the future
696 naRef parents = naNewVector(c);
697 naVec_append(parents, routePrototype);
698 hashset(c, route, "parents", parents);
703 static naRef f_route_getWP(naContext c, naRef me, int argc, naRef* args)
705 FGRouteMgr* rm = static_cast<FGRouteMgr*>(globals->get_subsystem("route-manager"));
709 index = rm->currentIndex();
711 index = (int) naNumValue(args[0]).num;
714 if ((index < 0) || (index >= rm->numWaypts())) {
718 flightgear::Waypt* next = NULL;
719 if (index < (rm->numWaypts() - 1)) {
720 next = rm->wayptAtIndex(index + 1);
722 return hashForWaypoint(c, rm->wayptAtIndex(index), next);
725 static naRef f_route_currentWP(naContext c, naRef me, int argc, naRef* args)
727 FGRouteMgr* rm = static_cast<FGRouteMgr*>(globals->get_subsystem("route-manager"));
728 flightgear::Waypt* next = NULL;
729 if (rm->currentIndex() < (rm->numWaypts() - 1)) {
730 next = rm->wayptAtIndex(rm->currentIndex() + 1);
732 return hashForWaypoint(c, rm->currentWaypt(), next);
735 static naRef f_route_currentIndex(naContext c, naRef me, int argc, naRef* args)
737 FGRouteMgr* rm = static_cast<FGRouteMgr*>(globals->get_subsystem("route-manager"));
738 return naNum(rm->currentIndex());
741 static naRef f_route_numWaypoints(naContext c, naRef me, int argc, naRef* args)
743 FGRouteMgr* rm = static_cast<FGRouteMgr*>(globals->get_subsystem("route-manager"));
744 return naNum(rm->numWaypts());
747 static flightgear::Waypt* wayptFromMe(naRef me)
749 naRef ghost = naHash_cget(me, (char*) "_waypt");
750 if (naIsNil(ghost)) {
754 return wayptGhost(ghost);
757 static naRef f_waypoint_navaid(naContext c, naRef me, int argc, naRef* args)
759 flightgear::Waypt* w = wayptFromMe(me);
761 naRuntimeError(c, "waypoint.navaid called on non-waypoint object");
764 FGPositioned* pos = w->source();
769 switch (pos->type()) {
770 case FGPositioned::VOR:
771 case FGPositioned::NDB:
772 case FGPositioned::ILS:
773 case FGPositioned::LOC:
774 case FGPositioned::GS:
775 case FGPositioned::DME:
776 case FGPositioned::TACAN: {
777 FGNavRecord* nav = (FGNavRecord*) pos;
778 return hashForNavRecord(c, nav, globals->get_aircraft_position());
786 static naRef f_waypoint_airport(naContext c, naRef me, int argc, naRef* args)
788 flightgear::Waypt* w = wayptFromMe(me);
790 naRuntimeError(c, "waypoint.navaid called on non-waypoint object");
793 FGPositioned* pos = w->source();
794 if (!pos || FGAirport::isAirportType(pos)) {
798 return hashForAirport(c, (FGAirport*) pos);
801 static naRef f_waypoint_runway(naContext c, naRef me, int argc, naRef* args)
803 flightgear::Waypt* w = wayptFromMe(me);
805 naRuntimeError(c, "waypoint.navaid called on non-waypoint object");
808 FGPositioned* pos = w->source();
809 if (!pos || (pos->type() != FGPositioned::RUNWAY)) {
813 return hashForRunway(c, (FGRunway*) pos);
816 // Table of extension functions. Terminate with zeros.
817 static struct { const char* name; naCFunction func; } funcs[] = {
818 { "carttogeod", f_carttogeod },
819 { "geodtocart", f_geodtocart },
820 { "geodinfo", f_geodinfo },
821 { "airportinfo", f_airportinfo },
822 { "navinfo", f_navinfo },
823 { "route", f_route },
824 { "magvar", f_magvar },
825 { "courseAndDistance", f_courseAndDistance },
826 { "bucketPath", f_tilePath },
831 naRef initNasalPositioned(naRef globals, naContext c, naRef gcSave)
833 airportPrototype = naNewHash(c);
834 hashset(c, gcSave, "airportProto", airportPrototype);
836 hashset(c, airportPrototype, "tower", naNewFunc(c, naNewCCode(c, f_airport_tower)));
837 hashset(c, airportPrototype, "comms", naNewFunc(c, naNewCCode(c, f_airport_comms)));
838 hashset(c, airportPrototype, "sids", naNewFunc(c, naNewCCode(c, f_airport_sids)));
839 hashset(c, airportPrototype, "stars", naNewFunc(c, naNewCCode(c, f_airport_stars)));
841 routePrototype = naNewHash(c);
842 hashset(c, gcSave, "routeProto", routePrototype);
844 hashset(c, routePrototype, "getWP", naNewFunc(c, naNewCCode(c, f_route_getWP)));
845 hashset(c, routePrototype, "currentWP", naNewFunc(c, naNewCCode(c, f_route_currentWP)));
846 hashset(c, routePrototype, "currentIndex", naNewFunc(c, naNewCCode(c, f_route_currentIndex)));
847 hashset(c, routePrototype, "getPlanSize", naNewFunc(c, naNewCCode(c, f_route_numWaypoints)));
849 waypointPrototype = naNewHash(c);
850 hashset(c, gcSave, "wayptProto", waypointPrototype);
852 hashset(c, waypointPrototype, "navaid", naNewFunc(c, naNewCCode(c, f_waypoint_navaid)));
853 hashset(c, waypointPrototype, "runway", naNewFunc(c, naNewCCode(c, f_waypoint_runway)));
854 hashset(c, waypointPrototype, "airport", naNewFunc(c, naNewCCode(c, f_waypoint_airport)));
856 for(int i=0; funcs[i].name; i++) {
857 hashset(c, globals, funcs[i].name,
858 naNewFunc(c, naNewCCode(c, funcs[i].func)));