]> git.mxchange.org Git - flightgear.git/blob - src/Scripting/NasalSys.cxx
eca5d59c48a500e87f87999f6c03cb7a26d9a713
[flightgear.git] / src / Scripting / NasalSys.cxx
1
2 #ifdef HAVE_CONFIG_H
3 #  include "config.h"
4 #endif
5
6 #ifdef HAVE_SYS_TIME_H
7 #  include <sys/time.h>  // gettimeofday
8 #endif
9
10 #include <string.h>
11 #include <stdio.h>
12 #include <sys/types.h>
13 #include <sys/stat.h>
14 #include <fstream>
15 #include <sstream>
16
17 #include <simgear/nasal/nasal.h>
18 #include <simgear/props/props.hxx>
19 #include <simgear/math/sg_random.h>
20 #include <simgear/misc/sg_path.hxx>
21 #include <simgear/misc/sg_dir.hxx>
22 #include <simgear/misc/interpolator.hxx>
23 #include <simgear/scene/material/mat.hxx>
24 #include <simgear/structure/commands.hxx>
25 #include <simgear/math/sg_geodesy.hxx>
26 #include <simgear/structure/event_mgr.hxx>
27
28 #include <Airports/runways.hxx>
29 #include <Airports/simple.hxx>
30 #include <Main/globals.hxx>
31 #include <Main/fg_props.hxx>
32 #include <Main/util.hxx>
33 #include <Scenery/scenery.hxx>
34 #include <Navaids/navlist.hxx>
35 #include <Navaids/procedure.hxx>
36
37
38 #include "NasalSys.hxx"
39
40 static FGNasalSys* nasalSys = 0;
41
42 // Listener class for loading Nasal modules on demand
43 class FGNasalModuleListener : public SGPropertyChangeListener
44 {
45 public:
46     FGNasalModuleListener(SGPropertyNode* node);
47
48     virtual void valueChanged(SGPropertyNode* node);
49
50 private:
51     SGPropertyNode_ptr _node;
52 };
53
54 FGNasalModuleListener::FGNasalModuleListener(SGPropertyNode* node) : _node(node)
55 {
56 }
57
58 void FGNasalModuleListener::valueChanged(SGPropertyNode*)
59 {
60     if (_node->getBoolValue("enabled",false)&&
61         !_node->getBoolValue("loaded",true))
62     {
63         nasalSys->loadPropertyScripts(_node);
64     }
65 }
66
67
68 // Read and return file contents in a single buffer.  Note use of
69 // stat() to get the file size.  This is a win32 function, believe it
70 // or not. :) Note the REALLY IMPORTANT use of the "b" flag to fopen.
71 // Text mode brain damage will kill us if we're trying to do bytewise
72 // I/O.
73 static char* readfile(const char* file, int* lenOut)
74 {
75     struct stat data;
76     if(stat(file, &data) != 0) return 0;
77     FILE* f = fopen(file, "rb");
78     if(!f) return 0;
79     char* buf = new char[data.st_size];
80     *lenOut = fread(buf, 1, data.st_size, f);
81     fclose(f);
82     if(*lenOut != data.st_size) {
83         // Shouldn't happen, but warn anyway since it represents a
84         // platform bug and not a typical runtime error (missing file,
85         // etc...)
86         SG_LOG(SG_NASAL, SG_ALERT,
87                "ERROR in Nasal initialization: " <<
88                "short count returned from fread() of " << file <<
89                ".  Check your C library!");
90         delete[] buf;
91         return 0;
92     }
93     return buf;
94 }
95
96 FGNasalSys::FGNasalSys()
97 {
98     nasalSys = this;
99     _context = 0;
100     _globals = naNil();
101     _gcHash = naNil();
102     _nextGCKey = 0; // Any value will do
103     _callCount = 0;
104 }
105
106 // Does a naCall() in a new context.  Wrapped here to make lock
107 // tracking easier.  Extension functions are called with the lock, but
108 // we have to release it before making a new naCall().  So rather than
109 // drop the lock in every extension function that might call back into
110 // Nasal, we keep a stack depth counter here and only unlock/lock
111 // around the naCall if it isn't the first one.
112 naRef FGNasalSys::call(naRef code, int argc, naRef* args, naRef locals)
113 {
114     naContext ctx = naNewContext();
115     if(_callCount) naModUnlock();
116     _callCount++;
117     naRef result = naCall(ctx, code, argc, args, naNil(), locals);
118     if(naGetError(ctx))
119         logError(ctx);
120     _callCount--;
121     if(_callCount) naModLock();
122     naFreeContext(ctx);
123     return result;
124 }
125
126 FGNasalSys::~FGNasalSys()
127 {
128     nasalSys = 0;
129     map<int, FGNasalListener *>::iterator it, end = _listener.end();
130     for(it = _listener.begin(); it != end; ++it)
131         delete it->second;
132
133     naFreeContext(_context);
134     _globals = naNil();
135 }
136
137 bool FGNasalSys::parseAndRun(const char* sourceCode)
138 {
139     naRef code = parse("FGNasalSys::parseAndRun()", sourceCode,
140                        strlen(sourceCode));
141     if(naIsNil(code))
142         return false;
143     call(code, 0, 0, naNil());
144     return true;
145 }
146
147 FGNasalScript* FGNasalSys::parseScript(const char* src, const char* name)
148 {
149     FGNasalScript* script = new FGNasalScript();
150     script->_gcKey = -1; // important, if we delete it on a parse
151     script->_nas = this; // error, don't clobber a real handle!
152
153     char buf[256];
154     if(!name) {
155         sprintf(buf, "FGNasalScript@%p", (void *)script);
156         name = buf;
157     }
158
159     script->_code = parse(name, src, strlen(src));
160     if(naIsNil(script->_code)) {
161         delete script;
162         return 0;
163     }
164
165     script->_gcKey = gcSave(script->_code);
166     return script;
167 }
168
169 // Utility.  Sets a named key in a hash by C string, rather than nasal
170 // string object.
171 void FGNasalSys::hashset(naRef hash, const char* key, naRef val)
172 {
173     naRef s = naNewString(_context);
174     naStr_fromdata(s, (char*)key, strlen(key));
175     naHash_set(hash, s, val);
176 }
177
178 // The get/setprop functions accept a *list* of strings and walk
179 // through the property tree with them to find the appropriate node.
180 // This allows a Nasal object to hold onto a property path and use it
181 // like a node object, e.g. setprop(ObjRoot, "size-parsecs", 2.02).  This
182 // is the utility function that walks the property tree.
183 // Future enhancement: support integer arguments to specify array
184 // elements.
185 static SGPropertyNode* findnode(naContext c, naRef* vec, int len)
186 {
187     SGPropertyNode* p = globals->get_props();
188     try {
189         for(int i=0; i<len; i++) {
190             naRef a = vec[i];
191             if(!naIsString(a)) return 0;
192             p = p->getNode(naStr_data(a));
193             if(p == 0) return 0;
194         }
195     } catch (const string& err) {
196         naRuntimeError(c, (char *)err.c_str());
197         return 0;
198     }
199     return p;
200 }
201
202 // getprop() extension function.  Concatenates its string arguments as
203 // property names and returns the value of the specified property.  Or
204 // nil if it doesn't exist.
205 static naRef f_getprop(naContext c, naRef me, int argc, naRef* args)
206 {
207     using namespace simgear;
208     const SGPropertyNode* p = findnode(c, args, argc);
209     if(!p) return naNil();
210
211     switch(p->getType()) {
212     case props::BOOL:   case props::INT:
213     case props::LONG:   case props::FLOAT:
214     case props::DOUBLE:
215         {
216         double dv = p->getDoubleValue();
217         if (osg::isNaN(dv)) {
218           SG_LOG(SG_NASAL, SG_ALERT, "Nasal getprop: property " << p->getPath() << " is NaN");
219           return naNil();
220         }
221         
222         return naNum(dv);
223         }
224         
225     case props::STRING:
226     case props::UNSPECIFIED:
227         {
228             naRef nastr = naNewString(c);
229             const char* val = p->getStringValue();
230             naStr_fromdata(nastr, (char*)val, strlen(val));
231             return nastr;
232         }
233     case props::ALIAS: // <--- FIXME, recurse?
234     default:
235         return naNil();
236     }
237 }
238
239 // setprop() extension function.  Concatenates its string arguments as
240 // property names and sets the value of the specified property to the
241 // final argument.
242 static naRef f_setprop(naContext c, naRef me, int argc, naRef* args)
243 {
244 #define BUFLEN 1024
245     char buf[BUFLEN + 1];
246     buf[BUFLEN] = 0;
247     char* p = buf;
248     int buflen = BUFLEN;
249     if(argc < 2) naRuntimeError(c, "setprop() expects at least 2 arguments");
250     for(int i=0; i<argc-1; i++) {
251         naRef s = naStringValue(c, args[i]);
252         if(naIsNil(s)) return naNil();
253         strncpy(p, naStr_data(s), buflen);
254         p += naStr_len(s);
255         buflen = BUFLEN - (p - buf);
256         if(i < (argc-2) && buflen > 0) {
257             *p++ = '/';
258             buflen--;
259         }
260     }
261
262     SGPropertyNode* props = globals->get_props();
263     naRef val = args[argc-1];
264     bool result = false;
265     try {
266         if(naIsString(val)) result = props->setStringValue(buf, naStr_data(val));
267         else {
268             naRef n = naNumValue(val);
269             if(naIsNil(n))
270                 naRuntimeError(c, "setprop() value is not string or number");
271                 
272             if (osg::isNaN(n.num)) {
273                 naRuntimeError(c, "setprop() passed a NaN");
274             }
275             
276             result = props->setDoubleValue(buf, n.num);
277         }
278     } catch (const string& err) {
279         naRuntimeError(c, (char *)err.c_str());
280     }
281     return naNum(result);
282 #undef BUFLEN
283 }
284
285 // print() extension function.  Concatenates and prints its arguments
286 // to the FlightGear log.  Uses the highest log level (SG_ALERT), to
287 // make sure it appears.  Is there better way to do this?
288 static naRef f_print(naContext c, naRef me, int argc, naRef* args)
289 {
290     string buf;
291     int n = argc;
292     for(int i=0; i<n; i++) {
293         naRef s = naStringValue(c, args[i]);
294         if(naIsNil(s)) continue;
295         buf += naStr_data(s);
296     }
297     SG_LOG(SG_NASAL, SG_ALERT, buf);
298     return naNum(buf.length());
299 }
300
301 // fgcommand() extension function.  Executes a named command via the
302 // FlightGear command manager.  Takes a single property node name as
303 // an argument.
304 static naRef f_fgcommand(naContext c, naRef me, int argc, naRef* args)
305 {
306     naRef cmd = argc > 0 ? args[0] : naNil();
307     naRef props = argc > 1 ? args[1] : naNil();
308     if(!naIsString(cmd) || (!naIsNil(props) && !naIsGhost(props)))
309         naRuntimeError(c, "bad arguments to fgcommand()");
310     SGPropertyNode_ptr tmp, *node;
311     if(!naIsNil(props))
312         node = (SGPropertyNode_ptr*)naGhost_ptr(props);
313     else {
314         tmp = new SGPropertyNode();
315         node = &tmp;
316     }
317     return naNum(globals->get_commands()->execute(naStr_data(cmd), *node));
318 }
319
320 // settimer(func, dt, simtime) extension function.  Falls through to
321 // FGNasalSys::setTimer().  See there for docs.
322 static naRef f_settimer(naContext c, naRef me, int argc, naRef* args)
323 {
324     nasalSys->setTimer(c, argc, args);
325     return naNil();
326 }
327
328 // setlistener(func, property, bool) extension function.  Falls through to
329 // FGNasalSys::setListener().  See there for docs.
330 static naRef f_setlistener(naContext c, naRef me, int argc, naRef* args)
331 {
332     return nasalSys->setListener(c, argc, args);
333 }
334
335 // removelistener(int) extension function. Falls through to
336 // FGNasalSys::removeListener(). See there for docs.
337 static naRef f_removelistener(naContext c, naRef me, int argc, naRef* args)
338 {
339     return nasalSys->removeListener(c, argc, args);
340 }
341
342 // Returns a ghost handle to the argument to the currently executing
343 // command
344 static naRef f_cmdarg(naContext c, naRef me, int argc, naRef* args)
345 {
346     return nasalSys->cmdArgGhost();
347 }
348
349 // Sets up a property interpolation.  The first argument is either a
350 // ghost (SGPropertyNode_ptr*) or a string (global property path) to
351 // interpolate.  The second argument is a vector of pairs of
352 // value/delta numbers.
353 static naRef f_interpolate(naContext c, naRef me, int argc, naRef* args)
354 {
355     SGPropertyNode* node;
356     naRef prop = argc > 0 ? args[0] : naNil();
357     if(naIsString(prop)) node = fgGetNode(naStr_data(prop), true);
358     else if(naIsGhost(prop)) node = *(SGPropertyNode_ptr*)naGhost_ptr(prop);
359     else return naNil();
360
361     naRef curve = argc > 1 ? args[1] : naNil();
362     if(!naIsVector(curve)) return naNil();
363     int nPoints = naVec_size(curve) / 2;
364     double* values = new double[nPoints];
365     double* deltas = new double[nPoints];
366     for(int i=0; i<nPoints; i++) {
367         values[i] = naNumValue(naVec_get(curve, 2*i)).num;
368         deltas[i] = naNumValue(naVec_get(curve, 2*i+1)).num;
369     }
370
371     ((SGInterpolator*)globals->get_subsystem_mgr()
372         ->get_group(SGSubsystemMgr::INIT)->get_subsystem("interpolator"))
373         ->interpolate(node, nPoints, values, deltas);
374
375     delete[] values;
376     delete[] deltas;
377     return naNil();
378 }
379
380 // This is a better RNG than the one in the default Nasal distribution
381 // (which is based on the C library rand() implementation). It will
382 // override.
383 static naRef f_rand(naContext c, naRef me, int argc, naRef* args)
384 {
385     return naNum(sg_random());
386 }
387
388 static naRef f_srand(naContext c, naRef me, int argc, naRef* args)
389 {
390     sg_srandom_time();
391     return naNum(0);
392 }
393
394 static naRef f_abort(naContext c, naRef me, int argc, naRef* args)
395 {
396     abort();
397     return naNil();
398 }
399
400 // Return an array listing of all files in a directory
401 static naRef f_directory(naContext c, naRef me, int argc, naRef* args)
402 {
403     if(argc != 1 || !naIsString(args[0]))
404         naRuntimeError(c, "bad arguments to directory()");
405     
406     simgear::Dir d(SGPath(naStr_data(args[0])));
407     if(!d.exists()) return naNil();
408     naRef result = naNewVector(c);
409
410     simgear::PathList paths = d.children(simgear::Dir::TYPE_FILE | simgear::Dir::TYPE_DIR);
411     for (unsigned int i=0; i<paths.size(); ++i) {
412       std::string p = paths[i].file();
413       naVec_append(result, naStr_fromdata(naNewString(c), p.c_str(), p.size()));
414     }
415     
416     return result;
417 }
418
419 /**
420  * Given a data path, resolve it in FG_ROOT or an FG_AIRCRFT directory
421  */
422 static naRef f_resolveDataPath(naContext c, naRef me, int argc, naRef* args)
423 {
424     if(argc != 1 || !naIsString(args[0]))
425         naRuntimeError(c, "bad arguments to resolveDataPath()");
426
427     SGPath p = globals->resolve_maybe_aircraft_path(naStr_data(args[0]));
428     const char* pdata = p.c_str();
429     return naStr_fromdata(naNewString(c), const_cast<char*>(pdata), strlen(pdata));
430 }
431
432 // Parse XML file.
433 //     parsexml(<path> [, <start-tag> [, <end-tag> [, <data> [, <pi>]]]]);
434 //
435 // <path>      ... absolute path to an XML file
436 // <start-tag> ... callback function with two args: tag name, attribute hash
437 // <end-tag>   ... callback function with one arg:  tag name
438 // <data>      ... callback function with one arg:  data
439 // <pi>        ... callback function with two args: target, data
440 //                 (pi = "processing instruction")
441 // All four callback functions are optional and default to nil.
442 // The function returns nil on error, or the validated file name otherwise.
443 static naRef f_parsexml(naContext c, naRef me, int argc, naRef* args)
444 {
445     if(argc < 1 || !naIsString(args[0]))
446         naRuntimeError(c, "parsexml(): path argument missing or not a string");
447     if(argc > 5) argc = 5;
448     for(int i=1; i<argc; i++)
449         if(!(naIsNil(args[i]) || naIsFunc(args[i])))
450             naRuntimeError(c, "parsexml(): callback argument not a function");
451
452     const char* file = fgValidatePath(naStr_data(args[0]), false);
453     if(!file) {
454         naRuntimeError(c, "parsexml(): reading '%s' denied "
455                 "(unauthorized access)", naStr_data(args[0]));
456         return naNil();
457     }
458     std::ifstream input(file);
459     NasalXMLVisitor visitor(c, argc, args);
460     try {
461         readXML(input, visitor);
462     } catch (const sg_exception& e) {
463         naRuntimeError(c, "parsexml(): file '%s' %s",
464                 file, e.getFormattedMessage().c_str());
465         return naNil();
466     }
467     return naStr_fromdata(naNewString(c), const_cast<char*>(file), strlen(file));
468 }
469
470 // Return UNIX epoch time in seconds.
471 static naRef f_systime(naContext c, naRef me, int argc, naRef* args)
472 {
473 #ifdef _WIN32
474     FILETIME ft;
475     GetSystemTimeAsFileTime(&ft);
476     double t = (4294967296.0 * ft.dwHighDateTime + ft.dwLowDateTime);
477     // Converts from 100ns units in 1601 epoch to unix epoch in sec
478     return naNum((t * 1e-7) - 11644473600.0);
479 #else
480     struct timeval td;
481     gettimeofday(&td, 0);
482     return naNum(td.tv_sec + 1e-6 * td.tv_usec);
483 #endif
484 }
485
486 // Convert a cartesian point to a geodetic lat/lon/altitude.
487 static naRef f_carttogeod(naContext c, naRef me, int argc, naRef* args)
488 {
489     double lat, lon, alt, xyz[3];
490     if(argc != 3) naRuntimeError(c, "carttogeod() expects 3 arguments");
491     for(int i=0; i<3; i++)
492         xyz[i] = naNumValue(args[i]).num;
493     sgCartToGeod(xyz, &lat, &lon, &alt);
494     lat *= SG_RADIANS_TO_DEGREES;
495     lon *= SG_RADIANS_TO_DEGREES;
496     naRef vec = naNewVector(c);
497     naVec_append(vec, naNum(lat));
498     naVec_append(vec, naNum(lon));
499     naVec_append(vec, naNum(alt));
500     return vec;
501 }
502
503 // Convert a geodetic lat/lon/altitude to a cartesian point.
504 static naRef f_geodtocart(naContext c, naRef me, int argc, naRef* args)
505 {
506     if(argc != 3) naRuntimeError(c, "geodtocart() expects 3 arguments");
507     double lat = naNumValue(args[0]).num * SG_DEGREES_TO_RADIANS;
508     double lon = naNumValue(args[1]).num * SG_DEGREES_TO_RADIANS;
509     double alt = naNumValue(args[2]).num;
510     double xyz[3];
511     sgGeodToCart(lat, lon, alt, xyz);
512     naRef vec = naNewVector(c);
513     naVec_append(vec, naNum(xyz[0]));
514     naVec_append(vec, naNum(xyz[1]));
515     naVec_append(vec, naNum(xyz[2]));
516     return vec;
517 }
518
519 // For given geodetic point return array with elevation, and a material data
520 // hash, or nil if there's no information available (tile not loaded). If
521 // information about the material isn't available, then nil is returned instead
522 // of the hash.
523 static naRef f_geodinfo(naContext c, naRef me, int argc, naRef* args)
524 {
525 #define HASHSET(s,l,n) naHash_set(matdata, naStr_fromdata(naNewString(c),s,l),n)
526     if(argc < 2 || argc > 3)
527         naRuntimeError(c, "geodinfo() expects 2 or 3 arguments: lat, lon [, maxalt]");
528     double lat = naNumValue(args[0]).num;
529     double lon = naNumValue(args[1]).num;
530     double elev = argc == 3 ? naNumValue(args[2]).num : 10000;
531     const SGMaterial *mat;
532     SGGeod geod = SGGeod::fromDegM(lon, lat, elev);
533     if(!globals->get_scenery()->get_elevation_m(geod, elev, &mat))
534         return naNil();
535     naRef vec = naNewVector(c);
536     naVec_append(vec, naNum(elev));
537     naRef matdata = naNil();
538     if(mat) {
539         matdata = naNewHash(c);
540         naRef names = naNewVector(c);
541         const vector<string> n = mat->get_names();
542         for(unsigned int i=0; i<n.size(); i++)
543             naVec_append(names, naStr_fromdata(naNewString(c),
544                     const_cast<char*>(n[i].c_str()), n[i].size()));
545         HASHSET("names", 5, names);
546         HASHSET("solid", 5, naNum(mat->get_solid()));
547         HASHSET("friction_factor", 15, naNum(mat->get_friction_factor()));
548         HASHSET("rolling_friction", 16, naNum(mat->get_rolling_friction()));
549         HASHSET("load_resistance", 15, naNum(mat->get_load_resistance()));
550         HASHSET("bumpiness", 9, naNum(mat->get_bumpiness()));
551         HASHSET("light_coverage", 14, naNum(mat->get_light_coverage()));
552     }
553     naVec_append(vec, matdata);
554     return vec;
555 #undef HASHSET
556 }
557
558
559 class AirportInfoFilter : public FGAirport::AirportFilter
560 {
561 public:
562     AirportInfoFilter() : type(FGPositioned::AIRPORT) {
563     }
564
565     virtual FGPositioned::Type minType() const {
566         return type;
567     }
568
569     virtual FGPositioned::Type maxType() const {
570         return type;
571     }
572
573     FGPositioned::Type type;
574 };
575
576 // Returns data hash for particular or nearest airport of a <type>, or nil
577 // on error.
578 //
579 // airportinfo(<id>);                   e.g. "KSFO"
580 // airportinfo(<type>);                 type := ("airport"|"seaport"|"heliport")
581 // airportinfo()                        same as  airportinfo("airport")
582 // airportinfo(<lat>, <lon> [, <type>]);
583 static naRef f_airportinfo(naContext c, naRef me, int argc, naRef* args)
584 {
585     static SGConstPropertyNode_ptr latn = fgGetNode("/position/latitude-deg", true);
586     static SGConstPropertyNode_ptr lonn = fgGetNode("/position/longitude-deg", true);
587     SGGeod pos;
588     FGAirport* apt = NULL;
589
590     if(argc >= 2 && naIsNum(args[0]) && naIsNum(args[1])) {
591         pos = SGGeod::fromDeg(args[1].num, args[0].num);
592         args += 2;
593         argc -= 2;
594     } else {
595         pos = SGGeod::fromDeg(lonn->getDoubleValue(), latn->getDoubleValue());
596     }
597
598     double maxRange = 10000.0; // expose this? or pick a smaller value?
599
600     AirportInfoFilter filter; // defaults to airports only
601
602     if(argc == 0) {
603         // fall through and use AIRPORT
604     } else if(argc == 1 && naIsString(args[0])) {
605         const char *s = naStr_data(args[0]);
606         if(!strcmp(s, "airport")) filter.type = FGPositioned::AIRPORT;
607         else if(!strcmp(s, "seaport")) filter.type = FGPositioned::SEAPORT;
608         else if(!strcmp(s, "heliport")) filter.type = FGPositioned::HELIPORT;
609         else {
610             // user provided an <id>, hopefully
611             apt = FGAirport::findByIdent(s);
612             if (!apt) {
613                 // return nil here, but don't raise a runtime error; this is a
614                 // legitamate way to validate an ICAO code, for example in a
615                 // dialog box or similar.
616                 return naNil();
617             }
618         }
619     } else {
620         naRuntimeError(c, "airportinfo() with invalid function arguments");
621         return naNil();
622     }
623
624     if(!apt) {
625         apt = FGAirport::findClosest(pos, maxRange, &filter);
626         if(!apt) return naNil();
627     }
628
629     string id = apt->ident();
630     string name = apt->name();
631
632     // set runway hash
633     naRef rwys = naNewHash(c);
634     for(unsigned int r=0; r<apt->numRunways(); ++r) {
635         FGRunway* rwy(apt->getRunwayByIndex(r));
636
637         naRef rwyid = naStr_fromdata(naNewString(c),
638                       const_cast<char *>(rwy->ident().c_str()),
639                       rwy->ident().length());
640
641         naRef rwydata = naNewHash(c);
642 #define HASHSET(s,l,n) naHash_set(rwydata, naStr_fromdata(naNewString(c),s,l),n)
643         HASHSET("id", 2, rwyid);
644         HASHSET("lat", 3, naNum(rwy->latitude()));
645         HASHSET("lon", 3, naNum(rwy->longitude()));
646         HASHSET("heading", 7, naNum(rwy->headingDeg()));
647         HASHSET("length", 6, naNum(rwy->lengthM()));
648         HASHSET("width", 5, naNum(rwy->widthM()));
649         HASHSET("threshold", 9, naNum(rwy->displacedThresholdM()));
650         HASHSET("stopway", 7, naNum(rwy->stopwayM()));
651         
652         if (rwy->ILS()) {
653           HASHSET("ils_frequency_mhz", 17, naNum(rwy->ILS()->get_freq() / 100.0));
654         }
655         
656         std::vector<flightgear::SID*> sids(rwy->getSIDs());
657         naRef sidVec = naNewVector(c);
658         
659         for (unsigned int s=0; s < sids.size(); ++s) {
660           naRef procId = naStr_fromdata(naNewString(c),
661                     const_cast<char *>(sids[s]->ident().c_str()),
662                     sids[s]->ident().length());
663           naVec_append(sidVec, procId);
664         }
665         HASHSET("sids", 4, sidVec); 
666         
667         std::vector<flightgear::STAR*> stars(rwy->getSTARs());
668         naRef starVec = naNewVector(c);
669       
670         for (unsigned int s=0; s < stars.size(); ++s) {
671           naRef procId = naStr_fromdata(naNewString(c),
672                     const_cast<char *>(stars[s]->ident().c_str()),
673                     stars[s]->ident().length());
674           naVec_append(starVec, procId);
675         }
676         HASHSET("stars", 5, starVec); 
677
678 #undef HASHSET
679         naHash_set(rwys, rwyid, rwydata);
680     }
681
682     // set airport hash
683     naRef aptdata = naNewHash(c);
684 #define HASHSET(s,l,n) naHash_set(aptdata, naStr_fromdata(naNewString(c),s,l),n)
685     HASHSET("id", 2, naStr_fromdata(naNewString(c),
686             const_cast<char *>(id.c_str()), id.length()));
687     HASHSET("name", 4, naStr_fromdata(naNewString(c),
688             const_cast<char *>(name.c_str()), name.length()));
689     HASHSET("lat", 3, naNum(apt->getLatitude()));
690     HASHSET("lon", 3, naNum(apt->getLongitude()));
691     HASHSET("elevation", 9, naNum(apt->getElevation() * SG_FEET_TO_METER));
692     HASHSET("has_metar", 9, naNum(apt->getMetar()));
693     HASHSET("runways", 7, rwys);
694 #undef HASHSET
695     return aptdata;
696 }
697
698
699 // Returns vector of data hash for navaid of a <type>, nil on error
700 // navaids sorted by ascending distance 
701 // navinfo([<lat>,<lon>],[<type>],[<id>])
702 // lat/lon (numeric): use latitude/longitude instead of ac position
703 // type:              ("fix"|"vor"|"ndb"|"ils"|"dme"|"tacan"|"any")
704 // id:                (partial) id of the fix
705 // examples:
706 // navinfo("vor")     returns all vors
707 // navinfo("HAM")     return all navaids who's name start with "HAM"
708 // navinfo("vor", "HAM") return all vor who's name start with "HAM"
709 //navinfo(34,48,"vor","HAM") return all vor who's name start with "HAM" 
710 //                           sorted by distance relative to lat=34, lon=48
711 static naRef f_navinfo(naContext c, naRef me, int argc, naRef* args)
712 {
713     static SGConstPropertyNode_ptr latn = fgGetNode("/position/latitude-deg", true);
714     static SGConstPropertyNode_ptr lonn = fgGetNode("/position/longitude-deg", true);
715     SGGeod pos;
716
717     if(argc >= 2 && naIsNum(args[0]) && naIsNum(args[1])) {
718         pos = SGGeod::fromDeg(args[1].num, args[0].num);
719         args += 2;
720         argc -= 2;
721     } else {
722         pos = SGGeod::fromDeg(lonn->getDoubleValue(), latn->getDoubleValue());
723     }
724
725     FGPositioned::Type type = FGPositioned::INVALID;
726     nav_list_type navlist;
727     const char * id = "";
728
729     if(argc > 0 && naIsString(args[0])) {
730         const char *s = naStr_data(args[0]);
731         if(!strcmp(s, "any")) type = FGPositioned::INVALID;
732         else if(!strcmp(s, "fix")) type = FGPositioned::FIX;
733         else if(!strcmp(s, "vor")) type = FGPositioned::VOR;
734         else if(!strcmp(s, "ndb")) type = FGPositioned::NDB;
735         else if(!strcmp(s, "ils")) type = FGPositioned::ILS;
736         else if(!strcmp(s, "dme")) type = FGPositioned::DME;
737         else if(!strcmp(s, "tacan")) type = FGPositioned::TACAN;
738         else id = s; // this is an id
739         ++args;
740         --argc;
741     } 
742
743     if(argc > 0 && naIsString(args[0])) {
744         if( *id != 0 ) {
745             naRuntimeError(c, "navinfo() called with navaid id");
746             return naNil();
747         }
748         id = naStr_data(args[0]);
749         ++args;
750         --argc;
751     }
752
753     if( argc > 0 ) {
754         naRuntimeError(c, "navinfo() called with too many arguments");
755         return naNil();
756     }
757
758     navlist = globals->get_navlist()->findByIdentAndFreq( pos, id, 0.0, type );
759
760     naRef reply = naNewVector(c);
761     for( nav_list_type::const_iterator it = navlist.begin(); it != navlist.end(); ++it ) {
762         const FGNavRecord * nav = *it;
763
764         // set navdata hash
765         naRef navdata = naNewHash(c);
766 #define HASHSET(s,l,n) naHash_set(navdata, naStr_fromdata(naNewString(c),s,l),n)
767         HASHSET("id", 2, naStr_fromdata(naNewString(c),
768             const_cast<char *>(nav->ident().c_str()), nav->ident().length()));
769         HASHSET("name", 4, naStr_fromdata(naNewString(c),
770             const_cast<char *>(nav->name().c_str()), nav->name().length()));
771         HASHSET("frequency", 9, naNum(nav->get_freq()));
772         HASHSET("lat", 3, naNum(nav->get_lat()));
773         HASHSET("lon", 3, naNum(nav->get_lon()));
774         HASHSET("elevation", 9, naNum(nav->get_elev_ft() * SG_FEET_TO_METER));
775         HASHSET("type", 4, naStr_fromdata(naNewString(c),
776             const_cast<char *>(nav->nameForType(nav->type())), strlen(nav->nameForType(nav->type()))));
777         HASHSET("distance", 8, naNum(SGGeodesy::distanceNm( pos, nav->geod() ) * SG_NM_TO_METER ) );
778         HASHSET("bearing", 7, naNum(SGGeodesy::courseDeg( pos, nav->geod() ) ) );
779 #undef HASHSET
780         naVec_append( reply, navdata );
781     }
782     return reply;
783 }
784
785 // Table of extension functions.  Terminate with zeros.
786 static struct { const char* name; naCFunction func; } funcs[] = {
787     { "getprop",   f_getprop },
788     { "setprop",   f_setprop },
789     { "print",     f_print },
790     { "_fgcommand", f_fgcommand },
791     { "settimer",  f_settimer },
792     { "_setlistener", f_setlistener },
793     { "removelistener", f_removelistener },
794     { "_cmdarg",  f_cmdarg },
795     { "_interpolate",  f_interpolate },
796     { "rand",  f_rand },
797     { "srand",  f_srand },
798     { "abort", f_abort },
799     { "directory", f_directory },
800     { "resolvepath", f_resolveDataPath },
801     { "parsexml", f_parsexml },
802     { "systime", f_systime },
803     { "carttogeod", f_carttogeod },
804     { "geodtocart", f_geodtocart },
805     { "geodinfo", f_geodinfo },
806     { "airportinfo", f_airportinfo },
807     { "navinfo", f_navinfo },
808     { 0, 0 }
809 };
810
811 naRef FGNasalSys::cmdArgGhost()
812 {
813     return propNodeGhost(_cmdArg);
814 }
815
816 void FGNasalSys::init()
817 {
818     int i;
819
820     _context = naNewContext();
821
822     // Start with globals.  Add it to itself as a recursive
823     // sub-reference under the name "globals".  This gives client-code
824     // write access to the namespace if someone wants to do something
825     // fancy.
826     _globals = naInit_std(_context);
827     naSave(_context, _globals);
828     hashset(_globals, "globals", _globals);
829
830     hashset(_globals, "math", naInit_math(_context));
831     hashset(_globals, "bits", naInit_bits(_context));
832     hashset(_globals, "io", naInit_io(_context));
833     hashset(_globals, "thread", naInit_thread(_context));
834     hashset(_globals, "utf8", naInit_utf8(_context));
835
836     // Add our custom extension functions:
837     for(i=0; funcs[i].name; i++)
838         hashset(_globals, funcs[i].name,
839                 naNewFunc(_context, naNewCCode(_context, funcs[i].func)));
840
841     // And our SGPropertyNode wrapper
842     hashset(_globals, "props", genPropsModule());
843
844     // Make a "__gcsave" hash to hold the naRef objects which get
845     // passed to handles outside the interpreter (to protect them from
846     // begin garbage-collected).
847     _gcHash = naNewHash(_context);
848     hashset(_globals, "__gcsave", _gcHash);
849
850     // Now load the various source files in the Nasal directory
851     simgear::Dir nasalDir(SGPath(globals->get_fg_root(), "Nasal"));
852     loadScriptDirectory(nasalDir);
853
854     // Add modules in Nasal subdirectories to property tree
855     simgear::PathList directories = nasalDir.children(simgear::Dir::TYPE_DIR+
856             simgear::Dir::NO_DOT_OR_DOTDOT, "");
857     for (unsigned int i=0; i<directories.size(); ++i) {
858         simgear::Dir dir(directories[i]);
859         simgear::PathList scripts = dir.children(simgear::Dir::TYPE_FILE, ".nas");
860         addModule(directories[i].file(), scripts);
861     }
862
863     // set signal and remove node to avoid restoring at reinit
864     const char *s = "nasal-dir-initialized";
865     SGPropertyNode *signal = fgGetNode("/sim/signals", true);
866     signal->setBoolValue(s, true);
867     signal->removeChildren(s, false);
868
869     // Pull scripts out of the property tree, too
870     loadPropertyScripts();
871 }
872
873 void FGNasalSys::update(double)
874 {
875     if(!_dead_listener.empty()) {
876         vector<FGNasalListener *>::iterator it, end = _dead_listener.end();
877         for(it = _dead_listener.begin(); it != end; ++it) delete *it;
878         _dead_listener.clear();
879     }
880
881     if (!_loadList.empty())
882     {
883         // process Nasal load hook (only one per update loop to avoid excessive lags)
884         _loadList.pop()->load();
885     }
886     else
887     if (!_unloadList.empty())
888     {
889         // process pending Nasal unload hooks after _all_ load hooks were processed
890         // (only unload one per update loop to avoid excessive lags)
891         _unloadList.pop()->unload();
892     }
893
894     // The global context is a legacy thing.  We use dynamically
895     // created contexts for naCall() now, so that we can call them
896     // recursively.  But there are still spots that want to use it for
897     // naNew*() calls, which end up leaking memory because the context
898     // only clears out its temporary vector when it's *used*.  So just
899     // junk it and fetch a new/reinitialized one every frame.  This is
900     // clumsy: the right solution would use the dynamic context in all
901     // cases and eliminate _context entirely.  But that's more work,
902     // and this works fine (yes, they say "New" and "Free", but
903     // they're very fast, just trust me). -Andy
904     naFreeContext(_context);
905     _context = naNewContext();
906 }
907
908 bool pathSortPredicate(const SGPath& p1, const SGPath& p2)
909 {
910   return p1.file() < p2.file();
911 }
912
913 // Loads all scripts in given directory 
914 void FGNasalSys::loadScriptDirectory(simgear::Dir nasalDir)
915 {
916     simgear::PathList scripts = nasalDir.children(simgear::Dir::TYPE_FILE, ".nas");
917     // sort scripts, avoid loading sequence effects due to file system's
918     // random directory order
919     std::sort(scripts.begin(), scripts.end(), pathSortPredicate);
920
921     for (unsigned int i=0; i<scripts.size(); ++i) {
922       SGPath fullpath(scripts[i]);
923       SGPath file = fullpath.file();
924       loadModule(fullpath, file.base().c_str());
925     }
926 }
927
928 // Create module with list of scripts
929 void FGNasalSys::addModule(string moduleName, simgear::PathList scripts)
930 {
931     if (scripts.size()>0)
932     {
933         SGPropertyNode* nasal = globals->get_props()->getNode("nasal");
934         SGPropertyNode* module_node = nasal->getChild(moduleName,0,true);
935         for (unsigned int i=0; i<scripts.size(); ++i) {
936             SGPropertyNode* pFileNode = module_node->getChild("file",i,true);
937             pFileNode->setStringValue(scripts[i].c_str());
938         }
939         if (!module_node->hasChild("enabled",0))
940         {
941             SGPropertyNode* node = module_node->getChild("enabled",0,true);
942             node->setBoolValue(true);
943             node->setAttribute(SGPropertyNode::USERARCHIVE,true);
944         }
945     }
946 }
947
948 // Loads the scripts found under /nasal in the global tree
949 void FGNasalSys::loadPropertyScripts()
950 {
951     SGPropertyNode* nasal = globals->get_props()->getNode("nasal");
952     if(!nasal) return;
953
954     for(int i=0; i<nasal->nChildren(); i++)
955     {
956         SGPropertyNode* n = nasal->getChild(i);
957         loadPropertyScripts(n);
958     }
959 }
960
961 // Loads the scripts found under /nasal in the global tree
962 void FGNasalSys::loadPropertyScripts(SGPropertyNode* n)
963 {
964     bool is_loaded = false;
965
966     const char* module = n->getName();
967     if(n->hasChild("module"))
968         module = n->getStringValue("module");
969     if (n->getBoolValue("enabled",true))
970     {
971         // allow multiple files to be specified within a single
972         // Nasal module tag
973         int j = 0;
974         SGPropertyNode *fn;
975         bool file_specified = false;
976         bool ok=true;
977         while((fn = n->getChild("file", j)) != NULL) {
978             file_specified = true;
979             const char* file = fn->getStringValue();
980             SGPath p(file);
981             if (!p.isAbsolute() || !p.exists())
982             {
983                 p = globals->resolve_maybe_aircraft_path(file);
984                 if (p.isNull())
985                 {
986                     SG_LOG(SG_NASAL, SG_ALERT, "Cannot find Nasal script '" <<
987                             file << "' for module '" << module << "'.");
988                 }
989             }
990             ok &= p.isNull() ? false : loadModule(p, module);
991             j++;
992         }
993
994         const char* src = n->getStringValue("script");
995         if(!n->hasChild("script")) src = 0; // Hrm...
996         if(src)
997             createModule(module, n->getPath().c_str(), src, strlen(src));
998
999         if(!file_specified && !src)
1000         {
1001             // module no longer exists - clear the archived "enable" flag
1002             n->setAttribute(SGPropertyNode::USERARCHIVE,false);
1003             SGPropertyNode* node = n->getChild("enabled",0,false);
1004             if (node)
1005                 node->setAttribute(SGPropertyNode::USERARCHIVE,false);
1006
1007             SG_LOG(SG_NASAL, SG_ALERT, "Nasal error: " <<
1008                     "no <file> or <script> defined in " <<
1009                     "/nasal/" << module);
1010         }
1011         else
1012             is_loaded = ok;
1013     }
1014     else
1015     {
1016         SGPropertyNode* enable = n->getChild("enabled");
1017         if (enable)
1018         {
1019             FGNasalModuleListener* listener = new FGNasalModuleListener(n);
1020             enable->addChangeListener(listener, false);
1021         }
1022     }
1023     SGPropertyNode* loaded = n->getChild("loaded",0,true);
1024     loaded->setAttribute(SGPropertyNode::PRESERVE,true);
1025     loaded->setBoolValue(is_loaded);
1026 }
1027
1028 // Logs a runtime error, with stack trace, to the FlightGear log stream
1029 void FGNasalSys::logError(naContext context)
1030 {
1031     SG_LOG(SG_NASAL, SG_ALERT,
1032            "Nasal runtime error: " << naGetError(context));
1033     SG_LOG(SG_NASAL, SG_ALERT,
1034            "  at " << naStr_data(naGetSourceFile(context, 0)) <<
1035            ", line " << naGetLine(context, 0));
1036     for(int i=1; i<naStackDepth(context); i++)
1037         SG_LOG(SG_NASAL, SG_ALERT,
1038                "  called from: " << naStr_data(naGetSourceFile(context, i)) <<
1039                ", line " << naGetLine(context, i));
1040 }
1041
1042 // Reads a script file, executes it, and places the resulting
1043 // namespace into the global namespace under the specified module
1044 // name.
1045 bool FGNasalSys::loadModule(SGPath file, const char* module)
1046 {
1047     int len = 0;
1048     char* buf = readfile(file.c_str(), &len);
1049     if(!buf) {
1050         SG_LOG(SG_NASAL, SG_ALERT,
1051                "Nasal error: could not read script file " << file.c_str()
1052                << " into module " << module);
1053         return false;
1054     }
1055
1056     bool ok = createModule(module, file.c_str(), buf, len);
1057     delete[] buf;
1058     return ok;
1059 }
1060
1061 // Parse and run.  Save the local variables namespace, as it will
1062 // become a sub-object of globals.  The optional "arg" argument can be
1063 // used to pass an associated property node to the module, which can then
1064 // be accessed via cmdarg().  (This is, for example, used by XML dialogs.)
1065 bool FGNasalSys::createModule(const char* moduleName, const char* fileName,
1066                               const char* src, int len,
1067                               const SGPropertyNode* cmdarg,
1068                               int argc, naRef* args)
1069 {
1070     naRef code = parse(fileName, src, len);
1071     if(naIsNil(code))
1072         return false;
1073
1074     // See if we already have a module hash to use.  This allows the
1075     // user to, for example, add functions to the built-in math
1076     // module.  Make a new one if necessary.
1077     naRef locals;
1078     naRef modname = naNewString(_context);
1079     naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
1080     if(!naHash_get(_globals, modname, &locals))
1081         locals = naNewHash(_context);
1082
1083     _cmdArg = (SGPropertyNode*)cmdarg;
1084
1085     call(code, argc, args, locals);
1086     hashset(_globals, moduleName, locals);
1087     return true;
1088 }
1089
1090 void FGNasalSys::deleteModule(const char* moduleName)
1091 {
1092     naRef modname = naNewString(_context);
1093     naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
1094     naHash_delete(_globals, modname);
1095 }
1096
1097 naRef FGNasalSys::parse(const char* filename, const char* buf, int len)
1098 {
1099     int errLine = -1;
1100     naRef srcfile = naNewString(_context);
1101     naStr_fromdata(srcfile, (char*)filename, strlen(filename));
1102     naRef code = naParseCode(_context, srcfile, 1, (char*)buf, len, &errLine);
1103     if(naIsNil(code)) {
1104         SG_LOG(SG_NASAL, SG_ALERT,
1105                "Nasal parse error: " << naGetError(_context) <<
1106                " in "<< filename <<", line " << errLine);
1107         return naNil();
1108     }
1109
1110     // Bind to the global namespace before returning
1111     return naBindFunction(_context, code, _globals);
1112 }
1113
1114 bool FGNasalSys::handleCommand(const SGPropertyNode* arg)
1115 {
1116     const char* nasal = arg->getStringValue("script");
1117     const char* moduleName = arg->getStringValue("module");
1118     naRef code = parse(arg->getPath(true).c_str(), nasal, strlen(nasal));
1119     if(naIsNil(code)) return false;
1120
1121     // Commands can be run "in" a module.  Make sure that module
1122     // exists, and set it up as the local variables hash for the
1123     // command.
1124     naRef locals = naNil();
1125     if(moduleName[0]) {
1126         naRef modname = naNewString(_context);
1127         naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
1128         if(!naHash_get(_globals, modname, &locals)) {
1129             locals = naNewHash(_context);
1130             naHash_set(_globals, modname, locals);
1131         }
1132     }
1133
1134     // Cache this command's argument for inspection via cmdarg().  For
1135     // performance reasons, we won't bother with it if the invoked
1136     // code doesn't need it.
1137     _cmdArg = (SGPropertyNode*)arg;
1138
1139     call(code, 0, 0, locals);
1140     return true;
1141 }
1142
1143 // settimer(func, dt, simtime) extension function.  The first argument
1144 // is a Nasal function to call, the second is a delta time (from now),
1145 // in seconds.  The third, if present, is a boolean value indicating
1146 // that "real world" time (rather than simulator time) is to be used.
1147 //
1148 // Implementation note: the FGTimer objects don't live inside the
1149 // garbage collector, so the Nasal handler functions have to be
1150 // "saved" somehow lest they be inadvertently cleaned.  In this case,
1151 // they are inserted into a globals.__gcsave hash and removed on
1152 // expiration.
1153 void FGNasalSys::setTimer(naContext c, int argc, naRef* args)
1154 {
1155     // Extract the handler, delta, and simtime arguments:
1156     naRef handler = argc > 0 ? args[0] : naNil();
1157     if(!(naIsCode(handler) || naIsCCode(handler) || naIsFunc(handler))) {
1158         naRuntimeError(c, "settimer() with invalid function argument");
1159         return;
1160     }
1161
1162     naRef delta = argc > 1 ? args[1] : naNil();
1163     if(naIsNil(delta)) {
1164         naRuntimeError(c, "settimer() with invalid time argument");
1165         return;
1166     }
1167
1168     bool simtime = (argc > 2 && naTrue(args[2])) ? false : true;
1169
1170     // Generate and register a C++ timer handler
1171     NasalTimer* t = new NasalTimer;
1172     t->handler = handler;
1173     t->gcKey = gcSave(handler);
1174     t->nasal = this;
1175
1176     globals->get_event_mgr()->addEvent("NasalTimer",
1177                                        t, &NasalTimer::timerExpired,
1178                                        delta.num, simtime);
1179 }
1180
1181 void FGNasalSys::handleTimer(NasalTimer* t)
1182 {
1183     call(t->handler, 0, 0, naNil());
1184     gcRelease(t->gcKey);
1185 }
1186
1187 int FGNasalSys::gcSave(naRef r)
1188 {
1189     int key = _nextGCKey++;
1190     naHash_set(_gcHash, naNum(key), r);
1191     return key;
1192 }
1193
1194 void FGNasalSys::gcRelease(int key)
1195 {
1196     naHash_delete(_gcHash, naNum(key));
1197 }
1198
1199 void FGNasalSys::NasalTimer::timerExpired()
1200 {
1201     nasal->handleTimer(this);
1202     delete this;
1203 }
1204
1205 int FGNasalSys::_listenerId = 0;
1206
1207 // setlistener(<property>, <func> [, <initial=0> [, <persistent=1>]])
1208 // Attaches a callback function to a property (specified as a global
1209 // property path string or a SGPropertyNode_ptr* ghost). If the third,
1210 // optional argument (default=0) is set to 1, then the function is also
1211 // called initially. If the fourth, optional argument is set to 0, then the
1212 // function is only called when the property node value actually changes.
1213 // Otherwise it's called independent of the value whenever the node is
1214 // written to (default). The setlistener() function returns a unique
1215 // id number, which is to be used as argument to the removelistener()
1216 // function.
1217 naRef FGNasalSys::setListener(naContext c, int argc, naRef* args)
1218 {
1219     SGPropertyNode_ptr node;
1220     naRef prop = argc > 0 ? args[0] : naNil();
1221     if(naIsString(prop)) node = fgGetNode(naStr_data(prop), true);
1222     else if(naIsGhost(prop)) node = *(SGPropertyNode_ptr*)naGhost_ptr(prop);
1223     else {
1224         naRuntimeError(c, "setlistener() with invalid property argument");
1225         return naNil();
1226     }
1227
1228     if(node->isTied())
1229         SG_LOG(SG_NASAL, SG_DEBUG, "Attaching listener to tied property " <<
1230                 node->getPath());
1231
1232     naRef code = argc > 1 ? args[1] : naNil();
1233     if(!(naIsCode(code) || naIsCCode(code) || naIsFunc(code))) {
1234         naRuntimeError(c, "setlistener() with invalid function argument");
1235         return naNil();
1236     }
1237
1238     int init = argc > 2 && naIsNum(args[2]) ? int(args[2].num) : 0;
1239     int type = argc > 3 && naIsNum(args[3]) ? int(args[3].num) : 1;
1240     FGNasalListener *nl = new FGNasalListener(node, code, this,
1241             gcSave(code), _listenerId, init, type);
1242
1243     node->addChangeListener(nl, init != 0);
1244
1245     _listener[_listenerId] = nl;
1246     return naNum(_listenerId++);
1247 }
1248
1249 // removelistener(int) extension function. The argument is the id of
1250 // a listener as returned by the setlistener() function.
1251 naRef FGNasalSys::removeListener(naContext c, int argc, naRef* args)
1252 {
1253     naRef id = argc > 0 ? args[0] : naNil();
1254     map<int, FGNasalListener *>::iterator it = _listener.find(int(id.num));
1255
1256     if(!naIsNum(id) || it == _listener.end() || it->second->_dead) {
1257         naRuntimeError(c, "removelistener() with invalid listener id");
1258         return naNil();
1259     }
1260
1261     it->second->_dead = true;
1262     _dead_listener.push_back(it->second);
1263     _listener.erase(it);
1264     return naNum(_listener.size());
1265 }
1266
1267
1268
1269 // FGNasalListener class.
1270
1271 FGNasalListener::FGNasalListener(SGPropertyNode *node, naRef code,
1272                                  FGNasalSys* nasal, int key, int id,
1273                                  int init, int type) :
1274     _node(node),
1275     _code(code),
1276     _gcKey(key),
1277     _id(id),
1278     _nas(nasal),
1279     _init(init),
1280     _type(type),
1281     _active(0),
1282     _dead(false),
1283     _last_int(0L),
1284     _last_float(0.0)
1285 {
1286     if(_type == 0 && !_init)
1287         changed(node);
1288 }
1289
1290 FGNasalListener::~FGNasalListener()
1291 {
1292     _node->removeChangeListener(this);
1293     _nas->gcRelease(_gcKey);
1294 }
1295
1296 void FGNasalListener::call(SGPropertyNode* which, naRef mode)
1297 {
1298     if(_active || _dead) return;
1299     SG_LOG(SG_NASAL, SG_DEBUG, "trigger listener #" << _id);
1300     _active++;
1301     naRef arg[4];
1302     arg[0] = _nas->propNodeGhost(which);
1303     arg[1] = _nas->propNodeGhost(_node);
1304     arg[2] = mode;                  // value changed, child added/removed
1305     arg[3] = naNum(_node != which); // child event?
1306     _nas->call(_code, 4, arg, naNil());
1307     _active--;
1308 }
1309
1310 void FGNasalListener::valueChanged(SGPropertyNode* node)
1311 {
1312     if(_type < 2 && node != _node) return;   // skip child events
1313     if(_type > 0 || changed(_node) || _init)
1314         call(node, naNum(0));
1315
1316     _init = 0;
1317 }
1318
1319 void FGNasalListener::childAdded(SGPropertyNode*, SGPropertyNode* child)
1320 {
1321     if(_type == 2) call(child, naNum(1));
1322 }
1323
1324 void FGNasalListener::childRemoved(SGPropertyNode*, SGPropertyNode* child)
1325 {
1326     if(_type == 2) call(child, naNum(-1));
1327 }
1328
1329 bool FGNasalListener::changed(SGPropertyNode* node)
1330 {
1331     using namespace simgear;
1332     props::Type type = node->getType();
1333     if(type == props::NONE) return false;
1334     if(type == props::UNSPECIFIED) return true;
1335
1336     bool result;
1337     switch(type) {
1338     case props::BOOL:
1339     case props::INT:
1340     case props::LONG:
1341         {
1342             long l = node->getLongValue();
1343             result = l != _last_int;
1344             _last_int = l;
1345             return result;
1346         }
1347     case props::FLOAT:
1348     case props::DOUBLE:
1349         {
1350             double d = node->getDoubleValue();
1351             result = d != _last_float;
1352             _last_float = d;
1353             return result;
1354         }
1355     default:
1356         {
1357             string s = node->getStringValue();
1358             result = s != _last_string;
1359             _last_string = s;
1360             return result;
1361         }
1362     }
1363 }
1364
1365
1366
1367 // FGNasalModelData class.  If sgLoad3DModel() is called with a pointer to
1368 // such a class, then it lets modelLoaded() run the <load> script, and the
1369 // destructor the <unload> script. The latter happens when the model branch
1370 // is removed from the scene graph.
1371
1372 unsigned int FGNasalModelData::_module_id = 0;
1373
1374 void FGNasalModelData::load()
1375 {
1376     std::stringstream m;
1377     m << "__model" << _module_id++;
1378     _module = m.str();
1379
1380     SG_LOG(SG_NASAL, SG_DEBUG, "Loading nasal module " << _module.c_str());
1381
1382     const char *s = _load ? _load->getStringValue() : "";
1383
1384     naRef arg[2];
1385     arg[0] = nasalSys->propNodeGhost(_root);
1386     arg[1] = nasalSys->propNodeGhost(_prop);
1387     nasalSys->createModule(_module.c_str(), _path.c_str(), s, strlen(s),
1388                            _root, 2, arg);
1389 }
1390
1391 void FGNasalModelData::unload()
1392 {
1393     if (_module.empty())
1394         return;
1395
1396     if(!nasalSys) {
1397         SG_LOG(SG_NASAL, SG_WARN, "Trying to run an <unload> script "
1398                 "without Nasal subsystem present.");
1399         return;
1400     }
1401
1402     SG_LOG(SG_NASAL, SG_DEBUG, "Unloading nasal module " << _module.c_str());
1403
1404     if (_unload)
1405     {
1406         const char *s = _unload->getStringValue();
1407         nasalSys->createModule(_module.c_str(), _module.c_str(), s, strlen(s), _root);
1408     }
1409
1410     nasalSys->deleteModule(_module.c_str());
1411 }
1412
1413 void FGNasalModelDataProxy::modelLoaded(const string& path, SGPropertyNode *prop,
1414                                    osg::Node *)
1415 {
1416     if(!nasalSys) {
1417         SG_LOG(SG_NASAL, SG_WARN, "Trying to run a <load> script "
1418                 "without Nasal subsystem present.");
1419         return;
1420     }
1421
1422     if(!prop)
1423         return;
1424
1425     SGPropertyNode *nasal = prop->getNode("nasal");
1426     if(!nasal)
1427         return;
1428
1429     SGPropertyNode* load   = nasal->getNode("load");
1430     SGPropertyNode* unload = nasal->getNode("unload");
1431
1432     if ((!load) && (!unload))
1433         return;
1434
1435     _data = new FGNasalModelData(_root, path, prop, load, unload);
1436
1437     // register Nasal module to be created and loaded in the main thread.
1438     nasalSys->registerToLoad(_data);
1439 }
1440
1441 FGNasalModelDataProxy::~FGNasalModelDataProxy()
1442 {
1443     // when necessary, register Nasal module to be destroyed/unloaded
1444     // in the main thread.
1445     if ((_data.valid())&&(nasalSys))
1446         nasalSys->registerToUnload(_data);
1447 }
1448
1449 // NasalXMLVisitor class: handles EasyXML visitor callback for parsexml()
1450 //
1451 NasalXMLVisitor::NasalXMLVisitor(naContext c, int argc, naRef* args) :
1452     _c(naSubContext(c)),
1453     _start_element(argc > 1 ? args[1] : naNil()),
1454     _end_element(argc > 2 ? args[2] : naNil()),
1455     _data(argc > 3 ? args[3] : naNil()),
1456     _pi(argc > 4 ? args[4] : naNil())
1457 {
1458 }
1459
1460 void NasalXMLVisitor::startElement(const char* tag, const XMLAttributes& a)
1461 {
1462     if(naIsNil(_start_element)) return;
1463     naRef attr = naNewHash(_c);
1464     for(int i=0; i<a.size(); i++) {
1465         naRef name = make_string(a.getName(i));
1466         naRef value = make_string(a.getValue(i));
1467         naHash_set(attr, name, value);
1468     }
1469     call(_start_element, 2, make_string(tag), attr);
1470 }
1471
1472 void NasalXMLVisitor::endElement(const char* tag)
1473 {
1474     if(!naIsNil(_end_element)) call(_end_element, 1, make_string(tag));
1475 }
1476
1477 void NasalXMLVisitor::data(const char* str, int len)
1478 {
1479     if(!naIsNil(_data)) call(_data, 1, make_string(str, len));
1480 }
1481
1482 void NasalXMLVisitor::pi(const char* target, const char* data)
1483 {
1484     if(!naIsNil(_pi)) call(_pi, 2, make_string(target), make_string(data));
1485 }
1486
1487 void NasalXMLVisitor::call(naRef func, int num, naRef a, naRef b)
1488 {
1489     naRef args[2];
1490     args[0] = a;
1491     args[1] = b;
1492     naCall(_c, func, num, args, naNil(), naNil());
1493     if(naGetError(_c))
1494         naRethrowError(_c);
1495 }
1496
1497 naRef NasalXMLVisitor::make_string(const char* s, int n)
1498 {
1499     return naStr_fromdata(naNewString(_c), const_cast<char *>(s),
1500                           n < 0 ? strlen(s) : n);
1501 }
1502
1503