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