]> git.mxchange.org Git - flightgear.git/blob - src/Scripting/NasalPositioned_cppbind.cxx
NasalTimerObject tweaks.
[flightgear.git] / src / Scripting / NasalPositioned_cppbind.cxx
1 // NasalPositioned_cppbind.cxx -- expose FGPositioned classes to Nasal
2 //
3 // Port of NasalPositioned.cpp to the new nasal/cppbind helpers. Will replace
4 // old NasalPositioned.cpp once finished.
5 //
6 // Copyright (C) 2013  Thomas Geymayer <tomgey@gmail.com>
7 //
8 // This program is free software; you can redistribute it and/or
9 // modify it under the terms of the GNU General Public License as
10 // published by the Free Software Foundation; either version 2 of the
11 // License, or (at your option) any later version.
12 //
13 // This program is distributed in the hope that it will be useful, but
14 // WITHOUT ANY WARRANTY; without even the implied warranty of
15 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16 // General Public License for more details.
17 //
18 // You should have received a copy of the GNU General Public License
19 // along with this program; if not, write to the Free Software
20 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
21
22 #ifdef HAVE_CONFIG_H
23 #  include "config.h"
24 #endif
25
26 #include "NasalPositioned.hxx"
27
28 #include <algorithm>
29 #include <functional>
30
31 #include <boost/foreach.hpp>
32 #include <boost/algorithm/string/case_conv.hpp>
33
34 #include <simgear/nasal/cppbind/from_nasal.hxx>
35 #include <simgear/nasal/cppbind/to_nasal.hxx>
36 #include <simgear/nasal/cppbind/NasalHash.hxx>
37 #include <simgear/nasal/cppbind/Ghost.hxx>
38
39 #include <Airports/airport.hxx>
40 #include <Airports/dynamics.hxx>
41 #include <Airports/pavement.hxx>
42 #include <ATC/CommStation.hxx>
43 #include <Main/globals.hxx>
44 #include <Navaids/NavDataCache.hxx>
45 #include <Navaids/navlist.hxx>
46 #include <Navaids/navrecord.hxx>
47 #include <Navaids/fix.hxx>
48
49 typedef nasal::Ghost<FGPositionedRef> NasalPositioned;
50 typedef nasal::Ghost<FGRunwayRef> NasalRunway;
51 typedef nasal::Ghost<FGParkingRef> NasalParking;
52 typedef nasal::Ghost<FGAirportRef> NasalAirport;
53 typedef nasal::Ghost<flightgear::CommStationRef> NasalCommStation;
54 typedef nasal::Ghost<FGNavRecordRef> NasalNavRecord;
55 typedef nasal::Ghost<FGRunwayRef> NasalRunway;
56 typedef nasal::Ghost<FGFixRef> NasalFix;
57
58 //------------------------------------------------------------------------------
59 naRef to_nasal_helper(naContext c, flightgear::SID* sid)
60 {
61   // TODO SID ghost
62   return nasal::to_nasal(c, sid->ident());
63 }
64
65 //------------------------------------------------------------------------------
66 naRef to_nasal_helper(naContext c, flightgear::STAR* star)
67 {
68   // TODO STAR ghost
69   return nasal::to_nasal(c, star->ident());
70 }
71
72 //------------------------------------------------------------------------------
73 naRef to_nasal_helper(naContext c, flightgear::Approach* iap)
74 {
75   // TODO Approach ghost
76   return nasal::to_nasal(c, iap->ident());
77 }
78
79 //------------------------------------------------------------------------------
80 naRef to_nasal_helper(naContext c, const SGGeod& pos)
81 {
82   nasal::Hash hash(c);
83   hash.set("lat", pos.getLatitudeDeg());
84   hash.set("lon", pos.getLongitudeDeg());
85   hash.set("elevation", pos.getElevationM());
86   return hash.get_naRef();
87 }
88
89 //------------------------------------------------------------------------------
90 static naRef f_navaid_course(naContext, FGNavRecord& nav)
91 {
92   if( !(  nav.type() == FGPositioned::ILS
93        || nav.type() == FGPositioned::LOC
94        ) )
95     return naNil();
96
97   double radial = nav.get_multiuse();
98   return naNum(SGMiscd::normalizePeriodic(0.5, 360.5, radial));
99 }
100
101 //------------------------------------------------------------------------------
102 static FGRunwayBaseRef f_airport_runway(FGAirport& apt, std::string ident)
103 {
104   boost::to_upper(ident);
105
106   if( apt.hasRunwayWithIdent(ident) )
107     return apt.getRunwayByIdent(ident);
108   else if( apt.hasHelipadWithIdent(ident) )
109     return apt.getHelipadByIdent(ident);
110
111   return 0;
112 }
113
114 //------------------------------------------------------------------------------
115 template<class T, class C1, class C2>
116 std::vector<T> extract( const std::vector<C1>& in,
117                         T (C2::*getter)() const )
118 {
119   std::vector<T> ret(in.size());
120   std::transform(in.begin(), in.end(), ret.begin(), std::mem_fun(getter));
121   return ret;
122 }
123
124 //------------------------------------------------------------------------------
125 static naRef f_airport_comms(FGAirport& apt, const nasal::CallContext& ctx)
126 {
127   FGPositioned::Type comm_type =
128     FGPositioned::typeFromName( ctx.getArg<std::string>(0) );
129
130   // if we have an explicit type, return a simple vector of frequencies
131   if( comm_type != FGPositioned::INVALID )
132     return ctx.to_nasal
133     (
134       extract( apt.commStationsOfType(comm_type),
135                &flightgear::CommStation::freqMHz )
136     );
137   else
138     // otherwise return a vector of ghosts, one for each comm station.
139     return ctx.to_nasal(apt.commStations());
140 }
141
142 //------------------------------------------------------------------------------
143 FGRunway* runwayFromNasalArg( const FGAirport& apt,
144                               const nasal::CallContext& ctx,
145                               size_t index = 0 )
146 {
147   if( index >= ctx.argc )
148     return NULL;
149
150   try
151   {
152     std::string ident = ctx.getArg<std::string>(index);
153     if( !ident.empty() )
154     {
155       if( !apt.hasRunwayWithIdent(ident) )
156         // TODO warning/exception?
157         return NULL;
158
159       return apt.getRunwayByIdent(ident);
160     }
161   }
162   catch(...)
163   {}
164
165   // TODO warn/error if no runway?
166   return NasalRunway::fromNasal(ctx.c, ctx.args[index]);
167 }
168
169 //------------------------------------------------------------------------------
170 static naRef f_airport_sids(FGAirport& apt, const nasal::CallContext& ctx)
171 {
172   FGRunway* rwy = runwayFromNasalArg(apt, ctx);
173   return ctx.to_nasal
174   (
175     extract(rwy ? rwy->getSIDs() : apt.getSIDs(), &flightgear::SID::ident)
176   );
177 }
178
179 //------------------------------------------------------------------------------
180 static naRef f_airport_stars(FGAirport& apt, const nasal::CallContext& ctx)
181 {
182   FGRunway* rwy = runwayFromNasalArg(apt, ctx);
183   return ctx.to_nasal
184   (
185     extract(rwy ? rwy->getSTARs() : apt.getSTARs(), &flightgear::STAR::ident)
186   );
187 }
188
189 //------------------------------------------------------------------------------
190 static naRef f_airport_approaches(FGAirport& apt, const nasal::CallContext& ctx)
191 {
192   FGRunway* rwy = runwayFromNasalArg(apt, ctx);
193
194   flightgear::ProcedureType type = flightgear::PROCEDURE_INVALID;
195   std::string type_str = ctx.getArg<std::string>(1);
196   if( !type_str.empty() )
197   {
198     boost::to_upper(type_str);
199     if(      type_str == "NDB" ) type = flightgear::PROCEDURE_APPROACH_NDB;
200     else if( type_str == "VOR" ) type = flightgear::PROCEDURE_APPROACH_VOR;
201     else if( type_str == "ILS" ) type = flightgear::PROCEDURE_APPROACH_ILS;
202     else if( type_str == "RNAV") type = flightgear::PROCEDURE_APPROACH_RNAV;
203   }
204
205   return ctx.to_nasal
206   (
207     extract( rwy ? rwy->getApproaches(type)
208                  // no runway specified, report them all
209                  : apt.getApproaches(type),
210              &flightgear::Approach::ident )
211   );
212 }
213
214 //------------------------------------------------------------------------------
215 static FGParkingList
216 f_airport_parking(FGAirport& apt, nasal::CallContext ctx)
217 {
218   std::string type = ctx.getArg<std::string>(0);
219   bool only_available = ctx.getArg<bool>(1);
220
221   FGAirportDynamics* dynamics = apt.getDynamics();
222   PositionedIDVec parkings =
223     flightgear::NavDataCache::instance()
224       ->airportItemsOfType(apt.guid(), FGPositioned::PARKING);
225
226   FGParkingList ret;
227   BOOST_FOREACH(PositionedID parking, parkings)
228   {
229     // filter out based on availability and type
230     if( only_available && !dynamics->isParkingAvailable(parking) )
231       continue;
232
233     FGParking* park = dynamics->getParking(parking);
234     if( !type.empty() && (park->getType() != type) )
235       continue;
236
237     ret.push_back(park);
238   }
239
240   return ret;
241 }
242
243 /**
244  * Extract a SGGeod from a nasal function argument list.
245  *
246  * <lat>, <lon>
247  * {"lat": <lat-deg>, "lon": <lon-deg>}
248  * geo.Coord.new() (aka. {"_lat": <lat-rad>, "_lon": <lon-rad>})
249  */
250 static bool extractGeod(nasal::CallContext& ctx, SGGeod& result)
251 {
252   if( !ctx.argc )
253     return false;
254
255   if( ctx.isGhost(0) )
256   {
257     FGPositioned* pos =
258       NasalPositioned::fromNasal(ctx.c, ctx.requireArg<naRef>(0));
259
260     if( pos )
261     {
262       result = pos->geod();
263       ctx.popFront();
264       return true;
265     }
266   }
267   else if( ctx.isHash(0) )
268   {
269     nasal::Hash pos_hash = ctx.requireArg<nasal::Hash>(0);
270
271     // check for manual latitude / longitude names
272     naRef lat = pos_hash.get("lat"),
273           lon = pos_hash.get("lon");
274     if( naIsNum(lat) && naIsNum(lon) )
275     {
276       result = SGGeod::fromDeg( ctx.from_nasal<double>(lon),
277                                 ctx.from_nasal<double>(lat) );
278       ctx.popFront();
279       return true;
280     }
281
282     // geo.Coord uses _lat/_lon in radians
283     // TODO should we check if its really a geo.Coord?
284     lat = pos_hash.get("_lat");
285     lon = pos_hash.get("_lon");
286     if( naIsNum(lat) && naIsNum(lon) )
287     {
288       result = SGGeod::fromRad( ctx.from_nasal<double>(lon),
289                                 ctx.from_nasal<double>(lat) );
290       ctx.popFront();
291       return true;
292     }
293   }
294   else if( ctx.isNumeric(0) && ctx.isNumeric(1) )
295   {
296     // lat, lon
297     result = SGGeod::fromDeg( ctx.requireArg<double>(1),
298                               ctx.requireArg<double>(0) );
299     ctx.popFront(2);
300     return true;
301   }
302
303   return false;
304 }
305
306 /**
307  * Extract position from ctx or return current aircraft position if not given.
308  */
309 static SGGeod getPosition(nasal::CallContext& ctx)
310 {
311   SGGeod pos;
312   if( !extractGeod(ctx, pos) )
313     pos = globals->get_aircraft_position();
314
315   return pos;
316 }
317
318 //------------------------------------------------------------------------------
319 // Returns Nasal ghost for particular or nearest airport of a <type>, or nil
320 // on error.
321 //
322 // airportinfo(<id>);                   e.g. "KSFO"
323 // airportinfo(<type>);                 type := ("airport"|"seaport"|"heliport")
324 // airportinfo()                        same as  airportinfo("airport")
325 // airportinfo(<lat>, <lon> [, <type>]);
326 static naRef f_airportinfo(nasal::CallContext ctx)
327 {
328   SGGeod pos = getPosition(ctx);
329
330   if( ctx.argc > 1 )
331     naRuntimeError(ctx.c, "airportinfo() with invalid function arguments");
332
333   // optional type/ident
334   std::string ident("airport");
335   if( ctx.isString(0) )
336     ident = ctx.requireArg<std::string>(0);
337
338   FGAirport::TypeRunwayFilter filter;
339   if( !filter.fromTypeString(ident) )
340     // user provided an <id>, hopefully
341     return ctx.to_nasal(FGAirport::findByIdent(ident));
342
343   double maxRange = 10000.0; // expose this? or pick a smaller value?
344   return ctx.to_nasal( FGAirport::findClosest(pos, maxRange, &filter) );
345 }
346
347 /**
348  * findAirportsWithinRange([<position>,] <range-nm> [, type])
349  */
350 static naRef f_findAirportsWithinRange(nasal::CallContext ctx)
351 {
352   SGGeod pos = getPosition(ctx);
353   double range_nm = ctx.requireArg<double>(0);
354
355   FGAirport::TypeRunwayFilter filter; // defaults to airports only
356   filter.fromTypeString( ctx.getArg<std::string>(1) );
357
358   FGPositionedList apts = FGPositioned::findWithinRange(pos, range_nm, &filter);
359   FGPositioned::sortByRange(apts, pos);
360
361   return ctx.to_nasal(apts);
362 }
363
364 /**
365  * findAirportsByICAO(<ident/prefix> [, type])
366  */
367 static naRef f_findAirportsByICAO(nasal::CallContext ctx)
368 {
369   std::string prefix = ctx.requireArg<std::string>(0);
370
371   FGAirport::TypeRunwayFilter filter; // defaults to airports only
372   filter.fromTypeString( ctx.getArg<std::string>(1) );
373
374   return ctx.to_nasal( FGPositioned::findAllWithIdent(prefix, &filter, false) );
375 }
376
377 // Returns vector of data hash for navaid of a <type>, nil on error
378 // navaids sorted by ascending distance
379 // navinfo([<lat>,<lon>],[<type>],[<id>])
380 // lat/lon (numeric): use latitude/longitude instead of ac position
381 // type:              ("fix"|"vor"|"ndb"|"ils"|"dme"|"tacan"|"any")
382 // id:                (partial) id of the fix
383 // examples:
384 // navinfo("vor")     returns all vors
385 // navinfo("HAM")     return all navaids who's name start with "HAM"
386 // navinfo("vor", "HAM") return all vor who's name start with "HAM"
387 //navinfo(34,48,"vor","HAM") return all vor who's name start with "HAM"
388 //                           sorted by distance relative to lat=34, lon=48
389 static naRef f_navinfo(nasal::CallContext ctx)
390 {
391   SGGeod pos = getPosition(ctx);
392   std::string id = ctx.getArg<std::string>(0);
393
394   FGNavList::TypeFilter filter;
395   if( filter.fromTypeString(id) )
396     id = ctx.getArg<std::string>(1);
397   else if( ctx.argc > 1 )
398     naRuntimeError(ctx.c, "navinfo() already got an ident");
399
400   return ctx.to_nasal( FGNavList::findByIdentAndFreq(pos, id, 0.0, &filter) );
401 }
402
403 //------------------------------------------------------------------------------
404 static naRef f_findWithinRange(nasal::CallContext ctx)
405 {
406   SGGeod pos = getPosition(ctx);
407   double range_nm = ctx.requireArg<double>(0);
408
409   FGPositioned::TypeFilter filter(FGPositioned::typeFromName(ctx.getArg<std::string>(1)));
410     
411   FGPositionedList items = FGPositioned::findWithinRange(pos, range_nm, &filter);
412   FGPositioned::sortByRange(items, pos);
413   return ctx.to_nasal(items);
414 }
415
416 static naRef f_findByIdent(nasal::CallContext ctx)
417 {
418   std::string prefix = ctx.requireArg<std::string>(0);
419   
420   FGPositioned::TypeFilter filter(FGPositioned::typeFromName(ctx.getArg<std::string>(1)));
421   bool exact = ctx.getArg<bool>(2, false);
422
423   return ctx.to_nasal( FGPositioned::findAllWithIdent(prefix, &filter, exact) );
424 }
425
426 static naRef f_findByName(nasal::CallContext ctx)
427 {
428   std::string prefix = ctx.requireArg<std::string>(0);
429   
430   FGPositioned::TypeFilter filter(FGPositioned::typeFromName(ctx.getArg<std::string>(1)));
431   
432   return ctx.to_nasal( FGPositioned::findAllWithName(prefix, &filter, false) );
433 }
434
435 //------------------------------------------------------------------------------
436
437 static naRef f_courseAndDistance(nasal::CallContext ctx)
438 {
439   SGGeod from = globals->get_aircraft_position(), to, pos;
440   bool ok = extractGeod(ctx, pos);
441   if (!ok) {
442     naRuntimeError(ctx.c, "invalid arguments to courseAndDistance");
443   }
444   
445   if (extractGeod(ctx, to)) {
446     from = pos; // we parsed both FROM and TO args, so first was FROM
447   } else {
448     to = pos; // only parsed one arg, so FROM is current
449   }
450   
451   double course, course2, d;
452   SGGeodesy::inverse(from, to, course, course2, d);
453   
454   naRef result = naNewVector(ctx.c);
455   naVec_append(result, naNum(course));
456   naVec_append(result, naNum(d * SG_METER_TO_NM));
457   return result;
458 }
459
460 static naRef f_sortByRange(nasal::CallContext ctx)
461 {
462   FGPositionedList items = ctx.requireArg<FGPositionedList>(0);
463   ctx.popFront();
464   FGPositioned::sortByRange(items, getPosition(ctx));
465   return ctx.to_nasal(items);
466 }
467
468 //------------------------------------------------------------------------------
469 naRef initNasalPositioned_cppbind(naRef globalsRef, naContext c, naRef gcSave)
470 {
471   NasalPositioned::init("Positioned")
472     .member("id", &FGPositioned::ident)
473     .member("ident", &FGPositioned::ident) // TODO to we really need id and ident?
474     .member("name", &FGPositioned::name)
475     .member("type", &FGPositioned::typeString)
476     .member("lat", &FGPositioned::latitude)
477     .member("lon", &FGPositioned::longitude)
478     .member("elevation", &FGPositioned::elevationM);
479   NasalRunway::init("Runway")
480     .bases<NasalPositioned>();
481   NasalParking::init("Parking")
482     .bases<NasalPositioned>();
483   NasalCommStation::init("CommStation")
484     .bases<NasalPositioned>()
485     .member("frequency", &flightgear::CommStation::freqMHz);
486   NasalNavRecord::init("Navaid")
487     .bases<NasalPositioned>()
488     .member("frequency", &FGNavRecord::get_freq)
489     .member("range_nm", &FGNavRecord::get_range)
490     .member("course", &f_navaid_course);
491
492   NasalFix::init("Fix")
493     .bases<NasalPositioned>();
494   
495   NasalAirport::init("FGAirport")
496     .bases<NasalPositioned>()
497     .member("has_metar", &FGAirport::getMetar)
498     .member("runways", &FGAirport::getRunwayMap)
499     .member("helipads", &FGAirport::getHelipadMap)
500     .member("taxiways", &FGAirport::getTaxiways)
501     .member("pavements", &FGAirport::getPavements)
502     .method("runway", &f_airport_runway)
503     .method("helipad", &f_airport_runway)
504     .method("tower", &FGAirport::getTowerLocation)
505     .method("comms", &f_airport_comms)
506     .method("sids", &f_airport_sids)
507     .method("stars", &f_airport_stars)
508     .method("getApproachList", f_airport_approaches)
509     .method("parking", &f_airport_parking)
510     .method("getSid", &FGAirport::findSIDWithIdent)
511     .method("getStar", &FGAirport::findSTARWithIdent)
512     .method("getIAP", &FGAirport::findApproachWithIdent)
513     .method("tostring", &FGAirport::toString);
514
515   nasal::Hash globals(globalsRef, c),
516               positioned( globals.createHash("positioned") );
517
518   positioned.set("airportinfo", &f_airportinfo);
519   positioned.set("findAirportsWithinRange", f_findAirportsWithinRange);
520   positioned.set("findAirportsByICAO", &f_findAirportsByICAO);
521   positioned.set("navinfo", &f_navinfo);
522   
523   positioned.set("findWithinRange", &f_findWithinRange);
524   positioned.set("findByIdent", &f_findByIdent);
525   positioned.set("findByName", &f_findByName);
526   positioned.set("courseAndDistance", &f_courseAndDistance);
527   positioned.set("sortByRange", &f_sortByRange);
528   
529   return naNil();
530 }