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