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