]> git.mxchange.org Git - flightgear.git/blob - src/Scripting/NasalPositioned.cxx
Push SGMaterial use into these classes that need it.
[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 #include <boost/algorithm/string/case_conv.hpp>
31
32 #include <simgear/sg_inlines.h>
33 #include <simgear/scene/material/mat.hxx>
34 #include <simgear/magvar/magvar.hxx>
35 #include <simgear/timing/sg_time.hxx>
36 #include <simgear/bucket/newbucket.hxx>
37
38 #include <Airports/runways.hxx>
39 #include <Airports/simple.hxx>
40 #include <Airports/dynamics.hxx>
41 #include <Airports/parking.hxx>
42 #include <Scripting/NasalSys.hxx>
43 #include <Navaids/navlist.hxx>
44 #include <Navaids/procedure.hxx>
45 #include <Main/globals.hxx>
46 #include <Main/fg_props.hxx>
47 #include <Scenery/scenery.hxx>
48 #include <ATC/CommStation.hxx>
49 #include <Navaids/FlightPlan.hxx>
50 #include <Navaids/waypoint.hxx>
51 #include <Navaids/fix.hxx>
52 #include <Autopilot/route_mgr.hxx>
53 #include <Navaids/procedure.hxx>
54 #include <Navaids/airways.hxx>
55
56 using namespace flightgear;
57
58 static void positionedGhostDestroy(void* g);
59 static void wayptGhostDestroy(void* g);
60 static void legGhostDestroy(void* g);
61 static void routeBaseGhostDestroy(void* g);
62
63 naGhostType PositionedGhostType = { positionedGhostDestroy, "positioned" };
64
65 static const char* airportGhostGetMember(naContext c, void* g, naRef field, naRef* out);
66 naGhostType AirportGhostType = { positionedGhostDestroy, "airport", airportGhostGetMember, 0 };
67
68 static const char* navaidGhostGetMember(naContext c, void* g, naRef field, naRef* out);
69 naGhostType NavaidGhostType = { positionedGhostDestroy, "navaid", navaidGhostGetMember, 0 };
70
71 static const char* runwayGhostGetMember(naContext c, void* g, naRef field, naRef* out);
72 naGhostType RunwayGhostType = { positionedGhostDestroy, "runway", runwayGhostGetMember, 0 };
73
74 static const char* fixGhostGetMember(naContext c, void* g, naRef field, naRef* out);
75 naGhostType FixGhostType = { positionedGhostDestroy, "fix", fixGhostGetMember, 0 };
76
77 static const char* wayptGhostGetMember(naContext c, void* g, naRef field, naRef* out);
78 static void waypointGhostSetMember(naContext c, void* g, naRef field, naRef value);
79
80 naGhostType WayptGhostType = { wayptGhostDestroy, 
81   "waypoint",
82   wayptGhostGetMember,
83   waypointGhostSetMember};
84
85 static const char* legGhostGetMember(naContext c, void* g, naRef field, naRef* out);
86 static void legGhostSetMember(naContext c, void* g, naRef field, naRef value);
87
88 naGhostType FPLegGhostType = { legGhostDestroy, 
89   "flightplan-leg",
90   legGhostGetMember,
91   legGhostSetMember};
92
93 static const char* flightplanGhostGetMember(naContext c, void* g, naRef field, naRef* out);
94 static void flightplanGhostSetMember(naContext c, void* g, naRef field, naRef value);
95
96 naGhostType FlightPlanGhostType = { routeBaseGhostDestroy, 
97   "flightplan",
98   flightplanGhostGetMember,
99   flightplanGhostSetMember
100 };
101
102 static const char* procedureGhostGetMember(naContext c, void* g, naRef field, naRef* out);
103 naGhostType ProcedureGhostType = { routeBaseGhostDestroy, 
104   "procedure",
105   procedureGhostGetMember,
106   0};
107
108 static void hashset(naContext c, naRef hash, const char* key, naRef val)
109 {
110   naRef s = naNewString(c);
111   naStr_fromdata(s, (char*)key, strlen(key));
112   naHash_set(hash, s, val);
113 }
114
115 static naRef stringToNasal(naContext c, const std::string& s)
116 {
117     return naStr_fromdata(naNewString(c),
118                    const_cast<char *>(s.c_str()), 
119                    s.length());
120 }
121
122 static WayptFlag wayptFlagFromString(const char* s)
123 {
124   if (!strcmp(s, "sid")) return WPT_DEPARTURE;
125   if (!strcmp(s, "star")) return WPT_ARRIVAL;
126   if (!strcmp(s, "approach")) return WPT_APPROACH;
127   if (!strcmp(s, "missed")) return WPT_MISS;
128   if (!strcmp(s, "pseudo")) return WPT_PSEUDO;
129   
130   return (WayptFlag) 0;
131 }
132
133 static naRef wayptFlagToNasal(naContext c, unsigned int flags)
134 {
135   if (flags & WPT_PSEUDO) return stringToNasal(c, "pseudo");
136   if (flags & WPT_DEPARTURE) return stringToNasal(c, "sid");
137   if (flags & WPT_ARRIVAL) return stringToNasal(c, "star");
138   if (flags & WPT_MISS) return stringToNasal(c, "missed");
139   if (flags & WPT_APPROACH) return stringToNasal(c, "approach");
140   return naNil();
141 }
142
143 static FGPositioned* positionedGhost(naRef r)
144 {
145     if ((naGhost_type(r) == &AirportGhostType) ||
146         (naGhost_type(r) == &NavaidGhostType) ||
147         (naGhost_type(r) == &RunwayGhostType) ||
148         (naGhost_type(r) == &FixGhostType))
149     {
150         return (FGPositioned*) naGhost_ptr(r);
151     }
152   
153     return 0;
154 }
155
156 static FGAirport* airportGhost(naRef r)
157 {
158   if (naGhost_type(r) == &AirportGhostType)
159     return (FGAirport*) naGhost_ptr(r);
160   return 0;
161 }
162
163 static FGNavRecord* navaidGhost(naRef r)
164 {
165   if (naGhost_type(r) == &NavaidGhostType)
166     return (FGNavRecord*) naGhost_ptr(r);
167   return 0;
168 }
169
170 static FGRunway* runwayGhost(naRef r)
171 {
172   if (naGhost_type(r) == &RunwayGhostType)
173     return (FGRunway*) naGhost_ptr(r);
174   return 0;
175 }
176
177 static FGFix* fixGhost(naRef r)
178 {
179   if (naGhost_type(r) == &FixGhostType)
180     return (FGFix*) naGhost_ptr(r);
181   return 0;
182 }
183
184
185 static void positionedGhostDestroy(void* g)
186 {
187     FGPositioned* pos = (FGPositioned*)g;
188     if (!FGPositioned::put(pos)) // unref
189         delete pos;
190 }
191
192 static Waypt* wayptGhost(naRef r)
193 {
194   if (naGhost_type(r) == &WayptGhostType)
195     return (Waypt*) naGhost_ptr(r);
196   
197   if (naGhost_type(r) == &FPLegGhostType) {
198     FlightPlan::Leg* leg = (FlightPlan::Leg*) naGhost_ptr(r);
199     return leg->waypoint();
200   }
201   
202   return 0;
203 }
204
205 static void wayptGhostDestroy(void* g)
206 {
207   Waypt* wpt = (Waypt*)g;
208   if (!Waypt::put(wpt)) // unref
209     delete wpt;
210 }
211
212 static void legGhostDestroy(void* g)
213 {
214   // nothing for now
215 }
216
217
218 static FlightPlan::Leg* fpLegGhost(naRef r)
219 {
220   if (naGhost_type(r) == &FPLegGhostType)
221     return (FlightPlan::Leg*) naGhost_ptr(r);
222   return 0;
223 }
224
225 static Procedure* procedureGhost(naRef r)
226 {
227   if (naGhost_type(r) == &ProcedureGhostType)
228     return (Procedure*) naGhost_ptr(r);
229   return 0;
230 }
231
232 static FlightPlan* flightplanGhost(naRef r)
233 {
234   if (naGhost_type(r) == &FlightPlanGhostType)
235     return (FlightPlan*) naGhost_ptr(r);
236   return 0;
237 }
238
239 static void routeBaseGhostDestroy(void* g)
240 {
241   // nothing for now
242 }
243
244 static naRef airportPrototype;
245 static naRef flightplanPrototype;
246 static naRef waypointPrototype;
247 static naRef geoCoordClass;
248 static naRef fpLegPrototype;
249 static naRef procedurePrototype;
250
251 naRef ghostForAirport(naContext c, const FGAirport* apt)
252 {
253   if (!apt) {
254     return naNil();
255   }
256   
257   FGPositioned::get(apt); // take a ref
258   return naNewGhost2(c, &AirportGhostType, (void*) apt);
259 }
260
261 naRef ghostForNavaid(naContext c, const FGNavRecord* n)
262 {
263   if (!n) {
264     return naNil();
265   }
266   
267   FGPositioned::get(n); // take a ref
268   return naNewGhost2(c, &NavaidGhostType, (void*) n);
269 }
270
271 naRef ghostForRunway(naContext c, const FGRunway* r)
272 {
273   if (!r) {
274     return naNil();
275   }
276   
277   FGPositioned::get(r); // take a ref
278   return naNewGhost2(c, &RunwayGhostType, (void*) r);
279 }
280
281 naRef ghostForFix(naContext c, const FGFix* r)
282 {
283   if (!r) {
284     return naNil();
285   }
286   
287   FGPositioned::get(r); // take a ref
288   return naNewGhost2(c, &FixGhostType, (void*) r);
289 }
290
291
292 naRef ghostForWaypt(naContext c, const Waypt* wpt)
293 {
294   if (!wpt) {
295     return naNil();
296   }
297   
298   Waypt::get(wpt); // take a ref
299   return naNewGhost2(c, &WayptGhostType, (void*) wpt);
300 }
301
302 naRef ghostForLeg(naContext c, const FlightPlan::Leg* leg)
303 {
304   if (!leg) {
305     return naNil();
306   }
307   
308   return naNewGhost2(c, &FPLegGhostType, (void*) leg);
309 }
310
311 naRef ghostForFlightPlan(naContext c, const FlightPlan* fp)
312 {
313   if (!fp) {
314     return naNil();
315   }
316   
317   return naNewGhost2(c, &FlightPlanGhostType, (void*) fp);
318 }
319
320 naRef ghostForProcedure(naContext c, const Procedure* proc)
321 {
322   if (!proc) {
323     return naNil();
324   }
325   
326   return naNewGhost2(c, &ProcedureGhostType, (void*) proc);
327 }
328
329 static const char* airportGhostGetMember(naContext c, void* g, naRef field, naRef* out)
330 {
331   const char* fieldName = naStr_data(field);
332   FGAirport* apt = (FGAirport*) g;
333   
334   if (!strcmp(fieldName, "parents")) {
335     *out = naNewVector(c);
336     naVec_append(*out, airportPrototype);
337   } else if (!strcmp(fieldName, "id")) *out = stringToNasal(c, apt->ident());
338   else if (!strcmp(fieldName, "name")) *out = stringToNasal(c, apt->name());
339   else if (!strcmp(fieldName, "lat")) *out = naNum(apt->getLatitude());
340   else if (!strcmp(fieldName, "lon")) *out = naNum(apt->getLongitude());
341   else if (!strcmp(fieldName, "elevation")) {
342     *out = naNum(apt->getElevation() * SG_FEET_TO_METER);
343   } else if (!strcmp(fieldName, "has_metar")) {
344     *out = naNum(apt->getMetar());
345   } else if (!strcmp(fieldName, "runways")) {
346     *out = naNewHash(c);
347     double minLengthFt = fgGetDouble("/sim/navdb/min-runway-length-ft");
348     for(unsigned int r=0; r<apt->numRunways(); ++r) {
349       FGRunway* rwy(apt->getRunwayByIndex(r));
350       
351     // ignore unusably short runways
352       if (rwy->lengthFt() < minLengthFt) {
353         continue;
354       }
355       
356       naRef rwyid = stringToNasal(c, rwy->ident());
357       naRef rwydata = ghostForRunway(c, rwy);
358       naHash_set(*out, rwyid, rwydata);
359     }
360
361   } else {
362     return 0;
363   }
364   
365   return "";
366 }
367
368 static const char* waypointCommonGetMember(naContext c, Waypt* wpt, const char* fieldName, naRef* out)
369 {
370   if (!strcmp(fieldName, "wp_name")) *out = stringToNasal(c, wpt->ident());
371   else if (!strcmp(fieldName, "wp_type")) *out = stringToNasal(c, wpt->type());
372   else if (!strcmp(fieldName, "wp_role")) *out = wayptFlagToNasal(c, wpt->flags());
373   else if (!strcmp(fieldName, "wp_lat")) *out = naNum(wpt->position().getLatitudeDeg());
374   else if (!strcmp(fieldName, "wp_lon")) *out = naNum(wpt->position().getLongitudeDeg());
375   else if (!strcmp(fieldName, "wp_parent_name")) {
376     Procedure* proc = dynamic_cast<Procedure*>(wpt->owner());
377     *out = proc ? stringToNasal(c, proc->ident()) : naNil();
378   } else if (!strcmp(fieldName, "wp_parent")) {
379     Procedure* proc = dynamic_cast<Procedure*>(wpt->owner());
380     *out = ghostForProcedure(c, proc);
381   } else if (!strcmp(fieldName, "fly_type")) {
382     if (wpt->type() == "hold") {
383       *out = stringToNasal(c, "Hold");
384     } else {
385       *out = stringToNasal(c, wpt->flag(WPT_OVERFLIGHT) ? "flyOver" : "flyBy");
386     }
387   } else {
388     return NULL; // member not found
389   }
390
391   return "";
392 }
393
394 static void waypointCommonSetMember(naContext c, Waypt* wpt, const char* fieldName, naRef value)
395 {
396   if (!strcmp(fieldName, "wp_role")) {
397     if (!naIsString(value)) naRuntimeError(c, "wp_role must be a string");
398     if (wpt->owner() != NULL) naRuntimeError(c, "cannot override wp_role on waypoint with parent");
399     WayptFlag f = wayptFlagFromString(naStr_data(value));
400     if (f == 0) {
401       naRuntimeError(c, "unrecognized wp_role value %s", naStr_data(value));
402     }
403     
404     wpt->setFlag(f, true);
405   }
406 }
407
408 static const char* wayptGhostGetMember(naContext c, void* g, naRef field, naRef* out)
409 {
410   const char* fieldName = naStr_data(field);
411   Waypt* wpt = (flightgear::Waypt*) g;
412   return waypointCommonGetMember(c, wpt, fieldName, out);
413 }
414
415 static RouteRestriction routeRestrictionFromString(const char* s)
416 {
417   string u(s);
418   boost::to_lower(u);
419   if (u == "computed") return RESTRICT_COMPUTED;
420   if (u == "at") return RESTRICT_AT;
421   if (u == "mach") return SPEED_RESTRICT_MACH;
422   if (u == "computed-mach") return SPEED_COMPUTED_MACH;
423   if (u == "delete") return RESTRICT_DELETE;
424   return RESTRICT_NONE;
425 };
426
427 naRef routeRestrictionToNasal(naContext c, RouteRestriction rr)
428 {
429   switch (rr) {
430     case RESTRICT_NONE: return naNil();
431     case RESTRICT_AT: return stringToNasal(c, "at");
432     case RESTRICT_ABOVE: return stringToNasal(c, "above");
433     case RESTRICT_BELOW: return stringToNasal(c, "below");
434     case SPEED_RESTRICT_MACH: return stringToNasal(c, "mach");
435     case RESTRICT_COMPUTED: return stringToNasal(c, "computed");
436     case SPEED_COMPUTED_MACH: return stringToNasal(c, "computed-mach");
437     case RESTRICT_DELETE: return stringToNasal(c, "delete");
438   }
439   
440   return naNil();
441 }
442
443 static const char* legGhostGetMember(naContext c, void* g, naRef field, naRef* out)
444 {
445   const char* fieldName = naStr_data(field);
446   FlightPlan::Leg* leg = (FlightPlan::Leg*) g;
447   Waypt* wpt = leg->waypoint();
448   
449   if (!strcmp(fieldName, "parents")) {
450     *out = naNewVector(c);
451     naVec_append(*out, fpLegPrototype);
452   } else if (!strcmp(fieldName, "index")) {
453     *out = naNum(leg->index());
454   } else if (!strcmp(fieldName, "alt_cstr")) {
455     *out = naNum(leg->altitudeFt());
456   } else if (!strcmp(fieldName, "alt_cstr_type")) {
457     *out = routeRestrictionToNasal(c, leg->altitudeRestriction());
458   } else if (!strcmp(fieldName, "speed_cstr")) {
459     double s = isMachRestrict(leg->speedRestriction()) ? leg->speedMach() : leg->speedKts();
460     *out = naNum(s);
461   } else if (!strcmp(fieldName, "speed_cstr_type")) {
462     *out = routeRestrictionToNasal(c, leg->speedRestriction());  
463   } else if (!strcmp(fieldName, "leg_distance")) {
464     *out = naNum(leg->distanceNm());
465   } else if (!strcmp(fieldName, "leg_bearing")) {
466     *out = naNum(leg->courseDeg());
467   } else if (!strcmp(fieldName, "distance_along_route")) {
468     *out = naNum(leg->distanceAlongRoute());
469   } else { // check for fields defined on the underlying waypoint
470     return waypointCommonGetMember(c, wpt, fieldName, out);
471   }
472   
473   return ""; // success
474 }
475
476 static void waypointGhostSetMember(naContext c, void* g, naRef field, naRef value)
477 {
478   const char* fieldName = naStr_data(field);
479   Waypt* wpt = (Waypt*) g;
480   waypointCommonSetMember(c, wpt, fieldName, value);
481 }
482
483 static void legGhostSetMember(naContext c, void* g, naRef field, naRef value)
484 {
485   const char* fieldName = naStr_data(field);
486   FlightPlan::Leg* leg = (FlightPlan::Leg*) g;
487     
488   waypointCommonSetMember(c, leg->waypoint(), fieldName, value);
489 }
490
491 static const char* flightplanGhostGetMember(naContext c, void* g, naRef field, naRef* out)
492 {
493   const char* fieldName = naStr_data(field);
494   FlightPlan* fp = (FlightPlan*) g;
495   
496   if (!strcmp(fieldName, "parents")) {
497     *out = naNewVector(c);
498     naVec_append(*out, flightplanPrototype);
499   } else if (!strcmp(fieldName, "id")) *out = stringToNasal(c, fp->ident());
500   else if (!strcmp(fieldName, "departure")) *out = ghostForAirport(c, fp->departureAirport());
501   else if (!strcmp(fieldName, "destination")) *out = ghostForAirport(c, fp->destinationAirport());
502   else if (!strcmp(fieldName, "departure_runway")) *out = ghostForRunway(c, fp->departureRunway());
503   else if (!strcmp(fieldName, "destination_runway")) *out = ghostForRunway(c, fp->destinationRunway());
504   else if (!strcmp(fieldName, "sid")) *out = ghostForProcedure(c, fp->sid());
505   else if (!strcmp(fieldName, "sid_trans")) *out = ghostForProcedure(c, fp->sidTransition());
506   else if (!strcmp(fieldName, "star")) *out = ghostForProcedure(c, fp->star());
507   else if (!strcmp(fieldName, "star_trans")) *out = ghostForProcedure(c, fp->starTransition());
508   else if (!strcmp(fieldName, "approach")) *out = ghostForProcedure(c, fp->approach());
509   else if (!strcmp(fieldName, "current")) *out = naNum(fp->currentIndex());
510   else {
511     return 0;
512   }
513   
514   return "";
515 }
516
517 static void flightplanGhostSetMember(naContext c, void* g, naRef field, naRef value)
518 {
519   const char* fieldName = naStr_data(field);
520   FlightPlan* fp = (FlightPlan*) g;
521   
522   if (!strcmp(fieldName, "id")) {
523     if (!naIsString(value)) naRuntimeError(c, "flightplan.id must be a string");
524     fp->setIdent(naStr_data(value));
525   } else if (!strcmp(fieldName, "current")) {
526     int index = value.num;
527     if ((index < 0) || (index >= fp->numLegs())) {
528       return;
529     }
530     fp->setCurrentIndex(index);
531   } else if (!strcmp(fieldName, "departure")) {
532     FGAirport* apt = airportGhost(value);
533     if (apt) {
534       fp->setDeparture(apt);
535       return;
536     }
537     
538     FGRunway* rwy = runwayGhost(value);
539     if (rwy){
540       fp->setDeparture(rwy);
541       return;
542     }
543     
544     naRuntimeError(c, "bad argument type setting departure");
545   } else if (!strcmp(fieldName, "destination")) {
546     FGAirport* apt = airportGhost(value);
547     if (apt) {
548       fp->setDestination(apt);
549       return;
550     }
551     
552     FGRunway* rwy = runwayGhost(value);
553     if (rwy){
554       fp->setDestination(rwy);
555       return;
556     }
557     
558     naRuntimeError(c, "bad argument type setting destination");
559   } else if (!strcmp(fieldName, "departure_runway")) {
560     FGRunway* rwy = runwayGhost(value);
561     if (rwy){
562       fp->setDeparture(rwy);
563       return;
564     }
565     
566     naRuntimeError(c, "bad argument type setting departure");
567   } else if (!strcmp(fieldName, "destination_runway")) {
568     FGRunway* rwy = runwayGhost(value);
569     if (rwy){
570       fp->setDestination(rwy);
571       return;
572     }
573     
574     naRuntimeError(c, "bad argument type setting departure");
575   } else if (!strcmp(fieldName, "sid")) {
576     Procedure* proc = procedureGhost(value);
577     if (proc && (proc->type() == PROCEDURE_SID)) {
578       fp->setSID((flightgear::SID*) proc);
579       return;
580     }
581     // allow a SID transition to be set, implicitly include the SID itself
582     if (proc && (proc->type() == PROCEDURE_TRANSITION)) {
583       fp->setSID((Transition*) proc);
584       return;
585     }
586         
587     if (naIsString(value)) {
588       FGAirport* apt = fp->departureAirport();
589       fp->setSID(apt->findSIDWithIdent(naStr_data(value)));
590       return;
591     }
592     
593     naRuntimeError(c, "bad argument type setting SID");
594   } else if (!strcmp(fieldName, "star")) {
595     Procedure* proc = procedureGhost(value);
596     if (proc && (proc->type() == PROCEDURE_STAR)) {
597       fp->setSTAR((STAR*) proc);
598       return;
599     }
600     
601     if (proc && (proc->type() == PROCEDURE_TRANSITION)) {
602       fp->setSTAR((Transition*) proc);
603       return;
604     }
605     
606     if (naIsString(value)) {
607       FGAirport* apt = fp->destinationAirport();
608       fp->setSTAR(apt->findSTARWithIdent(naStr_data(value)));
609       return;
610     }
611     
612     naRuntimeError(c, "bad argument type setting STAR");
613   } else if (!strcmp(fieldName, "approach")) {
614     Procedure* proc = procedureGhost(value);
615     if (proc && Approach::isApproach(proc->type())) {
616       fp->setApproach((Approach*) proc);
617       return;
618     }
619     
620     if (naIsString(value)) {
621       FGAirport* apt = fp->destinationAirport();
622       fp->setApproach(apt->findApproachWithIdent(naStr_data(value)));
623       return;
624     }
625     
626     naRuntimeError(c, "bad argument type setting approach");
627   }
628 }
629
630
631 static naRef procedureTpType(naContext c, ProcedureType ty)
632 {
633   switch (ty) {
634     case PROCEDURE_SID: return stringToNasal(c, "sid");
635     case PROCEDURE_STAR: return stringToNasal(c, "star");
636     case PROCEDURE_APPROACH_VOR: 
637     case PROCEDURE_APPROACH_ILS: 
638     case PROCEDURE_APPROACH_RNAV: 
639     case PROCEDURE_APPROACH_NDB:
640       return stringToNasal(c, "IAP");
641     default:
642       return naNil();
643   }
644 }
645
646 static naRef procedureRadioType(naContext c, ProcedureType ty)
647 {
648   switch (ty) {
649     case PROCEDURE_APPROACH_VOR: return stringToNasal(c, "VOR");
650     case PROCEDURE_APPROACH_ILS: return stringToNasal(c, "ILS");
651     case PROCEDURE_APPROACH_RNAV: return stringToNasal(c, "RNAV");
652     case PROCEDURE_APPROACH_NDB: return stringToNasal(c, "NDB");
653     default:
654       return naNil();
655   }
656 }
657
658 static const char* procedureGhostGetMember(naContext c, void* g, naRef field, naRef* out)
659 {
660   const char* fieldName = naStr_data(field);
661   Procedure* proc = (Procedure*) g;
662   
663   if (!strcmp(fieldName, "parents")) {
664     *out = naNewVector(c);
665     naVec_append(*out, procedurePrototype);
666   } else if (!strcmp(fieldName, "id")) *out = stringToNasal(c, proc->ident());
667   else if (!strcmp(fieldName, "airport")) *out = ghostForAirport(c, proc->airport());
668   else if (!strcmp(fieldName, "tp_type")) *out = procedureTpType(c, proc->type());
669   else if (!strcmp(fieldName, "radio")) *out = procedureRadioType(c, proc->type());
670   else if (!strcmp(fieldName, "runways")) {
671     *out = naNewVector(c);
672     BOOST_FOREACH(FGRunwayPtr rwy, proc->runways()) {
673       naVec_append(*out, stringToNasal(c, rwy->ident()));
674     }
675   } else if (!strcmp(fieldName, "transitions")) {
676     if ((proc->type() != PROCEDURE_SID) && (proc->type() != PROCEDURE_STAR)) {
677       *out = naNil();
678       return "";
679     }
680         
681     ArrivalDeparture* ad = static_cast<ArrivalDeparture*>(proc);
682     *out = naNewVector(c);
683     BOOST_FOREACH(string id, ad->transitionIdents()) {
684       naVec_append(*out, stringToNasal(c, id));
685     }
686   } else {
687     return 0;
688   }
689   
690   return "";
691 }
692
693 static const char* runwayGhostGetMember(naContext c, void* g, naRef field, naRef* out)
694 {
695   const char* fieldName = naStr_data(field);
696   FGRunway* rwy = (FGRunway*) g;
697   
698   if (!strcmp(fieldName, "id")) *out = stringToNasal(c, rwy->ident());
699   else if (!strcmp(fieldName, "lat")) *out = naNum(rwy->latitude());
700   else if (!strcmp(fieldName, "lon")) *out = naNum(rwy->longitude());
701   else if (!strcmp(fieldName, "heading")) *out = naNum(rwy->headingDeg());
702   else if (!strcmp(fieldName, "length")) *out = naNum(rwy->lengthM());
703   else if (!strcmp(fieldName, "width")) *out = naNum(rwy->widthM());
704   else if (!strcmp(fieldName, "threshold")) *out = naNum(rwy->displacedThresholdM());
705   else if (!strcmp(fieldName, "stopway")) *out = naNum(rwy->stopwayM());
706   else if (!strcmp(fieldName, "ils_frequency_mhz")) {
707     *out = rwy->ILS() ? naNum(rwy->ILS()->get_freq() / 100.0) : naNil();
708   } else if (!strcmp(fieldName, "ils")) {
709     *out = ghostForNavaid(c, rwy->ILS());
710   } else {
711     return 0;
712   }
713   
714   return "";
715 }
716
717 static const char* navaidGhostGetMember(naContext c, void* g, naRef field, naRef* out)
718 {
719   const char* fieldName = naStr_data(field);
720   FGNavRecord* nav = (FGNavRecord*) g;
721   
722   if (!strcmp(fieldName, "id")) *out = stringToNasal(c, nav->ident());
723   else if (!strcmp(fieldName, "name")) *out = stringToNasal(c, nav->name());
724   else if (!strcmp(fieldName, "lat")) *out = naNum(nav->get_lat());
725   else if (!strcmp(fieldName, "lon")) *out = naNum(nav->get_lon());
726   else if (!strcmp(fieldName, "elevation")) {
727     *out = naNum(nav->get_elev_ft() * SG_FEET_TO_METER);
728   } else if (!strcmp(fieldName, "type")) {
729     *out = stringToNasal(c, nav->nameForType(nav->type()));
730   } else if (!strcmp(fieldName, "frequency")) {
731     *out = naNum(nav->get_freq()); 
732   } else if (!strcmp(fieldName, "range_nm")) {
733     *out = naNum(nav->get_range()); 
734   } else if (!strcmp(fieldName, "course")) {
735     if ((nav->type() == FGPositioned::ILS) || (nav->type() == FGPositioned::LOC)) {
736       double radial = nav->get_multiuse();
737       SG_NORMALIZE_RANGE(radial, 0.0, 360.0);
738       *out = naNum(radial);
739     } else {
740       *out = naNil();
741     }
742   } else {
743     return 0;
744   }
745   
746   return "";
747 }
748
749 static const char* fixGhostGetMember(naContext c, void* g, naRef field, naRef* out)
750 {
751   const char* fieldName = naStr_data(field);
752   FGFix* fix = (FGFix*) g;
753   
754   if (!strcmp(fieldName, "id")) *out = stringToNasal(c, fix->ident());
755   else if (!strcmp(fieldName, "lat")) *out = naNum(fix->get_lat());
756   else if (!strcmp(fieldName, "lon")) *out = naNum(fix->get_lon());
757   else {
758     return 0;
759   }
760   
761   return "";
762 }
763
764 static bool hashIsCoord(naRef h)
765 {
766   naRef parents = naHash_cget(h, (char*) "parents");
767   if (!naIsVector(parents)) {
768     return false;
769   }
770   
771   return naEqual(naVec_get(parents, 0), geoCoordClass);
772 }
773
774 bool geodFromHash(naRef ref, SGGeod& result)
775 {
776   if (!naIsHash(ref)) {
777     return false;
778   }
779
780   
781 // check for manual latitude / longitude names
782   naRef lat = naHash_cget(ref, (char*) "lat");
783   naRef lon = naHash_cget(ref, (char*) "lon");
784   if (naIsNum(lat) && naIsNum(lon)) {
785     result = SGGeod::fromDeg(naNumValue(lon).num, naNumValue(lat).num);
786     return true;
787   }
788   
789   if (hashIsCoord(ref)) {
790     naRef lat = naHash_cget(ref, (char*) "_lat");
791     naRef lon = naHash_cget(ref, (char*) "_lon");
792     if (naIsNum(lat) && naIsNum(lon)) {
793       result = SGGeod::fromRad(naNumValue(lon).num, naNumValue(lat).num);
794       return true;
795     }
796   }
797     
798 // check for any synonyms?
799     // latitude + longitude?
800   
801   return false;
802 }
803
804 static int geodFromArgs(naRef* args, int offset, int argc, SGGeod& result)
805 {
806   if (offset >= argc) {
807     return 0;
808   }
809   
810   if (naIsGhost(args[offset])) {
811     naGhostType* gt = naGhost_type(args[offset]);
812     if (gt == &AirportGhostType) {
813       result = airportGhost(args[offset])->geod();
814       return 1;
815     }
816     
817     if (gt == &NavaidGhostType) {
818       result = navaidGhost(args[offset])->geod();
819       return 1;
820     }
821     
822     if (gt == &RunwayGhostType) {
823       result = runwayGhost(args[offset])->geod();
824       return 1;
825     }
826     
827     if (gt == &FixGhostType) {
828       result = fixGhost(args[offset])->geod();
829       return 1;
830     }
831     
832     if (gt == &WayptGhostType) {
833       result = wayptGhost(args[offset])->position();
834       return 1;
835     }
836   }
837   
838   if (geodFromHash(args[offset], result)) {
839     return 1;
840   }
841   
842   if (((argc - offset) >= 2) && naIsNum(args[offset]) && naIsNum(args[offset + 1])) {
843     double lat = naNumValue(args[0]).num,
844     lon = naNumValue(args[1]).num;
845     result = SGGeod::fromDeg(lon, lat);
846     return 2;
847   }
848   
849   return 0;
850 }
851
852 // Convert a cartesian point to a geodetic lat/lon/altitude.
853 static naRef f_carttogeod(naContext c, naRef me, int argc, naRef* args)
854 {
855   double lat, lon, alt, xyz[3];
856   if(argc != 3) naRuntimeError(c, "carttogeod() expects 3 arguments");
857   for(int i=0; i<3; i++)
858     xyz[i] = naNumValue(args[i]).num;
859   sgCartToGeod(xyz, &lat, &lon, &alt);
860   lat *= SG_RADIANS_TO_DEGREES;
861   lon *= SG_RADIANS_TO_DEGREES;
862   naRef vec = naNewVector(c);
863   naVec_append(vec, naNum(lat));
864   naVec_append(vec, naNum(lon));
865   naVec_append(vec, naNum(alt));
866   return vec;
867 }
868
869 // Convert a geodetic lat/lon/altitude to a cartesian point.
870 static naRef f_geodtocart(naContext c, naRef me, int argc, naRef* args)
871 {
872   if(argc != 3) naRuntimeError(c, "geodtocart() expects 3 arguments");
873   double lat = naNumValue(args[0]).num * SG_DEGREES_TO_RADIANS;
874   double lon = naNumValue(args[1]).num * SG_DEGREES_TO_RADIANS;
875   double alt = naNumValue(args[2]).num;
876   double xyz[3];
877   sgGeodToCart(lat, lon, alt, xyz);
878   naRef vec = naNewVector(c);
879   naVec_append(vec, naNum(xyz[0]));
880   naVec_append(vec, naNum(xyz[1]));
881   naVec_append(vec, naNum(xyz[2]));
882   return vec;
883 }
884
885 // For given geodetic point return array with elevation, and a material data
886 // hash, or nil if there's no information available (tile not loaded). If
887 // information about the material isn't available, then nil is returned instead
888 // of the hash.
889 static naRef f_geodinfo(naContext c, naRef me, int argc, naRef* args)
890 {
891 #define HASHSET(s,l,n) naHash_set(matdata, naStr_fromdata(naNewString(c),s,l),n)
892   if(argc < 2 || argc > 3)
893     naRuntimeError(c, "geodinfo() expects 2 or 3 arguments: lat, lon [, maxalt]");
894   double lat = naNumValue(args[0]).num;
895   double lon = naNumValue(args[1]).num;
896   double elev = argc == 3 ? naNumValue(args[2]).num : 10000;
897   const simgear::BVHMaterial *material;
898   SGGeod geod = SGGeod::fromDegM(lon, lat, elev);
899   if(!globals->get_scenery()->get_elevation_m(geod, elev, &material))
900     return naNil();
901   const SGMaterial *mat = dynamic_cast<const SGMaterial *>(material);
902   naRef vec = naNewVector(c);
903   naVec_append(vec, naNum(elev));
904   naRef matdata = naNil();
905   if(mat) {
906     matdata = naNewHash(c);
907     naRef names = naNewVector(c);
908     BOOST_FOREACH(const std::string& n, mat->get_names())
909       naVec_append(names, stringToNasal(c, n));
910       
911     HASHSET("names", 5, names);
912     HASHSET("solid", 5, naNum(mat->get_solid()));
913     HASHSET("friction_factor", 15, naNum(mat->get_friction_factor()));
914     HASHSET("rolling_friction", 16, naNum(mat->get_rolling_friction()));
915     HASHSET("load_resistance", 15, naNum(mat->get_load_resistance()));
916     HASHSET("bumpiness", 9, naNum(mat->get_bumpiness()));
917     HASHSET("light_coverage", 14, naNum(mat->get_light_coverage()));
918   }
919   naVec_append(vec, matdata);
920   return vec;
921 #undef HASHSET
922 }
923
924
925 class AirportInfoFilter : public FGAirport::AirportFilter
926 {
927 public:
928   AirportInfoFilter() : type(FGPositioned::AIRPORT) {
929     minRunwayLengthFt = fgGetDouble("/sim/navdb/min-runway-length-ft", 0.0);
930   }
931   
932   bool fromArg(naRef arg)
933   {
934     const char *s = naStr_data(arg);
935     if(!strcmp(s, "airport")) type = FGPositioned::AIRPORT;
936     else if(!strcmp(s, "seaport")) type = FGPositioned::SEAPORT;
937     else if(!strcmp(s, "heliport")) type = FGPositioned::HELIPORT;
938     else
939       return false;
940     
941     return true;
942   }
943   
944   virtual FGPositioned::Type minType() const {
945     return type;
946   }
947   
948   virtual FGPositioned::Type maxType() const {
949     return type;
950   }
951     
952   virtual bool pass(FGPositioned* aPos) const
953   {
954     FGAirport* apt = (FGAirport*) aPos;
955     if ((apt->type() == FGPositioned::AIRPORT) && 
956         !apt->hasHardRunwayOfLengthFt(minRunwayLengthFt)) 
957     {
958       return false;
959     }
960
961     return true;
962   }
963   
964   FGPositioned::Type type;
965   double minRunwayLengthFt;
966 };
967
968 // Returns data hash for particular or nearest airport of a <type>, or nil
969 // on error.
970 //
971 // airportinfo(<id>);                   e.g. "KSFO"
972 // airportinfo(<type>);                 type := ("airport"|"seaport"|"heliport")
973 // airportinfo()                        same as  airportinfo("airport")
974 // airportinfo(<lat>, <lon> [, <type>]);
975 static naRef f_airportinfo(naContext c, naRef me, int argc, naRef* args)
976 {
977   SGGeod pos = globals->get_aircraft_position();
978   FGAirport* apt = NULL;
979   
980   if(argc >= 2 && naIsNum(args[0]) && naIsNum(args[1])) {
981     pos = SGGeod::fromDeg(args[1].num, args[0].num);
982     args += 2;
983     argc -= 2;
984   }
985   
986   double maxRange = 10000.0; // expose this? or pick a smaller value?
987   
988   AirportInfoFilter filter; // defaults to airports only
989   
990   if(argc == 0) {
991     // fall through and use AIRPORT
992   } else if(argc == 1 && naIsString(args[0])) {
993     if (filter.fromArg(args[0])) {
994       // done!
995     } else {
996       // user provided an <id>, hopefully
997       apt = FGAirport::findByIdent(naStr_data(args[0]));
998       if (!apt) {
999         // return nil here, but don't raise a runtime error; this is a
1000         // legitamate way to validate an ICAO code, for example in a
1001         // dialog box or similar.
1002         return naNil();
1003       }
1004     }
1005   } else {
1006     naRuntimeError(c, "airportinfo() with invalid function arguments");
1007     return naNil();
1008   }
1009   
1010   if(!apt) {
1011     apt = FGAirport::findClosest(pos, maxRange, &filter);
1012     if(!apt) return naNil();
1013   }
1014   
1015   return ghostForAirport(c, apt);
1016 }
1017
1018 static naRef f_findAirportsWithinRange(naContext c, naRef me, int argc, naRef* args)
1019 {
1020   int argOffset = 0;
1021   SGGeod pos = globals->get_aircraft_position();
1022   argOffset += geodFromArgs(args, 0, argc, pos);
1023   
1024   if (!naIsNum(args[argOffset])) {
1025     naRuntimeError(c, "findAirportsWithinRange expected range (in nm) as arg %d", argOffset);
1026   }
1027   
1028   AirportInfoFilter filter; // defaults to airports only
1029   double rangeNm = args[argOffset++].num;
1030   if (argOffset < argc) {
1031     filter.fromArg(args[argOffset++]);
1032   }
1033   
1034   naRef r = naNewVector(c);
1035   
1036   FGPositioned::List apts = FGPositioned::findWithinRange(pos, rangeNm, &filter);
1037   FGPositioned::sortByRange(apts, pos);
1038   
1039   BOOST_FOREACH(FGPositionedRef a, apts) {
1040     FGAirport* apt = (FGAirport*) a.get();
1041     naVec_append(r, ghostForAirport(c, apt));
1042   }
1043   
1044   return r;
1045 }
1046
1047 static naRef f_findAirportsByICAO(naContext c, naRef me, int argc, naRef* args)
1048 {
1049   if (!naIsString(args[0])) {
1050     naRuntimeError(c, "findAirportsByICAO expects string as arg 0");
1051   }
1052   
1053   int argOffset = 0;
1054   string prefix(naStr_data(args[argOffset++]));
1055   AirportInfoFilter filter; // defaults to airports only
1056   if (argOffset < argc) {
1057     filter.fromArg(args[argOffset++]);
1058   }
1059   
1060   naRef r = naNewVector(c);
1061   
1062   FGPositioned::List apts = FGPositioned::findAllWithIdent(prefix, &filter, false);
1063   
1064   BOOST_FOREACH(FGPositionedRef a, apts) {
1065     FGAirport* apt = (FGAirport*) a.get();
1066     naVec_append(r, ghostForAirport(c, apt));
1067   }
1068   
1069   return r;
1070 }
1071
1072 static naRef f_airport_tower(naContext c, naRef me, int argc, naRef* args)
1073 {
1074     FGAirport* apt = airportGhost(me);
1075     if (!apt) {
1076       naRuntimeError(c, "airport.tower called on non-airport object");
1077     }
1078   
1079     // build a hash for the tower position    
1080     SGGeod towerLoc = apt->getTowerLocation();
1081     naRef tower = naNewHash(c);
1082     hashset(c, tower, "lat", naNum(towerLoc.getLatitudeDeg()));
1083     hashset(c, tower, "lon", naNum(towerLoc.getLongitudeDeg()));
1084     hashset(c, tower, "elevation", naNum(towerLoc.getElevationM()));
1085     return tower;
1086 }
1087
1088 static naRef f_airport_comms(naContext c, naRef me, int argc, naRef* args)
1089 {
1090     FGAirport* apt = airportGhost(me);
1091     if (!apt) {
1092       naRuntimeError(c, "airport.comms called on non-airport object");
1093     }
1094     naRef comms = naNewVector(c);
1095     
1096 // if we have an explicit type, return a simple vector of frequencies
1097     if (argc > 0 && naIsScalar(args[0])) {
1098         std::string commName = naStr_data(args[0]);
1099         FGPositioned::Type commType = FGPositioned::typeFromName(commName);
1100         
1101         BOOST_FOREACH(flightgear::CommStation* comm, apt->commStationsOfType(commType)) {
1102             naVec_append(comms, naNum(comm->freqMHz()));
1103         }
1104     } else {
1105 // otherwise return a vector of hashes, one for each comm station.
1106         BOOST_FOREACH(flightgear::CommStation* comm, apt->commStations()) {
1107             naRef commHash = naNewHash(c);
1108             hashset(c, commHash, "frequency", naNum(comm->freqMHz()));
1109             hashset(c, commHash, "ident", stringToNasal(c, comm->ident()));
1110             naVec_append(comms, commHash);
1111         }
1112     }
1113     
1114     return comms;
1115 }
1116
1117 static naRef f_airport_runway(naContext c, naRef me, int argc, naRef* args)
1118 {
1119   FGAirport* apt = airportGhost(me);
1120   if (!apt) {
1121     naRuntimeError(c, "airport.runway called on non-airport object");
1122   }
1123   
1124   if ((argc < 1) || !naIsString(args[0])) {
1125     naRuntimeError(c, "airport.runway expects a runway ident argument");
1126   }
1127   
1128   std::string ident(naStr_data(args[0]));
1129   boost::to_upper(ident);
1130   if (!apt->hasRunwayWithIdent(ident)) {
1131     return naNil();
1132   }
1133   
1134   return ghostForRunway(c, apt->getRunwayByIdent(ident));
1135 }
1136
1137 static naRef f_airport_sids(naContext c, naRef me, int argc, naRef* args)
1138 {
1139   FGAirport* apt = airportGhost(me);
1140   if (!apt) {
1141     naRuntimeError(c, "airport.sids called on non-airport object");
1142   }
1143   
1144   naRef sids = naNewVector(c);
1145   
1146   FGRunway* rwy = NULL;
1147   if (argc > 0 && naIsString(args[0])) {
1148     if (!apt->hasRunwayWithIdent(naStr_data(args[0]))) {
1149       return naNil();
1150     }
1151
1152     rwy = apt->getRunwayByIdent(naStr_data(args[0]));
1153   } else if (argc > 0) {
1154     rwy = runwayGhost(args[0]);
1155   }
1156
1157   if (rwy) {
1158     BOOST_FOREACH(flightgear::SID* sid, rwy->getSIDs()) {
1159       naRef procId = stringToNasal(c, sid->ident());
1160       naVec_append(sids, procId);
1161     }
1162   } else {
1163     for (unsigned int s=0; s<apt->numSIDs(); ++s) {
1164       flightgear::SID* sid = apt->getSIDByIndex(s);
1165       naRef procId = stringToNasal(c, sid->ident());
1166       naVec_append(sids, procId);
1167     }
1168   }
1169   
1170   return sids;
1171 }
1172
1173 static naRef f_airport_stars(naContext c, naRef me, int argc, naRef* args)
1174 {
1175   FGAirport* apt = airportGhost(me);
1176   if (!apt) {
1177     naRuntimeError(c, "airport.stars called on non-airport object");
1178   }
1179   
1180   naRef stars = naNewVector(c);
1181   
1182   FGRunway* rwy = NULL;
1183   if (argc > 0 && naIsString(args[0])) {
1184     if (!apt->hasRunwayWithIdent(naStr_data(args[0]))) {
1185       return naNil();
1186     }
1187         
1188     rwy = apt->getRunwayByIdent(naStr_data(args[0]));
1189   } else if (argc > 0) {
1190     rwy = runwayGhost(args[0]);
1191   }
1192   
1193   if (rwy) {
1194     BOOST_FOREACH(flightgear::STAR* s, rwy->getSTARs()) {
1195       naRef procId = stringToNasal(c, s->ident());
1196       naVec_append(stars, procId);
1197     }
1198   } else {
1199     for (unsigned int s=0; s<apt->numSTARs(); ++s) {
1200       flightgear::STAR* star = apt->getSTARByIndex(s);
1201       naRef procId = stringToNasal(c, star->ident());
1202       naVec_append(stars, procId);
1203     }
1204   }
1205   
1206   return stars;
1207 }
1208
1209 static naRef f_airport_approaches(naContext c, naRef me, int argc, naRef* args)
1210 {
1211   FGAirport* apt = airportGhost(me);
1212   if (!apt) {
1213     naRuntimeError(c, "airport.getApproachList called on non-airport object");
1214   }
1215   
1216   naRef approaches = naNewVector(c);
1217   
1218   ProcedureType ty = PROCEDURE_INVALID;
1219   if ((argc > 1) && naIsString(args[1])) {
1220     std::string u(naStr_data(args[1]));
1221     boost::to_upper(u);
1222     if (u == "NDB") ty = PROCEDURE_APPROACH_NDB;
1223     if (u == "VOR") ty = PROCEDURE_APPROACH_VOR;
1224     if (u == "ILS") ty = PROCEDURE_APPROACH_ILS;
1225     if (u == "RNAV") ty = PROCEDURE_APPROACH_RNAV;
1226   }
1227   
1228   FGRunway* rwy = NULL;
1229   if (argc > 0 && (rwy = runwayGhost(args[0]))) {
1230     // ok
1231   } else if (argc > 0 && naIsString(args[0])) {
1232     if (!apt->hasRunwayWithIdent(naStr_data(args[0]))) {
1233       return naNil();
1234     }
1235     
1236     rwy = apt->getRunwayByIdent(naStr_data(args[0]));
1237   }
1238   
1239   if (rwy) {
1240     BOOST_FOREACH(Approach* s, rwy->getApproaches()) {
1241       if ((ty != PROCEDURE_INVALID) && (s->type() != ty)) {
1242         continue;
1243       }
1244       
1245       naRef procId = stringToNasal(c, s->ident());
1246       naVec_append(approaches, procId);
1247     }
1248   } else {
1249     // no runway specified, report them all
1250     for (unsigned int s=0; s<apt->numApproaches(); ++s) {
1251       Approach* app = apt->getApproachByIndex(s);
1252       if ((ty != PROCEDURE_INVALID) && (app->type() != ty)) {
1253         continue;
1254       }
1255       
1256       naRef procId = stringToNasal(c, app->ident());
1257       naVec_append(approaches, procId);
1258     }
1259   }
1260   
1261   return approaches;
1262 }
1263
1264 static naRef f_airport_parking(naContext c, naRef me, int argc, naRef* args)
1265 {
1266   FGAirport* apt = airportGhost(me);
1267   if (!apt) {
1268     naRuntimeError(c, "airport.parking called on non-airport object");
1269   }
1270   
1271   naRef r = naNewVector(c);
1272   std::string type;
1273   bool onlyAvailable = false;
1274   
1275   if (argc > 0 && naIsString(args[0])) {
1276     type = naStr_data(args[0]);
1277   }
1278   
1279   if ((argc > 1) && naIsNum(args[1])) {
1280     onlyAvailable = (args[1].num != 0.0);
1281   }
1282   
1283   FGAirportDynamics* dynamics = apt->getDynamics();
1284   for (int i=0; i<dynamics->getNrOfParkings(); ++i) {
1285     FGParking* park = dynamics->getParking(i);
1286   // filter out based on availability and type
1287     if (onlyAvailable && !park->isAvailable()) {
1288       continue;
1289     }
1290     
1291     if (!type.empty() && (park->getType() != type)) {
1292       continue;
1293     }
1294     
1295     const SGGeod& parkLoc = park->getGeod();
1296     naRef ph = naNewHash(c);
1297     hashset(c, ph, "name", stringToNasal(c, park->getName()));
1298     hashset(c, ph, "lat", naNum(parkLoc.getLatitudeDeg()));
1299     hashset(c, ph, "lon", naNum(parkLoc.getLongitudeDeg()));
1300     hashset(c, ph, "elevation", naNum(parkLoc.getElevationM()));
1301     naVec_append(r, ph);
1302   }
1303   
1304   return r;
1305 }
1306
1307 static naRef f_airport_getSid(naContext c, naRef me, int argc, naRef* args)
1308 {
1309   FGAirport* apt = airportGhost(me);
1310   if (!apt) {
1311     naRuntimeError(c, "airport.getSid called on non-airport object");
1312   }
1313   
1314   if ((argc != 1) || !naIsString(args[0])) {
1315     naRuntimeError(c, "airport.getSid passed invalid argument");
1316   }
1317   
1318   string ident = naStr_data(args[0]);
1319   return ghostForProcedure(c, apt->findSIDWithIdent(ident));
1320 }
1321
1322 static naRef f_airport_getStar(naContext c, naRef me, int argc, naRef* args)
1323 {
1324   FGAirport* apt = airportGhost(me);
1325   if (!apt) {
1326     naRuntimeError(c, "airport.getStar called on non-airport object");
1327   }
1328   
1329   if ((argc != 1) || !naIsString(args[0])) {
1330     naRuntimeError(c, "airport.getStar passed invalid argument");
1331   }
1332   
1333   string ident = naStr_data(args[0]);
1334   return ghostForProcedure(c, apt->findSTARWithIdent(ident));
1335 }
1336
1337 static naRef f_airport_getApproach(naContext c, naRef me, int argc, naRef* args)
1338 {
1339   FGAirport* apt = airportGhost(me);
1340   if (!apt) {
1341     naRuntimeError(c, "airport.getIAP called on non-airport object");
1342   }
1343   
1344   if ((argc != 1) || !naIsString(args[0])) {
1345     naRuntimeError(c, "airport.getIAP passed invalid argument");
1346   }
1347   
1348   string ident = naStr_data(args[0]);
1349   return ghostForProcedure(c, apt->findApproachWithIdent(ident));
1350 }
1351
1352 static naRef f_airport_toString(naContext c, naRef me, int argc, naRef* args)
1353 {
1354   FGAirport* apt = airportGhost(me);
1355   if (!apt) {
1356     naRuntimeError(c, "airport.tostring called on non-airport object");
1357   }
1358   
1359   return stringToNasal(c, "an airport " + apt->ident());
1360 }
1361
1362 // Returns vector of data hash for navaid of a <type>, nil on error
1363 // navaids sorted by ascending distance 
1364 // navinfo([<lat>,<lon>],[<type>],[<id>])
1365 // lat/lon (numeric): use latitude/longitude instead of ac position
1366 // type:              ("fix"|"vor"|"ndb"|"ils"|"dme"|"tacan"|"any")
1367 // id:                (partial) id of the fix
1368 // examples:
1369 // navinfo("vor")     returns all vors
1370 // navinfo("HAM")     return all navaids who's name start with "HAM"
1371 // navinfo("vor", "HAM") return all vor who's name start with "HAM"
1372 //navinfo(34,48,"vor","HAM") return all vor who's name start with "HAM" 
1373 //                           sorted by distance relative to lat=34, lon=48
1374 static naRef f_navinfo(naContext c, naRef me, int argc, naRef* args)
1375 {
1376   SGGeod pos;
1377   
1378   if(argc >= 2 && naIsNum(args[0]) && naIsNum(args[1])) {
1379     pos = SGGeod::fromDeg(args[1].num, args[0].num);
1380     args += 2;
1381     argc -= 2;
1382   } else {
1383     pos = globals->get_aircraft_position();
1384   }
1385   
1386   FGPositioned::Type type = FGPositioned::INVALID;
1387   nav_list_type navlist;
1388   const char * id = "";
1389   
1390   if(argc > 0 && naIsString(args[0])) {
1391     const char *s = naStr_data(args[0]);
1392     if(!strcmp(s, "any")) type = FGPositioned::INVALID;
1393     else if(!strcmp(s, "fix")) type = FGPositioned::FIX;
1394     else if(!strcmp(s, "vor")) type = FGPositioned::VOR;
1395     else if(!strcmp(s, "ndb")) type = FGPositioned::NDB;
1396     else if(!strcmp(s, "ils")) type = FGPositioned::ILS;
1397     else if(!strcmp(s, "dme")) type = FGPositioned::DME;
1398     else if(!strcmp(s, "tacan")) type = FGPositioned::TACAN;
1399     else id = s; // this is an id
1400     ++args;
1401     --argc;
1402   } 
1403   
1404   if(argc > 0 && naIsString(args[0])) {
1405     if( *id != 0 ) {
1406       naRuntimeError(c, "navinfo() called with navaid id");
1407       return naNil();
1408     }
1409     id = naStr_data(args[0]);
1410     ++args;
1411     --argc;
1412   }
1413   
1414   if( argc > 0 ) {
1415     naRuntimeError(c, "navinfo() called with too many arguments");
1416     return naNil();
1417   }
1418   
1419   navlist = globals->get_navlist()->findByIdentAndFreq( pos, id, 0.0, type );
1420   
1421   naRef reply = naNewVector(c);
1422   for( nav_list_type::const_iterator it = navlist.begin(); it != navlist.end(); ++it ) {
1423     naVec_append( reply, ghostForNavaid(c, *it) );
1424   }
1425   return reply;
1426 }
1427
1428 static naRef f_findNavaidsWithinRange(naContext c, naRef me, int argc, naRef* args)
1429 {
1430   int argOffset = 0;
1431   SGGeod pos = globals->get_aircraft_position();
1432   argOffset += geodFromArgs(args, 0, argc, pos);
1433   
1434   if (!naIsNum(args[argOffset])) {
1435     naRuntimeError(c, "findNavaidsWithinRange expected range (in nm) as arg %d", argOffset);
1436   }
1437   
1438   FGPositioned::Type type = FGPositioned::INVALID;
1439   double rangeNm = args[argOffset++].num;
1440   if (argOffset < argc) {
1441     type = FGPositioned::typeFromName(naStr_data(args[argOffset]));
1442   }
1443   
1444   naRef r = naNewVector(c);
1445   FGNavList::TypeFilter filter(type);
1446   FGPositioned::List navs = FGPositioned::findWithinRange(pos, rangeNm, &filter);
1447   FGPositioned::sortByRange(navs, pos);
1448   
1449   BOOST_FOREACH(FGPositionedRef a, navs) {
1450     FGNavRecord* nav = (FGNavRecord*) a.get();
1451     naVec_append(r, ghostForNavaid(c, nav));
1452   }
1453   
1454   return r;
1455 }
1456
1457 static naRef f_findNavaidByFrequency(naContext c, naRef me, int argc, naRef* args)
1458 {
1459   int argOffset = 0;
1460   SGGeod pos = globals->get_aircraft_position();
1461   argOffset += geodFromArgs(args, 0, argc, pos);
1462   
1463   if (!naIsNum(args[argOffset])) {
1464     naRuntimeError(c, "findNavaidByFrequency expectes frequency (in Mhz) as arg %d", argOffset);
1465   }
1466   
1467   FGPositioned::Type type = FGPositioned::INVALID;
1468   double freqMhz = args[argOffset++].num;
1469   if (argOffset < argc) {
1470     type = FGPositioned::typeFromName(naStr_data(args[argOffset]));
1471   }
1472   
1473   nav_list_type navs = globals->get_navlist()->findAllByFreq(freqMhz, pos, type);
1474   if (navs.empty()) {
1475     return naNil();
1476   }
1477   
1478   return ghostForNavaid(c, navs.front().ptr());
1479 }
1480
1481 static naRef f_findNavaidsByFrequency(naContext c, naRef me, int argc, naRef* args)
1482 {
1483   int argOffset = 0;
1484   SGGeod pos = globals->get_aircraft_position();
1485   argOffset += geodFromArgs(args, 0, argc, pos);
1486   
1487   if (!naIsNum(args[argOffset])) {
1488     naRuntimeError(c, "findNavaidsByFrequency expectes frequency (in Mhz) as arg %d", argOffset);
1489   }
1490   
1491   FGPositioned::Type type = FGPositioned::INVALID;
1492   double freqMhz = args[argOffset++].num;
1493   if (argOffset < argc) {
1494     type = FGPositioned::typeFromName(naStr_data(args[argOffset]));
1495   }
1496   
1497   naRef r = naNewVector(c);
1498   nav_list_type navs = globals->get_navlist()->findAllByFreq(freqMhz, pos, type);
1499   
1500   BOOST_FOREACH(nav_rec_ptr a, navs) {
1501     naVec_append(r, ghostForNavaid(c, a.ptr()));
1502   }
1503   
1504   return r;
1505 }
1506
1507 static naRef f_findNavaidsByIdent(naContext c, naRef me, int argc, naRef* args)
1508 {
1509   int argOffset = 0;
1510   SGGeod pos = globals->get_aircraft_position();
1511   argOffset += geodFromArgs(args, 0, argc, pos);
1512   
1513   if (!naIsString(args[argOffset])) {
1514     naRuntimeError(c, "findNavaidsByIdent expectes ident string as arg %d", argOffset);
1515   }
1516   
1517   FGPositioned::Type type = FGPositioned::INVALID;
1518   string ident = naStr_data(args[argOffset++]);
1519   if (argOffset < argc) {
1520     type = FGPositioned::typeFromName(naStr_data(args[argOffset]));
1521   }
1522   
1523   naRef r = naNewVector(c);
1524   nav_list_type navs = globals->get_navlist()->findByIdentAndFreq(pos, ident, 0.0, type);
1525   
1526   BOOST_FOREACH(nav_rec_ptr a, navs) {
1527     naVec_append(r, ghostForNavaid(c, a.ptr()));
1528   }
1529   
1530   return r;
1531 }
1532
1533 static naRef f_findFixesByIdent(naContext c, naRef me, int argc, naRef* args)
1534 {
1535   int argOffset = 0;
1536   SGGeod pos = globals->get_aircraft_position();
1537   argOffset += geodFromArgs(args, 0, argc, pos);
1538   
1539   if (!naIsString(args[argOffset])) {
1540     naRuntimeError(c, "findFixesByIdent expectes ident string as arg %d", argOffset);
1541   }
1542   
1543   string ident(naStr_data(args[argOffset]));
1544   naRef r = naNewVector(c);
1545   
1546   FGPositioned::TypeFilter filter(FGPositioned::FIX);
1547   FGPositioned::List fixes = FGPositioned::findAllWithIdent(ident, &filter);
1548   FGPositioned::sortByRange(fixes, pos);
1549   
1550   BOOST_FOREACH(FGPositionedRef f, fixes) {
1551     naVec_append(r, ghostForFix(c, (FGFix*) f.ptr()));
1552   }
1553   
1554   return r;
1555 }
1556
1557 // Convert a cartesian point to a geodetic lat/lon/altitude.
1558 static naRef f_magvar(naContext c, naRef me, int argc, naRef* args)
1559 {
1560   SGGeod pos = globals->get_aircraft_position();
1561   if (argc == 0) {
1562     // fine, use aircraft position
1563   } else if (geodFromArgs(args, 0, argc, pos)) {
1564     // okay
1565   } else {
1566     naRuntimeError(c, "magvar() expects no arguments, a positioned hash or lat,lon pair");
1567   }
1568   
1569   double jd = globals->get_time_params()->getJD();
1570   double magvarDeg = sgGetMagVar(pos, jd) * SG_RADIANS_TO_DEGREES;
1571   return naNum(magvarDeg);
1572 }
1573
1574 static naRef f_courseAndDistance(naContext c, naRef me, int argc, naRef* args)
1575 {
1576     SGGeod from = globals->get_aircraft_position(), to, p;
1577     int argOffset = geodFromArgs(args, 0, argc, p);
1578     if (geodFromArgs(args, argOffset, argc, to)) {
1579       from = p; // we parsed both FROM and TO args, so first was from
1580     } else {
1581       to = p; // only parsed one arg, so FROM is current
1582     }
1583   
1584     if (argOffset == 0) {
1585         naRuntimeError(c, "invalid arguments to courseAndDistance");
1586     }
1587     
1588     double course, course2, d;
1589     SGGeodesy::inverse(from, to, course, course2, d);
1590     
1591     naRef result = naNewVector(c);
1592     naVec_append(result, naNum(course));
1593     naVec_append(result, naNum(d * SG_METER_TO_NM));
1594     return result;
1595 }
1596
1597 static naRef f_greatCircleMove(naContext c, naRef me, int argc, naRef* args)
1598 {
1599   SGGeod from = globals->get_aircraft_position(), to;
1600   int argOffset = 0;
1601   
1602   // complication - don't inerpret two doubles (as the only args)
1603   // as a lat,lon pair - only do so if we have at least three args.
1604   if (argc > 2) {
1605     argOffset = geodFromArgs(args, 0, argc, from);
1606   }
1607   
1608   if ((argOffset + 1) >= argc) {
1609     naRuntimeError(c, "isufficent arguments to greatCircleMove");
1610   }
1611   
1612   if (!naIsNum(args[argOffset]) || !naIsNum(args[argOffset+1])) {
1613     naRuntimeError(c, "invalid arguments %d and %d to greatCircleMove",
1614                    argOffset, argOffset + 1);
1615   }
1616   
1617   double course = args[argOffset].num, course2;
1618   double distanceNm = args[argOffset + 1].num;
1619   SGGeodesy::direct(from, course, distanceNm * SG_NM_TO_METER, to, course2);
1620   
1621   // return geo.Coord
1622   naRef coord = naNewHash(c);
1623   hashset(c, coord, "lat", naNum(to.getLatitudeDeg()));
1624   hashset(c, coord, "lon", naNum(to.getLongitudeDeg()));
1625   return coord;
1626 }
1627
1628 static naRef f_tilePath(naContext c, naRef me, int argc, naRef* args)
1629 {
1630     SGGeod pos = globals->get_aircraft_position();
1631     geodFromArgs(args, 0, argc, pos);
1632     SGBucket b(pos);
1633     return stringToNasal(c, b.gen_base_path());
1634 }
1635
1636 static naRef f_tileIndex(naContext c, naRef me, int argc, naRef* args)
1637 {
1638   SGGeod pos = globals->get_aircraft_position();
1639   geodFromArgs(args, 0, argc, pos);
1640   SGBucket b(pos);
1641   return naNum(b.gen_index());
1642 }
1643
1644 static naRef f_route(naContext c, naRef me, int argc, naRef* args)
1645 {
1646   if (argc == 0) {
1647     FGRouteMgr* rm = static_cast<FGRouteMgr*>(globals->get_subsystem("route-manager"));  
1648     return ghostForFlightPlan(c, rm->flightPlan());
1649   }
1650   
1651   if ((argc > 0) && naIsString(args[0])) {
1652     flightgear::FlightPlan* fp = new flightgear::FlightPlan;
1653     SGPath path(naStr_data(args[0]));
1654     if (!path.exists()) {
1655       naRuntimeError(c, "flightplan, no file at path %s", path.c_str());
1656     }
1657     
1658     if (!fp->load(path)) {
1659       SG_LOG(SG_NASAL, SG_WARN, "failed to load flight-plan from " << path);
1660       delete fp;
1661       return naNil();
1662     }
1663     
1664     return ghostForFlightPlan(c, fp);
1665   }
1666   
1667   naRuntimeError(c, "bad arguments to flightplan()");
1668   return naNil();
1669 }
1670
1671 class NasalFPDelegate : public FlightPlan::Delegate
1672 {
1673 public:
1674   NasalFPDelegate(FlightPlan* fp, FGNasalSys* sys, naRef ins) :
1675     _nasal(sys),
1676     _plan(fp),
1677     _instance(ins)
1678   {
1679     SG_LOG(SG_NASAL, SG_INFO, "created Nasal delegate for " << fp);
1680     _gcSaveKey = _nasal->gcSave(ins);
1681   }
1682   
1683   virtual ~NasalFPDelegate()
1684   {
1685     SG_LOG(SG_NASAL, SG_INFO, "destroying Nasal delegate for " << _plan);
1686     _nasal->gcRelease(_gcSaveKey);
1687   }
1688   
1689   virtual void departureChanged()
1690   {
1691     callDelegateMethod("departureChanged");
1692   }
1693   
1694   virtual void arrivalChanged()
1695   {
1696     callDelegateMethod("arrivalChanged");
1697   }
1698   
1699   virtual void waypointsChanged()
1700   {
1701     callDelegateMethod("waypointsChanged");
1702   }
1703   
1704   virtual void currentWaypointChanged()
1705   {
1706     callDelegateMethod("currentWaypointChanged");
1707   }
1708 private:
1709   
1710   void callDelegateMethod(const char* method)
1711   {
1712     naRef f;
1713     naMember_cget(_nasal->context(), _instance, method, &f);
1714     if (naIsNil(f)) {
1715       return; // no method on the delegate
1716     }
1717     
1718     naRef arg[1];
1719     arg[0] = ghostForFlightPlan(_nasal->context(), _plan);
1720     _nasal->callMethod(f, _instance, 1, arg, naNil());
1721   }
1722   
1723   FGNasalSys* _nasal;
1724   FlightPlan* _plan;
1725   naRef _instance;
1726   int _gcSaveKey;
1727 };
1728
1729 class NasalFPDelegateFactory : public FlightPlan::DelegateFactory
1730 {
1731 public:
1732   NasalFPDelegateFactory(naRef code)
1733   {
1734     _nasal = (FGNasalSys*) globals->get_subsystem("nasal");
1735     _func = code;
1736     _gcSaveKey = _nasal->gcSave(_func);
1737   }
1738   
1739   ~NasalFPDelegateFactory()
1740   {
1741     _nasal->gcRelease(_gcSaveKey);
1742   }
1743   
1744   virtual FlightPlan::Delegate* createFlightPlanDelegate(FlightPlan* fp)
1745   {
1746     naRef args[1];
1747     args[0] = ghostForFlightPlan(_nasal->context(), fp);
1748     naRef instance = _nasal->call(_func, 1, args, naNil());
1749     if (naIsNil(instance)) {
1750       return NULL;
1751     }
1752     
1753     return new NasalFPDelegate(fp, _nasal, instance);
1754   }
1755 private:
1756   FGNasalSys* _nasal;
1757   naRef _func;
1758   int _gcSaveKey;
1759 };
1760
1761 static naRef f_registerFPDelegate(naContext c, naRef me, int argc, naRef* args)
1762 {
1763   if ((argc < 1) || !naIsFunc(args[0])) {
1764     naRuntimeError(c, "non-function argument to registerFlightPlanDelegate");
1765   }
1766   
1767   NasalFPDelegateFactory* factory = new NasalFPDelegateFactory(args[0]);
1768   FlightPlan::registerDelegateFactory(factory);
1769   
1770   return naNil();
1771 }
1772
1773 static WayptRef wayptFromArg(naRef arg)
1774 {
1775   WayptRef r = wayptGhost(arg);
1776   if (r.valid()) {
1777     return r;
1778   }
1779   
1780   FGPositioned* pos = positionedGhost(arg);
1781   if (!pos) {
1782     // let's check if the arg is hash, coudl extra a geod and hence build
1783     // a simple waypoint
1784     
1785     return WayptRef();
1786   }
1787   
1788 // special-case for runways
1789   if (pos->type() == FGPositioned::RUNWAY) {
1790     return new RunwayWaypt((FGRunway*) pos, NULL);
1791   }
1792   
1793   return new NavaidWaypoint(pos, NULL);
1794 }
1795
1796 static naRef convertWayptVecToNasal(naContext c, const WayptVec& wps)
1797 {
1798   naRef result = naNewVector(c);
1799   BOOST_FOREACH(WayptRef wpt, wps) {
1800     naVec_append(result, ghostForWaypt(c, wpt.get()));
1801   }
1802   return result;
1803 }
1804
1805 static naRef f_airwaySearch(naContext c, naRef me, int argc, naRef* args)
1806 {
1807   if (argc < 2) {
1808     naRuntimeError(c, "airwaysSearch needs at least two arguments");
1809   }
1810   
1811   WayptRef start = wayptFromArg(args[0]), 
1812     end = wayptFromArg(args[1]);
1813   
1814   if (!start || !end) {
1815     SG_LOG(SG_NASAL, SG_WARN, "airwaysSearch: start or end points are invalid");
1816     return naNil();
1817   }
1818   
1819   bool highLevel = true;
1820   if ((argc > 2) && naIsString(args[2])) {
1821     if (!strcmp(naStr_data(args[2]), "lowlevel")) {
1822       highLevel = false;
1823     }
1824   }
1825   
1826   WayptVec route;
1827   if (highLevel) {
1828     Airway::highLevel()->route(start, end, route);
1829   } else {
1830     Airway::lowLevel()->route(start, end, route);
1831   }
1832   
1833   return convertWayptVecToNasal(c, route);
1834 }
1835
1836 static naRef f_createWP(naContext c, naRef me, int argc, naRef* args)
1837 {
1838   SGGeod pos;
1839   int argOffset = geodFromArgs(args, 0, argc, pos);
1840   
1841   if (((argc - argOffset) < 1) || !naIsString(args[argOffset])) {
1842     naRuntimeError(c, "createWP: no identifier supplied");
1843   }
1844     
1845   string ident = naStr_data(args[argOffset++]);
1846   WayptRef wpt = new BasicWaypt(pos, ident, NULL);
1847   
1848 // set waypt flags - approach, departure, pseudo, etc
1849   if (argc > argOffset) {
1850     WayptFlag f = wayptFlagFromString(naStr_data(args[argOffset++]));
1851     wpt->setFlag(f);
1852   }
1853   
1854   return ghostForWaypt(c, wpt);
1855 }
1856
1857 static naRef f_createWPFrom(naContext c, naRef me, int argc, naRef* args)
1858 {
1859   if (argc < 1) {
1860     naRuntimeError(c, "createWPFrom: need at least one argument");
1861   }
1862   
1863   FGPositioned* positioned = positionedGhost(args[0]);
1864   if (!positioned) {
1865     naRuntimeError(c, "createWPFrom: couldn;t convert arg[0] to FGPositioned");
1866   }
1867   
1868   WayptRef wpt;
1869   if (positioned->type() == FGPositioned::RUNWAY) {
1870     wpt = new RunwayWaypt((FGRunway*) positioned, NULL);
1871   } else {
1872     wpt = new NavaidWaypoint(positioned, NULL);
1873   }
1874
1875   // set waypt flags - approach, departure, pseudo, etc
1876   if (argc > 1) {
1877     WayptFlag f = wayptFlagFromString(naStr_data(args[1]));
1878     wpt->setFlag(f);
1879   }
1880   
1881   return ghostForWaypt(c, wpt);
1882 }
1883
1884 static naRef f_flightplan_getWP(naContext c, naRef me, int argc, naRef* args)
1885 {
1886   FlightPlan* fp = flightplanGhost(me);
1887   if (!fp) {
1888     naRuntimeError(c, "flightplan.getWP called on non-flightplan object");
1889   }
1890
1891   int index;
1892   if (argc == 0) {
1893     index = fp->currentIndex();
1894   } else {
1895     index = (int) naNumValue(args[0]).num;
1896   }
1897   
1898   if ((index < 0) || (index >= fp->numLegs())) {
1899     return naNil();
1900   }
1901   
1902   return ghostForLeg(c, fp->legAtIndex(index));
1903 }
1904
1905 static naRef f_flightplan_currentWP(naContext c, naRef me, int argc, naRef* args)
1906 {
1907   FlightPlan* fp = flightplanGhost(me);
1908   if (!fp) {
1909     naRuntimeError(c, "flightplan.currentWP called on non-flightplan object");
1910   }
1911   return ghostForLeg(c, fp->currentLeg());
1912 }
1913
1914 static naRef f_flightplan_nextWP(naContext c, naRef me, int argc, naRef* args)
1915 {
1916   FlightPlan* fp = flightplanGhost(me);
1917   if (!fp) {
1918     naRuntimeError(c, "flightplan.nextWP called on non-flightplan object");
1919   }
1920   return ghostForLeg(c, fp->nextLeg());
1921 }
1922
1923 static naRef f_flightplan_numWaypoints(naContext c, naRef me, int argc, naRef* args)
1924 {
1925   FlightPlan* fp = flightplanGhost(me);
1926   if (!fp) {
1927     naRuntimeError(c, "flightplan.numWaypoints called on non-flightplan object");
1928   }
1929   return naNum(fp->numLegs());
1930 }
1931
1932 static naRef f_flightplan_appendWP(naContext c, naRef me, int argc, naRef* args)
1933 {
1934   FlightPlan* fp = flightplanGhost(me);
1935   if (!fp) {
1936     naRuntimeError(c, "flightplan.appendWP called on non-flightplan object");
1937   }
1938   
1939   WayptRef wp = wayptGhost(args[0]);
1940   int index = fp->numLegs();
1941   fp->insertWayptAtIndex(wp.get(), index);
1942   return naNum(index);
1943 }
1944
1945 static naRef f_flightplan_insertWP(naContext c, naRef me, int argc, naRef* args)
1946 {
1947   FlightPlan* fp = flightplanGhost(me);
1948   if (!fp) {
1949     naRuntimeError(c, "flightplan.insertWP called on non-flightplan object");
1950   }
1951   
1952   WayptRef wp = wayptGhost(args[0]);
1953   int index = -1; // append
1954   if ((argc > 1) && naIsNum(args[1])) {
1955     index = (int) args[1].num;
1956   }
1957   
1958   fp->insertWayptAtIndex(wp.get(), index);
1959   return naNil();
1960 }
1961
1962 static naRef f_flightplan_insertWPAfter(naContext c, naRef me, int argc, naRef* args)
1963 {
1964   FlightPlan* fp = flightplanGhost(me);
1965   if (!fp) {
1966     naRuntimeError(c, "flightplan.insertWPAfter called on non-flightplan object");
1967   }
1968   
1969   WayptRef wp = wayptGhost(args[0]);
1970   int index = -1; // append
1971   if ((argc > 1) && naIsNum(args[1])) {
1972     index = (int) args[1].num;
1973   }
1974   
1975   fp->insertWayptAtIndex(wp.get(), index + 1);
1976   return naNil();
1977 }
1978
1979 static naRef f_flightplan_insertWaypoints(naContext c, naRef me, int argc, naRef* args)
1980 {
1981   FlightPlan* fp = flightplanGhost(me);
1982   if (!fp) {
1983     naRuntimeError(c, "flightplan.insertWaypoints called on non-flightplan object");
1984   }
1985   
1986   WayptVec wps;
1987   if (!naIsVector(args[0])) {
1988     naRuntimeError(c, "flightplan.insertWaypoints expects vector as first arg");
1989   }
1990
1991   int count = naVec_size(args[0]);
1992   for (int i=0; i<count; ++i) {
1993     Waypt* wp = wayptGhost(naVec_get(args[0], i));
1994     if (wp) {
1995       wps.push_back(wp);
1996     }
1997   }
1998   
1999   int index = -1; // append
2000   if ((argc > 1) && naIsNum(args[1])) {
2001     index = (int) args[1].num;
2002   }
2003
2004   fp->insertWayptsAtIndex(wps, index);
2005   return naNil();
2006 }
2007
2008 static naRef f_flightplan_deleteWP(naContext c, naRef me, int argc, naRef* args)
2009 {
2010   FlightPlan* fp = flightplanGhost(me);
2011   if (!fp) {
2012     naRuntimeError(c, "flightplan.deleteWP called on non-flightplan object");
2013   }
2014   
2015   if ((argc < 1) || !naIsNum(args[0])) {
2016     naRuntimeError(c, "bad argument to flightplan.deleteWP");
2017   }
2018   
2019   int index = (int) args[0].num;
2020   fp->deleteIndex(index);
2021   return naNil();
2022 }
2023
2024 static naRef f_flightplan_clearPlan(naContext c, naRef me, int argc, naRef* args)
2025 {
2026   FlightPlan* fp = flightplanGhost(me);
2027   if (!fp) {
2028     naRuntimeError(c, "flightplan.clearPlan called on non-flightplan object");
2029   }
2030   
2031   fp->clear();
2032   return naNil();
2033 }
2034
2035 static naRef f_flightplan_clearWPType(naContext c, naRef me, int argc, naRef* args)
2036 {
2037   FlightPlan* fp = flightplanGhost(me);
2038   if (!fp) {
2039     naRuntimeError(c, "flightplan.clearWPType called on non-flightplan object");
2040   }
2041   
2042   if (argc < 1) {
2043     naRuntimeError(c, "insufficent args to flightplan.clearWPType");
2044   }
2045   
2046   WayptFlag flag = wayptFlagFromString(naStr_data(args[0]));
2047   fp->clearWayptsWithFlag(flag);
2048   return naNil();
2049 }
2050
2051 static naRef f_flightplan_clone(naContext c, naRef me, int argc, naRef* args)
2052 {
2053   FlightPlan* fp = flightplanGhost(me);
2054   if (!fp) {
2055     naRuntimeError(c, "flightplan.clone called on non-flightplan object");
2056   }
2057   
2058   return ghostForFlightPlan(c, fp->clone());
2059 }
2060
2061 static naRef f_leg_setSpeed(naContext c, naRef me, int argc, naRef* args)
2062 {
2063   FlightPlan::Leg* leg = fpLegGhost(me);
2064   if (!leg) {
2065     naRuntimeError(c, "leg.setSpeed called on non-flightplan-leg object");
2066   }
2067   
2068   if (argc < 2) {
2069     naRuntimeError(c, "bad arguments to leg.setSpeed");
2070   }
2071   
2072   RouteRestriction rr = routeRestrictionFromString(naStr_data(args[1]));
2073   leg->setSpeed(rr, args[0].num);
2074   return naNil();
2075 }
2076
2077 static naRef f_leg_setAltitude(naContext c, naRef me, int argc, naRef* args)
2078 {
2079   FlightPlan::Leg* leg = fpLegGhost(me);
2080   if (!leg) {
2081     naRuntimeError(c, "leg.setAltitude called on non-flightplan-leg object");
2082   }
2083   
2084   if (argc < 2) {
2085     naRuntimeError(c, "bad arguments to leg.setAltitude");
2086   }
2087   
2088   RouteRestriction rr = routeRestrictionFromString(naStr_data(args[1]));
2089   leg->setAltitude(rr, args[0].num);
2090   return naNil();
2091 }
2092
2093 static naRef f_waypoint_navaid(naContext c, naRef me, int argc, naRef* args)
2094 {
2095   flightgear::Waypt* w = wayptGhost(me);
2096   if (!w) {
2097     naRuntimeError(c, "waypoint.navaid called on non-waypoint object");
2098   }
2099   
2100   FGPositioned* pos = w->source();
2101   if (!pos) {
2102     return naNil();
2103   }
2104   
2105   switch (pos->type()) {
2106   case FGPositioned::VOR:
2107   case FGPositioned::NDB:
2108   case FGPositioned::ILS:
2109   case FGPositioned::LOC:
2110   case FGPositioned::GS:
2111   case FGPositioned::DME:
2112   case FGPositioned::TACAN: {
2113     FGNavRecord* nav = (FGNavRecord*) pos;
2114     return ghostForNavaid(c, nav);
2115   }
2116       
2117   default:
2118     return naNil();
2119   }
2120 }
2121
2122 static naRef f_waypoint_airport(naContext c, naRef me, int argc, naRef* args)
2123 {
2124   flightgear::Waypt* w = wayptGhost(me);
2125   if (!w) {
2126     naRuntimeError(c, "waypoint.navaid called on non-waypoint object");
2127   }
2128   
2129   FGPositioned* pos = w->source();
2130   if (!pos || FGAirport::isAirportType(pos)) {
2131     return naNil();
2132   }
2133   
2134   return ghostForAirport(c, (FGAirport*) pos);
2135 }
2136
2137 static naRef f_waypoint_runway(naContext c, naRef me, int argc, naRef* args)
2138 {
2139   flightgear::Waypt* w = wayptGhost(me);
2140   if (!w) {
2141     naRuntimeError(c, "waypoint.navaid called on non-waypoint object");
2142   }
2143   
2144   FGPositioned* pos = w->source();
2145   if (!pos || (pos->type() != FGPositioned::RUNWAY)) {
2146     return naNil();
2147   }
2148   
2149   return ghostForRunway(c, (FGRunway*) pos);
2150 }
2151
2152 static naRef f_procedure_transition(naContext c, naRef me, int argc, naRef* args)
2153 {
2154   Procedure* proc = procedureGhost(me);
2155   if (!proc) {
2156     naRuntimeError(c, "procedure.transition called on non-procedure object");
2157   }
2158   
2159   if ((proc->type() != PROCEDURE_SID) && (proc->type() != PROCEDURE_STAR)) {
2160     naRuntimeError(c, "procedure.transition called on non-SID or -STAR");
2161   }
2162   
2163   ArrivalDeparture* ad = (ArrivalDeparture*) proc;
2164   Transition* trans = ad->findTransitionByName(naStr_data(args[0]));
2165   
2166   return ghostForProcedure(c, trans);
2167 }
2168
2169 static naRef f_procedure_route(naContext c, naRef me, int argc, naRef* args)
2170 {
2171   Procedure* proc = procedureGhost(me);
2172   if (!proc) {
2173     naRuntimeError(c, "procedure.route called on non-procedure object");
2174   }
2175   
2176 // wrapping up tow different routines here - approach routing from the IAF
2177 // to the associated runway, and SID/STAR routing via an enroute transition
2178 // and possibly a runway transition or not.
2179   if (Approach::isApproach(proc->type())) {
2180     WayptRef iaf;
2181     if (argc > 0) {
2182       iaf = wayptFromArg(args[0]);
2183     }
2184     
2185     WayptVec r;
2186     Approach* app = (Approach*) proc;
2187     if (!app->route(iaf, r)) {
2188       SG_LOG(SG_NASAL, SG_WARN, "procedure.route failed for Approach somehow");
2189       return naNil();
2190     }
2191     
2192     return convertWayptVecToNasal(c, r);
2193   } else if ((proc->type() != PROCEDURE_SID) && (proc->type() != PROCEDURE_STAR)) {
2194     naRuntimeError(c, "procedure.route called on unsuitable procedure type");
2195   }
2196   
2197   int argOffset = 0;
2198   FGRunway* rwy = runwayGhost(args[0]);
2199   if (rwy) ++argOffset;
2200   
2201   ArrivalDeparture* ad = (ArrivalDeparture*) proc;
2202   Transition* trans = NULL;
2203   if (argOffset < argc) {
2204     trans = (Transition*) procedureGhost(args[argOffset]);
2205   }
2206   
2207   // note either runway or trans may be NULL - that's ok
2208   WayptVec r;
2209   if (!ad->route(rwy, trans, r)) {
2210     SG_LOG(SG_NASAL, SG_WARN, "prcoedure.route failed for ArrvialDeparture somehow");
2211     return naNil();
2212   }
2213   
2214   return convertWayptVecToNasal(c, r);
2215 }
2216
2217
2218 // Table of extension functions.  Terminate with zeros.
2219 static struct { const char* name; naCFunction func; } funcs[] = {
2220   { "carttogeod", f_carttogeod },
2221   { "geodtocart", f_geodtocart },
2222   { "geodinfo", f_geodinfo },
2223   { "airportinfo", f_airportinfo },
2224   { "findAirportsWithinRange", f_findAirportsWithinRange },
2225   { "findAirportsByICAO", f_findAirportsByICAO },
2226   { "navinfo", f_navinfo },
2227   { "findNavaidsWithinRange", f_findNavaidsWithinRange },
2228   { "findNavaidByFrequency", f_findNavaidByFrequency },
2229   { "findNavaidsByFrequency", f_findNavaidsByFrequency },
2230   { "findNavaidsByID", f_findNavaidsByIdent },
2231   { "findFixesByID", f_findFixesByIdent },
2232   { "flightplan", f_route },
2233   { "registerFlightPlanDelegate", f_registerFPDelegate },
2234   { "createWP", f_createWP },
2235   { "createWPFrom", f_createWPFrom },
2236   { "airwaysRoute", f_airwaySearch },
2237   { "magvar", f_magvar },
2238   { "courseAndDistance", f_courseAndDistance },
2239   { "greatCircleMove", f_greatCircleMove },
2240   { "tileIndex", f_tileIndex },
2241   { "tilePath", f_tilePath },
2242   { 0, 0 }
2243 };
2244
2245
2246 naRef initNasalPositioned(naRef globals, naContext c, naRef gcSave)
2247 {
2248     airportPrototype = naNewHash(c);
2249     hashset(c, gcSave, "airportProto", airportPrototype);
2250   
2251     hashset(c, airportPrototype, "runway", naNewFunc(c, naNewCCode(c, f_airport_runway)));
2252     hashset(c, airportPrototype, "tower", naNewFunc(c, naNewCCode(c, f_airport_tower)));
2253     hashset(c, airportPrototype, "comms", naNewFunc(c, naNewCCode(c, f_airport_comms)));
2254     hashset(c, airportPrototype, "sids", naNewFunc(c, naNewCCode(c, f_airport_sids)));
2255     hashset(c, airportPrototype, "stars", naNewFunc(c, naNewCCode(c, f_airport_stars)));
2256     hashset(c, airportPrototype, "getApproachList", naNewFunc(c, naNewCCode(c, f_airport_approaches)));
2257     hashset(c, airportPrototype, "parking", naNewFunc(c, naNewCCode(c, f_airport_parking)));
2258     hashset(c, airportPrototype, "getSid", naNewFunc(c, naNewCCode(c, f_airport_getSid)));
2259     hashset(c, airportPrototype, "getStar", naNewFunc(c, naNewCCode(c, f_airport_getStar)));
2260     hashset(c, airportPrototype, "getIAP", naNewFunc(c, naNewCCode(c, f_airport_getApproach)));
2261     hashset(c, airportPrototype, "tostring", naNewFunc(c, naNewCCode(c, f_airport_toString)));
2262   
2263     flightplanPrototype = naNewHash(c);
2264     hashset(c, gcSave, "flightplanProto", flightplanPrototype);
2265       
2266     hashset(c, flightplanPrototype, "getWP", naNewFunc(c, naNewCCode(c, f_flightplan_getWP)));
2267     hashset(c, flightplanPrototype, "currentWP", naNewFunc(c, naNewCCode(c, f_flightplan_currentWP))); 
2268     hashset(c, flightplanPrototype, "nextWP", naNewFunc(c, naNewCCode(c, f_flightplan_nextWP))); 
2269     hashset(c, flightplanPrototype, "getPlanSize", naNewFunc(c, naNewCCode(c, f_flightplan_numWaypoints)));
2270     hashset(c, flightplanPrototype, "appendWP", naNewFunc(c, naNewCCode(c, f_flightplan_appendWP))); 
2271     hashset(c, flightplanPrototype, "insertWP", naNewFunc(c, naNewCCode(c, f_flightplan_insertWP))); 
2272     hashset(c, flightplanPrototype, "deleteWP", naNewFunc(c, naNewCCode(c, f_flightplan_deleteWP))); 
2273     hashset(c, flightplanPrototype, "insertWPAfter", naNewFunc(c, naNewCCode(c, f_flightplan_insertWPAfter))); 
2274     hashset(c, flightplanPrototype, "insertWaypoints", naNewFunc(c, naNewCCode(c, f_flightplan_insertWaypoints))); 
2275     hashset(c, flightplanPrototype, "cleanPlan", naNewFunc(c, naNewCCode(c, f_flightplan_clearPlan))); 
2276     hashset(c, flightplanPrototype, "clearWPType", naNewFunc(c, naNewCCode(c, f_flightplan_clearWPType))); 
2277     hashset(c, flightplanPrototype, "clone", naNewFunc(c, naNewCCode(c, f_flightplan_clone))); 
2278   
2279     waypointPrototype = naNewHash(c);
2280     hashset(c, gcSave, "wayptProto", waypointPrototype);
2281     
2282     hashset(c, waypointPrototype, "navaid", naNewFunc(c, naNewCCode(c, f_waypoint_navaid)));
2283     hashset(c, waypointPrototype, "runway", naNewFunc(c, naNewCCode(c, f_waypoint_runway)));
2284     hashset(c, waypointPrototype, "airport", naNewFunc(c, naNewCCode(c, f_waypoint_airport)));
2285   
2286     procedurePrototype = naNewHash(c);
2287     hashset(c, gcSave, "procedureProto", procedurePrototype);
2288     hashset(c, procedurePrototype, "transition", naNewFunc(c, naNewCCode(c, f_procedure_transition)));
2289     hashset(c, procedurePrototype, "route", naNewFunc(c, naNewCCode(c, f_procedure_route)));
2290   
2291     fpLegPrototype = naNewHash(c);
2292     hashset(c, gcSave, "fpLegProto", fpLegPrototype);
2293     hashset(c, fpLegPrototype, "setSpeed", naNewFunc(c, naNewCCode(c, f_leg_setSpeed)));
2294     hashset(c, fpLegPrototype, "setAltitude", naNewFunc(c, naNewCCode(c, f_leg_setAltitude)));
2295   
2296     for(int i=0; funcs[i].name; i++) {
2297       hashset(c, globals, funcs[i].name,
2298       naNewFunc(c, naNewCCode(c, funcs[i].func)));
2299     }
2300   
2301   return naNil();
2302 }
2303
2304 void postinitNasalPositioned(naRef globals, naContext c)
2305 {
2306   naRef geoModule = naHash_cget(globals, (char*) "geo");
2307   if (naIsNil(geoModule)) {
2308     SG_LOG(SG_GENERAL, SG_WARN, "postinitNasalPositioned: geo.nas not loaded");
2309     return;
2310   }
2311   
2312   geoCoordClass = naHash_cget(geoModule, (char*) "Coord");
2313 }
2314
2315