1 // NasalPositioned_cppbind.cxx -- expose FGPositioned classes to Nasal
3 // Port of NasalPositioned.cpp to the new nasal/cppbind helpers. Will replace
4 // old NasalPositioned.cpp once finished.
6 // Copyright (C) 2013 Thomas Geymayer <tomgey@gmail.com>
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.
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.
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.
26 #include "NasalPositioned.hxx"
31 #include <boost/foreach.hpp>
32 #include <boost/algorithm/string/case_conv.hpp>
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>
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>
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;
58 //------------------------------------------------------------------------------
59 naRef to_nasal_helper(naContext c, flightgear::SID* sid)
62 return nasal::to_nasal(c, sid->ident());
65 //------------------------------------------------------------------------------
66 naRef to_nasal_helper(naContext c, flightgear::STAR* star)
69 return nasal::to_nasal(c, star->ident());
72 //------------------------------------------------------------------------------
73 naRef to_nasal_helper(naContext c, flightgear::Approach* iap)
75 // TODO Approach ghost
76 return nasal::to_nasal(c, iap->ident());
79 //------------------------------------------------------------------------------
80 naRef to_nasal_helper(naContext c, const SGGeod& pos)
83 hash.set("lat", pos.getLatitudeDeg());
84 hash.set("lon", pos.getLongitudeDeg());
85 hash.set("elevation", pos.getElevationM());
86 return hash.get_naRef();
89 //------------------------------------------------------------------------------
90 static naRef f_navaid_course(naContext, FGNavRecord& nav)
92 if( !( nav.type() == FGPositioned::ILS
93 || nav.type() == FGPositioned::LOC
97 double radial = nav.get_multiuse();
98 return naNum(SGMiscd::normalizePeriodic(0.5, 360.5, radial));
101 //------------------------------------------------------------------------------
102 static FGRunwayBaseRef f_airport_runway(FGAirport& apt, std::string ident)
104 boost::to_upper(ident);
106 if( apt.hasRunwayWithIdent(ident) )
107 return apt.getRunwayByIdent(ident);
108 else if( apt.hasHelipadWithIdent(ident) )
109 return apt.getHelipadByIdent(ident);
114 //------------------------------------------------------------------------------
115 template<class T, class C1, class C2>
116 std::vector<T> extract( const std::vector<C1>& in,
117 T (C2::*getter)() const )
119 std::vector<T> ret(in.size());
120 std::transform(in.begin(), in.end(), ret.begin(), std::mem_fun(getter));
124 //------------------------------------------------------------------------------
125 static naRef f_airport_comms(FGAirport& apt, const nasal::CallContext& ctx)
127 FGPositioned::Type comm_type =
128 FGPositioned::typeFromName( ctx.getArg<std::string>(0) );
130 // if we have an explicit type, return a simple vector of frequencies
131 if( comm_type != FGPositioned::INVALID )
134 extract( apt.commStationsOfType(comm_type),
135 &flightgear::CommStation::freqMHz )
138 // otherwise return a vector of ghosts, one for each comm station.
139 return ctx.to_nasal(apt.commStations());
142 //------------------------------------------------------------------------------
143 FGRunway* runwayFromNasalArg( const FGAirport& apt,
144 const nasal::CallContext& ctx,
147 if( index >= ctx.argc )
152 std::string ident = ctx.getArg<std::string>(index);
155 if( !apt.hasRunwayWithIdent(ident) )
156 // TODO warning/exception?
159 return apt.getRunwayByIdent(ident);
165 // TODO warn/error if no runway?
166 return NasalRunway::fromNasal(ctx.c, ctx.args[index]);
169 //------------------------------------------------------------------------------
170 static naRef f_airport_sids(FGAirport& apt, const nasal::CallContext& ctx)
172 FGRunway* rwy = runwayFromNasalArg(apt, ctx);
175 extract(rwy ? rwy->getSIDs() : apt.getSIDs(), &flightgear::SID::ident)
179 //------------------------------------------------------------------------------
180 static naRef f_airport_stars(FGAirport& apt, const nasal::CallContext& ctx)
182 FGRunway* rwy = runwayFromNasalArg(apt, ctx);
185 extract(rwy ? rwy->getSTARs() : apt.getSTARs(), &flightgear::STAR::ident)
189 //------------------------------------------------------------------------------
190 static naRef f_airport_approaches(FGAirport& apt, const nasal::CallContext& ctx)
192 FGRunway* rwy = runwayFromNasalArg(apt, ctx);
194 flightgear::ProcedureType type = flightgear::PROCEDURE_INVALID;
195 std::string type_str = ctx.getArg<std::string>(1);
196 if( !type_str.empty() )
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;
207 extract( rwy ? rwy->getApproaches(type)
208 // no runway specified, report them all
209 : apt.getApproaches(type),
210 &flightgear::Approach::ident )
214 //------------------------------------------------------------------------------
216 f_airport_parking(FGAirport& apt, nasal::CallContext ctx)
218 std::string type = ctx.getArg<std::string>(0);
219 bool only_available = ctx.getArg<bool>(1);
221 FGAirportDynamics* dynamics = apt.getDynamics();
222 PositionedIDVec parkings =
223 flightgear::NavDataCache::instance()
224 ->airportItemsOfType(apt.guid(), FGPositioned::PARKING);
227 BOOST_FOREACH(PositionedID parking, parkings)
229 // filter out based on availability and type
230 if( only_available && !dynamics->isParkingAvailable(parking) )
233 FGParking* park = dynamics->getParking(parking);
234 if( !type.empty() && (park->getType() != type) )
244 * Extract a SGGeod from a nasal function argument list.
247 * {"lat": <lat-deg>, "lon": <lon-deg>}
248 * geo.Coord.new() (aka. {"_lat": <lat-rad>, "_lon": <lon-rad>})
250 static bool extractGeod(nasal::CallContext& ctx, SGGeod& result)
258 NasalPositioned::fromNasal(ctx.c, ctx.requireArg<naRef>(0));
262 result = pos->geod();
267 else if( ctx.isHash(0) )
269 nasal::Hash pos_hash = ctx.requireArg<nasal::Hash>(0);
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) )
276 result = SGGeod::fromDeg( ctx.from_nasal<double>(lon),
277 ctx.from_nasal<double>(lat) );
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) )
288 result = SGGeod::fromRad( ctx.from_nasal<double>(lon),
289 ctx.from_nasal<double>(lat) );
294 else if( ctx.isNumeric(0) && ctx.isNumeric(1) )
297 result = SGGeod::fromDeg( ctx.requireArg<double>(1),
298 ctx.requireArg<double>(0) );
307 * Extract position from ctx or return current aircraft position if not given.
309 static SGGeod getPosition(nasal::CallContext& ctx)
312 if( !extractGeod(ctx, pos) )
313 pos = globals->get_aircraft_position();
318 //------------------------------------------------------------------------------
319 // Returns Nasal ghost for particular or nearest airport of a <type>, or nil
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)
328 SGGeod pos = getPosition(ctx);
331 naRuntimeError(ctx.c, "airportinfo() with invalid function arguments");
333 // optional type/ident
334 std::string ident("airport");
335 if( ctx.isString(0) )
336 ident = ctx.requireArg<std::string>(0);
338 FGAirport::TypeRunwayFilter filter;
339 if( !filter.fromTypeString(ident) )
340 // user provided an <id>, hopefully
341 return ctx.to_nasal(FGAirport::findByIdent(ident));
343 double maxRange = 10000.0; // expose this? or pick a smaller value?
344 return ctx.to_nasal( FGAirport::findClosest(pos, maxRange, &filter) );
348 * findAirportsWithinRange([<position>,] <range-nm> [, type])
350 static naRef f_findAirportsWithinRange(nasal::CallContext ctx)
352 SGGeod pos = getPosition(ctx);
353 double range_nm = ctx.requireArg<double>(0);
355 FGAirport::TypeRunwayFilter filter; // defaults to airports only
356 filter.fromTypeString( ctx.getArg<std::string>(1) );
358 FGPositionedList apts = FGPositioned::findWithinRange(pos, range_nm, &filter);
359 FGPositioned::sortByRange(apts, pos);
361 return ctx.to_nasal(apts);
365 * findAirportsByICAO(<ident/prefix> [, type])
367 static naRef f_findAirportsByICAO(nasal::CallContext ctx)
369 std::string prefix = ctx.requireArg<std::string>(0);
371 FGAirport::TypeRunwayFilter filter; // defaults to airports only
372 filter.fromTypeString( ctx.getArg<std::string>(1) );
374 return ctx.to_nasal( FGPositioned::findAllWithIdent(prefix, &filter, false) );
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
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)
391 SGGeod pos = getPosition(ctx);
392 std::string id = ctx.getArg<std::string>(0);
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");
400 return ctx.to_nasal( FGNavList::findByIdentAndFreq(pos, id, 0.0, &filter) );
403 //------------------------------------------------------------------------------
404 static naRef f_findWithinRange(nasal::CallContext ctx)
406 SGGeod pos = getPosition(ctx);
407 double range_nm = ctx.requireArg<double>(0);
409 FGPositioned::TypeFilter filter(FGPositioned::typeFromName(ctx.getArg<std::string>(1)));
411 FGPositionedList items = FGPositioned::findWithinRange(pos, range_nm, &filter);
412 FGPositioned::sortByRange(items, pos);
413 return ctx.to_nasal(items);
416 static naRef f_findByIdent(nasal::CallContext ctx)
418 std::string prefix = ctx.requireArg<std::string>(0);
420 FGPositioned::TypeFilter filter(FGPositioned::typeFromName(ctx.getArg<std::string>(1)));
421 bool exact = ctx.getArg<bool>(2, false);
423 return ctx.to_nasal( FGPositioned::findAllWithIdent(prefix, &filter, exact) );
426 static naRef f_findByName(nasal::CallContext ctx)
428 std::string prefix = ctx.requireArg<std::string>(0);
430 FGPositioned::TypeFilter filter(FGPositioned::typeFromName(ctx.getArg<std::string>(1)));
432 return ctx.to_nasal( FGPositioned::findAllWithName(prefix, &filter, false) );
435 //------------------------------------------------------------------------------
437 static naRef f_courseAndDistance(nasal::CallContext ctx)
439 SGGeod from = globals->get_aircraft_position(), to, pos;
440 bool ok = extractGeod(ctx, pos);
442 naRuntimeError(ctx.c, "invalid arguments to courseAndDistance");
445 if (extractGeod(ctx, to)) {
446 from = pos; // we parsed both FROM and TO args, so first was FROM
448 to = pos; // only parsed one arg, so FROM is current
451 double course, course2, d;
452 SGGeodesy::inverse(from, to, course, course2, d);
454 naRef result = naNewVector(ctx.c);
455 naVec_append(result, naNum(course));
456 naVec_append(result, naNum(d * SG_METER_TO_NM));
460 static naRef f_sortByRange(nasal::CallContext ctx)
462 FGPositionedList items = ctx.requireArg<FGPositionedList>(0);
464 FGPositioned::sortByRange(items, getPosition(ctx));
465 return ctx.to_nasal(items);
468 //------------------------------------------------------------------------------
469 naRef initNasalPositioned_cppbind(naRef globalsRef, naContext c, naRef gcSave)
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);
492 NasalFix::init("Fix")
493 .bases<NasalPositioned>();
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);
515 nasal::Hash globals(globalsRef, c),
516 positioned( globals.createHash("positioned") );
518 positioned.set("airportinfo", &f_airportinfo);
519 positioned.set("findAirportsWithinRange", f_findAirportsWithinRange);
520 positioned.set("findAirportsByICAO", &f_findAirportsByICAO);
521 positioned.set("navinfo", &f_navinfo);
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);