]> git.mxchange.org Git - flightgear.git/blob - src/Scripting/NasalSys.cxx
Maik JUSTUS: add functions carttogeod() and geodtocart() to convert between
[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
15 #include <plib/ul.h>
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/interpolator.hxx>
22 #include <simgear/structure/commands.hxx>
23 #include <simgear/math/sg_geodesy.hxx>
24
25 #include <Main/globals.hxx>
26 #include <Main/fg_props.hxx>
27
28 #include "NasalSys.hxx"
29
30 static FGNasalSys* nasalSys = 0;
31
32
33 // Read and return file contents in a single buffer.  Note use of
34 // stat() to get the file size.  This is a win32 function, believe it
35 // or not. :) Note the REALLY IMPORTANT use of the "b" flag to fopen.
36 // Text mode brain damage will kill us if we're trying to do bytewise
37 // I/O.
38 static char* readfile(const char* file, int* lenOut)
39 {
40     struct stat data;
41     if(stat(file, &data) != 0) return 0;
42     FILE* f = fopen(file, "rb");
43     if(!f) return 0;
44     char* buf = new char[data.st_size];
45     *lenOut = fread(buf, 1, data.st_size, f);
46     fclose(f);
47     if(*lenOut != data.st_size) {
48         // Shouldn't happen, but warn anyway since it represents a
49         // platform bug and not a typical runtime error (missing file,
50         // etc...)
51         SG_LOG(SG_NASAL, SG_ALERT,
52                "ERROR in Nasal initialization: " <<
53                "short count returned from fread() of " << file <<
54                ".  Check your C library!");
55         delete[] buf;
56         return 0;
57     }
58     return buf;
59 }
60
61 FGNasalSys::FGNasalSys()
62 {
63     nasalSys = this;
64     _context = 0;
65     _globals = naNil();
66     _gcHash = naNil();
67     _nextGCKey = 0; // Any value will do
68     _callCount = 0;
69     _purgeListeners = false;
70 }
71
72 // Does a naCall() in a new context.  Wrapped here to make lock
73 // tracking easier.  Extension functions are called with the lock, but
74 // we have to release it before making a new naCall().  So rather than
75 // drop the lock in every extension function that might call back into
76 // Nasal, we keep a stack depth counter here and only unlock/lock
77 // around the naCall if it isn't the first one.
78 naRef FGNasalSys::call(naRef code, naRef locals)
79 {
80     naContext ctx = naNewContext();
81     if(_callCount) naModUnlock();
82     _callCount++;
83     naRef result = naCall(ctx, code, 0, 0, naNil(), locals);
84     if(naGetError(ctx))
85         logError(ctx);
86     _callCount--;
87     if(_callCount) naModLock();
88     naFreeContext(ctx);
89     return result;
90 }
91
92 FGNasalSys::~FGNasalSys()
93 {
94     nasalSys = 0;
95     map<int, FGNasalListener *>::iterator it, end = _listener.end();
96     for(it = _listener.begin(); it != end; ++it)
97         delete it->second;
98
99     naFreeContext(_context);
100     _globals = naNil();
101 }
102
103 bool FGNasalSys::parseAndRun(const char* sourceCode)
104 {
105     naRef code = parse("FGNasalSys::parseAndRun()", sourceCode,
106                        strlen(sourceCode));
107     if(naIsNil(code))
108         return false;
109     call(code, naNil());
110     return true;
111 }
112
113 FGNasalScript* FGNasalSys::parseScript(const char* src, const char* name)
114 {
115     FGNasalScript* script = new FGNasalScript();
116     script->_gcKey = -1; // important, if we delete it on a parse
117     script->_nas = this; // error, don't clobber a real handle!
118
119     char buf[256];
120     if(!name) {
121         sprintf(buf, "FGNasalScript@%p", (void *)script);
122         name = buf;
123     }
124
125     script->_code = parse(name, src, strlen(src));
126     if(naIsNil(script->_code)) {
127         delete script;
128         return 0;
129     }
130
131     script->_gcKey = gcSave(script->_code);
132     return script;
133 }
134
135 // Utility.  Sets a named key in a hash by C string, rather than nasal
136 // string object.
137 void FGNasalSys::hashset(naRef hash, const char* key, naRef val)
138 {
139     naRef s = naNewString(_context);
140     naStr_fromdata(s, (char*)key, strlen(key));
141     naHash_set(hash, s, val);
142 }
143
144 // The get/setprop functions accept a *list* of strings and walk
145 // through the property tree with them to find the appropriate node.
146 // This allows a Nasal object to hold onto a property path and use it
147 // like a node object, e.g. setprop(ObjRoot, "size-parsecs", 2.02).  This
148 // is the utility function that walks the property tree.
149 // Future enhancement: support integer arguments to specify array
150 // elements.
151 static SGPropertyNode* findnode(naContext c, naRef* vec, int len)
152 {
153     SGPropertyNode* p = globals->get_props();
154     try {
155         for(int i=0; i<len; i++) {
156             naRef a = vec[i];
157             if(!naIsString(a)) return 0;
158             p = p->getNode(naStr_data(a));
159             if(p == 0) return 0;
160         }
161     } catch (const string& err) {
162         naRuntimeError(c, (char *)err.c_str());
163         return 0;
164     }
165     return p;
166 }
167
168 // getprop() extension function.  Concatenates its string arguments as
169 // property names and returns the value of the specified property.  Or
170 // nil if it doesn't exist.
171 static naRef f_getprop(naContext c, naRef me, int argc, naRef* args)
172 {
173     const SGPropertyNode* p = findnode(c, args, argc);
174     if(!p) return naNil();
175
176     switch(p->getType()) {
177     case SGPropertyNode::BOOL:   case SGPropertyNode::INT:
178     case SGPropertyNode::LONG:   case SGPropertyNode::FLOAT:
179     case SGPropertyNode::DOUBLE:
180         return naNum(p->getDoubleValue());
181
182     case SGPropertyNode::STRING:
183     case SGPropertyNode::UNSPECIFIED:
184         {
185             naRef nastr = naNewString(c);
186             const char* val = p->getStringValue();
187             naStr_fromdata(nastr, (char*)val, strlen(val));
188             return nastr;
189         }
190     case SGPropertyNode::ALIAS: // <--- FIXME, recurse?
191     default:
192         return naNil();
193     }
194 }
195
196 // setprop() extension function.  Concatenates its string arguments as
197 // property names and sets the value of the specified property to the
198 // final argument.
199 static naRef f_setprop(naContext c, naRef me, int argc, naRef* args)
200 {
201 #define BUFLEN 1024
202     char buf[BUFLEN + 1];
203     buf[BUFLEN] = 0;
204     char* p = buf;
205     int buflen = BUFLEN;
206     for(int i=0; i<argc-1; i++) {
207         naRef s = naStringValue(c, args[i]);
208         if(naIsNil(s)) return naNil();
209         strncpy(p, naStr_data(s), buflen);
210         p += naStr_len(s);
211         buflen = BUFLEN - (p - buf);
212         if(i < (argc-2) && buflen > 0) {
213             *p++ = '/';
214             buflen--;
215         }
216     }
217
218     SGPropertyNode* props = globals->get_props();
219     naRef val = args[argc-1];
220     try {
221         if(naIsString(val)) props->setStringValue(buf, naStr_data(val));
222         else {
223             naRef n = naNumValue(val);
224             if(naIsNil(n))
225                 naRuntimeError(c, "setprop() value is not string or number");
226             props->setDoubleValue(buf, n.num);
227         }
228     } catch (const string& err) {
229         naRuntimeError(c, (char *)err.c_str());
230     }
231     return naNil();
232 #undef BUFLEN
233 }
234
235 // print() extension function.  Concatenates and prints its arguments
236 // to the FlightGear log.  Uses the highest log level (SG_ALERT), to
237 // make sure it appears.  Is there better way to do this?
238 static naRef f_print(naContext c, naRef me, int argc, naRef* args)
239 {
240     string buf;
241     int n = argc;
242     for(int i=0; i<n; i++) {
243         naRef s = naStringValue(c, args[i]);
244         if(naIsNil(s)) continue;
245         buf += naStr_data(s);
246     }
247     SG_LOG(SG_GENERAL, SG_ALERT, buf);
248     return naNum(buf.length());
249 }
250
251 // fgcommand() extension function.  Executes a named command via the
252 // FlightGear command manager.  Takes a single property node name as
253 // an argument.
254 static naRef f_fgcommand(naContext c, naRef me, int argc, naRef* args)
255 {
256     naRef cmd = argc > 0 ? args[0] : naNil();
257     naRef props = argc > 1 ? args[1] : naNil();
258     if(!naIsString(cmd) || (!naIsNil(props) && !naIsGhost(props)))
259         naRuntimeError(c, "bad arguments to fgcommand()");
260     SGPropertyNode_ptr tmp, *node;
261     if(!naIsNil(props))
262         node = (SGPropertyNode_ptr*)naGhost_ptr(props);
263     else {
264         tmp = new SGPropertyNode();
265         node = &tmp;
266     }
267     return naNum(globals->get_commands()->execute(naStr_data(cmd), *node));
268 }
269
270 // settimer(func, dt, simtime) extension function.  Falls through to
271 // FGNasalSys::setTimer().  See there for docs.
272 static naRef f_settimer(naContext c, naRef me, int argc, naRef* args)
273 {
274     nasalSys->setTimer(c, argc, args);
275     return naNil();
276 }
277
278 // setlistener(func, property, bool) extension function.  Falls through to
279 // FGNasalSys::setListener().  See there for docs.
280 static naRef f_setlistener(naContext c, naRef me, int argc, naRef* args)
281 {
282     return nasalSys->setListener(c, argc, args);
283 }
284
285 // removelistener(int) extension function. Falls through to
286 // FGNasalSys::removeListener(). See there for docs.
287 static naRef f_removelistener(naContext c, naRef me, int argc, naRef* args)
288 {
289     return nasalSys->removeListener(c, argc, args);
290 }
291
292 // Returns a ghost handle to the argument to the currently executing
293 // command
294 static naRef f_cmdarg(naContext c, naRef me, int argc, naRef* args)
295 {
296     return nasalSys->cmdArgGhost();
297 }
298
299 // Sets up a property interpolation.  The first argument is either a
300 // ghost (SGPropertyNode_ptr*) or a string (global property path) to
301 // interpolate.  The second argument is a vector of pairs of
302 // value/delta numbers.
303 static naRef f_interpolate(naContext c, naRef me, int argc, naRef* args)
304 {
305     SGPropertyNode* node;
306     naRef prop = argc > 0 ? args[0] : naNil();
307     if(naIsString(prop)) node = fgGetNode(naStr_data(prop), true);
308     else if(naIsGhost(prop)) node = *(SGPropertyNode_ptr*)naGhost_ptr(prop);
309     else return naNil();
310
311     naRef curve = argc > 1 ? args[1] : naNil();
312     if(!naIsVector(curve)) return naNil();
313     int nPoints = naVec_size(curve) / 2;
314     double* values = new double[nPoints];
315     double* deltas = new double[nPoints];
316     for(int i=0; i<nPoints; i++) {
317         values[i] = naNumValue(naVec_get(curve, 2*i)).num;
318         deltas[i] = naNumValue(naVec_get(curve, 2*i+1)).num;
319     }
320
321     ((SGInterpolator*)globals->get_subsystem_mgr()
322         ->get_group(SGSubsystemMgr::INIT)->get_subsystem("interpolator"))
323         ->interpolate(node, nPoints, values, deltas);
324
325     return naNil();
326 }
327
328 // This is a better RNG than the one in the default Nasal distribution
329 // (which is based on the C library rand() implementation). It will
330 // override.
331 static naRef f_rand(naContext c, naRef me, int argc, naRef* args)
332 {
333     return naNum(sg_random());
334 }
335
336 static naRef f_srand(naContext c, naRef me, int argc, naRef* args)
337 {
338     sg_srandom_time();
339     return naNum(0);
340 }
341
342 // Return an array listing of all files in a directory
343 static naRef f_directory(naContext c, naRef me, int argc, naRef* args)
344 {
345     if(argc != 1 || !naIsString(args[0]))
346         naRuntimeError(c, "bad arguments to directory()");
347     naRef ldir = args[0];
348     ulDir* dir = ulOpenDir(naStr_data(args[0]));
349     if(!dir) return naNil();
350     naRef result = naNewVector(c);
351     ulDirEnt* dent;
352     while((dent = ulReadDir(dir)))
353         naVec_append(result, naStr_fromdata(naNewString(c), dent->d_name,
354                                             strlen(dent->d_name)));
355     ulCloseDir(dir);
356     return result;
357 }
358
359 // Return UNIX epoch time in seconds.
360 static naRef f_systime(naContext c, naRef me, int argc, naRef* args)
361 {
362 #ifdef WIN32
363     FILETIME ft;
364     GetSystemTimeAsFileTime(&ft);
365     double t = (4294967296.0 * ft.dwHighDateTime + ft.dwLowDateTime);
366     // Converts from 100ns units in 1601 epoch to unix epoch in sec
367     return naNum((t * 1e-7) - 11644473600.0);
368 #else
369     time_t t;
370     struct timeval td;
371     do { t = time(0); gettimeofday(&td, 0); } while(t != time(0));
372     return naNum(t + 1e-6 * td.tv_usec);
373 #endif
374
375 }
376
377 // Convert a cartesian point to a geodetic lat/lon/altitude.
378 static naRef f_carttogeod(naContext c, naRef me, int argc, naRef* args)
379 {
380     double lat, lon, alt, xyz[3];
381     static const float RAD2DEG = 1./0.0174532925199;
382     if(argc != 3) naRuntimeError(c, "carttogeod() expects 3 arguments");
383     for(int i=0; i<3; i++)
384         xyz[i] = naNumValue(args[i]).num;
385     sgCartToGeod(xyz, &lat, &lon, &alt);
386     lat *= RAD2DEG;
387     lon *= RAD2DEG;
388     naRef vec = naNewVector(c);
389     naVec_append(vec, naNum(lat));
390     naVec_append(vec, naNum(lon));
391     naVec_append(vec, naNum(alt));
392     return vec;
393 }
394
395 // Convert a cartesian point to a geodetic lat/lon/altitude.
396 static naRef f_geodtocart(naContext c, naRef me, int argc, naRef* args)
397 {
398     static const float DEG2RAD = 0.0174532925199;
399     if(argc != 3) naRuntimeError(c, "geodtocart() expects 3 arguments");
400     double lat = naNumValue(args[0]).num * DEG2RAD;
401     double lon = naNumValue(args[1]).num * DEG2RAD;
402     double alt = naNumValue(args[2]).num * DEG2RAD;
403     double xyz[3];
404     sgGeodToCart(lat, lon, alt, xyz);
405     naRef vec = naNewVector(c);
406     naVec_append(vec, naNum(xyz[0]));
407     naVec_append(vec, naNum(xyz[1]));
408     naVec_append(vec, naNum(xyz[2]));
409     return vec;
410 }
411
412 // Table of extension functions.  Terminate with zeros.
413 static struct { char* name; naCFunction func; } funcs[] = {
414     { "getprop",   f_getprop },
415     { "setprop",   f_setprop },
416     { "print",     f_print },
417     { "_fgcommand", f_fgcommand },
418     { "settimer",  f_settimer },
419     { "_setlistener", f_setlistener },
420     { "removelistener", f_removelistener },
421     { "_cmdarg",  f_cmdarg },
422     { "_interpolate",  f_interpolate },
423     { "rand",  f_rand },
424     { "srand",  f_srand },
425     { "directory", f_directory },
426     { "systime", f_systime },
427     { "carttogeod", f_carttogeod },
428     { "geodtocart", f_geodtocart },
429     { 0, 0 }
430 };
431
432 naRef FGNasalSys::cmdArgGhost()
433 {
434     return propNodeGhost(_cmdArg);
435 }
436
437 void FGNasalSys::init()
438 {
439     int i;
440
441     _context = naNewContext();
442
443     // Start with globals.  Add it to itself as a recursive
444     // sub-reference under the name "globals".  This gives client-code
445     // write access to the namespace if someone wants to do something
446     // fancy.
447     _globals = naInit_std(_context);
448     naSave(_context, _globals);
449     hashset(_globals, "globals", _globals);
450
451     hashset(_globals, "math", naInit_math(_context));
452     hashset(_globals, "bits", naInit_bits(_context));
453     hashset(_globals, "io", naInit_io(_context));
454     hashset(_globals, "thread", naInit_thread(_context));
455     hashset(_globals, "utf8", naInit_utf8(_context));
456
457     // Add our custom extension functions:
458     for(i=0; funcs[i].name; i++)
459         hashset(_globals, funcs[i].name,
460                 naNewFunc(_context, naNewCCode(_context, funcs[i].func)));
461
462     // And our SGPropertyNode wrapper
463     hashset(_globals, "props", genPropsModule());
464
465     // Make a "__gcsave" hash to hold the naRef objects which get
466     // passed to handles outside the interpreter (to protect them from
467     // begin garbage-collected).
468     _gcHash = naNewHash(_context);
469     hashset(_globals, "__gcsave", _gcHash);
470
471     // Now load the various source files in the Nasal directory
472     SGPath p(globals->get_fg_root());
473     p.append("Nasal");
474     ulDirEnt* dent;
475     ulDir* dir = ulOpenDir(p.c_str());
476     while(dir && (dent = ulReadDir(dir)) != 0) {
477         SGPath fullpath(p);
478         fullpath.append(dent->d_name);
479         SGPath file(dent->d_name);
480         if(file.extension() != "nas") continue;
481         loadModule(fullpath, file.base().c_str());
482     }
483     ulCloseDir(dir);
484
485     // set signal and remove node to avoid restoring at reinit
486     const char *s = "nasal-dir-initialized";
487     SGPropertyNode *signal = fgGetNode("/sim/signals", true);
488     signal->setBoolValue(s, true);
489     signal->removeChildren(s);
490
491     // Pull scripts out of the property tree, too
492     loadPropertyScripts();
493 }
494
495 void FGNasalSys::update(double)
496 {
497     if(_purgeListeners) {
498         _purgeListeners = false;
499         map<int, FGNasalListener *>::iterator it;
500         for(it = _listener.begin(); it != _listener.end();) {
501             FGNasalListener *nl = it->second;
502             if(nl->_dead) {
503                 _listener.erase(it++);
504                 delete nl;
505             } else {
506                 ++it;
507             }
508         }
509     }
510 }
511
512 // Loads the scripts found under /nasal in the global tree
513 void FGNasalSys::loadPropertyScripts()
514 {
515     SGPropertyNode* nasal = globals->get_props()->getNode("nasal");
516     if(!nasal) return;
517
518     for(int i=0; i<nasal->nChildren(); i++) {
519         SGPropertyNode* n = nasal->getChild(i);
520
521         const char* module = n->getName();
522         if(n->hasChild("module"))
523             module = n->getStringValue("module");
524
525         // allow multiple files to be specified within in a single
526         // Nasal module tag
527         int j = 0;
528         SGPropertyNode *fn;
529         bool file_specified = false;
530         while ( (fn = n->getChild("file", j)) != NULL ) {
531             file_specified = true;
532             const char* file = fn->getStringValue();
533             SGPath p(globals->get_fg_root());
534             p.append(file);
535             loadModule(p, module);
536             j++;
537         }
538
539         // Old code which only allowed a single file to be specified per module
540         /*
541         const char* file = n->getStringValue("file");
542         if(!n->hasChild("file")) file = 0; // Hrm...
543         if(file) {
544             SGPath p(globals->get_fg_root());
545             p.append(file);
546             loadModule(p, module);
547         }
548         */
549         
550         const char* src = n->getStringValue("script");
551         if(!n->hasChild("script")) src = 0; // Hrm...
552         if(src)
553             createModule(module, n->getPath(), src, strlen(src));
554
555         if(!file_specified && !src)
556             SG_LOG(SG_NASAL, SG_ALERT, "Nasal error: " <<
557                    "no <file> or <script> defined in " <<
558                    "/nasal/" << module);
559     }
560 }
561
562 // Logs a runtime error, with stack trace, to the FlightGear log stream
563 void FGNasalSys::logError(naContext context)
564 {
565     SG_LOG(SG_NASAL, SG_ALERT,
566            "Nasal runtime error: " << naGetError(context));
567     SG_LOG(SG_NASAL, SG_ALERT,
568            "  at " << naStr_data(naGetSourceFile(context, 0)) <<
569            ", line " << naGetLine(context, 0));
570     for(int i=1; i<naStackDepth(context); i++)
571         SG_LOG(SG_NASAL, SG_ALERT,
572                "  called from: " << naStr_data(naGetSourceFile(context, i)) <<
573                ", line " << naGetLine(context, i));
574 }
575
576 // Reads a script file, executes it, and places the resulting
577 // namespace into the global namespace under the specified module
578 // name.
579 void FGNasalSys::loadModule(SGPath file, const char* module)
580 {
581     int len = 0;
582     char* buf = readfile(file.c_str(), &len);
583     if(!buf) {
584         SG_LOG(SG_NASAL, SG_ALERT,
585                "Nasal error: could not read script file " << file.c_str()
586                << " into module " << module);
587         return;
588     }
589
590     createModule(module, file.c_str(), buf, len);
591     delete[] buf;
592 }
593
594 // Parse and run.  Save the local variables namespace, as it will
595 // become a sub-object of globals.  The optional "arg" argument can be
596 // used to pass an associated property node to the module, which can then
597 // be accessed via cmdarg().  (This is, for example, used by XML dialogs.)
598 void FGNasalSys::createModule(const char* moduleName, const char* fileName,
599                               const char* src, int len, const SGPropertyNode* arg)
600 {
601     naRef code = parse(fileName, src, len);
602     if(naIsNil(code))
603         return;
604
605     // See if we already have a module hash to use.  This allows the
606     // user to, for example, add functions to the built-in math
607     // module.  Make a new one if necessary.
608     naRef locals;
609     naRef modname = naNewString(_context);
610     naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
611     if(!naHash_get(_globals, modname, &locals))
612         locals = naNewHash(_context);
613
614     _cmdArg = (SGPropertyNode*)arg;
615
616     call(code, locals);
617     hashset(_globals, moduleName, locals);
618 }
619
620 void FGNasalSys::deleteModule(const char* moduleName)
621 {
622     naRef modname = naNewString(_context);
623     naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
624     naHash_delete(_globals, modname);
625 }
626
627 naRef FGNasalSys::parse(const char* filename, const char* buf, int len)
628 {
629     int errLine = -1;
630     naRef srcfile = naNewString(_context);
631     naStr_fromdata(srcfile, (char*)filename, strlen(filename));
632     naRef code = naParseCode(_context, srcfile, 1, (char*)buf, len, &errLine);
633     if(naIsNil(code)) {
634         SG_LOG(SG_NASAL, SG_ALERT,
635                "Nasal parse error: " << naGetError(_context) <<
636                " in "<< filename <<", line " << errLine);
637         return naNil();
638     }
639
640     // Bind to the global namespace before returning
641     return naBindFunction(_context, code, _globals);
642 }
643
644 bool FGNasalSys::handleCommand(const SGPropertyNode* arg)
645 {
646     const char* nasal = arg->getStringValue("script");
647     const char* moduleName = arg->getStringValue("module");
648     naRef code = parse(arg->getPath(true), nasal, strlen(nasal));
649     if(naIsNil(code)) return false;
650
651     // Commands can be run "in" a module.  Make sure that module
652     // exists, and set it up as the local variables hash for the
653     // command.
654     naRef locals = naNil();
655     if(moduleName[0]) {
656         naRef modname = naNewString(_context);
657         naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
658         if(!naHash_get(_globals, modname, &locals)) {
659             locals = naNewHash(_context);
660             naHash_set(_globals, modname, locals);
661         }
662     }
663
664     // Cache this command's argument for inspection via cmdarg().  For
665     // performance reasons, we won't bother with it if the invoked
666     // code doesn't need it.
667     _cmdArg = (SGPropertyNode*)arg;
668
669     call(code, locals);
670     return true;
671 }
672
673 // settimer(func, dt, simtime) extension function.  The first argument
674 // is a Nasal function to call, the second is a delta time (from now),
675 // in seconds.  The third, if present, is a boolean value indicating
676 // that "real world" time (rather than simulator time) is to be used.
677 //
678 // Implementation note: the FGTimer objects don't live inside the
679 // garbage collector, so the Nasal handler functions have to be
680 // "saved" somehow lest they be inadvertently cleaned.  In this case,
681 // they are inserted into a globals.__gcsave hash and removed on
682 // expiration.
683 void FGNasalSys::setTimer(naContext c, int argc, naRef* args)
684 {
685     // Extract the handler, delta, and simtime arguments:
686     naRef handler = argc > 0 ? args[0] : naNil();
687     if(!(naIsCode(handler) || naIsCCode(handler) || naIsFunc(handler))) {
688         naRuntimeError(c, "settimer() with invalid function argument");
689         return;
690     }
691
692     naRef delta = argc > 1 ? args[1] : naNil();
693     if(naIsNil(delta)) {
694         naRuntimeError(c, "settimer() with invalid time argument");
695         return;
696     }
697
698     bool simtime = (argc > 2 && naTrue(args[2])) ? false : true;
699
700     // Generate and register a C++ timer handler
701     NasalTimer* t = new NasalTimer;
702     t->handler = handler;
703     t->gcKey = gcSave(handler);
704     t->nasal = this;
705
706     globals->get_event_mgr()->addEvent("NasalTimer",
707                                        t, &NasalTimer::timerExpired,
708                                        delta.num, simtime);
709 }
710
711 void FGNasalSys::handleTimer(NasalTimer* t)
712 {
713     call(t->handler, naNil());
714     gcRelease(t->gcKey);
715 }
716
717 int FGNasalSys::gcSave(naRef r)
718 {
719     int key = _nextGCKey++;
720     naHash_set(_gcHash, naNum(key), r);
721     return key;
722 }
723
724 void FGNasalSys::gcRelease(int key)
725 {
726     naHash_delete(_gcHash, naNum(key));
727 }
728
729 void FGNasalSys::NasalTimer::timerExpired()
730 {
731     nasal->handleTimer(this);
732     delete this;
733 }
734
735 int FGNasalSys::_listenerId = 0;
736
737 // setlistener(property, func, bool) extension function.  The first argument
738 // is either a ghost (SGPropertyNode_ptr*) or a string (global property
739 // path), the second is a Nasal function, the optional third one a bool.
740 // If the bool is true, then the listener is executed initially. The
741 // setlistener() function returns a unique id number, that can be used
742 // as argument to the removelistener() function.
743 naRef FGNasalSys::setListener(naContext c, int argc, naRef* args)
744 {
745     SGPropertyNode_ptr node;
746     naRef prop = argc > 0 ? args[0] : naNil();
747     if(naIsString(prop)) node = fgGetNode(naStr_data(prop), true);
748     else if(naIsGhost(prop)) node = *(SGPropertyNode_ptr*)naGhost_ptr(prop);
749     else {
750         naRuntimeError(c, "setlistener() with invalid property argument");
751         return naNil();
752     }
753
754     if(node->isTied())
755         SG_LOG(SG_NASAL, SG_DEBUG, "Attaching listener to tied property " <<
756                 node->getPath());
757
758     naRef handler = argc > 1 ? args[1] : naNil();
759     if(!(naIsCode(handler) || naIsCCode(handler) || naIsFunc(handler))) {
760         naRuntimeError(c, "setlistener() with invalid function argument");
761         return naNil();
762     }
763
764     bool initial = argc > 2 && naTrue(args[2]);
765
766     FGNasalListener *nl = new FGNasalListener(node, handler, this,
767             gcSave(handler), _listenerId);
768     node->addChangeListener(nl, initial);
769
770     _listener[_listenerId] = nl;
771     return naNum(_listenerId++);
772 }
773
774 // removelistener(int) extension function. The argument is the id of
775 // a listener as returned by the setlistener() function.
776 naRef FGNasalSys::removeListener(naContext c, int argc, naRef* args)
777 {
778     naRef id = argc > 0 ? args[0] : naNil();
779     map<int, FGNasalListener *>::iterator it = _listener.find(int(id.num));
780
781     if(!naIsNum(id) || it == _listener.end() || it->second->_dead) {
782         naRuntimeError(c, "removelistener() with invalid listener id");
783         return naNil();
784     }
785
786     FGNasalListener *nl = it->second;
787     if(nl->_active) {
788         nl->_dead = true;
789         _purgeListeners = true;
790         return naNum(-1);
791     }
792
793     _listener.erase(it);
794     delete nl;
795     return naNum(_listener.size());
796 }
797
798
799
800 // FGNasalListener class.
801
802 FGNasalListener::FGNasalListener(SGPropertyNode_ptr node, naRef handler,
803                                  FGNasalSys* nasal, int key, int id) :
804     _node(node),
805     _handler(handler),
806     _gcKey(key),
807     _id(id),
808     _nas(nasal),
809     _active(0),
810     _dead(false)
811 {
812 }
813
814 FGNasalListener::~FGNasalListener()
815 {
816     _node->removeChangeListener(this);
817     _nas->gcRelease(_gcKey);
818 }
819
820 void FGNasalListener::valueChanged(SGPropertyNode* node)
821 {
822     // drop recursive listener calls
823     if(_active || _dead)
824         return;
825
826     SG_LOG(SG_NASAL, SG_DEBUG, "trigger listener #" << _id);
827     _active++;
828     _nas->_cmdArg = node;
829     _nas->call(_handler, naNil());
830     _active--;
831 }
832
833
834
835
836 // FGNasalModelData class.  If sgLoad3DModel() is called with a pointer to
837 // such a class, then it lets modelLoaded() run the <load> script, and the
838 // destructor the <unload> script. The latter happens when the model branch
839 // is removed from the scene graph.
840
841 void FGNasalModelData::modelLoaded(const string& path, SGPropertyNode *prop,
842                                    osg::Node *)
843 {
844     SGPropertyNode *n = prop->getNode("nasal"), *load;
845     if(!n)
846         return;
847
848     load = n->getNode("load");
849     _unload = n->getNode("unload");
850     if(!load && !_unload)
851         return;
852
853     _module = path;
854     const char *s = load ? load->getStringValue() : "";
855     nasalSys->createModule(_module.c_str(), _module.c_str(), s, strlen(s), _props);
856 }
857
858 FGNasalModelData::~FGNasalModelData()
859 {
860     if(_module.empty())
861         return;
862
863     if(!nasalSys) {
864         SG_LOG(SG_NASAL, SG_ALERT, "Trying to run an <unload> script "
865                 "without Nasal subsystem present.");
866         return;
867     }
868
869     if(_unload) {
870         const char *s = _unload->getStringValue();
871         nasalSys->createModule(_module.c_str(), _module.c_str(), s, strlen(s), _props);
872     }
873     nasalSys->deleteModule(_module.c_str());
874 }
875
876