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