]> git.mxchange.org Git - flightgear.git/blob - src/Scripting/NasalPositioned.cxx
a813e23511d22a3cdbb0f76007d2f157a31b2822
[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 "NasalPositioned.hxx"
26
27 #include <simgear/scene/material/mat.hxx>
28 #include <simgear/magvar/magvar.hxx>
29 #include <simgear/timing/sg_time.hxx>
30
31 #include <Airports/runways.hxx>
32 #include <Airports/simple.hxx>
33 #include <Navaids/navlist.hxx>
34 #include <Navaids/procedure.hxx>
35 #include <Main/globals.hxx>
36 #include <Main/fg_props.hxx>
37 #include <Scenery/scenery.hxx>
38
39
40 static void ghostDestroy(void* g);
41 naGhostType PositionedGhostType = { ghostDestroy, "positioned" };
42
43 static FGPositioned* positionedGhost(naRef r)
44 {
45     if (naGhost_type(r) == &PositionedGhostType)
46         return (FGPositioned*) naGhost_ptr(r);
47     return 0;
48 }
49
50
51 static void ghostDestroy(void* g)
52 {
53     FGPositioned* pos = (FGPositioned*)g;
54     SGReferenced::put(pos); // unref
55 }
56
57 naRef ghostForPositioned(naContext c, const FGPositioned* pos)
58 {
59     if (!pos) {
60         return naNil();
61     }
62     
63     SGReferenced::get(pos); // take a ref
64     return naNewGhost(c, &PositionedGhostType, (void*) pos);
65 }
66
67 naRef hashForAirport(naContext c, const FGAirport* apt)
68 {
69     std::string id = apt->ident();
70     std::string name = apt->name();
71     
72   // build runways hash
73     naRef rwys = naNewHash(c);
74     for(unsigned int r=0; r<apt->numRunways(); ++r) {
75       FGRunway* rwy(apt->getRunwayByIndex(r));
76     
77       naRef rwyid = naStr_fromdata(naNewString(c),
78                                  const_cast<char *>(rwy->ident().c_str()),
79                                  rwy->ident().length());
80       naRef rwydata = hashForRunway(c, rwy);
81       naHash_set(rwys, rwyid, rwydata);
82     }
83   
84     naRef aptdata = naNewHash(c);
85 #define HASHSET(s,l,n) naHash_set(aptdata, naStr_fromdata(naNewString(c),s,l),n)
86     HASHSET("id", 2, naStr_fromdata(naNewString(c),
87             const_cast<char *>(id.c_str()), id.length()));
88     HASHSET("name", 4, naStr_fromdata(naNewString(c),
89             const_cast<char *>(name.c_str()), name.length()));
90     HASHSET("lat", 3, naNum(apt->getLatitude()));
91     HASHSET("lon", 3, naNum(apt->getLongitude()));
92     HASHSET("elevation", 9, naNum(apt->getElevation() * SG_FEET_TO_METER));
93     HASHSET("has_metar", 9, naNum(apt->getMetar()));
94     HASHSET("runways", 7, rwys);
95     
96     HASHSET("_positioned", 11, ghostForPositioned(c, apt));
97 #undef HASHSET
98     
99     return aptdata;
100 }
101
102 naRef hashForRunway(naContext c, FGRunway* rwy)
103 {
104     naRef rwyid = naStr_fromdata(naNewString(c),
105                   const_cast<char *>(rwy->ident().c_str()),
106                   rwy->ident().length());
107
108     naRef rwydata = naNewHash(c);
109 #define HASHSET(s,l,n) naHash_set(rwydata, naStr_fromdata(naNewString(c),s,l),n)
110     HASHSET("id", 2, rwyid);
111     HASHSET("lat", 3, naNum(rwy->latitude()));
112     HASHSET("lon", 3, naNum(rwy->longitude()));
113     HASHSET("heading", 7, naNum(rwy->headingDeg()));
114     HASHSET("length", 6, naNum(rwy->lengthM()));
115     HASHSET("width", 5, naNum(rwy->widthM()));
116     HASHSET("threshold", 9, naNum(rwy->displacedThresholdM()));
117     HASHSET("stopway", 7, naNum(rwy->stopwayM()));
118         
119     if (rwy->ILS()) {
120       HASHSET("ils_frequency_mhz", 17, naNum(rwy->ILS()->get_freq() / 100.0));
121     }
122         
123     std::vector<flightgear::SID*> sids(rwy->getSIDs());
124     naRef sidVec = naNewVector(c);
125         
126     for (unsigned int s=0; s < sids.size(); ++s) {
127       naRef procId = naStr_fromdata(naNewString(c),
128                 const_cast<char *>(sids[s]->ident().c_str()),
129                 sids[s]->ident().length());
130       naVec_append(sidVec, procId);
131     }
132     HASHSET("sids", 4, sidVec); 
133         
134     std::vector<flightgear::STAR*> stars(rwy->getSTARs());
135     naRef starVec = naNewVector(c);
136       
137     for (unsigned int s=0; s < stars.size(); ++s) {
138       naRef procId = naStr_fromdata(naNewString(c),
139                 const_cast<char *>(stars[s]->ident().c_str()),
140                 stars[s]->ident().length());
141       naVec_append(starVec, procId);
142     }
143     HASHSET("stars", 5, starVec); 
144     
145     HASHSET("_positioned", 11, ghostForPositioned(c, rwy));
146 #undef HASHSET
147     return rwydata;
148 }
149
150 naRef hashForNavRecord(naContext c, const FGNavRecord* nav, const SGGeod& rel)
151 {
152     naRef navdata = naNewHash(c);
153 #define HASHSET(s,l,n) naHash_set(navdata, naStr_fromdata(naNewString(c),s,l),n)
154     HASHSET("id", 2, naStr_fromdata(naNewString(c),
155         const_cast<char *>(nav->ident().c_str()), nav->ident().length()));
156     HASHSET("name", 4, naStr_fromdata(naNewString(c),
157         const_cast<char *>(nav->name().c_str()), nav->name().length()));
158     HASHSET("frequency", 9, naNum(nav->get_freq()));
159     HASHSET("lat", 3, naNum(nav->get_lat()));
160     HASHSET("lon", 3, naNum(nav->get_lon()));
161     HASHSET("elevation", 9, naNum(nav->get_elev_ft() * SG_FEET_TO_METER));
162     HASHSET("type", 4, naStr_fromdata(naNewString(c),
163         const_cast<char *>(nav->nameForType(nav->type())), strlen(nav->nameForType(nav->type()))));
164     HASHSET("distance", 8, naNum(SGGeodesy::distanceNm( rel, nav->geod() ) * SG_NM_TO_METER ) );
165     HASHSET("bearing", 7, naNum(SGGeodesy::courseDeg( rel, nav->geod() ) ) );
166     
167     // record the real object as a ghost for further operations
168     HASHSET("_positioned",11, ghostForPositioned(c, nav));
169 #undef HASHSET
170     
171     return navdata;
172 }
173
174 bool geodFromHash(naRef ref, SGGeod& result)
175 {
176   if (!naIsHash(ref)) {
177     return false;
178   }
179   
180 // first, see if the hash contains a FGPositioned ghost - in which case
181 // we can read off its position directly
182   naRef posGhost = naHash_cget(ref, (char*) "_positioned");
183   if (!naIsNil(posGhost)) {
184     FGPositioned* pos = positionedGhost(posGhost);
185     result = pos->geod();
186     return true;
187   }
188   
189 // then check for manual latitude / longitude names
190   naRef lat = naHash_cget(ref, (char*) "lat");
191   naRef lon = naHash_cget(ref, (char*) "lon");
192   if (naIsNum(lat) && naIsNum(lon)) {
193     result = SGGeod::fromDeg(naNumValue(lat).num, naNumValue(lon).num);
194     return true;
195   }
196   
197 // check for any synonyms?
198 // latitude + longitude?
199   
200   return false;
201 }
202
203 // Convert a cartesian point to a geodetic lat/lon/altitude.
204 static naRef f_carttogeod(naContext c, naRef me, int argc, naRef* args)
205 {
206   double lat, lon, alt, xyz[3];
207   if(argc != 3) naRuntimeError(c, "carttogeod() expects 3 arguments");
208   for(int i=0; i<3; i++)
209     xyz[i] = naNumValue(args[i]).num;
210   sgCartToGeod(xyz, &lat, &lon, &alt);
211   lat *= SG_RADIANS_TO_DEGREES;
212   lon *= SG_RADIANS_TO_DEGREES;
213   naRef vec = naNewVector(c);
214   naVec_append(vec, naNum(lat));
215   naVec_append(vec, naNum(lon));
216   naVec_append(vec, naNum(alt));
217   return vec;
218 }
219
220 // Convert a geodetic lat/lon/altitude to a cartesian point.
221 static naRef f_geodtocart(naContext c, naRef me, int argc, naRef* args)
222 {
223   if(argc != 3) naRuntimeError(c, "geodtocart() expects 3 arguments");
224   double lat = naNumValue(args[0]).num * SG_DEGREES_TO_RADIANS;
225   double lon = naNumValue(args[1]).num * SG_DEGREES_TO_RADIANS;
226   double alt = naNumValue(args[2]).num;
227   double xyz[3];
228   sgGeodToCart(lat, lon, alt, xyz);
229   naRef vec = naNewVector(c);
230   naVec_append(vec, naNum(xyz[0]));
231   naVec_append(vec, naNum(xyz[1]));
232   naVec_append(vec, naNum(xyz[2]));
233   return vec;
234 }
235
236 // For given geodetic point return array with elevation, and a material data
237 // hash, or nil if there's no information available (tile not loaded). If
238 // information about the material isn't available, then nil is returned instead
239 // of the hash.
240 static naRef f_geodinfo(naContext c, naRef me, int argc, naRef* args)
241 {
242 #define HASHSET(s,l,n) naHash_set(matdata, naStr_fromdata(naNewString(c),s,l),n)
243   if(argc < 2 || argc > 3)
244     naRuntimeError(c, "geodinfo() expects 2 or 3 arguments: lat, lon [, maxalt]");
245   double lat = naNumValue(args[0]).num;
246   double lon = naNumValue(args[1]).num;
247   double elev = argc == 3 ? naNumValue(args[2]).num : 10000;
248   const SGMaterial *mat;
249   SGGeod geod = SGGeod::fromDegM(lon, lat, elev);
250   if(!globals->get_scenery()->get_elevation_m(geod, elev, &mat))
251     return naNil();
252   naRef vec = naNewVector(c);
253   naVec_append(vec, naNum(elev));
254   naRef matdata = naNil();
255   if(mat) {
256     matdata = naNewHash(c);
257     naRef names = naNewVector(c);
258     const std::vector<std::string> n = mat->get_names();
259     for(unsigned int i=0; i<n.size(); i++)
260       naVec_append(names, naStr_fromdata(naNewString(c),
261                                          const_cast<char*>(n[i].c_str()), n[i].size()));
262     HASHSET("names", 5, names);
263     HASHSET("solid", 5, naNum(mat->get_solid()));
264     HASHSET("friction_factor", 15, naNum(mat->get_friction_factor()));
265     HASHSET("rolling_friction", 16, naNum(mat->get_rolling_friction()));
266     HASHSET("load_resistance", 15, naNum(mat->get_load_resistance()));
267     HASHSET("bumpiness", 9, naNum(mat->get_bumpiness()));
268     HASHSET("light_coverage", 14, naNum(mat->get_light_coverage()));
269   }
270   naVec_append(vec, matdata);
271   return vec;
272 #undef HASHSET
273 }
274
275
276 class AirportInfoFilter : public FGAirport::AirportFilter
277 {
278 public:
279   AirportInfoFilter() : type(FGPositioned::AIRPORT) {
280   }
281   
282   virtual FGPositioned::Type minType() const {
283     return type;
284   }
285   
286   virtual FGPositioned::Type maxType() const {
287     return type;
288   }
289   
290   FGPositioned::Type type;
291 };
292
293 // Returns data hash for particular or nearest airport of a <type>, or nil
294 // on error.
295 //
296 // airportinfo(<id>);                   e.g. "KSFO"
297 // airportinfo(<type>);                 type := ("airport"|"seaport"|"heliport")
298 // airportinfo()                        same as  airportinfo("airport")
299 // airportinfo(<lat>, <lon> [, <type>]);
300 static naRef f_airportinfo(naContext c, naRef me, int argc, naRef* args)
301 {
302   static SGConstPropertyNode_ptr latn = fgGetNode("/position/latitude-deg", true);
303   static SGConstPropertyNode_ptr lonn = fgGetNode("/position/longitude-deg", true);
304   SGGeod pos;
305   FGAirport* apt = NULL;
306   
307   if(argc >= 2 && naIsNum(args[0]) && naIsNum(args[1])) {
308     pos = SGGeod::fromDeg(args[1].num, args[0].num);
309     args += 2;
310     argc -= 2;
311   } else {
312     pos = SGGeod::fromDeg(lonn->getDoubleValue(), latn->getDoubleValue());
313   }
314   
315   double maxRange = 10000.0; // expose this? or pick a smaller value?
316   
317   AirportInfoFilter filter; // defaults to airports only
318   
319   if(argc == 0) {
320     // fall through and use AIRPORT
321   } else if(argc == 1 && naIsString(args[0])) {
322     const char *s = naStr_data(args[0]);
323     if(!strcmp(s, "airport")) filter.type = FGPositioned::AIRPORT;
324     else if(!strcmp(s, "seaport")) filter.type = FGPositioned::SEAPORT;
325     else if(!strcmp(s, "heliport")) filter.type = FGPositioned::HELIPORT;
326     else {
327       // user provided an <id>, hopefully
328       apt = FGAirport::findByIdent(s);
329       if (!apt) {
330         // return nil here, but don't raise a runtime error; this is a
331         // legitamate way to validate an ICAO code, for example in a
332         // dialog box or similar.
333         return naNil();
334       }
335     }
336   } else {
337     naRuntimeError(c, "airportinfo() with invalid function arguments");
338     return naNil();
339   }
340   
341   if(!apt) {
342     apt = FGAirport::findClosest(pos, maxRange, &filter);
343     if(!apt) return naNil();
344   }
345   
346   std::string id = apt->ident();
347   std::string name = apt->name();
348   
349   // set runway hash
350   naRef rwys = naNewHash(c);
351   for(unsigned int r=0; r<apt->numRunways(); ++r) {
352     FGRunway* rwy(apt->getRunwayByIndex(r));
353     
354     naRef rwyid = naStr_fromdata(naNewString(c),
355                                  const_cast<char *>(rwy->ident().c_str()),
356                                  rwy->ident().length());
357     
358     naRef rwydata = naNewHash(c);
359 #define HASHSET(s,l,n) naHash_set(rwydata, naStr_fromdata(naNewString(c),s,l),n)
360     HASHSET("id", 2, rwyid);
361     HASHSET("lat", 3, naNum(rwy->latitude()));
362     HASHSET("lon", 3, naNum(rwy->longitude()));
363     HASHSET("heading", 7, naNum(rwy->headingDeg()));
364     HASHSET("length", 6, naNum(rwy->lengthM()));
365     HASHSET("width", 5, naNum(rwy->widthM()));
366     HASHSET("threshold", 9, naNum(rwy->displacedThresholdM()));
367     HASHSET("stopway", 7, naNum(rwy->stopwayM()));
368     
369     if (rwy->ILS()) {
370       HASHSET("ils_frequency_mhz", 17, naNum(rwy->ILS()->get_freq() / 100.0));
371     }
372     
373     std::vector<flightgear::SID*> sids(rwy->getSIDs());
374     naRef sidVec = naNewVector(c);
375     
376     for (unsigned int s=0; s < sids.size(); ++s) {
377       naRef procId = naStr_fromdata(naNewString(c),
378                                     const_cast<char *>(sids[s]->ident().c_str()),
379                                     sids[s]->ident().length());
380       naVec_append(sidVec, procId);
381     }
382     HASHSET("sids", 4, sidVec); 
383     
384     std::vector<flightgear::STAR*> stars(rwy->getSTARs());
385     naRef starVec = naNewVector(c);
386     
387     for (unsigned int s=0; s < stars.size(); ++s) {
388       naRef procId = naStr_fromdata(naNewString(c),
389                                     const_cast<char *>(stars[s]->ident().c_str()),
390                                     stars[s]->ident().length());
391       naVec_append(starVec, procId);
392     }
393     HASHSET("stars", 5, starVec); 
394     
395 #undef HASHSET
396     naHash_set(rwys, rwyid, rwydata);
397   }
398   
399   // set airport hash
400   naRef aptdata = naNewHash(c);
401 #define HASHSET(s,l,n) naHash_set(aptdata, naStr_fromdata(naNewString(c),s,l),n)
402   HASHSET("id", 2, naStr_fromdata(naNewString(c),
403                                   const_cast<char *>(id.c_str()), id.length()));
404   HASHSET("name", 4, naStr_fromdata(naNewString(c),
405                                     const_cast<char *>(name.c_str()), name.length()));
406   HASHSET("lat", 3, naNum(apt->getLatitude()));
407   HASHSET("lon", 3, naNum(apt->getLongitude()));
408   HASHSET("elevation", 9, naNum(apt->getElevation() * SG_FEET_TO_METER));
409   HASHSET("has_metar", 9, naNum(apt->getMetar()));
410   HASHSET("runways", 7, rwys);
411 #undef HASHSET
412   return aptdata;
413 }
414
415
416 // Returns vector of data hash for navaid of a <type>, nil on error
417 // navaids sorted by ascending distance 
418 // navinfo([<lat>,<lon>],[<type>],[<id>])
419 // lat/lon (numeric): use latitude/longitude instead of ac position
420 // type:              ("fix"|"vor"|"ndb"|"ils"|"dme"|"tacan"|"any")
421 // id:                (partial) id of the fix
422 // examples:
423 // navinfo("vor")     returns all vors
424 // navinfo("HAM")     return all navaids who's name start with "HAM"
425 // navinfo("vor", "HAM") return all vor who's name start with "HAM"
426 //navinfo(34,48,"vor","HAM") return all vor who's name start with "HAM" 
427 //                           sorted by distance relative to lat=34, lon=48
428 static naRef f_navinfo(naContext c, naRef me, int argc, naRef* args)
429 {
430   static SGConstPropertyNode_ptr latn = fgGetNode("/position/latitude-deg", true);
431   static SGConstPropertyNode_ptr lonn = fgGetNode("/position/longitude-deg", true);
432   SGGeod pos;
433   
434   if(argc >= 2 && naIsNum(args[0]) && naIsNum(args[1])) {
435     pos = SGGeod::fromDeg(args[1].num, args[0].num);
436     args += 2;
437     argc -= 2;
438   } else {
439     pos = SGGeod::fromDeg(lonn->getDoubleValue(), latn->getDoubleValue());
440   }
441   
442   FGPositioned::Type type = FGPositioned::INVALID;
443   nav_list_type navlist;
444   const char * id = "";
445   
446   if(argc > 0 && naIsString(args[0])) {
447     const char *s = naStr_data(args[0]);
448     if(!strcmp(s, "any")) type = FGPositioned::INVALID;
449     else if(!strcmp(s, "fix")) type = FGPositioned::FIX;
450     else if(!strcmp(s, "vor")) type = FGPositioned::VOR;
451     else if(!strcmp(s, "ndb")) type = FGPositioned::NDB;
452     else if(!strcmp(s, "ils")) type = FGPositioned::ILS;
453     else if(!strcmp(s, "dme")) type = FGPositioned::DME;
454     else if(!strcmp(s, "tacan")) type = FGPositioned::TACAN;
455     else id = s; // this is an id
456     ++args;
457     --argc;
458   } 
459   
460   if(argc > 0 && naIsString(args[0])) {
461     if( *id != 0 ) {
462       naRuntimeError(c, "navinfo() called with navaid id");
463       return naNil();
464     }
465     id = naStr_data(args[0]);
466     ++args;
467     --argc;
468   }
469   
470   if( argc > 0 ) {
471     naRuntimeError(c, "navinfo() called with too many arguments");
472     return naNil();
473   }
474   
475   navlist = globals->get_navlist()->findByIdentAndFreq( pos, id, 0.0, type );
476   
477   naRef reply = naNewVector(c);
478   for( nav_list_type::const_iterator it = navlist.begin(); it != navlist.end(); ++it ) {
479     const FGNavRecord * nav = *it;
480     
481     // set navdata hash
482     naRef navdata = naNewHash(c);
483 #define HASHSET(s,l,n) naHash_set(navdata, naStr_fromdata(naNewString(c),s,l),n)
484     HASHSET("id", 2, naStr_fromdata(naNewString(c),
485                                     const_cast<char *>(nav->ident().c_str()), nav->ident().length()));
486     HASHSET("name", 4, naStr_fromdata(naNewString(c),
487                                       const_cast<char *>(nav->name().c_str()), nav->name().length()));
488     HASHSET("frequency", 9, naNum(nav->get_freq()));
489     HASHSET("lat", 3, naNum(nav->get_lat()));
490     HASHSET("lon", 3, naNum(nav->get_lon()));
491     HASHSET("elevation", 9, naNum(nav->get_elev_ft() * SG_FEET_TO_METER));
492     HASHSET("type", 4, naStr_fromdata(naNewString(c),
493                                       const_cast<char *>(nav->nameForType(nav->type())), strlen(nav->nameForType(nav->type()))));
494     HASHSET("distance", 8, naNum(SGGeodesy::distanceNm( pos, nav->geod() ) * SG_NM_TO_METER ) );
495     HASHSET("bearing", 7, naNum(SGGeodesy::courseDeg( pos, nav->geod() ) ) );
496 #undef HASHSET
497     naVec_append( reply, navdata );
498   }
499   return reply;
500 }
501
502 // Convert a cartesian point to a geodetic lat/lon/altitude.
503 static naRef f_magvar(naContext c, naRef me, int argc, naRef* args)
504 {
505   SGGeod pos;
506   if ((argc == 1) && geodFromHash(args[0], pos)) {
507     // okay
508   } else if (argc == 2) {
509     double lat = naNumValue(args[0]).num,
510       lon = naNumValue(args[1]).num;
511     pos = SGGeod::fromDeg(lon, lat);
512   } else {
513     naRuntimeError(c, "magvar() expects 1 object arugment, or a lat/lon");
514   }
515   
516   double jd = globals->get_time_params()->getJD();
517   double magvarDeg = sgGetMagVar(pos, jd);
518   return naNum(magvarDeg);
519 }
520
521 // Table of extension functions.  Terminate with zeros.
522 static struct { const char* name; naCFunction func; } funcs[] = {
523   { "carttogeod", f_carttogeod },
524   { "geodtocart", f_geodtocart },
525   { "geodinfo", f_geodinfo },
526   { "airportinfo", f_airportinfo },
527   { "magvar", f_magvar },
528   { 0, 0 }
529 };
530
531 static void hashset(naContext c, naRef hash, const char* key, naRef val)
532 {
533   naRef s = naNewString(c);
534   naStr_fromdata(s, (char*)key, strlen(key));
535   naHash_set(hash, s, val);
536 }
537
538 naRef initNasalPositioned(naRef globals, naContext c)
539 {
540   for(int i=0; funcs[i].name; i++) {
541     hashset(c, globals, funcs[i].name,
542             naNewFunc(c, naNewCCode(c, funcs[i].func)));
543   }
544   
545   return naNil();
546 }
547