Debian Codegraph @

src/Scripting/NasalPositioned.cxx

raw symbols ◀ ▶ SCIP
1 Debian patch touch this file
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 #include "config.h"
22
23 #include <cstring>
24 #include <algorithm>
25
26 #include "NasalPositioned.hxx"
27
28 #include <simgear/sg_inlines.h>
29 #include <simgear/scene/material/mat.hxx>
30 #include <simgear/magvar/magvar.hxx>
31 #include <simgear/timing/sg_time.hxx>
32 #include <simgear/bucket/newbucket.hxx>
33
34 #include <Airports/runways.hxx>
35 #include <Airports/airport.hxx>
36 #include <Airports/dynamics.hxx>
37 #include <Airports/parking.hxx>
38 #include <Scripting/NasalSys.hxx>
39 #include <Navaids/navlist.hxx>
40 #include <Navaids/procedure.hxx>
41 #include <Main/globals.hxx>
42 #include <Main/fg_props.hxx>
43 #include <Main/util.hxx>
44 #include <Scenery/scenery.hxx>
45 #include <ATC/CommStation.hxx>
46 #include <Navaids/fix.hxx>
47 #include <Autopilot/route_mgr.hxx>
48 #include <Navaids/NavDataCache.hxx>
49
50 #include "NasalFlightPlan.hxx"
51
52 using namespace flightgear;
53
54 static void positionedGhostDestroy(void* g);
55
56 ///static naGhostType PositionedGhostType = { positionedGhostDestroy, "positioned", nullptr, nullptr };
57
58 static const char* airportGhostGetMember(naContext c, void* g, naRef field, naRef* out);
59 static naGhostType AirportGhostType = { positionedGhostDestroy, "airport", airportGhostGetMember, nullptr };
60
61 static const char* navaidGhostGetMember(naContext c, void* g, naRef field, naRef* out);
62 static naGhostType NavaidGhostType = { positionedGhostDestroy, "navaid", navaidGhostGetMember, nullptr };
63
64 static const char* runwayGhostGetMember(naContext c, void* g, naRef field, naRef* out);
65 static naGhostType RunwayGhostType = { positionedGhostDestroy, "runway", runwayGhostGetMember, nullptr };
66 static naGhostType HelipadGhostType = { positionedGhostDestroy, "helipad", runwayGhostGetMember, nullptr };
67 static naGhostType TaxiwayGhostType = { positionedGhostDestroy, "taxiway", runwayGhostGetMember, nullptr };
68
69 static const char* fixGhostGetMember(naContext c, void* g, naRef field, naRef* out);
70 static naGhostType FixGhostType = { positionedGhostDestroy, "fix", fixGhostGetMember, nullptr };
71
72 static const char* commGhostGetMember(naContext c, void* g, naRef field, naRef* out);
73 static naGhostType CommGhostType = {positionedGhostDestroy, "comm", commGhostGetMember, nullptr};
74
75 static const char* poiGhostGetMember(naContext c, void* g, naRef field, naRef* out);
76 static naGhostType POIGhostType = {positionedGhostDestroy, "poi", poiGhostGetMember, nullptr};
77
78 static void hashset(naContext c, naRef hash, const char* key, naRef val)
79 {
80 naRef s = naNewString(c);
81 naStr_fromdata(s, (char*)key, strlen(key));
82 naHash_set(hash, s, val);
83 }
84
85 static naRef stringToNasal(naContext c, const std::string& s)
86 {
87 return naStr_fromdata(naNewString(c),
88 const_cast<char *>(s.c_str()),
89 s.length());
90 }
91
92 FGPositioned* positionedGhost(naRef r)
93 {
94 if ((naGhost_type(r) == &AirportGhostType) ||
95 (naGhost_type(r) == &NavaidGhostType) ||
96 (naGhost_type(r) == &RunwayGhostType) ||
97 (naGhost_type(r) == &FixGhostType) ||
98 (naGhost_type(r) == &FixGhostType) ||
99 (naGhost_type(r) == &POIGhostType)) {
100 return (FGPositioned*) naGhost_ptr(r);
101 }
102
103 return 0;
104 }
105
106 FGAirport* airportGhost(naRef r)
107 {
108 if (naGhost_type(r) == &AirportGhostType)
109 return (FGAirport*) naGhost_ptr(r);
110 return 0;
111 }
112
113 static FGNavRecord* navaidGhost(naRef r)
114 {
115 if (naGhost_type(r) == &NavaidGhostType)
116 return (FGNavRecord*) naGhost_ptr(r);
117 return 0;
118 }
119
120 FGRunway* runwayGhost(naRef r)
121 {
122 if (naGhost_type(r) == &RunwayGhostType)
123 return (FGRunway*) naGhost_ptr(r);
124 return 0;
125 }
126
127 static FGTaxiway* taxiwayGhost(naRef r)
128 {
129 if (naGhost_type(r) == &TaxiwayGhostType)
130 return (FGTaxiway*) naGhost_ptr(r);
131 return 0;
132 }
133
134 static FGFix* fixGhost(naRef r)
135 {
136 if (naGhost_type(r) == &FixGhostType)
137 return (FGFix*) naGhost_ptr(r);
138 return 0;
139 }
140
141 #if 0
142 static flightgear::CommStation* commGhost(naRef r)
143 {
144 if (naGhost_type(r) == &CommGhostType)
145 return (flightgear::CommStation*)naGhost_ptr(r);
146 return nullptr;
147 }
148 #endif
149
150 static POI* poiGhost(naRef r)
151 {
152 if (naGhost_type(r) == &POIGhostType)
153 return (POI*)naGhost_ptr(r);
154 return nullptr;
155 }
156
157
158 static void positionedGhostDestroy(void* g)
159 {
160 FGPositioned* pos = (FGPositioned*)g;
161 if (!FGPositioned::put(pos)) // unref
162 delete pos;
163 }
164
165
166 static naRef airportPrototype;
167 static naRef geoCoordClass;
168 static naRef waypointPrototype;
169
170 naRef ghostForAirport(naContext c, const FGAirport* apt)
171 {
172 if (!apt) {
173 return naNil();
174 }
175
176 FGPositioned::get(apt); // take a ref
177 return naNewGhost2(c, &AirportGhostType, (void*) apt);
178 }
179
180 naRef ghostForNavaid(naContext c, const FGNavRecord* n)
181 {
182 if (!n) {
183 return naNil();
184 }
185
186 FGPositioned::get(n); // take a ref
187 return naNewGhost2(c, &NavaidGhostType, (void*) n);
188 }
189
190 naRef ghostForRunway(naContext c, const FGRunway* r)
191 {
192 if (!r) {
193 return naNil();
194 }
195
196 FGPositioned::get(r); // take a ref
197 return naNewGhost2(c, &RunwayGhostType, (void*) r);
198 }
199
200 naRef ghostForHelipad(naContext c, const FGHelipad* r)
201 {
202 if (!r) {
203 return naNil();
204 }
205
206 FGPositioned::get(r); // take a ref
207 return naNewGhost2(c, &HelipadGhostType, (void*) r);
208 }
209
210 naRef ghostForTaxiway(naContext c, const FGTaxiway* r)
211 {
212 if (!r) {
213 return naNil();
214 }
215
216 FGPositioned::get(r); // take a ref
217 return naNewGhost2(c, &TaxiwayGhostType, (void*) r);
218 }
219
220 naRef ghostForFix(naContext c, const FGFix* r)
221 {
222 if (!r) {
223 return naNil();
224 }
225
226 FGPositioned::get(r); // take a ref
227 return naNewGhost2(c, &FixGhostType, (void*) r);
228 }
229
230 naRef ghostForComm(naContext c, const flightgear::CommStation* comm)
231 {
232 if (!c) {
233 return naNil();
234 }
235
236 FGPositioned::get(comm); // take a ref
237 return naNewGhost2(c, &CommGhostType, (void*)comm);
238 }
239
240 naRef ghostForPOI(naContext c, const POI* r)
241 {
242 if (!r) {
243 return naNil();
244 }
245
246 FGPositioned::get(r); // take a ref
247 return naNewGhost2(c, &POIGhostType, (void*)r);
248 }
249
250 naRef ghostForPositioned(naContext c, FGPositionedRef pos)
251 {
252 if (!pos) {
253 return naNil();
254 }
255
256 switch (pos->type()) {
257 case FGPositioned::VOR:
258 case FGPositioned::NDB:
259 case FGPositioned::TACAN:
260 case FGPositioned::DME:
261 case FGPositioned::ILS:
262 return ghostForNavaid(c, fgpositioned_cast<FGNavRecord>(pos));
263 case FGPositioned::FIX:
264 return ghostForFix(c, fgpositioned_cast<FGFix>(pos));
265 case FGPositioned::HELIPAD:
266 return ghostForHelipad(c, fgpositioned_cast<FGHelipad>(pos));
267 case FGPositioned::RUNWAY:
268 return ghostForRunway(c, fgpositioned_cast<FGRunway>(pos));
269 case FGPositioned::FREQ_APP_DEP:
270 case FGPositioned::FREQ_AWOS:
271 case FGPositioned::FREQ_GROUND:
272 case FGPositioned::FREQ_TOWER:
273 case FGPositioned::FREQ_ATIS:
274 case FGPositioned::FREQ_CLEARANCE:
275 case FGPositioned::FREQ_UNICOM:
276 case FGPositioned::FREQ_ENROUTE:
277 return ghostForComm(c, fgpositioned_cast<flightgear::CommStation>(pos));
278
279 case FGPositioned::WAYPOINT:
280 case FGPositioned::CITY:
281 case FGPositioned::COUNTRY:
282 case FGPositioned::TOWN:
283 case FGPositioned::VISUAL_REPORTING_POINT:
284 case FGPositioned::VILLAGE:
285 return ghostForPOI(c, fgpositioned_cast<POI>(pos));
286
287 default:
288 SG_LOG(SG_NASAL, SG_DEV_ALERT, "Type lacks Nasal ghost mapping:" << pos->typeString());
289 return naNil();
290 }
291 }
292
293 static const char* airportGhostGetMember(naContext c, void* g, naRef field, naRef* out)
294 {
295 const char* fieldName = naStr_data(field);
296 FGAirport* apt = (FGAirport*) g;
297
298 if (!strcmp(fieldName, "parents")) {
299 *out = naNewVector(c);
300 naVec_append(*out, airportPrototype);
301 } else if (!strcmp(fieldName, "id")) *out = stringToNasal(c, apt->ident());
302 else if (!strcmp(fieldName, "name")) *out = stringToNasal(c, apt->name());
303 else if (!strcmp(fieldName, "lat")) *out = naNum(apt->getLatitude());
304 else if (!strcmp(fieldName, "lon")) *out = naNum(apt->getLongitude());
305 else if (!strcmp(fieldName, "elevation")) {
306 *out = naNum(apt->getElevation() * SG_FEET_TO_METER);
307 } else if (!strcmp(fieldName, "has_metar")) {
308 *out = naNum(apt->getMetar());
309 } else if (!strcmp(fieldName, "runways")) {
310 *out = naNewHash(c);
311 double minLengthFt = fgGetDouble("/sim/navdb/min-runway-length-ft");
312 for(unsigned int r=0; r<apt->numRunways(); ++r) {
313 FGRunway* rwy(apt->getRunwayByIndex(r));
314 // ignore unusably short runways
315 if (rwy->lengthFt() < minLengthFt) {
316 continue;
317 }
318 naRef rwyid = stringToNasal(c, rwy->ident());
319 naRef rwydata = ghostForRunway(c, rwy);
320 naHash_set(*out, rwyid, rwydata);
321 }
322 } else if (!strcmp(fieldName, "helipads")) {
323 *out = naNewHash(c);
324
325 for(unsigned int r=0; r<apt->numHelipads(); ++r) {
326 FGHelipad* hp(apt->getHelipadByIndex(r));
327
328 naRef rwyid = stringToNasal(c, hp->ident());
329 naRef rwydata = ghostForHelipad(c, hp);
330 naHash_set(*out, rwyid, rwydata);
331 }
332
333 } else if (!strcmp(fieldName, "taxiways")) {
334 *out = naNewVector(c);
335 for(unsigned int r=0; r<apt->numTaxiways(); ++r) {
336 FGTaxiway* taxi(apt->getTaxiwayByIndex(r));
337 naRef taxidata = ghostForTaxiway(c, taxi);
338 naVec_append(*out, taxidata);
339 }
340
341 } else {
342 return 0;
343 }
344
345 return "";
346 }
347
348 static const char* runwayGhostGetMember(naContext c, void* g, naRef field, naRef* out)
349 {
350 const char* fieldName = naStr_data(field);
351 FGRunwayBase* base = (FGRunwayBase*) g;
352
353 if (!strcmp(fieldName, "id")) *out = stringToNasal(c, base->ident());
354 else if (!strcmp(fieldName, "lat")) *out = naNum(base->latitude());
355 else if (!strcmp(fieldName, "lon")) *out = naNum(base->longitude());
356 else if (!strcmp(fieldName, "heading")) *out = naNum(base->headingDeg());
357 else if (!strcmp(fieldName, "magnetic_heading"))
358 *out = naNum(base->magneticHeadingDeg());
359 else if (!strcmp(fieldName, "length")) *out = naNum(base->lengthM());
360 else if (!strcmp(fieldName, "width")) *out = naNum(base->widthM());
361 else if (!strcmp(fieldName, "surface")) *out = naNum(base->surface());
362 else if (!strcmp(fieldName, "airport"))
363 *out = ghostForAirport(c, base->airport());
364 else if (base->type() == FGRunwayBase::RUNWAY) {
365 FGRunway* rwy = (FGRunway*) g;
366 if (!strcmp(fieldName, "threshold")) *out = naNum(rwy->displacedThresholdM());
367 else if (!strcmp(fieldName, "stopway")) *out = naNum(rwy->stopwayM());
368 else if (!strcmp(fieldName, "reciprocal")) {
369 *out = ghostForRunway(c, rwy->reciprocalRunway());
370 } else if (!strcmp(fieldName, "ils_frequency_mhz")) {
371 *out = rwy->ILS() ? naNum(rwy->ILS()->get_freq() / 100.0) : naNil();
372 } else if (!strcmp(fieldName, "ils")) {
373 *out = ghostForNavaid(c, rwy->ILS());
374 } else {
375 return 0;
376 }
377 } else {
378 return 0;
379 }
380
381 return "";
382 }
383
384 static const char* navaidGhostGetMember(naContext c, void* g, naRef field, naRef* out)
385 {
386 const char* fieldName = naStr_data(field);
387 FGNavRecord* nav = (FGNavRecord*) g;
388
389 if (!strcmp(fieldName, "id")) *out = stringToNasal(c, nav->ident());
390 else if (!strcmp(fieldName, "name")) *out = stringToNasal(c, nav->name());
391 else if (!strcmp(fieldName, "lat")) *out = naNum(nav->get_lat());
392 else if (!strcmp(fieldName, "lon")) *out = naNum(nav->get_lon());
393 else if (!strcmp(fieldName, "elevation")) {
394 *out = naNum(nav->get_elev_ft() * SG_FEET_TO_METER);
395 } else if (!strcmp(fieldName, "type")) {
396 *out = stringToNasal(c, nav->nameForType(nav->type()));
397 } else if (!strcmp(fieldName, "frequency")) {
398 *out = naNum(nav->get_freq());
399 } else if (!strcmp(fieldName, "range_nm")) {
400 *out = naNum(nav->get_range());
401 } else if (!strcmp(fieldName, "magvar")) {
402 if (nav->type() == FGPositioned::VOR) {
403 // For VORs, the multiuse function provides the magnetic variation
404 double variation = nav->get_multiuse();
405 SG_NORMALIZE_RANGE(variation, 0.0, 360.0);
406 *out = naNum(variation);
407 } else {
408 *out = naNil();
409 }
410 } else if (!strcmp(fieldName, "colocated_dme")) {
411 FGNavRecordRef dme = FGPositioned::loadById<FGNavRecord>(nav->colocatedDME());
412 if (dme) {
413 *out = ghostForNavaid(c, dme);
414 } else {
415 *out = naNil();
416 }
417 } else if (!strcmp(fieldName, "dme")) {
418 *out = naNum(nav->hasDME());
419 } else if (!strcmp(fieldName, "vortac")) {
420 *out = naNum(nav->isVORTAC());
421 } else if (!strcmp(fieldName, "course")) {
422 if ((nav->type() == FGPositioned::ILS) || (nav->type() == FGPositioned::LOC)) {
423 double radial = nav->get_multiuse();
424 SG_NORMALIZE_RANGE(radial, 0.0, 360.0);
425 *out = naNum(radial);
426 } else {
427 *out = naNil();
428 }
429 } else if (!strcmp(fieldName, "guid")) {
430 *out = naNum(nav->guid());
431 } else if (!strcmp(fieldName, "runway")) {
432 *out = ghostForRunway(c, nav->runway());
433 } else if (!strcmp(fieldName, "airport")) {
434 if (nav->runway()) {
435 *out = ghostForAirport(c, nav->runway()->airport());
436 } else {
437 *out = naNil(); // not associated with an airport / runway
438 }
439 } else {
440 return 0;
441 }
442
443 return "";
444 }
445
446 static const char* fixGhostGetMember(naContext c, void* g, naRef field, naRef* out)
447 {
448 const char* fieldName = naStr_data(field);
449 FGFix* fix = (FGFix*) g;
450
451 if (!strcmp(fieldName, "id")) *out = stringToNasal(c, fix->ident());
452 else if (!strcmp(fieldName, "lat")) *out = naNum(fix->get_lat());
453 else if (!strcmp(fieldName, "lon")) *out = naNum(fix->get_lon());
454 // for homogenity with other values returned by navinfo()
455 else if (!strcmp(fieldName, "type")) *out = stringToNasal(c, "fix");
456 else if (!strcmp(fieldName, "name")) *out = stringToNasal(c, fix->ident());
457 else if (!strcmp(fieldName, "guid"))
458 *out = naNum(fix->guid());
459 else {
460 return 0;
461 }
462
463 return "";
464 }
465
466 static const char* commGhostGetMember(naContext c, void* g, naRef field, naRef* out)
467 {
468 const char* fieldName = naStr_data(field);
469 auto comm = static_cast<flightgear::CommStation*>(g);
470
471 if (!strcmp(fieldName, "id"))
472 *out = stringToNasal(c, comm->ident());
473 else if (!strcmp(fieldName, "lat"))
474 *out = naNum(comm->latitude());
475 else if (!strcmp(fieldName, "lon"))
476 *out = naNum(comm->longitude());
477 else if (!strcmp(fieldName, "airport"))
478 *out = ghostForAirport(c, comm->airport());
479 else if (!strcmp(fieldName, "range_nm"))
480 *out = naNum(comm->rangeNm());
481 else if (!strcmp(fieldName, "type")) {
482 *out = stringToNasal(c, comm->nameForType(comm->type()));
483 } else if (!strcmp(fieldName, "name"))
484 *out = stringToNasal(c, comm->name());
485 else if (!strcmp(fieldName, "frequency")) {
486 *out = naNum(comm->freqMHz());
487 } else if (!strcmp(fieldName, "guid")) {
488 *out = naNum(comm->guid());
489 } else {
490 return 0;
491 }
492
493 return "";
494 }
495
496 static const char* poiGhostGetMember(naContext c, void* g, naRef field, naRef* out)
497 {
498 const char* fieldName = naStr_data(field);
499 POI* wpt = (POI*)g;
500
501 if (!strcmp(fieldName, "parents")) {
502 *out = naNewVector(c);
503 naVec_append(*out, waypointPrototype);
504 } else if (!strcmp(fieldName, "id"))
505 *out = stringToNasal(c, wpt->ident());
506 else if (!strcmp(fieldName, "lat"))
507 *out = naNum(wpt->latitude());
508 else if (!strcmp(fieldName, "lon"))
509 *out = naNum(wpt->longitude());
510 else if (!strcmp(fieldName, "type"))
511 *out = stringToNasal(c, wpt->nameForType(wpt->type()));
512 else if (!strcmp(fieldName, "name"))
513 *out = stringToNasal(c, wpt->name());
514 else if (!strcmp(fieldName, "guid"))
515 *out = naNum(wpt->guid());
516 else {
517 return 0;
518 }
519
520 return "";
521 }
522
523
524 static bool hashIsCoord(naRef h)
525 {
526 naRef parents = naHash_cget(h, (char*) "parents");
527 if (!naIsVector(parents)) {
528 return false;
529 }
530
531 return naEqual(naVec_get(parents, 0), geoCoordClass) != 0;
532 }
533
534 bool geodFromHash(naRef ref, SGGeod& result)
535 {
536 if (!naIsHash(ref)) {
537 return false;
538 }
539
540
541 // check for manual latitude / longitude names
542 naRef lat = naHash_cget(ref, (char*) "lat");
543 naRef lon = naHash_cget(ref, (char*) "lon");
544 if (naIsNum(lat) && naIsNum(lon)) {
545 result = SGGeod::fromDeg(naNumValue(lon).num, naNumValue(lat).num);
546 return true;
547 }
548
549 // handle geo.nas geo.Coord object
550 if (hashIsCoord(ref)) {
551 naRef polarDirtyFlag = naHash_cget(ref, (char*) "_pdirty");
552 naRef cartesianDirtyFlag = naHash_cget(ref, (char*) "_cdirty");
553
554 if (naNumValue(polarDirtyFlag).num == 0) {
555 // polar values are valid
556 naRef lat = naHash_cget(ref, (char*) "_lat");
557 naRef lon = naHash_cget(ref, (char*) "_lon");
558 naRef alt_feet = naHash_cget(ref, (char*) "_alt");
559
560 if (naIsNum(lat) && naIsNum(lon) && naIsNil(alt_feet)) {
561 result = SGGeod::fromRad(naNumValue(lon).num, naNumValue(lat).num);
562 return true;
563 }
564
565 if (naIsNum(lat) && naIsNum(lon) && naIsNum(alt_feet)) {
566 result = SGGeod::fromRadFt(naNumValue(lon).num, naNumValue(lat).num, naNumValue(alt_feet).num);
567 return true;
568 }
569 } else if (naNumValue(cartesianDirtyFlag).num == 0) {
570 // cartesian values are valid
571 naRef x = naHash_cget(ref, (char*) "_x");
572 naRef y = naHash_cget(ref, (char*) "_y");
573 naRef z = naHash_cget(ref, (char*) "_z");
574
575 if (naIsNum(x) && naIsNum(y) && naIsNum(z)) {
576 result = SGGeod::fromCart(SGVec3d{naNumValue(x).num,
577 naNumValue(y).num, naNumValue(z).num});
578 return true;
579 }
580 } else {
581 SG_LOG(SG_NASAL, SG_DEV_ALERT, "geo.Coord() instance has invalid coordinates");
582 }
583 }
584 // check for any synonyms?
585 // latitude + longitude?
586
587 return false;
588 }
589
590 int geodFromArgs(naRef* args, int offset, int argc, SGGeod& result)
591 {
592 if (offset >= argc || !args) {
593 return 0;
594 }
595
596 if (naIsGhost(args[offset])) {
597 naGhostType* gt = naGhost_type(args[offset]);
598 if (gt == &AirportGhostType) {
599 result = airportGhost(args[offset])->geod();
600 return 1;
601 }
602
603 if (gt == &NavaidGhostType) {
604 result = navaidGhost(args[offset])->geod();
605 return 1;
606 }
607
608 if (gt == &RunwayGhostType) {
609 result = runwayGhost(args[offset])->geod();
610 return 1;
611 }
612
613 if (gt == &TaxiwayGhostType) {
614 result = taxiwayGhost(args[offset])->geod();
615 return 1;
616 }
617
618 if (gt == &FixGhostType) {
619 result = fixGhost(args[offset])->geod();
620 return 1;
621 }
622
623 if (gt == &POIGhostType) {
624 result = poiGhost(args[offset])->geod();
625 return 1;
626 }
627
628 auto wp = wayptGhost(args[offset]);
629 if (wp) {
630 result = wp->position();
631 return 1;
632 }
633
634 auto leg = fpLegGhost(args[offset]);
635 if (leg) {
636 result = leg->waypoint()->position();
637 return 1;
638 }
639 }
640
641 if (geodFromHash(args[offset], result)) {
642 return 1;
643 }
644
645 if (((argc - offset) >= 2) && naIsNum(args[offset]) && naIsNum(args[offset + 1])) {
646 double lat = naNumValue(args[0]).num,
647 lon = naNumValue(args[1]).num;
648 result = SGGeod::fromDeg(lon, lat);
649 return 2;
650 }
651
652 return 0;
653 }
654
655 bool vec3dFromHash(naRef ref, SGVec3d& result)
656 {
657 if (!naIsHash(ref)) {
658 return false;
659 }
660
661 // check for manual latitude / longitude names
662 naRef x = naHash_cget(ref, (char*) "x");
663 naRef y = naHash_cget(ref, (char*) "y");
664 naRef z = naHash_cget(ref, (char*) "z");
665 if (naIsNum(x) && naIsNum(y) && naIsNum(z)) {
666 result = SGVec3d(naNumValue(x).num, naNumValue(y).num, naNumValue(z).num);
667 return true;
668 }
669 return false;
670 }
671
672 // Convert a cartesian point to a geodetic lat/lon/altitude.
673 static naRef f_carttogeod(naContext c, naRef me, int argc, naRef* args)
674 {
675 double lat, lon, alt, xyz[3];
676 if(argc != 3) naRuntimeError(c, "carttogeod() expects 3 arguments");
677 for(int i=0; i<3; i++)
678 xyz[i] = naNumValue(args[i]).num;
679 sgCartToGeod(xyz, &lat, &lon, &alt);
680 lat *= SG_RADIANS_TO_DEGREES;
681 lon *= SG_RADIANS_TO_DEGREES;
682 naRef vec = naNewVector(c);
683 naVec_append(vec, naNum(lat));
684 naVec_append(vec, naNum(lon));
685 naVec_append(vec, naNum(alt));
686 return vec;
687 }
688
689 // Convert a geodetic lat/lon/altitude to a cartesian point.
690 static naRef f_geodtocart(naContext c, naRef me, int argc, naRef* args)
691 {
692 if(argc != 3) naRuntimeError(c, "geodtocart() expects 3 arguments");
693 double lat = naNumValue(args[0]).num * SG_DEGREES_TO_RADIANS;
694 double lon = naNumValue(args[1]).num * SG_DEGREES_TO_RADIANS;
695 double alt = naNumValue(args[2]).num;
696 double xyz[3];
697 sgGeodToCart(lat, lon, alt, xyz);
698 naRef vec = naNewVector(c);
699 naVec_append(vec, naNum(xyz[0]));
700 naVec_append(vec, naNum(xyz[1]));
701 naVec_append(vec, naNum(xyz[2]));
702 return vec;
703 }
704
705 /**
706 * @name f_get_cart_ground_intersection
707 * @brief Returns where the given position in the specified direction will intersect with the ground
708 *
709 * Exposes the built in function to Nasal to allow a craft to ascertain
710 * whether or not a certain position and direction pair intersect with
711 * the ground.
712 *
713 * Useful for radars, terrain avoidance (GPWS), etc.
714 *
715 * @param [in] vec3d(x,y,z) position
716 * @param [in] vec3d(x,y,z) direction
717 *
718 * @retval geod hash (lat:rad,lon:rad,elevation:Meters) intersection
719 * @retval nil no intersection found.
720 *
721 * Example Usage:
722 * @code
723 * var end = geo.Coord.new(start);
724 * end.apply_course_distance(heading, speed_horz_fps*FT2M);
725 * end.set_alt(end.alt() - speed_down_fps*FT2M);
726 *
727 * var dir_x = end.x() - start.x();
728 * var dir_y = end.y() - start.y();
729 * var dir_z = end.z() - start.z();
730 * var xyz = { "x":start.x(), "y" : start.y(), "z" : start.z() };
731 * var dir = { "x":dir_x, "y" : dir_y, "z" : dir_z };
732 *
733 * var geod = get_cart_ground_intersection(xyz, dir);
734 * if (geod != nil) {
735 * end.set_latlon(geod.lat, geod.lon, geod.elevation);
736 var dist = start.direct_distance_to(end)*M2FT;
737 * var time = dist / speed_fps;
738 * setprop("/sim/model/radar/time-until-impact", time);
739 * }
740 * @endcode
741 */
742 static naRef f_get_cart_ground_intersection(naContext c, naRef me, int argc, naRef* args)
743 {
744 SGVec3d dir;
745 SGVec3d pos;
746
747 if (argc != 2)
748 naRuntimeError(c, "geod_hash get_cart_ground_intersection(position: hash{x,y,z}, direction:hash{x,y,z}) expects 2 arguments");
749
750 if (!vec3dFromHash(args[0], pos))
751 naRuntimeError(c, "geod_hash get_cart_ground_intersection(position:hash{x,y,z}, direction:hash{x,y,z}) expects argument(0) to be hash of position containing x,y,z");
752
753 if (!vec3dFromHash(args[1], dir))
754 naRuntimeError(c, "geod_hash get_cart_ground_intersection(position: hash{x,y,z}, direction:hash{x,y,z}) expects argument(1) to be hash of direction containing x,y,z");
755
756 SGVec3d nearestHit;
757 if (!globals->get_scenery()->get_cart_ground_intersection(pos, dir, nearestHit))
758 return naNil();
759
760 const SGGeod geodHit = SGGeod::fromCart(nearestHit);
761
762 // build a hash for returned intersection
763 naRef intersection_h = naNewHash(c);
764 hashset(c, intersection_h, "lat", naNum(geodHit.getLatitudeDeg()));
765 hashset(c, intersection_h, "lon", naNum(geodHit.getLongitudeDeg()));
766 hashset(c, intersection_h, "elevation", naNum(geodHit.getElevationM()));
767 return intersection_h;
768 }
769
770 // convert from aircraft reference frame to global (ECEF) cartesian
771 static naRef f_aircraftToCart(naContext c, naRef me, int argc, naRef* args)
772 {
773 if (argc != 1)
774 naRuntimeError(c, "hash{x,y,z} aircraftToCart(position: hash{x,y,z}) expects one argument");
775
776 SGVec3d offset;
777 if (!vec3dFromHash(args[0], offset))
778 naRuntimeError(c, "aircraftToCart expects argument(0) to be a hash containing x,y,z");
779
780 double heading, pitch, roll;
781 globals->get_aircraft_orientation(heading, pitch, roll);
782
783 // Transform that one to the horizontal local coordinate system.
784 SGQuatd hlTrans = SGQuatd::fromLonLat(globals->get_aircraft_position());
785
786 // post-rotate the orientation of the aircraft wrt the horizontal local frame
787 hlTrans *= SGQuatd::fromYawPitchRollDeg(heading, pitch, roll);
788
789 // The offset converted to the usual body fixed coordinate system
790 // rotated to the earth fiexed coordinates axis
791 offset = hlTrans.backTransform(offset);
792
793 SGVec3d v = globals->get_aircraft_position_cart() + offset;
794
795 // build a hash for returned location
796 naRef pos_h = naNewHash(c);
797 hashset(c, pos_h, "x", naNum(v.x()));
798 hashset(c, pos_h, "y", naNum(v.y()));
799 hashset(c, pos_h, "z", naNum(v.z()));
800 return pos_h;
801 }
802
803 // For given geodetic point return array with elevation, and a material data
804 // hash, or nil if there's no information available (tile not loaded). If
805 // information about the material isn't available, then nil is returned instead
806 // of the hash.
807 static naRef f_geodinfo(naContext c, naRef me, int argc, naRef* args)
808 {
809 #define HASHSET(s,l,n) naHash_set(matdata, naStr_fromdata(naNewString(c),s,l),n)
810 if(argc < 2 || argc > 3)
811 naRuntimeError(c, "geodinfo() expects 2 or 3 arguments: lat, lon [, maxalt]");
812 double lat = naNumValue(args[0]).num;
813 double lon = naNumValue(args[1]).num;
814 double elev = argc == 3 ? naNumValue(args[2]).num : 10000;
815 const simgear::BVHMaterial *material;
816 SGGeod geod = SGGeod::fromDegM(lon, lat, elev);
817
818 if (globals == nullptr)
819 return naNil();
820
821 const auto scenery = globals->get_scenery();
822 if (scenery == nullptr)
823 return naNil();
824
825 if(!scenery->get_elevation_m(geod, elev, &material)) {
826 return naNil();
827 }
828
829 naRef vec = naNewVector(c);
830 naVec_append(vec, naNum(elev));
831
832 naRef matdata = naNil();
833
834 const SGMaterial *mat = dynamic_cast<const SGMaterial *>(material);
835 if(mat) {
836 matdata = naNewHash(c);
837 naRef names = naNewVector(c);
838 for (const std::string& n : mat->get_names())
839 naVec_append(names, stringToNasal(c, n));
840
841 HASHSET("region", 6, stringToNasal(c, mat->get_region_name()));
842 HASHSET("names", 5, names);
843 HASHSET("solid", 5, naNum(mat->get_solid()));
844 HASHSET("friction_factor", 15, naNum(mat->get_friction_factor()));
845 HASHSET("rolling_friction", 16, naNum(mat->get_rolling_friction()));
846 HASHSET("load_resistance", 15, naNum(mat->get_load_resistance()));
847 HASHSET("bumpiness", 9, naNum(mat->get_bumpiness()));
848 HASHSET("light_coverage", 14, naNum(mat->get_light_coverage()));
849 } else if (material) {
850 matdata = naNewHash(c);
851 naRef names = naNewVector(c);
852 naVec_append(names, stringToNasal(c, ""));
853
854 HASHSET("region", 6, stringToNasal(c, ""));
855 HASHSET("names", 5, names);
856 HASHSET("solid", 5, naNum(material->get_solid()));
857 HASHSET("friction_factor", 15, naNum(material->get_friction_factor()));
858 HASHSET("rolling_friction", 16, naNum(material->get_rolling_friction()));
859 HASHSET("load_resistance", 15, naNum(material->get_load_resistance()));
860 HASHSET("bumpiness", 9, naNum(material->get_bumpiness()));
861 }
862
863 naVec_append(vec, matdata);
864 return vec;
865 #undef HASHSET
866 }
867
868
869 // Returns data hash for particular or nearest airport of a <type>, or nil
870 // on error.
871 //
872 // airportinfo(<id>); e.g. "KSFO"
873 // airportinfo(<type>); type := ("airport"|"seaport"|"heliport")
874 // airportinfo() same as airportinfo("airport")
875 // airportinfo(<lat>, <lon> [, <type>]);
876 static naRef f_airportinfo(naContext c, naRef me, int argc, naRef* args)
877 {
878 SGGeod pos = globals->get_aircraft_position();
879 FGAirport* apt = NULL;
880
881 if(argc >= 2 && naIsNum(args[0]) && naIsNum(args[1])) {
882 pos = SGGeod::fromDeg(args[1].num, args[0].num);
883 args += 2;
884 argc -= 2;
885 }
886
887 double maxRange = 10000.0; // expose this? or pick a smaller value?
888
889 FGAirport::TypeRunwayFilter filter; // defaults to airports only
890
891 if(argc == 0) {
892 // fall through and use AIRPORT
893 } else if(argc == 1 && naIsString(args[0])) {
894 if (filter.fromTypeString(naStr_data(args[0]))) {
895 // done!
896 } else {
897 // user provided an <id>, hopefully
898 apt = FGAirport::findByIdent(naStr_data(args[0]));
899 if (!apt) {
900 // return nil here, but don't raise a runtime error; this is a
901 // legitamate way to validate an ICAO code, for example in a
902 // dialog box or similar.
903 return naNil();
904 }
905 }
906 } else {
907 naRuntimeError(c, "airportinfo() with invalid function arguments");
908 return naNil();
909 }
910
911 if(!apt) {
912 apt = FGAirport::findClosest(pos, maxRange, &filter);
913 if(!apt) return naNil();
914 }
915
916 return ghostForAirport(c, apt);
917 }
918
919 static naRef f_findAirportsWithinRange(naContext c, naRef me, int argc, naRef* args)
920 {
921 int argOffset = 0;
922 SGGeod pos = globals->get_aircraft_position();
923 argOffset += geodFromArgs(args, 0, argc, pos);
924
925 if (!naIsNum(args[argOffset])) {
926 naRuntimeError(c, "findAirportsWithinRange expected range (in nm) as arg %d", argOffset);
927 }
928
929 FGAirport::TypeRunwayFilter filter; // defaults to airports only
930 double rangeNm = args[argOffset++].num;
931 if (argOffset < argc) {
932 filter.fromTypeString(naStr_data(args[argOffset++]));
933 }
934
935 naRef r = naNewVector(c);
936
937 FGPositionedList apts = FGPositioned::findWithinRange(pos, rangeNm, &filter);
938 FGPositioned::sortByRange(apts, pos);
939
940 for (FGPositionedRef a : apts) {
941 naVec_append(r, ghostForAirport(c, fgpositioned_cast<FGAirport>(a)));
942 }
943
944 return r;
945 }
946
947 static naRef f_findAirportsByICAO(naContext c, naRef me, int argc, naRef* args)
948 {
949 if (!naIsString(args[0])) {
950 naRuntimeError(c, "findAirportsByICAO expects string as arg 0");
951 }
952
953 int argOffset = 0;
954 std::string prefix(naStr_data(args[argOffset++]));
955 FGAirport::TypeRunwayFilter filter; // defaults to airports only
956 if (argOffset < argc) {
957 filter.fromTypeString(naStr_data(args[argOffset++]));
958 }
959
960 naRef r = naNewVector(c);
961
962 FGPositionedList apts = FGPositioned::findAllWithIdent(prefix, &filter, false);
963 for (FGPositionedRef a : apts) {
964 naVec_append(r, ghostForAirport(c, fgpositioned_cast<FGAirport>(a)));
965 }
966
967 return r;
968 }
969
970 static naRef f_airport_tower(naContext c, naRef me, int argc, naRef* args)
971 {
972 FGAirport* apt = airportGhost(me);
973 if (!apt) {
974 naRuntimeError(c, "airport.tower called on non-airport object");
975 }
976
977 // build a hash for the tower position
978 SGGeod towerLoc = apt->getTowerLocation();
979 naRef tower = naNewHash(c);
980 hashset(c, tower, "lat", naNum(towerLoc.getLatitudeDeg()));
981 hashset(c, tower, "lon", naNum(towerLoc.getLongitudeDeg()));
982 hashset(c, tower, "elevation", naNum(towerLoc.getElevationM()));
983 return tower;
984 }
985
986 static naRef f_airport_comms(naContext c, naRef me, int argc, naRef* args)
987 {
988 FGAirport* apt = airportGhost(me);
989 if (!apt) {
990 naRuntimeError(c, "airport.comms called on non-airport object");
991 }
992 naRef comms = naNewVector(c);
993
994 // if we have an explicit type, return a simple vector of frequencies
995 if (argc > 0 && !naIsString(args[0])) {
996 naRuntimeError(c, "airport.comms argument must be a frequency type name");
997 }
998
999 if (argc > 0) {
1000 std::string commName = naStr_data(args[0]);
1001 FGPositioned::Type commType = FGPositioned::typeFromName(commName);
1002
1003 for (auto comm : apt->commStationsOfType(commType)) {
1004 naVec_append(comms, naNum(comm->freqMHz()));
1005 }
1006 } else {
1007 // otherwise return a vector of hashes, one for each comm station.
1008 for (auto comm : apt->commStations()) {
1009 naRef commHash = naNewHash(c);
1010 hashset(c, commHash, "frequency", naNum(comm->freqMHz()));
1011 hashset(c, commHash, "ident", stringToNasal(c, comm->ident()));
1012 naVec_append(comms, commHash);
1013 }
1014 }
1015
1016 return comms;
1017 }
1018
1019 static naRef f_airport_runway(naContext c, naRef me, int argc, naRef* args)
1020 {
1021 FGAirport* apt = airportGhost(me);
1022 if (!apt) {
1023 naRuntimeError(c, "airport.runway called on non-airport object");
1024 }
1025
1026 if ((argc < 1) || !naIsString(args[0])) {
1027 naRuntimeError(c, "airport.runway expects a runway ident argument");
1028 }
1029
1030 std::string ident = simgear::strutils::uppercase(naStr_data(args[0]));
1031
1032 if (apt->hasRunwayWithIdent(ident)) {
1033 return ghostForRunway(c, apt->getRunwayByIdent(ident));
1034 } else if (apt->hasHelipadWithIdent(ident)) {
1035 return ghostForHelipad(c, apt->getHelipadByIdent(ident));
1036 }
1037 return naNil();
1038 }
1039
1040 static naRef f_airport_runwaysWithoutReciprocals(naContext c, naRef me, int argc, naRef* args)
1041 {
1042 FGAirport* apt = airportGhost(me);
1043 if (!apt) {
1044 naRuntimeError(c, "airport.runwaysWithoutReciprocals called on non-airport object");
1045 }
1046
1047 FGRunwayList rwylist(apt->getRunwaysWithoutReciprocals());
1048 naRef runways = naNewVector(c);
1049 for (unsigned int r=0; r<rwylist.size(); ++r) {
1050 FGRunway* rwy(rwylist[r]);
1051 naVec_append(runways, ghostForRunway(c, apt->getRunwayByIdent(rwy->ident())));
1052 }
1053 return runways;
1054 }
1055
1056 static naRef f_airport_sids(naContext c, naRef me, int argc, naRef* args)
1057 {
1058 FGAirport* apt = airportGhost(me);
1059 if (!apt) {
1060 naRuntimeError(c, "airport.sids called on non-airport object");
1061 }
1062
1063 naRef sids = naNewVector(c);
1064
1065 FGRunway* rwy = NULL;
1066 if (argc > 0 && naIsString(args[0])) {
1067 if (!apt->hasRunwayWithIdent(naStr_data(args[0]))) {
1068 return naNil();
1069 }
1070
1071 rwy = apt->getRunwayByIdent(naStr_data(args[0]));
1072 } else if (argc > 0) {
1073 rwy = runwayGhost(args[0]);
1074 }
1075
1076 if (rwy) {
1077 for (auto sid : rwy->getSIDs()) {
1078 naRef procId = stringToNasal(c, sid->ident());
1079 naVec_append(sids, procId);
1080 }
1081 } else {
1082 for (unsigned int s=0; s<apt->numSIDs(); ++s) {
1083 flightgear::SID* sid = apt->getSIDByIndex(s);
1084 naRef procId = stringToNasal(c, sid->ident());
1085 naVec_append(sids, procId);
1086 }
1087 }
1088
1089 return sids;
1090 }
1091
1092 static naRef f_airport_stars(naContext c, naRef me, int argc, naRef* args)
1093 {
1094 FGAirport* apt = airportGhost(me);
1095 if (!apt) {
1096 naRuntimeError(c, "airport.stars called on non-airport object");
1097 }
1098
1099 naRef stars = naNewVector(c);
1100
1101 FGRunway* rwy = NULL;
1102 if (argc > 0 && naIsString(args[0])) {
1103 if (!apt->hasRunwayWithIdent(naStr_data(args[0]))) {
1104 return naNil();
1105 }
1106
1107 rwy = apt->getRunwayByIdent(naStr_data(args[0]));
1108 } else if (argc > 0) {
1109 rwy = runwayGhost(args[0]);
1110 }
1111
1112 if (rwy) {
1113 for (flightgear::STAR* s : rwy->getSTARs()) {
1114 naRef procId = stringToNasal(c, s->ident());
1115 naVec_append(stars, procId);
1116 }
1117 } else {
1118 for (unsigned int s=0; s<apt->numSTARs(); ++s) {
1119 flightgear::STAR* star = apt->getSTARByIndex(s);
1120 naRef procId = stringToNasal(c, star->ident());
1121 naVec_append(stars, procId);
1122 }
1123 }
1124
1125 return stars;
1126 }
1127
1128 static naRef f_airport_approaches(naContext c, naRef me, int argc, naRef* args)
1129 {
1130 FGAirport* apt = airportGhost(me);
1131 if (!apt) {
1132 naRuntimeError(c, "airport.getApproachList called on non-airport object");
1133 }
1134
1135 naRef approaches = naNewVector(c);
1136
1137 ProcedureType ty = PROCEDURE_INVALID;
1138 if ((argc > 1) && naIsString(args[1])) {
1139 std::string u = simgear::strutils::uppercase(naStr_data(args[1]));
1140 if (u == "NDB") ty = PROCEDURE_APPROACH_NDB;
1141 if (u == "VOR") ty = PROCEDURE_APPROACH_VOR;
1142 if (u == "ILS") ty = PROCEDURE_APPROACH_ILS;
1143 if (u == "RNAV") ty = PROCEDURE_APPROACH_RNAV;
1144 }
1145
1146 FGRunway* rwy = NULL;
1147 STAR* star = nullptr;
1148 if (argc > 0 && (rwy = runwayGhost(args[0]))) {
1149 // ok
1150 } else if (argc > 0 && (procedureGhost(args[0]))) {
1151 Procedure* proc = procedureGhost(args[0]);
1152 if (proc->type() != PROCEDURE_STAR)
1153 return naNil();
1154 star = static_cast<STAR*>(proc);
1155 } else if (argc > 0 && naIsString(args[0])) {
1156 if (!apt->hasRunwayWithIdent(naStr_data(args[0]))) {
1157 return naNil();
1158 }
1159
1160 rwy = apt->getRunwayByIdent(naStr_data(args[0]));
1161 }
1162
1163 if (rwy) {
1164 for (Approach* s : rwy->getApproaches()) {
1165 if ((ty != PROCEDURE_INVALID) && (s->type() != ty)) {
1166 continue;
1167 }
1168
1169 naRef procId = stringToNasal(c, s->ident());
1170 naVec_append(approaches, procId);
1171 }
1172 } else if (star) {
1173 std::set<std::string> appIds;
1174 for (auto rwy : star->runways()) {
1175 for (auto app : rwy->getApproaches()) {
1176 appIds.insert(app->ident());
1177 }
1178 }
1179
1180 for (auto s : appIds) {
1181 naVec_append(approaches, stringToNasal(c, s));
1182 }
1183 } else {
1184 // no runway specified, report them all
1185 RunwayVec runways;
1186 if (star)
1187 runways = star->runways();
1188
1189 for (unsigned int s=0; s<apt->numApproaches(); ++s) {
1190 Approach* app = apt->getApproachByIndex(s);
1191 if ((ty != PROCEDURE_INVALID) && (app->type() != ty)) {
1192 continue;
1193 }
1194
1195 naRef procId = stringToNasal(c, app->ident());
1196 naVec_append(approaches, procId);
1197 }
1198 }
1199
1200 return approaches;
1201 }
1202
1203 static naRef f_airport_parking(naContext c, naRef me, int argc, naRef* args)
1204 {
1205 FGAirport* apt = airportGhost(me);
1206 if (!apt) {
1207 naRuntimeError(c, "airport.parking called on non-airport object");
1208 }
1209
1210 naRef r = naNewVector(c);
1211 std::string type;
1212 bool onlyAvailable = false;
1213
1214 if (argc > 0 && naIsString(args[0])) {
1215 type = naStr_data(args[0]);
1216 }
1217
1218 if ((argc > 1) && naIsNum(args[1])) {
1219 onlyAvailable = (args[1].num != 0.0);
1220 }
1221
1222 FGAirportDynamicsRef dynamics = apt->getDynamics();
1223 FGParkingList parkings = dynamics->getParkings(onlyAvailable, type);
1224 FGParkingList::const_iterator it;
1225 for (it = parkings.begin(); it != parkings.end(); ++it) {
1226 FGParkingRef park = *it;
1227 const SGGeod& parkLoc = park->geod();
1228 naRef ph = naNewHash(c);
1229 hashset(c, ph, "name", stringToNasal(c, park->getName()));
1230 hashset(c, ph, "lat", naNum(parkLoc.getLatitudeDeg()));
1231 hashset(c, ph, "lon", naNum(parkLoc.getLongitudeDeg()));
1232 hashset(c, ph, "elevation", naNum(parkLoc.getElevationM()));
1233 naVec_append(r, ph);
1234 }
1235
1236 return r;
1237 }
1238
1239 static naRef f_airport_getSid(naContext c, naRef me, int argc, naRef* args)
1240 {
1241 FGAirport* apt = airportGhost(me);
1242 if (!apt) {
1243 naRuntimeError(c, "airport.getSid called on non-airport object");
1244 }
1245
1246 if ((argc != 1) || !naIsString(args[0])) {
1247 naRuntimeError(c, "airport.getSid passed invalid argument");
1248 }
1249
1250 std::string ident = naStr_data(args[0]);
1251 return ghostForProcedure(c, apt->findSIDWithIdent(ident));
1252 }
1253
1254 static naRef f_airport_getStar(naContext c, naRef me, int argc, naRef* args)
1255 {
1256 FGAirport* apt = airportGhost(me);
1257 if (!apt) {
1258 naRuntimeError(c, "airport.getStar called on non-airport object");
1259 }
1260
1261 if ((argc != 1) || !naIsString(args[0])) {
1262 naRuntimeError(c, "airport.getStar passed invalid argument");
1263 }
1264
1265 std::string ident = naStr_data(args[0]);
1266 return ghostForProcedure(c, apt->findSTARWithIdent(ident));
1267 }
1268
1269 static naRef f_airport_getApproach(naContext c, naRef me, int argc, naRef* args)
1270 {
1271 FGAirport* apt = airportGhost(me);
1272 if (!apt) {
1273 naRuntimeError(c, "airport.getIAP called on non-airport object");
1274 }
1275
1276 if ((argc != 1) || !naIsString(args[0])) {
1277 naRuntimeError(c, "airport.getIAP passed invalid argument");
1278 }
1279
1280 std::string ident = naStr_data(args[0]);
1281 return ghostForProcedure(c, apt->findApproachWithIdent(ident));
1282 }
1283
1284 static naRef f_airport_findBestRunway(naContext c, naRef me, int argc, naRef* args)
1285 {
1286 FGAirport* apt = airportGhost(me);
1287 if (!apt) {
1288 naRuntimeError(c, "findBestRunway called on non-airport object");
1289 }
1290
1291 SGGeod pos;
1292 if (!geodFromArgs(args, 0, argc, pos)) {
1293 naRuntimeError(c, "findBestRunway must be passed a position");
1294 }
1295
1296 return ghostForRunway(c, apt->findBestRunwayForPos(pos));
1297 }
1298
1299 static naRef f_airport_toString(naContext c, naRef me, int argc, naRef* args)
1300 {
1301 FGAirport* apt = airportGhost(me);
1302 if (!apt) {
1303 naRuntimeError(c, "airport.tostring called on non-airport object");
1304 }
1305
1306 return stringToNasal(c, "an airport " + apt->ident());
1307 }
1308
1309 // Returns vector of data hash for navaid of a <type>, nil on error
1310 // navaids sorted by ascending distance
1311 // navinfo([<lat>,<lon>],[<type>],[<id>])
1312 // lat/lon (numeric): use latitude/longitude instead of ac position
1313 // type: ("fix"|"vor"|"ndb"|"ils"|"dme"|"tacan"|"any")
1314 // id: (partial) id of the fix
1315 // examples:
1316 // navinfo("vor") returns all vors
1317 // navinfo("HAM") return all navaids who's name start with "HAM"
1318 // navinfo("vor", "HAM") return all vor who's name start with "HAM"
1319 //navinfo(34,48,"vor","HAM") return all vor who's name start with "HAM"
1320 // sorted by distance relative to lat=34, lon=48
1321 static naRef f_navinfo(naContext c, naRef me, int argc, naRef* args)
1322 {
1323 SGGeod pos;
1324
1325 if(argc >= 2 && naIsNum(args[0]) && naIsNum(args[1])) {
1326 pos = SGGeod::fromDeg(args[1].num, args[0].num);
1327 args += 2;
1328 argc -= 2;
1329 } else {
1330 pos = globals->get_aircraft_position();
1331 }
1332
1333 FGPositioned::Type type = FGPositioned::INVALID;
1334 nav_list_type navlist;
1335 const char * id = "";
1336
1337 if(argc > 0 && naIsString(args[0])) {
1338 const char *s = naStr_data(args[0]);
1339 if(!strcmp(s, "any")) type = FGPositioned::INVALID;
1340 else if(!strcmp(s, "fix")) type = FGPositioned::FIX;
1341 else if(!strcmp(s, "vor")) type = FGPositioned::VOR;
1342 else if(!strcmp(s, "ndb")) type = FGPositioned::NDB;
1343 else if(!strcmp(s, "ils")) type = FGPositioned::ILS;
1344 else if(!strcmp(s, "dme")) type = FGPositioned::DME;
1345 else if(!strcmp(s, "tacan")) type = FGPositioned::TACAN;
1346 else id = s; // this is an id
1347 ++args;
1348 --argc;
1349 }
1350
1351 if(argc > 0 && naIsString(args[0])) {
1352 if( *id != 0 ) {
1353 naRuntimeError(c, "navinfo() called with navaid id");
1354 return naNil();
1355 }
1356 id = naStr_data(args[0]);
1357 ++args;
1358 --argc;
1359 }
1360
1361 if( argc > 0 ) {
1362 naRuntimeError(c, "navinfo() called with too many arguments");
1363 return naNil();
1364 }
1365
1366 FGNavList::TypeFilter filter(type);
1367 navlist = FGNavList::findByIdentAndFreq( pos, id, 0.0, &filter );
1368
1369 naRef reply = naNewVector(c);
1370 for( nav_list_type::const_iterator it = navlist.begin(); it != navlist.end(); ++it ) {
1371 naVec_append( reply, ghostForNavaid(c, *it) );
1372 }
1373 return reply;
1374 }
1375
1376 static naRef f_findNavaidsWithinRange(naContext c, naRef me, int argc, naRef* args)
1377 {
1378 int argOffset = 0;
1379 SGGeod pos = globals->get_aircraft_position();
1380 argOffset += geodFromArgs(args, 0, argc, pos);
1381
1382 if (!naIsNum(args[argOffset])) {
1383 naRuntimeError(c, "findNavaidsWithinRange expected range (in nm) as arg %d", argOffset);
1384 }
1385
1386 FGPositioned::Type type = FGPositioned::INVALID;
1387 double rangeNm = args[argOffset++].num;
1388 if (argOffset < argc) {
1389 type = FGPositioned::typeFromName(naStr_data(args[argOffset]));
1390 }
1391
1392 naRef r = naNewVector(c);
1393 FGNavList::TypeFilter filter(type);
1394 FGPositionedList navs = FGPositioned::findWithinRange(pos, rangeNm, &filter);
1395 FGPositioned::sortByRange(navs, pos);
1396
1397 for (FGPositionedRef a : navs) {
1398 FGNavRecord* nav = (FGNavRecord*) a.get();
1399 naVec_append(r, ghostForNavaid(c, nav));
1400 }
1401
1402 return r;
1403 }
1404
1405 static naRef f_findNDBByFrequency(naContext c, naRef me, int argc, naRef* args)
1406 {
1407 int argOffset = 0;
1408 SGGeod pos = globals->get_aircraft_position();
1409 argOffset += geodFromArgs(args, 0, argc, pos);
1410
1411 if (!naIsNum(args[argOffset])) {
•1412 naRuntimeError(c, "findNDBByFrquency expected frequency (in kHz) as arg %d", argOffset);
1413 }
1414
1415 double dbFreq = args[argOffset++].num;
1416 FGNavList::TypeFilter filter(FGPositioned::NDB);
1417 nav_list_type navs = FGNavList::findAllByFreq(dbFreq, pos, &filter);
1418 if (navs.empty()) {
1419 return naNil();
1420 }
1421
1422 return ghostForNavaid(c, navs.front().ptr());
1423 }
1424
1425 static naRef f_findNDBsByFrequency(naContext c, naRef me, int argc, naRef* args)
1426 {
1427 int argOffset = 0;
1428 SGGeod pos = globals->get_aircraft_position();
1429 argOffset += geodFromArgs(args, 0, argc, pos);
1430
1431 if (!naIsNum(args[argOffset])) {
•1432 naRuntimeError(c, "findNDBsByFrquency expected frequency (in kHz) as arg %d", argOffset);
1433 }
1434
1435 double dbFreq = args[argOffset++].num;
1436 FGNavList::TypeFilter filter(FGPositioned::NDB);
1437 nav_list_type navs = FGNavList::findAllByFreq(dbFreq, pos, &filter);
1438 if (navs.empty()) {
1439 return naNil();
1440 }
1441
1442 naRef r = naNewVector(c);
1443 for (nav_rec_ptr a : navs) {
1444 naVec_append(r, ghostForNavaid(c, a.ptr()));
1445 }
1446 return r;
1447 }
1448
1449 static naRef f_findNavaidByFrequency(naContext c, naRef me, int argc, naRef* args)
1450 {
1451 int argOffset = 0;
1452 SGGeod pos = globals->get_aircraft_position();
1453 argOffset += geodFromArgs(args, 0, argc, pos);
1454
1455 if (!naIsNum(args[argOffset])) {
•1456 naRuntimeError(c, "findNavaidByFrequency expected frequency (in Mhz) as arg %d", argOffset);
1457 }
1458
1459 FGPositioned::Type type = FGPositioned::INVALID;
1460 double freqMhz = args[argOffset++].num;
1461 if (argOffset < argc) {
1462 type = FGPositioned::typeFromName(naStr_data(args[argOffset]));
1463 if (type == FGPositioned::NDB) {
1464 naRuntimeError(c, "Use findNDBByFrquency to seach NDBs");
1465 }
1466 }
1467
1468 FGNavList::TypeFilter filter(type);
1469 auto navs = FGNavList::findAllByFreq(freqMhz, pos, &filter);
1470 if (navs.empty()) {
1471 return naNil();
1472 }
1473
1474 return ghostForNavaid(c, navs.front().ptr());
1475 }
1476
1477 static naRef f_findNavaidsByFrequency(naContext c, naRef me, int argc, naRef* args)
1478 {
1479 int argOffset = 0;
1480 SGGeod pos = globals->get_aircraft_position();
1481 argOffset += geodFromArgs(args, 0, argc, pos);
1482
1483 if (!naIsNum(args[argOffset])) {
•1484 naRuntimeError(c, "findNavaidsByFrequency expected frequency (in Mhz) as arg %d", argOffset);
1485 }
1486
1487 FGPositioned::Type type = FGPositioned::INVALID;
1488 double freqMhz = args[argOffset++].num;
1489 if (argOffset < argc) {
1490 type = FGPositioned::typeFromName(naStr_data(args[argOffset]));
1491 if (type == FGPositioned::NDB) {
1492 naRuntimeError(c, "Use findNDBsByFrquency to seach NDBs");
1493 }
1494 }
1495
1496 naRef r = naNewVector(c);
1497 FGNavList::TypeFilter filter(type);
1498 auto navs = FGNavList::findAllByFreq(freqMhz, pos, &filter);
1499 for (auto a : navs) {
1500 naVec_append(r, ghostForNavaid(c, a.ptr()));
1501 }
1502
1503 return r;
1504 }
1505
1506 static naRef f_findCommByFrequency(naContext c, naRef me, int argc, naRef* args)
1507 {
1508 int argOffset = 0;
1509 SGGeod pos = globals->get_aircraft_position();
1510 argOffset += geodFromArgs(args, 0, argc, pos);
1511
1512 if (!naIsNum(args[argOffset])) {
1513 naRuntimeError(c, "findCommByFrequencyMhz expectes frequency (in Mhz) as arg %d", argOffset);
1514 }
1515
1516 // initial filter is all comm types
1517 FGPositioned::TypeFilter filter(FGPositioned::FREQ_GROUND, FGPositioned::FREQ_UNICOM);
1518 double freqMhz = args[argOffset++].num;
1519 if (argOffset < argc) {
1520 // allow specifying an explicitly type by name
1521 filter = FGPositioned::TypeFilter::fromString(naStr_data(args[argOffset]));
1522 }
1523
1524 auto ref = NavDataCache::instance()->findCommByFreq(static_cast<int>(freqMhz * 1000), pos, &filter);
1525 if (!ref) {
1526 return naNil();
1527 }
1528
1529 auto comm = fgpositioned_cast<flightgear::CommStation>(ref);
1530 return ghostForComm(c, comm);
1531 }
1532
1533 static naRef f_findCommsByFrequency(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 (!naIsNum(args[argOffset])) {
1540 naRuntimeError(c, "f_findCommsByFrequency expectes frequency (in Mhz) as arg %d", argOffset);
1541 }
1542
1543 FGPositioned::TypeFilter filter(FGPositioned::FREQ_GROUND, FGPositioned::FREQ_UNICOM);
1544 double freqMhz = args[argOffset++].num;
1545 if (argOffset < argc) {
1546 // allow specifying an explicitly type by name
1547 filter = FGPositioned::TypeFilter::fromString(naStr_data(args[argOffset]));
1548 }
1549
1550 naRef r = naNewVector(c);
1551 auto stations = NavDataCache::instance()->findCommsByFreq(static_cast<int>(freqMhz * 1000), pos, &filter);
1552 for (auto id : stations) {
1553 auto sta = FGPositioned::loadById<CommStation>(id);
1554 naVec_append(r, ghostForComm(c, sta.ptr()));
1555 }
1556
1557 return r;
1558 }
1559
1560 static naRef f_findNavaidsByIdent(naContext c, naRef me, int argc, naRef* args)
1561 {
1562 int argOffset = 0;
1563 SGGeod pos = globals->get_aircraft_position();
1564 argOffset += geodFromArgs(args, 0, argc, pos);
1565
1566 if (!naIsString(args[argOffset])) {
•1567 naRuntimeError(c, "findNavaidsByIdent expected ident string as arg %d", argOffset);
1568 }
1569
1570 FGPositioned::Type type = FGPositioned::INVALID;
1571 std::string ident = naStr_data(args[argOffset++]);
1572 if (argOffset < argc) {
1573 type = FGPositioned::typeFromName(naStr_data(args[argOffset]));
1574 }
1575
1576 FGNavList::TypeFilter filter(type);
1577 naRef r = naNewVector(c);
1578 nav_list_type navs = FGNavList::findByIdentAndFreq(pos, ident, 0.0, &filter);
1579
1580 for (nav_rec_ptr a : navs) {
1581 naVec_append(r, ghostForNavaid(c, a.ptr()));
1582 }
1583
1584 return r;
1585 }
1586
1587 static naRef f_findFixesByIdent(naContext c, naRef me, int argc, naRef* args)
1588 {
1589 int argOffset = 0;
1590 SGGeod pos = globals->get_aircraft_position();
1591 argOffset += geodFromArgs(args, 0, argc, pos);
1592
1593 if (!naIsString(args[argOffset])) {
•1594 naRuntimeError(c, "findFixesByIdent expected ident string as arg %d", argOffset);
1595 }
1596
1597 std::string ident(naStr_data(args[argOffset]));
1598 naRef r = naNewVector(c);
1599
1600 FGPositioned::TypeFilter filter(FGPositioned::FIX);
1601 FGPositionedList fixes = FGPositioned::findAllWithIdent(ident, &filter);
1602 FGPositioned::sortByRange(fixes, pos);
1603
1604 for (FGPositionedRef f : fixes) {
1605 naVec_append(r, ghostForFix(c, (FGFix*) f.ptr()));
1606 }
1607
1608 return r;
1609 }
1610
1611 static naRef f_findByIdent(naContext c, naRef me, int argc, naRef* args)
1612 {
1613 if ((argc < 2) || !naIsString(args[0]) || !naIsString(args[1]) ) {
1614 naRuntimeError(c, "finxByIdent: expects ident and type as first two args");
1615 }
1616
1617 std::string ident(naStr_data(args[0]));
1618 std::string typeSpec(naStr_data(args[1]));
1619
1620 // optional specify search pos as final argument
1621 SGGeod pos = globals->get_aircraft_position();
1622 geodFromArgs(args, 2, argc, pos);
1623 FGPositioned::TypeFilter filter(FGPositioned::TypeFilter::fromString(typeSpec));
1624
1625 naRef r = naNewVector(c);
1626
1627 FGPositionedList matches = FGPositioned::findAllWithIdent(ident, &filter);
1628 FGPositioned::sortByRange(matches, pos);
1629
1630 for (auto f : matches) {
1631 naVec_append(r, ghostForPositioned(c, f));
1632 }
1633
1634 return r;
1635 }
1636
1637
1638 // Convert a cartesian point to a geodetic lat/lon/altitude.
1639 static naRef f_magvar(naContext c, naRef me, int argc, naRef* args)
1640 {
1641 SGGeod pos = globals->get_aircraft_position();
1642 if (argc == 0) {
1643 // fine, use aircraft position
1644 } else if (geodFromArgs(args, 0, argc, pos)) {
1645 // okay
1646 } else {
1647 naRuntimeError(c, "magvar() expects no arguments, a positioned hash or lat,lon pair");
1648 }
1649
1650 double jd = globals->get_time_params()->getJD();
1651 double magvarDeg = sgGetMagVar(pos, jd) * SG_RADIANS_TO_DEGREES;
1652 return naNum(magvarDeg);
1653 }
1654
1655 static naRef f_courseAndDistance(naContext c, naRef me, int argc, naRef* args)
1656 {
1657 SGGeod from = globals->get_aircraft_position(), to, p;
1658 int argOffset = geodFromArgs(args, 0, argc, p);
1659 if (geodFromArgs(args, argOffset, argc, to)) {
1660 from = p; // we parsed both FROM and TO args, so first was from
1661 } else {
1662 to = p; // only parsed one arg, so FROM is current
1663 }
1664
1665 if (argOffset == 0) {
1666 naRuntimeError(c, "invalid arguments to courseAndDistance");
1667 }
1668
1669 double course, course2, d;
1670 SGGeodesy::inverse(from, to, course, course2, d);
1671
1672 naRef result = naNewVector(c);
1673 naVec_append(result, naNum(course));
1674 naVec_append(result, naNum(d * SG_METER_TO_NM));
1675 return result;
1676 }
1677
1678 static naRef f_formatLatLon(naContext c, naRef me, int argc, naRef* args)
1679 {
1680 SGGeod p;
1681 int argOffset = geodFromArgs(args, 0, argc, p);
1682 if (argOffset == 0) {
1683 naRuntimeError(c, "invalid arguments to formatLatLon, expect a geod or lat,lon");
1684 }
1685
1686 simgear::strutils::LatLonFormat format =
1687 static_cast<simgear::strutils::LatLonFormat>(fgGetInt("/sim/lon-lat-format"));
1688 if (argOffset < argc && naIsNum(args[argOffset])) {
1689 format = static_cast<simgear::strutils::LatLonFormat>((int) args[argOffset].num);
1690 if (format > simgear::strutils::LatLonFormat::DECIMAL_DEGREES_SYMBOL) {
1691 naRuntimeError(c, "invalid lat-lon format requested");
1692 }
1693 }
1694
1695 const auto s = simgear::strutils::formatGeodAsString(p, format);
1696 return stringToNasal(c, s);
1697 }
1698
1699 static naRef f_parseStringAsLatLonValue(naContext c, naRef me, int argc, naRef* args)
1700 {
1701 if ((argc < 1) || !naIsString(args[0])) {
1702 naRuntimeError(c, "Missing / bad argument to parseStringAsLatLonValue");
1703 }
1704
1705 double value;
1706 bool ok = simgear::strutils::parseStringAsLatLonValue(naStr_data(args[0]), value);
1707 if (!ok) {
1708 return naNil();
1709 }
1710
1711 return naNum(value);
1712 }
1713
1714
1715 static naRef f_greatCircleMove(naContext c, naRef me, int argc, naRef* args)
1716 {
1717 SGGeod from = globals->get_aircraft_position(), to;
1718 int argOffset = 0;
1719
1720 // complication - don't inerpret two doubles (as the only args)
1721 // as a lat,lon pair - only do so if we have at least three args.
1722 if (argc > 2) {
1723 argOffset = geodFromArgs(args, 0, argc, from);
1724 }
1725
1726 if ((argOffset + 1) >= argc) {
1727 naRuntimeError(c, "isufficent arguments to greatCircleMove");
1728 }
1729
1730 if (!naIsNum(args[argOffset]) || !naIsNum(args[argOffset+1])) {
1731 naRuntimeError(c, "invalid arguments %d and %d to greatCircleMove",
1732 argOffset, argOffset + 1);
1733 }
1734
1735 double course = args[argOffset].num, course2;
1736 double distanceNm = args[argOffset + 1].num;
1737 SGGeodesy::direct(from, course, distanceNm * SG_NM_TO_METER, to, course2);
1738
1739 // return geo.Coord
1740 naRef coord = naNewHash(c);
1741 hashset(c, coord, "lat", naNum(to.getLatitudeDeg()));
1742 hashset(c, coord, "lon", naNum(to.getLongitudeDeg()));
1743 return coord;
1744 }
1745
1746 static naRef f_tilePath(naContext c, naRef me, int argc, naRef* args)
1747 {
1748 SGGeod pos = globals->get_aircraft_position();
1749 geodFromArgs(args, 0, argc, pos);
1750 SGBucket b(pos);
1751 return stringToNasal(c, b.gen_base_path());
1752 }
1753
1754 static naRef f_tileIndex(naContext c, naRef me, int argc, naRef* args)
1755 {
1756 SGGeod pos = globals->get_aircraft_position();
1757 geodFromArgs(args, 0, argc, pos);
1758 SGBucket b(pos);
1759 return naNum(b.gen_index());
1760 }
1761
1762 static naRef f_createWaypoint(naContext c, naRef me, int argc, naRef* args)
1763 {
1764 if ((argc < 3) || !naIsString(args[0]) || !naIsString(args[1])) {
1765 naRuntimeError(c, "createWaypoint: expects type and ident as first two args");
1766 }
1767
1768 std::string typeSpec(naStr_data(args[0]));
1769 std::string ident(naStr_data(args[1]));
1770 std::string name;
1771
1772 FGPositioned::Type wptType = FGPositioned::typeFromName(typeSpec);
1773
1774 SGGeod pos;
1775 int argOffset = geodFromArgs(args, 2, argc, pos) + 2;
1776 if ((argc > argOffset) && naIsString(args[argOffset])) {
1777 name = naStr_data(args[argOffset]);
1778 ++argOffset;
1779 }
1780
1781 bool isTemporary = false;
1782 if ((argc > argOffset) && naIsNum(args[argOffset])) {
1783 isTemporary = (args[argOffset].num > 0);
1784 }
1785
1786 try {
1787 auto wpt = FGPositioned::createWaypoint(wptType, ident, pos, isTemporary, name);
1788 if (wptType == FGPositioned::FIX) {
1789 return ghostForFix(c, fgpositioned_cast<FGFix>(wpt));
1790 }
1791
1792 auto poi = fgpositioned_cast<POI>(wpt);
1793 return ghostForPOI(c, poi);
1794 } catch (std::exception& e) {
1795 naRuntimeError(c, "Failed to create waypoint: %s", e.what());
1796 }
1797
1798 return naNil();
1799 }
1800
1801
1802 static naRef f_deleteWaypoint(naContext c, naRef me, int argc, naRef* args)
1803 {
1804 if (argc < 1) {
1805 naRuntimeError(c, "deleteWaypoint: missing argument");
1806 }
1807
1808 FGPositioned* wpt = poiGhost(args[0]);
1809 if (!wpt && naIsNum(args[0])) {
1810 PositionedID guid = static_cast<PositionedID>(args[0].num);
1811 wpt = NavDataCache::instance()->loadById(guid);
1812 if (!POI::isType(wpt->type())) {
1813 naRuntimeError(c, "deleteWaypoint: only waypoints can be deleted for now");
1814 }
1815 }
1816
1817 FGPositioned::deleteWaypoint(wpt);
1818 // note wpt is dead here, don't access
1819 return naNil();
1820 }
1821
1822 static naRef f_waypoint_move(naContext c, naRef me, int argc, naRef* args)
1823 {
1824 POI* wpt = poiGhost(me);
1825 if (!wpt) {
1826 naRuntimeError(c, "waypoint.move called on non-POI object");
1827 }
1828
1829 SGGeod pos;
1830 geodFromArgs(args, 0, argc, pos);
1831
1832 NavDataCache::instance()->updatePosition(wpt->guid(), pos);
1833 return naNil();
1834 }
1835
1836 void shutdownNasalPositioned()
1837 {
1838 }
1839
1840 FGPositionedRef positionedFromArg(naRef ref)
1841 {
1842 if (!naIsGhost(ref))
1843 return {};
1844
1845 naGhostType* gt = naGhost_type(ref);
1846 if (gt == &AirportGhostType)
1847 return airportGhost(ref);
1848
1849 if (gt == &NavaidGhostType)
1850 return navaidGhost(ref);
1851
1852 if (gt == &RunwayGhostType)
1853 return runwayGhost(ref);
1854
1855 if (gt == &TaxiwayGhostType)
1856 return taxiwayGhost(ref);
1857
1858 if (gt == &FixGhostType)
1859 return fixGhost(ref);
1860
1861 auto wpg = wayptGhost(ref);
1862 if (wpg)
1863 return wpg->source();
1864
1865 return {};
1866 }
1867
1868 // Table of extension functions. Terminate with zeros.
1869 static struct {
1870 const char* name;
1871 naCFunction func;
1872 } funcs[] = {
1873 {"carttogeod", f_carttogeod},
1874 {"geodtocart", f_geodtocart},
1875 {"geodinfo", f_geodinfo},
1876 {"formatLatLon", f_formatLatLon},
1877 {"parseStringAsLatLonValue", f_parseStringAsLatLonValue},
1878 {"get_cart_ground_intersection", f_get_cart_ground_intersection},
1879 {"aircraftToCart", f_aircraftToCart},
1880 {"airportinfo", f_airportinfo},
1881 {"findAirportsWithinRange", f_findAirportsWithinRange},
1882 {"findAirportsByICAO", f_findAirportsByICAO},
1883 {"navinfo", f_navinfo},
1884 {"findNavaidsWithinRange", f_findNavaidsWithinRange},
1885 {"findNDBByFrequencyKHz", f_findNDBByFrequency},
1886 {"findNDBsByFrequencyKHz", f_findNDBsByFrequency},
1887 {"findNavaidByFrequencyMHz", f_findNavaidByFrequency},
1888 {"findNavaidsByFrequencyMHz", f_findNavaidsByFrequency},
1889 {"findCommByFrequencyMHz", f_findCommByFrequency},
1890 {"findCommsByFrequencyMHz", f_findCommsByFrequency},
1891 {"findNavaidsByID", f_findNavaidsByIdent},
1892 {"findFixesByID", f_findFixesByIdent},
1893 {"findByIdent", f_findByIdent},
1894 {"magvar", f_magvar},
1895 {"courseAndDistance", f_courseAndDistance},
1896 {"greatCircleMove", f_greatCircleMove},
1897 {"tileIndex", f_tileIndex},
1898 {"tilePath", f_tilePath},
1899 {"createWaypoint", f_createWaypoint},
1900 {"deleteWaypoint", f_deleteWaypoint},
1901 {0, 0}};
1902
1903
1904 naRef initNasalPositioned(naRef globals, naContext c)
1905 {
1906 airportPrototype = naNewHash(c);
1907 naSave(c, airportPrototype);
1908
1909 hashset(c, airportPrototype, "runway", naNewFunc(c, naNewCCode(c, f_airport_runway)));
1910 hashset(c, airportPrototype, "runwaysWithoutReciprocals", naNewFunc(c, naNewCCode(c, f_airport_runwaysWithoutReciprocals)));
1911 hashset(c, airportPrototype, "helipad", naNewFunc(c, naNewCCode(c, f_airport_runway)));
1912 hashset(c, airportPrototype, "tower", naNewFunc(c, naNewCCode(c, f_airport_tower)));
1913 hashset(c, airportPrototype, "comms", naNewFunc(c, naNewCCode(c, f_airport_comms)));
1914 hashset(c, airportPrototype, "sids", naNewFunc(c, naNewCCode(c, f_airport_sids)));
1915 hashset(c, airportPrototype, "stars", naNewFunc(c, naNewCCode(c, f_airport_stars)));
1916 hashset(c, airportPrototype, "getApproachList", naNewFunc(c, naNewCCode(c, f_airport_approaches)));
1917 hashset(c, airportPrototype, "parking", naNewFunc(c, naNewCCode(c, f_airport_parking)));
1918 hashset(c, airportPrototype, "getSid", naNewFunc(c, naNewCCode(c, f_airport_getSid)));
1919 hashset(c, airportPrototype, "getStar", naNewFunc(c, naNewCCode(c, f_airport_getStar)));
1920
1921 naRef approachFunc = naNewFunc(c, naNewCCode(c, f_airport_getApproach));
1922
1923 // allow this to be used under either name
1924 hashset(c, airportPrototype, "getIAP", approachFunc);
1925 hashset(c, airportPrototype, "getApproach", approachFunc);
1926
1927 hashset(c, airportPrototype, "findBestRunwayForPos", naNewFunc(c, naNewCCode(c, f_airport_findBestRunway)));
1928 hashset(c, airportPrototype, "tostring", naNewFunc(c, naNewCCode(c, f_airport_toString)));
1929
1930 waypointPrototype = naNewHash(c);
1931 naSave(c, waypointPrototype);
1932 hashset(c, waypointPrototype, "move", naNewFunc(c, naNewCCode(c, f_waypoint_move)));
1933
1934 for(int i=0; funcs[i].name; i++) {
1935 hashset(c, globals, funcs[i].name,
1936 naNewFunc(c, naNewCCode(c, funcs[i].func)));
1937 }
1938
1939 return naNil();
1940 }
1941
1942 void postinitNasalPositioned(naRef globals, naContext c)
1943 {
1944 naRef geoModule = naHash_cget(globals, (char*) "geo");
1945 if (naIsNil(geoModule)) {
1946 SG_LOG(SG_GENERAL, SG_WARN, "postinitNasalPositioned: geo.nas not loaded");
1947 return;
1948 }
1949
1950 geoCoordClass = naHash_cget(geoModule, (char*) "Coord");
1951 }