]> git.mxchange.org Git - flightgear.git/blob - src/Scripting/NasalPositioned.cxx
78e1bc8d7316dd126cd09be4a9ea6497d2981a59
[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 <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>
49
50 static void sgrefGhostDestroy(void* g);
51 naGhostType PositionedGhostType = { sgrefGhostDestroy, "positioned" };
52 naGhostType WayptGhostType = { sgrefGhostDestroy, "waypoint" };
53
54 static void hashset(naContext c, naRef hash, const char* key, naRef val)
55 {
56   naRef s = naNewString(c);
57   naStr_fromdata(s, (char*)key, strlen(key));
58   naHash_set(hash, s, val);
59 }
60
61 static naRef stringToNasal(naContext c, const std::string& s)
62 {
63     return naStr_fromdata(naNewString(c),
64                    const_cast<char *>(s.c_str()), 
65                    s.length());
66 }
67
68 static FGPositioned* positionedGhost(naRef r)
69 {
70     if (naGhost_type(r) == &PositionedGhostType)
71         return (FGPositioned*) naGhost_ptr(r);
72     return 0;
73 }
74
75 static flightgear::Waypt* wayptGhost(naRef r)
76 {
77   if (naGhost_type(r) == &WayptGhostType)
78     return (flightgear::Waypt*) naGhost_ptr(r);
79   return 0;
80 }
81
82 static void sgrefGhostDestroy(void* g)
83 {
84     SGReferenced* ref = (SGReferenced*)g;
85     SGReferenced::put(ref); // unref
86 }
87
88 static naRef airportPrototype;
89 static naRef routePrototype;
90 static naRef waypointPrototype;
91
92 naRef ghostForPositioned(naContext c, const FGPositioned* pos)
93 {
94     if (!pos) {
95         return naNil();
96     }
97     
98     SGReferenced::get(pos); // take a ref
99     return naNewGhost(c, &PositionedGhostType, (void*) pos);
100 }
101
102 naRef ghostForWaypt(naContext c, const flightgear::Waypt* wpt)
103 {
104   if (!wpt) {
105     return naNil();
106   }
107   
108   SGReferenced::get(wpt); // take a ref
109   return naNewGhost(c, &WayptGhostType, (void*) wpt);
110 }
111
112 naRef hashForAirport(naContext c, const FGAirport* apt)
113 {
114     std::string id = apt->ident();
115     std::string name = apt->name();
116     
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);
124     }
125   
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);
138     
139     return aptdata;
140 }
141
142 naRef hashForWaypoint(naContext c, flightgear::Waypt* wpt, flightgear::Waypt* next)
143 {
144   SGGeod pos = wpt->position();
145   naRef h = naNewHash(c);
146   
147   flightgear::Procedure* proc = dynamic_cast<flightgear::Procedure*>(wpt->owner());
148   if (proc) {
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
152   }
153
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"));
158   } else {
159     hashset(c, h, "fly_type", stringToNasal(c, "flyBy"));
160   }
161   
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()));
167   
168   if (wpt->speedRestriction() == flightgear::SPEED_RESTRICT_MACH) {
169     hashset(c, h, "spd_cstr", naNum(wpt->speedMach()));
170   } else {
171     hashset(c, h, "spd_cstr", naNum(wpt->speedKts()));
172   }
173   
174   if (next) {
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()));
180   }
181   
182 // leg bearing, distance, etc
183   
184   
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);
190   
191   return h;
192
193 }
194
195 naRef hashForRunway(naContext c, FGRunway* rwy)
196 {
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()));
208         
209     if (rwy->ILS()) {
210       HASHSET("ils_frequency_mhz", 17, naNum(rwy->ILS()->get_freq() / 100.0));
211       HASHSET("ils", 3, hashForNavRecord(c, rwy->ILS(), SGGeod()));
212     }
213     
214     HASHSET("_positioned", 11, ghostForPositioned(c, rwy));
215 #undef HASHSET
216     return rwydata;
217 }
218
219 naRef hashForNavRecord(naContext c, const FGNavRecord* nav, const SGGeod& rel)
220 {
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())));
230     
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() ) ) );
234     
235     // record the real object as a ghost for further operations
236     HASHSET("_positioned",11, ghostForPositioned(c, nav));
237 #undef HASHSET
238     
239     return navdata;
240 }
241
242 bool geodFromHash(naRef ref, SGGeod& result)
243 {
244   if (!naIsHash(ref)) {
245     return false;
246   }
247   
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();
254     return true;
255   }
256   
257   naRef ghost = naHash_cget(ref, (char*) "_waypt");
258   if (!naIsNil(ghost)) {
259     flightgear::Waypt* w = wayptGhost(ghost);
260     result = w->position();
261     return true;
262   }
263   
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);
269     return true;
270   }
271   
272 // check for geo.Coord type
273     
274 // check for any synonyms?
275     // latitude + longitude?
276   
277   return false;
278 }
279
280 static int geodFromArgs(naRef* args, int offset, int argc, SGGeod& result)
281 {
282   if (offset >= argc) {
283     return 0;
284   }
285   
286   if (geodFromHash(args[offset], result)) {
287     return 1;
288   }
289   
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);
294     return 2;
295   }
296   
297   return 0;
298 }
299
300 // Convert a cartesian point to a geodetic lat/lon/altitude.
301 static naRef f_carttogeod(naContext c, naRef me, int argc, naRef* args)
302 {
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));
314   return vec;
315 }
316
317 // Convert a geodetic lat/lon/altitude to a cartesian point.
318 static naRef f_geodtocart(naContext c, naRef me, int argc, naRef* args)
319 {
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;
324   double xyz[3];
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]));
330   return vec;
331 }
332
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
336 // of the hash.
337 static naRef f_geodinfo(naContext c, naRef me, int argc, naRef* args)
338 {
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))
348     return naNil();
349   naRef vec = naNewVector(c);
350   naVec_append(vec, naNum(elev));
351   naRef matdata = naNil();
352   if(mat) {
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));
357       
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()));
365   }
366   naVec_append(vec, matdata);
367   return vec;
368 #undef HASHSET
369 }
370
371
372 class AirportInfoFilter : public FGAirport::AirportFilter
373 {
374 public:
375   AirportInfoFilter() : type(FGPositioned::AIRPORT) {
376   }
377   
378   bool fromArg(naRef arg)
379   {
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;
384     else
385       return false;
386     
387     return true;
388   }
389   
390   virtual FGPositioned::Type minType() const {
391     return type;
392   }
393   
394   virtual FGPositioned::Type maxType() const {
395     return type;
396   }
397   
398   FGPositioned::Type type;
399 };
400
401 // Returns data hash for particular or nearest airport of a <type>, or nil
402 // on error.
403 //
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)
409 {
410   SGGeod pos = globals->get_aircraft_position();
411   FGAirport* apt = NULL;
412   
413   if(argc >= 2 && naIsNum(args[0]) && naIsNum(args[1])) {
414     pos = SGGeod::fromDeg(args[1].num, args[0].num);
415     args += 2;
416     argc -= 2;
417   }
418   
419   double maxRange = 10000.0; // expose this? or pick a smaller value?
420   
421   AirportInfoFilter filter; // defaults to airports only
422   
423   if(argc == 0) {
424     // fall through and use AIRPORT
425   } else if(argc == 1 && naIsString(args[0])) {
426     if (filter.fromArg(args[0])) {
427       // done!
428     } else {
429       // user provided an <id>, hopefully
430       apt = FGAirport::findByIdent(naStr_data(args[0]));
431       if (!apt) {
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.
435         return naNil();
436       }
437     }
438   } else {
439     naRuntimeError(c, "airportinfo() with invalid function arguments");
440     return naNil();
441   }
442   
443   if(!apt) {
444     apt = FGAirport::findClosest(pos, maxRange, &filter);
445     if(!apt) return naNil();
446   }
447   
448   return hashForAirport(c, apt);
449 }
450
451 static naRef f_findAirportsWithinRange(naContext c, naRef me, int argc, naRef* args)
452 {
453   int argOffset = 0;
454   SGGeod pos = globals->get_aircraft_position();
455   argOffset += geodFromArgs(args, 0, argc, pos);
456   
457   if (!naIsNum(args[argOffset])) {
458     naRuntimeError(c, "findAirportsWithinRange expected range (in nm) as arg %d", argOffset);
459   }
460   
461   AirportInfoFilter filter; // defaults to airports only
462   double rangeNm = args[argOffset++].num;
463   if (argOffset < argc) {
464     filter.fromArg(args[argOffset++]);
465   }
466   
467   naRef r = naNewVector(c);
468   
469   FGPositioned::List apts = FGPositioned::findWithinRange(pos, rangeNm, &filter);
470   FGPositioned::sortByRange(apts, pos);
471   
472   BOOST_FOREACH(FGPositionedRef a, apts) {
473     FGAirport* apt = (FGAirport*) a.get();
474     naVec_append(r, hashForAirport(c, apt));
475   }
476   
477   return r;
478 }
479
480 static naRef f_findAirportsByICAO(naContext c, naRef me, int argc, naRef* args)
481 {
482   if (!naIsString(args[0])) {
483     naRuntimeError(c, "findAirportsByICAO expects string as arg 0");
484   }
485   
486   int argOffset = 0;
487   string prefix(naStr_data(args[argOffset++]));
488   AirportInfoFilter filter; // defaults to airports only
489   if (argOffset < argc) {
490     filter.fromArg(args[argOffset++]);
491   }
492   
493   naRef r = naNewVector(c);
494   
495   FGPositioned::List apts = FGPositioned::findAllWithIdent(prefix, &filter, false);
496   
497   BOOST_FOREACH(FGPositionedRef a, apts) {
498     FGAirport* apt = (FGAirport*) a.get();
499     naVec_append(r, hashForAirport(c, apt));
500   }
501   
502   return r;
503 }
504
505 static FGAirport* airportFromMe(naRef me)
506 {  
507     naRef ghost = naHash_cget(me, (char*) "_positioned");
508     if (naIsNil(ghost)) {
509         return NULL;
510     }
511   
512     FGPositioned* pos = positionedGhost(ghost);
513     if (pos && FGAirport::isAirportType(pos)) {
514         return (FGAirport*) pos;
515     }
516
517     return NULL;
518 }
519
520 static naRef f_airport_tower(naContext c, naRef me, int argc, naRef* args)
521 {
522     FGAirport* apt = airportFromMe(me);
523     if (!apt) {
524       naRuntimeError(c, "airport.tower called on non-airport object");
525     }
526   
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()));
533     return tower;
534 }
535
536 static naRef f_airport_comms(naContext c, naRef me, int argc, naRef* args)
537 {
538     FGAirport* apt = airportFromMe(me);
539     if (!apt) {
540       naRuntimeError(c, "airport.comms called on non-airport object");
541     }
542     naRef comms = naNewVector(c);
543     
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);
548         
549         BOOST_FOREACH(flightgear::CommStation* comm, apt->commStationsOfType(commType)) {
550             naVec_append(comms, naNum(comm->freqMHz()));
551         }
552     } else {
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);
559         }
560     }
561     
562     return comms;
563 }
564
565 static naRef f_airport_sids(naContext c, naRef me, int argc, naRef* args)
566 {
567   FGAirport* apt = airportFromMe(me);
568   if (!apt) {
569     naRuntimeError(c, "airport.sids called on non-airport object");
570   }
571   
572   naRef sids = naNewVector(c);
573   
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]))) {
577       return naNil();
578     }
579
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);
584     }
585   } else {
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);
590     }
591   }
592   
593   return sids;
594 }
595
596 static naRef f_airport_stars(naContext c, naRef me, int argc, naRef* args)
597 {
598   FGAirport* apt = airportFromMe(me);
599   if (!apt) {
600     naRuntimeError(c, "airport.stars called on non-airport object");
601   }
602   
603   naRef stars = naNewVector(c);
604   
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]))) {
608       return naNil();
609     }
610         
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);
615     }
616   } else {
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);
621     }
622   }
623   
624   return stars;
625 }
626
627 static naRef f_airport_parking(naContext c, naRef me, int argc, naRef* args)
628 {
629   FGAirport* apt = airportFromMe(me);
630   if (!apt) {
631     naRuntimeError(c, "airport.parking called on non-airport object");
632   }
633   
634   naRef r = naNewVector(c);
635   std::string type;
636   bool onlyAvailable = false;
637   
638   if (argc > 0 && naIsString(args[0])) {
639     type = naStr_data(args[0]);
640   }
641   
642   if ((argc > 1) && naIsNum(args[1])) {
643     onlyAvailable = (args[1].num != 0.0);
644   }
645   
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()) {
651       continue;
652     }
653     
654     if (!type.empty() && (park->getType() != type)) {
655       continue;
656     }
657     
658     naRef nm = stringToNasal(c, park->getName());
659     naVec_append(r, nm);
660   }
661   
662   return r;
663 }
664
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
671 // examples:
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)
678 {
679   SGGeod pos;
680   
681   if(argc >= 2 && naIsNum(args[0]) && naIsNum(args[1])) {
682     pos = SGGeod::fromDeg(args[1].num, args[0].num);
683     args += 2;
684     argc -= 2;
685   } else {
686     pos = globals->get_aircraft_position();
687   }
688   
689   FGPositioned::Type type = FGPositioned::INVALID;
690   nav_list_type navlist;
691   const char * id = "";
692   
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
703     ++args;
704     --argc;
705   } 
706   
707   if(argc > 0 && naIsString(args[0])) {
708     if( *id != 0 ) {
709       naRuntimeError(c, "navinfo() called with navaid id");
710       return naNil();
711     }
712     id = naStr_data(args[0]);
713     ++args;
714     --argc;
715   }
716   
717   if( argc > 0 ) {
718     naRuntimeError(c, "navinfo() called with too many arguments");
719     return naNil();
720   }
721   
722   navlist = globals->get_navlist()->findByIdentAndFreq( pos, id, 0.0, type );
723   
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) );
727   }
728   return reply;
729 }
730
731 static naRef f_findNavaidsWithinRange(naContext c, naRef me, int argc, naRef* args)
732 {
733   int argOffset = 0;
734   SGGeod pos = globals->get_aircraft_position();
735   argOffset += geodFromArgs(args, 0, argc, pos);
736   
737   if (!naIsNum(args[argOffset])) {
738     naRuntimeError(c, "findNavaidsWithinRange expected range (in nm) as arg %d", argOffset);
739   }
740   
741   FGPositioned::Type type = FGPositioned::INVALID;
742   double rangeNm = args[argOffset++].num;
743   if (argOffset < argc) {
744     type = FGPositioned::typeFromName(naStr_data(args[argOffset]));
745   }
746   
747   naRef r = naNewVector(c);
748   FGNavList::TypeFilter filter(type);
749   FGPositioned::List navs = FGPositioned::findWithinRange(pos, rangeNm, &filter);
750   FGPositioned::sortByRange(navs, pos);
751   
752   BOOST_FOREACH(FGPositionedRef a, navs) {
753     FGNavRecord* nav = (FGNavRecord*) a.get();
754     naVec_append(r, hashForNavRecord(c, nav, pos));
755   }
756   
757   return r;
758 }
759
760 static naRef f_findNavaidByFrequency(naContext c, naRef me, int argc, naRef* args)
761 {
762   int argOffset = 0;
763   SGGeod pos = globals->get_aircraft_position();
764   argOffset += geodFromArgs(args, 0, argc, pos);
765   
766   if (!naIsNum(args[argOffset])) {
767     naRuntimeError(c, "findNavaidByFrequency expectes frequency (in Mhz) as arg %d", argOffset);
768   }
769   
770   FGPositioned::Type type = FGPositioned::INVALID;
771   double freqMhz = args[argOffset++].num;
772   if (argOffset < argc) {
773     type = FGPositioned::typeFromName(naStr_data(args[argOffset]));
774   }
775   
776   nav_list_type navs = globals->get_navlist()->findAllByFreq(freqMhz, pos, type);
777   if (navs.empty()) {
778     return naNil();
779   }
780   
781   return hashForNavRecord(c, navs.front().ptr(), pos);
782 }
783
784 static naRef f_findNavaidsByFrequency(naContext c, naRef me, int argc, naRef* args)
785 {
786   int argOffset = 0;
787   SGGeod pos = globals->get_aircraft_position();
788   argOffset += geodFromArgs(args, 0, argc, pos);
789   
790   if (!naIsNum(args[argOffset])) {
791     naRuntimeError(c, "findNavaidsByFrequency expectes frequency (in Mhz) as arg %d", argOffset);
792   }
793   
794   FGPositioned::Type type = FGPositioned::INVALID;
795   double freqMhz = args[argOffset++].num;
796   if (argOffset < argc) {
797     type = FGPositioned::typeFromName(naStr_data(args[argOffset]));
798   }
799   
800   naRef r = naNewVector(c);
801   nav_list_type navs = globals->get_navlist()->findAllByFreq(freqMhz, pos, type);
802   
803   BOOST_FOREACH(nav_rec_ptr a, navs) {
804     naVec_append(r, hashForNavRecord(c, a.ptr(), pos));
805   }
806   
807   return r;
808 }
809
810 static naRef f_findNavaidsByIdent(naContext c, naRef me, int argc, naRef* args)
811 {
812   int argOffset = 0;
813   SGGeod pos = globals->get_aircraft_position();
814   argOffset += geodFromArgs(args, 0, argc, pos);
815   
816   if (!naIsString(args[argOffset])) {
817     naRuntimeError(c, "findNavaidsByIdent expectes ident string as arg %d", argOffset);
818   }
819   
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]));
824   }
825   
826   naRef r = naNewVector(c);
827   nav_list_type navs = globals->get_navlist()->findByIdentAndFreq(pos, ident, 0.0, type);
828   
829   BOOST_FOREACH(nav_rec_ptr a, navs) {
830     naVec_append(r, hashForNavRecord(c, a.ptr(), pos));
831   }
832   
833   return r;
834 }
835
836
837 // Convert a cartesian point to a geodetic lat/lon/altitude.
838 static naRef f_magvar(naContext c, naRef me, int argc, naRef* args)
839 {
840   SGGeod pos = globals->get_aircraft_position();
841   if (argc == 0) {
842     // fine, use aircraft position
843   } else if (geodFromArgs(args, 0, argc, pos)) {
844     // okay
845   } else {
846     naRuntimeError(c, "magvar() expects no arguments, a positioned hash or lat,lon pair");
847   }
848   
849   double jd = globals->get_time_params()->getJD();
850   double magvarDeg = sgGetMagVar(pos, jd) * SG_RADIANS_TO_DEGREES;
851   return naNum(magvarDeg);
852 }
853
854 static naRef f_courseAndDistance(naContext c, naRef me, int argc, naRef* args)
855 {
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
860     } else {
861       to = p; // only parsed one arg, so FROM is current
862     }
863   
864     if (argOffset == 0) {
865         naRuntimeError(c, "invalid arguments to courseAndDistance");
866     }
867     
868     double course, course2, d;
869     SGGeodesy::inverse(from, to, course, course2, d);
870     
871     naRef result = naNewVector(c);
872     naVec_append(result, naNum(course));
873     naVec_append(result, naNum(d * SG_METER_TO_NM));
874     return result;
875 }
876
877 static naRef f_tilePath(naContext c, naRef me, int argc, naRef* args)
878 {
879     SGGeod pos = globals->get_aircraft_position();
880     geodFromArgs(args, 0, argc, pos);
881     SGBucket b(pos);
882     return stringToNasal(c, b.gen_base_path());
883 }
884
885 static naRef f_route(naContext c, naRef me, int argc, naRef* args)
886 {
887   naRef route = naNewHash(c);
888   
889   // return active route hash by default,
890   // other routes in the future
891   
892   naRef parents = naNewVector(c);
893   naVec_append(parents, routePrototype);
894   hashset(c, route, "parents", parents);
895   
896   return route;
897 }
898
899 static naRef f_route_getWP(naContext c, naRef me, int argc, naRef* args)
900 {
901   FGRouteMgr* rm = static_cast<FGRouteMgr*>(globals->get_subsystem("route-manager"));
902   
903   int index;
904   if (argc == 0) {
905     index = rm->currentIndex();
906   } else {
907     index = (int) naNumValue(args[0]).num;
908   }
909   
910   if ((index < 0) || (index >= rm->numWaypts())) {
911     return naNil();
912   }
913   
914   flightgear::Waypt* next = NULL;
915   if (index < (rm->numWaypts() - 1)) {
916     next = rm->wayptAtIndex(index + 1);
917   }
918   return hashForWaypoint(c, rm->wayptAtIndex(index), next);
919 }
920
921 static naRef f_route_currentWP(naContext c, naRef me, int argc, naRef* args)
922 {
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);
927   }
928   return hashForWaypoint(c, rm->currentWaypt(), next);
929 }
930
931 static naRef f_route_currentIndex(naContext c, naRef me, int argc, naRef* args)
932 {
933   FGRouteMgr* rm = static_cast<FGRouteMgr*>(globals->get_subsystem("route-manager"));
934   return naNum(rm->currentIndex());
935 }
936
937 static naRef f_route_numWaypoints(naContext c, naRef me, int argc, naRef* args)
938 {
939   FGRouteMgr* rm = static_cast<FGRouteMgr*>(globals->get_subsystem("route-manager"));
940   return naNum(rm->numWaypts());
941 }
942
943 static flightgear::Waypt* wayptFromMe(naRef me)
944 {  
945   naRef ghost = naHash_cget(me, (char*) "_waypt");
946   if (naIsNil(ghost)) {
947     return NULL;
948   }
949   
950   return wayptGhost(ghost);
951 }
952
953 static naRef f_waypoint_navaid(naContext c, naRef me, int argc, naRef* args)
954 {
955   flightgear::Waypt* w = wayptFromMe(me);
956   if (!w) {
957     naRuntimeError(c, "waypoint.navaid called on non-waypoint object");
958   }
959   
960   FGPositioned* pos = w->source();
961   if (!pos) {
962     return naNil();
963   }
964   
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());
975   }
976       
977   default:
978     return naNil();
979   }
980 }
981
982 static naRef f_waypoint_airport(naContext c, naRef me, int argc, naRef* args)
983 {
984   flightgear::Waypt* w = wayptFromMe(me);
985   if (!w) {
986     naRuntimeError(c, "waypoint.navaid called on non-waypoint object");
987   }
988   
989   FGPositioned* pos = w->source();
990   if (!pos || FGAirport::isAirportType(pos)) {
991     return naNil();
992   }
993   
994   return hashForAirport(c, (FGAirport*) pos);
995 }
996
997 static naRef f_waypoint_runway(naContext c, naRef me, int argc, naRef* args)
998 {
999   flightgear::Waypt* w = wayptFromMe(me);
1000   if (!w) {
1001     naRuntimeError(c, "waypoint.navaid called on non-waypoint object");
1002   }
1003   
1004   FGPositioned* pos = w->source();
1005   if (!pos || (pos->type() != FGPositioned::RUNWAY)) {
1006     return naNil();
1007   }
1008   
1009   return hashForRunway(c, (FGRunway*) pos);
1010 }
1011
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 },
1029   { 0, 0 }
1030 };
1031
1032
1033 naRef initNasalPositioned(naRef globals, naContext c, naRef gcSave)
1034 {
1035     airportPrototype = naNewHash(c);
1036     hashset(c, gcSave, "airportProto", airportPrototype);
1037   
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)));
1043   
1044     routePrototype = naNewHash(c);
1045     hashset(c, gcSave, "routeProto", routePrototype);
1046       
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)));
1051     
1052     waypointPrototype = naNewHash(c);
1053     hashset(c, gcSave, "wayptProto", waypointPrototype);
1054     
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)));
1058   
1059     for(int i=0; funcs[i].name; i++) {
1060       hashset(c, globals, funcs[i].name,
1061             naNewFunc(c, naNewCCode(c, funcs[i].func)));
1062     }
1063   
1064   return naNil();
1065 }
1066