]> git.mxchange.org Git - flightgear.git/blob - src/Scripting/NasalPositioned.cxx
979ef06a8dcaa57a379dddc493a0946373448c48
[flightgear.git] / src / Scripting / NasalPositioned.cxx
1 // NasalPositioned.cxx -- expose FGPositioned classes to Nasal
2 //
3 // Written by James Turner, started 2012.
4 //
5 // Copyright (C) 2012 James Turner
6 //
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.
11 //
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.
16 //
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.
20
21 #ifdef HAVE_CONFIG_H
22 #  include "config.h"
23 #endif
24
25 #include <string.h>
26
27 #include "NasalPositioned.hxx"
28
29 #include <boost/foreach.hpp>
30
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>
35
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>
47
48 static void sgrefGhostDestroy(void* g);
49 naGhostType PositionedGhostType = { sgrefGhostDestroy, "positioned" };
50 naGhostType WayptGhostType = { sgrefGhostDestroy, "waypoint" };
51
52 static void hashset(naContext c, naRef hash, const char* key, naRef val)
53 {
54   naRef s = naNewString(c);
55   naStr_fromdata(s, (char*)key, strlen(key));
56   naHash_set(hash, s, val);
57 }
58
59 static naRef stringToNasal(naContext c, const std::string& s)
60 {
61     return naStr_fromdata(naNewString(c),
62                    const_cast<char *>(s.c_str()), 
63                    s.length());
64 }
65
66 static FGPositioned* positionedGhost(naRef r)
67 {
68     if (naGhost_type(r) == &PositionedGhostType)
69         return (FGPositioned*) naGhost_ptr(r);
70     return 0;
71 }
72
73 static flightgear::Waypt* wayptGhost(naRef r)
74 {
75   if (naGhost_type(r) == &WayptGhostType)
76     return (flightgear::Waypt*) naGhost_ptr(r);
77   return 0;
78 }
79
80 static void sgrefGhostDestroy(void* g)
81 {
82     SGReferenced* ref = (SGReferenced*)g;
83     SGReferenced::put(ref); // unref
84 }
85
86 static naRef airportPrototype;
87 static naRef routePrototype;
88 static naRef waypointPrototype;
89
90 naRef ghostForPositioned(naContext c, const FGPositioned* pos)
91 {
92     if (!pos) {
93         return naNil();
94     }
95     
96     SGReferenced::get(pos); // take a ref
97     return naNewGhost(c, &PositionedGhostType, (void*) pos);
98 }
99
100 naRef ghostForWaypt(naContext c, const flightgear::Waypt* wpt)
101 {
102   if (!wpt) {
103     return naNil();
104   }
105   
106   SGReferenced::get(wpt); // take a ref
107   return naNewGhost(c, &WayptGhostType, (void*) wpt);
108 }
109
110 naRef hashForAirport(naContext c, const FGAirport* apt)
111 {
112     std::string id = apt->ident();
113     std::string name = apt->name();
114     
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);
122     }
123   
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);
136     
137     return aptdata;
138 }
139
140 naRef hashForWaypoint(naContext c, flightgear::Waypt* wpt, flightgear::Waypt* next)
141 {
142   SGGeod pos = wpt->position();
143   naRef h = naNewHash(c);
144   
145   flightgear::Procedure* proc = dynamic_cast<flightgear::Procedure*>(wpt->owner());
146   if (proc) {
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
150   }
151
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"));
156   } else {
157     hashset(c, h, "fly_type", stringToNasal(c, "flyBy"));
158   }
159   
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()));
165   
166   if (wpt->speedRestriction() == flightgear::SPEED_RESTRICT_MACH) {
167     hashset(c, h, "spd_cstr", naNum(wpt->speedMach()));
168   } else {
169     hashset(c, h, "spd_cstr", naNum(wpt->speedKts()));
170   }
171   
172   if (next) {
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()));
178   }
179   
180 // leg bearing, distance, etc
181   
182   
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);
188   
189   return h;
190
191 }
192
193 naRef hashForRunway(naContext c, FGRunway* rwy)
194 {
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()));
206         
207     if (rwy->ILS()) {
208       HASHSET("ils_frequency_mhz", 17, naNum(rwy->ILS()->get_freq() / 100.0));
209       HASHSET("ils", 3, hashForNavRecord(c, rwy->ILS(), SGGeod()));
210     }
211     
212     HASHSET("_positioned", 11, ghostForPositioned(c, rwy));
213 #undef HASHSET
214     return rwydata;
215 }
216
217 naRef hashForNavRecord(naContext c, const FGNavRecord* nav, const SGGeod& rel)
218 {
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())));
228     
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() ) ) );
232     
233     // record the real object as a ghost for further operations
234     HASHSET("_positioned",11, ghostForPositioned(c, nav));
235 #undef HASHSET
236     
237     return navdata;
238 }
239
240 bool geodFromHash(naRef ref, SGGeod& result)
241 {
242   if (!naIsHash(ref)) {
243     return false;
244   }
245   
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();
252     return true;
253   }
254   
255   naRef ghost = naHash_cget(ref, (char*) "_waypt");
256   if (!naIsNil(ghost)) {
257     flightgear::Waypt* w = wayptGhost(ghost);
258     result = w->position();
259     return true;
260   }
261   
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);
267     return true;
268   }
269   
270 // check for geo.Coord type
271     
272 // check for any synonyms?
273     // latitude + longitude?
274   
275   return false;
276 }
277
278 // Convert a cartesian point to a geodetic lat/lon/altitude.
279 static naRef f_carttogeod(naContext c, naRef me, int argc, naRef* args)
280 {
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));
292   return vec;
293 }
294
295 // Convert a geodetic lat/lon/altitude to a cartesian point.
296 static naRef f_geodtocart(naContext c, naRef me, int argc, naRef* args)
297 {
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;
302   double xyz[3];
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]));
308   return vec;
309 }
310
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
314 // of the hash.
315 static naRef f_geodinfo(naContext c, naRef me, int argc, naRef* args)
316 {
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))
326     return naNil();
327   naRef vec = naNewVector(c);
328   naVec_append(vec, naNum(elev));
329   naRef matdata = naNil();
330   if(mat) {
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));
335       
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()));
343   }
344   naVec_append(vec, matdata);
345   return vec;
346 #undef HASHSET
347 }
348
349
350 class AirportInfoFilter : public FGAirport::AirportFilter
351 {
352 public:
353   AirportInfoFilter() : type(FGPositioned::AIRPORT) {
354   }
355   
356   virtual FGPositioned::Type minType() const {
357     return type;
358   }
359   
360   virtual FGPositioned::Type maxType() const {
361     return type;
362   }
363   
364   FGPositioned::Type type;
365 };
366
367 // Returns data hash for particular or nearest airport of a <type>, or nil
368 // on error.
369 //
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)
375 {
376   SGGeod pos;
377   FGAirport* apt = NULL;
378   
379   if(argc >= 2 && naIsNum(args[0]) && naIsNum(args[1])) {
380     pos = SGGeod::fromDeg(args[1].num, args[0].num);
381     args += 2;
382     argc -= 2;
383   } else {
384     pos = globals->get_aircraft_position();
385   }
386   
387   double maxRange = 10000.0; // expose this? or pick a smaller value?
388   
389   AirportInfoFilter filter; // defaults to airports only
390   
391   if(argc == 0) {
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;
398     else {
399       // user provided an <id>, hopefully
400       apt = FGAirport::findByIdent(s);
401       if (!apt) {
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.
405         return naNil();
406       }
407     }
408   } else {
409     naRuntimeError(c, "airportinfo() with invalid function arguments");
410     return naNil();
411   }
412   
413   if(!apt) {
414     apt = FGAirport::findClosest(pos, maxRange, &filter);
415     if(!apt) return naNil();
416   }
417   
418   return hashForAirport(c, apt);
419 }
420
421 static FGAirport* airportFromMe(naRef me)
422 {  
423     naRef ghost = naHash_cget(me, (char*) "_positioned");
424     if (naIsNil(ghost)) {
425         return NULL;
426     }
427   
428     FGPositioned* pos = positionedGhost(ghost);
429     if (pos && FGAirport::isAirportType(pos)) {
430         return (FGAirport*) pos;
431     }
432
433     return NULL;
434 }
435
436 static naRef f_airport_tower(naContext c, naRef me, int argc, naRef* args)
437 {
438     FGAirport* apt = airportFromMe(me);
439     if (!apt) {
440       naRuntimeError(c, "airport.tower called on non-airport object");
441     }
442   
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()));
449     return tower;
450 }
451
452 static naRef f_airport_comms(naContext c, naRef me, int argc, naRef* args)
453 {
454     FGAirport* apt = airportFromMe(me);
455     if (!apt) {
456       naRuntimeError(c, "airport.comms called on non-airport object");
457     }
458     naRef comms = naNewVector(c);
459     
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);
464         
465         BOOST_FOREACH(flightgear::CommStation* comm, apt->commStationsOfType(commType)) {
466             naVec_append(comms, naNum(comm->freqMHz()));
467         }
468     } else {
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);
475         }
476     }
477     
478     return comms;
479 }
480
481 static naRef f_airport_sids(naContext c, naRef me, int argc, naRef* args)
482 {
483   FGAirport* apt = airportFromMe(me);
484   if (!apt) {
485     naRuntimeError(c, "airport.sids called on non-airport object");
486   }
487   
488   naRef sids = naNewVector(c);
489   
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]))) {
493       return naNil();
494     }
495
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);
500     }
501   } else {
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);
506     }
507   }
508   
509   return sids;
510 }
511
512 static naRef f_airport_stars(naContext c, naRef me, int argc, naRef* args)
513 {
514   FGAirport* apt = airportFromMe(me);
515   if (!apt) {
516     naRuntimeError(c, "airport.stars called on non-airport object");
517   }
518   
519   naRef stars = naNewVector(c);
520   
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]))) {
524       return naNil();
525     }
526         
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);
531     }
532   } else {
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);
537     }
538   }
539   
540   return stars;
541 }
542
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
549 // examples:
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)
556 {
557   SGGeod pos;
558   
559   if(argc >= 2 && naIsNum(args[0]) && naIsNum(args[1])) {
560     pos = SGGeod::fromDeg(args[1].num, args[0].num);
561     args += 2;
562     argc -= 2;
563   } else {
564     pos = globals->get_aircraft_position();
565   }
566   
567   FGPositioned::Type type = FGPositioned::INVALID;
568   nav_list_type navlist;
569   const char * id = "";
570   
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
581     ++args;
582     --argc;
583   } 
584   
585   if(argc > 0 && naIsString(args[0])) {
586     if( *id != 0 ) {
587       naRuntimeError(c, "navinfo() called with navaid id");
588       return naNil();
589     }
590     id = naStr_data(args[0]);
591     ++args;
592     --argc;
593   }
594   
595   if( argc > 0 ) {
596     naRuntimeError(c, "navinfo() called with too many arguments");
597     return naNil();
598   }
599   
600   navlist = globals->get_navlist()->findByIdentAndFreq( pos, id, 0.0, type );
601   
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) );
605   }
606   return reply;
607 }
608
609 // Convert a cartesian point to a geodetic lat/lon/altitude.
610 static naRef f_magvar(naContext c, naRef me, int argc, naRef* args)
611 {
612   SGGeod pos = globals->get_aircraft_position();
613   if (argc == 0) {
614     // fine, use aircraft position
615   } else if ((argc == 1) && geodFromHash(args[0], pos)) {
616     // okay
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);
621   } else {
622     naRuntimeError(c, "magvar() expects no arguments, a positioned hash or lat,lon pair");
623   }
624   
625   double jd = globals->get_time_params()->getJD();
626   double magvarDeg = sgGetMagVar(pos, jd) * SG_RADIANS_TO_DEGREES;
627   return naNum(magvarDeg);
628 }
629
630 static naRef f_courseAndDistance(naContext c, naRef me, int argc, naRef* args)
631 {
632     SGGeod from = globals->get_aircraft_position(), to;
633     if ((argc == 1) && geodFromHash(args[0], to)) {
634         // done
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)) {
641         // done
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");
653         }
654         
655         from = SGGeod::fromDeg(naNumValue(args[1]).num, naNumValue(args[0]).num);
656         to = SGGeod::fromDeg(naNumValue(args[3]).num, naNumValue(args[2]).num);
657     } else {
658         naRuntimeError(c, "invalid arguments to courseAndDistance");
659     }
660     
661     double course, course2, d;
662     SGGeodesy::inverse(from, to, course, course2, d);
663     
664     naRef result = naNewVector(c);
665     naVec_append(result, naNum(course));
666     naVec_append(result, naNum(d * SG_METER_TO_NM));
667     return result;
668 }
669
670 static naRef f_tilePath(naContext c, naRef me, int argc, naRef* args)
671 {
672     SGGeod pos = globals->get_aircraft_position();
673     if (argc == 0) {
674         // fine, use aircraft position
675     } else if ((argc == 1) && geodFromHash(args[0], pos)) {
676         // okay
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);
681     } else {
682         naRuntimeError(c, "bucketPath() expects no arguments, a positioned hash or lat,lon pair");
683     }
684     
685     SGBucket b(pos);
686     return stringToNasal(c, b.gen_base_path());
687 }
688
689 static naRef f_route(naContext c, naRef me, int argc, naRef* args)
690 {
691   naRef route = naNewHash(c);
692   
693   // return active route hash by default,
694   // other routes in the future
695   
696   naRef parents = naNewVector(c);
697   naVec_append(parents, routePrototype);
698   hashset(c, route, "parents", parents);
699   
700   return route;
701 }
702
703 static naRef f_route_getWP(naContext c, naRef me, int argc, naRef* args)
704 {
705   FGRouteMgr* rm = static_cast<FGRouteMgr*>(globals->get_subsystem("route-manager"));
706   
707   int index;
708   if (argc == 0) {
709     index = rm->currentIndex();
710   } else {
711     index = (int) naNumValue(args[0]).num;
712   }
713   
714   if ((index < 0) || (index >= rm->numWaypts())) {
715     return naNil();
716   }
717   
718   flightgear::Waypt* next = NULL;
719   if (index < (rm->numWaypts() - 1)) {
720     next = rm->wayptAtIndex(index + 1);
721   }
722   return hashForWaypoint(c, rm->wayptAtIndex(index), next);
723 }
724
725 static naRef f_route_currentWP(naContext c, naRef me, int argc, naRef* args)
726 {
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);
731   }
732   return hashForWaypoint(c, rm->currentWaypt(), next);
733 }
734
735 static naRef f_route_currentIndex(naContext c, naRef me, int argc, naRef* args)
736 {
737   FGRouteMgr* rm = static_cast<FGRouteMgr*>(globals->get_subsystem("route-manager"));
738   return naNum(rm->currentIndex());
739 }
740
741 static naRef f_route_numWaypoints(naContext c, naRef me, int argc, naRef* args)
742 {
743   FGRouteMgr* rm = static_cast<FGRouteMgr*>(globals->get_subsystem("route-manager"));
744   return naNum(rm->numWaypts());
745 }
746
747 static flightgear::Waypt* wayptFromMe(naRef me)
748 {  
749   naRef ghost = naHash_cget(me, (char*) "_waypt");
750   if (naIsNil(ghost)) {
751     return NULL;
752   }
753   
754   return wayptGhost(ghost);
755 }
756
757 static naRef f_waypoint_navaid(naContext c, naRef me, int argc, naRef* args)
758 {
759   flightgear::Waypt* w = wayptFromMe(me);
760   if (!w) {
761     naRuntimeError(c, "waypoint.navaid called on non-waypoint object");
762   }
763   
764   FGPositioned* pos = w->source();
765   if (!pos) {
766     return naNil();
767   }
768   
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());
779   }
780       
781   default:
782     return naNil();
783   }
784 }
785
786 static naRef f_waypoint_airport(naContext c, naRef me, int argc, naRef* args)
787 {
788   flightgear::Waypt* w = wayptFromMe(me);
789   if (!w) {
790     naRuntimeError(c, "waypoint.navaid called on non-waypoint object");
791   }
792   
793   FGPositioned* pos = w->source();
794   if (!pos || FGAirport::isAirportType(pos)) {
795     return naNil();
796   }
797   
798   return hashForAirport(c, (FGAirport*) pos);
799 }
800
801 static naRef f_waypoint_runway(naContext c, naRef me, int argc, naRef* args)
802 {
803   flightgear::Waypt* w = wayptFromMe(me);
804   if (!w) {
805     naRuntimeError(c, "waypoint.navaid called on non-waypoint object");
806   }
807   
808   FGPositioned* pos = w->source();
809   if (!pos || (pos->type() != FGPositioned::RUNWAY)) {
810     return naNil();
811   }
812   
813   return hashForRunway(c, (FGRunway*) pos);
814 }
815
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 },
827   { 0, 0 }
828 };
829
830
831 naRef initNasalPositioned(naRef globals, naContext c, naRef gcSave)
832 {
833     airportPrototype = naNewHash(c);
834     hashset(c, gcSave, "airportProto", airportPrototype);
835   
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)));
840   
841     routePrototype = naNewHash(c);
842     hashset(c, gcSave, "routeProto", routePrototype);
843       
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)));
848     
849     waypointPrototype = naNewHash(c);
850     hashset(c, gcSave, "wayptProto", waypointPrototype);
851     
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)));
855   
856     for(int i=0; funcs[i].name; i++) {
857       hashset(c, globals, funcs[i].name,
858             naNewFunc(c, naNewCCode(c, funcs[i].func)));
859     }
860   
861   return naNil();
862 }
863