]> git.mxchange.org Git - flightgear.git/blob - src/Scripting/NasalPositioned.cxx
Fix explicit reference counting with waypoints and positions.
[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 positionedGhostDestroy(void* g);
51 static void wayptGhostDestroy(void* g);
52 naGhostType PositionedGhostType = { positionedGhostDestroy, "positioned" };
53 naGhostType WayptGhostType = { wayptGhostDestroy, "waypoint" };
54
55 static void hashset(naContext c, naRef hash, const char* key, naRef val)
56 {
57   naRef s = naNewString(c);
58   naStr_fromdata(s, (char*)key, strlen(key));
59   naHash_set(hash, s, val);
60 }
61
62 static naRef stringToNasal(naContext c, const std::string& s)
63 {
64     return naStr_fromdata(naNewString(c),
65                    const_cast<char *>(s.c_str()), 
66                    s.length());
67 }
68
69 static FGPositioned* positionedGhost(naRef r)
70 {
71     if (naGhost_type(r) == &PositionedGhostType)
72         return (FGPositioned*) naGhost_ptr(r);
73     return 0;
74 }
75
76 static void positionedGhostDestroy(void* g)
77 {
78     FGPositioned* pos = (FGPositioned*)g;
79     if (!FGPositioned::put(pos)) // unref
80         delete pos;
81 }
82
83 static flightgear::Waypt* wayptGhost(naRef r)
84 {
85   if (naGhost_type(r) == &WayptGhostType)
86     return (flightgear::Waypt*) naGhost_ptr(r);
87   return 0;
88 }
89
90 static void wayptGhostDestroy(void* g)
91 {
92   flightgear::Waypt* wpt = (flightgear::Waypt*)g;
93   if (!flightgear::Waypt::put(wpt)) // unref
94     delete wpt;
95 }
96
97 static naRef airportPrototype;
98 static naRef routePrototype;
99 static naRef waypointPrototype;
100
101 naRef ghostForPositioned(naContext c, const FGPositioned* pos)
102 {
103     if (!pos) {
104         return naNil();
105     }
106     
107     FGPositioned::get(pos); // take a ref
108     return naNewGhost(c, &PositionedGhostType, (void*) pos);
109 }
110
111 naRef ghostForWaypt(naContext c, const flightgear::Waypt* wpt)
112 {
113   if (!wpt) {
114     return naNil();
115   }
116   
117   flightgear::Waypt::get(wpt); // take a ref
118   return naNewGhost(c, &WayptGhostType, (void*) wpt);
119 }
120
121 naRef hashForAirport(naContext c, const FGAirport* apt)
122 {
123     std::string id = apt->ident();
124     std::string name = apt->name();
125     
126   // build runways hash
127     naRef rwys = naNewHash(c);
128     for(unsigned int r=0; r<apt->numRunways(); ++r) {
129       FGRunway* rwy(apt->getRunwayByIndex(r));
130       naRef rwyid = stringToNasal(c, rwy->ident());
131       naRef rwydata = hashForRunway(c, rwy);
132       naHash_set(rwys, rwyid, rwydata);
133     }
134   
135     naRef aptdata = naNewHash(c);
136     hashset(c, aptdata, "id", stringToNasal(c, id));
137     hashset(c, aptdata, "name", stringToNasal(c, name));
138     hashset(c, aptdata, "lat", naNum(apt->getLatitude()));
139     hashset(c, aptdata, "lon", naNum(apt->getLongitude()));
140     hashset(c, aptdata, "elevation", naNum(apt->getElevation() * SG_FEET_TO_METER));
141     hashset(c, aptdata, "has_metar", naNum(apt->getMetar()));
142     hashset(c, aptdata, "runways", rwys);
143     hashset(c, aptdata, "_positioned", ghostForPositioned(c, apt));
144     naRef parents = naNewVector(c);
145     naVec_append(parents, airportPrototype);
146     hashset(c, aptdata, "parents", parents);
147     
148     return aptdata;
149 }
150
151 naRef hashForWaypoint(naContext c, flightgear::Waypt* wpt, flightgear::Waypt* next)
152 {
153   SGGeod pos = wpt->position();
154   naRef h = naNewHash(c);
155   
156   flightgear::Procedure* proc = dynamic_cast<flightgear::Procedure*>(wpt->owner());
157   if (proc) {
158     hashset(c, h, "wp_parent_name", stringToNasal(c, proc->ident()));
159     // set 'wp_parent' route object to query the SID / STAR / airway?
160     // TODO - needs some extensions to flightgear::Route
161   }
162
163   if (wpt->type() == "hold") {
164     hashset(c, h, "fly_type", stringToNasal(c, "Hold"));
165   } else if (wpt->flag(flightgear::WPT_OVERFLIGHT)) {
166     hashset(c, h, "fly_type", stringToNasal(c, "flyOver"));
167   } else {
168     hashset(c, h, "fly_type", stringToNasal(c, "flyBy"));
169   }
170   
171   hashset(c, h, "wp_type", stringToNasal(c, wpt->type()));
172   hashset(c, h, "wp_name", stringToNasal(c, wpt->ident()));
173   hashset(c, h, "wp_lat", naNum(pos.getLatitudeDeg()));
174   hashset(c, h, "wp_lon", naNum(pos.getLongitudeDeg()));
175   hashset(c, h, "alt_cstr", naNum(wpt->altitudeFt()));
176   
177   if (wpt->speedRestriction() == flightgear::SPEED_RESTRICT_MACH) {
178     hashset(c, h, "spd_cstr", naNum(wpt->speedMach()));
179   } else {
180     hashset(c, h, "spd_cstr", naNum(wpt->speedKts()));
181   }
182   
183   if (next) {
184     std::pair<double, double> crsDist =
185       next->courseAndDistanceFrom(pos);
186     hashset(c, h, "leg_distance", naNum(crsDist.second * SG_METER_TO_NM));
187     hashset(c, h, "leg_bearing", naNum(crsDist.first));
188     hashset(c, h, "hdg_radial", naNum(wpt->headingRadialDeg()));
189   }
190   
191 // leg bearing, distance, etc
192   
193   
194 // parents and ghost of the C++ object
195   hashset(c, h, "_waypt", ghostForWaypt(c, wpt));
196   naRef parents = naNewVector(c);
197   naVec_append(parents, waypointPrototype);
198   hashset(c, h, "parents", parents);
199   
200   return h;
201
202 }
203
204 naRef hashForRunway(naContext c, FGRunway* rwy)
205 {
206     naRef rwyid = stringToNasal(c, rwy->ident());
207     naRef rwydata = naNewHash(c);
208 #define HASHSET(s,l,n) naHash_set(rwydata, naStr_fromdata(naNewString(c),s,l),n)
209     HASHSET("id", 2, rwyid);
210     HASHSET("lat", 3, naNum(rwy->latitude()));
211     HASHSET("lon", 3, naNum(rwy->longitude()));
212     HASHSET("heading", 7, naNum(rwy->headingDeg()));
213     HASHSET("length", 6, naNum(rwy->lengthM()));
214     HASHSET("width", 5, naNum(rwy->widthM()));
215     HASHSET("threshold", 9, naNum(rwy->displacedThresholdM()));
216     HASHSET("stopway", 7, naNum(rwy->stopwayM()));
217         
218     if (rwy->ILS()) {
219       HASHSET("ils_frequency_mhz", 17, naNum(rwy->ILS()->get_freq() / 100.0));
220       HASHSET("ils", 3, hashForNavRecord(c, rwy->ILS(), SGGeod()));
221     }
222     
223     HASHSET("_positioned", 11, ghostForPositioned(c, rwy));
224 #undef HASHSET
225     return rwydata;
226 }
227
228 naRef hashForNavRecord(naContext c, const FGNavRecord* nav, const SGGeod& rel)
229 {
230     naRef navdata = naNewHash(c);
231 #define HASHSET(s,l,n) naHash_set(navdata, naStr_fromdata(naNewString(c),s,l),n)
232     HASHSET("id", 2, stringToNasal(c, nav->ident()));
233     HASHSET("name", 4, stringToNasal(c, nav->name()));
234     HASHSET("frequency", 9, naNum(nav->get_freq()));
235     HASHSET("lat", 3, naNum(nav->get_lat()));
236     HASHSET("lon", 3, naNum(nav->get_lon()));
237     HASHSET("elevation", 9, naNum(nav->get_elev_ft() * SG_FEET_TO_METER));
238     HASHSET("type", 4, stringToNasal(c, nav->nameForType(nav->type())));
239     
240 // FIXME - get rid of these, people should use courseAndDistance instead
241     HASHSET("distance", 8, naNum(SGGeodesy::distanceNm( rel, nav->geod() ) * SG_NM_TO_METER ) );
242     HASHSET("bearing", 7, naNum(SGGeodesy::courseDeg( rel, nav->geod() ) ) );
243     
244     // record the real object as a ghost for further operations
245     HASHSET("_positioned",11, ghostForPositioned(c, nav));
246 #undef HASHSET
247     
248     return navdata;
249 }
250
251 bool geodFromHash(naRef ref, SGGeod& result)
252 {
253   if (!naIsHash(ref)) {
254     return false;
255   }
256   
257 // first, see if the hash contains a FGPositioned ghost - in which case
258 // we can read off its position directly
259   naRef posGhost = naHash_cget(ref, (char*) "_positioned");
260   if (!naIsNil(posGhost)) {
261     FGPositioned* pos = positionedGhost(posGhost);
262     result = pos->geod();
263     return true;
264   }
265   
266   naRef ghost = naHash_cget(ref, (char*) "_waypt");
267   if (!naIsNil(ghost)) {
268     flightgear::Waypt* w = wayptGhost(ghost);
269     result = w->position();
270     return true;
271   }
272   
273 // then check for manual latitude / longitude names
274   naRef lat = naHash_cget(ref, (char*) "lat");
275   naRef lon = naHash_cget(ref, (char*) "lon");
276   if (naIsNum(lat) && naIsNum(lon)) {
277     result = SGGeod::fromDeg(naNumValue(lat).num, naNumValue(lon).num);
278     return true;
279   }
280   
281 // check for geo.Coord type
282     
283 // check for any synonyms?
284     // latitude + longitude?
285   
286   return false;
287 }
288
289 static int geodFromArgs(naRef* args, int offset, int argc, SGGeod& result)
290 {
291   if (offset >= argc) {
292     return 0;
293   }
294   
295   if (geodFromHash(args[offset], result)) {
296     return 1;
297   }
298   
299   if (((argc - offset) >= 2) && naIsNum(args[offset]) && naIsNum(args[offset + 1])) {
300     double lat = naNumValue(args[0]).num,
301     lon = naNumValue(args[1]).num;
302     result = SGGeod::fromDeg(lon, lat);
303     return 2;
304   }
305   
306   return 0;
307 }
308
309 // Convert a cartesian point to a geodetic lat/lon/altitude.
310 static naRef f_carttogeod(naContext c, naRef me, int argc, naRef* args)
311 {
312   double lat, lon, alt, xyz[3];
313   if(argc != 3) naRuntimeError(c, "carttogeod() expects 3 arguments");
314   for(int i=0; i<3; i++)
315     xyz[i] = naNumValue(args[i]).num;
316   sgCartToGeod(xyz, &lat, &lon, &alt);
317   lat *= SG_RADIANS_TO_DEGREES;
318   lon *= SG_RADIANS_TO_DEGREES;
319   naRef vec = naNewVector(c);
320   naVec_append(vec, naNum(lat));
321   naVec_append(vec, naNum(lon));
322   naVec_append(vec, naNum(alt));
323   return vec;
324 }
325
326 // Convert a geodetic lat/lon/altitude to a cartesian point.
327 static naRef f_geodtocart(naContext c, naRef me, int argc, naRef* args)
328 {
329   if(argc != 3) naRuntimeError(c, "geodtocart() expects 3 arguments");
330   double lat = naNumValue(args[0]).num * SG_DEGREES_TO_RADIANS;
331   double lon = naNumValue(args[1]).num * SG_DEGREES_TO_RADIANS;
332   double alt = naNumValue(args[2]).num;
333   double xyz[3];
334   sgGeodToCart(lat, lon, alt, xyz);
335   naRef vec = naNewVector(c);
336   naVec_append(vec, naNum(xyz[0]));
337   naVec_append(vec, naNum(xyz[1]));
338   naVec_append(vec, naNum(xyz[2]));
339   return vec;
340 }
341
342 // For given geodetic point return array with elevation, and a material data
343 // hash, or nil if there's no information available (tile not loaded). If
344 // information about the material isn't available, then nil is returned instead
345 // of the hash.
346 static naRef f_geodinfo(naContext c, naRef me, int argc, naRef* args)
347 {
348 #define HASHSET(s,l,n) naHash_set(matdata, naStr_fromdata(naNewString(c),s,l),n)
349   if(argc < 2 || argc > 3)
350     naRuntimeError(c, "geodinfo() expects 2 or 3 arguments: lat, lon [, maxalt]");
351   double lat = naNumValue(args[0]).num;
352   double lon = naNumValue(args[1]).num;
353   double elev = argc == 3 ? naNumValue(args[2]).num : 10000;
354   const SGMaterial *mat;
355   SGGeod geod = SGGeod::fromDegM(lon, lat, elev);
356   if(!globals->get_scenery()->get_elevation_m(geod, elev, &mat))
357     return naNil();
358   naRef vec = naNewVector(c);
359   naVec_append(vec, naNum(elev));
360   naRef matdata = naNil();
361   if(mat) {
362     matdata = naNewHash(c);
363     naRef names = naNewVector(c);
364     BOOST_FOREACH(const std::string& n, mat->get_names())
365       naVec_append(names, stringToNasal(c, n));
366       
367     HASHSET("names", 5, names);
368     HASHSET("solid", 5, naNum(mat->get_solid()));
369     HASHSET("friction_factor", 15, naNum(mat->get_friction_factor()));
370     HASHSET("rolling_friction", 16, naNum(mat->get_rolling_friction()));
371     HASHSET("load_resistance", 15, naNum(mat->get_load_resistance()));
372     HASHSET("bumpiness", 9, naNum(mat->get_bumpiness()));
373     HASHSET("light_coverage", 14, naNum(mat->get_light_coverage()));
374   }
375   naVec_append(vec, matdata);
376   return vec;
377 #undef HASHSET
378 }
379
380
381 class AirportInfoFilter : public FGAirport::AirportFilter
382 {
383 public:
384   AirportInfoFilter() : type(FGPositioned::AIRPORT) {
385   }
386   
387   bool fromArg(naRef arg)
388   {
389     const char *s = naStr_data(arg);
390     if(!strcmp(s, "airport")) type = FGPositioned::AIRPORT;
391     else if(!strcmp(s, "seaport")) type = FGPositioned::SEAPORT;
392     else if(!strcmp(s, "heliport")) type = FGPositioned::HELIPORT;
393     else
394       return false;
395     
396     return true;
397   }
398   
399   virtual FGPositioned::Type minType() const {
400     return type;
401   }
402   
403   virtual FGPositioned::Type maxType() const {
404     return type;
405   }
406   
407   FGPositioned::Type type;
408 };
409
410 // Returns data hash for particular or nearest airport of a <type>, or nil
411 // on error.
412 //
413 // airportinfo(<id>);                   e.g. "KSFO"
414 // airportinfo(<type>);                 type := ("airport"|"seaport"|"heliport")
415 // airportinfo()                        same as  airportinfo("airport")
416 // airportinfo(<lat>, <lon> [, <type>]);
417 static naRef f_airportinfo(naContext c, naRef me, int argc, naRef* args)
418 {
419   SGGeod pos = globals->get_aircraft_position();
420   FGAirport* apt = NULL;
421   
422   if(argc >= 2 && naIsNum(args[0]) && naIsNum(args[1])) {
423     pos = SGGeod::fromDeg(args[1].num, args[0].num);
424     args += 2;
425     argc -= 2;
426   }
427   
428   double maxRange = 10000.0; // expose this? or pick a smaller value?
429   
430   AirportInfoFilter filter; // defaults to airports only
431   
432   if(argc == 0) {
433     // fall through and use AIRPORT
434   } else if(argc == 1 && naIsString(args[0])) {
435     if (filter.fromArg(args[0])) {
436       // done!
437     } else {
438       // user provided an <id>, hopefully
439       apt = FGAirport::findByIdent(naStr_data(args[0]));
440       if (!apt) {
441         // return nil here, but don't raise a runtime error; this is a
442         // legitamate way to validate an ICAO code, for example in a
443         // dialog box or similar.
444         return naNil();
445       }
446     }
447   } else {
448     naRuntimeError(c, "airportinfo() with invalid function arguments");
449     return naNil();
450   }
451   
452   if(!apt) {
453     apt = FGAirport::findClosest(pos, maxRange, &filter);
454     if(!apt) return naNil();
455   }
456   
457   return hashForAirport(c, apt);
458 }
459
460 static naRef f_findAirportsWithinRange(naContext c, naRef me, int argc, naRef* args)
461 {
462   int argOffset = 0;
463   SGGeod pos = globals->get_aircraft_position();
464   argOffset += geodFromArgs(args, 0, argc, pos);
465   
466   if (!naIsNum(args[argOffset])) {
467     naRuntimeError(c, "findAirportsWithinRange expected range (in nm) as arg %d", argOffset);
468   }
469   
470   AirportInfoFilter filter; // defaults to airports only
471   double rangeNm = args[argOffset++].num;
472   if (argOffset < argc) {
473     filter.fromArg(args[argOffset++]);
474   }
475   
476   naRef r = naNewVector(c);
477   
478   FGPositioned::List apts = FGPositioned::findWithinRange(pos, rangeNm, &filter);
479   FGPositioned::sortByRange(apts, pos);
480   
481   BOOST_FOREACH(FGPositionedRef a, apts) {
482     FGAirport* apt = (FGAirport*) a.get();
483     naVec_append(r, hashForAirport(c, apt));
484   }
485   
486   return r;
487 }
488
489 static naRef f_findAirportsByICAO(naContext c, naRef me, int argc, naRef* args)
490 {
491   if (!naIsString(args[0])) {
492     naRuntimeError(c, "findAirportsByICAO expects string as arg 0");
493   }
494   
495   int argOffset = 0;
496   string prefix(naStr_data(args[argOffset++]));
497   AirportInfoFilter filter; // defaults to airports only
498   if (argOffset < argc) {
499     filter.fromArg(args[argOffset++]);
500   }
501   
502   naRef r = naNewVector(c);
503   
504   FGPositioned::List apts = FGPositioned::findAllWithIdent(prefix, &filter, false);
505   
506   BOOST_FOREACH(FGPositionedRef a, apts) {
507     FGAirport* apt = (FGAirport*) a.get();
508     naVec_append(r, hashForAirport(c, apt));
509   }
510   
511   return r;
512 }
513
514 static FGAirport* airportFromMe(naRef me)
515 {  
516     naRef ghost = naHash_cget(me, (char*) "_positioned");
517     if (naIsNil(ghost)) {
518         return NULL;
519     }
520   
521     FGPositioned* pos = positionedGhost(ghost);
522     if (pos && FGAirport::isAirportType(pos)) {
523         return (FGAirport*) pos;
524     }
525
526     return NULL;
527 }
528
529 static naRef f_airport_tower(naContext c, naRef me, int argc, naRef* args)
530 {
531     FGAirport* apt = airportFromMe(me);
532     if (!apt) {
533       naRuntimeError(c, "airport.tower called on non-airport object");
534     }
535   
536     // build a hash for the tower position    
537     SGGeod towerLoc = apt->getTowerLocation();
538     naRef tower = naNewHash(c);
539     hashset(c, tower, "lat", naNum(towerLoc.getLatitudeDeg()));
540     hashset(c, tower, "lon", naNum(towerLoc.getLongitudeDeg()));
541     hashset(c, tower, "elevation", naNum(towerLoc.getElevationM()));
542     return tower;
543 }
544
545 static naRef f_airport_comms(naContext c, naRef me, int argc, naRef* args)
546 {
547     FGAirport* apt = airportFromMe(me);
548     if (!apt) {
549       naRuntimeError(c, "airport.comms called on non-airport object");
550     }
551     naRef comms = naNewVector(c);
552     
553 // if we have an explicit type, return a simple vector of frequencies
554     if (argc > 0 && naIsScalar(args[0])) {
555         std::string commName = naStr_data(args[0]);
556         FGPositioned::Type commType = FGPositioned::typeFromName(commName);
557         
558         BOOST_FOREACH(flightgear::CommStation* comm, apt->commStationsOfType(commType)) {
559             naVec_append(comms, naNum(comm->freqMHz()));
560         }
561     } else {
562 // otherwise return a vector of hashes, one for each comm station.
563         BOOST_FOREACH(flightgear::CommStation* comm, apt->commStations()) {
564             naRef commHash = naNewHash(c);
565             hashset(c, commHash, "frequency", naNum(comm->freqMHz()));
566             hashset(c, commHash, "ident", stringToNasal(c, comm->ident()));
567             naVec_append(comms, commHash);
568         }
569     }
570     
571     return comms;
572 }
573
574 static naRef f_airport_sids(naContext c, naRef me, int argc, naRef* args)
575 {
576   FGAirport* apt = airportFromMe(me);
577   if (!apt) {
578     naRuntimeError(c, "airport.sids called on non-airport object");
579   }
580   
581   naRef sids = naNewVector(c);
582   
583   // if we have an explicit type, return a simple vector of frequencies
584   if (argc > 0 && naIsString(args[0])) {
585     if (!apt->hasRunwayWithIdent(naStr_data(args[0]))) {
586       return naNil();
587     }
588
589     FGRunway* rwy = apt->getRunwayByIdent(naStr_data(args[0]));
590     BOOST_FOREACH(flightgear::SID* sid, rwy->getSIDs()) {
591       naRef procId = stringToNasal(c, sid->ident());
592       naVec_append(sids, procId);
593     }
594   } else {
595     for (unsigned int s=0; s<apt->numSIDs(); ++s) {
596       flightgear::SID* sid = apt->getSIDByIndex(s);
597       naRef procId = stringToNasal(c, sid->ident());
598       naVec_append(sids, procId);
599     }
600   }
601   
602   return sids;
603 }
604
605 static naRef f_airport_stars(naContext c, naRef me, int argc, naRef* args)
606 {
607   FGAirport* apt = airportFromMe(me);
608   if (!apt) {
609     naRuntimeError(c, "airport.stars called on non-airport object");
610   }
611   
612   naRef stars = naNewVector(c);
613   
614   // if we have an explicit type, return a simple vector of frequencies
615   if (argc > 0 && naIsString(args[0])) {
616     if (!apt->hasRunwayWithIdent(naStr_data(args[0]))) {
617       return naNil();
618     }
619         
620     FGRunway* rwy = apt->getRunwayByIdent(naStr_data(args[0]));
621     BOOST_FOREACH(flightgear::STAR* s, rwy->getSTARs()) {
622       naRef procId = stringToNasal(c, s->ident());
623       naVec_append(stars, procId);
624     }
625   } else {
626     for (unsigned int s=0; s<apt->numSTARs(); ++s) {
627       flightgear::STAR* star = apt->getSTARByIndex(s);
628       naRef procId = stringToNasal(c, star->ident());
629       naVec_append(stars, procId);
630     }
631   }
632   
633   return stars;
634 }
635
636 static naRef f_airport_parking(naContext c, naRef me, int argc, naRef* args)
637 {
638   FGAirport* apt = airportFromMe(me);
639   if (!apt) {
640     naRuntimeError(c, "airport.parking called on non-airport object");
641   }
642   
643   naRef r = naNewVector(c);
644   std::string type;
645   bool onlyAvailable = false;
646   
647   if (argc > 0 && naIsString(args[0])) {
648     type = naStr_data(args[0]);
649   }
650   
651   if ((argc > 1) && naIsNum(args[1])) {
652     onlyAvailable = (args[1].num != 0.0);
653   }
654   
655   FGAirportDynamics* dynamics = apt->getDynamics();
656   for (int i=0; i<dynamics->getNrOfParkings(); ++i) {
657     FGParking* park = dynamics->getParking(i);
658   // filter out based on availability and type
659     if (onlyAvailable && !park->isAvailable()) {
660       continue;
661     }
662     
663     if (!type.empty() && (park->getType() != type)) {
664       continue;
665     }
666     
667     naRef nm = stringToNasal(c, park->getName());
668     naVec_append(r, nm);
669   }
670   
671   return r;
672 }
673
674 // Returns vector of data hash for navaid of a <type>, nil on error
675 // navaids sorted by ascending distance 
676 // navinfo([<lat>,<lon>],[<type>],[<id>])
677 // lat/lon (numeric): use latitude/longitude instead of ac position
678 // type:              ("fix"|"vor"|"ndb"|"ils"|"dme"|"tacan"|"any")
679 // id:                (partial) id of the fix
680 // examples:
681 // navinfo("vor")     returns all vors
682 // navinfo("HAM")     return all navaids who's name start with "HAM"
683 // navinfo("vor", "HAM") return all vor who's name start with "HAM"
684 //navinfo(34,48,"vor","HAM") return all vor who's name start with "HAM" 
685 //                           sorted by distance relative to lat=34, lon=48
686 static naRef f_navinfo(naContext c, naRef me, int argc, naRef* args)
687 {
688   SGGeod pos;
689   
690   if(argc >= 2 && naIsNum(args[0]) && naIsNum(args[1])) {
691     pos = SGGeod::fromDeg(args[1].num, args[0].num);
692     args += 2;
693     argc -= 2;
694   } else {
695     pos = globals->get_aircraft_position();
696   }
697   
698   FGPositioned::Type type = FGPositioned::INVALID;
699   nav_list_type navlist;
700   const char * id = "";
701   
702   if(argc > 0 && naIsString(args[0])) {
703     const char *s = naStr_data(args[0]);
704     if(!strcmp(s, "any")) type = FGPositioned::INVALID;
705     else if(!strcmp(s, "fix")) type = FGPositioned::FIX;
706     else if(!strcmp(s, "vor")) type = FGPositioned::VOR;
707     else if(!strcmp(s, "ndb")) type = FGPositioned::NDB;
708     else if(!strcmp(s, "ils")) type = FGPositioned::ILS;
709     else if(!strcmp(s, "dme")) type = FGPositioned::DME;
710     else if(!strcmp(s, "tacan")) type = FGPositioned::TACAN;
711     else id = s; // this is an id
712     ++args;
713     --argc;
714   } 
715   
716   if(argc > 0 && naIsString(args[0])) {
717     if( *id != 0 ) {
718       naRuntimeError(c, "navinfo() called with navaid id");
719       return naNil();
720     }
721     id = naStr_data(args[0]);
722     ++args;
723     --argc;
724   }
725   
726   if( argc > 0 ) {
727     naRuntimeError(c, "navinfo() called with too many arguments");
728     return naNil();
729   }
730   
731   navlist = globals->get_navlist()->findByIdentAndFreq( pos, id, 0.0, type );
732   
733   naRef reply = naNewVector(c);
734   for( nav_list_type::const_iterator it = navlist.begin(); it != navlist.end(); ++it ) {
735     naVec_append( reply, hashForNavRecord(c, *it, pos) );
736   }
737   return reply;
738 }
739
740 static naRef f_findNavaidsWithinRange(naContext c, naRef me, int argc, naRef* args)
741 {
742   int argOffset = 0;
743   SGGeod pos = globals->get_aircraft_position();
744   argOffset += geodFromArgs(args, 0, argc, pos);
745   
746   if (!naIsNum(args[argOffset])) {
747     naRuntimeError(c, "findNavaidsWithinRange expected range (in nm) as arg %d", argOffset);
748   }
749   
750   FGPositioned::Type type = FGPositioned::INVALID;
751   double rangeNm = args[argOffset++].num;
752   if (argOffset < argc) {
753     type = FGPositioned::typeFromName(naStr_data(args[argOffset]));
754   }
755   
756   naRef r = naNewVector(c);
757   FGNavList::TypeFilter filter(type);
758   FGPositioned::List navs = FGPositioned::findWithinRange(pos, rangeNm, &filter);
759   FGPositioned::sortByRange(navs, pos);
760   
761   BOOST_FOREACH(FGPositionedRef a, navs) {
762     FGNavRecord* nav = (FGNavRecord*) a.get();
763     naVec_append(r, hashForNavRecord(c, nav, pos));
764   }
765   
766   return r;
767 }
768
769 static naRef f_findNavaidByFrequency(naContext c, naRef me, int argc, naRef* args)
770 {
771   int argOffset = 0;
772   SGGeod pos = globals->get_aircraft_position();
773   argOffset += geodFromArgs(args, 0, argc, pos);
774   
775   if (!naIsNum(args[argOffset])) {
776     naRuntimeError(c, "findNavaidByFrequency expectes frequency (in Mhz) as arg %d", argOffset);
777   }
778   
779   FGPositioned::Type type = FGPositioned::INVALID;
780   double freqMhz = args[argOffset++].num;
781   if (argOffset < argc) {
782     type = FGPositioned::typeFromName(naStr_data(args[argOffset]));
783   }
784   
785   nav_list_type navs = globals->get_navlist()->findAllByFreq(freqMhz, pos, type);
786   if (navs.empty()) {
787     return naNil();
788   }
789   
790   return hashForNavRecord(c, navs.front().ptr(), pos);
791 }
792
793 static naRef f_findNavaidsByFrequency(naContext c, naRef me, int argc, naRef* args)
794 {
795   int argOffset = 0;
796   SGGeod pos = globals->get_aircraft_position();
797   argOffset += geodFromArgs(args, 0, argc, pos);
798   
799   if (!naIsNum(args[argOffset])) {
800     naRuntimeError(c, "findNavaidsByFrequency expectes frequency (in Mhz) as arg %d", argOffset);
801   }
802   
803   FGPositioned::Type type = FGPositioned::INVALID;
804   double freqMhz = args[argOffset++].num;
805   if (argOffset < argc) {
806     type = FGPositioned::typeFromName(naStr_data(args[argOffset]));
807   }
808   
809   naRef r = naNewVector(c);
810   nav_list_type navs = globals->get_navlist()->findAllByFreq(freqMhz, pos, type);
811   
812   BOOST_FOREACH(nav_rec_ptr a, navs) {
813     naVec_append(r, hashForNavRecord(c, a.ptr(), pos));
814   }
815   
816   return r;
817 }
818
819 static naRef f_findNavaidsByIdent(naContext c, naRef me, int argc, naRef* args)
820 {
821   int argOffset = 0;
822   SGGeod pos = globals->get_aircraft_position();
823   argOffset += geodFromArgs(args, 0, argc, pos);
824   
825   if (!naIsString(args[argOffset])) {
826     naRuntimeError(c, "findNavaidsByIdent expectes ident string as arg %d", argOffset);
827   }
828   
829   FGPositioned::Type type = FGPositioned::INVALID;
830   string ident = naStr_data(args[argOffset++]);
831   if (argOffset < argc) {
832     type = FGPositioned::typeFromName(naStr_data(args[argOffset]));
833   }
834   
835   naRef r = naNewVector(c);
836   nav_list_type navs = globals->get_navlist()->findByIdentAndFreq(pos, ident, 0.0, type);
837   
838   BOOST_FOREACH(nav_rec_ptr a, navs) {
839     naVec_append(r, hashForNavRecord(c, a.ptr(), pos));
840   }
841   
842   return r;
843 }
844
845
846 // Convert a cartesian point to a geodetic lat/lon/altitude.
847 static naRef f_magvar(naContext c, naRef me, int argc, naRef* args)
848 {
849   SGGeod pos = globals->get_aircraft_position();
850   if (argc == 0) {
851     // fine, use aircraft position
852   } else if (geodFromArgs(args, 0, argc, pos)) {
853     // okay
854   } else {
855     naRuntimeError(c, "magvar() expects no arguments, a positioned hash or lat,lon pair");
856   }
857   
858   double jd = globals->get_time_params()->getJD();
859   double magvarDeg = sgGetMagVar(pos, jd) * SG_RADIANS_TO_DEGREES;
860   return naNum(magvarDeg);
861 }
862
863 static naRef f_courseAndDistance(naContext c, naRef me, int argc, naRef* args)
864 {
865     SGGeod from = globals->get_aircraft_position(), to, p;
866     int argOffset = geodFromArgs(args, 0, argc, p);
867     if (geodFromArgs(args, argOffset, argc, to)) {
868       from = p; // we parsed both FROM and TO args, so first was from
869     } else {
870       to = p; // only parsed one arg, so FROM is current
871     }
872   
873     if (argOffset == 0) {
874         naRuntimeError(c, "invalid arguments to courseAndDistance");
875     }
876     
877     double course, course2, d;
878     SGGeodesy::inverse(from, to, course, course2, d);
879     
880     naRef result = naNewVector(c);
881     naVec_append(result, naNum(course));
882     naVec_append(result, naNum(d * SG_METER_TO_NM));
883     return result;
884 }
885
886 static naRef f_tilePath(naContext c, naRef me, int argc, naRef* args)
887 {
888     SGGeod pos = globals->get_aircraft_position();
889     geodFromArgs(args, 0, argc, pos);
890     SGBucket b(pos);
891     return stringToNasal(c, b.gen_base_path());
892 }
893
894 static naRef f_route(naContext c, naRef me, int argc, naRef* args)
895 {
896   naRef route = naNewHash(c);
897   
898   // return active route hash by default,
899   // other routes in the future
900   
901   naRef parents = naNewVector(c);
902   naVec_append(parents, routePrototype);
903   hashset(c, route, "parents", parents);
904   
905   return route;
906 }
907
908 static naRef f_route_getWP(naContext c, naRef me, int argc, naRef* args)
909 {
910   FGRouteMgr* rm = static_cast<FGRouteMgr*>(globals->get_subsystem("route-manager"));
911   
912   int index;
913   if (argc == 0) {
914     index = rm->currentIndex();
915   } else {
916     index = (int) naNumValue(args[0]).num;
917   }
918   
919   if ((index < 0) || (index >= rm->numWaypts())) {
920     return naNil();
921   }
922   
923   flightgear::Waypt* next = NULL;
924   if (index < (rm->numWaypts() - 1)) {
925     next = rm->wayptAtIndex(index + 1);
926   }
927   return hashForWaypoint(c, rm->wayptAtIndex(index), next);
928 }
929
930 static naRef f_route_currentWP(naContext c, naRef me, int argc, naRef* args)
931 {
932   FGRouteMgr* rm = static_cast<FGRouteMgr*>(globals->get_subsystem("route-manager"));
933   flightgear::Waypt* next = NULL;
934   if (rm->currentIndex() < (rm->numWaypts() - 1)) {
935     next = rm->wayptAtIndex(rm->currentIndex() + 1);
936   }
937   return hashForWaypoint(c, rm->currentWaypt(), next);
938 }
939
940 static naRef f_route_currentIndex(naContext c, naRef me, int argc, naRef* args)
941 {
942   FGRouteMgr* rm = static_cast<FGRouteMgr*>(globals->get_subsystem("route-manager"));
943   return naNum(rm->currentIndex());
944 }
945
946 static naRef f_route_numWaypoints(naContext c, naRef me, int argc, naRef* args)
947 {
948   FGRouteMgr* rm = static_cast<FGRouteMgr*>(globals->get_subsystem("route-manager"));
949   return naNum(rm->numWaypts());
950 }
951
952 static flightgear::Waypt* wayptFromMe(naRef me)
953 {  
954   naRef ghost = naHash_cget(me, (char*) "_waypt");
955   if (naIsNil(ghost)) {
956     return NULL;
957   }
958   
959   return wayptGhost(ghost);
960 }
961
962 static naRef f_waypoint_navaid(naContext c, naRef me, int argc, naRef* args)
963 {
964   flightgear::Waypt* w = wayptFromMe(me);
965   if (!w) {
966     naRuntimeError(c, "waypoint.navaid called on non-waypoint object");
967   }
968   
969   FGPositioned* pos = w->source();
970   if (!pos) {
971     return naNil();
972   }
973   
974   switch (pos->type()) {
975   case FGPositioned::VOR:
976   case FGPositioned::NDB:
977   case FGPositioned::ILS:
978   case FGPositioned::LOC:
979   case FGPositioned::GS:
980   case FGPositioned::DME:
981   case FGPositioned::TACAN: {
982     FGNavRecord* nav = (FGNavRecord*) pos;
983     return hashForNavRecord(c, nav, globals->get_aircraft_position());
984   }
985       
986   default:
987     return naNil();
988   }
989 }
990
991 static naRef f_waypoint_airport(naContext c, naRef me, int argc, naRef* args)
992 {
993   flightgear::Waypt* w = wayptFromMe(me);
994   if (!w) {
995     naRuntimeError(c, "waypoint.navaid called on non-waypoint object");
996   }
997   
998   FGPositioned* pos = w->source();
999   if (!pos || FGAirport::isAirportType(pos)) {
1000     return naNil();
1001   }
1002   
1003   return hashForAirport(c, (FGAirport*) pos);
1004 }
1005
1006 static naRef f_waypoint_runway(naContext c, naRef me, int argc, naRef* args)
1007 {
1008   flightgear::Waypt* w = wayptFromMe(me);
1009   if (!w) {
1010     naRuntimeError(c, "waypoint.navaid called on non-waypoint object");
1011   }
1012   
1013   FGPositioned* pos = w->source();
1014   if (!pos || (pos->type() != FGPositioned::RUNWAY)) {
1015     return naNil();
1016   }
1017   
1018   return hashForRunway(c, (FGRunway*) pos);
1019 }
1020
1021 // Table of extension functions.  Terminate with zeros.
1022 static struct { const char* name; naCFunction func; } funcs[] = {
1023   { "carttogeod", f_carttogeod },
1024   { "geodtocart", f_geodtocart },
1025   { "geodinfo", f_geodinfo },
1026   { "airportinfo", f_airportinfo },
1027   { "findAirportsWithinRange", f_findAirportsWithinRange },
1028   { "findAirportsByICAO", f_findAirportsByICAO },
1029   { "navinfo", f_navinfo },
1030   { "findNavaidsWithinRange", f_findNavaidsWithinRange },
1031   { "findNavaidByFrequency", f_findNavaidByFrequency },
1032   { "findNavaidsByFrequency", f_findNavaidsByFrequency },
1033   { "findNavaidsByID", f_findNavaidsByIdent },
1034   { "route", f_route },
1035   { "magvar", f_magvar },
1036   { "courseAndDistance", f_courseAndDistance },
1037   { "bucketPath", f_tilePath },
1038   { 0, 0 }
1039 };
1040
1041
1042 naRef initNasalPositioned(naRef globals, naContext c, naRef gcSave)
1043 {
1044     airportPrototype = naNewHash(c);
1045     hashset(c, gcSave, "airportProto", airportPrototype);
1046   
1047     hashset(c, airportPrototype, "tower", naNewFunc(c, naNewCCode(c, f_airport_tower)));
1048     hashset(c, airportPrototype, "comms", naNewFunc(c, naNewCCode(c, f_airport_comms)));
1049     hashset(c, airportPrototype, "sids", naNewFunc(c, naNewCCode(c, f_airport_sids)));
1050     hashset(c, airportPrototype, "stars", naNewFunc(c, naNewCCode(c, f_airport_stars)));
1051     hashset(c, airportPrototype, "parking", naNewFunc(c, naNewCCode(c, f_airport_parking)));
1052   
1053     routePrototype = naNewHash(c);
1054     hashset(c, gcSave, "routeProto", routePrototype);
1055       
1056     hashset(c, routePrototype, "getWP", naNewFunc(c, naNewCCode(c, f_route_getWP)));
1057     hashset(c, routePrototype, "currentWP", naNewFunc(c, naNewCCode(c, f_route_currentWP)));
1058     hashset(c, routePrototype, "currentIndex", naNewFunc(c, naNewCCode(c, f_route_currentIndex)));
1059     hashset(c, routePrototype, "getPlanSize", naNewFunc(c, naNewCCode(c, f_route_numWaypoints)));
1060     
1061     waypointPrototype = naNewHash(c);
1062     hashset(c, gcSave, "wayptProto", waypointPrototype);
1063     
1064     hashset(c, waypointPrototype, "navaid", naNewFunc(c, naNewCCode(c, f_waypoint_navaid)));
1065     hashset(c, waypointPrototype, "runway", naNewFunc(c, naNewCCode(c, f_waypoint_runway)));
1066     hashset(c, waypointPrototype, "airport", naNewFunc(c, naNewCCode(c, f_waypoint_airport)));
1067   
1068     for(int i=0; funcs[i].name; i++) {
1069       hashset(c, globals, funcs[i].name,
1070             naNewFunc(c, naNewCCode(c, funcs[i].func)));
1071     }
1072   
1073   return naNil();
1074 }
1075