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