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